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>/// <reference path="../typings/jasmine/jasmine.d.ts"/> //The above line was added for Visual Studio users. //Describe blocks can be nested. They describe blocks of code //and tell Jasmine/Mocha how to interact with your test suite describe('testObject', function () { //This variable is enclosed in the describe block and is relatively safe. //Note this variable is declared, but not initialized. That's VERY important //for good, clean-room style testing. var testObject; //BeforeEach will execute before each test. //Anything you want to execute each time should be wrapped in an anonymous function beforeEach(function () { //Always initialize your test variables inside a beforeEach block. //It's critical that these variables always start at the same baseline so //all tests behave predictably. testObject = { foo: 'bar', baz: 'quux' }; }); //AfterEach will run after each test. //The function names aren't very imaginative, but they are descriptive afterEach(function () { testObject = null; //Technically still an object. ; ) }); //it blocks are where you peform test operations. Each it block should //contain one test path and one expectation. Expectations can be equated //to assertions in jUnit. it('should be an object', function () { expect(typeof testObject).toBe('object'); //Hey! It passes. (Unless you changed the testObject) }); });
97ff57aa8841cc7f02f613849cbdd27e9a967b52
[ "JavaScript" ]
1
JavaScript
cmstead/jsTestDemo
417ff3183ae4aaa87fb8db3f5f7a72c9a8867cbb
a34d027bfa14978444ccb2acac479a18c725276f
refs/heads/master
<repo_name>belkinai/flatpickr-genitive<file_sep>/src/plugins/dayRangeSelect/dayRangeSelect.ts import { DayElement } from "../../types/instance"; import { Plugin } from "../../types/options"; export type PlusRange = { rangeStartDay: Date; rangeEndDay: Date; rangeStartDayFormatted: string; rangeEndDayFormatted: string; rangeCheckbox: HTMLInputElement; }; export interface Config { daysAround?: number; rangeCheckboxState?: boolean; } declare global { interface Window { dayRangeSelect: (config?: Config) => void; } } function dayRangeSelectPlugin(config: Config): Plugin<PlusRange> { return function(fp) { function onDayHover(event: MouseEvent) { if (config.daysAround === undefined) { config.daysAround = 2; } const day = event.target as DayElement; if ( !day.classList.contains("flatpickr-day") || day.classList.contains("flatpickr-disabled") || !fp.rangeCheckbox.checked ) return; const days = fp.days.childNodes; const dayIndex = day.$i; let startDayIndexAvailable = dayIndex; for (let i = 0; i < days.length; i++) { if (!(days[i] as DayElement).classList.contains("flatpickr-disabled")) { startDayIndexAvailable = (days[i] as DayElement).$i; break; } } let rangeStartDayIndex; if (dayIndex - config.daysAround < startDayIndexAvailable) { rangeStartDayIndex = startDayIndexAvailable; } else { rangeStartDayIndex = dayIndex - config.daysAround; } const rangeStartDay = (days[rangeStartDayIndex] as DayElement).dateObj; let rangeEndDayIndex; if (days.length - 1 < dayIndex + config.daysAround) { rangeEndDayIndex = days.length - 1; } else { rangeEndDayIndex = dayIndex + config.daysAround; } const rangeEndDay = (days[rangeEndDayIndex] as DayElement).dateObj; for (let i = days.length; i--; ) { const day = days[i] as DayElement; const date = day.dateObj; if (date > rangeEndDay || date < rangeStartDay) day.classList.remove("inRange"); else day.classList.add("inRange"); } } function highlightDayRange() { if (config.daysAround === undefined) { config.daysAround = 2; } const selDate = fp.latestSelectedDateObj; const day = fp.selectedDateElem; if ( selDate !== undefined && selDate.getMonth() === fp.currentMonth && selDate.getFullYear() === fp.currentYear && fp.rangeCheckbox.checked ) { const days = fp.days.childNodes; const dayIndex = (day as DayElement).$i; let startDayIndexAvailable = dayIndex; for (let i = 0; i < days.length; i++) { if ( !(days[i] as DayElement).classList.contains("flatpickr-disabled") ) { startDayIndexAvailable = (days[i] as DayElement).$i; break; } } let rangeStartDayIndex; if (dayIndex - config.daysAround < startDayIndexAvailable) { rangeStartDayIndex = startDayIndexAvailable; } else { rangeStartDayIndex = dayIndex - config.daysAround; } fp.rangeStartDay = (days[rangeStartDayIndex] as DayElement).dateObj; let rangeEndDayIndex; if (days.length - 1 < dayIndex + config.daysAround) { rangeEndDayIndex = days.length - 1; } else { rangeEndDayIndex = dayIndex + config.daysAround; } fp.rangeEndDay = (days[rangeEndDayIndex] as DayElement).dateObj; } else { fp.rangeStartDay = (day as DayElement).dateObj; fp.rangeEndDay = (day as DayElement).dateObj; } if (fp.rangeStartDay !== fp.rangeEndDay) { const days = fp.days.childNodes; for (let i = days.length; i--; ) { const date = (days[i] as DayElement).dateObj; if (date >= fp.rangeStartDay && date <= fp.rangeEndDay) (days[i] as DayElement).classList.add( "faltpickr-range-select", "selected" ); } } fp.rangeStartDayFormatted = fp.formatDate( fp.rangeStartDay, fp.config.dateFormat ); fp.rangeEndDayFormatted = fp.formatDate( fp.rangeEndDay, fp.config.dateFormat ); if ( fp.rangeStartDay !== undefined && fp.rangeEndDay !== undefined && fp.rangeCheckbox.checked ) { fp.input.value = fp.rangeStartDayFormatted + "-" + fp.rangeEndDayFormatted; } } function clearHover() { const days = fp.days.childNodes; for (let i = days.length; i--; ) (days[i] as Element).classList.remove("inRange"); } function clearRangeSelect() { const days = fp.days.childNodes; for (let i = days.length; i--; ) (days[i] as Element).classList.remove( "faltpickr-range-select", "selected" ); } function onReady() { if (fp.daysContainer !== undefined) fp.daysContainer.addEventListener("mouseover", onDayHover); let checkboxHtml = '<input class="flatpickr-dayRangeSelect-checkbox" type="checkbox">\n' + '<label for="flatpickr-dayRangeSelect-checkbox-label">+-' + config.daysAround + " дня</label>\n"; let checkboxNode = document.createElement("div"); checkboxNode.innerHTML = checkboxHtml; if (fp.calendarContainer !== undefined) { fp.rangeCheckbox = fp.calendarContainer.appendChild(checkboxNode) .firstChild as HTMLInputElement; if (config.rangeCheckboxState === true) { fp.rangeCheckbox.checked = true; } fp.rangeCheckbox.addEventListener("click", clearRangeSelect); fp.rangeCheckbox.addEventListener("click", clearHover); } } function onDestroy() { if (fp.daysContainer !== undefined) fp.daysContainer.removeEventListener("mouseover", onDayHover); } return { onValueUpdate: highlightDayRange, onMonthChange: highlightDayRange, onYearChange: highlightDayRange, onOpen: highlightDayRange, onClose: clearHover, onParseConfig: function() { fp.config.mode = "single"; fp.config.enableTime = false; fp.config.dateFormat = fp.config.dateFormat ? fp.config.dateFormat : "\\W\\e\\e\\k #W, Y"; fp.config.altFormat = fp.config.altFormat ? fp.config.altFormat : "\\W\\e\\e\\k #W, Y"; }, onReady: [ onReady, highlightDayRange, () => { fp.loadedPlugins.push("dayRangeSelect"); }, ], onDestroy, }; }; } export default dayRangeSelectPlugin;
6f24992efe2296875db382266d2236ee8cc52146
[ "TypeScript" ]
1
TypeScript
belkinai/flatpickr-genitive
15b970a11230cd589dfcd4af05fc89365622c8a6
c958dfce257ded0a5213800657f70217fbe8925d
refs/heads/main
<file_sep>package main import ( "mvcgolang/app/controller" "mvcgolang/app/middleware" "github.com/gin-contrib/cors" "github.com/gin-gonic/gin" ) func main() { router := gin.Default() router.Use(cors.Default()) router.POST("/api/v1/account/add", controller.CreateAccount) router.POST("/api/v1/login", controller.Login) router.GET("/api/v1/account", middleware.Auth, controller.GetAccount) router.POST("/api/v1/transfer", middleware.Auth, controller.Transfer) router.POST("/api/v1/withdraw", middleware.Auth, controller.Withdraw) router.POST("/api/v1/deposit", middleware.Auth, controller.Deposit) router.Run(":8090") } <file_sep>package model import ( "fmt" "gorm.io/driver/mysql" "gorm.io/gorm" ) var DB *gorm.DB func init() { var err error DB, err = gorm.Open(mysql.Open(fmt.Sprintf("root@/be02?charset=utf8&parseTime=True&loc=Local")), &gorm.Config{}) if err != nil { panic("failede to connect to database" + err.Error()) } DB.AutoMigrate(new(Account), new(Transaction)) } <file_sep>package constant const ( TRANSFER = 0 WITHDRAW = 1 DEPOSIT = 2 )
7b1a751a9e73eebd403686ca5f849226fe594a4f
[ "Go" ]
3
Go
aghiffari20/gorm-mysql
4a2265c94c24247336cdffc515b9f064681f8b9c
f10861ec3eaab5ee5a2d8af86f3a63693afa2c78
refs/heads/main
<file_sep>package test1; public class Solution { public static void main(String[] args) { if ( System . out . printf ( "Hello, World.\nHello, Java." ) != null ){ } } }<file_sep># ATM My first stupid program 大量的if else 使它看起来很蠢
1a5db6b468d189dd2017a9c9e826d58c39180423
[ "Markdown", "Java" ]
2
Java
xiaosuojin/ATM
e6486a97f45c41ef9fe055aa86f21fa5aa855b69
3c74b38675532e3c70e2bb3763d349efca0f0d12
refs/heads/master
<repo_name>anoopps/onelinetest<file_sep>/getquestion.php <?php require_once('db.php'); session_start(); $output = array(); $sql = "SELECT * FROM questions"; //$result = $connect->query($sql)? if ($result=mysqli_query($connect,$sql)) { $rowcount=mysqli_num_rows($result); $_SESSION['totalcount'] = $rowcount; } if (!isset($_SESSION['counter'])){ $_SESSION['counter'] = 0; }else{ $_SESSION['counter'] = $_SESSION['counter']+1; } $limit = $_SESSION['counter']; $sql = "SELECT id, question,answer,option1,opton2 FROM `questions` LIMIT $limit ,1"; $result = $connect->query($sql); if ($result->num_rows > 0) { while($outputquest = $result->fetch_assoc()) { $output['question'] = $outputquest['question']; $output['questionid'] = $outputquest['id']; $output['option1'] = $outputquest['option1']; $output['opton2'] = $outputquest['opton2']; } }else{ $output['score'] = $_SESSION['score']; if( $_SESSION['counter'] == $_SESSION['totalcount'] && $_SESSION['counter'] > 9 ){ // session_destroy(); } } echo json_encode($output); exit; ?><file_sep>/questions.sql -- phpMyAdmin SQL Dump -- version 4.7.4 -- https://www.phpmyadmin.net/ -- -- Host: 127.0.0.1 -- Generation Time: Dec 03, 2018 at 12:43 PM -- Server version: 10.1.28-MariaDB -- PHP Version: 7.1.11 SET SQL_MODE = "NO_AUTO_VALUE_ON_ZERO"; SET AUTOCOMMIT = 0; START TRANSACTION; SET time_zone = "+00:00"; /*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */; /*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */; /*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */; /*!40101 SET NAMES utf8mb4 */; -- -- Database: `questionary` -- -- -------------------------------------------------------- -- -- Table structure for table `questions` -- CREATE TABLE `questions` ( `id` int(11) NOT NULL, `question` text NOT NULL, `answer` varchar(150) NOT NULL, `option1` varchar(150) NOT NULL, `opton2` varchar(150) NOT NULL ) ENGINE=InnoDB DEFAULT CHARSET=latin1; -- -- Dumping data for table `questions` -- INSERT INTO `questions` (`id`, `question`, `answer`, `option1`, `opton2`) VALUES (3, 'Which is the tallest buiding in india', 'tajmahal', 'tajmahal', 'qutabminar'), (4, 'Which is the new airpot in kerala', 'kannur', 'kannur', 'cochin'), (5, 'Who won the 6 title in boxing', 'kim', 'kim', 'sathu'), (6, 'who is know as the brave heart of kerala', 'ayyankali', 'ayyankali', 'pinaryi'), (7, 'Who is the famous music director of india', 'arrahman', 'arrahman', 'vidyasagar'), (8, 'First turbain power generation india', 'trivandrum', 'trivandrum', 'cochin'), (9, 'Who is the father of nation', '<NAME>', 'ma<NAME>', 'patel'), (10, 'Who is the iron man of india', 's<NAME>ai patel', 'sardar valabai patel', 'sarbai'), (11, 'who is know as the missile man of india', 'apj abdhulkalam', 'apj abdhulkalam', 'sarabi'), (12, 'who directed the movie baahubali', 'ss rajamouli', 'ss rajamouli', 'shankar'); -- -- Indexes for dumped tables -- -- -- Indexes for table `questions` -- ALTER TABLE `questions` ADD PRIMARY KEY (`id`); -- -- AUTO_INCREMENT for dumped tables -- -- -- AUTO_INCREMENT for table `questions` -- ALTER TABLE `questions` MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=14; COMMIT; /*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */; /*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */; /*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */; <file_sep>/db.php <?php $user = "root"; $host ="localhost"; $pass = ""; $connect = mysqli_connect($host,$user,$pass,'<PASSWORD>'); if($connect->connect_error){ die("Connection error!"); } ?><file_sep>/review.php <?php require_once('db.php'); session_start(); $questionid = filter($_REQUEST['questionid']); $answer = filter($_REQUEST['option']); if($questionid && $answer){ $query = "SELECT answer FROM `questions` WHERE id='".$questionid."'"; $result = $connect->query($query); if( $result->fetch_object()->answer == $answer){ answerCounter(); } } function answerCounter(){ if( empty($_SESSION['score'] )){ $_SESSION['score'] = 1; }else{ $_SESSION['score'] = $_SESSION['score']+1; } } function filter($data){ if($data){ return strip_tags(trim($data)); } } ?><file_sep>/README.md # onelinetest Online test created using php, mysql, jQuery, ajax, html, css Link :https://anoopps.github.io/onelinetest/ <file_sep>/question.php <?php require_once('db.php'); $question = filter($_REQUEST['question']); $option1 = filter($_REQUEST['option1']); $option2 = filter($_REQUEST['option2']); $answer = filter($_REQUEST['answer']); $output = array(); if($question && $answer && $option1 && $option2){ $query ="INSERT INTO `questions` (`question`, `answer`, `option1`, `opton2`) VALUES ('".$question."', '".$answer."', '".$option1."', '".$option2."');"; if($connect->query($query)==TRUE){ $output['status'] = 1; $output['message'] = "Question succesfully entered"; }else{ $output['status'] = 0; $output['message'] = "Error!"; } echo json_encode($output); exit; } function filter($data){ if($data){ return strip_tags(trim($data)); } } ?>
58b75ee46855f71e76b82d7358093cf14d6eeeb6
[ "Markdown", "SQL", "PHP" ]
6
PHP
anoopps/onelinetest
82c7624a806014955672542380bd2f437da3e979
f59a17da57235b32db14224c3d46d436dc17bf2a
refs/heads/master
<repo_name>DmitrijsR/HMS<file_sep>/HMS/Controllers/FiltersController.cs using System; using System.Collections.Generic; using System.Data.Entity.Core.Objects; using System.Linq; using System.Web; using System.Web.Mvc; using System.Web.Routing; using System.Web.Security; using HMS.Models; using System.Linq.Dynamic; namespace HMS.Controllers { [HMSAuthorize] public class FiltersController : Controller { public ActionResult Index() { ViewBag.HistoryTab = false; var model = new TaskFilters(); using (var DB = new DBDataContext()) { populateModel(model, DB); model.Tasks = DB.F_ViewTasks("En", null, null, null).ToList().Select(x => new TaskFilters.FilteredTaskItem { ID = x.ID, Title = x.Title, Patient_Name = x.Patient_Name, Patient_Surname = x.Patient_Surname, Patient_Department = x.Patient_Department, Priority = x.Priority, Instructions = x.Instructions, Status = x.Status, Creator_Name = x.Creator_Name, Creator_Surname = x.Creator_Surname, Creator_Department = x.Creator_Department, TimeCreated = x.TimeCreated, TimeUpdated = x.TimeUpdated, Responsible_Name = x.Responsible_Name, Responsible_Surname = x.Responsible_Surname, Responsible_Department = x.Responsible_Department, Deletable = x.Deletable }); model.HistoryTasks = DB.F_HistoryTasks("En").ToList().Select(x => new TaskFilters.FilteredTaskItem { ID = x.ID, Title = x.Title, Patient_Name = x.Patient_Name, Patient_Surname = x.Patient_Surname, Patient_Department = x.Patient_Department, Priority = x.Priority, Instructions = x.Instructions, Status = x.Status, Creator_Name = x.Creator_Name, Creator_Surname = x.Creator_Surname, Creator_Department = x.Creator_Department, TimeCreated = x.TimeCreated, TimeUpdated = x.TimeUpdated, Responsible_Name = x.Responsible_Name, Responsible_Surname = x.Responsible_Surname, Responsible_Department = x.Responsible_Department }); } return View("Index", model); } public ActionResult ActiveSortFilter(int? Importance, int? Status, int? TaskType, int? Patient, int? Responsible, string From, string Till, string sortBy = "Priority", bool ascending = true, int page = 1, int pageSize = 10) { var model = new TaskFilters(); ViewBag.HistoryTab = false; populateModel(model, new DBDataContext()); try { model.SortBy = sortBy; model.SortAscending = ascending; model.CurrentPageIndex = page; model.PageSize = pageSize; ViewBag.Importance = Importance.ToString(); ViewBag.Status = Status.ToString(); ViewBag.TaskType = TaskType; ViewBag.Patient = Patient.ToString(); ViewBag.Responsible = Responsible.ToString(); ViewBag.From = From; ViewBag.Till = Till; using (var DB = new DBDataContext()) { var tempmodel = new TaskFilters(); tempmodel.Tasks = DB.F_ViewTasks("En", null, null, null).OrderBy(model.SortExpression).ToList().Select(x => new TaskFilters.FilteredTaskItem { ID = x.ID, Title = x.Title, Patient_Name = x.Patient_Name, Patient_Surname = x.Patient_Surname, Patient_Department = x.Patient_Department, Priority = x.Priority, Instructions = x.Instructions, Status = x.Status, Creator_Name = x.Creator_Name, Creator_Surname = x.Creator_Surname, Creator_Department = x.Creator_Department, TimeCreated = x.TimeCreated, TimeUpdated = x.TimeUpdated, Responsible_Name = x.Responsible_Name, Responsible_Surname = x.Responsible_Surname, Responsible_Department = x.Responsible_Department, Deletable = x.Deletable }).AsQueryable(); if (Importance != null) { string pri = model.PriorityTypes.Where(pr => pr.Value == Importance.Value.ToString()).SingleOrDefault().Text; tempmodel.Tasks = tempmodel.Tasks.Where(p => p.Priority == pri); } if (Status != null) { string stat = model.StatusTypes.Where(pr => pr.Value == Status.Value.ToString()).SingleOrDefault().Text; tempmodel.Tasks = tempmodel.Tasks.Where(p => p.Status == stat); } if (TaskType != null) { string typ = model.TaskTypes.Where(pr => pr.id == TaskType).SingleOrDefault().Text; tempmodel.Tasks = tempmodel.Tasks.Where(p => p.Title == typ); } if (Patient != null) { string Surname = model.Patients.Where(pr => pr.Value == Patient.Value.ToString()).SingleOrDefault().Text; string[] comb = Surname.Split(' '); // since Model.Patients stores Patient ID and combination of surname,name and department in one string tempmodel.Tasks = tempmodel.Tasks.Where(p => p.Patient_Surname == comb[0]); } if (Responsible != null) { string Surname = model.Responsibles.Where(pr => pr.Value == Responsible.Value.ToString()).SingleOrDefault().Text; string[] comb = Surname.Split(' '); // since Model.Patients stores Patient ID and combination of surname,name and department in one string tempmodel.Tasks = tempmodel.Tasks.Where(p => p.Responsible_Name == comb[0]); } if (!String.IsNullOrEmpty(From)) { DateTime parsedFrom; if (DateTime.TryParse(From, out parsedFrom)) tempmodel.Tasks = tempmodel.Tasks.Where(p => p.TimeCreated > parsedFrom); else { From = ""; throw new Exception("Date Parse Error"); } } if (!String.IsNullOrEmpty(Till)) { DateTime parsedTill; if (DateTime.TryParse(Till, out parsedTill)) tempmodel.Tasks = tempmodel.Tasks.Where(p => p.TimeCreated < parsedTill); else { Till = ""; throw new Exception("Date Parse Error"); } } model.HistoryTasks = DB.F_HistoryTasks("En").ToList().Select(x => new TaskFilters.FilteredTaskItem { ID = x.ID, Title = x.Title, Patient_Name = x.Patient_Name, Patient_Surname = x.Patient_Surname, Patient_Department = x.Patient_Department, Priority = x.Priority, Instructions = x.Instructions, Status = x.Status, Creator_Name = x.Creator_Name, Creator_Surname = x.Creator_Surname, Creator_Department = x.Creator_Department, TimeCreated = x.TimeCreated, TimeUpdated = x.TimeUpdated, Responsible_Name = x.Responsible_Name, Responsible_Surname = x.Responsible_Surname, Responsible_Department = x.Responsible_Department }); model.Tasks = tempmodel.Tasks; model.TotalRecordCount = DB.F_ViewTasks("En", null, null, null).ToList().Count; model.From = DateTime.Today.AddYears(-1); model.Till = DateTime.Now; } } catch (Exception ex) { ViewBag.Error = "Incorrect Filter Arguments"; } ViewBag.Importance = Importance.ToString(); ViewBag.Status = Status.ToString(); ViewBag.TaskType = TaskType; ViewBag.Patient = Patient.ToString(); ViewBag.Responsible = Responsible.ToString(); ViewBag.From = From; ViewBag.Till = Till; return View("Index", model); } [HMSAuthorize(Roles = "Doctor")] public ActionResult HistorySortFilter(int? HistoryPatient, string HistoryFrom, string HistoryTill, string sortBy = "Priority", bool ascending = true, int page = 1, int pageSize = 10) { ViewBag.HistoryTab = true; var model = new TaskFilters(); populateModel(model, new DBDataContext()); try { model.SortBy = sortBy; model.SortAscending = ascending; model.CurrentPageIndex = page; model.PageSize = pageSize; using (var DB = new DBDataContext()) { model.HistoryTasks = DB.F_HistoryTasks("En").OrderBy(model.SortExpression).ToList().Select(x => new TaskFilters.FilteredTaskItem { ID = x.ID, Title = x.Title, Patient_Name = x.Patient_Name, Patient_Surname = x.Patient_Surname, Patient_Department = x.Patient_Department, Priority = x.Priority, Instructions = x.Instructions, Status = x.Status, Creator_Name = x.Creator_Name, Creator_Surname = x.Creator_Surname, Creator_Department = x.Creator_Department, TimeCreated = x.TimeCreated, TimeUpdated = x.TimeUpdated, Responsible_Name = x.Responsible_Name, Responsible_Surname = x.Responsible_Surname, Responsible_Department = x.Responsible_Department }).AsQueryable(); if (HistoryPatient != null) { string Surname = model.Patients.Where(pr => pr.Value == HistoryPatient.Value.ToString()).SingleOrDefault().Text; string[] comb = Surname.Split(' '); // since Model.Patients stores Patient ID and combination of surname,name and department in one string model.HistoryTasks = model.HistoryTasks.Where(p => p.Patient_Surname == comb[0]); } if (!String.IsNullOrEmpty(HistoryFrom)) { DateTime parsedFrom; if (DateTime.TryParse(HistoryFrom, out parsedFrom)) model.HistoryTasks = model.HistoryTasks.Where(p => p.TimeCreated > parsedFrom); else { HistoryFrom = ""; throw new Exception("Date Parse Error"); } } if (!String.IsNullOrEmpty(HistoryTill)) { DateTime parsedTill; if (DateTime.TryParse(HistoryTill, out parsedTill)) model.HistoryTasks = model.HistoryTasks.Where(p => p.TimeCreated < parsedTill); else { HistoryTill = ""; throw new Exception("Date Parse Error"); } } model.TotalRecordCount = DB.F_ViewTasks("En", null, null, null).ToList().Count; } } catch (Exception ex) { ViewBag.Error = "Incorrect Filter Arguments"; } ViewBag.HistoryPatient = HistoryPatient.ToString(); ViewBag.From = HistoryFrom; ViewBag.Till = HistoryTill; return View("Index", model); } void populateModel(TaskFilters model, DBDataContext DB) { model.TaskTypes = DB.F_TaskTypes("En").ToList().Select(x => new TaskFilters.FilteredTaskType { id = x.ID, Text = x.Text, HasInstr = x.HasInstr }); // For Active Tasks model.PriorityTypes = DB.F_PriorityTypes("En").ToList().Select(x => new SelectListItem { Value = x.ID.ToString(), Text = x.Text }); // For Active Tasks model.StatusTypes = DB.F_StatusTypes("En").ToList().Select(x => new SelectListItem { Value = x.ID.ToString(), Text = x.Text }); model.StatusTypes = model.StatusTypes.Where(x => x.Value != "5"); // filter out Complete status // for Active Tasks model.Patients = DB.F_Patients().ToList().Select(x => new SelectListItem { Value = x.ID.ToString(), Text = x.Surname + " " + x.Name + " (" + x.Department + ")" }); // for Patients History model.AllPatients = DB.F_AllPatients(User.Identity.Name).ToList().Select(x => new SelectListItem { Value = x.ID.ToString(), Text = x.Surname + " " + x.Name + " (" + x.Department + ")" }); // For Active Tasks model.Responsibles = DB.F_Nurses(User.Identity.Name).ToList().Select(x => new SelectListItem { Value = x.ID.ToString(), Text = x.Nurse_Name + " " + x.Nurse_Surname + " (" + x.Department + ")" }); model.Dictionary = DB.F_Dictionary("En").ToDictionary(k => k.Tag, v => v.Text); } } }<file_sep>/HMS/Models/TaskDetails.cs using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; namespace HMS.Models { public class TaskDetails { public TaskDetailItem Details { get; set; } public Dictionary<string, string> Dictionary { get; set; } public IEnumerable<SelectListItem> StatusTypes { get; set; } public IEnumerable<SelectListItem> PriorityTypes { get; set; } public IEnumerable<ReportItem> CommentsNotifications { get; set; } public class TaskDetailItem { public int? ID { get; set; } public String Title { get; set; } public String Patient_Name { get; set; } public String Patient_Surname { get; set; } public String Patient_SocialNr { get; set; } public String Patient_Department { get; set; } public String Priority { get; set; } public String Instructions { get; set; } public int? Status_ID { get; set; } public String Status { get; set; } public int? Creator_ID { get; set; } public DateTime? TimeCreated { get; set; } public DateTime? TimeUpdated { get; set; } public String Responsible_Name { get; set; } public String Responsible_Surname { get; set; } public String Responsible_Department { get; set; } } public class ReportItem { public int? id { get; set; } public String Text { get; set; } } } }<file_sep>/HMS/Controllers/AccountController.cs using System; using System.Collections.Generic; using System.Data.Entity.Core.Objects; using System.Linq; using System.Web; using System.Web.Mvc; using System.Web.Routing; using System.Web.Security; using HMS.Models; namespace HMS.Controllers { public class AccountController : Controller { public HMSMempershipProvider MembershipService { get; set; } public HMSRoleProvider AuthorizationService { get; set; } protected override void Initialize(RequestContext requestContext) { if (MembershipService == null) MembershipService = new HMSMempershipProvider(); if (AuthorizationService == null) AuthorizationService = new HMSRoleProvider(); base.Initialize(requestContext); } [AllowAnonymous] public ActionResult Login() { //Check if authorization check has been called if (TempData["Auth_Error"] == null) { if (User.Identity.IsAuthenticated) return RedirectToAction("Index", "ViewTasks"); } else { ViewBag.Error = TempData["Auth_Error"]; } var model = new HMSUser(); using (var DB = new DBDataContext()) { model.Dictionary = DB.F_Dictionary("En").ToDictionary(k => k.Tag, v => v.Text); } return View(model); } [AllowAnonymous] [HttpPost] public ActionResult Login(HMSUser model, string ReturnUrl) { if (ModelState.IsValid) { if (MembershipService.ValidateUser(model.Username, model.Password)) { FormsAuthentication.SetAuthCookie(model.Username, false); return RedirectToLocal(ReturnUrl); } } using (var DB = new DBDataContext()) { model.Dictionary = DB.F_Dictionary("En").ToDictionary(k => k.Tag, v => v.Text); } ViewBag.Error = "The user name or password provided is incorrect."; // If we got this far, something failed, redisplay form //ModelState.AddModelError("login", "The user name or password provided is incorrect."); return View(model); } [HMSAuthorize] public ActionResult Logout() { FormsAuthentication.SignOut(); Session.Abandon(); // clear authentication cookie HttpCookie cookie1 = new HttpCookie(FormsAuthentication.FormsCookieName, ""); cookie1.Expires = DateTime.Now.AddYears(-1); Response.Cookies.Add(cookie1); // clear session cookie (not necessary for your current problem but i would recommend you do it anyway) HttpCookie cookie2 = new HttpCookie("ASP.NET_SessionId", ""); cookie2.Expires = DateTime.Now.AddYears(-1); Response.Cookies.Add(cookie2); FormsAuthentication.RedirectToLoginPage(); return RedirectToAction("Login", "Account"); } private ActionResult RedirectToLocal(string returnUrl) { if (Url.IsLocalUrl(returnUrl)) { return Redirect(returnUrl); } else { return RedirectToAction("Index", "ViewTasks"); } } } }<file_sep>/HMS/Controllers/TaskAssignmentController.cs using HMS.Models; using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; namespace HMS.Controllers { [HMSAuthorize(Roles = "Headnurse")] public class TaskAssignmentController : Controller { public ActionResult Index(Int32? Task_ID) { var model = new TaskAssignment(); using (var DB = new DBDataContext()) { if (Task_ID != null) { model.NurseList = DB.F_NurseWorkLoad(Task_ID).ToList().Select(x => new TaskAssignment.Nurse { ID = x.ID, Nurse_Name = x.Nurse_Name, Nurse_Surname = x.Nurse_Surname, Active_Tasks = x.Active_Tasks, All_Tasks = x.All_Tasks, IsResponsible = x.IsResponsible }); model.ResponsibleCurrent = model.ResponsiblePrev = model.NurseList.Where(u => u.IsResponsible == true).Select(u => u.ID).FirstOrDefault(); model.TaskID = Task_ID; } model.Dictionary = DB.F_Dictionary("En").ToDictionary(k => k.Tag, v => v.Text); } return View("Index", model); } [HttpPost] public ActionResult Assign(TaskAssignment AssignedNurse) { if (ModelState.IsValid) { using (var DB = new DBDataContext()) { // a control might be added, whether the correct headnurse is assigning int? result = DB.SP_Task_Assign(AssignedNurse.TaskID,AssignedNurse.ResponsibleCurrent,User.Identity.Name).First(); return RedirectToAction("Index", "ViewTasks"); } } //ItemID task = new ItemID(); //task.ID = (int)AssignedNurse.TaskID; return RedirectToAction("Index", "ViewTasks"); } } }<file_sep>/HMS/HMSRoleProvider.cs using System; using System.Collections.Generic; using System.Data.Entity.Core.Objects; using System.Linq; using System.Web; using System.Web.Security; using HMS.Models; namespace HMS { public class HMSRoleProvider: RoleProvider { public override void AddUsersToRoles(string[] usernames, string[] roleNames) { throw new NotImplementedException(); } public override string ApplicationName { get { throw new NotImplementedException(); } set { throw new NotImplementedException(); } } public override void CreateRole(string roleName) { throw new NotImplementedException(); } public override bool DeleteRole(string roleName, bool throwOnPopulatedRole) { throw new NotImplementedException(); } public override string[] FindUsersInRole(string roleName, string usernameToMatch) { throw new NotImplementedException(); } public override string[] GetAllRoles() { throw new NotImplementedException(); } public override string[] GetRolesForUser(string username) { List<string> roles; ObjectResult<string> roleList; using (var DB = new DBDataContext()) { roleList = DB.SP_GetRoles(username); roles = roleList.ToList(); } string[] roleArray = roles.Select(role => role.Trim()).ToArray(); return roleArray; } public override string[] GetUsersInRole(string roleName) { throw new NotImplementedException(); } public override bool IsUserInRole(string username, string roleName) { throw new NotImplementedException(); /* Personnel user = repository.GetUser(username); AUthTEstg.Models.Roles role = repository.GetRole(roleName); if (!repository.UserExists(user)) return false; if (!repository.RoleExists(role)) return false; return user.Roles.Contains(role); * */ } public override void RemoveUsersFromRoles(string[] usernames, string[] roleNames) { throw new NotImplementedException(); } public override bool RoleExists(string roleName) { throw new NotImplementedException(); } } }<file_sep>/HMS.Tests/Controllers/CreateToDoTests.cs using System; using Microsoft.VisualStudio.TestTools.UnitTesting; using System.Web.Mvc; using HMS.Models; namespace HMS.Tests.Controllers { [TestClass] public class CreateToDoTests { private CreateToDoController controller; [TestInitialize] public void Setup() { controller = new CreateToDoController(); } [TestCleanup] public void TestCleanUp() { controller.Dispose(); controller = null; } [TestMethod] public void CreateToDo_Index_is_not_Null() { var result = controller.Index(); Assert.IsNotNull(result); } [TestMethod] public void CreateToDo_Index_returns_ViewResult() { var result = controller.Index(); // Assert Assert.IsInstanceOfType(result, typeof(ViewResult)); } [TestMethod] public void CreateToDo_Index_returns_IndexView() { // Arrange const string expectedView = "Index"; // Act ViewResult result = controller.Index() as ViewResult; // Assert Assert.AreEqual(expectedView, result.ViewName); } [TestMethod] public void CreateToDo_Create_is_not_Null() { var result = controller.Create(new ToDoList()); Assert.IsNotNull(result); } [TestMethod] public void CreateToDo_Create_Redirects_To_ViewTasks_Index() { // Arrange // Act RedirectToRouteResult result = controller.Create(new ToDoList()) as RedirectToRouteResult; // Assert Assert.IsNotNull(result, "Not a redirect result"); Assert.IsFalse(result.Permanent); // Or IsTrue if you use RedirectToActionPermanent Assert.AreEqual("Index", result.RouteValues["Action"]); Assert.AreEqual("ViewTasks", result.RouteValues["Controller"]); } } public class CreateToDo_Index_Model_Tests { private CreateToDoController controller; [TestInitialize] public void Setup() { controller = new CreateToDoController(); } [TestCleanup] public void TestCleanUp() { controller.Dispose(); controller = null; } [TestMethod] public void CreateToDo_Patients_are_not_empty() { var result = controller.Index() as ViewResult; var toDoList = (ToDoList)result.ViewData.Model; Assert.IsNotNull(toDoList.Patients); } [TestMethod] public void CreateToDo_PriorityTypes_are_not_empty() { var result = controller.Index() as ViewResult; var toDoList = (ToDoList)result.ViewData.Model; Assert.IsNotNull(toDoList.PriorityTypes); } [TestMethod] public void CreateToDo_NotificationTypes_are_not_empty() { var result = controller.Index() as ViewResult; var toDoList = (ToDoList)result.ViewData.Model; Assert.IsNotNull(toDoList.NotificationTypes); } [TestMethod] public void CreateToDo_Dictionary_is_not_empty() { var result = controller.Index() as ViewResult; var toDoList = (ToDoList)result.ViewData.Model; Assert.IsNotNull(toDoList.Dictionary); } [TestMethod] public void CreateToDo_TaskTypes_are_not_empty() { var result = controller.Index() as ViewResult; var toDoList = (ToDoList)result.ViewData.Model; Assert.IsNotNull(toDoList.TaskTypes); } } [TestClass] public class TaskItem_Validity_Tests { private ToDoList.TaskItem NewItem; [TestInitialize] public void Setup() { NewItem = new ToDoList.TaskItem(); } [TestCleanup] public void TestCleanUp() { NewItem = null; } [TestMethod] public void New_TaskItem_Is_Not_Null() { Assert.IsNotNull(NewItem); } /************************************************** * TaskItem.TaskID Validity Tests * ***********************************************/ [TestMethod] public void TaskItem_TaskID_Accepts_Integers() { // Any value that exists in dbo.TaskTypes.ID NewItem.TaskID = 1; Assert.AreEqual(NewItem.TaskID, Convert.ToInt16(1)); } /************************************************** * TaskItem.Value Validity Tests * ***********************************************/ [TestMethod] public void TaskItem_Value_Accepts_Integers() { NewItem.Value = "tuberculosis 1cm3"; Assert.AreEqual(NewItem.Value, "tuberculosis 1cm3"); } /************************************************** * TaskItem.Importance Validity Tests * ***********************************************/ [TestMethod] public void TaskItem_Importance_Accepts_Integers() { NewItem.Importance = 1; Assert.AreEqual(NewItem.Importance, Convert.ToInt16(1)); } /************************************************** * TaskItem.NotificationType Validity Tests * ***********************************************/ [TestMethod] public void TaskItem_NotificationType_Accepts_Integers() { NewItem.NotificationType = 1; Assert.AreEqual(NewItem.NotificationType, Convert.ToInt16(1)); } } [TestClass] public class TaskItem_Boundary_Tests { private ToDoList.TaskItem NewItem; [TestInitialize] public void Setup() { NewItem = new ToDoList.TaskItem(); } [TestCleanup] public void TestCleanUp() { NewItem = null; } /************************************************** * TaskItem.TaskID Lower Boundary Tests * ***********************************************/ [TestMethod] [ExpectedException(typeof(ArgumentOutOfRangeException))] public void TaskItem_TaskID_Throws_ArgumentOutOfRangeException_If_Zero() { NewItem.TaskID = 0; //ID.Identity Field in SQl Server starts at 1 } [TestMethod] [ExpectedException(typeof(ArgumentOutOfRangeException))] public void TaskItem_TaskID_Throws_ArgumentOutOfRangeException_If_Negative() { NewItem.TaskID = -1; } /************************************************** * TaskItem.TaskID NotExistingValue Tests * ***********************************************/ [TestMethod] [ExpectedException(typeof(ArgumentOutOfRangeException))] public void TaskItem_TaskID_Throws_ArgumentOutOfRangeException_If_More_Than_Max_Nr_Of_Tasks() { // 100 does not(!) exists in dbo.TaskTypes.ID NewItem.TaskID = 100; } /************************************************** * TaskItem.Importance Lower Boundary Tests * ***********************************************/ [TestMethod] [ExpectedException(typeof(ArgumentOutOfRangeException))] public void TaskItem_Importance_Throws_ArgumentOutOfRangeException_If_Zero() { NewItem.Importance = 0; } [TestMethod] [ExpectedException(typeof(ArgumentOutOfRangeException))] public void TaskItem_Importance_Throws_ArgumentOutOfRangeException_If_Negative() { NewItem.Importance = -1; } /************************************************** * TaskItem.Importance NotExistingValue Tests * ***********************************************/ [TestMethod] [ExpectedException(typeof(ArgumentOutOfRangeException))] public void TaskItem_Importance_Throws_ArgumentOutOfRangeException_If_More_Than_Nr_Of_PriorityTypes() { NewItem.Importance = 100; } /************************************************** * TaskItem.NotificationType Lower Boundary Tests * ***********************************************/ [TestMethod] [ExpectedException(typeof(ArgumentOutOfRangeException))] public void TaskItem_NotificationType_Throws_ArgumentOutOfRangeException_If_Zero() { NewItem.NotificationType = 0; } [TestMethod] [ExpectedException(typeof(ArgumentOutOfRangeException))] public void TaskItem_NotificationType_Throws_ArgumentOutOfRangeException_If_Negative() { NewItem.NotificationType = -1; } /************************************************** * TaskItem.NotificationType NotExistingValue Tests * ***********************************************/ [TestMethod] [ExpectedException(typeof(ArgumentOutOfRangeException))] public void TaskItem_NotificationType_Throws_ArgumentOutOfRangeException_If_More_Than_Nr_Of_NotificationTypes() { NewItem.NotificationType = 100; } } }<file_sep>/HMS/Controllers/FollowPatientController.cs using System; using System.Collections.Generic; using System.Data.Entity.Core.Objects; using System.Linq; using System.Web; using System.Web.Mvc; using System.Web.Routing; using System.Web.Security; using HMS.Models; namespace HMS.Controllers { public class FollowPatientController: Controller { [HMSAuthorize(Roles = "Doctor, Headnurse")] public ActionResult Index() { FollowPatient model = new FollowPatient(); using (var DB = new DBDataContext()) { model.PrevFollowedPatients = DB.F_FollowedPatients(User.Identity.Name).ToList().Select(x => new FollowPatient.FPatient { ID = x.ID, Name = x.Surname + " " + x.Name + " (" + x.Department + ")" }); model.CurrFollowedPatients = DB.F_FollowedPatients(User.Identity.Name).ToList().Select(x => new FollowPatient.FPatient { ID = x.ID, Name = x.Surname + " " + x.Name + " (" + x.Department + ")" }); model.Patients = DB.F_Patients().ToList().Select(x => new SelectListItem { Value = x.ID.ToString(), Text = x.Surname + " " + x.Name + " (" + x.Department + ")" }); model.Dictionary = DB.F_Dictionary("En").ToDictionary(k => k.Tag, v => v.Text); } return View("Index",model); } public ActionResult Follow(FollowPatient model) { using (var DB = new DBDataContext()) { if (model.CurrFollowedPatients != null) { foreach (FollowPatient.FPatient curr in model.CurrFollowedPatients) { if (model.PrevFollowedPatients == null) DB.SP_Follow_Patient(User.Identity.Name, curr.ID); else if (!model.PrevFollowedPatients.Any(x=>x.ID == curr.ID)) // if Previously followed patients does not contain currently followed patient then add { DB.SP_Follow_Patient(User.Identity.Name, curr.ID); } } } if(model.PrevFollowedPatients != null) { foreach (FollowPatient.FPatient prev in model.PrevFollowedPatients) { if (model.CurrFollowedPatients == null) DB.SP_Unfollow_Patient(User.Identity.Name, prev.ID); else if (!model.CurrFollowedPatients.Any(x => x.ID == prev.ID)) // if Currently followed patients does not contain a previously followed patient then delete { DB.SP_Unfollow_Patient(User.Identity.Name, prev.ID); } } } model.PrevFollowedPatients = DB.F_FollowedPatients(User.Identity.Name).ToList().Select(x => new FollowPatient.FPatient { ID = x.ID, Name = x.Surname + " " + x.Name + " (" + x.Department + ")" }); model.CurrFollowedPatients = DB.F_FollowedPatients(User.Identity.Name).ToList().Select(x => new FollowPatient.FPatient { ID = x.ID, Name = x.Surname + " " + x.Name + " (" + x.Department + ")" }); model.Patients = DB.F_Patients().ToList().Select(x => new SelectListItem { Value = x.ID.ToString(), Text = x.Surname + " " + x.Name + " (" + x.Department + ")" }); model.Dictionary = DB.F_Dictionary("En").ToDictionary(k => k.Tag, v => v.Text); } return RedirectToAction("Index","ViewTasks"); } } }<file_sep>/HMS/Controllers/ViewTasksController.cs using HMS.Models; using System; using System.Collections.Generic; using System.Data.Entity.Core.Objects; using System.Linq; using System.Web; using System.Web.Mvc; namespace HMS.Controllers { [HMSAuthorize] public class ViewTasksController : Controller { // // GET: /ViewTasks/ public ActionResult Index() { var model = new ViewTasksList(); String Doctor_UID = null; String HNurse_UID = null; String Nurse_UID = null; using (var DB = new DBDataContext()) { if (User.IsInRole("Doctor")) Doctor_UID = User.Identity.Name; else if (User.IsInRole("Nurse")) Nurse_UID = User.Identity.Name; else if (User.IsInRole("Headnurse")) HNurse_UID = User.Identity.Name; model.Tasks = DB.F_ViewTasks("En", Doctor_UID, HNurse_UID, Nurse_UID).ToList().Select(x => new ViewTasksList.TaskItem { ID = x.ID, Title = x.Title, Patient_Name = x.Patient_Name, Patient_Surname = x.Patient_Surname, Patient_Department = x.Patient_Department, Priority = x.Priority, Instructions = x.Instructions, Status = x.Status, Creator_Name = x.Creator_Name, Creator_Surname = x.Creator_Surname, Creator_Department = x.Creator_Department, TimeCreated = x.TimeCreated, TimeUpdated = x.TimeUpdated, Responsible_Name = x.Responsible_Name, Responsible_Surname = x.Responsible_Surname, Responsible_Department = x.Responsible_Department, Deletable = x.Deletable }); model.Dictionary = DB.F_Dictionary("En").ToDictionary(k => k.Tag, v => v.Text); } return View("Index", model); } public ActionResult Delete(ItemID RecordID) { var json = new { deleted = false }; using (var DB = new DBDataContext()) { int? result = DB.SP_Tasks_Delete(RecordID.ID).First(); if (result == 0) json = new { deleted = true }; } return Json(json); } } }<file_sep>/HMS/Models/HMSUser.cs using System; using System.Collections.Generic; using System.Data.Entity.Core.Objects; using System.Linq; using System.Web; using System.Web.Security; namespace HMS.Models { public class HMSUser { public Int32? ID { get; set; } public string Username{ get; set; } public string Password { get; set; } public Dictionary<string, string> Dictionary { get; set; } //retrieve userID based on username public static Int32? GetUserID(string username) { using (var DB = new DBDataContext()) { int?[] ids; ObjectResult<int?> UserId; UserId = DB.SP_GetUserID(username); ids = UserId.ToArray(); return ids[0]; } } } }<file_sep>/HMS/Controllers/NotificationsController.cs using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; using HMS.Models; namespace HMS.Controllers { public class NotificationsController : Controller { // // GET: /Notifications/ public ActionResult Index() { var model = new Notifications(); using (var DB = new DBDataContext()) { model.Items = DB.F_ViewNotifications("En", User.Identity.Name).ToList().Select(x => new Notifications.NotifItem { id = x.ID, Notification = x.Notification }); model.Dictionary = DB.F_Dictionary("En").ToDictionary(k => k.Tag, v => v.Text); } return View("Index", model); } } }<file_sep>/HMS/Controllers/CreateToDoController.cs using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; using HMS.Models; using System.Data.Entity.Core.Objects; using System.Web.Security; namespace HMS { [HMSAuthorize(Roles = "Doctor")] public class CreateToDoController : Controller { // // GET: /CreateToDo/ public ActionResult Index() { var model = new ToDoList(); using (var DB = new DBDataContext()) { model.TaskTypes = DB.F_TaskTypes("En").ToList().Select(x => new ToDoList.TaskType { id = x.ID, Text = x.Text, HasInstr = x.HasInstr }); model.Patients = DB.F_Patients().ToList().Select(x => new SelectListItem { Value = x.ID.ToString(), Text = x.Surname + " " + x.Name + " (" + x.Department + ")" }); model.PriorityTypes = DB.F_PriorityTypes("En").ToList().Select(x => new SelectListItem { Value = x.ID.ToString(), Text = x.Text }); model.NotificationTypes = DB.F_NotificationTypes("En").ToList().Select(x => new SelectListItem { Value = x.ID.ToString(), Text = x.Text }); model.Dictionary = DB.F_Dictionary("En").ToDictionary(k => k.Tag, v => v.Text); } return View("Index", model); } public ActionResult Create(ToDoList model) { if (ModelState.IsValid) { //The model is OK. We can do whatever we want to do with the model using (var DB = new DBDataContext()) { if (model.Tasks != null) { foreach (ToDoList.TaskItem ti in model.Tasks) { var output = new ObjectParameter("NewTaskID", typeof(int)); //change 1 to insert current user id int? result = DB.SP_Tasks_Add(ti.TaskID, model.PatientID, ti.Importance, ti.Value, User.Identity.Name, ti.NotificationType, output).First(); if (result.HasValue && result == 0) { // Insert successful } } } } return RedirectToAction("Index", "ViewTasks"); } var Error_model = new DictionaryModel(); using (var DB = new DBDataContext()) { Error_model.Dictionary = DB.F_Dictionary("En").ToDictionary(k => k.Tag, v => v.Text); } return View("Create", Error_model); } } }<file_sep>/HMS/Models/TaskFilters.cs using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.Linq; using System.Web; using System.Web.Mvc; namespace HMS.Models { public class TaskFilters { public IEnumerable<FilteredTaskItem> Tasks { get; set; } public IEnumerable<FilteredTaskItem> HistoryTasks { get; set; } public IEnumerable<FilteredTaskType> TaskTypes { get; set; } public IEnumerable<SelectListItem> StatusTypes { get; set; } public IEnumerable<SelectListItem> Patients { get; set; } public IEnumerable<SelectListItem> AllPatients { get; set; } public IEnumerable<SelectListItem> PriorityTypes { get; set; } public IEnumerable<SelectListItem> Responsibles { get; set; } public DateTime From { get; set; } public DateTime Till { get; set; } public DateTime HistoryFrom { get; set; } public DateTime HistoryTill { get; set; } public Dictionary<string, string> Dictionary { get; set; } public TaskFilters() { this.PageSize = 10; this.NumericPageCount = 10; } // Paging-related properties public int CurrentPageIndex { get; set; } public int PageSize { get; set; } public int TotalRecordCount { get; set; } public int PageCount { get { return this.TotalRecordCount / this.PageSize; } } public int NumericPageCount; // Sorting-related properties public string SortBy { get; set; } public bool SortAscending { get; set; } public string SortExpression { get { return this.SortAscending ? this.SortBy + " asc" : this.SortBy + " desc"; } } public class FilteredTaskType { public int? id { get; set; } public String Text { get; set; } private Boolean hasInstr; public object HasInstr { get { return this.hasInstr; } set { if (value.GetType() == typeof(string) && value.Equals("1")) this.hasInstr = true; else this.hasInstr = false; } } } public class FilteredTaskItem { public int? ID { get; set; } public String Title { get; set; } public String Patient_Name { get; set; } public String Patient_Surname { get; set; } public String Patient_Department { get; set; } public String Priority { get; set; } public String Instructions { get; set; } public String Status { get; set; } public String Creator_Name { get; set; } public String Creator_Surname { get; set; } public String Creator_Department { get; set; } public DateTime? TimeCreated { get; set; } public DateTime? TimeUpdated { get; set; } public String Responsible_Name { get; set; } public String Responsible_Surname { get; set; } public String Responsible_Department { get; set; } public bool? Deletable { get; set; } } public class Nurse { public int? ID { get; set; } public String Name { get; set; } public String Surname { get; set; } public String Department { get; set; } } } }<file_sep>/HMS/Models/TaskAssignment.cs using System; using System.Collections.Generic; using System.Linq; using System.Web; namespace HMS.Models { public class TaskAssignment { public IEnumerable<Nurse> NurseList { get; set; } public Int32? ResponsiblePrev { get; set; } public Int32? ResponsibleCurrent { get; set; } public Int32? TaskID { get; set; } public Dictionary<string, string> Dictionary { get; set; } public class Nurse { public int? ID { get; set; } public String Nurse_Name { get; set; } public String Nurse_Surname { get; set; } public Int32? All_Tasks { get; set; } public Int32? Active_Tasks { get; set; } public bool? IsResponsible { get; set; } } } }<file_sep>/HMS/HMSAuthorizeAttribute.cs using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; namespace HMS { public class HMSAuthorize : AuthorizeAttribute { protected override void HandleUnauthorizedRequest(System.Web.Mvc.AuthorizationContext filterContext) { //filterContext.ActionDescriptor.ActionName filterContext.Controller.TempData["Auth_Error"] = "You are not authorized for this action."; base.HandleUnauthorizedRequest(filterContext); } } }<file_sep>/HMS/Models/ItemID.cs using System; using System.Collections.Generic; using System.Linq; using System.Web; namespace HMS.Models { public class ItemID { public Int32 ID { get; set; } } }<file_sep>/HMS/Models/ToDoList.cs using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; namespace HMS.Models { public class ToDoList { public int PatientID { get; set; } public IEnumerable<TaskItem> Tasks { get; set; } public IEnumerable<TaskType> TaskTypes { get; set; } public IEnumerable<SelectListItem> Patients { get; set; } public IEnumerable<SelectListItem> PriorityTypes { get; set; } public IEnumerable<SelectListItem> NotificationTypes { get; set; } public Dictionary<string, string> Dictionary { get; set; } public class TaskType { public int? id { get; set; } public String Text { get; set; } private Boolean hasInstr; public object HasInstr { get { return this.hasInstr; } set { if (value.GetType() == typeof(string) && value.Equals("1")) this.hasInstr = true; else this.hasInstr = false; } } } public class TaskItem { public Int16 TaskID { get; set; } public String Value { get; set; } public Int16 Importance { get; set; } public Int16 NotificationType { get; set; } } } }<file_sep>/HMS/Controllers/TaskDetailsController.cs using HMS.Models; using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; namespace HMS.Controllers { [HMSAuthorize] public class TaskDetailsController : Controller { // // GET: /TaskDetails/ public ActionResult Index(ItemID RecordID) { if (ModelState.IsValid) { var model = new TaskDetails(); using (var DB = new DBDataContext()) { if (RecordID == null) { model.Details = null; } else { model.Details = DB.F_ViewTaskDetails(RecordID.ID, "En").ToList().Select(x => new TaskDetails.TaskDetailItem { ID = x.ID, Title = x.Title, Patient_Name = x.Patient_Name, Patient_Surname = x.Patient_Surname, Patient_SocialNr = x.Patient_SocialNr, Patient_Department = x.Patient_Department, Priority = x.Priority, Instructions = x.Instructions, Status_ID = x.Status_ID, Status = x.Status, Creator_ID = x.Creator_ID, TimeCreated = x.TimeCreated, TimeUpdated = x.TimeUpdated, Responsible_Name = x.Responsible_Name, Responsible_Surname = x.Responsible_Surname, Responsible_Department = x.Responsible_Department }).FirstOrDefault(); } if (model.Details != null) { model.StatusTypes = DB.F_StatusTypes("En").ToList().Select(x => new SelectListItem { Value = x.ID.ToString(), Text = x.Text }); model.PriorityTypes = DB.F_PriorityTypes("En").ToList().Select(x => new SelectListItem { Value = x.ID.ToString(), Text = x.Text }); model.Dictionary = DB.F_Dictionary("En").ToDictionary(k => k.Tag, v => v.Text); return View("Index", model); } } } var Error_model = new DictionaryModel(); using (var DB = new DBDataContext()) { Error_model.Dictionary = DB.F_Dictionary("En").ToDictionary(k => k.Tag, v => v.Text); } return View("Error", Error_model); } public ActionResult Edit(int Task_ID, string Instructions, int Priority, int Status) { if (ModelState.IsValid) { using (var DB = new DBDataContext()) { DB.SP_Tasks_Edit(Task_ID, Status, Priority, Instructions, User.Identity.Name); } } return RedirectToAction("Index", "ViewTasks"); } } }<file_sep>/HMS/Models/FollowPatient.cs using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; namespace HMS.Models { public class FollowPatient { public IEnumerable<SelectListItem> Patients { get; set; } public IEnumerable<FPatient> PrevFollowedPatients { get; set; } public IEnumerable<FPatient> CurrFollowedPatients { get; set; } public Dictionary<string, string> Dictionary { get; set; } public class FPatient { public int? ID { get; set; } public string Name { get; set; } } } }<file_sep>/HMS.Tests/Models/DBModelTests.cs using System; using Microsoft.VisualStudio.TestTools.UnitTesting; using HMS.Models; using System.Linq; namespace HMS.Tests.Models { [TestClass] public class DBModelTests { [TestMethod] public void DB_Model_is_not_Null() { var DB = new DBDataContext(); Assert.IsNotNull(DB); } [TestMethod] public void DB_Patients_is_not_Null() { var DB = new DBDataContext(); var patients = from p in DB.F_Patients() select p; Assert.IsNotNull(patients); } [TestMethod] public void DB_TaskTypes_is_not_Null() { var DB = new DBDataContext(); var tasktypes = from tt in DB.F_TaskTypes("En") select tt; Assert.IsNotNull(tasktypes); } [TestMethod] public void DB_PriorityTypes_is_not_Null() { var DB = new DBDataContext(); var prioritytypes = from pt in DB.F_PriorityTypes("En") select pt; Assert.IsNotNull(prioritytypes); } [TestMethod] public void DB_NotificationTypes_is_not_Null() { var DB = new DBDataContext(); var notificationtypes = from nt in DB.F_NotificationTypes("En") select nt; Assert.IsNotNull(notificationtypes); } [TestMethod] public void DB_Dictionary_is_not_Null() { var DB = new DBDataContext(); var dictionary = from d in DB.F_Dictionary("En") select d; Assert.IsNotNull(dictionary); } } } <file_sep>/HMS/Models/ReportReq.cs using System; using System.Collections.Generic; using System.Linq; using System.Web; namespace HMS.Models { public class ReportReq { public int Task_ID { get; set; } public Status Details { get; set; } public string comment { get; set; } public HttpPostedFileBase attachment { get; set; } public string IsEmergency { get; set; } public class Status { public int Status_ID { get; set; } } } }<file_sep>/HMS/Models/ViewTasksList.cs using System; using System.Collections.Generic; using System.Linq; using System.Web; namespace HMS.Models { public class ViewTasksList { public IEnumerable<TaskItem> Tasks { get; set; } public Dictionary<string, string> Dictionary { get; set; } public class TaskItem { public int? ID { get; set; } public String Title { get; set; } public String Patient_Name { get; set; } public String Patient_Surname { get; set; } public String Patient_Department { get; set; } public String Priority { get; set; } public String Instructions { get; set; } public String Status { get; set; } public String Creator_Name { get; set; } public String Creator_Surname { get; set; } public String Creator_Department { get; set; } public DateTime? TimeCreated { get; set; } public DateTime? TimeUpdated { get; set; } public String Responsible_Name { get; set; } public String Responsible_Surname { get; set; } public String Responsible_Department { get; set; } public bool? Deletable { get; set; } } } }
4cdbec56f8ffa735a6be6d69a918022fe4673297
[ "C#" ]
21
C#
DmitrijsR/HMS
6bb33e99eae157144a36f3620b4fbc2d1cd666ec
d2ac565de1a35ef742b9235f84b734b15b6e2796
refs/heads/master
<repo_name>DouglasAmorim/CII_Alura<file_sep>/Forca/forca.c #include <stdio.h> #include <string.h> void abertura() { printf("******************************\n"); printf("* Jogo da Forca *\n"); printf("******************************\n"); } void chuta(int* tentativas, char chutes[26]) { char chute; scanf(" %c", &chute); chutes[*tentativas] = chute; (*tentativas)++; } int jaChutou(char letra, char chutes[26], char tentativas) { int achou = 0; for(int j = 0; j < tentativas; j++) { if (chutes[j] == letra) { achou = 1; break; } } return achou; } void desenhaForca(char palavraSecreta[20], char chutes[20], int tentativas) { for (int i = 0; i < strlen(palavraSecreta); ++i) { int achou = jaChutou(palavraSecreta[i], chutes, tentativas); if (achou) { printf("%c ", palavraSecreta[i]); } else { printf("_ "); } } } void escolhaPalavra(char palavraSecreta[20]) { // ultimo caracter tem que ser \0 sprintf(palavraSecreta, "MELANCIA"); } int main() { char palavraSecreta[20]; char chutes[26]; int tentativas = 0; int acertou = 0; int enforcou = 0; escolhaPalavra(palavraSecreta); abertura(); do { desenhaForca(palavraSecreta, chutes, tentativas); chuta(&tentativas, chutes); } while(!acertou && !enforcou); } <file_sep>/Exercicios/array.c #include <stdio.h> int main() { int notas[5]; notas[0] = 1; notas[1] = 4; notas[2] = 7; notas[3] = 5; notas[4] = 10; for(int i = 0; i < 5; i ++) { printf("%d\n", notas[i]); } } <file_sep>/README.md # Curso C II Alura Estudos dos módulos introdutórios ao C do curso: "C II: Avançando na linguagem" da Alura. Link para as aulas: [Alura](https://cursos.alura.com.br/course/introducao-a-programacao-com-c-parte-2 "Cursos Alura") ## Assuntos revisados nesse curso: Assustos tratados nessa revisão: - Manipulação de Arrays ~~~C int notas[10]; ~~~ - sprintf ~~~C #include <stdio.h> char palavraSecreta[20]; sprintf(palavraSecreta, "MELANCIA"); ~~~ - strlen ~~~C for(int i = 0; i < strlen(palavraSecreta); i ++) { } ~~~ - Ler um char com Scanf Ao ler um char com o scanf lembrar de sempre usar espaço %c, para ignorar o enter ~~~C char chute scanf(" %c", &chute) ~~~ - Ponteiro. ~~~C void calcula(int* c) { (*c)++; printf("%d\n", *c); } [...] int c = 10; calcula(&c); [...] ~~~ ### Revisão da linguagem Markdown *Refazer o MD desse readme* Guia basico de uso de [MarkDown](https://docs.pipz.com/central-de-ajuda/learning-center/guia-basico-de-markdown#open "guia")<file_sep>/Forca/ponteiro.c #include <stdio.h> void calcula(int* c) { (*c)++; printf("%d\n", *c); } int main() { int c = 10; calcula(&c); }
e5d05c5af465a897526069a69f34063df39a19bc
[ "Markdown", "C" ]
4
C
DouglasAmorim/CII_Alura
1c7b4780f0f44c6f49686fe58c4cf369b07a77ed
96e66911d33d6232f89e18820e847147692bc8d4
refs/heads/master
<file_sep>import java.util.Random; public class RaceCarRunner { public static void main(String[] args) { int meters=0; Random rand = new Random(); /* Do the following things without changing the RaceCar class */ // 1. Create a RaceCar and place it in 5th position RaceCar car = new RaceCar("stuff",5); while(true) { System.out.println(meters); // 2. Print the RaceCar's position in the race System.out.println(car.getPositionInRace()); // 3. Crash the RaceCar car.crash(); meters+=10; // 4. If the car is damaged. Bring it in for a pit stop. if(car.isDamaged()) { car.pit(); meters+=5; } // 5. Help the car move into first place. for (int i = 0; i < 4; i++) { if(rand.nextInt(5)==0) { car.crash(); meters+=10; }else { car.overtake(); meters+=50; } meters+=100; if(car.getPositionInRace()==1) { System.out.println("You won!"); System.out.println("You traveled "+meters+" meters"); System.exit(0); } } } } } <file_sep> public class Platypus { private String name; Platypus(String n){ System.out.println("Hi!"); name=n; } void sayHi(){ System.out.println("The platypus " + name + " is smarter than your average platypus."); } } <file_sep> public class Pufferfish { boolean puffed; int size; Pufferfish(boolean puffed, int size){ this.puffed=puffed; this.size=size; } void puff() { System.out.println("puffing up"); } void shrink() { System.out.println("shrinking"); } void hungry() { System.out.println("i am hungry"); } } <file_sep> public class driver { static Platypus p = new Platypus("stuff"); public static void main(String[] args) { p.sayHi(); } } <file_sep>import javax.swing.JOptionPane; public class PopcornMaker { public static void main(String[] args) { Microwave m = new Microwave(); String flavor = JOptionPane.showInputDialog("What flavor do you want the popcorn to be?"); Popcorn p = new Popcorn(flavor); m.putInMicrowave(p); String time = JOptionPane.showInputDialog("How much time do you want to cook it?"); int timeInt = Integer.parseInt(time); m.setTime(timeInt); m.startMicrowave(); } }
a824e25215659f6e5154efd220cd4ac8885607b0
[ "Java" ]
5
Java
League-Level1-Student/level1-module1-npasetto
88d7b6683ce70fede16d6dc4115184f22cbad934
ee366558fb116dc79bf0ae9979416f673363a4d3
refs/heads/master
<file_sep>/** * Created by E560KCD on 2017/3/15. */ $(function () { //吸顶 // $(window).scroll(function(){//fixed出现 // if($(this).scrollTop()>($("header").outerHeight(true)+$("#top").outerHeight(true)+$("#search").outerHeight(true)+$("#nav").outerHeight(true))){ // $("#fixed").fadeIn();//渐显 // }else{ // $("#fixed").fadeOut(); // } // }); $(window).scroll(function(){//fixed出现 if($(this).scrollTop()>660){ $(".search-top").fadeIn();//渐显 }else{ $(".search-top").fadeOut(); } }); //导入头部文档html $(".top-header").load("public.html"); //导入导航栏文档HTML // $(".con").load("navpublic.html") //首页轮播图 $.post("../json/banner.json",function (data) { var _ban_big_li="";//承载轮播图大图的li var _ban_big_li1="";//承载轮播图大图的li集合 var _tab_big_li="";//承载轮播图下标的li var _tab_big_li1="";//承载轮播图下标的li集合 var _ban_small_li="";//承载轮播图小图的li var _ban_small_ul="";//承载轮播图小图集合的ul var _ban_small_uls="";//承载轮播图小图集合ul的集合 var _ban_small_ulss="";//承载轮播图小图集合ul集合的集合 //轮播图大图 for(var n in data["big"]){ _ban_big_li="<li><a href='javasnript:;'><img src='"+data["big"][n]+"'></a></li> "; _ban_big_li1+=_ban_big_li; } //轮播图大图下边的数标 for(var i in data["tab"]){ _tab_big_li="<li>"+data["tab"][i]+"</li> "; _tab_big_li1+=_tab_big_li; } //轮播图小图 for(var k in data["small"]){ for(var m in data["small"][k]){ _ban_small_li="<li><a href='javasnript:;'><img src='"+data["small"][k][m]+"'><span class='cover'></span></a></li> "; _ban_small_ul+=_ban_small_li; } _ban_small_uls+="<ul>"+_ban_small_ul+"</ul>"; _ban_small_ul=""; } _ban_small_ulss+=_ban_small_uls; $(".pic").append(_ban_big_li1); $(".tab").append(_tab_big_li1); $(".tab li:first-child").addClass("on") $(".ban-sm-box").append(_ban_small_uls); // banner轮播图动态 // 鼠标滑过两套箭头滑出 var _timer=0; var num=1; var _num=1; $(".banner-banner").mouseenter(function () { clearTimeout(_timer) }); $(".banner-banner").mouseleave(function () { setTimeout(main,200) }); //大轮播图的左右按钮滑过显示 $(".banner-big").mouseenter(function () { $(".banner-big .btn-l").stop().animate({ "left":"0px" },"linner"); $(".banner-big .btn-r").stop().animate({ "right":"0px" },"linner") }); $(".banner-big").mouseleave(function () { $(".banner-big .btn-l").stop().animate({ "left":"-46px" },"linner"); $(".banner-big .btn-r").stop().animate({ "right":"-46px" },"linner") }); //小轮播图的左右按钮滑过显示 $(".banner-small").mouseenter(function () { $(".banner-small .btn-l").stop().animate({ "left":"0px" },"linner"); $(".banner-small .btn-r").stop().animate({ "right":"0px" },"linner") }); $(".banner-small").mouseleave(function () { $(".banner-small .btn-l").stop().animate({ "left":"-46px" },"linner"); $(".banner-small .btn-r").stop().animate({ "right":"-46px" },"linner") }); //滑过左右箭头num-1 $(".banner-banner .btn").mouseenter(function (){ num--; _num--; }); //大轮播图按钮左右箭头点击事件 $(".banner-big .btn-l").click(function () { $(".pic li").css("opacity","0"); $(".ban-sm-box ul").css({"opacity":"0","z-index":"0"}); num--; _num--; if (num<0){ num=7; } $(".tab li").removeClass("on"); $(".tab li").eq(num).addClass("on"); $(".pic li").eq(num).fadeTo("600",1) if (_num<0){ _num=3; } $(".ban-sm-box ul").eq(_num).fadeTo("600",1).css("z-index","9"); }); $(".banner-big .btn-r").click(function () { $(".pic li").css("opacity","0"); $(".ban-sm-box ul").css({"opacity":"0","z-index":"0"}); num++; _num++; console.log(_num) if (num>7){ num=0; } $(".tab li").removeClass("on"); $(".tab li").eq(num).addClass("on"); $(".pic li").eq(num).fadeTo("600",1) if (_num>3){ _num=0; } $(".ban-sm-box ul").eq(_num).fadeTo("600",1).css("z-index","9"); }); //小轮播图的按钮的点击事件 $(".banner-small .btn-l").click(function () { $(".pic li").css("opacity","0"); $(".ban-sm-box ul").css({"opacity":"0","z-index":"0"}); num--; _num--; if (num<0){ num=7; } $(".tab li").removeClass("on"); $(".tab li").eq(num).addClass("on"); $(".pic li").eq(num).fadeTo("600",1) if (_num<0){ _num=3; } $(".ban-sm-box ul").eq(_num).fadeTo("600",1).css("z-index","9"); }); $(".banner-small .btn-r").click(function () { $(".pic li").css("opacity","0"); $(".ban-sm-box ul").css({"opacity":"0","z-index":"0"}); num++; _num++; if (num>7){ num=0; // $(".pic li:first-child").fadeTo("600",1) } $(".tab li").removeClass("on"); $(".tab li").eq(num).addClass("on"); $(".pic li").eq(num).fadeTo("600",1) if (_num>3){ _num=0; // $(".ban-sm-box ul:first-child").fadeTo("600",1).css("z-index","9") } $(".ban-sm-box ul").eq(_num).fadeTo("600",1).css("z-index","9"); }); // 鼠标滑过下边的小图标 $(".tab li").mouseenter(function () { clearTimeout(_timer) num=(this.innerHTML-1); if(num<4){ _num=num; }else if(num==4){ _num=0; }else if(num==5){ _num=1; }else if(num==6){ _num=2; }else if(num==7){ _num=3; } $(".pic li").css("opacity","0"); $(".ban-sm-box ul").css({"opacity":"0","z-index":"0"}); $(".pic li").eq(num).fadeTo("600",1); $(".ban-sm-box ul").eq(_num).fadeTo("600",1).css("z-index","9"); $(".tab li").removeClass("on"); $(this).addClass("on") }); // 自动轮播 function main() { _timer=setTimeout(function (){ clearTimeout(_timer); $(".pic li").css("opacity","0"); $(".ban-sm-box ul").css({"opacity":"0","z-index":"0"}); $(".pic li").eq(num).fadeTo("600",1) if (num<8){ num++; }else { num=1; $(".pic li:first-child").fadeTo("600",1) } //小图标跟着num变化 $(".tab li").removeClass("on"); $(".tab li").eq(num-1).addClass("on"); $(".ban-sm-box ul").eq(_num).fadeTo("600",1).css("z-index","9"); if (_num<4){ _num++; }else { _num=1; $(".ban-sm-box ul:first-child").fadeTo("600",1).css("z-index","9") } setTimeout(main,200) },2000); } main(); }); //首页轮播图右侧 $(".ban-r-z-ul>li:first-child").addClass("on"); $(".ban-r-z-ul>li:first-child>div").css("display","block"); $(".ban-r-z-ul>li").mouseenter(function () { $(".ban-r-z-ul>li").removeClass("on") $(this).addClass("on") $(".ban-r-z-ul li>div").css("display","none") $(this).children("div").css("display","block") }); $(".ban-r-xia-ul>li:first-child").addClass("on"); $(".ban-r-xia-ul>li:first-child>div").css("display","block"); $(".ban-r-xia-ul>li").mouseenter(function () { $(".ban-r-xia-ul>li").removeClass("on") $(this).addClass("on") $(".ban-r-xia-ul li>div").css("display","none") $(this).children("div").css("display","block") }); // 秒杀和厂商周 //倒计时抢购 time(); setInterval(time,1000); var t=0; function time(){ var oEndtime = new Date("2017/4/1 8:47:10");//结束时间 var oStarttime = new Date();//开始时间 var time = oEndtime.getTime()-oStarttime.getTime()+(3600*1000*2*t); if(time<1000){ t++; // return; } var hour = (Math.floor(time/1000/60/60)); var min = (Math.floor(time/1000/60%60)); var sec = (Math.floor(time/1000%60)); function twoTo( n ){ if( n<10 ){ n = "0"+ n ; } return n; } $(".h").html(twoTo(hour)); $(".m").html(twoTo(min)); $(".s").html(twoTo(sec)); } // 秒杀产品 $.post("../json/miaosha.json",function (data) { var m_info="";//承载产品的div var m_a_img="";//承载图片的a标签 var m_line="";//承载line的div var m_num="";//承载秒杀数字的div var m_name="";//承载name的div var m_price="";//承载价格的div var m_zong="";//承载所有标签的载体 var m_li="";//承载厂商周的li标签 var firm_box="";//承载li的集合 for(var i in data["miaosha"]){ m_a_img="<a href='javascript:;' class='a-img' title='"+data["miaosha"][i]["d-title"]+"'><img src='"+data["miaosha"][i]["d-img"]+"'></a>" m_line="<div class='m-line'><span class='shu'></span><span class='num-bg'></span></div>" m_num="<div class='num'>已秒杀24%</div>" m_name="<div class='name'><a href='javascript:;'>"+data["miaosha"][i]["d-name"]+"</a> </div>" m_price="<div class='price'>秒杀价:¥<span>69</span><span class='del'>109</span></div>" m_zong+="<div class='m-info'>"+m_a_img+m_line+m_num+m_name+m_price+"</div>" } m_info+=m_zong; $(".m-list").append(m_info); for(var n=0;n<data["firm-week"].length;n++){ m_li="<li><a href='javascript:;'><img src='"+data["firm-week"][n]+"'></a></li> " firm_box+=m_li } $(".firm-box").append(firm_box); //尾品汇 var w_left_a="";//承载img的a标签 var w_con_left="";//承载左侧的集合 var w_con_logo="";//承载logo的集合 var w_right_top="";//承载右侧上边的集合 var w_right_top_a="";//承载右侧上边的a标签集合 var w_right_foot_a="";//承载右侧下边的a标签集合 w_left_a="<a href='javascript:;'><img src='"+data["w-con-left"][0]+"'></a> "; for(var k=0;k<data["w-con-logo"].length;k++){ w_con_logo+="<a href='javascript:;'><img src='"+data["w-con-logo"][k]+"'></a> "; } w_con_left=w_left_a+"<div class='w-con-logo'>"+w_con_logo+"</div>"; $(".w-con-left").append(w_con_left); for(var m=0;m<data["w-con-r-top"].length;m++){ w_right_top_a+="<a href='javascript:;'><img src='"+data["w-con-r-top"][m]+"'></a> "; } $(".w-con-r-top").append(w_right_top_a); for(var h=0;h<data["w-con-r-foot"].length;h++){ w_right_foot_a+="<a href='javascript:;'><img src='"+data["w-con-r-foot"][h]+"'></a> "; } $(".w-con-r-foot").append(w_right_foot_a); // 当当优选 var d_title="";//承载小标题的a var d_list_a="";//承载内容的a标签 var d_list_ul="";//承载li的ul标签 var d_head=""; d_title="<a href='javascript:;' class='dd-brand-head-title'>"+data["dd-brand-head-title"][0]+"</a> "; for(var d=0;d<data["list-aa"].length;d++){ d_list_a+="<li><a href='javascript:;'>"+data["list-aa"][d]+"<span class='hot'>"+data["hot"][d]+"</span></a></li> "; } d_list_ul="<ul class='list-aa'>"+d_list_a+"</ul>"; d_head=d_title+d_list_ul; $(".dd-brand-head").append(d_head) var dd_left_a="";//承载左侧图片的a标签 var dd_right_a="";//承载右侧图片的a标签 var dd_zhong_a="";//承载中间图片的a标签 dd_zhong_a="<a href='javascript:;'><img src='"+data["dd-brand-con-z"][0]+"'></a> "; for(var s=0;s<data["dd-brand-con-l"].length;s++){ dd_left_a+="<a href='javascript:;'><img src='"+data["dd-brand-con-l"][s]+"'></a> "; } for(var t=0;t<data["dd-brand-con-r"].length;t++){ dd_right_a+="<a href='javascript:;'><img src='"+data["dd-brand-con-r"][t]+"'></a> "; } $(".dd-brand-con-l").append(dd_left_a); $(".dd-brand-con-z").append(dd_zhong_a); $(".dd-brand-con-r").append(dd_right_a); // 图书电子书 //分类 var book_con_aa=""; for(var r=0;r<data["book-con-ul"].length;r++){ book_con_aa+="<li><a href='javascript:;'>"+data["book-con-ul"][r]+"</a></li> "; } $(".book-con-ul").append(book_con_aa); var book_right=""; var book_right_1=""; var book_right_2=""; for(var o in data["book-right"]){ for(var q=0;q<data["book-right"]["d1"].length;q++){ book_right_1="<ul class='book-right-list'><li><a href='javascript:;' class='img'><img src='"+data["book-right"]["d1"][0]+"'></a><p class='book-name'><a href='javascript:;'>"+data["book-right"]["d1"][1]+"</a></p><p class='book-price'><span class='rob'>"+data["book-right"]["d1"][2]+"</span><span class='price-r'>"+data["book-right"]["d1"][3]+"</span></p></li></ul> "; } for(var p=0;p<data["book-right"]["d2"].length;p++){ book_right_2="<ul class='book-right-list'><li><a href='javascript:;' class='img'><img src='"+data["book-right"]["d2"][0]+"'></a><p class='book-name'><a href='javascript:;'>"+data["book-right"]["d2"][1]+"</a></p><p class='book-price'><span class='rob'>"+data["book-right"]["d1"][2]+"</span><span class='price-r'>"+data["book-right"]["d1"][3]+"</span></p></li></ul> "; } } book_right=book_right_1+book_right_2; $(".book-right").append(book_right); var book_con_foot=""; var book_foot_ul1=""; var book_foot_ul2=""; var book_foot_ul3=""; var book_foot_ul4=""; for(var a in data["book-con-foot"]){ for(var z=0;z<data["book-con-foot"]["d1"].length;z++){ book_foot_ul1="<ul class='book-foot-ul'><li><a href='javascript:;' class='img'><img src='"+data["book-con-foot"]["d1"][0]+"'></a><p class='book-name'><a href='javascript:;'>"+data["book-con-foot"]["d1"][1]+"</a></p><p class='book-price'><span class='rob'>"+data["book-con-foot"]["d1"][2]+"</span><span class='price-r'>"+data["book-con-foot"]["d1"][3]+"</span></p></li></ul> "; } for(var c=0;c<data["book-con-foot"]["d2"].length;c++){ book_foot_ul2="<ul class='book-foot-ul'><li><a href='javascript:;' class='img'><img src='"+data["book-con-foot"]["d2"][0]+"'></a><p class='book-name'><a href='javascript:;'>"+data["book-con-foot"]["d2"][1]+"</a></p><p class='book-price'><span class='rob'>"+data["book-con-foot"]["d2"][2]+"</span><span class='price-r'>"+data["book-con-foot"]["d2"][3]+"</span></p></li></ul> "; } for(var b=0;b<data["book-con-foot"]["d3"].length;b++){ book_foot_ul3="<ul class='book-foot-ul'><li><a href='javascript:;' class='img'><img src='"+data["book-con-foot"]["d3"][0]+"'></a><p class='book-name'><a href='javascript:;'>"+data["book-con-foot"]["d3"][1]+"</a></p><p class='book-price'><span class='rob'>"+data["book-con-foot"]["d3"][2]+"</span><span class='price-r'>"+data["book-con-foot"]["d3"][3]+"</span></p></li></ul> "; } for(var x=0;x<data["book-con-foot"]["d4"].length;x++){ book_foot_ul4="<ul class='book-foot-ul'><li><a href='javascript:;' class='img'><img src='"+data["book-con-foot"]["d4"][0]+"'></a><p class='book-name'><a href='javascript:;'>"+data["book-con-foot"]["d4"][1]+"</a></p><p class='book-price'><span class='rob'>"+data["book-con-foot"]["d4"][2]+"</span><span class='price-r'>"+data["book-con-foot"]["d4"][3]+"</span></p></li></ul> "; } } book_con_foot=book_foot_ul1+book_foot_ul2+book_foot_ul3+book_foot_ul4; $(".book-con-foot").append(book_con_foot); // 图书电子书轮播图 var over_li=""; var over_ul=""; for(var l=0;l<data["over"].length;l++){ over_li+="<li><img src='"+data["over"][l]+"'></li> "; } over_ul="<ul class='over-ul' id='over-ul'>"+over_li+"</ul>"; $("#over").append(over_ul); var over2_li=""; var over2_ul=""; for(var v=0;v<data["over2"].length;v++){ over2_li+="<li><img src='"+data["over2"][v]+"'></li> "; } over2_ul="<ul class='over-ul' id='over2-ul'>"+over2_li+"</ul>"; $("#over2").append(over2_ul); var over3_li=""; var over3_ul=""; for(var f=0;f<data["over3"].length;f++){ over3_li+="<li><img src='"+data["over3"][f]+"'></li> "; } over3_ul="<ul class='over-ul' id='over3-ul'>"+over3_li+"</ul>"; $("#over3").append(over3_ul); var over4_li=""; var over4_ul=""; for(var e=0;e<data["over4"].length;e++){ over4_li+="<li><img src='"+data["over4"][e]+"'></li> "; } over4_ul="<ul class='over-ul' id='over4-ul'>"+over4_li+"</ul>"; $("#over4").append(over4_ul); // $(".over ul li:nth-of-type(0)").addClass("li0"); // $(".over ul li:nth-of-type(1)").addClass("li1"); // $(".over ul li:nth-of-type(2)").addClass("li2"); // $(".over ul li:nth-of-type(3)").addClass("li3"); var _time=0; var _allow=0; var _all=0; var _num=0; var g=0; function main() { if(_allow==1 || _all==0) { var first = $('#over-ul li:first-child'); $("#over-ul").stop().animate({"left": "-335px"}, 600, function () { $("#over-ul").append(first); $("#over-ul").css("left", "0px"); _allow=0; if(g<3){ g++; }else { g=0; } $(".book-con-list li").removeClass("current"); $(".book-con-list li").eq(g).addClass("current"); }); } } $(".box-con-right").click(function () { if(_allow==0) { _allow=1; main(); } }); $(".box-con-left").stop().click(function () { // var last=$('.over-ul li:last-child'); $("#over-ul").css({"left":"-335px"}); $("#over-ul li:last-child").prependTo($("#over-ul")); $("#over-ul").animate({"left":"0px"},600); }); $(".book-con-list li:first-child").addClass("current") $(".book-con-list li").click(function () { $(".book-con-list li").removeClass("current"); $(this).addClass("current"); var i=$(this).index(); // var lil="li"+i+"" //bao liu // var aa = $(".lil"); // console.log(aa) $("#over-ul").stop().animate({"left": -i*335+"px"}, 600, function () { // $("#over-ul").append(aa); }); }); //自动轮播 _time=setInterval(main,3000); $(".book-con-zl1").mouseenter(function () { clearInterval(_time) }); $(".book-con-zl1").mouseleave(function () { setInterval(main,3000) }); var _time2=0; var _allow2=0; var _all2=0; function main2() { if(_allow2==1 || _all2==0) { var first = $('#over2-ul li:first-child'); $("#over2-ul").stop().animate({"left": "-335px"}, 600, function () { $("#over2-ul").append(first); $("#over2-ul").css("left", "0px"); _allow2=0; }); } } $(".box-con-right").click(function () { if(_allow2==0) { _allow2=1; main2(); } }); $(".box-con-left").stop().click(function () { // var last=$('.over-ul li:last-child'); $("#over2-ul").css({"left":"-335px"}); $("#over2-ul li:last-child").prependTo($("#over2-ul")); $("#over2-ul").animate({"left":"0px"},600); }); //自动轮播 _time2=setInterval(main2,2000); $(".book-con-zl2").mouseenter(function () { clearInterval(_time2) }); $(".book-con-zl2").mouseleave(function () { setInterval(main2,2000) }); var _time3=0; var _allow3=0; var _all3=0; function main3() { if(_allow3==1 || _all3==0) { var first = $('#over3-ul li:first-child'); $("#over3-ul").stop().animate({"left": "-335px"}, 600, function () { $("#over3-ul").append(first); $("#over3-ul").css("left", "0px"); _allow3=0; }); } } $(".box-con-right").click(function () { if(_allow3==0) { _allow3=1; main3(); } }); $(".box-con-left").stop().click(function () { // var last=$('.over-ul li:last-child'); $("#over3-ul").css({"left":"-335px"}); $("#over3-ul li:last-child").prependTo($("#over3-ul")); $("#over3-ul").animate({"left":"0px"},600); }); //自动轮播 _time3=setInterval(main3,2000); $(".book-con-zl3").mouseenter(function () { clearInterval(_time3) }); $(".book-con-zl3").mouseleave(function () { setInterval(main3,2000) }); var _time4=0; var _allow4=0; var _all4=0; function main4() { if(_allow4==1 || _all4==0) { var first = $('#over4-ul li:first-child'); $("#over4-ul").stop().animate({"left": "-335px"}, 600, function () { $("#over4-ul").append(first); $("#over4-ul").css("left", "0px"); _allow4=0; }); } } $(".box-con-right").click(function () { if(_allow4==0) { _allow4=1; main4(); } }); $(".box-con-left").stop().click(function () { $("#over4-ul").css({"left":"-335px"}); $("#over4-ul li:last-child").prependTo($("#over4-ul")); $("#over4-ul").animate({"left":"0px"},600); }); //自动轮播 _time4=setInterval(main4,2000); $(".book-con-zl4").mouseenter(function () { clearInterval(_time4) }); $(".book-con-zl4").mouseleave(function () { setInterval(main4,2000) }); var book_aa=""; for(var w=0;w<data["book-top"].length;w++){ book_aa+="<li><span>"+data["book-top"][w]+"</span></li> "; } $(".book-tab-aa").append(book_aa); $(".book-tab-aa li:first-child").addClass("on"); $(".book-tab>div").eq(0).css("display","block"); $(".book-tab-aa li").mouseenter(function () { $(".book-tab-aa li").removeClass("on"); $(".book-tab>div").css("display","none"); var i=$(this).index(); $(".book-tab>div").eq(i).css("display","block"); $(this).addClass("on") }) }); // 排行榜 $.post("../json/paihang.json",function (data) { var li=""; var ul=""; for (var i in data["chang"]){ li+="<li><div class='num-num'><span class='num'>"+data["chang"][i]["num"]+"</span><p class='name'><a>"+data["chang"][i]["name"]+"</a></p></div><div class='item'><span class='num'>"+data["chang"][i]["num1"]+"</span><a href='javascript:;' class='img'><img src='"+data["chang"][i]["img"]+"'></a><p class='name'><a href='javascript:;'>"+data["chang"][i]["p-name"]+"<span>"+data["chang"][i]["p-nei"]+"</span></a></div></li>"; } for (var n in data["xin"]){ ul+="<li><div class='num-num'><span class='num'>"+data["xin"][n]["num"]+"</span><p class='name'><a>"+data["xin"][n]["name"]+"</a></p></div><div class='item'><span class='num'>"+data["xin"][n]["num1"]+"</span><a href='javascript:;' class='img'><img src='"+data["xin"][n]["img"]+"'></a><p class='name'><a href='javascript:;'>"+data["xin"][n]["p-name"]+"<span>"+data["xin"][n]["p-nei"]+"</span></a></div></li>"; } $("#teb1").append(li) $("#teb2").append(ul) $(".teb-book1 li>div").eq(0).addClass("hidden"); $(".teb-book2 li>div").eq(0).addClass("hidden"); $(".teb-book1 .item").css("display","none"); $(".teb-book2 .item").css("display","none"); $(".teb-book1 .item").eq(0).css("display","list-item"); $(".teb-book2 .item").eq(0).css("display","list-item"); $(".teb-aa li:first-child").addClass("on"); $(".book-teb-top ul").addClass("hidde"); $(".book-teb-top ul:first-child").removeClass("hidde"); $(".teb-aa li").mouseenter(function () { $(".teb-aa li").removeClass("on"); $(this).addClass("on"); var i=$(this).index(); $(".book-teb-top ul").addClass("hidde"); $(".book-teb-top ul").eq(i).removeClass("hidde"); }); $(".teb-book1 li").mouseenter(function () { $(".teb-book1 .item").css("display","none"); $(".teb-book1 li>div").removeClass("hidden"); $(this).children(".num-num").addClass("hidden"); $(this).children(".item").css("display","list-item") }); $(".teb-book2 li").mouseenter(function () { $(".teb-book2 .item").css("display","none"); $(".teb-book2 li>div").removeClass("hidden"); $(this).children(".num-num").addClass("hidden"); $(this).children(".item").css("display","list-item") }); var fz_aa=""; for (var m=0;m<data["fz"].length;m++){ fz_aa+="<li><a href='javascript:;'>"+data["fz"][m]+"</a></li> " } $(".tall-cloth-left").append(fz_aa); // var _time5=0; // var _allow5=0; // var _all5=0; // function main5() { // if(_allow5==1 || _all5==0) { // var first = $('.tall-over1 ul li:first-child'); // $(".tall-over1 ul").stop().animate({"left": "-383px"}, 600, function () { // $(".tall-over1 ul").append(first); // $(".tall-over1 ul").css("left", "0px"); // _allow5=0; // }); // } // } // $(".tall-con-right").click(function () { // if(_allow5==0) { // _allow5=1; // main5(); // } // }); // $(".tall-con-left").stop().click(function () { // $(".tall-over1 ul").css({"left":"-383px"}); // $(".tall-over1 ul li:last-child").prependTo($(".tall-over1 ul")); // $(".tall-over1 ul").animate({"left":"0px"},600); // }); // // 自动轮播 // _time5=setInterval(main5,2000); // $(".tall-con1").mouseenter(function () { // clearInterval(_time5); // $(".tall-btn").css("display","block"); // }); // $(".tall-con1").mouseleave(function () { // setInterval(main5,2000) // $(".tall-btn").css("display","none"); // }); // var _time6=0; // var _allow6=0; // var _all6=0; // function main6() { // if(_allow6==1 || _all6==0) { // var first = $('.tall-over2 ul li:first-child'); // $(".tall-over2 ul").stop().animate({"left": "-383px"}, 600, function () { // $(".tall-over2 ul").append(first); // $(".tall-over2 ul").css("left", "0px"); // _allow6=0; // }); // } // } // $(".tall-con-right").click(function () { // if(_allow6==0) { // _allow6=1; // main6(); // } // }); // $(".tall-con-left").stop().click(function () { // // var last=$('.over-ul li:last-child'); // $(".tall-over2 ul").css({"left":"-383px"}); // $(".tall-over2 ul li:last-child").prependTo($(".tall-over2 ul")); // $(".tall-over2 ul").animate({"left":"0px"},600); // }); // // 自动轮播 // _time6=setInterval(main6,2000); // $(".tall-con").mouseenter(function () { // // clearInterval(_time6) // $(".tall-btn").css("display","block"); // }); // $(".tall-con").mouseleave(function () { // // setInterval(main6,2000) // $(".tall-btn").css("display","none"); // }); // // // // var _time7=0; // var _allow7=0; // var _all7=0; // function main7() { // if(_allow7==1 || _all7==0) { // var first = $('.tall-over3 ul li:first-child'); // $(".tall-over3 ul").stop().animate({"left": "-383px"}, 600, function () { // $(".tall-over3 ul").append(first); // $(".tall-over3 ul").css("left", "0px"); // _allow6=0; // }); // } // } // $(".tall-con-right").click(function () { // if(_allow7==0) { // _allow7=1; // main7(); // } // }); // $(".tall-con-left").stop().click(function () { // // var last=$('.over-ul li:last-child'); // $(".tall-over3 ul").css({"left":"-383px"}); // $(".tall-over3 ul li:last-child").prependTo($(".tall-over3 ul")); // $(".tall-over3 ul").animate({"left":"0px"},600); // }); // // 自动轮播 // _time7=setInterval(main7,2000); // $(".tall-con").mouseenter(function () { // // clearInterval(_time7) // $(".tall-btn").css("display","block"); // }); // $(".tall-con").mouseleave(function () { // // setInterval(main7,2000) // $(".tall-btn").css("display","none"); // }); // // // // var _time8=0; // var _allow8=0; // var _all8=0; // function main8() { // if(_allow8==1 || _all8==0) { // var first = $('.tall-over4 ul li:first-child'); // $(".tall-over4 ul").stop().animate({"left": "-383px"}, 600, function () { // $(".tall-over4 ul").append(first); // $(".tall-over4 ul").css("left", "0px"); // _allow6=0; // }); // } // } // $(".tall-con-right").click(function () { // if(_allow8==0) { // _allow8=1; // main8(); // } // }); // $(".tall-con-left").stop().click(function () { // // var last=$('.over-ul li:last-child'); // $(".tall-over4 ul").css({"left":"-383px"}); // $(".tall-over4 ul li:last-child").prependTo($(".tall-over4 ul")); // $(".tall-over4 ul").animate({"left":"0px"},600); // }); // // 自动轮播 // _time8=setInterval(main8,2000); // $(".tall-con").mouseenter(function () { // // clearInterval(_time8) // $(".tall-btn").css("display","block"); // }); // $(".tall-con").mouseleave(function () { // // setInterval(main8,2000) // $(".tall-btn").css("display","none"); // }); // // // var _time9=0; // var _allow9=0; // var _all9=0; // function main9() { // if(_allow9==1 || _all9==0) { // var first = $('.tall-over5 ul li:first-child'); // $(".tall-over5 ul").stop().animate({"left": "-383px"}, 600, function () { // $(".tall-over5 ul").append(first); // $(".tall-over5 ul").css("left", "0px"); // _allow9=0; // }); // } // } // $(".tall-con-right").click(function () { // if(_allow9==0) { // _allow9=1; // main9(); // } // }); // $(".tall-con-left").stop().click(function () { // // var last=$('.over-ul li:last-child'); // $(".tall-over5 ul").css({"left":"-383px"}); // $(".tall-over5 ul li:last-child").prependTo($(".tall-over5 ul")); // $(".tall-over5 ul").animate({"left":"0px"},600); // }); // // 自动轮播 // _time9=setInterval(main9,2000); // $(".tall-con").mouseenter(function () { // // clearInterval(_time9) // $(".tall-btn").css("display","block"); // }); // $(".tall-con").mouseleave(function () { // // setInterval(main9,2000) // $(".tall-btn").css("display","none"); // }); $(".tall-head ul li:first-child").addClass("on"); $(".tall-lunbo1>div").css("display","none"); $(".tall-lunbo1>div:first-child").css("display","block"); $(".tall-head ul li").mouseenter(function () { $(".tall-head ul li").removeClass("on"); $(this).addClass("on"); $(".tall-lunbo1>div").css("display","none"); var i=$(this).index(); $(".tall-lunbo1>div").eq(i).css("display","block"); }) //运动器械 $(".tall-head2 ul li:first-child").addClass("on"); $(".tall-lunbo2>div").css("display","none"); $(".tall-lunbo2>div:first-child").css("display","block"); $(".tall-head2 ul li").mouseenter(function () { $(".tall-head2 ul li").removeClass("on"); $(this).addClass("on"); $(".tall-lunbo2>div").css("display","none"); var i=$(this).index(); $(".tall-lunbo2>div").eq(i).css("display","block"); }); // 猜你喜欢 var x_img=""; var x_name=""; for(var k in data["cai"]){ x_img+="<li><a href='javascript:;' class='cai-img'><img src='"+data["cai"][k]["d-img"]+"'></a><p class='name'><a href='javascript:;'> "+data["cai"][k]["d-name"]+"</a></p><p class='price'>"+data["cai"][k]["d-price"]+"</p> </li>" } x_name="<ul>"+x_img+"</ul>" $(".cai-con").append(x_name); }) // 右侧广告 $(".sidebar-top a").mouseenter(function () { $(".sidebar-top a").children("span").removeClass("on") $(this).children("span").stop().addClass("on").animate({"left":"-79px"},300) }) $(".sidebar-top a").mouseleave(function () { $(".sidebar-top a").children("span").removeClass("on").css("left","0px") }) $(".back-top").mouseenter(function () { $(this).children("span").stop().addClass("on").animate({"left":"-79px"},300) }) $(".back-top").mouseleave(function () { $(".back-top").children("span").removeClass("on").css("left","0px") }) $(".back-top").click(function () { $("body,html").animate({scrollTop:0},300) }) //左侧电梯 $(".fix-screen-list li").mouseenter(function () { $(".fix-screen-list li").removeClass("on") $(".fix-box").addClass("on"); $(this).addClass("on") }) $(".fix-screen-list li").mouseleave(function () { $(".fix-screen-list li").removeClass("on") $(".fix-box").removeClass("on"); }) $(".fix-screen-list li").click(function(){ var ww = $(this).index(); var Top = $(".bd-body .lou").eq(ww).offset().top; $("body,html").animate({scrollTop:Top}); $(".fix-screen-list li").removeClass("current"); $(this).addClass("current"); }); $(window).scroll(function(){//fixed出现 if($(this).scrollTop()>($(".top-header").outerHeight(true)+$(".new-pro").outerHeight(true))&&$(this).scrollTop()<$(".bd-body").outerHeight(true)){ $(".fix-box").removeClass("broaden"); $(".fix-box").addClass("reduce");//渐显 }else{ $(".fix-box").removeClass("reduce"); $(".fix-box").addClass("broaden"); } if($(this).scrollTop()>$(".book--new").offset().top-450){ $(".bd-body .lou").each(function(){ var qq = $(this).index(); var _height = $(this).offset().top+ $(this).height()/2; var _top = $(window).scrollTop(); if(_height>_top){ $(".fix-screen-list li").removeClass("current"); $(".fix-screen-list li").eq(qq).addClass("current"); return false; } }) }else { $(".fix-screen-list li").removeClass("current"); } }); })<file_sep>/** * Created by E560KCD on 2017/3/30. */ $(function () { //top菜单 $.post("../json/address.json",null,function (data) { var _data=data; // console.log(_data); var _code=""; for(var i=0;i<_data["address"].length;i++){ _code+='<li><a href="javascript:;">'+_data["address"][i]+'</a> </li>'; } $("#top-left-address").html(_code); //换地址 $("#top-left-address a").click(function () { $("#address").html(this.innerHTML) $("#top-left-address").css("display","none"); $(this).css({ "background":"none", "border-color":"#f9f9f9" }) $(".address-one").css("background","url(\"../images/img.png\")no-repeat right -303px") }) }) //地址 $(".top-left").mouseenter(function () { $("#top-left-address").css("display","block"); $(this).css({ "background":"#fff", "border-color":"#e6e6e6" }) $(".address-one").css("background","url(\"../images/img.png\")no-repeat right -321px") }); $(".top-left").mouseleave(function () { $("#top-left-address").css("display","none"); $(this).css({ "background":"none", "border-color":"#f9f9f9" }) $(".address-one").css("background","url(\"../images/img.png\")no-repeat right -303px") }); //我的当当,企业采购,客户服务 $(".top-right-list-li").mouseenter(function () { $(".top-right-list").css("display","none"); $(this).children("div").css("display","block"); $(this).css({ "background":"#fff", "border-color":"#e6e6e6" }) $(".my-dd").css({"background":"url(\"../images/img.png\")no-repeat right -307px"}) $(this).children("a").css({ "background":"#fff url(\"../images/img.png\")no-repeat right -325px", "color":"#ff2832" }) }) $(".top-right-list-li").mouseleave(function () { $(".top-right-list").css("display","none"); $(this).css({ "background":"url(\"../images/img.png\") no-repeat left -285px", "border-color":"#f9f9f9" }) $(this).children("a").css({ "background":"url(\"../images/img.png\")no-repeat right -307px", "color":"#646464" }) }) //手机当当 $(".top-right-list-li-phone").mouseenter(function () { $(".top-right-list-phone").css("display","block"); $(".phone").css("background","url(\"../images/img.png\")no-repeat -51px -70px") $(this).css({ "border-color":"#e6e6e6", "background":"#fff" }) $(this).children("a").css({ "color":"#ff2832" }) }) $(".top-right-list-li-phone").mouseleave(function () { $(".top-right-list-phone").css("display","none"); $(".phone").css("background","url(\"../images/img.png\")no-repeat -40px -70px") $(this).css({ "border-color":"#f9f9f9", "background":"url(\"../images/img.png\") no-repeat left -285px" }) $(this).children("a").css({ "color":"#646464" }) }) function createitem() { var _cookie=document.cookie; var _uname=""; var _gdg=""; var _una=""; var ggg=""; if(_cookie.indexOf("name")>=0){ var bbb=_cookie.split(";")[1]; var ccc=bbb.split(","); ggg=ccc[1] } if(ccc[0].indexOf("name")>=0){ _una=ccc[0].split("=")[1]; } if(_cookie.indexOf("name")>=0){ var aaa=_cookie.split(";")[0]; var _arr=aaa.split(","); _gdg=_arr[1] } if(_arr[0].indexOf("name")>=0){ _uname=_arr[0].split("=")[1]; } $.post("../json/cart.json",null,function (data){ var pos="",posl="",txt="",txtl=""; for(var i in data[_uname]){ pos="<ul class='shangxin'><li class='shangxin1'><input type='checkbox' class='shangxuan1 shangxuan' /></li><li class='row_img'><a href='javascript:;'><img src='"+data[_uname]["img"]+"'></a> </li><li class='row_name'><div class='name'>"+data[_uname]["name"]+"</div></li><li class='row3 pric'><span>"+data[_uname]["price"]+"</span></li><li class='fn-count-tip row3 '><div class='div4'><span class='div5 fl'><button id='jian' class='jia'>-</button><input class='ipt4' id='ipt' type='text' value='"+_gdg+"' /><button id='jia' class='jia'>+</button></span></div></li><li class='row4'><span class='red'>0</span></li><li class='row5'><a href='javascript:;' class='shanchu'>删除</a> </li></ul>" } for(var q in data[_una]){ posl="<ul class='shangxin'><li class='shangxin1'><input type='checkbox' class='shangxuan1 shangxuan' /></li><li class='row_img'><a href='javascript:;'><img src='"+data[_una]["img"]+"'></a> </li><li class='row_name'><div class='name'>"+data[_una]["name"]+"</div></li><li class='row3 pric'><span>"+data[_una]["price"]+"</span></li><li class='fn-count-tip row3 '><div class='div4'><span class='div5 fl'><button id='jian1' class='jia'>-</button><input class='ipt4' id='ipt1' type='text' value='"+ggg+"' /><button id='jia1' class='jia'>+</button></span></div></li><li class='row4'><span class='red'>0</span></li><li class='row5'><a href='javascript:;' class='shanchu'>删除</a> </li></ul>" } txt=posl+pos $(".shang1").append(txt) jiajianyunsuan(); var _spans = document.getElementsByClassName("shanchu"); for(var t = 0; t < _spans.length; t++) { _spans[t].onclick = function() { console.log(1) if(window.confirm("是否删除?")) { // Cookie.deleteCookie(this.Name, "/"); // createitem(); $(this).parents(".shangxin").remove() } } } function jiajianyunsuan() { var oIpt = document.getElementById("ipt"); var oJia = document.getElementById("jia"); var oJian = document.getElementById("jian"); oJia.onclick = function() { if(oIpt.value >= 1 && oIpt.value < 20) { oIpt.value++; } else if(oIpt.value > 20) { oIpt.value = 20; } else if(oIpt.value < 1) { oIpt.value = 1; } }; oJian.onclick = function() { if(oIpt.value > 1 && oIpt.value < 20) { oIpt.value--; } else if(oIpt.value > 20) { oIpt.value = 20; } else if(oIpt.value < 1) { oIpt.value = 1; } } var oIpt1 = document.getElementById("ipt1"); var oJia1 = document.getElementById("jia1"); var oJian1 = document.getElementById("jian1"); oJia1.onclick = function() { if(oIpt1.value >= 1 && oIpt1.value < 20) { oIpt1.value++; } else if(oIpt1.value > 20) { oIpt1.value = 20; } else if(oIpt1.value < 1) { oIpt1.value = 1; } }; oJian1.onclick = function() { if(oIpt1.value > 1 && oIpt1.value < 20) { oIpt1.value--; } else if(oIpt1.value > 20) { oIpt1.value = 20; } else if(oIpt1.value < 1) { oIpt1.value = 1; } } } function eventHandle() { var _all = document.getElementById("all"); var _all1 = document.getElementById("all1"); var _boxes = document.getElementsByClassName("shangxuan"); _all.onclick = function() { for(var i = 0; i < _boxes.length; i++) { if(this.checked) { _boxes[i]["checked"] = true; _all1["checked"] = true; } else { _boxes[i]["checked"] = false; _all1["checked"] = false; } } } _all1.onclick = function() { for(var j = 0; j < _boxes.length; j++) { if(this.checked) { _boxes[j]["checked"] = true; _all["checked"] = true; } else { _boxes[j]["checked"] = false; _all["checked"] = false; } } }; var money=""; for(var n = 0; n < _boxes.length; n++) { _boxes[n].onclick = function() { if(this.checked) { var _flag = 0; for(var m = 0; m < _boxes.length; m++) { if(!_boxes[m].checked) { _flag = 1; } } if(_flag == 0) { _all.checked = true; _all1.checked = true; } } else { _all.checked = false; _all1.checked = false; } if(this["checked"]){ $(this).parent().siblings(".row4").children(".red").html((($(this).parent().siblings(".pric").children("span").text())*($(this).parent().siblings(".fn-count-tip").children(".div4").children(".div5").children(".ipt4").val()))) $(".jia").click(function () { $(this).parents(".fn-count-tip").siblings(".row4").children(".red").html((($(this).parents(".fn-count-tip").siblings(".pric").children("span").text())*($(this).siblings(".ipt4").val()))) }) }else { $(this).parent().siblings(".row4").children(".red").html("0") } money=Number($(".red").text()); console.log(money) money=""; // $(".zongjia").html() }; } } eventHandle() }) } createitem(); })<file_sep>/** * Created by E560KCD on 2017/3/19. */ $(function () { $.post("../json/nav.json",function (data) { var _code = "";//导航栏里面的span和a var _cod = "";//导航栏span标签 var _aa = "";//滑过显示的大详情表的上头一排a标签 var _top = "";//滑过显示的大详情表的上头要放进div标签 var _left_top = "";//承载内容的盒子 var _nav_pop = "";//承载盒子的框架 var zong = "";//导航栏li标签 var _left_box = "";//承载详情li标签的ul var _h4 = "";//承载小类目标题的标签 var _aa2 = "";//承载小类目右面的详细的分类的a标签 var _div2 = "";//承载小类目右面的详细的分类的div var _li = "";//承载小类目标题跟分类div的li var _li1 = "";//承载小类目标题跟分类div的li的集合 var _ul = "";//承载小类目标题跟分类div的li的ul var _div3 = "";//承载ul的li for (var i in data) { //左侧导航栏 for (var n in data[i]["dd-nav"]) { _code += "<a href='javascript:;'>" + data[i]["dd-nav"][n]["dd-name"] + "</a>"; _cod = "<span>" + _code + "</span>"; } for (var m in data[i]["dd-top"]) { _aa += "<a href='javascript:;'>" + data[i]["dd-top"][m]["dd-name"] + "</a>"; _top = "<div class='new-pop-guan'>" + _aa + "</div>"; } for (var k in data[i]["dd-left"]) { _h4 = "<h4><a href='javascript:;'>" + data[i]["dd-left"][k]["dd-name"] + "</a></h4>" for (var h in data[i]["dd-left"][k]["dd-right"]) { _aa2 += "<a href='javascript:;'>" + data[i]["dd-left"][k]["dd-right"][h]["dd-name"] + "</a>" _div2 = "<div>" + _aa2 + "</div>" _li = "<li>" + _h4 + _div2 + "</li>" } _aa2 = "" _li1 += _li } _ul = "<ul class='left'>" + _li1 + "</ul>" _left_top = "<div class='left-box'>" + _top + _ul + "</div>"; _nav_pop = "<div class='nav-pop'>" + _left_top + "</div>"; zong = "<li>" + _cod + _nav_pop + "</li>" $(".banner-nav").append(zong); _aa = ""; _top = ""; _code = ""; _cod = ""; _h4=""; _ul=""; _div2=""; _li=""; _aa2=""; _li1=""; } // for(var i=0;i<$(".banner-nav>li").length;i++){ // (function(i){ // $(".banner-nav>li").eq(i).css({ // "top":i*30+"px" // }) // })(i) // } $(".banner-nav>li").mouseenter(function () { $(".banner-nav>li").children("div").css("display","none"); $(this).children("div").css("display","block"); $(this).addClass("on"); }); $(".banner-nav>li").mouseleave(function () { $(".banner-nav>li").children("div").css("display","none"); $(this).removeClass("on"); }); }) })<file_sep>/** * Created by E560KCD on 2017/3/19. */ $(function () { $(".top-header").load("public.html", function () { $("#all").mouseenter(function () { $("#nav-1").css("display", "block") }); $("#all").mouseleave(function () { $("#nav-1").css("display", "none") }); }) // 放大镜 $(".luntu").mouseenter(function () { $(".img").children("img").attr("src",$(this).children("img").attr("src")) $(".big-pic").children("img").attr("src",$(this).children("img").attr("src")) }) function fangda() { $(".img").on("mousemove",function (e) { $(".zoom-pup").css("display","block"); $(".big-pic").css("display","block"); var x=e.pageX; var y=e.pageY; var zl=x-$(".pic-info").offset().left-($(".zoom-pup").width())/2; var zt=y-$(".pic-info").offset().top-($(".zoom-pup").height())/2; if(zl<0){ zl=0 } if(zt<0){ zt=0 } if(zl>$(".pic").width()-$(".zoom-pup").width()){ zl=$(".pic").width()-$(".zoom-pup").width(); } if(zt>$(".pic").height()-$(".zoom-pup").height()){ zt=$(".pic").height()-$(".zoom-pup").height(); } $(".zoom-pup").css({ "left":zl, "top":zt }); var percentX=zl/($(".pic").width()-$(".zoom-pup").width()); var percentY=zt/($(".pic").height()-$(".zoom-pup").height()); $(".big-pic img").css({ "left":percentX*($(".big-pic").width()-$(".big-pic img").width()), "top":percentY*($(".big-pic").height()-$(".big-pic img").height()) }) }) $(".img").mouseleave(function () { $(".zoom-pup").css("display","none"); $(".big-pic").css("display","none"); }) } fangda() $(".price-ph").mouseenter(function () { $(".price-ph-erwei").css("display","block") }) $(".price-ph").mouseleave(function () { $(".price-ph-erwei").css("display","none") }); var oIpt = document.getElementById("ipt"); var oJia = document.getElementById("jia"); var oJian = document.getElementById("jian"); oJia.onclick = function() { if(oIpt.value >= 1 && oIpt.value < 20) { oIpt.value++; } else if(oIpt.value > 20) { oIpt.value = 20; } else if(oIpt.value < 1) { oIpt.value = 1; } }; oJian.onclick = function() { if(oIpt.value > 1 && oIpt.value < 20) { oIpt.value--; } else if(oIpt.value > 20) { oIpt.value = 20; } else if(oIpt.value < 1) { oIpt.value = 1; } } // 返回顶部 $(".little").mouseenter(function () { $(".big").css("display","block") }) $(".little").mouseleave(function () { $(".big").css("display","none") }) $(window).scroll(function(){//fixed出现 if($(this).scrollTop()>400){ $(".fix_box_back_up").css("display","block"); }else{ $(".fix_box_back_up").css("display","none"); } }); $(".fix_box_back_up").click(function () { $("body,html").animate({scrollTop:0},300) }) $.post("../json/xiangqing.json",function (data) { var li=""; for(var i=0;i<data["xiang"].length;i++){ li+="<li><p class='pic'><a href='javascript:;'><img src='"+data["xiang"][i]["pic"]+"'></a> </p><p class='price'><span class='price-d'>"+data["xiang"][i]["price"]+"</span><a href='javascript:;' class='pinglun'>"+data["xiang"][i]["pinglun"]+"</a> </p></li>" } $(".list-alsoview").append(li) }) // 瀑布流 // function autolo() { // var i=0; // var me=this; // // this.getdata=function () { // $.post("../json/xiangqing.json",function (data) { // var puimg=""; // i++; // for(var i=0;i<data["pubu"].length;i++){ // puimg+="<img src='"+data["pubu"][i]+"' />" // $(".descrip").append(puimg); // } // }) // } // // // this.getscrolltop=function () { // // var scrotop=0; // // if($(document).scrollTop()){ // // scrotop=$(document).scrollTop() // // } // // return scrotop; // // } // // this.getclient=function () { // // var clienth=0; // // if($(window).height()) // // } // // // this.getscrolltop=function () { // var scrotop=0; // if (document.documentElement.scrollTop) { // scrotop = document.documentElement.scrollTop; // } else if (document.body) { // scrotop = document.body.scrollTop; // } // return scrotop; // } // this.getclient=function () { // var clienth=0; // if (document.body.clientHeight && document.documentElement.clientHeight) { // clienth = Math.min(document.body.clientHeight, document.documentElement.clientHeight) // } else { // clienth = Math.max(document.body.clientHeight, document.documentElement.clientHeight); // } // return clienth // } // this.getscroheig=function () { // var getscroheig = Math.max(document.body.scrollHeight, document.documentElement.scrollHeight); // return getscroheig; // } // // me.getdata(); // } // 瀑布流 function autolo() { var i=0; function getdata() { $.post("../json/xiangqing.json",function (data) { var puimg=""; i++; for(var i=0;i<data["pubu"].length;i++){ puimg="<img src='"+data["pubu"][i]+"' />"; $(".descrip").append(puimg); } //可以再改一下,传两个参数判断加载的具体图片 }) } //获取滚动条当前的位置 function getscrolltop() { var scrotop=0; if (document.documentElement.scrollTop) { scrotop = document.documentElement.scrollTop; } else if (document.body) { scrotop = document.body.scrollTop; } return scrotop; } //获取当前窗口可视范围的高度 function getclient() { var clienth=0; if (document.body.clientHeight && document.documentElement.clientHeight) { clienth = Math.min(document.body.clientHeight, document.documentElement.clientHeight) } else { clienth = Math.max(document.body.clientHeight, document.documentElement.clientHeight); } return clienth } //获取文档完整高度 function getscroheig() { var getscroheig = Math.max(document.body.scrollHeight, document.documentElement.scrollHeight); return getscroheig; } getdata(); window.onscroll=function () { if(getscrolltop()+getclient()==getscroheig()){ var sum=5; var timer=null; function ajacs() { if(i<5){timer=setTimeout(getdata(),500);} if(i==sum){clearTimeout(timer)} } ajacs(); } } } autolo(); // $.post("../json/cart.json",function (data) { // $(".a11").click(function () { // for(var k in data){ // Cookie.setCookie(k,1,"/",new Date(new Date().getTime()+7*24*3600*1000)); // } // console.log(Cookie.readCookie()) // }) // // // }) $(".a11").click(function () { document.cookie="name=dd1,"+$("#ipt").val()+";expires="+new Date(new Date().getTime()+7*24*3600000); window.location.href = "../html/shopping.html"; }) });<file_sep>/** * Created by E560KCD on 2017/3/19. */ $(function () { //导入头部文档html $(".top-header").load("public.html", function () { $("#all").mouseenter(function () { $("#nav-1").css("display", "block") }); $("#all").mouseleave(function () { $("#nav-1").css("display", "none") }); }); $.post("../json/huodong.json",function (data) { var span=""; for(var i=0;i<data["pinpai"].length;i++){ span+="<span><a href='javascript:;'>"+data["pinpai"][i]+"</a></span> " } $(".clearfix1").append(span); var span2=""; for(var q=0;q<data["fenlei"].length;q++){ span2+="<span><a href='javascript:;'>"+data["fenlei"][q]+"</a></span> " } $(".clearfix2").append(span2); // var li=""; // var li1=""; // function fenye() { // for(var w in data["list"]){ // for(var e=0;e<data["list"][w]["lunbo"].length;e++){ // li1+="<li><a href='javascript:;'><img src='"+data["list"][w]["lunbo"][e]+"'></a> </li>" // } // li+="<li class='lun'><a href='javascript:;' class='pic'><img class='datu' src='"+data["list"][w]["pic"]+"'></a><div class='pic-list-show'><a class='btn-a btn-l'></a><a class='btn-a btn-r'></a><div class='pic-list-lunbo'><ul>"+li1+"</ul></div></div><p class='price'><span class='price-n'>"+data["list"][w]["price"]+"</span></p><p class='name'><a href='javascript:;'>"+data["list"][w]["title"]+"</a></p><p class='search-hot-word'>"+data["list"][w]["hot-word"]+"</p><p class='star'><span class='level'><span></span></span><a href='javascript:;'>"+data["list"][w]["star"]+"</a></p><p class='link'><a>"+data["list"][w]["link"]+"</a></p> </li>" // li1="" // } // $(".bigimg").append(li); // $(".pic-list-lunbo ul").each(function(){ // $(this).css("width",$(this)[0].children.length*45+"px"); // if($(this).width()<150){ // $(this).parent().siblings().css("display","none") // } // }); // $(".pic-list-lunbo ul li a").click(function () { // // $(this).parent().parent().parent().parent().parent() // $(this).parents(".lun").children(".pic").children(".datu").attr("src",$(this).children("img").attr("src")) // }) // $(".btn-l").click(function () { // $(this).siblings(".pic-list-lunbo").children("ul").css("margin-left","0px") // }) // $(".btn-r").click(function () { // $(this).siblings(".pic-list-lunbo").children("ul").css("margin-left","-180px") // }) // } // fenye(); //右侧推广 var li2=""; for(var r in data["tui"]){ li2+="<li><a href='javascript:;' class='pic'><img src='"+data["tui"][r]["pic"]+"'></a><p class='dat'><a href='javascript:;'>"+data["tui"][r]["title"]+"</a> </p><p class='red'>"+data["tui"][r]["red"]+"</p><p class='price-p'><span class='d-price'>"+data["tui"][r]["price"]+"</span></p> </li>" } $(".list3").append(li2); //下边推广 var li3=""; for(var t in data["shang"]){ li3+="<li><a href='javascript:;' class='pic'><img src='"+data["shang"][t]["pic"]+"'></a><a href='javascript:;' class='name'>"+data["shang"][t]["title"]+"</a> <p class='red'>"+data["shang"][t]["hot-word"]+"</p><p class='price-p'><span class='d-price'>"+data["tui"][r]["price"]+"</span></p> </li>" } $(".hot-con-over ul").append(li3) }); //分页 function page() { var pos="",pos1="",txt="",txt1=""; var _s=0,_e=60; var me=this; var _num=""; var li=""; var li1=""; this.bianli=function (_x,_y,dd) { li=""; $.post("../json/huodong.json",function (data) { for(var d=_x;d<_y;d++){ for(var w in data["list"][d]){ for(var e=0;e<data["list"][d][w]["lunbo"].length;e++){ li1+="<li><a href='javascript:;'><img src='"+data["list"][d][w]["lunbo"][e]+"'></a> </li>" } li+="<li class='lun'><a href='javascript:;' class='pic'><img class='datu' src='"+data["list"][d][w]["pic"]+"'></a><div class='pic-list-show'><a class='btn-a btn-l'></a><a class='btn-a btn-r'></a><div class='pic-list-lunbo'><ul>"+li1+"</ul></div></div><p class='price'><span class='price-n'>"+data["list"][d][w]["price"]+"</span></p><p class='name'><a href='javascript:;'>"+data["list"][d][w]["title"]+"</a></p><p class='search-hot-word'>"+data["list"][d][w]["hot-word"]+"</p><p class='star'><span class='level'><span></span></span><a href='javascript:;'>"+data["list"][d][w]["star"]+"</a></p><p class='link'><a>"+data["list"][d][w]["link"]+"</a></p> </li>" li1="" } } $(".bigimg").html(li); $(".pic-list-lunbo ul").each(function(){ $(this).css("width",$(this)[0].children.length*45+"px"); if($(this).width()<150){ $(this).parent().siblings().css("display","none") } }); $(".pic-list-lunbo ul li a").click(function () { // $(this).parent().parent().parent().parent().parent() $(this).parents(".lun").children(".pic").children(".datu").attr("src",$(this).children("img").attr("src")) }); $(".btn-l").click(function () { $(this).siblings(".pic-list-lunbo").children("ul").css("margin-left","0px") }); $(".btn-r").click(function () { $(this).siblings(".pic-list-lunbo").children("ul").css("margin-left","-180px") }); if($(dd).index()==1 && parseInt($(dd).html())-2>0){ for(var y=0;y<$(".fenyema").length;y++){ $(".fenyema").eq(y).html(parseInt($(".fenyema").eq(y).html())-2) } $(".fenyema").eq(3).css({ "background":"red", "color":"#fff" }).siblings().css({ "background":"#fff", "color":"#000" }) }else { } if($(dd).index()==$(".fenyema").length){ for(var i=0;i<$(".fenyema").length;i++){ $(".fenyema").eq(i).html(parseInt($(".fenyema").eq(i).html())+2) if(parseInt($(".fenyema").eq(i).html())>data["list"].length/60){ $(".fenyema").eq(i).css("display","none") } } }else { } }); }; me.bianli(_s,_e); this.click=function () { $(".fenyema").click(function () { var dd=this; _s=parseInt($(this).html()); me.bianli((_s-1)*60,_s*60,dd); $(".number").html($(this).html()); $(".or").html($(this).html()); }) } this.prev=function () { $(".prev").click(function () { _s-=1; if(_s>=1&&$(".fenyema").eq(0).html()>1){ me.bianli((_s-1)*60,_s*60); $(".number").html($(this).html()); $(".or").html($(this).html()); for (var i=0;i<$(".fenyema").length;i++){ $(".fenyema").eq(i).html(parseInt($(".fenyema").eq(i).html())-1) } }else { _s=1; } }) } this.next=function () { $(".next").click(function () { _s+=1; if(_s<15 && $(".fenyema").last().html()<15){ me.bianli((_s-1)*5,_s*5); $(".number").html($(this).html()); $(".or").html($(this).html()); for (var i=0;i<$(".fenyema").length;i++){ $(".fenyema").eq(i).html(parseInt($(".fenyema").eq(i).html())+1) } }else { _s=15; } }) } this.up=function () { if($(this).index()==$(".fenyema").length-1){ for (var i=0;i<$(".fenyema").length;i++){ $(".fenyema").eq(i).html(parseInt($(".fenyema").eq(i).html())+1) } } } } var _page=new page(); _page.click(); _page.prev(); _page.next(); // 返回顶部 $(".little").mouseenter(function () { $(".big").css("display","block") }) $(".little").mouseleave(function () { $(".big").css("display","none") }) $(window).scroll(function(){//fixed出现 if($(this).scrollTop()>400){ $(".fix_box_back_up").css("display","block"); }else{ $(".fix_box_back_up").css("display","none"); } }); $(".fix_box_back_up").click(function () { $("body,html").animate({scrollTop:0},300) }) });<file_sep>/** * Created by E560KCD on 2017/3/18. */ $(function () { //导入导航栏文档HTML //导航栏js文件,目前只能放在公共的文档里面才能用,分开成两个js文件就不能用。有待解决 $.post("../json/nav.json",function (data) { var _code = "";//导航栏里面的span和a var _cod = "";//导航栏span标签 var _aa = "";//滑过显示的大详情表的上头一排a标签 var _top = "";//滑过显示的大详情表的上头要放进div标签 var _left_top = "";//承载内容的盒子 var _nav_pop = "";//承载盒子的框架 var zong = "";//导航栏li标签 var _left_box = "";//承载详情li标签的ul var _h4 = "";//承载小类目标题的标签 var _aa2 = "";//承载小类目右面的详细的分类的a标签 var _div2 = "";//承载小类目右面的详细的分类的div var _li = "";//承载小类目标题跟分类div的li var _li1 = "";//承载小类目标题跟分类div的li的集合 var _ul = "";//承载小类目标题跟分类div的li的ul var _div3 = "";//承载ul的li for (var i in data) { //左侧导航栏 for (var n in data[i]["dd-nav"]) { _code += "<a href='javascript:;'>" + data[i]["dd-nav"][n]["dd-name"] + "</a>"; _cod = "<span>" + _code + "</span>"; } for (var m in data[i]["dd-top"]) { _aa += "<a href='javascript:;'>" + data[i]["dd-top"][m]["dd-name"] + "</a>"; _top = "<div class='new-pop-guan'>" + _aa + "</div>"; } for (var k in data[i]["dd-left"]) { _h4 = "<h4><a href='javascript:;'>" + data[i]["dd-left"][k]["dd-name"] + "</a></h4>" for (var h in data[i]["dd-left"][k]["dd-right"]) { _aa2 += "<a href='javascript:;'>" + data[i]["dd-left"][k]["dd-right"][h]["dd-name"] + "</a>" _div2 = "<div>" + _aa2 + "</div>" _li = "<li>" + _h4 + _div2 + "</li>" } _aa2 = "" _li1 += _li } _ul = "<ul class='left'>" + _li1 + "</ul>" _left_top = "<div class='left-box'>" + _top + _ul + "</div>"; _nav_pop = "<div class='nav-pop'>" + _left_top + "</div>"; zong = "<li>" + _cod + _nav_pop + "</li>" $(".banner-nav").append(zong); _aa = ""; _top = ""; _code = ""; _cod = ""; _h4=""; _ul=""; _div2=""; _li=""; _aa2=""; _li1=""; } // for(var i=0;i<$(".banner-nav>li").length;i++){ // (function(i){ // $(".banner-nav>li").eq(i).css({ // "top":i*30+"px" // }) // })(i) // } $(".banner-nav>li").mouseenter(function () { $(".banner-nav>li").children("div").css("display","none"); $(this).children("div").css("display","block"); $(this).addClass("on"); }); $(".banner-nav>li").mouseleave(function () { $(".banner-nav>li").children("div").css("display","none"); $(this).removeClass("on"); }); }) //top菜单 $.post("../json/address.json",null,function (data) { var _data=data; // console.log(_data); var _code=""; for(var i=0;i<_data["address"].length;i++){ _code+='<li><a href="javascript:;">'+_data["address"][i]+'</a> </li>'; } $("#top-left-address").html(_code); //换地址 $("#top-left-address a").click(function () { $("#address").html(this.innerHTML) $("#top-left-address").css("display","none"); $(this).css({ "background":"none", "border-color":"#f9f9f9" }) $(".address-one").css("background","url(\"../images/img.png\")no-repeat right -303px") }) }) //地址 $(".top-left").mouseenter(function () { $("#top-left-address").css("display","block"); $(this).css({ "background":"#fff", "border-color":"#e6e6e6" }) $(".address-one").css("background","url(\"../images/img.png\")no-repeat right -321px") }); $(".top-left").mouseleave(function () { $("#top-left-address").css("display","none"); $(this).css({ "background":"none", "border-color":"#f9f9f9" }) $(".address-one").css("background","url(\"../images/img.png\")no-repeat right -303px") }); //我的当当,企业采购,客户服务 $(".top-right-list-li").mouseenter(function () { $(".top-right-list").css("display","none"); $(this).children("div").css("display","block"); $(this).css({ "background":"#fff", "border-color":"#e6e6e6" }) $(".my-dd").css({"background":"url(\"../images/img.png\")no-repeat right -307px"}) $(this).children("a").css({ "background":"#fff url(\"../images/img.png\")no-repeat right -325px", "color":"#ff2832" }) }) $(".top-right-list-li").mouseleave(function () { $(".top-right-list").css("display","none"); $(this).css({ "background":"url(\"../images/img.png\") no-repeat left -285px", "border-color":"#f9f9f9" }) $(this).children("a").css({ "background":"url(\"../images/img.png\")no-repeat right -307px", "color":"#646464" }) }) //手机当当 $(".top-right-list-li-phone").mouseenter(function () { $(".top-right-list-phone").css("display","block"); $(".phone").css("background","url(\"../images/img.png\")no-repeat -51px -70px") $(this).css({ "border-color":"#e6e6e6", "background":"#fff" }) $(this).children("a").css({ "color":"#ff2832" }) }) $(".top-right-list-li-phone").mouseleave(function () { $(".top-right-list-phone").css("display","none"); $(".phone").css("background","url(\"../images/img.png\")no-repeat -40px -70px") $(this).css({ "border-color":"#f9f9f9", "background":"url(\"../images/img.png\") no-repeat left -285px" }) $(this).children("a").css({ "color":"#646464" }) }) //搜索框 $.post("../json/hotword.json",function (data) { var _data=data; var _code=""; for(var i=0;i<_data["hotword"].length;i++){ _code+='<a href="javascript:;">'+_data["hotword"][i]+'</a>'; } $(".search-hot").append(_code); }) // 搜索数据 $(".search-text").focus(function () { $(".search-key").css("display", "block") }) $(".search-text").on("keyup", function () { var url= "https://suggest.taobao.com/sug?code=utf-8&q=" + $(this).val() + "&callback=?" $.getJSON(url,fn) }) function fn(data) { $(".search-key").empty() for (var i in data.result) { $(".search-key").append($('<li>' + data.result[i][0] + '</li>')) } $(".search-key li").click(function () { $(".search-text").val(this.innerHTML) $(".search-key").css("display","none"); }) } // $(".search-key").blur(function () { // $(".search-key").css("display", "none") // }) // 搜索框全部分类 $.post("../json/allcategories.json",function (data) { var _data=data; var _code=""; for(var i=0;i<_data["allcategories"].length;i++){ _code+='<a href="javascript:;"><span>'+_data["allcategories"][i]+'</span></a>'; } $(".search-all").append(_code); $(".search-allcategories").mouseenter(function () { $(".search-all").css({ "height":"286px", "border-width": "1px", "padding":"1px" }); $(".search-all a").click(function () { $(".allcategories").html(this.innerHTML) $(".search-all").css({ "height":"0px", "border-width": "0", "padding":"0px" }); }) }); }); $(".search-allcategories").mouseleave(function () { $(".search-all").css({ "height":"0px", "border-width": "0", "padding":"0px" }); }); // 一级导航栏 $.post("../json/allcategories.json",function (data) { var _data=data; var _code=""; for(var i=0;i<_data["nav-top"].length;i++){ _code+='<li><a href="javascript:;">'+_data["nav-top"][i]+'</a></li>'; } $("#navall1").append(_code); }); });<file_sep>/** * Created by E560KCD on 2017/3/30. */ $(function () { $(".btn").click(function () { ajaxRequest("post", "../javascript/login.php", true, { "user": $(".user").val(), "pwd": $(".pass").val() }, function (data) { /** * {"user":"h51615","pwd":"<PASSWORD>"} * 向服务器传递参数,上面的两个key不可改变。 */ data=data.replace(/\s+/g,""); if(data!="0") { alert(1) window.location.href="index.html" }else{ alert("用户名或者密码错误!!!请输入正确的用户名或者密码!!!"); } }); }) })<file_sep>{ "1":{ "ddname":{ "p_name":"产品1", "p_price":100, "p_discount":0.9, "p_detail":[1,2,3,4,6], "p_main":"main.jpg", "p_group":[1,2,3,4,5,6,7], "p_category":"101101", "p_brand":1, "p_config":"这里是产品的配置内容......" }, "p_name":"产品1", "p_price":100, "p_discount":0.9, "p_detail":[1,2,3,4,6], "p_main":"main.jpg", "p_group":[1,2,3,4,5,6,7], "p_category":"101101", "p_brand":1, "p_config":"这里是产品的配置内容......" }, "2":{ "p_name":"产品2", "p_price":100, "p_discount":0.9, "p_detail":[1,2,3,4,6], "p_main":"main.jpg", "p_group":[1,2,3,4,5,6,7], "p_category":"102101", "p_brand":1, "p_config":"这里是产品的配置内容......" } }
2bcc6906592bc5d1e8e1dcc690236115055561e9
[ "JavaScript", "JSON with Comments" ]
8
JavaScript
shuai0910/zhang
9ac07fe756579af1d97377f5c115fc739b48fdaa
c66a0ddd3d60b2fdd6b61b7b8eabde3264457163
refs/heads/master
<file_sep>def speak_to_grandma if speak_to_grandma == "Hi Nana, how are you?" puts "HUH?! SPEAK UP, SONNY!".upcase else speak_to_grandma == "HI NANA, HOW ARE YOU?" if speak_to_grandma == "HI NANA, HOW ARE YOU?" puts "NO, NOT SINCE 1938!" if speak_to_grandma == "I LOVE YOU GRANDMA!" puts "I LOVE YOU TOO PUMPKIN!" if ("responds with HUH?! SPEAK UP, SONNY! for a second time") do speak_to_grandma == "Hi" puts "HUH?! SPEAK UP, SONNY!" end
c07dc4f3c504923b790794b854090ac2ce56c061
[ "Ruby" ]
1
Ruby
CGonzalez0115/speaking-grandma-online-web-pt-081219
53e213ba58599dff10d1cbc08275f6a4048cc6dd
263f5425c5f7a17630385b11b599f43a66eac041
refs/heads/master
<repo_name>mengxx123/color-front<file_sep>/src/components/index.js import page from './page' import colorPicker from './color-picker' import colorPickerEx from './color-picker-ex' import preview from './preview' import appList from './app-list' // import colorPicker2 from './color-picker/index2' // import colorPicker3 from './picker' export default { install: function (Vue) { Vue.component('my-page', page) Vue.component('ui-color-picker', colorPicker) Vue.component('ui-color-picker-ex', colorPickerEx) Vue.component('preview', preview) Vue.component('app-list', appList) // Vue.component('my-color-picker2', colorPicker2) // Vue.component('my-color-picker3', colorPicker3) } } <file_sep>/src/components/picker/index.js import vueGoback from '../color-picker/index.vue' export default vueGoback <file_sep>/src/router/index.js import Vue from 'vue' import Router from 'vue-router' const Home = resolve => require(['@/views/Home'], resolve) const All = resolve => require(['@/views/All'], resolve) const Palette = resolve => require(['@/views/Palette'], resolve) const PaletteHelp = resolve => require(['@/views/PaletteHelp'], resolve) const PaletteSettings = resolve => require(['@/views/PaletteSettings'], resolve) const Gradient = resolve => require(['@/views/Gradient'], resolve) const ChineseColor = resolve => require(['@/views/ChineseColor'], resolve) const JapenColor = resolve => require(['@/views/JapenColor'], resolve) const MaterialDesignColor = resolve => require(['@/views/MaterialDesignColor'], resolve) const ColorScheme = resolve => require(['@/views/ColorScheme'], resolve) const Hue = resolve => require(['@/views/Hue'], resolve) const Search = resolve => require(['@/views/Search'], resolve) const Convert = resolve => require(['@/views/Convert'], resolve) const Error404 = resolve => require(['@/views/error/Error404'], resolve) Vue.use(Router) let routes = [ { path: '/', component: Home }, { path: '/palette', component: Palette }, { path: '/palette/help', component: PaletteHelp }, { path: '/palette/settings', component: PaletteSettings }, { path: '/hue', component: Hue }, { path: '/gradient', component: Gradient }, { path: '/color/chinese', component: ChineseColor }, { path: '/color/japen', component: JapenColor }, { path: '/color/materialDesign', component: MaterialDesignColor }, { path: '/colorScheme', component: ColorScheme }, { path: '/search', component: Search }, { path: '/color/all', component: All }, { path: '/convert', component: Convert }, { path: '*', component: Error404 } ] let router = new Router({ mode: 'history', routes: routes, scrollBehavior (to, from, savedPosition) { return { x: 0, y: 0 } } }) export default router
901f9f1b06985e981aaeabc8806b5052ba9dcb43
[ "JavaScript" ]
3
JavaScript
mengxx123/color-front
7f84e75ed0740ed86002b4bdad37a83f12a055b8
667d751f47209c4edb31a87e46df9aac21640259
refs/heads/master
<repo_name>kiazim14/Kata-tennis<file_sep>/README.md "# Kata-tennis" <file_sep>/Scorefinaltest.java package com.kata_tennis.test; import com.kata_tennis.service.Scorefinal; import junit.framework.TestCase; public class Scorefinaltest extends TestCase{ Scorefinal scofi = new Scorefinal("player_1" , "player_2"); int player_2 = 0; public void testNewScoreBall() throws Exception { String score = scofi.result(); assertEquals("zero", score); } public void testFirstBall() throws Exception { scofi.firstplayerscoreInc(); scofi.secondplayerscoreInc(); String score = scofi.result(); assertEquals("zero", score); } public void testFifteenAll() throws Exception{ scofi.firstplayerscoreInc(); scofi.secondplayerscoreInc(); String score = scofi.result(); assertEquals("Fifteen all", score); } public void testThirtyAll() throws Exception{ scofi.firstplayerscoreInc(); scofi.secondplayerscoreInc(); String score = scofi.result(); assertEquals("Thirty all", score); } public void testFortyAll() throws Exception{ scofi.firstplayerscoreInc(); scofi.secondplayerscoreInc(); String score = scofi.result(); assertEquals("Forty all", score); } public void testplayer_2master() throws Exception { createScore(0, 2); String score = scofi.result(); assertEquals("zero,Thirty", score); } public void testplayer_1master() throws Exception{ createScore(3, 0); String score = scofi.result(); assertEquals("Forty,zero", score); } public void testplayersareDeuce() throws Exception { createScore(3, 3); String score = scofi.result(); assertEquals("Deuce", score); } public void testplayer_1Adscore() throws Exception { createScore(4, 0); String score = scofi.result(); assertEquals("player_1", score); } public void testPlayersAreDuce4() throws Exception { createScore(4, 4); String score = scofi.result(); assertEquals("Deuce", score); } public void testplayer_1Adscorega() throws Exception{ createScore(5, 4); String score = scofi.result(); assertEquals("Advantage player_1", score); } public void testplayer_1Afscore() throws Exception { createScore(8, 6); String score = scofi.result(); assertEquals("Player_1 master", score); } private void createScore(int player_1, int player2) { for (int i = 0; i < player_1; i++) { scofi.firstplayerscoreInc(); } for (int i = 0; i <player_2; i++) { scofi.secondplayerscoreInc(); } } }
f4c52aa89ccfe4746fe99b8839e8102d96ffd2b6
[ "Markdown", "Java" ]
2
Markdown
kiazim14/Kata-tennis
7e12f740ee48a338f4259b57fb85a9ba7119c666
8a66738f7ffe3e450e03cd8c33626302fd7a1b6f
refs/heads/master
<file_sep>#!/usr/bin/env python3 ''' Abbreviations: BotT: Bane of the Trapped CHC: Critical Hit Chance CHD: Critical Hit Damage FA: Fetish Army IAS: Increased Attack Speed Intel: Intelligence MoJ: Mask of Jeram SZD: Summon Zombie Dogs ''' class SheetStat: intel = 9400 CHC = 50.5 / 100 CHD = 403 / 100 weapon_damage = (2122, 2122) weapon_base_APS = 1.4 IAS_on_weapon = 0 / 100 IAS_on_gear_and_paragon_points = 35 / 100 class WD: # Input gear mask = ("Mask of Jeram", "Carnevil", "Other")[0] MoJ_increase_pet_damage_rate = 79 / 100 cold_damage_increase_rate = 0 / 100 physical_damage_increase_rate = 0 / 100 fire_damage_increase_rate = 0 / 100 poison_damage_increase_rate = 0 / 100 FA_damage_increase_rate = 0 / 100 SZD_damage_increase_rate = 0 / 100 Gargantuan_damage_increase_rate = 0 / 100 damage_increase_against_elites = 0 / 100 # Legendary gems Enforcer = 22.5 / 100 BotT =<file_sep># d3dc Diablo3 Damage Calculator Started based on <NAME>'s mighty Google sheet: https://docs.google.com/spreadsheets/d/1ZwY2AgfCTYu2sBF4uXM9F-8jfy3BH-w1MzuqV8CEXb4/edit#gid=530231805
8986d45f6ee893a9236d6373329c27c2d59d067e
[ "Markdown", "Python" ]
2
Python
MichaelLing83/d3dc
cf91b6c741ca5dcd9f6c537f7a020634da4281c4
9a0521d486433b290959cc05334695ed9905dee5
refs/heads/master
<repo_name>hitontology/csv2rdf<file_sep>/download.py from urllib import request import subprocess RESET = "\033[1;0m" GREEN = "\033[1;32m" sheets = { "Link/link.csv": {"key": "<KEY>", "gid": 0}, "Mb/applicationsystemtype.csv": {"key": "<KEY>", "gid": 1532284086}, "JoshiPacs/feature.csv": {"key": "<KEY>", "gid": 256105438}, "WhoDhiSystemCategory/applicationsystemtype.csv": {"key": "<KEY>", "gid": 1235425432}, "WhoDhiClient/feature.csv": {"key": "<KEY>", "gid": 73177652}, "WhoDhiHealthcareProvider/function.csv": {"key": "<KEY>", "gid": 0}, "WhoDhiHealthcareProvider/feature.csv": {"key": "<KEY>", "gid": 54553433}, "WhoDhiHealthSystemManager/function.csv": {"key": "<KEY>", "gid": 405952217}, "WhoDhiHealthSystemManager/feature.csv": {"key": "<KEY>", "gid": 754899153}, "WhoDhiDataService/feature.csv": {"key": "<KEY>", "gid": 799700984}, "EhrSfm/feature.csv": {"key": "<KEY>", "gid": 0}, "Bb/applicationsystemtype.csv": {"key": "<KEY>", "gid": 1532284086}, "Bb/function.csv": {"key": "<KEY>", "gid": 1259391562}, "Bb/feature.csv": {"key": "<KEY>", "gid": 1234838117}, } def csvUrl(key,sheet): return "https://docs.google.com/spreadsheets/d/" + key + "/export?format=csv&gid=" + str(sheet) for file in sheets: s = sheets[file] url = csvUrl(s["key"],s["gid"]) print("Downloading", GREEN, file, RESET, "from", GREEN, url, RESET + "...") request.urlretrieve(url, file) print(GREEN,"Downloads finished",RESET) # end of line conversion from CRLF to LF (\n) to match repository and not cause unnecessary diffs try: subprocess.run("dos2unix */*.csv", shell=True) except FileNotFoundError: print("dos2unix command not found. Skipping end of line conversion.") try: subprocess.run(["git", "status"]) except FileNotFoundError: pass <file_sep>/README.md # HITO-CSV2RDF Transformation of the HITO CSV tables to RDF/OWL ## Background The HITO project contains catalogues of features and other things. These catalogues are first extracted as CSV tables and then converted to RDF. This repository contains the scripts used to convert CSV tables, that are created by domain experts working for SNIK. After a catalogue is converted to RDF, it gets added to the HITO ontology repository and a copy is uploaded to the [HITO SPARQL Endpoint](http://www.hitontology.eu/sparql). The repository is the source of truth and changes to the SPARQL endpoint are not permanent. We are currently in the process of moving the source of truth for all software products and related attributes to a database, see https://github.com/hitontology/database. ## Attributes You may describe software products both with an attribute.csv and a base.ttl file, though we recommend to use attribute.csv for all supported attributes and base.ttl for the rest. attribute.csv doesn't fit catalogues well, so we recommend just the base.ttl there. ## Requirements * Linux * installed [tarql](https://tarql.github.io/) and [rapper](http://librdf.org/raptor/rapper.html) ## Steps 1. Run `map`, if there is an error with your directory or the final test is not successful, fix the source files and run map again until it completes successfully. 2. Upload the resulting ntriples files (1 per directory/source) in the [HITO SPARQL endpoint conductor](https://www.snik.eu/conductor) (credentials required). Make sure to provide the correct graph name, such as http://hitontology.eu/ontology and to clear that graph first. <file_sep>/classlist.py # reads list of DBpedia classes and outputs sorted list of common classes along with their occurrence # SELECT DISTINCT(?type) {dbr:Arden_syntax rdf:type ?type.} from collections import defaultdict from sys import stdin import requests import urllib.parse classes = defaultdict(set) count = 0 for resource in stdin: count+=1 resource = resource.strip() types = list(requests.get("http://dbpedia.org/sparql?default-graph-uri=http%3A%2F%2Fdbpedia.org&query=SELECT+DISTINCT%28%3Ftype%29+%7Bdbr%3A"+resource+"+rdf%3Atype+%3Ftype.%7D&format=text%2Ftab-separated-values").text.replace('"','').split("\n")) types.pop(0) # header types = set(types) types.remove(""); #print(types) for t in types: classes[t].add(resource) #print(classes) sorted = sorted(classes.keys(), key=lambda k: -len(classes[k])) sorted = sorted[:11] for k in sorted: quote = urllib.parse.quote_plus(k) query = "https://dbpedia.org/sparql?default-graph-uri=http%3A%2F%2Fdbpedia.org&query=SELECT+COUNT%28DISTINCT%28%3Fx%29%29+%7B%3Fx+a+%3C"+quote+"%3E+%7D&format=text%2Ftab-separated-values&CXML_redir_for_subjs=121&CXML_redir_for_hrefs=&timeout=30000&debug=on&run=+Run+Query+" size = int(requests.get(query).text.split("\n")[1]) print("|",k,"|",len(classes[k]),"|",size,"|",len(classes[k])*100/size,"|") #print(k+";"+len(classes[k])+";"+size+";"+classes[k]) print(count,"resources in total") <file_sep>/check.py # reads list of SNIK bb class suffixes from stdin and outputs those that don't exist import requests from sys import stdin for line in stdin: if (requests.get("https://www.snik.eu/sparql?default-graph-uri=&query=ASK+%7Bbb%3A"+line+"+%3Fp+%3Fo.%7D&should-sponge=&format=text%2Fhtml&timeout=0&debug=on").json() == False): print(line.strip()) <file_sep>/map.dist #!/bin/bash set -e SUBS="Bahmni Bb GnuHealth Orthanc Standard WhoDhiClient WhoDhiDataService WhoDhiHealthcareProvider WhoDhiHealthSystemManager WhoDhiSystemCategory EhrSfm Mb Link" TEMPLATES="attribute standard subfeature feature function applicationsystemtype applicationsystemtypecitation featurecitation functioncitation organizationalunitcitation usergroupcitation link" RED='\033[0;31m' ORANGE='\033[0;33m' LIGHTGREEN='\033[1;32m' GRAY='\033[0;37m' YELLOW='\033[1;33m' BLUE='\033[1;34m' NC='\033[0m' function map { echo -e "* ${BLUE}DIRECTORY ${s}${NC}" mkdir -p ${s}/tmp mkdir -p ${s}/tmp/old mv ${s}/tmp/*.nt ${s}/tmp/old || true found=0 for t in $TEMPLATES do csv="${s}/${t}.csv" if [ -e $csv ] then echo -e -n "** ${LIGHTGREEN}Using Template ${t} on ${csv} ${NC}..." ((found=found+1)) mkdir -p ${s}/out sed "s|{SUB}|${s}|g" ${t}.tarql.template > ${s}/tmp/${t}.tarql tarql ${s}/tmp/${t}.tarql | rapper -q -i turtle - http://hitontology.eu/ontology/ > ${s}/tmp/${t}.nt echo -e " ${LIGHTGREEN}`wc -l < ${s}/tmp/${t}.nt` triples${NC}" #else #echo -e "${GRAY}**** ${csv} DOES NOT EXIST, SKIPPING TEMPLATE ${t} *******************************${NC}" fi done if [ $found -eq "0" ] then echo -e "** ${RED}ERROR: DIRECTORY ${s} DOES NOT MATCH ANY TEMPLATE, SKIPPING ${s} ${NC}" return fi echo -e -n "** ${LIGHTGREEN}Merging${NC}... " if [ -e ${s}/base.ttl ] then echo -e -n "$LIGHTGREEN adding base${NC}: " rapper -q -i turtle ${s}/base.ttl > ${s}/tmp/base.nt echo -e -n "$LIGHTGREEN `wc -l < ${s}/tmp/base.nt` triples${NC}. " fi cat prefix.ttl ${s}/tmp/*.nt | rapper -q -i turtle -o turtle - http://hitontology.eu/ontology/ > ${s}/out/all.ttl rapper -q -i turtle -o ntriples ${s}/out/all.ttl >> /tmp/combined.nt echo -e -n "${LIGHTGREEN}Testing${NC}... " rapper -q -i turtle -c ${s}/out/all.ttl echo -e "${LIGHTGREEN}`wc -l < ${s}/out/all.ttl` triples in ${s}/out/all.ttl, `wc -l < /tmp/combined.nt` total${NC}" } rm -f /tmp/combined.nt for s in $SUBS do if [ ! -d "${s}" ] then echo -e "** ${RED}ERROR: DIRECTORY ${s} DOES NOT EXIST, SKIPPING ${s} ${NC}" else map $s # no fork needed, tarql is parallized already fi done echo -e -n "${LIGHTGREEN}sorting and converting to Turtle format${NC}... " sort /tmp/combined.nt -o /tmp/combined.nt rapper -q -i turtle -c /tmp/combined.nt cat prefix.ttl /tmp/combined.nt | rapper -q -i turtle -o turtle - http://hitontology.eu/ontology/ > /tmp/combined.ttl echo -e "${LIGHTGREEN}`wc -l < /tmp/combined.nt` triples in /tmp/combined.ttl${NC}"
fe105db2e9160e145fbd689bfcf8f85e9b30393f
[ "Markdown", "Python", "Shell" ]
5
Python
hitontology/csv2rdf
38eef662a101d37a654c12e856dc54694a9adddb
a0399caf8d0aeb2dd72b432a7321cdd0005ad5b3
refs/heads/master
<file_sep>httplib2==0.9.2 keyring==9.3 launchpadlib==1.10.3 lazr.authentication==0.1.3 lazr.restfulclient==0.13.1 lazr.uri==1.0.3 oauth==1.0.1 pbr==1.10.0 simplejson==3.8.2 six==1.10.0 testresources==2.0.1 wadllib==1.3.2 wsgi-intercept==1.2.2 wsgiref==0.1.2 zope.interface==4.2.0 <file_sep>import csv from launchpadlib.launchpad import Launchpad from pprint import pprint class Report(object): default_filepath = 'reports/bugdump.csv' default_project = 'openstack' default_importance = [ 'Critical' ] default_status = [ 'New', 'Incomplete', 'In Progress', 'Confirmed', 'Triaged', 'Fix Committed' ] def __init__(self, debug=False, limit=None): self.limit = limit # Stop after 'limit' bugs if not None self.debug = debug self.dialect = csv.excel self.report = [] if self.debug: print("Enabling debug output") if self.limit: print("Limiting report to %d bugs" % self.limit) def get_meta_keys(self): # Unused, but this is the list of all fields present in a 'task'. # A 'task' contain meta-data encapsulating a bug. return [ 'http_etag', 'is_complete', 'milestone_link', 'resource_type_link', 'bug_watch_link', 'date_assigned', 'date_closed', 'date_confirmed', 'date_fix_committed', 'date_fix_released', 'date_in_progress', 'date_incomplete', 'date_left_closed', 'date_left_new', 'date_triaged', 'assignee_link', 'bug_link', 'bug_target_display_name', 'bug_target_name', 'date_created', 'importance', 'owner_link', 'related_tasks_collection_link', 'self_link', 'status', 'target_link', 'title', 'web_link' ] def get_ordered_fieldnames(self): return [ 'req', 'bug', 'version', 'project', 'component', 'fault_class', 'fault_type', 'fault_description', 'fault_symptom', 'severity', 'priority', 'status', 'mitigation', 'log', 'repro', 'submitter', 'assignee', 'created', 'deployment' ] def xstr(self, string): if string is None: return '' else: return string.encode('utf8') def create(self, project, importance, status): iteration = 0 self.report = [] lp = Launchpad.login_anonymously('just testing', 'production', 'cache', version='devel') p = lp.projects[project] # pass status to filter on a subset of bugs bug_tasks = p.searchTasks(importance=importance, status=status) print("Found %d bugs in the %s project with importance %s" % (len(bug_tasks), project, str(importance))) for task in bug_tasks: if self.limit: self.limit -= 1 bug = lp.bugs.getBugData(bug_id=task.bug.id)[0] if self.debug: print "Processing %s" % task else: iteration += 1 (q, r) = divmod(iteration, 10) print '%s' % iteration if r == 0 else '.', # remap fields from lb task and bug empty = '' row = { 'req': self.xstr(bug['bug_summary']), 'bug': self.xstr(task.web_link), 'version': empty, 'project': self.xstr(task.bug_target_name), 'component': empty, 'fault_class': empty, 'fault_type': empty, 'fault_description': self.xstr(bug['description']), 'fault_symptom': empty, 'severity': self.xstr(task.importance), 'priority': empty, 'status': self.xstr(task.status), 'mitigation': empty, 'log': empty, 'repro': empty, 'submitter': self.xstr(task.owner_link), 'assignee': self.xstr(task.assignee_link), 'created': self.xstr(str(task.date_created)), 'deployment': empty } self.report.append(row) if self.limit == 0: break print("\nFinished compiling table for project %s" % project) def dump(self): for row in self.report: pprint(row) def save(self, filepath): with open(filepath, 'w') as csvfile: writer = csv.DictWriter(csvfile, fieldnames=self.get_ordered_fieldnames(), dialect=self.dialect) writer.writeheader() for row in self.report: try: writer.writerow(row) except Exception as err: print 'Row:' pprint(row) print 'Exception: %s' % err csvfile.close() def open(self, filepath): self.report = [] with open(filepath, 'rb') as csvfile: reader = csv.DictReader(csvfile, dialect=self.dialect) for row in reader: self.report.append(row) csvfile.close() def generate_report(filepath=Report.default_filepath, project=Report.default_project, importance=Report.default_importance, status=Report.default_status): report = Report(debug=False, limit=None) report.create(project, importance, status) report.save(filepath) def read_report(filepath): report = Report(debug=False, limit=None) report.open(filepath) report.dump() if __name__ == "__main__": generate_report(importance=['High'])
fd3351196930aa981b8aec0f4493a6a9b8d99cff
[ "Python", "Text" ]
2
Text
mattgreene/openstack-faultgenes
a6930c959384094da43757ec6baf553d4487f0e2
d72691cbb60bda4b0c824871418970d2d7c8c9e4
refs/heads/master
<file_sep>Django>=1.3 git+git://github.com/vencax/feincms.git<file_sep>from setuptools import setup, find_packages print find_packages() setup( name='django-value-ladder', version='0.1', description='Things value definition application.', author='<NAME>', author_email='<EMAIL>', url='vxk.cz', packages=find_packages(), include_package_data=True, ) <file_sep>from django.db import models from django.utils.translation import gettext_lazy as _ from feincms import translations from django.template.defaultfilters import slugify from django.conf import settings class ThingObjectManager(translations.TranslatedObjectManager): """ Object manager that offers get_default thing method """ def get_default(self): return self.get(code=settings.DEFAULT_CURRENCY) class Thing(models.Model, translations.TranslatedObjectMixin): """ Represents a thing ... :) """ code = models.CharField(_('code'), max_length=16) objects = ThingObjectManager() class Meta: verbose_name = _('thing') verbose_name_plural = _('things') class ThingTranslation(translations.Translation(Thing)): title = models.CharField(_('category title'), max_length=32) slug = models.SlugField(_('slug'), unique=True) description = models.CharField(_('description'), max_length=256, blank=True) class Meta: verbose_name = _('thing translation') verbose_name_plural = _('thing translations') ordering = ['title'] def __unicode__(self): return self.title @models.permalink def get_absolute_url(self): return ('forum_category', (), { 'slug': self.slug, }) def save(self, *args, **kwargs): if not self.slug: self.slug = slugify(self.title)[:32] super(ThingTranslation, self).save(*args, **kwargs) class ThingValue(models.Model): """ Value ratio between the two things. """ class Meta: verbose_name = _('thing value') verbose_name_plural = _('thing values') unique_together = ('thingA', 'thingB', 'ratio') thingA = models.ForeignKey(Thing, verbose_name='%s A' % _('thing'), related_name='changing_things') thingB = models.ForeignKey(Thing, verbose_name='%s B' % _('thing'), related_name='changed_things') ratio = models.FloatField(_('value ratio between the 2')) <file_sep>from django.contrib import admin from feincms.translations import admin_translationinline from .models import Thing, ThingValue from valueladder.models import ThingTranslation ThingTranslationInline = admin_translationinline(ThingTranslation, prepopulated_fields={'slug': ('title',)}) class ThingAdmin(admin.ModelAdmin): inlines = [ThingTranslationInline] list_display = ['__unicode__', 'code'] search_fields = ['translations__title', 'code'] class ThingValueAdmin(admin.ModelAdmin): search_fields = ['thingA', 'thingB'] list_display = ['thingA', 'thingB', 'ratio'] admin.site.register(Thing, ThingAdmin) admin.site.register(ThingValue, ThingValueAdmin)
68c0b85ed07154df0bcb9c43228f23871a4003fb
[ "Python", "Text" ]
4
Text
vencax/django-value-ladder
f3a2429c3d5186c3b46305c6b03c228f1b918669
af02588abbb28846cb7fd59b90b2607d75a63b11
refs/heads/master
<file_sep>CREATE DATABASE test; USE test; CREATE TABLE test ( record VARCHAR(50) ); INSERT INTO test (record) VALUES ("SOLERA"); INSERT INTO test (record) VALUES ("CHALLENGE"); <file_sep>#!/bin/bash # # #--=--=--=--=--=--=--=--=--=--=--=--=--=--=--=--=--=--=--=--=--=--=--=--=--=--=--=--=--=--=--=--=--=--# # # iptable.sh # Created: 2016-03-20 # Distributed under terms of the no license. # #--=--=--=--=--=--=--=--=--=--=--=--=--=--=--=--=--=--=--=--=--=--=--=--=--=--=--=--=--=--=--=--=--=--# # Flushing all rules iptables -F iptables -X # Setting default filter policy iptables -P INPUT DROP iptables -P OUTPUT DROP iptables -P FORWARD DROP # Allow unlimited traffic on loopback iptables -A INPUT -i lo -j ACCEPT iptables -A OUTPUT -o lo -j ACCEPT # Allow incoming ssh only iptables -A INPUT -p tcp -s 10.0.0.0/8 --sport 513:65535 --dport 22 -m state --state NEW,ESTABLISHED -j ACCEPT iptables -A OUTPUT -p tcp -s 10.0.0.0/8 --sport 22 --dport 513:65535 -m state --state ESTABLISHED -j ACCEPT iptables -A OUTPUT -p tcp --dport 80 -j ACCEPT # make sure nothing comes or goes out of this box iptables -A INPUT -j DROP iptables -A OUTPUT -j DROP <file_sep>#!/bin/bash # # #--=--=--=--=--=--=--=--=--=--=--=--=--=--=--=--=--=--=--=--=--=--=--=--=--=--=--=--=--=--=--=--=--=--=--=--=--=--=--=--=--# # # Author: <NAME> # Copyright (C) # Distributed under terms of the no license. # ##--=--=--=--=--=--=--=--=--=--=--=--=--=--=--=--=--=--=--=--=--=--=--=--=--=--=--=--=--=--=--=--=--=--=--=--=--=--=--=--=--# JAR="demo.war" folder="/vagrant/files" JAVAOPT=" -Xms64m -Xmx128m" JAVAAGENT='' JAVA="/usr/bin/java" WAIT=30 START_WAIT=3 export APP_VERSION="0.1" export APP_PORT=8080 export DB_NAME=test export DOCKER_DEMO_MYSQL_SERVICE_HOST=localhost # Source function library. INITD=/etc/rc.d/init.d . $INITD/functions # Get network config. . /etc/sysconfig/network # Find the name of the script NAME=`basename $0` if [ ${NAME:0:1} = "S" -o ${NAME:0:1} = "K" ] then NAME=${NAME:3} fi #pid files lockfile="/var/lock/subsys/demo" pidfile="/var/run/demo.pid" script_result=0 getStatus() { status -p $pidfile script_result=$? } getPid() { # get pid PID=`pgrep -x -f ".*$JAR.*$"` echo "$PID" } start() { DEMO=$"Starting ${NAME} service: " if [ -n "$(getPid)" ] then echo "${NAME} is already running (pid: $(getPid))" else echo -n "$DEMO" cd $folder $JAVA $JAVAOPT $JAVAAGENT -jar $JAR >& /dev/null & # wait to make sure it starts properly count=1 until [ $count -gt $START_WAIT ] do echo -n "#" sleep 1 let count=$count+1; done if [ "x$(getPid)" != x ] then success "$DEMO" touch "$lockfile" echo $(getPid) > "$pidfile" echo else failure "$DEMO" echo script_result=1 fi fi } stop(){ XPID=$(getPid) echo -n $"Stopping ${NAME} service: " if [ -e "$lockfile" -o -e "$lockfile1" ] && [ -n "$XPID" ] then kill -15 "$XPID" > /dev/null 2>&1 < /dev/null & wait ret=$? count=0 until [ `ps -p "$XPID" 2> /dev/null | grep -c "$XPID"` = '0' ] || [ $count -gt $WAIT ] do echo -n "#" sleep 1 let count=$count+1; if [ $count -gt $WAIT ] then kill -9 "$XPID" > /dev/null 2>&1 < /dev/null fi done if [ $ret -eq 0 ] then echo_success rm -f "$pidfile" rm -f "$lockfile" else echo_failure script_result=1 fi elif [ -n "$XPID" ] then kill -15 "$XPID" > /dev/null 2>&1 < /dev/null ret=$? count=0 until [ `ps -p "$XPID" 2> /dev/null | grep -c "$XPID"` = '0' ] || [ $count -gt $WAIT ] do echo -n "#" sleep 1 let count=$count+1; if [ $count -gt $WAIT ] then kill -9 "$XPID" > /dev/null 2>&1 < /dev/null fi done if [ $ret -eq 0 ] then echo_success rm -f "$pidfile" rm -f "$lockfile" else echo_failure script_result=1 fi else # not running; per LSB standards this is "ok" echo_success fi echo } forceStop(){ echo -n $"Stopping ${NAME} service: " if [ -e "$lockfile" ] && [ -n "$(getPid)" ] then kill -9 "$(getPid)" > /dev/null 2>&1 < /dev/null ret=$? count=0 WAIT=5 until [ `ps -p "$(getPid)" 2> /dev/null | grep -c "$(getPid)"` = '0' ] || [ $count -gt $WAIT ] do echo -n "#" sleep 1 let count=$count+1; done if [ $ret -eq 0 ] then echo_success rm -f "$pidfile" rm -f "$lockfile" else echo_failure script_result=1 fi else # not running; per LSB standards this is "ok" echo_success fi echo } case "$1" in start) start script_result=$? ;; stop) stop script_result=$? ;; restart) stop start script_result=$? ;; status) getStatus ;; force-stop) forceStop script_result=$? ;; *) echo "Usage:$0{start|stop|restart|status|force-stop}" script_result=1 esac exit $script_result
83bb90070cab296de4361bf0a3057a500096bda3
[ "SQL", "Shell" ]
3
SQL
ay4you/DG-DevopsAssessment
98ec11e7fa2c30abe01b42ec5409e362a0476ccf
8004676ff74602d8dd28f67ea66b192b29501a36
refs/heads/master
<repo_name>thejimbirch/someonedosomething<file_sep>/sites/all/themes/flatty/templates/user-login-block.tpl.php <div class="pull-right well" style="padding: 15px 15px 0px; width: 390px;"> <div class="panel panel-default"> <div class="panel-body"> <?php print $name; // Display username field ?> <?php print $pass; // Display Password field ?> <?php print $submit; // Display submit button ?> <?php print $rendered; // Display hidden elements (required for successful login) ?> </div> </div> </div><file_sep>/sites/all/themes/flatty/layouts/content/content.inc <?php /** * implementation of hook_panels_layouts() */ // Plugin definition $plugin = array( 'title' => t('Content Layout'), 'category' => t('Flatty'), 'icon' => 'content.png', 'theme' => 'panels-content', 'css' => 'content.css', 'regions' => array( 'hero-left' => t('Hero Left'), 'hero-right' => t('Hero Right'), 'centered-six' => t('Centered Six'), 'triple-left' => t('Triple Left'), 'triple-middle' => t('Triple Middle'), 'triple-right' => t('Triple Right'), 'content' => t('Content'), 'sidebar' => t('Sidebar'), 'centered-eight' => t('Centered Eight'), 'background-image' => t('Background Image') ), ); <file_sep>/sites/all/themes/flatty/layouts/content/panels-content.tpl.php <?php if (!empty($content['hero-left']) || !empty($content['hero-right'])): ?> <div id="headerwrap"> <div class="container"> <div class="row"> <div class="col-lg-6"><?php print $content['hero-left']; ?></div> <div class="col-lg-6"><?php print $content['hero-right']; ?></div> </div> </div> </div> <?php endif; ?> <?php if (!empty($content['centered-six'])): ?> <div id="centered-six"> <div class="container"> <div class="row mt centered"> <div class="col-lg-6 col-lg-offset-3"><?php print $content['centered-six']; ?></div> </div> </div> </div> <?php endif; ?> <?php if (!empty($content['triple-left']) || !empty($content['triple-middle']) || !empty($content['triple-right'])): ?> <div id="triple-content" class="full-width"> <div class="container"> <div class="row mt centered"> <div class="col-lg-4"><?php print $content['triple-left']; ?></div> <div class="col-lg-4"><?php print $content['triple-middle']; ?></div> <div class="col-lg-4"><?php print $content['triple-right']; ?></div> </div> </div> </div> <?php endif; ?> <?php if (!empty($content['content']) || !empty($content['sidebar'])): ?> <div id="main-content" class="full-width"> <div class="container"> <div class="row"> <div class="col-sm-8"><?php print $content['content']; ?></div> <div class="col-sm-4"><?php print $content['sidebar']; ?></div> </div> </div> </div> <?php endif; ?> <?php if (!empty($content['centered-eight'])): ?> <div id="centered" class="full-width"> <div class="container"> <div class="row"> <div class="col-sm-8 col-sm-offset-2"><?php print $content['centered']; ?></div> </div> </div> </div> <?php endif; ?> <?php if (!empty($content['background-image'])): ?><?php print $content['background-image']; ?><?php endif; ?> <file_sep>/sites/all/themes/child_theme/templates/panels-pane--custom.tpl.php <div class="panel panel-default"> <?php print render($title_prefix); ?> <?php if ($title): ?> <div class="panel-heading"<?php print $title_attributes; ?>><?php print $title; ?></div> <?php endif; ?> <?php print render($title_suffix); ?> <div class="panel-body"><?php print render($content); ?></div> </div><file_sep>/sites/all/themes/flatty/templates/panels-pane--block--system-user-menu.tpl.php <?php if ($admin_links): ?> <?php print $admin_links; ?> <?php endif; ?> <?php print render($content); ?> <file_sep>/sites/all/themes/flatty/layouts/default/default.inc <?php /** * implementation of hook_panels_layouts() */ // Plugin definition $plugin = array( 'title' => t('Default Panel Layout'), 'category' => t('Flatty'), 'icon' => 'default.png', 'theme' => 'panels-default', 'css' => 'default.css', 'regions' => array( 'logo' => t('Header Logo Area'), 'menu' => t('Header Menu Area'), 'message-area' => t('Message Area'), 'content-area' => t('Content Area'), 'footer' => t('Footer') ), ); <file_sep>/sites/all/themes/flatty/template.php <?php /** * @file * template.php */ function flatty_panels_default_style_render_region($vars) { $output = ''; $output .= implode('', $vars['panes']); return $output; } function flatty_preprocess_image_style(&$vars) { if($vars['style_name'] == 'medium'){ $vars['attributes']['class'][] = 'col-lg-4'; // http://getbootstrap.com/css/#overview-responsive-images } }<file_sep>/sites/all/themes/flatty/layouts/default/panels-default.tpl.php <div class="navbar navbar-default navbar-fixed-top"> <div class="container"> <div class="navbar-header"> <button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-collapse"> <span class="icon-bar"></span> <span class="icon-bar"></span> <span class="icon-bar"></span> </button> <?php if (!empty($content['logo'])): ?> <span class="navbar-brand"><?php print $content['logo']; ?></span> <?php endif; ?> </div> <?php if (!empty($content['menu'])): ?> <div class="navbar-collapse collapse"><?php print $content['menu']; ?></div> <?php endif; ?> </div> </div> <?php if (!empty($content['message-area'])): ?> <div id="message-area" class="full-width"> <div class="container"> <div class="row"> <div class="col-sm-12"><?php print $content['message-area']; ?></div> </div> </div> </div> <?php endif; ?> <?php if (!empty($content['content-area'])): ?><?php print $content['content-area']; ?><?php endif; ?> <?php if (!empty($content['footer'])): ?> <footer class="footer container"> <div class="row"> <div class="col-sm-12"><?php print $content['footer']; ?></div> </div> </footer> <?php endif; ?> <file_sep>/sites/all/themes/flatty/templates/panels-pane--node-updated.tpl.php <div class="date"><?php print render($content); ?></div>
068d26f4a9335ff9e226432b011cf6ffae37d7e7
[ "PHP" ]
9
PHP
thejimbirch/someonedosomething
2bb4e6b56b7387715c14268e316af89e195c71f7
519e2a8db239eed60e97766fa2f0c6950233a67c
refs/heads/master
<repo_name>Alphamikee/InstagramClone<file_sep>/src/userContext.js import React , {createContext , useReducer} from "react"; export const LoginContext = createContext(); const reducer = (state,pair) => ({...state,...pair}); const initialState = { Login: false, email: null, Photos: {}, password: '', userId: null, fullName: null, profilePhoto:'', availabeUsers: null, UID: null, allUsersData: [{ profilePhoto: null, followers: [], following: [] , userId: 'hi' }], target: null, targetUser: { fullName: null, userId: null, followers: null, following: [], photo: null, id: null }, Posts: [{Author : {userId: 'hi'} , Comments : [] , likes : [ ]}], array: [ { userId : 'Alpha' , nums : [1,2,3,4,5] } , { userId: 'Alpha2', nums : [6,7,8,9,0] } ] , Stories: [] } export function ObjectProvider(props){ const [state, update] = useReducer(reducer, initialState) return ( <LoginContext.Provider value={{state,update}}> {props.children} </LoginContext.Provider> )} <file_sep>/src/Posts and Stories/Storeis.js import React, { useContext, useEffect , useState } from 'react'; import Zuck from 'zuck.js'; import Firebase from '../Firebase'; import { LoginContext } from '../userContext'; export default function Storeis() { let { state , update } = useContext(LoginContext); let myStories = state.Stories; let myStoriesArray = [] let CurrentUser = state.allUsersData.filter( user => user.id === Firebase.auth.currentUser.uid)[0]; for( let Story in myStories){ myStoriesArray.push(myStoriesArray[Story]); } let toArray = obj => { let newArray = []; for( let value in obj){ newArray.push(obj[value]); } return newArray; } /* [ { [ { } ] } ] */ let copyStories = [...myStories]; copyStories = copyStories.map( story => story = {...copyStories[copyStories.findIndex( storee => storee.docId === story.docId)] , items: copyStories[copyStories.findIndex( storee => storee.docId === story.docId)].items.map( item => toArray(item) ).flat()}); let myStory = { id: 'ramon', photo: 'https://raw.githubusercontent.com/ramon82/assets/master/zuck.js/users/1.jpg', name : 'Ramon', link : '', lastUpdated : 1575221470504, items: [ [ 'ramon-1',//id 'photo',//type 3,//length 'https://raw.githubusercontent.com/ramon82/assets/master/zuck.js/stories/1.jpg',//src 'https://raw.githubusercontent.com/ramon82/assets/master/zuck.js/stories/1.jpg',//preview '',//link false,//seen false,// linktext 1575221470504,//last update ], [ 'ramon-2', 'video', 0, 'https://raw.githubusercontent.com/ramon82/assets/master/zuck.js/stories/2.mp4', 'https://raw.githubusercontent.com/ramon82/assets/master/zuck.js/stories/2.jpg', '', false, false, 1575221470504, ], [ 'ramon-3', 'photo', 3, 'https://raw.githubusercontent.com/ramon82/assets/master/zuck.js/stories/3.png', 'https://raw.githubusercontent.com/ramon82/assets/master/zuck.js/stories/3.png', 'https://ramon.codes', 'Visit my Portfolio', false, 1575221470504, ], ] } let [storiesElement , setStoriesElement] = useState(null); let [ Stories, setStories] = useState( copyStories.filter( story => story.name === CurrentUser.userId || CurrentUser.following.includes(story.name)).filter( story => Date.now() / 1000 - story.lastUpdated / 1000 < 86400).map( story => Zuck.buildTimelineItem( story.id , story.photo , story.name , story.link , story.lastUpdated , story.items ))); useEffect(() => { let stories = new Zuck(storiesElement, { skin: 'snapgram', // container class avatars: true, // shows user photo instead of last story item preview list: false, // displays a timeline instead of carousel openEffect: true, // enables effect when opening story - may decrease performance cubeEffect: false, // enables the 3d cube effect when sliding story - may decrease performance autoFullScreen: false, // enables fullscreen on mobile browsers backButton: true, // adds a back button to close the story viewer backNative: false, // uses window history to enable back button on browsers/android previousTap: true, // use 1/3 of the screen to navigate to previous item when tap the story localStorage: true, // set true to save "seen" position. Element must have a id to save properly. reactive: true, // set true if you use frameworks like React to control the timeline (see react.sample.html) stories: Stories, }); } , []) const timelineItems = []; Stories.map((story, storyId) => { const storyItems = []; story.items.map(storyItem => { storyItems.push( <li key={storyItem.id} data-id={storyItem.id} data-time={storyItem.time} className={storyItem.seen ? 'seen' : ''} > <a href={storyItem.src} data-type={storyItem.type} data-length={storyItem.length} data-link={storyItem.link} data-linkText={storyItem.linkText} > <img src={storyItem.preview} /> </a> </li>, ); }); let arrayFunc = story.seen ? 'push' : 'unshift'; timelineItems[arrayFunc]( <div className={story.seen ? 'story seen' : 'story'} key={storyId} data-id={storyId} data-last-updated={story.lastUpdated} data-photo={story.photo} > <a className="item-link" href={story.link}> <span className="item-preview"> <img src={story.photo} /> </span> <span className="info" itemProp="author" itemScope="" itemType="http://schema.org/Person"> <strong className="name" itemProp="name"> {story.name} </strong> <span className="time">{story.lastUpdated}</span> </span> </a> <ul className="items">{storyItems}</ul> </div>, ); }) return ( <div> <div ref={node => (storiesElement = node)} id="stories-react" className="storiesWrapper"> {timelineItems} </div> </div> ) }<file_sep>/src/profile Page/ProfilePage.js import React , {useContext} from 'react' import { LoginContext } from '../userContext'; import { Redirect } from 'react-router-dom'; import NavBar from '../Home Page/navBar'; import SingleImage from './SingleImage' import styled from 'styled-components' import Firebase from '../Firebase'; import { useState } from 'react'; const ProfileContainer = styled.div` max-width: 1010px; width: 100%; margin: 20px auto; ` const ProfileDetails = styled.div` display: flex; margin-right: auto; margin-left: auto; ` const ProfileDetailsLeft = styled.div` margin-right: 40px; width: 300px; margin-top: 25px; display: flex; align-items: center; justify-content: center; ` const ProfileDetailsRight = styled.div` display: flex; align-items: end; justify-content: center; flex-direction: column; ` const ProfileImage = styled.img` border-radius: 50%; width: 150px; height: 150px; border: 1px solid #ccc; ` const ProfileDetailsUsername = styled.div` display: flex; align-items: center; margin-top: -30px; justify-content: center; margin-bottom: 15px; ` const EditProfileButton = styled.div` background-color: transparent; border: 1px solid #dbdbdb; color: #262626; border-radius: 4px; outline: none; cursor: pointer; font-weight: 600; padding: 5px 9px; text-transform: capitalize; font-size: 14px; margin-left: 20px; ` const HeadingThreeText = styled.p` font-family: '-apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Helvetica, Arial, sans-serif'; font-size: 28px; line-height: 32px; letter-spacing: normal; fill: #262626; ` const ParagraphText = styled.p` margin-right: 25px; margin-bottom: 10px ` const ProfileDetailsMeta = styled.div` display: flex; justify-content: center; ` const ProfileDetailsName = styled.div` text-align: left; ` const ImagesWrapper = styled.div` margin-top: 50px; display: flex; flex-wrap: wrap; ` let AppWarpper = styled.div` background-color: #fafafa; fill: #fafafa; margin-top: -20px; margin-bottom: 0px; `; export default function ProfilePage(props) { let { state , update } = useContext(LoginContext); let [sillyState,setsillyState] = useState(false); let CurrentUser = state.allUsersData.filter( person => person.id === state.UID)[0]; function EditProfile(){ let elementIndex = state.array.findIndex( object => object.userId === 'Alpha'); console.log(elementIndex); let copyState = [...state.array]; console.log(copyState); copyState[elementIndex] = {...copyState[elementIndex] , userId: 'hisss'} update({array : copyState}) console.log(state.array) } function follow(){ console.log(CurrentUser); update({[state.allUsersData.filter( doc => doc.id === props.id)]: state.allUsersData.filter(doc => doc.id === props.id)[0].followers.push(CurrentUser.userId)}) update({[state.allUsersData.filter( doc => doc.id === Firebase.auth.currentUser.uid)]: state.allUsersData.filter(doc => doc.id === Firebase.auth.currentUser.uid)[0].following.push(props.UserId)}) console.log(CurrentUser); Firebase.db.collection('User').doc(props.id).update({ followers: state.targetUser.followers }) Firebase.db.collection('User').doc(Firebase.auth.currentUser.uid).update({ following: CurrentUser.following })} function unFollow(){ let elementIndex = state.allUsersData.findIndex( doc => doc.id === props.id); let copyUsersData = [...state.allUsersData]; copyUsersData[elementIndex] = {...copyUsersData[elementIndex] , followers : state.allUsersData[elementIndex].followers.filter( follower => follower !== CurrentUser.userId)} let followingIndex = state.allUsersData.findIndex( doc => doc.id === Firebase.auth.currentUser.uid); copyUsersData[followingIndex] = {...copyUsersData[followingIndex] , following : state.allUsersData[followingIndex].following.filter( user => user !== props.UserId)} console.log(copyUsersData); console.log(state.allUsersData); console.log(copyUsersData); Firebase.db.collection('User').doc(props.id).update({ followers: copyUsersData[elementIndex].followers }) Firebase.db.collection('User').doc(Firebase.auth.currentUser.uid).update({ following: copyUsersData[followingIndex].following }) update({allUsersData : copyUsersData}); setsillyState( !setsillyState); } let Posts = state.Posts.filter( Post => Post.Author.userId === props.UserId); Posts.length > 0 ? Posts = Posts.map( post => ( <SingleImage image={post} key={post.id} /> )) : Posts = <div>{console.log(state.Posts.filter( Post => Post.Author.userId === props.UserId))}</div> return ( state.allUsersData.length > 2 && state.Login === true ? [ <NavBar /> , <AppWarpper> <ProfileContainer> <ProfileDetails> <ProfileDetailsLeft> <ProfileImage src={props.img} /> </ProfileDetailsLeft> {console.log(props)} {console.log(state.Posts)} <ProfileDetailsRight> <ProfileDetailsUsername> <HeadingThreeText> {props.UserId} </HeadingThreeText> { Firebase.auth.currentUser.uid === props.id ? <EditProfileButton onClick={EditProfile}>Edit Profile</EditProfileButton> : CurrentUser.following.includes( props.UserId) === false ? <EditProfileButton onClick={follow}> follow </EditProfileButton>: <EditProfileButton onClick = {unFollow}> unFollow </EditProfileButton> } </ProfileDetailsUsername> <ProfileDetailsMeta> <ParagraphText> <strong>{Posts.length}</strong> posts </ParagraphText> <ParagraphText> {console.log(props.followers)} <strong>{props.followers.length}</strong> followers </ParagraphText> <ParagraphText> <strong>{props.following.length}</strong> follwings </ParagraphText> </ProfileDetailsMeta> <ProfileDetailsName> <ParagraphText> {props.fullName} </ParagraphText> </ProfileDetailsName> </ProfileDetailsRight> </ProfileDetails> {console.log(state.Posts.filter( Post => Post.Author.userId === props.UserId))} <ImagesWrapper> {Posts} </ImagesWrapper> </ProfileContainer> </AppWarpper> ] : <Redirect to='/' /> ) } <file_sep>/src/Home Page/navBar.js import React , {useContext , useState}from "react"; import './searchResults.css'; import {LoginContext} from '../userContext'; import Autosuggest from 'react-autosuggest'; import styled from 'styled-components'; import SearchResults from "./searchResults"; import { Link } from "react-router-dom"; import { ReactComponent as Explore } from './explore.svg'; import { ReactComponent as Avatar } from './avatar.svg'; import { ReactComponent as Compass } from './compass.svg'; import { ReactComponent as HomeIcon} from './icons8-home (1).svg'; const Nav = styled.div` background-color: #fff; border-bottom: 1px outset rgba(0,0,0,.0975); box-shadow: 0 2px 2px -2px gray; ` const NavHeader = styled.div` max-width: 1010px; max-height: 55px; padding-bottom: 40px; padding: 26px 20px; width: 100%; display: flex; align-items: center; margin: 0 auto; ` const NavLeft = styled.div` width: 33.333%; text-align: left; ` const NavCenter = styled.div` width: 33.333%; text-align: center; ` const NavRight = styled.div` width: 33.333%; text-align: right; svg { margin-right: 20px; } ` function NavBar(){ let {state,update} = useContext(LoginContext); let [value,setValue] = useState(''); let [suggestions,setSuggestions] = useState(''); let allList = state.allUsersData; const getSuggestions = value => { const inputValue = value.trim().toLowerCase(); const inputLength = inputValue.length; return inputLength === 0 ? [] : allList.filter( person => person.userId.toLowerCase().slice( 0 , inputLength) === inputValue) } const getSuggestionValue = suggestion => suggestion.name; const renderSuggestion = suggestion => ( <SearchResults userId = {suggestion.userId} img ={suggestion.profilePhoto} followers={suggestion.followers} following={suggestion.following} fullName={suggestion.fullName} id={suggestion.id} key={suggestion.id}/> ) let onSuggestionsFetchRequested = ({value}) => { setSuggestions(getSuggestions(value)); } const inputProps = { placeholder: 'Type a UserId', value, onChange: e => setValue(e.target.value) }; let onSuggestionsClearRequested = () => { setSuggestions([]); } return ( <Nav> <NavHeader> <NavLeft>NotInstagram</NavLeft> <NavCenter> <Autosuggest suggestions ={suggestions} onSuggestionsFetchRequested ={onSuggestionsFetchRequested} onSuggestionsClearRequested ={onSuggestionsClearRequested} getSuggestionValue={getSuggestionValue} renderSuggestion={renderSuggestion} inputProps={inputProps} /> </NavCenter> <NavRight> <Compass /> <Explore /> <Link to='/profilePage'> <Avatar /> </Link> <Link to='/' > <HomeIcon /> </Link> </NavRight> </NavHeader> </Nav> )} //<a href="https://icons8.com/icon/132/search">Search icon by Icons8</a> export default NavBar;<file_sep>/src/Home Page/searchResults.js import React , {useContext , useState} from 'react' import { Link } from 'react-router-dom'; import './searchResults'; import {LoginContext} from '../userContext'; export default function SearchResults(props) { let {state,update} = useContext(LoginContext); function createPage(){ update({target: props.userId, targetUser: { fullName: props.fullName, userId: props.userId, followers: props.followers, following: props.following, photo: props.img, id: props.id } }) } return ( <div className='searchResult' onClick={createPage}> <img className='searchPhoto' src={props.img}/> <div className='searchUserId'><Link to={props.userId}>{props.userId}</Link></div> </div> ) } <file_sep>/src/Home Page/Home.js import React , {useContext , useState , useEffect} from 'react'; import Firebase from "../Firebase"; import {LoginContext} from '../userContext' import { Redirect } from 'react-router-dom'; import NavBar from "./navBar"; import MainContents from "./MainContents"; function Home(props){ let {state,update} = useContext(LoginContext); let [allowRenderStories , setAllowRenderStories] = useState(false); let [allowRenderUsers , setAllowRenderUsers] = useState(false); useEffect( () => { Firebase.fetchAllDate().then( data => update({ allUsersData : data.map( data => data[0] = {...data[0] , id: data[1]})})).then(() => setAllowRenderUsers(true)); Firebase.fetchAllPosts().then(data =>{ update({Posts: data.map( data => data[0] = {...data[0] , id: data[1]})}) } ) Firebase.fetchAllStories().then( data => update({Stories: data.map( data => data[0] = {...data[0] , docId : data[1]})}) ).then( setAllowRenderStories(true)) } , []) return ( state.Login ? allowRenderStories & allowRenderUsers ? <div> <NavBar /> <MainContents /> </div> : <div className='loader'></div> : <Redirect to={'/Login' } /> ); } export default Home;<file_sep>/README.md Instagram clone with followers , following , profilePage , posts , stories and without the chat app <file_sep>/src/profile Page/SingleImage.js import React, { useContext } from 'react'; import styled from 'styled-components'; import { ReactComponent as Comment } from './comment.svg'; import { ReactComponent as Heart } from './heart.svg'; import {ReactComponent as Play } from './play.svg' import { LoginContext } from '../userContext'; import Firebase from '../Firebase'; const ImgContainer = styled.div` position: relative; flex-basis: 100%; flex-basis: calc(33.333% - 20px); margin: 10px; cursor: pointer; transition: 0.5s all ease-in; `; const ImgIcons = styled.div` display: flex; align-items: center; justify-content: center; color: #ffffff; margin-right: 20px; svg { margin-right: 10px; } `; const ImgMeta = styled.div` display: none; align-items: center; justify-content: center; position: absolute; background-color: rgba(0, 0, 0, 0.5); top: 0; right: 0; bottom: 0; left: 0; ${ImgContainer}:hover & { display: flex !important; } `; const Img = styled.img` cursor: pointer; width: 100%; `; function Image (props) { const item = props.image let {state,update} = useContext(LoginContext); let CurrentUser = state.allUsersData.filter(user => user.id === Firebase.auth.currentUser.uid)[0]; function like(){ let copyData = [...state.Posts]; let targetPost = copyData.filter( post => post.id === item.id)[0]; let targetIndex = copyData.findIndex( post => post.id === item.id); item.likes.includes(CurrentUser.userId) ? copyData[targetIndex] = {...copyData[targetIndex] , likes: copyData[targetIndex].likes.filter(user => user !== CurrentUser.userId)} : targetPost.likes.push(CurrentUser.userId); Firebase.db.collection("Posts").doc(item.id).update({ likes: copyData[targetIndex].likes }) update({Posts: copyData}); } return ( <ImgContainer> <Img src={item.image} /> <ImgMeta> <ImgIcons>{item.isVideo ? <Play /> : <image src={require('./heart.svg')} onClick={like} style={{fill: ! item.likes.includes(CurrentUser.userId) ? 'white' : 'red'}}> <Heart /> </image> } {item.likes.length}</ImgIcons> <ImgIcons> <Comment />{item.Comments.length}</ImgIcons> </ImgMeta> </ImgContainer> ) } export default Image; <file_sep>/src/App.js import React, {useEffect , useState , useContext, Fragment} from 'react'; import { SignUp } from './authentication/SignUp' import Home from "./Home Page/Home"; import Firebase from './Firebase' import {LoginContext, ObjectProvider} from './userContext'; import ProfilePage from './profile Page/ProfilePage'; import { BrowserRouter as Router, Route, Link, Switch , Redirect } from 'react-router-dom' import Login from "./authentication/Login"; function App(){ let [firebaseInitialized, setFirebaseInitialized] = useState(false); let {state , update} = useContext(LoginContext); useEffect(() => { Firebase.isInitialized().then(val => setFirebaseInitialized(val)); } , []); let CurrentUser = state.allUsersData.filter( person => person.id === state.UID)[0]; return Firebase.isInitialized() !== false ? ( <Router> <Switch> <Route exact component={Login} path={'/Login'}/> <Route exact component={SignUp} path={'/SignUp'}/> <Route exact component={Home} path={'/'}/> <Route exact component={() => <ProfilePage posts={state.Posts.filter( post => post.Author === CurrentUser.userId)} followers={CurrentUser.followers} following={CurrentUser.following} fullName ={CurrentUser.fullName} img={CurrentUser.profilePhoto} UserId={CurrentUser.userId } id={CurrentUser.id} />} path={'/ProfilePage'} /> <Route exact component={() => <ProfilePage posts={[]} followers={state.targetUser.followers} following={state.targetUser.following} fullName ={state.targetUser.fullName} img={state.targetUser.photo} UserId={state.targetUser.userId } id={state.targetUser.id} /> } path={`/${state.target}`} /> </Switch> </Router> ) : <div id={'loader'}><h1>loadeing...</h1></div>; } // posts,followers,following,fullName export default App;<file_sep>/src/Home Page/PopUpContent.js import React, { useContext, useState } from 'react'; import {Tab , Tabs , TabList , TabPanel} from 'react-tabs'; import styled from 'styled-components'; import {LoginContext} from '../userContext'; import Firebase from '../Firebase'; let Div = styled.div` width: 500px; height: 300px; background-color: white; color: black; display: grid; grid-template-rows: 1.5fr 12fr; `; let StyledTabs = styled.div` display: grid; grid-template-columns: 1fr 1fr; color: white; text-align: center; background-color: #D9AFD9; background-image: linear-gradient(90deg, #D9AFD9 0%, #97D9E1 100%); & > { &: focus { outline: none; } } `; let PopContent = styled.div` display: block; text-align: center; color: black; border: whitesmoke 1px outset; margin-top: -10px; padding-top: 20px; `; let Input = styled.input` border: none; background-color: white; height: 25px; border-left: 3px aqua solid; border-bottom: 1px gray solid; margin: auto; font-size: 20px; &: focus { outline: none; } `; const FileStyling = { width:' 0.1px', height:' 0.1px', opacity: '0', overflow: "visible" /*Alpha*/, position: 'absolute', Zindex: '-1' } const Label = styled.label` display: inline-block; border: none; color: gray; background-color: white; height: 25px; width: 123px; border-bottom: 1px gray solid; margin: auto; margin-top: 40px; font-size: 20px; &: focus { outline: none; color: white; } `; let PostButton = styled.button` display: inline-block; background-color: deepskyblue; margin-left: 40px; margin-top: auto; border: none; color: white; width: 120px; height: 35px; &: focus { outline: none; } &: hover { //background-color: #1E90FF; background: rgb(30,227,255); background: linear-gradient(90deg, deepskyblue 0%, #1E90FF) 91%); }; `; let FileTypeLabel = styled.label` display: inline-block; margin: 6px;`; export default function PopUpContent({close}) { let timeStamp = require('time-stamp'); let [content , setContent] = useState(''); let [image , setImage] = useState(''); let { state, update} = useContext(LoginContext); let [fileType , setFileType] = useState(''); let Url; let StoriesUrl; let CurrentUser = state.allUsersData.filter( user => user.id === Firebase.auth.currentUser.uid)[0]; function post() { Firebase.promisedUploadData(image).then(data => { Firebase.downloadData(data.ref.name).then(url => (url)); Firebase.downloadData(data.ref.name).then(url => Url = url).then(() => { let doc = Firebase.db.collection('Posts').doc(); doc.set({ Author : { image: CurrentUser.profilePhoto , userId: state.allUsersData.filter( doc => doc.id === Firebase.auth.currentUser.uid)[0].userId } , Comments: [] , Content: content , date : timeStamp.utc('YYYY/MM/DD:HH:mm:ss') , likes: [] , image: Url }).then( () => { let copyData = [...state.Posts]; copyData.push({ Author : { image: CurrentUser.profilePhoto , userId: state.allUsersData.filter( doc => doc.id === Firebase.auth.currentUser.uid)[0].userId } , Comments: [] , Content: content , date : timeStamp.utc('YYYY/MM/DD:HH:mm:ss') , likes: [] , image: Url, id: doc.id }); update({Posts: copyData}); })})}); } function Story(){ let Array = state.Stories.filter( story => story.name === CurrentUser.userId && Date.now() / 1000 - story.lastUpdated / 1000 < 86400); Firebase.promisedUploadData(image).then(data => { Firebase.downloadData(data.ref.name).then(url => StoriesUrl = url).then(() => { Array.length > 0 ? (() => { Array[0].items.push( {[Firebase.db.collection('Stories').doc().id] : [Firebase.db.collection('Stories').doc().id , fileType , 3 , StoriesUrl , CurrentUser.profilePhoto , '' , false , false , Date.now()]}) Firebase.db.collection('Stories').doc(Array[0].docId).update({ items: Array[0].items }).then( () => { Firebase.fetchAllStories().then( data => update({Stories: data.map( data => data[0] = {...data[0] , docId : data[1]})}) ) }) })(): Firebase.db.collection('Stories').doc().set({ id: CurrentUser.userId , lastUpdated: Date.now() , link: '' , name : CurrentUser.userId , photo : CurrentUser.profilePhoto , items: [ {FirstStory : [Firebase.db.collection('Stories').doc().id , fileType , 3 , StoriesUrl , StoriesUrl , '' , false , false , Date.now()]} ] }).then(() => { Firebase.fetchAllStories().then( data => update({Stories: data.map( data => data[0] = {...data[0] , docId : data[1]})}) ) }).then(() => { alert('done'); }) })}) } return ( <Tabs> <Div> <TabList> <StyledTabs> <Tab>Post</Tab> <Tab>Story</Tab> </StyledTabs> </TabList> <PopContent> <TabPanel> <Input placeholder={'Post\'s description'} onChange={ e => setContent(e.target.value)} value={content} /> <br /> <input type={'file'} required style={FileStyling} name={'file'} id={'file'} onChange={ e => e.target.files[0] != undefined ? setImage(e.target.files[0]) : console.log()}/> <Label for={'file'} > { image.name !== undefined ? image.name : 'Post photo'}</Label> <PostButton onClick={post}>Post</PostButton> </TabPanel> <TabPanel> <input type={'file'} required style={FileStyling} name={'file'} id={'file'} onChange={ e => e.target.files[0] != undefined ? setImage(e.target.files[0]) : console.log()}/> <Label for={'file'} > { image.name !== undefined ? image.name : 'Post photo'}</Label> <input type = 'radio' id = 'photo' name = 'fileType' value = 'photo' onClick = { () => setFileType('photo')}/><FileTypeLabel for = 'photo'>photo</FileTypeLabel> <input type = 'radio' id = 'video' name = 'fileType' value = 'video' onClick = { () => setFileType('video')}/><FileTypeLabel for = 'video'>video</FileTypeLabel> <PostButton onClick={Story}>Story</PostButton> </TabPanel> </PopContent> </Div> </Tabs> ) } <file_sep>/src/Posts and Stories/ViewPosts.js import React , {useContext, useState} from 'react' import { Link } from 'react-router-dom'; import styled from 'styled-components' import Firebase from '../Firebase'; import { LoginContext } from '../userContext'; let Container = styled.div` width: 880px; height: 600px; margin: 14px; margin-left: auto; margin-right: auto; display: grid; grid-template-columns: 1.6fr 1fr; background-color: white; border: 1px outset whitesmoke; `; let Image = styled.img` height: 598px; width: 544px; `; let CommentsSection = styled.div` display: grid; border-left: whitesmoke 0.1px outset; grid-template-rows: 1fr 5.2fr 0.6fr 0.23943fr 0.28169014084fr 0.70422535211fr; `; let Bio = styled.div` width: 100%; height: 100%; display: grid; grid-template-columns: 1fr 1.5fr 1.5fr; border-bottom: whitesmoke 1px solid; `; let BioImage = styled.img` display: inline-block; width: 32px; height: 32px; border-radius: 50%; margin: auto; margin-left: auto; margin-right: 15px; `; let CommentContainer = styled.div` width: 380px; height: 70px; border: none; border-bottom: whitesmoke 1px solid; display: grid; grid-template-columns: 1fr 3fr; `; let AnotherCommentImage = styled.img` width: 32px; height: 32px; border-radius: 50%; margin: auto ; `; let Icon = styled.img` height: 24px; width: 24px; margin: auto; `; let IconContainer = styled.div` width: 100%; height: 100%; border-bottom: whitesmoke 1px solid; border-top: whitesmoke 1px solid; padding-top: 6px; padding-left: 12px; display: grid; grid-template-columns: 1fr 1fr 1fr 4fr; `; let Input = styled.input` border: none; background-color: white; color: black; display: inline-block; & :focus{ outline: none; } `; let I = styled.i` margin: auto; width: 100%; margin-right: auto; margin-left: 30px; margin-top: 7px; `; const Button = styled.button` border: none; font-size: 12px; display: inline-block; background-color: white; &:focus{ outline: none; } border-left: 1px whitesmoke solid; border-top: 1px whitesmoke solid; `; let InputsContainer = styled.div` max-width: 87%; display: grid; grid-template-columns: 4fr 1fr; `; function Comments(props) { return ( <CommentContainer> <AnotherCommentImage src={props.img}/> <p style={{margin: 'auto' , marginRight: 'auto' , marginLeft: '3px'}}><strong>{props.Author}</strong> {props.Content}</p> </CommentContainer> ) } export default function ViewPosts(props) { let { state , update } = useContext(LoginContext); let CurrentUser = state.allUsersData.filter( user => user.id === Firebase.auth.currentUser.uid)[0]; let [ Comment , setComment ] = useState(''); function like(){ let copyData = [...state.Posts]; let targetPost = copyData.filter( post => post.id === props.id)[0]; let targetIndex = copyData.findIndex( post => post.id === props.id); props.likes.includes(CurrentUser.userId) ? copyData[targetIndex] = {...copyData[targetIndex] , likes: copyData[targetIndex].likes.filter(user => user !== CurrentUser.userId)} : targetPost.likes.push(CurrentUser.userId); Firebase.db.collection("Posts").doc(props.id).update({ likes: copyData[targetIndex].likes }) update({Posts: copyData}); } function comment(){ let copyData = [...state.Posts]; let targetPost = copyData.filter( post => post.id === props.id)[0]; targetPost.Comments.push({Content: Comment , Author: CurrentUser.userId , likes: [] , image: props.launcher.img}); setComment(''); Firebase.db.collection('Posts').doc(props.id).update({ Comments: targetPost.Comments }) update({Posts: copyData}); } function createPage(){ let targetUser = state.allUsersData.filter(user => user.userId === props.launcher.userId)[0]; update({target: props.launcher.userId, targetUser: { fullName: targetUser.fullName, userId: targetUser.userId, followers: targetUser.followers, following: targetUser.following, photo: props.launcher.img, id: targetUser.id } }) } function follow(){ let targetUser = state.allUsersData.filter(user => user.userId === props.launcher.userId)[0]; update({[state.allUsersData.filter( doc => doc.userId === props.launcher.userId)]: state.allUsersData.filter(doc => doc.userId === props.launcher.userId)[0].followers.push(CurrentUser.userId)}) update({[state.allUsersData.filter( doc => doc.id === Firebase.auth.currentUser.uid)]: state.allUsersData.filter(doc => doc.id === Firebase.auth.currentUser.uid)[0].following.push(props.launcher.userId)}) Firebase.db.collection('User').doc(targetUser.id).update({ followers: targetUser.followers }) Firebase.db.collection('User').doc(Firebase.auth.currentUser.uid).update({ following: CurrentUser.following })} function unFollow(){ let elementIndex = state.allUsersData.findIndex( doc => doc.userId === props.launcher.userId); let copyUsersData = [...state.allUsersData]; copyUsersData[elementIndex] = {...copyUsersData[elementIndex] , followers : state.allUsersData[elementIndex].followers.filter( follower => follower !== CurrentUser.userId)} let followingIndex = state.allUsersData.findIndex( doc => doc.id === Firebase.auth.currentUser.uid); copyUsersData[followingIndex] = {...copyUsersData[followingIndex] , following : state.allUsersData[followingIndex].following.filter( user => user !== props.launcher.userId)} Firebase.db.collection('User').doc(state.allUsersData.filter( user => user.userId === props.launcher.userId)[0].id).update({ followers: copyUsersData[elementIndex].followers }) Firebase.db.collection('User').doc(Firebase.auth.currentUser.uid).update({ following: copyUsersData[followingIndex].following }) update({allUsersData : copyUsersData}); } console.log(props.Comments); return ( <Container> <Image src={props.img}/> <CommentsSection > <Bio> <BioImage src={props.launcher.img}/> <Link onClick={createPage} to={props.launcher.userId} style={{margin: 'auto' , marginRight: 'auto' , marginLeft: '1px'}} ><strong>{props.launcher.userId}</strong></Link> <strong style={{margin: 'auto' , marginRight: '100px' , marginLeft: '1px'}} onClick={CurrentUser.following.includes(props.launcher.userId) ? unFollow : follow}>{CurrentUser.following.includes(props.launcher.userId) ? 'unfollow' : 'follow'}{console.log(CurrentUser.following.includes(props.launcher.userId))}</strong> </Bio> <div style={{width: '90%' , height: '100%'}}> { props.Comments.length > 0 ? props.Comments.map( Comment => <Comments img = {Comment.image} Author = {Comment.Author} Content = {Comment.Content} />) : <div></div>} </div> <IconContainer> <Icon src={require('./iconmonstr-heart-thin.svg')} onClick={like} style={{filter: props.likes.includes(CurrentUser.userId) ? 'invert(15%) sepia(90%) saturate(7438%) hue-rotate(358deg) brightness(103%) contrast(107%)' : 'none'}} /> <Icon src={require('./Chat.svg')} /> <Icon src={require('./paperPlane.svg')} /> <Icon src={require('./Save.svg')} /> </IconContainer> <I >{props.likes.length > 0 ? `${props.likes.length} likes` : 'No likes yet'}</I> <I >{props.date}</I> <InputsContainer> <Input placeholder='Write a Comment' onChange={ e => setComment(e.target.value)} value = {Comment}/> <Button style={{color : Comment.length > 0 ? 'blue' : 'lightblue'}} onClick={ Comment.length > 1 ? comment : () => alert('Please Write a Comment first')}>Post</Button> </InputsContainer> </CommentsSection> </Container> ) } <file_sep>/src/Posts and Stories/Posts.js import React , {useState , useContext} from 'react'; import {LoginContext} from '../userContext'; import { ReactComponent as PaperPlane } from './paperPlane.svg'; import {ReactComponent as Chat} from './Chat.svg'; import {ReactComponent as Save} from './Save.svg'; import styled from 'styled-components'; import {Link} from 'react-router-dom'; import Firebase from '../Firebase'; import Popup from 'reactjs-popup'; import ViewPosts from './ViewPosts'; const Div = styled.div` background-color: white; display: grid; grid-template-rows: 1fr 10fr 4fr; width: 616px; height: 811px; margin-left: auto ; margin-right: auto; margin-top: 12px; border-radius: 5px 5px 0px 0px; `; const Header = styled.div` display: grid; height: 60px; grid-template-columns: 1fr 6fr 2fr; align-items: left; border-top: 1px solid lightgray; border-right: 1px solid lightgray; border-left: 1px solid lightgray; border-radius: 5px 5px 0px 0px; `; const Image = styled.img` width: 616px; height: 530px; margin-left: auto; margin-right: auto; ` const Footer = styled.div` border-bottom: 1px solid lightgray; border-right: 1px solid lightgray; border-left: 1px solid lightgray; display: grid; grid-template-rows: 4fr 1fr; height: 219px; `; const Status = styled.div` display: inline-block; border-bottom: 1px solid lightgray; color: black; padding-left: 6px; `; const InputContaier = styled.div` width: 614px; border-bottom: 1px; margin-left: 0px; margin-right: 0px; padding: 3px; display: grid; grid-template-columns: 1fr 8fr; `; const Input = styled.input` border: none; background-color: white; color: black; display: inline-block; width: 570px; &:focus { outline: none; }; &::-webkit-input-placeholder { color: gray; } `; const Button = styled.button` border: none; font-size: 12px; margin-left: -20px; display: inline-block; background-color: white; &:focus{ outline: none; } `; const Img = styled.img` width: 32px; height: 32px; margin-left: auto; margin-right: auto; margin-top: 20px; border-radius: 50%; border: 1px solid lightgray; `; const I = styled.i` padding: 4px; display: inline-block; `; const P = styled.p` display: inline-block; color: gray; font-size: 14px; `; let HeartS = styled.span` background-image: url(".glass.png"); background-size: 100%; background-repeat: no-repeat; `; let ImagE = styled.img` //filter: invert(15%) sepia(90%) saturate(7438%) hue-rotate(358deg) brightness(103%) contrast(107%); `; let Btn = styled.button` border: none; background-color: white; display: inline-block; margin: auto; color: lightblue; &:hover { color: blue; } &:focus{ outline: none; } `; export default function Posts(props) { let [Comment,setComment] = useState(''); let {state,update} = useContext(LoginContext); let CurrentUser = state.allUsersData.filter(user => user.id === Firebase.auth.currentUser.uid)[0]; function createPage(){ let targetUser = state.allUsersData.filter(user => user.userId === props.launcher.userId)[0]; update({target: props.launcher.userId, targetUser: { fullName: targetUser.fullName, userId: targetUser.userId, followers: targetUser.followers, following: targetUser.following, photo: props.launcher.img, id: targetUser.id } }) } function like(){ let copyData = [...state.Posts]; let targetPost = copyData.filter( post => post.id === props.id)[0]; let targetIndex = copyData.findIndex( post => post.id === props.id); props.likes.includes(CurrentUser.userId) ? copyData[targetIndex] = {...copyData[targetIndex] , likes: copyData[targetIndex].likes.filter(user => user !== CurrentUser.userId)} : targetPost.likes.push(CurrentUser.userId); Firebase.db.collection("Posts").doc(props.id).update({ likes: copyData[targetIndex].likes }) update({Posts: copyData}); } function comment(){ let copyData = [...state.Posts]; let targetPost = copyData.filter( post => post.id === props.id)[0]; targetPost.Comments.push({Content: Comment , Author: CurrentUser.userId , likes: [] , image: props.launcher.img}); setComment(''); Firebase.db.collection('Posts').doc(props.id).update({ Comments: targetPost.Comments }) update({Posts: copyData}); } return ( <Div> <Header > <Img src={props.launcher.img} alt='launcherPhoto' /> <Link to ={props.launcher.userId} onClick={createPage}> <p style={{marginRight: 'auto' , marginTop: '25px'}}>{props.launcher.userId}</p> </Link> <Popup modal trigger ={<Btn>ViewPost</Btn>}> {close => <ViewPosts close={close} likes={props.likes} Comments={props.Comments} img={props.img} launcher={{img: props.launcher.img , userId: props.launcher.userId}} id={props.id}/>} </Popup> </Header> <Image src={props.img} /> <Footer> <Status> <img src={require('./iconmonstr-heart-thin.svg')} onClick={like} style={{filter: props.likes.includes(CurrentUser.userId) ? 'invert(15%) sepia(90%) saturate(7438%) hue-rotate(358deg) brightness(103%) contrast(107%)' : 'none'}}></img> <I><Chat /></I> <I><PaperPlane /></I> <I style={{ marginLeft: '460px'}}><Save /></I> <p style={{fontFamily: 'Segoe UI, Tahoma, Geneva, Verdana'}}>{props.Content}</p> <p>{props.likes.length} likes</p> <P>view all {props.Comments.length} comments</P> <p style={{fontSize: '14px'}}>{props.date}</p> {props.Comments.length > 2 ? props.Comments.sort( (commentOne,commentTwo) => commentOne.likes + commentTwo.likes).slice(0 , 2).map( comment => <h4>{comment.Author} {comment.Content}</h4>) : console.log()} </Status> <InputContaier> <Input placeholder='Add a comment...' type='text' onChange = { e => setComment(e.target.value)} value={Comment}/> <Button style={{color : Comment.length > 0 ? 'blue' : 'lightblue'}} onClick={comment}> Post </Button> </InputContaier> </Footer> </Div> ) } <file_sep>/src/Firebase.js import firebase from "firebase"; import app from 'firebase/app'; import 'firebase/auth' import 'firebase/firebase-firestore' var firebaseConfig = { apiKey: "<KEY>", authDomain: "inastgram-156cc.firebaseapp.com", databaseURL: "https://inastgram-156cc.firebaseio.com", projectId: "inastgram-156cc", storageBucket: "inastgram-156cc.appspot.com", messagingSenderId: "28493662096", appId: "1:28493662096:web:6bdd09f4c03d3d19255515", measurementId: "G-BT5J8YLPQ2" }; class Firebase{ constructor(){ app.initializeApp(firebaseConfig); this.auth = app.auth(); this.db = app.firestore() this.storage = app.storage(); this.provider = new app.auth.GoogleAuthProvider(); this.uploadData = this.uploadData.bind(this); this.downloadData = this.downloadData.bind(this); this.fetchAllDate = this.fetchAllDate.bind(this); this.promisedUploadData = this.promisedUploadData.bind(this); } login(email,password){ return this.auth.signInWithEmailAndPassword(email,password); } logout(){ return this.auth.signOut().then(() => alert('done')); } downloadData(value) { let storageref = this.storage.ref(); return storageref.child(value).getDownloadURL() .then( url => url) } async signUp(fullName,email,password,userId){ await this.auth.createUserWithEmailAndPassword(email,password); } uploadData(file){ let storageref = this.storage.ref(); let thisRef = storageref.child(file.name); thisRef.put(file).then(snapshot => alert('done!')); } isInitialized(){ return new Promise(resolve => { this.auth.onAuthStateChanged(resolve) }) } isLoggedIn(){ return this.auth.currentUser ? true : false; } fetchAllDate(){ return this.db.collection('User').get() .then( datas => datas.docs.map( doc => [doc.data() , doc.id]).filter( name => name !== undefined)) //let array = snapshot.docs.map(doc => doc.data()).filter( name => name !== undefined); } fetchAllPosts(){ return this.db.collection('Posts').get() .then(datas => datas.docs.map( doc => [doc.data() , doc.id])) } promisedUploadData(file){ return this.storage.ref().child(file.name).put(file) } fetchAllStories(){ return this.db.collection('Stories').get() .then( Stories => Stories.docs.map( doc => [doc.data() , doc.id])) } } export default new Firebase();
31fd67de15966278ebe26f57bc11e6ad820da6b8
[ "JavaScript", "Markdown" ]
13
JavaScript
Alphamikee/InstagramClone
f61d0b2bf079b82b247b267e5c56fe77ce863acf
3e1e5862ca76cd5d0f69cb1a554b3167660ee109
refs/heads/master
<repo_name>honely/new_app-1<file_sep>/application/Admin/model/Qqinfo.php <?php /** * QQ model. * User: Pengfan * Date: 2017/10/17 * Time: 14:20 */ namespace app\Admin\model; use think\Model; class Qqinfo extends Model { /** * table */ protected $table = 'qq'; /** * 获取qq信息 * @param $openid qq唯一标识openid * @return array or null; */ public function get_qq_info($openid){ $data = parent::where(['openId' => $openid])->select(); return $data ? $data : null; } }<file_sep>/application/Home/model/Productsortm.php <?php /** * 商品分类model. * User: Pengfan * Date: 2017/11/3 * Time: 17:15 */ namespace app\home\model; use think\Db; use think\Model; class Productsortm extends Model { /** * table */ protected $table = 'e_product_sort'; /** * 获取分类 * @return array or null; */ public function get_sort_list(){ $data = Db::table('e_product_sort')->select(); return $data ? $data : null; } /** * 获取分类信息 * @param $sort_id 分类id * @return array or null; */ public function get_sort_info($sort_id){ $one_data = Db::table('e_product_sort') ->where(['sort_id' => $sort_id]) ->select(); return $one_data ? $one_data : null; } /** * 修改分类信息 * @param $sort_id 分类id 分类名称 * @return true or false; */ public function update_sort($sort_id,$sort_name){ $upate_data = [ 'sort_name' => $sort_name ]; $res = Db::table('e_product_sort')->where(['sort_id' => $sort_id]) ->update($upate_data); return $res ? true : false; } /** * 添加新的分类 * @param $data 新分类数据 * @return true or false; */ public function add_new_sort($data){ if(isset($data['status']) && $data['status'] == 'on'){ $status = 1; }else{ $status = 3; } if($data['level'] == 1){ $insert_data = [ 'sort_name' => $data['sort_name'], 'status' => $status ]; }elseif($data['level'] == 2){ $insert_data = [ 'parent_id' => $data['parent_id'], 'sort_name' => $data['sort_name'], 'status' => $status ]; } $res = Db::table('e_product_sort')->insert($insert_data); return $res ? true : false; } }<file_sep>/application/Home/Controller/User.php <?php /** * 平台会员controller. * User: Pengfan * Date: 2017/10/26 * Time: 12:02 */ namespace app\Home\controller; use app\Home\model\Admin; use app\Home\model\Couponm; use app\Home\model\Userp; use think\Cache; use think\Controller; use think\Db; use think\Request; class User extends Controller { /** * 平台会员添加 */ public function Add_plat_user(){ $power_str = "tianjiapingtaihuiyuan"; if(!login_over_time()){ $this->redirect('home/login/index'); } if(!_mate_power($power_str)){ $this->success('你没有权限进行该操作!','home/index/index'); } $user_model = new Userp(); if(Request::instance()->isPost()){ $param = Request::instance()->post(); $rand_str = _rand_str(6); $select_res = Db::table('e_user')->where(['user_name' => $param['user_name']])->select(); if($select_res){ return json(['code' => -2,'msg' => '该昵称已被注册!']); } $add_plat_user = $user_model->add_plat_user($param,$rand_str); return $add_plat_user ? json(['code' => -1,'msg' => '添加成功!']) : json(['code' => -1,'msg' => '添加失败!']); } return $this->fetch('add_user'); } /** * 获取会员列表信息 */ public function Get_user_list(){ $power_str = "huiyuanliebiao"; if(!login_over_time()){ $this->redirect('home/login/index'); } if(!_mate_power($power_str)){ $this->success('你没有权限进行该操作!','home/index/index'); } $user_model = new Userp(); $page = input('page'); if(isset($page) && null !== $page){ $current = $page; }else{ $current = 1; } $options = [ 'page'=>$current, 'path'=>url('index') ]; $get_user_list = $user_model->get_user_list($options); $get_coupon_list = Db::table('e_coupon')->where(['status' => 1])->select(); $this->assign('coupon_data',$get_coupon_list); $this->assign('data',$get_user_list['data']); $this->assign('page',$get_user_list['page']); return $this->fetch('index'); } /** * 管理员列表 */ public function Admin_list(){ $power_str = "guanliyuanliebiao"; if(!login_over_time()){ $this->redirect('home/login/index'); } if(!_mate_power($power_str)){ $this->success('您没有权限进行该操作!','home/user/index'); } $user_model = new Admin(); $get_admin_user = $user_model->get_admin_list(); $this->assign('admin_user_data',$get_admin_user); return $this->fetch('admin_list'); } /** * 管理员权限管理 */ public function Power(){ $power_str = "quanxianguanli"; if(!login_over_time()){ $this->redirect('home/login/index'); } if(!_mate_power($power_str)){ $this->success("您没有权限进行该操作!",'home/user/index'); } $uid = input('uid'); $power_list = _add_power(); $power_data = ""; foreach ($power_list as $val){ $power_data[] = explode('*',$val); } $get_user_power = Db::table('e_admin_power')->where(['admin_uid' => $uid])->select(); $user_power_data = ""; foreach ($get_user_power as $key => $val){ $user_power_data[] = $val['power']; } if(isset($get_user_power[0]['admin_uid'])){ $uid = $get_user_power[0]['admin_uid']; } $this->assign('uid',$uid); $this->assign('user_power_data',$user_power_data); $this->assign('power_data',$power_data); return $this->fetch('power_list'); } /** * 管理员添加权限 */ public function add_power(){ $power_str = "tianjiaquanxian"; if(!login_over_time()){ return json(['code' => -2,'url' => 'home/login/index']); } if(!_mate_power($power_str)){ $this->success("您没有权限进行该操作!",'home/user/index'); } $admin_model = new Admin(); $param = Request::instance()->post(); $add_admin_power = $admin_model->add_admin_power($param); return $add_admin_power ? json(['code' => 1,'msg' => '添加成功!']) : json(['code' => -1,'msg' => '添加失败!']); } /** * 修改管理员状态 */ public function Update_admin_status(){ $power_str = "xiugaiguanliyuanzhuangtai"; if(!login_over_time()){ return json(['code' => -2,'url' => 'home/login/index']); } if(!_mate_power($power_str)){ $this->success('您没有权限进行该操作!','home/user/index'); } $uid = input('uid'); $status = input('status'); $admin_model = new Admin(); $update_admin_status = $admin_model->update_admin_status($uid,$status); return $update_admin_status ? json(['code' => 1,'msg' => '修改成功!']) : json(['code' => -1,'msg' => '修改失败!']); } /** * 会员禁言 & 恢复禁言 */ public function Gag_user(){ $power_str = "huiyuanhuihuazhuangtai"; if(!login_over_time()){ $this->redirect('home/login/index'); } if(!_mate_power($power_str)){ $this->success('你没有权限进行该操作!','home/index/index'); } $uid = input('uid'); $status = input('status'); $user_model = new Userp(); $gag_user = $user_model->update_user_status($uid,$status); return $gag_user ? json(['code' => 1,'msg' => '修改成功!']) : json(['code' => -1,'msg' => '修改失败!']); } /** * 向会员发送礼券 */ public function send_coupon(){ $power_str = 'fasongliquan'; if(!login_over_time()){ return json(['code' => -2,'url' => 'home/login/index']); } if(!_mate_power($power_str)){ $this->success('您没有权限进行该操作!','home/user/index'); } $user_model = new Userp(); $uid = Request::instance()->get('uid'); $coupon_id = Request::instance()->get('coupon_id'); $send_coupon = $user_model->send_coupon($coupon_id,$uid); return $send_coupon ? json(['code' => 1,'msg' => '发送成功!']) : json(['code' => -1,'msg' => '发送失败!']); } /** * 发送手机验证码 */ public function send_sms_code(){ header('Content-Type: text/plain; charset=utf-8'); $param = Request::instance()->post(); $mobile = $param['mobile']; $accessKeyId = "<KEY>"; $accessKeySecret = "<KEY>"; $signName = "彭耀久"; $templateCode = "SMS_94605099"; $phoneNumbers = $mobile; $send_class = new \SmsDemo($accessKeyId,$accessKeySecret); $code = _rand_str(4); Cache::set('mobile_code_plat',$code); $send_code = $send_class->sendSms( $signName, $templateCode, $phoneNumbers, ['number' => $code] ); $send_data = json_encode($send_code); if($send_data->Code == 'ok'){ return json(['code' => 1,'msg' => '发送成功!']); }else{ return json(['code' => -1,'msg' => $send_data->Message]); } } /** * 图片上传、视频、音频 */ public function Upload_file(){ $route = '../public/headImg/'; $host = "http://".$_SERVER['SERVER_NAME']; $file_url = upload_img('file',400000,$route,0); return json(['url_str' => $host.'/headImg/'.$file_url]); } }<file_sep>/mysql/ebay.sql /* Navicat MySQL Data Transfer Source Server : localhost Source Server Version : 50553 Source Host : localhost:3306 Source Database : ebay Target Server Type : MYSQL Target Server Version : 50553 File Encoding : 65001 Date: 2017-11-09 15:32:41 */ SET FOREIGN_KEY_CHECKS=0; -- ---------------------------- -- Table structure for e_activity -- ---------------------------- DROP TABLE IF EXISTS `e_activity`; CREATE TABLE `e_activity` ( `id` int(11) unsigned NOT NULL AUTO_INCREMENT, `img_url` varchar(255) NOT NULL COMMENT '活动专题图片', `jump_url` varchar(255) NOT NULL COMMENT '跳转地址', `pro_id` int(11) NOT NULL COMMENT '商品id', `add_time` int(10) NOT NULL COMMENT '添加时间', `status` tinyint(1) NOT NULL COMMENT '状态', PRIMARY KEY (`id`) ) ENGINE=MyISAM DEFAULT CHARSET=utf8 COMMENT='活动专题表'; -- ---------------------------- -- Records of e_activity -- ---------------------------- -- ---------------------------- -- Table structure for e_add_user -- ---------------------------- DROP TABLE IF EXISTS `e_add_user`; CREATE TABLE `e_add_user` ( `id` int(11) unsigned NOT NULL AUTO_INCREMENT, `uid` int(11) NOT NULL COMMENT '会员uid', `add_uid` int(11) NOT NULL COMMENT '被添加的会员uid', `add_time` int(10) NOT NULL COMMENT '添加时间', PRIMARY KEY (`id`) ) ENGINE=MyISAM DEFAULT CHARSET=utf8; -- ---------------------------- -- Records of e_add_user -- ---------------------------- -- ---------------------------- -- Table structure for e_admin_power -- ---------------------------- DROP TABLE IF EXISTS `e_admin_power`; CREATE TABLE `e_admin_power` ( `id` int(11) unsigned NOT NULL AUTO_INCREMENT, `admin_uid` int(11) NOT NULL COMMENT '管理员id', `power` varchar(255) DEFAULT NULL COMMENT '权限', PRIMARY KEY (`id`) ) ENGINE=MyISAM AUTO_INCREMENT=27 DEFAULT CHARSET=utf8 COMMENT='权限表'; -- ---------------------------- -- Records of e_admin_power -- ---------------------------- INSERT INTO `e_admin_power` VALUES ('26', '1', 'deletezuopincomment'); INSERT INTO `e_admin_power` VALUES ('25', '1', 'xiugaizuopin'); INSERT INTO `e_admin_power` VALUES ('24', '1', 'zuopinliebiao'); -- ---------------------------- -- Table structure for e_admin_user -- ---------------------------- DROP TABLE IF EXISTS `e_admin_user`; CREATE TABLE `e_admin_user` ( `id` int(11) unsigned NOT NULL AUTO_INCREMENT, `user_name` varchar(255) NOT NULL COMMENT '管理员名称', `pass_word` varchar(255) NOT NULL COMMENT '密码', `add_time` int(10) NOT NULL COMMENT '添加时间', `status` tinyint(1) NOT NULL COMMENT '状态', PRIMARY KEY (`id`) ) ENGINE=MyISAM AUTO_INCREMENT=2 DEFAULT CHARSET=utf8 COMMENT='后台管理员'; -- ---------------------------- -- Records of e_admin_user -- ---------------------------- INSERT INTO `e_admin_user` VALUES ('1', 'admin', '14e1b600b1fd579f47433b88e8d85291', '0', '1'); -- ---------------------------- -- Table structure for e_article -- ---------------------------- DROP TABLE IF EXISTS `e_article`; CREATE TABLE `e_article` ( `article_id` int(11) unsigned NOT NULL AUTO_INCREMENT, `article_title` varchar(255) NOT NULL COMMENT '文章标题', `nav_id` int(11) NOT NULL COMMENT '分类id', `uid` int(11) NOT NULL COMMENT '会员id', `is_share` tinyint(1) NOT NULL COMMENT '是否被分享', `is_like` tinyint(1) NOT NULL COMMENT '是否被点赞', `see_num` int(11) NOT NULL COMMENT '浏览次数', `add_time` int(10) NOT NULL COMMENT '添加时间', `update_time` int(10) NOT NULL COMMENT '修改时间', `status` tinyint(1) NOT NULL COMMENT '状态', PRIMARY KEY (`article_id`) ) ENGINE=MyISAM AUTO_INCREMENT=11 DEFAULT CHARSET=utf8 COMMENT='作品表'; -- ---------------------------- -- Records of e_article -- ---------------------------- INSERT INTO `e_article` VALUES ('1', '测试文章1', '1', '1', '0', '0', '0', '0', '1509702696', '1'); INSERT INTO `e_article` VALUES ('5', '上传测试1', '1', '1', '0', '0', '0', '1508920150', '1509702092', '1'); INSERT INTO `e_article` VALUES ('6', '测试标题2', '1', '1', '0', '0', '0', '1508989651', '1509702515', '1'); INSERT INTO `e_article` VALUES ('7', 'qwertyt', '1', '1', '0', '0', '0', '1509334727', '0', '1'); INSERT INTO `e_article` VALUES ('8', '给V缝纫工', '1', '1', '0', '0', '0', '1509335173', '1509514373', '1'); INSERT INTO `e_article` VALUES ('9', '文章标题', '3', '4', '0', '0', '0', '1509701379', '0', '1'); INSERT INTO `e_article` VALUES ('10', '测试标题', '3', '4', '0', '0', '0', '1509701621', '0', '1'); -- ---------------------------- -- Table structure for e_article_info -- ---------------------------- DROP TABLE IF EXISTS `e_article_info`; CREATE TABLE `e_article_info` ( `id` int(11) unsigned NOT NULL AUTO_INCREMENT, `article_id` int(11) NOT NULL COMMENT '作品id', `content` varchar(6533) NOT NULL COMMENT '作品内容', `img_url` varchar(255) NOT NULL COMMENT '作品图片', `music_url` varchar(255) NOT NULL COMMENT '音乐地址', `video_url` varchar(255) NOT NULL COMMENT '视频地址', PRIMARY KEY (`id`), KEY `article` (`article_id`) USING BTREE ) ENGINE=MyISAM AUTO_INCREMENT=11 DEFAULT CHARSET=utf8 COMMENT='作品详情表'; -- ---------------------------- -- Records of e_article_info -- ---------------------------- INSERT INTO `e_article_info` VALUES ('1', '1', '<p style=\"text-align: center;\">测试数据<img src=\"http://www.ebay.com/static/javascript/images/face/14.gif\" alt=\"[亲亲]\"></p>', 'http://www.ebay.com/article/59fc3c26c3161.jpg,http://www.ebay.com/article/59fc3c26c3d19.jpg,', '', ''); INSERT INTO `e_article_info` VALUES ('5', '5', '<p style=\"text-align: center;\">测试内容<img src=\"http://www.ebay.com/static/javascript/images/face/47.gif\" alt=\"[心]\"></p>', 'http://www.ebay.com/article/59fc39cb9687d.jpg', '', ''); INSERT INTO `e_article_info` VALUES ('6', '6', '<p style=\"text-align: center;\">这是测试数据<img src=\"http://www.ebay.com/static/javascript/images/face/49.gif\" alt=\"[猪头]\"></p>', 'http://www.ebay.com/article/59fc3b70b8bb5.jpg,', '', ''); INSERT INTO `e_article_info` VALUES ('7', '7', '<p style=\"text-align: center;\">图片上传测试</p>', '', '', ''); INSERT INTO `e_article_info` VALUES ('8', '8', '<p style=\"text-align: center;\"><img src=\"http://www.ebay.com/static/javascript/images/face/13.gif\" alt=\"[偷笑]\">这是内容<img src=\"http://www.ebay.com/static/javascript/images/face/14.gif\" alt=\"[亲亲]\">啊哈哈哈哈<img src=\"http://www.ebay.com/static/javascript/images/face/37.gif\" alt=\"[色]\"></p>', 'http://www.ebay.com/article/59f6a07764c1e.jpg,http://www.ebay.com/article/59f6a077b45a0.jpg,http://www.ebay.com/article/59f6a077bb6ea.jpg,http://www.ebay.com/article/59f6a0785bfb5.jpg,', '', ''); INSERT INTO `e_article_info` VALUES ('9', '9', '<p style=\"text-align: center;\">哈哈哈<img src=\"http://www.ebay.com/static/javascript/images/face/36.gif\" alt=\"[酷]\"></p>', 'www.ebay.com/article/59fc36f65ad7b.jpg,www.ebay.com/article/59fc36f65e044.jpg,www.ebay.com/article/59fc36f660b3d.jpg,', '', ''); INSERT INTO `e_article_info` VALUES ('10', '10', '<p style=\"text-align: center;\"><img src=\"http://www.ebay.com/static/javascript/images/face/41.gif\" alt=\"[悲伤]\"><br></p>', 'www.ebay.com/article/59fc37e677961.jpg,', '', ''); -- ---------------------------- -- Table structure for e_brand -- ---------------------------- DROP TABLE IF EXISTS `e_brand`; CREATE TABLE `e_brand` ( `brand_id` int(11) unsigned NOT NULL AUTO_INCREMENT, `brand_name` varchar(255) NOT NULL COMMENT '品牌名称', `brand_logo` varchar(255) NOT NULL COMMENT '品牌logo', `add_time` int(10) NOT NULL COMMENT '添加时间', `status` tinyint(1) NOT NULL COMMENT '状态', PRIMARY KEY (`brand_id`) ) ENGINE=MyISAM DEFAULT CHARSET=utf8 COMMENT='品牌表'; -- ---------------------------- -- Records of e_brand -- ---------------------------- -- ---------------------------- -- Table structure for e_collection -- ---------------------------- DROP TABLE IF EXISTS `e_collection`; CREATE TABLE `e_collection` ( `id` int(11) unsigned NOT NULL AUTO_INCREMENT, `article_id` int(11) NOT NULL COMMENT '文章id', `uid` int(11) NOT NULL COMMENT '收藏该文章的会员uid', `coll_time` int(10) NOT NULL COMMENT '收藏时间', PRIMARY KEY (`id`) ) ENGINE=MyISAM DEFAULT CHARSET=utf8 COMMENT='文章收藏表'; -- ---------------------------- -- Records of e_collection -- ---------------------------- -- ---------------------------- -- Table structure for e_comment -- ---------------------------- DROP TABLE IF EXISTS `e_comment`; CREATE TABLE `e_comment` ( `id` int(11) unsigned NOT NULL AUTO_INCREMENT, `article_id` int(11) NOT NULL COMMENT '作品id', `uid` int(11) NOT NULL COMMENT '评论会员uid', `comment_text` varchar(255) NOT NULL COMMENT '评论内容', `be_comment_id` int(11) NOT NULL COMMENT '被评论的评论id', `be_commont_uid` int(11) NOT NULL COMMENT '被评论会员uid', `is_be_reply` tinyint(1) NOT NULL COMMENT '是否被评论', `add_time` int(10) NOT NULL COMMENT '评论时间', `status` tinyint(1) NOT NULL COMMENT '状态', PRIMARY KEY (`id`) ) ENGINE=MyISAM AUTO_INCREMENT=2 DEFAULT CHARSET=utf8 COMMENT='文章评论表'; -- ---------------------------- -- Records of e_comment -- ---------------------------- INSERT INTO `e_comment` VALUES ('1', '1', '1', 'reqwrq', '0', '0', '0', '0', '1'); -- ---------------------------- -- Table structure for e_coupon -- ---------------------------- DROP TABLE IF EXISTS `e_coupon`; CREATE TABLE `e_coupon` ( `id` int(11) unsigned NOT NULL AUTO_INCREMENT, `coupon_name` varchar(255) NOT NULL COMMENT '礼券名称', `quota` int(11) NOT NULL COMMENT '礼券金额', `use_rule` int(11) NOT NULL COMMENT '礼券规则', `effective_day` int(11) NOT NULL COMMENT '有效天数', `add_time` int(10) NOT NULL, `status` tinyint(1) NOT NULL COMMENT '状态', PRIMARY KEY (`id`) ) ENGINE=MyISAM AUTO_INCREMENT=4 DEFAULT CHARSET=utf8 COMMENT='礼券表'; -- ---------------------------- -- Records of e_coupon -- ---------------------------- INSERT INTO `e_coupon` VALUES ('1', '新人礼券测试版', '100', '1000', '1', '0', '1'); INSERT INTO `e_coupon` VALUES ('2', '礼券添加测试', '1000', '123456', '1', '1509588592', '1'); INSERT INTO `e_coupon` VALUES ('3', '新的礼券', '100', '200', '7', '1509592466', '1'); -- ---------------------------- -- Table structure for e_follow -- ---------------------------- DROP TABLE IF EXISTS `e_follow`; CREATE TABLE `e_follow` ( `id` int(11) unsigned NOT NULL AUTO_INCREMENT, `uid` int(11) NOT NULL COMMENT '会员uid', `be_uid` int(11) NOT NULL COMMENT '被关注的会员uid', `foll_time` int(10) NOT NULL COMMENT '关注时间', PRIMARY KEY (`id`) ) ENGINE=MyISAM DEFAULT CHARSET=utf8 COMMENT='会员关注表'; -- ---------------------------- -- Records of e_follow -- ---------------------------- -- ---------------------------- -- Table structure for e_guess_like -- ---------------------------- DROP TABLE IF EXISTS `e_guess_like`; CREATE TABLE `e_guess_like` ( `id` int(11) unsigned NOT NULL AUTO_INCREMENT, `article_id` int(11) NOT NULL COMMENT '作品id', `pro_id` int(11) NOT NULL COMMENT '商品id', `add_time` int(11) NOT NULL COMMENT '浏览时间', `uid` int(11) NOT NULL COMMENT '会员uid', PRIMARY KEY (`id`) ) ENGINE=MyISAM DEFAULT CHARSET=utf8 COMMENT='浏览记录'; -- ---------------------------- -- Records of e_guess_like -- ---------------------------- -- ---------------------------- -- Table structure for e_like -- ---------------------------- DROP TABLE IF EXISTS `e_like`; CREATE TABLE `e_like` ( `id` int(11) unsigned NOT NULL AUTO_INCREMENT, `article_id` int(11) NOT NULL COMMENT '文章id', `uid` int(11) NOT NULL COMMENT '点赞会员uid', `like_time` int(10) NOT NULL COMMENT '点赞时间', PRIMARY KEY (`id`) ) ENGINE=MyISAM AUTO_INCREMENT=3 DEFAULT CHARSET=utf8 COMMENT='文章点赞表'; -- ---------------------------- -- Records of e_like -- ---------------------------- INSERT INTO `e_like` VALUES ('1', '1', '0', '0'); INSERT INTO `e_like` VALUES ('2', '1', '0', '0'); -- ---------------------------- -- Table structure for e_micro_blog -- ---------------------------- DROP TABLE IF EXISTS `e_micro_blog`; CREATE TABLE `e_micro_blog` ( `id` int(11) unsigned NOT NULL AUTO_INCREMENT, `uid` int(11) NOT NULL COMMENT '微博注册唯一uid', `openId` int(11) NOT NULL COMMENT '微博参数openid', `access_token` varchar(255) NOT NULL COMMENT '授权', `regdate_ip` varchar(255) NOT NULL COMMENT '注册ip', `source` varchar(255) NOT NULL COMMENT '来源', `add_time` int(10) NOT NULL COMMENT '添加时间', `status` tinyint(1) NOT NULL COMMENT '状态', PRIMARY KEY (`id`) ) ENGINE=MyISAM DEFAULT CHARSET=utf8 COMMENT='微博会员表'; -- ---------------------------- -- Records of e_micro_blog -- ---------------------------- -- ---------------------------- -- Table structure for e_nav_banner -- ---------------------------- DROP TABLE IF EXISTS `e_nav_banner`; CREATE TABLE `e_nav_banner` ( `id` int(11) unsigned NOT NULL AUTO_INCREMENT, `nav_id` int(11) NOT NULL COMMENT '分类导航id', `banner_img` varchar(255) NOT NULL COMMENT 'banner图片地址', `Jump_url` varchar(255) NOT NULL COMMENT '跳转地址', `add_time` int(10) NOT NULL COMMENT '添加时间', `status` tinyint(1) NOT NULL COMMENT '状态', PRIMARY KEY (`id`) ) ENGINE=MyISAM AUTO_INCREMENT=4 DEFAULT CHARSET=utf8 COMMENT='分类导航banner表'; -- ---------------------------- -- Records of e_nav_banner -- ---------------------------- INSERT INTO `e_nav_banner` VALUES ('1', '1', 'http://www.ebay.com/nav_banner/59fbe0f390ff4.jpg', 'www.baidu.cn', '0', '1'); INSERT INTO `e_nav_banner` VALUES ('2', '1', 'http://www.ebay.com/nav_banner/59fbe68c3e76c.jpg', 'www.baidu.com', '1509680781', '1'); INSERT INTO `e_nav_banner` VALUES ('3', '3', 'http://www.ebay.com/nav_banner/59fc36acba7e9.jpg', 'www', '1509701293', '1'); -- ---------------------------- -- Table structure for e_nav_list -- ---------------------------- DROP TABLE IF EXISTS `e_nav_list`; CREATE TABLE `e_nav_list` ( `nav_id` int(11) unsigned NOT NULL AUTO_INCREMENT COMMENT '分类id', `nav_name` varchar(255) NOT NULL COMMENT '分类名称', `add_time` int(10) NOT NULL COMMENT '添加时间', `status` tinyint(1) NOT NULL COMMENT '状态', PRIMARY KEY (`nav_id`) ) ENGINE=MyISAM AUTO_INCREMENT=4 DEFAULT CHARSET=utf8 COMMENT='分类导航表'; -- ---------------------------- -- Records of e_nav_list -- ---------------------------- INSERT INTO `e_nav_list` VALUES ('1', '测试分类_one', '0', '1'); INSERT INTO `e_nav_list` VALUES ('2', '添加测试', '1509675247', '1'); INSERT INTO `e_nav_list` VALUES ('3', '女神', '1509701261', '1'); -- ---------------------------- -- Table structure for e_news -- ---------------------------- DROP TABLE IF EXISTS `e_news`; CREATE TABLE `e_news` ( `id` int(11) unsigned NOT NULL AUTO_INCREMENT, `uid` int(11) NOT NULL COMMENT '会员id', `news` varchar(255) NOT NULL COMMENT '消息', `send_uid` int(11) NOT NULL COMMENT '发送信息uid', `send_time` int(10) NOT NULL COMMENT '发送时间', PRIMARY KEY (`id`) ) ENGINE=MyISAM DEFAULT CHARSET=utf8 COMMENT='消息表'; -- ---------------------------- -- Records of e_news -- ---------------------------- -- ---------------------------- -- Table structure for e_order -- ---------------------------- DROP TABLE IF EXISTS `e_order`; CREATE TABLE `e_order` ( `id` int(11) unsigned NOT NULL AUTO_INCREMENT, `order_num` int(11) NOT NULL COMMENT '特订订单id', `product_id` int(11) NOT NULL COMMENT '商品id', `receipt_addr` int(11) NOT NULL COMMENT '收货地址', `uid` int(11) NOT NULL COMMENT '会员id', PRIMARY KEY (`id`) ) ENGINE=MyISAM DEFAULT CHARSET=utf8 COMMENT='订单表'; -- ---------------------------- -- Records of e_order -- ---------------------------- -- ---------------------------- -- Table structure for e_product -- ---------------------------- DROP TABLE IF EXISTS `e_product`; CREATE TABLE `e_product` ( `pro_id` int(11) unsigned NOT NULL AUTO_INCREMENT, `product_name` varchar(255) NOT NULL COMMENT '商品名称', `sort_id` int(11) NOT NULL COMMENT '商品分类', `brand_id` int(11) NOT NULL COMMENT '品牌id', `def_pro_img` varchar(255) NOT NULL COMMENT '商品图片', `def_price` decimal(10,2) NOT NULL COMMENT '价格', `descptions` varchar(255) NOT NULL COMMENT '商品描述', `add_time` int(10) NOT NULL COMMENT '添加时间', `status` tinyint(1) NOT NULL COMMENT '状态', PRIMARY KEY (`pro_id`) ) ENGINE=MyISAM DEFAULT CHARSET=utf8 COMMENT='商品表'; -- ---------------------------- -- Records of e_product -- ---------------------------- -- ---------------------------- -- Table structure for e_product_attr_val -- ---------------------------- DROP TABLE IF EXISTS `e_product_attr_val`; CREATE TABLE `e_product_attr_val` ( `id` int(11) unsigned NOT NULL AUTO_INCREMENT, `product_id` int(11) NOT NULL COMMENT '商品id', `attr_id` int(11) NOT NULL COMMENT '属性id', `attr_value` varchar(255) NOT NULL COMMENT '属性值', PRIMARY KEY (`id`) ) ENGINE=MyISAM DEFAULT CHARSET=utf8 COMMENT='商品属性表'; -- ---------------------------- -- Records of e_product_attr_val -- ---------------------------- -- ---------------------------- -- Table structure for e_product_comment -- ---------------------------- DROP TABLE IF EXISTS `e_product_comment`; CREATE TABLE `e_product_comment` ( `id` int(11) unsigned NOT NULL AUTO_INCREMENT, `product_id` int(11) NOT NULL COMMENT '商品id', `uid` int(11) NOT NULL COMMENT '评论会员uid', `comment_text` varchar(255) NOT NULL COMMENT '评论内容', `be_comment_id` int(11) NOT NULL COMMENT '被评论的评论id', `is_be_reply` tinyint(1) NOT NULL COMMENT '是否被评论', `add_time` int(10) NOT NULL COMMENT '评论时间', `status` tinyint(1) NOT NULL COMMENT '状态', PRIMARY KEY (`id`) ) ENGINE=MyISAM DEFAULT CHARSET=utf8 COMMENT='商品评论表'; -- ---------------------------- -- Records of e_product_comment -- ---------------------------- -- ---------------------------- -- Table structure for e_product_img -- ---------------------------- DROP TABLE IF EXISTS `e_product_img`; CREATE TABLE `e_product_img` ( `id` int(11) unsigned NOT NULL AUTO_INCREMENT, `pro_img` varchar(255) NOT NULL COMMENT '商品图册', `product_id` int(11) NOT NULL COMMENT '商品id', PRIMARY KEY (`id`) ) ENGINE=MyISAM DEFAULT CHARSET=utf8 COMMENT='商品图册表'; -- ---------------------------- -- Records of e_product_img -- ---------------------------- -- ---------------------------- -- Table structure for e_product_sort -- ---------------------------- DROP TABLE IF EXISTS `e_product_sort`; CREATE TABLE `e_product_sort` ( `sort_id` int(11) unsigned NOT NULL AUTO_INCREMENT, `sort_name` varchar(255) NOT NULL COMMENT '商品名称', `parent_id` int(11) NOT NULL COMMENT '根据id判断二级分类', `status` tinyint(1) NOT NULL COMMENT '状态', PRIMARY KEY (`sort_id`) ) ENGINE=MyISAM DEFAULT CHARSET=utf8 COMMENT='商品分类表'; -- ---------------------------- -- Records of e_product_sort -- ---------------------------- -- ---------------------------- -- Table structure for e_pro_collection -- ---------------------------- DROP TABLE IF EXISTS `e_pro_collection`; CREATE TABLE `e_pro_collection` ( `id` int(11) unsigned NOT NULL AUTO_INCREMENT, `pro_id` int(11) NOT NULL COMMENT '商品id', `uid` int(11) NOT NULL COMMENT '会员id', `add_time` int(10) NOT NULL COMMENT '收藏时间', PRIMARY KEY (`id`) ) ENGINE=MyISAM DEFAULT CHARSET=utf8 COMMENT='商品收藏表'; -- ---------------------------- -- Records of e_pro_collection -- ---------------------------- -- ---------------------------- -- Table structure for e_qq -- ---------------------------- DROP TABLE IF EXISTS `e_qq`; CREATE TABLE `e_qq` ( `id` int(11) unsigned NOT NULL AUTO_INCREMENT, `uid` int(11) NOT NULL COMMENT 'qq注册唯一的uid', `openId` varchar(255) NOT NULL COMMENT 'qq参数openId', `access_token` varchar(255) NOT NULL COMMENT '授权', `regdate_ip` varchar(255) NOT NULL COMMENT '注册ip', `source` varchar(255) NOT NULL COMMENT '来源', `add_time` int(10) NOT NULL COMMENT '添加时间', `status` tinyint(1) NOT NULL COMMENT '状态', PRIMARY KEY (`id`) ) ENGINE=MyISAM DEFAULT CHARSET=utf8 COMMENT='qq会员表'; -- ---------------------------- -- Records of e_qq -- ---------------------------- -- ---------------------------- -- Table structure for e_receipt_addr -- ---------------------------- DROP TABLE IF EXISTS `e_receipt_addr`; CREATE TABLE `e_receipt_addr` ( `id` int(11) unsigned NOT NULL AUTO_INCREMENT, `receipt_name` varchar(255) NOT NULL COMMENT '收货人姓名', `province` int(11) NOT NULL COMMENT '省', `city` int(11) NOT NULL COMMENT '市', `area` int(11) NOT NULL COMMENT '区', `detailed_addr` varchar(255) NOT NULL COMMENT '详细地址', `telephone` varchar(255) NOT NULL COMMENT '收货人电话', `email` varchar(255) NOT NULL COMMENT '邮箱', `add_time` int(10) NOT NULL COMMENT '添加时间', `uid` int(11) NOT NULL COMMENT '会员id', `status` tinyint(1) NOT NULL COMMENT '状态', PRIMARY KEY (`id`) ) ENGINE=MyISAM DEFAULT CHARSET=utf8 COMMENT='收货地址'; -- ---------------------------- -- Records of e_receipt_addr -- ---------------------------- -- ---------------------------- -- Table structure for e_share -- ---------------------------- DROP TABLE IF EXISTS `e_share`; CREATE TABLE `e_share` ( `id` int(11) unsigned NOT NULL AUTO_INCREMENT, `article_id` int(11) NOT NULL COMMENT '文章id', `uid` int(11) NOT NULL COMMENT '分享会员uid', `share_time` int(10) NOT NULL COMMENT '分享时间', PRIMARY KEY (`id`) ) ENGINE=MyISAM DEFAULT CHARSET=utf8 COMMENT='文章分享表'; -- ---------------------------- -- Records of e_share -- ---------------------------- -- ---------------------------- -- Table structure for e_shopping_cart -- ---------------------------- DROP TABLE IF EXISTS `e_shopping_cart`; CREATE TABLE `e_shopping_cart` ( `id` int(11) unsigned NOT NULL AUTO_INCREMENT, `uid` int(11) NOT NULL COMMENT '会员uid', `pro_id` int(11) NOT NULL COMMENT '商品id', `redis_pro_key` varchar(255) NOT NULL COMMENT '商品缓存key', `add_time` int(10) NOT NULL COMMENT '添加时间', PRIMARY KEY (`id`) ) ENGINE=MyISAM DEFAULT CHARSET=utf8 COMMENT='购物车表'; -- ---------------------------- -- Records of e_shopping_cart -- ---------------------------- -- ---------------------------- -- Table structure for e_sort_attr -- ---------------------------- DROP TABLE IF EXISTS `e_sort_attr`; CREATE TABLE `e_sort_attr` ( `attr_id` int(11) unsigned NOT NULL AUTO_INCREMENT, `attr_name` varchar(255) NOT NULL COMMENT '属性名称', `type_id` int(11) NOT NULL COMMENT '分类类型id', `status` tinyint(1) NOT NULL, PRIMARY KEY (`attr_id`) ) ENGINE=MyISAM DEFAULT CHARSET=utf8 COMMENT='类型属性表'; -- ---------------------------- -- Records of e_sort_attr -- ---------------------------- -- ---------------------------- -- Table structure for e_sort_type -- ---------------------------- DROP TABLE IF EXISTS `e_sort_type`; CREATE TABLE `e_sort_type` ( `type_id` int(11) unsigned NOT NULL AUTO_INCREMENT, `type_name` varchar(255) NOT NULL COMMENT '属性名称', `sort_id` int(11) NOT NULL COMMENT '商品类型id', `status` tinyint(1) NOT NULL COMMENT '状态', PRIMARY KEY (`type_id`) ) ENGINE=MyISAM DEFAULT CHARSET=utf8 COMMENT='分类类型表'; -- ---------------------------- -- Records of e_sort_type -- ---------------------------- -- ---------------------------- -- Table structure for e_user -- ---------------------------- DROP TABLE IF EXISTS `e_user`; CREATE TABLE `e_user` ( `uid` int(11) unsigned NOT NULL AUTO_INCREMENT COMMENT '会员uid', `user_name` varchar(255) NOT NULL COMMENT '会员账号', `pass_word` varchar(255) NOT NULL COMMENT '密码', `head_img` varchar(255) NOT NULL COMMENT '头像', `mobile` char(11) NOT NULL COMMENT '手机号', `salt_str` char(6) NOT NULL COMMENT '随机字符', `register_ip` varchar(255) NOT NULL COMMENT '注册ip', `integral` int(11) NOT NULL COMMENT '积分', `is_follow` tinyint(1) NOT NULL COMMENT '是否被关注', `is_plat` tinyint(1) unsigned zerofill NOT NULL COMMENT '是否平台注册', `add_time` int(10) NOT NULL COMMENT '注册时间', `status` tinyint(1) NOT NULL COMMENT '状态(1正常,2禁言,3删除,4禁止使用)', PRIMARY KEY (`uid`) ) ENGINE=MyISAM AUTO_INCREMENT=7 DEFAULT CHARSET=utf8 COMMENT='会员基本信息表'; -- ---------------------------- -- Records of e_user -- ---------------------------- INSERT INTO `e_user` VALUES ('1', 'admin', '123456', 'http://www.ebay.com/article/59f6a0785bfb5.jpg', '13474376703', '', '127.0.0.1', '100', '0', '0', '0', '1'); INSERT INTO `e_user` VALUES ('2', '米玛', '1de4d4e54196393de362e0de0e4fa068', 'http://www.ebay.com/article/59f6a0785bfb5.jpg', '13474376703', 'i7qu5v', '127.0.0.1', '100', '0', '0', '1509350464', '1'); INSERT INTO `e_user` VALUES ('3', '你咯', 'dcc2c37d5c27bd6a81c4620c73d20b69', 'http://www.ebay.com/headImg/59f6dccedff01.jpg', '13474376703', 'a4wbw8', '127.0.0.1', '100', '0', '0', '1509350646', '1'); INSERT INTO `e_user` VALUES ('4', '妮妮', '743628bed3723f491651a827ae81c5c0', 'http://www.ebay.com/headImg/59f6ddbdce472.jpg', '1347437603', 'z9n5e4', '127.0.0.1', '100', '0', '1', '1509350848', '1'); INSERT INTO `e_user` VALUES ('5', 'plat', '9c537a5c9f232004c345f15dc64ac99c', 'http://www.ebay.com/headImg/59f96de17a9a6.jpg', '13473796', '29bb24', '127.0.0.1', '100', '0', '1', '1509518818', '1'); INSERT INTO `e_user` VALUES ('6', 'user', '4483000bd6ee04f74749935564e78d64', 'http://www.ebay.com/headImg/59fc30e8e4a15.jpg', '12345678', 'kqmgh8', '127.0.0.1', '100', '0', '1', '1509699817', '1'); -- ---------------------------- -- Table structure for e_user_coupon -- ---------------------------- DROP TABLE IF EXISTS `e_user_coupon`; CREATE TABLE `e_user_coupon` ( `id` int(11) unsigned NOT NULL AUTO_INCREMENT, `uid` int(11) NOT NULL COMMENT '会员uid', `coupon_id` int(11) NOT NULL COMMENT '礼券类型', `add_time` int(10) NOT NULL COMMENT '添加时间', `overdue_time` int(10) NOT NULL COMMENT '过期时间', `status` tinyint(1) NOT NULL COMMENT '状态', PRIMARY KEY (`id`) ) ENGINE=MyISAM AUTO_INCREMENT=6 DEFAULT CHARSET=utf8 COMMENT='会员礼券表'; -- ---------------------------- -- Records of e_user_coupon -- ---------------------------- INSERT INTO `e_user_coupon` VALUES ('3', '5', '3', '1509603125', '1510207925', '1'); INSERT INTO `e_user_coupon` VALUES ('2', '5', '1', '1509603057', '1509689457', '1'); INSERT INTO `e_user_coupon` VALUES ('4', '1', '2', '1509604636', '1509691036', '1'); INSERT INTO `e_user_coupon` VALUES ('5', '1', '3', '1509681238', '1510286038', '1'); -- ---------------------------- -- Table structure for e_wechat -- ---------------------------- DROP TABLE IF EXISTS `e_wechat`; CREATE TABLE `e_wechat` ( `id` int(11) unsigned NOT NULL AUTO_INCREMENT, `uid` int(11) NOT NULL COMMENT '微信注册唯一的uid', `openId` int(11) NOT NULL COMMENT '微信参数openid', `access_token` varchar(255) NOT NULL COMMENT '授权', `regdate_ip` varchar(255) NOT NULL COMMENT '注册ip', `source` varchar(255) NOT NULL COMMENT '来源', `add_time` int(10) NOT NULL COMMENT '添加时间', `status` tinyint(1) NOT NULL COMMENT '状态', PRIMARY KEY (`id`) ) ENGINE=MyISAM DEFAULT CHARSET=utf8 COMMENT='微信会员表'; -- ---------------------------- -- Records of e_wechat -- ---------------------------- <file_sep>/application/Admin/Controller/Login.php <?php /** * 登录controller. * User: Pengfan * Date: 2017/10/13 * Time: 14:58 */ namespace app\Admin\controller; use app\Admin\model\Qqinfo; use app\Admin\model\User; use Org\QQ; use think\Cache; use think\Controller; use think\Request; class Login extends Controller { /** * qq三方登录参数 */ private $qq_param = [ //APP ID 'app_id' => "", //APP Key 'app_key' => "", //回调地址 'callBackUrl' => "" ]; /** * 会员账号登录 */ public function login(){ $param = Request::instance()->post(); if(empty($param)){ return json(['code' => 0,'msg' => '参数为空!']); } $user_model = new User(); $get_user_info = $user_model->get_user_info($param); $uid = $get_user_info['data']['uid']; $token = _produce_token($uid); Cache::set('token',$token); return json($get_user_info); } /** * 会员注册 */ public function register(){ $param = Request::instance()->post(); if(empty($param)){ return json(['code' => 0,'msg' => '数据错误!']); } $ip = $_SERVER['REMOTE_ADDR']; $rand_str = _rand_str(6); $user_model = new User(); $add_user_info = $user_model->add_user_info($param,$rand_str,$ip); return json($add_user_info); } /** * 修改密码 */ public function update_pw(){ $param = Request::instance()->post(); $uid = $param['uid']; $token = $param['token']; $new_pw = $param['new_pw']; if(!_check_token($uid,$token)){ return json(['code' => -3,'msg' => '身份验证失败,请重新登录!']); } $user_model = new User(); $update_pw = $user_model->update_pw($uid,$new_pw); return $update_pw ? json(['code' => 1,'msg' => '修改成功!']) : json(['code' => -1,'msg' => '修改失败!']); } /** * 修改绑定手机号 */ public function update_mobile(){ $param = Request::instance()->post(); $uid = $param['uid']; $token = $param['token']; $new_mobile = $param['new_mobile']; if(!_check_token($uid,$token)){ return json(['code' => -3,'msg' => '身份验证失败,请重新登录!']); } $user_model = new User(); $upate_mobile = $user_model->update_mobile($uid,$new_mobile); return $upate_mobile ? json(['code' => 1,'msg' => '修改成功!']) : json(['code' => -1,'msg' => '修改失败!']); } /** * 修改头像 */ public function update_head_img(){ $param = Request::instance()->post(); $uid = $param['uid']; $token = $param['token']; if(!_check_token($uid,$token)){ return json(['code' => -3,'msg' => '身份验证失败,请重新登录!']); } $user_model = new User(); $route = "headImg/"; $img_url = upload_img('head_img',1024*1024,$route,0); $update_head_img = $user_model->update_head_img($img_url,$uid); return $update_head_img ? json(['code' => 1,'msg' => '修改成功!']) : json(['code' => -1,'msg' => '修改失败!']); } /** * 发送手机验证码 */ public function send_sms_code(){ header('Content-Type: text/plain; charset=utf-8'); $param = Request::instance()->post(); $uid = $param['uid']; $token = $param['token']; $mobile = $param['mobile']; if(!_check_token($uid,$token)){ return json(['code' => -3,'msg' => '身份验证失败,请重新登录!']); } $accessKeyId = "<KEY>"; $accessKeySecret = "<KEY>"; $signName = "彭耀久"; $templateCode = "SMS_94605099"; $phoneNumbers = $mobile; $send_class = new \SmsDemo($accessKeyId,$accessKeySecret); $code = _rand_str(4); Cache::set('mobile_code',$code); $send_code = $send_class->sendSms( $signName, $templateCode, $phoneNumbers, ['number' => $code] ); $send_data = json_encode($send_code); if($send_data->Code == 'ok'){ return json(['code' => 1,'msg' => '发送成功!']); }else{ return json(['code' => -1,'msg' => $send_data->Message]); } } /** * qq三方登录 */ public function qq_login(){ $app_id = $this->qq_param['app_id']; $app_key = $this->qq_param['app_key']; $callBach_url = $this->qq_param['callBackUrl']; $qq_class = new QQ($app_id,$app_key,$callBach_url); $qq_class->getAuthCode(); } /** * qq回调 */ public function callback(){ $app_id = $this->qq_param['app_id']; $app_key = $this->qq_param['app_key']; $callBach_url = $this->qq_param['callBackUrl']; $Qqconnect = new QQ($app_id,$app_key,$callBach_url); $openid = $Qqconnect->getOpenId(); $qq = session('qq'); $map = array(); $qq_model = new Qqinfo(); $userInfo = $qq_model->get_qq_info($openid); if(!empty($userInfo)){ return json(['code' => 1,'msg' => '登录成功!']); } } }<file_sep>/application/Home/model/Userp.php <?php /** * 会员model. * User: Pengfan * Date: 2017/10/26 * Time: 12:47 */ namespace app\home\model; use think\Db; use think\Model; class Userp extends Model { /** * table */ protected $table = "e_user"; /** * 添加平台会员 * @param $data 会员基本信息数据 $rand_str 随机字符 * @return true or false; */ public function add_plat_user($data,$rand_str){ $pass_word = md5(md5($data['pass_word']).$rand_str); $isert_data = [ 'user_name' => $data['user_name'], 'pass_word' => $<PASSWORD>, 'head_img' => $data['head_img'], 'mobile' => $data['mobile'], 'salt_str' => $rand_str, 'register_ip' => $_SERVER['REMOTE_ADDR'], 'integral' => config('def_integ'), 'is_plat' => 1, 'add_time' => time(), 'status' => 1 ]; $res = Db::table('e_user')->insert($isert_data); return $res ? true : false; } /** * 获取平台会员 * @return array or null; */ public function get_plat_user(){ $data = Db::table('e_user')->where(['is_plat' => 1])->select(); return $data ? $data : null; } /** * 获取会员列表 * @param $options 分页参数 * @return array or null; */ public function get_user_list($options){ $data = Db::table('e_user')->order('add_time DESC')->paginate(15,false,$options); $page = $data->render(); return ($data || $page) ? ['data' => $data,'page' => $page] : null; } /** * 会员禁言状态 * @param $uid 会员id $status 会员状态 * @return true or false; */ public function update_user_status($uid,$status){ $data = ['status' => $status]; $res = Db::table('e_user')->where(['uid' => $uid])->update($data); return $res ? true : false; } /** * 发送礼券 * @param $coupon_id 礼券id $uid 会员uid * @return true or false; */ public function send_coupon($coupon_id,$uid){ $data = Db::table('e_coupon')->where(['id' => $coupon_id])->select(); $time = time(); $day = $data[0]['effective_day']; if($data[0]['effective_day']){ $over_time = date("Y-m-d H:i:s",strtotime("+$day day")); }else{ $over_time = date("Y-m-d H:i:s",strtotime("+1 day")); } $insert_data = [ 'uid' => $uid, 'coupon_id' => $coupon_id, 'add_time' => $time, 'overdue_time' => strtotime($over_time), 'status' => 1 ]; $res = Db::table('e_user_coupon')->insert($insert_data); return $res ? true : false; } } <file_sep>/application/Home/Controller/Product.php <?php /** * 商品Controller. * User: Pengfan * Date: 2017/11/3 * Time: 16:12 */ namespace app\HOme\controller; use app\home\model\Productm; use think\Controller; class Product extends Controller { /** * 商品列表 */ public function Product_list(){ $power_str = "productlist"; if(!login_over_time()){ $this->redirect('home/login/index'); } if(!_mate_power($power_str)){ $this->success('您没有权限进行该操作!','home/index/index'); } $product_model = new Productm(); $page = input('page'); if(isset($page) && $page !== null){ $current = $page; }else{ $current = 1; } $options = [ 'page' => $current, 'url' => url('index') ]; $get_product_list = $product_model->get_product_list($options); $this->assign('data',$get_product_list['data']); $this->assign('page',$get_product_list['page']); return $this->fetch('index'); } }<file_sep>/public/README.md ebay接口说明 ==== ####登录 **url:www.ebay.com/admin/login/login** **Method:POST** **Param:** ```text ``` <file_sep>/application/Home/model/Admin.php <?php /** * 管理员model. * User: Pengfan * Date: 2017/10/23 * Time: 15:30 */ namespace app\Home\model; use think\Db; use think\Model; class Admin extends Model { /** * table */ protected $table = 'e_admin_user'; /** * 管理员登录 * @param $user_name 账号 $pass_word 密码 * @return array or null; */ public function login($user_name,$pass_word){ $pass_word = md5(md5($pass_word)); $data = parent::where(['user_name' => $user_name,'pass_word' => $pass_word,'status' => 1])->select(); return $data ? $data : null; } /** * 获取权限 * @param $admin_id 管理员id * @return array or null; */ public function get_admin_power($admin_id){ $data = Db::table('e_admin_power') ->where(['admin_uid'=>$admin_id]) ->select(); return $data ? $data : null; } /** * 添加管理员 * @param $user_name 用户名 $pass_word 密码 * @return true or false; */ public function add_user($user_name,$pass_word){ $pass_word = md5(md5($pass_word)); $this->user_name = $user_name; $this->pass_word = $<PASSWORD>; $res = $this->save(); return $res ? true : false; } /** * 获取管理员列表 * @return array or null; */ public function get_admin_list(){ $data = Db::table('e_admin_user')->select(); return $data ? $data : null; } /** * 修改管理员状态 * @param $uid 管理员id $status 状态 * @return true or false; */ public function update_admin_status($uid,$status){ $update_data = [ 'status' => $status ]; $res = Db::table('e_admin_user')->where(['id' => $uid])->update($update_data); return $res ? true : false; } /** * 添加管理员权限 * @param $data 权限数据 * @return true or false; */ public function add_admin_power($data){ $result = Db::table('e_admin_power')->where(['admin_uid' => $data['uid']])->delete(); if($result || empty($result)){ $power = explode(',',trim($data['power'],',')); $insert_data = ""; foreach ($power as $val){ $insert_data[] = ['power' => $val,'admin_uid' => $data['uid']]; } $res = Db::table('e_admin_power')->insertAll($insert_data); return ($res || $res == 0) ? true : false; }else{ return false; } } }<file_sep>/application/Home/Controller/Article.php <?php /** * 作品controller. * User: Pengfan * Date: 2017/10/23 * Time: 15:00 */ namespace app\Home\controller; use app\Home\model\Articlem; use app\Home\model\Navsort; use app\home\model\Userp; use think\Controller; use think\Request; class Article extends Controller { /** * 作品列表 */ public function Index(){ $power_str = "zuopinliebiao"; if(!login_over_time()){ $this->redirect('home/login/index'); } if(!_mate_power($power_str)){ $this->success('你没有权限进行此操作!','home/index/index'); } $page = input('page'); $article_model = new Articlem(); if (isset($page) && null !== $page) { $current = $page; }else { $current = 1; } $options = [ 'page'=>$current, 'path'=>url('index') ]; $get_article_list = $article_model->get_article_list_info($options); $this->assign('art_data', $get_article_list['data']); $this->assign('page', $get_article_list['page']); return $this->fetch('index'); } /** * 删除 */ public function Del_article(){ $power_str = "shanchuzuopin"; if(!login_over_time()){ return json(['code' => -2,'url' => 'home/login/index']); } if(!_mate_power($power_str)){ $this->success('你没有权限进行此操作!','home/index/index'); } $article_model = new Articlem(); $article_id = input('article_id'); $status = input('status'); $del_article = $article_model->del_article($article_id,$status); return $del_article ? json(['code' => 1,'msg' => '操作成功!']) : json(['code' => -1,'msg' => '操作失败!']); } /** * 查看详情 */ public function Article_details(){ if(!login_over_time()){ $this->redirect('home/login/index'); } $article_id = input('article_id'); $article_model = new Articlem(); $nav_model = new Navsort(); $get_article_info = $article_model->get_article_info($article_id); $get_nav_list = $nav_model->get_sort_nav_info(); $this->assign('data',$get_article_info); $this->assign('nav_data',$get_nav_list); return $this->fetch('details_article'); } /** * 修改作品 */ public function Update_article(){ $power_str = 'xiugaizuopin'; if(!login_over_time()){ return json(['code' => -2,'url' => 'home/login/index']); } if(!_mate_power($power_str)){ $this->success('你没有权限进行此操作!','home/index/index'); } $param = Request::instance()->post(); $article_model = new Articlem(); $update_article = $article_model->Update_article($param); return $update_article ? json(['code' => 1,'msg' => '修改成功!']) : json(['code' => -1,'msg' => '修改失败!']); } /** * 添加作品 */ public function Add_new_article(){ $power_str = "tianjiaxinzuopin"; if(!login_over_time()){ $this->redirect('home/login/index'); } if(!_mate_power($power_str)){ $this->success('你没有权限进行此操作!','home/index/index'); } $nav_model = new Navsort(); $user_model = new Userp(); $get_user_list = $user_model->get_plat_user(); $get_nav_list = $nav_model->get_sort_nav_info(); $this->assign('nav_data',$get_nav_list); $this->assign('user_data',$get_user_list); $param = Request::instance()->post(); if($param){ $article_model = new Articlem(); $add_article = $article_model->add_new_article($param); return $add_article ? json(['code' => 1,'msg' => '添加成功!']) : json(['code' => -1,'msg' => '添加失败!']); } return $this->fetch('add_article'); } /** * 图片上传、视频、音频 */ public function Upload_file(){ $route = '../public/article/'; $host = 'http://'.$_SERVER['SERVER_NAME']; $file_url = upload_img('file',400000,$route,0); return json(['url_str' => $host.'/article/'.$file_url]); } }<file_sep>/application/Home/Controller/Index.php <?php /** * 后台首页controller. * User: Pengfan * Date: 2017/10/19 * Time: 14:02 */ namespace app\Home\controller; use think\Controller; class Index extends Controller { public function index(){ $power_str = "shouye"; if(!login_over_time()){ $this->redirect('home/login/index'); } if(!_mate_power($power_str)){ return json(['code' => -1,'msg' => '你没有权限查看该功能!']); } return $this->fetch('index'); } } <file_sep>/application/Home/model/Articlem.php <?php /** * 作品model. * User: Pengfan * Date: 2017/10/24 * Time: 12:55 */ namespace app\Home\model; use think\Db; use think\Model; class Articlem extends Model { /** * table */ protected $table = "e_article"; /** * 获取作品列表信息 * @param $options 分页参数 * @return array or null; */ public function get_article_list_info($options){ $data = Db::table('e_article')->alias('ar') ->field('ar.*,ai.*,na.nav_name,us.user_name') ->join('e_article_info ai','ar.article_id = ai.article_id') ->join('e_user as us','us.uid = ar.uid') ->join('e_nav_list as na','ar.nav_id = na.nav_id') ->order('ar.add_time DESC')->paginate('15',false,$options); $page = $data->render(); return ($data || $page) ? ['data' => $data,'page' => $page] : null; } /** * 删除article * @param $article_id 作品id $status 作品状态 * @return true or false; */ public function del_article($article_id,$status){ $res = Db::table('e_article')->where(['article_id' => $article_id]) ->update([ 'status' => $status ]); return $res ? true :false; } /** * 获取作品信息 * @param $article_id 作品id * @return array or null; */ public function get_article_info($article_id){ $data = Db::table('e_article')->alias('ar') ->field('ar.*,ai.*,us.uid,us.user_name,na.nav_name') ->join('e_article_info as ai','ar.article_id = ai.article_id') ->join('e_user as us','us.uid = ar.uid') ->join('e_nav_list as na','na.nav_id = ar.nav_id') ->where(['ar.article_id' => $article_id]) ->select(); return $data ? $data : null; } /** * 修改作品信息 * @param $data 作品数据 * @return true or false; */ public function Update_article($data){ $update_data = [ 'article_title' => $data['title'], 'nav_id' => $data['nav_sort'], 'update_time' => time() ]; $update_info = [ 'content' => trim($data['content']," "), 'img_url' => $data['img_url'], ]; $res = Db::table('e_article')->where(['article_id' => $data['article_id']]) ->update($update_data); $res_info = Db::table('e_article_info')->where(['article_id' => $data['article_id']]) ->update($update_info); return ($res || $res_info) ? true : false; } /** * 添加新作品 * @param $data 作品数据 * @return true or false; */ public function add_new_article($data){ $insert_data = [ 'article_title' => $data['title'], 'nav_id' => $data['nav_sort'], 'uid' => $data['uid'], 'add_time' => time(), 'status' => 1 ]; $res = Db::table('e_article')->insertGetId($insert_data); if($res){ $insert_info_data = [ 'article_id' => $res, 'content' => $data['content'], 'img_url' => $data['img_url'] ]; $res_info = Db::table('e_article_info')->insert($insert_info_data); return $res_info ? true : false; } return false; } }<file_sep>/application/Home/Controller/Coupon.php <?php /** * 礼券controller. * User: Pengfan * Date: 2017/11/1 * Time: 14:50 */ namespace app\Home\controller; use app\Home\model\Couponm; use think\Controller; use think\Db; use think\Request; class Coupon extends Controller { /** * 礼券列表 */ public function Index(){ $power_str = "liquanxinxi"; if(!login_over_time()){ $this->redirect('home/login/index'); } if(!_mate_power($power_str)){ $this->success('您没有权限进行该操作!','home/index/index'); } $coupon_model = new Couponm(); $page = input('page'); if(isset($page) && $page !== null){ $current = $page; }else{ $current = 1; } $options = [ 'page' => $current, 'url' => url('index') ]; $get_coupon_list = $coupon_model->get_coupon_info($options); $this->assign('data',$get_coupon_list['data']); $this->assign('page',$get_coupon_list['page']); return $this->fetch('index'); } /** * 添加礼券 */ public function Add_coupon(){ $power_str = "tianjialiquan"; if(!login_over_time()){ $this->redirect('home/login/index'); } if(!_mate_power($power_str)){ $this->success('您没有权限进行该操作!','home/coupon/index'); } if(Request::instance()->isPost()){ $coupon_model = new Couponm(); $param = Request::instance()->post(); $where = ['coupon_name' => $param['coupon_name']]; $result = Db::table('e_coupon')->where($where)->select(); if(!empty($result)){ return json(['code' => -1,'msg' => '该礼券名称重复!']); } $add_coupon = $coupon_model->add_coupon($param); return $add_coupon ? json(['code' => 1,'msg' => '添加成功!']) : json(['code' => -2,'msg' => '添加失败!']); } return $this->fetch('add_coupon'); } /** * 删除礼券 */ public function Del_coupon(){ $power_str = "shanchuliquan"; if(!login_over_time()){ return json(['code' => -1,'url' => 'home/login/index']); } if(!_mate_power($power_str)){ $this->success('您没有权限进行该操作!','home/coupon/index'); } $coupon_model = new Couponm(); $param = Request::instance()->get(); $coupon_id = $param['coupon_id']; $status = $param['status']; $del_coupon = $coupon_model->Del_coupon($coupon_id,$status); return $del_coupon ? json(['code' => 1,'msg' => '删除成功!']) : json(['code' => -2,'msg' => '删除失败!']); } /** * 礼券详情 */ public function Details_coupon(){ $power_str = "xiugailiquan"; if(!login_over_time()){ $this->redirect('home/login/index'); } if(!_mate_power($power_str)){ $this->success('您没有权限进行该操作!','home/coupon/index'); } $coupon_model = new Couponm(); $coupon_id = input('coupon_id'); $coupon_info = $coupon_model->coupon_info($coupon_id); if(Request::instance()->isPost()){ $param = Request::instance()->post(); $upate_coupon = $coupon_model->update_coupon($param); return $upate_coupon ? json(['code' => 1,'msg' => '修改成功!']) : json(['code' => -1,'msg' => '修改失败!']); } $this->assign('data',$coupon_info); return $this->fetch('coupon_details' ); } }<file_sep>/application/Home/model/Commentm.php <?php /** * 文章评论model. * User: Pengfan * Date: 2017/11/1 * Time: 15:01 */ namespace app\Home\model; use think\Db; use think\Model; class Commentm extends Model { /** * table */ protected $table = 'e_comment'; /** * 获取文章评论 * @param $options 分页参数 * @return array or null; */ public function get_article_comment($options){ $data = Db::table('e_comment as co') ->join('e_user as us','us.uid=co.uid') ->join('e_article as ar','ar.article_id=co.article_id') ->field('co.*') ->field('us.user_name') ->field('ar.article_title') ->paginate('15',false,$options); $page = $data->render(); return ($data || $page) ? ['data' => $data,'page' => $page] : ['data' => '','page' => '']; } /** * 修改文章状态 * @param $comment_id 评论id $status 评论状态 * @return true or false; */ public function del_comment($comment_id,$status){ $update_data = [ 'status' => $status, ]; $res = Db::table('e_comment')->where(['id' => $comment_id]) ->update($update_data); return ($res || $res == 0) ? true : false; } /** * 获取商品评论 * @param $options 分页参数 * @return array or null; */ public function get_product_comment($options){ $data = Db::table('e_product_comment as co') ->join('e_user as us','us.uid=co.uid') ->join('e_product as ar','ar.pro_id=co.product_id') ->field('co.*') ->field('us.user_name') ->field('ar.product_name') ->paginate('15',false,$options); $page = $data->render(); return ($data || $page) ? ['data' => $data,'page' => $page] : ['data' => '','page' => '']; } }<file_sep>/application/Admin/model/User.php <?php /** * 会员model. * User: Pengfan * Date: 2017/10/13 * Time: 15:04 */ namespace app\Admin\model; use think\Model; class User extends Model { /** * table */ protected $table = 'user'; /** * 获取用户信息 * @param $data 登录数据(账号,密码); * @return array or null; */ public function get_user_info($data){ $where = ['user_name' => $data['user_name']]; $result = parent::where($where)->select(); if($result){ $pass_word = md5(md5($data['pass_word']).$result[0]['salt_str']); if($pass_word == $result['pass_word']){ return ['code' => 1,'msg'=>'登录成功!','data' => $result[0]]; }else{ return ['code' => -1,'msg'=>'密码错误!','data' => ""]; } }else{ return ['code' => -2,'msg'=>'该用户不存在!','data' => ""]; } } /** * 会员注册 * @param $data 会员注册数据 $rand_str 随机字符串 * @return true or false; */ public function add_user_info($data,$rand_str,$ip){ $data = parent::where(['user_name' => $data['user_name']])->select(); if($data){ return ['code' => -3,'msg' => '该用户名已存在!']; } $model = new User; $pass_word = md5(md5($data['pass_word']).$<PASSWORD>); $model->user_name = $data['user_name']; $model->pass_word = $<PASSWORD>; $model->head_img = $data['head_img']; $model->mobile = $data['mobile']; $model->salt_str = $rand_str; $model->register_ip = $ip; $model->integral = config('def_integ'); $model->add_time = time(); $model->status = 1; $res = $model->save(); if($res !== false){ return ['code' => 1,'msg' => '注册成功!']; }else{ return ['code' => -2,'msg' => '注册失败!']; } } /** * 修改会员密码 * @param $uid 会员uid $new_pw 修改的新密码 * @return true or false; */ public function update_pw($uid,$new_pw){ $resutl = parent::where(['uid' => $uid])->update(['pass_word' => $new_pw]); return $resutl ? true : false; } /** * 修改绑定的手机号 * @param $uid 会员uid $new_mobile 新的手机号 * @return true or false; */ public function update_mobile($uid,$new_mobile){ $result = parent::where(['uid' => $uid])->update(['mobile' => $new_mobile]); return $result ? true : false; } /** * 修改会员头像 * @param $img_url 会员新头像 $uid 会员uid * @return true or false; */ public function update_head_img($img_url,$uid){ $result = parent::where(['uid' => $uid])->update(['head_img' => $img_url]); return $result ? true : false; } }<file_sep>/application/Home/model/Navsort.php <?php /** * 分类导航model. * User: Pengfan * Date: 2017/10/23 * Time: 15:10 */ namespace app\Home\model; use think\Db; use think\Model; class Navsort extends Model { /** * table */ protected $table = 'e_nav_list'; /** * 获取分类导航信息 * @return array or null; */ public function get_sort_nav_info(){ $data = Db::table('e_nav_list')->select(); return $data ? $data : null; } /** * 添加新的导航 * @param $data 导航数据 * @return true or false; */ public function add_new_nav($data){ $insert_data = [ 'nav_name' => $data['nav_name'], 'add_time' => time(), 'status' => 1 ]; $res = Db::table('e_nav_list')->insert($insert_data); return $res ? true : false; } /** * 修改导航状态 * @param $id 导航id $status 导航状态 * @return true or false; */ public function update_nav_status($id,$status){ $update_data = [ 'status' => $status ]; $res = Db::table('e_nav_list')->where(['nav_id' => $id])->update($update_data); return $res ? true : false; } /** * 获取导航信息 * @param $nav_id 导航id * @return array or null; */ public function get_nav_info($nav_id){ $data = Db::table('e_nav_list')->where(['nav_id' => $nav_id])->select(); return $data ? $data : null; } /** * 获取导航banner * @param $options 分页参数 * @return array or null; */ public function get_nav_banner($options){ $data = Db::table('e_nav_banner as nav') ->join('e_nav_list as n','n.nav_id=nav.nav_id') ->field('n.nav_name') ->field('nav.*') ->paginate('15',false,$options); $page = $data->render(); return ($data || $page) ? ['data'=>$data,'page' => $page] : ['data' => '','page' => '']; } /** * 修改banner状态 * @param $banner_id banner唯一id $status 状态 * @return true or false; */ public function update_banner_status($banner_id,$status){ $update_data = [ 'status' => $status ]; $res = Db::table('e_nav_banner')->where(['id' => $banner_id])->update($update_data); return $res ? true : false; } /** * 添加导航banner * @param $data 导航banner数据 * @return true Or false; */ public function add_nav_banner($data){ $insert_data = [ 'nav_id' => $data['nav_id'], 'banner_img' => $data['banner_img'], 'Jump_url' => $data['Jump_url'], 'add_time' => time(), 'status' => 1 ]; $res = Db::table('e_nav_banner')->insert($insert_data); return $res ? true : false; } /** * 修改导航信息 * @param $data 修改后的导航数据 * @return true or false; */ public function update_nav_info($data){ if(isset($data['status']) && $data['status'] == 'on'){ $status = 1; }elseif(!isset($data['status'])){ $status = 3; } $update_data = [ 'nav_name' => $data['nav_name'], 'status' => $status ]; $res = Db::table('e_nav_list')->where(['nav_id' => $data['nav_id']])->update($update_data); return ($res || $res == 0) ? true : false; } /** * 获取导航banner信息 * @param $nav_banner_id banner唯一id * @return array or null; */ public function get_nav_banner_info($nav_banner_id){ $data = Db::table('e_nav_banner as ban') ->join('e_nav_list as nav',"ban.nav_id=nav.nav_id") ->where(['ban.id' => $nav_banner_id]) ->field('ban.*') ->field('nav.nav_name') ->select(); return $data ? $data : null; } /** * 修改导航banner信息 * @param $data banner数据 * @return true or false; */ public function update_banner_info($data){ $update_data = [ 'banner_img' => $data['banner_img'], 'Jump_url' => $data['Jump_url'], 'nav_id' => $data['nav_id'] ]; $res = Db::table('e_nav_banner')->where(['id' => $data['banner_id']])->update($update_data); return ($res || $res == 0) ? true : false; } }<file_sep>/application/Home/Controller/Member.php <?php /** * 会员controller. * User: Pengfan * Date: 2017/10/23 * Time: 15:01 */ namespace app\Home\controller; use think\Controller; class Member extends Controller { /** * 会员信息 */ public function Index(){ } }<file_sep>/application/Admin/common.php <?php // +---------------------------------------------------------------------- // | ThinkPHP [ WE CAN DO IT JUST THINK ] // +---------------------------------------------------------------------- // | Copyright (c) 2006-2016 http://thinkphp.cn All rights reserved. // +---------------------------------------------------------------------- // | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 ) // +---------------------------------------------------------------------- // | Author: 流年 <<EMAIL>> // +---------------------------------------------------------------------- /** * token 验证 * @param $uid 用户uid $token 用户token * @return true or false; */ function _check_token($uid,$token){ $token_key = config('token_key'); $vali_token = substr(md5(md5($uid).$token_key),0,10); if($token == $vali_token){ return true; }else{ return false; } } /** * 生成随机数 * @param $len 长度; * @return string or null; */ function _rand_str($len){ $str = "123456789abcdefghijkmnpqrstuvwxyz"; $str_code = ""; for($i = 0; $i < $len; $i++){ $str_code .= $str[mt_rand(0,strlen($str))]; } return $str_code ? $str_code : null; } /** * 生成token * @param $uid 会员uid $token_key token链接字符 * @return string */ function _produce_token($uid){ $token_key = config('token_key'); $token_str = substr(md5(md5($uid).$token_key),0,10); return $token_str; } /** * 上传文件(包含图片,视频,音频) * @param $name name名称 $maxsize 文件最大值 $route 文件路径 $type 文件类型 * @return array or string; */ function upload_img($name,$maxsize,$route,$type = 0){ switch ($type){ case 0: $arr = ['jpg','jpeg','png','gif']; break; case 1: $arr = ['mp3','ogg']; break; case 2: $arr = ['rmvb']; break; } if(is_array($_FILES[$name]['name'])){ $nameArr = $_FILES[$name]['name']; $objArr = $_FILES[$name]['tmp_name']; $sizeArr = $_FILES[$name]['size']; $arr_return = []; for($i = 0; $i < count($nameArr); $i++){ if(!$nameArr[$i]){ continue; } $_arr = explode('.',$nameArr[$i]); $lastTime = end($_arr); if(in_array($lastTime,$arr) && $sizeArr[$i] <= $maxsize){ $savrName = $route.uniqid().'.'.$lastTime; move_uploaded_file($objArr[$i],$savrName); array_push($arr_return,$savrName); } } return $arr_return; }else{ $_name = $_FILES[$name]['name']; $_size = $_FILES[$name]['size']; $_obj = $_FILES[$name]['tmp_name']; $_arrName = explode('.',$_name); $_lastName = end($_arrName); $_savrName = ""; if(in_array($_lastName,$arr) && $_size <= $maxsize){ $_savrName = $route.uniqid().'.'.$_lastName; move_uploaded_file($_obj,$_savrName); } return $_savrName; } } <file_sep>/application/Admin/model/Navsort.php <?php /** * 分类导航model. * User: Pengfan * Date: 2017/11/9 * Time: 11:38 */ namespace app\Admin\model; use think\Db; use think\Model; class Navsort extends Model { /** * table */ protected $table = 'e_nav_list'; /** * 获取导航分类 * @return array or null; */ public function get_nav_list(){ $data = Db::table('e_nav_list') ->where(['status' => 1]) ->select(); return $data ? $data : null; } /** * 获取导航banner * @param $nav_id 导航id * @return array or null; */ public function get_nav_banner($nav_id){ $data = Db::table('e_nav_banner') ->where(['nav_id' => $nav_id,'status' => 1]) ->select(); return $data ? $data : null; } /** * 获取作品 * @param $nav_id 导航id * @param $page 第几页 * @return array or null; */ public function get_article_list($nav_id,$page){ $page = abs($page - 1); $data = Db::table('e_article as ar') ->join('e_article_info as ai','ai.article_id = ar.article_id') ->join('e_user as us','ar.uid = us.uid') ->where(['ar.nav_id' => $nav_id,'ar.status' => 1]) ->order('ar.add_time DESC') ->field('ar.*,ai.content,ai.img_url,ai.music_url,ai.video_url,us.user_name,us.head_img') ->limit($page*10,'10') ->select(); return $data ? $data : null; } }<file_sep>/application/Home/Controller/Nav.php <?php /** * 分类导航controller. * User: Pengfan * Date: 2017/10/23 * Time: 14:46 */ namespace app\Home\controller; use app\Home\model\Navsort; use think\Controller; use think\Request; class Nav extends Controller { /** * 分类导航信息 */ public function Index(){ $power_str = "daohangliebiao"; if(!login_over_time()){ $this->redirect('home/login/index'); } if(!_mate_power($power_str)){ $this->success('您没有权限进行该操作!','home/index/index'); } $nav_model = new Navsort(); $get_nav_list = $nav_model->get_sort_nav_info(); $this->assign('nav_data',$get_nav_list); return $this->fetch('index'); } /** * 添加导航 */ public function Add_nav(){ $power_str = "tianjiadaohang"; if(!login_over_time()){ $this->redirect('home/login/index'); } if(!_mate_power($power_str)){ $this->success('您没有权限进行该操作!','home/index/index'); } $nav_model = new Navsort(); if(Request::instance()->isPost()){ $param = Request::instance()->post(); $add_new_nav = $nav_model->add_new_nav($param); return $add_new_nav ? json(['code' => 1,'msg' => '添加成功!']) : json(['code' => -1,'msg' => '添加失败!']); } return $this->fetch('add_nav'); } /** * 修改导航状态 */ public function Update_nav_status(){ $power_str = "xiugaidaohangzhuangtai"; if(!login_over_time()){ return json(['code' => -2,'url' => 'home/login/index']); } if(!_mate_power($power_str)){ $this->success('您没有权限进行该操作!','home/index/index'); } $nav_model = new Navsort(); $nav_id = input('id'); $status = input('status'); $update_nav_status = $nav_model->update_nav_status($nav_id,$status); return $update_nav_status ? json(['code' => 1,'msg' => '修改成功!']) : json(['code' => -1,'msg' => '修改失败!']); } /** * 修改导航信息 */ public function Update_nav_info(){ $power_str = "xiugaidaohangxinxi"; if(!login_over_time()){ return json(['code' => -2,'url' => 'home/login/index']); } if(!_mate_power($power_str)){ $this->success('您没有权限进行该操作!','home/index/index'); } $nav_model = new Navsort(); $id = input('nav_id'); if(Request::instance()->post()){ $param = Request::instance()->post(); $update_nav = $nav_model->update_nav_info($param); return $update_nav ? json(['code' => 1,'msg' => '修改成功!']) : json(['code' => -1,'msg' => '修改失败!']); } $get_nav_data = $nav_model->get_nav_info($id); $this->assign('data',$get_nav_data[0]); return $this->fetch('details_nav'); } /** * 分类导航banner */ public function Get_nav_banner(){ if(!login_over_time()){ $this->redirect('home/login/index'); } $nav_model = new Navsort(); $page = input('page'); if(isset($page) && $page !== null){ $current = $page; }else{ $current = 1; } $options = [ 'page' => $current, 'url' => url('get_nav_banner') ]; $get_nav_banner = $nav_model->get_nav_banner($options); $this->assign('data',$get_nav_banner['data']); $this->assign('page',$get_nav_banner['page']); return $this->fetch('nav_banner'); } /** * 修改banner状态 */ public function Update_banner_status(){ $power_str = "xiugaibannerzhuangtai"; if(!login_over_time()){ return json(['code' => -2,'url' => 'home/login/index']); } if(!_mate_power($power_str)){ $this->success('您没有权限进行该操作!','home/index/index'); } $nav_model = new Navsort(); $banner_id = input('id'); $status = input('status'); $update_status = $nav_model->update_banner_status($banner_id,$status); return $update_status ? json(['code' => 1,'msg' =>'修改成功!']) : json(['code' => -1,'msg' => '修改失败!']); } /** * 修改导航banner信息 */ public function Update_banner_info(){ $power_str = "xiugainavbannerxinxi"; if(!login_over_time()){ $this->redirect('home/login/index'); } if(!_mate_power($power_str)){ $this->success('您没有权限进行该操作!','home/index/index'); } $nav_model = new Navsort(); $banner_id = input('banner_id'); if(Request::instance()->isPost()){ $param = Request::instance()->post(); $update_banner_info = $nav_model->update_banner_info($param); return $update_banner_info ? json(['code' => 1,'msg' => '修改成功!']) : json(['code' => -1,'msg' => '修改失败!']); } $get_nav_banner = $nav_model->get_nav_banner_info($banner_id); $this->assign('banner_data',$get_nav_banner[0]); return $this->fetch('details_banner'); } /** * 添加导航banner */ public function Add_nav_banner(){ $power_str = "tianjianavbanner"; if(!login_over_time()){ $this->redirect('home/login/index'); } if(!_mate_power($power_str)){ $this->success('您没有权限进行该操作!','home/index/index'); } $nav_model = new Navsort(); $get_nav_list = $nav_model->get_sort_nav_info(); if(Request::instance()->isPost()){ $param = Request::instance()->post(); $add_nav_banner = $nav_model->add_nav_banner($param); return $add_nav_banner ? json(['code' => 1,'msg' => '添加成功!']) : json(['code' => -1,'msg' =>'添加失败!']); } $this->assign('nav_data',$get_nav_list); return $this->fetch('add_nav_banner'); } /** * 图片上传、视频、音频 */ public function Upload_file(){ $route = '../public/nav_banner/'; $host = "http://".$_SERVER['SERVER_NAME']; $file_url = upload_img('file',400000,$route,0); return json(['url_str' => $host.'/nav_banner/'.$file_url]); } }<file_sep>/application/Home/Controller/Productsort.php <?php /** * 商品分类controller. * User: PengFan * Date: 2017/11/3 * Time: 17:10 */ namespace app\home\controller; use app\home\model\Productsortm; use think\Controller; use think\Db; use think\Request; class Productsort extends Controller { /** * 商品分类列表 */ public function Index(){ $power_str = "prosortlist"; if(!login_over_time()){ $this->redirect('home/login/index'); } if(!_mate_power($power_str)){ $this->success('您没有权限进行该操作!','home/index/index'); } $productsort_model = new Productsortm(); $get_sort_list = $productsort_model->get_sort_list(); $this->assign('sort_data',$get_sort_list); return $this->fetch('index'); } /** * 修改分类状态 */ public function Update_sort_status(){ $power_str = 'updatesortstatus'; if(!login_over_time()){ return json(['code' => -2,'url' => 'home/login/index']); } if(!_mate_power($power_str)){ $this->success('您没有权限进行该操作!','home/index/index'); } $status = input('status'); $sort_id = input('sort_id'); $updata_data = [ 'status' => $status ]; $res = Db::table('e_product_sort') ->where(['sort_id' => $sort_id]) ->update($updata_data); return $res ? json(['code' => 1,'msg' => '修改成功!']) : json(['code' => -1,'msg' => '修改失败!']); } /** * 商品分类详情 */ public function Details_pro_sort(){ $power_str = "updateprosort"; if(!login_over_time()){ $this->redirect('home/login/index'); } if(!_mate_power($power_str)){ $this->success('您没有权限进行该操作!','home/index/index'); } $sort_id = input('sort_id'); $poSort_model = new Productsortm(); if(Request::instance()->post()){ $param = Request::instance()->post(); $sort_id = $param['sort_id']; $sort_name = $param['sort_name']; $update_sotr = $poSort_model->update_sort($sort_id,$sort_name); return $update_sotr ? json(['code' => 1,'msg' => '修改成功!']) : json(['code' => -1,'msg' => '修改失败!']); } $get_pro_sort_info = $poSort_model->get_sort_info($sort_id); $this->assign('one_data',$get_pro_sort_info); return $this->fetch('details_sort'); } /** * 添加分类 */ public function Add_sort(){ $power_str = "addnewsort"; if(!login_over_time()){ return json(['code' => -2,'url' => 'home/login/index']); } if(!_mate_power($power_str)){ $this->success('您没有权限进行该操作!','home/index/index'); } $sort_model = new Productsortm(); if(Request::instance()->post()){ $param = Request::instance()->post(); $old_data = Db::table('e_product_sort')->where(['sort_name' => $param['sort_name']])->select(); if(!empty($old_data)){ return json(['code' => -3,'msg' => '该分类已存在!']); } $add_sort = $sort_model->add_new_sort($param); return $add_sort ? json(['code' => 1,'msg' => '添加成功!']) : json(['code' => -1,'msg' => '添加失败!']); } return $this->fetch('add_sort'); } }<file_sep>/application/Home/Controller/Login.php <?php /** * 后台管理controller. * User: Pengfan * Date: 2017/10/23 * Time: 15:18 */ namespace app\Home\controller; use app\Home\model\Admin; use think\Cache; use think\Controller; use think\Request; class Login extends Controller { /** * 管理员登录 */ public function Index(){ if(Cache::get("admin_data")){ $this->redirect('home/index/index'); } $param = Request::instance()->post(); if(Request::instance()->isPost()){ $user_name = $param['user_name']; $pass_word = $param['pass_<PASSWORD>']; if(empty($user_name) || empty($pass_word)){ $this->error('新增失败'); } $admin_model = new Admin(); $get_user_info = $admin_model->login($user_name,$pass_word); $get_power = $admin_model->get_admin_power($get_user_info[0]['id']); $power = ""; foreach ($get_power as $key => $val){ $power .= $val['power'].','; } Cache::set('admin_data',$get_user_info,3600); Cache::set('admin_power',$power); return $get_user_info ? json(['code' => 1,'msg' => '登录成功!']) : json(['code' => -1,'msg' => '登录失败!']); }else{ return $this->fetch('index'); } } /** * 退出 */ public function Login_out(){ Cache::set('admin_data',null); if(Cache::get('admin_data') == null){ $this->redirect('home/login/index'); } } /** * 添加管理员 */ public function Add_admin_user(){ $power_str = "tianjiaguanliyuan"; if(!login_over_time()){ return json(['code' => 0,'msg' => '账号在线超时!']); } if(!_mate_power($power_str)){ return json(['code' => -1,'msg' => '你没有权限进行该操作!']); } $admin_model = new Admin(); $param = Request::instance()->post(); $user_name = $param['user_name']; $pass_word = $param['<PASSWORD>']; if(empty($user_name) || empty($pass_word)){ return json(['code' => -3,'msg' => '账号或密码不能为空!']); } $add_user = $admin_model->add_user($user_name,$pass_word); return $add_user ? json(['code' => 1,'msg' => '添加成功!']) : json(['code' => -2,'msg' => '添加失败!']); } }<file_sep>/application/Home/Controller/Comment.php <?php /** * 文章评论controller. * User: Pengfan * Date: 2017/11/1 * Time: 14:58 */ namespace app\Home\controller; use app\Home\model\Commentm; use think\Controller; use think\Db; class Comment extends Controller { /** * 文章评论列表 */ public function Index(){ $power_str = "wenzhangpinglun"; if(!login_over_time()){ $this->redirect('home/login/index'); } if(!_mate_power($power_str)){ $this->success('您没有权限进行该操作!','home/index/index'); } $comment_model = new Commentm(); $page = input('page'); if(isset($page) && $page !== null){ $current = $page; }else{ $current = 1; } $options = [ 'page' => $current, 'url' => url('index') ]; $get_comment = $comment_model->get_article_comment($options); $this->assign('data',$get_comment['data']); $this->assign('page',$get_comment['page']); return $this->fetch('index'); } /** * 删除文章评论 */ public function Update_comment_ststus(){ $power_str = "deletezuopincomment"; if(!login_over_time()){ return json(['code' => -2,'url' => 'home/login/index']); } if(!_mate_power($power_str)){ $this->success('您没有权限进行该操作!','home/index/index'); } $comment_id = input('comment_id'); $status = input('status'); $comment_model = new Commentm(); $del_comment_status = $comment_model->del_comment($comment_id,$status); return $del_comment_status ? json(['code' => 1,'msg' =>'修改成功!']) : json(['code' => -1,'msg' => '修改失败!']); } /** * 商品评论列表 */ public function Get_pro_comment(){ $power_str = "productcommentlist"; if(!login_over_time()){ $this->redirect('home/login/index'); } if(!_mate_power($power_str)){ $this->success('您没有权限进行该操作!','home/index/index'); } $comment_model = new Commentm(); $page = input('page'); if(isset($page) && $page !== null){ $current = $page; }else{ $current = 1; } $options = [ 'page' => $current, 'url' => url('get_pro_comment') ]; $get_pro_comment = $comment_model->get_product_comment($options); $this->assign('data',$get_pro_comment['data']); $this->assign('page',$get_pro_comment['page']); return $this->fetch('pro_comment'); } /** * 修改商品评论状态 */ public function Update_pro_comment_status(){ $power_str = "xiugaiprocommentstatus"; if(!login_over_time()){ return json(['code' => -2,'url' => 'home/login/index']); } if(!_mate_power($power_str)){ $this->success('您没有权限进行该操作!','home/index/index'); } $comment_id = input('comment_id'); $status = input('status'); $update_data = [ 'status' => $status, ]; $res = Db::table('e_product_comment') ->where(['id' => $comment_id]) ->update($update_data); return $res ? json(['code' => -1,'msg' => '修改成功!']) : json(['code' => -1,'msg' =>'修改失败!']); } }<file_sep>/application/Home/model/Couponm.php <?php /** * 礼券model. * User: Pengfan * Date: 2017/11/1 * Time: 16:00 */ namespace app\Home\model; use think\Db; use think\Model; class Couponm extends Model { /** * table */ protected $table = 'e_coupon'; /** * 获取礼券列表信息 * @param $options 分页所需要的参数 * @return array or null; */ public function get_coupon_info($options){ $data = Db::table('e_coupon')->order('add_time DESC') ->paginate(15,false,$options); $page = $data->render(); return ($data || $page) ? ['data' => $data,'page' => $page] : ['data' => '','page' => ''] ; } /** * 添加礼券 * @param $data 添加礼券所需参数 * @retun true or false; */ public function add_coupon($data){ if(isset($data['status']) && $data['status'] == 'on'){ $status = 1; }else{ $status = 3; } $insert_data = [ 'coupon_name' => $data['coupon_name'], 'quota' => $data['quota'], 'use_rule' => $data['use_rule'], 'add_time' => time(), 'effective_day' => $data['effective_day'], 'status' => $status ]; $res = Db::table('e_coupon')->insert($insert_data); return $res ? true : false; } /** * 删除礼券 * @param $coupon_id 礼券id $status 礼券状态 * @return true or false; */ public function Del_coupon($coupon_id,$status){ $update_data = [ 'status' => $status ]; $where = ['id' => $coupon_id]; $res = Db::table('e_coupon')->where($where)->update($update_data); return $res ? true : false; } /** * 礼券详情 * @param $coupon_id 礼券id * @return array or null; */ public function coupon_info($coupon_id){ $data = Db::table('e_coupon')->where(['id' => $coupon_id])->select(); return $data ? $data : null; } /** * 修改礼券 * @param $data 礼券的详情数据 * @return true or false; */ public function update_coupon($data){ $upate_data = [ 'coupon_name' => $data['coupon_name'], 'quota' => $data['quota'], 'use_rule' => $data['use_rule'], 'effective_day' => $data['effective_day'] ]; $res = Db::table('e_coupon')->where(['id' => $data['coupon_id']])->update($upate_data); return ($res || $res == 0) ? true : false; } }<file_sep>/application/Admin/Controller/Find.php <?php /** * 首页controller. * User: Pengfan * Date: 2017/11/9 * Time: 11:32 */ namespace app\Admin\controller; use app\Admin\model\Navsort; use think\Controller; class Find extends Controller { /** * 导航nav */ public function Get_nav(){ $navsort_model = new Navsort(); $get_nav_list = $navsort_model->get_nav_list(); return $get_nav_list ? json(['code' => 1,'msg' => 'success','data' => $get_nav_list]) : json(['code' => -1,'msg' => '数据为空!']) ; } /** * 获取nav_banner */ public function Get_nav_banner(){ $nav_model = new Navsort(); $nav_id = input('nav_id'); if(empty($nav_id)){ return json(['code' => -2,'msg' => '导航id为空!']); } $get_banner = $nav_model->get_nav_banner($nav_id); return $get_banner ? json(['code' => 1,'msg' => 'success','data' => $get_banner]) : json(['code' => -1,'msg' =>'数据为空!']) ; } /** * 获取分类导航内容 */ public function Get_nav_article(){ $nav_id = input('nav_id'); $page = input('page'); if(empty($nav_id) && empty($page)){ return json(['code' => -2,'msg' => '导航id和页数为空!']); } $navsort_model = new Navsort(); $get_article_list = $navsort_model->get_article_list($nav_id,$page); return $get_article_list ? json(['code' => 1,'msg' => 'success','data' => $get_article_list]) : json(['code' => -1,'msg'=>'数据为空!']) ; } } <file_sep>/application/Home/model/Productm.php <?php /** * 商品model. * User: Pengfan * Date: 2017/11/3 * Time: 16:24 */ namespace app\home\model; use think\Db; use think\Model; class Productm extends Model { /** * table */ protected $table = 'e_product'; /** * 获取商品信息 * @param $options 分页参数 * @return array or null; */ public function get_product_list($options){ $data = Db::table('e_product as pr') ->join('e_product_sort as so','so.sort_id=pr.sort_id') ->join('e_product_attr_val as attr','pr.pro_id=attr.product_id') ->join('e_sort_attr as rt','rt.attr_id=attr.attr_id') ->paginate(15,false,$options); $page = $data->render(); return ($data || $page) ? ['data' => $data,'page' => $page] : ['data' => '','page' =>'']; } }
64c794a3a22463b338107cfdbb60f52d9a258932
[ "Markdown", "SQL", "PHP" ]
26
PHP
honely/new_app-1
4b77e70b613c1cdb5048354e7d60a3ea248fa887
a5f54a606a879864b5ec09eafe3ca2d97c3d883c
refs/heads/master
<repo_name>nick16/ImageManipulation<file_sep>/Lab2.cpp //Created By <NAME> //Lab 2. Excersises 1-3 //This program demonstrates image manipulation using recursion. #include "EasyBMP.h" #include "EasyBMP_DataStructures.h" #include "EasyBMP_BMP.h" #include "EasyBMP_VariousBMPutilities.h" #include "EasyBMP.cpp" #include <iostream> #include <cstdlib> //for rand() using namespace std; void pattern(BMP & image) { int picWidth = image.TellWidth(); int picHeight = image.TellHeight(); for (int i = 0; i < picWidth; ++i) //X row for (int j = 0; j < picHeight; ++j) //Y col { int row = i / 32; int col = j / 32; if ((row + col) % 2 == 0) //if even, then red { image(i, j)->Red = 255; image(i, j)->Green = 0; image(i, j)->Blue = 0; } else //set to black { image(i, j)->Red = 0; image(i, j)->Green = 0; image(i, j)->Blue = 0; } } } void triangle(BMP & image, BMP & X, BMP & Y, BMP & Z, BMP & P, int counter) //recursive function for creating triangle { if (counter != 0) { int chose = rand() % 3; if (chose == 0) //X { //create a red dot between x-cord and p-cord. Then recursive call but with new P being half of current P BMP midpoint; int picWidth2 = ((X.TellWidth() + P.TellWidth()) / 2); int picHeight2 = ((P.TellHeight() + X.TellHeight()) / 2); midpoint.SetSize(picWidth2, picHeight2); image(midpoint.TellWidth(), midpoint.TellHeight())->Red = 255; image(midpoint.TellWidth(), midpoint.TellHeight())->Blue = 0; image(midpoint.TellWidth(), midpoint.TellHeight())->Green = 0; triangle(image, X, Y, Z, midpoint, --counter); } else if (chose == 1) //Y { BMP midpoint; int picWidth2 = ((Y.TellWidth() + P.TellWidth()) / 2); int picHeight2 = ((P.TellHeight() + Y.TellHeight()) / 2); midpoint.SetSize(picWidth2, picHeight2); image(midpoint.TellWidth(), midpoint.TellHeight())->Red = 255; image(midpoint.TellWidth(), midpoint.TellHeight())->Blue = 0; image(midpoint.TellWidth(), midpoint.TellHeight())->Green = 0; triangle(image, X, Y, Z, midpoint, --counter); } else if (chose == 2) //Z { BMP midpoint; int picWidth2 = ((Z.TellWidth() + P.TellWidth()) / 2); int picHeight2 = ((P.TellHeight() + Z.TellHeight()) / 2); midpoint.SetSize(picWidth2, picHeight2); image(midpoint.TellWidth(), midpoint.TellHeight())->Red = 255; image(midpoint.TellWidth(), midpoint.TellHeight())->Blue = 0; image(midpoint.TellWidth(), midpoint.TellHeight())->Green = 0; triangle(image, X, Y, Z, midpoint, --counter); } } return; } void Tile(BMP & input_image, BMP & output_image) { if (input_image.TellWidth() == 1) //Base Case: when the recieved input has been reduced to a 1x1 size. { return; } BMP temp; temp.SetSize(input_image.TellWidth(), input_image.TellHeight()); Rescale(input_image, 'p', 50); RangedPixelToPixelCopy(input_image, 0, output_image.TellWidth() / 2, output_image.TellHeight() / 2, 0, temp, 0, temp.TellHeight() / 2); Tile(input_image, temp); //**************** RangedPixelToPixelCopy(temp, 0, output_image.TellWidth() / 2, output_image.TellHeight() / 2, 0, output_image, 0, 0); RangedPixelToPixelCopy(temp, 0, output_image.TellWidth() / 2, output_image.TellHeight() / 2, 0, output_image, output_image.TellHeight() / 4, 0); //The top two lines copy the image left and the bottom two lines copy the image down. RangedPixelToPixelCopy(temp, 0, output_image.TellWidth() / 2, output_image.TellHeight() / 2, 0, output_image, output_image.TellHeight() / 2, output_image.TellHeight() / 2); RangedPixelToPixelCopy(temp, 0, output_image.TellWidth() / 2, output_image.TellHeight() / 2, 0, output_image, output_image.TellHeight() / 2, output_image.TellHeight() / 4); //*************** RangedPixelToPixelCopy(temp, 0, output_image.TellWidth() / 2, output_image.TellHeight() / 2, 0, output_image, output_image.TellHeight() / 2, 0); //recursively places the images in the top right corner of the previous } int main() { BMP board; board.SetSize(256, 256); board.SetBitDepth(8); //color depth to 8 bits pattern(board); board.WriteToFile("testimage.bmp"); //********************************************************* BMP image; image.SetSize(256, 256); BMP X, Y, Z, P; X.SetSize(128, 5); Y.SetSize(5, 251); Z.SetSize(251, 251); P.SetSize(171, 34); triangle(image, X, Y, Z, P, 10000); image.WriteToFile("sierpinski.bmp"); //******************************************************* BMP input_image; input_image.ReadFromFile("einstein.bmp"); BMP output_image; output_image.SetSize(input_image.TellWidth(), input_image.TellHeight()); Rescale(input_image, 'p', 50); RangedPixelToPixelCopy(input_image, 0, output_image.TellWidth() / 2, output_image.TellHeight() / 2, 0, output_image, 0, output_image.TellHeight() / 2); //LEFT BOTTOM CORNER Tile(input_image, output_image); output_image.WriteToFile("NEW_einstein.bmp"); //******************************************************** //system("PAUSE"); return 0; }
c19eb3bdeecd597ac0383c550372012af0af906e
[ "C++" ]
1
C++
nick16/ImageManipulation
ae84d5cc00efdc165b49c1ff7789b54fc8d355cf
d7fe3a7409c5e1497b56d7402a7765fed333ef79
refs/heads/master
<file_sep>package com.marshmallow.beacon.login; import android.support.test.espresso.action.ViewActions; import android.support.test.espresso.matcher.ViewMatchers; import android.support.test.rule.ActivityTestRule; import android.support.test.runner.AndroidJUnit4; import static android.support.test.espresso.Espresso.onView; import static android.support.test.espresso.action.ViewActions.click; import static android.support.test.espresso.action.ViewActions.typeText; import static android.support.test.espresso.matcher.ViewMatchers.hasErrorText; import static android.support.test.espresso.matcher.ViewMatchers.withId; import static android.support.test.espresso.matcher.ViewMatchers.withText; import com.marshmallow.beacon.R; import com.marshmallow.beacon.ui.user.LoginActivity; import org.junit.Rule; import org.junit.Test; import org.junit.runner.RunWith; /** * Created by George on 9/8/2018. */ @RunWith(AndroidJUnit4.class) public class SuccessfulLoginTest { @Rule public ActivityTestRule<LoginActivity> loginActivityActivityTestRule = new ActivityTestRule<>(LoginActivity.class); @Test public void successfulLogin() { onView(ViewMatchers.withId(R.id.email_text)).perform(typeText("<EMAIL>"), ViewActions.closeSoftKeyboard()); onView(withId(R.id.password_text)).perform(typeText("<PASSWORD>"), ViewActions.closeSoftKeyboard()); onView(withId(R.id.sign_in_button)).perform(click()); } } <file_sep>package com.marshmallow.beacon; import com.marshmallow.beacon.models.contacts.Request; import java.util.HashMap; import java.util.Vector; /** * Created by George on 7/28/2018. */ public class ContactRequestManager { private static ContactRequestManager instance = null; private HashMap<String, Request> requestsIn; private HashMap<String, Request> requestsOut; private ContactRequestManager() { requestsIn = new HashMap<>(); requestsOut = new HashMap<>(); } public static ContactRequestManager getInstance() { if (instance == null) { instance = new ContactRequestManager(); } return instance; } public void addRequestIn(Request requestIn) { requestsIn.put(requestIn.getFrom(), requestIn); } public void removeRequestIn(Request requestIn) { requestsIn.remove(requestIn.getFrom()); } public void addRequestOut(Request requestOut) { requestsOut.put(requestOut.getTo(), requestOut); } public void removeRequestsOut(Request requestOut) { requestsOut.remove(requestOut.getTo()); } public Vector<Request> getIncomingRequests() { return new Vector<>(requestsIn.values()); } public Vector<Request> getOutgoingRequests() { return new Vector<>(requestsOut.values()); } } <file_sep>package com.marshmallow.beacon.models.marketing; import com.marshmallow.beacon.models.marketing.SponsorMarketValues; import com.marshmallow.beacon.models.marketing.SurveyMarketValues; import org.junit.Test; import static junit.framework.Assert.assertEquals; /** * Created by George on 9/7/2018. */ public class SurveyMarketValuesTest { private SurveyMarketValues surveyMarketValues = new SurveyMarketValues(); @Test public void firstNameValueTest() { surveyMarketValues.setFirstNameValue(5); assertEquals(5, surveyMarketValues.getFirstNameValue().intValue()); } @Test public void lastNameValueTest() { surveyMarketValues.setLastNameValue(7); assertEquals(7, surveyMarketValues.getLastNameValue().intValue()); } @Test public void geolocationValueTest() { surveyMarketValues.setGeolocationValue(8); assertEquals(8, surveyMarketValues.getGeolocationValue().intValue()); } @Test public void emailValueTest() { surveyMarketValues.setEmailValue(1); assertEquals(1, surveyMarketValues.getEmailValue().intValue()); } @Test public void birthdayValueTest() { surveyMarketValues.setBirthdayValue(22); assertEquals(22, surveyMarketValues.getBirthdayValue().intValue()); } @Test public void cityValueTest() { surveyMarketValues.setCityValue(382); assertEquals(382, surveyMarketValues.getCityValue().intValue()); } @Test public void stateValueTest() { surveyMarketValues.setStateValue(99); assertEquals(99, surveyMarketValues.getStateValue().intValue()); } @Test public void phoneValueTest() { surveyMarketValues.setPhoneValue(302); assertEquals(302, surveyMarketValues.getPhoneValue().intValue()); } } <file_sep>package com.marshmallow.beacon.ui.contacts; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.content.IntentFilter; import android.os.Bundle; import android.support.annotation.NonNull; import android.support.annotation.Nullable; import android.support.design.widget.FloatingActionButton; import android.support.v7.widget.CardView; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ImageView; import android.widget.TextView; import com.google.firebase.auth.FirebaseAuth; import com.google.firebase.database.ChildEventListener; import com.google.firebase.database.DataSnapshot; import com.google.firebase.database.DatabaseError; import com.google.firebase.database.FirebaseDatabase; import com.google.firebase.database.Query; import com.marshmallow.beacon.ContactRequestManager; import com.marshmallow.beacon.R; import com.marshmallow.beacon.UserManager; import com.marshmallow.beacon.models.contacts.Contact; import com.marshmallow.beacon.models.contacts.Request; import com.marshmallow.beacon.models.user.User; import com.marshmallow.beacon.ui.BaseActivity; import java.util.Collection; import java.util.HashMap; import java.util.List; import java.util.Vector; /** * Created by George on 7/13/2018. */ public class ContactsActivity extends BaseActivity { // GUI handles private CardView incomingRequestsCard; private TextView incomingRequestsCountText; private CardView outgoingRequestsCard; private TextView outgoingRequestsCountText; private TextView noContactsText; private RecyclerView contactsRecyclerView; private FloatingActionButton addContactButton; private RecyclerView.LayoutManager contactsLayoutManager; private ContactsAdapter contactsAdapter; private Vector<Contact> contacts; private HashMap<Query, ChildEventListener> contactReferences = null; // Firebase private FirebaseAuth firebaseAuth; private FirebaseDatabase firebaseInst; private Query requestsInQuery; private Query requestsOutQuery; private ChildEventListener requestsInQueryListener; private ChildEventListener requestsOutQueryListener; // Models User user; ContactRequestManager contactRequestManager; @Override protected void onCreate(Bundle savedInstanceState) { setContentView(R.layout.activity_contacts); activityType = MainActivityTypes.CONTACTS; super.onCreate(savedInstanceState); // Model initialization user = UserManager.getInstance().getUser(); contactRequestManager = ContactRequestManager.getInstance(); // GUI handle instantiation incomingRequestsCard = findViewById(R.id.incoming_requests); incomingRequestsCountText = findViewById(R.id.received_contact_request_count); outgoingRequestsCard = findViewById(R.id.outgoing_requests); outgoingRequestsCountText = findViewById(R.id.sent_contact_request_count); noContactsText = findViewById(R.id.no_contacts_title); contacts = new Vector<>() ; contactsRecyclerView = findViewById(R.id.contacts_recycler_view); contactsLayoutManager = new LinearLayoutManager(this); contactsRecyclerView.setLayoutManager(contactsLayoutManager); contactsAdapter = new ContactsAdapter(contacts); contactsRecyclerView.setAdapter(contactsAdapter); addContactButton = findViewById(R.id.add_contact_fab); // Firebase initialization firebaseAuth = FirebaseAuth.getInstance(); firebaseInst = FirebaseDatabase.getInstance(); initializeContactRequestListeners(); initializeContactListeners(); // Set GUI business logic addContactButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent intent = new Intent(getApplicationContext(), NewContactActivity.class); startActivity(intent); } }); incomingRequestsCard.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent intent = new Intent(getApplicationContext(), IncomingContactRequestsActivity.class); startActivity(intent); } }); outgoingRequestsCard.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent intent = new Intent(getApplicationContext(), OutgoingContactRequestsActivity.class); startActivity(intent); } }); } private void initializeContactRequestListeners() { String username = UserManager.getInstance().getUser().getUsername(); requestsInQuery = firebaseInst.getReference("requests").orderByChild("to").equalTo(username); requestsOutQuery = firebaseInst.getReference("requests").orderByChild("from").equalTo(username); requestsInQueryListener = new ChildEventListener() { @Override public void onChildAdded(@NonNull DataSnapshot dataSnapshot, @Nullable String s) { Request requestIn = dataSnapshot.getValue(Request.class); contactRequestManager.addRequestIn(requestIn); updateRequestCounts(); } @Override public void onChildChanged(@NonNull DataSnapshot dataSnapshot, @Nullable String s) { Request requestIn = dataSnapshot.getValue(Request.class); contactRequestManager.addRequestIn(requestIn); updateRequestCounts(); } @Override public void onChildRemoved(@NonNull DataSnapshot dataSnapshot) { Request request = dataSnapshot.getValue(Request.class); contactRequestManager.removeRequestIn(request); updateRequestCounts(); } @Override public void onChildMoved(@NonNull DataSnapshot dataSnapshot, @Nullable String s) { } @Override public void onCancelled(@NonNull DatabaseError databaseError) { // TODO submit error } }; requestsOutQueryListener = new ChildEventListener() { @Override public void onChildAdded(@NonNull DataSnapshot dataSnapshot, @Nullable String s) { Request requestOut = dataSnapshot.getValue(Request.class); contactRequestManager.addRequestOut(requestOut); updateRequestCounts(); } @Override public void onChildChanged(@NonNull DataSnapshot dataSnapshot, @Nullable String s) { Request requestOut = dataSnapshot.getValue(Request.class); contactRequestManager.addRequestOut(requestOut); updateRequestCounts(); } @Override public void onChildRemoved(@NonNull DataSnapshot dataSnapshot) { Request requestOut = dataSnapshot.getValue(Request.class); contactRequestManager.removeRequestsOut(requestOut); updateRequestCounts(); } @Override public void onChildMoved(@NonNull DataSnapshot dataSnapshot, @Nullable String s) { } @Override public void onCancelled(@NonNull DatabaseError databaseError) { // submit error } }; requestsInQuery.addChildEventListener(requestsInQueryListener); requestsOutQuery.addChildEventListener(requestsOutQueryListener); } public void initializeContactListeners() { contactReferences = new HashMap<>(); if (user.getRolodex() != null) { List<String> userNames = user.getRolodex().getUsernames(); for (String username : userNames) { Query query = firebaseInst.getReference("users").orderByChild("username").equalTo(username); ChildEventListener childEventListener = new ChildEventListener() { @Override public void onChildAdded(@NonNull DataSnapshot dataSnapshot, @Nullable String s) { Contact contact = dataSnapshot.getValue(Contact.class); if (contact != null) { UserManager.getInstance().getContacts().put(contact.getUsername(), contact); contactsAdapter.notifyDataSetChanged(); updateNumberOfContacts(); } } @Override public void onChildChanged(@NonNull DataSnapshot dataSnapshot, @Nullable String s) { Contact contact = dataSnapshot.getValue(Contact.class); if (contact != null) { UserManager.getInstance().getContacts().put(contact.getUsername(), contact); contactsAdapter.notifyDataSetChanged(); updateNumberOfContacts(); } } @Override public void onChildRemoved(@NonNull DataSnapshot dataSnapshot) { // TODO removed? Likely just remove from contact list if they deleted profile } @Override public void onChildMoved(@NonNull DataSnapshot dataSnapshot, @Nullable String s) { } @Override public void onCancelled(@NonNull DatabaseError databaseError) { // TODO failures? } }; query.addChildEventListener(childEventListener); contactReferences.put(query, childEventListener); } } } @Override public void onBackPressed() { super.onBackPressed(); finish(); } @Override public void onResume() { super.onResume(); updateRequestCounts(); } private void updateRequestCounts() { incomingRequestsCountText.setText(String.format("%d", contactRequestManager.getIncomingRequests().size())); outgoingRequestsCountText.setText(String.format("%d",contactRequestManager.getOutgoingRequests().size())); } private void updateNumberOfContacts() { if (contacts.size() != 0) { noContactsText.setVisibility(View.GONE); contactsRecyclerView.setVisibility(View.VISIBLE); } else { noContactsText.setVisibility(View.VISIBLE); contactsRecyclerView.setVisibility(View.GONE); } } public class ContactsAdapter extends RecyclerView.Adapter<ContactsAdapter.ContactHolder> { private Vector<Contact> contacts; public ContactsAdapter(Vector<Contact> contacts) { this.contacts = contacts; } @NonNull @Override public ContactsAdapter.ContactHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) { View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.contact_basic, parent, false); return new ContactsAdapter.ContactHolder(v); } @Override public void onBindViewHolder(@NonNull final ContactHolder holder, final int position) { Contact contact = contacts.get(position); holder.contactNameText.setText(contact.getUsername()); holder.contactProfilePicture.setImageBitmap(contact.getProfilePictureBitmap()); if (contact.getSignedIn()) { holder.signedInStatus.setImageResource(R.drawable.beacon_on_mini); } else { holder.signedInStatus.setImageResource(R.drawable.beacon_off_mini); } // TODO handle selecting a single contact } @Override public int getItemCount() { return contacts.size(); } public class ContactHolder extends RecyclerView.ViewHolder { public ImageView contactProfilePicture; public TextView contactNameText; public ImageView signedInStatus; public ContactHolder(View v) { super(v); contactProfilePicture = v.findViewById(R.id.contact_profile_picture); contactNameText = v.findViewById(R.id.contact_name); signedInStatus = v.findViewById(R.id.sign_in_status_image); } } } } <file_sep>package com.marshmallow.beacon.models.user; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.util.Base64; import com.google.firebase.database.Exclude; import java.io.ByteArrayOutputStream; /** * Created by George on 7/17/2018. */ public class User { private String username; private String profilePicture; private Boolean signedIn; private Integer points; private DataPoint geolocationOn; private DataPoint firstName; private DataPoint lastName; private DataPoint email; private DataPoint birthday; private DataPoint city; private DataPoint state; private DataPoint phoneNumber; private Boolean accountCreationComplete; private Rolodex rolodex; public User () { } public User(String email) { this.username = null; this.profilePicture = null; this.signedIn = true; this.points = 0; this.geolocationOn = new DataPoint(null, false); this.firstName = new DataPoint(null, false); this.lastName = new DataPoint(null, false); this.email = new DataPoint(email, true); this.birthday = new DataPoint(null, false); this.city = new DataPoint(null, false); this.state = new DataPoint(null, false); this.phoneNumber = new DataPoint(null, false); this.accountCreationComplete = false; rolodex = new Rolodex(); } public Boolean getSignedIn() { return signedIn; } public void setSignedIn(Boolean signedIn) { this.signedIn = signedIn; } public DataPoint getFirstName() { return firstName; } public void setFirstName(DataPoint firstName) { this.firstName = firstName; } public DataPoint getLastName() { return lastName; } public void setLastName(DataPoint lastName) { this.lastName = lastName; } public DataPoint getEmail() { return email; } public void setEmail(DataPoint email) { this.email = email; } public DataPoint getBirthday() { return birthday; } public void setBirthday(DataPoint birthday) { this.birthday = birthday; } public DataPoint getCity() { return city; } public void setCity(DataPoint city) { this.city = city; } public DataPoint getState() { return state; } public void setState(DataPoint state) { this.state = state; } public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } public Rolodex getRolodex() { return rolodex; } public void setRolodex(Rolodex rolodex) { this.rolodex = rolodex; } public Integer getPoints() { return points; } public void setPoints(Integer points) { this.points = points; } public String getProfilePicture() { return profilePicture; } public void setProfilePicture(String profilePicture) { this.profilePicture = profilePicture; } public DataPoint getGeolocationOn() { return geolocationOn; } public void setGeolocationOn(DataPoint geolocationOn) { this.geolocationOn = geolocationOn; } @Exclude public Bitmap getProfilePictureBitmap() { if (profilePicture != null) { byte[] decodedString = Base64.decode(profilePicture, Base64.DEFAULT); return BitmapFactory.decodeByteArray(decodedString, 0, decodedString.length); } else { return null; } } @Exclude public void setProfilePictureFromBitmap(Bitmap profilePictureBitmap) { ByteArrayOutputStream byteArrayBitmapStream = new ByteArrayOutputStream(); profilePictureBitmap.compress(Bitmap.CompressFormat.PNG, 100, byteArrayBitmapStream); byte[] b = byteArrayBitmapStream.toByteArray(); profilePicture = Base64.encodeToString(b, Base64.DEFAULT); } public DataPoint getPhoneNumber() { return phoneNumber; } public void setPhoneNumber(DataPoint phoneNumber) { this.phoneNumber = phoneNumber; } public Boolean getAccountCreationComplete() { return accountCreationComplete; } public void setAccountCreationComplete(Boolean accountCreationComplete) { this.accountCreationComplete = accountCreationComplete; } } <file_sep>package com.marshmallow.beacon.ui.user; import android.content.Intent; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.view.View; import android.widget.Button; import com.marshmallow.beacon.R; /** * Created by George on 8/2/2018. */ public class WelcomePrimaryActivity extends AppCompatActivity { // GUI handles private Button backButton; private Button nextButton; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_primary_welcome); // GUI instantiation backButton = findViewById(R.id.edit_profile_back_button); nextButton = findViewById(R.id.welcome_primary_next_button); backButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { finish(); } }); nextButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent intent = new Intent(getApplicationContext(), EditProfileActivity.class); intent.putExtra("creatingAccount", true); startActivity(intent); finish(); } }); } } <file_sep>package com.marshmallow.beacon.models.marketing; import android.support.annotation.NonNull; import com.marshmallow.beacon.models.user.User; /** * Created by George on 8/5/2018. */ public class UserMarketDataSnapshot { private String username; private String firstName; private String lastName; private String email; private String birthday; private String city; private String state; private String phone; public UserMarketDataSnapshot() { } public UserMarketDataSnapshot(@NonNull User user) { username = user.getUsername(); if (user.getFirstName().getShared()) { firstName = user.getFirstName().getValue(); } if (user.getLastName().getShared()) { lastName = user.getLastName().getValue(); } if (user.getEmail().getShared()) { email = user.getEmail().getValue(); } if (user.getBirthday().getShared()) {birthday = user.getBirthday().getValue(); } if (user.getCity().getShared()) { city = user.getCity().getValue(); } if (user.getState().getShared()) { state = user.getState().getValue(); } if (user.getPhoneNumber().getShared()) { phone = user.getPhoneNumber().getValue(); } } public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } public String getFirstName() { return firstName; } public void setFirstName(String firstName) { this.firstName = firstName; } public String getLastName() { return lastName; } public void setLastName(String lastName) { this.lastName = lastName; } public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } public String getBirthday() { return birthday; } public void setBirthday(String birthday) { this.birthday = birthday; } public String getCity() { return city; } public void setCity(String city) { this.city = city; } public String getState() { return state; } public void setState(String state) { this.state = state; } public String getPhone() { return phone; } public void setPhone(String phone) { this.phone = phone; } } <file_sep>package com.marshmallow.beacon.models.contacts; /** * Created by George on 7/17/2018. */ public class Request { private String uid; private String to; private String from; private Status status; public enum Status { PENDING, ACCEPTED, DECLINED } public Request() { } public Request(String to, String from) { this.to = to; this.from = from; this.status = Status.PENDING; } public String getTo() { return to; } public void setTo(String to) { this.to = to; } public String getFrom() { return from; } public void setFrom(String from) { this.from = from; } public Status getStatus() { return status; } public void setStatus(Status status) { this.status = status; } public String getUid() { return uid; } public void setUid(String uid) { this.uid = uid; } } <file_sep>package com.marshmallow.beacon.ui.marketing; import android.content.Context; import android.content.Intent; import android.graphics.Color; import android.net.Uri; import android.os.Build; import android.os.Bundle; import android.support.annotation.NonNull; import android.support.v7.app.AppCompatActivity; import android.view.Gravity; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.view.WindowManager; import android.widget.Button; import android.widget.EditText; import android.widget.ImageView; import android.widget.PopupWindow; import android.widget.TextView; import android.widget.Toast; import com.google.firebase.auth.FirebaseAuth; import com.google.firebase.database.DataSnapshot; import com.google.firebase.database.DatabaseError; import com.google.firebase.database.DatabaseReference; import com.google.firebase.database.FirebaseDatabase; import com.google.firebase.database.ValueEventListener; import com.marshmallow.beacon.MarketingManager; import com.marshmallow.beacon.R; import com.marshmallow.beacon.UserManager; import com.marshmallow.beacon.models.marketing.Sponsor; import com.marshmallow.beacon.models.marketing.SponsorMarketValues; import com.marshmallow.beacon.models.user.User; /** * Created by George on 9/12/2018. */ public class IndividualSponsorActivity extends AppCompatActivity { // GUI handles private ImageView sponsorImageView; private TextView sponsorNameTextView; private ImageView websiteImageView; private ImageView likeButton; private ImageView dislikeButton; private EditText postEditText; private Button postCommentButton; // Basic model data Sponsor sponsor; private SponsorMarketValues sponsorMarketValues; private int sponsorImageResId; private boolean sponsorVisited; private boolean likedTriggeredOnce; private boolean liked; // Intent data public static final String sponsorUidKey = "sponsorUid"; public static final String sponsorNameKey = "sponsorName"; public static final String sponsorImageResIdKey = "sponsorImageResId"; public static final String sponsorUrlKey = "sponsorUrl"; // Firebase private FirebaseAuth firebaseAuth; private FirebaseDatabase firebaseInst; private DatabaseReference userVisitDataReference; private DatabaseReference userWebVisitedDataReference; private DatabaseReference userLikeDataReference; private ValueEventListener userLikeStatusListener; private ValueEventListener userWebVisitedStatusListener; private DatabaseReference sponsorMarketValueReference; private ValueEventListener sponsorMarketValueEventListener; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_individual_sponsor); // Instantiate Firebase firebaseAuth = FirebaseAuth.getInstance(); firebaseInst = FirebaseDatabase.getInstance(); // Instantiate GUI sponsorImageView = findViewById(R.id.sponsor_image); sponsorNameTextView = findViewById(R.id.sponsor_name); websiteImageView = findViewById(R.id.website_image); likeButton = findViewById(R.id.like_button); dislikeButton = findViewById(R.id.dislike_button); postEditText = findViewById(R.id.post_edit_text); postCommentButton = findViewById(R.id.post_button); // Retrieve intent data and populate GUI sponsor = new Sponsor(); sponsor.setUid(getIntent().getStringExtra(sponsorUidKey)); sponsor.setName(getIntent().getStringExtra(sponsorNameKey)); sponsor.setUrl(getIntent().getStringExtra(sponsorUrlKey)); sponsorImageResId = getIntent().getIntExtra(sponsorImageResIdKey, -1); sponsorNameTextView.setText(sponsor.getName()); sponsorImageView.setImageResource(sponsorImageResId); // Retrieve database values for user visit and likes setupUserVisitDataListeners(); initializeMarketValueListeners(); // TODO set up timer to say loading sponsor data to prevent people from clicking web links before it is determined whether they've visited or not // Set up interaction listeners websiteImageView.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { handleWebsiteVisitInteraction(); } }); likeButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { handleLikeInteractions(true); } }); dislikeButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { handleLikeInteractions(false); } }); postCommentButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { String comment = postEditText.getText().toString(); String newPostKey = userVisitDataReference.child("posts").push().getKey(); // Store comment key in the user entry, and also post the full string to the sponsor entry if (newPostKey != null) { userVisitDataReference.child("posts").child(newPostKey).setValue(true); long timestamp = System.currentTimeMillis(); firebaseInst.getReference("sponsorVisitData").child(sponsor.getUid()).child("posts").child(newPostKey).child("timestamp").setValue(timestamp); firebaseInst.getReference("sponsorVisitData").child(sponsor.getUid()).child("posts").child(newPostKey).child("text").setValue(comment); Toast.makeText(IndividualSponsorActivity.this, "Commented posted", Toast.LENGTH_SHORT).show(); postEditText.setText(""); } } }); } @Override protected void onDestroy() { super.onDestroy(); destroyUserVisitDataListeners(); } private void setupUserVisitDataListeners() { if (firebaseAuth.getUid() != null) { userVisitDataReference = firebaseInst.getReference("sponsorVisitData").child(sponsor.getUid()).child("usersVisited").child(firebaseAuth.getUid()); userWebVisitedDataReference = userVisitDataReference.child("visited"); userLikeDataReference = userVisitDataReference.child("like"); userWebVisitedStatusListener = new ValueEventListener() { @Override public void onDataChange(@NonNull DataSnapshot dataSnapshot) { if (dataSnapshot.exists()) { sponsorVisited = (boolean) dataSnapshot.getValue(); updateWebsiteVisitStatus(sponsorVisited); } else { sponsorVisited = false; } } @Override public void onCancelled(@NonNull DatabaseError databaseError) { } }; userLikeStatusListener = new ValueEventListener() { @Override public void onDataChange(@NonNull DataSnapshot dataSnapshot) { if (dataSnapshot.exists()) { likedTriggeredOnce = true; liked = (boolean) dataSnapshot.getValue(); updateLikeStatuses(liked); } else { likedTriggeredOnce = false; } } @Override public void onCancelled(@NonNull DatabaseError databaseError) { } }; userWebVisitedDataReference.addValueEventListener(userWebVisitedStatusListener); userLikeDataReference.addValueEventListener(userLikeStatusListener); } } private void destroyUserVisitDataListeners() { userWebVisitedDataReference.removeEventListener(userWebVisitedStatusListener); userLikeDataReference.removeEventListener(userLikeStatusListener); userWebVisitedStatusListener = null; userLikeStatusListener = null; userWebVisitedDataReference = null; userLikeDataReference = null; userVisitDataReference = null; } private void initializeMarketValueListeners() { // TODO move to sponsors having their own prices they are willing to pay out sponsorMarketValueEventListener = new ValueEventListener() { @Override public void onDataChange(@NonNull DataSnapshot dataSnapshot) { sponsorMarketValues = dataSnapshot.getValue(SponsorMarketValues.class); } @Override public void onCancelled(@NonNull DatabaseError databaseError) { } }; sponsorMarketValueReference = firebaseInst.getReference("sponsorMarketValues"); sponsorMarketValueReference.addValueEventListener(sponsorMarketValueEventListener); } private void handleLikeInteractions(boolean liked) { userLikeDataReference.setValue(liked); if (!likedTriggeredOnce) { // Store user points User user = UserManager.getInstance().getUser(); int newUserPoints = user.getPoints() + 1; // TODO get like/dislike market values DatabaseReference userReference = firebaseInst.getReference().child("users").child(firebaseAuth.getUid()); userReference.child("points").setValue(newUserPoints); // Show pop up window LayoutInflater inflater = (LayoutInflater) IndividualSponsorActivity.this.getSystemService(Context.LAYOUT_INFLATER_SERVICE); View layout = inflater.inflate(R.layout.sponsor_like_pop_up, null); ((TextView)layout.findViewById(R.id.pop_point_total)).setText(String.format("%d Points", 1)); // TODO get like/dislike market values final PopupWindow popupWindow = new PopupWindow(layout, ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT); popupWindow.showAtLocation(findViewById(R.id.activity_individual_sponsor_layout), Gravity.CENTER, 0, 0); // Dim the background final View container; if (popupWindow.getBackground() == null) { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M){ container = (View) popupWindow.getContentView().getParent(); } else { container = popupWindow.getContentView(); } } else { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) { container = (View) popupWindow.getContentView().getParent().getParent(); } else { container = (View) popupWindow.getContentView().getParent(); } } Context context = popupWindow.getContentView().getContext(); final WindowManager windowManager = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE); final WindowManager.LayoutParams layoutParams = (WindowManager.LayoutParams) container.getLayoutParams(); layoutParams.flags = WindowManager.LayoutParams.FLAG_DIM_BEHIND; layoutParams.dimAmount = 0.75f; windowManager.updateViewLayout(container, layoutParams); (layout.findViewById(R.id.pop_up_button)).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { // Un-dim the background layoutParams.dimAmount = 0.0f; windowManager.updateViewLayout(container, layoutParams); popupWindow.dismiss(); } }); } } private void handleWebsiteVisitInteraction() { userWebVisitedDataReference.setValue(true); if (!sponsorVisited) { // Store user points User user = UserManager.getInstance().getUser(); int newUserPoints = user.getPoints() + MarketingManager.getInstance().getUserSponsorMarketingValue(user, sponsorMarketValues); DatabaseReference userReference = firebaseInst.getReference().child("users").child(firebaseAuth.getUid()); userReference.child("points").setValue(newUserPoints); // Show pop up window LayoutInflater inflater = (LayoutInflater) IndividualSponsorActivity.this.getSystemService(Context.LAYOUT_INFLATER_SERVICE); View layout = inflater.inflate(R.layout.sponsor_visit_popup, null); ((TextView)layout.findViewById(R.id.pop_point_total)).setText(String.format("%d Points", 1)); // TODO get like/dislike market values final PopupWindow popupWindow = new PopupWindow(layout, ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT); popupWindow.showAtLocation(findViewById(R.id.activity_individual_sponsor_layout), Gravity.CENTER, 0, 0); // Dim the background final View container; if (popupWindow.getBackground() == null) { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M){ container = (View) popupWindow.getContentView().getParent(); } else { container = popupWindow.getContentView(); } } else { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) { container = (View) popupWindow.getContentView().getParent().getParent(); } else { container = (View) popupWindow.getContentView().getParent(); } } Context context = popupWindow.getContentView().getContext(); final WindowManager windowManager = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE); final WindowManager.LayoutParams layoutParams = (WindowManager.LayoutParams) container.getLayoutParams(); layoutParams.flags = WindowManager.LayoutParams.FLAG_DIM_BEHIND; layoutParams.dimAmount = 0.75f; windowManager.updateViewLayout(container, layoutParams); (layout.findViewById(R.id.pop_up_button)).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { // Un-dim the background layoutParams.dimAmount = 0.0f; windowManager.updateViewLayout(container, layoutParams); popupWindow.dismiss(); visitSponsorSite(sponsor.getUrl()); } }); } else { visitSponsorSite(sponsor.getUrl()); } } private void visitSponsorSite(String url) { Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url)); intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); startActivity(intent); } private void updateWebsiteVisitStatus(boolean visited) { if (visited) { websiteImageView.setBackgroundColor(Color.parseColor("#16a916")); } } private void updateLikeStatuses(boolean liked) { if (liked) { likeButton.setBackgroundColor(Color.parseColor("#5167ca")); dislikeButton.setBackgroundColor(Color.parseColor("#FFC1BFBF")); } else { likeButton.setBackgroundColor(Color.parseColor("#FFC1BFBF")); dislikeButton.setBackgroundColor(Color.parseColor("#9e090e")); } } } <file_sep>package com.marshmallow.beacon.ui.contacts; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.content.IntentFilter; import android.os.Bundle; import android.os.SystemClock; import android.support.annotation.NonNull; import android.support.v7.app.AppCompatActivity; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.LinearLayout; import android.widget.TextView; import android.widget.Toast; import com.google.firebase.database.DataSnapshot; import com.google.firebase.database.DatabaseError; import com.google.firebase.database.DatabaseReference; import com.google.firebase.database.FirebaseDatabase; import com.google.firebase.database.ValueEventListener; import com.marshmallow.beacon.R; import com.marshmallow.beacon.UserManager; import com.marshmallow.beacon.models.contacts.Request; /** * Created by George on 7/28/2018. */ public class NewContactActivity extends AppCompatActivity { // GUI handles private EditText contactUserNameEditText; private Button addContactButton; private LinearLayout progressBarLinearLayout; private TextView progressBarText; // Firebase private FirebaseDatabase firebaseInst; // Username text private String username; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_add_new_contact); // Firebase firebaseInst = FirebaseDatabase.getInstance(); // Set GUI handles contactUserNameEditText = findViewById(R.id.new_contact_username_edit_text); addContactButton = findViewById(R.id.add_contact_button); progressBarLinearLayout = findViewById(R.id.new_contact_progress_bar_layout); progressBarText = findViewById(R.id.new_contact_progress_bar_text); addContactButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if (isValidEntry()) { if (notAlreadyAContact() && notSearchingThyself()) { showProgressBar("Submitting contact request..."); username = contactUserNameEditText.getText().toString(); final Request request = new Request(username, UserManager.getInstance().getUser().getUsername()); firebaseInst.getReference().child("users").orderByChild("username").equalTo(request.getTo()).addListenerForSingleValueEvent(new ValueEventListener() { @Override public void onDataChange(@NonNull DataSnapshot dataSnapshot) { // If user exists submit the request! if (dataSnapshot.exists()) { // Create Request model and submit to database DatabaseReference requestsReference = firebaseInst.getReference("requests"); String requestUniqueId = requestsReference.child("requests").push().getKey(); if (requestUniqueId != null) { request.setUid(requestUniqueId); requestsReference.child(requestUniqueId).setValue(request); contactRequestSubmitSucceeded(); } else { requestCreationFailed("Unable to create new request"); } } else { contactRequestContactNotFound(); } } @Override public void onCancelled(@NonNull DatabaseError databaseError) { contactRequestSubmitFailed(databaseError.getMessage()); } }); } } } }); } private boolean notSearchingThyself() { String requestedUsername = contactUserNameEditText.getText().toString(); if (requestedUsername.equals(UserManager.getInstance().getUser().getUsername())) { Toast.makeText(this, "You cannot add yourself!", Toast.LENGTH_SHORT).show(); return false; } else { return true; } } private boolean notAlreadyAContact() { String requestedUsername = contactUserNameEditText.getText().toString(); if (UserManager.getInstance().getUser().getRolodex() != null && UserManager.getInstance().getUser().getRolodex().getUsernames().contains(requestedUsername)) { Toast.makeText(this, "You are already connected to " + requestedUsername, Toast.LENGTH_SHORT).show(); return false; } else { return true; } } private void requestCreationFailed(String failureString) { hideProgressBar(); Toast.makeText(this, failureString, Toast.LENGTH_SHORT).show(); } private boolean isValidEntry() { if (contactUserNameEditText.toString().isEmpty()) { contactUserNameEditText.setError("username can't be empty"); return false; } else { return true; } } private void contactRequestContactNotFound() { hideProgressBar(); Toast.makeText(this, username + " is not an existing user!", Toast.LENGTH_SHORT).show(); } private void contactRequestSubmitFailed(String failureString) { hideProgressBar(); Toast.makeText(this, "Contact Request Failed: " + failureString, Toast.LENGTH_SHORT).show(); } private void contactRequestSubmitSucceeded() { Toast.makeText(this, "Contact Request Submitted!", Toast.LENGTH_SHORT).show(); progressBarLinearLayout.setVisibility(View.GONE); SystemClock.sleep(300); finish(); } public void showProgressBar(String progressBarText) { // Hide all views in this layout and only show the progress bar linear layout findViewById(R.id.contact_username_title).setVisibility(View.INVISIBLE); contactUserNameEditText.setVisibility(View.INVISIBLE); addContactButton.setVisibility(View.INVISIBLE); this.progressBarText.setText(progressBarText); progressBarLinearLayout.setVisibility(View.VISIBLE); } public void hideProgressBar() { findViewById(R.id.contact_username_title).setVisibility(View.VISIBLE); contactUserNameEditText.setVisibility(View.VISIBLE); addContactButton.setVisibility(View.VISIBLE); // Hide progress bar progressBarLinearLayout.setVisibility(View.GONE); } } <file_sep>package com.marshmallow.beacon.models; import com.marshmallow.beacon.UserManager; import com.marshmallow.beacon.models.user.User; import org.junit.Test; import static junit.framework.Assert.assertEquals; /** * Created by George on 9/7/2018. */ public class UserManagerTest { @Test public void singletonTest() { UserManager userManager1 = UserManager.getInstance(); UserManager userManager2 = UserManager.getInstance(); assertEquals(userManager1, userManager2); } @Test public void userTest() { User user = new User(); UserManager.getInstance().setUser(user); assertEquals(user, UserManager.getInstance().getUser()); } } <file_sep>package com.marshmallow.beacon.models.marketing; import android.os.SystemClock; import com.marshmallow.beacon.models.marketing.SurveyResponseItem; import com.marshmallow.beacon.models.marketing.SurveyResult; import com.marshmallow.beacon.models.marketing.UserMarketDataSnapshot; import org.junit.Test; import java.util.Vector; import static junit.framework.Assert.assertEquals; /** * Created by George on 9/7/2018. */ public class SurveyResultTest { private SurveyResult surveyResult = new SurveyResult(); @Test public void timestampTest() { long timestamp = System.currentTimeMillis(); surveyResult.setTimestamp(timestamp); assertEquals(timestamp, surveyResult.getTimestamp().longValue()); } @Test public void surveyResponseItemTest() { Vector<SurveyResponseItem> surveyResponseItems = new Vector<>(); surveyResult.setSurveyResponseItems(surveyResponseItems); assertEquals(surveyResponseItems, surveyResult.getSurveyResponseItems()); } @Test public void userMarketDataSnapshot() { UserMarketDataSnapshot userMarketDataSnapshot = new UserMarketDataSnapshot(); surveyResult.setUserMarketDataSnapshot(userMarketDataSnapshot); assertEquals(userMarketDataSnapshot, surveyResult.getUserMarketDataSnapshot()); } } <file_sep>package com.marshmallow.beacon.models.marketing; import com.marshmallow.beacon.models.marketing.SponsorMarketValues; import org.junit.Test; import static junit.framework.Assert.assertEquals; /** * Created by George on 9/7/2018. */ public class SponsorMarketValuesTest { private SponsorMarketValues sponsorMarketValues = new SponsorMarketValues(); @Test public void firstNameValueTest() { sponsorMarketValues.setFirstNameValue(5); assertEquals(5, sponsorMarketValues.getFirstNameValue().intValue()); } @Test public void lastNameValueTest() { sponsorMarketValues.setLastNameValue(7); assertEquals(7, sponsorMarketValues.getLastNameValue().intValue()); } @Test public void geolocationValueTest() { sponsorMarketValues.setGeolocationValue(8); assertEquals(8, sponsorMarketValues.getGeolocationValue().intValue()); } @Test public void emailValueTest() { sponsorMarketValues.setEmailValue(1); assertEquals(1, sponsorMarketValues.getEmailValue().intValue()); } @Test public void birthdayValueTest() { sponsorMarketValues.setBirthdayValue(22); assertEquals(22, sponsorMarketValues.getBirthdayValue().intValue()); } @Test public void cityValueTest() { sponsorMarketValues.setCityValue(382); assertEquals(382, sponsorMarketValues.getCityValue().intValue()); } @Test public void stateValueTest() { sponsorMarketValues.setStateValue(99); assertEquals(99, sponsorMarketValues.getStateValue().intValue()); } @Test public void phoneValueTest() { sponsorMarketValues.setPhoneValue(302); assertEquals(302, sponsorMarketValues.getPhoneValue().intValue()); } } <file_sep>package com.marshmallow.beacon.ui.contacts; import android.os.Bundle; import android.support.annotation.NonNull; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.Button; import android.widget.TextView; import com.google.firebase.auth.FirebaseAuth; import com.google.firebase.database.DatabaseReference; import com.google.firebase.database.FirebaseDatabase; import com.marshmallow.beacon.ContactRequestManager; import com.marshmallow.beacon.R; import com.marshmallow.beacon.UserManager; import com.marshmallow.beacon.models.contacts.Request; import com.marshmallow.beacon.models.user.Rolodex; import java.util.Vector; /** * Created by George on 7/29/2018. */ public class OutgoingContactRequestsActivity extends AppCompatActivity { // GUI handles private RecyclerView outgoingRequestsRecyclerView; private RecyclerView.LayoutManager outgoingRequestsLayoutManager; private OutgoingContactRequestsAdapter outgoingContactRequestsAdapter; private Vector<Request> outgoingRequests; // Firebase private FirebaseAuth firebaseAuth; private FirebaseDatabase firebaseInst; // Models private ContactRequestManager contactRequestManager; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_outgoing_contact_requests); // Firebase firebaseAuth = FirebaseAuth.getInstance(); firebaseInst = FirebaseDatabase.getInstance(); // Model contactRequestManager = ContactRequestManager.getInstance(); // GUI handle instantiation outgoingRequestsRecyclerView = findViewById(R.id.outgoing_request_recycler_view); outgoingRequestsLayoutManager = new LinearLayoutManager(this); outgoingRequestsRecyclerView.setLayoutManager(outgoingRequestsLayoutManager); outgoingRequests = contactRequestManager.getOutgoingRequests(); outgoingContactRequestsAdapter = new OutgoingContactRequestsAdapter(outgoingRequests); outgoingRequestsRecyclerView.setAdapter(outgoingContactRequestsAdapter); } public class OutgoingContactRequestsAdapter extends RecyclerView.Adapter<OutgoingContactRequestsAdapter.OutgoingContactRequestHolder> { private Vector<Request> outgoingRequests; public OutgoingContactRequestsAdapter(Vector<Request> outgoingRequests) { this.outgoingRequests = outgoingRequests; } @NonNull @Override public OutgoingContactRequestHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) { View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.outgoing_request_basic, parent, false); return new OutgoingContactRequestHolder(v); } @Override public void onBindViewHolder(@NonNull final OutgoingContactRequestHolder holder, final int position) { final Request outgoingRequest = outgoingRequests.get(position); Request.Status status = outgoingRequest.getStatus(); holder.requestStatus.setText(status.name()); holder.requestUsername.setText(outgoingRequest.getTo()); switch(status) { case PENDING: holder.requestActionButton.setText(R.string.outgoing_request_action_button_cancel_text); break; case ACCEPTED: holder.requestActionButton.setText(R.string.outgoing_request_action_button_confirm_text); break; case DECLINED: holder.requestActionButton.setText(R.string.outgoing_request_action_button_clear_text); break; } holder.requestActionButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { switch (outgoingRequest.getStatus()) { case PENDING: cancelRequest(outgoingRequest); break; case ACCEPTED: confirmRequest(outgoingRequest); break; case DECLINED: clearRequest(outgoingRequest); break; } } }); } @Override public int getItemCount() { return outgoingRequests.size(); } public class OutgoingContactRequestHolder extends RecyclerView.ViewHolder { public TextView requestStatus; public TextView requestUsername; public Button requestActionButton; public OutgoingContactRequestHolder(View v) { super(v); requestStatus = v.findViewById(R.id.request_status_text); requestUsername = v.findViewById(R.id.request_username); requestActionButton = v.findViewById(R.id.outgoing_request_action_button); } } } private void confirmRequest(Request request) { DatabaseReference databaseReference = firebaseInst.getReference(); databaseReference.child("requests").child(request.getUid()).removeValue(); Rolodex rolodex = UserManager.getInstance().getUser().getRolodex(); if (rolodex == null) { rolodex = new Rolodex(); } rolodex.addUsername(request.getTo()); if (firebaseAuth.getUid() != null) { databaseReference.child("users").child(firebaseAuth.getUid()).child("rolodex").setValue(rolodex); } } private void cancelRequest(Request request) { DatabaseReference databaseReference = firebaseInst.getReference(); databaseReference.child("requests").child(request.getUid()).removeValue(); } private void clearRequest(Request request) { cancelRequest(request); } } <file_sep>package com.marshmallow.beacon.ui.user; import android.content.Intent; import android.os.Bundle; import android.support.annotation.NonNull; import android.support.v7.app.AppCompatActivity; import android.text.TextUtils; import android.view.View; import android.widget.Button; import android.widget.LinearLayout; import android.widget.TextView; import android.widget.Toast; import com.google.android.gms.tasks.OnCompleteListener; import com.google.android.gms.tasks.Task; import com.google.firebase.auth.AuthResult; import com.google.firebase.auth.FirebaseAuth; import com.google.firebase.database.DataSnapshot; import com.google.firebase.database.DatabaseError; import com.google.firebase.database.DatabaseReference; import com.google.firebase.database.FirebaseDatabase; import com.google.firebase.database.ValueEventListener; import com.marshmallow.beacon.R; import com.marshmallow.beacon.UserManager; import com.marshmallow.beacon.models.user.User; public class LoginActivity extends AppCompatActivity { // GUI handles private TextView emailTextEntry; private TextView passwordTextEntry; private LinearLayout progressBarLinearLayout; private TextView progressBarText; private Button createAccountButton; private Button loginButton; // Firebase private FirebaseAuth firebaseAuth = null; private FirebaseDatabase firebaseInst; private DatabaseReference userReference; private ValueEventListener userValueEventListener; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_login); // Instantiate Firebase firebaseAuth = FirebaseAuth.getInstance(); firebaseInst = FirebaseDatabase.getInstance(); // Set GUI handles emailTextEntry = findViewById(R.id.email_text); passwordTextEntry = findViewById(R.id.password_text); progressBarLinearLayout = findViewById(R.id.progress_bar_layout); progressBarText = findViewById(R.id.progress_bar_text); createAccountButton = findViewById(R.id.create_account_button); loginButton = findViewById(R.id.sign_in_button); createAccountButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { final String email = emailTextEntry.getText().toString(); String password = passwordTextEntry.getText().toString(); if (emailIsValid(email) && passwordIsValid(password)) { showProgressBar("Creating Account..."); firebaseAuth.createUserWithEmailAndPassword(email, password).addOnCompleteListener(new OnCompleteListener<AuthResult>() { @Override public void onComplete(@NonNull Task<AuthResult> task) { if (task.isSuccessful()) { User user = new User(email); UserManager.getInstance().setUser(user); storeNewUser(user); accountCreationSuccess(); } else { if (task.getException() != null) { accountCreationFailed(task.getException().getMessage()); } } } }); } } }); loginButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { String email = emailTextEntry.getText().toString(); String password = passwordTextEntry.getText().toString(); if (emailIsValid(email) && passwordIsValid(password)) { showProgressBar("Logging in..."); firebaseAuth.signInWithEmailAndPassword(email, password).addOnCompleteListener(new OnCompleteListener<AuthResult>() { @Override public void onComplete(@NonNull Task<AuthResult> task) { if (task.isSuccessful()) { initializeUserListener(); } else { if (task.getException() != null) { signInFailed(task.getException().getMessage()); } } } }); } } }); } private void storeNewUser(User user) { DatabaseReference databaseReference = firebaseInst.getReference("users"); if (firebaseAuth.getUid() != null) { databaseReference.child(firebaseAuth.getUid()).setValue(user); } } public Boolean emailIsValid(String email) { if (TextUtils.isEmpty(email)) { emailTextEntry.setError("Email Required"); return false; } else { emailTextEntry.setError(null); return true; } } public Boolean passwordIsValid(String password) { if (TextUtils.isEmpty(password)) { passwordTextEntry.setError("Empty Password Not Allowed"); return false; } else { passwordTextEntry.setError(null); return true; } } public void initializeUserListener() { userValueEventListener = new ValueEventListener() { @Override public void onDataChange(@NonNull DataSnapshot dataSnapshot) { UserManager.getInstance().setUser(dataSnapshot.getValue(User.class)); accountLoadingSucceeded(); } @Override public void onCancelled(@NonNull DatabaseError databaseError) { accountLoadingFailed(databaseError.getMessage()); } }; if (firebaseAuth.getUid() != null) { userReference = firebaseInst.getReference("users").child(firebaseAuth.getUid()); userReference.child("signedIn").setValue(true); userReference.addValueEventListener(userValueEventListener); } } private void removeListeners() { userReference.removeEventListener(userValueEventListener); userValueEventListener = null; } public void accountCreationSuccess() { hideProgressBar(); Intent intent = new Intent(this, WelcomePrimaryActivity.class); startActivity(intent); } public void accountCreationFailed(String failureString) { hideProgressBar(); Toast.makeText(this, "Account Creation Failed: " + failureString, Toast.LENGTH_SHORT).show(); } public void signInSucceeded() { // TODO handle intermediary screen till user data has loaded } public void signInFailed(String failureString) { hideProgressBar(); Toast.makeText(this, "Sign In Failed: " + failureString, Toast.LENGTH_SHORT).show(); } public void accountLoadingSucceeded() { removeListeners(); hideProgressBar(); if (UserManager.getInstance().getUser().getAccountCreationComplete()) { Intent intent = new Intent(this, HomeActivity.class); startActivity(intent); } else { Intent intent = new Intent(this, WelcomePrimaryActivity.class); startActivity(intent); } } public void accountLoadingFailed(String failureString) { hideProgressBar(); Toast.makeText(this, "Loading account on application launch failed: " + failureString, Toast.LENGTH_SHORT).show(); } public void showProgressBar(String progressBarText) { // Hide all views in this layout and only show the progress bar linear layout findViewById(R.id.login_button_layout).setVisibility(View.GONE); findViewById(R.id.account_info_layout).setVisibility(View.GONE); this.progressBarText.setText(progressBarText); progressBarLinearLayout.setVisibility(View.VISIBLE); } public void hideProgressBar() { progressBarLinearLayout.setVisibility(View.GONE); findViewById(R.id.login_button_layout).setVisibility(View.VISIBLE); findViewById(R.id.account_info_layout).setVisibility(View.VISIBLE); } } <file_sep>package com.marshmallow.beacon.models.marketing; import com.marshmallow.beacon.models.marketing.SponsorVisitEvent; import com.marshmallow.beacon.models.marketing.UserMarketDataSnapshot; import org.junit.Test; import static junit.framework.Assert.assertEquals; /** * Created by George on 9/7/2018. */ public class SponsorVisitEventTest { @Test public void creationTest() { UserMarketDataSnapshot userMarketDataSnapshot = new UserMarketDataSnapshot(); SponsorVisitEvent sponsorVisitEvent = new SponsorVisitEvent(userMarketDataSnapshot); assertEquals(userMarketDataSnapshot, sponsorVisitEvent.getUserMarketDataSnapshot()); } @Test public void userMarketDataSnapshotTest() { SponsorVisitEvent sponsorVisitEvent = new SponsorVisitEvent(); UserMarketDataSnapshot userMarketDataSnapshot = new UserMarketDataSnapshot(); sponsorVisitEvent.setUserMarketDataSnapshot(userMarketDataSnapshot); assertEquals(userMarketDataSnapshot, sponsorVisitEvent.getUserMarketDataSnapshot()); } @Test public void timestampTest() { SponsorVisitEvent sponsorVisitEvent = new SponsorVisitEvent(); long timestamp = System.currentTimeMillis(); sponsorVisitEvent.setTimestamp(timestamp); assertEquals(timestamp, sponsorVisitEvent.getTimestamp().longValue()); } } <file_sep>package com.marshmallow.beacon.models.marketing; import com.marshmallow.beacon.models.marketing.Sponsor; import org.junit.Test; import static junit.framework.Assert.assertEquals; import static junit.framework.Assert.assertTrue; /** * Created by George on 9/7/2018. */ public class SponsorTest { private Sponsor sponsor = new Sponsor(); @Test public void nameTest() { sponsor.setName("sponsor"); assertEquals("sponsor", sponsor.getName()); } @Test public void uidTest() { sponsor.setUid("12345"); assertEquals("12345", sponsor.getUid()); } @Test public void pictureTest() { sponsor.setPicture("alfihwefih"); assertEquals("alfihwefih", sponsor.getPicture()); } @Test public void urlTest() { sponsor.setUrl("hello.com"); assertEquals("hello.com", sponsor.getUrl()); } @Test public void pictureIsNullTest() { sponsor.setPicture(null); assertEquals(null, sponsor.getProfilePictureBitmap()); } } <file_sep>package com.marshmallow.beacon.ui.user; import android.content.Intent; import android.graphics.Bitmap; import android.net.Uri; import android.os.Bundle; import android.provider.MediaStore; import android.support.v7.app.AppCompatActivity; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.ImageButton; import android.widget.Toast; import com.google.firebase.auth.FirebaseAuth; import com.google.firebase.database.DatabaseReference; import com.google.firebase.database.FirebaseDatabase; import com.marshmallow.beacon.R; import com.marshmallow.beacon.UserManager; import com.marshmallow.beacon.models.user.User; import com.marshmallow.beacon.ui.ProfileUpdateManager; import com.marshmallow.beacon.ui.marketing.EditMarketingActivity; import java.io.IOException; /** * Created by George on 8/2/2018. */ public class EditProfileActivity extends AppCompatActivity { // GUI handles private ImageButton profileImageButton; private EditText firstNameEditText; private EditText lastNameEditText; private EditText birthdayEditText; private EditText cityEditText; private EditText stateEditText; private EditText phoneEditText; private Button backButton; private Button nextButton; // Firebase FirebaseAuth firebaseAuth; FirebaseDatabase firebaseInst; // Image handling private int PICK_IMAGE_REQUEST = 1; // TODO change to false once images are better private boolean validImage = true; // Editable user private User editableUser; // Activity handle private EditProfileActivity self; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_edit_profile); // Firebase instantiation firebaseAuth = FirebaseAuth.getInstance(); firebaseInst = FirebaseDatabase.getInstance(); // GUI instantiation profileImageButton = findViewById(R.id.edit_profile_image_button); firstNameEditText = findViewById(R.id.edit_profile_first_name_edit_text); lastNameEditText = findViewById(R.id.edit_profile_last_name_edit_text); birthdayEditText = findViewById(R.id.edit_profile_birthday_edit_text); cityEditText = findViewById(R.id.edit_profile_city_edit_text); stateEditText = findViewById(R.id.edit_profile_state_edit_text); phoneEditText = findViewById(R.id.edit_profile_phone_number_edit_text); backButton = findViewById(R.id.edit_profile_back_button); nextButton = findViewById(R.id.edit_profile_next_button); // User instantiation editableUser = UserManager.getInstance().getUser(); // Activity handle self = this; // Image button initialization if (editableUser.getProfilePictureBitmap() != null) { validImage = true; profileImageButton.setImageBitmap(editableUser.getProfilePictureBitmap()); } // Edit text setup initializeTextFields(); profileImageButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent intent = new Intent(); intent.setType("image/*"); intent.setAction(Intent.ACTION_GET_CONTENT); startActivityForResult(Intent.createChooser(intent, "Select Picture"), PICK_IMAGE_REQUEST); } }); backButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { ProfileUpdateManager.getInstance().removeProfileUpdateActivity(self); finish(); } }); nextButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if (profileIsValid()) { editableUser.getFirstName().setValue(firstNameEditText.getText().toString()); editableUser.getLastName().setValue(lastNameEditText.getText().toString()); editableUser.getBirthday().setValue(birthdayEditText.getText().toString()); editableUser.getCity().setValue(cityEditText.getText().toString()); editableUser.getState().setValue(stateEditText.getText().toString()); editableUser.getPhoneNumber().setValue(phoneEditText.getText().toString()); Intent intent = new Intent(getApplicationContext(), EditMarketingActivity.class); Intent activityStartIntent = getIntent(); if (activityStartIntent.hasExtra("creatingAccount")) { intent.putExtra("creatingAccount", activityStartIntent.getBooleanExtra("creatingAccount", false)); } ProfileUpdateManager.getInstance().addProfileUpdateActivity(self); startActivity(intent); } else { Toast.makeText(getApplicationContext(), "Please fill out all profile entries", Toast.LENGTH_SHORT).show(); } } }); } private void initializeTextFields() { firstNameEditText.setText(editableUser.getFirstName().getValue()); lastNameEditText.setText(editableUser.getLastName().getValue()); birthdayEditText.setText(editableUser.getBirthday().getValue()); cityEditText.setText(editableUser.getCity().getValue()); stateEditText.setText(editableUser.getState().getValue()); phoneEditText.setText(editableUser.getPhoneNumber().getValue()); } private boolean profileIsValid() { boolean profileIsValid = true; // TODO bring back profile pictures // if (!validImage) { // profileIsValid = false; // Toast.makeText(this, "Please select a profile picture", Toast.LENGTH_SHORT).show(); // } if (firstNameEditText.getText().toString().isEmpty()) { profileIsValid = false; firstNameEditText.setError("First name cannot be empty!"); } if (lastNameEditText.getText().toString().isEmpty()) { profileIsValid = false; lastNameEditText.setError("Last name cannot be empty!"); } if (birthdayEditText.getText().toString().isEmpty()) { profileIsValid = false; birthdayEditText.setError("Birthday name cannot be empty!"); } if (cityEditText.getText().toString().isEmpty()) { profileIsValid = false; cityEditText.setError("City name cannot be empty!"); } if (stateEditText.getText().toString().isEmpty()) { profileIsValid = false; stateEditText.setError("State name cannot be empty!"); } if (phoneEditText.getText().toString().isEmpty()) { profileIsValid = false; phoneEditText.setError("Phone number cannot be empty"); } return profileIsValid; } @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { if (requestCode == PICK_IMAGE_REQUEST && resultCode == RESULT_OK && data != null && data.getData() != null) { Uri uri = data.getData(); try { Bitmap bitmap = MediaStore.Images.Media.getBitmap(getContentResolver(), uri); profileImageButton.setImageBitmap(bitmap); editableUser.setProfilePictureFromBitmap(bitmap); } catch (IOException e) { e.printStackTrace(); } validImage = true; } } } <file_sep>package com.marshmallow.beacon.models.user; import com.marshmallow.beacon.models.user.DataPoint; import org.junit.Test; import static junit.framework.Assert.assertEquals; import static junit.framework.Assert.assertTrue; /** * Created by George on 9/7/2018. */ public class DataPointTest { private DataPoint dataPoint = new DataPoint(); @Test public void creation() { DataPoint dataPoint = new DataPoint("hello", false); assertEquals(false, dataPoint.getShared().booleanValue()); assertEquals("hello", dataPoint.getValue()); } @Test public void sharedTrueTest() { dataPoint.setShared(true); assertEquals(true, dataPoint.getShared().booleanValue()); } @Test public void sharedFalseTest() { dataPoint.setShared(false); assertEquals(false, dataPoint.getShared().booleanValue()); } @Test public void valueTest() { dataPoint.setValue("hello"); assertEquals("hello", dataPoint.getValue()); } } <file_sep>package com.marshmallow.beacon.ui; import android.content.Intent; import android.os.Bundle; import android.support.annotation.NonNull; import android.support.design.widget.BottomNavigationView; import android.support.v7.app.AppCompatActivity; import android.view.MenuItem; import com.marshmallow.beacon.R; import com.marshmallow.beacon.ui.contacts.ContactsActivity; import com.marshmallow.beacon.ui.marketing.SponsorsActivity; import com.marshmallow.beacon.ui.user.HomeActivity; /** * Created by George on 7/13/2018. */ public class BaseActivity extends AppCompatActivity { protected MainActivityTypes activityType; protected enum MainActivityTypes { HOME, CONTACTS, SPONSORS } @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); BottomNavigationView bottomNavigationView = findViewById(R.id.bottom_navigation); bottomNavigationView.setOnNavigationItemSelectedListener(new BottomNavigationView.OnNavigationItemSelectedListener() { @Override public boolean onNavigationItemSelected(@NonNull MenuItem item) { switch(item.getItemId()) { case R.id.home_button: if (activityType != MainActivityTypes.HOME) { finish(); } break; // case R.id.contacts_button: // if (activityType != MainActivityTypes.CONTACTS) { // if (activityType != MainActivityTypes.HOME) { // finish(); // } // // Intent contactsIntent = new Intent(getApplicationContext(), ContactsActivity.class); // startActivity(contactsIntent); // } // // break; case R.id.sponsors_button: if (activityType != MainActivityTypes.SPONSORS) { if (activityType != MainActivityTypes.HOME) { finish(); } Intent sponsorsIntent = new Intent(getApplicationContext(), SponsorsActivity.class); startActivity(sponsorsIntent); } break; } return true; } }); } } <file_sep>package com.marshmallow.beacon.login; import android.os.SystemClock; import android.support.test.espresso.action.ViewActions; import android.support.test.espresso.matcher.ViewMatchers; import android.support.test.rule.ActivityTestRule; import android.support.test.runner.AndroidJUnit4; import android.view.View; import com.marshmallow.beacon.R; import com.marshmallow.beacon.ui.marketing.SponsorsActivity; import com.marshmallow.beacon.ui.user.LoginActivity; import org.junit.Rule; import org.junit.Test; import org.junit.runner.RunWith; import static android.support.test.espresso.Espresso.onView; import static android.support.test.espresso.action.ViewActions.click; import static android.support.test.espresso.action.ViewActions.typeText; import static android.support.test.espresso.assertion.ViewAssertions.doesNotExist; import static android.support.test.espresso.assertion.ViewAssertions.matches; import static android.support.test.espresso.matcher.ViewMatchers.isDisplayed; import static android.support.test.espresso.matcher.ViewMatchers.withId; /** * Created by George on 9/13/2018. */ @RunWith(AndroidJUnit4.class) public class SponsorActivityTest { @Rule public ActivityTestRule<LoginActivity> loginActivityActivityTestRule = new ActivityTestRule<>(LoginActivity.class); @Test public void navigateToSponsorsPage() { // Login onView(ViewMatchers.withId(R.id.email_text)).perform(typeText("<EMAIL>"), ViewActions.closeSoftKeyboard()); onView(withId(R.id.password_text)).perform(typeText("<PASSWORD>"), ViewActions.closeSoftKeyboard()); onView(withId(R.id.sign_in_button)).perform(click()); // Wait till login is complete... SystemClock.sleep(20000); // Navigate to sponsors page onView(withId(R.id.sponsors_button)).perform(click()); SystemClock.sleep(5000); } } <file_sep>package com.marshmallow.beacon.models.marketing; import com.marshmallow.beacon.models.marketing.UserMarketDataSnapshot; import com.marshmallow.beacon.models.user.DataPoint; import com.marshmallow.beacon.models.user.User; import org.junit.Before; import org.junit.Test; import static junit.framework.Assert.assertEquals; /** * Created by George on 9/7/2018. */ public class UserMarketDataSnapshotTest { private UserMarketDataSnapshot userMarketDataSnapshot; @Before public void preTest() { User user = new User(); user.setFirstName(new DataPoint("George", true)); user.setLastName(new DataPoint("Kontos", true)); user.setBirthday(new DataPoint("6/15/1989", true)); user.setCity(new DataPoint("Des Plaines", true)); user.setState(new DataPoint("IL", true)); user.setPhoneNumber(new DataPoint("847", true)); user.setEmail(new DataPoint("<EMAIL>", true)); userMarketDataSnapshot = new UserMarketDataSnapshot(user); } @Test public void firstNameTest() { assertEquals("George", userMarketDataSnapshot.getFirstName()); } @Test public void lastNameTest() { assertEquals("Kontos", userMarketDataSnapshot.getLastName()); } @Test public void birthdayTest() { assertEquals("6/15/1989", userMarketDataSnapshot.getBirthday()); } @Test public void emailTest() { assertEquals("<EMAIL>", userMarketDataSnapshot.getEmail()); } @Test public void cityTest() { assertEquals("Des Plaines", userMarketDataSnapshot.getCity()); } @Test public void stateTest() { assertEquals("IL", userMarketDataSnapshot.getState()); } @Test public void phoneTest() { assertEquals("847", userMarketDataSnapshot.getPhone()); } @Test public void setFirstNameTest() { UserMarketDataSnapshot userMarketDataSnapshot = new UserMarketDataSnapshot(); userMarketDataSnapshot.setFirstName("Hey"); assertEquals("Hey", userMarketDataSnapshot.getFirstName()); } @Test public void setLastNameTest() { UserMarketDataSnapshot userMarketDataSnapshot = new UserMarketDataSnapshot(); userMarketDataSnapshot.setLastName("There"); assertEquals("There", userMarketDataSnapshot.getLastName()); } @Test public void setEmailTest() { UserMarketDataSnapshot userMarketDataSnapshot = new UserMarketDataSnapshot(); userMarketDataSnapshot.setEmail("<EMAIL>"); assertEquals("<EMAIL>", userMarketDataSnapshot.getEmail()); } @Test public void setBirthdayTest() { UserMarketDataSnapshot userMarketDataSnapshot = new UserMarketDataSnapshot(); userMarketDataSnapshot.setBirthday("123"); assertEquals("123", userMarketDataSnapshot.getBirthday()); } @Test public void setCityTest() { UserMarketDataSnapshot userMarketDataSnapshot = new UserMarketDataSnapshot(); userMarketDataSnapshot.setCity("funtown"); assertEquals("funtown", userMarketDataSnapshot.getCity()); } @Test public void setStateTest() { UserMarketDataSnapshot userMarketDataSnapshot = new UserMarketDataSnapshot(); userMarketDataSnapshot.setState("ID"); assertEquals("ID", userMarketDataSnapshot.getState()); } @Test public void setPhoneTest() { UserMarketDataSnapshot userMarketDataSnapshot = new UserMarketDataSnapshot(); userMarketDataSnapshot.setPhone("999"); assertEquals("999", userMarketDataSnapshot.getPhone()); } } <file_sep>package com.marshmallow.beacon.ui.marketing; import android.app.ActivityManager; import android.content.Context; import android.content.Intent; import android.os.Bundle; import android.support.annotation.NonNull; import android.support.v7.app.AppCompatActivity; import android.view.View; import android.widget.Button; import android.widget.CompoundButton; import android.widget.TextView; import android.widget.ToggleButton; import com.google.firebase.auth.FirebaseAuth; import com.google.firebase.database.DataSnapshot; import com.google.firebase.database.DatabaseError; import com.google.firebase.database.DatabaseReference; import com.google.firebase.database.FirebaseDatabase; import com.google.firebase.database.ValueEventListener; import com.marshmallow.beacon.MarketingManager; import com.marshmallow.beacon.R; import com.marshmallow.beacon.UserManager; import com.marshmallow.beacon.models.marketing.SponsorMarketValues; import com.marshmallow.beacon.models.marketing.SurveyMarketValues; import com.marshmallow.beacon.models.user.DataPoint; import com.marshmallow.beacon.models.user.User; import com.marshmallow.beacon.ui.ProfileUpdateManager; import com.marshmallow.beacon.ui.user.HomeActivity; /** * Created by George on 8/10/2018. */ public class EditMarketingActivity extends AppCompatActivity{ // GUI handles private TextView pointsPerSurveyTextView; private TextView pointsPerSponsorTextView; private ToggleButton geolocationToggleButton; private ToggleButton firstNameToggleButton; private ToggleButton lastNameToggleButton; private ToggleButton birthdayToggleButton; private ToggleButton cityToggleButton; private ToggleButton stateToggleButton; private ToggleButton phoneToggleButton; private Button backButton; private Button submitButton; // Firebase private FirebaseAuth firebaseAuth; private FirebaseDatabase firebaseInst; private DatabaseReference sponsorMarketValueReference; private ValueEventListener sponsorMarketValueEventListener; private DatabaseReference surveyMarketValueReference; private ValueEventListener surveyMarketValueEventListener; // Editable user private User editableUser; // Marketing models private SponsorMarketValues sponsorMarketValues; private SurveyMarketValues surveyMarketValues; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_edit_marketing); // Firebase instantiation firebaseAuth = FirebaseAuth.getInstance(); firebaseInst = FirebaseDatabase.getInstance(); // GUI instantiation pointsPerSponsorTextView = findViewById(R.id.points_per_sponsor_text_view); pointsPerSurveyTextView = findViewById(R.id.points_per_survey_text_view); geolocationToggleButton = findViewById(R.id.geolocation_toggle_button); firstNameToggleButton = findViewById(R.id.first_name_toggle_button); lastNameToggleButton = findViewById(R.id.last_name_toggle_button); birthdayToggleButton = findViewById(R.id.birthday_toggle_button); cityToggleButton = findViewById(R.id.city_toggle_button); stateToggleButton = findViewById(R.id.state_toggle_button); phoneToggleButton = findViewById(R.id.phone_toggle_button); backButton = findViewById(R.id.edit_marketing_back_button); submitButton = findViewById(R.id.edit_marketing_submit_button); // User instantiation editableUser = UserManager.getInstance().getUser(); initializeEditProfileRelation(geolocationToggleButton, editableUser.getGeolocationOn()); initializeEditProfileRelation(firstNameToggleButton, editableUser.getFirstName()); initializeEditProfileRelation(lastNameToggleButton, editableUser.getLastName()); initializeEditProfileRelation(birthdayToggleButton, editableUser.getBirthday()); initializeEditProfileRelation(cityToggleButton, editableUser.getCity()); initializeEditProfileRelation(stateToggleButton, editableUser.getState()); initializeEditProfileRelation(phoneToggleButton, editableUser.getPhoneNumber()); // Set up listeners for market values initializeMarketValueListeners(); backButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { finish(); } }); submitButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { submitProfileUpdates(); ProfileUpdateManager.getInstance().destroyProfileUpdateActivities(); finish(); } }); } @Override public void finish() { super.finish(); Intent activityStartIntent = getIntent(); if (activityStartIntent.hasExtra("creatingAccount") && activityStartIntent.getBooleanExtra("creatingAccount", false)) { Intent intent = new Intent(getApplicationContext(), HomeActivity.class); startActivity(intent); } } private void submitProfileUpdates() { DatabaseReference userReference = firebaseInst.getReference("users"); editableUser.setAccountCreationComplete(true); if (firebaseAuth.getUid() != null) { userReference.child(firebaseAuth.getUid()).setValue(editableUser); } } private void initializeMarketValueListeners() { sponsorMarketValueEventListener = new ValueEventListener() { @Override public void onDataChange(@NonNull DataSnapshot dataSnapshot) { sponsorMarketValues = dataSnapshot.getValue(SponsorMarketValues.class); updateUserMarketingValue(); } @Override public void onCancelled(@NonNull DatabaseError databaseError) { } }; surveyMarketValueEventListener = new ValueEventListener() { @Override public void onDataChange(@NonNull DataSnapshot dataSnapshot) { surveyMarketValues = dataSnapshot.getValue(SurveyMarketValues.class); updateUserMarketingValue(); } @Override public void onCancelled(@NonNull DatabaseError databaseError) { } }; sponsorMarketValueReference = firebaseInst.getReference("sponsorMarketValues"); sponsorMarketValueReference.addValueEventListener(sponsorMarketValueEventListener); surveyMarketValueReference = firebaseInst.getReference("surveyMarketValues"); surveyMarketValueReference.addValueEventListener(surveyMarketValueEventListener); } private void initializeEditProfileRelation(ToggleButton toggleButton, final DataPoint dataPoint) { toggleButton.setChecked(dataPoint.getShared()); toggleButton.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() { @Override public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { dataPoint.setShared(isChecked); updateUserMarketingValue(); } }); } private void updateUserMarketingValue() { if (sponsorMarketValues != null) { pointsPerSponsorTextView.setText(MarketingManager.getInstance().getUserSponsorMarketingValue(editableUser, sponsorMarketValues).toString()); } if (surveyMarketValues != null) { pointsPerSurveyTextView.setText(MarketingManager.getInstance().getUserSurveyMarketingValue(editableUser, surveyMarketValues).toString()); } } }
b5e571a14bd806b9892872ebefc16328bd95f61c
[ "Java" ]
23
Java
gkontos89/Beacon
b260ec022827d1274e148f2ad56f68786dc80708
8675a604b887b59edbe065e3827e21d9147e1631
refs/heads/master
<file_sep>This project was bootstrapped with [Create React App](https://github.com/facebook/create-react-app). ## References * https://www.robinwieruch.de/react-hooks-fetch-data <file_sep>import React, {Fragment, useState, useEffect} from 'react'; import axios from 'axios'; const Main = () => { const BASE_URL = 'https://hn.algolia.com/api/v1/search'; const [data, setData] = useState({hits: []}); const [query, setQuery] = useState(''); const [url, setUrl] = useState(`${BASE_URL}?query=${query}`) const [isLoading, setIsLoading] = useState(false); useEffect(() => { const fetchData = async () => { setIsLoading(true); const result = await axios({url}); setData(result.data); setIsLoading(false); }; fetchData() },[url]); return( <Fragment> <div hidden={!isLoading} >Loading...</div> <input type="text" value={query} onChange={e => setQuery(e.target.value)}/> <button type="button" onClick={() => setUrl(`${BASE_URL}?query=${query}`)}>Search</button> <hr/> <ul> {data.hits.map(item => <li key={item.objectID}> <a href={item.url}>{item.title}</a> </li> )} </ul> </Fragment> ) } export default Main;
24f1103650f0948d22ea68f6ce8dc45b92592ab9
[ "Markdown", "JavaScript" ]
2
Markdown
flzpenteado/react-hook-fetch-data
5c4220b741d19b47a71c51ccf888e65e5c4245c5
b606595397b5f5c78d9710a649ab8dfcb8ee2960
refs/heads/master
<file_sep><?php require_once __DIR__ . '/../../models/User.php'; $user = new User; $user->username = "wyattb"; $user->email = '<EMAIL>'; $user->password = $_ENV['USER_PASS']; $user->date_joined = '2016-10-06'; $user->image_url = '/img/default_profile_img.jpg'; $user->save(); $user = new User; $user->username = "justinr"; $user->email = '<EMAIL>'; $user->password = $_ENV['USER_<PASSWORD>']; $user->date_joined = '2016-10-06'; $user->image_url = '/img/default_profile_img.jpg'; $user->save(); $user = new User; $user->username = "mittsyt"; $user->email = '<EMAIL>'; $user->password = $_ENV['<PASSWORD>']; $user->date_joined = '2016-10-06'; $user->image_url = '/img/default_profile_img.jpg'; $user->save(); $user = new User; $user->username = "guestSeller"; $user->email = '<EMAIL>'; $user->password = $_ENV['<PASSWORD>']; $user->date_joined = '2016-10-06'; $user->image_url = '/img/default_profile_img.jpg'; $user->save(); $user = new User; $user->username = "guestBuyer"; $user->email = '<EMAIL>'; $user->password = $_ENV['<PASSWORD>']; $user->date_joined = '2016-10-06'; $user->image_url = '/img/default_profile_img.jpg'; $user->save(); <file_sep><div class="container"> <section id="login"> <div class="row"> <h1 class="section-title text-center">Login</h1> <div class="col-md-6 col-md-offset-3"> <!-- checks username and password, if incorrect throws an error --> <?php if (isset($_SESSION['ERROR_MESSAGE'])) : ?> <div class="alert alert-danger"> <p class="error"><?= $_SESSION['ERROR_MESSAGE']; ?></p> </div> <?php unset($_SESSION['ERROR_MESSAGE']); ?> <?php endif; ?> <!-- checking to see if user is already signed in, if so success --> <?php if (isset($_SESSION['SUCCESS_MESSAGE'])) : ?> <div class="alert alert-success"> <p class="success"><?= $_SESSION['SUCCESS_MESSAGE']; ?></p> </div> <?php unset($_SESSION['SUCCESS_MESSAGE']); ?> <?php endif; ?> <!-- LOGIN FORM --> <form method="POST" action="" data-validation data-required-message="This field is required" class="text-center"> <!-- checks to see if you are logged in --> <?php if (Auth::check()) { echo '<h3>Login Successful</h3>'; } ?> <!-- email --> <div class="form-group"> <input type="text" class="form-control" id="email" name="email" placeholder="Email" data-required> </div> <!-- password --> <div class="form-group"> <input type="<PASSWORD>" class="form-control" id="password" name="password" placeholder="<PASSWORD>" data-required> </div> <div class="row"> <!-- login --> <div class="col-xs-6 col-sm-6 col-md-6 col-lg-6 text-center"> <button type="submit" class="btn btn-primary loginButtons">Login</button> </div> <!-- signup --> <div class="col-xs-6 col-sm-6 col-md-6 col-lg-6 text-center"> <a href="/signup" class="btn btn-success loginButtons">Go To Signup</a> </div> </div> </form> <!-- closes form --> </div> <!-- closing div for col-md-6 --> </div> <!-- closes row --> </section> <!-- closes section login --> </div> <!-- closes container --> <file_sep><div class="container"> <section id="login"> <div class="row"> <h1 class="section-title text-center">Create Your Profile</h1> <div class="col-md-6 col-md-offset-3"> <!-- checks username and password, if incorrect throws an error --> <?php if (isset($_SESSION['ERROR_MESSAGE'])) : ?> <div class="alert alert-danger"> <p class="error"><?= $_SESSION['ERROR_MESSAGE']; ?></p> </div> <?php unset($_SESSION['ERROR_MESSAGE']); ?> <?php endif; ?> <!-- checking to see if user is already signed in, if so success --> <?php if (isset($_SESSION['SUCCESS_MESSAGE'])) : ?> <div class="alert alert-success"> <p class="success"><?= $_SESSION['SUCCESS_MESSAGE']; ?></p> </div> <?php unset($_SESSION['SUCCESS_MESSAGE']); ?> <?php endif; ?> <!-- FORM FOR SIGN UP --> <form method="POST" action="" data-validation data-required-message="This field is required" class="text-center" enctype="multipart/form-data"> <!-- IMAGE UPLOADER --> <div class="imageupload panel panel-default"> <!-- top of image upload box --> <div class="panel-heading clearfix"> <h3 class="panel-title pull-left">Upload Image</h3> <div class="btn-group pull-right"> </div> </div> <!-- middle of image box --> <div class="file-tab panel-body"> <label class="btn btn-default btn-file"> <span>Browse</span> <!-- The file is stored here. --> <input type="file" name="image_url"> </label> <button type="button" class="btn btn-default">Remove</button> </div> </div> <!-- FORM INFO --> <!-- username --> <div class="form-group"> <input type="text" class="form-control" id="username" name="username" placeholder="Username" data-required> </div> <!-- email --> <div class="form-group"> <input type="text" class="form-control" id="email" name="email" placeholder="Email" data-required> </div> <!-- password --> <div class="form-group"> <input type="<PASSWORD>" class="form-control" id="password" name="password" placeholder="<PASSWORD>" data-required> </div> <!-- confirm password --> <div class="form-group"> <input type="<PASSWORD>" class="form-control" id="confirm_password" name="confirm-password" placeholder="<PASSWORD>" data-required> </div> <!-- signup button --> <div class="row"> <div class="col-xs-12 col-sm-12 col-md-12 col-lg-12 text-center"> <button type="submit" class="btn btn-primary signupButton">Signup</button> </div> </div> </form> <!-- close post form --> </div> <!-- close col-md --> </div> <!-- close row --> </section> <!-- close login --> </div> <!-- close container --> <file_sep><?php require_once __DIR__ . "/../../utils/Auth.php"; function clearSession() { Auth::logout(); header('Location: /'); die(); } clearSession(); ?><file_sep><?php require_once __DIR__ . '/user_seeder.php'; require_once __DIR__ . '/item_seeder.php'; <file_sep><!-- .navbar-fixed-top, or .navbar-fixed-bottom can be added to keep the nav bar fixed on the screen --> <nav class="navbar navbar-inverse" role="navigation"> <!-- Brand and toggle get grouped for better mobile display --> <div class="navbar-header"> <!-- Button that toggles the navbar on and off on small screens --> <button type="button" class="navbar-toggle collapsed hamburgerButton" data-toggle="collapse" data-target="#navbar-collapse-1" aria-expanded="false"> <!-- Hides information from screen readers --> <span class="sr-only"></span> <!-- Draws 3 bars in navbar button when in small mode --> <span class="icon-bar"></span> <span class="icon-bar"></span> <span class="icon-bar"></span> </button> <!-- You'll have to add padding in your image on the top and right of a few pixels (CSS Styling will break the navbar) --> <a class="pull-left wutsinLogo" href="/"><img src="/img/wutsinLogo.png"></a> </div> <!-- Collect the nav links, forms, and other content for toggling --> <div class="collapse navbar-collapse" id="navbar-collapse-1"> <ul class="nav navbar-nav"> <li><a href="/">Home <span class="sr-only">(current)</span></a></li> <li><a href="/ads?search=">Items</a></li> <?php if (!Auth::check()) { echo '<li><a href="/login">Login</a></li> <li><a href="/signup">SignUp</a></li>'; } else { echo '<li><a href="/account?userId=' . Auth::id() . '">Account</a></li> <li><a href="/create">Post Ad</a></li> <li><a href="/logout">Logout</a></li>'; } ?> </ul> <!-- navbar-left will move the search to the left --> <form method="GET" action="/ads" id="searchform" class="navbar-form navbar-right" role="search"> <div class="input-group form-group-md"> <input type="text" name="search" class="form-control" placeholder="Search"> <span class="input-group-btn"> <button type="submit" class="btn btn-default">Submit</button> </span> </div> </form> <!-- close form --> </div><!-- /.navbar-collapse --> </nav> <!-- close navbar --> <file_sep><?php $_ENV = include __DIR__ . '/../../.env.php'; require_once '../db_connect.php'; $dbc->exec('DROP TABLE IF EXISTS items'); $dbc->exec('DROP TABLE IF EXISTS users'); require_once __DIR__ . '/user_migration.php'; require_once __DIR__ . '/item_migration.php'; <file_sep><?php require_once __DIR__ . '/../utils/helper_functions.php'; function pageController() { // defines array to be returned and extracted for view $data = []; $data['itemUpdateMessage'] = ''; // finds position for ? in url so we can look at the url minus the get variables $get_pos = strpos($_SERVER['REQUEST_URI'], '?'); // if a ? was found, cuts off get variables if not just gives full url if ($get_pos !== false) { if (isset($_REQUEST['itemId'])) { $itemId = $_REQUEST['itemId']; } if (isset($_REQUEST['userId'])) { $userId = $_REQUEST['userId']; } if (isset($_REQUEST['search'])) { $search = $_REQUEST['search']; } $request = substr($_SERVER['REQUEST_URI'], 0, $get_pos); } else { $request = $_SERVER['REQUEST_URI']; } // switch that will run functions and setup variables dependent on what route was accessed switch ($request) { case '/' : $main_view = '../views/home.php'; break; case '/create' : if($_POST) { itemsSave(); } $main_view = '../views/ads/create.php'; break; case '/edit' : $main_view = '../views/ads/edit.php'; $data['items'] = Item::find($itemId); if (isset($_POST['delete'])) { Item::deleteItem($data['items']->id); header("Location: http://adlister.dev/ads?search="); $main_view = '../views/ads/index.php'; } else if ($_POST) { itemsUpdate($data['items']); header("Location: http://adlister.dev/ads?search="); $main_view = '../views/ads/index.php'; } break; case '/ads' : if(isset($search)) { $data['search'] = Item::searchItems($search); $data['items'] = $data['search']; } else { $data['items'] = Item::all(); } $main_view = '../views/ads/index.php'; case '/index' : $main_view = '../views/ads/index.php'; break; case '/show' : $data['items'] = Item::find($itemId); $data['user'] = User::find($data['items']->user_id); $main_view = '../views/ads/show.php'; break; case '/account' : $data['items'] = Item::findByUserId($userId); $data['user'] = User::find($userId); $main_view = '../views/users/account.php'; break; case '/editUser' : $data['user'] = User::find($userId); if($_POST) { userUpdate($data['user']); } // $data['items'] = User::find($itemId); $main_view = '../views/users/edit.php'; break; case '/login' : if($_POST) { Auth::attempt($_POST['email'], $_POST['password']); } $main_view = '../views/users/login.php'; break; case '/signup' : if ($_POST) { userSave(); } $main_view = '../views/users/signup.php'; break; case '/logout' : $main_view = '../views/users/logout.php'; break; default: // displays 404 if route not specified above $data['black_background'] = true; $main_view = '../views/404.php'; break; } $data['main_view'] = $main_view; return $data; } extract(pageController()); <file_sep> <?php session_start(); require_once __DIR__ . '/../bootstrap.php'; ?> <!DOCTYPE html> <html> <head> <title>Wutsin Wheels</title> <?php require '../views/partials/head.php'; ?> </head> <body class="<?= (isset($black_background)) ? 'black-background' : '' ?>"> <?php require '../views/partials/navbar.php'; ?> <?php require $main_view; ?> <?php require '../views/partials/common_js.php'; ?> <div class="copyright">Copyright &copy <NAME>, <NAME>, <NAME> 2016</div> </body> </html> <file_sep><?php require_once __DIR__ . '/../../models/Item.php'; // bike1 $item = new Item; $item->user_id = 1; $item->item_type = "Bicycle"; $item->headline = "GT hybrid Bicycle"; $item->price = 110; $item->date_listed = "2016-10-2"; $item->state = "Colorado"; $item->county = "Boulder County"; $item->image_url = "/img/bike1.jpg"; $item->description = "Great bike, perfect for commuting to and from school or commuting in downtown its a GT nomad comfort hybrid style bike the headset adjust back and forth, the only real problem with it is the gel seats leather is starting to peal up, comfortable bike to ride I don't ride this bike anymore cause I have a car now and do not have room for the bike."; $item->save(); // bike2 $item = new Item; $item->user_id = 2; $item->item_type = "Bicycle"; $item->headline = "Australian Made by <NAME>"; $item->price = 999; $item->date_listed = "2016-03-15"; $item->state = "Washington"; $item->county = "Wahkiakum County"; $item->image_url = "/img/bike2.jpg"; $item->description = "The launch of the Clamont range was based on quality Australian- made frames, durable components, backed up by professional assembly, excellent after sales service at competitive, realistic prices. The range was designed to cover the entire spectrum of bicycle activities from recreational cycling for the family, to off road, mountain bikes, to the highest level of professional and Olympic standard competition. All frames are manufactured in Australia and are built to produce strong, durable frames for Australian conditions. Each bicycle in the range boasts its own range of unique features. To support their commitment to Australian-made quality, Clamont frames carry a lifetime warranty on the frame."; $item->save(); // uni1 $item = new Item; $item->user_id = 3; $item->item_type = "Unicycle"; $item->headline = "InMotion ELectric Unicycle"; $item->price = 799; $item->date_listed = "2016-07-05"; $item->state = "Texas"; $item->county = "Bexar County"; $item->image_url = "/img/uni1.jpeg"; $item->description = "Ninebot One E+ Self Balancing Electric Unicycle manufactured by Ninebot-Segway. Far superior than any Hoverboard. This unit comes with a 1 year warranty with all service work done in the USA not China. The Ninebot One E+ is great for commuting or just cruising around with friends. You can ride off-road and in the rain. The Ninebot One E+ will go up to 14mph and 17-20 miles on a single charge. Charge time is less than 2.5 hrs. The Ninebot One E+ is a very high quality product and has a very safe Lithium Ion Battery. The same type of battery that Tesla Motors uses."; $item->save(); // uni2 $item = new Item; $item->user_id = 4; $item->item_type = "Unicycle"; $item->headline = "SkyHigh 20in. Unicycle"; $item->price = 139.99; $item->date_listed = "2016-06-08"; $item->state = "Massachusetts"; $item->county = "Norfolk County"; $item->image_url = "/img/uni2.jpeg"; $item->description = "With the Uno High 20'' Unicycle, you can take your balance and coordination skills to a whole other level! Designed for a whole new challenge, this specialty cycle easily adjusts between 55'' and 60'', depending on the seat height. The High Unicycle features a durable steel construction with a 20'' alloy wheel. The Kenda tire and cartridge bearings ensure a smooth ride with every rotation. Truly test your skills with the Uno High 20'' Unicycle!"; $item->save(); // skateboard1 $item = new Item; $item->user_id = 5; $item->item_type = "Skateboard"; $item->headline = "10in One Wheel Smart ELectric Skateboard"; $item->price = 469; $item->date_listed = "2016-04-09"; $item->state = "Texas"; $item->county = "Gregg County"; $item->image_url = "/img/sb1.jpeg"; $item->description = "Max Speed:25 km/h, Distance:About 16-19km, Max Tilt:Around 45°, Battery:60v 2200mAh, Highest power:500w, Max load:120kg, Engin:2x500w, Size:789*213*264(mm), Charging voltage:AC100-240V 50-60HZ, Using temperature:15 degree centigarde - 45degree centigrade"; $item->save(); // skateboard2 $item = new Item; $item->user_id = 1; $item->item_type = "Skateboard"; $item->headline = "Krainkn Skateboards Pro Complete "; $item->price = 69.11; $item->date_listed = "2016-10-01"; $item->state = "Maryland"; $item->county = "Howard County"; $item->image_url = "/img/sb2.jpeg"; $item->description = "Krainkn is a new way to ride a traditional skateboard. It is a great training tool and also a new extreme sport. Practice new tricks that work well for Krainkn and for snowboarding. Teach yourself, your kids or your friends how to ride a skateboard in one day. It's also a great workout and can be a very extreme sport. "; $item->save(); // bike1 $item = new Item; $item->user_id = 5; $item->item_type = "Skateboard"; $item->headline = "Rad Board Man"; $item->price = 420; $item->date_listed = "2016-9-24"; $item->state = "Colorado"; $item->county = "Boulder County"; $item->image_url = "/img/sb3.jpeg"; $item->description = "It's Cool, it's rad"; $item->save(); // bike2 $item = new Item; $item->user_id = 4; $item->item_type = "Bicycle"; $item->headline = "It's A Bike"; $item->price = 99; $item->date_listed = "2016-03-20"; $item->state = "Washington"; $item->county = "Wahkiakum County"; $item->image_url = "/img/bike3.jpg"; $item->description = "It moves when you pedal."; $item->save(); // uni1 $item = new Item; $item->user_id = 3; $item->item_type = "Skateboard"; $item->headline = "Nice Deck"; $item->price = 79; $item->date_listed = "2016-07-25"; $item->state = "Texas"; $item->county = "Bexar County"; $item->image_url = "/img/sb5.jpg"; $item->description = "Had it for years, always did me well."; $item->save(); // uni2 $item = new Item; $item->user_id = 2; $item->item_type = "Bicycle"; $item->headline = "Motorized"; $item->price = 600; $item->date_listed = "2016-06-12"; $item->state = "Massachusetts"; $item->county = "Norfolk County"; $item->image_url = "/img/bike4.jpg"; $item->description = "It does all the work for you!"; $item->save(); // skateboard1 $item = new Item; $item->user_id = 1; $item->item_type = "Unicycle"; $item->headline = "One Wheel"; $item->price = 69; $item->date_listed = "2016-05-09"; $item->state = "Texas"; $item->county = "Gregg County"; $item->image_url = "/img/uni3.jpg"; $item->description = "Max Speed:100 km/h"; $item->save(); // skateboard2 $item = new Item; $item->user_id = 1; $item->item_type = "Unicycle"; $item->headline = "PEDALS!!!"; $item->price = 124.45; $item->date_listed = "2016-10-05"; $item->state = "Maryland"; $item->county = "Howard County"; $item->image_url = "/img/uni4.jpg"; $item->description = "It go forward, backward, AND you can turn"; $item->save(); <file_sep><?php require_once 'Log.php'; require_once '../models/User.php'; class Auth { // runs login attempt with parameters public static function attempt($username, $password) { // makes sure the values passed in are not empty if(($username == '' || $username == null) || ($password == '' || $password == null)) { $_SESSION['ERROR_MESSAGE'] = 'Login information was incorrect'; return false; } // gets instance of user model by searching with username or email($username) $user = User::findByUsernameOrEmail($username); // makes sure the instance returned is not empty if ($user == null) { $_SESSION['ERROR_MESSAGE'] = 'Login information was incorrect'; return false; } // checks password submitted against hashed password if (password_verify($password, $user->password)) { // sets session variables used for logged in user $_SESSION['IS_LOGGED_IN'] = $user->username; $_SESSION['LOGGED_IN_ID'] = $user->id; return true; } $_SESSION['ERROR_MESSAGE'] = 'Login information was incorrect'; return false; } // checks session to see if user is logged in public static function check() { return (isset($_SESSION['IS_LOGGED_IN']) && $_SESSION['IS_LOGGED_IN'] != ''); } // returns id of the currently logged in user public static function id() { if (Auth::check()) { return $_SESSION['LOGGED_IN_ID']; } return null; } // returns instance of the user model for the user that is currently logged in public static function user() { if (self::check()) { return User::findByUsernameOrEmail($_SESSION['IS_LOGGED_IN']); } return null; } // clears session variables(logs out user) public static function logout() { // clear $_SESSION array session_unset(); // delete session data on the server session_destroy(); // ensure client is sent a new session cookie session_regenerate_id(true); // start a new session - session_destroy() ended our previous session so // if we want to store any new data in $_SESSION we must start a new one session_start(); // clear $_SESSION array // session_unset(); // delete session data on the server and send the client a new cookie // session_regenerate_id(true); return true; } } ?> <file_sep><main> <div class="container"> <div class="row"> <!-- SORT BY --> <div class="col-xs-12 col-sm-12 col-md-10 col-lg-12"> <div class="dropdown form-group pull-right"> <label>Sort By</label> <select name="item_type" onchange="location = this.value;" class="btn btn-default dropdown-toggle"> <option value="/ads?search=" selected="selected">--Sort By--</option> <option value="/ads?search=">All</option> <option value="/ads?search=bicycle">Bicycle</option> <option value="/ads?search=unicycle">Unicycle</option> <option value="/ads?search=skateboard">Skateboard</option> </select> </div> </div> <!-- ITEMS FOR SALE --> <div class="col-xs-12 col-sm-12 col-md-12 col-lg-12"> <h2 class="itemsForSaleHeader">Items for Sale</h2> </div> </div> <!-- end row --> <div class="row"> <?php if($search === null) : ?> <div class="col-xs-12 col-sm-12 col-md-12 col-lg-12"> <h3>No Results Were Found</h3> </div> <?php else : ?> <?php foreach($items->attributes as $item) : ?> <div class="col-xs-12 col-sm-6 col-md-5 col-lg-4"> <div class="thumbnail customThumbNail"> <a href="/show?itemId=<?= $item['id']; ?>"> <div class="caption customCaption"> <!-- item image --> <img src=<?= $item['image_url']; ?> alt="Image File Path Bad" class="custom-adINDEX-ad-img"> <!-- item info --> <h4 class="custom-adINDEX-h3"><?= $item['headline']; ?></h4> <p><?= '$' . $item['price']; ?></p> <p>State: <?= $item['state']; ?></p> <p>County: <?= $item['county']; ?></p> </div> </a> </div> </div> <?php endforeach; ?> <?php endif; ?> </div> <!-- end row --> </div> <!-- end container --> </main> <file_sep>'use strict'; // function to check if the user is already logged in $(document).ready(function() { var loggedInUser = ''; var url = window.location.href; loggedInUser = url.match(/userId=(.+)/)[1]; hideButtons(loggedInUser); }); // if the user is logged in, then buttons in the navbar will change accordingly function hideButtons(loggedInUser) { if (loggedInUser !== userId) { $('#updateProfileBtn').hide(); $('.editAdButton').hide(); } } <file_sep><?php // List of helper functions used throughout the application. // Primarily used within the PageController function. // takes image from form submission and moves it into the uploads directory function saveUploadedImage($input_name) { $valid = true; // checks if $input_name is in the files super global if(isset($_FILES[$input_name]) && $_FILES[$input_name]['name']) { // checks if there are any errors on the upload from the submission if(!$_FILES[$input_name]['error']) { $tempFile = $_FILES[$input_name]['tmp_name']; $positionOfLastSlash = strrpos($tempFile, '/'); $newName = substr($tempFile, $positionOfLastSlash); $extension = pathinfo($_FILES[$input_name]['name'], PATHINFO_EXTENSION); // Validate Size and Extension if( $_FILES[$input_name]['size'] > (1024000000)) { $valid = false; } // only allows certain file extensions if( $extension != 'jpg' && $extension != 'jpeg' && $extension != 'png' && $extension != 'gif') { $valid = false; } // If Image file makes it to this point, send file to this directory if($valid) { $image_url = '/img/uploads' . $newName . '.' . $extension; move_uploaded_file($tempFile, __DIR__ .'/../public' . $image_url); return $image_url; } else { return null; } } } else { return null; } } function itemsSave() { $item = new Item(); $item->item_type = Input::get('item_type'); $item->headline = Input::get('headline'); $item->price = Input::get('price'); $item->date_listed = date('Y-m-d'); $item->state = Input::get('state'); $item->county = Input::get('county'); $item->image_url = saveUploadedImage('image_url'); $item->description = Input::get('description'); $item->user_id = Auth::id(); $item->save(); } function itemsUpdate($items) { $item = new Item(); $item->id = $items->attributes['id']; $item->item_type = Input::get('item_type'); $item->headline = Input::get('headline'); $item->price = Input::get('price'); $item->state = Input::get('state'); $item->county = Input::get('county'); $item->image_url = saveUploadedImage('image_url'); $item->description = Input::get('description'); $data['itemUpdateMessage'] = "Item was updated"; $item->user_id = Auth::id(); $item->save(); } function userSave() { $user = new User(); $user->image_url = saveUploadedImage('image_url'); $user->username = Input::get('username'); $user->email = Input::get('email'); $user->password = Input::get('<PASSWORD>'); $user->date_joined = date('Y-m-d'); $user->save(); } function userUpdate($users) { $user = new User(); $user->id = $users->attributes['id']; $user->image_url = saveUploadedImage('image_url'); $user->username = Input::get('username'); $user->email = Input::get('email'); $user->password = Input::get('<PASSWORD>'); $user->save(); } <file_sep><?php require_once __DIR__ . '/Model.php'; class Item extends Model { protected static $table = 'items'; public static function findByUserId ($id) { return parent::findyby('user_Id', $id); } public static function searchItems($searchTerm) { self::dbConnect(); $query = "SELECT * FROM " . static::$table . " WHERE item_type LIKE '%" . $searchTerm . "%' OR headline LIKE '%" . $searchTerm . "%' OR state LIKE '%" . $searchTerm . "%' OR county LIKE '%" . $searchTerm . "%' OR description LIKE '%" . $searchTerm . "%';"; $stmt = self::$dbc->prepare($query); $stmt->execute(); //Store the resultset in a variable named $result $results = $stmt->fetchAll(PDO::FETCH_ASSOC); $instance = null; if ( $results ) { $instance = new static; $instance->attributes = $results; } return $instance; } public static function deleteItem($id) { $query = 'DELETE FROM items WHERE id = :id'; $stmt = self::$dbc->prepare($query); $stmt->bindValue(':id', $id, PDO::PARAM_INT); $stmt->execute(); } } <file_sep><!--Page for user account home--> <div class="container"> <section id="login"> <div class="row"> <!-- checks username and password, if incorrect throws an error --> <?php if (isset($_SESSION['ERROR_MESSAGE'])) : ?> <div class="alert alert-danger"> <p class="error"><?= $_SESSION['ERROR_MESSAGE']; ?></p> </div> <?php unset($_SESSION['ERROR_MESSAGE']); ?> <?php endif; ?> <!-- checking to see if user is already signed in, if so success --> <?php if (isset($_SESSION['SUCCESS_MESSAGE'])) : ?> <div class="alert alert-success"> <p class="success"><?= $_SESSION['SUCCESS_MESSAGE']; ?></p> </div> <?php unset($_SESSION['SUCCESS_MESSAGE']); ?> <?php endif; ?> <!-- YOUR PROFILE INFO --> <form method="POST" class="text-center"> <div class="container"> <!-- image --> <img class="img-circle" src="<?= $user->image_url; ?>"> <!-- usermname --> <h1 class="section-title text-center"><?= $user->username; ?></h1> <!-- profile info --> <h4 class="section-title"><?= $user->email; ?></h4> <?php // Checking url // var_dump($_SERVER['REQUEST_URI']); // Checking query value after userId // var_dump(ltrim($_SERVER['QUERY_STRING'], 'userId=')); // Checking current logged in user's id // var_dump(Auth::id()); $loggedUser = Auth::id(); echo "<script>"; echo ('var userId = ' . json_encode($loggedUser) . ';'); echo "</script>"; // Checks if URL id != Logged User id. ltrim takes away characters in second argument from first argument if (Auth::id() != ltrim($_SERVER['QUERY_STRING'], 'userId=')) { } ?> <!-- edit profile THIS IS ONE OF THE BUTTONS TO HIDE --> <a href="/editUser?userId=<?php echo($user->attributes['id']); ?>" class="btn btn-primary btn-md active" role="button" id="updateProfileBtn">Update Profile</a> </div> <!-- YOUR ADS --> <div class="container"> <h1>Posted Ads</h1> <!-- ads info --> <?php foreach ($items->attributes as $item) : ?> <div class="row"> <div class="thumbnail"> <!-- image --> <img src="<?= $item['image_url']; ?>" alt="Image File Path Bad"> <!-- item info --> <div class="panel-body"> <ul class="list-group"> <!-- item info --> <li class="list-group-item active">Item Information</li> <!-- item headline --> <li class="list-group-item"><b><?= $item['headline']; ?></b></li> <!-- item price --> <li class="list-group-item"><b>Price: </b><?= '$' . $item['price']; ?></li> <!-- item location --> <li class="list-group-item"> <b>State: </b> <?= $item['state']; ?><br> <b>County:</b> <?= $item['county']; ?></li> <!-- item description --> <li class="list-group-item"><b>Description: </b><?= $item['description']; ?></li> </ul> <div class="col-xs-12 col-sm-12 col-md-12 col-lg-12 text-center"> <a href="/edit?itemId=<?php echo($item['id']); ?>" class="btn btn-primary loginButtons editAdButton" id="">Edit Ad</a> </div> </div> <!-- closes item info --> </div> <!-- closes the row class --> <?php endforeach; ?> </div> <!-- closes container --> </form> </div> <!-- close row --> </section> <!-- close login --> </div> <!-- close container --> <file_sep><!--Page for single advertisement --> <main class="container"> <h2 class="custom-adSHOW-ad-show-header">Item Description</h2> <div class="container"> <div class="row"> <div class="col-xs-12 col-sm-12 col-md-6 col-lg-6"> <div class="thumbnail"> <img src="<?= $items->attributes['image_url']; ?>" alt="Image File Path Bad" class="custom-adSHOW-ad-img"> <div class="caption"> <p> <?= $items->attributes['description']; ?> </p> </div> </div> </div> <div class="col-xs-12 col-sm-12 col-md-6 col-lg-6"> <div class="custom-adSHOW-center"> <div class="panel-body"> <ul class="list-group"> <li class="list-group-item active">Item Information</li> <li class="list-group-item"><?= $items->attributes['headline']; ?></li> <li class="list-group-item"><?= '$' . $items->attributes['price']; ?></li> <li class="list-group-item">State: <?= $items->attributes['state']; ?></li> <li class="list-group-item">County: <?= $items->attributes['county']; ?></li> <li class="list-group-item">Type of Item: <?= $items->attributes['item_type']; ?></li> </ul> </div> <p>Posted by <a href="/account?userId=<?= $user->id; ?>"><?= $user->username ; ?></a></p> </div> </div> </div> </div> </main> <file_sep><?php $_ENV = include __DIR__ . '/../../.env.php'; require_once '../db_connect.php'; $dbc->exec('DROP TABLE IF EXISTS items'); $query = "CREATE TABLE items ( id INT UNSIGNED NOT NULL AUTO_INCREMENT, user_id INT UNSIGNED NOT NULL, item_type ENUM('Bicycle', 'Unicycle', 'Skateboard') NOT NULL, headline CHAR(100) NOT NULL, price DECIMAL(13,2) NOT NULL, date_listed DATE NOT NULL, state VARCHAR(255) NOT NULL, county VARCHAR(255) NOT NULL, image_url VARCHAR(255) DEFAULT '/img/wutsinLogo.png', description TEXT NOT NULL, PRIMARY KEY (id), FOREIGN KEY (user_id) REFERENCES users (id) )"; $dbc->exec($query);
e3c5e77f7299f3e97a0f42e9b34538b1bac10b25
[ "JavaScript", "PHP" ]
18
PHP
Wutsin/adlister.dev
0567990db42023cf90d173fb76f9b601667f9f0f
24c949b0617f3a21626ee5e196a3a1f075edfc5b
refs/heads/master
<file_sep>namespace OneTechStudentManagerService.Migrations { using System; using System.Data.Entity; using System.Data.Entity.Migrations; using System.Linq; internal sealed class Configuration : DbMigrationsConfiguration<OneTechStudentManagerService.MyContext> { public Configuration() { AutomaticMigrationsEnabled = false; } protected override void Seed(OneTechStudentManagerService.MyContext context) { for (var i = 1; i < 10; i++) { context.Students.AddOrUpdate( new Student { Email = "<EMAIL>", FirstName = "<NAME>", LastName = "Phạm", PhoneNumber = "0762941097" }); } } } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Web; namespace OneTechStudentManagerService { public class StudentRepository : IStudentRepository { private readonly MyContext _db = new MyContext(); public List<Student> GetAllStudents() { return _db.Students.ToList(); } } }<file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Runtime.Serialization; using System.ServiceModel; using System.Text; namespace OneTechStudentManagerService { // NOTE: You can use the "Rename" command on the "Refactor" menu to change the class name "StudentManagerServices" in code, svc and config file together. // NOTE: In order to launch WCF Test Client for testing this service, please select StudentManagerServices.svc or StudentManagerServices.svc.cs at the Solution Explorer and start debugging. public class StudentManagerServices : IStudentManagerServices { private static readonly IStudentRepository Repository = new StudentRepository(); public List<Student> GetBooksList() { var rs = Repository.GetAllStudents(); return rs; } } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Runtime.Serialization; using System.ServiceModel; using System.ServiceModel.Web; using System.Text; namespace OneTechStudentManagerService { // NOTE: You can use the "Rename" command on the "Refactor" menu to change the interface name "IStudentManager" in both code and config file together. [ServiceContract] public interface IStudentManagerServices { [OperationContract] [WebInvoke( Method = "GET", RequestFormat = WebMessageFormat.Json, ResponseFormat = WebMessageFormat.Json, UriTemplate = "Students/" )] List<Student> GetBooksList(); } public interface IStudentRepository { List<Student> GetAllStudents(); } }
477b1b44bd17b48fa5dda84ff64be9ef025eba0c
[ "C#" ]
4
C#
Senbonzakura1234/OneTechStudentManagerService
11b615d688c2737623eeb34591eda52e5e51d7a6
2cc75be6068587ea92d5263bc46bf6118e87c01c
refs/heads/master
<file_sep># 1.2 大型项目的结构 ![大型项目的结构](/images/architecture.png) 上图中的项目结构是从我们学习的综合demo改造而来的,下面一一介绍一下每个目录及其文件的意义 ###各个目录介绍 - app:用于存放整个应用中大部分的代码,模版和静态文件 - main:用于蓝图注册所需的代码文件的存放 - templates:存放整个应用包中的模板文件 - migrations:存在数据库迁移记录文件 - tests:用于存放测试所需的代码文件 ###配置文件config.py import os class Config: SECRET_KEY=os.environ.get('SECRET_KEY') or 'secret msg' SQLALCHEMY_TRACK_MODIFICATIONS=True MAIL_SERVER='smtp.126.com' MAIL_PORT=465 MAIL_USE_SSL=True MAIL_USERNAME='ccyznhy' MAIL_PASSWORD='<PASSWORD>' MY_MAIL_SENDER='ccy<<EMAIL>>' MY_MAIL_TO='<EMAIL>' @staticmethod def init_app(self): pass class DevelopmentConfig(Config): DEBUG=True SQLALCHEMY_DATABASE_URI='mysql://root:mysql@127.0.0.1:3306/demo' class TestingConfig(Config): TESTING=True SQLALCHEMY_DATABASE_URI='mysql://root:mysql@127.0.0.1:3306/demo' class ProductionConfig(Config): SQLALCHEMY_DATABASE_URI='mysql://root:mysql@127.0.0.1:3306/demo' config={ 'development':DevelopmentConfig, 'testing':TestingConfig, 'production':ProductionConfig, 'default':DevelopmentConfig } 随着flask程序越来越复杂,配置项会越来越多,通过观察上述代码,大家发现我们定义了一个基类的配置,然后定义了几个子类(DevelopmentConfig,TestingConfig,ProductionConfig)用于继承基类配置,这些子类的配置是根据不同场景进行的配置 - DevelopmentConfig:开发用配置 - TestingConfig:测试所用的配置 - ProductionConfig:产品上线后使用的配置 ###启动文件(manage.py) import os from app import create_app,db from app.models import User,Role from flask_script import Manager,Shell from flask_migrate import Migrate,MigrateCommand app=create_app(os.getenv('FLASK_CONFIG') or 'default') manager=Manager(app) migrate=Migrate(app,db) def make_shell_context(): return dict(app=app,db=db,User=User,Role=Role) manager.add_command('shell',Shell(make_context=make_shell_context)) manager.add_command('db',MigrateCommand) if __name__=='__main__': print os.environ.get('FLASK_CONFIG','a') manager.run() 用于管理应用程序的启动,其中,创建app及部分对象的实例由create_app函数来实现 ###使用程序工厂函数(app/__init__.py) 在单个文件中开发程序很方便,但却有个很大的缺点,因为程序在全局作用域中创建,所以无法动态修改配置。运行脚本时,程序实例已经创建,再修改配置为时已晚。这一点对单元测试尤其重要,因为有时为了提高测试覆盖度,必须在不同的配置环境中运行程序。这个问题的解决方法是延迟创建程序实例,把创建过程移到可显式调用的工厂函数中。这种方法不仅可以给脚本留出配置程序的时间,还能够创建多个程序实例,这些实例有时在测试中非常有用。程序的工厂函数在app包的构造文件中定义。构造文件导入了大多数正在使用的 Flask 扩展。由于尚未初始化所需的程序实例,所以没有初始化扩展,创建扩展类时没有向构造函数传入参数。create\_app() 函数就是程序的工厂函数,接受一个参数,是程序使用的配置名。配置类在 config.py 文件中定义,其中保存的配置可以使用 Flask app.config 配置对象提供的 from\_object() 方法直接导入程序。至于配置对象,则可以通过名字从 config 字典中选择。程序创建并配置好后,就能初始化扩展了。在之前创建的扩展对象上调init_app()可以完成初始化过程。工厂函数返回创建的程序示例,不过要注意,现在工厂函数创建的程序还不完整,因为没有路由和自定义的错误页面处理程序 #coding:utf-8 from flask import Flask from flask_bootstrap import Bootstrap from flask_mail import Mail from flask_moment import Moment from flask_sqlalchemy import SQLAlchemy from config import config bootstrap=Bootstrap() mail=Mail() moment=Moment() db=SQLAlchemy() def create_app(config_name): app=Flask(__name__) app.config.from_object(config[config_name]) config[config_name].init_app(app) bootstrap.init_app(app) mail.init_app(app) moment.init_app(app) db.init_app(app) from app.main import main as main_blueprint app.register_blueprint(main_blueprint) return app ###使用蓝图实现程序功能(main/__init__.py) from flask import Blueprint main=Blueprint('main',__name__) from . import views,errors 转换为工厂函数后,处理路由的操作也要从启动文件中分离出来,我们可以使用蓝图来处理,为了获得最大的灵活性,程序包中创建了一个子包,用于保存蓝图 其中views.py(存放路由相关的代码),errors.py(存放错误处理代码),forms.py(存放表单相关代码)三个文件均位于蓝图所在的main目录中 __init__.py文件: from flask import Blueprint main=Blueprint('main',__name__) from . import views,errors ###其他文件 email.py文件:用于存放发送邮件相关的代码 from threading import Thread from flask import current_app from flask_mail import Message from . import mail def send_email(app,msg): with app.app_context(): mail.send(msg) def send_async_email(to,subject): app=current_app._get_current_object() msg=Message(subject,sender=app.config['MY_MAIL_SENDER'],recipients=[to]) msg.body='msg body' msg.html='<h1>msg html</h1>' t=Thread(target=send_email,args=[app,msg]) t.start() return t models.py文件:用于存放数据库模型 from . import db class Role(db.Model): __tablename__='roles' id=db.Column(db.Integer,primary_key=True) name=db.Column(db.String(64),unique=True) users=db.relationship('User',backref='role',lazy='dynamic') def __repr__(self): return 'Role:%s'%self.name class User(db.Model): __tablename__='users' id=db.Column(db.Integer,primary_key=True) username=db.Column(db.String(64),unique=True) role_id=db.Column(db.Integer,db.ForeignKey('roles.id')) def __repr__(self): return 'User:%s'%self.username<file_sep># 注册后端编写 1. passport 一般是代表关于用户,认证,登录之类的! 2. 然后register这个处理注册的函数是这样的. 1. ## 因为涉及到是请求注册一个新用户,所以,method是POST 2. 请求获得参数是 1. 手机号码(作为用户名) 2. 短信验证码 3. 用户输入的密码 3. 一般视图函数的处理代码是 ```python def function123(): '''我是视图函数 param: moblie:手机号 param: sms_code:手机验证码 parm: password:用户设置的密码 ``` 4. ## request.json 只能够接受方法为POST、Body为raw,header 内容为 application/json类型的数据:对应图1 1. https://blog.csdn.net/tengdazhang770960436/article/details/80106533 2. body内容 1. form-data 2. x-www-form-urlencodeed 3. raw 4. binary 3. 2.c =request.get_json() 将请求参数做了处理,得到的是字典格式的,因此排序会打乱依据字典排序规则 https://www.cnblogs.com/yy-cola/p/8066020.html 5. ## 上面的步骤就成功获取到json信息并且转换到字典,然后就可以使用get去获取内容了. 6. 检验参数,老步骤了.! 7. 从redis拉去手机短信验证码的有关信息,看看是否存在或者是否过期了.!! 8. ## 然后就保存信息到数据库持久化了.! 1. 实现实例化模型类数据库 ```python user = User(mobile=1324XX,password=<PASSWORD>) #估计差不多这样子就可以保存数据吧 db.session.add(user) db.session.commit() ``` 2. 更多的关于flask的数据库可以参考这里. 通过数据库会话管理对数据库所做的改动,在 Flask-SQLAlchemy 中,会话由 db.session 表示。准备把对象写入数据库之前,先要将其添加到会话中:https://www.cnblogs.com/zknublx/p/7133750.html 2. ## 如果出现问题.就撤销保存,db.session.rollback() 9. 然后给数据库的手机号码字段设置为唯一字段. 10. 然后把验证成功的验证码删除,防止用于重复验证.! 11. ## # 前端修改 1. 修改表单 1. method用post请求方式 2. ## 需要拦截表单,因为一些校验步骤需要验证正确之后才可以提交 1. ### 为什么这样做?因为表单提交的数据格式不是真正的json格式,需要用ajax格式化一下,用js格式化一下 2. ### 拦截表单的方法1就是,绑定表单提交按钮,$("..formxx").submit(function(e){xxx}) 3. ### 上面的e还有故事,这个代表的是这个行为的描述信息.! 4. ### 拦截语句是e.preventDefault() 5. ### 关于js拦截的部分知识点 1. preventDefault https://www.cnblogs.com/AndrewXu/p/4631521.html 2. 关于js中return false、event.preventDefault()和event.stopPropagation() https://www.cnblogs.com/momo798/p/6025777.html 6. ### 调用JSON.stringify(xx)将字典转换成为json数据. 7. ### 还可以自己定义ajax来写请求,因为需要加入不少的参数,例如需要header加入'Content-Type'='application/json' `$.ajax({url:"/jquery/test1.txt",async:false});` 关于手动使用ajax的一些参数说明 http://www.w3school.com.cn/jquery/ajax_ajax.asp 例子 ```python $.ajax({ url: "/api/v1.0/users", type: "post", data: req_json, contentType: "application/json", dataType: "json", headers: { "X-CSRFToken": getCookie("csrf_token") }, // 请求头,将csrf_token值放到请求中,方便后端csrf进行验证 success: function (resp) { if (resp.errno == "0") { // 注册成功,跳转到主页 location.href = "/index.html"; } else { alert(resp.errmsg); } } ``` 8. ### 跨站调用的问题,在当前某一个网站直接使用ajax调用其他网站的话,这是一个不怎么允许的操作.! 9. ### 原来jquery并不能直接调用cookie的. # 密码加密与property装饰器使用 1. md5已经变成不安全了.! 1. 暴力破解,已经有大量的对比密码资料了.! 2. 数学方法反推! 2. ## 建议使用sha256 3. ## 在models那边进行密码加密,不在视图那边加密密码了.! 1. ### 使用werkzeug的security的generate_password_hash 2. ### 在flask里面已经提供了一个函数,用于加密和解密的校验!. 3. generate_password_hash的介绍 1. method就是加密的方式 1. pbkdf2:sha256 2. salt_lenth 盐值长度 3. 然后返回盐值和计算结果.! 4. #### 盐值和密码要放在一起.! 2. ### 我观察到的就是,这个加密的步骤写在了models那边去了,然后在外面调用数据库模型类的时候挺方便的. 1. 先调用加密的函数. 2. 然后将获取到的值再保存到数据库当中就可以了.! 4. ## 知识点应用,装饰器,@property把函数封装一下,变成属性,可以用于设置值. 1. 代码 ```python class Student(object): @property def score(self): return self._score @score.setter def score(self, value): if not isinstance(value, int): raise ValueError('score must be an integer!') if value < 0 or value > 100: raise ValueError('score must between 0 ~ 100!') self._score = value ``` 5. ## 方法有三种: 1. 对象方法 2. 类方法 3. 静态方法 6. 上面说到的,使用装饰器的问题,现在思考一下,就是, 1. 使用property的话,一个涉及到读取问题,一个涉及到设置值的问题 2. 如果是涉及到设置数值的话,就需要检查变量,然后再设置数值 3. ### 如果都是设置好装饰器这种模式的话,设置保存密码就很方便了.!<file_sep># 提供静态文件的蓝图编写 1. ## 为static做准备!. 1. 专门写一个视图函数去处理这个satic路径的问题.! 2. 在ihmoe下面新建一个蓝图,单一文件,专门用于处理url处理.web_html 1. 在web_html.py在里面url匹配地址,就好像django里面的urls的处理.! ```python from flask import Blueprint,current_app #提供静态文件的蓝图 html = Blueprint("web.html",__name__) @html.route("/<re(r'.*'):html_file_name>") def get_html(html_file_name): '''提供html文件''' #如果html_file_name为空的话,表示访问的路径是/,请求的是主页 if not html_file_name: html_file_name = "index.html" if html_file_name != 'favicon.ico': html_file_name = "html/" + html_file_name return current_app.send_static_file(html_file_name) ``` 3. 然后在utils文件里面新建一个commons.py. 1. 在里面定义正则转换器,继承一个基本的,然后返回一个自定义的!. ```python # coding:utf-8 from werkzeug.routing import BaseConverter # 定义正则转换器 class ReConverter(BaseConverter): """""" def __init__(self, url_map, regex): # 调用父类的初始化方法 super(ReConverter, self).__init__(url_map) # 保存正则表达式 self.regex = regex ``` 4. 然后在ihome的init文件里面导入. ```python #为flask添加自定义的转换器 app.url_map.converters['re'] = ReConverter #注册提供静态文件的蓝图 from ihome import web_html app.register_blueprint(web_html.html) return app ``` 5. 在这里,勉强看得懂,就是,这里利用了吧把html的名字转换了一下.匹配正则!. ```python @html.route("/<re(r'.*'):html_file_name>") ``` # csrf防护机制 1. 从cookie中获取一个大概叫csrf_token的值, 2. 从请求体中获取一个csrf_token的值 3. 如果两个值相同,则检验通过,可以进入到视图函数中执行, 如果两个值不同,则检验失败,会向前端返回状态码400的错误! 4. 跨站攻击.! 5. 有一个插图,可以参考一下有道云笔记,2018年8月15日. 6. csrf跨站攻击. 1. Web安全之CSRF攻击的防御措施 https://www.cnblogs.com/cxying93/p/6035031.html 7. ## 防御办法 1. 尽量使用POST,限制GET 2. 浏览器Cookie策略 3. 加验证码 4. Referer Check 5. Anti CSRF Token 现在业界对CSRF的防御,一致的做法是使用一个Token(Anti CSRF Token)。 例子: 1. 用户访问某个表单页面。 2. 服务端生成一个Token,放在用户的Session中,或者浏览器的Cookie中。 3. 在页面表单附带上Token参数。 4. 用户提交请求后, 服务端验证表单中的Token是否与用户Session(或Cookies)中的Token一致,一致为合法请求,不是则非法请求。 这个Token的值必须是随机的,不可预测的。由于Token的存在,攻击者无法再构造一个带有合法Token的请求实施CSRF攻击。另外使用Token时应注意Token的保密性,尽量把敏感操作由GET改为POST,以form或AJAX形式提交,避免Token泄露。 注意: CSRF的Token仅仅用于对抗CSRF攻击。当网站同时存在XSS漏洞时候,那这个方案也是空谈。所以XSS带来的问题,应该使用XSS的防御方案予以解决。 8. 什么是xss攻击. 1. 跨站脚本功攻击,xss,一个简单的例子让你知道什么是xss攻击 https://blog.csdn.net/Ideality_hunter/article/details/80621138 9. ## 同源策略 1. 限制了不同源的网站不能相互操作资源. # 如何设置csrf防护 1. 看情况 1. 前后端不分离,直接在模板植入csrf_token()就可以了! # send_static_file <file_sep>## 什么是flask 1. Flask是一个使用 Python 编写的轻量级 Web 应用框架。其 WSGI 工具箱采用 Werkzeug ,模板引擎则使用 Jinja2 。Flask使用 BSD 授权。 2. Flask也被称为 “microframework” ,因为它使用简单的核心,用 extension 增加其他功能。Flask没有默认使用的数据库、窗体验证工具。 3. 然而,Flask保留了扩增的弹性,可以用Flask-extension加入这些功能:ORM、窗体验证工具、文件上传、各种开放式身份验证技术。最新版本为0.11] ## flask的历史 1. Flask 本是作者 <NAME>的一个愚人节玩笑 [1] ,不过后来大受欢迎,进而成为一个正式项目。"It came out of an April Fool's joke but proved popular enough to make into a serious application in its own right." Flask 受到了基于 Ruby 语言的Sinatra项目的影响。 ## flask的特色 1. 自带开发用服务器和debugger 2. 集成单元测试 (unit testing) 3. RESTful request dispatching 4. 使用Jinja2(英语:Jinja (template engine)) 模板引擎 5. 支持 secure cookies (client side sessions) 6. 100% WSGI 1.0 兼容 7. Unicode based 8. 详细的文件、教学 9. Google App Engine兼容 10. 可用 Extensions 增加其他功能 ## 参见 1. Django 2. Pylons 3. Bottle ## 版本 1. 最早版本大概是version0.1 2. 然后,第二个版本的释放是vsersion0.2 2010.03.12(8年的历史!)<file_sep># 1.1 web表单 web表单是web应用程序的基本功能。 它是HTML页面中负责数据采集的部件。表单有三个部分组成:表单标签、表单域、表单按钮。表单允许用户输入数据,负责HTML页面数据采集,通过表单将用户输入的数据提交给服务器。 在Flask中,为了处理web表单,我们一般使用Flask-WTF扩展,它封装了WTForms,并且它有验证表单数据的功能。 ### WTForms支持的HTML标准字段 ![表单支持的字段](/images/form_field.png) ### WTForms常用验证函数 ![常用验证函数](/images/validate_method.png) 使用Flask-WTF需要配置参数SECRET_KEY。 ###在HTML页面中直接写form表单: #模板文件 <form method='post'> <input type="text" name="username" placeholder='Username'> <input type="<PASSWORD>" name="password" placeholder='<PASSWORD>'> <input type="submit"> </form> ###视图函数中获取表单数据: from flask import Flask,render_template,request @app.route('/login',methods=['GET','POST']) def login(): if request.method == 'POST': username = request.form['username'] password = request.form['<PASSWORD>'] print username,password return render_template('login.html',method=request.method) ###使用Flask-WTF实现表单 配置参数: ``` app.config['SECRET_KEY'] = 'silence is gold' ``` 模板页面: <form method="post"> #设置csrf_token {{ form.csrf_token() }} {{ form.us.label }} <p>{{ form.us }}</p> {{ form.ps.label }} <p>{{ form.ps }}</p> {{ form.ps2.label }} <p>{{ form.ps2 }}</p> <p>{{ form.submit() }}</p> {% for x in get_flashed_messages() %} {{ x }} {% endfor %} </form> 视图函数: #coding=utf-8 from flask import Flask,render_template,\ redirect,url_for,session,request,flash #导入wtf扩展的表单类 from flask_wtf import Form #导入自定义表单需要的字段 from wtforms import SubmitField,StringField,PasswordField #导入wtf扩展提供的表单验证器 from wtforms.validators import DataRequired,EqualTo app = Flask(__name__) app.config['SECRET_KEY']='1' #自定义表单类,文本字段、密码字段、提交按钮 class Login(Form): us = StringField(label=u'用户:',validators=[DataRequired()]) ps = PasswordField(label=u'密码',validators=[DataRequired(),EqualTo('ps2','err')]) ps2 = PasswordField(label=u'确认密码',validators=[DataRequired()]) submit = SubmitField(u'提交') @app.route('/login') def login(): return render_template('login.html') #定义根路由视图函数,生成表单对象,获取表单数据,进行表单数据验证 @app.route('/',methods=['GET','POST']) def index(): form = Login() if form.validate_on_submit(): name = form.us.data pswd = form.ps.data pswd2 = form.ps2.data print name,pswd,pswd2 return redirect(url_for('login')) else: if request.method=='POST': flash(u'信息有误,请重新输入!') print form.validate_on_submit() return render_template('index.html',form=form) if __name__ == '__main__': app.run(debug=True) ###CSRF攻击原理: ![CSRF攻击原理](/images/csrf_principle.jpg) CSRF(Cross-site request forgery)跨站请求伪造 图中Browse是浏览器,WebServerA是受信任网站/被攻击网站A,WebServerB是恶意网站/攻击网站B。 (1),一开始用户打开浏览器,访问受信任网站A,输入用户名和密码登陆请求登陆网站A。 (2),网站A验证用户信息,用户信息通过验证后,网站A产生Cookie信息并返回给浏览器。 (3),用户登陆网站A成功后,可以正常请求网站A。 (4),用户未退出网站A之前,在同一浏览器中,打开一个TAB访问网站B。 (5),网站B看到有人访问后,他会返回一些攻击性代码。 (6),浏览器在接受到这些攻击性代码后,促使用户不知情的情况下浏览器携带Cookie(包括sessionId)信息,请求网站A。这种请求有可能更新密码,添加用户什么的操作。 从上面CSRF攻击原理可以看出,要完成一次CSRF攻击,需要被攻击者完成两个步骤: 1, 登陆受信任网站A,并在本地生成COOKIE。 2, 在不登出A的情况下,访问危险网站 B。 看到这里,你也许会说:“如果我不满足以上两个条件中的一个,我就不会受到CSRF的攻击”。是的,确实如此,但你不能保证以下情况不会发生: 1.你不能保证你登录了一个网站后,不再打开一个tab页面并访问另外的网站。 2.你不能保证你关闭浏览器了后,你本地的Cookie立刻过期,你上次的会话已经结束。(事实上,关闭浏览器不能结束一个会话,但大多数人都会错误的认为关闭浏览器就等于退出登录/结束会话了……) 3.上图中所谓的攻击网站,可能是一个存在其他漏洞的可信任的经常被人访问的网站。 在处理 POST 请求之前,flask-wtf 会验证这个请求的 cookie 里的 csrftoken 字段的值和提交的表单里的 csrfmiddlewaretoken 字段的值是否一样。如果一样,则表明这是一个合法的请求,否则,这个请求可能是来自于别人的 csrf 攻击,返回 403 Forbidden CSRF\_ENABLED是为了CSRF(跨站请求伪造)保护。 SECRET_KEY用来生成加密令牌,当CSRF激活的时候,该设置会根据设置的密匙生成加密令牌。 # 1.2 数据库 知识点 - Flask-SQLALchemy安装 - 连接数据库 - 使用数据库 - 数据库迁移 ### 数据库的设置 Web应用中普遍使用的是关系模型的数据库,关系型数据库把所有的数据都存储在表中,表用来给应用的实体建模,表的列数是固定的,行数是可变的。它使用结构化的查询语言。关系型数据库的列定义了表中表示的实体的数据属性。比如:商品表里有name、price、number等。 Flask本身不限定数据库的选择,你可以选择SQL或NOSQL的任何一种。也可以选择更方便的SQLALchemy,类似于Django的ORM。SQLALchemy实际上是对数据库的抽象,让开发者不用直接和数据库打交道,而是通过Python对象来操作数据库,在舍弃一些性能开销的同时,换来的是开发效率的较大提升。 SQLALchemy是一个关系型数据库框架,它提供了高层的ORM和底层的原生数据库的操作。flask-sqlalchemy是一个简化了SQLALchemy操作的flask扩展。 ### 安装 ``` pip install flask-sqlalchemy ``` 如果连接的是mysql数据库,需要安装mysqldb ``` pip install flask-mysqldb ``` ### 使用Flask-SQLAlchemy管理数据库 在Flask-SQLAlchemy中,数据库使用URL指定,而且程序使用的数据库必须保存到Flask配置对象的SQLALCHEMY\_DATABASE\_URI键中。 对比下Django和Flask中的数据库设置: Django的数据库设置: ![Django的数据库设置]() Flask的数据库设置: app.config['SQLALCHEMY\_DATABASE\_URI'] = 'mysql://root:mysql@127.0.0.1:3306/test' ###常用的SQLAlchemy字段类型 ![字段类型]() ###常用的SQLAlchemy列选项 ![列选项]() ###常用的SQLAlchemy关系选项 ![关系选项]() #数据库基本操作 在Flask-SQLAlchemy中,插入、修改、删除操作,均由数据库会话管理。会话用db.session表示。在准备把数据写入数据库前,要先将数据添加到会话中然后调用commit()方法提交会话。 在Flask-SQLAlchemy中,查询操作是通过query对象操作数据。最基本的查询是返回表中所有数据,可以通过过滤器进行更精确的数据库查询。 ###在视图函数中定义模型类 from flask import Flask from flask_sqlalchemy import SQLAlchemy ​ ``` app = Flask(__name__) #设置连接数据库的URL app.config['SQLALCHEMY_DATABASE_URI'] = 'mysql://root:mysql@127.0.0.1:3306/Flask_test' app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = True #查询时会显示原始SQL语句 app.config['SQLALCHEMY_ECHO'] = True db = SQLAlchemy(app) class Role(db.Model): # 定义表名 __tablename__ = 'roles' # 定义列对象 id = db.Column(db.Integer, primary_key=True) name = db.Column(db.String(64), unique=True) us = db.relationship('User', backref='role') #repr()方法显示一个可读字符串 def __repr__(self): return 'Role:%s'% self.name class User(db.Model): __tablename__ = 'users' id = db.Column(db.Integer, primary_key=True) name = db.Column(db.String(64), unique=True, index=True) email = db.Column(db.String(64),unique=True) pswd = db.Column(db.String(64)) role_id = db.Column(db.Integer, db.ForeignKey('roles.id')) def __repr__(self): return 'User:%s'%self.name if __name__ == '__main__': app.run(debug=True) ``` ###模型之前的关联 **一对多** ```python class Role(db.Model): ... #关键代码 us = db.relationship('User', backref='role', lazy='dynamic') ... class User(db.Model): ... role_id = db.Column(db.Integer, db.ForeignKey('roles.id')) ``` 其中realtionship描述了Role和User的关系。在此文中,第一个参数为对应参照的类"User"; 第二个参数backref为类User申明新属性的方法;第三个参数lazy决定了什么时候SQLALchemy从数据库中加载数据,如果设置为子查询方式(subquery),则会在加载完User对象后,就立即加载与其关联的对象,这样会让总查询数量减少,但如果返回的条目数量很多,就会比较慢,另外,也可以设置为动态方式(dynamic),这样关联对象会在被使用的时候再进行加载,并且在返回前进行过滤,如果返回的对象数很多,或者未来会变得很多,那最好采用这种方式 **多对多** ```python registrations = db.Table('registrations', db.Column('student_id', db.Integer, db.ForeignKey('students.id')), db.Column('course_id', db.Integer, db.ForeignKey('courses.id')) ) class Course(db.Model): ... class Student(db.Model): ... classes = db.relationship('Course',secondary=registrations, backref='student', lazy='dynamic') ``` ###常用的SQLAlchemy查询过滤器 ![查询过滤器]() ###常用的SQLAlchemy查询执行器 ![查询执行器]() ###将数据添加到会话中示例: user = User(name='python') db.session.add(user) db.session.commit() ###创建表: ``` db.create_all() ``` ###删除表 ``` db.drop_all() ``` ###插入一条数据 ro1 = Role(name='admin') db.session.add(ro1) db.session.commit() #再次插入一条数据 ro2 = Role(name='user') db.session.add(ro2) db.session.commit() ###一次插入多条数据 us1 = User(name='wang',email='<EMAIL>',pswd='<PASSWORD>',role_id=ro1.id) us2 = User(name='zhang',email='<EMAIL>',pswd='201512',role_id=ro2.id) us3 = User(name='chen',email='<EMAIL>',pswd='987654',role_id=ro2.id) us4 = User(name='zhou',email='<EMAIL>',pswd='456789',role_id=ro1.id) db.session.add_all([us1,us2,us3,us4]) db.session.commit() ###查询:filter_by精确查询 返回名字等于wang的所有人 ``` User.query.filter_by(name='wang').all() ``` ![过滤名字]() ###first()返回查询到的第一个对象 ``` User.query.first() ``` ###all()返回查询到的所有对象 ``` User.query.all() ``` ![查询所有对象]() ###filter模糊查询,返回名字结尾字符为g的所有数据。 ``` User.query.filter(User.name.endswith('g')).all() ``` ![模糊查询]() ###get():参数为主键,如果主键不存在没有返回内容 ``` User.query.get() ``` ###逻辑非,返回名字不等于wang的所有数据 ``` User.query.filter(User.name!='wang').all() ``` ![逻辑非]() ###逻辑与,需要导入and,返回and()条件满足的所有数据 from sqlalchemy import and_ User.query.filter(and_(User.name!='wang',User.email.endswith('163.com'))).all() ![逻辑与]() ###逻辑或,需要导入or_ from sqlalchemy import or_ User.query.filter(or_(User.name!='wang',User.email.endswith('163.com'))).all() ![逻辑或]() ###not_ 相当于取反 from sqlalchemy import not_ User.query.filter(not_(User.name=='chen')).all() ![取反]() ###查询数据后删除 user = User.query.first() db.session.delete(user) db.session.commit() User.query.all() ###更新数据 user = User.query.first() user.name = 'dong' db.session.commit() User.query.first() ![更新数据]() ###关联查询示例:角色和用户的关系是一对多的关系,一个角色可以有多个用户,一个用户只能属于一个角色。 查询角色的所有用户 ``` #查询roles表id为1的角色 ro1 = Role.query.get(1) #查询该角色的所有用户 ro1.us.all() ``` ![查询角色的所有用户]() 查询用户所属角色 ``` #查询users表id为3的用户 us1 = User.query.get(3) #查询用户属于什么角色 us1.role ``` ![查询用户所属角色]() # 1.4 综合案例(图书管理) ###定义模型 模型表示程序使用的数据实体,在Flask-SQLAlchemy中,模型一般是Python类,继承自db.Model,db是SQLAlchemy类的实例,代表程序使用的数据库。 类中的属性对应数据库表中的列。id为主键,是由Flask-SQLAlchemy管理。db.Column类构造函数的第一个参数是数据库列和模型属性类型。 注:向数据库中插入中文后,会报错,需要修改数据库的编码集: ``` alter database 数据库名 CHARACTER SET utf8 ``` 如下示例:定义了两个模型类,作者和书名。 ``` #coding=utf-8 from flask import Flask,render_template,redirect,url_for from flask_sqlalchemy import SQLAlchemy app = Flask(__name__) #设置连接数据 app.config['SQLALCHEMY_DATABASE_URI'] = 'mysql://root:mysql@127.0.0.1:3306/test1' app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = True #实例化SQLAlchemy对象 db = SQLAlchemy(app) #定义模型类-作者 class Author(db.Model): __tablename__ = 'author' id = db.Column(db.Integer,primary_key=True) name = db.Column(db.String(32),unique=True) email = db.Column(db.String(64)) au_book = db.relationship('Book',backref='author') def __str__(self): return 'Author:%s' %self.name #定义模型类-书名 class Book(db.Model): __tablename__ = 'books' id = db.Column(db.Integer,primary_key=True) info = db.Column(db.String(32),unique=True) lead = db.Column(db.String(32)) au_book = db.Column(db.Integer,db.ForeignKey('author.id')) def __str__(self): return 'Book:%s,%s'%(self.info,self.lead) ``` ###创建表 ![创建表]() ###查看author表结构 desc author ![author表结构]() ###查看books表结构 desc books ![books表结构]() ``` #coding=utf-8 from flask import Flask,render_template,url_for,redirect,request from flask_sqlalchemy import SQLAlchemy from flask_wtf import Form from wtforms.validators import DataRequired from wtforms import StringField,SubmitField app = Flask(__name__) app.config['SQLALCHEMY_DATABASE_URI'] = 'mysql://root:mysql@localhost/test1' app.config['SQLALCHEMY_COMMIT_ON_TEARDOWN'] = True app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = True app.config['SECRET_KEY']='s' db = SQLAlchemy(app) #创建表单类,用来添加信息 class Append(Form): au_info = StringField(validators=[DataRequired()]) bk_info = StringField(validators=[DataRequired()]) submit = SubmitField(u'添加') ``` ​ ``` @app.route('/',methods=['GET','POST']) def index(): author = Author.query.all() book = Book.query.all() form = Append() if form.validate_on_submit(): #获取表单输入数据 wtf_au = form.au_info.data wtf_bk = form.bk_info.data #把表单数据存入模型类 db_au = Author(name=wtf_au) db_bk = Book(info=wtf_bk) db.session.add_all([db_au,db_bk]) db.session.commit() author = Author.query.all() book = Book.query.all() return render_template('index.html',author=author,book=book,form=form) else: if request.method=='POST': flash(u'输入错误,请重新输入') return render_template('index.html',author=author,book=book,form=form) #删除作者 @app.route('/delete_author<id>') def delete_author(id): au = Author.query.filter_by(id=id).first() db.session.delete(au) return redirect(url_for('index')) #删除书名 @app.route('/delete_book<id>') def delete_book(id): bk = Book.query.filter_by(id=id).first() db.session.delete(bk) return redirect(url_for('index')) ``` ​ ``` if __name__ == '__main__': db.drop_all() db.create_all() #生成数据 au_xi = Author(name='我吃西红柿',email='<EMAIL>') au_qian = Author(name='萧潜',email='<EMAIL>') au_san = Author(name='唐家三少',email='<EMAIL>') bk_xi = Book(info='吞噬星空',lead='罗峰') bk_xi2 = Book(info='寸芒',lead='李杨') bk_qian = Book(info='飘渺之旅',lead='李强') bk_san = Book(info='冰火魔厨',lead='融念冰') #把数据提交给用户会话 db.session.add_all([au_xi,au_qian,au_san,bk_xi,bk_xi2,bk_qian,bk_san]) #提交会话 db.session.commit() app.run(debug=True) ``` ###生成数据后,查看数据: ![生成数据]() ###模板页面示例: ``` <h1>玄幻系列</h1> <form method="post"> {{ form.csrf_token }} <p>作者:{{ form.au_info }}</p> <p>书名:{{ form.bk_info }}</p> <p>{{ form.submit }}</p> </form> {% for message in get_flashed_messages() %} {{ message }} {% endfor %} <ul> <li>{% for x in author %}</li> <li>{{ x }}</li><a href='/delete_author{{ x.id }}'>删除</a> <li>{% endfor %}</li> </ul> <hr> <ul> <li>{% for x in book %}</li> <li>{{ x }}</li><a href='/delete_book{{ x.id }}'>删除</a> <li>{% endfor %}</li> </ul> ``` ###添加数据后,查看数据: ![添加数据]() # 1.5 数据库迁移 在开发过程中,需要修改数据库模型,而且还要在修改之后更新数据库。最直接的方式就是删除旧表,但这样会丢失数据。 更好的解决办法是使用数据库迁移框架,它可以追踪数据库模式的变化,然后把变动应用到数据库中。 在Flask中可以使用Flask-Migrate扩展,来实现数据迁移。并且集成到Flask-Script中,所有操作通过命令就能完成。 为了导出数据库迁移命令,Flask-Migrate提供了一个MigrateCommand类,可以附加到flask-script的manager对象上。 首先要在虚拟环境中安装Flask-Migrate。 ``` pip install flask-migrate ``` ###创建迁移仓库 ``` #这个命令会创建migrations文件夹,所有迁移文件都放在里面。 python database.py db init ``` ![创建迁移仓库]() ###创建迁移脚本 自动创建迁移脚本有两个函数,upgrade()函数把迁移中的改动应用到数据库中。downgrade()函数则将改动删除。自动创建的迁移脚本会根据模型定义和数据库当前状态的差异,生成upgrade()和downgrade()函数的内容。对比不一定完全正确,有可能会遗漏一些细节,需要进行检查 ``` #创建自动迁移脚本 python database.py db migrate -m 'initial migration' ``` ![创建迁移脚本]() ###更新数据库 ``` python database.py db upgrade ``` ``` #coding=utf-8 from flask import Flask from flask_sqlalchemy import SQLAlchemy from flask_migrate import Migrate,MigrateCommand from flask_script import Shell,Manager app = Flask(__name__) manager = Manager(app) app.config['SQLALCHEMY_DATABASE_URI'] = 'mysql://root:mysql@127.0.0.1:3306/Flask_test' app.config['SQLALCHEMY_COMMIT_ON_TEARDOWN'] = True app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = True db = SQLAlchemy(app) #第一个参数是Flask的实例,第二个参数是Sqlalchemy数据库实例 migrate = Migrate(app,db) #manager是Flask-Script的实例,这条语句在flask-Script中添加一个db命令 manager.add_command('db',MigrateCommand) #定义模型Role class Role(db.Model): # 定义表名 __tablename__ = 'roles' # 定义列对象 id = db.Column(db.Integer, primary_key=True) name = db.Column(db.String(64), unique=True) user = db.relationship('User', backref='role') #repr()方法显示一个可读字符串, def __repr__(self): return 'Role:'.format(self.name) #定义用户 class User(db.Model): __talbe__ = 'users' id = db.Column(db.Integer, primary_key=True) username = db.Column(db.String(64), unique=True, index=True) #设置外键 role_id = db.Column(db.Integer, db.ForeignKey('roles.id')) def __repr__(self): return 'User:'.format(self.username) ``` ​ ``` if __name__ == '__main__': manager.run() ``` ###返回以前的版本 可以根据history命令找到版本号,然后传给downgrade命令: ``` python app.py db history ``` <base> -> 版本号 (head), initial migration ``` python app.py db downgrade 版本号 ``` ###实际操作顺序: - 1,python 文件 db init - 2,python 文件 db migrate -m"版本名" - 3,python 文件 db upgrade 然后观察表结构 - 4,根据需求修改模型 - 5,python 文件 db migrate -m"新版本名" - 6,python 文件 db upgrade 然后观察表结构 - 7,若返回版本,则利用 python 文件 db history查看版本号 - 8,python 文件 db downgrade 版本号 <file_sep># 发布新房源 1. ## 城区信息 1. ### 因为这个信息经常被调用,所以,要充分利用好redis+mysql配合使用. 2. flask的日常查询数据库`area_li = Area.query.all() 3. try ...Exception可以配合使用else 1. 意思是,代码 ```python try: function(xxx) except Exception as e: return xx else: #意思就是,假如没有错误的话,就运行这里 ``` 4. `to python`和`to dict` 1. 将对象转换为字典. ```python def to_dict(): d = { "a":'xx', } ``` 2. 然后其他函数就可以调用这个转换函数了 3. ### 上面的转换是在models里面设置的.! # 缓存机制 1. 首页大量去访问,所以得有缓存机制. 2. 首先去redis里面获取数据 1. 如果没有数据,就去mysql去获取数据 2. 然后顺便保存一份数据到redis 3. 下一次获取数据的时候,重复上面的步骤. 4. 这样子,多数重复的数据就可以去redis获取了.! 3. ## 问题,数据不同步 1. 一定要设置有效期, 2. ### 解决方法 1. 在操作mysql的时候,删除缓存数据 2. 给redis缓存数据设置有效期,保证过了有效期,缓存数据会被删除 # 用户模块修改 1. ## 在关于RESTFUL定义里面,修改信息,应该用`PUT`方法 2. 所以修改用户,提交的方法就使用put方法. 3. ## 因为在曾经写了一个装饰器,里面验证用户身份之后,会自动将用户的id自动保存到全局变量g对象中. 1. 然后在传过来的json格式的信息进行分类. 2. g对象的定义 `名字:g:global` 1. g对象是专门用来保存用户的数据的。 2. g对象在一次请求中的所有的代码的地方,都是可以使用的。(感觉像超全局对象) 4. ## 为了保证名字的唯一性,所以,就需要去查询数据库. 5. ## 然后日常操作数据库,都是使用commit,rollback,之类的.! 6. ## 还有一个就是如果成功修改了用户之后,记得session里面的名字也要记得一起修改. 7. 在返回头像的时候, 1. 如果用户存在头像的url地址的话,就给拼接前面的域名,不然的话,就返回为空就可以了. 8. 调用当前对象的`create_time.strftime("%Y-%m-%d %H:%M:%S")`,可以方便保存时间在数据库里面.! 1. 上面的create方法,原来取之于上面的基类里面的create_time来的,然后上面的用于是把当前时间转换格式.方便调用.! # 实名认证 1. 定义视图 2. 用route和login_required去装饰这个函数. 3. 反正就是一个普通的查询 4. ## 另外一个接口就是专用用于设置用户的认证信息 1. 请求方式是POST,第一次访问就使用POST. 2. ### 用户只能设置一次实名设置信息 1. 进行判断,加入user里面的id_card和real_name都为空才进行设置信息 flask日常数据库查询 `User.query.filter_by(id="xx",real_name=None,id_card=None) 5. 日常前端 1. 用ajax提交信息,很多时候都得传递json格式的数据,所以得用stringify,将字典类型转换为json格式! 2. 想想,如果用$.post的话,后面的传递不是也是字典吗? 1. 看了一下资料,关于$.post的参数说明,就是,最后一个dataType,原来是大概说让服务器可以返回哪些信息. 3. 然后都是叭叭叭日常前端信息判断和跳转. # 城区信息前端编写与前端模板的使用 1. 后端已经写好了,现在看看前端要怎么编写. 2. 前端接收后端传递过来的城区信息进行展示. 1. ## 老生常谈了,也是在定义加载好了之后,写js函数. 1. 关于在js的遍历 1. for循环 ```js for (i=0;i>=x;i++){xx} ``` 2. 然后对内容进行追加.对目标对象,进行下标迭代遍历. ```js for (i=0; i<areas.length; i++) { var area = areas[i]; $("#area-id").append('<option value="'+ area.aid +'">'+ area.aname +'</option>'); } ``` 3. ## 使用js模板,上面的操作的确可以通过后台获取到信息并且在前台展示,但是,现在有更加简便的方法. 1. ### 使用ART-TEMPLATE--高性能javascript 模板引擎 腾讯前员工开源的https://aui.github.io/art-template/zh-cn/docs/index.html 1. 实现. 2. 引入,在jq后面引入`xx/js/template.js` 2. ### 定义模板 1. 找位置定义模板 ```js <script type="text/html" id="编号名字" > {{each areas as area }} <option value="{{area.aid}}">{{ area.aname }}</option> {{/each}} </script> ``` 2. 然后ajax获取到数据之后,把这些数据放塞到模板里面. 3. 然后再利用js去渲染 3. ### 自己感觉就是少了去操作选择器了,不过也挺好的,对于熟悉选择器的人来说! 4. ### 使用template函数 1. 代码,注意了,下面里面的id-xx就是关键了,对象上面说的id="编号名字"了. ```js var html_text = template("id-xx",{areas:areas}) $("area-id").html(html); ``` 2. 这些东西看起来很jijia2X 3. 有个截图,可以看有道云的笔记.2018年8月22日 # 关于谷歌,关于如何查看网站加载模式,关于chrome,利用开发者工具,就是F12,然后找到source,就可以查看具体的运行过程了.<file_sep># 2.1 邮件扩展 在开发过程中,很多应用程序都需要通过邮件提醒用户,Flask的扩展包Flask-Mail通过包装了Python内置的smtplib包,可以用在Flask程序中发送邮件。 Flask-Mail连接到简单邮件协议(Simple Mail Transfer Protocol,SMTP)服务器,并把邮件交给服务器发送。 ###设置邮箱授权码 ![设置授权码](/images/identify_code.png) 如下示例,通过开启QQ邮箱SMTP服务设置,发送邮件。 ``` #coding:utf-8 from flask import Flask,render_template from flask_mail import Mail, Message from threading import Thread ``` ​ ``` app = Flask(__name__) # 配置邮件:服务器/端口/安全套接字层/邮箱名/授权码 app.config['MAIL_SERVER'] = 'smtp.126.com' app.config['MAIL_PORT'] = 465 app.config['MAIL_USE_SSL'] = True app.config['MAIL_USERNAME'] = 'ccyznhy' app.config['MAIL_PASSWORD'] = '<PASSWORD>' app.config['MY_MAIL_SENDER'] = 'Flasky Admin123<<EMAIL>>' app.config['MY_MAIL_TO'] = '939<EMAIL>' mail = Mail(app) ``` ​ ``` def send_async_email(app, msg): with app.app_context(): mail.send(msg) ``` ​ ``` def send_email(to, subject): msg = Message(subject,sender=app.config['MY_MAIL_SENDER'], recipients=[to]) msg.body = 'msg body' # msg.html = '<h1>html数据</h1>' thr = Thread(target=send_async_email, args=[app, msg]) thr.start() return thr ``` ​ ``` @app.route('/') def index(): send_email(app.config['MY_MAIL_TO'], 'New User') return "Sent Succeed" if __name__ == "__main__": app.run() ``` # 2.2 综合案例 需求: 在表单中提交输入内容,如果是第一次输入,则显示陌生人,并提示"第一次见到你",否则显示输入内容,并提示"很高兴再次见到你" 屏幕下方显示本地时间 效果图如下: ![案例效果图](/images/demo_result.png) ###案例分析: - 1,界面需要用到模板相关知识,如果需要快速实现,可以继承已有的flask-bootstrap扩展中的模板 - 2,表单使用flask-wtf相关知识 - 3,记录数据使用flask-sqlalchemy相关知识 ###数据库处理 app = Flask(__name__) app.config['SECRET_KEY'] = 'hard to guess string' app.config['SQLALCHEMY_DATABASE_URI'] ='mysql://root:mysql@127.0.0.1:3306/test' app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = True ``` manager = Manager(app) bootstrap = Bootstrap(app) moment = Moment(app) db = SQLAlchemy(app) migrate = Migrate(app, db) ``` ​ ``` class Role(db.Model): __tablename__ = 'roles' id = db.Column(db.Integer, primary_key=True) name = db.Column(db.String(64), unique=True) users = db.relationship('User', backref='role', lazy='dynamic') def __repr__(self): return '<Role %r>' % self.name ``` ​ ``` class User(db.Model): __tablename__ = 'users' id = db.Column(db.Integer, primary_key=True) username = db.Column(db.String(64), unique=True, index=True) role_id = db.Column(db.Integer, db.ForeignKey('roles.id')) def __repr__(self): return '<User %r>' % self.username #为数据库添加上下文信息,使得进入shell后,无需导入app,db,User,Role这些对象 def make_shell_context(): return dict(app=app, db=db, User=User, Role=Role) manager.add_command("shell", Shell(make_context=make_shell_context)) manager.add_command('db', MigrateCommand) if __name__ == '__main__': db.drop_all() db.create_all() manager.run() ``` ###界面处理 base.html ``` {% extends "bootstrap/base.html" %} {% block title %}Demo{% endblock %} {% block head %} {{ super() }} {% endblock %} {# 顶部内容 #} {% block navbar %} <div class="navbar navbar-inverse" role="navigation"> <div class="container"> <div class="navbar-header"> <button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-collapse"> <span class="sr-only">Toggle navigation</span> <span class="icon-bar"></span> <span class="icon-bar"></span> <span class="icon-bar"></span> </button> <a class="navbar-brand" href="/">Demo</a> </div> <div class="navbar-collapse collapse"> <ul class="nav navbar-nav"> <li><a href="/">主页</a></li> </ul> </div> </div> </div> {% endblock %} {# 内容部分 #} {% block content %} <div class="container"> {% for message in get_flashed_messages() %} <div class="alert alert-warning"> <button type="button" class="close" data-dismiss="alert">&times;</button> {{ message }} </div> {% endfor %} {% block page_content %}{% endblock %} </div> {% endblock %} {# 时间显示 #} {% block scripts %} {{ super() }} {{ moment.include_moment() }} {% endblock %} ``` index.html ``` {% extends "base.html" %} {% import "bootstrap/wtf.html" as wtf %} {% block title %}Demo{% endblock %} {% block page_content %} <div class="page-header"> <h1>你好, {% if name %}{{ name }}{% else %}陌生人{% endif %}!</h1> {% if not known %} <p>第一次见到你</p> {% else %} <p>很高兴再次见到你</p> {% endif %} {{ wtf.quick_form(form) }} <br/> <p>当前时间为: {{ moment(current_time).format('LLLL') }}.</p> </div> {% endblock %} ``` 404.html ``` {% extends "base.html" %} {% block title %}页面没有找到{% endblock %} {% block page_content %} <div class="page-header"> <h1>Not Found</h1> </div> {% endblock %} ``` 500.html ``` {% extends "base.html" %} {% block title %}服务器搬家了{% endblock %} {% block page_content %} <div class="page-header"> <h1>Internal Server Error</h1> </div> {% endblock %} ``` ###表单处理 class NameForm(FlaskForm): name = StringField(u'你叫什么名字?', validators=[DataRequired()]) submit = SubmitField('Submit') ###表单验证 ```python @app.route('/', methods=['GET', 'POST']) def index(): form = NameForm() if form.validate_on_submit(): user = User.query.filter_by(username=form.name.data).first() if user is None: user = User(username=form.name.data) db.session.add(user) session['known'] = False else: session['known'] = True session['name'] = form.name.data return redirect(url_for('index')) return render_template('index.html', form=form, name=session.get('name'), known=session.get('known', False),current_time=datetime.utcnow()) ``` ​ 2.3 控制代码块 ###if语句 Jinjia语法中的if语句跟Python中的if语句相似,后面的布尔值或返回布尔值的表达式将决定代码中的哪个流程会被执行: ``` {%if user.is_logged_in() %} <a href='/logout'>Logout</a> {% else %} <a href='/login'>Login</a> {% endif %} ``` 过滤器可以被用在if语句中: ``` {% if comments | length > 0 %} There are {{ comments | length }} comments {% else %} There are no comments {% endif %} ``` ###循环 我们可以在Jinjia中使用循环来迭代任何列表或者生成器函数 ``` {% for post in posts %} <div> <h1>{{ post.title }}</h1> <p>{{ post.text | safe }}</p> </div> {% endfor %} ``` 循环和if语句可以组合使用,以模拟Python循环中的break功能,下面这个循环将只会渲染post.text不为None的那些post: {% for post in posts if post.text %} <div> <h1>{{ post.title }}</h1> <p>{{ post.text | safe }}</p> </div> {% endfor %} 在循环内部,你可以使用一个叫做loop的特殊变量来获得关于for循环的一些信息,比如,要是我们想知道当前被迭代的元素序号,并模拟Python中的enumerate函数做的事情,则可以使用loop变量的index属性,例如: ``` {% for post in posts%} {{loop.index}}. {{post.title}} {% endfor %} ``` 会生成这样的结果: 1,Post title 2,Second Post cycle函数会在每次循环的时候,返回其参数中的下一个元素,可以拿上面的例子来说明: ``` {% for post in posts%} {{loop.cycle('odd','even')}} {{post.title}} {% endfor %} ``` 会输出这样的结果: odd Post Title even Second Post ###宏 对宏(macro)最合适的理解是把它看作Jinjia中的一个函数,它会返回一个模板或者HTML字符串,为了避免反复地编写同样的模板代码,可以把他们写成函数以进行重用,例如:下面的宏可以在你的模板中添加一个带有label标签且使用Bootstrap css的输入框 ``` {% macro input(name,label,value='',type='text') %} <div class="form-group"> <input type="{{type}}" name="{{name}}" value="{{value|escape}}" class="form-control"> </div> {% endmacro %} ``` 现在你就可以通过调用这个宏,快速的向表单插入一个输入框: 这会输出: <div class="form-group"> <input type="text" name="name" value="" class="form-control"> </div> 把宏单独抽取取来,封装成html文件,其它模板中导入使用 文件名可以自定义macro.html ``` {% macro function() %} <div class="form-group"> <input type="{{type}}" name="{{name}}" value="{{value|escape}}" class="form-control"> </div> {% endmacro %} ``` 在其它模板文件中先导入,再调用 ``` {% import 'macro.html' as func %} {% func.function() %} ``` # 2.4 模板的继承 ###基本使用 模板继承是为了重用模板中的公共内容。{% block head %}标签定义的元素可以在衍生模板中修改,extends指令声明这个模板继承自哪,父模板中定义的块在子模板中被重新定义,在子模板中调用父模板的内容可以使用super()。a ``` {% extends 'base.html' %} {% block content %} ... {% endblock %} ``` ###综合案例 通过访问url,显示不同的网页内容(见代码附件) # 2.5 Flask特有的变量和函数 你可以在自己的模板中访问一些Flask默认内置的函数和对象 **config** 你可以从模板中直接访问Flask当前的config对象: ``` {{config.SQLALCHEMY_DATABASE_URI}} sqlite:///database.db ``` **request** 就是flask中代表当前请求的request对象: ``` {{request.url}} http://127.0.0.1 ``` **session** 为Flask的session对象 ``` {{session.new}} True ``` **url_for()** url\_for会根据传入的路由器函数名,返回该路由对应的URL,在模板中始终使用url_for()就可以安全的修改路由绑定的URL,则不比担心模板中渲染出错的链接: ``` {{url_for('home')}} / ``` 如果我们定义的路由URL是带有参数的,则可以把它们作为关键字参数传入url_for(),Flask 会把他们填充进最终生成的URL中: ``` {{ url_for('post', post_id=1)}} /post/1 ``` **get\_flashed\_messages()** 这个函数会返回之前在flask中通过flask()传入的消息的列表,flash函数的作用很简单,可以把由Python字符串表示的消息加入一个消息队列中,再使用get\_flashed\_message函数取出它们并消费掉: ``` {%for message in get_flashed_messages()%} {{message}} {%endfor%} ``` <file_sep># 订单后端说明 1. 后端接收数据日常 1. 定义路由 2. 然后,根据是否需要权限,添加权限验证装饰器 3. 然后,考虑到是保存参数,所以,定义路由的时候是POST方法 2. 然后条件转换 1. 都是用try ...except这种形式. 2. 时间的转换 1. 日期转换 1. 计算预订的天数,`(end_date - start_date).days + 1` 3. 判断房子是否存在 4. 应用了g全局对象 5. 然后查询订单,使用filter,然后添加多个条件. 3. save_order 1. 一般保存数据的操作 4. 当提交完成以后,就调到<我的订单> 1. get_user_orders,用的方法是get方法,因为是查询 5. 还有一个就是客户订单,就是给房东看的. 6. 然后不管是用户还是房东,都公用一套接口 1. 方法就是,在get_user_orders后面添加参数,role=xxx 2. 要求用户必须登录,还有传递当前用户 7. 分页的话,看情况而定. 8. 通过house_id去查询所定的房子,或者查询订单数据. 1. 或者通过house_id查询自己的信息 2. 查询好了以后再排序 9. 然后就是接单和拒单了 1. 公用一套接口. 2. `order/<int:order_id>/status,method=PUT 3. 返回来的信息,只有两个, 1. accept 接单 2. reject 拒单 4. 对当前订单进行判断,看看是否具体相同的状态 10. 在数据库,如果需要建立索引的话,开启的方法是,amount = db.Column(xxx,index=True) 11. <file_sep>from .CCPRestSDK import REST #主帐号 accountSid= '8aaf0708654176180165421b0eab0022'; #主帐号Token accountToken= '<KEY>'; #应用Id appId='8aaf0708654176180165421b0f0c0029'; #请求地址,格式如下,不需要写http:// serverIP='app.cloopen.com'; #请求端口 serverPort='8883'; #REST版本号 softVersion='2013-12-26'; # 发送模板短信 # @param to 手机号码 # @param datas 内容数据 格式为数组 例如:{'12','34'},如不需替换请填 '' # @param $tempId 模板Id class CCP: """自己封装的发送短信的辅助类""" tag = None def __new__(cls): if cls.tag is None: cls.tag = super().__new__(cls) cls.tag.rest = REST(serverIP,serverPort,softVersion) cls.tag.rest.setAccount(accountSid,accountToken) cls.tag.rest.setAppId(appId) return cls.tag def send_template_sms(self,to,datas,temp_id): result = self.rest.sendTemplateSMS(to,datas,temp_id) # for k,v in result.items(): # if k=='templateSMS' : # for k,s in v.items(): # print ("%s:%s"%(k, s)) # else: # print ("%s:%s"%(k, v)) status_code = result.get('statusCode') if status_code == "000000": #表示发送成功 return 0 else: return -1 #初始化REST SDK #sendTemplateSMS(手机号码,内容数据,模板Id) if __name__ == "__main__": cpp = CCP() #id是魔板 cpp.send_template_sms("13249700923",["hello_world","10"],1) <file_sep># 项目说明 1. 前后端分离 1. django不是前后端分离 1. 意思是,数据业务处理和模板都是后端处理就是前后端不分离. 2. ## 前后端分离 1. 后端不在控制前端的效果展示 2. 所以说,跟上面的情况相关的就是前后端分离了!. 3. ### 执行的流程. 1. 例如用户通过浏览器请求index.html 2. 然后nginx返回index.html页面,里面估计有大量的js脚本. 3. 然后用户浏览器这一端通过js的ajax方法请求数据,这样子的一个形式. 4. #### 对,就是这种方式了.! 3. ## 怎么去理解前后端分离 1. 如果说,用户请求的是index.html页面,返回是nginx提供的index.html文件. 2. ### 我猜对了,就是服务端只返回json等格式数据! 4. ## 所以flask是一个轻量级的框架. 1. 因为,它可以只需要返回json格式的数据就可以了.!很轻. 5. ## 前前端后分离对于搜索引擎的缺点. 1. 从爬虫的角度思考.! 2. 爬虫只能获取到json数据了.! 3. ### 如何可以看到原始的这种分离的执行流程呢? 1. 在谷歌浏览器的这一端,平时是选择network工具的,现在去选择Sources 2. 6. ## 项目业务说明.! 1. 需求文档. 1. 但是不是所有公司都有提<需求文档>这种东东. 1. 有些可能是口头说的功能! 2. 例子:需求 1. 主页. 1. 5个房屋logo图片展示 2. 提供登陆/注册入口 3. 用户可以选择城区,入住时间等等. 4. 城区的区域信息需动态加载.! 2. 注册. 1. 用户账号手 3. 登陆 4. 房屋列表页 5. 房屋详情页 6. 房屋预定 7. 我的爱家 8. 个人信息修改 9. 我的订单 10. 实名认证 11. 我的房源 12. 发布新房源 13. 客户订单(房东) 14. 退出 3. 具体的完整需求文档可以看百度云盘. 1. 这里先截图一个.用于展示.! 4. 看起来有14个大需求.<file_sep># 图片验证码原理 1. 相关截图可以看8月15日的相关信息.有道云笔记. 2. ## 关于有效期 1. 保存到内存是否可以? 1. 可以,但是如果用户过了一年,验证码还是存在,还有没有意义? 2. 如果保存到数据库呢? 1. 数据库是持久保存,这样不太好.! 3. 最好就是放到redis当中!. 1. 将验证码的真实值存放到redis. 4. ## 验证码要和编号一起传递 5. ## 用户访问的时候就生成一个编号给用户.! 1. 然后用户请求验证码的时候,携带刚刚生成的编号 2. 然后去查询redis数据库.! 3. ### 在redis数据库使用setex,这是一个包含时间有效期的设置.这是设置一个String类型的!. # RESTFUL风格介绍 - 简书介绍的RESTFUL https://www.jianshu.com/p/265397f812d4 1. REST(Representational State Transfer) 定义了一套基于Web的数据交互方式的设计风格。 2. RESTful 符合REST风格的API就可以叫做RESTful API。注意,本文讲到的RESTful API设计方法将是基于HTTP和JSON实现方式,但不论HTTP还是JSON都不是REST的标准。REST只是风格,没有标准。 3. 动词、RPC 在微信里搜索【RESTful API 设计】,出来好多文章都是说怎么在RESTful Uri里使用动词等等,这些人除了一部分是把文章拿来抄一抄的,其他的其实搞混了REST和RPC的概念了,REST强调资源,RPC强调动作,所以REST的Uri组成为名词,RPC多为动词短语。然而它们也并不是完全不相关的两个东西,本文中的实现就会参考一部分JSON-RPC的设计思想。 4. Web Service 这个是一个更古老的概念,有一套它的理论,不过我更倾向于把它理解成任何基于Web提供的服务。 5. ## 设计方法及原则: 1. 使用HTTP方法: 更清晰API设计的可能会使用**GETPOST PUT DELETE**四种方法分别代表“查询、添加、更新、删除”等四个动作,这在概念上是符合HTTP规范的,如Google的如下API: 2. Uri格式: 3. 固定返回码 4. 固定返回结构 6. ## 综上所述,本文所探讨的API设计是这样的: 所有API的Uri为基于HTTP的名词性短语,用来代表一种资源。 Uri格式如文中所述。 使用GET POST PUT DELETE四种方法分别代表对资源的“查询、添加、更新、删除”。 服务端接收到客户端的请求之后,统一返回200,如果客户端获取到的返回码不是200,代表链路上某一个环节出了问题。 服务端所有的响应格式为: { “code”: -32600, “message”: “Invalid Request”, “data”:{ } } 他们的含义分别代表: code为0代表调用成功,其他会自定义的错误码; message表示在API调用失败的情况下详细的错误信息,这个信息可以由客户端直接呈现给用户,否则为空; data表示服务端返回的数据,具体格式由服务端自定义,API调用错误为空 1. 非强制性,推荐方法.博士推荐的.是风格. 2. 定义后端路径是怎么定义的. 3. api后面接的都是表示资源.(一) 4. 尽量使用4中操作(四) ----.GET(获取),POST(新建),DELETE(删除),PUT(更新) 5. 尽量保留版本(二) 1. 代码 ```python http://xx/api/1.0/info ``` 6. 如果是get资源的话,尽量不要出现动词,然后,要是出现动词的话,最好是在灾最后的名词?get=xx(三)(五) 7. 状态码 1. 200 OK 2. 201 CREATE 3. 202 ACCEPT 4. 400 错误 5. 401 没有权限 6. 406 用户请求格式错误 7. 500 服务器发生错误 8. 响应结果 # 使用captcha 1. 在python3里面出现了问题,TypeError: string argument expected, got 'bytes' https://blog.csdn.net/yu599207582/article/details/59109815 1. 解决办法: 1. 把StringIO替换成为BytesIO # 开发流程与接口文档编写 1. 分析需求 2. 编写代码 3. 单元测试(YES,终于可以做了.....)最后再讲!. 4. 自测 ? 5. 编写接口文档 1. 接口的名字 提供图片验证码 ```python ``` 2. 描述信息(描述清楚接口的功能) 3. 传入参数 4. 返回值 5. 举例 ```python 接口: 获取图片验证码 描述: 前端访问,可以获取到验证码图片 url: /api/v1.0/image_codes/<image_code_id> 参数参数: 格式:参数是查询字符串,请求体的表单,json,xml 名字 类型 是否必须 说明 image_code_id 字符串 是 验证图片的编码 返回值: 格式: 正常:图片, 异常:json 名字 类型 是否必传 说明 errno 字符串 否 错误代码 errmsg 字符串 否 错误内容 实例:xx '{"errno":"4001","errmsg":"保存图片验证码失败"}' ``` # 单元测试 1. 为什么需要测试? 1. 一个完整的开发过程包括这几个阶段 1. 需求分析 2. 设计阶段 3. 实现阶段 4. 测试阶段 2. 测试的分类 1. 单元测试 2. 集成测试 3. 系统测试 3. 与程序开发人员最密切的就是单元测试 4. ## 关于更多的整理好的资料,请参考本文件夹里面的<flask基础知识> 5. ## 用自己的话来表达<单元测试>,就是,把测试的过程记录下来,就是单元测试.! 6. ## assert 断言 1. 代码 ```python def num_div(num1,num2): assert isinstance(num1, int) assert isinstance(num2, int) print(num1/num2) if __name__ == '__main__': num_div(100,"b") ``` 2. ## 平时判断是用if,现在还可以用断言,assert 3. ## 单元测试 1. 代码 ```python import unittest class TestClass(unittest.TestCase): #该方法会首先执行,相当于做测试钱的准备工作 def setUp(self): pass #该方法会在测试代码执行完后执行,相当于做测试后的扫尾工作 def tearDown(self): pass #测试代码 #这部分定义的方法,前缀必须是test_这样的形式.! def test_app_exist(self): pass ``` 2. ### 测试案例图片,请参考有道云笔记的截图,8月16日 1. 构造测试请求,使用requests,urllib等等. 2. #### flask 提供客户端 1. from login import app 2. 创建进行web请求的客户端, ```python 1. client = app.test_client() ``` 3. 利用client客户端,模拟发送请求 1. ret = client.post("/login",data={}) 2. ret是视图返回的响应对象 ```python resp = ret.data #data是响应体的数据 ``` 3. 因为login视图返回的是json字符串 ```python resp = json.loads(resp) ``` 4. 拿到返回值进行断言测试 ```python self.assertIn("code",resp) self.assertEqual(resp['code'],1) #调用 if __name__ == '__main__': unittest.main() ``` 4. 里面的截图例子分别是用pycharm的测试和自己运行test.py模块,都有. 3. ## 单元测试,有一个特殊用法,setup 1. 意思:在执行测试案例之前,先执行这一步.!初始化的东西.! 4. ## 测试模式 1. 设置 app.config["TESTING"] = True 2. 开启以后,可以知道具体发生错误的位置发生在那个位置. 3. ### 这个模拟提交请求,然后把返回结果对比之后,进行判断.! 1. 但是,有意义吗? 2. #### 需要去了解自动测试的东东.! 3. 自動軟體測試、TDD 與 BDD 1. https://medium.com/@yurenju/%E8%87%AA%E5%8B%95%E8%BB%9F%E9%AB%94%E6%B8%AC%E8%A9%A6-tdd-%E8%88%87-bdd-464519672ac5 2. https://www.zhihu.com/question/49530527 3. # 编写前端去用接口! 1. 生成一个边好 1. 时间戳 2. uuid(全局唯一标识符) # 数据库测试 1. 首先打开app的测试, ```python app.testing = True ``` 2. 然后导入指定的model类. 1. 例子,from author_book import Author,db,app 3. ## setUp上面的这些操作,会在特殊函数,setUp函数里面提前加入参数, 1. ## 测试ING.还有具体说明一下,就是前面加入的参数,包括了加入了数据库的地址,到时候测试的时候,也不会用到什么真的数据!. 4. ##tearDown 结尾.! <file_sep># 图片存储服务的引入 1. # 问题 1. 图片保存到本地,扩容(磁盘满的问题) 2. 备份的问题 3. 多机存储问题 4. 重复图片问题 1. 包括重名不同文件 2. 不同文件名但文件内容相同. 5. 解决方案 1. FastDFS 快速分布式文件存储系统 2. HDFS Hadoop hadoop分布式文件系统 3. 七牛云存储 2. # 使用七牛 1. `pip install qiniu` 2. ## 使用七牛的put_data 1. 为什么不用put_file 1. 因为put_file还得指定一个文件名,所以这里就直接使用put_data就好了.! 3. 使用put_data的时候,key就设置为None就可以了.! 4. 简单的上传 ```python with open("xx.jpg",'rb') as f: file_data = f.read() storage(file_data) ``` 3. 获取文件 `f = request.files.get() ` # 上传用户图像 1. 在api下写profile.py 2. 添加好蓝图路径 3. 应用上一节的,如果要装饰函数的话,就多使用一个函数,返回被装饰函数的属性. ```python @api.route("xxx",methods=["POST"]) @login_required def set_user_avatar(): xxx ``` 4. 部分代码 ```python file1 = request.files.get() file1.read() ``` 1. 对对对,单一文件或者进入文件,最好还是设置一下,主文件启动, ```python if __name__ == "__main__": #这种形式 ``` 2. 然后假如图片成功上传了,就得返回数据了,给flask的数据库记录图片的网址. 3. 然后调用七牛图片. 1. 使用try来捕获异常. 4. 对用户对应的id模型类数据库更新头像的图片网址. 5. ## flask对数据库进行更新操作 1. User.query.filter_by(id=xx).update({"avatar_url":filename}) 2. session.commit() 3. 如果有问题就session.rollback() 4. 如果出问题可以记录一下日志 5. 有空的时候,做一下测试,因为上面的好像只使用update方法就可以更新数据了.! # 图片表单说明 1. ## 只要是传多媒体文件,你都要在form标签里面写`enctype="multipart/form-data"` 2. 然后input文件的type指明是"file",然后accept="image/*",作用是让用户筛选文件, 3. 既不想用ajax来处理上传图片的问题,但是普通的浏览器又不能处理 1. 这个时候就引入一个插件! 1. 引入`jquery.form.min.js` 2. ### 还有一个问题,ajax里面的data这个数据,我们无法很方便地定义. 2. 不知道为什么,每次绑定表单事件,都会回传一个参数回来,接收这个变量,随便起个什么名字都是可以的.! `e.preventDeafault` 3. 调用插件的ajaxSubmit ```python $(this).ajaxSubmit({ url: "/api/v1.0/users/avatar", type: "post", dataType: "json", headers: { "X-CSRFToken": getCookie("csrf_token") }, ``` 1. 在另外一端如何接收提交过来的图片呢? 1. 后端通过request.files.get("xx")获得的 4. ### 重点难点 1. 当上传的需求要求可预览、显示上传进度、中断上传过程、大文件分片上传等等,这时传统的表单上传很难实现这些功能,我们可以借助现有插件完成。 5. ajaxSubmit 1. jQuery使用ajaxSubmit()提交表单示例(转) https://blog.csdn.net/xinghuo0007/article/details/72806717 1. jquery.form.js的ajaxSubmit和ajaxForm使用 https://www.cnblogs.com/popzhou/p/4338040.html 7. 如百度上传插件Web Uploader、jQuery图片预览插件imgPreview 、拖拽上传与图像预览插件Dropzone.js等等,大家可根据项目实际需求选择适合的插件。 8. ### 看一下flask如何保存图片 1. 就是直接使用update更新数据的!. <file_sep># 云通讯介绍 1. 先注册 2. 然后稍微看一下模板. 3. 然后去SDK下载一个东东!demo.测试压缩包 https://www.yuntongxun.com/doc/ready/demo/1_4_1_2.html 4. 然后,我们想发短信的时候,调用一下函数就可以了. 1. 但是,好像有个但是,看看什么情况.! 2. 但是在调用send_template,已经持续在跟云通讯通信了. 3. 先拿到凭据,然后再进行通信. 4. ## 然后每次都调用上面的代码,重复去调用,会有延迟,所以可以自定义一个类.! 5. 然后把一些不应该重复的代码,就封装在类里面,但是又必须第一时间运行,就放到__init__里面就可以了. 1. 但是,注意了,如果这些代码需要被调用的话,还得设置赋值给self,不然的话,不好共享啊~.不设置就变成局部变量了.! 6. 然后还可以设置一个单例模式. 1. 忘记返回的是调用父类的new方法. 2. 除非是第一次实例化,返回父类的new方法,否则,都是返回已经实例化过的单类. 1. 这个例子里面,学到了,就是如果都是返回同一个类型的数值,判断条件又只有两个,就可以这样了,挺灵活的.! ```python def __new__(cls): if cls.tag !=None: return super().__new__(cls) return cls.tag ``` 3. ## 对,如果该文件不是被调用,如果这个文件,作为单独运行的,或者入口的话,都得设置 if __name__ = "__main__"来运行, 这是一个好习惯.! 4. 这...传智介绍的短信.....太烂了....都是基于python2的....意思是,我得精通python3..太好了.当做练习.! 7. python3里面,不建议使用urllib了. 8. python3里面,字典取消了iteritems(),直接被items()取缔了.! # 路由url地址转化原来就叫过滤器. 1. 这是是关于简书的一遍文章,说的就是转换器. https://www.jianshu.com/p/ce3028e9546e 2. ## 在flask中使用jsonify和json.dumps的区别 https://blog.csdn.net/Duke_Huan_of_Qi/article/details/76064225 1. 所以说,在flask中的话,就尽量多用jsonify. 3. ## 获取get过来的参数 1. 写法是 xx = request.args.get("xxx") 2. 然后使用if not all(['xx','yy']) 3. 然后我观察了一下路由和函数的关系 ```python @api.route("/sms_codes/<re(r'1[34578]\d{9}'):mobile>") def get_sms_code(mobile): ``` > 恩恩,顾名思义 4. ## 看一下flask操作数据库先! 1. ### 从redis获取str类型数据 ```python redis_store.get('xxx') ``` 2. ### 如果发生错误,调用当前的 currect_app.logger.error(e) 3. 记得经常返回json数据的话,用 return jsonify 4. ### 获取模型类的数据 ```python from models import xxx User.query.filter_by(mobile=mobile).first() ``` 5. 如果查询手机号码异常的话,就继续往下走.暂时不管了.! 6. 生成手机验证码>! 1. 生成随机数.使用random,---> sms_code = "%06d" % random.randint(0, 999999) 2. ### 字符串格式符."%06",注意了,6前面的0,意思是,这是一个固定的6位数,如果这个整数不足6位数的话,就自动补充0. 3. ### 保存真实验证码内容 1. 也是使用setex 5. 为什么,不用一个大的try来去捕获所有的错误?而这么麻烦去一个一个去写.! 1. except不能判断具体那一块出问题. 2. 在try中间的代码块还是越少越好,不然有时候可能会影响效率.! 6. ## 稍稍总结一下后台验证码的流程. - ### 强调一下,在python3里面麻烦就下载一下pip install captcha 1. 首先调用另外一个生成验证码的模块 1. 然后返回正式验证码,还有图片验证码 1. 说说细节,上面的模块调用会返回三个返回值 第一是:name,唯一值 第二是:真实验证码的字符串 第三是:图片流 2. ### 真实验证码就必须存到数据库,保存到redis数据库中.! 3. ### 图片验证码图片流就放到make_response(xx)里面. 1. #### 然后函数里面调用PIL的image,然后创建一个空白的, out = Bytes() 然后image.save = (out,format='JPEG') 4. ### 记得啊,这些视图处理函数都得返回信息啊!.返回图片流,而且是header-->Content-Type=image/jpeg 返回image.get_value()的的图片流 2. ### 然后某些容易出错部分,可以设置日志记录 2. 发送短信验证码 1. 生成随机的验证码. 1. 先生成UUID号码.然后绑定随机的验证码 2. 把真实值保存到redis中! 2. 调用短信API发送 1. 从数据库中获取图形验证码的真实值,然后保存到当前bianliang 1. 然后删除redis当中保存的验证码,防止多次验证.>((???为了防止爬虫?)) 2. 得用正则判断一下手机号码的有效性吧. 1. 然后就对比图形化验证码的有效性. 2. ### 然后,判断一下手机是否60秒过于频繁. 1. 如果是就返回! 3. 判断手机号码是否存在??????/ 1. 什么意思? 2. 看到了,是去User数据库里面找到,目标就看看这个用户是否注册过!. 3. 如果都正确就可以发送了.! # 修改前端,用来发送手机短信验证码 1. 如果点击了发送验证码之后,可以使用remoteAttr,去移除点击按钮.!暂时性的.等下重新添加属性.! 2. # 校验步骤 1. 接收数据 2. 校验数据 3. 业务处理 4. 返回数据<file_sep># 关于flask中,csrf过期的优化 1. 因为获取csrf的数值也是依赖浏览器中给定的session的数值。 2. ## 优化 1. 所以,在配置项中,添加Session(app),把数据存到redis当中。这个是利用`flask-session` 2. 因为请求过程是 1. 首先去前端的cookie取一个值 2. 然后到请求体或者python中 3. 然后就进行校验 4. ### flask-session是flask框架的session组件,由于原来flask内置session使用签名cookie保存,该组件则将支持session保存到多个地方 3. 解决: 1. 引入flask-session机制的话,默认的这些数值就不存在前端的cookie里面了。 2. 然后提取`csrf_token`的数值的话,现在就从redis里面提取了。 1. `csrf_token = redis.get('redis')` 3. flask-session在进行的时候,就添加了一个钩子(感觉很装饰器),对所有内容进行验证。 4. ### 想起来了一个很重要的问题,就是,原来之前的csrf的对比值,是对比session里面的csrf和body发送过来的csrf的数值进行对比。 1. 现在优化的这部分,是body对比redis中的数值。 5. ### 有三个地方存在csrf数值。 3. ## 重点了,如果如何呢? 1. 在退出的时候,不一次性删除 1. 首先提取csrf并且保存 2. 然后再使用session.clear 3. 然后就设置回去 4. 为什么放到最后才讲? 1. 为了就是认识csrf的认证机制。 # 关于数据库优化介绍 1. ## 如何解决并发问题 1. 最重要就是解决数据库的问题了。 2. 具体的优化细项目,请看目录里面的note.txt 3. 表结构设计 1. 扩展 2. 查询的快慢问题 3. 三范式 https://www.zhihu.com/question/24696366 1. 表要拆到不能再猜 2. 只保留主要的,非主要就提取出来 3. 非主要表,继续来拆分表 1. 如果某一部分的数据丢失的话,不至于影响全部的数据。 4. ## 查询优化->建立索引 菜鸟的讲解 http://www.runoob.com/mysql/mysql-index.html 1. 比如说现在`select * from ih_house_info where id=1;` 2. ### 实际上,上面的这些操作,是不断地去数据库逐条数据查询的,这样想当浪费时间。 3. 如何快速查询 1. 建立索引。(酒店前台,小姐姐围护的那个表,就是索引了,公安通过问小姐姐,直接就可以定位具体的数据在哪里,这就是索引了。) 4. ### 再次说明,其实,主键也是属于主键的一种,所以,查询`id`的时候,其实想当于可以直接找小姐姐拿数据了。 5. ### 还有唯一约束 1. 建立约束的时候也就是同时建立了主键 6. ### 索引 (key,index) 1. 在sql语句中 2. 通过`show create table xx`可以查询表结构 1. 顺便可以查询索引有那些 3. ### 联合主键,联合索引 1. 如果经常查询重复出现两个主键,那就整合两个主键为联合主键 2. #### SQL的实现方式:key `a_b_key` (a,b) 3. 不是直接放`index=True`,在flask里面实现: db.index("a_b",a,b) 4. #### 关于联合索引修改的问题 http://www.jianshu.com/p/2b541c028157 1. `alter table mytable add index name_city_age (name(10),city,age)` 1. ##### 对应上面的问题,建表时,username长度为16,这里用10,因为一般情况下名字和长度不会超过10 这样可以加速索引查询速度,还会减少索引文件的大小,提高INSERT的更新速度。 2. 然后查询的时候,必须是`username,city,age`或者`username,city`或者`username`,如果 都不是上面的这些形式的话,索引就白建立了。 7. ### 但是还是有坏处 1. 降低增删改的速度 2. 所以说,也不能设置过多 8. 通过index创建索引 1. `create INDEX indexName ON mytable(username(length)) 2. 代码 ```python CREATE TABLE mytable( ID INT NOT NULL, username VARCHAR(16) NOT NULL, INDEX [indexName] username(length)) ); ``` 3. 删除的方法 `drop INDEX [indexName] ON mytable` 5. ### 最左原则。 1. 就是关于查询的时候,建议where后面的条件顺序,最后把有建立索引的字段放在最前面 6. ### 修改表索引 1. 7. ### 关于django的优化小提及 1. 如果模型类查询速度实在太慢了,就手动查询语句 1. 只要在程序中去查询的话,一定不要使用`select *`,效率不一定高,主要是没有必要,尽量就节约网络流量。 8. ### 可以使用联合查询,就尽量不适用嵌套查询(子查询) 1. `join`是联合查询 2. `select xx from xx where filed = (select xx from yy )`是子查询 2. ## 外键,作用,保证数据的完整性。 1. 如果使用参数选项,`cascade`级联,就可以删除外键的时候,顺便删除对应牵连的数据(围护外键有额外开销,影响性能) 2. 使用分析工具分析效率低的sql语句 慢查询工具 https://flyerboy.github.io/2016/12/23/mysql_slow/ https://yemengying.com/2016/05/24/mysql-tuning/ 3. ### 如果数据大的时候,不在使用外键 3. ## 缓存 1. redis 2. memcached 4. 读写备份 1. 读写分离 2. 主从备份 2. 主从热备份 1. 查的操作可以和增删改分离。 5. ## 分库分表(上亿,几千万的数据) 1. http://www.infoq.com/cn/articles/key-steps-and-likely-problems-of-split-table 2. ### 垂直分表(通俗的说法是,"大表拆小表") 1. 某一个表中的字段过多,就可以新建立一张扩展表 3. ### 垂直分库 1. 以数据库的方向来切。 2. 比如说,订单就单独分为一个数据库,用户就分为一个单独的数据 4. ### 水平分表(用得最多) 1. 相同的字段,不过分几个表来保存这些类似的数据,例如xx_user1,xx_user2 2. 但是预防id重复,主键重复。 1. 自己维护id表 2. 而且这个分表了,但是,还是在同一个磁盘操作,所以还是会卡的。 3. 把数据表都设置在不同的数据库,不同的主机当中。 # 工作流程 1. 分析需求 2. 编写代码 3. 编写单元测试 4. 自测 5. 编写接口文档 6. 提测代码 # 账号 1. email 2. git账号(gitlab) 1. 权限 1. 具体产品 2. rsa密钥 3. vpn账号 阿里云,腾讯云,aws亚马逊 4. 公司可能让你去熟悉公司的业务,代码等等。 5. <file_sep># 2.1 模版 ### 模版 ###知识点 - 模板使用 - 变量 - 过滤器 - web表单 - 控制语句 - 宏与继承 - Flask中的特殊变量和方法 在flask中,内置了一个模版语言,称之为Jinjia2,它是由Python实现的模版语言. 模版语言是一种被设计来自动生成文档的简单文本格式,在模版语言中,一般都会把一些变量传给模版,替换模版的特定位置上预先定义好的占位变量名 在Jinjia中,变量名是由{{}}来表示的,这种{{}}语法叫做变量代码块,另外还有用{% %}定义的控制代码块,可以实现一些语言层次的功能,比如循环或者if语句 例子: <h1>{{ post.title }}</h1> Jinjia模版中的变量代码块可以是任意Python类型或者对象,只要它能够被Python的str()方法转换为一个字符串就可以,比如,可以通过下面的方式显示一个字典或者列表中的某个元素: {{your_dict['key']}} {{your_list[0]}} # 2.2 过滤器 一种常见的错误观点是,Jinjia和Python差不多,因此它们看起来很像,但其实Jinjia和Python有很多不同之处,在jinjia中一些常用的Python函数其实并不存在,在Jinjia中可以把变量传给一些内建的函数来进行某些修改,以满足显示的需要,这些函数叫做过滤器(filter),在变量代码块中使用管道操作符|可以调用它们 ``` {{variable | filter_name(*args)}} ``` 如果没有任何参数传给过滤器,则可以把括号省略掉 ``` {{variable | filter_name}} ``` 过滤器也可以在控制代码块中调用,这样就可以对一整块文字应用这个过滤器: {% filter filter_name %} 一大堆文字 {% endfilter %} **default** 变量在为假值的时候被替换成默认值,把传给default的第2个参数设为True: ``` {{'' | default{'An empty string', True}}} ``` **float** 可使用Python的float()方法将传入只转换为浮点数显示: ``` {{75|float}} ``` **int** 可使用Python的int()方法将传入值转换为整数显示: ``` {{12.5|int}} ``` **join** 这个过滤器会把列表拼成一个字符串,与list的同名方法的作用完全一样 ``` {{['Python','SQL'] |join(',')}} ``` **length** 这个过滤器扮演了与Python中的len()方法同样的角色 ``` {{post.tags|length}} ``` **round** 它会把一个浮点数转换到给定的小数位数 ``` {{3.1415926 | round(1)}} ``` 你还可以指定如何转换: {{4.8 | round(1,"common")}} {{4.2 | round(1,"common")}} {{4.8 | round(1,"floor")}} {{4.2 | round(1,"ceil")}} common代表的方式就跟我们在生活中做的一样:对多位数进行四舍五入,floor则总是把位数直接截断,ceil总是会向上取整,不论后面的小数是多少 **safe** 如果你向直接把HTML作为变量插入页面中,比如在想显示一部分内容的时候,Jinjia会自动尝试对输出进行HTML转义 ``` {{"<h1>test content</h1>"}} ``` 这是必要的安全措施,如果应用某个输入接口允许用户提交任何文本,那么恶意用户也可以用它来提交HTML代码,比如,一名用户在恢复狂里提交了含有script标签的文本,如果Jinjia没有转义功能,那么访问这个页面的所有浏览器都会执行这个标签中的脚本 但是,我们仍然需要一种方式,对安全的HTML不转义且直接显示,例如我们当然能确保HTML内容是安全的,这样可以用safe来实现 ``` {{"<h1>test content</h1>" | safe}} ``` **title** 可以把字符串中单词的手自缚改为大写格式: ``` {{"test content" | title}} ``` **tojson** 可以用这种方式调用Python的json.dumps函数来序列化对象,需要确保传过去的对象是被json模块序列化的: ``` {{ {'key':False, 'key2':None , 'key3': 45} | tojson}} ``` **trucate** 用于接收一个长字符串,返回一个截断成指定长度的字符串,并添加省略号: ``` {{"test content test content test content test content" | truncate(10)}} ``` 在缺省状态下,任何从中间被截断的单词会被丢弃掉,如果不想这样,则可以传一个额外的参数值True: ``` {{"test content test content test content test content" | truncate(10,True)}} ``` **capitalize** 把变量值的首字母转成大写,其余字母转小写 ``` {{ 'hello' | capitalize }} ``` **lower** 把值转成小写 ``` {{ 'HELLO' | lower }} ``` **upper** 把值转成大写 ``` {{ 'hello' | upper }} ``` **trim** 把值的首尾空格去掉 ``` {{ ' hello world ' | trim }} ``` **format** 格式化输出 ``` {{ '%s is %d' | format('name',17) }} ``` **striptags** 渲染之前把值中所有的HTML标签都删掉 ``` {{ '<em>hello</em>' | striptags }} ``` 自定义过滤器 在Jinjia中增加一个过滤器非常简单,就跟在Python中写一个函数一样,我们可以通过一个例子来理解过滤器的原理,下面这个简单的过滤器计算一个子字符串在元字符串中出现的次数,并且将其返回,调用方式是: ``` {{variable | filter_name("string")}} ``` 因此我们可以这样定义过滤器函数: def count_substring(string, sub): return string.count(sub) 我们需要在main.py文件中手动地把它加入到jia_env对象的filter字典,以使该函数可作为过滤器被调用: ``` app.jinjia_env.filters['count_substring'] = count_substring ``` **注释** 模板中的注释使用{# #}来定义,不会出现在生成的HTML中,例如: {# 我是注释 #} # 2.3 控制代码块 ###if语句 Jinjia语法中的if语句跟Python中的if语句相似,后面的布尔值或返回布尔值的表达式将决定代码中的哪个流程会被执行: {%if user.is_logged_in() %} <a href='/logout'>Logout</a> {% else %} <a href='/login'>Login</a> {% endif %} 过滤器可以被用在if语句中: {% if comments | length > 0 %} There are {{ comments | length }} comments {% else %} There are no comments {% endif %} ###循环 我们可以在Jinjia中使用循环来迭代任何列表或者生成器函数 {% for post in posts %} <div> <h1>{{ post.title }}</h1> <p>{{ post.text | safe }}</p> </div> {% endfor %} 循环和if语句可以组合使用,以模拟Python循环中的break功能,下面这个循环将只会渲染post.text不为None的那些post: {% for post in posts if post.text %} <div> <h1>{{ post.title }}</h1> <p>{{ post.text | safe }}</p> </div> {% endfor %} 在循环内部,你可以使用一个叫做loop的特殊变量来获得关于for循环的一些信息,比如,要是我们想知道当前被迭代的元素序号,并模拟Python中的enumerate函数做的事情,则可以使用loop变量的index属性,例如: {% for post in posts%} {{loop.index}}. {{post.title}} {% endfor %} 会生成这样的结果: 1,Post title 2,Second Post cycle函数会在每次循环的时候,返回其参数中的下一个元素,可以拿上面的例子来说明: {% for post in posts%} {{loop.cycle('odd','even')}} {{post.title}} {% endfor %} 会输出这样的结果: odd Post Title even Second Post ###宏 对宏(macro)最合适的理解是把它看作Jinjia中的一个函数,它会返回一个模板或者HTML字符串,为了避免反复地编写同样的模板代码,可以把他们写成函数以进行重用,例如:下面的宏可以在你的模板中添加一个带有label标签且使用Bootstrap css的输入框 {% macro input(name,label,value='',type='text') %} <div class="form-group"> <input type="{{type}}" name="{{name}}" value="{{value|escape}}" class="form-control"> </div> {% endmacro %} 现在你就可以通过调用这个宏,快速的向表单插入一个输入框: 这会输出: <div class="form-group"> <input type="text" name="name" value="" class="form-control"> </div> 把宏单独抽取取来,封装成html文件,其它模板中导入使用 文件名可以自定义macro.html {% macro function() %} <div class="form-group"> <input type="{{type}}" name="{{name}}" value="{{value|escape}}" class="form-control"> </div> {% endmacro %} 在其它模板文件中先导入,再调用 {% import 'macro.html' as func %} {% func.function() %} # 2.4 模板的继承 ###基本使用 模板继承是为了重用模板中的公共内容。{% block head %}标签定义的元素可以在衍生模板中修改,extends指令声明这个模板继承自哪,父模板中定义的块在子模板中被重新定义,在子模板中调用父模板的内容可以使用super()。 {% extends 'base.html' %} {% block content %} ... {% endblock %} ###综合案例 通过访问url,显示不同的网页内容(见代码附件) # 2.5 Flask特有的变量和函数 你可以在自己的模板中访问一些Flask默认内置的函数和对象 **config** 你可以从模板中直接访问Flask当前的config对象: {{config.SQLALCHEMY_DATABASE_URI}} sqlite:///database.db **request** 就是flask中代表当前请求的request对象: {{request.url}} http://127.0.0.1 **session** 为Flask的session对象 {{session.new}} True **url_for()** url\_for会根据传入的路由器函数名,返回该路由对应的URL,在模板中始终使用url_for()就可以安全的修改路由绑定的URL,则不比担心模板中渲染出错的链接: {{url_for('home')}} / 如果我们定义的路由URL是带有参数的,则可以把它们作为关键字参数传入url_for(),Flask 会把他们填充进最终生成的URL中: {{ url_for('post', post_id=1)}} /post/1 **get\_flashed\_messages()** 这个函数会返回之前在flask中通过flask()传入的消息的列表,flash函数的作用很简单,可以把由Python字符串表示的消息加入一个消息队列中,再使用get\_flashed\_message函数取出它们并消费掉: {%for message in get_flashed_messages()%} {{message}} {%endfor%} <file_sep># 保存房屋基本信息数据后端编写 1. 整理好前端的基本信息 2. 还有配套设施(有冇WIFI/空调/暖气等等)) 3. 补充一下check,`<li class="col01"><input type="checkbox" name="sku_ids" value={{ sku.id }} checked></li>` 4. checkbox,不做特殊处理,只返回name和true值 1. 首先需要传递id数值 1. 理想传递是这样的`"facility":['7','8'] 2. 如何传递id数值 1. 5. ## 后端接收数据 1. house_data = request.get_json() 2. xx = house_data.get('xx') 3. 然后就检验参数 1. 如果参数有问题,可以引起异常 4. 业务处理 1. 保存数据 ```python house = House(user_id=user_id,area_id=area_id,title=title,address=address,room_count=room_count,acreage=acreage,xxx) try: db.session.add(house) #db.session.commit() except Exception as e: db.session.rollback() ``` 2. ### 准备处理房屋的设施信息 1. 代码 ```python #如果用户勾选了再保存数据库信息 #需要进行过滤 facxxx_ids = house.get('') if facilities: try: Facility.query.filter(Facility.id.in_(facxxx_ids)) except Exception as e: return jsonify("xxx") if facilities: #表示有合法的数据 #保存设施数据 #利用关联数据库保存数据 house.facilities = facilities try: db.session.add(house) db.session.commit() except Exception as e: db.session.rollback() retutn "xxx" ``` 3. ### 需要过滤信息表 4. 看了一下,Facility这个数据库模型类,居然只有id和name信息. 5. return house_id 6. ## 上传图片是需要house_id的. # 保存房屋图片后端编写 1. 两个装饰器`@api.route+@login_required` 2. 请求house_id ```python iamge_file = request.files.get("house_image") house_file = request.form.get("house_id") ``` 3. 判断house是否存在 1. 使用try 4. 调用函数去保存图片到七牛服务器.! ```python try: file_name = storage(image_data) except Exception as e: current_app.logger.error(e) return jsonify() ``` 5. 然后就保存数据,flask,多个数据库同时保存信息. ```python # 保存图片信息到数据库中 house_image = HouseImage(house_id=house_id, url=file_name) db.session.add(house_image) # 处理房屋的主图片 if not house.index_image_url: house.index_image_url = file_name db.session.add(house) try: db.session.commit() except Exception as e: current_app.logger.error(e) db.session.rollback() return jsonify(errno=RET.DBERR, errmsg="保存图片数据异常") ``` 6. 然后拼接一下链接.! # 补充一下关于db.session的知识. 1. 多个数据库插入数据库,可以一次db.session.add(xx) 1. 如果先一次性写完,可以写成列表的形式,db.session.add_all([xx1,xx2]) 2. flask更新数据 1. `db.session.add(xx)` 2. `db.session.commit()` 3. 或者可以试试直接`User.query.filter_by(id=xx).update({"avatar_url":filename})` 3. flask删除行 1. `db.session.delete(xxx)` 2. `db.session.commit()` # 保存房屋基本信息前端代码 1. 什么是serializeArray() 1. serialize()序列化表单元素为字符串,用于 Ajax 请求。 2. serializeArray()序列化表单元素为JSON数据。 2. 获取前端数据`$("#form-house-info").serializeArray()` 3. js的map方法 1. `$("#form-house-info").serializeArray().map(function(x){data['x.name']=x.value})` 2. 然后直接查看data数据就知道数据已经组织好了.! 4. 但是,看图,有道云笔记的,标题和上面的对应. 1. facxxxx需要特殊处理一下.! 1. ```js var facXX = [] $(":checked[name=facility]").each(function(index,x){facXX[index] = $(x).val()}) ``` 上面的说明:x是一个对象,所以还得用jq去再获取一下数值 2. 补充js的each知识 1. 参数 描述 function(index,element) 必需。为每个匹配元素规定运行的函数。 index - 选择器的 index 位置 element - 当前的元素(也可使用 "this" 选择器) 5. 然后整理好数据之后,就往后端塞数据了.! ```python $.ajax({ url: "/api/v1.0/houses/info", type: "post", contentType: "application/json", data: JSON.stringify(data), dataType: "json", headers: { "X-CSRFToken": getCookie("csrf_token") }, ``` # 发布房源 1. 前端 1. 表单的提交 1. 引入异步提交的js插件,form.js 2. data参数就不用管,等插件自己处理就可以了. 2. 然后成功的回调函数,里面对`$(".house-image-cons").append('<img src="xxxx">')`<file_sep>#第一步导入flask模块 from ihome import create_app, db from flask_script import Manager from flask_migrate import Migrate, MigrateCommand app = create_app('develop') manager = Manager(app) Migrate(app,db) manager.add_command('db',MigrateCommand) if __name__ == "__main__": manager.run()<file_sep># 1.5 利用uwsgi和nginx进行服务器部署 ###阿里云服务器 - 1,选择云服务器:阿里云服务器 - 2,购买服务器:在首页最底下有一个免费使用的优惠购买:最便宜的套餐为9.9元,送一个入门级别的云服务器ECS和其他的一些服务器 - 3,购买后,再次进入首页最底下,点击免费获取 ![免费获取1](/images/free_get1.png) - 4,进入如下图所示的界面,点击第一项云服务器ECS的立即开通(由于本人已经创建,故:没有显示立即开通,而是前往控制台).注:创建服务器选择ubuntu16.04 64位的操作系统 ![免费获取2](/images/free_get2.png) ![创建服务器](/images/server_create.png) - 4,进入控制台,查看实例创建情况 ![控制台](/images/instance.png) - 5,利用命令行进行远程服务器登陆 打开本地的ubuntu系统,通过ssh命令进行登陆 ``` ssh 用户名@ip地址 ``` ``` 输入密码:<PASSWORD> ``` ##登陆后的相关软件安装 ###python和pip 这两个环境是ubuntu16.04自带的 ###uwsgi安装 uwsgi是一个能够运行flask项目的高性能web服务器 需要先安装两个依赖 ``` apt-get install build-essential python-dev ``` 然后进行uwsgi的安装 ``` pip install uwsgi ``` ###nginx安装 通过指令进行安装 ``` apt-get install nginx ``` ###hello world程序的部署 1,利用pycharm创建python项目 2,利用scp命令将整个项目上传到远程服务器中 在本地目录下输入指令: ``` scp -r 本地目录 用户名@ip地址:远程目录 ``` 3,创建config.ini文件作为uwsgi的初始化配置文件 [uwsgi] #需要声明uwsgi使得uwsgi能够识别当前文件 master = true socket = :5000 #如果单纯运行uwsgi文件则使用http,如果和nginx配合,则使用socket processes = 4 #设定进程数 threads = 2 #设定线程数 wsgi-file = app.py #指定运行的文件 chdir = /home/hello #指定运行的项目的目录 callable = app #指定运行的实例 buffer-size = 32768 #指定uwsgi服务器的缓冲大小 4,通过指令运行uwsgi.ini服务器 ``` uwsgi --ini config.ini -d uwsgi.log ``` 其中 --ini config.ini 表示指定运行的配置文件 -d uwsgi.log 表示uwsgi在后台运行,运行过程中产生的日志会存储在uwsgi.log中 5,配置nginx服务器 编辑文件:/etc/nginx-sites-available/default 修改为如下内容: server { listen 80 default_server; server_name 192.168.127.12; location / { include uwsgi_params; uwsgi_pass 192.168.127.12:5000; uwsgi_read_timeout 100; } } 将server中原有的,上述配置中不能存在的内容注释或删除掉 6,启动和停止nginx服务器 ``` /etc/init.d/nginx start ``` ``` /etc/init.d/nginx stop ``` ###本地项目的远程部署 软件的安装: mysql的安装: ``` apt-get install mysql-server ``` ``` apt-get install libmysqlclient-dev ``` 虚拟环境的安装 virtualenv和virtualenvwrapper的安装: ``` pip install virutalenv ``` ``` pip install virutalenvwrapper ``` 使得安装的virtualenvwrapper生效: - 1,编辑~/.bashrc文件 内容如下: export WORKON_HOME=$HOME/.virtualenvs export PROJECT_HOME=$HOME/workspace source /usr/local/bin/virtualenvwrapper.sh - 2,使编辑后的文件生效 ``` source ~/.bashrc ``` - 3,创建虚拟环境 ``` mkvirtualenv 虚拟环境名称 ``` - 4,在虚拟环境中安装项目所需要的依赖 ``` pip install -r 依赖文件(requirements.txt) ``` - 5,通过scp命令将整个项目上传到远程服务器 - 6,创建config.ini文件,配置和之前一致,但要加入一个虚拟环境的配置 ``` pythonpath = /root/.virtualenvs/flask_test/lib/python2.7/site-packages #表示指定虚拟环境目录,使用虚拟环境中安装的扩展 ``` - 7,运行uwsgi和之前操作一致,但要修改项目目录 - 8,运行nginx和之前操作一致,但要修改项目目录<file_sep>基本关系模式 快速了解基本关系模式。 用于以下每个部分的导入如下: ```python from sqlalchemy import Table, Column, Integer, ForeignKey from sqlalchemy.orm import relationship from sqlalchemy.ext.declarative import declarative_base Base = declarative_base() ``` 一对多 一对多关系将外键放在引用父对象的子表上。 relationship()然后在父项上指定,作为引用子项表示的项集合: ```python class Parent(Base): __tablename__ = 'parent' id = Column(Integer, primary_key=True) children = relationship("Child") class Child(Base): __tablename__ = 'child' id = Column(Integer, primary_key=True) parent_id = Column(Integer, ForeignKey('parent.id')) ``` 要在一对多中建立双向关系,其中“反向”是多对一,请指定一个附加relationship()并使用以下relationship.back_populates参数连接两者: ```python class Parent(Base): __tablename__ = 'parent' id = Column(Integer, primary_key=True) children = relationship("Child", back_populates="parent") class Child(Base): __tablename__ = 'child' id = Column(Integer, primary_key=True) parent_id = Column(Integer, ForeignKey('parent.id')) parent = relationship("Parent", back_populates="children") ``` Child将获得parent具有多对一语义的属性。 或者,该backref选项可用于单个relationship()而不是使用 back_populates: 重点!这个backref,原来只是一个名字而已! ![image.png](https://upload-images.jianshu.io/upload_images/4151356-03874685b6eb8b10.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240) ```python class Parent(Base): __tablename__ = 'parent' id = Column(Integer, primary_key=True) children = relationship("Child", backref="parent") ``` ------ 多对一 多对一将外键放在引用该子对象的父表中。 relationship()在父级上声明,将创建一个新的标量持有属性: ```python class Parent(Base): __tablename__ = 'parent' id = Column(Integer, primary_key=True) child_id = Column(Integer, ForeignKey('child.id')) child = relationship("Child") class Child(Base): __tablename__ = 'child' id = Column(Integer, primary_key=True) 通过添加秒relationship() 并relationship.back_populates在两个方向上应用参数来实现双向行为: ```python class Parent(Base): __tablename__ = 'parent' id = Column(Integer, primary_key=True) child_id = Column(Integer, ForeignKey('child.id')) child = relationship("Child", back_populates="parents") class Child(Base): __tablename__ = 'child' id = Column(Integer, primary_key=True) parents = relationship("Parent", back_populates="child") 或者,backref参数可以应用于单个relationship(),例如Parent.child: class Parent(Base): __tablename__ = 'parent' id = Column(Integer, primary_key=True) child_id = Column(Integer, ForeignKey('child.id')) child = relationship("Child", backref="parents") ``` ------ 一对一 One To One本质上是双向关系,双方都有标量属性。为实现此目的,该uselist标志指示在关系的“多”侧放置标量属性而不是集合。将一对多转换为一对一: ```python class Parent(Base): __tablename__ = 'parent' id = Column(Integer, primary_key=True) child = relationship("Child", uselist=False, back_populates="parent") class Child(Base): __tablename__ = 'child' id = Column(Integer, primary_key=True) parent_id = Column(Integer, ForeignKey('parent.id')) parent = relationship("Parent", back_populates="child") ``` 或多对一: ```python class Parent(Base): __tablename__ = 'parent' id = Column(Integer, primary_key=True) child_id = Column(Integer, ForeignKey('child.id')) child = relationship("Child", back_populates="parent") class Child(Base): __tablename__ = 'child' id = Column(Integer, primary_key=True) parent = relationship("Parent", back_populates="child", uselist=False) ``` 与往常一样,可以使用relationship.backref和backref()函数来代替relationship.back_populates方法; 要uselist在backref 上指定,请使用以下backref()函数: ```python from sqlalchemy.orm import backref class Parent(Base): __tablename__ = 'parent' id = Column(Integer, primary_key=True) child_id = Column(Integer, ForeignKey('child.id')) child = relationship("Child", backref=backref("parent", uselist=False)) ``` ------ 多对多 Many to Many在两个类之间添加了一个关联表。关联表由secondary参数表示 relationship()。通常,Table使用MetaData 与声明性基类关联的对象,以便ForeignKey 指令可以找到要链接的远程表: ```python association_table = Table('association', Base.metadata, Column('left_id', Integer, ForeignKey('left.id')), Column('right_id', Integer, ForeignKey('right.id')) ) class Parent(Base): __tablename__ = 'left' id = Column(Integer, primary_key=True) children = relationship("Child", secondary=association_table) class Child(Base): __tablename__ = 'right' id = Column(Integer, primary_key=True) ``` 对于双向关系,关系的两侧都包含一个集合。指定using relationship.back_populates,并为每个relationship()指定公共关联表: ```python association_table = Table('association', Base.metadata, Column('left_id', Integer, ForeignKey('left.id')), Column('right_id', Integer, ForeignKey('right.id')) ) class Parent(Base): __tablename__ = 'left' id = Column(Integer, primary_key=True) children = relationship( "Child", secondary=association_table, back_populates="parents") class Child(Base): __tablename__ = 'right' id = Column(Integer, primary_key=True) parents = relationship( "Parent", secondary=association_table, back_populates="children") ``` 当使用backref参数代替时 relationship.back_populates,backref将自动使用相同的secondary参数作为反向关系: ```python association_table = Table('association', Base.metadata, Column('left_id', Integer, ForeignKey('left.id')), Column('right_id', Integer, ForeignKey('right.id')) ) class Parent(Base): __tablename__ = 'left' id = Column(Integer, primary_key=True) children = relationship("Child", secondary=association_table, backref="parents") class Child(Base): __tablename__ = 'right' id = Column(Integer, primary_key=True) 所述secondary的论点relationship()也接受返回最终的说法,当第一次使用映射器,其仅被评估一个可调用。使用它,我们可以association_table在以后定义,只要在所有模块初始化完成后它可用于callable: class Parent(Base): __tablename__ = 'left' id = Column(Integer, primary_key=True) children = relationship("Child", secondary=lambda: association_table, backref="parents") 使用声明性扩展时,也接受传统的“表的字符串名称”,匹配存储在Base.metadata.tables以下表中的表的名称: class Parent(Base): __tablename__ = 'left' id = Column(Integer, primary_key=True) children = relationship("Child", secondary="association", backref="parents") 删除多个表中的行 这是唯一的一个行为secondary参数relationship() 是,Table它在这里指定为自动受INSERT和DELETE语句,如对象添加或从集合中删除。有没有必要从该表中手动删除。从集合中删除记录的行为将具有在flush上删除行的效果: ```python # row will be deleted from the "secondary" table # automatically myparent.children.remove(somechild) 经常出现的一个问题是当子对象直接递送到“辅助”表中的行时如何删除Session.delete(): session.delete(somechild) ``` 这里有几种可能性: 如果存在relationship()from Parentto Child,但 没有将特定链接Child到每个的反向关系Parent,则SQLAlchemy将不会意识到在删除此特定 Child对象时,它需要维护将其链接到的“辅助”表Parent。不会删除“辅助”表。 如果存在将特定链接Child到每个特定的关系Parent,假设它被调用Child.parents,默认情况下SQLAlchemy将加载到Child.parents集合中以查找所有Parent对象,并从建立此链接的“辅助”表中删除每一行。请注意,此关系不需要是bidrectional; SQLAlchemy严格查看relationship()与Child被删除对象相关的每个内容。 这里性能更高的选项是使用ON DELETE CASCADE指令和数据库使用的外键。假设数据库支持此功能,则可以使数据库本身自动删除“辅助”表中的行,因为删除了“child”中的引用行。Child.parents 在这种情况下,可以指示SQLAlchemy 使用passive_deletes 指令on 来放弃在集合中的主动加载relationship(); 有关详细信息,请参阅使用被动删除。 请再次注意,这些行为仅与使用的secondary选项相关relationship()。如果处理显式映射且不存在于secondary相关选项中的关联表,则relationship()可以使用级联规则来自动删除实体以响应被删除的相关实体 - 有关此功能的信息,请参阅级联。 >关联对象 关联对象模式是多对多的变体:当关联表包含除左表和右表外键之外的其他列时,它会被使用。secondary您可以将新类直接映射到关联表,而不是使用参数。关系的左侧通过一对多引用关联对象,关联类通过多对一引用右侧。下面我们说明映射到的关联表Association,其包括称为柱类extra_data,它是与之间每个关联一起存储的字符串值Parent和 Child: ```python class Association(Base): __tablename__ = 'association' left_id = Column(Integer, ForeignKey('left.id'), primary_key=True) right_id = Column(Integer, ForeignKey('right.id'), primary_key=True) extra_data = Column(String(50)) child = relationship("Child") class Parent(Base): __tablename__ = 'left' id = Column(Integer, primary_key=True) children = relationship("Association") class Child(Base): __tablename__ = 'right' id = Column(Integer, primary_key=True) ``` 与往常一样,双向版本使用relationship.back_populates 或relationship.backref: ``` class Association(Base): __tablename__ = 'association' left_id = Column(Integer, ForeignKey('left.id'), primary_key=True) right_id = Column(Integer, ForeignKey('right.id'), primary_key=True) extra_data = Column(String(50)) child = relationship("Child", back_populates="parents") parent = relationship("Parent", back_populates="children") class Parent(Base): __tablename__ = 'left' id = Column(Integer, primary_key=True) children = relationship("Association", back_populates="parent") class Child(Base): __tablename__ = 'right' id = Column(Integer, primary_key=True) parents = relationship("Association", back_populates="child") ``` 以直接形式使用关联模式要求子对象在被附加到父对象之前与关联实例相关联; 类似地,从父级到子级的访问通过关联对象: ```python # create parent, append a child via association p = Parent() a = Association(extra_data="some data") a.child = Child() p.children.append(a) # iterate through child objects via association, including association # attributes for assoc in p.children: print(assoc.extra_data) print(assoc.child) ```<file_sep># from . import commons<file_sep># 1.1 了解Flask: ***Web应用程序的本质:*** Web(World Wide Web)诞生最初的目的,是为了利用互联网交流工作文档。 ![HTTP请求过程](/images/http_request.png) - 一切从客户端发起请求开始。 - 所有Flask程序都必须创建一个程序实例。 - 当客户端想要获取资源时,一般会通过浏览器发起HTTP请求。 - 此时,Web服务器使用一种名为WEB服务器网关接口的WSGI(Web Server Gateway Interface)协议,把来自客户端的请求都交给Flask程序实例。 - Flask使用Werkzeug来做路由分发(URL请求和视图函数之间的对应关系)。根据每个URL请求,找到具体的视图函数。 - 在Flask程序中,路由一般是通过程序实例的装饰器实现。通过调用视图函数,获取到数据后,把数据传入HTML模板文件中,模板引擎负责渲染HTTP响应数据,然后由Flask返回响应数据给浏览器,最后浏览器显示返回的结果。 ### 为什么要用Web框架? web网站发展至今,特别是服务器端,涉及到的知识、内容,非常广泛。这对程序员的要求会越来越高。如果采用成熟,稳健的框架,那么一些基础的工作,比如,安全性,数据流控制等都可以让框架来处理,那么程序开发人员可以把精力放在具体的业务逻辑上面 1. 稳定性和可扩展性强 - ,可以降低开发难度,提高开发效率。 总结一句话:{% em color="#fff700" %}避免重复造轮子。{% endem %} ### Flask框架的诞生: Flask诞生于2010年,是Armin ronacher(人名)用Python语言基于Werkzeug工具箱编写的轻量级Web开发框架。它主要面向需求简单的小应用。 Flask本身相当于一个内核,其他几乎所有的功能都要用到扩展(邮件扩展Flask-Mail,用户认证Flask-Login),都需要用第三方的扩展来实现。比如可以用Flask-extension加入ORM、窗体验证工具,文件上传、身份验证等。Flask没有默认使用的数据库,你可以选择MySQL,也可以用NoSQL。其 WSGI 工具箱采用 Werkzeug(路由模块) ,模板引擎则使用 Jinja2 。 可以说Flask框架的核心就是Werkzeug和Jinja2。 Python最出名的框架要数Django,此外还有Flask、Tornado等框架。虽然Flask不是最出名的框架,但是Flask应该算是最灵活的框架之一,这也是Flask受到广大开发者喜爱的原因。 **Flask扩展包:** + Flask-SQLalchemy:操作数据库; + Flask-migrate:管理迁移数据库; + Flask-Mail:邮件; + Flask-WTF:表单; + Flask-Bable:提供国际化和本地化支持,翻译; + Flask-script:插入脚本; + Flask-Login:认证用户状态; + Flask-OpenID:认证; + Flask-RESTful:开发REST API的工具; + Flask-Bootstrap:集成前端Twitter Bootstrap框架; + Flask-Moment:本地化日期和时间; 1. 中文文档([http://docs.jinkan.org/docs/flask/](http://docs.jinkan.org/docs/flask/)) 2. 英文文档([http://flask.pocoo.org/docs/0.11/](http://flask.pocoo.org/docs/0.11/)) # 1.2 Flask和django对比 ### 框架之间的差别 Django的一站式解决的思路能让开发者不用在开发之前就在选择应用的基础设施上花费大量时间。Django有模板,表单,路由,认证,基本的数据库管理等等内建功能。与之相反,flask包含路由和验证,但是模板和数据库管理需要第三方库。 用Flask来构建应用之前,选择组件的时候会给开发者带来更多的灵活性 ,可能有的应用场景不适合使用一个标准的ORM,或者需要与不同的工作流和模板系统交互。 Flask创始于2010年年中。Django发布于2006年,是非常成熟的框架,积累了大量的插件和扩展来满足不同需要。 尽管Flask的历史较短,但它能够从以前的框架学到一些东西并且将它的目标设定在了小型项目上。它在一些仅有一两个功能的小型项目上得到了大量应用。比如httpbin这样的项目,简单但非常强大,是一个帮助debug和测试HTTP的库。 ### 社区 Django的社区是最活跃的,在StackOverflow上有80000个相关问题和大量的博客和强大的用户。Flask的社区就没有这么大了,但是它们的社区在邮件列表和IRC里还是挺活跃的。在StackOverflow上只有5000个相关问题,Flask比Django的关注度小15倍。在Github上,它们的stars数相近。 ### 入门引导 Flask的Hello World应用的代码是最简单的,只用在一个Python文件里码7行代码就够了。 from flask import Flask app = Flask(__name__) @app.route("/") def hello(): return "Hello World!" if __name__ == "__main__": app.run() 这就是为什么Flask没有引导工具:因为它根本不需要。从上面的Hello World应用的特点来看,一个没什么Python web开发经验的人就可以很快的上手开始撸代码。 对于需要把组件分离开的项目,Flask有blueprints。例如,你可以这样构建你的应用,将与用户有关的功能放在user.py里,把与销售相关的功能放在ecommerce.py里。 Django拥有自己的引导工具,它是django-admin的一部分 django-admin startproject hello_django django-admin startapp hello 我们已经可以看到Django和flask的一些区别。Django把一个项目分成各自独立的应用,而Flask认为一个项目应该是一个包含一些视图和模型的单个应用。也可以在Flask里复制出像Django那样的项目结构,但那不是默认的。 ![django框架结构](/images/project_structure.png) 默认情况下,Django只包含空的模型和模板文件,一个新的用户可以看一点例子代码就开始工作。它也能让开发者选择如何分配Django的应用。 ###模版 Django的模版大家都很熟悉,我们举一个简单的例子 ```python <!-- view.html --> <div class="top-bar row"> <div class="col-md-10"> <!-- more top bar things go here --> </div> {% if user %} <div class="col-md-2 whoami"> You are logged in as {{ user.fullname }} </div> {% endif %} </div> {% for widget in inventory %} <li>{{ widget.displayname }}</li> {% endfor %} ``` 对于大多数普通的模板任务来说,Django能够轻松实现,非常容易上手。 Flask默认使用一个受Django启发而发展起来的名为Jinja2的模板,但也可以通过配置来使用其他的语言。一个码农可能会将Django和Jinja模板弄混。事实上,所有上面的Django模板的例子在Jinja2里也是好使的。我们就不重复上面的例子了,我们来看看Jinja2比Django模板的一些更有表现力的特点。 ```python <!-- Django --> <div class="categories">Categories: {{ post.categories|join:", " }}</div> ​```python <!-- Jinja --> <div class="categories">Categories: {{ post.categories|join(", ") }}</div> ``` 在Jinja的模板语言里,可以把任何数量的参数传给过滤器,因为Jinja像调用一个Python函数的方式来看待它,用圆括号来封装参数。Django使用冒号来分隔过滤器名和参数,这样就只能传递一个参数了。 Jinja和Django的 for 循环很相似。我们来看看它们的区别。在Jinja2, for-else-endfor 结构让你能对一个列表进行迭代,也能处理列表为空的情况。 ```python {% for item in inventory %} <div class="display-item">{{ item.render() }}</div> {% else %} <div class="display-warn"> <h3>No items found</h3> <p>Try another search, maybe?</p> </div> {% endfor %} ``` 在Django版本的功能是一样的,只是使用了 for-empty-endfor 这样的结构替换了 for-else-endfor 的结构。 ```python {% for item in inventory %} <div class="display-item">{{ item.render }}</div> {% empty %} <div class="display-warn"> <h3>No items found</h3> <p>Try another search, maybe?</p> </div> {% endfor %} ``` 除了上述的语法区别,flask还提供了很多特有的上下文变量 ```python (url_for,get_flashed_messages()等) ``` #安装环境 使用虚拟环境安装Flask,可以避免包的混乱和版本的冲突,虚拟环境是Python解释器的副本,在虚拟环境中你可以安装扩展包,为每个程序单独创建的虚拟环境,可以保证程序只能访问虚拟环境中的包。而不会影响系统中安装的全局Python解释器,从而保证全局解释器的整洁。 虚拟环境使用virtualenv创建,可以查看系统是否安装了virtualenv: ```bash $ virtualenv --version ``` **安装虚拟环境** ```bash $ sudo pip install virtualenv $ sudo pip install virtualenvwrapper ``` **创建虚拟环境(须在联网状态下)** ```bash $ mkvirtualenv Flask_py ``` **进入虚拟环境** ```bash $ workon Flask_py ``` ** 退出虚拟环境** 如果所在环境为真实环境,会提示deactivate:未找到命令 ```bash $ deactivate Flask_py ``` # 1.2.1 安装Flask ```bash 指定Flask版本安装 $ pip install flask==0.10.1 pip freeze > requirements.txt ``` Mac系统: ```bash $ easy_install flask==0.10.1 ``` **在ipython中测试安装是否成功** ```bash $ from flask import Flask ``` ![安装成功1](/images/install_success1.png) ![安装成功2](/images/install_success2.png) # 1.3 从 Hello World 开始 ###Flask程序运行过程: 所有Flask程序必须有一个程序实例。 Flask调用视图函数后,会将视图函数的返回值作为响应的内容,返回给客户端。一般情况下,响应内容主要是字符串和状态码。 当客户端想要获取资源时,一般会通过浏览器发起HTTP请求。此时,Web服务器使用WSGI(Web Server Gateway Interface)协议,把来自客户端的所有请求都交给Flask程序实例,程序实例使用Werkzeug来做路由分发(URL请求和视图函数之间的对应关系)。根据每个URL请求,找到具体的视图函数。 在Flask程序中,路由的实现一般是通过程序实例的装饰器实现。通过调用视图函数,获取到数据后,把数据传入HTML模板文件中,模板引擎负责渲染HTTP响应数据,然后由Flask返回响应数据给浏览器,最后浏览器处理返回的结果显示给客户端。 ## 示例: 新建文件hello.py: 导入Flask类 ``` from flask import Flask ``` Flask函数接收一个参数__name__,它会指向程序所在的模块 ``` app = Flask(__name__) ``` 装饰器的作用是将路由映射到视图函数index @app.route('/') def index(): return 'Hello World' Flask应用程序实例的run方法启动WEB服务器 if __name__ == '__main__': app.run() ![装饰器路由](/images/app_route.png) ### 给路由传参示例: 有时我们需要将同一类URL映射到同一个视图函数处理,比如:使用同一个视图函数 来显示不同用户的个人信息。 路由传递的参数默认当做string处理,这里指定int,尖括号中的内容是动态的 @app.route('/user/<int:id>') def hello_itcast(id): return 'hello itcast %d' %id ![给路由传参](/images/dynamic_route.png) ### 返回状态码示例: python @app.route('/') def hello_itcast(): return 'hello itcast',404 ![404](/images/404.png) ### 重定向redirect示例 from flask import redirect @app.route('/') def hello_itcast(): return redirect('http://www.itcast.cn') ![302](/images/302.png) ### 正则URL示例: from flask import Flask,render_template,request from werkzeug.routing import BaseConverter class Regex_url(BaseConverter): def __init__(self,url_map,*args): super(Regex_url,self).__init__(url_map) self.regex = args[0] app = Flask(__name__) app.url_map.converters['re'] = Regex_url @app.route('/user/<re("[a-z]{3}"):id>') def hello_itcast(id): return 'hello %s' %id ###返回json python from flask import Flask,json @app.route('/json') def do_json(): hello = {"name":"stranger", "say":"hello"} return json.dumps(hello) # 1.5 上下文和扩展 ### 请求上下文(request context) Flask从客户端收到请求时,要让视图函数能访问一些对象,这样才能处理请求,请求对象是一个很好的例子,它封装了客户端发送的HTTP请求. 要想让视图函数能够访问请求对象,一个显而易见的方式是将其作为参数传入视图函数,不过这会导致程序中的每个视图函数都增加一个参数,除了访问请求对象,如果视图函数在处理请求时还要访问其他对象,情况会变得更糟.为了避免大量可有可无的参数把视图函数弄得一团糟,Flask使用上下文临时把某些对象变为全局可访问 + request和response都属于请求上下文对象。 - 当调用app = Flask(__name__)的时候,创建了程序应用对象app; - request 在每次http请求发生时,WSGI server调Flask.call();然后在Flask内部创建的request对象; - app的生命周期大于request,一个app存活期间,可能发生多次http请求,所以就会有多个request。 - 最终传入视图函数,通过return、redirect或render_template生成response对象,返回给客户端。 ###设置cookie python from flask imoprt Flask,make_response @app.route('/cookie') def set_cookie(): resp = make_response('this is to set cookie') resp.set_cookie('username', 'itcast') return resp ![设置cookie](/images/cookie.png) session数据的获取 session:请求上下文,用于处理http请求中的一些数据内容 python from flask import Flask, session, redirect, url_for, escape, request @app.route('/index1') def index1(): session['username'] = 'itcast' return redirect(url_for('index')) @app.route('/') def index(): return session.get('username') ###应用上下文current_app,g current_app:应用程序上下文,用于存储应用程序中的变量,可以通过current_app.name打印当前app的名称,也可以在current_app中存储一些变量 应用的启动脚本是哪个文件,启动时指定了哪些参数 加载了哪些配置文件,导入了哪些配置 连了哪个数据库 有哪些public的工具类、常量 应用跑再哪个机器上,IP多少,内存多大 current_app.name current_app.test_value='value' g作为flask程序全局的一个临时变量,充当者中间媒介的作用,我们可以通过它传递一些数据 g.name='abc' ## Flask-Script 通过使用Flask-Script扩展,我们可以在Flask服务器启动的时候,通过命令行的方式传入参数。 我们可以通过python hello.py runserver --help来查看参数。 我们还可以通过python hello.py shell进入shell,在命令行中调试代码 ![命令行](/images/terminator.png) python from flask import Flask from flask_script import Manager app = Flask(__name__) manager = Manager(app) @app.route('/') def index(): return '床前明月光' if __name__ == "__main__": manager.run() <file_sep># celery模型说明 1. 发送短信,可能会发生堵塞 2. 安装`pip install -U celery 3. 任务队列 1. rabbitMQ 2. MessageQueue 3. redis 4. celery结构 1. 客户端(发布任务的一方,例如是django,flask) 2. 任务处理者(worker,多进程,协程,gevent,greenlet)-具备多任务处理 3. 任务队列(broker) 4. 还可以有一个第四方,专门用来存放数据(backend) 5. # 客户端定义的时候需要写的代码 ```python app = celery() #定义任务 @app.task def send_sms(): ..... #然后发布任务 send_sms.delay() ``` 1. 然后任务处理者,需要有完整的,和客户端一样的代码 2. ## 所以,客户端的具体需要实现的函数,里面可以是pass,但是任务处理者里面一定是功能完整的代码 6. 开启celery worker 1. 执行代码`celery -A 定义任务的python模块 worker -l info` 7. # 还是关于客户端的这边,需要改装一下,把真正想做异步处理的具体函数,比如是这个短信,下面这段代码是改造前的 ```python # 发送短信 try: ccp = CCP() result = ccp.send_template_sms(mobile, [sms_code, int(constants.SMS_CODE_REDIS_EXPIRES/60)], 1) except Exception as e: current_app.logger.error(e) return jsonify(errno=RET.THIRDERR, errmsg="发送异常") ``` 改造后 ```python #引用到celery导入进来的send_sms.delay() send_sms.delay() ``` 8. ## 然后celery这端的任务者,继承上面的发送任务 ```python @celery_app.tasks def send_sms(to, datas, temp_id): ccp = CCP() cpp.send_template_sms(to, datas, temp_id) ``` 9. ## 关于返回值 1. ## 不存在,直接告诉用于已经成功了.如果用户收不到短信的话,就直接甩锅吧! 10. ## celery的目录结构使用 1. 如果异步任务比较多,就用目录的方式去管理 2. 定义启动文件(main.py) 3. 然后新建一个sms目录,专门用于管理发送短信的 1. 关于配置文件,可以让参数单独写成一个配置文件. 4. ### 然后可以引入配置信息 ```python from celery import Celery from ihome.tasks import config celery_app = Celery("ihome") #引入配置信息 #这个地方,可以引入对象作为配置信息,也可以导入模块,当作配置信息 cerery_app.config_from_object(config) ``` 5. 然后在main文件,添加celery_app.autodiscover_tasks(["ihome.tasks.sms"]) 11. 就是,在web中,多使用异步的这种东东.! 12. ## celery独立的目录使用 1. 假如需要独立的话,仅仅只是依赖云通讯的那几个模块!. 13. ## celery接收返回值 1. ## 不仅可以用目录的方式定义celery,还可以用工程的方式去定义 2. 可以将main.py改名为celery.py,cerlery就会自动找到这个主文件了. 3. 如果有返回值,直接返回 ```python result = ccp.send_template_sms(mobile, [sms_code, int(constants.SMS_CODE_REDIS_EXPIRES/60)], 1) ``` 4. ### 通过get方法获取cerlery异步执行的结果 ```python #get方法默认是阻塞的行为,会等到有了执行结果之后才返回 #get方法也接受参数timeout,超时时间,超过超时时间还拿不到结果,就返回 ret = result.get() ``` 14. ## 结束<file_sep>#配置数据库 import redis from urllib import parse class DbConfig: '''配置参数''' SECRET_KEY = "<KEY>" SQLALCHEMY_DATABASE_URI = "mysql://root:%s@localhost:3306/ihome"%parse.unquote_plus("<EMAIL>") SQLALCHEMY_TRACK_MODIFICATIONS = True ##配置redis链接信息 REDIS_HOST = '127.0.0.1' REDIS_PORT = 6379 #flask-session配置 SESSION_TYPE = 'redis' SESSION_REDIS = redis.StrictRedis(host=REDIS_HOST,port=REDIS_PORT) SESSION_USE_SIGNER = True #对cookie中的session_id进行隐藏.! PERMANENT_SESSION_LIFETIME = 86400 #session数据的有效期,单位秒 class DevelopmentConfig(DbConfig): '''开发环境''' DEBUG = True class ProductionConfig(DbConfig): '''生产环境''' pass config_map = { 'develop': DevelopmentConfig, 'product': ProductionConfig, }<file_sep># 在单一文件中构建所有依赖工具 1. flask并没有官方组织方法.目录排列结构.! 2. 举例: ```python from flask import Flask app = Flask(__name__) @app.route("/index") def index(): return "index page" if __name__ == '__main__': app.run() ``` 3. 添加配置信息 ```python from flask_sqlalchemy import SQLAlchemy class Config(object): '''配置信息''' DEBUG = True SECRET_KEY = "as&^*^&%(*&)(*hhuoioih)" #数据库 SQLALCHEMY_DATABASE_URI = "mysql://root:kumanxuan123:3306:ihome" SQLALCHEMY_TRACK_MODIFICATIONS = True app.config.from_object(Config) db = SQLAlchemy(app) ``` 4. 添加缓存 ```python REDIS_HOST = '127.0.0.1' REDIS_PORT = 6379 import redis #创建redis连接对象 redis_store = redis.StrictRedis(host=localhost,port=6379,) ``` 5. ## sqlalchemy实质是独立的python操作数据库的python库. 1. 然而在flask中,为了方便使用,被封装成为flask_sqlalchemy. 2. ### 数据库添加密码转义,python使用urllib.parse里面的unquote_plus 6. 为flask添加redis 7. 添加csrf防护 1. 实质里面,用的就是装饰器. 8. 配置session,使用redis作为缓存保存数据.! # 创建工程目录1 1. 把刚刚的DbConfig复制出来.放到新的文件 1. 然后,上面那个作为父类,如果你需要修改什么信息的话,可以通过创建一个子类去覆盖参数.! 2. flask建议使用工厂模式. 1. 什么是工厂模式. 1. Python设计模式——工厂方法模式(FactoryMethod) https://www.cnblogs.com/Xjng/p/3879064.html 2. 摘抄 1. 首先我自己不是生成一个app对象吗? 1. 如果想按<开发模式>就按这模式生成,想要<生产模式>就按这模式生成.! 3. 里面的文件夹组织很讲究的样子,前面的高度工厂化,然后后面的高度封装起来了!. 4. 关于数据库一些初始化代码放到具体那些位置会比较好一点! 1. 整个flask项目会用到数据库和redis 2. 你可能在models函数用到了db,也有可能在views用到了db 3. 所以都是公共的工具,所以把db放到init文件中来.! 4. ## 但是数据库有一个问题,创建的时候,不能第一时间绑定app,所以只能推迟去绑定.! 5. ## 问题又来了,就是,redis究竟是放在create_app后面还是前面? 1. 如果是公共的话,必须是放到外面.! 2. ### 但是还有一个问题,就是,你的redis究竟是用那一个配置文件还是没有定下来的时候, 还是,可以先创建,但是一开始为空的.!?????我大概明白了,就是先定义一个空的全局变量吧.! 果然,里面也是这么说的.但是,为什么db并没有这样的操作.可能是因为需要绑定app参数的原因.! 5. 现在关于如何把剩下的这个视图函数也封装,一下 1. 课件里面讲的是,在外面设置两个或者多个入口,然后,用于区分入口,例如是新版1.0,旧版2.0这样! 2. 现在在ihome下面新建包,当作是蓝图使用,然后起名字会比较讲究一下.! 6. 会讲到RETFUL. 1. 如何去定义路径.! 7. ## 现在,如果牵涉到数据库的话,还有迁移的问题,最好还是用相应的迁移方法.!迁移插件.! 1. Flask Script扩展提供向Flask插入外部脚本的功能,包括运行一个开发用的服务器,一个定制的Python shell,设置数据库的脚本,cronjobs,及其他运行在web应用之外的命令行任务;使得脚本和系统分开; 8. ## 如何避免循环导包 1. 尝试在api_1_0里面的demo文件,添加导入from ihome import db, 这样就可以引起循环导包了.为什么??看下来讲解. 1. 因为在demo.py文件和ihome的init文件永远在互相导入而没有去执行db这个. 2. ### 推迟导入 解决办法就是,什么时候用就什么时候导入! 9. # 一般来说,会有两个文件夹. 1. utils 这个文件夹代表是工具类 2. libs 引用第三方工具包的存放位置 10. # 日志功能 1. import logging 1. 4种等级 2. logging.error("String you like want to write") 是一个函数. 3. logging.wran() 4. logging.info() 5. logging.debug() 2. 设置方法 1. logging.basecConfig(level=logging.DEBUG) ............... 3. ## 日志级别的说明 1. 原来,debug级别是包括了info,wran,和error级别. 2. 然后info包括以前三个.以此类推.! 4. ## 手动设置日志信息 1. from flask import current_app 2. current_app.logger.error("error message") 5. ## 注意了,原来如果配置文件当前选择的是DEBUG模式的话,你前面设置的等级全部都是DEBUG,意思是全部信息都输出.! 11. <file_sep># 表与表之间的关系 ```python class Parent(Base): __tablename__ = 'parent' id = Column(Integer, primary_key=True) children = relationship("Child") class Child(Base): __tablename__ = 'child' id = Column(Integer, primary_key=True) parent_id = Column(Integer, ForeignKey('parent.id')) ``` 1. ## 上面两个表存在一定的关系 1. 与django有一定区别的 2. ### flask跟底层是靠近的. 3. ### `parent_id`是真实存在在`Child`中的,所以得写数据类型的,在`django`那边是不用定义的. 4. ### 但是仅仅用上面的步骤,是没有产生关联的,`ForeignKey('parent.id')` 1. #### 注意了,ForeignKey后面的是表名+字段,注意了,是数据表 5. relationship并不在数据库中的,所以这仅仅是描述关系,方便查询的. 1. 当你操作`Parent`里面的children是关联那个对象呢,后面你就可以自己填写了,注意了,模型类考虑的. 6. 以上的操作,已经可以让Parent查询到他下面都有那些Child信息了. 2. ## 但是,加入Child需要展示信息,上面的id可以方便展示,但是`parent_id`只是一个普通的Integer属性,只能显示数字 1. 所以,得在上面的`Parent`,里面的children的relationship,添加其他属性,添加`backref="parent"` 3. 除了使用模型类的名字去查询数据库数据query,还有一种语法就是,写db.session.query(Role).all(),其中db意思是指db = SQLAlchemy(app)这个db. 4. ## filter是万能查询。 1. ### 注意了,`filter(User.name=="xx").first()`,字段必须是这种,直接引用模型类的。然后`==`代表的是,一个普通的`=` 2. 多条记录`filter(User.name=="xx",User.id=='yy').all()` 2. ### 还可以引入 或者 `from sqlalchemy import or_ 1. 例子`User.query.filter(or_(User.name=='wang',User.email.endswith("163.com"))` 3. ### offset ,意思是从第几条开始取数据,limit是限制 1. example:`User.query.filter(User.name=="xx").offset(2).all()`,意思是跳过前两条。 4. ### 注意了,limit是限制,但是后面必须取数据,意思是,`User.query.filter(User.name=="xx").offset(2).limit(2).all()`这种形式 5. 排序 order_by(),但是不是很通用 1. example: `User.query.order_by("-id").all()` 2. 这个才是推荐使用的方法,`User.query.order_by(User.id.desc()).all()` 6. group_by分组 1. `select name,id,count(id) from xxx group_by id` 2. 导入`from sqlalchemy import func` 1. 示例`db.session.query(User.role_id,funct.count(user.role_id)).group_by(user.role_id).all()` 7. <file_sep># 这里是视图吗? from . import api from ihome import db, models @api.route("/index") def index(): return "index page" <file_sep># 前端 1. #### 由于前后端分离,所以,用户页面展示的认真就是靠前端不断去后台询问用户是否登陆了. 2. #### jq去拦截表单的时候,首先必须是阻止表单提交,e.preventDeafault,然后就是各种操作了.,ajax,post,get等操作. 3. #### <file_sep>## 定义蓝图 from flask import Blueprint #创建蓝图对象 api = Blueprint("api_1_0",__name__) #导入蓝图的视图 from . import demo,verify_code,passport,profile,houses,orders,pay <file_sep># 房屋管理 1. ## 查询当前数据库的house信息 1. 通过`houses = House.query.filter_by(id=user_id)` 2. ### 通过查询user信息,`user = User.query.get(user_id)` 1. 因为user有一个字段house是一对多的关系,所以也可以通过user查询到他对应的房子信息 2. 然后就可以获取得到房源信息了`houses = user.houses` 3. 然后在House模型类里面,专门设置了一个将对象转换成为字典的方法,将基本信息转换为字典数据 ```python def to_basic_dict(self): """将基本信息转换为字典数据""" house_dict = { "house_id": self.id, "title": self.title, "price": self.price, "area_name": self.area.name, "img_url": constants.QINIU_URL_DOMAIN + self.index_image_url if self.index_image_url else "", "room_count": self.room_count, "order_count": self.order_count, "address": self.address, "user_avatar": constants.QINIU_URL_DOMAIN + self.user.avatar_url if self.user.avatar_url else "", "ctime": self.create_time.strftime("%Y-%m-%d") } return house_dict ``` 2. ## 主页就不用添加装饰器了 1. 查询热门的数据就可以了.! 2. 相关的属性,可以看一下config 3. ### 有一个细节 1. 如果这个房源信息,没有设置主页的图片 1. 然后就直接用continue跳过 4. 引入缓存. 1. 一旦查询出结果,存到redis当中 2. 也可以存json格式的数据! 5. ### 向前端返回 涉及效率问题 1. 问题1,现在可以直接向前端返回数组,但是jsonify里面是转换python的对象,例如是列表,字典之类的. 2. 然后,尽量不要转换之后继续用jsonify再转换,因为这些转换都是很耗时.例如是,`return jsonify(errr=xxx,data=json_data)`, 如果json_data已经是转换好的json数据的话,这一步的转换就有点浪费力气了. 3. 解决 1. `'{"error":"0","errmsg":"OK","data":$s}'%s 4. #### 然后记得,补充状态码(200),和返回数据的类型(Content-Type:"application/json"))) 6. 数据到底是用缓存还是不不用? 1. 注意好,使用try except,如果查询不到数据的话,出现异常,如果不使用else的话,就需要在出现异常后面紧接设置ret为空.! 7. ### 房屋的详细信息数据 1. 如果判断,让如果当前用户是房东自己,然后不能让房东自己提交订房按钮. 2. 判断userid和houseid是否为同一个. 1. 自行决定要不要返回显示数据 3. 封装返回数据的方法 1. 因为涉及的数据太多了.! 4. 关于backref,也就是反向引用.这是一个relationship 5. 补充backref,db.relationship() 中的 backref 参数向 User 模型中添加一个 role 属性,从而定义反向关 系。这一属性可替代 role_id 访问 Role 模型,此时获取的是模型对象,而不是外键的值。 1. 图 5-1 中的一对多关系在模型类中的表示方法如示例 5-3 所示。 ```python 示例 5-3 hello.py:关系 class Role(db.Model): # ... users = db.relationship('User', backref='role') class User(db.Model): # ... role_id = db.Column(db.Integer, db.ForeignKey('roles.id')) 如图 5-1 所示,关系使用 users 表中的外键连接了两行。添加到 User 模型中的 role_id 列 被定义为外键,就是这个外键建立起了关系。传给 db.ForeignKey() 的参数 'roles.id' 表 明,这列的值是 roles 表中行的 id 值 ``` 2. #### 部分名词 |英文|中文| |----|--------------| |backref |在关系的另一个模型中添加反向引用| |primaryjoin |明确指定两个模型之间使用的联结条件。只在模棱两可的关系中需要指定| |lazy |指定如何加载相关记录。可选值有 select (首次访问时按需加载)、 immediate (源对象加载后就加载)、 joined (加载记录,但使用联结)、 subquery (立即加载,但使用子查询),noload (永不加载)和 dynamic (不加载记录,但提供加载记录的查询)数据库 49(续)| |uselist |如果设为 Fales ,不使用列表,而使用标量值 |order_by |指定关系中记录的排序方式 |secondary |指定 多对多 关系中关系表的名字 |secondaryjoin |SQLAlchemy 无法自行决定时,指定多对多关系中的二级联结条件| 3. ## 稍稍补充一下,Flask系列:数据库,一对多,多对多,关系,简书 1. https://www.jianshu.com/p/0c88017f9b46 2. 部分摘抄资料 >User(用户表) ```python >>> from sqlalchemy import Column, Integer, String >>> class User(Base): ... __tablename__ = 'users' ... ... id = Column(Integer, primary_key=True) ... name = Column(String) ... fullname = Column(String) ... password = Column(String) ... ... def __repr__(self): ... return "<User(name='%s', fullname='%s', password='%s')>" % ( self.name, self.fullname, self.password) ``` > ```python >>> from sqlalchemy import ForeignKey >>> from sqlalchemy.orm import relationship, backref >>> class Address(Base): ... __tablename__ = 'addresses' ... id = Column(Integer, primary_key=True) ... email_address = Column(String, nullable=False) ... user_id = Column(Integer, ForeignKey('users.id')) ... ... user = relationship("User", backref=backref('addresses', order_by=id)) ... ... def __repr__(self): ... return "<Address(email_address='%s')>" % self.email_address ``` #### 解释 ```python 上述类使用了ForeignKey函数,它是一个应用于Column的指令,表明这一列的值应该保存指定名称的远程列的值。 这是关系数据库的一个核心特征,是“胶水”,将原本无关的表变为有丰富的重叠关系的集合。上面的ForeignKey表示, Addresses.user_id列的值应该等于users.id列中的值,即,users的主键。 第二个函数,称为relationship(), 它告诉 ORM ,Address类本身应该使用属性Address.user链接到User类。 relationship()使用两个表之间的外键关系来确定这个链接的性质,这个例子中,确定Address.user将要成为 多对一中多的一侧。relationship()的参数中有一个称为backref()的relationship()的子函数, 反向提供详细的信息, 即在users中添加User对应的Address对象的集合,保存在User.addresses中。 多对一关系的反向始终是一对多的关系。一个完整的可用的relationship()配置目录在基本关系模式。 两个互补关系, Address.user和User.addresses被称为一个双向关系, 并且这是SQLAlchemy ORM的一个关键特性。 小节Linking Relationships with Backref详细讨论了“Backref”特性。 relationship()的参数中,关联的远程类可以通过字符串指定,如果声明系统在使用。 在上面的例子的User类中,一旦所有映射完成,这些字符串被认为是用于产生实际参数的 Python 表达式。 允许的名字在这个评估包括,除其他方面外,所有类的名称已被创建的声明的基础。 ``` # SQLAlchemy ORM教程之三:Relationship https://www.jianshu.com/p/9771b0a3e589 # Basic Relationship Patterns http://docs.sqlalchemy.org/en/rel_1_0/orm/basic_relationships.html#relationship-patterns # 房屋管理前端 1. ## 对用户进行判断 1. 如果用户还没有实名认证的话,就只显示请实名认证 2. 然后隐藏/不展示发布房源的按钮 2. 问题如何判断有没有做过实名认证 1. ## 跟前面的js获取用户状态一样,js发起ajax去认证 2. 然后根据后台返回的数据,去选择要显示那些样式显示. 3. ## 然后就是首页了 1. 然后根据返回的信息,如果没有出现错误的话,就把这些信息添加到信息 4. ## 然后添加js的新插件扩展,swiper.jquery,开源插件 1. 这个可以将数据转换为轮播图 2. 然后就是熟悉swiper的参数 1. loop:代表轮播完之后继续轮播 2. .... 3. 注意swiper的位置,不然不能及时获取数据展示 5. ## 然后渲染城区信息 6. ## 详情页面 1. 如何去打开详细页 1. 前端如何组织url的参数 2. 然后是如何发送请求到前台 3. 然后再次接收 2. ### 用`document.location.search`,然后这样就可以获取url后面的参数,例如是id=4&d=6之类的. 3. 进行两次分开渲染操作 7. 关于redis的问题,就是,经常显示数据都是带有b开头的.....现在其他东西判断的时候就一脸懵逼了.!<file_sep># 1.4 单元测试 ###什么是单元测试 测试一段程序很简单,要做的事情无非是运行程序中指定的部分,并声明你期待的结果,把这个结果跟程序实际返回的结果相比较,如果一致,则测试通过,如果不一致,则测试失败,一般来说,在把代码提交到Git仓库或者部署到线上服务器之前,都需要进行测试,这样就能避免错误的代码污染Git仓库或者线上服务. 对程序的测试有三种主要的类型:单元测试会对单独的代码块(例如函数)分别进行测试,以保证它们的正确性;集成测试会对大量的程序单元的协同工作情况做测试;系统测试会同时对整个系统的正确性进行检查,而不是针对独立的片段,我们学习的主要是单元测试,后期项目会进行系统测试 ###怎样进行测试 一个最简单的Python程序: def square(x): return x*x 为了检查这段代码的正确性,可以传一个值给它,并检查它的返回值是不是我们所期待的,比如,我们可以输入5,并期待返回值为25,为了演示这个概念,我们可以在命令行中使用assert语句来手动进行测试,Python里的assert语句的意思很简单,如果assert关键字后面跟的表达式返回了假值,就抛出异常: ``` assert square(5) == 25 ``` ###对应用进行单元测试 把assert语句组合在一起,放在特定类的函数里,就是Python中编写单元测试的方式,这些测试函数组成的类叫做测试用例,测试用例中的每个函数都必须只对一个任务进行测试,这是单元测试背后的主要理念,在单元测试中只测试一个任务,会强制你单独地对每段代码进行检查,而不容易遗漏代码中的任何功能,如果正确地编写单元测试,则你会得到越来越多的测试用例,虽然这看起来优点过度冗繁,但他们会帮你的大忙. 我们在开始编写测试用例之前,还需要专门对测试环境准备一个配置对象,用来构件测试专用的环境,这个配置就是我们在前面提到的TestingConfig对象 ###测试类的基本写法 通常需要定义一个类继承unittest.TestCase import unittest class TestClass(unittest.TestCase): pass ###测试中常用的两个方法 在这个测试用例中的每个测试都会用到测试客户端,但如果在每个测试中都写一端代码去生成测试客户端,则显然是不合理的,Flask提供了一个在每个单元测试运行之前被调用的方法,叫做setUp方法,在setUp方法中,我们需要使用TestConfig来创建应用对象,并生成测试客户端 class TestClass(unittest.TestCase): def setUp(self): self.app = create_app('testing') self.app_context = self.app.app_context() self.app_context.push() self.client = self.app.test_client() 另外还存在一个tearDown方法可以与setUp配合是使用,每个测试执行结束后,都会调用这个方法,可以在tearDown时销毁在setUp里创建的不会被自动垃圾回收干掉的对象 class TestClass(unittest.TestCase): def tearDown(self): db.session.remove() db.drop_all() ###基本测试 ```python class BasicsTestCase(unittest.TestCase): def setUp(self): self.app = create_app('testing') self.app_context = self.app.app_context() self.app_context.push() db.create_all() ``` ```python def tearDown(self): db.session.remove() db.drop_all() self.app_context.pop() def test_app_exists(self): self.assertFalse(current_app is None) def test_app_is_testing(self): self.assertTrue(current_app.config['TESTING']) ``` 上述代码为测试app实例是否创建成功的代码 ###测试User模型 class UserModelTestCase(unittest.TestCase): #... def test_password_setter(self): u = User(password='cat') self.assertTrue(u.password_hash is not None) def test_no_password_getter(self): u = User(password='cat') with self.assertRaises(AttributeError): u.password def test_password_verification(self): u = User(password='cat') self.assertTrue(u.verify_password('cat')) self.assertFalse(u.verify_password('dog')) ###简单的路由函数测试 def test_index(): result=self.client.get('/') self.assertEqual(result.status_code,200) self.assertIn('Demo',result.data) 示例中判断了返回结果的状态码及其返回结果中的内容 ###测试登陆功能 登陆是需要进行表单提交的,故:我们需要使用client来模拟post请求,并在请求中添加表单中需要的参数,但会出现一个csrf_token不存在的问题,我们需要先通过get请求来获取html数据,通过爬虫来获取html中的csrf_token的值 class LoginTestCase(unittest.TestCase): #... def test_login(self): html = self.client.get('/auth/login').data bs = BeautifulSoup(html, 'html5lib') csrf_token = bs.find(id='csrf_token')['value'] print csrf_token # ... 然后通过post请求模拟登陆 def test_login(self): #... result=self.client.post('/auth/login',data={ 'email':'<EMAIL>', 'password':'abc', 'csrf_token':csrf_token },follow_redirects=True) print result.data self.assertIn('你好, abc!',result.data) 安装BeautifulSoup的指令:pip install beautifulsoup4 安装html5lib的指令:apt-get install python-html5lib ###测试注册功能 除参数不同外,和测试登陆的实现过程基本一致 def test_register(self): login_html = self.client.get('/auth/register').data login_bs = BeautifulSoup(login_html, 'html5lib') csrf_token = login_bs.find(id='csrf_token')['value'] result = self.client.post('/auth/register', data={ 'email': '<EMAIL>', 'username': 'aaaa', 'password': '123', 'password2': '123', 'csrf_token':csrf_token},follow_redirects=True) self.assertEqual(result.status_code,200) <file_sep># 1.1 Blueprint ### 模块化 随着flask程序越来越复杂,我们需要对程序进行模块化的处理,之前学习过python的模块化管理,于是针对一个简单的flask程序进行模块化处理 举例来说: 我们有一个博客程序,前台界面需要的路由为:首页,列表,详情等页面 源程序app.py文件: from flask import Flask app=Flask(__name__) @app.route('/') def index(): return 'index' @app.route('/list') def list(): return 'list' @app.route('/detail') def detail(): return 'detail' if __name__=='__main__': app.run() 如果博主需要编辑博客,要进入后台进行处理:后台主页,编辑,创建,发布博客 改进后程序: from flask import Flask app=Flask(__name__) @app.route('/') def index(): return 'index' @app.route('/list') def list(): return 'list' @app.route('/detail') def detail(): return 'detail' @app.route('/') def admin_home(): return 'admin_home' @app.route('/new') def new(): return 'new' @app.route('/edit') def edit(): return 'edit' @app.route('/publish') def publish(): return 'publish' if __name__=='__main__': app.run() 这样就使得我们在一个py文件中写入了很多路由,将来维护代码会非常麻烦,此时,同学们就考虑到了模块化的处理方式,将admin相关的路由写到一个admin.py文件中,那我们就顺着这个思路走下去 修改后的代码: app.py from flask import Flask app=Flask(__name__) @app.route('/') def index(): return 'index' @app.route('/list') def list(): return 'list' @app.route('/detail') def detail(): return 'detail' if __name__=='__main__': app.run() admin.py @app.route('/') def admin_home(): return 'admin_home' @app.route('/new') def new(): return 'new' @app.route('/edit') def edit(): return 'edit' @app.route('/publish') def publish(): return 'publish' 发现app.py文件中的app直接报错,代码无法继续写下去,所以在flask程序中,使用传统的模块化是行不通的,需要flask提供一个特有的模块化处理方式,flask内置了一个模块化处理的类,即Blueprint ###Blueprint概念 简单来说,Blueprint 是一个存储操作方法的容器,这些操作在这个Blueprint 被注册到一个应用之后就可以被调用与招待,Flask 可以通过Blueprint来组织URL以及处理请求。 Flask使用Blueprint让应用实现模块化,在Flask中,Blueprint具有如下属性: - 一个应用可以具有多个Blueprint - 可以将一个Blueprint注册到任何一个未使用的URL下比如 “/”、“/sample”或者子域名 - 在一个应用中,一个模块可以注册多次 - Blueprint可以单独具有自己的模板、静态文件或者其它的通用操作方法,它并不是必须要实现应用的视图和函数的 - 在一个应用初始化时,就应该要注册需要使用的Blueprint 但是一个Blueprint并不是一个完整的应用,它不能独立于应用运行,而必须要注册到某一个应用中。 ###初识蓝图 蓝图/Blueprint对象用起来和一个应用/Flask对象差不多,最大的区别在于一个 蓝图对象没有办法独立运行,必须将它注册到一个应用对象上才能生效 使用蓝图可以分为三个步骤 - 1,创建一个蓝图对象 admin=Blueprint('admin',__name__) - 2,在这个蓝图对象上进行操作,注册路由,指定静态文件夹,注册模版过滤器 @admin.route('/') def admin_home(): return 'admin_home' - 3,在应用对象上注册这个蓝图对象 app.register_blueprint(admin,url\_prefix='/admin') 当这个应用启动后,通过/admin/可以访问到蓝图中定义的视图函数 ###运行机制 蓝图并不是一个可插拔的应用,它只是保存了一组将来可以在应用对象上执行的操作,注册路由就是一种操作,当在应用对象上调用route装饰器注册路由时,这个操作将修改对象的url\_map路由表,然而,蓝图对象根本没有路由表,当我们在蓝图对象上调用route装饰器注册路由时,它只是在内部的一个延迟操作记录列表defered\_functions中添加了一个项,当执行应用对象的 register\_blueprint() 方法时,应用对象将从蓝图对象的 defered\_functions 列表中取出每一项,并以自身作为参数执行该匿名函数,即调用应用对象的 add\_url\_rule() 方法,这将真正的修改应用对象的路由表 ###蓝图的url前缀 当我们在应用对象上注册一个蓝图时,需要指定一个url_prefix关键字参数(这个参数默认是/)。在应用最终的路由表 url\_map中,在蓝图上注册的路由URL自动被加上了这个前缀,这相当有用,我们可以在多个蓝图中使用相同的URL规则而不会最终引起冲突,只要在注册蓝图时将不同的蓝图挂接到不同的自路径即可,想一想对于大型应用而言,不同的蓝图通常是不同的人员开发的,你很难保证URL规则不发生冲突 ###为蓝图加上url前缀 我们创建蓝图对象时,第一个参数指定了蓝图的名字。当在应用中注册蓝图时, 蓝图的路由项中的访问点endpoint被自动添加了这个名字 当不同的团队开发不同的蓝图时,和URL规则类似,你很难保证他们的视图函数名 彼此不同,尤其像index这样俗套的名字。如果不对来自不同蓝图的endpoint 进行区隔,那么 url_for('index') 到底应该生成那个URL?这显然无法确定 一旦给不同蓝图的endpoint加上了蓝图名前缀,我们可以确切地告诉url\_for() 了 url_for('admin.index') # /admin/ ###注册静态路由 和应用对象不同,蓝图对象创建时不会默认注册静态目录的路由。需要我们在 创建时指定 static_folder 参数。 下面的示例将蓝图所在目录下的static_admin目录设置为静态目录 admin = Blueprint("admin",__name__,static_folder='static_admin') app.register_blueprint(admin,url_prefix='/admin') 现在就可以使用/admin/static\_admin/<filename> 访问static\_admin目录下的静态文件了 定制静态目录URL规则 :可以在创建蓝图对象时使用 static\_url_path 来改变静态目录的路由。下面的示例将为static\_admin文件夹的路由设置为 /lib admin = Blueprint("admin",__name__,static_folder='static_admin',static_url_path='/lib') app.register_blueprint(admin,url_prefix='/admin') ###设置模版目录 蓝图对象默认的模板目录为系统的模版目录,可以在创建蓝图对象时使用 template_folder 关键字参数设置模板目录 admin = Blueprint('admin',__name__,template_folder='my_templates') 注:如果在templates中存在和my_templates同名文件,则系统会优先使用templates中的文件,在使用templates目录同名的情况下,需要通过路径区分,例如: my_templates存在两个,若使用admin目录下的my\_templates目录,则需要使用如下方式注册: admin = Blueprint('admin',__name__,template_folder='admin/my_templates') <file_sep># 支付,创建钥匙 1. 详细的可以阅读: https://open.alipay.com/platform/home/html 2. 关于沙箱环境(开发模拟环境) 3. 然后设置到公钥和私钥的知识点(还好我都比较理解了.!) 4. 还有一些API的说明!> 5. 公共请求参数 1. 有什么作用. 1. app_id 2. method 3. ...... 6. 首先安装python的一些插件. 1. pip install python-alipay-sdk --upgrade 2. 生成密钥文件 ```python openssl OpenSSL> genrsa -out app_private_key.pem 2048 # 私钥 OpenSSL> rsa -in app_private_key.pem -pubout -out app_public_key.pem # 导出公钥 OpenSSL> exit ``` 7. 然后就是把这两个放到单独的keys文件夹里面。 8. 支付宝的密钥交换解释 1. Q:和支付宝交换公钥是什么意思? A:私钥由开发者自行保管,把对应公钥提供给支付宝。相应的,支付宝提供自己的公钥给开发者,这称为交换公钥。 开发者使用开发者私钥对请求内容签名,支付宝收到请求后,会使用开发者公钥进行验签,验签通过证明信息来源可靠并且未篡改。 支付宝发送给开发者的数据中,支付宝也会使用自己的私钥进行签名。商户收到后,使用支付宝公钥验签,验签通过证明是支付宝发送的消息,并且未篡改。 9. 顺带一些ssh的知识 1. https://www.cnblogs.com/ailx10/p/7664040.html 1. 部分截图信息,请查看有道云笔记本的--置顶笔记本 2. 但是单方向还是需要注意中间人攻击。 10. <file_sep># 图片单独一个表 1. 为什么需要单独建表 1. 字段数量不确定性,比如说这里有3个iamges1,2,3字段,但是每一次不一定3个字段都使用. 2. 尽量不调整表结构就不调整.! 2. 以空间换时间. 1. 冗余字段. 2. # 项目模型类型说明 1. ## 跟django一样,需要设置一个父类,里面设置好 1. 更新时间 2. 创建时间 3. 但是有个问题,我没有看到他的BaseModel写明是父类, 4. 代码 ```python class BaseModel(object): """模型基类,为每个模型补充创建时间与更新时间""" create_time = db.Column(db.DateTime, default=datetime.now) # 记录的创建时间 update_time = db.Column(db.DateTime, default=datetime.now, onupdate=datetime.now) # 记录的更新时间 class Area(BaseModel, db.Model): """城区""" __tablename__ = "ih_area_info" id = db.Column(db.Integer, primary_key=True) # 区域编号 name = db.Column(db.String(32), nullable=False) # 区域名字 houses = db.relationship("House", backref="area") # 区域的房屋 ``` 5. ## 多对多关系 1. 代码 ```python # 房屋设施表,建立房屋与设施的多对多关系 house_facility = db.Table( "ih_house_facility", ##第一个对应的是创建表的名字 ## db.Column("house_id", db.Integer, db.ForeignKey("ih_house_info.id"), primary_key=True), # 房屋编号 db.Column("facility_id", db.Integer, db.ForeignKey("ih_facility_info.id"), primary_key=True) # 设施编号 ) ``` 2. ### 联合主键 1. 把house_id和facility_id结合起来,组成联合主键.! 2. 设置方法就是同时设置成为联合主键.! 3. 图片参考,请参考2018年8月15日的有道云笔记截图 4. ### 过滤关系,利用second关键起来!. 1. 代码 ```python class House(BaseModel, db.Model): """房屋信息""" __tablename__ = "ih_house_info" facilities = db.relationship("Facility", secondary=house_facility) # 房屋的设施 ``` 6. ## 补充多对多的知识点 1. 多对多关系是关系数据库中两个表之间的一种关系, 该关系中第一个表中的一个行可以与第二个表中的一个或多个行相关。第二个表中的一个行也可以与第一个表中的一个或多个行相关。 [1] 2. 详细 实例解释 比如在常见的订单管理数据库当中“产品”表和“订单”表之间的关系。单个订单中可以包含多个产品。另一方面,一个产品可能出现在多个订单中。因此,对于“订单”表中的每条记录,都可能与“产品”表中的多条记录对应。此外,对于“产品”表中的每条记录,都可以与“订单”表中的多条记录对应。这种关系称为多对多关系,因为对于任何产品,都可以有多个订单,而对于任何订单,都可以包含许多产品。请注意,为了检测到表之间的现有多对多关系,务必考虑关系的双方。 [1] 3. ### 要表示多对多关系,您必须创建第三个表,该表通常称为联接表, 它将多对多关系划分为两个一对多关系。将这两个表的主键都插入到第三个表中。因此,第三个表记录关系的每个匹配项或实例。例如,“订单”表和“产品”表有一种多对多的关系,这种关系是通过与“订单明细”表建立两个一对多关系来定义的。一个订单可以有多个产品,每个产品可以出现在多个订单中。 4. ### mysql表的一对一/一对多/多对多联系 https://www.cnblogs.com/panxuejun/p/5975753.html 7. 数据库设计范式 https://www.cnblogs.com/knowledgesea/p/3667395.html 8. 模型类已经创建好了,现在进行数据库迁移.!创建数据库.create database table 重点!三部曲 1. 使用命令 ```python #第一步 python manage.py db init #第二步 python manage.py db migrate -m 'init tables' # ``` 2. 如果显示nodatabase change,解决办法 1. 在demo导入model. 3. ## 升级,更新(相当于迁移,migrate) ```python #第三步 python manage.py db upgrade ``` <file_sep># 登陆后逻辑编写 1. ## 登录状态需要保存到session当中 2. 这个逻辑还是写在passport当中. 1. 设置一个路由路径先. 3. 老生常谈了. 1. 接收参数 2. 校验参数 1. 看看参数是否完整 3. 业务逻辑 4. ## 登录 1. 注意了,这个是登录,不是注册 1. 所以,首先得防止一下非法的暴力破解 2. 根据手机号码查询数据库 3. 对比账号密码 1. 如果验证成功,就保存登录状态, 2. 如果验证失败,记录错误次数,返回信息 5. ## 具体的代码实现 1. 获取数据 `request.get_json()` #估计会自己转换成为字典,方便调用 2. ### flask获取用户的远程IP地址 `request.remote_addr` 1. #### 拓展 django的远程获取用户IP地址 `request.META['REMOTE_ADDR']` 2. 记得经常用异常去排除错误! 3. 还有配置日志错误记录 3. flask日常数据库查询 `User.query.filter_by(mobile=mobile).first()` 4. flask日常返回json数据 `return jsonify(xx) 5. ### 又涉及到密码的问题了,所以这次的代码,验证密码的这一部分,得在models里面定义好函数和进行! ```python def check_passwd(self,passwd): ''' :param passwd: 用户登录时候提交的原始密码 :return : 如果正确 ''' return check_password_hash(self.password_hash,passwd) ``` 6. 如果登录失败了,也记得记录喔.! 7. ### redis有一个函数专用用来做加减的. 1. INCR 1. Redis Incr 命令将 key 中储存的数字值增一。 如果 key 不存在,那么 key 的值会先被初始化为 0 ,然后再执行 INCR 操作。 如果值包含错误的类型,或字符串类型的值不能表示为数字,那么返回一个错误。 本操作的值限制在 64 位(bit)有符号数字表示之内。 2. 然后,这个登录错误的信息也是设置一个限度. 8. 登录成功,保存到session会话当中!. # 关于测试,的确是的,用一个外部的,可以随意get,post的软件,操作,测试,的确是想当方便的.! # 前端 1. 测试的时候用的是postman,仅仅用于测试的.! 1. ## 可以在body里面raw写json格式的数据. 2. 前端的日常登录 1. 利用postman进行日常的测试! 2. # 使用postman测试前端登陆 1. ## 具体的测试结果,请查看云笔记的,2018年8月21号的笔记详情.! 2. ## 记住了,json的严格格式是都是使用双引号的,"" 3. ## 测试了,密码错误之后,就阻止登陆了! # 检查登陆状态与退出代码 1. ## 原来这个讲师都准备讲了,只是我以为他在之前已经设置了登陆检查,晕,以后还是跟着视频来吧.! 2. ## 由于登陆,属于查询,所以,是GET查询了.! `@api.route("/session",methods=['GET'])` 1. 在session中尝试获取当前的session值. `name = session.get("name")` 1. 如果能获取得到值的话,就是登陆过了,并且返回name值 3. ## 如果是退出的话,由于是属于删除session的值,所以方式是DELETE `@api.route("/session",methods=["DELETE"])` 1. ### 清除当前用户的session值.`session.clear()` 4. 然后就是查看一下前端的代码 1. ## 某种原因,前端页面的登陆和注册按钮,还有用户地址栏,显示属性都是`display:none`,应该是css设置的.继续. 5. ## 还得继续说说退出这个地方,`logout`,但是需要用delete方法,所以得用ajax方式去退出了.! 1. ### 我设置头部请求的时候,ajax设置的时候也是设置`headers`的.!注意了. # 登陆验证装饰器 1. 个人信息 1. 闭包的应用. 2. ## 关于用户认证,用户登陆的问题,想想以前的django,才用的是定义一个自定义的,继承于Login_view的模块. 1. ### 然后是添加到urls,因为所有的请求都必须在这里分流,所以在这里添加认证. 2. ### 但是项目里面的话,是在具体那个view需要权限的时候才继承这个自定义认证类. 3. ## 用户认证,flask这里的做法,发酸是在commons.py写一个验证装饰器 1. 然后装饰器里面调用了一次去获取session_id的数值 1. ### 然后里面的视图函数也想向刚刚的装饰器获取他们的数值. 1. 这个时候得借助中间人了,引入中间人,g对象,`from flask import g`,是一个全局变量!.估计是基于session的吧. 2. ### 在装饰器的内层函数当再加装装饰器 1. 先导入`import functools` 2. `functools.warpper`专门用来装饰内层函数 3. 什么是说明文档 1. 就是类或者函数里面的一对'''或者"""里面的内容,就是说明文档了. ```python def test(): """ 其实我就是说明文档了.! """ ``` 4. ### 使用装饰器,不应该去改变被装饰的函数,一般默认的装饰方法会修改的 ```python def test_wrapper(func): def test_func(*args,**kwargs): pass return test_func def test(): """good""" pass print(test.__name__)#这里的值不再等于test了 print(test.__doc__)#这里也不存在数值了. ``` 5. 应对上面的办法就是,使用functools去返回被装饰函数的属性, ```python @functools.wraps(func) def wrapper(*args,**kwargs) ``` # 登陆验证问题 1. ### 由于是前后端分离,所以,基本上所有的认证信息都是由前端自己每次去轮询去认证了 不能靠后端强制刷新,不过后端还是会提示,验证权限等等的.!<file_sep># 房屋列表业务分析 1. 根据条件进行搜索,得出结果 1. 条件:入住时间,位置区域,最新上线 2. 但是默认不是上面的三个条件,而是一个默认的排列结果 3. 区域信息和价格都好处理 4. ## 重点是处理时间 1. 问题是,House模型类里面,并没有专门记录时间的字段 2. 关于时间问题,现在关联到订单信息这边来了 3. ### 时间筛选方便,去查询这段时间里面,订单有没有相应的记录,如果就,就排除这个房源信息 # 房屋列表后端参数判断 1. 获取房屋的列表信息 2. ## 时间处理 1. 获取get过来的参数,然后`start_date = request.args.get("sd","")`,后面的为空,意思就是如果参数为空的话,就设置默认为空. 1. 结束时间和上面类似了. 2. 其他的非时间参数,也是如果没有获取到参数,就默认设置为空. 3. ## 时间转换 1. 然后利用datetime将字符串的日期转换为python的时间对象 1. `datetime.strptime(start_date,"%Y-%m-%d")` 2. ### 因为前端传递过来的格式不一定每次都是正确的,所以,必须,使用try来排除异常 2. 补充生成现在时间的方法,datetime 1. 代码 ```python datetime.datetime.now() datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S") ``` 3. ### 一言不合就使用断言,`assert start_date <= end_date` 4. 判断区域id 1. 代码 ```python try: area = Area.query.get(area_id) except Exception as e: #记录日志 current_app.logger.error(e) return jsonify("xxx") ``` 5. 处理页数 1. 和上面的判断区域id差不多的步骤 2. 尝试将获取到的p,用int去转换 1. 如果转换失败,就是使用异常处理去设置为默认 # 构造时间条件 1. ## 查询数据库 1. ### 这个位置可以对参数进行拆分,因为这个位置要接收很多的参数进行数据库查询 1. 例如,时间,区域,等等信息 2. 填充过滤参数,参数不确定 1. 代码,留意好filter_params,filter的用法。 ```python filter_params = [] #填充过滤参数 ``` 3. #### 比较难搞时间交叉的时间 1. 查询冲突的房子`select * from order where order.begin_data<=end_date and order.end_date >= start_date` 2. #### 我用边界的思想去想象,就是,区域如果是重叠的话,达到边界就触发 3. 彼此的边界还是有接触的话,就证明还是存在交集的,恩恩,就是这样了。! 4. not in,notin查询,还有条件的组装,多重条件的组装查询,区域,时间, 1. 代码 ```python if conflict_orders: # 从订单中获取冲突的房屋id conflict_house_ids = [order.house_id for order in conflict_orders] # 如果冲突的房屋id不为空,向查询参数中添加条件 if conflict_house_ids: filter_params.append(House.id.notin_(conflict_house_ids)) # 区域条件 if area_id: filter_params.append(House.area_id == area_id) # 查询数据库 # 补充排序条件 if sort_key == "booking": # 入住最多 house_query = House.query.filter(*filter_params).order_by(House.order_count.desc()) elif sort_key == "price-inc": house_query = House.query.filter(*filter_params).order_by(House.price.asc()) elif sort_key == "price-des": house_query = House.query.filter(*filter_params).order_by(House.price.desc()) else: # 新旧 house_query = House.query.filter(*filter_params).order_by(House.create_time.desc()) ``` 2. House.query.filter() 3. #### 关于filter的用法,语法,filter比起filter_by更加强大,支持比较运算符,支持or_、in_等语法。 1. https://www.cnblogs.com/Orangeorchard/p/8133795.html 2. https://blog.csdn.net/bieguolaia/article/details/77922605 1. 部分代码 ```python # 查询 id 等于 1 的数据,只显示第一条。多个条件也是可以的。但格式只能是 key=value 的方式,多条件关系为 and。 print(User.query.filter(User.id == 1).first()) print(User.query.filter(User.id == 1, User.name == "小王").first()) # 先注意一下 filter 与 filter_by 参数写法上的区别。 # 另外再注意一下:filter 是 不 支 持 x and x 或者 x or x 这样的操作的,虽然这样写不报错... # filter 支持的操作是 > < = != 这些,当然还有上面 filter_by 的那种关系 x, y -> x and y。 # 那要用这种 and、or 怎么办 ? from sqlalchemy import and_, or_ print(User.query.filter(and_(User.id == 1, User.address == "BJ")).first()) print(User.query.filter(or_(User.id == 1, User.address == "SH")).first()) # 对,就这么搞 print(User.query.filter_by(id=1).value("name")) print(list(User.query.filter_by(id=2).values("name", "address"))) # 输出匹配数据的指定字段,默认是 select * form xxx,现在是 select name, address from xxx。 # 又要注意了:.value 只能用于找到的对象是一个时,例如找到多个对象,则 .value 只返回第一个对象的值。 ``` 3. 提及一下django的知识点先,就是,在django里面,使用filter添加多个查询条件,他们的关系是`and`关系, 1. 使用Q对象进行复杂查找 1. 关键字参数查询 - 输入filter()等 - 是“AND”编辑在一起。如果需要执行更复杂的查询(例如,带OR语句的查询),则可以使用。Q objects 4. flask数据库里面的filter_by用法,House.query.filter_by(user_id=user_id),这个就是才用关键字了。Models模块里面的House模型类的确存在一个user_id这个字段 5. 2. ## 然后就是排序 1. 按照传递过来的参数 # 房屋列表页分页补充与测试 1. page的使用(前期准备) 1. 在flask中使用分页更加的方便,直接在查询结果后面添加就可以了 1. example:`paginate = User.query.order_by("-id").paginate()` 2. 处理分页 1. page_data = paginate.items 2. 代码 ```python page_obj = User.query.order_by("-id").paginate(page=page,per_page=x,error_out=False) ``` 3. 获取页面数据`house_li = page_obj.items` 1. 转换成为字典的形式 1. 代码 ```python house_li = page_obj.items houses = [] for house in house_li: houses.append(house.to_base_dict()) ## 恩恩,to_base_dict是定义在models里面的 #同时返回总页数 total_page = page_obj.pages return jsonify("xxx") ``` # 解析_等好参数,也就是,我不理解的条件查询 1. `House.area_id == area_id`这个,filter,条件表达式,实质他是一个`BinaryExpression object` 2. 所以,这不是普通的用法 3. `House.area_id == area_id` 等价于 `House.area_id.__eq__(1)` # 房屋列表页缓存处理 1. # redis的pipeline的使用 1. ## 重要 1. 恩恩。很类似linux的shell的管道命令,就是,一次性可以执行多个操作 2. 使用,代码 ```python #创建管道对象,可以一次性执行多个语句 pipeline = redis_store.pipeline() #开启多个语句的记录 pipeline.multi() pipeline.hset(redis_key,page,resp_json) pipeline.expire(redis_key,xxx) #然后执行 pipeline.execute() ``` # 前端编写 1. 随着滚动,不断加载数据 1. 在前端会设置页数,当前页,总页数, 2. 填充页面 1. 请求了新的页面数据,形式是追加 2. 还有一种 1. 如果改变了条件,就重新填充了。 2. 部分代码 1. 代码-解析url中的查询字符串 ```js function decodeQuery(){ var search = decodeURI(document.location.search); return search.replace(/(^\?)/, '').split('&').reduce(function(result, item){ values = item.split('='); result[values[0]] = values[1]; return result; }, {}); } ``` 3. # `2018年8月26日补充` 1. 页面加载好了,就提取url的参数,去获取后台数据 2. ## 稍微详细一点点说明上面的流程 1. 首先,flask根据前端传送过来的请求,加载search.html,这个页面都是纯的html+css+js,此时并没有向后台查询数据 2. 然后当加载到js部分的时候,就进行了一系列的操作 1. 首选是根据当前页面的url参数,整理了一下 2. 然后这个时候才正式向后端查询当前的房屋情况.get请求. 3. ## 改变当前的搜索条件 1. ### 如果重新点击时间,位置和指定选项,如何做出改变呢 2. 答案就是 1. #### 前端写了一个空白区域的监听,$("display-mask") 2. 当这个区域被选中,被点击,就意味着需要重新搜索了. 3. 同时还需要重新设置前端浏览到的页数. 4. ## 关于滚动刷新的问题 1. ### 前端设置了一个绑定滚动的方法 1. #### `window.onscroll=function` 2. 为窗口的滚动添加事件函数 3. #### 滚动的时候,也同时设置前端的页面页数数量 4. #### 还有一个地方需要注意,要小心有重复的页面数据 1. 解决方法,就是添加一个全局变量,如果前端js确实在请求数据,就设置为真,其他多次查询就阻塞这样子. 2. 部分介绍 语法 array.reduce(function(total, currentValue, currentIndex, arr), initialValue) 参数 参数 描述 function(total,currentValue, index,arr) 必需。用于执行每个数组元素的函数。 函数参数: |参数 | 描述| |-----|------| |total |必需。初始值, 或者计算结束后的返回值。| |currentValue | 必需。当前元素| |currentIndex |可选。当前元素的索引| |arr |可选。当前元素所属的数组对象。| initialValue |可选。传递给函数的初始值| 2. ## 当文档加载好了以后的工作流程 ```js $(document).ready(function(){ var queryData = decodeQuery(); var startDate = queryData["sd"]; var endDate = queryData["ed"]; $("#start-date").val(startDate); $("#end-date").val(endDate); updateFilterDateDisplay(); var areaName = queryData["aname"]; if (!areaName) areaName = "位置区域"; $(".filter-title-bar>.filter-title").eq(1).children("span").eq(0).html(areaName); ``` 3. js如何获取当前url地址信息,如何获取url地址参数 1. document.location."当前页后缀",例如`document.location.search` 4. decodeURL 1. decodeURI() 函数可对 encodeURI() 函数编码过的 URI 进行解码。 1. 实例 ```python #在本例中,我们将使用 decodeURI() 对一个编码后的 URI 进行解码: <script type="text/javascript"> var test1="http://www.w3school.com.cn/My first/" document.write(encodeURI(test1)+ "<br />") document.write(decodeURI(test1)) </script> #输出: http://www.w3school.com.cn/My%20first/ http://www.w3school.com.cn/My first/ ``` 2. decodeURI与decodeURIComponent区别 https://www.cnblogs.com/hamsterPP/p/7131163.html 3. js的reduce用法 1. reduce() 方法接收一个函数作为累加器,数组中的每个值(从左到右)开始缩减,最终计算为一个值。 2. 实例 ```js var numbers = [65, 44, 12, 4]; function getSum(total, num) { return total + num; } function myFunction(item) { document.getElementById("demo").innerHTML = numbers.reduce(getSum); } #结果125 ``` 5. ## 后续 1. each的用法 ```js var arr = [ "one", "two", "three", "four"]; $.each(arr, function(){ alert(this); }); ``` 6. ## 关于jq的on方法 1. 定义和用法 on() 方法在被选元素及子元素上添加一个或多个事件处理程序。 自 jQuery 版本 1.7 起,on() 方法是 bind()、live() 和 delegate() 方法的新的替代品。该方法给 API 带来很多便利,我们推荐使用该方法,它简化了 jQuery 代码库。 2. 注意:使用 on() 方法添加的事件处理程序适用于当前及未来的元素(比如由脚本创建的新元素)。 3. 提示:如需移除事件处理程序,请使用 off() 方法。 4. 提示:如需添加只运行一次的事件然后移除,请使用 one() 方法。 5. 语法 $(selector).on(event,childSelector,data,function)<file_sep># 1.3 Flask-Login ###Flask-Login简介 Flask-Login扩展可以快速实现登陆注册功能 ###密码安全性处理 在登陆时,需要设置和使用密码,但开发中数据库存储密码一般不是明文存储,而是密文存储,我们在用户提交密码时,需要对密码进行加密处理,然后将加密后的密码进行进行存储,我们对数据库的加密方式为散列加密,如下所示: **使用Werkzeug实现密码散列** - generate\_password\_hash(password,method=pbkdf2:sha1,salt\_length=8):这个函数将 原始密码作为输入,以字符串形式输出密码的散列值,输出的值可保存在用户数据库中。 method和salt_length的默认值就能满足大多数需求。 - check\_password_hash(hash, password):这个函数的参数是从数据库中取回的密码散列值和用户输入的密码。返回值为True表明密码正确。 修改User模型,加入密码散列: # class User(db.Model): __tablename__ = 'users' id = db.Column(db.Integer, primary_key=True) email = db.Column(db.String(64), unique=True, index=True) username = db.Column(db.String(64), unique=True, index=True) password_hash = db.Column(db.String(128)) @property def password(self): raise AttributeError('password is not a readable attribute') @password.setter def password(self, password): self.password_hash = generate_password_hash(password) def verify_password(self, password): return check_password_hash(self.password_hash, password) def __repr__(self): return '<User %r>' % self.username 计算密码散列值的函数通过名为password的只写属性实现。设定这个属性的值时,赋值方法会调用Werkzeug提供的generate\_password\_hash()函数,并把得到的结果赋值给password_hash 字段。如果试图读取password属性的值,则会返回错误,原因很明显,因为生成散列值后就无法还原成原来的密码了 verify\_password方法接受一个参数(即密 码), 将其传给Werkzeug提供的check\_password\_hash()函数,和存储在User模型中的密码散列值进行比对。如果这个方法返回True,就表明密码是正确的 使用密码散列的好处为:两个用户使用相同的密码,但密码散列值也完全不一样 ###创建蓝图 由于注册登陆模块是一个独立的较大的模块,则我们创建一个独立的目录用于登陆注册功能的代码实现 代码: __init__.py文件代码: from flask import Blueprint auth = Blueprint('auth', __name__) from . import views views.py文件代码: from flask import render_template from . import auth @auth.route('/login') def login(): return render_template('auth/login.html') 注:为了方便管理,登陆所需要的模版文件保存在auth文件夹中,这个文件夹在app/templates中创建 注册蓝图: def create_app(config_name): # ... from .auth import auth as auth_blueprint app.register_blueprint(auth_blueprint, url_prefix='/auth') return app ###使用Flask-Login认证用户 Flask-Login是个非常有用的小型扩展,专门用于管理用户认证系统中的认证状态,且不依赖特定的认证机制 ###Flask-Login要求实现的用户方法 - is_authenticated() 如果用户已经登录,必须返回 True ,否则返回 False - is_active() 如果允许用户登录,必须返回 True ,否则返回 False 。如果要禁用账户,可以返回 False - is_anonymous() 对普通用户必须返回 False - get_id() 必须返回用户的唯一标识符,使用 Unicode 编码字符串 这些方法在模型类中需要实现,而flask-login提供了一个UserMixin类,已经默认实现了这四个方法,且满足大部分需求,所以,我们的User模型需要继承UserMixin类 ``` class User(UserMixin, db.Model): ``` ###初始化Flask-Login from flask_login import LoginManager login_manager = LoginManager() login_manager.session_protection = 'strong' login_manager.login_view = 'auth.login' def create_app(config_name): # ... login_manager.init_app(app) # ... LoginManager对象的session\_protection属性可以设为 None、'basic'或'strong',以提供不同的安全等级防止用户会话遭篡改。设为'strong'时,Flask-Login会记录客户端IP地址和浏览器的用户代理信息,如果发现异动就登出用户。login_view属性设置登录页面的端点。Flask-Login要求实现一个回调函数,使用指定的标识符加载用户,这个函数需要定义在models.py文件中 from . import login_manager @login_manager.user_loader def load_user(user_id): return User.query.get(int(user_id)) 加载用户的回调函数接收以 Unicode 字符串形式表示的用户标识符。如果能找到用户,这 个函数必须返回用户对象;否则应该返回None ##登入登出功能的实现 ###表单的处理 用户的登录表单中包含一个用于输入电子邮件地址的文本字段、一个密码字段、一个"记住我"复选框和提交按钮 class LoginForm(FlaskForm): email = StringField(u'邮箱', validators=[Required(), Length(1, 64), Email()]) password = PasswordField(u'密码', validators=[Required()]) remember_me = BooleanField(u'记住我') submit = SubmitField(u'登陆') ###表单验证 @auth.route('/login', methods=['GET', 'POST']) def login(): form = LoginForm() if form.validate_on_submit(): user = User.query.filter_by(email=form.email.data).first() if user is not None and user.verify_password(form.password.data): login_user(user, form.remember_me.data) return redirect(request.args.get('next') or url_for('main.index')) flash(u'用户名或密码错误') return render_template('auth/login.html', form=form) @auth.route('/logout') @login_required def logout(): logout_user() flash(u'成功注销用户') return redirect(url_for('main.index')) 其中:被login_required装饰器装饰过的路由函数只允许在登陆后才能访问 ##注册功能的实现 ###表单的处理 class RegistrationForm(FlaskForm): email = StringField('Email', validators=[Required(), Length(1, 64), Email()]) username = StringField(u'用户名', validators=[ Required(), Length(1, 64), Regexp('^[A-Za-z][A-Za-z0-9_.]*$', 0, '用户名只能包含字母,数字,点或下划')]) password = PasswordField(u'密码', validators=[ Required(), EqualTo('password2', message='两次密码输入不一致')]) password2 = PasswordField(u'<PASSWORD>', validators=[Required()]) submit = SubmitField(u'注册') def validate_email(self, field): if User.query.filter_by(email=field.data).first(): raise ValidationError('当前邮箱已经被注册过了') def validate_username(self, field): if User.query.filter_by(username=field.data).first(): raise ValidationError('当前用户名已经被占用') 这个表单使用WTForms提供的Regexp 验证函数,确保username字段只包含字母、数字、下划线和点号。这个验证函数中正则表达式后面的两个参数分别是正则表达式的旗标和验证失败时显示的错误消息。安全起见,密码要输入两次。此时要验证两个密码字段中的值是否一致,这种验证可使用WTForms 提供的另一验证函数实现,即EqualTo。个验证函数要附属到两个密码字段中的一个上,另一个字段则作为参数传入。这个表单还有两个自定义的验证函数,以方法的形式实现。如果表单类中定义了以validate_ 开头且后面跟着字段名的方法,这个方法就和常规的验证函数一起调用。本例分别为email和username字段定义了验证函数,确保填写的值在数据库中没出现过。自定义的验证函数要想表示验证失败,可以抛出ValidationError异常,其参数就是错误消息 ###表单验证 @auth.route('/register', methods=['GET', 'POST']) def register(): form = RegistrationForm() if form.validate_on_submit(): user = User(email=form.email.data, username=form.username.data, password=form.password.data) db.session.add(user) db.session.commit() flash('现在可以登陆了') return redirect(url_for('auth.login')) return render_template('auth/register.html', form=form)
22c1ed1d7dd6e3bdb4def2fdf3c5554cf731f3f4
[ "Markdown", "Python" ]
36
Markdown
headB/falsk_ihome
ea2b0fdd2aa21fdd40dbf1e82047bf0eb5de7959
1e3725f0f787a0fd8b11ca21df5bebe45ce6d67e
refs/heads/master
<repo_name>ZhukOffRoman/CS61A-1<file_sep>/lab13/lab13.py ## Lab 13: Coroutines ## # Q3 def hailstone(n): """ >>> for num in hailstone(10): ... print(num) ... 10 5 16 8 4 2 1 """ num = n while num != 1: if num%2 == 0: yield num num = num // 2 else: yield num num = (num * 3) + 1 print (1) <file_sep>/Downloads/fa16-hw3-master/ANSWERS.md ## Questions Go to `localhost:3000/teachers` in your browser; why does this not work? This does not work because there are no routes that match a GET request to "/teachers" because we are using POST here instead. What type of request did your browser just perform? GET request. Go back to `localhost:3000/teachers/new`; submit the form again. What URL do you end up at? localhost:3000/teachers Why does `localhost:3000/teachers` work now? There is a now an existing POST to '/teachers'. <file_sep>/README.md # CS61A Structure and Interpretation of Computer Programs - Summer 2016 An introduction to programming and computer science focused on abstraction techniques as means to manage program complexity. Techniques include procedural abstraction; control abstraction using recursion, higher-order functions, generators, and streams; data abstraction using interfaces, objects, classes, and generic operators; and language abstraction using interpreters and macros. The course exposes students to programming paradigms, including functional, object-oriented, and declarative approaches. It includes an introduction to asymptotic analysis of algorithms. There are several significant programming projects. The CS 61 series is an introduction to computer science, with particular emphasis on software and on machines from a programmer's point of view. This first course concentrates mostly on the idea of abstraction, allowing the programmer to think in terms appropriate to the problem rather than in low-level operations dictated by the computer hardware. The next course, CS 61B, will deal with the more advanced engineering aspects of software, such as constructing and analyzing large programs. Finally, CS 61C concentrates on machines and how they carry out the programs you write. In CS 61A, we are taught about programming, but not about how to use one particular programming language. We consider a series of techniques for controlling program complexity, such as functional programming, data abstraction, and object-oriented programming. Mastery of a particular programming language is a very useful side effect of studying these general techniques as well as learning the essence of programming. <file_sep>/lab01/tests/sevens.py test = { 'name': 'Sevens', 'points': 0, 'suites': [ { 'cases': [ { 'code': r""" >>> x = [1, 3, [5, 7], 9] # Write the code that indexes into x to output the 7 4707318cc6c23ab9528a5400ba87bf5f # locked >>> x = [[7]] # Write the code that indexes into x to output the 7 23839b8d7288983be6e91a70c40daa06 # locked >>> x = [1, [2, [3, [4, [5, [6, [7]]]]]]] # Write the code that indexes into x to output the 7 80ddd737afc4116c15d79235351b126d # locked """, 'hidden': False, 'locked': True } ], 'scored': False, 'type': 'wwpp' }, { 'cases': [ { 'code': r""" >>> lst = [3, 2, 7, [84, 83, 82]] >>> lst[4] d7b5fd49f83e4ee318af207fc969c9f4 # locked >>> lst = [3, 2, 7, [84, 83, 82]] # Write the code that indexes into lst to output the 82 860df3acadbda8704ab8bcc25394d43f # locked >>> lst[3][0] fc3c3fa6196cfd5212ef20f34fd36b0c # locked """, 'hidden': False, 'locked': True } ], 'scored': False, 'type': 'wwpp' } ] } <file_sep>/hw/hw07/hw07.py # Linked Lists (do not modify the following class!) class Link: """ >>> s = Link(1, Link(2, Link(3))) >>> s Link(1, Link(2, Link(3))) >>> len(s) 3 >>> s[2] 3 >>> s = Link.empty >>> len(s) 0 """ empty = () def __init__(self, first, rest=empty): assert rest is Link.empty or isinstance(rest, Link) self.first = first self.rest = rest # Q1 def link_to_list(link): """Takes a Link and returns a Python list with the same elements. >>> link = Link(1, Link(2, Link(3, Link(4)))) >>> link_to_list(link) [1, 2, 3, 4] >>> link_to_list(Link.empty) [] """ if link is Link.empty: return [] else: return [link.first] + link_to_list(link.rest) # Q2 (and Extra Question) def has_cycle(link): """Return whether link contains a cycle. >>> s = Link(1, Link(2, Link(3))) >>> s.rest.rest.rest = s >>> has_cycle(s) True >>> t = Link(1, Link(2, Link(3))) >>> has_cycle(t) False >>> u = Link(2, Link(2, Link(2))) >>> has_cycle(u) False """ seen = [] while link != Link.empty: seen += [link] link = link.rest if link in seen: return True return False def has_cycle_constant(link): """Return whether link contains a cycle. >>> s = Link(1, Link(2, Link(3))) >>> s.rest.rest.rest = s >>> has_cycle_constant(s) True >>> t = Link(1, Link(2, Link(3))) >>> has_cycle_constant(t) False """ "*** YOUR CODE HERE ***" # Trees (do not modify the following class!) class Tree: def __init__(self, entry, children=[]): for c in children: assert isinstance(c, Tree) self.entry = entry self.children = children def __repr__(self): if self.children: children_str = ', ' + repr(self.children) else: children_str = '' return 'Tree({0}{1})'.format(self.entry, children_str) def is_leaf(self): return not self.children # Q3 def cumulative_sum(t): """ Mutates t where each node's entry becomes the sum of all entries in the corresponding subtree rooted at t. >>> t = Tree(1, [Tree(3, [Tree(5)]), Tree(7)]) >>> cumulative_sum(t) >>> t Tree(16, [Tree(8, [Tree(5)]), Tree(7)]) """ if t.is_leaf(): return t else: for child in t.children: cumulative_sum(child) t.entry += sum([child.entry]) # Q4 def is_bst(t): """Returns True if the Tree t has the structure of a valid BST. >>> t1 = Tree(6, [Tree(2, [Tree(1), Tree(4)]), Tree(7, [Tree(7), Tree(8)])]) >>> is_bst(t1) True >>> t2 = Tree(8, [Tree(2, [Tree(9), Tree(1)]), Tree(3, [Tree(6)]), Tree(5)]) >>> is_bst(t2) False >>> t3 = Tree(6, [Tree(2, [Tree(4), Tree(1)]), Tree(7, [Tree(7), Tree(8)])]) >>> is_bst(t3) False >>> t4 = Tree(1, [Tree(2, [Tree(3, [Tree(4)])])]) >>> is_bst(t4) True >>> t5 = Tree(1, [Tree(0, [Tree(-1, [Tree(-2)])])]) >>> is_bst(t5) True >>> t6 = Tree(1, [Tree(4, [Tree(2, [Tree(3)])])]) >>> is_bst(t6) True """ if t.is_leaf(): return True if len(t.children) == 1: return True elif t.entry < t.children[0].entry and t.entry > t.children[1].entry: return False for c in t.children: return is_bst(c) #if bst_min(t.children) <= t.entry and bst_max(t.children) >= t.entry: #checks left and right node of children and compare it to the root #return True #def bst_max(t): #wanted to index through the right children by setting index to 1 and finding the max value by iterating through the list of of children #index = 1 #if is_leaf(t): # return entry(t) #else: #index += 1 #return max[bst_max(c) for c in t.children] #def bst_min(t): #wanted to index through the left children by setting index to 0 and finding the min value by iterating through the list of of children #index = 0 #if is_leaf(t): #return entry(t) #else: #index += 1 #return min[bst_min(c) for c in t.children] #def bst_max(self): #disc 9 references #if self.right is tree.empty: #return self.entry #return self.right.max #def bst_min (self): #if self.left is tree.empty: #return self.entry #return self.left.min""" # Sets (do not modify the following function!) import time def timeit(func): """Returns the time required to execute FUNC() in seconds.""" t0 = time.perf_counter() func() return time.perf_counter() - t0 # Q5 def add_up(n, lst): """Returns True if any two non identical elements in lst add up to n. >>> add_up(100, [1, 2, 3, 4, 5]) False >>> add_up(7, [1, 2, 3, 4, 2]) True >>> add_up(10, [5, 5]) False >>> add_up(151, range(0, 200000, 2)) False >>> timeit(lambda: add_up(151, range(0, 200000, 2))) < 1.0 True >>> add_up(50002, range(0, 200000, 2)) True """ for x in lst: for y in lst: if x > n or y > n: return False if x!=y and (x + y) == n: return True return False # Q6 def missing_val(lst0, lst1): """Assuming that lst0 contains all the values in lst1, but lst1 is missing one value in lst0, return the missing value. The values need not be numbers. >>> from random import shuffle >>> missing_val(range(10), [1, 0, 4, 5, 7, 9, 2, 6, 3]) 8 >>> big0 = [str(k) for k in range(15000)] >>> big1 = [str(k) for k in range(15000) if k != 293 ] >>> shuffle(big0) >>> shuffle(big1) >>> missing_val(big0, big1) '293' >>> timeit(lambda: missing_val(big0, big1)) < 1.0 True """ s = set(lst0).difference(lst1) return list(s)[0] #new set with elements in s but not in t
103225b7667911d231bfb68eaa7590282b0ba3b0
[ "Markdown", "Python" ]
5
Python
ZhukOffRoman/CS61A-1
5fbbed9e9525186b2c9a721eab2ba078e297decb
711e14e0f481fa9e7e7c46de7ea2de7618a59016
refs/heads/master
<repo_name>morgius/WeatherApi<file_sep>/WeatherApp/Services/WeatherService.cs  using Microsoft.Extensions.Options; using Newtonsoft.Json; using System; using System.Collections.Generic; using System.Linq; using System.Net.Http; using System.Text; using System.Threading.Tasks; using WeatherApp.Helpers; using WeatherApp.Models; namespace WeatherApp.Services { public class WeatherService: IWeatherService { //private readonly string myKey = "34f898d23f6bab3e64220d5f0ca9794c"; private readonly string myKey; private HttpClient Client { get; } public WeatherService(IHttpClientFactory httpClientFactory, IOptions<WeatherApi> options) { Client = httpClientFactory.CreateClient(); myKey = options.Value.Key; } public async Task<WeatherRequest> Get(string name) { HttpResponseMessage response = await Client.GetAsync($"https://api.openweathermap.org/data/2.5/weather?q={name}&appid={myKey}"); if (response.IsSuccessStatusCode) { string content = await response.Content.ReadAsStringAsync(); WeatherRequest weatherRequest = JsonConvert.DeserializeObject<WeatherRequest>(content); return weatherRequest; } else { return null; } } } } <file_sep>/WeatherApp/MapperProfiles/RequestToModelProfile.cs using AutoMapper; using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using WeatherApp.Helpers; using WeatherApp.Models; namespace WeatherApp.MapperProfiles { public class RequestToModelProfile:Profile { public RequestToModelProfile() { CreateMap<WeatherRequest, WeatherModel>().ForMember(dest => dest.Country, x => x.MapFrom(src => src.Sys.Country)) .ForMember(dest => dest.Temperature, x => x.MapFrom(src => src.Main.Temp.KelvinToCelsius())) .ForMember(dest => dest.TempMin, x => x.MapFrom(src => src.Main.Temp_Min.KelvinToCelsius())) .ForMember(dest => dest.TempMax, x => x.MapFrom(src => src.Main.Temp_Max.KelvinToCelsius())) .ForMember(dest => dest.Humidity, x => x.MapFrom(src => src.Main.Humidity)) .ForMember(dest => dest.Clouds, x => x.MapFrom(src => src.Clouds.All.CloudsInPercent())) .ForMember(dest => dest.WindSpeed, x => x.MapFrom(src => src.Wind.Speed)) .ForMember(dest => dest.Pressure, x => x.MapFrom(src => src.Main.Pressure)); } } } <file_sep>/WeatherApp/Models/WeatherModel.cs using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace WeatherApp.Models { public class WeatherModel { public string Name { get; set; } public float Temperature { get; set; } public float TempMin { get; set; } public float TempMax { get; set; } public int Humidity { get; set; } public string Clouds { get; set; } public float WindSpeed { get; set; } public int Pressure { get; set; } public string Country { get; set; } } } <file_sep>/WeatherApp/Controllers/WeatherController.cs using AutoMapper; using Microsoft.AspNetCore.Mvc; using Newtonsoft.Json; using System; using System.Collections.Generic; using System.Linq; using System.Net.Http; using System.Threading.Tasks; using WeatherApp.Models; using WeatherApp.Services; namespace WeatherApp.Controllers { [ApiController] [Route("api/weather")] public class WeatherController:ControllerBase { private readonly IMapper mapper; private readonly IWeatherService weatherService; public WeatherController(IWeatherService weatherService, IMapper mapper) { this.mapper = mapper; this.weatherService = weatherService; } [HttpGet()] [Route("GetWeather")] public async Task<IActionResult> GetWeather(string name) { var weather = await weatherService.Get(name); if (weather is null) { return NotFound(); } var response = mapper.Map<WeatherModel>(weather); return Ok(response); } } } <file_sep>/WeatherApp/Services/IWeatherService.cs using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using WeatherApp.Models; namespace WeatherApp.Services { public interface IWeatherService { Task<WeatherRequest> Get(string name); } } <file_sep>/WeatherApp/Helpers/Extensions.cs using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace WeatherApp.Helpers { public static class Extensions { public static float KelvinToCelsius(this float kelv) { return (float)Math.Round(kelv - 273.15); } public static string CloudsInPercent(this int num) { return $"{num}%"; } } }
0a69c42dafbb1effbd7c6422d5515dd56c568dff
[ "C#" ]
6
C#
morgius/WeatherApi
84f52d83b4d70a7aac77cd2cf67b94f817a90bc1
27492230f2a9ef56905f4498abe05cf0c481e924
refs/heads/master
<repo_name>nala1997/Weather<file_sep>/app/src/main/java/edu/niit/weatherforecast/activity/WeatherForecastMainActivity.java package edu.niit.weatherforecast.activity; import android.annotation.SuppressLint; import android.content.Intent; import android.support.v4.view.ViewPager; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.LayoutInflater; import android.view.View; import android.widget.Button; import android.widget.ImageView; import android.widget.ListView; import java.util.ArrayList; import edu.niit.weatherforecast.R; import edu.niit.weatherforecast.adapter.CityCursorApdater; import edu.niit.weatherforecast.adapter.WeatherAdapter; import edu.niit.weatherforecast.dao.CityDao; import edu.niit.weatherforecast.entity.City; public class WeatherForecastMainActivity extends AppCompatActivity implements View.OnClickListener{ private ImageView Title_City; private ViewPager pager_weather; private ArrayList<View> weatherList; private WeatherAdapter weatherAdapter; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_weather_forecast_main); Title_City=findViewById(R.id.title_city); Title_City.setOnClickListener(this); pager_weather=(ViewPager) findViewById(R.id.weekly_weather); weatherList=new ArrayList<View>(); LayoutInflater inflater=getLayoutInflater(); weatherList.add(inflater.inflate(R.layout.weekly_one,null,false)); weatherList.add(inflater.inflate(R.layout.weekly_two,null,false)); weatherAdapter=new WeatherAdapter(weatherList); pager_weather.setAdapter(weatherAdapter); pager_weather.setOffscreenPageLimit(10); } @Override public void onClick(View v) { switch (v.getId()){ case R.id.title_city: Intent intent=new Intent(WeatherForecastMainActivity.this,SelectActivity.class); startActivity(intent); break; } } } <file_sep>/app/src/main/java/edu/niit/weatherforecast/activity/SelectActivity.java package edu.niit.weatherforecast.activity; import android.app.Application; import android.content.Intent; import android.database.Cursor; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.View; import android.widget.AdapterView; import android.widget.ArrayAdapter; import android.widget.Button; import android.widget.ImageView; import android.widget.ListView; import java.util.ArrayList; import java.util.List; import edu.niit.weatherforecast.R; import edu.niit.weatherforecast.adapter.CityCursorApdater; import edu.niit.weatherforecast.dao.CityDao; import edu.niit.weatherforecast.entity.City; public class SelectActivity extends AppCompatActivity implements View.OnClickListener{ private ListView cityList; private CityDao cityDao; private City city; private CityCursorApdater apdater; private ImageView Btn_Back; private List<City> mCityList; private Application myApplication; private ArrayList<String> mArrayList; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.select_city); cityList=findViewById(R.id.city_item); cityDao=new CityDao(this); Btn_Back=findViewById(R.id.btn_back); Btn_Back.setOnClickListener(this); String[] listData={"北京-北京","北京-顺义","北京-海淀","上海-上海","上海-保定","上海-嘉定","上海-金山","天津-天津","天津-大港","天津-蓟县","重庆-重庆","重庆-合川","重庆-江津"}; ArrayAdapter<String> arrayAdapter=new ArrayAdapter<String>(SelectActivity.this, android.R.layout.simple_list_item_1,listData); cityList.setAdapter(arrayAdapter); /*Cursor cursor=cityDao.getCursor(); if (cursor!=null){ apdater=new CityCursorApdater(this,cursor); cityList.setAdapter(apdater); } cityList.setOnItemClickListener(new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView<?> adapterView, View view, int position, long id) { Cursor cursor= (Cursor) adapterView.getItemAtPosition(position); if (cursor!=null){ city=new City( cursor.getInt(cursor.getColumnIndex("_id")), cursor.getString(cursor.getColumnIndex("province")), cursor.getString(cursor.getColumnIndex("city")), cursor.getString(cursor.getColumnIndex("number")), cursor.getString(cursor.getColumnIndex("allPY")), cursor.getString(cursor.getColumnIndex("allfirstPY")), cursor.getString(cursor.getColumnIndex("firstPY"))); } } });*/ } @Override public void onClick(View v) { switch (v.getId()){ case R.id.btn_back: finish(); break; } } }
845a808d7fd182a61899e7c7b9fea5270cad47a7
[ "Java" ]
2
Java
nala1997/Weather
211988f6fd61fe95adedea55ae1a823ea525512f
06a9b871c01ac348018e3d88863e2ce58da8c486
refs/heads/master
<file_sep>package br.com.watch.api.dto; public class GetAngleDTO { private Integer hour; private Integer minutes; public Integer getHour() { return hour; } public void setHour(Integer hour) { this.hour = hour; } public Integer getMinutes() { return minutes; } public void setMinutes(Integer minutes) { this.minutes = minutes; } } <file_sep>package br.com.watch.api.dto; public class GetAngleResponseDTO { private double angle; public GetAngleResponseDTO(double angle) { this.angle = angle; } public double getAngle() { return angle; } } <file_sep>package br.com.watch.api.controller; import java.util.Calendar; import javax.ws.rs.POST; import javax.ws.rs.Path; import javax.ws.rs.Produces; import javax.ws.rs.core.MediaType; import br.com.watch.api.dto.GetAngleDTO; import br.com.watch.api.dto.GetAngleResponseDTO; import br.com.watch.utils.ClockUtils; @Path("/clock") public class Controller { @POST @Produces(MediaType.APPLICATION_JSON) public GetAngleResponseDTO getClock(GetAngleDTO getAngleDTO) { final Integer hour = getAngleDTO.getHour(); final Integer minutes = getAngleDTO.getMinutes(); final Calendar calendar = ClockUtils.getCalendar(hour, minutes); final double angle = ClockUtils.getClockAngle(calendar); return new GetAngleResponseDTO(angle); } }
d21284c7dfc20ed01cecddef6a10147c7c2f814d
[ "Java" ]
3
Java
Ph3anor/ClockAngle
8c7b0b007acbf86bd9629b8069e65e7db798e4ea
5ca114f545d652e9550049dc322693bb1fb20dcd
refs/heads/master
<repo_name>azakuanov/Python-for-Testers<file_sep>/data/contacts.py from model.contact import Contact testdata = [ Contact(firstname="name1", middlename="footer1", lastname="header1"), Contact(firstname="name2", middlename="footer2", lastname="header2") ] <file_sep>/test/test_add_group.py from model.group import Group def test_add_group(app, db, json_test, check_ui): group = json_test old_groups = db.get_group_list() app.group.create_new_group(group) assert len(old_groups) + 1 == app.group.count() new_groups = db.get_group_list() old_groups.append(group) assert sorted(old_groups, key=Group.id_or_max) == sorted(new_groups, key=Group.id_or_max) if check_ui: #assert new_groups == app.group.get_group_list assert sorted(new_groups, key = Group.id_or_max) == sorted(app.group.get_group_list(), key = Group.id_or_max) #def test_add_empty_group(app): # old_groups = app.group.get_group_list() # group = Group(name = "", header = "", footer = "") # app.group.create_new_group(group) #new_groups = app.group.get_group_list() # assert len(old_groups) + 1 == len(new_groups) # old_groups.append(group) # assert sorted(old_groups, key=Group.id_or_max) == sorted(new_groups, key=Group.id_or_max) <file_sep>/test/test_modify_group.py from model.group import Group from random import randrange from model.group import Group def test_modify_group_name(app, db, check_ui): old_groups = db.get_group_list() if app.group.count() == 0: app.group.create_new_group(Group(name="firstgroup", header = "jj")) index = randrange (len(old_groups)) group = Group(name ="ModifiedName") group.id = old_groups[index].id app.group.modify_group_by_index(index, group) new_groups = db.get_group_list() assert len(old_groups) == len(new_groups) old_groups[index] = group #assert sorted(old_groups, key=Group.id_or_max) == sorted(new_groups, key=Group.id_or_max) if check_ui: assert new_groups == app.group.get_group_list assert sorted(new_groups, key = Group.id_or_max) == sorted(app.group.get_group_list(), key = Group.id_or_max) def test_modify_group_header(app, db): if app.group.count() == 0: app.group.create_new_group(Group(name="firstgroup", header = "jj")) old_groups = db.get_group_list() index = randrange (len(old_groups)) group =Group(header ="ModifiedHeader") app.group.modify_group_by_index(index, group) new_groups = db.get_group_list() assert len(old_groups) == len(new_groups) <file_sep>/musor/README.md # Python-for-Testers <file_sep>/test/test_modify_contact.py from model.contact import Contact from random import randrange def test_modify_contact(app, db, check_ui): old_contacts = db.get_contact_list() if app.contact.count() == 0: app.contact.add_contact(Contact(firstname="firstgroup", middlename = "jj")) index = randrange (len(old_contacts)) contact = Contact(firstname = "ModifyFerst", middlename="Modifymiddle", lastname ="Modifylast", nickname ="ModifyNick", title = "ModifyQa engineer", company = "Modifystartpack", address = "Modifyrandom addres") contact.id = old_contacts[index].id app.contact.modify_contact_by_index(index, contact) new_contacts = db.get_contact_list() assert len(old_contacts) == len(new_contacts) old_contacts[index] = contact print(sorted(old_contacts, key=Contact.id_or_max)) print(sorted(new_contacts, key=Contact.id_or_max)) assert len(old_contacts) == len(new_contacts) if check_ui: #assert new_groups == app.group.get_group_list assert sorted(new_contacts, key = Contact.id_or_max) == sorted(app.group.get_group_list(), key = Contact.id_or_max) #assert sorted(old_contacts, key=Contact.id_or_max) == sorted(new_contacts, key=Contact.id_or_max) <file_sep>/check_db_connector.py import mysql.connector from fixture.db import DbFixture db = DbFixture(host="127.0.0.1", name = "addressbook", user = "root", password="") try: l = db.get_contact_list() for intem in l: print (intem) print (len(l)) finally: pass #db.destroy() <file_sep>/musor/hello_world_x_5.py def print_smth (name): print(name * 5) print_smth("vsem Privet!")<file_sep>/musor/privet_nv.py def print_smth (name): print(name * 5) print_smth("a tee from starbucks") <file_sep>/test/test_db_matches_ui.py from model.group import Group from model.contact import Contact from timeit import timeit def test_group_list(app, db): print(timeit(lambda: app.group.get_group_list(), number = 1)) def clean(group): return Group(id = group.id, name = group.name.strip()) print(timeit(lambda: map(clean, db.get_group_list()), number = 1000)) assert False #sorted(ui_list, key=Group.id_or_max) == sorted(db_list, key=Group.id_or_max) #def test_contact_list(app, db): # ui_list = app.contact.get_contact_list() # def clean(contact): # return Contact(id = contact.id, firstname = contact.firstname.strip()) #db_list = map(clean, db.get_contact_list()) #print (sorted(ui_list, key=Group.id_or_max)) #print (sorted(db_list, key=Group.id_or_max)) #assert sorted(ui_list, key=Contact.id_or_max) == sorted(db_list, key=Contact.id_or_max) <file_sep>/test/test_add_contact.py from model.contact import Contact import pytest from data.contacts import testdata import random import string def test_test_add_contact(app, json_contacts, db, check_ui): contact = json_contacts old_contacts = db.get_contact_list() app.contact.add_contact(contact) new_contacts = db.get_contact_list() assert len(old_contacts) + 1 == len(new_contacts) old_contacts.append(contact) if check_ui: #assert new_groups == app.group.get_group_list assert sorted(new_contacts, key = Contact.id_or_max) == sorted(app.contact.get_group_list(), key = Contact.id_or_max) #assert sorted(old_contacts, key=Contact.id_or_max) == sorted(new_contacts, key=Contact.id_or_max) <file_sep>/data/add_contact.py from model.contact import Contact import random import string def random_string (prefix, maxlen): symbols = string.ascii_letters + string.digits + " "*10 return prefix + "".join([random.choice(symbols) for i in range( random.randrange(maxlen))]) test_data = [Contact(firstname = "", middlename = "", lastname = "")] + [ Contact(firstname = random_string("firstname", 10), middlename = random_string("middlename", 20), lastname = random_string("lastname", 20)) for i in range(5) ] <file_sep>/test/test_delete_contact.py from model.contact import Contact from random import randrange def test_del_contact(app, db, check_ui): if app.contact.count() == 0: app.contact.add_contact(Contact(firstname="firstgroup", middlename = "jj")) old_contacts = db.get_contact_list() index = randrange (len(old_contacts)) app.contact.delete_contact_by_index(index) new_contacts = db.get_contact_list() assert len(old_contacts) == len(new_contacts) #old_contacts[index:index +1] = [] assert old_contacts == new_contacts if check_ui: #assert new_groups == app.group.get_group_list assert sorted(new_contacts, key = Contact.id_or_max) == sorted(app.contact.get_contact_list(), key = Contact.id_or_max)
b118745d41cae9dd3749af6cb5cd414a4c0b1eba
[ "Markdown", "Python" ]
12
Python
azakuanov/Python-for-Testers
22ef0c3138e6e73721915263855da263d8dbb424
f9094c633eee50b1dd2cfb817981b32f4067b78b
refs/heads/master
<repo_name>mayah/pfbase<file_sep>/README.md pfbase ====== Simple Play! framework application only having login features.<file_sep>/app/assets/javascripts/controllers.js var app = angular.module('app', ['ui.router']); app.config(['$stateProvider', '$locationProvider', '$urlRouterProvider', '$httpProvider', function($stateProvider, $locationProvider, $urlRouterProvider, $httpProvider) { $locationProvider.html5Mode(true).hashPrefix('!'); // --- Adds states. $stateProvider.state({ name: 'top', templateUrl: '/assets/htmls/top.html' }); $stateProvider.state({ name: 'home', url: '/', parent: 'top', templateUrl: '/assets/htmls/index.html', controller: 'indexController' }); $stateProvider.state({ name: 'userCreate', url: '/users/create', templateUrl: '/assets/htmls/users/create.html', controller: 'userCreateController' }); $stateProvider.state({ name: 'checkLogin', url: '/checkLogin', templateUrl: '/assets/htmls/checkLogin.html', controller: 'checkLoginController' }); $stateProvider.state({ name: 'loginRequired', url: '/loginRequired?redirectURL', templateUrl: '/assets/htmls/loginRequired.html' }); $stateProvider.state({ name: 'notFound', url: '/*all', templateUrl: '/assets/htmls/notfound.html' }); // --- Adds global response interceptor. $httpProvider.interceptors.push(['$q', '$location', function($q, $location) { return { 'responseError': function(response) { // Checks response.status for global error handling. switch (response.status) { case 401: // UNAUTHORIZED var newURL = '/loginRequired?redirectURL=' + encodeURIComponent($location.url()); $location.url(newURL); break; default: break; } return $q.reject(response); } };}]); }]); // ---------------------------------------------------------------------- // appController app.controller('appController', ['$scope', '$http', function($scope, $http) { $scope.setLoginUser = function(user) { $scope.loginUser = user; } $scope.logout = function() { var args = { sessionToken: window.sessionToken }; $http.post('/api/auth/logout', args).success(function(json) { location.href = '/'; }).error(function(json) { console.log(json); }); } if (window.loginUser) { $scope.setLoginUser(window.loginUser); } }]); // ---------------------------------------------------------------------- // IndexController app.controller('indexController', ['$scope', '$http', function($scope, $http) { }]); // ---------------------------------------------------------------------- // UserCreateController app.controller('userCreateController', ['$scope', '$http', function($scope, $http) { $scope.submit = function() { if ($scope.password != $scope.confirmation) { alert('パスワードが一致していません。'); return; } var args = { email: $scope.email, loginId: $scope.loginId, nickname: $scope.nickname, password: $<PASSWORD>, sessionToken: window.sessionToken }; $http.post('/api/users/create', args).success(function(json) { location.href = '/'; }).error(function(json) { console.log(json); alert('Failed'); }); } }]); // ---------------------------------------------------------------------- // Check Login Page app.controller('checkLoginController', ['$scope', '$http', function($scope, $http) { $http.get('/api/demo/checkLogin').success(function(json) { $scope.login = 'OK'; }).error(function(response) { console.log(response); $scope.login = 'NG'; }); }]); // ---------------------------------------------------------------------- // Error pages // ---------------------------------------------------------------------- // Login app.controller('loginFormController', ['$scope', '$http', function($scope, $http) { $scope.submit = function() { var args = { email: $scope.email, password: <PASSWORD>, rememberMe: $scope.rememberMe, sessionToken: sessionToken }; $http.post('/api/auth/login', args).success(function(json) { console.log(json); window.loginUser = json.user; window.sessionToken = json.sessionToken; $scope.setLoginUser(json.user); }).error(function(json) { alert('NG'); console.log(json); }); } }]); <file_sep>/conf/evolutions/default/1.sql # Creates PARTAKE configuration table. # --- !Ups CREATE TABLE Users( id UUID PRIMARY KEY, loginId VARCHAR(16) NOT NULL, nickname VARCHAR(16) NOT NULL, email VARCHAR(256) NOT NULL, hashedPassword VARCHAR(256) NOT NULL, createdAt TIMESTAMP NOT NULL ); CREATE UNIQUE INDEX NicknameOnUsers ON Users(nickname); CREATE UNIQUE INDEX EmailOnUsers ON Users(email); # --- !Downs DROP TABLE IF EXISTS Users;
db018e640925a6e414eef50782a878298fbaa9d5
[ "Markdown", "SQL", "JavaScript" ]
3
Markdown
mayah/pfbase
977eb67c10226bb7adc4f5d54331d5143919574b
cb7a926359c3493492605392ac8119f7aa68ea0a
refs/heads/master
<repo_name>neoribello/jungle-rails<file_sep>/spec/models/user_spec.rb require 'rails_helper' RSpec.describe User, type: :model do describe 'Validations' do # validation examples here it "should have all fields present" do user = User.create(name: "<NAME>", email: "<EMAIL>", password: "123", password_confirmation: "123") expect(user).to be_valid end it "should have a password" do user = User.create(name: "<NAME>", email: "<EMAIL>", password_confirmation: "123") expect(user).to_not be_valid expect(user.errors.full_messages).to include 'Password can\'t be blank' end it "should have a password confirmation" do user = User.create(name: "<NAME>", email: "<EMAIL>", password: "123") expect(user).to_not be_valid expect(user.errors.full_messages).to include 'Password confirmation can\'t be blank' end it "should password and password_confirmation match" do user = User.create(name: "<NAME>", email: "<EMAIL>", password: "123", password_confirmation: "<PASSWORD>") expect(user).to_not be_valid expect(user.errors.full_messages).to include 'Password confirmation doesn\'t match Password' end end it "should check that email is unique" do user1 = User.create(name: "<NAME>", email: "<EMAIL>", password: "123", password_confirmation: "123") user2 = User.create(name: "<NAME>", email: "<EMAIL>", password: "123", password_confirmation: "123") expect(user2).to_not be_valid end it "should have a name" do user = User.create(name: nil, email: "<EMAIL>", password: "123", password_confirmation: "123") expect(user).to_not be_valid expect(user.errors.full_messages).to include 'Name can\'t be blank' end it "should have an email" do user = User.create(name: "<NAME>", email: nil, password: "123", password_confirmation: "123") expect(user).to_not be_valid expect(user.errors.full_messages).to include 'Email can\'t be blank' end it "should have the right password length" do user = User.create(name: "<NAME>", email: "<EMAIL>", password: "12", password_confirmation: "12") expect(user).to_not be_valid expect(user.errors.full_messages).to include 'Password is too short (minimum is 3 characters)' end describe '.authenticate_with_credentials' do # examples for this class method here it 'returns a user with valid credentials' do @user1 = User.create(name: "<NAME>", email: "<EMAIL>", password: "123", password_confirmation: "123") user = User.authenticate_with_credentials('<EMAIL>', '123') expect(user).to be_an_instance_of(User) end it 'returns a user with upper and lower case characters' do @user1 = User.create(name: "<NAME>", email: "<EMAIL>", password: "123", password_confirmation: "123") user = User.authenticate_with_credentials('<EMAIL>', '123') expect(user).to be_an_instance_of(User) end it 'returns a user with trailing whitespaces' do @user1 = User.create(name: "<NAME>", email: "<EMAIL>", password: "123", password_confirmation: "123") user = User.authenticate_with_credentials(' <EMAIL> ', '123') expect(user).to be_an_instance_of(User) end end end<file_sep>/spec/models/product_spec.rb require 'rails_helper' RSpec.describe Product, type: :model do describe 'Validations' do # validation tests/examples here @category = Category.create(name: "Shoes") it "should have all fields present" do product = Product.create( :name => 'adidas', :price => 300, :quantity => 1, :category => @category ) end it "should have a name" do product = Product.create( :name => nil, :price => 300, :quantity => 1, :category => @category ) expect(product).to_not be_valid expect(product.errors.full_messages).to include 'Name can\'t be blank' end it "should have a price" do product = Product.create( :name => 'yeezy', :price => nil, :quantity => 1, :category => @category ) expect(product).to_not be_valid expect(product.errors.full_messages).to include 'Price can\'t be blank' end it "should have a quantiy" do product = Product.create( :name => 'yeezy', :price => 300, :quantity => nil, :category => @category ) expect(product).to_not be_valid expect(product.errors.full_messages).to include 'Quantity can\'t be blank' end it "should have a category" do product = Product.create( :name => 'yeezy', :price => 300, :quantity => 1, :category => nil ) expect(product).to_not be_valid expect(product.errors.full_messages).to include 'Category can\'t be blank' end end end
123db054644a1ae5566e300f7c27421e49b0c24f
[ "Ruby" ]
2
Ruby
neoribello/jungle-rails
c16daaa8c1661bba2afc0d9d79eee17f6260da52
97863912279928efba4a188c640d59d4ef57680c
refs/heads/master
<file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace PMMP { /// <summary> /// /// </summary> public class TaskItem { public int ID { get; set; } public string UniqueID { get; set; } public string DrivingPath { get; set; } public string Task { get; set; } public string Duration { get; set; } public string Predecessor { get; set; } public DateTime? Start { get; set; } public DateTime? Finish { get; set; } public DateTime? BaseLineStart { get; set; } public DateTime? BaseLineFinish { get; set; } public DateTime? Deadline { get; set; } public DateTime? ModifiedOn { get; set; } public string[] ShowOn { get; set; } public int WorkCompletePercentage { get; set; } public string TotalSlack { get; set; } public string BLDuration {get;set;} public string Hours { get; set; } public string CA { get; set; } public DateTime? EstFinish { get; set; } public DateTime? EstStart { get; set; } public string PMT { get; set; } public string ReasonRecovery { get; set; } } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using Microsoft.SharePoint; using Repository; using System.Data; using PMMP; using Constants = PMMP.Constants; using System.Collections.Specialized; using SvcProject; using SvcCustomFields; using System.Linq; namespace PMMP { public class TaskItemRepository { public static TaskGroupData GetTaskGroups(string projectUID) { Repository.Utility.WriteLog("GetTaskGroups started", System.Diagnostics.EventLogEntryType.Information); IList<TaskItemGroup> retVal = new List<TaskItemGroup>(); CustomFieldDataSet customFieldDataSet = DataRepository.ReadCustomFields(); DataAccess dataAccess = new Repository.DataAccess(new Guid(projectUID)); DataSet dataset = dataAccess.ReadProject(null); ProjectDataSet ds = DataRepository.ReadProject(new Guid(projectUID)); DataTable tasksDataTable = dataset.Tables["Task"]; Dictionary<string, IList<TaskItem>> ChartsData = GetChartsData(tasksDataTable, customFieldDataSet); TaskGroupData taskData = new TaskGroupData(); DateTime? projectStatusDate = GetProjectCurrentDate(new Guid(projectUID), ds); FiscalUnit fiscalPeriod = DataRepository.GetFiscalMonth(projectStatusDate); taskData.FiscalPeriod = fiscalPeriod; IList<TaskItemGroup> LateTasksData = GetLateTasksData(tasksDataTable, fiscalPeriod, customFieldDataSet); IList<TaskItemGroup> UpComingTasksData = GetupComingTasksData(tasksDataTable, fiscalPeriod, customFieldDataSet); taskData.TaskItemGroups = retVal; taskData.ChartsData = ChartsData; taskData.LateTaskGroups = LateTasksData; taskData.UpComingTaskGroups = UpComingTasksData; taskData.SPDLSTartToBL = GetSPDLSTartToBLData(new Guid(projectUID), ds); taskData.SPDLFinishToBL = GetSPDLFinishToBLData(new Guid(projectUID), ds); taskData.BEIData = GetBEIData(new Guid(projectUID), ds); if (tasksDataTable != null) { var dPaths = tasksDataTable.AsEnumerable().Where(t => !string.IsNullOrEmpty(t.Field<string>("TASK_DRIVINGPATH_ID"))).Select(t => t.Field<string>("TASK_DRIVINGPATH_ID")).Distinct(); var chartTypes = tasksDataTable.AsEnumerable().Select(t => t.Field<string>("CUSTOMFIELD_DESC")).Distinct(); ; foreach (string dPath in dPaths) { int taskCount = -1; var taskItemGroup = new TaskItemGroup { DrivingPath = dPath, TaskItems = new List<TaskItem>() }; string previousTitle = string.Empty; Dictionary<string, string> dictTitle = new Dictionary<string, string>(); int totalUnCompletedtaskCount = 0, totalCompletedTaskCount = 0; List<TaskItem> chartItems = new List<TaskItem>(); List<TaskItemGroup> completedTasks = new List<TaskItemGroup>(); EnumerableRowCollection<DataRow> collection = tasksDataTable.AsEnumerable().Where(t => t.Field<string>("TASK_DRIVINGPATH_ID") != null && t.Field<string>("TASK_DRIVINGPATH_ID").Split(",".ToCharArray()).Contains(dPath)); int completedTaskCount = -1; //DateTime? lastUpdate = GetLastUpdateDate(); TaskItemGroup completedTaskItemGroup = new TaskItemGroup { DrivingPath = dPath, TaskItems = new List<TaskItem>() }; foreach (DataRow item in collection) { if (item["TASK_DEADLINE"] != System.DBNull.Value && !string.IsNullOrEmpty(item["TASK_DEADLINE"].ToString())) { if (!dictTitle.ContainsKey(dPath.Split(",".ToCharArray())[0])) { dictTitle.Add(dPath.Split(",".ToCharArray())[0], item["TASK_NAME"].ToString()); } } if (item["CUSTOMFIELD_DESC"] != null) { chartItems.Add(BuildTaskItem(dPath, item, customFieldDataSet)); } if (!string.IsNullOrEmpty(item["TASK_ACT_FINISH"].ToString()) && (Convert.ToDateTime(item["TASK_ACT_FINISH"].ToString())).InCurrentFiscalMonth(fiscalPeriod)) { totalCompletedTaskCount++; completedTaskCount++; if (completedTaskCount == 10) { completedTasks.Add(completedTaskItemGroup); completedTaskItemGroup = new TaskItemGroup { DrivingPath = dPath, TaskItems = new List<TaskItem>() }; completedTaskCount = 0; completedTaskItemGroup.TaskItems.Add(BuildTaskItem(dPath, item, customFieldDataSet)); } else { completedTaskItemGroup.TaskItems.Add(BuildTaskItem(dPath, item, customFieldDataSet)); } } else { if (item["TASK_PCT_COMP"] != null && (Convert.ToInt32(item["TASK_PCT_COMP"].ToString().Trim().Trim("%".ToCharArray()).Trim()) < 100)) { totalUnCompletedtaskCount++; taskCount++; if (taskCount == 10) { retVal.Add(taskItemGroup); taskItemGroup = new TaskItemGroup { DrivingPath = dPath, TaskItems = new List<TaskItem>() }; taskItemGroup.Title = previousTitle; taskCount = 0; taskItemGroup.TaskItems.Add(BuildTaskItem(dPath, item, customFieldDataSet)); } else { taskItemGroup.TaskItems.Add(BuildTaskItem(dPath, item, customFieldDataSet)); } } } } if (totalUnCompletedtaskCount % 10 != 0) { retVal.Add(taskItemGroup); } if (totalCompletedTaskCount % 10 != 0) { completedTasks.Add(completedTaskItemGroup); if (totalUnCompletedtaskCount == 0) { retVal.Add(taskItemGroup); } } if (taskItemGroup.TaskItems.Count > 0 || (completedTasks.Count > 0 && completedTasks[0].TaskItems != null && completedTasks[0].TaskItems.Count > 0)) { taskItemGroup.CompletedTaskgroups = completedTasks; taskItemGroup.ChartTaskItems = chartItems; taskItemGroup.Charts = new string[chartTypes.Count()]; chartTypes.ToList().CopyTo(taskItemGroup.Charts, 0); taskItemGroup.Title = dictTitle.ContainsKey(dPath) ? dictTitle[dPath] : "Driving Path template"; } if (dPath != null && dictTitle.ContainsKey(dPath.Split(",".ToCharArray())[0])) { foreach (TaskItemGroup group in retVal) { if (group.DrivingPath == dPath) { group.Title = dictTitle[dPath.Split(",".ToCharArray())[0]]; } if (group.CompletedTaskgroups != null) { foreach (TaskItemGroup completedGroup in group.CompletedTaskgroups) { completedGroup.Title = dictTitle[dPath.Split(",".ToCharArray())[0]]; } } } } } } Repository.Utility.WriteLog("GetTaskGroups completed successfully", System.Diagnostics.EventLogEntryType.Information); return taskData; } private static List<GraphDataGroup> GetSPDLSTartToBLData(Guid projectUID, ProjectDataSet projectDataSet) { List<GraphDataGroup> group = new List<GraphDataGroup>(); DateTime? projectStatusDate = GetProjectCurrentDate(projectUID, projectDataSet); if (!projectStatusDate.HasValue) return new List<GraphDataGroup>(); List<FiscalUnit> projectStatusPeriods = GetProjectStatusPeriods(projectStatusDate.Value); IEnumerable<ProjectDataSet.TaskRow> tasks = projectDataSet.Task.Where(t => t.TASK_IS_SUMMARY == false && !t.IsTASK_DURNull() && t.TASK_DUR > 0); //Get CS Data List<GraphData> graphDataCS = new List<GraphData>(); foreach (FiscalUnit unit in projectStatusPeriods) { int count = tasks.Count(t => !t.IsTASK_ACT_STARTNull() && t.TASK_ACT_START >= unit.From && t.TASK_ACT_START <= unit.To); graphDataCS.Add(new GraphData() { Count = count, Title = unit.GetTitle() }); } group.Add(new GraphDataGroup() { Type = "CS", Data = graphDataCS }); //Get FCS Data List<GraphData> graphDataFCS = new List<GraphData>(); foreach (FiscalUnit unit in projectStatusPeriods) { int count = tasks.Count(t => !t.IsTASK_START_DATENull() && t.TASK_START_DATE >= unit.From && t.TASK_START_DATE <= unit.To && t.IsTASK_ACT_STARTNull() && t.TASK_PCT_COMP == 0); graphDataFCS.Add(new GraphData() { Count = count, Title = unit.GetTitle() }); } group.Add(new GraphDataGroup() { Type = "FCS", Data = graphDataFCS }); //Get DQ Data List<GraphData> graphDataDQ = new List<GraphData>(); foreach (FiscalUnit unit in projectStatusPeriods) { int count = tasks.Count(t => !t.IsTASK_START_DATENull() && !t.IsTB_STARTNull() && t.TB_START >= unit.From && t.TB_START <= unit.To && t.TASK_START_DATE > t.TB_START); graphDataDQ.Add(new GraphData() { Count = count, Title = unit.GetTitle() }); } group.Add(new GraphDataGroup() { Type = "DQ", Data = graphDataDQ }); //Get FDQ Data List<GraphData> graphDataFDQ = new List<GraphData>(); foreach (FiscalUnit unit in projectStatusPeriods) { int count = tasks.Count(t => !t.IsTASK_START_DATENull() && !t.IsTB_STARTNull() && t.TB_START >= unit.From && t.TB_START <= unit.To && t.TASK_START_DATE > t.TB_START && t.TASK_PCT_COMP == 0); graphDataFDQ.Add(new GraphData() { Count = count, Title = unit.GetTitle() }); } group.Add(new GraphDataGroup() { Type = "FDQ", Data = graphDataFDQ }); //Get CDQ Data List<GraphData> graphDataCDQ = new List<GraphData>(); foreach (FiscalUnit unit in projectStatusPeriods) { int count = tasks.Count(t => !t.IsTB_STARTNull() && t.TB_START <= projectStatusDate && t.TB_START >= unit.From && t.TB_START <= unit.To && t.IsTASK_ACT_STARTNull()); graphDataCDQ.Add(new GraphData() { Count = 0, Title = unit.GetTitle() }); } group.Add(new GraphDataGroup() { Type = "CDQ", Data = graphDataCDQ }); //Get FCDQ Data List<GraphData> graphDataFCDQ = new List<GraphData>(); foreach (FiscalUnit unit in projectStatusPeriods) { int count = tasks.Count(t => !t.IsTASK_START_DATENull() && !t.IsTB_STARTNull() && t.TASK_START_DATE > projectStatusDate && t.TASK_START_DATE >= unit.From && t.TASK_START_DATE <= unit.To && t.TASK_START_DATE > t.TB_START); graphDataFCDQ.Add(new GraphData() { Count = 0, Title = unit.GetTitle() }); } group.Add(new GraphDataGroup() { Type = "FCDQ", Data = graphDataFCDQ }); return group; } private static List<GraphDataGroup> GetSPDLFinishToBLData(Guid projectUID, ProjectDataSet projectDataSet) { List<GraphDataGroup> group = new List<GraphDataGroup>(); DateTime? projectStatusDate = GetProjectCurrentDate(projectUID, projectDataSet); List<FiscalUnit> projectStatusPeriods = GetProjectStatusPeriods(projectStatusDate); IEnumerable<ProjectDataSet.TaskRow> tasks = projectDataSet.Task.Where(t => t.TASK_IS_SUMMARY == false && !t.IsTASK_DURNull() && t.TASK_DUR > 0); //Get CS Data List<GraphData> graphDataCS = new List<GraphData>(); foreach (FiscalUnit unit in projectStatusPeriods) { int count = tasks.Count(t => !t.IsTASK_ACT_FINISHNull() && t.TASK_ACT_FINISH >= unit.From && t.TASK_ACT_FINISH <= unit.To); graphDataCS.Add(new GraphData() { Count = count, Title = unit.GetTitle() }); } group.Add(new GraphDataGroup() { Type = "CF", Data = graphDataCS }); //Get FCS Data List<GraphData> graphDataFCS = new List<GraphData>(); foreach (FiscalUnit unit in projectStatusPeriods) { int count = tasks.Count(t => !t.IsTASK_FINISH_DATENull() && t.TASK_FINISH_DATE >= unit.From && t.TASK_FINISH_DATE <= unit.To && t.IsTASK_ACT_FINISHNull() && t.TASK_PCT_COMP < 100); graphDataFCS.Add(new GraphData() { Count = count, Title = unit.GetTitle() }); } group.Add(new GraphDataGroup() { Type = "FCF", Data = graphDataFCS }); //Get DQ Data List<GraphData> graphDataDQ = new List<GraphData>(); foreach (FiscalUnit unit in projectStatusPeriods) { int count = tasks.Count(t => !t.IsTASK_FINISH_DATENull() && !t.IsTB_FINISHNull() && t.TB_FINISH >= unit.From && t.TB_FINISH <= unit.To && t.TASK_FINISH_DATE > t.TB_FINISH); graphDataDQ.Add(new GraphData() { Count = count, Title = unit.GetTitle() }); } group.Add(new GraphDataGroup() { Type = "DQF", Data = graphDataDQ }); //Get FDQ Data List<GraphData> graphDataFDQ = new List<GraphData>(); foreach (FiscalUnit unit in projectStatusPeriods) { int count = tasks.Count(t => !t.IsTASK_FINISH_DATENull() && t.TASK_FINISH_DATE > projectStatusDate && !t.IsTB_FINISHNull() && t.TB_FINISH >= unit.From && t.TB_FINISH <= unit.To && t.TASK_FINISH_DATE > t.TB_FINISH && t.TASK_PCT_COMP < 100); graphDataFDQ.Add(new GraphData() { Count = count, Title = unit.GetTitle() }); } group.Add(new GraphDataGroup() { Type = "FDQF", Data = graphDataFDQ }); //Get CDQ Data List<GraphData> graphDataCDQ = new List<GraphData>(); foreach (FiscalUnit unit in projectStatusPeriods) { int count = tasks.Count(t => !t.IsTB_FINISHNull() && t.TB_FINISH <= projectStatusDate && t.TB_FINISH >= unit.From && t.TB_FINISH <= unit.To && t.IsTASK_ACT_FINISHNull()); graphDataCDQ.Add(new GraphData() { Count = 0, Title = unit.GetTitle() }); } group.Add(new GraphDataGroup() { Type = "CDQF", Data = graphDataCDQ }); //Get FCDQ Data List<GraphData> graphDataFCDQ = new List<GraphData>(); foreach (FiscalUnit unit in projectStatusPeriods) { int count = tasks.Count(t => !t.IsTASK_FINISH_DATENull() && !t.IsTB_FINISHNull() && t.TASK_FINISH_DATE > projectStatusDate && t.TASK_FINISH_DATE >= unit.From && t.TASK_FINISH_DATE <= unit.To && t.TASK_FINISH_DATE > t.TB_FINISH); graphDataFCDQ.Add(new GraphData() { Count = 0, Title = unit.GetTitle() }); } group.Add(new GraphDataGroup() { Type = "FCDQF", Data = graphDataFCDQ }); return group; } private static List<GraphDataGroup> GetBEIData(Guid projectUID, ProjectDataSet projectDataSet) { List<GraphDataGroup> group = new List<GraphDataGroup>(); DateTime? projectStatusDate = GetProjectCurrentDate(projectUID, projectDataSet); List<FiscalUnit> projectStatusPeriods = GetProjectStatusWeekPeriods(projectStatusDate); IEnumerable<ProjectDataSet.TaskRow> tasks = projectDataSet.Task.Where(t => t.TASK_IS_SUMMARY == false && !t.IsTASK_DURNull() && t.TASK_DUR > 0); //Get BEIStart Data List<GraphData> graphDataBES = new List<GraphData>(); foreach (FiscalUnit unit in projectStatusPeriods) { int totalStart = tasks.Count(t => !t.IsTASK_ACT_STARTNull() && t.TASK_ACT_START >= unit.From && t.TASK_ACT_START <= unit.To); int totalTBStart = tasks.Count(t => !t.IsTB_STARTNull() && t.TB_START >= unit.From && t.TB_START <= unit.To); if (totalTBStart != 0) { graphDataBES.Add(new GraphData() { Count = totalStart / totalTBStart, Title = unit.GetTitle() }); } else { graphDataBES.Add(new GraphData() { Count = 0, Title = unit.GetTitle() }); } } group.Add(new GraphDataGroup() { Type = "BES", Data = graphDataBES }); //Get BEIFinish Data List<GraphData> graphDataBEF = new List<GraphData>(); foreach (FiscalUnit unit in projectStatusPeriods) { int totalFinish = tasks.Count(t => !t.IsTASK_ACT_FINISHNull() && t.TASK_ACT_FINISH >= unit.From && t.TASK_ACT_FINISH <= unit.To); int totalTBFinish = tasks.Count(t => !t.IsTB_FINISHNull() && t.TB_FINISH >= unit.From && t.TB_FINISH <= unit.To); if (totalTBFinish != 0) { graphDataBEF.Add(new GraphData() { Count = totalFinish / totalTBFinish, Title = unit.GetTitle() }); } else { graphDataBEF.Add(new GraphData() { Count = 0, Title = unit.GetTitle() }); } } group.Add(new GraphDataGroup() { Type = "BEF", Data = graphDataBEF }); //Get BEI Forecast Start Data List<GraphData> graphDataBEFS = new List<GraphData>(); foreach (FiscalUnit unit in projectStatusPeriods) { int totalStart = tasks.Count(t => !t.IsTASK_START_DATENull() && !t.IsTASK_PCT_COMPNull() && t.TASK_START_DATE >= unit.From && t.TASK_START_DATE <= unit.To && t.TASK_PCT_COMP == 0); int totalTBStart = tasks.Count(t => !t.IsTB_STARTNull() && t.TB_START >= unit.From && t.TB_START <= unit.To); if (totalTBStart != 0) { graphDataBEFS.Add(new GraphData() { Count = totalStart / totalTBStart, Title = unit.GetTitle() }); } else { graphDataBEFS.Add(new GraphData() { Count = 0, Title = unit.GetTitle() }); } } group.Add(new GraphDataGroup() { Type = "BEFS", Data = graphDataBEFS }); //Get BEI Forecast Finish Data List<GraphData> graphDataBEFF = new List<GraphData>(); foreach (FiscalUnit unit in projectStatusPeriods) { int totalFinish = tasks.Count(t => !t.IsTASK_FINISH_DATENull() && !t.IsTASK_PCT_COMPNull() && t.TASK_FINISH_DATE >= unit.From && t.TASK_FINISH_DATE <= unit.To); int totalTBFinish = tasks.Count(t => !t.IsTB_FINISHNull() && t.TB_FINISH >= unit.From && t.TB_FINISH <= unit.To); if (totalTBFinish != 0) { graphDataBEFF.Add(new GraphData() { Count = totalFinish / totalTBFinish, Title = unit.GetTitle() }); } else { graphDataBEFF.Add(new GraphData() { Count = 0, Title = unit.GetTitle() }); } } group.Add(new GraphDataGroup() { Type = "BEFF", Data = graphDataBEFF }); return group; } private static List<FiscalUnit> GetProjectStatusWeekPeriods(DateTime? projectStatusDate) { DataAccess da = new DataAccess(Guid.Empty); return da.GetProjectStatusWeekPeriods(projectStatusDate); } private static List<FiscalUnit> GetProjectStatusPeriods(DateTime? date) { DataAccess da = new DataAccess(Guid.Empty); return da.GetProjectStatusPeriods(date); } private static DateTime? GetProjectCurrentDate(Guid projectUID, ProjectDataSet projectDataSet) { DataAccess da = new DataAccess(projectUID); return da.GetProjectCurrentDate(projectDataSet, projectUID); } private static IList<TaskItemGroup> GetLateTasksData(DataTable tasksDataTable, FiscalUnit month, CustomFieldDataSet dataSet) { if (month.From == DateTime.MinValue && month.To == DateTime.MaxValue) return new List<TaskItemGroup>(); Repository.Utility.WriteLog("GetLateTasksData started", System.Diagnostics.EventLogEntryType.Information); int count = -1; int lateTaskCount = 0; IList<TaskItemGroup> retVal = new List<TaskItemGroup>(); TaskItemGroup taskData = new TaskItemGroup() { TaskItems = new List<TaskItem>() }; IList<TaskItem> items = new List<TaskItem>(); EnumerableRowCollection<DataRow> collection = tasksDataTable.AsEnumerable() .Where((t => t.Field<bool>("TASK_IS_SUMMARY") == false && t.Field<int>("TASK_PCT_COMP") == 0 && t.Field<DateTime?>("TASK_START_DATE").HasValue && t.Field<DateTime?>("TB_START").HasValue && t.Field<DateTime?>("TB_START").Value.InCurrentFiscalMonth(month) && t.Field<int>("TASK_PCT_COMP") < 100 && t.Field<DateTime?>("TASK_START_DATE").Value.Date > t.Field<DateTime?>("TB_START").Value.Date)); List<DataRow> mergedCollection = collection.Union(tasksDataTable.AsEnumerable() .Where(t => t.Field<bool>("TASK_IS_SUMMARY") == false && t.Field<DateTime?>("TASK_FINISH_DATE").HasValue && t.Field<DateTime?>("TB_FINISH").HasValue && t.Field<DateTime?>("TB_FINISH").Value.InCurrentFiscalMonth(month) && t.Field<int>("TASK_PCT_COMP") < 100 && t.Field<DateTime?>("TASK_FINISH_DATE").Value.Date > t.Field<DateTime?>("TB_FINISH").Value.Date) ).ToList(); foreach (DataRow item in mergedCollection) { count++; lateTaskCount++; TaskItem taskItem = BuildTaskItem("", item, dataSet); if (count == 10) { retVal.Add(taskData); taskData = new TaskItemGroup { TaskItems = new List<TaskItem>() }; count = -1; taskData.TaskItems.Add(BuildTaskItem("", item, dataSet)); } else { taskData.TaskItems.Add(BuildTaskItem("", item, dataSet)); } } if (count % 10 != 0) { retVal.Add(taskData); } Repository.Utility.WriteLog("GetLateTasksData completed successfully", System.Diagnostics.EventLogEntryType.Information); return retVal; } private static IList<TaskItemGroup> GetupComingTasksData(DataTable tasksDataTable, FiscalUnit month, CustomFieldDataSet dataSet) { if (month.From == DateTime.MinValue && month.To == DateTime.MaxValue) return new List<TaskItemGroup>(); FiscalUnit fiscalUnit = new FiscalUnit() { From = month.From, To = month.To.AddMonths(1) }; Repository.Utility.WriteLog("GetupComingTasksData started", System.Diagnostics.EventLogEntryType.Information); int count = -1; int upComingTaskCount = 0; IList<TaskItemGroup> retVal = new List<TaskItemGroup>(); TaskItemGroup taskData = new TaskItemGroup() { TaskItems = new List<TaskItem>() }; IList<TaskItem> items = new List<TaskItem>(); EnumerableRowCollection<DataRow> collection = tasksDataTable.AsEnumerable() .Where((t => t.Field<bool>("TASK_IS_SUMMARY") == false && t.Field<int>("TASK_PCT_COMP") < 100 && t.Field<DateTime?>("TASK_FINISH_DATE").HasValue && t.Field<DateTime?>("TASK_FINISH_DATE").Value.InCurrentFiscalMonth(fiscalUnit) )).OrderBy(t => t.Field<int>("TASK_ID")); foreach (DataRow item in collection) { count++; upComingTaskCount++; TaskItem taskItem = BuildTaskItem("", item, dataSet); if (count == 10) { retVal.Add(taskData); taskData = new TaskItemGroup { TaskItems = new List<TaskItem>() }; count = -1; taskData.TaskItems.Add(BuildTaskItem("", item, dataSet)); } else { taskData.TaskItems.Add(BuildTaskItem("", item, dataSet)); } } if (count % 10 != 0) { retVal.Add(taskData); } Repository.Utility.WriteLog("GetupComingTasksData completed successfully", System.Diagnostics.EventLogEntryType.Information); return retVal; } private static Dictionary<string, IList<TaskItem>> GetChartsData(DataTable tasksDataTable, CustomFieldDataSet dataSet) { Repository.Utility.WriteLog("GetLateTasksData started", System.Diagnostics.EventLogEntryType.Information); Dictionary<string, IList<TaskItem>> chartsData = new Dictionary<string, IList<TaskItem>>(); var chartTypes = tasksDataTable.AsEnumerable().Select(t => t.Field<string>("CUSTOMFIELD_DESC")).Distinct(); foreach (string chartType in chartTypes) { if (!string.IsNullOrEmpty(chartType)) { foreach (string chartTypeItem in chartType.Split(",".ToCharArray())) { IList<TaskItem> items = new List<TaskItem>(); EnumerableRowCollection<DataRow> collection = tasksDataTable.AsEnumerable().Where(t => t.Field<string>("CUSTOMFIELD_DESC") != null && t.Field<string>("CUSTOMFIELD_DESC").Split(",".ToCharArray()).Contains(chartTypeItem)).OrderBy(t => t.Field<int>("TASK_ID")).OrderByDescending(t=>t.Field<int>("TASK_ID")); foreach (DataRow item in collection) { TaskItem taskItem = BuildTaskItem("", item, dataSet); items.Add(taskItem); } if (items.Count > 0) { if (!chartsData.ContainsKey(chartTypeItem)) { chartsData.Add(chartTypeItem, items); } } } } } Repository.Utility.WriteLog("GetChartsData completed successfully", System.Diagnostics.EventLogEntryType.Information); return chartsData; } private static TaskItem BuildTaskItem(string dPath, DataRow item, CustomFieldDataSet dataSet) { DateTime? estFinish = (DateTime?)DataHelper.GetValueFromCustomFieldTextOrDate(item, CustomFieldType.EstFinish, dataSet); DateTime? estStart = (DateTime?)DataHelper.GetValueFromCustomFieldTextOrDate(item, CustomFieldType.EstStart, dataSet); object objreason = DataHelper.GetValueFromCustomFieldTextOrDate(item, CustomFieldType.ReasonRecovery, dataSet); string reasonrecovery = objreason != null ? objreason.ToString() : ""; return new TaskItem { ID = DataHelper.GetValueAsInteger(item["TASK_ID"].ToString()), UniqueID = DataHelper.GetValue(item["TASK_UID".ToString()]), DrivingPath = dPath, Task = DataHelper.GetValue(item["TASK_NAME"].ToString()), Duration = DataHelper.GetValue(item["TASK_DUR"].ToString()), Predecessor = DataHelper.GetValue(item["TASK_PREDECESSORS"].ToString()), Start = DataHelper.GetValueAsDateTime(item["TASK_START_DATE"].ToString()), Finish = DataHelper.GetValueAsDateTime(item["TASK_FINISH_DATE"].ToString()), Deadline = DataHelper.GetValueAsDateTime(item["TASK_DEADLINE"].ToString()), ShowOn = DataHelper.GetValueFromMultiChoice(item["CUSTOMFIELD_DESC"].ToString(), CustomFieldType.ShowOn), CA = string.Join(",", DataHelper.GetValueFromMultiChoice(item["CUSTOMFIELD_DESC"].ToString(), CustomFieldType.CA)), EstFinish = estFinish, EstStart = estStart, PMT = string.Join(",", DataHelper.GetValueFromMultiChoice(item["CUSTOMFIELD_DESC"].ToString(), CustomFieldType.PMT)), ReasonRecovery = reasonrecovery, ModifiedOn = DataHelper.GetValueAsDateTime(item["TASK_MODIFIED_ON"].ToString()), WorkCompletePercentage = DataHelper.GetValueAsInteger(item["TASK_PCT_COMP"].ToString()), TotalSlack = DataHelper.GetValue(item["TASK_TOTAL_SLACK"].ToString()), BaseLineStart = DataHelper.GetValueAsDateTime(item["TB_START"].ToString()), BaseLineFinish = DataHelper.GetValueAsDateTime(item["TB_FINISH"].ToString()), Hours = DataHelper.GetValue(item["TASK_WORK"].ToString()), BLDuration = DataHelper.GetValue(item["TB_DUR"].ToString()) }; } } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace PMMP { public enum SlideType { Grid = 0, Chart =1, Completed = 2 } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using DocumentFormat.OpenXml.Drawing.Charts; using DocumentFormat.OpenXml.Packaging; namespace PMMP { public class BarChartUtilities { public static void LoadChartData(ChartPart chartPart, System.Data.DataTable dataTable) { Chart chart = chartPart.ChartSpace.Elements<Chart>().First(); BarChart bc = chart.Descendants<BarChart>().FirstOrDefault(); if (bc != null) { BarChartSeries bcs1 = bc.Elements<BarChartSeries>().FirstOrDefault(); BarChartSeries bcs2 = bc.Elements<BarChartSeries>().ElementAt(1); if (bcs1 != null && bcs2 != null) { var categories = bcs1.Descendants<DocumentFormat.OpenXml.Drawing.Charts.CategoryAxisData>().First(); StringReference csr = categories.Descendants<StringReference>().First(); csr.Formula.Text = String.Format("Sheet1!$A$2:$A${0}", dataTable.Rows.Count + 1); StringCache sc = categories.Descendants<StringCache>().First(); CreateStringPoints(sc, dataTable.Rows.Count - 1); //Series 1 var values1 = bcs1.Descendants<DocumentFormat.OpenXml.Drawing.Charts.Values>().First(); NumberReference vnr1 = values1.Descendants<NumberReference>().First(); vnr1.Formula.Text = String.Format("Sheet1!$B$2:$B${0}", dataTable.Rows.Count + 1); NumberingCache nc1 = values1.Descendants<NumberingCache>().First(); CreateNumericPoints(nc1, dataTable.Rows.Count - 1); //Series 2 var values2 = bcs2.Descendants<DocumentFormat.OpenXml.Drawing.Charts.Values>().First(); NumberReference vnr2 = values2.Descendants<NumberReference>().First(); vnr2.Formula.Text = String.Format("Sheet1!$C$2:$C${0}", dataTable.Rows.Count + 1); NumberingCache nc2 = values2.Descendants<NumberingCache>().First(); CreateNumericPoints(nc2, dataTable.Rows.Count - 1); for (int i = 0; i < dataTable.Rows.Count; i++) { NumericValue sv = sc.Elements<StringPoint>().ElementAt(i).Elements<NumericValue>().FirstOrDefault(); sv.Text = dataTable.Rows[i][0].ToString(); NumericValue nv1 = nc1.Elements<NumericPoint>().ElementAt(i).Elements<NumericValue>().FirstOrDefault(); nv1.Text = ((DateTime)dataTable.Rows[i][1]).ToOADate().ToString(); NumericValue nv2 = nc2.Elements<NumericPoint>().ElementAt(i).Elements<NumericValue>().FirstOrDefault(); nv2.Text = "10"; } } } } private static void CreateNumericPoints(NumberingCache nc, int count) { var np1 = nc.Elements<NumericPoint>().ElementAt(0); for (int i = 0; i < count; i++) { var npref = nc.Elements<NumericPoint>().ElementAt(i); var np = (NumericPoint)np1.Clone(); np.Index = (UInt32)i + 1; nc.InsertAfter(np, npref); } } private static void CreateStringPoints(StringCache sc, int count) { var sp1 = sc.Elements<StringPoint>().ElementAt(0); for (int i = 0; i < count; i++) { var spref = sc.Elements<StringPoint>().ElementAt(i); var sp = (StringPoint)sp1.Clone(); sp.Index = (UInt32)i + 1; sc.InsertAfter(sp, spref); } } } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace Repository { /// <summary> /// /// </summary> public class PSIDataSetFactory { public static IPSIDataSet GetPSISDataSet(string type) { switch (type) { case "Lookup": return new LookupPSIDataSet(); } return null; } } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.IO; using Repository; namespace PMMP { public class PMPDocument :IPMPDocument { public Stream CreateDocument(string template,byte[] fileName,string projectUID) { Utility.WriteLog("Create Document Started", System.Diagnostics.EventLogEntryType.Information); Stream stream = PresentationDocumentFactory.CreateDocument(template, fileName, projectUID); Utility.WriteLog("Create Document ompleted Successfully", System.Diagnostics.EventLogEntryType.Information); return stream; } } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using SvcQueueSystem; using SvcResource; using SvcCustomFields; using SvcLookupTable; using SvcProject; using Repository; using SvcAdmin; using System.Collections; using SvcArchive; using SvcCalendar; namespace PMMP { public class DataRepository { public static AdminClient adminClient; public static ArrayList adUsers; public static ArchiveClient archiveClient; public static bool autoLogin; public static CalendarClient calendarClient; public static CustomFieldsClient customFieldsClient; public static int formsPort; public static string impersonatedUserName; public static bool isImpersonated; public static bool isWindowsAuth; public static Guid jobGuid; public static int loginStatus; public static LookupTableClient lookupTableClient; public static MySettings mySettings; public static string password; public static ProjectClient projectClient; public static Guid projectGuid; public static string projectServerUrl; public static Guid pwaSiteId; public static QueueSystemClient queueSystemClient; public static ResourceClient resourceClient; public static bool useDefaultWindowsCredentials; public static string userName; public static bool waitForIndividualQueue; public static bool waitForQueue; public static int windowsPort; public DataRepository(); public static string CatchFaultException(System.ServiceModel.FaultException faultEx); public static void ClearImpersonation(); public static bool ConfigClientEndpoints(); public void LoadProjects(string url); public static bool P14Login(string projectserverURL); public static CustomFieldDataSet ReadCustomFields(); public static LookupTableDataSet ReadLookupTables(); public static ProjectDataSet ReadProject(Guid projectUID); public static ProjectDataSet ReadProjectsList(); public static string ReadTaskEntityUID(); public enum queryType { GroupAndName = 0, GroupAndDisplayName = 1, UserNameAndName = 2, UserNameandDisplayName = 3, } } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using Microsoft.SharePoint; using DocumentFormat.OpenXml.Packaging; using System.IO; using PMMP; using DocumentFormat.OpenXml.Spreadsheet; using System.Xml.Serialization; using System.Xml; using System.Data; using System.ComponentModel; using DocumentFormat.OpenXml; using System.Runtime.Serialization; using System.Runtime.Serialization.Formatters.Binary; using DocumentFormat.OpenXml.Drawing.Charts; namespace TestLoadProjects { class Program { // public CopyChartFromXlsx2Pptx(string SourceFile, string TargetFile, string targetppt) //{ // ChartPart chartPart; // ChartPart newChartPart; // //SlidePart slidepartbkMark = null; // string chartPartIdBookMark = null; // File.Copy(TargetFile, targetppt, true); // //Powerpoint document // using (OpenXmlPkg.PresentationDocument pptPackage = OpenXmlPkg.PresentationDocument.Open(targetppt, true)) // { // OpenXmlPkg.PresentationPart presentationPart = pptPackage.PresentationPart; // var secondSlidePart = pptPackage.PresentationPart.SlideParts.Skip(0).First(); // this will retrieve your second slide // chartPart = secondSlidePart.ChartParts.First(); // chartPartIdBookMark = secondSlidePart.GetIdOfPart(chartPart); // //Console.WriteLine("ID:"+chartPartIdBookMark.ToString()); // secondSlidePart.DeletePart(chartPart); // secondSlidePart.Slide.Save(); // newChartPart = secondSlidePart.AddNewPart<ChartPart>(chartPartIdBookMark); // ChartPart saveXlsChart = null; // using (SpreadsheetDocument xlsDocument = SpreadsheetDocument.Open(SourceFile.ToString(), true)) // { // WorkbookPart xlsbookpart = xlsDocument.WorkbookPart; // foreach (var worksheetPart in xlsDocument.WorkbookPart.WorksheetParts) // { // if (worksheetPart.DrawingsPart != null) // if (worksheetPart.DrawingsPart.ChartParts.Any()) // { // saveXlsChart = worksheetPart.DrawingsPart.ChartParts.First(); // } // } // newChartPart.FeedData(saveXlsChart.GetStream()); // //newChartPart.FeedData( // secondSlidePart.Slide.Save(); // xlsDocument.Close(); // pptPackage.Close(); // } // } //} static void Main(string[] args) { try { ChartPart saveXlsChart = null; using (Stream stream = new FileStream("POC1.pptx", FileMode.Open, FileAccess.ReadWrite, FileShare.ReadWrite)) { using (var oPDoc = PresentationDocument.Open(stream,true,new OpenSettings())) { var oPPart = oPDoc.PresentationPart; SlidePart chartSlidePart = oPPart.GetSlidePartsInOrder().ToList()[0]; if (chartSlidePart.ChartParts.ToList().Count > 0) { var chartPart = chartSlidePart.ChartParts.ToList()[0]; foreach (IdPartPair part in chartPart.Parts) { var spreadsheet = chartPart.GetPartById(part.RelationshipId) as EmbeddedPackagePart; if (spreadsheet != null) { using (var oSDoc = SpreadsheetDocument.Open(spreadsheet.GetStream(FileMode.OpenOrCreate, FileAccess.ReadWrite), true)) { var workSheetPart = oSDoc.WorkbookPart.GetPartsOfType<WorksheetPart>().FirstOrDefault(); var sheetData = workSheetPart.Worksheet.Elements<SheetData>().FirstOrDefault(); DocumentFormat.OpenXml.Spreadsheet.Row row = WorkbookUtilities.GetRow(sheetData, 3); Cell dataCell1 = WorkbookUtilities.GetCell(row, 3); if (dataCell1.DataType != null && dataCell1.DataType == CellValues.SharedString) dataCell1.DataType = CellValues.String; dataCell1.CellValue.Text = "10"; if (workSheetPart.DrawingsPart != null) if (workSheetPart.DrawingsPart.ChartParts.Any()) { saveXlsChart = workSheetPart.DrawingsPart.ChartParts.First(); } //chartPart.ChartSpace.ChildElements[2].ChildElements[1].InnerXml = saveXlsChart.ChartSpace.ChildElements[2].ChildElements[1].InnerXml; // chartPart.FeedData(saveXlsChart.GetStream()); //workSheetPart.Worksheet.Save(); //chartSlidePart.DeletePart(chartPart); //chartSlidePart.FeedData(oSDoc.WorkbookPart.GetStream()); } using (var oSDoc = SpreadsheetDocument.Open(spreadsheet.GetStream(FileMode.OpenOrCreate, FileAccess.ReadWrite), true)) { var workSheetPart = oSDoc.WorkbookPart.GetPartsOfType<WorksheetPart>().FirstOrDefault(); var sheetData = workSheetPart.Worksheet.Elements<SheetData>().FirstOrDefault(); //var newChartPart = chartSlidePart.AddNewPart<ChartPart>(chartPartIdBookMark); //newChartPart.FeedData(saveXlsChart.GetStream()); //chartSlidePart.Slide.Save(); //chartSlidePart.FeedData(oSDoc.WorkbookPart.GetStream()); } } foreach (SlideMasterPart master in oPPart.SlideMasterParts) { master.SlideMaster.Save(); } //chartPart.EmbeddedPackagePart.FeedData(spreadsheet.GetStream()); } chartSlidePart.Slide.Save(); // SaveStreamToFile // ("POC1.pptx",ms); } } } } catch (Exception ex) { Console.WriteLine("An exception occured and the exception message ={0}", ex.Message); } Console.ReadKey(); } //public static DataTable ToDataTable<T>(IList<T> data) //{ // PropertyDescriptorCollection props = // TypeDescriptor.GetProperties(typeof(T)); // DataTable table = new DataTable(); // for (int i = 0; i < props.Count; i++) // { // PropertyDescriptor prop = props[i]; // table.Columns.Add(prop.Name, prop.PropertyType); // } // object[] values = new object[props.Count]; // foreach (T item in data) // { // for (int i = 0; i < values.Length; i++) // { // values[i] = props[i].GetValue(item); // } // table.Rows.Add(values); // } // return table; //} //public static MemoryStream SerializeObject(DataTable ds)// for given List<object> //{ // try // { // byte[] data = null; // using (MemoryStream stream = new MemoryStream()) // { // IFormatter bf = new BinaryFormatter(); // ds.RemotingFormat = SerializationFormat.Binary; // bf.Serialize(stream, ds); // return stream; // } // } // catch (Exception e) { System.Console.WriteLine(e); return null; } //} } } <file_sep>using System; using System.Linq; using Microsoft.SharePoint; using System.IO; using DocumentFormat.OpenXml.Presentation; using DocumentFormat.OpenXml.Packaging; using DocumentFormat.OpenXml.Spreadsheet; using System.Collections.Generic; namespace PMMPresentation.Console { class Program { static void Main(string[] args) { try { //TaskItemRepository.UpdateTasksList("http://intranet.contoso.com/projectserver5", new Guid("{4c0680a4-5074-4c7e-b198-c5d30aae83bf}")); //Run(); } catch (Exception ex) { System.Console.WriteLine(String.Format("An exception has ocurred. Message: {0}. Stack Trace:{1}", ex.Message, ex.StackTrace)); System.Console.WriteLine("Press any key to exit"); System.Console.Read(); } } private static void Run() { var filePath = String.Format(@"{0}\Templates\{1}", Directory.GetCurrentDirectory().Replace(@"bin\Debug", String.Empty), Configuration.TemplateFile); var fs = File.OpenRead(filePath); var bytes = new byte[fs.Length]; fs.Read(bytes, 0, bytes.Length); fs.Close(); var ms = PresentationManager.CreateStatusReport(bytes); var newFilePath = String.Format(@"{0}\Output\Result.pptx", Directory.GetCurrentDirectory().Replace(@"bin\Debug", String.Empty)); var file = new FileStream(newFilePath, FileMode.Create, System.IO.FileAccess.Write); ms.WriteTo(file); file.Close(); ms.Close(); } } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Data; using System.Data.SqlClient; using SvcLookupTable; using System.ServiceModel; using WCFHelpers; using System.Diagnostics; namespace Repository { /// <summary> /// /// </summary> public class LookupPSIDataSet : IPSIDataSet { private const string RBS_CON_STRING = "RBSConnectionString"; private string connectionString; public LookupPSIDataSet() { try { connectionString = System.Configuration.ConfigurationManager.ConnectionStrings[RBS_CON_STRING].ConnectionString; } catch (Exception ex) { Utility.WriteLog("Connection string for ParallonRBSLoad not present in App Config. Please add one",EventLogEntryType.Error); throw ex; } } public DataSet GetDataSet() { try { //Read lookup tables from the project server DataSet ds = DataRepository.ReadLookupTables(); Utility.WriteLog("Get Data Set From project server succeeded", EventLogEntryType.Information); //Test GitHub Check in changes return ds; } catch(Exception ex) { Utility.WriteLog("Error in Reading the lookup table from the Project server = " + ex.Message, EventLogEntryType.Error); throw ex; } } public void Update(DataSet delta) { try { DataRepository.UpdateLookupTables((LookupTableDataSet)delta); Utility.WriteLog("Update to project server completely succeeded", EventLogEntryType.Information); } catch (Exception ex) { Utility.WriteLog("Error in Update = " + ex.Message, EventLogEntryType.Error); } } public DataSet GetChanges() { try { //Read DataSet from the database updated by SSIS Package SqlConnection sqlCon = new SqlConnection(connectionString); SqlDataAdapter adapter = new SqlDataAdapter(); DataSet ds = new DataSet(); SqlCommand sqlCommand = new SqlCommand(); sqlCommand.Connection = sqlCon; sqlCommand.CommandText = "select * FROM [RBS_Values_Latest] s ORDER BY s.SortIndex asc"; adapter.SelectCommand = sqlCommand; adapter.Fill(ds); Utility.WriteLog("Get Changes from the SSIS Database succeeded", EventLogEntryType.Information); return ds; } catch (Exception ex) { Utility.WriteLog("Error in Gettting changes from the SSIS Database = " + ex.Message, EventLogEntryType.Error); } return new DataSet(); } public DataSet GetDelta(DataSet source, DataSet changes) { try { LookupTableDataSet lookUpSource = (LookupTableDataSet)source; LookupTableDataSet lookUpSourceCopy = (LookupTableDataSet)source.Copy(); LookupTableDataSet delta = new LookupTableDataSet(); // Build tow lists of Look up DTO's with one list repsenting the root node(all node with rowlevel =1) //and the second list containing all the child nodes( all node at row levels other thna 1) List<List<LookupDTO>> lookups = BuildLookUpObject(changes); //For each root element foreach (LookupDTO lookup in lookups[0]) { // check to ensure it is a root element so as to check does not have any parent node if (lookUpSourceCopy.LookupTableTrees.Any(t => t.Field<Guid?>("LT_PARENT_STRUCT_UID") == (Guid?)lookup.ID) == false) { //If the root node not already existing add a new root node if (lookUpSourceCopy.LookupTableTrees.Any(t => t.Field<Guid?>("LT_STRUCT_UID") == (Guid?)lookup.ID) == false) { AddTreeNode(lookup, lookUpSourceCopy); } //else Modify the root node else { Modify(lookUpSourceCopy.LookupTableTrees.First(t => t.Field<Guid?>("LT_STRUCT_UID") == (Guid?)lookup.ID), lookup); } } } //For each child node foreach (LookupDTO lookup in lookups[1]) { //If child node not already existing add a new node if (lookUpSourceCopy.LookupTableTrees.Any(t => t.Field<Guid?>("LT_STRUCT_UID") == (Guid?)lookup.ID) == false) { AddChildNode(lookup, lookUpSourceCopy); } //else modify the existing node else { LookupTableDataSet.LookupTableTreesRow rowNode = lookUpSourceCopy.LookupTableTrees.First(t => t.RowState != DataRowState.Deleted && t.Field<Guid?>("LT_STRUCT_UID") == (Guid?)lookup.ID); Modify(rowNode, lookup); } } // Traverse through all child node of each root node and if it is unchanged delete it foreach (LookupDTO lookup in lookups[0]) { //Delete all child rows that are unchanged DeleteAllChilds(lookup.ID, lookUpSourceCopy); } if (lookUpSourceCopy.HasChanges(DataRowState.Added)) delta.Merge( (SvcLookupTable.LookupTableDataSet)lookUpSourceCopy.GetChanges(DataRowState.Added), true); if (lookUpSourceCopy.HasChanges(DataRowState.Modified)) delta.Merge( (SvcLookupTable.LookupTableDataSet)lookUpSourceCopy.GetChanges(DataRowState.Modified), true); if (lookUpSourceCopy.HasChanges(DataRowState.Deleted)) delta.Merge( (SvcLookupTable.LookupTableDataSet)lookUpSourceCopy.GetChanges(DataRowState.Deleted), true); Utility.WriteLog("Get Delta from the Source and Destination Database succeeded", EventLogEntryType.Information); return delta; } catch (Exception ex) { Utility.WriteLog("Error in Get Delta from the Source and Destination Database =" + ex.Message, EventLogEntryType.Error); } return new DataSet(); } private void Modify(LookupTableDataSet.LookupTableTreesRow row, LookupDTO lookup) { try { if (row.RowState == DataRowState.Deleted) { row.RejectChanges(); } row.LT_PARENT_STRUCT_UID = lookup.ParentID; row.LT_VALUE_SORT_INDEX = lookup.SortIndex; row.LT_VALUE_TEXT = lookup.Text; //row.LT_VALUE_FULL = lookup.DotNotation; row.LT_VALUE_DESC = string.Empty; row.LT_UID = new Guid(Constants.LOOKUP_ENTITY_ID); } catch (Exception ex) { Utility.WriteLog("Error in Modifying a Lookup table tree row =" + ex.Message, EventLogEntryType.Error); } } /// <summary> /// Add Child node to the lookup Tree /// </summary> /// <param name="lookup"></param> /// <param name="lookUpSourceCopy"></param> private void AddChildNode(LookupDTO lookup, LookupTableDataSet lookUpSourceCopy) { try { //If its parent node is present for the node if (lookUpSourceCopy.LookupTableTrees.Any(t => t.Field<Guid?>("LT_STRUCT_UID") == (Guid?)lookup.ParentID) == true) { // Add or modify depending on whether the node itself already exists if (lookUpSourceCopy.LookupTableTrees.Any(t => t.Field<Guid?>("LT_STRUCT_UID") == (Guid?)lookup.ID) == false) { AddTreeNode(lookup, lookUpSourceCopy); } else { LookupTableDataSet.LookupTableTreesRow row = lookUpSourceCopy.LookupTableTrees.First(t => t.Field<Guid?>("LT_STRUCT_UID") == (Guid?)lookup.ID); Modify(row, lookup); } } //Else add up the parent node else { // If aprent node does not already exist in the lookup Tree if (lookUpSourceCopy.LookupTableTrees.Any(t => t.Field<Guid?>("LT_STRUCT_UID") == (Guid?)lookup.ParentID) == false) { // Add Parent Node if (lookup.ParentNode != null) { AddTreeNode(lookup.ParentNode, lookUpSourceCopy); } } else { //Else modify the Parent Node if (lookup.ParentNode != null) { LookupTableDataSet.LookupTableTreesRow row = lookUpSourceCopy.LookupTableTrees.First(t => t.Field<Guid?>("LT_STRUCT_UID") == (Guid?)lookup.ParentID); Modify(row, lookup.ParentNode); } } } } catch (Exception ex) { Utility.WriteLog("Error in Adding a Lookup table tree row =" + ex.Message, EventLogEntryType.Error); } } /// <summary> /// Add Tree Node to the look up Tree /// </summary> /// <param name="lookup"></param> /// <param name="lookUpSourceCopy"></param> private void AddTreeNode(LookupDTO lookup, LookupTableDataSet lookUpSourceCopy) { try { LookupTableDataSet.LookupTableTreesRow row = lookUpSourceCopy.LookupTableTrees.NewLookupTableTreesRow(); row.LT_STRUCT_UID = lookup.ID; if (lookup.ParentID != Guid.Empty) { row.LT_PARENT_STRUCT_UID = lookup.ParentID; } row.LT_VALUE_SORT_INDEX = lookup.SortIndex; row.LT_VALUE_TEXT = lookup.Text; row.LT_VALUE_FULL = lookup.DotNotation; row.LT_VALUE_DESC = string.Empty; row.LT_UID = new Guid(Constants.LOOKUP_ENTITY_ID); lookUpSourceCopy.LookupTableTrees.AddLookupTableTreesRow(row); } catch (Exception ex) { Utility.WriteLog("Error in Adding a Lookup table tree row =" + ex.Message, EventLogEntryType.Error); } } /// <summary> /// Delete all child nodes for a given root element /// </summary> /// <param name="guid"></param> /// <param name="lookUpSourceCopy"></param> private void DeleteAllChilds(Guid guid, LookupTableDataSet lookUpSourceCopy) { try { if (lookUpSourceCopy.LookupTableTrees.Any(t => t.RowState != DataRowState.Deleted && t.Field<Guid?>("LT_PARENT_STRUCT_UID") == (Guid?)guid) == false) return; EnumerableRowCollection<LookupTableDataSet.LookupTableTreesRow> rows = lookUpSourceCopy.LookupTableTrees.Where(t => t.RowState != DataRowState.Deleted && t.Field<Guid?>("LT_PARENT_STRUCT_UID") == (Guid?)guid); foreach (LookupTableDataSet.LookupTableTreesRow row in rows) { DeleteAllChilds(row.LT_STRUCT_UID, lookUpSourceCopy); if (row.RowState == DataRowState.Unchanged || row.RowState == DataRowState.Detached) { row.Delete(); } } } catch (Exception ex) { Utility.WriteLog("Error in Deleting a Lookup table tree row =" + ex.Message, EventLogEntryType.Error); } } /// <summary> /// Build a lookup Data List of Root Node and Child node lists into two lists returned /// </summary> /// <param name="ds"></param> /// <returns></returns> private List<List<LookupDTO>> BuildLookUpObject(DataSet ds) { try { //List of Root Node and Child node lists into two lists returned List<List<LookupDTO>> nodes = new List<List<LookupDTO>>(); //List of root Nodes List<LookupDTO> rootListDto = new List<LookupDTO>(); //List of child Nodes List<LookupDTO> childistDto = new List<LookupDTO>(); //Use a Dictionary so that you can add a parent node to a child node when you need it Dictionary<Guid, LookupDTO> dictLookup = new Dictionary<Guid, LookupDTO>(); if (ds.Tables.Count > 0) { //For each row read from the SSIS package foreach (DataRow row in ds.Tables[0].Rows) { //Create a lookup DTO LookupDTO lookupDTO = MapLookupRow(row); //If it is a root node add to the root node list if (lookupDTO.ParentID == Guid.Empty) { rootListDto.Add(lookupDTO); dictLookup.Add(lookupDTO.ID, lookupDTO); } //else add to the child node list else { if (dictLookup.ContainsKey(lookupDTO.ParentID)) { lookupDTO.ParentNode = dictLookup[lookupDTO.ParentID]; } childistDto.Add(lookupDTO); dictLookup.Add(lookupDTO.ID, lookupDTO); } } } return new List<List<LookupDTO>> { rootListDto, childistDto }; } catch (Exception ex) { Utility.WriteLog("Error in Building DTO for a Lookup table tree row =" + ex.Message, EventLogEntryType.Error); } return new List<List<LookupDTO>>(); } /// <summary> /// Maps a single row from a SSIS data to a DTO object /// </summary> /// <param name="row"></param> /// <returns></returns> private LookupDTO MapLookupRow(DataRow row) { try { LookupDTO dto = new LookupDTO(); if (row != null) { dto.ID = row["GeneratedGUID"] != System.DBNull.Value ? new Guid(row["GeneratedGUID"].ToString()) : Guid.Empty; dto.ParentID = row["ParentGeneratedGUID"] != System.DBNull.Value ? new Guid(row["ParentGeneratedGUID"].ToString()) : Guid.Empty; dto.LastLoad = row["LastLoad"] != System.DBNull.Value ? Convert.ToDateTime(row["LastLoad"].ToString()) : default(DateTime); dto.ProcessingDate = row["ProcessingDate"] != System.DBNull.Value ? Convert.ToDateTime(row["ProcessingDate"].ToString()) : default(DateTime); dto.RowLevel = row["RowLevel"] != System.DBNull.Value ? Convert.ToInt32(row["RowLevel"].ToString()) : 0; dto.SortIndex = row["SortIndex"] != System.DBNull.Value ? Convert.ToInt32(row["SortIndex"].ToString()) : 0; dto.Text = row["Item"] != System.DBNull.Value ? row["Item"].ToString() : string.Empty; dto.DotNotation = row["DotNotation"] != System.DBNull.Value ? row["DotNotation"].ToString() : string.Empty; dto.COID = row["COID"] != System.DBNull.Value ? row["COID"].ToString() : string.Empty; } return dto; } catch (Exception ex) { Utility.WriteLog("Error in Mapping DTO for a Lookup table tree row =" + ex.Message, EventLogEntryType.Error); } return new LookupDTO(); } } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace PMMP { /// <summary> /// /// </summary> public class Constants { public const string DOCLIB_NAME_PMM_PRESENTATIONS = "PMM Presentations"; public static readonly Guid FieldId_Comments = new Guid("{3836b42f-8de1-4e40-9a2b-8797cb18e102}"); public static readonly Guid FieldId_Task = new Guid("{23042158-9c72-47ba-a676-0a9b59dd4a81}"); public static readonly Guid FieldId_Duration = new Guid("{2a6ba979-b3f0-439b-987a-28e8e826c6af}"); public static readonly Guid FieldId_Predecessor = new Guid("{7da94127-1926-42b4-8e7d-f37af75adb71}"); public static readonly Guid FieldId_Start = new Guid("{00216713-71cf-41ba-b25d-c257a1815fb9}"); public static readonly Guid FieldId_Finish = new Guid("{6bc6478d-af16-4026-babd-5c9eadc6f0e9}"); public static readonly Guid FieldId_ModifiedOn = new Guid("{754c19ee-2a06-4185-b99e-df950aa43e4b}"); public static readonly Guid FieldId_UniqueID = new Guid("{60797583-89d3-4f7a-9e74-b115c10d4b1b}"); public static readonly Guid FieldId_PercentComplete = new Guid("{e33417bf-5996-40f5-9a30-e529a46c9f62}"); public static readonly Guid FieldId_Deadline = new Guid("{73b8cc55-d228-43f6-9802-384e08fea888}"); public static readonly Guid FieldId_DrivingPath = new Guid("{180b71da-55c1-45ee-9895-db22fd359391}"); public static readonly Guid FieldId_ShowOn = new Guid("{64660977-9686-4f0b-a1da-ac9f6d591fbf}"); public const string PROPERTY_NAME_DB_SERVICE_URL = "PMM-ServiceURL"; public const string PROPERTY_NAME_DB_PROJECT_UID = "PMM-ProjectUID"; public const string TEMPLATE_FILE_LOCATION = "_cts/PMM Presentation/PMM Template.pptx"; public const string CT_PMM_NAME = "PMM Presentation"; public const string LIST_NAME_PROJECT_TASKS = "Project Tasks"; } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using DocumentFormat.OpenXml.Packaging; using DocumentFormat.OpenXml.Presentation; namespace PMMP { public class PresentationUtilities { public static int CountSlides(PresentationDocument presentationDocument) { if (presentationDocument == null) throw new ArgumentNullException("presentationDocument"); int slidesCount = 0; PresentationPart presentationPart = presentationDocument.PresentationPart; if (presentationPart != null) slidesCount = presentationPart.SlideParts.Count(); return slidesCount; } public static void MoveSlide(PresentationDocument presentationDocument, int from, int to) { if (presentationDocument == null) throw new ArgumentNullException("presentationDocument"); int slidesCount = CountSlides(presentationDocument); if (from < 0 || from >= slidesCount) throw new ArgumentOutOfRangeException("from"); if (to < 0 || from >= slidesCount || to == from) throw new ArgumentOutOfRangeException("to"); PresentationPart presentationPart = presentationDocument.PresentationPart; Presentation presentation = presentationPart.Presentation; SlideIdList slideIdList = presentation.SlideIdList; SlideId sourceSlide = slideIdList.ChildElements[from] as SlideId; SlideId targetSlide = null; if (to == 0) targetSlide = null; if (from < to) targetSlide = slideIdList.ChildElements[to] as SlideId; else targetSlide = slideIdList.ChildElements[to - 1] as SlideId; sourceSlide.Remove(); slideIdList.InsertAfter(sourceSlide, targetSlide); presentation.Save(); } public static void DeleteSlide(PresentationDocument presentationDocument, int slideIndex) { if (presentationDocument == null) throw new ArgumentNullException("presentationDocument"); int slidesCount = CountSlides(presentationDocument); if (slideIndex < 0 || slideIndex >= slidesCount) throw new ArgumentOutOfRangeException("slideIndex"); PresentationPart presentationPart = presentationDocument.PresentationPart; Presentation presentation = presentationPart.Presentation; SlideIdList slideIdList = presentation.SlideIdList; SlideId slideId = slideIdList.ChildElements[slideIndex] as SlideId; string slideRelId = slideId.RelationshipId; slideIdList.RemoveChild(slideId); if (presentation.CustomShowList != null) { foreach (var customShow in presentation.CustomShowList.Elements<CustomShow>()) { if (customShow.SlideList != null) { LinkedList<SlideListEntry> slideListEntries = new LinkedList<SlideListEntry>(); foreach (SlideListEntry slideListEntry in customShow.SlideList.Elements()) if (slideListEntry.Id != null && slideListEntry.Id == slideRelId) slideListEntries.AddLast(slideListEntry); foreach (SlideListEntry slideListEntry in slideListEntries) customShow.SlideList.RemoveChild(slideListEntry); } } } presentation.Save(); SlidePart slidePart = presentationPart.GetPartById(slideRelId) as SlidePart; presentationPart.DeletePart(slidePart); } } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Configuration; namespace PMMPresentation.Console { public class Configuration { public static string SampleDataFile { get { return GetConfigurationValue("sampleDataFile"); } } public static string TemplateFile { get { return GetConfigurationValue("templateFile"); } } private static string GetConfigurationValue(string key) { string value = null; if (ConfigurationManager.AppSettings.Count > 0) { if (ConfigurationManager.AppSettings.AllKeys.Contains(key)) { value = ConfigurationManager.AppSettings[key]; } } return value; } } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.IO; namespace PMMP { /// <summary> /// /// </summary> interface IPMPDocument { Stream CreateDocument(string template, byte[] fileName,string projectUID); } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using Repository; namespace PMMP { /// <summary> /// /// </summary> public class TaskGroupData { public IList<TaskItemGroup> TaskItemGroups { get; set; } public Dictionary<string, IList<TaskItem>> ChartsData { get; set; } public IList<TaskItemGroup> LateTaskGroups { get; set; } public IList<TaskItemGroup> UpComingTaskGroups { get; set; } public FiscalUnit FiscalPeriod { get; set; } public List<GraphDataGroup> SPDLSTartToBL { get; set; } public List<GraphDataGroup> SPDLFinishToBL { get; set; } public List<GraphDataGroup> BEIData { get; set; } } public enum ChartType { SPBaseLineStart, SPBaseLineFinish, SPBEI } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using DocumentFormat.OpenXml.Drawing; namespace PMMP { public class TableUtilities { public static void PopulateTable(Table table, IList<TaskItem> items) { Repository.Utility.WriteLog("PopulateTable started ", System.Diagnostics.EventLogEntryType.Information); RunProperties contentCellProperties = table.ChildElements[3].ChildElements.ToList()[0].Descendants<RunProperties>().ToList()[0]; table.ChildElements[3].Remove(); foreach (TaskItem item in items) { TableRow tr = new TableRow(); tr.Height = 304800L; tr.Append(CreateTextCell(item.ID.ToString(), contentCellProperties)); tr.Append(CreateTextCell(item.UniqueID.ToString(), contentCellProperties)); tr.Append(CreateTextCell(item.Task, contentCellProperties)); if (Convert.ToInt32(item.Duration) != 0) { tr.Append(CreateTextCell((Convert.ToInt32(item.Duration) / 4800).ToString(), contentCellProperties)); } else { tr.Append(CreateTextCell(item.Duration.ToString(), contentCellProperties)); } tr.Append(CreateTextCell(item.Predecessor, contentCellProperties)); tr.Append(CreateTextCell(item.Start.HasValue ? item.Start.Value.ToShortDateString() : String.Empty, contentCellProperties)); tr.Append(CreateTextCell(item.Finish.HasValue ? item.Finish.Value.ToShortDateString() : String.Empty, contentCellProperties)); //tr.Append(CreateTextCell(item.ModifiedOn.HasValue ? item.ModifiedOn.Value.ToShortDateString() : String.Empty)); table.Append(tr); } Repository.Utility.WriteLog("PopulateTable completed successfully ", System.Diagnostics.EventLogEntryType.Information); } static TableCell CreateTextCell(string text,RunProperties runProperties, params System.Drawing.Color[] color) { try { Repository.Utility.WriteLog("CreateTextCell started ", System.Diagnostics.EventLogEntryType.Information); TableCellProperties tableCellProperty = new TableCellProperties(); if (color.Length > 0) { SolidFill solidFill1 = new SolidFill(); RgbColorModelHex rgbColorModelHex1 = new RgbColorModelHex() { Val = color[0].ToHexString() }; solidFill1.Append(rgbColorModelHex1); tableCellProperty.Append(solidFill1); } TableCell tc = new TableCell( new TextBody( new BodyProperties(), new Paragraph( new Run( runProperties.Clone() as RunProperties, new Text(text)))), tableCellProperty); Repository.Utility.WriteLog("CreateTextCell completed successfully ", System.Diagnostics.EventLogEntryType.Information); return tc; } catch { return new TableCell(); } } internal static void PopulateLateOrUpComingTasksTable(Table table, IList<TaskItem> iList, Repository.FiscalUnit fiscalMonth) { Repository.Utility.WriteLog("PopulateLateTasksTable started ", System.Diagnostics.EventLogEntryType.Information); RunProperties contentCellProperties = table.ChildElements[3].ChildElements.ToList()[0].Descendants<RunProperties>().ToList()[0]; table.ChildElements[3].Remove(); foreach (TaskItem item in iList) { //shp.Table.Cell(2, 2).Shape.Fill.ForeColor.RGB = System.Drawing.ColorTranslator.ToOle(System.Drawing.Color.Red); TableRow tr = new TableRow(); tr.Height = 304800L; tr.Append(CreateTextCell(item.UniqueID.ToString(), contentCellProperties)); //tr.Append(CreateTextCell(item.UniqueID.ToString())); tr.Append(CreateTextCell(item.CA, contentCellProperties)); tr.Append(CreateTextCell(item.Task, contentCellProperties)); if (Convert.ToInt32(item.TotalSlack) != 0) { tr.Append(CreateTextCell((Convert.ToInt32(item.TotalSlack) / 4800).ToString(), contentCellProperties)); } else { tr.Append(CreateTextCell(item.TotalSlack.ToString(), contentCellProperties)); } tr.Append(CreateTextCell(item.Start.HasValue ? item.Start.Value.ToVeryShortDateString() : String.Empty, contentCellProperties)); tr.Append(CreateTextCell(item.Finish.HasValue ? item.Finish.Value.ToVeryShortDateString() : String.Empty, contentCellProperties)); TableCell baseLineStart; TableCell baseLineFinish; if (!item.BaseLineStart.HasValue) { baseLineStart = CreateTextCell(String.Empty, contentCellProperties); } else { if (item.Start.HasValue && item.Start.Value <= fiscalMonth.From && item.Start.Value >= fiscalMonth.To && item.Start.Value.Month > fiscalMonth.To.Month) { baseLineStart = CreateTextCell(item.BaseLineStart.Value.ToVeryShortDateString(), contentCellProperties,System.Drawing.Color.Red); } else if (item.Start.HasValue && item.Start > item.BaseLineStart) { baseLineStart = CreateTextCell(item.BaseLineStart.Value.ToVeryShortDateString(), contentCellProperties, System.Drawing.Color.Yellow); } else if (item.Start.HasValue && item.Start <= item.BaseLineStart) { baseLineStart = CreateTextCell(item.BaseLineStart.Value.ToVeryShortDateString(), contentCellProperties, System.Drawing.Color.Green); } else if (item.Start.HasValue && item.Start.Value.Year == DateTime.Now.Year && item.Start.Value.Month < DateTime.Now.Month && item.BaseLineStart.Value.Month == DateTime.Now.Month) { baseLineStart = CreateTextCell(item.BaseLineStart.Value.ToVeryShortDateString(), contentCellProperties, System.Drawing.Color.Blue); } else { baseLineStart = CreateTextCell(item.BaseLineStart.Value.ToVeryShortDateString(), contentCellProperties); } } if (!item.BaseLineFinish.HasValue) { baseLineFinish = CreateTextCell(String.Empty, contentCellProperties); } else { if (item.Finish.HasValue && item.Finish.Value <= fiscalMonth.From && item.Finish.Value >= fiscalMonth.To && item.Finish.Value.Month > fiscalMonth.To.Month) { baseLineFinish = CreateTextCell(item.BaseLineFinish.Value.ToVeryShortDateString(), contentCellProperties, System.Drawing.Color.Red); } else if (item.Finish.HasValue && item.Finish > item.BaseLineFinish) { baseLineFinish = CreateTextCell(item.BaseLineFinish.Value.ToVeryShortDateString(), contentCellProperties, System.Drawing.Color.Yellow); } else if (item.Finish.HasValue && item.Finish <= item.BaseLineFinish) { baseLineFinish = CreateTextCell(item.BaseLineFinish.Value.ToVeryShortDateString(), contentCellProperties, System.Drawing.Color.Green); } else if (item.Finish.HasValue && item.Finish.Value.Year == DateTime.Now.Year && item.Finish.Value.Month < DateTime.Now.Month && item.BaseLineFinish.Value.Month == DateTime.Now.Month) { baseLineFinish = CreateTextCell(item.BaseLineFinish.Value.ToVeryShortDateString(), contentCellProperties, System.Drawing.Color.Blue); } else { baseLineFinish = CreateTextCell(item.BaseLineFinish.Value.ToVeryShortDateString(), contentCellProperties); } } tr.Append(baseLineStart); tr.Append(baseLineFinish); tr.Append(Convert.ToDouble(item.Hours) != 0 ? CreateTextCell(((int)(Convert.ToDouble(item.Hours) / 60000)).ToString(), contentCellProperties) : CreateTextCell(item.Hours, contentCellProperties)); tr.Append(CreateTextCell(item.PMT, contentCellProperties)); tr.Append(CreateTextCell(item.ReasonRecovery, contentCellProperties)); tr.Append(CreateTextCell("", contentCellProperties)); if (Convert.ToInt32(item.Duration) != 0) { tr.Append(CreateTextCell((Convert.ToInt32(item.Duration) / 4800).ToString(), contentCellProperties)); } else { tr.Append(CreateTextCell(item.Duration, contentCellProperties)); } tr.Append(CreateTextCell(item.EstStart.HasValue ? item.EstStart.Value.ToVeryShortDateString() : String.Empty, contentCellProperties)); tr.Append(CreateTextCell(item.EstFinish.HasValue ? item.EstFinish.Value.ToVeryShortDateString() : String.Empty, contentCellProperties)); table.Append(tr); } Repository.Utility.WriteLog("PopulateLateTasksTable completed successfully ", System.Diagnostics.EventLogEntryType.Information); } } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.IO; namespace PMMP { /// <summary> /// /// </summary> interface IBuilder { object BuildDataFromDataSource(string projectGuid); MemoryStream CreateDocument(byte[] template,string projectUID); } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.IO; using DocumentFormat.OpenXml.Packaging; using System.Data; using DocumentFormat.OpenXml.Spreadsheet; using DocumentFormat.OpenXml.Drawing.Spreadsheet; using DocumentFormat.OpenXml.Wordprocessing; namespace PMMP { public class PresentationBuilder : IBuilder { public string FileName { get; set; } public byte[] OpenFile(string fileName) { Repository.Utility.WriteLog("OpenFile started ", System.Diagnostics.EventLogEntryType.Information); var fs = File.OpenRead(Constants.TEMPLATE_FILE_LOCATION); var bytes = new byte[fs.Length]; fs.Read(bytes, 0, bytes.Length); fs.Close(); Repository.Utility.WriteLog("OpenFile completed successfully", System.Diagnostics.EventLogEntryType.Information); return bytes; } public object BuildDataFromDataSource(string projectGuid) { Repository.Utility.WriteLog("BuildDataFromDataSource started", System.Diagnostics.EventLogEntryType.Information); object data = TaskItemRepository.GetTaskGroups(projectGuid); Repository.Utility.WriteLog("BuildDataFromDataSource completed successfully", System.Diagnostics.EventLogEntryType.Information); return data; } public MemoryStream CreateDocument(byte[] template, string projectUID) { Repository.Utility.WriteLog("CreateDocument started", System.Diagnostics.EventLogEntryType.Information); var ms = new MemoryStream(); ms.Write(template, 0, (int)template.Length); using (var oPDoc = PresentationDocument.Open(ms, true)) { var oPPart = oPDoc.PresentationPart; int gridSlideIndex = GetSlideindexByTitle(oPPart, "Driving Path"); int completedSlideIndex = GetSlideindexByTitle(oPPart, "Completed Driving Path Tasks (current Fiscal Month)"); var lateSlideIndex = GetSlideindexByTitle(oPPart, "Late Tasks (current Fiscal Month)"); var upcomingSlideIndex = GetSlideindexByTitle(oPPart, "Upcoming Tasks (current Fiscal Month)"); var chartSlideIndex = GetSlideindexByTitle(oPPart, "Chart"); var SPDLSTartToBLSlideIndex = GetSlideindexByTitle(oPPart, "Schedule Performance – Delinquent Starts to BL"); var SPDLFinishToBLSlideIndex = GetSlideindexByTitle(oPPart, "Schedule Performance – Delinquent Finishes to BL"); var BEISlideIndex = GetSlideindexByTitle(oPPart, "Schedule Performance – Baseline Execution Index (BEI)"); SlidePart gridSlidePart = null; SlidePart chartSlidePart = null; SlidePart lateSlidePart = null; SlidePart upcomingSlidePart = null; SlidePart completedSlidePart = null; SlidePart SPDLSTartToBLSlidePart = null; SlidePart SPDLFinishToBLSlidePart = null; SlidePart BEISlideIndexPart = null; if (gridSlideIndex > -1) { gridSlidePart = oPPart.GetSlidePartsInOrder().ToList()[gridSlideIndex]; } if (completedSlideIndex > -1) { completedSlidePart = oPPart.GetSlidePartsInOrder().ToList()[completedSlideIndex]; } if (chartSlideIndex > -1) { chartSlidePart = oPPart.GetSlidePartsInOrder().ToList()[chartSlideIndex]; } if (lateSlideIndex > -1) { lateSlidePart = oPPart.GetSlidePartsInOrder().ToList()[lateSlideIndex]; } if (upcomingSlideIndex > -1) { upcomingSlidePart = oPPart.GetSlidePartsInOrder().ToList()[upcomingSlideIndex]; } if (SPDLSTartToBLSlideIndex > -1) { SPDLSTartToBLSlidePart = oPPart.GetSlidePartsInOrder().ToList()[SPDLSTartToBLSlideIndex]; } if (SPDLFinishToBLSlideIndex > -1) { SPDLFinishToBLSlidePart = oPPart.GetSlidePartsInOrder().ToList()[SPDLFinishToBLSlideIndex]; } if (BEISlideIndex > -1) { BEISlideIndexPart = oPPart.GetSlidePartsInOrder().ToList()[BEISlideIndex]; } DPSlidePart = gridSlidePart; ChartSlidePart = chartSlidePart; LateSlidePart = lateSlidePart; UpComingSlidePart = upcomingSlidePart; CPSlidePart = completedSlidePart; SPDSSlidePart =SPDLSTartToBLSlidePart; SPDFSlidePart = SPDLFinishToBLSlidePart; SPBEISlidePart = BEISlideIndexPart; var taskData = TaskItemRepository.GetTaskGroups(projectUID); var data = taskData.TaskItemGroups; int[] dynamicSlideIndices = { gridSlideIndex, completedSlideIndex }; int[] fixedSlideIndices = { lateSlideIndex, upcomingSlideIndex, chartSlideIndex, SPDLSTartToBLSlideIndex, SPDLFinishToBLSlideIndex, BEISlideIndex }; dynamicSlideIndices = dynamicSlideIndices.Where(t => t != -1).ToArray(); fixedSlideIndices = fixedSlideIndices.Where(t => t != -1).ToArray(); Array.Sort(dynamicSlideIndices); Array.Sort(fixedSlideIndices); if (dynamicSlideIndices[0] < fixedSlideIndices[0]) { CreateDynamicSlides(data, dynamicSlideIndices, gridSlideIndex, completedSlideIndex, gridSlidePart, completedSlidePart, oPPart); CreateFixedSlides(taskData, fixedSlideIndices, lateSlideIndex,upcomingSlideIndex, chartSlideIndex,SPDLSTartToBLSlideIndex,SPDLFinishToBLSlideIndex,BEISlideIndex, lateSlidePart,upcomingSlidePart, chartSlidePart,SPDLSTartToBLSlidePart,SPDLFinishToBLSlidePart,BEISlideIndexPart, oPPart); } else { CreateFixedSlides(taskData, fixedSlideIndices, lateSlideIndex, upcomingSlideIndex, chartSlideIndex, SPDLSTartToBLSlideIndex, SPDLFinishToBLSlideIndex, BEISlideIndex, lateSlidePart, upcomingSlidePart, chartSlidePart, SPDLSTartToBLSlidePart, SPDLFinishToBLSlidePart, BEISlideIndexPart, oPPart); CreateDynamicSlides(data, dynamicSlideIndices, gridSlideIndex, completedSlideIndex, gridSlidePart, completedSlidePart, oPPart); } int lowestSLideIndex; if (dynamicSlideIndices[0] < fixedSlideIndices[0]) { lowestSLideIndex = dynamicSlideIndices[0]; } else { lowestSLideIndex = fixedSlideIndices[0]; } for (int i = 0; i < (dynamicSlideIndices.Count() + fixedSlideIndices.Count()); i++) { PresentationUtilities.DeleteSlide(oPDoc, lowestSLideIndex); } PresentationUtilities.MoveSlide(oPDoc, lowestSLideIndex, PresentationUtilities.CountSlides(oPDoc) - 1); int createdCount = 0; if (dynamicSlideIndices[0] < fixedSlideIndices[0]) { CreateDynamicSlidesData(data, dynamicSlideIndices, gridSlideIndex, lowestSLideIndex, ref createdCount, completedSlideIndex, oPPart); CreateFixedSlidesData(taskData, fixedSlideIndices, lateSlideIndex,upcomingSlideIndex, chartSlideIndex, lowestSLideIndex, SPDLSTartToBLSlideIndex, SPDLFinishToBLSlideIndex,BEISlideIndex, ref createdCount, oPPart); } else { CreateFixedSlidesData(taskData, fixedSlideIndices, lateSlideIndex,upcomingSlideIndex, chartSlideIndex, lowestSLideIndex,SPDLSTartToBLSlideIndex,SPDLFinishToBLSlideIndex,BEISlideIndex, ref createdCount, oPPart); CreateDynamicSlidesData(data, dynamicSlideIndices, gridSlideIndex, lowestSLideIndex, ref createdCount, completedSlideIndex, oPPart); } Repository.Utility.WriteLog("CreateDocument completed successfully", System.Diagnostics.EventLogEntryType.Information); return ms; } } private void CreateFixedSlidesData(TaskGroupData taskData, int[] fixedSlideIndices, int lateSlideIndex,int upcomingSlideIndex, int chartSlideIndex, int lowestSLideIndex, int SPDLSTartToBLSlideIndex, int SPDLFinishToBLSlideIndex,int BEISlideIndex,ref int createdCount, PresentationPart oPPart) { Repository.Utility.WriteLog("CreateFixedSlidesData started", System.Diagnostics.EventLogEntryType.Information); foreach (int slideIndex in fixedSlideIndices) { if (slideIndex == lateSlideIndex) { CreateLateSlides(taskData, lowestSLideIndex, ref createdCount, oPPart); } if (slideIndex == upcomingSlideIndex) { CreateUpComingSlides(taskData, lowestSLideIndex, ref createdCount, oPPart); } if (slideIndex == chartSlideIndex) { CreateChartSlides(taskData, lowestSLideIndex, ref createdCount, oPPart); } if (slideIndex == SPDLSTartToBLSlideIndex) { CreateSPDLToBLSlides(taskData, lowestSLideIndex, ref createdCount, oPPart,ChartType.SPBaseLineStart); } if (slideIndex == SPDLFinishToBLSlideIndex) { CreateSPDLToBLSlides(taskData, lowestSLideIndex, ref createdCount, oPPart, ChartType.SPBaseLineFinish); } if (slideIndex == BEISlideIndex) { CreateSPDLToBLSlides(taskData, lowestSLideIndex, ref createdCount, oPPart, ChartType.SPBEI); } } Repository.Utility.WriteLog("CreateFixedSlidesData completed successfully", System.Diagnostics.EventLogEntryType.Information); } private void CreateUpComingSlides(TaskGroupData taskData, int lowestSLideIndex, ref int createdCount, PresentationPart oPPart) { Repository.Utility.WriteLog("CreateupComingSlides started", System.Diagnostics.EventLogEntryType.Information); try { if (UpComingSlidePart == null) return; #region upComingSlides if (taskData.UpComingTaskGroups == null || taskData.UpComingTaskGroups.Count == 0) { createdCount++; return; } foreach (TaskItemGroup upComingTaskgroup in taskData.UpComingTaskGroups) { try { SlidePart upComingSlidePart = oPPart.GetSlidePartsInOrder().ToList()[lowestSLideIndex + createdCount]; var table = upComingSlidePart.Slide.Descendants<DocumentFormat.OpenXml.Drawing.Table>().FirstOrDefault(); if (table != null && upComingTaskgroup.TaskItems.Count > 0) { TableUtilities.PopulateLateOrUpComingTasksTable(table, upComingTaskgroup.TaskItems, taskData.FiscalPeriod); } createdCount++; } catch { continue; } } #endregion } catch (Exception ex) { Repository.Utility.WriteLog(string.Format("CreateupComingSlides had an error and the error message={0}", ex.Message), System.Diagnostics.EventLogEntryType.Information); } Repository.Utility.WriteLog("CreateupComingSlides completed", System.Diagnostics.EventLogEntryType.Information); } private void CreateSPDLToBLSlides(TaskGroupData taskData, int lowestSLideIndex, ref int createdCount, PresentationPart oPPart, ChartType chartType) { Repository.Utility.WriteLog("CreateLateSlides started", System.Diagnostics.EventLogEntryType.Information); try { #region LateSlides if (chartType == ChartType.SPBaseLineStart && SPDSSlidePart == null) return; if (chartType == ChartType.SPBaseLineFinish && SPDFSlidePart == null) return; if (chartType == ChartType.SPBEI && SPBEISlidePart == null) return; SlidePart chartSlidePart = oPPart.GetSlidePartsInOrder().ToList()[lowestSLideIndex + createdCount]; if (chartSlidePart.ChartParts.ToList().Count > 0) { var chartPart = chartSlidePart.ChartParts.ToList()[0]; foreach (IdPartPair part in chartPart.Parts) { var spreadsheet = chartPart.GetPartById(part.RelationshipId) as EmbeddedPackagePart; if (spreadsheet != null) { using (var oSDoc = SpreadsheetDocument.Open(spreadsheet.GetStream(FileMode.OpenOrCreate, FileAccess.ReadWrite), true)) { var workSheetPart = oSDoc.WorkbookPart.GetPartsOfType<WorksheetPart>().FirstOrDefault(); var sheetData = workSheetPart.Worksheet.Elements<SheetData>().FirstOrDefault(); switch (chartType) { case ChartType.SPBaseLineStart: if (taskData.SPDLSTartToBL != null && taskData.SPDLSTartToBL.Count > 0 && taskData.SPDLSTartToBL[0].Data != null) { WorkbookUtilities.ReplicateRow(sheetData, 2, taskData.SPDLSTartToBL[0].Data.Count - 1); WorkbookUtilities.LoadGraphSheetData(sheetData, taskData.SPDLSTartToBL, 1, 0); BarChartUtilities.LoadChartData(chartPart, taskData.SPDLSTartToBL); } break; case ChartType.SPBaseLineFinish: if (taskData.SPDLFinishToBL != null && taskData.SPDLFinishToBL.Count > 0 && taskData.SPDLFinishToBL[0].Data != null) { WorkbookUtilities.ReplicateRow(sheetData, 2, taskData.SPDLFinishToBL[0].Data.Count - 1); WorkbookUtilities.LoadGraphSheetData(sheetData, taskData.SPDLFinishToBL, 1, 0); BarChartUtilities.LoadChartData(chartPart, taskData.SPDLFinishToBL); } break; case ChartType.SPBEI: if (taskData.BEIData != null && taskData.BEIData.Count > 0 && taskData.BEIData[0].Data != null) { WorkbookUtilities.ReplicateRow(sheetData, 2, taskData.BEIData[0].Data.Count - 1); WorkbookUtilities.LoadGraphSheetData(sheetData, taskData.BEIData, 1, 0); BarChartUtilities.LoadChartData(chartPart, taskData.BEIData); } break; } } break; } } } #endregion } catch (Exception ex) { Repository.Utility.WriteLog(string.Format("CreateLateSlides had an error and the error message={0}", ex.Message), System.Diagnostics.EventLogEntryType.Information); } createdCount++; Repository.Utility.WriteLog("CreateLateSlides completed", System.Diagnostics.EventLogEntryType.Information); } private void CreateDynamicSlidesData(IList<TaskItemGroup> data, int[] dynamicSlideIndices, int gridSlideIndex, int lowestSLideIndex, ref int createdCount, int completedSlideIndex, PresentationPart oPPart) { Repository.Utility.WriteLog("CreateDynamicSlidesData started", System.Diagnostics.EventLogEntryType.Information); if (data.Count == 0) { createdCount += 2; return; } for (int i = 0; i < data.Count; i++) { var group = data[i]; foreach (int slideIndex in dynamicSlideIndices) { if (slideIndex == gridSlideIndex) { CreateGridSlide(oPPart, lowestSLideIndex, createdCount, group); createdCount++; } if (slideIndex == completedSlideIndex) { CreateCompletedSlides(group, lowestSLideIndex + createdCount, oPPart); createdCount++; } } } Repository.Utility.WriteLog("CreateDynamicSlidesData completed successfully", System.Diagnostics.EventLogEntryType.Information); } private void CreateChartSlides(TaskGroupData taskData, int lowestSLideIndex, ref int createdCount, PresentationPart oPPart) { Repository.Utility.WriteLog("CreateChartSlides started", System.Diagnostics.EventLogEntryType.Information); try { if (ChartSlidePart == null) return; if (taskData.ChartsData == null || taskData.ChartsData.Keys.Count == 0 || !taskData.ChartsData.Keys.Any(t=>t.StartsWith("Show On"))) { createdCount++; return; } if (taskData.ChartsData != null) { foreach (string key in taskData.ChartsData.Keys) { try { if (key.StartsWith("Show On")) { //Get all Tasks related to Driving path TaskItemGroup newGroup = new TaskItemGroup() { ChartTaskItems = taskData.ChartsData[key] }; var chartDataTable = newGroup.GetChartDataTable(key); #region Charts if (chartDataTable != null) { SlidePart chartSlidePart = oPPart.GetSlidePartsInOrder().ToList()[lowestSLideIndex + createdCount]; if (chartSlidePart.ChartParts.ToList().Count > 0) { createdCount++; var chartPart = chartSlidePart.ChartParts.ToList()[0]; foreach (IdPartPair part in chartPart.Parts) { var spreadsheet = chartPart.GetPartById(part.RelationshipId) as EmbeddedPackagePart; if (spreadsheet != null) { OpenSettings settings = new OpenSettings(); settings.AutoSave = true; using (var oSDoc = SpreadsheetDocument.Open(spreadsheet.GetStream(FileMode.OpenOrCreate, FileAccess.ReadWrite), true,settings)) { var workSheetPart = oSDoc.WorkbookPart.GetPartsOfType<WorksheetPart>().FirstOrDefault(); var sheetData = workSheetPart.Worksheet.Elements<SheetData>().FirstOrDefault(); for (int i = sheetData.Elements().Count() - 1; i >= 2; i--) { sheetData.ElementAt(i).Remove(); } string reference = workSheetPart.TableDefinitionParts.ElementAt(0).Table.Reference.Value; string length = reference.Split(":".ToCharArray())[1].Replace("I",""); WorkbookUtilities.ReplicateRow(sheetData, 2, chartDataTable.Rows.Count - 1); WorkbookUtilities.LoadSheetData(sheetData, chartDataTable, 1, 0); workSheetPart.TableDefinitionParts.ElementAt(0).Table.Reference.Value = reference.Replace(length, (chartDataTable.Rows.Count + 1).ToString()); BarChartUtilities.LoadChartData(chartPart, chartDataTable); workSheetPart.TableDefinitionParts.ElementAt(0).Table.Save(); workSheetPart.Worksheet.Save(); } break; } } var titleShape = chartSlidePart.Slide.Descendants<DocumentFormat.OpenXml.Presentation.Shape>().ToList(); if (titleShape.Count > 0) { titleShape[0].TextBody = new DocumentFormat.OpenXml.Presentation.TextBody( new DocumentFormat.OpenXml.Drawing.BodyProperties(), new DocumentFormat.OpenXml.Drawing.ListStyle(), new DocumentFormat.OpenXml.Drawing.Paragraph( new DocumentFormat.OpenXml.Drawing.Run( new DocumentFormat.OpenXml.Drawing.RunProperties() { FontSize = 3600 }, new DocumentFormat.OpenXml.Drawing.Text { Text = key.Replace("Show On_", "") }))); } } #endregion } } } catch (Exception ex) { Repository.Utility.WriteLog(string.Format("CreateChartSlides had an error and the error message={0}", ex.Message), System.Diagnostics.EventLogEntryType.Information); continue; } } } } catch (Exception ex) { Repository.Utility.WriteLog(string.Format("CreateChartSlides had an error and the error message={0}", ex.Message), System.Diagnostics.EventLogEntryType.Information); } Repository.Utility.WriteLog("CreateChartSlides completed", System.Diagnostics.EventLogEntryType.Information); } private void CreateLateSlides(TaskGroupData taskData, int lowestSLideIndex, ref int createdCount, PresentationPart oPPart) { Repository.Utility.WriteLog("CreateLateSlides started", System.Diagnostics.EventLogEntryType.Information); try { if (LateSlidePart == null) return; #region LateSlides if (taskData.LateTaskGroups == null || taskData.LateTaskGroups.Count == 0) { createdCount++; return; } foreach (TaskItemGroup lateTaskgroup in taskData.LateTaskGroups) { try { SlidePart lateSlidePart = oPPart.GetSlidePartsInOrder().ToList()[lowestSLideIndex + createdCount]; var table = lateSlidePart.Slide.Descendants<DocumentFormat.OpenXml.Drawing.Table>().FirstOrDefault(); if (table != null && lateTaskgroup.TaskItems.Count > 0) { TableUtilities.PopulateLateOrUpComingTasksTable(table, lateTaskgroup.TaskItems, taskData.FiscalPeriod); } createdCount++; } catch { continue; } } #endregion } catch (Exception ex) { Repository.Utility.WriteLog(string.Format("CreateLateSlides had an error and the error message={0}", ex.Message), System.Diagnostics.EventLogEntryType.Information); } Repository.Utility.WriteLog("CreateLateSlides completed", System.Diagnostics.EventLogEntryType.Information); } private void CreateCompletedSlides(TaskItemGroup group, int completedSlideIndex, PresentationPart oPPart) { Repository.Utility.WriteLog("CreateCompletedSlides started", System.Diagnostics.EventLogEntryType.Information); try { if (CPSlidePart == null) return; if (group.CompletedTaskgroups != null) { IList<TaskItemGroup> CompletedTasks = group.CompletedTaskgroups; if (CompletedTasks != null && CompletedTasks.Count() > 0) { foreach (TaskItemGroup completedTaskgroup in CompletedTasks) { SlidePart completedSlidePart = oPPart.GetSlidePartsInOrder().ToList()[completedSlideIndex]; DocumentFormat.OpenXml.Presentation.TextBody numberPart = (DocumentFormat.OpenXml.Presentation.TextBody)completedSlidePart.Slide.CommonSlideData.ShapeTree.Elements().ToList()[3].Elements().ToList()[2]; int bulletCount = numberPart.Elements<DocumentFormat.OpenXml.Drawing.Paragraph>().Count(); foreach (string task in completedTaskgroup.TaskItems.Select(t => t.Task)) { DocumentFormat.OpenXml.Drawing.Paragraph paragraph = (DocumentFormat.OpenXml.Drawing.Paragraph)numberPart.Elements().ToList()[3].Clone(); for (int i = paragraph.Elements().Count() - 1; i >=1; i--) { if (paragraph.ElementAt(i).GetType() == typeof(DocumentFormat.OpenXml.Drawing.Run)) { paragraph.ElementAt(i).Remove(); } } (paragraph.Elements().ToList()[0] as DocumentFormat.OpenXml.Drawing.Run).Text = new DocumentFormat.OpenXml.Drawing.Text(task); numberPart.Append(paragraph); } //var titleShape = completedSlidePart.Slide.Descendants<DocumentFormat.OpenXml.Presentation.Shape>().ToList(); //if (titleShape.Count > 0) //{ // titleShape[0].TextBody = new DocumentFormat.OpenXml.Presentation.TextBody( // new DocumentFormat.OpenXml.Drawing.BodyProperties(), // new DocumentFormat.OpenXml.Drawing.ListStyle(), // new DocumentFormat.OpenXml.Drawing.Paragraph( // new DocumentFormat.OpenXml.Drawing.Run( // new DocumentFormat.OpenXml.Drawing.RunProperties() { FontSize = 3600 }, // new DocumentFormat.OpenXml.Drawing.Text { Text = group.Title }))); //} DocumentFormat.OpenXml.Presentation.TextBody numPart = (DocumentFormat.OpenXml.Presentation.TextBody)completedSlidePart.Slide.CommonSlideData.ShapeTree.Elements().ToList()[3].Elements().ToList()[2]; for (int i = bulletCount - 2; i >= 0; i--) { ((DocumentFormat.OpenXml.Drawing.Paragraph)numPart.Elements().ToList()[3]).Remove(); } } } } } catch (Exception ex) { Repository.Utility.WriteLog(string.Format("CreateCompletedSlides had an error and the error message={0}", ex.Message), System.Diagnostics.EventLogEntryType.Information); } Repository.Utility.WriteLog("CreateCompletedSlides completed", System.Diagnostics.EventLogEntryType.Information); } private void CreateGridSlide(PresentationPart oPPart, int gridSlideIndex, int i, TaskItemGroup group) { Repository.Utility.WriteLog("CreateGridSlide started", System.Diagnostics.EventLogEntryType.Information); try { if (DPSlidePart == null) return; SlidePart gridSlidePart = oPPart.GetSlidePartsInOrder().ToList()[gridSlideIndex + i]; var dataTable = group.TaskItemsDataTable; var table = gridSlidePart.Slide.Descendants<DocumentFormat.OpenXml.Drawing.Table>().FirstOrDefault(); if (table != null && group.TaskItems != null && group.TaskItems.Count > 0) { TableUtilities.PopulateTable(table, group.TaskItems); } //else //{ // DocumentFormat.OpenXml.OpenXmlElement parent = table.Parent; // parent.ReplaceChild(new DocumentFormat.OpenXml.Presentation.Text("No Data Avialable"), table); // //table.Remove(); //} var titleShape = gridSlidePart.Slide.Descendants<DocumentFormat.OpenXml.Presentation.Shape>().ToList(); if (titleShape.Count > 0) { titleShape[0].TextBody = new DocumentFormat.OpenXml.Presentation.TextBody( new DocumentFormat.OpenXml.Drawing.BodyProperties(), new DocumentFormat.OpenXml.Drawing.ListStyle(), new DocumentFormat.OpenXml.Drawing.Paragraph( new DocumentFormat.OpenXml.Drawing.Run( new DocumentFormat.OpenXml.Drawing.RunProperties() { FontSize = 3600 }, new DocumentFormat.OpenXml.Drawing.Text { Text = group.Title }))); } } catch (Exception ex) { Repository.Utility.WriteLog(string.Format("CreateGridSlide had an error and the error message={0}", ex.Message), System.Diagnostics.EventLogEntryType.Information); } Repository.Utility.WriteLog("CreateGridSlide completed", System.Diagnostics.EventLogEntryType.Information); } private void CreateFixedSlides(TaskGroupData taskData, int[] dynamicSlideIndices, int lateSlideIndex,int upComingSlideIndex, int chartSlideIndex, int SPDLSTartToBLSlideIndex, int SPDLFinishToBLSlideIndex,int BEISlideIndex, SlidePart lateSlidePart,SlidePart upComingSlidePart, SlidePart chartSlidePart, SlidePart SPDLSTartToBLSlidePart, SlidePart SPDLFinishToBLSlidePart,SlidePart BEISlidePart, PresentationPart oPPart) { Repository.Utility.WriteLog("CreateFixedSlides started", System.Diagnostics.EventLogEntryType.Information); foreach (int slideIndex in dynamicSlideIndices) { if (lateSlideIndex == slideIndex) { if (taskData.LateTaskGroups != null && taskData.LateTaskGroups.Count > 0) { if (lateSlidePart != null) { foreach (TaskItemGroup group in taskData.LateTaskGroups) { var newLateSlidePart = lateSlidePart.CloneSlide(SlideType.Late); oPPart.AppendSlide(newLateSlidePart); } } } else { if (lateSlidePart != null) { var newLateSlidePart = lateSlidePart.CloneSlide(SlideType.Late); oPPart.AppendSlide(newLateSlidePart); } } } if (upComingSlideIndex == slideIndex) { if (taskData.UpComingTaskGroups != null && taskData.UpComingTaskGroups.Count > 0) { if (upComingSlidePart != null) { foreach (TaskItemGroup group in taskData.UpComingTaskGroups) { var newupComingSlidePart = upComingSlidePart.CloneSlide(SlideType.Late); oPPart.AppendSlide(newupComingSlidePart); } } } else { if (upComingSlidePart != null) { var newupComingSlidePart = upComingSlidePart.CloneSlide(SlideType.Late); oPPart.AppendSlide(newupComingSlidePart); } } } if (SPDLSTartToBLSlideIndex == slideIndex) { if (SPDLSTartToBLSlidePart != null) { var newSPDLStartToBLSlidePart = SPDLSTartToBLSlidePart.CloneSlide(SlideType.Chart); oPPart.AppendSlide(newSPDLStartToBLSlidePart); } } if (SPDLFinishToBLSlideIndex == slideIndex) { if (SPDLFinishToBLSlidePart != null) { var newSPDLFinishToBLSlidePart = SPDLFinishToBLSlidePart.CloneSlide(SlideType.Chart); oPPart.AppendSlide(newSPDLFinishToBLSlidePart); } } if (BEISlideIndex == slideIndex) { if (BEISlidePart != null) { var newBEISlidePart = BEISlidePart.CloneSlide(SlideType.Chart); oPPart.AppendSlide(newBEISlidePart); } } if (chartSlideIndex == slideIndex) { if (taskData.ChartsData != null && taskData.ChartsData.Count > 0) { if (chartSlidePart != null && taskData.ChartsData.Keys.Any(t => t.StartsWith("Show On") == true)) { foreach (string chartType in taskData.ChartsData.Keys) { if (chartType.StartsWith("Show On")) { var newChartSlidePart = chartSlidePart.CloneSlide(SlideType.Chart); oPPart.AppendSlide(newChartSlidePart); } } } else { var newChartSlidePart = chartSlidePart.CloneSlide(SlideType.Chart); oPPart.AppendSlide(newChartSlidePart); } } } } Repository.Utility.WriteLog("CreateFixedSlides completed successfully", System.Diagnostics.EventLogEntryType.Information); } private void CreateDynamicSlides(IList<TaskItemGroup> data, int[] dynamicSlideIndices, int gridSlideIndex, int completedSlideIndex, SlidePart gridSlidePart, SlidePart completedSlidePart, PresentationPart oPPart) { Repository.Utility.WriteLog("CreateDynamicSlides started", System.Diagnostics.EventLogEntryType.Information); if (data.Count < 1) { foreach (int slideIndex in dynamicSlideIndices) { if (slideIndex == gridSlideIndex) { var newGridSlidePart = gridSlidePart.CloneSlide(SlideType.Grid); oPPart.AppendSlide(newGridSlidePart); } if (slideIndex == completedSlideIndex) { var newCompletedSlidePart = completedSlidePart.CloneSlide(SlideType.Completed); oPPart.AppendSlide(newCompletedSlidePart); } } } for (int i = 0; i < data.Count; i++) { foreach (int slideIndex in dynamicSlideIndices) { if (slideIndex == gridSlideIndex) { if (gridSlidePart != null) { var newGridSlidePart = gridSlidePart.CloneSlide(SlideType.Grid); oPPart.AppendSlide(newGridSlidePart); } } if (slideIndex == completedSlideIndex) { if (data[i].CompletedTaskgroups != null) { if (completedSlidePart != null) { if (data[i].CompletedTaskgroups.Count == 0) { var newCompletedSlidePart = completedSlidePart.CloneSlide(SlideType.Completed); oPPart.AppendSlide(newCompletedSlidePart); } else { foreach (TaskItemGroup group in data[i].CompletedTaskgroups) { var newCompletedSlidePart = completedSlidePart.CloneSlide(SlideType.Completed); oPPart.AppendSlide(newCompletedSlidePart); } } } } else { var newCompletedSlidePart = completedSlidePart.CloneSlide(SlideType.Completed); oPPart.AppendSlide(newCompletedSlidePart); } } } } Repository.Utility.WriteLog("CreateDynamicSlides completed successfully", System.Diagnostics.EventLogEntryType.Information); } private int GetSlideindexByTitle(PresentationPart oPPart, string title) { Repository.Utility.WriteLog("GetSlideindexByTitle started", System.Diagnostics.EventLogEntryType.Information); List<SlidePart> slides = oPPart.GetSlidePartsInOrder().ToList(); int count = 0; foreach (var gridSlidePart in slides) { var titleShape = gridSlidePart.Slide.Descendants<DocumentFormat.OpenXml.Presentation.Shape>().ToList(); if (titleShape.Count > 0) { if (titleShape[0].TextBody.InnerText.Trim().ToUpper() == title.Trim().ToUpper()) { Repository.Utility.WriteLog("GetSlideindexByTitle completed successfully", System.Diagnostics.EventLogEntryType.Information); return count; } } count++; } Repository.Utility.WriteLog("GetSlideindexByTitle completed successfully", System.Diagnostics.EventLogEntryType.Information); return -1; } public SlidePart DPSlidePart { get; set; } public SlidePart CPSlidePart { get; set; } public SlidePart LateSlidePart { get; set; } public SlidePart UpComingSlidePart { get; set; } public SlidePart ChartSlidePart { get; set; } public SlidePart SPDSSlidePart { get; set; } public SlidePart SPDFSlidePart { get; set; } public SlidePart SPBEISlidePart { get; set; } } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.IO; namespace PMMP { class PresentationDirector : IDirector { public Stream Construct(IBuilder builder, byte[] fileName,string projectGuid) { Repository.Utility.WriteLog("Construct started", System.Diagnostics.EventLogEntryType.Information); //builder.BuildDataFromDataSource(projectGuid); Stream oStream = builder.CreateDocument(fileName,projectGuid); Repository.Utility.WriteLog("Construct completed successfully", System.Diagnostics.EventLogEntryType.Information); return oStream; } } } <file_sep>//using System; //using System.Collections.Generic; //using System.Linq; //using System.Text; //using DocumentFormat.OpenXml.Packaging; //using System.IO; //using System.Xml; //using Ionic.Zip; //namespace TestLoadProjects //{ // class ChartBuilder // { // public void EditGraph(PresentationPart pPart, DocumentFormat.OpenXml.Packaging.ChartPart[] charts) // { // String check = grab(pPart); // ChartPart chart = null; // for (int i = 0; i < charts.Count(); i++) //loop th // { // chart = charts[i]; // if (check.ToLower().Equals(chart.Uri.ToString().ToLower())) // break; // } // //chart now contains the chart-cache you are looking to edit. // } // private String grab(PresentationPart pPart) // { // //isolate chart // #region grab // var rids = RelsRID; // DocumentFormat.OpenXml.Wordprocessing.Drawing elem = null; // DocumentFormat.OpenXml.Drawing.Charts.ChartReference gd = null; // try // { // elem = pPart.NextSibling().Elements<Drawing>().ElementAt(0); //første forsøg på at finde vores graf // } // catch (Exception) // { //forsøg nummer 2 // OpenXmlElement testE = pPart.NextSibling(); // while (testE.LocalName.ToLower() != "drawing") // { // testE = testE.NextSibling(); // for (int i = 0; i < testE.Elements().Count(); i++) // if (testE.ElementAt(i).LocalName.ToLower() == "drawing") testE = testE.ElementAt(i); // } // elem = (DocumentFormat.OpenXml.Wordprocessing.Drawing)testE; // } // try // { //first try at grabbing graph data // gd = (DocumentFormat.OpenXml.Drawing.Charts.ChartReference)elem.Inline.Graphic.GraphicData.ElementAt(0); // } // catch (Exception) // { //second possible route // gd = (DocumentFormat.OpenXml.Drawing.Charts.ChartReference)elem.Anchor.Elements<Graphic>().First().Elements<GraphicData>().First().ElementAt(0); // } // var id = gd.Id; // String matchname = "/word/" + rids[id.ToString()]; //create filepath // #endregion // return matchname; // } // private Dictionary<String, String> RelsRIDToFile(string file) // { // String rels; // using (MemoryStream memory = new MemoryStream()) // { // using (ZipFile zip = ZipFile.Read(file)) // { // ZipEntry e = zip["ppt/_rels/presentation.xml.rels"]; // e.Extract(memory); // } // using (StreamReader reader = new StreamReader(memory)) // { // memory.Seek(0, SeekOrigin.Begin); // rels = reader.ReadToEnd(); // } // } // XmlDataDocument xml = new XmlDataDocument(); // xml.LoadXml(rels); // XmlNodeList xmlnode; // xmlnode = xml.GetElementsByTagName("Relationship"); // Dictionary<String, String> result = new Dictionary<string, string>(); // for (int i = 0; i < xmlnode.Count; i++) // { // var node = xmlnode[i]; // var atts = node.Attributes; // String id = ""; // String target = ""; // for (int ii = 0; ii < atts.Count; ii++) // { // var att = atts[ii]; // if (att.Name.ToLower() == "id") id = att.Value; // if (att.Name.ToLower() == "target") target = att.Value; // } // result[id] = target; // } // return result; // } // } //} <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace Repository { /// <summary> /// /// </summary> class CustomFieldDTO { public string Text { get; set; } public string Description { get; set; } internal void AppendText(string text) { Text += "," + text; Text = string.Join(",", Text.Split(",".ToCharArray(),StringSplitOptions.RemoveEmptyEntries)); } internal void AppendDescription(string description) { Description += "," + description; Description = string.Join(",", Description.Split(",".ToCharArray(), StringSplitOptions.RemoveEmptyEntries)); } } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Data; using SvcProject; namespace Repository { /// <summary> /// /// </summary> public class DataAccess { private DataSet projectDataSet; private DataSet customFieldsDataSet; private DataSet lookUpDataSet; private Dictionary<string, CustomFieldDTO> customFieldsTaskDictionary = new Dictionary<string, CustomFieldDTO>(); private string entity_uid; private Guid project_id; public DataAccess(Guid projectid) { project_id = projectid; } public DataSet ReadProject(DataSet taskDataSetToCompare) { entity_uid = DataRepository.ReadTaskEntityUID(); customFieldsDataSet = DataRepository.ReadCustomFields(); projectDataSet = DataRepository.ReadProject(project_id); lookUpDataSet = DataRepository.ReadLookupTables(); DataSet outputDataSet = TransformDataSet(); return CompareTaskData(outputDataSet, taskDataSetToCompare); } private DataSet CompareTaskData(DataSet outputDataSet, DataSet inputTaskData) { DataSet deltaDataSet = new DataSet(); if (inputTaskData == null || inputTaskData.Tables["Task"].Rows.Count < 1) { return outputDataSet; } deltaDataSet.Tables.Add(outputDataSet.Tables["Task"].Clone()); foreach (DataRow row in outputDataSet.Tables["Task"].Rows) { try { if (inputTaskData.Tables["Task"].AsEnumerable().Any<DataRow>(t => t.Field<Guid>("TASK_UID") == new Guid(row["TASK_UID"].ToString()))) { DataRow inputRow = inputTaskData.Tables["Task"].AsEnumerable().First<DataRow>(t => t.Field<Guid>("TASK_UID") == new Guid(row["TASK_UID"].ToString())); if (inputRow != null) { if (!CompareRows(row, inputRow)) { deltaDataSet.Tables["Task"].ImportRow(row); } else { deltaDataSet.Tables["Task"].ImportRow(row); } } } //IF row not found in destination table add the row as a delta else { deltaDataSet.Tables["Task"].ImportRow(row); } } catch (Exception ex) { // Any exception occured while comparing skip and contniue with next row to compare by catching exception continue; } } foreach (DataRow row in inputTaskData.Tables["Task"].Rows) { try { if (outputDataSet.Tables["Task"].AsEnumerable().Any<DataRow>(t => t.Field<Guid>("TASK_UID") == new Guid(row["TASK_UID"].ToString()))) { DataRow inputRow = outputDataSet.Tables["Task"].AsEnumerable().First<DataRow>(t => t.Field<Guid>("TASK_UID") == new Guid(row["TASK_UID"].ToString())); //If a row from input not found in destination mark it deleted if (inputRow == null) { deltaDataSet.Tables["Task"].ImportRow(row); deltaDataSet.Tables["Task"].AsEnumerable().First<DataRow>(t => t.Field<Guid>("TASK_UID") == new Guid(row["TASK_UID"].ToString())).AcceptChanges(); deltaDataSet.Tables["Task"].AsEnumerable().First<DataRow>(t => t.Field<Guid>("TASK_UID") == new Guid(row["TASK_UID"].ToString())).Delete(); } } else { deltaDataSet.Tables["Task"].ImportRow(row); deltaDataSet.Tables["Task"].AsEnumerable().First<DataRow>(t => t.Field<Guid>("TASK_UID") == new Guid(row["TASK_UID"].ToString())).AcceptChanges(); deltaDataSet.Tables["Task"].AsEnumerable().First<DataRow>(t => t.Field<Guid>("TASK_UID") == new Guid(row["TASK_UID"].ToString())).Delete(); } } catch (Exception ex) { // Any exception occured while comparing skip and contniue with next row to compare by catching exception continue; } } return deltaDataSet; } private bool CompareRows(DataRow row, DataRow inputRow) { string[] fieldsToCompare = new string[]{"TASK_PREDECESSORS","TASK_PCT_COMP","TASK_START_DATE","TASK_FINISH_DATE","TASK_DEADLINE","CUSTOMFIELD_DESC", "TASK_DRIVINGPATH_ID"}; foreach (string column in fieldsToCompare) { if (column == "CUSTOMFIELD_DESC") { if (!string.IsNullOrEmpty(row["CUSTOMFIELD_TEXT"].ToString())) { if (row["CUSTOMFIELD_TEXT"].ToString().Contains("Show On")) { if (row[column].ToString() != inputRow[column].ToString()) return false; } } } else { if (row[column].ToString() != inputRow[column].ToString()) return false; } } return true; } private DataSet TransformDataSet() { Utility.WriteLog(string.Format("Calling TransformDataSet"), System.Diagnostics.EventLogEntryType.Information); DataSet outputDataSet = projectDataSet.Copy(); //add new table DrivingPath outputDataSet.Tables.Add("DrivingPath"); outputDataSet.Tables["DrivingPath"].Columns.Add("PROJ_UID", typeof(String)); outputDataSet.Tables["DrivingPath"].Columns.Add("TASK_DRIVINGPATH_ID", typeof(String)); outputDataSet.Tables["DrivingPath"].Columns.Add("DrivingPathName", typeof(String)); // Add new columns for output DataSet outputDataSet.Tables["Task"].Columns.Add("TASK_PREDECESSORS", typeof(String)); outputDataSet.Tables["Task"].Columns.Add("TASK_DRIVINGPATH_ID", typeof(String)); outputDataSet.Tables["Task"].Columns.Add("TASK_MODIFIED_ON", typeof(DateTime)); //Add new Columns for Custom Fields outputDataSet.Tables["Task"].Columns.Add("CUSTOMFIELD_TEXT", typeof(String)); outputDataSet.Tables["Task"].Columns.Add("CUSTOMFIELD_DESC", typeof(String)); #region Build Predecessors Dcitionary // the query var taskResult = from x in outputDataSet.Tables["Dependency"].AsEnumerable() join y in outputDataSet.Tables["Task"].AsEnumerable() on (Guid)x["LINK_SUCC_UID"] equals (Guid)y["TASK_UID"] join z in outputDataSet.Tables["Task"].AsEnumerable() on (Guid)x["LINK_PRED_UID"] equals (Guid)z["TASK_UID"] select new { LINK_SUCC_UID = x["LINK_SUCC_UID"], LINK_PRED_UID = x["LINK_PRED_UID"], TASK_ID = z["TASK_ID"], DATA_ROW = z }; Dictionary<string, List<TASKDTO>> PredecessorsDictionary = new Dictionary<string, List<TASKDTO>>(); foreach (var dataRow in taskResult) { if (PredecessorsDictionary.ContainsKey(dataRow.LINK_SUCC_UID.ToString())) { TASKDTO task = new TASKDTO(); List<TASKDTO> tasks = PredecessorsDictionary[dataRow.LINK_SUCC_UID.ToString()]; PredecessorsDictionary.Remove(dataRow.LINK_SUCC_UID.ToString()); task.LINK_PRED_UID = dataRow.LINK_PRED_UID.ToString(); task.TASK_ID = dataRow.TASK_ID.ToString(); task.Row = dataRow.DATA_ROW; tasks.Add(task); PredecessorsDictionary.Add(dataRow.LINK_SUCC_UID.ToString(), tasks); } else { List<TASKDTO> tasks = new List<TASKDTO>(); TASKDTO task = new TASKDTO(); task.LINK_PRED_UID = dataRow.LINK_PRED_UID.ToString(); task.TASK_ID = dataRow.TASK_ID.ToString(); task.Row = dataRow.DATA_ROW; tasks.Add(task); PredecessorsDictionary.Add(dataRow.LINK_SUCC_UID.ToString(), tasks); } } #endregion #region Build CustomFields customFieldsTaskDictionary = new Dictionary<string, CustomFieldDTO>(); // create the default row to be used when no value found var defaultRow = customFieldsDataSet.Tables["CustomFields"].NewRow(); // the query var result = from x in outputDataSet.Tables["TaskCustomFields"].AsEnumerable() join y in customFieldsDataSet.Tables["CustomFields"].AsEnumerable() on (Guid)x["MD_PROP_UID"] equals (Guid)y["MD_PROP_UID"] select new { MD_PROP_NAME = y["MD_PROP_NAME"], MD_ENT_TYPE_UID = y["MD_ENT_TYPE_UID"], CODE_VALUE = x["CODE_VALUE"], TASK_UID = x["TASK_UID"] }; foreach (var customFieldRow in result) { string propertyname = ""; propertyname = customFieldRow.MD_PROP_NAME.ToString(); string codevalue = customFieldRow.CODE_VALUE.ToString(); string task_uid = customFieldRow.TASK_UID.ToString(); if (!string.IsNullOrEmpty(codevalue)) { EnumerableRowCollection<DataRow> rows = lookUpDataSet.Tables["LookupTableTrees"].AsEnumerable().Where(t => t.Field<Guid>("LT_STRUCT_UID") == new Guid(codevalue)); foreach (DataRow row in rows) { CustomFieldDTO customFieldDTO = new CustomFieldDTO(); customFieldDTO.Text = propertyname + "_" + row["LT_VALUE_TEXT"].ToString(); customFieldDTO.Description = propertyname + "_" + row["LT_VALUE_DESC"].ToString(); if (customFieldsTaskDictionary.ContainsKey(task_uid)) { CustomFieldDTO existingCustomFieldDTO = customFieldsTaskDictionary[task_uid]; customFieldsTaskDictionary.Remove(task_uid); existingCustomFieldDTO.AppendText(customFieldDTO.Text); existingCustomFieldDTO.AppendDescription(customFieldDTO.Description); customFieldsTaskDictionary.Add(task_uid, existingCustomFieldDTO); } else { customFieldsTaskDictionary.Add(task_uid, customFieldDTO); } } } } #endregion int count = 0; List<DataRow> successorTasks = new List<DataRow>(); #region Update Tasks Table with Driving Path and SPredecessors and Custom Fields //For each Task foreach (DataRow dataRow in projectDataSet.Tables["Task"].Rows) { if (customFieldsTaskDictionary.ContainsKey(dataRow["TASK_UID"].ToString())) { CustomFieldDTO customDTO = customFieldsTaskDictionary[dataRow["TASK_UID"].ToString()]; DataRow outputRow = outputDataSet.Tables["Task"].AsEnumerable().First<DataRow>(t=>t.Field<Guid>("TASK_UID").ToString() == dataRow["TASK_UID"].ToString()); outputRow["CUSTOMFIELD_TEXT"] = customDTO.Text; outputRow["CUSTOMFIELD_DESC"] = customDTO.Description; } DataRow SuccessorRow = outputDataSet.Tables["Task"].Rows[count]; //From the Dependency Table get all Successors for this Task List<TASKDTO> rows = new List<TASKDTO>(); if (PredecessorsDictionary.ContainsKey(dataRow["TASK_UID"].ToString())) { rows = PredecessorsDictionary[dataRow["TASK_UID"].ToString()]; } DataRow deadLineTaskRow = null; if (rows.Count > 0) { StringBuilder sb = new StringBuilder(); foreach (TASKDTO row in rows) { DataRow taskRow = row.Row; sb.Append("," + row.TASK_ID.ToString()); //If it as a deadline task stor it so that you can iterate through all tasks in the task chain list to update them later if (SuccessorRow["TASK_DEADLINE"] != System.DBNull.Value) { deadLineTaskRow = SuccessorRow; //Update Driving Path Table DataRow drivingPathRow = outputDataSet.Tables["DrivingPath"].Rows.Add(taskRow.Field<Guid>("PROJ_UID"), deadLineTaskRow.Field<int>("TASK_ID").ToString(), deadLineTaskRow.Field<string>("TASK_NAME")); } //mantian the list of tasks in the task chain list so as to update deadline task later successorTasks.Add(taskRow); //// add custom fields //if (customFieldsTaskDictionary.ContainsKey(taskRow["TASK_UID"].ToString())) //{ // CustomFieldDTO customDTO = customFieldsTaskDictionary[taskRow["TASK_UID"].ToString()]; // taskRow["CUSTOMFIELD_TEXT"] = customDTO.Text; // taskRow["CUSTOMFIELD_DESC"] = customDTO.Description; //} taskRow["TASK_MODIFIED_ON"] = DateTime.Now; } //update deadline tasks for each task in the task chain list if (deadLineTaskRow != null) { foreach (DataRow row in successorTasks) { if (BelongsToDrivingPath(outputDataSet, deadLineTaskRow, row, PredecessorsDictionary)) { row["TASK_DRIVINGPATH_ID"] = BuildCommaSeperatedValue(row["TASK_DRIVINGPATH_ID"], deadLineTaskRow.Field<int>("TASK_ID").ToString()); } } deadLineTaskRow["TASK_DRIVINGPATH_ID"] = BuildCommaSeperatedValue(deadLineTaskRow["TASK_DRIVINGPATH_ID"], deadLineTaskRow.Field<int>("TASK_ID").ToString()); } string predescessor = sb.ToString(); predescessor = string.Join(",", predescessor.Split(",".ToCharArray(), StringSplitOptions.RemoveEmptyEntries)); SuccessorRow["TASK_PREDECESSORS"] = predescessor; } count++; } #endregion Utility.WriteLog(string.Format("TransformDataSet completed successfully"), System.Diagnostics.EventLogEntryType.Information); return outputDataSet; } private bool BelongsToDrivingPath(DataSet outputDataSet, DataRow deadLineTaskRow, DataRow row, Dictionary<string, List<TASKDTO>> PredecessorsDictionary) { if (deadLineTaskRow["TASK_ID"].ToString() == row["TASK_ID"].ToString()) { return true; } if (!PredecessorsDictionary.ContainsKey(deadLineTaskRow["TASK_UID"].ToString())) { return false; } List<string> Pred = PredecessorsDictionary[deadLineTaskRow["TASK_UID"].ToString()].Select(t => t.TASK_ID).ToList(); foreach (string pred in Pred) { DataRow predTask = outputDataSet.Tables["Task"].AsEnumerable().First(t => t.Field<int>("TASK_ID").ToString() == pred); if (BelongsToDrivingPath(outputDataSet, predTask, row, PredecessorsDictionary) == true) { return true; } } return false; } private string BuildCommaSeperatedValue(object taskRow, string value) { if (taskRow != null && !taskRow.ToString().Split(",".ToCharArray()).Contains(value)) { taskRow += "," + value; if (taskRow != null) { string sTaskRow = taskRow.ToString(); sTaskRow = string.Join(",", sTaskRow.Split(",".ToCharArray(), StringSplitOptions.RemoveEmptyEntries)); return sTaskRow; } } return taskRow != null ? taskRow.ToString():""; } public DateTime? GetProjectCurrentDate(ProjectDataSet projectDataSet,Guid projectGuid) { return DataRepository.GetProjectCurrentDate(projectDataSet, projectGuid); } public List<FiscalUnit> GetProjectStatusPeriods(DateTime? date) { return DataRepository.GetProjectStatusPeriods(date); } public List<FiscalUnit> GetProjectStatusWeekPeriods(DateTime? projectStatusDate) { return DataRepository.GetProjectStatusWeekPeriods(projectStatusDate); } } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using Microsoft.SharePoint; using System.Collections.Specialized; using System.Data; using SvcProject; using SvcCustomFields; namespace PMMP { public class DataHelper { public static string GetValue(object value) { Repository.Utility.WriteLog("GetValue started", System.Diagnostics.EventLogEntryType.Information); if (value != null) { Repository.Utility.WriteLog("GetValue completed successfully", System.Diagnostics.EventLogEntryType.Information); return value.ToString(); } Repository.Utility.WriteLog("GetValue completed successfully", System.Diagnostics.EventLogEntryType.Information); return string.Empty; } public static int GetValueAsInteger(object oValue) { Repository.Utility.WriteLog("GetValueAsInteger started", System.Diagnostics.EventLogEntryType.Information); int value = 0; if (oValue != null) { value = Convert.ToInt32(oValue.ToString()); Repository.Utility.WriteLog("GetValueAsInteger completed successfully", System.Diagnostics.EventLogEntryType.Information); } return value; } public static object GetValueFromCustomFieldTextOrDate(DataRow dataRow, CustomFieldType type, CustomFieldDataSet dataSet) { try { StringCollection value = new StringCollection(); Guid mdPropID = Guid.Empty; if ((dataSet as CustomFieldDataSet).CustomFields.Any(t => t.MD_PROP_NAME == type.GetString())) { mdPropID = (dataSet as CustomFieldDataSet).CustomFields.First(t => t.MD_PROP_NAME == type.GetString()).MD_PROP_UID; } if (mdPropID == Guid.Empty) { return null; } if (type == CustomFieldType.EstStart || type == CustomFieldType.EstFinish) { if ((dataRow.Table.DataSet as ProjectDataSet).TaskCustomFields.Any(t => t.TASK_UID == (dataRow as ProjectDataSet.TaskRow).TASK_UID && t.MD_PROP_UID == mdPropID)) return (dataRow.Table.DataSet as ProjectDataSet).TaskCustomFields.First(t => t.TASK_UID == (dataRow as ProjectDataSet.TaskRow).TASK_UID && t.MD_PROP_UID == mdPropID && !t.IsDATE_VALUENull()).DATE_VALUE; else return null; } else if (type == CustomFieldType.PMT || type == CustomFieldType.ReasonRecovery) { if ((dataRow.Table.DataSet as ProjectDataSet).TaskCustomFields.Any(t => t.TASK_UID == (dataRow as ProjectDataSet.TaskRow).TASK_UID && t.MD_PROP_UID == mdPropID && !t.IsTEXT_VALUENull())) return (dataRow.Table.DataSet as ProjectDataSet).TaskCustomFields.First(t => t.TASK_UID == (dataRow as ProjectDataSet.TaskRow).TASK_UID && t.MD_PROP_UID == mdPropID && !t.IsTEXT_VALUENull()).TEXT_VALUE; else return null; } return null; } catch { return null; } } public static string[] GetValueFromMultiChoice(object oValue, CustomFieldType type) { Repository.Utility.WriteLog("GetValueFromMultiChoice started", System.Diagnostics.EventLogEntryType.Information); StringCollection value = new StringCollection(); if (oValue != null) { string[] fieldValue = oValue.ToString().Split(",".ToCharArray()); for (int i = 0; i < fieldValue.Length; i++) { foreach (string fieldval in fieldValue[i].Split(",".ToCharArray())) { if (fieldval.StartsWith(type.GetString())) { if (!string.IsNullOrEmpty(fieldval)) { value.Add(fieldval); } } } } } if (value.Count == 0) { return new string[0]; } string[] array = new string[value.Count]; value.CopyTo(array, 0); Repository.Utility.WriteLog("GetValueFromMultiChoice completed successfully", System.Diagnostics.EventLogEntryType.Information); return array; } public static DateTime? GetValueAsDateTime(object oValue) { Repository.Utility.WriteLog("GetValueAsDateTime started", System.Diagnostics.EventLogEntryType.Information); DateTime? value = null; if (oValue != null && !string.IsNullOrEmpty(oValue.ToString())) value = Convert.ToDateTime(oValue); Repository.Utility.WriteLog("GetValueAsDateTime completed successfully", System.Diagnostics.EventLogEntryType.Information); return value; } } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using Microsoft.SharePoint; using PMMP; namespace PMMPPresentation { /// <summary> /// /// </summary> public class Configuration { public static string ServiceURL { get { return GetConfigValue(Constants.PROPERTY_NAME_DB_SERVICE_URL); } set { SetConfigValue(Constants.PROPERTY_NAME_DB_SERVICE_URL, value); } } public static string ProjectUID { get { return GetConfigValue(Constants.PROPERTY_NAME_DB_PROJECT_UID); } set { SetConfigValue(Constants.PROPERTY_NAME_DB_PROJECT_UID, value); } } /// <summary> /// Gets a config parameter stored in the web properties bag /// </summary> /// <param name="key">The parameter key</param> /// <returns></returns> private static string GetConfigValue(string key) { string retVal = string.Empty; var web = SPContext.Current.Web; if (web.Properties.ContainsKey(key)) retVal = web.Properties[key]; return retVal; } private static void SetConfigValue(string key, string value) { var web = SPContext.Current.Web; if (web.Properties.ContainsKey(key)) web.Properties[key] = value; else web.Properties.Add(key, value); web.AllowUnsafeUpdates = true; web.Properties.Update(); web.AllowUnsafeUpdates = false; } } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace PMMP { public class GraphDataGroup { public string Type { get; set; } public List<GraphData> Data { get; set; } } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Data; namespace Repository { /// <summary> /// /// </summary> public class TASKDTO { public string LINK_PRED_UID { get; set; } public string TASK_ID { get; set; } public DataRow Row { get; set; } } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Data; namespace Repository { /// <summary> /// /// </summary> public interface IPSIDataSet { DataSet GetDataSet(); DataSet GetChanges(); DataSet GetDelta(DataSet source, DataSet changes); void Update(DataSet ds); } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using Microsoft.SharePoint; namespace PMMP { public class DataHelper { public static string GetValue(object value) { if (value != null) return value.ToString(); return string.Empty; } public static int GetValueAsInteger(object oValue) { int value = 0; if (oValue != null) value = Convert.ToInt32(oValue.ToString()); return value; } public static string[] GetValueFromMultiChoice(object oValue) { string[] value = null; if (oValue != null) { SPFieldMultiChoiceValue fieldValue = new SPFieldMultiChoiceValue(oValue.ToString()); value = new string[fieldValue.Count]; for (int i = 0; i < fieldValue.Count; i++) value[i] = fieldValue[i]; } return value; } public static DateTime? GetValueAsDateTime(object oValue) { DateTime? value = null; if (oValue != null) value = Convert.ToDateTime(oValue); return value; } } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.IO; namespace PMMP { /// <summary> /// /// </summary> interface IDirector { Stream Construct(IBuilder builder, byte[] fileName, string projectGuid); } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using Microsoft.SharePoint; using Repository; using System.Data; using PMMP; using Constants = PMMP.Constants; using System.Collections.Specialized; using SvcProject; namespace PMMP { public class TaskItemRepository { public static void DeleteAllFromList() { SPWeb web=null; if (SPContext.Current != null) web = SPContext.Current.Web; var list = web.Lists.TryGetList(Constants.LIST_NAME_PROJECT_TASKS); if (list != null) { for (int i = list.ItemCount - 1; i >= 0; i--) list.Items[i].Delete(); list.Update(); } } public static DateTime? GetLastUpdateDate() { DateTime? maxValue = null; try { SPWeb web; if (SPContext.Current != null) web = SPContext.Current.Web; else web = new SPSite("http://finweb.contoso.com/sites/PMM").OpenWeb(); SPList objList = web.Lists.TryGetList(Constants.LIST_NAME_PROJECT_TASKS); SPQuery objQuery = new SPQuery(); objQuery.Query = "<OrderBy><FieldRef Name='ModifiedOn' Ascending='False' /></OrderBy><RowLimit>1</RowLimit>"; objQuery.Folder = objList.RootFolder; // Execute the query against the list SPListItemCollection colItems = objList.GetItems(objQuery); if (colItems.Count > 0) { maxValue = Convert.ToDateTime(colItems[0]["ModifiedOn"]); } } catch (Exception ex) { } return maxValue; } public static IList<TaskItemGroup> GetTaskGroups() { IList<TaskItemGroup> retVal = new List<TaskItemGroup>(); SPWeb web; if (SPContext.Current != null) web = SPContext.Current.Web; else web = new SPSite("http://finweb.contoso.com/sites/PMM").OpenWeb(); var list = web.Lists.TryGetList(Constants.LIST_NAME_PROJECT_TASKS); if (list != null) { var dPathsField = list.Fields[Constants.FieldId_DrivingPath] as SPFieldMultiChoice; var dPaths = dPathsField.Choices; var chartTypesField = list.Fields[Constants.FieldId_ShowOn] as SPFieldMultiChoice; var chartTypes = chartTypesField.Choices; dPaths = dPathsField.Choices; foreach (string dPath in dPaths) { var q = new SPQuery(); q.Query += "<Where>" + "<Eq>" + "<FieldRef ID='" + dPathsField.Id + "' />" + "<Value Type='MultiChoice'>" + dPath + "</Value>" + "</Eq>" + //"<OrderBy>" + // "<FieldRef ID='" + startField.Id + "' Ascending='True' />" + //"</OrderBy>" + "</Where>"; int taskCount = -1; var taskItemGroup = new TaskItemGroup { DrivingPath = dPath, TaskItems = new List<TaskItem>() }; string previousTitle = string.Empty; Dictionary<string, string> dictTitle = new Dictionary<string, string>(); int totalUnCompletedtaskCount = 0, totalCompletedTaskCount = 0; List<TaskItem> chartItems = new List<TaskItem>(); List<TaskItemGroup> completedTasks = new List<TaskItemGroup>(); SPListItemCollection collection = list.GetItems(q); int completedTaskCount = -1; DateTime? lastUpdate = GetLastUpdateDate(); TaskItemGroup completedTaskItemGroup = new TaskItemGroup { DrivingPath = dPath, TaskItems = new List<TaskItem>() }; foreach (SPListItem item in collection) { if (item[Constants.FieldId_Deadline] != null) { if (!dictTitle.ContainsKey(dPath.Split(",".ToCharArray())[0])) { dictTitle.Add(dPath.Split(",".ToCharArray())[0], item[Constants.FieldId_Task].ToString()); } } if (item[Constants.FieldId_ShowOn] != null) { chartItems.Add(BuildTaskItem(dPath, item)); } if (item[Constants.FieldId_PercentComplete] != null && (Convert.ToInt32(item[Constants.FieldId_PercentComplete].ToString().Trim().Trim("%".ToCharArray()).Trim()) < 100)) { totalUnCompletedtaskCount++; taskCount++; if (taskCount == 10) { retVal.Add(taskItemGroup); taskItemGroup = new TaskItemGroup { DrivingPath = dPath, TaskItems = new List<TaskItem>() }; taskItemGroup.Title = previousTitle; taskCount = 0; taskItemGroup.TaskItems.Add(BuildTaskItem(dPath, item)); } else { taskItemGroup.TaskItems.Add(BuildTaskItem(dPath, item)); } } else { if (!lastUpdate.HasValue || Convert.ToDateTime(item["ModifiedOn"].ToString()) == lastUpdate.Value) { totalCompletedTaskCount++; completedTaskCount++; if (completedTaskCount == 10) { completedTasks.Add(completedTaskItemGroup); completedTaskItemGroup = new TaskItemGroup { DrivingPath = dPath, TaskItems = new List<TaskItem>() }; completedTaskCount = 0; completedTaskItemGroup.TaskItems.Add(BuildTaskItem(dPath, item)); } else { completedTaskItemGroup.TaskItems.Add(BuildTaskItem(dPath, item)); } } } } if (totalUnCompletedtaskCount % 10 != 0) { retVal.Add(taskItemGroup); } if (totalCompletedTaskCount % 10 != 0) { completedTasks.Add(completedTaskItemGroup); if (totalUnCompletedtaskCount == 0) { retVal.Add(taskItemGroup); } } if (taskItemGroup.TaskItems.Count > 0 || (completedTasks.Count > 0 && completedTasks[0].TaskItems != null && completedTasks[0].TaskItems.Count > 0)) { taskItemGroup.CompletedTaskgroups = completedTasks; taskItemGroup.ChartTaskItems = chartItems; taskItemGroup.Charts = new string[chartTypes.Count]; chartTypes.CopyTo(taskItemGroup.Charts, 0); taskItemGroup.Title = dictTitle.ContainsKey(dPath) ? dictTitle[dPath] : "Driving Path template"; } if (dPath != null && dictTitle.ContainsKey(dPath.Split(",".ToCharArray())[0])) { foreach (TaskItemGroup group in retVal) { if (group.DrivingPath == dPath) { group.Title = dictTitle[dPath.Split(",".ToCharArray())[0]]; } if (group.CompletedTaskgroups != null) { foreach (TaskItemGroup completedGroup in group.CompletedTaskgroups) { completedGroup.Title = dictTitle[dPath.Split(",".ToCharArray())[0]]; } } } } } } if (SPContext.Current == null) web.Dispose(); return retVal; } public static DataSet GetProjectDataSetFromList() { ProjectDataSet projectDataSet = new ProjectDataSet(); DataSet outputDataSet = projectDataSet.Copy(); //add new table DrivingPath outputDataSet.Tables.Add("DrivingPath"); outputDataSet.Tables["DrivingPath"].Columns.Add("PROJ_UID", typeof(String)); outputDataSet.Tables["DrivingPath"].Columns.Add("TASK_DRIVINGPATH_ID", typeof(String)); outputDataSet.Tables["DrivingPath"].Columns.Add("DrivingPathName", typeof(String)); // Add new columns for output DataSet outputDataSet.Tables["Task"].Columns.Add("TASK_PREDECESSORS", typeof(String)); outputDataSet.Tables["Task"].Columns.Add("TASK_DRIVINGPATH_ID", typeof(String)); outputDataSet.Tables["Task"].Columns.Add("TASK_MODIFIED_ON", typeof(DateTime)); //Add new Columns for Custom Fields outputDataSet.Tables["Task"].Columns.Add("CUSTOMFIELD_TEXT", typeof(String)); outputDataSet.Tables["Task"].Columns.Add("CUSTOMFIELD_DESC", typeof(String)); SPWeb web; if (SPContext.Current != null) web = SPContext.Current.Web; else web = new SPSite("http://finweb.contoso.com/sites/PMM").OpenWeb(); var list = web.Lists.TryGetList(Constants.LIST_NAME_PROJECT_TASKS); var dPathsField = list.Fields[Constants.FieldId_DrivingPath] as SPFieldMultiChoice; var dShownField = list.Fields[Constants.FieldId_ShowOn] as SPFieldMultiChoice; Guid guid = Guid.NewGuid(); if (list != null) { for (int i = 0; i < list.ItemCount; i++) { DataRow row = outputDataSet.Tables["Task"].NewRow(); BuildTaskRowFromListItem(row, list.Items[i], guid); outputDataSet.Tables["Task"].Rows.Add(row); } } return outputDataSet; } private static void BuildTaskRowFromListItem(DataRow row, SPListItem sPListItem, Guid guid) { var dPathsField = sPListItem.ParentList.Fields[Constants.FieldId_DrivingPath] as SPFieldMultiChoice; var dShownField = sPListItem.ParentList.Fields[Constants.FieldId_ShowOn] as SPFieldMultiChoice; string dPath = dPathsField.GetFieldValueAsText(sPListItem[Constants.FieldId_DrivingPath]); TaskItem item = BuildTaskItem(dPath, sPListItem); if (item.Deadline.HasValue) { row["TASK_DEADLINE"] = item.Deadline.Value; } else { row["TASK_DEADLINE"] = System.DBNull.Value; } row["TASK_DRIVINGPATH_ID"] = item.DrivingPath; row["TASK_FINISH_DATE"] = item.Finish; row["TASK_ID"] = item.ID; if (item.ModifiedOn.HasValue) { row["TASK_MODIFIED_ON"] = item.ModifiedOn.Value; } row["TASK_PREDECESSORS"] = item.Predecessor; string[] showOnValues = dShownField.GetFieldValueAsText(sPListItem[Constants.FieldId_ShowOn]).Split(",".ToCharArray()); for (int i = 0; i < showOnValues.Count(); i++) { if (!string.IsNullOrEmpty(showOnValues[i])) { showOnValues[i] = "Show On_" + showOnValues[i].Trim(); } } row["CUSTOMFIELD_DESC"] = string.Join(",", showOnValues); row["TASK_START_DATE"] = item.Start; row["TASK_UID"] = item.UniqueID; row["TASK_PCT_COMP"] = item.WorkCompletePercentage; row["PROJ_UID"] = guid.ToString(); } private void AddItemToList() { } private static TaskItem BuildTaskItem(string dPath, SPListItem item) { return new TaskItem { ID = DataHelper.GetValueAsInteger(item.Title), UniqueID = DataHelper.GetValue(item[Constants.FieldId_UniqueID]), DrivingPath = dPath, Task = DataHelper.GetValue(item[Constants.FieldId_Task]), Duration = DataHelper.GetValue(item[Constants.FieldId_Duration]), Predecessor = DataHelper.GetValue(item[Constants.FieldId_Predecessor]), Start = DataHelper.GetValueAsDateTime(item[Constants.FieldId_Start]), Finish = DataHelper.GetValueAsDateTime(item[Constants.FieldId_Finish]), Deadline = DataHelper.GetValueAsDateTime(item[Constants.FieldId_Deadline]), ShowOn = DataHelper.GetValueFromMultiChoice(item[Constants.FieldId_ShowOn]), ModifiedOn = DataHelper.GetValueAsDateTime(item[Constants.FieldId_ModifiedOn]), WorkCompletePercentage = DataHelper.GetValueAsInteger(item[Constants.FieldId_PercentComplete]) }; } public static void UpdateTasksList(string serviceUrl, Guid projectUID) { DataRepository.ClearImpersonation(); if (DataRepository.P14Login(serviceUrl)) { DataAccess dataAccess = new Repository.DataAccess(projectUID); DataSet dataset = dataAccess.ReadProject(TaskItemRepository.GetProjectDataSetFromList()); DataTable tasksDataTable = dataset.Tables["Task"]; DataTable tDeletedRows = tasksDataTable.GetChanges(DataRowState.Deleted); var queryTasks = (from m in tasksDataTable.GetChanges(DataRowState.Added | DataRowState.Modified | DataRowState.Unchanged).AsEnumerable() select new TaskItem { ID = m.Field<int>("TASK_ID"), UniqueID = m.Field<Guid>("TASK_UID").ToString(), DrivingPath = m.Field<String>("TASK_DRIVINGPATH_ID"), Task = m.Field<String>("TASK_NAME"), Predecessor = m.Field<String>("TASK_PREDECESSORS"), Start = m.Field<DateTime?>("TASK_START_DATE"), Finish = m.Field<DateTime?>("TASK_FINISH_DATE"), Deadline = m.Field<DateTime?>("TASK_DEADLINE"), ShowOn = GetShownOnColumnValue(m.Field<String>("CUSTOMFIELD_DESC")), ModifiedOn = m.Field<DateTime?>("TASK_MODIFIED_ON"), WorkCompletePercentage = m.Field<int>("TASK_PCT_COMP") }); var items = queryTasks.ToList(); SPWeb web; if (SPContext.Current != null) web = SPContext.Current.Web; else web = new SPSite("http://finweb.contoso.com/sites/PMM").OpenWeb(); var list = web.Lists.TryGetList(Constants.LIST_NAME_PROJECT_TASKS); var dPathsField = list.Fields[Constants.FieldId_DrivingPath] as SPFieldMultiChoice; var dShownField = list.Fields[Constants.FieldId_ShowOn] as SPFieldMultiChoice; var dIdField = list.Fields[Constants.FieldId_UniqueID] as SPFieldGuid; if (list != null) { if (tDeletedRows != null && tDeletedRows.Rows.Count > 0) { foreach (DataRow row in tDeletedRows.Rows) { row.RejectChanges(); var q = new SPQuery(); q.Query += "<Where>" + "<Eq>" + "<FieldRef ID='" + dIdField.Id + "' />" + "<Value Type='Guid'>" + row["TASK_UID"].ToString() + "</Value>" + "</Eq>" + //"<OrderBy>" + // "<FieldRef ID='" + startField.Id + "' Ascending='True' />" + //"</OrderBy>" + "</Where>"; list.GetItems(q)[0].Delete(); row.Delete(); } list.Update(); } foreach (TaskItem task in items) { var q = new SPQuery(); q.Query += "<Where>" + "<Eq>" + "<FieldRef ID='" + dIdField.Id + "' />" + "<Value Type='Text'>" + task.UniqueID + "</Value>" + "</Eq>" + //"<OrderBy>" + // "<FieldRef ID='" + startField.Id + "' Ascending='True' />" + //"</OrderBy>" + "</Where>"; SPListItemCollection listItems = list.GetItems(q); if (listItems.Count > 0) { var existingItem = listItems[0]; BuildListItem(existingItem, task); existingItem.Update(); } else { var newItem = list.Items.Add(); BuildListItem(newItem, task); newItem.Update(); } //web.AllowUnsafeUpdates = true; //web.AllowUnsafeUpdates = false; } } dPathsField.Update(); dShownField.Update(); } } private static void BuildListItem(SPListItem newItem, TaskItem task) { var dPathsField = newItem.ParentList.Fields[Constants.FieldId_DrivingPath] as SPFieldMultiChoice; var dShownField = newItem.ParentList.Fields[Constants.FieldId_ShowOn] as SPFieldMultiChoice; newItem[SPBuiltInFieldId.Title] = task.ID; newItem[Constants.FieldId_UniqueID] = task.UniqueID; SPFieldMultiChoiceValue value = GetDrivingPaths(task.DrivingPath) as SPFieldMultiChoiceValue; if (value != null) { for (int i = 0; i < value.Count; i++) { if (!dPathsField.Choices.Contains(value[i])) { dPathsField.Choices.Add(value[i]); } } } newItem[Constants.FieldId_DrivingPath] = GetDrivingPaths(task.DrivingPath); newItem[Constants.FieldId_Task] = task.Task; newItem[Constants.FieldId_Duration] = (task.Finish.HasValue && task.Start.HasValue) ? task.Finish.Value.Subtract(task.Start.Value).Days.ToString() + " days" : String.Empty; newItem[Constants.FieldId_Predecessor] = task.Predecessor; newItem[Constants.FieldId_Start] = task.Start; newItem[Constants.FieldId_Finish] = task.Finish; newItem[Constants.FieldId_Deadline] = task.Deadline; value = ConvertToMultiChoiceValue(task.ShowOn) as SPFieldMultiChoiceValue; if (value != null) { for (int i = 0; i < value.Count; i++) { if (!dShownField.Choices.Contains(value[i])) { dShownField.Choices.Add(value[i]); } } } newItem[Constants.FieldId_ShowOn] = ConvertToMultiChoiceValue(task.ShowOn); newItem[Constants.FieldId_ModifiedOn] = task.ModifiedOn; newItem[Constants.FieldId_PercentComplete] = task.WorkCompletePercentage; } private static object GetDrivingPaths(string dPaths) { var value = new SPFieldMultiChoiceValue(); if (!String.IsNullOrEmpty(dPaths)) foreach (string dPath in dPaths.Split(',')) value.Add(dPath); return value; } private static string[] GetShownOnColumnValue(string value) { string[] retVal = null; if (value != null) { var vList = new List<string>(); var values = value.Split(','); foreach (string val in values) { if (val.StartsWith("Show On")) vList.Add(val.Split('_')[1]); } if (vList.Count > 0) retVal = vList.ToArray(); } return retVal; } private static object ConvertToMultiChoiceValue(string[] values) { var value = new SPFieldMultiChoiceValue(); if (values != null) foreach (string val in values) value.Add(val); return value; } } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace Repository { /// <summary> /// /// </summary> public static class Constants { public const string TASK_ENTITY_ID = "ebad93e7-2149-410d-9a39-a8680738329d"; public const string LOOKUP_ENTITY_ID = "00008e67-65a3-4898-baaa-d82d995bbb02"; } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Data; namespace Repository { /// <summary> /// /// </summary> public class PSIDataSetFacade { public void Update(IPSIDataSet dataSet) { //Read lookup tables from the project server DataSet source = dataSet.GetDataSet(); //Read DataSet from the database updated by SSIS Package DataSet destination = dataSet.GetChanges(); // Get the delta of the changes merged into the dataset returned DataSet delta = dataSet.GetDelta(source, destination); // Update project server with the changes dataSet.Update(delta); } } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using DocumentFormat.OpenXml.Packaging; using DocumentFormat.OpenXml.Presentation; using System.IO; using DocumentFormat.OpenXml.Drawing.Charts; using System.Reflection; namespace PMMP { public static class PresentationExtensions { static char[] hexDigits = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F'}; public static bool InCurrentFiscalMonth(this DateTime date,Repository.FiscalUnit months) { if (date >= months.From && date <= months.To) return true; else return false; } public static string ToVeryShortDateString(this DateTime date) { string format = "M/d"; return date.ToString(format); } public static string ToHexString(this System.Drawing.Color color) { byte[] bytes = new byte[3]; bytes[0] = color.R; bytes[1] = color.G; bytes[2] = color.B; char[] chars = new char[bytes.Length * 2]; for (int i = 0; i < bytes.Length; i++) { int b = bytes[i]; chars[i * 2] = hexDigits[b >> 4]; chars[i * 2 + 1] = hexDigits[b & 0xF]; } return new string(chars); } public static IEnumerable<SlidePart> GetSlidePartsInOrder(this PresentationPart presentationPart) { Repository.Utility.WriteLog("GetSlidePartsInOrder started", System.Diagnostics.EventLogEntryType.Information); SlideIdList slideIdList = presentationPart.Presentation.SlideIdList; var objects = slideIdList.ChildElements .Cast<SlideId>() .Select(x => presentationPart.GetPartById(x.RelationshipId)) .Cast<SlidePart>(); Repository.Utility.WriteLog("GetSlidePartsInOrder completed successfully", System.Diagnostics.EventLogEntryType.Information); return objects; } public static SlidePart CloneSlide(this SlidePart templatePart, SlideType type) { Repository.Utility.WriteLog("CloneSlide started", System.Diagnostics.EventLogEntryType.Information); // find the presentationPart: makes the API more fluent var presentationPart = templatePart.GetParentParts().OfType<PresentationPart>().Single(); int i = presentationPart.SlideParts.Count(); // clone slide contents var slidePartClone = presentationPart.AddNewPart<SlidePart>("newSlide" + i); slidePartClone.FeedData(templatePart.GetStream(FileMode.Open)); // copy layout part slidePartClone.AddPart(templatePart.SlideLayoutPart, templatePart.GetIdOfPart(templatePart.SlideLayoutPart)); if (type == SlideType.Grid) { foreach (IdPartPair part in templatePart.Parts) { var tPart = templatePart.GetPartById(part.RelationshipId); var embeddedPackagePart = tPart as EmbeddedPackagePart; if (embeddedPackagePart != null) { var newPart = slidePartClone.AddEmbeddedPackagePart(embeddedPackagePart.ContentType); newPart.FeedData(embeddedPackagePart.GetStream()); slidePartClone.ChangeIdOfPart(newPart, templatePart.GetIdOfPart(embeddedPackagePart)); } var vmlDrawingPart = tPart as VmlDrawingPart; if (vmlDrawingPart != null) { var newPart = slidePartClone.AddNewPart<VmlDrawingPart>(); newPart.FeedData(vmlDrawingPart.GetStream()); var drawingImg = vmlDrawingPart.ImageParts.ToList()[0]; var newImgPart = newPart.AddImagePart(drawingImg.ContentType, templatePart.GetIdOfPart(drawingImg)); newImgPart.FeedData(drawingImg.GetStream()); } var imagePart = tPart as ImagePart; if (imagePart != null) { var newPart = slidePartClone.AddImagePart(imagePart.ContentType, templatePart.GetIdOfPart(imagePart)); newPart.FeedData(imagePart.GetStream()); } } } else { foreach (ChartPart cpart in templatePart.ChartParts) { ChartPart newcpart = slidePartClone.AddNewPart<ChartPart>(templatePart.GetIdOfPart(cpart)); newcpart.FeedData(cpart.GetStream()); // copy the embedded excel file EmbeddedPackagePart epart = newcpart.AddEmbeddedPackagePart(cpart.EmbeddedPackagePart.ContentType); epart.FeedData(cpart.EmbeddedPackagePart.GetStream()); // link the excel to the chart newcpart.ChartSpace.GetFirstChild<ExternalData>().Id = newcpart.GetIdOfPart(epart); newcpart.ChartSpace.Save(); } } Repository.Utility.WriteLog("CloneSlide completed successfully", System.Diagnostics.EventLogEntryType.Information); return slidePartClone; } public static void AppendSlide(this PresentationPart presentationPart, SlidePart newSlidePart) { Repository.Utility.WriteLog("AppendSlide started", System.Diagnostics.EventLogEntryType.Information); SlideIdList slideIdList = presentationPart.Presentation.SlideIdList; // find the highest id uint maxSlideId = slideIdList.ChildElements.Cast<SlideId>().Max(x => x.Id.Value); // Insert the new slide into the slide list after the previous slide. var id = maxSlideId + 1; SlideId newSlideId = new SlideId(); slideIdList.Append(newSlideId); newSlideId.Id = id; newSlideId.RelationshipId = presentationPart.GetIdOfPart(newSlidePart); Repository.Utility.WriteLog("AppendSlide completed successfully", System.Diagnostics.EventLogEntryType.Information); } public static string GetString(this CustomFieldType e) { switch (e) { case CustomFieldType.CA: return "Cost Account"; case CustomFieldType.EstFinish: return "CAM Finish"; case CustomFieldType.EstStart: return "CAM Start"; case CustomFieldType.PMT: return "PMT"; case CustomFieldType.ReasonRecovery: return "Reason_Recovery"; case CustomFieldType.ShowOn: return "Show On"; } return null; } } } <file_sep>jQuery(document).ready(function () { FixSharePointFunction(); //To change the content type icon // jQuery(jQuery("body")[0]).bind("DOMSubtreeModified", // function () { // console.log('change'); // var img = jQuery("img[alt='PMM Presentation']"); // if (img) // img.attr("src", "/_layouts/images/lg_icxlsx.png"); // }); //end }); function FixSharePointFunction() { window.oldFunction = window.STSNavigate2; window.STSNavigate2 = function STSNavigate2(event, url) { if (url.indexOf("/_layouts/PMMPresentation/NewPMMPresentation.aspx") == -1) window.oldFunction(event, url); else { if (url.indexOf("IsDlg") == -1) url += "&IsDlg=1"; NewItem2(event, url); } }; }<file_sep>using System; using Microsoft.SharePoint; using Microsoft.SharePoint.WebControls; using Repository; using System.Web.UI.WebControls; using Configuration = PMMPPresentation.Configuration; using Constants = PMMP.Constants; namespace PMMPresentation.Layouts.PMMPresentation { public partial class Settings : LayoutsPageBase { protected void Page_Load(object sender, EventArgs e) { try { //This gets the app pool account SPSecurity.RunWithElevatedPrivileges(() => { var obj = System.Security.Principal.WindowsIdentity.GetCurrent(); lblLoggedInUser.Text = "The Logged in User =" + SPContext.Current.Web.CurrentUser.LoginName; lblAppPoolUser.Text = "The App Pool User =" + System.Security.Principal.WindowsIdentity.GetCurrent().Name; if (!Page.IsPostBack) { // Now impersonating // Access resources using the identity of the authenticated user this.txtServiceURL.Text = Configuration.ServiceURL; this.lnkTemplate.NavigateUrl = String.Format("{0}/{1}", this.Web.Url, Constants.TEMPLATE_FILE_LOCATION); if (!String.IsNullOrEmpty(this.txtServiceURL.Text)) { DataRepository.ClearImpersonation(); // CredentialCache.DefaultNetworkCredentials if (DataRepository.P14Login(this.txtServiceURL.Text)) { var projectList = DataRepository.ReadProjectsList(); this.ddlProject.DataSource = projectList.Tables["Project"]; this.ddlProject.DataTextField = "PROJ_NAME"; this.ddlProject.DataValueField = "PROJ_UID"; this.ddlProject.DataBind(); int index = 0; foreach (ListItem item in this.ddlProject.Items) { if (item.Value == Configuration.ProjectUID) break; index++; } if (index >= this.ddlProject.Items.Count) index = 0; this.ddlProject.SelectedIndex = index; } } } }); } catch (Exception ex) { this.ShowErrorMessage(ex); } } protected void btnLoad_Click(object sender, EventArgs e) { SPSecurity.RunWithElevatedPrivileges(() => { try { if (!String.IsNullOrEmpty(this.txtServiceURL.Text)) { // Access resources using the identity of the authenticated user DataRepository.ClearImpersonation(); if (DataRepository.P14Login(this.txtServiceURL.Text)) { var obj = System.Security.Principal.WindowsIdentity.GetCurrent(); var projectList = DataRepository.ReadProjectsList(); ddlProject.DataSource = projectList.Tables["Project"]; ddlProject.DataTextField = "PROJ_NAME"; ddlProject.DataValueField = "PROJ_UID"; ddlProject.DataBind(); } } } catch (Exception ex) { this.ShowErrorMessage(ex); } }); } protected void btnOK_Click(object sender, EventArgs e) { SPSecurity.RunWithElevatedPrivileges(() => { try { // Access resources using the identity of the authenticated user if (!String.IsNullOrEmpty(this.txtServiceURL.Text) && !String.IsNullOrEmpty(this.ddlProject.SelectedValue)) { var updateList = Configuration.ProjectUID != this.ddlProject.SelectedValue; Configuration.ServiceURL = this.txtServiceURL.Text; Configuration.ProjectUID = this.ddlProject.SelectedValue; if (this.TemplateFileUpload.HasFile) this.Web.Files.Add(Constants.TEMPLATE_FILE_LOCATION, this.TemplateFileUpload.FileBytes, true); this.pnlClose.Visible = true; } } catch (Exception ex) { this.ShowErrorMessage(ex); } }); } protected void btnCancel_Click(object sender, EventArgs e) { this.pnlClose.Visible = true; } private void ShowErrorMessage(Exception ex) { this.lblErrorMessage.Text = String.Format("An exception has ocurred. Message:{0}. Stack Trace:{1}", ex.Message, ex.StackTrace); this.mvMain.ActiveViewIndex = 1; } } } <file_sep>using System; using Microsoft.SharePoint; using Microsoft.SharePoint.WebControls; using System.Linq; using Configuration = PMMPPresentation.Configuration; using Constants = PMMP.Constants; using WCFHelpers; using System.Security.Principal; using Repository; using System.Web; using Microsoft.SharePoint.Utilities; using Microsoft.SharePoint.WebPartPages; namespace PMMPresentation.Layouts.PMMPresentation { /// <summary> /// /// </summary> public partial class NewPMMPresentation : LayoutsPageBase { private Guid ListId { get { return new Guid(this.Request.QueryString["List"]); } } protected void Page_Load(object sender, EventArgs e) { if (!Page.IsPostBack) this.txtDocumentName.Text = String.Format("PMMPresentation_{0}_{1}", this.Web.Title, DateTime.Now.ToString("dMMMyyyy")); } #region Events protected void btnCreate_Click(object sender, EventArgs e) { try { SPSecurity.RunWithElevatedPrivileges(() => { //operation.EndScript("SP.UI.ModalDialog.commonModalDialogClose(1, 'Submitted');"); #region Create document if (!String.IsNullOrEmpty(Configuration.ServiceURL) && !String.IsNullOrEmpty(Configuration.ProjectUID)) { if (DataRepository.P14Login(((string)SPContext.Current.Web.Properties[Constants.PROPERTY_NAME_DB_SERVICE_URL]))) { Utility.WriteLog("Successful P14 Login to the system for Document creation stage", System.Diagnostics.EventLogEntryType.Information); using (var operation = new SPLongOperation(this)) { try { operation.LeadingHTML = "<b>Document creation in Progress...</b>"; operation.TrailingHTML = ""; operation.Begin(); var docName = this.txtDocumentName.Text + ".pptx"; var docLib = this.Web.Lists[this.ListId]; var templateFile = this.Web.GetFile(Constants.TEMPLATE_FILE_LOCATION); PMMP.PMPDocument document = new PMMP.PMPDocument(); var stream = document.CreateDocument("Presentation", templateFile.OpenBinary(), Configuration.ProjectUID); SPListItem item = docLib.RootFolder.Files.Add(docName, stream, true).Item; var pmmContentType = (from SPContentType ct in docLib.ContentTypes where ct.Name.ToLower() == Constants.CT_PMM_NAME.ToLower() select ct).FirstOrDefault(); if (pmmContentType != null) { item[SPBuiltInFieldId.ContentTypeId] = pmmContentType.Id; item[Constants.FieldId_Comments] = txtComment.Text; item.Update(); } } catch (Exception ex) { this.ShowErrorMessage(ex); SPUtility.TransferToErrorPage(ex.ToString()); } finally { EndOperation(operation); } } } else { Utility.WriteLog("An error has ocurred in trying to P14 Login to the system", System.Diagnostics.EventLogEntryType.Error); this.ShowErrorMessage("An error has ocurred in trying to P14 Login to the system"); } } else { this.ShowErrorMessage("An error has ocurred trying to get the configuration parameters"); Utility.WriteLog("An error has ocurred trying to get the configuration parameters", System.Diagnostics.EventLogEntryType.Error); } #endregion }); } catch (Exception ex) { this.ShowErrorMessage(ex); } this.pnlSubmit.Visible = true; } protected void EndOperation(SPLongOperation operation) { HttpContext context = HttpContext.Current; if (context.Request.QueryString["IsDlg"] != null) { context.Response.Write("<script type='text/javascript'>window.frameElement.commitPopup();</script>"); context.Response.Flush(); context.Response.End(); } else { string url = SPContext.Current.Web.Url; operation.End(url, SPRedirectFlags.CheckUrl, context, string.Empty); } } protected void btnCancel_Click(object sender, EventArgs e) { var docLib = this.Web.Lists[this.ListId]; this.pnlClose.Visible = true; } #endregion #region Private methods private void ShowErrorMessage(Exception ex) { this.lblErrorMessage.Text = String.Format("An exception has ocurred. Message:{0}. Stack Trace:{1}", ex.Message, ex.StackTrace); this.mvMain.ActiveViewIndex = 1; } private void ShowErrorMessage(string message) { this.lblErrorMessage.Text = message; this.mvMain.ActiveViewIndex = 1; } #endregion } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Diagnostics; using System.Security.Principal; namespace Repository { public static class Utility { public static void WriteLog(string message, EventLogEntryType type) { //WindowsIdentity winId = (WindowsIdentity)System.Security.Principal.WindowsIdentity.GetCurrent(); //WindowsImpersonationContext ctx = null; try { // Start impersonating //ctx = winId.Impersonate(); // Now impersonating // Access resources using the identity of the authenticated user System.Diagnostics.EventLog appLog = new System.Diagnostics.EventLog(); appLog.Source = "PMM Presentation"; appLog.WriteEntry(message, type); } // Prevent exceptions from propagating catch { } //finally //{ // // Revert impersonation // if (ctx != null) // ctx.Undo(); //} } } }<file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using DocumentFormat.OpenXml.Spreadsheet; using DocumentFormat.OpenXml; using System.Data; namespace PMMP { public static class WorkbookUtilities { public static void ReplicateRow(SheetData sheetData, int refRowIndex, int count) { IEnumerable<Row> rows = sheetData.Descendants<Row>().Where(r => r.RowIndex.Value > refRowIndex); foreach (Row row in rows) IncrementIndexes(row, count); Row refRow = GetRow(sheetData, refRowIndex); for (int i = 0; i < count; i++) { Row newRow = (Row)refRow.Clone(); IncrementIndexes(newRow, i + 1); sheetData.InsertAfter(newRow, GetRow(sheetData, refRowIndex + i)); } } public static void LoadSheetData(SheetData sheetData, DataTable data, int rowIndex, int columnindex) { //Populate data int startRow = rowIndex + 1; for (int i = 0; i < data.Rows.Count; i++) { Row row = GetRow(sheetData, i + startRow); if (row == null) { row = CreateContentRow(data.Rows[i], i + startRow, columnindex); sheetData.AppendChild(row); } else PopulateRow(data.Rows[i], columnindex, row); } } private static Row GetRow(SheetData sheetData, int rowIndex) { return sheetData.Elements<Row>().Where(r => r.RowIndex == rowIndex).First(); } private static Cell GetCell(Row row, int columnIndex) { return row.Elements<Cell>().FirstOrDefault(c => string.Compare(c.CellReference.Value, GetColumnName(columnIndex) + row.RowIndex, true) == 0); } private static string GetColumnName(int columnIndex) { int dividend = columnIndex; string columnName = String.Empty; int modifier; while (dividend > 0) { modifier = (dividend - 1) % 26; columnName = Convert.ToChar(65 + modifier).ToString() + columnName; dividend = (int)((dividend - modifier) / 26); } return columnName; } private static Row CreateContentRow(DataRow dataRow, int rowIndex, int columnindex) { Row row = new Row { RowIndex = (UInt32)rowIndex }; PopulateRow(dataRow, columnindex, row); return row; } private static void PopulateRow(DataRow dataRow, int columnindex, Row row) { int rowIndex = (int)row.RowIndex.Value; for (int i = 0; i < dataRow.Table.Columns.Count; i++) { int index = i + columnindex + 1; Cell dataCell = GetCell(row, index); if (dataCell == null) { dataCell = CreateCell(i + columnindex + 1, rowIndex, dataRow[i]); row.AppendChild(dataCell); } else { if (dataCell.DataType != null && dataCell.DataType == CellValues.SharedString) dataCell.DataType = CellValues.String; if (dataRow[i].GetType() == typeof(DateTime)) dataCell.CellValue.Text = ((DateTime)dataRow[i]).ToOADate().ToString(); else dataCell.CellValue.Text = dataRow[i].ToString(); } } } private static Cell CreateCell(int columnIndex, int rowIndex, object cellValue) { Cell cell = new Cell(); cell.CellReference = GetColumnName(columnIndex) + rowIndex; var value = cellValue.ToString(); Decimal number; if (cellValue.GetType() == typeof(Decimal) || Decimal.TryParse(value, out number)) { cell.DataType = CellValues.Number; } else if (cellValue.GetType() == typeof(DBNull)) { cell.DataType = CellValues.String; value = "NULL"; } else if (cellValue.GetType() == typeof(DateTime)) { cell.StyleIndex = (UInt32Value)12U; value = (cellValue as DateTime?).Value.ToOADate().ToString(); } else if (cellValue.GetType() == typeof(Boolean)) { value = ((bool)cellValue) ? "1" : "0"; } else { cell.DataType = CellValues.String; } cell.CellValue = new CellValue(value); return cell; } private static void IncrementIndexes(Row row, int increment) { uint newRowIndex; newRowIndex = System.Convert.ToUInt32(row.RowIndex.Value + increment); foreach (Cell cell in row.Elements<Cell>()) { string cellReference = cell.CellReference.Value; cell.CellReference = new StringValue(cellReference.Replace(row.RowIndex.Value.ToString(), newRowIndex.ToString())); } row.RowIndex = new UInt32Value(newRowIndex); } } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using DocumentFormat.OpenXml.Packaging; using System.IO; namespace PMMP { public class PresentationDocumentFactory { public static Stream CreateDocument(string template, byte[] fileName,string projectGuid) { Repository.Utility.WriteLog("CreateDocument started", System.Diagnostics.EventLogEntryType.Information); switch (template) { case "Presentation": PresentationDirector director = new PresentationDirector(); Repository.Utility.WriteLog("CreateDocument completed successfuly", System.Diagnostics.EventLogEntryType.Information); return director.Construct(new PresentationBuilder(), fileName, projectGuid); } Repository.Utility.WriteLog("CreateDocument completed successfuly", System.Diagnostics.EventLogEntryType.Information); return null; } } }<file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace PMMP { public class GraphData { public float Count {get;set;} public string Title {get;set;} } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using DocumentFormat.OpenXml.Drawing.Charts; using DocumentFormat.OpenXml.Packaging; using System.Data; namespace PMMP { public class BarChartUtilities { public static void LoadChartData(ChartPart chartPart, System.Data.DataTable dataTable) { Repository.Utility.WriteLog("LoadChartData started", System.Diagnostics.EventLogEntryType.Information); Chart chart = chartPart.ChartSpace.Elements<Chart>().First(); BarChart bc1 = chart.Descendants<BarChart>().FirstOrDefault(); BarChart bc2 = chart.Descendants<BarChart>().ElementAt(1); DateTime maxAxisvAlue=DateTime.MinValue; DateTime minAxisvAlue = DateTime.MaxValue; DateTime maxFinishValue = dataTable.AsEnumerable().Select(t=>t.Field<DateTime>("Finish")).Max(); DateTime maxBFinishvalue = dataTable.AsEnumerable().Select(t => t.Field<DateTime>("BaseLineFinish")).Max(); maxAxisvAlue = maxBFinishvalue > maxFinishValue ? maxBFinishvalue : maxFinishValue; DateTime minStartValue = dataTable.AsEnumerable().Select(t => t.Field<DateTime>("Start")).Min(); DateTime minBStartvalue = dataTable.AsEnumerable().Select(t => t.Field<DateTime>("BaseLineStart")).Min(); minAxisvAlue = minBStartvalue < minStartValue ? minBStartvalue : minStartValue; IEnumerable<ValueAxis> axes = chart.Descendants<ValueAxis>(); foreach (ValueAxis axis in axes) { if (maxAxisvAlue != DateTime.MaxValue) { axis.Scaling.MaxAxisValue.Val = maxAxisvAlue.ToOADate(); } if (minAxisvAlue != DateTime.MinValue) { axis.Scaling.MinAxisValue.Val = minAxisvAlue.ToOADate(); } if (dataTable.Rows.Count > 0) { axis.Elements<MajorUnit>().FirstOrDefault().Val = (axis.Scaling.MaxAxisValue.Val - axis.Scaling.MinAxisValue.Val) / dataTable.Rows.Count; } } if (bc1 != null && bc2 != null) { BarChartSeries bcs1 = bc1.Elements<BarChartSeries>().FirstOrDefault(); BarChartSeries bcs2 = bc1.Elements<BarChartSeries>().ElementAt(1); BarChartSeries bcs3 = bc2.Elements<BarChartSeries>().FirstOrDefault(); BarChartSeries bcs4 = bc2.Elements<BarChartSeries>().ElementAt(1); if (bcs1 != null && bcs2 != null) { var categories = bcs1.Descendants<DocumentFormat.OpenXml.Drawing.Charts.CategoryAxisData>().First(); StringReference csr = categories.Descendants<StringReference>().First(); csr.Formula.Text = String.Format("Sheet1!$A$2:$A${0}", dataTable.Rows.Count + 1); StringCache sc = categories.Descendants<StringCache>().First(); CreateStringPoints(sc, dataTable.Rows.Count,false); //Series 1 var values1 = bcs1.Descendants<DocumentFormat.OpenXml.Drawing.Charts.Values>().First(); NumberReference vnr1 = values1.Descendants<NumberReference>().First(); vnr1.Formula.Text = String.Format("Sheet1!$B$2:$B${0}", dataTable.Rows.Count + 1); NumberingCache nc1 = values1.Descendants<NumberingCache>().First(); CreateNumericPoints(nc1, dataTable.Rows.Count,false); //Series 2 var values2 = bcs2.Descendants<DocumentFormat.OpenXml.Drawing.Charts.Values>().First(); NumberReference vnr2 = values2.Descendants<NumberReference>().First(); vnr2.Formula.Text = String.Format("Sheet1!$C$2:$C${0}", dataTable.Rows.Count + 1); NumberingCache nc2 = values2.Descendants<NumberingCache>().First(); CreateNumericPoints(nc2, dataTable.Rows.Count, false); //Series 3 var values3 = bcs3.Descendants<DocumentFormat.OpenXml.Drawing.Charts.Values>().First(); NumberReference vnr3 = values3.Descendants<NumberReference>().First(); vnr3.Formula.Text = String.Format("Sheet1!$D$2:$D${0}", dataTable.Rows.Count + 1); NumberingCache nc3 = values3.Descendants<NumberingCache>().First(); CreateNumericPoints(nc3, dataTable.Rows.Count,false); //Series 4 var values4 = bcs4.Descendants<DocumentFormat.OpenXml.Drawing.Charts.Values>().First(); NumberReference vnr4 = values4.Descendants<NumberReference>().First(); vnr4.Formula.Text = String.Format("Sheet1!$E$2:$E${0}", dataTable.Rows.Count + 1); NumberingCache nc4 = values4.Descendants<NumberingCache>().First(); CreateNumericPoints(nc4, dataTable.Rows.Count, false); for (int i = 0; i < dataTable.Rows.Count; i++) { NumericValue sv = sc.Elements<StringPoint>().ElementAt(i).Elements<NumericValue>().FirstOrDefault(); sv.Text = dataTable.Rows[i]["Task"].ToString() + " | " + ((DateTime)dataTable.Rows[i]["Finish"]).ToString("MM/dd"); NumericValue nv1 = nc1.Elements<NumericPoint>().ElementAt(i).Elements<NumericValue>().FirstOrDefault(); NumericValue nv2 = nc2.Elements<NumericPoint>().ElementAt(i).Elements<NumericValue>().FirstOrDefault(); NumericValue nv3 = nc3.Elements<NumericPoint>().ElementAt(i).Elements<NumericValue>().FirstOrDefault(); NumericValue nv4 = nc4.Elements<NumericPoint>().ElementAt(i).Elements<NumericValue>().FirstOrDefault(); nv1.Text = ((DateTime)dataTable.Rows[i]["Start"]).ToOADate().ToString(); nv2.Text = ((DateTime)dataTable.Rows[i]["Finish"] - (DateTime)dataTable.Rows[i]["Start"]).TotalDays > 4 ? ((DateTime)dataTable.Rows[i]["Finish"] - (DateTime)dataTable.Rows[i]["Start"]).TotalDays.ToString() : "5"; nv3.Text = ((DateTime)dataTable.Rows[i]["BaseLineStart"]).ToOADate().ToString(); nv4.Text = ((DateTime)dataTable.Rows[i]["BaseLineFinish"] - (DateTime)dataTable.Rows[i]["BaseLineStart"]).TotalDays > 4 ? ((DateTime)dataTable.Rows[i]["BaseLineFinish"] - (DateTime)dataTable.Rows[i]["BaseLineStart"]).TotalDays.ToString() : "5"; } } } Repository.Utility.WriteLog("LoadChartData completed successfully", System.Diagnostics.EventLogEntryType.Information); } private static void CreateNumericPoints(NumberingCache nc, int count,bool deleteClone) { Repository.Utility.WriteLog("CreateNumericPoints started", System.Diagnostics.EventLogEntryType.Information); var np1 = nc.Elements<NumericPoint>().ElementAt(0); for (int i = nc.Elements<NumericPoint>().Count() - 1; i > 0; i--) { nc.Elements<NumericPoint>().ElementAt(i).Remove(); } for (int i = 0; i < count; i++) { var npref = nc.Elements<NumericPoint>().ElementAt(i); var np = (NumericPoint)np1.Clone(); np.Index = (UInt32)i + 1; nc.InsertAfter(np, npref); } np1.Remove(); Repository.Utility.WriteLog("CreateNumericPoints completed successfully", System.Diagnostics.EventLogEntryType.Information); } private static void CreateStringPoints(StringCache sc, int count,bool deleteClone) { Repository.Utility.WriteLog("CreateStringPoints started", System.Diagnostics.EventLogEntryType.Information); var sp1 = sc.Elements<StringPoint>().ElementAt(0); for (int i = sc.Elements<StringPoint>().Count() - 1; i > 0; i--) { sc.Elements<StringPoint>().ElementAt(i).Remove(); } for (int i = 0; i < count; i++) { var spref = sc.Elements<StringPoint>().ElementAt(i); var sp = (StringPoint)sp1.Clone(); sp.Index = (UInt32)i + 1; sc.InsertAfter(sp, spref); } sp1.Remove(); Repository.Utility.WriteLog("CreateStringPoints completed successfully", System.Diagnostics.EventLogEntryType.Information); } internal static void LoadChartData(ChartPart chartPart, List<GraphDataGroup> list) { Repository.Utility.WriteLog("LoadChartData started", System.Diagnostics.EventLogEntryType.Information); Chart chart = chartPart.ChartSpace.Elements<Chart>().First(); BarChart bc = chart.Descendants<BarChart>().FirstOrDefault(); LineChart lc = chart.Descendants<LineChart>().FirstOrDefault(); BarChartSeries bcs1 = null; BarChartSeries bcs2 = null; BarChartSeries bcs3 = null; BarChartSeries bcs4 = null; NumberingCache nc1 = null; NumberingCache nc2 = null; NumberingCache nc3 = null; NumberingCache nc4 = null; NumberingCache nc5 = null; NumberingCache nc6 = null; StringCache sc = null; if (bc != null) { bcs1 = bc.Elements<BarChartSeries>().ElementAt(0); bcs2 = bc.Elements<BarChartSeries>().ElementAt(1); bcs3 = bc.Elements<BarChartSeries>().ElementAt(2); bcs4 = bc.Elements<BarChartSeries>().ElementAt(3); } LineChartSeries lcs1 = lc.Elements<LineChartSeries>().ElementAt(0); LineChartSeries lcs2 = lc.Elements<LineChartSeries>().ElementAt(1); LineChartSeries lcs3=null; if(lc.Elements<LineChartSeries>().Count() > 2) lcs3 = lc.Elements<LineChartSeries>().ElementAt(2); LineChartSeries lcs4=null; if (lc.Elements<LineChartSeries>().Count() > 3) lcs4 = lc.Elements<LineChartSeries>().ElementAt(3); int count = 0; for (int j = 0; j < list.Count; j++) { try { GraphDataGroup graphGroup = list[j]; DocumentFormat.OpenXml.Drawing.Charts.CategoryAxisData categories; if (graphGroup.Type == "BES" || graphGroup.Type == "BEFS" || graphGroup.Type == "BEFF" || graphGroup.Type == "BEF") { categories = lcs1.Descendants<DocumentFormat.OpenXml.Drawing.Charts.CategoryAxisData>().ToList()[count]; } else { categories = bcs1.Descendants<DocumentFormat.OpenXml.Drawing.Charts.CategoryAxisData>().ToList()[count]; } if (graphGroup.Type == "CS" || graphGroup.Type == "CF" || graphGroup.Type == "BES") { StringReference csr = categories.Descendants<StringReference>().First(); //csr.Formula.Text = String.Format("Sheet1!$A$2:$A${0}", list[j].Data.Count - 1); sc = categories.Descendants<StringCache>().First(); CreateStringPoints(sc, list[j].Data.Count,true); } //Series 1 DocumentFormat.OpenXml.Drawing.Charts.Values values1; if (graphGroup.Type == "BES" || graphGroup.Type == "BEFS" || graphGroup.Type == "BEFF" || graphGroup.Type == "BEF") { values1 = lcs1.Descendants<DocumentFormat.OpenXml.Drawing.Charts.Values>().First(); } else { values1 = bcs1.Descendants<DocumentFormat.OpenXml.Drawing.Charts.Values>().First(); } if (graphGroup.Type == "CS" || graphGroup.Type == "CF" || graphGroup.Type == "BES" ) { NumberReference vnr1 = values1.Descendants<NumberReference>().First(); //vnr1.Formula.Text = String.Format("Sheet1!$B$2:$B${0}", list[j].Data.Count - 1); nc1 = values1.Descendants<NumberingCache>().First(); CreateNumericPoints(nc1, list[j].Data.Count,true); } //Series 2 DocumentFormat.OpenXml.Drawing.Charts.Values values2; if (graphGroup.Type == "BES" || graphGroup.Type == "BEFS" || graphGroup.Type == "BEFF" || graphGroup.Type == "BEF") { values2 = lcs2.Descendants<DocumentFormat.OpenXml.Drawing.Charts.Values>().First(); } else { values2 = bcs2.Descendants<DocumentFormat.OpenXml.Drawing.Charts.Values>().First(); } if (graphGroup.Type == "FCS" || graphGroup.Type == "FCF" || graphGroup.Type == "BEF") { nc2 = values2.Descendants<NumberingCache>().First(); NumberReference vnr2 = values2.Descendants<NumberReference>().First(); //vnr2.Formula.Text = String.Format("Sheet1!$C$2:$C${0}", list[j].Data.Count - 1 + 1); CreateNumericPoints(nc2, list[j].Data.Count,true); } //Series 3 DocumentFormat.OpenXml.Drawing.Charts.Values values3; if (graphGroup.Type == "BES" || graphGroup.Type == "BEFS" || graphGroup.Type == "BEFF" || graphGroup.Type == "BEF") { values3 = lcs3.Descendants<DocumentFormat.OpenXml.Drawing.Charts.Values>().First(); } else { values3 = bcs3.Descendants<DocumentFormat.OpenXml.Drawing.Charts.Values>().First(); } if (graphGroup.Type == "DQ" || graphGroup.Type == "DQF" || graphGroup.Type == "BEFS") { NumberReference vnr3 = values3.Descendants<NumberReference>().First(); //vnr3.Formula.Text = String.Format("Sheet1!$D$2:$D${0}", list[j].Data.Count); nc3 = values3.Descendants<NumberingCache>().First(); CreateNumericPoints(nc3, list[j].Data.Count,true); } //Series 4 DocumentFormat.OpenXml.Drawing.Charts.Values values4; if (graphGroup.Type == "BES" || graphGroup.Type == "BEFS" || graphGroup.Type == "BEFF" || graphGroup.Type == "BEF") { values4 = lcs4.Descendants<DocumentFormat.OpenXml.Drawing.Charts.Values>().First(); } else { values4 = bcs4.Descendants<DocumentFormat.OpenXml.Drawing.Charts.Values>().First(); } if (graphGroup.Type == "FDQ" || graphGroup.Type == "FDQF" || graphGroup.Type == "BEFS") { NumberReference vnr4 = values4.Descendants<NumberReference>().First(); //vnr4.Formula.Text = String.Format("Sheet1!$E$2:$E${0}", list[j].Data.Count); nc4 = values4.Descendants<NumberingCache>().First(); CreateNumericPoints(nc4, list[j].Data.Count,true); } if (graphGroup.Type == "BES" || graphGroup.Type == "BEFS" || graphGroup.Type == "BEFF" || graphGroup.Type == "BEF") { goto xy; } if (graphGroup.Type == "CDQ" || graphGroup.Type == "CDQF") { //Series 5 var values5 = lcs1.Descendants<DocumentFormat.OpenXml.Drawing.Charts.Values>().First(); NumberReference vnr5 = values5.Descendants<NumberReference>().First(); //vnr5.Formula.Text = String.Format("Sheet1!$F$2:$F${0}", list[j].Data.Count); nc5 = values5.Descendants<NumberingCache>().First(); CreateNumericPoints(nc5, list[j].Data.Count, true); } if (graphGroup.Type == "FCDQ" || graphGroup.Type == "FCDQF") { //Series 6 var values6 = lcs2.Descendants<DocumentFormat.OpenXml.Drawing.Charts.Values>().First(); NumberReference vnr6 = values6.Descendants<NumberReference>().First(); //vnr6.Formula.Text = String.Format("Sheet1!$G$2:$G${0}", list[j].Data.Count); nc6 = values6.Descendants<NumberingCache>().First(); CreateNumericPoints(nc6, list[j].Data.Count, true); } xy: for (int i = 0; i < graphGroup.Data.Count; i++) { try { switch (graphGroup.Type) { case "CF": case "CS": case "BES": NumericValue nv1 = nc1.Elements<NumericPoint>().ElementAt(i).Elements<NumericValue>().FirstOrDefault(); nv1.Text = graphGroup.Data[i].Count.ToString(); NumericValue sv = sc.Elements<StringPoint>().ElementAt(i).Elements<NumericValue>().FirstOrDefault(); sv.Text = graphGroup.Data[i].Title.ToString(); break; case "FCF": case "FCS": case "BEF": NumericValue nv2 = nc2.Elements<NumericPoint>().ElementAt(i).Elements<NumericValue>().FirstOrDefault(); nv2.Text = graphGroup.Data[i].Count.ToString(); break; case "DQF": case "DQ": case "BEFS": NumericValue nv3 = nc3.Elements<NumericPoint>().ElementAt(i).Elements<NumericValue>().FirstOrDefault(); nv3.Text = graphGroup.Data[i].Count.ToString(); break; case "FDQF": case "FDQ": case "BEFF": NumericValue nv4 = nc4.Elements<NumericPoint>().ElementAt(i).Elements<NumericValue>().FirstOrDefault(); nv4.Text = graphGroup.Data[i].Count.ToString(); break; case "CDQF": case "CDQ": NumericValue nv5 = nc5.Elements<NumericPoint>().ElementAt(i).Elements<NumericValue>().FirstOrDefault(); nv5.Text = graphGroup.Data[i].Count.ToString(); break; case "FCDQF": case "FCDQ": NumericValue nv6 = nc6.Elements<NumericPoint>().ElementAt(i).Elements<NumericValue>().FirstOrDefault(); nv6.Text = graphGroup.Data[i].Count.ToString(); break; } } catch { continue; } } } catch { continue; } } Repository.Utility.WriteLog("LoadChartData completed successfully", System.Diagnostics.EventLogEntryType.Information); } } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace PMMP { /// <summary> /// /// </summary> public enum CustomFieldType { ShowOn, CA , PMT, ReasonRecovery, EstStart, EstFinish } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.ComponentModel; using System.Data; using Microsoft.SharePoint; namespace PMMP { public class TaskItemGroup { string _title; public string Title { get { var retVal = this._title; return retVal; } set { this._title = value; } } public string DrivingPath { get; set; } public string[] Charts { get; set; } public IList<TaskItem> TaskItems { get; set; } public IList<TaskItem> ChartTaskItems { get; set; } public IList<TaskItemGroup> CompletedTaskgroups { get; set; } public DataTable TaskItemsDataTable { get { return this.ToDataTable(this.TaskItems, SlideType.Grid); } } public DataTable GetChartDataTable(string chartName) { Repository.Utility.WriteLog("GetChartDataTable started", System.Diagnostics.EventLogEntryType.Information); IList<TaskItem> tasks = new List<TaskItem>(); string[] values = chartName.Split(",".ToCharArray()); for (int i = 0; i < values.Count(); i++) { foreach (TaskItem item in this.ChartTaskItems) { foreach(string showOn in item.ShowOn) { if (!string.IsNullOrEmpty(showOn) && showOn.Contains(values[i])) { tasks.Add(item); } } } } Repository.Utility.WriteLog("GetChartDataTable completed successfully", System.Diagnostics.EventLogEntryType.Information); if (tasks.Count > 0) return this.ToDataTable(tasks, SlideType.Chart); else return null; } private DataTable ToDataTable(IList<TaskItem> data, SlideType type) { Repository.Utility.WriteLog("ToDataTable started", System.Diagnostics.EventLogEntryType.Information); PropertyDescriptorCollection props = TypeDescriptor.GetProperties(typeof(TaskItem)); DataTable table = new DataTable(); for (int i = 0; i < props.Count; i++) { PropertyDescriptor prop = props[i]; if (IsValidColumn(prop.Name, type)) table.Columns.Add(this.GetColumnName(prop.Name), GetColumnType(prop.PropertyType)); } object[] values = new object[table.Columns.Count]; foreach (TaskItem item in data) { var index = 0; for (int i = 0; i < props.Count; i++) { if (IsValidColumn(props[i].Name, type)) { values[index] = this.GetValue(props[i], item, type); index++; } } table.Rows.Add(values); } Repository.Utility.WriteLog("ToDataTable completed successfully", System.Diagnostics.EventLogEntryType.Information); return table; } private bool IsValidColumn(string name, SlideType type) { bool retVal = true; if (type == SlideType.Grid && name == "Deadline" || name == "ShowOn") retVal = false; else if (name != "Task" && name != "Start" && name != "Duration" && name != "BaseLineStart" && name != "BLDuration" && name !="Finish" && name!= "BaseLineFinish" && name != "ID") { retVal = false; } return retVal; } private string GetColumnName(string propName) { string retVal = propName; switch (propName) { case "BaseLineStart": return "BaseLineStart"; case "BLDuration": return "BLDuration"; case "Duration": return "Duration"; case "ID": retVal = "ID"; break; case "UniqueID": retVal = "UniqueID"; break; case "DrivingPath": retVal = "Driving Path"; break; case "Task": retVal = "Task"; break; case "Predecessor": retVal = "Predecessor"; break; case "Start": retVal = "Start"; break; case "Finish": retVal = "Finish"; break; case "Deadline": retVal = "Deadline"; break; case "ShowOn": retVal = "Show On"; break; default: break; } return retVal; } private Type GetColumnType(Type type) { Type retVal = type; if (type == typeof(DateTime?)) retVal = typeof(DateTime); return retVal; } private object GetValue(PropertyDescriptor prop, TaskItem item, SlideType type) { Repository.Utility.WriteLog("GetValue started", System.Diagnostics.EventLogEntryType.Information); object retVal = prop.GetValue(item); //TODO Delete Later //if (type == SlideType.Chart && prop.Name == "Task") // retVal = String.Format("{0}: {1}", item.Task, item.Finish.HasValue ? item.Finish.Value.ToString("MM/dd") : String.Empty); Repository.Utility.WriteLog("GetValue completed successfully", System.Diagnostics.EventLogEntryType.Information); return retVal; } } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using DocumentFormat.OpenXml.Spreadsheet; using DocumentFormat.OpenXml; using System.Data; using DocumentFormat.OpenXml.Drawing.Spreadsheet; using DocumentFormat.OpenXml.Packaging; using DocumentFormat.OpenXml.Drawing; namespace PMMP { public static class WorkbookUtilities { public static void ReplicateRow(SheetData sheetData, int refRowIndex, int count) { Repository.Utility.WriteLog("ReplicateRow started", System.Diagnostics.EventLogEntryType.Information); IEnumerable<Row> rows = sheetData.Descendants<Row>().Where(r => r.RowIndex.Value > refRowIndex); foreach (Row row in rows) IncrementIndexes(row, count); Row refRow = GetRow(sheetData, refRowIndex); for (int i = 0; i < count; i++) { Row newRow = (Row)refRow.Clone(); IncrementIndexes(newRow, i + 1); //sheetData.InsertAt(newRow, i + 1); sheetData.InsertAfter(newRow, GetRow(sheetData, refRowIndex + i)); } Repository.Utility.WriteLog("ReplicateRow completed successfully", System.Diagnostics.EventLogEntryType.Information); } public static void LoadSheetData(SheetData sheetData, DataTable data, int rowIndex, int columnindex) { //Populate data Repository.Utility.WriteLog("LoadSheetData started", System.Diagnostics.EventLogEntryType.Information); int startRow = rowIndex + 1; for (int i = 0; i < data.Rows.Count; i++) { Row row = GetRow(sheetData, i + startRow); if (row == null) { row = CreateContentRow(data.Rows[i], i + startRow, columnindex); sheetData.AppendChild(row); } else { PopulateRow(data.Rows[i], i + 2, row); } } // // Position the chart on the worksheet using a TwoCellAnchor object. // drawingsPart.WorksheetDrawing = new WorksheetDrawing(); // TwoCellAnchor twoCellAnchor = drawingsPart.WorksheetDrawing.AppendChild<TwoCellAnchor>(new TwoCellAnchor()); // twoCellAnchor.Append(new DocumentFormat.OpenXml.Drawing.Spreadsheet.FromMarker(new ColumnId("1"), // new RowId("2") // )); // twoCellAnchor.Append(new DocumentFormat.OpenXml.Drawing.Spreadsheet.ToMarker(new ColumnId("5"), // new RowId(data.Rows.Count.ToString()) // )); // twoCellAnchor.Append(new ClientData()); // // Save the WorksheetDrawing object. // drawingsPart.WorksheetDrawing.Save(); Repository.Utility.WriteLog("LoadSheetData completed successfully", System.Diagnostics.EventLogEntryType.Information); } public static Row GetRow(SheetData sheetData, int rowIndex) { try { return sheetData.Elements<Row>().Where(r => r.RowIndex == rowIndex).First(); } catch { return null; } } public static Cell GetCell(Row row, int columnIndex) { return row.Elements<Cell>().FirstOrDefault(c => string.Compare(c.CellReference.Value, GetColumnName(columnIndex) + row.RowIndex, true) == 0); } private static string GetColumnName(int columnIndex) { int dividend = columnIndex; string columnName = String.Empty; int modifier; while (dividend > 0) { modifier = (dividend - 1) % 26; columnName = Convert.ToChar(65 + modifier).ToString() + columnName; dividend = (int)((dividend - modifier) / 26); } return columnName; } private static Row CreateContentRow(DataRow dataRow, int rowIndex, int columnindex) { Row row = new Row { RowIndex = (UInt32)rowIndex }; PopulateRow(dataRow, rowIndex + 2, row); return row; } private static void PopulateRow(DataRow dataRow, int rowindex, Row row) { Repository.Utility.WriteLog("PopulateRow started", System.Diagnostics.EventLogEntryType.Information); Cell dataCell = GetCell(row, 1); if (dataCell.DataType != null && dataCell.DataType == CellValues.SharedString) dataCell.DataType = CellValues.String; //dataCell.CellValue.Text = dataRow["Task"].ToString().Split(":".ToCharArray())[0] + " " + ((DateTime)dataRow["Finish"]).ToShortDateString(); //dataCell.CellFormula = new CellFormula(string.Format("=CONCATENATE(I{0},\": \",TEXT(H{1},\"m/d\"))", rowindex, rowindex)); //dataCell = GetCell(row, 4); //if (dataCell.DataType != null && dataCell.DataType == CellValues.SharedString) // dataCell.DataType = CellValues.String; //if (dataRow["Task"] != System.DBNull.Value) //dataCell.CellValue.Text = dataRow["Task"].ToString().Split(":".ToCharArray())[0]; dataCell = GetCell(row, 2); if (dataCell.DataType != null && dataCell.DataType == CellValues.SharedString) dataCell.DataType = CellValues.String; if (dataRow["Start"] != System.DBNull.Value && !string.IsNullOrEmpty(dataRow["Start"].ToString())) dataCell.CellValue.Text = ((DateTime)dataRow["Start"]).ToOADate().ToString(); dataCell = GetCell(row, 3); if (dataCell.DataType != null && dataCell.DataType == CellValues.SharedString) dataCell.DataType = CellValues.String; //dataCell.CellFormula = new CellFormula(string.Format("=IF(F{0}-B{1} > 4,F{2}-B{3},5)", rowindex, rowindex, rowindex, rowindex)); //if (dataRow["Duration"] != System.DBNull.Value) // dataCell.CellValue.Text = Convert.ToInt32(dataRow["Duration"].ToString()) != 0 ? (Convert.ToInt32(dataRow["Duration"].ToString()) / 4800).ToString() : "0"; //else // dataCell.CellValue.Text = ""; dataCell = GetCell(row, 4); if (dataCell.DataType != null && dataCell.DataType == CellValues.SharedString) dataCell.DataType = CellValues.String; else dataCell.CellValue.Text = ""; if (dataRow["BaseLineStart"] != System.DBNull.Value && !string.IsNullOrEmpty(dataRow["BaseLineStart"].ToString())) dataCell.CellValue.Text = ((DateTime)dataRow["BaseLineStart"]).ToOADate().ToString(); else dataCell.CellValue.Text = ""; dataCell = GetCell(row, 5); if (dataCell.DataType != null && dataCell.DataType == CellValues.SharedString) dataCell.DataType = CellValues.String; //dataCell.CellFormula = new CellFormula(string.Format("=IF(H{0}-D{1} > 4,H{2}-D{3},5)", rowindex, rowindex, rowindex, rowindex)); //else // dataCell.CellValue.Text = ""; //if (dataRow["BLDuration"] != System.DBNull.Value) //dataCell.CellValue.Text = Convert.ToInt32(dataRow["BLDuration"].ToString()) != 0 ? (Convert.ToInt32(dataRow["BLDuration"].ToString()) / 4800).ToString() : "0"; //else // dataCell.CellValue.Text = ""; dataCell = GetCell(row, 6); if (dataCell.DataType != null && dataCell.DataType == CellValues.SharedString) dataCell.DataType = CellValues.String; else dataCell.CellValue.Text = ""; if (dataRow["Finish"] != System.DBNull.Value && !string.IsNullOrEmpty(dataRow["Finish"].ToString())) dataCell.CellValue.Text = ((DateTime)dataRow["Finish"]).ToOADate().ToString(); else dataCell.CellValue.Text = ""; dataCell = GetCell(row, 7); if (dataCell.DataType != null && dataCell.DataType == CellValues.SharedString) dataCell.DataType = CellValues.String; else dataCell.CellValue.Text = ""; if (dataRow["ID"] != System.DBNull.Value && !string.IsNullOrEmpty(dataRow["ID"].ToString())) dataCell.CellValue.Text = dataRow["ID"].ToString(); else dataCell.CellValue.Text = ""; dataCell = GetCell(row, 8); if (dataCell.DataType != null && dataCell.DataType == CellValues.SharedString) dataCell.DataType = CellValues.String; else dataCell.CellValue.Text = ""; if (dataRow["BaseLineFinish"] != System.DBNull.Value && !string.IsNullOrEmpty(dataRow["BaseLineFinish"].ToString())) dataCell.CellValue.Text = ((DateTime)dataRow["BaseLineFinish"]).ToOADate().ToString(); else dataCell.CellValue.Text = ""; dataCell = GetCell(row, 9); if (dataCell.DataType != null && dataCell.DataType == CellValues.SharedString) dataCell.DataType = CellValues.String; else dataCell.CellValue.Text = ""; if (dataRow["Task"] != System.DBNull.Value && !string.IsNullOrEmpty(dataRow["Task"].ToString())) dataCell.CellValue.Text = dataRow["Task"].ToString(); else dataCell.CellValue.Text = ""; Repository.Utility.WriteLog("PopulateRow complete successfully", System.Diagnostics.EventLogEntryType.Information); } private static Cell CreateCell(int columnIndex, int rowIndex, object cellValue) { Repository.Utility.WriteLog("CreateCell started", System.Diagnostics.EventLogEntryType.Information); Cell cell = new Cell(); cell.CellReference = GetColumnName(columnIndex) + rowIndex; var value = cellValue.ToString(); Decimal number; if (cellValue.GetType() == typeof(Decimal) || Decimal.TryParse(value, out number)) { cell.DataType = CellValues.Number; } else if (cellValue.GetType() == typeof(DBNull)) { cell.DataType = CellValues.String; value = "NULL"; } else if (cellValue.GetType() == typeof(DateTime)) { cell.StyleIndex = (UInt32Value)12U; value = (cellValue as DateTime?).Value.ToOADate().ToString(); } else if (cellValue.GetType() == typeof(Boolean)) { value = ((bool)cellValue) ? "1" : "0"; } else { cell.DataType = CellValues.String; } cell.CellValue = new CellValue(value); Repository.Utility.WriteLog("CreateCell completed successfully", System.Diagnostics.EventLogEntryType.Information); return cell; } private static void IncrementIndexes(Row row, int increment) { Repository.Utility.WriteLog("IncrementIndexes started", System.Diagnostics.EventLogEntryType.Information); uint newRowIndex; newRowIndex = System.Convert.ToUInt32(row.RowIndex.Value + increment); foreach (Cell cell in row.Elements<Cell>()) { string cellReference = cell.CellReference.Value; cell.CellReference = new StringValue(cellReference.Replace(row.RowIndex.Value.ToString(), newRowIndex.ToString())); string cellFormula = cell.CellFormula != null ? cell.CellFormula.Text : ""; if (cellFormula != "") { cell.CellValue.Remove(); cell.CellFormula = new CellFormula(string.Format("={0}", cellFormula.Replace(row.RowIndex.Value.ToString(), newRowIndex.ToString()), newRowIndex)); } } row.RowIndex = new UInt32Value(newRowIndex); Repository.Utility.WriteLog("IncrementIndexes completed successfully", System.Diagnostics.EventLogEntryType.Information); } internal static void LoadGraphSheetData(SheetData sheetData, List<GraphDataGroup> data, int rowIndex, int columnIndex) { //Populate data Repository.Utility.WriteLog("LoadSheetData started", System.Diagnostics.EventLogEntryType.Information); int startRow = rowIndex + 1; for (int i = 0; i < data.Count; i++) { for (int j = 0; j < data[i].Data.Count; j++) { Row row = GetRow(sheetData, j + startRow); if (row == null) { row = CreateContentRow(data[i], j + startRow, columnIndex); sheetData.AppendChild(row); } else PopulateRow(data[i].Data[j], row, data[i].Type); } } Repository.Utility.WriteLog("LoadSheetData completed successfully", System.Diagnostics.EventLogEntryType.Information); } private static Row CreateContentRow(GraphDataGroup graphDataGroup, int rowIndex, int columnIndex) { Row row = new Row { RowIndex = (UInt32)rowIndex }; foreach (GraphData data in graphDataGroup.Data) { PopulateRow(data, row, graphDataGroup.Type); } return row; } private static void PopulateRow(GraphData graphData, Row row, string type) { Repository.Utility.WriteLog("PopulateRow started", System.Diagnostics.EventLogEntryType.Information); Cell dataCell = GetCell(row, 1); if (dataCell.DataType != null && dataCell.DataType == CellValues.SharedString) dataCell.DataType = CellValues.String; dataCell.CellValue.Text = graphData.Title.ToString(); switch (type) { case "CF": case "BES": case "CS": Cell dataCell1 = GetCell(row, 2); if (dataCell1.DataType != null && dataCell1.DataType == CellValues.SharedString) dataCell1.DataType = CellValues.String; dataCell1.CellValue.Text = graphData.Count.ToString(); break; case "BEF": case "FCF": case "FCS": Cell dataCell2 = GetCell(row, 3); if (dataCell2.DataType != null && dataCell2.DataType == CellValues.SharedString) dataCell2.DataType = CellValues.String; dataCell2.CellValue.Text = graphData.Count.ToString(); break; case "BEFS": case "DQF": case "DQ": Cell dataCell3 = GetCell(row, 4); if (dataCell3.DataType != null && dataCell3.DataType == CellValues.SharedString) dataCell3.DataType = CellValues.String; dataCell3.CellValue.Text = graphData.Count.ToString(); break; case "BEFF": case "FDQF": case "FDQ": Cell dataCell4 = GetCell(row, 5); if (dataCell4.DataType != null && dataCell4.DataType == CellValues.SharedString) dataCell4.DataType = CellValues.String; dataCell4.CellValue.Text = graphData.Count.ToString(); break; case "CDQF": case "CDQ": Cell dataCell5 = GetCell(row, 6); if (dataCell5.DataType != null && dataCell5.DataType == CellValues.SharedString) dataCell5.DataType = CellValues.String; dataCell5.CellValue.Text = graphData.Count.ToString(); break; case "FCDQF": case "FCDQ": Cell dataCell6 = GetCell(row, 7); if (dataCell6.DataType != null && dataCell6.DataType == CellValues.SharedString) dataCell6.DataType = CellValues.String; dataCell6.CellValue.Text = graphData.Count.ToString(); break; } Repository.Utility.WriteLog("PopulateRow complete successfully", System.Diagnostics.EventLogEntryType.Information); } } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using DocumentFormat.OpenXml.Drawing; namespace PMMP { public class TableUtilities { public static void PopulateTable(Table table, IList<TaskItem> items) { foreach (TaskItem item in items) { TableRow tr = new TableRow(); tr.Height = 304800L; tr.Append(CreateTextCell(item.ID.ToString())); //tr.Append(CreateTextCell(item.UniqueID.ToString())); tr.Append(CreateTextCell(item.Task)); tr.Append(CreateTextCell(item.Duration)); tr.Append(CreateTextCell(item.Predecessor)); tr.Append(CreateTextCell(item.Start.HasValue ? item.Start.Value.ToShortDateString() : String.Empty)); tr.Append(CreateTextCell(item.Finish.HasValue ? item.Start.Value.ToShortDateString() : String.Empty)); tr.Append(CreateTextCell(item.ModifiedOn.HasValue ? item.ModifiedOn.Value.ToShortDateString() : String.Empty)); table.Append(tr); } } static TableCell CreateTextCell(string text) { TableCell tc = new TableCell( new TextBody( new BodyProperties(), new Paragraph( new Run( new RunProperties() { FontSize = 1200 }, new Text(text)))), new TableCellProperties()); return tc; } } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using DocumentFormat.OpenXml.Packaging; using DocumentFormat.OpenXml.Presentation; using System.IO; using DocumentFormat.OpenXml.Drawing.Charts; using System.Reflection; namespace PMMP { public static class PresentationExtensions { public static string StringValueOf(this Enum value) { FieldInfo fi = value.GetType().GetField(value.ToString()); Microsoft.SharePoint.Linq.ChoiceAttribute[] attributes = (Microsoft.SharePoint.Linq.ChoiceAttribute[])fi.GetCustomAttributes( typeof(Microsoft.SharePoint.Linq.ChoiceAttribute), false); if (attributes.Length > 0) { return attributes[0].Value; } else { return value.ToString(); } } public static string ExceptChars(this string str, IEnumerable<char> toExclude) { StringBuilder sb = new StringBuilder(); for (int i = 0; i < str.Length; i++) { char c = str[i]; if (!toExclude.Contains(c)) sb.Append(c); } return sb.ToString(); } public static IEnumerable<SlidePart> GetSlidePartsInOrder(this PresentationPart presentationPart) { SlideIdList slideIdList = presentationPart.Presentation.SlideIdList; return slideIdList.ChildElements .Cast<SlideId>() .Select(x => presentationPart.GetPartById(x.RelationshipId)) .Cast<SlidePart>(); } public static SlidePart CloneSlide(this SlidePart templatePart, SlideType type) { // find the presentationPart: makes the API more fluent var presentationPart = templatePart.GetParentParts().OfType<PresentationPart>().Single(); int i = presentationPart.SlideParts.Count(); // clone slide contents var slidePartClone = presentationPart.AddNewPart<SlidePart>("newSlide" + i); slidePartClone.FeedData(templatePart.GetStream(FileMode.Open)); // copy layout part slidePartClone.AddPart(templatePart.SlideLayoutPart, templatePart.GetIdOfPart(templatePart.SlideLayoutPart)); if (type == SlideType.Grid) { foreach (IdPartPair part in templatePart.Parts) { var tPart = templatePart.GetPartById(part.RelationshipId); var embeddedPackagePart = tPart as EmbeddedPackagePart; if (embeddedPackagePart != null) { var newPart = slidePartClone.AddEmbeddedPackagePart(embeddedPackagePart.ContentType); newPart.FeedData(embeddedPackagePart.GetStream()); slidePartClone.ChangeIdOfPart(newPart, templatePart.GetIdOfPart(embeddedPackagePart)); } var vmlDrawingPart = tPart as VmlDrawingPart; if (vmlDrawingPart != null) { var newPart = slidePartClone.AddNewPart<VmlDrawingPart>(); newPart.FeedData(vmlDrawingPart.GetStream()); var drawingImg = vmlDrawingPart.ImageParts.ToList()[0]; var newImgPart = newPart.AddImagePart(drawingImg.ContentType, templatePart.GetIdOfPart(drawingImg)); newImgPart.FeedData(drawingImg.GetStream()); } var imagePart = tPart as ImagePart; if (imagePart != null) { var newPart = slidePartClone.AddImagePart(imagePart.ContentType, templatePart.GetIdOfPart(imagePart)); newPart.FeedData(imagePart.GetStream()); } } } else { foreach (ChartPart cpart in templatePart.ChartParts) { ChartPart newcpart = slidePartClone.AddNewPart<ChartPart>(templatePart.GetIdOfPart(cpart)); newcpart.FeedData(cpart.GetStream()); // copy the embedded excel file EmbeddedPackagePart epart = newcpart.AddEmbeddedPackagePart(cpart.EmbeddedPackagePart.ContentType); epart.FeedData(cpart.EmbeddedPackagePart.GetStream()); // link the excel to the chart newcpart.ChartSpace.GetFirstChild<ExternalData>().Id = newcpart.GetIdOfPart(epart); newcpart.ChartSpace.Save(); } } return slidePartClone; } public static void AppendSlide(this PresentationPart presentationPart, SlidePart newSlidePart) { SlideIdList slideIdList = presentationPart.Presentation.SlideIdList; // find the highest id uint maxSlideId = slideIdList.ChildElements.Cast<SlideId>().Max(x => x.Id.Value); // Insert the new slide into the slide list after the previous slide. var id = maxSlideId + 1; SlideId newSlideId = new SlideId(); slideIdList.Append(newSlideId); newSlideId.Id = id; newSlideId.RelationshipId = presentationPart.GetIdOfPart(newSlidePart); } } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Data; using SvcProject; using SvcLookupTable; using SvcCustomFields; using WCFHelpers; using System.Collections; using System.Net; using System.Security.Cryptography.X509Certificates; using System.Configuration; using System.ServiceModel; using PSLib = Microsoft.Office.Project.Server.Library; using System.Security.Principal; using System.Xml; using System.Data.SqlClient; using System.Web.Services.Protocols; using SvcResource; using System.Globalization; namespace Repository { public class FiscalUnit { public FiscalUnit() { From = DateTime.MinValue; To = DateTime.MaxValue; } public FiscalUnit(DateTime fromDate, DateTime toDate, int month, int year, bool isWeekly, int weekNoStart) { From = fromDate; To = toDate; Month = month; Year = year; IsWeekly = isWeekly; WeekNoStart = weekNoStart; } public FiscalUnit(DateTime fromDate, DateTime toDate, int month, int year, bool nonFiscal) { From = fromDate; To = toDate; Month = month; Year = year; IsWeekly = false; NonFiscal = nonFiscal; } public bool IsWeekly { get; set; } public int WeekNoStart { get; set; } public int Month { get; set; } public int Year { get; set; } public DateTime To { get; set; } public DateTime From { get; set; } public bool NonFiscal { get; set; } public string GetTitle() { if (NonFiscal) { return To.ToString("dd/MM"); } if (IsWeekly) { DateTime date = new DateTime(Year, Month, 1); return date.ToString("MMM y " + string.Format("WK{0}", WeekNoStart)); } else { DateTime date = new DateTime(Year, Month, 1); return date.ToString("MMM y"); } } public int GetNoOfWeeks() { return (To - From).Days / 7; } } /// <summary> /// /// </summary> public class DataRepository { // WCF endpoint names in app.config. private const string ENDPOINT_ADMIN = "basicHttp_Admin"; private const string ENDPOINT_Q = "basicHttp_QueueSystem"; private const string ENDPOINT_RES = "basicHttp_Resource"; private const string ENDPOINT_PROJ = "basicHttp_Project"; private const string ENDPOINT_LUT = "basicHttp_LookupTable"; private const string ENDPOINT_CF = "basicHttp_CustomFields"; private const string ENDPOINT_CAL = "basicHttp_Calendar"; private const string ENDPOINT_AR = "basicHttp_Archive"; private const string ENDPOINT_PWA = "basicHttp_PWA"; private const int NO_QUEUE_MESSAGE = -1; public static SvcAdmin.AdminClient adminClient; public static SvcQueueSystem.QueueSystemClient queueSystemClient; public static SvcResource.ResourceClient resourceClient; public static SvcProject.ProjectClient projectClient; public static SvcLookupTable.LookupTableClient lookupTableClient; public static SvcCustomFields.CustomFieldsClient customFieldsClient; public static SvcCalendar.CalendarClient calendarClient; public static SvcArchive.ArchiveClient archiveClient; public static SvcStatusing.StatusingClient pwaClient; public static bool isImpersonated = false; private static SvcLoginWindows.LoginWindows loginWindows; // Use for logon of different Windows user. //public static SvcLoginForms.LoginForms loginForms = new SvcLoginForms.LoginForms(); //public static SvcLoginWindows.LoginWindows loginWindows = new SvcLoginWindows.LoginWindows(); public static string projectServerUrl = ""; public static string userName = ""; public static string password = ""; public static bool isWindowsAuth = true; public static bool useDefaultWindowsCredentials = true; // Currently must be true for Windows authentication in ProjTool. public static int windowsPort = 80; public static int formsPort = 81; public static bool waitForQueue = true; public static bool waitForIndividualQueue = false; public static bool autoLogin = false; public static Guid pwaSiteId = Guid.Empty; public static Guid jobGuid; public static Guid projectGuid = new Guid(); public static int loginStatus = 0; public static string impersonatedUserName = ""; public enum queryType { GroupAndName, GroupAndDisplayName, UserNameAndName, UserNameandDisplayName } public static ArrayList adUsers = new ArrayList(); public static MySettings mySettings = new MySettings(); public static void SetImpersonation(bool isWindowsUser) { string impersonatedUser = System.Security.Principal.WindowsIdentity.GetCurrent().Name; Guid resourceGuid = GetResourceUid(impersonatedUser); Guid trackingGuid = Guid.NewGuid(); Guid siteId = Guid.Empty; // Project Web App site ID. CultureInfo languageCulture = null; // The language culture is not used. CultureInfo localeCulture = null; // The locale culture is not used. WcfHelpers.SetImpersonationContext(isWindowsUser, impersonatedUser, resourceGuid, trackingGuid, siteId, languageCulture, localeCulture); } // Get the GUID for a Project Server account name. public static Guid GetResourceUid(String accountName) { Guid resourceUid = Guid.Empty; ResourceDataSet resourceDs = new ResourceDataSet(); // Filter for the account name, which can be a // Windows account or Project Server account. PSLib.Filter filter = new PSLib.Filter(); filter.FilterTableName = resourceDs.Resources.TableName; PSLib.Filter.Field accountField = new PSLib.Filter.Field( resourceDs.Resources.TableName, resourceDs.Resources.WRES_ACCOUNTColumn.ColumnName); filter.Fields.Add(accountField); PSLib.Filter.FieldOperator op = new PSLib.Filter.FieldOperator( PSLib.Filter.FieldOperationType.Equal, resourceDs.Resources.WRES_ACCOUNTColumn.ColumnName, accountName); filter.Criteria = op; string filterXml = filter.GetXml(); resourceDs = resourceClient.ReadResources(filterXml, false); // Return the account GUID. if (resourceDs.Resources.Rows.Count > 0) resourceUid = (Guid)resourceDs.Resources.Rows[0]["RES_UID"]; return resourceUid; } public void LoadProjects(string url) { ClearImpersonation(); if (P14Login(url)) { ReadProjectsList(); } } public static SvcProject.ProjectDataSet ReadProjectsList() //called by configuration screen { SvcProject.ProjectDataSet projectList = new SvcProject.ProjectDataSet(); try { using (OperationContextScope scope = new OperationContextScope(projectClient.InnerChannel)) { WcfHelpers.UseCorrectHeaders(isImpersonated); Utility.WriteLog(string.Format("Calling ReadStatus"), System.Diagnostics.EventLogEntryType.Information); SvcStatusing.StatusingDataSet dataSet = pwaClient.ReadStatus(Guid.Empty, DateTime.MinValue, DateTime.MaxValue); Utility.WriteLog(string.Format("ReadStatus Successful"), System.Diagnostics.EventLogEntryType.Information); // Get projects of type normal, templates, proposals, master, and inserted. string projectName = string.Empty; Utility.WriteLog(string.Format("Calling ReadStatus on Project Store"), System.Diagnostics.EventLogEntryType.Information); projectList.Merge(projectClient.ReadProjectStatus(Guid.Empty, SvcProject.DataStoreEnum.PublishedStore, projectName, (int)PSLib.Project.ProjectType.Project)); Utility.WriteLog(string.Format("ReadStatus on Project Store Successful"), System.Diagnostics.EventLogEntryType.Information); Utility.WriteLog(string.Format("Calling ReadStatus on Inserted Store"), System.Diagnostics.EventLogEntryType.Information); projectList.Merge(projectClient.ReadProjectStatus(Guid.Empty, SvcProject.DataStoreEnum.PublishedStore, projectName, (int)PSLib.Project.ProjectType.InsertedProject)); Utility.WriteLog(string.Format("ReadStatus on Inserted Store Successful"), System.Diagnostics.EventLogEntryType.Information); Utility.WriteLog(string.Format("Calling ReadStatus on Published Store"), System.Diagnostics.EventLogEntryType.Information); projectList.Merge(projectClient.ReadProjectStatus(Guid.Empty, SvcProject.DataStoreEnum.PublishedStore, projectName, (int)PSLib.Project.ProjectType.MasterProject)); Utility.WriteLog(string.Format("ReadStatus on Inserted Published Store Successful"), System.Diagnostics.EventLogEntryType.Information); //SvcProject.ProjectDataSet pds = projectClient.ReadProjectList(); // this fails if no permission... Conversely...ReadProjectStatus returns 0 if no permission. } } catch (Exception ex) { Utility.WriteLog(string.Format("An error occured in ReadProjectsList and the error ={0}", ex.Message), System.Diagnostics.EventLogEntryType.Information); } finally { } return projectList; } public static bool P14Login(string projectserverURL) { bool endPointError = false; bool result = false; try { projectServerUrl = projectserverURL.Trim(); if (!projectServerUrl.EndsWith("/")) { projectServerUrl = projectServerUrl + "/"; } String baseUrl = projectServerUrl; // Configure the WCF endpoints of PSI services used in ProjTool, before logging on. if (mySettings.UseAppConfig) { endPointError = !ConfigClientEndpoints(); } else { endPointError = !SetClientEndpointsProg(baseUrl); } if (endPointError) return false; // NOTE: Windows logon with the default Windows credentials, Forms logon, and impersonation work in ProjTool. // Windows logon without the default Windows credentials does not currently work. if (!isImpersonated) { if (isWindowsAuth) { if (useDefaultWindowsCredentials) { result = true; } else { String[] splits = userName.Split('\\'); if (splits.Length != 2) { String errorMessage = "User name must be in the format domainname\\accountname"; result = false; } else { // Order of strings returned by String.Split is not deterministic // Hence we cannot use splits[0] and splits[1] to obtain domain name and user name int positionOfBackslash = userName.IndexOf('\\'); String windowsDomainName = userName.Substring(0, positionOfBackslash); String windowsUserName = userName.Substring(positionOfBackslash + 1); loginWindows = new SvcLoginWindows.LoginWindows(); loginWindows.Url = baseUrl + "_vti_bin/PSI/LoginWindows.asmx"; loginWindows.Credentials = new NetworkCredential(windowsUserName, password, windowsDomainName); Utility.WriteLog(string.Format("Logging in with username={0} password={1} Domain={1} ", windowsUserName, password, windowsDomainName), System.Diagnostics.EventLogEntryType.Information); result = loginWindows.Login(); Utility.WriteLog(string.Format("Logging in result ={0} ", result.ToString()), System.Diagnostics.EventLogEntryType.Information); } } } else { // Forms authentication requires the Authentication web service in Microsoft SharePoint Foundation. Utility.WriteLog(string.Format("Logging in with username={0} password={1} ", userName, password), System.Diagnostics.EventLogEntryType.Information); result = WcfHelpers.LogonWithMsf(userName, password, new Uri(baseUrl)); Utility.WriteLog(string.Format("Logging in result ={0} ", result.ToString()), System.Diagnostics.EventLogEntryType.Information); } } return result; } catch (Exception ex) { return false; } } public static void ClearImpersonation() { WcfHelpers.ClearImpersonationContext(); isImpersonated = false; } public static string CatchFaultException(FaultException faultEx) { string errAttributeName; string errAttribute; string errOut; string errMess = "".PadRight(30, '=') + "\r\n" + "Error details: " + "\r\n"; PSLib.PSClientError error = WcfHelpers.GetPSClientError(faultEx, out errOut); errMess += errOut; PSLib.PSErrorInfo[] errors = error.GetAllErrors(); PSLib.PSErrorInfo thisError; for (int i = 0; i < errors.Length; i++) { thisError = errors[i]; errMess += "\r\n".PadRight(30, '=') + "\r\nPSClientError output:\r\n"; errMess += thisError.ErrId.ToString() + "\n"; for (int j = 0; j < thisError.ErrorAttributes.Length; j++) { errAttributeName = thisError.ErrorAttributeNames()[j]; errAttribute = thisError.ErrorAttributes[j]; errMess += "\r\n\t" + errAttributeName + ": " + errAttribute; } } return errMess; } #region Configure WCF client and impersonation // Configure the PSI client endpoints by using the settings in app.config. public static bool ConfigClientEndpoints() { bool result = true; string[] endpoints = { ENDPOINT_ADMIN, ENDPOINT_Q, ENDPOINT_RES, ENDPOINT_PROJ, ENDPOINT_LUT, ENDPOINT_CF, ENDPOINT_CAL, ENDPOINT_AR, ENDPOINT_PWA }; try { foreach (string endPt in endpoints) { switch (endPt) { case ENDPOINT_ADMIN: adminClient = new SvcAdmin.AdminClient(endPt); break; case ENDPOINT_PROJ: projectClient = new SvcProject.ProjectClient(endPt); break; case ENDPOINT_Q: queueSystemClient = new SvcQueueSystem.QueueSystemClient(endPt); break; case ENDPOINT_RES: resourceClient = new SvcResource.ResourceClient(endPt); break; case ENDPOINT_LUT: lookupTableClient = new SvcLookupTable.LookupTableClient(endPt); break; case ENDPOINT_CF: customFieldsClient = new SvcCustomFields.CustomFieldsClient(endPt); break; case ENDPOINT_CAL: calendarClient = new SvcCalendar.CalendarClient(endPt); break; case ENDPOINT_AR: archiveClient = new SvcArchive.ArchiveClient(endPt); break; case ENDPOINT_PWA: pwaClient = new SvcStatusing.StatusingClient(endPt); break; default: result = false; Console.WriteLine("Invalid endpoint: {0}", endPt); break; } } } catch (Exception ex) { result = false; } return result; } // Set the PSI client endpoints programmatically; don't use app.config. private static bool SetClientEndpointsProg(string pwaUrl) { const int MAXSIZE = int.MaxValue; const string SVC_ROUTER = "_vti_bin/PSI/ProjectServer.svc"; bool isHttps = pwaUrl.ToLower().StartsWith("https"); bool result = true; BasicHttpBinding binding = null; try { if (isHttps) { // Create a binding for HTTPS. binding = new BasicHttpBinding(BasicHttpSecurityMode.Transport); } else { // Create a binding for HTTP. binding = new BasicHttpBinding(BasicHttpSecurityMode.TransportCredentialOnly); } binding.Name = "basicHttpConf"; binding.MessageEncoding = WSMessageEncoding.Text; binding.CloseTimeout = new TimeSpan(00, 05, 00); binding.OpenTimeout = new TimeSpan(00, 05, 00); binding.ReceiveTimeout = new TimeSpan(00, 05, 00); binding.SendTimeout = new TimeSpan(00, 05, 00); binding.TextEncoding = System.Text.Encoding.UTF8; // If the TransferMode is buffered, the MaxBufferSize and // MaxReceived MessageSize must be the same value. binding.TransferMode = TransferMode.Buffered; binding.MaxBufferSize = MAXSIZE; binding.MaxReceivedMessageSize = MAXSIZE; binding.MaxBufferPoolSize = MAXSIZE; binding.Security.Transport.ClientCredentialType = HttpClientCredentialType.Ntlm; binding.GetType().GetProperty("ReaderQuotas").SetValue(binding, XmlDictionaryReaderQuotas.Max, null); // The endpoint address is the ProjectServer.svc router for all public PSI calls. EndpointAddress address = new EndpointAddress(pwaUrl + SVC_ROUTER); adminClient = new SvcAdmin.AdminClient(binding, address); adminClient.ChannelFactory.Credentials.Windows.AllowedImpersonationLevel = TokenImpersonationLevel.Impersonation; adminClient.ChannelFactory.Credentials.Windows.AllowNtlm = true; projectClient = new SvcProject.ProjectClient(binding, address); projectClient.ChannelFactory.Credentials.Windows.AllowedImpersonationLevel = TokenImpersonationLevel.Impersonation; projectClient.ChannelFactory.Credentials.Windows.AllowNtlm = true; queueSystemClient = new SvcQueueSystem.QueueSystemClient(binding, address); queueSystemClient.ChannelFactory.Credentials.Windows.AllowedImpersonationLevel = TokenImpersonationLevel.Impersonation; queueSystemClient.ChannelFactory.Credentials.Windows.AllowNtlm = true; resourceClient = new SvcResource.ResourceClient(binding, address); resourceClient.ChannelFactory.Credentials.Windows.AllowedImpersonationLevel = TokenImpersonationLevel.Impersonation; resourceClient.ChannelFactory.Credentials.Windows.AllowNtlm = true; lookupTableClient = new SvcLookupTable.LookupTableClient(binding, address); lookupTableClient.ChannelFactory.Credentials.Windows.AllowedImpersonationLevel = TokenImpersonationLevel.Impersonation; lookupTableClient.ChannelFactory.Credentials.Windows.AllowNtlm = true; customFieldsClient = new SvcCustomFields.CustomFieldsClient(binding, address); customFieldsClient.ChannelFactory.Credentials.Windows.AllowedImpersonationLevel = TokenImpersonationLevel.Impersonation; customFieldsClient.ChannelFactory.Credentials.Windows.AllowNtlm = true; calendarClient = new SvcCalendar.CalendarClient(binding, address); calendarClient.ChannelFactory.Credentials.Windows.AllowedImpersonationLevel = TokenImpersonationLevel.Impersonation; calendarClient.ChannelFactory.Credentials.Windows.AllowNtlm = true; archiveClient = new SvcArchive.ArchiveClient(binding, address); archiveClient.ChannelFactory.Credentials.Windows.AllowedImpersonationLevel = TokenImpersonationLevel.Impersonation; archiveClient.ChannelFactory.Credentials.Windows.AllowNtlm = true; pwaClient = new SvcStatusing.StatusingClient(binding, address); pwaClient.ChannelFactory.Credentials.Windows.AllowedImpersonationLevel = TokenImpersonationLevel.Impersonation; pwaClient.ChannelFactory.Credentials.Windows.AllowNtlm = true; } catch (Exception ex) { result = false; } return result; } #endregion public static FiscalUnit GetFiscalMonth(DateTime? date) { if (!date.HasValue) { return new FiscalUnit() { From = DateTime.MinValue, To = DateTime.MaxValue }; } Utility.WriteLog(string.Format("Calling GetCurrentFiscalMonth"), System.Diagnostics.EventLogEntryType.Information); using (OperationContextScope scope = new OperationContextScope(adminClient.InnerChannel)) { WcfHelpers.UseCorrectHeaders(isImpersonated); SvcAdmin.FiscalPeriodDataSet fiscalPeriods = adminClient.ReadFiscalPeriods(date.Value.Year); if (fiscalPeriods.FiscalPeriods.Rows.Count > 0) { foreach (DataRow row in fiscalPeriods.FiscalPeriods.Rows) { SvcAdmin.FiscalPeriodDataSet.FiscalPeriodsRow fiscalRow = (SvcAdmin.FiscalPeriodDataSet.FiscalPeriodsRow)row; if (date >= fiscalRow.WFISCAL_PERIOD_START_DATE && date <= fiscalRow.WFISCAL_PERIOD_FINISH_DATE) { return new FiscalUnit() { From = fiscalRow.WFISCAL_PERIOD_START_DATE, To = fiscalRow.WFISCAL_PERIOD_FINISH_DATE }; } } } fiscalPeriods = adminClient.ReadFiscalPeriods(date.Value.Year - 1); if (fiscalPeriods.FiscalPeriods.Rows.Count > 0) { foreach (DataRow row in fiscalPeriods.FiscalPeriods.Rows) { SvcAdmin.FiscalPeriodDataSet.FiscalPeriodsRow fiscalRow = (SvcAdmin.FiscalPeriodDataSet.FiscalPeriodsRow)row; if (date >= fiscalRow.WFISCAL_PERIOD_START_DATE && date <= fiscalRow.WFISCAL_PERIOD_FINISH_DATE) { return new FiscalUnit() { From = fiscalRow.WFISCAL_PERIOD_START_DATE, To = fiscalRow.WFISCAL_PERIOD_FINISH_DATE }; } } } fiscalPeriods = adminClient.ReadFiscalPeriods(date.Value.Year + 1); if (fiscalPeriods.FiscalPeriods.Rows.Count > 0) { foreach (DataRow row in fiscalPeriods.FiscalPeriods.Rows) { SvcAdmin.FiscalPeriodDataSet.FiscalPeriodsRow fiscalRow = (SvcAdmin.FiscalPeriodDataSet.FiscalPeriodsRow)row; if (date >= fiscalRow.WFISCAL_PERIOD_START_DATE && date <= fiscalRow.WFISCAL_PERIOD_FINISH_DATE) { Utility.WriteLog(string.Format("GetCurrentFiscalMonth completed successfully"), System.Diagnostics.EventLogEntryType.Information); return new FiscalUnit() { From = fiscalRow.WFISCAL_PERIOD_START_DATE, To = fiscalRow.WFISCAL_PERIOD_FINISH_DATE }; } } } } Utility.WriteLog(string.Format("GetCurrentFiscalMonth completed successfully"), System.Diagnostics.EventLogEntryType.Information); return new FiscalUnit() { From = DateTime.MinValue, To = DateTime.MaxValue }; } public static CustomFieldDataSet ReadCustomFields() { Utility.WriteLog(string.Format("Calling ReadCustomFields"), System.Diagnostics.EventLogEntryType.Information); using (OperationContextScope scope = new OperationContextScope(customFieldsClient.InnerChannel)) { WcfHelpers.UseCorrectHeaders(isImpersonated); } var obj = customFieldsClient.ReadCustomFields(string.Empty, false); Utility.WriteLog(string.Format("ReadCustomFields completed successfully"), System.Diagnostics.EventLogEntryType.Information); return obj; } public static LookupTableDataSet ReadLookupTables() { using (OperationContextScope scope = new OperationContextScope(lookupTableClient.InnerChannel)) { WcfHelpers.UseCorrectHeaders(isImpersonated); } return lookupTableClient.ReadLookupTables(string.Empty, false, 1); } public static ProjectDataSet ReadProject(Guid projectUID) { Utility.WriteLog(string.Format("Calling ReadProject"), System.Diagnostics.EventLogEntryType.Information); using (OperationContextScope scope = new OperationContextScope(projectClient.InnerChannel)) { WcfHelpers.UseCorrectHeaders(isImpersonated); } var obj = projectClient.ReadProject(projectUID, SvcProject.DataStoreEnum.PublishedStore); Utility.WriteLog(string.Format("ReadProject completed successfully"), System.Diagnostics.EventLogEntryType.Information); return obj; } public static string ReadTaskEntityUID() { return Constants.LOOKUP_ENTITY_ID; } internal static void UpdateLookupTables(LookupTableDataSet lookupTableDataSet) { using (OperationContextScope scope = new OperationContextScope(lookupTableClient.InnerChannel)) { try { WcfHelpers.UseCorrectHeaders(true); lookupTableClient.CheckOutLookupTables(new Guid[] { new Guid(Constants.LOOKUP_ENTITY_ID) }); lookupTableClient.UpdateLookupTables(lookupTableDataSet, false, true, 1033); //lookupTableClient.CheckInLookupTables(new Guid[] { new Guid(Constants.LOOKUP_ENTITY_ID) },true); } catch (SoapException ex) { string errMess = ""; // Pass the exception to the PSClientError constructor to get // all error information. PSLib.PSClientError psiError = new PSLib.PSClientError(ex); PSLib.PSErrorInfo[] psiErrors = psiError.GetAllErrors(); for (int j = 0; j < psiErrors.Length; j++) { errMess += psiErrors[j].ErrId.ToString() + "\n"; } errMess += "\n" + ex.Message.ToString(); // Send error string to console or message box. } } } internal static List<FiscalUnit> GetProjectStatusPeriods(DateTime? date) { List<FiscalUnit> months = new List<FiscalUnit>(); if (!date.HasValue) { return months; } using (OperationContextScope scope = new OperationContextScope(adminClient.InnerChannel)) { WcfHelpers.UseCorrectHeaders(isImpersonated); SvcAdmin.FiscalPeriodDataSet fiscalPeriods = adminClient.ReadFiscalPeriods(date.Value.Year); if (fiscalPeriods.FiscalPeriods.Rows.Count > 0) { for (int count = 0; count < fiscalPeriods.FiscalPeriods.Rows.Count; count++) { DataRow row = fiscalPeriods.FiscalPeriods.Rows[count]; SvcAdmin.FiscalPeriodDataSet.FiscalPeriodsRow fiscalRow = (SvcAdmin.FiscalPeriodDataSet.FiscalPeriodsRow)row; int noOfWeeks = 0; if (date >= fiscalRow.WFISCAL_PERIOD_START_DATE && date <= fiscalRow.WFISCAL_PERIOD_FINISH_DATE) { for (int i = 3; i > 0; i--) { if (count >= 0) { DataRow row1 = fiscalPeriods.FiscalPeriods.Rows[count - i]; SvcAdmin.FiscalPeriodDataSet.FiscalPeriodsRow fiscalRow1 = (SvcAdmin.FiscalPeriodDataSet.FiscalPeriodsRow)row1; FiscalUnit fiscalMonth = new FiscalUnit(fiscalRow1.WFISCAL_PERIOD_START_DATE, fiscalRow1.WFISCAL_PERIOD_FINISH_DATE, fiscalRow1.WFISCAL_MONTH, fiscalRow1.WFISCAL_YEAR, false, 0); months.Add(fiscalMonth); } } //count += 3; FiscalUnit fiscalMonth1 = new FiscalUnit(fiscalRow.WFISCAL_PERIOD_START_DATE, fiscalRow.WFISCAL_PERIOD_START_DATE.AddDays(7), fiscalRow.WFISCAL_MONTH, fiscalRow.WFISCAL_YEAR, true, (1)); FiscalUnit fiscalMonth2 = new FiscalUnit(fiscalRow.WFISCAL_PERIOD_START_DATE.AddDays(7), fiscalRow.WFISCAL_PERIOD_START_DATE.AddDays(14), fiscalRow.WFISCAL_MONTH, fiscalRow.WFISCAL_YEAR, true, (2)); FiscalUnit fiscalMonth3 = new FiscalUnit(fiscalRow.WFISCAL_PERIOD_START_DATE.AddDays(14), fiscalRow.WFISCAL_PERIOD_START_DATE.AddDays(21), fiscalRow.WFISCAL_MONTH, fiscalRow.WFISCAL_YEAR, true, (3)); FiscalUnit fiscalMonth4 = new FiscalUnit(fiscalRow.WFISCAL_PERIOD_START_DATE.AddDays(21), fiscalRow.WFISCAL_PERIOD_START_DATE.AddDays(28), fiscalRow.WFISCAL_MONTH, fiscalRow.WFISCAL_YEAR, true, (4)); months.Add(fiscalMonth1); months.Add(fiscalMonth2); months.Add(fiscalMonth3); months.Add(fiscalMonth4); if (new FiscalUnit(fiscalRow.WFISCAL_PERIOD_START_DATE, fiscalRow.WFISCAL_PERIOD_FINISH_DATE, fiscalRow.WFISCAL_MONTH, fiscalRow.WFISCAL_YEAR, false, 0).GetNoOfWeeks() > 4) { FiscalUnit fiscalMonth5 = new FiscalUnit(fiscalRow.WFISCAL_PERIOD_START_DATE.AddDays(28), fiscalRow.WFISCAL_PERIOD_START_DATE.AddDays(35), fiscalRow.WFISCAL_MONTH, fiscalRow.WFISCAL_YEAR, true, (5)); months.Add(fiscalMonth5); } for (int i = 0; i < 3; i++) { count++; if (count < fiscalPeriods.FiscalPeriods.Rows.Count) { DataRow row1 = fiscalPeriods.FiscalPeriods.Rows[count]; SvcAdmin.FiscalPeriodDataSet.FiscalPeriodsRow fiscalRow1 = (SvcAdmin.FiscalPeriodDataSet.FiscalPeriodsRow)row1; FiscalUnit fiscalMonth = new FiscalUnit(fiscalRow1.WFISCAL_PERIOD_START_DATE, fiscalRow1.WFISCAL_PERIOD_FINISH_DATE, fiscalRow1.WFISCAL_MONTH, fiscalRow1.WFISCAL_YEAR, false, 0); months.Add(fiscalMonth); } } break; } noOfWeeks += new FiscalUnit(fiscalRow.WFISCAL_PERIOD_START_DATE, fiscalRow.WFISCAL_PERIOD_FINISH_DATE, fiscalRow.WFISCAL_MONTH, fiscalRow.WFISCAL_YEAR, false, 0).GetNoOfWeeks(); } } } return months; } internal static DateTime? GetProjectCurrentDate(ProjectDataSet projectDataSet, Guid projUID) { try { DateTime date = projectDataSet.Project.First(t => t.PROJ_UID == projUID).PROJ_INFO_STATUS_DATE; return date; } catch { return DateTime.Now; } } internal static List<FiscalUnit> GetProjectStatusWeekPeriods(DateTime? date) { List<FiscalUnit> weekly = new List<FiscalUnit>(); if (!date.HasValue) { return weekly; } FiscalUnit fiscalMonth1 = new FiscalUnit(date.Value.AddDays(-35), date.Value.AddDays(-28),date.Value.Month, date.Value.Year, true); FiscalUnit fiscalMonth2 = new FiscalUnit(date.Value.AddDays(-28), date.Value.AddDays(-21), date.Value.Month, date.Value.Year, true); FiscalUnit fiscalMonth3 = new FiscalUnit(date.Value.AddDays(-21), date.Value.AddDays(-14), date.Value.Month, date.Value.Year, true); FiscalUnit fiscalMonth4 = new FiscalUnit(date.Value.AddDays(-14), date.Value.AddDays(-7), date.Value.Month, date.Value.Year, true); FiscalUnit fiscalMonth5 = new FiscalUnit(date.Value.AddDays(-7), date.Value, date.Value.Month, date.Value.Year, true); FiscalUnit fiscalMonth6 = new FiscalUnit(date.Value, date.Value.AddDays(7), date.Value.Month, date.Value.Year, true); FiscalUnit fiscalMonth7 = new FiscalUnit(date.Value.AddDays(7), date.Value.AddDays(14), date.Value.Month, date.Value.Year, true); FiscalUnit fiscalMonth8 = new FiscalUnit(date.Value.AddDays(14), date.Value.AddDays(21), date.Value.Month, date.Value.Year, true); FiscalUnit fiscalMonth9 = new FiscalUnit(date.Value.AddDays(21), date.Value.AddDays(28), date.Value.Month, date.Value.Year, true); FiscalUnit fiscalMonth10 = new FiscalUnit(date.Value.AddDays(28), date.Value.AddDays(25), date.Value.Month, date.Value.Year, true); weekly.Add(fiscalMonth1); weekly.Add(fiscalMonth2); weekly.Add(fiscalMonth3); weekly.Add(fiscalMonth4); weekly.Add(fiscalMonth5); weekly.Add(fiscalMonth6); weekly.Add(fiscalMonth7); weekly.Add(fiscalMonth8); weekly.Add(fiscalMonth9); weekly.Add(fiscalMonth10); return weekly; } } public sealed class MySettings : ApplicationSettingsBase { [global::System.Configuration.ApplicationScopedSettingAttribute()] [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] [global::System.Configuration.DefaultSettingValueAttribute("http://LocalHost/PWA/")] public string ProjectServerURL { get { return (string)this["ProjectServerURL"]; } set { this["ProjectServerURL"] = value; } } [global::System.Configuration.ApplicationScopedSettingAttribute()] [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] [global::System.Configuration.DefaultSettingValueAttribute("FormsAdmin")] public string UserName { get { return (string)this["UserName"]; } set { this["UserName"] = value; } } [global::System.Configuration.ApplicationScopedSettingAttribute()] [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] [global::System.Configuration.DefaultSettingValueAttribute("pass@<PASSWORD>1")] public string PassWord { get { return (string)this["PassWord"]; } set { this["PassWord"] = value; } } [global::System.Configuration.ApplicationScopedSettingAttribute()] [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] [global::System.Configuration.DefaultSettingValueAttribute("true")] public bool IsWindowsAuth { get { return (bool)this["IsWindowsAuth"]; } set { this["IsWindowsAuth"] = value; } } [global::System.Configuration.ApplicationScopedSettingAttribute()] [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] [global::System.Configuration.DefaultSettingValueAttribute("true")] public bool UseDefaultWindowsCredentials { get { return (bool)this["UseDefaultWindowsCredentials"]; } set { this["UseDefaultWindowsCredentials"] = value; } } [global::System.Configuration.ApplicationScopedSettingAttribute()] [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] [global::System.Configuration.DefaultSettingValueAttribute("80")] public int WindowsPort { get { return (int)this["WindowsPort"]; } set { this["WindowsPort"] = value; } } [global::System.Configuration.ApplicationScopedSettingAttribute()] [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] [global::System.Configuration.DefaultSettingValueAttribute("81")] public int FormsPort { get { return (int)this["FormsPort"]; } set { this["FormsPort"] = value; } } [global::System.Configuration.ApplicationScopedSettingAttribute()] [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] [global::System.Configuration.DefaultSettingValueAttribute("false")] public bool WaitForQueue { get { return (bool)this["WaitForQueue"]; } set { this["WaitForQueue"] = value; } } [global::System.Configuration.ApplicationScopedSettingAttribute()] [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] [global::System.Configuration.DefaultSettingValueAttribute("false")] public bool WaitForIndividualQueue { get { return (bool)this["WaitForIndividualQueue"]; } set { this["WaitForIndividualQueue"] = value; } } [global::System.Configuration.ApplicationScopedSettingAttribute()] [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] [global::System.Configuration.DefaultSettingValueAttribute("false")] public bool AutoLogin { get { return (bool)this["AutoLogin"]; } set { this["AutoLogin"] = value; } } [global::System.Configuration.ApplicationScopedSettingAttribute()] [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] [global::System.Configuration.DefaultSettingValueAttribute("false")] public bool UseAppConfig { get { return (bool)this["UseAppConfig"]; } set { this["UseAppConfig"] = value; } } } public class LangItem { int lcid; string langName; public int LCID { get { return lcid; } set { lcid = value; } } public string LangName { get { return langName; } set { langName = value; } } public LangItem(int Lcid, string name) { LCID = Lcid; LangName = name; } } #region SSL Certificate Handling Class // The MyCertificateValidation class is needed for handling SSL certificates. // It checks the validity of a certificate and shows a // message to allow the user to choose whether to continue // in case of a potentially invalid certificate. public class MyCertificateValidation : ICertificatePolicy { // Default policy for certificate validation. public static bool CheckDefaultValidate; public enum CertificateProblem : long { CertEXPIRED = 0x800B0101, CertVALIDITYPERIODNESTING = 0x800B0102, CertROLE = 0x800B0103, CertPATHLENCONST = 0x800B0104, CertCRITICAL = 0x800B0105, CertPURPOSE = 0x800B0106, CertISSUERCHAINING = 0x800B0107, CertMALFORMED = 0x800B0108, CertUNTRUSTEDROOT = 0x800B0109, CertCHAINING = 0x800B010A, CertREVOKED = 0x800B010C, CertUNTRUSTEDTESTROOT = 0x800B010D, CertREVOCATION_FAILURE = 0x800B010E, CertCN_NO_MATCH = 0x800B010F, CertWRONG_USAGE = 0x800B0110, CertUNTRUSTEDCA = 0x800B0112 } public bool CheckValidationResult(ServicePoint sp, X509Certificate cert, WebRequest request, int problem) { if (problem == 0) return true; return CheckDefaultValidate; } private String GetProblemMessage(CertificateProblem Problem) { String ProblemMessage = ""; CertificateProblem problemList = new CertificateProblem(); String ProblemCodeName = Enum.GetName(problemList.GetType(), Problem); if (ProblemCodeName != null) ProblemMessage = ProblemMessage + ProblemCodeName; else ProblemMessage = "Unknown Certificate Problem"; return ProblemMessage; } } #endregion } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace PMMP { public class TaskItem { public int ID { get; set; } public string UniqueID { get; set; } public string DrivingPath { get; set; } public string Task { get; set; } public string Duration { get; set; } public string Predecessor { get; set; } public DateTime? Start { get; set; } public DateTime? Finish { get; set; } public DateTime? Deadline { get; set; } public DateTime? ModifiedOn { get; set; } public string[] ShowOn { get; set; } public int WorkCompletePercentage { get; set; } } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace Repository { /// <summary> /// /// </summary> public class LookupDTO { public Guid ID {get;set;} public Guid ParentID { get; set; } public string Text { get; set; } public int SortIndex { get; set; } public int RowLevel { get; set; } public string DotNotation { get; set; } public string COID { get; set; } public DateTime ProcessingDate { get; set; } public DateTime LastLoad { get; set; } public LookupDTO ParentNode {get;set;} } }
eb17b17e167abfae3649ab774d0aea948ec5cdf8
[ "JavaScript", "C#" ]
49
C#
jgoodso2/PMMP
83e1a0e7e836f4a18fd1bca1fec446ec9fb6969c
b4891472d767849b6a47407080363e7f3d4c3b97
refs/heads/master
<repo_name>shubhamkarad/Burger-builder<file_sep>/src/axios-orders.js import axios from 'axios'; //Adding axios instance Method const instance = axios.create({ baseURL:"Enter Your Path"; }); export default instance;<file_sep>/src/store/reducers/order.js import * as actionTypes from "../actions/actionTypes"; import {updateObject} from "../../Shared/utility"; const initialState={ orders:[], loading: false, purchased:false } // ************ Just to Keep the code clean. I have added functions for the Switch statements. and return (call) the functions in switch statements.******** const purchaseInit = (state, action)=>{ return updateObject(state, {purchased:false}); } const purchaseBurgerStart = (state, action)=>{ return updateObject(state, {loading:true}); } const purchaseBurgerSuccess = (state, action)=>{ const newOrder=updateObject(action.orderData, {id:action.orderId}); return updateObject(state, { loading:false, purchased:true, orders:state.orders.concat(newOrder) }); } const purchaseBurgerFail = (state, action)=>{ return updateObject(state, {loading:false}); } const fetchOrderStart = (state, action)=>{ return updateObject(state,{loading:true}); } const fetchOrderSuccess = (state, action)=>{ return updateObject(state, {orders:action.orders, loading:false}); } const fetchOrderFail = (state, action)=>{ return updateObject(state, {loading:false}); } const reducer = (state=initialState, action)=>{ switch(action.type){ case actionTypes.PURCHASE_INIT: return purchaseInit(state, action); case actionTypes.PURCHASE_BURGER_START: return purchaseBurgerStart(state, action); case actionTypes.PURCHASE_BURGER_SUCCESS: return purchaseBurgerSuccess(state, action); case actionTypes.PURCHASE_BURGER_FAIL: return purchaseBurgerFail(state, action); case actionTypes.FETCH_ORDERS_START: return fetchOrderStart(state, action); case actionTypes.FETCH_ORDERS_SUCCESS: return fetchOrderSuccess(state, action); case actionTypes.FETCH_ORDERS_FAIL: return fetchOrderFail(state, action); default: return state; } }; export default reducer;<file_sep>/src/store/actions/order.js import * as actionTypes from "./actionTypes"; import axios from "../../axios-orders" //Sychronous request export const purchaseBurgerSuccess = (id, orderData)=>{ return{ type:actionTypes.PURCHASE_BURGER_SUCCESS, orderId:id, orderData:orderData }; }; export const purchaseBurgerFail = (error)=>{ return{ type:actionTypes.PURCHASE_BURGER_FAIL, error:error } } export const purchaseBurgerStart = ()=>{ return{ type:actionTypes.PURCHASE_BURGER_START } } export const purchaseBurger = (orderData, token)=>{ return dispatch=>{ //whatever you pass as an endoint URL it will automatically created in Firebase. //Always make sure to add .json at the end. dispatch(purchaseBurgerStart()); axios.post('/orders.json?auth=' + token, orderData) .then(response=> { //Set the spinner false to close it // this.setState({loading:false}); // this.props.history.push("/"); console.log(response.data); dispatch(purchaseBurgerSuccess(response.data.name, orderData)); }) .catch(error=> { //Set the spinner false to close it // this.setState({loading:false}); dispatch(purchaseBurgerFail(error)); }) } } export const purchaseInit = ()=>{ return{ type:actionTypes.PURCHASE_INIT } } export const fetchOrderStart = ()=>{ return{ type: actionTypes.FETCH_ORDERS_START, } } export const fetchOrderSuccess = (orders)=>{ return{ type: actionTypes.FETCH_ORDERS_SUCCESS, orders:orders } } export const fetchOrderFail = (error)=>{ return{ type: actionTypes.FETCH_ORDERS_FAIL, error:error } } export const fetchOrders =(token, userId)=>{ return dispatch=>{ dispatch(fetchOrderStart()); //This variable use to show the orders by userId or we can say User specific Order const queryParams = '?auth=' + token + '&orderBy="userId"&equalTo="' + userId + '"'; axios.get('/orders.json'+ queryParams) .then(res=>{ const fetchedOrders=[]; for(let key in res.data){ fetchedOrders.push({ ...res.data[key], id:key }); } // console.log(res.data) dispatch(fetchOrderSuccess(fetchedOrders)) // this.setState({loading:false, orders:fetchedOrders}) }) .catch(err=>{ // this.setState({loading:false}) dispatch(fetchOrderFail(err)); }) } }
8e99687e5d13fb7c81ef574d9229122e325d6760
[ "JavaScript" ]
3
JavaScript
shubhamkarad/Burger-builder
fc2e763c92e11e36c5b9cfad1d8f3b14b4a601db
3b5a3074ec992419acbf36e6ac6f6fdbe346acd1
refs/heads/main
<file_sep>using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations.Schema; using System.Linq; using System.Threading.Tasks; namespace HD_proj.Models { public class Cchn : IdentityBase { public enum Trangthaivb { ACTIVE = 0, DEACTIVE = 1, REPLACE = 2, CANCEL = 3 } [Display(Name = "Số")] [Required] public string So { get; set; } [Display(Name = "Ngày Cấp")] [Required] [DataType(DataType.Date)] public DateTime Ngaycap { get; set; } [Display(Name = "Loại")] public string Loai { get; set; } [Display(Name = "Trình độ")] [Required] public string Trinhdo { get; set; } [Display(Name = "Phạm vi Hợp đồng")] [Required] public string Phamvi { get; set; } [Display(Name = "Hình thức cấp")] [Required] public string Hinhthuccap { get; set; } [Display(Name = "Ngày hiệu lực")] [Required] [DataType(DataType.Date)] public DateTime Ngayhieuluc { get; set; } [Display (Name = "Trạng thái")] [Required] public Trangthaivb Trangthai { get;set; } public string Cmnd { get; set; } public Guid Quyetdinh { get; set; } [Display(Name = "Người ký duyệt")] [Required] public string Nguoikyduyet { get; set; } } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace HD_proj.Models { public class ModelViewmodel { public Giaytotuythan Giaytotuythan {get; set;} public Cchn Cchn { get; set; } public Gcndkkd Gcndkkd { get; set; } public Quyetdinh Quyetdinh { get; set; } public Gcngpp Gcngpp { get; set; } } } <file_sep># soyte a <file_sep>using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.Linq; using System.Threading.Tasks; namespace HD_proj.Models { public class Quyetdinh : IdentityBase { [Display(Name = "Số hiệu")] public string Sohieu { get; set; } [Display(Name = "Người ký duyệt")] public string Nguoiky { get; set; } [Display(Name = "Ngày ký")] [DataType(DataType.Date)] public DateTime Ngayky { get; set; } } } <file_sep>using System; using Microsoft.EntityFrameworkCore.Migrations; namespace HD_proj.Migrations { public partial class datagp : Migration { protected override void Up(MigrationBuilder migrationBuilder) { migrationBuilder.CreateTable( name: "Gcngpps", columns: table => new { Id = table.Column<Guid>(nullable: false), DateUpdate = table.Column<DateTime>(nullable: false), UpdateBy = table.Column<string>(nullable: true), Ghichu = table.Column<string>(nullable: true), So = table.Column<string>(nullable: true), Loai = table.Column<string>(nullable: true), idGCN_DKKD = table.Column<string>(nullable: true), idGCN_CCHN = table.Column<string>(nullable: true), Tencoso = table.Column<string>(nullable: true), Truso = table.Column<string>(nullable: true), Diachikinhdoanh = table.Column<string>(nullable: true), Loaihinh = table.Column<string>(nullable: true), Phamvi = table.Column<string>(nullable: true), Ngaycap = table.Column<DateTime>(nullable: false), Ngayhieuluc = table.Column<DateTime>(nullable: false), Trangthai = table.Column<int>(nullable: false), Cmnd = table.Column<string>(nullable: true), Quyetdinh = table.Column<Guid>(nullable: false), Nguoikyduyet = table.Column<string>(nullable: true) }, constraints: table => { table.PrimaryKey("PK_Gcngpps", x => x.Id); }); } protected override void Down(MigrationBuilder migrationBuilder) { migrationBuilder.DropTable( name: "Gcngpps"); } } } <file_sep>using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.Linq; using System.Threading.Tasks; namespace HD_proj.Models { public class Giaytotuythan { [Key] [Display(Name = "Số Cmnd/Cccd")] [MinLength(9)] [Required] public string IdCmnd { get; set; } [Display(Name = "Họ tên")] [Required] public string Hoten { get; set; } [Display(Name = "Ngày sinh")] [Required] [DataType(DataType.Date)] public DateTime Ngaysinh { get; set; } [Display(Name = "Ngày cấp")] [Required] [DataType(DataType.Date)] public DateTime Ngaycap { get; set; } [Display(Name = "Nơi cấp")] [Required] public string Noicap { get; set; } [Display(Name = "Số điện thoại")] [DataType(DataType.PhoneNumber)] public string Sodienthoai {get;set;} [Display(Name = "Email")] [DataType(DataType.EmailAddress)] public string Email { get; set; } [Display (Name = "Địa chỉ thường trú")] [Required] public string Diachi { get; set; } [DisplayFormat(DataFormatString = "{0:yyyy/MM/dd HH:mm:ss}")] public DateTime DateUpdate { get; set; } = DateTime.Now; public string UpdateBy { get; set; } } } <file_sep>using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.Linq; using System.Threading.Tasks; namespace HD_proj.Models { public class DanhmucFile : IdentityBase { [Display (Name = "Tên file")] public string Ten { get; set; } [Display (Name = "Loại file")] public string TenLoai { get; set; } public string DuongDan { get; set; } public string PhanMoRong { get; set; } public string LoaiDulieu { get; set; } public Guid FatherId { get; set; } } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc.Rendering; using Microsoft.EntityFrameworkCore; using HD_proj.Data; using HD_proj.Models; using Microsoft.AspNetCore.Identity; using Microsoft.Extensions.Logging; using Microsoft.AspNetCore.Hosting; using Microsoft.AspNetCore.Authorization; using System.Security.Claims; using Microsoft.AspNetCore.Http; using HD_proj.Areas.Identity.Pages.Account; using System.Text; using System.IO; using Microsoft.AspNetCore.WebUtilities; namespace HD_proj.Controllers { public class CchnsController : Controller { private readonly SignInManager<ApplicationUser> _signInManager; private readonly UserManager<ApplicationUser> _userManager; private readonly ILogger<RegisterModel> _logger; private readonly ApplicationDbContext _context; private IWebHostEnvironment _env; public CchnsController(ApplicationDbContext context, UserManager<ApplicationUser> userManager, SignInManager<ApplicationUser> signInManager, ILogger<RegisterModel> logger, IWebHostEnvironment env ) { _env = env; _context = context; _userManager = userManager; _signInManager = signInManager; _logger = logger; } [Authorize] public async Task<IActionResult> Index() { var userId = User.FindFirstValue(ClaimTypes.NameIdentifier); var user = await _userManager.FindByIdAsync(userId); var cchn = await (from a in _context.Cchns join b in _context.Giaytotuythans on a.Cmnd equals b.IdCmnd into join1 from j1 in join1.DefaultIfEmpty() join c in _context.Quyetdinhs on a.Quyetdinh equals c.Id into join2 from j2 in join2.DefaultIfEmpty() select new ModelViewmodel { Giaytotuythan = j1, Cchn = a, Quyetdinh = j2 } ).ToListAsync(); if (Request.Headers["X-Requested-With"] == "XMLHttpRequest") { return PartialView("_DataTablePartial", cchn); } return View(cchn); } [Authorize] public async Task<IActionResult> Create(Guid? id) { var cchn = new Cchn(); ViewData["Giayto"] = _context.Giaytotuythans.ToList(); if (id.HasValue) { ViewData["File"] = _context.DanhmucFiles.Where(a => a.FatherId == id).ToList(); cchn = await _context.Cchns.FindAsync(id); ViewData["Giaytotuythan"] = _context.Giaytotuythans.Where(a => a.IdCmnd == cchn.Cmnd).FirstOrDefault(); ViewData["Quyetdinh"] = _context.Quyetdinhs.Where(a => a.Id == cchn.Quyetdinh).FirstOrDefault(); } return PartialView("_OrderPartial", cchn); } // POST: Cchns/Create // To protect from overposting attacks, enable the specific properties you want to bind to, for // more details, see http://go.microsoft.com/fwlink/?LinkId=317598. [HttpPost] [Authorize] [ValidateAntiForgeryToken] public async Task<IActionResult> Create(Guid? id, [Bind("So,Ngaycap,Loai,Trinhdo,Phamvi,Hinhthuccap,Ngayhieuluc,Nguoikyduyet,Id,Ghichu")] Cchn cchn, IFormCollection collect) { cchn.UpdateBy = User.Identity.Name; var giayto = _context.Giaytotuythans.AsNoTracking().Where(a => a.IdCmnd == collect["old_giayto"].ToString()).FirstOrDefault(); if (giayto != null) { _context.Giaytotuythans.Remove(giayto); _context.SaveChanges(); } giayto = new Giaytotuythan(); giayto.IdCmnd = collect["sogiayto"]; giayto.Hoten = collect["Hoten"]; giayto.Noicap = collect["noicap"]; giayto.Ngaysinh = DateTime.Parse(collect["ngaysinh"]); giayto.Ngaycap = DateTime.Parse(collect["ngaycapgiayto"]); giayto.Sodienthoai = collect["sodienthoai"]; giayto.Email = collect["email"]; giayto.Diachi = collect["diachi"]; var quyetdinh = new Quyetdinh(); if (collect["quyetdinhID"].ToString() != Guid.Empty.ToString()) { quyetdinh = _context.Quyetdinhs.Where(a => a.Id == Guid.Parse(collect["quyetdinhID"].ToString())).FirstOrDefault(); if (quyetdinh != null && quyetdinh.Id != Guid.Parse(collect["quyetdinhID"].ToString())) { _context.Quyetdinhs.Remove(quyetdinh); _context.SaveChanges(); } } quyetdinh.Id = Guid.NewGuid(); quyetdinh.Sohieu = collect["sohieuquyetdinh"]; quyetdinh.Nguoiky = cchn.Nguoikyduyet; quyetdinh.Ngayky = DateTime.Parse(collect["ngayquyetdinh"]); cchn.Quyetdinh = quyetdinh.Id; cchn.Cmnd = collect["sogiayto"]; cchn.Trangthai = Cchn.Trangthaivb.ACTIVE; await _context.Quyetdinhs.AddAsync(quyetdinh); _context.Giaytotuythans.Add(giayto); if (ModelState.IsValid) { try { if (id.HasValue) { _context.Update(cchn); await _context.SaveChangesAsync(); TempData["Notifications"] = "Updated Successfully"; } else { await _context.AddAsync(cchn); await _context.SaveChangesAsync(); TempData["Notifications"] = " Successfully"; } } catch (DbUpdateConcurrencyException) { if (id.HasValue && !CchnExists(cchn.Id)) { return NotFound(); } else { throw; } } } return PartialView("_OrderPartial", cchn); } [Authorize] public async Task<IActionResult> Replace(Guid? id) { var cchn = new Cchn(); ViewData["Giayto"] = _context.Giaytotuythans.ToList(); if (id.HasValue) { ViewData["File"] = _context.DanhmucFiles.Where(a => a.FatherId == id).ToList(); cchn = await _context.Cchns.FindAsync(id); ViewData["Giaytotuythan"] = _context.Giaytotuythans.Where(a => a.IdCmnd == cchn.Cmnd).FirstOrDefault(); ViewData["Quyetdinh"] = _context.Quyetdinhs.Where(a => a.Id == cchn.Quyetdinh).FirstOrDefault(); } if(cchn != null && cchn.Trangthai == Cchn.Trangthaivb.ACTIVE) { return PartialView("_ReplacePartial", cchn); } return NotFound(); } [HttpPost] [Authorize] [ValidateAntiForgeryToken] public async Task<IActionResult> Replace(Guid? id, [Bind("So,Ngaycap,Loai,Trinhdo,Phamvi,Hinhthuccap,Ngayhieuluc,Nguoikyduyet,Id,Ghichu")] Cchn cchn, IFormCollection collect) { cchn.UpdateBy = User.Identity.Name; var cccu = _context.Cchns.Find(Guid.Parse(collect["Socu"].ToString())); if (cccu != null) { cccu.Trangthai = Cchn.Trangthaivb.REPLACE; cccu.Ghichu = cccu.Ghichu + Environment.NewLine + "Đã được thay thế bởi Chứng chỉ dược số: " + cchn.So; } var giayto = _context.Giaytotuythans.AsNoTracking().Where(a => a.IdCmnd == collect["sogiayto"].ToString()).FirstOrDefault(); if (giayto != null) { giayto.Hoten = collect["Hoten"]; giayto.Noicap = collect["noicap"]; giayto.Ngaysinh = DateTime.Parse(collect["ngaysinh"]); giayto.Ngaycap = DateTime.Parse(collect["ngaycapgiayto"]); giayto.Sodienthoai = collect["sodienthoai"]; giayto.Email = collect["email"]; giayto.Diachi = collect["diachi"]; _context.Giaytotuythans.Update(giayto); } else { var giayto_new = new Giaytotuythan(); giayto_new.IdCmnd = collect["sogiayto"]; giayto_new.Hoten = collect["Hoten"]; giayto_new.Noicap = collect["noicap"]; giayto_new.Ngaysinh = DateTime.Parse(collect["ngaysinh"]); giayto_new.Ngaycap = DateTime.Parse(collect["ngaycapgiayto"]); giayto_new.Sodienthoai = collect["sodienthoai"]; giayto_new.Email = collect["email"]; giayto_new.Diachi = collect["diachi"]; _context.Giaytotuythans.Add(giayto_new); } var quyetdinh = new Quyetdinh(); quyetdinh.Id = Guid.NewGuid(); quyetdinh.Sohieu = collect["sohieuquyetdinh"]; quyetdinh.Nguoiky = cchn.Nguoikyduyet; quyetdinh.Ngayky = DateTime.Parse(collect["ngayquyetdinh"]); cchn.Quyetdinh = quyetdinh.Id; cchn.Cmnd = collect["sogiayto"]; cchn.Trangthai = Cchn.Trangthaivb.ACTIVE; cchn.Id = Guid.NewGuid(); _context.Quyetdinhs.Add(quyetdinh); if (ModelState.IsValid) { try { await _context.AddAsync(cchn); await _context.SaveChangesAsync(); TempData["Notifications"] = " Successfully"; } catch (DbUpdateConcurrencyException) { if (id.HasValue && !CchnExists(cchn.Id)) { return NotFound(); } else { throw; } } } return PartialView("_OrderPartial", cchn); } [Authorize] public async Task<IActionResult> Delete(Guid? id) { var cchn = new Cchn(); if (id.HasValue) { cchn = await _context.Cchns.FindAsync(id); } return PartialView("_DeletePartial", cchn); } [HttpPost] [ValidateAntiForgeryToken] public async Task<IActionResult> Delete(Guid id) { var cchn = await _context.Cchns.FindAsync(id); cchn.Trangthai = Cchn.Trangthaivb.CANCEL; _context.Update(cchn); await _context.SaveChangesAsync(); return PartialView("_DeletePartial", cchn); } [Authorize] public async Task<IActionResult> Print(Guid? id) { var cchn = new Cchn(); ViewData["Giayto"] = _context.Giaytotuythans.ToList(); if (id.HasValue) { ViewData["File"] = _context.DanhmucFiles.Where(a => a.FatherId == id).ToList(); cchn = await _context.Cchns.FindAsync(id); ViewData["Giaytotuythan"] = _context.Giaytotuythans.Where(a => a.IdCmnd == cchn.Cmnd).FirstOrDefault(); ViewData["Quyetdinh"] = _context.Quyetdinhs.Where(a => a.Id == cchn.Quyetdinh).FirstOrDefault(); } return PartialView("_PdfPartialcshtml", cchn); } private bool CchnExists(Guid id) { return _context.Cchns.Any(e => e.Id == id); } } } <file_sep>using System; using System.Collections.Generic; using System.Text; using HD_proj.Models; using Microsoft.AspNetCore.Identity; using Microsoft.AspNetCore.Identity.EntityFrameworkCore; using Microsoft.EntityFrameworkCore; namespace HD_proj.Data { public class ApplicationDbContext : IdentityDbContext<ApplicationUser, IdentityRole<Guid>, Guid> { public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options) : base(options) { } public DbSet<DanhmucFile> DanhmucFiles { get; set; } public DbSet<Cchn> Cchns { get; set; } public DbSet<Quyetdinh> Quyetdinhs { get; set; } public DbSet<Giaytotuythan> Giaytotuythans { get; set; } public DbSet<Gcndkkd> Gcndkkds { get; set; } public DbSet<Gcngpp> Gcngpps { get; set; } } } <file_sep>using System; using HD_proj.Data; using HD_proj.Models; using Microsoft.AspNetCore.Hosting; using Microsoft.AspNetCore.Identity; using Microsoft.AspNetCore.Identity.UI; using Microsoft.EntityFrameworkCore; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; [assembly: HostingStartup(typeof(HD_proj.Areas.Identity.IdentityHostingStartup))] namespace HD_proj.Areas.Identity { public class IdentityHostingStartup : IHostingStartup { public void Configure(IWebHostBuilder builder) { builder.ConfigureServices((context, services) => { }); } } }
95a763104c5f173ab7c399a650081d0ffa00f907
[ "Markdown", "C#" ]
10
C#
yamikara97/soyte
a4fffc1a028ef6a19006da7a0b7e529e14d7c504
e529a205b1ee7ab0722c5512801606ba165a653c
refs/heads/master
<file_sep>library(testthat) library(ActivityIndex) test_check("ActivityIndex") <file_sep>## ----"setup",echo=FALSE,cache=FALSE,warning=FALSE,message=FALSE---- library(ActivityIndex) library(knitr) opt_setup=options(width=52,scipen=1,digits=5) opts_chunk$set(tidy=TRUE) ## ----"AccessCSV",echo=TRUE,eval=FALSE------------- # system.file("extdata","sample_GT3X+.csv.gz",package="ActivityIndex") # system.file("extdata","sample_table.csv.gz",package="ActivityIndex") ## ----"GT3X+_CSV",echo=FALSE,eval=TRUE------------- fname = system.file("extdata", "sample_GT3X+.csv.gz", package = "ActivityIndex") unzipped = R.utils::gunzip(fname, temporary = TRUE, remove = FALSE, overwrite = TRUE) cat(readLines(unzipped, n = 15), sep = "\n") ## ----"Table_CSV",echo=FALSE,eval=TRUE------------- fname = system.file("extdata", "sample_table.csv.gz", package = "ActivityIndex") unzipped = R.utils::gunzip(fname, temporary = TRUE, remove = FALSE, overwrite = TRUE) cat(readLines(unzipped, n = 5), sep = "\n") ## ----"ReadData",echo=TRUE,warning=FALSE,message=FALSE---- sampleGT3XPlus=ReadGT3XPlus(system.file("extdata","sample_GT3X+.csv.gz",package="ActivityIndex")) sampleTable=ReadTable(system.file("extdata", "sample_table.csv.gz",package="ActivityIndex")) ## ----"str_sampleGT3XPlus",echo=TRUE,eval=TRUE----- str(sampleGT3XPlus) ## ----"head_sampleTable",echo=TRUE,eval=TRUE------- head(sampleTable,n=6) ## ----"computeAI_syntax",echo=TRUE,eval=FALSE------ # computeActivityIndex(x, x_sigma0 = NULL, sigma0 = NULL, epoch = 1, hertz) ## ----"computeAI_onthefly",echo=TRUE,eval=TRUE----- AI_sampleTable_x=computeActivityIndex(sampleTable, x_sigma0=sampleTable[1004700:1005600,], epoch=1, hertz=30) AI_sampleGT3XPlus_x=computeActivityIndex(sampleGT3XPlus, x_sigma0=sampleTable[1004700:1005600,], epoch=1, hertz=30) ## ----"compute_sigma0",echo=TRUE,eval=TRUE--------- sample_sigma0=Sigma0(sampleTable[1004700:1005600,],hertz=30) ## ----"computeAI_beforehand",echo=TRUE,eval=TRUE---- AI_sampleTable=computeActivityIndex(sampleTable, sigma0=sample_sigma0, epoch=1, hertz=30) AI_sampleGT3XPlus=computeActivityIndex(sampleGT3XPlus, sigma0=sample_sigma0, epoch=1, hertz=30) ## ----"head_AI",echo=TRUE,eval=TRUE---------------- head(AI_sampleGT3XPlus,n=10) ## ----"computeAI_minute",echo=TRUE,eval=TRUE------- AI_sampleTable_min=computeActivityIndex(sampleTable, sigma0=sample_sigma0, epoch=60, hertz=30) AI_sampleGT3XPlus_min=computeActivityIndex(sampleGT3XPlus, sigma0=sample_sigma0, epoch=60, hertz=30) ## ----"head_AI_min",echo=TRUE,eval=TRUE------------ head(AI_sampleGT3XPlus_min) ## ----"setup_cleanup",echo=FALSE,cache=FALSE,warning=FALSE,message=FALSE---- options(opt_setup) <file_sep> <!-- README.md is generated from README.Rmd. Please edit that file --> @muschellij2 badges: [![Travis build status](https://travis-ci.com/muschellij2/ActivityIndex.svg?branch=master)](https://travis-ci.com/muschellij2/ActivityIndex) [![AppVeyor build status](https://ci.appveyor.com/api/projects/status/github/muschellij2/ActivityIndex?branch=master&svg=true)](https://ci.appveyor.com/project/muschellij2/ActivityIndex) # ActivityIndex ActivityIndex is an R package which provides functions to read and process raw accelerometry data. ## Overview ActivityIndex provides R functions to read raw accelerometry data collected by accelerometers. Specifically, it can directly handle **.csv** data files generated by accelerometer model GT3X+ and software ActiLife by ActiGraph. The package also provides functions to calculate summarizing metrics such as Activity Index (AI), using the raw data. The AI is a way of summarizing densely sampled accelerometry data into given epochs (such as every 1 second or every 15 seconds, etc). Essentially, AI describes the variability of the raw acceleration signals, after normalizing it using systematic noise of the signal. AI is an evolution of the original metric, **Activity Intensity**, proposed in the paper [Normalization and extraction of interpretable metrics from raw accelerometry data](https://doi.org/10.1093/biostatistics/kxt029) by <NAME> et al (2014). The AI addresses some limitation of the original Activity Intensity, and has favorable properties. More details on these properties and a direct comparison of AI versus other metrics such as Activity Count could be found in the paper [An Activity Index for Raw Accelerometry Data and Its Comparison with Other Activity Metrics](https://doi.org/10.1371/journal.pone.0160644). ## Package Installation ActivityIndex software can be installed via GitHub. Users should have `R` installed on their computer before installing ActivityIndex. ### Install devtools package To install ActivityIndex package via GitHub, the user must have installed [devtools](https://cran.r-project.org/package=devtools), which could be completed by using the following R command ``` r install.packages("devtools") ``` ### Install ActivityIndex package The following R command can be used to install the latest version of ActivityIndex via GitHub: ``` r devtools::install_github("javybai/ActivityIndex") ``` ## ActivityIndex User Manual The ActivityIndex package includes a vignette to demonstrate a typical work flow of computing AI. The vignette can either be accessed by R command ``` r browseVignettes(package="ActivityIndex") ``` and interactively browsing or going to <https://javybai.github.io/ActivityIndex/articles/ActivityIndexIntro.html>. ## Further Questions Please contact the author and maintainer <NAME> (jbai \[at\] jhsph \[dot\] edu) or open an issue at GitHub.
2bca639cfde96bd180935e8157babf84a3ce0133
[ "Markdown", "R" ]
3
R
cran/ActivityIndex
4df428ef295f98c82cc3a9759f32ee2675e200ad
f69b499e87edf86937dd67247211367ac1b11caf
refs/heads/master
<repo_name>strDr156/js-slider<file_sep>/slider.js window.onload = function() { // please rename all img to image_index ex. image_1.jpg // settings slider const parentContainer = 'main-slideshow'; const imagesQuantity = 5; const imagesDirectory = './assets/img/'; const imageExpansion = '.jpg'; const width = 400; const height = 300; const units= 'px'; const prevBut = 'prevImg'; const nextBut = 'nextImg'; const stopBut = 'stop'; let slider = document.getElementById(parentContainer); slider.style= `width:`+ width + units +`; height:`+ height + units +`; position: relative; overflow: hidden; `; for(let i = 1; i<=imagesQuantity; i++){ let slide=document.createElement('div'); slide.className = parentContainer + '__image'; slide.innerHTML = '<img src="'+ imagesDirectory + 'image_'+i+imageExpansion+'" width="'+width+units+'" height="'+height+units+'"/>'; slide.style=`position: absolute; left: `+ ((i-1)*width) + units +`; `; slider.appendChild(slide); } // buttons for slider let next = document.createElement('button'); next.id='next'; next.textContent=nextBut; let prev = document.createElement('button'); prev.id = 'prev'; prev.textContent = prevBut; document.body.append( prev,next); let nextButton = document.getElementById('next'); let prevButton = document.getElementById('prev'); let slidesCollection = document.getElementsByClassName(''+ parentContainer +'__image'); let slides = Array.from(slidesCollection); slides[0].classList.add('active'); nextButton.onclick = function(){ slides[0].classList.remove('active'); for(let i = 0; i < slides.length; i++){ let getLeftValue = Number(window.getComputedStyle(slides[i], null).getPropertyValue('left').replace( /px/g, "" )); slides[i].style.left=`${getLeftValue - 400 + units}`; } getLastLeftValue = Number(window.getComputedStyle(slides[4], null).getPropertyValue('left').replace( /px/g, "" )); slides[0].style.left = `${getLastLeftValue + 400 + units}`; slides.push(slides.shift()); slides[0].classList.add('active'); } /* ---- end buttons ----- */ /* ---- navigation ---- */ let navigation = document.createElement('div'); navigation.className = `navigation`; document.body.append(navigation); for(let i = 0 ; i < slides.length; i++ ){ let navItem = document.createElement('button'); navItem.className = `nav-item`; navItem.id = 'navBut'; navigation.appendChild(navItem); } let navBut = document.getElementById('navBut'); navBut.onclick = function(){ if(slides[0].classList.contains('active')){ navBut.style.background = `red`; }else{ navBut.style.background = `#333`; } } /* ---- end navigation ---- */ // nextButton.onclick = function(){ // for(let i = 0; i < slide.length; i++){ // if(slide[i].classList.contains('active')){ // slide[i].style.left = '0'; // // let active = i+1; // // for(let j=0;j<=slide.length-active;j++){ // // slide[j].style.left=-400*j+units; // // } // } // } // let slideNext = slide[i+1]; // slideNext.style.left='0'; // let slideLeftValue = Number(window.getComputedStyle(slide[index], null).getPropertyValue('left').replace(/[^+\d]/g, '')); // slide[i].style.left=`` + slideLeftValue-width + `px`; // slideNext.classList.add('active'); // slideNext.previousElementSibling.classList.remove('active'); // } //let index = 0; // let index1 = 1; // nextButton.onclick = function() { // let slideLeftValue = Number(window.getComputedStyle(slide[index], null).getPropertyValue('left').replace(/[^+\d]/g, '')); // slide[index].style.left=`` + slideLeftValue-width + `px`; // let slideNext = slide[index+1]; // slideNext.style.left='0'; // slideNext.classList.add('active'); // slideNext.previousElementSibling.classList.remove('active'); // index++; // } // nextButton.onclick = function(){ // slide[index].style.left=`` + width + `px`; // let slideNext = slide[index+1]; // slideNext.style.left='0'; // slideNext.classList.add('active'); // slideNext.previousElementSibling.classList.remove('active'); // let slideLeftValue = Number(window.getComputedStyle(slide[index], null).getPropertyValue('left').replace(/[^+\d]/g, '')); // slideNext.previousElementSibling.style.left = index1 *-slideLeftValue + units; // index++; // } // function sliderScroll(){ // getComputedStyle() // } // setTimeout(sliderScroll, 6000); }
caf52fcb9f8c7c6ab4a39a282bfea0d3ca743b53
[ "JavaScript" ]
1
JavaScript
strDr156/js-slider
988b5dcdcfc2384244c85951d2f6839c9a95739f
4cb71ae5656410e1cc378d826cd68c4e97fc6f28
refs/heads/master
<repo_name>pared/spark_cluster_example<file_sep>/README.md # spark_cluster_example Run local spark cluster Based on [this post](https://medium.com/@marcovillarreal_40011/creating-a-spark-standalone-cluster-with-docker-and-docker-compose-ba9d743a157f) <file_sep>/build-images.sh #!/bin/bash set -e docker build base -t spark-base:2.3.1 docker build master -t spark-master:2.3.1 docker build worker -t spark-worker:2.3.1 docker build submit -t spark-submit:2.3.1
44cc2c673c71e6d0431493d4dda6d965a528bca0
[ "Markdown", "Shell" ]
2
Markdown
pared/spark_cluster_example
83d071160f199ac59a02c9f0c2537152a7783fa4
71eb54b4469aef572b795d442851d9c1a71020e5
refs/heads/main
<repo_name>imodclub/ServerAPI<file_sep>/README.md # ServerAPI ServerAPI for E Stock <file_sep>/index.js const express = require("express"); const cors = require("cors"); const mongoose = require("mongoose"); const app = express(); //-------Mongoose Connect ---------- const db = require('./models'); const Role = db.role; mongoose .connect( "mongodb+srv://imodclub:<EMAIL>/stock?retryWrites=true&w=majority", { useNewUrlParser: true, useUnifiedTopology: true } ) .then(() => { console.log("Successfully connect to MongoDB"); initial(); }) .catch((error) => { handleError(error) process.exit() }); mongoose.Promise = global.Promise; function initial() { Role.estimatedDocumentCount((err, count) => { if (!err && count === 0) { new Role({ name: "user" }).save(err => { if (err) { console.log("Error ", err); } console.log("added 'user' to roles collection"); }); new Role({ name: "moderator" }).save(err => { if (err) { console.log("Error " , err); } console.log("added 'moderator' ro roles collection") }); new Role({ name: "admin", }).save((err) => { if (err) { console.log("Error ", err); } console.log("added 'admin' to roles collection"); }); } }) } //-------Mongoose End------------- app.use(cors()); app.use(express.json()); app.use(express.static("public")); app.use(express.urlencoded({ extended: true })); const users = require("./routers/users"); require('./routers/auth.routes')(app); require('./routers/user.routes')(app); app.use("/", users); app.use((err, req, res, next) => { res.status(422).send({ error: err.message }); }); const port = process.env.PORT || 3001; app.listen(port, () => console.log(`Server stated on port ${port}`)); <file_sep>/config/auth.config.js module.exports = { secret:"estock-secret-key" }
5341f4ce173f6d1125c529d32c5cc2cc3c605797
[ "Markdown", "JavaScript" ]
3
Markdown
imodclub/ServerAPI
5a1ccc8ad1d4084525363fc5aa981201a4bdf090
e8291e9515f05bb8d10629cba22df6c9f575a8f1
refs/heads/master
<repo_name>washucode/Akhan-Calculator<file_sep>/README.md # APPLICATION NAME : AKHAN NAME CALCULATOR ## CONTRIBUTORS : <NAME> ## LINK : https://washucode.github.io/Akhan-Calculator/ ## PURPOSE: To find the name of an individiual based on the exact day they were born. ## CONTRIBUTE: To contribute: * Fork Repository. * On your terminal run the command git clone https://github.com/washucode/Akhan-Calculator * Again on you terminal run the command cd Akhan-Calculator. * atom . or code . depending on the text editor you use. * feel free to play around with it. ## BDD: Feature: As a user I want to key in my birthdate so that i can get my Akhan Name. Scenario: User supplies correct birthdate Given that I am on the page with the form When I enter my birthdate correctly And click ‘Submit’ Then I get an alert of my Akhan Name Scenario: User does NOT enter any date Given that I am on the page with the form When I don't enter date on the date picker and click ‘Submit’ Then I see an alert "Your Akhan Name is undefined." ## LICENSE This project is licensed under the MIT License - see the [license.md](license.md) file for details. ## AKNOWLEDGEMENTS [Moringa Cirruculum.Check out Moringa here:] (https://moringaschool.com) W3C Schools. Talk to me: <EMAIL> <file_sep>/js/main.js function calulateAkhan() { //takes input from the datepicker var userDateInput = document.getElementById("inputDate").value; if(userDateInput==="yyyy-mm-dd"){//checks if nothing has been entered and the user returns the default alert('Enter Valid Date'); return false; } var gender ; //the if statement is to check what radio button is checked. if (document.getElementById('femaleChecked').checked) { //to check if female is checked gender = document.getElementById('femaleChecked').value; } else if(document.getElementById('maleChecked').checked){ //to check if male is checked gender = document.getElementById('maleChecked').value; } var century = parseInt(userDateInput.slice(0,2)); //slice date to get century var year = parseInt(userDateInput.slice(2,4)); //slice date to get year var month = parseInt(userDateInput.slice(5,7)); // to get month var day = parseInt(userDateInput.slice(8,10)); //slice date to get day var maleName = ["Kwasi","Kwadwo","Kwabena","Kwaku","Yaw","Kofi","Kwame"];//put in an array for ease of access var femaleName = ["Akosua","Adwoa","Abenaa","Akua","Yaa","Afua","Ama"];//put in an array for ease of access //to calculate exact day of birth var dayofBirth = parseInt(((century / 4) - 2 * century - 1) + ((5 * year / 4)) + ((26 * (month + 1) / 10))+day) % 7; if (dayofBirth < 0){//checks if dayofBirth is negative and converts to positive dayofBirth = dayofBirth * -1; } else if(dayofBirth == 0){ dayofBirth += 7;//the day of birth that returns by 0 is Saturday so this avoids printing out a name thats Sunday } else { dayofBirth = parseInt((((century / 4) - 2 * century - 1) + ((5 * year / 4)) + ((26 * (month + 1) / 10))+day) % 7); } if (gender ==="M"){ //checks if gender is male var mName = maleName[dayofBirth-1];//find out value of gender in index [dayofBirth-1] alert("Your Akhan Name is "+ mName); document.getElementById("displayName").innerHTML = "Your Akhan Name is "+ mName;//write value in html element p } else { //checks if gender is female var fName = femaleName[dayofBirth-1];//find out value of gender in index [dayofBirth-1] alert("Your Akhan Name is "+ fName); document.getElementById("displayName").innerHTML = "Your Akhan Name is "+ fName;//write value in html element p } }
fb116394e0c4c4ad9855331791d8a75db58813e8
[ "Markdown", "JavaScript" ]
2
Markdown
washucode/Akhan-Calculator
8731aca914cdcf885ae5eec4a42b9fb8f759222a
f13c96f6263a2356a60abeb66d48c45de32786e8
refs/heads/main
<file_sep>"""empty message Revision ID: 788a9539c7c6 Revises: <KEY> Create Date: 2021-09-16 18:11:45.263480 """ from alembic import op import sqlalchemy as sa # revision identifiers, used by Alembic. revision = '788a9539c7c6' down_revision = '<KEY>' branch_labels = None depends_on = None def upgrade(): # ### commands auto generated by Alembic - please adjust! ### op.create_table('product', sa.Column('id', sa.Integer(), nullable=False), sa.Column('name', sa.String(length=250), nullable=False), sa.Column('brand', sa.String(length=100), nullable=False), sa.PrimaryKeyConstraint('id') ) # ### end Alembic commands ### def downgrade(): # ### commands auto generated by Alembic - please adjust! ### op.drop_table('product') # ### end Alembic commands ### <file_sep>import React, { useContext, useState, useEffect } from "react"; import { Context } from "../store/appContext"; import "../../styles/home.scss"; export const Home = () => { const { store, actions } = useContext(Context); const [products, setProducts] = useState([]); const [text, setText] = useState(""); const [suggestions, setSuggestions] = useState([]); useEffect(() => { fetch("https://3001-bronze-fox-4ipzyv4w.ws-us15.gitpod.io/api/products") .then(resp => { if (resp.ok) { return resp.json(); } }) .then(json => setProducts(json.data)); }, []); const onChangeHandler = text => { let matches = []; if (text.length > 0) { matches = products.filter(product => { const regex = new RegExp(`${text}`, "gi"); return product.name.match(regex); }); } setSuggestions(matches); setText(text); }; return ( <div className="text-center mt-5"> <div className="container"> <input type="text" className="col-md-12 input" onChange={e => onChangeHandler(e.target.value)} value={text} onBlur={() => setSuggestions([])} /> </div> {suggestions && suggestions.map((suggestion, i) => ( <div onClick={() => setText(suggestion.name)} key={i} className="suggestion col-md-12 justify-content-md-center"> {suggestion.name} </div> ))} </div> ); };
8883d2268ba2e5eee6587614464c9ed55ba3bfe0
[ "JavaScript", "Python" ]
2
Python
manuelabarca/search_4geeks
8cef846cde987b4a86aea36cc9e3e567282e4b08
f6b418ba05b39366d9652fda1274a20f2af8f0cb
refs/heads/master
<repo_name>zcc1307/vowpal_wabbit<file_sep>/vowpalwabbit/cbify.cc #include <float.h> #include "reductions.h" #include "cb_algs.h" #include "rand48.h" #include "bs.h" #include "../explore/cpp/MWTExplorer.h" #include "vw.h" //In the future, the above two's names should be changed to //WARM_START and INTERACTION #define SUPERVISED 1 #define BANDIT 2 #define SUPERVISED_WS 1 #define BANDIT_WS 2 #define UAR 1 #define CIRCULAR 2 #define OVERWRITE 3 #define BANDIT_VALI 1 #define SUPERVISED_VALI_SPLIT 2 #define SUPERVISED_VALI_NOSPLIT 3 #define INSTANCE_WT 1 #define DATASET_WT 2 #define ABS_CENTRAL 1 #define MINIMAX_CENTRAL 2 #define MINIMAX_CENTRAL_ZEROONE 3 #define ABS_CENTRAL_ZEROONE 4 using namespace LEARNER; using namespace MultiWorldTesting; using namespace MultiWorldTesting::SingleAction; using namespace ACTION_SCORE; struct cbify; //Scorer class for use by the exploration library class vw_scorer : public IScorer<example> { public: vector<float> Score_Actions(example& ctx); }; struct vw_recorder : public IRecorder<example> { void Record(example& context, u32 a, float p, string /*unique_key*/) { } virtual ~vw_recorder() { } }; struct cbify_adf_data { example* ecs; example* empty_example; size_t num_actions; }; struct cbify { CB::label cb_label; COST_SENSITIVE::label cs_label; GenericExplorer<example>* generic_explorer; //v_array<float> probs; vw_scorer* scorer; MwtExplorer<example>* mwt_explorer; vw_recorder* recorder; v_array<action_score> a_s; // used as the seed size_t example_counter; vw* all; bool use_adf; // if true, reduce to cb_explore_adf instead of cb_explore cbify_adf_data adf_data; float loss0; float loss1; size_t choices_lambda; size_t warm_start_period; size_t bandit_period; v_array<float> cumulative_costs; v_array<float> lambdas; size_t num_actions; bool ind_bandit; bool ind_supervised; COST_SENSITIVE::label* csls; COST_SENSITIVE::label* csl_empty; CB::label* cbls; CB::label* cbl_empty; polyprediction pred; bool warm_start; float* old_weights; float corrupt_prob_supervised; float corrupt_prob_bandit; size_t corrupt_type_supervised; size_t corrupt_type_bandit; size_t corrupted_label; size_t validation_method; size_t bandit_iter; size_t warm_start_iter; size_t weighting_scheme; v_array<example> supervised_validation; size_t lambda_scheme; float epsilon; float cumulative_variance; size_t overwrite_label; size_t warm_start_type; size_t mc_pred; uint32_t warm_start_train_size; }; float minimax_lambda(float epsilon, size_t num_actions, size_t warm_start_period, size_t bandit_period, size_t dim) { /* if ( (epsilon / num_actions) * bandit_period >= dim ) return 1.0; else { float z = sqrt( dim * ( (epsilon / num_actions) * bandit_period + warm_start_period) - (epsilon / num_actions) * bandit_period * warm_start_period ); float numer = (epsilon / num_actions) + warm_start_period * (epsilon / num_actions) * (1/z); float denom = 1 + (epsilon / num_actions) + (warm_start_period - bandit_period) * (epsilon / num_actions) * (1/z); //cout<<"z = "<<z<<endl; //cout<<"numer = "<<numer<<endl; //cout<<"denom = "<<denom<<endl; return numer / denom; } */ return epsilon / (num_actions + epsilon); } void setup_lambdas(cbify& data, example& ec) { // The lambdas are in fact arranged in ascending order (the middle lambda is 0.5) v_array<float>& lambdas = data.lambdas; //bandit only if (!data.ind_supervised && data.ind_bandit) { for (uint32_t i = 0; i<data.choices_lambda; i++) lambdas[i] = 1.0; return; } //supervised only if (!data.ind_bandit && data.ind_supervised) { for (uint32_t i = 0; i<data.choices_lambda; i++) lambdas[i] = 0.0; return; } //if no supervised and no bandit, then as there are no updates anyway, //we are still fine uint32_t mid = data.choices_lambda / 2; if (data.lambda_scheme == ABS_CENTRAL || data.lambda_scheme == ABS_CENTRAL_ZEROONE) lambdas[mid] = 0.5; else lambdas[mid] = minimax_lambda(data.epsilon, data.num_actions, data.warm_start_period, data.bandit_period, ec.num_features); for (uint32_t i = mid; i > 0; i--) lambdas[i-1] = lambdas[i] / 2; for (uint32_t i = mid+1; i < data.choices_lambda; i++) lambdas[i] = 1 - (1-lambdas[i-1]) / 2; if (data.lambda_scheme == MINIMAX_CENTRAL_ZEROONE || data.lambda_scheme == ABS_CENTRAL_ZEROONE) { lambdas[0] = 0.0; lambdas[data.choices_lambda-1] = 1.0; } //cout<<"lambdas:"<<endl; //for (uint32_t i = 0; i < data.choices_lambda; i++) // cout<<lambdas[i]<<endl; } float rand_zeroone(vw* all) { float f = merand48(all->random_state); //cout<<f<<endl; return f; } size_t generate_uar_action(cbify& data) { float rand = rand_zeroone(data.all); //cout<<rand<<endl; for (size_t i = 1; i <= data.num_actions; i++) { if (rand <= float(i) / data.num_actions) return i; } return data.num_actions; } size_t corrupt_action(size_t action, cbify& data, size_t ec_type) { float corrupt_prob; size_t corrupt_type; if (ec_type == SUPERVISED) { corrupt_prob = data.corrupt_prob_supervised; corrupt_type = data.corrupt_type_supervised; } else { corrupt_prob = data.corrupt_prob_bandit; corrupt_type = data.corrupt_type_bandit; } float rand = rand_zeroone(data.all); if (rand < corrupt_prob) { if (corrupt_type == UAR) return generate_uar_action(data); else if (corrupt_type == OVERWRITE) return data.overwrite_label; else return (action % data.num_actions) + 1; } else return action; } vector<float> vw_scorer::Score_Actions(example& ctx) { vector<float> probs_vec; for(uint32_t i = 0; i < ctx.pred.a_s.size(); i++) probs_vec.push_back(ctx.pred.a_s[i].score); return probs_vec; } float loss(cbify& data, uint32_t label, uint32_t final_prediction) { if (label != final_prediction) return data.loss1; else return data.loss0; } template<class T> inline void delete_it(T* p) { if (p != nullptr) delete p; } bool ind_update(cbify& data, size_t ec_type) { if (ec_type == SUPERVISED) return data.ind_supervised; else return data.ind_bandit; } float compute_weight_multiplier(cbify& data, size_t i, size_t ec_type) { float weight_multiplier; float ws_train_size = data.warm_start_train_size; float intr_train_size = data.bandit_period; if (data.validation_method != BANDIT_VALI) { if (ec_type == SUPERVISED && data.warm_start_iter >= ws_train_size) return 0.0; } float total_size = ws_train_size + intr_train_size; if (data.weighting_scheme == INSTANCE_WT) { float total_weight = (1-data.lambdas[i]) * ws_train_size + data.lambdas[i] * intr_train_size; if (ec_type == SUPERVISED) weight_multiplier = (1-data.lambdas[i]) * total_size / total_weight; else weight_multiplier = data.lambdas[i] * total_size / total_weight; } else { if (ec_type == SUPERVISED) weight_multiplier = (1-data.lambdas[i]) * total_size / ws_train_size; else weight_multiplier = data.lambdas[i] * total_size / intr_train_size; } /*if (ec_type == SUPERVISED) { if (data.lambdas[i] >= 0.5) weight_multiplier = (1 - data.lambdas[i]) / data.lambdas[i]; else weight_multiplier = 1; if (data.validation_method != BANDIT_VALI && data.warm_start_iter >= data.warm_start_train_size) weight_multiplier = 0.0; } else { if (data.lambdas[i] >= 0.5) weight_multiplier = 1; else weight_multiplier = data.lambdas[i] / (1-data.lambdas[i]); if (data.weighting_scheme == DATASET_WT) weight_multiplier = weight_multiplier * data.warm_start_train_size / data.bandit_period; //(data.bandit_iter+1) * (data.bandit_iter+2) }*/ return weight_multiplier; } uint32_t find_min(v_array<float> arr) { float min_val = FLT_MAX; uint32_t argmin = 0; for (uint32_t i = 0; i < arr.size(); i++) { //cout<<arr[i]<<endl; if (arr[i] < min_val) { min_val = arr[i]; argmin = i; } } return argmin; } void finish(cbify& data) { cout<<"Ideal average variance = "<<data.num_actions / data.epsilon<<endl; cout<<"Measured average variance = "<<data.cumulative_variance / data.bandit_period<<endl; CB::cb_label.delete_label(&data.cb_label); //data.probs.delete_v(); delete_it(data.scorer); delete_it(data.generic_explorer); delete_it(data.mwt_explorer); delete_it(data.recorder); data.a_s.delete_v(); data.lambdas.delete_v(); data.cumulative_costs.delete_v(); if (data.validation_method != BANDIT_VALI ) { for (size_t i = 0; i < data.warm_start_period; ++i) VW::dealloc_example(MULTICLASS::mc_label.delete_label, data.supervised_validation[i]); data.supervised_validation.delete_v(); } if (data.use_adf) { for (size_t a = 0; a < data.adf_data.num_actions; ++a) VW::dealloc_example(CB::cb_label.delete_label, data.adf_data.ecs[a]); VW::dealloc_example(CB::cb_label.delete_label, *data.adf_data.empty_example); free(data.adf_data.ecs); free(data.adf_data.empty_example); //TODO: Use CB::cb_label.delete_label / CS here for (size_t a = 0; a < data.adf_data.num_actions; ++a) data.csls[a].costs.delete_v(); data.csl_empty->costs.delete_v(); free(data.csls); free(data.csl_empty); free(data.cbls); free(data.cbl_empty); free(data.old_weights); } else { COST_SENSITIVE::cs_label.delete_label(&data.cs_label); } } void copy_example_to_adf(cbify& data, example& ec) { auto& adf_data = data.adf_data; const uint64_t ss = data.all->weights.stride_shift(); const uint64_t mask = data.all->weights.mask(); for (size_t a = 0; a < adf_data.num_actions; ++a) { auto& eca = adf_data.ecs[a]; // clear label auto& lab = eca.l.cb; CB::cb_label.default_label(&lab); // copy data VW::copy_example_data(false, &eca, &ec); // offset indicies for given action for (features& fs : eca) { for (feature_index& idx : fs.indicies) { idx = ((((idx >> ss) * 28904713) + 4832917 * (uint64_t)a) << ss) & mask; } } // avoid empty example by adding a tag (hacky) if (CB_ALGS::example_is_newline_not_header(eca) && CB::example_is_test(eca)) { eca.tag.push_back('n'); } } } void convert_mc_to_cs(cbify& data, example& ec) { //generate cost-sensitive label (only for CSOAA's use - this will be retracted at the end) COST_SENSITIVE::label& csl = data.cs_label; size_t label = ec.l.multi.label; for (uint32_t j = 0; j < data.num_actions; j++) { csl.costs[j].class_index = j+1; csl.costs[j].x = loss(data, label, j+1); } ec.l.cs = csl; } size_t predict_sublearner_noadf(cbify& data, example& ec, uint32_t i) { //For vw's internal reason, we need to first have a cs label before //using csoaa to predict MULTICLASS::label_t ld = ec.l.multi; convert_mc_to_cs(data, ec); data.all->cost_sensitive->predict(ec, i); ec.l.multi = ld; return ec.pred.multiclass; } void accumulate_costs_ips(cbify& data, example& ec) { CB::cb_class& cl = data.cb_label.costs[0]; // validation using bandit data if (data.validation_method == BANDIT_VALI) { //IPS for approximating the cumulative costs for all lambdas for (uint32_t i = 0; i < data.choices_lambda; i++) { uint32_t action = predict_sublearner_noadf(data, ec, i); if (action == cl.action) data.cumulative_costs[i] += cl.cost / cl.probability; //cout<<data.cumulative_costs[i]<<endl; } //cout<<endl; } else //validation using supervised data (their labels are already set to cost-sensitive labels) { //only update cumulative costs every warm_start_period iterations if (abs(log2(data.bandit_iter) - floor(log2(data.bandit_iter))) < 1e-4) { for (uint32_t i = 0; i < data.choices_lambda; i++) data.cumulative_costs[i] = 0; //cout<<"updating validation error on supervised data: " << data.bandit_iter / data.warm_start_period << endl; for (uint32_t i = 0; i < data.choices_lambda; i++) { //go over the supervised validation set for (uint32_t j = 0; j < data.warm_start_period; j++) { example& ec_valid = data.supervised_validation[j]; uint32_t action = predict_sublearner_noadf(data, ec_valid, i); data.cumulative_costs[i] += loss(data, ec_valid.l.multi.label, action); } //cout<<data.cumulative_costs[i]<<endl; } //cout<<endl; } } } size_t predict_cs(cbify& data, example& ec) { uint32_t argmin = find_min(data.cumulative_costs); //cout<<argmin<<endl; return predict_sublearner_noadf(data, ec, argmin); } void learn_cs(cbify& data, example& ec, size_t ec_type) { float old_weight = ec.weight; for (uint32_t i = 0; i < data.choices_lambda; i++) { float weight_multiplier = compute_weight_multiplier(data, i, ec_type); ec.weight = old_weight * weight_multiplier; data.all->cost_sensitive->learn(ec, i); } ec.weight = old_weight; } void predict_or_learn_cs(cbify& data, example& ec, size_t ec_type) { MULTICLASS::label_t ld = ec.l.multi; //predict predict_cs(data, ec); data.mc_pred = ec.pred.multiclass; //learn //first, corrupt fully supervised example ec's label here ec.l.multi.label = data.corrupted_label; convert_mc_to_cs(data, ec); if (ind_update(data, ec_type)) learn_cs(data, ec, ec_type); //set the label of ec back to a multiclass label ec.l.multi = ld; ec.pred.multiclass = data.mc_pred; } void convert_mc_to_cb(cbify& data, example& ec, uint32_t action) { auto& cl = data.cb_label.costs[0]; cl.action = action; cl.probability = ec.pred.a_s[action-1].score; if(!cl.action) THROW("No action with non-zero probability found!"); cl.cost = loss(data, data.corrupted_label, action); ec.l.cb = data.cb_label; } uint32_t predict_bandit(cbify& data, base_learner& base, example& ec) { // we need the cb cost array to be an empty array to make cb prediction ec.l.cb.costs = v_init<CB::cb_class>(); // TODO: not sure why we need the following sentence ec.pred.a_s = data.a_s; uint32_t argmin = find_min(data.cumulative_costs); base.predict(ec, argmin); data.pred = ec.pred; uint32_t action = data.mwt_explorer->Choose_Action(*data.generic_explorer, StringUtils::to_string(data.example_counter++), ec); ec.l.cb.costs.delete_v(); return action; } void learn_bandit(cbify& data, base_learner& base, example& ec, size_t ec_type) { float old_weight = ec.weight; for (uint32_t i = 0; i < data.choices_lambda; i++) { float weight_multiplier = compute_weight_multiplier(data, i, ec_type); ec.weight = old_weight * weight_multiplier; base.learn(ec, i); } ec.weight = old_weight; } void predict_or_learn_bandit(cbify& data, base_learner& base, example& ec, size_t ec_type) { MULTICLASS::label_t ld = ec.l.multi; uint32_t action = predict_bandit(data, base, ec); data.mc_pred = action; convert_mc_to_cb(data, ec, action); // accumulate the cumulative costs of lambdas, given data.cb_label has the ips info if (ec_type == BANDIT) { accumulate_costs_ips(data, ec); ec.l.cb = data.cb_label; //make sure the prediction here is a cb prediction ec.pred = data.pred; } if (ind_update(data, ec_type)) learn_bandit(data, base, ec, ec_type); //data.a_s.erase(); data.a_s = ec.pred.a_s; ec.l.multi = ld; ec.pred.multiclass = action; } void add_to_sup_validation(cbify& data, example& ec) { MULTICLASS::label_t ld = ec.l.multi; ec.l.multi.label = data.corrupted_label; example* ec_copy = calloc_or_throw<example>(1); VW::copy_example_data(false, ec_copy, &ec, 0, MULTICLASS::mc_label.copy_label); ec.l.multi = ld; // I believe we cannot directly do push_back(ec), as the label won't be deeply copied and that space will be // reallocated when the example fall out of the predict_or_learn scope data.supervised_validation.push_back(*ec_copy); free(ec_copy); } void accumulate_variance(cbify& data, example& ec) { size_t pred_best_approx = predict_cs(data, ec); data.cumulative_variance += 1.0 / data.a_s[pred_best_approx-1].score; //cout<<"variance at bandit round "<< data.bandit_iter << " = " << 1.0 / data.a_s[pred_best_approx-1].score << endl; //cout<<pred_best_approx<<endl; } template <bool is_learn> void predict_or_learn(cbify& data, base_learner& base, example& ec) { //Store the multiclass input label //cout<<ld.label<<endl; // Initialize the lambda vector if (data.warm_start_iter == 0 && data.bandit_iter == 0) setup_lambdas(data, ec); if (data.warm_start_iter < data.warm_start_period) // Call the cost-sensitive learner directly { data.corrupted_label = corrupt_action(ec.l.multi.label, data, SUPERVISED); if (data.warm_start_type == SUPERVISED_WS) predict_or_learn_cs(data, ec, SUPERVISED); else predict_or_learn_bandit(data, base, ec, SUPERVISED); if (data.validation_method != BANDIT_VALI) add_to_sup_validation(data, ec); ec.weight = 0; ec.pred.multiclass = data.mc_pred; data.warm_start_iter++; } else if (data.bandit_iter < data.bandit_period) //Call the cb_explore learner. It returns a vector of probabilities for each action { data.corrupted_label = corrupt_action(ec.l.multi.label, data, BANDIT); predict_or_learn_bandit(data, base, ec, BANDIT); data.bandit_iter++; if (data.bandit_iter == data.bandit_period) { cout<<"Ideal average variance = "<<data.num_actions / data.epsilon<<endl; cout<<"Measured average variance = "<<data.cumulative_variance / data.bandit_period<<endl; } // accumulate the cumulative variances, given we have data.a_s has the score info accumulate_variance(data, ec); ec.pred.multiclass = data.mc_pred; } else { //skipping //base.predict(ec, argmin); ec.pred.multiclass = 0; ec.weight = 0; } } uint32_t predict_sublearner_adf(cbify& data, base_learner& base, example& ec, uint32_t i) { //cout<<"predict using sublearner "<< i <<endl; copy_example_to_adf(data, ec); example* ecs = data.adf_data.ecs; example* empty = data.adf_data.empty_example; for (size_t a = 0; a < data.adf_data.num_actions; ++a) { base.predict(ecs[a], i); //data.all->cost_sensitive->predict(ecs[a], argmin); } base.predict(*empty, i); //data.all->cost_sensitive->predict(*empty, argmin); uint32_t pred_action = ecs[0].pred.a_s[0].action+1; return pred_action; } size_t predict_cs_adf(cbify& data, base_learner& base, example& ec) { uint32_t argmin = find_min(data.cumulative_costs); return predict_sublearner_adf(data, base, ec, argmin); } void add_to_sup_validation_adf(cbify& data, example& ec) { //cout<<ec.l.cs.costs.size()<<endl; example* ec_copy = calloc_or_throw<example>(1); VW::copy_example_data(false, ec_copy, &ec, 0, MULTICLASS::mc_label.copy_label); data.supervised_validation.push_back(*ec_copy); free(ec_copy); } void accumulate_costs_ips_adf(cbify& data, example& ec, base_learner& base) { CB::cb_class& cl = data.cb_label.costs[0]; if (data.validation_method == BANDIT_VALI) { //IPS for approximating the cumulative costs for all lambdas for (uint32_t i = 0; i < data.choices_lambda; i++) { uint32_t action = predict_sublearner_adf(data, base, ec, i); if (action == cl.action) data.cumulative_costs[i] += cl.cost / cl.probability; //cout<<data.cumulative_costs[i]<<endl; } //cout<<endl; } else { //only update cumulative costs every warm_start_period iterations if ( data.bandit_iter >= 1 && abs( log2(data.bandit_iter+1) - floor(log2(data.bandit_iter+1)) ) < 1e-4 ) { for (uint32_t i = 0; i < data.choices_lambda; i++) data.cumulative_costs[i] = 0; uint32_t num_epochs = ceil(log2(data.bandit_period)); uint32_t epoch = log2(data.bandit_iter+1) - 1; uint32_t ws_train_size = data.warm_start_train_size; uint32_t ws_vali_size = data.warm_start_period - data.warm_start_train_size; float batch_vali_size = ((float) ws_vali_size) / num_epochs; uint32_t lb, ub; if (data.validation_method == SUPERVISED_VALI_SPLIT) { lb = ws_train_size + ceil(batch_vali_size * epoch); ub = ws_train_size + ceil(batch_vali_size * (epoch + 1)); } else { lb = ws_train_size; ub = ws_train_size + ws_vali_size; } //cout<<"updating validation error on supervised data: " << data.bandit_iter / data.warm_start_period << endl; for (uint32_t i = 0; i < data.choices_lambda; i++) { for (uint32_t j = lb; j < ub; j++) { example& ec_valid = data.supervised_validation[j]; uint32_t pred_label = predict_sublearner_adf(data, base, ec_valid, i); data.cumulative_costs[i] += loss(data, ec_valid.l.multi.label, pred_label); //cout<<ec_valid.l.multi.label<<" "<<pred_label<<endl; } //cout<<data.cumulative_costs[i]<<endl; } } } } void accumulate_variance_adf(cbify& data, base_learner& base, example& ec) { size_t pred_best_approx = predict_cs_adf(data, base, ec); float temp_variance; for (size_t a = 0; a < data.adf_data.num_actions; ++a) if (pred_best_approx == data.a_s[a].action + 1) temp_variance = 1.0 / data.a_s[a].score; data.cumulative_variance += temp_variance; //cout<<"variance at bandit round "<< data.bandit_iter << " = " << temp_variance << endl; //cout<<pred_pi<<" "<<pred_best_approx<<" "<<ld.label<<endl; } void multiclass_to_cs_adf(cbify& data, COST_SENSITIVE::label* csls, size_t corrupted_label) { for (size_t a = 0; a < data.adf_data.num_actions; ++a) { csls[a].costs[0].class_index = a+1; csls[a].costs[0].x = loss(data, corrupted_label, a+1); } } void generate_corrupted_cs_adf(cbify& data, MULTICLASS::label_t ld, size_t corrupted_label) { //suppose copy_example_data has already been called example* ecs = data.adf_data.ecs; example* empty_example = data.adf_data.empty_example; //generate cost-sensitive label (only for CSOAA's use - this will be retracted at the end) COST_SENSITIVE::label* csls = data.csls; COST_SENSITIVE::label* csl_empty = data.csl_empty; multiclass_to_cs_adf(data, csls, corrupted_label); for (size_t a = 0; a < data.adf_data.num_actions; ++a) { ecs[a].l.cs = csls[a]; //cout<<ecs[a].l.cs.costs.size()<<endl; } empty_example->l.cs = *csl_empty; } void learn_cs_adf(cbify& data, size_t ec_type) { example* ecs = data.adf_data.ecs; example* empty_example = data.adf_data.empty_example; for (size_t a = 0; a < data.adf_data.num_actions; ++a) data.old_weights[a] = ecs[a].weight; for (uint32_t i = 0; i < data.choices_lambda; i++) { float weight_multiplier = compute_weight_multiplier(data, i, ec_type); //cout<<"weight multiplier in sup = "<<weight_multiplier<<endl; for (size_t a = 0; a < data.adf_data.num_actions; ++a) { ecs[a].weight = data.old_weights[a] * weight_multiplier; data.all->cost_sensitive->learn(ecs[a],i); } data.all->cost_sensitive->learn(*empty_example,i); } //Seems like we don't need to set the weights back as this example will be //discarded anyway for (size_t a = 0; a < data.adf_data.num_actions; ++a) ecs[a].weight = data.old_weights[a]; } void predict_or_learn_cs_adf(cbify& data, base_learner& base, example& ec, bool is_update, size_t ec_type) { //Store the multiclass input label MULTICLASS::label_t ld = ec.l.multi; uint32_t best_action = predict_cs_adf(data, base, ec); //data.all->cost_sensitive->predict(ec,argmin); //generate cost-sensitive label // ecs[a].weight *= 1; // cout << "size cbify = " << ecs[a].l.cs.costs.size() << endl; size_t corrupted_label = corrupt_action(ld.label, data, ec_type); generate_corrupted_cs_adf(data, ld, corrupted_label); if (is_update) learn_cs_adf(data, ec_type); ec.pred.multiclass = best_action; ec.l.multi = ld; //a hack here - allocated memories not deleted //to be corrected if (ec_type == SUPERVISED && data.validation_method != BANDIT_VALI) add_to_sup_validation_adf(data, ec); } size_t predict_bandit_adf(cbify& data, base_learner& base, example& ec) { uint32_t argmin = find_min(data.cumulative_costs); predict_sublearner_adf(data, base, ec, argmin); // get output scores auto& out_ec = data.adf_data.ecs[0]; uint32_t idx = data.mwt_explorer->Choose_Action( *data.generic_explorer, StringUtils::to_string(data.example_counter++), out_ec) - 1; data.a_s.erase(); for (size_t a = 0; a < data.adf_data.num_actions; ++a) data.a_s.push_back({out_ec.pred.a_s[a].action, out_ec.pred.a_s[a].score}); return idx; } void generate_corrupted_cb_adf(cbify& data, CB::cb_class& cl, MULTICLASS::label_t& ld, size_t idx, size_t corrupted_label) { auto& out_ec = data.adf_data.ecs[0]; cl.action = out_ec.pred.a_s[idx].action + 1; cl.probability = out_ec.pred.a_s[idx].score; if(!cl.action) THROW("No action with non-zero probability found!"); cl.cost = loss(data, corrupted_label, cl.action); } void learn_bandit_adf(cbify& data, base_learner& base, size_t ec_type) { example* ecs = data.adf_data.ecs; example* empty_example = data.adf_data.empty_example; for (size_t a = 0; a < data.adf_data.num_actions; ++a) data.old_weights[a] = ecs[a].weight; for (uint32_t i = 0; i < data.choices_lambda; i++) { float weight_multiplier = compute_weight_multiplier(data, i, ec_type); //cout<<"learn in sublearner "<< i <<" with weight multiplier "<<weight_multiplier<<endl; for (size_t a = 0; a < data.adf_data.num_actions; ++a) { ecs[a].weight = data.old_weights[a] * weight_multiplier; base.learn(ecs[a], i); } base.learn(*empty_example, i); } for (size_t a = 0; a < data.adf_data.num_actions; ++a) ecs[a].weight = data.old_weights[a]; } void predict_or_learn_bandit_adf(cbify& data, base_learner& base, example& ec, bool is_update, size_t ec_type) { //Store the multiclass input label MULTICLASS::label_t ld = ec.l.multi; //copy_example_to_adf(data, ec); //for (size_t a = 0; a < data.adf_data.num_actions; ++a) // data.cbls[a].costs = data.adf_data.ecs[a].l.cb.costs; //data.cbl_empty->costs = data.adf_data.empty_example->l.cb.costs; //size_t pred_pi = predict_cs_adf(data, base, ec); uint32_t idx = predict_bandit_adf(data, base, ec); CB::cb_class cl; size_t corrupted_label = corrupt_action(ld.label, data, ec_type); generate_corrupted_cb_adf(data, cl, ld, idx, corrupted_label); // accumulate the cumulative costs of lambdas if (ec_type == BANDIT) { data.cb_label.costs[0] = cl; //accumulate_costs_ips_adf(data, ec, base); } // add cb label to chosen action auto& lab = data.adf_data.ecs[cl.action - 1].l.cb; lab.costs.push_back(cl); if (ec_type == BANDIT && data.validation_method == BANDIT_VALI) accumulate_costs_ips_adf(data, ec, base); if (is_update) learn_bandit_adf(data, base, ec_type); if (ec_type == BANDIT && data.validation_method != BANDIT_VALI) accumulate_costs_ips_adf(data, ec, base); if (ec_type == BANDIT) accumulate_variance_adf(data, base, ec); lab.costs.delete_v(); ec.pred.multiclass = cl.action; if (ec_type == SUPERVISED && data.validation_method != BANDIT_VALI) add_to_sup_validation_adf(data, ec); } template <bool is_learn> void predict_or_learn_adf(cbify& data, base_learner& base, example& ec) { if (data.warm_start_iter == 0 && data.bandit_iter == 0) setup_lambdas(data, ec); copy_example_to_adf(data, ec); // As we will be processing the examples with cs or cb labels, // we need to store the default cb label so that the next time we call copy_example_to_adf // we can free it successfully (that is the whole purpose of data.cbls) for (size_t a = 0; a < data.adf_data.num_actions; ++a) data.cbls[a].costs = data.adf_data.ecs[a].l.cb.costs; data.cbl_empty->costs = data.adf_data.empty_example->l.cb.costs; if (data.warm_start_iter < data.warm_start_period) // Call the cost-sensitive learner directly { if (data.warm_start_type == SUPERVISED_WS) predict_or_learn_cs_adf(data, base, ec, data.ind_supervised, SUPERVISED); else predict_or_learn_bandit_adf(data, base, ec, data.ind_supervised, SUPERVISED); ec.weight = 0; data.warm_start_iter++; } else if (data.bandit_iter < data.bandit_period) // call the bandit learner { predict_or_learn_bandit_adf(data, base, ec, data.ind_bandit, BANDIT); data.bandit_iter++; //if (data.bandit_iter == data.bandit_period) //{} } else { ec.pred.multiclass = 0; ec.weight = 0; } //data.adf_data.ecs[0].pred.a_s.erase(); for (size_t a = 0; a < data.adf_data.num_actions; ++a) data.adf_data.ecs[a].l.cb.costs = data.cbls[a].costs; data.adf_data.empty_example->l.cb.costs = data.cbl_empty->costs; } void init_adf_data(cbify& data, const size_t num_actions) { auto& adf_data = data.adf_data; adf_data.num_actions = num_actions; adf_data.ecs = VW::alloc_examples(CB::cb_label.label_size, num_actions); adf_data.empty_example = VW::alloc_examples(CB::cb_label.label_size, 1); for (size_t a=0; a < num_actions; ++a) { auto& lab = adf_data.ecs[a].l.cb; CB::cb_label.default_label(&lab); } CB::cb_label.default_label(&adf_data.empty_example->l.cb); adf_data.empty_example->in_use = true; adf_data.empty_example->pred.a_s = v_init<action_score>(); data.csls = calloc_or_throw<COST_SENSITIVE::label>(num_actions); data.csl_empty = calloc_or_throw<COST_SENSITIVE::label>(1); data.cbls = calloc_or_throw<CB::label>(num_actions); data.cbl_empty = calloc_or_throw<CB::label>(1); data.old_weights = calloc_or_throw<float>(num_actions); data.csl_empty->costs = v_init<COST_SENSITIVE::wclass>(); data.csl_empty->costs.push_back({0, 0, 0, 0}); data.csl_empty->costs[0].class_index = 0; data.csl_empty->costs[0].x = FLT_MAX; for (uint32_t a = 0; a < num_actions; ++a) { data.csls[a].costs = v_init<COST_SENSITIVE::wclass>(); data.csls[a].costs.push_back({0, a+1, 0, 0}); //cout<<data.csls[a].costs.size()<<endl; } data.cb_label.costs = v_init<CB::cb_class>(); data.cb_label.costs.push_back({0, 1, 0, 0}); } base_learner* cbify_setup(vw& all) { //parse and set arguments if (missing_option<size_t, true>(all, "cbify", "Convert multiclass on <k> classes into a contextual bandit problem")) return nullptr; new_options(all, "CBIFY options") ("loss0", po::value<float>(), "loss for correct label") ("loss1", po::value<float>(), "loss for incorrect label") ("warm_start", po::value<size_t>(), "number of training examples for warm start") ("bandit", po::value<size_t>(), "number of training examples for bandit processing") ("choices_lambda", po::value<size_t>(), "numbers of lambdas importance weights to aggregate") ("no_supervised", "indicator of using supervised only") ("no_bandit", "indicator of using bandit only") ("corrupt_prob_supervised", po::value<float>(), "probability of label corruption in the supervised part") ("corrupt_prob_bandit", po::value<float>(), "probability of label corruption in the bandit part") ("corrupt_type_supervised", po::value<size_t>(), "type of label corruption in the supervised part (1 is uar, 2 is circular)") ("corrupt_type_bandit", po::value<size_t>(), "probability of label corruption in the bandit part (1 is uar, 2 is circular)") ("validation_method", po::value<size_t>(), "lambda selection criterion (1 is using bandit with progressive validation, 2 is using supervised)") ("weighting_scheme", po::value<size_t>(), "weighting scheme (1 is per instance weighting, 2 is per dataset weighting (where we use a diminishing weighting scheme) )") ("lambda_scheme", po::value<size_t>(), "Lambda set scheme (1 is expanding based on center 0.5, 2 is expanding based on center=minimax lambda, 3 is expanding based on center=minimax lambda along with forcing 0,1 in Lambda )") ("overwrite_label", po::value<size_t>(), "the label type 3 corruptions (overwriting) turn to") ("warm_start_type", po::value<size_t>(), "the type of warm start approach (1 is supervised warm start, 2 is contextual bandit warm start)"); add_options(all); po::variables_map& vm = all.vm; uint32_t num_actions = (uint32_t)vm["cbify"].as<size_t>(); cbify& data = calloc_or_throw<cbify>(); data.use_adf = count(all.args.begin(), all.args.end(),"--cb_explore_adf") > 0; data.loss0 = vm.count("loss0") ? vm["loss0"].as<float>() : 0.f; data.loss1 = vm.count("loss1") ? vm["loss1"].as<float>() : 1.f; data.ind_supervised = vm.count("no_supervised") ? false : true; data.ind_bandit = vm.count("no_bandit") ? false : true; data.recorder = new vw_recorder(); data.mwt_explorer = new MwtExplorer<example>("vw",*data.recorder); data.scorer = new vw_scorer(); data.a_s = v_init<action_score>(); //data.probs = v_init<float>(); data.generic_explorer = new GenericExplorer<example>(*data.scorer, (u32)num_actions); data.all = &all; //cout<<data.warm_start_period<<endl; data.warm_start_period = vm.count("warm_start") ? vm["warm_start"].as<size_t>() : 0; data.bandit_period = vm.count("bandit") ? vm["bandit"].as<size_t>() : UINT32_MAX; //ideally should be the size of the dataset //cout<<data.warm_start_period<<endl; data.choices_lambda = vm.count("choices_lambda") ? vm["choices_lambda"].as<size_t>() : 1; data.corrupt_prob_supervised = vm.count("corrupt_prob_supervised") ? vm["corrupt_prob_supervised"].as<float>() : 0.0; data.corrupt_prob_bandit = vm.count("corrupt_prob_bandit") ? vm["corrupt_prob_bandit"].as<float>() : 0.0; data.corrupt_type_supervised = vm.count("corrupt_type_supervised") ? vm["corrupt_type_supervised"].as<size_t>() : UAR; // 1 is the default value data.corrupt_type_bandit = vm.count("corrupt_type_bandit") ? vm["corrupt_type_bandit"].as<size_t>() : UAR; // 1 is the default value data.validation_method = vm.count("validation_method") ? vm["validation_method"].as<size_t>() : BANDIT_VALI; // 1 is the default value data.weighting_scheme = vm.count("weighting_scheme") ? vm["weighting_scheme"].as<size_t>() : INSTANCE_WT; // 1 is the default value data.lambda_scheme = vm.count("lambda_scheme") ? vm["lambda_scheme"].as<size_t>() : ABS_CENTRAL; data.epsilon = vm.count("epsilon") ? vm["epsilon"].as<float>() : 0.05; data.overwrite_label = vm.count("overwrite_label") ? vm["overwrite_label"].as<size_t>() : 1; data.warm_start_type = vm.count("warm_start_type") ? vm["warm_start_type"].as<size_t>() : SUPERVISED_WS; //cout<<"does epsilon exist?"<<vm.count("epsilon")<<endl; //cout<<"epsilon = "<<data.epsilon<<endl; if (data.validation_method != BANDIT_VALI) { data.supervised_validation = v_init<example>(); //calloc_or_throw<example>(data.warm_start_period); data.warm_start_train_size = data.warm_start_period / 2; } else data.warm_start_train_size = data.warm_start_period; data.bandit_iter = 0; data.warm_start_iter = 0; //generate_lambdas(data.lambdas, data.choices_lambda); data.lambdas = v_init<float>(); for (uint32_t i = 0; i < data.choices_lambda; i++) data.lambdas.push_back(0.); for (size_t i = 0; i < data.choices_lambda; i++) data.cumulative_costs.push_back(0.); data.cumulative_variance = 0; data.num_actions = num_actions; if (data.use_adf) { init_adf_data(data, num_actions); } else { //data.csls = calloc_or_throw<COST_SENSITIVE::label>(1); //auto& csl = data.csls[0]; data.cs_label.costs = v_init<COST_SENSITIVE::wclass>(); //Note: these two lines are important, otherwise the cost sensitive vector seems to be unbounded. for (uint32_t a = 0; a < num_actions; ++a) data.cs_label.costs.push_back({0, a+1, 0, 0}); data.cb_label.costs = v_init<CB::cb_class>(); data.cb_label.costs.push_back({0, 1, 0, 0}); } if (count(all.args.begin(), all.args.end(),"--cb_explore") == 0 && !data.use_adf) { all.args.push_back("--cb_explore"); stringstream ss; ss << num_actions; all.args.push_back(ss.str()); } if (count(all.args.begin(), all.args.end(), "--baseline")) { all.args.push_back("--lr_multiplier"); stringstream ss; ss << max<float>(abs(data.loss0), abs(data.loss1)) / (data.loss1 - data.loss0); all.args.push_back(ss.str()); } base_learner* base = setup_base(all); all.delete_prediction = nullptr; learner<cbify>* l; if (data.use_adf) { l = &init_multiclass_learner(&data, base, predict_or_learn_adf<true>, predict_or_learn_adf<false>, all.p, data.choices_lambda); } else { l = &init_multiclass_learner(&data, base, predict_or_learn<true>, predict_or_learn<false>, all.p, data.choices_lambda); } l->set_finish(finish); return make_base(*l); } <file_sep>/scripts/run_vw_commands.py import subprocess from itertools import product import os import math import argparse import time import glob import re class model: def __init__(self): # Setting up argument-independent learning parameters in the constructor self.baselines_on = True self.algs_on = True self.optimal_on = False self.majority_on = False self.num_checkpoints = 200 # use fractions instead of absolute numbers #mod.warm_start_multipliers = [pow(2,i) for i in range(4)] self.warm_start_multipliers = [pow(2,i) for i in range(4)] self.choices_cb_type = ['mtr'] #mod.choices_choices_lambda = [2,4,8] self.choices_choices_lambda = [2,8,16] #mod.choices_corrupt_type_supervised = [1,2,3] #mod.choices_corrupt_prob_supervised = [0.0,0.5,1.0] self.choices_corrupt_type_supervised = [1] self.choices_corrupt_prob_supervised = [0.0] self.learning_rates_template = [0.1, 0.03, 0.3, 0.01, 1.0, 0.003, 3.0, 0.001, 10.0] self.adf_on = True self.choices_corrupt_type_bandit = [1,2,3] self.choices_corrupt_prob_bandit = [0.0,0.5,1.0] self.validation_method = 1 self.weighting_scheme = 2 #self.epsilon = 0.05 #self.epsilon_on = True self.critical_size_ratios = [184 * pow(2, -i) for i in range(7) ] def collect_stats(mod): avg_error_value = avg_error(mod) actual_var_value = actual_var(mod) ideal_var_value = ideal_var(mod) vw_run_results = [] vw_result_template = { 'bandit_size': 0, 'bandit_supervised_size_ratio': 0, 'avg_error': 0.0, 'actual_variance': 0.0, 'ideal_variance': 0.0 } if 'majority_approx' in mod.param or 'optimal_approx' in mod.param: vw_result = vw_result_template.copy() if 'optimal_approx' in mod.param: # this condition is for computing the optimal error vw_result['avg_error'] = avg_error_value else: # this condition is for computing the majority error err = 1 - float(mod.param['majority_size']) / mod.param['total_size'] vw_result['avg_error'] = float('%0.5f' % err) vw_run_results.append(vw_result) return vw_run_results f = open(mod.vw_output_filename, 'r') i = 0 for line in f: vw_progress_pattern = '\d+\.\d+\s+\d+\.\d+\s+\d+\s+\d+\.\d+\s+[a-zA-Z0-9]+\s+[a-zA-Z0-9]+\s+\d+.*' matchobj = re.match(vw_progress_pattern, line) if matchobj: s = line.split() if len(s) >= 8: s = s[:7] avg_loss_str, last_loss_str, counter_str, weight_str, curr_label_str, \ curr_pred_str, curr_feat_str = s avg_loss = float(avg_loss_str) bandit_effective = int(float(weight_str)) for ratio in mod.critical_size_ratios: if bandit_effective >= (1 - 1e-7) * mod.param['warm_start'] * ratio and \ bandit_effective <= (1 + 1e-7) * mod.param['warm_start'] * ratio: vw_result = vw_result_template.copy() vw_result['bandit_size'] = bandit_effective vw_result['bandit_supervised_size_ratio'] = ratio vw_result['avg_error'] = avg_loss vw_result['actual_variance'] = actual_var_value vw_result['ideal_variance'] = ideal_var_value vw_run_results.append(vw_result) f.close() return vw_run_results def gen_vw_options_list(mod): mod.vw_options = format_setting(mod.vw_template, mod.param) vw_options_list = [] for k, v in mod.vw_options.iteritems(): vw_options_list.append('--'+str(k)) vw_options_list.append(str(v)) return vw_options_list def gen_vw_options(mod): if 'optimal_approx' in mod.param: # Fully supervised on full dataset mod.vw_template = {'data':'', 'progress':2.0, 'passes':0, 'oaa':0, 'cache_file':''} mod.param['passes'] = 5 mod.param['oaa'] = mod.param['num_classes'] mod.param['cache_file'] = mod.param['data'] + '.cache' elif 'majority_approx' in mod.param: # Compute majority error; basically we would like to skip vw running as fast as possible mod.vw_template = {'data':'', 'progress':2.0, 'cbify':0, 'warm_start':0, 'bandit':0} mod.param['cbify'] = mod.param['num_classes'] mod.param['warm_start'] = 0 mod.param['bandit'] = 0 else: # General CB mod.vw_template = {'data':'', 'progress':2.0, 'corrupt_type_bandit':0, 'corrupt_prob_bandit':0.0, 'bandit':0, 'cb_type':'mtr', 'choices_lambda':0, 'corrupt_type_supervised':0, 'corrupt_prob_supervised':0.0, 'lambda_scheme':1, 'learning_rate':0.5, 'warm_start_type':1, 'cbify':0, 'warm_start':0, 'overwrite_label':1, 'validation_method':1, 'weighting_scheme':1} mod.param['warm_start'] = mod.param['warm_start_multiplier'] * mod.param['progress'] mod.param['bandit'] = mod.param['total_size'] - mod.param['warm_start'] mod.param['cbify'] = mod.param['num_classes'] mod.param['overwrite_label'] = mod.param['majority_class'] if mod.param['adf_on'] is True: mod.param['cb_explore_adf'] = ' ' mod.vw_template['cb_explore_adf'] = ' ' else: mod.param['cb_explore'] = mod.param['num_classes'] mod.vw_template['cb_explore'] = 0 if mod.param['no_warm_start_update'] is True: mod.param['no_supervised'] = ' ' mod.vw_template['no_supervised'] = ' ' if mod.param['no_interaction_update'] is True: mod.param['no_bandit'] = ' ' mod.vw_template['no_bandit'] = ' ' def execute_vw(mod): gen_vw_options(mod) vw_options_list = gen_vw_options_list(mod) cmd = intersperse([mod.vw_path]+vw_options_list, ' ') print cmd f = open(mod.vw_output_filename, 'w') process = subprocess.Popen(cmd, shell=True, stdout=f, stderr=f) #subprocess.check_call(cmd, shell=True) process.wait() f.close() def intersperse(l, ch): s = '' for item in l: s += str(item) s += ch return s def param_to_str(param): param_list = [ str(k)+'='+str(v) for k,v in param.iteritems() ] return intersperse(param_list, ',') def replace_if_in(dic, k, k_new): if k in dic: dic[k_new] = dic[k] del dic[k] def replace_keys(dic, simplified_keymap): dic_new = dic.copy() for k, k_new in simplified_keymap.iteritems(): replace_if_in(dic_new, k, k_new) return dic_new def param_to_str_simplified(mod): #print 'before replace' #print param vw_run_param_set = ['lambda_scheme','learning_rate','validation_method', 'fold','no_warm_start_update','no_interaction_update', 'corrupt_prob_bandit', 'corrupt_prob_supervised', 'corrupt_type_bandit', 'corrupt_type_supervised', 'warm_start_type','warm_start_multiplier','choices_lambda','weighting_scheme', 'cb_type','optimal_approx','majority_approx','dataset', 'adf_on'] mod.template_red = dict([(k,mod.result_template[k]) for k in vw_run_param_set]) mod.simplified_keymap_red = dict([(k,mod.simplified_keymap[k]) for k in vw_run_param_set]) # step 1: use the above as a template to filter out irrelevant parameters # in the vw output file title param_formatted = format_setting(mod.template_red, mod.param) # step 2: replace the key names with the simplified names param_simplified = replace_keys(param_formatted, mod.simplified_keymap_red) #print 'after replace' #print param return param_to_str(param_simplified) def gen_comparison_graph(mod): mod.param['data'] = mod.ds_path + str(mod.param['fold']) + '/' + mod.param['dataset'] mod.param['total_size'] = get_num_lines(mod.param['data']) mod.param['num_classes'] = get_num_classes(mod.param['data']) mod.param['majority_size'], mod.param['majority_class'] = get_majority_class(mod.param['data']) mod.param['progress'] = int(math.ceil(float(mod.param['total_size']) / float(mod.num_checkpoints))) mod.vw_output_dir = mod.results_path + remove_suffix(mod.param['data']) + '/' mod.vw_output_filename = mod.vw_output_dir + param_to_str_simplified(mod) + '.txt' #plot_errors(mod) #print mod.param['validation_method'] execute_vw(mod) vw_run_results = collect_stats(mod) for vw_result in vw_run_results: result_combined = merge_two_dicts(mod.param, vw_result) #print mod.result_template['no_interaction_update'] #print result_combined['no_interaction_update'] result_formatted = format_setting(mod.result_template, result_combined) record_result(mod, result_formatted) print('') # The following function is a "template filling" function # Given a template, we use the setting dict to fill it as much as possible def format_setting(template, setting): formatted = template.copy() for k, v in setting.iteritems(): if k in template.keys(): formatted[k] = v return formatted def record_result(mod, result): result_row = [] for k in mod.result_header_list: result_row.append(result[k]) #print result['validation_method'] #print result_row summary_file = open(mod.summary_file_name, 'a') summary_file.write( intersperse(result_row, '\t') + '\n') summary_file.close() def ds_files(ds_path): prevdir = os.getcwd() os.chdir(ds_path) dss = sorted(glob.glob('*.vw.gz')) #dss = [ds_path+ds for ds in dss] os.chdir(prevdir) return dss def merge_two_dicts(x, y): #print 'x = ', x #print 'y = ', y z = x.copy() # start with x's keys and values z.update(y) # modifies z with y's keys and values & returns None return z def param_cartesian(param_set_1, param_set_2): prod = [] for param_1 in param_set_1: for param_2 in param_set_2: prod.append(merge_two_dicts(param_1, param_2)) return prod def param_cartesian_multi(param_sets): #print param_sets prod = [{}] for param_set in param_sets: prod = param_cartesian(prod, param_set) return prod def dictify(param_name, param_choices): result = [] for param in param_choices: dic = {} dic[param_name] = param result.append(dic) print param_name, len(result) return result def params_per_task(mod): # Problem parameters params_corrupt_type_sup = dictify('corrupt_type_supervised', mod.choices_corrupt_type_supervised) params_corrupt_prob_sup = dictify('corrupt_prob_supervised', mod.choices_corrupt_prob_supervised) params_corrupt_type_band = dictify('corrupt_type_bandit', mod.choices_corrupt_type_bandit) params_corrupt_prob_band = dictify('corrupt_prob_bandit', mod.choices_corrupt_prob_bandit) params_warm_start_multiplier = dictify('warm_start_multiplier', mod.warm_start_multipliers) params_learning_rate = dictify('learning_rate', mod.learning_rates) # could potentially induce a bug if the maj and best does not have this parameter params_fold = dictify('fold', mod.folds) # Algorithm parameters params_cb_type = dictify('cb_type', mod.choices_cb_type) # Common parameters params_common = param_cartesian_multi([params_corrupt_type_sup, params_corrupt_prob_sup, params_corrupt_type_band, params_corrupt_prob_band, params_warm_start_multiplier, params_learning_rate, params_cb_type, params_fold]) params_common = filter(lambda param: param['corrupt_type_bandit'] == 3 or abs(param['corrupt_prob_bandit']) > 1e-4, params_common) # Baseline parameters construction if mod.baselines_on: params_baseline_basic = [ [{'choices_lambda': 1, 'warm_start_type': 1, 'lambda_scheme': 3}], [{'no_warm_start_update': True, 'no_interaction_update': False}, {'no_warm_start_update': False, 'no_interaction_update': True}] ] params_baseline = param_cartesian_multi([params_common] + params_baseline_basic) #params_baseline = filter(lambda param: param['no_warm_start_update'] == True or param['no_interaction_update'] == True, params_baseline) else: params_baseline = [] # Algorithm parameters construction if mod.algs_on: params_choices_lambd = dictify('choices_lambda', mod.choices_choices_lambda) params_algs_1 = param_cartesian_multi([params_choices_lambd, [{'no_warm_start_update': False, 'no_interaction_update': False, 'warm_start_type': 1, 'lambda_scheme': 3}], [{'validation_method':2}, {'validation_method':3}]] ) params_algs_2 = [{'no_warm_start_update': False, 'no_interaction_update': False, 'warm_start_type': 2, 'lambda_scheme': 1, 'choices_lambda':1}] params_algs = param_cartesian( params_common, params_algs_1 + params_algs_2 ) else: params_algs = [] params_constant_baseline = [{'weighting_scheme':1, 'adf_on':True}] params_constant_algs = [{'weighting_scheme':mod.weighting_scheme, 'adf_on':True}] params_baseline_and_algs = param_cartesian_multi([params_constant_baseline, params_baseline]) + param_cartesian_multi([params_constant_algs, params_algs]) #for p in params_common: # print p #for p in params_baseline: # print p print len(params_common) print len(params_baseline) print len(params_algs) print len(params_baseline_and_algs) # Optimal baselines parameter construction if mod.optimal_on: params_optimal = [{ 'optimal_approx': True, 'fold': 1, 'corrupt_type_supervised':1, 'corrupt_prob_supervised':0.0, 'corrupt_type_bandit':1, 'corrupt_prob_bandit':0.0} ] else: params_optimal = [] if mod.majority_on: params_majority = [{ 'majority_approx': True, 'fold': 1, 'corrupt_type_supervised':1, 'corrupt_prob_supervised':0.0, 'corrupt_type_bandit':1, 'corrupt_prob_bandit':0.0} ] else: params_majority = [] #print len(params_baseline) #print len(params_algs) #print len(params_common) #raw_input('..') # Common factor in all 3 groups: dataset params_dataset = dictify('dataset', mod.dss) params_all = param_cartesian_multi( [params_dataset, params_baseline_and_algs + params_optimal + params_majority] ) params_all = sorted(params_all, key=lambda d: (d['dataset'], d['corrupt_type_supervised'], d['corrupt_prob_supervised'], d['corrupt_type_bandit'], d['corrupt_prob_bandit'])) print 'The total number of VW commands to run is: ', len(params_all) #for row in params_all: # print row return get_params_task(params_all) def get_params_task(params_all): params_task = [] for i in range(len(params_all)): if (i % mod.num_tasks == mod.task_id): params_task.append(params_all[i]) return params_task def get_num_lines(dataset_name): num_lines = subprocess.check_output(('zcat ' + dataset_name + ' | wc -l'), shell=True) return int(num_lines) def get_num_classes(ds): # could be a bug for including the prefix.. did, n_actions = os.path.basename(ds).split('.')[0].split('_')[1:] did, n_actions = int(did), int(n_actions) return n_actions def get_majority_class(dataset_name): maj_class_str = subprocess.check_output(('zcat '+ dataset_name +' | cut -d \' \' -f 1 | sort | uniq -c | sort -r -n | head -1 | xargs '), shell=True) maj_size, maj_class = maj_class_str.split() return int(maj_size), int(maj_class) def avg_error(mod): return vw_output_extract(mod, 'average loss') def actual_var(mod): return vw_output_extract(mod, 'Measured average variance') def ideal_var(mod): return vw_output_extract(mod, 'Ideal average variance') def vw_output_extract(mod, pattern): #print mod.vw_output_filename vw_output = open(mod.vw_output_filename, 'r') vw_output_text = vw_output.read() #print vw_output_text #rgx_pattern = '^'+pattern+' = (.*)(|\sh)\n.*$' #print rgx_pattern rgx_pattern = '.*'+pattern+' = ([\d]*.[\d]*)( h|)\n.*' rgx = re.compile(rgx_pattern, flags=re.M) errs = rgx.findall(vw_output_text) if not errs: avge = 0 else: #print errs avge = float(errs[0][0]) vw_output.close() return avge def write_summary_header(mod): summary_file = open(mod.summary_file_name, 'w') summary_header = intersperse(mod.result_header_list, '\t') summary_file.write(summary_header+'\n') summary_file.close() def main_loop(mod): mod.summary_file_name = mod.results_path+str(mod.task_id)+'of'+str(mod.num_tasks)+'.sum' # The reason for using a list is that, we would like to keep the order of the #columns in this way. Maybe use ordered dictionary in the future? mod.result_template_list = [ ('fold', 'fd', 0), ('data', 'dt', ''), ('dataset', 'ds', ''), ('num_classes','nc', 0), ('total_size', 'ts', 0), ('majority_size','ms', 0), ('corrupt_type_supervised', 'cts', 0), ('corrupt_prob_supervised', 'cps', 0.0), ('corrupt_type_bandit', 'ctb', 0), ('corrupt_prob_bandit', 'cpb', 0.0), ('adf_on', 'ao', True), ('warm_start_multiplier','wsm',1), ('warm_start', 'ws', 0), ('warm_start_type', 'wst', 0), ('bandit_size', 'bs', 0), ('bandit_supervised_size_ratio', 'bssr', 0), ('cb_type', 'cbt', 'mtr'), ('validation_method', 'vm', 0), ('weighting_scheme', 'wts', 0), ('lambda_scheme','ls', 0), ('choices_lambda', 'cl', 0), ('no_warm_start_update', 'nwsu', False), ('no_interaction_update', 'niu', False), ('learning_rate', 'lr', 0.0), ('optimal_approx', 'oa', False), ('majority_approx', 'ma', False), ('avg_error', 'ae', 0.0), ('actual_variance', 'av', 0.0), ('ideal_variance', 'iv', 0.0)] num_cols = len(mod.result_template_list) mod.result_header_list = [ mod.result_template_list[i][0] for i in range(num_cols) ] mod.result_template = dict([ (mod.result_template_list[i][0], mod.result_template_list[i][2]) for i in range(num_cols) ]) mod.simplified_keymap = dict([ (mod.result_template_list[i][0], mod.result_template_list[i][1]) for i in range(num_cols) ]) write_summary_header(mod) for mod.param in mod.config_task: #if (mod.param['no_interaction_update'] is True): # raw_input(' ') gen_comparison_graph(mod) def create_dir(dir): if not os.path.exists(dir): os.makedirs(dir) import stat os.chmod(dir, os.stat(dir).st_mode | stat.S_IWOTH) def remove_suffix(filename): return os.path.basename(filename).split('.')[0] if __name__ == '__main__': parser = argparse.ArgumentParser(description='vw job') parser.add_argument('task_id', type=int, help='task ID, between 0 and num_tasks - 1') parser.add_argument('num_tasks', type=int) parser.add_argument('--results_dir', default='../../../figs/') parser.add_argument('--ds_dir', default='../../../vwshuffled/') parser.add_argument('--num_learning_rates', type=int, default=1) parser.add_argument('--num_datasets', type=int, default=-1) parser.add_argument('--num_folds', type=int, default=1) args = parser.parse_args() flag_dir = args.results_dir + 'flag/' mod = model() mod.num_tasks = args.num_tasks mod.task_id = args.task_id mod.vw_path = '../vowpalwabbit/vw' mod.ds_path = args.ds_dir mod.results_path = args.results_dir print 'reading dataset files..' #TODO: this line specifically for multiple folds #Need a systematic way to detect subfolder names mod.dss = ds_files(mod.ds_path + '1/') print len(mod.dss) if args.num_datasets == -1 or args.num_datasets > len(mod.dss): pass else: mod.dss = mod.dss[:args.num_datasets] #print mod.dss if args.task_id == 0: #process = subprocess.Popen('make -C .. clean; make -C ..', shell=True, stdout=f, stderr=f) #subprocess.check_call(cmd, shell=True) #process.wait() # To avoid race condition of writing to the same file at the same time create_dir(args.results_dir) # This is specifically designed for teamscratch, as accessing a folder # with a huge number of result files can be super slow. Hence, we create a # subfolder for each dataset to alleviate this. for ds in mod.dss: ds_no_suffix = remove_suffix(ds) create_dir(args.results_dir + ds_no_suffix + '/') create_dir(flag_dir) else: # may still have the potential of race condition on those subfolders (if # we have a lot of datasets to run and the datasets are small) while not os.path.exists(flag_dir): time.sleep(1) if args.num_learning_rates <= 0 or args.num_learning_rates >= 10: mod.learning_rates = mod.learning_rates_template else: mod.learning_rates = mod.learning_rates_template[:args.num_learning_rates] #mod.folds = range(1,11) mod.folds = range(1, args.num_folds+1) #mod.dss = ["ds_223_63.vw.gz"] #mod.dss = mod.dss[:5] print 'generating tasks..' # here, we are generating the task specific parameter settings # by first generate all parameter setting and pick every num_tasks of them mod.config_task = params_per_task(mod) print 'task ' + str(mod.task_id) + ' of ' + str(mod.num_tasks) + ':' print len(mod.config_task) #print mod.ds_task # we only need to vary the warm start fraction, and there is no need to vary the bandit fraction, # as each run of vw automatically accumulates the bandit dataset main_loop(mod) <file_sep>/scripts/alg_comparison.py import matplotlib matplotlib.use('Agg') import matplotlib.pyplot as plt import pylab import os import glob import pandas as pd import scipy.stats as stats from itertools import compress from math import sqrt import argparse import numpy as np import seaborn as sns from matplotlib.colors import ListedColormap from matplotlib.font_manager import FontProperties class model: def __init__(self): pass def sum_files(result_path): prevdir = os.getcwd() os.chdir(result_path) dss = sorted(glob.glob('*.sum')) os.chdir(prevdir) return dss def parse_sum_file(sum_filename): f = open(sum_filename, 'r') #f.seek(0, 0) table = pd.read_table(f, sep='\s+',lineterminator='\n') return table def get_z_scores(errors_1, errors_2, sizes): z_scores = [] for i in range(len(errors_1)): #print i z_scores.append( z_score(errors_1[i], errors_2[i], sizes[i]) ) return z_scores def z_score(err_1, err_2, size): if (abs(err_1) < 1e-6 or abs(err_1) > 1-1e-6) and (abs(err_2) < 1e-6 or abs(err_2) > 1-1e-6): return 0 #print err_1, err_2, size, sqrt( (err_1*(1 - err_1) + err_2*(1-err_2)) / size ) z = (err_1 - err_2) / sqrt( (err_1*(1 - err_1) + err_2*(1-err_2)) / size ) return z #print z def is_significant(z): if (stats.norm.cdf(z) < 0.05) or (stats.norm.cdf(z) > 0.95): return True else: return False def plot_comparison(errors_1, errors_2, sizes): #print title plt.plot([0,1],[0,1]) z_scores = get_z_scores(errors_1, errors_2, sizes) sorted_z_scores = sorted(enumerate(z_scores), key=lambda x:x[1]) #for s in sorted_z_scores: # print s, is_significant(s[1]) significance = map(is_significant, z_scores) results_signi_1 = list(compress(errors_1, significance)) results_signi_2 = list(compress(errors_2, significance)) plt.scatter(results_signi_1, results_signi_2, s=18, c='r') insignificance = [not b for b in significance] results_insigni_1 = list(compress(errors_1, insignificance)) results_insigni_2 = list(compress(errors_2, insignificance)) plt.scatter(results_insigni_1, results_insigni_2, s=2, c='k') len_errors = len(errors_1) wins_1 = [z_scores[i] < 0 and significance[i] for i in range(len_errors) ] wins_2 = [z_scores[i] > 0 and significance[i] for i in range(len_errors) ] num_wins_1 = wins_1.count(True) num_wins_2 = wins_2.count(True) return num_wins_1, num_wins_2 def alg_info(alg_name, result_lst): if (alg_name[0] == 0): return result_lst[0] if (alg_name[0] == 2): return result_lst[1] if (alg_name[2] == True and alg_name[3] == True): return result_lst[2] if (alg_name[2] == True and alg_name[3] == False): return result_lst[3] if (alg_name[2] == False and alg_name[3] == True): return result_lst[4] if (alg_name[2] == False and alg_name[3] == False and alg_name[1] == 2 and alg_name[4] == 2): return result_lst[5] if (alg_name[2] == False and alg_name[3] == False and alg_name[1] == 4 and alg_name[4] == 2): return result_lst[6] if (alg_name[2] == False and alg_name[3] == False and alg_name[1] == 8 and alg_name[4] == 2): return result_lst[7] if (alg_name[2] == False and alg_name[3] == False and alg_name[1] == 16 and alg_name[4] == 2): return result_lst[8] if (alg_name[2] == False and alg_name[3] == False and alg_name[1] == 2 and alg_name[4] == 3): return result_lst[9] if (alg_name[2] == False and alg_name[3] == False and alg_name[1] == 4 and alg_name[4] == 3): return result_lst[10] if (alg_name[2] == False and alg_name[3] == False and alg_name[1] == 8 and alg_name[4] == 3): return result_lst[11] if (alg_name[2] == False and alg_name[3] == False and alg_name[1] == 16 and alg_name[4] == 3): return result_lst[12] return result_lst[13] def alg_str(alg_name): return alg_info(alg_name, ['Most-Freq', 'Sim-Bandit', 'Class-1', 'Bandit-Only', 'Sup-Only', 'MinimaxBandits, one validation', 'AwesomeBandits with $|\Lambda|$=4, one validation', 'AwesomeBandits with $|\Lambda|$=8, one validation', 'AwesomeBandits with $|\Lambda|$=16, one validation', 'MinimaxBandits, multiple validation', 'AwesomeBandits with $|\Lambda|$=4, multiple validation', 'AwesomeBandits with $|\Lambda|$=8, multiple validation', 'AwesomeBandits with $|\Lambda|$=16, multiple validation', 'unknown']) def alg_str_compatible(alg_name): return alg_info(alg_name, ['Most-Freq', 'Sim-Bandit', 'Class-1', 'Bandit-Only', 'Sup-Only', 'Choices_lambda=2, validation_method=2', 'Choices_lambda=4, validation_method=2', 'Choices_lambda=8, validation_method=2', 'Choices_lambda=16, validation_method=2', 'Choices_lambda=2, validation_method=3', 'Choices_lambda=4, validation_method=3', 'Choices_lambda=8, validation_method=3', 'Choices_lambda=16, validation_method=3', 'unknown']) def alg_color_style(alg_name): palette = sns.color_palette('colorblind') colors = palette.as_hex() #colors = [colors[5], colors[4], 'black', colors[2], colors[1], colors[3], 'black', colors[0], 'black', 'black'] colors = [ colors[5], colors[3], 'black', colors[0], colors[1], colors[2], colors[2], colors[2], colors[2], colors[4], colors[4], colors[4], colors[4], 'black' ] styles = [ 'solid', 'solid', 'solid', 'solid', 'dashed', 'dotted', 'dashdot', 'solid', 'dashed', 'dotted', 'dashdot', 'solid', 'dashed', 'solid'] return alg_info(alg_name, zip(colors, styles)) #['black', 'magenta', 'lime', 'green', 'blue', 'darkorange','darksalmon', 'red', 'cyan'] def alg_index(alg_name): return alg_info(alg_name, [7.0, 6.0, 8.0, 5.0, 4.0, 2.0, 1.0, 1.2, 1.5, 3.0, 2.0, 2.2, 2.5, 9.0]) def order_legends(indices): ax = plt.gca() handles, labels = ax.get_legend_handles_labels() # sort both labels and handles by labels labels, handles, indices = zip(*sorted(zip(labels, handles, indices), key=lambda t: t[2])) ax.legend(handles, labels) def save_legend(mod, indices): ax = plt.gca() handles, labels = ax.get_legend_handles_labels() labels, handles, indices = zip(*sorted(zip(labels, handles, indices), key=lambda t: t[2])) #figlegend = pylab.figure(figsize=(26,1)) #figlegend.legend(handles, labels, 'center', fontsize=26, ncol=8) figlegend = pylab.figure(figsize=(17,1.5)) figlegend.legend(handles, labels, 'center', fontsize=26, ncol=3) figlegend.tight_layout(pad=0) figlegend.savefig(mod.problemdir+'legend.pdf') def problem_str(name_problem): return 'sct='+str(name_problem[0]) \ +'_scp='+str(name_problem[1]) \ +'_bct='+str(name_problem[2]) \ +'_bcp='+str(name_problem[3]) \ +'_ratio='+str(name_problem[4]) def noise_type_str(noise_type): if noise_type == 1: return 'UAR' elif noise_type == 2: return 'CYC' elif noise_type == 3: return 'MAJ' def problem_text(name_problem): s='' s += 'Ratio = ' + str(name_problem[2]) + ', ' if abs(name_problem[1]) < 1e-6: s += 'noiseless' else: s += noise_type_str(name_problem[0]) + ', ' s += 'p = ' + str(name_problem[1]) return s def plot_cdf(alg_name, errs): print alg_name print errs print len(errs) col, sty = alg_color_style(alg_name) plt.step(np.sort(errs), np.linspace(0, 1, len(errs), endpoint=False), label=alg_str(alg_name), color=col, linestyle=sty, linewidth=2.0) # #raw_input("Press Enter to continue...") def plot_all_cdfs(alg_results, mod): #plot all cdfs: print 'printing cdfs..' indices = [] pylab.figure(figsize=(8,6)) for alg_name, errs in alg_results.iteritems(): indices.append(alg_index(alg_name)) plot_cdf(alg_name, errs) if mod.normalize_type == 1: plt.xlim(0,1) elif mod.normalize_type == 2: plt.xlim(-1,1) elif mod.normalize_type == 3: plt.xlim(0, 1) plt.ylim(0,1) #params={'legend.fontsize':26, #'axes.labelsize': 24, 'axes.titlesize':26, 'xtick.labelsize':20, #'ytick.labelsize':20 } #plt.rcParams.update(params) #plt.xlabel('Normalized error',fontsize=34) #plt.ylabel('Cumulative frequency', fontsize=34) #plt.title(problem_text(mod.name_problem), fontsize=36) plt.xticks(fontsize=30) plt.yticks(fontsize=30) plt.tight_layout(pad=0) ax = plt.gca() order_legends(indices) ax.legend_.set_zorder(-1) plt.savefig(mod.problemdir+'cdf.pdf') ax.legend_.remove() plt.savefig(mod.problemdir+'cdf_nolegend.pdf') save_legend(mod, indices) plt.clf() def plot_all_pair_comp(alg_results, sizes, mod): alg_names = alg_results.keys() for i in range(len(alg_names)): for j in range(len(alg_names)): if i < j: errs_1 = alg_results[alg_names[i]] errs_2 = alg_results[alg_names[j]] print len(errs_1), len(errs_2), len(sizes) #raw_input('Press any key to continue..') num_wins_1, num_wins_2 = plot_comparison(errs_1, errs_2, sizes) plt.title( 'total number of comparisons = ' + str(len(errs_1)) + '\n'+ alg_str(alg_names[i]) + ' wins ' + str(num_wins_1) + ' times, \n' + alg_str(alg_names[j]) + ' wins ' + str(num_wins_2) + ' times') plt.savefig(mod.problemdir+alg_str_compatible(alg_names[i])+'_vs_'+alg_str_compatible(alg_names[j])+'.pdf') plt.clf() #def init_results(result_table): # alg_results = {} # for idx, row in result_table.iterrows(): # alg_name = (row['warm_start_type'], row['choices_lambda'], row['no_warm_start_update'], row['no_interaction_update']) # alg_results[alg_name] = [] # alg_results[(0, 0, False, False)] = [] # return alg_results def normalize_score(unnormalized_result, mod): if mod.normalize_type == 1: l = get_best_error(mod.best_error_table, mod.name_dataset) u = max(unnormalized_result.values()) return { k : ((v - l) / (u - l + 1e-4)) for k, v in unnormalized_result.iteritems() } elif mod.normalize_type == 2: l = unnormalized_result[(1, 1, True, False)] return { k : ((v - l) / (l + 1e-4)) for k, v in unnormalized_result.iteritems() } elif mod.normalize_type == 3: return unnormalized_result def get_best_error(best_error_table, name_dataset): name = name_dataset[0] best_error_oneline = best_error_table[best_error_table['dataset'] == name] best_error = best_error_oneline.loc[best_error_oneline.index[0], 'avg_error'] #print name #raw_input("...") #print best_error_oneline #raw_input("...") #print best_error #raw_input("...") return best_error def get_maj_error(maj_error_table, name_dataset): name = name_dataset[0] maj_error_oneline = maj_error_table[maj_error_table['data'] == name] maj_error = maj_error_oneline.loc[maj_error_oneline.index[0], 'avg_error'] return maj_error #normalized_results[alg_name].append(normalized_errs[i]) #errs = [] #for idx, row in result_table.iterrows(): # errs.append(row['avg_error']) def get_unnormalized_results(result_table): new_unnormalized_results = {} new_size = 0 i = 0 for idx, row in result_table.iterrows(): if i == 0: new_size = row['bandit_size'] if row['bandit_size'] == new_size: alg_name = (row['warm_start_type'], row['choices_lambda'], row['no_warm_start_update'], row['no_interaction_update'], row['validation_method']) new_unnormalized_results[alg_name] = row['avg_error'] i += 1 return new_size, new_unnormalized_results def update_result_dict(results_dict, new_result): for k, v in new_result.iteritems(): results_dict[k].append(v) def plot_all(mod, all_results): #all_results = all_results[all_results['corrupt_prob_supervised']!=0.0] grouped_by_problem = all_results.groupby(['corrupt_type_supervised', 'corrupt_prob_supervised', 'corrupt_type_bandit', 'corrupt_prob_bandit', 'bandit_supervised_size_ratio']) #then group by dataset and warm_start size (corresponding to each point in cdf) for name_problem, group_problem in grouped_by_problem: normalized_results = None unnormalized_results = None sizes = None mod.name_problem = name_problem grouped_by_dataset = group_problem.groupby(['dataset','warm_start']) #then select unique combinations of (no_supervised, no_bandit, choices_lambda) #e.g. (True, True, 1), (True, False, 1), (False, True, 1), (False, False, 2) #(False, False, 8), and compute a normalized score for name_dataset, group_dataset in grouped_by_dataset: result_table = group_dataset grouped_by_algorithm = group_dataset.groupby(['warm_start_type', 'choices_lambda', 'no_warm_start_update', 'no_interaction_update', 'validation_method']) mod.name_dataset = name_dataset #The 'learning_rate' would be the only free degree here now. Taking the #min aggregation will give us the algorithms we are evaluating. #In the future this should be changed if we run multiple folds: we #should average among folds before choosing the min result_table = grouped_by_algorithm.min() result_table = result_table.reset_index() #print result_table #group_dataset.groupby(['choices_lambda','no_supervised', 'no_bandit']) #print alg_results #dummy = input('') #in general (including the first time) - record the error rates of all algorithms #print result_table new_size, new_unnormalized_result = get_unnormalized_results(result_table) new_unnormalized_result[(0, 0, False, False, 1)] = get_maj_error(mod.maj_error_table, mod.name_dataset) new_normalized_result = normalize_score(new_unnormalized_result, mod) #first time - generate names of algorithms considered if normalized_results is None: sizes = [] unnormalized_results = dict([(k,[]) for k in new_unnormalized_result.keys()]) normalized_results = dict([(k,[]) for k in new_unnormalized_result.keys()]) update_result_dict(unnormalized_results, new_unnormalized_result) update_result_dict(normalized_results, new_normalized_result) sizes.append(new_size) #print 'sizes:' #print len(sizes) #for k, v in unnormalized_results.iteritems(): # print len(v) mod.problemdir = mod.fulldir+problem_str(mod.name_problem)+'/' if not os.path.exists(mod.problemdir): os.makedirs(mod.problemdir) print 'best_errors', mod.best_error_table print 'unnormalized_results', unnormalized_results print 'normalized_results', normalized_results if mod.pair_comp_on is True: plot_all_pair_comp(unnormalized_results, sizes, mod) if mod.cdf_on is True: plot_all_cdfs(normalized_results, mod) def save_to_hdf(mod): print 'saving to hdf..' store = pd.HDFStore('store.h5') store['result_table'] = mod.all_results store.close() def load_from_hdf(mod): print 'reading from hdf..' store = pd.HDFStore('store.h5') mod.all_results = store['result_table'] store.close() def load_from_sum(mod): print 'reading directory..' dss = sum_files(mod.results_dir) print len(dss) #print dss[168] all_results = None print 'reading sum tables..' for i in range(len(dss)): print 'result file name: ', dss[i] result = parse_sum_file(mod.results_dir + dss[i]) if (i == 0): all_results = result else: all_results = all_results.append(result) print all_results mod.all_results = all_results # This is a hack - need to do this systematically in the future #def load_maj_error(mod): # return parse_sum_file(mod.maj_error_dir) if __name__ == '__main__': parser = argparse.ArgumentParser(description='result summary') parser.add_argument('--results_dir', default='../../../figs/') parser.add_argument('--filter', default='1') parser.add_argument('--plot_subdir', default='expt1/') parser.add_argument('--from_hdf', action='store_true') parser.add_argument('--normalize_type', type=int, default=1) args = parser.parse_args() mod = model() mod.results_dir = args.results_dir mod.filter = args.filter mod.plot_subdir = args.plot_subdir mod.normalize_type = args.normalize_type #1: normalized score; 2: bandit only centered score; 3: raw score mod.pair_comp_on = False mod.cdf_on = True mod.maj_error_dir = '../../../figs_all/expt_0509/figs_maj_errors/0of1.sum' mod.best_error_dir = '../../../figs_all/expt_0606/best_errors/0of1.sum' mod.fulldir = mod.results_dir + mod.plot_subdir if not os.path.exists(mod.fulldir): os.makedirs(mod.fulldir) #print args.from_hdf #raw_input(' ') if args.from_hdf is True: load_from_hdf(mod) else: load_from_sum(mod) save_to_hdf(mod) #first group by corruption mode, then corruption prob #then group by warm start - bandit ratio #these constitutes all the problem settings we are looking at (corresponding #to each cdf graph) all_results = mod.all_results #print mod.best_error_table[mod.best_error_table['dataset'] == 'ds_160_5.vw.gz'] #raw_input(' ') all_results = all_results[all_results['choices_lambda'] != 0] #ignore the no update row: all_results = all_results[(all_results['no_warm_start_update'] == False) | (all_results['no_interaction_update'] == False)] #ignore the choice_lambda = 4 row all_results = all_results[(all_results['choices_lambda'] != 4)] #filter choices_lambdas = 2,4,8? #if (alg_name[2] == False and alg_name[3] == False and alg_name[1] != 8): # pass #else: mod.maj_error_table = parse_sum_file(mod.maj_error_dir) mod.maj_error_table = mod.maj_error_table[mod.maj_error_table['majority_approx']] mod.best_error_table = parse_sum_file(mod.best_error_dir) mod.best_error_table = mod.best_error_table[mod.best_error_table['optimal_approx']] if mod.filter == '1': pass elif mod.filter == '2': #print all_results['warm_start_size'] >= 100 #raw_input(' ') all_results = all_results[all_results['warm_start_size'] >= 100] elif mod.filter == '3': all_results = all_results[all_results['num_classes'] >= 3] elif mod.filter == '4': all_results = all_results[all_results['num_classes'] <= 2] elif mod.filter == '5': all_results = all_results[all_results['total_size'] >= 10000] all_results = all_results[all_results['num_classes'] >= 3] elif mod.filter == '6': all_results = all_results[all_results['warm_start_size'] >= 100] all_results = all_results[all_results['learning_rate'] == 0.3] elif mod.filter == '7': all_results = all_results[all_results['warm_start_size'] >= 100] all_results = all_results[all_results['num_classes'] >= 3] plot_all(mod, all_results) #if i >= 331 and i <= 340: # print 'result:', result # print 'all_results:', all_results
88f3ecddc5b90b9de951632571a2f94ebae630e5
[ "Python", "C++" ]
3
C++
zcc1307/vowpal_wabbit
d372d9ac951cc116247b7178b11865acefc961a8
c8ab3cd3476d0b7062ff8a81ade0051b69b4db84
refs/heads/master
<repo_name>LucasD11/TopCoder<file_sep>/requirements.txt appnope==0.1.2 astroid==2.4.2 backcall==0.2.0 decorator==4.4.2 greenlet==1.0.0 ipython==7.20.0 ipython-genutils==0.2.0 isort==5.7.0 jedi==0.18.0 lazy-object-proxy==1.4.3 mccabe==0.6.1 msgpack==1.0.2 neovim==0.3.1 parso==0.8.1 pexpect==4.8.0 pickleshare==0.7.5 prompt-toolkit==3.0.14 ptyprocess==0.7.0 Pygments==2.7.4 pylint==2.6.0 pynvim==0.4.2 six==1.15.0 toml==0.10.2 traitlets==5.0.5 wcwidth==0.2.5 wrapt==1.12.1 <file_sep>/TCCC 2003 Semifinals 3/ZigZag.html <!DOCTYPE html> <html> <head> <meta charset="utf-8" /> <title>TopCoder TCCC 2003 Semifinals 3 - 300: ZigZag</title> <link type="image/x-icon" rel="shortcut icon" href="http://www.topcoder.com/i/favicon.ico"/> <style type="text/css"> /* font */ body { font-family: Helvetica, Arial, Verdana, sans-serif; font-size: 16px; line-height: 1.2em; } ul.constraints > li:before, ul.notes > li:before { font-family: monospace; font-weight: normal; } .heading { font-weight: bold; font-size: 175%; line-height: 1.2em; } .section .section-title { font-weight: bold; font-size: 125%; } ol.testcases > li:before { font-family: monospace; } type { font-weight: bold; font-family: monospace; } li.testcase .data { font-family: monospace; line-height: 1.5em; } /* layout */ .heading { margin-top: 0.1em; margin-bottom:0.1em; text-align: center; } .section .section-title { margin-top : 1em; margin-bottom: 1em; } .problem-intro, note, user-constraint { padding-left: 1.25em; } /* Lists */ ul.constraints, ul.notes, ul.variables, ul.problem-definition-lines { list-style-type: none; padding: 0px; } ul.constraints > li:before { content: "-"; position:relative; margin-left: 0px; /* optional, for multiline li element */ left: 0.625em; } ul.notes > li:before { content: "-"; position:relative; margin-left: 0px; /* optional, for multiline li element */ left: 0.625em; } /* Testcases */ li.testcase { line-height: 1.1em; padding-top: 0.625em; padding-bottom: 0.625em; overflow: auto; } li.testcase > .testcase-content > div { padding-bottom: 0.5em; padding-left: 1em; } li.testcase .testcase-comment { margin: 0; padding-left: 1em; } .testcase-comment p:first-child { margin-top: 0; } .testcase-comment p:last-child { margin-bottom: 0; } li.testcase .testcase-content { margin: 0.31em; } /* Data and variables */ .testcase-output { padding: 0.2em 1em 0.2em 0em; } .variables, .testcase-output { margin-left: 0.5em; display: table; margin-bottom: 0px; margin-top: 0px; } .variable { display: table-row; } .variable .name { padding: 0.2em 0em 0.2em 1em; font-weight: bold; display: table-cell; text-align: right; } .testcase-output .prefix { padding: 0.2em 0em 0.2em 1em; display: table-cell; } .testcase-output .prefix:after { content : ":"; padding-right: 0.5em; } .variable .name:after { font-weight: bold; content : ":"; padding-right: 0.5em; } .variable .value, .testcase-output .value { padding: 0.2em 1em 0.2em 0em; display: table-cell; } ol.testcases { padding: 0px; counter-reset: test_number -1; } ol.testcases > li { list-style:none; } ol.testcases > li:before { counter-increment:test_number; display: block; clear: both; content:counter(test_number) ")"; color: inherit; background: inherit; } /* Problem Definition */ .problem-definition, .problem-limits { padding-left: 1.25em; } .problem-definition-lines, .limit-lines { display: table; margin-top: 0px; margin-bottom: 0px; padding-left: 0px; } .definition-line, .limit-line { display: table-row; height: 1.5em; overflow: auto; } .limit-name:after { content: ":"; margin-right: 1em; } .definition-name, .definition-value, .limit-name, .limit-value { display: table-cell; } .definition-value { padding-left: 0.5em; } .definition-name:after { content: ":"; } #contest-division:before { content: "Div "; } #problem-score:before { content: "- Problem "; } #problem-name { display: block; } /* Tags, hidden default */ .tag { visibility: hidden; position: absolute; } body { /* font color */ color: #333333; /* background color */ background-color: white; } .section .section-title { /* title color */ color: black; } li.testcase .data { /* highlight color */ background: #eee; } </style> </head> <body> <h1 class="heading"> <span id='contest-name'>TCCC 2003 Semifinals 3</span> <span id='problem-score'>300</span> <span id='problem-name'>ZigZag</span> </h1> <hr /> <!-- Problem Statement --> <div class="section"> <h2 class="section-title">Problem Statement</h2> <div class="problem-intro"> <intro><p> A sequence of numbers is called a <i>zig-zag sequence</i> if the differences between successive numbers strictly alternate between positive and negative. The first difference (if one exists) may be either positive or negative. A sequence with fewer than two elements is trivially a zig-zag sequence. </p> <p> For example, 1,7,4,9,2,5 is a zig-zag sequence because the differences (6,-3,5,-7,3) are alternately positive and negative. In contrast, 1,4,7,2,5 and 1,7,4,5,5 are <i>not</i> zig-zag sequences, the first because its first two differences are positive and the second because its last difference is zero. </p> <p> Given a sequence of integers, <b>sequence</b>, return the length of the longest subsequence of <b>sequence</b> that is a zig-zag sequence. A subsequence is obtained by deleting some number of elements (possibly zero) from the original sequence, leaving the remaining elements in their original order. </p> </intro> </div> </div> <!-- Problem definition --> <div class="section" id="definition"> <h2 class="section-title">Definition</h2> <div class="problem-definition"> <ul class="problem-definition-lines"> <li class="definition-line" id='class-line'> <span class='definition-name'>Class</span> <span class='definition-value'>ZigZag</span> </li> <li class="definition-line" id='method-line'> <span class='definition-name'>Method</span> <span class='definition-value'>longestZigZag</span> </li> <li class="definition-line" id='parameters-line'> <span class='definition-name'>Parameters</span> <span class='definition-value'> tuple(integer) </span> </li> <li class="definition-line" id='returns-line'> <span class='definition-name'>Returns</span> <span class='definition-value'> integer </span> </li> <li class="definition-line" id='signature-line'> <span class='definition-name'>Method signature</span> <span class='definition-value'> def longestZigZag(self, sequence) </span> </li> </ul> <div class="problem-definition-public-tip">(be sure your method is public)</div> </div> </div> <!-- Limits --> <div class="section"> <h2 class="section-title">Limits</h2> <div class='problem-limits'> <ul class="limit-lines"> <li class='limit-line'> <span class='limit-name'>Time limit (s)</span> <span class='limit-value'>2.000</span> </li> <li class='limit-line'> <span class='limit-name'>Memory limit (MB)</span> <span class='limit-value'>64</span> </li> </ul> </div> </div> <!-- Constraints --> <div class="section"> <h2 class="section-title">Constraints</h2> <ul class="constraints"> <li><user-constraint><b>sequence</b> contains between 1 and 50 elements, inclusive.</user-constraint></li> <li><user-constraint>Each element of <b>sequence</b> is between 1 and 1000, inclusive.</user-constraint></li> </ul> </div> <!-- Test cases --> <div class="section"> <h2 class="section-title">Test cases</h2> <ol class="testcases" start='0'> <li class="testcase"> <div class="testcase-content"> <div class="testcase-input"> <div class='tag'>input</div> <ul class="variables"> <li class="variable data"> <span class="name data">sequence</span> <span class="value data"> { 1, 7, 4, 9, 2, 5 } </span> </li> </ul> </div> <div class="testcase-output"> <div class='tag'>output</div> <span class="prefix data">Returns</span> <span class="value data"> 6 </span> </div> <div class="testcase-annotation"> <div class='tag'>note</div> <div class="testcase-comment">The entire sequence is a zig-zag sequence.</div> </div> </div> </li> <li class="testcase"> <div class="testcase-content"> <div class="testcase-input"> <div class='tag'>input</div> <ul class="variables"> <li class="variable data"> <span class="name data">sequence</span> <span class="value data"> { 1, 17, 5, 10, 13, 15, 10, 5, 16, 8 } </span> </li> </ul> </div> <div class="testcase-output"> <div class='tag'>output</div> <span class="prefix data">Returns</span> <span class="value data"> 7 </span> </div> <div class="testcase-annotation"> <div class='tag'>note</div> <div class="testcase-comment">There are several subsequences that achieve this length. One is 1,17,10,13,10,16,8.</div> </div> </div> </li> <li class="testcase"> <div class="testcase-content"> <div class="testcase-input"> <div class='tag'>input</div> <ul class="variables"> <li class="variable data"> <span class="name data">sequence</span> <span class="value data"> { 44 } </span> </li> </ul> </div> <div class="testcase-output"> <div class='tag'>output</div> <span class="prefix data">Returns</span> <span class="value data"> 1 </span> </div> </div> </li> <li class="testcase"> <div class="testcase-content"> <div class="testcase-input"> <div class='tag'>input</div> <ul class="variables"> <li class="variable data"> <span class="name data">sequence</span> <span class="value data"> { 1, 2, 3, 4, 5, 6, 7, 8, 9 } </span> </li> </ul> </div> <div class="testcase-output"> <div class='tag'>output</div> <span class="prefix data">Returns</span> <span class="value data"> 2 </span> </div> </div> </li> <li class="testcase"> <div class="testcase-content"> <div class="testcase-input"> <div class='tag'>input</div> <ul class="variables"> <li class="variable data"> <span class="name data">sequence</span> <span class="value data"> { 70, 55, 13, 2, 99, 2, 80, 80, 80, 80, 100, 19, 7, 5, 5, 5, 1000, 32, 32 } </span> </li> </ul> </div> <div class="testcase-output"> <div class='tag'>output</div> <span class="prefix data">Returns</span> <span class="value data"> 8 </span> </div> </div> </li> <li class="testcase"> <div class="testcase-content"> <div class="testcase-input"> <div class='tag'>input</div> <ul class="variables"> <li class="variable data"> <span class="name data">sequence</span> <span class="value data"> { 374, 40, 854, 203, 203, 156, 362, 279, 812, 955, 600, 947, 978, 46, 100, 953, 670, 862, 568, 188, 67, 669, 810, 704, 52, 861, 49, 640, 370, 908, 477, 245, 413, 109, 659, 401, 483, 308, 609, 120, 249, 22, 176, 279, 23, 22, 617, 462, 459, 244 } </span> </li> </ul> </div> <div class="testcase-output"> <div class='tag'>output</div> <span class="prefix data">Returns</span> <span class="value data"> 36 </span> </div> </div> </li> </ol> </div> <hr /> This problem statement is the exclusive and proprietary property of TopCoder, Inc. Any unauthorized use or reproduction of this information without the prior written consent of TopCoder, Inc. is strictly prohibited. (c)2003, TopCoder, Inc. All rights reserved. </body> </html> <file_sep>/template.py # -*- coding: utf-8 -*- # # Author: <NAME> <<EMAIL>> # import string, copy class ${ClassName}: def ${Method.Name}(self, ${Method.Params}): return ${Method.ReturnType;zeroval} ${CutBegin} ${<TestCode} ${CutEnd} <file_sep>/SRM 753/MaxCutFree.py # -*- coding: utf-8 -*- import math,string,itertools,fractions,heapq,collections,re,array,bisect class MaxCutFree: def solve(self, n, a, b): l = len(a) is_bridge = [False for _ in range(l)] for i in range(l): start = a[i] end = b[i] used = [False for _ in range(l)] used[i] = True def dfs(point): if point == end: return True for j in range(l): if used[j]: continue if a[j] == point: used[j] = True if dfs(b[j]): return True if b[j] == point: if dfs(a[j]): return True return False is_bridge[i] = not dfs(start) removed = [] pairs = [(a[i], b[i]) for i in range(l) if is_bridge[i]] while pairs: counts = {} nums = [i for i, _ in pairs] + [j for _, j in pairs] for k in nums: if k not in counts: counts[k] = 0 counts[k] += 1 r = None c = 0 for k, v in counts.items(): if v > c: c = v r = k removed.append(r) pairs = [(i, j) for i, j in pairs if r not in (i, j)] return n - len(removed) # CUT begin # TEST CODE FOR PYTHON {{{ import sys, time, math def tc_equal(expected, received): try: _t = type(expected) received = _t(received) if _t == list or _t == tuple: if len(expected) != len(received): return False return all(tc_equal(e, r) for (e, r) in zip(expected, received)) elif _t == float: eps = 1e-9 d = abs(received - expected) return not math.isnan(received) and not math.isnan(expected) and d <= eps * max(1.0, abs(expected)) else: return expected == received except: return False def pretty_str(x): if type(x) == str: return '"%s"' % x elif type(x) == tuple: return '(%s)' % (','.join( (pretty_str(y) for y in x) ) ) else: return str(x) def do_test(n, a, b, __expected): startTime = time.time() instance = MaxCutFree() exception = None try: __result = instance.solve(n, a, b); except: import traceback exception = traceback.format_exc() elapsed = time.time() - startTime # in sec if exception is not None: sys.stdout.write("RUNTIME ERROR: \n") sys.stdout.write(exception + "\n") return 0 if tc_equal(__expected, __result): sys.stdout.write("PASSED! " + ("(%.3f seconds)" % elapsed) + "\n") return 1 else: sys.stdout.write("FAILED! " + ("(%.3f seconds)" % elapsed) + "\n") sys.stdout.write(" Expected: " + pretty_str(__expected) + "\n") sys.stdout.write(" Received: " + pretty_str(__result) + "\n") return 0 def run_tests(): sys.stdout.write("MaxCutFree (1000 Points)\n\n") passed = cases = 0 case_set = set() for arg in sys.argv[1:]: case_set.add(int(arg)) with open("MaxCutFree.sample", "r") as f: while True: label = f.readline() if not label.startswith("--"): break n = int(f.readline().rstrip()) a = [] for i in range(0, int(f.readline())): a.append(int(f.readline().rstrip())) a = tuple(a) b = [] for i in range(0, int(f.readline())): b.append(int(f.readline().rstrip())) b = tuple(b) f.readline() __answer = int(f.readline().rstrip()) cases += 1 if len(case_set) > 0 and (cases - 1) in case_set: continue sys.stdout.write(" Testcase #%d ... " % (cases - 1)) passed += do_test(n, a, b, __answer) sys.stdout.write("\nPassed : %d / %d cases\n" % (passed, cases)) T = time.time() - 1553095536 PT, TT = (T / 60.0, 75.0) points = 1000 * (0.3 + (0.7 * TT * TT) / (10.0 * PT * PT + TT * TT)) sys.stdout.write("Time : %d minutes %d secs\n" % (int(T/60), T%60)) sys.stdout.write("Score : %.2f points\n" % points) if __name__ == '__main__': run_tests() # }}} # CUT end <file_sep>/SRM 165/ShortPalindromes.cpp #include <string> #include <vector> #include <iostream> #include <strstream> #include <sstream> #include <stdio.h> #include <stdlib.h> #include <algorithm> #include <cmath> using namespace std; int len[50][50]; int pad[50][50]; int n; class ShortPalindromes { public: string shortest(string base) { string ans = ""; int i,j,l; n = base.size(); for(i = 0; i < n; i++){ len[i][i] = 1; pad[i][i] = 4; len[i+1][i] = 0; pad[i+1][i] = 4; } for(l = 2; l <= n; l++){ for(i = 0; i <= n - l; i++){ char h, t; j = i + l - 1; h = base[i]; t = base[j]; if(h == t){ len[i][j] = len[i+1][j-1] + 2; pad[i][j] = 3; } else{ if(len[i+1][j] < len[i][j-1]){ len[i][j] = len[i+1][j] + 2; pad[i][j] = 1; } if(len[i+1][j] > len[i][j-1]){ len[i][j] = len[i][j-1] + 2; pad[i][j] = 2; } if(len[i+1][j] == len[i][j-1]){ if(h < t){ len[i][j] = len[i+1][j] + 2; pad[i][j] = 1; } else{ len[i][j] = len[i][j-1] + 2; pad[i][j] = 2; } } } } } //cout<<"end"; i = 0; j = n - 1; l = 0; while(i < j){ switch(pad[i][j]){ case 1: ans = ans + base[i]; i++; l++; break; case 2: ans = ans + base[j]; j--; l++; break; case 3: ans = ans + base[i]; i++; j--; l++; break; case 4: break; } } if(i==j) ans += base[i]; for(i = l - 1; i >= 0; i--){ ans += ans[i]; } return ans; } }; // Powered by PopsEdit <file_sep>/2003 TCO Semifinals 4/AvoidRoads.html <!DOCTYPE html> <html> <head> <meta charset="utf-8" /> <title>TopCoder 2003 TCO Semifinals 4 - 250: AvoidRoads</title> <link type="image/x-icon" rel="shortcut icon" href="http://www.topcoder.com/i/favicon.ico"/> <style type="text/css"> /* font */ body { font-family: Helvetica, Arial, Verdana, sans-serif; font-size: 16px; line-height: 1.2em; } ul.constraints > li:before, ul.notes > li:before { font-family: monospace; font-weight: normal; } .heading { font-weight: bold; font-size: 175%; line-height: 1.2em; } .section .section-title { font-weight: bold; font-size: 125%; } ol.testcases > li:before { font-family: monospace; } type { font-weight: bold; font-family: monospace; } li.testcase .data { font-family: monospace; line-height: 1.5em; } /* layout */ .heading { margin-top: 0.1em; margin-bottom:0.1em; text-align: center; } .section .section-title { margin-top : 1em; margin-bottom: 1em; } .problem-intro, note, user-constraint { padding-left: 1.25em; } /* Lists */ ul.constraints, ul.notes, ul.variables, ul.problem-definition-lines { list-style-type: none; padding: 0px; } ul.constraints > li:before { content: "-"; position:relative; margin-left: 0px; /* optional, for multiline li element */ left: 0.625em; } ul.notes > li:before { content: "-"; position:relative; margin-left: 0px; /* optional, for multiline li element */ left: 0.625em; } /* Testcases */ li.testcase { line-height: 1.1em; padding-top: 0.625em; padding-bottom: 0.625em; overflow: auto; } li.testcase > .testcase-content > div { padding-bottom: 0.5em; padding-left: 1em; } li.testcase .testcase-comment { margin: 0; padding-left: 1em; } .testcase-comment p:first-child { margin-top: 0; } .testcase-comment p:last-child { margin-bottom: 0; } li.testcase .testcase-content { margin: 0.31em; } /* Data and variables */ .testcase-output { padding: 0.2em 1em 0.2em 0em; } .variables, .testcase-output { margin-left: 0.5em; display: table; margin-bottom: 0px; margin-top: 0px; } .variable { display: table-row; } .variable .name { padding: 0.2em 0em 0.2em 1em; font-weight: bold; display: table-cell; text-align: right; } .testcase-output .prefix { padding: 0.2em 0em 0.2em 1em; display: table-cell; } .testcase-output .prefix:after { content : ":"; padding-right: 0.5em; } .variable .name:after { font-weight: bold; content : ":"; padding-right: 0.5em; } .variable .value, .testcase-output .value { padding: 0.2em 1em 0.2em 0em; display: table-cell; } ol.testcases { padding: 0px; counter-reset: test_number -1; } ol.testcases > li { list-style:none; } ol.testcases > li:before { counter-increment:test_number; display: block; clear: both; content:counter(test_number) ")"; color: inherit; background: inherit; } /* Problem Definition */ .problem-definition, .problem-limits { padding-left: 1.25em; } .problem-definition-lines, .limit-lines { display: table; margin-top: 0px; margin-bottom: 0px; padding-left: 0px; } .definition-line, .limit-line { display: table-row; height: 1.5em; overflow: auto; } .limit-name:after { content: ":"; margin-right: 1em; } .definition-name, .definition-value, .limit-name, .limit-value { display: table-cell; } .definition-value { padding-left: 0.5em; } .definition-name:after { content: ":"; } #contest-division:before { content: "Div "; } #problem-score:before { content: "- Problem "; } #problem-name { display: block; } /* Tags, hidden default */ .tag { visibility: hidden; position: absolute; } body { /* font color */ color: #333333; /* background color */ background-color: white; } .section .section-title { /* title color */ color: black; } li.testcase .data { /* highlight color */ background: #eee; } </style> </head> <body> <h1 class="heading"> <span id='contest-name'>2003 TCO Semifinals 4</span> <span id='problem-score'>250</span> <span id='problem-name'>AvoidRoads</span> </h1> <hr /> <!-- Problem Statement --> <div class="section"> <h2 class="section-title">Problem Statement</h2> <div class="problem-intro"> <intro><i>Problem contains images. Plugin users can view them in the applet.</i><br /> In the city, roads are arranged in a grid pattern. Each point on the grid represents a corner where two blocks meet. The points are connected by line segments which represent the various street blocks. Using the cartesian coordinate system, we can assign a pair of integers to each corner as shown below. <br /> <br /> <img src="http://www.topcoder.com/contest/problem/AvoidRoads/AvoidPic1.GIF"></img> <br /> You are standing at the corner with coordinates 0,0. Your destination is at corner <b>width</b>,<b>height</b>. You will return the number of distinct paths that lead to your destination. Each path must use exactly <b>width+height</b> blocks. In addition, the city has declared certain street blocks untraversable. These blocks may not be a part of any path. You will be given a <type>String[]</type> <b>bad</b> describing which blocks are bad. If (quotes for clarity) &quot;a b c d&quot; is an element of <b>bad</b>, it means the block from corner a,b to corner c,d is untraversable. For example, let's say <pre> <b>width</b> = 6 <b>length</b> = 6 <b>bad</b> = {&quot;0 0 0 1&quot;,&quot;6 6 5 6&quot;}</pre> The picture below shows the grid, with untraversable blocks darkened in black. A sample path has been highlighted in red.<br /> <br /> <img src="http://www.topcoder.com/contest/problem/AvoidRoads/AvoidPic2.GIF"></img> <br /></intro> </div> </div> <!-- Problem definition --> <div class="section" id="definition"> <h2 class="section-title">Definition</h2> <div class="problem-definition"> <ul class="problem-definition-lines"> <li class="definition-line" id='class-line'> <span class='definition-name'>Class</span> <span class='definition-value'>AvoidRoads</span> </li> <li class="definition-line" id='method-line'> <span class='definition-name'>Method</span> <span class='definition-value'>numWays</span> </li> <li class="definition-line" id='parameters-line'> <span class='definition-name'>Parameters</span> <span class='definition-value'> integer , integer , tuple(string) </span> </li> <li class="definition-line" id='returns-line'> <span class='definition-name'>Returns</span> <span class='definition-value'> integer </span> </li> <li class="definition-line" id='signature-line'> <span class='definition-name'>Method signature</span> <span class='definition-value'> def numWays(self, width, height, bad) </span> </li> </ul> <div class="problem-definition-public-tip">(be sure your method is public)</div> </div> </div> <!-- Limits --> <div class="section"> <h2 class="section-title">Limits</h2> <div class='problem-limits'> <ul class="limit-lines"> <li class='limit-line'> <span class='limit-name'>Time limit (s)</span> <span class='limit-value'>2.000</span> </li> <li class='limit-line'> <span class='limit-name'>Memory limit (MB)</span> <span class='limit-value'>64</span> </li> </ul> </div> </div> <!-- Constraints --> <div class="section"> <h2 class="section-title">Constraints</h2> <ul class="constraints"> <li><user-constraint><b>width</b> will be between 1 and 100 inclusive.</user-constraint></li> <li><user-constraint><b>height</b> will be between 1 and 100 inclusive.</user-constraint></li> <li><user-constraint><b>bad</b> will contain between 0 and 50 elements inclusive.</user-constraint></li> <li><user-constraint>Each element of <b>bad</b> will contain between 7 and 14 characters inclusive.</user-constraint></li> <li><user-constraint>Each element of the bad will be in the format &quot;a b c d&quot; where, <ul><li> a,b,c,d are integers with no extra leading zeros,</li><li> a and c are between 0 and <b>width</b> inclusive,</li><li> b and d are between 0 and <b>height</b> inclusive,</li><li>and a,b is one block away from c,d.</li></ul></user-constraint></li> <li><user-constraint>The return value will be between 0 and 2^63-1 inclusive.</user-constraint></li> </ul> </div> <!-- Test cases --> <div class="section"> <h2 class="section-title">Test cases</h2> <ol class="testcases" start='0'> <li class="testcase"> <div class="testcase-content"> <div class="testcase-input"> <div class='tag'>input</div> <ul class="variables"> <li class="variable data"> <span class="name data">width</span> <span class="value data"> 6 </span> </li> <li class="variable data"> <span class="name data">height</span> <span class="value data"> 6 </span> </li> <li class="variable data"> <span class="name data">bad</span> <span class="value data"> {&quot;0 0 0 1&quot;,<br />&nbsp;&quot;6 6 5 6&quot;} </span> </li> </ul> </div> <div class="testcase-output"> <div class='tag'>output</div> <span class="prefix data">Returns</span> <span class="value data"> 252 </span> </div> <div class="testcase-annotation"> <div class='tag'>note</div> <div class="testcase-comment">Example from above.</div> </div> </div> </li> <li class="testcase"> <div class="testcase-content"> <div class="testcase-input"> <div class='tag'>input</div> <ul class="variables"> <li class="variable data"> <span class="name data">width</span> <span class="value data"> 1 </span> </li> <li class="variable data"> <span class="name data">height</span> <span class="value data"> 1 </span> </li> <li class="variable data"> <span class="name data">bad</span> <span class="value data"> { } </span> </li> </ul> </div> <div class="testcase-output"> <div class='tag'>output</div> <span class="prefix data">Returns</span> <span class="value data"> 2 </span> </div> <div class="testcase-annotation"> <div class='tag'>note</div> <div class="testcase-comment">Four blocks aranged in a square. Only 2 paths allowed.</div> </div> </div> </li> <li class="testcase"> <div class="testcase-content"> <div class="testcase-input"> <div class='tag'>input</div> <ul class="variables"> <li class="variable data"> <span class="name data">width</span> <span class="value data"> 35 </span> </li> <li class="variable data"> <span class="name data">height</span> <span class="value data"> 31 </span> </li> <li class="variable data"> <span class="name data">bad</span> <span class="value data"> { } </span> </li> </ul> </div> <div class="testcase-output"> <div class='tag'>output</div> <span class="prefix data">Returns</span> <span class="value data"> 6406484391866534976 </span> </div> <div class="testcase-annotation"> <div class='tag'>note</div> <div class="testcase-comment">Big number.</div> </div> </div> </li> <li class="testcase"> <div class="testcase-content"> <div class="testcase-input"> <div class='tag'>input</div> <ul class="variables"> <li class="variable data"> <span class="name data">width</span> <span class="value data"> 2 </span> </li> <li class="variable data"> <span class="name data">height</span> <span class="value data"> 2 </span> </li> <li class="variable data"> <span class="name data">bad</span> <span class="value data"> {&quot;0 0 1 0&quot;,<br />&nbsp;&quot;1 2 2 2&quot;,<br />&nbsp;&quot;1 1 2 1&quot;} </span> </li> </ul> </div> <div class="testcase-output"> <div class='tag'>output</div> <span class="prefix data">Returns</span> <span class="value data"> 0 </span> </div> </div> </li> </ol> </div> <hr /> This problem statement is the exclusive and proprietary property of TopCoder, Inc. Any unauthorized use or reproduction of this information without the prior written consent of TopCoder, Inc. is strictly prohibited. (c)2003, TopCoder, Inc. All rights reserved. </body> </html> <file_sep>/README.rst =================== TopCoder Playground =================== This is just a backup of my topcoder playground.
d00168df6d8d6ffa6b49a7b15fc6f9dfca5b4519
[ "HTML", "reStructuredText", "Python", "Text", "C++" ]
7
Text
LucasD11/TopCoder
9e383ce2c013c1b086d61625416faa9f6be75aac
53cc3acf99c136b2059e4af33e46ee424cadead9
refs/heads/main
<repo_name>albanLM/DucksNDynamite<file_sep>/src/game_engine/entity.cpp #include "entity.h" Entity::Entity(GraphicalObject graphicalObject):_graphicalObject(graphicalObject) { } GraphicalObject *Entity::graphicalObject() { return &_graphicalObject; } <file_sep>/src/graphical_engine/spritesheet.cpp #include "spritesheet.h" SpriteSheet::SpriteSheet(SDL_Renderer* pRenderer, std::string const &file, Uint8 backgroundRed, Uint8 backgroundGreen, Uint8 backgroundBlue):_file(file) { _pImage = IMG_Load(file.c_str()); _backgroundColor = SDL_MapRGB(_pImage->format,backgroundRed,backgroundGreen,backgroundBlue); SDL_SetColorKey(_pImage, SDL_TRUE,_backgroundColor); _pTexture = SDL_CreateTextureFromSurface(pRenderer,_pImage); } SpriteSheet::SpriteSheet(SDL_Renderer* pRenderer, std::string const &file): SpriteSheet(pRenderer, file, 0, 255, 0) { } SpriteSheet::~SpriteSheet() { SDL_DestroyTexture(_pTexture); SDL_FreeSurface(_pImage); } SDL_Texture *SpriteSheet::pTexture() const { return _pTexture; } <file_sep>/include/controllers/window_controller.h #ifndef WINDOWCONTROLLER_H #define WINDOWCONTROLLER_H #include "controller.h" class WindowController : public Controller { public: WindowController(); void processEvent(SDL_Event event, Actions * pActions); }; #endif // WINDOWCONTROLLER_H <file_sep>/src/main.cpp #include <iostream> #include "window.h" #include "game.h" int main() { Window * pWindow = Window::Instance(); std::unique_ptr<Game> &pGame = Game::Instance(); pGame->run(); free(pWindow); return 0; } <file_sep>/src/rectangle.cpp #include "rectangle.h" Rectangle::Rectangle(float x, float y, float width, float height): _x(x), _y(y), _width(width), _height(height) { } Rectangle::Rectangle():Rectangle(0.0, 0.0, 0.0, 0.0) { } SDL_Rect Rectangle::toSdlRect() { return SDL_Rect{(int)_x, (int)_y, (int)_width, (int)_height}; } float Rectangle::x() const { return _x; } float Rectangle::y() const { return _y; } float Rectangle::width() const { return _width; } float Rectangle::height() const { return _height; } void Rectangle::setX(float x) { _x = x; } void Rectangle::setY(float y) { _y = y; } void Rectangle::setWidth(float width) { _width = width; } void Rectangle::setHeight(float height) { _height = height; } <file_sep>/include/graphical_engine/spritesheet.h #ifndef SPRITESHEET_H #define SPRITESHEET_H #include <SDL2/SDL.h> #include <SDL2/SDL_image.h> #include <string> /** * Represent a sprite sheet object. * Sprite sheets are loaded from the filesystem. */ class SpriteSheet { public: SpriteSheet(SpriteSheet const &spriteSheet); SpriteSheet(SDL_Renderer *pRenderer, std::string const &file, Uint8 backgroundRed, Uint8 backgroundGreen, Uint8 backgroundBlue); SpriteSheet(SDL_Renderer *pRenderer, std::string const &file); ~SpriteSheet(); SDL_Texture *pTexture() const; private: std::string _file; SDL_Surface * _pImage; Uint32 _backgroundColor; SDL_Texture * _pTexture; }; #endif // SPRITESHEET_H <file_sep>/src/game_engine/tangible_entities/character.cpp #include "tangible_entities/character.h" #include <cmath> Character::Character(GraphicalObject const &graphicalObject,Hitbox const &hitbox) : TangibleEntity(graphicalObject,hitbox) {} void Character::dropBomb() { } void Character::move(Direction direction) { // Add movement based on player inputs float x = 0.0f, y = 0.0f; switch (direction) { case Up: y--; break; case Down: y++; break; case Left: x--; break; case Right: x++; break; } // Normalize the vector float dist = sqrt(x*x + y*y); x = x / (dist == 0 ? 1 : dist) * _speed; y = y / (dist == 0 ? 1 : dist) * _speed; // Send the translation to the object _graphicalObject.translate(x, y); } <file_sep>/src/graphical_engine/graphical_scene.cpp #include "graphical_scene.h" GraphicalScene::GraphicalScene() { } GraphicalScene::~GraphicalScene() { for (auto i = _plans.rbegin() ; i != _plans.rend(); i++) { delete *i; } } void GraphicalScene::displayGame() { Window* pWindow = Window::Instance(); SDL_RenderClear(pWindow->pRenderer()); for (auto i = _plans.rbegin() ; i != _plans.rend(); i++) { (*i)->display(); } SDL_RenderPresent(pWindow->pRenderer()); } void GraphicalScene::addPlan(float scrollingSpeed) { GraphicalPlan * pGraphicalPlan = new GraphicalPlan(scrollingSpeed); _plans.push_back(pGraphicalPlan); } void GraphicalScene::addObjectToPlan(GraphicalObject *pObject, int plan) { if((int)_plans.size()>plan) _plans.at(plan)->addObject(pObject); } <file_sep>/src/game.cpp #include "game.h" #include "actions.h" #include <iostream> using namespace std; std::unique_ptr<Game> Game::_instance; Game::Game(int width, int height) { Window * pWindow = Window::Instance(); pWindow->resize(width,height); } Game::~Game() { while (!_spriteSheets.empty()) { auto it = _spriteSheets.begin(); delete it->second; _spriteSheets.erase( it ); } } unique_ptr<Game> & Game::Instance() { if (_instance == nullptr) { // If no instance of game exists, create a new instance _instance = std::unique_ptr<Game>(new Game()); } // Else return _instance; } void Game::run() { // Add plans to the scene _scene.addPlan(2.0); _scene.addPlan(1.0); // Load and add the sprite sheets to the scene const char * file = "../sprites/MegamanX_Zero_spritesheet_green.png"; SpriteSheet *pSpriteSheet = loadSpriteSheet(file); Rectangle rec(8,14,38,44); GraphicalObject g1(pSpriteSheet, rec, 3, 0, 0); GraphicalObject g2(pSpriteSheet, rec, 3, 200, 0); Hitbox hitbox(8,14,38,44); Character *pCharacter = new Character(g1,hitbox); Entity *pEntity = new Entity(g2); _scene.addObjectToPlan(pCharacter->graphicalObject(), 0); _scene.addObjectToPlan(pEntity->graphicalObject(), 1); // Game loop. Runs until the user presses ESCAPE. while(!_actions[Actions::Quit]) { _scene.displayGame(); _controllersManager.processEvents(&_actions); // Iterate over possible actions for (pair<const Actions::Action, bool> action : _actions.actions) { // If action is no activated, skip if (!action.second) continue; // Else, perform the corresponding action switch (action.first) { case Actions::Confirm: break; case Actions::Up: pCharacter->move(Up); break; case Actions::Down: pCharacter->move(Down); break; case Actions::Left: pCharacter->move(Left); break; case Actions::Right: pCharacter->move(Right); break; case Actions::Enter: delete pEntity; pEntity = nullptr; } } } } SpriteSheet* Game::loadSpriteSheet(std::string const &fileName) { // Search in memory the sprite sheet with given name auto i = _spriteSheets.find(fileName); // If the given sprite sheet was not found in memory, load the fileName if(i == _spriteSheets.end()) { // Load the sprite sheet SpriteSheet *pSpriteSheet = new SpriteSheet(Window::Instance()->pRenderer(), fileName); // Insert the sprite sheet into the map _spriteSheets.insert(i, pair<std::string, SpriteSheet*>(fileName, pSpriteSheet)); return pSpriteSheet; } // Else, return the one that was found return i->second; } <file_sep>/src/game_engine/tangible_entity.cpp #include "tangible_entity.h" TangibleEntity::TangibleEntity(GraphicalObject graphicalObject, Hitbox hitbox):Entity(graphicalObject),_hitbox(hitbox) { } Hitbox TangibleEntity::hitbox() const { return _hitbox; } <file_sep>/include/controllers/controllers_manager.h #ifndef CONTROLLERSMANAGER_H #define CONTROLLERSMANAGER_H #include <SDL2/SDL.h> #include "window_controller.h" #include "keyboard_controller.h" #include "actions.h" class ControllersManager { public: ControllersManager(); void processEvents(Actions * pActions); private: WindowController _windowController; KeyboardController _keyboardController; }; #endif // CONTROLLERSMANAGER_H <file_sep>/src/controllers/window_controller.cpp #include "window_controller.h" WindowController::WindowController() { } void WindowController::processEvent(SDL_Event event, Actions * pActions) { switch (event.window.event) { case SDL_WINDOWEVENT_CLOSE: (*pActions)[Actions::Quit] = true; break; default: break; } } <file_sep>/src/game_engine/entities_manager.cpp #include "entities_manager.h" EntitiesManager::EntitiesManager() { } <file_sep>/include/controllers/actions.h #ifndef ACTIONS_H #define ACTIONS_H #include <map> class Actions { public: enum Action { Quit, Confirm, Up, Down, Left, Right, Enter }; std::map<Action, bool> actions { {Quit,false}, {Confirm, false}, {Up, false}, {Down, false}, {Left, false}, {Right, false}, {Enter, false} }; Actions() = default; ~Actions() = default; bool& operator[](Action const &action); bool operator[](Action const &action) const; }; #endif // ACTIONS_H <file_sep>/src/game_engine/hitbox.cpp #include "hitbox.h" Hitbox::Hitbox(float x, float y, float width, float height):Rectangle(x,y,width,height) { } Hitbox::Hitbox():Rectangle() { } bool Hitbox::isCrossing(Hitbox *h) { //if (x1<=x2 && x1+w1>=x2) || (x2<=x1 && x2+w2>=x1) //if (y1<=y2 && y1+h1>=y2) || (y2<=y1 && y2+h2>=y1) bool xCrossing = (_x<=h->x() && _x+_width >= h->x()) || (h->x()<=_x && h->x()+h->width() >= _x); bool yCrossing = (_y<=h->y() && _y+_height >= h->y()) || (h->y()<=_y && h->y()+h->height() >= _y); return (xCrossing && yCrossing); } <file_sep>/src/controllers/actions.cpp #include "actions.h" bool& Actions::operator[](Actions::Action const &action) { return actions.at(action); } bool Actions::operator[](Actions::Action const &action) const { return actions.at(action); } <file_sep>/include/rectangle.h #ifndef RECTANGLE_H #define RECTANGLE_H #include <SDL2/SDL.h> class Rectangle { public: Rectangle(float x, float y, float width, float height); Rectangle(); SDL_Rect toSdlRect(); float x() const; float y() const; float width() const; float height() const; void setX(float x); void setY(float y); void setWidth(float width); void setHeight(float height); protected: float _x; float _y; float _width; float _height; }; #endif // RECTANGLE_H <file_sep>/include/game.h #ifndef GAME_H #define GAME_H #include <SDL2/SDL.h> #include <iostream> #include <memory> #include <map> #include "graphical_scene.h" #include "window.h" #include "controllers_manager.h" #include "actions.h" #include "entity.h" #include "character.h" /** * Main class of the program. Launch the main game loop and quit when the user presses ESCAPE. */ class Game { private: explicit Game(int width = 640, int height = 480); /** * @brief Search in memory for a sprite sheet with the given name. If it doesn't exist, load the sprite sheet from the filesystem. * @param fileName Name of the fileName containing the sprite sheet * @return a pointer to the given sprite sheet stored in memory */ SpriteSheet* loadSpriteSheet(std::string const &fileName); Actions _actions; GraphicalScene _scene; ControllersManager _controllersManager; static std::unique_ptr<Game> _instance; std::map<std::string, SpriteSheet*> _spriteSheets; public: ~Game(); /** * @return a singleton instance of Game */ static std::unique_ptr<Game> & Instance(); /** * Run the main game loop, a while loop. * Quit when the user presses ESCAPE. */ void run(); }; #endif // GAME_H <file_sep>/include/controllers/controller.h #ifndef CONTROLLER_H #define CONTROLLER_H #include <SDL2/SDL.h> #include "actions.h" class Game; class Controller { public: Controller(); virtual void processEvent(SDL_Event event, Actions * pActions) = 0; }; #endif // CONTROLLER_H <file_sep>/src/controllers/keyboard_controller.cpp #include <iostream> #include "keyboard_controller.h" // TODO: Refactor this. Add a file with a key-to-action map. void KeyboardController::processEvent(SDL_Event event, Actions * pActions) { switch(event.type) { case SDL_KEYDOWN: switch (event.key.keysym.sym) { case SDLK_KP_SPACE: (*pActions)[Actions::Confirm] = true; break; case SDLK_z: (*pActions)[Actions::Up] = true; break; case SDLK_s: (*pActions)[Actions::Down] = true; break; case SDLK_q: (*pActions)[Actions::Left] = true; break; case SDLK_d: (*pActions)[Actions::Right] = true; break; case SDLK_RETURN: (*pActions)[Actions::Enter] = true; break; default: break; } break; case SDL_KEYUP: switch (event.key.keysym.sym) { case SDLK_ESCAPE: (*pActions)[Actions::Quit] = true; break; case SDLK_KP_SPACE: (*pActions)[Actions::Confirm] = false; break; case SDLK_z: (*pActions)[Actions::Up] = false; break; case SDLK_s: (*pActions)[Actions::Down] = false; break; case SDLK_q: (*pActions)[Actions::Left] = false; break; case SDLK_d: (*pActions)[Actions::Right] = false; break; case SDLK_RETURN: (*pActions)[Actions::Enter] = false; break; default: break; } break; } } <file_sep>/src/controllers/controllers_manager.cpp #include "controllers_manager.h" ControllersManager::ControllersManager() { } void ControllersManager::processEvents(Actions *pActions) { SDL_Event event; while(SDL_PollEvent(&event)) { switch(event.type) { case SDL_WINDOWEVENT: _windowController.processEvent(event, pActions); break; case SDL_KEYDOWN: case SDL_KEYUP: _keyboardController.processEvent(event, pActions); break; } } } <file_sep>/src/graphical_engine/graphical_object.cpp #include "graphical_object.h" GraphicalObject::GraphicalObject(SpriteSheet *spritesheet, Rectangle spriteRect, float sizeCoef, float x, float y, SDL_RendererFlip flip): _pSpritesheet(spritesheet), _spriteRect(spriteRect), _sizeCoef(sizeCoef), _x(x), _y(y), _flip(flip) { } GraphicalObject::GraphicalObject(SpriteSheet *spritesheet, Rectangle spriteRect, float sizeCoef, float x, float y): GraphicalObject(spritesheet, spriteRect, sizeCoef, x, y, SDL_FLIP_NONE) { } Rectangle GraphicalObject::spriteRect() const { return _spriteRect; } SpriteSheet *GraphicalObject::pSpritesheet() const { return _pSpritesheet; } float GraphicalObject::sizeCoef() const { return _sizeCoef; } float GraphicalObject::x() const { return _x; } float GraphicalObject::y() const { return _y; } SDL_RendererFlip GraphicalObject::flip() const { return _flip; } void GraphicalObject::setSpriteRect(const Rectangle &spriteRect) { _spriteRect = spriteRect; } void GraphicalObject::setSizeCoef(float sizeCoef) { _sizeCoef = sizeCoef; } void GraphicalObject::setCoordinates(float x, float y) { _x = x; _y = y; } void GraphicalObject::setFlip(const SDL_RendererFlip &flip) { _flip = flip; } void GraphicalObject::translate(float x, float y) { _x += x; _y += y; } <file_sep>/include/graphical_engine/window.h #ifndef WINDOW_H #define WINDOW_H #include <iostream> #include <SDL2/SDL.h> #include <SDL2/SDL_image.h> class Window { public: ~Window(); static Window* Instance(); void resize(int width, int height); SDL_Renderer *pRenderer() const; int width() const; int height() const; private : Window(); void createWindow(); void destroyWindow(); static Window * _instance; SDL_Window* _pSdlWindow; SDL_Renderer* _pRenderer; int _width = 640; int _height = 480; }; #endif // WINDOW_H <file_sep>/include/graphical_engine/graphical_scene.h #ifndef GRAPHICALSCENE_H #define GRAPHICALSCENE_H #include <vector> #include <iostream> #include <SDL2/SDL.h> #include "graphical_plan.h" #include "graphical_object.h" class GraphicalScene { public: GraphicalScene(); ~GraphicalScene(); void displayGame(); void addPlan(float scrollingSpeed); void addObjectToPlan(GraphicalObject * pObject, int plan); private: std::vector<GraphicalPlan*> _plans; }; #endif // GRAPHICALSCENE_H <file_sep>/include/game_engine/tangible_entity.h #ifndef TANGIBLEENTITY_H #define TANGIBLEENTITY_H #include "entity.h" #include "hitbox.h" #include "graphical_object.h" class TangibleEntity : public Entity { public: TangibleEntity(GraphicalObject graphicalObject, Hitbox hitbox); Hitbox hitbox() const; protected: Hitbox _hitbox; }; #endif // TANGIBLEENTITY_H <file_sep>/include/controllers/keyboard_controller.h #ifndef KEYBOARDCONTROLLER_H #define KEYBOARDCONTROLLER_H #include "controller.h" class KeyboardController : public Controller { public: KeyboardController() = default; void processEvent(SDL_Event event, Actions * pActions); }; #endif // KEYBOARDCONTROLLER_H <file_sep>/src/graphical_engine/graphical_plan.cpp #include "graphical_plan.h" GraphicalPlan::GraphicalPlan(float scrollingSpeed): _scrollingSpeed(scrollingSpeed) { } void GraphicalPlan::addObject(GraphicalObject *pObject) { _objects.push_back(pObject); } void GraphicalPlan::display() { Window * pWindow = Window::Instance(); SDL_Rect spriteRect; SpriteSheet * pSpritesheet; float sizeCoef, x, y; SDL_RendererFlip flip; for (std::vector<GraphicalObject *>::iterator i = _objects.begin() ; i != _objects.end(); i++) { // If the graphical object doesn't exist anymore, remove it from the list if (*i == nullptr) { i = _objects.erase(i)--; continue; } pSpritesheet = (*i)->pSpritesheet(); spriteRect = (*i)->spriteRect().toSdlRect(); sizeCoef = (*i)->sizeCoef(); x = (*i)->x(); y = (*i)->y(); flip = (*i)->flip(); SDL_Rect renderRect = {(int)(pWindow->width()/2 - spriteRect.w/2*sizeCoef + x), (int)(pWindow->height()/2 - spriteRect.h/2*sizeCoef + y), (int)(spriteRect.w*sizeCoef), (int)(spriteRect.h*sizeCoef)}; SDL_RenderCopyEx(pWindow->pRenderer(),pSpritesheet->pTexture(),&spriteRect,&renderRect,0.0,NULL,flip); } } void GraphicalPlan::setScrollingSpeed(float scrollingSpeed) { _scrollingSpeed = scrollingSpeed; } GraphicalPlan::~GraphicalPlan() { while (!_objects.empty()) { auto it = _objects.begin(); delete *it; _objects.erase( it ); } } <file_sep>/include/game_engine/hitbox.h #ifndef HITBOX_H #define HITBOX_H #include "rectangle.h" class Hitbox : public Rectangle { public: Hitbox(float x, float y, float width, float height); Hitbox(); bool isCrossing(Hitbox * h); }; #endif // HITBOX_H <file_sep>/include/graphical_engine/graphical_object.h #ifndef GRAPHICALOBJECT_H #define GRAPHICALOBJECT_H #include "spritesheet.h" #include "rectangle.h" #include "window.h" /** * Graphical representation of an entity. * Contains a position on the canvas, a sprite sheet, and a size coefficient. */ class GraphicalObject { public: GraphicalObject(SpriteSheet* spritesheet, Rectangle spriteRect, float sizeCoef, float x, float y, SDL_RendererFlip flip); GraphicalObject(SpriteSheet* spritesheet, Rectangle spriteRect, float sizeCoef, float x, float y); Rectangle spriteRect() const; SpriteSheet *pSpritesheet() const; float sizeCoef() const; float x() const; float y() const; SDL_RendererFlip flip() const; void setSpriteRect(const Rectangle &spriteRect); void setSizeCoef(float sizeCoef); void setCoordinates(float x, float y); void setFlip(const SDL_RendererFlip &flip); void translate(float x, float y); private: SpriteSheet * _pSpritesheet; Rectangle _spriteRect; float _sizeCoef; float _x; float _y; SDL_RendererFlip _flip; }; #endif // GRAPHICALOBJECT_H <file_sep>/include/game_engine/entities_manager.h #ifndef ENTITIESMANAGER_H #define ENTITIESMANAGER_H class EntitiesManager { public: EntitiesManager(); }; #endif // ENTITIESMANAGER_H<file_sep>/src/graphical_engine/window.cpp #include "window.h" Window *Window::_instance = nullptr; Window::Window() { /* Initializing SDL */ if (SDL_Init(SDL_INIT_VIDEO) != 0) { std::cerr << "Error while initializing SDL: " << SDL_GetError() << "\n"; } // Load support for the JPG and PNG image formats int flags = IMG_INIT_JPG|IMG_INIT_PNG; int imgSupport = IMG_Init(flags); if((imgSupport & flags) != flags) { std::cerr << "Error while initializing image support by SDL_Image: " << IMG_GetError() << "\n"; IMG_Quit(); SDL_Quit(); } createWindow(); } Window::~Window(){ destroyWindow(); IMG_Quit(); SDL_Quit(); } Window* Window::Instance() { if (_instance == nullptr) { _instance = new Window; } return _instance; } void Window::createWindow() { _pSdlWindow = SDL_CreateWindow("Ducks N Dynamite", SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, _width, _height, SDL_WINDOW_SHOWN); if(_pSdlWindow) { _pRenderer = SDL_CreateRenderer(_pSdlWindow,-1,SDL_RENDERER_ACCELERATED); if (_pRenderer) { SDL_SetRenderDrawColor(_pRenderer, 0, 0, 0, 255); } } } void Window::destroyWindow() { SDL_DestroyRenderer(_pRenderer); SDL_DestroyWindow(_pSdlWindow); } int Window::height() const { return _height; } int Window::width() const { return _width; } SDL_Renderer *Window::pRenderer() const { return _pRenderer; } void Window::resize(int width, int height) { destroyWindow(); _width = width; _height = height; createWindow(); } <file_sep>/include/game_engine/tangible_entities/character.h #ifndef DUCKSNDYNAMITE_CHARACTER_H #define DUCKSNDYNAMITE_CHARACTER_H #include <tangible_entity.h> enum Direction { Up, Down, Left, Right }; class Character : public TangibleEntity { private: Direction _direction {Down}; float _speed {0.01f}; int _nbMaxBombs {1}; int _explosionSize {1}; public: explicit Character(GraphicalObject const &graphicalObject,Hitbox const &hitbox); void dropBomb(); void move(Direction direction); }; #endif //DUCKSNDYNAMITE_CHARACTER_H <file_sep>/include/game_engine/entity.h #ifndef ENTITY_H #define ENTITY_H #include "graphical_object.h" class Entity { public: Entity(GraphicalObject graphicalObject); GraphicalObject * graphicalObject(); protected: GraphicalObject _graphicalObject; }; #endif // ENTITY_H <file_sep>/CMakeLists.txt cmake_minimum_required(VERSION 3.19) project(DucksNDynamite) set(CMAKE_CXX_STANDARD 20) add_executable(DucksNDynamite src/controllers/actions.cpp src/controllers/controller.cpp src/controllers/controllers_manager.cpp src/controllers/keyboard_controller.cpp src/controllers/window_controller.cpp src/game_engine/entities_manager.cpp src/game_engine/entity.cpp src/game_engine/hitbox.cpp src/game_engine/tangible_entity.cpp src/graphical_engine/graphical_object.cpp src/graphical_engine/graphical_plan.cpp src/graphical_engine/graphical_scene.cpp src/graphical_engine/spritesheet.cpp src/graphical_engine/window.cpp src/game.cpp src/main.cpp src/rectangle.cpp src/game_engine/tangible_entities/character.cpp include/game_engine/tangible_entities/character.h) target_include_directories(DucksNDynamite PRIVATE include/) target_include_directories(DucksNDynamite PRIVATE include/controllers) target_include_directories(DucksNDynamite PRIVATE include/game_engine) target_include_directories(DucksNDynamite PRIVATE include/graphical_engine) target_include_directories(DucksNDynamite PRIVATE include/game_engine/tangible_entities) ### Dependencies ## Add SDL2 list(APPEND CMAKE_MODULE_PATH ${CMAKE_CURRENT_SOURCE_DIR}/cmake/sdl2) find_package(SDL2 REQUIRED) find_package(SDL2_image REQUIRED) target_link_libraries(DucksNDynamite PRIVATE SDL2::Main SDL2::Image)<file_sep>/include/graphical_engine/graphical_plan.h #ifndef GRAPHICALPLAN_H #define GRAPHICALPLAN_H #include <vector> #include <iostream> #include "graphical_object.h" #include "window.h" class GraphicalPlan { public: explicit GraphicalPlan(float scrollingSpeed); ~GraphicalPlan(); void addObject(GraphicalObject * pObject); void display(); void setScrollingSpeed(float scrollingSpeed); private: float _scrollingSpeed; std::vector<GraphicalObject *> _objects; }; #endif // GRAPHICALPLAN_H
312712a556450aa7ddfb9e9b216c160a1c4037b6
[ "CMake", "C++" ]
35
C++
albanLM/DucksNDynamite
57dced39d6b54c6ecc4dce1149355b39da37bfa6
b27b278710ecccd9822135d1d3b729fa88f3c763
refs/heads/master
<file_sep>module Dry::Initializer # Contains definitions for a single attribute, and builds its parts of mixin class Attribute class << self # Collection of additional dispatchers for method options # # @example Enhance the gem by adding :coercer alias for type # Dry::Initializer::Attribute.dispatchers << -> (string: nil, **op) do # op[:type] = proc(&:to_s) if string # op # end # # class User # extend Dry::Initializer # param :name, string: true # same as `type: proc(&:to_s)` # end # def dispatchers @@dispatchers ||= [] end def new(source, coercer = nil, **options) options[:source] = source options[:target] = options.delete(:as) || source options[:type] ||= coercer params = dispatchers.inject(options) { |h, m| m.call(h) } super(params) end def param(*args) Param.new(*args) end def option(*args) Option.new(*args) end end attr_reader :source, :target, :coercer, :default, :optional, :reader def initialize(options) @source = options[:source] @target = options[:target] @coercer = options[:type] @default = options[:default] @optional = !!(options[:optional] || @default) @reader = options.fetch(:reader, :public) @undefined = options.fetch(:undefined, true) validate end def ==(other) source == other.source end def postsetter "@__options__[:#{target}] = @#{target}" \ " unless @#{target} == #{undefined}" end def getter return unless reader command = %w(private protected).include?(reader.to_s) ? reader : :public <<-RUBY undef_method :#{target} if method_defined?(:#{target}) || protected_method_defined?(:#{target}) || private_method_defined?(:#{target}) #{reader_definition} #{command} :#{target} RUBY end private def validate validate_target validate_default validate_coercer end def undefined @undefined ? "Dry::Initializer::UNDEFINED" : "nil" end def reader_definition if @undefined "def #{target}; @#{target} unless @#{target} == #{undefined}; end" else "attr_reader :#{target}" end end def validate_target return if target =~ /\A\w+\Z/ fail ArgumentError.new("Invalid name '#{target}' for the target variable") end def validate_default return if default.nil? || default.is_a?(Proc) fail DefaultValueError.new(source, default) end def validate_coercer return if coercer.nil? || coercer.respond_to?(:call) fail TypeConstraintError.new(source, coercer) end def default_hash(type) default ? { :"#{type}_#{source}" => default } : {} end def coercer_hash(type) return {} unless coercer value = coercer unless @undefined value ||= proc { |v| v == Dry::Initializer::UNDEFINED ? v : coercer.(v) } { :"#{type}_#{source}" => value } end end end <file_sep>Bundler.require(:benchmarks) require "dry-initializer" class NoOptsTest extend Dry::Initializer::Mixin param :foo option :bar end class DefaultsTest extend Dry::Initializer::Mixin param :foo, default: proc { "FOO" } option :bar, default: proc { "BAR" } end class TypesTest extend Dry::Initializer::Mixin param :foo, proc(&:to_s) option :bar, proc(&:to_s) end class DefaultsAndTypesTest extend Dry::Initializer::Mixin param :foo, proc(&:to_s), default: proc { "FOO" } option :bar, proc(&:to_s), default: proc { "BAR" } end puts "Benchmark for various options" Benchmark.ips do |x| x.config time: 15, warmup: 10 x.report("no opts") do NoOptsTest.new "foo", bar: "bar" end x.report("with defaults") do DefaultsTest.new end x.report("with types") do TypesTest.new "foo", bar: "bar" end x.report("with defaults and types") do DefaultsAndTypesTest.new end x.compare! end <file_sep>RSpec.describe ROM::SQL::Association::OneToOne, helpers: true do subject(:assoc) do ROM::SQL::Association::OneToOne.new(source, target, options) end let(:options) { {} } let(:users) { double(:users, primary_key: :id) } let(:tasks) { double(:tasks) } let(:avatars) { double(:avatars) } describe '#associate' do let(:source) { :users } let(:target) { :avatar } let(:relations) do { users: users, avatar: avatars } end it 'returns child tuple with FK set' do expect(avatars).to receive(:foreign_key).with(:users).and_return(:user_id) avatar_tuple = { url: 'http://rom-rb.org/images/logo.svg' } user_tuple = { id: 3 } expect(assoc.associate(relations, avatar_tuple, user_tuple)).to eql( user_id: 3, url: 'http://rom-rb.org/images/logo.svg' ) end end shared_examples_for 'one-to-one association' do describe '#combine_keys' do it 'returns a hash with combine keys' do expect(tasks).to receive(:foreign_key).with(:users).and_return(:user_id) expect(assoc.combine_keys(relations)).to eql(id: :user_id) end end end context 'with default names' do let(:source) { :users } let(:target) { :tasks } let(:relations) do { users: users, tasks: tasks } end it_behaves_like 'one-to-one association' describe '#join_keys' do it 'returns a hash with combine keys' do expect(tasks).to receive(:foreign_key).with(:users).and_return(:user_id) expect(assoc.join_keys(relations)).to eql( qualified_attribute(:users, :id) => qualified_attribute(:tasks, :user_id) ) end end end context 'with custom relation names' do let(:source) { assoc_name(:users, :people) } let(:target) { assoc_name(:tasks, :user_tasks) } let(:relations) do { users: users, tasks: tasks } end it_behaves_like 'one-to-one association' describe '#join_keys' do it 'returns a hash with combine keys' do expect(tasks).to receive(:foreign_key).with(:users).and_return(:user_id) expect(assoc.join_keys(relations)).to eql( qualified_attribute(:people, :id) => qualified_attribute(:user_tasks, :user_id) ) end end end end <file_sep># coding: utf-8 RSpec.describe 'Repository with multi-adapters configuration' do let(:configuration) { ROM::Configuration.new(default: [:sql, DB_URI], memory: [:memory]) } let(:sql_conn) { configuration.gateways[:default].connection } let(:rom) { ROM.container(configuration) } let(:users) { rom.relation(:sql_users) } let(:tasks) { rom.relation(:memory_tasks) } let(:repo) { Test::Repository.new(rom) } before do [:tags, :tasks, :posts, :books, :users, :posts_labels, :labels, :reactions, :messages].each { |table| sql_conn.drop_table?(table) } sql_conn.create_table :users do primary_key :id column :name, String end module Test class Users < ROM::Relation[:sql] schema(:users, as: :sql_users, infer: true) end class Tasks < ROM::Relation[:memory] schema(:tasks, as: :memory_tasks) do attribute :user_id, ROM::Types::Int attribute :title, ROM::Types::String end gateway :memory use :key_inference view(:base, [:user_id, :title]) do self end def for_users(users) restrict(user_id: users.pluck(:id)) end end class Repository < ROM::Repository[:sql_users] relations :memory_tasks def users_with_tasks(id) aggregate(many: { tasks: memory_tasks }).where(id: id) end end end configuration.register_relation(Test::Users) configuration.register_relation(Test::Tasks) user_id = configuration.gateways[:default].dataset(:users).insert(name: 'Jane') configuration.gateways[:memory].dataset(:tasks).insert(user_id: user_id, title: 'Jane Task') end specify 'ᕕ⁞ ᵒ̌ 〜 ᵒ̌ ⁞ᕗ' do user = repo.users_with_tasks(users.last[:id]).first expect(user.name).to eql('Jane') expect(user.tasks[0].user_id).to eql(user.id) expect(user.tasks[0].title).to eql('Jane Task') end end <file_sep># Hanami::Webconsole [Hanami](http://hanamirb.org) development web console. ## Status [![Gem Version](http://img.shields.io/gem/v/hanami-webconsole.svg)](https://badge.fury.io/rb/hanami-webconsole) [![Build Status](http://img.shields.io/travis/hanami/webconsole/master.svg)](https://travis-ci.org/hanami/webconsole?branch=master) ## Installation Add this line to your Hanami project's `Gemfile`: ```ruby group :development do gem "hanami-webconsole" end ``` And then execute: ```shell $ bundle install ``` **NOTE:** You need a version of `hanami` `1.2.0+`. ## Usage When an exception is raised during your local development in-browser, you'll see the web console. ### Code reloading This gem in incompatible with `hanami` code reloading. In order to use this gem, you have two alternatives: 1. Start the server without code reloading: `bundle exec hanami server --no-code-reloading` 1. Use [`hanami-reloader`](https://rubygems.org/gems/hanami-reloader) gem and start the server as usual: `bundle exec hanami server` ## Development After checking out the repo, run `bin/setup` to install dependencies. You can also run `bin/console` for an interactive prompt that will allow you to experiment. To install this gem onto your local machine, run `bundle exec rake install`. To release a new version, update the version number in `version.rb`, and then run `bundle exec rake release`, which will create a git tag for the version, push git commits and tags, and push the `.gem` file to [rubygems.org](https://rubygems.org). To run all the test, use `script/ci`. ## Contributing Bug reports and pull requests are welcome on GitHub at https://github.com/hanami/webconsole. ## Acknowledgements This gem is based on the great work of [`better_errors`](https://rubygems.org/gems/better_errors) and [`binding_of_caller`](https://rubygems.org/gems/binding_of_caller) gems. Thank you! ## Copyright Copyright © 2018 <NAME> – Released under MIT License <file_sep>require 'rom/commands/result' module ROM module SQL module Commands # Adds transaction interface to commands # # @api private module Transaction ROM::SQL::Rollback = Class.new(Sequel::Rollback) # Start a transaction # # @param [Hash] options The options hash supported by Sequel # # @return [ROM::Commands::Result::Success,ROM::Commands::Result::Failure] # # @api public def transaction(options = {}, &block) result = relation.dataset.db.transaction(options, &block) if result ROM::Commands::Result::Success.new(result) else ROM::Commands::Result::Failure.new(result) end rescue ROM::CommandError => e ROM::Commands::Result::Failure.new(e) end end end end end <file_sep>RSpec.describe 'Eager loading' do include_context 'users and tasks' with_adapters do before do conf.relation(:users) do def by_name(name) where(name: name) end end conf.relation(:tasks) do def for_users(users) where(user_id: users.map { |tuple| tuple[:id] }) end end conf.relation(:tags) do def for_tasks(tasks) inner_join(:task_tags, task_id: :id) .where(task_id: tasks.map { |tuple| tuple[:id] }) end end end it 'issues 3 queries for 3.graphd relations' do users = container.relation(:users).by_name('Piotr') tasks = container.relation(:tasks) tags = container.relation(:tags) relation = users.graph(tasks.for_users.graph(tags.for_tasks)) # TODO: figure out a way to assert correct number of issued queries expect(relation.call).to be_instance_of(ROM::Relation::Loaded) end end end <file_sep>module Dry::Initializer module InstanceDSL private # The method is reloaded explicitly # in a class that extend [Dry::Initializer], or in its subclasses. def initialize(*args) __initialize__(*args) end # The method is redefined implicitly every time # a `param` or `option` is invoked. def __initialize__(*); end end end <file_sep>require 'rom/sql/function' RSpec.describe ROM::SQL::Function, :postgres do subject(:func) { ROM::SQL::Function.new(type) } include_context 'database setup' let(:ds) { container.gateways[:default][:users] } let(:type) { ROM::SQL::Types::Int } describe '#sql_literal' do context 'without alias' do specify do expect(func.count(:id).sql_literal(ds)).to eql(%(COUNT("id"))) end end context 'with alias' do specify do expect(func.count(:id).as(:count).sql_literal(ds)).to eql(%(COUNT("id") AS "count")) end end end describe '#is' do it 'returns an sql boolean expression' do expect(ds.literal(func.count(:id).is(1))).to eql(%((COUNT("id") = 1))) end end describe '#method_missing' do it 'responds to anything when not set' do expect(func.count(:id)).to be_instance_of(func.class) end it 'raises error when is set already' do expect { func.count(:id).upper.sql_literal(ds) }. to raise_error(NoMethodError, /upper/) end end describe '#cast' do it 'transforms data' do expect(func.cast(:id, 'varchar').sql_literal(ds)). to eql(%(CAST("id" AS varchar(255)))) end end end <file_sep>RSpec.describe ROM::SQL::Association::ManyToOne, helpers: true do with_adapters do context 'common name conventions' do include_context 'users and tasks' include_context 'accounts' subject(:assoc) { ROM::SQL::Association::ManyToOne.new(:tasks, :users) } before do conf.relation(:tasks) do schema do attribute :id, ROM::SQL::Types::Serial attribute :user_id, ROM::SQL::Types::ForeignKey(:users) attribute :title, ROM::SQL::Types::String end end end describe '#result' do specify { expect(ROM::SQL::Association::ManyToOne.result).to be(:one) } end describe '#name' do it 'uses target by default' do expect(assoc.name).to be(:users) end end describe '#target' do it 'builds full relation name' do assoc = ROM::SQL::Association::ManyToOne.new(:users, :tasks, relation: :foo) expect(assoc.name).to be(:tasks) expect(assoc.target).to eql(ROM::SQL::Association::Name[:foo, :tasks]) end end describe '#call' do it 'prepares joined relations' do relation = assoc.call(container.relations) expect(relation.schema.map(&:to_sql_name)). to eql([Sequel.qualify(:users, :id), Sequel.qualify(:users, :name), Sequel.qualify(:tasks, :id).as(:task_id)]) expect(relation.where(user_id: 1).one).to eql(id: 1, task_id: 2, name: 'Jane') expect(relation.where(user_id: 2).one).to eql(id: 2, task_id: 1, name: 'Joe') expect(relation.to_a). to eql([ { id: 1, task_id: 2, name: 'Jane' }, { id: 2, task_id: 1, name: 'Joe' } ]) end end describe ROM::Plugins::Relation::SQL::AutoCombine, '#for_combine' do it 'preloads relation based on association' do relation = users.for_combine(assoc).call(tasks.call) expect(relation.to_a). to eql([ { id: 1, task_id: 2, name: 'Jane' }, { id: 2, task_id: 1, name: 'Joe' } ]) end it 'maintains original relation' do users.accounts.insert(user_id: 2, number: '31', balance: 0) relation = users. join(:accounts, user_id: :id). select_append(users.accounts[:number].as(:account_num)). order(:account_num). for_combine(assoc).call(tasks.call) expect(relation.to_a). to eql([{ id: 2, task_id: 1, name: 'Joe', account_num: '31' }, { id: 1, task_id: 2, name: 'Jane', account_num: '42' }]) end end end context 'arbitrary name conventions' do include_context 'users' include_context 'posts' let(:articles_name) { ROM::Relation::Name[:articles, :posts] } let(:articles) { container.relations[:articles] } subject(:assoc) do ROM::SQL::Association::ManyToOne.new(articles_name, :users) end before do conf.relation(:articles) do schema(:posts) do attribute :post_id, ROM::SQL::Types::Serial attribute :author_id, ROM::SQL::Types::ForeignKey(:users) attribute :title, ROM::SQL::Types::Strict::String attribute :body, ROM::SQL::Types::Strict::String end end end describe '#call' do it 'prepares joined relations' do relation = assoc.call(container.relations) expect(relation.schema.map(&:to_sql_name)). to eql([Sequel.qualify(:users, :id), Sequel.qualify(:users, :name), Sequel.qualify(:posts, :post_id)]) expect(relation.order(:id).to_a).to eql([ { id: 1, name: 'Jane', post_id: 2 }, { id: 2, name: 'Joe', post_id: 1 } ]) expect(relation.where(author_id: 1).to_a).to eql( [id: 1, name: 'Jane', post_id: 2] ) expect(relation.where(author_id: 2).to_a).to eql( [id: 2, name: 'Joe', post_id: 1] ) end end end end end <file_sep>require 'rom/sql/dsl' module ROM module SQL # @api private class RestrictionDSL < DSL # @api private def call(&block) instance_exec(&block) end # Returns a result of SQL EXISTS clause. # # @example # users.where { exists(users.where(name: 'John')) } def exists(relation) relation.dataset.exists end private # @api private def method_missing(meth, *args, &block) if schema.key?(meth) schema[meth] else type = type(meth) if type ::ROM::SQL::Function.new(type) else ::Sequel::VIRTUAL_ROW.__send__(meth, *args, &block) end end end end end end <file_sep>RSpec.describe 'Schema inference for common datatypes', seeds: false do include_context 'users and tasks' before do inferrable_relations.concat %i(test_characters test_inferrence test_numeric) end let(:schema) { container.relations[dataset].schema } def trunc_ts(time, drop_usec: false) usec = drop_usec ? 0 : time.to_time.usec.floor Time.mktime(time.year, time.month, time.day, time.hour, time.min, time.sec, usec) end with_adapters do |adapter| describe 'inferring attributes' do before do dataset = self.dataset conf.relation(dataset) do schema(dataset, infer: true) end end context 'for simple table' do let(:dataset) { :users } let(:source) { ROM::Relation::Name[dataset] } it 'can infer attributes for dataset' do expect(schema.to_h). to eql( id: ROM::SQL::Types::Serial.meta(name: :id, source: source), name: ROM::SQL::Types::String.meta(name: :name, limit: 255, source: source) ) end end context 'for a table with FKs' do let(:dataset) { :tasks } let(:source) { ROM::Relation::Name[:tasks] } it 'can infer attributes for dataset' do |ex| if mysql?(ex) indexes = { index: %i(user_id).to_set } else indexes = {} end expect(schema.to_h). to eql( id: ROM::SQL::Types::Serial.meta(name: :id, source: source), title: ROM::SQL::Types::String.meta(limit: 255).optional.meta(name: :title, source: source), user_id: ROM::SQL::Types::Int.optional.meta( name: :user_id, foreign_key: true, source: source, target: :users, **indexes ) ) end end context 'for complex table' do before do |example| ctx = self conn.create_table :test_inferrence do primary_key :id String :text, text: false, null: false Time :time Date :date if ctx.oracle?(example) Date :datetime, null: false else DateTime :datetime, null: false end if ctx.sqlite?(example) add_constraint(:test_constraint) { char_length(text) > 3 } end if ctx.postgres?(example) Bytea :data else Blob :data end end end let(:dataset) { :test_inferrence } let(:source) { ROM::Relation::Name[dataset] } it 'can infer attributes for dataset' do |ex| date_type = oracle?(ex) ? ROM::SQL::Types::Time : ROM::SQL::Types::Date expect(schema.to_h). to eql( id: ROM::SQL::Types::Serial.meta(name: :id, source: source), text: ROM::SQL::Types::String.meta(name: :text, limit: 255, source: source), time: ROM::SQL::Types::Time.optional.meta(name: :time, source: source), date: date_type.optional.meta(name: :date, source: source), datetime: ROM::SQL::Types::Time.meta(name: :datetime, source: source), data: ROM::SQL::Types::Blob.optional.meta(name: :data, source: source), ) end end context 'character datatypes' do before do conn.create_table :test_characters do String :text1, text: false, null: false String :text2, size: 100, null: false column :text3, 'char(100)', null: false column :text4, 'varchar', null: false column :text5, 'varchar(100)', null: false String :text6, size: 100 end end let(:dataset) { :test_characters } let(:source) { ROM::Relation::Name[dataset] } let(:char_t) { ROM::SQL::Types::String.meta(source: source) } it 'infers attributes with limit' do expect(schema.to_h).to eql( text1: char_t.meta(name: :text1, limit: 255), text2: char_t.meta(name: :text2, limit: 100), text3: char_t.meta(name: :text3, limit: 100), text4: char_t.meta(name: :text4, limit: 255), text5: char_t.meta(name: :text5, limit: 100), text6: ROM::SQL::Types::String.meta(limit: 100).optional.meta( name: :text6, source: source ) ) end end context 'numeric datatypes' do before do conn.create_table :test_numeric do primary_key :id decimal :dec, null: false decimal :dec_prec, size: 12, null: false numeric :num, size: [5, 2], null: false smallint :small integer :int float :floating double :double_p end end let(:dataset) { :test_numeric } let(:source) { ROM::Relation::Name[dataset] } let(:integer) { ROM::SQL::Types::Int.meta(source: source) } let(:decimal) { ROM::SQL::Types::Decimal.meta(source: source) } it 'infers attributes with precision' do |example| if mysql?(example) default_precision = decimal.meta(name: :dec, precision: 10, scale: 0) elsif oracle?(example) # Oracle treats DECIMAL as NUMBER(38, 0) default_precision = integer.meta(name: :dec) else default_precision = decimal.meta(name: :dec) end pending 'Add precision inferrence for Oracle' if oracle?(example) expect(schema.to_h). to eql( id: ROM::SQL::Types::Serial.meta(name: :id, source: source), dec: default_precision, dec_prec: decimal.meta(name: :dec_prec, precision: 12, scale: 0), num: decimal.meta(name: :num, precision: 5, scale: 2), small: ROM::SQL::Types::Int.optional.meta(name: :small, source: source), int: ROM::SQL::Types::Int.optional.meta(name: :int, source: source), floating: ROM::SQL::Types::Float.optional.meta(name: :floating, source: source), double_p: ROM::SQL::Types::Float.optional.meta(name: :double_p, source: source), ) end end end describe 'using commands with inferred schema' do before do inferrable_relations.concat %i(people) end let(:relation) { container.relation(:people) } before do conf.relation(:people) do schema(dataset, infer: true) end conf.commands(:people) do define(:create) do result :one end end end describe 'inserting' do let(:create) { commands[:people].create } context "Sequel's types" do before do conn.create_table :people do primary_key :id String :name, null: false end end it "doesn't coerce or check types on insert by default" do result = create.call(name: Sequel.function(:upper, 'Jade')) expect(result).to eql(id: 1, name: 'JADE') end end context 'nullable columns' do before do conn.create_table :people do primary_key :id String :name, null: false Integer :age, null: true end end it 'allows to insert records with nil value' do result = create.call(name: 'Jade', age: nil) expect(result).to eql(id: 1, name: 'Jade', age: nil) end it 'allows to omit nullable columns' do result = create.call(name: 'Jade') expect(result).to eql(id: 1, name: 'Jade', age: nil) end end context 'columns with default value' do before do conn.create_table :people do primary_key :id String :name, null: false Integer :age, null: false, default: 18 end end it 'sets default value on missing key' do result = create.call(name: 'Jade') expect(result).to eql(id: 1, name: 'Jade', age: 18) end it 'raises an error on inserting nil value' do expect { create.call(name: 'Jade', age: nil) }.to raise_error(ROM::SQL::NotNullConstraintError) end end context 'coercions' do context 'date' do before do conn.create_table :people do primary_key :id String :name, null: false Date :birth_date, null: false end end it 'accetps Time' do |ex| time = Time.iso8601('1970-01-01T06:00:00') result = create.call(name: 'Jade', birth_date: time) # Oracle's Date type stores time expected_date = oracle?(ex) ? time : Date.iso8601('1970-01-01T00:00:00') expect(result).to eql(id: 1, name: 'Jade', birth_date: expected_date) end end unless metadata[:sqlite] && defined? JRUBY_VERSION context 'timestamp' do before do |ex| ctx = self conn.create_table :people do primary_key :id String :name, null: false # TODO: fix ROM, then Sequel to infer TIMESTAMP NOT NULL for Oracle Timestamp :created_at, null: ctx.oracle?(ex) end end it 'accepts Date' do date = Date.today result = create.call(name: 'Jade', created_at: date) expect(result).to eql(id: 1, name: 'Jade', created_at: date.to_time) end it 'accepts Time' do |ex| now = Time.now result = create.call(name: 'Jade', created_at: now) expected_time = trunc_ts(now, drop_usec: mysql?(ex)) expect(result).to eql(id: 1, name: 'Jade', created_at: expected_time) end it 'accepts DateTime' do |ex| now = DateTime.now result = create.call(name: 'Jade', created_at: now) expected_time = trunc_ts(now, drop_usec: mysql?(ex)) expect(result).to eql(id: 1, name: 'Jade', created_at: expected_time) end # TODO: Find out if Oracle's adapter really doesn't support RFCs if !metadata[:mysql] && !metadata[:oracle] it 'accepts strings in RFC 2822' do now = Time.now result = create.call(name: 'Jade', created_at: now.rfc822) expect(result).to eql(id: 1, name: 'Jade', created_at: trunc_ts(now, drop_usec: true)) end it 'accepts strings in RFC 3339' do now = DateTime.now result = create.call(name: 'Jade', created_at: now.rfc3339) expect(result).to eql(id: 1, name: 'Jade', created_at: trunc_ts(now, drop_usec: true)) end end end end end end end describe 'inferring indices', oracle: false do before do |ex| conn.create_table :test_inferrence do primary_key :id Integer :foo Integer :bar, null: false Integer :baz, null: false index :foo, name: :foo_idx index :bar, name: :bar_idx index :baz, name: :baz1_idx index :baz, name: :baz2_idx index %i(bar baz), name: :composite_idx end end let(:dataset) { :test_inferrence } let(:source) { ROM::Relation::Name[dataset] } it 'infers types with indices' do int = ROM::SQL::Types::Int expect(schema.to_h). to eql( id: int.meta(name: :id, source: source, primary_key: true), foo: int.optional.meta(name: :foo, source: source, index: %i(foo_idx).to_set), bar: int.meta(name: :bar, source: source, index: %i(bar_idx composite_idx).to_set), baz: int.meta(name: :baz, source: source, index: %i(baz1_idx baz2_idx).to_set) ) end end end end <file_sep>describe "gem enhancement" do before do Dry::Initializer::Attribute.dispatchers << ->(string: false, **op) do op[:type] = proc(&:to_s) if string op end class Test::Foo extend Dry::Initializer param :bar, string: true end end it "works" do foo = Test::Foo.new(:BAZ) expect(foo.bar).to eq "BAZ" end end <file_sep>require 'rom/header' require 'rom/repository/struct_builder' module ROM class Repository # @api private class HeaderBuilder attr_reader :struct_builder def initialize(struct_namespace: nil, **options) @struct_builder = StructBuilder.new(struct_namespace) end def call(ast) Header.coerce(*visit(ast)) end alias_method :[], :call private def visit(node) name, node = node __send__("visit_#{name}", node) end def visit_relation(node) relation_name, meta, header = node name = meta[:combine_name] || relation_name model = meta.fetch(:model) do if meta[:combine_name] false else struct_builder[name, header] end end options = [visit(header), model: model] if meta[:combine_type] type = meta[:combine_type] == :many ? :array : :hash keys = meta.fetch(:keys) [name, combine: true, type: type, keys: keys, header: Header.coerce(*options)] elsif meta[:wrap] [name, wrap: true, type: :hash, header: Header.coerce(*options)] else options end end def visit_header(node) node.map { |attribute| visit(attribute) } end def visit_attribute(attr) if attr.wrapped? [attr.name, from: attr.alias] else [attr.name] end end end end end <file_sep>require 'rom/plugins/relation/instrumentation' module ROM module Plugins module Relation module SQL # @api private module Instrumentation def self.included(klass) super klass.class_eval do include ROM::Plugins::Relation::Instrumentation # @api private def notification_payload(relation) super.merge(query: relation.dataset.sql) end end end end end end end end ROM.plugins do adapter :sql do register :instrumentation, ROM::Plugins::Relation::SQL::Instrumentation, type: :relation end end <file_sep>require 'dry/core/cache' require 'rom/mapper' require 'rom/repository/header_builder' module ROM class Repository # @api private class MapperBuilder extend Dry::Core::Cache attr_reader :header_builder def initialize(options = EMPTY_HASH) @header_builder = HeaderBuilder.new(options) end def call(ast) fetch_or_store(ast) { Mapper.build(header_builder[ast]) } end alias_method :[], :call end end end <file_sep>RSpec.describe 'Using changesets' do include_context 'database' include_context 'relations' before do module Test class User < Dry::Struct attribute :id, Dry::Types['strict.int'] attribute :name, Dry::Types['strict.string'] end end configuration.mappers do define(:users) do model Test::User register_as :user end end end describe 'Create' do subject(:repo) do Class.new(ROM::Repository[:users]) { relations :books, :posts commands :create, update: :by_pk }.new(rom) end let(:create_changeset) do Class.new(ROM::Changeset::Create) end let(:add_book_changeset) do Class.new(ROM::Changeset::Create[:books]) end let(:update_changeset) do Class.new(ROM::Changeset::Update) end it 'can be passed to a command' do changeset = repo.changeset(name: "<NAME>") command = repo.command(:create, repo.users) result = command.(changeset) expect(result.id).to_not be(nil) expect(result.name).to eql("<NAME>") end it 'can be passed to a command graph' do changeset = repo.changeset( name: "<NAME>", posts: [{ title: "Just Do It", alien: "or sutin" }] ) command = repo.command(:create, repo.aggregate(:posts)) result = command.(changeset) expect(result.id).to_not be(nil) expect(result.name).to eql("<NAME>") expect(result.posts.size).to be(1) expect(result.posts[0].title).to eql("Just Do It") end it 'preprocesses data using changeset pipes' do changeset = repo.changeset(:books, title: "rom-rb is awesome").map(:add_timestamps) command = repo.command(:create, repo.books) result = command.(changeset) expect(result.id).to_not be(nil) expect(result.title).to eql("rom-rb is awesome") expect(result.created_at).to be_instance_of(Time) expect(result.updated_at).to be_instance_of(Time) end it 'preprocesses data using custom block' do changeset = repo. changeset(:books, title: "rom-rb is awesome"). map { |tuple| tuple.merge(created_at: Time.now) } command = repo.command(:create, repo.books) result = command.(changeset) expect(result.id).to_not be(nil) expect(result.title).to eql("rom-rb is awesome") expect(result.created_at).to be_instance_of(Time) end it 'preprocesses data using built-in steps and custom block' do changeset = repo. changeset(:books, title: "rom-rb is awesome"). extend(:touch) { |tuple| tuple.merge(created_at: Time.now) } command = repo.command(:create, repo.books) result = command.(changeset) expect(result.id).to_not be(nil) expect(result.title).to eql("rom-rb is awesome") expect(result.created_at).to be_instance_of(Time) expect(result.updated_at).to be_instance_of(Time) end it 'preserves relation mappers with create' do changeset = repo. changeset(create_changeset). new(repo.users.relation.as(:user)). data(name: '<NAME>') expect(changeset.commit).to eql(Test::User.new(id: 1, name: '<NAME>')) end it 'creates changesets for non-root relations' do repo.create(name: '<NAME>') changeset = repo.changeset(add_book_changeset).data(title: 'The War of the Worlds') expect(changeset.commit). to include( id: 1, title: 'The War of the Worlds', created_at: nil, updated_at: nil ) end end describe 'Update' do subject(:repo) do Class.new(ROM::Repository[:books]) { commands :create, update: :by_pk }.new(rom) end it 'can be passed to a command' do book = repo.create(title: 'rom-rb is awesome') changeset = repo .changeset(book.id, title: 'rom-rb is awesome for real') .extend(:touch) expect(changeset.diff).to eql(title: 'rom-rb is awesome for real') result = repo.update(book.id, changeset) expect(result.id).to be(book.id) expect(result.title).to eql('rom-rb is awesome for real') expect(result.updated_at).to be_instance_of(Time) end it 'skips update execution with no diff' do book = repo.create(title: 'rom-rb is awesome') changeset = repo .changeset(book.id, title: 'rom-rb is awesome') .extend(:touch) expect(changeset).to_not be_diff result = repo.update(book.id, changeset) expect(result.id).to be(book.id) expect(result.title).to eql('rom-rb is awesome') expect(result.updated_at).to be(nil) end it 'works with mixed several class-level pipes' do book = repo.create(title: 'rom-rb is awesome') changeset_class = Class.new(ROM::Changeset::Update[:books]) do map { |title: | { title: title.upcase } } extend { |title: | { title: title.reverse } } end changeset = repo .changeset(changeset_class) .by_pk(book.id) .data(title: 'rom-rb is really awesome') expect(changeset.diff).to eql(title: 'ROM-RB IS REALLY AWESOME') expect(changeset.to_h).to eql(title: 'EMOSEWA YLLAER SI BR-MOR') end it 'works with mixed several instance-level pipes' do book = repo.create(title: 'rom-rb is awesome') changeset = repo. changeset(book.id, title: 'rom-rb is really awesome'). map { |title: | { title: title.upcase } }. extend { |title: | { title: title.reverse } } expect(changeset.diff).to eql(title: 'ROM-RB IS REALLY AWESOME') expect(changeset.to_h).to eql(title: 'EMOSEWA YLLAER SI BR-MOR') end end end <file_sep>require 'dry/core/inflector' require 'dry/core/cache' require 'dry/core/class_builder' require 'rom/struct' require 'rom/open_struct' require 'rom/schema/attribute' module ROM class Repository # @api private class StructBuilder extend Dry::Core::Cache def call(*args) fetch_or_store(*args) do name, header = args attributes = visit(header).compact if attributes.empty? ROM::OpenStruct else build_class(name, ROM::Struct) do |klass| attributes.each do |(name, type)| klass.attribute(name, type) end end end end end alias_method :[], :call attr_reader :namespace def initialize(namespace = nil) @namespace = namespace || ROM::Struct end private def visit(ast) name, node = ast __send__("visit_#{name}", node) end def visit_header(node) node.map(&method(:visit)) end def visit_relation(node) relation_name, meta, header = node name = meta[:combine_name] || relation_name.relation model = meta.fetch(:model) { call(name, header) } member = if model < Dry::Struct model else Dry::Types::Definition.new(model).constructor(&model.method(:new)) end if meta[:combine_type] == :many [name, Types::Array.member(member)] else [name, member.optional] end end def visit_attribute(attr) [attr.aliased? && !attr.wrapped? ? attr.alias : attr.name, attr.to_read_type] end def build_class(name, parent, &block) Dry::Core::ClassBuilder.new(name: class_name(name), parent: parent, namespace: namespace).call(&block) end def class_name(name) Dry::Core::Inflector.classify(Dry::Core::Inflector.singularize(name)) end end end end <file_sep>RSpec.describe 'ROM::SQL::Schema::SqliteInferrer', :sqlite do include_context 'database setup' before do inferrable_relations.concat %i(test_inferrence) end before do conn.create_table :test_inferrence do tinyint :tiny int8 :big bigint :long column :dummy, nil boolean :flag, null: false end end before do conf.relation(:test_inferrence) do schema(infer: true) end end let(:schema) { container.relations[:test_inferrence].schema } let(:source) { container.relations[:test_inferrence].name } it 'can infer attributes for dataset' do expect(schema.to_h). to eql( tiny: ROM::SQL::Types::Int.optional.meta(name: :tiny, source: source), big: ROM::SQL::Types::Int.optional.meta(name: :big, source: source), long: ROM::SQL::Types::Int.optional.meta(name: :long, source: source), dummy: ROM::SQL::Types::SQLite::Object.optional.meta(name: :dummy, source: source), flag: ROM::SQL::Types::Bool.meta(name: :flag, source: source) ) end end <file_sep>require 'rom/sql/extensions/postgres/commands' require 'rom/sql/extensions/postgres/types' require 'rom/sql/extensions/postgres/inferrer' <file_sep>module ROM module SQL class Association class ManyToOne < Association result :one # @api public def call(relations, left = relations[target.relation]) right = relations[source.relation] left_pk = left.primary_key right_fk = left.foreign_key(source.relation) left_schema = left.schema right_schema = right.schema.project_pk schema = if left.schema.key?(right_fk) left_schema else left_schema.merge(right_schema.project_fk(left_pk => right_fk)) end.qualified relation = left.inner_join(source_table, join_keys(relations)) if view apply_view(schema, relation) else schema.(relation) end end # @api public def combine_keys(relations) Hash[*with_keys(relations)] end # @api public def join_keys(relations) with_keys(relations) { |source_key, target_key| { qualify(source_alias, source_key) => qualify(target, target_key) } } end # @api private def associate(relations, child, parent) fk, pk = join_key_map(relations) child.merge(fk => parent.fetch(pk)) end protected # @api private def source_table self_ref? ? Sequel.as(source.dataset, source_alias) : source end # @api private def source_alias self_ref? ? :"#{source.dataset.to_s[0]}_0" : source end # @api private def with_keys(relations, &block) source_key = foreign_key || relations[source.relation].foreign_key(target.relation) target_key = relations[target.relation].primary_key return [source_key, target_key] unless block yield(source_key, target_key) end end end end end <file_sep>require 'transproc/registry' require 'transproc/transformer' module ROM class Changeset # Transproc Registry useful for pipe # # @api private module PipeRegistry extend Transproc::Registry import Transproc::HashTransformations def self.add_timestamps(data) now = Time.now data.merge(created_at: now, updated_at: now) end def self.touch(data) data.merge(updated_at: Time.now) end end # Composable data transformation pipe used by default in changesets # # @api private class Pipe < Transproc::Transformer[PipeRegistry] extend Initializer param :processor, default: -> { self.class.transproc } option :use_for_diff, optional: true, default: -> { true } option :diff_processor, optional: true, default: -> { use_for_diff ? processor : nil } def self.[](name) container[name] end def [](name) self.class[name] end def bind(context) return self unless processor.is_a?(Proc) || diff_processor.is_a?(Proc) new(bind_processor(processor, context), diff_processor: bind_processor(diff_processor, context)) end def compose(other, use_for_diff: other.is_a?(Pipe) ? other.use_for_diff : false) new_proc = processor ? processor >> other : other if use_for_diff diff_proc = diff_processor ? diff_processor >> other : other new(new_proc, diff_processor: diff_proc) else new(new_proc) end end alias_method :>>, :compose def call(data) if processor processor.call(data) else data end end def for_diff(data) if diff_processor diff_processor.call(data) else data end end def with(opts) if opts.empty? self else Pipe.new(processor, options.merge(opts)) end end def new(processor, opts = EMPTY_HASH) Pipe.new(processor, options.merge(opts)) end def bind_processor(processor, context) if processor.is_a?(Proc) self[-> *args { context.instance_exec(*args, &processor) }] else processor end end end end end <file_sep>require 'dry-types' require 'sequel' require 'ipaddr' Sequel.extension(*%i(pg_array pg_array_ops pg_json pg_json_ops pg_hstore)) module ROM module SQL module Types module PG # UUID UUID = Types::String # Array Array = Types.Definition(Sequel::Postgres::PGArray) @array_types = ::Hash.new do |hash, type| name = "#{ type }[]" array_type = Array.constructor(-> (v) { Sequel.pg_array(v, type) }). meta(type: name, db_type: name, database: 'postgres') Attribute::TypeExtensions.register(array_type) { include ArrayMethods } hash[type] = array_type end def self.Array(db_type) @array_types[db_type] end # @!parse # class ROM::SQL::Attribute # # @!method contain(other) # # Check whether the array includes another array # # Translates to the @> operator # # # # @param [Array] other # # # # @return [SQL::Attribute<Types::Bool>] # # # # @api public # # # @!method get(idx) # # Get element by index (PG uses 1-based indexing) # # # # @param [Integer] idx # # # # @return [SQL::Attribute] # # # # @api public # # # @!method any(value) # # Check whether the array includes a value # # Translates to the ANY operator # # # # @param [Object] value # # # # @return [SQL::Attribute<Types::Bool>] # # # # @api public # # # @!method contained_by(other) # # Check whether the array is contained by another array # # Translates to the <@ operator # # # # @param [Array] other # # # # @return [SQL::Attribute<Types::Bool>] # # # # @api public # # # @!method length # # Return array size # # # # @return [SQL::Attribute<Types::Int>] # # # # @api public # # # @!method overlaps(other) # # Check whether the arrays have common values # # Translates to && # # # # @param [Array] other # # # # @return [SQL::Attribute<Types::Bool>] # # # # @api public # # # @!method remove_value(value) # # Remove elements by value # # # # @param [Object] value # # # # @return [SQL::Attribute<Types::PG::Array>] # # # # @api public # # # @!method join(delimiter, null_repr) # # Convert the array to a string by joining # # values with a delimiter (empty stirng by default) # # and optional filler for NULL values # # Translates to an `array_to_string` call # # # # @param [Object] delimiter # # @param [Object] null # # # # @return [SQL::Attribute<Types::String>] # # # # @api public # # # @!method +(other) # # Concatenate two arrays # # # # @param [Array] other # # # # @return [SQL::Attribute<Types::PG::Array>] # # # # @api public # end module ArrayMethods def contain(type, expr, other) Attribute[Types::Bool].meta(sql_expr: expr.pg_array.contains(type[other])) end def get(type, expr, idx) Attribute[type].meta(sql_expr: expr.pg_array[idx]) end def any(type, expr, value) Attribute[Types::Bool].meta(sql_expr: { value => expr.pg_array.any }) end def contained_by(type, expr, other) Attribute[Types::Bool].meta(sql_expr: expr.pg_array.contained_by(type[other])) end def length(type, expr) Attribute[Types::Int].meta(sql_expr: expr.pg_array.length) end def overlaps(type, expr, other_array) Attribute[Types::Bool].meta(sql_expr: expr.pg_array.overlaps(type[other_array])) end def remove_value(type, expr, value) Attribute[type].meta(sql_expr: expr.pg_array.remove(value)) end def join(type, expr, delimiter = '', null = nil) Attribute[Types::String].meta(sql_expr: expr.pg_array.join(delimiter, null)) end def +(type, expr, other) Attribute[type].meta(sql_expr: expr.pg_array.concat(other)) end end Attribute::TypeExtensions.register(Array.constructor -> { }) do include ArrayMethods end # JSON JSONArray = Types.Constructor(Sequel::Postgres::JSONArray, &Sequel.method(:pg_json)) JSONHash = Types.Constructor(Sequel::Postgres::JSONArray, &Sequel.method(:pg_json)) JSONOp = Types.Constructor(Sequel::Postgres::JSONOp, &Sequel.method(:pg_json)) JSON = (JSONArray | JSONHash | JSONOp).meta(database: 'postgres', db_type: 'jsonb') # JSONB JSONBArray = Types.Constructor(Sequel::Postgres::JSONBArray, &Sequel.method(:pg_jsonb)) JSONBHash = Types.Constructor(Sequel::Postgres::JSONBHash, &Sequel.method(:pg_jsonb)) JSONBOp = Types.Constructor(Sequel::Postgres::JSONBOp, &Sequel.method(:pg_jsonb)) JSONB = (JSONBArray | JSONBHash | JSONBOp).meta(database: 'postgres', db_type: 'jsonb') # @!parse # class ROM::SQL::Attribute # # @!method contain(value) # # Check whether the JSON value includes a json value # # Translates to the @> operator # # # # @example # # people.where { fields.contain(gender: 'Female') } # # people.where(people[:fields].contain([name: 'age'])) # # people.select { fields.contain(gender: 'Female').as(:is_female) } # # # # @param [Hash,Array,Object] value # # # # @return [SQL::Attribute<Types::Bool>] # # # # @api public # # # @!method contained_by(value) # # Check whether the JSON value is contained by other value # # Translates to the <@ operator # # # # @example # # people.where { custom_values.contained_by(age: 25, foo: 'bar') } # # # # @param [Hash,Array] value # # # # @return [SQL::Attribute<Types::Bool>] # # # # @api public # # # @!method get(*path) # # Extract the JSON value using at the specified path # # Translates to -> or #> depending on the number of arguments # # # # @example # # people.select { data.get('age').as(:person_age) } # # people.select { fields.get(0).as(:first_field) } # # people.select { fields.get('0', 'value').as(:first_field_value) } # # # # @param [Array<Integer>,Array<String>] path Path to extract # # # # @return [SQL::Attribute<Types::PG::JSON>,SQL::Attribute<Types::PG::JSONB>] # # # # @api public # # # @!method get_text(*path) # # Extract the JSON value as text using at the specified path # # Translates to ->> or #>> depending on the number of arguments # # # # @example # # people.select { data.get('age').as(:person_age) } # # people.select { fields.get(0).as(:first_field) } # # people.select { fields.get('0', 'value').as(:first_field_value) } # # # # @param [Array<Integer>,Array<String>] path Path to extract # # # # @return [SQL::Attribute<Types::String>] # # # # @api public # # # @!method has_key(key) # # Does the JSON value have the specified top-level key # # Translates to ? # # # # @example # # people.where { data.has_key('age') } # # # # @param [String] key # # # # @return [SQL::Attribute<Types::Bool>] # # # # @api public # # # @!method has_any_key(*keys) # # Does the JSON value have any of the specified top-level keys # # Translates to ?| # # # # @example # # people.where { data.has_any_key('age', 'height') } # # # # @param [Array<String>] keys # # # # @return [SQL::Attribute<Types::Bool>] # # # # @api public # # # @!method has_all_keys(*keys) # # Does the JSON value have all the specified top-level keys # # Translates to ?& # # # # @example # # people.where { data.has_all_keys('age', 'height') } # # # # @param [Array<String>] keys # # # # @return [SQL::Attribute<Types::Bool>] # # # # @api public # # # @!method merge(value) # # Concatenate two JSON values # # Translates to || # # # # @example # # people.select { data.merge(fetched_at: Time.now).as(:data) } # # people.select { (fields + [name: 'height', value: 165]).as(:fields) } # # # # @param [Hash,Array] value # # # # @return [SQL::Attribute<Types::PG::JSONB>] # # # # @api public # # # @!method +(value) # # An alias for ROM::SQL::Attribute<JSONB>#merge # # # # @api public # # # @!method delete(*path) # # Deletes the specified value by key, index, or path # # Translates to - or #- depending on the number of arguments # # # # @example # # people.select { data.delete('age').as(:data_without_age) } # # people.select { fields.delete(0).as(:fields_without_first) } # # people.select { fields.delete(-1).as(:fields_without_last) } # # people.select { data.delete('deeply', 'nested', 'value').as(:data) } # # people.select { fields.delete('0', 'name').as(:data) } # # # # @param [Array<String>] path # # # # @return [SQL::Attribute<Types::PG::JSONB>] # # # # @api public # end module JSONMethods def self.[](type, wrap) parent = self Module.new do include parent define_method(:json_type) { type } define_method(:wrap, wrap) end end def get(type, expr, *path) Attribute[json_type].meta(sql_expr: wrap(expr)[path_args(path)]) end def get_text(type, expr, *path) Attribute[Types::String].meta(sql_expr: wrap(expr).get_text(path_args(path))) end private def path_args(path) case path.size when 0 then raise ArgumentError, "wrong number of arguments (given 0, expected 1+)" when 1 then path[0] else path end end end Attribute::TypeExtensions.register(JSON) do include JSONMethods[JSON, :pg_json.to_proc] end Attribute::TypeExtensions.register(JSONB) do include JSONMethods[JSONB, :pg_jsonb.to_proc] def contain(type, expr, value) Attribute[Types::Bool].meta(sql_expr: wrap(expr).contains(value)) end def contained_by(type, expr, value) Attribute[Types::Bool].meta(sql_expr: wrap(expr).contained_by(value)) end def has_key(type, expr, key) Attribute[Types::Bool].meta(sql_expr: wrap(expr).has_key?(key)) end def has_any_key(type, expr, *keys) Attribute[Types::Bool].meta(sql_expr: wrap(expr).contain_any(keys)) end def has_all_keys(type, expr, *keys) Attribute[Types::Bool].meta(sql_expr: wrap(expr).contain_all(keys)) end def merge(type, expr, value) Attribute[JSONB].meta(sql_expr: wrap(expr).concat(value)) end alias_method :+, :merge def delete(type, expr, *path) sql_expr = path.size == 1 ? wrap(expr) - path : wrap(expr).delete_path(path) Attribute[JSONB].meta(sql_expr: sql_expr) end end # HStore HStoreR = Types.Constructor(Hash, &:to_hash) HStore = Types.Constructor(Sequel::Postgres::HStore, &Sequel.method(:hstore)).meta(read: HStoreR) Bytea = Types.Constructor(Sequel::SQL::Blob, &Sequel::SQL::Blob.method(:new)) IPAddressR = Types.Constructor(IPAddr) { |ip| IPAddr.new(ip.to_s) } IPAddress = Types.Constructor(IPAddr, &:to_s).meta(read: IPAddressR) Money = Types::Decimal # Geometric types Point = ::Struct.new(:x, :y) PointD = Types.Definition(Point) PointTR = Types.Constructor(Point) do |p| x, y = p.to_s[1...-1].split(',', 2) Point.new(Float(x), Float(y)) end PointT = Types.Constructor(Point) { |p| "(#{ p.x },#{ p.y })" }.meta(read: PointTR) Line = ::Struct.new(:a, :b, :c) LineTR = Types.Constructor(Line) do |ln| a, b, c = ln.to_s[1..-2].split(',', 3) Line.new(Float(a), Float(b), Float(c)) end LineT = Types.Constructor(Line) { |ln| "{#{ ln.a },#{ ln.b },#{ln.c}}"}.meta(read: LineTR) Circle = ::Struct.new(:center, :radius) CircleTR = Types.Constructor(Circle) do |c| x, y, r = c.to_s.tr('()<>', '').split(',', 3) center = Point.new(Float(x), Float(y)) Circle.new(center, Float(r)) end CircleT = Types.Constructor(Circle) { |c| "<(#{ c.center.x },#{ c.center.y }),#{ c.radius }>" }.meta(read: CircleTR) Box = ::Struct.new(:upper_right, :lower_left) BoxTR = Types.Constructor(Box) do |b| x_right, y_right, x_left, y_left = b.to_s.tr('()', '').split(',', 4) upper_right = Point.new(Float(x_right), Float(y_right)) lower_left = Point.new(Float(x_left), Float(y_left)) Box.new(upper_right, lower_left) end BoxT = Types.Constructor(Box) { |b| "((#{ b.upper_right.x },#{ b.upper_right.y }),(#{ b.lower_left.x },#{ b.lower_left.y }))" }.meta(read: BoxTR) LineSegment = ::Struct.new(:begin, :end) LineSegmentTR = Types.Constructor(LineSegment) do |lseg| x_begin, y_begin, x_end, y_end = lseg.to_s.tr('()[]', '').split(',', 4) point_begin = Point.new(Float(x_begin), Float(y_begin)) point_end = Point.new(Float(x_end), Float(y_end)) LineSegment.new(point_begin, point_end) end LineSegmentT = Types.Constructor(LineSegment) do |lseg| "[(#{ lseg.begin.x },#{ lseg.begin.y }),(#{ lseg.end.x },#{ lseg.end.y })]" end.meta(read: LineSegmentTR) Polygon = Types::Strict::Array.member(PointD) PolygonTR = Polygon.constructor do |p| coordinates = p.to_s.tr('()', '').split(',').each_slice(2) points = coordinates.map { |x, y| Point.new(Float(x), Float(y)) } Polygon[points] end PolygonT = PointD.constructor do |path| points_joined = path.map { |p| "(#{ p.x },#{ p.y })" }.join(',') "(#{ points_joined })" end.meta(read: PolygonTR) Path = ::Struct.new(:points, :type) do def open? type == :open end def closed? type == :closed end def to_a points end end PathD = Types.Definition(Path) PathTR = PathD.constructor do |path| open = path.to_s.start_with?('[') && path.to_s.end_with?(']') coordinates = path.to_s.tr('()[]', '').split(',').each_slice(2) points = coordinates.map { |x, y| Point.new(Float(x), Float(y)) } if open Path.new(points, :open) else Path.new(points, :closed) end end PathT = PathD.constructor do |path| points_joined = path.to_a.map { |p| "(#{ p.x },#{ p.y })" }.join(',') if path.open? "[#{ points_joined }]" else "(#{ points_joined })" end end.meta(read: PathTR) end end end end <file_sep>module ROM module SQL class Relation < ROM::Relation module Writing # Add upsert option (only PostgreSQL >= 9.5) # Uses internal Sequel implementation # Default - ON CONFLICT DO NOTHING # more options: http://sequel.jeremyevans.net/rdoc-adapters/classes/Sequel/Postgres/DatasetMethods.html#method-i-insert_conflict # # @example # users.upsert({ name: 'Jane', email: '<EMAIL>' }, # { target: :email, update: { name: :excluded__name } } # # @api public def upsert(*args, &block) if args.size > 1 && args[-1].is_a?(Hash) *values, opts = args else values = args opts = EMPTY_HASH end dataset.insert_conflict(opts).insert(*values, &block) end # Insert tuple into relation # # @example # users.insert(name: 'Jane') # # @param [Hash] tuple # # @return [Relation] # # @api public def insert(*args, &block) dataset.insert(*args, &block) end # Multi insert tuples into relation # # @example # users.multi_insert([{name: 'Jane'}, {name: 'Jack'}]) # # @param [Array] tuples # # @return [Relation] # # @api public def multi_insert(*args, &block) dataset.multi_insert(*args, &block) end # Update tuples in the relation # # @example # users.update(name: 'Jane') # users.where(name: 'Jane').update(name: '<NAME>') # # @return [Relation] # # @api public def update(*args, &block) dataset.update(*args, &block) end # Delete tuples from the relation # # @example # users.delete # deletes all # users.where(name: 'Jane').delete # delete tuples # from restricted relation # # @return [Relation] # # @api public def delete(*args, &block) dataset.delete(*args, &block) end end end end end <file_sep>require 'rom' require 'rom/repository' <file_sep>module ROM module SQL # Query API for SQL::Relation # # @api public module SequelAPI # Select specific columns for select clause # # @example # users.select(:id, :name).first # # {:id => 1, :name => "Jane" } # # @return [Relation] # # @api public def select(*args, &block) new(dataset.__send__(__method__, *args, &block)) end # Append specific columns to select clause # # @example # users.select(:id, :name).select_append(:email) # # {:id => 1, :name => "Jane", :email => "<EMAIL>"} # # @param [Array<Symbol>] *args A list with column names # # @return [Relation] # # @api public def select_append(*args, &block) new(dataset.__send__(__method__, *args, &block)) end # Restrict a relation to match criteria # # If block is passed it'll be executed in the context of a condition # builder object. # # @example # users.where(name: 'Jane') # # users.where { age >= 18 } # # @param [Hash] *args An optional hash with conditions for WHERE clause # # @return [Relation] # # @see http://sequel.jeremyevans.net/rdoc/files/doc/dataset_filtering_rdoc.html # # @api public def where(*args, &block) new(dataset.__send__(__method__, *args, &block)) end # Restrict a relation to match grouping criteria # # @example # users.with_task_count.having( task_count: 2 ) # # users.with_task_count.having { task_count > 3 } # # @param [Hash] *args An optional hash with conditions for HAVING clause # # @return [Relation] # # @see http://sequel.jeremyevans.net/rdoc/files/doc/dataset_filtering_rdoc.html # # @api public def having(*args, &block) new(dataset.__send__(__method__, *args, &block)) end # Set order for the relation # # @example # users.order(:name) # # @param [Array<Symbol>] *args A list with column names # # @return [Relation] # # @api public def order(*args, &block) new(dataset.__send__(__method__, *args, &block)) end # Join with another relation using INNER JOIN # # @example # users.inner_join(:tasks, id: :user_id) # # @param [Symbol] relation name # @param [Hash] join keys # # @return [Relation] # # @api public def inner_join(*args, &block) new(dataset.__send__(__method__, *args, &block)) end # Join other relation using LEFT OUTER JOIN # # @example # users.left_join(:tasks, id: :user_id) # # @param [Symbol] relation name # @param [Hash] join keys # # @return [Relation] # # @api public def left_join(*args, &block) new(dataset.__send__(__method__, *args, &block)) end # Group by specific columns # # @example # tasks.group(:user_id) # # @param [Array<Symbol>] *args A list of column names # # @return [Relation] # # @api public def group(*args, &block) new(dataset.__send__(__method__, *args, &block)) end end end end <file_sep>module ROM VERSION = '3.3.3'.freeze end <file_sep>source 'https://rubygems.org' gemspec gem 'inflecto' group :development do gem 'dry-equalizer', '~> 0.2' gem 'sqlite3', platforms: [:mri, :rbx] gem 'jdbc-sqlite3', platforms: :jruby end group :test do gem 'rom', git: 'https://github.com/rom-rb/rom.git', branch: 'release-3.0' gem 'rom-sql', git: 'https://github.com/rom-rb/rom-sql.git', branch: 'release-1.0' gem 'rspec' gem 'dry-struct' gem 'byebug', platforms: :mri gem 'pg', platforms: [:mri, :rbx] gem 'jdbc-postgres', platforms: :jruby platform :mri do gem 'codeclimate-test-reporter', require: false gem 'simplecov' end end group :benchmarks do gem 'hotch', platforms: :mri gem 'benchmark-ips' gem 'activerecord', '~> 5.0' end group :tools do gem 'pry' gem 'mutant' gem 'mutant-rspec' end <file_sep>Bundler.require(:benchmarks) require "dry-initializer" class ParamDefaults extend Dry::Initializer::Mixin param :foo, default: proc { "FOO" } param :bar, default: proc { "BAR" } param :baz, default: proc { "BAZ" } end class OptionDefaults extend Dry::Initializer::Mixin option :foo, default: proc { "FOO" } option :bar, default: proc { "BAR" } option :baz, default: proc { "BAZ" } end puts "Benchmark for param's vs. option's defaults" Benchmark.ips do |x| x.config time: 15, warmup: 10 x.report("param's defaults") do ParamDefaults.new end x.report("option's defaults") do OptionDefaults.new end x.compare! end <file_sep>RSpec.describe ROM::Repository::Root, '#aggregate' do subject(:repo) do Class.new(ROM::Repository[:users]) do relations :tasks, :posts, :labels end.new(rom) end include_context 'database' include_context 'relations' include_context 'seeds' it 'loads a graph with aliased children and its parents' do user = repo.aggregate(aliased_posts: :author).first expect(user.aliased_posts.count).to be(1) expect(user.aliased_posts[0].author.id).to be(user.id) expect(user.aliased_posts[0].author.name).to eql(user.name) end it 'exposes nodes via `node` method' do jane = repo. aggregate(:posts). node(:posts) { |posts| posts.where(title: 'Another one') }. where(name: 'Jane').one expect(jane.name).to eql('Jane') expect(jane.posts).to be_empty repo.posts.insert author_id: 1, title: 'Another one' jane = repo. aggregate(:posts). node(:posts) { |posts| posts.where(title: 'Another one') }. where(name: 'Jane').one expect(jane.name).to eql('Jane') expect(jane.posts.size).to be(1) expect(jane.posts[0].title).to eql('Another one') end it 'exposes nested nodes via `node` method' do jane = repo. aggregate(posts: :labels). node(posts: :labels) { |labels| labels.where(name: 'red') }. where(name: 'Jane').one expect(jane.name).to eql('Jane') expect(jane.posts.size).to be(1) expect(jane.posts[0].labels.size).to be(1) expect(jane.posts[0].labels[0].name).to eql('red') end it 'raises arg error when invalid relation name was passed to `node` method' do expect { repo.aggregate(:posts).node(:poztz) {} }. to raise_error(ArgumentError, ':poztz is not a valid aggregate node name') end end <file_sep>RSpec.describe ROM::SQL::Association::ManyToMany, helpers: true do subject(:assoc) do ROM::SQL::Association::ManyToMany.new(source, target, options) end let(:options) { { through: :tasks_tags } } let(:tags) { double(:tags, primary_key: :id) } let(:tasks) { double(:tasks, primary_key: :id) } let(:tasks_tags) { double(:tasks, primary_key: [:task_id, :tag_id]) } let(:source) { :tasks } let(:target) { :tags } let(:relations) do { tasks: tasks, tags: tags, tasks_tags: tasks_tags } end shared_examples_for 'many-to-many association' do describe '#combine_keys' do it 'returns a hash with combine keys' do expect(tasks_tags).to receive(:foreign_key).with(:tasks).and_return(:tag_id) expect(assoc.combine_keys(relations)).to eql(id: :tag_id) end end end describe '#result' do it 'is :many' do expect(assoc.result).to be(:many) end end describe '#associate' do let(:join_assoc) { double(:join_assoc) } let(:source) { :tags } let(:target) { :tasks } it 'returns a list of join keys for given child tuples' do expect(tasks_tags).to receive(:associations).and_return(assoc.target => join_assoc) expect(join_assoc).to receive(:join_key_map).with(relations).and_return([:task_id, :id]) expect(tasks_tags).to receive(:foreign_key).with(:tags).and_return(:tag_id) task_tuple = { id: 3 } tag_tuples = [{ id: 1 }, { id: 2 }] expect(assoc.associate(relations, tag_tuples, task_tuple)).to eql([ { tag_id: 1, task_id: 3 }, { tag_id: 2, task_id: 3 } ]) end end context 'with default names' do it_behaves_like 'many-to-many association' describe '#join_keys' do it 'returns a hash with combine keys' do expect(tasks_tags).to receive(:foreign_key).with(:tasks).and_return(:tag_id) expect(assoc.join_keys(relations)).to eql( qualified_attribute(:tasks, :id) => qualified_attribute(:tasks_tags, :tag_id) ) end end end context 'with custom relation names' do let(:source) { assoc_name(:tasks, :user_tasks) } let(:target) { assoc_name(:tags, :user_tags) } let(:relations) do { tasks: tasks, tags: tags, tasks_tags: tasks_tags } end it_behaves_like 'many-to-many association' describe '#join_keys' do it 'returns a hash with combine keys' do expect(tasks_tags).to receive(:foreign_key).with(:tasks).and_return(:tag_id) expect(assoc.join_keys(relations)).to eql( qualified_attribute(:user_tasks, :id) => qualified_attribute(:tasks_tags, :tag_id) ) end end end end <file_sep>RSpec.describe 'ROM::SQL::Schema::MysqlInferrer', :mysql do include_context 'database setup' before do inferrable_relations.concat %i(test_inferrence) end before do conn.create_table :test_inferrence do tinyint :tiny mediumint :medium bigint :big datetime :created_at column :date_and_time, 'datetime(0)' column :time_with_ms, 'datetime(3)' timestamp :unix_time_usec column :unix_time_sec, 'timestamp(0) null' boolean :flag, null: false end end before do conf.relation(:test_inferrence) do schema(infer: true) end end let(:schema) { container.relations[:test_inferrence].schema } let(:source) { container.relations[:test_inferrence].name } it 'can infer attributes for dataset' do expect(schema.to_h). to eql( tiny: ROM::SQL::Types::Int.optional.meta(name: :tiny, source: source), medium: ROM::SQL::Types::Int.optional.meta(name: :medium, source: source), big: ROM::SQL::Types::Int.optional.meta(name: :big, source: source), created_at: ROM::SQL::Types::Time.optional.meta(name: :created_at, source: source), date_and_time: ROM::SQL::Types::Time.optional.meta(name: :date_and_time, source: source), time_with_ms: ROM::SQL::Types::Time.optional.meta(name: :time_with_ms, source: source), unix_time_usec: ROM::SQL::Types::Time.meta(name: :unix_time_usec, source: source), unix_time_sec: ROM::SQL::Types::Time.optional.meta(name: :unix_time_sec, source: source), flag: ROM::SQL::Types::Bool.meta(name: :flag, source: source) ) end end <file_sep>require 'rom/sql/types' require 'rom/sql/schema' require 'rom/sql/relation/reading' require 'rom/sql/relation/writing' require 'rom/sql/relation/sequel_api' require 'rom/plugins/relation/key_inference' require 'rom/plugins/relation/sql/auto_combine' require 'rom/plugins/relation/sql/auto_wrap' module ROM module SQL # Sequel-specific relation extensions # # @api public class Relation < ROM::Relation include SQL adapter :sql use :key_inference use :auto_combine use :auto_wrap include Writing include Reading schema_dsl SQL::Schema::DSL # Set default dataset for a relation sub-class # # @api private def self.inherited(klass) super klass.class_eval do schema_inferrer -> (name, gateway) do inferrer_for_db = ROM::SQL::Schema::Inferrer.get(gateway.connection.database_type.to_sym) begin inferrer_for_db.new.call(name, gateway) rescue Sequel::Error => e inferrer_for_db.on_error(klass, e) ROM::Schema::DEFAULT_INFERRER.() end end dataset do # TODO: feels strange to do it here - we need a new hook for this during finalization klass.define_default_views! schema = klass.schema table = opts[:from].first if db.table_exists?(table) if schema select(*schema.map(&:to_sql_name)).order(*schema.project(*schema.primary_key_names).qualified.map(&:to_sql_name)) else select(*columns).order(*klass.primary_key_columns(db, table)) end else self end end end end # @api private def self.define_default_views! if schema.primary_key.size > 1 # @!method by_pk(val1, val2) # Return a relation restricted by its composite primary key # # @param [Array] args A list with composite pk values # # @return [SQL::Relation] # # @api public class_eval <<-RUBY, __FILE__, __LINE__ + 1 def by_pk(#{schema.primary_key.map(&:name).join(', ')}) where(#{schema.primary_key.map { |attr| "self.class.schema[:#{attr.name}] => #{attr.name}" }.join(', ')}) end RUBY else # @!method by_pk(pk) # Return a relation restricted by its primary key # # @param [Object] pk The primary key value # # @return [SQL::Relation] # # @api public class_eval <<-RUBY, __FILE__, __LINE__ + 1 def by_pk(pk) if primary_key.nil? raise MissingPrimaryKeyError.new( "Missing primary key for :\#{schema.name}" ) end where(self.class.schema[self.class.schema.primary_key_name].qualified => pk) end RUBY end end # @api private def self.associations schema.associations end # @api private def self.primary_key_columns(db, table) names = db.respond_to?(:primary_key) ? Array(db.primary_key(table)) : [:id] names.map { |col| :"#{table}__#{col}" } end option :primary_key, default: -> { schema.primary_key_name } # Return relation that will load associated tuples of this relation # # This method is useful for defining custom relation views for relation # composition when you want to enhance default association query # # @example # assoc(:tasks).where(tasks[:title] => "Task One") # # @param [Symbol] name The association name # # @return [Relation] # # @api public def assoc(name) associations[name].(__registry__) end # Return raw column names # # @return [Array<Symbol>] # # @api private def columns @columns ||= dataset.columns end end end end <file_sep># -*- encoding: utf-8 -*- # stub: rom-repository 1.4.0 ruby lib Gem::Specification.new do |s| s.name = "rom-repository".freeze s.version = "1.4.0" s.required_rubygems_version = Gem::Requirement.new(">= 0".freeze) if s.respond_to? :required_rubygems_version= s.require_paths = ["lib".freeze] s.authors = ["<NAME>".freeze] s.date = "2017-07-04" s.description = "rom-repository adds support for auto-mapping and commands on top of rom-rb relations".freeze s.email = "<EMAIL>".freeze s.homepage = "http://rom-rb.org".freeze s.licenses = ["MIT".freeze] s.rubygems_version = "3.0.3".freeze s.summary = "Repository abstraction for rom-rb".freeze s.installed_by_version = "3.0.3" if s.respond_to? :installed_by_version if s.respond_to? :specification_version then s.specification_version = 4 if Gem::Version.new(Gem::VERSION) >= Gem::Version.new('1.2.0') then s.add_runtime_dependency(%q<rom>.freeze, ["~> 3.3"]) s.add_runtime_dependency(%q<rom-mapper>.freeze, ["~> 0.5"]) s.add_runtime_dependency(%q<dry-core>.freeze, ["~> 0.3", ">= 0.3.1"]) s.add_runtime_dependency(%q<dry-struct>.freeze, ["~> 0.3"]) s.add_development_dependency(%q<rake>.freeze, ["~> 11.2"]) s.add_development_dependency(%q<rspec>.freeze, ["~> 3.5"]) else s.add_dependency(%q<rom>.freeze, ["~> 3.3"]) s.add_dependency(%q<rom-mapper>.freeze, ["~> 0.5"]) s.add_dependency(%q<dry-core>.freeze, ["~> 0.3", ">= 0.3.1"]) s.add_dependency(%q<dry-struct>.freeze, ["~> 0.3"]) s.add_dependency(%q<rake>.freeze, ["~> 11.2"]) s.add_dependency(%q<rspec>.freeze, ["~> 3.5"]) end else s.add_dependency(%q<rom>.freeze, ["~> 3.3"]) s.add_dependency(%q<rom-mapper>.freeze, ["~> 0.5"]) s.add_dependency(%q<dry-core>.freeze, ["~> 0.3", ">= 0.3.1"]) s.add_dependency(%q<dry-struct>.freeze, ["~> 0.3"]) s.add_dependency(%q<rake>.freeze, ["~> 11.2"]) s.add_dependency(%q<rspec>.freeze, ["~> 3.5"]) end end <file_sep>require 'rom/sql/commands/create' require 'rom/sql/commands/update' module ROM module SQL module Commands module Postgres module Create # Executes insert statement and returns inserted tuples # # @api private def insert(tuples) dataset = tuples.map do |tuple| relation.dataset.returning.insert(tuple) end.flatten(1) wrap_dataset(dataset) end # Executes multi_insert statement and returns inserted tuples # # @api private def multi_insert(tuples) relation.dataset.returning.multi_insert(tuples) end # Executes upsert statement (INSERT with ON CONFLICT clause) # and returns inserted/updated tuples # # @api private def upsert(tuple, opts = EMPTY_HASH) relation.dataset.returning.insert_conflict(opts).insert(tuple) end end module Update # Executes update statement and returns updated tuples # # @api private def update(tuple) dataset = relation.dataset.returning.update(tuple) wrap_dataset(dataset) end end # Upsert command # # Uses a feature of PostgreSQL 9.5 commonly called an "upsert". # The command been called attempts to perform an insert and # can make an update (or silently do nothing) in case of # the insertion was unsuccessful due to a violation of a unique # constraint. # Very important implementation detail is that the whole operation # is atomic, i.e. aware of concurrent transactions, and doesn't raise # exceptions if used properly. # # See PG's docs in INSERT statement for details # https://www.postgresql.org/docs/current/static/sql-insert.html # # Normally, the command should configured via class level settings. # By default, that is without any settings provided, the command # uses ON CONFLICT DO NOTHING clause. # # This implementation uses Sequel's API underneath, the docs are available at # http://sequel.jeremyevans.net/rdoc-adapters/classes/Sequel/Postgres/DatasetMethods.html#method-i-insert_conflict # # @api public class Upsert < SQL::Commands::Create adapter :sql defines :constraint, :conflict_target, :update_statement, :update_where # @!attribute [r] constraint # @return [Symbol] the name of the constraint expected to be violated option :constraint, default: -> { self.class.constraint } # @!attribute [r] conflict_target # @return [Object] the column or expression to handle a violation on option :conflict_target, default: -> { self.class.conflict_target } # @!attribute [r] update_statement # @return [Object] the update statement which will be executed in case of a violation option :update_statement, default: -> { self.class.update_statement } # @!attribute [r] update_where # @return [Object] the WHERE clause to be added to the update option :update_where, default: -> { self.class.update_where } # Tries to insert provided tuples and do an update (or nothing) # when the inserted record violates a unique constraint and hence # cannot be appended to the table # # @return [Array<Hash>] # # @api public def execute(tuples) inserted_tuples = with_input_tuples(tuples) do |tuple| upsert(input[tuple], upsert_options) end inserted_tuples.flatten(1) end # @api private def upsert_options @upsert_options ||= { constraint: constraint, target: conflict_target, update_where: update_where, update: update_statement } end end end end end end <file_sep>module ROM module Plugins module Relation module SQL # @api private module AutoWrap # @api private def self.included(klass) super klass.class_eval do include(InstanceInterface) extend(ClassInterface) end end # @api private module ClassInterface # @api private def inherited(klass) super klass.auto_curry :for_wrap end end # @api private module InstanceInterface # Default methods for fetching wrapped relation # # This method is used by default by `wrap` and `wrap_parents` # # @return [SQL::Relation] # # @api private def for_wrap(keys, name) rel, other = if associations.key?(name) assoc = associations[name] other = __registry__[assoc.target.relation] [assoc.join(__registry__, :inner_join, self, other), other] else # TODO: deprecate this before 2.0 other = __registry__[name] other_dataset = other.name.dataset [qualified.inner_join(other_dataset, keys), other] end rel.schema.merge(other.schema.wrap).qualified.(rel) end end end end end end end ROM.plugins do adapter :sql do register :auto_wrap, ROM::Plugins::Relation::SQL::AutoWrap, type: :relation end end <file_sep>RSpec.describe 'ROM::SQL::Schema::PostgresInferrer', :postgres do include_context 'database setup' before do inferrable_relations.concat %i(test_inferrence) end colors = %w(red orange yellow green blue purple) before do conn.extension :pg_enum conn.execute('create extension if not exists hstore') conn.drop_table?(:test_inferrence) conn.drop_enum(:rainbow, if_exists: true) conn.create_enum(:rainbow, colors) conn.create_table :test_inferrence do primary_key :id, :uuid bigint :big Json :json_data Jsonb :jsonb_data Decimal :money, null: false column :tags, "text[]" column :tag_ids, "bigint[]" column :ip, "inet" column :subnet, "cidr" column :hw_address, "macaddr" rainbow :color point :center xml :page hstore :mapping line :line circle :circle box :box lseg :lseg polygon :polygon path :path timestamp :created_at column :datetime, "timestamp(0) without time zone" column :datetime_tz, "timestamp(0) with time zone" boolean :flag, null: false end end let(:schema) { container.relations[:test_inferrence].schema } let(:source) { container.relations[:test_inferrence].name } context 'inferring db-specific attributes' do before do conf.relation(:test_inferrence) do schema(infer: true) end end it 'can infer attributes for dataset' do expect(schema.to_h). to eql( id: ROM::SQL::Types::PG::UUID.meta(name: :id, source: source, primary_key: true), big: ROM::SQL::Types::Int.optional.meta(name: :big, source: source), json_data: ROM::SQL::Types::PG::JSON.optional.meta(name: :json_data, source: source), jsonb_data: ROM::SQL::Types::PG::JSONB.optional.meta(name: :jsonb_data, source: source), money: ROM::SQL::Types::Decimal.meta(name: :money, source: source), tags: ROM::SQL::Types::PG::Array('text').optional.meta(name: :tags, source: source), tag_ids: ROM::SQL::Types::PG::Array('bigint').optional.meta(name: :tag_ids, source: source), color: ROM::SQL::Types::String.enum(*colors).optional.meta(name: :color, source: source), ip: ROM::SQL::Types::PG::IPAddress.optional.meta( name: :ip, source: source, read: ROM::SQL::Types::PG::IPAddressR.optional ), subnet: ROM::SQL::Types::PG::IPAddress.optional.meta( name: :subnet, source: source, read: ROM::SQL::Types::PG::IPAddressR.optional ), hw_address: ROM::SQL::Types::String.optional.meta(name: :hw_address, source: source), center: ROM::SQL::Types::PG::PointT.optional.meta( name: :center, source: source, read: ROM::SQL::Types::PG::PointTR.optional ), page: ROM::SQL::Types::String.optional.meta(name: :page, source: source), mapping: ROM::SQL::Types::PG::HStore.optional.meta( name: :mapping, source: source, read: ROM::SQL::Types::PG::HStoreR.optional ), line: ROM::SQL::Types::PG::LineT.optional.meta( name: :line, source: source, read: ROM::SQL::Types::PG::LineTR.optional ), circle: ROM::SQL::Types::PG::CircleT.optional.meta( name: :circle, source: source, read: ROM::SQL::Types::PG::CircleTR.optional ), box: ROM::SQL::Types::PG::BoxT.optional.meta( name: :box, source: source, read: ROM::SQL::Types::PG::BoxTR.optional ), lseg: ROM::SQL::Types::PG::LineSegmentT.optional.meta( name: :lseg, source: source, read: ROM::SQL::Types::PG::LineSegmentTR.optional ), polygon: ROM::SQL::Types::PG::PolygonT.optional.meta( name: :polygon, source: source, read: ROM::SQL::Types::PG::PolygonTR.optional ), path: ROM::SQL::Types::PG::PathT.optional.meta( name: :path, source: source, read: ROM::SQL::Types::PG::PathTR.optional ), created_at: ROM::SQL::Types::Time.optional.meta(name: :created_at, source: source), datetime: ROM::SQL::Types::Time.optional.meta(name: :datetime, source: source), datetime_tz: ROM::SQL::Types::Time.optional.meta(name: :datetime_tz, source: source), flag: ROM::SQL::Types::Bool.meta(name: :flag, source: source) ) end end context 'with a table without columns' do before do conn.create_table(:dummy) unless conn.table_exists?(:dummy) conf.relation(:dummy) { schema(infer: true) } end it 'does not fail with a weird error when a relation does not have attributes' do expect(container.relations[:dummy].schema).to be_empty end end context 'with a column with bi-directional mapping' do before do conn.execute('create extension if not exists hstore') conn.create_table(:test_bidirectional) do primary_key :id inet :ip point :center hstore :mapping line :line circle :circle box :box lseg :lseg polygon :polygon path :closed_path path :open_path end conf.relation(:test_bidirectional) { schema(infer: true) } conf.commands(:test_bidirectional) do define(:create) do result :one end end end let(:point) { ROM::SQL::Types::PG::Point.new(7.5, 30.5) } let(:point_2) { ROM::SQL::Types::PG::Point.new(8.5, 35.5) } let(:line) { ROM::SQL::Types::PG::Line.new(2.3, 4.9, 3.1415) } let(:dns) { IPAddr.new('8.8.8.8') } let(:mapping) { Hash['hot' => 'cold'] } let(:circle) { ROM::SQL::Types::PG::Circle.new(point, 1.0) } let(:lseg) { ROM::SQL::Types::PG::LineSegment.new(point, point_2) } let(:box_corrected) { ROM::SQL::Types::PG::Box.new(point_2, point) } let(:box) do upper_left = ROM::SQL::Types::PG::Point.new(point.x, point_2.y) lower_right = ROM::SQL::Types::PG::Point.new(point_2.x, point.y) ROM::SQL::Types::PG::Box.new(upper_left, lower_right) end let(:polygon) { ROM::SQL::Types::PG::Polygon[[point, point_2]] } let(:closed_path) { ROM::SQL::Types::PG::Path.new([point, point_2], :closed) } let(:open_path) { ROM::SQL::Types::PG::Path.new([point, point_2], :open) } let(:relation) { container.relations[:test_bidirectional] } let(:create) { commands[:test_bidirectional].create } it 'writes and reads data & corrects data' do # Box coordinates are reordered if necessary inserted = create.call( id: 1, center: point, ip: dns, mapping: mapping, line: line, circle: circle, lseg: lseg, box: box, polygon: polygon, closed_path: closed_path, open_path: open_path ) expect(inserted). to eql( id: 1, center: point, ip: dns, mapping: mapping, line: line, circle: circle, lseg: lseg, box: box_corrected, polygon: polygon, closed_path: closed_path, open_path: open_path ) expect(relation.to_a).to eql([inserted]) end end end <file_sep>module ROM module Plugins module Relation module SQL # @api private module AutoCombine # @api private def self.included(klass) super klass.class_eval do include(InstanceInterface) extend(ClassInterface) end end # @api private module ClassInterface # @api private def inherited(klass) super klass.auto_curry :for_combine klass.auto_curry :preload end end # @api private module InstanceInterface # Default methods for fetching combined relation # # This method is used by default by `combine` # # @return [SQL::Relation] # # @api private def for_combine(spec) case spec when ROM::SQL::Association spec.call(__registry__, self).preload(spec) else preload(spec) end end # @api private def preload(spec, source) case spec when ROM::SQL::Association::ManyToOne pk = source.source[source.source.primary_key].qualified where(pk => source.pluck(pk.name)) when Hash, ROM::SQL::Association source_key, target_key = spec.is_a?(Hash) ? spec.flatten(1) : spec.join_keys(__registry__).flatten(1) target_pks = source.pluck(source_key.to_sym) target_pks.uniq! where(target_key => target_pks) end end end end end end end end ROM.plugins do adapter :sql do register :auto_combine, ROM::Plugins::Relation::SQL::AutoCombine, type: :relation end end <file_sep>module ROM module Plugins module Relation module SQL # Generates methods for restricting relations by their indexed attributes # # This plugin must be enabled for the whole adapter, `use` won't work as # schema is not yet available, unless it was defined explicitly. # # @example # rom = ROM.container(:sql, 'sqlite::memory') do |config| # config.create_table(:users) do # primary_key :id # column :email, String, null: false, unique: true # end # # config.plugin(:sql, relations: :auto_restrictions) # # config.relation(:users) do # schema(infer: true) # end # end # # # now `by_email` is available automatically # rom.relations[:users].by_email('<EMAIL>') # # @api public module AutoRestrictions EmptySchemaError = Class.new(ArgumentError) do def initialize(klass) super("#{klass} relation has no schema. " \ "Make sure :auto_restrictions is enabled after defining a schema") end end def self.included(klass) super schema = klass.schema raise EmptySchemaError, klass if schema.nil? methods, mod = restriction_methods(schema) klass.include(mod) methods.each { |meth| klass.auto_curry(meth) } end def self.restriction_methods(schema) mod = Module.new indexed_attrs = schema.select { |attr| attr.meta[:index] } methods = indexed_attrs.map do |attr| meth_name = :"by_#{attr.name}" mod.module_eval do define_method(meth_name) do |value| where(attr.is(value)) end end meth_name end [methods, mod] end end end end end end ROM.plugins do adapter :sql do register :auto_restrictions, ROM::Plugins::Relation::SQL::AutoRestrictions, type: :relation end end <file_sep>## v1.4.1 2017-04-05 ### Fixed - Warning about redefined `#initialize` in case the method reloaded in a klass that extends the module (nepalez, sergey-chechaev) ### Internals - Rename `Dry::Initializer::DSL` -> `Dry::Initializer::ClassDSL` (nepalez) - Add `Dry::Initializer::InstanceDSL` (nepalez) [Compare v1.4.0...v1.4.1](https://github.com/dry-rb/dry-initializer/compare/v1.4.0...v1.4.1) ## v1.4.0 2017-03-08 ### Changed (backward-incompatible) - The `@__options__` hash now collects all assigned attributes, collected via `#option` (as before), and `#param` (nepalez) [Compare v1.3.0...v1.4.0](https://github.com/dry-rb/dry-initializer/compare/v1.3.0...v1.4.0) ## v1.3.0 2017-03-05 ### Added - No-undefined configuration of the initializer (nepalez, flash-gordon) You can either extend or include module `Dry::Initializer` with additional option `[undefined: false]`. This time `nil` will be assigned instead of `Dry::Initializer::UNDEFINED`. Readers becomes faster because there is no need to chech whether a variable was defined or not. At the same time the initializer doesn't distinct cases when a variable was set to `nil` explicitly, and when it wasn's set at all: class Foo # old behavior extend Dry::Initializer param :qux, optional: true end class Bar # new behavior extend Dry::Initializer[undefined: false] param :qux, optional: true end Foo.new.instance_variable_get(:@qux) # => Dry::Initializer::UNDEFINED Bar.new.instance_variable_get(:@qux) # => nil ### Internals - Fixed method definitions for performance at the load time (nepalez, flash-gordon) [Compare v1.2.0...v1.3.0](https://github.com/dry-rb/dry-initializer/compare/v1.2.0...v1.3.0) ## v1.2.0 2017-03-05 ### Fixed - The `@__options__` variable collects renamed options after default values and coercions were applied (nepalez) [Compare v1.1.3...v1.2.0](https://github.com/dry-rb/dry-initializer/compare/v1.1.3...v1.2.0) ## v1.1.3 2017-03-01 ### Added - Support for lambdas as default values (nepalez, gzigzigzeo) [Compare v1.1.2...v1.1.3](https://github.com/dry-rb/dry-initializer/compare/v1.1.2...v1.1.3) ## v1.1.2 2017-02-06 ### Internals - Remove previously defined methods before redefining them (flash-gordon) [Compare v1.1.1...v1.1.2](https://github.com/dry-rb/dry-initializer/compare/v1.1.1...v1.1.2) ## v1.1.1 2017-02-04 ### Bugs Fixed - `@__options__` collects defined options only (nepalez) [Compare v1.1.0...v1.1.1](https://github.com/dry-rb/dry-initializer/compare/v1.1.0...v1.1.1) ## v1.1.0 2017-01-28 ### Added: - enhancement via `Dry::Initializer::Attribute.dispatchers` registry (nepalez) # Register dispatcher for `:string` option Dry::Initializer::Attribute.dispatchers << ->(string: nil, **op) do string ? op.merge(type: proc(&:to_s)) : op end # Now you can use the `:string` key for `param` and `option` class User extend Dry::Initializer param :name, string: true end User.new(:Andy).name # => "Andy" ### Internals: - optimize assignments for performance (nepalez) [Compare v1.0.0...v1.1.0](https://github.com/dry-rb/dry-initializer/compare/v1.0.0...v1.1.0) ## v1.0.0 2017-01-22 In this version the code has been rewritten for simplicity ### BREAKING CHANGES - when `param` or `option` was not defined, the corresponding **variable** is set to `Dry::Initializer::UNDEFINED`, but the **reader** (when defined) will return `nil` (nepalez) ### Added: - support for reloading `param` and `option` definitions (nepalez) class User extend Dry::Initializer param :name param :phone, optional: true end User.new # => Boom! class Admin < User param :name, default: proc { 'Merlin' } end # order of the param not changed Admin.new.name # => "Merlin" - support for assignment of attributes via several options (nepalez) class User extend Dry::Initializer option :phone option :number, as: :phone end # Both ways provide the same result User.new(phone: '1234567890').phone # => '1234567890' User.new(number: '1234567890').phone # => '1234567890' ### Internals - `Dry::Initializer` and `Dry::Initializer::Mixin` became aliases (nepalez) [Compare v0.11.0...v1.0.0](https://github.com/dry-rb/dry-initializer/compare/v0.11.0...v1.0.0) ## v0.11.0 2017-01-02 ### Added * Support of reloading `#initializer` with `super` (nepalez) ### Internal * Refactor the way [#initializer] method is (re)defined (nepalez) When you extend class with `Dry::Initializer::Mixin`, the initializer is defined not "inside" the class per se, but inside the included module. The reference to that module is stored as class-level `__initializer_mixin__`. Mixin method [#initialize] calls another private method [#__initialize__]. It is this method to be reloaded every time you envoke a helper `option` or `product`. When new subclass is inherited, new mixin is added to chain of accessors, but this time it does reload `__initialize__` only, not the `initialize`. That is how you can safely reload initializer using `super`, but at the same time use the whole power of dry-initializer DSL both in parent class and its subclasses. The whole stack of accessors looks like the following: - Parent class mixin: `initialize` --> `__initialize__` ^ - Parent class: `initialize` - Subclass mixin: ^ `__initialize__` - Subclass: `initialize` See specification `spec/custom_initializer_spec.rb` to see how this works. [Compare v0.10.2...v0.11.0](https://github.com/dry-rb/dry-initializer/compare/v0.10.2...v0.11.0) ## v0.10.2 2016-12-31 ### Added * Support of Ruby 2.4 (flas-gordon) ### Internal * Code clearance for ROM integration (flash-gordon) [Compare v0.10.1...v0.10.2](https://github.com/dry-rb/dry-initializer/compare/v0.10.1...v0.10.2) ## v0.10.1 2016-12-27 ### Fixed * Wrong arity when there were no options and the last param had a default (nolith) [Compare v0.10.0...v0.10.1](https://github.com/dry-rb/dry-initializer/compare/v0.10.0...v0.10.1) ## v0.10.0 2016-11-20 ### Deleted (BREAKING CHANGE!) * Deprecated method DSL#using (nepalez) [Compare v0.9.3...v0.10.0](https://github.com/dry-rb/dry-initializer/compare/v0.9.3...v0.10.0) ## v0.9.3 2016-11-20 ### Deprecated * After discussion in [PR #17](https://github.com/dry-rb/dry-initializer/pull/17) (many thanks to @sahal2080 and @hrom512 for starting that issue and PR), the method `using` is deprecated and will be removed from v0.10.0 (nepalez) ### Fixed * Support of weird option names (nepalez) ```ruby option :"First name", as: :first_name ``` [Compare v0.9.2...v0.9.3](https://github.com/dry-rb/dry-initializer/compare/v0.9.2...v0.9.3) ## v0.9.2 2016-11-10 ### Fixed * Validation of attributes (params and options) (nepalez) [Compare v0.9.1...v0.9.2](https://github.com/dry-rb/dry-initializer/compare/v0.9.1...v0.9.2) ## v0.9.1 2016-11-06 ### Added * Support for renaming an option during initialization (nepalez) option :name, as: :username # to take :name option and create :username attribute [Compare v0.9.0...v0.9.1](https://github.com/dry-rb/dry-initializer/compare/v0.9.0...v0.9.1) ## v0.9.0 2016-11-06 ### Added * The method `#initialize` is defined when a class extended the module (nepalez) In previous versions the method was defined only by `param` and `option` calls. ### Breaking Changes * The initializer accepts any option (but skips unknown) from the very beginning (nepalez) ### Deleted * Deprecated methods `tolerant_to_unknown_options` and `intolerant_to_unknown_options` (nepalez) ### Internal * Refactor scope (`using`) to support methods renaming and aliasing (nepalez) [Compare v0.8.1...v0.9.0](https://github.com/dry-rb/dry-initializer/compare/v0.8.1...v0.9.0) ## v0.8.1 2016-11-05 ### Added * Support for `dry-struct`ish syntax for constraints (type as a second parameter) (nepalez) option :name, Dry::Types['strict.string'] [Compare v0.8.0...v0.8.1](https://github.com/dry-rb/dry-initializer/compare/v0.8.0...v0.8.1) ## v0.8.0 2016-11-05 In this version we switched from key arguments to ** to support special keys: option :end option :begin In previous versions this was translated to def initialize(end:, begin:) @end = end # BOOM! SyntaxError! @begin = begin # Potential BOOM (unreached) end Now the assignment is imlemented like this: def initialize(**__options__) @end = __options__.fetch(:end) @begin = __options__.fetch(:begin) end As a side effect of the change the initializer becomes tolerant to any unknown option if, and only if some `option` was set explicitly. Methods `tolerant_to_unknown_options` and `intolerant_to_unknown_options` are deprecated and will be removed in the next version of the gem. ### Added * support for special options like `option :end`, `option :begin` etc. (nepalez) ### Internals * switched from key arguments to serialized hash argument in the initializer (nepalez) ### Breaking Changes * the initializer becomes tolerant to unknown options when any `option` was set, ignoring `intolerant_to_unknown_options` helper. * the initializer becomes intolerant to options when no `option` was set, ignoring `tolerant_to_unknown_options` helper. ### Deprecated * `tolerant_to_unknown_options` * `intolerant_to_unknown_options` [Compare v0.7.0...v0.8.0](https://github.com/dry-rb/dry-initializer/compare/v0.7.0...v0.8.0) ## v0.7.0 2016-10-11 ### Added * Shared settings with `#using` method (nepalez) [Compare v0.6.0...v0.7.0](https://github.com/dry-rb/dry-initializer/compare/v0.6.0...v0.7.0) ## v0.6.0 2016-10-09 ### Added * Support for private and protected readers in the `reader:` option (jmgarnier) [Compare v0.5.0...v0.6.0](https://github.com/dry-rb/dry-initializer/compare/v0.5.0...v0.6.0) ## v0.5.0 2016-08-21 ### Added * Allow `optional` attribute to be left undefined (nepalez) [Compare v0.4.0...v0.5.0](https://github.com/dry-rb/dry-initializer/compare/v0.4.0...v0.5.0) ## v0.4.0 2016-05-28 ### Deleted (backward-incompatible changes) * Support of modules and case equality as type constraints (nepalez) [Compare v0.3.3...v0.4.0](https://github.com/dry-rb/dry-initializer/compare/v0.3.3...v0.4.0) ## v0.3.3 2016-05-28 * Add deprecation warnings about modules and case equality as type constraints (nepalez) [Compare v0.3.2...v0.3.3](https://github.com/dry-rb/dry-initializer/compare/v0.3.2...v0.3.3) ## v0.3.2 2016-05-25 ### Bugs Fixed * Add explicit requirement for ruby 'set' (rickenharp) [Compare v0.3.1...v0.3.2](https://github.com/dry-rb/dry-initializer/compare/v0.3.1...v0.3.2) ## v0.3.1 2016-05-22 ### Added * Support for tolerance to unknown options (nepalez) [Compare v0.3.0...v0.3.1](https://github.com/dry-rb/dry-initializer/compare/v0.3.0...v0.3.1) ## v0.3.0 2016-05-19 Breaks interface for adding new plugins. Register new plugin via: ``` def self.extended(klass) klass.register_initializer_plugin NewPlugin end ``` instead of: ``` def self.extended(klass) klass.initializer_builder.register NewPlugin end ``` While the private method ##initializer_builder is still accessible its method #register doesn't mutate the builder instance. ### Changed (backward-incompatible changes) * Made Mixin##initializer_builder method private (nepalez) * Add Mixin#register_initializer_plugin(plugin) method (nepalez) ### Bugs Fixed * Prevent plugin's registry from polluting superclass (nepalez) [Compare v0.2.1...v0.3.0](https://github.com/dry-rb/dry-initializer/compare/v0.2.1...v0.3.0) ### Internals * Make all instances (Builder and Signature) immutable (nepalez) * Decouple mixin from a builder to prevent pollution (nepalez) * Ensure default value block can use private variables (jeremyf) [Compare v0.2.0...v0.2.1](https://github.com/dry-rb/dry-initializer/compare/v0.2.0...v0.2.1) ## v0.2.1 2016-05-19 ### Bugs Fixed * Fix polluting superclass with declarations from subclass (nepalez) ### Internals * Make all instances (Builder and Signature) immutable (nepalez) * Decouple mixin from a builder to prevent pollution (nepalez) * Ensure default value block can use private variables (jeremyf) [Compare v0.2.0...v0.2.1](https://github.com/dry-rb/dry-initializer/compare/v0.2.0...v0.2.1) ## v0.2.0 2016-05-16 The gem internals has been rewritten heavily to make the gem pluggable and fix bugs in "container style". Type constraints were extracted to a plugin that should be added explicitly. Small extensions were added to type constraints to support constraint by any object, and apply value coercion via `dry-types`. Default assignments became slower (while plain type constraint are not)! ### Changed (backward-incompatible changes) * Make dry-types constraint to coerce variables (nepalez) ```ruby # This will coerce `name: :foo` to `"foo"` option :name, type: Dry::Types::Coercible::String ``` * Stop supporing proc type constraint (nepalez) ```ruby option :name, type: ->(v) { String === v } # this does NOT work any more ``` later it will be implemented via coercion plugin (not added by default): ```ruby require 'dry/initializer/coercion' class MyClass extend Dry::Initializer::Mixin extend Dry::Initializer::Coercion option :name, coercer: ->(v) { (String === v) ? v.to_sym : fail } end ``` ### Added * Support type constraint via every object's case equality (nepalez) ```ruby option :name, type: /foo/ option :name, type: (1...14) ``` * Support defaults and type constraints for the "container" syntax (nepalez) * Support adding extensions via plugin system (nepalez) ### Internal * Private method `##__after_initialize__` is added by the `Mixin` along with `#initialize` (nepalez) The previous implementation required defaults and types to be stored in the class method `.initializer_builder`. That made "container" syntax to support neither defaults nor types. Now the `#initializer` is still defined via `instance_eval(code)` for efficiency. Some operations (like default assignments, coercions, dry-type constraints etc.) cannot be implemented in this way. They are made inside `##__after_initialize__` callback, that is biult via `default_method(&block)` using instance evals. [Compare v0.1.1...v0.2.0](https://github.com/dry-rb/dry-initializer/compare/v0.1.1...v0.2.0) ## v0.1.1 2016-04-28 ### Added * `include Dry::Initializer.define -> do ... end` syntax (flash-gordon) [Compare v0.1.0...v0.1.1](https://github.com/dry-rb/dry-initializer/compare/v0.1.0...v0.1.1) ## v0.1.0 2016-04-26 Class DSL splitted to mixin and container versions (thanks to @AMHOL for the idea). Backward compatibility is broken. ### Changed (backward-incompatible changes) * Use `extend Dry::Initializer::Mixin` instead of `extend Dry::Initializer` (nepalez) ### Added * Use `include Dry::Initializer.define(&block)` as an alternative to extending the class (nepalez) [Compare v0.0.1...v0.1.0](https://github.com/dry-rb/dry-initializer/compare/v0.0.1...v0.1.0) ## v0.0.1 2016-04-09 First public release <file_sep>module ROM module SQL # @api private class DSL < BasicObject # @api private attr_reader :schema # @api private def initialize(schema) @schema = schema end # @api private def call(&block) result = instance_exec(&block) if result.is_a?(::Array) result else [result] end end # @api private def respond_to_missing?(name, include_private = false) super || schema.key?(name) end private # @api private def type(identifier) type_name = ::Dry::Core::Inflector.classify(identifier) types.const_get(type_name) if types.const_defined?(type_name) end # @api private def types ::ROM::SQL::Types end end end end <file_sep>RSpec.describe ROM::SQL::Association::OneToOne do include_context 'users' include_context 'accounts' subject(:assoc) { ROM::SQL::Association::OneToOne.new(:users, :accounts) } with_adapters do before do conn[:accounts].insert user_id: 1, number: '43', balance: -273.15.to_d conf.relation(:accounts) do schema do attribute :id, ROM::SQL::Types::Serial attribute :user_id, ROM::SQL::Types::ForeignKey(:users) attribute :number, ROM::SQL::Types::String attribute :balance, ROM::SQL::Types::Decimal end end end describe '#result' do specify { expect(ROM::SQL::Association::OneToOne.result).to be(:one) } end describe '#call' do it 'prepares joined relations' do |example| relation = assoc.call(container.relations) expect(relation.schema.map(&:name)).to eql(%i[id user_id number balance]) # TODO: this if caluse should be removed when (and if) https://github.com/xerial/sqlite-jdbc/issues/112 # will be resolved. See https://github.com/rom-rb/rom-sql/issues/49 for details if jruby? && sqlite?(example) expect(relation.to_a). to eql([{ id: 1, user_id: 1, number: '42', balance: 10_000 }, { id: 2, user_id: 1, number: '43', balance: -273.15 }]) else expect(relation.to_a). to eql([{ id: 1, user_id: 1, number: '42', balance: 10_000.to_d }, { id: 2, user_id: 1, number: '43', balance: -273.15.to_d }]) end end end describe ROM::Plugins::Relation::SQL::AutoCombine, '#for_combine' do it 'preloads relation based on association' do |example| relation = accounts.for_combine(assoc).call(users.call) # TODO: this if caluse should be removed when (and if) https://github.com/xerial/sqlite-jdbc/issues/112 # will be resolved. See https://github.com/rom-rb/rom-sql/issues/49 for details if jruby? && sqlite?(example) expect(relation.to_a). to eql([{ id: 1, user_id: 1, number: '42', balance: 10_000 }, { id: 2, user_id: 1, number: '43', balance: -273.15 }]) else expect(relation.to_a). to eql([{ id: 1, user_id: 1, number: '42', balance: 10_000.to_d }, { id: 2, user_id: 1, number: '43', balance: -273.15.to_d }]) end end end end end <file_sep>require 'pathname' require 'rom/types' require 'rom/initializer' module ROM module SQL module Migration # @api private class Migrator extend Initializer DEFAULT_PATH = 'db/migrate'.freeze VERSION_FORMAT = '%Y%m%d%H%M%S'.freeze param :connection option :path, type: ROM::Types.Definition(Pathname), default: -> { DEFAULT_PATH } # @api private def run(options = {}) Sequel::Migrator.run(connection, path.to_s, options) end # @api private def pending? !Sequel::Migrator.is_current?(connection, path.to_s) end # @api private def migration(&block) Sequel.migration(&block) end # @api private def create_file(name, version = generate_version) filename = "#{version}_#{name}.rb" dirname = Pathname(path) fullpath = dirname.join(filename) FileUtils.mkdir_p(dirname) File.write(fullpath, migration_file_content) fullpath end # @api private def generate_version Time.now.utc.strftime(VERSION_FORMAT) end # @api private def migration_file_content File.read(Pathname(__FILE__).dirname.join('template.rb').realpath) end end end end end <file_sep>RSpec.describe ROM::Repository, '#transaction' do let(:user_repo) do Class.new(ROM::Repository[:users]) { commands :create }.new(rom) end let(:task_repo) do Class.new(ROM::Repository[:tasks]) { commands :create, :update }.new(rom) end include_context 'database' include_context 'relations' it 'creating user with tasks' do user, task = user_repo.transaction do user_changeset = user_repo.changeset(name: 'Jane') task_changeset = task_repo.changeset(title: 'Task One') user = user_repo.create(user_changeset) task = task_repo.create(task_changeset.associate(user, :user)) [user, task] end expect(user.name).to eql('Jane') expect(task.user_id).to be(user.id) expect(task.title).to eql('Task One') end it 'updating tasks user' do jane = user_repo.create(name: 'Jane') john = user_repo.create(name: 'John') task = task_repo.create(title: 'Jane Task', user_id: jane.id) task = task_repo.transaction do task_changeset = task_repo.changeset(task.id, title: 'John Task').associate(john, :user).commit task_repo.update(task_changeset) end expect(task.user_id).to be(john.id) expect(task.title).to eql('John Task') end end <file_sep>require 'dry/core/deprecations' require 'rom/initializer' require 'rom/repository/class_interface' require 'rom/repository/mapper_builder' require 'rom/repository/relation_proxy' require 'rom/repository/command_compiler' require 'rom/repository/changeset' require 'rom/repository/session' module ROM # Abstract repository class to inherit from # # A repository provides access to composable relations, commands and changesets. # Its job is to provide application-specific data that is already materialized, so that # relations don't leak into your application layer. # # Typically, you're going to work with Repository::Root that is configured to # use a single relation as its root, and compose aggregates and use changesets and commands # against the root relation. # # @example # rom = ROM.container(:sql, 'sqlite::memory') do |conf| # conf.default.create_table(:users) do # primary_key :id # column :name, String # end # # conf.default.create_table(:tasks) do # primary_key :id # column :user_id, Integer # column :title, String # end # # conf.relation(:users) do # associations do # has_many :tasks # end # end # end # # class UserRepo < ROM::Repository[:users] # relations :tasks # # def users_with_tasks # aggregate(:tasks).to_a # end # end # # user_repo = UserRepo.new(rom) # user_repo.users_with_tasks # # @see Repository::Root # # @api public class Repository # Mapping for supported changeset classes used in #changeset(type => relation) method CHANGESET_TYPES = { create: Changeset::Create, update: Changeset::Update, delete: Changeset::Delete }.freeze extend ClassInterface extend Initializer extend Dry::Core::ClassAttributes # @!method self.auto_struct # Get or set auto_struct setting # # When disabled, rom structs won't be created # # @overload auto_struct # Return auto_struct setting value # @return [TrueClass,FalseClass] # # @overload auto_struct(value) # Set auto_struct value # @return [Class] defines :auto_struct auto_struct true # @!method self.auto_struct # Get or set struct namespace defines :struct_namespace struct_namespace ROM::Struct # @!attribute [r] container # @return [ROM::Container] The container used to set up a repo param :container, allow: ROM::Container # @!attribute [r] struct_namespace # @return [Module,Class] The namespace for auto-generated structs option :struct_namespace, default: -> { self.class.struct_namespace } # @!attribute [r] auto_struct # @return [Boolean] The container used to set up a repo option :auto_struct, default: -> { self.class.auto_struct } # @!attribute [r] relations # @return [RelationRegistry] The relation proxy registry used by a repo attr_reader :relations # @!attribute [r] mappers # @return [MapperBuilder] The auto-generated mappers for repo relations attr_reader :mappers # @!attribute [r] commmand_compiler # @return [Method] Function for compiling commands bound to a repo instance attr_reader :command_compiler # Initializes a new repo by establishing configured relation proxies from # the passed container # # @param container [ROM::Container] The rom container with relations and optional commands # # @api public def initialize(container, opts = EMPTY_HASH) super @mappers = MapperBuilder.new(struct_namespace: struct_namespace) @relations = RelationRegistry.new do |registry, relations| self.class.relations.each do |name| relation = container.relations[name] relation = relation.with(mappers: container.mappers[name]) if container.mappers.key?(name) proxy = RelationProxy.new( relation, name: name, mappers: mappers, registry: registry, auto_struct: auto_struct ) instance_variable_set("@#{name}", proxy) relations[name] = proxy end end @command_compiler = method(:command) end # Return a command for a relation # # @overload command(type, relation) # Returns a command for a relation # # @example # repo.command(:create, repo.users) # # @param type [Symbol] The command type (:create, :update or :delete) # @param relation [RelationProxy] The relation for which command should be built for # # @overload command(options) # Builds a command for a given relation identifier # # @example # repo.command(create: :users) # # @param options [Hash<Symbol=>Symbol>] A type => rel_name map # # @overload command(rel_name) # Returns command registry for a given relation identifier # # @example # repo.command(:users)[:my_custom_command] # # @param rel_name [Symbol] The relation identifier from the container # # @return [CommandRegistry] # # @overload command(rel_name, &block) # Yields a command graph composer for a given relation identifier # # @param rel_name [Symbol] The relation identifier from the container # # @return [ROM::Command] # # @api public def command(*args, **opts, &block) all_args = args + opts.to_a.flatten if all_args.size > 1 commands.fetch_or_store(all_args.hash) do compile_command(*args, **opts) end else container.command(*args, &block) end end # Return a changeset for a relation # # @overload changeset(name, attributes) # Return a create changeset for a given relation identifier # # @example # repo.changeset(:users, name: "Jane") # # @param name [Symbol] The relation container identifier # @param attributes [Hash] # # @return [Changeset::Create] # # @overload changeset(name, primary_key, attributes) # Return an update changeset for a given relation identifier # # @example # repo.changeset(:users, 1, name: "<NAME>") # # @param name [Symbol] The relation container identifier # @param restriction_arg [Object] The argument passed to restricted view # # @return [Changeset::Update] # # @overload changeset(changeset_class) # Return a changeset object using provided class # # @example # repo.changeset(NewUserChangeset).data(attributes) # # @param [Class] changeset_class Custom changeset class # # @return [Changeset] # # @overload changeset(opts) # Return a changeset object using provided changeset type and relation # # @example # repo.changeset(delete: repo.users.where { id > 10 }) # # @param [Hash<Symbol=>Relation] opts Command type => Relation config # # @return [Changeset] # # @api public def changeset(*args) opts = { command_compiler: command_compiler } if args.size == 2 name, data = args elsif args.size == 3 name, pk, data = args elsif args.size == 1 if args[0].is_a?(Class) klass = args[0] if klass < Changeset return klass.new(relations[klass.relation], opts) else raise ArgumentError, "+#{klass.name}+ is not a Changeset subclass" end else type, relation = args[0].to_a[0] end else raise ArgumentError, 'Repository#changeset accepts 1-3 arguments' end if type klass = CHANGESET_TYPES.fetch(type) { raise ArgumentError, "+#{type.inspect}+ is not a valid changeset type. Must be one of: #{CHANGESET_TYPES.keys.inspect}" } klass.new(relation, opts) else relation = relations[name] if pk Changeset::Update.new(relation.by_pk(pk), opts.update(__data__: data)) else Changeset::Create.new(relation, opts.update(__data__: data)) end end end # Open a database transaction # # @example commited transaction # user = transaction do |t| # create(changeset(name: 'Jane')) # end # # user # # => #<ROM::Struct::User id=1 name="Jane"> # # @example with a rollback # user = transaction do |t| # changeset(name: 'Jane').commit # t.rollback! # end # # user # # nil # # @api public def transaction(&block) container.gateways[:default].transaction(&block) end # Return a string representation of a repository object # # @return [String] # # @api public def inspect %(#<#{self.class} relations=[#{self.class.relations.map(&:inspect).join(' ')}]>) end # Start a session for multiple changesets # # TODO: this is partly done, needs tweaks in changesets so that we can gather # command results and return them in a nice way # # @!visibility private # # @api public def session(&block) session = Session.new(self) yield(session) transaction { session.commit! } end private # Local command cache # # @api private def commands @__commands__ ||= Concurrent::Map.new end # Build a new command or return existing one # # @api private def compile_command(*args, mapper: nil, use: nil, **opts) type, name = args + opts.to_a.flatten(1) relation = name.is_a?(Symbol) ? relations[name] : name ast = relation.to_ast adapter = relations[relation.name].adapter if mapper mapper_instance = container.mappers[relation.name.relation][mapper] elsif mapper.nil? mapper_instance = mappers[ast] end command = CommandCompiler[container, type, adapter, ast, use, opts] if mapper_instance command >> mapper_instance else command.new(relation) end end # @api private def map_tuple(relation, tuple) relations[relation.name].mapper.([tuple]).first end end end require 'rom/repository/root' <file_sep>RSpec.describe 'Plugins / :auto_wrap' do with_adapters do include_context 'users and tasks' describe '#for_wrap' do shared_context 'joined tuple' do it 'returns joined tuples' do task_with_user = tasks .for_wrap({ id: :user_id }, name) .where { id.qualified.is(2) } .one expect(task_with_user).to eql( id: 2, user_id: 1, title: "Jane's task", users_name: "Jane", users_id: 1 ) end it 'works with by_pk' do task_with_user = tasks .for_wrap({ id: :user_id }, users.name.relation) .by_pk(1) .one expect(task_with_user). to eql(id: 1, user_id: 2, title: "Joe's task", users_name: "Joe", users_id: 2) end end context 'when parent relation is registered under dataset name' do before do conf.relation(:tasks) { schema(infer: true) } conf.relation(:users) { schema(infer: true) } end include_context 'joined tuple' do let(:name) { :users } end end context 'when parent relation is registered under a custom name' do before do conf.relation(:tasks) { schema(infer: true) } conf.relation(:authors) { schema(:users, infer: true) } end include_context 'joined tuple' do let(:users) { relations[:authors] } let(:name) { :authors} end end context 'using association with inferred relation name' do before do conf.relation(:tasks) do schema(infer: true) do associations do belongs_to :user end end end conf.relation(:users) do schema(infer: true) end end include_context 'joined tuple' do let(:name) { :user } end end context 'using association with an alias' do before do conf.relation(:tasks) do schema(infer: true) do associations do belongs_to :users, as: :assignee end end end conf.relation(:users) do schema(infer: true) end end include_context 'joined tuple' do let(:name) { :assignee } end end context 'using association with an aliased relation' do before do conf.relation(:tasks) do schema(infer: true) do associations do belongs_to :users, as: :assignee, relation: :people end end end conf.relation(:people) do schema(:users, infer: true) end end include_context 'joined tuple' do let(:users) { relations[:people] } let(:name) { :assignee } end end end end end <file_sep>require 'sequel/core' require 'dry/core/cache' require 'rom/schema/attribute' require 'rom/sql/projection_dsl' module ROM module SQL # Extended schema attributes tailored for SQL databases # # @api public class Attribute < ROM::Schema::Attribute OPERATORS = %i[>= <= > <].freeze NONSTANDARD_EQUALITY_VALUES = [true, false, nil].freeze # Error raised when an attribute cannot be qualified QualifyError = Class.new(StandardError) # Type-specific methods # # @api public module TypeExtensions class << self # Gets extensions for a type # # @param [Dry::Types::Type] type # # @return [Hash] # # @api public def [](wrapped) type = wrapped.default? ? wrapped.type : wrapped type = type.optional? ? type.right : type @types[type.meta[:database]][type.meta[:db_type]] || EMPTY_HASH end # Registers a set of operations supported for a specific type # # @example # ROM::SQL::Attribute::TypeExtensions.register(ROM::SQL::Types::PG::JSONB) do # def contain(type, expr, keys) # Attribute[Types::Bool].meta(sql_expr: expr.pg_jsonb.contains(value)) # end # end # # @param [Dry::Types::Type] type Type # # @api public def register(type, &block) extensions = @types[type.meta[:database]] db_type = type.meta[:db_type] raise ArgumentError, "Type #{ type } already registered" if @types.key?(type) mod = Module.new(&block) ctx = Object.new.extend(mod) functions = mod.public_instance_methods.each_with_object({}) { |m, ms| ms[m] = ctx.method(m) } extensions[db_type] = functions end end @types = ::Hash.new do |hash, database| hash[database] = {} end end extend Dry::Core::Cache # @api private def self.[](*args) fetch_or_store(args) { new(*args) } end option :extensions, type: Types::Hash, default: -> { TypeExtensions[type] } # Return a new attribute with an alias # # @example # users[:id].aliased(:user_id) # # @return [SQL::Attribute] # # @api public def aliased(name) super.meta(name: meta.fetch(:name, name), sql_expr: sql_expr.as(name)) end alias_method :as, :aliased # Return a new attribute in its canonical form # # @api public def canonical if aliased? meta(alias: nil, sql_expr: nil) else self end end # Return a new attribute marked as qualified # # @example # users[:id].aliased(:user_id) # # @return [SQL::Attribute] # # @api public def qualified return self if qualified? case sql_expr when Sequel::SQL::AliasedExpression, Sequel::SQL::Identifier type = meta(qualified: true) type.meta(sql_expr: type.to_sql_name) else raise QualifyError, "can't qualify #{name.inspect} (#{sql_expr.inspect})" end end # Return a new attribute marked as joined # # Whenever you join two schemas, the right schema's attribute # will be marked as joined using this method # # @return [SQL::Attribute] # # @api public def joined meta(joined: true) end # Return if an attribute was used in a join # # @example # schema = users.schema.join(tasks.schema) # # schema[:id, :tasks].joined? # # => true # # @return [Boolean] # # @api public def joined? meta[:joined].equal?(true) end # Return if an attribute type is qualified # # @example # id = users[:id].qualify # # id.qualified? # # => true # # @return [Boolean] # # @api public def qualified? meta[:qualified].equal?(true) end # Return a new attribute marked as a FK # # @return [SQL::Attribute] # # @api public def foreign_key meta(foreign_key: true) end # Return symbol representation of an attribute # # This uses convention from sequel where double underscore in the name # is used for qualifying, and triple underscore means aliasing # # @example # users[:id].qualified.to_sym # # => :users__id # # users[:id].as(:user_id).to_sym # # => :id___user_id # # users[:id].qualified.as(:user_id).to_sym # # => :users__id___user_id # # @return [Symbol] # # @api public def to_sym @_to_sym ||= if qualified? && aliased? :"#{source.dataset}__#{name}___#{meta[:alias]}" elsif qualified? :"#{source.dataset}__#{name}" elsif aliased? :"#{name}___#{meta[:alias]}" else name end end # Return a boolean expression with an equality operator # # @example # users.where { id.is(1) } # # users.where(users[:id].is(1)) # # @param [Object] other Any SQL-compatible object type # # @api public def is(other) self =~ other end # @api public def =~(other) meta(sql_expr: sql_expr =~ binary_operation_arg(other)) end # Return a boolean expression with a negated equality operator # # @example # users.where { id.not(1) } # # users.where(users[:id].not(1)) # # @param [Object] other Any SQL-compatible object type # # @api public def not(other) !is(other) end # Negate the attribute's sql expression # # @example # users.where(!users[:id].is(1)) # # @return [Attribute] # # @api public def ! ~self end # Return a boolean expression with an inclusion test # # If the single argument passed to the method is a Range object # then the resulting expression will restrict the attribute value # with range's bounds. Upper bound condition will be inclusive/non-inclusive # depending on the range type. # # If more than one argument is passed to the method or the first # argument is not Range then the result will be a simple IN check. # # @example # users.where { id.in(1..100) | created_at(((Time.now - 86400)..Time.now)) } # users.where { id.in(1, 2, 3) } # users.where(users[:id].in(1, 2, 3)) # # @param [Array<Object>] *args A range or a list of values for an inclusion check # # @api public def in(*args) if args.first.is_a?(Range) range = args.first lower_cond = __cmp__(:>=, range.begin) upper_cond = __cmp__(range.exclude_end? ? :< : :<=, range.end) Sequel::SQL::BooleanExpression.new(:AND, lower_cond, upper_cond) else __cmp__(:IN, args) end end # Create a function DSL from the attribute # # @example # users[:id].func { int::count(id).as(:count) } # # @return [SQL::Function] # # @api public def func(&block) ProjectionDSL.new(name => self).call(&block).first end # Create a CONCAT function from the attribute # # @example with default separator (' ') # users[:id].concat(users[:name]) # # @example with custom separator # users[:id].concat(users[:name], '-') # # @param [SQL::Attribute] other # # @return [SQL::Function] # # @api public def concat(other, sep = ' ') Function.new(type).concat(self, sep, other) end # Sequel calls this method to coerce an attribute into SQL string # # @param [Sequel::Dataset] # # @api private def sql_literal(ds) ds.literal(sql_expr) end # Sequel column representation # # @return [Sequel::SQL::AliasedExpression,Sequel::SQL::Identifier] # # @api private def to_sql_name @_to_sql_name ||= if qualified? && aliased? Sequel.qualify(source.dataset, name).as(meta[:alias]) elsif qualified? Sequel.qualify(source.dataset, name) elsif aliased? Sequel.as(name, meta[:alias]) else Sequel[name] end end private # Return Sequel Expression object for an attribute # # @api private def sql_expr @sql_expr ||= (meta[:sql_expr] || to_sql_name) end # Delegate to sql expression if it responds to a given method # # @api private def method_missing(meth, *args, &block) if OPERATORS.include?(meth) __cmp__(meth, args[0]) elsif extensions.key?(meth) extensions[meth].(type, sql_expr, *args, &block) elsif sql_expr.respond_to?(meth) meta(sql_expr: sql_expr.__send__(meth, *args, &block)) else super end end # A simple wrapper for the boolean expression constructor where # the left part is the attribute value # # @api private def __cmp__(op, other) Sequel::SQL::BooleanExpression.new(op, self, binary_operation_arg(other)) end # Preprocess input value for binary operations # # @api private def binary_operation_arg(value) case value when Sequel::SQL::Expression value else type[value] end end end end end <file_sep>require 'dry/core/class_attributes' require 'dry/equalizer' require 'dry/struct/errors' require 'dry/struct/constructor' module Dry class Struct # Class-level interface of {Struct} and {Value} module ClassInterface include Core::ClassAttributes include Dry::Types::Builder # @param [Class] klass def inherited(klass) super klass.equalizer Equalizer.new(*schema.keys) klass.send(:include, klass.equalizer) end # Adds an attribute for this {Struct} with given `name` and `type` # and modifies {.schema} accordingly. # # @param [Symbol] name name of the defined attribute # @param [Dry::Types::Definition] type # @return [Dry::Struct] # @raise [RepeatedAttributeError] when trying to define attribute with the # same name as previously defined one # # @example # class Language < Dry::Struct # attribute :name, Types::String # end # # Language.schema # #=> {name: #<Dry::Types::Definition primitive=String options={}>} # # ruby = Language.new(name: 'Ruby') # ruby.name #=> 'Ruby' def attribute(name, type) attributes(name => type) end # @param [Hash{Symbol => Dry::Types::Definition}] new_schema # @return [Dry::Struct] # @raise [RepeatedAttributeError] when trying to define attribute with the # same name as previously defined one # @see #attribute # @example # class Book1 < Dry::Struct # attributes( # title: Types::String, # author: Types::String # ) # end # # Book.schema # #=> {title: #<Dry::Types::Definition primitive=String options={}>, # # author: #<Dry::Types::Definition primitive=String options={}>} def attributes(new_schema) check_schema_duplication(new_schema) schema schema.merge(new_schema) input Types['coercible.hash'].public_send(constructor_type, schema) attr_reader(*new_schema.keys) equalizer.instance_variable_get('@keys').concat(new_schema.keys) self end # @param [Hash{Symbol => Dry::Types::Definition, Dry::Struct}] new_schema # @raise [RepeatedAttributeError] when trying to define attribute with the # same name as previously defined one def check_schema_duplication(new_schema) shared_keys = new_schema.keys & (schema.keys - superclass.schema.keys) raise RepeatedAttributeError, shared_keys.first if shared_keys.any? end private :check_schema_duplication # @param [Hash{Symbol => Object},Dry::Struct] attributes # @raise [Struct::Error] if the given attributes don't conform {#schema} # with given {#constructor_type} def new(attributes = default_attributes) if attributes.instance_of?(self) attributes else super(input[attributes]) end rescue Types::SchemaError, Types::MissingKeyError, Types::UnknownKeysError => error raise Struct::Error, "[#{self}.new] #{error}" end # Calls type constructor. The behavior is identical to `.new` but returns # the input back if it's a subclass of the struct. # # @param [Hash{Symbol => Object},Dry::Struct] attributes # @return [Dry::Struct] def call(attributes = default_attributes) return attributes if attributes.is_a?(self) new(attributes) end alias_method :[], :call # @param [#call,nil] constructor # @param [Hash] options # @param [#call,nil] block # @return [Dry::Struct::Constructor] def constructor(constructor = nil, **_options, &block) Struct::Constructor.new(self, fn: constructor || block) end # Retrieves default attributes from defined {.schema}. # Used in a {Struct} constructor if no attributes provided to {.new} # # @return [Hash{Symbol => Object}] def default_attributes check_invalid_schema_keys schema.each_with_object({}) { |(name, type), result| result[name] = type.evaluate if type.default? } end def check_invalid_schema_keys invalid_keys = schema.select { |name, type| type.instance_of?(String) } raise ArgumentError, argument_error_msg(invalid_keys.keys) if invalid_keys.any? end def argument_error_msg(keys) "Invaild argument for #{keys.join(', ')}" end # @param [Hash{Symbol => Object}] input # @yieldparam [Dry::Types::Result::Failure] failure # @yieldreturn [Dry::Types::ResultResult] # @return [Dry::Types::Result] def try(input) Types::Result::Success.new(self[input]) rescue Struct::Error => e failure = Types::Result::Failure.new(input, e.message) block_given? ? yield(failure) : failure end # @param [({Symbol => Object})] args # @return [Dry::Types::Result::Success] def success(*args) result(Types::Result::Success, *args) end # @param [({Symbol => Object})] args # @return [Dry::Types::Result::Failure] def failure(*args) result(Types::Result::Failure, *args) end # @param [Class] klass # @param [({Symbol => Object})] args def result(klass, *args) klass.new(*args) end # @return [false] def default? false end # @param [Object, Dry::Struct] value # @return [Boolean] def valid?(value) self === value end # @return [true] def constrained? true end # @return [self] def primitive self end # @return [false] def optional? false end # Checks if this {Struct} has the given attribute # # @param [Symbol] key Attribute name # @return [Boolean] def attribute?(key) schema.key?(key) end # Gets the list of attribute names # # @return [Array<Symbol>] def attribute_names schema.keys end end end end <file_sep># Hanami::Webconsole Hanami development web console. ## v0.1.0 - 2018-04-11 ## v0.1.0.rc2 - 2018-04-06 ## v0.1.0.rc1 - 2018-03-30 ## v0.1.0.beta2 - 2018-03-23 ## v0.1.0.beta1 - 2018-02-28 ### Added - [<NAME> & <NAME>] Package as Hanami plugin <file_sep>module Dry::Initializer class Option < Attribute # part of __initializer__ definition def initializer_signature "**__options__" end # parts of __initalizer__ def presetter "@#{target} = #{undefined}" if dispensable? && @undefined end def safe_setter "@#{target} = #{safe_coerced}#{maybe_optional}" end def fast_setter return safe_setter unless dispensable? "@#{target} = __options__.key?(:'#{source}')" \ " ? #{safe_coerced}" \ " : #{undefined}" end # part of __defaults__ def default_hash super :option end # part of __coercers__ def coercer_hash super :option end private def dispensable? optional && !default end def maybe_optional " if __options__.key? :'#{source}'" if dispensable? end def safe_coerced return safe_default unless coercer "__coercers__[:'option_#{source}'].call(#{safe_default})" end def safe_default "__options__.fetch(:'#{source}')#{default_part}" end def default_part if default " { instance_exec(&__defaults__[:'option_#{source}']) }" elsif !optional " { raise ArgumentError, \"option :'#{source}' is required\" }" end end end end <file_sep>module ROM module SQL VERSION = '1.3.5'.freeze end end <file_sep>module ROM module SQL class Association class OneToMany < Association result :many # @api public def call(relations, right = relations[target.relation]) schema = right.schema.qualified relation = right.inner_join(source_table, join_keys(relations)) if view apply_view(schema, relation) else schema.(relation) end end # @api public def combine_keys(relations) Hash[*with_keys(relations)] end # @api public def join_keys(relations) with_keys(relations) { |source_key, target_key| { qualify(source_alias, source_key) => qualify(target, target_key) } } end # @api private def associate(relations, child, parent) pk, fk = join_key_map(relations) child.merge(fk => parent.fetch(pk)) end protected # @api private def source_table self_ref? ? Sequel.as(source.dataset, source_alias) : source end # @api private def source_alias self_ref? ? :"#{source.dataset.to_s[0]}_0" : source end # @api private def with_keys(relations, &block) source_key = relations[source.relation].primary_key target_key = foreign_key || relations[target.relation].foreign_key(source.relation) return [source_key, target_key] unless block yield(source_key, target_key) end end end end end <file_sep>RSpec.describe ROM::Relation, '#exists' do include_context 'users and tasks' let(:tasks) { container.relations.tasks } let(:users) { container.relations.users } with_adapters do it 'returns true if subquery has at least one tuple' do subquery = tasks.where(tasks[:user_id].qualified => users[:id].qualified) expect(users.where { exists(subquery) }.count).to eql(2) end it 'returns false if subquery is empty' do subquery = tasks.where(false) expect(users.where { exists(subquery) }.count).to eql(0) end end end <file_sep>require 'rom/schema/attribute' module ROM module SQL # @api private class Function < ROM::Schema::Attribute def sql_literal(ds) if name ds.literal(func.as(name)) else ds.literal(func) end end def name meta[:alias] || super end def qualified meta( func: ::Sequel::SQL::Function.new(func.name, *func.args.map { |arg| arg.respond_to?(:qualified) ? arg.qualified : arg }) ) end def is(other) ::Sequel::SQL::BooleanExpression.new(:'=', func, other) end # Convert an expression result to another data type # # @example # users.select { bool::cast(json_data.get_text('activated'), :boolean).as(:activated) } # # @param [ROM::SQL::Attribute] expr Expression to be cast # @param [String] db_type Target database type # # @return [ROM::SQL::Attribute] # # @api private def cast(expr, db_type) Attribute[type].meta(sql_expr: ::Sequel.cast(expr, db_type)) end private def func meta[:func] end def method_missing(meth, *args) if func if func.respond_to?(meth) meta(func: func.__send__(meth, *args)) else super end else meta(func: Sequel::SQL::Function.new(meth.to_s.upcase, *args)) end end end end end <file_sep>module ROM class Repository # Class-level APIs for repositories # # @api public module ClassInterface # Create a root-repository class and set its root relation # # @example # # where :users is the relation name in your rom container # class UserRepo < ROM::Repository[:users] # end # # @param name [Symbol] The relation `register_as` value # # @return [Class] descendant of ROM::Repository::Root # # @api public def [](name) klass = Class.new(self < Repository::Root ? self : Repository::Root) klass.relations(name) klass.root(name) klass end # Inherits configured relations and commands # # @api private def inherited(klass) super return if self === Repository klass.relations(*relations) klass.commands(*commands) end # Define which relations your repository is going to use # # @example # class MyRepo < ROM::Repository # relations :users, :tasks # end # # my_repo = MyRepo.new(rom) # # my_repo.users # my_repo.tasks # # @return [Array<Symbol>] # # @api public def relations(*names) if names.empty? @relations ||= [] else attr_reader(*(names - relations)) @relations = relations | names end end # Defines command methods on a root repository # # @example # class UserRepo < ROM::Repository[:users] # commands :create, update: :by_pk, delete: :by_pk # end # # # with custom command plugin # class UserRepo < ROM::Repository[:users] # commands :create, plugin: :my_command_plugin # end # # # with custom mapper # class UserRepo < ROM::Repository[:users] # commands :create, mapper: :my_custom_mapper # end # # @param [Array<Symbol>] names A list of command names # @option :mapper [Symbol] An optional mapper identifier # @option :use [Symbol] An optional command plugin identifier # # @return [Array<Symbol>] A list of defined command names # # @api public def commands(*names, mapper: nil, use: nil, **opts) if names.any? || opts.any? @commands = names + opts.to_a @commands.each do |spec| type, *view = Array(spec).flatten if view.size > 0 define_restricted_command_method(type, view, mapper: mapper, use: use) else define_command_method(type, mapper: mapper, use: use) end end else @commands ||= [] end end private # @api private def define_command_method(type, **opts) define_method(type) do |*input| if input.size == 1 && input[0].respond_to?(:commit) changeset = input[0] map_tuple(changeset.relation, changeset.commit) else command(type => self.class.root, **opts).call(*input) end end end # @api private def define_restricted_command_method(type, views, **opts) views.each do |view_name| meth_name = views.size > 1 ? :"#{type}_#{view_name}" : type define_method(meth_name) do |*args| view_args, *input = args changeset = input.first if changeset.respond_to?(:commit) map_tuple(changeset.relation, changeset.commit) else command(type => self.class.root, **opts) .public_send(view_name, *view_args) .call(*input) end end end end end end end <file_sep>require "bundler/setup" Bundler::GemHelper.install_tasks require "rspec/core/rake_task" RSpec::Core::RakeTask.new :default namespace :benchmark do desc "Runs benchmarks without options" task :without_options do system "ruby benchmarks/without_options.rb" end desc "Runs benchmarks for several defaults" task :several_defaults do system "ruby benchmarks/several_defaults.rb" end desc "Runs benchmarks for defaults of params vs. options" task :params_vs_options do system "ruby benchmarks/params_vs_options.rb" end desc "Runs benchmarks with types" task :with_types do system "ruby benchmarks/with_types.rb" end desc "Runs benchmarks with defaults" task :with_defaults do system "ruby benchmarks/with_defaults.rb" end desc "Runs benchmarks with types and defaults" task :with_types_and_defaults do system "ruby benchmarks/with_types_and_defaults.rb" end desc "Runs benchmarks for plain params" task :params do system "ruby benchmarks/params.rb" end desc "Runs benchmarks various opts" task :options do system "ruby benchmarks/options.rb" end end desc "Runs profiler" task :profile do system "ruby benchmarks/profiler.rb && " \ "dot -Tpng ./tmp/profile.dot > ./tmp/profile.png" end <file_sep>[gem]: https://rubygems.org/gems/rom-mapper [travis]: https://travis-ci.org/rom-rb/rom-mapper [gemnasium]: https://gemnasium.com/rom-rb/rom-mapper [codeclimate]: https://codeclimate.com/github/rom-rb/rom-mapper [inchpages]: http://inch-ci.org/github/rom-rb/rom-mapper # rom-mapper [![Gem Version](https://badge.fury.io/rb/rom-mapper.svg)][gem] [![Build Status](https://travis-ci.org/rom-rb/rom-mapper.svg?branch=master)][travis] [![Dependency Status](https://gemnasium.com/rom-rb/rom-mapper.svg)][gemnasium] [![Code Climate](https://codeclimate.com/github/rom-rb/rom-mapper/badges/gpa.svg)][codeclimate] [![Test Coverage](https://codeclimate.com/github/rom-rb/rom-mapper/badges/coverage.svg)][codeclimate] [![Inline docs](http://inch-ci.org/github/rom-rb/rom-mapper.svg?branch=master)][inchpages] ROM mapper component is a DSL for defining object mappers with pluggable mapping backends. It is the default mapper in ROM. Resources: - [Guides](http://www.rubydoc.info/gems/rom-mapper/0.3.0/ROM/Mapper/AttributeDSL) - [Importing Data with ROM and Transproc](http://solnic.eu/2015/07/15/importing-data-with-rom-and-transproc.html) ## License See `LICENSE` file. <file_sep># -*- encoding: utf-8 -*- # stub: hanami 1.3.2 ruby lib Gem::Specification.new do |s| s.name = "hanami".freeze s.version = "1.3.2" s.required_rubygems_version = Gem::Requirement.new(">= 0".freeze) if s.respond_to? :required_rubygems_version= s.metadata = { "allowed_push_host" => "https://rubygems.org" } if s.respond_to? :metadata= s.require_paths = ["lib".freeze] s.authors = ["<NAME>".freeze] s.date = "2019-07-26" s.description = "Hanami is a web framework for Ruby".freeze s.email = ["<EMAIL>".freeze] s.executables = ["hanami".freeze] s.files = ["bin/hanami".freeze] s.homepage = "http://hanamirb.org".freeze s.licenses = ["MIT".freeze] s.required_ruby_version = Gem::Requirement.new(">= 2.3.0".freeze) s.rubygems_version = "3.0.3".freeze s.summary = "The web, with simplicity".freeze s.installed_by_version = "3.0.3" if s.respond_to? :installed_by_version if s.respond_to? :specification_version then s.specification_version = 4 if Gem::Version.new(Gem::VERSION) >= Gem::Version.new('1.2.0') then s.add_runtime_dependency(%q<hanami-utils>.freeze, ["~> 1.3"]) s.add_runtime_dependency(%q<hanami-validations>.freeze, [">= 1.3", "< 3"]) s.add_runtime_dependency(%q<hanami-router>.freeze, ["~> 1.3"]) s.add_runtime_dependency(%q<hanami-controller>.freeze, ["~> 1.3"]) s.add_runtime_dependency(%q<hanami-view>.freeze, ["~> 1.3"]) s.add_runtime_dependency(%q<hanami-helpers>.freeze, ["~> 1.3"]) s.add_runtime_dependency(%q<hanami-mailer>.freeze, ["~> 1.3"]) s.add_runtime_dependency(%q<hanami-assets>.freeze, ["~> 1.3"]) s.add_runtime_dependency(%q<hanami-cli>.freeze, ["~> 0.3"]) s.add_runtime_dependency(%q<concurrent-ruby>.freeze, ["~> 1.0"]) s.add_runtime_dependency(%q<bundler>.freeze, [">= 1.6", "< 3"]) s.add_development_dependency(%q<rspec>.freeze, ["~> 3.7"]) s.add_development_dependency(%q<rack-test>.freeze, ["~> 1.1"]) s.add_development_dependency(%q<aruba>.freeze, ["~> 0.14"]) s.add_development_dependency(%q<rake>.freeze, ["~> 12.0"]) else s.add_dependency(%q<hanami-utils>.freeze, ["~> 1.3"]) s.add_dependency(%q<hanami-validations>.freeze, [">= 1.3", "< 3"]) s.add_dependency(%q<hanami-router>.freeze, ["~> 1.3"]) s.add_dependency(%q<hanami-controller>.freeze, ["~> 1.3"]) s.add_dependency(%q<hanami-view>.freeze, ["~> 1.3"]) s.add_dependency(%q<hanami-helpers>.freeze, ["~> 1.3"]) s.add_dependency(%q<hanami-mailer>.freeze, ["~> 1.3"]) s.add_dependency(%q<hanami-assets>.freeze, ["~> 1.3"]) s.add_dependency(%q<hanami-cli>.freeze, ["~> 0.3"]) s.add_dependency(%q<concurrent-ruby>.freeze, ["~> 1.0"]) s.add_dependency(%q<bundler>.freeze, [">= 1.6", "< 3"]) s.add_dependency(%q<rspec>.freeze, ["~> 3.7"]) s.add_dependency(%q<rack-test>.freeze, ["~> 1.1"]) s.add_dependency(%q<aruba>.freeze, ["~> 0.14"]) s.add_dependency(%q<rake>.freeze, ["~> 12.0"]) end else s.add_dependency(%q<hanami-utils>.freeze, ["~> 1.3"]) s.add_dependency(%q<hanami-validations>.freeze, [">= 1.3", "< 3"]) s.add_dependency(%q<hanami-router>.freeze, ["~> 1.3"]) s.add_dependency(%q<hanami-controller>.freeze, ["~> 1.3"]) s.add_dependency(%q<hanami-view>.freeze, ["~> 1.3"]) s.add_dependency(%q<hanami-helpers>.freeze, ["~> 1.3"]) s.add_dependency(%q<hanami-mailer>.freeze, ["~> 1.3"]) s.add_dependency(%q<hanami-assets>.freeze, ["~> 1.3"]) s.add_dependency(%q<hanami-cli>.freeze, ["~> 0.3"]) s.add_dependency(%q<concurrent-ruby>.freeze, ["~> 1.0"]) s.add_dependency(%q<bundler>.freeze, [">= 1.6", "< 3"]) s.add_dependency(%q<rspec>.freeze, ["~> 3.7"]) s.add_dependency(%q<rack-test>.freeze, ["~> 1.1"]) s.add_dependency(%q<aruba>.freeze, ["~> 0.14"]) s.add_dependency(%q<rake>.freeze, ["~> 12.0"]) end end <file_sep>source 'https://rubygems.org' gemspec gem 'rom', git: 'https://github.com/rom-rb/rom.git', branch: 'release-3.0' group :test do gem 'pry-byebug', platforms: :mri gem 'pry', platforms: %i(jruby rbx) gem 'dry-struct' gem 'activesupport', '~> 5.0' gem 'codeclimate-test-reporter', require: false gem 'simplecov', require: false if RUBY_ENGINE == 'rbx' gem 'pg', '~> 0.18.0', platforms: :rbx else gem 'pg', '~> 0.19', platforms: :mri end gem 'mysql2', platforms: [:mri, :rbx] gem 'jdbc-postgres', platforms: :jruby gem 'jdbc-mysql', platforms: :jruby gem 'sqlite3', platforms: [:mri, :rbx] gem 'jdbc-sqlite3', platforms: :jruby gem 'ruby-oci8', platforms: :mri if ENV['ROM_USE_ORACLE'] end group :tools do gem 'rom-repository', git: 'https://github.com/rom-rb/rom-repository.git', branch: 'master' end <file_sep>require 'dry/core/deprecations' require 'rom/initializer' require 'rom/relation/materializable' require 'rom/repository/relation_proxy/combine' require 'rom/repository/relation_proxy/wrap' module ROM class Repository # RelationProxy decorates a relation and automatically generates mappers that # will map raw tuples into rom structs # # Relation proxies are being registered within repositories so typically there's # no need to instantiate them manually. # # @api public class RelationProxy extend Initializer extend Dry::Core::Deprecations[:rom] include Relation::Materializable (Kernel.private_instance_methods - %i(raise)).each(&method(:undef_method)) include RelationProxy::Combine include RelationProxy::Wrap deprecate :combine_parents deprecate :combine_children deprecate :wrap_parent RelationRegistryType = Types.Definition(RelationRegistry).constrained(type: RelationRegistry) # @!attribute [r] relation # @return [Relation, Relation::Composite, Relation::Graph, Relation::Curried] The decorated relation object param :relation option :name, type: Types::Strict::Symbol option :mappers, default: -> { MapperBuilder.new } option :meta, default: -> { EMPTY_HASH } option :registry, type: RelationRegistryType, default: -> { RelationRegistry.new } option :auto_struct, default: -> { true } # Relation name # # @return [ROM::Relation::Name] # # @api public def name @name ? relation.name.with(@name) : relation.name end # Materializes wrapped relation and sends it through a mapper # # For performance reasons a combined relation will skip mapping since # we only care about extracting key values for combining # # @api public def call(*args) ((combine? || composite?) ? relation : (relation >> mapper)).call(*args) end # Maps the wrapped relation with other mappers available in the registry # # @overload map_with(model) # Map tuples to the provided custom model class # # @example # users.as(MyUserModel) # # @param [Class>] model Your custom model class # # @overload map_with(*mappers) # Map tuples using registered mappers # # @example # users.map_with(:my_mapper, :my_other_mapper) # # @param [Array<Symbol>] mappers A list of mapper identifiers # # @overload map_with(*mappers, auto_map: true) # Map tuples using auto-mapping and custom registered mappers # # If `auto_map` is enabled, your mappers will be applied after performing # default auto-mapping. This means that you can compose complex relations # and have them auto-mapped, and use much simpler custom mappers to adjust # resulting data according to your requirements. # # @example # users.map_with(:my_mapper, :my_other_mapper, auto_map: true) # # @param [Array<Symbol>] mappers A list of mapper identifiers # # @return [RelationProxy] A new relation proxy with pipelined relation # # @api public def map_with(*names, **opts) if names.size == 1 && names[0].is_a?(Class) map_to(names[0]) elsif names.size > 1 && names.any? { |name| name.is_a?(Class) } raise ArgumentError, 'using custom mappers and a model is not supported' else if opts[:auto_map] && !meta[:combine_type] mappers = [mapper, *names.map { |name| relation.mappers[name] }] mappers.reduce(self) { |a, e| a >> e } else names.reduce(self) { |a, e| a >> relation.mappers[e] } end end end # @api public def as(*names, **opts) if names.size == 1 && names[0].is_a?(Class) msg = <<-STR Relation#as will change behavior in 4.0. Use `map_to` instead => Called at: #{Kernel.caller[0..5].join("\n")} STR Dry::Core::Deprecations.warn(msg) map_to(names[0]) elsif names.size > 1 && names.any? { |name| name.is_a?(Class) } raise ArgumentError, 'using custom mappers and a model is not supported' else if opts[:auto_map] && !meta[:combine_type] mappers = [mapper, *names.map { |name| relation.mappers[name] }] mappers.reduce(self) { |a, e| a >> e } else names.reduce(self) { |a, e| a >> relation.mappers[e] } end end end # @api public def map_to(model) with(meta: meta.merge(model: model)) end # Return a new graph with adjusted node returned from a block # # @example with a node identifier # aggregate(:tasks).node(:tasks) { |tasks| tasks.prioritized } # # @example with a nested path # aggregate(tasks: :tags).node(tasks: :tags) { |tags| tags.where(name: 'red') } # # @param [Symbol] name The node relation name # # @yieldparam [RelationProxy] The relation node # @yieldreturn [RelationProxy] The new relation node # # @return [RelationProxy] # # @api public def node(name, &block) if name.is_a?(Symbol) && !nodes.map { |n| n.name.relation }.include?(name) raise ArgumentError, "#{name.inspect} is not a valid aggregate node name" end new_nodes = nodes.map { |node| case name when Symbol name == node.name.relation ? yield(node) : node when Hash other, *rest = name.flatten(1) if other == node.name.relation nodes.detect { |n| n.name.relation == other }.node(*rest, &block) else node end else node end } with_nodes(new_nodes) end # Return a string representation of this relation proxy # # @return [String] # # @api public def inspect %(#<#{relation.class} name=#{name} dataset=#{dataset.inspect}>) end # Infers a mapper for the wrapped relation # # @return [ROM::Mapper] # # @api private def mapper mappers[to_ast] end # Returns a new instance with new options # # @param new_options [Hash] # # @return [RelationProxy] # # @api private def with(new_options) __new__(relation, options.merge(new_options)) end # Returns if this relation is combined aka a relation graph # # @return [Boolean] # # @api private def combine? meta[:combine_type] end # Return if this relation is a composite # # @return [Boolean] # # @api private def composite? relation.is_a?(Relation::Composite) end # @return [Symbol] The wrapped relation's adapter identifier ie :sql or :http # # @api private def adapter relation.class.adapter end # Returns AST for the wrapped relation # # @return [Array] # # @api private def to_ast @to_ast ||= begin attr_ast = schema.map { |attr| [:attribute, attr] } meta = self.meta.merge(dataset: base_name.dataset) meta.update(model: false) unless meta[:model] || auto_struct meta.delete(:wraps) header = attr_ast + nodes_ast + wraps_ast [:relation, [base_name.relation, meta, [:header, header]]] end end # @api private def respond_to_missing?(meth, _include_private = false) relation.respond_to?(meth) || super end private # @api private def schema if meta[:wrap] relation.schema.wrap else relation.schema.reject(&:wrapped?) end end # @api private def base_name relation.base_name end # @api private def nodes_ast @nodes_ast ||= nodes.map(&:to_ast) end # @api private def wraps_ast @wraps_ast ||= wraps.map(&:to_ast) end # Return a new instance with another relation and options # # @return [RelationProxy] # # @api private def __new__(relation, new_options = EMPTY_HASH) self.class.new( relation, new_options.size > 0 ? options.merge(new_options) : options ) end # Return all nodes that this relation combines # # @return [Array<RelationProxy>] # # @api private def nodes relation.graph? ? relation.nodes : EMPTY_ARRAY end # Return all nodes that this relation wraps # # @return [Array<RelationProxy>] # # @api private def wraps meta.fetch(:wraps, EMPTY_ARRAY) end # Forward to relation and wrap it with proxy if response was a relation too # # TODO: this will be simplified once ROM::Relation has lazy-features built-in # and ROM::Lazy is gone # # @api private def method_missing(meth, *args, &block) if relation.respond_to?(meth) result = relation.__send__(meth, *args, &block) if result.kind_of?(Relation::Materializable) && !result.is_a?(Relation::Loaded) __new__(result) else result end else raise NoMethodError, "undefined method `#{meth}' for #{relation.class.name}" end end end end end <file_sep>require 'rom/sql/schema/inferrer' module ROM module SQL class Schema class SqliteInferrer < Inferrer[:sqlite] NO_TYPE = EMPTY_STRING def map_type(_, db_type, **_kw) if db_type.eql?(NO_TYPE) ROM::SQL::Types::SQLite::Object else super end end end end end end <file_sep>require 'dry/core/cache' module ROM module SQL # Used as a pair table name + field name. # Similar to Sequel::SQL::QualifiedIdentifier but we don't want # Sequel types to leak into ROM # # @api private class QualifiedAttribute include Dry::Equalizer(:dataset, :attribute) extend Dry::Core::Cache # Dataset (table) name # # @api private attr_reader :dataset # Attribute (field, column) name # # @api private attr_reader :attribute # @api private def self.[](*args) fetch_or_store(args) { new(*args) } end # @api private def initialize(dataset, attribute) @dataset = dataset @attribute = attribute end # Used by Sequel for building SQL statements # # @api private def sql_literal_append(ds, sql) ds.qualified_identifier_sql_append(sql, dataset, attribute) end # Convinient interface for attribute names # # @return [Symbol] # # @api private def to_sym attribute end end end end <file_sep>require 'set' module ROM module SQL module Plugin # Make a command that automatically fills in timestamp attributes on # input tuples # # @api private module Timestamps # @api private def self.included(klass) klass.extend(ClassInterface) super end module ClassInterface # @api private def self.extended(klass) klass.defines :timestamp_columns, :datestamp_columns klass.timestamp_columns Set.new klass.datestamp_columns Set.new super end # Set up attributes to timestamp when the command is called # # @example # class CreateTask < ROM::Commands::Create[:sql] # result :one # use :timestamps # timestamps :created_at, :updated_at # end # # create_user = rom.command(:user).create.with(name: 'Jane') # # result = create_user.call # result[:created_at] #=> Time.now.utc # # @param [Symbol] name of the attribute to set # # @api public def timestamps(*args) timestamp_columns timestamp_columns.merge(args) include InstanceMethods end alias timestamp timestamps # Set up attributes to datestamp when the command is called # # @example # class CreateTask < ROM::Commands::Create[:sql] # result :one # use :timestamps # datestamps :created_on, :updated_on # end # # create_user = rom.command(:user).create.with(name: 'Jane') # # result = create_user.call # result[:created_at] #=> Date.today # # @param [Symbol] name of the attribute to set # # @api public def datestamps(*args) datestamp_columns datestamp_columns.merge(args) include InstanceMethods end alias datestamp datestamps end module InstanceMethods # @api private def self.included(base) base.before :set_timestamps end # @api private def timestamp_columns self.class.timestamp_columns end # @api private def datestamp_columns self.class.datestamp_columns end # Set the timestamp attributes on the given tuples # # @param [Array<Hash>, Hash] tuples the input tuple(s) # # @return [Array<Hash>, Hash] # # @api private def set_timestamps(tuples, *) timestamps = build_timestamps case tuples when Hash timestamps.merge(tuples) when Array tuples.map { |t| timestamps.merge(t) } end end private # @api private def build_timestamps time = Time.now.utc date = Date.today timestamps = {} timestamp_columns.each do |column| timestamps[column.to_sym] = time end datestamp_columns.each do |column| timestamps[column.to_sym] = date end timestamps end end end end end end <file_sep>require 'rom/types' module ROM module SQL module Types include ROM::Types def self.Constructor(*args, &block) ROM::Types.Constructor(*args, &block) end def self.Definition(*args, &block) ROM::Types.Definition(*args, &block) end Serial = Int.meta(primary_key: true) Blob = Constructor(Sequel::SQL::Blob, &Sequel::SQL::Blob.method(:new)) Void = Nil end end end <file_sep>require 'dry/core/constants' require 'dry/core/class_attributes' require 'rom/types' require 'rom/initializer' require 'rom/sql/qualified_attribute' require 'rom/sql/association/name' module ROM module SQL # Abstract association class # # @api public class Association include Dry::Core::Constants include Dry::Equalizer(:source, :target, :result) extend Initializer extend Dry::Core::ClassAttributes defines :result # @!attribute [r] source # @return [ROM::Relation::Name] the source relation name param :source # @!attribute [r] target # @return [ROM::Relation::Name] the target relation name param :target # @!attribute [r] relation # @return [Symbol] an optional relation identifier for the target option :relation, Types::Strict::Symbol, optional: true # @!attribute [r] result # @return [Symbol] either :one or :many option :result, Types::Strict::Symbol, default: -> { self.class.result } # @!attribute [r] as # @return [Symbol] an optional association alias name option :as, Types::Strict::Symbol, default: -> { target.to_sym } # @!attribute [r] foreign_key # @return [Symbol] an optional association alias name option :foreign_key, Types::Optional::Strict::Symbol, optional: true # @!attribute [r] view # @return [Symbol] An optional view that should be used to extend assoc relation option :view, optional: true alias_method :name, :as # @api public def self.new(source, target, options = EMPTY_HASH) super( Name[source], Name[options[:relation] || target, target, options[:as] || target], options ) end # @api public def join(relations, type, source = relations[self.source], target = relations[self.target]) source.__send__(type, target.name.dataset, join_keys(relations)).qualified end # Returns a qualified attribute name for a given dataset # # This is compatible with Sequel's SQL generator and can be used in query # DSL methods # # @param name [ROM::Relation::Name] # @param attribute [Symbol] # # @return [QualifiedAttribute] # # @api public def qualify(name, attribute) QualifiedAttribute[name.to_sym, attribute] end # @api protected def apply_view(schema, relation) view_rel = relation.public_send(view) schema.merge(view_rel.schema.qualified).uniq(&:to_sql_name).(view_rel) end # @api private def join_key_map(relations) join_keys(relations).to_a.flatten.map(&:to_sym) end def self_ref? source.dataset == target.dataset end end end end require 'rom/sql/association/one_to_many' require 'rom/sql/association/one_to_one' require 'rom/sql/association/many_to_many' require 'rom/sql/association/many_to_one' require 'rom/sql/association/one_to_one_through' <file_sep>RSpec.describe 'Plugins / :auto_restrictions', seeds: true do include_context 'users and tasks' with_adapters do before do conn.add_index :tasks, :title, unique: true end shared_context 'auto-generated restriction view' do it 'defines restriction views for all indexed attributes' do expect(tasks.select(:id).by_title("Jane's task").one).to eql(id: 2) end it 'defines curried methods' do expect(tasks.by_title.("Jane's task").first).to eql(id: 2, user_id: 1, title: "Jane's task") end end context 'with an inferred schema' do before do conf.plugin(:sql, relations: :auto_restrictions) end include_context 'auto-generated restriction view' end context 'with explicit schema' do before do conf.relation(:tasks) do schema do attribute :id, ROM::SQL::Types::Serial attribute :user_id, ROM::SQL::Types::Int attribute :title, ROM::SQL::Types::String.meta(index: true) end use :auto_restrictions end end include_context 'auto-generated restriction view' end it 'raises error when enabled w/o a schema' do expect { conf.relation(:tasks) do use :auto_restrictions end }.to raise_error( ROM::Plugins::Relation::SQL::AutoRestrictions::EmptySchemaError, "ROM::Relation[Tasks] relation has no schema. Make sure :auto_restrictions is enabled after defining a schema" ) end end end <file_sep>require 'dry/core/inflector' module ROM class Repository class RelationProxy # Provides convenient methods for composing relations # # @api public module Combine # Returns a combine representation of a loading-proxy relation # # This will carry meta info used to produce a correct AST from a relation # so that correct mapper can be generated # # @return [RelationProxy] # # @api private def combined(name, keys, type) meta = { keys: keys, combine_type: type, combine_name: name } with(name: name, meta: self.meta.merge(meta)) end # Combine with other relations # # @overload combine(*associations) # Composes relations using configured associations # @example # users.combine(:tasks, :posts) # @param *associations [Array<Symbol>] A list of association names # # @overload combine(options) # Composes relations based on options # # @example # # users have-many tasks (name and join-keys inferred, which needs associations in schema) # users.combine(many: tasks) # # # users have-many tasks with custom name (join-keys inferred, which needs associations in schema) # users.combine(many: { priority_tasks: tasks.priority }) # # # users have-many tasks with custom view and join keys # users.combine(many: { tasks: [tasks.for_users, id: :task_id] }) # # # users has-one task # users.combine(one: { task: tasks }) # # @param options [Hash] Options for combine # @option :many [Hash] Sets options for "has-many" type of association # @option :one [Hash] Sets options for "has-one/belongs-to" type of association # # @return [RelationProxy] # # @api public def combine(*args) options = args[0].is_a?(Hash) ? args[0] : args combine_opts = Hash.new { |h, k| h[k] = {} } options.each do |key, value| if key == :one || key == :many if value.is_a?(Hash) value.each do |name, spec| if spec.is_a?(Array) combine_opts[key][name] = spec else _, (curried, keys) = combine_opts_from_relations(spec).to_a[0] combine_opts[key][name] = [curried, keys] end end else _, (curried, keys) = combine_opts_from_relations(value).to_a[0] combine_opts[key][curried.combine_tuple_key(key)] = [curried, keys] end else if value.is_a?(Array) other = if registry.key?(key) registry[key] else registry[associations[key].target] end curried = combine_from_assoc(key, other).combine(*value) result, _, keys = combine_opts_for_assoc(key) combine_opts[result][key] = [curried, keys] else result, curried, keys = combine_opts_for_assoc(key, value) combine_opts[result][key] = [curried, keys] end end end nodes = combine_opts.flat_map do |type, relations| relations.map { |name, (relation, keys)| relation.combined(name, keys, type) } end __new__(relation.graph(*nodes)) end # Shortcut for combining with parents which infers the join keys # # @example # # tasks belong-to users # tasks.combine_parents(one: users) # # # tasks belong-to users with custom user view # tasks.combine_parents(one: users.task_owners) # # @param options [Hash] Combine options hash # # @return [RelationProxy] # # @api public def combine_parents(options) combine_opts = {} options.each do |type, parents| combine_opts[type] = case parents when Hash parents.each_with_object({}) { |(name, parent), r| keys = combine_keys(parent, relation, :parent) curried = combine_from_assoc_with_fallback(name, parent, keys) r[name] = [curried, keys] } when Array parents.each_with_object({}) { |parent, r| keys = combine_keys(parent, relation, :parent) tuple_key = parent.combine_tuple_key(type) curried = combine_from_assoc_with_fallback(parent.name, parent, keys) r[tuple_key] = [curried, keys] } else keys = combine_keys(parents, relation, :parent) tuple_key = parents.combine_tuple_key(type) curried = combine_from_assoc_with_fallback(parents.name, parents, keys) { tuple_key => [curried, keys] } end end combine(combine_opts) end # Shortcut for combining with children which infers the join keys # # @example # # users have-many tasks # users.combine_children(many: tasks) # # # users have-many tasks with custom mapping (requires associations) # users.combine_children(many: { priority_tasks: tasks.priority }) # # @param [Hash] options # # @return [RelationProxy] # # @api public def combine_children(options) combine_opts = {} options.each do |type, children| combine_opts[type] = case children when Hash children.each_with_object({}) { |(name, child), r| keys = combine_keys(relation, child, :children) curried = combine_from_assoc_with_fallback(name, child, keys) r[name] = [curried, keys] } when Array children.each_with_object({}) { |child, r| keys = combine_keys(relation, child, :children) tuple_key = child.combine_tuple_key(type) curried = combine_from_assoc_with_fallback(child.name, child, keys) r[tuple_key] = [curried, keys] } else keys = combine_keys(relation, children, :children) curried = combine_from_assoc_with_fallback(children.name, children, keys) tuple_key = children.combine_tuple_key(type) { tuple_key => [curried, keys] } end end combine(combine_opts) end protected # Infer join/combine keys for a given relation and association type # # When source has association corresponding to target's name, it'll be # used to get the keys. Otherwise we fall back to using default keys based # on naming conventions. # # @param [Relation::Name] source The source relation name # @param [Relation::Name] target The target relation name # @param [Symbol] type The association type, can be either :parent or :children # # @return [Hash<Symbol=>Symbol>] # # @api private def combine_keys(source, target, type) source.associations.try(target.name) { |assoc| assoc.combine_keys(__registry__) } or infer_combine_keys(source, target, type) end # Build combine options from a relation mapping hash passed to `combine` # # This method will infer combine keys either from defined associations # or use the keys provided explicitly for ad-hoc combines # # It returns a mapping like `name => [preloadable_relation, combine_keys]` # and this mapping is used by `combine` to build a full relation graph # # @api private def combine_opts_from_relations(*relations) relations.each_with_object({}) do |spec, h| # We assume it's a child relation keys = combine_keys(relation, spec, :children) rel = combine_from_assoc_with_fallback(spec.name, spec, keys) h[spec.name.relation] = [rel, keys] end end # @api private def combine_from_assoc_with_fallback(name, other, keys) combine_from_assoc(name, other) do other.combine_method(relation, keys) end end # Try to get a preloadable relation from a defined association # # If association doesn't exist we call the fallback block # # @return [RelationProxy] # # @api private def combine_from_assoc(name, other, &fallback) return other if other.curried? associations.try(name) { |assoc| other.for_combine(assoc) } or fallback.call end # Extract result (either :one or :many), preloadable relation and its keys # by using given association name # # This is used when a flat list of association names was passed to `combine` # # @api private def combine_opts_for_assoc(name, opts = nil) assoc = relation.associations[name] curried = registry[assoc.target.relation].for_combine(assoc) curried = curried.combine(opts) unless opts.nil? keys = assoc.combine_keys(__registry__) [assoc.result, curried, keys] end # Build a preloadable relation for relation graph # # When a given relation defines `for_other_relation` then it will be used # to preload `other_relation`. ie `users` relation defines `for_tasks` # then when we preload tasks for users, this custom method will be used # # This *defaults* to the built-in `for_combine` with explicitly provided # keys # # @return [RelationProxy] # # @api private def combine_method(other, keys) custom_name = :"for_#{other.name.dataset}" if relation.respond_to?(custom_name) __send__(custom_name) else for_combine(keys) end end # Infer key under which a combine relation will be loaded # # This is used in cases like ad-hoc combines where relation was passed # in without specifying the key explicitly, ie: # # tasks.combine_parents(one: users) # # # ^^^ this will be expanded under-the-hood to: # tasks.combine(one: { user: users }) # # @return [Symbol] # # @api private def combine_tuple_key(result) if result == :one Dry::Core::Inflector.singularize(base_name.relation).to_sym else base_name.relation end end # Fallback mechanism for `combine_keys` when there's no association defined # # @api private def infer_combine_keys(source, target, type) primary_key = source.primary_key foreign_key = target.foreign_key(source) if type == :parent { foreign_key => primary_key } else { primary_key => foreign_key } end end end end end end <file_sep>module MapperRegistry def mapper_for(relation) mapper_builder[relation.to_ast] end def mapper_builder @mapper_builder ||= ROM::Repository::MapperBuilder.new end end <file_sep>require "dry-initializer" require "ruby-prof" require "fileutils" class User extend Dry::Initializer param :first_name, proc(&:to_s), default: proc { "Unknown" } param :second_name, proc(&:to_s), default: proc { "Unknown" } option :email, proc(&:to_s), optional: true option :phone, proc(&:to_s), optional: true end result = RubyProf.profile do 1_000.times { User.new :Andy, email: :"<EMAIL>" } end FileUtils.mkdir_p "./tmp" FileUtils.touch "./tmp/profile.dot" File.open("./tmp/profile.dot", "w+") do |output| RubyProf::DotPrinter.new(result).print(output, min_percent: 0) end FileUtils.touch "./tmp/profile.html" File.open("./tmp/profile.html", "w+") do |output| RubyProf::CallStackPrinter.new(result).print(output, min_percent: 0) end <file_sep>RSpec.describe 'struct builder', '#call' do subject(:builder) { ROM::Repository::StructBuilder.new } def attr_double(name, type, **opts) double( name: name, aliased?: false, wrapped?: false, foreign_key?: false, to_read_type: ROM::Types.const_get(type), **opts ) end let(:input) do [:users, [:header, [ [:attribute, attr_double(:id, :Int)], [:attribute, attr_double(:name, :String)]]]] end context 'ROM::Struct' do before { builder[*input] } it 'generates a struct for a given relation name and columns' do struct = builder.class.cache[input.hash] user = struct.new(id: 1, name: 'Jane') expect(user.id).to be(1) expect(user.name).to eql('Jane') expect(user[:id]).to be(1) expect(user[:name]).to eql('Jane') expect(Hash[user]).to eql(id: 1, name: 'Jane') expect(user.inspect).to eql('#<ROM::Struct::User id=1 name="Jane">') expect(user.to_s).to match(/\A#<ROM::Struct::User:0x[0-9a-f]+>\z/) end it 'stores struct in the cache' do expect(builder.class.cache[input.hash]).to be(builder[*input]) end context 'with reserved keywords as attribute names' do let(:input) do [:users, [:header, [ [:attribute, attr_double(:id, :Int)], [:attribute, attr_double(:name, :String)], [:attribute, attr_double(:alias, :String)], [:attribute, attr_double(:until, :Time)]]]] end it 'allows to build a struct class without complaining' do struct = builder.class.cache[input.hash] user = struct.new(id: 1, name: 'Jane', alias: 'JD', until: Time.new(2030)) expect(user.id).to be(1) expect(user.name).to eql('Jane') expect(user.alias).to eql('JD') expect(user.until).to eql(Time.new(2030)) end end it 'raise a friendly error on missing keys' do struct = builder.class.cache[input.hash] expect { struct.new(id: 1) }.to raise_error( Dry::Struct::Error, /:name is missing/ ) end end context 'custom entity container' do before do module Test module Custom end end end let(:struct) { builder[*input] } subject(:builder) { ROM::Repository::StructBuilder.new(Test::Custom) } it 'generates a struct class inside a given module' do expect(struct.name).to eql('Test::Custom::User') user = struct.new(id: 1, name: 'Jane') expect(user.inspect).to eql(%q{#<Test::Custom::User id=1 name="Jane">}) end it 'uses the existing class as a parent' do class Test::Custom::User < ROM::Struct def upcased_name name.upcase end end user = struct.new(id: 1, name: 'Jane') expect(user.upcased_name).to eql('JANE') end it 'raises a nice error on missing attributes' do class Test::Custom::User < ROM::Struct def upcased_middle_name middle_name.upcase end end user = struct.new(id: 1, name: 'Jane') expect { user.upcased_middle_name }.to raise_error( ROM::Struct::MissingAttribute, /not loaded attribute\?/ ) end it 'works with implicit coercions' do user = struct.new(id: 1, name: 'Jane') expect([user].flatten).to eql([user]) end end end <file_sep>module Dry::Initializer class DefaultValueError < TypeError def initialize(name, value) super "Cannot set #{value.inspect} directly as a default value" \ " of the argument '#{name}'. Wrap it to either proc or lambda." end end end <file_sep>RSpec.describe 'Inferring schema from database' do include_context 'users' include_context 'posts' with_adapters do context "when database schema exists" do it "infers the schema from the database relations" do conf.relation(:users) expect(container.relations.users.to_a) .to eql(container.gateways[:default][:users].to_a) end end context "for empty database schemas" do it "returns an empty schema" do expect { container.users }.to raise_error(NoMethodError) end end context 'defining associations', seeds: false do it "allows defining a one-to-many" do class Test::Posts < ROM::Relation[:sql] schema(:posts) do associations do one_to_many :tags end end end assoc = ROM::SQL::Association::OneToMany.new(:posts, :tags) expect(Test::Posts.associations[:tags]).to eql(assoc) end it "allows defining a one-to-many using has_many shortcut" do class Test::Posts < ROM::Relation[:sql] schema(:posts) do associations do has_many :tags end end end assoc = ROM::SQL::Association::OneToMany.new(:posts, :tags) expect(Test::Posts.associations[:tags]).to eql(assoc) end it "allows defining a one-to-one" do class Test::Users < ROM::Relation[:sql] schema(:users) do associations do one_to_one :accounts end end end assoc = ROM::SQL::Association::OneToOne.new(:users, :accounts) expect(Test::Users.associations[:accounts]).to eql(assoc) end it "allows defining a one-to-one using has_one shortcut" do class Test::Users < ROM::Relation[:sql] schema(:users) do associations do has_one :account end end end assoc = ROM::SQL::Association::OneToOne.new(:users, :accounts, as: :account) expect(Test::Users.associations[:account]).to eql(assoc) expect(Test::Users.associations[:account].target).to be_aliased end it "allows defining a one-to-one using has_one shortcut with an alias" do class Test::Users < ROM::Relation[:sql] schema(:users) do associations do has_one :account, as: :user_account end end end assoc = ROM::SQL::Association::OneToOne.new(:users, :accounts, as: :user_account) expect(Test::Users.associations[:user_account]).to eql(assoc) expect(Test::Users.associations[:user_account].target).to be_aliased end it "allows defining a one-to-one-through" do class Test::Users < ROM::Relation[:sql] schema(:users) do associations do one_to_one :cards, through: :accounts end end end assoc = ROM::SQL::Association::OneToOneThrough.new(:users, :cards, through: :accounts) expect(Test::Users.associations[:cards]).to eql(assoc) end it "allows defining a many-to-one" do class Test::Tags < ROM::Relation[:sql] schema(:tags) do associations do many_to_one :posts end end end assoc = ROM::SQL::Association::ManyToOne.new(:tags, :posts) expect(Test::Tags.associations[:posts]).to eql(assoc) end it "allows defining a many-to-one using belongs_to shortcut" do class Test::Tags < ROM::Relation[:sql] schema(:tags) do associations do belongs_to :post end end end assoc = ROM::SQL::Association::ManyToOne.new(:tags, :posts, as: :post) expect(Test::Tags.associations[:post]).to eql(assoc) end it "allows defining a many-to-one using belongs_to shortcut" do class Test::Tags < ROM::Relation[:sql] schema(:tags) do associations do belongs_to :post, as: :post_tag end end end assoc = ROM::SQL::Association::ManyToOne.new(:tags, :posts, as: :post_tag) expect(Test::Tags.associations[:post_tag]).to eql(assoc) end it "allows defining a many-to-many" do class Test::Posts < ROM::Relation[:sql] schema(:posts) do associations do one_to_many :tags, through: :posts_tags end end end assoc = ROM::SQL::Association::ManyToMany.new(:posts, :tags, through: :posts_tags) expect(Test::Posts.associations[:tags]).to eql(assoc) end it "allows defining a many-to-one with a custom name" do class Test::Tags < ROM::Relation[:sql] schema(:tags) do associations do many_to_one :published_posts, relation: :posts end end end assoc = ROM::SQL::Association::ManyToOne.new(:tags, :published_posts, relation: :posts) expect(Test::Tags.associations[:published_posts]).to eql(assoc) end end end end <file_sep>module Dry::Initializer class Param < Attribute # part of __initializer__ definition def initializer_signature optional ? "#{target} = #{undefined}" : target end # parts of __initalizer__ def presetter; end def safe_setter "@#{target} = #{maybe_coerced}" end def fast_setter safe_setter end # part of __defaults__ def default_hash super :param end # part of __coercers__ def coercer_hash super :param end private def initialize(*args, **options) fail ArgumentError.new("Do not rename params") if options.key? :as super end def maybe_coerced return maybe_default unless coercer "__coercers__[:param_#{target}].call(#{maybe_default})" end def maybe_default "#{target}#{default_part}" end def default_part return unless default " == #{undefined} ?" \ " instance_exec(&__defaults__[:param_#{target}]) :" \ " #{target}" end end end <file_sep>RSpec.describe ROM::Repository::Root do subject(:repo) do Class.new(ROM::Repository[:users]) do relations :tasks, :posts, :labels end.new(rom) end include_context 'database' include_context 'relations' describe '.[]' do it 'creates a pre-configured root repo class' do klass = ROM::Repository[:users] expect(klass.relations).to eql([:users]) expect(klass.root).to be(:users) child = klass[:users] expect(child.relations).to eql([:users]) expect(child.root).to be(:users) expect(child < klass).to be(true) end end describe 'inheritance' do it 'inherits root and relations' do klass = Class.new(repo.class) expect(klass.relations).to eql([:users, :tasks, :posts, :labels]) expect(klass.root).to be(:users) end it 'creates base root class' do klass = Class.new(ROM::Repository)[:users] expect(klass.relations).to eql([:users]) expect(klass.root).to be(:users) end end describe '#root' do it 'returns configured root relation' do expect(repo.root.relation).to be(rom.relations[:users]) end end describe '#changeset' do it 'returns a changeset automatically set for root relation' do klass = Class.new(ROM::Changeset::Create) changeset = repo.changeset(klass) expect(changeset.relation).to be(repo.users) expect(changeset).to be_kind_of(klass) end end describe '#aggregate' do include_context 'seeds' it 'builds an aggregate from the root relation and other relation(s)' do user = repo.aggregate(many: repo.tasks).where(name: 'Jane').one expect(user.name).to eql('Jane') expect(user.tasks.size).to be(1) expect(user.tasks[0].title).to eql('Jane Task') end context 'with associations' do it 'builds an aggregate from a canonical association' do user = repo.aggregate(:labels).where(name: 'Joe').one expect(user.name).to eql('Joe') expect(user.labels.size).to be(1) expect(user.labels[0].name).to eql('green') end it 'builds an aggregate with nesting level = 2' do user = repo.aggregate(posts: [:labels, :author]).where(name: 'Joe').one expect(user.name).to eql('Joe') expect(user.posts.size).to be(1) expect(user.posts[0].title).to eql('Hello From Joe') expect(user.posts[0].labels.size).to be(1) end it 'builds a command from an aggregate' do command = repo.command(:create, repo.aggregate(:posts)) result = command.call(name: 'Jade', posts: [{ title: 'Jade post' }]) expect(result.name).to eql('Jade') expect(result.posts.size).to be(1) expect(result.posts[0].title).to eql('Jade post') end it 'builds same relation as manual combine' do left = repo.aggregate(:posts) right = repo.users.combine_children(many: repo.posts) expect(left.to_ast).to eql(right.to_ast) end end end end <file_sep>RSpec.describe ROM::Repository, '#command' do include_context 'database' include_context 'relations' include_context 'repo' context 'accessing custom command from the registry' do before do configuration.commands(:users) do define(:upsert, type: ROM::SQL::Commands::Create) define(:create) end configuration.commands(:tasks) do define(:create) end end it 'returns registered command' do expect(repo.command(:users).upsert).to be(rom.command(:users).upsert) expect(repo.command(:users)[:upsert]).to be(rom.command(:users).upsert) end it 'exposes command builder DSL' do command = repo.command.create(user: :users) { |user| user.create(:tasks) } expect(command).to be_instance_of(ROM::Command::Graph) end end context ':create' do it 'builds Create command for a relation' do create_user = repo.command(create: :users) user = create_user.call(name: '<NAME>') expect(user.id).to_not be(nil) expect(user.name).to eql('<NAME>') end it 'uses input_schema for command input' do create_user = repo.command(create: :users) expect(create_user.input).to eql(repo.users.input_schema) end it 'caches commands' do create_user = -> { repo.command(create: :users) } expect(create_user.()).to be(create_user.()) end it 'builds Create command for a relation graph with one-to-one' do create_user = repo.command( :create, repo.users.combine_children(one: repo.tasks) ) user = create_user.call(name: '<NAME>', task: { title: 'Task one' }) expect(user.id).to_not be(nil) expect(user.name).to eql('<NAME>') expect(user.task.title).to eql('Task one') end it 'builds Create command for a deeply nested relation graph' do create_user = repo.command( :create, repo.users.combine_children(one: repo.tasks.combine_children(many: repo.tags)) ) user = create_user.call( name: '<NAME>', task: { title: 'Task one', tags: [{ name: 'red' }] } ) expect(user.id).to_not be(nil) expect(user.name).to eql('<NAME>') expect(user.task.title).to eql('Task one') expect(user.task.tags).to be_instance_of(Array) expect(user.task.tags.first.name).to eql('red') end it 'builds Create command for a relation graph with one-to-many' do create_user = repo.command( :create, repo.users.combine_children(many: repo.tasks) ) user = create_user.call(name: '<NAME>', tasks: [{ title: 'Task one' }]) expect(user.id).to_not be(nil) expect(user.name).to eql('<NAME>') expect(user.tasks).to be_instance_of(Array) expect(user.tasks.first.title).to eql('Task one') end it 'builds Create command for a relation graph with one-to-many with aliased association' do create_user = repo.command(:create, repo.users.combine(:aliased_posts)) user = create_user.call(name: '<NAME>', aliased_posts: [{ title: 'Post one' }, { title: 'Post two' }]) expect(user.id).to_not be(nil) expect(user.name).to eql('<NAME>') expect(user.aliased_posts.size).to be(2) end it 'builds Create command for a deeply nested graph with one-to-many' do create_user = repo.command( :create, repo.aggregate(many: repo.tasks.combine_children(many: repo.tags)) ) user = create_user.call( name: 'Jane', tasks: [{ title: 'Task', tags: [{ name: 'red' }]}] ) expect(user.id).to_not be(nil) expect(user.name).to eql('Jane') expect(user.tasks).to be_instance_of(Array) expect(user.tasks.first.title).to eql('Task') expect(user.tasks.first.tags).to be_instance_of(Array) expect(user.tasks.first.tags.first.name).to eql('red') end it 'builds Create command for a deeply nested graph with many-to-one & one-to-many' do create_user = repo.command( :create, repo.aggregate(one: repo.tasks.combine_children(many: repo.tags)) ) user = create_user.call( name: 'Jane', task: { title: 'Task', tags: [{ name: 'red' }, { name: 'blue' }] } ) expect(user.id).to_not be(nil) expect(user.name).to eql('Jane') expect(user.task.title).to eql('Task') expect(user.task.tags).to be_instance_of(Array) expect(user.task.tags.size).to be(2) expect(user.task.tags[0].name).to eql('red') expect(user.task.tags[1].name).to eql('blue') end it 'builds Create command for a deeply nested graph with many-to-one' do create_user = repo.command( :create, repo.aggregate(one: repo.tasks.combine_children(one: repo.tags)) ) user = create_user.call( name: 'Jane', task: { title: 'Task', tag: { name: 'red' } } ) expect(user.id).to_not be(nil) expect(user.name).to eql('Jane') expect(user.task.id).to_not be(nil) expect(user.task.title).to eql('Task') expect(user.task.tag.id).to_not be(nil) expect(user.task.tag.name).to eql('red') end it 'builds Create command for a nested graph with many-to-many' do user = repo.command(:create, repo.users).(name: 'Jane') create_post = repo.command( :create, repo.posts.combine_children(many: { labels: repo.labels }) ) post = create_post.call( author_id: user.id, title: 'Jane post', labels: [{ name: 'red' }] ) expect(post.labels.size).to be(1) end context 'relation with a custom dataset name' do it 'allows configuring a create command' do create_comment = comments_repo.command(create: :comments) comment = create_comment.(author: 'gerybabooma', body: 'DIS GUY MUST BE A ALIEN OR SUTIN') expect(comment.message_id).to eql(1) expect(comment.author).to eql('gerybabooma') expect(comment.body).to eql('DIS GUY MUST BE A ALIEN OR SUTIN') end it 'allows configuring a create command with aliased one-to-many' do pending 'custom association names in the input are not yet support' create_comment = comments_repo.command(:create, comments_repo.comments.combine(:emotions)) comment = create_comment.(author: 'Jane', body: 'Hello Joe', emotions: [{ author: 'Joe' }]) expect(comment.message_id).to eql(1) expect(comment.author).to eql('Jane') expect(comment.body).to eql('Hello Joe') expect(comment.emotions.size).to eql(1) expect(comment.emotions[0].author).to eql('Joe') end end end context ':update' do it 'builds Update command for a relation' do repo.users.insert(id: 3, name: 'Jane') update_user = repo.command(:update, repo.users) user = update_user.by_pk(3).call(name: '<NAME>') expect(user.id).to be(3) expect(user.name).to eql('<NAME>') end end context ':delete' do it 'builds Delete command for a relation' do repo.users.insert(id: 3, name: 'Jane') delete_user = repo.command(:delete, repo.users) delete_user.by_pk(3).call expect(repo.users.by_pk(3).one).to be(nil) end end end <file_sep>require 'dry/core/constants' require 'dry-types' require 'dry/struct/version' require 'dry/struct/errors' require 'dry/struct/class_interface' require 'dry/struct/hashify' module Dry # Typed {Struct} with virtus-like DSL for defining schema. # # ### Differences between dry-struct and virtus # # {Struct} look somewhat similar to [Virtus][] but there are few significant differences: # # * {Struct}s don't provide attribute writers and are meant to be used # as "data objects" exclusively. # * Handling of attribute values is provided by standalone type objects from # [`dry-types`][]. # * Handling of attribute hashes is provided by standalone hash schemas from # [`dry-types`][], which means there are different types of constructors in # {Struct} (see {Dry::Struct::ClassInterface#constructor_type}) # * Struct classes quack like [`dry-types`][], which means you can use them # in hash schemas, as array members or sum them # # {Struct} class can specify a constructor type, which uses [hash schemas][] # to handle attributes in `.new` method. # See {ClassInterface#new} for constructor types descriptions and examples. # # [`dry-types`]: https://github.com/dry-rb/dry-types # [Virtus]: https://github.com/solnic/virtus # [hash schemas]: http://dry-rb.org/gems/dry-types/hash-schemas # # @example # require 'dry-struct' # # module Types # include Dry::Types.module # end # # class Book < Dry::Struct # attribute :title, Types::Strict::String # attribute :subtitle, Types::Strict::String.optional # end # # rom_n_roda = Book.new( # title: 'Web Development with ROM and Roda', # subtitle: nil # ) # rom_n_roda.title #=> 'Web Development with ROM and Roda' # rom_n_roda.subtitle #=> nil # # refactoring = Book.new( # title: 'Refactoring', # subtitle: 'Improving the Design of Existing Code' # ) # refactoring.title #=> 'Refactoring' # refactoring.subtitle #=> 'Improving the Design of Existing Code' class Struct include Dry::Core::Constants extend ClassInterface # {Dry::Types::Hash} subclass with specific behaviour defined for # @return [Dry::Types::Hash] # @see #constructor_type defines :input input Types['coercible.hash'] # @return [Hash{Symbol => Dry::Types::Definition, Dry::Struct}] defines :schema schema EMPTY_HASH # Sets or retrieves {#constructor} type as a symbol # # @note All examples below assume that you have defined {Struct} with # following attributes and explicitly call only {#constructor_type}: # # ```ruby # class User < Dry::Struct # attribute :name, Types::Strict::String.default('<NAME>') # attribute :age, Types::Strict::Int # end # ``` # # ### Common constructor types include: # # * `:permissive` - the default constructor type, useful for defining # {Struct}s that are instantiated using data from the database # (i.e. results of a database query), where you expect *all defined # attributes to be present* and it's OK to ignore other keys # (i.e. keys used for joining, that are not relevant from your domain # {Struct}s point of view). Default values **are not used** otherwise # you wouldn't notice missing data. # * `:schema` - missing keys will result in setting them using default # values, unexpected keys will be ignored. # * `:strict` - useful when you *do not expect keys other than the ones # you specified as attributes* in the input hash # * `:strict_with_defaults` - same as `:strict` but you are OK that some # values may be nil and you want defaults to be set # # To feel the difference between constructor types, look into examples. # Each of them provide the same attributes' definitions, # different constructor type, and 4 cases of given input: # # 1. Input omits a key for a value that does not have a default # 2. Input omits a key for a value that has a default # 3. Input contains nil for a value that specifies a default # 4. Input includes a key that was not specified in the schema # # @note Don’t use `:weak` and `:symbolized` as {#constructor_type}, # and instead use [`dry-validation`][] to process and validate # attributes, otherwise your struct will behave as a data validator # which raises exceptions on invalid input (assuming your attributes # types are strict) # [`dry-validation`]: https://github.com/dry-rb/dry-validation # # @example `:permissive` constructor # class User < Dry::Struct # constructor_type :permissive # end # # User.new(name: "Jane") # #=> Dry::Struct::Error: [User.new] :age is missing in Hash input # User.new(age: 31) # #=> Dry::Struct::Error: [User.new] :name is missing in Hash input # User.new(name: nil, age: 31) # #=> #<User name="<NAME>" age=31> # User.new(name: "Jane", age: 31, unexpected: "attribute") # #=> #<User name="Jane" age=31> # # @example `:schema` constructor # class User < Dry::Struct # constructor_type :schema # end # # User.new(name: "Jane") #=> #<User name="Jane" age=nil> # User.new(age: 31) #=> #<User name="<NAME>" age=31> # User.new(name: nil, age: 31) #=> #<User name="<NAME>" age=31> # User.new(name: "Jane", age: 31, unexpected: "attribute") # #=> #<User name="Jane" age=31> # # @example `:strict` constructor # class User < Dry::Struct # constructor_type :strict # end # # User.new(name: "Jane") # #=> Dry::Struct::Error: [User.new] :age is missing in Hash input # User.new(age: 31) # #=> Dry::Struct::Error: [User.new] :name is missing in Hash input # User.new(name: nil, age: 31) # #=> Dry::Struct::Error: [User.new] nil (NilClass) has invalid type for :name # User.new(name: "Jane", age: 31, unexpected: "attribute") # #=> Dry::Struct::Error: [User.new] unexpected keys [:unexpected] in Hash input # # @example `:strict_with_defaults` constructor # class User < Dry::Struct # constructor_type :strict_with_defaults # end # # User.new(name: "Jane") # #=> Dry::Struct::Error: [User.new] :age is missing in Hash input # User.new(age: 31) # #=> #<User name="<NAME>" age=31> # User.new(name: nil, age: 31) # #=> Dry::Struct::Error: [User.new] nil (NilClass) has invalid type for :name # User.new(name: "Jane", age: 31, unexpected: "attribute") # #=> Dry::Struct::Error: [User.new] unexpected keys [:unexpected] in Hash input # # @see http://dry-rb.org/gems/dry-types/hash-schemas # # @overload constructor_type(type) # Sets the constructor type for {Struct} # @param [Symbol] type one of constructor types, see above # @return [Symbol] # # @overload constructor_type # Returns the constructor type for {Struct} # @return [Symbol] (:strict) defines :constructor_type constructor_type :permissive # @return [Dry::Equalizer] defines :equalizer # @param [Hash, #each] attributes def initialize(attributes) attributes.each { |key, value| instance_variable_set("@#{key}", value) } end # Retrieves value of previously defined attribute by its' `name` # # @param [String] name # @return [Object] # # @example # class Book < Dry::Struct # attribute :title, Types::Strict::String # attribute :subtitle, Types::Strict::String.optional # end # # rom_n_roda = Book.new( # title: 'Web Development with ROM and Roda', # subtitle: nil # ) # rom_n_roda[:title] #=> 'Web Development with ROM and Roda' # rom_n_roda[:subtitle] #=> nil def [](name) public_send(name) end # Converts the {Dry::Struct} to a hash with keys representing # each attribute (as symbols) and their corresponding values # # @return [Hash{Symbol => Object}] # # @example # class Book < Dry::Struct # attribute :title, Types::Strict::String # attribute :subtitle, Types::Strict::String.optional # end # # rom_n_roda = Book.new( # title: 'Web Development with ROM and Roda', # subtitle: nil # ) # rom_n_roda.to_hash # #=> {title: 'Web Development with ROM and Roda', subtitle: nil} def to_hash self.class.schema.keys.each_with_object({}) do |key, result| result[key] = Hashify[self[key]] end end alias_method :to_h, :to_hash # Create a copy of {Dry::Struct} with overriden attributes # # @param [Hash{Symbol => Object}] changeset # # @return [Struct] # # @example # class Book < Dry::Struct # attribute :title, Types::Strict::String # attribute :subtitle, Types::Strict::String.optional # end # # rom_n_roda = Book.new( # title: 'Web Development with ROM and Roda', # subtitle: '2nd edition' # ) # #=> #<Book title="Web Development with ROM and Roda" subtitle="2nd edition"> # # rom_n_roda.new(subtitle: '3nd edition') # #=> #<Book title="Web Development with ROM and Roda" subtitle="3nd edition"> def new(changeset) self.class[to_hash.merge(changeset)] end alias_method :__new__, :new end end require 'dry/struct/value' <file_sep>module Dry::Initializer class Builder def param(*args, **opts) @params = insert @params, Attribute.param(*args, **@config.merge(opts)) validate_collections end def option(*args, **opts) @options = insert @options, Attribute.option(*args, **@config.merge(opts)) validate_collections end def call(mixin) clear_method(mixin, :__defaults__) clear_method(mixin, :__coercers__) clear_method(mixin, :__initialize__) defaults = send(:defaults) coercers = send(:coercers) mixin.send(:define_method, :__defaults__) { defaults } mixin.send(:define_method, :__coercers__) { coercers } mixin.class_eval(code) end private def initialize(**config) @config = config @params = [] @options = [] end def insert(collection, new_item) index = collection.index(new_item) || collection.count collection.dup.tap { |list| list[index] = new_item } end def clear_method(mixin, name) mixin.send(:undef_method, name) if mixin.private_method_defined? name end def code <<-RUBY def __initialize__(#{initializer_signatures}) @__options__ = {} #{initializer_presetters} #{initializer_setters} #{initializer_postsetters} end private :__initialize__ private :__defaults__ private :__coercers__ #{getters} RUBY end def attributes @params + @options end def duplications attributes.group_by(&:target) .reject { |_, val| val.count == 1 } .keys end def initializer_signatures sig = @params.map(&:initializer_signature).compact.uniq sig << (sig.any? && @options.any? ? "**__options__" : "__options__ = {}") sig.join(", ") end def initializer_presetters dups = duplications attributes.map { |a| " #{a.presetter}" if dups.include? a.target } .compact.uniq.join("\n") end def initializer_setters dups = duplications attributes.map do |a| dups.include?(a.target) ? " #{a.safe_setter}" : " #{a.fast_setter}" end.compact.uniq.join("\n") end def initializer_postsetters attributes.map { |a| " #{a.postsetter}" }.compact.uniq.join("\n") end def defined_options if @options.any? keys = @options.map(&:target).join(" ") "__options__.select { |key| %i(#{keys}).include? key }" else "{}" end end def getters attributes.map(&:getter).compact.uniq.join("\n") end def defaults attributes.map(&:default_hash).reduce({}, :merge) end def coercers attributes.map(&:coercer_hash).reduce({}, :merge) end def validate_collections optional_param = nil @params.each do |param| if param.optional optional_param = param.source if param.optional elsif optional_param fail ParamsOrderError.new(param.source, optional_param) end end self end end end <file_sep>module ROM class Changeset module Restricted # Return a command restricted by the changeset's relation # # @see Changeset#command # # @api private def command super.new(relation) end # Restrict changeset's relation by its PK # # @example # repo.changeset(UpdateUser).by_pk(1).data(name: "Jane") # # @param [Object] pk # # @return [Changeset] # # @api public def by_pk(pk, data = EMPTY_HASH) new(relation.by_pk(pk), __data__: data) end end end end <file_sep>require 'rom/plugins/relation/sql/instrumentation' require 'rom/plugins/relation/sql/auto_restrictions' require 'rom/sql/plugin/associates' require 'rom/sql/plugin/pagination' require 'rom/sql/plugin/timestamps' ROM.plugins do adapter :sql do register :pagination, ROM::SQL::Plugin::Pagination, type: :relation register :associates, ROM::SQL::Plugin::Associates, type: :command register :timestamps, ROM::SQL::Plugin::Timestamps, type: :command end end <file_sep>RSpec.describe ROM::SQL::Association::Name do describe '.[]' do it 'returns a name object from a relation name' do rel_name = ROM::Relation::Name[:users] assoc_name = ROM::SQL::Association::Name[rel_name] expect(assoc_name).to eql(ROM::SQL::Association::Name.new(rel_name, :users)) end it 'returns a name object from a relation and a dataset symbols' do rel_name = ROM::Relation::Name[:users, :people] assoc_name = ROM::SQL::Association::Name[:users, :people] expect(assoc_name).to eql(ROM::SQL::Association::Name.new(rel_name, :people)) end it 'returns a name object from a relation and a dataset symbols and an alias' do rel_name = ROM::Relation::Name[:users, :people] assoc_name = ROM::SQL::Association::Name[:users, :people, :author] expect(assoc_name).to eql(ROM::SQL::Association::Name.new(rel_name, :author)) end it 'caches names' do name = ROM::SQL::Association::Name[:users] expect(name).to be(ROM::SQL::Association::Name[:users]) name = ROM::SQL::Association::Name[:users, :people] expect(name).to be(ROM::SQL::Association::Name[:users, :people]) name = ROM::SQL::Association::Name[:users, :people, :author] expect(name).to be(ROM::SQL::Association::Name[:users, :people, :author]) end end describe '#aliased?' do it 'returns true if a name has an alias' do expect(ROM::SQL::Association::Name[:users, :people, :author]).to be_aliased end it 'returns false if a name has no alias' do expect(ROM::SQL::Association::Name[:users, :people]).to_not be_aliased end end describe '#inspect' do it 'includes info about the relation name' do expect(ROM::SQL::Association::Name[:users].inspect).to eql( "ROM::SQL::Association::Name(users)" ) end it 'includes info about the relation name and its dataset' do expect(ROM::SQL::Association::Name[:users, :people].inspect).to eql( "ROM::SQL::Association::Name(users on people)" ) end it 'includes info about the relation name, its dataset and alias' do expect(ROM::SQL::Association::Name[:users, :people, :author].inspect).to eql( "ROM::SQL::Association::Name(users on people as author)" ) end end end <file_sep>RSpec.describe ROM::SQL::Relation, '#instrument', :sqlite do include_context 'users and tasks' subject(:relation) do relations[:users] end let(:notifications) do spy(:notifications) end before do conf.plugin(:sql, relations: :instrumentation) do |p| p.notifications = notifications end end it 'instruments relation materialization' do users.to_a expect(notifications). to have_received(:instrument).with(:sql, name: :users, query: users.dataset.sql) end it 'instruments methods that return a single tuple' do users.first expect(notifications). to have_received(:instrument).with(:sql, name: :users, query: users.limit(1).dataset.sql) users.last expect(notifications). to have_received(:instrument).with(:sql, name: :users, query: users.reverse.limit(1).dataset.sql) end it 'instruments aggregation methods' do pending "no idea how to make this work with sequel" users.count expect(notifications). to have_received(:instrument).with(:sql, name: :users, query: 'SELECT COUNT(*) FROM users') end end <file_sep>RSpec.describe ROM::SQL::Association::OneToOneThrough, helpers: true do subject(:assoc) do ROM::SQL::Association::OneToOneThrough.new(source, target, options) end let(:options) { { through: :tasks_tags } } let(:tags) { double(:tags, primary_key: :id) } let(:tasks) { double(:tasks, primary_key: :id) } let(:tasks_tags) { double(:tasks, primary_key: [:task_id, :tag_id]) } let(:source) { :tasks } let(:target) { :tags } describe '#result' do it 'is :one' do expect(assoc.result).to be(:one) end end shared_examples_for 'many-to-many association' do describe '#combine_keys' do it 'returns a hash with combine keys' do expect(tasks_tags).to receive(:foreign_key).with(:tasks).and_return(:tag_id) expect(assoc.combine_keys(relations)).to eql(id: :tag_id) end end end context 'with default names' do let(:relations) do { tasks: tasks, tags: tags, tasks_tags: tasks_tags } end it_behaves_like 'many-to-many association' describe '#join_keys' do it 'returns a hash with combine keys' do expect(tasks_tags).to receive(:foreign_key).with(:tasks).and_return(:tag_id) expect(assoc.join_keys(relations)).to eql( qualified_attribute(:tasks, :id) => qualified_attribute(:tasks_tags, :tag_id) ) end end end context 'with custom relation names' do let(:source) { assoc_name(:tasks, :user_tasks) } let(:target) { assoc_name(:tags, :user_tags) } let(:relations) do { tasks: tasks, tags: tags, tasks_tags: tasks_tags } end it_behaves_like 'many-to-many association' describe '#join_keys' do it 'returns a hash with combine keys' do expect(tasks_tags).to receive(:foreign_key).with(:tasks).and_return(:tag_id) expect(assoc.join_keys(relations)).to eql( qualified_attribute(:user_tasks, :id) => qualified_attribute(:tasks_tags, :tag_id) ) end end end end <file_sep># -*- encoding: utf-8 -*- # stub: rom-sql 1.3.5 ruby lib Gem::Specification.new do |s| s.name = "rom-sql".freeze s.version = "1.3.5" s.required_rubygems_version = Gem::Requirement.new(">= 0".freeze) if s.respond_to? :required_rubygems_version= s.require_paths = ["lib".freeze] s.authors = ["<NAME>".freeze] s.date = "2017-10-12" s.description = "SQL databases support for ROM".freeze s.email = ["<EMAIL>".freeze] s.homepage = "http://rom-rb.org".freeze s.licenses = ["MIT".freeze] s.rubygems_version = "3.0.3".freeze s.summary = "SQL databases support for ROM".freeze s.installed_by_version = "3.0.3" if s.respond_to? :installed_by_version if s.respond_to? :specification_version then s.specification_version = 4 if Gem::Version.new(Gem::VERSION) >= Gem::Version.new('1.2.0') then s.add_runtime_dependency(%q<sequel>.freeze, ["~> 4.43"]) s.add_runtime_dependency(%q<dry-equalizer>.freeze, ["~> 0.2"]) s.add_runtime_dependency(%q<dry-types>.freeze, ["~> 0.11.0"]) s.add_runtime_dependency(%q<dry-core>.freeze, ["~> 0.3"]) s.add_runtime_dependency(%q<rom>.freeze, ["~> 3.2", ">= 3.2.2"]) s.add_development_dependency(%q<bundler>.freeze, [">= 0"]) s.add_development_dependency(%q<rake>.freeze, ["~> 10.0"]) s.add_development_dependency(%q<rspec>.freeze, ["~> 3.5"]) else s.add_dependency(%q<sequel>.freeze, ["~> 4.43"]) s.add_dependency(%q<dry-equalizer>.freeze, ["~> 0.2"]) s.add_dependency(%q<dry-types>.freeze, ["~> 0.11.0"]) s.add_dependency(%q<dry-core>.freeze, ["~> 0.3"]) s.add_dependency(%q<rom>.freeze, ["~> 3.2", ">= 3.2.2"]) s.add_dependency(%q<bundler>.freeze, [">= 0"]) s.add_dependency(%q<rake>.freeze, ["~> 10.0"]) s.add_dependency(%q<rspec>.freeze, ["~> 3.5"]) end else s.add_dependency(%q<sequel>.freeze, ["~> 4.43"]) s.add_dependency(%q<dry-equalizer>.freeze, ["~> 0.2"]) s.add_dependency(%q<dry-types>.freeze, ["~> 0.11.0"]) s.add_dependency(%q<dry-core>.freeze, ["~> 0.3"]) s.add_dependency(%q<rom>.freeze, ["~> 3.2", ">= 3.2.2"]) s.add_dependency(%q<bundler>.freeze, [">= 0"]) s.add_dependency(%q<rake>.freeze, ["~> 10.0"]) s.add_dependency(%q<rspec>.freeze, ["~> 3.5"]) end end <file_sep>require 'rom/sql/extensions/mysql/inferrer' <file_sep>require 'rom/types' module ROM module SQL class Association class ManyToMany < Association result :many option :through, type: Types::Strict::Symbol.optional # @api private def initialize(*) super @through = Relation::Name[ options[:through] || options[:through_relation], options[:through] ] end # @api public def call(relations, target_rel = nil) join_rel = join_relation(relations) assocs = join_rel.associations left = target_rel ? assocs[target].(relations, target_rel) : assocs[target].(relations) right = relations[target.relation] left_fk = foreign_key || join_rel.foreign_key(source.relation) schema = if left.schema.key?(left_fk) if target_rel target_rel.schema.merge(left.schema.project(left_fk)) else left.schema.project(*(right.schema.map(&:name) + [left_fk])) end else right.schema.merge(join_rel.schema.project(left_fk)) end.qualified relation = left.inner_join(source, join_keys(relations)) if view apply_view(schema, relation) else schema.(relation) end end # @api private def persist(relations, children, parents) join_tuples = associate(relations, children, parents) join_relation = join_relation(relations) join_relation.multi_insert(join_tuples) end # @api private def parent_combine_keys(relations) relations[target].associations[source].combine_keys(relations).to_a.flatten(1) end # @api public def join(relations, type, source = relations[self.source], target = relations[self.target]) through_assoc = source.associations[through] joined = through_assoc.join(relations, type, source) joined.__send__(type, target.name.dataset, join_keys(relations)).qualified end # @api public def join_keys(relations) with_keys(relations) { |source_key, target_key| { qualify(source, source_key) => qualify(through, target_key) } } end # @api public def combine_keys(relations) Hash[*with_keys(relations)] end # @api private def associate(relations, children, parent) ((spk, sfk), (tfk, tpk)) = join_key_map(relations) case parent when Array parent.map { |p| associate(relations, children, p) }.flatten(1) else children.map { |tuple| { sfk => tuple.fetch(spk), tfk => parent.fetch(tpk) } } end end # @api private def join_relation(relations) relations[through.relation] end protected # @api private def with_keys(relations, &block) source_key = relations[source.relation].primary_key target_key = foreign_key || relations[through.relation].foreign_key(source.relation) return [source_key, target_key] unless block yield(source_key, target_key) end # @api private def join_key_map(relations) left = super right = join_relation(relations).associations[target].join_key_map(relations) [left, right] end end end end end <file_sep># frozen_string_literal: true module Hanami # Hanami web console for development # # @since 0.1.0 module Webconsole require "hanami/webconsole/version" require "hanami/webconsole/plugin" end end <file_sep>require 'spec_helper' RSpec.describe ROM::SQL::Attribute, :postgres do include_context 'users and tasks' let(:ds) { users.dataset } describe '#is' do context 'with a standard value' do it 'returns a boolean expression' do expect(users[:id].is(1).sql_literal(ds)).to eql('("id" = 1)') end it 'returns a boolean equality expression for qualified attribute' do expect((users[:id].qualified.is(1)).sql_literal(ds)).to eql('("users"."id" = 1)') end end context 'with a nil value' do it 'returns an IS NULL expression' do expect(users[:id].is(nil).sql_literal(ds)).to eql('("id" IS NULL)') end it 'returns an IS NULL expression for qualified attribute' do expect((users[:id].qualified.is(nil)).sql_literal(ds)).to eql('("users"."id" IS NULL)') end end context 'with a boolean true' do it 'returns an IS TRUE expression' do expect(users[:id].is(true).sql_literal(ds)).to eql('("id" IS TRUE)') end it 'returns an IS TRUE expression for qualified attribute' do expect((users[:id].qualified.is(true)).sql_literal(ds)).to eql('("users"."id" IS TRUE)') end end context 'with a boolean false' do it 'returns an IS FALSE expression' do expect(users[:id].is(false).sql_literal(ds)).to eql('("id" IS FALSE)') end it 'returns an IS FALSE expression for qualified attribute' do expect((users[:id].qualified.is(false)).sql_literal(ds)).to eql('("users"."id" IS FALSE)') end end end describe '#not' do context 'with a standard value' do it 'returns a negated boolean equality expression' do expect(users[:id].not(1).sql_literal(ds)).to eql('("id" != 1)') end it 'returns a negated boolean equality expression for qualified attribute' do expect((users[:id].qualified.not(1)).sql_literal(ds)).to eql('("users"."id" != 1)') end end context 'with a nil value' do it 'returns an IS NOT NULL expression' do expect(users[:id].not(nil).sql_literal(ds)).to eql('("id" IS NOT NULL)') end it 'returns an IS NOT NULL expression for qualified attribute' do expect((users[:id].qualified.not(nil)).sql_literal(ds)).to eql('("users"."id" IS NOT NULL)') end end context 'with a boolean true' do it 'returns an IS NOT TRUE expression' do expect(users[:id].not(true).sql_literal(ds)).to eql('("id" IS NOT TRUE)') end it 'returns an IS NOT TRUE expression for qualified attribute' do expect((users[:id].qualified.not(true)).sql_literal(ds)).to eql('("users"."id" IS NOT TRUE)') end end context 'with a boolean false' do it 'returns an IS NOT FALSE expression' do expect(users[:id].not(false).sql_literal(ds)).to eql('("id" IS NOT FALSE)') end it 'returns an IS NOT FALSE expression for qualified attribute' do expect((users[:id].qualified.not(false)).sql_literal(ds)).to eql('("users"."id" IS NOT FALSE)') end end end describe '#!' do it 'returns a new attribute with negated sql expr' do expect((!users[:id].is(1)).sql_literal(ds)).to eql('("id" != 1)') end end describe '#concat' do it 'returns a concat function attribute' do expect(users[:id].concat(users[:name]).as(:uid).sql_literal(ds)). to eql(%(CONCAT("id", ' ', "name") AS "uid")) end end end <file_sep>RSpec.describe ROM::SQL::Association::OneToMany do subject(:assoc) { ROM::SQL::Association::OneToMany.new(:users, :tasks) } include_context 'users and tasks' with_adapters do before do conf.relation(:tasks) do schema do attribute :id, ROM::SQL::Types::Serial attribute :user_id, ROM::SQL::Types::ForeignKey(:users) attribute :title, ROM::SQL::Types::String end end end describe '#result' do specify { expect(ROM::SQL::Association::OneToMany.result).to be(:many) } end describe '#call' do it 'prepares joined relations' do relation = assoc.call(container.relations) expect(relation.schema.map(&:name)).to eql(%i[id user_id title]) expect(relation.order(tasks[:id].qualified).to_a).to eql([ { id: 1, user_id: 2, title: "<NAME>" }, { id: 2, user_id: 1, title: "<NAME>" } ]) expect(relation.where(user_id: 1).to_a).to eql([ { id: 2, user_id: 1, title: "<NAME>" } ]) expect(relation.where(user_id: 2).to_a).to eql([ { id: 1, user_id: 2, title: "<NAME>" } ]) end end describe ROM::Plugins::Relation::SQL::AutoCombine, '#for_combine' do it 'preloads relation based on association' do relation = tasks.for_combine(assoc).call(users.call) expect(relation.to_a).to eql([ { id: 1, user_id: 2, title: "<NAME>" }, { id: 2, user_id: 1, title: "<NAME>" } ]) end it 'maintains original relation' do relation = tasks. join(:task_tags, tag_id: :id). select_append(tasks.task_tags[:tag_id].qualified). for_combine(assoc).call(users.call) expect(relation.to_a).to eql([{ id: 1, user_id: 2, title: "<NAME>", tag_id: 1 }]) end it 'respects custom order' do relation = tasks. order(tasks[:title].qualified). for_combine(assoc).call(users.call) expect(relation.to_a). to eql([{ id: 2, user_id: 1, title: "<NAME>" }, { id: 1, user_id: 2, title: "Joe's task" }]) end end end end <file_sep>module ROM class Repository class RelationProxy # Provides convenient methods for producing wrapped relations # # @api public module Wrap # Wrap other relations # # @example # tasks.wrap(owner: [users, user_id: :id]) # # @param [Hash] options # # @return [RelationProxy] # # @api public def wrap(*names, **options) new_wraps = wraps_from_names(names) + wraps_from_options(options) relation = new_wraps.reduce(self) { |a, e| name = e.meta[:wrap_from_assoc] ? e.meta[:combine_name] : e.base_name.relation a.relation.for_wrap(e.meta.fetch(:keys), name) } __new__(relation, meta: { wraps: wraps + new_wraps }) end # Shortcut to wrap parents # # @example # tasks.wrap_parent(owner: users) # # @return [RelationProxy] # # @api public def wrap_parent(options) wrap( options.each_with_object({}) { |(name, parent), h| keys = combine_keys(parent, relation, :children) h[name] = [parent, keys] } ) end # Return a wrapped representation of a loading-proxy relation # # This will carry meta info used to produce a correct AST from a relation # so that correct mapper can be generated # # @return [RelationProxy] # # @api private def wrapped(name, keys, wrap_from_assoc = false) with( name: name, meta: { keys: keys, wrap_from_assoc: wrap_from_assoc, wrap: true, combine_name: name } ) end # @api private def wraps_from_options(options) options.map { |(name, (relation, keys))| relation.wrapped(name, keys) } end # @api private def wraps_from_names(names) names.map { |name| assoc = associations[name] registry[assoc.target.relation].wrapped(name, assoc.combine_keys(__registry__), true) } end end end end end <file_sep>require 'dry/core/class_attributes' module ROM class Repository # A specialized repository type dedicated to work with a root relation # # This repository type builds commands and aggregates for its root relation # # @example # class UserRepo < ROM::Repository[:users] # commands :create, update: :by_pk, delete: :by_pk # end # # rom = ROM.container(:sql, 'sqlite::memory') do |conf| # conf.default.create_table(:users) do # primary_key :id # column :name, String # end # end # # user_repo = UserRepo.new(rom) # # user = user_repo.create(name: "Jane") # # changeset = user_repo.changeset(user.id, name: "<NAME>") # user_repo.update(user.id, changeset) # # user_repo.delete(user.id) # # @api public class Root < Repository # @!method self.root # Get or set repository root relation identifier # # This method is automatically used when you define a class using # MyRepo[:rel_identifier] shortcut # # @overload root # Return root relation identifier # @return [Symbol] # # @overload root(identifier) # Set root relation identifier # @return [Symbol] defines :root # @!attribute [r] root # @return [RelationProxy] The root relation attr_reader :root # Sets descendant root relation # # @api private def self.inherited(klass) super klass.root(root) end # @see Repository#initialize def initialize(container, opts = EMPTY_HASH) super @root = relations[self.class.root] end # Compose a relation aggregate from the root relation # # @overload aggregate(*associations) # Composes an aggregate from configured associations on the root relation # # @example # user_repo.aggregate(:tasks, :posts) # # @param *associations [Array<Symbol>] A list of association names # # @overload aggregate(*associations, *assoc_opts) # Composes an aggregate from configured associations and assoc opts # on the root relation # # @example # user_repo.aggregate(:tasks, posts: :tags) # # @param *associations [Array<Symbol>] A list of association names # @param [Hash] Association options for nested aggregates # # @overload aggregate(options) # Composes an aggregate by delegating to combine_children method. # # @example # user_repo.aggregate(tasks: :labels) # user_repo.aggregate(posts: [:tags, :comments]) # # @param options [Hash] An option hash # # @see RelationProxy::Combine#combine_children # # @return [RelationProxy] # # @api public def aggregate(*args) if args.all? { |arg| arg.is_a?(Symbol) } root.combine(*args) else args.reduce(root) { |a, e| a.combine(e) } end end # @overload changeset(name, *args) # Delegate to Repository#changeset # # @see Repository#changeset # # @overload changeset(data) # Builds a create changeset for the root relation # # @example # user_repo.changeset(name: "Jane") # # @param data [Hash] New data # # @return [Changeset::Create] # # @overload changeset(primary_key, data) # Builds an update changeset for the root relation # # @example # user_repo.changeset(1, name: "<NAME>") # # @param primary_key [Object] Primary key for restricting relation # # @return [Changeset::Update] # # @overload changeset(changeset_class) # Return a changeset prepared for repo's root relation # # @example # changeset = user_repo.changeset(MyChangeset) # # changeset.relation == user_repo.root # # true # # @param [Class] changeset_class Your custom changeset class # # @return [Changeset] # # @see Repository#changeset # # @api public def changeset(*args) if args.first.is_a?(Symbol) && relations.key?(args.first) super elsif args.first.is_a?(Class) klass, *rest = args super(klass[klass.relation || self.class.root], *rest) else super(root.name, *args) end end end end end <file_sep>require 'dry-struct' RSpec.describe 'loading proxy' do include_context 'database' include_context 'relations' include_context 'repo' include_context 'structs' include_context 'seeds' let(:users_proxy) do repo.users end let(:tasks_proxy) do repo.tasks end let(:tags_proxy) do repo.tags end describe '#inspect' do specify do expect(users_proxy.inspect). to eql("#<ROM::Relation[Users] name=users dataset=#{users.dataset.inspect}>") end end describe '#each' do it 'yields loaded structs' do result = [] users_proxy.each { |user| result << user } expect(result).to eql([jane, joe]) end it 'returns an enumerator when block is not given' do expect(users_proxy.each.to_a).to eql([jane, joe]) end end describe '#map_with/#as' do context 'with custom mappers' do before do configuration.mappers do register :users, { name_list: -> users { users.map { |u| u[:name] } }, upcase_names: -> names { names.map(&:upcase) }, identity: -> users { users } } end end it 'sends the relation through custom mappers' do expect(users_proxy.map_with(:name_list, :upcase_names).to_a).to match_array(%w(JANE JOE)) end it 'does not use the default(ROM::Struct) mapper' do expect(users_proxy.map_with(:identity).to_a).to match_array( [{ id: 1, name: 'Jane' }, {id: 2, name: 'Joe' }] ) end it 'raises error when custom mapper is used with a model class' do expect { users_proxy.map_with(:name_list, Class.new) }. to raise_error(ArgumentError, 'using custom mappers and a model is not supported') end end context 'setting custom model type' do let(:user_type) do Class.new(Dry::Struct) do attribute :id, Dry::Types['strict.int'] attribute :name, Dry::Types['strict.string'] end end let(:custom_users) { users_proxy.as(user_type) } it 'instantiates custom model' do expect(custom_users.where(name: 'Jane').one).to be_instance_of(user_type) end end end describe 'retrieving a single struct' do describe '#first' do it 'returns exactly one struct' do expect(users_proxy.first).to eql(jane) end end describe '#one' do it 'returns exactly one struct' do expect(users_proxy.find(id: 1).one).to eql(jane) expect(users_proxy.find(id: 3).one).to be(nil) expect { users_proxy.find(id: [1,2]).one }.to raise_error(ROM::TupleCountMismatchError) end end describe '#one!' do it 'returns exactly one struct' do expect(users_proxy.find(id: 1).one!).to eql(jane) expect { users_proxy.find(id: [1, 2]).one! }.to raise_error(ROM::TupleCountMismatchError) expect { users_proxy.find(id: [3]).one! }.to raise_error(ROM::TupleCountMismatchError) end end end describe '#to_ast' do it 'returns valid ast for a single relation' do expect(users_proxy.to_ast).to eql( [:relation, [ :users, { dataset: :users }, [:header, [[:attribute, users_proxy.schema[:id]], [:attribute, users_proxy.schema[:name]]]]] ] ) end it 'returns valid ast for a combined relation' do relation = users_proxy.combine(many: { user_tasks: [tasks_proxy, id: :user_id] }) expect(relation.to_ast).to eql( [:relation, [ :users, { dataset: :users }, [:header, [ [:attribute, users_proxy.schema[:id]], [:attribute, users_proxy.schema[:name]], [:relation, [ :tasks, { dataset: :tasks, keys: { id: :user_id }, combine_type: :many, combine_name: :user_tasks }, [:header, [ [:attribute, tasks_proxy.schema[:id]], [:attribute, tasks_proxy.schema[:user_id]], [:attribute, tasks_proxy.schema[:title]]]] ]] ] ]]] ) end it 'returns valid ast for a wrapped relation' do relation = tags_proxy.wrap_parent(task: tasks_proxy) tags_schema = tags_proxy.schema.qualified tasks_schema = tasks_proxy.schema.wrap expect(relation.to_ast).to eql( [:relation, [ :tags, { dataset: :tags }, [:header, [ [:attribute, tags_schema[:id]], [:attribute, tags_schema[:task_id]], [:attribute, tags_schema[:name]], [:relation, [ :tasks, { dataset: :tasks, keys: { id: :task_id }, wrap_from_assoc: false, wrap: true, combine_name: :task }, [:header, [ [:attribute, tasks_schema[:id]], [:attribute, tasks_schema[:user_id]], [:attribute, tasks_schema[:title]]]] ]] ]] ]] ) end end describe '#method_missing' do it 'proxies to the underlying relation' do expect(users_proxy.gateway).to be(:default) end it 'returns proxy when response was not materialized' do expect(users_proxy.by_pk(1)).to be_instance_of(ROM::Repository::RelationProxy) end it 'returns curried proxy when response was curried' do expect(users_proxy.by_pk).to be_instance_of(ROM::Repository::RelationProxy) end it 'raises when method is missing' do expect { users_proxy.not_here }.to raise_error(NoMethodError, "undefined method `not_here' for ROM::Relation[Users]") end it 'proxies Kernel methods when using with SimpleDelegator' do proxy = Class.new(SimpleDelegator).new(users_proxy) expect(users_proxy.select(:name)).to be_instance_of(ROM::Repository::RelationProxy) expect(proxy.select(:name)).to be_instance_of(ROM::Repository::RelationProxy) end end end <file_sep>module Dry::Initializer class TypeConstraintError < TypeError def initialize(name, type) super "#{type} constraint for argument '#{name}' doesn't respond to #call" end end end <file_sep>RSpec.describe ROM::Repository, '#changeset' do subject(:repo) do Class.new(ROM::Repository) { relations :users }.new(rom) end include_context 'database' include_context 'relations' describe ROM::Changeset::Create do context 'with a hash' do let(:changeset) do repo.changeset(:users, name: 'Jane') end it 'has data' do expect(changeset.to_h).to eql(name: 'Jane') end it 'has relation' do expect(changeset.relation).to be(repo.users) end it 'can be commited' do expect(changeset.commit).to eql(id: 1, name: 'Jane') end end context 'with an array' do let(:changeset) do repo.changeset(:users, data) end let(:data) do [{ name: 'Jane' }, { name: 'Joe' }] end it 'has data' do expect(changeset.to_a).to eql(data) end it 'has relation' do expect(changeset.relation).to be(repo.users) end it 'can be commited' do expect(changeset.commit).to eql([{ id: 1, name: 'Jane' }, { id: 2, name: 'Joe' }]) end end end describe ROM::Changeset::Update do let(:data) do { name: '<NAME>' } end shared_context 'a valid update changeset' do let!(:jane) do repo.command(:create, repo.users).call(name: 'Jane') end let!(:joe) do repo.command(:create, repo.users).call(name: 'Joe') end it 'has data' do expect(changeset.to_h).to eql(name: '<NAME>') end it 'has diff' do expect(changeset.diff).to eql(name: '<NAME>') end it 'has relation' do expect(changeset.relation.one).to eql(repo.users.by_pk(jane[:id]).one) end it 'can be commited' do expect(changeset.commit).to eql(id: 1, name: '<NAME>') expect(repo.users.by_pk(joe[:id]).one).to eql(joe) end end context 'using PK to restrict a relation' do let(:changeset) do repo.changeset(:users, jane[:id], data) end include_context 'a valid update changeset' end context 'using custom relation' do let(:changeset) do repo.changeset(update: repo.users.by_pk(jane[:id])).data(data) end include_context 'a valid update changeset' end end describe ROM::Changeset::Delete do let(:changeset) do repo.changeset(delete: relation) end let(:relation) do repo.users.by_pk(user[:id]) end let(:user) do repo.command(:create, repo.users).call(name: 'Jane') end it 'has relation' do expect(changeset.relation).to eql(relation) end it 'can be commited' do expect(changeset.commit.to_h).to eql(id: 1, name: 'Jane') expect(relation.one).to be(nil) end end describe 'custom changeset class' do context 'with a Create' do let(:changeset) do repo.changeset(changeset_class[:users]).data({}) end let(:changeset_class) do Class.new(ROM::Changeset::Create) do def to_h __data__.merge(name: 'Jane') end end end it 'has data' do expect(changeset.to_h).to eql(name: 'Jane') end it 'has relation' do expect(changeset.relation).to be(repo.users) end it 'can be commited' do expect(changeset.commit).to eql(id: 1, name: 'Jane') end end context 'with an Update' do let(:changeset) do repo.changeset(changeset_class).by_pk(user.id, name: 'Jade') end let(:changeset_class) do Class.new(ROM::Changeset::Update[:users]) do map { |t| t.merge(name: "#{t[:name]} Doe") } end end let(:user) do repo.command(:create, repo.users).call(name: 'Jane') end it 'has data' do expect(changeset.to_h).to eql(name: '<NAME>') end it 'has relation restricted by pk' do expect(changeset.relation.dataset).to eql(repo.users.by_pk(user.id).dataset) end it 'can be commited' do expect(changeset.commit).to eql(id: 1, name: '<NAME>') end end end it 'raises ArgumentError when unknown type was used' do expect { repo.changeset(not_here: repo.users) }. to raise_error( ArgumentError, '+:not_here+ is not a valid changeset type. Must be one of: [:create, :update, :delete]' ) end it 'raises ArgumentError when unknown class was used' do klass = Class.new { def self.name 'SomeClass' end } expect { repo.changeset(klass) }. to raise_error(ArgumentError, /SomeClass/) end end <file_sep>module Dry::Initializer module ClassDSL attr_reader :config def [](**settings) Module.new do extend Dry::Initializer::ClassDSL include Dry::Initializer @config = settings end end def define(fn = nil, &block) mixin = Module.new { include InstanceDSL } builder = Builder.new Hash(config) builder.instance_exec(&(fn || block)) builder.call(mixin) mixin end private def extended(klass) super mixin = klass.send(:__initializer_mixin__) builder = klass.send(:__initializer_builder__, Hash(config)) builder.call(mixin) klass.include(InstanceDSL) # defines #initialize klass.include(mixin) # defines #__initialize__ (to be redefined) end def mixin(fn = nil, &block) define(fn, &block) end end end <file_sep>require 'set' require 'dry/core/class_attributes' module ROM module SQL class Schema < ROM::Schema # @api private class Inferrer extend Dry::Core::ClassAttributes defines :ruby_type_mapping, :numeric_pk_type, :db_type, :db_registry ruby_type_mapping( integer: Types::Int, string: Types::String, time: Types::Time, date: Types::Date, datetime: Types::Time, boolean: Types::Bool, decimal: Types::Decimal, float: Types::Float, blob: Types::Blob ).freeze numeric_pk_type Types::Serial db_registry Hash.new(self) CONSTRAINT_DB_TYPE = 'add_constraint'.freeze DECIMAL_REGEX = /(?:decimal|numeric)\((\d+)(?:,\s*(\d+))?\)/.freeze def self.inherited(klass) super Inferrer.db_registry[klass.db_type] = klass unless klass.name.nil? end def self.[](type) Class.new(self) { db_type(type) } end def self.get(type) db_registry[type] end def self.on_error(relation, e) warn "[#{relation}] failed to infer schema. " \ "Make sure tables exist before ROM container is set up. " \ "This may also happen when your migration tasks load ROM container, " \ "which is not needed for migrations as only the connection is required " \ "(#{e.message})" end # @api private def call(source, gateway) dataset = source.dataset columns = filter_columns(gateway.connection.schema(dataset)) all_indexes = indexes_for(gateway, dataset) fks = fks_for(gateway, dataset) inferred = columns.map do |(name, definition)| indexes = column_indexes(all_indexes, name) type = build_type(**definition, foreign_key: fks[name], indexes: indexes) if type type.meta(name: name, source: source) end end.compact [inferred, columns.map(&:first) - inferred.map { |attr| attr.meta[:name] }] end private def filter_columns(schema) schema.reject { |(_, definition)| definition[:db_type] == CONSTRAINT_DB_TYPE } end def build_type(primary_key:, db_type:, type:, allow_null:, foreign_key:, indexes:, **rest) if primary_key map_pk_type(type, db_type) else mapped_type = map_type(type, db_type, rest) if mapped_type read_type = mapped_type.meta[:read] mapped_type = mapped_type.optional if allow_null mapped_type = mapped_type.meta(foreign_key: true, target: foreign_key) if foreign_key mapped_type = mapped_type.meta(index: indexes) unless indexes.empty? if read_type && allow_null mapped_type.meta(read: read_type.optional) elsif read_type mapped_type.meta(read: read_type) else mapped_type end end end end def map_pk_type(_ruby_type, _db_type) self.class.numeric_pk_type.meta(primary_key: true) end def map_type(ruby_type, db_type, **kw) type = self.class.ruby_type_mapping[ruby_type] if db_type.is_a?(String) && db_type.include?('numeric') || db_type.include?('decimal') map_decimal_type(db_type) elsif db_type.is_a?(String) && db_type.include?('char') && kw[:max_length] type.meta(limit: kw[:max_length]) else type end end # @api private def fks_for(gateway, dataset) gateway.connection.foreign_key_list(dataset).each_with_object({}) do |definition, fks| column, fk = build_fk(definition) fks[column] = fk if fk end end # @api private def indexes_for(gateway, dataset) if gateway.connection.respond_to?(:indexes) gateway.connection.indexes(dataset) else # index listing is not implemented EMPTY_HASH end end # @api private def column_indexes(indexes, column) indexes.each_with_object(Set.new) do |(name, idx), indexes| indexes << name if idx[:columns][0] == column end end # @api private def build_fk(columns: , table: , **rest) if columns.size == 1 [columns[0], table] else # We don't have support for multicolumn foreign keys columns[0] end end # @api private def map_decimal_type(type) precision = DECIMAL_REGEX.match(type) if precision prcsn, scale = precision[1..2].map(&:to_i) self.class.ruby_type_mapping[:decimal].meta( precision: prcsn, scale: scale ) else self.class.ruby_type_mapping[:decimal] end end end end end end <file_sep>describe "definition" do shared_examples :initializer do |in_context| subject { Test::Foo.new(1, bar: 2) } it "sets variables when defined via `#{in_context}`" do expect(subject.instance_variable_get(:@foo)).to eql 1 expect(subject.instance_variable_get(:@bar)).to eql 2 end end it_behaves_like :initializer, "extend Dry::Initializer" do before do class Test::Foo extend Dry::Initializer param :foo option :bar end end end it_behaves_like :initializer, "extend Dry::Initializer::Mixin" do before do class Test::Foo extend Dry::Initializer::Mixin param :foo option :bar end end end it_behaves_like :initializer, "extend Dry::Initializer[undefined: false]" do before do class Test::Foo extend Dry::Initializer[undefined: false] param :foo option :bar end end end it_behaves_like :initializer, "include Dry::Initializer with block" do before do class Test::Foo include Dry::Initializer.define { param :foo option :bar } end end end it_behaves_like :initializer, "include Dry::Initializer with lambda" do before do class Test::Foo include Dry::Initializer.define -> do param :foo option :bar end end end end it_behaves_like :initializer, "include Dry::Initializer[undefined: false]" do before do class Test::Foo include Dry::Initializer[undefined: false].define { param :foo option :bar } end end end it_behaves_like :initializer, "include Dry::Initializer::Mixin" do before do class Test::Foo include Dry::Initializer::Mixin.define { param :foo option :bar } end end end end <file_sep>require 'rom/relation' require 'rom/command' require 'rom/registry' require 'rom/command_registry' require 'rom/mapper_registry' require 'rom/container' require 'rom/setup/finalize/finalize_commands' require 'rom/setup/finalize/finalize_relations' require 'rom/setup/finalize/finalize_mappers' # temporary require 'rom/configuration_dsl/relation' module ROM # This giant builds an container using defined classes for core parts of ROM # # It is used by the setup object after it's done gathering class definitions # # @private class Finalize attr_reader :gateways, :repo_adapter, :datasets, :gateway_map, :relation_classes, :mapper_classes, :mapper_objects, :command_classes, :plugins, :config # @api private def initialize(options) @gateways = options.fetch(:gateways) @gateway_map = options.fetch(:gateway_map) @relation_classes = options.fetch(:relation_classes) @command_classes = options.fetch(:command_classes) mappers = options.fetch(:mappers, []) @mapper_classes = mappers.select { |mapper| mapper.is_a?(Class) } @mapper_objects = (mappers - @mapper_classes).reduce(:merge) || {} @config = options.fetch(:config) @plugins = options.fetch(:plugins) initialize_datasets end # Return adapter identifier for a given gateway object # # @return [Symbol] # # @api private def adapter_for(gateway) @gateway_map.fetch(gateways[gateway]) end # Run the finalization process # # This creates relations, mappers and commands # # @return [Container] # # @api private def run! infer_relations mappers = load_mappers relations = load_relations(mappers) commands = load_commands(relations) container = Container.new(gateways, relations, mappers, commands) container.freeze container end private # Infer all datasets using configured gateways # # Not all gateways can do that, by default an empty array is returned # # @return [Hash] gateway name => array with datasets map # # @api private def initialize_datasets @datasets = gateways.each_with_object({}) do |(key, gateway), h| infer_relations = config.gateways && config.gateways[key] && config.gateways[key][:infer_relations] h[key] = gateway.schema if infer_relations end end # Build entire relation registry from all known relation subclasses # # This includes both classes created via DSL and explicit definitions # # @api private def load_relations(mappers) FinalizeRelations.new( gateways, relation_classes, mappers: mappers, plugins: plugins.select(&:relation?) ).run! end # @api private def load_mappers FinalizeMappers.new(mapper_classes, mapper_objects).run! end # Build entire command registries # # This includes both classes created via DSL and explicit definitions # # @api private def load_commands(relations) FinalizeCommands.new(relations, gateways, command_classes).run! end # For every dataset infered from gateways we infer a relation # # Relations explicitly defined are being skipped # # @api private def infer_relations datasets.each do |gateway, schema| schema.each do |name| if infer_relation?(gateway, name) klass = ROM::ConfigurationDSL::Relation.build_class(name, adapter: adapter_for(gateway)) klass.gateway(gateway) klass.dataset(name, deprecation: false) @relation_classes << klass else next end end end end def infer_relation?(gateway, name) inferrable_relations(gateway).include?(name) && relation_classes.none? { |klass| klass.dataset == name } end def inferrable_relations(gateway) gateway_config = config.gateways[gateway] schema = gateways[gateway].schema allowed = gateway_config[:inferrable_relations] || schema skipped = gateway_config[:not_inferrable_relations] || [] schema & allowed - skipped end end end <file_sep># frozen_string_literal: true require "better_errors" require "binding_of_caller" Hanami.plugin do middleware.use BetterErrors::Middleware BetterErrors.application_root = Hanami.root.to_s end <file_sep>require 'rom/schema' require 'rom/sql/order_dsl' require 'rom/sql/group_dsl' require 'rom/sql/projection_dsl' require 'rom/sql/restriction_dsl' module ROM module SQL class Schema < ROM::Schema # @!attribute [r] primary_key_name # @return [Symbol] The name of the primary key. This is set because in # most of the cases relations don't have composite pks attr_reader :primary_key_name # @!attribute [r] primary_key_names # @return [Array<Symbol>] A list of all pk names attr_reader :primary_key_names # @api private def initialize(*) super initialize_primary_key_names end # @api public def restriction(&block) RestrictionDSL.new(self).call(&block) end # @api public def order(&block) OrderDSL.new(self).call(&block) end # @api public def group(&block) GroupDSL.new(self).call(&block) end # Return a new schema with attributes marked as qualified # # @return [Schema] # # @api public def qualified new(map(&:qualified)) end # Return a new schema with attributes restored to canonical form # # @return [Schema] # # @api public def canonical new(map(&:canonical)) end # @api public def project(*names, &block) if block super(*(names + ProjectionDSL.new(self).(&block))) else super end end # @api private def project_pk project(*primary_key_names) end # @api private def project_fk(mapping) new(rename(mapping).map(&:foreign_key)) end # @api public def join(other) merge(other.joined) end # @api public def joined new(map(&:joined)) end # Create a new relation based on the schema definition # # @param [Relation] relation The source relation # # @return [Relation] # # @api public def call(relation) relation.new(relation.dataset.select(*self), schema: self) end # Return an empty schema # # @return [Schema] # # @api public def empty new(EMPTY_ARRAY) end # @api private def finalize!(*args) super do initialize_primary_key_names end end # @api private def initialize_primary_key_names if primary_key.size > 0 @primary_key_name = primary_key[0].meta[:name] @primary_key_names = primary_key.map { |type| type.meta[:name] } end end end end end require 'rom/sql/schema/dsl' <file_sep>require 'rom/sql/dsl' require 'rom/sql/function' module ROM module SQL # @api private class ProjectionDSL < DSL # @api public def `(value) expr = ::Sequel.lit(value) ::ROM::SQL::Attribute.new(type(:string)).meta(sql_expr: expr) end # @api private def respond_to_missing?(name, include_private = false) super || type(name) end private # @api private def method_missing(meth, *args, &block) if schema.key?(meth) schema[meth] else type = type(meth) if type ::ROM::SQL::Function.new(type) else super end end end end end end <file_sep>module Dry module Initializer require_relative "initializer/exceptions/default_value_error" require_relative "initializer/exceptions/type_constraint_error" require_relative "initializer/exceptions/params_order_error" require_relative "initializer/attribute" require_relative "initializer/param" require_relative "initializer/option" require_relative "initializer/builder" require_relative "initializer/instance_dsl" require_relative "initializer/class_dsl" # rubocop: disable Style/ConstantName Mixin = self # for compatibility to versions below 0.12 # rubocop: enable Style/ConstantName UNDEFINED = Object.new.tap do |obj| obj.define_singleton_method(:inspect) { "Dry::Initializer::UNDEFINED" } end.freeze extend Dry::Initializer::ClassDSL def param(*args) __initializer_builder__.param(*args).call(__initializer_mixin__) end def option(*args) __initializer_builder__.option(*args).call(__initializer_mixin__) end private def __initializer_mixin__ @__initializer_mixin__ ||= Module.new end def __initializer_builder__(**settings) @__initializer_builder__ ||= Dry::Initializer::Builder.new(settings) end def inherited(klass) builder = @__initializer_builder__.dup mixin = Module.new klass.instance_variable_set :@__initializer_builder__, builder klass.instance_variable_set :@__initializer_mixin__, mixin builder.call(mixin) klass.include mixin super end end end <file_sep>module ROM class Repository VERSION = '1.4.0'.freeze end end <file_sep>module Dry::Initializer class ParamsOrderError < RuntimeError def initialize(required, optional) super "Optional param '#{optional}'" \ " should not preceed required '#{required}'" end end end <file_sep>require 'rom/initializer' module ROM module SQL module Plugin module Pagination class Pager extend Initializer include Dry::Equalizer(:dataset, :options) param :dataset option :current_page, default: -> { 1 } option :per_page def next_page num = current_page + 1 num if total_pages >= num end def prev_page num = current_page - 1 num if num > 0 end def total dataset.unlimited.count end def total_pages (total / per_page.to_f).ceil end def at(dataset, current_page, per_page = self.per_page) current_page = current_page.to_i per_page = per_page.to_i self.class.new( dataset.offset((current_page-1)*per_page).limit(per_page), current_page: current_page, per_page: per_page ) end alias_method :limit_value, :per_page end def self.included(klass) super klass.class_eval do defines :per_page option :pager, default: -> { Pager.new(dataset, per_page: self.class.per_page) } end end # Paginate a relation # # @example # rom.relation(:users).class.per_page(10) # rom.relation(:users).page(1) # rom.relation(:users).pager # => info about pagination # # @return [Relation] # # @api public def page(num) next_pager = pager.at(dataset, num) new(next_pager.dataset, pager: next_pager) end # Set limit for pagination # # @example # rom.relation(:users).page(2).per_page(10) # # @api public def per_page(num) next_pager = pager.at(dataset, pager.current_page, num) new(next_pager.dataset, pager: next_pager) end end end end end <file_sep>require 'rom/sql/schema/inferrer' module ROM module SQL class Schema class MysqlInferrer < Inferrer[:mysql] end end end end <file_sep># this is needed for guard to work, not sure why :( require "bundler" Bundler.setup if RUBY_ENGINE == 'ruby' && ENV['COVERAGE'] == 'true' require 'yaml' rubies = YAML.load(File.read(File.join(__dir__, '..', '.travis.yml')))['rvm'] latest_mri = rubies.select { |v| v =~ /\A\d+\.\d+.\d+\z/ }.max if RUBY_VERSION == latest_mri require 'simplecov' SimpleCov.start do add_filter '/spec/' end end end require 'rom-sql' require 'rom-repository' begin require 'byebug' rescue LoadError end root = Pathname(__FILE__).dirname LOGGER = Logger.new(File.open('./log/test.log', 'a')) require 'dry/core/deprecations' Dry::Core::Deprecations.set_logger!(root.join('../log/deprecations.log')) # Make inference errors quiet class ROM::SQL::Schema::Inferrer def self.on_error(*args) # shush end end # Namespace holding all objects created during specs module Test def self.remove_constants constants.each(&method(:remove_const)) end end warning_api_available = RUBY_VERSION >= '2.4.0' module SileneceWarnings def warn(str) if str['/sequel/'] || str['/rspec-core'] nil else super end end end DB_URI = if defined? JRUBY_VERSION 'jdbc:postgresql://localhost/rom_repository' else 'postgres://localhost/rom_repository' end Warning.extend(SileneceWarnings) if warning_api_available RSpec.configure do |config| config.disable_monkey_patching! config.warnings = warning_api_available config.after do Test.remove_constants end Dir[root.join('support/*.rb').to_s].each do |f| require f end Dir[root.join('shared/*.rb').to_s].each do |f| require f end config.include(MapperRegistry) end <file_sep>module Helpers def qualified_attribute(*args) ROM::SQL::QualifiedAttribute[*args] end def assoc_name(*args) ROM::SQL::Association::Name[*args] end def define_schema(name, attrs) ROM::SQL::Schema.define( name, attributes: attrs.map { |key, value| value.meta(name: key, source: ROM::Relation::Name.new(name)) }, attr_class: ROM::SQL::Attribute ) end def define_type(name, id, **opts) ROM::SQL::Attribute.new(ROM::Types.const_get(id).meta(name: name, **opts)) end end <file_sep>require 'spec_helper' RSpec.describe 'Using legacy sequel api', :sqlite do include_context 'users' before do conf.relation(:users) do include ROM::SQL::Relation::SequelAPI end users.insert(name: 'Jane') end describe '#select' do it 'selects columns' do expect(users.select(Sequel.qualify(:users, :id), Sequel.qualify(:users, :name)).first). to eql(id: 1, name: 'Jane') end it 'supports legacy blocks' do expect(users.select { count(id).as(:count) }.group(:id).first).to eql(count: 1) end end describe '#where' do it 'restricts relation' do expect(users.where(name: 'Jane').first).to eql(id: 1, name: 'Jane') end end describe '#order' do it 'orders relation' do expect(users.order(Sequel.qualify(:users, :name)).first).to eql(id: 1, name: 'Jane') end end end <file_sep>RSpec.describe ROM::SQL::Association::OneToOneThrough do include_context 'users' include_context 'accounts' subject(:assoc) { ROM::SQL::Association::OneToOneThrough.new(:users, :cards, through: :accounts) } with_adapters do before do conf.relation(:accounts) do schema do attribute :id, ROM::SQL::Types::Serial attribute :user_id, ROM::SQL::Types::ForeignKey(:users) attribute :number, ROM::SQL::Types::String attribute :balance, ROM::SQL::Types::Decimal associations do one_to_many :cards one_to_many :subscriptions, through: :cards end end end conf.relation(:cards) do schema do attribute :id, ROM::SQL::Types::Serial attribute :account_id, ROM::SQL::Types::ForeignKey(:accounts) attribute :pan, ROM::SQL::Types::String associations do one_to_many :subscriptions end end end conf.relation(:subscriptions) do schema do attribute :id, ROM::SQL::Types::Serial attribute :card_id, ROM::SQL::Types::ForeignKey(:cards) attribute :service, ROM::SQL::Types::String associations do many_to_one :cards end end end end describe '#result' do specify { expect(ROM::SQL::Association::OneToOneThrough.result).to be(:one) } end describe '#call' do it 'prepares joined relations' do relation = assoc.call(container.relations) expect(relation.schema.map(&:name)).to eql(%i[id account_id pan user_id]) expect(relation.to_a).to eql([id: 1, account_id: 1, pan: '*6789', user_id: 1]) end end describe ':through another assoc' do subject(:assoc) do ROM::SQL::Association::OneToOneThrough.new(:users, :subscriptions, through: :accounts) end let(:account_assoc) do ROM::SQL::Association::OneToOneThrough.new(:accounts, :subscriptions, through: :cards) end it 'prepares joined relations through other association' do relation = assoc.call(container.relations) expect(relation.schema.map(&:name)).to eql(%i[id card_id service user_id]) expect(relation.to_a).to eql([id: 1, card_id: 1, service: 'aws', user_id: 1]) end end describe ROM::Plugins::Relation::SQL::AutoCombine, '#for_combine' do it 'preloads relation based on association' do relation = cards.for_combine(assoc).call(users.call) expect(relation.to_a).to eql([id: 1, account_id: 1, pan: '*6789', user_id: 1]) end end end end
459c10f3fbd782511a4c297e686cd82c40a454af
[ "Markdown", "Ruby" ]
109
Ruby
okamotchan/what_is_hanami
25baba9ae1964f851e9969ab63c3493c7a5ae5ee
c701ba006690f77198e88deb64ed244e3550b497
refs/heads/main
<file_sep>import React from 'react'; import {NavigationContainer} from '@react-navigation/native'; import {createDrawerNavigator} from '@react-navigation/drawer'; import {createStackNavigator} from '@react-navigation/stack'; import {CityList, RestaurantDetail, About, RestaurantList} from './pages'; const Stack = createStackNavigator(); const Drawer = createDrawerNavigator(); const Home = () => { return ( <Stack.Navigator> <Stack.Screen name="Cities" component={CityList} options={{headerShown: false}} /> <Stack.Screen name="Restaurants" component={RestaurantList} options={{headerShown: false}} /> <Stack.Screen name="Details" component={RestaurantDetail} options={{headerShown: false}} /> </Stack.Navigator> ); }; const Router = () => { return ( <NavigationContainer> <Drawer.Navigator> <Drawer.Screen name="Home" component={Home} /> <Drawer.Screen name="About" component={About} /> </Drawer.Navigator> </NavigationContainer> ); }; export default Router; <file_sep><h1 align="center">YELP App</h1> ## Overview <img src="src/assets/yelpapp.gif" height="500"> ### Built With - [React-native](https://reactnative.dev/) ## Features This app comprises use of Stack Navigation and RESTFUL Web APIs - User can either scroll or type letters into search bar to choose a city. - When the user finds the desired city and taps on it, a new page opens showing a list of restaurants in chosen city. Information here comprises an image and the name of the restaurants. Since the API source does not offer different images, only a default graphical was used all through the app. - The user either scrolls or types letters to search bar to choose a restaurant. - When the user taps on the image of the chosen restaurent, a new page showing the detailed information of the restaurant opens. ## How To Use To use this application, the packages for navigation and for APIs (axios) should be installed prior to running the app. From your command line: ``` npm install @react-navigation/native For expo : expo install react-native-gesture-handler react-native-reanimated react-native-screens react-native-safe-area-context @react-native-community/masked-view For bare React-native: npm install react-native-reanimated react-native-gesture-handler react-native-screens react-native-safe-area-context @react-native-community/masked-view For IOS: npx pod-install ios npm install @react-navigation/stack npm install axios ```
4207c3079550463c5411a62b7e10559a2bbc3e20
[ "JavaScript", "Markdown" ]
2
JavaScript
furkan-cloud/city-yelp-app-api
31a84b835148d385aa5b3897c96f02d7618b065d
6cc5f9a4f298e158f2bad2e100042b307895ebeb
refs/heads/master
<repo_name>AndrasNyiri/AllInOneGameServer<file_sep>/LightEngineCore/PhysicsEngine/Dynamics/Handlers/PreSolveHandler.cs using LightEngineCore.PhysicsEngine.Collision.ContactSystem; using LightEngineCore.PhysicsEngine.Collision.Narrowphase; namespace LightEngineCore.PhysicsEngine.Dynamics.Handlers { public delegate void PreSolveHandler(Contact contact, ref Manifold oldManifold); }<file_sep>/LightEngineSerializeable/SerializableClasses/DeckGameObjectBind.cs using LightEngineSerializeable.SerializableClasses.DatabaseModel; namespace LightEngineSerializeable.SerializableClasses { public class DeckGameObjectBind : SerializableModel { public byte DeckIndex { get; set; } public ushort GameObjectId { get; set; } } } <file_sep>/LightEngineCore/PhysicsEngine/Dynamics/Handlers/PostSolveHandler.cs using LightEngineCore.PhysicsEngine.Collision.ContactSystem; using LightEngineCore.PhysicsEngine.Dynamics.Solver; namespace LightEngineCore.PhysicsEngine.Dynamics.Handlers { public delegate void PostSolveHandler(Contact contact, ContactVelocityConstraint impulse); }<file_sep>/LightGameServer/NetworkHandling/PendingGamePool.cs using System; using System.Collections.Generic; using LightGameServer.NetworkHandling.Model; namespace LightGameServer.NetworkHandling { class PendingGamePool { private readonly List<PeerInfo> _pendingPool = new List<PeerInfo>(); private const int LADDER_SCORE_MAX_DIFF = 100; private const int PENDING_WAIT_TIME = 2; public void AddPlayer(PeerInfo playerInfo) { playerInfo.PendingPoolJoinTime = DateTime.Now; _pendingPool.Add(playerInfo); } public void RemoveLeaver(PeerInfo peerInfo) { _pendingPool.Remove(peerInfo); } public List<PeerInfo> ResolveWaiters() { List<PeerInfo> waiters = new List<PeerInfo>(); foreach (var peerInfo in _pendingPool) { var resolveTime = peerInfo.PendingPoolJoinTime.AddSeconds(PENDING_WAIT_TIME); if (DateTime.Now > resolveTime) { waiters.Add(peerInfo); } } waiters.ForEach(w => { _pendingPool.Remove(w); }); return waiters; } public List<PlayerPair> ResolvePendings() { List<PlayerPair> pairs = new List<PlayerPair>(); foreach (var playerPeerInfo in _pendingPool) { if (InPairs(pairs, playerPeerInfo)) continue; List<PeerInfo> candidates = new List<PeerInfo>(); foreach (var otherPeerInfo in _pendingPool) { if (playerPeerInfo == otherPeerInfo || InPairs(pairs, otherPeerInfo)) continue; if (Math.Abs(playerPeerInfo.PlayerData.LadderScore - otherPeerInfo.PlayerData.LadderScore) < LADDER_SCORE_MAX_DIFF) { candidates.Add(otherPeerInfo); } } PeerInfo match = null; int minDif = int.MaxValue; foreach (var candidate in candidates) { var diff = Math.Abs(playerPeerInfo.PlayerData.LadderScore - candidate.PlayerData.LadderScore); if (diff < minDif) { match = candidate; minDif = diff; } } if (match != null) { pairs.Add(new PlayerPair { PlayerOne = playerPeerInfo, PlayerTwo = match }); } } pairs.ForEach(p => { _pendingPool.Remove(p.PlayerOne); _pendingPool.Remove(p.PlayerTwo); }); return pairs; } private bool InPairs(List<PlayerPair> pairs, PeerInfo peerInfo) { foreach (var pair in pairs) { if (pair.PlayerOne == peerInfo || pair.PlayerTwo == peerInfo) { return true; } } return false; } } } <file_sep>/LightEngineSerializeable/Utils/Serializers/ObjectSerializationUtil.cs using System; using System.IO; using System.Reflection; using System.Runtime.Serialization; using System.Runtime.Serialization.Formatters.Binary; using LightEngineSerializeable.LiteNetLib.Utils; using LightEngineSerializeable.SerializableClasses.Enums; namespace LightEngineSerializeable.Utils.Serializers { public class ObjectSerializationUtil { public static byte[] ObjectToByteArray(Object obj) { if (obj == null) return null; BinaryFormatter bf = new BinaryFormatter(); MemoryStream ms = new MemoryStream(); bf.Serialize(ms, obj); return ms.ToArray(); } public static Object ByteArrayToObject(byte[] arrBytes) { MemoryStream memStream = new MemoryStream(); BinaryFormatter binForm = new BinaryFormatter(); binForm.Binder = new PreMergeToMergedDeserializationBinder(); memStream.Write(arrBytes, 0, arrBytes.Length); memStream.Seek(0, SeekOrigin.Begin); Object obj = binForm.Deserialize(memStream); return obj; } public static NetDataWriter SerializeObjects(object[] parameters) { NetDataWriter writer = new NetDataWriter(true); var ts = new TypeSwitch() .Case((string x) => { writer.Put(x); }) .Case((int x) => { writer.Put(x); }) .Case((uint x) => { writer.Put(x); }) .Case((float x) => { writer.Put(x); }) .Case((long x) => { writer.Put(x); }) .Case((ulong x) => { writer.Put(x); }) .Case((byte x) => { writer.Put(x); }) .Case((short x) => { writer.Put(x); }) .Case((ushort x) => { writer.Put(x); }) .Case((double x) => { writer.Put(x); }) .Case((bool x) => { writer.Put(x); }) .Case((byte[] x) => { writer.PutBytesWithLength(x); }); foreach (var data in parameters) { ts.Switch(data); } return writer; } sealed class PreMergeToMergedDeserializationBinder : SerializationBinder { public override Type BindToType(string assemblyName, string typeName) { Type typeToDeserialize = null; String exeAssembly = Assembly.GetExecutingAssembly().FullName; typeToDeserialize = Type.GetType(String.Format("{0}, {1}", typeName, exeAssembly)); return typeToDeserialize; } } } } <file_sep>/LightEngineSerializeable/SerializableClasses/Enums/PlayerType.cs namespace LightEngineSerializeable.SerializableClasses.Enums { public enum PlayerType { PlayerOne, PlayerTwo } }<file_sep>/LightGameServer/ConsoleStuff/MenuOption.cs using System; namespace LightGameServer.ConsoleStuff { public class MenuOption { public string DisplayText { get; set; } public Action Action { get; set; } } } <file_sep>/LightGameServer/NetworkHandling/Model/PlayerPair.cs namespace LightGameServer.NetworkHandling.Model { class PlayerPair { public PeerInfo PlayerOne { get; set; } public PeerInfo PlayerTwo { get; set; } } } <file_sep>/LightEngineSerializeable/SerializableClasses/GameModel/RequestEvents/PlayUnitAbilityRequest.cs using LightEngineSerializeable.SerializableClasses.Enums; namespace LightEngineSerializeable.SerializableClasses.GameModel.RequestEvents { public class PlayUnitAbilityRequest : RequestEvent { public float DirectionX { get; set; } public float DirectionY { get; set; } public PlayUnitAbilityRequest() : base(RequestEventType.PlayUnitAbility) { } } } <file_sep>/LightEngineSerializeable/SerializableClasses/GameModel/GameEvent.cs using LightEngineSerializeable.SerializableClasses.DatabaseModel; using LightEngineSerializeable.SerializableClasses.Enums; namespace LightEngineSerializeable.SerializableClasses.GameModel { [System.Serializable] public class GameEvent : SerializableModel { public GameEventType Type { get; protected set; } public float TimeStamp { get; set; } public GameEvent(GameEventType type) { this.Type = type; } } } <file_sep>/LightEngineSerializeable/SerializableClasses/DatabaseModel/PlayerUnit.cs namespace LightEngineSerializeable.SerializableClasses.DatabaseModel { [System.Serializable] public class PlayerUnit : SerializableModel { public short UnitId { get; set; } public int Amount { get; set; } } } <file_sep>/LightGameServer/Game/Prefabs/Units/UnitFactory.cs using LightEngineCore.PhysicsEngine.Primitives; using LightGameServer.Game.Model; namespace LightGameServer.Game.Prefabs.Units { static class UnitFactory { public static Unit CreateUnit(short unitId, Match match, PlayerInfo playerInfo, Vector2 pos) { switch (unitId) { case 1: return new Caster1(match, playerInfo, pos); case 2: return new Caster2(match, playerInfo, pos); case 3: return new Caster3(match, playerInfo, pos); case 4: return new Caster4(match, playerInfo, pos); } return null; } } } <file_sep>/LightEngineSerializeable/SerializableClasses/Enums/NetworkObjectType.cs namespace LightEngineSerializeable.SerializableClasses.Enums { public enum NetworkObjectType { Caster1, Caster2, Caster3, Caster4, FireBall } } <file_sep>/LightEngineCore/PhysicsEngine/Templates/Shapes/CircleShapeTemplate.cs using LightEngineCore.PhysicsEngine.Collision.Shapes; using LightEngineCore.PhysicsEngine.Primitives; namespace LightEngineCore.PhysicsEngine.Templates.Shapes { public class CircleShapeTemplate : ShapeTemplate { public CircleShapeTemplate() : base(ShapeType.Circle) { } /// <summary> /// Get or set the position of the circle /// </summary> public Vector2 Position { get; set; } } }<file_sep>/LightEngineCore/Components/GameObject.cs using System; using System.Collections.Generic; using LightEngineCore.Configuration; using LightEngineCore.Loop; using LightEngineCore.PhysicsEngine.Collision.ContactSystem; using LightEngineCore.PhysicsEngine.Dynamics; using Vector2 = LightEngineCore.PhysicsEngine.Primitives.Vector2; namespace LightEngineCore.Components { public class GameObject { public delegate void OnCollidedWithGameObjectDelegate(GameObject go); public delegate void OnBelowGroundDelegate(); public OnCollidedWithGameObjectDelegate onCollidedWithGameObject; public GameLoop match; public List<Behaviour> components = new List<Behaviour>(); public string name; public ushort id; public GameObject(GameLoop match, string name = "", params Behaviour[] initBehaviours) { this.match = match; match.RegisterGameObject(this); this.name = name; if (string.IsNullOrEmpty(name)) { this.name = GetType().ToString(); } foreach (var component in initBehaviours) { AddComponent(component); } } public void Assign(GameLoop gl) { this.match = gl; } public virtual void Update() { foreach (var component in components) { component.Update(); } } public GameObject AddComponent(Behaviour behaviour) { behaviour.Assign(this); this.components.Add(behaviour); return this; } public GameObject AddComponent<T>() where T : Behaviour, new() { T newComponent = new T(); newComponent.Assign(this); this.components.Add(newComponent); return this; } public T GetComponent<T>() where T : Behaviour { foreach (var x in this.components) { if (!(x is T)) continue; return (T)x; } return default(T); } public Vector2 Pos { get { var rb = GetComponent<Rigidbody>(); return rb != null ? rb.body.Position : default(Vector2); } } public float Rot { get { var rb = GetComponent<Rigidbody>(); return rb != null ? rb.body.Rotation : 0f; } } public virtual void Draw() { try { Vector2 topLeft = Settings.drawOrigin + new Vector2((float)Math.Floor(Pos.X), (float)Math.Ceiling(Pos.Y)); Console.SetCursorPosition((int)topLeft.X, (int)topLeft.Y); Console.Write("B"); } catch (ArgumentOutOfRangeException) { } } public void InvokeCollidedDelegate(GameObject go) { if (onCollidedWithGameObject != null) onCollidedWithGameObject.Invoke(go); } public virtual void Destroy() { match.Destroy(this); } } } <file_sep>/LightEngineCore/PhysicsEngine/Collision/Narrowphase/ClipVertex.cs using LightEngineCore.PhysicsEngine.Collision.ContactSystem; using LightEngineCore.PhysicsEngine.Primitives; namespace LightEngineCore.PhysicsEngine.Collision.Narrowphase { /// <summary> /// Used for computing contact manifolds. /// </summary> internal struct ClipVertex { public ContactID ID; public Vector2 V; } }<file_sep>/LightGameServer/ConsoleStuff/ConsoleMEnu.cs using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace LightGameServer.ConsoleStuff { public class ConsoleMenu { private readonly List<MenuOption> _options; public ConsoleMenu(params MenuOption[] options) { _options = options.ToList(); } public ConsoleMenu Add(string displayText, Action action) { _options.Add(new MenuOption { DisplayText = displayText, Action = action }); return this; } public void Update() { if (Console.KeyAvailable) { var input = Console.ReadKey(true); if (char.IsDigit(input.KeyChar)) { var result = int.Parse(input.KeyChar.ToString()); int index = result - 1; if (index >= 0 && index < _options.Count) { _options[index].Action(); Display(); } } } } public void Display() { Console.Clear(); StringBuilder menuBuilder = new StringBuilder(); for (var i = 0; i < _options.Count; i++) { var menuOption = _options[i]; menuBuilder.AppendLine(string.Format("{0}. {1}", i + 1, menuOption.DisplayText)); } Console.WriteLine(menuBuilder.ToString()); } } } <file_sep>/LightGameServer/NetworkHandling/Server.cs using System; using System.Collections.Generic; using System.Runtime.Remoting.Channels; using System.Threading; using LightEngineSerializeable.LiteNetLib; using LightEngineSerializeable.SerializableClasses.DatabaseModel; using LightEngineSerializeable.SerializableClasses.Enums; using LightEngineSerializeable.Utils; using LightGameServer.ConsoleStuff; using LightGameServer.Database; using LightGameServer.Game; using LightGameServer.NetworkHandling.Handlers; using LightGameServer.NetworkHandling.Model; using NLog; namespace LightGameServer.NetworkHandling { class Server { #region Singleton private static Server _instance; public static Server Get() { if (_instance == null) _instance = new Server(); return _instance; } #endregion private const string CONNECTION_KEY = "<KEY>;>K]7{vUB[R!B\"?>sV!&d~b(G-pYW%5&,6_J5>Hky95.DTG_dhM^x]ph(&.\\.Xc(B.fFGW`e_"; private const int PORT = 60001; public const int UPDATE_TIME = 33; public Dictionary<NetPeer, PeerInfo> PeerInfos { get; } public PendingGamePool PendingGamePool { get; } public GameManager GameManager { get; } public QueryRepository QueryRepository { get; } public DataStore DataStore { get; } private readonly Logger _logger = LogManager.GetCurrentClassLogger(); public Server() { PeerInfos = new Dictionary<NetPeer, PeerInfo>(); PendingGamePool = new PendingGamePool(); GameManager = new GameManager(); QueryRepository = new QueryRepository(); DataStore = new DataStore(QueryRepository); } public void Start() { EventBasedNetListener listener = new EventBasedNetListener(); NetManager server = new NetManager(listener, 10000, CONNECTION_KEY); server.Start(PORT); server.UpdateTime = UPDATE_TIME; Console.WriteLine("Game server is listening..."); bool running = true; ConsoleMenu consoleMenu = new ConsoleMenu() .Add("Exit", () => { running = false; }) .Add("Refresh static data cache", () => { DataStore.Refresh(); }); listener.NetworkErrorEvent += (point, code) => { _logger.Error(string.Format("Error occured. Endpoint:{0} , ErrorCode: {1}", point, code)); }; listener.PeerConnectedEvent += peer => { Console.WriteLine("We got connection: {0}", peer.EndPoint); PeerInfos.Add(peer, new PeerInfo()); }; listener.PeerDisconnectedEvent += (peer, info) => { var playerData = PeerInfos.ContainsKey(peer) ? PeerInfos[peer].PlayerData : null; if (playerData != null) { var match = GameManager.GetMatch(playerData.PlayerId); if (match != null) GameManager.StopMatch(match); } PendingGamePool.RemoveLeaver(PeerInfos[peer]); PeerInfos.Remove(peer); Console.WriteLine("Peer disconnected: {0}", peer.EndPoint); }; listener.NetworkReceiveEvent += (peer, reader) => { NetworkCommandHandler.New(reader, peer).HandleReceived(); }; consoleMenu.Display(); while (running) { server.PollEvents(); ReslovePendingPool(); consoleMenu.Update(); Thread.Sleep(UPDATE_TIME); } server.Stop(); } private void ReslovePendingPool() { var pairs = PendingGamePool.ResolvePendings(); foreach (var playerPair in pairs) { DataSender.New(playerPair.PlayerOne.NetPeer).Send(NetworkCommand.GameStarted, SendOptions.ReliableOrdered, playerPair.PlayerTwo.PlayerData.Name); DataSender.New(playerPair.PlayerTwo.NetPeer).Send(NetworkCommand.GameStarted, SendOptions.ReliableOrdered, playerPair.PlayerOne.PlayerData.Name); GameManager.StartMatch(playerPair.PlayerOne, playerPair.PlayerTwo); } var waiters = PendingGamePool.ResolveWaiters(); foreach (var waiter in waiters) { DataSender.New(waiter.NetPeer) .Send(NetworkCommand.GameStarted, SendOptions.ReliableOrdered, "BOT"); GameManager.StartMatch(waiter); } } public void AddToPendingPool(NetPeer peer) { PendingGamePool.AddPlayer(PeerInfos[peer]); } } } <file_sep>/LightEngineSerializeable/SerializableClasses/GameModel/GameEvents/NetworkObjectDestroyEvent.cs using LightEngineSerializeable.SerializableClasses.Enums; namespace LightEngineSerializeable.SerializableClasses.GameModel.GameEvents { public class NetworkObjectDestroyEvent : GameEvent { public ushort Id { get; set; } public NetworkObjectDestroyEvent() : base(GameEventType.NetworkObjectDestroy) { } } } <file_sep>/LightEngineCore/PhysicsEngine/Collision/Handlers/OnSeparationHandler.cs using LightEngineCore.PhysicsEngine.Collision.ContactSystem; using LightEngineCore.PhysicsEngine.Dynamics; namespace LightEngineCore.PhysicsEngine.Collision.Handlers { public delegate void OnSeparationHandler(Fixture fixtureA, Fixture fixtureB, Contact contact); }<file_sep>/LightGameServer/Game/GameManager.cs using System.Collections.Generic; using LightEngineCore.Configuration; using LightEngineCore.Loop; using LightGameServer.NetworkHandling.Model; namespace LightGameServer.Game { class GameManager { private readonly List<Match> _matches = new List<Match>(); private readonly LoopManager _loopManager = new LoopManager(Settings.simulatedThreadCount); public void StartMatch(PeerInfo playerOne, PeerInfo playerTwo) { Match newMatch = new Match(_loopManager.StartLoop(), playerOne, playerTwo); _matches.Add(newMatch); } public void StartMatch(PeerInfo playerOne) { Match newMatch = new Match(_loopManager.StartLoop(), playerOne, null); _matches.Add(newMatch); } public void StopMatch(Match match) { _loopManager.StopLoop(match.gameLoop); _matches.Remove(match); } public Match GetMatch(uint playerId) { foreach (var match in _matches) { if (match.playerOne != null && match.playerOne.PeerInfo.PlayerData != null && match.playerOne.PeerInfo.PlayerData.PlayerId == playerId || match.playerTwo != null && match.playerTwo.PeerInfo.PlayerData != null && match.playerTwo.PeerInfo.PlayerData.PlayerId == playerId) { return match; } } return null; } } } <file_sep>/LightEngineCore/PhysicsEngine/Dynamics/Handlers/ControllerHandler.cs using LightEngineCore.PhysicsEngine.Extensions.Controllers.ControllerBase; namespace LightEngineCore.PhysicsEngine.Dynamics.Handlers { public delegate void ControllerHandler(Controller controller); }<file_sep>/LightGameServer/Game/Behaviours/Scripts/Jump.cs using LightEngineCore.Components; using LightEngineCore.PhysicsEngine.Primitives; using MathHelper = LightEngineCore.Common.MathHelper; namespace LightGameServer.Game.Behaviours.Scripts { class Jump : Behaviour { public float jumpDelay = 1f; private float _jumpTime; public override void Update() { if (this.gameObject.match.Time > _jumpTime && this.gameObject.GetComponent<Rigidbody>().body.LinearVelocity.Length() < 0.3f) { _jumpTime = this.gameObject.match.Time + jumpDelay; this.gameObject.GetComponent<Rigidbody>().body.ApplyLinearImpulse(new Vector2(MathHelper.NextFloat(-15f, 15f), MathHelper.NextFloat(-15f, 15f))); } } } } <file_sep>/LightEngineSerializeable/Utils/TypeSwitch.cs using System; using System.Collections.Generic; namespace LightEngineSerializeable.Utils { public class TypeSwitch { private readonly Dictionary<Type, Action<object>> _matches = new Dictionary<Type, Action<object>>(); public TypeSwitch Case<T>(Action<T> action) { _matches.Add(typeof(T), x => action((T)x)); return this; } public void Switch(object x) { if (x != null && _matches.ContainsKey(x.GetType())) _matches[x.GetType()](x); } } } <file_sep>/LightEngineSerializeable/SerializableClasses/DatabaseModel/PlayerData.cs using System.Collections.Generic; using LightEngineSerializeable.LiteNetLib.Utils; using LightEngineSerializeable.SerializableClasses.Enums; using LightEngineSerializeable.Utils.Serializers; namespace LightEngineSerializeable.SerializableClasses.DatabaseModel { [System.Serializable] public class PlayerData : SerializableModel { public uint PlayerId { get; set; } public string DeviceId { get; set; } public string Name { get; set; } public int Coin { get; set; } public int Diamond { get; set; } public int LadderScore { get; set; } public PlayerUnit[] OwnedUnits { get; set; } public PlayerDeck Deck { get; set; } public override List<object> GetPropertyValues() { List<object> parameters = new List<object>(); parameters.Add((byte)OwnedUnits.Length); foreach (var ownedUnit in OwnedUnits) { parameters.AddRange(ownedUnit.GetPropertyValues()); } parameters.AddRange(Deck.GetPropertyValues()); parameters.Add(PlayerId); parameters.Add(DeviceId); parameters.Add(Name); parameters.Add(Coin); parameters.Add(Diamond); parameters.Add(LadderScore); return parameters; } public override NetDataWriter Serialize(NetworkCommand command, params object[] extra) { List<object> parameters = new List<object> { (byte)command }; parameters.AddRange(extra); parameters.Add((byte)OwnedUnits.Length); foreach (var ownedUnit in OwnedUnits) { parameters.AddRange(ownedUnit.GetPropertyValues()); } parameters.AddRange(Deck.GetPropertyValues()); parameters.Add(PlayerId); parameters.Add(DeviceId); parameters.Add(Name); parameters.Add(Coin); parameters.Add(Diamond); parameters.Add(LadderScore); return ObjectSerializationUtil.SerializeObjects(parameters.ToArray()); } public static PlayerData DeSerialize(NetDataReader reader, bool dropCommand = false) { if (dropCommand) reader.GetByte(); List<PlayerUnit> ownedUnits = new List<PlayerUnit>(); var ownedUnitCount = reader.GetByte(); for (int i = 0; i < ownedUnitCount; i++) { ownedUnits.Add(DeSerialize<PlayerUnit>(reader)); } var deck = DeSerialize<PlayerDeck>(reader); return new PlayerData { PlayerId = reader.GetUInt(), DeviceId = reader.GetString(), Name = reader.GetString(), Coin = reader.GetInt(), Diamond = reader.GetInt(), LadderScore = reader.GetInt(), OwnedUnits = ownedUnits.ToArray(), Deck = deck }; } } } <file_sep>/LightGameServer/Database/QueryRepository.cs using System.Collections.Generic; using LightEngineSerializeable.SerializableClasses.DatabaseModel; using LightGameServer.Database.Utils; using LightGameServer.Game.Model; using MySql.Data.MySqlClient; namespace LightGameServer.Database { class QueryRepository { private readonly DbConnector _dbConnector; private readonly ModelCreator _modelCreator; private readonly int[] _defaultUnits = { 1, 2, 3, 4 }; public QueryRepository() { _dbConnector = new DbConnector(); _modelCreator = new ModelCreator(this); } #region Wrappers private List<Dictionary<string, object>> ExecuteSelect(string query, params KeyValuePair<string, object>[] parameters) { List<Dictionary<string, object>> valueList = new List<Dictionary<string, object>>(); using (MySqlConnection con = _dbConnector.OpenConnection()) { using (MySqlCommand cmd = new MySqlCommand(query, con)) { foreach (var paramater in parameters) { cmd.Parameters.AddWithValue(paramater.Key, paramater.Value); } using (MySqlDataReader reader = cmd.ExecuteReader()) { while (reader.Read()) { Dictionary<string, object> values = new Dictionary<string, object>(); for (int i = 0; i < reader.FieldCount; i++) { if (values.ContainsKey(reader.GetName(i))) { continue; } values.Add(reader.GetName(i), reader.GetValue(i)); } valueList.Add(values); } return valueList; } } } } private void ExecuteNonQuery(string query, params KeyValuePair<string, object>[] parameters) { using (MySqlConnection con = _dbConnector.OpenConnection()) { using (MySqlCommand cmd = new MySqlCommand(query, con)) { foreach (var paramater in parameters) { cmd.Parameters.AddWithValue(paramater.Key, paramater.Value); } cmd.ExecuteNonQuery(); } } } #endregion public PlayerData CreatePlayerData(string name) { if (name.Length > 30) { name = name.Substring(0, 30); } string query = @"INSERT INTO player_data (name) VALUES (?name); SELECT LAST_INSERT_ID() as player_id"; var values = ExecuteSelect(query, Pair.Of("name", name)); uint newPlayerId = values[0].Get<uint>("player_id"); query = @"INSERT INTO device_id_player_id (player_id) VALUES (?player_id); SELECT LAST_INSERT_ID() as device_id;"; values = ExecuteSelect(query, Pair.Of("player_id", newPlayerId)); uint newDeviceId = values[0].Get<uint>("device_id"); query = @"INSERT INTO player_unit (player_id,unit_id) VALUES (?player_id,?unit_id)"; foreach (var defaultUnit in _defaultUnits) { ExecuteNonQuery(query, Pair.Of("player_id", newPlayerId), Pair.Of("unit_id", defaultUnit)); } query = @"INSERT INTO player_deck (player_id,unit_one_id,unit_two_id,unit_three_id,unit_four_id) VALUES (?player_id,?unit_one_id,?unit_two_id,?unit_three_id,?unit_four_id);"; ExecuteNonQuery(query, Pair.Of("player_id", newPlayerId), Pair.Of("unit_one_id", _defaultUnits[0]), Pair.Of("unit_two_id", _defaultUnits[1]), Pair.Of("unit_three_id", _defaultUnits[2]), Pair.Of("unit_four_id", _defaultUnits[3])); return GetPlayerData(Encryptor.EncryptDeviceId(newDeviceId)); } public PlayerData GetPlayerData(string deviceId) { uint decryptedDeviceId = Encryptor.DecryptDeviceId(deviceId); string query = @"SELECT * FROM player_data JOIN device_id_player_id AS d ON d.player_id=player_data.player_id WHERE d.device_id=?device_id LIMIT 1"; var values = ExecuteSelect(query, Pair.Of("device_id", decryptedDeviceId)); return values.Count > 0 ? _modelCreator.CreatePlayerData(values[0]) : null; } public UnitSettings GetUnitSettingsByName(string unitName) { string query = @"SELECT u.id,name,density,radius,push_force,hp,damage FROM units AS u INNER JOIN weight AS w ON u.weight=w.id INNER JOIN size AS sz ON u.size=sz.id INNER JOIN speed AS sp ON u.speed=sp.id WHERE u.name=?name LIMIT 1;"; var values = ExecuteSelect(query, Pair.Of("name", unitName)); return values.Count > 0 ? _modelCreator.CreateUnitSettings(values[0]) : null; } public UnitSettings[] GetAllUnitSettings() { string query = @"SELECT u.id,name,density,radius,push_force,hp,damage,projectile_damage FROM unit AS u INNER JOIN weight AS w ON u.weight=w.id INNER JOIN size AS sz ON u.size=sz.id INNER JOIN speed AS sp ON u.speed=sp.id;"; var values = ExecuteSelect(query); List<UnitSettings> units = new List<UnitSettings>(); foreach (var value in values) { units.Add(_modelCreator.CreateUnitSettings(value)); } return units.ToArray(); } public SkillSettings[] GetAllSkillSettings() { string query = @"SELECT * FROM skill"; var values = ExecuteSelect(query); List<SkillSettings> skills = new List<SkillSettings>(); foreach (var value in values) { skills.Add(_modelCreator.CreateSkillSettings(value)); } return skills.ToArray(); } public PlayerUnit[] GetPlayerUnits(uint playerId) { List<PlayerUnit> playerUnits = new List<PlayerUnit>(); string query = @"SELECT t.unit_id, t.amount FROM player_unit t WHERE t.player_id = ?player_id"; var values = ExecuteSelect(query, Pair.Of("player_id", playerId)); foreach (var value in values) { playerUnits.Add(_modelCreator.CreatePlayerUnit(value)); } return playerUnits.ToArray(); } public PlayerDeck GetPlayerDeck(uint playerId) { string query = @"SELECT unit_one_id,unit_two_id,unit_three_id,unit_four_id FROM player_deck WHERE player_id=?player_id LIMIT 1;"; var values = ExecuteSelect(query, Pair.Of("player_id", playerId)); return _modelCreator.CreatePlayerDeck(values[0]); } } } <file_sep>/LightEngineSerializeable/SerializableClasses/DatabaseModel/SerializableModel.cs using System; using System.Collections.Generic; using LightEngineSerializeable.LiteNetLib.Utils; using LightEngineSerializeable.SerializableClasses.Enums; using LightEngineSerializeable.Utils.Serializers; namespace LightEngineSerializeable.SerializableClasses.DatabaseModel { [System.Serializable] public abstract class SerializableModel { public virtual List<object> GetPropertyValues() { List<object> parameters = new List<object>(); foreach (var property in GetType().GetProperties()) { if (property.GetGetMethod() == null || !property.GetGetMethod().IsPublic || property.GetSetMethod() == null || !property.GetSetMethod().IsPublic) { continue; } var obj = property.GetValue(this, null); if (obj == null) obj = ""; parameters.Add(obj); } return parameters; } public virtual NetDataWriter Serialize(NetworkCommand command, params object[] extra) { List<object> parameters = new List<object> { (byte)command }; parameters.AddRange(extra); foreach (var property in GetType().GetProperties()) { if (property.GetGetMethod() == null || !property.GetGetMethod().IsPublic || property.GetSetMethod() == null || !property.GetSetMethod().IsPublic) { continue; } var obj = property.GetValue(this, null); if (obj == null) obj = ""; parameters.Add(obj); } return ObjectSerializationUtil.SerializeObjects(parameters.ToArray()); } public static T DeSerialize<T>(NetDataReader reader, bool dropCommand = false) where T : SerializableModel, new() { if (dropCommand) reader.GetByte(); T model = new T(); foreach (var property in model.GetType().GetProperties()) { if (property.GetGetMethod() == null || !property.GetGetMethod().IsPublic || property.GetSetMethod() == null || !property.GetSetMethod().IsPublic) { continue; } property.SetValue(model, Convert.ChangeType(reader.Get(property.PropertyType), property.PropertyType), null); } return model; } } } <file_sep>/LightEngineSerializeable/SerializableClasses/DatabaseModel/PlayerDeck.cs namespace LightEngineSerializeable.SerializableClasses.DatabaseModel { [System.Serializable] public class PlayerDeck : SerializableModel { public short UnitOne { get; set; } public short UnitTwo { get; set; } public short UnitThree { get; set; } public short UnitFour { get; set; } } } <file_sep>/LightEngineCore/PhysicsEngine/Collision/Handlers/CollisionFilterHandler.cs using LightEngineCore.PhysicsEngine.Dynamics; namespace LightEngineCore.PhysicsEngine.Collision.Handlers { public delegate bool CollisionFilterHandler(Fixture fixtureA, Fixture fixtureB); }<file_sep>/LightGameServer/Game/Prefabs/Static/Wall.cs using LightEngineCore.Components; using LightEngineCore.Loop; using LightEngineCore.PhysicsEngine.Dynamics; using LightEngineCore.PhysicsEngine.Primitives; using LightEngineSerializeable.Utils; namespace LightGameServer.Game.Prefabs.Static { class Wall : GameObject { public Wall(GameLoop match, string name, float width, float height, Vector2 pos, float rot = 0) : base(match, name, new Rigidbody(match, width, height, 1f, pos, BodyType.Static, rot.ToRadians())) { } } } <file_sep>/LightEngineSerializeable/SerializableClasses/Enums/CommandObjectCommand.cs namespace LightEngineSerializeable.SerializableClasses.Enums { public enum CommandObjectCommand { } } <file_sep>/LightGameServer/Database/ModelCreator.cs using System.Collections.Generic; using LightEngineSerializeable.SerializableClasses.DatabaseModel; using LightGameServer.Database.Utils; using LightGameServer.Game.Model; namespace LightGameServer.Database { class ModelCreator { private QueryRepository _repo; public ModelCreator(QueryRepository repo) { this._repo = repo; } public PlayerData CreatePlayerData(Dictionary<string, object> value) { uint playerId = value.Get<uint>("player_id"); if (value.ContainsKey("device_id")) { return new PlayerData { DeviceId = Encryptor.EncryptDeviceId(value.Get<uint>("device_id")), PlayerId = playerId, Name = value.Get<string>("name"), Coin = value.Get<int>("coin"), Diamond = value.Get<int>("diamond"), LadderScore = value.Get<int>("ladder_score"), OwnedUnits = _repo.GetPlayerUnits(playerId), Deck = _repo.GetPlayerDeck(playerId) }; } return new PlayerData { PlayerId = playerId, Name = value.Get<string>("name"), Coin = value.Get<int>("coin"), Diamond = value.Get<int>("diamond"), LadderScore = value.Get<int>("ladder_score"), OwnedUnits = _repo.GetPlayerUnits(playerId), Deck = _repo.GetPlayerDeck(playerId) }; } public UnitSettings CreateUnitSettings(Dictionary<string, object> value) { return new UnitSettings { Id = value.Get<short>("id"), Name = value.Get<string>("name"), Density = value.Get<float>("density"), Radius = value.Get<float>("radius"), PushForce = value.Get<short>("push_force"), Hp = value.Get<short>("hp"), Damage = value.Get<short>("damage"), ProjectileDamage = value.Get<short>("projectile_damage") }; } public SkillSettings CreateSkillSettings(Dictionary<string, object> value) { return new SkillSettings { Id = value.Get<short>("id"), Name = value.Get<string>("name"), Radius = value.Get<float>("radius"), Density = value.Get<float>("density"), Value1 = value.Get<float>("value1"), Value2 = value.Get<float>("value2"), Value3 = value.Get<float>("value3") }; } public PlayerUnit CreatePlayerUnit(Dictionary<string, object> value) { return new PlayerUnit { UnitId = value.Get<short>("unit_id"), Amount = value.Get<int>("amount") }; } public PlayerDeck CreatePlayerDeck(Dictionary<string, object> value) { return new PlayerDeck { UnitOne = value.Get<short>("unit_one_id"), UnitTwo = value.Get<short>("unit_two_id"), UnitThree = value.Get<short>("unit_three_id"), UnitFour = value.Get<short>("unit_four_id"), }; } } } <file_sep>/LightEngineCore/PhysicsEngine/Collision/Handlers/BeginContactHandler.cs using LightEngineCore.PhysicsEngine.Collision.ContactSystem; namespace LightEngineCore.PhysicsEngine.Collision.Handlers { /// <summary> /// This delegate is called when a contact is created /// </summary> public delegate bool BeginContactHandler(Contact contact); }<file_sep>/LightEngineSerializeable/SerializableClasses/GameModel/GameEvents/TurnSyncEvent.cs using LightEngineSerializeable.SerializableClasses.Enums; namespace LightEngineSerializeable.SerializableClasses.GameModel.GameEvents { public class TurnSyncEvent : GameEvent { public byte PlayerType { get; set; } public TurnSyncEvent() : base(GameEventType.TurnSync) { } } } <file_sep>/LightEngineSerializeable/Utils/Serializers/GameEventSerializer.cs using System.Collections.Generic; using LightEngineSerializeable.LiteNetLib.Utils; using LightEngineSerializeable.SerializableClasses; using LightEngineSerializeable.SerializableClasses.DatabaseModel; using LightEngineSerializeable.SerializableClasses.Enums; using LightEngineSerializeable.SerializableClasses.GameModel; using LightEngineSerializeable.SerializableClasses.GameModel.GameEvents; namespace LightEngineSerializeable.Utils.Serializers { public class GameEventSerializer { public NetDataWriter Serialize(params GameEvent[] gameEvents) { var parameters = new List<object> { (byte)NetworkCommand.GameEventOption, (byte)gameEvents.Length }; foreach (var gameEvent in gameEvents) { parameters.Add((byte)gameEvent.Type); switch (gameEvent.Type) { case GameEventType.PositionGroupSync: var groupPositionSyncEvent = (PositionGroupSyncEvent)gameEvent; parameters.Add(groupPositionSyncEvent.TimeStamp); parameters.Add((byte)groupPositionSyncEvent.PositionSyncs.Count); foreach (var posSync in groupPositionSyncEvent.PositionSyncs) { parameters.AddRange(posSync.GetPropertyValues()); } break; case GameEventType.GameStart: var gameStartEvent = (GameStartEvent)gameEvent; parameters.Add(gameStartEvent.TimeStamp); parameters.Add((byte)gameStartEvent.PlayerType); parameters.Add(gameStartEvent.LevelId); parameters.Add((byte)gameStartEvent.SpawnEvents.Length); foreach (var groupSpawnEvent in gameStartEvent.SpawnEvents) { parameters.AddRange(groupSpawnEvent.GetPropertyValues()); } parameters.AddRange(gameStartEvent.EnemyPlayerData.GetPropertyValues()); parameters.Add((byte)gameStartEvent.MyDeckBind.Length); foreach (var bind in gameStartEvent.MyDeckBind) { parameters.AddRange(bind.GetPropertyValues()); } parameters.Add((byte)gameStartEvent.EnemyDeckBind.Length); foreach (var bind in gameStartEvent.EnemyDeckBind) { parameters.AddRange(bind.GetPropertyValues()); } break; default: parameters.AddRange(gameEvent.GetPropertyValues()); break; } } return ObjectSerializationUtil.SerializeObjects(parameters.ToArray()); } public List<GameEvent> Deserialize(NetDataReader reader) { List<GameEvent> eventList = new List<GameEvent>(); int count = reader.GetByte(); for (int i = 0; i < count; i++) { GameEventType eventType = (GameEventType)reader.GetByte(); switch (eventType) { case GameEventType.NetworkObjectSpawn: eventList.Add(SerializableModel.DeSerialize<NetworkObjectSpawnEvent>(reader)); break; case GameEventType.PositionGroupSync: float groupTimeStamp = reader.GetFloat(); List<PositionSyncEvent> posSyncEvents = new List<PositionSyncEvent>(); byte posCount = reader.GetByte(); for (int j = 0; j < posCount; j++) { posSyncEvents.Add(SerializableModel.DeSerialize<PositionSyncEvent>(reader)); } eventList.Add(new PositionGroupSyncEvent { TimeStamp = groupTimeStamp, PositionSyncs = posSyncEvents }); break; case GameEventType.GameStart: float networkTime = reader.GetFloat(); var playerType = (PlayerType)reader.GetByte(); var levelId = reader.GetByte(); List<NetworkObjectSpawnEvent> spawnEvents = new List<NetworkObjectSpawnEvent>(); byte spawnCount = reader.GetByte(); for (int j = 0; j < spawnCount; j++) { spawnEvents.Add(SerializableModel.DeSerialize<NetworkObjectSpawnEvent>(reader)); } var enemyPlayerData = PlayerData.DeSerialize(reader); var myDeckBindCount = reader.GetByte(); List<DeckGameObjectBind> myDeckBindList = new List<DeckGameObjectBind>(); for (int j = 0; j < myDeckBindCount; j++) { myDeckBindList.Add(SerializableModel.DeSerialize<DeckGameObjectBind>(reader)); } var enemyDeckBindCount = reader.GetByte(); List<DeckGameObjectBind> enemyDeckBindList = new List<DeckGameObjectBind>(); for (int j = 0; j < enemyDeckBindCount; j++) { enemyDeckBindList.Add(SerializableModel.DeSerialize<DeckGameObjectBind>(reader)); } eventList.Add(new GameStartEvent { TimeStamp = networkTime, PlayerType = playerType, LevelId = levelId, SpawnEvents = spawnEvents.ToArray(), EnemyPlayerData = enemyPlayerData, MyDeckBind = myDeckBindList.ToArray(), EnemyDeckBind = enemyDeckBindList.ToArray() }); break; case GameEventType.TurnSync: eventList.Add(SerializableModel.DeSerialize<TurnSyncEvent>(reader)); break; case GameEventType.CanPlay: eventList.Add(SerializableModel.DeSerialize<CanPlayEvent>(reader)); break; case GameEventType.NetworkObjectDestroy: eventList.Add(SerializableModel.DeSerialize<NetworkObjectDestroyEvent>(reader)); break; case GameEventType.UnitHealthSync: eventList.Add(SerializableModel.DeSerialize<UnitHealthSyncEvent>(reader)); break; case GameEventType.EndGame: eventList.Add(SerializableModel.DeSerialize<EndGameEvent>(reader)); break; } } return eventList; } } } <file_sep>/LightGameServer/Game/Prefabs/Units/Caster2.cs using LightEngineCore.Loop; using LightEngineCore.PhysicsEngine.Primitives; using LightGameServer.Game.Model; using LightGameServer.Game.Prefabs.Skills; using LightGameServer.NetworkHandling; namespace LightGameServer.Game.Prefabs.Units { class Caster2 : Unit { public Caster2(Match myMatch, PlayerInfo playerInfo, Vector2 pos) : base(myMatch, playerInfo, Server.Get().DataStore.GetUnitSettings("Caster2"), pos) { } public override void PlayAbility(Vector2 direction) { direction.Normalize(); Vector2 pos = Pos + direction * (Settings.Radius + Server.Get().DataStore.GetSkillSettings("FireBall").Radius + 0.1f); new FireBall(MyMatch, Player, pos, direction * Settings.PushForce, Settings.ProjectileDamage); } } } <file_sep>/LightEngineSerializeable/SerializableClasses/GameModel/RequestEvent.cs using LightEngineSerializeable.SerializableClasses.DatabaseModel; using LightEngineSerializeable.SerializableClasses.Enums; namespace LightEngineSerializeable.SerializableClasses.GameModel { [System.Serializable] public class RequestEvent : SerializableModel { public RequestEventType Type { get; protected set; } public float TimeStamp { get; set; } public RequestEvent(RequestEventType type) { this.Type = type; } } } <file_sep>/LightEngineSerializeable/SerializableClasses/Enums/NetworkCommand.cs namespace LightEngineSerializeable.SerializableClasses.Enums { public enum NetworkCommand { CommandObjectOption, Register, GetPlayerData, Login, StartGame, GameEventOption, RequestEventOption, GameStarted, GetStaticData } }<file_sep>/LightEngineCore/Configuration/Settings.cs using Vector2 = LightEngineCore.PhysicsEngine.Primitives.Vector2; namespace LightEngineCore.Configuration { public static class Settings { public static float targetFrameRate = 30f; public static float gravity = 0f; public static float velocityLimit = 50f; public static float belowGround = -35f; public static Vector2 drawOrigin = new Vector2(10, 10); public static int simulatedThreadCount = 8; public static float timeScale = 1.0f; } } <file_sep>/LightEngineSerializeable/SerializableClasses/GameModel/GameEvents/GameStartEvent.cs using LightEngineSerializeable.SerializableClasses.DatabaseModel; using LightEngineSerializeable.SerializableClasses.Enums; namespace LightEngineSerializeable.SerializableClasses.GameModel.GameEvents { public class GameStartEvent : GameEvent { public PlayerType PlayerType { get; set; } public byte LevelId { get; set; } public NetworkObjectSpawnEvent[] SpawnEvents { get; set; } public PlayerData EnemyPlayerData { get; set; } public DeckGameObjectBind[] MyDeckBind { get; set; } public DeckGameObjectBind[] EnemyDeckBind { get; set; } public GameStartEvent() : base(GameEventType.GameStart) { } } } <file_sep>/LightEngineSerializeable/SerializableClasses/GameModel/GameEvents/CanPlayEvent.cs using LightEngineSerializeable.SerializableClasses.Enums; namespace LightEngineSerializeable.SerializableClasses.GameModel.GameEvents { public class CanPlayEvent : GameEvent { public bool CanPlay { get; set; } public ushort SelectedUnitId { get; set; } public CanPlayEvent() : base(GameEventType.CanPlay) { } } } <file_sep>/LightEngineCore/Components/Behaviour.cs namespace LightEngineCore.Components { public abstract class Behaviour { public GameObject gameObject; public virtual void Update() { } public void Assign(GameObject go) { this.gameObject = go; } } } <file_sep>/LightGameServer/Database/Utils/Pair.cs using System.Collections.Generic; namespace LightGameServer.Database.Utils { public static class Pair { public static KeyValuePair<string, object> Of(string key, object value) { return new KeyValuePair<string, object>(key, value); } } } <file_sep>/LightEngineSerializeable/SerializableClasses/GameModel/GameEvents/EndGameEvent.cs using LightEngineSerializeable.SerializableClasses.Enums; namespace LightEngineSerializeable.SerializableClasses.GameModel.GameEvents { public class EndGameEvent : GameEvent { public byte WinnerPlayerType { get; set; } public EndGameEvent() : base(GameEventType.EndGame) { } } } <file_sep>/LightEngineSerializeable/SerializableClasses/StaticData.cs using System; using System.Collections.Generic; using System.Globalization; using LightEngineSerializeable.LiteNetLib.Utils; using LightEngineSerializeable.SerializableClasses.DatabaseModel; using LightEngineSerializeable.SerializableClasses.Enums; using LightEngineSerializeable.Utils.Serializers; namespace LightEngineSerializeable.SerializableClasses { [System.Serializable] public class StaticData : SerializableModel { public string TimeStamp { get; set; } public UnitSettings[] UnitSettings { get; set; } public SkillSettings[] SkillSettings { get; set; } public override NetDataWriter Serialize(NetworkCommand command, params object[] extra) { List<object> parameters = new List<object> { (byte)command }; parameters.AddRange(extra); parameters.Add(TimeStamp); parameters.Add((byte)UnitSettings.Length); foreach (var unit in UnitSettings) { parameters.AddRange(unit.GetPropertyValues()); } parameters.Add((byte)SkillSettings.Length); foreach (var skill in SkillSettings) { parameters.AddRange(skill.GetPropertyValues()); } return ObjectSerializationUtil.SerializeObjects(parameters.ToArray()); } public static StaticData DeSerialize(NetDataReader reader, bool dropCommand = false) { if (dropCommand) reader.GetByte(); string timeStamp = reader.GetString(); List<UnitSettings> unitSettings = new List<UnitSettings>(); List<SkillSettings> skillSettings = new List<SkillSettings>(); byte length = reader.GetByte(); for (int i = 0; i < length; i++) { unitSettings.Add(DeSerialize<UnitSettings>(reader)); } length = reader.GetByte(); for (int i = 0; i < length; i++) { skillSettings.Add(DeSerialize<SkillSettings>(reader)); } return new StaticData { TimeStamp = timeStamp, UnitSettings = unitSettings.ToArray(), SkillSettings = skillSettings.ToArray() }; } } } <file_sep>/LightEngineSerializeable/SerializableClasses/Enums/GameEventType.cs namespace LightEngineSerializeable.SerializableClasses.Enums { public enum GameEventType { NetworkObjectSpawn, NetworkObjectDestroy, PositionGroupSync, GameStart, TurnSync, CanPlay, UnitHealthSync, EndGame } } <file_sep>/LightGameServer/Game/Model/PlayerInfo.cs using System.Linq; using LightEngineSerializeable.SerializableClasses.Enums; using LightGameServer.Game.Prefabs.Units; using LightGameServer.NetworkHandling.Model; namespace LightGameServer.Game.Model { class PlayerInfo { public PeerInfo PeerInfo { get; set; } public PlayerType PlayerType { get; set; } public Unit[] Deck { get; set; } public int DeckIndex { get; set; } public bool CanPlay { get; set; } public bool IncrementDeckIndex() { int currentIndex = DeckIndex; for (int i = 0; i <= Deck.Length; i++) { currentIndex = (currentIndex + 1) % Deck.Length; if (Deck[currentIndex].IsAlive) { DeckIndex = currentIndex; return true; } } return false; } public bool AreAllUnitsDead() { return Deck.All(unit => !unit.IsAlive); } public bool IsInDeck(Unit unit) { return Deck.ToList().Find(u => u == unit) != null; } public Unit GetSelectedUnit() { return Deck[DeckIndex]; } public ushort GetSelectedGoId() { return GetSelectedUnit().id; } } } <file_sep>/LightEngineCore/Loop/LoopManager.cs using System.Collections.Generic; using System.Threading; namespace LightEngineCore.Loop { public class LoopManager { private readonly List<List<GameLoop>> _loopList = new List<List<GameLoop>>(); public LoopManager(int threadCount) { for (int i = 0; i < threadCount; i++) { _loopList.Add(new List<GameLoop>()); ThreadPool.QueueUserWorkItem(UpdateLoop, i); } } private void UpdateLoop(object context) { int index = (int)context; var myList = _loopList[index]; while (true) { lock (myList) { for (var i = myList.Count - 1; i >= 0; i--) { myList[i].Update(); } } Thread.Sleep(1); } } public void AddLoop(GameLoop gameLoop) { int threadIndex = GetLeastBusyThreadIndex(); gameLoop.threadIndex = threadIndex; lock (_loopList[threadIndex]) { _loopList[threadIndex].Add(gameLoop); } } public GameLoop StartLoop() { int threadIndex = GetLeastBusyThreadIndex(); GameLoop newLoop = new GameLoop(); newLoop.threadIndex = threadIndex; lock (_loopList[threadIndex]) { _loopList[threadIndex].Add(newLoop); } return newLoop; } public void StopLoop(GameLoop gameLoop) { if (gameLoop == null) return; lock (_loopList[gameLoop.threadIndex]) { _loopList[gameLoop.threadIndex].Remove(gameLoop); } } private int GetLeastBusyThreadIndex() { int minValue = int.MaxValue; int index = 0; for (var i = 0; i < _loopList.Count; i++) { lock (_loopList[i]) { if (_loopList[i].Count < minValue) { minValue = _loopList[i].Count; index = i; } } } return index; } } } <file_sep>/LightEngineSerializeable/SerializableClasses/Enums/RequestEventType.cs namespace LightEngineSerializeable.SerializableClasses.Enums { public enum RequestEventType { PlayUnitAbility, SetAimDirection } }<file_sep>/LightEngineCore/Common/MathHelper.cs using System; namespace LightEngineCore.Common { public static class MathHelper { public static Random rng = new Random(); public static T Clamp<T>(T val, T min, T max) where T : IComparable<T> { if (val.CompareTo(min) < 0) return min; else if (val.CompareTo(max) > 0) return max; else return val; } public static float NextFloat(float min, float max) { return Convert.ToSingle(rng.NextDouble() * (max - min) + min); } public static float Remap(this float value, float from1, float to1, float from2, float to2) { return (value - from1) / (to1 - from1) * (to2 - from2) + from2; } } } <file_sep>/LightEngineCore/PhysicsEngine/Templates/Shapes/PolygonShapeTemplate.cs using LightEngineCore.PhysicsEngine.Collision.Shapes; using LightEngineCore.PhysicsEngine.Shared; namespace LightEngineCore.PhysicsEngine.Templates.Shapes { public class PolygonShapeTemplate : ShapeTemplate { public PolygonShapeTemplate() : base(ShapeType.Polygon) { } public Vertices Vertices { get; set; } } }<file_sep>/LightEngineSerializeable/Utils/Extensions.cs using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace LightEngineSerializeable.Utils { public static class Extensions { private const double DEGREES_TO_RADIANS = (Math.PI / 180); private const float FLOAT_TO_SHORT_MULTIPLIER = 100f; public static IEnumerable<List<T>> SplitList<T>(this List<T> locations, int nSize = 30) { for (int i = 0; i < locations.Count; i += nSize) { yield return locations.GetRange(i, Math.Min(nSize, locations.Count - i)); } } public static short ToShort(this float f) { return Convert.ToInt16(f * FLOAT_TO_SHORT_MULTIPLIER); } public static float ToFloat(this short s) { return s / FLOAT_TO_SHORT_MULTIPLIER; } public static float ToRadians(this float f) { return (float)(f * DEGREES_TO_RADIANS); } public static float Remap(this float value, float from1, float to1, float from2, float to2) { return (value - from1) / (to1 - from1) * (to2 - from2) + from2; } } } <file_sep>/LightGameServer/NetworkHandling/Handlers/NetworkCommandHandler.cs using System; using LightEngineSerializeable.LiteNetLib; using LightEngineSerializeable.LiteNetLib.Utils; using LightEngineSerializeable.SerializableClasses; using LightEngineSerializeable.SerializableClasses.DatabaseModel; using LightEngineSerializeable.SerializableClasses.Enums; using LightEngineSerializeable.Utils; using LightEngineSerializeable.Utils.Serializers; using LightGameServer.NetworkHandling.Model; using NLog; namespace LightGameServer.NetworkHandling.Handlers { class NetworkCommandHandler { public static NetworkCommandHandler New(NetDataReader reader, NetPeer peer) { return new NetworkCommandHandler(reader, peer); } private readonly Logger _logger = LogManager.GetCurrentClassLogger(); private readonly NetDataReader _reader; private readonly NetPeer _peer; public NetworkCommandHandler(NetDataReader reader, NetPeer peer) { _reader = reader; _peer = peer; } public void HandleReceived() { try { NetworkCommand command = (NetworkCommand)_reader.GetByte(); switch (command) { case NetworkCommand.Register: string nameToRegister = _reader.GetString(); PlayerData newPlayerData = Server.Get().QueryRepository.CreatePlayerData(nameToRegister); Server.Get().PeerInfos[_peer] = new PeerInfo { DeviceId = newPlayerData.DeviceId, PlayerData = newPlayerData, NetPeer = _peer }; DataSender.New(_peer).Send(newPlayerData.Serialize(NetworkCommand.Register), SendOptions.ReliableOrdered); break; case NetworkCommand.GetPlayerData: PeerInfo getPlayerDataPeerInfo = Server.Get().PeerInfos[_peer]; PlayerData gotPlayerData = Server.Get().QueryRepository.GetPlayerData(getPlayerDataPeerInfo.DeviceId); Server.Get().PeerInfos[_peer].PlayerData = gotPlayerData; DataSender.New(_peer).Send(gotPlayerData.Serialize(NetworkCommand.GetPlayerData), SendOptions.ReliableOrdered); break; case NetworkCommand.Login: string loginDeviceId = _reader.GetString(); PlayerData loginPlayerData = Server.Get().QueryRepository.GetPlayerData(loginDeviceId); Server.Get().PeerInfos[_peer] = new PeerInfo { DeviceId = loginPlayerData.DeviceId, PlayerData = loginPlayerData, NetPeer = _peer }; DataSender.New(_peer).Send(loginPlayerData.Serialize(NetworkCommand.Login), SendOptions.ReliableOrdered); break; case NetworkCommand.StartGame: Server.Get().AddToPendingPool(_peer); DataSender.New(_peer).Send(NetworkCommand.StartGame, SendOptions.ReliableOrdered); break; case NetworkCommand.RequestEventOption: RequestEventSerializer requestSerializer = new RequestEventSerializer(); var requests = requestSerializer.Deserialize(_reader); var requestPeerInfo = Server.Get().PeerInfos[_peer]; var playerMatch = Server.Get().GameManager.GetMatch(requestPeerInfo.PlayerData.PlayerId); if (playerMatch != null) playerMatch.ProcessRequests(requestPeerInfo, requests.ToArray()); break; case NetworkCommand.GetStaticData: StaticData storedStaticData = Server.Get().DataStore.Data; string clientStaticDataTimeStamp = _reader.GetString(); if (clientStaticDataTimeStamp != storedStaticData.TimeStamp) { DataSender.New(_peer).Send(storedStaticData.Serialize(NetworkCommand.GetStaticData, false), SendOptions.ReliableOrdered); } else { DataSender.New(_peer).Send(NetworkCommand.GetStaticData, SendOptions.ReliableOrdered, true); } break; } } catch (Exception e) { _logger.Error(e); } } } } <file_sep>/LightEngineSerializeable/Utils/DataSender.cs using System; using System.Linq; using LightEngineSerializeable.LiteNetLib; using LightEngineSerializeable.LiteNetLib.Utils; using LightEngineSerializeable.SerializableClasses.Enums; using LightEngineSerializeable.Utils.Serializers; namespace LightEngineSerializeable.Utils { public class DataSender { public static DataSender New(NetPeer peer) { return new DataSender(peer); } private readonly NetPeer _peer; public DataSender(NetPeer peer) { _peer = peer; } public void Send(NetworkCommand command, SendOptions sendOption, params object[] data) { try { var sendData = data.ToList(); sendData.Insert(0, (byte)command); _peer.Send(ObjectSerializationUtil.SerializeObjects(sendData.ToArray()), sendOption); } catch (Exception e) { Console.WriteLine(e.Message); Console.WriteLine(e.StackTrace); } } public void Send(NetDataWriter writer, SendOptions sendOption) { try { _peer.Send(writer, sendOption); } catch (Exception e) { Console.WriteLine(e.Message); Console.WriteLine(e.StackTrace); } } } } <file_sep>/LightEngineSerializeable/SerializableClasses/DatabaseModel/SkillSettings.cs namespace LightEngineSerializeable.SerializableClasses.DatabaseModel { [System.Serializable] public class SkillSettings : SerializableModel { public short Id { get; set; } public string Name { get; set; } public float Radius { get; set; } public float Density { get; set; } public float Value1 { get; set; } public float Value2 { get; set; } public float Value3 { get; set; } } } <file_sep>/LightEngineSerializeable/Utils/Serializers/RequestEventSerializer.cs using System.Collections.Generic; using LightEngineSerializeable.LiteNetLib.Utils; using LightEngineSerializeable.SerializableClasses.DatabaseModel; using LightEngineSerializeable.SerializableClasses.Enums; using LightEngineSerializeable.SerializableClasses.GameModel; using LightEngineSerializeable.SerializableClasses.GameModel.RequestEvents; namespace LightEngineSerializeable.Utils.Serializers { public class RequestEventSerializer { public NetDataWriter Serialize(params RequestEvent[] requests) { var parameters = new List<object> { (byte)NetworkCommand.RequestEventOption, (byte)requests.Length }; foreach (var request in requests) { parameters.Add((byte)request.Type); parameters.AddRange(request.GetPropertyValues()); } return ObjectSerializationUtil.SerializeObjects(parameters.ToArray()); } public List<RequestEvent> Deserialize(NetDataReader reader) { List<RequestEvent> requestList = new List<RequestEvent>(); int count = reader.GetByte(); for (int i = 0; i < count; i++) { RequestEventType requestType = (RequestEventType)reader.GetByte(); switch (requestType) { case RequestEventType.PlayUnitAbility: requestList.Add(SerializableModel.DeSerialize<PlayUnitAbilityRequest>(reader)); break; case RequestEventType.SetAimDirection: requestList.Add(SerializableModel.DeSerialize<SetAimDirectionRequest>(reader)); break; } } return requestList; } } } <file_sep>/LightEngineSerializeable/SerializableClasses/GameModel/GameEvents/PositionSyncEvent.cs using LightEngineSerializeable.SerializableClasses.DatabaseModel; namespace LightEngineSerializeable.SerializableClasses.GameModel.GameEvents { public class PositionSyncEvent : SerializableModel { public ushort Id { get; set; } public short PositionX { get; set; } public short PositionY { get; set; } } } <file_sep>/LightEngineSerializeable/SerializableClasses/GameModel/GameEvents/PositionGroupSyncEvent.cs using System.Collections.Generic; using LightEngineSerializeable.SerializableClasses.Enums; namespace LightEngineSerializeable.SerializableClasses.GameModel.GameEvents { public class PositionGroupSyncEvent : GameEvent { public PositionGroupSyncEvent() : base(GameEventType.PositionGroupSync) { } public List<PositionSyncEvent> PositionSyncs { get; set; } } } <file_sep>/LightGameServer/Database/DataStore.cs using System; using System.Globalization; using LightEngineSerializeable.SerializableClasses; using LightEngineSerializeable.SerializableClasses.DatabaseModel; namespace LightGameServer.Database { class DataStore { public StaticData Data { get; set; } private readonly QueryRepository _queryRepository; public DataStore(QueryRepository queryRepository) { _queryRepository = queryRepository; Refresh(); } public void Refresh() { Data = new StaticData { TimeStamp = DateTime.UtcNow.ToString(CultureInfo.CurrentCulture), UnitSettings = _queryRepository.GetAllUnitSettings(), SkillSettings = _queryRepository.GetAllSkillSettings() }; } public UnitSettings GetUnitSettings(string unitName) { foreach (var unitSetting in Data.UnitSettings) { if (unitSetting.Name == unitName) return unitSetting; } return null; } public SkillSettings GetSkillSettings(string skillName) { foreach (var skillSetting in Data.SkillSettings) { if (skillSetting.Name == skillName) return skillSetting; } return null; } } } <file_sep>/LightEngineCore/PhysicsEngine/Dynamics/Solver/Velocity.cs using LightEngineCore.PhysicsEngine.Primitives; namespace LightEngineCore.PhysicsEngine.Dynamics.Solver { /// This is an internal structure. public struct Velocity { public Vector2 V; public float W; } }<file_sep>/LightGameServer/Game/Prefabs/Units/Unit.cs using System; using LightEngineCore.Components; using LightEngineCore.PhysicsEngine.Dynamics; using LightEngineCore.PhysicsEngine.Primitives; using LightEngineSerializeable.LiteNetLib; using LightEngineSerializeable.SerializableClasses.DatabaseModel; using LightEngineSerializeable.SerializableClasses.GameModel.GameEvents; using LightGameServer.Game.Model; namespace LightGameServer.Game.Prefabs.Units { class Unit : GameObject { private float _drag = 1.2f; private float _restitution = 1f; private float _firction = 0f; public Match MyMatch { get; } public UnitSettings Settings { get; } public PlayerInfo Player { get; } public bool IsAttacking { get; set; } public short Hp { get; set; } public short MeeleDamage { get { return Settings.Damage; } } public short ProjectileDamage { get { return Settings.ProjectileDamage; } } public short PushForce { get { return Settings.PushForce; } } public bool IsAlive { get { return Hp > 0; } } public bool Destroyed { get; private set; } public Unit(Match myMatch, PlayerInfo playerInfo, UnitSettings settings, Vector2 pos) : base(myMatch.gameLoop, settings.Name, new Rigidbody(myMatch.gameLoop, settings.Radius, settings.Density, pos, BodyType.Dynamic)) { Hp = settings.Hp; MyMatch = myMatch; Player = playerInfo; Settings = settings; var body = GetComponent<Rigidbody>().body; body.LinearDamping = _drag; body.Restitution = _restitution; body.Friction = _firction; body.SleepingAllowed = true; this.onCollidedWithGameObject += OnCollision; } public virtual void OnCollision(GameObject go) { if (!IsAttacking) return; if (go is Unit) { Unit unit = (Unit)go; if (Player.IsInDeck(unit)) return; unit.TakeDamage(Settings.Damage); } } public virtual void PlayAbility(Vector2 direction) { } public virtual void TakeDamage(int amountInt) { short amount = (short)amountInt; var healthChanged = Hp - amount >= 0 ? amount : Hp; Hp -= healthChanged; if (healthChanged > 0) MyMatch.SendGameEventToPlayers(SendOptions.ReliableOrdered, new UnitHealthSyncEvent { Id = this.id, IsDamaged = true, CurrentHealth = Hp, HealthChanged = healthChanged }); } public virtual void Heal(int amountInt) { short amount = (short)amountInt; short healthChanged = Hp + amount <= Settings.Hp ? amount : (short)(Settings.Hp - Hp); Hp += healthChanged; if (healthChanged > 0) MyMatch.SendGameEventToPlayers(SendOptions.ReliableOrdered, new UnitHealthSyncEvent { Id = this.id, IsDamaged = false, CurrentHealth = Hp, HealthChanged = healthChanged }); } public override void Destroy() { if (Destroyed) return; Destroyed = true; MyMatch.SendGameEventToPlayers(SendOptions.ReliableOrdered, new NetworkObjectDestroyEvent { Id = id }); base.Destroy(); } } } <file_sep>/LightEngineSerializeable/SerializableClasses/GameModel/RequestEvents/SetAimDirectionRequest.cs using LightEngineSerializeable.SerializableClasses.Enums; namespace LightEngineSerializeable.SerializableClasses.GameModel.RequestEvents { public class SetAimDirectionRequest : RequestEvent { public bool Active { get; set; } public float DirectionX { get; set; } public float DirectionZ { get; set; } public SetAimDirectionRequest() : base(RequestEventType.SetAimDirection) { } } } <file_sep>/LightEngineCore/PhysicsEngine/Collision/Handlers/AfterCollisionHandler.cs using LightEngineCore.PhysicsEngine.Collision.ContactSystem; using LightEngineCore.PhysicsEngine.Dynamics; using LightEngineCore.PhysicsEngine.Dynamics.Solver; namespace LightEngineCore.PhysicsEngine.Collision.Handlers { public delegate void AfterCollisionHandler(Fixture fixtureA, Fixture fixtureB, Contact contact, ContactVelocityConstraint impulse); }<file_sep>/LightEngineCore/Loop/Invokable.cs using System; namespace LightEngineCore.Loop { public class Invokable { private GameLoop _gameLoop; private long _deltaSum; private readonly Action _action; private readonly bool _deleteOnInvoke; private float _interval; private bool _interrupted; public Invokable(Action action, float interval = 1, bool deleteOnInvoke = false) { _action = action; _deleteOnInvoke = deleteOnInvoke; _interval = interval; } public void SetGameLoop(GameLoop gameLoop) { _gameLoop = gameLoop; } private void TryToInvoke() { if (_deltaSum < _interval) return; if (_interrupted) { _gameLoop.RemoveInvokeable(this); return; } _action(); _deltaSum = 0; if (_deleteOnInvoke) { _gameLoop.RemoveInvokeable(this); } } public void Update(long deltaTime) { _deltaSum += deltaTime; TryToInvoke(); } public void Interrupt() { _interrupted = true; } public void AddToInterval(float amount) { _interval += amount; } } } <file_sep>/LightEngineSerializeable/SerializableClasses/DatabaseModel/UnitSettings.cs namespace LightEngineSerializeable.SerializableClasses.DatabaseModel { [System.Serializable] public class UnitSettings : SerializableModel { public short Id { get; set; } public string Name { get; set; } public float Density { get; set; } public float Radius { get; set; } public short PushForce { get; set; } public short Hp { get; set; } public short Damage { get; set; } public short ProjectileDamage { get; set; } } } <file_sep>/LightEngineSerializeable/SerializableClasses/GameModel/GameEvents/NetworkObjectSpawnEvent.cs using LightEngineSerializeable.SerializableClasses.Enums; namespace LightEngineSerializeable.SerializableClasses.GameModel.GameEvents { public class NetworkObjectSpawnEvent : GameEvent { public ushort Id { get; set; } public byte ObjectType { get; set; } public short PositionX { get; set; } public short PositionY { get; set; } public byte Owner { get; set; } public NetworkObjectSpawnEvent() : base(GameEventType.NetworkObjectSpawn) { } } } <file_sep>/LightGameServer/Database/Utils/DictExtension.cs using System; using System.Collections.Generic; namespace LightGameServer.Database.Utils { public static class DictExtension { public static T Get<T>(this Dictionary<string, object> dict, string key) { object value = dict[key]; if (value is T) { return (T)value; } try { return (T)Convert.ChangeType(value, typeof(T)); } catch (InvalidCastException) { return default(T); } } } } <file_sep>/LightGameServer/Game/Match.cs using System; using LightEngineCore.Components; using LightEngineCore.Loop; using LightEngineCore.PhysicsEngine.Dynamics; using LightEngineCore.PhysicsEngine.Primitives; using LightEngineSerializeable.Utils; using LightGameServer.NetworkHandling.Model; using System.Collections.Generic; using LightEngineSerializeable.LiteNetLib; using LightEngineSerializeable.LiteNetLib.Utils; using LightEngineSerializeable.SerializableClasses; using LightEngineSerializeable.SerializableClasses.DatabaseModel; using LightEngineSerializeable.SerializableClasses.Enums; using LightEngineSerializeable.SerializableClasses.GameModel; using LightEngineSerializeable.SerializableClasses.GameModel.GameEvents; using LightEngineSerializeable.SerializableClasses.GameModel.RequestEvents; using LightEngineSerializeable.Utils.Serializers; using LightGameServer.Game.Model; using LightGameServer.Game.Prefabs.Skills; using LightGameServer.Game.Prefabs.Static; using LightGameServer.Game.Prefabs.Units; using LightGameServer.NetworkHandling; using MathHelper = LightEngineCore.Common.MathHelper; namespace LightGameServer.Game { class Match { public readonly GameLoop gameLoop; public readonly PlayerInfo playerOne; public readonly PlayerInfo playerTwo; private readonly GameEventSerializer _gameEventSerializer = new GameEventSerializer(); private readonly RequestEventSerializer _requestEventSerializer = new RequestEventSerializer(); private const float START_TIME = 2f; private const float TURN_TIME = 20f; private bool _sendPositions = true; private float _turnTimeLeft; private bool _timerRunning; private PlayerType _playerTurn; private Invokable _everytingStopped; public Match(GameLoop gameLoop, PeerInfo playerOne, PeerInfo playerTwo) { this.gameLoop = gameLoop; this.playerOne = new PlayerInfo { PeerInfo = playerOne, PlayerType = PlayerType.PlayerOne, DeckIndex = 0 }; this.playerTwo = playerTwo != null ? new PlayerInfo { PeerInfo = playerTwo, PlayerType = PlayerType.PlayerTwo, DeckIndex = 0 } : new PlayerInfo { PeerInfo = new PeerInfo { PlayerData = new PlayerData { Name = "BOT", DeviceId = "", OwnedUnits = new PlayerUnit[0], Deck = playerOne.PlayerData.Deck } }, PlayerType = PlayerType.PlayerTwo, DeckIndex = 0 }; _playerTurn = MathHelper.rng.Next(0, 2) == 1 ? PlayerType.PlayerOne : PlayerType.PlayerTwo; gameLoop.AddInvokable(new Invokable(Setup, START_TIME * 1000f, true)); } public void ProcessRequests(PeerInfo peerInfo, params RequestEvent[] requests) { foreach (var request in requests) { switch (request.Type) { case RequestEventType.PlayUnitAbility: if (GetPlayerInTurn().PeerInfo != peerInfo || !GetPlayerInTurn().CanPlay) return; var abilityRequest = (PlayUnitAbilityRequest)request; if (new Vector2(abilityRequest.DirectionX, abilityRequest.DirectionY) == Vector2.Zero) continue; PlayUnitAbility(new Vector2(abilityRequest.DirectionX, abilityRequest.DirectionY)); break; case RequestEventType.SetAimDirection: RedirectRequest(SendOptions.Sequenced, request, GetOppositePeer(peerInfo)); break; } } } private void PlayUnitAbility(Vector2 direction) { SetAttackingFlag(); _timerRunning = false; _sendPositions = true; GetPlayerInTurn().GetSelectedUnit().PlayAbility(direction); GetPlayerInTurn().CanPlay = false; SwitchTurns(); } private void SetAttackingFlag() { foreach (var unit in GetPlayerNotInTurn().Deck) { unit.IsAttacking = false; } foreach (var unit in GetPlayerInTurn().Deck) { unit.IsAttacking = true; } } public PlayerInfo GetPlayerInTurn() { return _playerTurn == PlayerType.PlayerOne ? playerOne : playerTwo; } private PlayerInfo GetPlayerNotInTurn() { return _playerTurn == PlayerType.PlayerOne ? playerTwo : playerOne; } private NetPeer GetOppositePeer(PeerInfo peerInfo) { return playerOne.PeerInfo.PlayerData.PlayerId == peerInfo.PlayerData.PlayerId ? playerTwo.PeerInfo.NetPeer : playerOne.PeerInfo.NetPeer; } private PlayerInfo GetOppositePlayer(PlayerInfo player) { return player == playerOne ? playerTwo : playerOne; } private void BuildWalls() { new Wall(gameLoop, "FrontWall", 12.03f, 1f, new Vector2(0, 12)); new Wall(gameLoop, "TopRightWall", 5.85351f, 1f, new Vector2(8f, 10.22f), -45f); new Wall(gameLoop, "TopLeftWall", 5.85351f, 1f, new Vector2(-8f, 10.22f), 45f); new Wall(gameLoop, "BottomWall", 12.03f, 1f, new Vector2(0, -12)); new Wall(gameLoop, "BottomRightWall", 5.85351f, 1f, new Vector2(8f, -10.22f), 45f); new Wall(gameLoop, "BottomLeftWall", 5.85351f, 1f, new Vector2(-8f, -10.22f), -45f); new Wall(gameLoop, "LeftWall", 1f, 16.7883f, new Vector2(-10f, 0f)); new Wall(gameLoop, "RightWall", 1f, 16.7883f, new Vector2(10f, 0f)); } private void CreateCasters() { playerOne.Deck = new[] { UnitFactory.CreateUnit(playerOne.PeerInfo.PlayerData.Deck.UnitOne,this, playerOne, new Vector2(-4.5f, -5f)), UnitFactory.CreateUnit(playerOne.PeerInfo.PlayerData.Deck.UnitTwo,this, playerOne, new Vector2(-2f, -7f)), UnitFactory.CreateUnit(playerOne.PeerInfo.PlayerData.Deck.UnitThree,this, playerOne, new Vector2(2f, -7f)), UnitFactory.CreateUnit(playerOne.PeerInfo.PlayerData.Deck.UnitFour,this, playerOne, new Vector2(4.5f, -5f)) }; playerTwo.Deck = new[] { UnitFactory.CreateUnit(playerTwo.PeerInfo.PlayerData.Deck.UnitOne,this, playerTwo, new Vector2(-4.5f, 5f)), UnitFactory.CreateUnit(playerTwo.PeerInfo.PlayerData.Deck.UnitTwo,this, playerTwo, new Vector2(-2f, 7f)), UnitFactory.CreateUnit(playerTwo.PeerInfo.PlayerData.Deck.UnitThree,this, playerTwo, new Vector2(2f, 7f)), UnitFactory.CreateUnit(playerTwo.PeerInfo.PlayerData.Deck.UnitFour,this, playerTwo, new Vector2(4.5f, 5f)) }; } private void ResetTimer() { _turnTimeLeft = TURN_TIME; _timerRunning = true; } private void SendGameStartEvent(PlayerInfo playerInfo) { List<NetworkObjectSpawnEvent> spawnEvents = new List<NetworkObjectSpawnEvent>(); List<GameEvent> otherEvents = new List<GameEvent>(); foreach (var go in gameLoop.activeObjects) { if (go is Unit) { Unit unit = (Unit)go; if (!unit.IsAlive) continue; NetworkObjectType objectType = (NetworkObjectType)Enum.Parse(typeof(NetworkObjectType), go.name); spawnEvents.Add(new NetworkObjectSpawnEvent { Id = go.id, ObjectType = (byte)objectType, PositionX = go.Pos.X.ToShort(), PositionY = go.Pos.Y.ToShort(), Owner = (byte)unit.Player.PlayerType }); otherEvents.Add(new UnitHealthSyncEvent { Id = go.id, CurrentHealth = unit.Hp }); } } SendGameEventToPlayer(playerInfo, new GameStartEvent { LevelId = 1, PlayerType = playerInfo.PlayerType, SpawnEvents = spawnEvents.ToArray(), EnemyPlayerData = GetOppositePlayer(playerInfo).PeerInfo.PlayerData, MyDeckBind = new[] { new DeckGameObjectBind{DeckIndex = 0, GameObjectId = playerInfo.Deck[0].id}, new DeckGameObjectBind{DeckIndex = 1, GameObjectId = playerInfo.Deck[1].id}, new DeckGameObjectBind{DeckIndex = 2, GameObjectId = playerInfo.Deck[2].id}, new DeckGameObjectBind{DeckIndex = 3, GameObjectId = playerInfo.Deck[3].id} }, EnemyDeckBind = new[] { new DeckGameObjectBind{DeckIndex = 0, GameObjectId = GetOppositePlayer(playerInfo).Deck[0].id}, new DeckGameObjectBind{DeckIndex = 1, GameObjectId = GetOppositePlayer(playerInfo).Deck[1].id}, new DeckGameObjectBind{DeckIndex = 2, GameObjectId = GetOppositePlayer(playerInfo).Deck[2].id}, new DeckGameObjectBind{DeckIndex = 3, GameObjectId = GetOppositePlayer(playerInfo).Deck[3].id} } }); SendGameEventToPlayer(playerInfo, otherEvents.ToArray()); } private void SendTurnEvent() { SendGameEventToPlayers(SendOptions.ReliableOrdered, new TurnSyncEvent { PlayerType = (byte)_playerTurn }); } private void SwitchTurns(bool skipStopped = false) { _playerTurn = _playerTurn == PlayerType.PlayerOne ? PlayerType.PlayerTwo : PlayerType.PlayerOne; SendTurnEvent(); if (!skipStopped) { StartCheckEverytingStopped(); } else { if (!GetPlayerNotInTurn().IncrementDeckIndex()) { EndGame(); } } } private void StartCheckEverytingStopped() { _everytingStopped = gameLoop.AddInvokable(new Invokable(() => { if (IsEverytingStopped()) { OnEverytingStopped(); } })); } private bool IsEverytingStopped() { bool stopped = true; foreach (var go in gameLoop.activeObjects) { var rb = go.GetComponent<Rigidbody>(); if (rb != null && rb.body.LinearVelocity.Length() > 0.1f) { stopped = false; } } return stopped; } private void OnEverytingStopped() { foreach (var go in gameLoop.activeObjects) { var rb = go.GetComponent<Rigidbody>(); if (rb != null) rb.body.LinearVelocity = Vector2.Zero; } foreach (var go in gameLoop.activeObjects) { if (go is Skill) { go.Destroy(); } } if (!IsEverytingStopped()) { return; } _everytingStopped.Interrupt(); foreach (var go in gameLoop.activeObjects) { if (go is Unit) { var unit = (Unit)go; if (!unit.IsAlive && !unit.Destroyed) { unit.Destroy(); if (GetPlayerInTurn().GetSelectedUnit() == unit) { if (!GetPlayerInTurn().IncrementDeckIndex()) { EndGame(); return; } } } } } if (!GetPlayerNotInTurn().IncrementDeckIndex()) { EndGame(); return; } ResetTimer(); _sendPositions = false; SendCanPlay(); if (!GetPlayerInTurn().PeerInfo.IsConnected) { PlayBotMove(); } } private void SendCanPlay() { GetPlayerInTurn().CanPlay = true; SendGameEventToPlayer(GetPlayerInTurn(), new CanPlayEvent { CanPlay = true, SelectedUnitId = GetPlayerInTurn().GetSelectedGoId() }); GetPlayerNotInTurn().CanPlay = false; SendGameEventToPlayer(GetPlayerNotInTurn(), new CanPlayEvent { CanPlay = false, SelectedUnitId = GetPlayerInTurn().GetSelectedGoId() }); } private void PlayBotMove() { var dir = new Vector2(MathHelper.NextFloat(-1, 1f), MathHelper.NextFloat(-1, 1f)); dir.Normalize(); gameLoop.AddInvokable(new Invokable(() => { RedirectRequest(SendOptions.ReliableOrdered, new SetAimDirectionRequest { Active = true, DirectionX = dir.X, DirectionZ = dir.Y }, GetPlayerNotInTurn().PeerInfo.NetPeer); }, 100f, true)); gameLoop.AddInvokable(new Invokable(() => { RedirectRequest(SendOptions.ReliableOrdered, new SetAimDirectionRequest { Active = false }, GetPlayerNotInTurn().PeerInfo.NetPeer); PlayUnitAbility(dir); }, 2000f, true)); } private void Setup() { BuildWalls(); CreateCasters(); SendGameStartEvent(playerOne); SendGameStartEvent(playerTwo); SendTurnEvent(); SendCanPlay(); ResetTimer(); gameLoop.AddInvokable(new Invokable(() => { if (!_timerRunning) return; _turnTimeLeft -= gameLoop.DeltaTime; if (_turnTimeLeft <= 0) { GetPlayerInTurn().CanPlay = false; SwitchTurns(skipStopped: true); GetPlayerInTurn().CanPlay = true; SendGameEventToPlayer(GetPlayerNotInTurn(), new CanPlayEvent { CanPlay = false, SelectedUnitId = GetPlayerInTurn().GetSelectedGoId() }); ResetTimer(); if (!GetPlayerInTurn().PeerInfo.IsConnected) { PlayBotMove(); } } })); gameLoop.AddInvokable(new Invokable(() => { if (!_sendPositions) return; List<PositionSyncEvent> posEvents = new List<PositionSyncEvent>(); foreach (var go in gameLoop.activeObjects) { Rigidbody goRig = go.GetComponent<Rigidbody>(); if (goRig != null && goRig.body.BodyType == BodyType.Dynamic) { var pos = go.Pos; posEvents.Add(new PositionSyncEvent { Id = go.id, PositionX = pos.X.ToShort(), PositionY = pos.Y.ToShort(), }); } } var sections = posEvents.SplitList(); foreach (var section in sections) { GameEvent positionGroupEvent = new PositionGroupSyncEvent { PositionSyncs = section }; SendGameEventToPlayers(SendOptions.Sequenced, positionGroupEvent); } }, Server.UPDATE_TIME)); if (!GetPlayerInTurn().PeerInfo.IsConnected) { PlayBotMove(); } } private PlayerInfo GetWinnner() { if (playerOne.AreAllUnitsDead()) return playerTwo; if (playerTwo.AreAllUnitsDead()) return playerOne; return null; } private void EndGame() { var winner = GetWinnner(); if (winner != null) { SendGameEventToPlayers(SendOptions.ReliableOrdered, new EndGameEvent { WinnerPlayerType = (byte)winner.PlayerType }); Server.Get().GameManager.StopMatch(this); } } private void SendGameEventToPlayer(PlayerInfo player, params GameEvent[] gameEvents) { foreach (var gameEvent in gameEvents) { gameEvent.TimeStamp = gameLoop.Time; } NetDataWriter writer = _gameEventSerializer.Serialize(gameEvents); if (player.PeerInfo.IsConnected) DataSender.New(player.PeerInfo.NetPeer).Send(writer, SendOptions.ReliableOrdered); } public void SendGameEventToPlayers(SendOptions sendOption, params GameEvent[] gameEvents) { foreach (var gameEvent in gameEvents) { gameEvent.TimeStamp = gameLoop.Time; } NetDataWriter writer = _gameEventSerializer.Serialize(gameEvents); if (playerOne.PeerInfo.IsConnected) DataSender.New(playerOne.PeerInfo.NetPeer).Send(writer, sendOption); if (playerTwo.PeerInfo.IsConnected) DataSender.New(playerTwo.PeerInfo.NetPeer).Send(writer, sendOption); } private void RedirectRequest(SendOptions sendOption, RequestEvent requestEvent, NetPeer peer) { if (peer == null) return; requestEvent.TimeStamp = gameLoop.Time; NetDataWriter writer = _requestEventSerializer.Serialize(requestEvent); DataSender.New(peer).Send(writer, sendOption); } } }<file_sep>/LightEngineCore/PhysicsEngine/Dynamics/Handlers/JointHandler.cs using LightEngineCore.PhysicsEngine.Dynamics.Joints; namespace LightEngineCore.PhysicsEngine.Dynamics.Handlers { public delegate void JointHandler(Joint joint); }<file_sep>/LightGameServer/Game/Prefabs/Skills/FireBall.cs using System; using LightEngineCore.Components; using LightEngineCore.PhysicsEngine.Primitives; using LightEngineSerializeable.SerializableClasses.Enums; using LightGameServer.Game.Model; using LightGameServer.Game.Prefabs.Units; using LightGameServer.NetworkHandling; namespace LightGameServer.Game.Prefabs.Skills { class FireBall : Skill { //Value1: ExplodeRadius //Value2: ExplodeDamage Multiplier //Value3: PushForce public FireBall(Match match, PlayerInfo player, Vector2 pos, Vector2 pushDir, short damage) : base(match, player, NetworkObjectType.FireBall, Server.Get().DataStore.GetSkillSettings("FireBall"), pos, damage) { GetComponent<Rigidbody>().body.ApplyLinearImpulse(pushDir); } public override void OnCollided(GameObject go) { if (Destroyed) return; if (go is Unit) { Unit unit = (Unit)go; if (Player.IsInDeck(unit)) return; unit.TakeDamage(Damage); this.Destroy(); } } public override void Destroy() { Explode(); base.Destroy(); } private void Explode() { var affectedUnits = MyMatch.gameLoop.GetInOverlapCircle<Unit>(Pos, Settings.Value1); foreach (var affectedUnit in affectedUnits) { var pushDir = affectedUnit.Pos - Pos; pushDir.Normalize(); affectedUnit.GetComponent<Rigidbody>().body.ApplyLinearImpulse(pushDir * Settings.Value3); if (Player.IsInDeck(affectedUnit)) continue; affectedUnit.TakeDamage((int)(Damage * Settings.Value2)); } } } } <file_sep>/LightGameServer/Run.cs using LightGameServer.NetworkHandling; using NLog; namespace LightGameServer { class Run { static void Main(string[] args) { Server.Get().Start(); LogManager.Shutdown(); } } } <file_sep>/LightGameServer/Game/Prefabs/Skills/Skill.cs using System; using LightEngineCore.Components; using LightEngineCore.Loop; using LightEngineCore.PhysicsEngine.Dynamics; using LightEngineCore.PhysicsEngine.Primitives; using LightEngineSerializeable.LiteNetLib; using LightEngineSerializeable.LiteNetLib.Utils; using LightEngineSerializeable.SerializableClasses.DatabaseModel; using LightEngineSerializeable.SerializableClasses.Enums; using LightEngineSerializeable.SerializableClasses.GameModel.GameEvents; using LightEngineSerializeable.Utils; using LightGameServer.Game.Model; using LightGameServer.Game.Prefabs.Units; namespace LightGameServer.Game.Prefabs.Skills { abstract class Skill : GameObject { private float _drag = 1.2f; private float _restitution = 1f; private float _firction = 0f; public short Damage { get; } public PlayerInfo Player { get; } public SkillSettings Settings { get; } public Match MyMatch { get; } public NetworkObjectType Type { get; } public bool Destroyed { get; private set; } protected Skill(Match match, PlayerInfo player, NetworkObjectType type, SkillSettings skillSettings, Vector2 pos, short damage) : base(match.gameLoop, skillSettings.Name, new Rigidbody(match.gameLoop, skillSettings.Radius, skillSettings.Density, pos, BodyType.Dynamic)) { var body = GetComponent<Rigidbody>().body; body.LinearDamping = _drag; body.Restitution = _restitution; body.Friction = _firction; body.SleepingAllowed = true; Type = type; MyMatch = match; Player = player; Settings = skillSettings; Damage = damage; this.onCollidedWithGameObject += OnCollided; SendSpawnEvent(); } public virtual void OnCollided(GameObject go) { if (go is Unit) { if (Player.IsInDeck((Unit)go)) return; Console.WriteLine("I " + name + ", should attack " + go.name); } } private void SendSpawnEvent() { var spawnEvent = new NetworkObjectSpawnEvent { Id = id, ObjectType = (byte)Type, PositionX = Pos.X.ToShort(), PositionY = Pos.Y.ToShort(), Owner = (byte)Player.PlayerType }; MyMatch.SendGameEventToPlayers(SendOptions.ReliableOrdered, spawnEvent); } public override void Destroy() { if (Destroyed) return; Destroyed = true; MyMatch.SendGameEventToPlayers(SendOptions.ReliableOrdered, new NetworkObjectDestroyEvent { Id = id }); base.Destroy(); } } } <file_sep>/LightEngineCore/Components/Rigidbody.cs using LightEngineCore.Loop; using LightEngineCore.PhysicsEngine.Collision.ContactSystem; using LightEngineCore.PhysicsEngine.Dynamics; using Body = LightEngineCore.PhysicsEngine.Dynamics.Body; using BodyFactory = LightEngineCore.PhysicsEngine.Factories.BodyFactory; using BodyType = LightEngineCore.PhysicsEngine.Dynamics.BodyType; using Vector2 = LightEngineCore.PhysicsEngine.Primitives.Vector2; namespace LightEngineCore.Components { public class Rigidbody : Behaviour { public readonly Body body; private readonly GameLoop _gameLoop; public Rigidbody(GameLoop gameLoop, float radius, float density, Vector2 position, BodyType bType) { _gameLoop = gameLoop; body = BodyFactory.CreateCircle(gameLoop.physicsWorld, radius, density, position, bType, this); body.OnCollision += OnBodyCollision; if (bType == BodyType.Dynamic) body.IsBullet = true; } public Rigidbody(GameLoop gameLoop, float width, float height, float density, Vector2 position, BodyType bType, float rotation = 0f) { _gameLoop = gameLoop; body = BodyFactory.CreateRectangle(gameLoop.physicsWorld, width, height, density, position, rotation, bType, this); body.OnCollision += OnBodyCollision; if (bType == BodyType.Dynamic) body.IsBullet = true; } private void OnBodyCollision(Fixture myFixture, Fixture otherFixture, Contact contact) { var otherGo = _gameLoop.GetGameObjectByBody(otherFixture.Body); this.gameObject.InvokeCollidedDelegate(otherGo); } } } <file_sep>/LightGameServer/Database/DBConnector.cs using System; using MySql.Data.MySqlClient; namespace LightGameServer.Database { class DbConnector { private string _connectionString; public DbConnector() { Initialize(); } private void Initialize() { MySqlConnectionStringBuilder connectionStringBuilder = new MySqlConnectionStringBuilder { Server = "localhost", Database = "castforce", UserID = "root", Password = "<PASSWORD>!", MinimumPoolSize = 20, MaximumPoolSize = 1000, SslMode = MySqlSslMode.None }; _connectionString = connectionStringBuilder.ToString(); } public MySqlConnection OpenConnection() { try { MySqlConnection mySqlConnection = new MySqlConnection(_connectionString); mySqlConnection.Open(); return mySqlConnection; } catch (MySqlException ex) { switch (ex.Number) { case 0: Console.WriteLine("Cannot connect to MySQL server"); break; case 1045: Console.WriteLine("MySQL: Invalid username/password, please try again"); break; } } catch (NullReferenceException) { Console.WriteLine("Connection string is not specifed"); } return null; } public bool CloseConnection(MySqlConnection connection) { try { connection.Close(); return true; } catch (MySqlException ex) { Console.WriteLine(ex.StackTrace); return false; } } } } <file_sep>/LightEngineCore/Loop/GameLoop.cs using System; using System.Collections.Generic; using LightEngineCore.Components; using LightEngineCore.Configuration; using LightEngineCore.PhysicsEngine.Dynamics; using Vector2 = LightEngineCore.PhysicsEngine.Primitives.Vector2; using World = LightEngineCore.PhysicsEngine.Dynamics.World; namespace LightEngineCore.Loop { public class GameLoop { public int threadIndex; public bool shouldDrawToConsole = false; public long time; public readonly List<GameObject> activeObjects = new List<GameObject>(); public readonly World physicsWorld; private long _deltaTime; private readonly long _startTime; private readonly List<Invokable> _invokables = new List<Invokable>(); private readonly List<GameObject> _gameObjectsToRemove = new List<GameObject>(); private static readonly float MillisPerSecond = 1000f / Settings.targetFrameRate; public float DeltaTime => _deltaTime / 1000f; public float Time => time / 1000f; private int _frames; private float _lastTime; public int Fps { get; private set; } private ushort _goIdCounter = 1; public GameLoop() { _startTime = DateTimeOffset.Now.ToUnixTimeMilliseconds(); physicsWorld = new World(new Vector2(0.0f, Settings.gravity)); } private void CalculateTime() { long nowMilis = DateTimeOffset.Now.ToUnixTimeMilliseconds(); long newTime = nowMilis - _startTime; _deltaTime = newTime - time; time = newTime; } public void Update() { if (DateTimeOffset.Now.ToUnixTimeMilliseconds() - _startTime - time < Math.Floor(MillisPerSecond)) return; CalculateTime(); if (_lastTime < Time) { _lastTime = Time + 1; Fps = _frames; _frames = 0; } else { _frames++; } physicsWorld.Step(DeltaTime * Settings.timeScale); if (shouldDrawToConsole) { Console.Clear(); foreach (var gameObject in activeObjects) { gameObject.Draw(); } } for (int i = _invokables.Count - 1; i > -1; i--) { _invokables[i].Update(_deltaTime); } foreach (var gameObject in activeObjects) { gameObject.Update(); } if (_gameObjectsToRemove.Count > 0) { foreach (var gameObject in _gameObjectsToRemove) { activeObjects.Remove(gameObject); } _gameObjectsToRemove.Clear(); } } public void RegisterGameObject(GameObject go) { go.id = _goIdCounter++; activeObjects.Add(go); } public void Destroy(GameObject go) { Rigidbody rb = go.GetComponent<Rigidbody>(); if (rb != null) physicsWorld.RemoveBody(rb.body); _gameObjectsToRemove.Add(go); } public Invokable AddInvokable(Invokable invokable) { _invokables.Add(invokable); invokable.SetGameLoop(this); return invokable; } public void RemoveInvokeable(Invokable invokable) { _invokables.Remove(invokable); } public GameObject GetGameObjectByBody(Body body) { foreach (var go in activeObjects) { Rigidbody rb = go.GetComponent<Rigidbody>(); if (rb != null && rb.body == body) return go; } return null; } public List<T> GetInOverlapCircle<T>(Vector2 pos, float radius) where T : GameObject { List<T> affectedGameObjects = new List<T>(); foreach (var go in activeObjects) { if (go is T && Vector2.Distance(go.Pos, pos) <= radius) { affectedGameObjects.Add((T)go); } } return affectedGameObjects; } } } <file_sep>/LightGameServer/NetworkHandling/Model/PeerInfo.cs using System; using LightEngineSerializeable.LiteNetLib; using LightEngineSerializeable.SerializableClasses.DatabaseModel; namespace LightGameServer.NetworkHandling.Model { class PeerInfo { public PlayerData PlayerData { get; set; } public string DeviceId { get; set; } public NetPeer NetPeer { get; set; } public DateTime PendingPoolJoinTime { get; set; } public bool IsConnected => NetPeer != null && NetPeer.ConnectionState == ConnectionState.Connected; } } <file_sep>/LightEngineCore/PhysicsEngine/Collision/Handlers/BroadphaseHandler.cs using LightEngineCore.PhysicsEngine.Dynamics; namespace LightEngineCore.PhysicsEngine.Collision.Handlers { public delegate void BroadphaseHandler(ref FixtureProxy proxyA, ref FixtureProxy proxyB); }<file_sep>/LightEngineSerializeable/SerializableClasses/GameModel/GameEvents/UnitHealthSyncEvent.cs using LightEngineSerializeable.SerializableClasses.Enums; namespace LightEngineSerializeable.SerializableClasses.GameModel.GameEvents { public class UnitHealthSyncEvent : GameEvent { public ushort Id { get; set; } public bool IsDamaged { get; set; } public short CurrentHealth { get; set; } public short HealthChanged { get; set; } public UnitHealthSyncEvent() : base(GameEventType.UnitHealthSync) { } } }
8a666e36bb2bf6f69361e0ea3bcfc1e9a3274e5d
[ "C#" ]
78
C#
AndrasNyiri/AllInOneGameServer
dadfaff851d853c8ef5babf3863377cf1cb2dc30
e2ec8379abd866c8c2f1b8f010553f2bac382d53
refs/heads/master
<repo_name>rbenyounes/kata<file_sep>/bin/kata #!/usr/bin/env ruby require 'kata' err1 = 'Erreur! Il faut donner une séquence de vainqueurs. Exemple: 111212121' err2 = 'Erreur! la séquence doit contenir uniquement les chiffres 1 et 2' raise err1 if ARGV.length != 1 chars = ARGV[0].split(//) raise err2 if !chars.all?{ |c| c == '1' or c == '2' } winners = chars.map{ |c| c.to_i } p1 = Partie.new p1.run winners <file_sep>/lib/kata.rb require 'kata/echange' require 'kata/partie' require 'kata/kata_error' <file_sep>/test/test_echange.rb require 'minitest/autorun' require 'kata' class TestEchange < MiniTest::Test def setup @e1 = Echange.new end def test_update @e1.update! 1 assert_equal @e1.j1, 1 assert_equal @e1.j2, 0 end def test_to_s assert_equal @e1.to_s, 'zéro partout' @e1.update! 1 @e1.update! 2 assert_equal @e1.to_s, 'quinze partout' end end <file_sep>/lib/kata/echange.rb # Il s'agit d'une machine a etats composee de 20 etats (combinaisons de # 0,15,30,40,40+ et 40++). class Echange attr_reader :j1, :j2 @@valid_results = ['zéro','quinze','trente','quarante','avantage','gagnant'] def initialize @j1 = 0 @j2 = 0 end def update!( winner ) if (@j1 == 5 or @j2 == 5) raise EchangeTermineError elsif (@j1 == 4 and @j2 == 3) case winner when 1 @j1 += 1 when 2 @j1 -= 1 end elsif (@j1 == 3 and @j2 == 4) case winner when 1 @j2 -= 1 when 2 @j2 += 1 end elsif (winner == 1 and @j1 == 3 and @j2 != 3) @j1 += 2 elsif (winner == 2 and @j2 == 3 and @j1 != 3) @j2 += 2 else case winner when 1 @j1 += 1 when 2 @j2 += 1 end end end def to_s str = 'Erreur' if (@j1 == @j2) and @j1 <= 2 str = "#{@@valid_results[@j1]} partout" elsif (@j1 == @j2) and @j1 == 3 str = "égalité" elsif @j1 == 5 str = "j1 gagnant" elsif @j2 == 5 str = "j2 gagnant" elsif @j1 == 4 str = "avantage j1" elsif @j2 == 4 str = "avantage j2" else str = "#{@@valid_results[@j1]} #{@@valid_results[@j2]}" end str end end <file_sep>/lib/kata/kata_error.rb class KataError < StandardError end class EchangeTermineError < KataError end class PartieTermineeError < KataError end <file_sep>/README.md # Build $ build kata.gemspec # Install $ gem install ./kata-0.0.0.gem # Tests $ rake # Binary ## Example 1 $ kata 121211 quinze zéro quinze partout trente quinze trente partout quarante trente j1 gagnant +Partie non terminée: 1, 0 ## Example 2 $ kata 1212121222 quinze zéro quinze partout trente quinze trente partout quarante trente égalité avantage j1 égalité avantage j2 j2 gagnant +Partie non terminée: 0, 1 ## Example 3 $ kata 111111111111111111111111 quinze zéro trente zéro quarante zéro j1 gagnant +Partie non terminée: 1, 0 quinze zéro trente zéro quarante zéro j1 gagnant +Partie non terminée: 2, 0 quinze zéro trente zéro quarante zéro j1 gagnant +Partie non terminée: 3, 0 quinze zéro trente zéro quarante zéro j1 gagnant +Partie non terminée: 4, 0 quinze zéro trente zéro quarante zéro j1 gagnant +Partie non terminée: 5, 0 quinze zéro trente zéro quarante zéro j1 gagnant +Partie terminée: Joueur1 gagnant <file_sep>/lib/kata/partie.rb class Partie attr_reader :echanges def initialize @echanges = [Echange.new] end def update! winner s1 = score( 1 ) s2 = score( 2 ) if s1 < 6 and s2 < 6 begin @echanges.last.update! winner rescue EchangeTermineError @echanges << Echange.new @echanges.last.update! winner end elsif (s1 == 6 and s2 <= 4) or (s2 == 6 and s1 <= 4) raise PartieTermineeError end end def run winners begin nb_echanges_termines = 0 winners.each{ |w| update! w if nb_echanges_termines < @echanges.length - 1 puts self nb_echanges_termines += 1 end puts @echanges.last } puts self rescue PartieTermineeError puts self end end def score joueur s = 0 case joueur when 1 s = @echanges.find_all{ |e| e.j1 == 5 }.length when 2 s = @echanges.find_all{ |e| e.j2 == 5 }.length end s end def to_s s1 = score( 1 ) s2 = score( 2 ) if s1 == 6 and s2 <= 4 w = '+Partie terminée: Joueur1 gagnant' elsif s2 == 6 and s1 <= 4 w = '+Partie terminée: Joueur2 gagnant' else w = "+Partie non terminée: #{s1}, #{s2}" end w end end <file_sep>/test/test_partie.rb require 'minitest/autorun' require 'kata' class TestPartie < MiniTest::Test def setup @p1 = Partie.new end def test_update @p1.update! 1 @p1.update! 1 @p1.update! 1 @p1.update! 1 @p1.update! 1 assert_equal @p1.echanges.length, 2 end def test_score @p1.update! 1 # 15,0 @p1.update! 1 # 30,0 @p1.update! 1 # 40,0 @p1.update! 1 # j1 @p1.update! 1 # 15,0 assert_equal @p1.score( 1 ), 1 assert_equal @p1.score( 2 ), 0 @p1.update! 2 # 15,15 @p1.update! 2 # 15,30 @p1.update! 2 # 15,40 @p1.update! 2 # j2 assert_equal @p1.score( 1 ), 1 assert_equal @p1.score( 2 ), 1 end end <file_sep>/kata.gemspec # -*- encoding: utf-8 -*- Gem::Specification.new do |s| s.name = 'kata' s.version = '0.0.1' s.date = '2014-09-16' s.summary = 'Kata de tennis.' s.description = 'Une application de Kata de tennis.' s.authors = ["<NAME>"] s.email = '<EMAIL>' s.test_files = [ 'test/test_echange.rb', 'test/test_partie.rb', ] s.files = [ 'Rakefile', 'LICENSE', 'README.md', 'state_machine.jpg', 'lib/kata.rb', 'lib/kata/echange.rb', 'lib/kata/partie.rb', 'lib/kata/kata_error.rb', ] s.executables = [ 'kata' ] s.homepage = 'http://rubygems.org/gems/kata' s.license = 'MIT' s.require_paths = ["lib"] end
b4cef910db4c7ac3e6e3016464fa8f2f2231873b
[ "Markdown", "Ruby" ]
9
Ruby
rbenyounes/kata
3252e7d578309ed212d95b04b3951f4e877ddfad
8f9d4012e860be61deaa4f12d122cc979b14871c
refs/heads/master
<file_sep><?php use Illuminate\Http\Request; use Illuminate\Support\Facades\Auth; /* |-------------------------------------------------------------------------- | API Routes |-------------------------------------------------------------------------- | | Here is where you can register API routes for your application. These | routes are loaded by the RouteServiceProvider within a group which | is assigned the "api" middleware group. Enjoy building your API! | */ // Route::middleware('auth:api')->get('/user', function (Request $request) { // return $request->user(); // }); // Route::name('api.login')->post('login', 'Api\AuthController@login'); // Route::post('refresh', 'Api\AuthController@refresh'); // Route::group(['middleware' => 'auth:api'], function (){ // Route::get('users', function(){ // return \App\User::all(); // }); // Route::post('logout', 'Api\AuthController@logout'); // }); Route::post('login','Api\AuthController@login'); Route::get('logout','Api\AuthController@logout'); Route::group(['prefix' => 'admin','middleware' => 'assign.guard'], function(){ Route::name('admin')->get('','Api\AdminController@index'); }); Route::group(['prefix' => 'funcionario', 'middleware' => 'assign.guard'], function(){ Route::name('funcionario')->get('',function(){ return 'Hello World'; }); }); Route::group(['prefix' => 'cliente', 'middleware' => 'assign.guard'],function (){ Route::name('cliente')->get('',function(){ return 'Hello Cliente'; }); }); <file_sep><?php namespace App\Http\Controllers\Api; use App\Http\Controllers\Controller; use App\User; use Illuminate\Foundation\Auth\AuthenticatesUsers; use Illuminate\Http\Request; use Illuminate\Support\Facades\Auth; use Illuminate\Support\Facades\DB; use Tymon\JWTAuth\Facades\JWTAuth; class AuthController extends Controller { use AuthenticatesUsers; /** * login * * @param mixed $req * * @return void */ public function login(Request $req){ $credentials = $req->only('email', 'password'); try { if (! $token = JWTAuth::attempt($credentials)) { return response()->json(['error' => 'invalid_credentials'], 400); } } catch (JWTException $e) { return response()->json(['error' => 'could_not_create_token'], 500); } JWTAuth::setToken($token); return response()->json(compact('token')); } public function otherWaylogin(Request $req){ $this->validateLogin($req); $credentials = $this->credentials($req); $token = Auth::guard('api')->attempt($credentials); return $this->responseToken($token); } /** * responseToken * * @param mixed $token * * @return void */ private function responseToken($token){ return $token ? ['token' => $token] : response()->json([ 'error' => \Lang::get('auth.failed') ],400); } /** * logout * * @return void */ public function logout(){ Auth::guard('api')->logout(); return response()->json([], 204); } /** * refresh * * @return void */ public function refresh(){ $token = Auth::guard('api')->refresh(); return ['token' => $token]; } } <file_sep><?php namespace App\Http\Middleware; use Closure; use Tymon\JWTAuth\Facades\JWTAuth; class AssignGuard { /** * Handle an incoming request. * * @param \Illuminate\Http\Request $request * @param \Closure $next * @return mixed */ public function handle($request, Closure $next) { $token = JWTAuth::getToken(); $decode = JWTAuth::decode($token); $id = $decode['tipo_user_id']; if($id != null) auth()->shouldUse($id); return $next($request); } } <file_sep><?php use Illuminate\Database\Seeder; class TipoUserSeeder extends Seeder { /** * Run the database seeds. * * @return void */ public function run() { $dados = [ [ 'tipo_user' => 'Admin' ],[ 'tipo_user' => 'Funcionario' ],[ 'tipo_user' => 'Cliente' ] ]; DB::table('tipo_users')->insert($dados); } } <file_sep><?php //Header $header = [ 'alg' => 'HS256', 'typ' => 'JWT' ]; $header_json = json_encode($header); $header_base64 = base64_encode($header_json); echo $header_base64; //Payload $payload = [ 'first Name' => 'Luiz', 'Last Name' => 'Diniz', 'Email' => '<EMAIL>', 'exp' => (new \DateTime())->getTimestamp() ]; $payload_json = json_encode($payload); $payload_base64 = base64_encode($payload_json); echo $payload_base64; //Signature $key = '789456123andre789456231'; $signature = hash_hmac('sha256', $header_base64.$payload_base64, $key, true);<file_sep><?php namespace App\Http\Controllers\Api; use App\Http\Controllers\Controller; use Illuminate\Http\Request; use Illuminate\Support\Facades\DB; use Tymon\JWTAuth\Facades\JWTAuth; class AdminController extends Controller { public function index(Request $req){ $token = JWTAuth::getToken(); $decode = JWTAuth::decode($token); $email = $decode['email']; $users = DB::table('users')->join('tipo_users', 'users.tipo_user_id', '=', 'tipo_users.id')->where('email', '=', $email)->get(); return response()->json(['user' => $users]); } }
abf89320161effbb1ef204761a574321c46714b4
[ "PHP" ]
6
PHP
AndreTGama/JWTLaravel
a404665db884ef31fdd697afa3b437f4181aab49
34b87901d37ebac417a4d13d34098c71f87fba80
refs/heads/master
<file_sep>namespace :logons do desc "Cleans up the logons which were not logged off" task cleanup: :environment do # TODO We should send out an email to admins here Logon.active.update_all(:logout_time, Time.now) end end <file_sep>class Site < ActiveRecord::Base belongs_to :company has_many :site_hazards has_many :hazards, through: :site_hazards has_many :orientations belongs_to :manager has_many :logins validates :name, :manager_id, :company_id, presence: true end <file_sep>class Employee < Worker end <file_sep>class WorkersController < ApplicationController before_action :require_manager before_action :set_worker, only: [:show, :edit, :update, :destroy] respond_to :html def index @workers = superuser? ? Worker.all : manager.company.workers end def show end def new @worker = Worker.new end def edit end def create @worker = Worker.new(worker_params) @worker.company_id = manager.company.id if manager? if @worker.save flash[:notice] = "New worker added" redirect_to worker_path(@worker) else flash.now[:error]= "something went wrong" render 'new' end end def update @worker.update(worker_params) flash[:notice] = "Worker information updated" redirect_to worker_path(@worker) end def destroy @worker.destroy flash[:notice] = "worker removed" redirect_to workers_path end private def set_worker @worker = Worker.find(params[:id]) end def worker_params common_params = [:first_name, :last_name, :contact, :email, :type] common_params << :company_id if superuser? params.require(:worker).permit(*common_params) end end <file_sep>class Contractor < Worker end <file_sep>class OrientationsController < ApplicationController before_action :require_manager before_action :set_site respond_to :html def show @orientation = Orientation.find(params[:id]) end def new @orientation = Orientation.new end def create @orientation = Orientation.new(orientation_params) @orientation.site = @site if @orientation.save flash[:notice] = "Orientation completed" redirect_to site_orientation_path(@site, @orientation) else flash.now[:error] = "Something went wrong, check the errors" render 'new' end end private def set_site @site = Site.find(params[:site_id]) end def orientation_params params.require(:orientation).permit(:worker_id, :hazard_ids => []) end end <file_sep>class LoginsController < ApplicationController before_action :check_access, :load_resource def new @login = Login.new(loggable: @resource) @login.email = @resource.email if @resource.is_a? Manager end def create @login = Login.new(login_params) @login.loggable = @resource if @login.save if @resource.is_a? Manager redirect_to worker_path(@resource), notice: "Login created successfully" else redirect_to @resource, notice: "Login created successfully" end else render 'new' end end protected def check_access if (params[:worker_id].present? && !superuser?) && !manager? redirect_to root_path, alert: "You are not allowed to perform this action" end end def load_resource if params[:worker_id].present? @resource = Manager.find(params[:worker_id]) if !@resource.logins.empty? redirect_to worker_path(@resource), alert: "Login exists for this user" end elsif params[:site_id].present? @resource = Site.find(params[:site_id]) end end def login_params params.require(:login).permit(:email, :password, :password_confirmation) end end <file_sep>class Manager < Worker validates :email, presence: true has_many :sites end <file_sep>every 1.day, at: '12:05 am' do rake "logons:cleanup" end <file_sep>class OrientationHazard < ActiveRecord::Base belongs_to :orientation belongs_to :hazard end <file_sep>class CreateOrientationHazards < ActiveRecord::Migration def change create_table :orientation_hazards do |t| t.integer :orientation_id t.integer :hazard_id t.timestamps end end end <file_sep>class Company < ActiveRecord::Base has_many :employees has_many :contractors has_many :managers has_many :workers validates :name, :address, presence: true end <file_sep>class ApplicationController < ActionController::Base protect_from_forgery with: :exception helper_method :superuser?, :manager?, :manager protected def superuser? current_login && current_login.superuser? end def manager? current_login && current_login.loggable.present? && current_login.loggable.is_a?(Manager) end def manager manager? ? current_login.loggable : nil end def require_superuser redirect_to root_path, alert: "You are not allowed to perform this operation" unless superuser? end def require_manager redirect_to root_path, alert: "You are not allowed to perform this operation" unless (manager? || superuser?) end end <file_sep>class LogonsController < ApplicationController before_action :authenticate_login! respond_to :html def index if superuser? @logons = Logon.all elsif manager? @logons = Logon.recent.where(:site_id => manager.sites.map(&:id)) else @logons = Logon.recent.where(:site_id => current_login.loggable.id) end end def new @logon = Logon.new end def create @logon = Logon.new(logon_params) unless superuser? || manager? @logon.site_id = current_login.loggable.id end if @logon.save flash[:notice] = " Employee logged on" redirect_to logons_path else flash.now[:error]= "Check the errors below and proceed again." render 'new' end end def logout @logon = Logon.find(params[:id]) if @logon.update_attribute(:logout_time, Time.now) redirect_to logons_path, notice: "Logged out #{@logon.worker.full_name}" else redirect_to logons_path, alert: "Unable to logout #{@logon.worker.full_name}, try again." end end private def logon_params if superuser? || manager? params.require(:logon).permit(:worker_id, :site_id) else params.require(:logon).permit(:worker_id) end end end <file_sep>module WorkerHelper def worker_type_options %w(Manager Employee Contractor).map { |type| [type, type] } end end <file_sep>class Hazard < ActiveRecord::Base has_many :orientation_hazards has_many :orientations, through: :orientation_hazards has_many :site_hazards has_many :sites, through: :site_hazards validates :name, presence: true end <file_sep>class AddLoggableIdToLogin < ActiveRecord::Migration def change add_column :logins, :loggable_id, :integer add_column :logins, :loggable_type, :string end end <file_sep>class SiteHazard < ActiveRecord::Base belongs_to :site belongs_to :hazard end <file_sep>class SitesController < ApplicationController before_action :require_superuser, only: [:new, :create, :destroy] before_action :require_manager before_action :set_site, only: [:show, :edit, :update, :destroy] respond_to :html def index @sites = Site.all end def show @orientations = @site.orientations @hazards = @site.hazards end def new @site = Site.new end def edit end def create @site = Site.new(site_params) if @site.save flash[:notice] = "New site added" redirect_to site_path(@site) else flash.now[:error]= "something went wrong" render 'new' end end def update @site.update(site_params) flash[:notice] = "Site information updated" respond_with(@site) end def destroy @site.destroy flash[:notice] = "Site removed" redirect_to sites_path end private def set_site @site = Site.find(params[:id]) end def site_params if superuser? params.require(:site).permit(:name, :manager_id, :company_id, :hazard_ids => []) else params.require(:site).permit(:hazard_ids => []) end end end <file_sep>class Worker < ActiveRecord::Base belongs_to :company has_many :orientations has_many :logins, as: :loggable has_many :logons validates :first_name, :last_name, :company, presence: true VALID_EMAIL_REGEX = /\A[\w+\-.]+@[a-z\d\-.]+\.[a-z]+\z/i validates :email, length: { maximum: 255 }, format: { with: VALID_EMAIL_REGEX } VALID_CONTACT_REGEX = /\((\d{3})\)\s+(\d{3})-(\d{4})/ validates :contact, format: { with: VALID_CONTACT_REGEX } scope :non_managers, -> { where.not(type: Manager.name) } def full_name "#{first_name} #{last_name}" end def name_with_designation "[#{type}] #{full_name}" end end <file_sep>Rails.application.routes.draw do devise_for :logins resources :companies resources :hazards resources :workers do resources :logins, only: [:new, :create] end resources :sites do resources :orientations, only: [:show, :new, :create] resources :logins, only: [:new, :create] end resources :logons, only: [:index, :new, :create] do get 'logout', on: :member end root 'welcome#index' end <file_sep># This file should contain all the record creation needed to seed the database with its default values. # The data can then be loaded with the rake db:seed (or created alongside the db with db:setup). # # Examples: # # cities = City.create([{ name: 'Chicago' }, { name: 'Copenhagen' }]) # Mayor.create(name: 'Emanuel', city: cities.first) Company.create(name:"Myk Construction Ltd.", address:"828 W 8th Ave, Vancouver, BC V5Z 1E2") Company.create(name:"Squareone Contracting", address:"2140 124 St, Surrey, BC V4A 3M5") Company.create(name:"D Henriksen Contracting and Construction Inc", address:"5811 Oliver Dr, Richmond, BC V6V 2P1") Company.create(name:"RGC Construction Management Ltd", address:"104-18677 52 Ave, Surrey, BC V3S 8E5 ") Company.create(name:"BC Coastal Projects", address:"19662 Joyner Pl, Pitt Meadows, BC V3Y 2S3") Company.create(name:"Coastline Development Group Ltd", address:"150-21900 Westminster Hwy, Richmond, BC V6V 0A8") Company.create(name:"Blue Ocean Construction Inc", address:"221-17 Fawcett Rd, Coquitlam, BC V3K 6V2") Company.create(name:"W S Nicholas Western Construction Ltd", address:"851 Derwent Way, Delta, BC V3M 5R4 ") Company.create(name:"Graham construction and Engineering Ltd", address:"7216 Brown St, Delta, BC V4G 1G8") Company.create(name:"Pagilaro Projects Ltd", address:"3940 Charles St, Burnaby, BC V5C 3K8") Login.create(email: "<EMAIL>", password: "<PASSWORD>", superuser: true) Hazard.create(name: "Falls from working at height") Hazard.create(name: "Crush injuries in excavation work") Hazard.create(name: "Slips and trips") Hazard.create(name: "Being struck by falling objects") Hazard.create(name: "Moving heavy loads") Hazard.create(name: "Bad working positions, often in confined spaces") Hazard.create(name: "Being struck or crushed by a workplace vehicle") Hazard.create(name: "Receiving injuries from hand tools") Hazard.create(name: "Inhalation of dust") Hazard.create(name: "Handling of rough materials") Hazard.create(name: "Exposure to dangerous substances (chemical and biological)") Hazard.create(name: "Working near, in, or over water") Hazard.create(name: "Exposure to radiation") Hazard.create(name: "Loud noise") Hazard.create(name: "Vibration from tools or vibrating machinery") Worker.create(first_name: "Gay", last_name: "Garner", contact: "(564) 229-9507", email: "<EMAIL>", type: "Employee",company_id:1) Worker.create(first_name: "Vaughan", last_name: "Sanford", contact: "(598) 953-1160", email: "<EMAIL>", type: "Employee", company_id:2) Worker.create(first_name: "Chase", last_name: "Williams", contact: "(723) 587-1593", email: "<EMAIL>", type: "Manager", company_id: 3) Worker.create(first_name: "Abraham", last_name: "Meritt", contact: "(951) 205-4225", email: "<EMAIL>", type: "Contractor", company_id: 4) Worker.create(first_name: "Rhona", last_name: "Stevenson", contact: "(867) 998-0298", email: "<EMAIL>", type: "Employee", company_id: 4) Worker.create(first_name: "Keefe", last_name: "Key", contact: "(707) 626-8002", email: "<EMAIL>", type: "Contractor", company_id: 6) Worker.create(first_name: "Drew", last_name: "Kaufman", contact: "(329) 556-5294", email: "<EMAIL>", type: "Employee", company_id: 6) Worker.create(first_name: "Aimee", last_name: "Christen", contact: "(464) 733-7165", email: "<EMAIL>", type: "Contractor", company_id: 7) Worker.create(first_name: "Jane", last_name: "Garner", contact: "(393) 217-2402", email: "<EMAIL>", type: "Employee", company_id: 8) Worker.create(first_name: "Evan", last_name: "Peters", contact: "(920) 221-1805", email: "<EMAIL>", type: "Employee", company_id: 9) Worker.create(first_name: "Imani", last_name: "Le", contact: "(450) 751-6269", email: "<EMAIL>", type: "Contractor", company_id: 7) Worker.create(first_name: "Ciaro", last_name: "Stuart", contact: "(237) 474-1951", email: "<EMAIL>", type: "Employee", company_id: 2) Worker.create(first_name: "Kelsie", last_name: "Graham", contact: "(606) 201-8560", email: "<EMAIL>", type: "Contractor", company_id: 3) Worker.create(first_name: "Carol", last_name: "Mosley", contact: "(393) 193-7968", email: "<EMAIL>", type: "Employee", company_id: 5) Worker.create(first_name: "Charlotte", last_name: "Ferguson", contact: "(715) 787-1924", email: "<EMAIL>", type: "Contractor", company_id: 1) Worker.create(first_name: "Gray", last_name: "Ward", contact: "(133) 223-8023", email: "<EMAIL>", type: "Contractor", company_id: 4) Worker.create(first_name: "Imelda", last_name: "Vance", contact: "(517) 685-9809", email: "<EMAIL>", type: "Manager", company_id: 7) Worker.create(first_name: "Jackson", last_name: "Clay", contact: "(127) 904-2473", email: "<EMAIL>", type: "Manager", company_id: 4) Worker.create(first_name: "Byron", last_name: "Rosa", contact: "(987) 910-2987", email: "<EMAIL>", type: "Manager", company_id: 2) Worker.create(first_name: "Melinda", last_name: "Bryant", contact: "(236) 541-0859", email: "<EMAIL>", type: "Manager", company_id: 7) Worker.create(first_name: "Gray", last_name: "Vance", contact: "(987) 555-4321", email: "<EMAIL>", type: "Manager", company_id: 9) Site.create(name: "Foot of Bewicke", manager_id: 3, company_id: 3) Site.create(name: "Intersection of Hamilton Avenue & West 16th Street", manager_id: 17, company_id: 10) Site.create(name: "500 Block of West 28th Street", manager_id: 18, company_id: 4) Site.create(name: "105 Carrie Cates Court (Foot of Lonsdale)", manager_id: 19, company_id: 2) Site.create(name: "2358 Western Avenue", manager_id: 20, company_id: 7) Site.create(name: "131 East 3rd Street", manager_id: 21, company_id: 9) <file_sep>source 'https://rubygems.org' ruby '2.1.4' gem 'rails', '4.1.7' gem 'pg' gem 'devise' gem 'uglifier', '>= 1.3.0' gem 'sass-rails', '~> 4.0.3' gem 'coffee-rails', '~> 4.0.0' gem 'jquery-rails' gem 'jbuilder', '~> 2.0' gem 'bootstrap-sass' gem 'simple_form', '~> 3.1.0.rc2' gem 'quiet_assets' gem 'spring', group: :development gem 'whenever', :require => false gem 'rails_12factor', group: :production<file_sep>class Orientation < ActiveRecord::Base has_many :orientation_hazards has_many :hazards, through: :orientation_hazards belongs_to :worker belongs_to :site validates_presence_of :worker_id, :site_id def valid_orientation? (self.site.hazards.map(&:id) - self.hazards.map(&:id)).empty? && self.updated_at > 1.year.ago end def self.valid_for_site_and_worker(site_id, worker_id) Orientation.where(site_id: site_id, worker_id: worker_id).select(&:valid_orientation?) end end <file_sep>class HazardsController < ApplicationController before_action :set_hazard, only: [:show, :edit, :update, :destroy] respond_to :html def index @hazards = Hazard.all end def show end def new @hazard = Hazard.new end def edit end def create @hazard = Hazard.new(hazard_params) if @hazard.save flash[:notice] = "New hazard added" redirect_to hazard_path(@hazard) else flash.now[:error] = "Something went wrong" render 'new' end end def update @hazard.update(hazard_params) flash[:notice] = "Hazard information updated" respond_with(@hazard) end def destroy @hazard.destroy flash[:notice] = "Hazard removed" redirect_to hazards_path end private def set_hazard @hazard = Hazard.find(params[:id]) end def hazard_params params.require(:hazard).permit(:name) end end <file_sep>class Logon < ActiveRecord::Base belongs_to :worker belongs_to :site validates_presence_of :worker, :site validate :valid_orientation validate :no_current_logon scope :active, -> { where(:logout_time => nil) } scope :recent, -> { where('created_at > ?', Date.today.beginning_of_day) } def valid_orientation if worker.present? && site.present? if Orientation.valid_for_site_and_worker(site.id, worker.id).empty? self.errors.add(:worker_id, "does not have valid orientation, contact Manager for adding one.") end end end def no_current_logon if worker.present? && site.present? && self.new_record? if Logon.where(worker: worker, site: site, logout_time: nil).count > 0 self.errors.add(:worker_id, "is already logged in.") end end end end <file_sep>This is a management tool made for 'Lafarge Contruction Company' as a class project. It keeps track of employees and contractors working for lafarge at all locations. All employees are logged out automatically and email is sent to the admin/site manager about employees who did not sign out on their own. <file_sep>class AddSuperuserToLogins < ActiveRecord::Migration def change add_column :logins, :superuser, :boolean end end
2a31bf3af022b762ab96e2ad2f9aeb49caf07217
[ "RDoc", "Ruby" ]
28
Ruby
gurvircheema/Lafarge351
9c0ce878dd297f59164ff49fc88cf121fddf8a41
95b14ecee792b32ead0d53abf8eb0abc6c155c4b
refs/heads/main
<file_sep># citd3 CITD3 2021 Spring Topic : On Accelerating On-device Mobile Sensing AI <file_sep>### Instruction ``` chmod +x pre-install.sh chmod +x build.sh bash ./pre-install.sh <REBOOT YOUR COMPUTER> shutdown -r now <AFTER REBOOTED> bash ./build.sh ``` (Note that ./build.sh will take long)<file_sep>INSTALLDIR=/home/xilinx/torch PYTORCHVER=v1.7.1 CORES=2 TORCHVISIONVER=v0.8.2 apt install libopenblas-dev libblas-dev m4 cmake cython python3-dev python3-yaml python3-setuptools mkdir $INSTALLDIR && cd $INSTALLDIR git clone --recursive https://github.com/pytorch/pytorch git checkout $PYTORCHVER cd pytorch export NO_CUDA=1 export NO_DISTRIBUTED=1 export NO_MKLDNN=1 export NO_NNPACK=1 export NO_QNNPACK=1 export MAX_JOBS=$CORES python3 setup.py build sudo -E python3 setup.py install <file_sep># APT apt update && apt upgrade # make swap area sudo dd if=/dev/zero of=/swap1 bs=1M count=2048 sudo mkswap /swap1 echo '/swap1 swap swap' >> /etc/fstab
da1e7bf15c93e5c78e4d801469baa1aa4cd47e8b
[ "Markdown", "Shell" ]
4
Markdown
jinhoko/citd3
f27e3c45170f9cc1e676f8961202178f2ba7c94c
19ab16fe8773af91e140adc6dbccd28d065750ca
refs/heads/master
<repo_name>LuftDaniel/Polyharmonic_shape<file_sep>/Symbol_Analysis.py from fenics import * import os import errno from datetime import datetime from copy import copy import numpy as np __this_files_path = os.path.realpath(__file__) __this_files_dir = os.path.dirname(__this_files_path) # Pfad zum Ordner mit den Gitter Dateien DATA_DIR = os.path.abspath(os.path.join(__this_files_dir, 'Meshes')) def get_vertex_normal(meshdata, facet_index): ''' Berechnet die aeusseren (?) Normalen und gibt diese nach Numerierung der Facetten nur 2D moeglich bis jetzt Format: 1d array: Koordinaten des i'ten Normalenvektor sind 2i und 2i+1 verschieden Interpolationen der Normalen auf Vertex durch Normale der umliegenden Facetten denkbar. (Wie finite diffrences stencils) ''' normal = [] # erste Normalen fuer erste Facette f = Facet(meshdata.mesh, facet_index[-1]) f_norm_1 = f.normal().array() f = Facet(meshdata.mesh, facet_index[0]) f_norm_2 = f.normal().array() # Interpolation der Facettennormalen normal_coords = 0.5 * (f_norm_1 + f_norm_2) normal.append(normal_coords[0]) normal.append(normal_coords[1]) for i in range(len(facet_index)-1): # hole Normalenkoordinaten der umliegenden Facetten von Vertex i+1 # .normal gibt durch FEniCS einen 3D Vektor zurueck f = Facet(meshdata.mesh, facet_index[i]) f_norm_1 = f.normal().array() f = Facet(meshdata.mesh, facet_index[i+1]) f_norm_2 = f.normal().array() # Interpolation der Facettennormalen normal_coords = 0.5 * (f_norm_1 + f_norm_2) normal.append(normal_coords[0]) normal.append(normal_coords[1]) # korrigiere die Vorzeichen der Normalenvektoren, um aeussere Normalen zu erhalten return np.array(normal) def order_boundary_facets(meshdata, bound_index): ''' Gibt geordnete Liste der Boundary-Facetten an nach FEniCS-Facet Indizierung) (Ordnung haengt von bound_index ab! ''' bound_facet_index = [] for i in range(len(bound_index)-1): v = Vertex(meshdata.mesh, bound_index[i]) # waehle Facette, die naechsten Vertex enthaelt for f in facets(v): if bound_index[i+1] in f.entities(0): bound_facet_index.append(f.index()) # fuer den letzten Index v = Vertex(meshdata.mesh, bound_index[len(bound_index)-1]) for f in facets(v): if bound_index[0] in f.entities(0): bound_facet_index.append(f.index()) return bound_facet_index def order_boundary_verts(meshdata): ''' Gibt geordnete Indexliste der Boundary-Punkte am Interace zurueck Muessen nur einmal berechnet werden, da invariant bei Deformation (testen?) ''' # Vertex-Indizes des Interface bekommen, bleiben invariant bei Deformation ind_boundary_facets = [] for i in range(0, len(meshdata.boundaries)): if meshdata.boundaries[i] > 4: ind_boundary_facets.append(i) ind_boundary_facets = list(set(ind_boundary_facets)) ind_boundary_vertices = [] for c in cells(meshdata.mesh): for f in facets(c): if f.index() in ind_boundary_facets: for v in vertices(f): ind_boundary_vertices.append(v.index()) interface_indizes = list(set(ind_boundary_vertices)) # ordne Interface Indizes der Connectivity nach, d.h. Nachbarn im Array sind Nachbarn im Interface ordered_interface_indizes = [] ordered_interface_indizes.append(interface_indizes[0]) i = 0 while(len(ordered_interface_indizes) < len(interface_indizes)): v = Vertex(meshdata.mesh, ordered_interface_indizes[i]) local_connectivity = [] for f in facets(v): # kann hoechstens zwei Elemente in 2D haben, da 1dim Unterman. # entferne Vertex, an welchem wir uns bei Iterationsschritt befinden if ordered_interface_indizes[i] in f.entities(0): f_erased = f.entities(0).tolist() del f_erased[f_erased.index(ordered_interface_indizes[i])] local_connectivity.append(f_erased[0]) if len(local_connectivity) >= 2: break if(i == 0): ordered_interface_indizes.append(local_connectivity[0]) # im ersten Knoten hat man 2 moegliche Nachbarn else: # ein Nachbar ist bereits in der Liste, waehle den anderen if local_connectivity[0] in ordered_interface_indizes: ordered_interface_indizes.append(local_connectivity[1]) else: ordered_interface_indizes.append(local_connectivity[0]) i += 1 return ordered_interface_indizes def input_signal(meshdata, ampl, omega, eps, perimeter_val, analytic = False): """ Erzeugt eine Schwingung auf dem Interface, diese ist Element der Orthonormalbasis auf dem Shape-Tangentialraum. Man sieht nur endlich viele aufgeloest, je nach Gitterfeinheit; also genau die Anzahl an Knoten viel ONV kann auf jede periodische Funktion auf der geschlossenen Boundary verallgemeinert werden omega: frequency; ampl: amplitude Was ist der Zsmmhg zwischen diesen ONV und Eigenvektoren bzgl. Shape-Hessian? """ # Calculate Perimeter of Interface V = FunctionSpace(meshdata.mesh, 'P', 1) ones = Function(V) ones.vector()[:] = 1. # if(analytic): # perimeter = perimeter_val # # else: # dS = Measure('dS', subdomain_data = meshdata.boundaries) # perimeter = assemble(ones*dS(5) + ones*dS(6)) # berechne Indizes der Vertizes, Facetten und Koordinaten der aeusseren Normalen auf Interface interface_indizes = order_boundary_verts(meshdata) interface_facet_inds = order_boundary_facets(meshdata, interface_indizes) normal_values = get_vertex_normal(meshdata, interface_facet_inds) V_vec = VectorFunctionSpace(meshdata.mesh, 'P', 1, dim = 2) signal = Function(V_vec) vtod_vec = dolfin.vertex_to_dof_map(V_vec) # Koordinaten der aeusseren Normalen fuer FEniCS Funktion func_vals = np.zeros(len(signal.vector().get_local())) # Berechnung der Koeffizienten des Signalvektorfeldes in Richtung auesserer Normalen # hier wird ausgenutzt, dass die Gitterpunkte alle aequidistant sind! ########################### # korrekter waere: bei allgemeinem Gitter berechne Abstand von einem Punkt zum benachbarten, # starte bei 0; addiere naechsten Abstand (genauer: Weg auf Interface --> Randintegral, eig. egal, da Punkte # benachbart!) # und werte in der mit der Parametrisierung des # Interfaces transformierten Signalfunktion Koeffizient aus und weise auf Punkt zu ########################### vals = (1./len(interface_indizes))*np.array(list(range(0,len(interface_indizes)))) signal_vals = ampl*np.sin(2.*pi*omega*vals) for i in range(0, len(interface_indizes)): func_vals[vtod_vec[2*interface_indizes[i] ]] = eps*normal_values[i] func_vals[vtod_vec[2*interface_indizes[i]+1]] = eps*normal_values[i+1] print(signal_vals) signal.vector()[:] = func_vals return signal<file_sep>/BFGS-Test.py import numpy as np import shape_bib as sovi import matplotlib matplotlib.use('agg') import matplotlib.pyplot as plt memory_length = 4 def f(x): return (x[0]**2)*(x[1]**2) #negative ableitung def f_div(x): return np.array([2.*x[0]*(x[1]**2), 2.*(x[0]**2)*(x[1])]) x_start = np.array([20., 20.]) bfgs_memory = sovi.bfgs_memory(np.zeros([memory_length, 2 ]), np.zeros([memory_length, 2 ]), memory_length, 0) current_val = x_start alpha = np.zeros(bfgs_memory.length) diff_grad = np.zeros(2) first_diff_grad = np.zeros(2) bfgs_memory.update_grad(f_div(x_start)) while(np.linalg.norm(bfgs_memory.gradient[0]) > 0.0001): #SCHRITT CALC q = bfgs_memory.gradient[0] if (bfgs_memory.step_nr + 1 >= bfgs_memory.length): # bei voll besetzter memory werden alle Eintraege verwendet for i in range(bfgs_memory.length - 1): # Vorwaertsschleife i = i + 1 diff_grad = (bfgs_memory.gradient[i - 1] - bfgs_memory.gradient[i]) alpha[i] = np.dot(bfgs_memory.deformation[i - 1], q) / np.dot(diff_grad, bfgs_memory.deformation[i - 1]) q = q - float(alpha[i]) * diff_grad # Reskalierung von q first_diff_grad = (bfgs_memory.gradient[0] - bfgs_memory.gradient[1]) gamma = np.dot(first_diff_grad, bfgs_memory.deformation[0]) / np.dot(first_diff_grad, first_diff_grad) q = gamma * q for i in range(bfgs_memory.length - 1): # Rueckwaertsschleife i = i + 1 diff_grad = (bfgs_memory.gradient[-(i + 1)] - bfgs_memory.gradient[-i]) beta = np.dot(diff_grad, q) / np.dot(diff_grad, bfgs_memory.deformation[-(i + 1)]) q = q + (float(alpha[-i]) - beta) * bfgs_memory.deformation[-(i + 1)] elif (bfgs_memory.step_nr == 0): # der erste BFGS-Schritt ist ein Gradientenschritt, U Gradient ist in negativer Richtung q = q else: # bei nicht voll besetzter memory werden lediglich die besetzten Eintraege verwendet for i in range(bfgs_memory.step_nr): # Vorwaertsschleife i = i + 1 diff_grad = (bfgs_memory.gradient[i - 1] - bfgs_memory.gradient[i]) alpha[i] = np.dot(bfgs_memory.deformation[i - 1], q) / np.dot(diff_grad, bfgs_memory.deformation[i - 1]) q = q - float(alpha[i]) * diff_grad # Reskalierung von q first_diff_grad = (bfgs_memory.gradient[0] - bfgs_memory.gradient[1]) gamma = np.dot(first_diff_grad, bfgs_memory.deformation[0]) / np.dot(first_diff_grad, first_diff_grad) q = gamma * q for i in range(bfgs_memory.step_nr): # Rueckwaertsschleife shift = (bfgs_memory.length - 1) - bfgs_memory.step_nr i = i + 1 diff_grad = (bfgs_memory.gradient[-(i + 1) - shift] - bfgs_memory.gradient[-i - shift]) beta = np.dot(diff_grad, q) / np.dot(diff_grad, bfgs_memory.deformation[-(i + 1) - shift]) q = q + (float(alpha[-i - shift]) - beta) * bfgs_memory.deformation[-(i + 1) - shift] q = -1.*q current_val = current_val + q bfgs_memory.step_nr = bfgs_memory.step_nr + 1 bfgs_memory.update_grad(f_div(current_val)) bfgs_memory.update_defo(q) print("curv cond: {0:3e}".format(np.dot(bfgs_memory.gradient[0]-bfgs_memory.gradient[1], bfgs_memory.deformation[0]))) print(current_val) <file_sep>/shape_main_polyharmonic.py from fenics import * import shape_bib_polyharmonic as bib import time import argparse import os import numpy as np import matplotlib matplotlib.use('tkagg') import matplotlib.pyplot as plt import Symbol_Analysis as sa parameters['allow_extrapolation'] = True # ----------------------- # # <NAME> # # ----------------------- # # Waehle die konstanten Funktionswerte in den zwei Gebieten f1 = -10.0 f2 = 100.0 # Waehle, ob das Zielgitter pertubiert werden soll Pertubation = False sigma = Constant(0.01) # Definition des minimalen und maximalen Lameparameters mu_min = 0.0 mu_max = 30.0 # Parameter fuer L-BFGS Algorithmus L_BFGS = True curv_break = False memory_length = 3 # Parameter fuer Perimeter-Regularisierung und Abbruchkriterium fuer Optimierung nu = 0.00001 tol_shopt = 8.e-8 # Parameter fuer Backtracking-Linesearch Linesearch = True Resetcounter = 0 shrinkage = 0.5 c = 0.0001 start_scale = 5.0 # ----------------------- # # <NAME> # # ----------------------- # print("\n#############################################") print("# Shape Optimization with L-BFGS-Algorithms #") print("#############################################") string_mesh_desription = """\nParameter und Verfahren muessen in Datei geaendert werden! \nFalls L-BFGS-Verfahren ausgeschaltet, so wird ein Gradientenverfahren verwendet! \nKombinationsmoeglichkeiten: \n [1] kleiner Kreis -> grosser Kreis \n [2] grosser Kreis -> kleiner Kreis \n [3] verschobener Kreis -> kleiner Kreis \n [4] kleiner Kreis -> verschobener Kreis \n [5] verschobener Kreis -> kleiner Kreis \n [6] kleiner Kreis hoch aufgeloest -> grosser Kreis hoch aufgeloest \n [7] grosser Kreis hoch aufgeloest -> kleiner Kreis hoch aufgeloest \n [8] kleiner Kreis -> kaputter Donut \n [9] kleiner Kreis hoch aufgeloest -> kaputter Donut hoch aufgeloest """ # ----------------------- # # INPUT ABFRAGE # # ----------------------- # parser = argparse.ArgumentParser(description=string_mesh_desription, formatter_class=argparse.RawTextHelpFormatter) parser.add_argument('-m','--mesh', type=int, help='Waehle Gitter-Kombinationen (1, 2, 3, 4, 5, 6, 7, 8, 9)', required=True) args = parser.parse_args() # ----------------------- # # INPUT ABFRAGE ENDE # # ----------------------- # # Liste aller Gitter-Kombinationen mesh_combination_list = [("mesh_smallercircle", "mesh_circle"), ("mesh_circle", "mesh_smallercircle"), ("mesh_form", "mesh_smallercircle"), ("mesh_smallercircle", "mesh_leftbottom"), ("mesh_leftbottom", "mesh_smallercircle"), ("mesh_fine_smallercircle", "mesh_fine_circle"), ("mesh_fine_circle", "mesh_fine_smallercircle"), ("mesh_smallercircle", "mesh_broken_donut"), ("mesh_fine_smallercircle", "mesh_fine_broken_donut")] # Anzahl aller Kombinationen n = len(mesh_combination_list) # Ueberpruefe ob gewaehlte Kombination vorhanden, sonst Ende if args.mesh - 1 >= n or args.mesh <= 0: print("Warnung: Waehle Kombination zwischen 1 und {0:1d}!".format(n)) quit() # Setze Start- und Zielgitter je nach Benutzerwahl aus der Liste (startMesh_file, targetMesh_file) = mesh_combination_list[args.mesh - 1] # ----------------------- # # PARAMETER # # ----------------------- # # Setze Funktionswerte als Array f_values = [f1, f2] # Keine Ausgabe von FEniCS Funktionen in der Konsole set_log_active(False) # Generiere Output Ordner falls nicht vorhanden outputfolder = bib.create_outputfolder() # Speichere Ausgabedateien fuer ParaView im Output Ordner file_mesh = File(os.path.join(outputfolder, 'Last_Step_Data', 'mesh.pvd')) file_sol_y_1 = File(os.path.join(outputfolder, 'Last_Step_Data', 'sol_y_1.pvd')) file_sol_y_2 = File(os.path.join(outputfolder, 'Last_Step_Data', 'sol_y_2.pvd')) file_adj_p_1 = File(os.path.join(outputfolder, 'Last_Step_Data', 'adj_p_1.pvd')) file_adj_p_2 = File(os.path.join(outputfolder, 'Last_Step_Data', 'adj_p_2.pvd')) file_bound = File(os.path.join(outputfolder, 'Last_Step_Data', 'bound.pvd')) file_grad_u = File(os.path.join(outputfolder, 'Gradient', 'def_u.pvd')) file_data_sol_y_1 = File(os.path.join(outputfolder, 'TargetData', 'solution_1.pvd')) file_data_sol_y_2 = File(os.path.join(outputfolder, 'TargetData', 'solution_2.pvd')) file_data_mesh = File(os.path.join(outputfolder, 'TargetData', 'mesh.pvd')) file_targ_bound = File(os.path.join(outputfolder, 'TargetData', 'mesh.pvd')) file_data_bound = File(os.path.join(outputfolder, 'BoundaryData', 'bound_target.pvd')) file_lame = File(os.path.join(outputfolder, 'LameParameter', 'lamepar.pvd')) file_bound_start = File(os.path.join(outputfolder, 'BoundaryData', 'bound_start.pvd')) file_bound_func = File(os.path.join(outputfolder, 'Gradient', 'func.pvd')) # Zusammenfassung aller Parameter als Ausgabe in der Konsole print("\n-----------------PARAMETER------------------------------\n") print("Zielgitter Dateiname: " + targetMesh_file) print("Ausgangsgitter Dateiname: " + startMesh_file) print("Perimeter Regularisierung: " + str(nu)) print("minimaler/ maximaler Lame-Parameter: " + str(mu_min) + " " + str(mu_max)) print("Backtracking-Linesearch: " + str(Linesearch)) print("L-BFGS (bei False Gradientenverfahren): " + str(L_BFGS)) if(L_BFGS): print("Abbruch bei verletzter Curv. Cond: " + str(curv_break)) print("Abbruch bei Toleranz: " + str(tol_shopt)) print("\n--------------------------------------------------------") # Zusammenfassung aller Parameter als Ausgabe in csv-Datei, welche in OPENOFFICE CALC geoffnet wird file_csv = open(os.path.join(outputfolder, 'output.csv'), 'a') file_csv.write("Gitter; Start; " + startMesh_file + "; L-BFGS; " + str(L_BFGS) + "; memory_length; " + str(memory_length) + "\n") file_csv.write("; Ziel; " + targetMesh_file + "; curv_break; " + str(curv_break) + "\n") file_csv.write("; mu_min; " + str(mu_min) + "; Linesearch; " + str(Linesearch) + "\n") file_csv.write("; mu_max; " + str(mu_max) + "; shrinkage; " + str(shrinkage) + "\n") file_csv.write("; tol; " + str(tol_shopt) + "; c; " + str(c) + "\n") file_csv.write("; Perimeter; " + str(nu) + "; start_scale; " + str(start_scale) + "\n") if(L_BFGS): file_csv.write("\n Iteration; ||f_elas||_L2;J=j+j_reg;||U||_L2; Curv. Cond.; Meshdistance" + "\n") elif(L_BFGS == False): file_csv.write("\n Iteration; ||f_elas||_L2;J=j+j_reg;||U||_L2; Meshdistance" + "\n") # -----------------------# # TARGETDATA CALCULATION # # -----------------------# print('\nSchritt 1/2: Zieldaten berechnen\n') # Gitterdaten laden if(Pertubation): # laed Optimierungsproblem, bei welchem das Startgitter gestoert wird, # und das Zielgitter das ungestoerte Gitter ist MeshData = bib.load_mesh(startMesh_file) targetMeshData = bib.load_mesh(startMesh_file) # Parameter Normalverteilung fuer Stoerung, sigma vorsichtig waehlen! mu = Constant(0.0) # finde Indizes der Knoten am Inneren Rand boundary_index_target = bib.__get_index_not_interior_boundary(MeshData.mesh, MeshData.subdomains, MeshData.boundaries, interior=False) # Stoere das Zielgitter! for i in boundary_index_target: MeshData.mesh.coordinates()[i,0] += np.random.normal(mu, sigma) MeshData.mesh.coordinates()[i,1] += np.random.normal(mu, sigma) elif(Pertubation == False): # Problem wie in der Beschreibung wird geladen MeshData = bib.load_mesh(startMesh_file) targetMeshData = bib.load_mesh(targetMesh_file) # Loesen der Zustandsgleichung auf dem Zielgitter y_z = bib.solve_state(targetMeshData, f_values) # Zustand y_z im Ziel und die Gitter in pvd-Datei speichern file_data_sol_y_1 << y_z[0] file_data_sol_y_2 << y_z[1] file_data_mesh << targetMeshData.mesh file_data_bound << targetMeshData.boundaries file_targ_bound << targetMeshData.boundaries #file_bound_start << MeshData.boundaries, 0 # ----------------------- # # FORM OPTIMIERUNG # # ----------------------- # print('Schritt 2/2: Formoptimierung \n') print("initial meshdistance: {0:8e} \n".format(bib.mesh_distance(MeshData, targetMeshData))) # file_mesh << MeshData.mesh # BFGS-memory initialisieren bfgs_memory = bib.bfgs_memory(np.zeros([memory_length, 2 * MeshData.mesh.num_vertices()]), np.zeros([memory_length, 2 * MeshData.mesh.num_vertices()]), memory_length, 0) # Lame-Parameter berechnen und speichern mu_elas = bib.calc_lame_par(MeshData, mu_min, mu_max) # Zaehler der Iterationen counter = 0 # Startzeit zum Zeitmessen start_time = time.time() # Outputgraphendateien erstellen file_output_grad = open(os.path.join(outputfolder, 'outputdata_grad.txt'),'a') file_output_mshd = open(os.path.join(outputfolder, 'outputdata_mshd.txt'),'a') # Formableitungen fuer Curv. Cond; 0 aktuelles Gitter, 1 vorheriges Gitter curv_cond = np.zeros(2) # Werte, welche aus voriger Iteration gespeichert sind; 0 aktuelles Gitter, 1 vorheriges Gitter # Werte, ausser nrm_f_elas, werden in Schritt k nach printen von Schritt k-1 berechnet, aber # erst in Schritt k+1 geprintet, deshalb keine Paare nrm_f_elas = np.zeros(2) J = 0. nrm_U_mag = 0. mesh_dist = 0. # Berechnete Deformation s_k last_defo = np.zeros([ 2 * MeshData.mesh.num_vertices()]) # Dummy um Schleife zu durchlaufen nrm_f_elas[1] = 1.0 # Werte, welche fuer jeden Schritt geprintet werden if(L_BFGS): print("Iteration " + " ||f_elas||_L2 " + " J = j + j_reg " + " ||U||_L2 " + " Curv. Cond. " + " Meshdistance") elif(L_BFGS == False): print("Iteration " + " ||f_elas||_L2 " + " J = j + j_reg " + " ||U||_L2 " + " Meshdistance") signal = sa.input_signal(MeshData, 3., 3., 0.2, 2.*np.pi*0.15, True) interface_indizes = sa.order_boundary_verts(MeshData) interface_facets = sa.order_boundary_facets(MeshData, interface_indizes) interface_normal = sa.get_vertex_normal(MeshData, interface_facets) print(len(interface_indizes)) print(len(interface_facets)) print(len(interface_normal)) for i in range(len(interface_indizes)): print(MeshData.mesh.coordinates()[interface_indizes[i]]) print interface_normal[2*i], interface_normal[2*i+1] #ALE.move(MeshData.mesh, signal) file_bound_start << MeshData.boundaries file_bound_func << signal exit() # Start der Optimierungsschritte while nrm_f_elas[1] > tol_shopt: # Zaehler erhoehen und ausgeben in Konsole counter += 1 # ----------------------- # # INTERPOLATION # # ----------------------- # V = FunctionSpace(MeshData.mesh, "P", 1) z_1 = project(y_z[0], V) z_2 = project(y_z[1], V) z = [z_1, z_2] mu_elas_projected = project(mu_elas, V) mu_elas_projected.rename("lame_par", "label") # --------------------------------------- # # STATE, ADJOINT & GRADIENT CALCULATION # # --------------------------------------- # # loese Zustandgleichung y = bib.solve_state(MeshData, f_values) # loese adjungierte Gleichung p = bib.solve_adjoint(MeshData, y, z) # Loese lineare Elastizitaetsgleichung, weise aktuelle nrm_f_elas zu U , nrm_f_elas[0] = bib.solve_linelas(MeshData, p, y, z, f_values, mu_elas_projected, nu, zeroed = True) n = FacetNormal(MeshData.mesh) dS = Measure('dS', subdomain_data=MeshData.boundaries) #print(assemble( (inner(n('+'),U))*dS)) #Gradientcheck if(L_BFGS == False): # Ohne BFGS: Deformation ist negativer Gradient nrm_f_elas[1] = nrm_f_elas[0] S = Function(VectorFunctionSpace(MeshData.mesh, "P", 1, dim=2)) S.vector()[:] = -1.*U.vector() #if(counter == 1): bfgs_memory.update_grad(U.vector().get_local()) # ----------------------- # # L-BFGS METHOD # # ----------------------- # if(L_BFGS): # --------------------------------# # CURVATURE CONDITION & PRINTING # # --------------------------------# # Curvature Condition berechnen V_k_1 = VectorFunctionSpace(MeshData.mesh, "P", 1, dim=2) last_defo_function = Function(V_k_1) if(bfgs_memory.step_nr == 0): last_defo_function.vector()[:] = U.vector().get_local() curv_cond[0] = bib.shape_deriv(MeshData, p, y, z, f_values, nu, last_defo_function) #last_defo_function.vector()[:] = bfgs_memory.deformation[0] if(bfgs_memory.step_nr > 0): last_defo_function.vector()[:] = last_defo curv_cond[0] = bib.shape_deriv(MeshData, p, y, z, f_values, nu, last_defo_function) # Curvature condition auswerten step_valid = True curv_cond_val = 0. if(bfgs_memory.step_nr > 0): print("Abl. aktuell: " + str(curv_cond[0]) + "Abl. alt: " + str(curv_cond[1])) curv_cond_val = curv_cond[0] - curv_cond[1] # Iterationsfortschritt in Konsole ausgeben, ein Zeitschritt versetzt, # da curv_cond_val erst dann berechnet werden kann if(counter > 1): print(" {0:3d} ".format(counter-1) + " | " + " {0:.2E} ".format(nrm_f_elas[1]) + " | " + " {0:.2E} ".format(J) + " | " + " {0:.2E}".format(nrm_U_mag) + " | " + " {0:.2E}".format(curv_cond_val) + " | " + " {0:.2E}".format(mesh_dist)) # speichere in CSV-Datei (hier, da curv_cond_val berechnet werden musste) von vorigem Schritt file_csv.write(str(counter-1) + ";" + str(nrm_f_elas[1]) + ";" + str(J) + ";" + str(nrm_U_mag) + ";" + str(curv_cond_val) + ";" + str(mesh_dist) + ";" + "\n") # aktualisiere, nachdem alte Werte geprintet wurden nrm_f_elas[1] = nrm_f_elas[0] # ----------------------- # # NON-UPDATE STEP # # ----------------------- # # Falls Curvature Condition nicht erfuellt, so update nicht und mache Schritt mit alter Information if(bfgs_memory.step_nr > 0): if(curv_cond_val <= 0.): print("Curvature Condition not fullfilled!") step_valid = False if(step_valid == False): if(bfgs_memory.step_nr == 0): # falls direkt Curvature condition verletzt, mache Gradientenschritt print("Mache Gradientenschritt!") bfgs_memory.update_grad(U.vector().get_local()) S = U S.vector()[:] = -1. * U.vector().get_local() bfgs_memory.update_defo(S.vector().get_local()) last_defo = S.vector().get_local() elif(bfgs_memory.step_nr > 0): if(curv_break): print("Curv. Cond. violated! Quitting optimization!") break elif(curv_break == False): print("Break ausgeschaltet. Mache Schritt, aber kein Update!") S = bib.bfgs_step(MeshData, bfgs_memory, mu_elas_projected, U.vector().get_local()) last_defo = S.vector().get_local() bfgs_memory.step_nr = bfgs_memory.step_nr - 1 # ----------------------- # # UPDATE STEP # # ----------------------- # # L-BFGS Schritt elif(step_valid): bfgs_memory.update_grad(U.vector().get_local()) if(bfgs_memory.step_nr == 0): S = U S.vector()[:] = -1. * U.vector().get_local() bfgs_memory.update_defo(S.vector().get_local()) last_defo = S.vector().get_local() elif(bfgs_memory.step_nr > 0): bfgs_memory.update_defo(last_defo) S = bib.bfgs_step(MeshData, bfgs_memory, mu_elas_projected, bfgs_memory.gradient[0]) last_defo = S.vector().get_local() # L-BFGS Schrittnummer erhoehen bfgs_memory.step_nr = bfgs_memory.step_nr + 1 #curv_cond[1] = bib.shape_deriv(MeshData, p, y, z, f_values, nu, S) # ----------------------- # # BACKTRACKING-LINESEARCH # # ----------------------- # if(Linesearch): scale_parameter = start_scale zero_function = Function(VectorFunctionSpace(MeshData.mesh, "P", 1, dim=2)) current_value = bib.targetfunction(MeshData, zero_function, y_z, f_values, nu) S.vector()[:] = start_scale * S.vector() current_deriv = bib.shape_deriv(MeshData, p, y, z, f_values, nu, S) counterer = 0 # Skaliert das Deformationsfeld bei jedem Schritt automatisch dauerhaft: NOCH OHNE AMIJO #while(bib.targetfunction(MeshData, S, y_z, f_values, nu) > current_value + c*scale_parameter*current_deriv): while(bib.targetfunction(MeshData, S, y_z, f_values, nu) > current_value): scale_parameter = shrinkage * scale_parameter S.vector()[:] = shrinkage * S.vector() counterer = counterer + 1 # ----------------------- # # MEMORY REBOOT # # ----------------------- # if(counterer >= 20): print("Had to break, restarting L-BFGS!") bfgs_memory.gradient = np.zeros([memory_length, 2 * MeshData.mesh.num_vertices()]) bfgs_memory.deformation = np.zeros([memory_length, 2 * MeshData.mesh.num_vertices()]) bfgs_memory.step_nr = 0 Resetcounter = Resetcounter + 1 S.vector()[:] = np.zeros(2*MeshData.mesh.num_vertices()) break if(counterer < 20): Resetcounter = 0 # reskalierte Deformation als letzte Deformation uebergeben last_defo = S.vector().get_local() if(Resetcounter >= 2): # Falls nach Restart immernoch keine gute Reskalierung gefunden, so stoppe das Verfahren print("Reboot didn't help, quitting L-BFGS optimization!") break if(L_BFGS): # setze nach Backtracking neuen alte Formableitung zur Berechnung von curv_cond_val im naechsten Schritt curv_cond[1] = bib.shape_deriv(MeshData, p, y, z, f_values, nu, S) # ------------------------------ # # MISC. CALCULATIONS & PRINTING # # ------------------------------ # # Norm des Deformationsvektorfeldes berechnen V = FunctionSpace(MeshData.mesh, 'P', 1) U_magnitude = sqrt(dot(U, U)) U_magnitude = project(U_magnitude, V) nrm_U_mag = norm(U_magnitude, 'L2', MeshData.mesh) # Zielfunktional berechnen zero_function = Function(VectorFunctionSpace(MeshData.mesh, "P", 1, dim=2)) J = bib.targetfunction(MeshData, zero_function, y_z, f_values, nu) # Abstand zum Zielgitter berechnen mesh_dist = bib.mesh_distance(MeshData, targetMeshData) # Iterationsfortschritt in Konsole ausgeben, falls Gradientenverfahren genutzt wird # hier ist versetzen nicht noetig, da curv_cond_val nicht berechnet werden muss if(L_BFGS == False): print(" {0:3d} ".format(counter) + " | " + " {0:.2E} ".format(nrm_f_elas[0]) + " | " + " {0:.2E} ".format(J) + " | " + " {0:.2E}".format(nrm_U_mag) + " | " + " {0:.2E}".format(mesh_dist)) # Iterationsschritt in csv-Datei speichern file_csv.write(str(counter) + ";" + str(nrm_f_elas[0]) + ";" + str(J) + ";" + str(nrm_U_mag) + ";" + str(mesh_dist) + ";" + "\n") # Norm von aktuellem f_elas plotten file_output_grad.write(str(counter) +";"+ str(np.log(nrm_f_elas[0])) + "\n") # Abstand zur Zielform plotten file_output_mshd.write(str(counter) +";"+ str(np.log(mesh_dist)) + "\n") # ----------------------- # # DEFORMATION # # ----------------------- # ALE.move(MeshData.mesh, S) # ----------------------- # # GITTER SPEICHERN # # ----------------------- # file_bound_increment = File(os.path.join(outputfolder, 'BoundaryData', 'bound_{}.pvd'.format(counter))) file_bound_increment << MeshData.boundaries, counter # ----------------------- # # FERTIG # # ----------------------- # # ----------------------- # # OUTPUT # # ----------------------- # if(L_BFGS): # hole bei L-BFGS das versetzte Printen des letzten Schrittes vor Ausstieg nach counter = counter + 1 print(" {0:3d} ".format(counter - 1) + " | " + " {0:.2E} ".format(nrm_f_elas[1]) + " | " + " {0:.2E} ".format(J) + " | " + " {0:.2E}".format(nrm_U_mag) + " | " + " {0:.2E}".format(curv_cond_val) + " | " + " {0:.2E}".format(mesh_dist)) # speichere in CSV-Datei (hier, da curv_cond_val berechnet werden musste) von vorigem Schritt file_csv.write(str(counter - 1) + ";" + str(nrm_f_elas[1]) + ";" + str(J) + ";" + str(nrm_U_mag) + ";" + str(curv_cond_val) + ";" + str(mesh_dist) + ";" + "\n") # Speichern in pvd-Datei fuer ParaView file_mesh << MeshData.mesh file_sol_y_1 << y[0] file_sol_y_2 << y[1] file_adj_p_1 << p[0] file_adj_p_2 << p[1] file_bound << MeshData.boundaries file_grad_u << U file_lame << mu_elas_projected file_output_grad.close() file_output_mshd.close() # Zeitmessung elapsed_time = time.time() - start_time # Dauer der Berechnung in csv-Datei speichern file_csv.write("Dauer der Berechnung in Sekunden;" + str(elapsed_time) + ";" + "\n") # Datei schliessen file_csv.close() # Abschluss Ausgabe in Konsole print("\n-------------------Fertig------------------------\n") print("Iterationen: {0:0d}".format(counter)) print("Dauer der Berechnungen: {0:.2f} min".format(int(elapsed_time)/60)) print("Ergebnisse in: '{0:s}/'".format(outputfolder)) print("\n-------------------------------------------------\n") # ----------------------- # # GRAPH PRINTING # # ----------------------- # with open(os.path.join(outputfolder, 'outputdata_grad.txt')) as output: items = (map(float, line.split(";")) for line in output) xs_grad, ys_grad = zip(*items) plot1, = plt.plot(xs_grad, ys_grad, label="log Norm f_elas") with open(os.path.join(outputfolder, 'outputdata_mshd.txt')) as output: items = (map(float, line.split(";")) for line in output) xs_mshd, ys_mshd = zip(*items) plot2, = plt.plot(xs_mshd, ys_mshd, label = "log Meshdistance") legend_mshd = plt.legend(handles=[plot1, plot2], loc=1) plt.savefig(os.path.join(outputfolder, 'convergence_fig')) plt.show() <file_sep>/shape_bib_polyharmonic.py from fenics import * import os import errno from datetime import datetime from copy import copy import numpy as np __this_files_path = os.path.realpath(__file__) __this_files_dir = os.path.dirname(__this_files_path) # Pfad zum Ordner mit den Gitter Dateien DATA_DIR = os.path.abspath(os.path.join(__this_files_dir, 'Meshes')) class MeshData: # Objekt mit allen Daten des Gitters def __init__(self, mesh, subdomains, boundaries, ind): # FEniCS Mesh self.mesh = mesh # FEniCS Subdomains self.subdomains = subdomains # FEniCS Boundaries self.boundaries = boundaries # Indizes der Knotenpunkte mit Traeger nicht am inneren Rand self.indNotIntBoundary = ind class bfgs_memory: """ Klasse, welche alle Information fuer das L-BFGS-Verfahren enthaelt. Besteht aus length Gradienten- und Deformationsvektoren, welche jeweils in einem Array der Historie nach absteigend sortiert sind. Besitzt die Funktion, Gradienten und Deformationen zu updaten, wobei der aelteste Eintrag verworfen wird. step_nr ist ein counter fuer das Verfahren. """ # Objekt mit gespeicherten Gradienten und Deformationen der letzten l Schritte in Form von Arrays def __init__(self, gradient, deformation, length, step_nr): # Liste von Gradientenvektorfeldern if (len(gradient) == length): self.gradient = gradient else: raise SystemExit("Fehler: Anzahl der Gradienten passt nicht zur Memorylaenge!") # Liste von Deformationsvektorfeldern if (len(deformation) == length): self.deformation = deformation else: raise SystemExit("Fehler: Anzahl der Deformationen passt nicht zur Memorylaenge!") # Anzahl der gespeicherten letzten Schritte self.length = length # Anzahl der bereits ausgefuehrten l-BFGS-Schritte if (step_nr >= 0 and isinstance(step_nr, int)): self.step_nr = step_nr else: raise SystemExit("Fehler: step_nr muss Integer groesser gleich 0 sein!") # macht ein Update der Memory; neueste Elemente bekommen Index 0 def update_grad(self, upd_grad): for i in range(self.length-1): self.gradient[-(i+1)] = self.gradient[-(i+2)] self.gradient[0] = upd_grad def update_defo(self, upd_defo): for i in range(self.length-1): self.deformation[-(i+1)] = self.deformation[-(i+2)] self.deformation[0] = upd_defo def initialize_grad(self, meshData, i): # erzeugt eine FEniCS-Funktion des Gradientenfeldes i auf einem Mesh aus den gespeicherten Arrays # ermoeglicht dadurch Transport; i entspricht Index in Speichermatrix self.gradient, aufsteigend im Alter if isinstance(meshData, MeshData): pass else: raise SystemExit("initialize_grad benoetigt Objekt der MeshData-Klasse als Input!") V = VectorFunctionSpace(meshData.mesh, "P", 1, dim=2) f = Function(V) f.vector()[:] = self.gradient[i] return f def initialize_defo(self, meshData, i): # erzeugt eine FEniCS-Funktion des Deformationsfeldes i auf einem Mesh aus den gespeicherten Arrays # ermoeglicht dadurch Transport; i entspricht Index in Speichermatrix self.deformation, aufsteigend im Alter if isinstance(meshData, MeshData): pass else: raise SystemExit("initialize_defo benoetigt Objekt der MeshData-Klasse als Input!") V = VectorFunctionSpace(meshData.mesh, "P", 1, dim=2) f = Function(V) f.vector()[:] = self.deformation[i] return f def create_outputfolder(): ''' Erstelt einen Outputordner, falls nicht vorhanden ''' try: os.mkdir('Output') except OSError as exc: if exc.errno != errno.EEXIST: raise exc pass # Erstelle Ordner fuer jeden Durchlauf nach Datum und Zeit outputfolder = os.path.join(__this_files_dir, 'Output', datetime.now().strftime('%Y%m%d_%H%M%S')) os.mkdir(outputfolder) # Gibt den Pfad zum speziellen Order im Output Ordner zurueck return outputfolder def load_mesh(name): ''' Initialisiert ein Objekt der MeshData-klasse mittels per GMesh und Dolfin erzeugter .xml Dateien ''' # Pfad zur speziellen Gitter Datei path_meshFile = os.path.join(DATA_DIR, name) # Erstelle FEniCS Mesh mit Subdomains und Boundaries mesh = Mesh(path_meshFile + ".xml") subdomains = MeshFunction("size_t", mesh, path_meshFile + "_physical_region.xml") boundaries = MeshFunction("size_t", mesh, path_meshFile + "_facet_region.xml") # Berechne Indizes mit Traeger nicht am inneren Rand ind = __get_index_not_interior_boundary(mesh, subdomains, boundaries) # Rueckgabe als MeshData Objekt return MeshData(mesh, subdomains, boundaries, ind) def __get_index_not_interior_boundary(mesh, subdomains, boundaries, interior = True): """ Gibt Indizes der Elemente ohne Traeger am inneren Rand zurueck. Falls interior = False, so werden die Indizes der Vertices des Inneren Randes zurueckgegeben. Diese nicht verwechseln mit DOF-Indizes! """ # Facetten Indizes des inneren Randes bestimmen ind_interior_boundary_facets = [] for i in range(0,len(boundaries)): if boundaries[i] > 4: ind_interior_boundary_facets.append(i) # Knoten Indizes des inneren Randes bestimmen ind_interior_boundary_vertices = [] for c in cells(mesh): for f in facets(c): if f.index() in ind_interior_boundary_facets: for v in vertices(f): ind_interior_boundary_vertices.append(v.index()) if(interior == False): return list(set(ind_interior_boundary_vertices)) ind_interior_boundary_vertices = list(set(ind_interior_boundary_vertices)) # Element Indizes des inneren Randes bestimmen ind_around_interior_boundary_cells = [] for c in cells(mesh): ind = False for v in vertices(c): if v.index() in ind_interior_boundary_vertices: ind = True if ind: ind_around_interior_boundary_cells.append(c.index()) # Als neue Subdomain definieren new_sub = MeshFunction("size_t", mesh, 2) new_sub.set_all(0) for i in ind_around_interior_boundary_cells: if subdomains[i] == 1: new_sub[i] = 1 else: new_sub[i] = 2 # Indizes berechenen mit Traeger nicht am inneren Rand ueber Testproblem V = VectorFunctionSpace(mesh, "P", 1, dim=2) dx_int = Measure('dx', domain=mesh, subdomain_data=new_sub) v = TestFunction(V) dummy_y = Constant((1.0, 1.0)) f_elas_int_1 = inner(dummy_y, v)*dx_int(1) F_elas_int_1 = assemble(f_elas_int_1) f_elas_int_2 = inner(dummy_y, v)*dx_int(2) F_elas_int_2 = assemble(f_elas_int_2) # Indizes setzen durch alle Punkte mit Wert 0, die keinen Einfluss haben ind1 = (F_elas_int_1.get_local() == 0.0) ind2 = (F_elas_int_2.get_local() == 0.0) ind = ind1 | ind2 if(interior): return ind def mesh_distance(mesh1, mesh2): """ Berechnet einen integrierten Abstand der Minima aller Punkte zweier Formen. mesh2 dient dabei als Ausgangsform, d.h. von dort aus wird Abstand gemessen. Input sind Objekte der MeshData-Klasse. """ # Berechne Indizes der Vertices der Boundaries boundary_index_mesh1 = __get_index_not_interior_boundary(mesh1.mesh, mesh1.subdomains, mesh1.boundaries, interior = False) boundary_index_mesh2 = __get_index_not_interior_boundary(mesh2.mesh, mesh2.subdomains, mesh2.boundaries, interior = False) # Berechne die Abstaende alle Vertices von mesh1 zu jeweils einem festen Vertex aus mesh2, # dann bilde das Minimum und fuege in Liste hinzu distance_list_vertex = np.zeros(mesh2.mesh.num_vertices()) for i in boundary_index_mesh2: temp_distance_list = [] for j in boundary_index_mesh1: local_dist = np.linalg.norm(mesh2.mesh.coordinates()[i] - mesh1.mesh.coordinates()[j]) temp_distance_list.append(local_dist) dist = np.amin(temp_distance_list) distance_list_vertex[i] = dist # definiere eine Funktion auf mesh2 mit Abstandswerten auf Boundaries der Form V = FunctionSpace(mesh2.mesh, "P", 1) distance_function = Function(V) vtod = dolfin.vertex_to_dof_map(V) # uebersetze Vertexindizes in zugehoerige DOF-Indizes (der fenicsfunction), da Indizes nicht gleich distance_list_dof = np.zeros(len(distance_function.vector().get_local())) for i in boundary_index_mesh2: distance_list_dof[vtod[i]] = distance_list_vertex[i] # definiere Funktion auf der Form distance_function.vector()[:] = distance_list_dof # Berechne das zugehoerige Integral dS = Measure('dS', subdomain_data=mesh2.boundaries) distance_integral = distance_function('+')*dS(5) + distance_function('+')*dS(6) value = assemble(distance_integral) return value def targetfunction(meshData, deformation, y_z, fValues, nu): """ Berechnet den Wert des Zielfunktionals nach Verschiebung """ # erzeuge lokale Gitterkopie msh = Mesh(meshData.mesh) sbd = MeshFunction("size_t", msh, 2) sbd.set_values(meshData.subdomains.array()) bnd = MeshFunction("size_t", msh, 1) bnd.set_values(meshData.boundaries.array()) ind = __get_index_not_interior_boundary(msh, sbd, bnd) local_mesh = MeshData(msh, sbd, bnd, ind) # verschiebe Gitterkopie ALE.move(local_mesh.mesh, deformation) # Berechne Zustand in verschobenem Gitter y = solve_state(local_mesh, fValues) # Assembliere Zielfunktional V = FunctionSpace(local_mesh.mesh, 'P', 1) z_1 = project(y_z[0], V) z_2 = project(y_z[1], V) z = [z_1, z_2] j = 1./2.*norm(project(y[1]-z[1], V), 'L2', local_mesh.mesh)**2 ds = Measure('dS', subdomain_data=local_mesh.boundaries) ones = Function(V) ones.vector()[:] = 1. j_reg_integral = ones*ds(5) + ones*ds(6) j_reg = nu*assemble(j_reg_integral) J = j + j_reg return J def shape_deriv(meshData, p, y, z, fValues, nu, V): """ Berechnet die Formableitung in Richtung V; V ist FEniCS Funktion, z ist Projektion von y_z """ dx = Measure('dx', domain=meshData.mesh, subdomain_data=meshData.subdomains) dS = Measure('dS', subdomain_data=meshData.boundaries) f1 = Constant(fValues[0]) f2 = Constant(fValues[1]) epsilon_V = sym(nabla_grad(V)) n = FacetNormal(meshData.mesh) # Gradient f ist 0, da f stueckweise konstant Dj = ((-inner(grad(y[0]), dot(epsilon_V*2, grad(p[0]))) -inner(grad(y[1]), dot(epsilon_V * 2, grad(p[1])))) * dx + nabla_div(V) * (1 / 2 * (y[1] - z[1]) ** 2 + inner(grad(y[0]), grad(p[0])) + inner(grad(y[1]), grad(p[1]))) * dx - nabla_div(V)*(f1*p[0] + y[0]*p[1])*dx(1) - nabla_div(V)*(f2*p[0] + y[0]*p[1])*dx(2)) Dj_reg = nu*((nabla_div(V('+')) - inner(dot(nabla_grad(V('+')), n('+')), n('+')))*dS(5) + (nabla_div(V('+')) - inner(dot(nabla_grad(V('+')), n('+')), n('+')))*dS(6)) deriv = assemble(Dj + Dj_reg) return deriv def solve_state(meshData, fValues): """ Loest Zustandsgleichung ohne Variationsungleichung """ # Funktionen Raum V = FunctionSpace(meshData.mesh, "P", 1) # Randbedingungen y_out = Constant(0.0) bcs = [ DirichletBC(V, y_out, meshData.boundaries, i) for i in range(1, 5) ] # Problem definieren dx = Measure('dx', domain=meshData.mesh, subdomain_data=meshData.subdomains) f1 = Constant(fValues[0]) f2 = Constant(fValues[1]) # Loesung der ersten Gleichung berechnen y_trial = TrialFunction(V) v = TestFunction(V) a = lhs(inner(grad(y_trial), grad(v))*dx('everywhere')) b = rhs(f1*v*dx(1) + f2*v*dx(2)) y_1 = Function(V, name="state_sol") solve(a == b, y_1, bcs) # Loesung der zweiten Gleichung berechnen y_trial = TrialFunction(V) v = TestFunction(V) a = lhs(inner(grad(y_trial), grad(v))*dx('everywhere')) b = rhs(y_1*v*dx('everywhere')) y_2 = Function(V, name="state_sol") solve(a == b, y_2, bcs) # Rueckgabe der Loesungen y = [y_1, y_2] #y.rename("state_sol", "label") return y def solve_adjoint(meshData, y, z): """ Loest Adjungierte Gleichung ohne Variationsungleichung """ # Funktionen Raum V = FunctionSpace(meshData.mesh, "P", 1) # Randbedingungen p_out = Constant(0.0) bcs = [ DirichletBC(V, p_out, meshData.boundaries, i) for i in range(1, 5) ] # Variationsproblem definieren dx = Measure('dx', domain=meshData.mesh, subdomain_data=meshData.subdomains) # Loesung der ersten Gleichung berechnen p_trial = TrialFunction(V) v = TestFunction(V) a = lhs(inner(grad(p_trial), grad(v))*dx) l = rhs(-y[1]*v*dx + z[1]*v*dx) p_1 = Function(V) solve(a == l, p_1, bcs) # Loesung der zweiten Gleichung berechnen p_trial = TrialFunction(V) v = TestFunction(V) a = lhs(inner(grad(p_trial), grad(v))*dx) l = rhs(p_1*v*dx) p_2 = Function(V) solve(a == l, p_2, bcs) # Rueckgabe der Loesung # ACHTUNG: ERSTER EINTRAG VON P ENTSPRICHT ZWEITEM EINTRAG VON Y UND VICE VERSA (muss noch geaendert werden) p = [p_2, p_1] return p def calc_lame_par(meshData, mu_min_value, mu_max_value): """ Berechnet die lokal variierenden Lame-Parameter mu_elas """ # Funktionen Raum V = FunctionSpace(meshData.mesh, "P", 1) # Randbedingungen mu_min = Constant(mu_min_value) mu_max = Constant(mu_max_value) bcs = ([ DirichletBC(V, mu_min, meshData.boundaries, i) for i in range(1, 5) ] + [ DirichletBC(V, mu_max, meshData.boundaries, i) for i in range(5, 7) ]) # Variationsproblem definieren dx = Measure('dx', domain=meshData.mesh, subdomain_data=meshData.subdomains) mu_elas = TrialFunction(V) v = TestFunction(V) f = Expression("0.0", degree=1) a = inner(grad(mu_elas), grad(v))*dx l = f*v*dx # Loesung berechnen mu_elas = Function(V, name="lame_par") solve(a == l, mu_elas, bcs) # Rueckgabe des Lame-Parameters return mu_elas def solve_linelas(meshData, p, y, z, fValues, mu_elas, nu, zeroed = True): """ Loest lineare Elastizitaetsgleichung ohne Variationsungleichung """ # Funktionenraum V = VectorFunctionSpace(meshData.mesh, "P", 1, dim=2) # Randbedingungen u_out = Constant((0.0, 0.0)) bcs = [ DirichletBC(V, u_out, meshData.boundaries, i) for i in range (1, 5) ] U = TrialFunction(V) v = TestFunction(V) LHS = bilin_a(meshData, U, v, mu_elas) F_elas = shape_deriv(meshData, p, y, z, fValues, nu, v) # Alle die keine Traeger am innerend Rand haben auf 0 setzen if(zeroed): F_elas[meshData.indNotIntBoundary] = 0.0 for bc in bcs: bc.apply(LHS) bc.apply(F_elas) # Norm der assemblierten rechten Seite wegen Abbruchbedingung nrm_f_elas = norm(F_elas, 'L2', meshData.mesh) # Berechne Loesung U = Function(V, name="deformation_vec") solve(LHS, U.vector(), F_elas) # Rueckgabe des Gradientenvektorfeldes U und der Abbruchbedingung return U, nrm_f_elas def bilin_a(meshData, U, V, mu_elas): """ Berechnet den Wert der Bilinearform (lin. El.) fuer gegebene Vektorfelder U, V Beide Vektorfelder muessen auf dem selben Mesh definiert sein Lame parameter lambda = 0 """ dx = Measure("dx", domain=meshData.mesh, subdomain_data=meshData.subdomains) epsilon_V = (1./2.)*sym(nabla_grad(V)) sigma_U = mu_elas*sym(nabla_grad(U)) a = inner(sigma_U, epsilon_V)*dx('everywhere') value = assemble(a) return value def bfgs_step(meshData, memory, mu_elas, q_target): """ berechnet aus einer BFGS-memory eine Mesh-Deformation q mittels double-loop-L-BFGS-Verfahren, welche zu memory.grad[0] gehoert benoetigt memory.grad[0] als aktuellen Gradienten, memory.deformation[0] als aktuell neueste Deformation Output q ist eine Fenics-Funktion der Art Function(V), V=VectorFunctionSpace(mesh, "P", 1, dim=2) """ if isinstance(meshData, MeshData): pass else: raise SystemExit("bfgs_step benoetigt Objekt der MeshData-Klasse als Input!") if isinstance(memory, bfgs_memory): pass else: raise SystemExit("bfgs_step benoetigt Objekt der BFGS-Memory-Klasse als Input!") V = VectorFunctionSpace(meshData.mesh, "P", 1, dim=2) q = Function(V) q.vector()[:] = q_target alpha = np.zeros(memory.length) diff_grad = Function(V) first_diff_grad = Function(V) if(memory.step_nr + 1 >= memory.length): # bei voll besetzter memory werden alle Eintraege verwendet for i in range(memory.length-1): # Vorwaertsschleife i = i+1 diff_grad.vector()[:] = (memory.initialize_grad(meshData, i-1).vector() - memory.initialize_grad(meshData, i).vector()) alpha[i] = bilin_a(meshData, memory.initialize_defo(meshData, i-1), q, mu_elas) / bilin_a(meshData, diff_grad, memory.initialize_defo(meshData, i-1), mu_elas) q.vector()[:] = q.vector() - float(alpha[i])*diff_grad.vector() # Reskalierung von q first_diff_grad.vector()[:] = (memory.initialize_grad(meshData, 0).vector() - memory.initialize_grad(meshData, 1).vector()) gamma = bilin_a(meshData, first_diff_grad, memory.initialize_defo(meshData, 0), mu_elas) / bilin_a(meshData, first_diff_grad, first_diff_grad, mu_elas) q.vector()[:] = gamma*q.vector() for i in range(memory.length-1): # Rueckwaertsschleife i = i+1 diff_grad.vector()[:] = (memory.initialize_grad(meshData, -(i+1)).vector() - memory.initialize_grad(meshData, -i).vector()) beta = bilin_a(meshData, diff_grad, q, mu_elas) / bilin_a(meshData, diff_grad, memory.initialize_defo(meshData, -(i+1)), mu_elas) q.vector()[:] = q.vector() + (float(alpha[-i]) - beta)*memory.initialize_defo(meshData, -(i+1)).vector() elif(memory.step_nr == 0): # der erste BFGS-Schritt ist ein Gradientenschritt, U Gradient ist in negativer Richtung q.vector()[:] = -1.*q.vector().get_local() return q else: # bei nicht voll besetzter memory werden lediglich die besetzten Eintraege verwendet for i in range(memory.step_nr): # Vorwaertsschleife i = i+1 diff_grad.vector()[:] = (memory.initialize_grad(meshData, i-1).vector() - memory.initialize_grad(meshData, i).vector()) alpha[i] = bilin_a(meshData, memory.initialize_defo(meshData, i-1), q, mu_elas) / bilin_a(meshData, diff_grad, memory.initialize_defo(meshData, i-1), mu_elas) q.vector()[:] = q.vector() - float(alpha[i])*diff_grad.vector() # Reskalierung von q first_diff_grad.vector()[:] = (memory.initialize_grad(meshData, 0).vector() - memory.initialize_grad(meshData, 1).vector()) gamma = bilin_a(meshData, first_diff_grad, memory.initialize_defo(meshData, 0), mu_elas) / bilin_a(meshData, first_diff_grad, first_diff_grad, mu_elas) q.vector()[:] = gamma*q.vector() for i in range(memory.step_nr): # Rueckwaertsschleife shift = (memory.length-1) - memory.step_nr i = i+1 diff_grad.vector()[:] = (memory.initialize_grad(meshData, -(i+1)-shift).vector() - memory.initialize_grad(meshData, -i-shift).vector()) beta = bilin_a(meshData, diff_grad, q, mu_elas) / bilin_a(meshData, diff_grad, memory.initialize_defo(meshData, -(i+1)-shift), mu_elas) q.vector()[:] = q.vector() + (float(alpha[-i-shift]) - beta)*memory.initialize_defo(meshData, -(i+1)-shift).vector() q.vector()[:] = -1. * q.vector() return q
66a39a34eff12eb71962f9ffa8063c7ad26973d1
[ "Python" ]
4
Python
LuftDaniel/Polyharmonic_shape
c213d31ab8638c582fde66682102fe26381984c9
5eb0aaa99875d4a58c0f7604c5380c5d86083246
refs/heads/master
<repo_name>Shashikanth101/Event-Notifier<file_sep>/functions/index.js const functions = require('firebase-functions'); const sendMail = require('./helpers/sendMail.js'); const { getSpreadsheetData } = require('./helpers/spreadsheet.js'); // Run once everyday at 6 am Indian Standard Time exports.checkForEvents = functions.region('asia-south1').pubsub.schedule('0 6 * * *').timeZone('Asia/Kolkata').onRun(async context => { const { spreadsheet_uri, smtp_config } = functions.config().eventnotifier; const { err, data: eventData } = await getSpreadsheetData(spreadsheet_uri); if (err) return sendMail({ err, smtp_config }); // current Date const currentDate = new Date(); const day = currentDate.getUTCDate(); const month = currentDate.getUTCMonth() + 1; // Check if there is any event today eventData.forEach(entry => { const [eventPerson, eventDay, eventMonth, eventType] = entry; if (Number(eventDay) === day && Number(eventMonth) === month) { sendMail({ event: { message: `Wish ${eventPerson}, A Happy ${eventType} today i.e., on ${day}/${month}`, eventType }, smtp_config: smtp_config }); } }); });<file_sep>/functions/helpers/spreadsheet.js const { GoogleSpreadsheet } = require('google-spreadsheet'); const credentials = require('./client_secret.json'); const getSpreadsheetData = async (SPREADSHEET_URI) => { try { const doc = new GoogleSpreadsheet(SPREADSHEET_URI); await doc.useServiceAccountAuth(credentials); await doc.loadInfo(); // Get the first sheet from the document const sheet = doc.sheetsByIndex[0]; // Get and format row data const rows = await sheet.getRows(); const data = rows.map(row => [...row._rawData]); return { data }; } catch (err) { return { err }; } } module.exports = { getSpreadsheetData };<file_sep>/functions/helpers/sendMail.js const nodemailer = require('nodemailer'); async function sendMail ({ err, event, smtp_config }) { const { eventType, message: eventMessage } = event // Environmant variables const { smtp_host: SMTP_HOST, smtp_port: SMTP_PORT, smtp_service: SMTP_SERVICE, email_id: EMAIL_ID, email_password: <PASSWORD>, receiver_email_id: RECEIVER_EMAIL_ID } = smtp_config; // Construct an SMTP transporter const transport = nodemailer.createTransport({ host: SMTP_HOST, port: SMTP_PORT, service: SMTP_SERVICE, secure: false, auth: { user: EMAIL_ID, pass: <PASSWORD> }, debug: false, logger: true }); // default message body const message = { from: `"From: <NAME>" <${EMAIL_ID}>`, to: RECEIVER_EMAIL_ID } // Message to be sent message.subject = err ? 'Error' : `Firebase Events: ${eventType} Reminder`; message.html = err ? err : `<div style="width: 100%; height: 40vh; font-family: sans-serif"> <div style="max-width: 70%; background-color: #0070F3; margin: 30px auto 0; padding: 10px; border-radius: 10px; text-align: center"> <h1 style="color: #FFF">${eventMessage}</h1> </div> <p style="color: #555; font-size: 0.9rem; text-align: center">Sent using Firebase functions | Shashikanth P &#169; 2020</p> </div>`; transport.sendMail(message, (err, info) => { if (err) { console.log('Error: '); console.log(err); } else { console.log('Success: '); console.log(info); } }); } module.exports = sendMail;<file_sep>/README.md # Event-Notifier A Firebase cloud function to notify about events through email ## Description A Cron Job that runs once every day at 6am. It reads a shared Google Spreadsheet for any events on that particular date. If there is one, it sends an email to the receiver with details about that event. ## Pre requisites - Make sure to have an email account which supports nodemailer. [(Check Article)](https://nodemailer.com/smtp/well-known/) - Make sure you have node.js and npm already installed and clone this repository - Save all event data in a google spreadsheet in the format [ Name | Day | Month | Event_Type ]. Example: [ Mom | 24 | 8 | Birthday ] - Make sure you have firebase-cli installed. If not, enter the below command in your terminal to install it globally ```bash npm install firebase-tools -g ``` ## Installation and Usage - Create a new project on Firebase, download the credntials and rename it to `client_secret.json` - Move this file inside `functions/helpers` directory of the project - Enable Google sheets API on GCP console under your project - Add the 'client_email' from the downloaded credentials to your google spreadsheet - Change your directory to `functions` and enter the below command to install dependencies ```bash npm install ``` Save all your credentials on firebase config environment as shown below. [(Check Article)](https://firebase.google.com/docs/functions/config-env) ```javascript { "eventnotifier": { "smtp_config": { "smtp_port": "<your_smtp_port>", "smtp_host": "<your_smtp_host>", "email_id": "<your_email_id>", "email_password": "<<PASSWORD>>", "smtp_service": "<your_smtp_service_provider>", "receiver_email_id": "<receiver_email_id>" }, "spreadsheet_uri": "<your_spreadsheet_uri>" } } ``` Enter the below command to deploy the function ```bash firebase deploy --only functions ```
d0b09a1ce15cc2f1a6f12f3016f4cac020db5464
[ "JavaScript", "Markdown" ]
4
JavaScript
Shashikanth101/Event-Notifier
a3ac456bb2c6f06173a47d865f86454956f96661
195111e5952fb626f5c7a50ac1ec48570fac8ca1
refs/heads/master
<repo_name>AzhirAhmadi/vue_jokester<file_sep>/src/store/actions.js import * as types from './mutation-types' export const initJokes = ({commit}) => { let fecths = [] for(let i=0;i<10;i++){ fecths.push(fetch('https://sv443.net/jokeapi/category/Any',{ method: 'GET' }).then(response => response.json())) } let combinedData = []; Promise.all(fecths).then(function(values){ for(let i=0;i<10;i++){ combinedData.push(values[i]) } commit(types.INIT_JOKES, combinedData) }); } export const addJoke = ({commit}) => { fetch('https://sv443.net/jokeapi/category/Any',{ method: 'GET' }).then(response => response.json()) .then(json => commit(types.ADD_JOKE, json)) } export const removeJoke = ({commit}, index) => { commit(types.REMOVE_JOKE, index) }
b1e22269bcd2095c63200e674a7445f144f3da05
[ "JavaScript" ]
1
JavaScript
AzhirAhmadi/vue_jokester
66278adb7980994341fcfed698d89e9d67e0c319
ea3ab0855a67e14530f4f643e7aaf30311977645
refs/heads/master
<repo_name>paulstandley/find-doc-wr<file_sep>/client.crisp.chat/static/javascripts/locales/en.js /** * crisp-client - Customer Messaging Made Simple. * @version v2.5.5 * @author Crisp IM SARL https://crisp.chat/ * @date 10/11/2019 */ window.$crisp.__spool.locale_handler({ _meta: { locale_name: "English", locale_code: "en", locale_direction: "ltr" }, _strings: { date: { hour_singular: "An hour ago", hour_plural: "%1s hours ago", minute_singular: "A minute ago", minute_plural: "%1s minutes ago", second: "A few seconds ago", now: "Just now" }, duration: { days: "A few days", hour_singular: "An hour", hour_plural: "%1s hours", minute_singular: "A minute", minute_plural: "%1s minutes", second: "A few seconds", now: "Instantly" }, days: { monday: "Monday", tuesday: "Tuesday", wednesday: "Wednesday", thursday: "Thursday", friday: "Friday", saturday: "Saturday", sunday: "Sunday" }, months: { january: "January", february: "February", march: "March", april: "April", may: "May", june: "June", july: "July", august: "August", september: "September", october: "October", november: "November", december: "December" }, theme_text: { default_chat: "Questions? Chat with us!", "1_chat": "Questions? Chat with me!", "2_chat": "Ask us your questions", "3_chat": "Ask me your questions", "4_chat": "Chat with support" }, theme_welcome: { default_chat: "How can we help with %1s?", "1_chat": "Hey, want to chat with us?", "2_chat": "Anything you want to ask?", "3_chat": "Hello, ask us any question about %1s.", "4_chat": "Hello! How can I help you? :)", "5_chat": "Any question about %1s?" }, minimized: { unauthorized_pane: "Invalid website", tooltip_entice_status_online: "Support is online.", tooltip_entice_status_away: "Support is away.", tooltip_entice_full_chat: "Chat with %1s Team", tooltip_entice_split_helpdesk: "Search help center", tooltip_entice_split_chat: "Chat" }, chat: { minimized_tooltip_message_from: "Message from", minimized_connect_alert_failure: "Failed to connect. Messaging may be unavailable at the moment.", chat_header_ongoing_from: "from", chat_header_ongoing_status_metrics: "Typically replies under %1s", chat_header_ongoing_status_last: "Was last active %1s", chat_header_ongoing_status_online: "Support is online", chat_header_ongoing_status_away: "Support is away", chat_alerts_new_messages: "There are new messages below. Click to see.", chat_alerts_email_invalid: "You mistyped your email, can you check it?", chat_alerts_wait_reply_online: "Thanks! We should reply in a few moments.", chat_alerts_wait_reply_away: "We are not online. We will email you back.", chat_pickers_selector_smileys: "Smileys", chat_pickers_selector_gifs: "GIFs", chat_pickers_gif_search: "Find GIFs...", chat_pickers_gif_no_results: "No results. Try another search.", chat_message_file_name: "Attached file", chat_message_file_button: "Download file", chat_message_tag_edited: "Edited", chat_message_tag_translated: "Translated", chat_message_info_read: "Read", chat_message_error_retry: "Failed to send. Retry?", chat_message_send_abort_warn: "Some messages have not yet been sent. Navigating will prevent them from being sent.", chat_form_field_message: "Compose your message...", chat_form_field_disabled: "Messaging is unavailable.", chat_form_smiley_tooltip: "Insert an emoji", chat_form_attach_tooltip: "Send a file", chat_form_attach_alert_quota: "Daily file upload quota has been exceeded, or file extension is not allowed.", chat_form_attach_alert_size: "File too large. Please reduce its size and try again.", chat_form_attach_alert_error: "An error occured while uploading the file. Please try again.", chat_form_attach_abort_warn: "Navigating when a file is being uploaded will stop upload.", minimized_tooltip_message_compose: "Compose your reply...", chat_game_controls_stop: "Stop playing", chat_header_ongoing_channel_continue: "Continue on %1s", chat_header_ongoing_channel_continue_email: "Email", chat_message_text_identity_main: "Just in case you leave or we reply later:", chat_message_text_identity_ask: "how do you want us to get back to you?", chat_message_text_identity_pick_email: "Email", chat_message_text_identity_pick_phone: "Phone", chat_message_text_identity_ask_email: "What is your email address?", chat_message_text_identity_ask_field_email: "Enter your email address...", chat_message_text_identity_ask_phone: "What is your phone number?", chat_message_text_identity_ask_field_phone: "Enter your phone number...", chat_message_text_identity_ask_field_submit: "OK", chat_message_text_game_main: "Looks like we are taking time to reply.", chat_message_text_game_ask: "While you wait, want to play a cool game?", chat_message_text_game_pick_yes: "Play a game", chat_message_text_game_pick_no: "No, thanks", chat_alerts_warn_reply_email_default: "Click to set your email to get notifications.", chat_alerts_warn_reply_email_force: "Please set your email to continue.", chat_alerts_warn_reply_phone_default: "Click to set your phone to get notifications.", chat_alerts_warn_reply_phone_force: "Please set your phone to continue.", chat_welcome_helpdesk: "Search on Helpdesk", chat_header_ongoing_channel_continue_phone: "Phone", chat_offline_main: "Network offline. Reconnecting...", chat_offline_fail: "Offline. Please reload the page.", chat_offline_label: "No messages can be received or sent for now.", chat_health_main: "Some of our services are not working.", chat_health_label_link: "See our status page", chat_health_label_updates: "for more updates.", chat_form_attach_confirm_upload: "Upload this pasted file?" }, article: { controls_close: "Close article", controls_view: "View in Helpdesk" }, spotlight: { search_form_field: "Search our help center...", action_close: "Close search", action_open: "Open Helpdesk", result_view: "View", result_empty: "Sorry, no search results were found. Try with another keyword." }, call: { ring_title_website: "%1s support", ring_title_label: "%1s is calling you...", ring_actions_decline: "Decline", ring_actions_accept: "Accept", screen_label_audio_muted: "Audio muted", screen_label_video_muted: "Video muted", screen_status_connecting: "Connecting...", screen_status_ongoing: "Ongoing", call_abort_warn: "Navigating when a call is ongoing will stop the call." }, browsing: { assist_mouse_tooltip: "%1s is assisting you" } } });<file_sep>/settings.crisp.chat/client/website/b5899eb1-b0f5-4c9b-a3ce-3ff26ba107b6/index.html window.$crisp.__spool.website_handler({"website":"Cater For You","domain":"cater4you.co.uk","mailer":"cater4you.on.crisp.email","settings":{"logo":null,"rating":true,"transcript":true,"enrich":true,"junk_filter":true,"tile":"default","wait_game":false,"last_operator_face":false,"ongoing_operator_face":true,"activity_metrics":false,"operator_privacy":false,"availability_tooltip":false,"hide_vacation":false,"hide_on_away":true,"hide_on_mobile":false,"position_reverse":false,"email_visitors":false,"phone_visitors":false,"force_identify":false,"ignore_privacy":false,"file_transfer":true,"helpdesk_link":false,"status_health_dead":true,"check_domain":false,"color_theme":"default","text_theme":"default","welcome_message":"default","locale":"","allowed_pages":[],"blocked_pages":[],"blocked_countries":[],"blocked_locales":[],"blocked_ips":[]},"operators":[{"user_id":"ced328b4-7a85-4e1f-a83a-ca38e0f7b142","avatar":"https://storage.crisp.chat/users/avatar/operator/ced328b4-7a85-4e1f-a83a-ca38e0f7b142/c9bb9f11-8f60-4861-bd54-3e4d12c4f7ee.jpg","nickname":"<NAME>","timestamp":1575547898543}],"plugins":{"urn:crisp.im:triggers:0":{"settings":{}},"urn:crisp.im:customization:0":{"settings":{}}},"online":true,"trial":false,"channels":{}});<file_sep>/platform.twitter.com/js/momenttimelinetweet.cb38d07468ec6018c11772ae620672f0.js (window.__twttrll = window.__twttrll || []).push([ [0], { 170: function(t, e, r) { var i = r(41), n = r(173), o = r(7); (i = Object.create(i)).build = o(i.build, null, n), t.exports = i }, 171: function(t, e, r) { var i = r(40), n = r(35), o = r(39), s = r(0), a = r(7), c = r(34), u = r(5), l = r(177); t.exports = function(t) { t.params({ partner: { fallback: a(c.val, c, "partner") } }), t.define("scribeItems", function() { return {} }), t.define("scribeNamespace", function() { return { client: "tfw" } }), t.define("scribeData", function() { return { widget_origin: o.rootDocumentLocation(), widget_frame: o.isFramed() && o.currentDocumentLocation(), widget_partner: this.params.partner, widget_site_screen_name: l(c.val("site")), widget_site_user_id: u.asNumber(c.val("site:id")), widget_creator_screen_name: l(c.val("creator")), widget_creator_user_id: u.asNumber(c.val("creator:id")) } }), t.define("scribe", function(t, e, r) { t = s.aug(this.scribeNamespace(), t || {}), e = s.aug(this.scribeData(), e || {}), i.scribe(t, e, !1, r) }), t.define("scribeInteraction", function(t, e, r) { var i = n.extractTermsFromDOM(t.target); i.action = t.type, "url" === i.element && (i.element = n.clickEventElement(t.target)), this.scribe(i, e, r) }) } }, 172: function(t, e, r) { var i = r(5), n = r(0); t.exports = function(t) { t.define("widgetDataAttributes", function() { return {} }), t.define("setDataAttributes", function() { var t = this.sandbox.sandboxEl; n.forIn(this.widgetDataAttributes(), function(e, r) { i.hasValue(r) && t.setAttribute("data-" + e, r) }) }), t.after("render", function() { this.setDataAttributes() }) } }, 173: function(t, e, r) { var i = r(42), n = r(0), o = r(174); function s() { i.apply(this, arguments), this.Widget = this.Component } s.prototype = Object.create(i.prototype), n.aug(s.prototype, { factory: o, build: function() { return i.prototype.build.apply(this, arguments) }, selectors: function(t) { var e = this.Widget.prototype.selectors; t = t || {}, this.Widget.prototype.selectors = n.aug({}, t, e) } }), t.exports = s }, 174: function(t, e, r) { var i = r(6), n = r(36), o = r(43), s = r(0), a = r(7), c = r(175), u = "twitter-widget-"; t.exports = function() { var t = o(); function e(e, r) { t.apply(this, arguments), this.id = u + c(), this.sandbox = r } return e.prototype = Object.create(t.prototype), s.aug(e.prototype, { selectors: {}, hydrate: function() { return i.resolve() }, prepForInsertion: function() {}, render: function() { return i.resolve() }, show: function() { return i.resolve() }, resize: function() { return i.resolve() }, select: function(t, e) { return 1 === arguments.length && (e = t, t = this.el), t ? (e = this.selectors[e] || e, s.toRealArray(t.querySelectorAll(e))) : [] }, selectOne: function() { return this.select.apply(this, arguments)[0] }, selectLast: function() { return this.select.apply(this, arguments).pop() }, on: function(t, e, r) { var i, o = this.el; this.el && (t = (t || "").split(/\s+/), 2 === arguments.length ? r = e : i = e, i = this.selectors[i] || i, r = a(r, this), t.forEach(i ? function(t) { n.delegate(o, t, i, r) } : function(t) { o.addEventListener(t, r, !1) })) } }), e } }, 175: function(t, e) { var r = 0; t.exports = function() { return String(r++) } }, 177: function(t, e) { t.exports = function(t) { return t && "@" === t[0] ? t.substr(1) : t } }, 178: function(t) { t.exports = { TWEET: 0, RETWEET: 10, CUSTOM_TIMELINE: 17, LIVE_VIDEO_EVENT: 28, QUOTE_TWEET: 23 } }, 179: function(t, e, r) { var i = r(178); t.exports = function(t) { return t ? (t = Array.isArray(t) ? t : [t]).reduce(function(t, e) { var r = e.getAttribute("data-tweet-id"), n = e.getAttribute("data-rendered-tweet-id") || r; return e.getAttribute("data-tweet-item-type") === i.QUOTE_TWEET.toString() ? t[r] = { item_type: i.QUOTE_TWEET } : r === n ? t[n] = { item_type: i.TWEET } : r && (t[n] = { item_type: i.RETWEET, target_type: i.TWEET, target_id: r }), t }, {}) : {} } }, 180: function(t, e, r) { var i = r(71), n = r(183), o = r(7), s = r(72); function a(t, e, r, o) { var a, c; return r = function(t) { return "dark" === t ? "dark" : "light" }(r), a = i.isRtlLang(e) ? "rtl" : "ltr", c = [t, o ? n.holdback_css : n.css, r, a, "css"].join("."), s.resourceBaseUrl + (o ? "/holdback" : "") + "/css/" + c } t.exports = { dmButton: function() { return s.resourceBaseUrl + "/css/" + ["dm_button", n.css, "css"].join(".") }, tweet: o(a, null, "tweet"), timeline: o(a, null, "timeline"), video: o(a, null, "video"), moment: o(a, null, "moment"), grid: o(a, null, "grid"), periscopeOnAir: function() { return s.resourceBaseUrl + "/css/" + ["periscope_on_air", n.css, "css"].join(".") } } }, 181: function(t, e, r) { var i = r(33), n = r(170), o = r(179); t.exports = n.couple(r(171), function(t) { t.selectors({ tweetIdInfo: ".js-tweetIdInfo", quotedTweetInfo: '[data-tweet-item-type="23"]' }), t.define("scribeClickInteraction", function(t, e) { var r = i.closest(this.selectors.tweetIdInfo, e, this.el), n = r && r.querySelector(this.selectors.quotedTweetInfo); this.scribeInteraction(t, function(t, e) { var r; if (t) return r = o(e ? [t, e] : [t]), { item_ids: Object.keys(r), item_details: r } }(r, n)) }), t.after("render", function() { this.on("click", "A", this.scribeClickInteraction), this.on("click", "BUTTON", this.scribeClickInteraction) }) }) }, 182: function(t, e, r) { var i = r(187), n = r(30), o = r(3), s = r(6), a = "data-url-ref-attrs-injected"; t.exports = function(t) { var e = {}; t.define("injectRefUrlParams", function(t) { return o.isTwitterURL(t.href) ? t.getAttribute(a) ? s.resolve() : (e = { twcamp: this.params.productName, twterm: this.params.id, twcon: t.getAttribute("data-twcon") }, n.getActiveExperimentDataString().then(function(r) { t.setAttribute(a, !0), e.twgr = r, t.href = i(t.href, e) }.bind(this)).catch(function() { t.setAttribute(a, !0), t.href = i(t.href, e) }.bind(this))) : s.resolve() }), t.after("render", function() { this.on("click", "A", function(t, e) { this.injectRefUrlParams(e) }) }) } }, 183: function(t) { t.exports = { css: "a4ac5782325ad1b5e51c8b06daf47853", holdback_css: "a4ac5782325ad1b5e51c8b06daf47853" } }, 184: function(t, e, r) { var i = r(4), n = r(5), o = i.createElement("div"); t.exports = function(t) { return n.isNumber(t) && (t += "px"), o.style.width = "", o.style.width = t, o.style.width || null } }, 185: function(t, e, r) { var i = r(35), n = r(170), o = r(44), s = r(188); t.exports = n.couple(r(171), function(t) { t.selectors({ inViewportMarker: ".js-inViewportScribingTarget" }), t.define("scribeInViewportSeen", function(t, e) { var r = i.extractTermsFromDOM(t); r.action = "seen", this.scribe(r, e, o.version) }), t.after("show", function() { var t = this.selectors.inViewportMarker; this.select(t).forEach(function(t) { t && s.inViewportOnce(t, this.sandbox.sandboxEl, function() { this.scribeInViewportSeen(t, this.scribeItems()) }.bind(this)) }, this) }) }) }, 187: function(t, e, r) { var i = r(11), n = r(39), o = "^", s = "|", a = "twsrc", c = "twterm", u = "twcamp", l = "twgr", d = "twcon"; function f(t, e) { return t + o + e } t.exports = function(t, e) { var r = [f(a, "tfw")]; return e && (r = r.concat(function(t) { var e = []; return t.twcamp && e.push(f(u, t.twcamp)), t.twterm && e.push(f(c, t.twterm)), t.twgr && e.push(f(l, t.twgr)), t.twcon && e.push(f(d, t.twcon)), e }(e))), function(t, e) { return i.url(t, { ref_src: e, ref_url: n.rootDocumentLocation() }) }(t, function(t) { return t.reduce(function(t, e) { return t + s + e }) }(r)) } }, 188: function(t, e, r) { var i = r(202), n = r(47), o = r(203), s = r(1), a = r(21), c = function(t) { return (s.requestIdleCallback || s.requestAnimationFrame || function(t) { t() })(t) }, u = function() { this.observers = [] }; u.prototype._register = function(t, e, r) { var n, u = this; return a.hasIntersectionObserverSupport() ? ((n = new s.IntersectionObserver(function(t) { t.forEach(function(t) { t.intersectionRatio >= 1 && (c(r), u._unregister(n)) }) }, { threshold: 1 })).observe(t), n) : (n = { update: function(o, s) { i(t, { viewportWidth: o, viewportHeight: s, sandboxEl: e }) && (r(), u._unregister(n)) } }, this.observers.push(n), 1 === this.observers.length && (this.unlisten = o.addScrollListener(this._onViewportChange.bind(this))), this._onViewportChange(), n) }, u.prototype._unregister = function(t) { var e; a.hasIntersectionObserverSupport() && t instanceof s.IntersectionObserver ? t.disconnect() : (e = this.observers.indexOf(t)) > -1 && (this.observers.splice(e, 1), 0 === this.observers.length && this.unlisten && this.unlisten()) }, u.prototype._onViewportChange = function() { n(c(function() { this._notify(o.getWidth(), o.getHeight()) }.bind(this)), 50, this) }, u.prototype._notify = function(t, e) { this.observers.forEach(function(r) { r.update(t, e) }) }, u.prototype.inViewportOnce = function(t, e, r) { return this._register(t, e, r) }, t.exports = new u }, 190: function(t, e, r) { var i = r(18), n = r(191), o = 375; t.exports = function(t) { t.after("prepForInsertion", function(t) { n.sizeIframes(t, this.sandbox.width, o, i.sync) }), t.after("resize", function() { n.sizeIframes(this.el, this.sandbox.width, o, i.write) }) } }, 191: function(t, e, r) { var i = r(1), n = r(0), o = r(46), s = r(11), a = r(82), c = r(21), u = r(225), l = r(10), d = "https://pbs.twimg.com/cards/player-placeholder", f = /max-width:\s*([\d.]+px)/, h = /top:\s*(-?[\d.]+%)/, p = /left:\s*(-?[\d.]+%)/, m = /padding-bottom:\s*([\d.]+%)/, b = { 64: "tiny", 120: "120x120", 240: "240x240", 360: "360x360", 680: "small", 900: "900x900", 1200: "medium", 2048: "large", 4096: "4096x4096" }, g = Object.keys(b).sort(function(t, e) { return t - e }), v = 2; function w(t, e) { t.getAttribute("data-image") === d ? t.src = d + ".png" : t.getAttribute("data-image") ? x(t, e) : E(t, e) } function y(t, e, r) { var i, n, o, s, a; if (n = I(t), o = e.split(",").map(function(t) { return new function(t) { var e = t.split(" "); this.url = decodeURIComponent(e[0].trim()), this.width = +e[1].replace(/w$/, "").trim() }(t.trim()) }), r) for (a = 0; a < o.length; a++) o[a].url === r && (i = o[a]); return s = o.reduce(function(t, e) { return e.width < t.width && e.width >= n ? e : t }, o[0]), i && i.width > s.width ? i : s } function x(t, e) { var r, i, n, o, c, u, l; i = (r = s.decodeURL(t.src).name) && a(g, function(t) { if (b[t] === r) return t }), n = function(t) { return { width: parseInt(t.getAttribute("width")), height: parseInt(t.getAttribute("height")) || 1 } }(t), i >= (c = ((l = n).height > l.width ? I(e) * n.height / n.width : I(e)) || 680) || (o = t.getAttribute("data-image"), u = a(g, function(t) { if (t >= c) return t }) || 4096, t.src = s.url(o, { format: t.getAttribute("data-image-format") || "jpg", name: b[u] })) } function I(t) { return i.devicePixelRatio ? t * Math.min(i.devicePixelRatio, v) : t } function E(t, e) { var r, i = t.getAttribute("data-srcset"), n = t.src; i && (r = y(e, i, n), t.src = r.url) } function C(t, e, r) { t && (n.toRealArray(t.querySelectorAll(".NaturalImage-image")).forEach(function(t) { r(function() { w(t, e) }) }), n.toRealArray(t.querySelectorAll(".CroppedImage-image")).forEach(function(t) { r(function() { w(t, e / 2) }) }), n.toRealArray(t.querySelectorAll("img.autosized-media")).forEach(function(t) { r(function() { w(t, e), t.removeAttribute("width"), t.removeAttribute("height") }) })) } function _(t, e, r, i) { t && n.toRealArray(t.querySelectorAll("iframe.autosized-media, .wvp-player-container")).forEach(function(t) { var n = A(t.getAttribute("data-width"), t.getAttribute("data-height"), u.effectiveWidth(t.parentElement) || e, r); i(function() { t.setAttribute("width", n.width), t.setAttribute("height", n.height), l.present(t, "wvp-player-container") ? (t.style.width = n.width, t.style.height = n.height) : (t.width = n.width, t.height = n.height) }) }) } function A(t, e, r, i, n, o) { return r = r || t, i = i || e, n = n || 0, o = o || 0, t > r && (e *= r / t, t = r), e > i && (t *= i / e, e = i), t < n && (e *= n / t, t = n), e < o && (t *= o / e, e = o), { width: Math.floor(t), height: Math.floor(e) } } function k(t, e, r, i) { n.toRealArray(t.querySelectorAll(e)).forEach(function(t) { var e = t.getAttribute("style") || t.getAttribute("data-style"), n = i.test(e) && RegExp.$1; n && (t.setAttribute("data-csp-fix", !0), t.style[r] = n) }) } t.exports = { scaleDimensions: A, retinize: function(t, e) { e = void 0 !== e ? !!e : c.retina(), n.toRealArray(t.getElementsByTagName("IMG")).forEach(function(t) { var r = t.getAttribute("data-src-1x") || t.getAttribute("src"), i = t.getAttribute("data-src-2x"); e && i ? t.src = i : r && (t.src = r) }) }, setSrcForImgs: C, sizeIframes: _, constrainMedia: function(t, e, r, i) { C(t, e, i), _(t, e, r, i) }, fixMediaCardLayout: function(t) { o.inlineStyle() || (k(t, ".MediaCard-widthConstraint", "maxWidth", f), k(t, ".MediaCard-mediaContainer", "paddingBottom", m), k(t, ".CroppedImage-image", "top", h), k(t, ".CroppedImage-image", "left", p)) }, __setSrcFromSet: E, __setSrcFromImage: x, __setImageSrc: w } }, 192: function(t, e, r) { var i = r(46), n = (r(12), r(0)), o = /^([a-zA-Z-]+):\s*(.+)$/; function s(t) { var e = (t.getAttribute("data-style") || "").split(";").reduce(function(t, e) { var r, i, n; return o.test(e.trim()) && (r = RegExp.$1, i = RegExp.$2, t[(n = r, n.replace(/-(.)/g, function(t, e) { return e.toUpperCase() }))] = i), t }, {}); 0 !== Object.keys(e).length && (t.setAttribute("data-csp-fix", "true"), n.forIn(e, function(e, r) { t.style[e] = r })) } t.exports = function(t) { t.selectors({ cspForcedStyle: ".js-cspForcedStyle" }), t.after("prepForInsertion", function(t) { i.inlineStyle() || this.select(t, "cspForcedStyle").forEach(s) }) } }, 193: function(t, e, r) { var i = r(191); t.exports = function(t) { t.after("prepForInsertion", function(t) { i.retinize(t) }) } }, 194: function(t, e, r) { var i = r(18), n = r(191); t.exports = function(t) { t.after("prepForInsertion", function(t) { n.setSrcForImgs(t, this.sandbox.width, i.sync) }), t.after("resize", function() { n.setSrcForImgs(this.el, this.sandbox.width, i.write) }) } }, 195: function(t, e) { var r = "data-iframe-title"; t.exports = function(t) { t.after("render", function() { var t = this.el.getAttribute(r); t && this.sandbox.setTitle && this.sandbox.setTitle(t) }) } }, 196: function(t, e, r) { var i = r(6), n = r(5), o = "env-bp-", s = o + "min"; function a(t) { return t.every(n.isInt) } function c(t) { var e = t.map(function(t) { return { size: +t, className: o + t } }).sort(function(t, e) { return t.size - e.size }); return e.unshift({ size: 0, className: s }), e } t.exports = function(t) { t.params({ breakpoints: { required: !0, validate: a, transform: c } }), t.define("getClassForWidth", function(t) { var e, r, i; for (r = this.params.breakpoints.length - 1; r >= 0; r--) if (t > (i = this.params.breakpoints[r]).size) { e = i.className; break } return e }), t.after("initialize", function() { this.allBreakpoints = this.params.breakpoints.map(function(t) { return t.className }) }), t.define("recalculateBreakpoints", function() { var t = this.getClassForWidth(this.sandbox.width); return t && this.sandbox.hasRootClass(t) ? i.resolve() : i.all([this.sandbox.removeRootClass(this.allBreakpoints), this.sandbox.addRootClass(t)]) }), t.after("render", function() { return this.recalculateBreakpoints() }), t.after("resize", function() { return this.recalculateBreakpoints() }) } }, 197: function(t, e, r) { var i = r(2), n = r(81), o = r(227), s = null; function a(t, e) { var r, i; if (i = { scribeContext: (e = e || {}).scribeContext || { client: "tfw" }, languageCode: e.languageCode, hideControls: e.hideControls || !1, addTwitterBranding: e.addBranding || !1, widgetOrigin: e.widgetOrigin, borderRadius: e.borderRadius, autoPlay: e.autoPlay }, (r = n(t, ".wvp-player-container")).length > 0) return s && o.setBaseUrl(s), { element: r[0], options: i } } t.exports = { insertForTweet: function(t, e, r) { var n, s = new i, c = a(t, r); if (c) return (n = o.createPlayerForTweet(c.element, e, c.options)) ? (s.resolve(n), s.promise) : s.reject(new Error("unable to create tweet video player")) }, insertForEvent: function(t, e, r) { var n, s = new i, c = a(t, r); return c ? ((n = o.createPlayerForLiveVideo(c.element, e, c.options)).on("ready", function() { n.playPreview(), s.resolve(n) }), s.promise) : s.reject(new Error("unable to initialize event video player")) }, remove: function(t) { var e = t.querySelector(".wvp-player-container"), r = e && o.findPlayerForElement(e); if (r) return r.teardown() }, find: function(t) { return o.findPlayerForElement(t) } } }, 198: function(t, e, r) { var i = r(33), n = r(228), o = r(170), s = r(30), a = r(35), c = r(0), u = r(6), l = "data-click-to-open-target"; t.exports = o.couple(r(171), function(t) { t.selectors({ clickToOpen: ".js-clickToOpenTarget" }), t.define("shouldOpenTarget", function(t) { var e = i.closest("A", t.target, this.el), r = i.closest("BUTTON", t.target, this.el), n = this.sandbox.hasSelectedText(); return !e && !r && !n }), t.define("openTarget", function(t, e) { var r = e && e.getAttribute(l), i = { twcamp: this.params.productName, twterm: this.params.id, twcon: e.getAttribute("data-twcon") }; return r ? s.getActiveExperimentDataString().then(function(e) { i.twgr = e, n(r, i), this.scribeOpenClick(t) }.bind(this)).catch(function() { n(r, i), this.scribeOpenClick(t) }.bind(this)) : u.resolve() }), t.define("attemptToOpenTarget", function(t, e) { return this.shouldOpenTarget(t) ? this.openTarget(t, e) : u.resolve() }), t.define("scribeOpenClick", function(t) { var e = a.extractTermsFromDOM(t.target), r = { associations: a.formatTweetAssociation(e) }, i = c.aug({}, { element: "chrome", action: "click" }, e); this.scribe(i, r) }), t.after("render", function() { this.on("click", "clickToOpen", this.attemptToOpenTarget) }) }) }, 199: function(t, e, r) { var i = r(33), n = r(34), o = r(73), s = r(39), a = r(11), c = r(3), u = r(7), l = "data-url-params-injected"; t.exports = function(t) { t.params({ productName: { required: !0 }, dataSource: { required: !1 }, related: { required: !1 }, partner: { fallback: u(n.val, n, "partner") } }), t.selectors({ timeline: ".timeline", tweetIdInfo: ".js-tweetIdInfo" }), t.define("injectWebIntentParams", function(t) { var e = i.closest(this.selectors.timeline, t, this.el), r = i.closest(this.selectors.tweetIdInfo, t, this.el); t.getAttribute(l) || (t.setAttribute(l, !0), t.href = a.url(t.href, { tw_w: this.params.dataSource && this.params.dataSource.id, tw_i: r && r.getAttribute("data-tweet-id"), tw_p: this.params.productName, related: this.params.related, partner: this.params.partner, query: e && e.getAttribute("data-search-query"), profile_id: e && e.getAttribute("data-profile-id"), original_referer: s.rootDocumentLocation() })) }), t.after("render", function() { this.on("click", "A", function(t, e) { c.isIntentURL(e.href) && (this.injectWebIntentParams(e), o.open(e.href, this.sandbox.sandboxEl, t)) }) }) } }, 200: function(t, e, r) { var i = r(21); t.exports = function(t) { t.before("render", function() { i.ios() && this.sandbox.addRootClass("env-ios"), i.ie9() && this.sandbox.addRootClass("ie9"), i.touch() && this.sandbox.addRootClass("is-touch") }) } }, 201: function(t, e, r) { var i = r(229); t.exports = function(t) { t.params({ pageForAudienceImpression: { required: !0 } }), t.before("hydrate", function() { i.scribeAudienceImpression(this.params.pageForAudienceImpression) }) } }, 202: function(t, e, r) { var i = r(4), n = r(1); t.exports = function(t, e) { var r, o, s, a; return o = (e = e || {}).viewportWidth || n.innerWidth, r = e.viewportHeight || n.innerHeight, s = t.getBoundingClientRect(), t.ownerDocument !== i && e.sandboxEl && (a = e.sandboxEl.getBoundingClientRect(), s = { top: s.top + a.top, bottom: s.bottom + a.top, left: s.left + a.left, right: s.right + a.left }), s.top >= 0 && s.left >= 0 && s.bottom <= r && s.right <= o } }, 203: function(t, e, r) { var i = r(1), n = { _addListener: function(t, e) { var r = function() { e() }; return i.addEventListener(t, r), function() { i.removeEventListener(t, r) } }, addScrollListener: function(t) { return this._addListener("scroll", t) }, getHeight: function() { return i.innerHeight }, getWidth: function() { return i.innerWidth } }; t.exports = n }, 204: function(t, e, r) { var i = r(170), n = r(230), o = 1; t.exports = i.couple(r(171), function(t) { var e = { action: "dimensions" }, r = new n(o); t.after("show", function() { var t; r.nextBoolean() && (t = { widget_width: this.sandbox.width, widget_height: this.sandbox.height }, this.scribe(e, t)) }) }) }, 225: function(t, e) { t.exports = { effectiveWidth: function t(e) { return e && 1 === e.nodeType ? e.offsetWidth || t(e.parentNode) : 0 } } }, 227: function(t, e, r) { var i, n; n = this, void 0 === (i = function() { return n.TwitterVideoPlayer = function() { var t = "https://twitter.com", e = /^https?:\/\/([a-zA-Z0-9]+\.)*twitter.com(:\d+)?$/, r = { suppressScribing: !1, squareCorners: !1, hideControls: !1, addTwitterBranding: !1 }, i = 0, n = {}; function o(t) { if (t && t.data && t.data.params && t.data.params[0]) { var e = t.data.params[0], r = t.data.id; if (e && e.context && "TwitterVideoPlayer" === e.context) { var i = e.playerId; delete e.playerId, delete e.context; var o = n[i]; o && o.processMessage(t.data.method, e, r) } } } function s(e, r, s, a, c) { var u = e.ownerDocument, l = u.defaultView; l.addEventListener("message", o), this.playerId = i++; var d = { embed_source: "clientlib", player_id: this.playerId, rpc_init: 1, autoplay: a.autoPlay }; if (this.scribeParams = {}, this.scribeParams.suppressScribing = a && a.suppressScribing, !this.scribeParams.suppressScribing) { if (!a.scribeContext) throw "video_player: Missing scribe context"; if (!a.scribeContext.client) throw "video_player: Scribe context missing client property"; this.scribeParams.client = a.scribeContext.client, this.scribeParams.page = a.scribeContext.page, this.scribeParams.section = a.scribeContext.section, this.scribeParams.component = a.scribeContext.component } this.scribeParams.debugScribe = a && a.scribeContext && a.scribeContext.debugScribing, this.scribeParams.scribeUrl = a && a.scribeContext && a.scribeContext.scribeUrl, this.promotedLogParams = a.promotedContext, this.adRequestCallback = a.adRequestCallback, a.languageCode && (d.language_code = a.languageCode), "tfw" === this.scribeParams.client && (d.use_syndication_guest_id = !0), a.autoPlay && (d.autoplay = 1); var f = function(t, e, r) { var i = Object.keys(r).filter(function(t) { return null != r[t] }).map(function(t) { var e = r[t]; return encodeURIComponent(t) + "=" + encodeURIComponent(e) }).join("&"); return i && (i = "?" + i), t + e + i }(t, r, d); return this.videoIframe = document.createElement("iframe"), this.videoIframe.setAttribute("src", f), this.videoIframe.setAttribute("allowfullscreen", ""), this.videoIframe.setAttribute("allow", "autoplay; fullscreen"), this.videoIframe.setAttribute("id", s), this.videoIframe.setAttribute("style", "width: 100%; height: 100%; position: absolute; top: 0; left: 0;"), this.domElement = e, this.domElement.appendChild(this.videoIframe), n[this.playerId] = this, this.eventCallbacks = {}, this.emitEvent = function(t, e) { var r = this.eventCallbacks[t]; void 0 !== r && r.forEach(function(t) { t.apply(this.playerInterface, [e]) }.bind(this)) }, this.jsonRpc = function(t) { var e = this.videoIframe.contentWindow; t.jsonrpc = "2.0", e && e.postMessage && e.postMessage(JSON.stringify(t), "*") }, this.jsonRpcCall = function(t, e) { this.jsonRpc({ method: t, params: e }) }, this.jsonRpcResult = function(t, e) { this.jsonRpc({ result: t, id: e }) }, this.processMessage = function(t, e, r) { switch (t) { case "requestPlayerConfig": this.jsonRpcResult({ scribeParams: this.scribeParams, promotedLogParams: this.promotedLogParams, squareCorners: a.squareCorners, borderRadius: a.borderRadius, hideControls: a.hideControls, embedded: a.addTwitterBranding, widgetOrigin: a.widgetOrigin, ignoreFineGrainGeoblocking: a.ignoreFineGrainGeoblocking }, r); break; case "videoPlayerAdStart": this.emitEvent("adStart", e); break; case "videoPlayerAdEnd": this.emitEvent("adEnd", e); break; case "videoPlayerPlay": this.emitEvent("play", e); break; case "videoPlayerPause": this.emitEvent("pause", e); break; case "videoPlayerMute": this.emitEvent("mute", e); break; case "videoPlayerUnmute": this.emitEvent("unmute", e); break; case "videoPlayerPlaybackComplete": this.emitEvent("playbackComplete", e); break; case "videoPlayerReady": this.emitEvent("ready", e); break; case "videoView": this.emitEvent("view", e); break; case "debugLoggingEvent": this.emitEvent("logged", e); break; case "requestDynamicAd": "function" == typeof this.adRequestCallback ? this.jsonRpcResult(this.adRequestCallback(), r) : this.jsonRpcResult({}, r); break; case "videoPlayerError": e && "NO_COOKIES_ERROR" === e.error_category ? this.emitEvent("noCookiesError", e) : e && "GEOBLOCK_ERROR" === e.error_category && this.emitEvent("geoblockError", e) } }, this.playerInterface = { on: function(t, e) { return void 0 === this.eventCallbacks[t] && (this.eventCallbacks[t] = []), this.eventCallbacks[t].push(e), this.playerInterface }.bind(this), off: function(t, e) { if (void 0 === e) delete this.eventCallbacks[t]; else { var r = this.eventCallbacks[t]; if (void 0 !== r) { var i = r.indexOf(e); i > -1 && r.splice(i, 1) } } return this.playerInterface }.bind(this), play: function() { return this.jsonRpcCall("play"), this.playerInterface }.bind(this), pause: function() { return this.jsonRpcCall("pause"), this.playerInterface }.bind(this), mute: function() { return this.jsonRpcCall("mute"), this.playerInterface }.bind(this), unmute: function() { return this.jsonRpcCall("unmute"), this.playerInterface }.bind(this), playPreview: function() { return this.jsonRpcCall("autoPlayPreview"), this.playerInterface }.bind(this), pausePreview: function() { return this.jsonRpcCall("autoPlayPreviewStop"), this.playerInterface }.bind(this), updatePosition: function(t) { return this.jsonRpcCall("updatePosition", [t]), this.playerInterface }.bind(this), updateLayoutBreakpoint: function(t) { return this.jsonRpcCall("updateLayoutBreakpoint", [t]), this.playerInterface }.bind(this), enterFullScreen: function() { return this.jsonRpcCall("enterFullScreen"), this.playerInterface }.bind(this), exitFullScreen: function() { return this.jsonRpcCall("exitFullScreen"), this.playerInterface }.bind(this), teardown: function() { this.eventCallbacks = {}, e.removeChild(this.videoIframe), this.videoIframe = void 0, delete n[this.playerId] }.bind(this) }, this.playerInterface } return { setBaseUrl: function(r) { e.test(r) ? t = r : window.console.error("newBaseUrl " + r + " not allowed") }, createPlayerForTweet: function(t, e, i) { var n = "/i/videos/tweet/" + e, o = "player_tweet_" + e; return new s(t, n, o, i || r) }, createPlayerForDm: function(t, e, i) { var n = "/i/videos/dm/" + e, o = "player_dm_" + e; return new s(t, n, o, i || r) }, createPlayerForLiveVideo: function(t, e, i) { var n = "/i/videos/live_video/" + e, o = "player_live_video_" + e; return new s(t, n, o, i || r) }, findPlayerForElement: function(t) { for (var e in n) if (n.hasOwnProperty(e)) { var r = n[e]; if (r && r.domElement === t) return r.playerInterface } return null } } }() }.call(e, r, e, t)) || (t.exports = i) }, 228: function(t, e, r) { var i = r(1), n = r(187), o = r(3); t.exports = function(t, e) { o.isTwitterURL(t) && (t = n(t, e)), i.open(t) } }, 229: function(t, e, r) { var i = r(80), n = r(35), o = r(79), s = {}; function a(t) { o.isHostPageSensitive() || s[t] || (s[t] = !0, i.scribe(n.formatClientEventNamespace({ page: t, action: "impression" }), n.formatGenericEventData("syndicated_impression", {}), n.AUDIENCE_ENDPOINT)) } t.exports = { scribeAudienceImpression: a, scribePartnerTweetAudienceImpression: function() { a("partnertweet") }, scribeTweetAudienceImpression: function() { a("tweet") }, scribeTimelineAudienceImpression: function() { a("timeline") }, scribeVideoAudienceImpression: function() { a("video") } } }, 230: function(t, e) { function r(t) { this.percentage = t } r.prototype.nextBoolean = function() { return 100 * Math.random() < this.percentage }, t.exports = r } } ]);<file_sep>/www.cater4you.co.uk/acatalog/actiniccore.js /*************************************************************** * * ActinicCore.js - core utility functions * * Copyright (c) 2014 SellerDeck Limited * ****************************************************************/ var bPageIsLoaded = false; /*********************************************************************** * * setCookie - Generic Set Cookie routine * * Input: sName - Name of cookie to create * sValue - Value to assign to the cookie * sExpire - Cookie expiry date/time (optional) * * Returns: null * ************************************************************************/ function setCookie(sName, sValue, sExpire) { var sCookie = sName + "=" + escape(sValue) + "; path=/"; // construct the cookie if (sExpire) { sCookie += "; expires=" + sExpire.toGMTString(); // add expiry date if present } document.cookie = sCookie; // store the cookie return null; } /*********************************************************************** * * getCookie - Generic Get Cookie routine * * Input: sName - Name of cookie to retrieve * * Returns: Requested cookie or null if not found * ************************************************************************/ function getCookie(sName) { var sCookiecrumbs = document.cookie.split("; "); // break cookie into crumbs array var sNextcrumb for (var i = 0; i < sCookiecrumbs.length; i++) { sNextcrumb = sCookiecrumbs[i].split("="); // break into name and value if (sNextcrumb[0] == sName) // if name matches { return unescape(sNextcrumb[1]); // return value } } return null; } /*********************************************************************** * * saveReferrer - Saves the referrer to a Cookie * * Input: nothing * * Returns: null * ************************************************************************/ function saveReferrer() { if (window.name == 'ActPopup') return; // don't save if on popup page var bSetCookie = false; if (parent.frames.length == 0) // No FrameSet { bSetCookie = true; } else // FrameSet in use { var bCatalogFrameSet = false; for (var nFrameId = parent.frames.length; nFrameId > 0; nFrameId--) { if (parent.frames[nFrameId - 1].name == 'CatalogBody') // Catalog FrameSet used { bCatalogFrameSet = true; break; } } if (bCatalogFrameSet) // Catalog FrameSet { if (window.name == 'CatalogBody') // and this is the CatalogBody frame { bSetCookie = true; } } else // Not Catalog FrameSet { bSetCookie = true; } } if (bSetCookie) { var sUrl = document.URL; var nHashPos = sUrl.lastIndexOf("#"); // Look for URL anchor var nSIDHashPos = sUrl.lastIndexOf("#SID="); // Look for URL with SID anchor if (nHashPos > 0 && nSIDHashPos == -1) // if it exists { sUrl = sUrl.substring(0, nHashPos); // then remove it } setCookie("ACTINIC_REFERRER", sUrl); // Emulates HTTP_REFERER } return null; } /*********************************************************************** * * CreateArray creates an array with n elements * * Input: n - number of elements * * Returns: the created array * ************************************************************************/ function CreateArray(n) { this.length = n; for (var i = 1; i <= n; i++) // for all ns { this[i] = new Section(); // create a section structure } return this; // return the created array } /*********************************************************************** * * Section - creates the section structure for raw section lists * * Input: nothing * * Returns: nothing ************************************************************************/ function Section() { this.sURL = null; this.sName = null; this.sImage = null; this.nImageWidth = null; this.nImageHeight = null; this.nSectionId = null; this.pChild = null; } /*********************************************************************** * * SwapImage - swaps an image to the alternative * * Input: sName - name of the image * * sAltImage - filename of the alternative image * ************************************************************************/ function SwapImage(sName, sAltImage) { var nCount = 0; document.aSource = new Array; // array for images if (document[sName] != null) // if image name exists { document.aSource[nCount++] = document[sName]; // store image if (null == document[sName].sOldSrc) { document[sName].sOldSrc = document[sName].src; // store image source } document[sName].src = sAltImage; // change image source to alternative } } /*********************************************************************** * * RestoreImage - restores an image to the original * * Input: nothing * * Returns: nothing ************************************************************************/ function RestoreImage() { var nCount, aSource = document.aSource; if (aSource != null) // if array of images exists { for (nCount = 0; nCount < aSource.length; nCount++) // restore all images { if ((aSource[nCount] != null) && (aSource[nCount].sOldSrc != null)) // if we stored something for this image { aSource[nCount].src = aSource[nCount].sOldSrc; // restore the original image } } } } /*********************************************************************** * * PreloadImages - restores an image to the original * * Input: nothing * * Returns: nothing * ************************************************************************/ function PreloadImages() { bPageIsLoaded = true; if (document.images) { if (!document.Preloaded) // preload array defined? { document.Preloaded = new Array(); // no, define it } var nCounter, nLen = document.Preloaded.length, saArguments = PreloadImages.arguments; for (nCounter = 0; nCounter < saArguments.length; nCounter++) // iterate through arguments { document.Preloaded[nLen] = new Image; document.Preloaded[nLen++].src = saArguments[nCounter]; } } } /*********************************************************************** * * ShowPopUp - creates pop up window * * Input: sUrl - URL of page to display * nWidth - Width of window * nHeight - Height of window * * Returns: nothing * ************************************************************************/ function ShowPopUp(sUrl, nWidth, nHeight) { if (sUrl.indexOf("http") != 0 && sUrl.indexOf("/") != 0) { var sBaseHref = GetDocumentBaseHref(); sUrl = sBaseHref + sUrl; } window.open(sUrl, 'ActPopup', 'width=' + nWidth + ',height=' + nHeight + ',scrollbars, resizable'); if (!bPageIsLoaded) { window.location.reload(true); } return false; } /*********************************************************************** * * GetDocumentBaseHref - Returns the href for the <base> element if it is defined * * Returns: base href if defined or empty string * ************************************************************************/ function GetDocumentBaseHref() { var collBase = document.getElementsByTagName("base"); if (collBase && collBase[0]) { var elemBase = collBase[0]; if (elemBase.href) { return elemBase.href; } } return ''; } /*********************************************************************** * * DecodeMail - decodes the obfuscated mail address in 'contactus' link * * Input: nothing * * Returns: nothing * ************************************************************************/ function DecodeMail() { var nIdx = 0; for (; nIdx < document.links.length; nIdx++) if (document.links[nIdx].name == "contactus") { var sOldRef = document.links[nIdx].href; while (sOldRef.indexOf(" [dot] ") != -1) sOldRef = sOldRef.replace(" [dot] ", "."); while (sOldRef.indexOf(" [at] ") != -1) sOldRef = sOldRef.replace(" [at] ", "@"); document.links[nIdx].href = sOldRef; } } /*********************************************************************** * * HtmlInclude - Parses the page for <a href> tags and if any found * with rel="fragment" attribute then create an XMLHTTP * request to download the referenced file and insert the * file content in place of the referring tag. * In case of error just leave it as is. * * NOTE: this function is automatically attached to the onload event handler * therefore this processing is done on all pages where this js file is included. * * Returns: nothing * * Author: <NAME> * ************************************************************************/ function HtmlInclude() { var req; // // Check browser type // if (typeof(XMLHttpRequest) == "undefined") // IE { try { req = new ActiveXObject("Msxml2.XMLHTTP"); } catch (e) { try { req = new ActiveXObject("Microsoft.XMLHTTP"); } catch (e) // no luck? { return; // nothing to do then } } } else // Mozzila { req = new XMLHttpRequest(); } // // Get <a href> tags and iterate on them // var tags = document.getElementsByTagName("A"); var i; for (i = 0; i < tags.length; i++) { // // Check if we got "fragment" as rel attribute // if (tags[i].getAttribute("rel") == "fragment") { try { // // Try to pull the referenced file from the server // req.open('GET', tags[i].getAttribute("href"), false); if (document.characterSet) { req.overrideMimeType("text/html; charset=" + document.characterSet); } req.send(null); if (req.status == 200) // got the content? { // // Replace the reference with the pulled in content // var span = document.createElement("SPAN"); span.innerHTML = req.responseText; tags[i].parentNode.replaceChild(span, tags[i]); } } catch (e) // couldn't pull it from the server (maybe preview) { return; // don't do anything then } } } } /*********************************************************************** * * AddEvent - Add event * Inputs: obj - object to add the event handler * type - type of the event * fn - event handler name * * Returns: - nothing * ************************************************************************/ function AddEvent(obj, type, fn) { if (obj.attachEvent) { obj['e' + type + fn] = fn; obj[type + fn] = function() { obj['e' + type + fn](window.event); } obj.attachEvent('on' + type, obj[type + fn]); } else { obj.addEventListener(type, fn, false); }; }; // // The following lines will automatically parse all the pages // where this script is included by attaching the HtmlInclude // function to the onload event. // AddEvent(window, "load", HtmlInclude); /*************************************************************** * * SDStorage - local storage or session storage methods * * Author: <NAME> * ****************************************************************/ window.SDStorage = { /*********************************************************************** * * SDStorage.isSupported - check if storage is supported in client browser * * Return: * true/false * ************************************************************************/ isSupported: function() { try { var uid = new Date().valueOf(); window.SDStorage.write(uid, uid, true); var storeuid = window.SDStorage.read(uid, true); window.SDStorage.remove(uid, true); return (uid == storeuid); } catch (e) { return false; } }, /*********************************************************************** * * SDStorage.writePage - writing a key-value pair to the store associated to the page * * Input: * key - key of the value to be associated and stored for the current page * value - value to be associated to the page * ************************************************************************/ writePage: function(key, value) { try { window.SDStorage.write(key + '|' + window.location.href, value, true); } catch (e) { // do nothing } }, /*********************************************************************** * * SDStorage.readPage - reading values by key from the store associated to the page * * Input: * key - key of the value to be associated and stored for the current page * * Return: * any type of data * ************************************************************************/ readPage: function(key) { return window.SDStorage.read(key + '|' + window.location.href, true); }, /*********************************************************************** * * SDStorage.writeGlobal - writing a key-value pair to the store that is independent of the current page * * Input: * key - key of the value to be associated and stored for the current page * value - value to be associated to the page * ************************************************************************/ writeGlobal: function(key, value) { window.SDStorage.write(key + '|global', value, true); }, /*********************************************************************** * * SDStorage.readGlobal - reading values by key from the store that is independent of the current page * * Input: * key - key of the value to be associated and stored for the current page * * Return: * any type of data * ************************************************************************/ readGlobal: function(key) { return window.SDStorage.read(key + '|global', true); }, /*********************************************************************** * * SDStorage.write - writing a key-value pair to the store * * Input: * key - key of the value to be stored on the client side * value - value to be stored * session - determines if we use session storage or not * ************************************************************************/ write: function(key, value, session) { if (typeof(value) === 'object') { value = JSON.stringify(value) } if (session) { sessionStorage.setItem(key, value); } else { localStorage.setItem(key, value); } }, /*********************************************************************** * * SDStorage.read - reading a key-value pair from the store * * Input: * key - key of the value to get from the store * session - determines if we use session storage or not * * Return: * any type of data * ************************************************************************/ read: function(key, session) { if (session) { var value = sessionStorage.getItem(key); } else { var value = localStorage.getItem(key); } try { var json = JSON.parse(value); } catch (e) { return value; } return json; }, /*********************************************************************** * * SDStorage.remove - removing a key and associate value from the store * * Input: * key - key of the value to be removed on the client side * session - determines if we use session storage or not * ************************************************************************/ remove: function(key, session) { if (session) { sessionStorage.removeItem(key); } else { localStorage.removeItem(key); } } };<file_sep>/www.cater4you.co.uk/acatalog/dynamic.js /*************************************************************** * * dynamic.js - utility functions for dynamic prices and choices * * Copyright (c) 2014 SellerDeck Limited * ****************************************************************/ var g_mapProds = {}; var timeout = null; var g_nTimeout = 1000; // 1 sec var g_sDynamicPriceURL = ''; /*********************************************************************** * * OnProdLoad - onload handler for this page * ************************************************************************/ function OnProdLoad(sURL, sSID, sShopID) { // // Need to handle a single add to cart button // if (sURL) // if we are using dynamic prices { g_sDynamicPriceURL = sURL; getAllDynamicPrices(sURL, sSID, sShopID); // get all dynamic prices for this page init } else // handle dynamic choices if applicable { g_sDynamicPriceURL = ''; if (g_bStockUpdateInProgress) { // // do not update choices when products stock update is in progress // note: currently selected options may be changed during stock update process // g_bChoicesUpdatePending = true; return; } // // Store variant settings // SetupVariants(false); // // Update dynamic choices to remove invalid generated choices // and to handle sequential dynamic choices if applicable // for (var sProdRef in g_mapProds) { var oProd = g_mapProds[sProdRef]; UpdateChoices(oProd, true, undefined); } } } /*********************************************************************** * * GetAttrFromSuffix - Get the attribute from the UI number * * Input: oProd - product object * nUI - UI number * * Returns: Object - attribute object or undefined * ************************************************************************/ function GetAttrFromSuffix(oProd, nUI) { if (!oProd.mapAttr) // if this is first time { oProd.mapAttr = {}; for (var i = 0; i < oProd.arrComps.length; i++) // for each component { var oComp = oProd.arrComps[i]; if (oComp.aA) // if it has attributes { for (var n = 0; n < oComp.aA.length; n++) { oProd.mapAttr[oComp.aA[n].nUI] = oComp.aA[n]; // map attribute to UI number } } } } return oProd.mapAttr[nUI]; // return attribute } /*********************************************************************** * * UpdateChoices - Update the choices for this product * * Input: oProd - product object * bLoading - whether this is the initial call * ************************************************************************/ function UpdateChoices(oProd, bLoading, elemChanged) { if (!oProd || oProd.bFixChoices || oProd.bNoATC || !oProd.arrComps) // skip if product isn't mapped, or it's not dynamic or no valid choices { return; } // // IE restores user choices on a refresh but appears to use the index of // the choice rather than the value which might not be the same. We save // the choices to a textarea (which IE restores) to get the correct choice // values // var arrProdChoices = GetProdChoices(oProd, elemChanged, bLoading); // get user input var oChangedIndices = GetChangedElemIndices(oProd, elemChanged); var nStartCompIndex = oChangedIndices ? oChangedIndices.nCompIndex : 0; var arrComps = oProd.arrComps; var nCompCount = arrComps.length; for (var i = nStartCompIndex; i < nCompCount; i++) // for each component from changed component { var arrCompChoices = arrProdChoices[i]; var oComp = arrComps[i]; if (!oComp.aA) // skip components with no attributes { continue; } if (bLoading) // if this is first time { MapInvalidPermutations(oComp); // filter out price permutations } if (oComp.mP || // if we have permutations oProd.bSequentialChoices) // or we are using sequential choices { // // To simplify processing of permutations when sequential choices // aren't used, we transform the permuation map so that the choices // are specified in the order the user selected them // if (!oComp.arrUserSeq) { oComp.arrUserSeq = []; } if (!oProd.bSequentialChoices && oChangedIndices && i == oChangedIndices.nCompIndex) { UpdateUserSequence(oComp, oChangedIndices.nAttrIndex, arrProdChoices[i]); } NormaliseAttrSeq(oComp); // // Update the user's choice array so that the choices are in the order // the user selected them // var arrCompChoices = NormaliseUserChoices(oComp, arrProdChoices[i]); // // Update the permutation map so that the choices are in the order // the user selected them // NormalisePerms(oComp); // // If we are using sequential choices and know which attribute choice changed // we only update from the changed choice // var nStartAttrIndex = 0; if (oProd.bSequentialChoices && // if we are using sequential choices i == nStartCompIndex && oChangedIndices) // and we know which element changed { nStartAttrIndex = oChangedIndices.nAttrIndex; // only update choices from the changed attribute } // // Now update the choices // UpdateCompChoices(oProd, oComp, arrCompChoices, nStartAttrIndex); // update choices for this component } } // // Updating choices loses the disabled status of options due to out-of-stock products // so re-apply the stock levels. // false indicates that selections aren't to be changed. As out of stock options will have // been disabled they will not be selectable here anyway. // updateStockDisplay(g_mapStockByRef, false); // // Enforce sequential choices if merchant wants it // if (oProd.bSequentialChoices) { UpdateSequentialDisplay(oProd, arrProdChoices); } } /*********************************************************************** * * UpdateSequentialDisplay - Update the sequential display of choices * * Input: oProd - product object * arrProdChoices - array of arrays containing choices * ************************************************************************/ function UpdateSequentialDisplay(oProd, arrProdChoices) { var bSequentialDisable = false; for (var i = 0; i < oProd.arrComps.length; i++) { var oComp = oProd.arrComps[i]; bSequentialDisable = UpdateSequentialCompDisplay(oProd, oComp, arrProdChoices[i], 0, bSequentialDisable); } } /*********************************************************************** * * UpdateSequentialCompDisplay - Update the sequential display of component choices * * Input: oProd - product object * oComp - component object * arrChoices - array of choices for the component * nStartIndex - index into array of choices to start from * bSequentialDisable - whether containing element should be disabled * * Returns: boolean - true if subsequent choices should be disabled * ************************************************************************/ function UpdateSequentialCompDisplay(oProd, oComp, arrCompChoices, nStartIndex, bSequentialDisable) { var elemComp = oComp.elemHTML; // get component element (hidden or checkbox) var bRequired = true; // default to required component if (elemComp.type == 'checkbox') // if this is a checkbox { elemComp.disabled = bSequentialDisable; // apply the disabled flag if (!bSequentialDisable) // if we aren't disabling the component { bRequired = elemComp.checked; // save whether it is included } } if (!oComp.aA) // if we have no attributes { return bSequentialDisable; // nothing more to do } // // Now update the attribute elements // var nCompAttrCount = oComp.aA.length; for (var i = nStartIndex; i < nCompAttrCount; i++) { var oAttr = oComp.aA[i]; var oAttrSelect = oAttr.elem; var elemSelect = oAttrSelect.elemHTML; // get the attribute HTML element if (bSequentialDisable || // if previous choices need to be made or !bRequired) // this component isn't required { EnableSelectElement(elemSelect, false); // disable UI if (elemSelect.tagName == 'SELECT') { elemSelect.selectedIndex = 0; // revert to 'Please select' } } else { // // Now if there is only one valid choice, select it // var oResult = GetValidChoiceCount(elemSelect); if ((!oComp.bOpt || (nCompAttrCount > 1)) && (oResult.nCount == 1)) { var nSelValue = GetAttributeValue(elemSelect); // save existing selection if (elemSelect.tagName == 'SELECT') // select the UI selection element { oResult.elemFirstValid.selected = true; } else { oResult.elemFirstValid.checked = true; } var sNewValue = GetAttributeValue(elemSelect); // get new value if (nSelValue != sNewValue) // if it changed { arrCompChoices[i] = sNewValue ? parseInt(sNewValue) : 0; UpdateCompChoices(oProd, oComp, arrCompChoices, i + 1); // update subsequent choices } } // // If we have a 'Please select' choice, disable subsequent choices // var nSelValue = GetAttributeValue(elemSelect); EnableSelectElement(elemSelect, true); if (nSelValue == '') // and it isn't 'None' { bSequentialDisable = true; // disable rest of elements } } } return bSequentialDisable; // tell caller if it should disable rest of choices } /*********************************************************************** * * GetValidChoiceCount - Get the number of valid choices and the first valid option available to the user * * Input: elemSelect - the select element * * Returns: Object - nCount property contains valid count, elemFirstValid contains the first valid element * ************************************************************************/ function GetValidChoiceCount(elemSelect) { var nCount = 0; var elemFirstOption = null; if (elemSelect.tagName == 'SELECT') { for (var i = 0; i < elemSelect.options.length; i++) { var oOption = elemSelect.options[i]; var nValue = parseInt(oOption.value ? oOption.value : '0'); if (nValue > 0 && !oOption.disabled) { nCount++; if (nCount == 1) { elemFirstOption = oOption; } } } } else { var collSel = document.getElementsByName(elemSelect.name); for (var i = 0; i < collSel.length; i++) { var elemRadio = collSel[i]; var nValue = parseInt(elemRadio.value ? elemRadio.value : '0'); if (nValue > 0) { nCount++; if (nCount == 1) { elemFirstOption = elemRadio; } } } } return { nCount: nCount, elemFirstValid: elemFirstOption }; } /*********************************************************************** * * EnableSelectElement - Enable or disable user selection element(s) * * Input: elemSelect - selection element * bEnable - false to disable * ************************************************************************/ function EnableSelectElement(elemSelect, bEnable) { if (elemSelect.tagName == 'SELECT') { elemSelect.disabled = !bEnable; } else { var collSel = document.getElementsByName(elemSelect.name); for (var i = 0; i < collSel.length; i++) { var elemRadio = collSel[i]; elemRadio.disabled = !bEnable; } } } /*********************************************************************** * * GetProdChoices - Get current choices for this product * * Input: oProd - product object * elemChanged - element that has changed * bLoading - true if we are loading the page * * Returns: Array - array of arrays of choices * ************************************************************************/ function GetProdChoices(oProd, elemChanged, bLoading) { if (!oProd.arrComps) // ignore products with no components mapped { return []; } var bSequentialDisable = false; // flag for clearing subsequent flags var arrProdChoices = new Array(oProd.arrComps.length); // create an array for each component for (var i = 0; i < oProd.arrComps.length; i++) // for each component { var oComp = oProd.arrComps[i]; if (oComp.aA) // if component has attributes { arrProdChoices[i] = new Array(oComp.aA.length); // create an array for each attribute for (var n = 0; n < oComp.aA.length; n++) // for each attribute { var oAttr = oComp.aA[n]; if (oAttr.nCC && oAttr.elem) // if attribute has choices and a UI element { if (bLoading) // if we are loading { if (oComp.bOpt && oComp.bSelDef && // if this is optional and default oAttr.elem.elemHTML.tagName == 'SPAN') // and using radio buttons { arrProdChoices[i][n] = 1; // select first valid option } else { arrProdChoices[i][n] = 0; // treat as Please select or first valid choice } } else { var sAttrValue = GetAttributeValue(oAttr.elem.elemHTML); // get value from UI var nAttrValue = (sAttrValue == '') ? 0 : parseInt(sAttrValue, 10); // // For sequential choices, any elements following a 'Please select' choice // should also be changed to 'Please select' // // Also any choices following an element that has changed should be reset // if (oProd.bSequentialChoices) { if (bSequentialDisable) // if we have already hit a please select { nAttrValue = 0; // change to Please select } else if (nAttrValue == 0 || // if user chose please select (elemChanged && elemChanged.name == oAttr.elem.elemHTML.name)) // or they changed this choice { if (!oComp.bOpt || IsCompEnabled(oComp, arrProdChoices[i])) // if this isn't an unselected optional component { bSequentialDisable = true; // reset subsequent choices } } } arrProdChoices[i][n] = nAttrValue; } } } } } return arrProdChoices; } /*********************************************************************** * * UpdateCompChoices - Update choices for a component * * Input: oProd - product object * oComp - component object * arrValues - array of user choices for the component * nStartIndex - index into the choices array to start from * ************************************************************************/ function UpdateCompChoices(oProd, oComp, arrValues, nStartIndex, nEndIndex) { if (!oComp.aA) { return; } var arrAttr = oComp.aA; if (nEndIndex == undefined) { nEndIndex = arrAttr.length; } for (var nAttrIndex = nStartIndex; nAttrIndex < nEndIndex; nAttrIndex++) // for each attribute { var nUserChoiceCount = GetUserChoiceCount(arrValues); var oAttr = GetNormAttr(oComp, nAttrIndex); // get the attribute var sUserValue = arrValues[nAttrIndex] ? arrValues[nAttrIndex] : ''; // save user's choice if (oAttr.elem == undefined) { continue; } var oSelect = oAttr.elem; var elemSelect = oSelect.elemHTML; // get HTML element var arrOptions = oSelect.arrOptions; // get original options var sHTML = ''; if (elemSelect.tagName == 'SELECT') { elemSelect.options.length = 0; // remove all options } else { sHTML = oSelect.arrHTMLFrag[0]; // start with leading HTML } var nOptIndex = 0; var nAdded = 0; var nSelIndex = -1; var nRBColCount = oAttr.nRBCCount; // get the column count if present var nOptionCount = arrOptions.length; var nValidChoiceCount = 0; var nFirstValidChoice = -1; var bOnlyOptionalChoiceAdded = false; for (var n = 0; n < nOptionCount; n++) { // // Note: Indexes into the arrFields structure defined by // how entries are added in function GetOptionsArray below. // var arrFields = arrOptions[n]; var sOptValue = arrFields[0]; arrValues[nAttrIndex] = sOptValue ? parseInt(sOptValue) : 0; var sText = arrOptions[n][1]; var sClass = arrOptions[n][2]; if ((n == 0 && sText == '') || // if Please select or IsValidOption(oComp, arrValues, nAttrIndex, nAttrIndex, nUserChoiceCount)) // this is valid? { if (n == 0 && arrValues[n] == 0) { bOnlyOptionalChoiceAdded = true; } else { bOnlyOptionalChoiceAdded = false; } nAdded++; if (sOptValue) // if this is a specific choice { nValidChoiceCount++; // increment specific choice count if (nValidChoiceCount == 1) // first valid specific choice? { nFirstValidChoice = arrValues[nAttrIndex]; // save it } } if (elemSelect.tagName == 'SELECT') // select element? { AddOption(elemSelect, sOptValue, sText, sOptValue == sUserValue, sClass); // just add the option } else { var sSepHTML = oSelect.arrHTMLFrag[nOptIndex + 1]; // get trailing html fragment if (nRBColCount > 1 && // more than 1 column? (nAdded % nRBColCount) == 0 && // and it's the first column n < arrOptions.length - 1) // but not last choice { sSepHTML = oSelect.arrHTMLFrag[nRBColCount]; // use the separator from the column } sHTML += sText + sSepHTML; // add the name plus trailing html } } nOptIndex++; } // // If we only have one valid choice, select it // if ((!oComp.bOpt || (arrAttr.length > 1)) && nValidChoiceCount == 1) { sUserValue = nFirstValidChoice; SetAttributeValue(elemSelect, sUserValue); // // If this is not a user-specified choice, then we need to // update any unspecified choices to reflect the new value // arrValues[nAttrIndex] = nFirstValidChoice; if (nAttrIndex > nUserChoiceCount) { UpdateCompChoices(oProd, oComp, arrValues, nUserChoiceCount, nAttrIndex); } } // // Disable the Add to cart if no valid choices // if ((nAdded == 0) || // no valid options? bOnlyOptionalChoiceAdded) { if (!oComp.bOpt) // not an optional component? { oProd.bNoATC = true; var sProdRef = oProd.sProdRef.replace(/^\d+!/, ''); var sOutOfStockID = 'EnableIfOutOfStock_' + sProdRef; var elemStock = document.getElementById(sOutOfStockID); if (elemStock) { elemStock.style.display = ''; elemStock.style.visibility = 'visible'; } elemStock = document.getElementById('RemoveIfOutOfStock_' + sProdRef); if (elemStock) { elemStock.style.display = 'none'; elemStock.style.visibility = 'hidden'; } elemStock = document.getElementById('RemoveIfOutOfStock_ATC_' + sProdRef); if (elemStock) { elemStock.style.display = 'none'; elemStock.style.visibility = 'hidden'; } } if (elemSelect.tagName == 'SELECT') { elemSelect.style.display = 'none'; oComp.elemHTML.value = ''; oComp.elemHTML.style.display = 'none'; if (oComp.elemHTML.type == 'checkbox') { oComp.elemHTML.checked = false; } } else {} } if (elemSelect.tagName != 'SELECT') { var elemContainer = document.getElementById('id' + elemSelect.name + '_Table'); elemContainer.innerHTML = sHTML; SetAttributeValue(elemSelect, sUserValue); } else { if (elemSelect.selectedIndex == -1) { elemSelect.selectedIndex = 0; } } var sAttrValue = GetAttributeValue(elemSelect); arrValues[nAttrIndex] = sAttrValue == '' ? 0 : parseInt(sAttrValue, 10); } } /*********************************************************************** * * GetPricePerm - Get a price permutation for user's choices * * Input: arrValues - array of user choices for the component * mapPerms - map of permutations for the component * ************************************************************************/ function GetPricePerm(arrValues, mapPerms) { if (!mapPerms) { return undefined; } if (mapPerms[arrValues]) // if we have a price object for these choices { return mapPerms[arrValues]; // return it } var arrTemp = Clone(arrValues); // copy the choices for (var i = 0; i < arrValues.length; i++) // now go through testing for 'Any' permutation { if (arrValues[i]) // if this isn't already 'Any' { arrTemp[i] = 0; if (mapPerms[arrTemp]) // if we have a permuation? { return mapPerms[arrTemp]; // found it } arrTemp[i] = arrValues[i]; // set back to user's choice } } return undefined; } /*********************************************************************** * * IsValidOption - Is this a valid choice for an attribute * * Input: oComp - component object * arrChoices - array of choices for this component * nAttrIndex - index of the attribute being tested * nTestIndex - index of the attribute whose choices are being populated * nUserChoiceCount - number of choices the user has made * * Returns: boolean - true if this is a valid choice * ************************************************************************/ function IsValidOption(oComp, arrChoices, nAttrIndex, nTestIndex, nUserChoiceCount) { if (oComp.nInvalidPermCount == 0) // if no invalid permutations { return true; // it's valid } var nUserChoice = arrChoices[nAttrIndex]; // save the choice if (nUserChoice > 0 && // if this is a specific choice oComp.nInvalidAnyCount == 0 && // and we have no invalid Any choice permutations oComp.arrInvalidPerms[nAttrIndex][nUserChoice] == 0) // and there are no invalid permutations for this choice { return true; // must be valid } var bValid = !IsInvalidAnyChoice(oComp, arrChoices, nAttrIndex, 0); if (bValid) { if (nAttrIndex != nTestIndex && // if this isn't the attribute we are testing nAttrIndex > nUserChoiceCount - 1) // and the choice wasn't set by the user { var oAttr = GetNormAttr(oComp, nAttrIndex); // get the attribute for this choice var nValidCount = oAttr.nCC - 1; // initialise number of valid specific choices for (var i = 1; i < oAttr.nCC; i++) // for each choice { arrChoices[nAttrIndex] = i; // update choice array if (nAttrIndex < arrChoices.length - 1) // if we have more attributes { if (!IsValidOption(oComp, arrChoices, nAttrIndex + 1, nTestIndex, nUserChoiceCount)) // test against the next attribute { nValidCount--; } } else if (oComp.mapNormPerms[arrChoices] == -1 || // if this choice is invalid (nAttrIndex > 0 && !HasValidPrevChoices(oComp, arrChoices, nTestIndex - 1, nTestIndex))) // or there are no valid previous choices { nValidCount--; } } bValid = nValidCount > 0; } else if (nAttrIndex < arrChoices.length - 1) // if not last attribute { bValid = IsValidOption(oComp, arrChoices, nAttrIndex + 1, nTestIndex, nUserChoiceCount); // check against rest of attributes } } arrChoices[nAttrIndex] = nUserChoice; // restore user choice if (bValid && nAttrIndex > 0) // if not the first attribute { if (!HasValidPrevChoices(oComp, arrChoices, nTestIndex - 1, nTestIndex)) // check against previous choices { bValid = false; } } return bValid; } /*********************************************************************** * * IsInvalidAnyChoice - Is this a valid choice for an attribute * * Input: oComp - component object * arrChoices - array of choices for this component * nAttrIndex - index of the attribute being tested * nStartIndex - index of the attribute to start testing against * * Returns: boolean - true if this is a valid choice * ************************************************************************/ function IsInvalidAnyChoice(oComp, arrChoices, nAttrIndex, nStartIndex) { if (oComp.mapNormPerms[arrChoices] == -1) // is this set of choices invalid? { return true; } if (oComp.nInvalidAnyCount == 0) // if there are no Any choice invalid permutations { return false; // choice is valid } for (var i = nStartIndex; i < arrChoices.length; i++) { if (arrChoices[i] == 0) // if this is Please select { // // Count how many specific choices are valid // var nValidCount = oComp.aA[nAttrIndex].nCC - 1; for (var nChoice = 1; nChoice < nValidCount; nChoice++) { arrChoices[i] = nChoice; if (oComp.mapNormPerms[arrChoices] == -1) { nValidCount--; } } arrChoices[i] = 0; if (nValidCount <= 0) { return true; } } if (i != nAttrIndex) // if this isn't the attribute being populated { var bInvalid = false; var nUserChoice = arrChoices[i]; arrChoices[i] = 0; // test against Any choice if (oComp.mapNormPerms[arrChoices] == -1) { bInvalid = true; } else if (i < arrChoices.length - 1) // if it's not the first attribute { if (IsInvalidAnyChoice(oComp, arrChoices, nAttrIndex, i + 1)) // check against Any choice for preceding attributes { bInvalid = true; } } arrChoices[i] = nUserChoice; // restore previous value if (bInvalid) { return true; } } } return false; } /*********************************************************************** * * HasValidPrevChoices - Is this choice compatible with any preceding choices * * Input: oComp - component object * arrChoices - array of choices for this component * nAttrIndex - index of the attribute being tested * nTestIndex - index of the attribute whose choices are being populated * * Returns: boolean - true if the choice specified by the attribute index is compatible the other choices * ************************************************************************/ function HasValidPrevChoices(oComp, arrChoices, nAttrIndex, nTestIndex) { if (nAttrIndex < 0) // no more attributes? { return true; // it must have choices } var bInvalid = false; var nUserChoice = arrChoices[nAttrIndex]; arrChoices[nAttrIndex] = 0; // check against Any choice if (oComp.mapNormPerms[arrChoices] == -1) { bInvalid = true; } else { arrChoices[nAttrIndex] = nUserChoice; // restore user choice if (nUserChoice == 0) // if this is Please select { var oAttr = GetNormAttr(oComp, nAttrIndex); // get the attribute object // // Count how many specific choices are valid // var nValidCount = oAttr.nCC - 1; for (var i = 1; i < oAttr.nCC; i++) { arrChoices[nAttrIndex] = i; if (oComp.mapNormPerms[arrChoices] == -1) { nValidCount--; } else { if (nAttrIndex > 0 && // if it is not previous attribute !HasValidPrevChoices(oComp, arrChoices, nAttrIndex - 1, nTestIndex)) // check against previous attributes { nValidCount--; } } } arrChoices[nAttrIndex] = nUserChoice; bInvalid = nValidCount < 1; } // // Check against previous attributes // if (!bInvalid && nAttrIndex > 0 && !HasValidPrevChoices(oComp, arrChoices, nAttrIndex - 1, nTestIndex)) { bInvalid = true; } } arrChoices[nAttrIndex] = nUserChoice; if (!bInvalid && nAttrIndex > 0) { // // Check against previous attributes // bInvalid = !HasValidPrevChoices(oComp, arrChoices, nAttrIndex - 1, nTestIndex); } return !bInvalid; } /*********************************************************************** * * IsCompEnabled - Is a component enabled * * Input: oComp - component object * arrCompChoices - array of choices for this component * * Returns: boolean - true if enabled * ************************************************************************/ function IsCompEnabled(oComp, arrCompChoices) { if (!oComp || !oComp.elemHTML) { return (false); } var elemComp = oComp.elemHTML; var bEnabled = (elemComp.value == 'on'); if (elemComp.type == 'checkbox') // if this is optional controlled by a checkbox { return elemComp.checked; // test if it is checked } if (arrCompChoices == undefined) // if component has no choices { return bEnabled; // no need to check for choice of -1 } return (bEnabled && (arrCompChoices[0] > -1)) // handle case where first select option has value of -1 } /*********************************************************************** * * ChoiceChanged - User has changed their choices * * Input: elemChanged - HTML element that changed * ************************************************************************/ function ChoiceChanged(elemChanged, sURL, sSID, sShopID) { var sName = elemChanged.name; // get name of HTML element var sProdRef; if (sName.indexOf('v_') == 0) // got the name? { var collMatch = sName.match(/^v_(.*)_\d+$/); // product ref is between 'v_' and '_nn' sProdRef = collMatch[1]; } else if (sName.indexOf('Q_') == 0) { sProdRef = sName.substr(2); } if (sProdRef) { if (!g_oConfig.bEstimateChoicePrices && !ValidateChoices(sProdRef, true, elemChanged)) { ShowDynamicPriceMessage(sProdRef, g_sUndeterminedPrice); } var oProd = g_mapProds[sProdRef]; // get the product UpdateChoices(oProd, false, elemChanged); // update the choices available UpdatePrice(oProd, sURL, sSID, sShopID); // update the price } } /*********************************************************************** * * ValidateChoices - Make sure user has supplied all required info * * Input: sProdRef - product reference * bSilent - true to suppress validation messages * elemChanged - element that has changed * * Returns: boolean - true if OK * ************************************************************************/ function ValidateChoices(sProdRef, bSilent, elemChanged) { var oProd = g_mapProds[sProdRef]; // get the product if (!oProd || !oProd.arrComps) { return true; } var arrProdChoices = GetProdChoices(oProd, elemChanged); // get choices for this product for (var i = 0; i < oProd.arrComps.length; i++) // for each product { if (!arrProdChoices[i]) { continue; } var oComp = oProd.arrComps[i]; if (IsCompEnabled(oComp, arrProdChoices[i]) && // if component is enabled !(oComp.bOpt && (oComp.aA.length == 1)) && // not an optional component with single attribute !ValidateComp(arrProdChoices[i], oComp.aA, bSilent)) // and the component doesn't have all selections { return false; // bomb out } } return true; // must be valid } /*********************************************************************** * * ValidateComp - Validate the choices for a component * * Input: arrCompChoices - array of choices for a component * arrAttr - array of attributes * * Returns: boolean - true if OK * ************************************************************************/ function ValidateComp(arrCompChoices, arrAttr, bSilent) { for (var i = 0; i < arrCompChoices.length; i++) // for each choice { if (!arrCompChoices[i]) // valid choices are greater than 0 or -1 (for optional components) { if (!bSilent) { var sMsg = 'Please select a ' + arrAttr[i].sN; var elemHTML = arrAttr[i].elem.elemHTML; alert(sMsg); // // There is an IE issue with the DOM thinking the span enclosing a radio button as empty even though it isn't. // To get around this, get the name from the span id and derive the name from that and just select // the first element in the collection. // if (elemHTML.tagName != 'SELECT') { var sFocusName = elemHTML.id.replace(/(_(\d+|))$/, ''); // get the name attribute of the element to focus var collNamed = document.getElementsByName(sFocusName); // get the collection if (collNamed.length > 0) { elemHTML = collNamed[0]; // set focus to first element } } elemHTML.focus(); } return false; // need more info } } return true; // must be OK } /*********************************************************************** * * UpdatePrice - Update the price for a product * * Input: oProd - product object * ************************************************************************/ function UpdatePrice(oProd, sURL, sSID, sShopID) { if (!oProd || oProd.bFixPrice || oProd.bNoATC || !sURL) // skip if no product, not dynamic pricing or no valid choices { return; } var elemTaxIncPrice = document.getElementById('id' + oProd.sProdRef + 'TaxIncPrice'); // get tax inclusive element var elemTaxExcPrice = document.getElementById('id' + oProd.sProdRef + 'TaxExcPrice'); // get tax exclusive element var elemAccPrice = document.getElementById('id' + oProd.sProdRef + 'AccountPrice'); // account price placeholder if (!elemTaxIncPrice && !elemTaxExcPrice && !elemAccPrice) // neither present? { return; // nothing to do } var elemTaxMsg = document.getElementById('id' + oProd.sProdRef + 'VATMsg'); // get the tax message element (e.g Including VAT at 20%) // // Display the price html // var elemPriceContainer = document.getElementById('id' + oProd.sProdRef + 'DynamicPrice'); var elemStPriceContainer = document.getElementById('id' + oProd.sProdRef + 'StaticPrice'); if (oProd.bOvrStaticPrice && elemStPriceContainer && !oProd.bQuantityBreak) { elemStPriceContainer.style.visibility = "hidden"; elemStPriceContainer.style.display = "none"; } var sOriginalRef = GetOriginalRef(oProd.sProdRef); if (!g_mapDynPrices[sOriginalRef] && !g_mapDynPrices.ErrorMsg) { getDynamicAccPrice(sURL, sSID, oProd, sShopID); // calculate account prices dynamically } else { if (g_mapDynPrices.ErrorMsg || g_mapDynPrices[sOriginalRef].ErrorMsg) // is there an error { if (elemTaxMsg) // make sure we have an element { elemTaxMsg.style.visibility = "hidden"; elemTaxMsg.style.display = "none"; } if (elemTaxExcPrice) // display the error message instead of the price { elemTaxExcPrice.innerHTML = g_mapDynPrices.ErrorMsg ? g_mapDynPrices.ErrorMsg : g_mapDynPrices[sOriginalRef].ErrorMsg; } else if (elemTaxIncPrice) { elemTaxIncPrice.innerHTML = g_mapDynPrices.ErrorMsg ? g_mapDynPrices.ErrorMsg : g_mapDynPrices[sOriginalRef].ErrorMsg; } if (elemPriceContainer) { elemPriceContainer.style.display = ''; elemPriceContainer.style.visibility = 'visible'; } return; } if (elemTaxMsg) // make sure we have an element { elemTaxMsg.style.visibility = "visible"; elemTaxMsg.style.display = ""; } var nTotalExcTax = g_mapDynPrices[sOriginalRef].Total; var nTotalIncTax = g_mapDynPrices[sOriginalRef].Total + g_mapDynPrices[sOriginalRef].Tax1 + g_mapDynPrices[sOriginalRef].Tax2; if (elemTaxExcPrice) { elemTaxExcPrice.innerHTML = FormatPrices(nTotalExcTax); } if (elemTaxIncPrice) { elemTaxIncPrice.innerHTML = FormatPrices(nTotalIncTax); } } if (elemPriceContainer) { elemPriceContainer.style.display = ''; elemPriceContainer.style.visibility = 'visible'; } } /*********************************************************************** * * FormatPrices - Format main and alternate currency prices * * Input: nPrice - price to format * * Returns: String - formatted price or prices * ************************************************************************/ function FormatPrices(nPrice) { var arrPrices = []; for (var i = 0; i < g_oConfig.arrCurrs.length; i++) { var oCurr = g_oConfig.arrCurrs[i]; arrPrices.push(FormatPrice(nPrice, oCurr)); } if (arrPrices.length == 1) { return arrPrices[0]; } else { return Sprintf(g_oConfig.sPriceFmt, arrPrices[0], arrPrices[1]); } } /*********************************************************************** * * ZeroPad - Returns a zero-padded number * * Input: nValue - number to pad if necessary * nLength - length to pad to * * Returns: String - 0-padded number * ************************************************************************/ function ZeroPad(nValue, nLength) { var sZeros = '000000000000000'; var sValue = nValue.toString(); if (sValue.length < nLength) { sValue = sZeros.substr(0, nLength - sValue.length) + sValue; } return sValue; } /*********************************************************************** * * FormatPrice - Format a currency price * * Input: nPrice - price to format * oCurr - currency object * * Returns: String - formatted price * ************************************************************************/ function FormatPrice(nPrice, oCurr) { var dRate = parseFloat(oCurr.sRate); var nCurrPrice = Math.round(nPrice * dRate); var nDecsFactor = Math.pow(10, oCurr.nDecs); var nThousFactor = Math.pow(10, oCurr.nThous); var sPrice = ''; var nTempPrice = nCurrPrice; if (nDecsFactor > 1) { var nDecPrice = nTempPrice % nDecsFactor; sPrice = oCurr.sDecSep + ZeroPad(nDecPrice, oCurr.nDecs); nTempPrice = parseInt(nTempPrice / nDecsFactor); } if (nTempPrice == 0) { sPrice = '0' + sPrice; } else { while (nTempPrice) { var nThous = nTempPrice % nThousFactor; nTempPrice = parseInt(nTempPrice / nThousFactor); if (nTempPrice) { sPrice = oCurr.sThouSep + ZeroPad(nThous, oCurr.nThous) + sPrice; } else { sPrice = nThous.toString() + sPrice; } } } return oCurr.sSym + sPrice; } /************************************************************************ * * GetTaxRate - Get tax rate from percentage * * Input: sTaxRate - tax rate as percentage * * Returns: tax rate as fraction * ************************************************************************/ function GetTaxRate(sTaxRate) { return sTaxRate / 100; } /************************************************************************ * * AddOption - Add an option to a select element * * Input: elemSelect - select element * sValue - value * sText - text * bSelected - selected or not * sClass - class name * * Returns: option element * ************************************************************************/ function AddOption(elemSelect, sValue, sText, bSelected, sClass) { var oOption = document.createElement("OPTION"); // create an option oOption.text = sText; // set text oOption.value = sValue; // set value if (bSelected) { oOption.selected = true; } oOption.className = sClass; elemSelect.options.add(oOption); // add option to select element return oOption; } /************************************************************************ * * CSelect - Object encapsulating the UI for choices * * Input: elemHTML - HTML element * ************************************************************************/ function CSelect(elemHTML) { this.elemHTML = elemHTML; if (elemHTML.tagName == 'SELECT') { this.arrOptions = GetOptionsArray(elemHTML); this.sValue = elemHTML.value; } else { this.arrOptions = GetOptionsArray(elemHTML, this); } } /************************************************************************ * * GetOptionsArray - Get options array * * Input: elemSelect - HTML element * oSelect - select object if choices are not a dropdown * * Returns: array of arrays containing value, text and class name * ************************************************************************/ function GetOptionsArray(elemSelect, oSelect) { var arrOptions = []; if (elemSelect.tagName == 'SELECT') { // // Just go through the option of a select element // for (var i = 0; i < elemSelect.options.length; i++) { var elemOption = elemSelect.options[i]; var arrData = [elemOption.value, elemOption.text, elemOption.className]; // these are accessed in function UpdateCompChoices above arrOptions.push(arrData); } } else { // // Radio buttons have the text as a separate element so we need to extract it from surrounding span // var elemContainer = document.getElementById('id' + elemSelect.name + '_Table'); if (elemContainer) { var sHTML = elemContainer.innerHTML; // get the inner HTML var arrHTML = []; // set up an array of HTML fragments between attribute spans var collNames = document.getElementsByName(elemSelect.name); // get all elements with this name var nStart = 0; var nIndex = 0; for (var i = 0; i < collNames.length; i++) // go through the elements { var elemName = collNames[i]; var sValue = elemName.value; // get the value var sClass = elemName.className; var sSpanID = elemSelect.name + '_' + sValue; // construct id of the span var elemSpan = document.getElementById(sSpanID); var sSpanHTML = elemSpan.outerHTML; // get whole HTML for the span if (!sSpanHTML) // outerHTML isn't supported universally { var nIDStart = sHTML.indexOf(elemSpan.id); // find the start of the id var nSpanStart = sHTML.lastIndexOf('<', nIDStart); // find start of the tag var nSpanEnd = sHTML.indexOf('>', nSpanStart + elemSpan.innerHTML.length); // find end of the tag sSpanHTML = sHTML.substring(nSpanStart, nSpanEnd + 1); } arrOptions.push([sValue, sSpanHTML, sClass]); // add to the options array. These are accessed in function UpdateCompChoices above nIndex = sHTML.indexOf(sSpanHTML, nStart); arrHTML.push(sHTML.substring(nStart, nIndex)); // add the HTML before the span nStart = nIndex + sSpanHTML.length; } arrHTML.push(sHTML.substr(nStart)); // add any trailing HTML oSelect.arrHTMLFrag = arrHTML; // save to the select object } } return arrOptions; } /************************************************************************ * * GetChoiceValues - Get choice values selected by user * * Input: elemForm - form element * * Returns: array of numeric values * ************************************************************************/ function GetChoiceValues(elemForm) { var arrValues = []; var arrElemAttr = GetAttributes(elemForm); for (var i = 0; i < arrElemAttr.length; i++) { var sAttrValue = GetAttributeValue(arrElemAttr[i]); var nAttrValue = (sAttrValue == '') ? 0 : parseInt(sAttrValue, 10); arrValues.push(nAttrValue); } return arrValues; } var reProdRefName = /^v_(.*)_\d+$/; var reProdRefID = /^v_(.*)_\d+_\d+$/; /************************************************************************ * * GetProdRefFromElem - Get product reference from an element * * Input: elemHTML - HTML element * * Returns: product ref or empty string * ************************************************************************/ function GetProdRefFromElem(elemHTML) { var sName = elemHTML.name; if (!sName) { var oMatch = elemHTML.id.match(reProdRefID); // try and get prod ref from the ID attribute if (oMatch) { return oMatch[1]; } } if (sName) { var oMatch = sName.match(reProdRefName); // try and get prod ref from name attribute if (oMatch) { return oMatch[1]; } } return ''; } var reAttr = /\bajs-attr\b/; /************************************************************************ * * GetAttributes - Get attributes from a form * * Input: elemForm - form element * * Returns: map of attributes keyed by prod refs * ************************************************************************/ function GetAttributes(elemForm) { var mapAttrElems = {}; var mapRadioAttrElems = {}; var arrAll = GetAllElements(elemForm); for (var i = 0; i < arrAll.length; i++) // go through all elements in the form { var elemHTML = arrAll[i]; if (reAttr.test(elemHTML.className)) // does it have ajs-attr in class name { var sProdRef = GetProdRefFromElem(elemHTML); // get product reference if (!mapAttrElems[sProdRef]) // first for this ref? { mapAttrElems[sProdRef] = []; // create a map } if (elemHTML.tagName == 'SELECT') { mapAttrElems[sProdRef].push(elemHTML); // just add a select element } else { var sName = elemHTML.id.replace(/_\d+$/, ''); // derive name from id elemHTML.name = sName; if (!mapRadioAttrElems[sName]) // only add the first radio button with this name { mapRadioAttrElems[sName] = elemHTML; mapAttrElems[sProdRef].push(elemHTML); } } } } return mapAttrElems; // return our map } /************************************************************************ * * GetAttributeValue - Get an attribute value * * Input: elemSelAttr - element associated with an attribute * * Returns: value HTML attribute associated with an attribute * ************************************************************************/ function GetAttributeValue(elemSelAttr) { if (elemSelAttr.tagName == 'SELECT') { return elemSelAttr.value; } var collSel = document.getElementsByName(elemSelAttr.name); for (var i = 0; i < collSel.length; i++) { if (collSel[i].checked) { return collSel[i].value; } } return 0; } /************************************************************************ * * SetAttributeValue - Set an attribute value * * Input: elemSelAttr - element associated with an attribute * sValue - value to set * ************************************************************************/ function SetAttributeValue(elemSelAttr, sValue) { if (elemSelAttr.tagName == 'SELECT') { elemSelAttr.value = sValue; return (elemSelAttr.value == sValue); } var collSel = document.getElementsByName(elemSelAttr.name); for (var i = 0; i < collSel.length; i++) { if (collSel[i].value == sValue) { collSel[i].checked = true; return true; } } if (collSel.length > 0) collSel[0].checked = true; return false; } /************************************************************************ * * Clone - Clone an array * * Input: arrSource - array to copy * * Returns: copy of the array * ************************************************************************/ function Clone(arrSource) { var arrReturn = new Array(arrSource.length); for (var i = 0; i < arrSource.length; i++) { arrReturn[i] = arrSource[i]; } return arrReturn; } /*********************************************************************** * * QuantityTimer - User has changed the quantity - timer fires * * Input: elemChanged - HTML element that changed * ************************************************************************/ function QuantityTimer(elemChanged, sURL, sSID, sShopID) { var sName = elemChanged.name; // get name of HTML element if (sName.indexOf('Q_') == 0) { sProdRef = sName.substr(2); } if (sProdRef) { var oProd = g_mapProds[sProdRef]; // get the product if (!g_oConfig.bEstimateChoicePrices && !ValidateChoices(sProdRef, true, elemChanged)) { var elemPriceContainer = document.getElementById('id' + sProdRef + 'DynamicPrice'); var elemStPriceContainer = document.getElementById('id' + sProdRef + 'StaticPrice'); if (oProd.bOvrStaticPrice && elemPriceContainer && elemPriceContainer.style.display == "none") { if (elemStPriceContainer && !oProd.bQuantityBreak) { elemStPriceContainer.style.visibility = "hidden"; elemStPriceContainer.style.display = "none"; } elemPriceContainer.style.display = ''; elemPriceContainer.style.visibility = 'visible'; } ShowDynamicPriceMessage(sProdRef, g_sUndeterminedPrice); return; } if (oProd.arrComps) // if we have components { UpdateChoices(oProd, false, elemChanged); // update the choices available } UpdatePrice(oProd, sURL, sSID, sShopID); // update the price } } /*********************************************************************** * * QuantityChanged - User has changed the quantity * * Input: elemChanged - HTML element that changed * ************************************************************************/ function QuantityChanged(elemChanged, sURL, sSID, sShopID) { if (timeout) { clearTimeout(timeout); // reset timeout = null; } timeout = setTimeout(function() { QuantityTimer(elemChanged, sURL, sSID, sShopID) }, g_nTimeout); } /*********************************************************************** * * ShowDynamicPriceMessage - Update the dynamic price with an * infomation/error message * * Input: sProdRef - the product reference * sMsg - the message * ************************************************************************/ function ShowDynamicPriceMessage(sProdRef, sMsg) { var elemTaxIncPrice = document.getElementById('id' + sProdRef + 'TaxIncPrice'); // get tax inclusive element var elemTaxExcPrice = document.getElementById('id' + sProdRef + 'TaxExcPrice'); // get tax exclusive element var elemTaxMsg = document.getElementById('id' + sProdRef + 'VATMsg'); // get the tax message element (e.g Including VAT at 20%) if (elemTaxMsg) // might be hidden if dynamic prices turned off { elemTaxMsg.style.visibility = "hidden"; elemTaxMsg.style.display = "none"; } if (elemTaxIncPrice && elemTaxExcPrice) { elemTaxIncPrice.innerHTML = ''; elemTaxExcPrice.innerHTML = sMsg; } else if (elemTaxIncPrice) { elemTaxIncPrice.innerHTML = sMsg; } else if (elemTaxExcPrice) { elemTaxExcPrice.innerHTML = sMsg; } } /************************************************************************ * * GetChangedElemIndices - Get the indices of component and attribute corresponding to an html element * * Input: oProd - product object * elemChanged - changed element * * Returns: undefined if not found, otherwise an object with nCompIndex and nAttrIndex properties * ************************************************************************/ function GetChangedElemIndices(oProd, elemChanged) { if (!elemChanged || // if there's no changed element !oProd.arrComps) // or no components { return; // bomb out } for (var nCompIndex = 0; nCompIndex < oProd.arrComps.length; nCompIndex++) // for each component { var oComp = oProd.arrComps[nCompIndex]; if (!oComp.aA) // skip components with no attributes { continue; } for (var nAttrIndex = 0; nAttrIndex < oComp.aA.length; nAttrIndex++) // for each attribute { var oAttr = oComp.aA[nAttrIndex]; if (elemChanged.tagName == 'SELECT') { if (oAttr.elem.elemHTML == elemChanged) // is this the changed attribute? { return { nCompIndex: nCompIndex, nAttrIndex: nAttrIndex }; // return indices } } else if (elemChanged.tagName == 'INPUT' && elemChanged.type == 'radio') { if (oAttr.elem.elemHTML.name == elemChanged.name) { return { nCompIndex: nCompIndex, nAttrIndex: nAttrIndex }; // return indices } } } } } /************************************************************************ * * CloneArray - Make a copy of an array * * Input: arrSrc - array to copy * * Returns: Array - copy of the array * ************************************************************************/ function CloneArray(arrSrc) { var arrClone = new Array(arrSrc.length); for (var i = 0; i < arrSrc.length; i++) { arrClone[i] = arrSrc[i]; } return arrClone; } /************************************************************************ * * UpdateUserSequence - Keep track of the order choices have been made * * Input: oComp - component object * nChangedAttrIndex - index of changed attribute * arrCompChoices - array of user choices * ************************************************************************/ function UpdateUserSequence(oComp, nChangedAttrIndex, arrCompChoices) { var arrUserSeq = oComp.arrUserSeq; var nChangedValue = arrCompChoices[nChangedAttrIndex]; // save changed choice for (var i = 0; i < arrUserSeq.length; i++) { if (arrUserSeq[i] == nChangedAttrIndex) // if this is the changed attribute { arrUserSeq.splice(i, 1); // remove it from the sequence break; } } if (nChangedValue > 0) // if the changed choice wasn't to Please select { arrUserSeq.push(nChangedAttrIndex); // add to end of user choices } } /************************************************************************ * * NormaliseAttrSeq - Normalise the attribute sequence * * Populate an array so that the sequence of choices the user has made * can be tracked to the actual attribute * * Input: oComp - component object * ************************************************************************/ function NormaliseAttrSeq(oComp) { if (!oComp.aA) { return; } // // The sequence of attribute indices will be user-specified user choices // with the most recent last followed by any other unspecified choices // var arrNormAttrSeq = []; var mapUsed = {}; // // Add user-selected choices // for (var i = 0; i < oComp.arrUserSeq.length; i++) { var nAttrIndex = oComp.arrUserSeq[i]; mapUsed[nAttrIndex] = 1; arrNormAttrSeq.push(nAttrIndex); } // // Add unspecified choices // for (var i = 0; i < oComp.aA.length; i++) { if (!mapUsed[i]) { arrNormAttrSeq.push(i); } } oComp.arrNormAttrSeq = arrNormAttrSeq; } /************************************************************************ * * NormaliseUserChoices - Change the order of user choices to reflect the * order the user made them * * Input: oComp - component object * arrCompChoices - index of choices in source code order * * Returns: Array - user choices in order the user made them * ************************************************************************/ function NormaliseUserChoices(oComp, arrCompChoices) { var arrNormChoices = []; for (var i = 0; i < oComp.arrNormAttrSeq.length; i++) { var nAttrIndex = oComp.arrNormAttrSeq[i]; arrNormChoices.push(arrCompChoices[nAttrIndex]); } return arrNormChoices; } /************************************************************************ * * GetNormAttr - Get an attribute object from the index of the user choice * * Input: oComp - component object * nNormIndex - index of the attribute adjusted for the sequence of choices made * * Returns: Object - attribute object * ************************************************************************/ function GetNormAttr(oComp, nNormIndex) { var nRealAttrIndex = oComp.arrNormAttrSeq[nNormIndex]; return oComp.aA[nRealAttrIndex]; } /************************************************************************ * * MapInvalidPermutations - Check how many invalid permutations there are * and transfer invalid permuations to a new map * * Input: oComp - component object * ************************************************************************/ function MapInvalidPermutations(oComp) { oComp.nInvalidPermCount = 0; if (!oComp.mP) { return; } var mapInvalid = {}; var mapPerms = oComp.mP; var bHideOutOfStock = oComp.hOS; for (var sKey in mapPerms) { var arrAssocDetails = mapPerms[sKey]; if ((arrAssocDetails[0] == -1) || // permutation invalid? ((arrAssocDetails[0] == 0) && // permutation valid? (bHideOutOfStock && arrAssocDetails[1] != '') && // hide out of stock (g_mapStockByRef[arrAssocDetails[1]] != undefined && // if we have a stock g_mapStockByRef[arrAssocDetails[1]] <= 0))) // out of stock { mapInvalid[sKey] = -1; oComp.nInvalidPermCount++; } } oComp.mapInvalid = mapInvalid; } /************************************************************************ * * NormalisePerms - Remap invalid permutations so they are keyed by user choice sequence * * Input: oComp - component object * ************************************************************************/ function NormalisePerms(oComp) { var mapNormPerms = {}; var mapPerms = oComp.mapInvalid; for (var sKey in mapPerms) { if (oComp.aA.length == 1) // single attribute? { mapNormPerms[sKey] = -1; // use existing key } else { var arrValues = sKey.split(','); var arrIndices = []; for (var i = 0; i < oComp.arrNormAttrSeq.length; i++) { var nAttrIndex = oComp.arrNormAttrSeq[i]; arrIndices.push(arrValues[nAttrIndex]); } mapNormPerms[arrIndices] = -1; } } oComp.mapNormPerms = mapNormPerms; GetInvalidAttrCounts(oComp); } /************************************************************************ * * GetInvalidAttrCounts - Calculate how many invalid permutations specify * a specific choice * * Input: oComp - component object * ************************************************************************/ function GetInvalidAttrCounts(oComp) { oComp.nInvalidAnyCount = 0; // // Create the array of attributes with each choice set to 0 // var arrInvalidPerms = new Array(oComp.aA.length); for (var nAttr = 0; nAttr < arrInvalidPerms.length; nAttr++) { var oAttr = GetNormAttr(oComp, nAttr); var nChoiceCount = oAttr.nCC var arrChoices = new Array(nChoiceCount); for (var i = 0; i < nChoiceCount; i++) { arrChoices[i] = 0; } arrInvalidPerms[nAttr] = arrChoices; } // // Update the counts for each specific choice // for (var sKey in oComp.mapNormPerms) { var arrVals = sKey.split(','); for (var nAttr = 0; nAttr < arrVals.length; nAttr++) // for each value { var arrInvalidAttrPerms = arrInvalidPerms[nAttr]; // get the attribute array var nVal = arrVals[nAttr]; // get choice value if (nVal != 0) { arrInvalidAttrPerms[nVal]++; // increment specific choice count } else { oComp.nInvalidAnyCount++; // increment global any choice count } } } oComp.arrInvalidPerms = arrInvalidPerms; } /************************************************************************ * * GetUserChoiceCount - Get how many specific choices there are * * Input: arrUserChoices - array of user choices * ************************************************************************/ function GetUserChoiceCount(arrUserChoices) { var nCount = 0; for (var i = 0; i < arrUserChoices.length; i++) { if (arrUserChoices[i] != 0) // not Please select? { nCount++; // increment count } } return nCount; }<file_sep>/www.cater4you.co.uk/acatalog/actinicsearch.js /*************************************************************** * * ActinicSearch.js - utility functions for search functionality * * Copyright (c) 2012-2014 SellerDeck Limited * ****************************************************************/ //-------------------------------------------------------------- // // Common functions // // For example initialisation // //-------------------------------------------------------------- // // Global variables for debugging // var g_bIsDebugging = false; // make it true for debugging var g_ErrorCode = { TAG: 1, // tag not found LOGIC: 2, // logical error IO: 3, // input/output error UNDEFINED: 4 // global variable undefined }; /*********************************************************************** * * ShowError - Show error message * Inputs: sMessage - message to log * nErrorType - error type code * * Returns: - nothing * ************************************************************************/ function ShowError(sMessage, nErrorType) { var sErrorType = ""; switch (nErrorType) { case g_ErrorCode.TAG: // tag not found error sErrorType = "Tag not found error"; break; case g_ErrorCode.LOGIC: // logical error sErrorType = "Logical error"; break; case g_ErrorCode.IO: // input/output error sErrorType = "Input output error"; break; case g_ErrorCode.UNDEFINED: sErrorType = "Variable undefined error"; break; default: // unknown error sErrorType = "Unknown error"; break; } var sError = "Error: " + sErrorType + "\nMessage: " + sMessage; if (g_bIsDebugging) // is debugging enabled { console.log(sError); // show error message } } /*********************************************************************** * * GetIEVersion - Get IE version * * Returns: - version * ************************************************************************/ function GetIEVersion() { var nVersion = 0; // default for other browsers if (/MSIE (\d+\.\d+);/.test(navigator.userAgent)) // test for IE { nVersion = new Number(RegExp.$1) // get the version } return nVersion; } /*********************************************************************** * * GetArrayIndex - Get index of given key in an array * * Inputs: arrInput - input array * sKey - key to match * * Returns: - return the matched index * ************************************************************************/ function GetArrayIndex(arrInput, sKey) { if (!Array.prototype.indexOf) // no indexOf defined { var nLen = arrInput.length; for (var nIdx = 0; nIdx < nLen; nIdx++) { if (arrInput[nIdx] === sKey) return nIdx; // match found } return -1; // no match found } else { return (arrInput.indexOf(sKey)); } } /*********************************************************************** * * InsertSort - Sort array * * Inputs: arrToStart - array to sort * * Returns: - sorted array * Ref: http://jsperf.com/ ************************************************************************/ function InsertSort(arrToStart) { for (var nIdx = 1; nIdx < arrToStart.length; nIdx++) { var tmpVal = arrToStart[nIdx]; var nIdxToComp = nIdx; while (arrToStart[nIdxToComp - 1] > tmpVal) { arrToStart[nIdxToComp] = arrToStart[nIdxToComp - 1]; --nIdxToComp; } arrToStart[nIdxToComp] = tmpVal; } return arrToStart; } /*********************************************************************** * * IsPreview - Check if we are in page/design preview * * Returns: - true/false * ************************************************************************/ function IsPreview() { if (window.location.href.indexOf('file://') == 0) // preview? { return true; } return false; } /*********************************************************************** * * EscapeRegExp - Escape Regular Expressions * * Inputs: sString - string to escape * * Returns: - modified string * ************************************************************************/ function EscapeRegExp(sString) { return sString.replace(/[\-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g, '\\$&'); } //-------------------------------------------------------------- // // Tweaks on standard functionality // // For example handling "Any" in multi-select UIs // //-------------------------------------------------------------- //-------------------------------------------------------------- // // Auto-suggestion in search text boxes // //-------------------------------------------------------------- /*********************************************************************** * * Based on script written by <NAME>, provided by Css Globe (cssglobe.com) * More info @ http://cssglobe.com/post/1202/style-your-websites-search-field-with-jscss/ * * Written by <NAME> * Note: Make sure the global variable 'pg_sSearchScript' defined in html page * ************************************************************************/ /*********************************************************************** * * AutoSuggest - Add autosuggest functionality to search field * * Inputs: thisSearch - auto suggest field * * Affects: functions added to thisSearch to implement auto-suggest * ************************************************************************/ function AutoSuggest(thisSearch) { // // The following values are incorporated into a closure that controls auto-suggest for the field // var mc_nTimerDelay = 500; // standard delay before auto-suggest kicks in var mc_bIsTimerOn = false; // is timer on for providing auto-suggest items var mc_nTimerID; var mc_arrPreviousSearchWords = new Array(); // previous word list var mc_arrUnchangedSearchWords = new Array(); // unchanged search word list var mc_mapUnmatchedSearchWords = {}; // unmatched word list var mc_sLastSearchText = ''; // last search text var mc_nSelectedIndex = 0; // currently selected item in suto-suggest drop-down // // variables to define keys // var AS_KEYS = { ENTER: 13, ESC: 27, SPACE: 32, LEFTARROW: 37, UP: 38, RIGHTARROW: 39, DOWN: 40 }; // // Ensure the following are defined // - pg_sSearchScript // - thisSearch // if ((typeof(pg_sSearchScript) !== 'undefined') && thisSearch) { if (thisSearch.value === 'Quick Search') // clear the default text { thisSearch.value = ""; // empty the text } var mc_elASDiv = document.createElement("div"); // div that contains the AutoSuggest list var posX = findPosX(thisSearch); var posY = findPosY(thisSearch); posY += thisSearch.offsetHeight; mc_elASDiv.style.left = posX + "px"; mc_elASDiv.style.top = posY + "px"; var mc_elASList = document.createElement("ul"); // list of AutoSuggest words mc_elASList.style.display = "none"; mc_elASDiv.className = "sf_suggestion"; mc_elASList.style.width = thisSearch.offsetWidth + "px"; mc_elASDiv.appendChild(mc_elASList); thisSearch.parentNode.appendChild(mc_elASDiv); /*********************************************************************** * * onblur - Focus has been lost from this field * * Auto-suggest div is removed from the parent * ************************************************************************/ thisSearch.onblur = function() { if (mc_elASDiv.parentNode === thisSearch.parentNode) // div is there? { thisSearch.parentNode.removeChild(mc_elASDiv); // remove the div tag completely } } /*********************************************************************** * * onkeypress - User has pressed a key * * Input: e - event for key that was pressed * ************************************************************************/ thisSearch.onkeypress = function(e) { var key = thisSearch.AS_getKeyCode(e); if (key == AS_KEYS.ENTER && // it's the enter key mc_elASList.style.display != 'none' && // list is displayed currently mc_nSelectedIndex != 0) // and there is a selection in the list { thisSearch.AS_selectList(); // select that item mc_nSelectedIndex = 0; } return true; } /*********************************************************************** * * onkeyup - User has released a key * * Inputs: e - event * ************************************************************************/ thisSearch.onkeyup = function(e) { var key = thisSearch.AS_getKeyCode(e); switch (key) { case AS_KEYS.LEFTARROW: // ignore these case AS_KEYS.RIGHTARROW: case AS_KEYS.ENTER: return false; case AS_KEYS.ESC: // clear list on escape thisSearch.value = ""; mc_nSelectedIndex = 0; thisSearch.AS_clearList(); break; case AS_KEYS.UP: // go up in the list thisSearch.AS_navList("up"); break; case AS_KEYS.DOWN: // go down in the list thisSearch.AS_navList("down"); break; default: if (thisSearch.value == '') // if the text entered is now empty (perhaps Delete pressed) { thisSearch.AS_clearList(); // make sure list is empty } else { // otherwise there's some valid input thisSearch.AS_clearTimer(); // clear mc_nTimerID before starting so if user typing, we don't look for suggestions too early thisSearch.AS_setTimer(mc_nTimerDelay); // set the time for a delay } break; } } /*********************************************************************** * * AS_getListItems - Get the result list * * Called on a timer to fill the list of items * ************************************************************************/ thisSearch.AS_getListItems = function() { var arrSearchHits = new Array(); var arrCurrentSearchWordsNoEmpty = new Array(); // words without empty var sJsonResponse = {}; var httpRequest; var sCleanWordCharacterSet = pg_sSearchValidWordCharacters; sCleanWordCharacterSet = sCleanWordCharacterSet.replace(/([\^\$\.\*\+\?\=\!\:\|\\\/\(\)\[\]\{\}])/g, "\\$1"); // escape any regular expression characters var reNonWordCharacterSet = new RegExp("[^" + sCleanWordCharacterSet + "]"); // create regular expression that matches any non-word characters var arrCurrentSearchWords = thisSearch.value.split(reNonWordCharacterSet); // split input on non-word characters var sSearchText = ''; arrCurrentSearchWordsNoEmpty.length = 0; // // clean list of words without empty // for (var i = 0; i < arrCurrentSearchWords.length; i++) { if (arrCurrentSearchWords[i]) { arrCurrentSearchWordsNoEmpty.push(arrCurrentSearchWords[i]); } } var arrChangedSearchWord = thisSearch.AS_getChangedSearchWord(arrCurrentSearchWordsNoEmpty); sSearchText = arrChangedSearchWord[arrChangedSearchWord.length - 1]; arrChangedSearchWord.length = 0; if (typeof(sSearchText) === 'undefined') { return; } // // global variable 'pg_sSearchScript' defined in html page // var sUrl = pg_sSearchScript; // // send request // var ajaxRequest = new ajaxObject(sUrl); ajaxRequest.callback = function(responseText) { if (responseText === '') { return; } try { sJsonResponse = responseText.parseJSON(); } catch (e) { return; } if (sJsonResponse.count != 0) { arrSearchHits = sJsonResponse.words; if (thisSearch.value.length > 0) { thisSearch.AS_createList(arrSearchHits, arrCurrentSearchWordsNoEmpty, sSearchText, true); mc_sLastSearchText = sSearchText; } else { thisSearch.AS_clearList(); } } else if (sSearchText) // capture unmatched words { mc_sLastSearchText = sSearchText; arrSearchHits.push(sSearchText); mc_mapUnmatchedSearchWords[sSearchText] = ''; thisSearch.AS_createList(arrSearchHits, arrCurrentSearchWordsNoEmpty, sSearchText, false); } } var sParams = 'ACTION=MATCH&TEXT=' + sSearchText; if (IsHostMode()) { sParams += '&SHOP=' + pg_sShopID; } ajaxRequest.update(sParams, "GET"); mc_arrPreviousSearchWords = arrCurrentSearchWordsNoEmpty; thisSearch.AS_clearTimer(); } /*********************************************************************** * * AS_getChangedSearchWord - Get changed search words * * Inputs: arrCurrentSearchWords - current search words * * Returns: - array of changed search words * ************************************************************************/ thisSearch.AS_getChangedSearchWord = function(arrCurrentSearchWords) { var arrNewSearchWords = new Array(); // new search word list if (arrCurrentSearchWords.length > 0) { for (var i = 0; i < arrCurrentSearchWords.length; i++) { if (thisSearch.AS_findFromArray(mc_arrPreviousSearchWords, arrCurrentSearchWords[i])) { mc_arrUnchangedSearchWords.push(arrCurrentSearchWords[i]); } else { arrNewSearchWords.push(arrCurrentSearchWords[i]); } } } return arrNewSearchWords; } /*********************************************************************** * * AS_createList - Create auto suggest list * Inputs: arrSearchHits - search hits * arrCurrentSearchWords - current search words * sSearchText - active search word * bMatchFound - match found? * * Returns: - nothing * ************************************************************************/ thisSearch.AS_createList = function(arrSearchHits, arrCurrentSearchWords, sSearchText, bMatchFound) { thisSearch.AS_resetList(); if (arrSearchHits.length > 0) { for (var i = 0; i < arrSearchHits.length; i++) { var elListItem = document.createElement("li"); elListItem.className = "notselected"; var elAnchor = document.createElement("a"); elAnchor.href = "javascript:void(0);"; elAnchor.m_nIndex = i + 1; var sFormatedSearchHit = sSearchText + "<b>" + arrSearchHits[i].substr(sSearchText.length) + "</b>"; // format the search hit if (!bMatchFound) { elAnchor.innerHTML = "<strike>" + sFormatedSearchHit + "</strike>"; } else { elAnchor.innerHTML = sFormatedSearchHit; } elListItem.m_nIndex = i + 1; /*********************************************************************** * * onmouseover - override mouse over to highlight list item * ************************************************************************/ elListItem.onmouseover = function() { thisSearch.AS_navListItem(this.m_nIndex); } /*********************************************************************** * * onmousedown - when clicked, select this item * ************************************************************************/ elAnchor.onmousedown = function() { mc_nSelectedIndex = this.m_nIndex; thisSearch.AS_selectList(this.m_nIndex); return false; } // // Add to the overall list // elListItem.appendChild(elAnchor); mc_elASList.setAttribute("tabindex", "-1"); mc_elASList.appendChild(elListItem); } mc_elASList.style.display = "block"; } else { thisSearch.AS_clearList(); } } /*********************************************************************** * * AS_resetList - Resetting the created auto suggest list * ************************************************************************/ thisSearch.AS_resetList = function() { var elListItem = mc_elASList.getElementsByTagName("li"); var nLen = elListItem.length; for (var i = 0; i < nLen; i++) { mc_elASList.removeChild(elListItem[0]); } } /*********************************************************************** * * AS_navList - Navigation (up/down) of list * * Inputs: dir - direction of navigation * ************************************************************************/ thisSearch.AS_navList = function(dir) { mc_nSelectedIndex += (dir == "down") ? 1 : -1; var elListItem = mc_elASList.getElementsByTagName("li"); if (mc_nSelectedIndex < 1) { mc_nSelectedIndex = elListItem.length; } if (mc_nSelectedIndex > elListItem.length) { mc_nSelectedIndex = 1; } thisSearch.AS_navListItem(mc_nSelectedIndex); } /*********************************************************************** * * AS_navListItem - List navigation and selection * * Inputs: index - list index to select * ************************************************************************/ thisSearch.AS_navListItem = function(index) { mc_nSelectedIndex = index; var elListItem = mc_elASList.getElementsByTagName("li"); for (var i = 0; i < elListItem.length; i++) { elListItem[i].className = (i == (mc_nSelectedIndex - 1)) ? "selected" : "notselected"; } } /*********************************************************************** * * AS_selectList - Selects item from the auto-suggest and clears the list * ************************************************************************/ thisSearch.AS_selectList = function() { var elListItem = mc_elASList.getElementsByTagName("li"); var elAnchor = elListItem[mc_nSelectedIndex - 1].getElementsByTagName("a")[0]; // // Tidy up the selected text // var sSelectedText = elAnchor.innerHTML.replace(/(<strike>(.*)<\/strike>)|(<[^>]+>)/g, ""); var sSearchValue = ''; for (var nSrchIndx = 0; nSrchIndx < mc_arrPreviousSearchWords.length; nSrchIndx++) { if (typeof(mc_mapUnmatchedSearchWords[mc_arrPreviousSearchWords[nSrchIndx]]) !== 'undefined') { continue; } if (mc_arrPreviousSearchWords[nSrchIndx] === mc_sLastSearchText) { sSearchValue += sSelectedText + ' '; // append selected text } else { sSearchValue += mc_arrPreviousSearchWords[nSrchIndx] + ' '; } } thisSearch.value = sSearchValue; thisSearch.AS_clearList(); } /*********************************************************************** * * AS_clearList - Clears the auto-suggest list * ************************************************************************/ thisSearch.AS_clearList = function() { if (mc_elASList) { mc_elASList.style.display = "none"; selectedIndex = 0; } mc_arrPreviousSearchWords.length = 0; } /*********************************************************************** * * AS_getKeyCode - Get the keycode * * Inputs: e - event * * Returns: code - key code * ************************************************************************/ thisSearch.AS_getKeyCode = function(e) { var code; if (!e) // if IE mode { var e = window.event; // use global window.event object } if (e.keyCode) // check again - code there? { code = e.keyCode; // use that } return code; } /*********************************************************************** * * AS_findFromArray - Find the value from the given array * * Inputs: arrInputArray - input array * objToFind - object to find * * Returns: true if found * ************************************************************************/ thisSearch.AS_findFromArray = function(inputArray, textToFind) { for (var i = 0; i < inputArray.length; i++) { if (inputArray[i] == textToFind) { return true; } } return false; } /*********************************************************************** * * AS_setTimer - start AutoSuggest timer * * Inputs: nTime - time in milliseconds * ************************************************************************/ thisSearch.AS_setTimer = function(nTime) { if (!mc_bIsTimerOn) { mc_nTimerID = setTimeout(thisSearch.AS_getListItems, nTime); // start executing the function after 'nTime' ms mc_bIsTimerOn = true; // set the mc_nTimerID } } /*********************************************************************** * * AS_clearTimer - Clear AutoSuggest timer * * Returns: - nothing * ************************************************************************/ thisSearch.AS_clearTimer = function() { if (mc_bIsTimerOn) { clearTimeout(mc_nTimerID); // clear the mc_nTimerID mc_bIsTimerOn = false; // reset the mc_nTimerID } } } } /*********************************************************************** * * AddAutoSuggest - Add autosuggest functionality * * Returns: - nothing * ************************************************************************/ function AddAutoSuggest() { if (IsPreview()) // preview? { return; } if (typeof(pg_sSearchScript) === "undefined" || pg_sSearchScript === '') { // // Update to user // var sErrorMsg = "Variable \"pg_sSearchScript\" undefined OR null, autosuggest may not work"; ShowError(sErrorMsg, g_ErrorCode.UNDEFINED); return; } // // add auto suggest for all form fields named as 'SS' // NOTE: change field name 'SS' appropriately if needed // for (var nIndex = 0; nIndex < document.forms.length; nIndex++) { if (document.forms[nIndex] && document.forms[nIndex].SS) { document.forms[nIndex].SS.setAttribute('autocomplete', 'off'); document.forms[nIndex].SS.setAttribute('onfocus', 'AutoSuggest(this)'); } } } //-------------------------------------------------------------- // // In-place updating of search results // //-------------------------------------------------------------- // // Call functions onready // $(document).ready(function() { AddAutoSuggest(); AddOnFilter(); CheckHashChangeEvent(); }); // // Global variables // var g_eResultLayout = { // result layout type STD: 1, // standard layout TABULAR: 2, // tabular layout UNDEFINED: 3 // layout variable undefined }; var gArrSortedProductRefs = new Array(); // sorted product references alone var gArrResultSet = new Array(); // result set containing decorated product refs var gArrayDefinedPropertiesSorted = new Array(); // sorted defined properties for the current page var gArrProperty = new Array(); // array of properties var gArrFilterGrpIdSorted = new Array(); // array of sorted filter group ids var gMapObjProductDetails = {}; // map product details with ProdRef as key var gMapPropIdDecoratedChoices = {}; // map of property id to decorated choices var gMapInvalidProdRefs = {}; // map of prod refs marked as invalid var gMapInvalidEmptyPermsProdRefs = {}; // map of prod refs with empty permutations marked as invalid var gMapPropNameToPropId = {}; // map of prop name to prop id var gMapFilterGrpIdToFilterGrpName = {}; // map of property id to prop name var gMapParams = {}; // map of url paramters, updated whenever needed var gMapProdRefToDecProdRef = {}; // map of product refs to decorated products refs var g_sSearchResultsTemplate = ''; // search result template var g_sListStartTemplate = ''; // list start template var g_sListRowStartTemplate = ''; // row template var g_sListCellStartTemplate = ''; // cell start template (say <td>) var g_sListCellEndTemplate = ''; // cell end template var g_sListRowEndTemplate = ''; // row end template var g_sListEndTemplate = ''; // list end template var g_sResultLayout = g_eResultLayout.UNDEFINED; // result layout type var g_nListColCount = 0; // no of columns in the result list var gMapAltProdToParentProductRef = {}; // map of alternate product ref to parent product reference var gMapProdToAltProdArray = {}; var gMapMatchedProducts = {}; var g_sDefinedPropertiesPattern; // defined properties pattern var gMapRefStock = {}; // map of product reference to stock var gMapChildToParentProducts = {}; // map of child product to parent // // Initialize the global arrays // gArrSortedProductRefs.length = 0; gArrResultSet.length = 0; // // Globals variables for result pagination // var g_nProductMinIndex = 0; // product minimum index number var g_nProductMaxIndex = 0; // product maximum index number var g_nCurrenPageNumber = 0; // current search result page number var g_nIEVersion = 0; // holds IE version, 0 for any other browser // // Filter timer variables // var g_eFilterTimer = { // enum for filter timer Cache: 1, // filter from cache Server: 2, // filter from server UNDEFINED: 3 // undefined }; var g_hFilterTimer; // filter timer handler var g_bFilterTimerOn = false; // flag to check filter timer // // Filter count variables // var g_bFirstLoad = false; // first time loaded? var g_bCacheStock = true; // cache stock filter var g_bClearAll = false; // clear all? var g_bHasPresetOptions = false; // has preset filter options? // // Filter storage variables // var g_bUseStorageFromClick = false; // use storage when selecting filter options var g_bUseStorageSortPage = false; // use storage when sorting and pagination var g_bSortOrder = ''; // sort order var g_eFilterSettings = { // enum for filter settings FILTER: 1, // filter setting SORTORDER: 2, // sort order setting PAGINATION: 3 // pagination setting }; /*********************************************************************** * * AddOnFilter - Add OnFilter call dynamically * * Returns: - nothing * ************************************************************************/ function AddOnFilter() { if (IsPreview()) // preview? { return; } var filterForm = document.forms['filter']; if (typeof(filterForm) === "undefined") { return; } if (typeof(pg_sSearchScript) === "undefined" || pg_sSearchScript === '') { // Update to user var sErrorMsg = "Variable \"pg_sSearchScript\" undefined OR null, filtering may not work"; ShowError(sErrorMsg, g_ErrorCode.UNDEFINED); return; } g_nIEVersion = GetIEVersion(); // get IE version // // Loop through the form elements and add dynamic filter call for the // required elements alone // Below are the supported elements // - INPUT (Checkbox Or radio button) // - SELECT (Different list controls) // var filterFormElements = document.forms['filter'].elements; // filter form elements for (var nIndex = 0; nIndex < filterFormElements.length; nIndex++) { if (filterFormElements[nIndex].tagName === 'INPUT' && // input element? (filterFormElements[nIndex].type === 'radio' || filterFormElements[nIndex].type === 'checkbox')) { filterFormElements[nIndex].setAttribute('onclick', 'OnFilter(this);'); } else if ((filterFormElements[nIndex].tagName === 'INPUT') && (filterFormElements[nIndex].type === 'submit')) { filterFormElements[nIndex].setAttribute('onclick', 'OnFilter(this, "link", false); return false;'); } } // // Intercept the sorting form controls. // var elSelectSortOrder = GetSelectWithinSortForm('filter_sortorder'); if (elSelectSortOrder) { elSelectSortOrder.setAttribute('onchange', 'OnSort(this);'); // handle sort locally } // // When loaded from a static page there is a duplicate that we have to handle differently // elSelectSortOrder = GetSelectWithinSortForm('filter_sortorder_static'); if (elSelectSortOrder) { elSelectSortOrder.setAttribute('onchange', 'OnSortStatic(this);'); // handle sort locally - using special function that copies the index to other form } // // Get the search result element globally // if (typeof(filterForm) !== "undefined") { var sSearchResultElement = document.getElementById('SearchResults'); if (sSearchResultElement) { g_sSearchResultsTemplate = sSearchResultElement.innerHTML; // get the search result template g_sSearchResultsTemplate = g_sSearchResultsTemplate.replace(/(<actinic:xmltemplate name=\"ImageLine\">((.*?)|(.*?(\n))+.*?)<\/actinic:xmltemplate>)/ig, ''); // // Substitute appropriate tags for product links in result template // g_sSearchResultsTemplate = g_sSearchResultsTemplate.replace(/(<script(\s*)type=\"text\/template\">([^`]*?)<\/script>)/ig, '$3'); // // Replace any custome scripts inlcuded in the template // Example: <script type="text/template"><sd_script language="javascript" type="text/javascript">document.write('Hello');</sd_script></script> // g_sSearchResultsTemplate = g_sSearchResultsTemplate.replace(/(<sd_script)/ig, '<script'); g_sSearchResultsTemplate = g_sSearchResultsTemplate.replace(/(<\/sd_script)/ig, '</script'); } else { // Update to user var sErrorMsg = "Element with id \"SearchResults\" not found in result template, search might not work properly"; ShowError(sErrorMsg, g_ErrorCode.TAG); } g_sResultLayout = GetResultLayoutUsed(); // // Get all tabular template and cache // if (g_sResultLayout === g_eResultLayout.TABULAR) // tabular list used { var sListStartElement = ''; var sListRowStartElement = ''; var sListCellStartElement = ''; var sListCellEndElement = ''; var sListRowEndElement = ''; var sListEndElement = ''; sListStartElement = document.getElementById('S_LISTSTART'); sListRowStartElement = document.getElementById('S_LISTROWSTART'); sListCellStartElement = document.getElementById('S_LISTCELLSTART'); sListCellEndElement = document.getElementById('S_LISTCELLEND'); sListRowEndElement = document.getElementById('S_LISTROWEND'); sListEndElement = document.getElementById('S_LISTEND'); if (sListStartElement) { g_sListStartTemplate = sListStartElement.innerHTML; g_sListStartTemplate = g_sListStartTemplate.replace(/(&lt;)/ig, '<'); g_sListStartTemplate = g_sListStartTemplate.replace(/(&gt;)/ig, '>'); } if (sListRowStartElement) { g_sListRowStartTemplate = sListRowStartElement.innerHTML; g_sListRowStartTemplate = g_sListRowStartTemplate.replace(/(&lt;)/ig, '<'); g_sListRowStartTemplate = g_sListRowStartTemplate.replace(/(&gt;)/ig, '>'); } if (sListCellStartElement) { g_sListCellStartTemplate = sListCellStartElement.innerHTML; g_sListCellStartTemplate = g_sListCellStartTemplate.replace(/(&lt;)/ig, '<'); g_sListCellStartTemplate = g_sListCellStartTemplate.replace(/(&gt;)/ig, '>'); } if (sListCellEndElement) { g_sListCellEndTemplate = sListCellEndElement.innerHTML; g_sListCellEndTemplate = g_sListCellEndTemplate.replace(/(&lt;)/ig, '<'); g_sListCellEndTemplate = g_sListCellEndTemplate.replace(/(&gt;)/ig, '>'); } if (sListRowEndElement) { g_sListRowEndTemplate = sListRowEndElement.innerHTML; g_sListRowEndTemplate = g_sListRowEndTemplate.replace(/(&lt;)/ig, '<'); g_sListRowEndTemplate = g_sListRowEndTemplate.replace(/(&gt;)/ig, '>'); } if (sListEndElement) { g_sListEndTemplate = sListEndElement.innerHTML; g_sListEndTemplate = g_sListEndTemplate.replace(/(&lt;)/ig, '<'); g_sListEndTemplate = g_sListEndTemplate.replace(/(&gt;)/ig, '>'); } } ResetSortOrder(); // reset the sort order } CacheProperties(); // cache the properties defined CacheFilterSections(); // cahce filter sections CacheDefinedPriceBands(); // cache defined price bands CachePriceBandPriceRange(); // cache defined price range CacheDefinedChoices(); // cache defined choices SetDefaultSelection(); // set default selections SortFilterGroup(); // sort filter group g_bHasPresetOptions = HasPresetFilterOptions(); // has preset filter options defined? SetSelectionMapsFromStorage(); // set the selection map from storage settings SetStoredPageNumber(); // set the page number if (IsFilterCountEnabled()) { // // Filter products for count alone // OnFilter(null, null, true); // filter only for count } else { GenerateDynamicFilterOptions(); // generate dynamic filter options if (IsFilterAsDefaultView()) { OnFilter(null, null, true); // filter only for count } else { OnFilter(null, null, false); // filter only for result } } HideModifyStaticControls(); // hide/modify static controls } /*********************************************************************** * * HasFilterStorage - Check if the page has the filter settings * stored * * Returns: - true/false * ************************************************************************/ function HasFilterStorage() { var sStoredFilterSettings = SDStorage.readPage('filterSettings'); if (sStoredFilterSettings === null || sStoredFilterSettings === '') { return false; } return true; } /*********************************************************************** * * IsUseFilterStorage - Check if we can use filter storage settings * * Returns: - true/false * ************************************************************************/ function IsUseFilterStorage() { // // Check if the URL has the hash 'usestorage' // if (window.location.hash.search('usestorage') == -1) { return false; } return true; } /*********************************************************************** * * CacheProperties - Cache defined properties * * Returns: - nothing * ************************************************************************/ function CacheProperties() { for (var nPropIndx = 0; nPropIndx < pg_arrayPropertyName.length; nPropIndx++) { if (typeof(pg_arrayPropertyName[nPropIndx]) !== "undefined") { var sProperty = pg_arrayPropertyName[nPropIndx].replace(/(&#95;)/g, "_"); // replace the encoded character var sPropIdPropName = sProperty.split(':'); var sPropId = sPropIdPropName[0]; var sPropName = sPropIdPropName[1]; var sDataType = sPropId.substr(sPropId.lastIndexOf('_') + 1); var sDecPropName = (sPropName + '_' + sDataType).toUpperCase(); gMapPropNameToPropId[sDecPropName] = sPropId; // property name to property id map gMapFilterGrpIdToFilterGrpName[sPropId] = sDecPropName; // property id to property name map gArrFilterGrpIdSorted.push(sPropId); gArrayDefinedPropertiesSorted.push(sDecPropName); gArrProperty.push(sPropId); // global property array } } InsertSort(gArrayDefinedPropertiesSorted); // sort properties g_sDefinedPropertiesPattern = '-' + gArrayDefinedPropertiesSorted.join('--') + '-'; } /*********************************************************************** * * SortFilterGroup - Sort the filter group * ************************************************************************/ function SortFilterGroup() { InsertSort(gArrFilterGrpIdSorted); } /*********************************************************************** * * GetSelectWithinSortForm - Get select element within a sort form * * Inputs: sFormName - form name * * Returns: - SELECT element, or null if not found * ************************************************************************/ function GetSelectWithinSortForm(sFormName) { var filterSortOrderForm = document.forms[sFormName]; if (typeof(filterSortOrderForm) !== "undefined") { var filterSortOrderFormElements = filterSortOrderForm.elements; if (typeof(filterSortOrderFormElements) !== "undefined") { for (var nIndex = 0; nIndex < filterSortOrderFormElements.length; nIndex++) { if (filterSortOrderFormElements[nIndex].tagName === 'SELECT') // select element? { return filterSortOrderFormElements[nIndex]; } } } } return null; } /*********************************************************************** * * OnFilter - Filtering functionality * * Inputs: element - current element * sControl - control type * bOnload - onload for the first time? * bClearAll - clear all? * * Returns: - nothing * ************************************************************************/ function OnFilter(element, sControl, bOnload, bClearAll) { var sParams = ''; // filtering parameters var filterForm = document.forms['filter']; // to be modified if different filter form is used // // Added new parameter to store up and retrieve filter settings // if (typeof(element) !== "undefined" && element !== null) { AppendUseStorageHash(g_eFilterSettings.FILTER); } if (g_bUseStorageFromClick) { ResetAllStorage(); g_bUseStorageFromClick = false; } ResetSortOrder(); if (typeof(element) !== "undefined" && element !== null) { if (g_nCurrenPageNumber != -1) { SetCurrentPageNumber(0); } } // // Add other default params needed for filtering // if (bOnload) { g_bFirstLoad = true; // loaded } else { g_bFirstLoad = false; } if (bClearAll) // set/unset the clear all functionality { g_bClearAll = true; } else { g_bClearAll = false; } if (!g_bFirstLoad) { ClearCtrlSelectionMap(); // clear control selection map } ClearURLParamCache(); // clear the URL parameter cache ShowLoadingDialog(); // show the loading dialog sParams += 'PAGE=' + 'DynamicFilter' + '&'; // parameter representing dynamic filter // // Handling of clickable links // if ((typeof(element) !== "undefined") && (typeof(sControl) !== "undefined" && sControl === "link") && (!g_bFirstLoad) && (element.id !== 'update_lnk' && element.id !== 'update_btn') // when is not update link or button ) { var sInputId = "hf_" + element.name; var sInputClickableLinkElement = ''; sInputClickableLinkElement = document.getElementById(sInputId); if (sInputClickableLinkElement) { sInputClickableLinkElement.parentNode.removeChild(sInputClickableLinkElement); // remove the input with the name starts with "hf_" } var inputName = ''; if (element.name === 'PR') { inputName = "hf_PR"; } else if (element.name === 'SX') { inputName = "hf_SX"; } else { inputName = "hf_" + element.id; } // // Tweaks for IE as setting of name attribute is not working // var input = ''; if ((g_nIEVersion < 9) && (g_nIEVersion !== 0)) // if IE and version < 9 { input = document.createElement('<input name="' + inputName + '">'); } else { input = document.createElement('input'); input.name = inputName; } input.id = "hf_" + element.name; // add id to hidden parameter if not price band input.type = "hidden"; input.value = element.value; element.parentNode.appendChild(input); // add new input tag for the clicked link // // Edit the clickable links // if (element.parentNode !== null) // NOTE: the parent node must not be modified from layout { var parentLI = GetParent('li', element); EditLabel(parentLI); } } ReadFilterParamsFromPage(); // read filter form page if (IsFilterCountEnabled()) { HideOptionAny(); // hide option before hand } ClearButtonHandler(); // handle clear button if ((IsFilterCountEnabled() || IsFilterAsDefaultView()) && (!g_bFirstLoad)) { ClearFilterTimer(); SetFilterTimer(g_eFilterTimer.Cache); } else { // // Do not send filter request when 'Clear All' button clicked or // accessed directly/indirectly // if ((!g_bFirstLoad) && (g_bClearAll || (GetClearButtonCount() < 1))) // clear all? { HideLoadingDialog(); return; // no operation } if (g_bFirstLoad && g_bCacheStock) { CacheStockFilter(); // cache stockfilter } // // 1. Get all products during onload // 2. Do always send filtering request from server when count OR filter default // is not enabled // sParams += GetURLParam(g_bClearAll); // get url parameter string // // Shop id for host mode // if (IsHostMode()) { sParams += 'SHOP=' + pg_sShopID + '&'; } // // current filtering section ID // if (IsFilterCountEnabled() || IsFilterAsDefaultView()) { sParams += 'SID=' + pg_nCurrentFilterSectionID + '&'; } // // Add default action parameter // if (filterForm.Action) // action name { var fieldValue = filterForm.Action.value; sParams += 'Action' + '=' + fieldValue; } ClearFilterTimer(); SetFilterTimer(g_eFilterTimer.Server, sParams); } } /*********************************************************************** * * ReadFilterParamsFromPage - Read filter parameters from page and cache * * Returns: - nothing * ************************************************************************/ function ReadFilterParamsFromPage() { // // Get other dynamic filter parameters // var filterForm = document.forms['filter']; // to be modified if different filter form is used var filterFormElements = filterForm.elements; // filter form elements for (var nIndex = 0; nIndex < filterFormElements.length; nIndex++) { // // Reset the URL parameters // var sControlId = ''; // control id used var sValue = ''; // control value var sListParams = ''; // list params var bIncludeParam = false; // whether include param? var fieldName = ''; // field name var fieldValue = ''; // field value var bIncludeListBoxParams = false; // whether include list param? // // Select appropriate filtering elements and enable them for // filtering // if ((filterFormElements[nIndex].tagName === 'INPUT') && // input element? ((filterFormElements[nIndex].type === 'checkbox') || (filterFormElements[nIndex].type === 'radio')) // checkbox or radio button ) { if (filterFormElements[nIndex].checked === true) // is checked? { fieldName = filterFormElements[nIndex].name; fieldValue = filterFormElements[nIndex].value; if (fieldName === 'SX') { sControlId = fieldValue; } else { sControlId = filterFormElements[nIndex].id; sValue = filterFormElements[nIndex].value; } bIncludeParam = true; } else { bIncludeParam = false; } } else if ((filterFormElements[nIndex].tagName === 'INPUT') && // input element? ((filterFormElements[nIndex].type === 'hidden') && // hidden parameter (filterFormElements[nIndex].name !== "PAGE") && // PAGE parameter will not be added (filterFormElements[nIndex].name !== "FILTERPAGE") && // FILTERPAGE parameter will not be added (filterFormElements[nIndex].name !== "ACTINIC_REFERRER") && // ACTINIC_REFERRER parameter will not be added (filterFormElements[nIndex].name !== "Action") && // Action parameter will not be added (filterFormElements[nIndex].name.match(/hf_/g) === null)) // hidden parameter for clickable link ) { fieldName = filterFormElements[nIndex].name; fieldValue = filterFormElements[nIndex].value; bIncludeParam = true; } else if (filterFormElements[nIndex].tagName === 'SELECT') // select element? { var currentElement = filterFormElements[nIndex]; sListParams = GetSelections(currentElement); // get the selected item bIncludeParam = false; bIncludeListBoxParams = true; // include list parameters } else if ((filterFormElements[nIndex].tagName === 'INPUT') && (filterFormElements[nIndex].type === 'hidden')) { if (filterFormElements[nIndex].name.substr(0, 3) === 'hf_') // tweaks for IE { var tmpFieldName = filterFormElements[nIndex].name.substr(3, filterFormElements[nIndex].name.length); fieldName = tmpFieldName.split('-')[0]; fieldValue = filterFormElements[nIndex].value; if (fieldName === "PR" || fieldName === "SX") { sControlId = fieldValue; // add control id } else { sControlId = tmpFieldName; // add control id sValue = fieldValue; // add the field value } bIncludeParam = true; } } else { bIncludeParam = false; } // // Construct the required parameters // if (bIncludeParam) { var tmpFieldValue = encodeURIComponent(fieldValue).replace(/!|'|\(|\)|\*|%20|%C2/g, function(x) { return { "!": "%21", "'": "%27", "(": "%28", ")": "%29", "*": "%2A", "%20": "+", "%C2": "" }[x]; }); if (!g_bFirstLoad) { GetControlSelections(fieldName, sControlId, sValue); // fill the control selection map } CacheURLParams(fieldName, tmpFieldValue); } } } /*********************************************************************** * * ClearButtonHandler - Clear button handler * * Returns: - nothing * ************************************************************************/ function ClearButtonHandler() { for (var sFilterGroup in gMapFilters) // for each filter group { var bShow = IsShowClearButton(sFilterGroup); // check if clear to show ShowHideClearButton(bShow, sFilterGroup); // show/hide clear button } } /*********************************************************************** * * SetFilterTimer - Set filter timer * * Inputs: eFilterTimer - enum for filter timer * sParams - url parameters * * Returns: - nothing * ************************************************************************/ function SetFilterTimer(eFilterTimer, sParams) { if (!g_bFilterTimerOn) { g_hFilterTimer = setTimeout( function() { if (eFilterTimer === g_eFilterTimer.Cache) { FilterProductsFromCache(); // filter within cached data } else if (eFilterTimer === g_eFilterTimer.Server) { FilterProductsFromServer(sParams); // filter from server } }, 25 // need for browser to update UI ); g_bFilterTimerOn = true; // set the timer flag } } /*********************************************************************** * * ClearFilterTimer - Reset filter timer * * Returns: - nothing * ************************************************************************/ function ClearFilterTimer() { if (g_bFilterTimerOn) { clearTimeout(g_hFilterTimer); // clear the g_hFilterTimer g_bFilterTimerOn = false; // reset the timer flag } } /*********************************************************************** * * FilterProductsFromServer - Filter products by sending the Ajax request * * Inputs: sParams - URL paramters * * Returns: - nothing * ************************************************************************/ function FilterProductsFromServer(sParams) { if ((typeof(pg_bFilteringCacheEnabled) !== "undefined") && (pg_bFilteringCacheEnabled !== 0) && (IsFilterCountEnabled() || IsFilterAsDefaultView())) { var xmlHttpClient = new XMLHttpRequest(); var sCacheFileName = "AjaxProductList_" + pg_nUploadReferenceNumber + "_" + pg_nCurrentFilterSectionID + ".js" try { xmlHttpClient.open("GET", GetFilterCacheURL(sCacheFileName), false); xmlHttpClient.send(); if ((xmlHttpClient.status === 200) || (xmlHttpClient.status === 304)) { var arrayJSONResponse = {}; try { arrayJSONResponse = xmlHttpClient.responseText.parseJSON(); } catch (e) { GetProductListFromServer(sParams); return; } if (arrayJSONResponse.ProductSearchResults.ResultCount != 0) // match found { gArrResultSet.length = 0; gArrResultSet = arrayJSONResponse.ProductSearchResults.ResultSet; var sSortOrder = GetSortOrder(); // get the sort order DoSort(sSortOrder, gArrResultSet); // sort product references RetrieveProductDetails(g_nCurrenPageNumber, true); // get product details } else // no match found { if (!g_bFirstLoad || IsFilterAsDefaultView()) { FormatResultHTML(false, null, null, false); // format the result } } HideLoadingDialog(); return; } } catch (e) {} } GetProductListFromServer(sParams); } /*********************************************************************** * * GetProductListFromServer - retrieves the product list thru AJAX call * * Input: sParams - URL paramters * * Returns: - nothing * ************************************************************************/ function GetProductListFromServer(sParams) { // // Send Ajax request // NOTE: make sure the variable 'pg_sSearchScript' is declared in the HTML // var sUrl = pg_sSearchScript; var ajaxRequest = new ajaxObject(sUrl); ajaxRequest.callback = function(responseText) { if (responseText === '') { return; } var arrayJSONResponse = {}; try { arrayJSONResponse = responseText.parseJSON(); } catch (e) { ShowJSONError(e); // show json error return; } if (arrayJSONResponse.ProductSearchResults.ResultCount != 0) // match found { gArrResultSet.length = 0; gArrResultSet = arrayJSONResponse.ProductSearchResults.ResultSet; var sSortOrder = GetSortOrder(); // get the sort order DoSort(sSortOrder, gArrResultSet); // sort product references RetrieveProductDetails(g_nCurrenPageNumber, true); // get product details } else // no match found { if (!g_bFirstLoad || IsFilterAsDefaultView()) { FormatResultHTML(false, null, null, false); // format the result } HideLoadingDialog(); } }; ajaxRequest.update(sParams, "GET"); // send the ajax request } /*********************************************************************** * * FilterProductsFromCache - Filter products from cached product details * * Returns: - nothing * ************************************************************************/ function FilterProductsFromCache() { if (GetClearButtonCount() < 1) // no clear button? { ClearCtrlSelectionMap(); // clear control selections g_bClearAll = true; // See if clear all is called indirectly from selecting/de-selecting an option } else { g_bClearAll = false; } if (g_bClearAll && (!IsFilterAsDefaultView())) // clear all? { UpdateFilterCount(); // calculate only count HideLoadingDialog(); return; } var sFilterPattern = ''; if (!g_bClearAll) // not clear all? { sFilterPattern = GetFilterPatternForResult(); // get filter pattern for result } gArrResultSet.length = 0; var arrFilteredProds = GetFilteredProducts(sFilterPattern); // get the filtered prods gArrResultSet = GetDecoratedProdRefs(arrFilteredProds); var sSortOrder = GetSortOrder(); // get the sort order DoSort(sSortOrder, gArrResultSet); // sort product references RetrieveProductDetails(g_nCurrenPageNumber, true); // show the result } /*********************************************************************** * * GetDecoratedProdRefs - Get the decorated prod refs for given array * of prod refs * * Inputs: arrProdRefs - array of prod refs * * Returns: - array of decorated prod refs * ************************************************************************/ function GetDecoratedProdRefs(arrProdRefs) { var arrDecProds = new Array(); for (var nProdIndx = 0; nProdIndx < arrProdRefs.length; nProdIndx++) { var sProdRef = arrProdRefs[nProdIndx]; if (typeof(gMapProdRefToDecProdRef[sProdRef]) !== 'undefined') { arrDecProds.push(gMapProdRefToDecProdRef[sProdRef]); } } return arrDecProds; } /*********************************************************************** * * GetFilterPatternForResult - Format the pattern for filter result * * Returns: - filter pattern * ************************************************************************/ function GetFilterPatternForResult() { // // Get the filter selections in regular expression // var mapPropIdToFilterSelections = {}; // map of property controlid to selections var sPattern = ''; for (var sFilterGroup in gMapFilterGrpIdToFilterGrpName) { // // Format the filter selection regular expression by considering all the filter // options // if (typeof(gMapControlToSelection[sFilterGroup]) !== 'undefined') { var mapFilterGroup = gMapControlToSelection[sFilterGroup]; var arrChoices = new Array(); var sChoices = ''; if (sFilterGroup === 'PR') // price group? { for (var sFilterCtrlId in mapFilterGroup) { var sChoice = sFilterGroup + '_' + sFilterCtrlId; arrChoices.push(sChoice); } } else if (sFilterGroup === 'SX') // section group? { // // Get the sub section details as well // var mapSecs = {}; for (var sFilterCtrlId in mapFilterGroup) { mapSecs[sFilterCtrlId] = ''; var arrSubSecIDs = gMapFilters['SX'][sFilterCtrlId].m_arrSubSectionIds; for (var nSecIdx = 0; nSecIdx < arrSubSecIDs.length; nSecIdx++) { if (GetArrayIndex(gArraySectionIDs, arrSubSecIDs[nSecIdx]) !== -1) // if sub section included { mapSecs[arrSubSecIDs[nSecIdx]] = ''; } } } for (var sSecId in mapSecs) { var sChoice = sFilterGroup + '_' + sSecId; arrChoices.push(sChoice); } } else // other filter groups { for (var sFilterChoiceCtrlId in mapFilterGroup) { if (typeof(gMapControlIdChoiceName[sFilterChoiceCtrlId]) !== 'undefined') { var sChoice = sFilterGroup + ':' + gMapControlIdChoiceName[sFilterChoiceCtrlId]; arrChoices.push(sChoice); } } } // // Format the regular expression // if (arrChoices.length > 0) { mapPropIdToFilterSelections[sFilterGroup] = '(\\!' + arrChoices.join('\\!|\\!') + '\\!)'; } } } for (var nFltrIdx = 0; nFltrIdx < gArrFilterGrpIdSorted.length; nFltrIdx++) { var sFltrGrpId = gArrFilterGrpIdSorted[nFltrIdx]; if (typeof(mapPropIdToFilterSelections[sFltrGrpId]) !== 'undefined') { if (sPattern.length > 0) { sPattern += '.*' } sPattern += mapPropIdToFilterSelections[sFltrGrpId]; } } return sPattern; } /*********************************************************************** * * CacheURLParams - Cache URL parameter * * Inputs: sParamName - paramter name * sParamValue - paramter value * * Returns: - nothing * ************************************************************************/ function CacheURLParams(sParamName, sParamValue) { // // Cache URL parameters into gMapParams // if (typeof(gMapParams[sParamName]) !== 'undefined') { gMapParams[sParamName].push(sParamValue); } else { gMapParams[sParamName] = new Array(); gMapParams[sParamName].push(sParamValue); } } /*********************************************************************** * * ClearURLParamCache - Clear URL parameter cache * * Returns: - nothing * ************************************************************************/ function ClearURLParamCache() { for (var sParam in gMapParams) { gMapParams[sParam] = new Array(); } } /*********************************************************************** * * GetURLParam - Get URL parameter string * * Inputs: bUseDefault - use default paramters * * Returns: - parameter string * ************************************************************************/ function GetURLParam(bUseDefault) { var sParam = ''; var bGetAllProds = false; if (bUseDefault) // use default options? { UpdateDefaultParams(); } // // Reset the parameters to get all products // if ((IsFilterAsDefaultView() || IsFilterCountEnabled()) && g_bFirstLoad) { for (var sPropId in gMapDefCtrlSelections) { if (typeof(gMapParams[sPropId]) !== 'undefined') // reset for choices { gMapParams[sPropId] = new Array(); gMapParams[sPropId].push(''); } } if (typeof(gMapParams['PR']) !== 'undefined') // reset for price band { gMapParams['PR'] = new Array(); gMapParams['PR'].push('-1'); } if (typeof(gMapParams['SX']) !== 'undefined') // rest for section { gMapParams['SX'] = new Array(); gMapParams['SX'].push('-1'); } } // // Create parameter string for each parameter // for (var sParamName in gMapParams) { var arrParamVal = gMapParams[sParamName]; var nLength = arrParamVal.length; if (nLength == 0) // use default when no options selected { var sParamValue = ''; if (sParamName === 'PR' || sParamName === 'SX') { sParamValue = '-1'; } sParam += sParamName + '=' + sParamValue + '&'; continue; } for (var nParamIdx = 0; nParamIdx < nLength; nParamIdx++) // create the parameter string { var sParamValue = arrParamVal[nParamIdx]; sParam += sParamName + '=' + sParamValue + '&'; } } return sParam; } /*********************************************************************** * * UpdateDefaultParams - Update default parameters * * Returns: - nothing * ************************************************************************/ function UpdateDefaultParams() { var sParams = ''; // // Update the default filter options in 'gMapParams' // for (var sSelection in gMapDefCtrlSelections) { var sKey = sSelection + '-' + gMapDefCtrlSelections[sSelection]; var sChoice = ''; if (typeof(gMapControlIdChoiceName[sKey]) !== 'undefined') { sChoice = gMapControlIdChoiceName[sKey]; } var sTmpChoice = encodeURIComponent(sChoice).replace(/!|'|\(|\)|\*|%20|%C2/g, function(x) { return { "!": "%21", "'": "%27", "(": "%28", ")": "%29", "*": "%2A", "%20": "+", "%C2": "" }[x]; }); if (typeof(gMapParams[sSelection]) !== 'undefined') // update for choices { gMapParams[sSelection] = new Array(); gMapParams[sSelection].push(sTmpChoice); } } if (typeof(gMapParams['PR']) !== 'undefined') // update for price band { gMapParams['PR'] = new Array(); gMapParams['PR'].push('-1'); } if (typeof(gMapParams['SX']) !== 'undefined') // update for section { gMapParams['SX'] = new Array(); gMapParams['SX'].push('-1'); } } /*********************************************************************** * * GetSelections - Get selected item from list box * * Inputs: elements - current select elements * * Returns: - selected parameters * ************************************************************************/ function GetSelections(elements) { var sParam = ''; var sControlId = ''; var sValue = ''; for (var nElmCount = 0; nElmCount < elements.options.length; nElmCount++) { // // Format needed parameters // if (elements.options[nElmCount].selected === true) { var sParamName = elements.name; var sParamValue = encodeURIComponent(elements.options[nElmCount].value); sParam += sParamName + '=' + sParamValue + '&'; if (sParamName === "PR" || sParamName === "SX") { sControlId = elements.options[nElmCount].value; } else { sControlId = elements.options[nElmCount].id; sValue = elements.options[nElmCount].value;; } // // Remember the selections // if (!g_bFirstLoad) { GetControlSelections(sParamName, sControlId, sValue); } CacheURLParams(sParamName, sParamValue); } } return sParam; } /*********************************************************************** * * ValidateMultipleListBox - Validate list box * * Inputs: elements - current select elements * * Returns: - nothing * ************************************************************************/ function ValidateMultipleListBox(elements) { var nSelectedCount = 0; for (var nElmCount = 0; nElmCount < elements.options.length; nElmCount++) { if (elements.options[nElmCount].selected === true) { nSelectedCount++; } } } /*********************************************************************** * * DoSort - Sort the result set of product references * * Inputs: sSort - sort order * arrSearchResults - result set of product references array * * Returns: - nothing * ************************************************************************/ function DoSort(sSort, arrSearchResults) { // // Stuff which has to be passed in from somewhere // Note: Make sure 'pg_sSortOrdersPrependedToProdRefs' defined in the html file // var sSortOrdersPrependedToReferences = pg_sSortOrdersPrependedToProdRefs; // which sort orders are prepended to product references, in this order // // Split the sort order from the keys, then sort by that. // The product references as keys of rhashResults are constructed as <sort order 1><sort order 2>...<sort order n><product ref> // The sort orders are specially encoded into strings that retain order when compared as strings. // This means they don't have to be decoded for sorting, and also are more compact. // // The values in rhashResults are the relevance scores for each product reference given the search words. // These may be 0 if relevance information is not stored or if not searching for words but just filtering. // var arrSort = sSort.split('_'); // separate the various sort params in the list arrSort.push("0", "0", "0", "0"); // make array long enough and ensure that we finish with product reference for (var nIndex = 0; nIndex < arrSort.length; nIndex++) { arrSort[nIndex] = parseInt(arrSort[nIndex]); } var arrSortOrders = sSortOrdersPrependedToReferences.split(","); // get list of sort orders prepended to product reference for (var nIndex = 0; nIndex < arrSortOrders.length; nIndex++) { arrSortOrders[nIndex] = parseInt(arrSortOrders[nIndex]); } // // Translates sort order to whether to sort ascending or not. // Extend with new sort orders when defined. // 1 indicates ascending, -1 indicates descending // var mapSortAsc = { 0: 1, // product reference - eSortProdRef 1: -1, // Relevance - eSortRelevance 2: 1, // price ascending - eSortPriceAsc 3: -1, // price descending - eSortPriceDesc 4: 1, // name ascending - eSortNameAsc 5: -1, // name descending - eSortNameDesc 6: 1, // recommended - eSortRecommended 7: -1, // new products - eSortNewProducts 8: -1, // best sellers - eSortBestSellers 9: -1 // feedback rating - eSortCustomerFeedback }; // // Translates given sort order to actual order stored with the product reference. // Extend with new sort orders when defined. // var mapSortBaseOrder = { 0: 0, // product reference - eSortProdRef 1: 1, // Relevance - eSortRelevance 2: 2, // price ascending - eSortPriceAsc 3: 2, // price descending - eSortPriceDesc 4: 4, // name ascending - eSortNameAsc 5: 4, // name descending - eSortNameDesc 6: 6, // recommended - eSortRecommended 7: 7, // new products - eSortNewProducts 8: 8, // best sellers - eSortBestSellers 9: 9 // feedback rating - eSortCustomerFeedback }; // // Extract the sort orders. Use a regular expression constructed dynamically. // var nSortOrderCount = arrSortOrders.length; // get number of sort orders defined var sPattern = "^"; // start matching at start of decorated reference sPattern += "([0-9]*)\:"; // first match is relevance, purely numerical followed by colon // // Form the pattern to match a sort order - either 2, 4 or 5 characters long // depending on lead-in char // sPattern += "([i|v])"; // valid/invalid prod ref notation for (var nCount = 0; nCount < nSortOrderCount; nCount++) { sPattern += "([0-9A-Za-z\?\_]{2}|\{[0-9A-Za-z\?\_]{3}|\}[0-9A-Za-z\?\_]{4})"; } sPattern += "(.*)$"; // last match item is product reference, finish at end of decorated reference var regPattern = new RegExp(sPattern); // // Split the sorting information and product refs // var mapProdRefToSortOrders = {}; // maps product reference to an array of sort orders; last two items are product reference and relevance gArrSortedProductRefs.length = 0; // sorted product references for (var nIndex = 0; nIndex < arrSearchResults.length; nIndex++) // iterate search results array { var arrMatches = arrSearchResults[nIndex].match(regPattern); if (arrMatches) // got a match? { var sProductRef = arrMatches[nSortOrderCount + 3]; // ref is last group in regular expression var arrProductRefs = sProductRef.split(':'); if (arrProductRefs.length == 2) { sProductRef = arrProductRefs[0]; gMapAltProdToParentProductRef[sProductRef] = arrProductRefs[1]; } gArrSortedProductRefs[nIndex] = sProductRef; // get list of product references arrMatches[1] = String("0000000000" + arrMatches[1]).substr(-10, 10); // relevance is numeric so ensure that it sorts correctly by prepending leading zeros and limiting size mapProdRefToSortOrders[sProductRef] = arrMatches; // map product reference to all the matches if (arrMatches[2] === 'i') // get the validity of the product { gMapInvalidProdRefs[sProductRef] = ''; // cache it in a global map } if (((IsFilterCountEnabled() || IsFilterAsDefaultView()) && g_bFirstLoad) || (!IsFilterCountEnabled())) { gMapProdRefToDecProdRef[sProductRef] = arrSearchResults[nIndex]; // cache map of prod refs to decorated prod refs } } else { // severe problem, give error message var sErrorMsg = "Logical error occurred during sorting"; ShowError(sErrorMsg, g_ErrorCode.LOGIC); } } // // We need to translate the requested sort order into a list of indexes of the sort // orders to apply. We use mapSortOrderIndex as a helper array mapping requested sort to // position in the arrays stored in mapProdRefToSortOrders // var mapSortOrderIndex = {}; for (var nOrderIndex = 0; nOrderIndex < nSortOrderCount; nOrderIndex++) { // // First element in match result is matched string; second element is relevance therefore have to add 2 to get decorated sort orders // mapSortOrderIndex[arrSortOrders[nOrderIndex]] = nOrderIndex + 3; } mapSortOrderIndex[0] = nSortOrderCount + 3; // index of product reference (sort order 0) in match array mapSortOrderIndex[1] = 1; // index of relevance (sort order 1) in match array // // Now get vars indicating sort order and index for each sort order requested // If there is ever more than a primary, secondary and tertiary sort then additional variables and compares are required. // var arrAsc = new Array( mapSortAsc[arrSort[0]], // indicates if first sortable item is ascending or not mapSortAsc[arrSort[1]], // etc. mapSortAsc[arrSort[2]], mapSortAsc[arrSort[3]]); var arrOrderIndex = new Array( mapSortOrderIndex[mapSortBaseOrder[arrSort[0]]], // index of first requested sort order in array stored against product reference mapSortOrderIndex[mapSortBaseOrder[arrSort[1]]], // etc. mapSortOrderIndex[mapSortBaseOrder[arrSort[2]]], mapSortOrderIndex[mapSortBaseOrder[arrSort[3]]]); // // Do the sort. Use the array of items at each index, selecting appropriate one each time. // gArrSortedProductRefs.sort(function(sRefA, sRefB) { var sFirst; var sSecond; for (var nSortIndex = 0; nSortIndex < 4; nSortIndex++) { sFirst = mapProdRefToSortOrders[sRefA][arrOrderIndex[nSortIndex]]; sSecond = mapProdRefToSortOrders[sRefB][arrOrderIndex[nSortIndex]]; // // Compare the values. Note that localeCompare can't be used as it gives // strange results with characters outside of 0..9A..Za..z with IE and FF. // if (sFirst < sSecond) { return (-1 * arrAsc[nSortIndex]); // invert sort result if arrAsc contains -1 } else if (sFirst > sSecond) { return (arrAsc[nSortIndex]); } } return (0); }); }; /*********************************************************************** * * RetrieveProductDetails - Get product details for the given * Product References * * Inputs: nPageNumber - page number * bFilterPropertyChanged - whether filter property changed * * Returns: - nothing * ************************************************************************/ function RetrieveProductDetails(nPageNumber, bFilterPropertyChanged) { var bRetrieveProdDetails = false; // flag to indicate need for product details request var bCacheDetailsOnServer = false; // flag to indicate if the server should cache the request for product details // // Format DPR parameter from the product references // ShowLoadingDialog(); // show loading dialog if not already shown SetCurrentPageNumber(nPageNumber); // set the current page number StoreSettings(); // store filter settings var arrNonCachedProdRefs = GetProdRefsOfNonCachedProductDetails(gArrSortedProductRefs); // get non cached product references if (arrNonCachedProdRefs.length > 0) { bRetrieveProdDetails = true; // retrieve product details } bCacheDetailsOnServer = (arrNonCachedProdRefs.length === gArrSortedProductRefs.length); var bNeedFilter = false; if (bFilterPropertyChanged || bRetrieveProdDetails) { bNeedFilter = true; // need filtering and count update? } // // Ajax call to get product details // if (bRetrieveProdDetails) // retrieve product details? { if ((typeof(pg_bFilteringCacheEnabled) !== "undefined") && (pg_bFilteringCacheEnabled !== 0) && (IsFilterCountEnabled() || IsFilterAsDefaultView())) { var xmlHttpClient = new XMLHttpRequest(); var sCacheFileName = "AjaxProductDetails_" + pg_nUploadReferenceNumber + "_" + pg_nCurrentFilterSectionID + ".js"; xmlHttpClient.open("GET", GetFilterCacheURL(sCacheFileName), false); xmlHttpClient.send(); if ((xmlHttpClient.status === 200) || (xmlHttpClient.status === 304)) { var arrayJSONResponse = {}; try { arrayJSONResponse = xmlHttpClient.responseText.parseJSON(); if (arrayJSONResponse.ProductDetails.ProductInfoCount == 0 || // empty product details in ajax file arrayJSONResponse.ProductDetails.ProductInfoCount !== arrNonCachedProdRefs.length) // different number of products in product details file { UpdateProductDetailsFromServer(arrNonCachedProdRefs, bCacheDetailsOnServer, bNeedFilter); // call the script directly to re-cache it return; } } catch (e) { UpdateProductDetailsFromServer(arrNonCachedProdRefs, bCacheDetailsOnServer, bNeedFilter); return; } UpdateProductDetails(arrayJSONResponse, bNeedFilter); } else { UpdateProductDetailsFromServer(arrNonCachedProdRefs, bCacheDetailsOnServer, bNeedFilter); } } else { UpdateProductDetailsFromServer(arrNonCachedProdRefs, bCacheDetailsOnServer, bNeedFilter); } } else { // // Check if the product references are not empty // if (gArrSortedProductRefs.length !== 0) { var bFilterDefView = IsFilterAsDefaultView(); var bFilterStorage = HasFilterStorage(); if (!g_bFirstLoad || bFilterDefView || bFilterStorage) { if ((bFilterDefView || IsFilterCountEnabled()) && bFilterPropertyChanged) { var sFilterPattern = GetFilterPatternForResult(); // get filter pattern for result gArrResultSet.length = 0; var arrFilteredProds = GetFilteredProducts(sFilterPattern); // get the filtered prods gArrResultSet = GetDecoratedProdRefs(arrFilteredProds); var sSortOrder = GetSortOrder(); // get the sort order DoSort(sSortOrder, gArrResultSet); // sort product references } FormatResultHTML(true, gArrSortedProductRefs, nPageNumber, bNeedFilter); // display result from the cached product details } else { UpdateFilterCount(); } } else { if (!g_bFirstLoad || IsFilterAsDefaultView()) { FormatResultHTML(true, null, null, bNeedFilter); // display no result } } } } /*********************************************************************** * * UpdateProductDetailsFromServer - updates the product details by AJAX call * * Input: arrNonCachedProdRefs - array of non-cached product references * bEnableAJAXCallCache - flag to enable AJAX call caching * bNeedFilter - whether filtering and count update needed? * * Returns: - nothing * ************************************************************************/ function UpdateProductDetailsFromServer(arrNonCachedProdRefs, bEnableAJAXCallCache, bNeedFilter) { var sParamPrdDetails = ''; for (var nIndex = 0; nIndex < arrNonCachedProdRefs.length; nIndex++) { if (typeof(arrNonCachedProdRefs[nIndex]) !== "undefined") { sParamPrdDetails += arrNonCachedProdRefs[nIndex]; if (nIndex + 1 < arrNonCachedProdRefs.length) { sParamPrdDetails += '_'; } } } var sUrl = pg_sSearchScript; var arrayJSONResponse = {}; var ajaxRequest = new ajaxObject(sUrl); ajaxRequest.callback = function(responseText) { if (responseText === '') { return; } var arrayJSONResponse = {}; try { arrayJSONResponse = responseText.parseJSON(); } catch (e) { ShowJSONError(e); // show json error return; } UpdateProductDetails(arrayJSONResponse, bNeedFilter); }; // // Construct parameter to fetch product details // sParamPrdDetails = 'PAGE=' + 'DynamicFilter&' + 'DPR=' + sParamPrdDetails; // // Fetch sub section details only once at the first load // if (IsSearchBySubSection() && g_bFirstLoad) // subsection search enabled? { var sSIDs = ''; for (var nSXIndx = 0; nSXIndx < gArraySectionIDs.length; nSXIndx++) { sSIDs += gArraySectionIDs[nSXIndx]; if (nSXIndx + 1 < gArraySectionIDs.length) { sSIDs += '_'; } } if (sSIDs !== '') { sParamPrdDetails += '&SIDS=' + sSIDs; } } if (bEnableAJAXCallCache) { sParamPrdDetails += '&SID=' + pg_nCurrentFilterSectionID; } // // Shop id for host mode // if (IsHostMode()) { sParamPrdDetails += '&SHOP=' + pg_sShopID; } ajaxRequest.update(sParamPrdDetails, "POST"); } /*********************************************************************** * * ShowJSONError - Show JSON error * * Inputs: oExp - exception * * Returns: - nothing * ************************************************************************/ function ShowJSONError(oExp) { if (typeof(oExp) !== 'undefined') { if (oExp.length > 500) { oExp = oExp.substring(0, 500) + '...'; } } var sError = 'The filter operation returned a script error. Please try again, and \ contact us if the error persists. The error was: \n\n[' + oExp + ']'; alert(sError); } /*********************************************************************** * * UpdateProductDetails - Updates product details in the page * * Inputs: arrayJSONResponse - array of JSON response * bNeedFilter - whether filtering and count update needed? * * Returns: - nothing * ************************************************************************/ function UpdateProductDetails(arrayJSONResponse, bNeedFilter) { var nProductCount = arrayJSONResponse.ProductDetails.ProductInfoCount; if (typeof(arrayJSONResponse.SectionDetails) !== 'undefined' && arrayJSONResponse.SectionDetails.SectionInfoCount != 0) // section details found { CacheSectionDetails(arrayJSONResponse.SectionDetails.SectionInfoSet); // cache section details } if (nProductCount != 0) // product details found { var arrProductDetailsSet = new Array(); arrProductDetailsSet = arrayJSONResponse.ProductDetails.ProductInfoSet; CacheProductDetails(arrProductDetailsSet); // cache product details CacheProductDetailsWithFullPermutation(bNeedFilter); } } /*********************************************************************** * * UpdateProductDetailsHelper - Updates product details helper function * * Inputs: bNeedFilter - whether filtering and count update needed? * * Returns: - nothing * ************************************************************************/ function UpdateProductDetailsHelper(bNeedFilter) { // // Calcultae count & remove filter options with zero count when filter options has preset values // var bFilterStorage = HasFilterStorage(); if (g_bFirstLoad && IsFilterCountEnabled() && (g_bHasPresetOptions || bFilterStorage)) // has preset value { CalculateCount(true); // calculate count RemoveFilterWithZeroCount(); // remove filter options with zero count ClearFilterCounts(); // clear off the filter options counts } var bFilterDefView = IsFilterAsDefaultView(); if (!g_bFirstLoad || bFilterDefView || bFilterStorage) { if (bFilterDefView || IsFilterCountEnabled()) { var sFilterPattern = GetFilterPatternForResult(); // get filter pattern for result gArrResultSet.length = 0; var arrFilteredProds = GetFilteredProducts(sFilterPattern); // get the filtered prods gArrResultSet = GetDecoratedProdRefs(arrFilteredProds); var sSortOrder = GetSortOrder(); // get the sort order DoSort(sSortOrder, gArrResultSet); // sort product references } FormatResultHTML(true, gArrSortedProductRefs, g_nCurrenPageNumber, bNeedFilter); // format the result } else { // // Update filter count // UpdateFilterCount(); HideLoadingDialog(); } } /*********************************************************************** * * CacheProductDetailsWithFullPermutation - Downloads and cache the full permutation * * Inputs: bNeedFilter - whether filtering and count update needed? * * Returns: - nothing * ************************************************************************/ function CacheProductDetailsWithFullPermutation(bNeedFilter) { // // NOTE: Check variable gArrSortedProductRefs and associated logic changes // var sProdRefParam = GetProdRefForFullPermutation(); if (sProdRefParam == '') { UpdateProductDetailsHelper(bNeedFilter); return; } // // Get full permutation list // Sample Url: http://localhost/cgi-bin/ss000013.pl?ACTION=FULLPERMLIST&PRODREF=3_4_5 // var arrProductToFullPermutation = new Array(); var sUrl = pg_sSearchScript; var ajaxRequest = new ajaxObject(sUrl); ajaxRequest.callback = function(responseText) { if (responseText === '') { UpdateProductDetailsHelper(bNeedFilter); return; } UpdateProductDetailsWithFullPermutation(responseText); UpdateProductDetailsHelper(bNeedFilter); }; sParams = 'ACTION=FULLPERMLIST&PRODREF=' + sProdRefParam; ajaxRequest.update(sParams, "GET", false); // send the ajax request } /*********************************************************************** * * SetSelectionMapsFromStorage - Set the selection map from filter * storage settings * * Returns: - nothing * ************************************************************************/ function SetSelectionMapsFromStorage() { if (!HasFilterStorage()) { return; } var sStoredFilterSettings = SDStorage.readPage('filterSettings'); ClearCtrlSelectionMap(); // clear control selection maps // // Fill up the control selection maps // arrSettings = sStoredFilterSettings.split(','); for (var nIdx = 0; nIdx < arrSettings.length; nIdx++) { var arrGrpControl = arrSettings[nIdx].split(':'); var sCtlrName = arrGrpControl[0]; var sContolID = arrGrpControl[1]; if (typeof(gMapControlToSelection[sCtlrName]) === 'undefined') { gMapControlToSelection[sCtlrName] = {}; gMapControlToSelection[sCtlrName][sContolID] = ''; } else { gMapControlToSelection[sCtlrName][sContolID] = ''; } if (sCtlrName === 'PR' || sCtlrName === 'SX') { gMapCtrlSelections[arrSettings[nIdx]] = true; } else { gMapCtrlSelections[sContolID] = true; } // // Fill the maps of 'Property Id to Selected Choice Ids' and // 'Property Ids to array of selections (decorated)' // if (typeof(gMapFilterGrpIdToFilterGrpName[sCtlrName]) !== 'undefined' && typeof(gMapControlIdChoiceName[sContolID]) !== 'undefined') { var sPropCtrlSelection = (gMapFilterGrpIdToFilterGrpName[sCtlrName] + ':' + gMapControlIdChoiceName[sContolID]).toUpperCase(); gMapPropCtrlSelections[sPropCtrlSelection] = true; if (typeof(gMapPropIdToSelections[sCtlrName]) === 'undefined') { gMapPropIdToSelections[sCtlrName] = new Array() // property id to selections } if (GetArrayIndex(gMapPropIdToSelections[sCtlrName], sPropCtrlSelection) == -1) { gMapPropIdToSelections[sCtlrName].push(sPropCtrlSelection); if (gMapPropIdToSelections[sCtlrName].length > 0) { InsertSort(gMapPropIdToSelections[sCtlrName]); } } } } } /*********************************************************************** * * HasPresetFilterOptions - Checks if the filter properties has * preset options * * Returns: - true/false * ************************************************************************/ function HasPresetFilterOptions() { var bPreset = false; for (var sFilterGroup in gMapFilters) // for each filter group { if (sFilterGroup !== 'PR' && sFilterGroup !== 'SX') // check only for properties { var sArrayChoices = gMapFilters[sFilterGroup].m_mapChoices; var nChoiceInx = 1; // starting choice index while (typeof(sArrayChoices[nChoiceInx]) !== "undefined") { var sChoiceID = sArrayChoices[nChoiceInx].m_sChoiceID; // get choice id (ex: S_417_1:2) if (typeof(gMapCtrlSelections[sChoiceID]) !== "undefined" && gMapFilters[sFilterGroup].m_mapChoices[nChoiceInx].m_sChoiceName !== '') // not 'Any'? { bPreset = true; // has preset options } nChoiceInx++; } } } return bPreset; } /*********************************************************************** * * FormatResultHTML - Format the result page * * Inputs: arrProductRefs - array of product references * bFound - identify if match found * nPageNumber - result page number * bNeedFilter - whether filtering and count update needed? * * Returns: - nothing * ************************************************************************/ function FormatResultHTML(bFound, arrProductRefs, nPageNumber, bNeedFilter) { if (bNeedFilter) { FilterProductsBasedOnPerms(); // validate product based on retrieved permutations } // // Remove the product list // var contentPageElement = document.getElementById('ContentPage'); if (contentPageElement) { contentPageElement.style.display = "none"; // hide the content } // // Enable search result and sort by template // var resultAreaElement = document.getElementById("filter_results_area"); if (resultAreaElement) { resultAreaElement.style.cssText = 'display:block'; } var resultListElement = document.getElementById("search_results_list"); if (resultListElement) { resultListElement.style.cssText = 'display:block'; } var sortbyElement = document.getElementById("SortBy"); if (sortbyElement) { sortbyElement.style.cssText = 'display:block'; } // // When carousel visibility changes, they have to be reloaded. // ReloadCarousels(); // // Display no match found message // if ((!bFound) || (gArrSortedProductRefs.length === 0)) // no matching products found { var resultContent = "No matching products were found."; UpdateResultContent(resultContent); // update result content UpdateResultSummary(false); // update summary UpdatePaginatedLinks(false); // update pagination links if (bNeedFilter) // need filtering { UpdateFilterCount(); // update the filter count } gArrSortedProductRefs.length = 0; // sorted product references alone gArrResultSet.length = 0; // result set containing decorated product refs HideLoadingDialog(); // hide loading dialog if any return; } if (g_sResultLayout === g_eResultLayout.TABULAR) { FormatTabularResult(nPageNumber); // format the tabular result page } else { FormatStandardResult(nPageNumber); // format the standard result page } if (bNeedFilter) // need filtering { UpdateFilterCount(); // update the filter count } } /*********************************************************************** * * FormatStandardResult - Format the standard result page * * Inputs: nPageNumber - result page number * * Returns: - nothing * ************************************************************************/ function FormatStandardResult(nPageNumber) { // // Format the actual result // var resultSet = ''; // contains all the result set var dummyResultTemplate = ''; var sArrProductRefs = GetPaginatedProducts(gArrSortedProductRefs, nPageNumber); // get paginated list of prod refs if (sArrProductRefs.length == 0) { nPageNumber = 0; sArrProductRefs = GetPaginatedProducts(gArrSortedProductRefs, nPageNumber); // get paginated list from the first page } for (var nProdCount = 0; nProdCount < sArrProductRefs.length; nProdCount++) { var objProductDetails = new ProductDetails(); objProductDetails = GetProductDetails(sArrProductRefs[nProdCount]); // get the product details from cache if (typeof(objProductDetails) !== "undefined") { dummyResultTemplate = ReplaceResultTemplates(objProductDetails, nProdCount); resultSet += '<div class="std-product-details">' + dummyResultTemplate + '<\/div>'; } } UpdateResultContent(resultSet); // update result content UpdateResultSummary(true); // update summary // // Create and update the paginated links // var sResultPageLnksPgs = CreateSearchResultPageLinks(); // create pagination links // // No pagination links provided if the number of pages are not more than one // if (sResultPageLnksPgs[1] < 2) // check the no of pages { UpdatePaginatedLinks(false); // update pagination links } else { UpdatePaginatedLinks(true, sResultPageLnksPgs[0]); } HideLoadingDialog(); // hide loading dialog if any } /*********************************************************************** * * FormatTabularResult - Format the tabular result page * * Inputs: nPageNumber - result page number * * Returns: - nothing * ************************************************************************/ function FormatTabularResult(nPageNumber) { // // Format the actual result // var resultSet = ''; // contains all the result set var dummyResultTemplate = ''; var sRowElements = ''; var sArrProductRefs = GetPaginatedProducts(gArrSortedProductRefs, nPageNumber); // get paginated list of prod refs if (sArrProductRefs.length == 0) { nPageNumber = 0; sArrProductRefs = GetPaginatedProducts(gArrSortedProductRefs, nPageNumber); // get paginated list from the first page } var bInsertRow = false; for (var nProdCount = 0; nProdCount < sArrProductRefs.length; nProdCount++) { var objProductDetails = new ProductDetails(); objProductDetails = GetProductDetails(sArrProductRefs[nProdCount]); // get the product details from cache if (typeof(objProductDetails) !== "undefined") { dummyResultTemplate = ReplaceResultTemplates(objProductDetails, nProdCount); if (g_nListColCount > 1) { if (((nProdCount + 1) % g_nListColCount) === 0) // insert row { sRowElements += g_sListCellStartTemplate + dummyResultTemplate + g_sListCellEndTemplate; bInsertRow = true; } else // insert column { sRowElements += g_sListCellStartTemplate + dummyResultTemplate + g_sListCellEndTemplate; bInsertRow = false; } if (bInsertRow) { resultSet += g_sListRowStartTemplate + sRowElements + g_sListRowEndTemplate; sRowElements = ''; } else if (((nProdCount + 1) === sArrProductRefs.length)) // special handling for last prod if in odd { resultSet += g_sListRowStartTemplate + sRowElements + g_sListRowEndTemplate; } } else // default single col list { resultSet += g_sListRowStartTemplate + g_sListCellStartTemplate + dummyResultTemplate + g_sListCellEndTemplate + g_sListRowEndTemplate; } } } resultSet = g_sListStartTemplate + resultSet + g_sListEndTemplate; // // Create and update the paginated links // var sResultPageLnksPgs = CreateSearchResultPageLinks(); // create pagination links // // No pagination links provided if the number of pages are not more than one // if (sResultPageLnksPgs[1] < 2) // check the no of pages { UpdatePaginatedLinks(false); // update pagination links } else { UpdatePaginatedLinks(true, sResultPageLnksPgs[0]); } UpdateResultContent(resultSet); // update result content HideLoadingDialog(); // hide loading dialog if any } /*********************************************************************** * * ReplaceResultTemplates - Replace result template with the actual values * * Inputs: objProductDetails - product details object * nProdCount - product count * * Returns: - modified content * ************************************************************************/ function ReplaceResultTemplates(objProductDetails, nProdCount) { var nProductCount = g_nProductMinIndex + 1 + nProdCount; // product count var sResultTemplate = g_sSearchResultsTemplate; sResultTemplate = ReplaceProductDetailstemplate(objProductDetails, sResultTemplate, nProductCount); // // Evaluate the script function call from the template // while (sResultTemplate.match(/<Actinic:ScriptFunctionCall[^>]*>([^`]*?)<\/Actinic:ScriptFunctionCall>/i)) { var arrMatch = sResultTemplate.match(/<Actinic:ScriptFunctionCall[^>]*>([^`]*?)<\/Actinic:ScriptFunctionCall>/i) if (arrMatch[1]) // script call available? { var scriptResult = ''; try { scriptResult = eval(arrMatch[1]); // call the JS function in template } catch (e) // failed in evaluating! { console.log('Error in evaluating the statement: ' + arrMatch[1]); } sResultTemplate = sResultTemplate.replace(/<Actinic:ScriptFunctionCall[^>]*>([^`]*?)<\/Actinic:ScriptFunctionCall>/i, scriptResult); } } return sResultTemplate; } /*********************************************************************** * * ReplaceProductDetailstemplate - Replace products details for result template * * Inputs: objProductDetails - product details object * sTemplate - template to check against * nProductCount - product count * * Returns: - modified content * ************************************************************************/ function ReplaceProductDetailstemplate(objProductDetails, sTemplate, nProductCount) { var sFormattedPrice = FormatPrices(objProductDetails.m_sPrice) // function from dynamic.js sTemplate = sTemplate.replace(/(<Actinic:S_ITEM><\/Actinic:S_ITEM>)/ig, nProductCount); var sProductLinkHREF = ''; if ((IsLoggedIn()) && (typeof(pg_sCustomerAccountsCGIURL) !== 'undefined') // logged in? && (pg_sCustomerAccountsCGIURL !== '')) { // // Shop id for host mode // var sHostParam = ''; if (IsHostMode()) { sHostParam = 'SHOP=' + pg_sShopID + '&'; } sProductLinkHREF = '<a href=\"' + pg_sCustomerAccountsCGIURL + '?' + sHostParam + 'PRODUCTPAGE=' + objProductDetails.m_sAnchor + '\">'; } else { sProductLinkHREF = '<a href=\"' + objProductDetails.m_sAnchor + '\">'; } var sSectionName = "(" + objProductDetails.m_sSection + ")" + "&nbsp;"; var sPrice = sFormattedPrice + "&nbsp;"; var sDescription = objProductDetails.m_sDescription + "&nbsp;"; sTemplate = sTemplate.replace(/((&lt;|<)Actinic:S_PNAME(&gt;|>)(&lt;|<)\/Actinic:S_PNAME(&gt;|>))/ig, objProductDetails.m_sName); sTemplate = sTemplate.replace(/(<Actinic:S_SNAME><\/Actinic:S_SNAME>)/ig, sSectionName); sTemplate = sTemplate.replace(/(<Actinic:S_LINK><\/Actinic:S_LINK>)/ig, sProductLinkHREF); sTemplate = sTemplate.replace(/(<Actinic:S_PRAWPRICE><\/Actinic:S_PRAWPRICE>)/ig, objProductDetails.m_sPrice); sTemplate = sTemplate.replace(/(<Actinic:S_PRICE><\/Actinic:S_PRICE>)/ig, sPrice); sTemplate = sTemplate.replace(/(<Actinic:S_DESCR><\/Actinic:S_DESCR>)/ig, sDescription); sTemplate = sTemplate.replace(/(<Actinic:S_STOCK><\/Actinic:S_STOCK>)/ig, objProductDetails.m_nStockLevel); // // Set the default product image // if (objProductDetails.m_sImage == '') { if (typeof(pg_sDefaultProductImage) !== "undefined") { objProductDetails.m_sImage = pg_sDefaultProductImage; // hope it has the real image } } // // Image replacement // if (objProductDetails.m_sImage !== '') { var myRegExpImg = /(<div[^>]*ResultImage[^>]*>([^`]*?)<\/div>)/igm; var arrMatch = new Array(); arrMatch = myRegExpImg.exec(sTemplate); if (arrMatch != null) { var sImageTags = arrMatch[2]; var sImageSize = ""; if ((typeof(pg_nProductImageWidth) !== 'undefined') && (pg_nProductImageWidth > 0)) { sImageSize += "width=\"" + pg_nProductImageWidth + "\" "; } if ((typeof(pg_nProductImageHeight) !== 'undefined') && (pg_nProductImageHeight > 0)) { sImageSize += "height=\"" + pg_nProductImageHeight + "\""; } sImageTags = sImageTags.replace(/=\"\"/ig, ''); sImageTags = sImageTags.replace(/netquotevar:thumbnailsize/ig, sImageSize); sImageTags = sImageTags.replace(/\bNETQUOTEVAR:THUMBNAIL\b/ig, objProductDetails.m_sImage); sTemplate = sTemplate.replace(myRegExpImg, sImageTags); } } else // cleanup the image template when there is none to display { sTemplate = sTemplate.replace(/(<div[^>]*ResultImage[^>]*>([^`]*?)<\/div>)/ig, ''); } // // Handle Feefo Logo // if (pg_bShowProductFeedback) { var myRegExpImg = /(<div[^>]*ResultFeefoLogo[^>]*>([^`]*?)<\/div>)/igm; var arrMatch = new Array(); arrMatch = myRegExpImg.exec(sTemplate); if (arrMatch != null) { var sFeefoLogoTags = arrMatch[2]; sFeefoLogoTags = sFeefoLogoTags.replace(/((&lt;|<)Actinic:S_PRODREF(&gt;|>)(&lt;|<)\/Actinic:S_PRODREF(&gt;|>))/ig, objProductDetails.m_sProdRef); sTemplate = sTemplate.replace(myRegExpImg, sFeefoLogoTags); } } else // cleanup the image template when there is none to display { sTemplate = sTemplate.replace(/(<div[^>]*ResultFeefoLogo[^>]*>([^`]*?)<\/div>)/ig, ''); } sTemplate = UpdateUDPVariableTemplates(objProductDetails, sTemplate); return sTemplate; } /*********************************************************************** * * UpdateUDPVariableTemplates - Update the UDP variable templates * * Inputs: objProductDetails - product details object * sTemplate - result template * * Returns: - modified template * ************************************************************************/ function UpdateUDPVariableTemplates(objProjectDetails, sTemplate) { for (var sUDPVariableName in objProjectDetails.m_mapUDPs) { if (sUDPVariableName) { // // Create actinic template to replace // var sEscapedUDPVariableName = EscapeRegExp(DecodeHtmlEntity(sUDPVariableName)); // escape if any regex characters var sVariableTemplate = '(((&lt;)|(<))actinic:template[^((&gt;)|(>))]*name=((&quot;)|(\"))' + sEscapedUDPVariableName + '((&quot;)|(\"))((&gt;)|(>))((&lt;)|(<))\/actinic:template((&gt;)|(>)))'; sTemplate = sTemplate.replace(new RegExp(sVariableTemplate, "ig"), objProjectDetails.m_mapUDPs[sUDPVariableName]); } } sTemplate = sTemplate.replace(/(<actinic:template[^>]*name[^>]*>([^`]*?)<\/actinic:template>)/ig, ''); // clean up of UDP template variables return sTemplate; } /*********************************************************************** * * DecodeHtmlEntity - Decode the HTML entity * * Inputs: sText - string to decode * * Returns: - nothing * * Ref: https://gist.github.com/CatTail/4174511 ************************************************************************/ var DecodeHtmlEntity = function(sText) { return sText.replace(/&#(\d+);/g, function(match, dec) { if (dec == '39' || dec == '34') // escape single and double quote { return ('\\' + String.fromCharCode(dec)); } return String.fromCharCode(dec); }); } /*********************************************************************** * * EncodeHtmlEntity - Encode HTML entity * * Inputs: sText - string to encode * * Returns: - nothing * * Ref: Ref: https://gist.github.com/CatTail/4174511 ************************************************************************/ var EncodeHtmlEntity = function(sText) { var sBuffer = []; for (var sIndex = sText.length - 1; sIndex >= 0; sIndex--) { sBuffer.unshift(['&#', sText[sIndex].charCodeAt(), ';'].join('')); } return sBuffer.join(''); } /*********************************************************************** * * ProductDetails - Product details class definition * * Returns: - nothing * ************************************************************************/ function ProductDetails() { this.m_sProdRef = ''; // product reference this.m_sSid = ''; // section id this.m_sName = ''; // product name this.m_sDescription = ''; // product description this.m_sSection = ''; // section name this.m_sImage = ''; // image name this.m_sAnchor = ''; // page name with anchor id this.m_sPrice = ''; // product price this.m_mapProperties = {}; // properties map this.m_mapCompToPermutation = {}; // map of combinations to valid permutations this.m_sDecSection = ''; // decorated section this.m_sDecPriceBand = ''; // decorated price band this.m_sDecFilterString = ''; // decorated filter string this.m_mapDecChoices = {}; // decorated choice map this.m_mapUDPs = {}; // udps this.m_nStockLevel; // stock level this.m_bFullPermutation = false; // full permutation } /*********************************************************************** * * ProductProperties - Product properties * * Returns: - nothing * ************************************************************************/ function ProductProperties() { this.m_mapChoices = {}; // choices content this.m_sPropID = ''; // property id this.m_bShow = false; // whether to show the property or not this.m_bHideAlways = false; // hide always? } /*********************************************************************** * * FilterChoiceDetails - Product choices * * Returns: - nothing * ************************************************************************/ function FilterChoiceDetails() { this.m_sChoiceID = ''; // choice ID this.m_sChoiceName = ''; // choice name this.m_nChoiceCount = 0; // choice count this.m_bHideAlways = false; // hide always? } /*********************************************************************** * * SetProductDetails - Set the product details * * Inputs: objProductDetails - product details object * arrProductInfo - product information array * * Returns: - nothing * ************************************************************************/ function SetProductDetails(objProductDetails, arrProductInfo) { objProductDetails.m_sProdRef = arrProductInfo[0]; objProductDetails.m_sSid = arrProductInfo[1]; objProductDetails.m_sName = arrProductInfo[2]; objProductDetails.m_sDescription = arrProductInfo[3]; objProductDetails.m_sSection = arrProductInfo[4]; objProductDetails.m_sImage = arrProductInfo[5]; objProductDetails.m_sAnchor = arrProductInfo[6]; objProductDetails.m_sPrice = arrProductInfo[7]; var sPermutationString = arrProductInfo[8]; // simplified permutation string var sChildProducts = arrProductInfo[9]; // child products var sPropertiesString = arrProductInfo[10]; // properties string var sUDPstring = arrProductInfo[11]; // udp string objProductDetails.m_nStockLevel = arrProductInfo[14] // stock level var arrProperties = sPropertiesString.split(','); // // Create a map of child products to parent product // if (sChildProducts != '') { var arrChildProducts = sChildProducts.split('|'); for (var nChildPodIdx = 0; nChildPodIdx < arrChildProducts.length; nChildPodIdx++) { var sChildProductRef = arrChildProducts[nChildPodIdx]; if (sChildProductRef != '') { sChildProductRef = DecodeHtmlEntity(sChildProductRef); if (typeof(gMapChildToParentProducts[sChildProductRef]) === 'undefined') { gMapChildToParentProducts[sChildProductRef] = new Array; } gMapChildToParentProducts[sChildProductRef].push(objProductDetails.m_sProdRef); } } } // // Set product properties details // var arrFilters = new Array(); for (var nPropInx = 0; nPropInx < arrProperties.length; nPropInx++) { // // Create a map of product properties. The keys is the Propertiy ID // var arrPropDetails = arrProperties[nPropInx].split('!'); var sPropId = arrPropDetails[0]; var sPropCtrlId = 'S_' + sPropId; if (typeof(gMapFilterGrpIdToFilterGrpName[sPropCtrlId]) === 'undefined') { continue; // continue if property is defined } objProductDetails.m_mapProperties[sPropCtrlId] = new ProductProperties(); // map to array of properties for (var nChIdx = 1; nChIdx < arrPropDetails.length; nChIdx++) { var sChoices = arrPropDetails[nChIdx].replace(/(^\s*)|(\s*$)/gi, ""); SetProductProperties(objProductDetails, sPropCtrlId, arrFilters, sPropId, sChoices); } } // // Set component details with decorated permutations for easy match // Example: (.*)\-S_654_0\:Red\-\-S_655_0\:Gold\-\-S_656_0\:I\-(.*) // var bInvalidEmptyPermsProduct = false; if (sPermutationString !== '') { var arrPermutations = sPermutationString.split(','); for (var nPermIdx = 0; nPermIdx < arrPermutations.length; nPermIdx++) { var sPattern = /(<(.*)>(.*))/igm; var arrMatch = sPattern.exec(arrPermutations[nPermIdx]); if (arrMatch !== null) { if (arrMatch[2] !== '') { var arrAttributeCombinations = (arrMatch[2].toUpperCase()).split(':'); // attribute combination (Ex: S_254_0:S_255_0:S_256_0) InsertSort(arrAttributeCombinations); var sCombinationKey = arrAttributeCombinations.join(':'); // // exclude undefined attribute combinations // for (var nAttrIdx = 0; nAttrIdx < arrAttributeCombinations.length; nAttrIdx++) { if (typeof(gMapPropNameToPropId[arrAttributeCombinations[nAttrIdx]]) === 'undefined') { arrAttributeCombinations.splice(nAttrIdx, 1); nAttrIdx--; } } // // Check if any combination of attributes defined in filter options, if not the permutation // details are not stored as they are not used // var sTmpAttributes = '\\-' + arrAttributeCombinations.join('\\-.*\\-') + '\\-'; var oRegExAttr = new RegExp(sTmpAttributes, 'i'); // regular expression if (arrAttributeCombinations.length == 0 || !oRegExAttr.test(g_sDefinedPropertiesPattern)) { continue; // do not store the permutation } var sPerms = arrMatch[3]; if (sPerms === '') { if (typeof(objProductDetails.m_mapCompToPermutation[sCombinationKey]) === 'undefined') { objProductDetails.m_mapCompToPermutation[sCombinationKey] = 'EMPTY'; bInvalidEmptyPermsProduct = true; } continue; } var arrPermCombinations = (sPerms.toUpperCase()).split('|'); // // Create a map of decorated valid permutations with the combination as key // for (var nIdx = 0; nIdx < arrPermCombinations.length; nIdx++) { // // prepare permutation regular expressions // var arrCombs = arrPermCombinations[nIdx].split('!!'); for (var nCombIdx = 0; nCombIdx < arrCombs.length; nCombIdx++) { var arrTempComb = arrCombs[nCombIdx].split('!'); if (typeof(gMapPropNameToPropId[arrTempComb[0]]) === 'undefined') { arrCombs.splice(nCombIdx, 1); nCombIdx--; } } if (arrCombs.length === 0) { continue; } InsertSort(arrCombs); var sTmpPerms = '\\-' + arrCombs.join('\\-.*\\-') + '\\-'; var arrTmpPerms = sTmpPerms.split('!'); var oRegEx = new RegExp(arrTmpPerms.join('\\:'), 'i'); // regular expression // // Create a map of valid permutations // if (typeof(objProductDetails.m_mapCompToPermutation[sCombinationKey]) === 'undefined' || objProductDetails.m_mapCompToPermutation[sCombinationKey] === 'EMPTY' || // might have been empty for some product objProductDetails.m_mapCompToPermutation[sCombinationKey] === 'OSTOCK') // might have been out of stock for some product { objProductDetails.m_mapCompToPermutation[sCombinationKey] = new Array; } objProductDetails.m_mapCompToPermutation[sCombinationKey].push(oRegEx); // permutation map of regular expressions } } } } } else { objProductDetails.m_mapCompToPermutation['EMPTY'] = ''; // no permutation! } // // mark empty permutation products which are invalid // if (bInvalidEmptyPermsProduct && typeof(gMapInvalidProdRefs[objProductDetails.m_sProdRef]) !== 'undefined') { for (sCombinationKey in objProductDetails.m_mapCompToPermutation) { if (objProductDetails.m_mapCompToPermutation[sCombinationKey] !== 'EMPTY') { bInvalidEmptyPermsProduct = false; } } if (bInvalidEmptyPermsProduct) { gMapInvalidEmptyPermsProdRefs[objProductDetails.m_sProdRef] = 0; } } // // Update the price band count // if (IsFilterCountEnabled() || IsFilterAsDefaultView()) { var sPriceBand = GetPriceBand(parseInt(objProductDetails.m_sPrice)); objProductDetails.m_sDecPriceBand = sPriceBand; // update the price band var sDecoratedPriceBand = 'PR_' + sPriceBand; arrFilters.push(sDecoratedPriceBand); objProductDetails.m_sDecSection = objProductDetails.m_sSid; var sDecoratedSection = 'SX_' + objProductDetails.m_sSid; arrFilters.push(sDecoratedSection); } // // Form decorated filter string for regexp match for filtering // InsertSort(arrFilters); var sDecoratedChoices = '!' + arrFilters.join('!!') + '!'; objProductDetails.m_sDecFilterString = sDecoratedChoices; // // Fill in UDPs map // var arrUDPValues = sUDPstring.split(','); for (var nUDPIdx = 0; nUDPIdx < arrUDPValues.length; nUDPIdx++) { var arrUDPVarValues = arrUDPValues[nUDPIdx].split('|'); objProductDetails.m_mapUDPs[arrUDPVarValues[0]] = arrUDPVarValues[1]; } } /*********************************************************************** * * SetProductProperties - Set the product property details * * Inputs: objProductDetails - product details * sPropCtrlId - property control id * arrFilters - array of filter options * sPropId - product property id * sChoices - product property choices * * Returns: - nothing * ************************************************************************/ function SetProductProperties(objProductDetails, sPropCtrlId, arrFilters, sPropId, sChoices) { objProductProperties = objProductDetails.m_mapProperties[sPropCtrlId]; objProductProperties.m_sPropID = sPropId; // // Special handling for choice type 'Any' // Note: Choice type 'Any' in the product details has property as '451_0:&#33;' // if (sChoices === '&#33;') { objProductProperties.m_mapChoices[0] = ""; return; } var sArryChoices = sChoices.split('&#33;'); // // Create array choices // for (var nChoiceIndx = 0; nChoiceIndx < sArryChoices.length; nChoiceIndx++) { var sChoice = sArryChoices[nChoiceIndx].replace(/(^\s*)|(\s*$)/gi, ""); // remove leading/trailing spaces var sCleanChoice = sChoice.replace(/(&#32;)/gi, " "); // replaces encoded charaters for space objProductProperties.m_mapChoices[sCleanChoice] = nChoiceIndx; if (sCleanChoice !== '') { var sDecoratedChoice = 'S_' + sPropId + ':' + sCleanChoice; arrFilters.push(sDecoratedChoice); objProductDetails.m_mapDecChoices[sDecoratedChoice] = ''; } } } /*********************************************************************** * * OnSortStatic - static sort order changing * * Inputs: ctrlDropDown - control name to identify * * Returns: - nothing * ************************************************************************/ function OnSortStatic(ctrlDropDown) { // // When loaded from a static page, there are two sort-order forms on the page. // This is the handler for the form in the static results. We have to update the // other form with the selection from this one, because after this one triggers it // is deleted and the dynamically inserted JS one is used. // var nSelectedIndex = ctrlDropDown.selectedIndex; var elFormSelectElement = GetSelectWithinSortForm('filter_sortorder'); if (elFormSelectElement) { elFormSelectElement.selectedIndex = nSelectedIndex; } // // Continue with standard sorting // OnSort(ctrlDropDown); } /*********************************************************************** * * OnSort - Sorting local set of products * * Inputs: ctrlDropDown - control name to identify * * Returns: - nothing * ************************************************************************/ function OnSort(ctrlDropDown) { // // Note: Form name to be modified if different filter form is used // var filterSortOrderForm = document.forms['filter_sortorder']; var nSelectedIndex = ctrlDropDown.selectedIndex; var sSelectedSortOrder = ctrlDropDown.options[nSelectedIndex].value; g_bSortOrder = sSelectedSortOrder; AppendUseStorageHash(g_eFilterSettings.SORTORDER); if (g_nCurrenPageNumber != -1) { SetCurrentPageNumber(0); } // // Change the default sort order with the selected one // ShowLoadingDialog(); // show loading dialog UpdateSortOrder(sSelectedSortOrder); DoSort(sSelectedSortOrder, gArrResultSet); // do the sort RetrieveProductDetails(g_nCurrenPageNumber, false); } /*********************************************************************** * * OnPagination - Pagination of product results * * Inputs: nPageNumber - page number to navigate * * Returns: - nothing * ************************************************************************/ function OnPagination(nPageNumber) { AppendUseStorageHash(g_eFilterSettings.PAGINATION); RetrieveProductDetails(nPageNumber, false); // get product details $(function() { // // Scroll to filter result header // $("html, body").animate({ scrollTop: $("#SortBy").offset().top }, "slow"); }); } /*********************************************************************** * * AppendUseStorageHash - Append storage hash to URL * * Inputs: eStorageSetting - storage setting * * Returns: - nothing * ************************************************************************/ function AppendUseStorageHash(eStorageSetting) { if (!SDStorage.isSupported()) { return; // do not append hash if storage is not supported } var bHashAppended = false; if (window.location.hash == '') { window.location.hash = '#usestorage'; bHashAppended = true; } else if (window.location.hash != '' && window.location.hash.indexOf('usestorage') != -1) { // do nothing bHashAppended = false; } else { window.location.hash = '#usestorage'; bHashAppended = true; } if (eStorageSetting == g_eFilterSettings.FILTER) { g_bUseStorageFromClick = bHashAppended; } else { g_bUseStorageSortPage = bHashAppended; } } /*********************************************************************** * * StoreSettings - Store settings handler * * Returns: - nothing * ************************************************************************/ function StoreSettings() { if (!IsUseFilterStorage()) { return; } var sFilterOptions = ''; // filter settings to store var arrFilterSettings = new Array(); // array of filter settings var nFltrSetInd = 0; var bSel = false; // is there a selection to store? // // Get the filter selections from map and store the same // for (var sFilterGroup in gMapControlToSelection) { var mapFilterOptions = gMapControlToSelection[sFilterGroup]; for (var sOption in mapFilterOptions) { var sKey = sFilterGroup + ':' + sOption; arrFilterSettings[nFltrSetInd++] = sKey; bSel = true; } } if (bSel) { sFilterOptions = arrFilterSettings.join(','); } SDStorage.writePage('filterSettings', sFilterOptions); // store filter options SDStorage.writePage('sortOrder', g_bSortOrder); // store filter sort order SDStorage.writePage('pageNumber', g_nCurrenPageNumber); // store filter pagination } /*********************************************************************** * * ResetAllStorage - Clear all storage settings * * Returns: - nothing * ************************************************************************/ function ResetAllStorage() { ResetStorage(g_eFilterSettings.FILTER); ResetStorage(g_eFilterSettings.SORTORDER); ResetStorage(g_eFilterSettings.PAGINATION); } /*********************************************************************** * * ResetStorage - Reset storage setting * * Inputs: eStorageSetting - storage setting to reset * * Returns: - nothing * ************************************************************************/ function ResetStorage(eStorageSetting) { switch (eStorageSetting) { case g_eFilterSettings.FILTER: SDStorage.writePage('filterSettings', ''); break; case g_eFilterSettings.SORTORDER: g_bSortOrder = pg_sDefaultSortOrder; SDStorage.writePage('sortOrder', g_bSortOrder); break; case g_eFilterSettings.PAGINATION: g_nCurrenPageNumber = 0; SDStorage.writePage('pageNumber', g_nCurrenPageNumber); break; } } /*********************************************************************** * * GetProductDetails - Get the stored product details for the * matched product reference * * Inputs: sProdRef - product reference to match * * Returns: - matched product details * ************************************************************************/ function GetProductDetails(sProdRef) { // // Look for the product details for the matched product reference // return gMapObjProductDetails[sProdRef]; } /*********************************************************************** * * IsProductDetailsCached - Check if the product details are cached * * Inputs: sProdRef - product reference to match * * Returns: - true if matched * ************************************************************************/ function IsProductDetailsCached(sProdRef) { var bMatchFound = false; // // Look for the product details for the matched product reference // if (typeof(gMapObjProductDetails[sProdRef]) !== "undefined") { bMatchFound = true; } return bMatchFound; } /*********************************************************************** * * GetPaginatedProducts - Get the product numbers based on the page * for the given number * * Inputs: arrInputProduct - array of product references * nPageNumber - page number * * Returns: arrProducts - array of products found * ************************************************************************/ function GetPaginatedProducts(arrInputProduct, nPageNumber) { var arrProducts = new Array(); if ((pg_nSearchResultsLimit === 0) || // believe that the global variable defined in HTML or (nPageNumber === -1)) // full page number is given? { g_nProductMinIndex = 0; g_nProductMaxIndex = arrInputProduct.length + 1; } else { g_nProductMinIndex = nPageNumber * pg_nSearchResultsLimit; g_nProductMaxIndex = (nPageNumber + 1) * pg_nSearchResultsLimit; } for (var nProductIndex = g_nProductMinIndex; nProductIndex < g_nProductMaxIndex; nProductIndex++) { if (typeof(arrInputProduct[nProductIndex]) !== "undefined") { arrProducts.push(arrInputProduct[nProductIndex]); } } return arrProducts; } /*********************************************************************** * * GetParent - Get the parent node * * Inputs: childObj - child element for which the parent node * to retrieve * parentNodeName - immediate parent node name * * Returns: - parent object * ************************************************************************/ function GetParent(parentNodeName, childObj) { var parentObj = childObj.parentNode; // // Find the immmediate parent node for the given node // if ((typeof(parentObj) != 'undefined') && (parentObj != null)) { if (parentObj.tagName != null) { while (parentObj.tagName !== parentNodeName.toUpperCase()) { parentObj = parentObj.parentNode; } } } return parentObj; } /*********************************************************************** * * EditLabel - Get the parent node * * Inputs: element - element to be edited * * Returns: - nothing * ************************************************************************/ function EditLabel(element) { var childElements = element.childNodes; // get child nodes // // Process all the child nodes of the currently selected node // var liElements = element.parentNode.childNodes; for (var liIndex = 0; liIndex < liElements.length; liIndex++) { if (liElements[liIndex] !== null) { var liChildElements = liElements[liIndex].childNodes; for (var liChildInx = 0; liChildInx < liChildElements.length; liChildInx++) { if (liChildElements[liChildInx] !== null && liChildElements[liChildInx].nodeName == "LABEL") { liChildElements[liChildInx].style.cssText = ''; // set the style attribute (IE & chrome tweaks) } } } } // // Process the child node of the currently selected node // for (var childIndex = 0; childIndex < childElements.length; childIndex++) { if ((childElements[childIndex] !== null) && (childElements[childIndex].nodeName == "LABEL")) { childElements[childIndex].style.cssText = 'color:red;'; // set the style attribute (IE tweaks) } } } /*********************************************************************** * * UpdateResultSummary - Update the result summary * * Inputs: bFound - result found (true/false) * * Returns: - nothing * ************************************************************************/ function UpdateResultSummary(bFound) { // // Summary update // var elResultList = ''; elResultList = document.getElementById("search_results_list"); if (elResultList === null) // no result list? { ShowError('Tag with the id \'search_results_list\' is not found in Filter Results Layout, result summary might not be updated properly', g_ErrorCode.TAG); return; } if (!bFound) // no search result found { var sResultSummary = "<Actinic:S_SUMMARY></Actinic:S_SUMMARY>"; elResultList.innerHTML = elResultList.innerHTML.replace(/(<Actinic:S_SUMMARY>(.*?)<\/Actinic:S_SUMMARY>)/ig, sResultSummary); return; } // // Get min max search result value to be displayed // var nMinMax = CalculateMinMaxSearchResult(); var sResultSummary = "<Actinic:S_SUMMARY>" + "Results " + nMinMax[0] + "-" + nMinMax[1] + " of " + gArrSortedProductRefs.length + "</Actinic:S_SUMMARY>"; elResultList.innerHTML = elResultList.innerHTML.replace(/(<Actinic:S_SUMMARY>(.*?)<\/Actinic:S_SUMMARY>)/ig, sResultSummary); } /*********************************************************************** * * CalculateMinMaxSearchResult - Calculate min max search result value * to be displayed * * Inputs: bFound - result found (true/false) * * Returns: - nothing * ************************************************************************/ function CalculateMinMaxSearchResult() { var nMinResultDisplay = g_nProductMinIndex + 1; var nMaxResultDisplay = 0; if (g_nProductMaxIndex > gArrSortedProductRefs.length) // result set size is less than the limit? { nMaxResultDisplay = gArrSortedProductRefs.length; } else { nMaxResultDisplay = g_nProductMaxIndex; // get the maximum value } return [nMinResultDisplay, nMaxResultDisplay]; } /*********************************************************************** * * UpdateResultContent - Update the result content * * Inputs: resultContent - content to update * * Returns: - nothing * ************************************************************************/ function UpdateResultContent(resultContent) { // // Cleanup any static contents // var searchResultContent = document.getElementById('FilterResultElements'); var sStaticResults = document.getElementById('StaticResults'); if (sStaticResults) { sStaticResults.innerHTML = ''; } // // Update content // if (g_sResultLayout === g_eResultLayout.TABULAR) // for tabular layout { var productResultContent = ''; productResultContent = document.getElementById('product-list'); if (productResultContent) { productResultContent.innerHTML = resultContent; } } else // for standard layout { if (searchResultContent) { searchResultContent.innerHTML = resultContent; // stick to the html page searchResultContent.style.display = "block"; // ensure the block is displayed } else { // // Update to user // var sErrorMsg = "Tag with the id \"SearchResults\" is not found in filter option layout, filter might not work properly"; ShowError(sErrorMsg, g_ErrorCode.TAG); } } } /*********************************************************************** * * CreateSearchResultPageLinks - Create search result page links * * Returns: - nothing * ************************************************************************/ function CreateSearchResultPageLinks() { var resultListTemplate = document.getElementById("PaginationLinksTemplate"); if (resultListTemplate) { // // pagination link template attributes // var sTemplate = resultListTemplate.innerHTML.replace(/(\n)/g, ''); var mapPaginationDesignAttributes = { 'nMaxVisibleLinks': '<Actinic:PAGINATION_VISIBLELINKS>(.*?)<\/Actinic:PAGINATION_VISIBLELINKS>', 'sHeader': '<Actinic:PAGINATION_HEADER>(.*?)<\/Actinic:PAGINATION_HEADER>', 'sShowFirstLink': '<Actinic:PAGINATION_SHOWFIRSTURL>(.*?)<\/Actinic:PAGINATION_SHOWFIRSTURL>', 'sFirstPageURL': '<Actinic:PAGINATION_FIRSTPAGEURL>(.*?)<\/Actinic:PAGINATION_FIRSTPAGEURL>', 'sPrevPageURL': '<Actinic:PAGINATION_PREVPAGEURL>(.*?)<\/Actinic:PAGINATION_PREVPAGEURL>', 'sLinksPageURL': '<Actinic:PAGINATION_LINKSPAGEURL>(.*?)<\/Actinic:PAGINATION_LINKSPAGEURL>', 'sNextPageURL': '<Actinic:PAGINATION_NEXTPAGEURL>(.*?)<\/Actinic:PAGINATION_NEXTPAGEURL>', 'sLastPageURL': '<Actinic:PAGINATION_LASTPAGEURL>(.*?)<\/Actinic:PAGINATION_LASTPAGEURL>', 'sFullPageURL': '<Actinic:PAGINATION_FULLPAGEURL>(.*?)<\/Actinic:PAGINATION_FULLPAGEURL>' } for (var key in mapPaginationDesignAttributes) { var pattern = new RegExp(mapPaginationDesignAttributes[key], 'gi'); var arrMatches = pattern.exec(sTemplate); if (arrMatches) { var matchedValue = arrMatches[1]; matchedValue = matchedValue.replace(/(&lt;)/ig, '<'); matchedValue = matchedValue.replace(/(&gt;)/ig, '>'); mapPaginationDesignAttributes[key] = matchedValue; } else { mapPaginationDesignAttributes[key] = ''; } } } var sResultPageLinks = ""; var nSearchResultsLimit = pg_nSearchResultsLimit; var nMaxVisibleLinks = parseInt(mapPaginationDesignAttributes['nMaxVisibleLinks']); // // ensure first split page is shown when full page is disabled // if ((pg_bShowFullPageInPagination === 0) && (g_nCurrenPageNumber === -1)) { g_nCurrenPageNumber = 0; } // // ensure filter results limit is not exceeded than the total number of results // if (nSearchResultsLimit > gArrSortedProductRefs.length) { nSearchResultsLimit = gArrSortedProductRefs.length; } // // Calculate number of pages // var nMaxPageCount = 0; if (nSearchResultsLimit !== 0) // if result limit is non zero { nMaxPageCount = Math.floor((gArrSortedProductRefs.length) / nSearchResultsLimit); if ((gArrSortedProductRefs.length) % nSearchResultsLimit !== 0) { nMaxPageCount++; } } if (nMaxPageCount < 2) // return if no of pages less than 2 { return [sResultPageLinks, nMaxPageCount]; } // // show first link when view all page is shown // if ((pg_bShowFullPageInPagination !== 0) && (g_nCurrenPageNumber === -1)) { var sPageLabel = mapPaginationDesignAttributes['sShowFirstLink']; var sLink = "javascript:OnPagination(0)"; sResultPageLinks = sPageLabel.replace(/<ACTINIC:PAGINATION_URLLINK><\/ACTINIC:PAGINATION_URLLINK>/gi, sLink); return [sResultPageLinks, nMaxPageCount]; } // // include pagination header // sResultPageLinks = mapPaginationDesignAttributes['sHeader']; if (0 !== g_nCurrenPageNumber) // we are not on page 0 { // // first page URL // var sPageLabel = mapPaginationDesignAttributes['sFirstPageURL']; var sLink = "javascript:OnPagination(0)"; sPageLabel = sPageLabel.replace(/<ACTINIC:PAGINATION_URLLINK><\/ACTINIC:PAGINATION_URLLINK>/gi, sLink); sResultPageLinks += sPageLabel; // // previous page URL // sPageLabel = mapPaginationDesignAttributes['sPrevPageURL']; sLink = "javascript:OnPagination(" + (g_nCurrenPageNumber - 1) + ")"; sPageLabel = sPageLabel.replace(/<ACTINIC:PAGINATION_URLLINK><\/ACTINIC:PAGINATION_URLLINK>/gi, sLink); sResultPageLinks += sPageLabel; } if (nMaxVisibleLinks === 0) { nMaxVisibleLinks = nMaxPageCount; } // // calculate page offset w.r.t current page number // var nPageOffset = 0; if (g_nCurrenPageNumber > -1) { nPageOffset = Math.floor(g_nCurrenPageNumber / nMaxVisibleLinks); } var nStartPage = nPageOffset * nMaxVisibleLinks; var nMaxPage = nStartPage + nMaxVisibleLinks; if (nMaxPage > nMaxPageCount) { nMaxPage = nMaxPageCount; } // // format the page links // for (var nPageIndex = nStartPage; nPageIndex <= nMaxPage; nPageIndex++) // enumerate the result pages { var sLink = "javascript:OnPagination(" + nPageIndex + ")"; var sPageLabel = mapPaginationDesignAttributes['sLinksPageURL']; var sLinkLable; var nPage = nPageIndex + 1; if (nPageIndex < nMaxPage) { if (nPageIndex === g_nCurrenPageNumber) { sLinkLable = " <b>" + nPage + "<\/b> "; sPageLabel = sPageLabel.replace(/<A(.*)<\/A>/gi, sLinkLable); } else { sPageLabel = sPageLabel.replace(/<ACTINIC:PAGINATION_INDEX><\/ACTINIC:PAGINATION_INDEX>/gi, nPage); sPageLabel = sPageLabel.replace(/<ACTINIC:PAGINATION_URLLINK><\/ACTINIC:PAGINATION_URLLINK>/gi, sLink); } sResultPageLinks += sPageLabel; } else if (nPageIndex < nMaxPageCount) { var sExtraLinks = "..."; sPageLabel = sPageLabel.replace(/<ACTINIC:PAGINATION_INDEX><\/ACTINIC:PAGINATION_INDEX>/gi, sExtraLinks); sPageLabel = sPageLabel.replace(/<ACTINIC:PAGINATION_URLLINK><\/ACTINIC:PAGINATION_URLLINK>/gi, sLink); sResultPageLinks += sPageLabel; } } if (nMaxPageCount !== (g_nCurrenPageNumber + 1)) // we are not on page MAX (the + 1 is because the page number index is from 0 -> max - 1) { sLink = "javascript:OnPagination(" + (g_nCurrenPageNumber + 1) + ")"; // // next page URL // sPageLabel = mapPaginationDesignAttributes['sNextPageURL']; sPageLabel = sPageLabel.replace(/<ACTINIC:PAGINATION_URLLINK><\/ACTINIC:PAGINATION_URLLINK>/gi, sLink); sResultPageLinks += sPageLabel; // // last page URL // sLink = "javascript:OnPagination(" + (nMaxPageCount - 1) + ")"; sPageLabel = mapPaginationDesignAttributes['sLastPageURL']; sPageLabel = sPageLabel.replace(/<ACTINIC:PAGINATION_URLLINK><\/ACTINIC:PAGINATION_URLLINK>/gi, sLink); sResultPageLinks += sPageLabel; } // // include view all page link if required // if (pg_bShowFullPageInPagination !== 0) { sPageLabel = mapPaginationDesignAttributes['sFullPageURL']; sLink = "javascript:OnPagination(-1)"; var nTotalProducts = gArrSortedProductRefs.length; sPageLabel = sPageLabel.replace(/<ACTINIC:PAGINATION_URLLINK><\/ACTINIC:PAGINATION_URLLINK>/gi, sLink); sPageLabel = sPageLabel.replace(/<ACTINIC:PAGINATION_PRODUCTCOUNT><\/ACTINIC:PAGINATION_PRODUCTCOUNT>/gi, nTotalProducts); sResultPageLinks += sPageLabel; } return [sResultPageLinks, nMaxPageCount]; } /*********************************************************************** * * UpdatePaginatedLinks - Create pagination links * * Inputs: bEnable - enable pagination * sPaginationLinks - pagination links * * Returns: - nothing * ************************************************************************/ function UpdatePaginatedLinks(bEnable, sPaginationLinks) { // // Update pagination links top // var sResultPaginationLinksTop = document.getElementById('filter_pagination_links_top'); if (sResultPaginationLinksTop) { if (bEnable) { sResultPaginationLinksTop.innerHTML = sPaginationLinks; } else { sResultPaginationLinksTop.innerHTML = ''; } } // // Update pagination links top // var sResultPaginationLinksBottom = document.getElementById('filter_pagination_links_bottom'); if (sResultPaginationLinksBottom) { if (bEnable) { sResultPaginationLinksBottom.innerHTML = sPaginationLinks; } else { sResultPaginationLinksBottom.innerHTML = ''; } } } /*********************************************************************** * * UpdateSortOrder - Update sort order in filter form * * Inputs: sSortOrd - sort order to update * * Returns: - nothing * ************************************************************************/ function UpdateSortOrder(sSortOrd) { var filterForm = document.forms['filter']; if (typeof(filterForm) !== "undefined") { var filterFormElements = filterForm.elements; // filter form elements for (var nIndex = 0; nIndex < filterFormElements.length; nIndex++) { if ((filterFormElements[nIndex].tagName === 'INPUT') && (filterFormElements[nIndex].name === 'SO')) { filterFormElements[nIndex].value = sSortOrd; } } } } /*********************************************************************** * * GetPaginationDetails - Get pagination details * * Returns: - actual search result limit and number of pages * ************************************************************************/ function GetPaginationDetails() { var nSearchResultLimit = 0; if (pg_nSearchResultsLimit > gArrSortedProductRefs.length) { nSearchResultLimit = gArrSortedProductRefs.length; } else { nSearchResultLimit = pg_nSearchResultsLimit; } // // Calculate number of pages // var nPages = 0; if (nSearchResultLimit !== 0) // if result limit is non zero { nPages = Math.floor((gArrSortedProductRefs.length) / nSearchResultLimit); if ((gArrSortedProductRefs.length) % nSearchResultLimit !== 0) { nPages++; } } return [nSearchResultLimit, nPages]; } /*********************************************************************** * * GetSortOrder - Get sort order * * Returns: - sort order * ************************************************************************/ function GetSortOrder() { var sSortOrder = ''; var filterForm = document.forms['filter']; if (typeof(filterForm) !== "undefined") { if (filterForm.SO) { sSortOrder = filterForm.SO.value; } } if ((sSortOrder === '') && (typeof(pg_sDefaultSortOrder) !== "undefined")) { sSortOrder = pg_sDefaultSortOrder; // default sort order } return sSortOrder; } /*********************************************************************** * * ResetSortOrder - Reset the with default sort order * * Returns: - nothing * ************************************************************************/ function ResetSortOrder() { var filterForm = document.forms['filter']; var sStoredSortOrder = ''; sStoredSortOrder = SDStorage.readPage('sortOrder'); // // loading sort order from local store if there is any // if (sStoredSortOrder) { g_bSortOrder = sStoredSortOrder; filterForm.SO.value = sStoredSortOrder; } else if ((typeof(filterForm) !== "undefined") && (typeof(pg_sDefaultSortOrder) !== "undefined")) { if (filterForm.SO) { g_bSortOrder = pg_sDefaultSortOrder; filterForm.SO.value = pg_sDefaultSortOrder; } } var frmFiltersortOrder = document.forms['filter_sortorder'] var options = ''; if (typeof(filterForm) !== "undefined") { options = frmFiltersortOrder.getElementsByTagName('option'); } for (var i in options) { if (options[i].value === g_bSortOrder) { options[i].selected = 'selected'; } else { options[i].selected = ''; } } } /*********************************************************************** * * SetCurrentPageNumber - Set the current search result page number * * Returns: - nothing * ************************************************************************/ function SetCurrentPageNumber(nPageNumber) { g_nCurrenPageNumber = nPageNumber; } /*********************************************************************** * * SetStoredPageNumber - Set the stored page number and * set the global variable * * Returns: - nothing * ************************************************************************/ function SetStoredPageNumber() { var nPageNumber = SDStorage.readPage('pageNumber'); if (nPageNumber != null) { g_nCurrenPageNumber = nPageNumber; } else { g_nCurrenPageNumber = 0; } } /*********************************************************************** * * ShowLoadingDialog - Show loading dialog * * Returns: - nothing * ************************************************************************/ function ShowLoadingDialog() { var loadingDialog = document.getElementById('loading-dialog'); if (loadingDialog) { loadingDialog.style.display = "block"; // show the dialog } } /*********************************************************************** * * HideLoadingDialog - Hide loading dialog * * Returns: - nothing * ************************************************************************/ function HideLoadingDialog() { var loadingDialog = document.getElementById('loading-dialog'); if (loadingDialog) { loadingDialog.style.display = "none"; // hide the dialog } } /*********************************************************************** * * GetProdRefsOfNonCachedProductDetails - Get the product references of * non cached product details * * Inputs: arrProductRefs - array of product to check * * Returns: - array of product refs of non cached * product details * ************************************************************************/ function GetProdRefsOfNonCachedProductDetails(arrProductRefs) { var arrNonCachedProdRefs = new Array(); arrNonCachedProdRefs.length = 0; if (arrProductRefs.length !== 0) { for (var prodRefIndx = 0; prodRefIndx < arrProductRefs.length; prodRefIndx++) { if (!IsProductDetailsCached(arrProductRefs[prodRefIndx])) { arrNonCachedProdRefs.push(arrProductRefs[prodRefIndx]); } } } return arrNonCachedProdRefs; } /*********************************************************************** * * CacheProductDetails - Cache product details on the global * variable * * Inputs: arrProductDetailsSet - product details set return from ajax call * * Returns: - nothing * ************************************************************************/ function CacheProductDetails(arrProductDetailsSet) { for (var nProdCount = 0; nProdCount < arrProductDetailsSet.length; nProdCount++) { var productInfo = arrProductDetailsSet[nProdCount].ProductInfo; var sProdRef = productInfo[0]; // // Check stock and exclude the the product if necessary // // productInfo[12] -> stock controlled // productInfo[13] -> in stock // if (IsOutOfStock(sProdRef, productInfo[12], productInfo[13])) { continue; // not cached/excluded from filtering } gMapObjProductDetails[sProdRef] = new ProductDetails(); // product details map with ProdRef as index SetProductDetails(gMapObjProductDetails[sProdRef], productInfo); // set product details } } /*********************************************************************** * * IsOutOfStock - Is out stock in real time * * Inputs: sProdRef - product reference * bIsStockControlled - stock controlled? * bInStockStatic - static stock from product details * * Returns: - true/false * ************************************************************************/ function IsOutOfStock(sProdRef, bIsStockControlled, bInStockStatic) { var bOutOfStock = IsOutOfStockFromStockFilter(sProdRef); // is out stock from filter file if (IsExcludeOutOfStockItems() && bIsStockControlled) { if (bOutOfStock == null) // not found in stockfilter file { if (bInStockStatic <= 0) // out of stock as per assoc prod details { return (true); } } else { if (bOutOfStock) // out of stock as per stockfilter file { return (true); } } } return (false); } //-------------------------------------------------------------- // // Filter Count // //-------------------------------------------------------------- // // global variables for filter count // var gMAX_INT = "9007199254740992"; // maximum int value var gMapPriceBandPriceRange = {}; // formatted price range map with price band ID as key var gMapFilters = {}; // properties map with property ID as key var gMapDefCtrlSelections = {}; // map of default control selections var gArrayPriceIDs = new Array(); // array of price band ID var gArraySectionIDs = new Array(); // array of section ID var gMapControlIdChoiceName = {}; // map of control id to choice name var gMapPropIdToBtnClearStatus = {}; // map of property id to clear button status var gMapCtrlSelections = {}; // map of control selections (example: S_0_422335_0-10:true) var gMapPropCtrlSelections = {}; // map of property control selections (example: BRAND_0:ADIDAS:true) var gMapPropIdToSelections = {}; // map of property id to selections (example: S_0_422335_0:Array[SIZE OPTIONS_0:UK 9, SIZE OPTIONS_0:UK 10]) var gMapControlToSelection = {}; // map of control selections (example: S_0_422335_0:Object[S_0_422335_0-10:"", S_0_422335_0-9:""]) // // Enum for the control type // var g_eControlType = { BUTTON: 1, // check box/radio button LIST: 2, // list (single/multiple select/drop down) LINK: 4, // clickable link UNDEFINED: 5 // undefined }; /*********************************************************************** * * UpdateFilterCount - Main function to fetch and update filter * count * * Returns: - nothing * ************************************************************************/ function UpdateFilterCount() { if (!IsFilterCountEnabled()) { return; } // // Return if the global variable is undefined // if ((typeof(pg_arrayPriceBandValues) === "undefined") || (typeof(pg_arrayProperties) === "undefined")) { return; } CalculateCount(false); // calculate count if (g_bFirstLoad && !g_bHasPresetOptions && !HasFilterStorage()) // has preset value { RemoveFilterWithZeroCount(); // remove filter options with zero count } GenerateDynamicFilterOptions(); // generate dynamic filter options ClearFilterCounts(); // clear off the filter options counts } /*********************************************************************** * * CacheDefinedPriceBands - Cache the price bands in numeric values * * Returns: - nothing * ************************************************************************/ function CacheDefinedPriceBands() { if (typeof(pg_arrayPriceBandValues) === "undefined") { var sErrorMsg = "Global variables 'pg_arrayPriceBandValues' is not defined, filtering functionality might not be available"; ShowError(sErrorMsg, g_ErrorCode.UNDEFINED); return; // return if the the global variable is undefined } // // Create map of price bands with the key as the priceband id // gMapFilterGrpIdToFilterGrpName['PR'] = 'PR' gArrFilterGrpIdSorted.push('PR'); gMapFilters['PR'] = {}; gMapFilters['PR'].m_bShow = false; for (var nPRIndx = 0; nPRIndx < pg_arrayPriceBandValues.length; nPRIndx++) { var arrPriceBand = pg_arrayPriceBandValues[nPRIndx].split(":"); var nMinMax = arrPriceBand[1].split("-"); var sPriceBandID = arrPriceBand[0]; // price ID gArrayPriceIDs.push(sPriceBandID); // array to hold the price band ID gMapFilters['PR'][sPriceBandID] = new PriceBandDetails(); if (nPRIndx === (pg_arrayPriceBandValues.length - 1)) { nMinMax[1] = gMAX_INT; } SetPriceDetails(gMapFilters['PR'][sPriceBandID], nMinMax[0], nMinMax[1]); // set the price band details } } /*********************************************************************** * * PriceBandDetails - Price band details class definition * * Returns: - nothing * ************************************************************************/ function PriceBandDetails() { this.m_nMin = 0; // minimum price this.m_nMax = 0; // maximum price this.m_nCount = 0; // number of product count this.m_bHideAlways = false; // hide always? } /*********************************************************************** * * SetPriceDetails - Set the price band details * * Inputs: objPriceBandDetails - price band details to update * nMinValue - minimum value * nMaxValue - maximum value * * Returns: - nothing * ************************************************************************/ function SetPriceDetails(objPriceBandDetails, nMinValue, nMaxValue) { objPriceBandDetails.m_nMin = parseInt(nMinValue); objPriceBandDetails.m_nMax = parseInt(nMaxValue); } /*********************************************************************** * * GetPriceBand - Get price band for the given price * * Inputs: nPrice - price to get the prceband * * Returns: - priceband id * ************************************************************************/ function GetPriceBand(nPrice) { var sPriceBandId = '-1'; // set to default band var mapPriceBands = gMapFilters['PR']; // get the priceband filters for (var sPriceId in mapPriceBands) { var nMinPrice = mapPriceBands[sPriceId].m_nMin; var nMaxPrice = mapPriceBands[sPriceId].m_nMax; if ((nPrice >= nMinPrice) && (nPrice <= nMaxPrice)) // price within the range? { sPriceBandId = sPriceId; break; } } return sPriceBandId; } /*********************************************************************** * * GenerateDynamicFilterOptions - Generate filter options * * Returns: - nothing * ************************************************************************/ function GenerateDynamicFilterOptions() { CreateFilterSectionOptions(); // generate section/department options CreateFilterPriceBandOptions(); // generate price band filter options CreateFilterPropertyOptions(); // generate filter property options } /*********************************************************************** * * ClearFilterCounts - Clear off filter options counts * * Returns: - nothing * ************************************************************************/ function ClearFilterCounts() { for (var sFilterGroup in gMapFilters) { if (sFilterGroup === 'PR') // filter price group { var mapPriceBands = gMapFilters[sFilterGroup]; for (var sPriceId in mapPriceBands) { mapPriceBands[sPriceId].m_nCount = 0; } gMapFilters[sFilterGroup].m_bShow = false; // do not show the group header by default } else if (sFilterGroup === 'SX') // filter section group { var mapSections = gMapFilters[sFilterGroup]; for (var sSectionId in mapSections) { mapSections[sSectionId].m_nCumulativeCount = 0; // clear off the cumulative count mapSections[sSectionId].m_nCount = 0; } gMapFilters[sFilterGroup].m_bShow = false; // do not show the group header by default } else // filter property group { var mapChoices = gMapFilters[sFilterGroup].m_mapChoices; for (var sChoiceId in mapChoices) { mapChoices[sChoiceId].m_nChoiceCount = 0; gMapFilters[sFilterGroup].m_bShow = false; // do not show the group header by default } } } } /*********************************************************************** * * cacheProductProperties - Cache prduct properties * * Returns: - nothing * ************************************************************************/ function CacheDefinedChoices() { if (typeof(pg_arrayProperties) === "undefined") { var sErrorMsg = "Global variables 'pg_arrayProperties' is not defined, filtering functionality might not be available"; ShowError(sErrorMsg, g_ErrorCode.UNDEFINED); return; } for (var nPropIndx = 0; nPropIndx < pg_arrayProperties.length; nPropIndx++) { if (typeof(pg_arrayProperties[nPropIndx]) !== "undefined") { // // The pg_arrayProperties values will be of the format S&#95;451-1:Red (S_PropID-ChoiceNumber:ChoiceName) // var arrayPropIDChoice = pg_arrayProperties[nPropIndx].split(":"); var sPropIDChoice = arrayPropIDChoice[0].replace(/(&#95;)/g, "_"); // replace the encoded character var sPropIDChoiceNo = sPropIDChoice.split("-"); var sPropID = sPropIDChoiceNo[0]; // property ID var sChoiceNo = sPropIDChoiceNo[1]; // choice No var sChoiceName = arrayPropIDChoice[1]; // // Create decorated choices in sorted order // gMapControlIdChoiceName[sPropIDChoice] = sChoiceName; if (typeof(gMapPropIdDecoratedChoices[sPropID]) === 'undefined') { gMapPropIdDecoratedChoices[sPropID] = new Array(); } if (sChoiceName !== '') { var sDecoratedChoiceName = gMapFilterGrpIdToFilterGrpName[sPropID] + ':' + sChoiceName; sDecoratedChoiceName.toUpperCase(); if (GetArrayIndex(gMapPropIdDecoratedChoices[sPropID], sDecoratedChoiceName) == -1) // create a map of decorated choices { gMapPropIdDecoratedChoices[sPropID].push(sDecoratedChoiceName); InsertSort(gMapPropIdDecoratedChoices[sPropID]); // sort } } // // Cache filters // if (typeof(gMapFilters[sPropID]) === "undefined") { gMapFilters[sPropID] = new ProductProperties(); // create a map of properties with the property ID as key } // // Create a map of product property choices with the key as ChoiceNo (1, 2, 3...) // if (typeof(gMapFilters[sPropID].m_mapChoices[sChoiceNo]) === "undefined") { gMapFilters[sPropID].m_mapChoices[sChoiceNo] = new FilterChoiceDetails(); // create a map of choices with choice ID as key } if (typeof(gMapFilters[sPropID].m_mapChoices[sChoiceNo]) !== "undefined") { SetDefinedChoices(gMapFilters[sPropID].m_mapChoices[sChoiceNo], sPropID, sPropIDChoice, sChoiceName); // set the defined choices } } } } /*********************************************************************** * * SetDefinedChoices - Get property choices count * * Inputs: objDefinedChoices - property choice object * sPropID - property ID * sChoiceID - choice ID (say, S_145-1) * sChoiceName - choice name * * Returns: - nothing * ************************************************************************/ function SetDefinedChoices(objDefinedChoices, sPropID, sChoiceID, sChoiceName) { objDefinedChoices.m_sChoiceID = sChoiceID; // set the choice ID objDefinedChoices.m_sChoiceName = sChoiceName; // set the choice name gMapFilters[sPropID].m_bShow = false; // mark to show this property } /*********************************************************************** * * CachePriceBandPriceRange - Cache the formatted price bands * * Returns: - nothing * ************************************************************************/ function CachePriceBandPriceRange() { if (typeof(pg_arrayPriceBandRange) === "undefined") { return; // return if the the global variable is undefined } // // Create map of price bands with the key as the priceband id // for (var nPRIndx = 0; nPRIndx < pg_arrayPriceBandRange.length; nPRIndx++) { var arrPriceBand = pg_arrayPriceBandRange[nPRIndx].split(":"); var sPriceBandId = arrPriceBand[0]; gMapPriceBandPriceRange[sPriceBandId] = arrPriceBand[1]; } } /*********************************************************************** * * CreateFilterPriceBandOptions - Create filter price band options dynamically * * Returns: - nothing * ************************************************************************/ function CreateFilterPriceBandOptions() { // // 1. Read the filter priceband layout based on id "FilterPriceBandOptions" // 2. Read the filter priceband options template using the id "PriceOptionTemplate" // 3. Replace the Filter Tags with the appropriate value and generate the list of options // // Sample filter option template: // ------------------------------ // <div id="PriceOptionTemplate" style="display:none;"> // <input type="checkbox" value="<Actinic:PriceIndex></Actinic:PriceIndex>" name="PR" id="<Actinic:PriceIndex></Actinic:PriceIndex>"/> // <label for="<Actinic:PriceIndex></Actinic:PriceIndex>"><Actinic:PriceBand></Actinic:PriceBand></label> // <br/> // </div> // var sFilterElement = ''; // filter element from price band options template var sFilterOptions = ''; // filter tags option from price option template sFilterElement = document.getElementById('FilterPriceBandOptions'); sFilterOptions = document.getElementById('PriceOptionTemplate'); if ((sFilterElement === null) || (sFilterOptions === null)) { var sErrorMsg = "Tag with the id \"FilterPriceBandOptions\" OR \"PriceOptionTemplate\" is not found in filter option layout, \ filter count might not work for price band"; ShowError(sErrorMsg, g_ErrorCode.TAG); return; // return if undefined } // // Hide the price band label when all option count zero // var bHideLabel = false; // hide label? if ((IsHideChoiceWithZeroResults() && IsFilterCountEnabled()) || (IsFilterCountEnabled() && g_bFirstLoad)) // check for hide filter group empty/all count 0 options for onload { var sPriceLabel = document.getElementById('PR'); if (!gMapFilters['PR'].m_bShow) { sPriceLabel.style.display = "none"; // hide label bHideLabel = true; } else { sPriceLabel.style.display = "block"; // show label bHideLabel = false; } } var sFilterOptionsTemplate = sFilterOptions.outerHTML; var sFilterOptionTemplate = sFilterOptions.innerHTML; var sDummyFilterOptionTemplate = ''; var sResultOptions = ''; var sControl = GetLayoutType(sFilterOptionTemplate); // get layout type // // Create Select start template // var sPriceOptionTemplateSelectTemplate = ''; // Price option select template var sPriceOptionTemplateSelectStart = ''; // select opening tag var sPriceOptionTemplateSelectEnd = ''; // select closing tag var sPriceOptionTemplateSelect = ''; // select tag sPriceOptionTemplateSelect = document.getElementById('PriceOptionTemplateSelect'); if (sPriceOptionTemplateSelect !== null) { sPriceOptionTemplateSelectTemplate = sPriceOptionTemplateSelect.outerHTML; var sPriceOptionTemplateSelectContent = sPriceOptionTemplateSelect.innerHTML; var sSelectTagIndex = sPriceOptionTemplateSelectContent.toLowerCase().indexOf("</act:select>"); // // Format select tag used for list controls // if (sSelectTagIndex > 0) { sPriceOptionTemplateSelectStart = sPriceOptionTemplateSelectContent.substring(0, sSelectTagIndex); sPriceOptionTemplateSelectStart = sPriceOptionTemplateSelectStart.replace(/(ACT:SELECT)/ig, 'select'); sPriceOptionTemplateSelectEnd = "</select>"; } } // // Manipulation of UL tags // var sPriceOptionStartULElement = ''; var sPriceOptionStartULContent = ''; var sPriceOptionStartULTemplate = ''; var sPriceOptionEndULElement = ''; var sPriceOptionEndULContent = ''; var sPriceOptionEndULTemplate = ''; sPriceOptionStartULElement = document.getElementById('PriceOptionTemplateStartUL'); if (sPriceOptionStartULElement !== null) { sPriceOptionStartULContent = sPriceOptionStartULElement.innerHTML; sPriceOptionStartULTemplate = sPriceOptionStartULElement.outerHTML; sPriceOptionStartULContent = sPriceOptionStartULContent.replace(/(&lt;)/ig, '<'); sPriceOptionStartULContent = sPriceOptionStartULContent.replace(/(&gt;)/ig, '>'); } sPriceOptionEndULElement = document.getElementById('PriceOptionTemplateEndUL'); if (sPriceOptionEndULElement !== null) { sPriceOptionEndULContent = sPriceOptionEndULElement.innerHTML; sPriceOptionEndULTemplate = sPriceOptionEndULElement.outerHTML; sPriceOptionEndULContent = sPriceOptionEndULContent.replace(/(&lt;)/ig, '<'); sPriceOptionEndULContent = sPriceOptionEndULContent.replace(/(&gt;)/ig, '>'); } // // Create default options if dropdown listbox layout used // if (!bHideLabel && (sPriceOptionTemplateSelectTemplate !== '') && IsDropDownListBox(sPriceOptionTemplateSelectTemplate)) { sDummyFilterOptionTemplate = sFilterOptionTemplate; sDummyFilterOptionTemplate = sDummyFilterOptionTemplate.replace(/(&lt;Actinic:PriceIndex&gt;&lt;\/Actinic:PriceIndex&gt;)/ig, '-1'); sDummyFilterOptionTemplate = sDummyFilterOptionTemplate.replace(/(<Actinic:PriceIndex><\/Actinic:PriceIndex>)/ig, '-1'); sDummyFilterOptionTemplate = sDummyFilterOptionTemplate.replace(/(<Actinic:PriceBand><\/Actinic:PriceBand>)/ig, 'Any'); // devfault option var sKey = "PR:-1"; var sSelection = ''; if (typeof(gMapCtrlSelections[sKey]) !== "undefined") { sSelection = "selected"; // default list box } sDummyFilterOptionTemplate = sDummyFilterOptionTemplate.replace(/(ActinicDisabledCtrl=\"\")/ig, ''); sDummyFilterOptionTemplate = sDummyFilterOptionTemplate.replace(/(ActinicDisabledStyle=\"\")/ig, ''); sDummyFilterOptionTemplate = sDummyFilterOptionTemplate.replace(/(ActinicCustomSelection=\"\")/ig, sSelection); sDummyFilterOptionTemplate = sDummyFilterOptionTemplate.replace(/(ACT:OPTION)/ig, 'option'); sDummyFilterOptionTemplate = sDummyFilterOptionTemplate.replace(/(<Actinic:HiddentInput><\/Actinic:HiddentInput>)/ig, ''); // hidden parameter sResultOptions += sDummyFilterOptionTemplate; } // // Create other price options // var nCount = 0; var nListCount = 1; // default size is one! sDummyFilterOptionTemplate = ''; // clear off for (var nPRIndx = 0; nPRIndx < gArrayPriceIDs.length; nPRIndx++) { var sPriceId = gArrayPriceIDs[nPRIndx]; if (typeof(gMapFilters['PR'][sPriceId]) === "undefined" || gMapFilters['PR'][sPriceId].m_bHideAlways) // hide always? { continue; } sHiddenInput = ""; nCount = gMapFilters['PR'][sPriceId].m_nCount; // get the price band count if ((!IsFilterCountEnabled()) || // filter not enabled? ((IsHideChoiceWithZeroResults() && nCount > 0) || (!IsHideChoiceWithZeroResults()))) { nListCount++; // // Replace "Price Index", "Price Band" with count and Selection (checked / selected) // sDummyFilterOptionTemplate = sFilterOptionTemplate; sDummyFilterOptionTemplate = sDummyFilterOptionTemplate.replace(/(&lt;Actinic:PriceIndex&gt;&lt;\/Actinic:PriceIndex&gt;)/ig, gArrayPriceIDs[nPRIndx]); sDummyFilterOptionTemplate = sDummyFilterOptionTemplate.replace(/(<Actinic:PriceIndex><\/Actinic:PriceIndex>)/ig, gArrayPriceIDs[nPRIndx]); var sPriceBand = gMapPriceBandPriceRange[gArrayPriceIDs[nPRIndx]].replace(/(&nbsp;)/ig, ' ') if (IsFilterCountEnabled()) { sPriceBand += ' (' + nCount + ')'; } sDummyFilterOptionTemplate = sDummyFilterOptionTemplate.replace(/(<Actinic:PriceBand><\/Actinic:PriceBand>)/ig, sPriceBand); // // Remember the previous selection // var sKey = "PR:" + gArrayPriceIDs[nPRIndx]; var sSelection = ""; var sDisabledStyle = ""; // disabled style for label var sDisabledCtrl = ""; // disabled control type if (typeof(gMapCtrlSelections[sKey]) !== "undefined") { if (sControl === 'LIST') { sSelection = "selected"; // list box } else if (sControl === 'LINKS') { // // Edit style for submit button // sSelection = "style=\"color:red\""; // clickable links sHiddenInput = "<input type=\"hidden\" value=\"" + gArrayPriceIDs[nPRIndx] + "\" name=\"hf_PR\" id=\"hf_PR\"/>"; } else { sSelection = "checked"; // radio button / check box } } if (IsFilterCountEnabled() && !IsHideChoiceWithZeroResults()) { if (sControl === 'LIST') { if (!(nCount > 0)) { sDisabledCtrl = "disabled=\"disabled\""; // disable lists } } else if (sControl === 'LINKS') { if (!(nCount > 0)) { sDisabledCtrl = "disabled=\"disabled\""; // disable sDisabledStyle = "style=\"color:gray;cursor:default\""; // make gray } } else { if (!(nCount > 0)) { sDisabledCtrl = "disabled=\"disabled\""; // disable buttons (check box/radio buttons) sDisabledStyle = "style=\"color:gray\""; } } } sDummyFilterOptionTemplate = sDummyFilterOptionTemplate.replace(/(ActinicDisabledCtrl=\"\")/ig, sDisabledCtrl); sDummyFilterOptionTemplate = sDummyFilterOptionTemplate.replace(/(ActinicDisabledStyle=\"\")/ig, sDisabledStyle); sDummyFilterOptionTemplate = sDummyFilterOptionTemplate.replace(/(ACT:OPTION)/ig, 'option'); // replace custom tag "ACT:OPTION" with "option" sDummyFilterOptionTemplate = sDummyFilterOptionTemplate.replace(/(ActinicCustomSelection=\"\")/ig, sSelection); sDummyFilterOptionTemplate = sDummyFilterOptionTemplate.replace(/(<Actinic:HiddentInput><\/Actinic:HiddentInput>)/ig, sHiddenInput); sResultOptions += sDummyFilterOptionTemplate; } } // // Update the count if any! // if (!bHideLabel) // hide label? { sPriceOptionTemplateSelectStart = sPriceOptionTemplateSelectStart.replace(/(&lt;Actinic:ListCount&gt;&lt;\/Actinic:ListCount&gt;)/ig, nListCount); sPriceOptionTemplateSelectStart = sPriceOptionTemplateSelectStart.replace(/(<Actinic:ListCount><\/Actinic:ListCount>)/ig, nListCount); } else { sPriceOptionTemplateSelectStart = ''; sPriceOptionStartULContent = ''; sResultOptions = ''; sPriceOptionEndULContent = ''; sPriceOptionTemplateSelectEnd = ''; } // // Update the filter price band content with the template and the needed filter options // sFilterElement.innerHTML = (sPriceOptionTemplateSelectTemplate + // select tag template sFilterOptionsTemplate + // option template sPriceOptionStartULTemplate + // start UL template sPriceOptionEndULTemplate + // end UL template sPriceOptionTemplateSelectStart + // select start tag sPriceOptionStartULContent + // opening ul tag sResultOptions + // option tag sPriceOptionEndULContent + // closing ul tag sPriceOptionTemplateSelectEnd); // select end tag } /*********************************************************************** * * CreateFilterPropertyOptions - Create filter properties options dynamically * * Returns: - nothing * ************************************************************************/ function CreateFilterPropertyOptions() { // // 1. Read the filter property layout based on id "FilterPropertyOptions_PropertyId" // 2. Read the filter property options template using the id "PropOptionTemplate_PropertyId" // 3. Replace the Filter Tags with the appropriate value and generate the list of options // // Sample filter property option template: // --------------------------------------- // <div id="PropOptionTemplate_<actinic:variable name="FilterPropControlName" />" style="display:none;"> // <input type="checkbox" name="<Actinic:FilterPropValueName></Actinic:FilterPropValueName>" value="<Actinic:FilterPropValue></Actinic:FilterPropValue>" id="<Actinic:FilterPropChoiceID></Actinic:FilterPropChoiceID>"/> // <label for="<Actinic:FilterPropChoiceID></Actinic:FilterPropChoiceID>"><Actinic:FilterPropText></Actinic:FilterPropText></label> // <br/> // </div> // for (var nPropIndx = 0; nPropIndx < gArrProperty.length; nPropIndx++) { if (typeof(gArrProperty[nPropIndx]) !== "undefined") { var sPropID = gArrProperty[nPropIndx]; var sFilterPropTagName = "FilterPropertyOptions_" + sPropID; // get filter property option content var sFilterPropOptionTagName = "PropOptionTemplate_" + sPropID; // get property option template var sFilterPropertyElement = ''; // filter property element template var sFilterPropertyTag = ''; // filter property tag template sFilterPropertyElement = document.getElementById(sFilterPropTagName); sFilterPropertyTag = document.getElementById(sFilterPropOptionTagName); // // Check if the templates are defined // if ((sFilterPropertyElement === null) || (sFilterPropertyTag === null)) { var sErrorMsg = "Tag with the id" + sFilterPropTagName + " OR " + sFilterPropOptionTagName + "is not found in filter option layout, \ filter count might not work for the property ID " + sPropID; ShowError(sErrorMsg, g_ErrorCode.TAG); continue; // continue if undefined } var sFilterPropertyOptionTagContent = sFilterPropertyTag.innerHTML; var sFilterPropertyOptionTemplate = sFilterPropertyTag.outerHTML; var sControl = GetLayoutType(sFilterPropertyOptionTagContent); // get layout type // // Show only the options with count non-zero // var sDummyFilterPropOptionTemplate = ''; var sResultOptions = ''; var bHidden = false; // is property hidden? if (typeof(gMapFilters[sPropID]) !== "undefined") { var sArrayChoices = gMapFilters[sPropID].m_mapChoices; var nChoiceInx = 1; // // Check if the property group to be shown at all // Get element by id name (say S&#95;451) and hide/show // if ((IsHideChoiceWithZeroResults() && IsFilterCountEnabled()) || (IsFilterCountEnabled() && g_bFirstLoad) // check for hide filter group empty/all count 0 options for onload || (gMapFilters[sPropID].m_bHideAlways)) // hide always? { var sPropLabel = document.getElementById(sPropID); if ((g_bFirstLoad && gMapFilters[sPropID].m_bHideAlways) || // onload and hide always (g_bFirstLoad && !gMapFilters[sPropID].m_bShow && IsHideChoiceWithZeroResults()) || // onload, hide zero results & all filter options with zero counts (!g_bFirstLoad && !gMapFilters[sPropID].m_bShow)) // not onload but all options count with zero { sPropLabel.style.display = "none"; // hide label sFilterPropertyElement.style.display = "none"; // hide filter property element bHidden = true; // property not hidden } else { sPropLabel.style.display = "block"; // show label sFilterPropertyElement.style.display = "block"; // show filter property element bHidden = false; } } // // Manipulate for list controls // var sPropOptionSelectContent = ""; // select tag for property options (say: <ACT:SELECT ...></ACT:SELECT>) var sPropOptionSelectTemplate = ""; // select template (say: <div id="PropOptionTemplateSelect_PropId><ACT:SELECT ...></ACT:SELECT></div>) var sPropOptionSelectTemplateStart = ""; // select opening tag (say: <select ...>) var sPropOptionSelectTemplateEnd = ""; // select ending tag (say: </select>) var sPropOptionSelectElement = ""; // select template element var sPropOptionTemplateSelectId = "PropOptionTemplateSelect_" + sPropID; sPropOptionSelectElement = document.getElementById(sPropOptionTemplateSelectId); if (sPropOptionSelectElement !== null) { sPropOptionSelectContent = sPropOptionSelectElement.innerHTML; sPropOptionSelectTemplate = sPropOptionSelectElement.outerHTML; // // Manipulate select tag // if (!bHidden) // not hidden? { var sSelectTagIndex = sPropOptionSelectContent.toLowerCase().indexOf("</act:select>"); if (sSelectTagIndex > 0) { sPropOptionSelectTemplateStart = sPropOptionSelectContent.substring(0, sSelectTagIndex); sPropOptionSelectTemplateStart = sPropOptionSelectTemplateStart.replace(/(ACT:SELECT)/ig, 'select'); sPropOptionSelectTemplateStart = sPropOptionSelectTemplateStart.replace(/(&lt;Actinic:FilterPropValueName&gt;&lt;\/Actinic:FilterPropValueName&gt;)/ig, sPropID); sPropOptionSelectTemplateStart = sPropOptionSelectTemplateStart.replace(/(<Actinic:FilterPropValueName><\/Actinic:FilterPropValueName>)/ig, sPropID); sPropOptionSelectTemplateEnd = "</select>"; } } } var bDropDwnLstBox = IsDropDownListBox(sPropOptionSelectContent); // // Manipulation of UL tags // var sPropOptionStartULElement = ''; var sPropOptionStartULContent = ''; var sPropOptionStartULTemplate = ''; var sPropOptionEndULElement = ''; var sPropOptionEndULContent = ''; var sPropOptionEndULTemplate = ''; sPropOptionStartULElement = document.getElementById('PropOptionTemplateStartUL_' + sPropID); if (sPropOptionStartULElement !== null) { sPropOptionStartULContent = sPropOptionStartULElement.innerHTML; sPropOptionStartULTemplate = sPropOptionStartULElement.outerHTML; sPropOptionStartULContent = sPropOptionStartULContent.replace(/(&lt;)/ig, '<'); sPropOptionStartULContent = sPropOptionStartULContent.replace(/(&gt;)/ig, '>'); } sPropOptionEndULElement = document.getElementById('PropOptionTemplateEndUL_' + sPropID); if (sPropOptionEndULElement !== null) { sPropOptionEndULContent = sPropOptionEndULElement.innerHTML; sPropOptionEndULTemplate = sPropOptionEndULElement.outerHTML; sPropOptionEndULContent = sPropOptionEndULContent.replace(/(&lt;)/ig, '<'); sPropOptionEndULContent = sPropOptionEndULContent.replace(/(&gt;)/ig, '>'); } // // Render filter property options // var nListCount = 0; // list count while (typeof(sArrayChoices[nChoiceInx]) !== "undefined") { var bIncludeAny = false; if (sArrayChoices[nChoiceInx].m_sChoiceName === '') // option 'Any' { if (bDropDwnLstBox && !bHidden) // drop down and not hidden { bIncludeAny = true; } else { nChoiceInx++; continue; } } if (sArrayChoices[nChoiceInx].m_sChoiceID === '' || // continue if choiceID is empty (sArrayChoices[nChoiceInx].m_bHideAlways && !bIncludeAny)) // hide the option always? { nChoiceInx++; continue; } var sHiddenInput = ""; var nCount = sArrayChoices[nChoiceInx].m_nChoiceCount; // choice count if ((!IsFilterCountEnabled()) || // filter not enabled? ((IsHideChoiceWithZeroResults() && nCount > 0) || (!IsHideChoiceWithZeroResults()) || bIncludeAny)) { nListCount++; sDummyFilterPropOptionTemplate = sFilterPropertyOptionTagContent; // // 'name' attribute // sDummyFilterPropOptionTemplate = sDummyFilterPropOptionTemplate.replace(/(&lt;Actinic:FilterPropValueName&gt;&lt;\/Actinic:FilterPropValueName&gt;)/ig, sPropID); sDummyFilterPropOptionTemplate = sDummyFilterPropOptionTemplate.replace(/(<Actinic:FilterPropValueName><\/Actinic:FilterPropValueName>)/ig, sPropID); // // 'value' attribute // var sValue = sArrayChoices[nChoiceInx].m_sChoiceName; sDummyFilterPropOptionTemplate = sDummyFilterPropOptionTemplate.replace(/(&lt;Actinic:FilterPropValue&gt;&lt;\/Actinic:FilterPropValue&gt;)/ig, sValue); sDummyFilterPropOptionTemplate = sDummyFilterPropOptionTemplate.replace(/(<Actinic:FilterPropValue><\/Actinic:FilterPropValue>)/ig, sValue); // // Remember previous selection // var sKey = sPropID + "-" + nChoiceInx; // example: S_145-1 var sSelection = ""; var sDisabledCtrl = ""; // disable control type var sDisabledStyle = ""; // disable label style if (typeof(gMapCtrlSelections[sKey]) !== "undefined" && !g_bClearAll) { if (sControl === 'LIST') { sSelection = "selected"; // list box } else if (sControl === 'LINKS') { // // Edit style for submit button // sSelection = "style=\"color:red\""; // click able links sHiddenInput = "<input type=\"hidden\" value=\"" + sArrayChoices[nChoiceInx].m_sChoiceName + "\" name=\"hf_" + sArrayChoices[nChoiceInx].m_sChoiceID + "\" id=\"hf_" + sPropID + "\"/>"; } else { sSelection = "checked"; // check box } } if (IsFilterCountEnabled() && !IsHideChoiceWithZeroResults() && !bIncludeAny) { if (sControl === 'LIST') { if (!(nCount > 0)) { sDisabledCtrl = "disabled=\"disabled\""; // disable list } } else if (sControl === 'LINKS') { if (!(nCount > 0)) { sDisabledCtrl = "disabled=\"disabled\""; // disable sDisabledStyle = "style=\"color:gray;cursor:default\""; // make gray } } else { if (!(nCount > 0)) { sDisabledCtrl = "disabled=\"disabled\""; // disable buttons (check box/radio buttons) sDisabledStyle = "style=\"color:gray\""; } } } sDummyFilterPropOptionTemplate = sDummyFilterPropOptionTemplate.replace(/(ACT:OPTION)/ig, 'option'); // replace custom tag "ACT:OPTION" with "option" sDummyFilterPropOptionTemplate = sDummyFilterPropOptionTemplate.replace(/(ActinicDisabledCtrl=\"\")/ig, sDisabledCtrl); sDummyFilterPropOptionTemplate = sDummyFilterPropOptionTemplate.replace(/(ActinicDisabledStyle=\"\")/ig, sDisabledStyle); sDummyFilterPropOptionTemplate = sDummyFilterPropOptionTemplate.replace(/(ActinicCustomSelection=\"\")/ig, sSelection); // // Value 'id' and 'for' attribute // sDummyFilterPropOptionTemplate = sDummyFilterPropOptionTemplate.replace(/(&lt;Actinic:FilterPropChoiceID&gt;&lt;\/Actinic:FilterPropChoiceID&gt;)/ig, sArrayChoices[nChoiceInx].m_sChoiceID); sDummyFilterPropOptionTemplate = sDummyFilterPropOptionTemplate.replace(/(<Actinic:FilterPropChoiceID><\/Actinic:FilterPropChoiceID>)/ig, sArrayChoices[nChoiceInx].m_sChoiceID); // // Replace label tab content // var sLabelText = sArrayChoices[nChoiceInx].m_sChoiceName; if (bIncludeAny) { sLabelText = 'Any'; } if (IsFilterCountEnabled() && !bIncludeAny) // show the count when count is enabled { sLabelText += ' (' + sArrayChoices[nChoiceInx].m_nChoiceCount + ')'; } sDummyFilterPropOptionTemplate = sDummyFilterPropOptionTemplate.replace(/(&lt;Actinic:FilterPropText&gt;&lt;\/Actinic:FilterPropText&gt;)/ig, sLabelText); sDummyFilterPropOptionTemplate = sDummyFilterPropOptionTemplate.replace(/(<Actinic:FilterPropText><\/Actinic:FilterPropText>)/ig, sLabelText); sDummyFilterPropOptionTemplate = sDummyFilterPropOptionTemplate.replace(/(<Actinic:HiddentInput><\/Actinic:HiddentInput>)/ig, sHiddenInput); sResultOptions += sDummyFilterPropOptionTemplate; // result options } nChoiceInx++; } // // Update the count if any! // if (nListCount === 1) { nListCount++; } sPropOptionSelectTemplateStart = sPropOptionSelectTemplateStart.replace(/(&lt;Actinic:ListCount&gt;&lt;\/Actinic:ListCount&gt;)/ig, nListCount); sPropOptionSelectTemplateStart = sPropOptionSelectTemplateStart.replace(/(<Actinic:ListCount><\/Actinic:ListCount>)/ig, nListCount); // // Update the filter property content with the template and the filter needed property options // sFilterPropertyElement.innerHTML = ""; // remove the content sFilterPropertyElement.innerHTML = (sPropOptionStartULTemplate + // opening ul template sPropOptionEndULTemplate + // closing ul template sPropOptionSelectTemplate + // select template sFilterPropertyOptionTemplate + // option template sPropOptionSelectTemplateStart + // opening select tag sPropOptionStartULContent + // opening ul tag sResultOptions + // result option list sPropOptionEndULContent + // closing ul tag sPropOptionSelectTemplateEnd // closing select tag ); // stick the filter options } } } } /*********************************************************************** * * GetLayoutType - Get the layout type * * Inputs: sTemplate - layout template to check * * Returns: - layout type * ************************************************************************/ function GetLayoutType(sTemplate) { var sControl; if (sTemplate.match(/(ACT:OPTION)/igm)) { sControl = 'LIST'; // list controls } else if (sTemplate.match(/(type=\"submit\")/igm) || sTemplate.match(/(type=submit)/igm)) { sControl = 'LINKS'; // clickable links } else { sControl = 'BUTTONS'; // chec kbox or radio buttons } return sControl; } /*********************************************************************** * * IsDropDownListBox - Check if dropdown list layout is used * * Inputs: sTemplate - layout template to check * * Returns: - true/false * ************************************************************************/ function IsDropDownListBox(sTemplate) { var bDropDownList = false; var arrMatch = sTemplate.match(/(ACT:SELECT(.*)size\s*=\s*["\']?([^"\' ]*)["\' ]\s*)/i); if (arrMatch) { if (typeof(arrMatch[3]) !== 'undefined' && arrMatch[3] === '1') // check size { bDropDownList = true; } } else if (sTemplate.match(/(ACT:SELECT)/i)) // dropdown list box { bDropDownList = true; } return bDropDownList; } /*********************************************************************** * * GetControlSelections - Get the control selections and cache as a * map * * Inputs: sCtlrName - selected control name * sContolID - selected control id * sValue - selected control value * * Returns: - nothing * ************************************************************************/ function GetControlSelections(sCtlrName, sContolID, sValue) { // // Map of control selections with the key as below // Example for price band: PR:-1 // Example for properties : S_451-1 // var sKey = ""; if ((sCtlrName === "SX") || (sCtlrName === "PR")) // price band { sKey = sCtlrName + ":" + sContolID; if (sContolID !== '-1') { if (typeof(gMapControlToSelection[sCtlrName]) === 'undefined') { gMapControlToSelection[sCtlrName] = {}; gMapControlToSelection[sCtlrName][sContolID] = ''; } else { gMapControlToSelection[sCtlrName][sContolID] = ''; } } } else // properties { sKey = sContolID; // // Create map of property id to selection // if (sKey !== '' && sValue !== '') { if (typeof(gMapControlIdChoiceName[sKey]) !== 'undefined') { var sChoiceName = gMapControlIdChoiceName[sKey]; var sPropId = sKey.split('-')[0]; var sTmpSelKey = gMapFilterGrpIdToFilterGrpName[sPropId] + ':' + sChoiceName; var sSelKey = sTmpSelKey.toUpperCase(); if (typeof(gMapPropIdToSelections[sPropId]) === 'undefined') { gMapPropIdToSelections[sPropId] = new Array() // property id to selections } if (GetArrayIndex(gMapPropIdToSelections[sPropId], sSelKey) == -1) { gMapPropIdToSelections[sPropId].push(sSelKey); if (gMapPropIdToSelections[sPropId].length > 0) { InsertSort(gMapPropIdToSelections[sPropId]); } } if (!(typeof(gMapPropCtrlSelections[sSelKey]) !== 'undefined')) { gMapPropCtrlSelections[sSelKey] = true; // property control selection } } } if (sKey !== '' && sCtlrName !== '' && sValue !== '') { if (typeof(gMapControlToSelection[sCtlrName]) === 'undefined') { gMapControlToSelection[sCtlrName] = {}; gMapControlToSelection[sCtlrName][sKey] = ''; } else { gMapControlToSelection[sCtlrName][sKey] = ''; } } } if (sKey !== '') { gMapCtrlSelections[sKey] = true; } } /*********************************************************************** * * ClearCtrlSelectionMap - Clear control selection map * * Returns: - nothing * ************************************************************************/ function ClearCtrlSelectionMap() { gMapCtrlSelections = {}; // clear map gMapControlToSelection = {}; gMapPropCtrlSelections = {}; // clear gMapPropIdToSelections = {}; // clear } /*********************************************************************** * * IsFilterCountEnabled - Check if filter count is enabled * * Returns: - true/false * ************************************************************************/ function IsFilterCountEnabled() { if (typeof(pg_bEnableFilterCount) !== "undefined" && pg_bEnableFilterCount) { return true; } return false; } /*********************************************************************** * * GetResultLayoutUsed - Get the result layout used * * Returns: - layout type (g_eResultLayout) * ************************************************************************/ function GetResultLayoutUsed() { var eResultLayout = g_eResultLayout.UNDEFINED; var sListColCountElement = ''; sListColCountElement = document.getElementById('S_LISTCOLCOUNT'); if (sListColCountElement) // table layout will { eResultLayout = g_eResultLayout.TABULAR; // // Get the column count as well // g_nListColCount = parseInt(sListColCountElement.innerHTML); } else { eResultLayout = g_eResultLayout.STD; } return eResultLayout; } /*********************************************************************** * * IsHostMode - Check if site is in host mode * * Returns: - true/false * ************************************************************************/ function IsHostMode() { if (typeof(pg_sShopID) !== "undefined" && pg_sShopID) { return true; } return false; } /*********************************************************************** * * SetDefaultSelection - Set the default filter options selections * * Returns: - nothing * ************************************************************************/ function SetDefaultSelection() { GetControlSelections('PR', '-1'); // set default to price band labeled 'Any' GetControlSelections('SX', '-1'); // set default to section labeled 'Any' // // Set the default properties in map // if (typeof(pg_arrayDefaultProperties) === "undefined") { return; } for (var nDefChoiceIndx = 0; nDefChoiceIndx < pg_arrayDefaultProperties.length; nDefChoiceIndx++) { if ((typeof(pg_arrayDefaultProperties[nDefChoiceIndx]) !== "undefined") && (pg_arrayDefaultProperties[nDefChoiceIndx] !== null)) { var sPropID = pg_arrayDefaultProperties[nDefChoiceIndx].replace(/(&#95;)/g, "_"); // replace the encoded character var sPropIDChoiceID = sPropID.split('-'); gMapDefCtrlSelections[sPropIDChoiceID[0]] = sPropIDChoiceID[1]; GetControlSelections(sPropIDChoiceID[0], sPropID, gMapControlIdChoiceName[sPropID]); } } } /*********************************************************************** * * CheckHashChangeEvent - Correct the CGI urls from the url in browser * * Returns: - nothing * ************************************************************************/ function CheckHashChangeEvent() { if (IsPreview()) // preview? { return; } var nIEVersion = GetIEVersion(); // get the IE version if ((nIEVersion < 8) && (nIEVersion !== 0)) // if IE and version < 9 { // have to explicitly call on a hash change var prevHash = ''; // so that initial setting of hash change is detected /*********************************************************************** * * HashCheck - Check if the hash has changed - using prevHash in closure * ************************************************************************/ function HashCheck() { if (window.location.hash !== prevHash) // has the hash changed? { HashChangeHandler(); // handle change - required hash change event in IE ver < 9 prevHash = window.location.hash; // remember the previous hash } } HashCheck(); // check for a hash value now - just in case window.setInterval(HashCheck, 500); // check every 500ms for another change } else { // // Newer browsers can just use hash change handler // AddEvent(window, "hashchange", HashChangeHandler); if (window.location.hash) // check if there is a hash value { HashChangeHandler(); // yes, trigger a handler call immediately } } } /*********************************************************************** * * HashChangeHandler - Hash change event handler * * Returns: - nothing * ************************************************************************/ function HashChangeHandler() { if (g_bUseStorageSortPage) { g_bUseStorageSortPage = false; return; } ResetSortOrder(); SetStoredPageNumber(); // set the page number if (window.location.hash.search('usestorage') != -1) // use storage? { SetSelectionMapsFromStorage(); // Set the selection map from storage settings if (IsFilterCountEnabled()) { // // Filter products for count alone // OnFilter(null, null, true); // filter only for count } else { GenerateDynamicFilterOptions(); // generate dynamic filter options if (IsFilterAsDefaultView()) { OnFilter(null, null, true); // filter only for count } else { OnFilter(null, null, false); // filter only for result } } return; } // // Hide the filter result and show the section content // var resultAreaElement = ''; resultAreaElement = document.getElementById("filter_results_area"); // get filter result content if (resultAreaElement) // go ahead when section has marked for filtering { var contentPageElement = ''; contentPageElement = document.getElementById('ContentPage'); // get content page if (contentPageElement) { contentPageElement.style.display = "block"; // show the section content } resultAreaElement.style.display = "none"; // hide the filter result if (window.location.hash != '') { window.location.hash = window.location.hash; // scrolling to the anchor } ShowSectionContent(); // show the section content HideAllClearButtons(); // hide all clear buttons ResetStorage(g_eFilterSettings.FILTER); // clear filter storage settings } } /*********************************************************************** * * IsHideChoiceWithZeroResults - Check if filter options need to be hidden * * Returns: - true/false * ************************************************************************/ function IsHideChoiceWithZeroResults() { if (typeof(pg_bHideChoiceWithZeroResults) !== "undefined" && (pg_bHideChoiceWithZeroResults === 1)) { return true; } return false; } /*********************************************************************** * * CreateClearButton - Create clear button dynamically * * Inputs: sID - property ID * * Returns: - nothing * ************************************************************************/ function CreateClearButton(sID) { var sClearButtonElement = document.getElementById(sID + '-clear-button'); // get the clear button elements if (sClearButtonElement) // is already there? { sClearButtonElement.style.cssText = 'display:block'; // ensure to show return; } // // Create the clear button // var sFilterHeaderElement = document.getElementById(sID); if (sFilterHeaderElement) { var sClearButton = '<a href=\'javascript:ClearFilterOptions(\"' + sID + '\");\' id="' + sID + '-clear-button" class="clear-button">Clear</a>'; sFilterHeaderElement.innerHTML = sFilterHeaderElement.innerHTML + sClearButton; } } /*********************************************************************** * * ShowHideClearButton - Show or hide the clear button dynamically * * Inputs: bShow - show/hide the clear button * sID - clear button ID * * Returns: - nothing * ************************************************************************/ function ShowHideClearButton(bShow, sID) { var sClearButtonElement = document.getElementById(sID + '-clear-button'); // get the clear button elements if (sClearButtonElement) { if (bShow) // show clear button { sClearButtonElement.style.cssText = 'display:block'; gMapPropIdToBtnClearStatus[sID] = true; // button shown } else // hide clear button { sClearButtonElement.style.cssText = 'display:none'; gMapPropIdToBtnClearStatus[sID] = false; // button hidden } } else if (bShow) { CreateClearButton(sID); gMapPropIdToBtnClearStatus[sID] = true; // button shown } if (GetClearButtonCount() < 1) { ShowSectionContent(); // show section content } } /*********************************************************************** * * GetClearButtonCount - Get clear button count that are shown * * Returns: - nothing * ************************************************************************/ function GetClearButtonCount() { var nCount = 0; for (sPropId in gMapPropIdToBtnClearStatus) { if (gMapPropIdToBtnClearStatus[sPropId] === true) { nCount++; } } return nCount; } /*********************************************************************** * * ClearFilterOptions - Clear filter options dynamically * * Inputs: sFilterHeaderID - filter header ID * * Returns: - nothing * ************************************************************************/ function ClearFilterOptions(sFilterHeaderID) { if (GetClearButtonCount() < 2) // single clear button? { OnClearAllOptions(); // same behaviour of Clear All } else { ClearFilterChoices(sFilterHeaderID); // clear filter choices OnFilter(); // filter based on the new options } } /*********************************************************************** * * ClearFilterChoices - Clear filter choices * * Inputs: sFilterHeaderID - filter header ID * * Returns: - nothing * ************************************************************************/ function ClearFilterChoices(sFilterHeaderID) { // // Clear filter options // var sFilterForm = document.forms['filter']; if (typeof(sFilterForm) !== "undefined") { var sFilterFormElements = document.forms['filter'].elements; // filter form elements for (var nIndex = 0; nIndex < sFilterFormElements.length; nIndex++) { var eControlType = GetControlType(sFilterFormElements[nIndex]); if ((sFilterHeaderID === sFilterFormElements[nIndex].name) && (eControlType !== g_eControlType.UNDEFINED)) { ResetSelectionCheck(eControlType, sFilterFormElements[nIndex], sFilterHeaderID); if (eControlType === g_eControlType.LINK) { break; // call only once for clickable links } } } } } /*********************************************************************** * * GetControlType - Get the control type * * Inputs: sControl - control element * * Returns: - nothing * ************************************************************************/ function GetControlType(sControl) { var eControlType = g_eControlType.UNDEFINED; var sControlType = sControl.type; var sControlTagName = sControl.tagName; if (sControlTagName === 'INPUT') { if (sControlType === 'checkbox' || sControlType === 'radio') { eControlType = g_eControlType.BUTTON; } else if (sControlType === 'submit') { eControlType = g_eControlType.LINK; } } else if (sControlTagName === 'SELECT') { eControlType = g_eControlType.LIST; } return (eControlType); } /*********************************************************************** * * ResetSelectionCheck - Reset filter options * * Inputs: eControlType - control type (g_eControlType) * sElement - control element * sControlID - control ID * * Returns: - nothing * ************************************************************************/ function ResetSelectionCheck(eControlType, sElement, sControlID) { switch (eControlType) // control type { case g_eControlType.BUTTON: // check box/radio buttons if (sElement.value != '-1' || sElement.value != '') { sElement.checked = false; } break; case g_eControlType.LIST: // list controls for (var nElmCount = 0; nElmCount < sElement.options.length; nElmCount++) { if (sElement.options[nElmCount].value != '-1' || sElement.options[nElmCount].value != '') { sElement.options[nElmCount].selected = false; } } break; case g_eControlType.LINK: // clickable links // // Remove the selection // var elHfElement = document.getElementById('hf_' + sControlID); if (elHfElement) { var sValue = elHfElement.value; var sLabelID = ''; if (sControlID === 'PR') { sLabelID = 'lbl_' + sValue; } else if (sControlID === 'SX') { sLabelID += 'lbl_SX_' + sValue; } else { var sLabelFor = elHfElement.name.split('hf_'); sLabelID = 'lbl_' + sLabelFor[1]; } var elLabel = document.getElementById(sLabelID); if (elLabel) { elLabel.style.cssText = ''; } elHfElement.parentNode.removeChild(elHfElement); } break; default: break; } } /*********************************************************************** * * HideModifyStaticControls - Hide/modify static controls * * Returns: - nothing * ************************************************************************/ function HideModifyStaticControls() { // // Hide update button at down // var sUpdateButtonBottomElement = document.getElementById('update_btn'); // update button bottom if (sUpdateButtonBottomElement) { var sFilterBtnWrprElmnt = sUpdateButtonBottomElement.parentNode; if (sFilterBtnWrprElmnt) { sFilterBtnWrprElmnt.parentNode.removeChild(sFilterBtnWrprElmnt); } } // // Modify the update button at top // var sUpdateButtonTopElement = document.getElementById('update_lnk'); // update button top if (sUpdateButtonTopElement) { sUpdateButtonTopElement.setAttribute('onclick', 'javascript:OnClearAllOptions(); return false;'); sUpdateButtonTopElement.value = 'Clear All'; } } /*********************************************************************** * * OnClearAllOptions - Clear all options to default * * Returns: - nothing * ************************************************************************/ function OnClearAllOptions() { if (GetClearButtonCount() < 1) { return; // return if nothing to clear } ShowSectionContent(); // show the section content HideAllClearButtons(); // hide all clear buttons ResetStorage(g_eFilterSettings.FILTER); // clear filter storage settings if (g_nCurrenPageNumber != -1) { ResetStorage(g_eFilterSettings.PAGINATION); // rest the pagination } } /*********************************************************************** * * ShowSectionContent - Show the section content * * Returns: - nothing * ************************************************************************/ function ShowSectionContent() { // // If filter view is not default, show the original section content // if (!IsFilterAsDefaultView()) { var elFilterResult = document.getElementById('filter_results_area'); if (elFilterResult) { elFilterResult.style.cssText = 'display:none'; } var elContentPage = document.getElementById('ContentPage'); if (elContentPage) { elContentPage.style.cssText = 'display:block'; } // // If carousel visibility changes they have to be reloaded // ReloadCarousels(); } } /*********************************************************************** * * HideAllClearButtons - Hide all clear buttons * * Returns: - nothing * ************************************************************************/ function HideAllClearButtons() { // // Clear filter choices for each property group where // 'Clear' button is shown // ClearCtrlSelectionMap(); // clear control selections for (var sPropId in gMapPropIdToBtnClearStatus) { if (gMapPropIdToBtnClearStatus[sPropId] === true) { ClearFilterChoices(sPropId); // clear filter choices } } OnFilter(null, null, false, true); // filter only for count } /*********************************************************************** * * CacheFilterSections - Cache filter section into a map * * Returns: - nothing * ************************************************************************/ function CacheFilterSections() { if (typeof pg_arrayFilterSections !== 'undefined') { gMapFilterGrpIdToFilterGrpName['SX'] = 'SX'; gArrFilterGrpIdSorted.push('SX'); gMapFilters['SX'] = {}; gMapFilters['SX'].m_bShow = false; for (var nFltrSecIndx = 0; nFltrSecIndx < pg_arrayFilterSections.length; nFltrSecIndx++) { if ((typeof(pg_arrayFilterSections[nFltrSecIndx]) !== "undefined") && (pg_arrayFilterSections[nFltrSecIndx] !== null)) { var sSectionIDName = pg_arrayFilterSections[nFltrSecIndx].split(':'); var sKey = sSectionIDName[0]; // section ID gMapFilters['SX'][sKey] = new SectionDetails(); gMapFilters['SX'][sKey].m_sSectionName = sSectionIDName[1]; gArraySectionIDs.push(sKey); } } } } /*********************************************************************** * * SectionDetails - Section details class definition * * Returns: - nothing * ************************************************************************/ function SectionDetails() { this.m_sSectionName = ''; // section name this.m_nCount = 0; // count to hold number of prods belong to this this.m_nCumulativeCount = 0; // all product counts including current and sub sections this.m_arrSubSectionIds = new Array(); // sub section IDs this.m_bHideAlways = false; // hide always? } /*********************************************************************** * * CreateFilterSectionOptions - Create filter sections/department options dynamically * * Returns: - nothing * ************************************************************************/ function CreateFilterSectionOptions() { // // 1. Read the filter section layout based on id "FilterSectionOptions" // 2. Read the filter section options template using the id "SectionOptionTemplate" // 3. Replace the Filter Tags with the appropriate value and generate the list of options // // Sample filter section option template: // -------------------------------------- // <div id="SectionOptionTemplate" style="display:none;"> // <input type="checkbox" value="<Actinic:SectionIndex></Actinic:SectionIndex>" name="SX" id="SX_<Actinic:SectionIndex></Actinic:SectionIndex>" ActinicCustomSelection="" ActinicDisabledCtrl=""/> // <label for="SX_<Actinic:SectionIndex></Actinic:SectionIndex>" ActinicDisabledStyle=""><Actinic:SectionName></Actinic:SectionName></label> // <br/> // </div> // var elFilterSection = ''; // filter element from price band options template var elFilterOption = ''; // filter tags option from price option template elFilterSection = document.getElementById('FilterSectionOptions'); elFilterOption = document.getElementById('SectionOptionTemplate'); if ((elFilterSection === null) || (elFilterOption === null)) { var sErrorMsg = "Tag with the id \"FilterSectionOptions\" OR \"SectionOptionTemplate\" is not found in filter option layout, \ filter count might not work for departments"; ShowError(sErrorMsg, g_ErrorCode.TAG); return; // return if undefined } // // Hide the section label when all option count zero // var bHideLabel = false; // hide label? if ((IsHideChoiceWithZeroResults() && IsFilterCountEnabled()) || (IsFilterCountEnabled() && g_bFirstLoad)) // check for hide filter group empty/all count 0 options for onload { var sSectionLabel = document.getElementById('SX'); if (!gMapFilters['SX'].m_bShow) { sSectionLabel.style.display = "none"; // hide label bHideLabel = true; } else { sSectionLabel.style.display = "block"; // show label bHideLabel = false; } } var sFilterSectionOptionTemplateOutput = elFilterOption.outerHTML; var sFilterSectionOptionTemplate = elFilterOption.innerHTML; var sDummyFilterSectionOptionTemplate = ''; var sResultOptions = ''; var sControl = GetLayoutType(sFilterSectionOptionTemplate); // get layout type // // Create Select start template // var sSectionOptionTemplateSelectTemplate = ''; // Price option select template var sSectionOptionTemplateSelectStart = ''; // select opening tag var sSectionOptionTemplateSelectEnd = ''; // select closing tag var sSectionOptionTemplateSelect = ''; // select tag sSectionOptionTemplateSelect = document.getElementById('SectionOptionTemplateSelect'); if (sSectionOptionTemplateSelect !== null) { sSectionOptionTemplateSelectTemplate = sSectionOptionTemplateSelect.outerHTML; var sSectionOptionTemplateSelectContent = sSectionOptionTemplateSelect.innerHTML; var sSelectTagIndex = sSectionOptionTemplateSelectContent.toLowerCase().indexOf("</act:select>"); // // Format select tag used for list controls // if (sSelectTagIndex > 0) { sSectionOptionTemplateSelectStart = sSectionOptionTemplateSelectContent.substring(0, sSelectTagIndex); sSectionOptionTemplateSelectStart = sSectionOptionTemplateSelectStart.replace(/(ACT:SELECT)/ig, 'select'); sSectionOptionTemplateSelectEnd = "</select>"; } } // // Manipulation of UL tags // var sSectionOptionStartULElement = ''; var sSectionOptionStartULContent = ''; var sSectionOptionStartULTemplate = ''; var sSectionOptionEndULElement = ''; var sSectionOptionEndULContent = ''; var sSectionOptionEndULTemplate = ''; sSectionOptionStartULElement = document.getElementById('SectionOptionTemplateStartUL'); if (sSectionOptionStartULElement !== null) { sSectionOptionStartULContent = sSectionOptionStartULElement.innerHTML; sSectionOptionStartULTemplate = sSectionOptionStartULElement.outerHTML; sSectionOptionStartULContent = sSectionOptionStartULContent.replace(/(&lt;)/ig, '<'); sSectionOptionStartULContent = sSectionOptionStartULContent.replace(/(&gt;)/ig, '>'); } sSectionOptionEndULElement = document.getElementById('SectionOptionTemplateEndUL'); if (sSectionOptionEndULElement !== null) { sSectionOptionEndULContent = sSectionOptionEndULElement.innerHTML; sSectionOptionEndULTemplate = sSectionOptionEndULElement.outerHTML; sSectionOptionEndULContent = sSectionOptionEndULContent.replace(/(&lt;)/ig, '<'); sSectionOptionEndULContent = sSectionOptionEndULContent.replace(/(&gt;)/ig, '>'); } // // Create default option if dropdown list layout used // if (!bHideLabel && (sSectionOptionTemplateSelectTemplate !== '') && IsDropDownListBox(sSectionOptionTemplateSelectTemplate)) { sDummyFilterSectionOptionTemplate = sFilterSectionOptionTemplate; sDummyFilterSectionOptionTemplate = sDummyFilterSectionOptionTemplate.replace(/(&lt;Actinic:SectionIndex&gt;&lt;\/Actinic:SectionIndex&gt;)/ig, '-1'); sDummyFilterSectionOptionTemplate = sDummyFilterSectionOptionTemplate.replace(/(<Actinic:SectionIndex><\/Actinic:SectionIndex>)/ig, '-1'); sDummyFilterSectionOptionTemplate = sDummyFilterSectionOptionTemplate.replace(/(<Actinic:SectionName><\/Actinic:SectionName>)/ig, 'Any'); var sKey = "SX:-1"; var sSelection = ''; if (typeof(gMapCtrlSelections[sKey]) !== "undefined") { sSelection = "selected"; // list box } sDummyFilterSectionOptionTemplate = sDummyFilterSectionOptionTemplate.replace(/(ActinicDisabledCtrl=\"\")/ig, ''); sDummyFilterSectionOptionTemplate = sDummyFilterSectionOptionTemplate.replace(/(ActinicDisabledStyle=\"\")/ig, ''); sDummyFilterSectionOptionTemplate = sDummyFilterSectionOptionTemplate.replace(/(ActinicCustomSelection=\"\")/ig, sSelection); sDummyFilterSectionOptionTemplate = sDummyFilterSectionOptionTemplate.replace(/(ACT:OPTION)/ig, 'option'); sDummyFilterSectionOptionTemplate = sDummyFilterSectionOptionTemplate.replace(/(<Actinic:HiddentInput><\/Actinic:HiddentInput>)/ig, ''); // hidden parameter sResultOptions += sDummyFilterSectionOptionTemplate; } // // Create other price options // var nCount = 0; var nListCount = 1; // default size is one! for (var nSXIndx = 0; nSXIndx < gArraySectionIDs.length; nSXIndx++) { sHiddenInput = ""; if (typeof(gMapFilters['SX'][gArraySectionIDs[nSXIndx]]) === 'undefined' || gMapFilters['SX'][gArraySectionIDs[nSXIndx]].m_bHideAlways) // hide always? { continue; } nCount = gMapFilters['SX'][gArraySectionIDs[nSXIndx]].m_nCumulativeCount; // get section/department count if ((!IsFilterCountEnabled()) || // filter not enabled? ((IsHideChoiceWithZeroResults() && nCount > 0) || (!IsHideChoiceWithZeroResults()))) { nListCount++; // // Replace "Price Index", "Price Band" with count and Selection (checked / selected) // sDummyFilterSectionOptionTemplate = sFilterSectionOptionTemplate; sDummyFilterSectionOptionTemplate = sDummyFilterSectionOptionTemplate.replace(/(&lt;Actinic:SectionIndex&gt;&lt;\/Actinic:SectionIndex&gt;)/ig, gArraySectionIDs[nSXIndx]); sDummyFilterSectionOptionTemplate = sDummyFilterSectionOptionTemplate.replace(/(<Actinic:SectionIndex><\/Actinic:SectionIndex>)/ig, gArraySectionIDs[nSXIndx]); var sSectionName = gMapFilters['SX'][gArraySectionIDs[nSXIndx]].m_sSectionName; if (IsFilterCountEnabled()) { sSectionName += ' (' + nCount + ')'; } sDummyFilterSectionOptionTemplate = sDummyFilterSectionOptionTemplate.replace(/(<Actinic:SectionName><\/Actinic:SectionName>)/ig, sSectionName); // // Remember the previous selection // var sKey = "SX:" + gArraySectionIDs[nSXIndx]; var sSelection = ""; var sDisabledStyle = ""; // disabled style for label var sDisabledCtrl = ""; // disabled control type if (typeof(gMapCtrlSelections[sKey]) !== "undefined") { if (sControl === 'LIST') { sSelection = "selected"; // list box } else if (sControl === 'LINKS') { // // Edit style for submit button // sSelection = "style=\"color:red\""; // clickable links sHiddenInput = "<input type=\"hidden\" value=\"" + gArraySectionIDs[nSXIndx] + "\" name=\"hf_SX\" id=\"hf_SX\"/>"; } else { sSelection = "checked"; // radio button / check box } } if (IsFilterCountEnabled() && !IsHideChoiceWithZeroResults()) { if (sControl === 'LIST') { if (!(nCount > 0)) { sDisabledCtrl = "disabled=\"disabled\""; // disable lists } } else if (sControl === 'LINKS') { if (!(nCount > 0)) { sDisabledCtrl = "disabled=\"disabled\""; // disable sDisabledStyle = "style=\"color:gray;cursor:default\""; // make gray } } else { if (!(nCount > 0)) { sDisabledCtrl = "disabled=\"disabled\""; // disable buttons (check box/radio buttons) sDisabledStyle = "style=\"color:gray\""; } } } sDummyFilterSectionOptionTemplate = sDummyFilterSectionOptionTemplate.replace(/(ActinicDisabledCtrl=\"\")/ig, sDisabledCtrl); sDummyFilterSectionOptionTemplate = sDummyFilterSectionOptionTemplate.replace(/(ActinicDisabledStyle=\"\")/ig, sDisabledStyle); sDummyFilterSectionOptionTemplate = sDummyFilterSectionOptionTemplate.replace(/(ACT:OPTION)/ig, 'option'); // replace custom tag "ACT:OPTION" with "option" sDummyFilterSectionOptionTemplate = sDummyFilterSectionOptionTemplate.replace(/(ActinicCustomSelection=\"\")/ig, sSelection); sDummyFilterSectionOptionTemplate = sDummyFilterSectionOptionTemplate.replace(/(<Actinic:HiddentInput><\/Actinic:HiddentInput>)/ig, sHiddenInput); sResultOptions += sDummyFilterSectionOptionTemplate; } } // // Update the count if any! // if (!bHideLabel) // hide label? { sSectionOptionTemplateSelectStart = sSectionOptionTemplateSelectStart.replace(/(&lt;Actinic:ListCount&gt;&lt;\/Actinic:ListCount&gt;)/ig, nListCount); sSectionOptionTemplateSelectStart = sSectionOptionTemplateSelectStart.replace(/(<Actinic:ListCount><\/Actinic:ListCount>)/ig, nListCount); } else { sSectionOptionTemplateSelectStart = ''; sSectionOptionStartULContent = ''; sResultOptions = ''; sSectionOptionEndULContent = ''; sSectionOptionTemplateSelectEnd = ''; } // // Update the filter price band content with the template and the needed filter options // elFilterSection.innerHTML = (sSectionOptionTemplateSelectTemplate + // select tag template sFilterSectionOptionTemplateOutput + // option template sSectionOptionStartULTemplate + // start UL template sSectionOptionEndULTemplate + // end UL template sSectionOptionTemplateSelectStart + // select start tag sSectionOptionStartULContent + // opening ul tag sResultOptions + // option tag sSectionOptionEndULContent + // closing ul tag sSectionOptionTemplateSelectEnd); // select end tag } /*********************************************************************** * * IsSearchBySubSection - Check if search by sub sections enabled * * Returns: - true/false * ************************************************************************/ function IsSearchBySubSection() { if (typeof(pg_bSearchBySubSection) !== "undefined" && (pg_bSearchBySubSection === 1)) { return true; } return false; } /*********************************************************************** * * CacheSectionDetails - Cache department information and store into * the section map * * Returns: - nothing * ************************************************************************/ function CacheSectionDetails(arrDepartmentInfo) { for (var nSecInfoIndx = 0; nSecInfoIndx < arrDepartmentInfo.length; nSecInfoIndx++) { var sSectionID = arrDepartmentInfo[nSecInfoIndx].SectionID; if (typeof(gMapFilters['SX'][sSectionID]) !== 'undefined') { gMapFilters['SX'][sSectionID].m_arrSubSectionIds = arrDepartmentInfo[nSecInfoIndx].SubSectionIDs; } else { gMapFilters['SX'][sSectionID] = new SectionDetails(); gMapFilters['SX'][sSectionID].m_arrSubSectionIds = arrDepartmentInfo[nSecInfoIndx].SubSectionIDs; } } } /*********************************************************************** * * UpdateCumulativeSectionCount - Update the cumulative department count * * Returns: - nothing * ************************************************************************/ function UpdateCumulativeSectionCount() { if (!IsSearchBySubSection()) { return; } // // Loop through each section ID and update the cumulative count // for (var nSecIdx = 0; nSecIdx < gArraySectionIDs.length; nSecIdx++) { var sSectionId = gArraySectionIDs[nSecIdx]; if (typeof(gMapFilters['SX'][sSectionId]) !== "undefined") { var arrSubSectionIDs = new Array(); arrSubSectionIDs = gMapFilters['SX'][sSectionId].m_arrSubSectionIds; for (var nSubSecIndx = 0; nSubSecIndx < arrSubSectionIDs.length; nSubSecIndx++) { // // Add the sub section count // if (typeof(gMapFilters['SX'][arrSubSectionIDs[nSubSecIndx]]) !== 'undefined') { gMapFilters['SX'][sSectionId].m_nCumulativeCount += gMapFilters['SX'][arrSubSectionIDs[nSubSecIndx]].m_nCount; } } // // Add the actual count // gMapFilters['SX'][sSectionId].m_nCumulativeCount += gMapFilters['SX'][sSectionId].m_nCount; } } } /*********************************************************************** * * HideOptionAny - Hiding option 'Any' from the static page * * Returns: - nothing * ************************************************************************/ function HideOptionAny() { // // Hide option 'Any' from departments // var bDefaultView = IsFilterAsDefaultView(); var elSXAny = document.getElementById('SX_-1'); if (elSXAny) { var elSXAnyParent = elSXAny.parentNode; var elChildAny; // // default view layouts from server will not have static controls such as <Actinic:StaticSearchField> // if (bDefaultView) { elChildAny = elSXAnyParent.childNodes; } else { elChildAny = elSXAnyParent.parentNode.childNodes; } for (var nIndx = 0; nIndx < elChildAny.length; nIndx++) { if (elChildAny[nIndx].tagName === 'LABEL' && elChildAny[nIndx].htmlFor === 'SX_-1') { elChildAny[nIndx].parentNode.removeChild(elChildAny[nIndx]); } } elSXAny.parentNode.removeChild(elSXAny); } // // Hide option 'Any' from price bands // var elPRAny = document.getElementById('-1'); if (elPRAny) { var elPRAnyParent = elPRAny.parentNode; var elChildAny; if (bDefaultView) { elChildAny = elPRAnyParent.childNodes; } else { elChildAny = elPRAnyParent.parentNode.childNodes; } for (var nIndx = 0; nIndx < elChildAny.length; nIndx++) { if (elChildAny[nIndx].tagName === 'LABEL' && elChildAny[nIndx].htmlFor === '-1') { elChildAny[nIndx].parentNode.removeChild(elChildAny[nIndx]); } } elPRAny.parentNode.removeChild(elPRAny); } // // Hide option 'Any' from filter properties // for (var nDefOptIdx = 0; nDefOptIdx < gArrProperty.length; nDefOptIdx++) { if (typeof(gArrProperty[nDefOptIdx]) !== 'undefined') { var sPropId = gArrProperty[nDefOptIdx]; // // Do not remove 'Any' when dropdown list used // var sPropOptionSelectContent = ''; var sPropOptTemplateSelectId = "PropOptionTemplateSelect_" + sPropId; var elPropOptionSelect = document.getElementById(sPropOptTemplateSelectId); if (elPropOptionSelect !== null) { sPropOptionSelectContent = elPropOptionSelect.innerHTML; } if (sPropOptionSelectContent !== '' && IsDropDownListBox(sPropOptionSelectContent)) { continue; } sPropId += '-1'; // property option 'Any' var elPropAny = document.getElementById(sPropId); if (elPropAny && elPropAny.value === '') // property value should be empty { var elPropAnyParent = elPropAny.parentNode; var elChildAny; if (bDefaultView) { elChildAny = elPropAnyParent.childNodes; } else { elChildAny = elPropAnyParent.parentNode.childNodes; } for (var nIndx = 0; nIndx < elChildAny.length; nIndx++) { if (elChildAny[nIndx].tagName === 'LABEL' && elChildAny[nIndx].htmlFor === sPropId) { elChildAny[nIndx].parentNode.removeChild(elChildAny[nIndx]); } } elPropAnyParent.removeChild(elPropAny); } } } } /*********************************************************************** * * IsFilterAsDefaultView - Check if filter result is marked as default * view * * Returns: - true/false * ************************************************************************/ function IsFilterAsDefaultView() { if (typeof(pg_bFilterDefaultView) !== "undefined" && pg_bFilterDefaultView) { return true; } return false; } /*********************************************************************** * * IsShowClearButton - Check whether to show clear button * * Inputs: sID - filter element id * * Returns: - true/false * ************************************************************************/ function IsShowClearButton(sID) { var bShow = false; if (sID === 'SX') // check for section/department { for (var nSectionID in gMapFilters['SX']) // for each section ID { if (typeof(gMapCtrlSelections['SX:' + nSectionID]) !== 'undefined') { if (gMapCtrlSelections[nSectionID] !== '-1') { bShow = true; } } } } else if (sID === 'PR') // check for price band { for (var nPriceBandID in gMapFilters['PR']) { if (typeof(gMapCtrlSelections['PR:' + nPriceBandID]) !== 'undefined') { if (gMapCtrlSelections[nPriceBandID] !== '-1') { bShow = true; } } } } else { if (typeof(gMapFilters[sID]) !== "undefined") { var sArrayChoices = gMapFilters[sID].m_mapChoices; var nChoiceInx = 1; // starting choice index while (typeof(sArrayChoices[nChoiceInx]) !== "undefined") { var sChoiceID = sArrayChoices[nChoiceInx].m_sChoiceID; // get choice id (ex: S_417_1:2) if (typeof(gMapCtrlSelections[sChoiceID]) !== "undefined" && gMapFilters[sID].m_mapChoices[nChoiceInx].m_sChoiceName !== '') // not 'Any'? { bShow = true; // show clear button } nChoiceInx++; } } } return bShow; } /*********************************************************************** * * FilterProductsBasedOnPerms - Validate product references against permutations * * Returns: - nothing * ************************************************************************/ function FilterProductsBasedOnPerms() { var mapProdRefToValidity = {}; // map of product reference to validity (true/false based on permutation) var arrSelections = new Array(); for (var sPropId in gMapPropCtrlSelections) { if (typeof(sPropId) !== 'undefined') { arrSelections.push(sPropId); } } if (arrSelections.length <= 0) // when no filter options selected { var sKey = gArrayDefinedPropertiesSorted.join(':'); for (var nProdIdx = 0; nProdIdx < gArrSortedProductRefs.length; nProdIdx++) { var sProdRef = gArrSortedProductRefs[nProdIdx]; if (typeof(gMapInvalidProdRefs[sProdRef]) === 'undefined' && !gMapObjProductDetails[sProdRef].m_bFullPermutation) // valid product { mapProdRefToValidity[sProdRef] = true; continue; } else // invalid { var mapCompToPerms = gMapObjProductDetails[sProdRef].m_mapCompToPermutation; if (typeof(mapCompToPerms[sKey]) !== 'undefined' && (mapCompToPerms[sKey] === 'EMPTY' || mapCompToPerms[sKey] === 'OSTOCK')) // empty/out of stock permutation { // // Check if any perms from other component are valid // if (IsAllOtherPermsValid(mapCompToPerms, sKey)) { mapProdRefToValidity[sProdRef] = true; // mark as valid (no perms defined for the current combination) } else { mapProdRefToValidity[sProdRef] = false; // mark as invalid (all permutations are invalid) } } else { // // Some permutations are valid, counted for choices // mapProdRefToValidity[sProdRef] = true; } } } } else { InsertSort(arrSelections); // sort the selection // // Create selection string // var sSelections = GetPermSelectionString(''); for (var nProdIdx = 0; nProdIdx < gArrSortedProductRefs.length; nProdIdx++) { var sProdRef = gArrSortedProductRefs[nProdIdx]; if (typeof(gMapInvalidProdRefs[sProdRef]) === 'undefined' && !gMapObjProductDetails[sProdRef].m_bFullPermutation) { mapProdRefToValidity[sProdRef] = true; continue; } mapProdRefToValidity[sProdRef] = false; // intially mark all as invalid var mapCompToPerms = gMapObjProductDetails[sProdRef].m_mapCompToPermutation; // // All permutations are invalid??? // if (typeof(mapCompToPerms['EMPTY']) !== 'undefined') // empty permutation { mapProdRefToValidity[sProdRef] = false; // mark as invalid (all permutations are invalid) continue; } var bInValid = true; // // For each component, check if any of the permutations is valid // var bCompMatched = false; for (sComponent in mapCompToPerms) { if (IsValidComponent(arrSelections, sComponent) === true) { bCompMatched = true; if (mapCompToPerms[sComponent] === 'EMPTY' || mapCompToPerms[sComponent] === 'OSTOCK') { // // Check if any other perms from other comp is valid // if (IsAllOtherPermsValid(mapCompToPerms, sComponent)) { mapProdRefToValidity[gArrSortedProductRefs[nProdIdx]] = true; // valid as no perms are defined for the current component } continue; } var arrPermutations = mapCompToPerms[sComponent]; if (arrPermutations.length > 0) { for (var nPermIdx = 0; nPermIdx < arrPermutations.length; nPermIdx++) { if (TestRegExp(arrPermutations[nPermIdx], sSelections)) { bInValid = false; break; } } } // // Mark the valid product refs based on valid permutations // if (bInValid === false) { mapProdRefToValidity[gArrSortedProductRefs[nProdIdx]] = true; } } } // // If no compoenents matched, then it is a valid product // if (!bCompMatched) { mapProdRefToValidity[gArrSortedProductRefs[nProdIdx]] = true; } } } // // Cleanup the global sorted array of product refs // for (var sProdRef in mapProdRefToValidity) { if (mapProdRefToValidity[sProdRef] === false) { var nIndex = GetArrayIndex(gArrSortedProductRefs, sProdRef); if (nIndex !== -1) // found? { gArrSortedProductRefs.splice(nIndex, 1); // filtered prod refs based on perms delete gMapMatchedProducts[sProdRef]; } } } // // exclude alternative products if any // for (var nIndex = 0; nIndex < gArrSortedProductRefs.length; nIndex++) { var sProdRef = gArrSortedProductRefs[nIndex]; if ((typeof(gMapAltProdToParentProductRef[sProdRef]) !== 'undefined') && (typeof(gMapMatchedProducts[gMapAltProdToParentProductRef[sProdRef]]) !== 'undefined')) { gArrSortedProductRefs.splice(nIndex, 1); // exclude the alternative from results nIndex--; } } // // Reset the global array // gArrResultSet.length = 0; gArrResultSet = GetDecoratedProdRefs(gArrSortedProductRefs); } /*********************************************************************** * * IsValidComponent - Validate product references against permutations * * Inputs: arrSelections - array of selections * sComponent - component string (combination) * * Returns: - true/false * ************************************************************************/ function IsValidComponent(arrSelections, sComponent) { var bValid = false; var arrPropIds = sComponent.split(':'); var sSelections = arrSelections.join('|'); // // Substring check for each property id in combination // for (var nCompIdx = 0; nCompIdx < arrPropIds.length; nCompIdx++) { var sPropName = arrPropIds[nCompIdx]; if (sSelections.indexOf(sPropName) !== -1) { bValid = true; break; } } return bValid; } /*********************************************************************** * * UpdatePermutationCount - Check whether to show clear button * * Returns: - nothing * ************************************************************************/ function UpdatePermutationCount(sCurFltrGrp, arrProds) { var arrSelections = new Array(); for (var sPropId in gMapPropCtrlSelections) { if (typeof(sPropId) !== 'undefined') { arrSelections.push(sPropId); } } if (sCurFltrGrp !== 'SX' && sCurFltrGrp !== 'PR') { var sChoiceNo = ''; var mapChoices = gMapFilters[sCurFltrGrp].m_mapChoices; // // Update count for each choice of the choices // for (sChoiceNo in mapChoices) { if (sChoiceNo === '') // empty? look for next choice { continue; } var nCount = mapChoices[sChoiceNo].m_nChoiceCount; // get choice count if (nCount === 0) // If Choice selected or choice count is 0, look for next choice { continue; } var sSelString = ''; var sPropId = sCurFltrGrp; var sChoiceName = mapChoices[sChoiceNo].m_sChoiceName; sSelString = GetPermSelectionString(sPropId, sChoiceName); // // For each product, get the permutation // for (var nProdIdx = 0; nProdIdx < arrProds.length; nProdIdx++) { var sProdRef = arrProds[nProdIdx]; if ((typeof(gMapAltProdToParentProductRef[sProdRef]) !== 'undefined') && (typeof(gMapProdToAltProdArray[gMapAltProdToParentProductRef[sProdRef]]) !== 'undefined')) { continue; } else if (typeof(gMapProdToAltProdArray[sProdRef]) !== 'undefined') { if (!CheckAlternativePermutations(sProdRef, sCurFltrGrp, sChoiceName, arrSelections)) { mapChoices[sChoiceNo].m_nChoiceCount--; } continue; } // // Apply the permutation only if the product has the choice defined // if (typeof(gMapObjProductDetails[sProdRef].m_mapProperties[sCurFltrGrp]) !== 'undefined') { var mapChs = gMapObjProductDetails[sProdRef].m_mapProperties[sCurFltrGrp].m_mapChoices; if (typeof(mapChs[sChoiceName]) === 'undefined') // choice not present { continue; } } else // property not present { continue; } var mapCompToPerms = gMapObjProductDetails[sProdRef].m_mapCompToPermutation; var sPropName = gMapFilterGrpIdToFilterGrpName[sPropId]; // // Get the combination of permutation to check // var sCombination = GetCombination(sPropName, mapCompToPerms); if (sCombination !== '') { if (!IsValidCombination(sProdRef, sSelString, sCombination)) { mapChoices[sChoiceNo].m_nChoiceCount--; // decrement the count } } else // non-permutation property { // // check for valid permutations in current selections // var sPermSelString = GetPermSelectionString(''); if (sPermSelString !== '') { var bInvalid = false; var sComponent = ''; for (sComponent in mapCompToPerms) { if (((arrSelections.length == 0) || IsValidComponent(arrSelections, sComponent)) && !IsValidCombination(sProdRef, sPermSelString, sComponent)) { bInvalid = true; break; } } if (bInvalid) { mapChoices[sChoiceNo].m_nChoiceCount--; // decrement the count } } } } } } else // Price or Section property { for (var nProdIdx = 0; nProdIdx < arrProds.length; nProdIdx++) { var sProdRef = arrProds[nProdIdx]; if ((typeof(gMapAltProdToParentProductRef[sProdRef]) !== 'undefined') && (typeof(gMapProdToAltProdArray[gMapAltProdToParentProductRef[sProdRef]]) !== 'undefined') && ((sCurFltrGrp === 'PR' && gMapObjProductDetails[gMapAltProdToParentProductRef[sProdRef]].m_sDecPriceBand === gMapObjProductDetails[sProdRef].m_sDecPriceBand) || (sCurFltrGrp === 'SX' && gMapObjProductDetails[gMapAltProdToParentProductRef[sProdRef]].m_sDecSection === gMapObjProductDetails[sProdRef].m_sDecSection))) { continue; } // // check for valid permutations in current selections // var sPermSelString = GetPermSelectionString(''); if (sPermSelString !== '') { var bInvalid = false; var sComponent = ''; var mapCompToPerms = gMapObjProductDetails[sProdRef].m_mapCompToPermutation; for (sComponent in mapCompToPerms) { if (((arrSelections.length == 0) || IsValidComponent(arrSelections, sComponent)) && !IsValidCombination(sProdRef, sPermSelString, sComponent)) { bInvalid = true; break; } } if (bInvalid) { if (sCurFltrGrp === 'PR') // price filter group { var sPriceBandId = gMapObjProductDetails[sProdRef].m_sDecPriceBand; var mapPrices = gMapFilters['PR']; for (var sPriceId in mapPrices) { if (sPriceBandId === sPriceId) { mapPrices[sPriceBandId].m_nCount--; break; } } } else if (sCurFltrGrp === 'SX') { var sSectionGroupID = gMapObjProductDetails[sProdRef].m_sDecSection; var mapSections = gMapFilters['SX']; for (var sSectionID in mapSections) { if (sSectionGroupID === sSectionID) { mapSections[sSectionGroupID].m_nCount--; break; } } } } } } } } /*********************************************************************** * * CheckAlternativePermutations - checks for valid permutations in * alternative products * * Inputs: sProdRef - parent product reference * sCurFltrGrp - current filter group * sChoiceName - choice name * arrSelections - array of current selections * * Returns: - true if there a valid permutation * ************************************************************************/ function CheckAlternativePermutations(sProdRef, sCurFltrGrp, sChoiceName, arrSelections) { if (typeof(gMapProdToAltProdArray[sProdRef]) === 'undefined') { return (true); } var sSelectionString = ''; var sPropId = sCurFltrGrp; var bValid = true; sSelectionString = GetPermSelectionString(sPropId, sChoiceName); var arrProds = gMapProdToAltProdArray[sProdRef]; // // For each product, get the permutation // for (var nProdIdx = 0; nProdIdx < arrProds.length; nProdIdx++) { var sProdRef = arrProds[nProdIdx]; // // Apply the permutation only if the product has the choice defined // if (typeof(gMapObjProductDetails[sProdRef].m_mapProperties[sCurFltrGrp]) !== 'undefined') { var mapChs = gMapObjProductDetails[sProdRef].m_mapProperties[sCurFltrGrp].m_mapChoices; if (typeof(mapChs[sChoiceName]) === 'undefined') // choice not present { continue; } } else // property not present { continue; } var mapCompToPerms = gMapObjProductDetails[sProdRef].m_mapCompToPermutation; var sPropName = gMapFilterGrpIdToFilterGrpName[sPropId]; // // Get the combination of permutation to check // var sCombination = GetCombination(sPropName, mapCompToPerms); if (sCombination !== '') { var arrPerms = mapCompToPerms[sCombination]; if (((typeof(gMapInvalidProdRefs[sProdRef]) !== 'undefined' && !gMapObjProductDetails[sProdRef].m_bFullPermutation) && // marked invalid product arrPerms === 'EMPTY') || // current component permutations are empty(all are invalid) (arrPerms === 'OSTOCK') ) { // // check for any valid perms in other components // if (IsAllOtherPermsValid(mapCompToPerms, sCombination)) { return (true); } bValid = false; continue; } else if (arrPerms === 'EMPTY') // all valid { return (true); } if (arrPerms.length > 0) { // // For each permutation // for (var nPermIdx = 0; nPermIdx < arrPerms.length; nPermIdx++) { if (TestRegExp(arrPerms[nPermIdx], sSelectionString)) { return (true); } } if (nPermIdx === arrPerms.length) { bValid = false; } } } else { // // check for valid permutations in current selections // var sPermSelString = GetPermSelectionString(''); if (sPermSelString !== '') { var bInvalid = false; var sComponent = ''; for (sComponent in mapCompToPerms) { if (IsValidComponent(arrSelections, sComponent)) { if (IsValidCombination(sProdRef, sPermSelString, sComponent)) { return (true); } bValid = false; break; } } } } } return (bValid); } /*********************************************************************** * * IsValidCombination - checks for valid combination * * Inputs: sProdRef - product reference * sSelString - current selection string * sCombination - combination string * * Returns: - true if its a valid combination * ************************************************************************/ function IsValidCombination(sProdRef, sSelString, sCombination) { var mapCompToPerms = gMapObjProductDetails[sProdRef].m_mapCompToPermutation; if (sCombination !== '') { var arrPerms = mapCompToPerms[sCombination]; if (((typeof(gMapInvalidProdRefs[sProdRef]) !== 'undefined' && !gMapObjProductDetails[sProdRef].m_bFullPermutation) && // marked invalid product arrPerms === 'EMPTY') || // current component permutations are empty(all are invalid) (arrPerms === 'OSTOCK') ) { // // check for any valid perms in other components // if any perms are valid // current compo has no perms defined // else all invalid perms // if (IsAllOtherPermsValid(mapCompToPerms, sCombination)) { return (true); // no perms are defined for the current component } else { return (false); } } else if (arrPerms === 'EMPTY') // all valid { return (true); } if (arrPerms.length > 0) { // // For each permutation // for (var nPermIdx = 0; nPermIdx < arrPerms.length; nPermIdx++) { if (TestRegExp(arrPerms[nPermIdx], sSelString)) { return (true); } } return (false); } } return (true); } /*********************************************************************** * * GetPermSelectionString - Create selection string * * Inputs: sCurrentPropId - current choice id * sCurrentChoiceName - current choice * Returns: - selection string * ************************************************************************/ function GetPermSelectionString(sCurrentPropId, sCurrentChoiceName) { var sSelString = ''; var sCurrentDecChoice = gMapFilterGrpIdToFilterGrpName[sCurrentPropId] + ':' + sCurrentChoiceName; // // Create selection string for the defined properties // for (var nPropIdx = 0; nPropIdx < gArrayDefinedPropertiesSorted.length; nPropIdx++) { var sProName = gArrayDefinedPropertiesSorted[nPropIdx]; var sPropId = gMapPropNameToPropId[sProName]; if (sCurrentPropId === sPropId) // check the current property { sSelString += '-' + sCurrentDecChoice + '-'; // include current choice alone } else if (typeof(gMapPropIdToSelections[sPropId]) !== 'undefined') // const strings { sSelString += '-' + gMapPropIdToSelections[sPropId].join('--') + '-'; } else { sSelString += '-' + gMapPropIdDecoratedChoices[sPropId].join('--') + '-'; // string of all the choices of the group } } return sSelString; } /*********************************************************************** * * GetCombination - Get combination to check * * Inputs: sPropName - property name * mapCompToPerms - map of component to permutations * * Returns: - attribute combination * ************************************************************************/ function GetCombination(sPropName, mapCompToPerms) { var sCombination = ''; for (var sKey in mapCompToPerms) // check for each of the combinations { if (sKey === '') { continue; } if (sKey.indexOf(sPropName) !== -1) // match found? { sCombination = sKey; break; // return the combination } } return sCombination; } /*********************************************************************** * * CalculateCount - Calculate count for choices * * Inputs: bForHideOptions - calculate count for hiding options? * * Returns: - nothing * ************************************************************************/ function CalculateCount(bForHideOptions) { // // 1. Filter products based on the selected filter options // 2. Update count from properties // 3. Update count using permutations // for (var nFltrIdx = 0; nFltrIdx < gArrFilterGrpIdSorted.length; nFltrIdx++) { var sSelectionPattern = ''; var sFilterGroup = gArrFilterGrpIdSorted[nFltrIdx]; if (!bForHideOptions && !g_bClearAll) // pattern will be empty during onload or clear all { sSelectionPattern = GetFilterPatternForCount(sFilterGroup); } // // Get filtered products based on the selected filter options // var arrFilteredProds = GetFilteredProducts(sSelectionPattern); // // Calculate count for each group // CountFilterOptions(sFilterGroup, arrFilteredProds); // // Update count based on permutations // UpdatePermutationCount(sFilterGroup, arrFilteredProds); // // Finally, find the cumulative count for all sub sections // if (sFilterGroup === 'SX') { UpdateCumulativeSectionCount(); } } } /*********************************************************************** * * GetFilterPatternForCount - Get filter pattern for count * * Inputs: sCurFilterGrp - current filter group * * Returns: - selection pattern for match * ************************************************************************/ function GetFilterPatternForCount(sCurFilterGrp) { // // Get the filter selections in regular expression. The selections are formulated by // ignoring the current filter group for which the count is being calculated // var mapPropIdToFilterSelections = {}; // map of property controlid to selections var sPattern = ''; for (var sFilterGroup in gMapFilterGrpIdToFilterGrpName) { if (sFilterGroup === sCurFilterGrp) // is this the current group to which count is being calculated? { continue; } // // Format the filter selection regular expression by considering all the filter // options selections excluding the current group for which the count is being // calculated // if (typeof(gMapControlToSelection[sFilterGroup]) !== 'undefined') { var mapFilterGroup = gMapControlToSelection[sFilterGroup]; var arrChoices = new Array(); var sChoices = ''; if (sFilterGroup === 'PR') // price or section group? { for (var sFilterCtrlId in mapFilterGroup) { var sChoice = sFilterGroup + '_' + sFilterCtrlId; arrChoices.push(sChoice); } } else if (sFilterGroup === 'SX') { // // Get the sub section details as well // var mapSecs = {}; for (var sFilterCtrlId in mapFilterGroup) { mapSecs[sFilterCtrlId] = ''; var arrSubSecIDs = gMapFilters['SX'][sFilterCtrlId].m_arrSubSectionIds; for (var nSecIdx = 0; nSecIdx < arrSubSecIDs.length; nSecIdx++) { if (GetArrayIndex(gArraySectionIDs, arrSubSecIDs[nSecIdx]) !== -1) // if sub section included { mapSecs[arrSubSecIDs[nSecIdx]] = ''; } } } for (var sSecId in mapSecs) { var sChoice = sFilterGroup + '_' + sSecId; arrChoices.push(sChoice); } } else // other filter groups { for (var sFilterChoiceCtrlId in mapFilterGroup) { if (typeof(gMapControlIdChoiceName[sFilterChoiceCtrlId]) !== 'undefined') { var sChoice = sFilterGroup + ':' + gMapControlIdChoiceName[sFilterChoiceCtrlId]; arrChoices.push(sChoice); } } } // // Format the regular expression // if (arrChoices.length > 0) { mapPropIdToFilterSelections[sFilterGroup] = '\\!' + arrChoices.join('\\!|\\!') + '\\!'; } } } for (var nFltrIdx = 0; nFltrIdx < gArrFilterGrpIdSorted.length; nFltrIdx++) { var sFltrGrpId = gArrFilterGrpIdSorted[nFltrIdx]; if (typeof(mapPropIdToFilterSelections[sFltrGrpId]) !== 'undefined') { if (sPattern.length > 0) { sPattern += '.*' } sPattern += mapPropIdToFilterSelections[sFltrGrpId]; } } return sPattern; } /*********************************************************************** * * GetFilteredProducts - Get the filtered products * * Inputs: sRegExProps - regular expression of property options * * Returns: - array of matched products * ************************************************************************/ function GetFilteredProducts(sRegExProps) { var arrMatchedProd = new Array(); var oRegExp = new RegExp(sRegExProps, 'i'); gMapMatchedProducts = {}; gMapProdToAltProdArray = {}; for (var sProdRef in gMapObjProductDetails) { if (sRegExProps === '') { arrMatchedProd.push(sProdRef); gMapMatchedProducts[sProdRef] = ''; continue; } // // Execute the regular pattern formed based on selection against the // decorated choices string // var sDecProps = gMapObjProductDetails[sProdRef].m_sDecFilterString; // // Check if choice match found // if (TestRegExp(oRegExp, sDecProps)) { arrMatchedProd.push(sProdRef); gMapMatchedProducts[sProdRef] = ''; } } // // create product alternatives lookup map // for (var nIndex = 0; nIndex < arrMatchedProd.length; nIndex++) { var sProdRef = arrMatchedProd[nIndex]; if ((typeof(gMapAltProdToParentProductRef[sProdRef]) !== 'undefined') && (typeof(gMapMatchedProducts[gMapAltProdToParentProductRef[sProdRef]]) !== 'undefined')) { if (typeof(gMapProdToAltProdArray[gMapAltProdToParentProductRef[sProdRef]]) === 'undefined') { gMapProdToAltProdArray[gMapAltProdToParentProductRef[sProdRef]] = new Array(); gMapProdToAltProdArray[gMapAltProdToParentProductRef[sProdRef]].push(gMapAltProdToParentProductRef[sProdRef]); } gMapProdToAltProdArray[gMapAltProdToParentProductRef[sProdRef]].push(sProdRef); } } return arrMatchedProd; } /*********************************************************************** * * TestRegExp - Count filter property options * * Inputs: sRegEx - regular expression * sPattern - pattern to test * * Returns: - true/false * ************************************************************************/ function TestRegExp(sRegEx, sPattern) { var bResult = false; if ((typeof(sRegEx) !== 'undefined') && (typeof(sPattern) !== 'undefined') && sPattern != '') { bResult = sRegEx.test(sPattern); } return (bResult); } /*********************************************************************** * * CountFilterOptions - Count filter property options * * Inputs: sCurFltrGrp - current filter group to calculate count * arrProds - array of products for count calculation * * Returns: - nothing * ************************************************************************/ function CountFilterOptions(sCurFltrGrp, arrProds) { var mapProducts = {}; // // prepare a result lookup map // for (var nProdIndx = 0; nProdIndx < arrProds.length; nProdIndx++) { mapProducts[arrProds[nProdIndx]] = ''; } // // Update the count by looking up each product // for (var nProdIndx = 0; nProdIndx < arrProds.length; nProdIndx++) { var sProdRef = arrProds[nProdIndx]; if (sCurFltrGrp === 'PR') // price filter group { var sPriceId = gMapObjProductDetails[arrProds[nProdIndx]].m_sDecPriceBand; // // ignore price count update if alternative product is listed with parent product // if ((typeof(gMapAltProdToParentProductRef[sProdRef]) === 'undefined') || (typeof(mapProducts[gMapAltProdToParentProductRef[sProdRef]]) === 'undefined') || (gMapObjProductDetails[gMapAltProdToParentProductRef[sProdRef]].m_sDecPriceBand !== sPriceId)) { UpdatePriceCount(sPriceId); } } else if (sCurFltrGrp === 'SX') // section filter group { var sSectionId = gMapObjProductDetails[arrProds[nProdIndx]].m_sDecSection; // // ignore section count update if alternative product is listed with parent product // if ((typeof(gMapAltProdToParentProductRef[sProdRef]) === 'undefined') || (typeof(mapProducts[gMapAltProdToParentProductRef[sProdRef]]) === 'undefined') || (gMapObjProductDetails[gMapAltProdToParentProductRef[sProdRef]].m_sDecSection !== sSectionId)) { UpdateSectionCount(sSectionId); } } else // choice filter group { var sChoicesString = gMapObjProductDetails[arrProds[nProdIndx]].m_sDecFilterString; var mapProdChoices = gMapObjProductDetails[arrProds[nProdIndx]].m_mapDecChoices; if ((typeof(gMapAltProdToParentProductRef[sProdRef]) === 'undefined') || (typeof(mapProducts[gMapAltProdToParentProductRef[sProdRef]]) === 'undefined')) { UpdateChoiceCount(sCurFltrGrp, sChoicesString, mapProdChoices); } else { var mapParentProdChoices = gMapObjProductDetails[gMapAltProdToParentProductRef[sProdRef]].m_mapDecChoices; var mapProdMergedChoices = {}; // // prepare the alternative product choices for the choice count calculation // for (var sDecChoice in mapProdChoices) { mapProdMergedChoices[sDecChoice] = ''; } // // exclude the alternative choices which are already present in parent product // for (var sDecChoice in mapParentProdChoices) { if (typeof(mapProdMergedChoices[sDecChoice]) !== 'undefined') { delete mapProdMergedChoices[sDecChoice]; } } UpdateChoiceCount(sCurFltrGrp, sChoicesString, mapProdMergedChoices); } } } } /*********************************************************************** * * UpdatePriceCount - Update price count * * Inputs: sPriceId - price id for count update * * Returns: - nothing * ************************************************************************/ function UpdatePriceCount(sPriceId) { var mapPrices = gMapFilters['PR']; var bShowPrGroup = false; for (var sPriceBandId in mapPrices) { if (sPriceBandId === sPriceId) { mapPrices[sPriceBandId].m_nCount++; bShowPrGroup = true; break; } } if (bShowPrGroup) { gMapFilters['PR'].m_bShow = true; } } /*********************************************************************** * * UpdateSectionCount - Update section count * * Inputs: sSectionId - section id for count update * * Returns: - nothing * ************************************************************************/ function UpdateSectionCount(sSectionId) { var mapSections = gMapFilters['SX']; var bShowSXGroup = false; for (var sSectionNo in mapSections) { if (sSectionNo === sSectionId) { mapSections[sSectionNo].m_nCount++; bShowSXGroup = true; break; } } if (bShowSXGroup) { gMapFilters['SX'].m_bShow = true; } } /*********************************************************************** * * UpdateChoiceCount - Update choice count * * Inputs: mapChoices - choices to update the count * sChoicesString - choices string from the product * mapProdChoices - map of product choices * * Returns: - nothing * ************************************************************************/ function UpdateChoiceCount(sCurFltrGrp, sChoicesString, mapProdChoices) { var mapFltrChoices = gMapFilters[sCurFltrGrp].m_mapChoices; var bShowFilterGroup = false; // // Update choice count for each choice // for (var nChoiceNo in mapFltrChoices) { var oChoice = mapFltrChoices[nChoiceNo]; if (oChoice.m_sChoiceName === '') // default choice with 'Any' { continue; } // // Check if choice defined in the product // var sKey = sCurFltrGrp + ':' + oChoice.m_sChoiceName; if (typeof(mapProdChoices[sKey]) !== 'undefined') { oChoice.m_nChoiceCount++; // update count bShowFilterGroup = true; } } if (bShowFilterGroup) { gMapFilters[sCurFltrGrp].m_bShow = true; // show the group header } } /*********************************************************************** * * RemoveFilterWithZeroCount - Remove filter options with count zero * * Returns: - nothing * ************************************************************************/ function RemoveFilterWithZeroCount() { for (var sFilterGroup in gMapFilters) { if (sFilterGroup === 'PR') // filter price group { var mapPriceBands = gMapFilters[sFilterGroup]; for (var sPriceId in mapPriceBands) { if (mapPriceBands[sPriceId].m_nCount == 0) { mapPriceBands[sPriceId].m_bHideAlways = true; // hide the option always } } } else if (sFilterGroup === 'SX') // filter section group { var mapSections = gMapFilters[sFilterGroup]; for (var sSectionId in mapSections) { if (mapSections[sSectionId].m_nCumulativeCount == 0) { mapSections[sSectionId].m_bHideAlways = true; // hide the option always } } } else // filter property group { var mapChoices = gMapFilters[sFilterGroup].m_mapChoices; gMapFilters[sFilterGroup].m_bHideAlways = true; for (var sChoiceId in mapChoices) { if (mapChoices[sChoiceId].m_nChoiceCount == 0) { mapChoices[sChoiceId].m_bHideAlways = true; // hide the option always } else { gMapFilters[sFilterGroup].m_bHideAlways = false; // do not hide } } } } } /*********************************************************************** * * IsAllOtherPermsValid - Check if other permuations defined under * other component of the product * * Inputs: mapCompToPerms - permutation map * sCurrentCombination - current permutation combination * * Returns: - true/false * ************************************************************************/ function IsAllOtherPermsValid(mapCompToPerms, sCurrentCombination) { var bValid = false; for (var sCombination in mapCompToPerms) { if (sCombination === sCurrentCombination) // do not check for the current combination { continue; } else { // // Check for the perms of other components // var arrPerms = mapCompToPerms[sCombination]; if (arrPerms !== 'EMPTY' && arrPerms !== 'OSTOCK') { if (arrPerms.length > 0) { bValid = true; // true if any valid perms break; } } } } return bValid; } /*********************************************************************** * * GetFilterCacheURL - Adjust the filter cache file name for a base href if present * * Input: sFileName - file name * * Returns: string input file name or URL if base href is present adjusted for protocol and top-level domain * ************************************************************************/ function GetFilterCacheURL(sFileName) { var sURL = ''; var collBase = document.getElementsByTagName('base'); if (collBase && collBase.length > 0) { sURL = collBase[0].href; var sDocProto = document.location.protocol; var sURLProto = sURL.split('//')[0]; if (sURLProto != sDocProto) { sURL = sURL.replace(new RegExp('^' + sURLProto), sDocProto); } var sURLHost = sURL.split('//')[1].split('/')[0]; if (sURLHost != document.location.host) { sURL = sURL.replace(sURLHost, document.location.host); } if (!sURL.match(/\/$/)) { sURL += '//'; } return sURL + sFileName; } return sFileName; } /*********************************************************************** * * ReloadCarousels - re-initialise carousels/sliders, which is necessary after their visibility changes. * ************************************************************************/ function ReloadCarousels() { // // Reload all the carousels/sliders. // This is necessary when their visibility is changed. // $("div[class^='bxSlider']").each( function(index) { var oSlider = $(this).data('sd_BXSlider'); // slider object is stored as jQuery data for the div. if (oSlider) { oSlider.reloadSlider(); // start again } }); } /*********************************************************************** * * CacheStockFilter - Cache stock filter file * ************************************************************************/ function CacheStockFilter() { if (!IsExcludeOutOfStockItems()) { return; } var stockFilterRequest = new ajaxObject('stockfilter.js'); stockFilterRequest.callback = function(responseText) { if (responseText === '') { return; } g_bCacheStock = false; // // Cache stock details // var arrStockDetails = responseText.split('|') gMapRefStock = {}; // clear cache for (index = 0; index < arrStockDetails.length; index++) { if (arrStockDetails[index] == '') { continue; } var arrRefStock = arrStockDetails[index].split('_'); gMapRefStock[arrRefStock[0]] = parseInt(arrRefStock[1]); } }; stockFilterRequest.update('', "GET", false); // send the sync request } /*********************************************************************** * * IsOutOfStockFromStockFilter - Check if the product is out of stock * with respect to stock filter file * * Returns: - true/false * ************************************************************************/ function IsOutOfStockFromStockFilter(sProdRef) { if ((typeof(gMapRefStock[sProdRef]) === 'undefined')) { return (null); } if (gMapRefStock[sProdRef] <= 0) { return (true); } return (false); } /*********************************************************************** * * IsExcludeOutOfStockItems - Check if Exclude Out of Stock items enabled * * Returns: - true/false * ************************************************************************/ function IsExcludeOutOfStockItems() { if (typeof(pg_bExcludeOutOfStockItems) !== 'undefined' && pg_bExcludeOutOfStockItems !== 0) { return (true); } return (false); } /*********************************************************************** * * GetProdRefForFullPermutation - Get product reference parameter to * download full permutation list * * Returns: string - formatted product references * ************************************************************************/ function GetProdRefForFullPermutation() { // // Get full permutations for the out of stock items // var mapProducts = {}; for (var sProdRef in gMapRefStock) // for each out of stock items { if (typeof(gMapChildToParentProducts[sProdRef]) !== 'undefined') { var arrParentProduct = gMapChildToParentProducts[sProdRef]; for (var nParentProdIdx = 0; nParentProdIdx < arrParentProduct.length; nParentProdIdx++) { mapProducts[arrParentProduct[nParentProdIdx]] = null; } } } for (var sProdRef in gMapInvalidEmptyPermsProdRefs) // for each out of stock items { mapProducts[sProdRef] = null; } // // Format the product reference list // var sProdRefParam = ''; var nCounter = 0; for (var sProdRef in mapProducts) { sProdRefParam += ((nCounter == 0) ? '' : '_') + sProdRef; nCounter++; } return (sProdRefParam); } /*********************************************************************** * * UpdateProductDetailsWithFullPermutation - Update product details with full * permutation list * ************************************************************************/ function UpdateProductDetailsWithFullPermutation(sResponseText) { var arrayJSONResponse = {}; try { arrayJSONResponse = sResponseText.parseJSON(); } catch (e) { ShowJSONError(e); // show json error return; } arrProductToFullPermutation = arrayJSONResponse.FullPermutationList; // // Update full permutation for all products // for (var nProdIdx = 0; nProdIdx < arrProductToFullPermutation.length; nProdIdx++) { var mapProductToFullPerms = arrProductToFullPermutation[nProdIdx]; for (var sProdRef in mapProductToFullPerms) { if (typeof(gMapObjProductDetails[sProdRef]) != 'undefined') { var objProductDetails = gMapObjProductDetails[sProdRef]; UpdateCompToPermMapWithFullPermutation(objProductDetails, mapProductToFullPerms[sProdRef]); // // Discard products with all permutations out of stock // var mapCompToPermutation = gMapObjProductDetails[sProdRef].m_mapCompToPermutation; if (Object.keys(mapCompToPermutation).length == 0) { continue; } var bAllOutOfStock = true; for (var sCombinationKey in mapCompToPermutation) { if (mapCompToPermutation[sCombinationKey] !== 'OSTOCK') { bAllOutOfStock = false; } } if (bAllOutOfStock) { delete gMapObjProductDetails[sProdRef]; // discard } } } } } /*********************************************************************** * * UpdateCompToPermMapWithFullPermutation - Update component to permutation map * with full permutation list * * Input: objProductDetails - product details map * sFullPermutationString - full permutation string * ************************************************************************/ function UpdateCompToPermMapWithFullPermutation(objProductDetails, sFullPermutationString) { // // Full permutation string format // <Attibute1_0:Attribute2_0>Attibute1_0!Ch12!!Attribute2_0!Ch21:1:0:v&#58;646!0!1!1!10!1 // // Set component details with decorated permutations for easy match // Example: (.*)\-S_654_0\:Red\-\-S_655_0\:Gold\-\-S_656_0\:I\-(.*) // if (sFullPermutationString !== '') { objProductDetails.m_mapCompToPermutation = {}; var arrPermutations = sFullPermutationString.split(','); for (var nPermIdx = 0; nPermIdx < arrPermutations.length; nPermIdx++) { var sPattern = /(<(.*)>(.*))/igm; var arrMatch = sPattern.exec(arrPermutations[nPermIdx]); if (arrMatch !== null) { if (arrMatch[2] !== '') { var arrAttributeCombinations = (arrMatch[2].toUpperCase()).split(':'); // attribute combination (Ex: S_254_0:S_255_0:S_256_0) InsertSort(arrAttributeCombinations); var sCombinationKey = arrAttributeCombinations.join(':'); // // exclude undefined attribute combinations // for (var nAttrIdx = 0; nAttrIdx < arrAttributeCombinations.length; nAttrIdx++) { if (typeof(gMapPropNameToPropId[arrAttributeCombinations[nAttrIdx]]) === 'undefined') { arrAttributeCombinations.splice(nAttrIdx, 1); nAttrIdx--; } } // // Check if any combination of attributes defined in filter options, if not the permutation // details are not stored as they are not used // var sTmpAttributes = '\\-' + arrAttributeCombinations.join('\\-.*\\-') + '\\-'; var oRegExAttr = new RegExp(sTmpAttributes, 'i'); // regular expression if (!oRegExAttr.test(g_sDefinedPropertiesPattern)) { continue; // do not store the permutation } var sFullPermutation = arrMatch[3]; // full permutation with associated product details if (sFullPermutation === '') { continue; // no permutation? } var arrPermCombinations = sFullPermutation.split('|'); // // Create a map of decorated valid permutations with the combination as key // for (var nIdx = 0; nIdx < arrPermCombinations.length; nIdx++) { var sPattern = /(.*)\:(\d)\:.*\:(.*)/igm; var arrMatch = sPattern.exec(arrPermCombinations[nIdx]); // // arrMatch[1] -> full permutation // arrMatch[2] -> permutation validity // arrMatch[3] -> associated product details // if (arrMatch[2] == 0) // is invalid permutation? { if (typeof(objProductDetails.m_mapCompToPermutation[sCombinationKey]) === 'undefined') { objProductDetails.m_mapCompToPermutation[sCombinationKey] = 'EMPTY'; } continue; } // // Associated product details check for out-of-stock/in stock // var sAssocProductsDetails = arrMatch[3]; // associated product details if (sAssocProductsDetails != '') // any associated product present { var arrAssocProductsDetails = sAssocProductsDetails.split('!'); var sAssocProdRef = arrAssocProductsDetails[0]; // product ref sAssocProdRef = DecodeHtmlEntity(sAssocProdRef); var bIsStockControlled = arrAssocProductsDetails[2]; // stock enabled for this permutation? var bInStockStatic = arrAssocProductsDetails[3]; // stock as per associated details in full permutation // // Exclude out of stock permutations // if (IsOutOfStock(sAssocProdRef, bIsStockControlled, bInStockStatic)) { if (typeof(objProductDetails.m_mapCompToPermutation[sCombinationKey]) === 'undefined' || // combination undefined? objProductDetails.m_mapCompToPermutation[sCombinationKey] === 'EMPTY') // some permutations are invalid { objProductDetails.m_mapCompToPermutation[sCombinationKey] = 'OSTOCK'; } continue; } } var sPermutation = arrMatch[1]; // full permutation // // prepare permutation regular expressions // var arrCombs = (sPermutation.toUpperCase()).split('!!'); for (var nCombIdx = 0; nCombIdx < arrCombs.length; nCombIdx++) { var arrTempComb = arrCombs[nCombIdx].split('!'); if (typeof(gMapPropNameToPropId[arrTempComb[0]]) === 'undefined') { arrCombs.splice(nCombIdx, 1); nCombIdx--; } } if (arrCombs.length === 0) { continue; } InsertSort(arrCombs); var sTmpPerms = '\\-' + arrCombs.join('\\-.*\\-') + '\\-'; var arrTmpPerms = sTmpPerms.split('!'); var oRegEx = new RegExp(arrTmpPerms.join('\\:'), 'i'); // regular expression // // Create a map of valid permutations // if (typeof(objProductDetails.m_mapCompToPermutation[sCombinationKey]) === 'undefined' || objProductDetails.m_mapCompToPermutation[sCombinationKey] === 'EMPTY' || // might have been empty for some product objProductDetails.m_mapCompToPermutation[sCombinationKey] === 'OSTOCK') // might have been out of stock for some product { objProductDetails.m_mapCompToPermutation[sCombinationKey] = new Array; } objProductDetails.m_mapCompToPermutation[sCombinationKey].push(oRegEx); // permutation map of regular expressions } } } } objProductDetails.m_bFullPermutation = true; } else { objProductDetails.m_mapCompToPermutation['EMPTY'] = ''; // no permutation! } }<file_sep>/www.cater4you.co.uk/acatalog/responsive-checkout.js /*************************************************************** * * Responsive Checkout * Bee Web Design * ***************************************************************/ function responsivecheckout() { var delivertodifferentaddress = function() { if ($('input#idSEPARATESHIP').is(':checked')) { $(".InvoiceField").removeClass("wide"); $(".InvoiceFieldLabel").removeClass("wide"); } else { $(".InvoiceField").addClass("wide"); $(".InvoiceFieldLabel").addClass("wide"); $("#idBothAddressesTable tr.ShowAlways #idDeliverHeader").css("display", "none"); } } delivertodifferentaddress(); $("input#idSEPARATESHIP").click(function() { delivertodifferentaddress(); }); }<file_sep>/www.cater4you.co.uk/acatalog/actinicextras.js /*************************************************************** * * ActinicExtras.js - additional utility functions * * Copyright (c) 2014 SellerDeck Limited * ****************************************************************/ var bDebug = false; var bShowErrors = true; var g_arrAJAX = []; // array of actions to pass to script var g_mapAJAXArgs = {}; // map of parameters to pass to script var g_mapAJAXResults = {}; // map of results from script var g_mapDynPrices = {}; // // Stock information - retained in page after initial download // var g_mapStockByRef = {}; // map of stock levels obtained from server var g_bStockUpdateInProgress = false; var g_bDynamicPriceUpdatePending = false; var g_bChoicesUpdatePending = false; // // Dispatch table for actions // var g_mapAJAXActions = { 'GetBreadcrumbTrail': SetBreadcrumbTrail }; var PRICING_MODEL_COMPONENTS_SUM = 1; /*********************************************************************** * * AddAJAXCall - Add an ajax call to the list * * Input: arguments - first item is the action, rest are parameters to pass to the script * ************************************************************************/ function AddAJAXCall() { var sAction = arguments[0]; g_arrAJAX.push(sAction); // add the action to the array for (var i = 1; i < arguments.length; i++) // make sure the rest of the arguments are only added once { if (!g_mapAJAXArgs[arguments[i]]) // not already added? { g_mapAJAXArgs[arguments[i]] = 1; // add the argument } } } /*********************************************************************** * * AJAXCall - Make the ajax call and process the results * ************************************************************************/ function AJAXCall() { if (g_arrAJAX.length == 0) // if no actions, quit { return; } var ajaxRequest = new ajaxObject(g_sAJAXScriptURL); ajaxRequest.callback = function(responseText) { if (bDebug) alert(responseText); g_mapAJAXResults = responseText.parseJSON(); // parse the JSON if (g_mapAJAXResults.Error) // handle script error { if (bDebug) alert('Programming Error:' + g_mapAJAXResults.Error); } else { ProcessAJAXResults(g_mapAJAXResults); // perform necessary action } } // // Add the parameters for the script // var sParams = 'ACTIONS=' + g_arrAJAX.join(','); for (var sArg in g_mapAJAXArgs) { if (sArg) sParams += '&' + sArg; } ajaxRequest.update(sParams, "GET"); } /*********************************************************************** * * ProcessAJAXResults - Process the results of an AJAX call * * Input: mapResults - map of response JSON objects * ************************************************************************/ function ProcessAJAXResults(mapResults) { for (var sAction in mapResults) // for each action { if (g_mapAJAXActions[sAction]) // get JSON object { g_mapAJAXActions[sAction](mapResults[sAction]); // pass the object to appropriate function } } } /*********************************************************************** * * AddAJAXBreadcrumbTrail - Add an ajax call to get the dynamic breadcrumb trail * * Input: sProdRef - product reference * ************************************************************************/ function AddAJAXBreadcrumbTrail(sProdRef) { // // Get breadcrumb trail elements // var elemBreadcrumbsTop = document.getElementById('idBreadcrumbsTop'); var elemBreadcrumbsBottom = document.getElementById('idBreadcrumbsBottom'); if (!elemBreadcrumbsTop && !elemBreadcrumbsBottom) { return; } // // Return if no section links generated // var elemBreadcrumbs = elemBreadcrumbsTop || elemBreadcrumbsBottom; var collLinks = elemBreadcrumbs.getElementsByTagName('a'); if (collLinks.length == 0) { return; } AdjustPageFileNameSIDAnchor() // adjust the section ID anchor // // Add the arguments for the call // var arrExtraArgs = []; if (document.location.href.match(/\bSID=(\d+)\b/)) { arrExtraArgs.push('SID=' + RegExp.$1); // add section ID } else { return; // no SID, leave bread crumbs as they are } // // Hide the elements // if (elemBreadcrumbsTop) { elemBreadcrumbsTop.style.visibility = 'hidden'; // hide top breadcrumb } if (elemBreadcrumbsBottom) { elemBreadcrumbsBottom.style.visibility = 'hidden'; // hide bottom breadcrumb } var elemLink = collLinks[0]; if (elemLink.className.match(/\bajs-bc-home\b/)) // if home link is present { arrExtraArgs.push('ROOTCLASS=' + elemLink.className); // add the home link class } var collAll = GetAllElements(elemBreadcrumbs); for (var i = 0; i < collAll.length; i++) { if (collAll[i].className.match(/\bajs-bc-prod\b/)) // if the product element is present { arrExtraArgs.push('PRODCLASS=' + collAll[i].className); // add the class break; } } AddAJAXCall('GetBreadcrumbTrail', 'REF=' + encodeURIComponent(sProdRef), arrExtraArgs.join('&')); // add the call to the list } /*********************************************************************** * * SetBreadcrumbTrail - Update the breadcrumb trails * * Input: oResp - response JSON object * ************************************************************************/ function SetBreadcrumbTrail(oResp) { if (oResp.HTML) // if we got some HTML { var elemBreadcrumbsTop = document.getElementById('idBreadcrumbsTop'); var elemBreadcrumbsBottom = document.getElementById('idBreadcrumbsBottom'); var sHTML = decodeURIComponent(oResp.HTML); // decode it if (elemBreadcrumbsTop) // update top breadcrumb trail { elemBreadcrumbsTop.innerHTML = sHTML; elemBreadcrumbsTop.style.visibility = 'visible'; } if (elemBreadcrumbsBottom) // update bottom breadcrumb trail { elemBreadcrumbsBottom.innerHTML = sHTML; elemBreadcrumbsBottom.style.visibility = 'visible'; } } if (bDebug) alert('Breadcrumb Trail:' + (oResp.HTML || oResp.Error)); if (bShowErrors && oResp.Error) alert('Breadcrumb Trail:' + oResp.Error); } /*********************************************************************** * * AdjustPageFileNameSIDAnchor - Adjust the PAGEFILENAME value * ************************************************************************/ function AdjustPageFileNameSIDAnchor() { var elemInput = GetInputElement(document, 'PAGEFILENAME'); if (!elemInput) { return; } var sSID = GetSIDAnchor(); // get the SID anchor if (sSID) // if present { elemInput.value = elemInput.value.replace(/#SID=\d+/, '#SID=' + sSID); // adjust the input value // // Need to make sure that the correct section ID is used for dynamic breadcrumb trail // var elemSID = GetInputElement(elemInput.form, 'SID'); if (elemSID) { elemSID.value = sSID; } } } /*********************************************************************** * * GetSIDAnchor - Get the section ID from URL anchor * * Returns: string - section ID or empty string * ************************************************************************/ function GetSIDAnchor() { var aSIDAnchor = document.location.href.split('#SID='); return (aSIDAnchor.length == 2) ? aSIDAnchor[1] : ''; } /*********************************************************************** * * AppendParentSection - Add the SID to the anchor * * Input: elemLink - <a> element * nSID - section ID * ************************************************************************/ function AppendParentSection(elemLink, nSID) { if (arguments.length == 1) // if nSID isn't supplied { var elemInput = GetInputElement(document, 'PAGE'); // only do this for product pages or search results for product pages if (!elemInput || elemInput.value != 'PRODUCT') { return; } // // Need to make sure that the correct section ID is used for dynamic breadcrumb trail // var elemSID = GetInputElement(elemInput.form, 'SID'); if (elemSID) { nSID = elemSID.value; } if (elemLink.href.indexOf('?') > -1) // needs reviewing { elemLink.href += '&SID=' + nSID; } return; } elemLink.href += '#SID=' + nSID; // add an SID anchor to the link } /*********************************************************************** * * getCartItem - Gets the Actinic Cart Value & No of Items * * Input: nIndex - Cart item index to retrieve * 1 = TOTAL_VALUE * 3 = CART_COUNT * * Returns: Requested cart item or 0 (zero) if not found * ************************************************************************/ //CART_CONTENT = Cookie name //1 = TOTAL_VALUE //3 = CART_COUNT var PASSWORD_MATCH_ERROR = "Passwords do not match."; function getCartItem(nIndex) { var act_cart = getCookie("CART_CONTENT") var sTemp = (act_cart != null) ? sTemp = act_cart.split("\t") : 0; return (sTemp.length > 0) ? sTemp[nIndex] : 0; } /*********************************************************************** * * GotoAnchor - JS for jumping to an anchor - some user agents don't handle * anchors correctly if BASE HREF is present * * Input: sAnchor * * Returns: nothing * ************************************************************************/ function GotoAnchor(sAnchor) { window.location.hash = sAnchor; } // The following block implements the string.parseJSON method (function(s) { // This prototype has been adapted from https://github.com/douglascrockford/JSON-js/blob/master/json2.js. // Large comments have been removed - <NAME> 7/12/2012 // Original Authorship: <NAME> // Augment String.prototype. We do this in an immediate anonymous function to // avoid defining global variables. s.parseJSON = function(filter) { try { if (typeof JSON === 'object') // if JSON is defined, use that { return JSON.parse(this, filter); } // otherwise use old parser var j; // Walk function to implement filtering if used function walk(holder, key) { var k, v, value = holder[key]; if (value && typeof value === 'object') { for (k in value) { if (Object.prototype.hasOwnProperty.call(value, k)) { v = walk(value, k); if (v !== undefined) { value[k] = v; } else { delete value[k]; } } } } return reviver.call(holder, key, value); } // Replace certain Unicode characters with escape sequences. var text = String(this); var cx = /[\u0000\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g; cx.lastIndex = 0; if (cx.test(text)) { text = text.replace(cx, function(a) { return '\\u' + ('0000' + a.charCodeAt(0).toString(16)).slice(-4); }); } // Run the text against regular expressions that look for non-JSON patterns. if (/^[\],:{}\s]*$/ .test(text.replace(/\\(?:["\\\/bfnrt]|u[0-9a-fA-F]{4})/g, '@') .replace(/"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g, ']') .replace(/(?:^|:|,)(?:\s*\[)+/g, ''))) { // Use the eval function to compile the text j = eval('(' + text + ')'); // Optionally recursively walk the new structure, passing // each name/value pair to a reviver function for possible transformation. return typeof reviver === 'function' ? walk({ '': j }, '') : j; } } catch (e) { // Fall through if the regexp test fails. } // If the text is not JSON parseable, then a SyntaxError is thrown. throw new SyntaxError("parseJSON"); }; })(String.prototype); // End public domain parseJSON block /*********************************************************************** * * ajaxObject - ajax communication library * * Input: url - the url of the json provider * callbackFunction - what function to call after communication * * Returns: nothing * ************************************************************************/ function ajaxObject(url, callbackFunction) { if (url.match(/^https?:/)) { // // Adjust the URL to match the document protocol // var sDocProto = document.location.protocol; var sURLProto = url.split('//')[0]; if (sURLProto != sDocProto) { url = url.replace(new RegExp('^' + sURLProto), sDocProto); } // // Adjust the URL to match the top-level domain // var sURLHost = url.split('//')[1].split('/')[0]; if (sURLHost != document.location.host) { url = url.replace(sURLHost, document.location.host); } } var that = this; this.updating = false; this.abort = function() { if (that.updating) { that.updating = false; that.AJAX.abort(); that.AJAX = null; } } this.update = function(passData, postMethod, bAsync) { bAsync = (typeof(bAsync) !== 'undefined' ? bAsync : true); if (that.updating) { return false; } that.AJAX = null; if (window.XMLHttpRequest) { that.AJAX = new XMLHttpRequest(); } else { that.AJAX = new ActiveXObject("Microsoft.XMLHTTP"); } if (that.AJAX == null) { return false; } else { that.AJAX.onreadystatechange = function() { if (that.AJAX.readyState == 4) { that.updating = false; that.callback(that.AJAX.responseText, that.AJAX.status, that.AJAX.responseXML); that.AJAX = null; } } that.updating = new Date(); if (/post/i.test(postMethod)) { var uri = urlCall; // POST is never cached so no need to add random data; it breaks PERL parsing of POST params anyway that.AJAX.open("POST", uri, bAsync); that.AJAX.setRequestHeader("Content-type", "application/x-www-form-urlencoded"); that.AJAX.send(passData); // Content-length is provided by the browser } else { var uri = urlCall + '?' + ((passData == '') ? '' : (passData + '&')) + 'timestamp=' + (that.updating.getTime()); that.AJAX.open("GET", uri, bAsync); that.AJAX.send(null); } return true; } } var urlCall = url; this.callback = callbackFunction || function() {}; } /*********************************************************************** * * getStockNodes - Get the nodes of the DOM tree where nodes are used to * dynamic stock display. These tags are marked with "ActinicRTS" class * * Output: array of elements matching the above criteria * ************************************************************************/ function getStockNodes() { var arrOut = new Array(); if (document.evaluate) { var xpathString = "//*[@class='ActinicRTS']" var xpathResult = document.evaluate(xpathString, document, null, 0, null); while ((arrOut[arrOut.length] = xpathResult.iterateNext())) {} arrOut.pop(); } else if (document.getElementsByTagName) { var aEl = document.getElementsByTagName('*'); for (var i = 0, j = aEl.length; i < j; i += 1) { if (aEl[i].className == 'ActinicRTS') { arrOut.push(aEl[i]); }; }; }; return arrOut; } /*********************************************************************** * * getProductStock - Gets the stock for a single product * * Input: sURL - the ajax script URL to call * sProdRef - product reference * sStock - stock level (used for preview) * sShopID - the shop ID (only used in host mode) * ************************************************************************/ function getProductStock(sURL, sProdRef, sStock, sShopID) { return getStock(sURL, null, sProdRef, sStock, sShopID); } /*********************************************************************** * * getSectionStock - Gets the stock for products in a section * * Input: sURL - the ajax script URL to call * sSID - the section ID list to be passed in to the ajax script * sProdRefs - list of the products with stock monitoring on in this section * sStockList - the stock level of the products in the list above * sShopID - the shop ID (only used in host mode) * ************************************************************************/ function getSectionStock(sURL, sSID, sProdRefs, sStockList, sShopID) { return getStock(sURL, sSID, sProdRefs, sStockList, sShopID) } /*********************************************************************** * * getStock - Call our server script to determine the real time stock levels * of the products in the given section * When the page is previewed from the desktop (within EC) we do not want to make * server calls for RTS levels. Therefore in this case we are passing in the * list of stock monitored products and their offline stock level in sProdRefs and * sStockList parameters. * * Input: sURL - the ajax script URL to call * sSID - the section ID list to be passed in to the ajax script or null if for a single product * sProdRefs - list of the products with stock monitoring on in this section or a single product refence * sStockList - the stock level of the products in the list above * sShopID - the shop ID (only used in host mode) * ************************************************************************/ function getStock(sURL, sSID, sProdRefs, sStockList, sShopID) { // // In case of preview use passed in data // if (sURL.indexOf("file://") == 0) { var arrProds = sProdRefs.split("|"); var arrStock = sStockList.split("|"); for (var i = 0; i < arrProds.length; i++) { var aRef = arrProds[i].split("!"); var sKey = aRef[aRef.length - 1]; g_mapStockByRef[sKey] = arrStock[i]; } updateStockDisplay(g_mapStockByRef, true); } else { g_bStockUpdateInProgress = true; var ajaxRequest = new ajaxObject(sURL); ajaxRequest.callback = function(responseText) { if (responseText.match(/^-?\d+$/)) // if response is a number { g_mapStockByRef[sProdRefs] = responseText; // assume this is for a single product } else if (responseText) // otherwise { g_mapStockByRef = responseText.parseJSON(); // parse response as JSON } updateStockDisplay(g_mapStockByRef, true); g_bStockUpdateInProgress = false; // // update dynamic prices if the process is still pending // if (g_bDynamicPriceUpdatePending && g_sDynamicPriceURL !== '') { if (sSID == undefined) { var sSectionID = GetSIDAnchor(); if ("" == sSectionID) { var elemInput = GetInputElement(document, 'PAGE'); // only do this for product pages if (elemInput && ('PRODUCT' == elemInput.value)) { var elemSID = GetInputElement(elemInput.form, 'SID'); if (elemSID) { sSectionID = elemSID.value; } } } if (sSectionID) { getAllDynamicPrices(g_sDynamicPriceURL, sSectionID, sShopID); } } else { getAllDynamicPrices(g_sDynamicPriceURL, sSID, sShopID); } } // // update choices if the process is still pending // else if (g_bChoicesUpdatePending) { SetupChoicesAllProducts(sURL, sSID, sShopID); g_bChoicesUpdatePending = false; } } // // If we don't supply a section ID, assume this is for a single product // var sParams = (sSID != null) ? ("ACTION=GETSECTIONSTOCK&SID=" + sSID) : ("ACTION=GETSTOCK&REF=" + encodeURIComponent(sProdRefs)); if (sSID == null && nAssocProdRefSID > 0) // if we want associated product stock { sParams += '&SID=' + nAssocProdRefSID; // supply the section ID } if (sShopID) { sParams += '&SHOP=' + sShopID; } ajaxRequest.update(sParams, "GET"); } } /*********************************************************************** * * updateStockDisplay - dynamically update the DOM tree depending on stock levels * * This is called on initial page load, and then after a selection is changed. * In that case we don't want to change the selection that the user has just made, * so the bUpdateSelection parameter is false. * * Input: mapStockByRef - product ref to stock level map * bUpdateSelection - true if selections are to be updated * ************************************************************************/ function updateStockDisplay(mapStockByRef, bUpdateSelection) { // // Detect which components don't have any in-stock choices and either // prevent the component being selected or prevent parent being added to the cart // var mapOOSComps = {}; var reRTS = /\brts_([^_]+)_/; var reChk = /\bchk_(v_[^_]+_\d+)_/; // // Start with choices in dropdowns // var arrSelect = document.getElementsByTagName('SELECT'); for (var i = 0; i < arrSelect.length; i++) { var elemSelect = arrSelect[i]; if (elemSelect.name.indexOf('v_') != 0) // skip any non-attribute dropdowns eg date fields { continue; } // // Try and detect the optional element if present // var elemOptional = null; var oMatch = elemSelect.className.match(reChk); if (oMatch) elemOptional = document.getElementsByName(oMatch[1])[0]; var nInStockChoices = 0; var bSelectedByDefault = false; var bSelectNextChoice = false; for (var o = 0; o < elemSelect.options.length; o++) // go through option in dropdown { var oOpt = elemSelect.options[o]; if (oOpt.value == "" || oOpt.value == -1) { elemOptional = oOpt; // the optional ui is part of the dropdown bSelectedByDefault = !elemOptional.selected; } var sClass = oOpt.className; var oMatch = sClass.match(reRTS); if (oMatch) // does this have an associated product? { var sRef = oMatch[1]; // save assoc product reference if (mapStockByRef[sRef] != undefined && // if we have a stock level mapStockByRef[sRef] <= 0) // and it is out of stock { oOpt.disabled = true; // disable the option if (oOpt.selected) // currently selected? { oOpt.selected = false; // deselect it bSelectNextChoice = true; // set the flag to select next valid choice } } else { oOpt.disabled = false; nInStockChoices++; // increment in-stock choices if (nInStockChoices == 1 && // first valid choice? and (bSelectNextChoice || bUpdateSelection)) // changing selection { oOpt.selected = true; // select it } } } else if (oOpt.value > 0) // if this is a real choice { nInStockChoices++; // increment count if (nInStockChoices == 1 && // first choice? bUpdateSelection) // and updating selection? { oOpt.selected = true; // select it } } } if (nInStockChoices == 0 || // no in-stock choices? (elemOptional && // or optional component and !bSelectedByDefault)) // we don't want to select a valid option { if (elemOptional && // if component is optional and (elemOptional.tagName == 'INPUT' || // it's a checkbox allowing item to be chosen or not or elemOptional.value == -1)) // it's an option and value is -1 indicating "None" as an acceptable choice { if (elemOptional.tagName == 'OPTION') // optional element is an option? { if (bUpdateSelection) // if updating selection { elemOptional.selected = true; // select it } } else if (nInStockChoices == 0) // no in-stock options for this component { elemOptional.checked = false; // uncheck optional checkbox elemOptional.disabled = true; // prevent user input } } else if (elemOptional && // otherwise component is not optional - but is there a "Please Select" item there? elemOptional.value == "" && nInStockChoices > 0) // and there's some stock { if (elemOptional.tagName == 'OPTION' && // optional element is an option? bUpdateSelection) // and updating selection { elemOptional.selected = true; // select it } } else { var sParentProd = elemSelect.name.match(/^v_([^_]+)_/)[1]; mapOOSComps[sParentProd] = 1; // mark parent product as out of stock if ((nInStockChoices == 0) && (elemSelect.options.length > 0)) { // // ensure out stock choices are shown in the drop down list // if ((typeof(elemSelect.options[0]) != 'undefined') && (elemSelect.options[0].tagName == 'OPTION')) { elemSelect.options[0].selected = true; } } } } } // // Now handle radio and push buttons // var mapRBGroups = {}; var mapOptComp = {}; var arrInput = document.getElementsByTagName('INPUT'); for (var i = 0; i < arrInput.length; i++) { var bSelectedByDefault = false; var elemInput = arrInput[i]; // // Detect any optional checkboxes // if (elemInput.type == 'checkbox') { var oRef = elemInput.name.match(/^v_([^_]+)/); if (oRef) { mapOptComp['_' + oRef[1]] = elemInput; } bSelectedByDefault = elemInput.checked; // remember if it was checked by default } // // Check class name for associated prod refs // var oMatch = elemInput.className.match(reRTS); if (oMatch) { var sName = elemInput.name; // get cgi name of element if (!mapRBGroups[sName]) // if this is first time we've hit this name { // // Try and get the optional element // var elemOptional = elemInput.type == 'checkbox' ? elemInput : null; // if this is a checkbox, this is the optional element oMatch = elemInput.className.match(reChk); if (oMatch) // if optional element is in the class name elemOptional = document.getElementsByName(oMatch[1])[0]; // save it if (!elemOptional && mapOptComp[sName]) // is it in our map? elemOptional = mapOptComp[sName]; // save it var nInStockChoices = 0; // // Go though all elements with this name // var collNames = document.getElementsByName(sName); for (var n = 0; n < collNames.length; n++) { var elemName = collNames[n]; if (elemName.value == -1) elemOptional = elemName; // optional element is a radio button oMatch = elemName.className.match(reRTS); if (oMatch) // if this has an associated product { var sRef = oMatch[1]; // save product ref if (mapStockByRef[sRef] != undefined && // if we have a stock level mapStockByRef[sRef] <= 0) // and it's out of stock { elemName.disabled = true; // disable choice if (elemName.type == 'submit') { elemName.parentNode.style.display = 'none'; } } else // in stock or no stock level? { elemName.disabled = false; nInStockChoices++; // increment in-stock choices if (nInStockChoices == 1 && // first choice? bUpdateSelection && // and updating selection? bSelectedByDefault) { elemName.checked = true; // select it } } } else if (elemName.type == 'submit' || // if this is a push-button elemName.value > 0) // or a real choice { elemName.disabled = false; nInStockChoices++; // increment in-stock choices if (nInStockChoices == 1 && // first choice? bUpdateSelection) // and updating selection? { elemName.checked = true; // select it } } } if (!nInStockChoices) // handle no in-stock choices { if (elemOptional) // optional component? { if (elemOptional.type == 'radio') // if radio button optional element { if (bUpdateSelection) // updating selection? { elemOptional.checked = true; // select it } } else { if (bUpdateSelection) // updating selection? { elemOptional.checked = false; // uncheck optional checkbox } elemOptional.disabled = true; } } else { var sParentProd = sName.indexOf('_') == 0 ? sName.substr(1) : // for push buttons sName.match(/^v_([^_]+)_/)[1]; // for radio buttons mapOOSComps[sParentProd] = 1; // mark parent product as out of stock } } mapRBGroups[sName] = 1; // mark name as processed } } } // // For each product reference set the stock level and enable/disable // the controlling DIV tags in the page source // var arrStockElems = getStockNodes(); for (var nIndex = 0; nIndex < arrStockElems.length; nIndex++) { var aRef = arrStockElems[nIndex].id.split("_"); var sProdRef = aRef[aRef.length - 1]; // // Double-check each product if it's an assembly product and has mandatory components // bound to associated products with a stock level not enough for a single pack // var oProd = GetProductFromMap(sProdRef); var nAssemblyStock = -1; if (oProd && oProd.bAssemblyProduct) { if (oProd.arrComps) { for (var i = 0; i < oProd.arrComps.length; i++) { var oComp = oProd.arrComps[i]; var nQ = oComp.nQ ? oComp.nQ : 1; // default the quantity used to one if not set if (null == mapStockByRef[oComp.sAsscProdRef] || // no stock level so no stock control for this component oComp.bOpt) // or an optional component so we don't care when displaying the stock level on the page { continue; } if (!mapOOSComps[sProdRef] && !oComp.bOpt && oComp.sAsscProdRef != null && nQ > mapStockByRef[oComp.sAsscProdRef]) { mapOOSComps[sProdRef] = 1; // at least one of the components has less in stock than the quantity used } var nCompMaxStock = Math.floor(mapStockByRef[oComp.sAsscProdRef] / nQ); // max orderable from this component nAssemblyStock = (-1 == nAssemblyStock) ? nCompMaxStock : (Math.min(nAssemblyStock, nCompMaxStock)); } } if (-1 == nAssemblyStock) { mapOOSComps[sProdRef] = 1; // no stock control used for any of the associated products, so the stock is zero } } var sIDStart = aRef[0]; if (mapStockByRef[sProdRef] != null) { // // The stock level // if (sIDStart == 'StockLevel') { if (oProd && oProd.bAssemblyProduct && // ignore main product stock if an assembly product nAssemblyStock > -1) { arrStockElems[nIndex].innerHTML = nAssemblyStock; } else { arrStockElems[nIndex].innerHTML = mapStockByRef[sProdRef]; } } // // Out of stock // if (sIDStart == 'EnableIfOutOfStock') { if (((mapStockByRef[sProdRef] <= 0) && !(oProd && oProd.bAssemblyProduct)) || // ignore parent out of stock if an assembly product mapOOSComps[sProdRef]) { arrStockElems[nIndex].style.visibility = "visible"; arrStockElems[nIndex].style.display = "inline"; var elemQty = GetElementByName('Q_' + sProdRef); if (elemQty) { elemQty.value = 0; elemQty.disabled = true; } } else { arrStockElems[nIndex].style.visibility = "hidden"; arrStockElems[nIndex].style.display = "none"; } } if (sIDStart == 'RemoveIfOutOfStock') { if (((mapStockByRef[sProdRef] <= 0) && !(oProd && oProd.bAssemblyProduct)) || // ignore parent out of stock if an assembly product mapOOSComps[sProdRef]) { arrStockElems[nIndex].innerHTML = ""; } } // // In stock // if (sIDStart == 'EnableIfInStock') { if (mapStockByRef[sProdRef] > 0 && !mapOOSComps[sProdRef]) { arrStockElems[nIndex].style.visibility = "visible"; arrStockElems[nIndex].style.display = "inline"; } else { arrStockElems[nIndex].style.visibility = "hidden"; arrStockElems[nIndex].style.display = "none"; } } if (sIDStart == 'RemoveIfInStock') { if (mapStockByRef[sProdRef] > 0 && !mapOOSComps[sProdRef]) { arrStockElems[nIndex].innerHTML = ""; } } // // Generic flag to indicate ajax call went fine // if (sIDStart == 'EnableIfStockOk') { arrStockElems[nIndex].style.visibility = "visible"; arrStockElems[nIndex].style.display = "inline"; } } } } /*********************************************************************** * * DisableOOSComponents - Ensure out of stock components can't be added to the cart * * This is used to clean up the generated html to prevent optional components being added * or prevent add to cart being added * * Input: sAttrName - CGI name of the attribute * sOptCompName - CGI name of the optional component element if present * ************************************************************************/ function DisableOOSComponents(sAttrName, sOptCompName) { var collName = document.getElementsByName(sAttrName); // get elements for this name for (var i = 0; i < collName.length; i++) { var elemName = collName[i]; if (elemName.tagName == 'SELECT') // if this is a dropdown { if (elemName.options.length == 0) // with no options? { HandleAllChoicesOutOfStock(sAttrName, sOptCompName); // handle no in stock choices } else if (elemName.options.length == 1) // or if we have a single choice { if (elemName.options[0].value == -1) // and it is 'None' { elemName.options[0].selected = true; // ensure selected } else if (!elemName.options[0].value) // single 'Please select' choice { elemName.options[0].selected = false; HandleAllChoicesOutOfStock(sAttrName, sOptCompName); // handle no in stock choices } } } else if (collName.length == 1) // if single radio button { if (elemName.value == -1) // 'None' choice? { elemName.checked = true; // select it } else if (!elemName.value) // 'Please select' choice? { elemName.disabled = true; HandleAllChoicesOutOfStock(sAttrName, sOptCompName); // handle no in stock choices } } } if (collName.length == 0) // no radio or push buttons { HandleAllChoicesOutOfStock(sAttrName, sOptCompName); // handle no in stock choices } } /*********************************************************************** * * HandleAllChoicesOutOfStock - Ensure an out of stock component can't be added to the cart * * Either ensure optional checkbox is unchecked or add to cart is disabled * * Input: sAttrName - CGI name of the attribute * sOptCompName - CGI name of the optional component element if present * ************************************************************************/ function HandleAllChoicesOutOfStock(sAttrName, sOptCompName) { if (sOptCompName) // if we have a checkbox { var elemOpt = GetElementByName(sOptCompName); // get element elemOpt.checked = false; // uncheck it elemOpt.disabled = true; // prevent user changing it } else { DisableAddToCart(sAttrName); // hide add to cart for non-optional components } } /*********************************************************************** * * DisableAddToCart - Disable the add to cart button for an out of stock component * * Input: sAttrName - CGI name of the attribute * ************************************************************************/ function DisableAddToCart(sAttrName) { var oMatch = sAttrName.match(/v_([^_]+)_/); // try and get product ref from the name if (!oMatch) { return; } var sProdRef = oMatch[1]; // // Disable the quantity field so single add to cart can't be used // var elemQty = GetElementByName('Q_' + sProdRef); if (elemQty) { elemQty.value = 0; elemQty.disabled = true; } // // Now handle RTS elements if they are present // var elemStock = document.getElementById('EnableIfOutOfStock_' + sProdRef); if (elemStock) { elemStock.style.visibility = "visible"; elemStock.style.display = "inline"; } elemStock = document.getElementById('RemoveIfOutOfStock_' + sProdRef); if (elemStock) { elemStock.innerHTML = ''; } elemStock = document.getElementById('EnableIfInStock_' + sProdRef); if (elemStock) { elemStock.style.visibility = "hidden"; elemStock.style.display = ""; } } /*********************************************************************** * * GetElementByName - Get the first element with a name * * Input: sName - name of the element * * Returns: first element or null if missing * ************************************************************************/ function GetElementByName(sName) { var collName = document.getElementsByName(sName); return (collName.length == 0) ? null : collName[0]; } /*********************************************************************** * * AttachEvent - Cross browser attachEvent function * * Input: obj - object which event is to be attached * eventName - name of the event to listen * eventHandler - the function to attach to the event * ************************************************************************/ function AttachEvent(obj, eventName, eventHandler) { if (obj) { if (eventName.substring(0, 2) == "on") { eventName = eventName.substring(2, eventName.length); } if (obj.addEventListener) { obj.addEventListener(eventName, eventHandler, false); } else if (obj.attachEvent) { obj.attachEvent("on" + eventName, eventHandler); } } } /*********************************************************************** * * ValidateCartNameDetails - Validate the cart name and password for saving * * Returns: true if data is OK * ************************************************************************/ function ValidateCartNameDetails() { if (document.location.href.indexOf('SID=') > -1) // TODO: move this to a better named function { document.location.href.match(/\bSID=(\d+)/); // deduce section ID var sSID = RegExp.$1; var elemBuyNow = GetInputElement(document, 'ACTION_BUYNOW'); // cart should always have this var elemForm = elemBuyNow.form; // got the form var elemSID = GetInputElement(elemForm, 'SID'); // see if there is an SID element in the form if (!elemSID) // no element so... { elemSID = document.createElement('INPUT'); // create an element for the SID elemSID.type = 'hidden'; elemSID.name = 'SID'; elemForm.appendChild(elemSID); // add it to the form } elemSID.value = sSID; } var elemDiv = document.getElementById("idRowCartNamePassword"); if (!elemDiv) { return true; } if (elemDiv.style.display == "none") { elemDiv.style.display = ""; return (false); } var elemInput = document.getElementById("idCartName"); if (elemInput.value == '') { alert('Username must be filled in'); return false; } elemInput = document.getElementById("idCartPassword"); if (elemInput.value == '') { alert('Password must be filled in'); return false; } return true; } /*********************************************************************** * * DeliveryCountryChanged - Handler for dynamic delivery state selection * ************************************************************************/ function DeliveryCountryChanged() { CountryChanged('Delivery'); } /*********************************************************************** * * InvoiceCountryChanged - Handler for dynamic invoice state selection * ************************************************************************/ function InvoiceCountryChanged() { CountryChanged('Invoice'); } /*********************************************************************** * * CountryChanged - Handler for dynamic state selection * * Input: sLocationType - 'Invoice' or 'Delivery' * ************************************************************************/ function CountryChanged(sLocationType) { // // Get appropriate country select element // var cmbCountry = document.getElementById('lst' + sLocationType + 'Country'); // // Get appropriate state/region select element // var cmbState = document.getElementById('lst' + sLocationType + 'Region'); if (!cmbCountry) { if (cmbState) { cmbState.style.display = "none"; // hide state select } return; } SetCountryTextFieldDisplay(sLocationType, ''); if (!cmbState || !cmbState.options) { return; } // // Get appropriate state/region text element // var editState = document.getElementById('id' + sLocationType + 'RegionEdit'); var sStateName = editState ? editState.value : ''; // // Save current state value // var sCurrentState = cmbState.value; cmbState.options.length = 1; // clear the state select options if (cmbCountry.value == "UndefinedRegion") // if no country is selected { cmbState.style.display = "none"; // hide state select if (editState) { editState.style.display = ""; } return; } var chkSeparateShip = document.getElementById("idSEPARATESHIP"); var bSeparateShip = chkSeparateShip && chkSeparateShip.checked; // // Get the js country state map // var mapCountries = (sLocationType == 'Delivery') ? g_mapDeliveryCountryStateMap : g_mapInvoiceCountryStateMap; // // Get states from the map // var arrOptions = mapCountries[cmbCountry.value]; if (!arrOptions && sLocationType == 'Invoice' && !bSeparateShip && g_mapDeliveryCountryStateMap[cmbCountry.value]) { arrOptions = g_mapDeliveryCountryStateMap[cmbCountry.value]; } if (!arrOptions) // if there are no states { cmbState.style.display = "none"; // hide state select if (editState) { editState.style.display = ""; } return; } cmbState.style.display = ""; // show the state select if (editState) { editState.style.display = "none"; } var bFound = false; for (var i = 0; i < arrOptions.length; i += 2) // go through state data { var oOption = document.createElement("OPTION"); // create an option oOption.text = arrOptions[i + 1]; // set state name oOption.value = arrOptions[i]; // set state code if (oOption.value == sCurrentState || // is this our current value? oOption.text == sStateName) // or it matches the text field { bFound = true; // mark as selected sCurrentState = oOption.value; oOption.selected = true; } cmbState.options.add(oOption); // add option to select element } if (bFound) { cmbState.value = sCurrentState; // restore current selection } } /*********************************************************************** * * SetCountryTextFieldDisplay - Set display of country text field * * Input: sLocationType - 'Invoice' or 'Delivery' * sDisplay - '' to display or 'none' to hide * ************************************************************************/ function SetCountryTextFieldDisplay(sLocationType, sDisplay) { var sTextID = (sLocationType == 'Delivery') ? 'idDELIVERCOUNTRYText' : 'idINVOICECOUNTRYText'; var elemCountryText = document.getElementById(sTextID); if (elemCountryText) { // // Get appropriate country select element // var cmbCountry = document.getElementById('lst' + sLocationType + 'Country'); elemCountryText.style.display = (cmbCountry && cmbCountry.value == '---') ? sDisplay : 'none'; } } /*********************************************************************** * * SetDeliveryAddressVisibility - Handler for showing or hiding delivery address fields * ************************************************************************/ function SetDeliveryAddressVisibility() { if (document.getElementById("idInvoiceRule") || document.getElementById("idDeliveryRule")) { SetAccountAddressVisibility(); return; } var bResponsive = SD.Responsive.getResponsiveDeliveryFields(); SetInvoiceCountries(); var bDisplay = IsElementChecked("idSEPARATESHIP") if (bResponsive) { // // Hide or show delivery field divs // $("#idBothAddressesTable #idDeliverHeader").toggle(bDisplay); $("#idBothAddressesTable > > .DeliverField:not(#idSeparateShipRow)").toggle(bDisplay); // // If we aren't showing the delivery fields, make the invoice field wider // $("#idBothAddressesTable > > .InvoiceField:not(#idSeparateShipRow)").toggleClass("wideInput", !bDisplay); } else { // // Set width of separate ship cell to cover full table // $("#idSeparateShipCell").attr('colSpan', $("#idDeliverHeader").length && bDisplay ? 2 : 1); // // Hide or show delivery fields as required // $("#idBothAddressesTable > > tr > td.DeliverField").toggle(bDisplay); } // // Hide residential flag for Invoice address if delivery address shown // $("#idINVOICERESIDENTIAL").toggle(!bDisplay); InvoiceCountryChanged(); } /*********************************************************************** * * SetAccountAddressVisibility - Handler for showing or hiding delivery address fields * ************************************************************************/ function SetAccountAddressVisibility() { var bResponsive = SD.Responsive.getResponsiveDeliveryFields(); /*********************************************************************** * * SetAddressesTableCellsChildDisplay - Show or hide cell's children in addresses table based on cell class name * * Input: sClassName - class name of cells to show or hide * bDisplay - show or hide * bBothDisplayed - are both sets of fields being displayed? * ************************************************************************/ var SetAddressesTableCellsChildDisplay = function(sClassName, bDisplay, bBothDisplayed) { if (bResponsive) { $("#idBothAddressesTable >") // select fieldset .children("." + sClassName) // children of the given class - should all be divs .filter("div:not(#idInvoiceAccountAddresses, #idDeliverAccountAddresses, #idSeparateShipRow)") // field divs only .toggle(bDisplay) // hide or show .toggleClass("wideInput", bDisplay && !bBothDisplayed); // add wideInput if we are showing this field and not both fields are displayed } else { $("#idBothAddressesTable tr:not(.ShowAlways) ." + sClassName) // all rows that don't have class ShowAlways and have matching sClassName elements .children() // we are hiding/showing elements in the cells .filter(":not([id^='pcaDiv'])") // not the post-code anywhere div .toggle(bDisplay); // display or not display } } var bNewInvoiceAddress = IsElementChecked("idINVOICEADDRESSSELECT_0"); var bNewDeliverAddress = IsElementChecked("idDELIVERADDRESSSELECT_0"); // // Hide address fields is neither 'Or enter new address is enabled // var bDisplay = (bNewInvoiceAddress || bNewDeliverAddress); // // Show or hide the delivery/invoice address area as appropriate // var jqElements; if (bResponsive) { jqElements = $("#idBothAddressesTable >"). // select fieldset children("div:not(#idInvoiceAccountAddresses, #idDeliverAccountAddresses), label, input"); // field divs, label or input checkbox children } else { // // As there are nested table rows that don't have a class of ShowAlways, // make sure that we only choose children of outer table that don't have ShowAlways // jqElements = $("#idBothAddressesTable > > tr:not(.ShowAlways)"); } jqElements.toggle(bDisplay); // hide or show if (!bDisplay) // nothing more to do if we're hiding rows { return; } // // Calculate delivery fields value // Show only if necessary // var bDeliveryDisplayed = false; if (bNewDeliverAddress) { if (!bNewInvoiceAddress || // if we're just showing delivery fields IsElementChecked("idSEPARATESHIP")) // or we showing a different delivery address from user entered invoice address { bDeliveryDisplayed = true; // display delivery fields } } var bBothDisplayed = (bNewInvoiceAddress && bDeliveryDisplayed); // both sets of fields displayed? // // Handle invoice fields // Simply hide or show depending on corresponding radio button // SetAddressesTableCellsChildDisplay("InvoiceField", bNewInvoiceAddress, bBothDisplayed); if (bNewInvoiceAddress) { InvoiceCountryChanged(); } SetAddressesTableCellsChildDisplay("DeliverField", bDeliveryDisplayed, bBothDisplayed); if (bDeliveryDisplayed) { DeliveryCountryChanged(); // call state/country set up after general blitz of delivery fields } // // Show the separate ship button if both addresses possible // $("#idSeparateShipRow").toggle(bNewInvoiceAddress && bNewDeliverAddress); } /*********************************************************************** * * IsElementChecked - Returns whether a radio-button or checkbox is checked * * Input: sID - id of element to check * * Returns: true if element exists and ic checked * ************************************************************************/ function IsElementChecked(sID) { var elemCheck = document.getElementById(sID); if (elemCheck && elemCheck.checked) { return true; } return false; } /*********************************************************************** * * SetShoppingCartVisibility - Handler for showing or hiding cart details * ************************************************************************/ function SetShoppingCartVisibility() { var elemShowHide = document.getElementById("idShowHide"); if (!elemShowHide) { return; } var spanShoppingCart = document.getElementById("idShoppingCartGrid"); if (!spanShoppingCart) { return; } var elemCartHeadingTotal = document.getElementById("idCartHeadingTotal"); var elemCartChangeCell = document.getElementById("idCartChangeCell"); if (spanShoppingCart.style.display == "none") { setCookie('cartDisplayPreference', 'show'); spanShoppingCart.style.display = ""; elemShowHide.innerHTML = 'hide'; elemCartHeadingTotal.style.display = 'none'; if (elemCartChangeCell) { document.getElementById("idCartChangeCell").style.display = ''; } } else { setCookie('cartDisplayPreference', 'hide'); spanShoppingCart.style.display = "none"; elemShowHide.innerHTML = 'show'; elemCartHeadingTotal.style.display = ''; if (elemCartChangeCell) { document.getElementById("idCartChangeCell").style.display = 'none'; } } } /*********************************************************************** * * HideCartDetailsOnCheckoutPages - Hiding cart details on all but the first page by default * ************************************************************************/ function HideCartDetailsOnCheckoutPages() { var sCartDisplayPreference = getCookie('cartDisplayPreference'); if (sCartDisplayPreference !== 'show') { SetShoppingCartVisibility(); } } /*********************************************************************** * * SetCreditCardFieldsVisibility - Handler for showing or hiding credit card fields * ************************************************************************/ function SetCreditCardFieldsVisibility() { // // Hide or show fields used for entering credit card details // // For the non-responsive checkout we have a table with id idPaymentMethodTable, with rows with class CreditCardField below it. // For responsive, we have a div with id idPaymentMethodTable with divs with class CreditCardField below it (but in a tbody in the dom) // // Therefore to be compatible with both we simple ignore the type of elements // $("#idPaymentMethodTable .CreditCardField").toggle(GetPaymentMethod() == "10005"); // // v12 Finance code // if (GetPaymentMethod() !== "90") { $("#idPaymentMethodTable .v12FinanceFields").hide(); return; } GetAvailableFinanceProducts(); } /*********************************************************************** * * CheckForm - Validate a form before submission * * Input: elemBtn - element doing the submission * * Returns: true to let form submit, false to prevent bubbling up * ************************************************************************/ function CheckForm(elemBtn) { // // Find the form element in ancestors // var elemForm = elemBtn.parentElement ? elemBtn.parentElement : elemBtn.parentNode; while (elemForm && elemForm.tagName != "FORM") { elemForm = elemForm.parentElement ? elemForm.parentElement : elemForm.parentNode; } if (!elemForm) // if form doesn't exist, bail out { return true; } // // We are submitting a form, add a hidden parameter JS="1" // to indicate that Javascript is enabled in this browser // $('#idCheckoutForm').append('<input type="hidden" name="JS" value="1" />'); if ($('#idPickupSelect') && $('#lstClass').prop("disabled")) // make sure that the shipping class value is posted even if dropdown disabled { $('#idCheckoutForm').append('<input type="hidden" name="ShippingClass" value="' + $('#lstClass').val() + '" />'); } // // Decide whether we should validate the confirmation email address // We don't confirm emails if we're selecting an account address // or a delivery address if it is the same as invoice address // var bAccountCustomer = (document.getElementsByName('INVOICEADDRESSSELECT').length > 0); var bSkipInvoice = false; if (bAccountCustomer) { bSkipInvoice = !IsElementChecked("idINVOICEADDRESSSELECT_0"); // skip invoice if we're selecting an address } var chkSeparateShip = document.getElementById('idSEPARATESHIP'); var bSkipDeliver = false; if (bAccountCustomer) { bSkipDeliver = !IsElementChecked("idDELIVERADDRESSSELECT_0"); // skip delivery if we're selecting an address } if (!bSkipDeliver) // if we're not selecting an address { bSkipDeliver = (chkSeparateShip && !chkSeparateShip.checked); // skip if delivery is same as invoice } if (bSkipInvoice && bSkipDeliver) // if we skip both addresses { return true; // nothing to check } var arrDescendants = GetAllElements(elemForm); for (var i = 0; i < arrDescendants.length; i++) { var elemThis = arrDescendants[i]; if ((elemThis.id == 'idINVOICEEMAIL_CONFIRM' && !bSkipInvoice) || (elemThis.id == 'idDELIVEREMAIL_CONFIRM' && !bSkipDeliver)) { var elemEmail = document.getElementById(elemThis.id.replace(/_CONFIRM$/, '')); if (elemEmail.style.display != 'none' && elemEmail.value != elemThis.value) { var sMsg = GetLabelText(elemThis) + "\n\n"; sMsg += "'" + elemThis.value + "' does not match '" + elemEmail.value + "'"; alert(sMsg); elemThis.focus(); return false; } } if ((elemThis.id == 'idNEWCUSTOMERPASSWORD2') && (IsElementChecked('idCREATEANACCOUNT') || document.getElementById('idCREATEANACCOUNT') == null)) { var elemPwd = document.getElementById('idNEWCUSTOMERPASSWORD'); if (elemPwd.style.display != 'none' && elemPwd.value != elemThis.value) { var sMsg = PASSWORD_MATCH_ERROR; alert(sMsg); elemThis.focus(); return false; } } } if (bSkipInvoice && !bSkipDeliver) { chkSeparateShip.checked = true; } return true; } /*********************************************************************** * * GetAllElements - Get all descendants of an element * * Input: elemParent - parent element * * Returns: collection of descendant elements * ************************************************************************/ function GetAllElements(elemParent) { if (elemParent.all) // IE-specific { return elemParent.all; } else if (elemParent.getElementsByTagName) // W3C compliant browsers { return elemParent.getElementsByTagName('*'); } } /*********************************************************************** * * SubmitPSPForm - Submit a form to a PSP * * Input: sShopID - the shop ID (only used in host mode) * * Returns: true to let form submit, false to prevent bubbling up * ************************************************************************/ var g_sConfirmOrderInitText = ''; function SubmitPSPForm(sShopID) { if (GetPaymentMethod() === "90") // v12 Finance { var sError = CheckMinMaxDeposit() if (sError !== "") { $("#idFinanceDepositError").html(sError); $("#idFinanceDepositError").show(); $("#idFinanceDeposit").focus(); return false; } } var nPaymentMethod = GetPaymentMethod(); if (nPaymentMethod == -1) { return true; } // // Drop a hidden wait message into the span place folder for the PSP form // Display the message on a greyed screen that disables all further input // var elemSpanPSPForm = document.getElementById("idSpanPSPForm"); if (elemSpanPSPForm) { elemSpanPSPForm.innerHTML = '<div id="pspwait" style="display:none;">Saving your order... Please wait</div>'; ShowPSPWait('pspwait'); ShowPSPForm(); } if (nPaymentMethod >= 10000 && nPaymentMethod < 30000) // if this ia an inbuilt payment method { return true; // don't get PSP form } GetPSPFormAndSubmit(nPaymentMethod, sShopID); return false; } /*********************************************************************** * * SubmitPPEForm - Submit the PayPal Express form * * Input: pForm - the form object * * Returns: false to prevent calling method from submitting form * ************************************************************************/ var g_bConfirmOrderDone = false; function SubmitPPEForm(pForm) { if (g_bConfirmOrderDone) // have we already submitted the form? { alert("Your order is being completed"); // tell the user what's happening return false; } g_bConfirmOrderDone = true; if ($('#idPickupSelect') && $('#lstClass').prop("disabled")) // make sure that the shipping class value is posted even if dropdown disabled { $(pForm).append('<input type="hidden" name="ShippingClass" value="' + $('#lstClass').val() + '" />'); } pForm.submit(); // submit the form return false; } /*********************************************************************** * * GetPaymentMethod - Get the payment method * * Returns: payment method or -1 if not found * ************************************************************************/ function GetPaymentMethod() { var cmbPaymentMethod = document.getElementById("idPAYMENTMETHOD"); if (cmbPaymentMethod) // if we have an element with correct id { return cmbPaymentMethod.value; // return it } // // Get radio buttons or hidden by name if present // var collPaymentMethods = document.getElementsByName("PAYMENTMETHOD"); if (!collPaymentMethods) { return -1; } if (collPaymentMethods.length == 1) // might have a single method in which case it will be hidden input { return collPaymentMethods[0].value; } for (var i = 0; i < collPaymentMethods.length; i++) // find checked radio button { if (collPaymentMethods[i].checked) { return collPaymentMethods[i].value; } } return -1; } /*********************************************************************** * * GetPSPFormAndSubmit - Submit a form to a PSP * * Input: nPaymentMethod - payment method * sShopID - the shop ID (only used in host mode) * ************************************************************************/ function GetPSPFormAndSubmit(nPaymentMethod, sShopID) { var ajaxRequest = new ajaxObject(document.location.href.split('?')[0]); ajaxRequest.callback = function(responseText, responseStatus) { if ((200 != responseStatus) || (responseText.substring(0, 6) == "Error:")) { alert(responseText); ShowPSPForm(false); // make sure the pop up window is removed return; } // // Get the placeholder span for the PSP form // var elemSpanPSPForm = document.getElementById("idSpanPSPForm"); if (!elemSpanPSPForm) { return; } elemSpanPSPForm.innerHTML = responseText; // // Try to get the standard PSP form // var elemPSPForm = document.getElementById("idPSPForm"); if (elemPSPForm) { // // Submit the PSP form if present // elemPSPForm.submit(); return; } // // If not found then this may be an InContext PSP // // Note: We are using file type .htm with .js to be able to maintain backwards compatibility // Only .htm or .html files are not signed by ISControl.ocx. // If the js file is signed it won't work // RequireScript("psplib" + nPaymentMethod + ".htm.js", function() { GetPSPHelper(); // call the PSP Helper function } ); return; } var sParams = "ACTION=GETPSPFORM&PAYMENTMETHOD=" + nPaymentMethod; if (sShopID) { sParams += '&SHOP=' + sShopID; } var elemPONumber = document.getElementsByName('PAYMENTPONO'); if (elemPONumber.length) { sParams += '&PAYMENTPONO=' + escape(elemPONumber[0].value); } var elemPayUserDef = document.getElementsByName('PAYMENTUSERDEFINED'); if (elemPayUserDef.length) { sParams += '&PAYMENTUSERDEFINED=' + escape(elemPayUserDef[0].value); } if ("90" === nPaymentMethod) { sParams += GetParams(); // add DEPOSIT, PRODUCTID and PRODUCTGUID } ajaxRequest.update(sParams, "GET"); } /*********************************************************************** * * CloseForm - Close the pop up form, called directly from the checkout page * ************************************************************************/ function CloseForm() { ShowPSPForm(false); // make sure the pop up window is removed } /*********************************************************************** * * RequireScript - Add a required script to the DOM and optionally call a * function when the script has loaded * * Input: sFile - name of the script to load * callback - callback function to run after script is loaded (optional) * ************************************************************************/ function RequireScript(sFile, callback) { var newjs = document.createElement('script'); var script = document.getElementsByTagName('script')[0]; // // error handler // newjs.onerror = function() { alert('Error loading [' + sFile + ']. Please try another payment method.'); ShowPSPForm(false); // make sure the pop up window is removed return; }; // // IE file loaded event // if (callback != undefined) { newjs.onreadystatechange = function() { if (newjs.readyState === 'loaded' || newjs.readyState === 'complete') { callback(); } }; // // Other browsers file loaded event // newjs.onload = function() { callback(); }; } newjs.src = sFile; script.parentNode.insertBefore(newjs, script); } /*********************************************************************** * * ShowPSPForm - Show or hide the PSP form * * Input: bShow - true to show, false to hide * optional, default is true * ************************************************************************/ function ShowPSPForm(bShow) { var elemDivPSPForm = document.getElementById("idDivPSPForm"); if (elemDivPSPForm) { if (bShow == null || bShow) { elemDivPSPForm.style.display = 'inline'; } else { elemDivPSPForm.style.display = 'none'; } } } /*********************************************************************** * * ShowPSPWait - Show or hide a PSP wait message * * Input: id - id of the message to show or hide * bShow - true to show, false to hide * optional, default is true * ************************************************************************/ function ShowPSPWait(id, bShow) { if (bShow == null || bShow) { // // Show the message and then the panel // document.getElementById(id).style.display = 'inline'; document.getElementById('pspwait').style.display = 'inline'; } else { // // hide the panel and then the message // document.getElementById('pspwait').style.display = 'none'; document.getElementById(id).style.display = 'none'; } } /*********************************************************************** * * SFDropDownMenu - Javascript function to handle Suckerfish drop-down menus in IE * * Input: sID - ID of the <UL> element * ************************************************************************/ function SFDropDownMenu(sID) { var collElems = document.getElementById(sID).getElementsByTagName("LI"); for (var i = 0; i < collElems.length; i++) { collElems[i].onmouseover = function() { this.className += " sfhover"; } collElems[i].onmouseout = function() { this.className = this.className.replace(new RegExp(" sfhover\\b"), ""); } } } /*********************************************************************** * * ShowHideHelp - Show or hide the help for a field under the field * * Input: elemSource - the field control * sDisplay - string to set style.display ('' to show, 'none' to hide) * ************************************************************************/ function ShowHideHelp(elemSource, sDisplay) { var elemHelp = document.getElementById(elemSource.id + 'help'); // get associated help element if (!elemHelp) { return; } elemHelp.style.display = sDisplay; // show or hide help element } /*********************************************************************** * * ShowHideHelpDiv - Show or hide the help for a field in the help area * * Input: elemSource - the field control * sDisplay - string to set style.display ('' to show, 'none' to hide) * ************************************************************************/ function ShowHideHelpDiv(elemSource, sDisplay) { var elemHelp = document.getElementById(elemSource.id + 'help'); // get associated help element if (!elemHelp) { return; } var elemHelpElem = document.getElementById('idCheckoutHelp'); // get help display element if (!elemHelpElem) { return; } var sText = elemHelp.innerHTML; var elemLabel = document.getElementById(elemSource.id + 'label'); // try and get label area if (elemLabel && elemLabel.className == 'actrequired') // if it's a required field { sText += ' This is a required field.'; // tell user } elemHelpElem.innerHTML = sDisplay == '' ? sText : ''; // set html for help display } /*********************************************************************** * * GetLabelText - Get the label text associated with a control * * Input: elemSource - user UI element * ************************************************************************/ function GetLabelText(elemSource) { var elemLabel = document.getElementById(elemSource.id + 'label'); // try and get label area if (!elemLabel) { elemLabel = document.getElementById(elemSource.id.replace(/DELIVER/, 'INVOICE') + 'label'); } if (elemLabel) { var sLabel = elemLabel.innerHTML; sLabel = sLabel.replace(/(\n|\t)/, ' '); sLabel = sLabel.replace(/<.*?>/g, ''); sLabel = sLabel.replace(/\s*\*$/, ''); return sLabel; } return ''; } /*********************************************************************** * * SetFocusToID - Set focus to element with supplied id * * Input: sID - id of element * ************************************************************************/ function SetFocusToID(sID) { var elemFocus = document.getElementById(sID); // get element to set focus to if (!elemFocus) { return; } if (elemFocus.style.display != 'none') elemFocus.focus(); // set focus } /*********************************************************************** * * SetInvoiceCountries - Populate the invoice countries dropdown depending upon * different address checkbox * ************************************************************************/ var g_sInvoiceCountryCode = ''; function SetInvoiceCountries() { var cmbCountry = document.getElementById('lstInvoiceCountry'); if (!cmbCountry || !cmbCountry.options) { return; } var editCountry = document.getElementById('idINVOICECOUNTRYText'); var chkSeparateShip = document.getElementById('idSEPARATESHIP'); var bSeparateShip = (chkSeparateShip && chkSeparateShip.checked) ? true : false; // // Save current country value // var sCurrentCountryCode = cmbCountry.value ? cmbCountry.value : g_sInvoiceCountryCode; var sCurrentCountryText = ((sCurrentCountryCode == '' || sCurrentCountryCode == '---') && editCountry) ? editCountry.value : ''; cmbCountry.options.length = 1; // clear the state select options except for 'Select country' var sFoundCode = ''; var sFoundNameCode = ''; for (var i in g_arrCountries) { var arrCountry = g_arrCountries[i]; var bAdd = true; if (g_bInvoiceLocationRestrictive) { if (!bSeparateShip && g_bDeliveryLocationRestrictive) { bAdd = arrCountry[2] && arrCountry[3]; } else { bAdd = arrCountry[2]; } } else if (g_bDeliveryLocationRestrictive && !bSeparateShip) { bAdd = arrCountry[3]; } else { bAdd = arrCountry[2] || arrCountry[3]; } if (bAdd) { var oOption = document.createElement("OPTION"); // create an option oOption.value = arrCountry[0]; // set country code oOption.text = arrCountry[1]; // set country name if (sCurrentCountryCode && oOption.value == sCurrentCountryCode) // if it matches the code { sFoundCode = oOption.value; } if (sCurrentCountryCode != '---' && oOption.text == sCurrentCountryText) // if it matches the code { sFoundNameCode = oOption.value; } cmbCountry.options.add(oOption); // add option to select element } } if (sFoundCode) { cmbCountry.value = sFoundCode; } if (sFoundNameCode) { cmbCountry.value = sFoundNameCode; } if (cmbCountry.value) { g_sInvoiceCountryCode = cmbCountry.value; } } /*********************************************************************** * * StateDropdownChanged - The selection in state dropdown has changed * * Input: cmbState - state dropdown * ************************************************************************/ function StateDropdownChanged(cmbState) { // // Get edit control // var idEdit = (cmbState.id.indexOf('Invoice') != -1) ? 'idInvoiceRegionEdit' : 'idDeliveryRegionEdit'; var editState = document.getElementById(idEdit); if (!editState || // if there's no text control cmbState.value == 'UndefinedRegion') // or the state is undefined { return; // quit } // // Update the text control with the text from combo // var nIndex = cmbState.selectedIndex; editState.value = cmbState.options[nIndex].text; } /*********************************************************************** * * LoadXMLDoc - Load the doc specified by input URL and return the XML response * * Input: sURL - URL of document * bReturnDoc - true if we want DOM document, false if we want XML string * * Returns: DOM document or XML string * ************************************************************************/ function LoadXMLDoc(sURL, bReturnDoc) { if (window.XMLHttpRequest) { xhttp = new XMLHttpRequest(); } else { xhttp = new ActiveXObject("Microsoft.XMLHTTP"); } xhttp.open("GET", sURL, false); xhttp.send(null); if (bReturnDoc) { return xhttp.responseXML; } else { return xhttp.responseText; } } /*********************************************************************** * * DOMDocFromXML - Create a DOM document from an XML string * * Input: sXML - source XML string * * Returns: DOM document or null if no parser supported * ************************************************************************/ function DOMDocFromXML(sXML) { var docDOM = null; if (window.ActiveXObject) // IE code { docDOM = new ActiveXObject("Microsoft.XMLDOM"); docDOM.async = "false"; docDOM.loadXML(sXML); } else if (window.DOMParser) // other browsers { var oParser = new DOMParser(); docDOM = oParser.parseFromString(sXML, "text/xml"); } return docDOM; } /*********************************************************************** * * DisplayFeefoFeedback - Display the feefo XML feed for products or the whole site * * Input: nLimit - the max number of comments to be displayed * sSiteURL - URL of the acatalog folder (needed to prefix extra data) * sCGIURL - URL to the cart script wrapper * sLogon - feefo logon * sProduct - the product reference (if this is an empty string, site feed displayed) * sShopID - shop ID for host mode (empty string in non-host mode) * ************************************************************************/ function DisplayFeefoFeedback(nLimit, sSiteURL, sCGIURL, sLogon, sProduct, sShopID) { var sParams = escape("?logon=" + sLogon); // escape the parameter // // If product ref specified then add it to the param String // var sNode = "FeefoFeedback"; if (sProduct != "") { sParams += escape("&vendorref=" + sProduct); sNode += "_" + sProduct; } // // Add the limit parameter // sParams += escape("&limit=" + nLimit); // // We need cdata // sParams += escape("&mozillahack=true"); // // Load the files // var sFeefoURL = sCGIURL + "?ACTION=FEEFOXML&FEEFOPARAM=" + sParams; if (sShopID) // add shop id in host mode { sFeefoURL += "&SHOP=" + escape(sShopID); } var xml = LoadXMLDoc(sFeefoURL, true); //?logon=www.examplesupplier.com"); if (xml == null || xml.xml == "") { return; } var sXslXML = LoadXMLDoc(sSiteURL + "feedback.xsl", false); // get xsl as string // // Convert css and image files to full URLs // var reFiles = /(feefo\.css|plus\.gif|minus\.gif)/ig; sXslXML = sXslXML.replace(reFiles, sSiteURL + "$1"); // convert to full URLs var docXSL = DOMDocFromXML(sXslXML); // create a DOM doc from XML string // // code for IE // if (window.ActiveXObject) { ex = xml.transformNode(docXSL); document.getElementById(sNode).innerHTML = ex; } // // code for Mozilla, Firefox, Opera, etc. // else if (document.implementation && document.implementation.createDocument) { xsltProcessor = new XSLTProcessor(); xsltProcessor.importStylesheet(docXSL); resultDocument = xsltProcessor.transformToFragment(xml, document); document.getElementById(sNode).appendChild(resultDocument); } } /*********************************************************************** * * ShowBackLink - Display the back link for SPP pages * ************************************************************************/ function ShowBackLink() { var sLastSection = getCookie('LAST_SECTION_URL'); // get last section page URL if (!sLastSection) { return; } var elemBackLink = document.getElementById('idSPPBackLink'); // get the back link if (!elemBackLink) { return; } elemBackLink.href = sLastSection; // set the url elemBackLink.style.display = ''; // show the link } /*********************************************************************** * * CheckPassword - Do the passwords match * * Input: elemPwd - password element * elemRetype - confirm password element * * Returns: true if the two passwords match * ************************************************************************/ function CheckPassword(elemPwd, elemRetype) { if (!elemPwd.value || !elemRetype.value || elemPwd.value != elemRetype.value) { var sMsg = PASSWORD_MATCH_ERROR; var elemFocus = elemPwd; if (!elemPwd.value) { sMsg = 'Please enter a value for ' + GetLabelText(elemPwd); } else if (!elemRetype.value) { sMsg = 'Please enter a value for ' + GetLabelText(elemRetype); elemFocus = elemRetype; } alert(sMsg); elemFocus.focus(); return false; } return true; } /*********************************************************************** * * GetScriptURL - Get the current location with no parameters * * Returns: current location with any parameters removed * ************************************************************************/ function GetScriptURL() { var sURL = document.location.href; return sURL.split('?')[0]; } /*************************************************************** * * IsLoggedIn - Returns whether the user is logged in * ***************************************************************/ function IsLoggedIn() { var sBusinessCookie = getCookie('ACTINIC_BUSINESS'); if (!sBusinessCookie) { return false; } var arrFields = sBusinessCookie.split(/\n/); for (var i = 0; i < arrFields.length; i++) { var arrNameValue = arrFields[i].split(/\t/); if (arrNameValue[0] == 'USERNAME' && arrNameValue[1] != '') { return true; } } return false; } /*************************************************************** * * GetScriptPrefix - Returns the 2 letter script prefix * ***************************************************************/ function GetScriptPrefix() { var nLastSlash = location.pathname.lastIndexOf('/'); if (nLastSlash != -1) { var sScript = location.pathname.substr(nLastSlash + 1); return sScript.substr(0, 2); } } /*************************************************************** * * SetBusinessCookies - Sets business cookies for customer accounts in split SSL * * Input: sBusinessCookie - business cookie or undefined if logging out * sCartCookie - cart cookie (ignored if logging out) * ***************************************************************/ function SetBusinessCookies(sBusinessCookie, sCartCookie) { if (!sBusinessCookie) { setCookie('CART_CONTENT', 'CART_TOTAL\t0\tCART_COUNT\t0'); setCookie('ACTINIC_BUSINESS', 'BASEFILE'); document.location.replace(document.location.href.replace(/#logout$/, '')); } } /*************************************************************** * * OnKeyDownForm - Handle a key-down even in the login form * * This is to workaround an IE9 bug that prevents the enter key * from submitting the login form * ***************************************************************/ function OnKeyDownForm() { if (/MSIE (\d+\.\d+);/.test(navigator.userAgent)) // test for IE { var nVersion = new Number(RegExp.$1) // get the version if (nVersion >= 9) // if it is IE9 { if (window.event.keyCode == 13) // if this is the Enter key { var elemSrc = window.event.srcElement; // get element that received the key press if (elemSrc.tagName == 'INPUT' && (elemSrc.type == 'submit' || elemSrc.type == 'button')) // if it is a button { return; // let browser handle it } for (var i = 0; i < elemSrc.form.all.length; i++) { var elemHTML = elemSrc.form.all[i]; if (elemHTML.tagName == 'INPUT' && elemHTML.type == 'submit') // if this is a submit button { elemHTML.click(); // simulate a click window.event.cancelBubble = true; // we've handled the key-press window.event.returnValue = false; return; } } } } } } /*********************************************************************** * * Sprintf - Very simple emulation of sprintf * * Only %s format specifier is supported and not tested against things like %%s * * Input: sFormat - format string * ... - arguments to substitute * * Returns: formatted string * ***********************************************************************/ function Sprintf(sFormat) { var sResult = sFormat; for (var i = 1; i < arguments.length; i++) { sResult = sResult.replace(/%s/, arguments[i]); } return sResult; } /*********************************************************************** * * Actinic Mega Menu * * Author: <NAME> * Modified by: <NAME> * <NAME> * ************************************************************************/ // // Variables // var g_mm_nMenuCloseTimeout = 500; // period of time that the menu remains before being cleared var g_mm_closeTimer = null; // ID of close timer var g_mm_menuParent = null; // active parent menu element var g_mm_menuItem = null; // active sub-menu element var g_mm_NO_MENU_ITEM = -1; // constant to indicate no menu item active var g_mm_nIDRecentMouseOver = g_mm_NO_MENU_ITEM; // menu item that had a recent mouseover - used to detect click via a touch device var g_mm_timerRecentMouseOver = null; // timer for recent mouseover var g_mm_nIDForMouseUp = g_mm_NO_MENU_ITEM; // menu item that had a mouseup. If a mouseout occurs immediately afterwards, then it's a windows device and we ignore mouseout var g_mm_nWindowsTouchOn = g_mm_NO_MENU_ITEM; // for windows devices, there was a touch on this menu var g_mm_mapListenersAdded = {}; // we add listeners to menu items - this map prevents us doing this multiple times /*********************************************************************** * * $tb - Shortcut for getElementById(element) * Returns: - element with matching ID * * Author: <NAME> * ************************************************************************/ var $ge = function(id) { return document.getElementById(id); }; /*********************************************************************** * * mmClick - handle a mega menu main item click. Prevent click on touch devices in some circumstances * * Input: evClick - event * nID - ID of mega menu * * Returns: false if preventing click; modifies ev. * ************************************************************************/ function mmClick(evClick, nID) { // // We detect a tap on the mega menu item if there is a mouseover directly followed by a click event. // On some touch devices the delay from the mouseover to the click can be significant - 300ms to 400ms. // Therefore we ignore click events for a button for a period after the mouseover. // g_mm_nIDRecentMouseOver is set to the id of the mega menu being shown during the period after the mouseover. // This means that the first tap opens up a mega menu, and a second tap follows the hotlink. // if (g_mm_nIDRecentMouseOver == nID) // recent mouseover for this mega menu tab? { if (evClick.preventDefault) // might not support in IE older versions { evClick.preventDefault(); // don't allow the click } return false; } } /*********************************************************************** * * mmClose - Hides the menu element * Returns: - nothing * * Author: <NAME> * ************************************************************************/ function mmClose() { if (g_mm_menuItem) { g_mm_menuItem.style.display = 'none'; g_mm_menuItem = null; } if (g_mm_menuParent) { g_mm_menuParent.className = ''; g_mm_menuParent = null; } } /*********************************************************************** * * mmCloseTime - Starts mega menu closing timer * Returns: - nothing * * Author: <NAME> * ************************************************************************/ function mmCloseTime() { // // If a normal mouseout then we just set up to close the menu // if (g_mm_nIDForMouseUp == g_mm_NO_MENU_ITEM) { if (g_mm_closeTimer) { window.clearTimeout(g_mm_closeTimer); g_mm_closeTimer = null; } g_mm_closeTimer = window.setTimeout(mmClose, g_mm_nMenuCloseTimeout); } else { // // In this case the mouseout occurred while mouseup was being handled so // we know it's a windows phone and we ignore the mouseout // g_mm_nWindowsTouchOn = g_mm_nIDForMouseUp; } } /*********************************************************************** * * mmCancelCloseTime - cancels the resetting of mega menu closing timer * Returns: - nothing * * Author: <NAME> * ************************************************************************/ function mmCancelCloseTime() { if (g_mm_closeTimer) { window.clearTimeout(g_mm_closeTimer); g_mm_closeTimer = null; } if (g_mm_menuParent) { g_mm_menuParent.className = 'sel'; } } /*********************************************************************** * * mmOpen - Function is called from mouseOver event and positions * the mega menu drop down in correct position as well * as ensuring it is made visible * Returns: - nothing * * Author: <NAME> * ************************************************************************/ function mmOpen(id) { // // If the mini navigation menu is shown i.e. its a compact touch device just ignore mouseover // This is because the sub-menu display is inline with the main menu and moves everything around. // This causes havoc with touch devices particularly as there is a delay to the click. // We let the More.. button open up because it's at the end, and there's no other way of seeing the // top level sections in it. // if ($("div.miniNav").is(":visible") && // if the miniNav bar is visible $("#main-link" + id).attr("href") != '#') // and the mouseover is not on the "More.." button then ignore it { g_mm_nIDRecentMouseOver = g_mm_NO_MENU_ITEM; // reset just in case return; } // // Check if Windows touch in which case a mouseout will have occurred after tap. // If there is another mouseover then we just ignore it as the mega menu is already dropped. // if (g_mm_nWindowsTouchOn == id) { return; } // // If we get a click event before the timer below fires, we know it was a touch event so we can // ignore it if it is for the current tab. If the click occurs after the timer has fired then we // let it go through. That way the first tap opens the mega menu; second tap follows the hotlink. // g_mm_nIDRecentMouseOver = id; // this indicates that a recent mouseover event occurred on this item if (g_mm_timerRecentMouseOver) // reset the timer if it's already active for another item { window.clearTimeout(g_mm_timerRecentMouseOver); } g_mm_timerRecentMouseOver = window.setTimeout(function() { g_mm_nIDRecentMouseOver = g_mm_NO_MENU_ITEM; // no recent mouseover now g_mm_timerRecentMouseOver = null; }, 500); // can be adjusted if some touch devices are very slow at sending the click through after a mouseover // cancel close timer mmCancelCloseTime(); // close old layer mmClose(); // get new layer and show it menuDiv = $ge('mega-menu'); g_mm_menuParent = $ge('main-link' + id); // // Set up mouseup handler so we can detect Windows touch device which sends mouseup & then mouseout after a tap // if (!g_mm_mapListenersAdded['mouseup' + id]) { AddEvent(g_mm_menuParent, "mouseup", mmMouseUpHandler(id)); g_mm_mapListenersAdded['mouseup' + id] = true; } g_mm_menuItem = $ge('tc' + id); //show the menu to enable dimension properties and show on page g_mm_menuItem.style.display = 'block'; //reposition //get position and size dimensions var topNavWidth = menuDiv.offsetWidth; var menuDropWidth = g_mm_menuItem.offsetWidth; var menuPosOnPage = findLeftPos(menuDiv); var itemPosOnPage = findLeftPos(g_mm_menuParent); // the width from the default menu start position to the edge of the container var MenuPlaceholderwidth = (topNavWidth - itemPosOnPage); //alert('menu placeholder width = ' + MenuPlaceholderwidth); //if the menu to display is greater than the top nav if (topNavWidth < menuDropWidth) { //get difference var widthDifference = menuDropWidth - topNavWidth; //center item g_mm_menuItem.style.left = (-1 * (itemPosOnPage + Math.floor((widthDifference / 2)) - menuPosOnPage)) + "px"; } else if (topNavWidth < ((itemPosOnPage - menuPosOnPage) + menuDropWidth)) { // off the page so align to right g_mm_menuItem.style.left = -1 * (((itemPosOnPage - menuPosOnPage) + menuDropWidth) - topNavWidth) + "px"; } else { //not wider than menu; not off the page, so set to standard g_mm_menuItem.style.left = 0 + "px"; } } /*********************************************************************** * * mmMouseUpHandler - MouseUp handler * * Returns: - nothing * ************************************************************************/ function mmMouseUpHandler(id) { var nID = id; return ( function() { g_mm_nIDForMouseUp = nID; // // If mouseout occurs before the timer below fires we detect it and set g_mm_nWindowsTouchOn // window.setTimeout(function() { g_mm_nIDForMouseUp = g_mm_NO_MENU_ITEM; }, 0); }); } /*********************************************************************** * * findPos - Finds the left position of an element in the window * Returns: - x coordinate of object in visible window * * Author: <NAME> * ************************************************************************/ function findLeftPos(obj) { var curleft = 0; if (obj.offsetParent) { do { curleft += obj.offsetLeft; } while (obj = obj.offsetParent); return curleft; } } /*********************************************************************** * * findPosX - Finds the left position of an element in the window * * Returns: - x coordinate of object in visible window * ************************************************************************/ function findPosX(obj) { var left = 0; if (obj.offsetParent) { while (1) { left += obj.offsetLeft; if (!obj.offsetParent) break; obj = obj.offsetParent; } } else if (obj.x) { left += obj.x; } return left; } /*********************************************************************** * * findPosY - Finds the left position of an element in the window * * Returns: - y coordinate of object in visible window * ************************************************************************/ function findPosY(obj) { var top = 0; if (obj.offsetParent) { while (1) { top += obj.offsetTop; if (!obj.offsetParent) break; obj = obj.offsetParent; } } else if (obj.y) { top += obj.y; } return top; } /*********************************************************************** * * getDynamicAccPrice - Call our server script to determine the total price * depending on the selection * * Input: sURL - the ajax script URL to call * sSID - the section ID list to be passed in to the ajax script or null if for a single product * oProd - the product * sShopID - the shop ID (only used in host mode) * ************************************************************************/ function getDynamicAccPrice(sURL, sSID, oProd, sShopID) { // // In case of preview use passed in data // var bPreview = (sURL.indexOf("file://") == 0); var sProdRef = oProd.sProdRef; var sVariantSettings = ""; if (bPreview) { return; } else { // // Get the element containing variants // var sName = 'v_' + sProdRef + '_'; var elemVars = document.getElementById('idVars' + sProdRef); if (elemVars) { if (oProd.arrComps) // if we have components { var arrComps = oProd.arrComps; var nLength = arrComps.length; for (var i = 0; i < nLength; i++) // for each one { var oComp = arrComps[i]; var sCompHTMLName = sName + oComp.nUI; var elemComp = document.getElementsByName(sCompHTMLName)[0]; if (elemComp.type == 'checkbox') { sVariantSettings += "&" + sCompHTMLName + "=" + (elemComp.checked ? "on" : "off"); } else { sVariantSettings += "&" + sCompHTMLName + "=" + elemComp.value; } oComp.elemHTML = elemComp; // store the UI element } } // // Store the attribute UI element // var mapElemAttr = GetAttributes(elemVars); var arrElemAttr = mapElemAttr[sProdRef]; if (arrElemAttr) { var nVarSuffix = parseInt(arrElemAttr[0].name.match(/_(\d+)$/)[1]); var nAttrElemCount = arrElemAttr.length for (var i = 0; i < nAttrElemCount; i++) { var elemAttr = arrElemAttr[i]; nVarSuffix = parseInt(elemAttr.name.match(/_(\d+)$/)[1]); if (oProd.arrComps) { var oAttr = GetAttrFromSuffix(oProd, nVarSuffix); // // Make sure the initial HTML elements are used before the javascript pixies // do any mischief // if (!oAttr.elem) { oAttr.elem = new CSelect(elemAttr); } } if (document.getElementsByName(elemAttr.name)[0].type == 'radio') { var oElement = document.getElementsByName(elemAttr.name)[0]; for (var j = 0; oElement != null;) { if (oElement.checked) { sVariantSettings += "&" + elemAttr.name + "=" + oElement.value; break; } oElement = document.getElementsByName(elemAttr.name)[++j]; } } else { sVariantSettings += "&" + elemAttr.name + "=" + elemAttr.value; } } } } // // Handle default setting for push button grids // var GridVariants = "sPushBtnGridVariants_" + sProdRef; if (typeof window[GridVariants] != 'undefined') { sVariantSettings += "&" + window[GridVariants]; } var sQuantity = "Q_" + sProdRef; sVariantSettings += "&" + sQuantity + "=" + document.getElementsByName(sQuantity)[0].value; var ajaxRequest = new ajaxObject(sURL); ajaxRequest.callback = function(responseText, responseStatus) { if (responseStatus != 200) // request returned other than OK, default too static price { var elemPriceContainer = document.getElementById('id' + oProd.sProdRef + 'DynamicPrice'); var elemStPriceContainer = document.getElementById('id' + oProd.sProdRef + 'StaticPrice'); if (oProd.bOvrStaticPrice && elemStPriceContainer && !oProd.bQuantityBreak) { elemStPriceContainer.style.visibility = "visible"; elemStPriceContainer.style.display = ""; } if (elemPriceContainer) { elemPriceContainer.style.display = 'none'; elemPriceContainer.style.visibility = 'hidden'; } return; } var elemPriceExc = document.getElementById('id' + sProdRef + 'TaxExcPrice'); var elemPriceInc = document.getElementById('id' + sProdRef + 'TaxIncPrice'); var elemTaxMsg = document.getElementById('id' + oProd.sProdRef + 'VATMsg'); // get the tax message element (e.g Including VAT at 20%) if (responseText != null) { try { var Results = responseText.parseJSON(); if (Results.ErrorMsg) // is there an error with quality validation? { if (elemTaxMsg) { elemTaxMsg.style.visibility = "hidden"; elemTaxMsg.style.display = "none"; } if (elemPriceExc) // display the error message instead of the price { elemPriceExc.innerHTML = Results.ErrorMsg; } else if (elemPriceInc) { elemPriceInc.innerHTML = Results.ErrorMsg; } return; } if (elemTaxMsg) { elemTaxMsg.style.visibility = "visible"; elemTaxMsg.style.display = ""; } var nTotalExcTax = Results.Total; var nTotalIncTax = Results.Total + Results.Tax1 + Results.Tax2; if (elemPriceExc) { elemPriceExc.innerHTML = FormatPrices(nTotalExcTax); } if (elemPriceInc) { elemPriceInc.innerHTML = FormatPrices(nTotalIncTax); } } catch (e) {} } } // // If we don't supply a section ID, assume this is for a single product // var sParams = ("ACTION=GETACCPRICE&PRODREF=" + sProdRef + "&SID=" + sSID); sParams += sVariantSettings; if (sShopID) { sParams += '&SHOP=' + sShopID; } ajaxRequest.update(sParams, "GET"); } } /*********************************************************************** * * SetupChoicesAllProducts - Update the choices and prices for all products * in the section * * Input: sURL - the ajax script URL to call * sSID - the section ID list to be passed in to the ajax script or null if for a single product * sShopID - the shop ID (only used in host mode) * ************************************************************************/ function SetupChoicesAllProducts(sURL, sSID, sShopID) { for (var sProdRef in g_mapProds) { var oProd = g_mapProds[sProdRef]; if (oProd) { // // Get the element containing variants // var sName = 'v_' + sProdRef + '_'; var elemVars = document.getElementById('idVars' + sProdRef); if (elemVars) { if (oProd.arrComps) // if we have components { var arrComps = oProd.arrComps; var nLength = arrComps.length; for (var i = 0; i < nLength; i++) // for each one { var oComp = arrComps[i]; var sCompHTMLName = sName + oComp.nUI; var elemComp = document.getElementsByName(sCompHTMLName)[0]; oComp.elemHTML = elemComp; // store the UI element } // // Store the attribute UI element // var mapElemAttr = GetAttributes(elemVars); var arrElemAttr = mapElemAttr[sProdRef]; if (arrElemAttr) { var nVarSuffix = parseInt(arrElemAttr[0].name.match(/_(\d+)$/)[1]); var nAttrElemCount = arrElemAttr.length for (var i = 0; i < nAttrElemCount; i++) { var elemAttr = arrElemAttr[i]; nVarSuffix = parseInt(elemAttr.name.match(/_(\d+)$/)[1]); var oAttr = GetAttrFromSuffix(oProd, nVarSuffix); // // Make sure the initial HTML elements are used before the javascript pixies // do any mischief // if (!oAttr.elem) { oAttr.elem = new CSelect(elemAttr); } } UpdateChoices(oProd, true); // update the choices } } if (!(oProd.bOvrStaticPrice && oProd.nPricingModel == PRICING_MODEL_COMPONENTS_SUM) || // only component prices used? (g_mapDynPrices[oProd.sProdRef] && (g_mapDynPrices[oProd.sProdRef].Total > 0))) // dynamic price calculated by default { UpdatePrice(oProd, sURL, sSID, sShopID); // update the price } } } } g_mapDynPrices = {}; // make sure it gets reloaded for individual products } /*********************************************************************** * * getAllDynamicPrices - Call our server script to determine the total price * depending on the selection * * Input: sURL - the ajax script URL to call * sSID - the section ID list to be passed in to the ajax script or null if for a single product * sShopID - the shop ID (only used in host mode) * ************************************************************************/ function getAllDynamicPrices(sURL, sSID, sShopID) { // // In case of preview use passed in data // var bPreview = (sURL.indexOf("file://") == 0); if (bPreview) { SetupVariants(true); return ""; } else { if (g_bStockUpdateInProgress) { // // do not update dynamic prices when products stock update is in progress // note: currently selected options may be changed during stock update process // g_bDynamicPriceUpdatePending = true; return ""; } // // Get the element containing variants // var ajaxRequest = new ajaxObject(sURL); ajaxRequest.callback = function(responseText, responseStatus) { if (responseText != null) { if (200 == responseStatus) { try { g_mapDynPrices = responseText.parseJSON(); } catch (e) {} } SetupChoicesAllProducts(sURL, sSID, sShopID); } } // // Get the prices for the whole section // var sParams = ("ACTION=GETALLPRICES&SID=" + sSID); var sVariantSettings = ""; // // Add default variant settings // sVariantSettings = SetupVariants(true); sParams += sVariantSettings; if (sShopID) { sParams += '&SHOP=' + sShopID; } ajaxRequest.update(sParams, "GET"); g_bDynamicPriceUpdatePending = false; } } /*********************************************************************** * * SetupVariantsForProduct - sets up variants in order to use with dynamic * pricing/selection validation for a product * * Input: sProdRef - product reference * bGetParams - if variant string should be constructed * * Returns: variant string * ************************************************************************/ function SetupVariantsForProduct(sProdRef, bGetParams) { var sVariantSettings = ""; var oProd = g_mapProds[sProdRef]; if (oProd) { var sName = 'v_' + sProdRef + '_'; var elemVars = document.getElementById('idVars' + sProdRef); if (elemVars) { if (oProd.arrComps) // if we have components { var arrComps = oProd.arrComps; var nLength = arrComps.length; for (var i = 0; i < nLength; i++) // for each one { var oComp = arrComps[i]; var sCompHTMLName = sName + oComp.nUI; var elemComp = document.getElementsByName(sCompHTMLName)[0]; if (bGetParams) { if (elemComp.type == 'checkbox') { sVariantSettings += "&" + sCompHTMLName + "=" + (elemComp.checked ? "on" : "off"); } else { sVariantSettings += "&" + sCompHTMLName + "=" + elemComp.value; } } oComp.elemHTML = elemComp; // store the UI element } // // Store the attribute UI element // var mapElemAttr = GetAttributes(elemVars); var arrElemAttr = mapElemAttr[sProdRef]; if (arrElemAttr) { var nVarSuffix = parseInt(arrElemAttr[0].name.match(/_(\d+)$/)[1]); var nAttrElemCount = arrElemAttr.length for (var i = 0; i < nAttrElemCount; i++) { var elemAttr = arrElemAttr[i]; nVarSuffix = parseInt(elemAttr.name.match(/_(\d+)$/)[1]); var oAttr = GetAttrFromSuffix(oProd, nVarSuffix); // // Make sure the initial HTML elements are used before the javascript pixies // do any mischief // if (!oAttr.elem) { oAttr.elem = new CSelect(elemAttr); } if (bGetParams) { if (document.getElementsByName(elemAttr.name)[0].type == 'radio') { var oElement = document.getElementsByName(elemAttr.name)[0]; for (var j = 0; oElement != null;) { if (oElement.checked) { sVariantSettings += "&" + elemAttr.name + "=" + oElement.value; break; } oElement = document.getElementsByName(elemAttr.name)[++j]; } } else { sVariantSettings += "&" + elemAttr.name + "=" + elemAttr.value; } } } } } } // // Handle default setting for push button grids if used // if (bGetParams) { var GridVariants = "sPushBtnGridVariants_" + sProdRef; if (typeof window[GridVariants] != 'undefined') { sVariantSettings += "&" + window[GridVariants]; } } } return (sVariantSettings); } /*********************************************************************** * * SetupVariants - sets up variants in order to use with dynamic pricing/ * selection validation * * Input: bGetParams - if variant string should be constructed * * Returns: variant string * ************************************************************************/ function SetupVariants(bGetParams) { var sVariants = ""; for (var sProdRef in g_mapProds) { sVariants += SetupVariantsForProduct(sProdRef, bGetParams); } return (sVariants); } /*********************************************************************** * * GetInputElement - Get a named INPUT element from a form * * Input: elemForm - form element * sID - name of the input element * * Returns: object/undefined - named element or undefined * ************************************************************************/ function GetInputElement(elemForm, sID) { var collInput = elemForm.getElementsByTagName('INPUT'); for (var nInputIndex = 0; nInputIndex < collInput.length; nInputIndex++) { var elemInput = collInput[nInputIndex]; if (elemInput.name == sID) { return elemInput; } } return undefined; } /************************************************************************ * * GetOriginalRef - Get the product reference * * Input: sProdRef - product reference, can be a duplicate one * Returns: the product reference * ************************************************************************/ function GetOriginalRef(sProdRef) { var arrRef = sProdRef.split("!"); return arrRef[arrRef.length - 1]; } /************************************************************************ * * GetProductFromMap - Get the product from the map, even if only * duplicates are present * * Input: sProdRef - product reference, can be a duplicate one * Returns: the product * ************************************************************************/ function GetProductFromMap(sProdRef) { // // If already in the map by the reference passed on, just return it // if (g_mapProds[sProdRef]) { return g_mapProds[sProdRef]; } for (var sMapRef in g_mapProds) { if (GetOriginalRef(sMapRef) == sProdRef) { return g_mapProds[sMapRef]; } } } /************************************************************************ * * SetupDPDPickupOptions - DPD pickup options ajax call handler * * Input: oResp - response JSON object * ************************************************************************/ function SetupDPDPickupOptions(oResp) { if (oResp.Error != null) { alert("There was an error in initializing the Collection Point Pickup service. Please select another shipping option"); $("#idDPDShippingType3").attr('disabled', true); HideLoadingDialog(); $("#idDPDShippingType1").click(); return; } $("#map").css("left", "0"); $("#map").css("position", "relative"); $("#map").css("width", "100%"); $('#map').show(); // just show the previously prepared controls g_mapPickupLocationsJSON = oResp; // don't have to call the service next time var mapDPDPickupLocations = oResp.data.results; var markers = []; markers.forEach(function(marker) { marker.setMap(null); // empty the map }); markers = []; var bounds = new google.maps.LatLngBounds(); mapDPDPickupLocations.forEach(function(location) { var lat = location.pickupLocation.addressPoint.latitude; var lng = location.pickupLocation.addressPoint.longitude; var myLatLng = new google.maps.LatLng(lat, lng); var LocationDetails = { "organisation": location.pickupLocation.address.organisation, "postcode": location.pickupLocation.address.postcode, "locality": location.pickupLocation.address.locality, "property": location.pickupLocation.address.property, "street": location.pickupLocation.address.street, "town": location.pickupLocation.address.town, "county": location.pickupLocation.address.county, "distance": Math.round(location.distance * 100) / 100, "disabledaccess": location.pickupLocation.disabledAccess, "parking": location.pickupLocation.parkingAvailable, "openlate": location.pickupLocation.openLate, "shortname": location.pickupLocation.shortName, "openhours": location.pickupLocation.pickupLocationAvailability.pickupLocationOpenWindow, "directions": location.pickupLocation.pickupLocationDirections }; var marker = new google.maps.Marker({ map: map, title: location.pickupLocation.address.organisation, position: myLatLng, pickupLocationCode: location.pickupLocation.pickupLocationCode, pickupLocationDetails: LocationDetails }); markers.push(marker); if (!bounds.contains(myLatLng)) { bounds.extend(myLatLng); } marker.addListener('click', function() { infowindow.open(map, marker); infowindow.setContent(SetupInfoWindow(marker)); }); var sDetails = (location.pickupLocation.address.organisation != "" ? location.pickupLocation.address.organisation + "," : "") + (location.pickupLocation.address.property != "" ? location.pickupLocation.address.property + "," : "") + (location.pickupLocation.address.street != "" ? location.pickupLocation.address.street + "," : "") + (location.pickupLocation.address.locality != "" ? location.pickupLocation.address.locality + "," : "") + (location.pickupLocation.address.postcode != "" ? location.pickupLocation.address.postcode + "," : "") + (location.pickupLocation.address.county != "" ? location.pickupLocation.address.county + "," : "") + location.pickupLocation.address.town; g_mapCodeToDetail[location.pickupLocation.pickupLocationCode] = sDetails; g_mapCodeToMarker[location.pickupLocation.pickupLocationCode] = marker; var sOption = "<option value='" + location.pickupLocation.pickupLocationCode + "'" + ($("#idDPDPickupDefault").val() === location.pickupLocation.pickupLocationCode ? " selected" : "") + ">" + sDetails + "</option>"; $("#idPickupSelect").append(sOption); }); google.maps.event.trigger(map, "resize"); // make sure that the map is displaying properly map.fitBounds(bounds); $('#idPickupSelect').show(); SelChangePickupLocations(); HideLoadingDialog(); } /************************************************************************ * * SelectPickupLocation - Make a pickup location selection * * Input: e - event object * marker - marker to get the details for * ************************************************************************/ function SelectPickupLocation(e) { e.preventDefault(); var oMarker = g_SelectedMarker; if (oMarker) { $("#idPickupSelect").val(oMarker.pickupLocationCode); $("input#idDPDPickupLocation").val(g_mapCodeToDetail[oMarker.pickupLocationCode]); $("#idMapBtn").text('Selected'); $("#idMapBtn").prop('disabled', true); } } /************************************************************************ * * SelChangePickupLocations - * ************************************************************************/ function SelChangePickupLocations() { var sCode = $("#idPickupSelect").val() var oMarker = g_mapCodeToMarker[sCode]; if (oMarker) { $("input#idDPDPickupLocation").val(g_mapCodeToDetail[oMarker.pickupLocationCode]); google.maps.event.trigger(oMarker, 'click'); $("#idMapBtn").text('Selected'); $("#idMapBtn").prop('disabled', true); } } /************************************************************************ * * ShippingTypeChanged * * Input: RadioButton value - of the button clicked * ************************************************************************/ function ShippingTypeChanged(nType) { switch (nType) { case "1": // Standard Delivery $('#map').hide(); $('#idPickupSelect').hide(); $('#idDeliveryDateFields').hide(); $('#lstClass').prop("disabled", false); $("#lstClass > option").each(function() { if ($(this).attr("data-ship2shop")) { $(this).prop("disabled", true); } else { $(this).prop("disabled", false); } }); $("#idSelectPickupLabel").hide(); $('#lstClass').children('option:enabled').eq(0).prop('selected', true); break; case "2": // Specified Day delivery $('#map').hide(); $('#idPickupSelect').hide(); $('#lstClass').prop("disabled", false); SetupDeliveryDateList(); FilterClassList(); $('#idDeliveryDateFields').show(); $("#idSelectPickupLabel").hide(); break; case "3": // Collection Point Pickup $('#idDeliveryDateFields').hide(); if (typeof g_mapPickupLocationsJSON.data === "undefined" && typeof g_mapPickupLocationsJSON.error === "undefined") { ShowLoadingDialog(); g_mapAJAXActions['GetDPDPickupLocations'] = SetupDPDPickupOptions; // add the handler function AddAJAXCall('GetDPDPickupLocations'); // add the call to the list AJAXCall(); } else { $('#map').show(); // just show the previously prepared controls $('#idPickupSelect').show(); SelChangePickupLocations(); } $("#lstClass > option").each(function() { if ($(this).attr("data-ship2shop")) { $(this).prop("disabled", false); $('#lstClass').val(this.value); $('#lstClass').prop("disabled", true); return false; } }); $("#idSelectPickupLabel").show(); break; } } /************************************************************************ * * SetupDeliveryDateList - set up available delivery dates dropdown * ************************************************************************/ function SetupDeliveryDateList() { var d = new Date(); var sOption; var sDay, sMonth, nYear, nDayOfMonth, sDateVal; var bWeekend = (d.getDay() == 6) || (d.getDay() == 0); // weekend date? first available date is Tuesday var bFriday = (d.getDay() == 5); var bBeforeNoon = (d.getHours() < 12); // before noon ? next day delivery available $('#idDeliveryDate').empty(); // // Decide the first available date // if (bWeekend || (bFriday && !bBeforeNoon)) { var nAdd = 1; switch (d.getDay()) { case 0: // Sunday nAdd = 2; break; case 6: // Saturday nAdd = 3; break; case 5: // Friday nAdd = 4; break; } d.setDate(d.getDate() + nAdd); // increment the date as appropriate } else if (bBeforeNoon) { d.setDate(d.getDate() + 1) // first day is tomorrow } else { d.setDate(d.getDate() + 2) // first day is the day after tomorrow } for (var i = 0; i < g_nMaxDays; i++) { sDay = aDaysOfWeek[d.getDay()]; sMonth = aMonths[d.getMonth()]; nYear = d.getFullYear(); nDayOfMonth = d.getDate(); sDateVal = nDayOfMonth + " " + sMonth + " " + nYear; sOption = "<option value='" + sDateVal + "'" + ($("#idDPDDateDefault").val() === sDateVal ? " selected" : "") + ">" + sDay + " " + nDayOfMonth + " " + sMonth + ", " + nYear + "</option>"; $('#idDeliveryDate').append(sOption); d.setDate(d.getDate() + 1); // increment the date } } /************************************************************************ * * FilterClassList - filter options based on specified delivery date * ************************************************************************/ function FilterClassList() { var d = new Date($('#idDeliveryDate').val()); console.log(d.getDay()); var dtoday = new Date(); var bBeforeNoon = (dtoday.getHours() < 12); // before noon ? next day delivery available var bWeekDay = (d.getDay() < 6) && (d.getDay() > 0); $("#lstClass > option").each(function() { var bCondition = false; switch ($(this).attr("data-filter")) { case "w": $(this).prop("disabled", bWeekDay ? false : true); // weekdays break; case "st": $(this).prop("disabled", (d.getDay() == 6) ? false : true); break; case "sn": $(this).prop("disabled", (d.getDay() == 0) ? false : true); break; default: $(this).prop("disabled", true); } return true; }); $('#lstClass').children('option:enabled').eq(0).prop('selected', true); } /************************************************************************ * * SetupInfoWindow - Google Maps info window * * Input: oMarker - merker object * * Returns: the html created for the window * ************************************************************************/ function SetupInfoWindow(oMarker) { var oLocationDetails = oMarker.pickupLocationDetails; var aOpenHours = Array(7); var sHours = ""; for (i = 0; i < oLocationDetails.openhours.length; i++) { sHours = ""; if (aOpenHours[oLocationDetails.openhours[i].pickupLocationOpenWindowDay] != undefined) { var sPrevHours = aOpenHours[oLocationDetails.openhours[i].pickupLocationOpenWindowDay]; var sEndTime = sPrevHours.substr(6); if (oLocationDetails.openhours[i].pickupLocationOpenWindowStartTime === sEndTime) { sHours = sPrevHours.substr(0, 5) + "-" + oLocationDetails.openhours[i].pickupLocationOpenWindowEndTime; } else { sHours = aOpenHours[oLocationDetails.openhours[i].pickupLocationOpenWindowDay] + "|" + oLocationDetails.openhours[i].pickupLocationOpenWindowStartTime + "-" + oLocationDetails.openhours[i].pickupLocationOpenWindowEndTime; } } else { sHours = oLocationDetails.openhours[i].pickupLocationOpenWindowStartTime + "-" + oLocationDetails.openhours[i].pickupLocationOpenWindowEndTime; } aOpenHours[oLocationDetails.openhours[i].pickupLocationOpenWindowDay] = sHours; } var sContent = '<div id="locationInfo">' + '<table style="line-height:1.3"><tr><td>' + '<strong>' + oLocationDetails.shortname + '</strong><br>' + (oLocationDetails.property != "" ? oLocationDetails.property + '<br>' : "") + (oLocationDetails.street != "" ? oLocationDetails.street + '<br>' : "") + (oLocationDetails.locality != "" ? oLocationDetails.locality + '<br>' : "") + (oLocationDetails.town != "" ? oLocationDetails.town + '<br>' : "") + (oLocationDetails.county != "" ? oLocationDetails.county + '<br>' : "") + oLocationDetails.postcode + '<br>'; sContent += 'Distance:' + oLocationDetails.distance + ' miles<br>' + 'Car Parking:' + (oLocationDetails.parking ? 'Yes' : 'No') + '<br>' + 'Disabled Access:' + (oLocationDetails.disabledaccess ? 'Yes' : 'No') + '<br>'; if (oLocationDetails.directions != "") { sContent += 'Additional directions:' + (oLocationDetails.directions) + '<br>'; } sContent += '</td><td>'; sContent += '<strong>Normal opening hours:&nbsp;</strong><br>' + 'Mon:&nbsp;' + (aOpenHours[1] != undefined ? aOpenHours[1] : "Closed") + '<br>' + 'Tue:&nbsp;' + (aOpenHours[2] != undefined ? aOpenHours[2] : "Closed") + '<br>' + 'Wed:&nbsp;' + (aOpenHours[3] != undefined ? aOpenHours[3] : "Closed") + '<br>' + 'Thu:&nbsp;' + (aOpenHours[4] != undefined ? aOpenHours[4] : "Closed") + '<br>' + 'Fri:&nbsp;' + (aOpenHours[5] != undefined ? aOpenHours[5] : "Closed") + '<br>'; if (aOpenHours[6] != undefined) { sContent += 'Sat:&nbsp;' + aOpenHours[6] + '<br>'; } if (aOpenHours[7] != undefined) { sContent += 'Sun:&nbsp;' + aOpenHours[7] + '<br>'; } sContent += '</td></tr></table>'; sContent += "<strong>Latitude:</strong>" + oMarker.position.lat().toFixed(5) + " | <strong>Longitude:</strong>" + oMarker.position.lng().toFixed(5) + "<br>"; sContent += '<div align="center"><button class="btn btn-primary" id="idMapBtn" onclick="SelectPickupLocation(event)">Select</button></div>' + '</div>'; g_SelectedMarker = oMarker; return sContent; } /************************************************************************ * * SetDefaultShippingType * ************************************************************************/ function SetDefaultShippingType() { var nValue = $('input[name=DPDShippingType]:checked').val(); ShippingTypeChanged(nValue); }<file_sep>/README.md # <NAME>
3b5ff6401c432b63b267414c3460cfa57caeb6b1
[ "JavaScript", "HTML", "Markdown" ]
9
JavaScript
paulstandley/find-doc-wr
097a7eecb91c197af8e692495774e829a6389248
168cab6dba00f8a349b1769f4b4f692cae90f9b3
refs/heads/master
<file_sep># SimpleMavenProject 1. Simple Maven 2. GRPC with Maven plugin 3. Standalone REST Jersey implemetation with Basic Auth <file_sep>package com.rajesh.java.maven.rest; import com.sun.net.httpserver.HttpServer; import org.glassfish.jersey.jdkhttp.JdkHttpServerFactory; import org.glassfish.jersey.server.ResourceConfig; import javax.ws.rs.core.UriBuilder; import java.net.URI; public class TestMain { //Test this service by URL: http://localhost:8080/rest/hello/rajesh (Authentication header is required, test this by TestClient class) public static void main(String[] args) { URI baseUri = UriBuilder.fromUri("http://localhost/").port(8080).uri("rest").build(); ResourceConfig config = new CustomApplication(); HttpServer server = JdkHttpServerFactory.createHttpServer(baseUri, config); } } <file_sep>package com.rajesh.java.maven.rest; import javax.annotation.security.RolesAllowed; import javax.jws.WebService; import javax.ws.rs.GET; import javax.ws.rs.Path; import javax.ws.rs.PathParam; import javax.ws.rs.Produces; @WebService @Path("/hello") public class HelloWorldService { @RolesAllowed("ADMIN") @GET @Path("/{param}") @Produces("text/plain") public String getMsg(@PathParam("param") String msg) { String output = "Jersey say : " + msg; return output; //return Response.status(200).entity(output).build(); } } <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.rajesh.java.maven</groupId> <artifactId>SimpleMavenJava</artifactId> <version>1.0-SNAPSHOT</version> <packaging>jar</packaging> <name>SimpleMavenJava</name> <url>http://maven.apache.org</url> <properties> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> </properties> <dependencies> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>3.8.1</version> <scope>test</scope> </dependency> <dependency> <groupId>com.google.guava</groupId> <artifactId>guava</artifactId> <version>21.0</version> </dependency> <dependency> <groupId>com.google.protobuf</groupId> <artifactId>protobuf-java</artifactId> <version>3.0.0</version> </dependency> <dependency> <groupId>io.grpc</groupId> <artifactId>grpc-all</artifactId> <version>1.2.0</version> </dependency> <dependency> <groupId>javax.ws.rs</groupId> <artifactId>javax.ws.rs-api</artifactId> <version>2.0</version> </dependency> <dependency> <groupId>org.glassfish.jersey.containers</groupId> <artifactId>jersey-container-jdk-http</artifactId> <version>2.25.1</version> </dependency> <dependency> <groupId>org.glassfish.jersey.core</groupId> <artifactId>jersey-server</artifactId> <version>2.25.1</version> </dependency> <!-- <dependency> <groupId>org.glassfish.jersey.core</groupId> <artifactId>jersey-client</artifactId> <version>2.25.1</version> </dependency> <dependency> <groupId>org.glassfish.jersey.core</groupId> <artifactId>jersey-common</artifactId> <version>2.25.1</version> </dependency>--> </dependencies> <build> <plugins> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-compiler-plugin</artifactId> <configuration> <source>1.8</source> <target>1.8</target> </configuration> </plugin> <plugin> <groupId>org.xolstice.maven.plugins</groupId> <artifactId>protobuf-maven-plugin</artifactId> <version>0.5.0</version> <extensions>true</extensions> <dependencies> <dependency> <groupId>com.google.protobuf</groupId> <artifactId>protobuf-java</artifactId> <version>3.0.0</version> </dependency> </dependencies> <configuration> <protocExecutable>C:\Setup\protoc-3.0.0-win32\bin\protoc</protocExecutable> <checkStaleness>true</checkStaleness> </configuration> <executions> <execution> <goals> <goal>compile</goal> </goals> </execution> </executions> </plugin> <!-- <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-toolchains-plugin</artifactId> <version>1.0</version> <executions> <execution> <phase>validate</phase> <goals> <goal>toolchain</goal> </goals> </execution> </executions> <configuration> <toolchains> <protobuf> <version>[3.0.0]</version> </protobuf> </toolchains> </configuration> </plugin>--> <!-- <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-dependency-plugin</artifactId> <version>3.0.0</version> <executions> <execution> <id>copy</id> <phase>validate</phase> <goals> <goal>copy</goal> </goals> </execution> </executions> <configuration> <artifactItems> <artifactItem> <groupId>com.google.protobuf</groupId> <artifactId>protobuf-java</artifactId> <version>3.0.0</version> <type>jar</type> <overWrite>false</overWrite> <outputDirectory>${project.build.directory}/dependencies/</outputDirectory> </artifactItem> </artifactItems> <outputDirectory>${project.build.directory}/wars</outputDirectory> <overWriteReleases>false</overWriteReleases> <overWriteSnapshots>true</overWriteSnapshots> </configuration> </plugin>--> </plugins> </build> </project> <file_sep>package com.rajesh.java.maven.rest; import org.glassfish.jersey.internal.util.Base64; import java.io.BufferedReader; import java.io.InputStream; import java.io.InputStreamReader; import java.net.HttpURLConnection; import java.net.URL; /** * Created by rajesh on 25/03/2017. */ public class TestClient { public static void main(String[] args) { String uri = "http://localhost:8080/rest/hello/rajesh"; URL url = null; byte[] response = new byte[1000]; String strResponse = ""; try { url = new URL(uri); HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("GET"); connection.setRequestProperty("Accept", "text/plain"); String userCredentials = "<PASSWORD>:<PASSWORD>"; String basicAuth = "Basic " + new String(new Base64().encode(userCredentials.getBytes())); connection.setRequestProperty("Authorization", basicAuth); System.out.println("connection.getContent() = " + connection.getContent()); System.out.println("connection.getResponseMessage() = " + connection.getResponseMessage()); strResponse = readString((InputStream) connection.getContent()); System.out.println("strResponse = " + strResponse); connection.disconnect(); } catch (Exception e) { e.printStackTrace(); } } public static String readString(InputStream is) { BufferedReader br = new BufferedReader(new InputStreamReader(is)); String content = br.lines().reduce("", String::concat); return content; } }
fdce1cbffd57bf385a3b4332301f41e2aed0de0a
[ "Markdown", "Java", "Maven POM" ]
5
Markdown
rajeshdave/SimpleMavenProject
10f354c4fc24ecabcdc83ff16baceea1580fdf57
d480a5dd635f6b6c4464f22ab8198c828ea873d4
refs/heads/master
<repo_name>mceSystems/meaco<file_sep>/README.md # meaco A Coroutine library supporting Promise, JarvisEmitter and Callbacks <file_sep>/test/test.js const meaco = require("../"); const JarvisEmitter = require("jarvis-emitter"); const { expect } = require("chai"); describe("meaco", () => { it("Testing JarvisEmitter, should sum 2 and 3 and resolve with 5", (done) => { const deferNumber = (d) => { const emitter = new JarvisEmitter(); setTimeout(() => { emitter.callDone(d); }, 200); return emitter; } meaco(function* () { const a = yield deferNumber(2); const b = yield deferNumber(3); return a + b; }) .done((sum) => { try { expect(sum).to.equal(5); } catch(e) { return done(e); } done(); }); }); it("Testing mixed JarvisEmitter and Promise, should sum 2 and 3 and resolve with 5", (done) => { const deferNumber = (d) => { const emitter = new JarvisEmitter(); setTimeout(() => { emitter.callDone(d); }, 200); return emitter; } const deferNumberWithPromise = (d) => { return new Promise((resolve, reject) => { setTimeout(() => { resolve(d); }, 200); }); } meaco(function* () { const a = yield deferNumber(2); const b = yield deferNumberWithPromise(3); return a + b; }) .done((sum) => { try { expect(sum).to.equal(5); } catch(e) { return done(e); } done(); }); }); it("Testing JarvisEmitter, should reject with error", (done) => { const doError = () => { const emitter = new JarvisEmitter(); setTimeout(() => { emitter.callError(); }, 200); return emitter; } meaco(function* () { yield doError(); }) .error(() => { done(); }) .done((sum) => { done(new Error("Reached done though error should have been called")); }); }); it("Testing Promise, should reject with error", (done) => { const doRejection = () => { return new Promise((resolve, reject) => { setTimeout(reject, 200); }); } meaco(function* () { yield doRejection(); }) .error(() => { done(); }) .done((sum) => { done(new Error("Reached done though promise should have rejected")); }); }); it("Testing exception catching, should call catch interface", (done) => { meaco(function* () { throw new Error(); }) .catch(() => { done(); }) .done((sum) => { done(new Error("Reached done though an exception should have been caught")); }); }); it("Testing arguments passing, should call done interface with sum of passed numbers", (done) => { const numbers = [1,2,3,4,5]; const expectedSum = numbers.reduce((a,b) => {return a + b}, 0); meaco(function* (...numbers) { return numbers.reduce((a,b) => {return a + b}, 0); }, ...numbers) .catch((err) => { done(err); }) .error((err) => { done(err); }) .done((sum) => { if(expectedSum === sum){ return done(); } done(new Error(`Expected sumc ${expectedSum} but got sum=${sum}`)); }); }); });<file_sep>/index.js const JarvisEmitter = require("jarvis-emitter"); function meaco(genFunction, ...args) { const promiseRet = new JarvisEmitter(); let rejected = false; const caller = genFunction(...args); function nextCall(lastWasError, ...args) { if (lastWasError) { promiseRet.callError(...args); return; } let nextYield; try { nextYield = caller.next(...args); } catch (e) { promiseRet.callCatch(e); return; } // was it rejected? if (rejected) { return; } const done = nextYield.done; let promise = nextYield.value; let fn = "then"; let catchFn = ""; const errorFn = "error"; if (!promise || done) { promiseRet.callDone(promise); return; } if (typeof promise === "object" && promise.promise && promise.fn) { ({ promise, fn } = promise); } else if (promise.constructor.name === "JarvisEmitter" || (promise instanceof JarvisEmitter)) { // this will not work in case promise is and instance of JarvisEmitter and code is minified fn = "done"; catchFn = "catch"; } if (promise[fn]) { promise[fn](nextCall.bind(this, false), nextCall.bind(this, true)); if (promise[errorFn]) { promise[errorFn](nextCall.bind(this, true)); } if (catchFn && promise[catchFn]) { promise[catchFn](promiseRet.callCatch.bind(this)); } return; } promiseRet.callDone(promise); } nextCall(false); return promiseRet; } module.exports = meaco;
28ca3b54a19b9f06ea2c13c54789b79a45610e1c
[ "Markdown", "JavaScript" ]
3
Markdown
mceSystems/meaco
a8eca890cf360f27e1bf267a0b7096ecfa32d540
da71010ed400ca0b27b4f6b5942feb13643b00ee
refs/heads/master
<file_sep>const router = require('express').Router(); const knex = require('knex'); // this config object teaches knex how to find the database and what driver to use const knexConfig = { client: 'sqlite3', //the yarn module we installed to use as database useNullAsDefault: true, // needed when working with SQLite3 connection: { //relative to the file folder filename: './data/rolex.db3' } } const db = knex(knexConfig); //now database object has access to all tools we want to include from router.get('/', (req, res) => { // get the roles from the database db('roles') .then(roles => { res.status(200).json(roles) }) .catch(error => { res.status(500).json(error) }) }); // router.get('/', (req, res) => { // // get the roles from the database // res.send('Write code to retrieve all roles'); // }); router.get('/:id', (req, res) => { // retrieve a role by id // res.send('Write code to retrieve a role by id'); db('roles') .where({id: req.params.id}) .then(role => { if(role) { res.status(200).json(role); }else { res.status(404).json({message: 'Role id not found'}) } }) .catch(error => { res.status(500).json(error); }) }); router.post('/', (req, res) => { // add a role to the database // res.send('Write code to add a role'); db('roles') .insert(req.body) .then(role => { const [id] = role; db('roles') .where({id}) .first() .then(role => { res.status(200).json(role) }) }) .catch(error => { res.status(500).json(error) }) }); router.put('/:id', (req, res) => { // update roles // res.send('Write code to modify a role'); db('roles') .where({id: req.params.id}) .update(req.body) .then(count => { if(count > 0){ //this code is for error checking and gives yyou back the changes so you can see them db('roles') .where({id: req.params.id}) .first() .then(role => { res.status(200).json(role) }) }else{ res.status(404).json({message: 'role id not found'}) } }) .catch(error => { res.status(500).json(error) }) }); router.delete('/:id', (req, res) => { // remove roles (inactivate the role) // res.send('Write code to remove a role'); db('roles') .where({id: req.params.id}) .del() // this returns a count of the records deleted if successful .then(count => { if(count > 0) { res.status(204).end(); }else{ res.status(404).json({message: 'role id not found'}) } }) .catch(error => { res.status(500).json(error) }) }); module.exports = router;
81220524e35e354f54f2c18739688a52deebeb88
[ "JavaScript" ]
1
JavaScript
sarahrileydev/webdb-ii-guided
fd75737199e8d5be3742436fbe3e169278e39c4f
7d00eae9dccea8474f5e3635dbc7ba5c4978b2ea
refs/heads/master
<file_sep>server.port=9090 arduinoPortName = COM3 arduinoBaudRate = 9600<file_sep>package com.ALuniv25.MotionLighting; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; @SpringBootApplication public class MotionLightingApplication { public static void main(String[] args) { SpringApplication.run(MotionLightingApplication.class, args); } } <file_sep> int led = 13; //pin for the LED int motion = 2; // pin for motion sensor int motion_value = 0; // motion sensor values int led_value = 0; int pirState = LOW; byte prestate; byte state = 1; void setup() { Serial.begin(9600); pinMode(LED_BUILTIN, OUTPUT); pinMode(motion, INPUT); pinMode(led, OUTPUT); } void loop() { int light_value = analogRead(A0); motion_value = digitalRead(motion); led_value = digitalRead(led); Serial.print(motion_value); Serial.print("-"); Serial.print(light_value); Serial.print("-"); Serial.print(led_value); Serial.println(); if(light_value < 500){ digitalWrite(led, LOW); digitalWrite(led, LOW); } if(light_value > 500){ if(motion_value == 1){ digitalWrite(led, HIGH); digitalWrite(led, HIGH); } if(motion_value == 0) { digitalWrite(led, LOW); } } }
c9ba3e0cffab9338077559cadcb19ba66026ec31
[ "Java", "C++", "INI" ]
3
INI
houssamboudiar/MotionLighting
d4c45a7c6d0fa3fe4e7e0449ff6e428364940569
53dc8794e863a31ed47f0e572c3d9cb2436e6f15
refs/heads/master
<file_sep>""" alfa and bata parameter see Bishop, <NAME>. "Pattern recognition." Machine Learning 128 (2006) Chapter three """ import matplotlib.pyplot as plt import numpy as np import BayesianRegGaussPrior as BRGP import toyData w=np.array([1,2,-10,5]); sigma=0.5 N=100; #training data Out=toyData.toyData(w,sigma,N); PHI=Out[2]; targets=Out[3]; y=Out[1] x=Out[0]; #train model Parameters=[1, 2]; Model =BRGP.BayesianRegGaussPrior(); Model.fit(PHI,targets,Parameters); #test data Out=toyData.toyData(w,sigma,N); PHI=Out[2]; #targets=Out[3]; y=Out[1] x=Out[0]; #predicte model y_pred=Model.predicte(PHI); sigma=np.sqrt(Model.var(PHI)); plt.figure() axes = plt.gca() plt.plot(x,y_pred) plt.plot(x,targets,'ro') plt.plot(x,y,'g') plt.fill_between(x,y_pred - 2 * sigma,y_pred + 2 * sigma, alpha=.10) axes.set_ylim([-3,3]) plt.legend(('Predicted function', 'targets',' function','2 xstd')) Ti='Testing Data Predicted function with N='+str(N); plt.title(Ti) <file_sep> import numpy as np from sklearn import preprocessing def toyData(w,sigma,N): """ This function creates 1d polynomial toy data for linear regression y= w[0]+w[1]x+..w[d]x^d Input w: numpy array of paramters (w)0 is the bias sigma:Standard deviation of noise N:Number of samples Output Out[0]:array representing value of axis value of axis Out[1]: Deterministic function Out[3]:Transformed design matrix Out[4]: Deterministic function with Additive noise """ #Degree of polynomial degree=w.size; #generate x values x=np.linspace(0, 1,N); poly=preprocessing.PolynomialFeatures(degree-1,include_bias=True) PHI=poly.fit_transform(x.reshape(N,1)) y=np.dot(PHI,w); target=y+np.random.normal(0, sigma, N); Out=[x,y,PHI, target] return Out <file_sep> import matplotlib.pyplot as plt import numpy as np import BayesianRegGaussPrior as BRGP import toyData from sklearn import linear_model,preprocessing """ example one This example shows how the confidence of the prediction is dependent on the location of your training samples @author: Joseph """ #Generate polynomial toy training data w=np.array([-1,-1,-10,12]); sigma=0.1 N=100; Out=toyData.toyData(w,sigma,N); PHI=Out[2]; targets=Out[3]; y=Out[1] x=Out[0]; #train model Parameters=[0]; Model =BRGP.BayesianRegGaussPrior(); Model.fit(PHI[x>0.5,:],targets[x>0.5],Parameters); #Generate test data Out=toyData.toyData(w,sigma,N); PHI=Out[2]; y=Out[1] # generate a prediction y_pred=Model.predicte(PHI); sigma=np.sqrt(Model.var(PHI)); #plot data plt.figure() axes = plt.gca() plt.plot(x,y_pred) plt.plot(x[x>0.5],targets[x>0.5],'ro') plt.plot(x,y,'g') plt.fill_between(x,y_pred - 2 * sigma,y_pred + 2 * sigma, alpha=.10) axes.set_ylim([-3,3]) plt.legend(('Predicted function', 'Training data',' function','2 xstd')) Ti='confidence of the prediction and location of training samples ' plt.title(Ti) <file_sep># Bayesian-regression-with-Infinitely-Broad-Prior-Gaussian-Parameter-Distribution- Class implements the Bayesian regression with Gaussian prior Parameter distribution this code only considers the Infinitely Broad Prior and the Equivalent kernel. Class BayesianRegGaussPrior: Bayesian regression with Gaussian prior Parameter distribution this code only considers the Infinitely Broad Prior and the Equivalent kernel. If the Parameter “kind “ is left empty the default feature vectors is used, else the parameter kind corresponds to the type of kernel. Methods and Parameters fit: trains the model Parameters PHI: feature vectors rows correspond to observations, columns correspond to variables Targets: targets Parameters: parameters of model If kind is a “basis” i.e a basis function model then then there are two options 1a)If there is one input the parameter corresponds to the “quadratic regularization term” used in ridge regression and Bata is calculated using the MAP estimate 1b) If there are two parameters the model alfa and bata see [1] If a kernel is used the parameters correspond to kernel parameters predicte(self,PHI): predicts the output given feature vectors PHI: feature vectors rows correspond to observations, columns correspond to variables var(self,PHI): predicts variance of estimate References: [1] Bishop, <NAME>. "Pattern recognition." Machine Learning 128 (2006) Chapter three """<file_sep>""" Class BayesianRegGaussPrior: Bayesian regression with Gaussian prior Parameter distribution this code only considers the Infinitely Broad Prior and the Equivalent kernel. If the Parameter “kind “ is left empty the default feature vectors is used, else the parameter kind corresponds to the type of kernel. Methods and Parameters fit: trains the model Parameters PHI: feature vectors rows correspond to observations, columns correspond to variables Targets: targets Parameters: parameters of model If kind is a “basis” i.e a basis function model then then there are two options 1a)If there is one input the parameter corresponds to the “quadratic regularization term” used in ridge regression and Bata is calculated using the MAP estimate 1b) If there are two parameters the model alfa and bata see [1] If a kernel is used the parameters correspond to kernel parameters predicte(self,PHI): predicts the output given feature vectors PHI: feature vectors rows correspond to observations, columns correspond to variables var(self,PHI): predicts variance of estimate References: [1] Bishop, <NAME>. "Pattern recognition." Machine Learning 128 (2006) Chapter three [2]http://scikit-learn.org/stable/modules/generated/sklearn.metrics.pairwise.pairwise_kernels.html """ import numpy as np from sklearn.metrics.pairwise import pairwise_kernels class BayesianRegGaussPrior: def __init__(self,kind=None): if kind is None: kind='basis'; self.kind=kind; self.Parameters=[]; self.targets=[]; self.Parameters=[]; self.Sn=[]; self.Mn=[]; self.y_pred=[]; self.bata=[]; self.sigma_train=[]; self.sigma=[]; self.trainingdata=[]; self.K=[]; def fit(self,PHI,targets, Parameters): if (self.kind=='rbf'or self.kind=='sigmoid'or self.kind=="polynomial" or self.kind== "lin" or self.kind =="cosine"): # save target need for kernel interpellation self.targets=targets; #parameters self.Parameters=Parameters; #Kernel matrix K=pairwise_kernels(PHI[:,:],PHI[:,:],metric=self.kind,filter_params= self.Parameters); #To make a prediction on sample x using n-training sample sum with respect to xn i.e sum k(x,xn) #must equal one i.e sum k(x,xn)=1 Normalization=np.power(np.tile(np.sum(K,1),(K.shape[1], 1)),-1) ; K=Normalization*K; # Prediction using training data y_pred=np.dot(K,targets); # Prediction varance self.bata=np.var(targets-y_pred); # Prediction variance of each sample self.sigma=(self.bata)+np.diag(K)/(self.bata); self.trainingdata=PHI; if (self.kind=='basis'): self.targets=targets; self.Parameters; dim=PHI.shape[1]; S0=np.identity(dim); Parameter=np.array(Parameters); if (Parameter.size==1): #zero mean ,broad prior, with one parameter with maximum likelihood estimation of prior Lambda=Parameter[0]; self.Sn=np.linalg.inv(Lambda*S0+np.dot(PHI.transpose(),PHI)) self.Mn=np.dot(self.Sn, np.dot(PHI.transpose(),targets)) # Prediction of training data y_pred=np.dot(PHI,self.Mn) self.bata=np.var(targets-y_pred); self.sigma=(self.bata)+np.diag(np.dot(PHI,np.dot(self.Sn,PHI.transpose()))); if (Parameter.size==2): #zero mean ,broad prior, with two parameter alfa=Parameter[0]; bata=Parameter[1]; self.Sn=np.linalg.inv(alfa*S0+bata*np.dot(PHI.transpose(),PHI)) self.Mn=bata*np.dot(self.Sn, np.dot(PHI.transpose(),targets)) # Prediction of training data y_pred=np.dot(PHI,self.Mn) #Calculate noise variance on training data using MAP estimate self.bata=np.var(targets-y_pred); # prediction variance on training data self.sigma=(self.bata)+np.diag(np.dot(PHI,np.dot(self.Sn,PHI.transpose()))); def predicte(self,PHI): if (self.kind=='basis'): yhat=np.dot(PHI,self.Mn); return yhat if (self.kind=='rbf'or self.kind=='sigmoid'or self.kind=="polynomial" or self.kind== "lin" or self.kind =="cosine"): self.K=pairwise_kernels(self.trainingdata,PHI[:,:],metric=self.kind,filter_params=self.Parameters) #To make a prediction on sample x using n-training sample sum with respect to xn i.e sum k(x,xn) #must equal one i.e sum k(x,xn)=1 Normalization=np.power(np.tile(np.sum(self.K,1),(self.K.shape[1], 1)),-1) ; self.K=Normalization*self.K; # Prediction using training data yhat=np.dot(self.K,self.targets); # Prediction variance of each sample self.sigma=(self.bata)+np.diag(self.K)/(self.bata); return yhat def var(self,PHI): if (self.kind=='basis'): #Variance of prediction for each of the testing samples sigma=(self.bata)+np.diag(np.dot(PHI,np.dot(self.Sn,PHI.transpose()))); return sigma; if (self.kind=='rbf'or self.kind=='sigmoid'or self.kind=="polynomial" or self.kind== "lin" or self.kind =="cosine"): sigma=np.zeros((PHI.shape[0])); #Variance of prediction for each of the testing samples sigma=(self.bata)+np.diag(self.K)/(self.bata); return sigma; <file_sep>""" Kernel interpolation using polynomial kernel """ import matplotlib.pyplot as plt import numpy as np import BayesianRegGaussPrior as BRGP import toyData #Parameters w=np.array([1,1,1]); sigma=0.1 N=100; #toy training data Out=toyData.toyData(w,sigma,N); PHI=Out[2]; targets=Out[3]; y=Out[1] x=Out[0]; #Train model Model =BRGP.BayesianRegGaussPrior('polynomial'); Model.fit(PHI,targets,[1,1,2]); #Test toy data Out=toyData.toyData(w,sigma,N); PHI=Out[2]; targets=Out[3]; y=Out[1] x=Out[0]; #Prediction yhat=Model.predicte(PHI); sigma=np.sqrt(Model.var(PHI)); #plot data plt.plot(x,yhat,'b') plt.plot(x,y,'g') plt.plot(x,targets,'ro') plt.fill_between(x,yhat - 2 * sigma,yhat+ 2 * sigma, alpha=.10) axes.set_ylim([-3,3]) plt.legend(('Predicted function',' function','targets','2 xstd')) Ti='Testing Data Predicted function with N='+str(N); plt.title(Ti)
d9a6162c12b572dc92e45b73e7d45a7e2cb4690c
[ "Markdown", "Python" ]
6
Python
SimpleDeepLearning/Bayesian-regression-with-Infinitely-Broad-Prior-Gaussian-Parameter-Distribution-
3cb790479fe721975bdcf66d9a04d8523e09e60f
192b2e64d7cd923d1e39b3bebd8b366fb71627d7
refs/heads/abdev
<file_sep>package com.bajwa.SafeSkin.models; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import java.util.Date; @Entity public class SkinCare { @Id @GeneratedValue(strategy = GenerationType.AUTO) private long skinId; private String name; private Date expirDate; private Boolean isOpen; private Double size; private Long sku; public SkinCare() { } public SkinCare(String name, long skinId, Date expirDate, Boolean isOpen, Double size, Long sku) { this.skinId = skinId; this.expirDate = expirDate; this.isOpen = isOpen; this.size = size; this.sku = sku; } public SkinCare(String name, long skinId, Date expirDate, Boolean isOpen, Double size) { this.skinId = skinId; this.expirDate = expirDate; this.isOpen = isOpen; this.size = size; } public String getName() { return name; } public void setName(String name) { this.name = name; } public long getSkinId() { return skinId; } public void setSkinId(long skinId) { this.skinId = skinId; } public Date getExpirDate() { return expirDate; } public void setExpirDate(Date expirDate) { this.expirDate = expirDate; } public Boolean getOpen() { return isOpen; } public void setOpen(Boolean open) { isOpen = open; } public Double getSize() { return size; } public void setSize(Double size) { this.size = size; } public Long getSku() { return sku; } public void setSku(Long sku) { this.sku = sku; } } <file_sep>package com.bajwa.SafeSkin.controllers; import org.springframework.stereotype.Controller; @Controller public class SkinCareController { } <file_sep>package com.bajwa.SafeSkin.controllers; import org.springframework.stereotype.Controller; @Controller public class MakeUpController { } <file_sep># SafeSkin An application designed to log makeup & skin care products in inventory to keep record of expiration dates. <file_sep>package com.bajwa.SafeSkin.repositories; import com.bajwa.SafeSkin.models.MakeUp; import org.springframework.data.repository.CrudRepository; import org.springframework.stereotype.Repository; @Repository public interface MakeUpRepository extends CrudRepository<MakeUp, Long> { } <file_sep>package com.bajwa.SafeSkin.repositories; import com.bajwa.SafeSkin.models.SkinCare; import org.springframework.data.repository.CrudRepository; import org.springframework.stereotype.Repository; @Repository public interface SkinCareRepository extends CrudRepository<SkinCare, Long> { }
bed9fdd86e08a4f6633405caf3b190e6cd0cb5b2
[ "Markdown", "Java" ]
6
Java
aash-bjw/SafeSkin
12cba97add2f211a3acdd3e8c5cb0f58490d44eb
8046d3b54cbcb9325d141f1ff1a947476fd4b142
refs/heads/master
<file_sep>from flask import Flask, flash, redirect, render_template, request, session, abort, jsonify from wtforms import SelectField, SubmitField from flask_wtf import FlaskForm import numpy as np from collections import OrderedDict # My Files from Flask_Template import Data as data # request.path - get current page # form.value.choices = data - change the values of SelectField or ..... # @app.route('/', methods=['GET', 'POST']) - if error "method not allowed" app = Flask(__name__) app.config['SECRET_KEY'] = 'cairocoders-ednalan' # Forms class Form1(FlaskForm): value0 = SelectField('dates', choices=data.data, default=data.data[0], coerce=str) value1 = SelectField('list_2', choices=[key for key in data.list_2], default=[key for key in data.list_2][0]) list_1 = data.array_numpy(step=1) value2 = SelectField('list_1', choices=list_1, default=list_1[0]) value3 = SelectField('Colormaps', choices=data.cmaps['Sequential'], default=data.cmaps['Sequential'][-1]) value4 = SelectField('Classes of colormaps', choices=data.cmaps.keys(), default='Sequential') # Pages @app.route('/') def page_main(error=None, text=None): form1 = Form1() with open('cmap.html', "r", encoding='utf-8') as f: table = f.read() return render_template('page_main.html', bokS=table, form1=form1, error=error, text=text) @app.route("/about") def page_about(): return render_template('about.html') @app.route("/Page 1") def page_1(error=None, text=None, table = ''): form1 = Form1() return render_template('Page 1.html', bokS=table, form1=form1, error=error, text=text) @app.route("/Page 2") def page_2(error=None, text=None): form1 = Form1() table = '' return render_template('Page 2.html', bokS=table, form1=form1, error=error, text=text) @app.route("/Page 3-2") @app.route("/Page 3-1") def page_3(error=None, text=None): form1 = Form1() table = '' if request.path == '/Page 3-1': return render_template('Page 3-1.html', bokS=table, form1=form1, error=error, text=text) elif request.path == '/Page 3-2': return render_template('Page 3-2.html', bokS=table, form1=form1, error=error, text=text) @app.route("/Page 4") def page_4(error=None, text=None): form1 = Form1() table = '' return render_template('Page 4.html', bokS=table, form1=form1, error=error, text=text) @app.route("/Page 5 tab1-1") @app.route("/Page 5 tab1-2") @app.route("/Page 5 tab1-3") def page_5(error=None, text=None): form1 = Form1() table = '' if request.path == '/Page 5 tab1-1': return render_template('Page 5 tab1-1.html', bokS=table, form1=form1, error=error, text=text) elif request.path == '/Page 5 tab1-2': return render_template('Page 5 tab1-2.html', bokS=table, form1=form1, error=error, text=text) else: return render_template('Page 5 tab1-3.html', bokS=table, form1=form1, error=error, text=text) # Update @app.route("/Page 5 tab1-3", methods=['GET', 'POST']) @app.route("/Page 5 tab1-2", methods=['GET', 'POST']) @app.route("/Page 5 tab1-1", methods=['GET', 'POST']) @app.route("/Page 4", methods=['GET', 'POST']) @app.route("/Page 3-2", methods=['GET', 'POST']) @app.route("/Page 3-1", methods=['GET', 'POST']) @app.route("/Page 2", methods=['GET', 'POST']) @app.route("/Page 1", methods=['GET', 'POST']) @app.route('/', methods=['GET', 'POST']) def update_values(): # available forms: form0, form1, form2 error = None values = dict.fromkeys(keys) input = request.form.get("text", False) form1 = Form1() value0 = form1.value0.data value1 = form1.value1.data value2 = form1.value2.data value3 = form1.value3.data value4 = form1.value4.data if input: try: input = int(input) if 50 < input or input < 10: error = 'Values between max:50 - min:10' input = None else: values['input'] = input except ValueError: error = 'Must be an Int' input = None values['value0'] = value0 values['value1'] = value1 values['value2'] = value2 values['value3'] = value3 values['value4'] = value4 values['page'] = request.path if request.method == 'POST': new_values_update(values, error) s = f'{input}, {value0}, {value1}, {value2},{value3},{value4}, {request.path}' print('Page: ', request.path) if error: print('Errors: ', error) # , "Values:", s) if request.path == '/': return page_main(text=values, error=error) elif request.path == '/Page 1': return page_1(text=values, error=error) elif request.path == '/Page 2': return page_2(text=values, error=error) elif request.path == '/Page 4': return page_4(text=values, error=error) elif '/Page 3' in request.path: return page_3(text=values, error=error) elif '/Page 5' in request.path: return page_5(text=values, error=error) return render_template('page_main.html', text=input, form1=form1) keys = ['input', 'value0', 'value1', 'value2', 'value3', 'value4', 'page'] cache = dict.fromkeys(keys) def new_values_update(values, error): """ - works with cache - dict - updates data for the table One_Candle_Select """ print('new_values_One_Candle_Select', request.path) print('cache', cache) print('values', values) new_values = False values['input'] = 10 if values['input'] == None else values['input'] cache['input'] = 10 if cache['input'] == None else cache['input'] for key in keys: if cache[key] != values[key]: new_values = True old = cache[key] cache[key] = values[key] if key != 'input' or values[key] != None else cache[key] if old != cache[key]: print('New value -', f'old: {old}', '------>', f'new: {cache[key]}') if new_values and error == None: print('Updated') print('cache', cache) if request.path == '/': data.return_cmap(cmap_name=cache['value3']) print('Active tab -', request.path) else: print('No new values') # dynamic select @app.route('/<value>') def dynamic_select(value): print('value:', value) if value in data.list_2: print("value1") data1 = data.array_numpy(step=data.list_2[value]) return jsonify({"data1": data1}) elif value in data.cmaps.keys(): print("value4") data2 = data.cmaps[value] return jsonify({"data2": data2}) if __name__ == "__main__": app.run(debug=True) <file_sep>from bokeh.models.widgets import Div, Paragraph, PreText from bokeh.plotting import figure from bokeh.models.tools import * from bokeh.models import Asterisk, LinearAxis, Select, ColumnDataSource, HoverTool, CustomJS, ColumnDataSource, \ HoverTool, BoxAnnotation, Legend from bokeh.layouts import column, row, gridplot from bokeh.io import curdoc from bokeh.plotting import figure, output_file, show import pandas as pd import re from bs4 import BeautifulSoup import time import prepare_df_Trading_Variables as prepare def plot_fig(df, name=None): # bokeh serve --show bokeh_MAs_Diff_Select.py instrument_name = name # Select the datetime format for the x axis depending on the timeframe xaxis_dt_format = '%d %b %Y, %H:%M:%S' # for e in range(len(df['Date'])): # df['Date'][e] = str(df['Date'][e]) hover = HoverTool() hover.tooltips = [("series name", "@legend")] TOOLS = ['pan', 'wheel_zoom', 'box_zoom', 'reset', 'save', 'xwheel_zoom', 'ywheel_pan', CrosshairTool()] # Use wheel_zoom to interact like in tradingview # 1 # Add window window1 = figure( # sizing_mode='stretch_both', # to fit everything in one window title="Open to High", title_location="right", tools=TOOLS, active_drag='pan', active_scroll='wheel_zoom', x_axis_type='linear', # x_range=Range1d(df.index[0], df.index[-1], bounds="auto"),# fix the zoom plot_height=500, plot_width=500, ) # Add on extra lines (e.g. moving averages) here # fig.line(df.index, <your data>) data1 = ColumnDataSource( data=dict(x=df.index, y=df['Open to High'], legend_label=["series 1"] * len(df))) line1 = window1.line("x", "y", line_color="purple", source=data1, legend_label="Open to High") # fig - fig is done, now adding indicator figures # 2 # Add window window2 = figure( # sizing_mode='stretch_both', title="Open to Low", title_location="right", tools=TOOLS, active_drag='pan', active_scroll='xwheel_zoom', x_axis_type='linear', # x_range=Range1d(df.index[0], df.index[-1], bounds="auto"), plot_height=500, plot_width=500, ) window2.xaxis.visible = True data1 = ColumnDataSource(data=dict(x=df.index, y=df['Open to Low'], legend_label=["series 1"] * len(df))) line2 = window2.line("x", "y", line_color="purple", source=data1, legend_label="Open to Low") # Add extra data to indicator window window2.add_layout(LinearAxis(), 'right') # 3 # Add indicator window window3 = figure( # sizing_mode='stretch_both', title="Candle body (Open to Close)", title_location="right", tools=TOOLS, active_drag='pan', active_scroll='xwheel_zoom', x_axis_type='linear', # x_range=Range1d(df.index[0], df.index[-1], bounds="auto"), plot_height=500, plot_width=500, ) window3.xaxis.visible = True data1 = ColumnDataSource( data=dict(x=df.index, y=df['Candle body (Open to Close)'], legend_label=["series 1"] * len(df))) line3 = window3.line("x", "y", line_color="purple", source=data1, legend_label="Candle body (Open to Close)") window3.add_layout(LinearAxis(), 'right') # 4 # Add indicator window window4 = figure( # sizing_mode='stretch_both', title="Range", title_location="right", tools=TOOLS, active_drag='pan', active_scroll='xwheel_zoom', x_axis_type='linear', # x_range=Range1d(df.index[0], df.index[-1], bounds="auto"), plot_height=500, plot_width=500, ) window4.xaxis.visible = True data1 = ColumnDataSource(data=dict(x=df.index, y=df['Total Range'], legend_label=["series 1"] * len(df))) line4 = window4.line("x", "y", line_color="purple", source=data1, legend_label="Total Range") # Add extra data to indicator window window4.add_layout(LinearAxis(), 'right') ########### # End of adding windows # Set up the hover tooltip to display some useful data # for window1 window1.add_tools(HoverTool( renderers=[line1], tooltips=[ ("X", "@x"), ("Y", "@y"), ], )) # for window2 window2.add_tools(HoverTool( renderers=[line2], tooltips=[ ("X", "@x"), ("Y", "@y"), ], )) # for window3 window3.add_tools(HoverTool( renderers=[line3], tooltips=[ ("X", "@x"), ("Y", "@y"), ], )) # for window4 window4.add_tools(HoverTool( renderers=[line4], tooltips=[ ("X", "@x"), ("Y", "@y"), ], )) window1.legend.click_policy = "hide" window2.legend.click_policy = "hide" window3.legend.click_policy = "hide" window4.legend.click_policy = "hide" # Add Divs pre = PreText( text="""Your text is initialized with the 'text' argument. The remaining Paragraph arguments are 'width' and 'height'.""", width=500, height=100) desc = describe_df(df) div = Div( text=df_to_html(desc), width=200, height=100) # Finalise the figure fig = gridplot([[window1, window2], [window3, window4]]) # include here to add indicator window #layout = row(column(pre, fig), column(pre, div)) #show(layout) return fig css = """ <html> <head><title>HTML Pandas Dataframe with CSS</title></head> <style> .mystyle { font-size: 11pt; font-family: Arial; border-collapse: collapse; border: 1px solid silver; width: 800px; max-heigth: 229px; margin: 10px; } .mystyle td, th{ font-size: 11pt; padding: 5px; height: 5px; max-height: 5px; } .mystyle thead, th { font-size: 11pt; background-color: #e4f0f5; # width: 100%; #height: 100%; overflow:hidden; border-spacing:10px; max-width: 100px; heigth: 5px; } .mystyle tr:nth-child { background: #E0E0E0; } .mystyle tr:hover { background: lightblue; cursor: pointer; } .mystyle caption { padding: 5px; caption-side: top } </style> """ def df_to_html(df): # html format pd.set_option('colheader_justify', 'center') # FOR TABLE <th> html = (df.style # .set_caption('') .set_table_attributes('class="dataframe mystyle"') .render() ) html html_string = ''' <html> <head><title>HTML Pandas Dataframe with CSS</title></head> <link rel="stylesheet" type="text/css" href="df_style_1.css"/> <body> {table} </body> </html> ''' #html = html_string.format(table=df.to_html(classes='mystyle')) html = css + df.to_html(classes='mystyle') # OUTPUT AN HTML FILE with open('myhtml2.html', 'w') as f: f.write(html) return html def html_to_object(html_file_path=None, page=None): """ :param html_file_path: :return: """ if html_file_path: page = open(html_file_path, "r") TAG_RE_head = re.compile(r'<+.[head>]+>') # remove <head> tag TAG_RE_body = re.compile(r'<+.[body>]+>') # remove <head> tag def remove_tags(text, TAG_RE): return TAG_RE.sub('', text) soup = BeautifulSoup(page, 'lxml') style = remove_tags(str(soup.head), TAG_RE_head) table = remove_tags(str(soup.body), TAG_RE_body) return style, table def format_df(df): # Format dataframe df = df.rename(columns=lambda x: x[0].upper() + x[1:]) df['Open'] = pd.to_numeric(df['Open'], errors='coerce') df['High'] = pd.to_numeric(df['High'], errors='coerce') df['Low'] = pd.to_numeric(df['Low'], errors='coerce') df['Close'] = pd.to_numeric(df['Close'], errors='coerce') # Convert tom time format and merge df['Date'] = df['Date'] + " " + df['Time'] df['Date'] = pd.to_datetime(df['Date']) df['Open'] = df['Open'].astype(float) df['High'] = df['High'].astype(float) df['Low'] = df['Low'].astype(float) df['Close'] = df['Close'].astype(float) df = df.drop(['Time', 'TimeFrame', 'Instrument'], axis=1) return df def calculate_stats(df): """ 1. Open to High 2. Open to Low 3. Candle body (Open to Close) 4. Total Range """ df['Open to High'] = df['High'] - df['Open'] df['Open to Low'] = df['Open'] - df['Low'] df['Candle body (Open to Close)'] = abs(df['Open'] - df['Close']) df['Total Range'] = df['High'] - df['Low'] def describe_df(df): """ Input: 1. df - dataframe Output: 1. new df """ df = df.describe() # this prevents from formatting df # create new df dict_names = ('count', 'mean', 'std', 'min', '25%', '50%', '75%', 'max') col_names = ('Open', 'High', 'Low', 'Close', 'Open to High', 'Open to Low', 'Candle body (Open to Close)', 'Total Range') df_new = pd.DataFrame(index=dict_names, columns=col_names) df_new = df_new.fillna('NaN') # with 0s rather than NaNs # copy and format data from df: for col in df.columns: a = df[col].tolist() a[0] = str(a[0]).split('.')[0] a[1:] = [round(s, 5) for s in a[1:]] df_new[col] = a return df_new def exec_main(instrument_name,timeframe, last=None ): df = prepare.get_format_df(instrument_name, timeframe, last=last) calculate_stats(df) return df def main(): # create df pd.set_option('max_columns', 100) #df_to_html(df) # fig = plot_fig(df, name='GBPUSD') # show the results # output to static HTML file # output_file("log_lines.html") instrument_list = ["EURUSD", "EURCAD", "EURAUD", "EURNZD", "EURJPY", "GBPUSD", "GBPCAD", "GBPAUD", "GBPNZD", "GBPJPY"] timeframe = { 'H1': '1 hours', 'H4': '4 hours', 'D1': '1 day', 'W1': '1 week', } path = 'C:\My Files\My Files\Study - (Courses)\#Education - Computer Science - Notion\Python\Chart py\MT5 data' def update_plot2(attrname, old, new): try: curdoc().clear() t0 = time.time() print('_______________________________________Update') # plot graphs df = exec_main(select2.value, timeframe['D1'], last=None) fig = plot_fig(df, name=select2.value) t1 = time.time() timer.text = '(Execution time: %s seconds)' % round(t1 - t0, 4) desc = describe_df(df) div = Div( text=df_to_html(desc), width=200, height=100) print(select2.value) except FileNotFoundError: print("No such instrument or Timeframe") return 0 layout = column( row(select2, timer), row(column(pre, fig), column(pre, div)) ) curdoc().add_root(layout) # initial data instrument_name = 'GBPJPY' t0_main = time.time() # plot graphs df = exec_main(instrument_name, timeframe['D1'], last=None) fig = plot_fig(df, name=instrument_name) pre = PreText( text="""Your text is initialized with the 'text' argument. The remaining Paragraph arguments are 'width' and 'height'.""", width=500, height=100) # plot tables desc = describe_df(df) div = Div( text=df_to_html(desc), width=200, height=100) # plot Select select2 = Select(title="Instrument", options=instrument_list, value=instrument_name) select2.on_change('value', update_plot2) # Plot Layout & run # row(div2, div22) timer = Paragraph() layout = column( row(select2, timer), row(column(pre, fig), column(pre, div)) ) curdoc().title = "Dashboard Demo" curdoc().theme = 'caliber' t1_main = time.time() timer.text = '(Execution time: %s seconds)' % round(t1_main - t0_main, 4) print(timer.text) curdoc().add_root(layout) main() # bokeh serve --show test_Analytics_Trading_2.py # bokeh serve --show test_Analytics_Trading_2 <file_sep>import time import re def isTimeFormat(line,): try: time.strptime(line, '%M:%S') #works only %M till 60 return True except ValueError: #output.append(line) return False def t(line): if re.search(r'(\d+:\d+)', line) == None: return True else: #output.add(line) return False f = open('input.txt', mode='r', encoding='utf-8-sig').read().split("\n") output = [] string = '"' for line in f: #print(isTimeFormat(line)) #print(t(line)) if (t(line) == True): string = string + " " + line #if (isTimeFormat(line) == False): #print(isTimeFormat(line), line) #string = string + line #if (isTimeFormat(line) == False) and (t(line)== False): # string = string + line #else: #for item in output: # string = string + item + " " print(string + '"') #print(len(f) """ if (isTimeFormat(f[0]) != True) and (t(f[0]) != True): pass #if f[0] == time 99:99 else: i = len(f) - 1 while i >= 0: #print(f[i]) del f[i] i = i - 2 string2 = "" for item in output: string2 = string2 + item + " " print(*f ) #for line in f: #print(isTimeFormat(line)) #print(re.search(r'(\d+:\d+)', line)) #string = string + " " + str(isTimeFormat(line)) #isTimeFormat(line) #print(string) #print(*output) #f = open("input1.txt", "w",encoding='utf-8-sig') #f.write(string) #f.close() #f.write(string) #f.write("\n".join(str(item) for item in output)) #print(string2) #f.write(string2) #f.close() #open and read the file after the appending: #f = open("input.txt", "r") #print(f.read()) """ <file_sep># Color cell with different colors with Styler .bar ### Example of Output: ### style_df: ![Screenshot_2](https://user-images.githubusercontent.com/48917675/86946339-146b6f00-c0ff-11ea-87a3-51f3677b7200.jpg) ### show_colormap(cmap_name='plasma'): ![Screenshot_3](https://user-images.githubusercontent.com/48917675/86946405-2d742000-c0ff-11ea-8d9f-5f14d3163a03.jpg) <file_sep> import matplotlib as mpl import matplotlib.cm as cm import matplotlib as matplotlib import matplotlib.pyplot as plt import matplotlib.cm as cm def color_map(value, cmap_name): norm = plt.Normalize(0, 1) norm = matplotlib.colors.Normalize(vmin=0, vmax=1) cmap = cm.get_cmap(cmap_name) # PiYG rgb = cmap(norm(value))[:3] # will return rgba, we take only first 3 so we get rgb color = matplotlib.colors.rgb2hex(rgb) return color html_string = ''' <meta name="viewport" content="user-scalable=no, initial-scale=1, maximum-scale=1, minimum-scale=1" /> <p style="background-color:{color};">This is a paragraph. {text}</p> ''' if __name__ == "__main__": cmap_name = 'seismic' file = open(f'{cmap_name}_cmap.html', "w") values = [ 0.0030, 0.2997 , 0.0002 , -0.9131 , 0.913, 1 , -1, 0 ] values = [num/100 for num in range(1, 100)] for val in values: c = color_map(abs(val), cmap_name) print(c) html = html_string.format(color=c, text=val ) file.write(html) file.close() <file_sep># Value to Colormap ### func: Numeric value to color from the colormap ### Example of Output: Colormap: ![image](https://user-images.githubusercontent.com/48917675/85925404-19056d00-b84d-11ea-9fae-274e57046b06.png) <file_sep>### 1 ![Screenshot_1](https://user-images.githubusercontent.com/48917675/110218374-602d0e80-7e6e-11eb-90af-249c809586c7.jpg) ### 2 ![Screenshot_2](https://user-images.githubusercontent.com/48917675/110218372-5efbe180-7e6e-11eb-9cd1-a16dedbb9b7d.jpg) <file_sep>![Screenshot_1](https://user-images.githubusercontent.com/48917675/89075441-09d57b80-d333-11ea-89f3-cd3585cdca2d.jpg) ![Screenshot_2](https://user-images.githubusercontent.com/48917675/89075442-0a6e1200-d333-11ea-9620-ca85b4fb8344.jpg) <file_sep> from wtforms import SelectField, SubmitField from flask_wtf import FlaskForm import numpy as np from collections import OrderedDict import matplotlib as matplotlib import matplotlib.pyplot as plt import matplotlib.cm as cm # request.path - get current page # form.value.choices = data - change the values of SelectField or ..... # @app.route('/', methods=['GET', 'POST']) - if error "method not allowed" html_string_2 = ''' <meta name="viewport" content="user-scalable=no, initial-scale=1, maximum-scale=1, minimum-scale=1" /> <p style="background-color:{color}; margin-top:0px; margin-bottom:0px; font-size:5pt">{text}</p> ''' def color_map(value, cmap_name='plasma', vmin=0, vmax=1, bg=False): norm = plt.Normalize(vmin, vmax) norm = matplotlib.colors.Normalize(vmin=vmin, vmax=vmax) cmap = cm.get_cmap(cmap_name) # PiYG rgb = cmap(norm(value))[:3] # will return rgba, we take only first 3 so we get rgb color = matplotlib.colors.rgb2hex(rgb) if bg: return 'background-color: %s' % color else: return color def return_cmap(cmap_name = 'autumn_r'): file = open('cmap.html', "w") values = [num for num in range(0, 50)] for val in values: c = color_map(abs(val), cmap_name, vmin=0, vmax=50) # print(c) html = html_string_2.format(color=c, text=val) file.write(html) file.close() with open('test1.txt', "r", encoding='utf-8') as f: data = [elem.replace("\n", "") for elem in f.readlines() if elem != "\n"] def array_numpy(step=1): return np.arange(start=0, stop=100+step, step=step).tolist() list_2 = { '1': 1, '2': 2, '3': 3, '4': 4, } cmaps = OrderedDict() cmaps['Perceptually Uniform Sequential'] = [ 'viridis', 'plasma', 'inferno', 'magma', 'cividis'] cmaps['Sequential'] = [ 'Greys', 'Purples', 'Blues', 'Greens', 'Oranges', 'Reds', 'YlOrBr', 'YlOrRd', 'OrRd', 'PuRd', 'RdPu', 'BuPu', 'GnBu', 'PuBu', 'YlGnBu', 'PuBuGn', 'BuGn', 'YlGn'] cmaps['Sequential (2)'] = [ 'binary', 'gist_yarg', 'gist_gray', 'gray', 'bone', 'pink', 'spring', 'summer', 'autumn', 'winter', 'cool', 'Wistia', 'hot', 'afmhot', 'gist_heat', 'copper'] cmaps['Diverging'] = [ 'PiYG', 'PRGn', 'BrBG', 'PuOr', 'RdGy', 'RdBu', 'RdYlBu', 'RdYlGn', 'Spectral', 'coolwarm', 'bwr', 'seismic'] cmaps['Cyclic'] = ['twilight', 'twilight_shifted', 'hsv'] cmaps['Qualitative'] = ['Pastel1', 'Pastel2', 'Paired', 'Accent', 'Dark2', 'Set1', 'Set2', 'Set3', 'tab10', 'tab20', 'tab20b', 'tab20c'] cmaps['Miscellaneous'] = [ 'flag', 'prism', 'ocean', 'gist_earth', 'terrain', 'gist_stern', 'gnuplot', 'gnuplot2', 'CMRmap', 'cubehelix', 'brg', 'gist_rainbow', 'rainbow', 'jet', 'nipy_spectral', 'gist_ncar'] <file_sep>from flask import Flask, render_template, url_for, request, flash, session, redirect, abort, Response, jsonify from wtforms import SelectField, SubmitField, SelectField, StringField from flask_wtf import FlaskForm import os, sys, time, random, datetime, secrets import threading from collections import OrderedDict # import schedule root = os.path.dirname(os.path.realpath(__file__)) os.chdir(root) sys.path.append(root) SECRET_KEY = os.urandom(32) app = Flask(__name__) app.config['SECRET_KEY'] = SECRET_KEY from wtforms import SelectField, SubmitField, SelectField, StringField from flask_wtf import FlaskForm class ExportingThread(threading.Thread): def __init__(self, id_=''): self.progress = 0 self.id_ = id_ # just for debugging super().__init__() def run(self): # Your exporting stuff goes here ... print(f'#{self.id_} start') for _ in range(10): time.sleep(1) print(f'#{self.id_} ..working {_}') self.progress += 10 print(f'#{self.id_} done') exporting_threads = OrderedDict() box_values = OrderedDict() exporting_threads2 = OrderedDict() box_values2 = OrderedDict() # Ordered dict ? # request last key? def some_task_2(id_): # Your exporting stuff goes here ... progress = 0 print(f'#{id_} start') for _ in range(10): time.sleep(1) print(f'#{id_} ..working {_}') progress += 10 print(f'#{id_} done') def some_task(): # generate token return secrets.token_urlsafe(20) @app.route('/_perpetual_stuff', methods=['GET']) def perpetual_progress(): return jsonify(result_perpetual=some_task()) @app.route('/_stuff', methods=['GET']) def progress(): # exporting_threads global box_values prev = list(exporting_threads.keys())[-1] if len(list(exporting_threads.keys())) > 0 else 0 result = str(exporting_threads[prev].progress) if prev else 0 # print(exporting_threads.keys()) # print(prev) # str(exporting_threads[thread_id].progress) return jsonify(result=result) @app.route('/_stuff2', methods=['GET']) def progress2(): # exporting_threads2 global box_values prev = list(exporting_threads2.keys())[-1] if len(list(exporting_threads2.keys())) > 0 else 0 print('prev', prev) # Measures time passed time_passed = 0 if prev != 0: if exporting_threads2[prev].is_alive() == False: box_values2[prev]['Status'] = 'Finished' time_passed = 'Finished' else: time_passed = str(datetime.datetime.now() - datetime.datetime.strptime( box_values2[prev]['Start Date'], "%Y-%m-%d %H:%M:%S")) return jsonify(result2=time_passed) @app.route('/', methods=['GET', 'POST']) def default_page(error=None, values=None, status=None): interval = 2000 # 2 seconds interval2 = 5000 # 5 seconds # form1 = Form1() global exporting_threads global box_values # start new task # if new thread, stops all the previous threads. Therefore only 1 thread is allowed. # Just need one task in the background if request.method == 'POST': print(request.form, list(request.form.keys())) # for 1 thread only # thread_id = 1010 # for multiple threads thread_id = random.randint(0, 10000) if 'submit_button_1' == list(request.form.keys())[0]: print('submit_button_1 pressed') # task with progress exporting_threads[thread_id] = ExportingThread(id_=thread_id) # start exporting_threads[thread_id].start() # Add text to box_values keys_ = ['ID', 'Status', 'Progress', 'Start Date', 'End Date', 'Duration'] box_values[thread_id] = dict.fromkeys(keys_) box_values[thread_id]['ID'] = thread_id box_values[thread_id]['Status'] = 'running' box_values[thread_id]['Start Date'] = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S") elif 'submit_button_2' == list(request.form.keys())[0]: print('submit_button_2 pressed') # task with unknown progress, for any function exporting_threads2[thread_id] = threading.Thread(target=some_task_2, kwargs={'id_': thread_id}) # start exporting_threads2[thread_id].start() # Add text to box_values2 keys_ = ['ID', 'Status', 'Start Date', 'End Date', 'Duration'] box_values2[thread_id] = dict.fromkeys(keys_) box_values2[thread_id]['ID'] = thread_id box_values2[thread_id]['Status'] = 'running' box_values2[thread_id]['Start Date'] = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S") # Add text to box_values for key in box_values.keys(): # If status has not yet been changed box_values[key]['Progress'] = str(exporting_threads[key].progress) # If finished if box_values[key]['Status'] == 'running' and box_values[key]['Progress'] == '100': box_values[key]['Status'] = 'Finished' if str(exporting_threads[key].progress) == '100' else 'running' box_values[key]['End Date'] = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S") box_values[key]['Duration'] = str(datetime.datetime.strptime(box_values[key]['End Date'], "%Y-%m-%d %H:%M:%S") - datetime.datetime.strptime( box_values[key]['Start Date'], "%Y-%m-%d %H:%M:%S")) for key in exporting_threads2.keys(): print('Alive or Dead:', key, exporting_threads2[key].is_alive()) # If finished if exporting_threads2[key].is_alive() == False: box_values2[key]['Status'] = 'Finished' box_values2[key]['End Date'] = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S") box_values2[key]['Duration'] = str(datetime.datetime.strptime(box_values2[key]['End Date'], "%Y-%m-%d %H:%M:%S") - datetime.datetime.strptime( box_values2[key]['Start Date'], "%Y-%m-%d %H:%M:%S")) # progress of the last thread # for exporting_threads status = str(exporting_threads[list(exporting_threads.keys())[-1]].progress) if len( list(exporting_threads.keys())) > 0 else 0 # thread1 = list(exporting_threads.keys())[0] if len(list(exporting_threads.keys())) > 0 else 0 # check of finished # print(exporting_threads.keys(), ) # # for thread in threading.enumerate(): # print(thread.name) # print(box_values.keys()) return render_template(f'main.html', bokS='', form1='form1', error=error, text2=box_values2, text=box_values, status=status, interval=interval, interval2=interval, interval3=interval2) if __name__ == '__main__': app.run() <file_sep>![sdvsdv](https://user-images.githubusercontent.com/48917675/87469574-564d5700-c5d0-11ea-8cdc-bfc8e8baebe6.jpg) ![asdfgvasfv](https://user-images.githubusercontent.com/48917675/87469672-7e3cba80-c5d0-11ea-91f8-1cfd1c11f8c3.jpg) ![sdfavfsbv](https://user-images.githubusercontent.com/48917675/87469706-885eb900-c5d0-11ea-8532-d4a2433f8e4e.jpg) <file_sep>from flask import Flask, render_template, request from wtforms import SelectField from flask_wtf import FlaskForm app = Flask(__name__) app.config['SECRET_KEY'] = 'cairocoders-ednalan' with open(r'C:\Users\khini\PycharmProjects\untitled1\test1.txt', "r", encoding='utf-8') as f: data = [elem.replace("\n", "") for elem in f.readlines() if elem != "\n"] # print(data, type(data)) class Form(FlaskForm): value = SelectField('country', choices=data) @app.route('/', methods=['GET', 'POST']) def index(): form = Form() form.value.choices = data if request.method == 'POST': value = form.value.data print(value) return '<h1>Value : {}</h1>'.format(value) return render_template('index.html', form=form) if __name__ == '__main__': app.run(debug=True) <file_sep> from datetime import datetime, timedelta import pytz import pandas as pd # initial format data def format_df(df): # Format dataframe df = df.rename(columns=lambda x: x[0].upper() + x[1:]) df['Open'] = pd.to_numeric(df['Open'], errors='coerce') df['High'] = pd.to_numeric(df['High'], errors='coerce') df['Low'] = pd.to_numeric(df['Low'], errors='coerce') df['Close'] = pd.to_numeric(df['Close'], errors='coerce') # Convert tom time format and merge df['Date'] = df['Date'] + " " + df['Time'] df['Date'] = pd.to_datetime(df['Date']) df['Open'] = df['Open'].astype(float) df['High'] = df['High'].astype(float) df['Low'] = df['Low'].astype(float) df['Close'] = df['Close'].astype(float) # df = df.drop(['Time','TimeFrame', 'Instrument'], axis=1) return df # time check def timeframe(df): if (pd.to_datetime(df['Date'][1]) - pd.to_datetime(df['Date'][0])) != timedelta(days=1): if (pd.to_datetime(df['Date'][1]) - pd.to_datetime(df['Date'][0])) != timedelta(weeks=1): # Convert tom time format and merge df['Date'] = df['Date'] + " " + df['Time'] def check_if_closed(df): # print(df['Close'][len(df) - 1]) if df['Close'][len(df) - 1] == "Open": df = df.drop(df.index[[len(df) - 1]]) else: """ Potential error if last 2 rows from different weeks - Weekend in between - date delta is different :param df: :return: Drops last row if candle has not closed """ # time_of_the_last_candle most_recent_quote = pd.to_datetime(df['Date'][len(df) - 1]) prev_most_recent_quote = pd.to_datetime(df['Date'][len(df) - 2]) print('_______________________________________') print('most_recent_quote', most_recent_quote) print('prev_most_recent_quote', prev_most_recent_quote) '''Get time of last candle close''' timediff = most_recent_quote - prev_most_recent_quote # also used for rates_frame["TimeFrame"] = str(timediff) candle_close_time = most_recent_quote + timediff print("timediff: ", timediff, type(timediff)) print("candle_close_time: ", candle_close_time, type(candle_close_time)) '''Get current time''' # set time zone to UTC timezone = pytz.timezone('Europe/Riga') # getting datetime of specified timezone current_time = datetime.now(tz=timezone).strftime('%Y-%m-%d %H:%M:%S') # check_if_candle_closed if pd.to_datetime(current_time) > candle_close_time: print("Candle has closed", df['TimeFrame'][0]) else: print("Candle has Not closed!", df['TimeFrame'][0]) df = df.drop(df.index[[len(df) - 1]]) # return df return df def exec_format(file, last=None): df = pd.read_csv(file) timeframe(df) df = check_if_closed(df) df = format_df(df) # Custom Slice the dataframe if last: print('Quotes until: ', last) try: indx = df[df['Date'] == last].index.item() df = df[0:indx + 1] except: print('Date is not Found, empty list - Perhaps day is a Weekend') df.reset_index(drop=True, inplace=True) # reset index return df # for last, checks H4 candle def h4_time(a2): """ Finds closest H4 candle Input: a2 - <class 'datetime.datetime'> Output: replaces %H if necessary """ t = (0, 4, 8, 12, 16, 20) if (int(a2.hour)) % 4 != 4: delta = [abs(int(a2.hour) - i) for i in t if int(a2.hour) >= i] min_delta = delta.index(min(delta)) a2 = a2.replace(hour=t[min_delta]) return a2 def get_format_df(instrument_name, timeframe, last=None): """ func: returns formatted df from file Input: 1. instrument_name - string 2. timeframe - string 3. last=None - Bool - time of the last candle """ path = 'C:\My Files\My Files\Study - (Courses)\#Education - Computer Science - Notion\Python\Chart py\MT5 data' instrument_name = instrument_name # Open files file = path + '\_raw_{}-{}.csv'.format(instrument_name, timeframe) df = exec_format(file, last=last) return df # main func def get_format_dfs(instrument_name, last=None): """ func: returns formatted dfs from files """ path = 'C:\My Files\My Files\Study - (Courses)\#Education - Computer Science - Notion\Python\Chart py\MT5 data' instrument_name = instrument_name # Open files file_h1 = path + '\_raw_{}-{}.csv'.format(instrument_name, '1 hours') file_h4 = path + '\_raw_{}-{}.csv'.format(instrument_name, '4 hours') file_d1 = path + '\_raw_{}-{}.csv'.format(instrument_name, '1 day') last_h1 = None last_h4 = None last_d1 = None if last: date1 = datetime.strptime(last, '%Y-%m-%d %H:%M:%S') last_h1 = str(date1) last_h4 = str(h4_time(date1)) last_d1 = str(date1.replace(hour=0)) df_h1 = exec_format(file_h1, last=last_h1) df_h4 = exec_format(file_h4, last=last_h4) df_d1 = exec_format(file_d1, last=last_d1) return df_h1, df_h4, df_d1 <file_sep>import matplotlib.pyplot as plt import matplotlib.cm as cm import matplotlib as matplotlib import pandas as pd def color_map_color(value, cmap_name='Wistia', vmin=0, vmax=1): # value to colormap color # norm = plt.Normalize(vmin, vmax) norm = matplotlib.colors.Normalize(vmin=vmin, vmax=vmax) cmap = cm.get_cmap(cmap_name) # PiYG rgb = cmap(norm(abs(value)))[:3] # will return rgba, we take only first 3 so we get rgb color = matplotlib.colors.rgb2hex(rgb) return color def show_colormap(cmap_name='Wistia'): cmap = cm.get_cmap(cmap_name) fig = plt.figure(figsize=(8, 2)) ax1 = fig.add_axes([0.05, 0.80, 0.9, 0.15]) norm = matplotlib.colors.Normalize(vmin=0, vmax=1) cb1 = matplotlib.colorbar.ColorbarBase(ax1, cmap=cmap, norm=norm, orientation='horizontal') plt.show() def style_df(df): # Example rows = 10 indx = list(df.index)[-rows:] # indecies of the last 10 rows # Colormap for the last 10 rows in Compare Body % last10 = df['Column'][-rows:] # values to color colors = [color_map_color(e, cmap_name='autumn_r', vmin=100, vmax=1000) for e in last10] # colors values = [pd.IndexSlice[indx[i], 'Column'] for i in range(rows)] # for .bar subset html = (df.style .bar(subset=values[0], color=colors[0], vmax=1000, vmin=0, align='left', width=100) .bar(subset=values[1], color=colors[1], vmax=1000, vmin=0, align='left', width=100) .bar(subset=values[2], color=colors[2], vmax=1000, vmin=0, align='left', width=100) ) html return html <file_sep>Transforms YouTube Transcript to Text Block. Exanple: ``` #input.txt земная гравитация 33:49 она слишком для нас велика именно 33:52 поэтому 85 процентов населения мира 33:55 страдает от искривление позвоночника и 33:58 остеохондроза ``` Output: ``` "земная гравитация она слишком для нас велика именно поэтому 85 процентов населения мира страдает от искривление позвоночника и остеохондроза " ```
b0b8607e6eaa2e46331d26a7d7b3868ce2a84b8a
[ "Markdown", "Python" ]
15
Python
khnh123/My-Code
a998bf9ffa3418bfd7860cdc6d36c3457d0c38ff
ae451bc3ced5d0abc0c3f1e4873ef3b255c87cdd
refs/heads/master
<repo_name>BIGLabHYU/BIGlab_practice<file_sep>/main.cpp /* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ /* * File: main.cpp * Author: Jwawon * * Created on April 15, 2016, 9:46 AM */ #include <cstdlib> #include <iostream> #include "BObject.h" #include "BVector.h" int main(int argc, char** argv) { BVector theVector; std::cout << theVector.getClassName(); std::cout << theVector.toString(); return 0; } <file_sep>/BVector.h /* * Copyright (C) 2016 <NAME> <<EMAIL>>. * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301 USA */ /* * File: BVector.h * Author: <NAME> <<EMAIL>> * * Created on 2016년 4월 27일 (수), 오전 8:23 */ #ifndef BVECTOR_H #define BVECTOR_H #include <vector> #include <iostream> #include <sstream> #include "BObject.h" class BVector : public virtual BObject { public: typedef std::vector<double> DoubleArray; typedef std::string::size_type size_type; BVector() { this->__setData(DoubleArray(3, 0)); } BVector(const int theSize, const double = 0) { if (theSize > 0) { this->__setData(DoubleArray(theSize, 0)); } else { std::cerr << "The input of theSize is not positive! in the " << this->getClassName() << "\n"; this->__setData(DoubleArray(3, 0)); } } BVector(const BVector& theVector) { } std::string getClassName() const { return "BVector"; } std::string toString() const { std::ostringstream theBuffer; if (this->__getData().empty()) { return ("[]"); } else { theBuffer << ("["); for (size_type i = 0, theEnd = this->size() - 1; i < theEnd; i++) { theBuffer << this->getValue(i) << ", "; } theBuffer << this->__getData().back() << "]"; } return theBuffer.str(); } inline const size_type size() const { return this->__getData().size(); } // Getters inline double getValue(const int theIndex) const { return this->__getData()[this->_toIndex(theIndex)]; } inline double get(const int theIndex) const { return this->getValue(theIndex); } // Setters void set(const BVector& theVector) { this->__setData() = theVector.__getData(); } void set(const int theIndex, const double theValue) { this->setValue(theIndex, theValue); } void setValue(const int theIndex, const double theValue) { this->__setData()[this->_toIndex(theIndex)] = theValue; } void resize(const size_type theSize) { if(theSize == 0) { std::cerr << "Vector size must be not zero! in the " << this->getClassName() << "\n"; } else { this->__setData().resize(theSize); } } // BVector& add(const BVector& theVector) { size_type theLastIndex = std::min(this->size(), theVector.size()); for (size_type i = 0; i < theLastIndex; i++) { this->setValue(i, this->getValue(i) + theVector.getValue(i)); } } BVector& append(const double theValue) { this->__setData().push_back(theValue); } BVector cross(const BVector& theVector) const { size_type theSize = this->size(); BVector theResultVector; if(theSize == theVector.size() && theSize == 3) { theResultVector.resize(theSize); theResultVector[0] = this->getValue(1) * theVector.getValue(2) - this->getValue(2) * theVector.getValue(1); theResultVector[1] = this->getValue(2) * theVector.getValue(0) - this->getValue(0) * theVector.getValue(2); theResultVector[2] = this->getValue(0) * theVector.getValue(1) - this->getValue(1) * theVector.getValue(0); } else { std::cerr << "The size of vectors is not 3 in the " << this->getClassName() << "\n"; } return theResultVector; } double dot(const BVector& theVector) const { size_type theSize = this->size(); double theDotProduct = 0; if(theSize == theVector.size()) { for(size_type i=0, theEnd=theVector.size();i<theEnd;i++) { theDotProduct += this->getValue(i) * theVector.getValue(i); } } else { std::cerr << "The sizes of two input vector are not same in the " << this->getClassName() << std::endl; } return theDotProduct; } BVector minus(const BVector& theVector) const { BVector thisVector(*this); thisVector.subtract(theVector); return thisVector; } BVector subtract(const BVector& theVector) { size_type theLastIndex = std::min(this->size(), theVector.size()); for(size_type i=0;i<theLastIndex;i++) { this->setValue(i, this->getValue(i) - theVector.getValue(i)); } } //Operators double& operator [] (const size_type theIndex) { return this->__setData()[theIndex]; } const double operator [] (const size_type theIndex) const { return this->__getData()[theIndex]; } BVector& operator = (const BVector& theVector) { this->set(theVector); return *this; } BVector operator - () const { BVector thisVector(*this); for(size_type i=0, theEnd=this->size();i<theEnd;i++) { thisVector.setValue(i, -this->getValue(i)); } } protected: size_type _toIndex(const int theIndex) const { if (theIndex < 0) { size_type theDiff = this->size() + theIndex; if (theDiff >= 0) { return theDiff; } else { std::cerr << "The index is wrong!!! in the " << this->getClassName() << "\n"; return 0; } } else { return theIndex; } } private: inline DoubleArray & __getData() { return this->itsData; } inline const DoubleArray & __getData() const { return this->itsData; } inline DoubleArray & __setData() { return this->itsData; } inline void __setData(const DoubleArray& theDoubleArray) { this->itsData = theDoubleArray; } DoubleArray itsData; }; #endif /* BVECTOR_H */ <file_sep>/BObject.h /* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ /* * File: BObject.h * Author: Jwawon * * Created on April 19, 2016, 11:01 AM */ #ifndef BOBJECT_H #define BOBJECT_H #include <iostream> //화면출력 함수 #include <string> class BObject { public: BObject(){ } BObject(const BObject& orig){ } virtual ~BObject(){ } virtual std::string toString() const { return this->getClassName(); } virtual std::string getClassName() const { return "BObject"; } friend inline std::ostream & operator<<(std::ostream &theStream, const BObject & theSelf) { return (theStream << theSelf.toString()); } private: }; #endif /* BOBJECT_H */
e94cc31fc6ea685bbc2cd905d4b16bdff163ff7b
[ "C++" ]
3
C++
BIGLabHYU/BIGlab_practice
f0ec46895af122bcf8c857400de1b7ecebb98cdd
701235d11dce0dea968319cb8b53f5c63bd24686
refs/heads/master
<file_sep>package com.itbank.dataCheck; import java.io.BufferedReader; import java.io.InputStreamReader; import java.io.StringReader; import java.net.HttpURLConnection; import java.net.URL; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.xpath.XPath; import javax.xml.xpath.XPathConstants; import javax.xml.xpath.XPathExpression; import javax.xml.xpath.XPathFactory; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.Node; import org.w3c.dom.NodeList; import org.xml.sax.InputSource; public class Data01 { // XPath를 활용한 xml기반 오픈 api java파싱 public static void main(String[] args) { BufferedReader br = null; // DocumentBuilderFactory 생성 DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); factory.setNamespaceAware(true); DocumentBuilder builder; Document doc = null; try { // OpenApi 호출 // String urlstr = // "http://apis.data.go.kr/1300000/jBGSSCJeongBo/list?numOfRows=100&pageNo=1&ServiceKey=a8VRdtLdlYzaiyorG5b6RtWyr1EfAi%2BO<KEY>Tzj5WcpHC%2FQmvPFroQ4Ne0uL3%2BZGTJHBViA%3D%3D"; String urlstr = "http://newsky2.kma.go.kr/service/SecndSrtpdFrcstInfoService2/list?numOfRows=100&pageNo=1&ServiceKey=%2<KEY>%2<KEY>%2FbiKyI%2F%2FImDCGyWCGn%2FJr44%2Bzgq7XKQUZZsKoVgUGuw%3D%3D"; URL url = new URL(urlstr); HttpURLConnection urlconnection = (HttpURLConnection) url.openConnection(); // 응답 읽기 br = new BufferedReader(new InputStreamReader(urlconnection.getInputStream(), "UTF-8")); String result = ""; String line; while ((line = br.readLine()) != null) { result = result + line.trim(); // result = URL로 XML을 읽은값 } // xml 파싱하기 InputSource is = new InputSource(new StringReader(result)); builder = factory.newDocumentBuilder(); doc = builder.parse(is); XPathFactory xPathFactory = XPathFactory.newInstance(); XPath xpath = xPathFactory.newXPath(); XPathExpression expr = xpath.compile("//items/item"); // 노드 문법입력 NodeList nodeList = (NodeList) expr.evaluate(doc, XPathConstants.NODESET); /* * for(int i = 0; i < nodeList.getLength(); i++) { NodeList child = * nodeList.item(i).getChildNodes(); * * for(int j = 0; j < child.getLength(); j++) { Node node = * child.item(j); System.out.println("현재노드 이름 : " + * node.getNodeName()); System.out.println("현재노드 타입 : " + * node.getNodeType()); System.out.println("현재노드 값 : " + * node.getTextContent()); System.out.println("현재노드 네임스페이스 : " + * node.getPrefix()); System.out.println("현재노드의 다음 노드 : " + * node.getNextSibling()); * * } } */ for (int i = 0; i < 1; i++) { NodeList child = nodeList.item(i).getChildNodes(); for (int j = 0; j < 12; j++) { Node node = child.item(j); System.out.println("현재<item>안의 노드 값 : " + node.getTextContent()); } } } catch (Exception e) { System.out.println(e.getMessage()+"why?"); } } }
43c3cf0e758f4ad83a4eaf8d2d9b12d48d993c38
[ "Java" ]
1
Java
PSJmeister/MyWeb01
b941dcd9292d310bd1d9ea0e6e709abf26a301c3
afa928ce4fd76f52b93407eaef962605f8d48b53
refs/heads/master
<file_sep>add_library('minim') import os import random import time path = os.getcwd() + '/' player = Minim(this) cardwidth = 70 cardlength = 100 class Card: def __init__(self, num, r, spade=True, faceup=False, moving=False): self.p = [] # the pile history of the card self.num = num # the order of it in current pile self.r = r # the rank self.spade = spade self.faceup = faceup self.fuh = [] # keep track of face up history self.moving = moving #if it is moving with the mouse self.img = loadImage(path + 'images/back.jpg') def display(self): if not self.moving: image(self.img, 30+(self.p[len(self.p)-1]-1)*(cardwidth+20), 160+self.num*20, cardwidth, cardlength) else: image(self.img, mouseX-cardwidth/2, mouseY-10+self.num*20, cardwidth, cardlength) def flip(self): # traditional flipping cards if not self.faceup: self.img = loadImage(path + 'images/' + str(int(self.spade)) + str(self.r) + '.png') self.faceup = True def cover(self): # in case of undo, sometimes a card needs to be unflipped if self.faceup: self.img = loadImage(path + 'images/back.jpg') self.faceup = False class Deck(list): def __init__(self, spade=True): self.spade = spade # whether of not the deck is all spade cards self.ranks = [] for i in range(13): self.ranks.append(i+1) if self.spade: # all spade cards for i in range(8): for r in self.ranks: self.append(Card(0, r, True, False)) else: # half spade cards, half heart cards for i in range(4): for r in self.ranks: self.append(Card(0, r, True, False)) for i in range(4): for r in self.ranks: self.append(Card(0, r, False, False)) def shuffle_cards(self): random.shuffle(self) class Game: def __init__(self, spade = True, win = False, gameon = False): self.moves = 0 self.win = win self.gameon = gameon # whether or not it is in the menu self.spade = spade # whether the game is easy or hard self.deck = Deck(self.spade) self.deck.shuffle_cards() self.mouselist = [] self.done = [] self.undotimes = 0 self.hinttimes = 0 self.doneimg1 = loadImage(path + 'images/11.png') self.doneimg2 = loadImage(path + 'images/01.png') self.bgimg = loadImage(path + 'images/bg.jpeg') # append each pile self.piles = [] for i in range(1,5): pile = Pile(i) for n in range(6): card = self.deck.pop() card.p.append(i) card.fuh.append(int(card.faceup)) card.num = n pile.append(card) pile[5].flip() pile[5].fuh[0] = 1 self.piles.append(pile) for i in range(5,11): pile = Pile(i) for n in range(5): card = self.deck.pop() card.p.append(i) card.fuh.append(int(card.faceup)) card.num = n pile.append(card) pile[4].flip() pile[4].fuh[0] = 1 self.piles.append(pile) # append each addon self.addons = [] for i in range(5): addon = Addon(i) for n in range(10): addon.append(self.deck.pop()) self.addons.append(addon) def gamestart(self): # the menu fill(255) textSize(60) text('SOLITAIRE', 330, 250) noFill() stroke(200) strokeWeight(2) rect(300, 350, 150, 50) rect(300, 480, 150, 50) textSize(40) text('EASY', 325, 390) text('HARD', 320, 520) textSize(30) text('Record: ', 470, 390) text('Record: ', 470, 520) # read highest record file1 = open(path + 'scoreboard/1.csv', 'r') file2 = open(path + 'scoreboard/2.csv', 'r') record1 = file1.read().split(',') record2 = file2.read().split(',') r1 = 1000 for n in range (1, len(record1)): if int(record1[n]) < r1: r1 = int(record1[n]) r2 = 1000 for n in range (1, len(record2)): if int(record2[n]) < r2: r2 = int(record2[n]) file1.close() file2.close() text(r1, 600, 390) text(r2, 600, 520) def display(self): #highlight strokeWeight(2) stroke(200) rect(30, 30, cardwidth, 30) textSize(26) text('Menu', 31, 56) rect(30, 100, cardwidth, 30) text('Undo', 31, 126) textSize(35) text(self.moves, 660, 93) rect(630, 60, 100, 40) textSize(35) text('Hint', 510, 93) rect(500, 60, 100, 40) # if a pile has no cards, display a rectangle in the card position for i in range(10): if self.piles[i] == []: stroke(200) noFill() strokeWeight(2) rect(30+i*(cardwidth+20), 160, cardwidth, cardlength) # if no done, display a rectangle in the position if self.done == []: rect(120, 30, cardwidth, cardlength) else: cnt = 0 for i in self.done: image(i, 120+cnt*20, 30, cardwidth, cardlength) cnt += 1 # if no more addons, display a rectangle if self.addons == []: rect(840, 30, cardwidth, cardlength) # display all the cards in the piles for pile in self.piles: if len(pile) != 0: for card in pile: card.display() # constantly updating what's following the mouse if self.mouselist != []: for c in self.mouselist: c.display() # display addons for addon in self.addons: addon.display() # highlight cards i = (mouseX-30)//90 if i >= 9: i = 9 elif i == -1: i = 0 if 160 <= mouseY <= 160 + (len(self.piles[i])-1)*20 + 100: if self.piles[i] == []: stroke(0, 0, 100) strokeWeight(3) rect(30+i*(cardwidth+20), 160, cardwidth, cardlength) else: n = min((mouseY-160)//20, len(self.piles[i])-1) stroke(0, 0, 100) strokeWeight(3) rect(30+i*(cardwidth+20), 160+n*20, cardwidth, 20*(len(self.piles[i])-n)+80) # highlight menu button if 30 < mouseX < 100 and 30 < mouseY < 60: noFill() strokeWeight(3) stroke(0, 0, 100) rect(30, 30, cardwidth, 30) # highlight undo button if 30 < mouseX < 100 and 100 < mouseY < 130: noFill() stroke(0, 0, 100) strokeWeight(3) rect(30, 100, 70, 30) # highlight addons if 30 < mouseY < 130 and 910-(len(self.addons)-1)*20-cardwidth < mouseX < 910-(len(self.addons)-1)*20: if self.addons != []: noFill() stroke(0, 0, 100) strokeWeight(3) rect(910-(len(self.addons)-1)*20-cardwidth, 30, 70, 100) # highlight hint button if 500 < mouseX < 600 and 60 < mouseY < 100: noFill() strokeWeight(3) stroke(0, 0, 100) rect(500, 60, 100, 40) def clicked(self): self.checkexit() self.checkundo() self.checkaddon() self.checkhint() def checkexit(self): if 30 < mouseX < 100 and 30 < mouseY < 60: menu.rewind() menu.play() self.gameon = False self.gamestart() def checkundo(self): if 30 < mouseX < 100 and 100 < mouseY < 130: self.undotimes += 1 if self.undotimes != 0 and self.moves != 70 and self.moves != 100 and self.undotimes%5 == 0: undo5.rewind() undo5.play() for pi in self.piles: for c in pi: if len(c.p) == 1: # if the game just starts or an addon is just distributed, no undo return self.moves += 1 self.checkmoves() # whether or not play sound # see which cards changed piles in the last move for pi in self.piles: updatelist = [] for c in pi: if c.p[len(c.p)-1] != c.p[len(c.p)-2]: updatelist.append(c) if updatelist != []: for c in updatelist: target = c.p[len(c.p)-1] home = c.p[len(c.p)-2] self.piles[target-1].remove(c) self.piles[home-1].append(c) break # every card goes back one in pile history for pi in self.piles: cnt = 0 for c in pi: c.p.pop() c.num = cnt cnt += 1 c.fuh.pop() if c.fuh[len(c.fuh)-1] == 0: c.cover() def checkaddon(self): if self.addons != []: if 30 < mouseY < 130 and 910-(len(self.addons)-1)*20-cardwidth < mouseX < 910-(len(self.addons)-1)*20: addon = self.addons[len(self.addons)-1] i = 0 # distribute one card to every pile for c in addon: self.piles[i].append(c) c.p.append(i+1) c.num = len(self.piles[i])-1 c.fuh.append(1) c.flip() i += 1 self.addons.remove(addon) def checkhint(self): if 500 < mouseX < 600 and 60 < mouseY < 100: self.hinttimes += 1 if self.hinttimes != 0 and self.hinttimes%5 == 0: hint5.rewind() hint5.play() #the first priority is to check the empty piles hintlist =[] #for empyty pile for i in range(10): if self.piles[i] == []: hintlist.append(i) if hintlist != []: h = random.choice(hintlist) frameRate(3) stroke(200,0,0) noFill() strokeWeight(3) rect(30+h*(cardwidth+20), 160, cardwidth, cardlength) elif hintlist == []: # find the card to attach to for j in range(10): fpsequence = [] # for the faceup list for every pile for c in self.piles[j]: if c.faceup == True: fpsequence.append(c) checkline = '' checkspade = 0 hintsequence = [] # for cards in order and with same suit, from bottom up hintsequence.append(fpsequence[len(fpsequence)-1]) for c in fpsequence[len(fpsequence)-2::-1]: if c.spade == fpsequence[len(fpsequence)-1].spade and c.r == hintsequence[len(hintsequence)-1].r+1: hintsequence.append(c) else: break # return hintsequence[-1].r+1 # check other piles last for i in range(10): b = False # if we can find a hint, True we double break, False we check addons if self.piles[i][len(self.piles[i])-1].spade == hintsequence[len(hintsequence)-1].spade and self.piles[i][len(self.piles[i])-1].r == hintsequence[len(hintsequence)-1].r+1: frameRate(3) stroke(200,0,0) noFill() strokeWeight(3) rect(30+j*(cardwidth+20), 160+20*(len(self.piles[j])-len(hintsequence)), cardwidth, 20*(len(hintsequence)-1)+100) stroke(50,0,0) rect(30+i*(cardwidth+20), 160+20*(len(self.piles[i])-1), cardwidth, cardlength) b = True break if b: break # check addons if not b and self.addons != []: frameRate(3) stroke(200,0,0) noFill() strokeWeight(3) rect(910-(len(self.addons)-1)*20-cardwidth, 30, cardwidth, cardlength) elif not b and self.addons == []: # no more possible moves, just quit self.hinttimes = 0 nohint.rewind() nohint.play() def pressed(self): # id which pile mouse's at pile = (mouseX-30)//90 if pile == 10: pile = 9 elif pile == -1: pile = 0 home = self.piles[pile] if len(home) != 0 and mouseY >= 160 and mouseY <= 160 + (len(home)-1)*20 + 100: cardn = (mouseY-160)//20 if cardn > len(home)-1: cardn = len(home)-1 sequence = home[cardn:] if home[cardn].faceup: # check if the sequence is in order if self.checkMovable(sequence): # can be moved, move with mouse self.mouselist = [] cnt = 0 for c in sequence: c.moving = True self.mouselist.append(c) c.num = cnt home.remove(c) cnt += 1 def released(self): if self.mouselist != []: # id target pile pile = (mouseX-30)//90 if pile == 10: pile = 9 elif pile == -1: pile = 0 target = self.piles[pile] home = self.piles[self.mouselist[0].p[len(self.mouselist[0].p)-1]-1] if mouseY >= 160 + (len(target)-1)*20 and mouseY <= 160 + (len(target)-1)*20 + 100: if self.checkAcceptable(pile, target): # can accept self.moves += 1 self.checkmoves() # flip the last card from the home pile if home != [] and not home[len(home)-1].faceup: home[len(home)-1].flip() # append cards to target for c in self.mouselist: target.append(c) # relabel cards for n in range(len(target)): target[n].num = n target[n].moving = False for pi in range(1, 11): for c in self.piles[pi-1]: c.p.append(pi) c.fuh.append(int(c.faceup)) # check possible win possiblewin = [] for c in target: if c.faceup: possiblewin.append(c) if len(possiblewin) >= 13: pw = possiblewin[-1:-14:-1] self.win = self.checkwin(target, pw) else: # not acceptable, move back to home for c in self.mouselist: home.append(c) c.moving = False c.num = len(home)-1 else: # release outside the pile zone, move back to home for c in self.mouselist: home.append(c) c.moving = False c.num = len(home)-1 self.mouselist = [] def checkMovable(self, sequence): checkline = '.' checkspade = 0 for c in sequence: checkline += (str(c.r)) checkline += '.' checkspade += int(c.spade) if checkline in '.13.12.11.10.9.8.7.6.5.4.3.2.1.': if checkspade == 0 or checkspade == len(sequence): return True else: return False else: return False def checkAcceptable(self, p, target): if target == []: return True else: if target[len(target)-1].faceup and target[len(target)-1].r - 1 == self.mouselist[0].r: return True else: return False def checkmoves(self): if self.moves == 70: move70.rewind() move70.play() elif self.moves == 100: move100.rewind() move100.play() def checkwin(self, target, pw): checkline = '' checkspade = 0 for c in pw: checkline += (str(c.r)) checkline += '.' checkspade += int(c.spade) if checkline == '1.2.3.4.5.6.7.8.9.10.11.12.13.': if checkspade == 0 or checkspade == 13: # either all spade or all heart for c in pw: target.remove(c) if target != [] and not target[len(target)-1].faceup: target[len(target)-1].flip() if checkspade == 0: # all spade self.done.append(self.doneimg2) else: # all heart self.done.append(self.doneimg1) for pi in range(10): for c in self.piles[pi]: c.fuh.append(int(c.faceup)) c.p = [pi+1] if len(self.done) == 1: win1.rewind() win1.play() elif len(self.done) == 4: win4.rewind() win4.play() elif len(self.done) == 7: win7.rewind() win7.play() elif len(self.done) == 8: winning.rewind() winning.play() # write record if self.spade: file = open(path + 'scoreboard/1.csv', 'a') else: file = open(path + 'scoreboard/2.csv', 'a') file.write(',' + str(self.moves)) file.close() return True else: return False else: return False class Addon(list): # distribute one new card to each pile when clicked def __init__(self, order): self.order = order self.backimg = loadImage(path + 'images/back.jpg') def display(self): image(self.backimg, 910-50-(self.order+1)*20, 30, cardwidth, cardlength) class Pile(list): def __init__(self, order): self.order = order g = Game() easywelcome = player.loadFile(path + 'sounds/easywelcome.mp3') hardwelcome = player.loadFile(path + 'sounds/hardwelcome.mp3') move70 = player.loadFile(path + 'sounds/move70.mp3') move100 = player.loadFile(path + 'sounds/move100.mp3') hint5 = player.loadFile(path + 'sounds/hint5.mp3') nohint = player.loadFile(path + 'sounds/nohint.mp3') menu = player.loadFile(path + 'sounds/menu.mp3') undo5 = player.loadFile(path + 'sounds/undo5.mp3') winning = player.loadFile(path + 'sounds/winning.mp3') win1 = player.loadFile(path + 'sounds/win1.mp3') win4 = player.loadFile(path + 'sounds/win4.mp3') win7 = player.loadFile(path + 'sounds/win7.mp3') def setup(): size(940, 800) background(100) def draw(): frameRate(15) image(g.bgimg, 0, 0) if g.win: textSize(50) text('CONGRATULATIONS!', 250, 300) elif not g.gameon: g.gamestart() else: g.display() def mouseClicked(): if not g.gameon: # menu if 300 < mouseX < 450 and 350 < mouseY < 400: # easy g.__init__(spade = True, win = False, gameon = False) g.gameon = True easywelcome.rewind() easywelcome.play() g.display() elif 300 < mouseX < 450 and 480 < mouseY < 530: # hard g.__init__(spade = False, win = False, gameon = False) g.gameon = True hardwelcome.rewind() hardwelcome.play() g.display() elif g.gameon and not g.win: g.clicked() elif g.win: time.sleep(7) g.win = False g.gameon = False g.gamestart() def mousePressed(): if g.gameon and not g.win: g.pressed() def mouseReleased(): if g.gameon and not g.win: g.released() <file_sep># Final-Project This is a joint work with <NAME> for our final CS project. We create a Spider Solitaire card game written in Python. To run this game, Processing is required. A simple game tutorial can be found here: https://www.wikihow.com/Play-Solitaire. One can access the code by cloning the git repo with the following code: git clone https://github.com/weihang-he/Final-Project.git. The purpose of the project is to design the classic spider solitaire. The game is expected to include to two mode of “easy” and “hard”, which allow the players to choose the number of card suits. A hint button, an undo button, a board that records the number of moves, and a record board of the best result are also included. The game is written in Python and can be run with Processing. We have incorporated the class functions and basic game logic. To make the game more personal, we specifically record voices and use as sound effect. * Note: Due to naming error, the Final-Project.pyde does not contain the actual code. Please run the Solitaire.pyde instead. Below is an image of the acutal game when running: <img width="924" alt="gameplay" src="https://user-images.githubusercontent.com/45058646/50028421-18113f80-0009-11e9-98ec-64dc8fd4c69f.png"> <file_sep># move freely # time steps # drag and drop (wrong position go back) # sound effect # add creepy voices asking 'wanna continue? 100 moves already' # undo # exit and start a new game # winning screen # how cards are displayed first import os import random path = os.getcwd() + '/' cardwidth = 80 cardlength = 100 class Card: def __init__(self,v,x,y,spade=True,faceup=False): self.v=v self.x=x self.y=y self.spade = spade self.faceup=faceup #display class Deck: def __init__(self, spade=True): self.deck=[] self.suits=['spades','hearts'] self.ranks=[] for i in range(13): self.rankes.append(i+1) #if spade: # for i in range(8): # #else: # for i in range(4): # def shuffle_cards(self): random.shuffle(self.deck) def load_cards(self): for suit in self.suits: for rank in self.ranks: self.card_images[img] = pygame.image.load(img) self.cards.append(Card(img,suit)) self.cards.append(Card(name_of_image,self.x,self.y,suit)) class Game: def __init__(self, spade = True, win = False): self.moves = 0 self.win = win self.spade = spade self.deck = Deck(self.spade) self.deck.shuffle_cards() self.piles = [] for i in range(4): pile = [] for n in range(6): pile.append(self.deck.pop()) piles.append(pile) for i in range(6): pile = [] for n in range(5): pile.append(self.deck.pop()) piles.append(pile) self.addons = [] for i in range(5): addon = [] for n in range(10): addon.append(self.deck.pop()) self.addons.append(addon) def display(self,): pass def clicked(self): x = mouseX y = mouseY # identify which pile # return home & target home = piles[x//#width of cards + space between piles] self.win = self.check_exit() if not self.win: undo = self.check_undo() if undo: self.un_do(card, home, target) card = checkValidMoves(card) #check if the first displayed in home is facedown: #faceup self.moves += 1 def checkValidMoves(self,card,target): #select cards --> # run a for loop from the top card #check if valid for card in sequence=[] sequence.append(card.v) for i in range(len(sequence)): checkvalid = ''.join(sequence[i]) if checkvalid in '13121110987654321': return True #if empty: #accept it elif: if card.v+1 == target[len(target)-1].v: target.append(sequence) def check_exit(self): x = mouseX y = mouseY if # x of exit button < x < buttonx + width and y return True def check_undo(self): x = mouseX y = mouseY if # x of exit button < x < buttonx + width and y return True def un_do(self, home, target): #draw the sequence back def check_win(): # class Addon: def __init__(self,#): #50 cards into 5 groups #display each group one at a time def clicked(): for card in self.cards: #distribute to all piles class Pile(list): def __init__(self, cards, x, y, card_size, pile_type="line"): # complete!!! self.cardwitdh,self.cardlength = card_size def update(self, piles_to_update): for pile in self.piles: pile.update() if piles_to_update != None: for pile in piles_to_update: pile.update_positions() def setup(): def draw(): #if player choose easy: g = Game(True,False) else: g = Game(False,False) g.display() def mouseClicked(): if not g.win(): g.clicked()
006abe8284bb7b14638ed007543cf2eb01f6e1ab
[ "Markdown", "Python" ]
3
Python
weihang-he/Final-Project
b6bd5882c81320a25515b7a3982e4f7477fa768c
2bd053d315c2142b965757188360be9f95acf67e
refs/heads/master
<repo_name>nanshan-high-school/cs50-problem-set-1-credit-Vincent-2019<file_sep>/credit.cpp #include <iostream> using namespace std ; int main() { long long num; cout << "請輸入卡號"; cin >> num; int str1 = num/10000000000000; int str2 = num/100000000000000; int str3 = num/1000000000000000; int str4 = num/1000000000000; if(str1 == 34 || str1 == 37){ cout<<"American Express"; }else if (str2 == 51||str2 == 52||str2 == 53||str2 == 54||str2 == 55) { cout<<"MasterCard"; }else if (str3 == 4||str4 == 4){ cout<<"Visa"; }else{ cout<<"無效"; } }
82a9dc2c71b124fd2e4d44e4476981e76c587708
[ "C++" ]
1
C++
nanshan-high-school/cs50-problem-set-1-credit-Vincent-2019
87049c0c2fe7c766e0dce1c00e93689135c43ca2
6b2b85d2229f87b93ca14da74ee069d89edcb780
refs/heads/master
<repo_name>vBjerre/eolive-sanity<file_sep>/schemas/schema.js // In the file schemas/schema.js import createSchema from 'part:@sanity/base/schema-creator' import schemaTypes from 'all:part:@sanity/base/schema-type' import header from './header.js' export default createSchema({ name: 'eoliveSchema', types: schemaTypes.concat([ header ]) })
5c8632480a698e3b0cb7cef6496100d47236f91c
[ "JavaScript" ]
1
JavaScript
vBjerre/eolive-sanity
122fe848a952de36129655208a0210bed40d068b
0bfddb12cc8b42af97c24eaa0f587e0418671267
refs/heads/master
<file_sep>package view; import javafx.fxml.FXML; import javafx.scene.effect.GaussianBlur; import javafx.scene.image.ImageView; import javafx.scene.shape.Circle; import javafx.scene.shape.Ellipse; public class BlurController { @FXML private ImageView imageView; private Ellipse ellipse; //recorte @FXML public void setclip() { ellipse = new Ellipse(); //para modificar la forma cambiar el valor del radio, en mi caso todo es 65 para que sea un circulo ellipse.centerXProperty().setValue(195); ellipse.centerYProperty().setValue(65); ellipse.radiusXProperty().setValue(65); ellipse.radiusYProperty().setValue(65); imageView.setClip(ellipse); } //borrroso @FXML public void setblur() { imageView.setEffect(new GaussianBlur(10)); } //cerrar @FXML public void hundlerClose() { System.exit(0); } } <file_sep>package application; import javafx.application.Application; import javafx.stage.Stage; import javafx.scene.Scene; import javafx.scene.layout.AnchorPane; import javafx.scene.layout.BorderPane; import javafx.application.Application; import javafx.fxml.*; import javafx.scene.*; import javafx.scene.effect.DropShadow; import javafx.scene.effect.GaussianBlur; import javafx.scene.image.*; import javafx.scene.layout.Pane; import javafx.scene.paint.Color; import javafx.scene.shape.Circle; import javafx.scene.shape.Ellipse; import javafx.scene.shape.Rectangle; import javafx.stage.Stage; import java.io.IOException; public class Main extends Application { private Pane mypane; @Override public void start(Stage stage) throws IOException { FXMLLoader loader = new FXMLLoader( getClass().getResource( "../view/forest.fxml" ) ); mypane = (Pane) loader.load(); stage.setTitle("The forest"); stage.setScene(new Scene(mypane)); stage.show(); } public static void main(String[] args) { launch(args); } }
16979aae84133752d8991400c2b29286294c63c8
[ "Java" ]
2
Java
elena240397/BASICJFXElena
374c168c6dd1b6504e592b6d0140b74e27dd20ea
801755745e929608601d3d8a02017d7c5f9cef35
refs/heads/master
<file_sep># This file should contain all the record creation needed to seed the database with its default values. # The data can then be loaded with the rake db:seed (or created alongside the db with db:setup). # # Examples: # # cities = City.create([{ name: 'Chicago' }, { name: 'Copenhagen' }]) # Mayor.create(name: 'Emanuel', city: cities.first) ActiveRecord::Base.transaction do User.destroy_all Band.destroy_all Track.destroy_all Album.destroy_all 5.times do u = User.create!(email: Faker::Internet.email, password: "<PASSWORD>") b = Band.create!(name: Faker::Book.title) 5.times do a = Album.create!( name: Faker::Hipster.sentence(3), album_type: ["Studio", "Live"].sample, band_id: b.id ) 8.times do Track.create!( title: Faker::Hacker.noun, album_id: a.id, track_type: ["Bonus", "Regular"].sample ) end end end end <file_sep>class ChangeBandsColumn < ActiveRecord::Migration def change rename_column :albums, :artist_id, :band_id end end <file_sep># == Schema Information # # Table name: tracks # # id :integer not null, primary key # album_id :integer not null # title :string # track_type :string # lyrics :text # class Track < ActiveRecord::Base TRACK_TYPES = %w(Regular Bonus) validates :album_id, :title, presence: :true validates :track_type, inclusion: TRACK_TYPES belongs_to :album has_one :band, through: :album, source: :band end
5caf98d6433370710172d43fd26646aef4d30547
[ "Ruby" ]
3
Ruby
mvodkin/w4d4
26172a35aa933866dfe87f9679c87b6dc9053798
cbac924a85810650cef2e0b3abdfc46271990d32
refs/heads/master
<file_sep>def fetch_resources(request): #@author: eyuep.alikilic - artefact Germany #@info: LW-Preload-List-Fetcher 21.06.2019 from flask import escape import requests import re import json request_json = request.get_json(silent=True) request_args = request.args if request_json and 'domain' in request_json: mainURL = request_json['domain'] elif request_args and 'domain' in request_args: mainURL = request_args['domain'] else: return json.dumps("No domain found") r = requests.get(mainURL) fullsource = r.text caturl = re.findall('id="nav-level0-copy"><ul[^>]*>.*?href="(.*?)"',fullsource) r = requests.get(caturl[0]) cat_fullsource = r.text produrl = re.findall('class=\"products-grid\">.*?<a href=\"(.*?)\"',cat_fullsource) r = requests.get(produrl[0]) prod_fullsource = r.text ruleCSS ='href=\"('+mainURL+'\/media\/css_secure\/.*?css.*?)\"' ruleJS = 'src=\"('+mainURL+'\/media\/js\/.*?.js.*?)\"' catCSS = re.findall(ruleCSS,cat_fullsource) catJS = re.findall(ruleJS,cat_fullsource) catRes=catJS catRes.extend(catCSS) prodCSS = re.findall(ruleCSS,prod_fullsource) prodJS = re.findall(ruleJS,prod_fullsource) prodRes=prodJS prodRes.extend(prodCSS) homeCSS = re.findall(ruleCSS,fullsource) homeJS = re.findall(ruleJS,fullsource) homeRes = homeJS homeRes.extend(homeCSS) res = catRes res.extend(prodRes) res.extend(homeRes) res = list(set(res)) base= re.findall('https:\/\/www.*..\.(.*)',mainURL) upload_blob("quicklink-resource-lists",json.dumps(res),"ql-res-list-"+base[0]+".json") def upload_blob(bucket_name, source_file_name, destination_blob_name): """Uploads a file to the bucket.""" from google.cloud import storage storage_client = storage.Client() bucket = storage_client.get_bucket(bucket_name) blob = bucket.blob(destination_blob_name) blob.upload_from_string(source_file_name,content_type='application/json') print('File {} uploaded to {}.'.format( source_file_name, destination_blob_name)) <file_sep># quicklink-cloud-functions Google Cloud Function for getting url list of critical files for loading in Quicklink.js Creates a cloud function in python which fetches the critical files of future navigations (example JS and CSS) into a list. This list can be passed as an arg to the quicklink.js library Example: You need every critical CSS and JS File of landing page , category page(PLP) and product page(PDP) in a list. Why? Because you need to specify a list of urls which should be prefetched with the quicklink.js (Of course you can use the elements) This is only for static urls. Example of quicklink.js + cloud function: follows, Live example of production environment: www.lights.ie <file_sep><script async defer src="https://unpkg.com/quicklink@1.0.0/dist/quicklink.umd.js"></script> <script language="javascript"> window.addEventListener('load', () =>{ let host = window.location.origin; let regex = new RegExp("https:\/\/www.+..\.(..)"); let base = regex.exec(host); let storageurl = "//storage.googleapis.com/quicklink-resource-lists/ql-res-list-"+base[1]+".json"; let reslist; fetch(storageurl,{credentials:'same-origin'}) .then(res => res.json()) .then((out) => { quicklink({urls:out}); }) .catch(err => { throw err }); }); </script>
7dfe5436e1208de18d1eacc061086927952e9a24
[ "Markdown", "Python", "JavaScript" ]
3
Python
ealikilic/quicklink-cloud-functions
d2b36459d54ab691c03a155b9f6e779c4a742d4a
895974fd97c735bb3342c4a8a243bde6bad33cf4
refs/heads/master
<file_sep><?php namespace PHPQuad; use \PHPQuad\Exception\RestError; use \PHPQuad\Core\DebuggingTrait; use \PHPQuad\REST\RestInterface; use \PHPQuad\REST\HttpTrait; use \PHPQuad\REST\InputTrait; use \PHPQuad\REST\OutputTrait; use \PHPQuad\REST\RequestTrait; class REST implements RestInterface { protected $debugging; public $request; public $input; public $output; use DebuggingTrait; use HttpTrait; use InputTrait; use OutputTrait; use RequestTrait; public function __construct() { if(getenv("PQ_DEBUGGING")) $this->debugging = true; $httpMethod = (isset($_SERVER["REQUEST_METHOD"])) ? strtoupper($_SERVER["REQUEST_METHOD"]) : ""; if(!in_array($httpMethod, ["GET","POST","PUT","DELETE"])) { $this->debugWarning(self::HTTP_REQUEST_ERROR); } else { $this->input = (object) ["format" => null, "method" => $httpMethod, "query" => $_GET, "data" => $_GET]; $this->getInput(); $this->output = (object) ["format" => $this->input->format]; if(isset($this->input->data["_format"]) && is_string($this->input->data["_format"])) { $this->output->format = strtolower($this->input->data["_format"]); } else { if(!empty($_SERVER["HTTP_ACCEPT"])) { $httpAccept = str_getcsv($_SERVER["HTTP_ACCEPT"]); $httpAccept = explode("/", $httpAccept[0]); $this->output->format = trim($httpAccept[1]); } } } if(isset($_SERVER["REQUEST_URI"])) { $this->request = array_map("urldecode", explode("/", ltrim(explode("?", $_SERVER["REQUEST_URI"])[0], "/"))); } } public function __toString() { return __CLASS__; } public function isREST() { return (isset($this->input->method)) ? true : false; } private function getInput() { $contentType = (isset($_SERVER["CONTENT_TYPE"])) ? $_SERVER["CONTENT_TYPE"] : null; $contentType = explode(";", $contentType)[0]; if($this->isREST() && isset($contentType)) { if(!in_array($this->input->method, ["PUT","DELETE"]) && in_array($contentType, ["application/x-www-form-urlencoded","multipart/form-data"])) { $this->input->format = "html"; $this->input->data = array_merge($this->input->data, $_POST); } else { $inputBody = file_get_contents("php://input"); if($inputBody !== false) { if($contentType == "application/json") { $this->input->format = "json"; $jsonData = @json_decode($inputBody, true); if(is_array($jsonData)) { foreach($jsonData as $key => $value) { $this->input->data[$key] = $value; } } } else if($contentType == "application/x-www-form-urlencoded") { $this->input->format = "html"; $formData = []; parse_str($inputBody, $formData); foreach($formData as $key => $value) { $this->input->data[$key] = $value; } } else { $inputData = []; parse_str($inputBody, $inputData); foreach($inputData as $key => $value) { $this->input->data[$key] = $value; } } } } } if(!isset($this->input->format)) $this->input->format = "text"; } }<file_sep><?php namespace PHPQuad\Database; trait PaginationTrait { public function paginate() { $this->queryBuilder->selectLock = false; $selectStart = (is_int($this->queryBuilder->selectStart)) ? $this->queryBuilder->selectStart : 0; $selectLimit = (is_int($this->queryBuilder->selectLimit)) ? $this->queryBuilder->selectLimit : 100; $selectTable = $this->queryBuilder->tableName; $selectColumns = $this->queryBuilder->selectColumns; $selectOrder = $this->queryBuilder->selectOrder; $whereClause = $this->queryBuilder->whereClause; $whereData = $this->queryBuilder->queryData; $this->queryBuilder->selectStart = null; $this->queryBuilder->selectLimit = null; $this->queryBuilder->selectColumns = "count(*)"; $paginated = new Paginated($selectStart, $selectLimit); $totalRows = $this->fetchFirst(); if(is_array($totalRows) && isset($totalRows["count(*)"])) { $totalRows = (int) $totalRows["count(*)"]; } if($totalRows > 0) { $paginated->totalRows = $totalRows; $paginated->totalPages = ceil($totalRows/$selectLimit); $this->queryBuilder->selectStart = $selectStart; $this->queryBuilder->selectLimit = $selectLimit; $this->queryBuilder->tableName = $selectTable; $this->queryBuilder->selectColumns = $selectColumns; $this->queryBuilder->selectOrder = $selectOrder; $this->queryBuilder->whereClause = $whereClause; $this->queryBuilder->queryData = $whereData; $rows = $this->fetchAll(); if(is_array($rows)) { $paginated->rows = $rows; $paginated->count = count($rows); } for($i=0;$i<$paginated->totalPages;$i++) { $paginated->pages[] = ["index" => $i+1, "start" => $i*$selectLimit]; } } return $paginated; } }<file_sep><?php namespace PHPQuad\Core; trait ExceptionTrait { public function shutDown() { \PHPQuad::shutDown($this->getMessage(), $this->getFile(), $this->getLine()); } }<file_sep><?php namespace PHPQuad\Security; abstract class AbstractSecurity { public function flush() { if(isset($_SESSION["PHPQuad"]) && isset($_SESSION["PHPQuad"]["Security"])) $_SESSION["PHPQuad"]["Security"] = []; } }<file_sep><?php use \PHPQuad\Core\Constants; use \PHPQuad\Core\Screen; use \PHPQuad\Core\ErrorHandler; use \PHPQuad\Core\DateTime; class PHPQuad implements Constants { public $dateTime; public $errorHandler; protected $domain; protected $debugging; protected $timeStamp; protected $session; public function __construct(array $options = null) { if(!is_array($options)) $options = []; $this->debugging = (array_key_exists("tbknk", $options) && $options["tbknk"] == true) ? true : false; $this->errorHandler = new ErrorHandler($options, $this->debugging); $this->dateTime = new DateTime((array_key_exists("tmsn", $options)) ? $options["tmsn"] : null); $this->domain = (!empty($_SERVER["HTTP_HOST"])) ? str_ireplace("www.", "", $_SERVER["HTTP_HOST"]) : null; $this->timeStamp = microtime(true); $this->session = false; if(session_id() !== "") { $this->session = true; if(!isset($_SESSION["PHPQuad"]) || !is_array($_SESSION["PHPQuad"])) { $_SESSION["PHPQuad"] = []; } } if($this->debugging === true) { putenv("PQ_DEBUGGING=1"); if(array_key_exists("tbknkbtoff", $options) && $this->intRange(intval($options["tbknkbtoff"]), 1, 10)) { putenv("PQ_DEBUG_BKTRC_OFST=" . intval($options["tbknkbtoff"])); } } } public function __toString() { return __CLASS__; } public function info($key = null) { $info = ["version" => self::VERSION]; $info["timeZone"] = $this->dateTime->getTimeZone(); foreach(["timeStamp","debugging","domain"] as $field) { $info[$field] = $this->$field; } if(is_string($key)) { return array_key_exists($key, $info) ? $info[$key] : null; } return $info; } public static function availablePlugins() { $plugins = []; foreach(glob(__DIR__ . "/PHPQuad/Plugins/*.php") as $plugin) { $plugins[] = sprintf("\PHPQuad\Plugins\%s", basename($plugin, ".php")); } return $plugins; } public static function shutDown($message = null, $file = null, $line = 0) { $screen = new Screen((string) $message, $file, $line); $screen->shutDown(); exit; } public static function stringClean($string) { return strip_tags($string); } public static function stringFormat($string, $filters = "adsq", $spaces = true, $whitelist = null) { if(!is_string($string)) return null; $pattern = ""; if(is_string($filters) && !empty($filters)) { $filters = strtolower($filters); for($i=0;$i<strlen($filters);$i++) { switch($filters{$i}) { case "a": $pattern .= "a-zA-Z"; break; case "u": $pattern .= "A-Z"; break; case "l": $pattern .= "a-z"; break; case "n": $pattern .= "0-9"; break; case "d": $pattern .= "0-9\."; break; case "s": $pattern .= preg_quote("!@#$%^&*()+=-[];,./_{}|:<>?~\\", "#"); break; case "q": $pattern .= preg_quote("\"'"); break; } } } if(empty($pattern)) $pattern = "a-zA-Z0-9\."; if(is_string($whitelist) && !empty($whitelist)) $pattern .= preg_quote($whitelist, "#"); if($spaces === true) $pattern .= " "; return trim(preg_replace(sprintf("#[^%s]+#", $pattern), "", $string)); } public static function evaluate($string, $extras = null) { if(is_bool($string)) return $string; $acceptable = ["true",1,"1","on","yes","enable"]; if(is_array($extras)) $acceptable = array_merge($acceptable, array_map("strtolower", $extras)); return in_array(strtolower($string), $acceptable); } public static function intRange($int, $from = 0, $to = 0) { if(is_int($int) && is_int($from) && is_int($to)) { return ($int >= $from && $int <= $to) ? true : false; } return false; } public static function random($digits = 12) { $digits = (int) $digits; $charset = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890"; $random = ""; for($i=0;$i<$digits;$i++) { $random .= $charset{rand(0,61)}; } return $random; } }<file_sep><?php namespace PHPQuad\Core; abstract class AbstractPlugin { public function pluginVersion() { return $this::VERSION; } public function pluginAuthor() { return $this::AUTHOR; } }<file_sep><?php namespace PHPQuad\i18n; interface i18nInterface { const BOOT_ERROR = "i18n could not be instantiated"; public function setLanguagesPath($path); public function languageExists($name); public function language($name); public function bindLanguage(\PHPQuad\i18n\Language $lang); public function boundLanguage(); }<file_sep><?php function __($key, $object = null) { if(is_string($key) && $key !== "") { if(is_object($object) && $object instanceof \PHPQuad\i18n\Language) { return $object->get($key); } else { global $PHPQUAD_BOUND_LANGUAGE; if(is_object($PHPQUAD_BOUND_LANGUAGE) && $PHPQUAD_BOUND_LANGUAGE instanceof \PHPQuad\i18n\Language) { return $PHPQUAD_BOUND_LANGUAGE->get($key); } } } return false; }<file_sep><?php namespace PHPQuad\REST; trait HttpTrait { public function httpRedirect($path) { header("Location: " . $path); } public function httpResponseCode($code = 200) { http_response_code((int) $code); } }<file_sep># PHPQuad Framework PHP Framework <file_sep><?php namespace PHPQuad\TemplateEngine; use \PHPQuad\Exception\TemplateError; trait CompileTrait { private function compile($tpl) { if(!isset($this->templatePath)) throw new TemplateError("Template files path is not defined"); if(!isset($this->compilePath)) throw new TemplateError("Compiling path is not defined"); $timerStart = microtime(true); $tplContents = $this->read($tpl); if(!$tplContents) { if(isset($this->error)) throw new TemplateError($this->error); return false; } else { $tplContents = $this->parse($tplContents, $tpl); if($tplContents) { $compile = sprintf("%s_%d.php", md5(microtime(false)), rand(1,100)); $compiler = @fopen($this->compilePath . $compile, "w"); if(is_resource($compiler)) { if(@fwrite($compiler, $tplContents) > 0) { @fclose($compiler); $timer_end = microtime(true); $this->updateTimer(($timer_end-$timerStart)); @ob_start(); include_once($this->compilePath . $compile); $compiled = @ob_get_contents(); @ob_end_clean(); $flush = @unlink($this->compilePath . $compile); if(!$flush) $this->debugWarning("Failed to flush a compiled template file"); return $compiled; } else { throw new TemplateError("Failed to write compiled template file"); } } else { throw new TemplateError("Failed to open resource for compiled template"); } } else { throw new TemplateError((isset($this->error)) ? $this->error : sprintf('Template file "%s%s" parsing error', $this->templatePath, $tpl)); } } return false; } }<file_sep><?php namespace PHPQuad\REST; trait RequestTrait { public function requestRoot() { return str_repeat("../", count((array) $this->request)); } public function requestFormat() { return $this->inputFormat(); } public function requestMethod($index = 0) { return (isset($this->request[$index]) && is_string($this->request[$index])) ? strtolower($this->input->method) . ucwords(strtolower($this->request[$index])) : false; } }<file_sep><?php namespace PHPQuad\Database; use \PHPQuad\Exception\DatabaseError; abstract class AbstractPdoMethods { public function __construct($dsn, $user = null, $pass = null, $options) { try { $this->pdo = @new \PDO($dsn, $user, $pass, $options); } catch (\PDOException $e) { throw new DatabaseError($e->getMessage(), 104); } } public function pdoSetAttribute($attr, $val) { try { return $this->pdo->setAttribute($attr, $val); } catch(\PDOException $e) { throw new DatabaseError($e->getMessage(), 105); } } public function pdoGetAttribute($attr) { try { return $this->pdo->getAttribute($attr); } catch(\PDOException $e) { throw new DatabaseError($e->getMessage(), 106); } } public function lastInsertId($col = null) { return $this->pdo->lastInsertId($col); } public function beginTransaction() { try { return $this->pdo->beginTransaction(); } catch(\PDOException $e) { $this->errors[] = $e->getMessage(); if($this->throwException) { throw new DatabaseError($e->getMessage(), 107); } else { $this->debugNotice($e->getMessage()); return false; } } } public function checkTransaction() { try { return $this->pdo->inTransaction(); } catch(\PDOException $e) { $this->errors[] = $e->getMessage(); if($this->throwException) { throw new DatabaseError($e->getMessage(), 108); } else { $this->debugNotice($e->getMessage()); return false; } } } public function commit() { try { return $this->pdo->commit(); } catch(\PDOException $e) { $this->errors[] = $e->getMessage(); if($this->throwException) { throw new DatabaseError($e->getMessage(), 109); } else { $this->debugNotice($e->getMessage()); return false; } } } public function commitTransaction() { return $this->commit(); } public function rollBack() { try { return $this->pdo->rollBack(); } catch(\PDOException $e) { $this->errors[] = $e->getMessage(); if($this->throwException) { throw new DatabaseError($e->getMessage(), 110); } else { $this->debugNotice($e->getMessage()); return false; } } } public function cancelTransaction() { return $this->rollBack(); } public function bindValueType($mixed) { $value_type = gettype($mixed); switch($value_type) { case "boolean": $type = \PDO::PARAM_BOOL; break; case "integer": $type = \PDO::PARAM_INT; break; case "NULL": $type = \PDO::PARAM_NULL; break; default: $type = \PDO::PARAM_STR; break; } return $type; } public function query($query, $data = null, $fetch = null) { if(!is_array($data)) { if($data !== null) { $this->debugWarning("Second argument must be an Array or NULL"); } $data = []; } try { $this->resetQuery(); $this->queryBuilder->resetQuery(); $stmnt = $this->pdo->prepare($query); $this->lastQuery->query = $stmnt->queryString; foreach((array) $data as $key => $value) { if(is_int($key)) $key++; $stmnt->bindValue($key, $value, $this->bindValueType($value)); } $exec = $stmnt->execute(); if($exec === true && $stmnt->errorCode() === "00000") { $this->lastQuery->rows = (int) $stmnt->rowCount(); if($fetch === 1112) { $result = $stmnt->fetchAll(\PDO::FETCH_ASSOC); if(is_array($result)) { if($this->config->fetchCount === 11002) { $this->lastQuery->rows = count($result); } else { $this->lastQuery->rows = (int) $stmnt->rowCount(); } return $result; } else { return false; } } else { return true; } } else { $error = $stmnt->errorInfo(); $this->lastQuery->error = sprintf("[%s-%s] %s", $error[0], $error[1], $error[2]); $this->errors[] = $this->lastQuery->error; if($this->throwException) { throw new DatabaseError($this->lastQuery->error, 112); } else { $this->debugWarning($this->lastQuery->error); } } } catch(\PDOException $e) { $this->lastQuery->error = $e->getMessage(); $this->errors[] = $e->getMessage(); if($this->throwException) { throw new DatabaseError($e->getMessage(), 111); } else { $this->debugWarning($e->getMessage()); } } return false; } }<file_sep><?php namespace PHPQuad\TemplateEngine\Modifiers; class Date { public function apply($parsed, $arguments = null) { if(!is_array($arguments)) $arguments = []; $format = (isset($arguments[0]) && is_string($arguments[0])) ? $arguments[0] : "d-M-Y h:i A"; return sprintf("date('%s', %s)", $format, $parsed); } }<file_sep><?php namespace PHPQuad\TemplateEngine\Modifiers; class Translate { public function apply($parsed, $arguments = null) { if(function_exists("\__")) { if(is_array($arguments) && isset($arguments[0])) { if(is_string($arguments[0]) && !empty($arguments[0])) return ($arguments[0]{0} == "$") ? sprintf("__(%s)", $arguments[0]) : sprintf("__('%s')", $arguments[0]); } else { return sprintf("__(%s)", $parsed); } } return $parsed; } }<file_sep><?php namespace PHPQuad\TemplateEngine; use \PHPQuad\Exception\TemplateError; trait DisplayTrait { public function prepare($tpl, $cache = 0) { $cached_name = null; if($cache > 0 && $cache <= PHP_INT_MAX) { if(isset($this->cachePath)) { $cached_name = $this->cachePath . sprintf("%s_%s.html", md5($tpl), @session_id()); $cache_timer_start = microtime(true); $cached = $this->cacheHandler->read($cached_name, $cache); $cache_timer_end = microtime(true); if($cached !== false && is_string($cached)) { $cached_name = null; $this->updateTimer(($cache_timer_end-$cache_timer_start)); return $cached; } } else { throw new TemplateError("Cache path is not set"); } } $compiled = $this->compile($tpl); if(isset($cached_name) && $compiled !== false) { $this->cacheHandler->write($cached_name, $compiled); } return $compiled; } public function display($tpl, $cache = 0) { print $this->prepare($tpl, $cache); } }<file_sep><?php namespace PHPQuad\Exception; class DateTimeError extends \PHPQuadException { }<file_sep><?php namespace PHPQuad\TemplateEngine\Modifiers; class Capitalize { public function apply($parsed, $arguments = null) { if(isset($arguments[0])) { if(filter_var($arguments[0], FILTER_VALIDATE_BOOLEAN)) { return sprintf("ucwords(%s)", $parsed); } } return sprintf("ucfirst(%s)", $parsed); } }<file_sep><?php namespace PHPQuad\TemplateEngine\Modifiers; class Urldecode { public function apply($parsed, $arguments = null) { return sprintf("urldecode(%s)", $parsed); } }<file_sep><?php class PHPQuadException extends \Exception { use \PHPQuad\Core\ExceptionTrait; }<file_sep><?php namespace PHPQuad\Security; use \PHPQuadException; use \PHPQuad\Exception\SecurityError; use \PHPQuad\Core\DebuggingTrait; class Form { protected $debugging; protected $name; protected $reaffirmKeys; use DebuggingTrait; public function __construct($name) { if(getenv("PQ_DEBUGGING")) $this->debugging = true; if(is_string($name) && $name !== "") { $this->name = $name; $this->reaffirmKeys = false; $this->prepareSessionVar(); } else { throw new SecurityError("Form name must be a String", 100); } } public function __toString() { return __CLASS__; } public function reaffirmKeys() { $this->reaffirmKeys = true; return $this; } private function prepareSessionVar() { if(session_id() !== "") { if(!isset($_SESSION["PHPQuad"]) || !is_array($_SESSION["PHPQuad"])) $_SESSION["PHPQuad"] = []; if(!isset($_SESSION["PHPQuad"]["Security"]) || !is_array($_SESSION["PHPQuad"]["Security"])) $_SESSION["PHPQuad"]["Security"] = []; if(!isset($_SESSION["PHPQuad"]["Security"]["Forms"]) || !is_array($_SESSION["PHPQuad"]["Security"]["Forms"])) $_SESSION["PHPQuad"]["Security"]["Forms"] = []; if(!isset($_SESSION["PHPQuad"]["Security"]["Forms"][$this->name]) || !is_array($_SESSION["PHPQuad"]["Security"]["Forms"][$this->name])) $_SESSION["PHPQuad"]["Security"]["Forms"][$this->name] = []; return true; } else { $this->debugWarning("Session is not available"); } return false; } public function set() { $obfuscated = []; if(func_num_args() > 0) { $fields = func_get_args(); foreach($fields as $field) { if(is_string($field) && !empty($field)) { if($this->reaffirmKeys === true) { while(true) { $random = \PHPQuad::random(12); if(!array_key_exists($random, $obfuscated)) break; } } else { $random = \PHPQuad::random(12); } $obfuscated[$field] = $random; } } if($this->prepareSessionVar()) $_SESSION["PHPQuad"]["Security"]["Forms"][$this->name] = $obfuscated; } else { $this->debugWarning("Expects at least one field name"); } return $obfuscated; } public function get() { if($this->prepareSessionVar()) { return (count($_SESSION["PHPQuad"]["Security"]["Forms"][$this->name]) > 0) ? $_SESSION["PHPQuad"]["Security"]["Forms"][$this->name] : false; } } public function flush() { if($this->prepareSessionVar()) unset($_SESSION["PHPQuad"]["Security"]["Forms"][$this->name]); } }<file_sep><?php namespace PHPQuad; use \PHPQuad\Exception\DatabaseError; use \PHPQuad\Core\DebuggingTrait; use \PHPQuad\DataObject; use \PHPQuad\Database\AbstractPdoMethods; use \PHPQuad\Database\DatabaseInterface; use \PHPQuad\Database\DatabaseTrait; use \PHPQuad\Database\QueryBuilder; use \PHPQuad\Database\QueryBuilderTrait; use \PHPQuad\Database\Paginated; use \PHPQuad\Database\PaginationTrait; class Database extends AbstractPdoMethods implements DatabaseInterface { protected $pdo; protected $config; protected $errors; protected $queryBuilder; protected $debugging; protected $throwException; public $lastQuery; use DebuggingTrait; use DatabaseTrait; use QueryBuilderTrait; use PaginationTrait; public function __construct($driver, $database, $host = "localhost", $user = null, $pass = <PASSWORD>, $persistent = 0) { $this->queryBuilder = new QueryBuilder; $this->errors = []; $this->throwException = false; $this->config = new \stdClass; $this->config->persistent = false; $this->config->driver = null; $this->config->fetchCount = \PHPQuad::DB_FETCH_COUNT_DEFAULT; if($driver === 1101) { $pdo_driver = "mysql"; $dsn = sprintf("mysql:host=%s;dbname=%s", $host, $database); } else if($driver === 1102) { $pdo_driver = "sqlite"; $dsn = sprintf("sqlite:%s", $database); } else if($driver === 1103) { $pdo_driver = "pgsql"; $dsn = sprintf("pgsql:host=%s;dbname=%s", $host, $database); } if(class_exists("\PDO")) { if(isset($pdo_driver, $dsn)) { if(in_array($pdo_driver, \PDO::getAvailableDrivers())) { $options = [\PDO::ATTR_ERRMODE => \PDO::ERRMODE_EXCEPTION]; if($persistent === 1111) { $options[\PDO::ATTR_PERSISTENT] = true; $this->config->persistent = true; } parent::__construct($dsn, $user, $pass, $options); $this->config->driver = $pdo_driver; $this->resetQuery(); if(getenv("PQ_DEBUGGING")) $this->debugging = true; } else { throw new DatabaseError(sprintf('"%s" is not available as PDO database driver', $pdo_driver), 103); } } else { throw new DatabaseError("Unacceptable database driver", 102); } } else { throw new DatabaseError("Requires PDO extension", 101); } } public function __toString() { return __CLASS__; } public function setFlag($flag) { switch($flag) { case 11001: $this->config->fetchCount = 11001; break; case 11002: $this->config->fetchCount = 11002; break; case 11003: $this->config->fetchCount = 11003; break; } } public function insert($data) { if(is_array($data)) { $insertKeys = ""; $insertValues = ""; foreach($data as $key => $value) { $insertKeys .= sprintf("`%s`, ", $key); $insertValues .= sprintf(":%s, ", $key); } $insertQuery = sprintf('INSERT INTO `%1$s` (%2$s) VALUES (%3$s)', $this->queryBuilder->tableName, substr($insertKeys, 0, -2), substr($insertValues, 0, -2)); $insert = $this->query($insertQuery, $data, \PHPQuad::DB_EXEC); return ($insert === true) ? (int) $this->lastInsertId() : 0; } else { $this->resetQuery(); $this->lastQuery->error = "First argument must be Array"; $this->errors[] = $this->lastQuery->error; $this->debugWarning($this->lastQuery->error); } return 0; } public function update($data) { if(is_array($data)) { if($this->queryBuilder->whereClause !== "1") { $updateData = $data; foreach((array) $this->queryBuilder->queryData as $key => $value) { $updateData["_" . $key] = $value; if(is_int($key)) { $error = "WHERE clause for UPDATE requires named parameters"; break; } } if(!isset($error)) { $updateColumns = ""; foreach($updateData as $key => $value) { if(substr($key, 0, 1) != "_") $updateColumns .= sprintf("`%s`=:%s, ", $key, $key); } $updateQuery = sprintf('UPDATE `%1$s` SET %2$s WHERE %3$s', $this->queryBuilder->tableName, substr($updateColumns, 0, -2), str_replace(":", ":_", $this->queryBuilder->whereClause)); $update = $this->query($updateQuery, $updateData, \PHPQuad::DB_EXEC); return ($update === true) ? $this->lastQuery->rows : 0; } } else { $error = "UPDATE query requires WHERE clause"; } } else { $error = "First argument must be Array"; } if(isset($error)) { $this->resetQuery(); $this->lastQuery->error = $error; $this->errors[] = $this->lastQuery->error; $this->debugWarning($this->lastQuery->error); } return 0; } public function delete() { if($this->queryBuilder->whereClause !== "1") { $deleteQuery = sprintf('DELETE FROM `%1$s` WHERE %2$s', $this->queryBuilder->tableName, $this->queryBuilder->whereClause); $delete = $this->query($deleteQuery, $this->queryBuilder->queryData, \PHPQuad::DB_EXEC); return ($delete === true) ? $this->lastQuery->rows : 0; } else { $this->resetQuery(); $this->lastQuery->error = "DELETE query requires WHERE clause"; $this->errors[] = $this->lastQuery->error; $this->debugWarning($this->lastQuery->error); } return 0; } public function fetchAll() { $lock = ($this->queryBuilder->selectLock === true) ? " FOR UPDATE" : ""; $limit = ""; if(is_int($this->queryBuilder->selectLimit)) { if(is_int($this->queryBuilder->selectStart)) { $limit = sprintf(" LIMIT %d,%d", $this->queryBuilder->selectStart, $this->queryBuilder->selectLimit); } else { $limit = sprintf(" LIMIT %d", $this->queryBuilder->selectLimit); } } $selectQuery = sprintf('SELECT %2$s FROM `%1$s` WHERE %3$s%4$s%5$s%6$s', $this->queryBuilder->tableName, $this->queryBuilder->selectColumns, $this->queryBuilder->whereClause, $this->queryBuilder->selectOrder, $limit, $lock); $fetch = $this->query($selectQuery, $this->queryBuilder->queryData, \PHPQuad::DB_FETCH); return is_array($fetch) ? $fetch : false; } public function fetchFirst() { $fetch = $this->fetchAll(); if(is_array($fetch) && isset($fetch[0])) { return $fetch[0]; } return false; } public function fetchLast() { $fetch = $this->fetchAll(); if(is_array($fetch) && isset($fetch[0])) { return end($fetch); } return false; } public function dataObject($index = null) { $fetch = $this->fetchAll(); if(is_array($fetch)) { if($index === null) { return new DataObject($fetch); } else if(is_int($index) && isset($fetch[$index])) { return new DataObject($fetch[$index]); } } return false; } }<file_sep><?php namespace PHPQuad; use \PHPQuad\Core\DebuggingTrait; class DataObject implements \Countable { protected $data; protected $count; protected $debugging; use DebuggingTrait; public function __construct($data = null) { if(getenv("PQ_DEBUGGING")) $this->debugging = true; if(in_array(gettype($data), ["array","object"])) { $this->data = json_decode(json_encode($data), true); $this->count = (is_array($this->data)) ? count($this->data) : 0; } else { $this->data = []; $this->debugWarning("First argument must be an Array or an Object"); } } public function __toString() { return __CLASS__; } public function count() { return $this->count; } private function search($key, $value = null) { if(is_string($key)) { $valueType = gettype($value); if(in_array($valueType, ["string","integer"])) { $results = []; $resultsCount = 0; foreach($this->data as $array) { if(is_array($array)) { if($valueType == "string") { if(strtolower($array[$key]) === strtolower($value)) { $results[] = $array; $resultsCount++; } } else { if((int) $array[$key] === $value) { $results[] = $array; $resultsCount++; } } } } return ($resultsCount > 0) ? $results : []; } else { $this->debugWarning("Second argument must be a String or an Integer"); } } else { $this->debugWarning("First argument must be a String"); } return false; } public function group($key, $value = null) { $search = $this->search($key, $value); return new DataObject($search); } public function find($key, $value = null) { $search = $this->search($key, $value); return new DataObject((isset($search[0])) ? $search[0] : []); } private function splitter($args, $unset = false) { $splitter = []; if(count($args) > 0) { foreach($args as $arg) { if(in_array(gettype($arg), ["string","integer"])) { if(array_key_exists($arg, $this->data)) { $splitter[$arg] = $this->data[$arg]; if($unset) unset($this->data[$arg]); } } else { $this->debugNotice("All arguments must be String or Integer"); } } } else { $this->debugWarning("Expects at least 1 argument"); } return new DataObject($splitter); } public function split() { $args = (func_num_args() > 0) ? func_get_args() : []; return call_user_func(array($this, "splitter"), $args, true); } public function copy() { $args = (func_num_args() > 0) ? func_get_args() : []; return call_user_func(array($this, "splitter"), $args, false); } public function getArray() { return $this->data; } public function getObject() { return json_decode(json_encode($this->data)); } }<file_sep><?php namespace PHPQuad\Exception; class RestError extends \PHPQuadException { }<file_sep><?php namespace PHPQuad\Exception; class i18nError extends \PHPQuadException { }<file_sep><?php namespace PHPQuad\TemplateEngine\Modifiers; class Strtoupper { public function apply($parsed, $arguments = null) { return sprintf("strtoupper(%s)", $parsed); } }<file_sep><?php namespace PHPQuad\TemplateEngine; use \PHPQuad\Exception\TemplateError; use \PHPQuad\Core\DebuggingTrait; class DOM { protected $debugging; protected $DOM; use DebuggingTrait; public function __construct() { if(getenv("PQ_DEBUGGING")) $this->debugging = true; $this->DOM = []; $this->DOM["phpquad"] = ["now" => time(), "this" => "", "timer" => 0, "version" => \PHPQuad::VERSION, "post" => $_POST, "get" => $_GET, "session" => (!empty(session_id())) ? $_SESSION : []]; $this->DOM["PHPQuad"] = $this->DOM["phpquad"]; } public function __toString() { return __CLASS__; } public function updateTimer($timer) { $this->DOM["phpquad"]["timer"] = $timer; $this->DOM["PHPQuad"]["timer"] = $timer; } public function __set($key, $value = null) { if(is_string($key) && !empty($key)) { $valueType = gettype($value); if(in_array($valueType, ["object","array"])) $value = @json_decode(@json_encode($value), true); if(in_array($valueType, ["boolean","integer","double","string","array","object","NULL"])) { if(strtoupper($key) != "PHPQUAD") { $this->DOM[$key] = $value; } else { $this->debugWarning('Cannot redeclare core variable "PHPQuad"'); } } else { $this->debugWarning(sprintf('Unsupported data type "%s" for assigned key "%s"', strtoupper($valueType), $key)); } } else { $this->debugWarning("Assigned key must be a String"); } } public function __get($key) { return (isset($this->DOM[$key])) ? $this->DOM[$key] : null; } }<file_sep><?php namespace PHPQuad\Exception; class CipherError extends \PHPQuadException { }<file_sep><?php namespace PHPQuad\TemplateEngine\Modifiers; class Number_Format { public function apply($parsed, $arguments = null) { if(is_array($arguments)) { $nformat = sprintf("number_format(%s, ", $parsed); foreach($arguments as $argument) { $nformat .= "'" . $argument . "', "; } $nformat = substr($nformat, 0, -2) . ")"; return $nformat; } return $parsed; } }<file_sep><?php namespace PHPQuad; use \PHPQuad\Exception\SecurityError; use \PHPQuad\Core\DebuggingTrait; use \PHPQuad\Security\AbstractSecurity; use \PHPQuad\Security\CSRF; class Security extends AbstractSecurity { protected $debugging; public $csrf; use DebuggingTrait; public function __construct() { if(getenv("PQ_DEBUGGING")) $this->debugging = true; $this->csrf = new CSRF; } public function __toString() { return __CLASS__; } }<file_sep><?php namespace PHPQuad\Emails; trait SendTrait { private function fallBack($callback1, $callback2, $args = null) { if(is_callable($callback1, false)) { return call_user_func_array($callback1, $args); } else { if(is_callable($callback2, false)) { return call_user_func_array($callback2, $args); } else { throw new EmailsError("No email transfer agent available"); } } } public function sendEmail($to, \PHPQuad\Emails\Message $message) { $this->lastSentCount = 0; foreach((array) $to as $address) { $send = $this->fallBack($this->agent, [$this,"phpSendMail"], [$address, $message->subject(), $message->body(), $message->headers(), $message->attachments()]); if($send === true) $this->lastSentCount++; } return $this->lastSentCount; } public function phpSendMail($to, $subject, $message, $headers = null, $attachments = null) { return mail($to, $subject, $message, $headers); } }<file_sep><?php namespace PHPQuad\REST; trait OutputTrait { public function outputFormat($replace = null) { if(is_string($replace)) $this->output->format = $replace; return $this->output->format; } public function outputMethod($prefix = null) { $prefix = (isset($prefix) && is_string($prefix)) ? $prefix : "output"; return $prefix . strtoupper($this->output->format); } public function output($data, $code = 200) { if($this->output->format != "jsonp") $this->httpResponseCode($code); if($this->output->format == "json") { header("Content-type: application/json"); echo json_encode($data); } else if($this->output->format == "jsonp") { if(is_array($data) && !isset($data["status"])) $data["http_status"] = $code; header("Content-type: application/javascript; charset=utf-8;"); $callback = (isset($this->input->data["_callback"]) && is_string($this->input->data["_callback"]) && $this->input->data["_callback"] !== "") ? $this->input->data["_callback"] : "callback"; printf('%s(%s);', $callback, json_encode($data)); } else { if($this->output->format == "javascript") { header("Content-Type: application/javascript; charset=utf-8;"); } if(is_array($data) || is_object($data)) { $jsonData = json_decode(json_encode($data), true); if(array_key_exists("message", $jsonData)) { print $jsonData["message"]; } else { print_r($data); } } else { print (string) $data; } } } }<file_sep><?php namespace PHPQuad\Cache; use \PHPQuad\Exception\CacheError; use \PHPQuad\Cache\AbstractCache; use \PHPQuad\Cache\CacheInterface; use \PHPQuad\Cache\RedisTrait; class Redis extends AbstractCache implements CacheInterface { use RedisTrait; public function __construct($host, $port = 6379, $persistent = 0) { $redis = @stream_socket_client($host . ":" . $port, $redis_error, $redis_error_message, 1); if(!$redis) { throw new CacheError(sprintf("Redis connection failed: %s", $redis_error_message), $redis_error); } else { @stream_set_timeout($redis, 1); parent::__construct($redis); } } public function __destruct() { $this->redisHandler("disconnect"); } public function __toString() { return __CLASS__; } public function set($key, $value, $expire = 0) { $expire = (is_int($expire) && $expire > 0) ? $expire : 0; if($this->connected) { if(is_string($key) && !empty($key)) { if(is_bool($value)) $value = ($value === true) ? "true" : "false"; if(in_array(gettype($value), ["string","integer","double","array","object"])) { $redisValue = (in_array(gettype($value), ["array","object"])) ? base64_encode(serialize($value)) : $value; $redisQuery = ($expire > 0) ? sprintf('SETEX %1$s %3$d "%2$s"', $key, $redisValue, $expire) : sprintf('SET %1$s "%2$s"', $key, $redisValue); $redisExec = $this->redisHandler($redisQuery); if($redisExec === true) { return true; } else { $error = $redisExec; } } else { $error = sprintf('Value data type "%s" is not acceptable', gettype($value)); } } else { $error = "First argument must be a String"; } } else { $error = CONN_ERROR; } if(isset($error)) { $this->errors[] = $error; $this->debugWarning($error); } return false; } public function get($key, $decode = false) { if($this->connected) { $redisGrab = $this->redisHandler(sprintf("GET %s", $key)); return ($decode === true) ? $this->decode($redisGrab) : $redisGrab; } else { $this->error = CONN_ERROR; } if(isset($error)) { $this->errors[] = $error; $this->debugWarning($error); } return null; } public function countUp($key, $inc = 1) { if(!is_int($inc) || $inc <= 0) $inc = 1; if($this->connected) { return (int) $this->redisHandler(sprintf("INCRBY %s %d", $key, $inc)); } else { $this->error = CONN_ERROR; } if(isset($error)) { $this->errors[] = $error; $this->debugWarning($error); } return false; } public function countDown($key, $dec = 1) { if(!is_int($dec) || $dec <= 0) $dec = 1; if($this->connected) { $redisDec = $this->redisHandler(sprintf("DECRBY %s %d", $key, $dec)); if($redisDec < 0) { $this->set($key, 0); return 0; } return (int) $redisDec; } else { $this->error = CONN_ERROR; } if(isset($error)) { $this->errors[] = $error; $this->debugWarning($error); } return false; } public function delete($key) { if($this->connected) { $redisDelete = $this->redisHandler(sprintf("DEL %s", $key)); return (boolval($redisDelete) === true) ? true : false; } else { $this->error = CONN_ERROR; } return false; } public function flush() { if($this->connected) { $redisFlush = $this->redisHandler("FLUSHALL"); return (boolval($redisFlush) === true) ? true : false; } else { $this->error = CONN_ERROR; } return false; } }<file_sep><?php namespace PHPQuad\REST; trait InputTrait { public function inputMethod($lowercase = true) { return ($lowercase) ? strtolower($this->input->method) : $this->input->method; } public function inputFormat() { return $this->input->format; } }<file_sep><?php namespace PHPQuad\Exception; class EmailsError extends \PHPQuadException { }<file_sep><?php namespace PHPQuad\Logging; use \PHPQuad\Exception\LoggingError; use \PHPQuad\Logging\AbstractLogging; use \PHPQuad\Logging\LoggingInterface; class FS extends AbstractLogging implements LoggingInterface { protected $dir; public function __construct($path = "") { parent::__construct(); if(!is_string($path)) $path = ""; if(substr($path, -1) != "/") $path .= "/"; if(@is_dir($path) === true && @is_writable($path) === true) { $this->dir = $path; } else { throw new LoggingError("Directory is not writable"); } } public function __toString() { return __CLASS__; } public function write($id, $log, $data = null) { if(isset($data)) $data = print_r($data, true); $this->lastError = null; if(is_string($id) && $id != "") { if(is_string($log) && $log != "") { $timeStamp = time(); $name = sprintf("%s_%d", substr(preg_replace("#[^a-z0-9_]+#", "", strtolower($id)), 0, 16), $timeStamp); $writer = @fopen($this->dir . $name . ".txt", "w"); if(is_resource($writer)) { $body = <<<'EOT' Name: %1$s Logged Message: %2$s ===== Data: %3$s ===== Timestamp: %5$s (%4$d) EOT; if(@fwrite($writer, sprintf($body, $name, $log, $data, $timeStamp, date("d-m-Y h:i A", $timeStamp))) >= 1) { @fclose($writer); return true; } else { $this->lastError = sprintf('Failed to write "%s.txt"', $name); } } else { $this->lastError = "Failed to open resource for log writing"; } if($this->lastError !== null) { $this->errors[] = $this->lastError; $this->debugWarning($this->lastError); } } else { $this->debugWarning("Second argument must be a String"); } } else { $this->debugWarning("First argument must be a String"); } return false; } public function read($id) { $this->lastError = null; if(is_string($id) && $id != "") { $reader = @fopen($this->dir . $id . ".txt", "r"); if(is_resource($reader)) { $read = @fread($reader, @filesize($this->dir . $id . ".txt")); @fclose($reader); if(is_string($read) && !empty($read)) return $read; } } else { $this->debugWarning("First argument must be a String"); } return false; } public function browse($match = null) { $this->lastError = null; $match = (is_string($match) && $match != "") ? "*" . $match . "*.txt" : "*.txt"; $browse = glob($this->dir . $match); if(is_array($browse)) { usort($browse, function($a, $b) { return filemtime($b) - filemtime($a); }); return array_map(function($file) { return basename($file, ".txt"); }, $browse); } return false; } public function delete($id) { $this->lastError = null; if(is_string($id) && $id != "") { return @unlink($this->dir . $id . ".txt"); } else { $this->debugWarning("First argument must be a String"); } return false; } }<file_sep><?php namespace PHPQuad\Cache; use \PHPQuad\Exception\CacheError; use \PHPQuad\Cache\AbstractCache; use \PHPQuad\Cache\CacheInterface; class Memcache extends AbstractCache implements CacheInterface { public function __construct($host, $port = 11211, $persistent = 0) { if(class_exists("\Memcache")) { $memcache = new \Memcache; $memcache_connect = ($persistent) ? @$memcache->pconnect($host, (int) $port) : @$memcache->connect($host, (int) $port); if($memcache_connect === true) { parent::__construct($memcache); } else { throw new CacheError("Memcache connection failed"); } } else { throw new CacheError("Requires Memcache extension"); } } public function __destruct() { @$this->handler->close(); } public function __toString() { return __CLASS__; } public function set($key, $value, $expire = 0) { $expire = (is_int($expire) && $expire > 0) ? $expire : 0; if($this->connected) { if(is_string($key) && !empty($key)) { if(is_bool($value)) $value = ($value === true) ? "true" : "false"; if(in_array(gettype($value), ["string","integer","double","array","object"])) { return @$this->handler->set($key, $value, null, $expire); } else { $error = sprintf('Value data type "%s" is not acceptable', gettype($value)); } } else { $error = "First argument must be a String"; } } else { $error = CONN_ERROR; } if(isset($error)) { $this->errors[] = $error; $this->debugWarning($error); } return false; } public function get($key, $decode = false) { if($this->connected) { $memcache_result = @$this->handler->get($key); return ($memcache_result === false) ? null : $memcache_result; } else { $this->error = CONN_ERROR; } if(isset($error)) { $this->errors[] = $error; $this->debugWarning($error); } return null; } public function countUp($key, $inc = 1) { if(!is_int($inc) || $inc <= 0) $inc = 1; if($this->connected) { $mc_result = @$this->handler->increment($key, $inc); if($mc_result === false) { return ($this->set($key, $inc) === true) ? $inc : 0; } return (int) $mc_result; } else { $this->error = CONN_ERROR; } if(isset($error)) { $this->errors[] = $error; $this->debugWarning($error); } return false; } public function countDown($key, $dec = 1) { if(!is_int($dec) || $dec <= 0) $dec = 1; if($this->connected) { $mc_result = @$this->handler->decrement($key, $dec); if($mc_result === false) { $this->set($key, 0); return 0; } return (int) $mc_result; } else { $this->error = CONN_ERROR; } if(isset($error)) { $this->errors[] = $error; $this->debugWarning($error); } return false; } public function delete($key) { if($this->connected) { return @$this->handler->delete($key); } else { $this->error = CONN_ERROR; } if(isset($error)) { $this->errors[] = $error; $this->debugWarning($error); } return false; } public function flush() { if($this->connected) { return @$this->handler->flush(); } else { $this->error = CONN_ERROR; } if(isset($error)) { $this->errors[] = $error; $this->debugWarning($error); } return false; } }<file_sep><?php namespace PHPQuad\TemplateEngine; use \PHPQuad\Exception\TemplateError; use \PHPQuad\Core\DebuggingTrait; use \PHPQuad\TemplateEngine\ParseTrait; use \PHPQuad\TemplateEngine\CompileTrait; use \PHPQuad\TemplateEngine\DisplayTrait; abstract class CompilerAbstract { protected $templatePath = null; protected $compilePath = null; protected $cachePath = null; protected $timer = 0; protected $dom; protected $cacheHandler; protected $debugging; protected $error; protected $tplRoster = []; protected $parseTally = ["if_open" => 0, "if_closed" => 0, "foreach_open" => 0, "foreach_closed" => 0, "for_open" => 0, "for_closed" => 0]; use DebuggingTrait; use ParseTrait; use CompileTrait; use DisplayTrait; public function __construct() { if(getenv("PQ_DEBUGGING")) $this->debugging = true; $this->dom = new \PHPQuad\TemplateEngine\DOM; $this->cacheHandler = new \PHPQuad\TemplateEngine\Cache; } public function __toString() { return __CLASS__; } public function setPath($type, $path = null) { if(is_string($type) && is_string($path)) { $type = strtolower($type); if(substr($path, -1) != "/") $path .= "/"; if(in_array($type, ["template","templates","cache","compile"])) { if(@is_dir($path) && @is_writeable($path)) { switch($type) { case "cache": $this->cachePath = $path; break; case "compile": $this->compilePath = $path; break; default: $this->templatePath = $path; break; } return true; } else { throw new TemplateError(sprintf('"%s" is not a writable directory', $path)); } } else { throw new TemplateError(sprintf('"%s" is an invalid path type', $type)); } } else { throw new TemplateError("Unacceptable arguments"); } return false; } private function updateTimer($timer) { $this->timer = $timer; $this->dom->updateTimer($timer); } public function timer($print = false) { return ($this->timer > 0) ? $this->timer : false; } public function assign($key, $value) { $this->dom->$key = $value; } private function read($tpl_file) { if(strtolower(substr($tpl_file, -4)) != ".tpl") { $this->error = "Template file must have a .tpl extension"; return false; } $tpl_file = $this->templatePath . $tpl_file; if(@is_readable($tpl_file)) { $tpl = @fopen($tpl_file, "r"); $tpl_size = @filesize($tpl_file); if(is_resource($tpl) && $tpl_size > 0) { $tpl_data = @fread($tpl, $tpl_size); @fclose($tpl); $this->tplRoster[] = $tpl_file; return $this->clean($tpl_data); } else { $this->error = sprintf('Failed to load "%s" template file', basename($tpl_file)); return false; } } else { $this->error = sprintf('Template file "%s" is not readable does not exist', basename($tpl_file)); return false; } } public function flushCache($sess_id = null) { return $this->cacheHandler->flush($this->cachePath, $sess_id); } public function flushDOM() { $this->dom = new \PHPQuad\TemplateEngine\DOM; } }<file_sep><?php namespace PHPQuad\Core; trait DebuggingTrait { public function debugBackTrace() { $backTrace = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS); $backTrace = array_reverse($backTrace); $backTraceOffset = getenv("PQ_DEBUG_BKTRC_OFST"); if(intval($backTraceOffset) > 0) { $backTrace = array_slice($backTrace, intval($backTraceOffset)); } foreach($backTrace as $trace) { if(isset($trace["class"])) break; } $trace["method"] = (isset($trace["class"])) ? sprintf("%s::%s", $trace["class"], $trace["function"]) : ""; return $trace; } public function debugNotice($str) { if($this->debugging) { $trace = $this->debugBackTrace(); extract($trace); trigger_error(sprintf('%2$s: %1$s in file "%3$s" on line %4$d', $str, $method, basename($file), $line), E_USER_NOTICE); } } public function debugWarning($str) { if($this->debugging) { $trace = $this->debugBackTrace(); extract($trace); trigger_error(sprintf('%2$s: %1$s in file "%3$s" on line %4$d', $str, $method, basename($file), $line), E_USER_WARNING); } } public function debugEnable() { $this->debugging = true; return $this; } public function debugDisable() { $this->debugging = false; return $this; } }<file_sep><?php namespace PHPQuad\Plugins; class Test extends \PHPQuad\Components\Plugins { public function __toString() { return __CLASS__; } public function fooBar() { return __METHOD__; } }<file_sep><?php namespace PHPQuad; use \PHPQuad\TemplateEngine\CompilerAbstract; use \PHPQuad\TemplateEngine\TemplateEngineInterface; class TemplateEngine extends CompilerAbstract implements TemplateEngineInterface { public function __construct() { parent::__construct(); } public function __toString() { return __CLASS__; } }<file_sep><?php namespace PHPQuad\Security; use \PHPQuadException; use \PHPQuad\Exception\SecurityError; use \PHPQuad\Core\DebuggingTrait; class CSRF { protected $debugging; use DebuggingTrait; public function __construct() { if(getenv("PQ_DEBUGGING")) $this->debugging = true; $this->prepareSessionVar(); } public function __toString() { return __CLASS__; } private function prepareSessionVar() { if(session_id() !== "") { if(!isset($_SESSION["PHPQuad"]) || !is_array($_SESSION["PHPQuad"])) $_SESSION["PHPQuad"] = []; if(!isset($_SESSION["PHPQuad"]["Security"]) || !is_array($_SESSION["PHPQuad"]["Security"])) $_SESSION["PHPQuad"]["Security"] = []; if(!isset($_SESSION["PHPQuad"]["Security"]["CSRF"]) || !is_array($_SESSION["PHPQuad"]["Security"]["CSRF"])) $_SESSION["PHPQuad"]["Security"]["CSRF"] = ["token" => null, "expire" => time()-1]; return true; } else { $this->debugWarning("Session is not available"); } return false; } public function setToken($expire = 0) { if($this->prepareSessionVar()) { $expire = (is_int($expire) && $expire > 0) ? $expire : 0; $token = hash("sha512", hash_hmac("sha512", hash("sha256", microtime(false)), \PHPQuad::random(12))); $_SESSION["PHPQuad"]["Security"]["CSRF"] = ["token" => $token, "expire" => ($expire > 0) ? time()+$expire : 0]; return $token; } return false; } public function getToken() { if($this->prepareSessionVar()) { if($_SESSION["PHPQuad"]["Security"]["CSRF"]["expire"] > 0) { if(time() >= (int) $_SESSION["PHPQuad"]["Security"]["CSRF"]["expire"]) { $_SESSION["PHPQuad"]["Security"]["CSRF"]["token"] = null; } } return $_SESSION["PHPQuad"]["Security"]["CSRF"]["token"]; } return false; } public function verify($str) { if(is_string($str) && !empty($str)) { $csrfToken = $this->getToken(); return (is_string($csrfToken) && $str === $csrfToken) ? true : false; } else { $this->debugWarning("First argument must be a String"); } return false; } }<file_sep><?php namespace PHPQuad\Emails; use \PHPQuad\Core\DebuggingTrait; class Message { protected $attachments; protected $sender; protected $subject; protected $body; protected $bodyType; protected $boundary; protected $debugging; use DebuggingTrait; public function __construct($subject, $body) { if(getenv("PQ_DEBUGGING")) $this->debugging = true; $this->attachments = []; $this->subject = $subject; $this->body = $body; $this->bodyType = "html"; $this->boundary = md5(microtime(false)); $this->sender = (object) ["name" => null, "email" => null]; } public function __toString() { return __CLASS__; } public function senderName($name = null) { if(is_string($name)) { if(!empty($name)) { $this->sender->name = $name; } else { $this->debugWarning("First argument must be a String"); } } return $this; } public function senderEmail($email = null) { if(is_string($email)) { if(filter_var($email, FILTER_VALIDATE_EMAIL)) { $this->sender->email = $email; } else { $this->debugWarning("Invalid email address"); } return $this; } return $this; } public function contentType($type = null) { if(is_string($type)) { $type = str_replace("text/", "", strtolower($type)); if($type == "plain") { $this->bodyType = "plain"; } else if($type == "html") { $this->bodyType = "html"; } else { $this->debugWarning("Unacceptable value"); } } return $this; } public function attach($file, $alias = null) { if(function_exists("finfo_open")) { if(@file_exists($file) && @is_readable($file)) { $file_info = @finfo_open(FILEINFO_MIME_TYPE); $mime_type = @finfo_file($file_info, $file); @finfo_close($file_info); if(is_string($mime_type) && !empty($mime_type)) { if(!is_string($alias) || empty($alias)) $alias = basename($file); $this->attachments[] = ["file" => $file, "alias" => $alias, "mime" => $mime_type]; return true; } } else { $this->debugWarning("Attachment file not found"); } } else { $this->debugWarning('Required "fileinfo" functions'); } return false; } public function subject() { return $this->subject; } public function attachments() { return $this->attachments; } public function headers() { $headers = sprintf('From: "%1$s" <%2$s>', $this->sender->name, $this->sender->email) . PHP_EOL; $headers .= sprintf('Subject: %s', $this->subject) . PHP_EOL; $headers .= sprintf('Content-Type: multipart/alternative; boundary="_PHPQuad-%s"', $this->boundary) .PHP_EOL; return $headers; } public function body() { $body = "This is a multi-part message in MIME format." . PHP_EOL; $body .= "--_PHPQuad-" . $this->boundary . PHP_EOL; $body .= sprintf('Content-Type: text/%s; charset="utf-8"', $this->bodyType) . PHP_EOL; $body .= "Content-Transfer-Encoding: 7Bit" . PHP_EOL . PHP_EOL; $body .= $this->body . PHP_EOL; $body .= "--_PHPQuad-" . $this->boundary; foreach($this->attachments as $attachment) { $handle = @fopen($attachment["file"], "rb"); $attached = @fread($handle, @filesize($attachment["file"])); @fclose($handle); $body .= PHP_EOL . sprintf('Content-Type: %2$s; name="%1$s"', basename($attachment["alias"]), $attachment["mime"]) . PHP_EOL; $body .= "Content-Transfer-Encoding: base64" . PHP_EOL; $body .= "Content-Disposition: attachment" . PHP_EOL . PHP_EOL; $body .= chunk_split(base64_encode($attached)); $body .= PHP_EOL . "--_PHPQuad-".$this->boundary; } $body .= "--"; return $body; } }<file_sep><?php namespace PHPQuad\Database; class Paginated implements \Countable { public $totalRows; public $totalPages; public $start; public $limit; public $rows; public $pages; public $count; public function __construct($start, $limit) { $this->totalRows = 0; $this->totalPages = 0; $this->count = 0; $this->start = (int) $start; $this->limit = (int) $limit; $this->rows = []; $this->pages = []; } public function count() { return $this->count; } }<file_sep><?php namespace PHPQuad\Logging; use \PHPQuad\Exception\LoggingError; use \PHPQuad\Logging\AbstractLogging; use \PHPQuad\Logging\LoggingInterface; class DB extends AbstractLogging implements LoggingInterface { protected $db; public function __construct(\PHPQuad\Database $db) { parent::__construct(); $driver = $db->driver(); if(isset($driver) && in_array($driver, ["mysql","sqlite","pgsql"])) { $this->db = $db; switch($driver) { case "mysql": $createTableQuery = "CREATE TABLE IF NOT EXISTS `phpquad_logging` (`id` mediumint UNSIGNED auto_increment, `name` char(27) NOT NULL, `message` varchar(255) NOT NULL, `data` text, `timestamp` int UNSIGNED, PRIMARY KEY(`id`), UNIQUE KEY (`name`)) ENGINE=InnoDB;"; break; case "sqlite": $createTableQuery = "CREATE TABLE IF NOT EXISTS `phpquad_logging` (`id` INTEGER PRIMARY KEY, `name` TEXT NOT NULL UNIQUE, `message` TEXT NOT NULL, `data` TEXT default NULL, `timestamp` INTEGER UNSIGNED);"; break; case "pgsql": $createTableQuery = "CREATE TABLE IF NOT EXISTS `phpquad_logging` (`id` BIGSERIAL PRIMARY KEY, `name` varchar NOT NULL UNIQUE, `message` varchar NOT NULL, `data` TEXT default NULL, `timestamp` INTEGER UNSIGNED)"; break; } if(!empty($createTableQuery)) { $this->db->query($createTableQuery, [], \PHPQuad::DB_EXEC); } } else { throw new LoggingError("Unacceptable database driver"); } } public function __toString() { return __CLASS__; } public function write($id, $log, $data = null) { if(isset($data)) $data = print_r($data, true); $this->lastError = null; if(is_string($id) && $id != "") { if(is_string($log) && $log != "") { $timeStamp = time(); $name = sprintf("%s_%d", substr(preg_replace("#[^a-z0-9_]+#", "", strtolower($id)), 0, 16), $timeStamp); $write = $this->db->table("phpquad_logging")->insert(["name" => $name, "message" => $log, "data" => $data, "timestamp" => $timeStamp]); if($write >= 1) { return $name; } else { $this->lastError = $this->db->lastQuery->error; $this->errors[] = $this->lastError; $this->debugWarning($this->lastError); } } else { $this->debugWarning("Second argument must be a String"); } } else { $this->debugWarning("First argument must be a String"); } return false; } public function read($id) { $this->lastError = null; if(is_string($id) && $id != "") { $read = $this->db->table("phpquad_logging")->where("name=?", [$id])->fetchFirst(); if(is_array($read) && isset($read["message"])) { return $read; } } else { $this->debugWarning("First argument must be a String"); } return false; } public function browse($match = null) { $this->lastError = null; $this->db->table("phpquad_logging")->select("id","name")->orderDesc("id"); if(is_string($match) && $match != "") { $this->db->where("name LIKE ?", ["%" . $match . "%"]); } $browse = $this->db->fetchAll(); if(is_array($browse)) { return array_column($browse, "name"); } else { if($this->db->lastQuery->error !== null) { $this->lastError = $this->db->lastQuery->error; $this->errors[] = $this->lastError; $this->debugWarning($this->lastError); } } return false; } public function delete($id) { $this->lastError = null; if(is_string($id) && $id != "") { if($this->db->table("phpquad_logging")->find("name=?", [$id])->delete() >= 1) { return true; } else { if($this->db->lastQuery->error !== null) { $this->lastError = $this->db->lastQuery->error; $this->errors[] = $this->lastError; $this->debugWarning($this->lastError); } } } else { $this->debugWarning("First argument must be a String"); } return false; } }<file_sep><?php namespace PHPQuad\TemplateEngine\Modifiers; class String_format { public function apply($parsed, $arguments = null) { if(is_array($arguments) && isset($arguments[0])) { if(is_string($arguments[0]) && !empty($arguments[0])) return sprintf("\PHPQuad::stringFormat(%s, '%s')", $parsed, $arguments[0]); } return $parsed; } }<file_sep><?php namespace PHPQuad\TemplateEngine\Modifiers; class Format { public function apply($parsed, $arguments = null) { if(is_array($arguments)) { $sprintf = sprintf("sprintf(%s, ", $parsed); foreach($arguments as $argument) { $sprintf .= "'" . $argument . "', "; } $sprintf = substr($sprintf, 0, -2) . ")"; return $sprintf; } return $parsed; } }<file_sep><?php namespace PHPQuad\Logging; interface LoggingInterface { public function errors(); public function lastError(); public function write($id, $log, $data = null); public function read($id); public function browse($match); public function delete($id); public function flush(); }<file_sep><?php namespace PHPQuad\Cache; use \PHPQuad\Exception\CacheError; use \PHPQuad\Core\DebuggingTrait; abstract class AbstractCache { protected $handler; protected $connected; protected $errors; protected $debugging; use DebuggingTrait; public function __construct($handler) { if(getenv("PQ_DEBUGGING")) $this->debugging = true; $this->connected = true; $this->handler = $handler; } public function errors() { return $this->errors; } public function lastError() { return end($this->errors); } public function checkStatus() { return $this->connected; } public function decode($val) { return (is_string($val)) ? unserialize(base64_decode($val)) : null; } }<file_sep><?php namespace PHPQuad\Database; interface DatabaseInterface { public function setFlag($flag); public function insert($data); public function update($data); public function delete(); public function paginate(); public function fetchAll(); public function fetchFirst(); public function fetchLast(); public function dataObject($index); }<file_sep><?php namespace PHPQuad\Core; interface Constants { const VERSION = "1.00"; const TIMEZONE = "tmsn"; const DEBUGGING = "tbknk"; const DEBUG_BACKTRACE_OFFSET = "tbknkbtoff"; const ERRORS_COLLECT = 1201; const ERRORS_PUBLISH = 1202; const ERRORS_DEFAULT = 1203; const ERRORS_IGNORE_NOTICE = 1204; const ERRORS_REPORT_ALL = 1205; const PDO_MYSQL = 1101; const PDO_SQLITE = 1102; const PDO_PGSQL = 1103; const PDO_PERSISTENT = 1111; const DB_FETCH = 1112; const DB_EXEC = 1113; const DB_FETCH_COUNT_DEFAULT = 11001; const DB_FETCH_COUNT_ARRAY = 11002; }<file_sep><?php namespace PHPQuad\Database; trait QueryBuilderTrait { public function table($str) { if(is_string($str) && !empty($str)) { $this->queryBuilder->tableName = trim($str); } else { $this->debugWarning("First argument must be a String"); } return $this; } public function find($clause, $data = null) { return $this->where($clause, $data); } public function where($clause, $data = null) { if(!is_array($data)) { if($data !== null) { $this->debugWarning("Second argument must be an Array or NULL"); } $data = []; } $this->queryBuilder->whereClause = trim($clause); $this->queryBuilder->queryData = $data; return $this; } public function select() { if(func_num_args() > 0) { $args = func_get_args(); $error = false; foreach($args as $arg) { if(!is_string($arg)) $error = true; } if(!$error) { $this->queryBuilder->selectColumns = implode(",", array_map("trim", $args)); } else { $this->debugWarning("All column names must be String"); } } else { $this->debugWarning("Expects at least 1 column name"); } return $this; } public function lock() { $this->queryBuilder->selectLock = true; return $this; } public function orderAsc($col) { if(func_num_args() > 0) { $args = func_get_args(); $cols = ""; $error = false; foreach($args as $arg) { if(!is_string($arg)) { $error = true; break; } $cols .= sprintf("`%s`,", trim($arg)); } if(!$error) { $this->queryBuilder->selectOrder = sprintf(" ORDER BY %s ASC", trim($cols, ",")); } else { $this->debugWarning("All column names must be String"); } } else { $this->debugWarning("Expects at least 1 column name"); } return $this; } public function orderDesc($col) { if(func_num_args() > 0) { $args = func_get_args(); $cols = ""; $error = false; foreach($args as $arg) { if(!is_string($arg)) { $error = true; break; } $cols .= sprintf("`%s`,", trim($arg)); } if(!$error) { $this->queryBuilder->selectOrder = sprintf(" ORDER BY %s DESC", trim($cols, ",")); } else { $this->debugWarning("All column names must be String"); } } else { $this->debugWarning("Expects at least 1 column name"); } return $this; } public function start($int) { if(is_string($int)) $int = (int) $int; if(is_int($int) && $int > -1) { $this->queryBuilder->selectStart = $int; } else { $this->debugWarning("First argument must be an Integer"); } return $this; } public function limit($int) { if(is_string($int)) $int = (int) $int; if(is_int($int) && $int > -1) { $this->queryBuilder->selectLimit = $int; } else { $this->debugWarning("First argument must be an Integer"); } return $this; } }<file_sep><?php namespace PHPQuad\Database; trait DatabaseTrait { public function driver() { return $this->config->driver; } public function persistent() { return $this->config->persistent; } public function errors() { return $this->errors; } public function lastError() { return end($this->errors); } public function resetQuery() { $this->lastQuery = (object) ["query" => "", "rows" => 0, "error" => null]; } public function rowCount() { return (isset($this->lastQuery) && is_object($this->lastQuery) && isset($this->lastQuery->rows)) ? (int) $this->lastQuery->rows : 0; } public function enableException() { $this->throwException = true; return $this; } public function throwException() { return $this->enableException(); } public function exceptionMode() { return $this->enableException(); } public function disableException() { $this->throwException = false; return $this; } public function silentMode() { return $this->disableException(); } }<file_sep><?php namespace PHPQuad\Core; abstract class AbstractErrorHandler { abstract public function setFlag(); abstract public function setFormat($format); abstract public function flush(); abstract public function fetchAll(); public function handle($type, $message, $file = null, $line = 0, $context = null) { if(error_reporting() === 0) return false; if(in_array($type, [2,8,512,1024,2048,8192,16384])) { $handle_ignore = ($type == E_NOTICE) ? $this->ignoreNotice : false; if(!$handle_ignore) { $error_type = $this->type($type); if($this->method != 1202) $this->errors[] = ["type" => strtolower($error_type), "message" => $message, "file" => $file, "line" => $line, "compiled" => sprintf($this->format, $message, $file, basename($file), $line, $error_type, strtoupper($error_type))]; if($this->method != 1201) printf($this->format . "<br />", $message, $file, basename($file), $line, $error_type, strtoupper($error_type)); } } else { \PHPQuad::shutDown($message, $file, $line); } } private function type($error) { $type = ""; switch($error) { case 1: $type = "Fatal Error"; break; case 2: $type = "Warning"; break; case 4: $type = "Parse Error"; break; case 8: $type = "Notice"; break; case 16: $type = "Core Error"; break; case 32: $type = "Core Warning"; break; case 64: $type = "Compile Error"; break; case 128: $type = "Compile Warning"; break; case 256: $type = "Error"; break; case 512: $type = "Warning"; break; case 1024: $type = "Notice"; break; case 2048: $type = "Strict"; break; case 4096: $type = "Recoverable"; break; case 8192: $type = "Deprecated"; break; case 16384: $type = "Deprecated"; break; default: $type = "Unknown"; break; } return $type; } }<file_sep><?php namespace PHPQuad\Core; class Screen extends AbstractBootstrapScreen { public $message; public $line; public $file; public function __construct($message, $file = null, $line = 0) { $this->message = htmlentities($message); $this->line = (int) $line; $this->file = (object) ["path" => $file, "name" => null]; if(!empty($file)) $this->file->name = basename($file); parent::__construct(); } public function __toString() { return __CLASS__; } public function shutDown() { exit($this->makeHTML()); } }<file_sep><?php namespace PHPQuad\Core; use \PHPQuad\Exception\DateTimeError; class DateTime { protected $timeZone; public function __construct($tz = null) { $this->timeZone = date_default_timezone_get(); if(!empty($tz)) $this->setTimeZone($tz); } public function __toString() { return __CLASS__; } public function setTimeZone($tz) { $zones = \DateTimeZone::listIdentifiers(); if(in_array($tz, $zones)) { $this->timeZone = $tz; return date_default_timezone_set($tz); } else { throw new DateTimeError(sprintf('Invalid Timezone "%1$s"', $tz), 101); } } public function getTimeZone() { return $this->timeZone; } public function difference($stamp_one, $stamp_two = 0) { $stamp_one = (int) $stamp_one; $stamp_two = (empty($stamp_two) || !is_int($stamp_two)) ? time() : (int) $stamp_two; return ($stamp_two > $stamp_one) ? $stamp_two-$stamp_one : $stamp_one-$stamp_two; } public function minutesDifference($stamp_one, $stamp_two = null) { return round(($this->difference($stamp_one, $stamp_two)/60), 1); } public function hoursDifference($stamp_one, $stamp_two = null) { return round((($this->difference($stamp_one, $stamp_two)/60)/60), 1); } }<file_sep><?php namespace PHPQuad\Core; class ErrorHandler extends AbstractErrorHandler { protected $errors; protected $method; protected $format; protected $ignoreNotice; protected $debugging; public function __construct($flags, $debugging = false) { $this->method = \PHPQuad::ERRORS_DEFAULT; $this->format = '[%6$s] %1$s in <u>%2$s</u> on line <u>%4$d</u>.'; $this->ignoreNotice = false; $this->debugging = ($debugging === true) ? true : false; $this->flush(); call_user_func_array([$this,"setFlag"], (array) $flags); set_error_handler(array($this, "handle")); set_exception_handler(function($e) { \PHPQuad::shutDown("Exception: " . $e->getMessage(), $e->getFile(), $e->getLine()); }); } public function __toString() { return __CLASS__; } public function setFlag() { foreach((array) func_get_args() as $flag) { switch($flag) { case 1201: $this->method = $flag; break; case 1202: $this->method = $flag; break; case 1203: $this->method = $flag; break; case 1204: $this->ignoreNotice = true; break; case 1205: $this->ignoreNotice = false; break; } } } public function setFormat($format) { if(is_string($format) && !empty($format)) { $this->format = $format; return true; } else { if($this->debugging) trigger_error(__METHOD__ . ": First argument must be a String.", E_USER_NOTICE); } return false; } public function fetchAll() { return $this->errors; } public function flush() { $this->errors = []; } }<file_sep><?php namespace PHPQuad\Core; abstract class AbstractBootstrapScreen { abstract public function shutDown(); public $type; public function __construct() { $this->type = "danger"; } public function type($type) { if(in_array($type, ["danger","warning","success","info"])) $this->type = $type; } public function makeHTML() { $screen = <<<'EOT' <!DOCTYPE html> <html> <head> <meta http-equiv="Content-Type" content="text/html;charset=UTF-8" /> <link rel="stylesheet" href="//maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css"> <link rel="stylesheet" href="//maxcdn.bootstrapcdn.com/font-awesome/4.4.0/css/font-awesome.min.css"> <title>%5$s</title> <style type="text/css"> body { background-color: #effbfa; } div.container { width: 80%; min-width: 800px; } div#screen { margin: 100px 0px; } </style> </head> <body> <div class="container"> <div class="row"> <div class="content"> <div class="panel panel-default" id="screen"> <div class="panel-body"> <div class="alert alert-%2$s">%1$s</div> </div> <div class="panel-footer text-muted"> %3$s <span class="pull-right"><i class="fa fa-cube"></i> PHPQuad %4$s</span> </div> </div> </div> </div> </div> </body> </html> EOT; $reference = (isset($this->file->name)) ? sprintf('<a href="javascript:alert(\'%1$s\');">%2$s</a>:%3$d', $this->file->path, $this->file->name, $this->line) : sprintf("[%d]", $this->line); $pageTitle = trim(substr(strip_tags($this->message), 0, 30)); if(strlen($this->message) > 30) $pageTitle .= "..."; return sprintf($screen, $this->message, $this->type, $reference, \PHPQuad::VERSION, $pageTitle); } }<file_sep><?php namespace PHPQuad\Cache; trait RedisTrait { private function redisHandler($command) { $command = trim($command); if(strtolower($command) == "disconnect") return @fclose($this->handler); $return = fwrite($this->handler, $this->redisPrepare($command)); if($return === false) { $this->error = "Error occurred while sending command to redis server."; return false; } else { return $this->redisReply(); } } private function redisPrepare($command) { $parts = str_getcsv($command, " ", '"'); $prepared = "*" . count($parts) . "\r\n"; foreach($parts as $part) { $prepared .= "$" . strlen($part) . "\r\n" . $part . "\r\n"; } return $prepared; } private function redisReply() { $reply = fgets($this->handler); if($reply === false) { $this->error = "Error occurred while receiving response from Redis server."; return false; } else { $reply = trim($reply); $reply_type = substr($reply, 0, 1); $data = substr($reply, 1); if($reply_type == "+") { return (strtolower($data) == "ok") ? true : $data; } else if($reply_type == "-") { $this->error = substr($data, 4); return false; } else if($reply_type == ":") { return $data; } else if($reply_type == "$") { $data_length = intval($data); if($data_length < 0) { return null; } else { $reply = @stream_get_contents($this->handler, ($data_length+2)); if($reply === false) { $this->error = "Error occured while reading Redis reply. [0]"; } else { return trim($reply); } } } else if($reply_type == "*") { $replies_count = intval($data); $replies = []; if($replies_count < 0) { return null; } else { for($i=0;$i<$replies_count;$i++) { $replies[] = $this->redisReply($redis); } return $replies; } } else { $this->error = "Unknown redis reply format."; return false; } } } }<file_sep><?php namespace PHPQuad; require __DIR__ . "/i18n/globalTranslateFunction.php"; use \PHPQuad\Exception\i18nError; use \PHPQuad\Core\DebuggingTrait; use \PHPQuad\i18n\i18nInterface; class i18n implements i18nInterface { protected $languagesPath; protected $boundLanguage; protected $debugging; use DebuggingTrait; public function __construct() { if(getenv("PQ_DEBUGGING")) $this->debugging = true; $this->boundLanguage = null; $this->languagesPath = ""; } public function __toString() { return __CLASS__; } public function setLanguagesPath($path) { if(function_exists("\__")) { if(is_string($path) && !empty($path)) { if(substr($path, -1) != "/") $path .= "/"; if(@is_dir($path) && @is_readable($path)) { $this->languagesPath = $path; return; } } throw new i18nError(sprintf('"%s" is not a valid directory path', $path)); } else { throw new i18nError(self::BOOT_ERROR); } } public function languageExists($name) { $language_file = $this->languagesPath . strtolower($name) . ".php"; return (@file_exists($language_file) && @is_readable($language_file)) ? true : false; } public function language($name) { if(function_exists("\__")) { $language_file = $this->languagesPath . strtolower($name) . ".php"; if(@file_exists($language_file) && @is_readable($language_file)) { $lang = new \PHPQuad\i18n\Language($name); @include_once($language_file); return $lang; } else { throw new i18nError(sprintf('"%s" language file not found in "%s"', $name, $this->languagesPath)); } } else { throw new i18nError(self::BOOT_ERROR); } return false; } public function bindLanguage(\PHPQuad\i18n\Language $lang) { global $PHPQUAD_BOUND_LANGUAGE; $PHPQUAD_BOUND_LANGUAGE = $lang; $this->boundLanguage = $lang->name(); return true; } public function boundLanguage() { return $this->boundLanguage; } }<file_sep><?php namespace PHPQuad\TemplateEngine\Modifiers; class Substr { public function apply($parsed, $arguments = null) { $from = (is_array($arguments) && isset($arguments[0])) ? (int) $arguments[0] : "null"; $to = (isset($from) && isset($arguments[1])) ? (int) $arguments[1] : "null"; return sprintf("substr(%s, %s, %s)", $parsed, $from, $to); } }<file_sep><?php namespace PHPQuad\TemplateEngine\Modifiers; class Round { public function apply($parsed, $arguments = null) { $decimals = 0; if(is_array($arguments)) { $decimals = (int) $arguments[0] > 0 ? $arguments[0] : 0; } return sprintf("round(%s, %d)", $parsed, $decimals); } }<file_sep><?php namespace PHPQuad\Database; class QueryBuilder { public $tableName; public $whereClause; public $selectColumns; public $selectLock; public $selectOrder; public $selectStart; public $selectLimit; public $queryData; public function __construct() { $this->resetQuery(); } public function resetQuery() { $this->tableName = ""; $this->whereClause = "1"; $this->selectColumns = "*"; $this->selectLock = false; $this->selectOrder = ""; $this->selectStart = null; $this->selectLimit = null; $this->queryData = []; } }<file_sep><?php namespace PHPQuad\TemplateEngine\Modifiers; class Trim { public function apply($parsed, $arguments = null) { if(is_array($arguments) && isset($arguments[0])) { if(is_string($arguments[0])) return sprintf("trim(%s, '%s')", $parsed, $arguments[0]); } return sprintf("trim(%s)", $parsed); } }<file_sep><?php namespace PHPQuad; use \PHPQuad\Exception\CipherError; use \PHPQuad\Core\DebuggingTrait; class Cipher { protected $defaultKey; protected $defaultHashAlgo; protected $debugging; use DebuggingTrait; public function __construct() { if(getenv("PQ_DEBUGGING")) $this->debugging = true; if(function_exists("mcrypt_encrypt")) { $this->defaultHashAlgo = "sha1"; $this->defaultKey = ""; } else { throw new CipherError("Requires MCRYPT extension", 100); } } public function __toString() { return __CLASS__; } private function adjustKeySize($key) { return str_pad(substr($key, 0, 32), 32, "\0", STR_PAD_RIGHT); } public function setDefaultKey($key) { if(is_string($key) && !empty($key)) { $this->defaultKey = $this->adjustKeySize($key); } else { throw new CipherError("First argument must be a String", 101); } } public function getDefaultKey() { return ($this->debugging === true) ? $this->defaultKey : false; } public function setDefaultHash($algo) { if(is_string($algo) && in_array($algo, hash_algos())) { $this->defaultHashAlgo = $algo; } else { throw new CipherError("Unacceptable hash algorithm"); } } public function getDefaultHash() { return $this->defaultHashAlgo; } public function encrypt($string, $key = null) { $key = (is_string($key)) ? $this->adjustKeySize($key) : $this->defaultKey; $string_iv = @rtrim(@base64_encode(@mcrypt_create_iv(@mcrypt_get_iv_size(MCRYPT_RIJNDAEL_256, MCRYPT_MODE_ECB), MCRYPT_DEV_URANDOM))); $encrypted = @base64_encode(@mcrypt_encrypt(MCRYPT_RIJNDAEL_256, $key, $string, MCRYPT_MODE_CBC, @base64_decode($string_iv))); return @sprintf("%s%s%s", @str_pad(strlen($string_iv), 4, 0, STR_PAD_LEFT), $string_iv, $encrypted); } public function encryptObject($object, $key = null) { if(in_array(gettype($object), ["object","array"])) { $object = base64_encode(serialize($object)); return $this->encrypt($object, $key); } else { $this->debugWarning("First argument must be an Array or an Object"); } return false; } public function decrypt($string, $key = null) { $key = (is_string($key)) ? $this->adjustKeySize($key) : $this->defaultKey; $string_iv = @substr($string, 4, intval(substr($string, 0, 4))); $encrypted = @substr($string, @intval(@substr($string, 0, 4))+4); return (!empty($encrypted) && !empty($string_iv)) ? @rtrim(@mcrypt_decrypt(MCRYPT_RIJNDAEL_256, $key, @base64_decode($encrypted), MCRYPT_MODE_CBC, @base64_decode($string_iv)), "\0") : ""; } public function decryptObject($string, $key = null) { $object = $this->decrypt($string, $key); if(is_string($object) && !empty($object)) { $object = @unserialize(@base64_decode($object)); if(in_array(gettype($object), ["object","array"])) { return $object; } else { $this->debugWarning("Decoded value is not an Array or an Object"); } } return false; } public function hash($string, $salt = "", $algo = null) { if(!is_string($algo)) $algo = $this->defaultHashAlgo; if(in_array($algo, hash_algos())) { $salt = (is_string($salt) && $salt != "") ? "*" . $salt : ""; return hash($algo, sprintf("%s%s", $string, $salt)); } else { $this->debugWarning("Unacceptable HASH algorithm"); } return false; } }<file_sep><?php namespace PHPQuad\Emails; trait ParseTrait { private function parse($message, $data, $parents = null) { if(!is_array($data)) $data = []; if(!is_array($parents)) $parents = []; $data = json_decode(json_encode($data), true); foreach($data as $key => $value) { if(is_array($value)) { $parents[] = $key; $message = $this->parse($message, $value, $parents); @array_pop($parents); } else { $variable = ""; $parents_count = count($parents); for($i=0;$i<$parents_count;$i++) { $variable .= ($i == 0) ? $parents[$i] : sprintf("[%s]", $parents[$i]); } $variable = sprintf(($parents_count > 0) ? "{{%s[%s]}}" : "{{%s%s}}", $variable, $key); $message = str_ireplace($variable, $value, $message); } } return $message; } private function wrap($subject, $message) { if(is_string($this->wrapper)) { $wrapped = str_ireplace("{{subject}}", $subject, $this->wrapper); $wrapped = str_ireplace("{{message}}", $message, $wrapped); return $wrapped; } return $message; } }<file_sep><?php namespace PHPQuad\i18n; class Language { protected $name; protected $strings = []; public function __construct($name = null) { if(isset($name)) $this->name = $name; } public function __toString() { return __CLASS__; } public function __set($key, $value) { return $this->set($key, $value); } public function name() { return $this->name; } public function set($key, $value) { if(is_string($key) && is_string($value)) $this->strings[strtoupper($key)] = $value; } public function get($key) { $key = strtoupper($key); return (isset($this->strings[$key])) ? $this->strings[$key] : false; } }<file_sep><?php namespace PHPQuad\Logging; abstract class AbstractLogging { protected $errors; protected $lastError; public function __construct() { $this->errors = []; $this->lastError = null; } public function errors() { return $this->errors; } public function lastError() { return $this->lastError; } public function flush() { $logs = $this->browse(); $flushed = 0; if(is_array($logs)) { foreach($logs as $id) { if($this->delete($id) === true) { $flushed++; } } } return ($flushed > 0) ? true : false; } }<file_sep><?php namespace PHPQuad\TemplateEngine\Modifiers; class Rawurldecode { public function apply($parsed, $arguments = null) { return sprintf("rawurldecode(%s)", $parsed); } }<file_sep><?php namespace PHPQuad\TemplateEngine; use \PHPQuad\Exception\TemplateError; trait ParseTrait { private function quotes($data) { return str_replace('"', "", str_replace("'", "", $data)); } private function clean($data) { if(is_string($data)) { $from = ["<?","?>"]; $to = ["&lt;?","?&gt;"]; return str_replace($from, $to, $data); } return false; } private function variable($var, $dom_element = true) { $var = explode("|", trim($var, "$")); $modifiers = $var; unset($modifiers[0]); $vars = explode(".", $var[0]); unset($var); $variable = ($dom_element === true) ? "this->dom->" : ""; for($i=0;$i<count($vars);$i++) { if($i != 0) $variable .= "[\""; $variable .= $vars[$i]; if($i != 0) $variable .= "\"]"; } $variable = "$".$variable; if(is_array($modifiers) && count($modifiers) >= 1) { foreach($modifiers as $modifier) { preg_match_all("~'[^']++'|\([^)]++\)|[^:]++~", $modifier, $modifier); $modifier = $modifier[0]; $modifier_args = $modifier; unset($modifier_args[0]); $modifier = $modifier[0]; $modifier_args = array_map(function($modifier_args) { return $this->quotes($modifier_args); }, $modifier_args); $modifier_obj = sprintf("\PHPQuad\TemplateEngine\Modifiers\%s", $modifier); if(class_exists($modifier_obj)) { $modifier_obj = new $modifier_obj(); $variable = $modifier_obj->apply($variable, array_values($modifier_args)); } else { $this->debugWarning(sprintf('Undefined modifier "%s"', $modifier)); } } } return $variable; } private function parse($data, $tpl_name) { if(is_string($data) && is_string($tpl_name)) { $tally = $this->parseTally; $parsed = ""; $phrase = null; $parse = null; $literal = false; $literal_vars = ["for" => [], "foreach" => []]; $data_len = strlen($data); for($i=0;$i<$data_len;$i++) { if(isset($phrase)) { $phrase .= $data{$i}; if($data{$i} == "}") { $parse = $phrase; $phrase = null; } } else { if($data{$i} == "{") { $phrase = "{"; } else { $parsed .= $data{$i}; } } if(isset($parse)) { $parse_literal = $parse; $parse = preg_replace("/\s+/", " ", substr($parse, 1, -1)); if(!$literal) { if(substr($parse, 0, 1) == "$") { $var = explode(".", explode("|", trim($parse, "$"))[0])[0]; $var_dom = (in_array($var, $literal_vars["for"]) || in_array($var, $literal_vars["foreach"])) ? false : true; $parsed .= sprintf("<?php echo(%s); ?>", $this->variable($parse, $var_dom)); } else if(substr($parse, 0, 1) == "(") { $direct_function_calls = preg_match("/[a-zA-Z0-9\_\.]+[\(]/", $parse); if($direct_function_calls >= 1) { throw new TemplateError(sprintf('Illegal attempt to call a function directly in "%s"', $tpl_name)); } else { if(substr($parse, -1) == ")") { $parse_chunk = $parse; $parse_chunk = preg_replace_callback("/[\$]([a-zA-Z0-9\.\_]+)/", function ($matches) use ($literal_vars) { $match_var = explode(".", trim($matches[0], "$"))[0]; $match_var_dom = (in_array($match_var, $literal_vars["for"]) || in_array($match_var, $literal_vars["foreach"])) ? false : true; return $this->variable(trim($matches[0], "$"), $match_var_dom); }, $parse_chunk); $parsed .= sprintf("<?php echo(%s); ?>", $parse_chunk); } } } else { $parse_chunks = explode(" ", $parse); if($parse_chunks[0] == "if") { $tally["if_open"]++; $if_statement = "<?php if("; for($f=0;$f<count($parse_chunks);$f++) { if($f == 0) continue; $parse_chunk = $parse_chunks[$f]; if(strpos($parse_chunk, "$") !== false && strpos($parse_chunk, "$") >= 0) { $parsed_chunk = preg_replace_callback("/[\$]([a-zA-Z0-9\.\_]+)/", function ($matches) use ($literal_vars) { $match_var = explode(".", trim($matches[0], "$"))[0]; $match_var_dom = (in_array($match_var, $literal_vars["for"]) || in_array($match_var, $literal_vars["foreach"])) ? false : true; return $this->variable(trim($matches[0], "$"), $match_var_dom); }, $parse_chunk); $parse_chunk = $parsed_chunk; } $if_statement .= sprintf(" %s", $parse_chunk); } $if_statement .= ") { ?>"; $parsed .= $if_statement; unset($if_statement); } else if($parse_chunks[0] == "/if") { $tally["if_closed"]++; $parsed .= "<?php } ?>"; } else if($parse_chunks[0] == "else") { $parsed .= "<?php } else { ?>"; } else if($parse_chunks[0] == "for") { $tally["for_open"]++; $for_command = str_replace(["$"," "], "", substr($parse, 4)); $for_command = array_map("trim", explode("=", $for_command)); $for_command[1] = array_map("trim", explode("to", $for_command[1])); $parsed .= sprintf("<?php for($%s=%d;$%s<=%d;$%s++) { ?>", $for_command[0], $for_command[1][0], $for_command[0], $for_command[1][1], $for_command[0]); $literal_vars["for"][] = $for_command[0]; unset($for_command); } else if($parse_chunks[0] == "/for") { $tally["for_closed"]++; $parsed .= "<?php } ?>"; $literal_vars["for"] = []; } else if($parse_chunks[0] == "foreach") { $tally["foreach_open"]++; $foreach_command = array_map("trim", explode(" as", substr($parse, 8))); $foreach_command_var = explode(".", trim($foreach_command[0], "$"))[0]; $parsed .= sprintf("<?php foreach((array) %s as %s) { ?>", $this->variable($foreach_command[0], (in_array($foreach_command_var, $literal_vars["for"]) || in_array($foreach_command_var, $literal_vars["foreach"])) ? false : true), $foreach_command[1]); $foreach_command_vars = explode("=>", str_replace(["$", " "], "", $foreach_command[1])); foreach($foreach_command_vars as $foreach_command_var) { if(is_string($foreach_command_var) && !empty($foreach_command_var)) $literal_vars["foreach"][] = $foreach_command_var; } unset($foreach_command_vars); unset($foreach_command); } else if($parse_chunks[0] == "/foreach") { $tally["foreach_closed"]++; $parsed .= "<?php } ?>"; $literal_vars["foreach"] = []; } else if($parse_chunks[0] == "include") { $include_command = $this->quotes($parse); $include_command = explode("file=", $include_command); $include_tpl = $this->read($include_command[1]); if(!$include_tpl) { $parsed .= sprintf("<strong>PHPQuad Template Engine:</strong> %s", $this->error); } else { $include_tpl = $this->parse($include_tpl, $include_command[1]); if(!$include_tpl) { throw new TemplateError((isset($this->error)) ? $this->error : sprintf('Template file "%s%s" parsing error', $this->templatePath, $include_command[1])); } else { $parsed .= $include_tpl; } } unset($include_tpl); unset($include_command); } else if($parse_chunks[0] == "literal") { $literal = true; } } } else { if($parse == "/literal") { $literal = false; } else { $parsed .= $parse_literal; } } $parse_literal = null; $parse = null; } } if(isset($phrase)) { $this->error = sprintf('Template file "%s" is either corrupted or incomplete', basename($tpl_name)); return false; } else { foreach(["if","foreach","for"] as $section) { if($tally["{$section}_open"] != $tally["{$section}_closed"]) { $this->error = sprintf('Uneven {%s} tags in template file "%s"', $section, basename($tpl_name)); return false; } } return $parsed; } } return false; } }<file_sep><?php namespace PHPQuad\REST; interface RestInterface { const HTTP_REQUEST_ERROR = "HTTP Request Method must be 'GET', 'POST', 'PUT' or 'DELETE'"; public function isREST(); public function httpRedirect($path); public function httpResponseCode($code); public function inputMethod($lc); public function inputFormat(); public function outputFormat($new); public function outputMethod($prefix); public function output($data, $code); public function requestRoot(); public function requestFormat(); public function requestMethod($index); }<file_sep><?php namespace PHPQuad\Cache; interface CacheInterface { const CONN_ERROR = "Connection with cache server is not established"; public function errors(); public function lastError(); public function checkStatus(); public function decode($val); public function set($key, $value, $expire = 0); public function get($key, $decode = false); public function countUp($key, $inc = false); public function countDown($key, $dec = false); public function delete($key); public function flush(); }<file_sep><?php namespace PHPQuad\TemplateEngine; interface TemplateEngineInterface { public function setPath($type, $path = null); //private function updateTimer($timer); public function timer($print = false); public function assign($key, $value); //private function read($tpl); public function flushCache($sess = null); public function flushDOM(); //private function compile($tpl); public function prepare($tpl, $cache = 0); public function display($tpl, $cache = 0); //private function quotes($data); //private function clean($data); //private function variable($var, $dom = true); //private function parse($data, $tpl); }<file_sep><?php namespace PHPQuad\TemplateEngine\Modifiers; class htmlEntities { public function apply($parsed, $arguments = null) { if(!is_array($arguments)) $arguments = []; $htmlents = sprintf("htmlentities(%s, ", $parsed); if(isset($arguments[0])) $htmlents .= $arguments[0] . ", "; if(isset($arguments[1])) $htmlents .= "'" . $arguments[1] . "', "; $htmlents = substr($htmlents, 0, -2) . ")"; return $htmlents; } }<file_sep><?php namespace PHPQuad\TemplateEngine; use \PHPQuad\Exception\TemplateError; use \PHPQuad\Core\DebuggingTrait; class Cache { protected $debugging; use DebuggingTrait; public function __construct($debugging = false) { if(getenv("PQ_DEBUGGING")) $this->debugging = true; } public function __toString() { return __CLASS__; } public function write($cache_file, $compiled) { $cacher = @fopen($cache_file, "w"); if(is_resource($cacher)) { if(@fwrite($cacher, $compiled) > 0) { @fclose($cacher); return true; } else { $this->debugWarning(sprintf('Failed to write cache file "%s"', basename($cache_file))); } } else { $this->debugWarning(sprintf('Failed to open cache resource for "%s"', basename($cache_file))); } } public function read($cached_file, $lifetime) { if(@file_exists($cached_file) && @is_readable($cached_file)) { $cache_stamp = filemtime($cached_file); if($cache_stamp > 0 && (time()-$cache_stamp) <= $lifetime) { $cache_read = @fopen($cached_file, "r"); if(is_resource($cache_read)) { $cached = @fread($cache_read, @filesize($cached_file)); @fclose($cache_read); if(is_string($cached) && strlen($cached) > 0) { return $cached; } else { $this->debugWarning(sprintf('Cached file "%s" is either corrupted or invalid', basename($cached_file))); } } else { if($this->debugging) trigger_error(__METHOD__ . sprintf(': .', basename($cached_file)), E_USER_NOTICE); $this->debugWarning(sprintf('Failed to open cache resource for "%s"', basename($cached_file))); } } } return false; } public function flush($cache_path, $sess_id = null) { $sess_id = (is_string($sess_id) && !empty($sess_id)) ? $sess_id : null; $flushed = 0; if(isset($cache_path)) { foreach((array) @glob($cache_path . sprintf("*_%s.html", (isset($sess_id)) ? $sess_id : "*")) as $cache_file) { if(@unlink($cache_file) === true) $flushed++; } } return $flushed; } }
53c848f26e6587a4d45496af9c561e363048001b
[ "Markdown", "PHP" ]
75
PHP
phpquad/PHPQuad
178182b73e15bdc644f6a0e803183251dd451680
977e8a3bb9d7ad8fd21f5d65259b8aff02db96ac
refs/heads/master
<repo_name>jmintegr1/Gordon<file_sep>/Jewell's Pizzaria/src/main/Application.java package main; public class Application { public static void main(String[] args) { Pizza myPizza = new Pizza(); Pizza jewellsPizza = new Pizza(); Pizza moesPizza = new Pizza("mushrooms", 16.0, "large", true); System.out.println("Jewell's pizza is " + myPizza.getTopping() + " and its " + myPizza.getSize()); System.out.println("Joe's pizza is " + myPizza.getTopping() + " and its for " + myPizza.isTakeOut()); System.out.println("Moe's pizza is " + myPizza.getTopping() + " and it cost" + " " + myPizza.getPrice()); } }
c5fc2cbf01243395d2c20e56587204981e0c8e38
[ "Java" ]
1
Java
jmintegr1/Gordon
8e214bb3e155e12b50bbe8b151c7f62ddbddd404
c2af08bb004c91ba5fca95c98844670a88c8f6ca
refs/heads/master
<repo_name>sielay/lackey-cms<file_sep>/modules/cms/server/lib/dust/editable.js /* jslint node:true, esnext:true */ 'use strict'; /* Copyright 2016 Enigma Marketing Services Limited 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. */ const format = require('prosemirror/dist/format'), parseFrom = format.parseFrom, atomus = require('atomus'), toHTML = format.toHTML, toText = format.toText, treeParser = require('../../../shared/treeparser'); let LackeySchema, HeadingSchema; function schema(type) { switch (type) { case 'heading': return HeadingSchema; default: return LackeySchema; } } function fromLayout(root, path, variant, locale, type, route, toFormat) { let output = treeParser.get(root, path, variant, null, locale); if (!output) { return ''; } try { if(typeof output === 'string') { output = parseFrom(schema(type), output, 'markdown'); } else { output = parseFrom(schema(type), output, 'json'); } output = treeParser.walk(output); output = (toFormat === 'text' ? toText : toHTML)(output, { serverSide: true, uri: route }); } catch (e) { let original = output; output = e.message + '<br/>'; output += 'Variant: ' + variant + '<br/>'; output += 'Locale: ' + locale + '<br/>'; output += 'Type: ' + type + '<br/>'; output += 'Path: ' + path + '<br/>'; output += 'Output: ' + JSON.stringify(original); } return output; } module.exports = (dust) => { dust.helpers.editable = function (chunk, context, bodies, params) { let editMode = params.editMode, content = params.content, id = content ? content.id + '' : '', layout = content ? content.layout : {}, variant = params.variant, path = params.path || null, parent = params.parent || null, type = params.type || 'doc', def = params.default || '', locale = context.get('locale'); if (parent) { path = parent + '.' + path; } if (editMode === true) { chunk.write('<div data-lky-pm data-lky-content="' + id + '"'); if (params.path) { chunk.write('div data-lky-path="' + path + '"'); } if (params.type) { chunk.write(' data-lky-type="' + type + '"'); } if (variant) { chunk.write(' data-lky-variant="' + variant + '"'); } chunk.write('></div>'); } else { try { if (layout && layout.type) { layout = fromLayout(layout, path, variant, locale, type, params.route); let regexMulti = /<dust-template(.+?)template=('|")(.*?)('|")(.+?)<\/dust-template>/g, regexSingle = /<dust-template(.+?)template=('|")(.*?)('|")(.+?)<\/dust-template>/, matches = layout.match(regexMulti); if (!matches || matches.length === 0) { if (type === 'heading') { layout = layout.replace(/<(\/|)p>/g, ''); } if (layout.replace(/\s+/g, '').length === 0) { layout = def; } return chunk.write(layout); } else { return chunk.map((injectedChunk) => { Promise.all(matches.map((match) => { let innerMatches = match.match(regexSingle); return new Promise((resolve) => { dust.render(innerMatches[3], context, (error, result) => { if (error) { return resolve({ original: match, replace: error.message }); } resolve({ original: match, replace: result }); }); }); })).then((results) => { results.forEach((result) => { layout = layout.replace(result.original, result.replace); }); if (type === 'heading') { layout = layout.replace(/<(\/|)p>/g, ''); } injectedChunk.write(layout); injectedChunk.end(); }, (error) => { throw error; }); }); } } else { return chunk; } } catch (error) { throw error; } } return chunk; }; }; module.exports.fromLayout = fromLayout; module.exports.browser = new Promise((resolve, reject) => { atomus().html('<html></html>').ready(function (errors, window) { try { if (errors) { return reject(errors); } GLOBAL.window = window; GLOBAL.navigator = window.navigator; GLOBAL.document = window.document; LackeySchema = require('../../../shared/content-blocks').LackeySchema; HeadingSchema = require('../../../shared/inline'); window.LackeySchema = LackeySchema; resolve(window); } catch (err) { return reject(err); } }); }); <file_sep>/modules/cms/shared/youtube.js /* jslint node:true, esnext:true */ 'use strict'; const regex = new RegExp('(https?://)?(www\\.)?(youtu\\.be/|youtube\\.com/)?((.+/)?(watch(\\?v=|.+&v=))?(v=)?)([\\w_-]{11})(&.+)?'); module.exports = (url) => { if(!url) { return null; } var match = url.match(regex); if(match && url.match(new RegExp('(youtu\\.be/|youtube\\.com/)'))) { return match[9]; } return null; }; <file_sep>/modules/cms/client/js/wysiwyg.js /* eslint no-cond-assign:0 */ /* jslint browser:true, node:true, esnext:true */ 'use strict'; /* Copyright 2016 Enigma Marketing Services Limited 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 */ const lackey = require('core/client/js'), LackeySchema = require('cms/shared/content-blocks').LackeySchema, InlineSchema = require('cms/shared/inline'), edit = require('prosemirror/dist/edit'), Media = require('cms/client/js/media'), ProseMirror = edit.ProseMirror; require('prosemirror/dist/menu/tooltipmenu'); require('prosemirror/dist/menu/menubar'); let pool = [], style = ` .ProseMirror-tooltip, .ProseMirror-menu-dropdown-menu, .ProseMirror-menubar, .ProseMirror-prompt { font-size: 12px; } `, styleBlock = document.createElement('style'); styleBlock.innerHTML = style; document.body.appendChild(styleBlock); class Wysiwyg { constructor(div) { var self = this; this._div = div; this._changed = false; this._wrap = div.getAttribute('data-lky-type') || 'doc'; this.variant = div.getAttribute('data-lky-variant') || '*'; this._placeholder = div.getAttribute('placeholder') || 'Type here'; this._schema = LackeySchema; if (this._wrap === 'inline') { this._schema = InlineSchema; } this._contentId = div.getAttribute('data-lky-content'); this._path = div.getAttribute('data-lky-path') || null; top.Lackey .manager .get(this.contentId, this.path, this.variant, this._schema) .then(function (source) { self._source = source; self.render(); top.Lackey.manager.on('reset', (event) => { if (event.data.type === 'content' && +event.data.id === +self._contentId) { top.Lackey .manager .get(self.contentId, self.path, self.variant, self._schema) .then((src) => { self._source = src; self._lock = true; self._pm.setContent(src, 'json'); self._lock = false; }); } }); }); } get contentId() { return this._contentId; } get path() { return this._path; } ready() { } isEmpty() { return (this._pm.getContent('text').replace(/^\s+|\s+$/g, '').length === 0); } render() { this._div.style.minHeight = '50px'; let pm, self = this, options = { place: this._div, schema: self._schema, docFormat: typeof this._source === 'string' ? 'text' : 'json', doc: this._source }; try { this._pm = pm = new ProseMirror(options); let overlay = document.createElement('div'); overlay.style.pointeEvents = 'none'; overlay.style.position = 'absolute'; overlay.style.display = 'none'; overlay.innerText = this._placeholder; overlay.style.width = '100%'; overlay.style.opacity = 0.5; overlay.style.textAling = 'center'; this._div.parentNode.insertBefore(overlay, this._div); if (!window.getComputedStyle(overlay.parentNode).position) { overlay.parentNode.style.position = 'relative'; overlay.style.transform = 'translateY(-50%)'; overlay.style.top = '50%'; } if (self.isEmpty()) { overlay.style.display = 'block'; } pm.on('focus', function () { overlay.style.display = 'none'; }); pm.on('blur', function () { if (self.isEmpty()) { overlay.style.display = 'block'; } }); pm.setOption('tooltipMenu', { selectedBlockMenu: true }); /*pm.setOption('menuBar', { float: true });*/ pm.on('change', function () { if (this._lock) { return; } self._changed = true; let newContent = pm.getContent('json'); top.Lackey.manager.set(self.contentId, self.path, self.variant, newContent); }); } catch (error) { console.error('this', this); console.error(error.stack); throw error; } } static factory(div) { return new Wysiwyg(div); } static init() { if(!top.Lackey || !top.Lackey.manager) { setTimeout(() => { Wysiwyg.init(); }, 250); return; } lackey.getWithAttribute('data-lky-pm').forEach(Wysiwyg.factory); lackey.select('[data-lky-media]').forEach((element) => { let media = new Media(element); media.selected((mediaObject) => { top.Lackey.manager.stack .inspectMedia(mediaObject.media, mediaObject.node) .then((result) => { if (result || result === -1) { mediaObject.set(result !== -1 ? result : null); mediaObject.notify(); } }); }); }); } static getContents() { let content = []; pool.forEach((instance) => { if (content.indexOf(instance.contentId) === -1) { content.push(instance.contentId); } }); return content; } static get pool() { return pool; } } module.exports = Wysiwyg; <file_sep>/modules/cms/shared/widgets/dust.js /* jslint node:true, esnext:true */ 'use strict'; /* Copyright 2016 Enigma Marketing Services Limited 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. */ const model = require('prosemirror/dist/model'), dom = require('prosemirror/dist/dom'), Inline = model.Inline, Attribute = model.Attribute, elt = dom.elt; class Dust extends Inline { get attrs() { return { template: new Attribute('') }; } } Dust.register('parseDOM', 'dust-template', { rank: 25, parse: function (domObj, state) { let type = domObj.getAttribute('template'); if (!type) { return false; } state.insert(this, { type }); } }); Dust.prototype.serializeDOM = node => elt('dust-template', { 'template': node.attrs.template }, node.attrs.template); Dust.register('command', 'insert', { derive: { params: [{ label: 'Template', attr: 'template', type: 'text' }] }, label: 'Insert dust template' }); Dust.register('insertMenu', 'main', { label: 'Dust', command: 'insert', rank: 1 }); module.exports.Dust = Dust; <file_sep>/modules/cms/client/js/snippet.js /* jslint node:true, esnext:true */ 'use strict'; /* Copyright 2016 Enigma Marketing Services Limited 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. */ const LackeySchema = require('cms/shared/content-blocks').LackeySchema, format = require('prosemirror/dist/format'), toText = format.toText, parseFrom = format.parseFrom; module.exports = (dust) => { dust.helpers.snippet = function (chunk, context, bodies, params) { let source = params.source || { 'type': 'doc' }, limit = params.limit || 100, text = toText(parseFrom(LackeySchema, source, 'json')).substring(0, limit); return chunk.write(text); }; }; <file_sep>/lib/server/init/falcor.js /*jslint node:true, unparam:true, regexp:true, esnext:true */ 'use strict'; /* Copyright 2016 Enigma Marketing Services Limited 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. */ const falcorExpress = require('falcor-express'), Router = require('falcor-router'); let LackeyRouter; module.exports = (server) => { /* istanbul ignore next : external */ let handler = (req) => { /* istanbul ignore next : external */ return new LackeyRouter(req.user); }; server.decorateMiddleware(['/model.json', falcorExpress.dataSourceRoute(handler)], 'falcor'); return function (routes) { let RouterBase = Router.createClass(routes); LackeyRouter = function (user) { RouterBase.call(this); this.user = user; }; LackeyRouter.prototype = Object.create(RouterBase.prototype); return LackeyRouter; }; }; <file_sep>/test/lib/server/init/falcor.test.js /* jslint node:true, esnext:true */ 'use strict'; /* Copyright 2016 Enigma Marketing Services Limited 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. */ const should = require('should'), middleware = require('../../../../lib/server/init/falcor'); describe('lib/server/init/falcor', () => { it('Works', () => { let server = { decorateMiddleware: (args, label) => { label.should.be.eql('falcor'); args.length.should.be.eql(2); args[0].should.be.eql('/model.json'); args[1].should.be.Function; } }, route = { route: 'pages.byPath[{keys:path}]', get: function () {} }, Router = middleware(server)([route]), router = new Router(1); router.user.should.be.eql(1); }); });
9f1e88c4ccb5ba759a18a24d3f29841dc104c0d7
[ "JavaScript" ]
7
JavaScript
sielay/lackey-cms
57c8140e306a405eaae2f0be52ca4aa1c9b45387
e7adbf0d7220517c1b4bb2e9ceecfe4a28fc779c
refs/heads/master
<repo_name>sunnyside0907/bubbletest<file_sep>/django_bookmarkss/bookmarks/views.py from django.http import HttpResponse from django.template import Context from django.template.loader import get_template from django.shortcuts import render, HttpResponse from bookmarks import views from django.http import HttpResponse, Http404 from django.contrib.auth.models import User from django.shortcuts import render # Create your views here. def main_page(request): template = get_template('main_page.html') variables = Context({ 'head_title':'장고 북마크', 'page_title':',wkdrh qnrakzmdp dhtlsrjtdmf ghksdud', 'page_body':'북마크 저장해라', }) output = template.render(variables) return HttpResponse(output) def hello(request): return HttpResponse("첫번째 만든 웹페이지") def user_page(request,username): try: user = User.objects.get(username=username) except: raise Http404('사용자 찾을수 없음') bookmarks = user.bookmark_set.all() template = get_template('main_page.html') variables = Context({ 'username' : username, 'bookmarks': bookmarks }) output = template.render(variables) return HttpResponse(output) <file_sep>/django_bookmarks/bookmarks/views.py from django.shortcuts import render from django.http import HttpResponse # Create your views here. def main_page(request): return HttpResponse("첫번째 만든 웹페이지") <file_sep>/mysite/bookmark/admin.py from django.contrib import admin from bookmark.models import Bookmark # Register your models here. #관리자 사이트에서 Bookmark 클래스 출력 모양 정의하는 코드 @admin.register(Bookmark) class BookmarkAdmin(admin.ModelAdmin): #관리자 화면에 출력할 필드 목록(튜플형식) list_display=('id','title','url') #Bookmark 클래스와 BookmarkAdmin 클래스 등록 #admin.site.register(Bookmark, BookmarkAdmin) @admin.register(Bookmark)와 동일 <file_sep>/README.md # bubbletest bubble 공부용 <file_sep>/pyboard/board/views.py import os import math import socket from datetime import datetime from django.http.response import HttpResponse from django.http import HttpResponseRedirect from django.shortcuts import render, redirect, get_object_or_404 from django.utils.http import urlquote from django.views.decorators.csrf import csrf_exempt from board.models import Board, Comment #model.py에 있는 테이블 사용 from django.db.models import Q #Q()| 사용 from django.core.paginator import * from . import models from django.views.generic import ListView UPLOAD_DIR = "/Users/chaehyejin/Documents/bubblegit/bubbletest/pyboard/upload" # upload 폴더정보 # Create your views here. # 글 읽기 페이지 작성 @csrf_exempt def list(request): # 검색하기 try: search_option = request.POST["search_option"] except: search_option = "" try: search = request.POST["search"] except: search="" if search_option == "all": boardCount = Board.objects.filter( Q(writer__contains = search) | Q(title__contains = search) | Q(content__contains = search) ).count() elif search_option == "writer": boardCount = Board.objects.filter(writer__contains = search).count() elif search_option == "title": boardCount = Board.objects.filter(title__contains = search).count() elif search_option == "content": boardCount = Board.objects.filter(content__contains = search).count() else: boardCount = Board.objects.all().count() try: start = int(request.GET['start']) except: start = 0 page_size = 1000 block_size = 10 end = start+page_size if search_option == "all": boardList = Board.objects.filter( Q(writer__contains=search) | Q(title__contains=search) | Q(content__contains=search) ).order_by('-idx')[start:end] elif search_option == "writer": boardList = Board.objects.filter(writer__contains = search).order_by('-idx')[start:end] elif search_option == "title": boardList = Board.objects.filter(title__contains = search).order_by('-idx')[start:end] elif search_option == "content": boardList = Board.objects.filter(content__contains = search).order_by('-idx')[start:end] else: boardList = Board.objects.all().order_by('-idx')[start:end] # 페이지 네이션 paginator = Paginator(boardList,5) try: page = request.GET.get('page') except: page = 1 try: boardList = paginator.page(page) except PageNotAnInteger: boardList = paginator.page(1) except EmptyPage: boardList = paginator.page(paginator.num_pages) contacts = paginator.get_page(page) page_range = 5 current_block = math.ceil((start+1)/page_range) if contacts.number > 5 : start_block = (current_block-1)*page_range+5 else : start_block = (current_block-1)*page_range end_block = start_block + page_range p_range = paginator.page_range[start_block:end_block] return render(request, "list.html", {"boardList":boardList, "boardCount":boardCount, "search_option":search_option, "search":search, 'contacts':contacts, 'p_range':p_range, } ) #fileter where Q() 는 %% like 검색 # 글쓰기 페이지 작성 def write(request): return render(request,"write.html") # 글쓰기 저장 @csrf_exempt def insert(request): fname = "" fsize = 0 if "file" in request.FILES: file=request.FILES["file"] fname = file.name fsize = file.size fp=open("%s%s" % (UPLOAD_DIR, fname), "wb") for chunk in file.chunks(): fp.write(chunk) fp.close() dto = Board( writer=request.POST["writer"],title=request.POST["title"], content=request.POST["content"], filename=fname,filesize=fsize ) dto.save() print(dto) return redirect("/") # 파일 다운로드 def download(request): id=request.GET['idx'] dto=Board.objects.get(idx=id) path = UPLOAD_DIR+dto.filename print("path:",path) filename= os.path.basename(path) filename = filename.encode("utf-8") filename = urlquote(filename) print("pfilename:",os.path.basename(path)) with open(path, 'rb') as file: response = HttpResponse(file.read(), content_type="application/octet-stream") response["Content-Disposition"] = "attachment; filename*=UTF-8''{0}".format(filename) dto.down_up() dto.save() return response # 상세보기 - 조회수 증가 처리 def detail(request): id = request.GET["idx"] dto = Board.objects.get(idx=id) dto.hit_up() dto.save() commentList = Comment.objects.filter(board_idx = id).order_by("idx") print("filesize:",dto.filesize) #filesize = "%0.2f" % (dto.filesize / 1024) 1024로 나눠서 반올림한 값으로 표시해주기 filesize = "%.2f"%(dto.filesize/1024) return render(request, "detail.html",{ "dto":dto,"filesize":filesize, "commentList":commentList }) # 수정하기 @csrf_exempt def update(request): print("**") #글번호 #id = request.POST["idx"] # 이건 에러뜨고 아래꺼는 ㄱㅊ... id = request.POST.get('idx',False) # select * from board_board where idx=id dto_src = Board.objects.get(idx=id) dto_src.save() # 수정시 조회수, 다운로드 수 날라가는거 방지 hitnum = dto_src.hit downnum = dto_src.down fname = dto_src.filename # 기존 첨부파일 이름 fsize = dto_src.filesize # 기존 첨부파일 크기 if "file" in request.FILES: # 새로운 첨부파일이 있으면 file = request.FILES["file"] fname = file.name # 새로운 첨부파일 이름 fsize = file.size fp = open("%s%s" % (UPLOAD_DIR, fname), "wb") for chunk in file.chunks(): fp.write(chunk) # 파일 저장 fp.close() # 첨부파일 크기 ( 업로드 완료 후 계산 fsize = os.path.getsize(UPLOAD_DIR+fname) # 수정 후 board의 내용 dto_new = Board(idx=id, writer=request.POST["writer"], title=request.POST["title"], content=request.POST["content"], filename=fname, filesize=fsize, hit=hitnum, down=downnum ) dto_new.save() # update query 호출 return redirect("/") # 시작페이지로 이ddong # 삭제하기 @csrf_exempt def delete(request): #삭제할 게시글 번호 id = request.POST["idx"] #레코드 삭제 Board.objects.get(idx=id).delete() return redirect("/") # 댓글쓰기 @csrf_exempt def reply_insert(request): id = request.POST['idx'] # 댓글 객체 생성 dto = Comment(board_idx=id, writer=request.POST["writer"],content=request.POST["content"]) # insert query 실행 dto.save() # detai?idx=글번호 페이지로 이동 return HttpResponseRedirect("detail?idx="+id) <file_sep>/mysite/bookmark/views.py from django.shortcuts import render from bookmark.models import Bookmark # Create your views here. def home(request): # select * from bookmark_bookmark order by title urlList = Bookmark.objects.order_by('title') # -title 내림차순 정렬 # select count(*) from bookmark_bookmark urlCount = Bookmark.objects.all().count() # list.html 페이지로 넘어가서 출력됨 # rander_to response("url",{"변수명","변수명"}) return render(request, 'bookmark/List.html', {'urlList':urlList, 'urlCount':urlCount}) def detail(request): # get 방식 변수 받아오기 request.GET["변수명"] # post방식 변수 받아오기 request.POST["변수명"] addr = request.GET['url'] # 변수가 url 인것임 # select * from bookmark_bookmark where url="..." dto = Bookmark.objects.get(url = addr) # get() = where 1개의 데이터 얻음. # detail.html로 포워딩 return render(request, "bookmark/detail.html",{"dto":dto})
89dc693503aac422664c2ae49d853104c2ae9feb
[ "Markdown", "Python" ]
6
Python
sunnyside0907/bubbletest
e357dd1b9992047be3a623e82882588973eab2e4
0b6a63cb31553ccf1b74c3c2643f97501a6d3967
refs/heads/main
<repo_name>glhermepaiva/Fillet-Frontend<file_sep>/src/Styles.js import styled from 'styled-components' export const Body = styled.div` background-color: rgb(231, 232, 246); width: 100vw; height: 100vh; display: flex; align-items: center; justify-content: center; ` export const Sidebar = styled.div` width: 19vw; height: 70vh; background-color: rgb(76, 84, 255); ` export const Main = styled.div` width: 35vw; height: 70vh; background-color: rgb(249, 249, 249); display: flex; align-items: center; justify-content: center; flex-direction: column; flex-wrap: wrap; padding: 0 3vw; ` export const SignUpText = styled.h1` color: rgb(255, 85, 218); font-size: 3vw; align-self: flex-start; margin: 0; user-select: none; ` export const InputContainer = styled.div` margin: 1vw -1vw 2vw -1vw; ` export const MainLoading = styled.div` width: 35vw; height: 70vh; background-color: rgb(249, 249, 249); display: flex; align-items: center; justify-content: center; flex-direction: column; flex-wrap: wrap; padding: 0 3vw; font-size: 10vw; `<file_sep>/README.md # **Fillet Front-end** ## Stack Esse é um projeto de Front-end Web no formato Single Page Application feito utilizando React.js, HTML e CSS. Foi utilizado a biblioteca Axios para requisições com a API, Material-UI e Styled Components para estilização. ## Sobre O projeto se trata de uma tela de cadastro simples onde o usuário deve informar seu primeiro e último nome, telefone, email e senha. ## Instruções para rodar Acessar o site https://filletfullstack.surge.sh ## Link para parte Backend do projeto https://github.com/glhermepaiva/Fillet-Backend ## Contato https://www.linkedin.com/in/glhrmpaiva // <EMAIL>
2d11d95a94a13431dca41c8e2866284471fa07bd
[ "JavaScript", "Markdown" ]
2
JavaScript
glhermepaiva/Fillet-Frontend
63943f9a3ef8ff3ba1396040a01886cba80c5a8a
1ef364c70f0046eb638845f032212d7523c768e1
refs/heads/master
<file_sep># Test-Driven-Development-Sutras [「テスト駆動開発」](https://www.amazon.co.jp/テスト駆動開発-Kent-Beck/dp/4274217884/)の写経 # 参考情報 * [t_wadaさんの講演](https://dev.classmethod.jp/study_meeting/read/what-tdd/) * FizzBuzzの要件を分解してToDoリストにする過程をみると勉強になる * 落ちると想定したものが落ちる(予想通りに落ちる)ことが大切 => 予想外なところで落ちたときや落ちた時はTDDの準備ができていないことが分かる * 初心者のテストの書き方 * 「前準備」=>「実行」=>「検証」で「検証」からブレークダウンしていくのが良い * テストのためのテスト => 三角測量 # メモ * 動作する、きれいなコード - 動作する <=> 動作しない - きれいな <=> きたない - 2つの方法がある - きれいな => 動作する(従来の開発方法) * 設計を終えて実装してみると、様々なフィードバックが得られる => 動かしてみないとわからない - 動作する => きれいな * * テスト駆動開発とはRed => Green => Refactorのサイクル - リファクタリングがちゃんと行われないと、テスト駆動の力が失われてしまう - リファクタリングは経営者からみると美味しくない - リファクタリングを開発のサイクルに入れてしまうことで解決 * 「仮実装」と「明白な実装」 ベタ書きの値を使うのが「仮実装」、簡単に思いつく頭の中の実装が「明白な実装」 # 考えるべきこと * SpringBootで開発するときどうすればいいのか<file_sep>package money; import java.util.HashMap; import java.util.Map; public class Bank { private Map<Pair, Integer> rates = new HashMap<>(); public Money reduce(Expression source, String to) { // ポリモーフィズム return source.reduce(this, to); // if(source instanceof Money) { // return ((Money) source).reduce(to); // } // Sum sum = (Sum) source; // return sum.reduce(to); } public void addRate(String from, String to, int rate) { rates.put(new Pair(from, to), rate); } public int rate(String from, String to) { if(from.equals(to)) return 1; return rates.get(new Pair(from, to)); } }
e0b2859e4be2273a7db42f54aa7319515e301e8a
[ "Markdown", "Java" ]
2
Markdown
genkiFurukawa/Test-Driven-Development-Sutras
1f4104264d25992e7317c7c1447e76954079be79
19ab3888ec8bce85ea53db6df4b8cb8c281d149b
refs/heads/master
<repo_name>hanavi/commercialtimer<file_sep>/main.py #!/usr/bin/env python3 # -*- coding: utf-8 -*- import logging from flask import Flask, request from datetime import datetime logging.basicConfig(level=logging.WARNING) logger = logging.getLogger("working") app = Flask(__name__, static_folder='') @app.route("/") def main(): return app.send_static_file("main.html") @app.route("/ct.css") def css(): return app.send_static_file("ct.css") @app.route("/ct.js") def js(): return app.send_static_file("ct.js") @app.route("/startcommercial") def start_commercial(): date = datetime.now().strftime("%a %b %-d %T CDT %Y") with open("log.txt", "a") as fd: fd.writelines(f"{date} start commercial\n") with open("log.txt", "r") as fd: ret = '' for line in fd.readlines()[-10:]: ret += line + "<br />" return ret @app.route("/endcommercial") def end_commercial(): date = datetime.now().strftime("%a %b %-d %T CDT %Y") with open("log.txt", "a") as fd: fd.writelines(f"{date} end commercial\n") with open("log.txt", "r") as fd: ret = '' for line in fd.readlines()[-10:]: ret += line + "<br />" return ret if __name__ == "__main__": app.run() <file_sep>/ct.js function start_commercial() { var xhr = new XMLHttpRequest(); var url = "http://localhost:5000/startcommercial"; xhr.open("GET", url, true); xhr.onreadystatechange = function () { if (xhr.readyState === 4 && xhr.status === 200) { // var ret = xhr.responseText // console.log(ret) document.getElementById("main").innerHTML = xhr.responseText; } }; xhr.send(); start_timer(true); timerid = setInterval(start_timer, 1000); window.timerid = timerid; } function pad(n, width, z) { z = z || '0'; n = n + ''; return n.length >= width ? n : new Array(width - n.length + 1).join(z) + n; } function end_commercial() { var xhr = new XMLHttpRequest(); var url = "http://localhost:5000/endcommercial"; xhr.open("GET", url, true); xhr.onreadystatechange = function () { if (xhr.readyState === 4 && xhr.status === 200) { // var ret = xhr.responseText // console.log(ret) document.getElementById("main").innerHTML = xhr.responseText; } }; xhr.send(); start_timer(true); timerid = setInterval(start_timer, 1000); window.timerid = timerid; } function start_timer(new_timer=false) { if (new_timer == true) { if (typeof window.timerid !== 'undefined') { clearInterval(window.timerid); last_timer = document.getElementById("timer").innerHTML; last_timer = "Last timer: " + last_timer; document.getElementById("timer-last").innerHTML = last_timer; } start_time = "00:00"; document.getElementById("timer").innerHTML = start_time; } else { start_time = document.getElementById("timer").innerHTML; var min, sec; min = start_time.split(":")[0]; sec = start_time.split(":")[1]; min = parseInt(min); sec = parseInt(sec); sec += 1; if (sec == 60) { sec = 0; min += 1; } new_time = pad(min,2) + ":" + pad(sec,2); document.getElementById("timer").innerHTML = new_time; } }
d2e53aa6bb70c9d524d0c757225e21bb0e89d318
[ "JavaScript", "Python" ]
2
Python
hanavi/commercialtimer
1dea795852086e0cd922eeef03159b121721fa4a
ef9f40c1beff4cfb7accfc6ee4958c33ae082e0b
refs/heads/main
<file_sep>const mongoose = require('mongoose') const Schema = mongoose.Schema const favoriteSchema = new Schema({ author : { type : mongoose.Schema.Types.ObjectId, ref : 'User' }, dishes : [{ type : mongoose.Schema.Types.ObjectId, ref: 'Dish' }] },{ timestamps : true }) let Favorites = mongoose.model('Favorite', favoriteSchema) module.exports = Favorites <file_sep>var express = require('express'); const bodyParser = require('body-parser') const User = require('../models/users') const passport = require('passport'); const authenticate = require('../authenticate'); const cors = require('./cors') const router = express.Router(); router.use(bodyParser.json()) /* GET users listing. */ router.get('/',cors.corsWithOprions, authenticate.verifyUser, authenticate.verifyAdmin, function(req, res, next) { User.find({}) .then((users) => { res.statusCode = 200 res.setHeader('Content-Type', 'application/json') res.json(users) }, (err) => next(err) ) .catch ((err) => {next(err)}) }); router.post('/signup',cors.corsWithOprions, (req, res, next) => { const data = req.body console.log('data', data) // User.findOne({username : data.username}) User.register(new User({username : data.username}),data.password, (err, user) => { if( err ){ res.statusCode = 500 res.setHeader('Content-Type' , 'application/json') res.json({err : err}) } else{ if (data.firstname){ user.firstname = data.firstname } if(data.lastname){ user.lastname = data.lastname } user.save((err, user) => { if (err) { res.statusCode = 500 res.setHeader('Content-Type' , 'application/json') res.json({err : err}) } passport.authenticate('local')(req, res, () => { res.statusCode = 200 res.setHeader('Content-Type' , 'application/json') res.json({success : true, status : 'Registeration successfull', user : user}) }) }) } }) }) router.post('/login',cors.corsWithOprions, passport.authenticate('local'),(req, res, next) => { const token = authenticate.getToken({_id : req.user._id}) res.statusCode = 200 res.setHeader('Content-Type' , 'application/json') res.json({success : true, status : 'Login successfull', token : token}) }) router.get('/logout',cors.corsWithOprions, (req ,res , next) => { if ( req.session ){ req.session.destroy() res.clearCookie('session-id') res.redirect('/') } else{ let err = new Error ("Your are not logged in!") err.status = 403 return next(err) } }) router.get('/facebook/token', passport.authenticate('facebook-token'), (req, res, next) => { if (req.user){ const token = authenticate.getToken({_id : req.user._id}) res.statusCode = 200 res.setHeader('Content-Type' , 'application/json') res.json({success : true, status : 'Login successfull', token : token}) } }) module.exports = router; <file_sep># Restaurant-demo This conFusion poject, it's an API created using Node, Express, mongoDb <file_sep>const express = require('express') const bodyParser = require('body-parser') const authenticate = require('../authenticate') const Promotions = require('../models/promotions') const cors = require('./cors') const promotionsRouter = express.Router() promotionsRouter.use(bodyParser.json()) promotionsRouter.route('/') .options(cors.corsWithOprions, (req, res) => {res.sendStatus(200)}) .get(cors.cors, (req, res, next) => { Promotions.find({}) .then((promotions) => { res.statusCode = 200 res.setHeader('Content-Type', 'application/json') res.json(promotions) }, (err) => next(err) ) .catch ((err) => {next(err)}) }) .post(cors.corsWithOprions, authenticate.verifyUser, authenticate.verifyAdmin, (req, res, next) => { Promotions.create(req.body) .then((promotion) => { console.log('promotion created: ', promotion) res.statusCode = 200 res.setHeader('Content-Type', 'application/json') res.json(promotion) }, (err) => next(err) ) .catch ((err) => {next(err)}) }) .put(cors.corsWithOprions, authenticate.verifyUser, authenticate.verifyAdmin, (req, res, next) => { res.statusCode = 403 res.end('PUT is not supported') }) .delete(cors.corsWithOprions, authenticate.verifyUser, authenticate.verifyAdmin, (req, res, next) => { Promotions.deleteMany({}) .then((resp) => { res.statusCode = 200; res.setHeader('Content-Type', 'application/json'); res.json(resp); }, (err) => next(err)) .catch((err) => next(err)); }); promotionsRouter.route('/:promotionId') .options(cors.corsWithOprions, (req, res) => {res.sendStatus(200)}) .get(cors.cors, (req,res,next) => { const promotionId = req.params.promotionId Promotions.findById(promotionId, ) .then((promotion) => { res.statusCode = 200 res.setHeader('Content-Type', 'application/json') res.json(promotion) }, (err) => next(err) ) .catch ((err) => {next(err)}) }) .post(cors.corsWithOprions, authenticate.verifyUser, authenticate.verifyAdmin, (req, res, next) => { res.statusCode = 403; res.end('POST operation not supported on /Promotions/'+ req.params.promotionId); }) .put(cors.corsWithOprions, authenticate.verifyUser, authenticate.verifyAdmin, (req, res, next) => { const promotionId = req.params.promotionId const updatedData = req.body Promotions.findOneAndUpdate(promotionId, { $set : updatedData }, { new : true }) .then((promotion) => { res.statusCode = 200 res.setHeader('Content-Type', 'application/json') res.json(promotion) }, (err) => next(err) ) .catch ((err) => {next(err)}) }) .delete(cors.corsWithOprions, authenticate.verifyUser, authenticate.verifyAdmin, (req, res, next) => { const promotionId = req.params.promotionId Promotions.findOneAndRemove(promotionId) .then((resp) => { res.statusCode = 200 res.setHeader('Content-Type', 'application/json') res.json(resp) }, (err) => console.log('err', err)) .catch((err) => console.log('err', err)) }) module.exports = promotionsRouter
5a9ce8d3c76bdb5fe1b1e61b613da2a207abd136
[ "JavaScript", "Markdown" ]
4
JavaScript
AhmedElsayed101/RestaurantAPI
11b516addc7b50821915bfa1e67a295a00f76606
5988bdb5340b9f4ad6963737535ee48fb3b1240d
refs/heads/master
<repo_name>dermeister/expression-calculator<file_sep>/src/index.js function eval() { // Do not use eval!!! return; } const toPolish = function(tokens) { const priority = { "*": 2, "/": 2, "+": 1, "-": 1 }; const stack = []; let result = ""; for (const token of tokens) { if (Number.isInteger(+token)) result += `${token} `; if (token === "(") stack.push(token); if (token === ")") { while (stack[stack.length - 1] !== "(") { if (stack.length === 0) throw new Error("ExpressionError: Brackets must be paired"); result += `${stack.pop()} `; } stack.pop(); } if (token in priority) { while (priority[stack[stack.length - 1]] >= priority[token]) { result += `${stack.pop()} `; } stack.push(token); } } while (stack.length > 0) { if (stack[stack.length - 1] === "(") throw new Error("ExpressionError: Brackets must be paired"); result += `${stack.pop()} `; } return result; }; const evaluate = expr => { const operators = { "+": (x, y) => x + y, "-": (x, y) => x - y, "*": (x, y) => x * y, "/": (x, y) => { if (y == 0) throw new Error("TypeError: Devision by zero."); return x / y; } }; let stack = []; expr .split(" ") .filter(token => Boolean(token)) .forEach(token => { if (token in operators) { let [y, x] = [stack.pop(), stack.pop()]; stack.push(operators[token](x, y)); } else { stack.push(parseFloat(token)); } }); return stack.pop(); }; const normalizeExpr = function(polish) { const operatorSymbols = ["*", "-", "+", "/", "(", ")"]; return polish .split("") .map(token => (operatorSymbols.includes(token) ? ` ${token} ` : token)) .join("") .split(" ") .filter(token => token !== ""); }; function expressionCalculator(expr) { return evaluate(toPolish(normalizeExpr(expr))); } module.exports = { expressionCalculator };
774c96e091f07d600715045bf22cabda64d2e14c
[ "JavaScript" ]
1
JavaScript
dermeister/expression-calculator
0fee44d343b8ee359c9dad63717841d5d01a303e
826fc3657d9ea964301683d04e1f26292f43a025
refs/heads/master
<repo_name>johnmcconnell/cal<file_sep>/README.md # cal: Go (golang) calendar library for dealing with holidays and work days [![Build Status](https://travis-ci.org/johnmcconnell/cal.svg?branch=master)](https://travis-ci.org/johnmcconnell/cal) This library augments the Go time package to provide easy handling of holidays and work days (business days). Holiday instances can be exact days, floating days such as the 3rd Monday of the month, or yearly offsets such as the 100th day of the year. The Calendar type provides functions for calculating workdays and dealing with holidays that are observed on alternate days when they fall on weekends. <file_sep>/holiday.go // (c) 2014 <NAME>. Licensed under the BSD license (see LICENSE). package cal import ( "time" ) // ObservedRule represents a rule for observing a holiday that falls // on a weekend. type ObservedRule int // Observence const ( ObservedNearest ObservedRule = iota // nearest weekday (Friday or Monday) ObservedExact // the exact day only ObservedMonday // Monday always ) // United States holidays var ( USNewYear = NewHoliday(time.January, 1) USMLK = NewHolidayFloat(time.January, time.Monday, 3) USPresidents = NewHolidayFloat(time.February, time.Monday, 3) USMemorial = NewHolidayFloat(time.May, time.Monday, -1) USIndependence = NewHoliday(time.July, 4) USLabor = NewHolidayFloat(time.September, time.Monday, 1) USColumbus = NewHolidayFloat(time.October, time.Monday, 2) USVeterans = NewHoliday(time.November, 11) USThanksgiving = NewHolidayFloat(time.November, time.Thursday, 4) USChristmas = NewHoliday(time.December, 25) ) // Holiday holds information about the yearly occurrence of a holiday. // // A valid Holiday consists of: // - Month and Day (such as March 14 for Pi Day) // - Month, Weekday, and Offset (such as the second Monday of October for Columbus Day) // - Offset (such as the 183rd day of the year for the start of the second half) type Holiday struct { Month time.Month Weekday time.Weekday Day int Offset int } // NewHoliday creates a new Holiday instance for an exact day of a month. func NewHoliday(month time.Month, day int) Holiday { return Holiday{Month: month, Day: day} } // NewHolidayFloat creates a new Holiday instance for an offset-based day of // a month. func NewHolidayFloat(month time.Month, weekday time.Weekday, offset int) Holiday { return Holiday{Month: month, Weekday: weekday, Offset: offset} } // Matches determines whether the given date is the one referred to by the // Holiday. func (h *Holiday) Matches(date time.Time) bool { if h.Month > 0 { if date.Month() != h.Month { return false } if h.Day > 0 { return date.Day() == h.Day } if h.Weekday > 0 && h.Offset != 0 { r := IsWeekdayN(date, h.Weekday, h.Offset) return r } } else if h.Offset > 0 { return date.YearDay() == h.Offset } return false }
c05b16ade6082f881560a7ef978afa7356316dea
[ "Markdown", "Go" ]
2
Markdown
johnmcconnell/cal
a9c16c40ddd7fb8887e54e71c68300efe8ab9600
d2c3752e8eae6f171349feb10740351ff5ca69c0
refs/heads/master
<repo_name>marcianadalim/Mytodolist2<file_sep>/app/src/main/java/com/example/mytodolist2/contacts.kt package com.example.mytodolist2 class Message(val id:String, val name: String, val message:String)
9ecae2570f32c3aa3419a4492d71196a0abaeaee
[ "Kotlin" ]
1
Kotlin
marcianadalim/Mytodolist2
911eedb6ee85a5ea940ca0cc973856f9b46fd348
8700aba658872b286687e729ee1c0623836ce1d7
refs/heads/master
<file_sep>#include <stdio.h> int main(void) { int num, hour, min, sec; printf("초를 입력 : "); scanf("%d", &num); hour = num / 3600; min = (num % 3600) / 60; sec = (num % 3600) % 60; printf("%d시 %d분 %d초 \n", hour, min, sec); return 0; }<file_sep>#include <stdio.h> int main(void) { int num = 0, res=0; do { res += num; num+=2; } while (num <= 100); printf("%d\n", res); return 0; }<file_sep>#include <stdio.h> int main(void) { int x; int y; int sum; printf("사각형 넓이 구하기\n"); printf("너비 입력 :"); scanf("%d", &x); printf("높이 입력:"); scanf("%d", &height); printf("넓이 : %d\n", weight * height); return 0; }<file_sep>#include <stdio.h> int main(void) { double weight; double height; double bmi; printf("몸무게를 입력하시오(kg):"); scanf("%lf", &weight); printf("키를 입력하시오(cm):"); scanf("%lf", &height); bmi = weight / height; printf("당신의 bmi는:%f\n", bmi); return 0; }<file_sep>#include <stdio.h> int main(void) { int num1, num2; printf("두 수 입력하시오 : "); scanf("%d %d", &num1, &num2); if (num1 >= num2) { printf("두 수의 차 : %d \n", num1 - num2); } else if (num2 > num1) { printf("두 수의 차 : %d \n", num2 - num1); } return 0; }<file_sep>#include <stdio.h> int main(void) { int num, i=1; printf("양의 정수를 하나 입력하시오 : "); scanf("%d", &num); while (i<=num) { printf("받아라 %d \n",i*3); i++; } return 0; }<file_sep>#include <stdio.h> int main(void) { int num; for (num = 1; num < 100; num++) { if (num % 7 == 0 || num % 9 == 0) { printf("7 또는 9의 배수 : %d \n", num); } } return 0; }<file_sep>#include <stdio.h> int main(void) { int a, b, i, j, temp; printf("두 수 입력하시오 : "); scanf("%d %d", &a, &b); if (b >= a) { temp = b; b = a; a = temp; } for (i = b; i <= a; i++) { for (j = a; j <= 9; j++) { printf("%d × %d = %d \n", i, j, i*j); } printf("\n"); } return 0; }<file_sep>#include <stdio.h> int main(void) { int w; int t; int s; printf("정수 w를 입력하시오:"); scanf("%d", &w); printf("정수 t를 입력하시오:"); scanf("%d", &t); s = w * t; printf("w=%d, t=%d, s=%d\n", w, t, s); return 0; }<file_sep>#include <stdio.h> int main(void) { int num1, num2, temp; printf("작은 수부터 두 정수 입력하시오 : "); scanf("%d %d", &num1, &num2); for (temp=0 ; num1 <= num2 ; num1++) { temp+=num1; } printf("결과 값 : %d \n", temp); return 0; }<file_sep>#include <stdio.h> int main(void) { int a, b; for (a = 2; a <= 9; a++) { for (b = 2; b <= 9; b++) { printf("%d Ąż %d = %d \n", a, b, a*b); } printf("\n"); } return 0; }<file_sep>#include <stdio.h> int main(void) { int num, temp, op; float res = 0; printf("정수 몇 개 입력하실래요 : "); scanf("%d", &num); for (temp = num; temp > 0; temp--) { printf("\n%d번째 정수를 입력하세요 : ", num - temp + 1); scanf("%d", &op); res += op; } printf("\n\n입력한 값들의 평균은 %f입니다. \n", res/num); return 0; }<file_sep>#include <stdio.h> int main(void) { int res = 0, temp = 5, num; while (temp > 0) { printf("정수를 입력하세요 : "); scanf("%d", &num); while (num >= 1) { res += num; temp--; num = 0; } } printf("5개 정수의 합은 %d입니다.\n", res); return 0; }<file_sep>#include <stdio.h> int main(void) { double printf("사각형 넓이 구하기\n"); printf("너비 입력 :"); scanf("%d", &x); printf("높이 입력:"); scanf("%d", &y); printf("넓이 : %d\n", x * y); return 0; }<file_sep>#include <stdio.h> int main(void) { int num = 5, line = 1; while (line <= 5) { num = line; while (num > 1) { printf("○"); num--; } line++; printf("#\n"); } return 0; } // 1번째 : 원 0회, 별 1회 // 2번째 : 원 1회, 별 1회 // 3번째 : 원 2회, 별 1회 // n번째 : 원 (n-1)회, 별 1회 <file_sep>#include <stdio.h> int main(void) { // 크림3개(4개) 새우 2개(3개) 콜라 4개(5개) int num, cream=4, shrimp=3, drink=5; printf("얼마 갖고 있나요 : "); scanf("%d", &num); while (shrimp >= 1) { cream = 4; while (cream >= 1) { drink = 5; while (drink >= 1) { if (cream * 500 + shrimp * 700 + drink * 400 == num) { printf("크림빵 %d개, 새우깡 %d개, 콜 라 %d개 \n", cream, shrimp, drink); } drink--; } cream--; } shrimp--; } return 0; }<file_sep>#include <stdio.h> int main(void) { int num, i=9; printf("구구단을 구할 양의 정수을 입력하시오 : "); scanf("%d", &num); while (i>=1) { printf("%d × %d = %d \n", num, i, num*i); i--; } return 0; }<file_sep>#include <stdio.h> int main(void) { int a, b, i, j; printf("두 수 입력하시오 : "); scanf("%d %d", &a, &b); for (i = a; i >= 1; i--) { if (a%i == 0) { for (j = b; j >= 1; j--) { if (b%j == 0) { if (i == j) { printf("최대 공약수 : %d \n", i); i = 0; j = 0; } } } } } return 0; }<file_sep>#include <stdio.h> int main(void) { int kor, eng, math, avr; printf("국어, 영어, 수학 점수를 입력하시오 : "); scanf("%d %d %d", &kor, &eng, &math); avr = (kor + eng + math) / 3; printf("평균 점수 %d\n", avr); if (avr >= 90) { printf("A학점\n"); } else if (avr >= 80) { printf("B학점\n"); } else if (avr >= 70) { printf("C학점\n"); } else if (avr >= 50) { printf("D학점\n"); } else { printf("F학점\n"); } }<file_sep>#include <stdio.h> int main(void) { int x; int y; int z; char score; printf("학점을 입력하세요:"); scanf("%c", &score ); printf("국어성적입력:"); scanf("%d", &x); printf("수학성적입력"); scanf("%d", &y); printf("영어성적입력:"); scanf("%d", &z); printf("총점 : %d\n", x + y + z); printf("평균 : %d\n", (x+y+z) / 3); return 0; }<file_sep>#include <stdio.h> int main(void) { int num=1, res=0, i=1; while (num!=0) { printf("양의 정수를 하나 입력하시오 : "); scanf("%d", &num); res += num; i++; } printf("%d \n", res); return 0; }<file_sep>#include <stdio.h> int main(void) { int num1, num2; printf("두 수 입력하시오 : "); scanf("%d %d", &num1, &num2); printf("두 수의 차 : %d \n", num1>num2 ? num1-num2 : num2-num1); return 0; }<file_sep>#include <stdio.h> int main(void) { int num, temp=1, i; printf("계승(factorial)을 구할 정수를 입력하시오 : "); scanf("%d", &num); for (i=1 ; i <= num ; i++) { temp*=i; } printf("결과 값 : %d \n", temp); return 0; }<file_sep>#include <stdio.h> int main(void) { int a, b, c, d; printf("숫자 A를 입력하시오:"); scanf("%d", &a); printf("숫자 B를 입력하시오:"); scanf("%d", &b); printf("숫자 C를 입력하시오:"); scanf("%d", &c); printf("숫자 D를 입력하시오:"); scanf("%d", &d); printf("S는 %d입니다.\n", a + b + c + d); printf("M은 %d입니다.\n", (a + b + c + d) / 4); return 0; }<file_sep>#include <stdio.h> int main(void) { int num; printf("10진수 정수를 입력 : "); scanf("%d", &num); printf("16진수 변화값 : %X \n", num); return 0; }
a92140505886de1185cf55e200d73d4cce193c85
[ "C" ]
25
C
songminseo/minseo
90b6766c9ad2ba39c75ab4453399ad16a39eff66
6382538d63ef4f5c7ac176baa0604a4213e8b6b2
refs/heads/master
<repo_name>LeninPA/arcade<file_sep>/dynamics/components.js /////// LOAD IMAGES //////// // LOAD BG IMAGE const fondo = new Image(); fondo.src = "../statics/img/fondo.jpg"; const imagen_nivel = new Image(); imagen_nivel.src = "../statics/img/level.png"; const vida_imagen = new Image(); vida_imagen.src = "../statics/img/life.png"; const scoreiImagen = new Image(); scoreiImagen.src = "../statics/img/score.png"; /////// END LOAD IMAGES //////// // ************************ // /////// LOAD SOUNDS //////// const choque = new Audio(); choque.src = "../statics/sounds/wall.mp3"; const vidaPerdida = new Audio(); vidaPerdida.src = "../statics/sounds/life_lost.mp3"; const PADDLE_HIT = new Audio(); PADDLE_HIT.src = "../statics/sounds/paddle_hit.mp3"; const gano = new Audio(); gano.src = "../statics/sounds/win.mp3"; const romperB = new Audio(); romperB.src = "../statics/sounds/brick_hit.mp3"; /////// END LOAD SOUNDS //////// <file_sep>/dynamics/inicio.js /*Estas variables nos ayudaran para cualquier dsipositivo obteniendo el ancho y largo de la pantall*/ var w = window.innerWidth; /*Nuestra altura sera necesaria para crear el efecto de que se vaya hacia arriba*/ var h = window.innerHeight; //Guardamos nuestro elemento intro en una variable homonima var intro = document.getElementsByClassName("intro")[0]; var historia = document.getElementsByClassName("historia")[0]; var parrafos = document.getElementsByClassName("parrafos")[0]; //Agregamos nuestra variable sonido var sonido = document.getElementById("sonido"); //esta seccion lo que hara es que conforme el ancho y largo de la pantalla se le asignara el tamaño de la letra intro.style.fontSize = w / 30 + "px"; historia.style.fontSize = w / 20 + "px"; parrafos.style.height = h + "px"; //Esta parte hara que se adaptable, en caso de que se reduzca la pantalla hara la function //Que hara que nuestrso valores se actualizen window.addEventListener("resize", function() { w = canvas.width = window.innerWidth; h = canvas.height = window.innerHeight; intro.style.fontSize = w / 30 + "px"; /*Tdo el tamaño de la letra de nuestro parrafo sera proporcional al ancho de nuestra ventana*/ historia.style.fontSize = w / 20 + "px"; parrafos.style.height = h + "px"; /*Fondo de estrellas*/ inicio(); nevada(); }); /*Esta parte nos servira para agregar dos nuevas clases una en el elemento intro y la otra en el elemento */ function animar() { intro.className = 'intro texto_intro animacion_intro'; historia.className = 'historia texto_historia animacion_historia'; sonido.play(); } <file_sep>/templates/header.html <!DOCTYPE html> <html lang="es"> <head> <!--Hago utilidad de la etiqueta meta y que sea compatible, se puedeborrar--> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>Coyo-express</title> <!--Estos link son para el favicon el estilo y el tipo de letra--> <link rel="shortcut icon" href="img/logo.png" type="image/png"> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css" integrity="<KEY>" crossorigin="anonymous"> <link rel="stylesheet" href="../statics/header.css"> <link href="https://fonts.googleapis.com/css?family=Open+Sans:300,400,700,800&display=swap" rel="stylesheet"> <link rel="icon" type="image/png" sizes="32x32" href="../statics/img/favicon_io/favicon-32x32.png"> <link rel="icon" type="image/png" sizes="16x16" href="../statics/img/favicon_io/favicon-16x16.png"> </head> <body> <header> <nav> <a href="./header.html">Inicio</a> <a href="../dynamics/Espacio.php">Sirtet</a> <a href="./terranos.html">Terranos</a> <a href="./breakout.html">Breakout</a> <button type="button" class="btn btn-outline-secondary" data-toggle="modal" data-target="#exampleModalLong"> Créditos </button> </nav> <section class="textos-header"> <h1>Arcade Coyotito</h1> <h2>Diviertete en el gran confinamiento</h2> <img src="../statics/img/logo.png" alt="gato pixel art" id="logo"> </section> <!--Esta aparte sera para darle como un borde curveado--> <div class="wave" style="height: 150px; overflow: hidden;"><svg viewBox="0 0 500 150" preserveAspectRatio="none" style="height: 100%; width: 100%;"> <path d="M0.00,49.98 C150.00,150.00 349.20,-50.00 500.00,49.98 L500.00,150.00 L0.00,150.00 Z" style="stroke: none; fill: #c6b1da;"></path> </svg></div> </header> <!-- Modal --> <div class="modal fade" id="exampleModalLong" tabindex="-1" role="dialog" aria-labelledby="exampleModalLongTitle" aria-hidden="true"> <div class="modal-dialog" role="document"> <div class="modal-content"> <div class="modal-header"> <h5 class="modal-title" id="exampleModalLongTitle">Créditos</h5> <button type="button" class="close" data-dismiss="modal" aria-label="Close"> <span aria-hidden="true">&times;</span> </button> </div> <div class="modal-body"> <div class="card"> <div class="card-body"> <h5 class="card-title"><NAME></h5> <p class="card-text">Programador del juego Breakout.<br>Gran compañero</p> </div> </div> <div class="card"> <div class="card-body"> <h5 class="card-title"><NAME></h5> <p class="card-text">La compañera que más aportó en el proyecto.<br> Estamos eternamente agradecidos con su esfuerzo constante e incansable. Sin ti este proyecto no se hubiera podido completar &hearts;.</p> </div> </div> <div class="card"> <div class="card-body"> <h5 class="card-title"><NAME></h5> <p class="card-text">Programador del juego terranos.<br>El nacimiento es sufrimiento, ergo hay que tener la mayor cantidad de gatos posibles en esta vida</p> </div> </div> <div class="card"> <div class="card-body"> <h5 class="card-title"><NAME></h5> <p class="card-text">Programadora del juego Sirtet, un Tetris renovado, más difícil y en donde es imposible girar las piezas. </p> </div> </div> <div class="modal-footer"> <button type="button" class="btn btn-secondary" data-dismiss="modal">Cerrar</button> </div> </div> </div> </div> </div> <div class="card-group"> <div class="card"> <img class="card-img-top" src="../statics/img/captura_sirtet.png" alt="Card image cap"> <div class="card-body"> <h1 class="card-title">Sirtet</h1> <p class="card-text">Un Tetris en donde pondrás tus habilidades a prueba conforme las piezas vayan cayendo. Diseñado solo para los mejores... ¿podrás superar los 1000 puntos? <h3>Instrucciones</h3> Conforme van cayendo las piezas en el tablero, acomódalas moviéndote hacia ambos lados para llenar una fila y que esta se rompa.<br> No llenes ninguna columna, o tu juego terminará. <h3>Controles</h3> Desplázate a los lados con las flechas izquierda y derecha o acelera tu caída con la flecha abajo. Puedes pausar para recargar energías con la tecla P. </p> <button onclick="location.href='../dynamics/Espacio.php'">JUGAR</button> <p class="card-text"><small class="text-muted">Come frutas y verduras</small></p> </div> </div> <div class="card"> <img class="card-img-top" src="../statics/img/captura_terranos.png" alt="Card image cap"> <div class="card-body"> <h1 class="card-title">Terranos</h1> <p class="card-text"> Desarmado y solitario, tú como píloto de la Xóchitl 6780-B debes de proteger a los últimos sobrevivientes de la Tierra. Sobrevive a los golpes de los enemigos hasta que lleguen los refuerzos. <h3>Instrucciones</h3> Evita los disparos enemigos hasta que lleguen las naves de refuerzo desplazándote hacia la derecha o la izquierda. Cada disparo sobrevivido suma a la puntuación <h3>Controles</h3> Desplazate con las teclas a y h hacia la derecha, y con las teclas d y l hacia la izquierda. </p> <button onclick="location.href='./terranos.html'">JUGAR</button> <p class="card-text"><small class="text-muted">Come frutas y verduras</small></p> </div> </div> <div class="card"> <img class="card-img-top" src="../statics/img/captura_breakout.png" alt="Card image cap"> <div class="card-body"> <h1 class="card-title">Breakout</h1> <p class="card-text">El mundo esta siendo atacado por grande bloques alienigenas y salvar al mundo depende de ti, no podemos asegurar tu supervivencia pero ya tu hablaras con tus actos, cuentas con una pelota que mas puedes pedir?... <h3>Instrucciones</h3> N O &nbsp;&nbsp; D E J E S &nbsp;&nbsp; Q U E &nbsp;&nbsp; L A &nbsp;&nbsp; P E L O T A &nbsp;&nbsp; C A I G A <h3>Controles</h3> Desplázate con las flechas derecha e izquierda. </p> <button onclick="location.href='./breakout.html'">JUGAR</button> <p class="card-text"><small class="text-muted">Come frutas y verduras</small></p> </div> </div> </div> <script src="https://code.jquery.com/jquery-3.5.1.slim.min.js" integrity="<KEY>" crossorigin="anonymous"></script> <script src="https://cdn.jsdelivr.net/npm/popper.js@1.16.0/dist/umd/popper.min.js" integrity="<KEY>" crossorigin="anonymous"></script> <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/js/bootstrap.min.js" integrity="<KEY>" crossorigin="anonymous"></script> </body> </html> <file_sep>/dynamics/score-terranos.js /**Este programa devuelve la puntuación que obtuvo el usuario * jugando terranos. */ function lectura_cookies(cookie) { let c = document.cookie let cookies = c.split(";"); let regex = new RegExp(cookie, "i"); for (indice in cookies) { let coincidencia = cookies[indice].search(regex); if (coincidencia > -1) { var posCookie = indice; break; } else { var posCookie = -1; } } if (posCookie != -1) { let valor_cookie = cookies[posCookie].split("=")[1]; return valor_cookie } else { return false } } // Impresión de puntuación let score = lectura_cookies("scoreTerranos"); console.log(score); $("#score").text(score); document.cookie = `scoreTerranos=0; expires=Thu, 01 Jan 1970 00:00:00 UTC;`;<file_sep>/dynamics/Espacio.php <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <link rel="stylesheet" href="../statics/Espacio.css" type="text/css"> <link rel="icon" type="image/png" sizes="32x32" href="../statics/img/favicon_io/favicon-32x32.png"> <link rel="icon" type="image/png" sizes="16x16" href="../statics/img/favicon_io/favicon-16x16.png"> <script type="text/javascript" src="../lib/jquery-3.5.1.min.js"></script> <script type="text/javascript" src="Espacio.js"></script> <title>Tetris</title> </head> <body> <!--Lado izquierdo de la pantalla--> <div id="letras"> <!--Caja que muestra la pieza siguiente--> <div id="caja"> <table> <?php $fil = 4; $col = 4; for($fi = 0; $fi < $fil; $fi++){ echo "<tr id='c".$fi."'>"; for($co = 0; $co < $col; $co++){ echo "<td id='c".$fi."_".$co."' class='celda'></td>"; } echo "</tr>"; } ?> </table> </div> <!--Apartado que muestra puntaje--> <div id="puntaje"> Puntaje: 0 </div> </div> <!--Lado derecho de la pantalla, tablero--> <div id="juego"> <table> <?php $fila = 20; $columna = 10; for($f = 0; $f < $fila; $f++){ echo "<tr id='j".$f."'>"; for($c = 0; $c < $columna; $c++){ echo "<td id='j".$f."_".$c."' class='celda'></td>"; } echo "</tr>"; } ?> </table> </div> <button onclick="location.href='../templates/header.html'">Regresa al principio</button> </body> </html><file_sep>/dynamics/game.js // SELECCIONAMOS NUESTRO CANVA const cvs = document.getElementById("breakout"); const ctx = cvs.getContext("2d"); // El borde de nuestro canvas cvs.style.border = "1px solid #0ff"; // La lineas para dibujar el canvas ctx.lineWidth = 3; // Las variables y constantes del juego que ocuparemos const largo = 100; const abajo = 50; const ancho = 20; const bolita_radio = 8; let vidas = 3; // Nuestro jugador tendra 3 vidas let score = 0; const unidad = 10; let nivel = 1; const max_nivel = 3; let lose = false; let leftArrow = false; let rightArrow = false; // Creacion del tablero const paddle = { x : cvs.width/2 - largo/2, y : cvs.height - abajo - ancho, width : largo, height : ancho, dx :5 } // Dibujar nuestra paleta que utilizaremos para rebotar function drawPaddle(){ ctx.fillStyle = "#2e3548"; ctx.fillRect(paddle.x, paddle.y, paddle.width, paddle.height); ctx.strokeStyle = "#ffcd05"; ctx.strokeRect(paddle.x, paddle.y, paddle.width, paddle.height); } // Controles document.addEventListener("keydown", function(event){ if(event.keyCode == 37){ leftArrow = true; }else if(event.keyCode == 39){ rightArrow = true; } }); document.addEventListener("keyup", function(event){ if(event.keyCode == 37){ leftArrow = false; }else if(event.keyCode == 39){ rightArrow = false; } }); // movimiento de la barra function movePaddle(){ if(rightArrow && paddle.x + paddle.width < cvs.width){ paddle.x += paddle.dx; }else if(leftArrow && paddle.x > 0){ paddle.x -= paddle.dx; } } // creacion de la bola const ball = { x : cvs.width/2, y : paddle.y - bolita_radio, radius : bolita_radio, speed : 4, dx : 3 * (Math.random() * 2 - 1), dy : -3 } // dibujo la bola function drawBall(){ ctx.beginPath(); ctx.arc(ball.x, ball.y, ball.radius, 0, Math.PI*2); ctx.fill(); ctx.stroke(); ctx.closePath(); } // El movimiento de la bola function moveBall(){ ball.x += ball.dx; ball.y += ball.dy; } // Deteccion de los choques ballWallCollision function ballWallCollision(){ if(ball.x + ball.radius > cvs.width || ball.x - ball.radius < 0){ ball.dx = - ball.dx; choque.play(); } if(ball.y - ball.radius < 0){ ball.dy = -ball.dy; choque.play(); } if(ball.y + ball.radius > cvs.height){ vidas--; // LOSE LIFE vidaPerdida.play(); resetBall(); } } // Regresa bolita function resetBall(){ ball.x = cvs.width/2; ball.y = paddle.y - bolita_radio; ball.dx = 3 * (Math.random() * 2 - 1); ball.dy = -3; } // Pelotita y la barra collisionan haciendo que rebote function ballPaddleCollision(){ if(ball.x < paddle.x + paddle.width && ball.x > paddle.x && paddle.y < paddle.y + paddle.height && ball.y > paddle.y){ // Sonido play cada vz que choque PADDLE_HIT.play(); // Checa si la pelota choca con el paddle let collidePoint = ball.x - (paddle.x + paddle.width/2); // Normaliza los valores collidePoint = collidePoint / (paddle.width/2); // Calcula el angulo de la pelotita let angle = collidePoint * Math.PI/3; //Podriamos modificar la velocidad ball.dx = ball.speed * Math.sin(angle); ball.dy = - ball.speed * Math.cos(angle); } } // Creacion de los valores para nuestrso bloques de arriba const brick = { row : 1, column : 5, width : 55, height : 20, offSetLeft : 20, offSetTop : 20, marginTop : 40, fillColor : "#2e3548", strokeColor : "#FFF" } let bricks = []; //Creacion de los bloques de arriba function createBricks(){ for(let r = 0; r < brick.row; r++){ bricks[r] = []; for(let c = 0; c < brick.column; c++){ bricks[r][c] = { x : c * ( brick.offSetLeft + brick.width ) + brick.offSetLeft, y : r * ( brick.offSetTop + brick.height ) + brick.offSetTop + brick.marginTop, status : true } } } } //Lalo a la funcion createBricks(); // Aghora solo los dibujo function drawBricks(){ for(let r = 0; r < brick.row; r++){ for(let c = 0; c < brick.column; c++){ let b = bricks[r][c]; // if the brick isn't broken if(b.status){ ctx.fillStyle = brick.fillColor; ctx.fillRect(b.x, b.y, brick.width, brick.height); ctx.strokeStyle = brick.strokeColor; ctx.strokeRect(b.x, b.y, brick.width, brick.height); } } } } // La collision con los bloques enemigos hara que amente nuestro puntaje function ballBrickCollision(){ for(let r = 0; r < brick.row; r++){ for(let c = 0; c < brick.column; c++){ let b = bricks[r][c]; // Si nuestro bloqeu choca if(b.status){ if(ball.x + ball.radius > b.x && ball.x - ball.radius < b.x + brick.width && ball.y + ball.radius > b.y && ball.y - ball.radius < b.y + brick.height){ romperB.play(); ball.dy = - ball.dy; b.status = false; //El bloque choca score += unidad; } } } } } // Muestra el estado de nuestro juego incorporando nuestras imagenes function showGameStats(text, textX, textY, img, imgX, imgY){ // draw text ctx.fillStyle = "#FFF"; ctx.font = "25px Germania One"; ctx.fillText(text, textX, textY); // dibujar imagenes ctx.drawImage(img, imgX, imgY, width = 25, height = 25); } // Con esta funcion llamaremos a nuestras funciones creadas anteriormente y ademas esaremos actualizansdo nuestras vidas y puntajes y niveles function draw(){ drawPaddle(); drawBall(); drawBricks(); // Mostrar el score showGameStats(score, 35, 25, scoreiImagen, 5, 5); // Mostrar las vidas showGameStats(vidas, cvs.width - 25, 25, vida_imagen, cvs.width-55, 5); // Mostrar el nivel en el que estas showGameStats(nivel, cvs.width/2, 25, imagen_nivel, cvs.width/2 - 30, 5); } // Juego perdido function gameOver(){ if(vidas <= 0){ window.location="GameOver.html"; lose = true; } } // Siguiente nivel function levelUp(){ let isLevelDone = true; // Checa si todos los bloques se han rotos for(let r = 0; r < brick.row; r++){ for(let c = 0; c < brick.column; c++){ isLevelDone = isLevelDone && ! bricks[r][c].status; } } if(isLevelDone){ gano.play(); if(nivel >= max_nivel){ window.location="GameWon.html"; lose = true; return; } brick.row++; createBricks(); ball.speed += 0.5; resetBall(); nivel++; } } // Actualizar l juego function update(){ movePaddle(); moveBall(); ballWallCollision(); ballPaddleCollision(); ballBrickCollision(); gameOver(); levelUp(); } // E4sta parte es importante aqui estaremos limpiando y generando canvas function loop(){ // Limpiar las canvas ctx.drawImage(fondo, 0, 0); draw(); update(); if(! lose){ requestAnimationFrame(loop); } } loop(); // Seleccionar nuestro elemento sound const soundElement = document.getElementById("sound"); soundElement.addEventListener("click", audioManager); function audioManager(){ // Nuestrso sonidos e imagenes acomodados, siendo sound nuestro interruptor del sonido let imgSrc = soundElement.getAttribute("src"); let SOUND_IMG = imgSrc == "../statics/img/SOUND_ON.png" ? "../statics/img/SOUND_OFF.png" : "../statics/img/SOUND_ON.png"; soundElement.setAttribute("src", SOUND_IMG); // Interruptor de sonidos choque.muted = choque.muted ? false : true; PADDLE_HIT.muted = PADDLE_HIT.muted ? false : true; romperB.muted = romperB.muted ? false : true; gano.muted = gano.muted ? false : true; vidaPerdida.muted = vidaPerdida.muted ? false : true; } // Mostrar mensaje de gameover /* elementos seleccionados */ const gameover = document.getElementById("gameover"); const restart = document.getElementById("restart"); <file_sep>/dynamics/Espacio.js var intervalo = 0; var noI = 0; //Función que limpia cajita function Limpiar(){ for(var fi = 3; fi >= 0; fi--){ for(var co = 3; co >= 0; co--){ $("#c"+fi+"_"+co).removeClass("I").removeClass("O").removeClass("T").removeClass("S").removeClass("Z").removeClass("L").removeClass("J"); } } } //Función que elige una pieza random para mostrar en la caja function Cajita(){ var pieza = Math.round(Math.random() * 18); switch(pieza){ case 0 : $("#c0_1, #c1_1, #c2_1, #c3_1").addClass("I") break; case 1 : $("#c0_1, #c1_1, #c0_2, #c1_2").addClass("O") break; case 2 : $("#c0_1, #c1_0, #c1_1, #c1_2").addClass("T") break; case 3 : $("#c0_1, #c0_2, #c1_0, #c1_1").addClass("S") break; case 4 : $("#c0_1, #c0_2, #c1_2, #c1_3").addClass("Z") break; case 5 : $("#c0_1, #c1_1, #c2_1, #c2_2").addClass("L") break; case 6 : $("#c0_1, #c1_1, #c2_1, #c2_0").addClass("J") break; case 7 : $("#c0_0, #c0_1, #c0_2, #c0_3").addClass("I") break; case 8 : $("#c0_1, #c1_1, #c1_2, #c2_1").addClass("T") break; case 9 : $("#c1_1, #c0_0, #c0_1, #c0_2").addClass("T") break; case 10 : $("#c0_1, #c1_1, #c2_1, #c1_0").addClass("T") break; case 11 : $("#c0_1, #c1_1, #c1_2, #c2_2").addClass("S") break; case 12 : $("#c0_1, #c1_0, #c1_1, #c2_0").addClass("Z") break; case 13 : $("#c0_1, #c0_2, #c1_2, #c2_2").addClass("L") break; case 14 : $("#c0_2, #c1_0, #c0_0, #c0_1").addClass("L") break; case 15 : $("#c1_0, #c1_1, #c1_2, #c2_0").addClass("L") break; case 16 : $("#c0_0, #c0_1, #c0_2, #c1_2").addClass("J") break; case 17 : $("#c1_0, #c1_1, #c1_2, #c0_0").addClass("J") break; case 18 : $("#c0_1, #c1_1, #c2_1, #c0_2").addClass("J") break; } } //Función que lleva la cuenta del puntaje function Puntaje (puntos){ //Toma el texto del puntaje del php var points = $("#puntaje").text(); //Separa la cadena, para tomar solo el valor points = points.split(": "); //Toma el valor del php y le suma puntos, setter $("#puntaje").text("Puntaje: "+ (parseInt(points[1]) + puntos)); } //Función que copia la pieza de la cajita al juego function Juego (){ //Checa color en filas de abajo hacia arriba for(var fi = 3; fi >= 0; fi--){ //Checa color en columnas de derecha a izquierda for(var co = 3; co >= 0; co--){ if($("#c"+fi+"_"+co).hasClass("I")){ $("#j"+fi+"_"+co).addClass("I").addClass("mov"); }else if($("#c"+fi+"_"+co ).hasClass("O")){ $("#j"+fi+"_"+co).addClass("O").addClass("mov"); }else if($("#c"+fi+"_"+co ).hasClass("S")){ $("#j"+fi+"_"+co).addClass("S").addClass("mov"); }else if($("#c"+fi+"_"+co ).hasClass("Z")){ $("#j"+fi+"_"+co).addClass("Z").addClass("mov"); }else if($("#c"+fi+"_"+co ).hasClass("T")){ $("#j"+fi+"_"+co).addClass("T").addClass("mov"); }else if($("#c"+fi+"_"+co ).hasClass("L")){ $("#j"+fi+"_"+co).addClass("L").addClass("mov"); }else if($("#c"+fi+"_"+co ).hasClass("J")){ $("#j"+fi+"_"+co).addClass("J").addClass("mov"); } } } } //Función que hace que la pieza baje function Baja(){ var arreglo = new Array; var para = 0; //Selecciona celdas pertenecientes a la pieza $(".mov").each(function(){ //Mete id's al arreglo arreglo.push($(this).attr("id")); //Saca id=this=f_c de cada celda y divide la cadena var cuad = $(this).attr("id").replace("j","").split("_"); //Si la celda debajo de las celdas coloreadas, pertenece a otra pieza, debe parar if( ($("#j"+(parseInt(cuad[0])+1)+"_"+parseInt(cuad[1])).hasClass("stat")) == true ){ para = 1; //Si la celda debajo de las celdas coloreadas, está en la última fila, debe parar }else if((parseInt(cuad[0])+1) == 20){ para = 1; } }); //Invierte el orden de sus elementos para recorrer de abajo hacia arriba arreglo.reverse(); //Si debe parar, deja de moverse, se quita .mov, y agrega .stat y se ganan 10 puntos if(para == 1){ Puntaje(10); $(".mov").each(function(){ $(this).removeClass("mov").addClass("stat"); }); //Una vez que para, inicia el nuevo ciclo Rompe(); var ciao = PerdedorPorSiempre(); //Si no ha llegado hasta arriba, continúa el juego if(ciao == ""){ Limpiar(); Cajita(); Juego(); clearInterval(intervalo); intervalo = setInterval(Baja, 1000); } //Envía mensaje y finaliza else{ var p = $("#puntaje").text(); p = p.split(": "); $("#puntaje").text("Perdiste, tu puntaje final es: "+p[1]); document.cookie = "Puntaje="+p[1]; } } //Si debe continuar moviéndose, lo hará else{ $.each(arreglo, function(){ //Se queda solo la clase del color var color = $("#"+this).attr("class").replace("mov", "").replace("celda", "").trim(); //Deja al valor del id separado var cuad = this.replace("j","").split("_"); //A la pieza debajo le añade las clases mov y color $("#j"+(parseInt(cuad[0])+1)+"_"+parseInt(cuad[1])).addClass("mov").addClass(color); //A la pieza en la que se encontraba, le remueve clases mov y color $("#"+this).removeClass(color).removeClass("mov"); }); } } //Función que mueve la pieza a los lados, acelera caída y pausa o reanuda function Teclas(e){ if(e.code == "ArrowLeft"){ var arreglo = new Array; var para = 0; //Selecciona celdas pertenecientes a la pieza $(".mov").each(function(){ //Mete id's al arreglo arreglo.push($(this).attr("id")); //Saca id de cada celda y divide la cadena var cuad = $(this).attr("id").replace("j","").split("_"); //Si a la izquierda de las celdas coloreadas, pertenece a otra pieza, debe parar if( ($("#j"+parseInt(cuad[0])+"_"+(parseInt(cuad[1])-1)).hasClass("stat")) == true ){ para = 1; //Si a la izquierda de las celdas coloreadas, está en la primera columna, debe parar }else if( (parseInt(cuad[1])-1) < 0 ){ para = 1; } }); //Si debe parar, deja de moverse //Si debe continuar moviéndose, lo hará if(para == 0){ $.each(arreglo, function(){ //Deja al valor del id separado var cuad = this.replace("j","").split("_"); //Se queda solo la clase del color var color = $("#"+this).attr("class").replace("mov", "").replace("celda", "").trim(); //A la pieza de la izquierda se le añade las clases mov y color $("#j"+parseInt(cuad[0])+"_"+(parseInt(cuad[1])-1)).addClass("mov").addClass(color); //A la pieza en la que se encontraba, le remueve clases mov y color $("#"+this).removeClass(color).removeClass("mov"); }); } } else if(e.code == "ArrowRight"){ var arreglo = new Array; var para = 0; //Selecciona celdas pertenecientes a la pieza $(".mov").each(function(){ //Mete id's al arreglo arreglo.push($(this).attr("id")); //Saca id de cada celda y divide la cadena var cuad = $(this).attr("id").replace("j","").split("_"); //Si a la derecha de las celdas coloreadas, pertenece a otra pieza, debe parar if( ($("#j"+parseInt(cuad[0])+"_"+(parseInt(cuad[1])+1)).hasClass("stat")) == true ){ para = 1; //Si a la derecha de las celdas coloreadas, está en la última columna, debe parar }else if( (parseInt(cuad[1])+1) > 9 ){ para = 1; } }); arreglo.reverse(); //Si debe parar, deja de moverse //Si debe continuar moviéndose, lo hará if(para == 0){ $.each(arreglo, function(){ //Deja al valor del id separado var cuad = this.replace("j","").split("_"); //Se queda solo la clase del color var color = $("#"+this).attr("class").replace("mov", "").replace("celda", "").trim(); //A la pieza de la derecha se le añade las clases mov y color $("#j"+parseInt(cuad[0])+"_"+(parseInt(cuad[1])+1)).addClass("mov").addClass(color); //A la pieza en la que se encontraba, le remueve clases mov y color $("#"+this).removeClass(color).removeClass("mov"); }); } } //Al presionar flecha abajo, se acelera la velocidad de bajada de la pieza else if(e.code == "ArrowDown"){ clearInterval(intervalo); intervalo = setInterval(Baja, 100); } //Pausa o reanuda el juego al presionar P else if(e.code == "KeyP"){ if(noI == 0){ clearInterval(intervalo); noI = clearInterval(intervalo); } else{ clearInterval(intervalo); intervalo = setInterval(Baja, 1000); noI = 0; } } } //Función que rompe filas llenas function Rompe(){ var romper = 1; var fi = 19; //Recorre filas while(fi >= 0){ //Variable que rompe fila romper = 1; //Recorre columnas for(var co = 9; co >= 0; co--){ //Si no tiene clase stat, no rompe fila y regresa al for de columna if( ($("#j"+fi+"_"+co).hasClass("stat")) == false ){ romper = 0; } } //Va a romper la fila if(romper == 1){ Puntaje(100); //Borra las celdas de la fila que está llena for(co = 9; co >= 0; co--){ $("#j"+fi+"_"+co).removeClass("stat").removeClass("I").removeClass("O").removeClass("T").removeClass("S").removeClass("Z").removeClass("L").removeClass("J"); } //Recorre filas superiores a la eliminada (fb = fila borrada) for(var fb = (fi-1); fb >=0; fb--){ //Recorre columnas de las filas (cr = columna recorrida) for(var cr = 9; cr>= 0; cr--){ //Obtiene clase del color de la celda en la que se encuentra var color = $("#j"+fb+"_"+cr).attr("class").replace("stat", "").replace("celda", "").trim(); //Coloca clases a la fila debajo, siempre que sea una pieza, y se las quita en donde está if(color != ""){ $("#j"+(fb+1)+"_"+cr).addClass("stat").addClass(color); } $("#j"+fb+"_"+cr).removeClass("stat").removeClass(color); } } //Si rompe, suma una fila(20) para checar si debe romper, desde abajo fi++; //Después resta la fila, para volver a la 19 } //Si no rompe, resta una fila y continua buscando para romper fi--; } } //Función que termina el juego al perder function PerdedorPorSiempre(){ var adios = ""; //Recorre las columnas en la fila 0 for(var co = 9; co >= 0; co--){ //Si está llena, deshabilita que las piezas bajen if($("#j0_"+co).hasClass("stat")){ clearInterval(intervalo); adios = "Perdiste!"; } } //Finaliza función y devuelve mensaje return adios; } //Ejecuta funciones $(document).ready(function(){ Cajita();//Escoge pieza Juego();//Copia pieza a juego intervalo = setInterval(Baja, 1000);//Baja la pieza document.addEventListener("keyup", Teclas);//Mueve a los lados, acelera caída y pausa o reanuda });<file_sep>/dynamics/terranos.js /* Este programa es un juego inspirado en Space invaders * Una nave del usuario se mueve con las teclas a, d, h, y l. * Empieza con tres vidas que se van reduciendo cada que es golpeda con un disparo * Se gana si se sigue vivo para cuando lleguen los refuerzos. * La puntuación se guarda en una cookie y se muestra en una sitio externo */ // Objetos class Nave{ constructor(x, y, tipo) { this.x = x; this.y = y; this.tipo = tipo; } } class NaveUsr{ constructor(){ this.x = 45; this.vidas = 3; this.viva = true; this.width = 0; } } // Creación de un proto-tablero class Nivel{ constructor(filNum, colNum, t1Num, t2Num, t3Num) { this.x = 1; this.y = 1; this.nFilas = filNum; this.nCols = colNum; /**La suma de los distintos tipos de naves debe de ser igual al * producto de las filas por las columnas */ this.t1Num = t1Num; this.t2Num = t2Num; this.t3Num = t3Num; this.filas = new Array(); this.cols = new Array(); this.naves = new Array(); // Asignación aletoria de los tipos a las naves if ((this.nFilas * this.nCols) == (this.t1Num + this.t2Num + this.t3Num)){ for (let i = 0; i < this.nFilas; i++){ for (let j = 0; j < this.nCols; j++) { let bool = true; do{ let n = Math.round(Math.random() * 2) + 1 if (n == 1 && this.t1Num > 0){ bool = false; this.t1Num--; this.naves.push(new Nave(j, i, 1)); } else if (n == 2 && this.t2Num > 0){ bool = false; this.t2Num--; this.naves.push(new Nave(j, i, 2)); } else if (n == 3 && this.t3Num > 0) { bool = false; this.t3Num--; this.naves.push(new Nave(j, i, 3)); } } while (bool); } } } } } // Adiquiere diversos valores de Nivel, pero agrega la longitud de cada nave class Tablero{ constructor(nivel){ this.cols = nivel.nCols; this.fil = nivel.nFilas; this.naves = nivel.naves; this.widthN = (window.innerWidth*0.5)/this.cols; console.log(this.widthN); } // Genera una longitud actualizada calcWidth(){ this.widthN = (window.innerWidth * 0.5) / this.cols; return this.widthN } } // Función para dibujar las naves function iniciaNaves(){ let velocidad = 500; let direccion = 1; let boolDibNaves = true; setTimeout(function dibNaves() { let v = $(window).width() / 100 * direccion; let topPos = parseInt($("#naves").css("top")) + 20; let left = parseInt($("#naves").css("left"), 10); let navesWidth = parseInt($("#naves").css("width"), 10); let tabWidth = parseInt($("#tablero").css("width"), 10); let padding = parseInt($("#tablero").css("padding"), 10); let pos = left + v; if (left + navesWidth >= tabWidth - v + padding){ direccion = -1; $("#naves").css("top", topPos + "px"); } else if (left <= -padding - v) { direccion = 1; $("#naves").css("top", topPos + "px"); }else{ $("#naves").css("left", pos + "px"); } setTimeout(() => { boolDibNaves = verifGanar(tab1); if (!boolDibNaves){ dibNaves(); } }, velocidad); }, velocidad); } // Función que genera los disparos function dispara(naveUsr, puntuacion) { // Posición del disparo let posLeft = Math.round(Math.random() * 109) - 19; // Clases del disparo let BalaUsr = $("<div>"); BalaUsr.addClass("bala"); BalaUsr.addClass("advertencia"); BalaUsr.css("top", "-45%"); BalaUsr.css("left", posLeft + "%"); $("#tablero").append(BalaUsr) // Cambio de advertencia a disparo setTimeout(function disparoEnemigo() { // Tablero let tabWidth = parseInt($("#tablero").css("width"), 10); // Usuario let leftUsr = naveUsr.x; let rightUsr = naveUsr.width + leftUsr; //Disparo let left = parseInt(BalaUsr.css("left"), 10) + tabWidth * 0.13; let width = parseInt(BalaUsr.css("width"), 10) - tabWidth * 0.05; let right = left + width; //Cambio de clases BalaUsr.removeClass("advertencia"); BalaUsr.addClass("disparo"); setTimeout(() => { // Evaluación de posiciones if ((leftUsr < left && rightUsr > left) || (leftUsr < right && rightUsr > right)){ $("#vida-" + naveUsr.vidas).remove(); naveUsr.vidas--; } setTimeout(() => { // Actualización de la posición puntuacion++; document.cookie = "scoreTerranos=" + puntuacion; BalaUsr.remove(); // Verfica si se cumplen las condiciones de victoria let ganar = verifGanar(tab1); if(ganar){ alert("Has ganado uwu") } else{ // De no ser así, verfica las vidas if(naveUsr.vidas > 0){ //Si sigue vivo, continúa disparando dispara(naveUsr, puntuacion); } else if (naveUsr.vidas == 0){ //De lo contrario, se manda al otro sitio window.location = "./score-terranos.html"; } } }, 600); }, 50); }, 1000); } // Función que evalúa las condiciones de victoria function verifGanar(tablero){ //Refuerzos let top = parseInt($("#naves").css("top"), 10); let heightNaves = parseInt($("#naves").css("height"), 10); let padding = parseInt($("#naves").css("padding"), 10); //Tablero let heightTab = parseInt($("#tablero").css("height"), 10) - tablero.widthN - padding; let boolGanar = false; if(heightNaves + top >= heightTab){ boolGanar = true; window.location = "./score-terranos.html"; } return boolGanar } // Instanciación de nivel y tablero let nivel1 = new Nivel(4, 6, 10, 10, 4); let tab1 = new Tablero(nivel1); let navesGraf = new Array(); // Dibuja las naves en el tablero for (let i = 0; i < tab1.cols; i++) { navesGraf[i] = new Array(); for (let j = 0; j < tab1.fil; j++) { navesGraf[i][j] = $("<div>"); navesGraf[i][j].addClass("terrano"); navesGraf[i][j].css("width",tab1.widthN); navesGraf[i][j].css("height", tab1.widthN); var nave; nivel1.naves.forEach((elem, index)=>{ if(elem.x == i && elem.y == j){ navesGraf[i][j].addClass("t" + elem.tipo); } }) $("#naves").append(navesGraf[i][j]); } } // Instanciación de la nave de usuario let jugador = new NaveUsr() // Dibuja la nave del usuario let naveUsrGraf = $("<div>"); naveUsrGraf.addClass("usr"); naveUsrGraf.css("width", tab1.widthN); jugador.width = tab1.widthN; naveUsrGraf.css("height", tab1.widthN); $("#tablero").append(naveUsrGraf); // En caso de cambiar el tamaño de la ventana $(window).resize(() => { window.location.reload(); }) // Eventos de teclas let empJuego = true; $(document).keypress((event) => { // Medidas del tablero let padding = parseInt(($("#tablero").css("padding")), 10); let tabWidth = parseInt(($("#tablero").css("width")), 10); let left = parseInt(naveUsrGraf.css("left"), 10); // Movimiento a la izquierda if (event.key == 'a' || event.key == 'h') { let anterior = left - tabWidth / 100; if (anterior > -padding) { naveUsrGraf.css("left", anterior + "px"); jugador.x = anterior; } if (empJuego) { dispara(jugador, 0, 0); iniciaNaves(); empJuego = false; } } // Movimiento a la derecha else if (event.key == 'd' || event.key == 'l') { let anterior = left + tabWidth / 100; if (anterior < tabWidth - padding) { naveUsrGraf.css("left", anterior + "px"); jugador.x = anterior; } if (empJuego) { dispara(jugador, 0, 0); iniciaNaves(); empJuego = false; } } })<file_sep>/README.md # Arcade Coyotito <h2>Equipo: Los tres mosqueteros y Arantxa</h2> Integrantes: - <NAME> - <NAME> - <NAME> - <NAME> Introducción: Este proyecto es un sitio Web en el que se encuentran 3 juegos distintos(un tetris difícil, un juego inspirado en space invaders, y un breakout con 3 niveles). Al inicio se escoge una paleta de colores y un nombre de usuario. Posteriormente se redirige al usuario a una página donde se encuentra una introducción a cada juego y se puede seleccionar uno para jugar. De igual forma en la parte superior se encuentran los créditos. Guía de instalación: Se deben adquirir los documentos de la rama master y descargarlos en la computadora en donde se desea accesar al arcade. Para ingresar a la página se debe iniciar en el documento index.html y a partir de ahí, las demás páginas funcionan correctamente. Antes de abrir los documentos se debe iniciar el servidor "Xampp" en el caso de Windows o "Mamp" en el caso de Mac, y los documentos se deben guardar en la carpeta "htdocs". Para abrir el documento, en el navegador se debe escribir la ruta "localhost/templates/index.html". Guía de configuración: No requiere ninguna configuración adicional. Características: - Pantalla de primera vez - Pantalla de bienvenida - Tarjetas individuales para cada juego - Pantallas individuales para cada juego - Pantalla de créditos - Sistema de puntajes en cada juego - Juegos - Sirtet "Tetris recargado" - Se le prohibe al usuario rotar las piezas - Se le asigna una orientación aleatoria a cada pieza que cae al usuario - El usuario puede mover la pieza a los lados o acelerar su caí - Se le asigna una orientación aleatoria a cada pieza que cae al usuario con las teclas :arrow_backward::arrow_down::arrow_forward: - Al llenarse una fila, esta se destruya y si hay un bloque superior, este baja una casilla - El juego termina cuando se llena una columna - Terranos - El usuario se dezplaza con a la derecha o izquierda en lo que las naves llegan a un 80% de la altitud del tablero - El jugador tiene 3 vidas - Un disparo cae del cielo en una posición aleatoria - Pierde una vida si se encuentra con un disparo - Breakout - Existe una pelota que rompe los bloques - La pelota tiene 3 vidas - Cuenta con 3 niveles en donde la dificultad va aumentando - La pelota debe rebotar en la barra inferior, o perderá - Cuenta con sonido - Gana al completar todos los niveles Comentarios adicionales: La integración de base de datos, que incluyen el registro del usuario y puntajes no se completó porque un integrante no pudo colaborar en el proyecto. Sin embargo, implementamos lo que consideramos más necesario para un mínimo funcionamiento de la página y fácil interfaz para el usuario. Esperamos puedan disfrutar de los juegos que programamos y agradecemos a los instructores del Curso Web por habernos brindado los conocimientos con los que llevamos a cabo este proyecto.
ed4e2724a588067f67a73d0c158f2e7d1d5b848b
[ "JavaScript", "Markdown", "HTML", "PHP" ]
9
JavaScript
LeninPA/arcade
642506f3b9128f9c0d189611be1536942180834f
d5af6a0584771f61f952119eaa9c06a4c0ffc71f
refs/heads/main
<file_sep>const height = 150; const width = 300; const width2 = 200; const height2 = 80; const diam = 50; const diam2 = 30; let xPos = 0; let yPos = 0; let countX = 0; function setup() { createCanvas(600, 675); noLoop(); strokeWeight(8); colorMode(RGB); } function draw() { let rFill = random(100, 255); let rFill1 = random(100, 255); function smlE(val) { const inc = 50 + countX; return inc + val; } function yPosSmlC(val) { const inc = countX+height/2; return inc + val; } function yPosGap(val){ const inc = countX+ 2*height; return inc+val; } function yPosGap1(val){ const inc = countX-3*height; return inc+val; } function xPosGap(val){ const inc = countX+ width/2; return inc+val; } background(186, rFill1, 88); //line0 vertical pattern1 xPos=-133.5 yPos=150 stroke(rFill,187,155); noFill(); //big ellipse rect(xPos, yPos, width, height, diam2); //small ellipse fill(216, 180, 150); rect(smlE(xPos), smlE(yPos), width2, height2, diam2); //right small circle fill(218, 212, 196); circle(xPos+width, yPosSmlC(yPos), diam); //left small circle circle(xPos, yPosSmlC(yPos), diam); //line0 vertical pattern2 yPos=yPosGap(yPos) noFill(); //big ellipse rect(xPos, yPos, width, height, diam2); //small ellipse fill(216, 180, 150); rect(smlE(xPos), smlE(yPos), width2, height2, diam2); //right small circle fill(218, 212, 196); circle(xPos+width, yPosSmlC(yPos), diam); //left small circle circle(xPos, yPosSmlC(yPos), diam); //line1 vertical pattern1 xPos=xPosGap(xPos) yPos=yPosGap1(yPos) noFill(); //big ellipse rect(xPos, yPos, width, height, diam2); //right small circle fill(218, 212, 196); circle(xPos+width, yPosSmlC(yPos), diam); //left small circle circle(xPos, yPosSmlC(yPos), diam); //small ellipse rect(smlE(xPos), smlE(yPos), width2, height2, diam2); //line1 vertical pattern2 yPos=yPosGap(yPos) noFill(); //big ellipse rect(xPos, yPos, width, height, diam2); //right small circle fill(218, 212, 196); circle(xPos+width, yPosSmlC(yPos), diam); //left small circle circle(xPos, yPosSmlC(yPos), diam); //small ellipse rect(smlE(xPos), smlE(yPos), width2, height2, diam2); //line1 vertical pattern3 yPos=yPosGap(yPos) noFill(); //big ellipse rect(xPos, yPos, width, height, diam2); //right small circle fill(218, 212, 196); circle(xPos+width, yPosSmlC(yPos), diam); //left small circle circle(xPos, yPosSmlC(yPos), diam); //small ellipse rect(smlE(xPos), smlE(yPos), width2, height2, diam2); //line2 vertical pattern1 xPos=xPosGap(xPos) yPos=yPosGap1(yPos) noFill(); //big ellipse rect(xPos, yPos, width, height, diam2); //small ellipse fill(216, 180, 150); rect(smlE(xPos), smlE(yPos), width2, height2, diam2); //right small circle fill(218, 212, 196); circle(xPos+width, yPosSmlC(yPos), diam); //left small circle circle(xPos, yPosSmlC(yPos), diam); //line2 vertical pattern2 yPos=yPosGap(yPos) noFill(); //big ellipse rect(xPos, yPos, width, height, diam2); //small ellipse fill(216, 180, 150); rect(smlE(xPos), smlE(yPos), width2, height2, diam2); //right small circle fill(218, 212, 196); circle(xPos+width, yPosSmlC(yPos), diam); //left small circle circle(xPos, yPosSmlC(yPos), diam); //line3 vertical pattern1 xPos=xPosGap(xPos) yPos=yPosGap1(yPos) noFill(); //big ellipse rect(xPos, yPos, width, height, diam2); //right small circle fill(218, 212, 196); circle(xPos+width, yPosSmlC(yPos), diam); //left small circle circle(xPos, yPosSmlC(yPos), diam); //small ellipse rect(smlE(xPos), smlE(yPos), width2, height2, diam2); //line3 vertical pattern2 yPos=yPosGap(yPos) noFill(); //big ellipse rect(xPos, yPos, width, height, diam2); //right small circle fill(218, 212, 196); circle(xPos+width, yPosSmlC(yPos), diam); //left small circle circle(xPos, yPosSmlC(yPos), diam); //small ellipse rect(smlE(xPos), smlE(yPos), width2, height2, diam2); //line3 vertical pattern3 yPos=yPosGap(yPos) noFill(); //big ellipse rect(xPos, yPos, width, height, diam2); //right small circle fill(218, 212, 196); circle(xPos+width, yPosSmlC(yPos), diam); //left small circle circle(xPos, yPosSmlC(yPos), diam); //small ellipse rect(smlE(xPos), smlE(yPos), width2, height2, diam2); //line4 vertical pattern1 xPos=xPosGap(xPos) yPos=yPosGap1(yPos) noFill(); //big ellipse rect(xPos, yPos, width, height, diam2); //small ellipse fill(216, 180, 150); rect(smlE(xPos), smlE(yPos), width2, height2, diam2); //right small circle fill(218, 212, 196); circle(xPos+width, yPosSmlC(yPos), diam); //left small circle circle(xPos, yPosSmlC(yPos), diam); //line4 vertical pattern2 yPos=yPosGap(yPos) noFill(); //big ellipse rect(xPos, yPos, width, height, diam2); //small ellipse fill(216, 180, 150); rect(smlE(xPos), smlE(yPos), width2, height2, diam2); //right small circle fill(218, 212, 196); circle(xPos+width, yPosSmlC(yPos), diam); //left small circle circle(xPos, yPosSmlC(yPos), diam); //line5 vertical pattern1 xPos=xPosGap(xPos) yPos=yPosGap1(yPos) noFill(); //big ellipse rect(xPos, yPos, width, height, diam2); //right small circle fill(218, 212, 196); circle(xPos+width, yPosSmlC(yPos), diam); //left small circle circle(xPos, yPosSmlC(yPos), diam); //small ellipse rect(smlE(xPos), smlE(yPos), width2, height2, diam2); //line5 vertical pattern2 yPos=yPosGap(yPos) noFill(); //big ellipse rect(xPos, yPos, width, height, diam2); //right small circle fill(218, 212, 196); circle(xPos+width,yPosSmlC(yPos), diam); //left small circle circle(xPos, yPosSmlC(yPos), diam); //small ellipse rect(smlE(xPos), smlE(yPos), width2, height2, diam2); //line5 vertical pattern3 yPos=yPosGap(yPos) noFill(); //big ellipse rect(xPos, yPos, width, height, diam2); //right small circle fill(218, 212, 196); circle(xPos+width, yPosSmlC(yPos), diam); //left small circle circle(xPos, yPosSmlC(yPos), diam); //small ellipse rect(smlE(xPos), smlE(yPos), width2, height2, diam2); }<file_sep>const width = 2000; const height = 2000; const yGap = 400; const xGap = 500; function setup() { createCanvas(windowWidth, windowHeight); noStroke(); noLoop(); } function draw() { background(133,203,199); xPos = 0; yPos = -50; //logo pattern //small triangle to the left for (let x=xPos; x<width; x+=xGap){ for (let y=yPos; y<height; y+=yGap){ noFill(); stroke(255); strokeWeight(2); triangle(x-50, y, x, y-45, x-100, y-45); }} //small triangle to the right for (let x=xPos; x<width; x+=xGap){ for (let y=yPos; y<height; y+=yGap){ triangle(x, y, x+50, y-45, x-50, y-45); }} //large triangle to the left for (let x=xPos; x<width; x+=xGap){ for (let y=yPos; y<height; y+=yGap){ triangle(x, y, x+180, y-45, x-180, y-45); }} //large triangle to the right for (let x=xPos; x<width; x+=xGap){ for (let y=yPos; y<height; y+=yGap){ triangle(x-50, y, x+130, y-45, x-230, y-45); }} xPos=-250; yPos=-250; //offset logo pattern //small triangle to the left for (let x=xPos; x<width; x+=xGap){ for (let y=yPos; y<height; y+=yGap){ strokeWeight(3); triangle(x-50, y, x, y-45, x-100, y-45); }} //small triangle to the right for (let x=xPos; x<width; x+=xGap){ for (let y=yPos; y<height; y+=yGap){ triangle(x, y, x+50, y-45, x-50, y-45); }} //large triangle to the left for (let x=xPos; x<width; x+=xGap){ for (let y=yPos; y<height; y+=yGap){ triangle(x, y, x+180, y-45, x-180, y-45); }} //large triangle to the right for (let x=xPos; x<width; x+=xGap){ for (let y=yPos; y<height; y+=yGap){ triangle(x-50, y, x+130, y-45, x-230, y-45); }} //save(); } <file_sep>function setup() { createCanvas(windowWidth, windowHeight); noStroke(); noLoop(); } function draw() { background(133,203,199); //triangles for (let x=width/2-50; x<=width/1.9; x+=60){ for (let y=height/2+25; y<=height/1.8; y+=100){ noFill(); stroke(255); strokeWeight(5) triangle(x, y, x+50, y-45, x-50, y-45); triangle(x, y, x+180, y-45, x-180, y-45); }} //save(); } <file_sep>const height = 10; const width = 215; const height2 = 10; let horxPos = 0; let horyPos = 0; let verxPos = 0; let veryPos = 0; let countX = 0; function setup() { createCanvas(655, 640); noLoop(); noStroke(); colorMode(RGB); background(11, 51, 102); } function draw() { let rFill = random(0, 360); let rFill1 = random(0, 360); function horxGap(val) { const inc = 320 + countX; return inc + val; } function horyGap(val){ const inc = 35 + countX; return inc + val; } function horyGap1(val){ const inc = 120 + countX; return inc + val; } function veryGap(val){ const inc = 310 + countX; return inc + val; } function verxGap(val){ const inc = 125 + countX; return inc + val; } function horxSmL(val){ const inc = 40 + countX; return inc + val; } function horySmL1(val){ const inc = 55 - countX; return inc + val; } function horxSmR(val){ const inc = countX + width - 60; return inc + val; } function horySmL(val){ const inc = 40 + countX; return inc + val; } function verxSmL(val){ const inc = 180 + countX; return inc + val; } //start of horizontal //line1 horizontal bottom pattern1 fill(rFill, 169, 200); horxPos = 40; //long rect rect(horxPos, horyPos, width, height); //left small rect rect(horxSmL(horxPos), horySmL(horyPos), height, height2); //right small rect rect(horxSmR(horxPos), horySmL(horyPos), height, height2); //line1 horizontal bottom pattern2 horxPos=horxGap(horxPos); //long rect rect(horxPos, horyPos, width, height); //left small rect rect(horxSmL(horxPos), horySmL(horyPos), height, height2); //right small rect rect(horxSmR(horxPos), horySmL(horyPos), height, height2); //line2 horizontal top pattern1 horxPos=-120; horyPos=120; //long rect rect(horxPos, horyPos, width, height); //left small rect rect(horxSmL(horxPos), horySmL1(horyPos), height, height2); //right small rect rect(horxSmR(horxPos), horySmL1(horyPos), height, height2); //line2 horizontal top pattern2 horxPos=horxGap(horxPos); //long rect rect(horxPos, horyPos, width, height); //left small rect rect(horxSmL(horxPos), horySmL1(horyPos), height, height2); //right small rect rect(horxSmR(horxPos), horySmL1(horyPos), height, height2); //line2 horizontal top pattern3 horxPos=horxGap(horxPos); //long rect rect(horxPos, horyPos, width, height); //left small rect rect(horxSmL(horxPos), horySmL1(horyPos), height, height2); //right small rect rect(horxSmR(horxPos), horySmL1(horyPos), height, height2); //line2 horizontal bottom pattern1 horxPos=-120; horyPos=horyGap(horyPos); //long rect rect(horxPos, horyPos, width, height); //left small rect rect(horxSmL(horxPos), horySmL(horyPos), height, height2); //right small rect rect(horxSmR(horxPos), horySmL(horyPos), height, height2); //line2 horizontal bottom pattern2 horxPos=horxGap(horxPos); //long rect rect(horxPos, horyPos, width, height); //left small rect rect(horxSmL(horxPos), horySmL(horyPos), height, height2); //right small rect rect(horxSmR(horxPos), horySmL(horyPos), height, height2); //line2 horizontal bottom pattern3 horxPos=horxGap(horxPos); //long rect rect(horxPos, horyPos, width, height); //left small rect rect(horxSmL(horxPos), horySmL(horyPos), height, height2); //right small rect rect(horxSmR(horxPos), horySmL(horyPos), height, height2); //line3 horizontal top pattern1 horxPos=40; horyPos=horyGap1(horyPos); //long rect rect(horxPos, horyPos, width, height); //left small rect rect(horxSmL(horxPos), horySmL1(horyPos), height, height2); //right small rect rect(horxSmR(horxPos), horySmL1(horyPos), height, height2); //line3 horizontal top pattern2 horxPos=horxGap(horxPos); //long rect rect(horxPos, horyPos, width, height); //left small rect rect(horxSmL(horxPos), horySmL1(horyPos), height, height2); //right small rect rect(horxSmR(horxPos), horySmL1(horyPos), height, height2); //line3 horizontal bottom pattern1 horxPos=40; horyPos=horyGap(horyPos); //long rect rect(horxPos, horyPos, width, height); //left small rect rect(horxSmL(horxPos), horySmL(horyPos), height, height2); //right small rect rect(horxSmR(horxPos), horySmL(horyPos), height, height2); //line3 horizontal bottom pattern2 horxPos= horxGap(horxPos); //long rect rect(horxPos, horyPos, width, height); //left small rect rect(horxSmL(horxPos), horySmL(horyPos), height, height2); //right small rect rect(horxSmR(horxPos), horySmL(horyPos), height, height2); //line4 horizontal top pattern1 horxPos=-120; horyPos=horyGap1(horyPos); //long rect rect(horxPos, horyPos, width, height); //left small rect rect(horxSmL(horxPos), horySmL1(horyPos), height, height2); //right small rect rect(horxSmR(horxPos), horySmL1(horyPos), height, height2); //line4 horizontal top pattern2 horxPos=horxGap(horxPos); //long rect rect(horxPos, horyPos, width, height); //left small rect rect(horxSmL(horxPos), horySmL1(horyPos), height, height2); //right small rect rect(horxSmR(horxPos), horySmL1(horyPos), height, height2); //line4 horizontal top pattern3 horxPos=horxGap(horxPos); //long rect rect(horxPos, horyPos, width, height); //left small rect rect(horxSmL(horxPos), horySmL1(horyPos), height, height2); //right small rect rect(horxSmR(horxPos), horySmL1(horyPos), height, height2); //line4 horizontal bottom pattern1 horxPos=-120; horyPos= horyGap(horyPos); //long rect rect(horxPos, horyPos, width, height); //left small rect rect(horxSmL(horxPos), horySmL(horyPos), height, height2); //right small rect rect(horxSmR(horxPos), horySmL(horyPos), height, height2); //line4 horizontal bottom pattern2 horxPos=horxGap(horxPos); //long rect rect(horxPos, horyPos, width, height); //left small rect rect(horxSmL(horxPos), horySmL(horyPos), height, height2); //right small rect rect(horxSmR(horxPos), horySmL(horyPos), height, height2); //line4 horizontal bottom pattern3 horxPos=horxGap(horxPos); //long rect rect(horxPos, horyPos, width, height); //left small rect rect(horxSmL(horxPos), horySmL(horyPos), height, height2); //right small rect rect(horxSmR(horxPos), horySmL(horyPos), height, height2); //line5 horizontal top pattern1 horxPos=40; horyPos=horyGap1(horyPos); //long rect rect(horxPos, horyPos, width, height); //left small rect rect(horxSmL(horxPos), horySmL1(horyPos), height, height2); //right small rect rect(horxSmR(horxPos), horySmL1(horyPos), height, height2); //line5 horizontal top pattern2 horxPos=horxGap(horxPos); //long rect rect(horxPos, horyPos, width, height); //left small rect rect(horxSmL(horxPos), horySmL1(horyPos), height, height2); //right small rect rect(horxSmR(horxPos), horySmL1(horyPos), height, height2); //line5 horizontal bottom pattern1 horxPos=40; horyPos=horyGap(horyPos); //long rect rect(horxPos, horyPos, width, height); //left small rect rect(horxSmL(horxPos), horySmL(horyPos), height, height2); //right small rect rect(horxSmR(horxPos), horySmL(horyPos), height, height2); //line5 horizontal bottom pattern2 horxPos= horxGap(horxPos); //long rect rect(horxPos, horyPos, width, height); //left small rect rect(horxSmL(horxPos), horySmL(horyPos), height, height2); //right small rect rect(horxSmR(horxPos), horySmL(horyPos), height, height2); //start of vertical //line1 vertical right pattern1 fill(rFill1, 169, 200); verxPos=-5; veryPos=-115; //long rect rect(verxPos, veryPos, height, width); //top small rect rect(verxSmL(verxPos), horxSmL(veryPos), height2, height); //bottom small rect rect(verxSmL(verxPos), horxSmR(veryPos), height2, height); //line2 vertical right pattern2 veryPos=veryGap(veryPos); //long rect rect(verxPos, veryPos, height, width); //top small rect rect(verxSmL(verxPos), horxSmL(veryPos), height2, height); //bottom small rect rect(verxSmL(verxPos), horxSmR(veryPos), height2, height); //line3 vertical right pattern3 veryPos=veryGap(veryPos); //long rect rect(verxPos, veryPos, height, width); //top small rect rect(verxSmL(verxPos), horxSmL(veryPos), height2, height); //bottom small rect rect(verxSmL(verxPos), horxSmR(veryPos), height2, height); //line2 vertical left pattern1 verxPos=verxGap(verxPos); veryPos=40; //long rect rect(verxPos, veryPos, height, width); //top small rect rect(horySmL1(verxPos), horxSmL(veryPos), height2, height); //bottom small rect rect(horySmL1(verxPos), horxSmR(veryPos), height2, height); //line2 vertical left pattern2 veryPos=veryGap(veryPos); //long rect rect(verxPos, veryPos, height, width); //top small rect rect(horySmL1(verxPos), veryPos + 35, height2, height); //bottom small rect rect(horySmL1(verxPos), horxSmR(veryPos), height2, height); //line2 vertical right pattern1 verxPos=horyGap(verxPos); veryPos=40; //long rect rect(verxPos, veryPos, height, width); //top small rect rect(verxSmL(verxPos), horxSmL(veryPos), height2, height); //bottom small rect rect(verxSmL(verxPos), horxSmR(veryPos), height2, height); //line2 vertical right pattern2 veryPos=veryGap(veryPos); //long rect rect(verxPos, veryPos, height, width); //top small rect rect(verxSmL(verxPos), horxSmL(veryPos), height2, height); //bottom small rect rect(verxSmL(verxPos), horxSmR(veryPos), height2, height); //line3 vertical left pattern1 verxPos=verxGap(verxPos); veryPos=-115; //long rect rect(verxPos, veryPos, height, width); //top small rect rect(horySmL1(verxPos), horxSmL(veryPos), height2, height); //bottom small rect rect(horySmL1(verxPos), horxSmR(veryPos), height2, height); //line3 vertical left pattern2 veryPos=veryGap(veryPos); //long rect rect(verxPos, veryPos, height, width); //top small rect rect(horySmL1(verxPos),horxSmL(veryPos), height2, height); //bottom small rect rect(horySmL1(verxPos), horxSmR(veryPos), height2, height); //line3 vertical left pattern3 veryPos=veryGap(veryPos); //long rect rect(verxPos, veryPos, height, width); //top small rect rect(horySmL1(verxPos), horxSmL(veryPos), height2, height); //bottom small rect rect(horySmL1(verxPos), horxSmR(veryPos), height2, height); //line3 vertical right pattern1 verxPos=horyGap(verxPos); veryPos=-115; //long rect rect(verxPos, veryPos, height, width); //top small rect rect(verxSmL(verxPos), horxSmL(veryPos), height2, height); //bottom small rect rect(verxSmL(verxPos), horxSmR(veryPos), height2, height); //line3 vertical right pattern2 veryPos=veryGap(veryPos); //long rect rect(verxPos, veryPos, height, width); //top small rect rect(verxSmL(verxPos), horxSmL(veryPos), height2, height); //bottom small rect rect(verxSmL(verxPos), horxSmR(veryPos), height2, height); //line3 vertical right pattern3 veryPos=veryGap(veryPos); //long rect rect(verxPos, veryPos, height, width); //top small rect rect(verxSmL(verxPos), horxSmL(veryPos), height2, height); //bottom small rect rect(verxSmL(verxPos), horxSmR(veryPos), height2, height); //line4 vertical left pattern1 verxPos=verxGap(verxPos); veryPos=40; //long rect rect(verxPos, veryPos, height, width); //top small rect rect(horySmL1(verxPos), horxSmL(veryPos), height2, height); //bottom small rect rect(horySmL1(verxPos), horxSmR(veryPos), height2, height); //line4 vertical left pattern2 veryPos=veryGap(veryPos); //long rect rect(verxPos, veryPos, height, width); //top small rect rect(horySmL1(verxPos), horxSmL(veryPos), height2, height); //bottom small rect rect(horySmL1(verxPos), horxSmR(veryPos), height2, height); //line4 vertical right pattern1 verxPos=horyGap(verxPos); veryPos=40; //long rect rect(verxPos, veryPos, height, width); //top small rect rect(verxSmL(verxPos), horxSmL(veryPos), height2, height); //bottom small rect rect(verxSmL(verxPos), horxSmR(veryPos), height2, height); //line4 vertical right pattern2 veryPos=veryGap(veryPos); //long rect rect(verxPos, veryPos, height, width); //top small rect rect(verxSmL(verxPos), horxSmL(veryPos), height2, height); //bottom small rect rect(verxSmL(verxPos), horxSmR(veryPos), height2, height); //line3 vertical left pattern1 verxPos=verxGap(verxPos); veryPos=-115; //long rect rect(verxPos, veryPos, height, width); //top small rect rect(horySmL1(verxPos), horxSmL(veryPos), height2, height); //bottom small rect rect(horySmL1(verxPos), horxSmR(veryPos), height2, height); //line3 vertical left pattern2 veryPos=veryGap(veryPos); //long rect rect(verxPos, veryPos, height, width); //top small rect rect(horySmL1(verxPos),horxSmL(veryPos), height2, height); //bottom small rect rect(horySmL1(verxPos), horxSmR(veryPos), height2, height); //line3 vertical left pattern3 veryPos=veryGap(veryPos); //long rect rect(verxPos, veryPos, height, width); //top small rect rect(horySmL1(verxPos),horxSmL(veryPos), height2, height); //bottom small rect rect(horySmL1(verxPos), horxSmR(veryPos), height2, height); //line3 vertical right pattern1 verxPos=horyGap(verxPos); veryPos=-115; //long rect rect(verxPos, veryPos, height, width); //top small rect rect(verxSmL(verxPos), horxSmL(veryPos), height2, height); //bottom small rect rect(verxSmL(verxPos), horxSmR(veryPos), height2, height); //line3 vertical right pattern2 veryPos=veryGap(veryPos); //long rect rect(verxPos, veryPos, height, width); //top small rect rect(verxSmL(verxPos), horxSmL(veryPos), height2, height); //bottom small rect rect(verxSmL(verxPos), horxSmR(veryPos), height2, height); //line3 vertical right pattern3 veryPos=veryGap(veryPos); //long rect rect(verxPos, veryPos, height, width); //top small rect rect(verxSmL(verxPos), horxSmL(veryPos), height2, height); //bottom small rect rect(verxSmL(verxPos), horxSmR(veryPos), height2, height); }<file_sep>const largeSqu = 115; const midSqu = 95; const smlSqu = 55; const diam = 45; let xPos = 0; let yPos = 0; function setup() { createCanvas(750, 500); noLoop(); noStroke(); } function draw() { background(93, 84, 67); //line1 pattern 1 //top left square //large square fill(212, 194, 164); square(xPos, yPos, largeSqu); //medium square fill(162, 148, 124); square(xPos+10, yPos+10, midSqu); //small square fill(212, 194, 164); square(xPos+30, yPos+30, smlSqu); //circle fill(162, 148, 124); circle(xPos+35, yPos+35, diam); //top right square //large square xPos=125 fill(212, 194, 164); square(xPos, yPos, largeSqu); //medium square fill(162, 148, 124); square(xPos+10, yPos+10, midSqu); //small square fill(212, 194, 164); square(xPos+30, yPos+30, smlSqu); //circle fill(162, 148, 124); circle(xPos+80, yPos+35, diam); //bottom left square //large square xPos=0 yPos=125 fill(191, 182, 139); square(xPos, yPos, largeSqu); //medium square fill(35, 25, 24); square(xPos+10, yPos+10, midSqu); //small square fill(191, 182, 139); square(xPos+30, yPos+30, smlSqu); //circle fill(35, 25, 24); circle(xPos+35, yPos+80, diam); //bottom right square //large square xPos=125 yPos=125 fill(191, 182, 139); square(xPos, yPos, largeSqu); //medium square fill(35, 25, 24); square(xPos+10, yPos+10, midSqu); //small square fill(191, 182, 139); square(xPos+30, yPos+30, smlSqu); //circle fill(35, 25, 24); circle(xPos+80, yPos+80, diam); //line1 pattern 2 //top left square //large square xPos=250 yPos=0 fill(212, 194, 164); square(xPos, yPos, largeSqu); //medium square fill(162, 148, 124); square(xPos+10, yPos+10, midSqu); //small square fill(212, 194, 164); square(xPos+30, yPos+30, smlSqu); //circle fill(162, 148, 124); circle(xPos+35, yPos+35, diam); //top right square //large square xPos=375 fill(212, 194, 164); square(xPos, yPos, largeSqu); //medium square fill(162, 148, 124); square(xPos+10, yPos+10, midSqu); //small square fill(212, 194, 164); square(xPos+30, yPos+30, smlSqu); //circle fill(162, 148, 124); circle(xPos+80, yPos+35, diam); //bottom left square //large square xPos=250 yPos=125 fill(191, 182, 139); square(xPos, yPos, largeSqu); //medium square fill(35, 25, 24); square(xPos+10, yPos+10, midSqu); //small square fill(191, 182, 139); square(xPos+30, yPos+30, smlSqu); //circle fill(35, 25, 24); circle(xPos+35, yPos+80, diam); //bottom right square //large square xPos=375 yPos=125 fill(191, 182, 139); square(xPos, yPos, largeSqu); //medium square fill(35, 25, 24); square(xPos+10, yPos+10, midSqu); //small square fill(191, 182, 139); square(xPos+30, yPos+30, smlSqu); //circle fill(35, 25, 24); circle(xPos+80, yPos+80, diam); //line1 pattern 3 //top left square //large square xPos=500 yPos=0 fill(212, 194, 164); square(xPos, yPos, largeSqu); //medium square fill(162, 148, 124); square(xPos+10, yPos+10, midSqu); //small square fill(212, 194, 164); square(xPos+30, yPos+30, smlSqu); //circle fill(162, 148, 124); circle(xPos+35, yPos+35, diam); //top right square //large square xPos=625 fill(212, 194, 164); square(xPos, yPos, largeSqu); //medium square fill(162, 148, 124); square(xPos+10, yPos+10, midSqu); //small square fill(212, 194, 164); square(xPos+30, yPos+30, smlSqu); //circle fill(162, 148, 124); circle(xPos+80, yPos+35, diam); //bottom left square //large square xPos=500 yPos=125 fill(191, 182, 139); square(xPos, yPos, largeSqu); //medium square fill(35, 25, 24); square(xPos+10, yPos+10, midSqu); //small square fill(191, 182, 139); square(xPos+30, yPos+30, smlSqu); //circle fill(35, 25, 24); circle(xPos+35, yPos+80, diam); //bottom right square //large square xPos=625 yPos=125 fill(191, 182, 139); square(xPos, yPos, largeSqu); //medium square fill(35, 25, 24); square(xPos+10, yPos+10, midSqu); //small square fill(191, 182, 139); square(xPos+30, yPos+30, smlSqu); //circle fill(35, 25, 24); circle(xPos+80, yPos+80, diam); //line2 pattern 1 //top left square //large square xPos=0 yPos=250 fill(255, 248, 240); square(xPos, yPos, largeSqu); //medium square fill(250, 229, 205); square(xPos+10, yPos+10, midSqu); //small square fill(254, 221, 185); square(xPos+30, yPos+30, smlSqu); //circle fill(250, 229, 205); circle(xPos+35, yPos+35, diam); //top right square //large square xPos=125 fill(255, 248, 240); square(xPos, yPos, largeSqu); //medium square fill(250, 229, 205); square(xPos+10, yPos+10, midSqu); //small square fill(254, 221, 185); square(xPos+30, yPos+30, smlSqu); //circle fill(250, 229, 205); circle(xPos+80, yPos+35, diam); //bottom left square //large square xPos=0 yPos=375 fill(191, 182, 139); square(xPos, yPos, largeSqu); //medium square fill(35, 25, 24); square(xPos+10, yPos+10, midSqu); //small square fill(191, 182, 139); square(xPos+30, yPos+30, smlSqu); //circle fill(35, 25, 24); circle(xPos+35, yPos+80, diam); //bottom right square //large square xPos=125 yPos=375 fill(191, 182, 139); square(xPos, yPos, largeSqu); //medium square fill(35, 25, 24); square(xPos+10, yPos+10, midSqu); //small square fill(191, 182, 139); square(xPos+30, yPos+30, smlSqu); //circle fill(35, 25, 24); circle(xPos+80, yPos+80, diam); //line2 pattern 2 //top left square //large square xPos=250 yPos=250 fill(255, 248, 240); square(xPos, yPos, largeSqu); //medium square fill(250, 229, 205); square(xPos+10, yPos+10, midSqu); //small square fill(254, 221, 185); square(xPos+30, yPos+30, smlSqu); //circle fill(250, 229, 205); circle(xPos+35, yPos+35, diam); //top right square //large square xPos=375 fill(255, 248, 240); square(xPos, yPos, largeSqu); //medium square fill(250, 229, 205); square(xPos+10, yPos+10, midSqu); //small square fill(254, 221, 185); square(xPos+30, yPos+30, smlSqu); //circle fill(250, 229, 205); circle(xPos+80, yPos+35, diam); //bottom left square //large square xPos=250 yPos=375 fill(191, 182, 139); square(xPos, yPos, largeSqu); //medium square fill(35, 25, 24); square(xPos+10, yPos+10, midSqu); //small square fill(191, 182, 139); square(xPos+30, yPos+30, smlSqu); //circle fill(35, 25, 24); circle(xPos+35, yPos+80, diam); //bottom right square //large square xPos=375 yPos=375 fill(191, 182, 139); square(xPos, yPos, largeSqu); //medium square fill(35, 25, 24); square(xPos+10, yPos+10, midSqu); //small square fill(191, 182, 139); square(xPos+30, yPos+30, smlSqu); //circle fill(35, 25, 24); circle(xPos+80, yPos+80, diam); //line2 pattern 3 //top left square //large square xPos=500 yPos=250 fill(255, 248, 240); square(xPos, yPos, largeSqu); //medium square fill(250, 229, 205); square(xPos+10, yPos+10, midSqu); //small square fill(254, 221, 185); square(xPos+30, yPos+30, smlSqu); //circle fill(250, 229, 205); circle(xPos+35, yPos+35, diam); //top right square //large square xPos=625 fill(255, 248, 240); square(xPos, yPos, largeSqu); //medium square fill(250, 229, 205); square(xPos+10, yPos+10, midSqu); //small square fill(254, 221, 185); square(xPos+30, yPos+30, smlSqu); //circle fill(250, 229, 205); circle(xPos+80, yPos+35, diam); //bottom left square //large square xPos=500 yPos=375 fill(191, 182, 139); square(xPos, yPos, largeSqu); //medium square fill(35, 25, 24); square(xPos+10, yPos+10, midSqu); //small square fill(191, 182, 139); square(xPos+30, yPos+30, smlSqu); //circle fill(35, 25, 24); circle(xPos+35, yPos+80, diam); //bottom right square //large square xPos=625 yPos=375 fill(191, 182, 139); square(xPos, yPos, largeSqu); //medium square fill(35, 25, 24); square(xPos+10, yPos+10, midSqu); //small square fill(191, 182, 139); square(xPos+30, yPos+30, smlSqu); //circle fill(35, 25, 24); circle(xPos+80, yPos+80, diam); }<file_sep>const diam = 100; let xPos = 350 let yPos = 350 function setup() { createCanvas(600, 600); noStroke(); noLoop(); } function draw() { background(250); //left ear fill(148, 121, 104); ellipse(xPos - 50, yPos - 45, diam/2, diam/2); //right ear fill(148, 121, 104); ellipse(xPos + 50, yPos - 45, diam/2, diam/2); //head fill(134, 107, 90); ellipse(xPos, yPos, diam + 30, diam); //nose fill(191, 166, 150 ); ellipse(xPos, yPos + 10, diam - 50, diam - 70); //left eye fill(66, 54, 47); ellipse(xPos-30, yPos - 8, diam/5, diam/5) //right eye fill(66, 54, 47); ellipse(xPos+30, yPos - 8, diam/5, diam/5) //pink nose fill(230, 198, 214); ellipse(xPos, yPos, 20, 10); }<file_sep>//runs once and setups the scene function setup(){ createCanvas(700,700); } //runs FOREVER function draw(){ background(211,175,139); //most bottom layer noStroke(); fill(203,184,171); strokeWeight(9); stroke(139, 117, 109); ellipse(580, 350, 430, 940); noStroke(); fill(211,175,139); strokeWeight(9); stroke(139, 117, 109); ellipse(650, 400, 430, 940); noStroke(); fill(211,175,139); beginShape(); vertex(300, 350); vertex(750, 350); vertex(750, 710); vertex(300, 710); endShape(CLOSE); noStroke(); fill(203,184,171); strokeWeight(9); stroke(139, 117, 109); beginShape(); vertex(162, 90); vertex(750, 90); vertex(750, 648); vertex(162, 648); endShape(CLOSE); noStroke(); fill(196, 153, 108); strokeWeight(9); stroke(139, 117, 109); beginShape(); vertex(162, 90); vertex(750, 90); vertex(750, 350); vertex(162, 350); endShape(CLOSE); noStroke(); fill(237,189,141); strokeWeight(9); stroke(139, 117, 109); beginShape(); vertex(432, 350); vertex(750, 350); vertex(720, 522); vertex(432, 522); endShape(CLOSE); noStroke(); fill(255, 255, 255); strokeWeight(9); stroke(139, 117, 109); beginShape(); vertex(432, 350); vertex(750, 350); vertex(740, 450); vertex(432, 450); endShape(CLOSE); noStroke(); fill(248, 210, 111); strokeWeight(9); stroke(139, 117, 109); beginShape(); vertex(350, 410); vertex(750, 410); vertex(740, 450); vertex(350, 450); endShape(CLOSE); noStroke(); fill(237,189,141); strokeWeight(9); stroke(139, 117, 109); beginShape(); vertex(-10, 500); vertex(380, 500); vertex(380, 720); vertex(-10, 720); endShape(CLOSE); }<file_sep>// runs once and setups the scene function setup(){ createCanvas(400, 400); } // runs FOREVER function draw(){ var rectWidth = 50; var rectHeight = 50; background(300); noStroke(); fill("red") ellipse(width/2, height/2, 100, 100); stroke(0); fill("green"); rect(width/2-rectWidth/2, height/2-rectHeight/2, 50, 50); noStroke(); fill("blue"); ellipse(width/2,height/2, 20, 20); stroke(0); fill(200, 0 , 200, 50); triangle(width/2, 100, 320, 100, 310, 80); }<file_sep>//runs once and setups the scene function setup(){ createCanvas(600,600); } //runs FOREVER function draw(){ var rectWidth = 50; var rectHeight = 100; background("black"); //most bottom layer noStroke(); fill("red"); ellipse(width/2, height/2, 100, 100); // rectangle stroke(0); //black line fill("white"); rect(0,600 - rectHeight, 60, 100); noStroke(); fill("orange"); beginShape(); vertex(-50,500); vertex(400,500); vertex(80,300); endShape(CLOSE); triangle(width/2, 100, 320, 100, 310, 80); ellipse(width/2, height/2, 100, 100); stroke(0); fill("green"); rect(width/2-rectWidth/2, height/2-rectHeight/2, 50, 50); noStroke(); fill("blue"); ellipse(width/2,height/2, 20, 20); stroke(0); fill(200, 0 , 200, 50); triangle(width/2, 100, 320, 100, 310, 80); }<file_sep>//runs once and setups the scene function setup(){ createCanvas(700,700); } //runs FOREVER function draw(){ background(255,255,255); //most bottom layer noStroke(); fill(172, 154, 117); strokeWeight(9); stroke(51, 51, 51); beginShape(); vertex(234, -10); vertex(710, -10); vertex(710, 710); vertex(234, 710); endShape(CLOSE); noStroke(); fill(21, 53, 98); strokeWeight(9); stroke(51, 51, 51); beginShape(); vertex(0, 710); vertex(234, 468); vertex(710, 710); endShape(CLOSE); noStroke(); fill(172, 154, 117); strokeWeight(9); stroke(51, 51, 51); beginShape(); vertex(216, -10); vertex(710, -10); vertex(710, 368); vertex(378, 230); vertex(378, 200); vertex(216, 126); endShape(CLOSE); noStroke(); fill(190, 174, 139); strokeWeight(9); stroke(51, 51, 51); beginShape(); vertex(400, 270); vertex(710, 400); vertex(710, 575); vertex(400, 432); endShape(CLOSE); noStroke(); fill(116, 104, 78); strokeWeight(9); stroke(51, 51, 51); beginShape(); vertex(400, 270); vertex(710, 400); vertex(710, 440); vertex(400, 306); endShape(CLOSE); noStroke(); fill(255, 255, 255); strokeWeight(9); stroke(51, 51, 51); beginShape(); vertex(349, 216); vertex(710, 368); vertex(710, 405); vertex(349, 252); endShape(CLOSE); noStroke(); fill(190, 174, 139); strokeWeight(9); stroke(51, 51, 51); beginShape(); vertex(36, -10); vertex(126, -10); vertex(126, 710); vertex(36, 710); endShape(CLOSE); }<file_sep>//runs once and setups the scene function setup(){ createCanvas(700,700); } //runs FOREVER function draw(){ background(52, 52, 52); //most bottom layer noStroke(); fill(245, 238, 211); strokeWeight(9); stroke(22, 15, 2); beginShape(); vertex(-10, -10); vertex(260, -10); vertex(198, 414); vertex(-10, 270); endShape(CLOSE); noStroke(); fill(123, 114, 82); strokeWeight(9); stroke(22, 15, 2); beginShape(); vertex(260, -10); vertex(402, -10); vertex(342, 360); vertex(198, 414); endShape(CLOSE); noStroke(); fill(245, 238, 211); strokeWeight(9); stroke(22, 15, 2); beginShape(); vertex(522, -10); vertex(710, -10); vertex(710, 216); vertex(486, 144); endShape(CLOSE); noStroke(); fill(245, 238, 211); strokeWeight(9); stroke(22, 15, 2); beginShape(); vertex(288, 540); vertex(421, 656); vertex(425, 710); vertex(300, 710); endShape(CLOSE); noStroke(); fill(123, 114, 82); strokeWeight(9); stroke(22, 15, 2); beginShape(); vertex(421, 656); vertex(710, 468); vertex(710, 710); vertex(425, 710); endShape(CLOSE); noStroke(); fill(205, 192, 145); strokeWeight(9); stroke(22, 15, 2); beginShape(); vertex(288, 540); vertex(710, 288); vertex(710, 468); vertex(421, 656); endShape(CLOSE); noStroke(); fill(245, 238, 211); strokeWeight(9); stroke(22, 15, 2); beginShape(); vertex(-10, 612); vertex(43, 641); vertex(45, 710); vertex(-10, 710); endShape(CLOSE); noStroke(); fill(205, 192, 145); strokeWeight(9); stroke(22, 15, 2); beginShape(); vertex(-10, 450); vertex(168, 576); vertex(43, 641); vertex(-10, 612); endShape(CLOSE); noStroke(); fill(123, 114, 82); strokeWeight(9); stroke(22, 15, 2); beginShape(); vertex(43, 641); vertex(168, 576); vertex(173, 710); vertex(45, 710); endShape(CLOSE); }<file_sep>const height = 20; const width = 215; const height2 = 25; let horxPos = 40; let horyPos = 0; let verxPos = 0; let veryPos = 0; function setup() { createCanvas(655, 640); noLoop(); noStroke(); } function draw() { background(125,105,50); //start of horizontal //line1 horizontal bottom pattern fill(65,51,14); //long rect rect(horxPos, horyPos, width, height); //left small rect rect(horxPos + 35, horyPos + 20, height, height2); //right small rect rect(horxPos + width - 55, horyPos + 20, height, height2); //line1 horizontal bottom pattern2 horxPos=360; //long rect rect(horxPos, horyPos, width, height); //left small rect rect(horxPos + 35, horyPos + 20, height, height2); //right small rect rect(horxPos + width - 55, horyPos + 20, height, height2); //line2 horizontal top pattern1 horxPos=-120; horyPos=120; //long rect rect(horxPos, horyPos, width, height); //left small rect rect(horxPos + 35, horyPos - 25, height, height2); //right small rect rect(horxPos + width - 55, horyPos - 25, height, height2); //line2 horizontal top pattern2 horxPos=horxPos+320; //long rect rect(horxPos, horyPos, width, height); //left small rect rect(horxPos + 35, horyPos - 25, height, height2); //right small rect rect(horxPos + width - 55, horyPos - 25, height, height2); //line2 horizontal top pattern3 horxPos=horxPos+320; //long rect rect(horxPos, horyPos, width, height); //left small rect rect(horxPos + 35, horyPos - 25, height, height2); //right small rect rect(horxPos + width - 55, horyPos - 25, height, height2); //line2 horizontal bottom pattern1 horxPos=-120; horyPos=horyPos+35; //long rect rect(horxPos, horyPos, width, height); //left small rect rect(horxPos + 35, horyPos + 20, height, height2); //right small rect rect(horxPos + width - 55, horyPos + 20, height, height2); //line2 horizontal bottom pattern2 horxPos=horxPos+320; //long rect rect(horxPos, horyPos, width, height); //left small rect rect(horxPos + 35, horyPos + 20, height, height2); //right small rect rect(horxPos + width - 55, horyPos + 20, height, height2); //line2 horizontal bottom pattern3 horxPos=horxPos+320; //long rect rect(horxPos, horyPos, width, height); //left small rect rect(horxPos + 35, horyPos + 20, height, height2); //right small rect rect(horxPos + width - 55, horyPos + 20, height, height2); //line3 horizontal top pattern1 horxPos=40; horyPos=horyPos+120; //long rect rect(horxPos, horyPos, width, height); //left small rect rect(horxPos + 35, horyPos - 25, height, height2); //right small rect rect(horxPos + width - 55, horyPos - 25, height, height2); //line3 horizontal top pattern2 horxPos=horxPos+320; //long rect rect(horxPos, horyPos, width, height); //left small rect rect(horxPos + 35, horyPos - 25, height, height2); //right small rect rect(horxPos + width - 55, horyPos - 25, height, height2); //line3 horizontal bottom pattern1 horxPos=40; horyPos=horyPos+35; //long rect rect(horxPos, horyPos, width, height); //left small rect rect(horxPos + 35, horyPos + 20, height, height2); //right small rect rect(horxPos + width - 55, horyPos + 20, height, height2); //line3 horizontal bottom pattern2 horxPos= horxPos+320; //long rect rect(horxPos, horyPos, width, height); //left small rect rect(horxPos + 35, horyPos + 20, height, height2); //right small rect rect(horxPos + width - 55, horyPos + 20, height, height2); //line4 horizontal top pattern1 horxPos=-120; horyPos=horyPos+120; //long rect rect(horxPos, horyPos, width, height); //left small rect rect(horxPos + 35, horyPos - 25, height, height2); //right small rect rect(horxPos + width - 55, horyPos - 25, height, height2); //line4 horizontal top pattern2 horxPos=horxPos+320; //long rect rect(horxPos, horyPos, width, height); //left small rect rect(horxPos + 35, horyPos - 25, height, height2); //right small rect rect(horxPos + width - 55, horyPos - 25, height, height2); //line4 horizontal top pattern3 horxPos=horxPos+320; //long rect rect(horxPos, horyPos, width, height); //left small rect rect(horxPos + 35, horyPos - 25, height, height2); //right small rect rect(horxPos + width - 55, horyPos - 25, height, height2); //line4 horizontal bottom pattern1 horxPos=-120; horyPos= horyPos+35; //long rect rect(horxPos, horyPos, width, height); //left small rect rect(horxPos + 35, horyPos + 20, height, height2); //right small rect rect(horxPos + width - 55, horyPos + 20, height, height2); //line4 horizontal bottom pattern2 horxPos=horxPos+320; //long rect rect(horxPos, horyPos, width, height); //left small rect rect(horxPos + 35, horyPos + 20, height, height2); //right small rect rect(horxPos + width - 55, horyPos + 20, height, height2); //line4 horizontal bottom pattern3 horxPos=horxPos+320; //long rect rect(horxPos, horyPos, width, height); //left small rect rect(horxPos + 35, horyPos + 20, height, height2); //right small rect rect(horxPos + width - 55, horyPos + 20, height, height2); //line5 horizontal top pattern1 horxPos=40; horyPos=horyPos+120; //long rect rect(horxPos, horyPos, width, height); //left small rect rect(horxPos + 35, horyPos - 25, height, height2); //right small rect rect(horxPos + width - 55, horyPos - 25, height, height2); //line5 horizontal top pattern2 horxPos=horxPos+320; //long rect rect(horxPos, horyPos, width, height); //left small rect rect(horxPos + 35, horyPos - 25, height, height2); //right small rect rect(horxPos + width - 55, horyPos - 25, height, height2); //line5 horizontal bottom pattern1 horxPos=40; horyPos=horyPos+35; //long rect rect(horxPos, horyPos, width, height); //left small rect rect(horxPos + 35, horyPos + 20, height, height2); //right small rect rect(horxPos + width - 55, horyPos + 20, height, height2); //line5 horizontal bottom pattern2 horxPos= horxPos+320; //long rect rect(horxPos, horyPos, width, height); //left small rect rect(horxPos + 35, horyPos + 20, height, height2); //right small rect rect(horxPos + width - 55, horyPos + 20, height, height2); //start of vertical //line1 vertical right pattern1 verxPos=-5; veryPos=-115; //long rect rect(verxPos, veryPos, height, width); //top small rect rect(verxPos + 20, veryPos + 35, height2, height); //bottom small rect rect(verxPos + 20, veryPos + width - 55, height2, height); //line2 vertical right pattern2 veryPos=195; //long rect rect(verxPos, veryPos, height, width); //top small rect rect(verxPos + 20, veryPos + 35, height2, height); //bottom small rect rect(verxPos + 20, veryPos + width - 55, height2, height); //line3 vertical right pattern3 veryPos=505; //long rect rect(verxPos, veryPos, height, width); //top small rect rect(verxPos + 20, veryPos + 35, height2, height); //bottom small rect rect(verxPos + 20, veryPos + width - 55, height2, height); //line2 vertical left pattern1 verxPos=120; veryPos=40; //long rect rect(verxPos, veryPos, height, width); //top small rect rect(verxPos - 25, veryPos + 35, height2, height); //bottom small rect rect(verxPos - 25, veryPos + width - 55, height2, height); //line2 vertical left pattern2 veryPos=350; //long rect rect(verxPos, veryPos, height, width); //top small rect rect(verxPos - 25, veryPos + 35, height2, height); //bottom small rect rect(verxPos - 25, veryPos + width - 55, height2, height); //line2 vertical right pattern1 verxPos=155; veryPos=40; //long rect rect(verxPos, veryPos, height, width); //top small rect rect(verxPos + 20, veryPos + 35, height2, height); //bottom small rect rect(verxPos + 20, veryPos + width - 55, height2, height); //line2 vertical right pattern2 veryPos=350; //long rect rect(verxPos, veryPos, height, width); //top small rect rect(verxPos + 20, veryPos + 35, height2, height); //bottom small rect rect(verxPos + 20, veryPos + width - 55, height2, height); //line3 vertical left pattern1 verxPos=280; veryPos=-115; //long rect rect(verxPos, veryPos, height, width); //top small rect rect(verxPos - 25, veryPos + 35, height2, height); //bottom small rect rect(verxPos - 25, veryPos + width - 55, height2, height); //line3 vertical left pattern2 veryPos=195; //long rect rect(verxPos, veryPos, height, width); //top small rect rect(verxPos - 25, veryPos + 35, height2, height); //bottom small rect rect(verxPos - 25, veryPos + width - 55, height2, height); //line3 vertical left pattern3 veryPos=505; //long rect rect(verxPos, veryPos, height, width); //top small rect rect(verxPos - 25, veryPos + 35, height2, height); //bottom small rect rect(verxPos - 25, veryPos + width - 55, height2, height); //line3 vertical right pattern1 verxPos=315; veryPos=-115; //long rect rect(verxPos, veryPos, height, width); //top small rect rect(verxPos + 20, veryPos + 35, height2, height); //bottom small rect rect(verxPos + 20, veryPos + width - 55, height2, height); //line3 vertical right pattern2 veryPos=195; //long rect rect(verxPos, veryPos, height, width); //top small rect rect(verxPos + 20, veryPos + 35, height2, height); //bottom small rect rect(verxPos + 20, veryPos + width - 55, height2, height); //line3 vertical right pattern3 veryPos=505; //long rect rect(verxPos, veryPos, height, width); //top small rect rect(verxPos + 20, veryPos + 35, height2, height); //bottom small rect rect(verxPos + 20, veryPos + width - 55, height2, height); //line4 vertical left pattern1 verxPos=440; veryPos=40; //long rect rect(verxPos, veryPos, height, width); //top small rect rect(verxPos - 25, veryPos + 35, height2, height); //bottom small rect rect(verxPos - 25, veryPos + width - 55, height2, height); //line4 vertical left pattern2 veryPos=350; //long rect rect(verxPos, veryPos, height, width); //top small rect rect(verxPos - 25, veryPos + 35, height2, height); //bottom small rect rect(verxPos - 25, veryPos + width - 55, height2, height); //line4 vertical right pattern1 verxPos=475; veryPos=40; //long rect rect(verxPos, veryPos, height, width); //top small rect rect(verxPos + 20, veryPos + 35, height2, height); //bottom small rect rect(verxPos + 20, veryPos + width - 55, height2, height); //line4 vertical right pattern2 veryPos=350; //long rect rect(verxPos, veryPos, height, width); //top small rect rect(verxPos + 20, veryPos + 35, height2, height); //bottom small rect rect(verxPos + 20, veryPos + width - 55, height2, height); //line3 vertical left pattern1 verxPos=600; veryPos=-115; //long rect rect(verxPos, veryPos, height, width); //top small rect rect(verxPos - 25, veryPos + 35, height2, height); //bottom small rect rect(verxPos - 25, veryPos + width - 55, height2, height); //line3 vertical left pattern2 veryPos=195; //long rect rect(verxPos, veryPos, height, width); //top small rect rect(verxPos - 25, veryPos + 35, height2, height); //bottom small rect rect(verxPos - 25, veryPos + width - 55, height2, height); //line3 vertical left pattern3 veryPos=505; //long rect rect(verxPos, veryPos, height, width); //top small rect rect(verxPos - 25, veryPos + 35, height2, height); //bottom small rect rect(verxPos - 25, veryPos + width - 55, height2, height); //line3 vertical right pattern1 verxPos=635; veryPos=-115; //long rect rect(verxPos, veryPos, height, width); //top small rect rect(verxPos + 20, veryPos + 35, height2, height); //bottom small rect rect(verxPos + 20, veryPos + width - 55, height2, height); //line3 vertical right pattern2 veryPos=195; //long rect rect(verxPos, veryPos, height, width); //top small rect rect(verxPos + 20, veryPos + 35, height2, height); //bottom small rect rect(verxPos + 20, veryPos + width - 55, height2, height); //line3 vertical right pattern3 veryPos=505; //long rect rect(verxPos, veryPos, height, width); //top small rect rect(verxPos + 20, veryPos + 35, height2, height); //bottom small rect rect(verxPos + 20, veryPos + width - 55, height2, height); }<file_sep>function setup() { createCanvas(windowWidth, windowHeight); noStroke(); } function draw() { background(180, 228, 225); let gap = 20; //moving squares for (let x = 0; x < gap; x++) { for (let y = 0; y < gap; y++) { let move1 = mouseX / 20 * random(-1, 0); let move2 = mouseY / 20 * random(-1, 0); let xPos = width / 20 * x; let yPos = height / 20 * y; fill(133,203,199,100); noStroke(); //squares push(); translate(xPos, yPos); square(move1,move2,100); pop(); }} //logo for (let x=width/2-50; x<=width/1.9; x+=60){ for (let y=height/2+25; y<=height/1.8; y+=100){ noFill(); stroke(255); strokeWeight(5) triangle(x, y, x+50, y-45, x-50, y-45); triangle(x, y, x+180, y-45, x-180, y-45); }} }
bb6ddec93f0c7bd89dfb3ae58fa281ab5e47f2dd
[ "JavaScript" ]
13
JavaScript
stephaniehuang279/SP21-PUFY1225-DIGITAL-CRAFT
f656988c60cce033a2f9e42e85b5d2d18724244a
523c1399f794ab3ddd735bfe634e6f50e96257db
refs/heads/master
<file_sep>import scrapy from scrapy.http import Request import re class QbsSpider(scrapy.Spider): name = 'rushing_stats' allowed_domains = ['www.nfl.com'] start_urls = ['https://nfl.com/stats/player-stats/category/rushing/{}/REG/all/rushingyards/desc'.format([str(x) for x in range(1970,2021)][i]) for i in range(len([str(x) for x in range(1970,2021)]))] def parse(self, response): try: next_page = response.xpath('//a[@title="Next Page"]/@href').extract_first() next_page_url = 'https://www.nfl.com' + next_page absolute_url = Request(url=next_page_url) yield absolute_url except: pass table = response.xpath('//table') trs = table.xpath('.//tr')[1:] for tr in trs: Name = tr.xpath('.//*[@class="d3-o-player-fullname nfl-o-cta--link"]/text()').re(r'\w+\s\w+') Year = response.xpath('//option[@selected="selected"]/text()').re(r'\d+') RushingYards = tr.xpath('.//td[2]/text()').re(r'\d+') Att = tr.xpath('.//td[3]/text()').re(r'\d+') TD = tr.xpath('.//td[4]/text()').re(r'\d+') TwentyPlus = tr.xpath('.//td[5]/text()').re(r'\d+') FourtyPlus = tr.xpath('.//td[6]/text()').re(r'\d+') Lng = tr.xpath('.//td[7]/text()').re(r'\d+') RushingFirst = tr.xpath('.//td[8]/text()').re(r'\d+') RushingFirstPerc = tr.xpath('.//td[9]/text()').re(r'\d+.\d+') RushingFum = tr.xpath('.//td[10]/text()').re(r'\d+') yield { 'Name' : Name, 'Year' : Year, 'RushingYards' : RushingYards, 'Att' : Att, 'TD' : TD, 'TwentyPlus' : TwentyPlus, 'FourtyPlus' : FourtyPlus, 'Lng' : Lng, 'RushingFirst' : RushingFirst, 'RushingFirstPerc' : RushingFirstPerc, 'RushingFum' : RushingFum, } <file_sep>import scrapy from scrapy.http import Request class QbsSpider(scrapy.Spider): name = 'receiving_stats' allowed_domains = ['www.nfl.com'] start_urls = ['https://www.nfl.com/stats/player-stats/category/receiving/{}/REG/all/receivingreceptions/desc/'.format([str(x) for x in range(1970,2021)][i]) for i in range(len([str(x) for x in range(1970,2021)]))] def parse(self, response): try: next_page = response.xpath('//a[@title="Next Page"]/@href').extract_first() next_page_url = 'https://www.nfl.com' + next_page absolute_url = Request(url=next_page_url) yield absolute_url except: pass table = response.xpath('//table') trs = table.xpath('.//tr')[1:] for tr in trs: Name = tr.xpath('.//*[@class="d3-o-player-fullname nfl-o-cta--link"]/text()').re(r'\w+\s\w+') Year = response.xpath('//option[@selected="selected"]/text()').re(r'\d+') Rec = tr.xpath('.//td[2]/text()').re(r'\d+') Yards = tr.xpath('.//td[3]/text()').re(r'\d+.\d+') TD = tr.xpath('.//td[4]/text()').re(r'\d+') TwentyPlus = tr.xpath('.//td[5]/text()').re(r'\d+') FortyPlus = tr.xpath('.//td[6]/text()').re(r'\d+') Lng = tr.xpath('.//td[7]/text()').re(r'\d+') RecFirst = tr.xpath('.//td[8]/text()').re(r'\d+') FirstPerc = tr.xpath('.//td[9]/text()').re(r'\d+.\d+') RecFUM = tr.xpath('.//td[10]/text()').re(r'\d+') Targets = tr.xpath('.//td[12]/text()').re(r'\d+') yield { 'Name' : Name, 'Year' : Year, 'Rec' : Rec, 'Yards' : Yards, 'TD' : TD, '20+' : TwentyPlus, '40+' : FortyPlus, 'Lng' : Lng, 'Rec 1st' : RecFirst, '1st %' : FirstPerc, 'Rec FUM' : RecFUM, 'Targets' : Targets, } <file_sep>import scrapy from scrapy.http import Request import re class QbsSpider(scrapy.Spider): name = 'passing_stats' allowed_domains = ['www.nfl.com'] start_urls = ['https://nfl.com/stats/player-stats/category/passing/{}/REG/all/passingyards/desc'.format([str(x) for x in range(1970,2021)][i]) for i in range(len([str(x) for x in range(1970,2021)]))] def parse(self, response): try: next_page = response.xpath('//a[@title="Next Page"]/@href').extract_first() next_page_url = 'https://www.nfl.com' + next_page absolute_url = Request(url=next_page_url) yield absolute_url except: pass table = response.xpath('//table') trs = table.xpath('.//tr')[1:] for tr in trs: Name = tr.xpath('.//*[@class="d3-o-player-fullname nfl-o-cta--link"]/text()').re(r'\w+\s\w+') Year = response.xpath('//option[@selected="selected"]/text()').re(r'\d+') PassYards = tr.xpath('.//td[2]/text()').re(r'\d+') YdsPerAtt = tr.xpath('.//td[3]/text()').re(r'\d+.\d+') Att = tr.xpath('.//td[4]/text()').re(r'\d+') Cmp = tr.xpath('.//td[5]/text()').re(r'\d+') CompPerc = tr.xpath('.//td[6]/text()').re(r'\d+.\d+') TD = tr.xpath('.//td[7]/text()').re(r'\d+') int = tr.xpath('.//td[8]/text()').re(r'\d+') Rate = tr.xpath('.//td[9]/text()').re(r'\d+.\d+') First = tr.xpath('.//td[10]/text()').re(r'\d+') FirstPerc = tr.xpath('.//td[11]/text()').re(r'\d+.\d+') TwentyPlus = tr.xpath('.//td[12]/text()').re(r'\d+') FortyPlus = tr.xpath('.//td[13]/text()').re(r'\d+') Lng = tr.xpath('.//td[14]/text()').re(r'\d+') Sck = tr.xpath('.//td[15]/text()').re(r'\d+') SckY = tr.xpath('.//td[16]/text()').re(r'\d+') PlayerHref = tr.xpath('.//a/@href').extract_first() Passing = 'https://www.nfl.com' + PlayerHref yield { 'Name' : Name, 'Year' : Year, 'PassYards' : PassYards, 'YdsPerAtt' : YdsPerAtt, 'Att' : Att, 'Cmp' : Cmp, 'Completion %' : CompPerc, 'TD' : TD, 'INT': int, 'Rate' : Rate, '1st' : First, '1st %' : FirstPerc, '20+' : TwentyPlus, '40+' : FortyPlus, 'Lng' : Lng, 'Sck' : Sck, 'SckY' : SckY, } <file_sep>import scrapy from scrapy.http import Request class CombineSpider(scrapy.Spider): handle_httpstatus_list = [404] name = 'combine' allowed_domains = ['nflcombineresults.com'] start_urls = ['https://nflcombineresults.com/nflcombinedata.php?year={}&pos=&college=' .format([str(x) for x in range(1987, 2021)][i]) for i in range(33)] def parse(self, response): hrefs = response.xpath('//*[contains(@href,"playerpage")]/@href').re('(?<=https://nflcombineresults.com/).+') for player in hrefs: players = 'https://nflcombineresults.com/' + player yield Request(players, callback=self.parse_player) def parse_player(self, response): first_name = response.xpath('//tr[contains(.,"First Name")]/td[2]/text()').re(r'\w+') last_name = response.xpath('//tr[contains(.,"Last Name")]/td[2]/text()').re(r'\w+') draft_year = response.xpath('//tr[contains(.,"Draft Class")]/td[2]/text()')[0].re(r'\d+') college = response.xpath('//tr[contains(.,"College")]/td[2]/text()').re(r'\w+') position = response.xpath('//tr[contains(.,"Position")]/td[2]/text()')[0].re(r'\w+') height = response.xpath('//tr[contains(.,"Height")]/td[2]/text()')[0].re(r'\d+') weight = response.xpath('//tr[contains(.,"Weight")]/td[2]/text()')[0].re(r'\d+') bmi = response.xpath('//tr[contains(.,"BMI")]/td[2]/text()')[0].re(r'\d+.\d+') arm_length = response.xpath('//tr[contains(.,"Arm Length")]/td[2]/text()')[0].re(r'\d+.\d+') hand_size = response.xpath('//tr[contains(.,"Hand Size")]/td[2]/text()')[0].re(r'\d+.\d+') wing_span = response.xpath('//tr[contains(.,"Wingspan")]/td[2]/text()')[0].re(r'\d+.\d+') forty_yard_dash = response.xpath('//tr[contains(.,"40 Yard Dash")]/td[2]/text()')[0].re(r'\d+.\d+') forty_yard_mph = response.xpath('//tr[contains(.,"40 Yard (MPH)")]/td[2]/text()')[0].re(r'\d+.\d+') twenty_yard_split = response.xpath('//tr[contains(.,"20 Yard Split")]/td[2]/text()')[0].re(r'\d+.\d+') bench = response.xpath('//tr[contains(.,"Bench Press")]/td[2]/text()')[0].extract() qb_ball_velocity = response.xpath('//tr[contains(.,"QB Ball Velocity")]/td[2]/text()')[0].extract() vertical_leap = response.xpath('//tr[contains(.,"Vertical Leap")]/td[2]/text()')[0].re(r'\d+.\d+') broad_jump = response.xpath('//tr[contains(.,"Broad Jump")]/td[2]/text()')[0].re(r'\d+.\d+') twenty_yrd_shuttle = response.xpath('//tr[contains(.,"20 Yd Shuttle")]/td[2]/text()')[0].re(r'\d+.\d+') three_cone = response.xpath('//tr[contains(.,"Three Cone")]/td[2]/text()')[0].re(r'\d+.\d+') yield {'First Name': first_name, 'Last Name': last_name, 'Draft Year': draft_year, 'College': college, 'Position': position, 'Height (inch)': height, 'Weight (lbs)': weight, 'BMI': bmi, 'ArmLength (inch)': arm_length, 'Hand Size (inch)': hand_size, 'Wing Span (inch)': wing_span, '40 Yard Dash (s)': forty_yard_dash, '40 Yard (MPH)': forty_yard_mph, '20 Yard Split (s)': twenty_yard_split, 'Bench Press': bench, 'QB Ball Velocity': qb_ball_velocity, 'Vertical Leap (inch)': vertical_leap, 'Broad Jump (inch)': broad_jump, '20 Yd Shuttle (s)': twenty_yrd_shuttle, 'Three Cone': three_cone } <file_sep>import scrapy from scrapy.http import Request import re class QbsSpider(scrapy.Spider): name = 'rushing_info' allowed_domains = ['www.nfl.com'] start_urls = ['https://nfl.com/stats/player-stats/category/rushing/{}/REG/all/rushingyards/desc'.format([str(x) for x in range(1970,2021)][i]) for i in range(len([str(x) for x in range(1970,2021)]))] def parse(self, response): players = response.xpath('//td/div/div/a/@href').extract() for player in players: qbs = 'https://www.nfl.com' + player yield Request(qbs, callback = self.player_data) try: next_page = response.xpath('//a[@title="Next Page"]/@href').extract_first() next_page_url = 'https://www.nfl.com' + next_page absolute_url = Request(url=next_page_url) yield absolute_url except: pass def player_data(self, response): Name = response.xpath('//h1/text()').extract() Team = response.xpath('//*[@class="nfl-o-cta--link"]/text()').extract() College = response.xpath('//li[contains(.,"College")]/div[2]/text()').extract() Height = response.xpath('//li[contains(.,"Height")]/div[2]/text()').extract() Weight = response.xpath('//li[contains(.,"Weight")]/div[2]/text()').extract() Arms = response.xpath('//li[contains(.,"Arms")]/div[2]/text()').extract() Hands = response.xpath('//li[contains(.,"Hands")]/div[2]/text()').extract() Age = response.xpath('//li[contains(.,"Age")]/div[2]/text()').extract() Position = response.xpath('//*[@class="nfl-c-player-header__position"]/text()').re('\w+') yield { 'Name':Name, 'Position':Position, 'Team':Team, 'College':College, 'Height': Height, 'Weight': Weight, 'Arms': Arms, 'Hands': Hands, 'Age': Age }
79e6712f270fbd81938fb32e66e5b768d07a543e
[ "Python" ]
5
Python
jiday512/nfl_spiders
0d330bed412fa88442a90bf79294ace745c31594
f8d48f9af37f977f97c56f81db873b86484538df
refs/heads/master
<repo_name>kuziomavladimir/HomeWork1<file_sep>/src/main/java/ru/example/MainClass.java package ru.example; import homework1.HomeWork1; import homework2.LifeCycle; public class MainClass { public static void main(String[] args) { // HomeWork1 homeWork1 = new HomeWork1(); new LifeCycle().startLife(); } } <file_sep>/src/main/java/homework2/Dog.java package homework2; public class Dog extends Animals { public Dog(String name) { this.name = name; health = 100; hunger = 20; // голод force = 35; // сила укуса isAlife = true; System.out.println("Собака создана"); } @Override public void doEat() { super.doEat(); health = (health > 100) ? 100 : health; } @Override public void doVote() { System.out.println("Av gav gav! wuf wuf!"); hunger += 2; checkHunger(); } @Override public void doMotion() { System.out.println(name + " Бежит гулять"); hunger += 5; checkHunger(); } @Override public void doClimbUpTrees() { System.out.println(name + ": Я не умею лазать по деревьям"); checkHunger(); } @Override public void doSwim() { System.out.println(name + " Плавает в бассейне"); hunger += 10; checkHunger(); } @Override public void checkHunger() { if(hunger > 65) health -= hunger / 10; if(health <= 0) isAlife = false; } }
7140620cfb0a8c74bd6a499c2ca0f19636599013
[ "Java" ]
2
Java
kuziomavladimir/HomeWork1
1046187ebb6d4553dd72db70205e1d259fd0c707
67750e8d0ea70a68ab23267ef893134efff766b6
refs/heads/master
<repo_name>hakanaku1234/OsuLearn<file_sep>/osu/rulesets/timing_points.py from . import hitobjects class TimingPoint: def __init__(self, *args): self.offset = int(args[0]) self.bpm = float(args[1]) self.meter = int(args[2]) self.sample_set = hitobjects.SampleSet(int(args[3])) self.sample_index = int(args[4]) self.volume = int(args[5]) self.inherited = bool(int(args[6])) self.kiai = bool(int(args[7])) def create(obj): return TimingPoint(*obj)<file_sep>/osu/rulesets/replay.py import lzma import time import matplotlib.pyplot as plt from matplotlib.path import Path import matplotlib.patches as mpatches from enum import IntFlag from . import beatmap as osu_beatmap from ._util.bsearch import bsearch from ._util.binfile import * from functools import reduce class Mod(IntFlag): DT = 0x40 HR = 0x10 class Replay: def __init__(self, file): self.game_mode = read_byte(file) # Sem minigames assert self.game_mode == 0, "Not a osu!std replay" # Versão do osu! e hash do mapa. A gente ignora. self.osu_version = read_int(file) self.map_md5 = read_binary_string(file) # Nome do jogador. self.player = read_binary_string(file) # Hash do replay. Dava pra usar, mas é meio desnecessário. self.replay_md5 = read_binary_string(file) # Acertos self.n_300s = read_short(file) self.n_100s = read_short(file) self.n_50s = read_short(file) self.n_geki = read_short(file) self.n_katu = read_short(file) self.n_misses = read_short(file) # Score e combo self.score = read_int(file) self.max_combo = read_short(file) self.perfect = read_byte(file) # Acurácia total = self.n_300s + self.n_100s + self.n_50s + self.n_misses self.accuracy = (self.n_300s + self.n_100s / 3 + self.n_50s / 6) / total # Mods (ignora) self.mods = Mod(read_int(file)) # Gráfico de vida. Vide site para o formato. life_graph = read_binary_string(file) self.life_graph = [t.split('|') for t in life_graph.split(',')[:-1]] # Timestamp do replay (ignora) self.timestamp = read_long(file) # Informações do replay em si replay_length = read_int(file) replay_data = lzma.decompress(file.read(replay_length)).decode('utf8') data = [t.split("|") for t in replay_data.split(',')[:-1]] data = [(int(w), float(x), float(y), int(z)) for w, x, y, z in data] self.data = [] offset = 0 for w, x, y, z in data: offset += w self.data.append((offset, x, y, z)) self.data = list(sorted(self.data)) # Não usado _ = read_long(file) def has_mods(self, *mods): mask = reduce(lambda x, y: x|y, mods) return bool(self.mods & mask) def frame(self, time): index = bsearch(self.data, time, lambda f: f[0]) offset, _, _, _ = self.data[index] if offset > time: if index > 0: return self.data[index - 1][1:] else: return (0, 0, 0) elif index >= len(self.data): index = -1 return self.data[index][1:] def load(filename): with open(filename, "rb") as file: return Replay(file)<file_sep>/osu/rulesets/_util/bezier.py # https://www.pygame.org/wiki/BezierCurve def compute(vertices, numPoints=None): if numPoints is None: numPoints = 30 if numPoints < 2 or len(vertices) != 4: return None result = [] b0x = vertices[0][0] b0y = vertices[0][1] b1x = vertices[1][0] b1y = vertices[1][1] b2x = vertices[2][0] b2y = vertices[2][1] b3x = vertices[3][0] b3y = vertices[3][1] # Compute polynomial coefficients from Bezier points ax = -b0x + 3 * b1x + -3 * b2x + b3x ay = -b0y + 3 * b1y + -3 * b2y + b3y bx = 3 * b0x + -6 * b1x + 3 * b2x by = 3 * b0y + -6 * b1y + 3 * b2y cx = -3 * b0x + 3 * b1x cy = -3 * b0y + 3 * b1y dx = b0x dy = b0y # Set up the number of steps and step size numSteps = numPoints - 1 # arbitrary choice h = 1.0 / numSteps # compute our step size # Compute forward differences from Bezier points and "h" pointX = dx pointY = dy firstFDX = ax * (h * h * h) + bx * (h * h) + cx * h firstFDY = ay * (h * h * h) + by * (h * h) + cy * h secondFDX = 6 * ax * (h * h * h) + 2 * bx * (h * h) secondFDY = 6 * ay * (h * h * h) + 2 * by * (h * h) thirdFDX = 6 * ax * (h * h * h) thirdFDY = 6 * ay * (h * h * h) # Compute points at each step result.append((int(pointX), int(pointY))) for _ in range(numSteps): pointX += firstFDX pointY += firstFDY firstFDX += secondFDX firstFDY += secondFDY secondFDX += thirdFDX secondFDY += thirdFDY result.append((int(pointX), int(pointY))) return result<file_sep>/README.md OsuLearn ======== ### An attempt at creating a Neural Network that learns how to play osu!std like a human from replays ###### (Plz don't judge me too much I'm new to machine learning and i can't english) Introduction ------------ > osu! is a free and open-source rhythm game developed and published by Australian-based company PPY Developments PTY, created by <NAME> (also known as peppy). Originally released for Microsoft Windows on September 16, 2007, the game has also been ported to macOS (this version might be unstable), and Windows Phone. Its gameplay is based on titles including Osu! Tatakae! Ouendan, Elite Beat Agents, Taiko no Tatsujin, Beatmania IIDX, O2Jam, and DJMax. > > -- <cite>[Wikipedia](https://en.wikipedia.org/wiki/Osu!)</cite> The goal here is to model and train a Neural Network to generate replays for any osu beatmap it is given based on a dataset of recorded human replays (`.osr` files) and their respective beatmap (`.osu`) file. To accomplish that, I've trained a Recurrent Neural Network with my replays and beatmaps. Results ------- This is a preview for a replay generated for a map the AI had never seen before: ![IA Generated Replay](https://media.giphy.com/media/cYDD6KQP0dqK1XcXpu/giphy.gif) Pretty good, actually! It has figured out how to aim without looking like a robot and can even hit some jumps. Of course it is not perfect, but neither is the data set it has been trained on, so I am considering this a success. Future ------ The next step is to transform this into a GAN, so it can generate multiple different replays for a given map, mimicking a human play style. This might take some time though, so that's it for now x).<file_sep>/osu/rulesets/_util/bsearch.py def bsearch(list, target, func): i = 0 beg = 0 end = len(list) while end > beg: i = (end + beg) // 2 obj_time = func(list[i]) if obj_time > target: end = i - 1 elif obj_time < target: beg = i + 1 else: break return i<file_sep>/osu/preview/__main__.py import math import os import re import numpy as np import pygame import mutagen.mp3 from osu.rulesets import beatmap as _beatmap, hitobjects as _hitobjects, \ replay as _replay from osu.rulesets.core import SCREEN_HEIGHT, SCREEN_WIDTH from osulearn import dataset from glob import glob from osu.preview import beatmap as beatmap_preview # Replay selection replays = glob(os.path.join(".generated", "* (*) [[]*[]].npy")) if len(replays) == 0: raise "No replays found" elif len(replays) == 1: replay_file = replays[0] else: for i, file in enumerate(replays): print(i, '-', os.path.basename(file)) replay_file = None while replay_file == None: print() print("Choose replay (0-{}):".format(len(replays) - 1), end='') n = input() if not n.isnumeric(): print("Invalid replay Id -", n) continue else: n = int(n) if n >= len(replays): print("Invalid replay Id -", n) continue replay_file = replays[n] replay_file = os.path.basename(replay_file) m = re.search(r"(.+)\s*\((.+)\)\s*\[(.+)\]", replay_file) assert not (m is None), "Invalid replay file" beatmap_pattern = "*{}*{}*{}*.osu".format(m[1], m[2], m[3]) # osu! Beatmap directory BEATMAPS_FOLDER = os.path.join(os.getenv('LocalAppData'), "osu!", "Songs") # Find beatmap beatmap_glob = glob(os.path.join(BEATMAPS_FOLDER, "**", beatmap_pattern)) assert len(beatmap_glob) > 0, "Beatmap not found" beatmap = _beatmap.load(beatmap_glob[0]) # Setup audio AUDIO = os.path.join(os.path.dirname(beatmap_glob[0]), beatmap["AudioFilename"]) mp3 = mutagen.mp3.MP3(AUDIO) pygame.mixer.init(frequency=mp3.info.sample_rate) pygame.mixer.music.load(AUDIO) # Load generated replay data REPLAY_DATA = os.path.join('.generated', replay_file) REPLAY_SAMPLING_RATE = dataset.FRAME_RATE ia_replay = np.load(REPLAY_DATA) pygame.init() time = 0 clock = pygame.time.Clock() screen = pygame.display.set_mode((SCREEN_WIDTH, SCREEN_HEIGHT)) FRAME_RATE = 1000 cx = 0 cy = 0 preview = beatmap_preview.from_beatmap(beatmap) trail = [] pygame.mixer.music.play(start=beatmap['AudioLeadIn'] / 1000) while True: time = pygame.mixer.music.get_pos() screen.fill((0, 0, 0)) for event in pygame.event.get(): if event.type == pygame.QUIT: exit(0) preview.render(screen, time) visible_objects = beatmap.visible_objects(time) if len(visible_objects) > 0: delta = visible_objects[0].time - time ox, oy = visible_objects[0].target_position(time, beatmap.beat_duration(time), beatmap['SliderMultiplier']) if delta > 0: cx += (ox - cx) / delta cy += (oy - cy) / delta else: cx = ox cy = oy #cx, cy, z = my_replay.frame(time) #pygame.draw.circle(screen, (255, 0, 0), (int(cx), int(cy)), 8) frame = (time - beatmap.start_offset()) // REPLAY_SAMPLING_RATE if frame > 0 and frame < len(ia_replay): x, y = ia_replay[frame] x += 0.5 y += 0.5 x *= SCREEN_WIDTH y *= SCREEN_HEIGHT pygame.draw.circle(screen, (0, 255, 0), (int(x), int(y)), 8) trail_surface = pygame.Surface((screen.get_width(), screen.get_height())) trail_surface.set_colorkey((0, 0, 0)) for tx, ty in trail: pygame.draw.circle(trail_surface, (0, 255, 0), (int(tx), int(ty)), 6) trail_surface.set_alpha(127) screen.blit(trail_surface, (0, 0)) trail.append((x, y)) if len(trail) > 64: trail.pop(0) pygame.display.flip() clock.tick(FRAME_RATE)<file_sep>/osu/rulesets/core.py SCREEN_WIDTH = 512 SCREEN_HEIGHT = 384 #CIRCLE_FADEOUT = 50 #SLIDER_FADEOUT = 100<file_sep>/osu/preview/beatmap.py from ..rulesets.beatmap import Beatmap as BeatmapRuleset from . import hitobjects COLOR_PALLETE = [ #( 255, 0, 0 ), ( 255, 0, 255 ), ( 255, 255, 0 ), #( 0, 255, 0 ), ( 0, 255, 255 ), ( 0, 0, 255 ), ] class Beatmap: def __init__(self, beatmap: BeatmapRuleset): self.beatmap = beatmap self.last_new_combo = 0 self.color_index = -1 def render(self, screen, time): visible_objects = self.beatmap.visible_objects(time) if len(visible_objects) == 0: return preempt, fade_in = self.beatmap.approach_rate() if visible_objects[0].new_combo and visible_objects[0].time > self.last_new_combo: self.color_index += visible_objects[0].combo_skip + 1 self.color_index %= len(COLOR_PALLETE) self.last_new_combo = visible_objects[0].time color_index = self.color_index circle_radius = int(self.beatmap.circle_radius()) beat_duration = self.beatmap.beat_duration(time) for i in range(len(visible_objects)): obj = visible_objects[i] if obj.new_combo and obj.time > self.last_new_combo: color_index += obj.combo_skip + 1 color_index %= len(COLOR_PALLETE) hitobjects.render( obj, time, screen, preempt, fade_in, COLOR_PALLETE[color_index], circle_radius, beat_duration, self.beatmap['SliderMultiplier'] ) def from_beatmap(beatmap): return Beatmap(beatmap)<file_sep>/osu/preview/hitobjects.py import pygame from ..rulesets import hitobjects as hitobjects def _render_hitcircle(hitcircle, time:int, screen:pygame.Surface, preempt: float, fade_in: float, color:pygame.Color, circle_radius:int, *args): surface = pygame.Surface((circle_radius * 2, circle_radius * 2)) surface.set_colorkey((0, 0, 0)) pygame.draw.circle(surface, color, (circle_radius, circle_radius), circle_radius) alpha = min([1, (time - hitcircle.time + preempt) / fade_in]) surface.set_alpha(alpha * 127) pos = (hitcircle.x - circle_radius, hitcircle.y - circle_radius) screen.blit(surface, pos) def _render_slider(slider, time:int, screen:pygame.Surface, preempt: float, fade_in: float, color:pygame.Color, circle_radius:int, beat_duration:float, multiplier:float=1.0): start_pos = (slider.x, slider.y) vertices = [start_pos] + slider.curve_points pygame.draw.lines(screen, (255, 255, 255), False, vertices) _render_hitcircle(slider, time, screen, preempt, fade_in, color, circle_radius) pos = slider.target_position(time, beat_duration, multiplier) pygame.draw.circle(screen, (255, 255, 255), list(map(int, pos)), circle_radius, 1) SPINNER_RADIUS = 128 def _render_spinner(spinner, time:int, screen:pygame.Surface, *args): pos = (spinner.x, spinner.y) pygame.draw.circle(screen, (255, 255, 255), pos, SPINNER_RADIUS, 2) def render(obj:hitobjects.HitObject, time:int, screen:pygame.Surface, *args): if isinstance(obj, hitobjects.HitCircle): _render_hitcircle(obj, time, screen, *args) if isinstance(obj, hitobjects.Slider): _render_slider(obj, time, screen, *args) if isinstance(obj, hitobjects.Spinner): _render_spinner(obj, time, screen, *args)<file_sep>/osu/rulesets/beatmap.py import math from datetime import time from . import core, hitobjects, timing_points from ._util.bsearch import bsearch import re _SECTION_TYPES = { 'General': 'a', 'Editor': 'a', 'Metadata': 'a', 'Difficulty': 'a', 'Events': 'b', 'TimingPoints': 'b', 'Colours': 'a', 'HitObjects': 'b' } class _BeatmapFile: def __init__(self, file): self.file = file self.format_version = self.file.readline() def read_all_sections(self): sections = {} section = self._read_section_header() while section != None: func = "_read_type_%s_section" % _SECTION_TYPES[section] section_name = re.sub('(.)([A-Z][a-z]+)', r'\1_\2', section).lower() sections[section_name] = getattr(self, func)() section = self._read_section_header() return sections def _read_section_header(self): header = self.file.readline() while header != '' and re.match(r"[^\n\r\s]", header) == None: header = self.file.readline() m = re.match(r"^\s*\[(\S+)\]\s*$", header) if m is None: return None return m[1] def _parse_value(self, v): if v.isdigit(): return int(v) elif v.replace('.', '', 1).isdigit(): return float(v) else: return v # Seção do tipo Chave: Valor def _read_type_a_section(self): d = dict() line = self.file.readline() while line != '' and re.match(r"[^\n\r\s]", line) != None: m = re.match(r"^\s*(\S+)\s*:\s*(.*)\s*\r?\n$", line) if m is None: raise RuntimeError("Invalid file") else: d[m[1]] = self._parse_value(m[2]) line = self.file.readline() return d # Seção do tipo a,b,c,...,d def _read_type_b_section(self): l = list() line = self.file.readline() while line != '' and re.match(r"[^\n\r\s]", line) != None: l.append(list(map(self._parse_value, line.rstrip("\r\n").split(',')))) line = self.file.readline() return l class Beatmap: def __init__(self, file): file = _BeatmapFile(file) self.format_version = file.format_version self.sections = file.read_all_sections() if 'timing_points' in self.sections: self.timing_points = list(map(timing_points.create, self.sections['timing_points'])) del self.sections['timing_points'] if 'hit_objects' in self.sections: self.hit_objects = list(map(hitobjects.create, self.sections['hit_objects'])) del self.sections['hit_objects'] def combo_color(self, new_combo, combo_skip): return (255, 0, 0) def __getattr__(self, key): if key in self.sections: return self.sections[key] else: return [] def __getitem__(self, key): for section in self.sections.values(): if key in section: return section[key] return None def approach_rate(self): ar = self["ApproachRate"] if ar <= 5: preempt = 1200 + 600 * (5 - ar) / 5 fade_in = 800 + 400 * (5 - ar) / 5 else: preempt = 1200 - 750 * (ar - 5) / 5 fade_in = 800 - 500 * (ar - 5) / 5 return preempt, fade_in def circle_radius(self): return 27.2 - 2.24 * self['CircleSize'] def start_offset(self): preempt, _ = self.approach_rate() return int(self.hit_objects[0].time - preempt) def length(self): if len(self.hit_objects) == 0: return 0 last_obj = self.hit_objects[-1] beat_duration = self.beat_duration(last_obj.time) return int(last_obj.time + last_obj.duration(beat_duration, self['SliderMultiplier'])) def _timing(self, time): bpm = None i = bsearch(self.timing_point, time, lambda tp: tp.time) timing_point = self.timing_points[i - 1] for tp in self.timing_points[i:]: if tp.offset > time: break if tp.bpm > 0: bpm = tp.bpm timing_point = tp while i >= 0 and bpm is None: i -= 1 if self.timing_points[i].bpm > 0: bpm = self.timing_points[i].bpm return bpm or 120, timing_point def beat_duration(self, time): bpm, timing_point = self._timing(time) beat_duration = timing_point.bpm if beat_duration < 0: return bpm * -beat_duration / 100 return beat_duration # Pega os objetos visíveis na tela em dado momento def visible_objects(self, time, count=None): objects = [] preempt, _ = self.approach_rate() i = bsearch(self.hit_objects, time, lambda obj: obj.time + preempt - obj.duration(self.beat_duration(obj.time), self['SliderMultiplier'])) i -= 5 if i < 0: i = 0 n = 0 for obj in self.hit_objects[i:]: obj_duration = obj.duration(self.beat_duration(obj.time), self['SliderMultiplier']) if time > obj.time + obj_duration: continue elif time < obj.time - preempt: break elif time < obj.time + obj_duration: objects.append(obj) n += 1 if not count is None and n >= count: return objects return objects def load(filename): with open(filename, 'r', encoding='utf8') as file: return Beatmap(file)<file_sep>/osulearn/_cli.py def _print_progress_bar(collection, index, bar_width=40, buffer_width=80, reverse=False): bar_format = "\r[{done}>{todo}] {text}" progress = index / (len(collection) - 1) if reverse: progress = 1 - progress bar_raw_length = len(bar_format.format(done='', todo='', text='')) done = int(round(progress * bar_width)) text = str(collection[index]) if len(text) > buffer_width - bar_raw_length - bar_width: text = text[:buffer_width - bar_raw_length - bar_width - 3] + '...' print(bar_format.format( done='=' * (done - 1), todo='.' * (bar_width - done), text=text).ljust(buffer_width), end='')<file_sep>/osu/rulesets/_util/binfile.py def read_byte(file): return ord(file.read(1)) def read_short(file): return read_byte(file) + (read_byte(file) << 8) def read_int(file): return read_short(file) + (read_short(file) << 16) def read_long(file): return read_int(file) + (read_int(file) << 32) def read_uleb128(file): n = 0 i = 0 while True: byte = read_byte(file) n += (byte & 0x7F) << i if byte & 0x80 != 0: i += 7 else: return n def read_binary_string(file): while True: flag = read_byte(file) if flag == 0x00: return "" elif flag == 0x0b: length = read_uleb128(file) return file.read(length).decode('utf8') else: raise RuntimeError("Invalid file")<file_sep>/osulearn/dataset.py import math import os import pickle import re from glob import escape as glob_escape, glob import numpy as np import pandas as pd from tensorflow.keras.preprocessing.sequence import pad_sequences import osu.rulesets.beatmap as osu_beatmap import osu.rulesets.core as osu_core import osu.rulesets.hitobjects as hitobjects import osu.rulesets.replay as osu_replay from ._cli import _print_progress_bar # Constants BATCH_LENGTH = 2048 FRAME_RATE = 24 # Feature index INPUT_FEATURES = ['x', 'y', 'visible', 'is_slider', 'is_spinner'] OUTPUT_FEATURES = ['x', 'y'] # Default beatmap frame information _DEFAULT_BEATMAP_FRAME = ( osu_core.SCREEN_WIDTH / 2, osu_core.SCREEN_HEIGHT / 2, # x, y float("inf"), False, False # time_left, is_slider, is_spinner ) def all_files(osu_path, limit=0, verbose=False): """Return a pandas DataFrame mapping replay files to beatmap files""" replays = _list_all_replays(osu_path) if limit > 0: replays = replays[:limit] beatmaps = [] for i in range(len(replays)-1, -1, -1): if verbose: _print_progress_bar(replays, i, reverse=True) beatmap = _get_replay_beatmap_file(osu_path, replays[i]) if beatmap is None: replays.pop(i) else: beatmaps.insert(0, beatmap) global _beatmap_cache with open('.data/beatmap_cache.dat', 'wb') as f: pickle.dump(_beatmap_cache, f) if verbose: print() print() files = list(zip(replays, beatmaps)) return pd.DataFrame(files, columns=['replay', 'beatmap']) def load(files, verbose=0): """Map the replay and beatmap files into osu! ruleset objects""" replays = [] beatmaps = [] for index, row in files.iterrows(): if verbose: _print_progress_bar(files['replay'].map(os.path.basename), index) try: replay = osu_replay.load(row['replay']) assert not replay.has_mods(osu_replay.Mod.DT, osu_replay.Mod.HR),\ "DT and HR are not supported yet" beatmap = osu_beatmap.load(row['beatmap']) except Exception as e: if verbose: print() print("\tFailed:", e) continue replays.append(replay) beatmaps.append(beatmap) return pd.DataFrame(list(zip(replays, beatmaps)), columns=['replay', 'beatmap']) def input_data(dataset, verbose=False): """Given a osu! ruleset dataset for replays and maps, generate a new DataFrame with beatmap object information across time.""" data = [] _memo = {} if isinstance(dataset, osu_beatmap.Beatmap): dataset = pd.DataFrame([dataset], columns=['beatmap']) beatmaps = dataset['beatmap'] for index, beatmap in beatmaps.iteritems(): if verbose: _print_progress_bar(beatmaps.map(lambda b: b['Title']), index) if beatmap in _memo: data += _memo[beatmap] continue if len(beatmap.hit_objects) == 0: continue _memo[beatmap] = [] chunk = [] preempt, _ = beatmap.approach_rate() last_ok_frame = None # Last frame with at least one visible object for time in range(beatmap.start_offset(), beatmap.length(), FRAME_RATE): frame = _beatmap_frame(beatmap, time) if frame is None: if last_ok_frame is None: frame = _DEFAULT_BEATMAP_FRAME else: frame = list(last_ok_frame) frame[2] = float("inf") else: last_ok_frame = frame px, py, time_left, is_slider, is_spinner = frame chunk.append(np.array([ px - 0.5, py - 0.5, time_left < preempt, is_slider, is_spinner ])) if len(chunk) == BATCH_LENGTH: data.append(chunk) _memo[beatmap].append(chunk) chunk = [] if len(chunk) > 0: data.append(chunk) _memo[beatmap].append(chunk) if verbose: print() print() data = pad_sequences(np.array(data), maxlen=BATCH_LENGTH, dtype='float', padding='post', value=0) index = pd.MultiIndex.from_product([ range(len(data)), range(BATCH_LENGTH) ], names=['chunk', 'frame']) data = np.reshape(data, (-1, len(INPUT_FEATURES))) return pd.DataFrame(data, index=index, columns=INPUT_FEATURES, dtype=np.float32) def target_data(dataset, verbose=False): """Given a osu! ruleset dataset for replays and maps, generate a new DataFrame with replay cursor position across time.""" target_data = [] for index, row in dataset.iterrows(): replay = row['replay'] beatmap = row['beatmap'] if verbose: _print_progress_bar(dataset['beatmap'].map(lambda b: b['Title']), index) if len(beatmap.hit_objects) == 0: continue chunk = [] for time in range(beatmap.start_offset(), beatmap.length(), FRAME_RATE): x, y = _replay_frame(beatmap, replay, time) chunk.append(np.array([x - 0.5, y - 0.5])) if len(chunk) == BATCH_LENGTH: target_data.append(chunk) chunk = [] if len(chunk) > 0: target_data.append(chunk) if verbose: print() print() data = pad_sequences(np.array(target_data), maxlen=BATCH_LENGTH, dtype='float', padding='post', value=0) index = pd.MultiIndex.from_product([range(len(data)), range(BATCH_LENGTH)], names=['chunk', 'frame']) return pd.DataFrame(np.reshape(data, (-1, len(OUTPUT_FEATURES))), index=index, columns=OUTPUT_FEATURES, dtype=np.float32) def _list_all_replays(osu_path): # Returns the full list of *.osr replays available for a given # osu! installation pattern = os.path.join(osu_path, "Replays", "*.osr") return glob(pattern) # Beatmap caching. This reduces beatmap search time a LOT. # # Maybe in the future I'll look into using osu! database file for that, # but this will do just fine for now. try: with open('.data/beatmap_cache.dat', 'rb') as f: _beatmap_cache = pickle.load(f) except: _beatmap_cache = {} def _get_replay_beatmap_file(osu_path, replay_file): global _beatmap_cache m = re.search(r"[^\\/]+ \- (.+ \- .+) \[(.+)\] \(.+\)", replay_file) if m is None: return None beatmap, diff = m[1], m[2] beatmap_file_pattern = "*" + glob_escape(beatmap) + "*" + glob_escape("[" + diff + "]") + ".osu" if beatmap_file_pattern in _beatmap_cache: return _beatmap_cache[beatmap_file_pattern] pattern = os.path.join(osu_path, "Songs", "**", beatmap_file_pattern) file_matches = glob(pattern) if len(file_matches) > 0: _beatmap_cache[beatmap_file_pattern] = file_matches[0] return file_matches[0] else: _beatmap_cache[beatmap_file_pattern] = None return None def _beatmap_frame(beatmap, time): visible_objects = beatmap.visible_objects(time, count=1) if len(visible_objects) > 0: obj = visible_objects[0] beat_duration = beatmap.beat_duration(obj.time) px, py = obj.target_position(time, beat_duration, beatmap['SliderMultiplier']) time_left = obj.time - time is_slider = int(isinstance(obj, hitobjects.Slider)) is_spinner = int(isinstance(obj, hitobjects.Spinner)) else: return None px = max(0, min(px / osu_core.SCREEN_WIDTH, 1)) py = max(0, min(py / osu_core.SCREEN_HEIGHT, 1)) return px, py, time_left, is_slider, is_spinner def _replay_frame(beatmap, replay, time): x, y, _ = replay.frame(time) x = max(0, min(x / osu_core.SCREEN_WIDTH, 1)) y = max(0, min(y / osu_core.SCREEN_HEIGHT, 1)) return x, y<file_sep>/osu/rulesets/hitobjects.py import math from abc import ABC, abstractmethod from enum import Enum, IntEnum, IntFlag from . import core from ._util import bezier class HitObjectType(IntFlag): CIRCLE = 0b00000001 SLIDER = 0b00000010 NEW_COMBO = 0b00000100 SPINNER = 0b00001000 COMBO_SKIP = 0b01110000 MANIA_HOLD = 0b10000000 class HitSounds(IntFlag): NORMAL = 0b0001 WHISTLE = 0b0010 FINISH = 0b0100 CLAP = 0b1000 class SampleSet(IntEnum): AUTO = 0 NORMAL = 1 SOFT = 2 DRUM = 3 class HitSoundExtras: def __init__(self, *args): self.sample_set = SampleSet(int(args[0])) self.addition_set = SampleSet(int(args[1])) self.customIndex = int(args[2]) self.sampleVolume = int(args[3]) self.filename = args[4] class HitObject(ABC): def __init__(self, *args): self.x = int(args[0]) self.y = int(args[1]) self.time = int(args[2]) self.new_combo = bool(int(args[3]) & HitObjectType.NEW_COMBO) self.combo_skip = int(args[3] & HitObjectType.COMBO_SKIP) >> 4 self.hitsounds = HitSounds(int(args[4])) #self.extras = HitSoundExtras(*args[-1].split(":")) @abstractmethod def duration(self, beat_duration:float, multiplier:float=1.0): pass def target_position(self, time:int, beat_duration:float, multiplier:float=1.0): return (self.x, self.y) class HitCircle(HitObject): def __init__(self, *args): super().__init__(*args) def duration(self, *args): return 0 class SliderType(Enum): LINEAR = "L" BEZIER = "B" PERFECT = "P" CATMUL = "C" class Slider(HitCircle): def __init__(self, *args): super().__init__(*args) slider_info = args[5].split("|") self.slider_type = SliderType(slider_info[0]) self.curve_points = list(map(lambda p: tuple(map(int, p)), [p.split(':') for p in slider_info[1:]])) self.repeat = int(args[6]) self.pixel_length = int(args[7]) #self.edge_hitsounds = [HitSounds(int(h)) for h in args[8].split('|')] #additions = [e.split(":") for e in args[9].split('|')] #self.edge_additions = [(SampleSet(int(s)), SampleSet(int(a))) for s, a in additions] def duration(self, beat_duration:float, multiplier:float=1.0): return beat_duration * self.pixel_length / (100 * multiplier) * self.repeat def real_curve_points(self): points = [] for i in range(1, self.repeat + 1): l = ([(self.x, self.y)] + self.curve_points) if i % 2 == 0: l = list(reversed(l)) points += l return points class _Patch: def __init__(self, start_position, length:float=0.0, angle:float=0.0): self.x, self.y = start_position self.length = length self.angle = angle @staticmethod def _get_patches(curve_points): processed = [] for i in range(len(curve_points) - 1): x, y = curve_points[i] next_x, next_y = curve_points[i + 1] dx = next_x - x dy = next_y - y distance = math.hypot(dx, dy) angle = math.atan2(dy, dx) processed.append(Slider._Patch((x, y), distance, angle)) processed.append(Slider._Patch(curve_points[-1], 0, 0)) return processed @staticmethod def _traverse_patches(elapsed, step, slider_track): while elapsed > 0: slider_track[0].length -= step if slider_track[0].length <= 0: if len(slider_track) > 2: slider_track.pop(0) else: break elapsed -= 1 def current_curve_point(self, time:int, beat_duration:float, multiplier:float=1.0): elapsed = time - self.time if elapsed <= 0 or len(self.curve_points) == 0: return (self.x, self.y) duration = self.duration(beat_duration, multiplier) if elapsed >= duration: return self.curve_points[-1] curve_points = self.real_curve_points() slider_track = Slider._get_patches(curve_points) step = self.pixel_length / duration * self.repeat self._traverse_patches(elapsed, step, slider_track) if len(slider_track) < 2: return self.curve_points[-1] x = slider_track[1].x - math.cos(slider_track[0].angle) * slider_track[0].length y = slider_track[1].y - math.sin(slider_track[0].angle) * slider_track[0].length return (x, y) def target_position(self, time:int, beat_duration:float, multiplier:float=1.0): return self.current_curve_point(time, beat_duration, multiplier) class Spinner(HitObject): def __init__(self, *args): super().__init__(*args) self.end_time = int(args[5]) def duration(self, *args): return self.end_time - self.time def create(obj): if obj[3] & HitObjectType.CIRCLE: return HitCircle(*obj) elif obj[3] & HitObjectType.SLIDER: return Slider(*obj) elif obj[3] & HitObjectType.SPINNER: return Spinner(*obj)
d322f83f7ec635eb2990fe1de172a427caaa71fd
[ "Markdown", "Python" ]
14
Python
hakanaku1234/OsuLearn
917768def65c35ebc51fe7647094f1f361537f41
4ec4033fc97aa1fd8e0ae10254cebe1bf8e013e2
refs/heads/main
<file_sep>import React, { Component } from 'react' import { Container, Nav, NavItem, NavLink, Dropdown, DropdownMenu, DropdownItem, DropdownToggle } from 'reactstrap' class MobileMenu extends Component { state = { isOpen: false } toggle = () => this.setState({ isOpen: !this.state.isOpen }) render() { return ( <div className="mobile-wrapper"> <div className="mobile-menu"> <Container className="pos-ref"> <i className="fas fa-times mobile-menu__close-bt" onClick={this.props.hideNav} /> </Container> </div> <Nav vertical className={'mobile-nav'}> <NavItem className="nav-item-m"> <NavLink>home</NavLink> </NavItem> <NavItem className="nav-item-m"> <NavLink>about</NavLink> </NavItem> <NavItem className="nav-item-m"> <NavLink>features</NavLink> </NavItem> <NavItem className="nav-item-m"> <NavLink>screenshots</NavLink> </NavItem> <NavItem className="nav-item-m"> <NavLink>team</NavLink> </NavItem> <NavItem className="nav-item-m"> <NavLink>pricing</NavLink> </NavItem> <NavItem> <Dropdown isOpen={this.state.isOpen} toggle={this.toggle}> <DropdownToggle className="drop-item" caret> Dropdown </DropdownToggle> <DropdownMenu className="drop-menu"> <DropdownItem>dropdown-1</DropdownItem> <DropdownItem>dropdown-2</DropdownItem> <DropdownItem>dropdown-3</DropdownItem> <DropdownItem>dropdown-4</DropdownItem> </DropdownMenu> </Dropdown> </NavItem> <NavItem className="nav-item-m"> <NavLink>blog</NavLink> </NavItem> <NavItem className="nav-item-m"> <NavLink>contact</NavLink> </NavItem> </Nav> </div> ) } } export default class extends Component { dropNav = React.createRef() hamButton = React.createRef() over = () => { this.dropNav.current.style.display = 'block' this.opacityTiemOut = setTimeout(() => { this.dropNav.current.style.opacity = '1' }) } out = () => { this.dropNav.current.style.transition = 'all .5s 1s' this.dropNav.current.style.opacity = '0' } onHide = () => { if (this.dropNav.current.style.opacity === '1') return this.dropNav.current.style.display = 'none' this.dropNav.current.style.transition = 'all .5s' } hideNav = e => { document.body.style.overflow = 'visible' this.mobileMenu.style.display = 'none' this.hamButton.style.display = '' this.mobileNav.style.transform = `translateX(-100%)` } showNav = e => { e.preventDefault() document.body.style.overflow = 'hidden' this.hamButton.style.display = 'none' this.menuWrapper.style.display = 'block' this.mobileMenu.style.display = 'block' setTimeout(() => { this.mobileNav.style.transform = 'translateX(0px)' }, 200) } fixedNav() { const nav = document.querySelector('.navi-menu') const navHeigth = parseInt(window.getComputedStyle(nav).height, 10) const scrollEl = document.scrollingElement if (scrollEl.scrollTop > navHeigth) { nav.style.position = 'fixed' nav.classList.add('scroll-nav') } else { nav.style.position = 'static' nav.classList.remove('scroll-nav') } } componentDidMount() { window.addEventListener('scroll', this.fixedNav) this.menuWrapper = document.querySelector('.mobile-wrapper') this.mobileMenu = document.querySelector('.mobile-menu') this.mobileNav = document.querySelector('.mobile-nav') this.hamButton = document.querySelector('.ham') } componentWillUnmount() { window.removeEventListener('scroll', this.fixedNav) } render() { return ( <div className="navi-menu"> <Container> <MobileMenu hideNav={this.hideNav} /> <Nav className="nav-n"> <NavItem className="nav-item-n logo"> <NavLink href="#">eStarup</NavLink> </NavItem> <NavItem className="nav-item-n ham" onClick={this.showNav}> <NavLink href=""> <i className="fas fa-bars" /> </NavLink> </NavItem> <NavItem className="nav-item-n"> <NavLink href="#">home</NavLink> </NavItem> <NavItem className="nav-item-n"> <NavLink href="#">about</NavLink> </NavItem> <NavItem className="nav-item-n"> <NavLink href="#">features</NavLink> </NavItem> <NavItem className="nav-item-n"> <NavLink href="#">screenshots</NavLink> </NavItem> <NavItem className="nav-item-n"> <NavLink href="#">team</NavLink> </NavItem> <NavItem className="nav-item-n"> <NavLink href="#">pricing</NavLink> </NavItem> <div className="drop" onMouseOver={this.over} onMouseOut={this.out} onTransitionEnd={this.onHide} > <NavItem> <NavLink href="#" className="nav-item-n caret"> dropdown </NavLink> </NavItem> <div className="drop__item" ref={this.dropNav}> <Nav vertical> <NavItem className="nav-item-n"> <NavLink href="#">dropdown-1</NavLink> </NavItem> <NavItem className="nav-item-n"> <NavLink href="#">dropdown-2</NavLink> </NavItem> <NavItem className="nav-item-n"> <NavLink href="#">dropdown-3</NavLink> </NavItem> <NavItem className="nav-item-n"> <NavLink href="#">dropdown-4</NavLink> </NavItem> </Nav> </div> </div> <NavItem className="nav-item-n"> <NavLink href="#">Blog</NavLink> </NavItem> <NavItem className="nav-item-n"> <NavLink href="#">Contact</NavLink> </NavItem> </Nav> </Container> </div> ) } } <file_sep>import React from 'react' // import { Container, Jumbotron } from 'reactstrap' const Header = () => { return ( <header> <div className="intro-logo jumbo-bg"> <h1>Next Dapp Here!!!</h1> <h3>Buy NFT stored in Eth smart conracts</h3> <div className="intro-button"> <a href="">Get Started</a> </div> <div className="company-icons"> <span className="company-icons__item"> <i className="fab fa-apple" /> app store </span> <span className="company-icons__item"> <i className="fab fa-google-play" /> google play </span> <span className="company-icons__item"> <i className="fab fa-windows" /> windows </span> </div> </div> </header> ) } export default Header
4d327b4bdda9be2fbb0f85935fc11ad1fce9cf79
[ "JavaScript" ]
2
JavaScript
Funfun/dapp-demo
2781e028d5e8f1dd7ccdebf8e1e56037d5dbd2de
5e74d3f825d95c0a00b6ceb0c97ea8efd5d230df
refs/heads/master
<file_sep>class LanguagesMentor < ApplicationRecord belongs_to :language belongs_to :mentor end <file_sep>class Language < ApplicationRecord has_many :languages_mentors has_many :mentors, through: :languages_mentors has_many :languages_students has_many :students, through: :languages_students has_many :resources has_many :subfields validates :name, presence: { message: 'cannot be blank.' } end <file_sep>class MentorsController < ApplicationController before_action :current_user before_action :logged_in?, except: [:new, :create] before_action :logged_out?, only: [:new] before_action :student_logged_in?, only: [:index] before_action :mentor_logged_in?, except: [:index, :new, :create] def index @available_mentors = Mentor.all.collect{|mentor| mentor if !mentor.has_student?} @available_mentors.compact! end def new @mentor = Mentor.new end def create @mentor = Mentor.new(mentor_params) if @mentor.save render 'new' unless @mentor.authenticate(params[:mentor][:password]) session[:mentor_id] = @mentor.id redirect_to mentor_path(@mentor) else render 'new' end end def show respond_to do |format| format.json { render json: @current_user.to_json( only: [:username, :first_name, :email, :profile_img, :location, :github_link], include: [languages: {only: :name}] ) } format.html { render :show } end end def update @current_user.update(mentor_params) redirect_to mentor_path(@current_user) end private def mentor_params params.require(:mentor).permit(:username, :first_name, :last_name, :email, :profile_img, :location, :github_link, :student_id, :password, :password_confirmation) end end <file_sep>class StudentSerializer < ActiveModel::Serializer attributes :id, :username, :first_name, :last_name, :profile_img, :location, :github_link has_many :languages_students end <file_sep>class SessionsController < ApplicationController before_action :current_user before_action :logged_out?, only: [:mentor_new, :student_new] def mentor_new @user = Mentor.new end def student_new @user = Student.new end def mentor_create @user = Mentor.find_by(username: params[:mentor][:username]) if @user && @user.authenticate(params[:mentor][:password]) session[:mentor_id] = @user.id redirect_to mentor_path(@user) else redirect_to mentors_login_path end end def mentor_gh_create @user = Mentor.find_or_create_by(uid: auth['uid']) do |u| u.username = auth['info']['nickname'] u.first_name = auth['info']['name'] u.email = auth['info']['email'] u.profile_img = auth['info']['image'] u.github_link = auth['info']['urls']['GitHub'] u.uid = auth['uid'] u.password = <PASSWORD>) end session[:mentor_id] = @user.id redirect_to mentor_path(@user) end def student_create @user = Student.find_by(username: params[:student][:username]) if @user && @user.authenticate(params[:student][:password]) session[:student_id] = @user.id redirect_to student_path(@user) else redirect_to students_login_path end end def logout reset_session redirect_to root_path end private def auth request.env['omniauth.auth'] end end <file_sep>#-Make resource show appear underneath resource list on index so long as it's serialized -Resources class prototype #-User has many languages and has array of languages belonging to user #-New resource appends to recently added resources section -Add button on top resources to save to my resources <file_sep>Rails.application.routes.draw do root to: 'application#index' get '/mentors/login', to: 'sessions#mentor_new' get '/students/login', to: 'sessions#student_new' post '/mentor_login', to: 'sessions#mentor_create' post '/student_login', to: 'sessions#student_create' get '/logout', to: 'sessions#logout' resources :languages, only: [:create] get '/languages/add_or_delete', to: 'languages#new_or_destroy', as: 'new_or_delete_language' post '/delete_language', to: 'languages#destroy' resources :mentors do resources :resources end get '/mentor/:id/student', to: 'mentors#show_student', as: 'mentor_student' resources :students, except: [:index] do resources :resources, only: [:index, :new, :show, :edit] end get '/student/:id/mentor', to: 'students#show_mentor', as: 'student_mentor' post '/add_mentor', to: 'students#add_mentor' resources :resources, only: [:index, :create, :update] get 'resources/top_resources', to: 'resources#top_resources', as: 'top_resources' get 'resources/top_resources/:id', to: 'resources#top_resource', as: 'top_resource' get '/auth/github/callback' => 'sessions#mentor_gh_create' end <file_sep>CODEMENTOR DESCRIPTION CodeMentor is a Rails-based web app that allows software engineers to sign up and match with a student who is looking to learn to code. Mentors can add open source materials to create a custom curriculum for their student, and get them started on their coding journey. INSTALL AND USAGE INSTRUCTIONS To use CodeMentor, fork and clone the repository. CD to the local repository files, run bundle install, and then run rails s from the terminal. In your web browser, navigate to the appropriate localhost, and sign up to either be a mentor or a student. If you are signing up as a mentor, your profile will appear to new students who are looking for someone to mentor them. If you sign up as a student, navigate to Find a Mentor to pick your mentor. CONTRIBUTOR'S GUIDE Bug reports and pull requests are welcome on GitHub at https://github.com/bbennett7/codementorapp LINK TO MIT LICENSE This is available as open source under the terms of the MIT License. <file_sep>class StudentsController < ApplicationController before_action :current_user before_action :logged_in?, except: [:new, :create] before_action :logged_out?, only: [:new] before_action :find_mentor, only: [:add_mentor] def new @student = Student.new end def create @student = Student.new(student_params) if @student.save render 'new' unless @student.authenticate(params[:student][:password]) session[:student_id] = @student.id redirect_to student_path(@student) else render 'new' end end def show respond_to do |format| format.json { render json: @current_user.to_json( only: [:username, :first_name, :email, :profile_img, :location, :github_link], include: [languages: {only: :name}] ) } format.html { render :show } end end def update @current_user.update(student_params) redirect_to student_path(@current_user) end def add_mentor @current_user.mentor = @mentor redirect_to mentor_path(@current_user.mentor) end private def student_params params.require(:student).permit(:username, :first_name, :last_name, :email, :profile_img, :location, :github_link, :password, :password_confirmation) end end <file_sep>class LanguagesStudent < ApplicationRecord belongs_to :language belongs_to :student end <file_sep>require 'valid_email' class Student < ApplicationRecord has_many :languages_students has_many :languages, through: :languages_students has_one :mentor has_many :resources, through: :mentor #delegate :resources, to: :mentor has_secure_password validates :username, presence: { message: 'cannot be blank.' } validates :username, uniqueness: { message: 'is already taken.' } validates :username, length: { minimum: 8, message: 'must be at least 8 characters.' } validates :first_name, presence: { message: 'cannot be blank.' } validates :email, presence: { message: 'cannot be blank.' } validates :email, uniqueness: { message: 'is associated with an existing account.' } validates :email, email: { message: 'is not a valid email address.' } # validates :github_link, presence: { message: 'Github link cannot be blank.' } validates :github_link, uniqueness: { message: 'is associated with an existing account.' }, :allow_blank => true validates :password, presence: { message: 'cannot be blank.' }, :if => :password validates :password, length: {minimum: 8, message: 'must be at least 8 characters.' }, :if => :password def has_mentor? self.mentor != nil end end <file_sep>module ApplicationHelper def session_id true if session[:mentor_id] || session[:student_id] end def current_user if session[:mentor_id] Mentor.find_by_id(session[:mentor_id]) elsif session[:student_id] Student.find_by_id(session[:student_id]) end end def student_or_mentor_path(user) if session[:mentor_id] mentor_path(user) elsif session[:student_id] student_path(user) end end def edit_student_or_mentor_path(user) if session[:mentor_id] edit_mentor_path(user) elsif session[:student_id] edit_student_path(user) end end def student_or_mentor_resources_path(user) if session[:mentor_id] mentor_resources_path(user) elsif session[:student_id] student_resources_path(user) end end def student_or_mentor_resource_path(user, resource) if session[:mentor_id] mentor_resource_path(user, resource) elsif session[:student_id] student_resource_path(user, resource) end end end <file_sep>class ApplicationController < ActionController::Base before_action :current_user def index logged_out? end private def current_user @current_user = Mentor.find_by_id(session[:mentor_id]) || Student.find_by_id(session[:student_id]) end def logged_in? redirect_to root_path unless !session[:mentor_id].nil? || !session[:student_id].nil? end def logged_out? redirect_to student_or_mentor_path(@current_user) unless session[:mentor_id].nil? && session[:student_id].nil? end def mentor_logged_in? redirect_to student_path(@current_user) unless session[:mentor_id] end def student_logged_in? redirect_to mentor_path(@current_user) unless !session[:student_id].nil? end def student_or_mentor_path(user) if session[:mentor_id] mentor_path(user) elsif session[:student_id] student_path(user) end end def student_or_mentor_resources_path(user) if session[:mentor_id] mentor_resources_path(user) elsif session[:student_id] student_resources_path(user) end end def student_or_mentor_resource_path(user, resource) if session[:mentor_id] mentor_resource_path(user, resource) elsif session[:student_id] student_resource_path(user, resource) end end def find_mentor @mentor = Mentor.find_by_id(params[:mentor_id]) end end <file_sep>class ResourcesController < ApplicationController before_action :current_user before_action :resource, only:[:show, :edit, :update, :top_resource] before_action :logged_in? before_action :mentor_logged_in?, only: [:new, :create, :edit] def new @resource = Resource.new end def index @read_resources = @current_user.resources.select{ |resource| resource.read }.sort_by{|resource| resource.language } @unread_resources = @current_user.resources.select{ |resource| !resource.read }.sort_by{|resource| resource.language } end def create if !params[:resource][:subfield][:name].empty? subfield = Subfield.find_or_create_by(name: params[:resource][:subfield][:name].strip) subfield.language_id = params[:resource][:language_id] subfield.save params[:resource][:subfield_id] = subfield.id end @resource = Resource.new(resource_params) if @resource.save render json: @resource, status: 201 else render 'new' end end def show @resource = Resource.find(params[:id]) respond_to do |format| format.json { render json: @resource.to_json } format.html { render :show } end end def top_resources @top_resources = Resource.top_resources respond_to do |format| format.html { render :top_resources } format.json { render json: @top_resources.to_json } end end def top_resource respond_to do |format| format.html { render :top_resource } format.json { render json: @resource.to_json } end end def edit end def update @resource.update(resource_params) redirect_to student_or_mentor_resources_path(@current_user) end private def resource_params params.require(:resource).permit(:website, :title, :url, :language_id, :subfield_id, :mentor_id, :read, :student_rating) end def resource @resource = Resource.find_by_id(params[:id]) end end <file_sep>VALIDATIONS: #-name # -must be present # -must contain only a-z #-username # -must be unique # -must be present # -must be at least 8 characters -Validate against both student and mentor models? #-email # -must be present # -must be unique # -must end with @ abc.com => gem for this? #-password # -must be present # -must be at least 8 characters -authorizations -student's can't access new, create, edit, and update resource paths -mentors can't see find a mentor page -students can't see find a student page <file_sep>require 'valid_email' class Mentor < ApplicationRecord has_many :languages_mentors has_many :languages, through: :languages_mentors has_many :resources has_many :subfields, through: :resources belongs_to :student, required: false has_secure_password validates :username, presence: { message: 'cannot be blank.' } validates :username, uniqueness: { message: 'is already taken.' } validates :username, length: { minimum: 8, message: 'must be at least 8 characters.' } validates :first_name, presence: { message: 'cannot be blank.' } validates :email, presence: { message: 'cannot be blank.' } validates :email, uniqueness: { message: 'is associated with an existing account.' } validates :email, email: { message: 'is not a valid email address.' } validates :github_link, presence: { message: 'cannot be blank.' } validates :github_link, uniqueness: { message: 'is associated with an existing account.' } validates :password, presence: { message: 'cannot be blank.' }, :if => :password validates :password, length: {minimum: 8, message: 'must be at least 8 characters.' }, :if => :password def has_student? self.student != nil end end <file_sep>class LanguagesStudentSerializer < ActiveModel::Serializer attributes :id, :language_id, :student_id belongs_to :student belongs_to :language end <file_sep>class LanguagesController < ApplicationController before_action :current_user before_action :logged_in? def new_or_destroy @language = Language.new end def create if params[:language][:name].empty? && params[:language][:id].empty? @language = Language.new(language_params) render 'new_or_destroy' else if !language_params[:name].empty? @language = Language.find_or_create_by(name: language_params[:name]) else @language = Language.find_by_id(params[:language][:id]) end if @language.nil? render 'new_or_destroy' else @current_user.languages << @language if !@current_user.languages.include?(@language) redirect_to student_or_mentor_path(@current_user) end end end def destroy @languages = params[:language][:id] @languages.delete("") @languages.each do |lang_id| language = Language.find_by_id(lang_id) @current_user.languages.destroy(language) end redirect_to student_or_mentor_path(@current_user) end private def language_params params.require(:language).permit(:name) end end
45e6da39d1ce4a18e15734c37e92c6f7a1912f9d
[ "Markdown", "Ruby" ]
18
Ruby
BebopVinh/codecoach
ee36d56cf1d983805ca9de84da645d99beaedd00
ba2c0baecd7fb2a053173be201dfc9222693b3d7
refs/heads/master
<repo_name>elmascan/newway-api-master<file_sep>/src/main/java/com/newway/newwayapi/web/rest/ProjectController.java package com.newway.newwayapi.web.rest; import com.newway.newwayapi.model.Project; import com.newway.newwayapi.repository.ProjectRepository; import com.newway.newwayapi.web.rest.errors.BadRequest; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.domain.Page; import org.springframework.data.domain.Pageable; import org.springframework.http.HttpHeaders; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.util.MultiValueMap; import org.springframework.web.bind.annotation.*; import org.springframework.web.util.UriComponentsBuilder; import java.net.URI; import java.net.URISyntaxException; import java.util.List; import java.util.Optional; import static com.newway.newwayapi.util.PaginationUtil.generatePaginationHttpHeaders; @RestController @RequestMapping("v1/projects") public class ProjectController { @Autowired private ProjectRepository projectRepository; @PostMapping public ResponseEntity<Project> createProject(@RequestBody Project project) throws URISyntaxException { if (project.getId() != null) { throw new BadRequest("Already have an ID"); } Project p = projectRepository.save(project); return ResponseEntity.created(new URI("v1/projects/" + p.getId())).body(p); } @GetMapping public ResponseEntity<List<Project>> readProjects(Pageable pageable, @RequestParam MultiValueMap<String, String> queryParams, UriComponentsBuilder uriBuilder) { Page<Project> page = projectRepository.findAll(pageable); uriBuilder.path("v1/projects/"); HttpHeaders headers = generatePaginationHttpHeaders(uriBuilder.queryParams(queryParams), page); return ResponseEntity.ok().headers(headers).body(page.getContent()); } @GetMapping("{id}") public ResponseEntity<Project> readProject(@PathVariable Long id) { Optional<Project> todo = projectRepository.findById(id); return todo.map(response -> ResponseEntity.ok().body(response)) .orElse(new ResponseEntity<>(HttpStatus.NOT_FOUND)); } @PutMapping("{id}") public ResponseEntity<Project> updateProject(@RequestBody Project project) { if (project.getId() == null) { throw new BadRequest("Invalid ID: Null"); } Project result = projectRepository.save(project); return ResponseEntity.ok().body(result); } @DeleteMapping("{id}") public ResponseEntity<Void> deleteProject(@PathVariable Long id) { projectRepository.deleteById(id); return ResponseEntity.ok().build(); } }<file_sep>/src/main/java/com/newway/newwayapi/model/Roadmap.java package com.newway.newwayapi.model; import lombok.Data; import lombok.EqualsAndHashCode; import javax.persistence.Column; import javax.persistence.Entity; @Entity @Data @EqualsAndHashCode(callSuper = true) public class Roadmap extends AbstractEntity { @Column(nullable = false) private String head_name; @Column(nullable = false) private String including_name; } <file_sep>/README.md # newway-api rest api for newway application # newway - create-new-people - swagger - url <file_sep>/src/main/java/com/newway/newwayapi/model/AbstractEntity.java package com.newway.newwayapi.model; import lombok.Data; import org.springframework.data.annotation.CreatedBy; import org.springframework.data.annotation.CreatedDate; import org.springframework.data.annotation.LastModifiedDate; import javax.persistence.*; import java.io.Serializable; import java.time.Instant; @MappedSuperclass @Data public abstract class AbstractEntity implements Serializable { private static final long serialVersionUID = 1L; @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Long id; @CreatedDate private Instant createdDate = Instant.now(); @LastModifiedDate private Instant updatedDate = Instant.now(); } <file_sep>/src/main/java/com/newway/newwayapi/model/Tag.java package com.newway.newwayapi.model; import lombok.Data; import lombok.EqualsAndHashCode; import javax.persistence.Column; import javax.persistence.Entity; @Entity @Data @EqualsAndHashCode(callSuper = true) public class Tag extends AbstractEntity { @Column(nullable = false) private String new_tag; public String getNew_tag() { return new_tag; } public void setNew_tag(String new_tag) { this.new_tag = new_tag; } }
a5adc903c5ba39c8fbba9848b01006d23cad88b6
[ "Markdown", "Java" ]
5
Java
elmascan/newway-api-master
0f7852888d94575d454d429356bba55c49826273
f87580f16651b541df809f1cff00843e633ea4d4
refs/heads/master
<repo_name>ravuthz/spring-boot-data-rest-sample<file_sep>/src/main/java/com/hti/pos/service/data/SettingSettingItemDataService.java package com.hti.pos.service.data; import com.hti.pos.domain.Setting; import com.hti.pos.domain.SettingItem; import com.hti.pos.repository.SettingItemRepository; import com.hti.pos.repository.SettingRepository; import com.hti.pos.specification.SearchCriteria; import com.hti.pos.specification.SearchOperation; import com.hti.pos.specification.SearchSpecification; import lombok.extern.slf4j.Slf4j; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import javax.persistence.criteria.JoinType; import java.util.Arrays; import java.util.List; @Slf4j @Service public class SettingSettingItemDataService { private final SettingRepository settingRepository; private final SettingItemRepository settingItemRepository; @Autowired public SettingSettingItemDataService(SettingRepository settingRepository, SettingItemRepository settingItemRepository) { this.settingRepository = settingRepository; this.settingItemRepository = settingItemRepository; } public Setting newOrUpdate(String name, String thumbnail, String description) { Setting setting = settingRepository.findOneByName(name); if (setting == null) { setting = new Setting(name, thumbnail, description); settingRepository.save(setting); } return setting; } public SettingItem newOrUpdateItem(String name, String value, String description, Setting setting) { SettingItem item = settingItemRepository.findOneByName(name); if (item == null) { item = new SettingItem(name, value, description); item.setSetting(setting); settingItemRepository.save(item); } return item; } public SettingItem newOrUpdateItem(String name, String value, String description) { return newOrUpdateItem(name, value, description, null); } public void generateData() { log.debug("SettingSettingItemDataService.generateData()"); Setting setting1 = newOrUpdate("Site", "website.png", "All settings for website"); SettingItem item1 = newOrUpdateItem("Title", "POS System", "Set title for website", setting1); SettingItem item2 = newOrUpdateItem("Email", "<EMAIL>", "Set email for website", setting1); SettingItem item3 = newOrUpdateItem("Phone", "0964577770", "Set phone number for website", setting1); List<SettingItem> items = Arrays.asList(item1, item2, item3); // settingItemRepository.saveAll(items); // setting1.getItems().addAll(items); // settingRepository.save(setting1); SearchSpecification<SettingItem> searchSpecification = new SearchSpecification<>(); searchSpecification.add(new SearchCriteria("name", "title", SearchOperation.MATCH)); searchSpecification.add(new SearchCriteria("value", "pos", SearchOperation.MATCH)); settingItemRepository.findAll(searchSpecification) .forEach(item -> System.out.println("Found item: " + item)); settingRepository.findAll((root, query, criteriaBuilder) -> { return criteriaBuilder.equal(root.join("items", JoinType.INNER).get("name"), "item-21"); }).forEach(item -> { System.out.println("Search found item: " + item); }); } } <file_sep>/src/test/java/com/hti/pos/service/EntityServiceTest.java package com.hti.pos.service; import com.hti.pos.domain.Setting; import com.hti.pos.domain.SettingItem; import lombok.extern.slf4j.Slf4j; import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import java.util.List; import java.util.Optional; import static org.assertj.core.api.Assertions.assertThat; @Slf4j @SpringBootTest public class EntityServiceTest { @Autowired private EntityService service; @Test public void findAll() { List<Setting> list = service.findAll(Setting.class); log.debug("list: " + list); assertThat(list).isNotEmpty(); List<SettingItem> listItems = service.findAll(SettingItem.class); log.debug("listItems: " + listItems); assertThat(listItems).isNotEmpty(); } @Test public void save() { Setting setting = new Setting("test1", "test1.png", "Test 1"); Setting entity = (Setting) service.save(Setting.class, setting); System.out.println("entity: " + entity); assertThat(entity).isNotNull(); } @Test public void count() { long count = service.count(Setting.class); System.out.println("Count: " + count); assertThat(count).isGreaterThan(0); } @Test public void delete() { Optional setting = service.findById(Setting.class, 2L); assertThat(setting).isNotNull(); assertThat(setting.isPresent()).isTrue(); assertThat(setting.isEmpty()).isFalse(); service.delete(Setting.class, setting); assertThat(setting).isNull(); } }<file_sep>/src/main/java/com/hti/pos/PostApplicationRunner.java package com.hti.pos; import com.hti.pos.domain.Setting; import com.hti.pos.domain.SettingItem; import com.hti.pos.repository.SettingItemRepository; import com.hti.pos.repository.SettingRepository; import com.hti.pos.service.data.SettingSettingItemDataService; import com.hti.pos.service.data.UserRolePermissionDataService; import lombok.extern.slf4j.Slf4j; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.ApplicationArguments; import org.springframework.boot.ApplicationRunner; import org.springframework.stereotype.Component; import java.util.Arrays; import java.util.List; @Slf4j @Component public class PostApplicationRunner implements ApplicationRunner { @Autowired private UserRolePermissionDataService userRolePermissionDataService; @Autowired private SettingSettingItemDataService settingSettingItemDataService; @Override public void run(ApplicationArguments args) throws Exception { log.debug("PostApplicationRunner.run()"); // userRolePermissionDataService.generateData(); // settingSettingItemDataService.generateData(); } } <file_sep>/src/main/java/com/hti/pos/serializers/SettingCombinedSerializer.java package com.hti.pos.serializers; import com.fasterxml.jackson.core.JsonGenerator; import com.fasterxml.jackson.core.JsonParser; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.core.TreeNode; import com.fasterxml.jackson.databind.DeserializationContext; import com.fasterxml.jackson.databind.JsonDeserializer; import com.fasterxml.jackson.databind.JsonSerializer; import com.fasterxml.jackson.databind.SerializerProvider; import com.fasterxml.jackson.databind.node.TextNode; import com.hti.pos.domain.Setting; import org.springframework.boot.jackson.JsonComponent; import java.io.IOException; //@JsonComponent public class SettingCombinedSerializer { public static class SettingSerializer extends JsonSerializer<Setting> { @Override public void serialize(Setting value, JsonGenerator generator, SerializerProvider serializers) throws IOException { // generator.writeStartObject(); generator.writeStringField("name", value.getName()); generator.writeStringField("desc", value.getDescription()); // generator.writeEndObject(); } } public static class SettingDeserializer extends JsonDeserializer<Setting> { @Override public Setting deserialize(JsonParser parser, DeserializationContext ctx) throws IOException, JsonProcessingException { TreeNode treeNode = parser.getCodec().readTree(parser); TextNode nameNode = (TextNode) treeNode.get("name"); TextNode descNode = (TextNode) treeNode.get("desc"); return new Setting(nameNode.asText(), descNode.asText()); } } }<file_sep>/build.gradle plugins { id 'org.springframework.boot' version '2.4.0' id 'io.spring.dependency-management' version '1.0.10.RELEASE' id 'java' id 'base' id 'com.palantir.docker' version '0.25.0' id 'com.palantir.docker-run' version '0.25.0' id 'com.palantir.docker-compose' version '0.25.0' id 'pl.allegro.tech.build.axion-release' version '1.12.0' } group = 'com.hti' version = '0.0.1-SNAPSHOT' sourceCompatibility = '15' project.version = scmVersion.version repositories { mavenCentral() } dependencies { implementation 'org.springframework.boot:spring-boot-starter-actuator' implementation 'org.springframework.boot:spring-boot-starter-data-rest' implementation 'org.springframework.boot:spring-boot-starter-data-jpa' implementation 'org.springframework.boot:spring-boot-starter-validation' implementation 'org.springframework.boot:spring-boot-starter-security' implementation "io.springfox:springfox-boot-starter:3.0.0" implementation "io.springfox:springfox-data-rest:3.0.0" implementation "io.springfox:springfox-swagger-ui:3.0.0" implementation "io.springfox:springfox-bean-validators:3.0.0" implementation 'commons-httpclient:commons-httpclient:3.1' runtimeOnly 'org.postgresql:postgresql' compileOnly 'org.projectlombok:lombok' implementation 'org.projectlombok:lombok' developmentOnly 'org.springframework.boot:spring-boot-devtools' testImplementation 'org.springframework.boot:spring-boot-starter-test' annotationProcessor 'org.projectlombok:lombok' testAnnotationProcessor 'org.projectlombok:lombok' } test { useJUnitPlatform() } docker { name "${project.name}:${project.version}" dockerfile file('./jenkins/Dockerfile') files "jenkins/plugins.txt", "jenkins/seedJob.xml", "jenkins/credentials.xml" } dockerRun { name "${project.name}" image "${project.name}:${project.version}" ports "9999:8080" clean true daemonize false } dockerCompose { dockerComposeFile './jenkins/docker-compose.yml' }<file_sep>/src/test/java/com/hti/pos/repository/SettingRepositoryTest.java package com.hti.pos.repository; import com.hti.pos.domain.Setting; import com.hti.pos.domain.SettingItem; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.test.context.ActiveProfiles; import org.springframework.test.context.jdbc.Sql; import java.util.Arrays; import java.util.List; import static org.assertj.core.api.Assertions.assertThat; @SpringBootTest @ActiveProfiles("test") public class SettingRepositoryTest { @Autowired private SettingRepository settingRepository; @Autowired private SettingItemRepository settingItemRepository; private Setting createSetting(String name) { Setting setting = new Setting(name, name, name); setting.setSlug(name); return setting; } private Setting updateSetting(String name, Setting setting) { setting.setName(name); setting.setSlug(name); setting.setThumbnail(name); setting.setDescription(name); return setting; } private SettingItem createSettingItem(String name, Setting setting) { SettingItem settingItem = new SettingItem(name, name, name, setting); settingItem.setValue(name); return settingItem; } private SettingItem updateSettingItem(String name, SettingItem settingItem) { settingItem.setName(name); settingItem.setSlug(name); settingItem.setValue(name); settingItem.setThumbnail(name); settingItem.setDescription(name); return settingItem; } private final String[] ignoreFields = {"id", "version", "createdAt", "createdBy", "updatedAt", "updatedBy", "description"}; private final String[] SETTINGS = {"", "test-setting-1", "test-setting-2", "test-setting-3", "test-setting-4"}; private final String[] SETTING_ITEMS = { "", "test-setting-item-1", "test-setting-item-2", "test-setting-item-3", "test-setting-item-4", "test-setting-item-5", "test-setting-item-6", "test-setting-item-7" }; @Test @DisplayName("Can read, list, create, update, delete settings by SettingRepository") public void canCRUDSetting() { // Create 2 settings settingRepository.deleteAll(); settingRepository.saveAll(Arrays.asList( createSetting(SETTINGS[1]), createSetting(SETTINGS[2]) )); // Can read single setting Setting setting = settingRepository.findOneByName(SETTINGS[1]); assertThat(setting) .isNotNull() .usingRecursiveComparison().ignoringFields(ignoreFields).isEqualTo(createSetting(SETTINGS[1])); // Can list multiple settings List<Setting> settingList = (List<Setting>) settingRepository.findAll(); assertThat(settingList) .isNotEmpty() .hasSizeGreaterThanOrEqualTo(2) .extracting("name").containsOnly(SETTINGS[1], SETTINGS[2]); // Can create setting and return setting as result Setting setting3 = settingRepository.save(createSetting(SETTINGS[3])); assertThat(setting3) .isNotNull() .usingComparatorForFields((a, b) -> 0, "version") .usingRecursiveComparison().ignoringFields(ignoreFields).isEqualTo(createSetting(SETTINGS[3])); // Can update setting and return setting as result Setting found = settingRepository.findOneByName(SETTINGS[3]); Setting setting4 = settingRepository.save(updateSetting(SETTINGS[4], found)); assertThat(setting4) .isNotNull() .usingComparatorForFields((a, b) -> 1, "version") .usingRecursiveComparison().ignoringFields(ignoreFields).isEqualTo(createSetting(SETTINGS[4])); } @Test @DisplayName("Can read, list, create, update, delete setting's items by SettingItemRepository") public void canCRUDSettingItems() { // Create 7 setting's items for different settings settingRepository.deleteAll(); settingItemRepository.deleteAll(); Setting setting3 = settingRepository.save(createSetting(SETTINGS[3])); Setting setting4 = settingRepository.save(createSetting(SETTINGS[4])); List<SettingItem> settingItems = Arrays.asList( createSettingItem(SETTING_ITEMS[1], setting3), createSettingItem(SETTING_ITEMS[2], setting3), createSettingItem(SETTING_ITEMS[3], setting3), createSettingItem(SETTING_ITEMS[4], setting4), createSettingItem(SETTING_ITEMS[5], setting4), createSettingItem(SETTING_ITEMS[6], setting4) ); settingItemRepository.saveAll(settingItems); // Can read single setting's item assertThat(settingItemRepository.findOneByName(SETTING_ITEMS[1])) .isNotNull() .usingRecursiveComparison() .ignoringFields(ignoreFields) .isEqualTo(createSettingItem(SETTING_ITEMS[1], setting3)); // Can list multiple setting's items assertThat(settingItemRepository.findAll()) .isNotEmpty() .hasSizeGreaterThanOrEqualTo(settingItems.size()) .extracting("name") .containsOnly( settingItems.stream().map(item -> item.getName()).toArray() ); // Can create setting's item and return setting as result assertThat(settingItemRepository.save(createSettingItem(SETTING_ITEMS[7], setting4))) .isNotNull() .usingComparatorForFields((a, b) -> 0, "version") .usingRecursiveComparison().ignoringFields(ignoreFields) .isEqualTo(createSettingItem(SETTING_ITEMS[7], setting4)); // Can update setting's item and return setting as result SettingItem found = settingItemRepository.findOneByName(SETTING_ITEMS[7]); assertThat(settingItemRepository.save(updateSettingItem(SETTING_ITEMS[7], found))) .isNotNull() .usingComparatorForFields((a, b) -> 1, "version") .usingRecursiveComparison() .ignoringFields(ignoreFields) .isEqualTo(createSettingItem(SETTING_ITEMS[7], setting4)); } @Test @Sql("classpath:test-setting.sql") @DisplayName("Can insert data from test-setting.sql") public void canInsertSettingBySQL() { List<Setting> settingList = (List<Setting>) settingRepository.findAll(); assertThat(settingList) .isNotEmpty() .hasSizeGreaterThanOrEqualTo(3) .extracting("name").containsOnly( "test-setting-3", "test-setting-4", "script-setting-1", "script-setting-2", "script-setting-3" ); } }<file_sep>/src/test/resources/test-setting.sql -- DROP INDEX uniq_setting_index; -- CREATE UNIQUE INDEX uniq_setting_index ON settings USING btree ( "id", "version", "name", "slug", "description", "thumbnail"); -- INSERT INTO settings ( "id", "version", "name", "slug", "description", "thumbnail" ) -- VALUES -- ( 40, 1, 'script-setting-1', 'script-setting-1', 'script-setting-1', 'script-setting-1.png' ) -- ON CONFLICT ( "id", "version", "name", "slug", "description", "thumbnail" ) DO -- UPDATE SET description = EXCLUDED.description || ';' || settings.description; INSERT INTO settings ("id", "version", "name", "slug", "description", "thumbnail") VALUES (1, 0, 'script-setting-1', 'script-setting-1', 'script-setting-1', 'script-setting-1.png'), (2, 0, 'script-setting-2', 'script-setting-2', 'script-setting-2', 'script-setting-2.png'), (3, 0, 'script-setting-3', 'script-setting-3', 'script-setting-3', 'script-setting-3.png') ON CONFLICT ON CONSTRAINT settings_pkey DO UPDATE SET description = EXCLUDED.description || '; Record ' || settings.id || ' updated at ' || NOW(); INSERT INTO setting_items ("id", "version", "name", "slug", "description", "thumbnail", "setting") VALUES (1, 1, 'script-setting-item-1', 'script-setting-item-1', 'script-setting-item-1', 'script-setting-item-1.png', 1), (2, 1, 'script-setting-item-2', 'script-setting-item-2', 'script-setting-item-2', 'script-setting-item-2.png', 1), (3, 1, 'script-setting-item-3', 'script-setting-item-3', 'script-setting-item-3', 'script-setting-item-3.png', 1), (4, 1, 'script-setting-item-4', 'script-setting-item-4', 'script-setting-item-4', 'script-setting-item-4.png', 2), (5, 1, 'script-setting-item-5', 'script-setting-item-5', 'script-setting-item-5', 'script-setting-item-5.png', 2), (6, 1, 'script-setting-item-6', 'script-setting-item-6', 'script-setting-item-6', 'script-setting-item-6.png', 2), (7, 1, 'script-setting-item-7', 'script-setting-item-7', 'script-setting-item-7', 'script-setting-item-7.png', 2) ON CONFLICT ON CONSTRAINT setting_items_pkey DO UPDATE SET description = EXCLUDED.description || '; Record ' || setting_items.id || ' updated at ' || NOW(); -- List Index And Filter Index ... -- SELECT * FROM pg_class CL JOIN pg_namespace NS ON NS.oid = CL.relnamespace -- WHERE NS.nspname = 'public' AND CL.relname LIKE '%setting%' ORDER BY CL.relname; -- -- SELECT -- t.relname as table_name, -- i.relname as index_name, -- a.attname as column_name -- FROM -- pg_class t, -- pg_class i, -- pg_index ix, -- pg_attribute a -- WHERE -- t.oid = ix.indrelid -- AND i.oid = ix.indexrelid -- AND a.attrelid = t.oid -- AND a.attnum = ANY(ix.indkey) -- AND t.relkind = 'r' -- AND t.relname LIKE 'setting%' -- ORDER BY t.relname, i.relname; -- INSERT INTO settings ("id", "version", "name", "slug", "description", "thumbnail") -- VALUES -- (1, 0, 'script-setting-1', 'script-setting-1', 'script-setting-1', 'script-setting-1.png'), -- (2, 0, 'script-setting-2', 'script-setting-2', 'script-setting-2', 'script-setting-2.png') -- ON CONFLICT ON CONSTRAINT settings_pkey DO NOTHING; -- -- INSERT INTO setting_items ("id", "version", "name", "slug", "description", "thumbnail", "setting") VALUES -- (1, 1, 'script-setting-item-1', 'script-setting-item-1', 'script-setting-item-1', 'script-setting-item-1.png', 1), -- (2, 1, 'script-setting-item-2', 'script-setting-item-2', 'script-setting-item-2', 'script-setting-item-2.png', 1), -- (3, 1, 'script-setting-item-3', 'script-setting-item-3', 'script-setting-item-3', 'script-setting-item-3.png', 1), -- (4, 1, 'script-setting-item-4', 'script-setting-item-4', 'script-setting-item-4', 'script-setting-item-4.png', 2), -- (5, 1, 'script-setting-item-5', 'script-setting-item-5', 'script-setting-item-5', 'script-setting-item-5.png', 2), -- (6, 1, 'script-setting-item-6', 'script-setting-item-6', 'script-setting-item-6', 'script-setting-item-6.png', 2), -- (7, 1, 'script-setting-item-7', 'script-setting-item-7', 'script-setting-item-7', 'script-setting-item-7.png', 2) -- ON CONFLICT ON CONSTRAINT setting_items_pkey DO NOTHING;<file_sep>/src/main/java/com/hti/pos/domain/SettingItem.java package com.hti.pos.domain; import lombok.*; import javax.persistence.*; /** * Created by ravuthz * Date : 12/4/2020, 10:57 PM * Email : <EMAIL>, * <EMAIL> */ @Setter @Getter @Entity @NoArgsConstructor @AllArgsConstructor @EqualsAndHashCode(callSuper = false) @Table(name = "setting_items") public class SettingItem extends BaseSetting { public SettingItem(String name, String thumbnail, String description, Setting setting) { this.init(name, thumbnail, description); this.setting = setting; } public SettingItem(String name, String value, String description) { this.init(name, "", description); this.value = value; } @ManyToOne(fetch = FetchType.LAZY) @JoinColumn(name = "setting") private Setting setting; @Column private String value; @Override public String toString() { return "SettingItem { " + "setting=" + (setting != null ? setting.getName() : null) + ", name='" + name + '\'' + ", slug='" + slug + '\'' + ", value='" + value + '\'' + ", thumbnail='" + thumbnail + '\'' + ", description='" + description + '\'' + " } "; } } <file_sep>/src/test/java/com/hti/pos/UserRolePermissionTest.java package com.hti.pos; import com.hti.pos.domain.Permission; import com.hti.pos.domain.Role; import com.hti.pos.domain.User; import com.hti.pos.repository.PermissionRepository; import com.hti.pos.repository.RoleRepository; import com.hti.pos.repository.UserRepository; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.autoconfigure.jdbc.AutoConfigureTestDatabase; import org.springframework.boot.test.autoconfigure.orm.jpa.DataJpaTest; import org.springframework.boot.test.autoconfigure.orm.jpa.TestEntityManager; import java.util.Arrays; import java.util.Collections; import java.util.HashSet; import java.util.List; import static org.assertj.core.api.Assertions.assertThat; import static org.junit.jupiter.api.Assertions.assertEquals; /** * Created by ravuthz * Date : 11/23/2020, 2:32 PM * Email : <EMAIL>, <EMAIL> */ //@ExtendWith(SpringExtension.class) @DataJpaTest @AutoConfigureTestDatabase(replace = AutoConfigureTestDatabase.Replace.NONE) public class UserRolePermissionTest { @Autowired private TestEntityManager testEntityManager; @Autowired private UserRepository userRepository; @Autowired private RoleRepository roleRepository; @Autowired private PermissionRepository permissionRepository; @Test @DisplayName("Test Spring Database Instance") public void testFindByName() { testEntityManager.persist(User.staticUser("Test1", "User")); System.out.println("\nUserRepository.findAll()"); userRepository.findAll().forEach(u -> System.out.println(u)); List<User> users = userRepository.findAllByFirstNameStartingWithIgnoreCase("test"); assertEquals(1, users.size()); assertThat(users).extracting(User::getFirstName).containsOnly("Test1"); } @Test @DisplayName("Test Create User with Roles and Permissions") public void createUserWithRolePermissions() { var permissions = Arrays.asList( new Permission("SHOW_UAT", "UAT can show application"), new Permission("LIST_UAT", "UAT can list application"), new Permission("CREATE_UAT", "UAT can create application"), new Permission("UPDATE_UAT", "UAT can update application"), new Permission("DELETE_UAT", "UAT can delete application") ); permissionRepository.saveAll(permissions); var role = new Role("UAT"); roleRepository.save(role); var auditPermission = new Permission("AUDIT_UAT", "UAT can audit application"); auditPermission.getRoles().add(role); permissionRepository.save(auditPermission); role.getPermissions().addAll(permissions); roleRepository.save(role); var user = User.staticUser("uat", "user"); user.getRoles().add(role); userRepository.save(user); System.out.println("\nPermissionRepository.findAll()"); permissionRepository.findAll().forEach(p -> System.out.println(p)); System.out.println("\nRoleRepository.findAll()"); roleRepository.findAll().forEach(r -> System.out.println(r)); System.out.println("\nUserRepository.findAll()"); userRepository.findAll().forEach(u -> System.out.println(u)); long startTime1 = System.nanoTime(); System.out.println("\nUserRepository.findAllByLastNameContainsIgnoreCase()"); userRepository.findAllByLastNameContainsIgnoreCase("account").forEach(u -> System.out.println(u)); System.out.println("Duration 1: " + (System.nanoTime() - startTime1)); long startTime2 = System.nanoTime(); System.out.println("\nUserRepository.findByLastNameEndsWith()"); userRepository.findByLastNameEndsWith("account").forEach(u -> System.out.println(u)); System.out.println("Duration 2: " + (System.nanoTime() - startTime2)); long startTime3 = System.nanoTime(); System.out.println("\nUserRepository.findByLastNameLikeIgnoreCase()"); userRepository.findByLastNameLikeIgnoreCase("account").forEach(u -> System.out.println(u)); System.out.println("Duration 3: " + (System.nanoTime() - startTime3)); } } <file_sep>/src/main/java/com/hti/pos/domain/BaseSetting.java package com.hti.pos.domain; import lombok.Getter; import lombok.Setter; import javax.persistence.Column; import javax.persistence.MappedSuperclass; import javax.validation.constraints.NotEmpty; import java.text.Normalizer; import java.util.Locale; import java.util.regex.Pattern; /** * Created by ravuthz * Date : 12/4/2020, 10:59 PM * Email : <EMAIL>, * <EMAIL> */ @Setter @Getter @MappedSuperclass public class BaseSetting extends BaseEntity { @NotEmpty @Column(unique = true) protected String name; @NotEmpty @Column protected String slug; @Column protected String thumbnail; @Column protected String description; private static final Pattern NONLATIN = Pattern.compile("[^\\w-]"); private static final Pattern WHITESPACE = Pattern.compile("[\\s]"); public String makeSlug(String input) { if (input == null) { throw new IllegalArgumentException("makeSlug.input is required"); } String noWhiteSpace = WHITESPACE.matcher(input).replaceAll("-"); String normalized = Normalizer.normalize(noWhiteSpace, Normalizer.Form.NFD); String slug = NONLATIN.matcher(normalized).replaceAll(""); return slug.toLowerCase(Locale.ENGLISH); } public void init(String name, String thumbnail, String description) { this.name = name; this.slug = makeSlug(name); this.thumbnail = thumbnail; this.description = description; } } <file_sep>/src/main/java/com/hti/pos/domain/User.java package com.hti.pos.domain; import com.fasterxml.jackson.annotation.JsonIgnore; import lombok.AllArgsConstructor; import lombok.Getter; import lombok.NoArgsConstructor; import lombok.Setter; import javax.persistence.*; import javax.validation.constraints.Email; import javax.validation.constraints.NotEmpty; import java.io.Serializable; import java.util.HashSet; import java.util.Set; /** * Created by ravuthz * Date : 11/23/2020, 1:27 PM * Email : <EMAIL>, * <EMAIL> */ @Setter @Getter @Entity @NoArgsConstructor @AllArgsConstructor @Table(name = "users") public class User extends BaseEntity implements Serializable { private static final long serialVersionUID = -7721781417455120512L; @Email @NotEmpty private String email; @NotEmpty @Column(unique = true, nullable = false) private String username; @NotEmpty @JsonIgnore private String password; @NotEmpty private String firstName; @NotEmpty private String lastName; private boolean enabled; private Integer failedLoginAttempts = 0; @ManyToMany(fetch = FetchType.LAZY) @JoinTable(name = "userRole", joinColumns = @JoinColumn(name = "userId"), inverseJoinColumns = @JoinColumn(name = "roleId")) private Set<Role> roles = new HashSet<>(); public User(User user) { this.email = user.email; this.username = user.username; this.password = <PASSWORD>; this.firstName = user.firstName; this.lastName = user.lastName; this.enabled = user.enabled; this.failedLoginAttempts = user.failedLoginAttempts; // this.roles = user.roles; } public User(String firstName, String lastName) { this.firstName = firstName; this.lastName = lastName; } public static User staticUser(String firstName, String lastName) { User user = new User(firstName, lastName); user.setEmail(firstName + "@gmail.com"); user.setUsername(firstName); user.setPassword("<PASSWORD>"); user.setEnabled(true); return user; } public void setFullName(String firstName, String lastName) { this.firstName = firstName; this.lastName = lastName; } @JsonIgnore public String getFullName() { return this.firstName + " " + this.lastName; } @Override public String toString() { return "User{" + "email='" + email + '\'' + ", username='" + username + '\'' + ", password='" + <PASSWORD> + '\'' + ", firstName='" + firstName + '\'' + ", lastName='" + lastName + '\'' + ", enabled=" + enabled + ", failedLoginAttempts=" + failedLoginAttempts + '}'; } } <file_sep>/src/main/java/com/hti/pos/repository/PermissionRepository.java package com.hti.pos.repository; import com.hti.pos.domain.Permission; import org.springframework.data.repository.PagingAndSortingRepository; import org.springframework.stereotype.Repository; import java.util.List; /** * Created by ravuthz * Date : 11/23/2020, 3:56 PM * Email : <EMAIL>, <EMAIL> */ @Repository public interface PermissionRepository extends PagingAndSortingRepository<Permission, Long> { Permission findByName(String permission); List<Permission> findAllByNameIgnoreCaseStartingWith(String text); List<Permission> findAllByNameIgnoreCaseEndingWith(String text); } <file_sep>/README.md # Configure System ### Using Techology - Generate by: [Spring Initialzer](https://start.spring.io/) with [Gradle build tool](https://gradle.org) - Java Framework: [Spring boot version 1.5.6.RELEASE](https://projects.spring.io/spring-boot/) - Database: [Hibernate](http://hibernate.org/) with [PostgreSQL](https://www.postgresql.org/) - Library: + Project Lombok + Spring Data-JPA + Spring Data-REST + [Srpingfox Swagger 2 (v3.0.0)](https://springfox.github.io/springfox/docs/current/#gradle) + [Springfox Swagger UI 2 (v3.0.0)](https://springfox.github.io/springfox/docs/current/#springfox-swagger-ui) + [Springfox Swagger Data REST (v3.0.0)](https://springfox.github.io/springfox/docs/current/#gradle-2) - IDE: [Idea IntelliJ 2020.1](https://www.jetbrains.com/idea/whatsnew/#2020-1) ### SetUp, Build & Start Development Server ```bash git clone https://github.com/ravuthz/spring-boot-data-rest-sample.git cd spring-boot-data-rest-sample ./gradlew build -x test ./gradlew bootRun ``` ### Start Server End Points ```bash # API URL start http://localhost:9999/ # Swagger URL start http://localhost:9999/swagger-ui/ # Settings & Setting Items API URL http http://localhost:9999/api/settings open http://localhost:9999/api/setting-items curl -H 'Accept:application/json' http://localhost:9999/api/settings curl -H 'Accept:application/schema+json' http://localhost:9999/api/settings ``` #### Build & Start Server ```bash gradlew build -x test gradlew bootRun ``` #### Docker in Gradle ```bash gradlew docker --info gradlew dockerRun --info gradlew dockerStop --info gradlew dockerStop docker dockerRun --info ``` #### DockerCompose in Gradle ```bash gradlew dockerComposeUp --info gradlew dockerComposeDown --info gradlew dockerComposeDown dockerComposeUp --info ``` <file_sep>/src/main/java/com/hti/pos/configure/SwaggerConfig.java package com.hti.pos.configure; import org.springframework.beans.factory.annotation.Value; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Import; import org.springframework.http.HttpMethod; import org.springframework.http.MediaType; import springfox.documentation.builders.*; import springfox.documentation.schema.ScalarType; import springfox.documentation.service.*; import springfox.documentation.spi.DocumentationType; import springfox.documentation.spi.service.contexts.SecurityContext; import springfox.documentation.spring.data.rest.configuration.SpringDataRestConfiguration; import springfox.documentation.spring.web.plugins.Docket; import springfox.documentation.swagger2.annotations.EnableSwagger2; import java.util.*; /** * Created by ravuthz * Date : 12/2/2020, 9:44 PM * Email : <EMAIL>, <EMAIL> */ @Configuration @EnableSwagger2 @Import(SpringDataRestConfiguration.class) public class SwaggerConfig { public static final String AUTHORIZATION = "AUTHORIZATION"; public static final String SCOPE_READ = "read"; public static final String SCOPE_WRITE = "write"; public static final String SCOPE_READ_DESC = "Can read only"; public static final String SCOPE_WRITE_DESC = "Can write only"; @Value("${security.oauth2.url:}") private String oAuthTokenUrl; @Value("${swagger.apiInfo.title:}") private String title; @Value("${swagger.apiInfo.description:}") private String description; @Value("${swagger.apiInfo.version:}") private String version; @Value("${swagger.apiInfo.termOfServiceUrl:}") private String termOfServiceUrl; @Value("${swagger.apiInfo.contactUrl:}") private String contactUrl; @Value("${swagger.apiInfo.contactName:}") private String contactName; @Value("${swagger.apiInfo.contactEmail:}") private String contactEmail; @Value("${swagger.apiInfo.license:}") private String license; @Value("${swagger.apiInfo.licenseUrl:}") private String licenseUrl; @Value("${swagger.defaultKey.page:page}") private String pageKey; private String pageDescription = "Pagination's page number start by index"; @Value("${swagger.defaultKey.size:size}") private String sizeKey; private String sizeDescription = "Pagination's items per page"; @Value("${swagger.defaultKey.sort:sort}") private String sortKey; private String sortDescription = "Pagination's sort item by field"; @Value("${swagger.defaultValue.page:0}") private String pageValue; @Value("${swagger.defaultValue.size:20}") private String sizeValue; @Value("${swagger.defaultValue.sort:id,desc}") private String sortValue; @Bean public Docket api() { List<RequestParameter> parameterList = Arrays.asList( parameterBuilder(ParameterType.QUERY, pageKey, pageDescription, pageValue, false), parameterBuilder(ParameterType.QUERY, sizeKey, sizeDescription, sizeValue, false), parameterBuilder(ParameterType.QUERY, sortKey, sortDescription, sortValue, false) ); List<Response> responseList = List.of( responseBuilder(MediaType.APPLICATION_JSON, "200", "OK") // responseBuilder(MediaType.ALL, "401", "Unauthorized"), // responseBuilder(MediaType.ALL, "403", "Forbidden"), // responseBuilder(MediaType.APPLICATION_JSON, "404", "Not Found") ); return new Docket(DocumentationType.OAS_30) .select() // .apis(RequestHandlerSelectors.withClassAnnotation(Repository.class)) // .apis(RequestHandlerSelectors.withClassAnnotation(RestController.class)) // .apis(RequestHandlerSelectors.withClassAnnotation(BasePathAwareController.class)) // .apis(RequestHandlerSelectors.withClassAnnotation(RepositoryRestController.class)) // .apis(RequestHandlerSelectors.basePackage("com.hti.pos")) .apis(RequestHandlerSelectors.any()) .paths(PathSelectors.any()) // .paths(PathSelectors.regex("(?!/error.*).*")) .build() // .globalResponses(HttpMethod.GET, responseList) // .globalResponses(HttpMethod.PUT, responseList) // .globalResponses(HttpMethod.POST, responseList) // .globalResponses(HttpMethod.PATCH, responseList) // .globalRequestParameters(parameterList) // .securityContexts(Lists.newArrayList(securityContext())) // .securitySchemes(Collections.singletonList(securitySchema())) .apiInfo(apiInfoBuilder()) .tags(new Tag("Pet Service", "All apis relating to pets")); } private ApiInfo apiInfoBuilder() { return new ApiInfoBuilder() .title(title) .description(description) .version(version) .termsOfServiceUrl(termOfServiceUrl) .contact(new Contact(contactName, contactUrl, contactEmail)) .license(license) .licenseUrl(licenseUrl) .build(); } private RequestParameter parameterBuilder(ParameterType type, String name, String description, String defaultValue, boolean required) { return new RequestParameterBuilder() .name(name) .description(description) .in(type) .required(required) .query(q -> q.model(m -> m.scalarModel(ScalarType.STRING))) .build(); } private Response responseBuilder(MediaType mediaType, String code, String description) { return new ResponseBuilder() .code(code) .description(description) .representation(mediaType) .apply(r -> r.model(m -> m.referenceModel(ref -> ref.key(k -> k.qualifiedModelName(q -> q.namespace("org.springframework.boot.autoconfigure.web.servlet.error").name("BasicErrorController") ) ) ) ) ) .build(); } private List<AuthorizationScope> scopes() { List<AuthorizationScope> list = new ArrayList(); list.add(new AuthorizationScope(SCOPE_READ, SCOPE_READ_DESC)); list.add(new AuthorizationScope(SCOPE_WRITE, SCOPE_WRITE_DESC)); return list; } private List<GrantType> grantTypes() { ResourceOwnerPasswordCredentialsGrant resourceOwnerPasswordCredentialsGrant = new ResourceOwnerPasswordCredentialsGrant(oAuthTokenUrl); List<GrantType> grantTypes = Collections.singletonList(resourceOwnerPasswordCredentialsGrant); return grantTypes; } private OAuth securitySchema() { return new OAuth(AUTHORIZATION, scopes(), grantTypes()); } private List<SecurityReference> defaultAuth() { AuthorizationScope[] authorizationScopes = new AuthorizationScope[]{ new AuthorizationScope(SCOPE_READ, SCOPE_READ_DESC), new AuthorizationScope(SCOPE_WRITE, SCOPE_WRITE_DESC) }; return new ArrayList<>((Collection<? extends SecurityReference>) new SecurityReference(AUTHORIZATION, authorizationScopes)); } private SecurityContext securityContext() { return SecurityContext .builder() .securityReferences(defaultAuth()) .forPaths(PathSelectors.any()) .build(); } } <file_sep>/src/main/java/com/hti/pos/domain/EventReadOnly.java package com.hti.pos.domain; import javax.persistence.PrePersist; import javax.persistence.PreRemove; import javax.persistence.PreUpdate; public class EventReadOnly { @PrePersist void onPrePersist(Object o) { throw new IllegalStateException("JPA is trying to persist an entity of type " + (o == null ? "null" : o.getClass())); } @PreUpdate void onPreUpdate(Object o) { throw new IllegalStateException("JPA is trying to update an entity of type " + (o == null ? "null" : o.getClass())); } @PreRemove void onPreRemove(Object o) { throw new IllegalStateException("JPA is trying to remove an entity of type " + (o == null ? "null" : o.getClass())); } } <file_sep>/src/main/java/com/hti/pos/repository/SettingItemRepository.java package com.hti.pos.repository; import com.hti.pos.domain.SettingItem; import org.springframework.data.jpa.repository.JpaSpecificationExecutor; import org.springframework.data.repository.PagingAndSortingRepository; import org.springframework.data.rest.core.annotation.RepositoryRestResource; @RepositoryRestResource(path = "setting-items", collectionResourceRel = "setting-items") public interface SettingItemRepository extends PagingAndSortingRepository<SettingItem, Long>, JpaSpecificationExecutor<SettingItem> { SettingItem findOneByName(String name); } <file_sep>/src/main/java/com/hti/pos/domain/Role.java package com.hti.pos.domain; import lombok.AllArgsConstructor; import lombok.Getter; import lombok.NoArgsConstructor; import lombok.Setter; import javax.persistence.*; import javax.validation.constraints.NotEmpty; import java.io.Serializable; import java.util.HashSet; import java.util.Set; /** * Created by ravuthz * Date : 11/23/2020, 1:49 PM * Email : <EMAIL>, * <EMAIL> */ @Setter @Getter @Entity @NoArgsConstructor @AllArgsConstructor @Table(name = "roles") public class Role extends BaseEntity implements Serializable { private static final long serialVersionUID = -5403723535622562579L; @NotEmpty @Column(unique = true) private String name; private String note; @ManyToMany(mappedBy = "roles") private Set<User> users = new HashSet<>(); @ManyToMany(fetch = FetchType.LAZY) @JoinTable(name = "rolePermission", joinColumns = @JoinColumn(name = "roleId", referencedColumnName = "id", nullable = false, updatable = false), inverseJoinColumns = @JoinColumn(name = "permissionId", referencedColumnName = "id", nullable = false, updatable = false)) private Set<Permission> permissions = new HashSet<>(); public Role(String name) { this.name = name; } public Role(String name, String note) { this.name = name; this.note = note; } @Override public String toString() { return "Role{" + "name='" + name + '\'' + ", note='" + note + '\'' + '}'; } } <file_sep>/src/test/java/com/hti/pos/serializers/SettingCombinedSerializerTest.java package com.hti.pos.serializers; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.ObjectMapper; import com.hti.pos.domain.Setting; import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.test.context.ActiveProfiles; import java.io.IOException; import static org.junit.jupiter.api.Assertions.assertEquals; @SpringBootTest @ActiveProfiles("test") public class SettingCombinedSerializerTest { @Autowired private ObjectMapper objectMapper; private final String JSON_1 = "{\"name\":\"setting-1\",\"desc\":\"setting-1 desc\"}"; private final String JSON_2 = "{\"name\":\"setting-2\",\"desc\":\"setting-2 desc\"}"; @Test public void testSerialize() throws JsonProcessingException { Setting setting = new Setting("setting-1", "setting-1 desc"); String json = objectMapper.writeValueAsString(setting); System.out.println("setting: " + setting); System.out.println("json: " + json); assertEquals(JSON_1, json); } @Test public void testDeserialize() throws IOException { Setting setting = objectMapper.readValue(JSON_2, Setting.class); System.out.println("setting: " + setting); System.out.println("json: " + JSON_2); assertEquals("setting-2", setting.getName()); assertEquals("setting-2 desc", setting.getDescription()); } }
f98605d2360c3b984ccffaf4d2b74724ee4156b2
[ "Markdown", "Java", "SQL", "Gradle" ]
18
Java
ravuthz/spring-boot-data-rest-sample
245148721961294da2a78077352d839504b06fe4
84dac486cf4b3283c9f41fae4206ce41790c514d
refs/heads/master
<file_sep>using Microsoft.AspNetCore.Identity; namespace CMC_DME_Core_Angular.Models { public class ApplicationUser : IdentityUser { //public string UserName { get; set; } //public string Email { get; set; } //public string Password { get; set; } } } <file_sep>using Microsoft.EntityFrameworkCore; namespace CMC_DME_Core_Angular.Models { public class AccountDbContext:DbContext { public AccountDbContext(DbContextOptions<AccountDbContext> options) : base(options) { } public DbSet<Account> AccountDetails { get; set; } } } <file_sep>namespace CMC_DME_Core_Angular.Models { public class ApplicationSettings { public string JWT_Secret_Code { get; set; } public string Client_URL { get; set; } } } <file_sep>using System; using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations.Schema; namespace CMC_DME_Core_Angular.Models { public class Account { [Key] public int AccountId { get; set; } [Required] [Column(TypeName = "nvarchar(150)")] public string AccountName { get; set; } [Column(TypeName = "nvarchar(200)")] public string Description { get; set; } [Column(TypeName = "nvarchar(200)")] public string ContactName { get; set; } [Column(TypeName = "nvarchar(15)")] public string ContactNumber { get; set; } [Column(TypeName = "nvarchar(150)")] public string Email { get; set; } [Column(TypeName = "nvarchar(150)")] public string CreatedBy { get; set; } public DateTime CreatedDateTime { get; set; } [Column(TypeName = "nvarchar(150)")] public string ModifiedBy { get; set; } public DateTime ModifiedDateTime { get; set; } public bool Status { get; set; } } }
b531639b7c7939e691099d186b52239b55d4bf77
[ "C#" ]
4
C#
renuuner/CMC-DME-Core-Angular
cb09dd127d6a21cc20c1528ee205c2758604f330
adc80522d004c510dab4170b339404c612fb641d
refs/heads/master
<file_sep>from flask import Flask app=Flask(__name__) @app.route("/") def home(): return "Hello Flask 3" @app.route("/test") def test(): return "This is Test 3" if __name__=="__main__": app.run()
b519448db809961acdf787717dbc45b04a94869e
[ "Python" ]
1
Python
kuozheng10/FLASK_HEROKU
a7fa0c2ff115138366e9be56b7108ece895f542d
ffe19115b0c8e179c8dfe7ea08c0c484a771b1cc
refs/heads/master
<file_sep>package com.baizhi.service; import com.baizhi.entity.User; import com.baizhi.mapper.UserMapper; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import java.util.List; @Service @Transactional public class UserServiceImpl implements UserService { @Autowired UserMapper userMapper; public List<User> queryAll() { return userMapper.selectAll(); } public Integer proCount(String pro) { User user = new User(); user.setProvince(pro); int i = userMapper.selectCount(user); return i; } public Integer queryCount(Integer min, Integer max) { return userMapper.queryCount(min, max); } } <file_sep>package com.baizhi.dto; import com.baizhi.entity.Album; import com.baizhi.entity.Chapter; import lombok.AllArgsConstructor; import lombok.Data; import lombok.NoArgsConstructor; import java.util.List; @Data @AllArgsConstructor @NoArgsConstructor public class DetailDto { private Album detail; private List<Chapter> list; } <file_sep>package com.baizhi.service; import com.baizhi.entity.Admin; import com.baizhi.mapper.AdminMapper; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; @Service @Transactional public class AdminServiceImpl implements AdminService { @Autowired AdminMapper adminMapper; public boolean longin(Admin admin) { //验证码没加 Admin select = adminMapper.selectOne(admin); if (select == null) { return false; } else { return true; } } public Admin queryOne(String name) { Admin admin = new Admin(); admin.setName(name); Admin admin1 = adminMapper.selectOne(admin); return admin1; } } <file_sep>package com.baizhi.service; import com.baizhi.entity.Rp; import com.baizhi.mapper.RpMapper; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import java.util.List; @Service @Transactional public class RpcImpl implements RpService { @Autowired RpMapper rpMapper; @Override public List<Rp> queryOneByRole(String role) { Rp rp = new Rp(); rp.setRole(role); return rpMapper.select(rp); } } <file_sep>package com.baizhi.mapper; import com.baizhi.entity.User; import org.apache.ibatis.annotations.Param; import tk.mybatis.mapper.common.Mapper; public interface UserMapper extends Mapper<User> { public Integer queryCount(@Param("min")Integer min,@Param("max") Integer max); } <file_sep>package com.baizhi.controller; import com.baizhi.dto.AlbumDto; import com.baizhi.entity.Album; import com.baizhi.entity.Chapter; import com.baizhi.service.AlbumService; import com.github.pagehelper.PageHelper; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.multipart.MultipartFile; import javax.servlet.ServletContext; import javax.servlet.ServletOutputStream; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; import java.io.*; import java.net.URLEncoder; import java.util.Date; import java.util.List; import java.util.UUID; @Controller @RequestMapping(value = "alb", produces = "application/json;charset=UTF-8") public class AlbumController { @Autowired AlbumService albumService; @RequestMapping("showAll") @ResponseBody public AlbumDto showAll(Integer page, Integer rows) { PageHelper.startPage(page, rows); List<Album> albums = albumService.queryAll(); AlbumDto dto = new AlbumDto(albums, albumService.selectCount()); return dto; } @RequestMapping("showOne") public String showOne(Integer id, Model model) { System.out.println(id); Album album = new Album(); album.setId(id); Album album1 = albumService.queryOne(album); System.out.println(album1); model.addAttribute("album", album1); return "forward:/datagrid/show.jsp"; } @RequestMapping("insertAlbum") @ResponseBody public void insertAlbum(Album album, MultipartFile file2, HttpSession session) throws IllegalStateException, IOException { ServletContext ctx = session.getServletContext(); String filename = file2.getOriginalFilename(); String realPath = ctx.getRealPath("/img/audioCollection"); // 目标文件 File descFile = new File(realPath + "/" + filename); // 上传 file2.transferTo(descFile); album.setCoverImg(file2.getOriginalFilename()); album.setPubDate(new Date()); albumService.insertAlbum(album); } @RequestMapping("insertCha") @ResponseBody public void insertCha(Chapter chapter, MultipartFile file3, HttpSession session) throws IllegalStateException, IOException { ServletContext ctx = session.getServletContext(); String filename = file3.getOriginalFilename(); String realPath = ctx.getRealPath("/music"); // 目标文件 File descFile = new File(realPath + "/" + filename); // 上传 file3.transferTo(descFile); chapter.setUrl(file3.getOriginalFilename()); chapter.setId(UUID.randomUUID().toString().replaceAll("-", "")); chapter.setUploadDate(new Date()); albumService.insertCha(chapter); } @RequestMapping(value = "/download") public String filedownload(String fname, HttpSession session, HttpServletResponse response) throws IOException { // 获取server端文件的 字节数组 String realPath = session.getServletContext().getRealPath("/music"); File file = new File(realPath + "/" + fname); String encode = null; try { encode = URLEncoder.encode(fname, "utf-8"); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } if (file.exists()) { //判断文件父目录是否存在 response.setContentType("application/force-download"); response.setHeader("Content-Disposition", "attachment;fileName=" + encode); byte[] buffer = new byte[1024]; FileInputStream fis = null; //文件输入流 BufferedInputStream bis = null; ServletOutputStream os = null; //输出流 try { os = response.getOutputStream(); fis = new FileInputStream(file); bis = new BufferedInputStream(fis); int i = bis.read(buffer); while (i != -1) { os.write(buffer); i = bis.read(buffer); } } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } System.out.println("----------file download" + encode); try { bis.close(); fis.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } return null; } } <file_sep>package com.baizhi.controller; import com.baizhi.entity.Prodect; import com.baizhi.service.LuceneService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import org.springframework.web.multipart.MultipartFile; import javax.servlet.ServletContext; import javax.servlet.http.HttpSession; import java.io.File; import java.io.IOException; import java.util.List; import java.util.UUID; @RestController @RequestMapping(value = "pro", produces = "application/json;charset=UTF-8") public class ProductController { @Autowired LuceneService luceneService; @RequestMapping("add") public void add(Prodect prodect, MultipartFile file2, HttpSession session) throws IllegalStateException, IOException { prodect.setId(UUID.randomUUID().toString().replaceAll("-", "")); ServletContext ctx = session.getServletContext(); String filename = file2.getOriginalFilename(); String realPath = ctx.getRealPath("/productImg"); // 目标文件 File descFile = new File(realPath + "/" + filename); // 上传 file2.transferTo(descFile); prodect.setUrl("productImg/" + file2.getOriginalFilename()); System.out.println(prodect); luceneService.insert(prodect); } @RequestMapping("query") public List<Prodect> add(String keyWords) { List<Prodect> prodects = luceneService.queryByTerm(keyWords); System.out.println(prodects); return prodects; } } <file_sep>package com.baizhi.controller; import com.baizhi.conf.Error; import com.baizhi.dto.Success; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.ResponseBody; @Controller @RequestMapping(value = "identify", produces = "application/json;charset=UTF-8") public class IdentifyController { @RequestMapping("obtain") @ResponseBody public Object obtain(String phone) { if (phone == null) { return new Error("参数不能为空233"); } else { //发短信的方法 return null; } } @RequestMapping("check") @ResponseBody public Object check(String phone, String code) { if (phone == null || code == null) { return new Error("参数不能为空233"); } else { if (code.equals("2580")) { return new Success("success"); } return new Error("验证码错误"); } } } <file_sep>package com.baizhi.service; import com.baizhi.entity.Rp; import java.util.List; public interface RpService { public List<Rp> queryOneByRole(String role); } <file_sep>package com.baizhi.indexDao; import com.baizhi.entity.Html; import com.baizhi.util.LuceneUtil; import org.apache.lucene.document.Document; import org.apache.lucene.document.Field; import org.apache.lucene.document.StringField; import org.apache.lucene.document.TextField; import org.apache.lucene.index.IndexWriter; import org.apache.lucene.queryparser.classic.MultiFieldQueryParser; import org.apache.lucene.queryparser.classic.ParseException; import org.apache.lucene.queryparser.classic.QueryParser; import org.apache.lucene.search.IndexSearcher; import org.apache.lucene.search.Query; import org.apache.lucene.search.ScoreDoc; import org.apache.lucene.search.TopDocs; import org.apache.lucene.util.Version; import org.springframework.stereotype.Component; import org.wltea.analyzer.lucene.IKAnalyzer; import java.io.IOException; import java.util.ArrayList; import java.util.List; //1.声明该对象为spring包扫面的对象 @Component //2.Config page 的方式 添加conf包里的LuceneConfig类 并在上面加上相关的注解 public class LuceneHtmlDao { public void createIndex(Html html) { IndexWriter indexWriter = LuceneUtil.getIndexWriter(); Document docFromPro = getDocFromPro(html); try { indexWriter.addDocument(docFromPro); LuceneUtil.commit(indexWriter); } catch (IOException e) { e.printStackTrace(); LuceneUtil.rollback(indexWriter); } } public List<Html> SearcherIndex(String params) { IndexSearcher indexSearcher = LuceneUtil.getIndexSearcher(); List<Html> list = null; String[] strings = {"title", "biref"}; QueryParser multiFieldQueryParser = new MultiFieldQueryParser(Version.LUCENE_44, strings, new IKAnalyzer()); Query query = null; try { query = multiFieldQueryParser.parse(params); } catch (ParseException e) { e.printStackTrace(); } try { TopDocs topDocs = indexSearcher.search(query, 10); ScoreDoc[] scoreDocs = topDocs.scoreDocs; list = new ArrayList<>(); for (int i = 0; i < scoreDocs.length; i++) { ScoreDoc scoreDoc = scoreDocs[i]; int doc = scoreDoc.doc; Document document = indexSearcher.doc(doc); Html html = getProFromDoc(document); list.add(html); } } catch (IOException e) { e.printStackTrace(); } return list; } public Document getDocFromPro(Html html) { Document document = new Document(); document.add(new StringField("id", html.getId(), Field.Store.YES)); document.add(new StringField("date", html.getDate(), Field.Store.YES)); document.add(new TextField("biref", html.getBiref(), Field.Store.YES)); document.add(new StringField("htmlUrl", html.getHtmlUrl(), Field.Store.YES)); document.add(new StringField("url", html.getUrl(), Field.Store.YES)); document.add(new StringField("title", html.getTitle(), Field.Store.YES)); return document; } public Html getProFromDoc(Document document) { Html html = new Html(); html.setId(document.get("id")); html.setDate(document.get("date")); html.setBiref(document.get("biref")); html.setHtmlUrl(document.get("htmlUrl")); html.setUrl(document.get("url")); html.setTitle(document.get("title")); return html; } } <file_sep>package com.baizhi.indexDao; import com.baizhi.entity.Prodect; import com.baizhi.util.LuceneUtil; import org.apache.lucene.document.*; import org.apache.lucene.index.IndexWriter; import org.apache.lucene.index.Term; import org.apache.lucene.queryparser.classic.MultiFieldQueryParser; import org.apache.lucene.queryparser.classic.ParseException; import org.apache.lucene.queryparser.classic.QueryParser; import org.apache.lucene.search.IndexSearcher; import org.apache.lucene.search.Query; import org.apache.lucene.search.ScoreDoc; import org.apache.lucene.search.TopDocs; import org.apache.lucene.util.Version; import org.springframework.stereotype.Component; import org.wltea.analyzer.lucene.IKAnalyzer; import java.io.IOException; import java.util.ArrayList; import java.util.List; //1.声明该对象为spring包扫面的对象 @Component //2.Config page 的方式 添加conf包里的LuceneConfig类 并在上面加上相关的注解 public class LuceneProductDao { public void createIndex(Prodect prodect) { IndexWriter indexWriter = LuceneUtil.getIndexWriter(); Document docFromPro = getDocFromPro(prodect); try { indexWriter.addDocument(docFromPro); LuceneUtil.commit(indexWriter); } catch (IOException e) { e.printStackTrace(); LuceneUtil.rollback(indexWriter); } } public void deleteIndex(String id) { IndexWriter indexWriter = LuceneUtil.getIndexWriter(); try { indexWriter.deleteDocuments(new Term("id", id)); LuceneUtil.commit(indexWriter); } catch (IOException e) { e.printStackTrace(); LuceneUtil.rollback(indexWriter); } } public void updateIndex(Prodect product) { IndexWriter indexWriter = LuceneUtil.getIndexWriter(); Document docFromPro = getDocFromPro(product); try { indexWriter.updateDocument(new Term("id", product.getId()), docFromPro); LuceneUtil.commit(indexWriter); } catch (IOException e) { e.printStackTrace(); LuceneUtil.rollback(indexWriter); } } public List<Prodect> SearcherIndex(String params) { IndexSearcher indexSearcher = LuceneUtil.getIndexSearcher(); List<Prodect> list = null; String[] strings = {"name", "biref", "price"}; QueryParser multiFieldQueryParser = new MultiFieldQueryParser(Version.LUCENE_44, strings, new IKAnalyzer()); Query query = null; try { query = multiFieldQueryParser.parse(params); } catch (ParseException e) { e.printStackTrace(); } try { TopDocs topDocs = indexSearcher.search(query, 100); ScoreDoc[] scoreDocs = topDocs.scoreDocs; list = new ArrayList<>(); for (int i = 0; i < scoreDocs.length; i++) { ScoreDoc scoreDoc = scoreDocs[i]; int doc = scoreDoc.doc; Document document = indexSearcher.doc(doc); Prodect prodect = getProFromDoc(document); list.add(prodect); } } catch (IOException e) { e.printStackTrace(); } return list; } public Document getDocFromPro(Prodect prodect) { Document document = new Document(); document.add(new StringField("id", prodect.getId(), Field.Store.YES)); document.add(new StringField("name", prodect.getName(), Field.Store.YES)); document.add(new TextField("biref", prodect.getBiref(), Field.Store.YES)); document.add(new DoubleField("price", prodect.getPrice(), Field.Store.YES)); document.add(new StringField("url", prodect.getUrl(), Field.Store.YES)); document.add(new StringField("status", prodect.getStatus(), Field.Store.YES)); document.add(new StringField("date", prodect.getDate(), Field.Store.YES)); document.add(new StringField("city", prodect.getCity(), Field.Store.YES)); return document; } public Prodect getProFromDoc(Document document) { Prodect prodect = new Prodect(); prodect.setId(document.get("id")); prodect.setName(document.get("name")); prodect.setBiref(document.get("biref")); prodect.setPrice(Double.valueOf(document.get("price"))); prodect.setUrl(document.get("url")); prodect.setStatus(document.get("status")); prodect.setDate(document.get("date")); prodect.setCity(document.get("city")); return prodect; } } <file_sep>package com.baizhi.entity; import cn.afterturn.easypoi.excel.annotation.Excel; import cn.afterturn.easypoi.excel.annotation.ExcelCollection; import cn.afterturn.easypoi.excel.annotation.ExcelIgnore; import com.alibaba.fastjson.annotation.JSONField; import lombok.AllArgsConstructor; import lombok.Data; import lombok.NoArgsConstructor; import org.springframework.format.annotation.DateTimeFormat; import javax.persistence.Id; import javax.persistence.Table; import java.io.Serializable; import java.util.Date; import java.util.List; @Data @AllArgsConstructor @NoArgsConstructor @Table(name = "album") public class Album implements Serializable { @Id @ExcelIgnore private Integer id; @Excel(name = "专辑名", width = 30, needMerge = true) private String title; @Excel(name = "个数", needMerge = true) private Integer count; @Excel(name = "img", type = 2, needMerge = true) private String coverImg; @Excel(name = "评分", needMerge = true) private Integer score; @Excel(name = "作者", needMerge = true) private String author; @Excel(name = "播音", needMerge = true) private String broadcast; @ExcelIgnore private String brief; @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss") @JSONField(format = "yyyy-MM-dd HH:mm:ss") @Excel(name = "修改时间", format = "YYYY-MM-dd", needMerge = true) private Date pubDate; @ExcelCollection(name = "章节", orderNum = "4") private List<Chapter> children; } <file_sep>package com.baizhi.controller; import com.baizhi.conf.CreateValidateCode; import com.baizhi.entity.Admin; import com.baizhi.service.AdminService; import org.apache.shiro.SecurityUtils; import org.apache.shiro.authc.AuthenticationToken; import org.apache.shiro.authc.IncorrectCredentialsException; import org.apache.shiro.authc.UnknownAccountException; import org.apache.shiro.authc.UsernamePasswordToken; import org.apache.shiro.subject.Subject; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; import java.io.IOException; @Controller @RequestMapping("/adm") public class AdminController { @Autowired AdminService adminService; @RequestMapping("/login") public String login(Admin admin, String enCode, HttpSession session) { String code1 = (String) session.getAttribute("code"); if (!enCode.equals(code1)) { return "redirect:/index.jsp"; } if (adminService.longin(admin)) { session.setAttribute("admin", admin); return "redirect:/main/main.jsp"; } else { return "redirect:/index.jsp"; } } @RequestMapping("/loginUser") public String loginUser(Admin admin, String enCode, HttpSession session) { System.out.println(enCode); String code1 = (String) session.getAttribute("code"); if (!enCode.equals(code1)) { System.out.println("验证码错误"); return "redirect:/login.jsp"; } Subject subject = SecurityUtils.getSubject(); AuthenticationToken token = new UsernamePasswordToken(admin.getName(), admin.getPassword()); try { subject.login(token); return "redirect:/main/main.jsp"; } catch (UnknownAccountException e) { System.out.println("账号错误"); return "redirect:/login.jsp"; } catch (IncorrectCredentialsException e) { System.out.println("密码错误"); return "redirect:/login.jsp"; } } @RequestMapping("logoutUser") public String logoutUser() { Subject subject = SecurityUtils.getSubject(); subject.logout(); return "redirect:/login.jsp"; } @RequestMapping("/out") public String out(HttpSession session) { session.removeAttribute("admin"); return "redirect:/login.jsp"; } @RequestMapping("/createImg") public void createImg(HttpSession session, HttpServletResponse response) throws IOException { // 调用工具类,生成图片上的随机字符 CreateValidateCode cvc = new CreateValidateCode(); String code = cvc.getCode(); // 存 随机字符到 --- session session.setAttribute("code", code); // 调用工具类,把生成的随机字符,使用输出流往client输出成图片 cvc.write(response.getOutputStream()); } } <file_sep>package com.baizhi; import cn.afterturn.easypoi.excel.ExcelExportUtil; import cn.afterturn.easypoi.excel.entity.ExportParams; import com.baizhi.entity.Album; import com.baizhi.mapper.ArticleMapper; import com.baizhi.mapper.UserMapper; import com.baizhi.service.AlbumService; import com.baizhi.service.ArticleService; import com.baizhi.service.LuceneService; import com.baizhi.service.UserService; import org.apache.poi.ss.usermodel.Workbook; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.test.context.junit4.SpringRunner; import java.io.FileOutputStream; import java.io.IOException; import java.util.List; @RunWith(SpringRunner.class) @SpringBootTest public class CmfzApplicationTests { @Autowired AlbumService albumService; @Test public void contextLoads() { System.out.println(albumService.queryAll()); } @Test public void easypoi() { //用easypoi生成 xls List<Album> albums = albumService.queryAll(); for (Album album : albums) { String coverImg = album.getCoverImg(); album.setCoverImg("D:\\source\\springboot\\cmfz\\src\\main\\webapp\\img\\audioCollection/" + coverImg); } Workbook workbook = ExcelExportUtil.exportExcel(new ExportParams("持明法洲——章节", "章节"), Album.class, albums); try { workbook.write(new FileOutputStream("E:/a.xls")); } catch (IOException e) { e.printStackTrace(); } } @Autowired ArticleService service; @Test public void test() { System.out.println(service.queryAll()); } } <file_sep>package com.baizhi.service; import com.baizhi.entity.Article; import com.baizhi.mapper.ArticleMapper; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import java.util.List; @Service @Transactional public class ArticleServiceImpl implements ArticleService { @Autowired ArticleMapper articleMapper; public List<Article> queryAll() { return articleMapper.selectAll(); } } <file_sep>package com.baizhi.controller; import com.baizhi.conf.Error; import com.baizhi.service.AlbumService; import com.baizhi.service.ArticleService; import com.baizhi.service.BannerService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.ResponseBody; import java.util.HashMap; import java.util.Map; @Controller @RequestMapping(value = "cmfz", produces = "application/json;charset=UTF-8") public class FirstController { @Autowired BannerService bannerService; @Autowired AlbumService albumService; @Autowired ArticleService articleService; @RequestMapping("first_page") @ResponseBody public Object test(String uid, String type, String sub_type) { if (uid == null || type == null) { return new Error("参数不能为空233"); } else { if (type.equals("all")) { Map<String, Object> map = new HashMap<>(); map.put("banner", bannerService.queryAll()); map.put("album", albumService.queryAll()); map.put("article", articleService.queryAll()); return map; } else if (type.equals("wen")) { Map<String, Object> map = new HashMap<>(); map.put("album", albumService.queryAll()); return map; } else { if (sub_type != null) { if (sub_type.equals("ssyj")) { Map<String, Object> map = new HashMap<>(); map.put("article", articleService.queryAll()); return map; } else { Map<String, Object> map = new HashMap<>(); map.put("article", articleService.queryAll()); return map; } } else { return new Error("思的类型不能为空"); } } } } } <file_sep>package com.baizhi.service; import com.baizhi.entity.Admin; public interface AdminService { public boolean longin(Admin admin); public Admin queryOne(String name); } <file_sep>package com.baizhi.controller; import com.baizhi.dto.BannerDto; import com.baizhi.entity.Banner; import com.baizhi.service.BannerService; import com.github.pagehelper.PageHelper; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.multipart.MultipartFile; import javax.servlet.ServletContext; import javax.servlet.http.HttpSession; import java.io.File; import java.io.IOException; import java.util.Date; import java.util.List; @Controller @RequestMapping(value = "bann", produces = "application/json;charset=UTF-8") public class BannerController { @Autowired BannerService bannerService; @RequestMapping("showAll") @ResponseBody public BannerDto showAll(Integer page, Integer rows) { PageHelper.startPage(page, rows); List<Banner> banners = bannerService.queryAll(); BannerDto dto = new BannerDto(banners, bannerService.selectCount()); return dto; } @RequestMapping("update") @ResponseBody public void update(Banner banner) { bannerService.update(banner); } @RequestMapping("delete") @ResponseBody public void delete(Integer id) { Banner banner = new Banner(); banner.setId(id); bannerService.delete(banner); } @RequestMapping("insert") @ResponseBody public void insert(Banner banner, MultipartFile file1, HttpSession session) throws IllegalStateException, IOException { ServletContext ctx = session.getServletContext(); String filename = file1.getOriginalFilename(); String realPath = ctx.getRealPath("/shouye"); // 目标文件 File descFile = new File(realPath + "/" + filename); // 上传 file1.transferTo(descFile); banner.setImgPath("shouye/" + file1.getOriginalFilename()); banner.setPubDate(new Date()); bannerService.insert(banner); } } <file_sep>package com.baizhi.controller; import com.alibaba.fastjson.JSON; import com.baizhi.dto.UserDto; import com.baizhi.entity.User; import com.baizhi.service.UserService; import io.goeasy.GoEasy; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.ResponseBody; import java.util.HashSet; import java.util.LinkedList; import java.util.List; @Controller @RequestMapping(value = "user", produces = "application/json;charset=UTF-8") public class UserController { @Autowired UserService userService; @RequestMapping("showAll") @ResponseBody public List<UserDto> showAll() { List<User> users = userService.queryAll(); LinkedList<UserDto> userDtos = new LinkedList<>(); HashSet<String> hashSet = new HashSet<>(); for (User user : users) { hashSet.add(user.getProvince()); } for (String set : hashSet) { userDtos.add(new UserDto(set, userService.proCount(set))); } return userDtos; } @RequestMapping("showDate") @ResponseBody public List<Integer> showDate() { LinkedList<Integer> integers = new LinkedList<>(); integers.add(0); for (int i = 0; i <= 3; i++) { Integer integer = userService.queryCount(i * 7, i * 7 + 7); integers.add(integer); } return integers; } @RequestMapping("Json") @ResponseBody public void Json() { List<Integer> integers = showDate(); String s = JSON.toJSONString(integers); System.out.println(s); GoEasy goEasy = new GoEasy("http://rest-hangzhou.goeasy.io", "BC-331b885bd904423c9fcf3bc85737b19e"); goEasy.publish("mds2", "" + s); } } <file_sep>package com.baizhi.dto; import java.io.Serializable; public class MenuDto implements Serializable { private String text; private String iconCls; private String path; public MenuDto(String text, String iconCls, String path) { this.text = text; this.iconCls = iconCls; this.path = path; } public MenuDto() { } @Override public String toString() { return "MenuDto{" + "text='" + text + '\'' + ", iconCls='" + iconCls + '\'' + ", path='" + path + '\'' + '}'; } public String getText() { return text; } public void setText(String text) { this.text = text; } public String getIconCls() { return iconCls; } public void setIconCls(String iconCls) { this.iconCls = iconCls; } public String getPath() { return path; } public void setPath(String path) { this.path = path; } } <file_sep>package com.baizhi.service; import com.baizhi.entity.Html; import com.baizhi.entity.Prodect; import com.baizhi.indexDao.LuceneHtmlDao; import com.baizhi.indexDao.LuceneProductDao; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import java.util.List; @Service @Transactional public class LuceneServiceImpl implements LuceneService { @Autowired LuceneProductDao luceneProductDao; @Autowired LuceneHtmlDao luceneHtmlDao; public void insertHtml(Html html) { luceneHtmlDao.createIndex(html); } public List<Html> queryHtmlByTerm(String str) { List<Html> htmls = luceneHtmlDao.SearcherIndex(str); return htmls; } public void insert(Prodect prodect) { luceneProductDao.createIndex(prodect); } public List<Prodect> queryByTerm(String str) { List<Prodect> prodects = luceneProductDao.SearcherIndex(str); return prodects; } } <file_sep>package com.baizhi.controller; import com.baizhi.conf.Error; import com.baizhi.dto.DetailDto; import com.baizhi.entity.Album; import com.baizhi.entity.Chapter; import com.baizhi.mapper.AlbumMapper; import com.baizhi.mapper.ChapterMapper; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.ResponseBody; import java.util.List; @Controller @RequestMapping(value = "detail", produces = "application/json;charset=UTF-8") public class DetailController { @Autowired AlbumMapper albumMapper; @Autowired ChapterMapper chapterMapper; @RequestMapping("wen") @ResponseBody public Object test(String uid, Integer id) { if (uid == null || id == null) { return new Error("参数不能为空233"); } else { Album album = new Album(); album.setId(id); Album album1 = albumMapper.selectByPrimaryKey(album); Chapter chapter = new Chapter(); chapter.setAlbId(id); List<Chapter> select2 = chapterMapper.select(chapter); DetailDto detailDto = new DetailDto(); detailDto.setDetail(album1); detailDto.setList(select2); if (album1 == null) { return new Error("这个ID对应的专辑不存在"); } else { return detailDto; } } } }
e660499f75340597da20b3d99f0241d4323f40d4
[ "Java" ]
22
Java
mendesheng/cmfz3
f6397c3f4d1837f06ebdbd0cc5532c1f5e12a371
0c92171e169e35dc1a6556141494fa8a08e24614
refs/heads/main
<file_sep># Checkbox-to-Hide-Show This snippet could be really useful for a variety of reasons. Hopefully, you’ll remember me when you need to do advanced customisation of the checkout and its fields. In today’s snippet, we’ll add a new checkbox and a new “hidden” field — the field will display if the checkbox is checked, otherwise it will disappear. <br>https://www.codeithub.com/checkbox-to-hide-show-custom-checkout-field/ <file_sep>add_filter( 'woocommerce_checkout_fields' , 'codeithub_display_checkbox_and_new_checkout_field' ); function codeithub_display_checkbox_and_new_checkout_field( $fields ) { $fields['billing']['checkbox_trigger'] = array( 'type' => 'checkbox', 'label' => __('Checkbox label', 'woocommerce'), 'class' => array('form-row-wide'), 'clear' => true ); $fields['billing']['new_billing_field'] = array( 'label' => __('New Billing Field Label', 'woocommerce'), 'placeholder' => _x('New Billing Field Placeholder', 'placeholder', 'woocommerce'), 'class' => array('form-row-wide'), 'clear' => true ); return $fields; } add_action( 'woocommerce_after_checkout_form', 'codeithub_conditionally_hide_show_new_field', 9999 ); function codeithub_conditionally_hide_show_new_field() { wc_enqueue_js( " jQuery('input#checkbox_trigger').change(function(){ if (! this.checked) { // HIDE IF NOT CHECKED jQuery('#new_billing_field_field').fadeOut(); jQuery('#new_billing_field_field input').val(''); } else { // SHOW IF CHECKED jQuery('#new_billing_field_field').fadeIn(); } }).change(); "); }
3edc2b0a02d858940b0a4576d120dc21519240a6
[ "Markdown", "PHP" ]
2
Markdown
codeithub/Checkbox-to-Hide-Show
ab561dfd4db14bbdb19af15e6f76f8004bcf7bef
e5bcdddc287c5184593107b1cef366446956d5b6
refs/heads/master
<file_sep>/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package raflyfahrezi; import java.awt.Color; import javax.swing.JFrame; /** * * @author raflyfahrezi */ public class kalkulator extends javax.swing.JFrame { /** * Creates new form kalkulator */ boolean operatorIsSet = false; String typeOfOperator = null; double value1 = 0; public kalkulator() { initComponents(); btnKali.setBackground(Color.ORANGE); btnBagi.setBackground(Color.ORANGE); btnHasil.setBackground(Color.ORANGE); btnKurang.setBackground(Color.ORANGE); btnTambah.setBackground(Color.ORANGE); No0.setBackground(Color.DARK_GRAY); No1.setBackground(Color.DARK_GRAY); No2.setBackground(Color.DARK_GRAY); No3.setBackground(Color.DARK_GRAY); No4.setBackground(Color.DARK_GRAY); No5.setBackground(Color.DARK_GRAY); No6.setBackground(Color.DARK_GRAY); No7.setBackground(Color.DARK_GRAY); No8.setBackground(Color.DARK_GRAY); No9.setBackground(Color.DARK_GRAY); btnTitik.setBackground(Color.DARK_GRAY); txtCurrent.setForeground(Color.WHITE); txtResult.setForeground(Color.WHITE); No0.setMnemonic('0'); No1.setMnemonic('1'); No2.setMnemonic('2'); No3.setMnemonic('3'); No4.setMnemonic('4'); No5.setMnemonic('5'); No6.setMnemonic('6'); No7.setMnemonic('7'); No8.setMnemonic('8'); No9.setMnemonic('9'); btnKali.setMnemonic('x'); btnBagi.setMnemonic('/'); btnKurang.setMnemonic('-'); btnTambah.setMnemonic('+'); btnHasil.setMnemonic('H'); btnClear.setMnemonic('C'); } private String getText() { String value = String.valueOf(txtCurrent.getText()); return value; } /** * This method is called from within the constructor to initialize the form. * WARNING: Do NOT modify this code. The content of this method is always * regenerated by the Form Editor. */ @SuppressWarnings("unchecked") // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents private void initComponents() { No4 = new javax.swing.JButton(); No5 = new javax.swing.JButton(); No6 = new javax.swing.JButton(); No1 = new javax.swing.JButton(); No2 = new javax.swing.JButton(); No3 = new javax.swing.JButton(); No0 = new javax.swing.JButton(); btnTitik = new javax.swing.JButton(); No8 = new javax.swing.JButton(); No7 = new javax.swing.JButton(); No9 = new javax.swing.JButton(); btnBagi = new javax.swing.JButton(); btnTambah = new javax.swing.JButton(); btnKurang = new javax.swing.JButton(); btnHasil = new javax.swing.JButton(); btnClear = new javax.swing.JButton(); btnKali = new javax.swing.JButton(); txtCurrent = new javax.swing.JLabel(); txtResult = new javax.swing.JLabel(); setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE); setBackground(new java.awt.Color(36, 36, 36)); setCursor(new java.awt.Cursor(java.awt.Cursor.DEFAULT_CURSOR)); No4.setFont(new java.awt.Font("Dialog", 1, 24)); // NOI18N No4.setText("4"); No4.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { No4ActionPerformed(evt); } }); No5.setFont(new java.awt.Font("Dialog", 1, 24)); // NOI18N No5.setText("5"); No5.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { No5ActionPerformed(evt); } }); No6.setFont(new java.awt.Font("Dialog", 1, 24)); // NOI18N No6.setText("6"); No6.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { No6ActionPerformed(evt); } }); No1.setFont(new java.awt.Font("Dialog", 1, 24)); // NOI18N No1.setText("1"); No1.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { No1ActionPerformed(evt); } }); No2.setFont(new java.awt.Font("Dialog", 1, 24)); // NOI18N No2.setText("2"); No2.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { No2ActionPerformed(evt); } }); No3.setFont(new java.awt.Font("Dialog", 1, 24)); // NOI18N No3.setText("3"); No3.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { No3ActionPerformed(evt); } }); No0.setFont(new java.awt.Font("Dialog", 1, 24)); // NOI18N No0.setText("0"); No0.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { No0ActionPerformed(evt); } }); btnTitik.setFont(new java.awt.Font("Dialog", 1, 24)); // NOI18N btnTitik.setText("."); btnTitik.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { btnTitikActionPerformed(evt); } }); No8.setFont(new java.awt.Font("Dialog", 1, 24)); // NOI18N No8.setText("8"); No8.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { No8ActionPerformed(evt); } }); No7.setFont(new java.awt.Font("Dialog", 1, 24)); // NOI18N No7.setText("7"); No7.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { No7ActionPerformed(evt); } }); No9.setFont(new java.awt.Font("Dialog", 1, 24)); // NOI18N No9.setText("9"); No9.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { No9ActionPerformed(evt); } }); btnBagi.setFont(new java.awt.Font("Dialog", 1, 24)); // NOI18N btnBagi.setText("/"); btnBagi.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { btnBagiActionPerformed(evt); } }); btnTambah.setFont(new java.awt.Font("Dialog", 1, 24)); // NOI18N btnTambah.setText("+"); btnTambah.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { btnTambahActionPerformed(evt); } }); btnKurang.setFont(new java.awt.Font("Dialog", 1, 24)); // NOI18N btnKurang.setText("-"); btnKurang.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { btnKurangActionPerformed(evt); } }); btnHasil.setFont(new java.awt.Font("Dialog", 1, 24)); // NOI18N btnHasil.setText("="); btnHasil.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { btnHasilActionPerformed(evt); } }); btnClear.setFont(new java.awt.Font("Dialog", 1, 24)); // NOI18N btnClear.setText("Clear"); btnClear.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { btnClearActionPerformed(evt); } }); btnKali.setFont(new java.awt.Font("Dialog", 1, 24)); // NOI18N btnKali.setText("x"); btnKali.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { btnKaliActionPerformed(evt); } }); txtCurrent.setFont(new java.awt.Font("Dialog", 1, 24)); // NOI18N txtCurrent.setHorizontalAlignment(javax.swing.SwingConstants.RIGHT); txtCurrent.setText("0"); txtResult.setFont(new java.awt.Font("Dialog", 1, 24)); // NOI18N txtResult.setHorizontalAlignment(javax.swing.SwingConstants.RIGHT); javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane()); getContentPane().setLayout(layout); layout.setHorizontalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addContainerGap() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false) .addComponent(txtCurrent, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addGroup(layout.createSequentialGroup() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false) .addComponent(btnClear, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addGroup(javax.swing.GroupLayout.Alignment.LEADING, layout.createSequentialGroup() .addComponent(No0, javax.swing.GroupLayout.PREFERRED_SIZE, 146, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(btnTitik, javax.swing.GroupLayout.PREFERRED_SIZE, 70, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGroup(javax.swing.GroupLayout.Alignment.LEADING, layout.createSequentialGroup() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(No4, javax.swing.GroupLayout.PREFERRED_SIZE, 70, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(No1, javax.swing.GroupLayout.PREFERRED_SIZE, 70, javax.swing.GroupLayout.PREFERRED_SIZE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addComponent(No5, javax.swing.GroupLayout.PREFERRED_SIZE, 70, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(No6, javax.swing.GroupLayout.PREFERRED_SIZE, 70, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGroup(layout.createSequentialGroup() .addComponent(No2, javax.swing.GroupLayout.PREFERRED_SIZE, 70, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(No3, javax.swing.GroupLayout.PREFERRED_SIZE, 70, javax.swing.GroupLayout.PREFERRED_SIZE)))) .addGroup(javax.swing.GroupLayout.Alignment.LEADING, layout.createSequentialGroup() .addComponent(No7, javax.swing.GroupLayout.PREFERRED_SIZE, 70, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(No8, javax.swing.GroupLayout.PREFERRED_SIZE, 70, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(No9, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false) .addComponent(btnBagi, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(btnTambah, javax.swing.GroupLayout.DEFAULT_SIZE, 86, Short.MAX_VALUE) .addComponent(btnKurang, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(btnHasil, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(btnKali, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))) .addComponent(txtResult, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) .addGap(0, 6, Short.MAX_VALUE)) ); layout.setVerticalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addContainerGap() .addComponent(txtResult, javax.swing.GroupLayout.PREFERRED_SIZE, 38, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(txtCurrent, javax.swing.GroupLayout.PREFERRED_SIZE, 37, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false) .addComponent(btnClear, javax.swing.GroupLayout.DEFAULT_SIZE, 50, Short.MAX_VALUE) .addComponent(btnKali, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false) .addComponent(No8, javax.swing.GroupLayout.DEFAULT_SIZE, 70, Short.MAX_VALUE) .addComponent(No7, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(No9, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(btnBagi, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(No4, javax.swing.GroupLayout.PREFERRED_SIZE, 70, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(No5, javax.swing.GroupLayout.PREFERRED_SIZE, 70, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(No6, javax.swing.GroupLayout.PREFERRED_SIZE, 70, javax.swing.GroupLayout.PREFERRED_SIZE)) .addComponent(btnKurang, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(No1, javax.swing.GroupLayout.PREFERRED_SIZE, 70, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(No2, javax.swing.GroupLayout.PREFERRED_SIZE, 70, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(No3, javax.swing.GroupLayout.PREFERRED_SIZE, 70, javax.swing.GroupLayout.PREFERRED_SIZE)) .addComponent(btnTambah, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false) .addComponent(No0, javax.swing.GroupLayout.DEFAULT_SIZE, 70, Short.MAX_VALUE) .addComponent(btnTitik, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(btnHasil, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) ); pack(); }// </editor-fold>//GEN-END:initComponents private void No4ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_No4ActionPerformed if (getText().equals("0")) { txtCurrent.setText("4"); } else { txtCurrent.setText(getText().concat("4")); } }//GEN-LAST:event_No4ActionPerformed private void btnKaliActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnKaliActionPerformed if (operatorIsSet == false && txtCurrent.getText() != "0" && txtCurrent.getText() != "") { txtResult.setText(getText().concat(" x ")); value1 = Double.valueOf(getText()); txtCurrent.setText(""); typeOfOperator = "x"; operatorIsSet = true; } }//GEN-LAST:event_btnKaliActionPerformed private void No1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_No1ActionPerformed if (getText().equals("0")) { txtCurrent.setText("1"); } else { txtCurrent.setText(getText().concat("1")); } }//GEN-LAST:event_No1ActionPerformed private void No2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_No2ActionPerformed if (getText().equals("0")) { txtCurrent.setText("2"); } else { txtCurrent.setText(getText().concat("2")); } }//GEN-LAST:event_No2ActionPerformed private void No3ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_No3ActionPerformed if (getText().equals("0")) { txtCurrent.setText("3"); } else { txtCurrent.setText(getText().concat("3")); } }//GEN-LAST:event_No3ActionPerformed private void No5ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_No5ActionPerformed if (getText().equals("0")) { txtCurrent.setText("5"); } else { txtCurrent.setText(getText().concat("5")); } }//GEN-LAST:event_No5ActionPerformed private void No6ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_No6ActionPerformed if (getText().equals("0")) { txtCurrent.setText("6"); } else { txtCurrent.setText(getText().concat("6")); } }//GEN-LAST:event_No6ActionPerformed private void No7ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_No7ActionPerformed if (getText().equals("0")) { txtCurrent.setText("7"); } else { txtCurrent.setText(getText().concat("7")); } }//GEN-LAST:event_No7ActionPerformed private void No8ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_No8ActionPerformed if (getText().equals("0")) { txtCurrent.setText("8"); } else { txtCurrent.setText(getText().concat("8")); } }//GEN-LAST:event_No8ActionPerformed private void No9ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_No9ActionPerformed if (getText().equals("0")) { txtCurrent.setText("9"); } else { txtCurrent.setText(getText().concat("9")); } }//GEN-LAST:event_No9ActionPerformed private void btnBagiActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnBagiActionPerformed if (operatorIsSet == false && txtCurrent.getText() != "0" && txtCurrent.getText() != "") { txtResult.setText(getText().concat(" / ")); value1 = Double.valueOf(getText()); txtCurrent.setText(""); typeOfOperator = "/"; operatorIsSet = true; } }//GEN-LAST:event_btnBagiActionPerformed private void btnKurangActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnKurangActionPerformed if (operatorIsSet == false && txtCurrent.getText() != "0" && txtCurrent.getText() != "") { txtResult.setText(getText().concat(" - ")); value1 = Double.valueOf(getText()); txtCurrent.setText(""); typeOfOperator = "-"; operatorIsSet = true; } }//GEN-LAST:event_btnKurangActionPerformed private void btnTambahActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnTambahActionPerformed if (operatorIsSet == false && txtCurrent.getText() != "0" && txtCurrent.getText() != "") { txtResult.setText(getText().concat(" + ")); value1 = Double.valueOf(getText()); txtCurrent.setText(""); typeOfOperator = "+"; operatorIsSet = true; } }//GEN-LAST:event_btnTambahActionPerformed private void btnHasilActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnHasilActionPerformed if (operatorIsSet && !getText().equals("")) { double result = 0; String temp = ""; switch (typeOfOperator) { case "x" : result = value1 * Double.valueOf(getText()); break; case "/" : result = value1 / Double.valueOf(getText()); break; case "-" : result = value1 - Double.valueOf(getText()); break; case "+" : result = value1 + Double.valueOf(getText()); break; } if (result == Math.floor(result)) { txtCurrent.setText(String.valueOf((int)result)); } else { txtCurrent.setText(String.format("%.2f", result)); } txtResult.setText(""); operatorIsSet = false; typeOfOperator = null; } }//GEN-LAST:event_btnHasilActionPerformed private void No0ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_No0ActionPerformed if (getText().equals("0")) { txtCurrent.setText("0"); } else { txtCurrent.setText(getText().concat("0")); } }//GEN-LAST:event_No0ActionPerformed private void btnTitikActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnTitikActionPerformed if (!getText().contains(".")) { txtCurrent.setText(getText().concat(".")); } }//GEN-LAST:event_btnTitikActionPerformed private void btnClearActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnClearActionPerformed txtCurrent.setText("0"); txtResult.setText(""); operatorIsSet = false; typeOfOperator = null; value1 = 0; }//GEN-LAST:event_btnClearActionPerformed /** * @param args the command line arguments */ public static void main(String args[]) { /* Set the Nimbus look and feel */ //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) "> /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel. * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html */ try { for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) { if ("Nimbus".equals(info.getName())) { javax.swing.UIManager.setLookAndFeel(info.getClassName()); break; } } } catch (ClassNotFoundException ex) { java.util.logging.Logger.getLogger(kalkulator.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (InstantiationException ex) { java.util.logging.Logger.getLogger(kalkulator.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (IllegalAccessException ex) { java.util.logging.Logger.getLogger(kalkulator.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (javax.swing.UnsupportedLookAndFeelException ex) { java.util.logging.Logger.getLogger(kalkulator.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } //</editor-fold> /* Create and display the form */ java.awt.EventQueue.invokeLater(new Runnable() { public void run() { Color background = new Color(36, 36, 36); kalkulator kalkulatorObj = new kalkulator(); kalkulatorObj.setLocationRelativeTo(null); kalkulatorObj.getContentPane().setBackground(background); kalkulatorObj.setTitle("Kalkulator"); kalkulatorObj.setVisible(true); } }); } // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JButton No0; private javax.swing.JButton No1; private javax.swing.JButton No2; private javax.swing.JButton No3; private javax.swing.JButton No4; private javax.swing.JButton No5; private javax.swing.JButton No6; private javax.swing.JButton No7; private javax.swing.JButton No8; private javax.swing.JButton No9; private javax.swing.JButton btnBagi; private javax.swing.JButton btnClear; private javax.swing.JButton btnHasil; private javax.swing.JButton btnKali; private javax.swing.JButton btnKurang; private javax.swing.JButton btnTambah; private javax.swing.JButton btnTitik; private javax.swing.JLabel txtCurrent; private javax.swing.JLabel txtResult; // End of variables declaration//GEN-END:variables }
c680f4d7414c48b6bf53a6896b81eebad71c8a54
[ "Java" ]
1
Java
raflyfahrezi/10118377_FarhanRaflyFahrezi_TugasKe3
dae606f02edcc4d8b6c5f147a75ecc570adb9975
1b65a2be0a83909241c6daf17c13908375822258
refs/heads/main
<file_sep>import os import discord import asyncio import os import time import numpy as np from matplotlib import pyplot as plt from discord import channel import youtube_dl from discord.channel import VoiceChannel from discord.ext import commands,tasks from dotenv import load_dotenv from edupage_api import Edupage, BadCredentialsException, LoginDataParsingException, EduDate, EduTime load_dotenv() TOKEN = str(os.getenv('DISCORD_TOKEN')) TOKEN = TOKEN.strip("{ }") EDUPAGE_PASS = str(os.getenv('EDUPAGE_PASS')) EDUPAGE_PASS = EDUPAGE_PASS.strip("{ }") EDUPAGE_NAME = str(os.getenv('EDUPAGE_NAME')) EDUPAGE_NAME = EDUPAGE_NAME.strip("{ }") EDUPAGE_SCHOOL = str(os.getenv('EDUPAGE_SCHOOL')) EDUPAGE_SCHOOL = EDUPAGE_SCHOOL.strip("{ }") bot = commands.Bot(command_prefix='-') youtube_dl.utils.bug_reports_message = lambda: '' ytdl_format_options = { 'format': 'bestaudio/best', 'restrictfilenames': True, 'noplaylist': True, 'nocheckcertificate': True, 'ignoreerrors': False, 'logtostderr': False, 'quiet': True, 'no_warnings': True, 'default_search': 'auto', 'source_address': '0.0.0.0' # bind to ipv4 since ipv6 addresses cause issues sometimes } ffmpeg_options = { 'options': '-vn' } ytdl = youtube_dl.YoutubeDL(ytdl_format_options) class YTDLSource(discord.PCMVolumeTransformer): def __init__(self, source, *, data, volume=0.3): super().__init__(source, volume) self.data = data self.title = data.get('title') self.url = "" @classmethod async def from_url(cls, url, *, loop=None, stream=False): loop = loop or asyncio.get_event_loop() data = await loop.run_in_executor(None, lambda: ytdl.extract_info(url, download=not stream)) if 'entries' in data: # take first item from a playlist data = data['entries'][0] filename = data['title'] if stream else ytdl.prepare_filename(data) return filename async def loggin(ctx): edupage = Edupage(EDUPAGE_SCHOOL, EDUPAGE_NAME, EDUPAGE_PASS) try: edupage.login() print("Login successfully!") return edupage except BadCredentialsException: print("Wrong username or password!") except LoginDataParsingException: print("Try again or open an issue!") @bot.event async def on_ready(): print(f'{bot.user.name} has connected to Discord!') @bot.command() async def join(ctx): channel = ctx.author.voice.channel await channel.connect() @bot.command() async def leave(ctx): await ctx.voice_client.disconnect() @bot.command() async def kde(ctx): try: await join(ctx) except: pass try : server = ctx.message.guild voice_channel = server.voice_client async with ctx.typing(): filename = await YTDLSource.from_url("https://www.youtube.com/watch?v=AlwgAcH9V7A", loop=bot.loop) voice_channel.play(discord.FFmpegPCMAudio(executable="ffmpeg.exe", source=filename)) time.sleep(10) await leave(ctx) except: await ctx.send("The bot is not connected to a voice channel.") @bot.command() async def sad(ctx): nm = ctx.username await ctx.edit(username=nm + "-sad") @bot.command() async def play(ctx, url): try: await join(ctx) except: pass try : server = ctx.message.guild voice_channel = server.voice_client async with ctx.typing(): filename = await YTDLSource.from_url(url, loop=bot.loop) voice_channel.play(discord.FFmpegPCMAudio(executable="ffmpeg.exe", source=filename)) except: await ctx.send("The bot is not connected to a voice channel.") @bot.command() async def hour(ctx): try: edupage = await loggin(ctx) except: print("failed to loggin") await ctx.send("failed to loggin") today = EduDate.today() timetable = edupage.get_timetable(today) current_time = EduTime.now() current_lesson = timetable.get_lesson_at_time(current_time) current_lesson = str(current_lesson).strip("{ }").split(", ")[0:2] current_lesson_split = [] for key_and_value in current_lesson: current_lesson_split.append(key_and_value.split(": ")[1]) await ctx.send(f"{str(current_lesson_split[0])} {str(current_lesson_split[1])}") @bot.command() async def home(ctx): try: edupage = await loggin(ctx) except: print("failed to loggin") await ctx.send("failed to loggin") try : homework = edupage.get_homework() for hw in range(10): print(f"| {homework[hw].due_date} | {homework[hw].subject} | {homework[hw].title} | ") await ctx.send(f"| {homework[hw].due_date} | {homework[hw].subject} | {homework[hw].title} | \n") except: await ctx.send("Error") @bot.command() async def graph(ctx, x, y): x = x.strip("[]").split(",") holderx = [] for i in x: holderx.append(float(i)) y = y.strip("[]() ").split(",") holdery = [] for i in y: holdery.append(float(i)) xpoints = np.array(holderx) ypoints = np.array(holdery) plt.plot(xpoints, ypoints, marker="x", color="black") plt.grid(True, "both") plt.savefig('figure.png') await ctx.send(file=discord.File('figure.png')) os.remove("./figure.png") bot.run(TOKEN) """-graph [0,0,15.9,24.7,25.6,26.9,27.7,28.9,29.8,31.0,31.9,32.8,33.9,21.8,21.7,21.6,21.6,21.5,21.5] [0,0,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,2.6,2.8,3.0,3.1,3.5,3.6] -graph [0,5,10.1,24.3,25.7,27,27.8,29,29.8,30.8,32,32.8,33.9,22,22,21.9,21.8,21.7,21.7] [0,0,0,0.,0.,0.,0.,0.,0.,0.,0.,0.,0,2.5,2.7,3.0,3.2,3.4,3.6] """
bc892189229cc61aea18eaacabcde6ac9f9d9403
[ "Python" ]
1
Python
hlasensky/Discord_bot
400113f3ba2824ce8eab1e6337329e475eb00b14
826562a07e93d49d2848d641df793490e1d563e6
refs/heads/master
<file_sep>/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package quiz058; /** * https://leetcode.com/problems/length-of-last-word/description/ * * Given a string s consists of upper/lower-case alphabets and empty space characters ' ', return the length of last word in the string. If the last word does not exist, return 0. Note: A word is defined as a character sequence consists of non-space characters only. For example, Given s = "<NAME>", return 5. * * @author sunwangshu */ public class Quiz058 { public static int lengthOfLastWord(String s) { char[] set = s.toCharArray(); int count = 0; boolean started = false; for (int i = set.length-1; i>=0; i--) { if (!started) { if (set[i] != ' ') { count ++; started = true; } } else { if (set[i] != ' '){ count ++; }else { break; } } } return count; } public static int lengthOfLastWord2(String s) { // from online int length = 0, tail = s.length() - 1; while(tail >= 0 && s.charAt(tail) == ' ') tail--; while(tail >= 0 && s.charAt(tail) != ' ') { length++; tail--; } return length; } /** * @param args the command line arguments */ public static void main(String[] args) { // TODO code application logic here //String s = "thi si ldkjf "; String s = ""; int count = lengthOfLastWord(s); System.out.println(count); } } <file_sep>/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package quiz027; /** * * @author sunwangshu * Given an array and a value, remove all instances of that value in place and return the new length. Do not allocate extra space for another array, you must do this in place with constant memory. The order of elements can be changed. It doesn't matter what you leave beyond the new length. Example: Given input array nums = [3,2,2,3], val = 3 Your function should return length = 2, with the first two elements of nums being 2. * */ public class Quiz027 { public static int removeElement1_1(int[] nums, int val) { /** a slower runner and a faster runner, just like #026 * if anything other than val then store it * nums can be empty? */ if (nums.length == 0) return 0; int i = 0; for (int j = 0; j < nums.length; j++) { if (nums[j] != val) { nums[i] = nums[j]; i++; } } return i; // not return i+1 } public static int removeElement1_2(int[] nums, int val) { /** oh someone point out that the element to be removed could be sparse * then I can just switch it with last element and decrease the length by 1 */ if (nums.length == 0) return 0; int l = nums.length; // could use n for (int j = 0; j < l; j++) { // could use i if (nums[j] == val) { nums[j] = nums[l-1]; l--; } } return l; } /** * @param args the command line arguments */ public static void main(String[] args) { // TODO code application logic here int[] nums = {1, 1, 2, 4, 5, 6, 6, 7, 8, 9, 9, 9, 9, 9}; int length = removeElement1_2(nums, 6); System.out.println(length); for (int i = 0; i < length; i++) { System.out.print(nums[i] + " "); } System.out.println(); } } <file_sep>/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package quiz053; /** *Find the contiguous subarray within an array (containing at least one number) which has the largest sum. For example, given the array [-2,1,-3,4,-1,2,1,-5,4], the contiguous subarray [4,-1,2,1] has the largest sum = 6. * @author sunwangshu */ public class Quiz053 { /*-------- just a way of thinking ------*/ // // public int maxSubArray(int[] nums) { // int currentMax = nums[0]; // for (int i = 0; i < nums.length; i++) { // int maxBefore = DP(nums,i); // if (maxBefore > currentMax) { // currentMax = maxBefore; // } // } // return currentMax; // } // public int DP(int[] nums, int i) { // if (i == 0) { // return nums[0]; // } // else { // int maxBefore = DP(nums, i-1); // return (maxBefore > 0 ? maxBefore: 0) + nums[i]; // } // } /*--------- optimized ---------*/ public static int maxSubArray(int[] nums) { int currentMax = nums[0]; int maxBefore = nums[0]; for (int i = 1; i < nums.length; i++) { maxBefore = (maxBefore > 0 ? maxBefore: 0) + nums[i]; // must use parenthesis if (maxBefore > currentMax) { currentMax = maxBefore; } } return currentMax; } /** * @param args the command line arguments */ public static void main(String[] args) { // TODO code application logic here int[] nums = {-2,1,-3,4,-1,2,1,-5,4}; int result = maxSubArray(nums); System.out.println(result); } } <file_sep>/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package quiz021; /** * * @author sunwangshu */ public class ListNodeGroup { ListNode head; ListNode[] nodes; ListNodeGroup (int[] x) { if (x.length > 0) { nodes = new ListNode[x.length]; for (int i = 0; i < x.length ; i++) { nodes[i] = new ListNode(x[i]); } for (int i = 0; i < x.length-1; i++) { nodes[i].next = nodes[i+1]; } head = nodes[0]; head.print(); } } } <file_sep>compile.on.save=true user.properties.file=/Users/sunwangshu/Library/Application Support/NetBeans/8.2/build.properties <file_sep>/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package quiz038; /** * * @author sunwangshu * * The count-and-say sequence is the sequence of integers with the first five terms as following: 1. 1 2. 11 3. 21 4. 1211 5. 111221 1 is read off as "one 1" or 11. 11 is read off as "two 1s" or 21. 21 is read off as "one 2, then one 1" or 1211. Given an integer n, generate the nth term of the count-and-say sequence. Note: Each term of the sequence of integers will be represented as a string. Example 1: Input: 1 Output: "1" Example 2: Input: 4 Output: "1211" */ public class Quiz038 { public static String countAndSay(int n) { /** recursive, using String "+" * around 30ms */ if (n == 1) return "1"; else { String s = countAndSay(n-1) + "0"; String sNew = ""; int counter = 1; char val = s.charAt(0); for (int i = 1; i < s.length(); i++) { if (s.charAt(i) != val) { sNew = sNew + counter + val; counter = 1; val = s.charAt(i); } else { counter ++; } } return sNew; } } public static String countAndSay2(int n) { /** recursive, using StringBuilder. * said to be faster than using String "+" * 4ms OMG */ if (n == 1) return "1"; else { String prev = countAndSay(n-1) + "0"; StringBuilder sb = new StringBuilder(); int counter = 1; char val = prev.charAt(0); for (int i = 1; i < prev.length(); i++) { if (prev.charAt(i) != val) { sb = sb.append(counter).append(val); counter = 1; val = prev.charAt(i); } else { counter ++; } } return sb.toString(); } } /** * @param args the command line arguments */ public static void main(String[] args) { // TODO code application logic here // Java doesn't have a end /0 // String s = "this"; // char test = s.charAt(4); // System.out.println(test); for (int i = 1; i < 20; i++) { String str = countAndSay2(i); System.out.println(str); } } } <file_sep>/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package quiz007; import java.util.*; /** * * @author sunwangshu */ public class Quiz007 { /** * @param args the command line arguments */ public static int reverse(int x) { // get each digit stored in an array int sign = x >= 0 ? 1 : -1; int divisor = Math.abs(x); List<Integer> digits = new ArrayList<Integer>(); // keep dividing by 10, get [0], [1], etc until the result is 0 while (divisor > 0) { int temp = divisor % 10; digits.add(temp); divisor = divisor /10; } // restore the number int result = 0; for (int i = 0; i < digits.size(); i++) { result *= 10; result += digits.get(i); } return result * sign; // if overflow then return 0 } public static int reverse2(int x) { int sign = x >= 0 ? 1 : -1; int divisor = Math.abs(x); int result = 0; while (divisor > 0) { int temp = divisor % 10; result = result * 10 + temp; if (result % 10 != temp) { return 0; } divisor = divisor /10; } return result * sign; } public static int reverse2_2(int x) { int result = 0; while (x != 0) { int temp = x % 10; int newResult = result * 10 + temp; if ((newResult - temp)/10 != result) { return 0; } result = newResult; x = x /10; } return result; } public static int reverse3(int x) { long rev= 0; while( x != 0){ rev= rev*10 + x % 10; x= x/10; if( rev > Integer.MAX_VALUE || rev < Integer.MIN_VALUE) return 0; } return (int) rev; } public static void main(String[] args) { // TODO code application logic here int test = -1999; test = reverse2_2(test); System.out.println(test); } }
1ca78b1a695fe83e405d0e778131f0b7acd593dc
[ "Java", "INI" ]
7
Java
sunwangshu/LeetCode_Java
177a852671b70f05b82a97774a5754719c727c31
2402a6cdf49cda5ffeaaed44f9664fbe86a09868
refs/heads/master
<repo_name>landersoft/mascotas<file_sep>/Mascotas/gatos/models.py from django.db import models # Create your models here. class Gato(models.Model): RAZAS = ( ('C', 'Callejero'), ('A', 'Angora'), ('S', 'Siames'), ) SEXO = ( ('F', 'Femenino'), ('M', 'Masculino'), ) nombre = models.CharField(max_length=100, blank=True, null=True) raza = models.CharField(max_length=50, blank=True, null=True, choices=RAZAS) nacimiento = models.DateField(blank=True, null=True) sexo = models.CharField(max_length=100, blank=True, null=True, choices=SEXO) def __str__(self): return self.nombre <file_sep>/Mascotas/gatos/migrations/0002_auto_20200409_0123.py # Generated by Django 3.0.5 on 2020-04-09 01:23 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('gatos', '0001_initial'), ] operations = [ migrations.AddField( model_name='gato', name='nacimiento', field=models.DateField(blank=True, null=True), ), migrations.AddField( model_name='gato', name='nombre', field=models.CharField(blank=True, max_length=100, null=True), ), migrations.AddField( model_name='gato', name='raza', field=models.CharField(blank=True, choices=[('C', 'Callejero'), ('A', 'Angora'), ('S', 'Siames')], max_length=50, null=True), ), migrations.AddField( model_name='gato', name='sexo', field=models.CharField(blank=True, choices=[('F', 'Femenino'), ('M', 'Masculino')], max_length=100, null=True), ), ] <file_sep>/Mascotas/gatos/views.py from django.shortcuts import render from rest_framework import viewsets from rest_framework import permissions from .serializers import GatoSerializer from .models import Gato from django.contrib.auth.decorators import login_required # Create your views here. class GatoViewSet(viewsets.ModelViewSet): queryset = Gato.objects.all().order_by('nombre') serializer_class = GatoSerializer @login_required def add(request): return render(request, 'index.html') <file_sep>/Mascotas/gatos/serializers.py from .models import Gato from rest_framework import serializers class GatoSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = Gato fields = ('id','nombre', 'raza', 'nacimiento', 'sexo') <file_sep>/Mascotas/gatos/urls.py from django.urls import include, path from rest_framework import routers from . import views router = routers.DefaultRouter() router.register(r'gatos', views.GatoViewSet) urlpatterns = [ path('', include(router.urls)), path('api-auth/', include('rest_framework.urls', namespace='rest_framework')), path('add/', views.add, name='add'), ] <file_sep>/Mascotas/gatos/admin.py from django.contrib import admin from .models import Gato class AdminGato(admin.ModelAdmin): list_display = ["id","nombre","raza","nacimiento","sexo"] list_filter = ["raza"] search_fields = ["nombre", "sexo"] # Register your models here. admin.site.register(Gato, AdminGato)
f5b211d24ce950d7e2941a573f28124c072e5248
[ "Python" ]
6
Python
landersoft/mascotas
ae48f5c02d981bf1ebfefafbd094b753c40b9dd1
afee009dc81c4f8044abfd1eaf9712acd7bb3ec1