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>extinct-mammals =============== Simple NodeJS/mongoDB API ##Objective This will help solidify your understanding of mongoDB alongside of NodeJS using a popular ORM for mongo called mongoose You'll build a public API of extinct mammals retrieved from Wikipedia: http://en.wikipedia.org/wiki/List_of_extinct_mammals ##Day One ###Step 1: Build your project * Create your package.json file with mongoose and express as dependencies * Make sure mongod is running in your terminal * Create a server.js file that will hold all of your API's logic * Be sure to require and initialize express ###Step 2: Setup the mongoDB connection (reference: http://mongoosejs.com/docs/) * In your server.js require the mongoose library and create a connection to your database server * Create your mammalSchema with three fields: `name`, `type`, and `year_extinct` * Use express to create two endpoints on `/`, one a GET and one a POST #### `GET /` * returns a JSON array of all extinct mammals, ordered by name #### `POST /` * saves a new Mammal model based on the fields given in the JSON request ###Step 3: Insert some data * Using your new API and the wikipedia article, add some extinct mammals: http://en.wikipedia.org/wiki/List_of_extinct_mammals ##Day Two ###Step 4: Break up your project into multiple modules * (You can use https://gist.github.com/fwielstra/1025038 as a good example) * Create an api.js to hold your `get` and `post` calls * Create a mammal.js that contains the schema and model creation for `Mammal` * Create an app.js file that brings everything together: * it should require the express and mongoose modules * it should instantiate express and connect to the mongo server * it should require the api module and connect the endoints to their appropriate functions in api.js * it should start the server listening on a desired port ###Step 5: Routing and fetching * Use a more complicated routing structure for your `GET /` call: * change the route to point to `/mammals` rather than just `/` * make it so that if someone requests `/mammals/marsupials` or `mammals/rodents` the call will return only mammals of that type * include an `order_by` query param that instructs the API to order the results by the given field ###Step 6 (Black Diamond): Query by id * Use regex to determine whether someone is asking for `/mammals/:id` or `/mammals/:type` and return the appropriate response ##Integration Tests with Jasmine ###Step 1: Create your spec file You can name it whatever you'd like, but since we're testing the API, let's call it test/spec/apispec.js ###Step 2: Make sure you have the correct setup * Make sure mongodb is running (either in another tab or via `mongod &`) * Make sure `node app.js` is running and has no problems * Make sure you're required the `request` lib in your spec * "Describe" your test case, maybe something like "tests the api" ###Step 3: Create a spec to make sure GET `/mammals` returns data * NOTE: make sure you have some data in your collection * Hint: Use the "toThrow" matcher in Jasmine to make sure try to parse JSON from the response body doesn't throw an error: ```javascript request("http://localhost:8888/mammals", function(err, response, body) { var checkJSON = function() { //if body isn't valid JSON, this will throw an error and break stuff JSON.parse(body); } expect(checkJSON).not.toThrow(); done(); }); ``` ###Step 4: Create specs to make sure both variations of `/mammals` work GET `/mammals` should work as well as `/mammals/marsupial` (or however you input the type) ###Step 5: Create a spec to ensure that POST `/mammals` works You're going to need to utilize the post method of the request library, like so: ```javascript request({ uri: url+"/mammals", method: 'POST', json: { "name": "<NAME>", "type": "test", "year_extinct": 2013 } }, function(err, response, body) { //code for assertion and done() here }); ``` <file_sep>var mongoose = require('mongoose'); var MammalSchema = new mongoose.Schema({ name: String, type: String, year_extinct: Number }); var Mammal = mongoose.model('Mammal', MammalSchema); module.exports = Mammal;<file_sep>var http = require('http'); var mongoose = require('mongoose'); var express = require('express'); var bodyParser = require('body-parser'); var app = express(); app.use(bodyParser.json()); app.use(bodyParser.urlencoded({ extended: true })); mongoose.connect('mongodb://localhost/test', function(err){ if(err) return console.error(err); console.log('connected'); }); var MammalSchema = new mongoose.Schema({ name: String, type: String, year_extinct: Number }); var Mammal = mongoose.model('Mammal', MammalSchema); app.get('/', function(req, res){ Mammal.find({},function (err, mammals) { if (err) return console.error(err); res.send(mammals) }) }) app.post('/', function(req, res){ var newMammal = new Mammal(req.body); newMammal.save() res.send("Worked"); }) var server = app.listen(8989, function(){ console.log("Listening on port %d", server.address().port); })
5b0d294740a1067401a1b5d0ce0228b6a8288a05
[ "Markdown", "JavaScript" ]
3
Markdown
Houwarnick/Extinct_Mammals
22acb8708493a98da5d4caca8e7ef9ba2f6fba46
9bb2fbc98f8943dff336d9980e60e70925accbf0
refs/heads/master
<file_sep>package com.varano.information.constants; import java.io.Serializable; import java.time.DayOfWeek; import com.varano.information.ClassPeriod; import com.varano.managers.Agenda; //<NAME> //[Program Descripion] //Sep 3, 2017 public enum Lab implements Serializable { LAB4 (DayOfWeek.MONDAY, Rotation.R1, 4, "Monday Half 1"), LAB5 (DayOfWeek.MONDAY, Rotation.R1, 5, "Monday Half 2"), LAB1 (DayOfWeek.TUESDAY, Rotation.ODD_BLOCK, 1, "Tuesday Half 1"), LAB3 (DayOfWeek.THURSDAY, Rotation.R4, 3, "Thursday Half 1"), LAB7 (DayOfWeek.THURSDAY, Rotation.R4, 7, "Thursday Half 2"), LAB2 (DayOfWeek.FRIDAY, Rotation.R3, 2, "Friday Half 1"), LAB6 (DayOfWeek.FRIDAY, Rotation.R3, 6, "Friday Half 2"), LAB0 (DayOfWeek.WEDNESDAY, Rotation.EVEN_BLOCK, 0, "Pascack Period (With Lab)"), LAB8 (DayOfWeek.WEDNESDAY, Rotation.EVEN_BLOCK, 8, "Pascack Period (With Lab)"); public static final boolean HALF_1 = true, HALF_2 = false; private final DayOfWeek day; private final Rotation rotation; private ClassPeriod.LabPeriod timeAtLab; private final int classSlot; private final boolean firstHalfLunch; private final String slotDescription; private final Waiter wait; private boolean completed; private Lab(DayOfWeek day, Rotation rotation, int classSlot, String slotDescription) { this.day = day; this.rotation = rotation; this.classSlot = classSlot; this.slotDescription = slotDescription; completed = false; wait = new Waiter(); firstHalfLunch = (classSlot < 5) ? HALF_1 : HALF_2; new Initializer().start(); } Waiter getWaiter() { return wait; } private void init() { Agenda.log(name() + " begun initialization"); boolean isPascack = (classSlot == 0 || classSlot == 8); String clName = (isPascack) ? "Pascack Period (Lab)" : "LAB"; timeAtLab = (isPascack) ? new ClassPeriod.LabPeriod(classSlot, clName, RotationConstants.getPascack().getStartTime(), RotationConstants.getPascack().getEndTime(), this) : (firstHalfLunch) ? new ClassPeriod.LabPeriod(classSlot, clName, rotation.getTimes()[rotation.getLunchSlot()] .getStartTime(), rotation.getLabSwitch(), this) : new ClassPeriod.LabPeriod(classSlot, clName, rotation.getLabSwitch(), rotation.getTimes()[rotation.getLunchSlot()] .getEndTime(), this); completed = true; if (allCompleted()) { System.out.println("LABS COMPLETED "); } } private synchronized boolean allCompleted() { for (Lab l : values()) { if (!l.completed) return false; } return true; } /* private void notifyMain() { synchronized(DisplayMain.waiter) { DisplayMain.waiter.notify(); } } */ class Waiter{} private static byte labCount = 0; private class Initializer extends Thread { public Initializer() { super("lab-init-"+labCount++); } public void run() { synchronized(wait) { try { wait.wait(); } catch (InterruptedException e) { e.printStackTrace(); } } init(); } } public static int toInt(Lab lab) { for (int i = 0; i < Lab.values().length; i++) if (Lab.values()[i].equals(lab)) return i; return -1; } public static Lab toLabFromClassSlot(int i) { for (Lab l : values()) { if (l.getClassSlot() == i) return l; } return null; } public static Lab toLab(int i) { return Lab.values()[i]; } public DayOfWeek getDay() { return day; } public Rotation getRotation() { return rotation; } public ClassPeriod getTimeAtLab() { return timeAtLab; } public int getClassSlot() { return classSlot; } public boolean getSideOfLunch() { return firstHalfLunch; } public String getSlotDescription() { return slotDescription; } public void setClassPreferences(ClassPeriod c) { timeAtLab.setRoomNumber(c.getRoomNumber()); timeAtLab.setTeacher(c.getTeacher()); } } <file_sep>package com.varano.resources.ioFunctions; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.ObjectOutputStream; import com.varano.information.Schedule; import com.varano.information.constants.ErrorID; //<NAME> //[Program Descripion] //Oct 19, 2017 public class SchedWriter { private ObjectOutputStream outStream; private FileOutputStream fileStream; private boolean debug; public SchedWriter(String route) { init(route); } public SchedWriter() { this(com.varano.managers.FileHandler.SCHED_ROUTE); } private void init(String route) { fileStream = null; try { fileStream = new FileOutputStream(route); } catch (FileNotFoundException e) { ErrorID.showError(e, false); } try { outStream = new ObjectOutputStream(fileStream); } catch (IOException e) { ErrorID.showError(e, false); } } public void write(Schedule s) { if (s == null) { if (debug) System.err.println("written schedule is null"); ErrorID.showError(new NullPointerException(), false); return; } try { outStream.writeObject(s); } catch (IOException e) { ErrorID.showError(e, false); } close(); } public void close() { try { fileStream.flush(); fileStream.close(); outStream.flush(); outStream.close(); } catch (IOException e) { ErrorID.showError(e, true); } } }<file_sep>//<NAME> //Mar 7, 2018 package com.varano.ui; import java.awt.Color; /** * Has all the functionality of the {@linkplain Color} class but is mutable, * so values can be changed and updated as they are changed. This is especially useful for updating GUIs, because references do * not change when the value is changed, so new colors do not need to be set (foreground, background, etc.) * @author <NAME> */ public class MutableColor extends java.awt.Color implements java.io.Serializable { private static final long serialVersionUID = 8016610396226834080L; private int argb; public MutableColor() { this(Color.WHITE); } public MutableColor(int r, int g, int b, int a) { super(r, g, b, a); argb = super.getRGB(); } public MutableColor(int r, int g, int b) { this(r, g, b, 255); } public MutableColor(Color c) { this(c.getRGB()); } public MutableColor(int value) { super(value); argb = value; } @Override public int getRGB() { return argb; } public void setValue(Color c) { setValue(c.getRGB()); } public void setValue(int r, int g, int b) { setValue(r, g, b, getAlpha()); } public void setValue(int r, int g, int b, int a) { argb = ((a & 0xFF) << 24) | ((r & 0xFF) << 16) | ((g & 0xFF) << 8) | ((b & 0xFF) << 0); } public void setValue(int value) { argb = value; } public void setAlpha(int a) { setValue(getRed(), getGreen(), getBlue(), a); } public void setRed(int r) { setValue(r, getGreen(), getBlue(), getAlpha()); } public void setBlue(int b) { setValue(getRed(), getGreen(), b, getAlpha()); } public void setGreen(int g) { setValue(getRed(), g, getBlue(), getAlpha()); } } <file_sep>package com.varano.ui.tools; import java.awt.Cursor; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import javax.swing.DefaultComboBoxModel; import javax.swing.JButton; import javax.swing.JComboBox; import com.varano.ui.UIHandler; import com.varano.ui.input.InputManager; //<NAME> //[Program Descripion] //Sep 25, 2017 public class AddButton extends JButton implements ActionListener { private static final long serialVersionUID = 1L; private int slot; private InputManager parentPanel; public AddButton(int slot, InputManager parentPanel) { super((slot == -1) ? "Add New Class" : "Add "+slot+" Period"); setBorderPainted(false); setFocusable(false); setOpaque(false); setFont(UIHandler.getButtonFont()); setForeground(UIHandler.foreground); setCursor(new Cursor(Cursor.HAND_CURSOR)); setSlot(slot); addActionListener(this); addMouseListener(UIHandler.buttonPaintListener(this)); if (parentPanel instanceof InputManager) { setParentPanel(parentPanel); } } public int getSlot() { return slot; } public void setSlot(int slot) { this.slot = slot; } public InputManager getParentPanel() { return parentPanel; } public void setParentPanel(InputManager parentPanel) { this.parentPanel = parentPanel; } @Override public void actionPerformed(ActionEvent e) { if (slot == -1) parentPanel.addCustomClass(); else parentPanel.addClass(slot); } //If you want a menu... public static class Menu extends JComboBox<String> implements ActionListener { private static final long serialVersionUID = 1L; private InputManager parentPanel; public Menu(InputManager parentPanel, int amtClasses) { super(); addActionListener(this); setCursor(new Cursor(Cursor.HAND_CURSOR)); setEditable(false); String[] classes = new String[3]; classes[0] = "Add Class At:"; classes[1] = ""+0; classes[2] = ""+8; setModel(new DefaultComboBoxModel<String>(classes)); setParentPanel( parentPanel); } public InputManager getParentPanel() { return parentPanel; } public void setParentPanel(InputManager parentPanel) { this.parentPanel = parentPanel; } @Override public void actionPerformed(ActionEvent e) { @SuppressWarnings("unchecked") JComboBox<String> c = (JComboBox<String>) e.getSource(); if (c.getSelectedIndex() != 0) parentPanel.addClass(Integer.parseInt((String) c.getSelectedItem())); } } }<file_sep>package com.varano.ui.input; import java.awt.Container; import java.awt.Dimension; import java.awt.FlowLayout; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.FocusEvent; import java.awt.event.FocusListener; import java.awt.event.KeyEvent; import java.awt.event.KeyListener; import javax.swing.AbstractButton; import javax.swing.JButton; import javax.swing.JCheckBox; import javax.swing.JComponent; import javax.swing.JLabel; import javax.swing.JOptionPane; import javax.swing.JPanel; import javax.swing.JTextField; import com.varano.information.ClassPeriod; import com.varano.information.constants.RotationConstants; import com.varano.managers.Agenda; import com.varano.ui.UIHandler; //<NAME> //[Program Descripion] //Sep 20, 2017 public class DataInputSlot extends JPanel implements ActionListener { private static final long serialVersionUID = 1L; private static final int WIDTH = 615; private static final Dimension NAME_SIZE = new Dimension(115, UIHandler.FIELD_HEIGHT); private static final Dimension TEACH_SIZE = new Dimension(135, UIHandler.FIELD_HEIGHT); private static final Dimension ROOM_SIZE = new Dimension(53, UIHandler.FIELD_HEIGHT); private int slotNumber; private String beginName; private Container parentPanel; private JCheckBox labBox; private String nameContent; private ClassPeriod dataHolder; private boolean hasParent, hasLab, removable, labFriendly; private JTextField[] promptFields; private static boolean debug; public DataInputSlot(int slotNumber, Container parentPanel) { this (new ClassPeriod(slotNumber), parentPanel); if (debug) System.out.println("input slot "+slotNumber+" initialized empty"); } public DataInputSlot(ClassPeriod c, Container parentPanel) { if (c == null) c = new ClassPeriod(); debug = false; dataHolder = c.clone(); beginName = c.getName(); if (debug) System.out.println("input 56 dataholder\n"+dataHolder.getInfo()); setFont(UIHandler.getInputLabelFont()); if (parentPanel != null) { setBackground(UIHandler.background); setForeground(UIHandler.foreground); } setName(c.getSlot() + "input slot"); setSlotNumber(c.getSlot()); hasLab = false; removable = ((slotNumber == 0 || slotNumber == 8) && parentPanel != null); if (parentPanel instanceof DataInput) { this.parentPanel = (DataInput)parentPanel; hasParent = true; } else this.parentPanel = parentPanel; labFriendly = true; int amtFields = 3; promptFields = new JTextField[amtFields]; addComponents(c); } public Dimension getPreferredSize() { return new Dimension(Agenda.PREF_W-100, 30); } public static ClassPeriod showInputSlot() { DataInputSlot in = new DataInputSlot(RotationConstants.NO_SLOT, null); in.setLabFriendly(false); if (JOptionPane.showOptionDialog(null, in, "Create New Class", JOptionPane.OK_CANCEL_OPTION, JOptionPane.INFORMATION_MESSAGE, null, null, null) == 0) return in.createClass(); if (debug) System.out.println("returning null"); return null; } private void addComponents(ClassPeriod c) { int index = 0; ((FlowLayout)getLayout()).setAlignment(FlowLayout.LEFT); //label for the class slot JLabel labelLeft = new JLabel((slotNumber == RotationConstants.PASCACK) ? "P-" : slotNumber+"-"); if (c.getSlot() == RotationConstants.NO_SLOT) labelLeft.setText(""); labelLeft.setFont(getFont()); labelLeft.setForeground(getForeground()); add(labelLeft); JLabel currentLabel = new JLabel("Class Name:"); // class name prompt addLabel(currentLabel, labelLeft); JTextField currentField = new JTextField(c.getName()); //class name field nameContent = currentField.getText().toLowerCase(); //checking the science requirement currentField.addKeyListener(new KeyListener() { @Override public void keyPressed(KeyEvent arg0) {} @Override public void keyReleased(KeyEvent arg0) { checkScience(); } @Override public void keyTyped(KeyEvent arg0) {} }); addField(currentField, currentLabel, index); index++; currentLabel = new JLabel("Teacher:"); //teacher prompt addLabel(currentLabel, currentField); currentField = new JTextField(c.getTeacher()); //teacher field addField(currentField, currentLabel, index); index++; currentLabel = new JLabel("Room:"); // rm number prompt addLabel(currentLabel, currentField); currentField = new JTextField(c.getRoomNumber()); //rm number field addField(currentField, currentLabel, index); labBox = new JCheckBox("Has Lab"); // check box to see if you have lab in that class labBox.setActionCommand("lab"); labBox.addActionListener(this); labBox.setFont(getFont()); labBox.setOpaque(false); labBox.setForeground(getForeground()); labBox.setBackground(getBackground()); if (labFriendly) { add(labBox); } if (debug) System.out.println("slot "+slotNumber+"componentSize:"+getComponents().length); if (removable) { JButton remove = new JButton("Remove"); //button to remove remove.setFont(UIHandler.getButtonFont()); remove.setActionCommand("remove"); remove.addActionListener(this); add(remove); } } private void addField(JTextField f, JComponent c, int index) { final int name = 0, teacher = 1; f.setMinimumSize((index == name) ? NAME_SIZE : (index == teacher) ? TEACH_SIZE : ROOM_SIZE); f.setMaximumSize((index == name) ? NAME_SIZE : (index == teacher) ? TEACH_SIZE : ROOM_SIZE); f.setPreferredSize((index == name) ? NAME_SIZE : (index == teacher) ? TEACH_SIZE : ROOM_SIZE); f.setFont(UIHandler.getInputFieldFont()); add(f); //set the tooltip to the f.setToolTipText(f.getText()); f.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { setToolTipField((JTextField) e.getSource()); } private void setToolTipField(JTextField f) { f.setToolTipText(f.getText()); } }); f.addFocusListener(new FocusListener() { @Override public void focusGained(FocusEvent e) {} @Override public void focusLost(FocusEvent e) { setToolTipField((JTextField)e.getSource()); f.revalidate(); } private void setToolTipField(JTextField f) { f.setToolTipText(f.getText()); } }); promptFields[index] = f; } private void addLabel(JLabel f, JComponent c) { f.setFont(getFont()); f.setForeground(getForeground()); add(f); } public void forceNames() { for (JTextField f : promptFields) if (f.getText().equals("")) f.setText("unspecified"); } private void checkScience() { String text = promptFields[0].getText().toLowerCase(); String[] sciences = {"chem", "science", "bio", "physics"}; for (String s : sciences) { if (text.contains(s)) { if (!nameContent.contains(s) && nameContent.toLowerCase().contains("computer")) labBox.setSelected(true); } else if (nameContent.contains(s)) labBox.setSelected(false); } nameContent = text; } private void checkHonorsText() { String text = promptFields[0].getText().toLowerCase(); if (text.equalsIgnoreCase(beginName)) return; if (debug) System.out.println(text); if (text.contains("honors") || text.contains("ap")) dataHolder.setHonors(true); } public ClassPeriod createClass() { forceNames(); checkHonorsText(); if (hasParent) { if (hasLab) { ((DataInput) parentPanel).addLab(slotNumber); if (debug) System.out.println("\tslot" + slotNumber + "Added lab"); } else { ((DataInput) parentPanel).removeLab(slotNumber); } } ClassPeriod retval = new ClassPeriod(slotNumber, promptFields[0].getText(), promptFields[1].getText(), promptFields[2].getText()); retval.setBackgroundData(dataHolder); if (debug) System.out.println("created:" + retval.getInfo()); return retval; } public void setLab(boolean hasLab) { labBox.setSelected(hasLab); this.hasLab = hasLab; } public String toString() { return getClass().getName()+"[slot="+slotNumber+", lab="+hasLab+"]"; } public int getSlotNumber() { return slotNumber; } public void setSlotNumber(int slotNumber) { this.slotNumber = slotNumber; } public boolean isRemovable() { return removable; } public void setRemovable(boolean removable) { this.removable = removable; } public boolean needsScroll() { return WIDTH > parentPanel.getWidth(); } public JTextField[] getPromptFields() { return promptFields; } public boolean isLabFriendly() { return labFriendly; } public void setLabFriendly(boolean b) { labFriendly = b; if (!labFriendly) remove(labBox); } @Override public void actionPerformed(ActionEvent e) { if (e.getSource() instanceof AbstractButton) { AbstractButton b = (AbstractButton) e.getSource(); if (b.getActionCommand().equals("remove")) { if (hasParent) ((DataInput) parentPanel).removeClassAndReOrder(slotNumber, this); else parentPanel.remove(this); } else if (b.getActionCommand().equals("lab")) { hasLab = !hasLab; if (debug) System.out.println(slotNumber+" has lab"); } if (debug) System.out.println("unassigned action for "+e.getSource()); } parentPanel.repaint(); } } <file_sep># Agenda A scheduler program for Pascack Hills and Valley. Using the rotating schedule, the user will be able to determine where they should be in school, how much time is left in their current activity, and their schedule for the day. They can take notes and keep their assignments in order for each class. They can also determine their GPA and customize their schedule. The program is custom to Pascack Hills and Valley, but can be modulated to work with other districts.<file_sep>//<NAME> //[Program Descripion] //Dec 21, 2017 package com.varano.ui.input; import com.varano.information.ClassPeriod; /** * Specifies an input manager, necessarily adding methods that are needed for each of them. * they may not all be completely implemented in both classes, but they are necessary for work between panels * * @author <NAME> * */ public interface InputManager { void addCustomClass(); void addClass(int index); void addClass(ClassPeriod c); void save(); void closeToDisp(); boolean isSaved(); } <file_sep> /** * all classes for display * * @author <NAME> * */ package com.varano.ui;<file_sep> /** * main package * * @author <NAME> * */ package com.varano;<file_sep>//<NAME> //[Program Descripion] //Jan 26, 2018 package com.varano.resources.ioFunctions.calendar; import java.time.LocalDate; import java.util.ArrayList; public class VCalendar { private ArrayList<VEvent> events; private VCalendar() { events = new ArrayList<VEvent>(); } private VCalendar(ArrayList<VEvent> events) { this.events = events; } public static VCalendar build(ArrayList<VEvent> events) { return new VCalendar(events); } public static VCalendar test() { ArrayList<VEvent> v = new ArrayList<VEvent>(); for (char i = 'A'; i < 'z'; i++) v.add(new VEvent(i + "")); return new VCalendar(v); } public ArrayList<VEvent> events() { return events; } public ArrayList<VEvent> eventsToday() { ArrayList<VEvent> ret = new ArrayList<VEvent>(); for (VEvent e : events) if (e.contains(LocalDate.now())) ret.add(e); return ret; } public String toString() { return getClass().getName() + "["+events.toString() + "]"; } } <file_sep>//<NAME> //Sep 4, 2018 package com.varano.resources.ioFunctions.email; import com.varano.managers.FileHandler; public class ErrorReport { public static void sendError(String msg, Throwable e) { new Thread(new Sender(msg, e)).run(); } private static class Sender implements Runnable { private String msg; private Throwable e; public Sender(String msg, Throwable e) { this.msg = msg; this.e = e; } public void sendError() { if (!EmailHandler.connect()) return; String completeMessage = ""; completeMessage += java.time.LocalTime.now() + ", " + java.time.LocalDate.now() + "\n\nUser: " + System.getProperty("user.name") + "\nMessage: "; completeMessage += (msg == null || msg.equals("")) ? "null" : msg; completeMessage += "\n\n"; completeMessage += "Exception: " + e.getClass().getName() + " - "+ e.getMessage(); EmailHandler.send("AGENDA ERROR", completeMessage, FileHandler.LOG_ROUTE); } @Override public void run() { sendError(); } } } <file_sep>package com.varano.ui.display.selection; import java.awt.Dimension; import javax.swing.JTextPane; import javax.swing.text.BadLocationException; import javax.swing.text.Style; import javax.swing.text.StyleConstants; import javax.swing.text.StyleContext; import javax.swing.text.StyledDocument; import com.varano.information.ClassPeriod; import com.varano.managers.Agenda; import com.varano.ui.UIHandler; //<NAME> //[Program Descripion] //Sep 10, 2017 public class ClassInfoPane extends JTextPane { private static final long serialVersionUID = 1L; private ClassPeriod c; private boolean thinConstraints, debug, showNames; public ClassInfoPane(ClassPeriod c) { super(); debug = false; setBackground(UIHandler.quaternary); setForeground(UIHandler.foreground); setName("unNamedInfoPane"); this.setEditable(false); this.setClassPeriod(c); this.setMinimumSize(new Dimension(60,60)); initStyles(); } private void createClassDetailPane() { if (debug) System.out.println(getName() + "Parent"+getParent()); this.setText(""); if (c == null) { putStyles(new String[] {"Class Not Selected"}, new String[] {"regular"}); return; } String newLine = "\n"; String tab = (thinConstraints) ?" ":""; if (debug) System.out.println(c); String hour = (c.getDuration().getHour24() > 0) ? c.getDuration().getHour24()+" hour, " : ""; String teacher = (thinConstraints) ? "Teacher: " + c.getTrimmedTeacher() + newLine : "Teacher: " + c.getTrimmedTeacher() + newLine; String classLength = (thinConstraints) ? "Class Length:"+ newLine +hour+c.getDuration().getMinute()+" minutes" : "Class Length: "+hour+c.getDuration().getMinute()+" minutes"; String times = c.getStartTime() + " - " + c.getEndTime(); if (showNames) { String[] uneditedText = { tab + "Rm. " + c.getTrimmedRoomNumber()+newLine, tab + teacher, tab + times +newLine, tab + classLength }; String[] styles = { "regular", "regular", "bold", "italic" }; putStyles(uneditedText, styles); } else { String[] uneditedText = { tab + times + newLine, tab + classLength }; String[] styles = { "bold", "italic" }; putStyles(uneditedText, styles); } } private void putStyles(String[] uneditedText, String[] styles) { StyledDocument styleDoc = getStyledDocument(); try { for (int i=0; i < uneditedText.length; i++) { styleDoc.insertString(styleDoc.getLength(), uneditedText[i], styleDoc.getStyle(styles[i])); } } catch (BadLocationException e) { Agenda.logError("cannot insert styles in infoPane", e); } } private void initStyles() { StyledDocument doc = getStyledDocument(); Style def = StyleContext.getDefaultStyleContext(). getStyle(StyleContext.DEFAULT_STYLE); Style regular = doc.addStyle("regular", def); StyleConstants.setBold(regular, false); StyleConstants.setFontFamily(regular, UIHandler.font.getFamily()); StyleConstants.setFontSize(regular, 14); Style s = doc.addStyle("italic", regular); StyleConstants.setItalic(s, true); s = doc.addStyle("bold", regular); StyleConstants.setBold(s, true); } public ClassPeriod getClassPeriod() { return c; } public void setClassPeriod(ClassPeriod c) { this.c = c; createClassDetailPane(); } public boolean isThinConstraints() { return thinConstraints; } public void setThinConstraints(boolean thinConstraints) { this.thinConstraints = thinConstraints; } public void setShowNames(boolean showNames) { this.showNames = showNames; } public boolean getShowNames() { return showNames; } } <file_sep>//<NAME> //[Program Descripion] //Nov 28, 2017 package com.varano.resources; import java.io.IOException; import java.io.InputStream; import java.net.URL; import javax.swing.ImageIcon; import com.varano.information.constants.ErrorID; public final class ResourceAccess { public static InputStream getResourceStream(String localPath) { return ResourceAccess.class.getResourceAsStream(localPath); } public static URL getResource(String localPath) { return ResourceAccess.class.getResource(localPath); } public static ImageIcon getIcon(String localPath) { try { return new ImageIcon(ResourceAccess.class.getResource(localPath)); } catch (NullPointerException e) { ErrorID.showError(e, true); return null; } } public static String readHtml(URL site) throws IOException { java.io.BufferedReader in = null; in = new java.io.BufferedReader(new java.io.InputStreamReader(site.openStream())); java.lang.StringBuilder b = new java.lang.StringBuilder(); String inputLine; while ((inputLine = in.readLine()) != null) { b.append(inputLine); b.append("\n"); } in.close(); return b.toString(); } } <file_sep>//<NAME> //Dec 18, 2017 package com.varano.ui.input; import java.awt.BorderLayout; import java.awt.Cursor; import java.awt.FlowLayout; import java.awt.GridLayout; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.util.ArrayList; import javax.swing.BorderFactory; import javax.swing.BoxLayout; import javax.swing.DefaultListModel; import javax.swing.JButton; import javax.swing.JLabel; import javax.swing.JList; import javax.swing.JOptionPane; import javax.swing.JPanel; import javax.swing.JScrollPane; import com.varano.information.ClassPeriod; import com.varano.information.Schedule; import com.varano.information.constants.ErrorID; import com.varano.information.constants.Lab; import com.varano.information.constants.RotationConstants; import com.varano.managers.Agenda; import com.varano.managers.PanelManager; import com.varano.ui.PanelView; import com.varano.ui.UIHandler; import com.varano.ui.display.selection.ScheduleList; import com.varano.ui.tools.ToolBar; /* * TODO * removing classes DONE * adding back from your regular schedule DONE * joption pane "add from your schedule or create new class" * ensuring the ease for lab switches DONE * question icon DONE * writing and reordering classes DONE * * */ /** * Central panel for allowing the user to integrate their GPA into the program. * <p> * <strong>NOTE this does not affect the classes in the display, just for the gpa. </strong> * * it uses the {@link Schedule} gpa classes arrayList to produce a separate list of classes. * * @author <NAME> * */ public class GPAInput extends JPanel implements InputManager, PanelView { private static final long serialVersionUID = 1L; private Schedule sched; private JPanel center; private boolean hasZero, saved; private ArrayList<GPAInputSlot> slots; private PanelManager manager; private JLabel weightLabel, unWeightLabel; private static final String weightedPrefix = "Weighted GPA: "; private static final String unWeightedPrefix = "UnWeighted GPA: "; public static final String[] letterGrades = {"A+", "A", "A-", "B+", "B", "B-", "C+", "C", "C-", "D+", "D", "D-", "F"}; public static final double[] gradePoints = {4.33, 4, 3.67, 3.33, 3, 2.67, 2.33, 2, 1.67, 1.33, 1}; public static final double[] unWeightedGradePoints = {4, 4, 3.67, 3.33, 3, 2.67, 2.33, 2, 1.67, 1.33, 1}; public static boolean show = false; private boolean debug, error; public GPAInput(Schedule sched, PanelManager manager) { super(); this.manager = manager; this.sched = sched; setFont(UIHandler.font); if (sched != null) init(sched); else init(0); Agenda.log("gpa constructed with schedule"); } public GPAInput(int amtClasses, PanelManager manager) { this.manager = manager; setFont(UIHandler.font); init(amtClasses); Agenda.log("gpa constructed empty"); } public GPAInput(PanelManager manager) { this(0, manager); } public Agenda getMain() { return manager.getMain(); } private void init0() { removeAll(); debug = false; center = new JPanel(); center.setBackground(UIHandler.background); center.setLayout(new BoxLayout(center, BoxLayout.Y_AXIS)); center.add(averageDisplay()); setLayout(new BorderLayout()); slots = new ArrayList<GPAInputSlot>(); initComponents(); } private void initComponents() { ToolBar bar = new ToolBar(PanelManager.GPA, this); add(bar, BorderLayout.NORTH); add(new JScrollPane(center), BorderLayout.CENTER); add(createBottomPanel(), BorderLayout.SOUTH); } private void init(Schedule s) { Agenda.log("gpa init with "+s.getName()); init0(); initAndAddSlots(s); } private void init(int amtClasses) { init0(); initAndAddSlots(amtClasses); } private void initAndAddSlots(Schedule sched) { hasZero = sched.hasZeroPeriod(); //ensure classes with lab are marked correctly for (Lab l : sched.getLabs()) sched.get(l.getClassSlot()).setCourseWeight(ClassPeriod.FULL_LAB); for (int i = 0; i < sched.getGpaClasses().size(); i++) { addSlot(sched.getGpaClasses().get(i), sched.hasZeroPeriod()); } } private void initAndAddSlots(int amtClasses) { hasZero = false; for (int i = 1; i <= amtClasses; i++) addSlot(new ClassPeriod(i), hasZero); } @Override public void addClass(int index) { if (debug) System.out.println("class added at "+index); addClass(new ClassPeriod(index)); } @Override public void addClass(ClassPeriod c) { if (debug) System.out.println("class added: "+c); if (c == null) return; sched.addGPAClass(c); addSlot(c, hasZero); } @Override public void addCustomClass() { int choice = 0; choice = JOptionPane.showOptionDialog(null, "Do you want to\nchoose a class from your schedule\nor create a new class?", "Add a GPA Class", JOptionPane.YES_NO_CANCEL_OPTION, JOptionPane.QUESTION_MESSAGE, null, new String[] {"Cancel", "Create", "Choose"} , "Cancel"); if (choice == 0) return; if (choice == 1) { addClass(DataInputSlot.showInputSlot()); } else addClass(chooseClass()); } private ClassPeriod chooseClass() { ArrayList<ClassPeriod> unSignedClasses = new ArrayList<ClassPeriod>(); for (int i = 0; i < sched.getClasses().length; i++) { ClassPeriod c = sched.getClasses()[i]; if (isApplicable(c) && !gpaContains(c)) unSignedClasses.add(sched.getClasses()[i]); } if (unSignedClasses.isEmpty()) { JOptionPane.showMessageDialog(null, "There are no unused\n" + "classes in your schedule.", "Select a Class", JOptionPane.QUESTION_MESSAGE, null); return null; } ScheduleList sl = new ScheduleList( new Schedule(unSignedClasses.toArray(new ClassPeriod[unSignedClasses.size()])), true); sl.setBorder(UIHandler.getTitledBorder("Select...")); JOptionPane.showMessageDialog(null, sl, "Select a Class", JOptionPane.QUESTION_MESSAGE, null); return sl.getSelectedValue(); } private boolean gpaContains(ClassPeriod c) { for (int j = 0; j < sched.getGpaClasses().size(); j++) if (sched.getGpaClasses().get(j).equals(c)) return true; return false; } private static boolean isApplicable(ClassPeriod c) { int sl = c.getSlot(); return sl != RotationConstants.LUNCH && sl != RotationConstants.PASCACK && sl != RotationConstants.PASCACK_STUDY; } private void addSlot(ClassPeriod c, boolean hasZero) { if (debug) System.out.println("adding"+ c.getInfo()); GPAInputSlot add = new GPAInputSlot(c, this); center.add(add); slots.add(add); revalidate(); } private JPanel averageDisplay() { JPanel p = new JPanel(); p.setBackground(UIHandler.background); ((FlowLayout) p.getLayout()).setAlignment(FlowLayout.RIGHT); final int gap = 5; weightLabel = new JLabel(weightedPrefix + "--"); weightLabel.setForeground(UIHandler.foreground); weightLabel.setFont(UIHandler.getInputLabelFont()); weightLabel.setBorder(BorderFactory.createEmptyBorder(gap,0,0,gap)); p.add(weightLabel); unWeightLabel = new JLabel(unWeightedPrefix + "--"); unWeightLabel.setForeground(UIHandler.foreground); unWeightLabel.setFont(UIHandler.getInputLabelFont()); unWeightLabel.setBorder(BorderFactory.createEmptyBorder(gap,0,0,gap)); p.add(unWeightLabel); return p; } private JPanel createBottomPanel() { JPanel p = new JPanel(); p.setBackground(UIHandler.secondary); p.setLayout(new GridLayout(1,2)); Cursor hand = new Cursor(Cursor.HAND_CURSOR); JButton button = new JButton("Save and Close"); button.setFont(UIHandler.getButtonFont()); button.setCursor(hand); button.setToolTipText("Exit and Save"); button.addActionListener(changeView(PanelManager.DISPLAY)); p.add(button); button = new JButton("Refresh GPA"); button.setToolTipText("See your new GPA"); button.setSelected(true); button.setFont(UIHandler.getButtonFont()); button.setCursor(hand); button.addActionListener(refreshListener()); p.add(button); return p; } private ActionListener refreshListener() { return new ActionListener() { @Override public void actionPerformed(ActionEvent arg0) { refreshGPA(); } }; } public void refreshGPA() { save(); double gpa = calculateWeightedGPA(); double unw = (gpa == -1) ? -1 : calculateUnWeightedGPA(); if (gpa == -1 || unw == -1) return; weightLabel.setText(weightedPrefix + gpa); unWeightLabel.setText(unWeightedPrefix + unw); } public ActionListener changeView(int type) { if (manager != null) return manager.changeViewListener(type); return new ActionListener() { @Override public void actionPerformed(ActionEvent arg0) { if (debug) System.out.println("CHANGED TO "+ type); } }; } public boolean checkAndSetError() { for (GPAInputSlot s : slots) { if (!s.canCreate()) { error = true; return error; } } error = false; return error; } public void save() { if (debug) System.out.println("GPA 272 gpa = " + sched.getGpaClasses().toString()); if (checkAndSetError()) { ErrorID.showUserError(ErrorID.INPUT_ERROR); return; } for (GPAInputSlot s : slots) { s.save(); if (sched.get(s.getSlot()) != null) sched.get(s.getSlot()).setHonors(s.isHonors()); } setSaved(true); if (manager != null) manager.saveSchedule(sched, getClass()); Agenda.log("gpa successfully saved"); } public void closeToDisp() { if (manager != null) { save(); manager.setCurrentPane(PanelManager.DISPLAY); } } public double calculateUnWeightedGPA() { double sum = 0; for (GPAInputSlot g : slots) { if (!g.canCreate()) { if (debug) System.out.println(g); ErrorID.showUserError(ErrorID.INPUT_ERROR); return -1; } sum += g.getUnweightedGradePoint(); } return (int) (sum / slots.size() * 10_000) / 10_000.0; } public double calculateWeightedGPA() { if (error) return -1; double sumWeights = 0; double sumCredits = 0; for (GPAInputSlot g : slots) { if (!g.canCreate()) { if (debug) System.out.println(g); ErrorID.showUserError(ErrorID.INPUT_ERROR); return -1; } sumWeights += g.getWeight(); sumCredits += g.finish(); } return (int) (sumCredits / sumWeights * 10_000) / 10_000.0; } public void setMethod(boolean numbers) { for (GPAInputSlot in : slots) { if (numbers == false) in.save(); else in.saveWeight(); in.setUseNumbers(numbers); } revalidate(); } public void removeSlot(GPAInputSlot slot) { sched.removeGPAClass(slot.getClassPeriod()); slots.remove(slot); center.remove(slot); revalidate(); } public void moveSlot(GPAInputSlot slot) { int newIndex = -1; JList<String> spaces = new JList<String>(); spaces.setBorder(UIHandler.getTitledBorder("Put "+slot.toString() + " after...")); DefaultListModel<String> dlm = new DefaultListModel<String>(); spaces.setModel(dlm); dlm.addElement("<Put First>"); for (GPAInputSlot in : slots) dlm.addElement(in.toString()); if (JOptionPane.showConfirmDialog(null, spaces, "Move Slot", JOptionPane.OK_CANCEL_OPTION, JOptionPane.QUESTION_MESSAGE, null) == 1) return; newIndex = spaces.getSelectedIndex(); if (newIndex < 0) return; removeSlot(slot); if (newIndex >= slots.size()) { center.add(slot); sched.addGPAClass(slot.getClassPeriod()); slots.add(slot); } else { sched.addGPAClass(slot.getClassPeriod(), newIndex); slots.add(newIndex, slot); center.add(slot, newIndex+1); } revalidate(); } public void setSchedule(Schedule s) { this.sched = s; init(s); } @Override public void open() { setSchedule(manager.getMainSched()); } @Override public void close() { save(); } public boolean isSaved() { return saved; } public void setSaved(boolean saved) { this.saved = saved; if (debug) System.out.println("gpa 389 SAVED = "+saved); } @Override public void refresh() { open(); } } <file_sep>//<NAME> //[Program Descripion] //Jan 26, 2018 package com.varano.resources.ioFunctions.calendar; import java.time.LocalDate; public class VEvent { private LocalDate start, end; private String summary, detail; public VEvent(String summary, LocalDate start, LocalDate end) { setSummary(summary); setStart(start); setEnd(end); } public VEvent(String summary) { this(summary, LocalDate.MIN, LocalDate.MIN); } public VEvent() { this(""); } public static LocalDate translateDate(String dateString) { return LocalDate.of(getYear(dateString), Integer.parseInt(dateString.substring(4,6)), Integer.parseInt(dateString.substring(6,8))); } public static int getYear(String dateString) { return Integer.parseInt(dateString.substring(0,4)); } //TODO should it include end? public boolean contains(LocalDate d) { return (d.isAfter(start) && d.isBefore(end)) || d.isEqual(start); } public LocalDate getStart() { return start; } public void setStart(LocalDate start) { this.start = start; } public LocalDate getEnd() { return end; } public void setEnd(LocalDate end) { this.end = end; } public String getSummary() { return summary; } public void setSummary(String summary) { this.summary = summary; } public String getDetail() { return detail; } public void setDetail(String detail) { this.detail = detail; } public String toString() { return getClass().getName() + "[" + summary + ", (" + start + " - "+end + ")]"; } } <file_sep>package com.varano.ui.display.selection; import javax.swing.DefaultListModel; import javax.swing.JList; import javax.swing.JPanel; import javax.swing.event.ListSelectionEvent; import javax.swing.event.ListSelectionListener; import com.varano.information.ClassPeriod; import com.varano.information.Schedule; import com.varano.information.constants.ErrorID; import com.varano.managers.Agenda; import com.varano.ui.UIHandler; import com.varano.ui.display.current.CurrentClassPane; //<NAME> //[Program Descripion] //Sep 9, 2017 public class ScheduleList extends JList<ClassPeriod> implements ListSelectionListener { private static final long serialVersionUID = 1L; private JPanel parentPane; private boolean selectable; private boolean thickConstraints, showNames; private boolean debug = false, debugNames = false; private Schedule schedule; public ScheduleList(Schedule schedule, boolean showNames) { super(); selectable = true; setName(schedule.getName() + " list"); setShowNames(showNames); setBackground(UIHandler.secondary); setModel(new DefaultListModel<ClassPeriod>()); setSchedule(schedule); setFont(UIHandler.font.deriveFont(getFont().getSize())); addListSelectionListener(this); if (debugNames) System.out.println(getName()+ " SHOWNAMES="+showNames); createList(); if (debug) System.out.println(getName()+"size"+getModel().getSize()); } private void createList() { try { ((DefaultListModel<ClassPeriod>) getModel()).removeAllElements(); } catch (ClassCastException e) { ErrorID.showError(e, false); } for (ClassPeriod c : schedule.getClasses()) { if (debug) System.out.println(getName()+" added "+c); ((DefaultListModel<ClassPeriod>) getModel()).addElement(c); if (debug) System.out.println(c + ", slot " + c.getSlot() + ", is "+c.canShowPeriod()); } if (debug) System.out.println(getName()+" CREATED size:" +getModel().getSize()); } public void setSelectedValue(int slot, boolean scroll) { setSelectedValue(schedule.get(slot), scroll); } public void autoSetSelection() { if (parentPane instanceof CurrentClassPane) { CurrentClassPane parent = (CurrentClassPane) parentPane; if (parent.checkInSchool()) { if (parent.getClassPeriod() == null) setSelectedValue(schedule.get(parent.findNextClass().getSlot()), true); else setSelectedValue(parent.getCurrentSlot(), true); if (debug) System.out.println(getName()+"value set to"+parent.getClassPeriod()); } else { if (debug) System.out.println(getName()+": out of school"); clearSelection(); } if (debug) System.out.println("move class back to "+((CurrentClassPane) parentPane).getClassPeriod()); } else { if (debug) System.out.println(getName()+"error in scheduleListAutoSelect"); Agenda.log("Error in autoSetSelection"); clearSelection(); } } // public JToolTip createToolTip() { // return null; //// return super.createToolTip(); // } public Schedule getSchedule() { return schedule; } public void setSchedule(Schedule schedule) { if (debugNames) System.out.println(getName() + "THE NEW SCHEDULE HERE IS "+schedule.getName()); this.schedule = schedule; createList(); } public JPanel getParentPane() { return parentPane; } public void setParentPane(JPanel parent) { this.parentPane = parent; } public boolean isThickConstraints() { return thickConstraints; } public void setThickConstraints(boolean thickConstraints) { this.thickConstraints = thickConstraints; } public boolean isShowNames() { return showNames; } public void setShowNames(boolean showNames) { this.showNames = showNames; } public boolean getSelectable() { return selectable; } public void setSelectable(boolean selectable) { this.selectable = selectable; setFocusable(selectable); } public String toString() { return getClass().getName() + "[" + getName() + " size = " + getSize() + "]"; } @Override public void valueChanged(ListSelectionEvent e) { if (debug) { if (getSelectedValue()!=null) System.out.println("SELECTION:"+getSelectedIndex() + ":"+ ((ClassPeriod)getSelectedValue()).getInfo()); else System.out.println("SELECTION:"+getSelectedIndex() + ":null"); } if (selectable) { if (parentPane != null) if (parentPane instanceof ScheduleInfoSelector) ((ScheduleInfoSelector) parentPane).updatePeriod(); } else { autoSetSelection(); } } }
28e8f74eeef7691ce19e3de61a65527e44897011
[ "Markdown", "Java" ]
16
Java
tvarano54/agenda
a00590a8457c8454e0e432c9b693f5636553374f
f71f19948a9c5ad82ed01e5141b32f566fb13758
refs/heads/master
<file_sep>// import var frameModule = require("tns-core-modules/ui/frame"); var HomeViewModel = require("./home-view-model"); var dialogs = require("tns-core-modules/ui/dialogs"); var homeViewModel = new HomeViewModel(); var credits = "Tŝilhqot’in Alphabet by <NAME>"; function pageLoaded(args) { var page = args.object; page.bindingContext = homeViewModel; } exports.pageLoaded = pageLoaded; function onButtonTap(args) { // say Hello alertMessage("Hello"); } exports.onButtonTap = onButtonTap; function showCredits(args) { alertMessage(credits); } exports.showCredits = showCredits; function alertMessage(theMessage) { dialogs.alert(theMessage); }
6a1bc025203ce861fc50492b17c913ad38103418
[ "JavaScript" ]
1
JavaScript
Tsilhqot-in-National-Government/alphabet-title
edd1f2f97ce61c8fc2191225d3edef6c7dbfca7f
95abd08bc7edb41ddf5f144876bc48404cef09f4
refs/heads/master
<repo_name>dmurtari/mbu-online<file_sep>/src/server/models/event.model.ts import { Table, Model, Column, Validate, DataType, HasMany, BelongsToMany } from 'sequelize-typescript'; import { Purchasable } from '@models/purchasable.model'; import { Scout } from '@models/scout.model'; import { Registration } from '@models/registration.model'; import { Badge } from '@models/badge.model'; import { Offering } from '@models/offering.model'; import { Semester, EventInterface } from '@interfaces/event.interface'; @Table({ underscored: true, tableName: 'Events' }) export class Event extends Model<Event> implements EventInterface { @Column({ allowNull: false }) public year!: number; @Validate({ isIn: [['Spring', 'Fall']] }) @Column({ allowNull: false, type: DataType.STRING }) public semester!: Semester; @Column({ allowNull: false, unique: true }) public date!: Date; @Column({ allowNull: false }) public registration_open!: Date; @Column({ allowNull: false }) public registration_close!: Date; @Column({ allowNull: false, type: DataType.DECIMAL(5, 2) }) public price!: number; @HasMany(() => Purchasable, 'event_id') public purchasables: Purchasable[]; @BelongsToMany(() => Scout, () => Registration, 'event_id', 'scout_id') public attendees: Scout[]; @BelongsToMany(() => Badge, () => Offering, 'event_id', 'badge_id') public offerings: Badge[]; } <file_sep>/src/client/src/validators/betweenDate.js import moment from 'moment' export default (first, second, format = 'MM/DD/YYYY') => { return (value, parentVm) => { const compareFirst = typeof first === 'function' ? first.call(this, parentVm) : parentVm[first] const compareSecond = typeof second === 'function' ? second.call(this, parentVm) : parentVm[second] const firstDate = moment(compareFirst, format); const secondDate = moment(compareSecond, format); const testDate = moment(value, format); if (!firstDate.isValid() || !secondDate.isValid()) return true; if (!testDate.isValid()) return false; return testDate.isBetween(firstDate, secondDate) || testDate.isBetween(secondDate, firstDate); } }<file_sep>/tests/server/testScouts.ts import faker from 'faker'; import { times } from 'lodash'; export default (count: number) => times(count, () => ({ firstname: faker.name.firstName(), lastname: faker.name.lastName(), birthday: faker.date.between(new Date(1998, 12, 12), new Date(2002, 12, 12)), troop: faker.random.number(), notes: faker.lorem.sentence(), emergency_name: faker.name.findName(), emergency_relation: faker.name.jobTitle(), emergency_phone: faker.phone.phoneNumber() })); <file_sep>/src/libs/interfaces/scout.interface.ts import { EventDto, EventInterface } from '@interfaces/event.interface'; import { RegistrationDto } from '@interfaces/registration.interface'; import { UserInterface, ScoutUserDto } from '@interfaces/user.interface'; export interface ScoutInterface { id?: number; firstname?: string; lastname?: string; fullname?: string; birthday?: Date; troop?: number; notes?: string; emergency_name?: string; emergency_relation?: string; emergency_phone?: string; user?: UserInterface; registrations?: EventInterface[]; } export interface ScoutDto extends ScoutInterface { scout_id?: number; user?: ScoutUserDto; registrations?: EventDto<RegistrationDto>[]; } export type ScoutsResponseDto = ScoutDto[]; export type CreateScoutRequestDto = ScoutDto; export interface ScoutRegistrationDto extends ScoutDto { registrations: EventDto<RegistrationDto>[]; } export type ScoutRegistrationResponseDto = ScoutRegistrationDto[]; export interface ScoutResponseDto { message: string; scout: ScoutDto; } <file_sep>/src/server/models/queries/registrationInformation.ts import { FindOptions } from 'sequelize'; import { Scout } from '@models/scout.model'; import { Offering } from '@models/offering.model'; import { Badge } from '@models/badge.model'; import { Purchasable } from '@models/purchasable.model'; export default <FindOptions>{ attributes: { include: [['id', 'registration_id'], 'created_at', 'updated_at', 'scout_id', 'event_id'], exclude: ['projectedCost', 'actualCost'] }, include: [ { model: Scout, as: 'scout', attributes: [['id', 'scout_id'], 'firstname', 'lastname', 'fullname', 'troop', 'notes'] }, { model: Offering, as: 'preferences', attributes: [['id', 'offering_id'], 'duration', 'periods', 'price'], through: <any>{ as: 'details', attributes: ['rank'] }, include: [{ model: Badge, as: 'badge', attributes: ['name'] }] }, { model: Offering, as: 'assignments', attributes: [['id', 'offering_id'], 'price'], through: <any>{ as: 'details', attributes: ['periods', 'completions'] }, include: [{ model: Badge, as: 'badge', attributes: ['name'] }] }, { model: Purchasable, as: 'purchases', attributes: [['id', 'purchasable_id'], 'item', 'price', 'has_size'], through: <any>{ as: 'details', attributes: ['size', 'quantity'] }, } ] }; <file_sep>/src/server/middleware/currentUser.ts import { Request, NextFunction, Response } from 'express'; import passport from 'passport'; import status from 'http-status-codes'; import { User } from '@models/user.model'; import { MessageResponseDto } from '@interfaces/shared.interface'; import { UserRole } from '@interfaces/user.interface'; export const currentUser = (otherAuthorizedRoles: UserRole[] = []) => (req: Request, res: Response, next: NextFunction) => { passport.authenticate('jwt', { session: false }, (_err, user: User) => { const roles = [UserRole.ADMIN, ...otherAuthorizedRoles]; if (roles.includes(user.role)) { return next(); } if ((req.params.userId && Number(req.params.userId) !== user.id) || (req.query.id && Number(req.query.id) !== user.id)) { return res.status(status.UNAUTHORIZED).json(<MessageResponseDto>{ message: 'Not the current user' }); } else { return next(); } })(req, res, next); }; <file_sep>/src/client/src/validators/commaSeparatedSpec.js import { expect } from 'chai' import commaSeparated from './commaSeparated'; describe('The comma separated validator', () => { it('should validate a comma separated list', () => { expect(commaSeparated('1, 2, 3')).to.be.true; expect(commaSeparated('1,2,3')).to.be.true; expect(commaSeparated('1, 2,3')).to.be.true; expect(commaSeparated('1a, 2, 3b')).to.be.true; expect(commaSeparated('1a, 2, a')).to.be.true; }); it('should accept ending with a comma', () => { expect(commaSeparated('1,2,3,')).to.be.true; }) it('should fail for other punctuation', () => { expect(commaSeparated('1.2.3')).to.be.false; expect(commaSeparated('1,2.3')).to.be.false; }); it('should pass for empty values', () => { expect(commaSeparated(null)).to.be.true; expect(commaSeparated('')).to.be.true; expect(commaSeparated(' ')).to.be.true; }); }); <file_sep>/src/server/routes/badges/getBadges.ts import { Request, Response } from 'express'; import status from 'http-status-codes'; import { WhereOptions } from 'sequelize'; import { Badge } from '@models/badge.model'; import { ErrorResponseDto } from '@interfaces/shared.interface'; export const getBadges = async (req: Request, res: Response) => { try { const queryableFields: string[] = ['name', 'semester']; const query: WhereOptions = {}; queryableFields.forEach(field => { if (req.query[field]) { query[field] = req.query[field]; } }); const badges: Badge[] = await Badge.findAll({ where: query }); return res.status(status.OK).json(badges); } catch (err) { return res.status(status.BAD_REQUEST).send(<ErrorResponseDto>{ message: 'Failed to get badges', error: err }); } }; <file_sep>/src/client/src/store/modules/classes.js import * as types from '../mutation-types'; import URLS from '../../urls'; import _ from 'lodash'; import Vue from 'vue'; import axios from 'axios'; const state = { eventClasses: {} }; const getters = { eventClasses(state) { return state.eventClasses; } }; const mutations = { [types.SET_CLASSES](state, details) { Vue.set(state.eventClasses, details.eventId, details.classes); }, [types.SET_CLASS_SIZES](state, details) { let existingClasses = state.eventClasses[details.eventId]; if (existingClasses == undefined) { return; } let classes = []; _.forEach(existingClasses, (classInfo) => { const sizeInfo = _.find(details.sizes, sizeInfo => { return classInfo.badge.badge_id === sizeInfo.badgeId; }); classes.push({ ...classInfo, sizeInfo: (sizeInfo && sizeInfo.sizeLimits) || classInfo.sizeInfo || {} }); }); Vue.set(state.eventClasses, details.eventId, classes); } }; const actions = { getClasses({ commit }, eventId) { return new Promise((resolve, reject) => { return axios .get(URLS.EVENTS_URL + eventId + '/offerings/assignees') .then(response => { commit(types.SET_CLASSES, { eventId: String(eventId), classes: response.data }); resolve(response.data); }) .catch(() => { reject(); }); }); }, getClassSizes({ commit }, details) { const requests = Promise.all( _.map(details.badgeIds, badgeId => { return axios.get( URLS.EVENTS_URL + details.eventId + '/badges/' + badgeId + '/limits' ); }) ); return new Promise((resolve, reject) => { requests .then(responses => { const sizes = _.map(responses, (response, index) => { return { badgeId: details.badgeIds[index], sizeLimits: response.data }; }); commit(types.SET_CLASS_SIZES, { eventId: details.eventId, sizes: sizes }); resolve(sizes); }) .catch(() => { reject(); }); }); } }; export default { state, getters, actions, mutations }; <file_sep>/tests/server/testBadges.ts export default [ { name: 'Swimming', description: 'Learn how to swim', notes: 'Swimsuit required' }, { name: 'Digital Technology', description: 'Learn about computers' }, { name: 'Citizenship in the World', description: 'Learn about world politics', notes: 'Eagle badge' } ]; <file_sep>/src/server/routes/events/updateEvents.ts import { Request, Response } from 'express'; import status from 'http-status-codes'; import { Event } from '@models/event.model'; import { EventResponseDto } from '@interfaces/event.interface'; import { ErrorResponseDto } from '@interfaces/shared.interface'; import { Badge } from '@models/badge.model'; import { Offering } from '@models/offering.model'; import { OfferingResponseDto } from '@interfaces/offering.interface'; import { Purchasable } from '@models/purchasable.model'; import { UpdatePurchasableResponseDto } from '@interfaces/purchasable.interface'; export const updateEvent = async (req: Request, res: Response) => { try { const event: Event = await Event.findByPk(req.params.id, { include: [{ model: Badge, as: 'offerings', through: <any> { as: 'details' } }] }); if (!event) { throw new Error('Event to update not found'); } await event.update(req.body); return res.status(status.OK).json(<EventResponseDto>{ message: 'Event updated successfully', event: event }); } catch (err) { return res.status(status.BAD_REQUEST).json(<ErrorResponseDto>{ message: 'Error updating event' , error: err }); } }; export const updateOffering = async (req: Request, res: Response) => { try { const offering: Offering = await Offering.findOne({ where: { badge_id: req.params.badgeId, event_id: req.params.eventId } }); if (!offering) { throw new Error('Offering to update not found'); } await offering.update(req.body); return res.status(status.OK).json(<OfferingResponseDto> { message: 'Offering updated successfully', offering: offering }); } catch (err) { return res.status(status.BAD_REQUEST).json(<ErrorResponseDto>{ message: 'Error updating offering' , error: err }); } }; export const updatePurchasable = async (req: Request, res: Response) => { try { const purchasable: Purchasable = await Purchasable.findOne({ where: { event_id: req.params.eventId, id: req.params.purchasableId } }); if (!purchasable) { throw new Error('Purchasable to update not found'); } await purchasable.update(req.body); return res.status(status.OK).json(<UpdatePurchasableResponseDto>{ message: 'Purchasable updated successfully', purchasable: purchasable }); } catch (err) { return res.status(status.BAD_REQUEST).json(<ErrorResponseDto>{ message: 'Error updating purchasable', error: err }); } }; <file_sep>/src/client/src/filters/numAlphaSort.js import _ from 'lodash'; export default (array) => { let sortable = _.cloneDeep(_.without(array, null, undefined)); return sortable.sort(function (first, second) { const firstSplit = first.split(/(?=\D)/); const secondSplit = second.split(/(?=\D)/); return firstSplit[0] - secondSplit[0] || (firstSplit[1] || '').localeCompare(secondSplit[1] || ''); }); } <file_sep>/src/client/src/main.js import Vue from 'vue'; import VueRouter from 'vue-router'; import Vuelidate from 'vuelidate'; import VuePaginate from 'vue-paginate'; import VTooltip from 'v-tooltip' import App from './App.vue'; import store from './store'; import routes from './router'; import components from './components'; import filters from './filters'; import './assets/sass/main.scss'; Vue.use(VueRouter); Vue.use(Vuelidate); Vue.use(VuePaginate); Vue.use(VTooltip) components(Vue); filters(Vue); export const router = new VueRouter({ mode: 'history', routes: routes, linkActiveClass: 'is-active' }); router.beforeEach((to, from, next) => { if (!localStorage.getItem('token')) { return next(); } if (to.meta.title) { document.title = 'MBU Online | ' + to.meta.title; } else { document.title = 'MBU Online'; } return next(); }); new Vue({ router, store, el: '#app', components: { App } }); <file_sep>/src/client/src/validators/beforeDate.js import moment from 'moment'; export default (beforeDate, format = 'MM/DD/YYYY') => { return (value, parentVm) => { const compareTo = typeof beforeDate === 'function' ? beforeDate.call(this, parentVm) : parentVm[beforeDate] const compareDate = moment(compareTo, format); const testDate = moment(value, format); if (!compareDate.isValid()) return true; if (!testDate.isValid()) return false; return testDate.isBefore(moment(compareTo, format)); } }<file_sep>/src/server/middleware/isAuthorized.ts import { Request, Response, NextFunction } from 'express'; import passport from 'passport'; import status from 'http-status-codes'; import { User } from '@models/user.model'; import { MessageResponseDto } from '@interfaces/shared.interface'; import { UserRole } from '@interfaces/user.interface'; export const isAuthorized = (roles: UserRole[] = []) => (req: Request, res: Response, next: NextFunction) => { passport.authenticate('jwt', { session: false }, (err, user: User) => { if (!!err) { return next(err); } if (!user) { return res.status(status.UNAUTHORIZED).json(<MessageResponseDto>{ message: 'Could not find a user with the given token' }); } if (!user.approved) { return res.status(status.UNAUTHORIZED).json(<MessageResponseDto>{ message: 'Account has not been approved yet' }); } const authorizedRoles: UserRole[] = [UserRole.ADMIN, ...roles]; if (authorizedRoles.includes(user.role)) { return next(); } else { return res.status(status.UNAUTHORIZED).json(<MessageResponseDto>{ message: 'Current role is not authorized to access this endpoint' }); } })(req, res, next); }; <file_sep>/src/libs/interfaces/purchasable.interface.ts export interface PurchasableInterface { id?: number; item?: string; description?: string; has_size?: boolean; price?: number|string; maximum_age?: number; minimum_age?: number; purchaser_limit?: number; } export interface PurchasableDto<T = any> extends PurchasableInterface { details?: T; purchaser_count?: number; } export type CreatePurchasableDto = PurchasableInterface; export type UpdatePurchasableDto = PurchasableInterface; export type PurchasablesResponseDto = PurchasableDto[]; export interface CreatePurchasablesResponseDto { purchasables: PurchasableInterface[]; message: string; } export interface UpdatePurchasableResponseDto { purchasable: PurchasableInterface; message: string; } <file_sep>/tests/server/authenticationSpec.ts import supertest from 'supertest'; import status from 'http-status-codes'; import { expect } from 'chai'; import app from '@app/app'; import TestUtils from './testUtils'; import { SignupRequestDto, UserTokenResponseDto } from '@interfaces/user.interface'; import { SuperTestResponse } from '@test/helpers/supertest.interface'; const request = supertest(app); describe('authentication', () => { beforeEach(async () => { await TestUtils.dropDb(); }); afterAll(async () => { await TestUtils.dropDb(); await TestUtils.closeDb(); }); describe('user roles', () => { test('should create a user with a default role', (done) => { const postData: SignupRequestDto = { email: '<EMAIL>', password: '<PASSWORD>', firstname: 'firstname', lastname: 'lastname' }; request.post('/api/signup') .send(postData) .expect(status.CREATED) .end((err, res: SuperTestResponse<UserTokenResponseDto>) => { if (err) { return done(err); } const user = res.body.profile; expect(user.email).to.equal(postData.email); expect(user.role).to.equal('anonymous'); return done(); }); }); test('should create a user with a role', (done) => { const postData: SignupRequestDto = { email: '<EMAIL>', password: '<PASSWORD>', firstname: 'firstname', lastname: 'lastname', role: 'coordinator' }; request.post('/api/signup') .send(postData) .expect(status.CREATED) .end((err, res: SuperTestResponse<UserTokenResponseDto>) => { if (err) { return done(err); } const user = res.body.profile; expect(user.email).to.equal(postData.email); expect(user.role).to.equal(postData.role); return done(); }); }); test('should not create a user with an invalid role', (done) => { const postData: SignupRequestDto = { email: '<EMAIL>', password: '<PASSWORD>', firstname: 'firstname', lastname: 'lastname', role: 'superuser' }; request.post('/api/signup') .send(postData) .expect(status.BAD_REQUEST, done); }); }); }); <file_sep>/src/server/seed/initial_schema.sql CREATE TABLE "Assignments" ( periods integer[] NOT NULL, offering_id integer NOT NULL, registration_id integer NOT NULL, created_at timestamp with time zone NOT NULL, updated_at timestamp with time zone NOT NULL ); ALTER TABLE "Assignments" OWNER TO mbu; CREATE TABLE "Badges" ( id integer NOT NULL, name character varying(255) NOT NULL, description text, notes character varying(255), created_at timestamp with time zone NOT NULL, updated_at timestamp with time zone NOT NULL ); ALTER TABLE "Badges" OWNER TO mbu; CREATE SEQUENCE "Badges_id_seq" START WITH 1 INCREMENT BY 1 NO MINVALUE NO MAXVALUE CACHE 1; ALTER TABLE "Badges_id_seq" OWNER TO mbu; ALTER SEQUENCE "Badges_id_seq" OWNED BY "Badges".id; CREATE TABLE "Events" ( id integer NOT NULL, year integer NOT NULL, semester character varying(255) NOT NULL, date timestamp with time zone NOT NULL, registration_open timestamp with time zone NOT NULL, registration_close timestamp with time zone NOT NULL, price numeric(5,2) NOT NULL, created_at timestamp with time zone NOT NULL, updated_at timestamp with time zone NOT NULL ); ALTER TABLE "Events" OWNER TO mbu; CREATE SEQUENCE "Events_id_seq" START WITH 1 INCREMENT BY 1 NO MINVALUE NO MAXVALUE CACHE 1; ALTER TABLE "Events_id_seq" OWNER TO mbu; ALTER SEQUENCE "Events_id_seq" OWNED BY "Events".id; CREATE TABLE "Offerings" ( id integer NOT NULL, duration integer NOT NULL, periods integer[] NOT NULL, price numeric(5,2) DEFAULT 0 NOT NULL, event_id integer NOT NULL, badge_id integer NOT NULL, created_at timestamp with time zone NOT NULL, updated_at timestamp with time zone NOT NULL ); ALTER TABLE "Offerings" OWNER TO mbu; CREATE SEQUENCE "Offerings_id_seq" START WITH 1 INCREMENT BY 1 NO MINVALUE NO MAXVALUE CACHE 1; ALTER TABLE "Offerings_id_seq" OWNER TO mbu; ALTER SEQUENCE "Offerings_id_seq" OWNED BY "Offerings".id; CREATE TABLE "Preferences" ( rank integer NOT NULL, offering_id integer NOT NULL, registration_id integer NOT NULL, created_at timestamp with time zone NOT NULL, updated_at timestamp with time zone NOT NULL ); ALTER TABLE "Preferences" OWNER TO mbu; CREATE TABLE "Purchasables" ( id integer NOT NULL, item character varying(255) NOT NULL, description character varying(255), price numeric(5,2) NOT NULL, created_at timestamp with time zone NOT NULL, updated_at timestamp with time zone NOT NULL, event_id integer ); ALTER TABLE "Purchasables" OWNER TO mbu; CREATE SEQUENCE "Purchasables_id_seq" START WITH 1 INCREMENT BY 1 NO MINVALUE NO MAXVALUE CACHE 1; ALTER TABLE "Purchasables_id_seq" OWNER TO mbu; ALTER SEQUENCE "Purchasables_id_seq" OWNED BY "Purchasables".id; CREATE TABLE "Purchases" ( purchasable_id integer NOT NULL, registration_id integer NOT NULL, size character varying(255), quantity integer DEFAULT 0 NOT NULL, created_at timestamp with time zone NOT NULL, updated_at timestamp with time zone NOT NULL ); ALTER TABLE "Purchases" OWNER TO mbu; CREATE TABLE "Registrations" ( id integer NOT NULL, event_id integer NOT NULL, scout_id integer NOT NULL, created_at timestamp with time zone NOT NULL, updated_at timestamp with time zone NOT NULL ); ALTER TABLE "Registrations" OWNER TO mbu; CREATE SEQUENCE "Registrations_id_seq" START WITH 1 INCREMENT BY 1 NO MINVALUE NO MAXVALUE CACHE 1; ALTER TABLE "Registrations_id_seq" OWNER TO mbu; ALTER SEQUENCE "Registrations_id_seq" OWNED BY "Registrations".id; CREATE TABLE "Scouts" ( id integer NOT NULL, firstname character varying(255) NOT NULL, lastname character varying(255) NOT NULL, birthday timestamp with time zone NOT NULL, troop integer NOT NULL, notes character varying(255), emergency_name character varying(255) NOT NULL, emergency_relation character varying(255) NOT NULL, emergency_phone character varying(255) NOT NULL, created_at timestamp with time zone NOT NULL, updated_at timestamp with time zone NOT NULL, user_id integer ); ALTER TABLE "Scouts" OWNER TO mbu; CREATE SEQUENCE "Scouts_id_seq" START WITH 1 INCREMENT BY 1 NO MINVALUE NO MAXVALUE CACHE 1; ALTER TABLE "Scouts_id_seq" OWNER TO mbu; ALTER SEQUENCE "Scouts_id_seq" OWNED BY "Scouts".id; CREATE TABLE "Users" ( id integer NOT NULL, email character varying(255) NOT NULL, password character varying(255) NOT NULL, reset_password_token character varying(255), reset_token_expires timestamp with time zone, firstname character varying(255) NOT NULL, lastname character varying(255) NOT NULL, role character varying(255) DEFAULT 'anonymous'::character varying NOT NULL, created_at timestamp with time zone NOT NULL, updated_at timestamp with time zone NOT NULL ); ALTER TABLE "Users" OWNER TO mbu; CREATE SEQUENCE "Users_id_seq" START WITH 1 INCREMENT BY 1 NO MINVALUE NO MAXVALUE CACHE 1; ALTER TABLE "Users_id_seq" OWNER TO mbu; ALTER SEQUENCE "Users_id_seq" OWNED BY "Users".id; ALTER TABLE ONLY "Badges" ALTER COLUMN id SET DEFAULT nextval('"Badges_id_seq"'::regclass); ALTER TABLE ONLY "Events" ALTER COLUMN id SET DEFAULT nextval('"Events_id_seq"'::regclass); ALTER TABLE ONLY "Offerings" ALTER COLUMN id SET DEFAULT nextval('"Offerings_id_seq"'::regclass); ALTER TABLE ONLY "Purchasables" ALTER COLUMN id SET DEFAULT nextval('"Purchasables_id_seq"'::regclass); ALTER TABLE ONLY "Registrations" ALTER COLUMN id SET DEFAULT nextval('"Registrations_id_seq"'::regclass); ALTER TABLE ONLY "Scouts" ALTER COLUMN id SET DEFAULT nextval('"Scouts_id_seq"'::regclass); ALTER TABLE ONLY "Users" ALTER COLUMN id SET DEFAULT nextval('"Users_id_seq"'::regclass); ALTER TABLE ONLY "Assignments" ADD CONSTRAINT "Assignments_pkey" PRIMARY KEY (offering_id, registration_id); ALTER TABLE ONLY "Badges" ADD CONSTRAINT "Badges_name_key" UNIQUE (name); ALTER TABLE ONLY "Badges" ADD CONSTRAINT "Badges_pkey" PRIMARY KEY (id); ALTER TABLE ONLY "Events" ADD CONSTRAINT "Events_date_key" UNIQUE (date); ALTER TABLE ONLY "Events" ADD CONSTRAINT "Events_pkey" PRIMARY KEY (id); ALTER TABLE ONLY "Offerings" ADD CONSTRAINT "Offerings_event_id_badge_id_key" UNIQUE (event_id, badge_id); ALTER TABLE ONLY "Offerings" ADD CONSTRAINT "Offerings_pkey" PRIMARY KEY (id); ALTER TABLE ONLY "Preferences" ADD CONSTRAINT "Preferences_pkey" PRIMARY KEY (offering_id, registration_id); ALTER TABLE ONLY "Purchasables" ADD CONSTRAINT "Purchasables_pkey" PRIMARY KEY (id); ALTER TABLE ONLY "Registrations" ADD CONSTRAINT "Registrations_event_id_scout_id_key" UNIQUE (event_id, scout_id); ALTER TABLE ONLY "Registrations" ADD CONSTRAINT "Registrations_pkey" PRIMARY KEY (id); ALTER TABLE ONLY "Scouts" ADD CONSTRAINT "Scouts_pkey" PRIMARY KEY (id); ALTER TABLE ONLY "Users" ADD CONSTRAINT "Users_email_key" UNIQUE (email); ALTER TABLE ONLY "Users" ADD CONSTRAINT "Users_pkey" PRIMARY KEY (id); CREATE UNIQUE INDEX badges_ ON "Badges" USING btree (lower((name)::text)); CREATE UNIQUE INDEX users_ ON "Users" USING btree (lower((email)::text)); ALTER TABLE ONLY "Assignments" ADD CONSTRAINT "Assignments_offering_id_fkey" FOREIGN KEY (offering_id) REFERENCES "Offerings"(id) ON UPDATE CASCADE ON DELETE CASCADE; ALTER TABLE ONLY "Assignments" ADD CONSTRAINT "Assignments_registration_id_fkey" FOREIGN KEY (registration_id) REFERENCES "Registrations"(id) ON UPDATE CASCADE ON DELETE CASCADE; ALTER TABLE ONLY "Offerings" ADD CONSTRAINT "Offerings_badge_id_fkey" FOREIGN KEY (badge_id) REFERENCES "Badges"(id) ON UPDATE CASCADE ON DELETE CASCADE; ALTER TABLE ONLY "Offerings" ADD CONSTRAINT "Offerings_event_id_fkey" FOREIGN KEY (event_id) REFERENCES "Events"(id) ON UPDATE CASCADE ON DELETE CASCADE; ALTER TABLE ONLY "Preferences" ADD CONSTRAINT "Preferences_offering_id_fkey" FOREIGN KEY (offering_id) REFERENCES "Offerings"(id) ON UPDATE CASCADE ON DELETE CASCADE; ALTER TABLE ONLY "Preferences" ADD CONSTRAINT "Preferences_registration_id_fkey" FOREIGN KEY (registration_id) REFERENCES "Registrations"(id) ON UPDATE CASCADE ON DELETE CASCADE; ALTER TABLE ONLY "Purchasables" ADD CONSTRAINT "Purchasables_event_id_fkey" FOREIGN KEY (event_id) REFERENCES "Events"(id) ON UPDATE CASCADE ON DELETE SET NULL; ALTER TABLE ONLY "Purchases" ADD CONSTRAINT "Purchases_purchasable_id_fkey" FOREIGN KEY (purchasable_id) REFERENCES "Purchasables"(id) ON UPDATE CASCADE ON DELETE CASCADE; ALTER TABLE ONLY "Purchases" ADD CONSTRAINT "Purchases_registration_id_fkey" FOREIGN KEY (registration_id) REFERENCES "Registrations"(id) ON UPDATE CASCADE ON DELETE CASCADE; ALTER TABLE ONLY "Registrations" ADD CONSTRAINT "Registrations_event_id_fkey" FOREIGN KEY (event_id) REFERENCES "Events"(id) ON UPDATE CASCADE ON DELETE CASCADE; ALTER TABLE ONLY "Registrations" ADD CONSTRAINT "Registrations_scout_id_fkey" FOREIGN KEY (scout_id) REFERENCES "Scouts"(id) ON UPDATE CASCADE ON DELETE CASCADE; ALTER TABLE ONLY "Scouts" ADD CONSTRAINT "Scouts_user_id_fkey" FOREIGN KEY (user_id) REFERENCES "Users"(id) ON UPDATE CASCADE ON DELETE SET NULL; ALTER TABLE ONLY "Purchases" ADD CONSTRAINT "Purchases_pkey" FOREIGN KEY (purchasable_id) REFERENCES "Purchasables"(id) ON UPDATE CASCADE ON DELETE SET NULL; <file_sep>/tests/server/scoutsSpec.ts import supertest from 'supertest'; import * as async from 'async'; import status from 'http-status-codes'; import { expect } from 'chai'; import app from '@app/app'; import TestUtils, { RoleTokenObjects } from './testUtils'; import testScouts from './testScouts'; import { CreateScoutRequestDto, ScoutResponseDto } from '@interfaces/scout.interface'; import { UserRole, UsersResponseDto } from '@interfaces/user.interface'; import { SuperTestResponse } from '@test/helpers/supertest.interface'; const request = supertest(app); describe('scouts', () => { let generatedUsers: RoleTokenObjects; let exampleScout: CreateScoutRequestDto; const badId = TestUtils.badId; beforeAll(async () => { await TestUtils.dropDb(); }); beforeAll(async () => { generatedUsers = await TestUtils.generateTokens([ UserRole.ADMIN, UserRole.TEACHER, UserRole.COORDINATOR, 'coordinator2' as any ]); }); beforeEach(() => { exampleScout = { firstname: 'Scouty', lastname: 'McScoutFace', birthday: new Date(1999, 1, 1), troop: 101, notes: 'Is a boat', emergency_name: '<NAME>', emergency_relation: 'Idol', emergency_phone: '1234567890' }; }); afterEach(async () => { TestUtils.removeScoutsForUser(generatedUsers.coordinator); }); afterAll(async () => { await TestUtils.dropDb(); await TestUtils.closeDb(); }); describe('in order to be associated with users', () => { test('should be able to be created', (done) => { request.post('/api/users/' + generatedUsers.coordinator.profile.id + '/scouts') .set('Authorization', generatedUsers.coordinator.token) .send(exampleScout) .expect(status.CREATED) .end((err, res: SuperTestResponse<ScoutResponseDto>) => { if (err) { return done(err); } const scout = res.body.scout; // expect(scout.name).to.equal(exampleScout.name); expect(scout.emergency_name).to.contain(exampleScout.emergency_name); expect(scout.emergency_relation).to.contain(exampleScout.emergency_relation); expect(scout.emergency_phone).to.contain(exampleScout.emergency_phone); expect(scout.troop).to.equal(exampleScout.troop); expect(scout.notes).to.equal(exampleScout.notes); expect(new Date(scout.birthday)).to.deep.equal(exampleScout.birthday); return done(); }); }); test('should not be created by a different coordinator', (done) => { request.post('/api/users/' + generatedUsers.coordinator.profile.id + '/scouts') .set('Authorization', generatedUsers.coordinator2.token) .send(exampleScout) .expect(status.UNAUTHORIZED, done); }); test('should be able to be created by teachers', (done) => { request.post('/api/users/' + generatedUsers.coordinator.profile.id + '/scouts') .set('Authorization', generatedUsers.teacher.token) .send(exampleScout) .expect(status.CREATED, done); }); test('should be able to be created by admins', (done) => { request.post('/api/users/' + generatedUsers.coordinator.profile.id + '/scouts') .set('Authorization', generatedUsers.admin.token) .send(exampleScout) .expect(status.CREATED, done); }); test('should require authorization', (done) => { request.post('/api/users/' + generatedUsers.coordinator.profile.id + '/scouts') .send(exampleScout) .expect(status.UNAUTHORIZED, done); }); test('should require valid scouts', (done) => { const postData = exampleScout; postData.birthday = new Date(4000, 1, 1); request.post('/api/users/' + generatedUsers.coordinator.profile.id + '/scouts') .set('Authorization', generatedUsers.coordinator.token) .send(postData) .expect(status.BAD_REQUEST, done); }); test( 'should not allow scouts to be associated with non-coordinators', (done) => { request.post('/api/users/' + generatedUsers.teacher.profile.id + '/scouts') .set('Authorization', generatedUsers.teacher.token) .send(exampleScout) .expect(status.BAD_REQUEST, done); } ); test('should not create a scout for an invalid id', (done) => { request.post('/api/users/' + badId + '/scouts') .set('Authorization', generatedUsers.coordinator.token) .send(exampleScout) .expect(status.UNAUTHORIZED, done); }); }); describe('when scouts exist', () => { const scoutCount = 5; let scouts: CreateScoutRequestDto[]; beforeEach(async () => { TestUtils.removeScoutsForUser(generatedUsers.coordinator); }); beforeEach(async () => { scouts = await TestUtils.createScoutsForUser(generatedUsers.coordinator, testScouts(scoutCount)); }); describe('seeing registered scouts', () => { test('should be able to get scouts for a user', (done) => { request.get('/api/users/' + generatedUsers.coordinator.profile.id + '/scouts') .set('Authorization', generatedUsers.coordinator.token) .expect(status.OK) .end((err, res: SuperTestResponse<UsersResponseDto>) => { if (err) { return done(err); } const user = res.body[0]; expect(user.scouts.length).to.equal(scoutCount); return done(); }); }); test('should let admins get scouts for a user', (done) => { request.get('/api/users/' + generatedUsers.coordinator.profile.id + '/scouts') .set('Authorization', generatedUsers.admin.token) .expect(status.OK) .end((err, res: SuperTestResponse<UsersResponseDto>) => { if (err) { return done(err); } const user = res.body[0]; expect(user.scouts.length).to.equal(scoutCount); return done(); }); }); test('should let teachers get scouts for a user', (done) => { request.get('/api/users/' + generatedUsers.coordinator.profile.id + '/scouts') .set('Authorization', generatedUsers.teacher.token) .expect(status.OK) .end((err, res: SuperTestResponse<UsersResponseDto>) => { if (err) { return done(err); } const user = res.body[0]; expect(user.scouts.length).to.equal(scoutCount); return done(); }); }); test('should not get scouts if the user doesnt exist', (done) => { request.get('/api/users/' + badId + '/scouts') .set('Authorization', generatedUsers.admin.token) .expect(status.BAD_REQUEST, done); }); test('should not get scouts with an invalid query', (done) => { request.get('/api/users?age=250') .set('Authorization', generatedUsers.admin.token) .expect(status.BAD_REQUEST, done); }); }); describe('updating registered scouts', () => { let scoutUpdate: CreateScoutRequestDto; beforeEach(() => { scoutUpdate = Object.assign({}, scouts[0]); }); test('should be able to update a scouts information', (done) => { scoutUpdate.firstname = 'Updated'; scoutUpdate.lastname = 'Scout'; scoutUpdate.emergency_name = 'Incompetent'; request.put('/api/users/' + generatedUsers.coordinator.profile.id + '/scouts/' + scouts[0].id) .set('Authorization', generatedUsers.coordinator.token) .send(scoutUpdate) .expect(status.OK) .end((err, res: SuperTestResponse<ScoutResponseDto>) => { if (err) { return done(err); } const scout = res.body.scout; expect(scout.id).to.equal(scouts[0].id); expect(scout.firstname).to.equal('Updated'); expect(scout.lastname).to.equal('Scout'); return done(); }); }); test('should allow fields to be deleted', (done) => { scoutUpdate.notes = null; request.put('/api/users/' + generatedUsers.coordinator.profile.id + '/scouts/' + scouts[0].id) .set('Authorization', generatedUsers.coordinator.token) .send(scoutUpdate) .expect(status.OK) .end((err, res: SuperTestResponse<ScoutResponseDto>) => { if (err) { return done(err); } const scout = res.body.scout; expect(scout.notes).to.not.exist; return done(); }); }); test('should allow updates from teachers', (done) => { request.put('/api/users/' + generatedUsers.coordinator.profile.id + '/scouts/' + scouts[0].id) .set('Authorization', generatedUsers.teacher.token) .send(scoutUpdate) .expect(status.OK, done); }); test('should allow updates from admins', (done) => { request.put('/api/users/' + generatedUsers.coordinator.profile.id + '/scouts/' + scouts[0].id) .set('Authorization', generatedUsers.admin.token) .send(scoutUpdate) .expect(status.OK, done); }); test('should not allow update from a different coordinator', (done) => { request.put('/api/users/' + generatedUsers.coordinator.profile.id + '/scouts/' + scouts[0].id) .set('Authorization', generatedUsers.coordinator2.token) .send(scoutUpdate) .expect(status.UNAUTHORIZED, done); }); test('should not update with invalid fields', (done) => { scoutUpdate.birthday = new Date(4000, 1, 1); request.put('/api/users/' + generatedUsers.coordinator.profile.id + '/scouts/' + scouts[0].id) .set('Authorization', generatedUsers.coordinator.token) .send(scoutUpdate) .expect(status.BAD_REQUEST, done); }); test('should not update a nonexistent user', (done) => { request.put('/api/users/' + badId + '/scouts/' + scouts[0].id) .set('Authorization', generatedUsers.coordinator.token) .send(scoutUpdate) .expect(status.UNAUTHORIZED, done); }); test('should not update nonexistent scouts', (done) => { request.put('/api/users/' + generatedUsers.coordinator.profile.id + '/scouts/' + badId) .set('Authorization', generatedUsers.coordinator.token) .send(scoutUpdate) .expect(status.BAD_REQUEST, done); }); }); describe('deleting scouts', () => { test('should delete scouts for a user', (done) => { async.series([ (cb) => { request.get('/api/users/' + generatedUsers.coordinator.profile.id + '/scouts') .set('Authorization', generatedUsers.admin.token) .expect(status.OK) .end((err, res: SuperTestResponse<UsersResponseDto>) => { if (err) { return done(err); } expect(res.body[0].scouts).to.have.lengthOf(scoutCount); return cb(); }); }, (cb) => { request.del('/api/users/' + generatedUsers.coordinator.profile.id + '/scouts/' + scouts[0].id) .set('Authorization', generatedUsers.coordinator.token) .expect(status.OK, cb); }, (cb) => { request.get('/api/users/' + generatedUsers.coordinator.profile.id + '/scouts') .set('Authorization', generatedUsers.admin.token) .expect(status.OK) .end((err, res: SuperTestResponse<UsersResponseDto>) => { if (err) { return done(err); } expect(res.body[0].scouts).to.have.lengthOf(scoutCount - 1); return cb(); }); } ], done); }); test('should require authorization', (done) => { request.del('/api/users/' + generatedUsers.coordinator.profile.id + '/scouts/' + scouts[0].id) .expect(status.UNAUTHORIZED, done); }); test('should check for the correct owner', (done) => { request.del('/api/users/' + generatedUsers.coordinator.profile.id + '/scouts/' + scouts[0].id) .set('Authorization', generatedUsers.coordinator2.token) .expect(status.UNAUTHORIZED, done); }); test('should allow admins to delete', (done) => { request.del('/api/users/' + generatedUsers.coordinator.profile.id + '/scouts/' + scouts[0].id) .set('Authorization', generatedUsers.admin.token) .expect(status.OK, done); }); test('should allow teachers to delete', (done) => { request.del('/api/users/' + generatedUsers.coordinator.profile.id + '/scouts/' + scouts[0].id) .set('Authorization', generatedUsers.teacher.token) .expect(status.OK, done); }); test('should not delete from nonexistent users', (done) => { request.del('/api/users/' + badId + '/scouts/' + scouts[0].id) .set('Authorization', generatedUsers.coordinator.token) .expect(status.UNAUTHORIZED, done); }); test('should not delete nonexistent scouts', (done) => { request.del('/api/users/' + generatedUsers.coordinator.profile.id + '/scouts/' + badId) .set('Authorization', generatedUsers.coordinator.token) .expect(status.BAD_REQUEST, done); }); }); }); }); <file_sep>/src/server/models/scout.model.ts import { Model, Table, Column, Validator, ForeignKey, BelongsTo, BelongsToMany, DataType } from 'sequelize-typescript'; import moment from 'moment'; import { User } from '@models/user.model'; import { Registration } from '@models/registration.model'; import { Event } from '@models/event.model'; import { ScoutInterface } from '@interfaces/scout.interface'; @Table({ underscored: true, tableName: 'Scouts' }) export class Scout extends Model<Scout> implements ScoutInterface { @Column({ allowNull: false }) public firstname!: string; @Column({ allowNull: false }) public lastname!: string; @Column({ allowNull: false }) public birthday!: Date; @Column({ allowNull: false }) public troop!: number; @Column public notes: string; @Column({ allowNull: false }) public emergency_name!: string; @Column({ allowNull: false }) public emergency_relation!: string; @Column({ allowNull: false }) public emergency_phone!: string; @Column(DataType.VIRTUAL) public get fullname(): string { return `${(this.firstname || '').trim()} ${(this.lastname || '').trim()}`; } @Column(DataType.VIRTUAL) public get age(): number { return moment().diff(moment(this.birthday), 'years'); } @ForeignKey(() => User) @Column public user_id: number; @BelongsTo(() => User) public user: User; @BelongsToMany(() => Event, () => Registration, 'scout_id', 'event_id') public registrations: Event[]; @Validator public birthdayInThePast(): void { if (this.birthday && !(this.birthday < new Date())) { throw new Error('Birthday must be in the past'); } } } <file_sep>/src/server/routes/users.ts import { Router, RequestHandler } from 'express'; import passport from 'passport'; import { signup, authenticate, addScout } from '@routes/users/postUsers'; import { byEmail, fromToken, byId, getEventRegistrations, getScoutRegistrations, getProjectedCost, getActualCost } from '@routes/users/getUsers'; import { updateProfile, updateScout } from '@routes/users/putUsers'; import { deleteUser, deleteScout } from '@routes/users/deleteUsers'; import { currentUser } from '@middleware/currentUser'; import { canUpdateRole } from '@middleware/canUpdateRole'; import { isAuthorized } from '@middleware/isAuthorized'; import { UserRole } from '@interfaces/user.interface'; import { isOwner } from '@middleware/isOwner'; export const userRoutes = Router(); const scoutMiddleware: RequestHandler[] = [currentUser([UserRole.TEACHER]), isAuthorized([UserRole.TEACHER, UserRole.COORDINATOR])]; userRoutes.param('scoutId', isOwner); userRoutes.post('/signup', signup); userRoutes.post('/authenticate', authenticate); userRoutes.get('/profile', passport.authenticate('jwt', { session: false }), fromToken); userRoutes.get('/users/:userId?', currentUser([UserRole.TEACHER]), byId()); userRoutes.put('/users/:userId', [currentUser([UserRole.TEACHER]), canUpdateRole], updateProfile); userRoutes.delete('/users/:userId', currentUser(), deleteUser); userRoutes.get('/users/exists/:email', byEmail); userRoutes.get('/users/:userId/scouts', scoutMiddleware, byId(true)); userRoutes.get('/users/:userId/scouts/registrations', scoutMiddleware, getScoutRegistrations); userRoutes.put('/users/:userId/scouts/:scoutId', scoutMiddleware, updateScout); userRoutes.post('/users/:userId/scouts', scoutMiddleware, addScout); userRoutes.delete('/users/:userId/scouts/:scoutId', scoutMiddleware, deleteScout); userRoutes.get('/users/:userId/events/:eventId/registrations', scoutMiddleware, getEventRegistrations); userRoutes.get('/users/:userId/events/:eventId/projectedCost', currentUser(), getProjectedCost); userRoutes.get('/users/:userId/events/:eventId/cost', currentUser(), getActualCost); <file_sep>/src/server/routes/shared/calculationType.enum.ts export enum CalculationType { Projected, Actual } <file_sep>/src/server/routes/users/postUsers.ts import { Request, Response } from 'express'; import { Op } from 'sequelize'; import jwt from 'jsonwebtoken'; import status from 'http-status-codes'; import config from '@config/secrets'; import { User } from '@models/user.model'; import { UserTokenResponseDto, UserRole } from '@interfaces/user.interface'; import { ErrorResponseDto } from '@interfaces/shared.interface'; import { Scout } from '@models/scout.model'; import { Event } from '@models/event.model'; export const signup = async (req: Request, res: Response) => { if (!req.body.email || !req.body.password || !req.body.firstname || !req.body.lastname) { return res.status(status.BAD_REQUEST).json({ message: 'Email, password, firstname, lastname required' }); } const newUser: User = req.body; newUser.approved = false; try { const user: User = await User.create(newUser); await user.save(); const token = jwt.sign(user.id, config.APP_SECRET); user.set('password', null); return res.status(status.CREATED).json(<UserTokenResponseDto>{ token: `JWT ${token}`, profile: user }); } catch (err) { return res.status(status.BAD_REQUEST).json(<ErrorResponseDto>{ message: 'Failed to create user', error: err }); } }; export const authenticate = async (req: Request, res: Response) => { try { const user: User = await User.findOne({ where: { email: { [Op.iLike]: req.body.email } } }); if (!user) { throw new Error('No matching email found'); } if (await user.comparePassword(req.body.password)) { const token: string = jwt.sign(user.id, config.APP_SECRET); user.set('password', null); return res.status(status.OK).json(<UserTokenResponseDto>{ token: `JWT ${token}`, profile: user }); } else { throw new Error('Password do no match'); } } catch (err) { return res.status(status.UNAUTHORIZED).json(<ErrorResponseDto>{ message: 'User authentication failed', error: err }); } }; export const addScout = async (req: Request, res: Response) => { try { const scout: Scout = await Scout.create(req.body); const user: User = await User.findByPk(req.params.userId); if (!user) { throw new Error('User not found'); } if (user.role !== UserRole.COORDINATOR) { throw new Error('Can only add scouts to coordinators'); } await user.$add('scout', scout); return res.status(status.CREATED).json({ message: 'Scout successfully created', scout: await Scout.findByPk(scout.id, { include: [{ model: Event, as: 'registrations' }] }) }); } catch (err) { return res.status(status.BAD_REQUEST).json(<ErrorResponseDto>{ message: 'Error creating scout', error: err }); } }; <file_sep>/src/server/models/assignment.model.ts import { Table, Model, Column, DataType, Default, ForeignKey, BeforeValidate } from 'sequelize-typescript'; import { Offering } from '@models/offering.model'; import { Registration } from '@models/registration.model'; import { AssignmentInterface } from '@interfaces/assignment.interface'; import { ClassSizeDto } from '@interfaces/event.interface'; @Table({ underscored: true, tableName: 'Assignments' }) export class Assignment extends Model<Assignment> implements AssignmentInterface { @BeforeValidate public static async ensureSizeLimit(assignment: Assignment): Promise<void> { if (!assignment.changed('periods')) { return; } try { const offering: Offering = await Offering.findByPk(assignment.offering_id); const sizes: ClassSizeDto = await offering.getClassSizes(); assignment.periods.forEach((period: number) => { if ((<any>sizes)[period] >= sizes.size_limit) { throw new Error(`Offering is at the size limit for period ${period}`); } }); } catch { throw new Error('Offering is at the class limit for the given periods'); } } @Column({ allowNull: false, type: DataType.ARRAY(DataType.INTEGER) }) public periods!: number[]; @Default([]) @Column({ allowNull: false, type: DataType.ARRAY(DataType.STRING) }) public completions: string[]; @ForeignKey(() => Offering) @Column({ allowNull: false }) public offering_id!: number; @ForeignKey(() => Registration) @Column({ allowNull: false }) public registration_id!: number; } <file_sep>/src/client/types/vue-paginate.d.ts declare module 'vue-paginate';<file_sep>/src/client/src/components/administration/offerings/OfferingListSpec.js import { shallowMount, createLocalVue } from '@vue/test-utils'; import Vuex from 'vuex'; import chai, { expect } from 'chai' import sinon from 'sinon'; import sinonChai from 'sinon-chai'; import OfferingList from './OfferingList.vue'; const localVue = createLocalVue(); localVue.use(Vuex); chai.use(sinonChai); describe('OfferingList.vue', () => { let wrapper, getters, store, actions, expectedOfferings; beforeEach(() => { expectedOfferings = [{ badge_id: '1', name: 'Badge 1', periods: [1, 2], duration: 1, price: undefined, requirements: ['1', '2'], size_limit: 10 }, { badge_id: '2', name: 'Badge 2', periods: undefined, duration: undefined, price: undefined, requirements: undefined, size_limit: undefined }, { badge_id: '3', name: 'Badge 3', periods: [2, 3], duration: 2, price: 10, requirements: ['1a'], size_limit: 20 } ]; actions = { getEvents: sinon.stub(), getCurrentEvent: sinon.stub(), getBadges: sinon.stub() }; getters = { badgeIdsAndNames: () => { return [{ id: '1', name: 'Badge 1' }, { id: '2', name: 'Badge 2' }, { id: '3', name: 'Badge 3' } ] }, // eslint-disable-next-line no-unused-vars offeringsForEvent: (eventId) => { return () => { return [{ details: { badge_id: '1', periods: [1, 2], duration: 1, requirements: ['1', '2'], size_limit: 10 } }, { details: { badge_id: '3', periods: [2, 3], duration: 2, price: 10, requirements: ['1a'], size_limit: 20 } } ] } } }; store = new Vuex.Store({ actions, getters }); wrapper = shallowMount(OfferingList, { localVue, store, }); }); it('should have gotten events', () => { expect(actions.getEvents).to.have.been.called; }); it('should have gotten the current event', () => { expect(actions.getCurrentEvent).to.have.been.called; }); it('should have gotten badges', () => { expect(actions.getBadges).to.have.been.called; }); it('should default to not filtering badges', () => { expect(wrapper.vm.offeredFilter).to.equal('all'); }); describe('when an event is selected', () => { beforeEach(() => { wrapper.setData({ eventId: '1', loading: false, eventLoading: false }) }); it('should show all badges', () => { expect(wrapper.vm.filteredOfferings).to.have.lengthOf(3); }); it('should compute a list of offered badges', () => { expect(wrapper.vm.offeringList).to.deep.equal(expectedOfferings); }); describe('filtering for offered badges', () => { beforeEach(() => { wrapper.setData({ offeredFilter: 'offered' }); }); it('should show only offered badges', () => { expect(wrapper.vm.filteredOfferings).to.have.lengthOf(2); }); it('should contain the offered badges', () => { console.info(wrapper.vm.filteredOfferings); expect(wrapper.vm.filteredOfferings).to.deep.include(expectedOfferings[0]); expect(wrapper.vm.filteredOfferings).to.deep.include(expectedOfferings[2]); }); it('should not contain the unoffered badge', () => { expect(wrapper.vm.filteredOfferings).not.to.deep.include(expectedOfferings[1]); }); }); describe('filtering for unoffered badges', () => { beforeEach(() => { wrapper.setData({ offeredFilter: 'unoffered' }); }); it('should show only offered badges', () => { expect(wrapper.vm.filteredOfferings).to.have.lengthOf(1); }); it('should not contain the offered badges', () => { expect(wrapper.vm.filteredOfferings).not.to.deep.contain(expectedOfferings[0]); expect(wrapper.vm.filteredOfferings).not.to.deep.contain(expectedOfferings[2]); }); it('should contain the unoffered badge', () => { expect(wrapper.vm.filteredOfferings).to.deep.include(expectedOfferings[1]); }); }); }); }); <file_sep>/src/server/routes/forgot/postForgot.ts import { Request, Response, NextFunction } from 'express'; import status from 'http-status-codes'; import { randomBytes } from 'crypto'; import { Op } from 'sequelize'; import mailer from '@sendgrid/mail'; import { MailData } from '@sendgrid/helpers/classes/mail'; import { User } from '@models/user.model'; import secrets from '@config/secrets'; import { MessageResponseDto, ErrorResponseDto } from '@interfaces/shared.interface'; export const forgot = async (req: Request, res: Response, next: NextFunction) => { try { const token: string = (await randomBytes(20)).toString('hex'); const user: User = await User.findOne({ where: { email: { [Op.iLike]: req.body.email } } }); if (!user) { throw new Error('User to reset not found'); } user.reset_password_token = <PASSWORD>; user.reset_token_expires = new Date(Date.now() + 3600000); await user.save(); mailer.setApiKey(secrets.SENDGRID_API_KEY); mailer.setSubstitutionWrappers('{{', '}}'); const url: string = req.body.url || `http://${req.headers.host}/api/reset/`; const message: MailData = { to: user.email, from: '<EMAIL>', subject: 'MBU Online Password Reset', templateId: 'b6cd8257-e07c-4390-9c58-cf2267e36e20', substitutions: { url: url, token: token }, content: [ { type: 'text/plain', value: 'Textual content' } ] }; await mailer.send(message) .then(() => res.status(status.OK).json(<MessageResponseDto>{ message: `An e-email has been sent to ${user.email} with further instructions` })) .catch((err) => res.status(status.INTERNAL_SERVER_ERROR).json(<ErrorResponseDto>{ error: err, message: 'Failed to send email' })); } catch (err) { return next(err); } }; export const reset = async (req: Request, res: Response) => { try { const user: User = await User.findOne({ where: { reset_password_token: req.body.token, reset_token_expires: { [Op.gt]: Date.now() } } }); if (!user) { throw new Error('User now found'); } user.password = <PASSWORD>; user.reset_password_token = <PASSWORD>; user.reset_token_expires = null; await user.save(); mailer.setApiKey(secrets.SENDGRID_API_KEY); mailer.setSubstitutionWrappers('{{', '}}'); const url: string = req.body.url || `http://${req.headers.host}/api/reset/`; const message: MailData = { to: user.email, from: '<EMAIL>', subject: 'MBU Online Password Changed', templateId: '6822bdf9-bdb2-4359-ab1a-6f5dc9ca2d2c', substitutions: { email: user.email }, content: [ { type: 'text/plain', value: 'Textual content' } ] }; await mailer.send(message) .then(() => res.status(status.OK).json(<MessageResponseDto>{ message: `Password change confirmation sent to ${user.email}` })) .catch((err) => res.status(status.INTERNAL_SERVER_ERROR).json(<ErrorResponseDto>{ error: err, message: 'Failed to send confirmation email' })); } catch (err) { return res.status(status.INTERNAL_SERVER_ERROR).json(<ErrorResponseDto>{ error: err, message: 'Reset password failed' }); } }; <file_sep>/src/server/models/validators.ts import { isEqual } from 'lodash'; export function durationValidator(periods: number[], duration: number): boolean { if (duration === 2) { return isEqual(periods.sort(), [2, 3]); } if (duration === 3) { return isEqual(periods.sort(), [1, 2, 3]); } return true; } <file_sep>/src/server/models/purchasable.model.ts import { Model, Column, Default, DataType, Table, Validator, ForeignKey, HasMany, BelongsToMany, Min } from 'sequelize-typescript'; import { Purchase } from '@models/purchase.model'; import { Registration } from '@models/registration.model'; import { Event } from '@models/event.model'; import { PurchasableInterface } from '@interfaces/purchasable.interface'; @Table({ underscored: true, tableName: 'Purchasables' }) export class Purchasable extends Model<Purchasable> implements PurchasableInterface { @Column({ allowNull: false }) public item!: string; @Column public description: string; @Default(false) @Column public has_size!: boolean; @Column({ type: DataType.DECIMAL(5, 2), allowNull: false }) public price!: number; @Column public maximum_age: number; @Column public minimum_age: number; @Min(0) @Column public purchaser_limit: number; @HasMany(() => Purchase, 'purchasable_id') public sold: Purchase[]; @BelongsToMany(() => Registration, () => Purchase, 'purchasable_id', 'registration_id') public buyers: Registration[]; @ForeignKey(() => Event) public event_id: number; public Purchase: Purchase; @Validator public maxGreaterThanMin(): void { if (this.maximum_age && this.minimum_age && (this.maximum_age < this.minimum_age)) { throw new Error('Max age must be greater than min'); } } public async getPurchaserCount(): Promise<number> { const purchases: Purchase[] = await Purchase.findAll({ where: { purchasable_id: this.id } }); return purchases.reduce((acc, cur) => acc += cur.quantity, 0); } } <file_sep>/src/server/routes/index/getIndex.ts import { Request, Response } from 'express'; import status from 'http-status-codes'; export const getIndex = (_req: Request, res: Response) => { res.status(status.OK).send('Welcome to the MBU API'); }; <file_sep>/src/client/src/validators/dateSpec.js import { expect } from 'chai' import date from './date'; describe('The date validator', () => { it('should validate a date', () => { expect(date()('01/11/2001')).to.be.true; expect(date()('02/21/2001')).to.be.true; }); it('should not validate a bad date', () => { expect(date()('00/00/0000')).to.be.false; expect(date()('02/30/2000')).to.be.false; expect(date()('13/20/2001')).to.be.false; }); it('should allow a custom format', () => { expect(date('DD/MM/YYYY')('23/01/2001')).to.be.true; expect(date('DD/MM/YYYY')('23/23/2001')).to.be.false; expect(date('YY/MM/DD')('17/01/31')).to.be.true; expect(date('YY/MM/DD')('17/28/20')).to.be.false; }); it('should enforce format strictly', () => { expect(date()('1/11/2001')).to.be.false; expect(date()('01/__/____')).to.be.false; }); }); <file_sep>/src/server/routes/badges.ts import { Router } from 'express'; import { isAuthorized } from '@middleware/isAuthorized'; import { UserRole } from '@interfaces/user.interface'; import { createBadge } from '@routes/badges/postBadges'; import { getBadges } from '@routes/badges/getBadges'; import { deleteBadge } from '@routes/badges/deleteBadges'; import { updateBadge } from '@routes/badges/updateBadges'; export const badgeRoutes = Router(); badgeRoutes.post('/', isAuthorized([UserRole.TEACHER]), createBadge); badgeRoutes.get('/', getBadges); badgeRoutes.delete('/:id', isAuthorized([UserRole.TEACHER]), deleteBadge); badgeRoutes.put('/:id', isAuthorized([UserRole.TEACHER]), updateBadge); <file_sep>/src/libs/interfaces/registration.interface.ts import { OfferingInterface, OfferingDto } from '@interfaces/offering.interface'; import { PreferenceInterface } from '@interfaces/preference.interface'; import { PurchasableDto, PurchasableInterface } from '@interfaces/purchasable.interface'; import { PurchaseInterface } from '@interfaces/purchase.interface'; import { AssignmentInterface } from '@interfaces/assignment.interface'; import { ScoutInterface } from '@interfaces/scout.interface'; export interface RegistrationInterface { id?: number; event_id?: number; scout_id?: number; notes?: string; preferences?: OfferingInterface[]; assignments?: OfferingInterface[]; purchases?: PurchasableInterface[]; } export interface RegistrationDto extends RegistrationInterface { event_id?: number; scout?: ScoutInterface; } export interface RegistrationDetailsDto extends RegistrationDto { preferences: OfferingDto<PreferenceInterface>[]; assignments: OfferingDto<AssignmentInterface>[]; purchases?: PurchasableDto<PurchaseInterface>[]; } export interface RegistrationPreferencesDto extends RegistrationDto { preferences: OfferingDto<PreferenceInterface>[]; } export interface RegistrationAssignmentsDto extends RegistrationDto { assignments: OfferingDto<AssignmentInterface>[]; } export interface RegistrationPurchasesDto extends RegistrationDto { purchases?: PurchasableDto<PurchaseInterface>[]; } export interface AssignmentRegistrationDto extends RegistrationDto { assignment?: AssignmentInterface; } export interface CreateRegistrationResponseDto { message: string; registration: RegistrationDto; } export interface RegistrationRequestDto { event_id?: string; notes?: string; } export interface CostCalculationResponseDto { cost: string; } export type RegistrationsResponseDto = RegistrationDetailsDto[]; <file_sep>/src/server/routes/scouts/updateScouts.ts import { Request, Response } from 'express'; import status from 'http-status-codes'; import { ErrorResponseDto } from '@interfaces/shared.interface'; import { Registration } from '@models/registration.model'; import { Preference } from '@models/preference.model'; import { UpdatePreferenceResponseDto } from '@interfaces/preference.interface'; import { Assignment } from '@models/assignment.model'; import { UpdateAssignmentResponseDto } from '@interfaces/assignment.interface'; import { Purchase } from '@models/purchase.model'; import { PurchaseResponseInterface } from '@interfaces/purchase.interface'; export const updatePreference = async (req: Request, res: Response) => { try { const [registration, preference]: [Registration, Preference] = await Promise.all([ Registration.findOne({ where: { id: req.params.registrationId, scout_id: req.params.scoutId } }), Preference.findOne({ where: { offering_id: req.params.offeringId, registration_id: req.params.registrationId } }) ]); if (!registration) { throw new Error('Registration to update not found'); } if (!preference) { throw new Error('Preference to update not found'); } await preference.update(req.body); return res.status(status.OK).json(<UpdatePreferenceResponseDto>{ message: 'Preference updated successfully', preference: preference }); } catch (err) { return res.status(status.BAD_REQUEST).json(<ErrorResponseDto>{ message: 'Error updating preference', error: err }); } }; export const updateAssignment = async (req: Request, res: Response) => { try { const [registration, assignment]: [Registration, Assignment] = await Promise.all([ Registration.findOne({ where: { id: req.params.registrationId, scout_id: req.params.scoutId } }), Assignment.findOne({ where: { offering_id: req.params.offeringId, registration_id: req.params.registrationId } }) ]); if (!registration) { throw new Error('Registration to update not found'); } if (!assignment) { throw new Error('Assignment to update not found'); } await assignment.update(req.body); return res.status(status.OK).json(<UpdateAssignmentResponseDto>{ message: 'Assignment updated successfully', assignment: assignment }); } catch (err) { return res.status(status.BAD_REQUEST).json(<ErrorResponseDto>{ message: 'Error updating assignment', error: err }); } }; export const updatePurchase = async (req: Request, res: Response) => { try { const [registration, purchase]: [Registration, Purchase] = await Promise.all([ Registration.findOne({ where: { id: req.params.registrationId, scout_id: req.params.scoutId } }), Purchase.findOne({ where: { purchasable_id: req.params.purchasableId, registration_id: req.params.registrationId } }) ]); if (!registration) { throw new Error('Registration to update not found'); } if (!purchase) { throw new Error('Purchase to update not found'); } await purchase.update(req.body); return res.status(status.OK).json(<PurchaseResponseInterface>{ message: 'Purchase updated successfully', purchase: purchase }); } catch (err) { return res.status(status.BAD_REQUEST).json(<ErrorResponseDto>{ message: 'Error updating purchase', error: 'err' }); } }; <file_sep>/tests/server/paymentsSpec.ts import supertest, { SuperTest } from 'supertest'; import * as async from 'async'; import status from 'http-status-codes'; import { expect } from 'chai'; import app from '@app/app'; import TestUtils, { RoleTokenObjects } from './testUtils'; import { Scout } from '@models/scout.model'; import { Event } from '@models/event.model'; import { Badge } from '@models/badge.model'; import testScouts from './testScouts'; import { ScoutInterface } from '@interfaces/scout.interface'; import { UserRole } from '@interfaces/user.interface'; import { CreateOfferingDto } from '@interfaces/offering.interface'; import { SuperTestResponse } from '@test/helpers/supertest.interface'; import { CreateOfferingResponseDto, IncomeCalculationResponseDto } from '@interfaces/event.interface'; import { CreatePurchasableDto, CreatePurchasablesResponseDto } from '@interfaces/purchasable.interface'; import { RegistrationRequestDto, CreateRegistrationResponseDto, CostCalculationResponseDto } from '@interfaces/registration.interface'; import { CreatePreferenceRequestDto } from '@interfaces/preference.interface'; import { CreatePurchaseRequestDto } from '@interfaces/purchase.interface'; import { CreateAssignmentRequestDto } from '@interfaces/assignment.interface'; const request = supertest(app); describe('payments', () => { let generatedUsers: RoleTokenObjects; let generatedTroop1: Scout[]; let generatedTroop2: Scout[]; let generatedEvents: Event[]; let generatedBadges: Badge[]; let offeringIds: number[]; let purchasableIds: number[]; let registrationIds: number[]; const badgeCost: string = '10.00'; const tShirtCost: string = '9.25'; const lunchCost: string = '12.00'; const scoutsGroup1: ScoutInterface[] = testScouts(2); const scoutsGroup2: ScoutInterface[] = testScouts(2); beforeEach(async () => { await TestUtils.dropDb(); generatedUsers = await TestUtils.generateTokens([UserRole.ADMIN, UserRole.TEACHER, UserRole.COORDINATOR, 'coordinator2' as any]); generatedEvents = await TestUtils.createEvents(); generatedBadges = await TestUtils.createBadges(); generatedTroop1 = await TestUtils.createScoutsForUser(generatedUsers.coordinator, scoutsGroup1); generatedTroop2 = await TestUtils.createScoutsForUser(generatedUsers.coordinator2, scoutsGroup2); }); beforeEach(() => { offeringIds = []; purchasableIds = []; registrationIds = []; }); beforeEach((done) => { async.series([ // Create offerings for an event (cb) => { request.post('/api/events/' + generatedEvents[0].id + '/badges') .set('Authorization', generatedUsers.admin.token) .send(<CreateOfferingDto>{ badge_id: generatedBadges[0].id, offering: { duration: 1, periods: [1, 2, 3], price: badgeCost } }) .expect(status.CREATED) .end((err, res: SuperTestResponse<CreateOfferingResponseDto>) => { if (err) { return cb(err); } offeringIds.push(res.body.event.offerings[0].details.id); return cb(); }); }, (cb) => { request.post('/api/events/' + generatedEvents[0].id + '/badges') .set('Authorization', generatedUsers.admin.token) .send(<CreateOfferingDto>{ badge_id: generatedBadges[1].id, offering: { duration: 2, periods: [2, 3] } }) .expect(status.CREATED) .end((err, res: SuperTestResponse<CreateOfferingResponseDto>) => { if (err) { return cb(err); } offeringIds.push(res.body.event.offerings[1].details.id); return cb(); }); }, (cb) => { request.post('/api/events/' + generatedEvents[1].id + '/badges') .set('Authorization', generatedUsers.admin.token) .send(<CreateOfferingDto>{ badge_id: generatedBadges[1].id, offering: { duration: 2, periods: [2, 3], price: badgeCost } }) .expect(status.CREATED) .end((err, res: SuperTestResponse<CreateOfferingResponseDto>) => { if (err) { return cb(err); } offeringIds.push(res.body.event.offerings[0].details.id); return cb(); }); }, // Create purchasable items for an event (cb) => { request.post('/api/events/' + generatedEvents[0].id + '/purchasables') .set('Authorization', generatedUsers.admin.token) .send(<CreatePurchasableDto>{ item: 'T-Shirt', price: tShirtCost }) .expect(status.CREATED) .end((err, res: SuperTestResponse<CreatePurchasablesResponseDto>) => { if (err) { return cb(err); } purchasableIds.push(res.body.purchasables[0].id); return cb(); }); }, (cb) => { request.post('/api/events/' + generatedEvents[0].id + '/purchasables') .set('Authorization', generatedUsers.admin.token) .send(<CreatePurchasableDto>{ item: 'Lunch', price: lunchCost }) .expect(status.CREATED) .end((err, res: SuperTestResponse<CreatePurchasablesResponseDto>) => { if (err) { return cb(err); } purchasableIds.push(res.body.purchasables[1].id); return cb(); }); }, // Register scout for an event (cb) => { request.post('/api/scouts/' + generatedTroop1[0].id + '/registrations') .set('Authorization', generatedUsers.coordinator.token) .send(<RegistrationRequestDto>{ event_id: generatedEvents[0].id }) .expect(status.CREATED) .end((err, res: SuperTestResponse<CreateRegistrationResponseDto>) => { if (err) { return cb(err); } registrationIds.push(res.body.registration.id); return cb(); }); }, // Create preferences for a registration (cb) => { request.post('/api/scouts/' + generatedTroop1[0].id + '/registrations/' + registrationIds[0] + '/preferences') .set('Authorization', generatedUsers.coordinator.token) .send(<CreatePreferenceRequestDto>{ offering: offeringIds[1], rank: 1 }) .expect(status.CREATED, cb); }, (cb) => { request.post('/api/scouts/' + generatedTroop1[0].id + '/registrations/' + registrationIds[0] + '/preferences') .set('Authorization', generatedUsers.coordinator.token) .send(<CreatePreferenceRequestDto>{ offering: offeringIds[0], rank: 2 }) .expect(status.CREATED, cb); }, (cb) => { request.post('/api/scouts/' + generatedTroop1[0].id + '/registrations/' + registrationIds[0] + '/purchases') .set('Authorization', generatedUsers.coordinator.token) .send(<CreatePurchaseRequestDto>{ // T-Shirt purchasable: purchasableIds[0], quantity: 3 }) .expect(status.CREATED, cb); }, (cb) => { request.post('/api/scouts/' + generatedTroop1[0].id + '/registrations/' + registrationIds[0] + '/purchases') .set('Authorization', generatedUsers.coordinator.token) .send(<CreatePurchaseRequestDto>{ // Lunch purchasable: purchasableIds[1], quantity: 1 }) .expect(status.CREATED, cb); }, // Register another scout for an event (cb) => { request.post('/api/scouts/' + generatedTroop1[1].id + '/registrations') .set('Authorization', generatedUsers.coordinator.token) .send(<RegistrationRequestDto>{ event_id: generatedEvents[0].id }) .expect(status.CREATED) .end((err, res: SuperTestResponse<CreateRegistrationResponseDto>) => { if (err) { return cb(err); } registrationIds.push(res.body.registration.id); return cb(); }); }, // Create preferences for a registration (cb) => { request.post('/api/scouts/' + generatedTroop1[1].id + '/registrations/' + registrationIds[1] + '/preferences') .set('Authorization', generatedUsers.coordinator.token) .send(<CreatePreferenceRequestDto>{ offering: offeringIds[1], rank: 1 }) .expect(status.CREATED, cb); }, (cb) => { request.post('/api/scouts/' + generatedTroop1[1].id + '/registrations/' + registrationIds[1] + '/preferences') .set('Authorization', generatedUsers.coordinator.token) .send(<CreatePreferenceRequestDto>{ offering: offeringIds[0], rank: 2 }) .expect(status.CREATED, cb); }, (cb) => { request.post('/api/scouts/' + generatedTroop1[1].id + '/registrations/' + registrationIds[1] + '/purchases') .set('Authorization', generatedUsers.coordinator.token) .send(<CreatePurchaseRequestDto>{ // T-Shirt purchasable: purchasableIds[0], quantity: 1 }) .expect(status.CREATED, cb); }, (cb) => { request.post('/api/scouts/' + generatedTroop1[1].id + '/registrations/' + registrationIds[1] + '/purchases') .set('Authorization', generatedUsers.coordinator.token) .send(<CreatePurchaseRequestDto>{ // Lunch purchasable: purchasableIds[1], quantity: 3 }) .expect(status.CREATED, cb); }, // Register the same scout for a different event (cb) => { request.post('/api/scouts/' + generatedTroop1[1].id + '/registrations') .set('Authorization', generatedUsers.coordinator.token) .send(<RegistrationRequestDto>{ event_id: generatedEvents[1].id }) .expect(status.CREATED) .end((err, res: SuperTestResponse<CreateRegistrationResponseDto>) => { if (err) { return cb(err); } registrationIds.push(res.body.registration.id); return cb(); }); }, (cb) => { request.post('/api/scouts/' + generatedTroop1[1].id + '/registrations/' + registrationIds[2] + '/preferences') .set('Authorization', generatedUsers.coordinator.token) .send(<CreatePreferenceRequestDto>{ offering: offeringIds[2], rank: 1 }) .expect(status.CREATED, cb); }, // Register a scout from a different troop (cb) => { request.post('/api/scouts/' + generatedTroop2[1].id + '/registrations') .set('Authorization', generatedUsers.coordinator2.token) .send(<RegistrationRequestDto>{ event_id: generatedEvents[0].id }) .expect(status.CREATED) .end((err, res: SuperTestResponse<CreateRegistrationResponseDto>) => { if (err) { return cb(err); } registrationIds.push(res.body.registration.id); return cb(); }); }, (cb) => { request.post('/api/scouts/' + generatedTroop2[1].id + '/registrations/' + registrationIds[3] + '/preferences') .set('Authorization', generatedUsers.coordinator2.token) .send(<CreatePreferenceRequestDto>{ offering: offeringIds[2], rank: 1 }) .expect(status.CREATED, cb); }, ], done); }); afterAll(async () => { await TestUtils.dropDb(); await TestUtils.closeDb(); }); describe('calculating potential prices', () => { test('should calculate for an individual scout', (done) => { request.get('/api/scouts/' + generatedTroop1[0].id + '/registrations/' + registrationIds[0] + '/projectedCost') .set('Authorization', generatedUsers.coordinator.token) .expect(status.OK) .end((err, res: SuperTestResponse<CostCalculationResponseDto>) => { if (err) { return done(err); } expect(res.body.cost).to.equal('59.75'); return done(); }); }); test('should calculate a different cost for another scout', (done) => { request.get('/api/scouts/' + generatedTroop1[1].id + '/registrations/' + registrationIds[1] + '/projectedCost') .set('Authorization', generatedUsers.coordinator.token) .expect(status.OK) .end((err, res: SuperTestResponse<CostCalculationResponseDto>) => { if (err) { return done(err); } expect(res.body.cost).to.equal('65.25'); return done(); }); }); test('should calculate a different cost for another scout for another event', (done) => { request.get('/api/scouts/' + generatedTroop1[1].id + '/registrations/' + registrationIds[2] + '/projectedCost') .set('Authorization', generatedUsers.coordinator.token) .expect(status.OK) .end((err, res: SuperTestResponse<CostCalculationResponseDto>) => { if (err) { return done(err); } expect(res.body.cost).to.equal('20.00'); return done(); }); }); test('should get the potential cost of attendance for a troop', (done) => { request.get('/api/users/' + generatedUsers.coordinator.profile.id + '/events/' + generatedEvents[0].id + '/projectedCost') .set('Authorization', generatedUsers.coordinator.token) .expect(status.OK) .end((err, res: SuperTestResponse<CostCalculationResponseDto>) => { if (err) { return done(err); } expect(res.body.cost).to.equal('125.00'); return done(); }); }); test('should get the potential cost of attendance for a troop for another event', (done) => { request.get('/api/users/' + generatedUsers.coordinator.profile.id + '/events/' + generatedEvents[1].id + '/projectedCost') .set('Authorization', generatedUsers.coordinator.token) .expect(status.OK) .end((err, res: SuperTestResponse<CostCalculationResponseDto>) => { if (err) { return done(err); } expect(res.body.cost).to.equal('20.00'); return done(); }); }); test('should get the potential cost of attendence for a different troop', (done) => { request.get('/api/users/' + generatedUsers.coordinator2.profile.id + '/events/' + generatedEvents[0].id + '/projectedCost') .set('Authorization', generatedUsers.coordinator2.token) .expect(status.OK) .end((err, res: SuperTestResponse<CostCalculationResponseDto>) => { if (err) { return done(err); } expect(res.body.cost).to.equal('20.00'); return done(); }); }); test('should get the total potential income from an event', (done) => { request.get('/api/events/' + generatedEvents[0].id + '/potentialIncome') .set('Authorization', generatedUsers.admin.token) .expect(status.OK) .end((err, res: SuperTestResponse<IncomeCalculationResponseDto>) => { if (err) { return done(err); } expect(res.body.income).to.equal('145.00'); return done(); }); }); test('should get the total potential income from another event', (done) => { request.get('/api/events/' + generatedEvents[1].id + '/potentialIncome') .set('Authorization', generatedUsers.admin.token) .expect(status.OK) .end((err, res: SuperTestResponse<IncomeCalculationResponseDto>) => { if (err) { return done(err); } expect(res.body.income).to.equal('20.00'); return done(); }); }); test('should fail for an invalid user', (done) => { request.get('/api/users/1337/events/' + generatedEvents[0].id + '/projectedCost') .set('Authorization', generatedUsers.admin.token) .expect(status.BAD_REQUEST, done); }); test('should fail for an invalid event', (done) => { request.get('/api/users/' + generatedUsers.coordinator2.profile.id + '/events/13370/projectedCost') .set('Authorization', generatedUsers.admin.token) .expect(status.BAD_REQUEST, done); }); test('should fail for an invalid scout', (done) => { request.get('/api/scouts/1337/registrations/' + registrationIds[0] + '/projectedCost') .set('Authorization', generatedUsers.coordinator.token) .expect(status.BAD_REQUEST, done); }); test('should fail for an invalid registration', (done) => { request.get('/api/scouts/' + generatedTroop1[1].id + '/registrations/1337/projectedCost') .set('Authorization', generatedUsers.coordinator.token) .expect(status.BAD_REQUEST, done); }); test('should fail to get total potential income from an invalid event', (done) => { request.get('/api/events/1337/potentialIncome') .set('Authorization', generatedUsers.admin.token) .expect(status.BAD_REQUEST, done); }); }); describe('calculating real prices', () => { beforeEach((done) => { async.series([ (cb) => { request.post('/api/scouts/' + generatedTroop1[0].id + '/registrations/' + registrationIds[0] + '/assignments') .set('Authorization', generatedUsers.teacher.token) .send(<CreateAssignmentRequestDto>{ periods: [2, 3], offering: offeringIds[1] }) .expect(status.CREATED, cb); }, (cb) => { request.post('/api/scouts/' + generatedTroop1[1].id + '/registrations/' + registrationIds[1] + '/assignments') .set('Authorization', generatedUsers.teacher.token) .send(<CreateAssignmentRequestDto>{ periods: [1], offering: offeringIds[0] }) .expect(status.CREATED, cb); }, (cb) => { request.post('/api/scouts/' + generatedTroop1[1].id + '/registrations/' + registrationIds[2] + '/assignments') .set('Authorization', generatedUsers.teacher.token) .send(<CreateAssignmentRequestDto>{ periods: [1], offering: offeringIds[0] }) .expect(status.CREATED, cb); }, (cb) => { request.post('/api/scouts/' + generatedTroop2[1].id + '/registrations/' + registrationIds[3] + '/assignments') .set('Authorization', generatedUsers.teacher.token) .send(<CreateAssignmentRequestDto>{ offering: offeringIds[2], periods: [1] }) .expect(status.CREATED, cb); }, ], done); }); test('should calculate the actual cost for an individual scout', (done) => { request.get('/api/scouts/' + generatedTroop1[0].id + '/registrations/' + registrationIds[0] + '/cost') .set('Authorization', generatedUsers.coordinator.token) .expect(status.OK) .end((err, res: SuperTestResponse<CostCalculationResponseDto>) => { if (err) { return done(err); } expect(res.body.cost).to.equal('49.75'); return done(); }); }); test('should calculate the actual cost for another scout', (done) => { request.get('/api/scouts/' + generatedTroop1[1].id + '/registrations/' + registrationIds[1] + '/cost') .set('Authorization', generatedUsers.coordinator.token) .expect(status.OK) .end((err, res: SuperTestResponse<CostCalculationResponseDto>) => { if (err) { return done(err); } expect(res.body.cost).to.equal('65.25'); return done(); }); }); test('should calculate the actual cost for another scout and different registration', (done) => { request.get('/api/scouts/' + generatedTroop1[1].id + '/registrations/' + registrationIds[2] + '/cost') .set('Authorization', generatedUsers.coordinator.token) .expect(status.OK) .end((err, res: SuperTestResponse<CostCalculationResponseDto>) => { if (err) { return done(err); } expect(res.body.cost).to.equal('20.00'); return done(); }); }); test('should get the cost of attendance for a troop', (done) => { request.get('/api/users/' + generatedUsers.coordinator.profile.id + '/events/' + generatedEvents[0].id + '/cost') .set('Authorization', generatedUsers.coordinator.token) .expect(status.OK) .end((err, res: SuperTestResponse<CostCalculationResponseDto>) => { if (err) { return done(err); } expect(res.body.cost).to.equal('115.00'); return done(); }); }); test('should get the cost of attendance for a troop for another event', (done) => { request.get('/api/users/' + generatedUsers.coordinator.profile.id + '/events/' + generatedEvents[1].id + '/cost') .set('Authorization', generatedUsers.coordinator.token) .expect(status.OK) .end((err, res: SuperTestResponse<CostCalculationResponseDto>) => { if (err) { return done(err); } expect(res.body.cost).to.equal('20.00'); return done(); }); }); test('should get the cost of attendence for a different troop', (done) => { request.get('/api/users/' + generatedUsers.coordinator2.profile.id + '/events/' + generatedEvents[0].id + '/cost') .set('Authorization', generatedUsers.coordinator2.token) .expect(status.OK) .end((err, res: SuperTestResponse<CostCalculationResponseDto>) => { if (err) { return done(err); } expect(res.body.cost).to.equal('20.00'); return done(); }); }); test('should get the real income from an event', (done) => { request.get('/api/events/' + generatedEvents[0].id + '/income') .set('Authorization', generatedUsers.admin.token) .expect(status.OK) .end((err, res: SuperTestResponse<IncomeCalculationResponseDto>) => { if (err) { return done(err); } expect(res.body.income).to.equal('135.00'); return done(); }); }); test('should get the real income from another event', (done) => { request.get('/api/events/' + generatedEvents[1].id + '/income') .set('Authorization', generatedUsers.admin.token) .expect(status.OK) .end((err, res: SuperTestResponse<IncomeCalculationResponseDto>) => { if (err) { return done(err); } expect(res.body.income).to.equal('20.00'); return done(); }); }); test('should fail for an invalid user', (done) => { request.get('/api/users/1337/events/' + generatedEvents[0].id + '/cost') .set('Authorization', generatedUsers.admin.token) .expect(status.BAD_REQUEST, done); }); test('should fail for an invalid event', (done) => { request.get('/api/users/' + generatedUsers.coordinator2.profile.id + '/events/13370/cost') .set('Authorization', generatedUsers.admin.token) .expect(status.BAD_REQUEST, done); }); test('should fail for an invalid scout', (done) => { request.get('/api/scouts/1337/registrations/' + registrationIds[0] + '/cost') .set('Authorization', generatedUsers.coordinator.token) .expect(status.BAD_REQUEST, done); }); test('should fail for an invalid registration', (done) => { request.get('/api/scouts/' + generatedTroop1[1].id + '/registrations/1337/cost') .set('Authorization', generatedUsers.coordinator.token) .expect(status.BAD_REQUEST, done); }); test('should fail to get total income from an invalid event', (done) => { request.get('/api/events/1337/income') .set('Authorization', generatedUsers.admin.token) .expect(status.BAD_REQUEST, done); }); }); }); <file_sep>/tests/server/classSizeSpec.ts import supertest from 'supertest'; import * as async from 'async'; import status from 'http-status-codes'; import { expect } from 'chai'; import app from '@app/app'; import TestUtils, { RoleTokenObjects } from './testUtils'; import { Badge } from '@models/badge.model'; import { Event } from '@models/event.model'; import { Scout } from '@models/scout.model'; import { Offering } from '@models/offering.model'; import { Assignment } from '@models/assignment.model'; import { Registration } from '@models/registration.model'; import testScouts from './testScouts'; import { CreateOfferingDto, OfferingInterface } from '@interfaces/offering.interface'; import { CreateAssignmentRequestDto, CreateAssignmentResponseDto } from '@interfaces/assignment.interface'; import { SuperTestResponse } from '@test/helpers/supertest.interface'; import { CreateRegistrationResponseDto } from '@interfaces/registration.interface'; import { CreateOfferingResponseDto, EventsResponseDto, ClassSizeDto } from '@interfaces/event.interface'; const request = supertest(app); describe('Class sizes', () => { let badges: Badge[]; let events: Event[]; let generatedUsers: RoleTokenObjects; let generatedScouts: Scout[]; let registrationIds: number[]; beforeAll(async () => { await TestUtils.dropDb(); }); beforeAll(async () => { generatedUsers = await TestUtils.generateTokens(); }); beforeEach(async () => { await TestUtils.dropTable([Event, Offering, Badge, Assignment, Registration]); }); beforeEach(async () => { badges = await TestUtils.createBadges(); events = await TestUtils.createEvents(); generatedScouts = await TestUtils.createScoutsForUser(generatedUsers.coordinator, testScouts(6)); }); beforeEach((done) => { registrationIds = []; async.forEachOfSeries(generatedScouts, (scout, index, cb) => { request.post('/api/scouts/' + scout.id + '/registrations') .set('Authorization', generatedUsers.coordinator.token) .send({ event_id: events[0].id }) .expect(status.CREATED) .end((err, res: SuperTestResponse<CreateRegistrationResponseDto>) => { if (err) { return done(err); } registrationIds.push(res.body.registration.id); return cb(); }); }, (err) => { done(err); }); }); afterAll(async () => { await TestUtils.dropDb(); await TestUtils.closeDb(); }); describe('when offerings do not exist', () => { let postData: CreateOfferingDto; beforeEach(() => { postData = { badge_id: badges[1].id, offering: { duration: 1, periods: [1, 2, 3], price: '10.00', requirements: ['1', '2', '3a', '3b'] } }; }); test('should default to 20 as the size limit', (done) => { request.post('/api/events/' + events[0].id + '/badges') .set('Authorization', generatedUsers.admin.token) .send(postData) .expect(status.CREATED) .end((err, res: SuperTestResponse<CreateOfferingResponseDto>) => { if (err) { return done(err); } const event = res.body.event; expect(event.offerings).to.have.lengthOf(1); expect(event.offerings[0].details.size_limit).to.equal(20); return done(); }); }); test('should accept an input for class size', (done) => { postData.offering.size_limit = 30; request.post('/api/events/' + events[0].id + '/badges') .set('Authorization', generatedUsers.admin.token) .send(postData) .expect(status.CREATED) .end((err, res: SuperTestResponse<CreateOfferingResponseDto>) => { if (err) { return done(err); } const event = res.body.event; expect(event.offerings).to.have.lengthOf(1); expect(event.offerings[0].details.size_limit).to.equal(30); return done(); }); }); test('should not allow a negative class size', (done) => { postData.offering.size_limit = -1; request.post('/api/events/' + events[0].id + '/badges') .set('Authorization', generatedUsers.admin.token) .send(postData) .expect(status.BAD_REQUEST, done); }); test('should expect a number', (done) => { postData.offering.size_limit = 'hello' as any; request.post('/api/events/' + events[0].id + '/badges') .set('Authorization', generatedUsers.admin.token) .send(postData) .expect(status.BAD_REQUEST, done); }); }); describe('when an offering exists with a size limit of 1', () => { let offering: OfferingInterface; let assignmentData: CreateAssignmentRequestDto; beforeEach((done) => { const postData: CreateOfferingDto = { badge_id: badges[1].id, offering: { duration: 1, periods: [1, 2, 3], price: '10.00', requirements: ['1', '2', '3a', '3b'], size_limit: 1 } }; request.post('/api/events/' + events[0].id + '/badges') .set('Authorization', generatedUsers.admin.token) .send(postData) .expect(status.CREATED) .end((err, res: SuperTestResponse<CreateOfferingResponseDto>) => { if (err) { return done(err); } const event = res.body.event; offering = event.offerings[0]; return done(); }); }); beforeEach(() => { assignmentData = { periods: [1], offering: (offering as any).details.id }; }); test('should get the allowed class size', (done) => { request.get('/api/events?id=' + events[0].id) .expect(status.OK) .end((err, res: SuperTestResponse<EventsResponseDto>) => { if (err) { return done(err); } const event = res.body[0]; expect(event.offerings.length).to.equal(1); const offeringResponse = event.offerings[0]; expect(offeringResponse.details.size_limit).to.equal(1); return done(); }); }); test('should know that there are no enrolled scouts', (done) => { request.get('/api/events/' + events[0].id + '/badges/' + offering.id + '/limits') .set('Authorization', generatedUsers.teacher.token) .expect(status.OK) .end((err, res: SuperTestResponse<ClassSizeDto>) => { if (err) { return done(err); } const sizeInfo = res.body; expect(sizeInfo).to.deep.equal({ size_limit: 1, total: 0, 1: 0, 2: 0, 3: 0 }); return done(); }); }); test('should allow joining if under the limit for a period', (done) => { request.post('/api/scouts/' + generatedScouts[0].id + '/registrations/' + registrationIds[0] + '/assignments') .set('Authorization', generatedUsers.teacher.token) .send(assignmentData) .expect(status.CREATED, done); }); test('should allow joining multiple periods under the limit', (done) => { async.series([ (cb) => { request.post('/api/scouts/' + generatedScouts[0].id + '/registrations/' + registrationIds[0] + '/assignments') .set('Authorization', generatedUsers.teacher.token) .send(assignmentData) .expect(status.CREATED, cb); }, (cb) => { assignmentData.periods = [2]; request.post('/api/scouts/' + generatedScouts[1].id + '/registrations/' + registrationIds[1] + '/assignments') .set('Authorization', generatedUsers.teacher.token) .send(assignmentData) .expect(status.CREATED, cb); } ], done); }); describe('and one scout has been assigned', () => { let offeringId: number; beforeEach((done) => { request.post('/api/scouts/' + generatedScouts[0].id + '/registrations/' + registrationIds[0] + '/assignments') .set('Authorization', generatedUsers.teacher.token) .send(assignmentData) .expect(status.CREATED) .end((err, res: SuperTestResponse<CreateAssignmentResponseDto>) => { if (err) { return done(err); } offeringId = res.body.registration.assignments[0].offering_id; return done(); }); }); test('should know that there is one scout registered', (done) => { request.get('/api/events/' + events[0].id + '/badges/' + offering.id + '/limits') .set('Authorization', generatedUsers.teacher.token) .expect(status.OK) .end((err, res: SuperTestResponse<ClassSizeDto>) => { if (err) { return done(err); } const sizeInfo = res.body; expect(sizeInfo).to.deep.equal({ size_limit: 1, total: 1, 1: 1, 2: 0, 3: 0 }); return done(); }); }); test('should not allow the scout to join a different period', (done) => { request.put('/api/scouts/' + generatedScouts[0].id + '/registrations/' + registrationIds[0] + '/assignments/' + assignmentData.offering) .set('Authorization', generatedUsers.teacher.token) .send(<CreateAssignmentRequestDto>{ periods: [3] }) .expect(status.OK, done); }); test('should allow a scout to join a different period', (done) => { assignmentData.periods = [2]; request.post('/api/scouts/' + generatedScouts[1].id + '/registrations/' + registrationIds[1] + '/assignments') .set('Authorization', generatedUsers.teacher.token) .send(assignmentData) .expect(status.CREATED, done); }); test('should not allow another scout to join the same period', (done) => { request.post('/api/scouts/' + generatedScouts[1].id + '/registrations/' + registrationIds[1] + '/assignments') .set('Authorization', generatedUsers.teacher.token) .send(assignmentData) .expect(status.BAD_REQUEST, done); }); test('should allow setting completions for that scout', (done) => { request.put('/api/scouts/' + generatedScouts[0].id + '/registrations/' + registrationIds[0] + '/assignments/' + offeringId) .set('Authorization', generatedUsers.admin.token) .send(<CreateAssignmentRequestDto>{ completions: ['1'] }) .expect(status.OK, done); }); describe('and a scout has joined a different period', () => { beforeEach((done) => { assignmentData.periods = [2]; request.post('/api/scouts/' + generatedScouts[1].id + '/registrations/' + registrationIds[1] + '/assignments') .set('Authorization', generatedUsers.teacher.token) .send(assignmentData) .expect(status.CREATED, done); }); test('should not allow editing the scout to be in a full class', (done) => { request.put('/api/scouts/' + generatedScouts[1].id + '/registrations/' + registrationIds[1] + '/assignments/' + assignmentData.offering) .set('Authorization', generatedUsers.teacher.token) .send(<CreateAssignmentRequestDto>{ periods: [1] }) .expect(status.BAD_REQUEST, done); }); }); }); }); describe('when a 2 period offering exists', () => { let offering: OfferingInterface; let assignmentData: CreateAssignmentRequestDto; beforeEach((done) => { const postData: CreateOfferingDto = { badge_id: badges[1].id, offering: { duration: 2, periods: [2, 3], price: '10.00', requirements: ['1', '2', '3a', '3b'], size_limit: 3 } }; request.post('/api/events/' + events[0].id + '/badges') .set('Authorization', generatedUsers.admin.token) .send(postData) .expect(status.CREATED) .end((err, res: SuperTestResponse<CreateOfferingResponseDto>) => { if (err) { return done(err); } const event = res.body.event; offering = event.offerings[0]; return done(); }); }); beforeEach(() => { assignmentData = { periods: [1], offering: (offering as any).details.id }; }); test('should know that there are no scouts assigned', (done) => { request.get('/api/events/' + events[0].id + '/badges/' + offering.id + '/limits') .set('Authorization', generatedUsers.teacher.token) .expect(status.OK) .end((err, res: SuperTestResponse<ClassSizeDto>) => { if (err) { return done(err); } const sizeInfo = res.body; expect(sizeInfo).to.deep.equal({ size_limit: 3, total: 0, 1: 0, 2: 0, 3: 0 }); return done(); }); }); describe('when a scout is assigned', () => { beforeEach((done) => { request.post('/api/scouts/' + generatedScouts[0].id + '/registrations/' + registrationIds[0] + '/assignments') .set('Authorization', generatedUsers.teacher.token) .send(assignmentData) .expect(status.CREATED, done); }); test('should know there is only one scout registered', (done) => { request.get('/api/events/' + events[0].id + '/badges/' + offering.id + '/limits') .set('Authorization', generatedUsers.teacher.token) .expect(status.OK) .end((err, res: SuperTestResponse<ClassSizeDto>) => { if (err) { return done(err); } const sizeInfo = res.body; expect(sizeInfo).to.deep.equal({ size_limit: 3, total: 1, 1: 1, 2: 0, 3: 0 }); return done(); }); }); }); }); describe('when an offering exists with a limit of 3', () => { let offering: OfferingInterface; let assignmentData: CreateAssignmentRequestDto; beforeEach((done) => { const postData: CreateOfferingDto = { badge_id: badges[1].id, offering: { duration: 1, periods: [1, 2, 3], price: '10.00', requirements: ['1', '2', '3a', '3b'], size_limit: 3 } }; request.post('/api/events/' + events[0].id + '/badges') .set('Authorization', generatedUsers.admin.token) .send(postData) .expect(status.CREATED) .end((err, res: SuperTestResponse<CreateOfferingResponseDto>) => { if (err) { return done(err); } const event = res.body.event; offering = event.offerings[0]; return done(); }); }); beforeEach(() => { assignmentData = { periods: [1], offering: (offering as any).details.id }; }); test('should know that there are no scouts assigned', (done) => { request.get('/api/events/' + events[0].id + '/badges/' + offering.id + '/limits') .set('Authorization', generatedUsers.teacher.token) .expect(status.OK) .end((err, res: SuperTestResponse<ClassSizeDto>) => { if (err) { return done(err); } const sizeInfo = res.body; expect(sizeInfo).to.deep.equal({ size_limit: 3, total: 0, 1: 0, 2: 0, 3: 0 }); return done(); }); }); describe('and scouts have been assigned', () => { beforeEach((done) => { async.series([ (cb) => { request.post('/api/scouts/' + generatedScouts[0].id + '/registrations/' + registrationIds[0] + '/assignments') .set('Authorization', generatedUsers.teacher.token) .send(assignmentData) .expect(status.CREATED, cb); }, (cb) => { request.post('/api/scouts/' + generatedScouts[1].id + '/registrations/' + registrationIds[1] + '/assignments') .set('Authorization', generatedUsers.teacher.token) .send(assignmentData) .expect(status.CREATED, cb); }, (cb) => { request.post('/api/scouts/' + generatedScouts[2].id + '/registrations/' + registrationIds[2] + '/assignments') .set('Authorization', generatedUsers.teacher.token) .send(assignmentData) .expect(status.CREATED, cb); }, (cb) => { assignmentData.periods = [2]; cb(); }, (cb) => { request.post('/api/scouts/' + generatedScouts[3].id + '/registrations/' + registrationIds[3] + '/assignments') .set('Authorization', generatedUsers.teacher.token) .send(assignmentData) .expect(status.CREATED, cb); } ], done); }); test('should return the correct class sizes', (done) => { request.get('/api/events/' + events[0].id + '/badges/' + offering.id + '/limits') .set('Authorization', generatedUsers.teacher.token) .expect(status.OK) .end((err, res: SuperTestResponse<ClassSizeDto>) => { if (err) { return done(err); } const sizeInfo = res.body; expect(sizeInfo).to.deep.equal({ size_limit: 3, total: 4, 1: 3, 2: 1, 3: 0 }); return done(); }); }); test('should not allow joining a full class period', (done) => { assignmentData.periods = [1]; request.post('/api/scouts/' + generatedScouts[5].id + '/registrations/' + registrationIds[5] + '/assignments') .set('Authorization', generatedUsers.teacher.token) .send(assignmentData) .expect(status.BAD_REQUEST, done); }); test('should allow joining a class period with room', (done) => { assignmentData.periods = [2]; request.post('/api/scouts/' + generatedScouts[5].id + '/registrations/' + registrationIds[5] + '/assignments') .set('Authorization', generatedUsers.teacher.token) .send(assignmentData) .expect(status.CREATED, done); }); }); }); }); <file_sep>/src/libs/interfaces/badge.interface.ts export interface BadgeInterface { id?: number; name?: string; description?: string; notes?: string; } export interface BadgeDto<K = any> extends BadgeInterface { details?: K; } export interface BadgeResponseDto { message: string; badge: BadgeInterface; } export type CreateUpdateBadgeDto = BadgeInterface; export type BadgesResponseDto = BadgeInterface[]; <file_sep>/src/client/src/validators/afterDate.js import moment from 'moment'; export default (afterDate, format = 'MM/DD/YYYY') => { return (value, parentVm) => { const compareTo = typeof afterDate === 'function' ? afterDate.call(this, parentVm) : parentVm[afterDate] const compareDate = moment(compareTo, format); const testDate = moment(value, format); if (!testDate.isValid()) return false; if (!compareDate.isValid()) return true; return testDate.isAfter(moment(compareTo, format)); } }<file_sep>/src/server/config/passport.ts import passport from 'passport'; import { ExtractJwt, Strategy as JwtStrategy, StrategyOptions } from 'passport-jwt'; import config from './secrets'; import { User } from '@models/user.model'; const options: StrategyOptions = { secretOrKey: config.APP_SECRET, jwtFromRequest: ExtractJwt.fromAuthHeaderWithScheme('jwt') }; passport.use(new JwtStrategy(options, async (jwtPayload, done) => { try { const user: User = await User.findByPk(jwtPayload); if (!!user) { return done(null, user); } else { return done(null, false); } } catch (err) { return done(err, false); } })); <file_sep>/src/server/app.ts import 'module-alias/register'; import '@config/passport'; import express, { Request, Response, NextFunction } from 'express'; import bodyParser from 'body-parser'; import morgan from 'morgan'; import passport from 'passport'; import path from 'path'; import compression from 'compression'; import helmet from 'helmet'; import history from 'connect-history-api-fallback'; import webpack from 'webpack'; import webpackDevMiddleware from 'webpack-dev-middleware'; import webpackHotMiddleware from 'webpack-hot-middleware'; import { sequelize } from './db'; import { indexRoutes } from '@routes/index'; import { userRoutes } from '@routes/users'; import { eventRoutes } from '@routes/events'; import { badgeRoutes } from '@routes/badges'; import { scoutRoutes } from '@routes/scouts'; import { forgotPasswordRoutes } from '@routes/forgot'; const app = express(); const env = process.env.NODE_ENV || 'development'; const port = process.env.PORT || 3000; const morganFormat = ':method :url :status :res[content-length] - :response-time ms'; app.use(history()); app.use(compression()); app.use(helmet()); app.use(bodyParser.json()); app.use(bodyParser.urlencoded({ extended: false })); if (env === 'development') { app.use(morgan(morganFormat)); app.use((req, res, next) => { setTimeout(() => { next(); }, 500); }); } if (env === 'production') { app.use(morgan(morganFormat)); app.use(express.static(path.join(__dirname, '../client'))); } app.use((_req: Request, res: Response, next: NextFunction) => { if (env === 'development') { res.setHeader('Access-Control-Allow-Origin', 'http://localhost:8080'); } res.setHeader('Access-Control-Allow-Methods', 'GET, POST, OPTIONS, PUT, PATCH, DELETE'); res.setHeader('Access-Control-Allow-Headers', 'X-Requested-With,content-type,Authorization'); res.setHeader('Access-Control-Allow-Credentials', 'true'); next(); }); app.use(passport.initialize()); app.use('/api', indexRoutes); app.use('/api', userRoutes); app.use('/api', forgotPasswordRoutes); app.use('/api/events', eventRoutes); app.use('/api/badges', badgeRoutes); app.use('/api/scouts', scoutRoutes); if (env === 'development') { const config = require('../../../src/client/webpack.dev.js'); const compiler = webpack(config); app.use(webpackDevMiddleware(compiler)); app.use(webpackHotMiddleware(compiler)); app.get('*', (req, res) => { res.sendFile(path.join(compiler.outputPath, 'index.html')); }); } app.use((_req, res, _next) => { res.status(404).send(); }); if (!module.parent) { sequelize.sync().then(() => { app.listen(port, () => { console.log('Listening on port:', port); }); }); } export default app; <file_sep>/tests/server/eventsSpec.ts import supertest from 'supertest'; import * as async from 'async'; import status from 'http-status-codes'; import { expect } from 'chai'; import app from '@app/app'; import TestUtils from './testUtils'; import { Event } from '@models/event.model'; import { EventCreateDto, Semester, EventResponseDto, SetCurrentEventDto, CurrentEventResponseDto, GetCurrentEventDto, EventsResponseDto } from '@interfaces/event.interface'; import { UserRole } from '@interfaces/user.interface'; import { SuperTestResponse } from '@test/helpers/supertest.interface'; const request = supertest(app); describe('events', () => { let coordinatorToken: string; let adminToken: string; const badId = TestUtils.badId; beforeAll(async () => { await TestUtils.dropDb(); }); beforeAll(async () => { const generatedTokens = await TestUtils.generateTokens([UserRole.COORDINATOR, UserRole.ADMIN]); coordinatorToken = generatedTokens[UserRole.COORDINATOR].token; adminToken = generatedTokens[UserRole.ADMIN].token; }); beforeEach(async () => { await TestUtils.dropTable([Event]); }); afterAll(async () => { await TestUtils.dropDb(); await TestUtils.closeDb(); }); describe('creating an event', () => { const testEvent: EventCreateDto = { year: 2016, semester: Semester.SPRING, date: new Date(2016, 3, 14), registration_open: new Date(2016, 1, 12), registration_close: new Date(2016, 3, 1), price: 10 }; test('should create events with year and semester', (done) => { request.post('/api/events') .set('Authorization', adminToken) .send(testEvent) .expect(status.CREATED, done); }); test('should require authorization as admin', (done) => { request.post('/api/events') .set('Authorization', coordinatorToken) .send(testEvent) .expect(status.UNAUTHORIZED, done); }); test('should fail gracefully for a blank request', (done) => { request.post('/api/events') .set('Authorization', adminToken) .send({}) .expect(status.BAD_REQUEST, done); }); test('should ignore extra fields', (done) => { const postData = testEvent as any; postData.extra = 'extra data'; request.post('/api/events') .set('Authorization', adminToken) .send(postData) .expect(status.CREATED) .end((err, res: SuperTestResponse<EventResponseDto>) => { if (err) { return done(err); } expect((res.body.event as any).extra).not.to.exist; done(); }); }); }); describe('when events already exist', () => { let id1: string; let id2: string; const testEvent1: EventCreateDto = { year: 2016, semester: Semester.SPRING, date: new Date(2016, 3, 14), registration_open: new Date(2016, 1, 12), registration_close: new Date(2016, 3, 1), price: 10 }; const testEvent2: EventCreateDto = { year: 2015, semester: Semester.FALL, date: new Date(2015, 11, 11), registration_open: new Date(2015, 9, 10), registration_close: new Date(2015, 11, 1), price: 10 }; beforeEach((done) => { async.series([ (cb) => { request.post('/api/events') .set('Authorization', adminToken) .send(testEvent1) .expect(status.CREATED) .end((err, res) => { if (err) { return done(err); } id1 = res.body.event.id; cb(); }); }, (cb) => { request.post('/api/events') .set('Authorization', adminToken) .send(testEvent2) .expect(status.CREATED) .end((err, res) => { if (err) { return done(err); } id2 = res.body.event.id; cb(); }); } ], done); }); describe('the current event', () => { test('should set the current event', (done) => { request.post('/api/events/current') .set('Authorization', adminToken) .send(<SetCurrentEventDto>{ id: id1 }) .expect(status.OK) .end((err, res: SuperTestResponse<CurrentEventResponseDto>) => { if (err) { return done(err); } expect(res.body.currentEvent.id).to.equal(id1); done(); }); }); test('should not set for an invalid id', (done) => { request.post('/api/events/current') .set('Authorization', adminToken) .send(<SetCurrentEventDto>{ id: 10000 }) .expect(status.BAD_REQUEST, done); }); test('should not allow teachers to set', (done) => { request.post('/api/events/current') .send(<SetCurrentEventDto>{ id: id1 }) .expect(status.UNAUTHORIZED, done); }); test('should get the current event', (done) => { async.series([ (cb) => { request.post('/api/events/current') .set('Authorization', adminToken) .send({ id: id1 }) .expect(status.OK) .end((err, res: SuperTestResponse<CurrentEventResponseDto>) => { if (err) { return done(err); } expect(res.body.currentEvent.id).to.equal(id1); return cb(); }); }, (cb) => { request.get('/api/events/current') .expect(status.OK) .end((err, res: SuperTestResponse<GetCurrentEventDto>) => { if (err) { return done(err); } expect(res.body.id).to.equal(id1); return cb(); }); } ], done); }); test('should keep track of the latest value', (done) => { async.series([ (cb) => { request.post('/api/events/current') .set('Authorization', adminToken) .send({ id: id1 }) .expect(status.OK) .end((err, res: SuperTestResponse<CurrentEventResponseDto>) => { if (err) { return done(err); } expect(res.body.currentEvent.id).to.equal(id1); return cb(); }); }, (cb) => { request.get('/api/events/current') .expect(status.OK) .end((err, res: SuperTestResponse<GetCurrentEventDto>) => { if (err) { return done(err); } expect(res.body.id).to.equal(id1); return cb(); }); }, (cb) => { request.post('/api/events/current') .set('Authorization', adminToken) .send({ id: id2 }) .expect(status.OK) .end((err, res: SuperTestResponse<CurrentEventResponseDto>) => { if (err) { return done(err); } expect(res.body.currentEvent.id).to.equal(id2); return cb(); }); }, (cb) => { request.get('/api/events/current') .expect(status.OK) .end((err, res: SuperTestResponse<GetCurrentEventDto>) => { if (err) { return done(err); } expect(res.body.id).to.equal(id2); return cb(); }); } ], done); }); }); describe('getting an event', () => { test('should be able to get an event by id', (done) => { async.series([ (cb) => { request.get('/api/events?id=' + id1) .expect(status.OK) .end((err, res: SuperTestResponse<EventsResponseDto>) => { if (err) { return done(err); } const event = res.body[0]; expect(event.id).to.equal(id1); cb(); }); }, (cb) => { request.get('/api/events?id=' + id2) .expect(status.OK) .end((err, res: SuperTestResponse<EventsResponseDto>) => { if (err) { return done(err); } const event = res.body[0]; expect(event.id).to.equal(id2); cb(); }); } ], done); }); test('should get an event by year and semester', (done) => { async.series([ (cb) => { request.get('/api/events?year=' + testEvent1.year + '&semester=' + testEvent1.semester) .expect(status.OK) .end((err, res: SuperTestResponse<EventsResponseDto>) => { if (err) { return done(err); } const event = res.body[0]; expect(event.year).to.equal(testEvent1.year); expect(event.semester).to.equal(testEvent1.semester); cb(); }); }, (cb) => { request.get('/api/events?year=' + testEvent2.year + '&semester=' + testEvent2.semester) .expect(status.OK) .end((err, res: SuperTestResponse<EventsResponseDto>) => { if (err) { return done(err); } const event = res.body[0]; expect(event.year).to.equal(testEvent2.year); expect(event.semester).to.equal(testEvent2.semester); cb(); }); } ], done); }); test('should find events by year', (done) => { request.get('/api/events?year=' + testEvent2.year) .expect(status.OK) .end((err, res: SuperTestResponse<EventsResponseDto>) => { if (err) { return done(err); } const event = res.body[0]; expect(event.id).to.equal(id2); done(); }); }); test('should find events by semester', (done) => { request.get('/api/events?semester=' + testEvent1.semester) .expect(status.OK) .end((err, res: SuperTestResponse<EventsResponseDto>) => { if (err) { return done(err); } const event = res.body[0]; expect(event.id).to.equal(id1); done(); }); }); test('should get all events if none is specified', (done) => { request.get('/api/events') .expect(status.OK) .end((err, res: SuperTestResponse<EventsResponseDto>) => { if (err) { return done(err); } const events = res.body; expect(events.length).to.equal(2); done(); }); }); test('should return empty if an event is not found by id', (done) => { request.get('/api/events?id=123123') .expect(status.OK) .end((err, res: SuperTestResponse<EventsResponseDto>) => { if (err) { return done(err); } const events = res.body; expect(events.length).to.equal(0); done(); }); }); test('should return empty if an event is not found by semester', (done) => { request.get('/api/events?semester=Summer') .expect(status.OK) .end((err, res: SuperTestResponse<EventsResponseDto>) => { if (err) { return done(err); } const events = res.body; expect(events.length).to.equal(0); done(); }); }); test('should return empty if an event is not found by year', (done) => { request.get('/api/events?year=1914') .expect(status.OK) .end((err, res: SuperTestResponse<EventsResponseDto>) => { if (err) { return done(err); } const events = res.body; expect(events.length).to.equal(0); done(); }); }); test('should return empty if an event is not found by year and semester', (done) => { request.get('/api/events?year=1916&semester=Spring') .expect(status.OK) .end((err, res: SuperTestResponse<EventsResponseDto>) => { if (err) { return done(err); } const events = res.body; expect(events.length).to.equal(0); done(); }); }); }); describe('deleting an event', () => { test('should require authorization', (done) => { request.del('/api/events/' + id1) .expect(status.UNAUTHORIZED, done); }); test('should delete an event by id', (done) => { async.series([ (cb) => { request.get('/api/events?id=' + id2) .expect(status.OK, cb); }, (cb) => { request.del('/api/events/' + id2) .set('Authorization', adminToken) .expect(status.OK, cb); }, (cb) => { request.get('/api/events?id=' + id2) .expect(status.OK) .end((err, res) => { if (err) { return done(err); } const events = res.body; expect(events.length).to.equal(0); done(); }); } ], done); }); test('should not delete a nonexistent id', (done) => { request.del('/api/events/' + badId) .set('Authorization', adminToken) .expect(status.BAD_REQUEST, done); }); test('should not delete all events', (done) => { request.del('/api/events') .set('Authorization', adminToken) .expect(status.NOT_FOUND, done); }); }); describe('updating an event', () => { let eventUpdate: EventCreateDto; beforeEach(() => { eventUpdate = { year: 2014, semester: Semester.SPRING, date: new Date(2014, 3, 14), registration_open: new Date(2014, 1, 12), registration_close: new Date(2014, 3, 1), price: 5 }; }); test('should update an event', (done) => { request.put('/api/events/' + id1) .set('Authorization', adminToken) .send(eventUpdate) .expect(status.OK) .end((err, res: SuperTestResponse<EventResponseDto>) => { if (err) { return done(err); } const event = res.body.event; expect(event.id).to.equal(id1); expect(event.year).to.equal(eventUpdate.year); expect(event.price).to.equal(eventUpdate.price); return done(); }); }); test('should require admin privileges', (done) => { request.put('/api/events/' + id1) .set('Authorization', coordinatorToken) .send(eventUpdate) .expect(status.UNAUTHORIZED, done); }); test('should allow partial updates', (done) => { delete eventUpdate.year; request.put('/api/events/' + id1) .set('Authorization', adminToken) .send(eventUpdate) .expect(status.OK) .end((err, res: SuperTestResponse<EventResponseDto>) => { if (err) { return done(err); } const event = res.body.event; expect(event.id).to.equal(id1); expect(event.year).to.equal(2016); expect(event.price).to.equal(eventUpdate.price); return done(); }); }); test('should delete only if explicitly set to null', (done) => { request.put('/api/events/' + id1) .set('Authorization', adminToken) .send({}) .expect(status.OK, done); }); }); }); }); <file_sep>/src/client/src/components/coordinators/registrations/PurchasedItemSpec.js import Vue from 'vue'; import PurchasedItem from './PurchasedItem.vue'; import Vuex from 'vuex'; import { shallowMount } from '@vue/test-utils'; import { expect } from 'chai' import chai from 'chai'; import sinon from 'sinon'; import sinonChai from 'sinon-chai'; import filters from 'filters'; chai.use(sinonChai); Vue.use(Vuex); filters(Vue); const selectors = { deleteButton: '#delete-purchased-item', deleteError: '#delete-warning' }; const propsData = { item: { id: 1, price: 10, item: 'Test Item', details: { size: 's', quantity: 2 } }, registrationId: 1, scoutId: 2 } describe('PurchasedItem.vue', () => { let wrapper, store, actions; beforeEach(() => { actions = { deletePurchase: sinon.stub() }; store = new Vuex.Store({ actions }); }); describe('when created with an item', () => { beforeEach(() => { wrapper = shallowMount(PurchasedItem, { store, propsData }); }); it('should display the item', () => { expect(wrapper.text()).to.contain('Test Item'); }); it('should show the item size', () => { expect(wrapper.text()).to.contain('S'); }); it('should show the total item price', () => { expect(wrapper.text()).to.contain('$20.00'); }); it('should have a delete button', () => { expect(wrapper.findAll(selectors.deleteButton)).to.have.lengthOf(1); }); it('should not have an error', () => { expect(wrapper.vm.error).to.equal(''); expect(wrapper.findAll(selectors.deleteError)).to.have.lengthOf(0); }); describe('and clicking the delete button', () => { beforeEach(() => { const button = wrapper.find(selectors.deleteButton); button.trigger('click'); }); it('should trigger the vuex delete method', () => { expect(actions.deletePurchase).to.have.been.calledWith(sinon.match.any, { purchasableId: 1, registrationId: 1, scoutId: 2 }); }); }); }); describe('a successful delete', () => { beforeEach(() => { actions = { deletePurchase: sinon.stub().resolves() }; store = new Vuex.Store({ actions }); wrapper = shallowMount(PurchasedItem, { store, propsData }); const button = wrapper.find(selectors.deleteButton); button.trigger('click'); }); it('should not set an error', () => { actions.deletePurchase().then(() => { expect(wrapper.vm.error).to.equal(''); }); }); it('should know that it is done deleting', () => { actions.deletePurchase().then(() => { expect(wrapper.vm.deleting).to.be.false; }); }); }); describe('a failed delete', () => { beforeEach(() => { actions = { deletePurchase: sinon.stub().rejects() }; store = new Vuex.Store({ actions, propsData }); wrapper = shallowMount(PurchasedItem, { store, propsData }); const button = wrapper.find(selectors.deleteButton); button.trigger('click'); }); it('should set an error', () => { actions.deletePurchase().catch(() => { expect(wrapper.vm.error).to.have.length.greaterThan(1); }); }); it('should know that it is done deleting', () => { actions.deletePurchase().catch(() => { expect(wrapper.vm.deleting).to.be.false; }); }); }); }); <file_sep>/src/server/routes/events/deleteEvents.ts import { Request, Response } from 'express'; import status from 'http-status-codes'; import { Event } from '@models/event.model'; import { ErrorResponseDto } from '@interfaces/shared.interface'; import { Purchasable } from '@models/purchasable.model'; import { Offering } from '@models/offering.model'; export const deleteEvent = async (req: Request, res: Response) => { try { const event: Event = await Event.findByPk(req.params.id); await event.destroy(); return res.status(status.OK).end(); } catch (err) { return res.status(status.BAD_REQUEST).json(<ErrorResponseDto>{ message: 'Failed to delete event', error: err }); } }; export const deleteOffering = async (req: Request, res: Response) => { try { const offering: Offering = await Offering.findOne({ where: { badge_id: req.params.badgeId, event_id: req.params.eventId } }); if (!offering) { throw new Error('Badge to remove as offering does not exist'); } await offering.destroy(); return res.status(status.OK).end(); } catch (err) { return res.status(status.BAD_REQUEST).json(<ErrorResponseDto>{ message: 'Failed to delete offering', error: err }); } }; export const deletePurchasable = async (req: Request, res: Response) => { try { const [event, purchasable] = await Promise.all([ Event.findByPk(req.params.eventId), Purchasable.findByPk(req.params.purchasableId) ]); if (!purchasable || !event) { throw new Error('Purchasable to remove not found'); } await purchasable.destroy(); return res.status(status.OK).end(); } catch (err) { return res.status(status.BAD_REQUEST).json(<ErrorResponseDto>{ message: 'Failed to delete purchasable', error: err }); } }; <file_sep>/src/server/routes/scouts/getScouts.ts import { Model, FindAttributeOptions, FindOptions } from 'sequelize'; import { Request, Response } from 'express'; import status from 'http-status-codes'; import { cloneDeep } from 'lodash'; import { ErrorResponseDto } from '@interfaces/shared.interface'; import registrationInformation from '@models/queries/registrationInformation'; import { Registration } from '@models/registration.model'; import { Offering } from '@models/offering.model'; import { Purchasable } from '@models/purchasable.model'; import { Scout } from '@models/scout.model'; import { Event } from '@models/event.model'; import { User } from '@models/user.model'; import { CostCalculationResponseDto } from '@interfaces/registration.interface'; import { CalculationType } from '@routes/shared/calculationType.enum'; const scoutQuery: FindOptions = { attributes: [ ['id', 'scout_id'], 'firstname', 'lastname', 'fullname', 'troop', 'notes', 'birthday', 'emergency_name', 'emergency_relation', 'emergency_phone', 'created_at' ], include: [{ model: Event, as: 'registrations', attributes: [ ['id', 'event_id'], 'year', 'semester' ], through: <any>{ as: 'details' } }, { model: User, as: 'user', attributes: [ ['id', 'user_id'], 'firstname', 'lastname', 'fullname', 'email', 'details' ] }] }; interface QueryDetailInterface { model: typeof Model; modelAttributes?: FindAttributeOptions; joinAttributes: FindAttributeOptions; } export const getRegistrations = async (req: Request, res: Response) => { try { const query = cloneDeep(registrationInformation); query.where = { scout_id: req.params.scoutId }; const registrations: Registration[] = await Registration.findAll(query); return res.status(status.OK).json(registrations); } catch (err) { res.status(status.BAD_REQUEST).send(<ErrorResponseDto>{ message: 'Could not get registration', error: err }); } }; export const getPreferences = async (req: Request, res: Response) => { getRegistrationDetails(req, res, 'preferences'); }; export const getAssignments = async (req: Request, res: Response) => { getRegistrationDetails(req, res, 'assignments'); }; export const getPurchases = async (req: Request, res: Response) => { getRegistrationDetails(req, res, 'purchases'); }; export const getProjectedCost = async (req: Request, res: Response) => { getCost(req, res, CalculationType.Projected); }; export const getActualCost = async (req: Request, res: Response) => { getCost(req, res, CalculationType.Actual); }; export const getAll = async (_req: Request, res: Response) => { try { const scouts: Scout[] = await Scout.findAll(scoutQuery); return res.status(status.OK).json(scouts); } catch (err) { return res.status(status.BAD_REQUEST).send(<ErrorResponseDto>{ message: `Failed to get all scouts`, error: err }); } }; export const getScout = async (req: Request, res: Response) => { try { const scout: Scout = await Scout.findByPk(req.params.scoutId, scoutQuery); return res.status(status.OK).json(scout); } catch (err) { return res.status(status.BAD_REQUEST).send(<ErrorResponseDto>{ message: `Failed to get scout`, error: err }); } }; async function getRegistrationDetails(req: Request, res: Response, target: 'preferences'|'assignments'|'purchases'): Promise<Response> { const detailQueryMap: { [key: string]: QueryDetailInterface } = { preferences: { model: Offering, modelAttributes: ['badge_id', ['id', 'offering_id']], joinAttributes: ['rank'] }, assignments: { model: Offering, modelAttributes: ['badge_id', ['id', 'offering_id']], joinAttributes: ['periods', 'completions'] }, purchases: { model: Purchasable, joinAttributes: ['quantity', 'size'] } }; try { const registration: Registration = await Registration.findOne({ where: { id: req.params.registrationId, scout_id: req.params.scoutId }, include: [{ model: detailQueryMap[target].model, as: target, attributes: detailQueryMap[target].modelAttributes, through: <any>{ as: 'details', attributes: detailQueryMap[target].joinAttributes } }] }); return res.status(status.OK).send(registration[target]); } catch (err) { return res.status(status.BAD_REQUEST).send(<ErrorResponseDto>{ message: `Failed to get ${target}`, error: err }); } } async function getCost(req: Request, res: Response, type: CalculationType): Promise<Response> { try { const registration: Registration = await Registration.findOne({ where: { id: req.params.registrationId, scout_id: req.params.scoutId } }); const cost: number = await (type === CalculationType.Actual ? registration.actualCost() : registration.projectedCost()); return res.status(status.OK).json(<CostCalculationResponseDto>{ cost: String(cost.toFixed(2)) }); } catch (err) { res.status(status.BAD_REQUEST).send(<ErrorResponseDto>{ message: 'Failed to calculate costs', error: err }); } } <file_sep>/tests/server/indexSpec.ts import supertest from 'supertest'; import status from 'http-status-codes'; import app from '@app/app'; const request = supertest(app); describe('index', () => { test('responds with OK if found', (done) => { request.get('/api') .expect(status.OK, done); }); test('responds with 404 if invalid', (done) => { request.get('/') .expect(status.NOT_FOUND, done); }); }); <file_sep>/src/server/routes/forgot/getForgot.ts import { Request, Response } from 'express'; import status from 'http-status-codes'; import { Op } from 'sequelize'; import { ErrorResponseDto, MessageResponseDto } from '@interfaces/shared.interface'; import { User } from '@models/user.model'; export const tokenValid = async (req: Request, res: Response) => { try { const users: User[] = await User.findAll({ where: { reset_password_token: req.params.token, reset_token_expires: { [Op.gt]: Date.now() } } }); if (users.length < 1) { throw new Error('No user found'); } return res.status(status.BAD_REQUEST).json(<MessageResponseDto>{ message: 'Reset token valid' }); } catch (err) { return res.status(status.BAD_REQUEST).json(<ErrorResponseDto>{ error: err, message: 'Reset token invalid or expired' }); } }; <file_sep>/tests/server/testEvents.ts import { Semester } from '@interfaces/event.interface'; export default [ { year: 2016, semester: Semester.SPRING, date: new Date(2016, 3, 14), registration_open: new Date(2016, 1, 1), registration_close: new Date(2016, 2, 11), price: 10, current: true }, { year: 2015, semester: Semester.FALL, date: new Date(2015, 11, 15), registration_open: new Date(2015, 9, 9), registration_close: new Date(2015, 10, 31), price: 10, current: false } ]; <file_sep>/src/server/migrations/20170928003811-add-class-size-to-offerings.js 'use strict'; module.exports = { up: (queryInterface, Sequelize) => { return queryInterface.addColumn('Offerings', 'size_limit', { type: Sequelize.INTEGER, defaultValue: 20 }); }, down: (queryInterface) => { return queryInterface.removeColumn('Offerings', 'size_limit'); } }; <file_sep>/src/server/config/secrets.ts export default { 'SENDGRID_USERNAME': process.env.SENDGRID_USERNAME, 'SENDGRID_PASSWORD': <PASSWORD>, 'APP_SECRET': process.env.APP_SECRET, 'SENDGRID_API_KEY': process.env.SENDGRID_API_KEY }; <file_sep>/src/client/src/validators/numberSpec.js import { expect } from 'chai' import number from './number'; describe('The number validator', () => { it('should pass for a number', () => { expect(number(123)).to.be.true; }); it('should pass for a string number', () => { expect(number('123')).to.be.true; }); it('should fail for alpha', () => { expect(number('a')).to.be.false; }); it('should fail for mixed text', () => { expect(number('1a')).to.be.false; }); it('should fail for spaced numbers', () => { expect(number(' 1 ')).to.be.false; expect(number('1 1')).to.be.false; }); it('should pass for null', () => { expect(number(null)).to.be.true; expect(number('')).to.be.true; }); }); <file_sep>/src/libs/interfaces/shared.interface.ts export interface ErrorResponseDto { message: string; error: any; } export interface MessageResponseDto { message: string; } <file_sep>/src/libs/interfaces/preference.interface.ts import { RegistrationPreferencesDto } from '@interfaces/registration.interface'; import { OfferingDto } from '@interfaces/offering.interface'; export interface PreferenceInterface { rank?: number; offering_id?: number; registration_id?: number; } export interface CreatePreferenceRequestDto { rank: number; offering: number; } export interface UpdatePreferenceRequestDto { rank: number; } export interface CreatePreferenceResponseDto { message: string; registration: RegistrationPreferencesDto; } export interface UpdatePreferenceResponseDto { preference: PreferenceInterface; message: string; } export type ScoutPreferenceResponseDto = OfferingDto<PreferenceInterface>[]; <file_sep>/src/server/migrations/20170211002127-add-purchasable-details.js 'use strict'; module.exports = { up: function (queryInterface, Sequelize) { return Promise.all([ queryInterface.addColumn('Purchasables', 'maximum_age', { type: Sequelize.INTEGER }), queryInterface.addColumn('Purchasables', 'minimum_age', { type: Sequelize.INTEGER }), queryInterface.addColumn('Purchasables', 'has_size', { type: Sequelize.BOOLEAN, defaultValue: false }), ]); }, down: function (queryInterface) { return Promise.all([ queryInterface.removeColumn('Purchasables', 'maximum_age'), queryInterface.removeColumn('Purchasables', 'minimum_age'), queryInterface.removeColumn('Purchasables', 'has_size'), ]); } }; <file_sep>/tests/server/completionRecordSpec.ts import supertest from 'supertest'; import * as async from 'async'; import status from 'http-status-codes'; import { expect } from 'chai'; import app from '@app/app'; import TestUtils, { RoleTokenObjects } from './testUtils'; import { Badge } from '@models/badge.model'; import { Event } from '@models/event.model'; import { Scout } from '@models/scout.model'; import { Offering } from '@models/offering.model'; import { OfferingInterface } from '@interfaces/offering.interface'; import testScouts from './testScouts'; import { CreateAssignmentRequestDto, UpdateAssignmentResponseDto, CreateAssignmentResponseDto } from '@interfaces/assignment.interface'; import { CreateRegistrationResponseDto, RegistrationRequestDto } from '@interfaces/registration.interface'; import { SuperTestResponse } from '@test/helpers/supertest.interface'; const request = supertest(app); describe('completion records', () => { let badges: Badge[]; let events: Event[]; let generatedUsers: RoleTokenObjects; let generatedScouts: Scout[]; let generatedOfferings: Offering[]; let scoutId: string; let registrationIds: number[]; const defaultRequirements: string[] = ['1', '2', '3a']; beforeEach(async () => { await TestUtils.dropDb(); }); beforeEach(async () => { generatedUsers = await TestUtils.generateTokens(); badges = await TestUtils.createBadges(); events = await TestUtils.createEvents(); const defaultPostData: OfferingInterface = { price: 10, periods: [1, 2, 3], duration: 1, requirements: defaultRequirements }; generatedOfferings = await TestUtils.createOfferingsForEvent(events[0], badges, defaultPostData); }); beforeEach(async () => { generatedScouts = await TestUtils.createScoutsForUser(generatedUsers.coordinator, testScouts(5)); }); beforeEach((done) => { scoutId = generatedScouts[0].id; registrationIds = []; async.series([ (cb) => { request.post('/api/scouts/' + scoutId + '/registrations') .set('Authorization', generatedUsers.coordinator.token) .send(<RegistrationRequestDto>{ event_id: events[0].id }) .expect(status.CREATED) .end((err, res: SuperTestResponse<CreateRegistrationResponseDto>) => { if (err) { return done(err); } registrationIds.push(res.body.registration.id); return cb(); }); }, (cb) => { request.post('/api/scouts/' + scoutId + '/registrations') .set('Authorization', generatedUsers.coordinator.token) .send(<RegistrationRequestDto>{ event_id: events[1].id }) .expect(status.CREATED) .end((err, res: SuperTestResponse<CreateRegistrationResponseDto>) => { if (err) { return done(err); } registrationIds.push(res.body.registration.id); return cb(); }); } ], done); }); afterAll(async () => { await TestUtils.dropDb(); await TestUtils.closeDb(); }); describe('adding completion records', () => { beforeEach((done) => { const postData: CreateAssignmentRequestDto[] = [{ periods: [1], offering: generatedOfferings[0].id }, { periods: [2], offering: generatedOfferings[1].id }, { periods: [3], offering: generatedOfferings[2].id }]; request.post('/api/scouts/' + scoutId + '/registrations/' + registrationIds[0] + '/assignments') .set('Authorization', generatedUsers.admin.token) .send(postData) .expect(status.CREATED) .end((err, res: SuperTestResponse<CreateAssignmentResponseDto>) => { if (err) { return done(err); } const registration = (res.body as any).registration; expect(registration.assignments).to.have.lengthOf(3); registration.assignments.forEach((assignment: any, index: number) => { expect(assignment.details.periods).to.deep.equal(postData[index].periods); expect(assignment.details.completions).to.deep.equal([]); expect(assignment.offering_id).to.equal(postData[index].offering); expect(assignment.price).to.exist; expect(assignment.badge.name).to.exist; }); return done(); }); }); test('should allow admins to change completion records', (done) => { request.put('/api/scouts/' + scoutId + '/registrations/' + registrationIds[0] + '/assignments/' + generatedOfferings[0].id) .set('Authorization', generatedUsers.admin.token) .send(<CreateAssignmentRequestDto>{ completions: ['1', '2'] }) .expect(status.OK) .end((err, res: SuperTestResponse<UpdateAssignmentResponseDto>) => { if (err) { return done(err); } const assignment = (res.body as UpdateAssignmentResponseDto).assignment; expect(assignment.offering_id).to.equal(generatedOfferings[0].id); expect(assignment.completions).to.deep.equal(['1', '2']); return done(); }); }); test('should allow teachers to change completion records', (done) => { request.put('/api/scouts/' + scoutId + '/registrations/' + registrationIds[0] + '/assignments/' + generatedOfferings[0].id) .set('Authorization', generatedUsers.admin.token) .send(<CreateAssignmentRequestDto>{ completions: ['1'] }) .expect(status.OK, done); }); test('should not allow coordinators to change completion records', (done) => { request.put('/api/scouts/' + scoutId + '/registrations/' + registrationIds[0] + '/assignments/' + generatedOfferings[0].id) .set('Authorization', generatedUsers.coordinator.token) .send(<CreateAssignmentRequestDto>{ completions: ['1'] }) .expect(status.UNAUTHORIZED, done); }); }); }); <file_sep>/tests/server/testUtils.ts import supertest from 'supertest'; import { Sequelize } from 'sequelize'; import status from 'http-status-codes'; import _ from 'lodash'; import app from '@app/app'; import { User } from '@models/user.model'; import { sequelize } from '@app/db'; import testEvents from './testEvents'; import testBadges from './testBadges'; import testPurchasables from './testPurchasables'; import { UserInterface, SignupRequestDto, UserRole, UserTokenResponseDto } from '@interfaces/user.interface'; import { Model } from 'sequelize-typescript'; import { ScoutInterface } from '@interfaces/scout.interface'; import { Scout } from '@models/scout.model'; import { BadgeInterface } from '@interfaces/badge.interface'; import { Badge } from '@models/badge.model'; import { EventInterface } from '@interfaces/event.interface'; import { Event } from '@models/event.model'; import { Offering } from '@models/offering.model'; import { OfferingInterface } from '@interfaces/offering.interface'; import { Purchasable } from '@models/purchasable.model'; import { SuperTestResponse } from '@test/helpers/supertest.interface'; const request = supertest(app); export interface TokenObject { token: string; profile: UserInterface; } export interface RoleTokenObjects { [role: string]: TokenObject; } export default class TestUtils { public static badId: string = '6575'; public static async dropDb(): Promise<Sequelize> { return await sequelize.sync({ force: true }); } public static async closeDb(): Promise<void> { return await sequelize.close(); } public static async dropTable(models: typeof Model[]): Promise<any> { for await (const model of models) { await model.sync({ force: true }); } } public static async generateTokens( roles: UserRole[] = [UserRole.ADMIN, UserRole.TEACHER, UserRole.COORDINATOR] ): Promise<RoleTokenObjects> { const tokens: RoleTokenObjects = {}; for await (const role of roles) { const { token, profile } = await this.generateToken(role); tokens[role] = { token, profile }; } return tokens; } public static async generateToken(name: string): Promise<TokenObject> { let token: string; let profile: UserInterface; const roleSearchRegexp: RegExp = /(\D+)/; const role = roleSearchRegexp.exec(name)[1]; const postData: SignupRequestDto = { email: name + '@test.com', password: '<PASSWORD>', firstname: 'firstname', lastname: 'lastname', role: role }; await request.post('/api/signup') .send(postData) .expect(status.CREATED) .expect((res: SuperTestResponse<UserTokenResponseDto>) => { profile = res.body.profile; token = res.body.token; }); const user: User = await User.findByPk(profile.id); user.approved = true; await user.save(); return { token, profile }; } public static async removeScoutsForUser(generatedUser: TokenObject): Promise<unknown> { const user: User = await User.findByPk(generatedUser.profile.id); return user.$set('scouts', []); } public static async createScoutsForUser(generatedUser: TokenObject, scouts: ScoutInterface[]): Promise<Scout[]> { const user: User = await User.findByPk(generatedUser.profile.id); const createdScouts: Scout[] = []; for await (const scout of scouts) { const createdScout: Scout = await Scout.create(scout); createdScouts.push(createdScout.toJSON() as Scout); await user.$add('scout', createdScout); } return createdScouts; } public static async createBadges(badges: BadgeInterface[] = testBadges): Promise<Badge[]> { const createdBadges: Badge[] = []; for await (const badge of badges) { const createdBadge: Badge = await Badge.create(badge); createdBadges.push(createdBadge); } return createdBadges; } public static async createEvents(events: EventInterface[] = testEvents): Promise<Event[]> { const createdEvents: Event[] = []; for await (const event of events) { const createdEvent: Event = await Event.create(event); createdEvents.push(createdEvent); } return createdEvents; } public static async createOfferingsForEvent(event: Event, badges: Badge[], offering: OfferingInterface): Promise<Offering[]> { for await (const badge of badges) { await event.$add('offering', badge.id, { through: offering }) as Offering[]; } return await Offering.findAll({ where: { event_id: event.id }}); } public static async createPurchasablesForEvent(event: Event): Promise<Purchasable[]> { const createdPurchasables: Purchasable[] = []; for await (const purchasable of testPurchasables) { const createdPurchasable: Purchasable = await Purchasable.create(purchasable); createdPurchasables.push(createdPurchasable); await event.$add('purchasable', createdPurchasable); } return createdPurchasables; } } <file_sep>/src/libs/interfaces/event.interface.ts import { BadgeInterface, BadgeDto } from '@interfaces/badge.interface'; import { OfferingInterface, OfferingDto } from '@interfaces/offering.interface'; import { ScoutInterface } from '@interfaces/scout.interface'; import { RegistrationPurchasesDto, AssignmentRegistrationDto } from '@interfaces/registration.interface'; import { PurchasableInterface, PurchasableDto } from '@interfaces/purchasable.interface'; export enum Semester { SPRING = 'Spring', FALL = 'Fall' } export interface EventInterface { id?: number; year?: number; semester?: Semester; date?: Date; registration_open?: Date; registration_close?: Date; price?: number; offerings?: BadgeInterface[]; purchasables?: PurchasableInterface[]; } export interface EventDto<T = any, K = any> extends EventInterface { event_id?: number; purchasables?: PurchasableDto[]; details?: T; offerings?: BadgeDto<K>[]; } export interface EventOfferingInterface extends EventInterface { offerings?: BadgeDto<OfferingInterface>[]; } export interface CurrentEventInterface { event_id?: string; event?: EventInterface; } export interface EventResponseDto { message: string; event: EventInterface; } export interface CreateOfferingResponseDto { message: string; event: EventOfferingInterface; } export interface CurrentEventResponseDto { message: string; currentEvent: EventInterface; } export interface IncomeCalculationResponseDto { income: string; } export interface AssigneeDto extends OfferingDto { badge?: BadgeDto; assignees?: AssignmentRegistrationDto[]; } export type AssigneesResponseDto = AssigneeDto[]; export type EventCreateDto = EventInterface; export type EventsResponseDto = EventDto<undefined, OfferingDto>[]; export type GetCurrentEventDto = EventInterface; export interface SetCurrentEventDto { id: string|number; } export interface EventStatisticsDto { scouts?: ScoutInterface[]; offerings?: BadgeDto[]; registrations?: RegistrationPurchasesDto[]; } export interface ClassSizeDto { size_limit: number; total: number; 1: number; 2: number; 3: number; } <file_sep>/src/server/routes/scouts.ts // tslint:disable: max-line-length import { Router } from 'express'; import { isAuthorized } from '@middleware/isAuthorized'; import { isOwner } from '@middleware/isOwner'; import { UserRole } from '@interfaces/user.interface'; import { createRegistration, createPreference, createAssignment, createPurchase } from '@routes/scouts/postScouts'; import { getRegistrations, getPreferences, getAssignments, getPurchases, getAll, getScout, getProjectedCost, getActualCost } from '@routes/scouts/getScouts'; import { deleteRegistration, deletePreference, deleteAssignment, deletePurchase } from '@routes/scouts/deleteScouts'; import { updatePreference, updateAssignment, updatePurchase } from '@routes/scouts/updateScouts'; export const scoutRoutes = Router(); scoutRoutes.param('scoutId', isOwner); scoutRoutes.get('/', isAuthorized([UserRole.TEACHER]), getAll); scoutRoutes.get('/:scoutId', isAuthorized([UserRole.TEACHER, UserRole.COORDINATOR]), getScout); // // Registration scoutRoutes.post('/:scoutId/registrations', isAuthorized([UserRole.TEACHER, UserRole.COORDINATOR]), createRegistration); scoutRoutes.get('/:scoutId/registrations', isAuthorized([UserRole.TEACHER, UserRole.COORDINATOR]), getRegistrations); scoutRoutes.delete('/:scoutId/registrations/:eventId', isAuthorized([UserRole.TEACHER, UserRole.COORDINATOR]), deleteRegistration); // // Preferences scoutRoutes.post('/:scoutId/registrations/:registrationId/preferences', isAuthorized([UserRole.TEACHER, UserRole.COORDINATOR]), createPreference); scoutRoutes.get('/:scoutId/registrations/:registrationId/preferences', isAuthorized([UserRole.TEACHER, UserRole.COORDINATOR]), getPreferences); scoutRoutes.put('/:scoutId/registrations/:registrationId/preferences/:offeringId', isAuthorized([UserRole.TEACHER, UserRole.COORDINATOR]), updatePreference); scoutRoutes.delete('/:scoutId/registrations/:registrationId/preferences/:offeringId', isAuthorized([UserRole.TEACHER, UserRole.COORDINATOR]), deletePreference); // // Assignments scoutRoutes.post('/:scoutId/registrations/:registrationId/assignments', isAuthorized([UserRole.TEACHER]), createAssignment); scoutRoutes.get('/:scoutId/registrations/:registrationId/assignments', isAuthorized([UserRole.TEACHER]), getAssignments); scoutRoutes.put('/:scoutId/registrations/:registrationId/assignments/:offeringId', isAuthorized([UserRole.TEACHER]), updateAssignment); scoutRoutes.delete('/:scoutId/registrations/:registrationId/assignments/:offeringId', isAuthorized([UserRole.TEACHER]), deleteAssignment); // // Purchases scoutRoutes.post('/:scoutId/registrations/:registrationId/purchases', isAuthorized([UserRole.COORDINATOR]), createPurchase); scoutRoutes.get('/:scoutId/registrations/:registrationId/purchases', isAuthorized([UserRole.TEACHER, UserRole.COORDINATOR]), getPurchases); scoutRoutes.put('/:scoutId/registrations/:registrationId/purchases/:purchasableId', isAuthorized([UserRole.COORDINATOR]), updatePurchase); scoutRoutes.delete('/:scoutId/registrations/:registrationId/purchases/:purchasableId', isAuthorized([UserRole.COORDINATOR]), deletePurchase); // // Payments scoutRoutes.get('/:scoutId/registrations/:registrationId/projectedCost', isAuthorized([UserRole.TEACHER, UserRole.COORDINATOR]), getProjectedCost); scoutRoutes.get('/:scoutId/registrations/:registrationId/cost', isAuthorized([UserRole.TEACHER, UserRole.COORDINATOR]), getActualCost); <file_sep>/src/libs/interfaces/assignment.interface.ts import { RegistrationAssignmentsDto } from '@interfaces/registration.interface'; import { OfferingDto } from '@interfaces/offering.interface'; export interface AssignmentInterface { periods?: number[]; completions?: string[]; offering_id?: number; registration_id?: number; } export interface CreateAssignmentRequestDto { periods?: number[]; offering?: number; completions?: string[]; } export interface CreateAssignmentResponseDto { message: string; registration: RegistrationAssignmentsDto; } export interface UpdateAssignmentResponseDto { message: string; assignment: AssignmentInterface; } export type ScoutAssignmentResponseDto = OfferingDto<AssignmentInterface>[]; <file_sep>/tests/server/preferencesSpec.ts import supertest from 'supertest'; import * as async from 'async'; import status from 'http-status-codes'; import { expect } from 'chai'; import app from '@app/app'; import TestUtils, { RoleTokenObjects } from './testUtils'; import testScouts from './testScouts'; import { Badge } from '@models/badge.model'; import { Event } from '@models/event.model'; import { Scout } from '@models/scout.model'; import { Offering } from '@models/offering.model'; import { UserRole } from '@interfaces/user.interface'; import { OfferingInterface } from '@interfaces/offering.interface'; import { Registration } from '@models/registration.model'; import { CreatePreferenceRequestDto, CreatePreferenceResponseDto, ScoutPreferenceResponseDto, UpdatePreferenceRequestDto } from '@interfaces/preference.interface'; import { Preference } from '@models/preference.model'; import { RegistrationRequestDto, CreateRegistrationResponseDto } from '@interfaces/registration.interface'; import { SuperTestResponse } from '@test/helpers/supertest.interface'; const request = supertest(app); describe('preferences', () => { let badges: Badge[]; let events: Event[]; let generatedUsers: RoleTokenObjects; let generatedScouts: Scout[]; let generatedOfferings: Offering[]; let scoutId: string; let registrationIds: number[] = []; const badId = TestUtils.badId; beforeAll(async () => { await TestUtils.dropDb(); }); beforeAll(async () => { generatedUsers = await TestUtils.generateTokens([UserRole.ADMIN, UserRole.TEACHER, UserRole.COORDINATOR, 'coordinator2' as any]); badges = await TestUtils.createBadges(); events = await TestUtils.createEvents(); const defaultPostData: OfferingInterface = { price: 10, periods: [1, 2, 3], duration: 1 }; generatedOfferings = await TestUtils.createOfferingsForEvent(events[0], badges, defaultPostData); }); beforeEach(async () => { await TestUtils.dropTable([Registration, Preference]); generatedScouts = await TestUtils.createScoutsForUser(generatedUsers.coordinator, testScouts(5)); }); beforeEach((done) => { scoutId = generatedScouts[0].id; registrationIds = []; async.series([ (cb) => { request.post('/api/scouts/' + scoutId + '/registrations') .set('Authorization', generatedUsers.coordinator.token) .send(<RegistrationRequestDto>{ event_id: events[0].id }) .expect(status.CREATED) .end((err, res: SuperTestResponse<CreateRegistrationResponseDto>) => { if (err) { return done(err); } registrationIds.push(res.body.registration.id); return cb(); }); }, (cb) => { request.post('/api/scouts/' + scoutId + '/registrations') .set('Authorization', generatedUsers.coordinator.token) .send(<RegistrationRequestDto>{ event_id: events[1].id }) .expect(status.CREATED) .end((err, res: SuperTestResponse<CreateRegistrationResponseDto>) => { if (err) { return done(err); } registrationIds.push(res.body.registration.id); return cb(); }); } ], done); }); afterAll(async () => { await TestUtils.dropDb(); await TestUtils.closeDb(); }); describe('when preferences do not exist', () => { test('should be able to be generated', (done) => { const postData: CreatePreferenceRequestDto = { offering: generatedOfferings[0].id, rank: 1 }; request.post('/api/scouts/' + generatedScouts[0].id + '/registrations/' + registrationIds[0] + '/preferences') .set('Authorization', generatedUsers.coordinator.token) .send(postData) .expect(status.CREATED) .end((err, res: SuperTestResponse<CreatePreferenceResponseDto>) => { if (err) { return done(err); } const registration = res.body.registration; expect(registration.preferences).to.have.length(1); const preference = registration.preferences[0]; expect(preference.badge_id).to.exist; expect(preference.offering_id).to.equal(postData.offering); expect(preference.details.rank).to.equal(postData.rank); return done(); }); }); test('should check for scout owner', (done) => { const postData: CreatePreferenceRequestDto = { offering: generatedOfferings[0].id, rank: 1 }; request.post('/api/scouts/' + generatedScouts[0].id + '/registrations/' + registrationIds[0] + '/preferences') .set('Authorization', generatedUsers.coordinator2.token) .send(postData) .expect(status.UNAUTHORIZED, done); }); test('should allow teachers to create', (done) => { const postData: CreatePreferenceRequestDto = { offering: generatedOfferings[0].id, rank: 1 }; request.post('/api/scouts/' + generatedScouts[0].id + '/registrations/' + registrationIds[0] + '/preferences') .set('Authorization', generatedUsers.teacher.token) .send(postData) .expect(status.CREATED, done); }); test('should allow admins to create', (done) => { const postData: CreatePreferenceRequestDto = { offering: generatedOfferings[0].id, rank: 1 }; request.post('/api/scouts/' + generatedScouts[0].id + '/registrations/' + registrationIds[0] + '/preferences') .set('Authorization', generatedUsers.admin.token) .send(postData) .expect(status.CREATED, done); }); test('should not create for a nonexistant offering', (done) => { const postData: CreatePreferenceRequestDto = { offering: badId as any, rank: 1 }; request.post('/api/scouts/' + generatedScouts[0].id + '/registrations/' + registrationIds[0] + '/preferences') .set('Authorization', generatedUsers.coordinator.token) .send(postData) .expect(status.BAD_REQUEST, done); }); test('should not create for nonexistant registrations', (done) => { const postData: CreatePreferenceRequestDto = { offering: generatedOfferings[0].id, rank: 1 }; request.post('/api/scouts/' + generatedScouts[0].id + '/registrations/' + badId + '/preferences') .set('Authorization', generatedUsers.coordinator.token) .send(postData) .expect(status.BAD_REQUEST, done); }); test('should not have a maximum rank of 6', (done) => { const postData: CreatePreferenceRequestDto = { offering: generatedOfferings[0].id, rank: 7 }; request.post('/api/scouts/' + generatedScouts[0].id + '/registrations/' + registrationIds[0] + '/preferences') .set('Authorization', generatedUsers.coordinator.token) .send(postData) .expect(status.BAD_REQUEST, done); }); test('should not have a minimum rank of 1', (done) => { const postData: CreatePreferenceRequestDto = { offering: generatedOfferings[0].id, rank: 0 }; request.post('/api/scouts/' + generatedScouts[0].id + '/registrations/' + registrationIds[0] + '/preferences') .set('Authorization', generatedUsers.coordinator.token) .send(postData) .expect(status.BAD_REQUEST, done); }); }); describe('when preferences exist', () => { beforeEach((done) => { async.series([ (cb) => { request.post('/api/scouts/' + generatedScouts[0].id + '/registrations/' + registrationIds[0] + '/preferences') .set('Authorization', generatedUsers.coordinator.token) .send(<CreatePreferenceRequestDto>{ offering: generatedOfferings[0].id, rank: 1 }) .expect(status.CREATED, cb); }, (cb) => { request.post('/api/scouts/' + generatedScouts[0].id + '/registrations/' + registrationIds[0] + '/preferences') .set('Authorization', generatedUsers.coordinator.token) .send(<CreatePreferenceRequestDto>{ offering: generatedOfferings[1].id, rank: 2 }) .expect(status.CREATED, cb); }, (cb) => { request.post('/api/scouts/' + generatedScouts[0].id + '/registrations/' + registrationIds[1] + '/preferences') .set('Authorization', generatedUsers.coordinator.token) .send(<CreatePreferenceRequestDto>{ offering: generatedOfferings[0].id, rank: 3 }) .expect(status.CREATED, cb); } ], done); }); describe('getting preferences', () => { test('should get all preferences for a registration', (done) => { request.get('/api/scouts/' + scoutId + '/registrations/' + registrationIds[0] + '/preferences') .set('Authorization', generatedUsers.coordinator.token) .expect(status.OK) .end((err, res: SuperTestResponse<ScoutPreferenceResponseDto>) => { if (err) { return done(err); } const preferences = res.body; expect(preferences).to.have.length(2); expect(preferences[0].badge_id).to.exist; expect(preferences[0].offering_id).to.equal(generatedOfferings[0].id); expect(preferences[0].details.rank).to.equal(1); expect(preferences[1].badge_id).to.exist; expect(preferences[1].offering_id).to.equal(generatedOfferings[1].id); expect(preferences[1].details.rank).to.equal(2); return done(); }); }); test('should not get with an incorrect scout', (done) => { request.get('/api/scouts/' + badId + '/registrations/' + registrationIds[0] + '/preferences') .set('Authorization', generatedUsers.coordinator.token) .expect(status.BAD_REQUEST, done); }); test('should not get with an incorrect registration', (done) => { request.get('/api/scouts/' + generatedScouts[0].id + '/registrations/' + badId + '/preferences') .set('Authorization', generatedUsers.coordinator.token) .expect(status.BAD_REQUEST, done); }); }); describe('updating preferences', () => { test('should update a preference rank', (done) => { async.series([ (cb) => { request.get('/api/scouts/' + scoutId + '/registrations/' + registrationIds[0] + '/preferences') .set('Authorization', generatedUsers.coordinator.token) .expect(status.OK) .end((err, res: SuperTestResponse<ScoutPreferenceResponseDto>) => { if (err) { return done(err); } const preference = res.body.find((_preference) => _preference.offering_id === 1); expect(preference.details.rank).to.equal(1); return cb(); }); }, (cb) => { // tslint:disable-next-line: max-line-length request.put('/api/scouts/' + scoutId + '/registrations/' + registrationIds[0] + '/preferences/' + generatedOfferings[0].id) .set('Authorization', generatedUsers.coordinator.token) .send(<UpdatePreferenceRequestDto>{ rank: 3 }) .expect(status.OK, cb); }, (cb) => { request.get('/api/scouts/' + scoutId + '/registrations/' + registrationIds[0] + '/preferences') .set('Authorization', generatedUsers.coordinator.token) .expect(status.OK) .end((err, res: SuperTestResponse<ScoutPreferenceResponseDto>) => { if (err) { return done(err); } const preference = res.body.find((_preference) => _preference.offering_id === 1); expect(preference.details.rank).to.equal(3); return cb(); }); }, ], done); }); test('should check for the owner', (done) => { request.put('/api/scouts/' + scoutId + '/registrations/' + registrationIds[0] + '/preferences/' + generatedOfferings[0].id) .set('Authorization', generatedUsers.coordinator2.token) .send(<UpdatePreferenceRequestDto>{ rank: 3 }) .expect(status.UNAUTHORIZED, done); }); test('should allow teachers to update', (done) => { request.put('/api/scouts/' + scoutId + '/registrations/' + registrationIds[0] + '/preferences/' + generatedOfferings[0].id) .set('Authorization', generatedUsers.teacher.token) .send(<UpdatePreferenceRequestDto>{ rank: 3 }) .expect(status.OK, done); }); test('should allow admins to update', (done) => { request.put('/api/scouts/' + scoutId + '/registrations/' + registrationIds[0] + '/preferences/' + generatedOfferings[0].id) .set('Authorization', generatedUsers.admin.token) .send(<UpdatePreferenceRequestDto>{ rank: 3 }) .expect(status.OK, done); }); test('should not update an invalid preference', (done) => { request.put('/api/scouts/' + scoutId + '/registrations/' + registrationIds[0] + '/preferences/' + badId) .set('Authorization', generatedUsers.coordinator.token) .expect(status.BAD_REQUEST, done); }); test('should not update an invalid registration', (done) => { request.put('/api/scouts/' + scoutId + '/registrations/' + badId + '/preferences/' + generatedOfferings[0].id) .set('Authorization', generatedUsers.coordinator.token) .expect(status.BAD_REQUEST, done); }); test('should not update for an invalid scout', (done) => { request.put('/api/scouts/' + badId + '/registrations/' + registrationIds[0] + '/preferences/' + generatedOfferings[0].id) .set('Authorization', generatedUsers.coordinator.token) .expect(status.BAD_REQUEST, done); }); }); describe('deleting preferences', () => { test('should delete an existing preference', (done) => { async.series([ (cb) => { request.get('/api/scouts/' + scoutId + '/registrations/' + registrationIds[0] + '/preferences') .set('Authorization', generatedUsers.coordinator.token) .expect(status.OK) .end((err, res: SuperTestResponse<ScoutPreferenceResponseDto>) => { if (err) { return done(err); } expect(res.body).to.have.length(2); return cb(); }); }, (cb) => { // tslint:disable-next-line: max-line-length request.del('/api/scouts/' + scoutId + '/registrations/' + registrationIds[0] + '/preferences/' + generatedOfferings[0].id) .set('Authorization', generatedUsers.coordinator.token) .expect(status.OK, cb); }, (cb) => { request.get('/api/scouts/' + scoutId + '/registrations/' + registrationIds[0] + '/preferences') .set('Authorization', generatedUsers.coordinator.token) .expect(status.OK) .end((err, res: SuperTestResponse<ScoutPreferenceResponseDto>) => { expect(res.body).to.have.length(1); return cb(); }); }, ], done); }); test('should check for the correct owner', (done) => { request.del('/api/scouts/' + scoutId + '/registrations/' + registrationIds[0] + '/preferences/' + generatedOfferings[0].id) .set('Authorization', generatedUsers.coordinator2.token) .expect(status.UNAUTHORIZED, done); }); test('should allow teachers to delete', (done) => { request.del('/api/scouts/' + scoutId + '/registrations/' + registrationIds[0] + '/preferences/' + generatedOfferings[0].id) .set('Authorization', generatedUsers.teacher.token) .expect(status.OK, done); }); test('should allow admins to delete', (done) => { request.del('/api/scouts/' + scoutId + '/registrations/' + registrationIds[0] + '/preferences/' + generatedOfferings[0].id) .set('Authorization', generatedUsers.admin.token) .expect(status.OK, done); }); test('should not delete an invalid preference', (done) => { request.del('/api/scouts/' + scoutId + '/registrations/' + registrationIds[0] + '/preferences/' + badId) .set('Authorization', generatedUsers.coordinator.token) .expect(status.BAD_REQUEST, done); }); test('should not delete an invalid registration', (done) => { request.del('/api/scouts/' + scoutId + '/registrations/' + badId + '/preferences/' + generatedOfferings[0].id) .set('Authorization', generatedUsers.coordinator.token) .expect(status.BAD_REQUEST, done); }); test('should not delete for an invalid scout', (done) => { request.del('/api/scouts/' + badId + '/registrations/' + registrationIds[0] + '/preferences/' + generatedOfferings[0].id) .set('Authorization', generatedUsers.coordinator.token) .expect(status.BAD_REQUEST, done); }); }); }); describe('batch modifying preferences', () => { test('should add a batch of preferences', (done) => { const postData: CreatePreferenceRequestDto[] = [{ offering: generatedOfferings[0].id, rank: 1 }, { offering: generatedOfferings[1].id, rank: 2 }]; request.post('/api/scouts/' + generatedScouts[0].id + '/registrations/' + registrationIds[0] + '/preferences') .set('Authorization', generatedUsers.coordinator.token) .send(postData) .expect(status.CREATED) .end((err, res: SuperTestResponse<CreatePreferenceResponseDto>) => { if (err) { return done(err); } const registration = res.body.registration; expect(registration.preferences).to.have.length(2); const preferences = registration.preferences; expect(preferences[0].badge_id).to.exist; expect(preferences[0].offering_id).to.equal(postData[0].offering); expect(preferences[0].details.rank).to.equal(postData[0].rank); expect(preferences[1].badge_id).to.exist; expect(preferences[1].offering_id).to.equal(postData[1].offering); expect(preferences[1].details.rank).to.equal(postData[1].rank); return done(); }); }); test('should override existing preferences', (done) => { async.series([ (cb) => { const postData: CreatePreferenceRequestDto[] = [{ offering: generatedOfferings[0].id, rank: 1 }, { offering: generatedOfferings[1].id, rank: 2 }]; request.post('/api/scouts/' + generatedScouts[0].id + '/registrations/' + registrationIds[0] + '/preferences') .set('Authorization', generatedUsers.coordinator.token) .send(postData) .expect(status.CREATED) .end((err, res: SuperTestResponse<CreatePreferenceResponseDto>) => { if (err) { return done(err); } const registration = res.body.registration; expect(registration.preferences).to.have.length(2); const preferences = registration.preferences; expect(preferences[0].badge_id).to.exist; expect(preferences[0].offering_id).to.equal(postData[0].offering); expect(preferences[0].details.rank).to.equal(postData[0].rank); expect(preferences[1].badge_id).to.exist; expect(preferences[1].offering_id).to.equal(postData[1].offering); expect(preferences[1].details.rank).to.equal(postData[1].rank); return cb(); }); }, (cb) => { const postData: CreatePreferenceRequestDto[] = [{ offering: generatedOfferings[2].id, rank: 1 }]; request.post('/api/scouts/' + generatedScouts[0].id + '/registrations/' + registrationIds[0] + '/preferences') .set('Authorization', generatedUsers.coordinator.token) .send(postData) .expect(status.CREATED) .end((err, res: SuperTestResponse<CreatePreferenceResponseDto>) => { if (err) { return done(err); } const registration = res.body.registration; expect(registration.preferences).to.have.length(1); const preferences = registration.preferences; expect(preferences[0].badge_id).to.exist; expect(preferences[0].offering_id).to.equal(postData[0].offering); expect(preferences[0].details.rank).to.equal(postData[0].rank); return cb(); }); } ], done); }); test('should not create with an invalid offering', (done) => { const postData: CreatePreferenceRequestDto[] = [{ offering: 30, rank: 1 }]; request.post('/api/scouts/' + generatedScouts[0].id + '/registrations/' + registrationIds[0] + '/preferences') .set('Authorization', generatedUsers.coordinator.token) .send(postData) .expect(status.BAD_REQUEST, done); }); test('should not create with an invalid rank', (done) => { const postData: CreatePreferenceRequestDto[] = [{ offering: generatedOfferings[0].id, rank: 30 }]; request.post('/api/scouts/' + generatedScouts[0].id + '/registrations/' + registrationIds[0] + '/preferences') .set('Authorization', generatedUsers.coordinator.token) .send(postData) .expect(status.BAD_REQUEST, done); }); }); }); <file_sep>/src/client/src/store/modules/registration.js import axios from 'axios'; import _ from 'lodash'; import Vue from 'vue'; import * as types from '../mutation-types'; import URLS from '../../urls'; const state = { registrations: {} }; const getters = { registrations(state) { return state.registrations; } }; const mutations = { [types.SET_COMPLETION] (state, details) { let registration = _.find(state.registrations[details.eventId], (registration) => { return registration.registration_id === details.registrationId; }); if (!registration) { return; } let assignment = _.find(registration.assignments, (assignment) => { return assignment.offering_id === details.offeringId; }); Vue.set(assignment.details, 'completions', details.completions); }, [types.SET_ASSIGNMENTS] (state, details) { let registration = _.find(state.registrations[details.eventId], (registration) => { return registration.registration_id === details.registrationId; }); Vue.set(registration, 'assignments', details.assignments); }, [types.SET_EVENT_REGISTRATIONS] (state, details) { Vue.set(state.registrations, details.eventId, details.registrations); } }; const actions = { getRegistrations({ commit, rootState }, eventId) { let getURL; if (rootState.authentication.profile.role === 'coordinator') { getURL = URLS.USERS_URL + rootState.authentication.profile.id + '/events/' + eventId + '/registrations'; } else { getURL = URLS.EVENTS_URL + eventId + '/registrations'; } return new Promise((resolve, reject) => { axios.get(getURL) .then((response) => { commit(types.SET_EVENT_REGISTRATIONS, { eventId: eventId, registrations: response.data }); resolve(); }) .catch(() => { reject(); }); }); }, saveCompletions({ commit }, details) { return new Promise((resolve, reject) => { axios.put(URLS.SCOUTS_URL + details.scoutId + '/registrations/' + details.registrationId + '/assignments/' + details.offeringId, { completions: details.completions }) .then((response) => { commit(types.SET_COMPLETION, { eventId: details.eventId, offeringId: details.offeringId, registrationId: details.registrationId, completions: details.completions }) resolve(response.data); }) .catch(()=> { reject(); }) }); }, setAssignments({ commit }, details) { return new Promise((resolve, reject) => { axios.post(URLS.SCOUTS_URL + details.scoutId + '/registrations/' + details.registrationId + '/assignments', details.assignments) .then((response) => { commit(types.SET_ASSIGNMENTS, { eventId: details.eventId, registrationId: details.registrationId, assignments: response.data.registration.assignments }); resolve(response.data.registration.assignments); }) .catch(() => { reject(); }) }); } }; export default { state, getters, actions, mutations }; <file_sep>/src/server/models/purchase.model.ts import { Table, Model, Column, Default, Min, ForeignKey, BeforeValidate } from 'sequelize-typescript'; import { Purchasable } from '@models/purchasable.model'; import { Registration } from '@models/registration.model'; import { Size, PurchaseInterface } from '@interfaces/purchase.interface'; @Table({ underscored: true, tableName: 'Purchases' }) export class Purchase extends Model<Purchase> implements PurchaseInterface { @BeforeValidate public static async ensurePurchaseLimit(purchase: Purchase): Promise<void> { try { const purchasable: Purchasable = await Purchasable.findByPk(purchase.purchasable_id); const currentPurchaserCount: number = await purchasable.getPurchaserCount(); if (!purchasable.purchaser_limit) { return; } if (currentPurchaserCount + Number(purchase.quantity) > purchasable.purchaser_limit) { throw new Error(`Purchaser limit has been met`); } } catch { throw new Error(`Purchaser limit has been met`); } } @Default(0) @Min(0) @Column({ allowNull: false }) public quantity!: number; @Column({ validate: { isIn: [['xs', 's', 'm', 'l', 'xl', 'xxl']] } }) public size: Size; @ForeignKey(() => Purchasable) @Column({ allowNull: false }) public purchasable_id!: number; @ForeignKey(() => Registration) @Column({ allowNull: false }) public registration_id!: number; } <file_sep>/tests/server/eventBadgesSpec.ts import supertest from 'supertest'; import * as async from 'async'; import status from 'http-status-codes'; import { expect } from 'chai'; import app from '@app/app'; import TestUtils from './testUtils'; import { Badge } from '@models/badge.model'; import { Event } from '@models/event.model'; import { UserRole } from '@interfaces/user.interface'; import { Offering } from '@models/offering.model'; import { CreateOfferingDto, OfferingInterface, OfferingResponseDto } from '@interfaces/offering.interface'; import { EventInterface, Semester, EventOfferingInterface, CreateOfferingResponseDto, EventsResponseDto, EventStatisticsDto } from '@interfaces/event.interface'; import { SuperTestResponse } from '@test/helpers/supertest.interface'; const request = supertest(app); describe('event badge association', () => { let adminToken: string; let badges: Badge[]; let events: Event[]; const badId = TestUtils.badId; beforeAll(async () => { await TestUtils.dropDb(); }); beforeAll(async () => { adminToken = (await TestUtils.generateToken(UserRole.ADMIN)).token; }); beforeEach(async () => { await TestUtils.dropTable([Event, Offering, Badge]); }); beforeEach(async () => { badges = await TestUtils.createBadges(); events = await TestUtils.createEvents(); }); afterAll(async () => { await TestUtils.dropDb(); await TestUtils.closeDb(); }); describe('when offerings do not exist', () => { test('should create a badge offering', (done) => { const postData: CreateOfferingDto = { badge_id: badges[1].id, offering: { duration: 1, periods: [1, 2, 3], price: '10.00', requirements: ['1', '2', '3a', '3b'] } }; request.post('/api/events/' + events[0].id + '/badges') .set('Authorization', adminToken) .send(postData) .expect(status.CREATED) .end((err, res: SuperTestResponse<CreateOfferingResponseDto>) => { if (err) { return done(err); } const event = res.body.event; expect(event.offerings).to.have.lengthOf(1); expect(event.offerings[0].details.price).to.equal(postData.offering.price); expect(event.offerings[0].details.requirements).to.deep.equal(postData.offering.requirements); expect(event.offerings[0].id).to.equal(badges[1].id); return done(); }); }); test('should default to a price of 0', (done) => { const postData: CreateOfferingDto = { badge_id: badges[0].id, offering: { duration: 1, periods: [1, 2, 3] } }; request.post('/api/events/' + events[0].id + '/badges') .set('Authorization', adminToken) .send(postData) .expect(status.CREATED) .end((err, res: SuperTestResponse<CreateOfferingResponseDto>) => { if (err) { return done(err); } const event = res.body.event; expect(event.offerings).to.have.lengthOf(1); expect(event.offerings[0].details.price).to.equal('0.00'); expect(event.offerings[0].id).to.equal(badges[0].id); return done(); }); }); test('should default to empty requirements', (done) => { const postData: CreateOfferingDto = { badge_id: badges[1].id, offering: { duration: 1, periods: [1, 2, 3], price: '10.00' } }; request.post('/api/events/' + events[0].id + '/badges') .set('Authorization', adminToken) .send(postData) .expect(status.CREATED) .end((err, res: SuperTestResponse<CreateOfferingResponseDto>) => { if (err) { return done(err); } const event = res.body.event as EventOfferingInterface; expect(event.offerings).to.have.lengthOf(1); expect(event.offerings[0].details.price).to.equal(postData.offering.price); expect(event.offerings[0].details.requirements).to.deep.equal([]); expect(event.offerings[0].id).to.equal(badges[1].id); return done(); }); }); test('should not save null periods', (done) => { const postData: CreateOfferingDto = { badge_id: badges[1].id, offering: { duration: 1, periods: [1, 2, null], price: '10.00' } }; request.post('/api/events/' + events[0].id + '/badges') .set('Authorization', adminToken) .send(postData) .expect(status.CREATED) .end((err, res: SuperTestResponse<CreateOfferingResponseDto>) => { if (err) { return done(err); } const event = res.body.event; expect(event.offerings).to.have.lengthOf(1); expect(event.offerings[0].details.price).to.equal(postData.offering.price); expect(event.offerings[0].details.periods).to.deep.equal([1, 2]); expect(event.offerings[0].id).to.equal(badges[1].id); return done(); }); }); test('should create multiple offerings', (done) => { async.series([ (cb) => { const postData: CreateOfferingDto = { badge_id: badges[0].id, offering: { duration: 1, periods: [1, 2, 3], price: 10 } }; request.post('/api/events/' + events[0].id + '/badges') .set('Authorization', adminToken) .send(postData) .expect(status.CREATED) .end((err, res: SuperTestResponse<CreateOfferingResponseDto>) => { if (err) { return done(err); } const event = res.body.event; expect(event.offerings).to.have.lengthOf(1); const offering = event.offerings.find(_offering => _offering.id === badges[0].id); expect(offering.details.price).to.equal('10.00'); expect(offering.details.duration).to.equal(1); expect(offering.details.periods).to.eql([1, 2, 3]); expect(offering.id).to.equal(badges[0].id); return cb(); }); }, (cb) => { const postData: CreateOfferingDto = { badge_id: badges[1].id, offering: { duration: 2, periods: [2, 3] } }; request.post('/api/events/' + events[0].id + '/badges') .set('Authorization', adminToken) .send(postData) .expect(status.CREATED) .end((err, res: SuperTestResponse<CreateOfferingResponseDto>) => { if (err) { return done(err); } const event = res.body.event; expect(event.offerings).to.have.lengthOf(2); const offering = event.offerings.find(_offering => _offering.id === badges[1].id); expect(offering.details.price).to.equal('0.00'); expect(offering.details.duration).to.equal(2); expect(offering.details.periods).to.eql([2, 3]); expect(offering.id).to.equal(badges[1].id); return cb(); }); } ], done); }); test('should not create an offering if the badge does not exist', (done) => { const postData: CreateOfferingDto = { badge_id: Number(badId), offering: { duration: 1, periods: [1, 2, 3] } }; request.post('/api/events/' + events[0].id + '/badges') .set('Authorization', adminToken) .send(postData) .expect(status.BAD_REQUEST, done); }); test('should not create an offering if the event does not exist', (done) => { const postData: CreateOfferingDto = { badge_id: badges[0].id, offering: { duration: 1, periods: [1, 2, 3] } }; request.post('/api/events/' + badId + '/badges') .set('Authorization', adminToken) .send(postData) .expect(status.BAD_REQUEST, done); }); test('should validate the presence of required fields', (done) => { const postData: any = { badge_id: badges[0].id }; request.post('/api/events/' + events[0].id + '/badges') .set('Authorization', adminToken) .send(postData) .expect(status.BAD_REQUEST, done); }); test('should validate for correct durations', (done) => { const postData: CreateOfferingDto = { badge_id: badges[0].id, offering: { duration: 2, periods: [1] } }; request.post('/api/events/' + events[0].id + '/badges') .set('Authorization', adminToken) .send(postData) .expect(status.BAD_REQUEST, done); }); test('should respond gracefully to bad ids', (done) => { const postData: CreateOfferingDto = { badge_id: badges[0].id, offering: { duration: 1, periods: [1, 2, 3] } }; request.post('/api/events/123/badges') .set('Authorization', adminToken) .send(postData) .expect(status.BAD_REQUEST, done); }); }); describe('when offerings exist', () => { let offerings: Offering[]; const defaultPostData: OfferingInterface = { price: 10, periods: [1, 2, 3], duration: 1, requirements: ['1', '2a', '3'] }; beforeEach(async () => { offerings = await TestUtils.createOfferingsForEvent(events[0], badges, defaultPostData); }); describe('getting offerings', () => { test('should get all offerings for an event', (done) => { request.get('/api/events?id=' + events[0].id) .expect(status.OK) .end((err, res: SuperTestResponse<EventsResponseDto>) => { if (err) { return done(err); } const event = res.body[0]; expect(event.offerings.length).to.equal(3); expect(event.offerings.map(offering => offering.id)).to.have.same.members(badges.map(badge => badge.id)); return done(); }); }); test('should get offerings as part of the event stats', (done) => { request.get('/api/events/' + events[0].id + '/stats') .set('Authorization', adminToken) .expect(status.OK) .end((err, res: SuperTestResponse<EventStatisticsDto>) => { if (err) { return done(err) } const stats = res.body; expect(stats.registrations).to.have.length(0); expect(stats.scouts).to.have.length(0); expect(stats.offerings).to.have.length(3); return done(); }); }); }); describe('updating offerings', () => { test('should be able to update without specifying a badge', (done) => { const offeringUpdate: OfferingInterface = { duration: 1, periods: [1, 2], price: '5.00', requirements: ['1', '2b'] }; request.put('/api/events/' + events[0].id + '/badges/' + offerings[0].badge_id) .set('Authorization', adminToken) .send(offeringUpdate) .end((err, res: SuperTestResponse<OfferingResponseDto>) => { if (err) { return done(err); } const offering = res.body.offering; expect(offering.badge_id).to.equal(badges[0].id); expect(offering.duration).to.equal(offeringUpdate.duration); expect(offering.periods).to.deep.equal(offeringUpdate.periods); expect(offering.price).to.equal(offeringUpdate.price); expect(offering.requirements).to.deep.equal(offeringUpdate.requirements); return done(); }); }); test('should not require price', (done) => { const offeringUpdate: OfferingInterface = { duration: 1, periods: [1, 2] }; request.put('/api/events/' + events[0].id + '/badges/' + offerings[0].badge_id) .set('Authorization', adminToken) .send(offeringUpdate) .end((err, res: SuperTestResponse<OfferingResponseDto>) => { if (err) { return done(err); } const offering = res.body.offering; expect(offering.badge_id).to.equal(badges[0].id); expect(offering.duration).to.equal(1); expect(offering.periods).to.deep.equal([1, 2]); expect(offering.price).to.equal('10.00'); // Default value for price if not specified return done(); }); }); test('should should not save null periods', (done) => { const offeringUpdate: OfferingInterface = { duration: 1, periods: [1, 2, null] }; request.put('/api/events/' + events[0].id + '/badges/' + offerings[0].badge_id) .set('Authorization', adminToken) .send(offeringUpdate) .end((err, res: SuperTestResponse<OfferingResponseDto>) => { if (err) { return done(err); } const offering = res.body.offering; expect(offering.badge_id).to.equal(badges[0].id); expect(offering.duration).to.equal(1); expect(offering.periods).to.deep.equal([1, 2]); expect(offering.price).to.equal('10.00'); // Default value for price if not specified return done(); }); }); test( 'should not delete existing offerings if an event is updating without supplying offerings', (done) => { const eventUpdate: EventInterface = { year: 2014, semester: Semester.SPRING, date: new Date(2014, 3, 14), registration_open: new Date(2014, 1, 12), registration_close: new Date(2014, 3, 1), price: 5 }; request.put('/api/events/' + events[0].id) .set('Authorization', adminToken) .send(eventUpdate) .expect(status.OK) .end((err, res: SuperTestResponse<CreateOfferingResponseDto>) => { if (err) { return done(err); } const event = res.body.event; expect(event.id).to.equal(events[0].id); expect(event.year).to.equal(eventUpdate.year); expect(event.price).to.equal(eventUpdate.price); expect(event.offerings).to.have.lengthOf(3); return done(); }); } ); test('should not allow an update with invalid information', (done) => { const offeringUpdate: OfferingInterface = { duration: 2, periods: [1] }; request.put('/api/events/' + events[0].id + '/badges/' + offerings[0].badge_id) .set('Authorization', adminToken) .send(offeringUpdate) .expect(status.BAD_REQUEST, done); }); test('should not update with extra fields', (done) => { const offeringUpdate: any = { duration: 1, periods: [1, 2], price: '5.00', extra: true }; request.put('/api/events/' + events[0].id + '/badges/' + offerings[0].badge_id) .set('Authorization', adminToken) .send(offeringUpdate) .end((err, res: SuperTestResponse<OfferingResponseDto>) => { if (err) { return done(err); } const offering = res.body.offering; expect(offering.badge_id).to.equal(badges[0].id); expect(offering.duration).to.equal(offeringUpdate.duration); expect(offering.periods).to.deep.equal(offeringUpdate.periods); expect(offering.price).to.equal(offeringUpdate.price); expect((offering as any).extra).to.not.exist; return done(); }); }); test('should update without deleting fields', (done) => { const offeringUpdate: OfferingInterface = { duration: 1 }; request.put('/api/events/' + events[0].id + '/badges/' + offerings[0].badge_id) .set('Authorization', adminToken) .send(offeringUpdate) .expect(status.OK) .end((err, res: SuperTestResponse<OfferingResponseDto>) => { if (err) { return done(err); } const offering = res.body.offering; expect(offering.badge_id).to.equal(badges[0].id); expect(offering.duration).to.equal(offeringUpdate.duration); expect(offering.periods).to.deep.equal(offerings[0].periods); expect(offering.price).to.equal(offerings[0].price); expect(offering.requirements).to.deep.equal(offerings[0].requirements); return done(); }); }); test('should not update a nonexistent event', (done) => { const offeringUpdate: OfferingInterface = { duration: 1, periods: [1, 2], price: 5 }; request.put('/api/events/' + badId + '/badges/' + offerings[0].badge_id) .set('Authorization', adminToken) .send(offeringUpdate) .expect(status.BAD_REQUEST, done); }); test('should not update a nonexistent offering', (done) => { const offeringUpdate: OfferingInterface = { duration: 1, periods: [1, 2], price: 5 }; request.put('/api/events/' + events[0].id + '/badges/' + badId) .set('Authorization', adminToken) .send(offeringUpdate) .expect(status.BAD_REQUEST, done); }); }); describe('deleting offerings', () => { test('should be able to delete an offering', (done) => { async.series([ (cb) => { request.get('/api/events?id=' + events[0].id) .expect(status.OK) .end((err, res: SuperTestResponse<EventsResponseDto>) => { if (err) { return cb(err); } const event = res.body[0]; expect(event.offerings).to.have.lengthOf(3); return cb(); }); }, (cb) => { request.del('/api/events/' + events[0].id + '/badges/' + offerings[1].badge_id) .set('Authorization', adminToken) .expect(status.OK, cb); }, (cb) => { request.get('/api/events?id=' + events[0].id) .expect(status.OK) .end((err, res: SuperTestResponse<EventsResponseDto>) => { if (err) { return cb(err); } const event = res.body[0]; expect(event.offerings).to.have.lengthOf(2); return cb(); }); } ], done); }); test('should require authorization', (done) => { request.del('/api/events/' + events[0].id + '/badges/' + offerings[0].badge_id) .expect(status.UNAUTHORIZED, done); }); test('should not delete from a nonexistant event', (done) => { request.del('/api/events/' + badId + '/badges/' + offerings[0].badge_id) .set('Authorization', adminToken) .expect(status.BAD_REQUEST, done); }); test('should not delete a nonexistant offering', (done) => { request.del('/api/events/' + events[0].id + '/badges/' + badId) .set('Authorization', adminToken) .expect(status.BAD_REQUEST, done); }); }); describe('deleting a badge', () => { test('should delete associated offerings', async () => { await request.get('/api/events?id=' + events[0].id) .expect(status.OK) .then((res: SuperTestResponse<EventsResponseDto>) => { const event = res.body[0]; expect(event.offerings.length).to.equal(3); }); await request.del(`/api/badges/${badges[0].id}`) .set('Authorization', adminToken) .expect(status.OK); await request.get('/api/events?id=' + events[0].id) .expect(status.OK) .then((res: SuperTestResponse<EventsResponseDto>) => { const event = res.body[0]; expect(event.offerings.length).to.equal(2); }); }); }); }); }); <file_sep>/src/server/models/preference.model.ts import { Table, Model, Column, Min, Max, ForeignKey } from 'sequelize-typescript'; import { Offering } from '@models/offering.model'; import { Registration } from '@models/registration.model'; import { PreferenceInterface } from '@interfaces/preference.interface'; @Table({ underscored: true, tableName: 'Preferences' }) export class Preference extends Model<Preference> implements PreferenceInterface { @Min(1) @Max(6) @Column({ allowNull: false }) public rank!: number; @ForeignKey(() => Offering) @Column({ allowNull: false }) public offering_id!: number; @ForeignKey(() => Registration) @Column({ allowNull: false }) public registration_id!: number; } <file_sep>/README.md ## MBU Online [![Build Status](https://travis-ci.org/dmurtari/mbu-online.svg?branch=master)](https://travis-ci.org/dmurtari/mbu-online) <file_sep>/src/server/routes/users/putUsers.ts import { Request, Response } from 'express'; import status from 'http-status-codes'; import jwt from 'jsonwebtoken'; import { User } from '@models/user.model'; import config from '@config/secrets'; import { EditUserResponseDto } from '@interfaces/user.interface'; import { ErrorResponseDto } from '@interfaces/shared.interface'; import { Scout } from '@models/scout.model'; import { ScoutResponseDto } from '@interfaces/scout.interface'; export const updateProfile = async (req: Request, res: Response) => { try { const user: User = await User.findByPk(req.params.userId); if (!user) { throw new Error('Profile to update not found'); } await user.update(req.body); user.set('password', null); const response: EditUserResponseDto = { message: 'User profile updated', profile: user }; if (req.body.password) { const token: string = jwt.sign(user.id, config.APP_SECRET); response.token = `JWT ${token}`; } return res.status(status.OK).json(response); } catch (err) { return res.status(status.BAD_REQUEST).json(<ErrorResponseDto>{ message: 'Error updating user', error: err }); } }; export const updateScout = async (req: Request, res: Response) => { try { const scout: Scout = await Scout.findByPk(req.params.scoutId); await scout.update(req.body); return res.status(status.OK).json(<ScoutResponseDto>{ message: 'Scout successfully updated', scout: scout }); } catch (err) { return res.status(status.BAD_REQUEST).json(<ErrorResponseDto>{ message: 'Error updating scout', error: err }); } }; <file_sep>/src/client/src/components/navigation/index.js import Navbar from './Navbar.vue'; import Footer from './Footer.vue'; export default function(Vue) { Vue.component('navbar', Navbar); Vue.component('mbu-footer', Footer); }<file_sep>/src/server/migrations/20150101000000-create-initial-schema.js const fs = require('fs'); const path = require('path'); module.exports = { up: (queryInterface) => { const initialSchemaPath = path.join(__dirname, '..', 'seed', 'initial_schema.sql'); const initialSchema = fs.readFileSync(initialSchemaPath, 'utf-8'); return queryInterface.sequelize.query(initialSchema); }, down: (queryInterface) => { return Promise.all([ queryInterface.dropTable('Assignments'), queryInterface.dropTable('Badges'), queryInterface.dropTable('Events'), queryInterface.dropTable('Offerings'), queryInterface.dropTable('Preferences'), queryInterface.dropTable('Purchasables'), queryInterface.dropTable('Purchases'), queryInterface.dropTable('Registrations'), queryInterface.dropTable('Scouts'), queryInterface.dropTable('Users'), ]); } }; <file_sep>/tests/server/registrationSpec.ts import supertest from 'supertest'; import * as async from 'async'; import status from 'http-status-codes'; import { expect } from 'chai'; import app from '@app/app'; import TestUtils, { RoleTokenObjects } from './testUtils'; import { Event } from '@models/event.model'; import { Scout } from '@models/scout.model'; import { UserRole } from '@interfaces/user.interface'; import { Registration } from '@models/registration.model'; import testScouts from './testScouts'; import { RegistrationRequestDto, CreateRegistrationResponseDto, RegistrationsResponseDto } from '@interfaces/registration.interface'; import { SuperTestResponse } from '@test/helpers/supertest.interface'; import { ScoutRegistrationResponseDto } from '@interfaces/scout.interface'; import { EventStatisticsDto } from '@interfaces/event.interface'; const request = supertest(app); describe('registration', () => { let events: Event[]; let generatedUsers: RoleTokenObjects; let generatedScouts: Scout[]; const badId = TestUtils.badId; beforeAll(async () => { await TestUtils.dropDb(); }); beforeAll(async () => { generatedUsers = await TestUtils.generateTokens([ UserRole.ADMIN, UserRole.TEACHER, UserRole.COORDINATOR, 'coordinator2' as any ]); }); beforeEach(async () => { await TestUtils.dropTable([Registration, Event, Scout]); events = await TestUtils.createEvents(); generatedScouts = await TestUtils.createScoutsForUser(generatedUsers.coordinator, testScouts(5)); }); afterAll(async () => { await TestUtils.dropDb(); await TestUtils.closeDb(); }); describe('registering a scout for an event', () => { test('should create the registration', (done) => { request.post('/api/scouts/' + generatedScouts[3].id + '/registrations') .set('Authorization', generatedUsers.coordinator.token) .send(<RegistrationRequestDto>{ event_id: events[0].id }) .expect(status.CREATED) .end((err, res: SuperTestResponse<CreateRegistrationResponseDto>) => { if (err) { return done(err); } const registration = res.body.registration; expect(registration.scout_id).to.equal(generatedScouts[3].id); expect(registration.event_id).to.equal(events[0].id); return done(); }); }); test('should create a registration with a note', (done) => { const note = 'This is a note'; request.post('/api/scouts/' + generatedScouts[3].id + '/registrations') .set('Authorization', generatedUsers.coordinator.token) .send(<RegistrationRequestDto>{ event_id: events[0].id, notes: note }) .expect(status.CREATED) .end((err, res: SuperTestResponse<CreateRegistrationResponseDto>) => { if (err) { return done(err); } const registration = res.body.registration; expect(registration.scout_id).to.equal(generatedScouts[3].id); expect(registration.event_id).to.equal(events[0].id); expect(registration.notes).to.equal(note); return done(); }); }); test('should check for the correct owner', (done) => { request.post('/api/scouts/' + generatedScouts[3].id + '/registrations') .set('Authorization', generatedUsers.coordinator2.token) .send(<RegistrationRequestDto>{ event_id: events[0].id }) .expect(status.UNAUTHORIZED, done); }); test('should allow admins to register', (done) => { request.post('/api/scouts/' + generatedScouts[3].id + '/registrations') .set('Authorization', generatedUsers.admin.token) .send(<RegistrationRequestDto>{ event_id: events[0].id }) .expect(status.CREATED, done); }); test('should allow teachers to register', (done) => { request.post('/api/scouts/' + generatedScouts[3].id + '/registrations') .set('Authorization', generatedUsers.teacher.token) .send(<RegistrationRequestDto>{ event_id: events[0].id }) .expect(status.CREATED, done); }); test('should not create a registration for a nonexistant scout', (done) => { request.post('/api/scouts/' + badId + '/registrations') .set('Authorization', generatedUsers.coordinator.token) .send(<RegistrationRequestDto>{ event_id: events[0].id }) .expect(status.BAD_REQUEST, done); }); test('should not create a registration for a nonexistant event', (done) => { request.post('/api/scouts/' + generatedScouts[3].id + '/registrations') .set('Authorization', generatedUsers.coordinator.token) .send(<RegistrationRequestDto>{ event_id: badId }) .expect(status.BAD_REQUEST, done); }); test('should not create duplicate registrations', (done) => { async.series([ (cb) => { request.post('/api/scouts/' + generatedScouts[3].id + '/registrations') .set('Authorization', generatedUsers.coordinator.token) .send(<RegistrationRequestDto>{ event_id: events[0].id }) .expect(status.CREATED, cb); }, (cb) => { request.post('/api/scouts/' + generatedScouts[3].id + '/registrations') .set('Authorization', generatedUsers.coordinator.token) .send(<RegistrationRequestDto>{ event_id: events[0].id }) .expect(status.BAD_REQUEST, cb); } ], done); }); }); describe('when a scout is already registered for events', () => { let scoutId: string; beforeEach((done) => { scoutId = generatedScouts[3].id; async.series([ (cb) => { request.post('/api/scouts/' + generatedScouts[1].id + '/registrations') .set('Authorization', generatedUsers.coordinator.token) .send(<RegistrationRequestDto>{ event_id: events[0].id }) .expect(status.CREATED, cb); }, (cb) => { request.post('/api/scouts/' + generatedScouts[1].id + '/registrations') .set('Authorization', generatedUsers.coordinator.token) .send(<RegistrationRequestDto>{ event_id: events[1].id }) .expect(status.CREATED, cb); }, (cb) => { request.post('/api/scouts/' + scoutId + '/registrations') .set('Authorization', generatedUsers.coordinator.token) .send(<RegistrationRequestDto>{ event_id: events[0].id }) .expect(status.CREATED, cb); }, (cb) => { request.post('/api/scouts/' + scoutId + '/registrations') .set('Authorization', generatedUsers.coordinator.token) .send(<RegistrationRequestDto>{ event_id: events[1].id }) .expect(status.CREATED, cb); }, (cb) => { request.post('/api/scouts/' + generatedScouts[2].id + '/registrations') .set('Authorization', generatedUsers.coordinator.token) .send(<RegistrationRequestDto>{ event_id: events[0].id }) .expect(status.CREATED, cb); } ], done); }); describe('getting a scouts registrations', () => { test('should get all associated registrations', (done) => { request.get('/api/scouts/' + scoutId + '/registrations') .set('Authorization', generatedUsers.coordinator.token) .expect(status.OK) .end((err, res: SuperTestResponse<RegistrationsResponseDto>) => { if (err) { return done(err); } const registrations = res.body; expect(registrations).to.have.lengthOf(2); expect(registrations[0].event_id).to.equal(events[1].id); expect(registrations[1].event_id).to.equal(events[0].id); registrations.forEach((registration: any) => { expect(registration.preferences).to.be.a('array'); expect(registration.purchases).to.be.a('array'); expect(registration.assignments).to.be.a('array'); }); return done(); }); }); }); describe('deleting a registration', () => { test('should delete a single registration', (done) => { async.series([ (cb) => { request.del('/api/scouts/' + scoutId + '/registrations/' + events[0].id) .set('Authorization', generatedUsers.coordinator.token) .expect(status.OK, cb); }, (cb) => { request.get('/api/scouts/' + scoutId + '/registrations') .set('Authorization', generatedUsers.coordinator.token) .expect(status.OK) .end((err, res: SuperTestResponse<RegistrationsResponseDto>) => { if (err) { return cb(err); } const registrations = res.body; expect(registrations).to.have.length(1); expect(registrations[0].event_id).to.equal(events[1].id); return cb(); }); } ], done); }); test('should check for the correct owner', (done) => { request.del('/api/scouts/' + scoutId + '/registrations/' + events[0].id) .set('Authorization', generatedUsers.coordinator2.token) .expect(status.UNAUTHORIZED, done); }); test('should allow teachers to delete', (done) => { request.del('/api/scouts/' + scoutId + '/registrations/' + events[0].id) .set('Authorization', generatedUsers.teacher.token) .expect(status.OK, done); }); test('should allow admins to delete', (done) => { request.del('/api/scouts/' + scoutId + '/registrations/' + events[0].id) .set('Authorization', generatedUsers.admin.token) .expect(status.OK, done); }); test('should not delete for an invalid scout', (done) => { request.del('/api/scouts/' + badId + '/registrations/' + events[0].id) .set('Authorization', generatedUsers.coordinator.token) .expect(status.BAD_REQUEST, done); }); test('should handle invalid events', (done) => { request.del('/api/scouts/' + scoutId + '/registrations/' + badId) .set('Authorization', generatedUsers.coordinator.token) .expect(status.BAD_REQUEST, done); }); }); }); describe('when multiple scouts are registered for an event', () => { let generatedScouts2: Scout[]; beforeEach(async () => { generatedScouts2 = await TestUtils.createScoutsForUser(generatedUsers.coordinator2, testScouts(5)); }); beforeEach((done) => { async.forEachOfSeries(generatedScouts, (scout, index, cb) => { request.post('/api/scouts/' + scout.id + '/registrations') .set('Authorization', generatedUsers.coordinator.token) .send(<RegistrationRequestDto>{ event_id: events[0].id }) .expect(status.CREATED, cb); }, (err) => { done(err); }); }); beforeEach((done) => { async.forEachOfSeries(generatedScouts, (scout, index, cb) => { request.post('/api/scouts/' + scout.id + '/registrations') .set('Authorization', generatedUsers.coordinator.token) .send(<RegistrationRequestDto>{ event_id: events[1].id }) .expect(status.CREATED, cb); }, (err) => { done(err); }); }); beforeEach((done) => { async.forEachOfSeries(generatedScouts2, (scout, index, cb) => { request.post('/api/scouts/' + scout.id + '/registrations') .set('Authorization', generatedUsers.coordinator2.token) .send(<RegistrationRequestDto>{ event_id: events[0].id }) .expect(status.CREATED, cb); }, (err) => { done(err); }); }); test('should get scout registrations for a user', (done) => { request.get('/api/users/' + generatedUsers.coordinator.profile.id + '/scouts/registrations') .set('Authorization', generatedUsers.coordinator.token) .expect(status.OK) .end((err, res: SuperTestResponse<ScoutRegistrationResponseDto>) => { if (err) { return done(err); } const scouts = res.body; expect(scouts).to.have.lengthOf(5); scouts.forEach((scout) => { expect(scout.registrations).to.have.lengthOf(2); expect(scout.registrations[0].event_id).to.equal(events[0].id); expect(scout.registrations[1].event_id).to.equal(events[1].id); }); return done(); }); }); test('should get registrations for an event for a user', (done) => { request.get('/api/users/' + generatedUsers.coordinator.profile.id + '/events/' + events[0].id + '/registrations') .set('Authorization', generatedUsers.coordinator.token) .expect(status.OK) .end((err, res: SuperTestResponse<RegistrationsResponseDto[]>) => { if (err) { return done(err); } const registrations = res.body; expect(registrations).to.have.lengthOf(5); registrations.forEach((registration: any, index: number) => { expect(registration.event_id).to.equal(events[0].id); expect(registration.scout_id).to.equal(generatedScouts[index].id); expect(registration.scout.fullname).to.equal(generatedScouts[index].fullname); expect(registration.preferences).to.be.a('array'); expect(registration.assignments).to.be.a('array'); expect(registration.purchases).to.be.a('array'); }); return done(); }); }); test('should get registrations for another event for a user', (done) => { request.get('/api/users/' + generatedUsers.coordinator.profile.id + '/events/' + events[1].id + '/registrations') .set('Authorization', generatedUsers.coordinator.token) .expect(status.OK) .end((err, res: SuperTestResponse<RegistrationsResponseDto[]>) => { if (err) { return done(err); } const registrations = res.body; expect(registrations).to.have.lengthOf(5); registrations.forEach((registration: any, index: number) => { expect(registration.event_id).to.equal(events[1].id); expect(registration.scout_id).to.equal(generatedScouts[index].id); expect(registration.scout.fullname).to.equal(generatedScouts[index].fullname); expect(registration.preferences).to.be.a('array'); expect(registration.assignments).to.be.a('array'); expect(registration.purchases).to.be.a('array'); }); return done(); }); }); test('should get registrations for an event for another user', (done) => { request.get('/api/users/' + generatedUsers.coordinator2.profile.id + '/events/' + events[0].id + '/registrations') .set('Authorization', generatedUsers.coordinator2.token) .expect(status.OK) .end((err, res: SuperTestResponse<RegistrationsResponseDto[]>) => { if (err) { return done(err); } const registrations = res.body; expect(registrations).to.have.lengthOf(5); registrations.forEach((registration: any, index: number) => { expect(registration.event_id).to.equal(events[0].id); expect(registration.scout_id).to.equal(generatedScouts2[index].id); expect(registration.scout.fullname).to.equal(generatedScouts2[index].fullname); expect(registration.preferences).to.be.a('array'); expect(registration.assignments).to.be.a('array'); expect(registration.purchases).to.be.a('array'); }); return done(); }); }); test('should allow admins to see scout registrations for a user', (done) => { request.get('/api/users/' + generatedUsers.coordinator.profile.id + '/scouts/registrations') .set('Authorization', generatedUsers.admin.token) .expect(status.OK, done); }); test('should allow teachers to see scout registrations for a user', (done) => { request.get('/api/users/' + generatedUsers.coordinator.profile.id + '/scouts/registrations') .set('Authorization', generatedUsers.teacher.token) .expect(status.OK, done); }); test('should not allow other coordinators to see scout registrations for a user', (done) => { request.get('/api/users/' + generatedUsers.coordinator.profile.id + '/scouts/registrations') .set('Authorization', generatedUsers.coordinator2.token) .expect(status.UNAUTHORIZED, done); }); test('should get registrations and offerings as parts of the event stats', (done) => { request.get('/api/events/' + events[0].id + '/stats') .set('Authorization', generatedUsers.admin.token) .expect(status.OK) .end((err, res: SuperTestResponse<EventStatisticsDto>) => { if (err) { return done(err) } const stats = res.body; expect(stats.registrations).to.have.length(10); expect(stats.scouts).to.have.length(10); expect(stats.offerings).to.have.length(0); return done(); }); }); }); }); <file_sep>/src/server/models/validatorsSpec.ts import { expect } from 'chai'; import { durationValidator } from './validators'; describe('durationValidator', () => { it('should return true for valid period/duration combinations', () => { expect(durationValidator([1, 2], 1)).to.equal(true); expect(durationValidator([3], 1)).to.equal(true); expect(durationValidator([1], 1)).to.equal(true); expect(durationValidator([2, 3], 2)).to.equal(true); expect(durationValidator([1, 2, 3], 3)).to.equal(true); }); it('should return false for invalid period/duration combinations', () => { expect(durationValidator([1, 2, 3], 2)).to.equal(false); expect(durationValidator([1, 2], 2)).to.equal(false); expect(durationValidator([1, 3], 2)).to.equal(false); expect(durationValidator([1, 3], 3)).to.equal(false); expect(durationValidator([1], 2)).to.equal(false); }); }); <file_sep>/src/client/src/mixins/RegistrationMappers.js import _ from 'lodash'; export default { props: { registration: { type: Object, required: true }, event: { type: Object, required: true } }, computed: { assignments() { return this.registration.assignments }, assignmentList() { let result = [null, null, null]; _.forEach(this.registration.assignments, (assignment) => { return _.forEach(assignment.details.periods, (period) => { result[Number(period) - 1] = assignment; }); }); return result; }, scout() { return this.registration.scout }, preferences() { return _.orderBy(this.registration.preferences, ['details.rank']); }, purchases() { return this.registration.purchases }, registrationAssignments() { return _.map(_.omitBy(this.assignmentList, _.isNil), (assignment) => { return { name: assignment.badge.name, price: assignment.price, periods: assignment.details.periods } }); }, registrationPreferences() { return _.map(this.preferences, (preference) => { return { name: preference.badge.name, price: preference.price }; }); }, registrationPurchases() { return _.map(this.purchases, (purchase) => { return { price: purchase.price, size: purchase.details.size, item: purchase.item, quantity: purchase.details.quantity, id: purchase.id }; }); } } } <file_sep>/src/server/routes/index.ts import { Router } from 'express'; import { getIndex } from '@routes/index/getIndex'; export const indexRoutes = Router(); indexRoutes.get('/', getIndex); <file_sep>/src/client/src/validators/date.js import moment from 'moment' export default (format = 'MM/DD/YYYY') => value => moment(value, format, true).isValid();<file_sep>/src/server/routes/scouts/deleteScouts.ts import { Request, Response } from 'express'; import status from 'http-status-codes'; import { ErrorResponseDto } from '@interfaces/shared.interface'; import { Scout } from '@models/scout.model'; import { Event } from '@models/event.model'; import { Registration } from '@models/registration.model'; import { Preference } from '@models/preference.model'; import { Assignment } from '@models/assignment.model'; import { Purchase } from '@models/purchase.model'; export const deleteRegistration = async (req: Request, res: Response) => { try { const scout: Scout = await Scout.findByPk(req.params.scoutId); if (!scout) { throw new Error('Scout not found'); } if (!(await Event.findByPk(req.params.eventId))) { throw new Error('No registration to delete'); } await scout.$remove('registration', req.params.eventId); return res.status(status.OK).end(); } catch (err) { return res.status(status.BAD_REQUEST).json(<ErrorResponseDto>{ message: `Could not unregister ${req.params.scoutId} from event ${req.params.eventId}`, error: err }); } }; export const deletePreference = async (req: Request, res: Response) => { try { const [registration, preference]: [Registration, Preference] = await Promise.all([ Registration.findOne({ where: { id: req.params.registrationId, scout_id: req.params.scoutId } }), Preference.findOne({ where: { offering_id: req.params.offeringId, registration_id: req.params.registrationId } }) ]); if (!registration) { throw new Error('No registration to delete from'); } if (!preference) { throw new Error('Preference to delete not found'); } await registration.$remove('preference', req.params.offeringId); return res.status(status.OK).end(); } catch (err) { return res.status(status.BAD_REQUEST).json(<ErrorResponseDto>{ message: `Could not remove preference ${req.params.offeringId} for registration ${req.params.registrationId}`, error: err }); } }; export const deleteAssignment = async (req: Request, res: Response) => { try { const [registration, assignment]: [Registration, Assignment] = await Promise.all([ Registration.findOne({ where: { id: req.params.registrationId, scout_id: req.params.scoutId } }), Assignment.findOne({ where: { offering_id: req.params.offeringId, registration_id: req.params.registrationId } }) ]); if (!registration) { throw new Error('No registration to delete from'); } if (!assignment) { throw new Error('Assignment to delete not found'); } await registration.$remove('assignment', req.params.offeringId); return res.status(status.OK).end(); } catch (err) { return res.status(status.BAD_REQUEST).json(<ErrorResponseDto>{ message: `Could not remove assignment ${req.params.offeringId} for registration ${req.params.registrationId}`, error: err }); } }; export const deletePurchase = async (req: Request, res: Response) => { try { const [registration, purchase]: [Registration, Purchase] = await Promise.all([ Registration.findOne({ where: { id: req.params.registrationId, scout_id: req.params.scoutId } }), Purchase.findOne({ where: { purchasable_id: req.params.purchasableId, registration_id: req.params.registrationId } }) ]); if (!registration) { throw new Error('No registration to delete from'); } if (!purchase) { throw new Error('Purchase to delete not found'); } await registration.$remove('purchase', req.params.purchasableId); return res.status(status.OK).end(); } catch (err) { return res.status(status.BAD_REQUEST).json(<ErrorResponseDto>{ message: `Could not remove purchase ${req.params.purchasableId} for registration ${req.params.registrationId}`, error: err }); } }; <file_sep>/src/client/src/mixins/ClassSizesUpdate.js import _ from 'lodash'; import { mapGetters } from 'vuex'; export default { data() { return { classesLoading: false, classLoadError: '' }; }, computed: { ...mapGetters(['eventClasses']) }, methods: { sizeInfoForOffering(eventId, offeringId) { const classes = this.classesForEvent(eventId); const classInfo = _.find(classes, { offering_id: offeringId }) || {}; return classInfo.sizeInfo; }, classesForEvent(eventId) { return this.eventClasses[eventId] || []; }, hasClassInfoForEvent(eventId) { const classes = this.classesForEvent(eventId); return classes && classes.length > 0 && classes[0].sizeInfo; }, loadClasses(eventId) { this.classesLoading = true; this.$store .dispatch('getClasses', eventId) .then(classes => { return this.getSizesForBadges( eventId, _.map(classes, 'badge.badge_id') ); }) .then(() => { this.classLoadError = ''; }) .catch(() => { this.classLoadError = 'Failed to get classes for this event'; }) .then(() => { this.classesLoading = false; }); }, getSizesForBadges(eventId, badgeIds) { return new Promise((resolve, reject) => { this.$store.dispatch('getClassSizes', { eventId: eventId, badgeIds: badgeIds }) .then(() => resolve()) .catch(() => reject()); }); } } }; <file_sep>/src/server/routes/users/getUsers.ts import { Request, Response } from 'express'; import status from 'http-status-codes'; import { Op, WhereOptions, Includeable } from 'sequelize'; import { User } from '@models/user.model'; import { ErrorResponseDto } from '@interfaces/shared.interface'; import { UserExistsResponseDto, UserProfileResponseDto } from '@interfaces/user.interface'; import { Scout } from '@models/scout.model'; import registrationInformation from '@models/queries/registrationInformation'; import { cloneDeep } from 'lodash'; import { Registration } from '@models/registration.model'; import { Event } from '@models/event.model'; import { CostCalculationResponseDto } from '@interfaces/registration.interface'; import { CalculationType } from '@routes/shared/calculationType.enum'; export const byEmail = async (req: Request, res: Response) => { try { const users: User[] = await User.findAll({ where: { email: { [ Op.iLike ]: req.params.email } } }); res.status(status.OK).json(<UserExistsResponseDto>{ exists: users.length > 0 }); } catch (err) { res.status(status.BAD_REQUEST).json(<ErrorResponseDto>{ message: 'Failed to find users', error: err }); } }; export const fromToken = async (req: Request, res: Response) => { return res.status(status.OK).json(<UserProfileResponseDto>{ message: 'Successfully authenticated', profile: req.user }); }; export const byId = (includeScouts: boolean = false) => async (req: Request, res: Response) => { let query: WhereOptions; const include: Includeable[] = []; if (req.params.userId) { query = { id: req.params.userId }; } else if (req.params.id) { query = { id: req.params.id }; } else if (Object.keys(req.query).length < 1) { query = {}; } else { return res.status(status.BAD_REQUEST).json(<ErrorResponseDto>{ message: 'Invalid query' }); } if (includeScouts) { include.push({ model: Scout, as: 'scouts' }); } try { const users: User[] = await User.findAll({ where: query, attributes: { exclude: [ 'password' ] }, include: include }); if (users.length < 1) { throw new Error('User not found'); } return res.status(status.OK).json(users); } catch (err) { return res.status(status.BAD_REQUEST).json(<ErrorResponseDto>{ error: err, message: 'Error getting user' }); } }; export const getEventRegistrations = async (req: Request, res: Response) => { try { const query = cloneDeep(registrationInformation); query.where = { event_id: req.params.eventId }; (<any>query.include[0]).where = { user_id: req.params.userId }; const registrations: Registration[] = await Registration.findAll(query); return res.status(status.OK).json(registrations); } catch (err) { return res.status(status.BAD_REQUEST).json(<ErrorResponseDto>{ error: err, message: 'Could not get registrations for event' }); } }; export const getScoutRegistrations = async (req: Request, res: Response) => { try { const scouts: Scout[] = await Scout.findAll({ where: { user_id: req.params.userId }, include: [{ model: Event, as: 'registrations', through: <any>{ as: 'details' }, attributes: [['id', 'event_id']] }] }); res.status(status.OK).json(scouts); } catch (err) { return res.status(status.BAD_REQUEST).json(<ErrorResponseDto>{ error: err, message: 'Could not get registration for scout' }); } }; export const getProjectedCost = async (req: Request, res: Response) => { getCost(req, res, CalculationType.Projected); }; export const getActualCost = async (req: Request, res: Response) => { getCost(req, res, CalculationType.Actual); }; async function getCost(req: Request, res: Response, type: CalculationType): Promise<Response> { try { const registrations: Registration[] = await Registration.findAll({ where: { event_id: req.params.eventId }, include: [{ model: Scout, where: { user_id: req.params.userId } }] }); if (registrations.length < 1) { throw new Error('No registrations found'); } const prices: number[] = await Promise.all(registrations.map(registration => { return (type === CalculationType.Actual ? registration.actualCost() : registration.projectedCost()); })); const cost: number = prices.reduce((acc, cur) => acc + cur, 0); return res.status(status.OK).json(<CostCalculationResponseDto>{ cost: String(cost.toFixed(2)) }); } catch (err) { return res.status(status.BAD_REQUEST).json(<ErrorResponseDto>{ error: err, message: `Could not calculate ${type} pricing information` }); } } <file_sep>/src/client/src/components/users/profile/EditSpec.js import { shallowMount, createLocalVue } from '@vue/test-utils'; import Vuex from 'vuex'; import Vuelidate from 'vuelidate'; import chai from 'chai'; import { expect } from 'chai' import sinon from 'sinon'; import sinonChai from 'sinon-chai'; import Edit from './Edit.vue'; chai.use(sinonChai); const localVue = createLocalVue(); localVue.use(Vuex); localVue.use(Vuelidate); describe('Profile Edit.vue', () => { let wrapper, getters, store, actions, $router; beforeEach(() => { $router = { push: sinon.spy() }; actions = { updateProfile: sinon.stub().resolves() }; getters = { profile: () => { return { firstname: 'First', lastname: 'Last', role: 'coordinator', details: {} }; } }; }); describe('when no props are supplied', () => { beforeEach(() => { store = new Vuex.Store({ actions, getters }); wrapper = shallowMount(Edit, { localVue, store, mocks: { $router } }); }); it('should create', () => { expect(wrapper.isVueInstance()).to.be.true; }); it('should set the editable profile from the store', () => { expect(wrapper.vm.profileUpdate.firstname).to.equal('First'); expect(wrapper.vm.profileUpdate.lastname).to.equal('Last'); }); describe('then saving the changes', () => { beforeEach((done) => { wrapper.find('#save-profile').trigger('click'); actions.updateProfile().then(() => done()); }); xit('should attempt to route', () => { expect(wrapper.vm.$router.push).to.have.been.calledWith('/profile'); }); it('should not emit anything', () => { expect(wrapper.emitted().done).to.be.undefined; }); }); }); describe('when props are supplied', () => { beforeEach(() => { store = new Vuex.Store({ actions, getters }); wrapper = shallowMount(Edit, { localVue, store, mocks: { $router }, propsData: { propProfile: { firstname: 'Props', lastname: 'PropLast' }, routable: false } }); }); it('should create', () => { expect(wrapper.isVueInstance()).to.be.true; }); it('should set the editable profile from the prop', () => { expect(wrapper.vm.profileUpdate.firstname).to.equal('Props'); expect(wrapper.vm.profileUpdate.lastname).to.equal('PropLast'); }); describe('then saving the changes', () => { beforeEach((done) => { wrapper.find('#save-profile').trigger('click'); actions.updateProfile().then(() => done()); }); it('should not attempt to route', () => { expect(wrapper.vm.$router.push).not.to.have.been.called; }); xit('should emit an event', () => { expect(wrapper.emitted().done).not.to.be.undefined; }); }); }); }); <file_sep>/src/server/routes/forgot.ts import { Router } from 'express'; import { forgot , reset } from '@routes/forgot/postForgot'; import { tokenValid } from '@routes/forgot/getForgot'; export const forgotPasswordRoutes = Router(); forgotPasswordRoutes.post('/forgot', forgot); forgotPasswordRoutes.get('/reset/:token', tokenValid); forgotPasswordRoutes.post('/reset', reset); <file_sep>/src/client/src/store/mutation-types.js // Authentication export const LOGIN = 'auth/LOGIN'; export const LOGOUT = 'auth/LOGOUT'; export const PROFILE = 'auth/SAVE_PROFILE'; export const SEND_RESET = 'auth/SEND_RESET_EMAIL'; export const SIGNUP = 'auth/SIGNUP'; export const UPDATE_PROFILE = 'auth/UPDATE_PROFILE'; // Badges export const ADD_BADGE = 'badges/ADD'; export const DELETE_BADGE = 'badges/DELETE'; export const GET_BADGES = 'badges/GET'; export const UPDATE_BADGE = 'badges/UPDATE'; // Classes export const SET_CLASSES = 'classes/SET'; export const SET_CLASS_SIZES = 'classes/SET_SIZES'; // Events export const ADD_EVENT = 'events/ADD'; export const DELETE_EVENT = 'events/DELETE'; export const GET_EVENTS = 'events/GET'; export const SET_CURRENT = 'events/SET_CURRENT'; export const SET_SELECTED = 'events/SET_SELECTED'; export const UPDATE_EVENT = 'events/UPDATE'; // Offerings export const ADD_OFFERING = 'offerings/ADD'; export const DELETE_OFFERING = 'offerings/DELETE'; export const GET_OFFERINGS = 'offerings/GET'; export const SET_OFFERINGS = 'offerings/SET'; export const UPDATE_OFFERING = 'offerings/UPDATE'; // Preferences export const SET_PREFERENCES = 'preferences/SET'; // Purchasables export const DELETE_PURCHASABLE = 'purchasable/DELETE'; export const SET_PURCHASABLES = 'purchasables/SET'; export const UPDATE_PURCHASABLE = 'purchasable/UPDATE'; // Purchases export const DELETE_PURCHASE = 'purchase/DELETE'; export const SET_PURCHASES = 'purchases/SET'; // Registrations export const ADD_REGISTRATION = 'registrations/ADD'; export const DELETE_REGISTRATION = 'registration/DELETE'; export const SET_REGISTRATIONS = 'registrations/SET'; // Event Registrations export const SET_EVENT_REGISTRATIONS = 'eventRegistrations/SET'; export const SET_ASSIGNMENTS = 'eventRegistrationAssignments/SET'; export const SET_COMPLETION = 'eventRegistrationCompletion/SET'; // Scouts export const ADD_SCOUT = 'scouts/ADD'; export const DELETE_SCOUT = 'scouts/DELETE'; export const GET_SCOUT = 'scouts/GET'; export const SET_SCOUTS = 'scouts/SET'; export const UPDATE_SCOUT = 'scouts/UPDATE'; // Users export const APPROVE_USER = 'users/APPROVE'; export const DELETE_USER = 'users/DELETE'; export const GET_USERS = 'users/GET_USERS'; <file_sep>/tests/server/purchasablesSpec.ts import supertest from 'supertest'; import * as async from 'async'; import status from 'http-status-codes'; import { expect } from 'chai'; import app from '@app/app'; import TestUtils, { RoleTokenObjects } from './testUtils'; import { Event } from '@models/event.model'; import { Scout } from '@models/scout.model'; import { UserRole } from '@interfaces/user.interface'; import { Purchasable } from '@models/purchasable.model'; import { CreatePurchasableDto, UpdatePurchasableResponseDto, CreatePurchasablesResponseDto, PurchasablesResponseDto, UpdatePurchasableDto } from '@interfaces/purchasable.interface'; import { Registration } from '@models/registration.model'; import { Purchase } from '@models/purchase.model'; import testScouts from './testScouts'; import { CreatePurchaseRequestDto, Size, CreatePurchaseResponseDto, ScoutPurchasesResponseDto, BuyersResponseDto } from '@interfaces/purchase.interface'; import { SuperTestResponse } from '@test/helpers/supertest.interface'; import { EventsResponseDto } from '@interfaces/event.interface'; import { RegistrationDto, CreateRegistrationResponseDto } from '@interfaces/registration.interface'; const request = supertest(app); describe('purchasables', () => { let events: Event[]; let generatedUsers: RoleTokenObjects; let generatedScouts: Scout[]; let scoutId: string; const badId = TestUtils.badId; beforeAll(async () => { await TestUtils.dropDb(); }); beforeAll(async () => { generatedUsers = await TestUtils.generateTokens([ UserRole.ADMIN, UserRole.TEACHER, UserRole.COORDINATOR, 'coordinator2' as any ]); events = await TestUtils.createEvents(); }); beforeEach(async () => { await TestUtils.dropTable([Purchasable]); }); afterAll(async () => { await TestUtils.dropDb(); await TestUtils.closeDb(); }); describe('creating a purchasable', () => { test('should be able to be created for an event', (done) => { const postData: CreatePurchasableDto = { item: 'T-Shirt', description: 'A t-shirt', price: '10.00' }; request.post('/api/events/' + events[0].id + '/purchasables') .set('Authorization', generatedUsers.admin.token) .send(postData) .expect(status.CREATED) .end((err, res: SuperTestResponse<CreatePurchasablesResponseDto>) => { if (err) { return done(err); } const purchasable = res.body.purchasables[0]; expect(purchasable.item).to.equal(postData.item); expect(purchasable.description).to.equal(postData.description); expect(purchasable.price).to.equal(postData.price); return done(); }); }); test('should not require a description', (done) => { const postData: CreatePurchasableDto = { item: 'T-Shirt', price: '10.00' }; request.post('/api/events/' + events[0].id + '/purchasables') .set('Authorization', generatedUsers.admin.token) .send(postData) .expect(status.CREATED) .end((err, res: SuperTestResponse<CreatePurchasablesResponseDto>) => { if (err) { return done(err); } const purchasable = res.body.purchasables[0]; expect(purchasable.item).to.equal(postData.item); expect(purchasable.price).to.equal(postData.price); return done(); }); }); test('should be created with a maximum age', (done) => { const postData: CreatePurchasableDto = { item: 'Youth Lunch', price: '10.00', maximum_age: 10 }; request.post('/api/events/' + events[0].id + '/purchasables') .set('Authorization', generatedUsers.admin.token) .send(postData) .expect(status.CREATED) .end((err, res: SuperTestResponse<CreatePurchasablesResponseDto>) => { if (err) { return done(err); } const purchasable = res.body.purchasables[0]; expect(purchasable.item).to.equal(postData.item); expect(purchasable.price).to.equal(postData.price); expect(purchasable.maximum_age).to.equal(postData.maximum_age); return done(); }); }); test('should not allow a blank maximum age', (done) => { const postData: any = { item: 'Youth Lunch', price: '10.00', maximum_age: '' }; request.post('/api/events/' + events[0].id + '/purchasables') .set('Authorization', generatedUsers.admin.token) .send(postData) .expect(status.BAD_REQUEST, done); }); test('should not allow a blank minimum age', (done) => { const postData: any = { item: 'Youth Lunch', price: '10.00', minimum_age: '' }; request.post('/api/events/' + events[0].id + '/purchasables') .set('Authorization', generatedUsers.admin.token) .send(postData) .expect(status.BAD_REQUEST, done); }); test('should be created with whether the item has a size', (done) => { const postData: CreatePurchasableDto = { item: 'T-Shirt', price: '10.00', has_size: true }; request.post('/api/events/' + events[0].id + '/purchasables') .set('Authorization', generatedUsers.admin.token) .send(postData) .expect(status.CREATED) .end((err, res: SuperTestResponse<CreatePurchasablesResponseDto>) => { if (err) { return done(err); } const purchasable = res.body.purchasables[0]; expect(purchasable.item).to.equal(postData.item); expect(purchasable.price).to.equal(postData.price); expect(purchasable.has_size).to.be.true; return done(); }); }); test('should not allow size as an empty string', (done) => { const postData: any = { item: 'Youth Lunch', price: '10.00', has_size: '' }; request.post('/api/events/' + events[0].id + '/purchasables') .set('Authorization', generatedUsers.admin.token) .send(postData) .expect(status.BAD_REQUEST, done); }); test('should be created with a minimum', (done) => { const postData: CreatePurchasableDto = { item: 'Adult Lunch', price: '12.00', minimum_age: 10 }; request.post('/api/events/' + events[0].id + '/purchasables') .set('Authorization', generatedUsers.admin.token) .send(postData) .expect(status.CREATED) .end((err, res: SuperTestResponse<CreatePurchasablesResponseDto>) => { if (err) { return done(err); } const purchasable = res.body.purchasables[0]; expect(purchasable.item).to.equal(postData.item); expect(purchasable.price).to.equal(postData.price); expect(purchasable.minimum_age).to.equal(postData.minimum_age); return done(); }); }); test('should create with an age range', (done) => { const postData: CreatePurchasableDto = { item: 'Teen Lunch', price: '12.00', minimum_age: 12, maximum_age: 18 }; request.post('/api/events/' + events[0].id + '/purchasables') .set('Authorization', generatedUsers.admin.token) .send(postData) .expect(status.CREATED) .end((err, res: SuperTestResponse<CreatePurchasablesResponseDto>) => { if (err) { return done(err); } const purchasable = res.body.purchasables[0]; expect(purchasable.item).to.equal(postData.item); expect(purchasable.price).to.equal(postData.price); expect(purchasable.minimum_age).to.equal(postData.minimum_age); expect(purchasable.maximum_age).to.equal(postData.maximum_age); return done(); }); }); test('should not create with an invalid range', (done) => { const postData: CreatePurchasableDto = { item: 'Teen Lunch', price: '12.00', minimum_age: 18, maximum_age: 12 }; request.post('/api/events/' + events[0].id + '/purchasables') .set('Authorization', generatedUsers.admin.token) .send(postData) .expect(status.BAD_REQUEST, done); }); test('should not allow an invalid age', (done) => { const postData: any = { item: 'Teen Lunch', price: '12.00', minimum_age: 'twelve' }; request.post('/api/events/' + events[0].id + '/purchasables') .set('Authorization', generatedUsers.admin.token) .send(postData) .expect(status.BAD_REQUEST, done); }); test('should not create with invalid data', (done) => { request.post('/api/events/' + events[0].id + '/purchasables') .set('Authorization', generatedUsers.admin.token) .send({ item: 'Blank' }) .expect(status.BAD_REQUEST, done); }); test('should require admin authorization', (done) => { request.post('/api/events/' + events[0].id + '/purchasables') .set('Authorization', generatedUsers.teacher.token) .expect(status.UNAUTHORIZED, done); }); test('should not create for a bad event', (done) => { request.post('/api/events/' + badId + '/purchasables') .set('Authorization', generatedUsers.admin.token) .expect(status.BAD_REQUEST, done); }); }); describe('when purchasables exist', () => { let purchasableIds: number[]; beforeEach(async () => { purchasableIds = []; await TestUtils.dropTable([Purchasable]); }); beforeEach((done) => { async.series([ (cb) => { request.post('/api/events/' + events[0].id + '/purchasables') .set('Authorization', generatedUsers.admin.token) .send({ item: 'T-Shirt', price: '15.00', has_size: true }) .expect(status.CREATED) .end((err, res: SuperTestResponse<CreatePurchasablesResponseDto>) => { if (err) { return done(err); } purchasableIds.push(res.body.purchasables[0].id); return cb(); }); }, (cb) => { request.post('/api/events/' + events[0].id + '/purchasables') .set('Authorization', generatedUsers.admin.token) .send({ item: 'Badge', price: '3.50' }) .expect(status.CREATED) .end((err, res: SuperTestResponse<CreatePurchasablesResponseDto>) => { if (err) { return done(err); } purchasableIds.push(res.body.purchasables[1].id); return cb(); }); }, (cb) => { request.post('/api/events/' + events[1].id + '/purchasables') .set('Authorization', generatedUsers.admin.token) .send({ item: 'T-Shirt', price: '10.00', has_size: true }) .expect(status.CREATED) .end((err, res: SuperTestResponse<CreatePurchasablesResponseDto>) => { if (err) { return done(err); } purchasableIds.push(res.body.purchasables[0].id); return cb(); }); }, (cb) => { request.post('/api/events/' + events[1].id + '/purchasables') .set('Authorization', generatedUsers.admin.token) .send({ item: 'Youth Lunch', price: '10.00', maximum_age: 10 }) .expect(status.CREATED) .end((err, res: SuperTestResponse<CreatePurchasablesResponseDto>) => { if (err) { return done(err); } purchasableIds.push(res.body.purchasables[1].id); return cb(); }); } ], done); }); describe('getting purchasables', () => { test('should show purchasables for an event', (done) => { request.get('/api/events/' + events[0].id + '/purchasables') .expect(status.OK) .end((err, res: SuperTestResponse<PurchasablesResponseDto>) => { if (err) { return done(err); } const purchasables = res.body; expect(purchasables).to.have.length(2); expect(purchasables[0].id).to.equal(purchasableIds[0]); expect(purchasables[0].item).to.equal('T-Shirt'); expect(purchasables[0].has_size).to.be.true; expect(purchasables[1].id).to.equal(purchasableIds[1]); expect(purchasables[1].item).to.equal('Badge'); return done(); }); }); test('should get different purchasables for a second event', (done) => { request.get('/api/events/' + events[1].id + '/purchasables') .expect(status.OK) .end((err, res: SuperTestResponse<PurchasablesResponseDto>) => { if (err) { return done(err); } const purchasables = res.body; expect(purchasables).to.have.length(2); expect(purchasables[0].id).to.equal(purchasableIds[2]); expect(purchasables[0].item).to.equal('T-Shirt'); expect(purchasables[0].has_size).to.be.true; expect(purchasables[1].id).to.equal(purchasableIds[3]); expect(purchasables[1].item).to.equal('Youth Lunch'); expect(purchasables[1].maximum_age).to.equal(10); return done(); }); }); test('should include purchasables for all events', (done) => { request.get('/api/events/') .expect(status.OK) .end((err, res: SuperTestResponse<EventsResponseDto>) => { if (err) { return done(err); } const allEvents = res.body; expect(allEvents).to.have.length(2); expect(allEvents[0].purchasables).to.have.length(2); expect(allEvents[1].purchasables).to.have.length(2); return done(); }); }); test('should not get purchasables for a bad event', (done) => { request.get('/api/events/' + badId + '/purchasables') .expect(status.BAD_REQUEST, done); }); }); describe('updating purchasables', () => { test('should update an existing purchasable', (done) => { request.put('/api/events/' + events[0].id + '/purchasables/' + purchasableIds[0]) .set('Authorization', generatedUsers.admin.token) .send(<UpdatePurchasableDto>{ item: 'T-Shirt', price: '10.00', has_size: false }) .expect(status.OK) .end((err, res: SuperTestResponse<UpdatePurchasableResponseDto>) => { if (err) { return done(err); } const purchasable = res.body.purchasable; expect(purchasable.id).to.equal(purchasableIds[0]); expect(purchasable.item).to.equal('T-Shirt'); expect(purchasable.price).to.equal('10.00'); expect(purchasable.has_size).to.be.false; return done(); }); }); test('should update an age requirement', (done) => { request.put('/api/events/' + events[1].id + '/purchasables/' + purchasableIds[3]) .set('Authorization', generatedUsers.admin.token) .send(<UpdatePurchasableDto>{ maximum_age: 8 }) .expect(status.OK) .end((err, res: SuperTestResponse<UpdatePurchasableResponseDto>) => { if (err) { return done(err); } const purchasable = res.body.purchasable; expect(purchasable.id).to.equal(purchasableIds[3]); expect(purchasable.item).to.equal('Youth Lunch'); expect(purchasable.maximum_age).to.equal(8); return done(); }); }); test('should update with new information', (done) => { request.put('/api/events/' + events[0].id + '/purchasables/' + purchasableIds[0]) .set('Authorization', generatedUsers.admin.token) .send(<UpdatePurchasableDto>{ item: 'T-Shirt', description: 'New description', price: '10.00' }) .expect(status.OK) .end((err, res: SuperTestResponse<UpdatePurchasableResponseDto>) => { if (err) { return done(err); } const purchasable = res.body.purchasable; expect(purchasable.id).to.equal(purchasableIds[0]); expect(purchasable.item).to.equal('T-Shirt'); expect(purchasable.description).to.equal('New description'); expect(purchasable.price).to.equal('10.00'); return done(); }); }); test('should not update without required fields', (done) => { request.put('/api/events/' + events[0].id + '/purchasables/' + purchasableIds[0]) .set('Authorization', generatedUsers.admin.token) .send(<UpdatePurchasableDto>{ item: null, price: '10.00' }) .expect(status.BAD_REQUEST, done); }); test('should not update for an invalid event', (done) => { request.put('/api/events/' + badId + '/purchasables/' + purchasableIds[0]) .set('Authorization', generatedUsers.admin.token) .send(<UpdatePurchasableDto>{ item: 'T-Shirt', price: '10.00' }) .expect(status.BAD_REQUEST, done); }); test('should not update for an invalid purchasable', (done) => { request.put('/api/events/' + events[0].id + '/purchasables/' + badId) .set('Authorization', generatedUsers.admin.token) .send(<UpdatePurchasableDto>{ item: 'T-Shirt', price: '10.00' }) .expect(status.BAD_REQUEST, done); }); test('should require admin privileges', (done) => { request.put('/api/events/' + events[0].id + '/purchasables/' + purchasableIds[0]) .set('Authorization', generatedUsers.coordinator.token) .expect(status.UNAUTHORIZED, done); }); test('should not create invalid fields', (done) => { request.put('/api/events/' + events[0].id + '/purchasables/' + purchasableIds[0]) .set('Authorization', generatedUsers.admin.token) .send(<UpdatePurchasableDto>{ item: 'T-Shirt', invalid: 'invalid', price: '10.00' }) .expect(status.OK) .end((err, res: SuperTestResponse<UpdatePurchasableResponseDto>) => { if (err) { return done(err); } const purchasable = res.body.purchasable; expect((purchasable as any).invalid).to.not.exist; return done(); }); }); }); describe('deleting purchasables', () => { test('should delete purchasables from an event', (done) => { async.series([ (cb) => { request.get('/api/events/' + events[0].id + '/purchasables') .expect(status.OK) .end((err, res: SuperTestResponse<PurchasablesResponseDto>) => { if (err) { return done(err); } expect(res.body).to.have.length(2); return cb(); }); }, (cb) => { request.del('/api/events/' + events[0].id + '/purchasables/' + purchasableIds[0]) .set('Authorization', generatedUsers.admin.token) .expect(status.OK, cb); }, (cb) => { request.get('/api/events/' + events[0].id + '/purchasables') .expect(status.OK) .end((err, res: SuperTestResponse<PurchasablesResponseDto>) => { if (err) { return done(err); } expect(res.body).to.have.length(1); expect(res.body[0].id).to.equal(purchasableIds[1]); return cb(); }); } ], done); }); test('should require admin privileges', (done) => { request.del('/api/events/' + events[0].id + '/purchasables/' + purchasableIds[0]) .set('Authorization', generatedUsers.coordinator.token) .expect(status.UNAUTHORIZED, done); }); test('should not delete from a bad event', (done) => { request.del('/api/events/' + badId + '/purchasables/' + purchasableIds[0]) .set('Authorization', generatedUsers.admin.token) .expect(status.BAD_REQUEST, done); }); test('should not delete a bad purchasable', (done) => { request.del('/api/events/' + events[0].id + '/purchasables/' + badId) .set('Authorization', generatedUsers.admin.token) .expect(status.BAD_REQUEST, done); }); }); describe('associating purchasables to a registration', () => { let purchasables: Purchasable[]; let registrationIds: number[]; beforeEach(async () => { await TestUtils.dropTable([Registration, Purchasable, Purchase, Scout]); }); beforeEach(async () => { generatedScouts = await TestUtils.createScoutsForUser(generatedUsers.coordinator, testScouts(5)); }); beforeEach((done) => { scoutId = generatedScouts[0].id; registrationIds = []; async.series([ (cb) => { request.post('/api/scouts/' + scoutId + '/registrations') .set('Authorization', generatedUsers.coordinator.token) .send(<RegistrationDto>{ event_id: events[0].id }) .expect(status.CREATED) .end((err, res: SuperTestResponse<CreateRegistrationResponseDto>) => { if (err) { return done(err); } registrationIds.push(res.body.registration.id); return cb(); }); }, (cb) => { request.post('/api/scouts/' + scoutId + '/registrations') .set('Authorization', generatedUsers.coordinator.token) .send(<RegistrationDto>{ event_id: events[1].id }) .expect(status.CREATED) .end((err, res: SuperTestResponse<CreateRegistrationResponseDto>) => { if (err) { return done(err); } registrationIds.push(res.body.registration.id); return cb(); }); }, (cb) => { request.post('/api/scouts/' + generatedScouts[1].id + '/registrations') .set('Authorization', generatedUsers.coordinator.token) .send(<RegistrationDto>{ event_id: events[0].id }) .expect(status.CREATED) .end((err, res: SuperTestResponse<CreateRegistrationResponseDto>) => { if (err) { return done(err); } registrationIds.push(res.body.registration.id); return cb(); }); } ], done); }); beforeEach(async () => { purchasables = await TestUtils.createPurchasablesForEvent(events[0]); }); describe('creating a purchase', () => { test('should associate the purchasable to an event', (done) => { const postData: CreatePurchaseRequestDto = { purchasable: purchasables[1].id, quantity: 3 }; request.post('/api/scouts/' + scoutId + '/registrations/' + registrationIds[0] + '/purchases') .set('Authorization', generatedUsers.coordinator.token) .send(postData) .expect(status.CREATED) .end((err, res: SuperTestResponse<CreatePurchaseResponseDto>) => { if (err) { return done(err); } expect(res.body.registration.purchases).to.have.length(1); const purchase = res.body.registration.purchases[0]; expect(purchase.id).to.equal(postData.purchasable); expect(purchase.details.quantity).to.equal(postData.quantity); expect(purchase.details.size).to.not.exist; return done(); }); }); test('should allow a scout that is in the valid age range', (done) => { let validPurchaseId: number; async.series([ (cb) => { const postData: CreatePurchasableDto = { item: 'Adult Lunch With Age', price: '12.00', minimum_age: 0 }; request.post('/api/events/' + events[0].id + '/purchasables') .set('Authorization', generatedUsers.admin.token) .send(postData) .expect(status.CREATED) .end((err, res: SuperTestResponse<CreatePurchasablesResponseDto>) => { if (err) { return done(err); } expect(res.body.purchasables[4].item).to.equal(postData.item); validPurchaseId = res.body.purchasables[4].id; return cb(); }); }, (cb) => { const postData: CreatePurchaseRequestDto = { purchasable: validPurchaseId }; request.post('/api/scouts/' + scoutId + '/registrations/' + registrationIds[0] + '/purchases') .set('Authorization', generatedUsers.coordinator.token) .send(postData) .expect(status.CREATED, cb); } ], done); }); xtest('should allow scouts to purchase an item multiple times', (done) => { const postData: CreatePurchaseRequestDto = { purchasable: purchasables[1].id, quantity: 3 }; async.series([ (cb) => { request.post('/api/scouts/' + scoutId + '/registrations/' + registrationIds[0] + '/purchases') .set('Authorization', generatedUsers.coordinator.token) .send(postData) .expect(status.CREATED, cb); }, (cb) => { request.post('/api/scouts/' + scoutId + '/registrations/' + registrationIds[0] + '/purchases') .set('Authorization', generatedUsers.coordinator.token) .send(postData) .expect(status.CREATED, cb); }, (cb) => { request.get('/api/scouts/' + scoutId + '/registrations/' + registrationIds[0] + '/purchases') .set('Authorization', generatedUsers.coordinator.token) .expect(status.OK) .end((err, res) => { if (err) { return done(err); } const purchases = res.body; expect(purchases).to.have.length(2); return cb(); }); } ], done); }); xtest('should not allow a scout that is too old to purchase', (done) => { let invalidPurchaseId: number; async.series([ (cb) => { const postData: CreatePurchasableDto = { item: 'Youth Lunch With Age', price: '12.00', maximum_age: 0 }; request.post('/api/events/' + events[0].id + '/purchasables') .set('Authorization', generatedUsers.admin.token) .send(postData) .expect(status.CREATED) .end((err, res) => { if (err) { return done(err); } expect(res.body.purchasables[4].item).to.equal(postData.item); invalidPurchaseId = res.body.purchasables[4].id; return cb(); }); }, (cb) => { const postData: CreatePurchaseRequestDto = { purchasable: invalidPurchaseId }; request.post('/api/scouts/' + scoutId + '/registrations/' + registrationIds[0] + '/purchases') .set('Authorization', generatedUsers.coordinator.token) .send(postData) .expect(status.BAD_REQUEST, cb); } ], done); }); test('should default to 0 for quantity', (done) => { const postData: CreatePurchaseRequestDto = { purchasable: purchasables[0].id }; request.post('/api/scouts/' + scoutId + '/registrations/' + registrationIds[0] + '/purchases') .set('Authorization', generatedUsers.coordinator.token) .send(postData) .expect(status.CREATED) .end((err, res: SuperTestResponse<CreatePurchaseResponseDto>) => { if (err) { return done(err); } expect(res.body.registration.purchases).to.have.length(1); const purchase = res.body.registration.purchases[0]; expect(purchase.id).to.equal(postData.purchasable); expect(purchase.details.quantity).to.equal(0); expect(purchase.details.size).to.not.exist; return done(); }); }); test('should accept a size', (done) => { const postData: CreatePurchaseRequestDto = { purchasable: purchasables[0].id, size: Size.L, quantity: 2 }; request.post('/api/scouts/' + scoutId + '/registrations/' + registrationIds[0] + '/purchases') .set('Authorization', generatedUsers.coordinator.token) .send(postData) .expect(status.CREATED) .end((err, res: SuperTestResponse<CreatePurchaseResponseDto>) => { if (err) { return done(err); } expect(res.body.registration.purchases).to.have.length(1); const purchase = res.body.registration.purchases[0]; expect(purchase.id).to.equal(postData.purchasable); expect(purchase.details.quantity).to.equal(postData.quantity); expect(purchase.details.size).to.equal(postData.size); return done(); }); }); test('should check for the scouts owner', (done) => { const postData: CreatePurchaseRequestDto = { purchasable: purchasables[0].id, size: Size.L, quantity: 2 }; request.post('/api/scouts/' + scoutId + '/registrations/' + registrationIds[0] + '/purchases') .set('Authorization', generatedUsers.coordinator2.token) .send(postData) .expect(status.UNAUTHORIZED, done); }); test('should not allow teachers to create', (done) => { const postData: CreatePurchaseRequestDto = { purchasable: purchasables[0].id, size: Size.L, quantity: 2 }; request.post('/api/scouts/' + scoutId + '/registrations/' + registrationIds[0] + '/purchases') .set('Authorization', generatedUsers.teacher.token) .send(postData) .expect(status.UNAUTHORIZED, done); }); test('should allow admins to create', (done) => { const postData: CreatePurchaseRequestDto = { purchasable: purchasables[0].id, size: Size.L, quantity: 2 }; request.post('/api/scouts/' + scoutId + '/registrations/' + registrationIds[0] + '/purchases') .set('Authorization', generatedUsers.admin.token) .send(postData) .expect(status.CREATED, done); }); test('should not create for a nonexistant purchasable', (done) => { const postData: CreatePurchaseRequestDto = { purchasable: TestUtils.badId as any, quantity: 1 }; request.post('/api/scouts/' + scoutId + '/registrations/' + registrationIds[0] + '/purchases') .set('Authorization', generatedUsers.coordinator.token) .send(postData) .expect(status.BAD_REQUEST, done); }); test('should not create for a nonexistant registration', (done) => { const postData: CreatePurchaseRequestDto = { purchasable: purchasables[0].id, quantity: 1 }; request.post('/api/scouts/' + scoutId + '/registrations/' + TestUtils.badId + '/purchases') .set('Authorization', generatedUsers.coordinator.token) .send(postData) .expect(status.BAD_REQUEST, done); }); test('should not create for a nonexistant scout', (done) => { const postData: CreatePurchaseRequestDto = { purchasable: purchasables[0].id, quantity: 1 }; request.post('/api/scouts/' + TestUtils.badId + '/registrations/' + registrationIds[0] + '/purchases') .set('Authorization', generatedUsers.coordinator.token) .send(postData) .expect(status.BAD_REQUEST, done); }); }); describe('when purchases already exist', () => { beforeEach((done) => { async.series([ (cb) => { request.post('/api/scouts/' + scoutId + '/registrations/' + registrationIds[0] + '/purchases') .set('Authorization', generatedUsers.coordinator.token) .send(<CreatePurchaseRequestDto>{ purchasable: purchasables[0].id, size: 'l', quantity: 2 }) .expect(status.CREATED, cb); }, (cb) => { request.post('/api/scouts/' + scoutId + '/registrations/' + registrationIds[0] + '/purchases') .set('Authorization', generatedUsers.coordinator.token) .send(<CreatePurchaseRequestDto>{ purchasable: purchasables[1].id, quantity: 1 }) .expect(status.CREATED, cb); }, (cb) => { request.post('/api/scouts/' + scoutId + '/registrations/' + registrationIds[1] + '/purchases') .set('Authorization', generatedUsers.coordinator.token) .send(<CreatePurchaseRequestDto>{ purchasable: purchasables[3].id, quantity: 5 }) .expect(status.CREATED, cb); }, (cb) => { request.post('/api/scouts/' + generatedScouts[1].id + '/registrations/' + registrationIds[2] + '/purchases') .set('Authorization', generatedUsers.coordinator.token) .send(<CreatePurchaseRequestDto>{ purchasable: purchasables[0].id, quantity: 5 }) .expect(status.CREATED, cb); }, (cb) => { request.post('/api/scouts/' + generatedScouts[1].id + '/registrations/' + registrationIds[2] + '/purchases') .set('Authorization', generatedUsers.coordinator.token) .send(<CreatePurchaseRequestDto>{ purchasable: purchasables[3].id, quantity: 5 }) .expect(status.CREATED, cb); } ], done); }); describe('getting purchases', () => { test('should get all purchases for a registration', (done) => { request.get('/api/scouts/' + scoutId + '/registrations/' + registrationIds[0] + '/purchases') .set('Authorization', generatedUsers.coordinator.token) .expect(status.OK) .end((err, res: SuperTestResponse<ScoutPurchasesResponseDto>) => { if (err) { return done(err); } const purchases = res.body; expect(purchases).to.have.length(2); expect(purchases[0].id).to.equal(purchasables[0].id); expect(purchases[0].details.size).to.equal('l'); expect(purchases[0].details.quantity).to.equal(2); expect(purchases[1].id).to.equal(purchasables[1].id); expect(purchases[1].details.quantity).to.equal(1); expect(purchases[1].details.size).to.not.exist; return done(); }); }); test('should not get with an incorrect scout', (done) => { request.get('/api/scouts/' + badId + '/registrations/' + registrationIds[0] + '/purchases') .set('Authorization', generatedUsers.coordinator.token) .expect(status.BAD_REQUEST, done); }); test('should not get with an incorrect registration', (done) => { request.get('/api/scouts/' + generatedScouts[0].id + '/registrations/' + badId + '/purchases') .set('Authorization', generatedUsers.coordinator.token) .expect(status.BAD_REQUEST, done); }); test('should get the buyers of an item', async () => { await request.get(`/api/events/${events[0].id}/purchasables/${purchasables[0].id}/buyers`) .set('Authorization', generatedUsers.admin.token) .expect(status.OK) .then((res: SuperTestResponse<BuyersResponseDto>) => { expect(res.body).to.have.length(2); const buyers = res.body; expect(buyers[0].scout.firstname).to.equal(generatedScouts[0].firstname); expect(buyers[0].purchases).to.have.length(1); expect(buyers[0].purchases[0].item).to.equal(purchasables[0].item); expect(buyers[0].purchases[0].details.quantity).to.equal(2); expect(buyers[1].scout.firstname).to.equal(generatedScouts[1].firstname); expect(buyers[1].purchases).to.have.length(1); expect(buyers[1].purchases[0].item).to.equal(purchasables[0].item); expect(buyers[1].purchases[0].details.quantity).to.equal(5); }); await request.get(`/api/events/${events[0].id}/purchasables/${purchasables[1].id}/buyers`) .set('Authorization', generatedUsers.admin.token) .expect(status.OK) .then((res: SuperTestResponse<BuyersResponseDto>) => { expect(res.body).to.have.length(1); const buyers = res.body; expect(buyers[0].scout.firstname).to.equal(generatedScouts[0].firstname); expect(buyers[0].purchases).to.have.length(1); expect(buyers[0].purchases[0].item).to.equal(purchasables[1].item); expect(buyers[0].purchases[0].details.quantity).to.equal(1); }); }); test('should not get buyers for an invalid item', async () => { await request.get(`/api/events/${events[0].id}/purchasables/${badId}/buyers`) .set('Authorization', generatedUsers.admin.token) .expect(status.OK) .then((res: SuperTestResponse<BuyersResponseDto>) => { expect(res.body).to.have.length(0); }); }); test('should not allow coordinators to get buyers', async () => { await request.get(`/api/events/${events[0].id}/purchasables/${purchasables[0].id}/buyers`) .set('Authorization', generatedUsers.coordinator.token) .expect(status.UNAUTHORIZED); }); }); describe('updating purchases', () => { test('should update a purchase', (done) => { async.series([ (cb) => { request.get('/api/scouts/' + generatedScouts[0].id + '/registrations/' + registrationIds[0] + '/purchases') .set('Authorization', generatedUsers.coordinator.token) .expect(status.OK) .end((err, res: SuperTestResponse<ScoutPurchasesResponseDto>) => { if (err) { return done(err); } expect(res.body[0].details.quantity).to.equal(2); return cb(); }); }, (cb) => { request.put('/api/scouts/' + generatedScouts[0].id + '/registrations/' + registrationIds[0] + '/purchases/' + purchasables[0].id) .set('Authorization', generatedUsers.coordinator.token) .send(<CreatePurchaseRequestDto>{ quantity: 1 }) .expect(status.OK, cb); }, (cb) => { request.get('/api/scouts/' + generatedScouts[0].id + '/registrations/' + registrationIds[0] + '/purchases') .set('Authorization', generatedUsers.coordinator.token) .expect(status.OK) .end((err, res: SuperTestResponse<ScoutPurchasesResponseDto>) => { if (err) { return done(err); } expect(res.body[0].details.quantity).to.equal(1); return cb(); }); } ], done); }); test('should check for the scouts owner', (done) => { request.put('/api/scouts/' + generatedScouts[0].id + '/registrations/' + registrationIds[0] + '/purchases/' + purchasables[0].id) .set('Authorization', generatedUsers.coordinator2.token) .send(<CreatePurchaseRequestDto>{ quantity: 1 }) .expect(status.UNAUTHORIZED, done); }); test('should not allow teachers to update', (done) => { request.put('/api/scouts/' + generatedScouts[0].id + '/registrations/' + registrationIds[0] + '/purchases/' + purchasables[0].id) .set('Authorization', generatedUsers.teacher.token) .send(<CreatePurchaseRequestDto>{ quantity: 1 }) .expect(status.UNAUTHORIZED, done); }); test('should allow admins to update', (done) => { request.put('/api/scouts/' + generatedScouts[0].id + '/registrations/' + registrationIds[0] + '/purchases/' + purchasables[0].id) .set('Authorization', generatedUsers.admin.token) .send(<CreatePurchaseRequestDto>{ quantity: 1 }) .expect(status.OK, done); }); test('should not update an invalid purchase', (done) => { request.put('/api/scouts/' + generatedScouts[0].id + '/registrations/' + registrationIds[0] + '/purchases/' + TestUtils.badId) .set('Authorization', generatedUsers.coordinator.token) .send(<CreatePurchaseRequestDto>{ quantity: 1 }) .expect(status.BAD_REQUEST, done); }); test('should not update an invalid registration', (done) => { request.put('/api/scouts/' + generatedScouts[0].id + '/registrations/' + TestUtils.badId + '/purchases/' + purchasables[0].id) .set('Authorization', generatedUsers.coordinator.token) .send(<CreatePurchaseRequestDto>{ quantity: 1 }) .expect(status.BAD_REQUEST, done); }); test('should not update an invalid scout', (done) => { request.put('/api/scouts/' + TestUtils.badId + '/registrations/' + registrationIds[0] + '/purchases/' + purchasables[0].id) .set('Authorization', generatedUsers.coordinator.token) .send(<CreatePurchaseRequestDto>{ quantity: 1 }) .expect(status.BAD_REQUEST, done); }); test('should not update a purchase for the wrong registration', (done) => { request.put('/api/scouts/' + generatedScouts[0].id + '/registrations/' + registrationIds[0] + '/purchases/' + purchasables[3].id) .set('Authorization', generatedUsers.coordinator.token) .send(<CreatePurchaseRequestDto>{ quantity: 1 }) .expect(status.BAD_REQUEST, done); }); test('should not allow a required value to be unset', (done) => { request.put('/api/scouts/' + generatedScouts[0].id + '/registrations/' + registrationIds[0] + '/purchases/' + purchasables[0].id) .set('Authorization', generatedUsers.coordinator.token) .send(<CreatePurchaseRequestDto>{ quantity: null }) .expect(status.BAD_REQUEST, done); }); }); describe('deleting purchases', () => { test('should delete a purchase', (done) => { async.series([ (cb) => { request.get('/api/scouts/' + generatedScouts[0].id + '/registrations/' + registrationIds[0] + '/purchases') .set('Authorization', generatedUsers.coordinator.token) .expect(status.OK) .end((err, res: SuperTestResponse<ScoutPurchasesResponseDto>) => { if (err) { return done(err); } expect(res.body).to.have.length(2); return cb(); }); }, (cb) => { request.del('/api/scouts/' + generatedScouts[0].id + '/registrations/' + registrationIds[0] + '/purchases/' + purchasables[0].id) .set('Authorization', generatedUsers.coordinator.token) .expect(status.OK, cb); }, (cb) => { request.get('/api/scouts/' + generatedScouts[0].id + '/registrations/' + registrationIds[0] + '/purchases') .set('Authorization', generatedUsers.coordinator.token) .expect(status.OK) .end((err, res: SuperTestResponse<ScoutPurchasesResponseDto>) => { if (err) { return done(err); } expect(res.body).to.have.length(1); return cb(); }); } ], done); }); test('should check for the scouts owner', (done) => { request.del('/api/scouts/' + generatedScouts[0].id + '/registrations/' + registrationIds[0] + '/purchases/' + purchasables[0].id) .set('Authorization', generatedUsers.coordinator2.token) .expect(status.UNAUTHORIZED, done); }); test('should not allow teachers to delete', (done) => { request.del('/api/scouts/' + generatedScouts[0].id + '/registrations/' + registrationIds[0] + '/purchases/' + purchasables[0].id) .set('Authorization', generatedUsers.teacher.token) .expect(status.UNAUTHORIZED, done); }); test('should allow admins to delete', (done) => { request.del('/api/scouts/' + generatedScouts[0].id + '/registrations/' + registrationIds[0] + '/purchases/' + purchasables[0].id) .set('Authorization', generatedUsers.admin.token) .expect(status.OK, done); }); test('should not delete an invalid purchase', (done) => { request.del('/api/scouts/' + generatedScouts[0].id + '/registrations/' + registrationIds[0] + '/purchases/' + TestUtils.badId) .set('Authorization', generatedUsers.coordinator.token) .expect(status.BAD_REQUEST, done); }); test('should not delete an invalid registration', (done) => { request.del('/api/scouts/' + generatedScouts[0].id + '/registrations/' + TestUtils.badId + '/purchases/' + purchasables[0].id) .set('Authorization', generatedUsers.coordinator.token) .expect(status.BAD_REQUEST, done); }); test('should not delete an invalid scout', (done) => { request.del('/api/scouts/' + TestUtils.badId + '/registrations/' + registrationIds[0] + '/purchases/' + purchasables[0].id) .set('Authorization', generatedUsers.coordinator.token) .expect(status.BAD_REQUEST, done); }); test('should not delete a purchase for the wrong registration', (done) => { request.del('/api/scouts/' + generatedScouts[0].id + '/registrations/' + registrationIds[0] + '/purchases/' + purchasables[3].id) .set('Authorization', generatedUsers.coordinator.token) .expect(status.BAD_REQUEST, done); }); }); describe('when an associated purchasable is deleted', () => { test('should delete associated purchases', async () => { await request.get('/api/scouts/' + scoutId + '/registrations/' + registrationIds[0] + '/purchases') .set('Authorization', generatedUsers.coordinator.token) .expect(status.OK) .then((res: SuperTestResponse<ScoutPurchasesResponseDto>) => { expect(res.body).to.have.length(2); }); await request.del('/api/events/' + events[0].id + '/purchasables/' + purchasableIds[0]) .set('Authorization', generatedUsers.admin.token) .expect(status.OK); await request.get('/api/scouts/' + scoutId + '/registrations/' + registrationIds[0] + '/purchases') .set('Authorization', generatedUsers.coordinator.token) .expect(status.OK) .then((res: SuperTestResponse<ScoutPurchasesResponseDto>) => { expect(res.body).to.have.length(1); }); }); }); }); }); }); }); <file_sep>/src/libs/interfaces/offering.interface.ts import { BadgeInterface } from '@interfaces/badge.interface'; import { RegistrationInterface } from '@interfaces/registration.interface'; export interface OfferingInterface { id?: number; duration?: number; periods?: number[]; price?: number|string; requirements?: string[]; badge?: BadgeInterface; assignees?: RegistrationInterface[]; event_id?: number; badge_id?: number; size_limit?: number; } export interface OfferingDto<T = any> extends OfferingInterface { offering_id?: number; details?: T; } export interface CreateOfferingDto { badge_id: number; offering: OfferingInterface; } export interface OfferingResponseDto { message: string; offering: OfferingInterface; } <file_sep>/src/client/src/components/MainSpec.js // import 'babel-polyfill'; import { expect } from 'chai' import Vue from 'vue'; import Main from './Main.vue'; import Vuex from 'vuex'; import { shallowMount } from '@vue/test-utils'; Vue.use(Vuex); describe('Main', () => { let wrapper, store, getters; describe('when logged out', () => { beforeEach(() => { getters = { isAuthenticated: () => false, isTeacher: () => false, isCoordinator: () => false, isAdmin: () => false, currentEvent: () => { return { semester: 'Fall', year: '2017' } } }; store = new Vuex.Store({ getters }); wrapper = shallowMount(Main, { store }); }); it('should show a welcome message', () => { expect(wrapper.findAll('#genericWelcome')).to.have.lengthOf(1); }); it('should show a signup link', () => { expect(wrapper.text()).to.contain('signup'); }); it('should show a login link', () => { expect(wrapper.text()).to.contain('Login'); }); it('should not show the admin welcome', () => { expect(wrapper.findAll('#adminWelcome')).to.have.lengthOf(0); }); it('should not show the teacher welcome', () => { expect(wrapper.findAll('#teacherWelcome')).to.have.lengthOf(0); }); it('should not show the coordinator welcome', () => { expect(wrapper.findAll('#coordinatorWelcome')).to.have.lengthOf(0); }); }); describe('when logged in as an admin', () => { beforeEach(() => { getters = { isAuthenticated: () => true, isTeacher: () => false, isCoordinator: () => false, isAdmin: () => true, currentEvent: () => { return { semester: 'Fall', year: '2017' } } }; store = new Vuex.Store({ getters }); wrapper = shallowMount(Main, { store }); }); it('should not show the generic welcome message', () => { expect(wrapper.findAll('#genericWelcome')).to.have.lengthOf(0); }); it('should show the admin welcome', () => { expect(wrapper.findAll('#adminWelcome')).to.have.lengthOf(1); }); it('should not show the teacher welcome', () => { expect(wrapper.findAll('#teacherWelcome')).to.have.lengthOf(0); }); it('should not show the coordinator welcome', () => { expect(wrapper.findAll('#coordinatorWelcome')).to.have.lengthOf(0); }); }); describe('when logged in as a teacher', () => { beforeEach(() => { getters = { isAuthenticated: () => true, isTeacher: () => true, isCoordinator: () => false, isAdmin: () => false, currentEvent: () => { return { semester: 'Fall', year: '2017' } } }; store = new Vuex.Store({ getters }); wrapper = shallowMount(Main, { store }); }); it('should not show the generic welcome message', () => { expect(wrapper.findAll('#genericWelcome')).to.have.lengthOf(0); }); it('should not show the admin welcome', () => { expect(wrapper.findAll('#adminWelcome')).to.have.lengthOf(0); }); it('should show the teacher welcome', () => { expect(wrapper.findAll('#teacherWelcome')).to.have.lengthOf(1); }); it('should not show the coordinator welcome', () => { expect(wrapper.findAll('#coordinatorWelcome')).to.have.lengthOf(0); }); }); describe('when logged in as a coordinator', () => { beforeEach(() => { getters = { isAuthenticated: () => true, isTeacher: () => false, isCoordinator: () => true, isAdmin: () => false, currentEvent: () => { return { semester: 'Fall', year: '2017' } } }; store = new Vuex.Store({ getters }); wrapper = shallowMount(Main, { store }); }); it('should not show the generic welcome message', () => { expect(wrapper.findAll('#genericWelcome')).to.have.lengthOf(0); }); it('should not show the admin welcome', () => { expect(wrapper.findAll('#adminWelcome')).to.have.lengthOf(0); }); it('should not show the teacher welcome', () => { expect(wrapper.findAll('#teacherWelcome')).to.have.lengthOf(0); }); it('should show the coordinator welcome', () => { expect(wrapper.findAll('#coordinatorWelcome')).to.have.lengthOf(1); }); }); }); <file_sep>/src/client/types/vue-tooltip.d.ts declare module 'v-tooltip';<file_sep>/src/server/models/registration.model.ts import { Model, PrimaryKey, Column, AutoIncrement, ForeignKey, Table, BelongsToMany, BelongsTo } from 'sequelize-typescript'; import { Event } from '@models/event.model'; import { Scout } from '@models/scout.model'; import { Offering } from '@models/offering.model'; import { Preference } from '@models/preference.model'; import { Assignment } from '@models/assignment.model'; import { Purchasable } from '@models/purchasable.model'; import { Purchase } from '@models/purchase.model'; import { RegistrationInterface } from '@interfaces/registration.interface'; @Table({ underscored: true, tableName: 'Registrations' }) export class Registration extends Model<Registration> implements RegistrationInterface { @PrimaryKey @AutoIncrement @Column public id: number; @ForeignKey(() => Event) @Column({ allowNull: false, unique: 'event_registration' }) public event_id!: number; @ForeignKey(() => Scout) @Column({ allowNull: false, unique: 'event_registration' }) public scout_id!: number; @Column public notes: string; @BelongsTo(() => Scout) public scout: Scout; @BelongsToMany(() => Offering, () => Preference, 'registration_id', 'offering_id') public preferences: Offering[]; @BelongsToMany(() => Offering, () => Assignment, 'registration_id', 'offering_id') public assignments: Offering[]; @BelongsToMany(() => Purchasable, () => Purchase, 'registration_id', 'purchasable_id') public purchases: Purchasable[]; public async projectedCost(): Promise<number> { let totalCost: number = 0; const [purchases, preferences, event]: [Purchasable[], Offering[], Event] = await Promise.all([ this.$get('purchases'), this.$get('preferences'), Event.findByPk(this.event_id) ]) as [Purchasable[], Offering[], Event]; totalCost = purchases.reduce((sum, purchase) => { return sum + (Number(purchase.price) * Number(purchase.Purchase.quantity)); }, totalCost); totalCost = preferences.reduce((sum, preference) => { return sum + Number(preference.price); }, totalCost); totalCost += Number(event.price); return totalCost; } public async actualCost(): Promise<number> { let totalCost: number = 0; const [purchases, assignments, event]: [Purchasable[], Offering[], Event] = await Promise.all([ this.$get('purchases'), this.$get('assignments'), Event.findByPk(this.event_id) ]) as [Purchasable[], Offering[], Event]; totalCost = purchases.reduce((sum, purchase) => { return sum + (Number(purchase.price) * Number(purchase.Purchase.quantity)); }, totalCost); totalCost = assignments.reduce((sum, assignment) => { return sum + Number(assignment.price); }, totalCost); totalCost += Number(event.price); return totalCost; } } <file_sep>/src/server/models/user.model.ts import { Sequelize } from 'sequelize'; import bcrypt from 'bcrypt'; import { isEmpty, omit } from 'lodash'; import { Model, Table, Column, Default, DataType, Validator, BeforeCreate, BeforeUpdate, HasMany } from 'sequelize-typescript'; import { Scout } from '@models/scout.model'; import { UserInterface, UserRole } from '@interfaces/user.interface'; @Table({ underscored: true, indexes: [ { unique: true, fields: [Sequelize.fn('lower', Sequelize.col('email')) as any] } ], tableName: 'Users' }) export class User extends Model<User> implements UserInterface { @BeforeCreate public static async hashPassword(user: User): Promise<void> { const salt = await bcrypt.genSalt(User.SALT_FACTOR); const hashedPassword = await bcrypt.hash(user.password, salt); user.password = <PASSWORD>; } @BeforeUpdate public static async updateHashedPassword(user: User): Promise<void> { if (user.changed('password')) { const salt = await bcrypt.genSalt(User.SALT_FACTOR); const hashedPassword = await bcrypt.hash(user.password, salt); user.password = hashedPassword; } } private static readonly SALT_FACTOR = process.env.NODE_ENV === 'test' ? 1 : 12; @Column({ allowNull: false, unique: true, validate: { isEmail: true, notEmpty: true } }) public email!: string; @Column({ allowNull: false }) public password!: string; @Column public reset_password_token: string; @Column public reset_token_expires: Date; @Column({ allowNull: false, validate: { notEmpty: true } }) public firstname!: string; @Column({ allowNull: false, validate: { notEmpty: true } }) public lastname!: string; @Default(UserRole.ANONYMOUS) @Column({ allowNull: false, defaultValue: UserRole.ANONYMOUS, type: DataType.STRING, validate: { isIn: [ ['admin', 'coordinator', 'teacher', 'anonymous'] ] } }) public role!: UserRole; @Default(false) @Column public approved!: boolean; @Default({}) @Column(DataType.JSON) public details: Object; @HasMany(() => Scout, 'user_id') public scouts: Scout[]; @Column(DataType.VIRTUAL) public get fullname(): string { return `${this.firstname.trim()} ${this.lastname.trim()}`; } @Validator public detailsValidator(): void { let allowedFields; if (this.role === UserRole.COORDINATOR) { allowedFields = ['troop', 'district', 'council']; if (!isEmpty(omit(this.details, allowedFields))) { throw new Error('Invalid details for coordinator'); } } if (this.role === UserRole.TEACHER) { allowedFields = ['chapter']; if (!isEmpty(omit(this.details, allowedFields))) { throw new Error('Invalid details for teacher'); } } } public comparePassword(candidatePassword: string): Promise<boolean> { return bcrypt.compare(candidatePassword, this.password); } } <file_sep>/tests/server/preferenceAssignmentSpec.ts import supertest from 'supertest'; import * as async from 'async'; import status from 'http-status-codes'; import { expect } from 'chai'; import app from '@app/app'; import TestUtils, { RoleTokenObjects } from './testUtils'; import { Event } from '@models/event.model'; import { Purchasable } from '@models/purchasable.model'; import { Scout } from '@models/scout.model'; import { Badge } from '@models/badge.model'; import { Offering } from '@models/offering.model'; import { UserRole } from '@interfaces/user.interface'; import { OfferingInterface } from '@interfaces/offering.interface'; import testScouts from './testScouts'; import { CreatePreferenceRequestDto, CreatePreferenceResponseDto, PreferenceInterface } from '@interfaces/preference.interface'; import { CreateAssignmentRequestDto } from '@interfaces/assignment.interface'; import { CreateRegistrationResponseDto, RegistrationRequestDto, RegistrationsResponseDto } from '@interfaces/registration.interface'; import { SuperTestResponse } from '@test/helpers/supertest.interface'; import { CreatePurchaseRequestDto } from '@interfaces/purchase.interface'; import { ScoutsResponseDto, ScoutDto } from '@interfaces/scout.interface'; import { AssigneesResponseDto } from '@interfaces/event.interface'; const request = supertest(app); describe('using preference and assignments', () => { let events: Event[]; let purchasables: Purchasable[]; let generatedUsers: RoleTokenObjects; let generatedScouts: Scout[]; let generatedBadges: Badge[]; let generatedOfferings: Offering[]; let preferences: { [key: string]: PreferenceInterface[]}; const badId = TestUtils.badId; beforeAll(async () => { await TestUtils.dropDb(); }); beforeAll(async () => { const defaultPostData: OfferingInterface = { price: 10, periods: [1, 2, 3], duration: 1 }; generatedUsers = await TestUtils.generateTokens([ UserRole.ADMIN, UserRole.TEACHER, UserRole.COORDINATOR, 'coordinator2' as any ]); preferences = {}; events = await TestUtils.createEvents(); generatedBadges = await TestUtils.createBadges(); generatedOfferings = await TestUtils.createOfferingsForEvent(events[0], generatedBadges, defaultPostData); generatedScouts = await TestUtils.createScoutsForUser(generatedUsers.coordinator, testScouts(5)); await TestUtils.createScoutsForUser(generatedUsers.coordinator2, testScouts(5)); purchasables = await TestUtils.createPurchasablesForEvent(events[0]); }); beforeAll((done) => { const postData: CreatePreferenceRequestDto[] = [{ offering: generatedOfferings[0].id, rank: 1 }, { offering: generatedOfferings[1].id, rank: 2 }]; async.forEachOfSeries(generatedScouts, (scout, index, cb) => { let registrationId: number; async.series([ (next) => { request.post('/api/scouts/' + scout.id + '/registrations') .set('Authorization', generatedUsers.coordinator.token) .send(<RegistrationRequestDto>{ event_id: events[0].id }) .expect(status.CREATED) .end((err, res: SuperTestResponse<CreateRegistrationResponseDto>) => { if (err) { return done(err); } registrationId = res.body.registration.id; return next(); }); }, (next) => { request.post('/api/scouts/' + scout.id + '/registrations/' + registrationId + '/purchases') .set('Authorization', generatedUsers.coordinator.token) .send(<CreatePurchaseRequestDto>{ purchasable: purchasables[0].id, quantity: 2, size: 'l' }) .expect(status.CREATED, next); }, (next) => { request.post('/api/scouts/' + scout.id + '/registrations/' + registrationId + '/preferences') .set('Authorization', generatedUsers.admin.token) .send(postData) .expect(status.CREATED) .end((err, res: SuperTestResponse<CreatePreferenceResponseDto>) => { if (err) { return done(err); } preferences[registrationId] = res.body.registration.preferences; return next(); }); }, (next) => { const assignmentPost: CreateAssignmentRequestDto[] = [{ periods: [1], offering: generatedOfferings[0].id }, { periods: [2], offering: generatedOfferings[1].id }, { periods: [3], offering: generatedOfferings[2].id }]; request.post('/api/scouts/' + scout.id + '/registrations/' + registrationId + '/assignments') .set('Authorization', generatedUsers.admin.token) .send(assignmentPost) .expect(status.CREATED, next); } ], cb); }, done); }); afterAll(async () => { await TestUtils.dropDb(); await TestUtils.closeDb(); }); describe('getting scouts that are registered for an event', () => { test('should get all registrations for an event', (done) => { request.get('/api/events/' + events[0].id + '/registrations') .set('Authorization', generatedUsers.admin.token) .expect(status.OK) .end((err, res: SuperTestResponse<RegistrationsResponseDto>) => { if (err) { return done(err); } res.body.forEach((registration) => { expect(registration.scout_id).to.exist; expect(registration.scout).to.exist; expect(registration.scout.firstname).to.exist; expect(registration.scout.lastname).to.exist; expect(registration.scout.troop).to.exist; expect(registration.preferences).to.have.lengthOf(2); expect(registration.assignments).to.have.lengthOf(3); expect(registration.purchases).to.have.lengthOf(1); registration.preferences.forEach((preference) => { expect(preference.badge.name).to.exist; expect(preference.details.rank).to.exist; }); registration.purchases.forEach((purchase) => { expect(purchase.item).to.exist; expect(purchase.price).to.exist; expect(purchase.details.quantity).to.exist; expect(purchase.details.size).to.exist; }); registration.assignments.forEach((assignment) => { expect(assignment.badge.name).to.exist; expect(assignment.details.periods).to.exist; expect(assignment.details.completions).to.exist; expect(assignment.price).to.exist; }); }); return done(); }); }); test('should allow teachers to see registrations', (done) => { request.get('/api/events/' + events[0].id + '/registrations') .set('Authorization', generatedUsers.teacher.token) .expect(status.OK, done); }); test('should not allow coordinators to see registrations', (done) => { request.get('/api/events/' + events[0].id + '/registrations') .set('Authorization', generatedUsers.coordinator.token) .expect(status.UNAUTHORIZED, done); }); test('should fail gracefully for a bad id', (done) => { request.get('/api/events/' + badId + '/registrations') .set('Authorization', generatedUsers.teacher.token) .expect(status.OK, done); }); }); describe('getting all scouts and all registrations', () => { test('should get all scouts of the site', (done) => { request.get('/api/scouts') .set('Authorization', generatedUsers.admin.token) .expect(status.OK) .end((err, res: SuperTestResponse<ScoutsResponseDto>) => { if (err) { return done(err); } const scouts = res.body; expect(scouts).to.have.lengthOf(10); scouts.forEach((scout) => { expect(scout.firstname).to.exist; expect(scout.lastname).to.exist; expect(scout.troop).to.exist; expect(scout.emergency_name).to.exist; expect(scout.emergency_phone).to.exist; expect(scout.emergency_relation).to.exist; expect(scout.notes).to.exist; expect(scout.registrations).to.exist; expect(scout.user).to.exist; }); return done(); }); }); test('should allow teachers to get a list of scouts', (done) => { request.get('/api/scouts') .set('Authorization', generatedUsers.teacher.token) .expect(status.OK, done); }); test('should get some details of the registration', (done) => { request.get('/api/scouts') .set('Authorization', generatedUsers.admin.token) .expect(status.OK) .end((err, res: SuperTestResponse<ScoutsResponseDto>) => { if (err) { return done(err); } const scouts = res.body; expect(scouts).to.have.lengthOf(10); scouts.forEach((scout) => { scout.registrations.forEach((registration) => { expect(registration.details.id).to.exist; expect(registration.event_id).to.exist; expect(registration.year).to.exist; expect(registration.semester).to.exist; }); }); return done(); }); }); test('should get some details of the user', (done) => { request.get('/api/scouts') .set('Authorization', generatedUsers.admin.token) .expect(status.OK) .end((err, res: SuperTestResponse<ScoutsResponseDto>) => { if (err) { return done(err); } const scouts = res.body; expect(scouts).to.have.lengthOf(10); scouts.forEach((scout) => { expect(scout.user.fullname).to.exist; expect(scout.user.email).to.exist; expect(scout.user.user_id).to.exist; }); return done(); }); }); test('should not allow coordinators to access', (done) => { request.get('/api/scouts') .set('Authorization', generatedUsers.coordinator.token) .expect(status.UNAUTHORIZED, done); }); test('should also get details for a single scout', (done) => { request.get('/api/scouts/' + generatedScouts[0].id) .set('Authorization', generatedUsers.admin.token) .expect(status.OK) .end((err, res: SuperTestResponse<ScoutDto>) => { if (err) { return done(err); } const scout = res.body; expect(scout.scout_id).to.equal(generatedScouts[0].id); expect(scout.registrations).to.have.lengthOf(1); expect(scout.user).to.exist; return done(); }); }); }); describe('getting scouts that are assigned to a class', () => { test('should get all assignees for an event', (done) => { request.get('/api/events/' + events[0].id + '/offerings/assignees') .set('Authorization', generatedUsers.admin.token) .expect(status.OK) .end((err, res: SuperTestResponse<AssigneesResponseDto>) => { if (err) { return done(err); } const offerings = res.body; expect(offerings).to.have.lengthOf(3); offerings.forEach((offering) => { expect(offering.badge.name).to.exist; expect(offering.assignees).to.have.lengthOf(5); offering.assignees.forEach((assignee) => { expect(assignee.scout.fullname).to.exist; expect(assignee.scout.troop).to.exist; expect(assignee.assignment.periods).to.exist; expect(assignee.assignment.completions).to.exist; }); }); return done(); }); }); test('should allow teachers to access assignees', (done) => { request.get('/api/events/' + events[0].id + '/offerings/assignees') .set('Authorization', generatedUsers.teacher.token) .expect(status.OK, done); }); test('should not allow coordinators to access assignees', (done) => { request.get('/api/events/' + events[0].id + '/offerings/assignees') .set('Authorization', generatedUsers.coordinator.token) .expect(status.UNAUTHORIZED, done); }); }); }); <file_sep>/src/server/middleware/isOwner.ts import { Request, Response, NextFunction } from 'express'; import passport from 'passport'; import status from 'http-status-codes'; import { User } from '@models/user.model'; import { UserRole } from '@interfaces/user.interface'; import { Scout } from '@models/scout.model'; import { MessageResponseDto } from '@interfaces/shared.interface'; export const isOwner = (req: Request, res: Response, next: NextFunction) => { passport.authenticate('jwt', { session: false }, async (_err, user: User) => { if (user.role === UserRole.ADMIN || user.role === UserRole.TEACHER) { return next(); } try { const scout = await Scout.findByPk(req.params.scoutId); if (!scout) { return res.status(status.BAD_REQUEST).json(<MessageResponseDto>{ message: 'Scout not found' }); } if (scout.user_id === user.id && user.role === UserRole.COORDINATOR) { return next(); } else { return res.status(status.UNAUTHORIZED).json(<MessageResponseDto>{ message: 'Current user is not authorized to update this scout' }); } } catch (err) { return next(err); } })(req, res, next); }; <file_sep>/src/server/routes/users/deleteUsers.ts import { Request, Response } from 'express'; import status from 'http-status-codes'; import { User } from '@models/user.model'; import { ErrorResponseDto } from '@interfaces/shared.interface'; import { Scout } from '@models/scout.model'; export const deleteUser = async (req: Request, res: Response) => { try { const user: User = await User.findByPk(req.params.userId); await user.destroy(); return res.status(status.OK).end(); } catch (err) { return res.status(status.BAD_REQUEST).json(<ErrorResponseDto> { message: 'Failed to delete user', error: err }); } }; export const deleteScout = async (req: Request, res: Response) => { try { const user: User = await User.findByPk(req.params.userId); const deleted: Scout = await user.$remove('scouts', req.params.scoutId); await Scout.findByPk(req.params.scoutId).then((scout) => scout.destroy()); if (!deleted) { throw new Error('No scout to delete'); } return res.status(status.OK).end(); } catch (err) { return res.status(status.BAD_REQUEST).json(<ErrorResponseDto> { message: 'Failed to delete scout' , error: err }); } }; <file_sep>/src/client/src/urls.js const env = process.env.NODE_ENV || 'development'; const API_URL = env === 'development' ? 'http://localhost:3000/api/' : '/api/' export default { API_URL: API_URL, BADGES_URL: API_URL + 'badges/', CURRENT_EVENT_URL: API_URL + 'events/current', EVENTS_URL: API_URL + 'events/', FORGOT_URL: API_URL + 'forgot/', LOGIN_URL: API_URL + 'authenticate/', PROFILE_URL: API_URL + 'profile/', RESET_API_URL: API_URL + 'reset/', RESET_URL: env === 'development' ? 'http://localhost:8080/reset/' : 'http://mbu.online/reset/', SCOUTS_URL: API_URL + 'scouts/', SIGNUP_URL: API_URL + 'signup/', USERS_URL: API_URL + 'users/' }; <file_sep>/src/client/src/validators/lessThanSpec.js import { expect } from 'chai' import lessThan from './lessThan'; describe('The less than validator', () => { const parentVm = { number: 12 }; const emptyParentVm = {}; it('should determine if something is less than a number', () => { expect(lessThan('number')(10, parentVm)).to.be.true; expect(lessThan('number')(-10, parentVm)).to.be.true; }); it('should fail if the number is greater', () => { expect(lessThan('number')(13, parentVm)).to.be.false; }); it('should pass if the number is equal', () => { expect(lessThan('number')(12, parentVm)).to.be.true; }); it('should pass if there is nothing to compare to', () => { expect(lessThan('number')(13, emptyParentVm)).to.be.true; }); it('should pass if nothing is passed in', () => { expect(lessThan('number')('', parentVm)).to.be.true; }); }); <file_sep>/src/server/migrations/20170224001516-remove-unique-purchases.js 'use strict'; module.exports = { up: function (queryInterface) { return Promise.all([ queryInterface.sequelize.query('ALTER TABLE "Purchases" DROP CONSTRAINT "Purchases_pkey";'), queryInterface.removeIndex('Purchases', 'Purchases_pkey'), ]); }, down: function (queryInterface) { return queryInterface.addIndex('Purchases', ['purchasable_id', 'registration_id'], { indexName: 'Purchases_pkey', indicesType: 'BTREE' } ); } }; <file_sep>/src/server/routes/badges/postBadges.ts import { Request, Response } from 'express'; import status from 'http-status-codes'; import { Badge } from '@models/badge.model'; import { BadgeResponseDto } from '@interfaces/badge.interface'; import { ErrorResponseDto } from '@interfaces/shared.interface'; export const createBadge = async (req: Request, res: Response) => { try { const badge: Badge = await Badge.create(req.body); return res.status(status.CREATED).json(<BadgeResponseDto>{ message: 'Badge successfully created', badge: badge }); } catch (err) { return res.status(status.BAD_REQUEST).json(<ErrorResponseDto>{ message: 'Failed to create badge', error: err }); } }; <file_sep>/tests/server/assignmentSpec.ts import supertest from 'supertest'; import * as async from 'async'; import status from 'http-status-codes'; import { expect } from 'chai'; import app from '@app/app'; import TestUtils, { RoleTokenObjects } from './testUtils'; import { Badge } from '@models/badge.model'; import { Event } from '@models/event.model'; import { Scout } from '@models/scout.model'; import { Offering } from '@models/offering.model'; import { OfferingInterface } from '@interfaces/offering.interface'; import { Registration } from '@models/registration.model'; import { Assignment } from '@models/assignment.model'; import testScouts from './testScouts'; import { CreateAssignmentRequestDto, CreateAssignmentResponseDto, ScoutAssignmentResponseDto, UpdateAssignmentResponseDto } from '@interfaces/assignment.interface'; import { SuperTestResponse } from '@test/helpers/supertest.interface'; const request = supertest(app); describe('assignments', () => { let badges: Badge[]; let events: Event[]; let generatedUsers: RoleTokenObjects; let generatedScouts: Scout[]; let generatedOfferings: Offering[]; let scoutId: string; let registrationIds: string[]; const badId = TestUtils.badId; const defaultRequirements: string[] = ['1', '2', '3a']; beforeAll(async () => { await TestUtils.dropDb(); }); beforeAll(async () => { generatedUsers = await TestUtils.generateTokens(); badges = await TestUtils.createBadges(); events = await TestUtils.createEvents(); const defaultPostData: OfferingInterface = { price: 10, periods: [1, 2, 3], duration: 1, requirements: defaultRequirements }; generatedOfferings = await TestUtils.createOfferingsForEvent(events[0], badges, defaultPostData); }); beforeEach(async () => { await TestUtils.dropTable([Registration, Assignment]); generatedScouts = await TestUtils.createScoutsForUser(generatedUsers.coordinator, testScouts(5)); }); beforeEach((done) => { scoutId = generatedScouts[0].id; registrationIds = []; async.series([ (cb) => { request.post('/api/scouts/' + scoutId + '/registrations') .set('Authorization', generatedUsers.coordinator.token) .send({ event_id: events[0].id }) .expect(status.CREATED) .end((err, res) => { if (err) { return done(err); } registrationIds.push(res.body.registration.id); return cb(); }); }, (cb) => { request.post('/api/scouts/' + scoutId + '/registrations') .set('Authorization', generatedUsers.coordinator.token) .send({ event_id: events[1].id }) .expect(status.CREATED) .end((err, res) => { if (err) { return done(err); } registrationIds.push(res.body.registration.id); return cb(); }); } ], done); }); afterAll(async () => { await TestUtils.dropDb(); await TestUtils.closeDb(); }); describe('when assignments do not exist', () => { test('should be able to assign a scout to an offering', (done) => { const postData: CreateAssignmentRequestDto = { periods: [1], offering: generatedOfferings[1].id }; request.post('/api/scouts/' + scoutId + '/registrations/' + registrationIds[0] + '/assignments') .set('Authorization', generatedUsers.teacher.token) .send(postData) .expect(status.CREATED) .end((err, res: SuperTestResponse<CreateAssignmentResponseDto>) => { if (err) { return done(err); } const registration = res.body.registration; expect(registration.assignments).to.have.length(1); const assignment = registration.assignments[0]; expect(assignment.offering_id).to.equal(postData.offering); expect(assignment.details.periods).to.deep.equal(postData.periods); return done(); }); }); test('should create a blank object of completions', (done) => { const postData: CreateAssignmentRequestDto = { periods: [1], offering: generatedOfferings[1].id }; request.post('/api/scouts/' + scoutId + '/registrations/' + registrationIds[0] + '/assignments') .set('Authorization', generatedUsers.teacher.token) .send(postData) .expect(status.CREATED) .end((err, res: SuperTestResponse<CreateAssignmentResponseDto>) => { if (err) { return done(err); } const registration = res.body.registration; expect(registration.assignments).to.have.length(1); const assignment = registration.assignments[0]; expect(assignment.offering_id).to.equal(postData.offering); expect(assignment.details.completions).to.deep.equal([]); expect(assignment.details.periods).to.deep.equal(postData.periods); return done(); }); }); test('should be able to batch assign to offerings', (done) => { const postData: CreateAssignmentRequestDto[] = [{ periods: [1], offering: generatedOfferings[0].id }, { periods: [2], offering: generatedOfferings[1].id }, { periods: [3], offering: generatedOfferings[2].id }]; request.post('/api/scouts/' + scoutId + '/registrations/' + registrationIds[0] + '/assignments') .set('Authorization', generatedUsers.admin.token) .send(postData) .expect(status.CREATED) .end((err, res: SuperTestResponse<CreateAssignmentResponseDto>) => { if (err) { return done(err); } const registration = res.body.registration; expect(registration.assignments).to.have.lengthOf(3); registration.assignments.forEach((assignment: any, index: number) => { expect(assignment.details.periods).to.deep.equal(postData[index].periods); expect(assignment.offering_id).to.equal(postData[index].offering); expect(assignment.price).to.exist; expect(assignment.badge.name).to.exist; }); return done(); }); }); test('should allow an empty period', (done) => { const postData: CreateAssignmentRequestDto[] = [{ periods: [2], offering: generatedOfferings[1].id }, { periods: [3], offering: generatedOfferings[2].id }]; request.post('/api/scouts/' + scoutId + '/registrations/' + registrationIds[0] + '/assignments') .set('Authorization', generatedUsers.admin.token) .send(postData) .expect(status.CREATED) .end((err, res: SuperTestResponse<CreateAssignmentResponseDto>) => { if (err) { return done(err); } const registration = res.body.registration; expect(registration.assignments).to.have.lengthOf(2); registration.assignments.forEach((assignment: any, index: number) => { expect(assignment.details.periods).to.deep.equal(postData[index].periods); expect(assignment.offering_id).to.equal(postData[index].offering); expect(assignment.price).to.exist; expect(assignment.badge.name).to.exist; }); return done(); }); }); test('should not allow coordinators to access', (done) => { const postData: CreateAssignmentRequestDto = { periods: [1], offering: generatedOfferings[1].id }; request.post('/api/scouts/' + scoutId + '/registrations/' + registrationIds[0] + '/assignments') .set('Authorization', generatedUsers.coordinator.token) .send(postData) .expect(status.UNAUTHORIZED, done); }); test('should not create for a nonexistant offering', (done) => { const postData: any = { offering: badId, periods: [1] }; request.post('/api/scouts/' + generatedScouts[0].id + '/registrations/' + registrationIds[0] + '/assignments') .set('Authorization', generatedUsers.teacher.token) .send(postData) .expect(status.BAD_REQUEST, done); }); test('should not create for nonexistant registrations', (done) => { const postData: CreateAssignmentRequestDto = { offering: generatedOfferings[0].id, periods: [1] }; request.post('/api/scouts/' + generatedScouts[0].id + '/registrations/' + badId + '/assignments') .set('Authorization', generatedUsers.teacher.token) .send(postData) .expect(status.BAD_REQUEST, done); }); }); describe('when assignments exist', () => { beforeEach((done) => { async.series([ (cb) => { request.post('/api/scouts/' + generatedScouts[0].id + '/registrations/' + registrationIds[0] + '/assignments') .set('Authorization', generatedUsers.teacher.token) .send(<CreateAssignmentRequestDto>{ offering: generatedOfferings[0].id, periods: [1] }) .expect(status.CREATED, cb); }, (cb) => { request.post('/api/scouts/' + generatedScouts[0].id + '/registrations/' + registrationIds[0] + '/assignments') .set('Authorization', generatedUsers.teacher.token) .send(<CreateAssignmentRequestDto>{ offering: generatedOfferings[1].id, periods: [2, 3] }) .expect(status.CREATED, cb); }, (cb) => { request.post('/api/scouts/' + generatedScouts[0].id + '/registrations/' + registrationIds[1] + '/assignments') .set('Authorization', generatedUsers.teacher.token) .send(<CreateAssignmentRequestDto>{ offering: generatedOfferings[0].id, periods: [3] }) .expect(status.CREATED, cb); } ], done); }); describe('getting assignments', () => { test('should get all assignments for a registration', (done) => { request.get('/api/scouts/' + scoutId + '/registrations/' + registrationIds[0] + '/assignments') .set('Authorization', generatedUsers.teacher.token) .expect(status.OK) .end((err, res: SuperTestResponse<ScoutAssignmentResponseDto>) => { if (err) { return done(err); } const assignments = res.body; expect(assignments).to.have.length(2); expect(assignments[0].offering_id).to.equal(generatedOfferings[0].id); expect(assignments[0].details.periods).to.deep.equal([1]); expect(assignments[0].details.completions).to.exist; expect(assignments[1].offering_id).to.equal(generatedOfferings[1].id); expect(assignments[1].details.periods).to.deep.equal([2, 3]); expect(assignments[1].details.completions).to.exist; return done(); }); }); test('should not get with an incorrect scout', (done) => { request.get('/api/scouts/' + badId + '/registrations/' + registrationIds[0] + '/assignments') .set('Authorization', generatedUsers.teacher.token) .expect(status.BAD_REQUEST, done); }); test('should not get with an incorrect registration', (done) => { request.get('/api/scouts/' + generatedScouts[0].id + '/registrations/' + badId + '/assignments') .set('Authorization', generatedUsers.teacher.token) .expect(status.BAD_REQUEST, done); }); }); describe('updating assignments', () => { test('should update a assignment periods', (done) => { async.series([ (cb) => { request.get('/api/scouts/' + scoutId + '/registrations/' + registrationIds[0] + '/assignments') .set('Authorization', generatedUsers.teacher.token) .expect(status.OK) .end((err, res: SuperTestResponse<ScoutAssignmentResponseDto>) => { if (err) { return done(err); } expect(res.body[0].offering_id).to.exist; expect(res.body[0].details.periods).to.deep.equal([1]); return cb(); }); }, (cb) => { request.put('/api/scouts/' + scoutId + '/registrations/' + registrationIds[0] + '/assignments/' + generatedOfferings[0].id) .set('Authorization', generatedUsers.teacher.token) .send({ periods: [2] }) .expect(status.OK) .end((err, res: SuperTestResponse<UpdateAssignmentResponseDto>) => { if (err) { return done(err); } expect(res.body.assignment.periods).to.deep.equal([2]); return cb(); }); }, (cb) => { request.get('/api/scouts/' + scoutId + '/registrations/' + registrationIds[0] + '/assignments') .set('Authorization', generatedUsers.teacher.token) .expect(status.OK) .end((err, res: SuperTestResponse<ScoutAssignmentResponseDto>) => { expect(res.body[0].offering_id).to.exist; expect(res.body[0].details.periods).to.deep.equal([2]); return cb(); }); }, ], done); }); test('should overwrite assignments with a batch', (done) => { const postData: CreateAssignmentRequestDto[] = [{ periods: [1], offering: generatedOfferings[0].id }, { periods: [2], offering: generatedOfferings[1].id }, { periods: [3], offering: generatedOfferings[2].id }]; request.post('/api/scouts/' + scoutId + '/registrations/' + registrationIds[0] + '/assignments') .set('Authorization', generatedUsers.admin.token) .send(postData) .expect(status.CREATED) .end((err, res: SuperTestResponse<CreateAssignmentResponseDto>) => { if (err) { return done(err); } const registration = res.body.registration; expect(registration.assignments).to.have.lengthOf(3); registration.assignments.forEach((assignment: any, index: number) => { expect(assignment.details.periods).to.deep.equal(postData[index].periods); expect(assignment.offering_id).to.equal(postData[index].offering); expect(assignment.price).to.exist; expect(assignment.badge.name).to.exist; }); return done(); }); }); test('should allow overwriting with empty values for a period', (done) => { const postData: CreateAssignmentRequestDto[] = [{ periods: [2], offering: generatedOfferings[1].id }, { periods: [3], offering: generatedOfferings[2].id }]; request.post('/api/scouts/' + scoutId + '/registrations/' + registrationIds[0] + '/assignments') .set('Authorization', generatedUsers.admin.token) .send(postData) .expect(status.CREATED) .end((err, res: SuperTestResponse<CreateAssignmentResponseDto>) => { if (err) { return done(err); } const registration = res.body.registration; expect(registration.assignments).to.have.lengthOf(2); registration.assignments.forEach((assignment: any, index: number) => { expect(assignment.details.periods).to.deep.equal(postData[index].periods); expect(assignment.offering_id).to.equal(postData[index].offering); expect(assignment.price).to.exist; expect(assignment.badge.name).to.exist; }); return done(); }); }); test('should not update an invalid assignment', (done) => { request.put('/api/scouts/' + scoutId + '/registrations/' + registrationIds[0] + '/assignments/' + badId) .set('Authorization', generatedUsers.teacher.token) .expect(status.BAD_REQUEST, done); }); test('should not update an invalid registration', (done) => { request.put('/api/scouts/' + scoutId + '/registrations/' + badId + '/assignments/' + generatedOfferings[0].id) .set('Authorization', generatedUsers.teacher.token) .expect(status.BAD_REQUEST, done); }); test('should not update for an invalid scout', (done) => { request.put('/api/scouts/' + badId + '/registrations/' + registrationIds[0] + '/assignments/' + generatedOfferings[0].id) .set('Authorization', generatedUsers.teacher.token) .expect(status.BAD_REQUEST, done); }); }); describe('deleting assignments', () => { test('should delete an existing assignment', (done) => { async.series([ (cb) => { request.get('/api/scouts/' + scoutId + '/registrations/' + registrationIds[0] + '/assignments') .set('Authorization', generatedUsers.teacher.token) .expect(status.OK) .end((err, res: SuperTestResponse<ScoutAssignmentResponseDto>) => { if (err) { return done(err); } expect(res.body).to.have.length(2); return cb(); }); }, (cb) => { request.del('/api/scouts/' + scoutId + '/registrations/' + registrationIds[0] + '/assignments/' + generatedOfferings[0].id) .set('Authorization', generatedUsers.teacher.token) .expect(status.OK, cb); }, (cb) => { request.get('/api/scouts/' + scoutId + '/registrations/' + registrationIds[0] + '/assignments') .set('Authorization', generatedUsers.teacher.token) .expect(status.OK) .end((err, res: SuperTestResponse<ScoutAssignmentResponseDto>) => { expect(res.body).to.have.length(1); return cb(); }); }, ], done); }); test('should not delete an invalid assignment', (done) => { request.del('/api/scouts/' + scoutId + '/registrations/' + registrationIds[0] + '/assignments/' + badId) .set('Authorization', generatedUsers.teacher.token) .expect(status.BAD_REQUEST, done); }); test('should not delete an invalid registration', (done) => { request.del('/api/scouts/' + scoutId + '/registrations/' + badId + '/assignments/' + generatedOfferings[0].id) .set('Authorization', generatedUsers.teacher.token) .expect(status.BAD_REQUEST, done); }); test('should not delete for an invalid scout', (done) => { request.del('/api/scouts/' + badId + '/registrations/' + registrationIds[0] + '/assignments/' + generatedOfferings[0].id) .set('Authorization', generatedUsers.teacher.token) .expect(status.BAD_REQUEST, done); }); }); }); }); <file_sep>/src/server/routes/events.ts import { Router } from 'express'; import { isAuthorized } from '@middleware/isAuthorized'; import { UserRole } from '@interfaces/user.interface'; import { createEvent, setCurrentEvent, createOffering, createPurchasable } from '@routes/events/postEvents'; import { getCurrentEvent, getEvent, getPurchasables, getClassSize, getRegistrations, getAssignees, getPotentialIncome, getActualIncome, getStats, getBuyers } from '@routes/events/getEvents'; import { deleteEvent, deleteOffering, deletePurchasable } from '@routes/events/deleteEvents'; import { updateEvent, updateOffering, updatePurchasable } from '@routes/events/updateEvents'; export const eventRoutes = Router(); eventRoutes.post('/', isAuthorized([UserRole.ADMIN]), createEvent); eventRoutes.get('/', getEvent); eventRoutes.delete('/:id', isAuthorized([UserRole.ADMIN]), deleteEvent); eventRoutes.put('/:id', isAuthorized([UserRole.ADMIN]), updateEvent); eventRoutes.post('/current', isAuthorized([UserRole.ADMIN]), setCurrentEvent); eventRoutes.get('/current', getCurrentEvent); eventRoutes.post('/:id/badges', isAuthorized([UserRole.ADMIN]), createOffering); eventRoutes.put('/:eventId/badges/:badgeId', isAuthorized([UserRole.ADMIN]), updateOffering); eventRoutes.delete('/:eventId/badges/:badgeId', isAuthorized([UserRole.ADMIN]), deleteOffering); eventRoutes.get('/:eventId/badges/:badgeId/limits', isAuthorized([UserRole.ADMIN, UserRole.TEACHER]), getClassSize); // // Routes for Purchasable CRUD eventRoutes.post('/:id/purchasables', isAuthorized([UserRole.ADMIN]), createPurchasable); eventRoutes.get('/:id/purchasables', getPurchasables); eventRoutes.get('/:id/registrations', isAuthorized([UserRole.TEACHER]), getRegistrations); eventRoutes.put('/:eventId/purchasables/:purchasableId', isAuthorized([UserRole.ADMIN]), updatePurchasable); eventRoutes.delete('/:eventId/purchasables/:purchasableId', isAuthorized([UserRole.ADMIN]), deletePurchasable); eventRoutes.get('/:eventId/purchasables/:purchasableId/buyers', isAuthorized([UserRole.ADMIN, UserRole.TEACHER]), getBuyers); // // Event income eventRoutes.get('/:id/potentialIncome', isAuthorized([UserRole.ADMIN]), getPotentialIncome); eventRoutes.get('/:id/income', isAuthorized([UserRole.ADMIN]), getActualIncome); eventRoutes.get('/:id/stats', isAuthorized([UserRole.ADMIN, UserRole.COORDINATOR, UserRole.TEACHER]), getStats); eventRoutes.get('/:id/offerings/assignees', isAuthorized([UserRole.TEACHER]), getAssignees); <file_sep>/tests/server/badgesSpec.ts import supertest from 'supertest'; import * as async from 'async'; import status from 'http-status-codes'; import { expect } from 'chai'; import faker from 'faker'; import app from '@app/app'; import TestUtils from './testUtils'; import { Badge } from '@models/badge.model'; import { UserRole } from '@interfaces/user.interface'; import { CreateUpdateBadgeDto, BadgeResponseDto, BadgesResponseDto } from '@interfaces/badge.interface'; import { SuperTestResponse } from '@test/helpers/supertest.interface'; const request = supertest(app); describe('merit badges', () => { let token: string; beforeAll(async () => { await TestUtils.dropDb(); }); beforeAll(async () => { token = (await TestUtils.generateToken(UserRole.ADMIN)).token; }); beforeEach(async () => { await TestUtils.dropTable([Badge]); }); afterAll(async () => { await TestUtils.dropDb(); await TestUtils.closeDb(); }); describe('creating merit badges', () => { const testBadge: CreateUpdateBadgeDto = { name: 'Test', description: 'A very good badge', notes: 'Eagle' }; test('should create badges with names', (done) => { const postData: CreateUpdateBadgeDto = { name: 'Test' }; request.post('/api/badges') .set('Authorization', token) .send(postData) .expect(status.CREATED, done); }); test('should require authentication', (done) => { const postData = testBadge; request.post('/api/badges') .send(postData) .expect(status.UNAUTHORIZED, done); }); test('should require name', (done) => { const postData: CreateUpdateBadgeDto = { description: 'No name' }; request.post('/api/badges') .set('Authorization', token) .send(postData) .expect(status.BAD_REQUEST, done); }); test('should not allow blank names', (done) => { const postData: CreateUpdateBadgeDto = { name: '' }; request.post('/api/badges') .set('Authorization', token) .send(postData) .expect(status.BAD_REQUEST, done); }); test('should allow long details', (done) => { const postData: CreateUpdateBadgeDto = { name: 'Swimming', description: 'Swimming is a leisure activity' }; request.post('/api/badges') .set('Authorization', token) .send(postData) .expect(status.CREATED, done); }); test('should not allow duplicate names', (done) => { async.series([ (cb) => { request.post('/api/badges') .set('Authorization', token) .send(testBadge) .expect(status.CREATED, cb); }, (cb) => { request.post('/api/badges') .set('Authorization', token) .send(testBadge) .expect(status.BAD_REQUEST, cb); } ], done); }); test('should ignore extra fields', (done) => { const postData: any = { name: 'Test', birthday: 'Nonsense' }; request.post('/api/badges') .set('Authorization', token) .send(postData) .expect(status.CREATED) .end((err, res: SuperTestResponse<BadgeResponseDto>) => { if (err) { return done(err); } expect(res.body.badge.name).to.equal(postData.name); expect((res.body.badge as any).birthday).not.to.exist; done(); }); }); }); describe('getting merit badges', () => { let id: number; const test1: CreateUpdateBadgeDto = { name: 'Test', description: 'A test', notes: 'Notes' }; const test2: CreateUpdateBadgeDto = { name: '<NAME>', description: 'A second test' }; beforeEach((done) => { request.post('/api/badges') .set('Authorization', token) .send(test1) .expect(status.CREATED) .end((err, res: SuperTestResponse<BadgeResponseDto>) => { if (err) { return done(err); } id = res.body.badge.id; done(); }); }); test('should be able to get a badge by id', (done) => { request.get('/api/badges?id=' + id) .expect(status.OK) .end((err, res: SuperTestResponse<BadgesResponseDto>) => { if (err) { return done(err); } const badge = res.body[0]; expect(badge.name).to.equal(test1.name); expect(badge.description).to.equal(test1.description); expect(badge.notes).to.equal(test1.notes); done(); }); }); test('should be able to get a badge by name', (done) => { request.get('/api/badges?name=' + test1.name) .expect(status.OK) .end((err, res: SuperTestResponse<BadgesResponseDto>) => { if (err) { return done(err); } const badge = res.body[0]; expect(badge.name).to.equal(test1.name); expect(badge.description).to.equal(test1.description); expect(badge.notes).to.equal(test1.notes); done(); }); }); test('should respond with all badges if no query is supplied', (done) => { async.series([ (cb) => { request.post('/api/badges') .set('Authorization', token) .send(test2) .expect(status.CREATED) .end((err) => { if (err) { return done(err); } cb(); }); }, (cb) => { request.get('/api/badges') .expect(status.OK) .end((err, res: SuperTestResponse<BadgesResponseDto>) => { if (err) { return done(err); } const badges = res.body; expect(badges.length).to.equal(2); cb(); }); } ], done); }); test('should fail gracefully if incorrect arguments are supplied', (done) => { request.get('/api/badges?wrong=hello') .expect(status.OK, done); }); test('should not fail if a badge does not exist', (done) => { request.get('/api/badges?name=dne') .expect(status.OK, done); }); }); describe('removing a merit badge', () => { let id: number; test('should remove a badge with a given id', (done) => { const badge: CreateUpdateBadgeDto = { name: 'Test' }; async.series([ (cb) => { request.post('/api/badges') .set('Authorization', token) .send(badge) .expect(status.CREATED) .end((err, res: SuperTestResponse<BadgeResponseDto>) => { if (err) { return done(err); } id = res.body.badge.id; cb(); }); }, (cb) => { request.del('/api/badges/' + id) .set('Authorization', token) .expect(status.OK, cb); }, (cb) => { request.get('/api/badges?id=' + id) .expect(status.OK) .end((err, res: SuperTestResponse<BadgesResponseDto>) => { if (err) { return done(err); } const badges = res.body; expect(badges.length).to.equal(0); cb(); }); } ], done); }); test('should fail gracefully if a badge is not found with a valid id form', (done) => { request.del('/api/badges/123123') .set('Authorization', token) .expect(status.BAD_REQUEST, done); }); test('should fail gracefully if a valid id is not supplied', (done) => { request.del('/api/badges/invalidid') .set('Authorization', token) .expect(status.BAD_REQUEST, done); }); test('should fail gracefully if delete is sent to the wrong endpoint', (done) => { request.del('/api/badges') .set('Authorization', token) .expect(status.NOT_FOUND, done); }); }); describe('editing a merit badge', () => { let id: number; const badge: CreateUpdateBadgeDto = { name: 'Test', description: 'What', notes: 'Note' }; test('should update a badge with all fields', (done) => { const badgeUpdate: CreateUpdateBadgeDto = { name: '<NAME>', description: 'New', notes: 'Updated' }; async.series([ (cb) => { request.post('/api/badges') .set('Authorization', token) .send(badge) .expect(status.CREATED) .end((err, res: SuperTestResponse<BadgeResponseDto>) => { if (err) { return done(err); } id = res.body.badge.id; cb(); }); }, (cb) => { request.put('/api/badges/' + id) .set('Authorization', token) .send(badgeUpdate) .expect(status.OK) .end((err, res: SuperTestResponse<BadgeResponseDto>) => { if (err) { return done(err); } expect(res.body.badge.name).to.equal(badgeUpdate.name); expect(res.body.badge.description).to.equal(badgeUpdate.description); expect(res.body.badge.notes).to.equal(badgeUpdate.notes); expect(res.body.badge.id).to.equal(id); cb(); }); } ], done); }); test('should update a badge with partial fields', (done) => { const badgeUpdate: CreateUpdateBadgeDto = { name: '<NAME>' }; async.series([ (cb) => { request.post('/api/badges') .set('Authorization', token) .send(badge) .expect(status.CREATED) .end((err, res: SuperTestResponse<BadgeResponseDto>) => { if (err) { return done(err); } id = res.body.badge.id; cb(); }); }, (cb) => { request.put('/api/badges/' + id) .set('Authorization', token) .send(badgeUpdate) .expect(status.OK) .end((err, res: SuperTestResponse<BadgeResponseDto>) => { if (err) { return done(err); } expect(res.body.badge.name).to.equal(badgeUpdate.name); expect(res.body.badge.id).to.equal(id); expect(res.body.badge.description).to.exist; expect(res.body.badge.notes).to.exist; cb(); }); } ], done); }); test('should fail gracefully if required fields are not supplied', (done) => { const badgeUpdate: CreateUpdateBadgeDto = { name: null, description: 'New', notes: 'Updated' }; async.series([ (cb) => { request.post('/api/badges') .set('Authorization', token) .send(badge) .expect(status.CREATED) .end((err, res: SuperTestResponse<BadgeResponseDto>) => { if (err) { return done(err); } id = res.body.badge.id; cb(); }); }, (cb) => { request.put('/api/badges/' + id) .set('Authorization', token) .send(badgeUpdate) .expect(status.BAD_REQUEST, cb); } ], done); }); test('should not allow badges to be modified to be duplicates', (done) => { let id2: number; const badge2 = Object.assign({}, badge); badge2.name = 'Different'; async.series([ (cb) => { request.post('/api/badges') .set('Authorization', token) .send(badge) .expect(status.CREATED) .end((err, res: SuperTestResponse<BadgeResponseDto>) => { if (err) { return done(err); } id = res.body.badge.id; cb(); }); }, (cb) => { request.post('/api/badges') .set('Authorization', token) .send(badge2) .expect(status.CREATED) .end((err, res: SuperTestResponse<BadgeResponseDto>) => { if (err) { return done(err); } id2 = res.body.badge.id; cb(); }); }, (cb) => { request.put('/api/badges/' + id2) .set('Authorization', token) .send(badge) .expect(status.BAD_REQUEST, cb); } ], done); }); test('should not edit the badge if no fields are supplied', (done) => { async.series([ (cb) => { request.post('/api/badges') .set('Authorization', token) .send(badge) .expect(status.CREATED) .end((err, res: SuperTestResponse<BadgeResponseDto>) => { if (err) { return done(err); } id = res.body.badge.id; cb(); }); }, (cb) => { request.put('/api/badges/' + id) .set('Authorization', token) .send(<CreateUpdateBadgeDto>{}) .expect(status.OK, (err, res) => { if (err) { return done(err); } expect(res.body.badge.id).to.equal(id); expect(res.body.badge.name).to.equal(badge.name); expect(res.body.badge.description).to.equal(badge.description); expect(res.body.badge.notes).to.equal(badge.notes); cb(); }); } ], done); }); test('should fail gracefully if the badge is not found', (done) => { async.series([ (cb) => { request.post('/api/badges') .set('Authorization', token) .send(badge) .expect(status.CREATED) .end((err, res: SuperTestResponse<BadgeResponseDto>) => { if (err) { return done(err); } id = res.body.badge.id; cb(); }); }, (cb) => { request.put('/api/badges/123456789012345678901234') .set('Authorization', token) .send(<CreateUpdateBadgeDto>{ name: 'DNE' }) .expect(status.BAD_REQUEST, cb); } ], done); }); test('should not edit the badge if an empty request is sent', (done) => { async.series([ (cb) => { request.post('/api/badges') .set('Authorization', token) .send(badge) .expect(status.CREATED) .end((err, res: SuperTestResponse<BadgeResponseDto>) => { if (err) { return done(err); } id = res.body.badge.id; cb(); }); }, (cb) => { request.put('/api/badges/' + id) .set('Authorization', token) .expect(status.OK, (err, res: SuperTestResponse<BadgeResponseDto>) => { if (err) { return done(err); } expect(res.body.badge.id).to.equal(id); expect(res.body.badge.name).to.equal(badge.name); expect(res.body.badge.description).to.equal(badge.description); expect(res.body.badge.notes).to.equal(badge.notes); cb(); }); } ], done); }); test('should fail gracefully if no id is sent', (done) => { request.put('/api/badges/') .set('Authorization', token) .expect(status.NOT_FOUND, done); }); test('should allow long details', (done) => { async.series([ (cb) => { request.post('/api/badges') .set('Authorization', token) .send(badge) .expect(status.CREATED) .end((err, res: SuperTestResponse<BadgeResponseDto>) => { if (err) { return done(err); } id = res.body.badge.id; cb(); }); }, (cb) => { request.put('/api/badges/' + id) .set('Authorization', token) .send(<CreateUpdateBadgeDto>{ description: faker.lorem.paragraph(3) }) .expect(status.OK, cb); } ], done); }); }); }); <file_sep>/src/client/src/store/modules/authentication.js import axios from 'axios'; import * as types from '../mutation-types'; import URLS from '../../urls'; const state = { profile: {}, isAuthenticated: false }; const getters = { profile(state) { return state.profile; }, role(state) { return state.profile.role; }, isAuthenticated(state) { return state.isAuthenticated; }, isApproved(state) { return state.profile.approved; }, isTeacher(state) { return state.profile.role === 'teacher'; }, isCoordinator(state) { return state.profile.role === 'coordinator'; }, isAdmin(state) { return state.profile.role === 'admin'; }, isTeacherOrAdmin(state) { return state.profile.role === 'teacher' || state.profile.role === 'admin'; }, isCoordinatorOrAdmin(state) { return state.profile.role === 'coordinator' || state.profile.role === 'admin'; } }; const mutations = { [types.LOGIN](state, response) { state.profile = response.profile; state.isAuthenticated = true; if (response.token) { localStorage.setItem('token', response.token); axios.defaults.headers.common['Authorization'] = response.token; } }, [types.LOGOUT](state) { state.profile = {}; state.isAuthenticated = false; localStorage.removeItem('token'); axios.defaults.headers.common['Authorization'] = ''; }, [types.PROFILE](state, profile) { state.profile = profile; state.isAuthenticated = true; axios.defaults.headers.common['Authorization'] = localStorage.getItem('token'); } }; const actions = { checkEmail(context, email) { return new Promise((resolve, reject) => { axios.get(URLS.USERS_URL + 'exists/' + email) .then((response) => { resolve(response.data.exists); }) .catch(() => { reject(); }); }); }, createAccount(context, credentials) { return new Promise((resolve, reject) => { axios.post(URLS.SIGNUP_URL, credentials) .then((response) => { resolve(response.data.profile.id); }) .catch((err) => { reject(err.response.data.message); }); }); }, deleteAccount({ commit }, id) { return new Promise((resolve, reject) => { axios.delete(URLS.USERS_URL + id) .then(() => { commit(types.LOGOUT); resolve(); }) .catch(() => { reject(); }) }); }, getProfile({ commit }) { return new Promise((resolve, reject) => { let token = localStorage.getItem('token'); axios.get(URLS.PROFILE_URL, { headers: { 'Authorization': token } }) .then((response) => { commit(types.PROFILE, response.data.profile); resolve(); }) .catch(() => { localStorage.removeItem('token'); reject(); }); }); }, login({ commit }, credentials) { return new Promise((resolve, reject) => { axios.post(URLS.LOGIN_URL, credentials) .then((response) => { commit(types.LOGIN, response.data); resolve(); }) .catch((err) => { reject(err.response.data.message); }); }); }, signup({ commit }, credentials) { return new Promise((resolve, reject) => { axios.post(URLS.SIGNUP_URL, credentials) .then((response) => { commit(types.LOGIN, response.data); resolve(); }) .catch((err) => { reject(err.response.data.message); }); }); }, sendResetEmail(context, email) { let data = { email: email, url: URLS.RESET_URL }; return new Promise((resolve, reject) => { axios.post(URLS.FORGOT_URL, data) .then(() => { resolve(); }) .catch(() => { reject(); }); }); }, resetPassword(context, data) { return new Promise((resolve, reject) => { axios.post(URLS.RESET_API_URL, data) .then(() => { resolve() }) .catch((err) => { reject(err.response.data.message); }); }); }, updateProfile({ commit, state }, data) { return new Promise((resolve, reject) => { axios.put(URLS.USERS_URL + data.id, data) .then((response) => { // Only login if user is updating their own profile if (state.profile.id == data.id) { commit(types.LOGIN, response.data); } resolve(); }) .catch((err) => { reject(err.response.data.message); }) }); }, logout({ commit }) { commit(types.LOGOUT); } }; export default { state, getters, actions, mutations }; <file_sep>/tests/server/testPurchasables.ts export default [ { item: 'T-Shirt', description: 'It is a t-shirt', price: '10.50' }, { item: 'Youth Lunch', description: 'Lunch for 12 and under', price: '9.75' }, { item: 'Adult Lunch', description: 'Lunch for older than 12', price: '12.50' }, { item: 'Badge', description: 'Commemerative badge', price: '3.00' } ]; <file_sep>/src/server/models/offering.model.ts import { Table, Model, PrimaryKey, Column, AutoIncrement, Min, Max, DataType, Default, ForeignKey, Validator, BeforeBulkCreate, BeforeValidate, BelongsTo, BelongsToMany } from 'sequelize-typescript'; import { without } from 'lodash'; import { Event } from '@models/event.model'; import { Badge } from '@models/badge.model'; import { Registration } from '@models/registration.model'; import { Assignment } from '@models/assignment.model'; import { durationValidator } from '@models/validators'; import { OfferingInterface } from '@interfaces/offering.interface'; import { Preference } from '@models/preference.model'; import { ClassSizeDto } from '@interfaces/event.interface'; @Table({ underscored: true, tableName: 'Offerings' }) export class Offering extends Model<Offering> implements OfferingInterface { @BeforeBulkCreate public static removeAllNullPeriods(offerings: Offering[]): void { offerings.forEach((offering: Offering) => { Offering.removeNullPeriods(offering); }); } @BeforeValidate public static removeNullPeriods(offering: Offering): void { offering.periods = without(offering.periods, null); } @PrimaryKey @AutoIncrement @Column public id!: number; @Min(1) @Max(3) @Column({ allowNull: false }) public duration!: number; @Column({ type: DataType.ARRAY(DataType.INTEGER), allowNull: false }) public periods!: number[]; @Default(0.0) @Column({ allowNull: false, type: DataType.DECIMAL(5, 2) }) public price!: number; @Default([]) @Column({ type: DataType.ARRAY(DataType.STRING), allowNull: false }) public requirements!: string[]; @ForeignKey(() => Event) @Column({ unique: 'event_offering', allowNull: false }) public event_id: number; @ForeignKey(() => Badge) @Column({ unique: 'event_offering', allowNull: false }) public badge_id: number; @Min(0) @Column({ defaultValue: 20 }) public size_limit: number; @BelongsTo(() => Badge) public badge: Badge; @BelongsToMany(() => Registration, () => Preference, 'offering_id', 'registration_id') public requesters: Registration[]; @BelongsToMany(() => Registration, () => Assignment, 'offering_id', 'registration_id') public assignees: Registration[]; @Validator public durationPeriodRelation(): void { if (!durationValidator(this.periods, this.duration)) { throw new Error('Duration validation failed'); } } public async getClassSizes(): Promise<ClassSizeDto> { const assignees: Registration[] = await this.$get('assignees') as Registration[]; const assignments: Assignment[] = await Assignment.findAll({ where: { offering_id: this.id }}); return assignments.reduce((result: ClassSizeDto, assignment: Assignment) => { assignment.periods.forEach((period: number) => { (<any>result)[period] += 1; }); return result; }, <ClassSizeDto>{ size_limit: this.size_limit, total: assignees.length, 1: 0, 2: 0, 3: 0 }); } } <file_sep>/tests/server/purchaseLimitSpec.ts import supertest from 'supertest'; import { expect } from 'chai'; import status from 'http-status-codes'; import app from '@app/app'; import TestUtils, { RoleTokenObjects } from '@test/server/testUtils'; import { Event } from '@models/event.model'; import { Scout } from '@models/scout.model'; import testScouts from '@test/server/testScouts'; import { Purchasable } from '@models/purchasable.model'; import { Purchase } from '@models/purchase.model'; import { Registration } from '@models/registration.model'; import { RegistrationRequestDto, CreateRegistrationResponseDto } from '@interfaces/registration.interface'; import { SuperTestResponse } from '@test/helpers/supertest.interface'; import { CreatePurchasableDto, CreatePurchasablesResponseDto, PurchasablesResponseDto, PurchasableDto } from '@interfaces/purchasable.interface'; import { EventsResponseDto } from '@interfaces/event.interface'; import { CreatePurchaseRequestDto } from '@interfaces/purchase.interface'; const request = supertest(app); describe('purchasable purchaser limits', () => { let generatedUsers: RoleTokenObjects; let generatedEvents: Event[]; let generatedScouts: Scout[]; let registrationIds: Map<number, number>; beforeAll(async () => { await TestUtils.dropDb(); }); beforeAll(async () => { generatedUsers = await TestUtils.generateTokens(); }); beforeEach(async () => { await TestUtils.dropTable([Scout, Event, Purchasable, Purchase, Registration]); }); beforeEach(async () => { generatedEvents = await TestUtils.createEvents(); generatedScouts = await TestUtils.createScoutsForUser(generatedUsers.coordinator, testScouts(5)); }); beforeEach(async () => { registrationIds = new Map(); await Promise.all(generatedScouts.map(scout => { return request.post(`/api/scouts/${scout.id}/registrations`) .set('Authorization', generatedUsers.coordinator.token) .send(<RegistrationRequestDto>{ event_id: generatedEvents[0].id }) .expect(status.CREATED) .then((res: SuperTestResponse<CreateRegistrationResponseDto>) => { registrationIds.set(scout.id, res.body.registration.id); }) .catch((err) => { throw new Error(err); }); })); }); afterAll(async () => { await TestUtils.dropDb(); await TestUtils.closeDb(); }); describe('when purchasable do not exist', () => { let postData: CreatePurchasableDto; beforeEach(() => { postData = { item: 'Test Item', price: 10 }; }); test('should not create a purchaser limit by default', async () => { await request.post(`/api/events/${generatedEvents[0].id}/purchasables`) .set('Authorization', generatedUsers.admin.token) .send(postData) .expect(status.CREATED) .then((res: SuperTestResponse<CreatePurchasablesResponseDto>) => { const purchasables = res.body.purchasables; expect(purchasables).to.have.length(1); expect(purchasables[0].item).to.equal('Test Item'); expect(purchasables[0].purchaser_limit).to.be.null; }); }); test('should be able to set a limit', async () => { postData.purchaser_limit = 10; await request.post(`/api/events/${generatedEvents[0].id}/purchasables`) .set('Authorization', generatedUsers.admin.token) .send(postData) .expect(status.CREATED) .then((res: SuperTestResponse<CreatePurchasablesResponseDto>) => { const purchasables = res.body.purchasables; expect(purchasables).to.have.length(1); expect(purchasables[0].item).to.equal('Test Item'); expect(purchasables[0].purchaser_limit).to.equal(10); }); }); test('should not allow a negative limit', async () => { postData.purchaser_limit = -1; await request.post(`/api/events/${generatedEvents[0].id}/purchasables`) .set('Authorization', generatedUsers.admin.token) .send(postData) .expect(status.BAD_REQUEST); }); test('should expect a number', async () => { postData.purchaser_limit = <any>'wrong'; await request.post(`/api/events/${generatedEvents[0].id}/purchasables`) .set('Authorization', generatedUsers.admin.token) .send(postData) .expect(status.BAD_REQUEST); }); }); describe('when a purchasable exists with a size limit', () => { let purchasableId: number; beforeEach(async () => { const postData: CreatePurchasableDto = { item: 'Test Item', price: 10, purchaser_limit: 2 }; await request.post(`/api/events/${generatedEvents[0].id}/purchasables`) .set('Authorization', generatedUsers.admin.token) .send(postData) .expect(status.CREATED) .then((res: SuperTestResponse<CreatePurchasablesResponseDto>) => { purchasableId = res.body.purchasables[0].id; }); }); test('should get the purchaser limit and count for an event', async () => { await request.get(`/api/events?id=${generatedEvents[0].id}`) .expect(status.OK) .then((res: SuperTestResponse<EventsResponseDto>) => { const event = res.body[0]; expect(event.purchasables.length).to.equal(1); expect(event.purchasables[0].purchaser_limit).to.equal(2); expect(event.purchasables[0].purchaser_count).to.equal(0); }); }); test('should get the purchaser limit and count for a specific item', async() => { await request.get(`/api/events/${generatedEvents[0].id}/purchasables`) .expect(status.OK) .then((res: SuperTestResponse<PurchasablesResponseDto>) => { expect(res.body).to.have.length(1); const purchasable: PurchasableDto = res.body[0]; expect(purchasable.purchaser_limit).to.equal(2); expect(purchasable.purchaser_count).to.equal(0); }); }); test('should allow adding a purchase if under the limit', async () => { await request.post(`/api/scouts/${generatedScouts[0].id}/registrations/${registrationIds.get(generatedScouts[0].id)}/purchases`) .set('Authorization', generatedUsers.coordinator.token) .send(<CreatePurchaseRequestDto>{ purchasable: purchasableId, quantity: 1 }) .expect(status.CREATED); }); test('should prevent adding a purchase if the limit has been met', async () => { await request.post(`/api/scouts/${generatedScouts[0].id}/registrations/${registrationIds.get(generatedScouts[0].id)}/purchases`) .set('Authorization', generatedUsers.coordinator.token) .send(<CreatePurchaseRequestDto>{ purchasable: purchasableId, quantity: 2 }) .expect(status.CREATED); await request.post(`/api/scouts/${generatedScouts[1].id}/registrations/${registrationIds.get(generatedScouts[1].id)}/purchases`) .set('Authorization', generatedUsers.coordinator.token) .send(<CreatePurchaseRequestDto>{ purchasable: purchasableId, quantity: 1 }) .expect(status.BAD_REQUEST); }); test('should prevent purchasing a quantity that exceeds the limit', async () => { await request.post(`/api/scouts/${generatedScouts[0].id}/registrations/${registrationIds.get(generatedScouts[0].id)}/purchases`) .set('Authorization', generatedUsers.coordinator.token) .send(<CreatePurchaseRequestDto>{ purchasable: purchasableId, quantity: 3 }) .expect(status.BAD_REQUEST); }); }); describe('when purchasers exist', () => { let purchasableId: number; beforeEach(async () => { const postData: CreatePurchasableDto = { item: 'Test Item', price: 10, purchaser_limit: 2 }; await request.post(`/api/events/${generatedEvents[0].id}/purchasables`) .set('Authorization', generatedUsers.admin.token) .send(postData) .expect(status.CREATED) .then((res: SuperTestResponse<CreatePurchasablesResponseDto>) => { purchasableId = res.body.purchasables[0].id; }); }); test('should count a single purchaser', async() => { await request.post(`/api/scouts/${generatedScouts[0].id}/registrations/${registrationIds.get(generatedScouts[0].id)}/purchases`) .set('Authorization', generatedUsers.coordinator.token) .send(<CreatePurchaseRequestDto>{ purchasable: purchasableId, quantity: 1 }) .expect(status.CREATED); await request.get(`/api/events/${generatedEvents[0].id}/purchasables`) .expect(status.OK) .then((res: SuperTestResponse<PurchasablesResponseDto>) => { expect(res.body).to.have.length(1); const purchasable: PurchasableDto = res.body[0]; expect(purchasable.purchaser_limit).to.equal(2); expect(purchasable.purchaser_count).to.equal(1); }); }); test('should count a purchase with more than one quantity', async () => { await request.post(`/api/scouts/${generatedScouts[0].id}/registrations/${registrationIds.get(generatedScouts[0].id)}/purchases`) .set('Authorization', generatedUsers.coordinator.token) .send(<CreatePurchaseRequestDto>{ purchasable: purchasableId, quantity: 2 }) .expect(status.CREATED); await request.get(`/api/events/${generatedEvents[0].id}/purchasables`) .expect(status.OK) .then((res: SuperTestResponse<PurchasablesResponseDto>) => { expect(res.body).to.have.length(1); const purchasable: PurchasableDto = res.body[0]; expect(purchasable.purchaser_limit).to.equal(2); expect(purchasable.purchaser_count).to.equal(2); }); }); }); }); <file_sep>/src/client/types/vuelidate.d.ts declare module 'vuelidate';<file_sep>/src/client/jest.config.js const { pathsToModuleNameMapper } = require('ts-jest/utils'); module.exports = { testRegex: '/.*Spec\.(ts|tsx|js)$', moduleFileExtensions: [ 'js', 'json', 'vue' ], moduleDirectories: ['node_modules', '<rootDir>/src'], transform: { '^.+\\.js$': 'babel-jest', '^.+\\.vue$': 'vue-jest' } }; <file_sep>/tests/helpers/supertest.interface.ts import { Response } from 'supertest'; export interface SuperTestResponse<T> extends Response { body: T; } <file_sep>/src/server/routes/events/getEvents.ts import { Request, Response } from 'express'; import { WhereOptions } from 'sequelize'; import status from 'http-status-codes'; import { cloneDeep } from 'lodash'; import { CurrentEvent } from '@models/currentEvent.model'; import { Event } from '@models/event.model'; import { ErrorResponseDto } from '@interfaces/shared.interface'; import { Badge } from '@models/badge.model'; import { Purchasable } from '@models/purchasable.model'; import { IncomeCalculationResponseDto, EventStatisticsDto, EventsResponseDto, EventDto } from '@interfaces/event.interface'; import { Offering } from '@models/offering.model'; import registrationInformation from '@models/queries/registrationInformation'; import { Registration } from '@models/registration.model'; import { Scout } from '@models/scout.model'; import { CalculationType } from '@routes/shared/calculationType.enum'; import { PurchasableDto } from '@interfaces/purchasable.interface'; export const getEvent = async (req: Request, res: Response) => { try { const queryableFields = ['id', 'year', 'semester']; const query: WhereOptions = queryableFields.reduce((_query: WhereOptions, field: string) => { if (req.query[field]) { (_query as any)[field] = req.query[field]; } return _query; }, {}); const events: Event[] = await Event.findAll({ where: query, include: [{ model: Badge, as: 'offerings', through: <any>{ as: 'details' } }, { model: Purchasable, as: 'purchasables' }] }); const result: EventsResponseDto = await Promise.all(events.map(async event => { const plainEvent: EventDto = event.get({ plain: true }); plainEvent.purchasables = await Promise.all(event.purchasables.map(async purchasable => { const purchasableDto: PurchasableDto = purchasable.get({ plain: true }); purchasableDto.purchaser_count = await purchasable.getPurchaserCount(); return purchasableDto; })); return plainEvent; })); return res.status(status.OK).json(result); } catch (err) { return res.status(status.BAD_REQUEST).json({ message: 'Error getting events', error: err }); } }; export const getCurrentEvent = async (_req: Request, res: Response) => { try { const currentEvent: CurrentEvent = await CurrentEvent.findOne({ include: [{ model: Event }] }); return res.status(status.OK).send(currentEvent.event); } catch (err) { res.status(status.BAD_REQUEST).json(<ErrorResponseDto>{ message: 'Failed to get the current event', error: err }); } }; export const getPurchasables = async (req: Request, res: Response) => { try { const event: Event = await Event.findByPk(req.params.id); const purchasables: Purchasable[] = await event.$get('purchasables') as Purchasable[]; const result: PurchasableDto[] = await Promise.all(purchasables.map(async purchasable => { const purchasableDto: PurchasableDto = purchasable.get({ plain: true }); purchasableDto.purchaser_count = await purchasable.getPurchaserCount(); return purchasableDto; })); return res.status(status.OK).json(result); } catch (err) { res.status(status.BAD_REQUEST).json(<ErrorResponseDto>{ message: 'Failed to get purchasables', error: err }); } }; export const getBuyers = async (req: Request, res: Response) => { try { const buyers: Registration[] = await Registration.findAll({ where: { event_id: req.params.eventId }, include: [{ model: Scout, as: 'scout' }, { model: Purchasable, as: 'purchases', where: { id: req.params.purchasableId }, through: <any>{ as: 'details' } }] }); return res.status(status.OK).json(buyers); } catch (err) { res.status(status.BAD_REQUEST).json(<ErrorResponseDto>{ message: 'Failed to get buyers', error: err }); } }; export const getClassSize = async (req: Request, res: Response) => { try { const offering: Offering = await Offering.findOne({ where: { badge_id: req.params.badgeId, event_id: req.params.eventId } }); return res.status(status.OK).send(await offering.getClassSizes()); } catch (err) { res.status(status.BAD_REQUEST).json(<ErrorResponseDto>{ message: 'Failed to get class size', error: err }); } }; export const getRegistrations = async (req: Request, res: Response) => { try { const query = cloneDeep(registrationInformation); query.where = { event_id: req.params.id }; const registrations: Registration[] = await Registration.findAll(query); return res.status(status.OK).json(registrations); } catch (err) { res.status(status.BAD_REQUEST).json(<ErrorResponseDto>{ message: 'Failed to get registrations', error: err }); } }; export const getAssignees = async (req: Request, res: Response) => { try { const offerings: Offering[] = await Offering.findAll({ where: { event_id: req.params.id }, attributes: [ ['id', 'offering_id'], 'duration', 'periods', 'requirements' ], include: <any>[{ model: Badge, as: 'badge', attributes: [ 'name', ['id', 'badge_id'] ] }, { model: Registration, as: 'assignees', attributes: { exclude: [ 'projectedCost', 'actualCost' ], include: [ ['id', 'registration_id'], 'notes' ], }, through: <any>{ as: 'assignment', attributes: [ 'periods', 'completions' ] }, include: [{ model: Scout, as: 'scout', attributes: [ 'firstname', 'lastname', 'fullname', 'troop' ] }] }] }); return res.status(status.OK).json(offerings); } catch (err) { res.status(status.BAD_REQUEST).json(<ErrorResponseDto>{ message: 'Failed to get assignees', error: err }); } }; export const getPotentialIncome = async (req: Request, res: Response) => { income(req, res, CalculationType.Projected); }; export const getActualIncome = async (req: Request, res: Response) => { income(req, res, CalculationType.Actual); }; export const getStats = async (req: Request, res: Response) => { try { const statsResult: EventStatisticsDto = {}; const [event, registrations]: [Event, Registration[]] = await Promise.all([ Event.findByPk(req.params.id, { include: [{ model: Scout, as: 'attendees', attributes: ['id', 'firstname', 'lastname', 'troop'] }, { model: Badge, as: 'offerings', attributes: ['id', 'name'] }] }), Registration.findAll({ where: { event_id: req.params.id }, attributes: ['scout_id'], include: [{ model: Purchasable, as: 'purchases', attributes: ['id', 'price', 'has_size'], through: <any>{ as: 'details', attributes: ['quantity', 'size'] } }] }) ]); statsResult.scouts = event.attendees; statsResult.offerings = event.offerings; statsResult.registrations = registrations; return res.status(status.OK).send(statsResult); } catch (err) { return res.status(status.BAD_REQUEST).json(<ErrorResponseDto>{ message: 'Failed to get stats', error: err }); } }; async function income(req: Request, res: Response, type: CalculationType): Promise<Response> { try { const registrations: Registration[] = await Registration.findAll({ where: { event_id: req.params.id } }); if (registrations.length < 1) { throw new Error('No registrations found'); } const prices: number[] = await Promise.all(registrations.map(registration => { return (type === CalculationType.Actual ? registration.actualCost() : registration.projectedCost()); })); const cost: number = prices.reduce((acc, cur) => acc + cur, 0); return res.status(status.OK).json(<IncomeCalculationResponseDto>{ income: String(cost.toFixed(2)) }); } catch (err) { return res.status(status.BAD_REQUEST).json(<ErrorResponseDto>{ message: `Failed to get ${type} event income`, error: err }); } } <file_sep>/src/libs/interfaces/user.interface.ts import { ScoutInterface } from './scout.interface'; export enum UserRole { ADMIN = 'admin', COORDINATOR = 'coordinator', TEACHER = 'teacher', ANONYMOUS = 'anonymous' } export interface UserInterface { id?: number; email: string; password: string; reset_password_token?: string; reset_token_expires?: Date; firstname: string; lastname: string; role: UserRole; approved?: boolean; details?: UserDetailsInterface; scouts?: ScoutInterface[]; fullname?: string; } export interface UserDetailsInterface { troop?: number; district?: string; council?: string; chapter?: string; } export interface ScoutUserDto extends UserInterface { user_id?: number; } export interface SignupRequestDto { email: string; password: string; firstname: string; lastname: string; role?: string; details?: UserDetailsInterface; } export interface EditUserDto { email?: string; password?: string; firstname?: string; lastname?: string; details?: UserDetailsInterface; } export interface EditUserResponseDto { message: string; profile: UserInterface; token?: string; } export type UsersResponseDto = UserInterface[]; export interface LoginRequestDto { email: string; password: string; } export interface UserTokenResponseDto { token: string; profile: UserInterface; } export interface UserExistsResponseDto { exists: boolean; } export interface UserProfileResponseDto { message: string; profile: UserInterface; } <file_sep>/src/client/src/validators/phoneSpec.js import { expect } from 'chai' import phone from './phone'; describe('The phone validator', () => { it('should validate a formatted phone number', () => { expect(phone('(123) 456-7890')).to.be.true; expect(phone('(123)456-7890')).to.be.true; }); it('should fail for unformatted numbers', () => { expect(phone('123-456-7890')).to.be.false; expect(phone('1234567890')).to.be.false; expect(phone('(123) 45-6789')).to.be.false; expect(phone('(123) 456-789')).to.be.false; expect(phone('(123) 45-67890')).to.be.false; expect(phone('(123) 4567-890')).to.be.false; }); }); <file_sep>/src/server/middleware/canUpdateRole.ts import { Request, NextFunction, Response } from 'express'; import passport from 'passport'; import status from 'http-status-codes'; import { User } from '@models/user.model'; import { MessageResponseDto } from '@interfaces/shared.interface'; import { UserRole } from '@interfaces/user.interface'; export const canUpdateRole = (req: Request, res: Response, next: NextFunction) => { return passport.authenticate('jwt', { session: false }, (_err, user: User) => { if ( (req.body.role && user.role !== UserRole.ADMIN) || (req.body.approved && user.role !== UserRole.ADMIN) || (req.body.password && (!(user.role === UserRole.ADMIN)) && Number(req.params.userId) !== user.id) ) { return res.status(status.UNAUTHORIZED).json(<MessageResponseDto>{ message: 'Only admins are allowed to update roles' }); } else { return next(); } })(req, res, next); }; <file_sep>/src/server/db.ts import { Sequelize } from 'sequelize-typescript'; const env = process.env.NODE_ENV || 'development'; const localDbUrl = env === 'development' ? 'postgres://mbu:mbu@localhost/mbu' : 'postgres://mbu:mbu@localhost/mbutest'; const dbUrl = process.env.DATABASE_URL ? process.env.DATABASE_URL : localDbUrl; export const sequelize: Sequelize = new Sequelize(dbUrl, { dialect: 'postgres', protocol: 'postgres', logging: false, models: [`${__dirname}/models/**/*.model*`], modelMatch: (filename: string, member: string) => { return filename.substring(0, filename.indexOf('.model')).toLowerCase() === member.toLowerCase(); } }); sequelize.authenticate() .catch((err) => { console.error('Failed to connect to database', err); }); <file_sep>/src/server/routes/scouts/postScouts.ts import { Request, Response } from 'express'; import status from 'http-status-codes'; import { Scout } from '@models/scout.model'; import { Registration } from '@models/registration.model'; import { ErrorResponseDto } from '@interfaces/shared.interface'; import { RegistrationInterface, CreateRegistrationResponseDto } from '@interfaces/registration.interface'; import { Event } from '@models/event.model'; import { Preference } from '@models/preference.model'; import { CreatePreferenceRequestDto, PreferenceInterface, CreatePreferenceResponseDto } from '@interfaces/preference.interface'; import { Offering } from '@models/offering.model'; import { Assignment } from '@models/assignment.model'; import { AssignmentInterface, CreateAssignmentRequestDto, CreateAssignmentResponseDto } from '@interfaces/assignment.interface'; import { Badge } from '@models/badge.model'; import { Purchasable } from '@models/purchasable.model'; import { CreatePurchaseResponseDto } from '@interfaces/purchase.interface'; import { Purchase } from '@models/purchase.model'; export const createRegistration = async (req: Request, res: Response) => { try { const [scout, event] = await Promise.all([ Scout.findByPk(req.params.scoutId), Event.findByPk(req.body.event_id) ]); if (!scout) { throw new Error('Scout to add registration for not found'); } if (!event) { throw new Error('Event to add registration for not found'); } const registration = await Registration.create({ scout_id: req.params.scoutId, event_id: req.body.event_id, notes: req.body.notes }); return res.status(status.CREATED).json(<RegistrationInterface>{ message: 'Scout successfully registered for event', registration: registration }); } catch (err) { return res.status(status.BAD_REQUEST).json(<ErrorResponseDto>{ message: 'Registration could not be created', error: 'err' }); } }; export const createPreference = async (req: Request, res: Response) => { try { const scoutId = req.params.scoutId; const registrationId = Number(req.params.registrationId); if (Array.isArray(req.body)) { await Preference.destroy({ where: { registration_id: registrationId } }); const preferences: PreferenceInterface[] = req.body.map((preference: CreatePreferenceRequestDto) => ({ registration_id: registrationId, offering_id: preference.offering, rank: preference.rank })); await Preference.bulkCreate(preferences, { individualHooks: true, validate: true }); } else { const registration: Registration = await Registration.findOne({ where: { id: registrationId, scout_id: scoutId } }); await registration.$add('preference', req.body.offering, { through: <any>{ rank: req.body.rank } }); } const createdRegistration: Registration = await Registration.findByPk(registrationId, { include: [{ model: Offering, as: 'preferences', attributes: ['badge_id', ['id', 'offering_id']], through: <any>{ as: 'details', attributes: ['rank'] } }] }); return res.status(status.CREATED).json(<CreatePreferenceResponseDto>{ message: 'Preference created', registration: createdRegistration }); } catch (err) { return res.status(status.BAD_REQUEST).json(<ErrorResponseDto>{ message: 'Preference could not be created', error: 'err' }); } }; export const createAssignment = async (req: Request, res: Response) => { try { const registrationId = Number(req.params.registrationId); let assignments: AssignmentInterface[]; if (Array.isArray(req.body)) { await Assignment.destroy({ where: { registration_id: registrationId } }); assignments = req.body.map((assignment: CreateAssignmentRequestDto) => ({ registration_id: registrationId, offering_id: assignment.offering, periods: assignment.periods, completions: assignment.completions })); } else { assignments = [{ registration_id: registrationId, offering_id: req.body.offering, periods: req.body.periods, completions: req.body.completions }]; } await Assignment.bulkCreate(assignments, { individualHooks: true, validate: true }); const createdRegistration: Registration = await Registration.findByPk(registrationId, { include: [{ model: Offering, as: 'assignments', attributes: ['badge_id', ['id', 'offering_id'], 'price'], through: <any>{ as: 'details', attributes: ['periods', 'completions'] }, include: [{ model: Badge, as: 'badge', attributes: ['name'] }] }], }); return res.status(status.CREATED).json(<CreateAssignmentResponseDto>{ message: 'Assignment created successfully', registration: createdRegistration }); } catch (err) { return res.status(status.BAD_REQUEST).json(<ErrorResponseDto>{ message: 'Assignment could not be created', error: 'err' }); } }; export const createPurchase = async (req: Request, res: Response) => { try { const registration: Registration = await Registration.findOne({ where: { id: req.params.registrationId, scout_id: req.params.scoutId } }); const purchase: Purchase = await Purchase.create({ quantity: req.body.quantity, size: req.body.size, purchasable_id: req.body.purchasable, registration_id: req.params.registrationId }); const createdRegistration: Registration = await Registration.findByPk(req.params.registrationId, { include: [{ model: Purchasable, as: 'purchases', through: <any>{ as: 'details', attributes: ['size', 'quantity'] } }] }); return res.status(status.CREATED).json(<CreatePurchaseResponseDto>{ message: 'Purchase created' , registration: createdRegistration }); } catch (err) { return res.status(status.BAD_REQUEST).json(<ErrorResponseDto>{ message: 'Purchase could not be created', error: err }); } }; <file_sep>/tests/server/userAccountsSpec.ts import supertest from 'supertest'; import * as async from 'async'; import status from 'http-status-codes'; import { expect } from 'chai'; import app from '@app/app'; import TestUtils, { RoleTokenObjects } from './testUtils'; import { SignupRequestDto, UserInterface, EditUserDto, UserRole, UserTokenResponseDto, UsersResponseDto, EditUserResponseDto, LoginRequestDto, UserProfileResponseDto } from '@interfaces/user.interface'; import { ScoutInterface } from '@interfaces/scout.interface'; import { SuperTestResponse } from '@test/helpers/supertest.interface'; const request = supertest(app); describe('user profiles', () => { let generatedUsers: RoleTokenObjects; beforeEach(async () => { await TestUtils.dropDb(); }); beforeEach(async () => { generatedUsers = await TestUtils.generateTokens(); }); afterAll(async () => { await TestUtils.dropDb(); await TestUtils.closeDb(); }); describe('account details', () => { test('creates an account with coordinator information', (done) => { const postData: SignupRequestDto = { email: '<EMAIL>', password: '<PASSWORD>', firstname: 'firstname', lastname: 'lastname', role: 'coordinator', details: { troop: 1, district: 'district', council: 'council' } }; request.post('/api/signup') .send(postData) .expect(status.CREATED) .end((err, res: SuperTestResponse<UserTokenResponseDto>) => { if (err) { return done(err); } expect(res.body.profile.email).to.equal(postData.email); expect(res.body.profile.firstname).to.equal(postData.firstname); expect(res.body.profile.lastname).to.equal(postData.lastname); expect(res.body.profile.password).to.not.exist; expect(res.body.token).to.exist; expect(res.body.profile.details).to.deep.equal(postData.details); return done(); }); }); test('creates an account with teacher information', (done) => { const postData: SignupRequestDto = { email: '<EMAIL>', password: '<PASSWORD>', firstname: 'firstname', lastname: 'lastname', role: 'teacher', details: { chapter: 'chapter' } }; request.post('/api/signup') .send(postData) .expect(status.CREATED) .end((err, res: SuperTestResponse<UserTokenResponseDto>) => { if (err) { return done(err); } expect(res.body.profile.email).to.equal(postData.email); expect(res.body.profile.firstname).to.equal(postData.firstname); expect(res.body.profile.lastname).to.equal(postData.lastname); expect(res.body.profile.password).to.not.exist; expect(res.body.token).to.exist; expect(res.body.profile.details).to.deep.equal(postData.details); return done(); }); }); test('does not create coordinator with teacher info', (done) => { const postData: SignupRequestDto = { email: '<EMAIL>', password: '<PASSWORD>', firstname: 'firstname', lastname: 'lastname', role: 'coordinator', details: { chapter: 'chapter' } }; request.post('/api/signup') .send(postData) .expect(status.BAD_REQUEST, done); }); test('does not create teacher with coordinator info', (done) => { const postData: SignupRequestDto = { email: '<EMAIL>', password: '<PASSWORD>', firstname: 'firstname', lastname: 'lastname', role: 'teacher', details: { troop: 1, district: 'district', council: 'council' } }; request.post('/api/signup') .send(postData) .expect(status.BAD_REQUEST, done); }); }); describe('getting account details', () => { let user1: UserInterface; let user2: UserInterface; let user1Token: string; let user2Token: string; beforeEach((done) => { user1 = { email: '<EMAIL>', password: '<PASSWORD>', firstname: 'firstname', lastname: 'lastname', role: UserRole.COORDINATOR, details: { troop: 1, district: 'district', council: 'council' } }; user2 = { email: '<EMAIL>', password: '<PASSWORD>', firstname: 'firstname', lastname: 'lastname', role: UserRole.COORDINATOR, details: { troop: 2, district: 'district2', council: 'council2' } }; async.series([ (cb) => { request.post('/api/signup') .send(user1) .expect(status.CREATED) .end((err, res: SuperTestResponse<UserTokenResponseDto>) => { if (err) { return done(err); } user1.id = res.body.profile.id; user1Token = res.body.token; return cb(); }); }, (cb) => { request.post('/api/signup') .send(user2) .expect(status.CREATED) .end((err, res: SuperTestResponse<UserTokenResponseDto>) => { if (err) { return done(err); } user2.id = res.body.profile.id; user2Token = res.body.token; return cb(); }); } ], done); }); test('should not return the encrypted password', (done) => { request.get('/api/users/' + user1.id) .set('Authorization', user1Token) .expect(status.OK) .end((err, res) => { if (err) { return done(err); } expect(res.body.password).to.not.exist; return done(); }); }); test('should get details for a user with their own token', (done) => { request.get('/api/users/' + user1.id) .set('Authorization', user1Token) .expect(status.OK) .end((err, res: SuperTestResponse<UsersResponseDto>) => { if (err) { return done(err); } expect(res.body[0].id).to.equal(user1.id); expect(res.body[0].details).to.deep.equal(user1.details); return done(); }); }); test('should get details for a user with an admin token', (done) => { request.get('/api/users/' + user1.id) .set('Authorization', generatedUsers.admin.token) .expect(status.OK) .end((err, res: SuperTestResponse<UsersResponseDto>) => { if (err) { return done(err); } expect(res.body[0].id).to.equal(user1.id); expect(res.body[0].details).to.deep.equal(user1.details); return done(); }); }); test('should get a list of users', (done) => { request.get('/api/users/') .set('Authorization', generatedUsers.admin.token) .expect(status.OK) .end((err, res: SuperTestResponse<UsersResponseDto>) => { if (err) { return done(err); } expect(res.body).to.have.length(5); return done(); }); }); test('should get details for a user with a teacher token', (done) => { request.get('/api/users/' + user1.id) .set('Authorization', generatedUsers.teacher.token) .expect(status.OK) .end((err, res: SuperTestResponse<UsersResponseDto>) => { if (err) { return done(err); } expect(res.body[0].id).to.equal(user1.id); expect(res.body[0].details).to.deep.equal(user1.details); return done(); }); }); test('should not allow other users to see other profiles', (done) => { request.get('/api/users/' + user1.id) .set('Authorization', user2Token) .expect(status.UNAUTHORIZED, done); }); test('should not allow other users to see other profiles with query', (done) => { request.get('/api/users?id=' + user1.id) .set('Authorization', user2Token) .expect(status.UNAUTHORIZED, done); }); test('should not get details for an invalid user', (done) => { request.get('/api/users/wat') .set('Authorization', generatedUsers.admin.token) .expect(status.BAD_REQUEST, done); }); }); describe('editing account details', () => { let user1: UserInterface; let user2: UserInterface; let user1Token: string; let user2Token: string; beforeEach((done) => { user1 = { email: '<EMAIL>', password: '<PASSWORD>', firstname: 'firstname', lastname: 'lastname', role: UserRole.COORDINATOR, details: { troop: 1, district: 'district', council: 'council' } }; user2 = { email: '<EMAIL>', password: '<PASSWORD>', firstname: 'firstname', lastname: 'lastname', role: UserRole.TEACHER, details: { chapter: 'Book' } }; async.series([ (cb) => { request.post('/api/signup') .send(user1) .expect(status.CREATED) .end((err, res: SuperTestResponse<UserTokenResponseDto>) => { if (err) { return done(err); } user1.id = res.body.profile.id; user1Token = res.body.token; return cb(); }); }, (cb) => { request.post('/api/signup') .send(user2) .expect(status.CREATED) .end((err, res: SuperTestResponse<UserTokenResponseDto>) => { if (err) { return done(err); } user2.id = res.body.profile.id; user2Token = res.body.token; return cb(); }); } ], done); }); test('should edit a profile', (done) => { const edited: EditUserDto = { firstname: 'changed', details: { troop: 1000 } }; request.put('/api/users/' + user1.id) .set('Authorization', user1Token) .send(edited) .expect(status.OK) .end((err, res: SuperTestResponse<EditUserResponseDto>) => { if (err) { return done(err); } expect(res.body.profile.id).to.equal(user1.id); expect(res.body.profile.firstname).to.equal(edited.firstname); expect(res.body.profile.lastname).to.equal(user1.lastname); expect(res.body.profile.details).to.deep.equal(edited.details); return done(); }); }); test('should still login after editing a profile', (done) => { async.series([ (cb) => { request.post('/api/authenticate') .send(<LoginRequestDto>{ email: user2.email, password: <PASSWORD> }) .expect(status.OK, cb); }, (cb) => { request.put('/api/users/' + user2.id) .set('Authorization', user2Token) .send(<EditUserDto>{ firstname: 'New' }) .expect(status.OK) .end((err) => { if (err) { return done(err); } cb(); }); }, (cb) => { request.post('/api/authenticate') .send(<LoginRequestDto>{ email: user2.email, password: <PASSWORD> }) .expect(status.OK, cb); } ], done); }); test('should not send a token if the password did not change', (done) => { request.put('/api/users/' + user1.id) .set('Authorization', user1Token) .send(<EditUserDto>{ firstname: 'New' }) .expect(status.OK) .end((err, res) => { if (err) { return done(err); } expect(res.body.token).to.not.exist; return done(); }); }); test('should not allow invalid details', (done) => { request.put('/api/users/' + user2.id) .set('Authorization', user2Token) .send(<EditUserDto>{ details: { troop: 450 } }) .expect(status.BAD_REQUEST, done); }); test('should not allow other coordinators to edit a coordinator profile', (done) => { request.put('/api/users/' + user1.id) .set('Authorization', generatedUsers.coordinator.token) .expect(status.UNAUTHORIZED, done); }); test('should not allow coordinators to edit a teacher profile', (done) => { request.put('/api/users/' + user2.id) .set('Authorization', user1Token) .expect(status.UNAUTHORIZED, done); }); test('should allow admins to edit a profile', (done) => { request.put('/api/users/' + user1.id) .set('Authorization', generatedUsers.admin.token) .expect(status.OK, done); }); test('should allow teachers to edit a profile', (done) => { request.put('/api/users/' + user1.id) .set('Authorization', generatedUsers.teacher.token) .expect(status.OK, done); }); test('should change a password', (done) => { let newToken: string; const edit: EditUserDto = { password: '<PASSWORD>' }; async.series([ (cb) => { request.post('/api/authenticate') .send(<LoginRequestDto>{ email: user2.email, password: <PASSWORD> }) .expect(status.OK, cb); }, (cb) => { request.put('/api/users/' + user2.id) .set('Authorization', user2Token) .send(edit) .expect(status.OK) .end((err, res: SuperTestResponse<EditUserResponseDto>) => { if (err) { return done(err); } newToken = res.body.token; cb(); }); }, (cb) => { request.post('/api/authenticate') .send(<LoginRequestDto>{ email: user2.email, password: <PASSWORD> }) .expect(status.OK, cb); }, (cb) => { request.get('/api/profile') .set('Authorization', newToken) .expect(status.OK) .end((err, res: SuperTestResponse<UserProfileResponseDto>) => { if (err) { return done(err); } expect(res.body.profile.email).to.equal(user2.email); expect(res.body.profile.details).to.deep.equal(user2.details); return cb(); }); } ], done); }); test('should allow changes to the same password', (done) => { let newToken: string; async.series([ (cb) => { request.post('/api/authenticate') .send(<LoginRequestDto>{ email: user2.email, password: <PASSWORD> }) .expect(status.OK, cb); }, (cb) => { request.put('/api/users/' + user2.id) .set('Authorization', user2Token) .send(<EditUserDto>{ password: <PASSWORD> }) .expect(status.OK) .end((err, res) => { if (err) { return done(err); } newToken = res.body.token; cb(); }); }, (cb) => { request.post('/api/authenticate') .send(<LoginRequestDto>{ email: user2.email, password: <PASSWORD> }) .expect(status.OK, cb); }, (cb) => { request.get('/api/profile') .set('Authorization', newToken) .expect(status.OK) .end((err, res: SuperTestResponse<UserProfileResponseDto>) => { if (err) { return done(err); } expect(res.body.profile.email).to.equal(user2.email); expect(res.body.profile.details).to.deep.equal(user2.details); return cb(); }); } ], done); }); test('should allow admins to edit a role', (done) => { async.series([ (cb) => { request.put('/api/users/' + user2.id) .set('Authorization', generatedUsers.admin.token) .send(<EditUserDto>{ role: 'admin' }) .expect(status.OK, cb); }, (cb) => { request.get('/api/users/' + user2.id) .set('Authorization', user2Token) .expect(status.OK) .end((err, res: SuperTestResponse<UsersResponseDto>) => { if (err) { return done(err); } expect(res.body[0].id).to.equal(user2.id); expect(res.body[0].role).to.equal('admin'); return cb(); }); } ], done); }); test('should not allow teachers to edit a role', (done) => { request.put('/api/users/' + user2.id) .set('Authorization', generatedUsers.teacher.token) .send(<EditUserDto>{ role: 'admin' }) .expect(status.UNAUTHORIZED, done); }); test('should not allow coordinators to edit a role', (done) => { request.put('/api/users/' + user2.id) .set('Authorization', generatedUsers.coordinator.token) .send(<EditUserDto>{ role: 'admin' }) .expect(status.UNAUTHORIZED, done); }); test('should not allow self role edits', (done) => { request.put('/api/users/' + user2.id) .set('Authorization', user2Token) .send(<EditUserDto>{ role: 'admin' }) .expect(status.UNAUTHORIZED, done); }); test('should not allow teachers to edit other passwords', (done) => { request.put('/api/users/' + user2.id) .set('Authorization', generatedUsers.teacher.token) .send(<EditUserDto>{ password: '<PASSWORD>' }) .expect(status.UNAUTHORIZED, done); }); test('should allow admins to edit a password', (done) => { request.put('/api/users/' + user2.id) .set('Authorization', generatedUsers.admin.token) .send(<EditUserDto>{ password: '<PASSWORD>' }) .expect(status.OK, done); }); test('should allow admins to edit a password', (done) => { request.put('/api/users/' + user2.id) .set('Authorization', generatedUsers.admin.token) .send(<EditUserDto>{ password: 'new' }) .expect(status.OK) .end((err, res: SuperTestResponse<EditUserResponseDto>) => { if (err) { return done(err); } expect(res.body.token).to.exist; done(); }); }); }); describe('deleting accounts', () => { let coordinator: UserInterface; let teacher: UserInterface; let coordinatorToken: string; let teacherToken: string; beforeEach((done) => { coordinator = { email: '<EMAIL>', password: '<PASSWORD>', firstname: 'firstname', lastname: 'lastname', role: UserRole.COORDINATOR, details: { troop: 1, district: 'district', council: 'council' } }; teacher = { email: '<EMAIL>', password: '<PASSWORD>', firstname: 'firstname', lastname: 'lastname', role: UserRole.TEACHER, details: { chapter: 'Book' } }; async.series([ (cb) => { request.post('/api/signup') .send(coordinator) .expect(status.CREATED) .end((err, res: SuperTestResponse<UserTokenResponseDto>) => { if (err) { return done(err); } coordinator.id = res.body.profile.id; coordinatorToken = res.body.token; return cb(); }); }, (cb) => { request.post('/api/signup') .send(teacher) .expect(status.CREATED) .end((err, res: SuperTestResponse<UserTokenResponseDto>) => { if (err) { return done(err); } teacher.id = res.body.profile.id; teacherToken = res.body.token; return cb(); }); } ], done); }); test('should delete own account', (done) => { async.series([ (cb) => { request.get('/api/users/' + coordinator.id) .set('Authorization', coordinatorToken) .expect(status.OK) .end((err, res: SuperTestResponse<UsersResponseDto>) => { if (err) { return done(err); } expect(res.body[0].id).to.equal(coordinator.id); cb(); }); }, (cb) => { request.del('/api/users/' + coordinator.id) .set('Authorization', coordinatorToken) .expect(status.OK, cb); }, (cb) => { request.get('/api/users/' + coordinator.id) .set('Authorization', generatedUsers.admin.token) .expect(status.BAD_REQUEST, cb); } ], done); }); test('should not delete another users account', (done) => { request.del('/api/users/' + coordinator.id) .set('Authorization', teacherToken) .expect(status.UNAUTHORIZED, done); }); test('should require a token', (done) => { request.del('/api/users/' + coordinator.id) .expect(status.UNAUTHORIZED, done); }); test('should allow admins to delete accounts', (done) => { request.del('/api/users/' + coordinator.id) .set('Authorization', generatedUsers.admin.token) .expect(status.OK, done); }); test('should fail gracefully if a user isnt found', (done) => { request.del('/api/users/walal') .set('Authorization', generatedUsers.admin.token) .expect(status.BAD_REQUEST, done); }); test('should require an id', (done) => { request.del('/api/users') .set('Authorization', generatedUsers.admin.token) .expect(status.NOT_FOUND, done); }); }); describe('account approval', () => { test('should default new accounts to not approved', (done) => { const postData: SignupRequestDto = { email: '<EMAIL>', password: '<PASSWORD>', firstname: 'firstname', lastname: 'lastname' }; request.post('/api/signup') .send(postData) .expect(status.CREATED) .end((err, res: SuperTestResponse<UserTokenResponseDto>) => { if (err) { return done(err); } expect(res.body.profile.approved).to.be.false; return done(); }); }); test('should not allow approval to be set by creator', (done) => { const postData: any = { email: '<EMAIL>', password: '<PASSWORD>', firstname: 'firstname', lastname: 'lastname', approved: true }; request.post('/api/signup') .send(postData) .expect(status.CREATED) .end((err, res: SuperTestResponse<UserTokenResponseDto>) => { if (err) { return done(err); } expect(res.body.profile.approved).to.be.false; return done(); }); }); test('should allow admins to change an accounts approval status', (done) => { let accountId: number; async.series([ (cb) => { const postData: SignupRequestDto = { email: '<EMAIL>', password: '<PASSWORD>', firstname: 'firstname', lastname: 'lastname' }; request.post('/api/signup') .send(postData) .expect(status.CREATED) .end((err, res: SuperTestResponse<UserTokenResponseDto>) => { if (err) { return done(err); } expect(res.body.profile.approved).to.be.false; accountId = res.body.profile.id; return cb(); }); }, (cb) => { request.put('/api/users/' + accountId) .set('Authorization', generatedUsers.admin.token) .send({ approved: true }) .expect(status.OK) .end((err, res) => { if (err) { return done(err); } expect(res.body.profile.approved).to.be.true; expect(res.body.profile.id).to.equal(accountId); return cb(); }); } ], done); }); test('should not allow coordinators to change account approval status', (done) => { let accountId: number; async.series([ (cb) => { const postData: SignupRequestDto = { email: '<EMAIL>', password: '<PASSWORD>', firstname: 'firstname', lastname: 'lastname' }; request.post('/api/signup') .send(postData) .expect(status.CREATED) .end((err, res: SuperTestResponse<UserTokenResponseDto>) => { if (err) { return done(err); } expect(res.body.profile.approved).to.be.false; accountId = res.body.profile.id; return cb(); }); }, (cb) => { request.put('/api/users/' + accountId) .set('Authorization', generatedUsers.coordinator.token) .send(<EditUserDto>{ approved: true }) .expect(status.UNAUTHORIZED, cb); } ], done); }); test('should not allow teachers to change account approval status', (done) => { let accountId: number; async.series([ (cb) => { const postData: SignupRequestDto = { email: '<EMAIL>', password: '<PASSWORD>', firstname: 'firstname', lastname: 'lastname' }; request.post('/api/signup') .send(postData) .expect(status.CREATED) .end((err, res) => { if (err) { return done(err); } expect(res.body.profile.approved).to.be.false; accountId = res.body.profile.id; return cb(); }); }, (cb) => { request.put('/api/users/' + accountId) .set('Authorization', generatedUsers.teacher.token) .send(<EditUserDto>{ approved: true }) .expect(status.UNAUTHORIZED, cb); } ], done); }); test('should require approval for protected routes', (done) => { let token: string; let accountId: number; const exampleScout: ScoutInterface = { firstname: 'Scouty', lastname: 'McScoutFace', birthday: new Date(1999, 1, 1), troop: 101, notes: 'Is a boat', emergency_name: '<NAME>', emergency_relation: 'Idol', emergency_phone: '1234567890' }; async.series([ (cb) => { const postData: SignupRequestDto = { email: '<EMAIL>', password: '<PASSWORD>', firstname: 'firstname', lastname: 'lastname', role: 'coordinator', details: { troop: 1, district: 'district', council: 'council' } }; request.post('/api/signup') .send(postData) .expect(status.CREATED) .end((err, res: SuperTestResponse<UserTokenResponseDto>) => { if (err) { return done(err); } expect(res.body.profile.approved).to.be.false; accountId = res.body.profile.id; token = res.body.token; return cb(); }); }, (cb) => { request.post('/api/users/' + accountId + '/scouts') .set('Authorization', token) .send(exampleScout) .expect(status.UNAUTHORIZED, cb); } ], done); }); test('should allow changes once an account is approved', (done) => { let token: string; let accountId: number; const exampleScout: ScoutInterface = { firstname: 'Scouty', lastname: 'McScoutFace', birthday: new Date(1999, 1, 1), troop: 101, notes: 'Is a boat', emergency_name: '<NAME>', emergency_relation: 'Idol', emergency_phone: '1234567890' }; async.series([ (cb) => { const postData: SignupRequestDto = { email: '<EMAIL>', password: '<PASSWORD>', firstname: 'firstname', lastname: 'lastname', role: 'coordinator', details: { troop: 1, district: 'district', council: 'council' } }; request.post('/api/signup') .send(postData) .expect(status.CREATED) .end((err, res: SuperTestResponse<UserTokenResponseDto>) => { if (err) { return done(err); } expect(res.body.profile.approved).to.be.false; accountId = res.body.profile.id; token = res.body.token; return cb(); }); }, (cb) => { request.post('/api/users/' + accountId + '/scouts') .set('Authorization', token) .send(exampleScout) .expect(status.UNAUTHORIZED, cb); }, (cb) => { request.put('/api/users/' + accountId) .set('Authorization', generatedUsers.admin.token) .send({ approved: true }) .expect(status.OK) .end((err, res: SuperTestResponse<EditUserResponseDto>) => { if (err) { return done(err); } expect(res.body.profile.approved).to.be.true; expect(res.body.profile.id).to.equal(accountId); return cb(); }); }, (cb) => { request.post('/api/users/' + accountId + '/scouts') .set('Authorization', token) .send(exampleScout) .expect(status.CREATED, cb); } ], done); }); }); }); <file_sep>/tests/server/assignmentRegistrationSpec.ts import supertest from 'supertest'; import * as async from 'async'; import status from 'http-status-codes'; import { expect } from 'chai'; import app from '@app/app'; import TestUtils, { RoleTokenObjects } from './testUtils'; import { Badge } from '@models/badge.model'; import { Event } from '@models/event.model'; import { Scout } from '@models/scout.model'; import { Offering } from '@models/offering.model'; import { Assignment } from '@models/assignment.model'; import { Registration } from '@models/registration.model'; import { UserRole } from '@interfaces/user.interface'; import { OfferingInterface } from '@interfaces/offering.interface'; import testScouts from './testScouts'; import { RegistrationRequestDto, CreateRegistrationResponseDto } from '@interfaces/registration.interface'; import { SuperTestResponse } from '@test/helpers/supertest.interface'; import { ScoutRegistrationResponseDto } from '@interfaces/scout.interface'; const request = supertest(app); describe('Assignments and registrations', () => { let badges: Badge[]; let events: Event[]; let generatedUsers: RoleTokenObjects; let generatedTroop1: Scout[]; let generatedTroop2: Scout[]; let generatedOfferings: Offering[]; let troop1Registrations: number[]; let troop2Registrations: number[]; beforeAll(async () => { await TestUtils.dropDb(); }); beforeAll(async () => { generatedUsers = await TestUtils.generateTokens([ UserRole.ADMIN, UserRole.COORDINATOR, UserRole.TEACHER, 'coordinator1' as any ]); }); beforeEach(async () => { troop1Registrations = []; troop2Registrations = []; await TestUtils.dropTable([Event, Offering, Badge, Assignment, Registration, Scout]); }); beforeEach(async () => { const defaultPostData: OfferingInterface = { price: 10, periods: [1, 2, 3], duration: 1, requirements: ['1', '2', '3'] }; badges = await TestUtils.createBadges(); events = await TestUtils.createEvents(); generatedOfferings = await TestUtils.createOfferingsForEvent(events[0], badges, defaultPostData); generatedTroop1 = await TestUtils.createScoutsForUser(generatedUsers.coordinator, testScouts(5)); generatedTroop2 = await TestUtils.createScoutsForUser(generatedUsers.coordinator1, testScouts(5)); }); afterAll(async () => { await TestUtils.dropDb(); await TestUtils.closeDb(); }); describe('when a group of scouts has been registered', () => { beforeEach((done) => { async.forEachOfSeries(generatedTroop1, (scout, index, cb) => { request.post('/api/scouts/' + scout.id + '/registrations') .set('Authorization', generatedUsers.coordinator.token) .send(<RegistrationRequestDto>{ event_id: events[0].id }) .expect(status.CREATED) .end((err, res: SuperTestResponse<CreateRegistrationResponseDto>) => { if (err) { return done(err); } troop1Registrations.push(res.body.registration.id); return cb(); }); }, (err) => { done(err); }); }); test('should contain the correct registrations', (done) => { request.get('/api/events/' + events[0].id + '/registrations') .set('Authorization', generatedUsers.admin.token) .expect(status.OK) .end((err, res: SuperTestResponse<ScoutRegistrationResponseDto>) => { if (err) { return done(err); } expect(res.body).to.have.lengthOf(5); return done(); }); }); describe('and another group of scouts is registered', () => { beforeEach((done) => { async.forEachOfSeries(generatedTroop2, (scout, index, cb) => { request.post('/api/scouts/' + scout.id + '/registrations') .set('Authorization', generatedUsers.coordinator1.token) .send(<RegistrationRequestDto>{ event_id: events[0].id }) .expect(status.CREATED) .end((err, res: SuperTestResponse<CreateRegistrationResponseDto>) => { if (err) { return done(err); } troop2Registrations.push(res.body.registration.id); return cb(); }); }, (err) => { done(err); }); }); test('should contain the correct registrations', (done) => { request.get('/api/events/' + events[0].id + '/registrations') .set('Authorization', generatedUsers.admin.token) .expect(status.OK) .end((err, res: SuperTestResponse<ScoutRegistrationResponseDto>) => { if (err) { return done(err); } expect(res.body).to.have.lengthOf(10); return done(); }); }); describe('and a coordinator requests registration information', () => { beforeEach((done) => { request.get('/api/users/' + generatedUsers.coordinator1.profile.id + '/events/' + events[0].id + '/registrations') .set('Authorization', generatedUsers.coordinator1.token) .expect(status.OK, done); }); test('should contain the correct registrations', (done) => { request.get('/api/events/' + events[0].id + '/registrations') .set('Authorization', generatedUsers.admin.token) .expect(status.OK) .end((err, res: SuperTestResponse<ScoutRegistrationResponseDto>) => { if (err) { return done(err); } expect(res.body).to.have.lengthOf(10); return done(); }); }); }); }); describe('and they have been assigned to classes', () => { beforeEach((done) => { async.forEachOfSeries(generatedTroop1, (scout, index: number, cb) => { request.post('/api/scouts/' + scout.id + '/registrations/' + troop1Registrations[index] + '/assignments') .set('Authorization', generatedUsers.teacher.token) .send(<RegistrationRequestDto>{ offering: generatedOfferings[0].id, periods: [1] }) .expect(status.CREATED, cb); }, (err) => { done(err); }); }); test('should contain the correct registrations', (done) => { request.get('/api/events/' + events[0].id + '/registrations') .set('Authorization', generatedUsers.admin.token) .expect(status.OK) .end((err, res: SuperTestResponse<ScoutRegistrationResponseDto>) => { if (err) { return done(err); } expect(res.body).to.have.lengthOf(5); return done(); }); }); describe('and another group of scouts is registered', () => { beforeEach((done) => { async.forEachOfSeries(generatedTroop2, (scout, index, cb) => { request.post('/api/scouts/' + scout.id + '/registrations') .set('Authorization', generatedUsers.coordinator1.token) .send(<RegistrationRequestDto>{ event_id: events[0].id }) .expect(status.CREATED) .end((err, res: SuperTestResponse<CreateRegistrationResponseDto>) => { if (err) { return done(err); } troop2Registrations.push(res.body.registration.id); return cb(); }); }, (err) => { done(err); }); }); test('should contain the correct registrations', (done) => { request.get('/api/events/' + events[0].id + '/registrations') .set('Authorization', generatedUsers.admin.token) .expect(status.OK) .end((err, res: SuperTestResponse<ScoutRegistrationResponseDto>) => { if (err) { return done(err); } expect(res.body).to.have.lengthOf(10); return done(); }); }); }); }); }); }); <file_sep>/src/server/models/currentEvent.model.ts import { Table, Model, ForeignKey, BelongsTo } from 'sequelize-typescript'; import { Event } from '@models/event.model'; @Table({ underscored: true, freezeTableName: true, tableName: 'CurrentEvent' }) export class CurrentEvent extends Model<CurrentEvent> { @ForeignKey(() => Event) public event_id: string; @BelongsTo(() => Event) public event: Event; } <file_sep>/src/server/models/badge.model.ts import { Model, Table, Sequelize, Column, Unique, NotEmpty, DataType, BelongsToMany } from 'sequelize-typescript'; import { Offering } from '@models/offering.model'; import { Event } from '@models/event.model'; import { BadgeInterface } from '@interfaces/badge.interface'; @Table({ underscored: true, indexes: [ { unique: true, fields: [Sequelize.fn('lower', Sequelize.col('name')) as any] } ], tableName: 'Badges' }) export class Badge extends Model<Badge> implements BadgeInterface { @NotEmpty @Unique @Column({ allowNull: false, }) public name!: string; @Column({ type: DataType.TEXT }) public description: string; @Column public notes: string; @BelongsToMany(() => Event, () => Offering, 'badge_id', 'event_id') public availability: Event[]; } <file_sep>/src/server/routes/events/postEvents.ts import { Request, Response } from 'express'; import status from 'http-status-codes'; import { Event } from '@models/event.model'; import { EventResponseDto, CurrentEventResponseDto, EventOfferingInterface, CreateOfferingResponseDto } from '@interfaces/event.interface'; import { ErrorResponseDto } from '@interfaces/shared.interface'; import { CurrentEvent } from '@models/currentEvent.model'; import { Offering } from '@models/offering.model'; import { Badge } from '@models/badge.model'; import { Purchasable } from '@models/purchasable.model'; import { CreatePurchasablesResponseDto } from '@interfaces/purchasable.interface'; export const createEvent = async (req: Request, res: Response) => { try { const event: Event = await Event.create(req.body); return res.status(status.CREATED).json(<EventResponseDto>{ message: 'Event successfully created', event: event }); } catch (err) { return res.status(status.BAD_REQUEST).json(<ErrorResponseDto>{ message: 'Event creation failed', error: err }); } }; export const setCurrentEvent = async (req: Request, res: Response) => { try { const [event, currentEvent] = await Promise.all([ Event.findByPk(req.body.id), new Promise<CurrentEvent>(async (resolve) => { const dbCurrentEvent = await CurrentEvent.findOne(); if (!!dbCurrentEvent) { resolve(dbCurrentEvent); } else { resolve(await CurrentEvent.create({})); } }) ]); if (!event) { throw new Error('Event to set as current not found'); } await currentEvent.$set('event', event); return res.status(status.OK).json(<CurrentEventResponseDto>{ message: 'Current event set', currentEvent: await Event.findByPk(currentEvent.event_id) }); } catch (err) { res.status(status.BAD_REQUEST).json(<ErrorResponseDto>{ message: 'Setting current event failed', error: err }); } }; export const createOffering = async (req: Request, res: Response) => { try { const [event, badge] = await Promise.all([ Event.findByPk(req.params.id), Badge.findByPk(req.body.badge_id) ]); if (!event) { throw new Error('Event to add offering to not found'); } if (!badge) { throw new Error('Badge does not exist'); } const offering: Offering = await event.$add('offering', req.body.badge_id, { through: req.body.offering }) as Offering; if (!offering) { throw new Error('Could not create offering'); } const eventWithOffering: EventOfferingInterface = await Event.findByPk(req.params.id, { include: [{ model: Badge, as: 'offerings', through: <any>{ as: 'details' } }] }); return res.status(status.CREATED).json(<CreateOfferingResponseDto>{ message: 'Offering created successfully', event: eventWithOffering }); } catch (err) { return res.status(status.BAD_REQUEST).json(<ErrorResponseDto>{ message: 'Failed to create offering', error: err }); } }; export const createPurchasable = async (req: Request, res: Response) => { try { const purchasable: Purchasable = await Purchasable.create(req.body); let event: Event = await Event.findByPk(req.params.id); await event.$add('purchasable', purchasable); event = await Event.findByPk(req.params.id, { include: [{ model: Purchasable, as: 'purchasables' }] }); return res.status(status.CREATED).json(<CreatePurchasablesResponseDto>{ message: 'Purchasable successfully created', purchasables: event.purchasables }); } catch (err) { return res.status(status.BAD_REQUEST).json(<ErrorResponseDto>{ message: 'Failed to create purchasable', error: err }); } }; <file_sep>/src/server/routes/badges/deleteBadges.ts import { Request, Response } from 'express'; import status from 'http-status-codes'; import { Badge } from '@models/badge.model'; import { ErrorResponseDto } from '@interfaces/shared.interface'; export const deleteBadge = async (req: Request, res: Response) => { try { const badge: Badge = await Badge.findByPk(req.params.id); await badge.destroy(); return res.status(status.OK).end(); } catch (err) { return res.status(status.BAD_REQUEST).json(<ErrorResponseDto>{ message: 'Failed to delete badge', error: err }); } }; <file_sep>/src/client/src/components/administration/offerings/OfferingEditSpec.js import { shallowMount, createLocalVue } from '@vue/test-utils'; import Vuex from 'vuex'; import Vuelidate from 'vuelidate'; import chai from 'chai'; import { expect } from 'chai' import sinon from 'sinon'; import sinonChai from 'sinon-chai'; import OfferingEdit from './OfferingEdit.vue'; const localVue = createLocalVue(); localVue.use(Vuex); localVue.use(Vuelidate); chai.use(sinonChai); describe('OfferingEdit.vue', () => { let wrapper, store, actions; beforeEach(() => { actions = { deleteOffering: sinon.stub(), createOffering: sinon.stub(), updateOffering: sinon.stub() }; store = new Vuex.Store({ actions }); wrapper = shallowMount(OfferingEdit, { localVue, store, propsData: { badge: { badge_id: 2, duration: 1, periods: [2, 3], requirements: [1, 2, 3], name: 'Badge' }, eventId: '1' } }); }); it('should be a component', () => { expect(wrapper.isVueInstance()).to.be.true; }); it('should default to editing', () => { expect(wrapper.vm.creating).to.be.false; }); it('should format the list of periods', () => { expect(wrapper.vm.editablePeriods).to.equal('2, 3'); }); it('should format the list of requirements', () => { expect(wrapper.vm.editableRequirements).to.equal('1, 2, 3'); }); it('should parse edited periods', () => { wrapper.vm.editablePeriods = '1, 2, 3'; expect(wrapper.vm.offering.periods).to.deep.equal([1, 2, 3]); }); it('should parse poorly formatted edited periods', () => { wrapper.vm.editablePeriods = '1 ,2,3,'; expect(wrapper.vm.offering.periods).to.deep.equal([1, 2, 3]); }); it('should only parse 3 periods', () => { wrapper.vm.editablePeriods = '1, 2, 3, 4'; expect(wrapper.vm.offering.periods).to.deep.equal([1, 2, 3]); }); it('should parse edited requirements', () => { wrapper.vm.editableRequirements = '1, 2, 3a, 4'; expect(wrapper.vm.offering.requirements).to.deep.equal(['1', '2', '3a', '4']); }); it('should parse poorly formatted edited requirements', () => { wrapper.vm.editableRequirements = '1,2 ,3,4'; expect(wrapper.vm.offering.requirements).to.deep.equal(['1', '2', '3', '4']); }); describe('and then trying to delete the offering', () => { beforeEach(() => { wrapper.vm.deleteOffering(); }); it('should have dispatched the appropriate action', () => { expect(actions.deleteOffering).to.have.been.called; }); xit('should have called with the appropriate information', () => { expect(actions.deleteOffering).to.have.been.calledWithMatch( { eventId: '1', badgeId: 2 } ) }); }); }); <file_sep>/src/libs/interfaces/purchase.interface.ts import { RegistrationPurchasesDto } from '@interfaces/registration.interface'; import { PurchasableDto } from '@interfaces/purchasable.interface'; export enum Size { XS = 'xs', S = 's', M = 'm', L = 'l', XL = 'xl', XXL = 'xxl' } export interface PurchaseInterface { quantity?: number; size?: Size; purchasable_id?: number; registration_id?: number; } export interface CreatePurchaseRequestDto { purchasable?: number; quantity?: number; size?: Size; } export interface CreatePurchaseResponseDto { message: string; registration: RegistrationPurchasesDto; } export interface PurchaseResponseInterface { purchase?: PurchaseInterface; message?: string; } export type ScoutPurchasesResponseDto = PurchasableDto<PurchaseInterface>[]; export type BuyersResponseDto = RegistrationPurchasesDto[]; <file_sep>/src/client/src/validators/greaterThanSpec.js import { expect } from 'chai' import greaterThan from './greaterThan'; describe('The less than validator', () => { const parentVm = { number: 12 }; const emptyParentVm = {}; it('should determine if something is greater than a number', () => { expect(greaterThan('number')(13, parentVm)).to.be.true; expect(greaterThan('number')(14, parentVm)).to.be.true; }); it('should fail if the number is less', () => { expect(greaterThan('number')(11, parentVm)).to.be.false; }); it('should pass if the number is equal', () => { expect(greaterThan('number')(12, parentVm)).to.be.true; }); it('should pass if there is nothing to compare to', () => { expect(greaterThan('number')(11, emptyParentVm)).to.be.true; }); it('should pass if nothing is passed in', () => { expect(greaterThan('number')('', parentVm)).to.be.true; }); }); <file_sep>/tests/server/usersSpec.ts import supertest from 'supertest'; import * as async from 'async'; import status from 'http-status-codes'; import { expect } from 'chai'; import app from '@app/app'; import TestUtils from './testUtils'; import { SignupRequestDto, UserTokenResponseDto, UserExistsResponseDto, LoginRequestDto, UserProfileResponseDto } from '@interfaces/user.interface'; import { SuperTestResponse } from '@test/helpers/supertest.interface'; const request = supertest(app); describe('users', () => { beforeEach(async () => { await TestUtils.dropDb(); }); afterAll(async () => { await TestUtils.dropDb(); await TestUtils.closeDb(); }); describe('user account creation', () => { test('creates an account if all required info is supplied', (done) => { const postData: SignupRequestDto = { email: '<EMAIL>', password: '<PASSWORD>', firstname: 'firstname', lastname: 'lastname' }; request.post('/api/signup') .send(postData) .expect(status.CREATED, done); }); test('should return a token and the profile', (done) => { const postData: SignupRequestDto = { email: '<EMAIL>', password: '<PASSWORD>', firstname: 'firstname', lastname: 'lastname' }; request.post('/api/signup') .send(postData) .expect(status.CREATED) .end((err, res: SuperTestResponse<UserTokenResponseDto>) => { if (err) { done(err); } expect(res.body.profile.email).to.equal(postData.email); expect(res.body.profile.firstname).to.equal(postData.firstname); expect(res.body.profile.lastname).to.equal(postData.lastname); expect(res.body.profile.password).to.not.exist; expect(res.body.token).to.exist; done(); }); }); test('requires email, password, firstname, lastname', (done) => { let postData: any = {}; async.series([ (cb) => { request.post('/api/signup') .send(postData) .expect(status.BAD_REQUEST, cb); }, (cb) => { postData = { email: '<EMAIL>' }; request.post('/api/signup') .send(postData) .expect(status.BAD_REQUEST, cb); }, (cb) => { postData = { email: '<EMAIL>', password: '<PASSWORD>' }; request.post('/api/signup') .send(postData) .expect(status.BAD_REQUEST, cb); }, (cb) => { postData = { firstname: 'firstname', lastname: 'lastname' }; request.post('/api/signup') .send(postData) .expect(status.BAD_REQUEST, cb); } ], done); }); test('checks for a valid email address', (done) => { let postData: SignupRequestDto; async.series([ (cb) => { postData = { email: 'invalid', password: '<PASSWORD>', firstname: 'firstname', lastname: 'lastname' }; request.post('/api/signup') .send(postData) .expect(status.BAD_REQUEST, cb); }, (cb) => { postData = { email: 'invalid@wrong', password: '<PASSWORD>', firstname: 'firstname', lastname: 'lastname' }; request.post('/api/signup') .send(postData) .expect(status.BAD_REQUEST, cb); }, (cb) => { postData = { email: 'invalid.wrong.com', password: '<PASSWORD>', firstname: 'firstname', lastname: 'lastname' }; request.post('/api/signup') .send(postData) .expect(status.BAD_REQUEST, cb); } ], done); }); describe('when a user already exists', () => { let postData: SignupRequestDto; beforeEach((done) => { postData = { email: '<EMAIL>', password: '<PASSWORD>', firstname: 'firstname', lastname: 'lastname' }; request.post('/api/signup') .send(postData) .expect(status.CREATED, done); }); test('should know if a user exists by email', (done) => { request.get('/api/users/exists/<EMAIL>') .expect(status.OK) .end((err, res: SuperTestResponse<UserExistsResponseDto>) => { if (err) { done(err); } expect(res.body.exists).to.be.true; done(); }); }); test('should not create a duplicate user', (done) => { request.post('/api/signup') .send(postData) .expect(status.BAD_REQUEST, done); }); test('should treat email as case insensitive', (done) => { const uppercaseData: SignupRequestDto = { email: '<EMAIL>', password: '<PASSWORD>', firstname: 'firstname', lastname: 'lastname' }; request.post('/api/signup') .send(uppercaseData) .expect(status.BAD_REQUEST, done); }); }); }); describe('account authentication', () => { beforeEach((done) => { const postData: SignupRequestDto = { email: '<EMAIL>', password: '<PASSWORD>', firstname: 'firstname', lastname: 'lastname' }; request.post('/api/signup') .send(postData) .expect(status.CREATED, done); }); test('should find a user and send back a token', (done) => { request.post('/api/authenticate') .send(<LoginRequestDto>{ email: '<EMAIL>', password: '<PASSWORD>' }) .expect(status.OK, done); }); test('should not enforce case sensitivity for emails', (done) => { request.post('/api/authenticate') .send(<LoginRequestDto>{ email: '<EMAIL>', password: '<PASSWORD>' }) .expect(status.OK, done); }); test('should fail gracefully if no email is supplied', (done) => { request.post('/api/authenticate') .expect(status.UNAUTHORIZED, done); }); test('should not find a nonexistent email', (done) => { request.post('/api/authenticate') .send(<LoginRequestDto>{ email: 'dne', password: '<PASSWORD>' }) .expect(status.UNAUTHORIZED, done); }); test('should fail to authenticate without a password', (done) => { request.post('/api/authenticate') .send(<LoginRequestDto>{ email: '<EMAIL>' }) .expect(status.UNAUTHORIZED, done); }); test('should fail to authenticate with an incorrect password', (done) => { request.post('/api/authenticate') .send(<LoginRequestDto>{ email: '<EMAIL>', password: 'pwd' }) .expect(status.UNAUTHORIZED, done); }); }); describe('getting a profile with token', () => { let token: string = null; beforeEach((done) => { const postData: SignupRequestDto = { email: '<EMAIL>', password: '<PASSWORD>', firstname: 'firstname', lastname: 'lastname' }; request.post('/api/signup') .send(postData) .expect(status.CREATED) .end((err, res: SuperTestResponse<UserTokenResponseDto>) => { if (err) { done(err); } token = res.body.token; done(); }); }); test('should reply with the profile for the jwt owner', (done) => { request.get('/api/profile') .set('Authorization', token) .expect(status.OK) .end((err, res: SuperTestResponse<UserProfileResponseDto>) => { if (err) { done(err); } expect(res.body.profile.email).to.equal('<EMAIL>'); expect(res.body.profile.firstname).to.equal('firstname'); expect(res.body.profile.lastname).to.equal('lastname'); expect(res.body.profile.role).to.equal('anonymous'); done(); }); }); }); });
a32321beb6fffe178381f545f58fe0a11792dd9e
[ "JavaScript", "SQL", "TypeScript", "Markdown" ]
117
TypeScript
dmurtari/mbu-online
173b1efa433df629a689650ee07cf401fbe6693c
72ee59c65064947195725347103242da3d401ceb
refs/heads/master
<file_sep>describe('protocommerce Automation Testing', function() { it('Verify Application Navigate when url hit', function() { browser.get('https://qaclickacademy.github.io/protocommerce/'); browser.driver.manage().window().maximize(); element(by.css("a[class*='navbar-brand']")).getText().then(function(text){ console.log("Page Title: " + text); }) }) it('Verify error message when user provided invalid name', function() { browser.get('https://qaclickacademy.github.io/protocommerce/'); browser.driver.manage().window().maximize(); element(by.name("name")).sendKeys("A").then(function(){ element(by.name("email")).sendKeys("") element(by.css("[class='alert alert-danger']")).getText().then(function(text){ console.log("Invalid Name Error Message: " + text); }) }) }) it('Verify error message when user provided invalid email', function() { browser.get('https://qaclickacademy.github.io/protocommerce/'); browser.driver.manage().window().maximize(); element(by.name("email")).sendKeys("E").then(function(){ browser.sleep(5000); element(by.name("email")).clear(); browser.sleep(5000); //element(by.css("[class='alert alert-danger']")).getText().then(function(text){ // console.log("Invalid Email Error Message: " + text); //}) }) }) it('Verify Submit Form with valid details', function() { browser.get('https://qaclickacademy.github.io/protocommerce/'); browser.driver.manage().window().maximize(); element(by.name("name")).sendKeys("<NAME>"); element(by.name("email")).sendKeys("<EMAIL>"); element(by.id("exampleInputPassword1")).sendKeys("<PASSWORD>"); element(by.id("exampleCheck1")).click(); element(by.cssContainingText("[id='exampleFormControlSelect1'] option","Female")).click(); element(by.buttonText("Submit")).click().then(function(){ element(by.css("div[class*='success']")).getText().then(function(text){ console.log("Success Message : "+ text); }) }) }) //function to add product to cart function selectProduct(product){ element.all(by.tagName("app-card")).each(function(item){ item.element(by.css("h4 a")).getText().then(function(text){ if(text==product){ item.element(By.css("button[class*='btn-info']")).click(); } }) }) } it('Verify the product count added in cart', function() { browser.get('https://qaclickacademy.github.io/protocommerce/'); browser.driver.manage().window().maximize(); element(by.linkText("Shop")).click(); selectProduct("Samsung Note 8"); selectProduct("iphone X"); element(by.partialLinkText("Checkout")).getText().then(function(text){ var res=text.split("("); var x=Number(res[1].trim().charAt(0)); console.log("Total Product Added to Cart: " + x); }) }) })
1c41ef47d53f9edb48b056a689cdfda947008e37
[ "JavaScript" ]
1
JavaScript
AbhijitBiradar/Explore-Protractor
705e30309fb7e1de095d27827588c148019d216b
5529ea11d6886a4868b164bab5906efad0c0be62
refs/heads/main
<repo_name>UpputuriPriyanka/MLCOURSE-WEEK-2-<file_sep>/script.js output("p","bot","Welcome <br> Hi Nice to meet you... and what is your name"); var user_input=document.getElementById("input") user_input.addEventListener("click",function loadDoc() { var xhttp = new XMLHttpRequest(); try{ xhttp.onreadystatechange = function() { if (this.readyState == 4 && this.status == 200) { var data= JSON.parse(this.responseText); var msg=document.getElementById("inp").value; document.getElementById("inp").value=""; output("p","user",msg); if(msg=="Hi" || msg=="hi" || msg=="hy" || msg=="Hy" || msg=='kumar' || msg=='priyanka') { output("p","bot",get_timeofday_greeting()+","+Greeting()+"<br>"+data["menu"]); } else if(msg.length==1) { if(data[msg]){ output("p","bot",data[msg]); if(msg=="3"){ output("p","image","<img style='margin-top:10px; margin-left:140px; width:400px; height:300px;' src='https://thumbs.dreamstime.com/b/white-stone-words-thank-you-smile-face-color-glitter-boke-background-117350639.jpg'>"); output("p","bot","Say hi to restart the bot"); } } else{ output("p","bot","Plz enter only a number [1-3]"); } } else if(msg.includes("calculate")){ evaluator(msg.split(" ")[1]); } else if(msg.includes("moviename")) { movie(msg.split(" ")[1].trim()) } else if(msg.includes("back")){ output("p","bot",data["menu"]); } else{ output("p","bot","Sorry I didnt get that"); } } }; xhttp.open("GET", "jsondata.json", true); xhttp.send(); } catch(e){ output("p","bot","Sorry I didnt get that"); } } ); function output(tag,className,text){ var reply= document.getElementById("main") if(className=="bot"){ reply.innerHTML+=`<img class="bot_image" src="https://www.logo.bot/img/landing/logobot_3d_banner.png">`; } if(className=="user"){ reply.innerHTML+=`<img class="user_image" src="https://encrypted-tbn0.gstatic.com/images?q=tbn%3AANd9GcTf5gL1EHaQMtnT7V1GhQnHATVtBQ0mQK8EYg&usqp=CAU">`; } if(className=="image"){ reply.innerHTML+=`<img class="bot_image" src="https://www.logo.bot/img/landing/logobot_3d_banner.png">`; } reply.innerHTML+=`<${tag} class=${className}>${text}</${tag}>` } function Greeting(){ res=[" Nice to see you. I can provide the following options for you", " Its a pleasure chatting with you. Here are the options I can provide you"]; return res[Math.floor((Math.random() * res.length))]; } function get_timeofday_greeting(){ var date = new Date(); var current_time = date.getHours(); let timeofday_greeting ="Good Morning" if(current_time>21) timeofday_greeting ="Good Night" else if(current_time>16) timeofday_greeting ="Good Evening" else if(current_time>=12) timeofday_greeting ="Good AfterNoon" return timeofday_greeting ; } function evaluator(expression){ output("p","image","<img style='margin-top:10px; margin-left:140px; width:400px; height:300px;' src='https://www.wikihow.com/images/0/01/Improve-Your-Mathematical-Calculation-Skills-Step-7.jpg'>"); try{ output("p","bot","Result of the expression:"+eval(expression)); output("p","bot","If you want to calculate another expression enter the expression as 'calculate 1+2' or "+"<br>"+ "enter back") } catch(e){ output("p","bot","Enter a valid expression"); } } function movie(moviename) { fetch('https://www.omdbapi.com/?t='+moviename+'&apikey=cdd20ef2') .then(response => response.json()) .then(mdata => { console.log(mdata['name']); output("p","image","<img style='margin-top:10px; margin-left:140px; width:400px; height:300px;' src='https://image.shutterstock.com/image-illustration/raster-version-cinematograph-concept-banner-260nw-1697799442.jpg'>"); output("p","bot","**** This is the movies list information in " +"****"+mdata['Title']+"****"+"<br>" +"Year : "+mdata['Year']+"<br>"+"Rated : "+mdata['Rated']+"<br>"+"Released : "+mdata['Released']+"<br>"+"Director:"+mdata['Director']+"<br>"+"Country:"+mdata['Country']+"<br>"+"Awards:"+mdata['Awards']); output("p","bot","If you want to know the another movies please enter the movie name as 'movie moviename' or "+"<br>"+ "enter back") }) .catch(err => { output("p","bot","Please enter correct movie name"); input.value=""; return 0; }); } <file_sep>/README.md # MLCOURSE-WEEK-2 We have done this project in a team of two members. * COLLABORATORS: 1. 18pa1a05g3-<NAME> 2. 19pa1a05i2-<NAME> * OBJECTIVE: It provides list of movies information and calculates the Expression. * DESCRIPTION: 1. Firstly, It greet the User and asks the name of a user. 2. After it welcomes the user and asks how to help the user. 3. Next it offer choices and asks to pick one of the choices based upon user requirement. # Calculate a expression: *If users picks option 1 ... then it asks user to enter a expression *After it will calculate the expression. # List of Information about movies *If users pick the option 2 ... then it asks User to enter a Movie. *After it gives the information about that movie. #End the bot *If users pick the otion 3......then it ends. *Finally Ends chat....when User choose to end chatbot. Links of Our Bot: * REPL Code LINK:https://repl.it/@VadlamuriKumar/DeepskyblueGrizzledTraining#index.html * REPL demo LINK:https://deepskybluegrizzledtraining.vadlamurikumar.repl.co/ * YOUTUBE LINK: https://youtu.be/MYanlF9C3PM
807c724b7a4c53cd2895df8b2bdc62ad6baac318
[ "JavaScript", "Markdown" ]
2
JavaScript
UpputuriPriyanka/MLCOURSE-WEEK-2-
8af6a191f353812c841c885726635207c9014c89
4e6aaa17bd3ab2d21170c63c1d1128740a5ac162
refs/heads/master
<file_sep>// jshint devel:true ; (function($){ $(document).ready(function(){ $('.btn-side-nav').on('click', function(e){ e.preventDefault(); $('.side-nav-wrap').addClass('active'); }); $('.side-nav-wrap .btn-back').on('click', function(e){ e.preventDefault(); $('.side-nav-wrap').removeClass('active'); }) }); })(jQuery);
d6c0d8e5dee1afc598a34e9555fb8f616cdc144c
[ "JavaScript" ]
1
JavaScript
luxiangrong/beijingxiehe_sp
20fa8fb14c5bc8eb833d51da28b16ff3b710e87f
65d7ccc3ccf73b23ee752a59030179dad10efdae
refs/heads/master
<file_sep>package saco.ProjectFireTruckV2.Handlers; import android.graphics.Bitmap; import android.os.Handler; import android.os.Message; import saco.ProjectFireTruckV2.Activities.ChatActivity; import saco.ProjectFireTruckV2.Activities.MainActivity; import saco.ProjectFireTruckV2.Activities.PhotoActivity; import saco.ProjectFireTruckV2.R; import saco.ProjectFireTruckV2.StaticFiles.TCPSocket; import static saco.ProjectFireTruckV2.Activities.MainActivity.chatButton; import static saco.ProjectFireTruckV2.Activities.MainActivity.connectButton; import static saco.ProjectFireTruckV2.Activities.MainActivity.connectThread; import static saco.ProjectFireTruckV2.Activities.MainActivity.failedConnectProcedure; import static saco.ProjectFireTruckV2.Activities.MainActivity.mToast; import static saco.ProjectFireTruckV2.Activities.MainActivity.readThread; import static saco.ProjectFireTruckV2.Activities.MainActivity.sendImageButton; import static saco.ProjectFireTruckV2.Activities.MainActivity.toastImage; /** * Created by PMGC37 on 1/28/2016. */ public class MainHandler { //Constants to indicate if connection is established public static final int CONNECTED = 1; public static final int CONNECTING = 2; public static final int FAILED_CONNECT = 3; public static final int DISCONNECTED = 4; public static final int SEND_SUCCESSFUL = 5; public static final int HEADER_ACKNOWLEDGED = 6; public static final int RECEIVED_IMAGE = 7; //Handler to handle object or message parsed from other thread in order to make changes in the main UI thread public static Handler mainHandler = new Handler(){ @Override public void handleMessage(Message msg) { super.handleMessage(msg); switch (msg.what){ case CONNECTED: connectButton.setImageResource(R.drawable.wifi_connected); connectButton.setEnabled(true); mToast.setText("Connected"); mToast.show(); chatButton.setEnabled(true); sendImageButton.setEnabled(true); break; case CONNECTING: connectButton.setImageResource(R.drawable.wifi_connecting); mToast.setText("Connecting"); mToast.show(); break; case FAILED_CONNECT: connectButton.setImageResource(R.drawable.wifi_notconnected); mToast.setText("Failed to connect\n" + "Ensure server is ready to accept socket\n" + "Or select new device"); mToast.show(); TCPSocket.setSocket(null); connectButton.setEnabled(true); if (connectThread!= null) { connectThread.interrupt(); connectThread = null; } failedConnectProcedure(); break; case DISCONNECTED: connectButton.setImageResource(R.drawable.wifi_notconnected); connectButton.setEnabled(true); mToast.setText("Disconnected"); mToast.show(); TCPSocket.setSocket(null); if (connectThread!= null) { connectThread.interrupt(); connectThread = null; } if (readThread != null){ readThread.interrupt(); readThread = null; } chatButton.setEnabled(false); sendImageButton.setEnabled(false); if (PhotoActivity.photoActivityState == true){ PhotoActivity.photoActivity.finish(); } if (ChatActivity.chatPageActive == true){ ChatActivity.chatActivity.finish(); } break; case SEND_SUCCESSFUL: mToast.setText("Sent successfully" + "\n" + "in " + String.format("%.3f",(double)msg.obj) + " seconds"); mToast.show(); if (PhotoActivity.photoActivityState == true) { PhotoActivity.changeSendButtonState("enabledTrue"); } break; case RECEIVED_IMAGE: MainActivity.toastForText.cancel(); toastImage.setImageBitmap((Bitmap) msg.obj); MainActivity.toastForImage.show(); break; case HEADER_ACKNOWLEDGED: break; default: mToast.setText("Acknowledged"); mToast.show(); break; } } }; } <file_sep>package saco.ProjectFireTruckV2.etc_utilities; import android.Manifest; import android.app.Activity; import android.content.Context; import android.content.pm.PackageManager; import android.support.v4.app.ActivityCompat; import android.support.v4.content.ContextCompat; import android.util.Log; /** * Created by ftjx73 on 1/28/2016. */ public class PermissionCheck { private static boolean STORAGE_PERMISSION = false; private static boolean CAMERA_PERMISSION = false; private static int PermissionCheck; public static void permissionCheckStorage(Context context, Activity activity) { // Here, thisActivity is the current activity if (ContextCompat.checkSelfPermission(context, Manifest.permission.WRITE_EXTERNAL_STORAGE)!= PackageManager.PERMISSION_GRANTED){ Log.i("myactivity", "trying to request for permission"); ActivityCompat.requestPermissions(activity, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, PermissionCheck); } else STORAGE_PERMISSION = true; } public static void permissionCheckCamera(Context context, Activity activity) { // Here, thisActivity is the current activity if (ContextCompat.checkSelfPermission(context, Manifest.permission.CAMERA)!= PackageManager.PERMISSION_GRANTED){ Log.i("myactivity", "trying to request for permission"); ActivityCompat.requestPermissions(activity, new String[]{Manifest.permission.CAMERA}, PermissionCheck); } else CAMERA_PERMISSION = true; } public static boolean getCameraPermisson(){ return CAMERA_PERMISSION; } public static boolean getStoragePermisson(){ return STORAGE_PERMISSION; } } <file_sep>package saco.ProjectFireTruckV2.Activities; import android.app.Activity; import android.content.Intent; import android.os.Bundle; import android.text.method.PasswordTransformationMethod; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.TextView; import saco.ProjectFireTruckV2.R; public class PasswordActivity extends Activity { private TextView text; private Button connect; private EditText editText; private String networkSSID = null; private String networkPass = null; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_password); setTitle("Enter Password: "); initialise(); clicksListener(); } public void initialise(){ text = (TextView)findViewById(R.id.textView15); connect = (Button)findViewById(R.id.button8); editText = (EditText)findViewById(R.id.editText3); editText.setTransformationMethod(PasswordTransformationMethod.getInstance()); Intent intent = getIntent(); networkSSID = intent.getExtras().getString("ssid"); text.setText("Network SSID: " + networkSSID); } public void clicksListener(){ connect.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { networkPass = String.valueOf(editText.getText()); Intent intent = new Intent(); intent.putExtra("password",networkPass); setResult(RESULT_OK,intent); finish(); } }); } } <file_sep>package saco.ProjectFireTruckV2.etc_utilities; import android.content.Context; import android.util.Log; import java.io.BufferedReader; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.OutputStreamWriter; import java.text.SimpleDateFormat; import java.util.Calendar; import saco.ProjectFireTruckV2.StaticFiles.IPAddress; /** * Created by ftjx73 on 1/8/2016. */ public class ReadWrite { public static synchronized String readFromFile(Context context, String file) { String ret = ""; try { InputStream inputStream = context.openFileInput(file); if ( inputStream != null ) { InputStreamReader inputStreamReader = new InputStreamReader(inputStream); BufferedReader bufferedReader = new BufferedReader(inputStreamReader); String receiveString = ""; StringBuilder stringBuilder = new StringBuilder(); while ( (receiveString = bufferedReader.readLine()) != null ) { stringBuilder.append(receiveString +"\n"); } inputStream.close(); ret = stringBuilder.toString(); } } catch (FileNotFoundException e) { Log.e("login activity", "File not found: " + e.toString()); } catch (IOException e) { Log.e("login activity", "Can not read file: " + e.toString()); } return ret; } public static synchronized void writeToFile(String data, Context context, String mode, String file) { switch (mode){ case "Replace": try { OutputStreamWriter outputStreamWriter = new OutputStreamWriter(context.openFileOutput(file, Context.MODE_PRIVATE)); outputStreamWriter.write(data); outputStreamWriter.close(); } catch (IOException e) { Log.e("Exception", "File write failed: " + e.toString()); } break; case "Append": try { OutputStreamWriter outputStreamWriter = new OutputStreamWriter(context.openFileOutput(file, Context.MODE_PRIVATE | Context.MODE_APPEND)); outputStreamWriter.write(data); outputStreamWriter.close(); } catch (IOException e) { Log.e("Exception", "File write failed: " + e.toString()); } break; } } public static synchronized void storeData(Context context, String fileName, String type, String file){ String timeStamp = new SimpleDateFormat("yyyy/MM/dd_HH:mm:ss").format(Calendar.getInstance().getTime()); writeToFile(">> " + type + "\r\n", context, "Append",file); writeToFile(fileName + "\r\n", context, "Append",file); writeToFile("Delivered: " + timeStamp + "\r\n", context, "Append",file); writeToFile("To IP Address: "+ IPAddress.getIP()+"\r\n",context,"Append",file); writeToFile("\r\n", context, "Append",file); } } <file_sep>package saco.ProjectFireTruckV2.Activities; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.content.IntentFilter; import android.net.ConnectivityManager; import android.net.NetworkInfo; import android.net.wifi.ScanResult; import android.net.wifi.WifiConfiguration; import android.net.wifi.WifiInfo; import android.net.wifi.WifiManager; import android.os.Bundle; import android.os.CountDownTimer; import android.support.v7.app.AppCompatActivity; import android.util.Log; import android.view.View; import android.view.View.OnClickListener; import android.widget.AdapterView; import android.widget.Button; import android.widget.ListView; import android.widget.Toast; import java.util.List; import saco.ProjectFireTruckV2.R; import saco.ProjectFireTruckV2.list_adapters.WifiActivity_listAdapter; public class WifiActivity extends AppCompatActivity { public static int connectedPosition = 99; private static final int REQUEST_WIFI = 1; private ListView listView; private WifiActivity_listAdapter<String> listAdapter; private WifiManager wifi; private String[] wifis; private WifiScanReceiver wifiReceiver; private String networkSSID; private String networkPass; private int itemPos; private Button scan; private int count = 0; private ConnectivityManager connManager; private NetworkInfo mWifi; List<WifiConfiguration> configurationList; private String filteredString; private String filteredConfig; private Toast mToast; private WifiInfo wInfo; private BroadcastReceiver broadcastReceiver = new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { String action = intent.getAction(); if (action.equals(WifiManager.NETWORK_STATE_CHANGED_ACTION)) { NetworkInfo networkInfo = intent.getParcelableExtra(WifiManager.EXTRA_NETWORK_INFO); if(networkInfo.isConnected()){ connectedPosition = 99; //reset connectedPosition listAdapter.clear(); retrieveConfig(); wifi.startScan(); }else if(networkInfo.getDetailedState() == NetworkInfo.DetailedState.FAILED){ mToast.setText("Connection Failed"); mToast.show(); Log.e("BC","Connecton Failed"); } } } }; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_wifi); setTitle("Connect to a Network:"); initialise(); retrieveConfig(); scanForWifi(); clicksListener(); } @Override protected void onDestroy() { super.onDestroy(); unregisterReceiver(broadcastReceiver); } public void initialise(){ mToast = Toast.makeText(getApplicationContext(), "", Toast.LENGTH_SHORT); scan = (Button)findViewById(R.id.button9); listView = (ListView)findViewById(R.id.listView3); listAdapter = new WifiActivity_listAdapter<>(this,android.R.layout.simple_list_item_1); listView.setAdapter(listAdapter); wifi = (WifiManager)getSystemService(Context.WIFI_SERVICE); wifiReceiver = new WifiScanReceiver(); connManager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE); IntentFilter intentFilter = new IntentFilter(); intentFilter.addAction(WifiManager.NETWORK_STATE_CHANGED_ACTION); registerReceiver(broadcastReceiver, intentFilter); } public void retrieveConfig(){ configurationList = wifi.getConfiguredNetworks(); mWifi = connManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI); if(mWifi.isConnected()){ wInfo = wifi.getConnectionInfo(); for(int i=0;i<configurationList.size();i++){ filteredString = configurationList.get(i).SSID; if(filteredString.equals(wInfo.getSSID())) { listAdapter.add(filteredString.replaceAll("\"", "") + "\n" + "Connected"); connectedPosition = i; }else{ listAdapter.add(filteredString.replaceAll("\"", "") + "\n" + "Saved, Secured"); } } }else { for (int i = 0; i < configurationList.size(); i++) { filteredString = configurationList.get(i).SSID; listAdapter.add(filteredString.replaceAll("\"", "") + "\n" + "Saved, Secured"); } } } public void clicksListener(){ listView.setOnItemClickListener(new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { if(listAdapter.getItem(position).contains("\n"+"Saved, Secured")){ networkSSID = configurationList.get(position).SSID; mToast.setText("Attempting connection to " + networkSSID); mToast.show(); connectedPosition = 99; //reset the position int netId = configurationList.get(position).networkId; wifi.disconnect(); wifi.enableNetwork(netId, true); wifi.reconnect(); listAdapter.clear(); listView.setAdapter(listAdapter); retrieveConfig(); wifi.startScan(); }else if(listAdapter.getItem(position).contains("\n"+"Connected")){ mToast.setText("Already connected to "+listAdapter.getItem(position).replaceAll("\n"+"Connected","")); mToast.show(); }else{ Intent intent = new Intent(getApplicationContext(), PasswordActivity.class); networkSSID = listAdapter.getItem(position); intent.putExtra("ssid", networkSSID); startActivityForResult(intent, REQUEST_WIFI); itemPos = position; } } }); scan.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { connectedPosition = 99; //reset connectedPosition listAdapter.clear(); listView.setAdapter(listAdapter); retrieveConfig(); wifi.startScan(); } }); } public void scanForWifi(){ connectedPosition = 99; //reset connectedPosition wifi.startScan(); scanTimeout(7); } public void scanTimeout(final int sec){ new CountDownTimer(1000, 1000) { @Override public void onTick(long millisUntilFinished) {} @Override public void onFinish() { count++; if (count != sec) { scanTimeout(sec); } else { count = 0; } } }.start(); } @Override protected void onResume() { registerReceiver(wifiReceiver, new IntentFilter(WifiManager.SCAN_RESULTS_AVAILABLE_ACTION)); super.onResume(); } @Override protected void onPause() { unregisterReceiver(wifiReceiver); super.onPause(); } private class WifiScanReceiver extends BroadcastReceiver { public void onReceive(Context c, Intent intent) { List<ScanResult> wifiScanList = wifi.getScanResults(); wifis = new String[wifiScanList.size()]; for(int i = 0; i < wifiScanList.size(); i++){ wifis[i] = ((wifiScanList.get(i)).SSID.toString()); if(wifis[i].equals("")){ wifis[i] = "Null"; } if(filterResults(wifis[i])==false && wifis[i]!=null) { listAdapter.add(wifis[i]); } } } } public boolean filterResults(String ssid){ for(int i=0;i<listAdapter.getCount();i++){ filteredConfig = listAdapter.getItem(i); if(listAdapter.getItem(i).equals(ssid) || filteredConfig.replaceAll("\n"+"Saved, Secured","").equals(ssid) || filteredConfig.replaceAll("\n"+"Connected","").equals(ssid)){ return true; } } return false; } @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); if(requestCode == REQUEST_WIFI){ if(resultCode == RESULT_OK){ String password = data.getStringExtra("password"); networkPass = <PASSWORD>; networkSSID = listAdapter.getItem(itemPos); connectWifi(); } } } public void connectWifi(){ WifiConfiguration wc = new WifiConfiguration(); wc.SSID = String.format("\"%s\"", networkSSID); wc.preSharedKey = String.format("\"%s\"",networkPass); int nedID = wifi.addNetwork(wc); wifi.disconnect(); wifi.enableNetwork(nedID, true); wifi.reconnect(); mWifi = connManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI); } @Override public void onBackPressed() { setResult(RESULT_OK); finish(); } } <file_sep>package saco.ProjectFireTruckV2.StaticFiles; /** * Created by pmgc37 on 1/27/2016. */ public class IPAddress { public static String SERVERIP = ""; //your computer IP address public static int SERVERPORT = 4001; public static String TEMPIP = null; //your temp computer IP address public static synchronized void setIP(String IP){ SERVERIP = IP; return; } public static synchronized String getIP(){ return SERVERIP; } public static synchronized int getServerport() {return SERVERPORT; } public static synchronized void setServerport(int ServerPort){ SERVERPORT = ServerPort; return; } public static synchronized void setTempIP(String IP) { TEMPIP = IP; return; } public static synchronized String getTempIP(){ return TEMPIP; } } <file_sep>package saco.ProjectFireTruckV2.etc_utilities; import android.app.Activity; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.content.IntentFilter; import android.os.Bundle; import android.view.Window; import saco.ProjectFireTruckV2.R; public class Loading extends Activity { BroadcastReceiver broadcast_reciever = null; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); getWindow().requestFeature(Window.FEATURE_ACTION_BAR); getActionBar().hide(); setContentView(R.layout.activity_loading); waitForBroadcast(); } private void waitForBroadcast() { broadcast_reciever = new BroadcastReceiver() { @Override public void onReceive(Context arg0, Intent intent) { String action = intent.getAction(); if (action.equals("finish_activity")) { finish(); } } }; registerReceiver(broadcast_reciever, new IntentFilter("finish_activity")); } @Override protected void onDestroy() { super.onDestroy(); unregisterReceiver(broadcast_reciever); } @Override public void onBackPressed() { } } <file_sep>package saco.ProjectFireTruckV2.etc_utilities; import android.util.Log; import java.nio.ByteBuffer; import java.nio.ByteOrder; import saco.ProjectFireTruckV2.Activities.MainActivity; /** * Created by PMGC37 on 1/28/2016. */ public class Tools { private static int count_1000; public static void printBytes(byte[] protocolPacket) { printBytes(protocolPacket,protocolPacket.length); } public static void printBytes(byte[] protocolPacket, int printLimit) { if (MainActivity.DEBUG_MODE == MainActivity.DEBUG_OFF){ return; } int bufferSize = printLimit; System.out.print("Printing BytePacket of size: " + String.valueOf(bufferSize)); System.out.println(); System.out.print("Byte content: \n"); count_1000 = 0; for (int i = 0; i< bufferSize; i++){ count_1000 ++; if (count_1000>1000){ System.out.print("\n"); count_1000 = 0; } System.out.print(Integer.toHexString(protocolPacket[i] & 0xFF | 0x100).substring(1)); if (Integer.toHexString(protocolPacket[i] & 0xFF | 0x100)== "\0"){ break; } } System.out.print("\n.\n.\n.\n"); } public static byte[] longToBytes(long integer, int size){ ByteBuffer bytesBuffer = ByteBuffer.allocate(8).order(ByteOrder.BIG_ENDIAN).putLong(integer); byte[] bytes = bytesBuffer.array(); byte[] byteTruncated = new byte[size]; for (int count = 0; count<size; count++){ byteTruncated[count] = bytes[bytes.length-(size-count)]; } return byteTruncated; } public static byte[] hexToBytes(String hexString, int size){ int intFromString= Integer.parseInt(hexString, 16); byte[] byteTruncated = longToBytes(intFromString, size); return byteTruncated; } public static void debug(String tag, String msg){ if (MainActivity.DEBUG_MODE == MainActivity.DEBUG_STANDARD){ Log.d(tag,msg); } else if (MainActivity.DEBUG_MODE == MainActivity.DEBUG_AS_ERROR){ Log.e(tag,msg); } } } <file_sep>package saco.ProjectFireTruckV2.ConfirmationPopUps; import android.app.Activity; import android.content.Intent; import android.os.Bundle; import android.view.View; import android.widget.Button; import android.widget.TextView; import saco.ProjectFireTruckV2.Activities.SetIPActivity; import saco.ProjectFireTruckV2.R; /** * Created by PMGC37 on 1/29/2016. */ public class RequestDeleteIPActivity extends Activity { private TextView text; private Button yes; private Button no; private String retrievedItem; private int RequestCode; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_popup); initialise(); clicksListener(); } public void initialise(){ setTitle("Delete IP Address"); yes = (Button)findViewById(R.id.button6); no = (Button)findViewById(R.id.button7); text = (TextView)findViewById(R.id.textView14); Intent intent = getIntent(); retrievedItem = intent.getExtras().getString("item"); RequestCode = intent.getExtras().getInt("RequestCode"); if (RequestCode == SetIPActivity.SINGLE_ITEM_DELETE) { text.setText("Are you sure you want to delete device with IP address:\n" + retrievedItem + "\n"); } else if (RequestCode == SetIPActivity.CLEAR_LIST){ text.setText("Are you sure you want to clear the list?"); } } public void clicksListener(){ no.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { finish(); } }); yes.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent intent = new Intent(); if (RequestCode == SetIPActivity.SINGLE_ITEM_DELETE) { intent.putExtra("items", retrievedItem); setResult(SetIPActivity.RESULT_OK, intent); } else if (RequestCode == SetIPActivity.CLEAR_LIST){ setResult(SetIPActivity.RESULT_OK, intent); } finish(); } }); } } <file_sep>package saco.ProjectFireTruckV2.TCP; import android.os.SystemClock; import android.util.Log; import java.io.BufferedOutputStream; import java.io.IOException; import java.io.OutputStream; import saco.ProjectFireTruckV2.Activities.MainActivity; import saco.ProjectFireTruckV2.Handlers.MainHandler; import saco.ProjectFireTruckV2.StaticFiles.MotoProtocol; import saco.ProjectFireTruckV2.StaticFiles.TCPSocket; import saco.ProjectFireTruckV2.StaticFiles.TransactionID; import saco.ProjectFireTruckV2.etc_utilities.Tools; /** * Created by PMGC37 on 1/28/2016. */ public class SendMessage { public static String ACK = ""; private final static String RESET = ""; private static final String REQUEST = "Request"; private static final String REPLY = "Reply"; private static final String ACKNOWLEDGED = "Acknowledged"; private static final String RECEIVED = "Received"; private static int timeOutCounter = 0; static long tStart; static long tStartContent; static long tEnd; static long tDelta; static double initialFileHeaderElapsedTimeInSeconds; static double contentReceivedElapsedTimeInSeconds; static double totalElapsedTimeInSeconds; public static boolean SendAsRequest(byte[] Content, String fileName){ tStart = SystemClock.uptimeMillis(); byte[] protocolPacket = null; Tools.debug("SendMessage.java", "Filename being sent is: " + fileName); protocolPacket = MotoProtocol.fileHeaderDynamicPacket(fileName, Content.length, 0, REQUEST); Tools.debug("SendMessage.java", "Sending FileHeaderRequest packet"); Tools.printBytes(protocolPacket); sendMessage(protocolPacket); while (ACK != ACKNOWLEDGED){ SystemClock.sleep(100); timeOutCounter++; if (timeOutCounter > 10){ if (MainActivity.connectThread != null) { MainActivity.connectThread.interrupt(); MainActivity.connectThread = null; } timeOutCounter = 0; ACK = RESET; return false; } } timeOutCounter = 0; if (ACK == ACKNOWLEDGED) { tStartContent = SystemClock.uptimeMillis(); protocolPacket = MotoProtocol.contentTransfer(Content, TransactionID.getTransactionID(),REQUEST); Tools.debug("SendMessage.java", "Sending ContentRequest packet with Transaction ID: " + String.valueOf(TransactionID.getTransactionID())); Tools.printBytes(protocolPacket); sendMessage(protocolPacket); while (ACK != RECEIVED){ SystemClock.sleep(100); timeOutCounter++; if (timeOutCounter > 150){ Tools.debug("SendMessage.java", "Sending time out reached, closing the socket"); if (MainActivity.connectThread != null) { MainActivity.connectThread.interrupt(); MainActivity.connectThread = null; } timeOutCounter = 0; ACK = RESET; return false; } } timeOutCounter = 0; ACK = RESET; } ACK = RESET; return true; } public static boolean SendAsReply(byte[] Content, String fileName){ byte[] protocolPacket = null; Tools.debug("SendMessage.java", "Filename being sent is: " + fileName); protocolPacket = MotoProtocol.fileHeaderDynamicPacket(fileName, Content.length, 0, REQUEST); Tools.debug("SendMessage.java", "Sending FileHeaderRequest packet"); Tools.printBytes(protocolPacket); sendMessage(protocolPacket); while (ACK != ACKNOWLEDGED){ SystemClock.sleep(100); timeOutCounter++; if (timeOutCounter > 10){ if (MainActivity.connectThread != null) { MainActivity.connectThread.interrupt(); MainActivity.connectThread = null; } timeOutCounter = 0; ACK = RESET; return false; } } timeOutCounter = 0; if (ACK == ACKNOWLEDGED) { protocolPacket = MotoProtocol.contentTransfer(Content, TransactionID.getTransactionID(),REQUEST); Tools.debug("SendMessage.java", "Sending ContentRequest packet with Transaction ID: " + String.valueOf(TransactionID.getTransactionID())); Tools.printBytes(protocolPacket); sendMessage(protocolPacket); while (ACK != RECEIVED){ SystemClock.sleep(100); timeOutCounter++; if (timeOutCounter > 150){ Tools.debug("SendMessage.java", "Sending time out reached, closing the socket"); if (MainActivity.connectThread != null) { MainActivity.connectThread.interrupt(); MainActivity.connectThread = null; } timeOutCounter = 0; ACK = RESET; return false; } } timeOutCounter = 0; ACK = RESET; } ACK = RESET; return true; } /** * Sends the message entered by client to the server * @param message text entered by client */ private static boolean sendMessage(byte[] message){ OutputStream out = null; try { out = new BufferedOutputStream(TCPSocket.getSocket().getOutputStream()); } catch (IOException e) { e.printStackTrace(); } try { out.write(message); return true; }catch (IOException e){ e.printStackTrace(); Log.e("TCP", "FAILED to send message"); MainActivity.mainHandler.obtainMessage(MainHandler.FAILED_CONNECT).sendToTarget(); return false; } finally { try { out.flush(); } catch (IOException e) { e.printStackTrace(); } } } } <file_sep>package saco.ProjectFireTruckV2.TCP; import android.util.Log; import java.io.IOException; import java.net.InetSocketAddress; import java.net.ServerSocket; import java.net.Socket; import saco.ProjectFireTruckV2.Activities.MainActivity; import saco.ProjectFireTruckV2.StaticFiles.IPAddress; import saco.ProjectFireTruckV2.StaticFiles.TCPSocket; /** * Created by pmgc37 on 1/27/2016. */ public class ServerThread implements Runnable { private Socket socket; private boolean ThreadActive = true; public void run() { if (TCPSocket.getSocket() == null) { try { MainActivity.serverSocket = new ServerSocket(); MainActivity.serverSocket.setReuseAddress(true); MainActivity.serverSocket.bind(new InetSocketAddress(IPAddress.getServerport())); while (!Thread.currentThread().isInterrupted() && ThreadActive==true) { try { socket = MainActivity.serverSocket.accept(); TCPSocket.setSocket(socket); MainActivity.connectThread = new Thread(new ConnectThread()); MainActivity.connectThread.start(); } catch (IOException e) { e.printStackTrace(); } } } catch (IOException e) { e.printStackTrace(); } finally { Log.d("ServerThread","Thread is interrupted, cancelling..."); cancel(); } } } public void cancel(){ Thread.currentThread().interrupt(); ThreadActive = false; if (MainActivity.serverSocket != null) { try { MainActivity.serverSocket.close(); } catch (IOException e) { e.printStackTrace(); } } } }<file_sep>package saco.ProjectFireTruckV2.Activities; import android.app.Activity; import android.content.Context; import android.content.Intent; import android.os.Bundle; import android.os.CountDownTimer; import android.os.SystemClock; import android.util.Log; import android.util.TypedValue; import android.view.View; import android.widget.AdapterView; import android.widget.ArrayAdapter; import android.widget.Button; import android.widget.EditText; import android.widget.ListView; import android.widget.TextView; import android.widget.Toast; import java.io.BufferedReader; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import saco.ProjectFireTruckV2.ConfirmationPopUps.RequestDeleteIPActivity; import saco.ProjectFireTruckV2.R; import saco.ProjectFireTruckV2.StaticFiles.IPAddress; import saco.ProjectFireTruckV2.StaticFiles.TCPSocket; import saco.ProjectFireTruckV2.etc_utilities.IPAddressKeyListener; import saco.ProjectFireTruckV2.etc_utilities.ReadWrite; public class SetIPActivity extends Activity { //Variables for IP addresses private String IP; private TextView IPaddress; private ListView listView; private ArrayAdapter<String> listAdapter; private EditText text; private Button add; private Button clearAll; public static final int SINGLE_ITEM_DELETE = 100; public static final int CLEAR_LIST = 50; public static boolean setIPActivityState = false; /** * Create activity on start up * @param savedInstanceState */ @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_ip_page); setTitle("IP address"); initialise(); clicksListener(); } @Override protected void onStart() { super.onStart(); setIPActivityState = true; } @Override protected void onStop() { super.onStop(); setIPActivityState = false; } /** * Function to initialise variables and get IP addresses from server */ public void initialise(){ text = (EditText)findViewById(R.id.editText2); add = (Button)findViewById(R.id.button2); clearAll = (Button)findViewById(R.id.button3); listView = (ListView)findViewById(R.id.listView2); listAdapter = new ArrayAdapter<>(this,android.R.layout.simple_list_item_1); listView.setAdapter(listAdapter); IP = IPAddress.getIP(); IPaddress = (TextView)findViewById(R.id.IP_address); IPaddress.setText(IP); IPaddress.setTextSize(TypedValue.COMPLEX_UNIT_SP, 20); readFile(getApplicationContext(), "ipList.txt"); if (filterIP(IP) && !IP.equals("")) { listAdapter.add(IP); ReadWrite.writeToFile(IP + "\n", getApplicationContext(), "Append", "ipList.txt"); } } /** * Function to listen for any button clicks */ public void clicksListener(){ text.setKeyListener(IPAddressKeyListener.getInstance()); add.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { String newIP = text.getText().toString(); IPAddress.setIP(newIP); if (newIP.isEmpty()){ IPAddress.setIP(IP); Toast.makeText(getApplicationContext(), "Please enter a valid IP address", Toast.LENGTH_LONG).show(); } else { if (TCPSocket.getSocket() == null || !newIP.matches(IP)) { MainActivity.connectButton.performClick(); Toast.makeText(getApplicationContext(), "Setting IP adress ...", Toast.LENGTH_SHORT).show(); SystemClock.sleep(1000); if (TCPSocket.getSocket() != null) { if (filterIP(newIP)) { ReadWrite.writeToFile(newIP + "\n", getApplicationContext(), "Append", "ipList.txt"); listAdapter.add(newIP); waitAndFinish(1); } } else { Toast.makeText(getApplicationContext(), "IP address not reachable", Toast.LENGTH_LONG).show(); IPAddress.setIP(IP); } } else { Toast.makeText(getApplicationContext(), "Already connected", Toast.LENGTH_LONG).show(); } } } }); listView.setOnItemClickListener(new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { if(!listAdapter.getItem(position).matches(IPAddress.getIP()) || TCPSocket.getSocket()==null) { IPAddress.setTempIP(IP); IP = listAdapter.getItem(position); IPAddress.setIP(IP); MainActivity.connectButton.performClick(); SystemClock.sleep(2100); if (TCPSocket.getSocket() == null){ IP = IPAddress.getTempIP(); IPAddress.setIP(IP); } IPaddress.setText(IP); //waitAndFinish(1); }else{ Toast.makeText(getApplicationContext(),"Already Connected",Toast.LENGTH_LONG).show(); } finish(); } }); listView.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() { @Override public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) { Intent intent = new Intent(getApplicationContext(), RequestDeleteIPActivity.class); intent.putExtra("item", listAdapter.getItem(position)); intent.putExtra("RequestCode", SINGLE_ITEM_DELETE); startActivityForResult(intent, SINGLE_ITEM_DELETE); return true; } }); clearAll.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent intent = new Intent(getApplicationContext(), RequestDeleteIPActivity.class); intent.putExtra("RequestCode", CLEAR_LIST); startActivityForResult(intent, CLEAR_LIST); } }); } public boolean filterIP(String IPadd){ for(int i=0;i<listAdapter.getCount();i++){ if(IPadd.equals(listAdapter.getItem(i))) { return false; } } return true; } public void readFile(Context context, String file) { try { InputStream inputStream = context.openFileInput(file); if ( inputStream != null ) { InputStreamReader inputStreamReader = new InputStreamReader(inputStream); BufferedReader bufferedReader = new BufferedReader(inputStreamReader); String receiveString = ""; StringBuilder stringBuilder = new StringBuilder(); while ( (receiveString = bufferedReader.readLine()) != null ) { stringBuilder.append(receiveString + "\n"); if(receiveString!=null) { listAdapter.add(receiveString); Log.d("Adapter","Adding "+receiveString); } Log.d("READ", receiveString); } inputStream.close(); } } catch (FileNotFoundException e) { Log.e("login activity", "File not found: " + e.toString()); } catch (IOException e) { Log.e("login activity", "Can not read file: " + e.toString()); } } @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); debug(String.valueOf(requestCode)); if(requestCode == SINGLE_ITEM_DELETE) { if (resultCode == RESULT_OK) { debug("request code"); String retrievedItem = data.getExtras().getString("items"); debug(retrievedItem + " retrieved"); ReadWrite.writeToFile("", getApplicationContext(), "Replace", "ipList.txt"); for (int i = 0; i < listAdapter.getCount(); i++) { if (listAdapter.getItem(i).matches(retrievedItem)) { listAdapter.remove(retrievedItem); } else { debug("writing"); ReadWrite.writeToFile(listAdapter.getItem(i), getApplicationContext(), "Append", "ipList.txt"); } } } else { //do nothing } } else if (requestCode == CLEAR_LIST) { if (resultCode == RESULT_OK) { listAdapter.clear(); ReadWrite.writeToFile("", getApplicationContext(), "Replace", "ipList.txt"); } else { //do nothing } } } public void waitAndFinish(int duration){ new CountDownTimer(duration*1000, 1000) { @Override public void onTick(long millisUntilFinished) { } @Override public void onFinish() { finish(); } }.start(); } public void debug(String message){ Log.d("INFO",message); } } <file_sep>package saco.ProjectFireTruckV2.StaticFiles; /** * Created by PMGC37 on 1/28/2016. */ public class TransactionID { public static int TransactionID = 0; public static synchronized void setTransactionID(int newTransactionID){ TransactionID = newTransactionID; return; } public static synchronized int getTransactionID(){ return TransactionID; } } <file_sep>package saco.ProjectFireTruckV2.Activities; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.text.method.ScrollingMovementMethod; import android.widget.TextView; import saco.ProjectFireTruckV2.R; import saco.ProjectFireTruckV2.etc_utilities.ReadWrite; public class LogActivity extends AppCompatActivity { private String log; private TextView text; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_log); setTitle("Recent Activity"); initialise(); } public void initialise(){ text = (TextView)findViewById(R.id.textView3); text.setTextSize(15); text.setMovementMethod(new ScrollingMovementMethod()); this.log = ReadWrite.readFromFile(getApplicationContext(), "config.txt"); /* SocketHandler.writeToFile(SocketHandler.getString(),getApplicationContext()); this.log = SocketHandler.readFromFile(getApplicationContext());*/ text.setText(log); } }
c69df814088c27c11d402c7990e48674c78dbecd
[ "Java" ]
14
Java
ang-minkyii/project-firetruck
660836acd5795e55be82dbcdfea214131cc43cd0
d8b657d6eeeda1298e3d67e56c46b5f647abe837
refs/heads/master
<file_sep>def addtwo(a, b): added = a + b return added num1 = input("Enter first number: ") num2 = input("Enter second number: ") x = addtwo(num2, num1) print(x) <file_sep>age = input('enter your age:') try: a = int(age) except: a = -1 if a>0: print('good job !') else: print('not a number..') <file_sep># Pythons-stuffs master This repository contains the codes that I wrote while learning Python programming language. <NAME> master
144d21170cbe207d46a03df85a31c23e8511050a
[ "Markdown", "Python" ]
3
Python
Rehan-Raza/Pythons-stuffs
f996e201efd9a81b0610609fcefb8e1297021489
40cd69250520fef7649ed5d46c5cb6d4dc884b52
refs/heads/master
<repo_name>aligarian/ReactDatanomist<file_sep>/src/action.js import Constants from "../constants/constants"; //import axios from 'axios'; const Data = [ { "id": "5c9b809fca9f0e631404df98", "category_title": "CAT_0", "child_categories": [ { "id": "5c9b809feccc88676fe7ca6d", "category_title": "Kathie", "elements": [ { "id": "5c9b809fee79bb475c9c3385", "title": "<NAME>", "city": "Otranto", "description": "Velit excepteur laboris ullamco et adipisicing nisi dolore non do duis proident est id. Id reprehenderit ipsum est labore eu. Elit minim commodo in consectetur cillum do sint ullamco anim veniam dolor pariatur.\r\n" }, { "id": "5c9b809fe638c8801e332942", "title": "<NAME>", "city": "Vaughn", "description": "Sunt culpa amet non commodo culpa eiusmod enim irure mollit ex consequat exercitation dolor sunt. Mollit ipsum cupidatat ex veniam sit deserunt mollit. Occaecat consequat anim adipisicing do incididunt excepteur sint sunt Lorem incididunt laboris occaecat aliqua sunt.\r\n" }, { "id": "5c9b809f9124dacc11982373", "title": "<NAME>", "city": "Caspar", "description": "Culpa esse cillum velit laboris eu nisi proident. Qui sunt sint consequat in aute voluptate ex excepteur occaecat aliquip ut do id. Incididunt duis dolore consectetur enim aliquip sit et. Velit id duis non magna laborum reprehenderit commodo adipisicing velit commodo sint adipisicing laboris nulla. Velit cillum ipsum ex occaecat dolore. Aliquip velit qui qui nisi officia ad eu nulla fugiat elit.\r\n" }, { "id": "5c9b809fb6a9f643c30c97d8", "title": "<NAME>", "city": "Cloverdale", "description": "Magna dolore velit fugiat exercitation officia Lorem commodo nisi non excepteur culpa. Deserunt voluptate ex aliqua aliquip nostrud excepteur mollit in commodo in ad. Culpa enim laborum deserunt eu duis. Non do magna Lorem magna veniam do aliquip occaecat elit nostrud eu eiusmod officia. Irure qui duis aliqua minim in excepteur. Elit nulla id ullamco anim adipisicing tempor incididunt eu eu. Exercitation ut et exercitation excepteur exercitation do qui elit aliqua cillum nostrud do.\r\n" }, { "id": "5c9b809f63f94be3c0d00ef3", "title": "<NAME>", "city": "Malo", "description": "Excepteur irure elit anim fugiat ipsum excepteur ex labore esse proident esse magna. Excepteur in consectetur sit commodo. Anim enim ex adipisicing ea anim aute ipsum proident reprehenderit dolore enim deserunt deserunt. Occaecat id ipsum tempor magna consectetur.\r\n" }, { "id": "5c9b809f7364c332f88c5f66", "title": "<NAME>", "city": "Carlton", "description": "Sit sunt consectetur voluptate ut sit aute elit labore. Et incididunt velit proident enim aute reprehenderit duis. Voluptate amet occaecat incididunt sit voluptate amet incididunt. Fugiat nisi aute anim id officia est aute.\r\n" } ] }, { "id": "5c9b809f0b94803c132eb957", "category_title": "Laverne", "elements": [ { "id": "5c9b809f32d167c162ac3022", "title": "<NAME>", "city": "Camas", "description": "Est consequat esse occaecat ipsum esse do reprehenderit veniam. Lorem enim consequat ullamco laborum. In occaecat est ullamco laboris minim laborum ut ullamco tempor esse sit nulla veniam. Laboris do est labore adipisicing aute ea commodo cupidatat ea amet cupidatat pariatur ad consequat. Consectetur aliquip in labore reprehenderit anim cillum. Non commodo esse labore ex sint.\r\n" }, { "id": "<KEY>", "title": "<NAME>", "city": "Trona", "description": "Commodo sit fugiat labore irure voluptate mollit aliqua. Veniam sit quis Lorem amet. Laborum sit reprehenderit commodo veniam laboris duis pariatur consequat est enim commodo ea commodo. Fugiat dolore duis aliquip Lorem nisi consectetur exercitation deserunt adipisicing nulla. Aute ea est amet tempor ad commodo quis Lorem aliquip dolor fugiat veniam. Aute in tempor officia occaecat occaecat duis ea. Aliqua irure incididunt incididunt exercitation.\r\n" }, { "id": "<KEY>", "title": "<NAME>", "city": "Lund", "description": "Proident ipsum nostrud non nisi anim et minim sint Lorem pariatur in. Qui laboris ea ipsum fugiat fugiat non Lorem eiusmod. Qui sunt ut dolore aute incididunt aliquip.\r\n" }, { "id": "<KEY>289c266f8334d32", "title": "<NAME>", "city": "Allentown", "description": "Sit nisi ipsum ipsum amet deserunt ea adipisicing anim officia id esse. Minim velit aliquip sit voluptate. Cillum nisi sunt eu ipsum est nulla aliquip tempor ex.\r\n" }, { "id": "<KEY>", "title": "<NAME>", "city": "Newry", "description": "Anim mollit cillum consectetur minim commodo magna commodo consequat consequat occaecat. Culpa Lorem do dolore laboris cupidatat enim. Lorem cupidatat amet amet officia voluptate fugiat aute excepteur nostrud pariatur cillum anim incididunt veniam. Et esse duis tempor anim deserunt adipisicing enim fugiat laboris est consectetur consectetur eu sint. Commodo deserunt et nisi consectetur aliquip mollit reprehenderit dolore Lorem nulla officia. Sit laborum deserunt anim adipisicing irure aute eiusmod laboris.\r\n" }, { "id": "<KEY>8e776804df098", "title": "<NAME>", "city": "Felt", "description": "Minim officia nisi excepteur in laboris aliquip anim minim. Ea reprehenderit velit dolor officia eiusmod pariatur duis cillum consequat incididunt ex adipisicing culpa ad. Esse aute ex anim esse dolor ullamco sit. Proident esse est commodo nulla ut ad aute voluptate magna. Elit veniam commodo do Lorem duis adipisicing nostrud id proident. Ullamco fugiat occaecat elit pariatur reprehenderit laborum cupidatat non aute in est ullamco ea labore.\r\n" } ] }, { "id": "5c9b809fb7d2c305eab5c841", "category_title": "Swanson", "elements": [ { "id": "5c9b809f7a795b295079e359", "title": "<NAME>", "city": "Twilight", "description": "Proident aliquip officia do ipsum dolore Lorem aliqua. Adipisicing incididunt excepteur consequat fugiat anim pariatur tempor tempor incididunt. Et cillum minim laborum est reprehenderit irure commodo cillum aliquip aute mollit dolore.\r\n" }, { "id": "5c9b809fe4bce0ac6b4a8577", "title": "<NAME>", "city": "Wilmington", "description": "Veniam commodo reprehenderit ea laboris nulla duis veniam esse occaecat esse. In mollit nostrud et in cupidatat nisi officia nostrud incididunt proident. Culpa cillum ex anim duis magna labore officia veniam quis velit ullamco dolore veniam. Lorem veniam commodo occaecat incididunt nostrud esse incididunt cillum. Nisi nisi officia nostrud do quis mollit dolor ad do non sint.\r\n" }, { "id": "5c9b809fb80c2c30508f5479", "title": "<NAME>", "city": "Takilma", "description": "Mollit officia nostrud ex adipisicing consequat Lorem consectetur do minim. Ut ut duis exercitation quis et. Est laboris mollit laboris laborum et est consectetur deserunt voluptate velit nostrud. Excepteur amet ut aliqua aute cillum et eiusmod excepteur.\r\n" }, { "id": "<KEY>", "title": "<NAME>", "city": "Greenbackville", "description": "Fugiat pariatur officia sint aute velit sint excepteur. Ea et officia anim velit aliquip sit. Do ea commodo aliqua aute incididunt sunt dolor eiusmod. Voluptate enim id veniam irure exercitation ea in eu occaecat quis duis laborum. Qui sunt ut dolor qui velit mollit commodo cillum duis aute exercitation dolore labore eu.\r\n" }, { "id": "<KEY>", "title": "<NAME>", "city": "Yukon", "description": "Velit enim et enim irure reprehenderit. Eiusmod consectetur ipsum et proident sunt duis nostrud nulla dolore nulla. Eu aliquip qui veniam aliquip. Aute quis commodo mollit ut anim laboris aute consectetur. Adipisicing reprehenderit est excepteur officia deserunt quis nisi ea excepteur aliquip.\r\n" }, { "id": "5c9b809f6c8dc545b2df3bf0", "title": "<NAME>", "city": "Grandview", "description": "Magna qui et cupidatat tempor pariatur. Commodo magna irure Lorem fugiat ipsum officia dolore commodo. Veniam culpa incididunt cillum ea dolore mollit pariatur dolore ipsum incididunt pariatur. Enim fugiat dolore veniam est.\r\n" } ] } ] }, { "id": "5c9b809f8f767ca754c47427", "category_title": "CAT_1", "child_categories": [ { "id": "5c9b809fb268698707c7f952", "category_title": "Bertie", "elements": [ { "id": "5c9b809f3518f8bfbec8c545", "title": "<NAME>", "city": "Beechmont", "description": "Fugiat excepteur eu deserunt et ea officia sint magna do cillum. Laborum anim exercitation in et minim proident occaecat. In aliqua eu magna aute laboris in exercitation velit adipisicing reprehenderit excepteur aute dolore. Do dolor deserunt anim veniam irure ad ad nisi incididunt ut consequat enim. Qui mollit irure esse laboris cillum et voluptate fugiat velit amet aliqua pariatur laboris voluptate.\r\n" }, { "id": "<KEY>", "title": "<NAME>", "city": "Shawmut", "description": "Exercitation proident amet ex dolore cupidatat excepteur anim. Consectetur cillum pariatur exercitation nisi irure ullamco enim ad ea laboris. Occaecat excepteur labore adipisicing elit mollit et laborum dolore aute fugiat cupidatat. Commodo deserunt ex ad id aliqua sunt mollit. Amet officia anim eu pariatur adipisicing ipsum incididunt minim dolor sint adipisicing Lorem reprehenderit reprehenderit.\r\n" }, { "id": "<KEY>", "title": "<NAME>", "city": "Alleghenyville", "description": "Ad veniam Lorem eiusmod pariatur occaecat eiusmod irure id ullamco Lorem officia commodo. Ut labore ut eu dolor dolor non laborum adipisicing sint. Ea quis esse nulla fugiat. Voluptate aliquip elit voluptate laborum id nulla magna quis ad dolor. Aliquip in reprehenderit cupidatat Lorem nostrud enim quis sit veniam dolor.\r\n" }, { "id": "5c9b809fadff6632604fb32e", "title": "<NAME>", "city": "Neahkahnie", "description": "Nostrud cillum quis cillum irure. Dolore tempor sit ipsum sit adipisicing culpa culpa ipsum occaecat consequat elit ex. Duis occaecat non sint reprehenderit commodo. Anim in sunt non dolore anim veniam reprehenderit eiusmod.\r\n" }, { "id": "<KEY>", "title": "<NAME>", "city": "Wattsville", "description": "Consequat ex pariatur aute consectetur ut. Cupidatat deserunt occaecat proident quis. Fugiat anim culpa veniam qui. Do commodo ex laborum incididunt culpa elit Lorem non. Eu tempor non dolor duis tempor cillum id quis esse.\r\n" }, { "id": "<KEY>", "title": "<NAME>", "city": "Allamuchy", "description": "Magna nulla sunt sit sit laborum veniam. Sit culpa sit do do eiusmod consequat commodo mollit ex non Lorem est. Id amet non ullamco laborum adipisicing cupidatat dolore et mollit ex Lorem consequat eu laborum. Culpa occaecat non consequat deserunt aute veniam aute est do dolor. In nostrud non consequat sint exercitation. Ullamco nostrud eu anim et Lorem excepteur magna amet aliqua aliquip in Lorem. Minim exercitation ipsum elit sit ullamco labore cupidatat cillum.\r\n" } ] }, { "id": "5c9b809f3faac<KEY>", "category_title": "Latoya", "elements": [ { "id": "<KEY>", "title": "<NAME>", "city": "Chapin", "description": "Ad non ullamco amet consequat reprehenderit duis est excepteur. Eiusmod minim ex nulla proident eiusmod proident ipsum ea excepteur. Ipsum commodo in culpa et consequat aliqua proident sit sunt velit. Deserunt est eiusmod Lorem deserunt labore voluptate deserunt. Sit fugiat tempor minim aliquip consectetur nulla culpa proident adipisicing reprehenderit.\r\n" }, { "id": "<KEY>", "title": "<NAME>", "city": "Warsaw", "description": "Commodo reprehenderit laborum cillum voluptate. Esse magna qui culpa veniam amet fugiat eu ipsum commodo proident eiusmod. Officia quis qui tempor dolore. Laborum labore et pariatur quis nisi ad consectetur fugiat.\r\n" }, { "id": "<KEY>0872e02e0749cac", "title": "<NAME>", "city": "Jennings", "description": "Enim magna voluptate nisi ipsum nisi qui fugiat qui officia non esse laboris dolor officia. Minim qui minim aute nulla minim nisi pariatur deserunt proident id. Laborum aliquip officia veniam Lorem veniam do ex in veniam eu labore ad. Reprehenderit laboris voluptate est amet consequat ut non nulla pariatur quis tempor. Mollit aliqua velit proident amet laboris do consectetur tempor dolor qui minim aliquip.\r\n" }, { "id": "5c9b809ff987b768e909d80e", "title": "<NAME>", "city": "Belgreen", "description": "Ut mollit pariatur nisi anim tempor et eu aute. Do minim in mollit nostrud ullamco pariatur sit consectetur deserunt officia sunt consequat aliqua. Magna laboris adipisicing in velit dolor Lorem Lorem mollit cupidatat excepteur do amet. Sint do aliqua voluptate elit sit Lorem.\r\n" }, { "id": "<KEY>", "title": "<NAME>", "city": "Strykersville", "description": "Voluptate consequat eiusmod ad occaecat fugiat nostrud velit ut laboris elit nisi adipisicing minim. Amet voluptate est ipsum est exercitation sunt aliquip consequat et sint quis. Non aliquip commodo mollit dolor est dolor dolor do ut sint. Tempor officia consectetur quis sint ipsum in pariatur ipsum elit consectetur sit Lorem nulla. Laborum commodo excepteur elit eiusmod dolore sunt dolor quis do amet et esse magna eu. Proident irure aliqua velit esse ex.\r\n" }, { "id": "<KEY>", "title": "<NAME>", "city": "Soham", "description": "Dolore labore mollit ad in voluptate velit. Reprehenderit adipisicing Lorem nisi veniam et ea. Veniam cupidatat aliqua non dolore deserunt. Fugiat laborum tempor et ex ex elit sit amet exercitation elit excepteur.\r\n" } ] }, { "id": "5c9b809f00c815c497e5df54", "category_title": "Tammy", "elements": [ { "id": "<KEY>eaaf6ee8e7f", "title": "<NAME>", "city": "Weogufka", "description": "Quis amet mollit dolor ea sint pariatur. Consectetur deserunt id enim nisi ipsum ea voluptate eiusmod. In cupidatat laborum dolore mollit enim. Deserunt aliquip minim aute labore nisi ipsum dolore nostrud officia.\r\n" }, { "id": "5c9b809fe2ac038d39aec760", "title": "<NAME>", "city": "Boykin", "description": "In mollit adipisicing nostrud incididunt nulla laborum elit eu tempor cillum officia mollit. Aute pariatur dolore deserunt veniam dolor dolore excepteur magna sint ut incididunt minim. Dolor duis irure labore aute aliquip est dolore culpa mollit. Dolore amet velit aute velit irure aliquip dolore.\r\n" }, { "id": "5c9b809f786ae8d30eafa4fe", "title": "<NAME>", "city": "Fivepointville", "description": "Labore esse officia veniam veniam velit esse ea eiusmod occaecat sint eu aliquip ad. Lorem Lorem exercitation voluptate adipisicing duis. Ex qui nisi velit eiusmod consectetur aliqua consectetur nulla anim consequat excepteur nulla. Elit esse officia eu velit magna excepteur.\r\n" }, { "id": "5c9b809f3e96f04350051263", "title": "<NAME>", "city": "Lewis", "description": "Minim anim ea in ut ut eiusmod quis ipsum veniam et. Ea aliquip enim consectetur proident labore ipsum reprehenderit officia et nostrud quis excepteur ad sit. Officia dolor ad Lorem minim Lorem sunt commodo dolore laborum do.\r\n" }, { "id": "5c9b809ffb18f93a35dd42ec", "title": "<NAME>", "city": "Yettem", "description": "Quis officia sunt Lorem veniam sit tempor consectetur esse voluptate velit incididunt cupidatat commodo nostrud. Labore duis do do ut. Elit laboris incididunt pariatur cupidatat consequat reprehenderit excepteur cillum.\r\n" }, { "id": "<KEY>", "title": "<NAME>", "city": "Swartzville", "description": "Qui ullamco minim officia esse mollit consequat amet Lorem nisi nulla laborum. Labore do reprehenderit enim dolore qui sint cillum consequat cupidatat cillum. Ex dolore nisi eiusmod pariatur voluptate quis reprehenderit dolor est veniam voluptate pariatur. Aliqua veniam ipsum culpa magna anim eu culpa irure eiusmod magna occaecat anim. Labore quis deserunt magna incididunt officia amet ea proident in enim non id pariatur.\r\n" } ] }, { "id": "5c9b809fa87973b9b01fe97b", "category_title": "Millicent", "elements": [ { "id": "5c9b809f11bf7aa6b0261e48", "title": "<NAME>", "city": "Chemung", "description": "Sint quis esse ea esse. Quis non sit ea mollit magna nostrud quis laboris eu sint nisi tempor deserunt. Pariatur ullamco est et dolor exercitation quis. Eu aute quis fugiat ut do aute magna est nulla reprehenderit velit sint. Eu laborum in dolore laboris velit in in laboris in fugiat nisi in est. Quis anim reprehenderit in nulla magna. Tempor aute esse anim nulla ullamco voluptate incididunt reprehenderit cillum do Lorem.\r\n" }, { "id": "<KEY>", "title": "<NAME>", "city": "Skyland", "description": "Occaecat exercitation mollit irure in nulla consectetur aliqua. Deserunt nulla occaecat incididunt nisi incididunt commodo laborum. Adipisicing mollit eiusmod mollit in. Laboris qui cupidatat sit laborum nostrud eu fugiat consequat occaecat do non ad.\r\n" }, { "id": "5c<KEY>acb18f189", "title": "<NAME>", "city": "Advance", "description": "Occaecat enim et esse ipsum dolore commodo dolore consectetur id nostrud in consequat. Sit incididunt et est duis consequat Lorem anim qui proident do reprehenderit incididunt incididunt commodo. Officia ad adipisicing eu adipisicing est est esse. Ut consequat anim reprehenderit irure consequat ut proident. Dolore quis ex mollit ipsum ullamco consectetur ad dolor mollit est nostrud ipsum aute.\r\n" }, { "id": "<KEY>", "title": "<NAME>", "city": "Manila", "description": "Et aliqua mollit in Lorem est qui incididunt consectetur adipisicing sunt. Fugiat nisi pariatur labore voluptate reprehenderit dolor culpa est. Non minim ipsum enim dolore tempor minim consequat occaecat veniam in aliquip. Anim excepteur enim pariatur qui ullamco laborum veniam occaecat laborum ea incididunt adipisicing eu.\r\n" }, { "id": "<KEY>", "title": "<NAME>", "city": "Gracey", "description": "Voluptate sit nisi do anim labore aliquip nostrud veniam pariatur velit sit ad fugiat. Anim elit do non incididunt in amet consequat et labore aute eiusmod anim. Ea pariatur id culpa mollit pariatur. Enim tempor est ad duis consectetur laboris dolore ut reprehenderit ut ullamco.\r\n" }, { "id": "5c9b809f0fb3c236cfad71e3", "title": "<NAME>", "city": "Nash", "description": "Sunt voluptate reprehenderit consequat pariatur reprehenderit adipisicing incididunt. Anim amet ullamco in exercitation irure laborum irure esse velit ea adipisicing excepteur commodo. Lorem ullamco excepteur incididunt ad nulla dolor adipisicing eu aliquip duis. Elit enim Lorem dolore eu commodo ullamco. Ad amet non sit consectetur Lorem velit reprehenderit esse pariatur magna pariatur culpa enim.\r\n" } ] } ] }, { "id": "5c9b809f7979bb4317ab1f2e", "category_title": "CAT_2", "child_categories": [ { "id": "5c9b809f68d63f2dd663b53c", "category_title": "Becker", "elements": [ { "id": "5c9b809f20631633b48c4cd3", "title": "<NAME>", "city": "Kidder", "description": "Ipsum irure veniam ad minim velit sit pariatur Lorem commodo mollit tempor cillum do Lorem. Reprehenderit dolor ipsum eiusmod aliqua. Occaecat ad voluptate sunt qui dolore officia laboris labore consectetur consequat sint. Anim nulla pariatur duis duis officia est sint nostrud Lorem aliqua Lorem nulla.\r\n" }, { "id": "5c9b809fa730fad57c29681b", "title": "<NAME>", "city": "Crucible", "description": "Elit aliqua incididunt voluptate deserunt quis Lorem dolore reprehenderit deserunt adipisicing laboris commodo amet anim. Quis et laboris consequat aliquip ipsum ipsum tempor proident. Qui ipsum excepteur cupidatat elit fugiat pariatur exercitation nostrud. Id dolor excepteur commodo aliqua cillum cupidatat quis commodo. Quis Lorem pariatur tempor nisi.\r\n" }, { "id": "5c9b809f77aa9e536c74f73f", "title": "<NAME>", "city": "Shelby", "description": "Occaecat velit eu mollit dolor sint labore laboris incididunt elit dolore excepteur et nisi. Incididunt minim aliquip cupidatat dolor. Proident aute ipsum pariatur laboris tempor incididunt elit incididunt aute amet tempor ipsum esse. Fugiat elit cillum nostrud sit. Officia aliquip officia eu fugiat. Nisi ut incididunt sit est voluptate consequat ipsum commodo ad nulla.\r\n" }, { "id": "5c9b809f21bb0919dde0a250", "title": "<NAME>", "city": "Caln", "description": "Tempor sit labore incididunt mollit velit eiusmod quis cillum deserunt nisi ullamco exercitation magna velit. Esse irure proident do ad dolore mollit minim esse. Deserunt labore voluptate reprehenderit voluptate reprehenderit ea consequat dolor dolore magna exercitation laborum eiusmod nulla. Dolore ad sint deserunt occaecat eu aliqua reprehenderit enim.\r\n" }, { "id": "5c9b809f0351fe82430e39d9", "title": "<NAME>", "city": "Henrietta", "description": "Exercitation incididunt magna sunt id eiusmod commodo duis ut enim. Aliqua dolor in veniam ad et anim occaecat do pariatur nostrud labore fugiat qui ad. Aute nostrud ipsum est ea minim laborum velit exercitation fugiat exercitation esse mollit. Et voluptate ad ea consequat. Consequat labore ea voluptate ullamco ullamco et sint deserunt ut ea consequat sunt et occaecat.\r\n" }, { "id": "5c9b809ff99b3405eb1e5aff", "title": "<NAME>", "city": "Thomasville", "description": "Ex est Lorem duis excepteur laboris quis ut ut aliquip amet ipsum. Ad amet ea nostrud nulla non. Aliquip quis eiusmod minim reprehenderit dolore et ipsum aute ipsum commodo. Enim ipsum cillum ea sunt consectetur amet est laboris labore nisi est aute aliquip. Qui quis incididunt qui et esse magna culpa occaecat excepteur dolore eu tempor dolore. Nostrud amet aliqua ullamco sit voluptate.\r\n" } ] }, { "id": "5c9b809f92a4a0073c2959eb", "category_title": "Deidre", "elements": [ { "id": "5c9b809f02cd96512b11a453", "title": "<NAME>", "city": "Bradenville", "description": "Cupidatat dolore proident elit sit adipisicing aute ullamco nulla aliqua. Amet adipisicing aliqua culpa officia quis consectetur velit. Adipisicing sint non dolor elit labore quis nisi amet laborum adipisicing.\r\n" }, { "id": "5c9b809f4998faf2940939de", "title": "<NAME>", "city": "Sandston", "description": "Enim esse veniam commodo occaecat nisi. Ullamco eu consectetur est ea sit mollit non dolore nostrud do. Ipsum in incididunt irure reprehenderit aliquip deserunt id enim culpa tempor mollit cillum cillum. Mollit velit non excepteur eu consectetur tempor excepteur officia pariatur quis esse dolor laboris.\r\n" }, { "id": "5c9b809fee<KEY>", "title": "<NAME>", "city": "Dowling", "description": "Culpa eiusmod quis in consectetur. Non elit mollit ut incididunt ea pariatur. In qui laboris esse duis fugiat anim veniam id Lorem. Sit laboris ut quis veniam amet proident laboris eu duis ex. Enim fugiat ex excepteur occaecat. Pariatur deserunt consectetur occaecat culpa non do.\r\n" }, { "id": "5c9b809f15251a647decb68a", "title": "<NAME>", "city": "Snyderville", "description": "Aliquip excepteur id Lorem ea irure. Mollit magna in et laboris ipsum aute do commodo. Tempor Lorem excepteur eu proident elit sunt exercitation eu. Laboris laboris ullamco non laborum est. Magna nostrud ullamco qui nulla.\r\n" }, { "id": "5c9b809feec0557e7e381de8", "title": "<NAME>", "city": "Summerfield", "description": "Excepteur sit fugiat id commodo minim occaecat sint in ipsum do magna veniam. Proident pariatur adipisicing eu est amet fugiat anim ad incididunt. Culpa sint Lorem amet in. Esse ex quis mollit quis ad ut ea. Elit tempor commodo aliqua tempor aliquip est pariatur incididunt ullamco. Esse et laboris dolor proident sint amet.\r\n" }, { "id": "5c9b809f52a26c96b4d1f5a7", "title": "<NAME>", "city": "Nicut", "description": "Pariatur aliqua veniam anim enim enim eu velit adipisicing voluptate amet eiusmod deserunt. Commodo id deserunt dolore ullamco qui deserunt non labore ullamco mollit. Dolor sit adipisicing et proident qui labore ipsum do aute dolore ut do consectetur. Culpa mollit ipsum amet tempor laborum fugiat incididunt nisi sint ipsum ea sit. Duis proident voluptate commodo et qui do adipisicing voluptate commodo cillum aute deserunt. Culpa do officia voluptate labore et elit commodo do in veniam.\r\n" } ] }, { "id": "5c9b809fd3e365ac31c2cb2a", "category_title": "Compton", "elements": [ { "id": "5c9b809f55c2b2021f2fe74b", "title": "<NAME>", "city": "Byrnedale", "description": "Labore ut culpa aliqua excepteur sit qui et. Ad ullamco aute consectetur dolor adipisicing dolor proident ullamco aliquip consequat quis quis nisi. Dolor veniam consectetur occaecat incididunt id et. Id ea duis esse minim adipisicing et.\r\n" }, { "id": "5c9b809f523242d0493fcaa4", "title": "<NAME>", "city": "Crawfordsville", "description": "Nostrud Lorem magna amet sint consequat est ad voluptate ex esse fugiat sint nulla cillum. Adipisicing nulla elit enim in pariatur proident qui proident ex incididunt minim irure deserunt consequat. Veniam aliqua sunt qui irure excepteur. Sit dolor in velit dolor laboris occaecat culpa in esse elit id exercitation. Dolor duis enim dolor dolore est elit nisi veniam in non exercitation.\r\n" }, { "id": "5c9b809f89b419d57c3f157a", "title": "<NAME>", "city": "Bendon", "description": "Sit in laboris ex exercitation enim esse deserunt occaecat minim veniam amet. Dolor eu consectetur nostrud consequat voluptate deserunt amet ad exercitation enim. Sint mollit ea consequat ad Lorem dolor occaecat tempor ipsum. Velit officia ad fugiat dolore duis eu amet non ad incididunt anim minim. Eu aute fugiat occaecat sint incididunt dolore. Exercitation proident esse sint et.\r\n" }, { "id": "5c9b809fc44ba70795b002e4", "title": "<NAME>", "city": "Day", "description": "Veniam magna eu ut exercitation. Labore tempor nulla est sint est mollit laboris culpa laborum non dolor eiusmod. Ea reprehenderit ullamco voluptate anim voluptate fugiat non qui dolore Lorem. Proident officia voluptate culpa cupidatat excepteur id veniam magna consequat excepteur culpa reprehenderit amet tempor. Occaecat voluptate cupidatat nulla ipsum labore. Ea in occaecat cupidatat pariatur mollit non anim deserunt cillum adipisicing est non. Duis excepteur duis esse anim consectetur sunt dolor id sint exercitation.\r\n" }, { "id": "5c9b809fad8ae6f4edf2526e", "title": "<NAME>", "city": "Grahamtown", "description": "Tempor laborum aliquip sint quis laborum deserunt do. Et magna id esse id elit ad adipisicing aliqua. Non minim in nisi quis sit consequat nulla non excepteur cillum elit. Labore aliqua eiusmod minim aliquip adipisicing minim quis culpa irure magna aliquip.\r\n" }, { "id": "5c9b809f74e8f99a0dc5facf", "title": "<NAME>", "city": "Hiwasse", "description": "Proident magna aute do Lorem non. Est ad esse sunt ullamco. Consectetur ipsum non ullamco in aliqua.\r\n" } ] } ] }, { "id": "5c9b809fe0c68a0c601b4ba9", "category_title": "CAT_3", "child_categories": [ { "id": "5c9b809f3c7aa5cd3c363c93", "category_title": "Nora", "elements": [ { "id": "5c9b809f3dfcd62f772b31bc", "title": "<NAME>", "city": "Kerby", "description": "Non laborum ea aliqua nostrud ex non enim veniam occaecat duis aute anim. Commodo elit consectetur elit esse irure fugiat est voluptate minim labore. Sit occaecat voluptate deserunt ipsum duis cupidatat nulla et. Enim sit aliquip fugiat anim officia pariatur reprehenderit cupidatat cillum eiusmod laboris nisi sit. Anim eiusmod eu dolor cillum irure elit. Enim nostrud anim cupidatat eu et qui nostrud voluptate esse exercitation. Amet tempor consectetur eiusmod eu laborum voluptate fugiat labore.\r\n" }, { "id": "<KEY>", "title": "<NAME>", "city": "Snelling", "description": "Nostrud minim ad eiusmod velit velit. Nostrud adipisicing anim exercitation sit Lorem laboris eu do elit cupidatat pariatur aute deserunt. Enim minim aute duis exercitation qui. Fugiat dolore id velit enim duis incididunt ad consequat ullamco laboris dolor labore laborum tempor. Fugiat enim do ipsum velit quis dolor sunt et esse ullamco. Fugiat exercitation id ipsum aute.\r\n" }, { "id": "<KEY>", "title": "<NAME>", "city": "Juarez", "description": "Lorem tempor sunt proident officia cupidatat ad aliquip voluptate in qui cupidatat pariatur. Ex adipisicing sit elit culpa enim sunt elit consequat tempor elit eu ex. Duis nostrud id aute sit laborum ullamco sunt aliquip. Sint eu culpa eu quis ut qui incididunt et fugiat laboris est anim elit.\r\n" }, { "id": "5c9b809fa385c2c92c09a234", "title": "<NAME>", "city": "Coleville", "description": "Lorem qui non in minim non pariatur eu magna. Officia magna cupidatat ex anim ea eu. In in amet proident nostrud sint eiusmod dolore enim non sint ullamco proident.\r\n" }, { "id": "5c9b809f216f75d36b17f39d", "title": "<NAME>", "city": "Lawrence", "description": "Aliqua culpa dolore culpa elit cillum laborum aute. Occaecat reprehenderit ex magna consectetur dolore labore nostrud culpa voluptate. Quis non sunt aliqua do id id nisi ullamco reprehenderit. Id cupidatat elit aliquip mollit elit consectetur magna commodo nulla. Id fugiat consequat qui mollit commodo sint duis nulla deserunt fugiat.\r\n" }, { "id": "<KEY>", "title": "<NAME>", "city": "Dellview", "description": "Minim pariatur nisi laboris duis proident nisi ea. Laboris dolor nisi commodo labore laboris excepteur anim amet dolor aliqua. Anim laborum dolor nulla ullamco.\r\n" } ] }, { "id": "5c9b809fff2f9b34216a788e", "category_title": "Ayala", "elements": [ { "id": "5c9b809f14c0efabf3da2181", "title": "<NAME>", "city": "Hobucken", "description": "Fugiat veniam nostrud elit et enim. Laboris dolore duis dolore consectetur ea irure culpa elit. Dolore aliquip sunt dolore qui elit voluptate Lorem ipsum. Ex sint duis excepteur cupidatat sint aliquip. Labore tempor proident eu in eu. Cillum proident fugiat cillum mollit officia qui commodo.\r\n" }, { "id": "5c9b809f6aab91f2f1e9a203", "title": "<NAME>", "city": "Edneyville", "description": "Do exercitation laboris incididunt officia id consectetur. Sint consequat do et dolore magna quis cillum minim elit consequat cupidatat. Reprehenderit aliquip ex officia in magna cupidatat officia exercitation. Aliqua adipisicing veniam aliqua culpa culpa Lorem deserunt. Dolor enim sit proident incididunt dolor laboris occaecat minim do tempor fugiat. Sunt do labore magna non incididunt eiusmod incididunt reprehenderit excepteur minim commodo qui. Ex aliquip irure esse proident do.\r\n" }, { "id": "5c9b809f0c8e912b2ef4ba1d", "title": "<NAME>", "city": "Brownlee", "description": "Velit eu et Lorem ullamco ea minim enim aliqua. Aliqua do commodo magna laboris officia quis nisi aliquip laboris amet. Ullamco irure consectetur aliquip dolor aute.\r\n" }, { "id": "<KEY>", "title": "<NAME>", "city": "Faxon", "description": "Enim magna consectetur reprehenderit et aliquip eiusmod cillum dolore. Non nostrud nostrud anim eiusmod ea eiusmod qui fugiat. Fugiat anim adipisicing cillum occaecat incididunt.\r\n" }, { "id": "<KEY>", "title": "<NAME>", "city": "Chestnut", "description": "Mollit cillum dolor excepteur quis eiusmod occaecat laborum cillum enim elit aliqua non commodo. Laborum sunt elit occaecat consectetur enim officia mollit ad veniam. Non sit est culpa aute aliqua sunt pariatur quis laboris aute ut mollit eu irure.\r\n" }, { "id": "5c9b809ff8204a2c96695d32", "title": "<NAME>", "city": "Rosburg", "description": "Tempor qui commodo minim occaecat magna cupidatat ad esse consequat ea eu officia. Enim velit irure adipisicing fugiat anim proident mollit ad ea est mollit culpa. Eu aliqua labore sunt nostrud duis. Magna culpa sint fugiat eu ea nulla incididunt do aute ut elit proident velit.\r\n" } ] }, { "id": "<KEY>", "category_title": "Rae", "elements": [ { "id": "5c9b809f9b57ae153c219f2f", "title": "<NAME>", "city": "Veguita", "description": "Magna amet exercitation qui irure. Tempor consectetur voluptate amet aute esse est veniam voluptate. Id minim tempor commodo magna reprehenderit ut officia culpa consectetur ea eiusmod commodo. Incididunt tempor cillum irure laboris nisi exercitation eiusmod. Ut occaecat cupidatat qui eiusmod cillum sunt veniam minim tempor aute pariatur qui.\r\n" }, { "id": "<KEY>", "title": "<NAME>", "city": "Lynn", "description": "Culpa reprehenderit Lorem non non qui veniam ullamco labore sit enim veniam elit minim esse. Ad velit excepteur laboris anim fugiat incididunt elit exercitation sunt et in nulla irure pariatur. Eiusmod dolore nostrud cupidatat irure veniam consectetur anim sit ipsum.\r\n" }, { "id": "<KEY>", "title": "<NAME>", "city": "Rockbridge", "description": "Anim minim do non Lorem esse qui incididunt aliquip elit. Id ex voluptate dolor cillum mollit commodo officia officia voluptate in fugiat laborum et. Laboris minim aliqua ipsum elit adipisicing. Deserunt ad nulla dolore duis enim velit minim deserunt ut nisi.\r\n" }, { "id": "<KEY>", "title": "<NAME>", "city": "Dodge", "description": "Sint ex excepteur elit veniam ut quis do id reprehenderit et cupidatat dolor. Officia amet dolor in anim aliqua nisi consectetur. Amet sint veniam Lorem consectetur reprehenderit incididunt tempor esse voluptate veniam minim ut duis voluptate. Proident cillum cillum quis non sint commodo occaecat labore quis eiusmod ut. Veniam esse esse minim cupidatat culpa nulla amet. Eiusmod dolore minim esse magna deserunt nisi commodo dolore.\r\n" }, { "id": "<KEY>", "title": "<NAME>", "city": "Dawn", "description": "Pariatur occaecat aliquip anim ut adipisicing consectetur excepteur adipisicing nulla excepteur sint duis fugiat enim. Occaecat id occaecat incididunt aliquip voluptate amet eiusmod exercitation sint aliqua qui. Id occaecat qui veniam duis veniam. Magna sunt magna commodo labore Lorem et ex. Velit do Lorem qui qui anim sit nulla. Sunt reprehenderit duis deserunt Lorem ad. Sint voluptate eiusmod aute adipisicing ut elit ad tempor.\r\n" }, { "id": "5c9b809f4906fe6fb9b8b7e1", "title": "<NAME>", "city": "Saddlebrooke", "description": "Nostrud duis reprehenderit eu ex reprehenderit irure commodo in. Ea cupidatat excepteur veniam ad nulla. Veniam tempor irure incididunt irure anim aliquip incididunt duis nisi Lorem. Adipisicing ullamco nulla duis non non velit. Tempor id sint ea consectetur id adipisicing id labore magna anim nostrud. Esse consequat pariatur id Lorem. Ea nisi aute nostrud sunt ullamco.\r\n" } ] }, { "id": "5c9b809f231385904986dc66", "category_title": "Marietta", "elements": [ { "id": "5c9b809f96a62a45c064aae9", "title": "<NAME>", "city": "Lodoga", "description": "Deserunt exercitation ipsum officia velit reprehenderit occaecat adipisicing anim Lorem consectetur labore. Amet adipisicing labore commodo irure sit exercitation consequat quis laboris nostrud id Lorem. Sunt ullamco ipsum id aliquip commodo incididunt mollit reprehenderit id et. Ad irure duis ex non pariatur labore laborum.\r\n" }, { "id": "5c9b809fab3d31471ac647ac", "title": "<NAME>", "city": "Weedville", "description": "Do laboris nostrud exercitation veniam magna ea incididunt fugiat ullamco quis. Consequat mollit ex fugiat est nisi quis mollit cillum id deserunt nisi non. Consectetur cupidatat consectetur reprehenderit incididunt et ea commodo eu excepteur ipsum irure incididunt nostrud.\r\n" }, { "id": "5c9b809fee6e4ccc3bf04b04", "title": "<NAME>", "city": "Lindisfarne", "description": "Ipsum labore cillum excepteur aliqua eu ea sunt ut. Cillum eiusmod ad qui quis magna nulla ex duis non sint incididunt non commodo culpa. Dolor amet exercitation labore excepteur voluptate ipsum deserunt et tempor.\r\n" }, { "id": "<KEY>", "title": "<NAME>", "city": "Waiohinu", "description": "Officia enim sit aute reprehenderit aute duis incididunt sunt duis laborum proident labore incididunt. Ullamco ut mollit aliquip velit in ullamco. Ad nisi eiusmod excepteur sit labore qui elit duis Lorem. Voluptate eiusmod voluptate nostrud Lorem nostrud sint ullamco proident sunt tempor.\r\n" }, { "id": "5c9b809f373c479c6db23c6c", "title": "<NAME>", "city": "Elbert", "description": "Eiusmod dolore nostrud et ullamco. Nulla eu nostrud voluptate reprehenderit duis eu exercitation incididunt qui. Aliquip dolor qui sint officia Lorem consectetur eiusmod.\r\n" }, { "id": "5c9b809fbd906ecc32c34f49", "title": "<NAME>", "city": "Sunbury", "description": "Est duis quis nostrud aute et non. Incididunt aute enim in amet pariatur. Lorem duis tempor voluptate nisi ullamco cillum excepteur eiusmod amet eu in exercitation irure. Nostrud est ex esse laboris. Qui dolore cillum aliquip eiusmod proident culpa laboris. Culpa ea proident adipisicing duis duis.\r\n" } ] }, { "id": "5c9b809f389b5d76f8313345", "category_title": "Polly", "elements": [ { "id": "5c9b809f3ae10eb629ca9aac", "title": "<NAME>", "city": "Hendersonville", "description": "Non esse voluptate consectetur qui reprehenderit sint excepteur elit cillum cupidatat sint officia ex. Voluptate irure ad consequat mollit sit officia culpa quis tempor sit eu do dolor officia. Amet labore ut aute cupidatat eiusmod duis eu. Ut consectetur irure cupidatat ipsum excepteur incididunt in excepteur dolor nisi pariatur aliqua adipisicing dolore. Do magna eu commodo aute laborum veniam tempor sit cillum velit duis cillum Lorem. Excepteur aute anim sint mollit adipisicing deserunt adipisicing non non officia quis est ullamco.\r\n" }, { "id": "5c9b809faaa51a3d897f3472", "title": "<NAME>", "city": "Westboro", "description": "Voluptate quis deserunt consectetur esse esse aliqua enim enim veniam anim sint deserunt ipsum. Duis proident anim ea officia id. Lorem exercitation laborum non non incididunt adipisicing pariatur laboris cupidatat non. Minim cupidatat eu duis pariatur id ea id sunt. Sit do occaecat do reprehenderit laborum anim esse irure aliqua adipisicing ex. Ipsum amet aliquip deserunt aliquip.\r\n" }, { "id": "<KEY>c<KEY>", "title": "<NAME>", "city": "Norris", "description": "Culpa magna nostrud magna proident ut Lorem nulla minim nisi irure mollit. Anim qui nisi velit commodo irure esse ipsum. Voluptate sit officia ullamco sit irure proident duis Lorem consequat consectetur.\r\n" }, { "id": "5c9b809f35fa56903460f2d8", "title": "<NAME>", "city": "Fairforest", "description": "Ad consectetur reprehenderit duis ea id irure irure. Enim esse culpa aliquip velit laboris nisi mollit dolore sit id occaecat sit voluptate. Sint tempor fugiat excepteur reprehenderit enim ad officia dolor tempor non.\r\n" }, { "id": "5c9b809f4b24f6baa50bcfd6", "title": "<NAME>", "city": "Dahlen", "description": "Ex minim aliquip sunt exercitation eu nulla incididunt nulla eiusmod. Duis sint et non dolor aute. Duis amet voluptate aliqua culpa. Pariatur enim elit commodo laborum velit sit culpa aliqua commodo est. Nulla velit proident tempor ullamco. Excepteur do do eiusmod sit velit minim consectetur occaecat do.\r\n" }, { "id": "5c9b809f5ac0348726e06721", "title": "<NAME>", "city": "Corriganville", "description": "Laboris ullamco aute Lorem magna esse consectetur ut tempor occaecat officia Lorem nostrud magna dolore. Id aute sint cupidatat irure anim dolore id id dolor quis in aliquip consectetur cillum. Dolore excepteur est quis anim. Veniam consectetur culpa nisi est proident eiusmod magna. Magna tempor fugiat fugiat ad. Duis sit est sunt irure quis velit.\r\n" } ] } ] }, { "id": "5c9b809f4ba3d93e32008a5a", "category_title": "CAT_4", "child_categories": [ { "id": "5c9b809f4c1b913c34cfcd5b", "category_title": "Marjorie", "elements": [ { "id": "5c9b809ff5c896d88f11b3d3", "title": "<NAME>", "city": "Russellville", "description": "Magna quis voluptate nostrud occaecat non proident. Nisi fugiat anim consectetur duis ex sint aute aute dolor incididunt commodo et. Eu nulla reprehenderit mollit nostrud ad deserunt nostrud ut. Deserunt laboris et qui est et nulla amet id incididunt ex Lorem. Ullamco quis labore commodo magna do veniam ut ea quis non adipisicing elit adipisicing voluptate. Officia dolor pariatur sint ad ea.\r\n" }, { "id": "5c9b809ff22b23f1504496ed", "title": "<NAME>", "city": "Eden", "description": "Tempor nostrud minim cillum exercitation laborum in aliqua officia do excepteur aliqua consequat. In dolore qui ad ea in laborum culpa tempor mollit irure. Aliquip commodo ullamco cillum Lorem est est exercitation irure anim minim consequat dolore sint. Laboris officia duis sint aliquip mollit nostrud ipsum commodo et ea. Amet mollit consectetur commodo incididunt magna cillum culpa dolor Lorem duis. Fugiat reprehenderit ex occaecat Lorem ut ea elit irure anim occaecat est laborum excepteur mollit.\r\n" }, { "id": "<KEY>", "title": "<NAME>", "city": "Dargan", "description": "Commodo ea aliquip elit nulla. Anim occaecat pariatur Lorem ea id et ipsum nostrud. Reprehenderit qui laborum reprehenderit veniam. Incididunt nulla sit consequat occaecat culpa ex do eu ut aute ex pariatur laboris. Enim et laborum in ex.\r\n" }, { "id": "5c9b809f74f3a033a46b36c3", "title": "<NAME>", "city": "Drytown", "description": "Eiusmod aute irure duis pariatur ullamco sint ex deserunt aute et voluptate. Nostrud proident enim ex deserunt nostrud. Aute sunt excepteur labore esse ea cillum incididunt velit nisi anim. Ea consectetur non incididunt consequat voluptate mollit duis fugiat esse commodo excepteur incididunt.\r\n" }, { "id": "5c9b809fadbc08e6a3de481e", "title": "<NAME>", "city": "Sabillasville", "description": "Sint eu pariatur sunt velit. Dolore occaecat sunt esse ex occaecat officia tempor in reprehenderit ea. Exercitation labore esse excepteur et fugiat aliquip ad ex aliquip dolor reprehenderit quis voluptate aliquip. Nisi qui consectetur commodo Lorem. Aliqua pariatur laborum sint dolor eiusmod id ut aliqua cupidatat proident ullamco quis tempor. In non id fugiat aliqua. Ut quis magna amet eu enim cupidatat reprehenderit duis.\r\n" }, { "id": "5c9b809fe18023a892fb1bf1", "title": "<NAME>", "city": "Spelter", "description": "Nisi do qui proident in veniam veniam aliqua. Veniam laborum commodo Lorem ad voluptate adipisicing id enim proident consectetur est quis. Sunt voluptate dolor minim qui pariatur non sunt in esse reprehenderit in veniam aliquip. Duis adipisicing nulla velit sit ex sit. Voluptate id nulla duis nulla adipisicing proident excepteur ullamco laborum culpa reprehenderit fugiat sint nulla. Eu consectetur officia nulla est voluptate laborum magna ea Lorem eu tempor cillum.\r\n" } ] }, { "id": "5c9b809fc028250ba061d7aa", "category_title": "Amie", "elements": [ { "id": "5c9b809f2cfd49f3e7b9f897", "title": "<NAME>", "city": "Falmouth", "description": "Fugiat non Lorem labore commodo commodo irure enim officia. Ea et adipisicing consectetur mollit do esse cupidatat nulla officia amet. Eiusmod deserunt laboris fugiat incididunt enim cupidatat minim cupidatat officia nulla culpa incididunt deserunt deserunt. Veniam laborum non officia excepteur incididunt duis pariatur. Ipsum officia consectetur officia duis et nostrud veniam. Ex ullamco qui reprehenderit consectetur.\r\n" }, { "id": "5c9b809f607c210c3cc92449", "title": "<NAME>", "city": "Wanamie", "description": "Exercitation voluptate excepteur veniam in voluptate magna Lorem aliquip adipisicing pariatur. Culpa consequat velit est sint. Ad velit mollit aliqua deserunt incididunt. Velit officia eiusmod consequat enim aliqua occaecat dolor laborum magna cupidatat fugiat culpa minim. Pariatur mollit irure magna ea veniam occaecat ut ipsum. Dolor velit excepteur reprehenderit tempor incididunt anim. Ex et officia do reprehenderit irure pariatur voluptate non culpa voluptate officia consequat proident.\r\n" }, { "id": "5c9b809fe4497d7e28a4ade1", "title": "<NAME>", "city": "Fannett", "description": "Voluptate magna est ex labore ut consequat. Ea officia excepteur ut tempor fugiat ex dolor. Aliqua voluptate cillum eu adipisicing cillum ea est fugiat incididunt. Velit id cupidatat aliqua aliquip ea minim. Proident cillum culpa dolore quis cupidatat cupidatat. Do ipsum ipsum cillum amet et ullamco ullamco pariatur cillum esse. Proident qui et consectetur reprehenderit mollit officia consectetur ad ullamco velit cillum ad sunt exercitation.\r\n" }, { "id": "<KEY>", "title": "<NAME>", "city": "Kenmar", "description": "Officia fugiat occaecat et do labore cupidatat commodo. Sint dolore enim eu sint tempor dolor commodo excepteur fugiat duis. Consectetur laboris veniam ipsum elit est est tempor ea laborum elit dolore dolore eiusmod nostrud. Incididunt laboris quis pariatur eu ex pariatur quis. Do eu aute ad mollit tempor. Id eu duis pariatur labore esse laborum laboris.\r\n" }, { "id": "5c9b809f8a6f69c09a866873", "title": "<NAME>", "city": "Columbus", "description": "Reprehenderit non qui reprehenderit excepteur do dolor id minim exercitation in. Aute adipisicing laborum non dolore ut nisi officia irure amet mollit duis nostrud culpa consectetur. Dolor ipsum dolor fugiat sit labore magna nisi reprehenderit enim do laborum. Quis consectetur anim laboris non deserunt aliquip ullamco velit excepteur. Esse et exercitation ex ad ea proident aute voluptate pariatur non fugiat quis minim esse.\r\n" }, { "id": "5c9b809f356f94435586d9f4", "title": "<NAME>", "city": "Marshall", "description": "Duis consequat occaecat esse consectetur irure irure esse. Laborum enim nulla consequat consectetur sint ad anim deserunt aute laborum velit elit ex. Est quis dolore duis consectetur mollit laboris. Ex eiusmod enim mollit qui ea id mollit fugiat sint tempor veniam et cupidatat. Tempor eiusmod sit reprehenderit sunt elit ex laborum ad proident dolore labore velit irure. Eu nulla adipisicing reprehenderit et enim nostrud qui amet. Mollit ex fugiat mollit quis.\r\n" } ] }, { "id": "5c9b809f1686f6b2da7a0d32", "category_title": "Letitia", "elements": [ { "id": "<KEY>", "title": "<NAME>", "city": "Alamo", "description": "Irure consectetur aliqua exercitation ea eiusmod. Proident duis fugiat eu pariatur laboris enim velit dolore. Sunt nisi velit nostrud ex veniam eiusmod cillum.\r\n" }, { "id": "<KEY>", "title": "<NAME>", "city": "Williamson", "description": "Voluptate fugiat velit sunt nulla dolor excepteur anim anim amet nisi ipsum consequat. Officia excepteur aute sit adipisicing laboris labore veniam enim. Cillum ipsum aliquip aliqua pariatur. Ipsum veniam Lorem tempor ex commodo qui excepteur labore reprehenderit tempor minim culpa incididunt. Est enim cillum consectetur est laboris deserunt fugiat quis velit in magna eu ipsum.\r\n" }, { "id": "5c9b809f0ceecdcb59afc423", "title": "<NAME>", "city": "Utting", "description": "Ad excepteur nostrud enim ad aliqua tempor labore elit esse. Commodo aute non aliquip enim ea non et commodo consequat pariatur ea nostrud eu. Nostrud incididunt laboris aliqua amet incididunt deserunt sit officia.\r\n" }, { "id": "5c9b809f936f2ecdc99df60e", "title": "<NAME>", "city": "Westerville", "description": "Magna aliqua officia occaecat deserunt enim cupidatat ea irure voluptate eu elit. Anim eiusmod mollit quis labore. Fugiat nulla consectetur sunt magna labore. Sint quis sint excepteur ipsum proident nostrud aute anim qui. Cillum eu voluptate est ipsum officia magna do id tempor aliquip amet dolore sit. Cillum laboris aliqua nisi cupidatat officia. Commodo voluptate aute exercitation do occaecat ut do ea quis.\r\n" }, { "id": "5c9b809feafce82d155c0cfe", "title": "<NAME>", "city": "Watrous", "description": "Aliqua qui Lorem cillum commodo duis duis cupidatat occaecat exercitation esse est amet. Magna sunt cillum dolor commodo esse quis esse consectetur ex ea. Ex sint duis anim occaecat velit excepteur irure.\r\n" }, { "id": "5c9b809f7c21383c877f32b2", "title": "<NAME>", "city": "Outlook", "description": "Aliqua pariatur culpa labore consectetur deserunt do magna ullamco culpa qui dolor. Aliqua occaecat ipsum quis quis proident minim incididunt magna. Voluptate exercitation officia velit dolore consectetur incididunt excepteur ipsum esse exercitation. Ut fugiat occaecat aliquip anim aute magna id ea et ut laboris reprehenderit. Est in elit velit pariatur exercitation cupidatat elit cillum.\r\n" } ] } ] }, { "id": "5c9b809f2b730c903b19ef1f", "category_title": "CAT_5", "child_categories": [ { "id": "5c9b809fd8e86e99c8fc6384", "category_title": "Bridget", "elements": [ { "id": "5c9b809f6689734d498b0518", "title": "<NAME>", "city": "Walton", "description": "Do nisi minim non adipisicing esse eiusmod sunt dolore consequat. Nulla pariatur ea ut adipisicing nisi amet tempor. Ad ullamco reprehenderit occaecat tempor.\r\n" }, { "id": "5c9b809f0a1f9ccf70f76a64", "title": "<NAME>", "city": "Turah", "description": "Eiusmod exercitation magna ut commodo aliqua voluptate ullamco adipisicing in proident. Esse quis nulla culpa pariatur elit aute dolore ex qui non. Esse nulla commodo ex sit qui amet cillum consectetur minim nulla. Ea deserunt nulla aute ea proident esse exercitation duis labore occaecat elit quis. Eu enim labore enim excepteur sunt amet Lorem fugiat cupidatat velit enim fugiat nulla ut.\r\n" }, { "id": "<KEY>", "title": "<NAME>", "city": "Crisman", "description": "Dolor anim anim cillum esse minim ea aliquip laboris cillum elit nisi. Dolor dolore adipisicing ullamco sint qui cupidatat exercitation adipisicing dolore dolore. Do quis pariatur veniam commodo dolor dolor proident aute eiusmod. Aliquip irure nisi esse exercitation. Ex fugiat cillum eiusmod aliquip magna cupidatat deserunt ex. Sit mollit aliquip incididunt sit ut aliquip.\r\n" }, { "id": "5c9b809f25ffe6ed8644ab70", "title": "<NAME>", "city": "Frank", "description": "Fugiat sit proident id aliquip laboris ut. Nulla deserunt sit esse est. Excepteur aliquip sunt aliqua adipisicing exercitation proident aliqua sint irure officia. Non qui excepteur nulla aute nisi do voluptate commodo cillum cupidatat id velit Lorem sit. Deserunt deserunt sint eu dolor exercitation nostrud eiusmod adipisicing sint Lorem id et commodo. Minim duis exercitation excepteur aliquip nulla.\r\n" }, { "id": "<KEY>", "title": "<NAME>", "city": "Babb", "description": "Minim sit elit magna consectetur elit laboris. Ullamco deserunt proident do pariatur cillum. Deserunt eiusmod deserunt magna cillum pariatur do velit aliquip sint.\r\n" }, { "id": "<KEY>", "title": "<NAME>", "city": "Mapletown", "description": "Sunt sit reprehenderit adipisicing ullamco cupidatat minim sit excepteur magna. Est adipisicing adipisicing fugiat in incididunt exercitation est sunt. Esse qui commodo ad ad quis ex do tempor eiusmod ipsum magna anim incididunt commodo. Enim officia minim commodo deserunt veniam fugiat nostrud dolore et laborum ut exercitation. Non eiusmod incididunt nostrud aliqua nisi nisi nulla eu nostrud ea consectetur irure et sint.\r\n" } ] }, { "id": "5c9b809f44a6b79d65c2cf5a", "category_title": "Karina", "elements": [ { "id": "5c9b809f2b6ba5b4601e8019", "title": "<NAME>", "city": "Haring", "description": "Nostrud ex magna amet in magna duis elit. Officia amet anim dolore tempor non fugiat nisi tempor nulla nostrud labore voluptate excepteur exercitation. Commodo Lorem reprehenderit excepteur veniam enim eu et adipisicing irure laborum laboris eu.\r\n" }, { "id": "5c9b809f0d31f6a049c86f28", "title": "<NAME>", "city": "Gloucester", "description": "Fugiat enim amet in cillum aliqua. Lorem enim veniam elit irure non occaecat nostrud labore ad non. Aliqua excepteur tempor irure proident non et Lorem. Nostrud enim enim cupidatat eu. Pariatur est deserunt commodo dolore cupidatat amet ut pariatur qui tempor tempor anim. Anim irure commodo amet consequat ipsum nulla minim mollit est cillum ullamco.\r\n" }, { "id": "5c9b809fbff1772907b11452", "title": "<NAME>", "city": "Naomi", "description": "Culpa sit laborum Lorem deserunt. Pariatur occaecat occaecat ipsum velit qui. Enim veniam voluptate laborum excepteur elit velit irure tempor esse excepteur nisi consequat aliquip id. Ut aliquip pariatur nulla non.\r\n" }, { "id": "5c9b809f07b3a955a3adce78", "title": "<NAME>", "city": "Sharon", "description": "Id qui ullamco dolor deserunt proident veniam ullamco sint aliqua officia. Eu dolore aliqua elit id dolore laboris adipisicing sit enim ad eu proident eu. Enim mollit sunt et in irure et eiusmod magna ex sunt fugiat eu dolor adipisicing.\r\n" }, { "id": "5c9b809fb07915eb613932b7", "title": "<NAME>", "city": "Rew", "description": "Ad exercitation velit eu voluptate officia quis et officia laboris in. Et ex incididunt non duis sit adipisicing. Aliquip sit qui proident consequat nulla. Laborum labore sit consectetur id est aliquip exercitation enim adipisicing irure.\r\n" }, { "id": "5c9b809f8ab92b6a7c929d80", "title": "<NAME>", "city": "Coinjock", "description": "Reprehenderit cillum aliqua nostrud id ad. Laboris proident sit est minim nulla nulla anim mollit cupidatat. Nisi tempor eiusmod ipsum duis pariatur dolore tempor deserunt occaecat. Ex voluptate dolore mollit exercitation sunt. Nulla anim sit enim Lorem laboris pariatur elit commodo.\r\n" } ] }, { "id": "5c9b809f535b9cebe0bee64b", "category_title": "Ryan", "elements": [ { "id": "5c9b809f07f6a1922011928a", "title": "<NAME>", "city": "Orin", "description": "Anim nostrud esse eu nostrud veniam veniam elit ut eiusmod ex in. Labore cillum adipisicing in deserunt ullamco est anim dolor pariatur quis. Eiusmod sunt incididunt est magna fugiat in enim sunt reprehenderit irure eiusmod. Cillum elit qui labore proident culpa occaecat magna sint.\r\n" }, { "id": "5c9b809fb4dd2b5d8ad66c1e", "title": "<NAME>", "city": "Sutton", "description": "Excepteur exercitation velit commodo reprehenderit minim occaecat magna consequat incididunt ut nostrud esse quis velit. Laboris sint magna voluptate voluptate irure culpa commodo non commodo adipisicing. Laborum irure ut magna fugiat culpa anim pariatur. Anim id Lorem fugiat ullamco consectetur incididunt voluptate esse ex quis laborum voluptate Lorem non. Lorem ut deserunt commodo ea incididunt anim ea enim eiusmod reprehenderit laboris non pariatur exercitation.\r\n" }, { "id": "5c9b809fcefca74c116981cc", "title": "<NAME>", "city": "Gibsonia", "description": "Esse adipisicing occaecat laboris nulla amet tempor ea consequat cillum. Voluptate quis culpa aliqua sit commodo esse nostrud deserunt laborum esse anim veniam culpa. Velit quis mollit enim ut cupidatat et in minim do non esse sint sunt fugiat. Laboris consectetur nulla duis amet ullamco ut culpa ex excepteur laborum. Amet elit sint commodo consequat qui ipsum veniam reprehenderit esse culpa aute. Cillum sint consectetur laborum quis Lorem ipsum ex mollit dolor officia in magna. Irure minim quis ut ipsum cillum magna proident et velit eiusmod irure.\r\n" }, { "id": "5c9b809f22f9c63fd615395d", "title": "<NAME>", "city": "Eagletown", "description": "Do duis commodo eu sunt laboris proident voluptate cupidatat mollit. Laborum voluptate cupidatat eiusmod sit in excepteur. Eiusmod nostrud cillum eu ad ipsum ullamco dolor exercitation. Aliqua et ut culpa deserunt deserunt sint aliquip. Sunt laborum in ea id. Do sint sit aliquip anim nisi sunt proident officia tempor. Aliqua fugiat sunt excepteur esse nostrud ullamco ex culpa ex velit veniam do sit.\r\n" }, { "id": "5c9b809f126b14c00aaffbfb", "title": "<NAME>", "city": "Norwood", "description": "Aliquip ad ea officia sit irure sint. Irure commodo non est aute aliquip ad pariatur. Culpa eiusmod enim esse Lorem.\r\n" }, { "id": "5c9b809f49f9e1165073c074", "title": "<NAME>", "city": "Jamestown", "description": "Elit Lorem aute ut pariatur ullamco duis dolor irure in sunt esse nostrud veniam. Velit ad pariatur incididunt sunt culpa proident aliquip. Amet incididunt fugiat duis sunt magna mollit culpa est nostrud dolor ipsum ea elit non. Sit proident pariatur dolore proident laboris aliqua dolore nisi irure aliqua nisi dolor officia. Minim fugiat laboris velit magna esse et. In eiusmod nisi deserunt occaecat incididunt anim pariatur reprehenderit qui elit Lorem do ut deserunt. Lorem cupidatat laboris veniam minim laborum laborum.\r\n" } ] }, { "id": "5c9b809fae6b81a56ad3bdee", "category_title": "Alexis", "elements": [ { "id": "5c9b809fe1f5b372062b54b8", "title": "<NAME>", "city": "Hayes", "description": "Aliqua magna eiusmod ullamco ex incididunt nisi cupidatat. Dolor aute velit dolor tempor commodo do consectetur sit velit. Eiusmod ea incididunt eiusmod exercitation officia incididunt sint velit non. Ipsum et culpa ullamco ad aliquip. Fugiat officia amet pariatur eiusmod consectetur anim voluptate quis ad quis consectetur. Duis esse tempor non officia sunt consequat consequat excepteur cupidatat. Ad non magna Lorem qui.\r\n" }, { "id": "5c9b809f6eb3a904b2113c52", "title": "<NAME>", "city": "Mooresburg", "description": "Lorem irure est officia laborum fugiat mollit anim cupidatat duis. Deserunt eu veniam pariatur amet mollit irure velit do pariatur eiusmod nostrud eiusmod. Do reprehenderit reprehenderit nisi amet magna.\r\n" }, { "id": "5c9b809f13e7b08e1b903022", "title": "<NAME>", "city": "Williams", "description": "Nisi veniam consequat elit esse magna. Fugiat id consectetur ullamco culpa mollit aliquip ut sit Lorem. Et do velit sunt amet consectetur sunt. Labore deserunt deserunt enim adipisicing culpa non veniam est elit ut aliquip. Consectetur enim dolor Lorem mollit dolor labore dolor excepteur excepteur labore nulla ut. Occaecat et occaecat officia eu elit elit mollit aute officia proident. Cillum minim minim do elit velit et enim et ipsum aliqua dolor.\r\n" }, { "id": "5c9b809fd2a145b4cc9bc34f", "title": "<NAME>", "city": "Rosine", "description": "Quis laborum irure laborum laborum adipisicing mollit non esse velit ex cillum aliqua laborum fugiat. Commodo aliqua eu qui irure tempor proident esse cupidatat. Quis excepteur laborum aliquip est Lorem cupidatat consequat dolore est enim voluptate nisi reprehenderit. Pariatur laboris nostrud magna sunt aliquip pariatur. Nulla reprehenderit nisi ea cillum adipisicing sint aliquip officia id id minim. Non proident nostrud laboris mollit ex non ullamco dolore laborum magna Lorem. Ipsum excepteur laboris laboris est quis reprehenderit consectetur sit.\r\n" }, { "id": "5c9b809f52c4fc47109090fe", "title": "<NAME>", "city": "Magnolia", "description": "Sunt dolore voluptate nostrud veniam exercitation. Dolore ipsum qui enim ea enim deserunt mollit mollit voluptate enim pariatur. Deserunt consequat eu consequat esse Lorem non enim tempor duis veniam magna eiusmod incididunt id.\r\n" }, { "id": "<KEY>", "title": "<NAME>", "city": "Lydia", "description": "Magna aliqua commodo anim anim dolore. Velit anim aliquip ex labore incididunt pariatur eu proident excepteur in ut. Non in fugiat commodo ut ad elit excepteur enim dolore velit voluptate qui.\r\n" } ] } ] } ]; const Actions = { fetchCategories: () => { let categories = Data.map((e)=>{ return e.category_title; }); //console.log(categories); return { type:Constants.FETCH_CATEGORIES, data:Data // axios.get('/api/v1/fetchCategories') // .then(function (response) { // dispatch({ // type: Constants.FETCH_RENTALS, // data: response.data // }) // }) // .catch(function (error) { // console.log(error); // }); } }, getItemsByCategoryId: (cat_id){ } // addRental: (data) => { // return { // type: Constants.FETCH_RENTALS, // data: Rentals.push(data) // } // }, // fetchRentalById: (id) => { // return (dispatch) => { // axios.get('/api/v1/rentals/' + id) // .then(function (response) { // dispatch({ type: Constants.FETCH_RENTAL_BY_ID, data: response.data }) // }) // .catch(function (error) { // console.log(error); // }); // } // }, // addpost: (data) => { // return { // type: 'ADD_TYPE', // data: data // } // } } export default Actions;<file_sep>/README.md # ReactDatanomist Small application React Redux <file_sep>/src/constants/constants.js const Constants = { FETCH_CATEGORIES: 'FETCH_CATEGORIES', FETCH_CATEGORIES_BY_ID: 'FETCH_CATEGORIES_BY_ID', } export default Constants;
06fac53fc1ffd92b159b977dfc1b3733876cef08
[ "JavaScript", "Markdown" ]
3
JavaScript
aligarian/ReactDatanomist
c4cd5432a36af0beefadc9641a0828c8801b04f7
8270e42099c3acb1796b84aba74c048af2a840ec
refs/heads/master
<file_sep>import React, { Component } from 'react'; class Footer extends Component { // constructor() { // super(); // console.log('FooterComponent is created'); // } render() { // console.log('FooterComponent is being rendered..'); return ( <footer className="App-footer"> <div className="wrapper"> <h4>App created with React by <NAME> for Juno College, 2020. &copy;</h4> <h5>API courtesy of Ticketmaster &copy; | Photo by <NAME> on Unsplash</h5> </div> </footer> ); } } export default Footer;
ab3d87e72caa30d2b888e19a22e701f7d3d04ed1
[ "JavaScript" ]
1
JavaScript
FabioDwyer/project5
897f61b0aa0759dbef77ef5b07036f7eee895776
a50d1daff3205cc8583e553b922bf4f8a4d7c4d0
refs/heads/master
<repo_name>gunyarakun/mid2flmml<file_sep>/mid2flmml.py FILE_NAME = 'tekito.mid' import midi notes = ['C', 'C+', 'D', 'D+', 'E', 'F', 'F+', 'G', 'G+', 'A', 'A+', 'B'] globals = [] channels = [[] for d in 17 * [None]] channel_stats = [{ 'note': None, 'note_on_time': None, 'note_off_time': None, 'velocity': None, 'octave': None, } for d in 17 * [None]] def pitch_to_octave_and_note(pitch): return [pitch / 12, notes[pitch % 12]] def add_length(e, note, from_time, tpq): if not note: raise 'note is none' td = e.time - from_time if td == 0: if note != 'R': raise 'no time diff' return while td > tpq: channels[e.channel].append(note) td -= tpq if td > 0: channels[e.channel].append('&') if td > 0: channels[e.channel].append(note) channels[e.channel].append(str(int(((tpq / td) * 4)))) def add_octave_and_note(event, octave, pitch, tpq): if channel_stats[e.channel]['note_on_time']: print 'WARNING!: detect waon.' return cmd = '' if channel_stats[e.channel]['note_off_time']: add_length(e, 'R', channel_stats[e.channel]['note_off_time'], tpq) if channel_stats[e.channel]['velocity'] != e.velocity: channels[e.channel].append('@V%d' % e.velocity) channel_stats[e.channel]['velocity'] = e.velocity octave, note = pitch_to_octave_and_note(e.pitch) if channel_stats[e.channel]['octave']: od = octave - channel_stats[e.channel]['octave'] else: od = None channel_stats[e.channel]['octave'] = octave if od == 1: channels[e.channel].append('<') elif od == 0: pass elif od == -1: channels[e.channel].append('>') else: channels[e.channel].append('O%d' % octave) channel_stats[e.channel]['note'] = note channel_stats[e.channel]['note_on_time'] = e.time channel_stats[e.channel]['note_off_time'] = None def note_off(e, tpq): add_length(e, channel_stats[e.channel]['note'], channel_stats[e.channel]['note_on_time'], tpq) channel_stats[e.channel]['note'] = None channel_stats[e.channel]['note_on_time'] = None channel_stats[e.channel]['note_off_time'] = e.time mid = midi.MidiFile() mid.open(FILE_NAME) mid.read() for track in mid.tracks: for e in track.events: if e.type == 'SEQUENCE_TRACK_NAME': globals.append('/* ' + e.data + ' */\n') elif e.type == 'COPYRIGHT_NOTICE': globals.append('/* ' + e.data + ' */\n') elif e.type == 'DeltaTime': pass elif e.type == 'SET_TEMPO': secPerQuarterNote = midi.getNumber(e.data, 3)[0] / 1000000.0 if mid.ticksPerQuarterNote: print "tpq: %d" % mid.ticksPerQuarterNote tpq = float(mid.ticksPerQuarterNote) else: print "tps: %d" % mid.ticksPerSecond tpq = mid.ticksPerSecond * secPerQuarterNote tempo = 60.0 / secPerQuarterNote print "tempo: %d" % tempo globals.append('T%d' % tempo) elif e.type == 'PROGRAM_CHANGE': # TODO: http://noike.info/~kenzi/cgi-bin/mml2mp3/doc/FlMML_to_mml2mid.html # globals.append('/* program change ' + str(e.data) + ' */') pass elif e.type == 'CONTROLLER_CHANGE': # TODO: like PITCH_BEND pass elif e.type == 'PITCH_BEND': if channel_stats[e.channel]['note_on_time']: if channel_stats[e.channel]['note_on_time'] != e.time: note_off(e, tpq) channels[e.channel].append('&') octave, note = pitch_to_octave_and_note(e.pitch) add_octave_and_note(e, octave, note, tpq) elif e.type == 'NOTE_ON': octave, note = pitch_to_octave_and_note(e.pitch) add_octave_and_note(e, octave, note, tpq) elif e.type == 'NOTE_OFF': note_off(e, tpq) elif e.type == 'END_OF_TRACK': pass else: print e # output print ''.join(globals) for i in channels: if len(i) > 0: print ''.join(i) print ';\n' mid.close()
e439df7139ed2be8d6331b56c9f4cedace53bdbf
[ "Python" ]
1
Python
gunyarakun/mid2flmml
5f20988a55933a93d0752e96b921dc7f9835efb2
67a715164564001ec559022bf1197c22b2e40629
refs/heads/master
<repo_name>Eventgithub/Server_Check<file_sep>/src/main/java/com.cxyz.check/entity/TaskInfo.java package com.cxyz.check.entity; import com.cxyz.check.util.date.Date; import com.cxyz.check.util.date.DateTime; import java.util.ArrayList; import java.util.List; /** * Created by 夏旭晨 on 2018/9/23. * 考勤任务基本信息 */ public class TaskInfo { private String id;//考勤任务编号 private String name;//考勤任务名称 private User sponsor = new User();//考勤任务发起人 private User checker = new User();//考勤任务考勤人 private DateTime start;//考勤开始时间 private DateTime len;//考勤时限 private Date end;//最后一次的考勤日期(预留) private ClassRoom room;//考勤所在地 private Integer type;//考勤任务类型,临时任务或者课程 private Grade grade = new Grade();//考勤班级 /* * 当前考勤任务的所有考勤情况 */ private List<TaskCompletion> completions = new ArrayList<TaskCompletion>(); public String getId() { return id; } public void setId(String id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public User getSponsor() { return sponsor; } public void setSponsor(User sponsor) { this.sponsor = sponsor; } public User getChecker() { return checker; } public void setChecker(User checker) { this.checker = checker; } public DateTime getStart() { return start; } public void setStart(DateTime start) { this.start = start; } public DateTime getLen() { return len; } public void setLen(DateTime len) { this.len = len; } public Date getEnd() { return end; } public void setEnd(Date end) { this.end = end; } public Integer getType() { return type; } public void setType(Integer type) { this.type = type; } public Grade getGrade() { return grade; } public void setGrade(Grade grade) { this.grade = grade; } public List<TaskCompletion> getCompletions() { return completions; } public void setCompletions(List<TaskCompletion> completions) { this.completions = completions; } public ClassRoom getRoom() { return room; } public void setRoom(ClassRoom room) { this.room = room; } @Override public String toString() { return "TaskInfo{" + "id='" + id + '\'' + ", name='" + name + '\'' + ", sponsor=" + sponsor + ", checker=" + checker + ", start=" + start + ", len=" + len + ", end=" + end + ", room=" + room + ", type=" + type + ", grade=" + grade + ", completions=" + completions + '}'; } } <file_sep>/src/test/java/com/cxyz/check/dao/TeacherDaoTest.java package com.cxyz.check.dao; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import javax.annotation.Resource; @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration({"classpath:spring/spring_dao.xml"}) public class TeacherDaoTest { @Resource private TeacherDao teacherDao; @Test public void getTeaById() { System.out.print(teacherDao.getTeaById("17478093")); } }<file_sep>/src/main/java/com.cxyz.check/exception/GradeException.java package com.cxyz.check.exception; /** * 班级操作时可能会抛出的异常 */ public class GradeException extends RuntimeException{ public GradeException() { } public GradeException(String message) { super(message); } public GradeException(String message, Throwable cause) { super(message, cause); } public GradeException(Throwable cause) { super(cause); } } <file_sep>/src/main/java/com.cxyz.check/enums/GradeErrorEnum.java package com.cxyz.check.enums; public enum GradeErrorEnum { GRADENOTFOUND("无此班级"),INNERERROR("服务器内部异常"); private String msg; public String getMsg() { return msg; } public void setMsg(String msg) { this.msg = msg; } private GradeErrorEnum(String msg) { this.msg = msg; } } <file_sep>/src/main/java/com.cxyz.check/entity/ClassRoom.java package com.cxyz.check.entity; /** * Created by 夏旭晨 on 2018/9/23. */ public class ClassRoom { private Integer id;//教室编号 private String name;//教室名称 private College college;//所属学院 private Integer state;//是否空闲状态(预留字段) public ClassRoom(){} public ClassRoom(Integer id){ setId(id); } public College getCollege() { return college; } public void setCollege(College c) { college = c; } public Integer getState() { return state; } public void setState(Integer state) { this.state = state; } public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } @Override public String toString() { return "ClassRoom{" + "id=" + id + ", name='" + name + '\'' + ", college=" + college + ", state=" + state + '}'; } } <file_sep>/src/main/java/com.cxyz.check/entity/User.java package com.cxyz.check.entity; /** * Created by 夏旭晨 on 2018/9/23. */ public class User { private String id;//编号 private String name;//姓名 private String sex;//性别 private String pwd;//密码 private String phone;//电话号码 private String photo;//照片的url /** * power属性用来区分权限 * 0为普通学生权限 * 5为考勤人权限 * 30为普通任课老师权限 * 35为班主任权限 * 45为系部管理员权限 * 55为校级管理员权限 * 100为超级管理员权限 */ private Integer power; /** * 用户类型 */ private Integer type; public String getId() { return id; } public void setId(String id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getSex() { return sex; } public void setSex(String sex) { this.sex = sex; } public String getPwd() { return pwd; } public void setPwd(String pwd) { this.pwd = pwd; } public String getPhone() { return phone; } public void setPhone(String phone) { this.phone = phone; } public String getPhoto() { return photo; } public void setPhoto(String photo) { this.photo = photo; } public Integer getPower() { return power; } public void setPower(Integer power) { this.power = power; } @Override public String toString() { return "User{" + "id='" + id + '\'' + ", name='" + name + '\'' + ", sex='" + sex + '\'' + ", pwd='" + pwd + '\'' + ", phone='" + phone + '\'' + ", photo='" + photo + '\'' + ", power=" + power + ", type=" + type + '}'; } } <file_sep>/src/main/java/com.cxyz.check/entity/Student.java package com.cxyz.check.entity; /** * Created by 夏旭晨 on 2018/9/23. * 学生实体 */ public class Student extends User { //更多信息在User中 private Grade grade;//所属班级 private String collegeName;//学院名称 public Student(){ this(null); } public Student(String id){ this(id,null); } public Student(String id,String pwd) { if(id != null) this.setId(id); if(pwd != null) this.setPwd(pwd); } public Grade getGrade() { return grade; } public void setGrade(Grade grade) { this.grade = grade; } public String getCollegeName() { return collegeName; } public void setCollegeName(String collegeName) { this.collegeName = collegeName; } @Override public String toString() { return "Student{" +super.toString()+ "grade=" + grade + ", collegeName='" + collegeName + '\'' + '}'; } } <file_sep>/src/test/java/com/cxyz/check/dao/StudentDaoTest.java package com.cxyz.check.dao; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import javax.annotation.Resource; import static org.junit.Assert.*; @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration({"classpath:spring/spring_dao.xml"}) public class StudentDaoTest { @Resource private StudentDao studentDao; @Test public void getStuById() { System.out.print(studentDao.getStuById("17478093")); //测试结果: /* Student{User{id='17478093', name='夏旭晨', sex='男', pwd='<PASSWORD>', phone='17779911413', photo='111', power=5, type=0}grade=Grade [name=null, college=null, headTeacher=null, classRoom=null, id=122], collegeName='信计学院'} */ } @Test public void getStusByGrade() { System.out.print(studentDao.getStusByGrade(122)); //测试结果: /* [Student{User{id='17478063', name='陈宸', sex='男', pwd='<PASSWORD>', phone='null', photo='null' , power=0, type=0}grade=Grade [name=null, college=null , headTeacher=null, classRoom=null, id=122], collegeName='null' }, Student{User{id='17478090', name='张奕文', sex='null', pwd='<PASSWORD>' , phone='null', photo='null', power=0, type=0}grade=Grade [name=null, college=null, headTeacher=null, classRoom=null, id=122], collegeName='null'}, Student{User{id='17478091', name='喻济生', sex='男', pwd='<PASSWORD>', phone='null', photo='null', power=0, type=0}grade=Grade [name=null, college=null, headTeacher=null, classRoom=null, id=122], collegeName='null'}, Student{User{id='17478093', name='夏旭晨', sex='男', pwd='<PASSWORD>', phone='17779911413', photo='111', power=5, type=0}grade=Grade [name=null, college=null, headTeacher=null , classRoom=null, id=122], collegeName='信计学院'} */ } }<file_sep>/src/main/java/com.cxyz.check/entity/College.java package com.cxyz.check.entity; /** * Created by 夏旭晨 on 2018/9/23. */ public class College { private Integer id;//学院编号 private String name;//学院名称 private School school;//所属学校 private Teacher manager;//系部管理员 public College(){} public College(Integer id){ this.id = id; } public Integer getId() { return id; } public void setId(Integer _id) { this.id = _id; } public String getName() { return name; } public void setName(String _name) { this.name = _name; } public School getSchool() { return school; } public void setSchool(School school) { this.school = school; } public Teacher getManager() { return manager; } public void setManager(Teacher manager) { this.manager = manager; } @Override public String toString() { return "College [_id=" + id + ", _name=" + name + ", school=" + school + ", manager=" + manager + "]"; } } <file_sep>/src/test/java/com/cxyz/check/service/UserServiceTest.java package com.cxyz.check.service; import com.cxyz.check.dto.UserDto; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import static org.junit.Assert.*; @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration( {"classpath:spring/spring_dao.xml", "classpath:spring/spring-service.xml"} ) public class UserServiceTest { @Autowired private UserService userService; @Test public void login() { System.out.print(userService.login("17478093", "123456", UserDto.STUDENT)); /**测试结果:成功 * UserDto{id='17478093', name='夏旭晨', sex='男' * , phone='17779911413', photo='111', power=5, * type=0, error='null', CollegeName='信计学院', * collegeId='null', gradeId=122, gradeName='null'} */ } @Test public void getGradeStus() { System.out.print(userService.getGradeStus(122)); /**测试结果:成功 * [UserDto{id='17478063', name='陈宸', * sex='男', phone='null', photo='null', * power=0, type=0, error='null', CollegeName='null', * collegeId='null', gradeId=122, gradeName='null'}, * UserDto{id='17478090', name='张奕文', sex='null', * phone='null', photo='null', power=0, type=0, error='null', * CollegeName='null', collegeId='null', gradeId=122, gradeName='null'}, * UserDto{id='17478091', name='喻济生', sex='男', phone='null', * photo='null', power=0, type=0, error='null', CollegeName='null', * collegeId='null', gradeId=122, gradeName='null'}, * UserDto{id='17478093', name='夏旭晨', sex='男', * phone='17779911413', photo='111', power=5, type=0, * error='null', CollegeName='信计学院', collegeId='null', * gradeId=122, gradeName='null'}] */ } }<file_sep>/src/main/java/com.cxyz.check/service/impl/UserServiceImpl.java package com.cxyz.check.service.impl; import com.cxyz.check.dao.StudentDao; import com.cxyz.check.dao.TeacherDao; import com.cxyz.check.dto.UserDto; import com.cxyz.check.entity.Student; import com.cxyz.check.entity.Teacher; import com.cxyz.check.exception.GradeNotFoundException; import com.cxyz.check.exception.PasswordErrorException; import com.cxyz.check.exception.UserNotFoundException; import com.cxyz.check.service.UserService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import java.util.ArrayList; import java.util.List; @Service public class UserServiceImpl implements UserService { @Autowired private StudentDao studentDao; @Autowired private TeacherDao teacherDao; @Override public UserDto login(String id, String password, int type) { if(type == UserDto.STUDENT) { Student stu = studentDao.getStuById(id); if(stu == null) throw new UserNotFoundException(); if(stu.getPwd().equals(password)) { return new UserDto(stu); } }else if(type == UserDto.TEACHER) { Teacher tea = teacherDao.getTeaById(id); if(tea == null) if(tea.getPwd().equals(password)) { return new UserDto(tea); } } throw new PasswordErrorException(); } @Override public List<UserDto> getGradeStus(int gradeId) { List<Student> stus = studentDao.getStusByGrade(gradeId); //如果查询不到对象,返回空 if (stus != null) { if (!stus.isEmpty()) { List<UserDto> userDtos = new ArrayList<UserDto>(); UserDto dto = null; for (Student stu : stus) { dto = new UserDto(stu); userDtos.add(dto); } return userDtos; } } throw new GradeNotFoundException(); } } <file_sep>/src/test/java/com/cxyz/check/dao/TaskInfoDaoTest.java package com.cxyz.check.dao; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import javax.annotation.Resource; @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration({"classpath:spring/spring_dao.xml"}) public class TaskInfoDaoTest { @Resource private TaskInfoDao taskInfoDao; @Test public void getTaskInfos() { System.out.print(taskInfoDao.getTaskInfos(122)); } @Test public void addTasks() { } }<file_sep>/src/main/java/com.cxyz.check/dao/TeacherDao.java package com.cxyz.check.dao; import com.cxyz.check.entity.Teacher; import org.apache.ibatis.annotations.Param; //测试成功 public interface TeacherDao { /** * 通过工号获取老师信息 * @param id 老师工号 * @return 单个老师的所有信息 */ public Teacher getTeaById(@Param("id") String id); } <file_sep>/src/main/resources/spring/jdbc.properties jdbc.driverClassName=com.mysql.jdbc.Driver jdbc.url=jdbc:mysql://localhost:3306/untilchecked?useUnicode=true&characterEncoding=UTF-8&allowMultiQueries=true jdbc.username=root jdbc.password=<PASSWORD> <file_sep>/src/main/java/com.cxyz.check/dao/TaskCompletionDao.java package com.cxyz.check.dao; import com.cxyz.check.entity.TaskCompletion; import org.apache.ibatis.annotations.Param; import java.util.List; public interface TaskCompletionDao { /** * 通过考勤基本信息的id获取所有的完成情况 * @param tid 考勤基本信息的id * @return */ List<TaskCompletion> getCompByTID(@Param("tid") String tid); /** * 通过考勤完成情况的id获取完整的考勤情况信息 * @param id 考勤完成情况id * @return */ TaskCompletion getTaskCompById(@Param("id")int id); /** * 添加考勤任务的考勤完成情况 * @param taskCompletions * @return */ void addTasksOfComp(@Param("comp") List<TaskCompletion> comp); }
192637c1b1b3f0ebd807c2b182897daeb0026fda
[ "Java", "INI" ]
15
Java
Eventgithub/Server_Check
1cde0f182821643f74c7c5c7b882059b51cbeddd
aa942952cc9550d2ca94264c099cf631748e4dd3
refs/heads/master
<file_sep>from distutils.core import setup setup(name='django-versioned-media-tag', version='0.2', url='http://github.com/alexvasi/django-versioned-media-tag', description='Django tag to include media files versioned with modification date.', packages=['versioned_media', 'versioned_media.templatetags']) <file_sep>import os from django.conf import settings from django import template URL_TEMPLATE = getattr(settings, 'VERSIONED_MEDIA_URL_TEMPLATE', '%(path)s%(name)s%(.ext)s?%(version)d') register = template.Library() @register.simple_tag def versioned_media(path): """ Allows auto versioning of files based on modification date. Usage:: {% versioned_media "js/script.js" %} """ fullpath = os.path.join(settings.MEDIA_ROOT, path) try: modification_time = os.path.getmtime(fullpath) except OSError: # file not found if settings.DEBUG: raise else: modification_time = 404 # be silent in production path, name = os.path.split(path) name, ext = os.path.splitext(name) if path: path += '/' url = URL_TEMPLATE % {'path': path, 'name': name, '.ext': ext, 'version': modification_time} return settings.MEDIA_URL + url <file_sep>django-versioned-media-tag ========================== Django tag to include media files versioned with modification date. Installation ============ #. Run ``python setup.py install`` or place versioned_media on your PYTHONPATH. #. Add ``'versioned_media'`` to the ``INSTALLED_APPS``. Usage ===== Following template:: {% load versioned_media %} {% versioned_media "styles.css" %} {% versioned_media "js/main.js" %} Will render to this:: http://example.com/static/styles.css?1280260290 http://example.com/static/js/main.js?1280260305 If you want, you can change the format of generated urls. For example, put this line to project's settings.py:: VERSIONED_MEDIA_URL_TEMPLATE = '%(path)s%(name)s.ver%(version)d%(.ext)s' And the mentioned template will render as:: http://example.com/static/styles.ver1280260290.css http://example.com/static/js/main.ver1280260305.js Related docs ============ http://developer.yahoo.com/performance/rules.html#expires
7da7184b5aff0022359e5cf40c1f22b713d48b5c
[ "Python", "reStructuredText" ]
3
Python
alexvasi/django-versioned-media-tag
3d26430f70bd7fc0f8686ed0a3a32d3c89f21309
a83b73c535074075f3c5237760e13d543e831b55
refs/heads/master
<repo_name>dcarballido/PR01<file_sep>/proc/signin.proc.php <?php include "../connection/db_connection.php"; $user = $_REQUEST['user']; $pass = $_REQUEST['password']; $encript = md5($pass); //Entra si está configurada la variable del formulario del login if(isset($_REQUEST['user'])){ // crea INSERT $query1 = "INSERT INTO usuarios (name_usuario, password_usuario) VALUES ('$user', '$<PASSWORD>')"; echo $query1; mysqli_query($conn,$query1); $query2 = "SELECT * FROM usuarios WHERE name_usuario='$user' AND password_usuario='$en<PASSWORD>'"; echo $query2; // ejecuta la query $result = mysqli_query($conn,$query2); //La variable $result debería de tener como mínimo un registro coincidente if(!empty($result) && mysqli_num_rows($result)==1){ echo "string1"; $row = mysqli_fetch_array($result); //Creo una nueva sesión y defino $_SESSION['nombre'] y $_SESSION['id_usuario'] session_start(); $_SESSION['nombre']=$user; $_SESSION['id_usuario']=$row['id_usuario']; //Voy a mi sitio personal header("Location: ../intranet.php"); }else{ echo "string2"; } //Si no está configurada la variable del formulario del login vuelve al index.php }else{ header("Location: ../index.php"); } ?><file_sep>/reserva.php <?php session_start(); $iduser = $_SESSION['id_user']; $name = $_SESSION['nom_us']." ".$_SESSION['cognom_us']; ?> <!DOCTYPE html> <html> <head> <title></title> <meta charset="utf-8"> <link rel="stylesheet" type="text/css" href="css/estilo.css"> </head> <body> <!-- BOTON DE CERRAR SESION DE USUARIO --> <div style="text-align: right;"> <?php //Mantengo la sesión. Por ende puedo utilizar la variable $_SESSION anteriormente configurada if(isset($_SESSION['id_user'])){ echo "<a href='./proc/logout.proc.php'>Cerrar sesión de ".$_SESSION['nom_us']."</a>&nbsp;&nbsp;"; }else{ header("Location: ../index.php"); } ?> </div> <h1>RESERVAS</h1> <!-- ------------------ --> <div> <!-- FORMULARIO PARA INSERTAR LAS RESERVAS DE LOS USUARIOS --> <form action="./insert/insert_reserva.php" method="POST"> ELIGE LA SALA:<br><select background:#ededed name="salas"> <!-- input donde se muestran las salas desde bbdd --> <option value="">Salas</option> <?php include "./connection/db_connection.php"; $qry = "SELECT * FROM tbl_salas"; $result = mysqli_query($conn,$qry); if (!empty($result) && mysqli_num_rows($result)>0) { while ($row = mysqli_fetch_array($result)) { echo "<br>"; echo "<option>".$row['nom_sala']."</option>"; } }else{echo "error";} ?> </select><br><br> ELIGE EL RECURSO:<br><select name="recursos"> <!-- input donde se muestran los recursos desde bbdd --> <option value="">Recursos</option> <?php include "./db_connection.php"; $qry = "SELECT * FROM tbl_recursos"; $result = mysqli_query($conn,$qry); if (!empty($result) && mysqli_num_rows($result)>0) { while ($row = mysqli_fetch_array($result)) { echo "<br>"; echo "<option>".$row['nom_recurs']."</option>"; } }else{echo "error";} ?> </select><br><br> ELIGE FECHA DE INICIO DE RESERVA: <input type="date" name="fecha_ini_res"><br><br> ELIGE FECHA DE FINAL DE RESERVA: <input type="date" name="fecha_fin_res"><br><br> <input type="submit" name="submit" value="Reservar"><br><br> </form> </div> </body> </html><file_sep>/bd/bd_proyecto01.sql -- phpMyAdmin SQL Dump -- version 4.8.5 -- https://www.phpmyadmin.net/ -- -- Servidor: 127.0.0.1 -- Tiempo de generación: 08-11-2019 a las 17:51:10 -- Versión del servidor: 8.0.13 -- Versión de PHP: 7.3.2 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 */; -- -- Base de datos: `bd_proyecto01` -- CREATE DATABASE `bd_proyecto01`; USE bd_proyecto01; -- -------------------------------------------------------- -- -- Estructura de tabla para la tabla `tbl_incidencia` -- CREATE TABLE `tbl_incidencia` ( `id_in` int(11) NOT NULL, `desc_in` text NOT NULL, `fecha_in` date NOT NULL, `id_reserva` int(11) NOT NULL ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 ; -- -- Volcado de datos para la tabla `tbl_incidencia` -- INSERT INTO `tbl_incidencia` (`id_in`, `desc_in`, `fecha_in`, `id_reserva`) VALUES (1, 'Se ha roto el fluorescente de la sala', '2019-11-02', 1), (2, 'Se ha roto el cable del enchufe del proyector', '2019-11-04', 4); -- -------------------------------------------------------- -- -- Estructura de tabla para la tabla `tbl_recursos` -- CREATE TABLE `tbl_recursos` ( `id_recurs` int(11) NOT NULL, `nom_recurs` varchar(25) NOT NULL, `tipo_recurs` enum('MATERIAL INFORMATICO','MATERIAL DEPORTIVO','MATERIAL EDUCATIVO','MATERIAL DE SOPORTE VISUAL') NOT NULL, `desc_recurs` text NOT NULL, `disponibilidad` enum('DISPONIBLE','OCUPADO') NOT NULL DEFAULT 'DISPONIBLE' ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4; -- -- Volcado de datos para la tabla `tbl_recursos` -- INSERT INTO `tbl_recursos` (`id_recurs`, `nom_recurs`, `tipo_recurs`, `desc_recurs`, `disponibilidad`) VALUES (1, 'portatil_01', 'MATERIAL INFORMATICO', '', 'OCUPADO'), (2, 'portatil_02', 'MATERIAL INFORMATICO', '', 'OCUPADO'), (3, 'proyector_01', 'MATERIAL DE SOPORTE VISUAL', '', 'OCUPADO'), (4, 'proyector_02', 'MATERIAL DE SOPORTE VISUAL', '', 'OCUPADO'), (5, 'portatil_03', 'MATERIAL INFORMATICO', '', 'DISPONIBLE'), (6, 'mobil_01', 'MATERIAL INFORMATICO', '', 'DISPONIBLE'), (7, 'mobil_02', 'MATERIAL INFORMATICO', '', 'DISPONIBLE'); -- -------------------------------------------------------- -- -- Estructura de tabla para la tabla `tbl_reserva` -- CREATE TABLE `tbl_reserva` ( `id_reserva` int(11) NOT NULL, `fecha_ini_res` date NOT NULL, `fecha_fin_res` date NOT NULL, `id_recurs` int(11) DEFAULT NULL, `id_user` int(11) NOT NULL, `id_sala` int(11) DEFAULT NULL ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4; -- -- Volcado de datos para la tabla `tbl_reserva` -- INSERT INTO `tbl_reserva` (`id_reserva`, `fecha_ini_res`, `fecha_fin_res`, `id_recurs`, `id_user`, `id_sala`) VALUES (1, '2019-10-30', '2019-11-08', NULL, 1, 1), (2, '2019-10-15', '2019-11-04', NULL, 2, 7), (3, '2019-11-01', '2019-11-05', 1, 4, NULL), (4, '2019-11-04', '2019-11-07', 3, 2, NULL), (5, '2019-10-15', '2019-11-27', NULL, 4, 7), (6, '2019-11-09', '2019-11-10', 1, 4, 1), (7, '2019-11-08', '2019-11-09', 2, 2, 7); -- -------------------------------------------------------- -- -- Estructura de tabla para la tabla `tbl_salas` -- CREATE TABLE `tbl_salas` ( `id_sala` int(11) NOT NULL, `nom_sala` varchar(25) NOT NULL, `tlf_sala` char(9) NOT NULL, `edificio_sala` varchar(40) NOT NULL, `desc_sala` text NOT NULL, `disponibilidad` enum('DISPONIBLE','OCUPADA') NOT NULL DEFAULT 'DISPONIBLE' ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 ; -- -- Volcado de datos para la tabla `tbl_salas` -- INSERT INTO `tbl_salas` (`id_sala`, `nom_sala`, `tlf_sala`, `edificio_sala`, `desc_sala`, `disponibilidad`) VALUES (1, 'sala_polivalent', '601301001', 'edifici 1', 'sala polivalent d\'us comu', 'OCUPADA'), (3, 'sala_ioga', '601301002', 'edifici 2', 'sala per a fer classes de ioga', 'OCUPADA'), (7, 'sala_reforç', '601301003', 'edifici 3', 'sala per a classes de reforç a alumnes', 'OCUPADA'), (9, 'sala_ball', '672635198', 'edifici 3', 'Sala per a classes de ball', 'DISPONIBLE'), (10, 'sala_presentacions', '652871925', 'edifici 1', 'Sala per a fer presentacions', 'DISPONIBLE'), (11, 'sala_informatica01', '625839156', 'edifici 2', 'Sala d\'us comú d\'informàtica', 'DISPONIBLE'), (12, 'sala_informatica02', '672541789', 'edifici 2', 'Sala per a classes d\'informàtica', 'DISPONIBLE'), (13, 'despatx_01', '635287156', 'edifici 3', 'Despatx per a reunions', 'DISPONIBLE'), (14, 'despatx_02', '635287156', 'edifici 3', 'Despatx per a reunions', 'DISPONIBLE'), (15, 'salo_de_actes', '625189352', 'edifici 1', '', 'DISPONIBLE'), (16, 'taller_cuina', '642517892', 'edifici 1', 'Taller per a classes de cuina', 'DISPONIBLE'), (17, 'Sala_de_reunions', '642517826', 'edifici 3', '', 'DISPONIBLE'); -- -------------------------------------------------------- -- -- Estructura de tabla para la tabla `tbl_usuario` -- CREATE TABLE `tbl_usuario` ( `id_user` int(11) NOT NULL, `username` varchar(30) NOT NULL, `password` varchar(255) NOT NULL, `nom_us` varchar(25) NOT NULL, `cognom_us` varchar(25) NOT NULL, `email_us` varchar(60) NOT NULL, `data_naix_us` date NOT NULL, `dni_us` char(9) NOT NULL, `tlf_us` char(9) NOT NULL ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4; -- -- Volcado de datos para la tabla `tbl_usuario` -- INSERT INTO `tbl_usuario` (`id_user`, `username`, `password`, `nom_us`, `cognom_us`, `email_us`, `data_naix_us`, `dni_us`, `tlf_us`) VALUES (1, 'diego', '<PASSWORD>', 'diego', '<PASSWORD>', '<EMAIL>', '2000-05-17', '48063010W', '619500622'), (2, 'edgar', '<PASSWORD>', 'edgar', 'godoy', '<EMAIL>', '2000-01-01', '38559257X', '615083610'), (4, 'raul', '<PASSWORD>36dbd8313ed055', 'raul', 'vazquez', '<EMAIL>', '1975-01-01', '48063018X', '657829345'); -- -- Índices para tablas volcadas -- -- -- Indices de la tabla `tbl_incidencia` -- ALTER TABLE `tbl_incidencia` ADD PRIMARY KEY (`id_in`), ADD KEY `fk_id_reserva` (`id_reserva`); -- -- Indices de la tabla `tbl_recursos` -- ALTER TABLE `tbl_recursos` ADD PRIMARY KEY (`id_recurs`); -- -- Indices de la tabla `tbl_reserva` -- ALTER TABLE `tbl_reserva` ADD PRIMARY KEY (`id_reserva`), ADD KEY `fk_id_user` (`id_user`), ADD KEY `fk_id_sala` (`id_sala`), ADD KEY `fk_id_recurs` (`id_recurs`); -- -- Indices de la tabla `tbl_salas` -- ALTER TABLE `tbl_salas` ADD PRIMARY KEY (`id_sala`); -- -- Indices de la tabla `tbl_usuario` -- ALTER TABLE `tbl_usuario` ADD PRIMARY KEY (`id_user`); -- -- AUTO_INCREMENT de las tablas volcadas -- -- -- AUTO_INCREMENT de la tabla `tbl_incidencia` -- ALTER TABLE `tbl_incidencia` MODIFY `id_in` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=3; -- -- AUTO_INCREMENT de la tabla `tbl_recursos` -- ALTER TABLE `tbl_recursos` MODIFY `id_recurs` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=8; -- -- AUTO_INCREMENT de la tabla `tbl_reserva` -- ALTER TABLE `tbl_reserva` MODIFY `id_reserva` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=9; -- -- AUTO_INCREMENT de la tabla `tbl_salas` -- ALTER TABLE `tbl_salas` MODIFY `id_sala` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=18; -- -- AUTO_INCREMENT de la tabla `tbl_usuario` -- ALTER TABLE `tbl_usuario` MODIFY `id_user` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=5; -- -- Restricciones para tablas volcadas -- -- -- Filtros para la tabla `tbl_incidencia` -- ALTER TABLE `tbl_incidencia` ADD CONSTRAINT `fk_id_reserva` FOREIGN KEY (`id_reserva`) REFERENCES `tbl_reserva` (`id_reserva`); -- -- Filtros para la tabla `tbl_reserva` -- ALTER TABLE `tbl_reserva` ADD CONSTRAINT `fk_id_recurs` FOREIGN KEY (`id_recurs`) REFERENCES `tbl_recursos` (`id_recurs`), ADD CONSTRAINT `fk_id_sala` FOREIGN KEY (`id_sala`) REFERENCES `tbl_salas` (`id_sala`), ADD CONSTRAINT `fk_id_user` FOREIGN KEY (`id_user`) REFERENCES `tbl_usuario` (`id_user`); 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>/index.php <?php // linkeamos con db_connection para conectar a la base de datos include "./connection/db_connection.php"; ?> <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title></title> <link rel="stylesheet" type="text/css" href="css/estilo.css"> <script src="./js/login.js"></script> </head> <body> <div style="text-align: center; margin-top: 5%"><h1>PR01</h1></div> <div style="text-align: center; margin-top: 10%;"> <!-- formulario de inicio de sesión --> <h1>Iniciar sesión</h1> <form method="POST" action="./proc/login.proc.php" onsubmit="first()"> <?php echo "<input pattern='[A-Za-z0-9_-]{1,15}' type='text' name='user' placeholder='Inserta el usuario' id='user'><br/> "; ?> <input type="<PASSWORD>" name="password" placeholder="<PASSWORD>" id="password" ><br/><br/> <input type="submit" name="Enviar" value="Iniciar sesión" > </form> <!-- --> <!-- formulario de registro --> <h1>Registrarse</h1> <form method="POST" action="./proc/signin.proc.php" onsubmit="second()"> <?php echo "<input pattern='[A-Za-z0-9_-]{1,15}' type='text' name='user' placeholder='Inserta el usuario' id='user''><br/> "; ?> <input pattern='[A-Za-z0-9_-]{1,15}' type="password" name="password" placeholder="<PASSWORD>" id="password" required><br/><br/> <input pattern='[A-Za-z0-9_-]{1,15}' type="submit" name="Enviar" value="Registrarse" > </form> <!-- --> </div> </body> </html><file_sep>/insert/insert_incidencias_salas.php <?php session_start(); $iduser = $_SESSION['id_user']; $name = $_SESSION['nom_us']." ".$_SESSION['cognom_us']; $sala = $_REQUEST['salas']; $desc = $_REQUEST['desc_incidencia_sala']; include "./db_connection.php"; $qry = "INSERT INTO tbl_incidencias (desc_in, fecha_in) VALUES (".$desc.", SYSDATE())"; mysqli_query($conn,$qry); ?><file_sep>/filtrar.php <!DOCTYPE html> <html> <head> <title>Página de disponibilidad</title> <link rel="stylesheet" type="text/css" href="\PRUEBA\PR01_v2\css\pagina.css"> <link href="https://fonts.googleapis.com/css?family=Open+Sans:400i&display=swap" rel="stylesheet"> <meta charset="utf-8"> </head> <body> <!-- BOTON DE CERRAR SESION DE USUARIO --> <div style="text-align: right;"> <?php //Mantengo la sesión. Por ende puedo utilizar la variable $_SESSION anteriormente configurada session_start(); if(isset($_SESSION['id_user'])){ echo "<a href='./proc/logout.proc.php'>Cerrar sesión de ".$_SESSION['nom_us']."</a>&nbsp;&nbsp;"; }else{ header("Location: ../index.php"); } ?> </div> <!-- ------------------ --> <center><h1 style=" text-align:center;padding: 12px;color: #ED820A;">PÁGINA DE DISPONIBILIDAD</h1></center> <div id="main-container"> <table> <thead> <tr> <th>Salas</th><th>Teléfono</th><th>Edificio</th><th>Estado</th> </tr> </thead> <?php include './connection/db_connection.php'; if (!isset($_GET['salas']) && !isset($_GET['recursos']) ) { $sala=$_REQUEST['salas']; $query_fs1="SELECT * FROM tbl_salas WHERE nom_sala='$sala'"; $result_fs1=mysqli_query($conn,$query_fs1); while ($row1 = mysqli_fetch_array($result_fs1)) { echo "<tr> <td>".$row1['nom_sala']."</td><td>".$row1['tlf_sala']."</td><td>".$row1['edificio_sala']."</td><td>".$row1['disponibilidad']."</td> </tr>"; } echo "<table> <thead> <tr> <th>ID</th><th>Nombre</th><th>Tipo</th><th>Estado</th> </tr> </thead>"; $recurs=$_REQUEST['recursos']; $query_fr1="SELECT * FROM tbl_recursos WHERE nom_recurs='$recurs'"; $result_fr1=mysqli_query($conn,$query_fr1); while ($row2 = mysqli_fetch_array($result_fr1)) { echo "<tr> <td>".$row2['id_recurs']."</td><td>".$row2['nom_recurs']."</td><td>".$row2['tipo_recurs']."</td><td>".$row2['disponibilidad']."</td> </tr>"; } } ?> </table> <br><br> </div> <div id="cajafiltro"> <div id="filter"> <h2 style="background-color: #ED820A; color: white; width: 833%; margin-top: -700%;">Filtros</h2> <form action="filtrar.php" method="post"> <a><select name="salas"> <option value="">Salas</option> <?php $query_s2="SELECT * FROM tbl_salas"; $result_s2=mysqli_query($conn,$query_s2); while ($row= mysqli_fetch_array($result_s2)) { echo "<option value=".$row['nom_sala'].">".$row['nom_sala']."</option>"; } ?> </select> </a> <br><br> <a><select name="recursos">Recursos: <option value="">Recursos</option> <?php $query_r2="SELECT * FROM tbl_recursos"; $result_r2=mysqli_query($conn,$query_r2); while ($row= mysqli_fetch_array($result_r2)) { echo "<option value=".$row['nom_recurs'].">".$row['nom_recurs']."</option>"; } ?> </select> </a> <br><br> <input style="margin-left: 8px; width: 740%;" type="submit" value="Filtrar" /><br><br> <input style="margin-left: 8px; width: 740%;" type="reset" value="Borrar"/> </form> <h2 style="background-color: #ED820A; color: white; width: 833%; margin-bottom: 10px;">Reservas</h2> <a href="mis_reservas.php" style="margin-left: 32px;"><button>MIS RESERVAS</button></a><br><br> <a href="reserva.php" style="margin-left: 32px;"><button>RESERVAR</button></a><br><br> </div> </div> </body> </html><file_sep>/intranet.php <!DOCTYPE html> <html> <head> <title>Página de disponibilidad</title> <link rel="stylesheet" type="text/css" href="css/pagina.css"> <link href="https://fonts.googleapis.com/css?family=Open+Sans:400i&display=swap" rel="stylesheet"> <meta charset="utf-8"> </head> <body> <!-- BOTON DE CERRAR SESION DE USUARIO --> <div style="text-align: right;"> <?php //Mantengo la sesión. Por ende puedo utilizar la variable $_SESSION anteriormente configurada session_start(); if(isset($_SESSION['id_user'])){ echo "<a href='./proc/logout.proc.php'>Cerrar sesión de ".$_SESSION['nom_us']."</a>&nbsp;&nbsp;"; }else{ header("Location: ../index.php"); } ?> </div> <!-- ------------------ --> <center><h1 style="color: #E8B25F;">PÁGINA DE DISPONIBILIDAD</h1></center> <div id="main-container"> <table> <thead> <tr> <th>Salas</th><th>Teléfono</th><th>Edificio</th><th>Estado</th> </tr> </thead> <?php include './connection/db_connection.php'; $query_s="SELECT * FROM tbl_salas ORDER BY nom_sala DESC"; $result_s=mysqli_query($conn,$query_s); while ($row = mysqli_fetch_array($result_s)) { echo "<tr> <td>".$row['nom_sala']."</td><td>".$row['tlf_sala']."</td><td>".$row['edificio_sala']."</td><td>".$row['disponibilidad']."</td> </tr>"; } ?> </table> <br><br> <table> <thead> <tr> <th>ID</th><th>Nombre</th><th>Tipo</th><th>Estado</th> </tr> </thead> <?php $query_r="SELECT * FROM tbl_recursos ORDER BY id_recurs ASC"; $result_r=mysqli_query($conn,$query_r); while ($row = mysqli_fetch_array($result_r)) { echo "<tr> <td>".$row['id_recurs']."</td><td>".$row['nom_recurs']."</td><td>".$row['tipo_recurs']."</td><td>".$row['disponibilidad']."</td> </tr>"; } ?> </table> </div> <div id="cajafiltro"> <div id="filtro"> <h2 style="background-color: #ED820A; color: white; width: 833%; margin-bottom: 10px;">Filtros</h2> <form action="filtrar.php" method="post"> <a><select name="salas"> <option value="">Salas</option> <?php $query_s2="SELECT * FROM tbl_salas"; $result_s2=mysqli_query($conn,$query_s2); while ($row= mysqli_fetch_array($result_s2)) { echo "<option value=".$row['nom_sala'].">".$row['nom_sala']."</option>"; } ?> </select> </a> <br><br> <a><select name="recursos">Recursos: <option value="">Recursos</option> <?php $query_r2="SELECT * FROM tbl_recursos"; $result_r2=mysqli_query($conn,$query_r2); while ($row= mysqli_fetch_array($result_r2)) { echo "<option value=".$row['nom_recurs'].">".$row['nom_recurs']."</option>"; } ?> </select> </a> <br><br> <input style="margin-left: 8px; width: 740%;" type="submit" value="Filtrar" /><br><br> <input style="margin-left: 8px; width: 740%;" type="reset" value="Borrar"/> </form> <h2 style="background-color: #ED820A; color: white; width: 833%; margin-bottom: 10px;">Reservas</h2> <a href="mis_reservas.php" style="margin-left: 40px;"><button>MIS RESERVAS</button></a><br><br> <a href="reserva.php" style="margin-left: 40px;"><button>RESERVAR</button></a><br><br> </div> </div> </body> </html><file_sep>/insert/insert_reserva.php <?php session_start(); $iduser = $_SESSION['id_user']; $name = $_SESSION['nom_us']." ".$_SESSION['cognom_us']; include "../connection/db_connection.php"; // LAS FECHAS RECOGIDAS SERVIRÁN PARA TODAS LAS RESERVAS $fecha_ini_res = $_REQUEST['fecha_ini_res']; $fecha_fin_res = $_REQUEST['fecha_fin_res']; // PARA HACER EL INSERT DE LAS RESERVAS DE SALAS Y RECURSOS // para recoger los id de los recursos $recurso = $_REQUEST['recursos']; $idrecurs = "SELECT id_recurs FROM tbl_recursos WHERE nom_recurs = '$recurso'"; $qryidrecurs = mysqli_query($conn, $idrecurs); echo $idrecurs."<br>"; if (!empty($qryidrecurs) && mysqli_num_rows($qryidrecurs)>0) { while ($row = mysqli_fetch_array($qryidrecurs)) { $outputidrecurs = $row['id_recurs']; echo $outputidrecurs."<br>"; } }else{echo "error";} // para recoger los id de las salas $sala = $_REQUEST['salas']; $idsala = "SELECT id_sala FROM tbl_salas WHERE nom_sala = '$sala'"; $qryidsala = mysqli_query($conn, $idsala); echo $idsala."<br>"; if (!empty($qryidsala) && mysqli_num_rows($qryidsala)>0) { while ($row = mysqli_fetch_array($qryidsala)) { $outputidsala = $row['id_sala']; echo $outputidsala."<br>"; } }else{echo "error";} $qry_reserva = "INSERT INTO tbl_reserva (fecha_ini_res, fecha_fin_res, id_recurs, id_user, id_sala) VALUES ('$fecha_ini_res','$fecha_fin_res',$outputidrecurs,$iduser,$outputidsala)"; echo $qry_reserva; $insercion = mysqli_query($conn, $qry_reserva); ?> <!DOCTYPE html> <html> <head> <title></title> <meta charset="utf-8"> <link rel="stylesheet" type="text/css" href=""> </head> <body> <br><br> <button><a href="../mis_reservas.php" style="text-decoration: none; color: black;">IR A MIS RESERVAS</a></button> </body> </html><file_sep>/mis_reservas.php <?php session_start(); $iduser = $_SESSION['id_user']; $name = $_SESSION['nom_us']." ".$_SESSION['cognom_us']; ?> <!DOCTYPE html> <html> <head> <link rel="stylesheet" type="text/css" href="css/estilo.css"> <title></title> </head> <body> <!-- BOTON DE CERRAR SESION DE USUARIO --> <div style="text-align: right;"> <?php //Mantengo la sesión. Por ende puedo utilizar la variable $_SESSION anteriormente configurada if(isset($_SESSION['id_user'])){ echo "<a href='./proc/logout.proc.php'>Cerrar sesión de ".$_SESSION['nom_us']."</a>&nbsp;&nbsp;"; }else{ header("Location: ./index.php"); } ?> </div> <!-- ------------------ --> <H1>MIS RESERVAS:</H1> <!-- PARA MOSTRAR LAS RESERVAS DEL USUARIO --> <?php include "./connection/db_connection.php"; echo "<H2>El nombre del usuario en DB es: ". strtoupper($name) . "</H2>"; $qry = "SELECT * FROM tbl_reserva left JOIN tbl_salas ON tbl_reserva.id_sala = tbl_salas.id_sala left join tbl_recursos on tbl_reserva.id_recurs = tbl_recursos.id_recurs WHERE tbl_reserva.id_user = $iduser ORDER BY tbl_reserva.id_reserva DESC"; $result = mysqli_query($conn,$qry); // muestra la informacion seleccionada if (!empty($result) && mysqli_num_rows($result)>0) { while ($row = mysqli_fetch_array($result)) { echo "<br>"; echo "<form><div style='background-color:#ED820A;</form>;'>"; echo "<br> EL ID DE LA RESERVA ES: " .$row['id_reserva'] . "<br>"; echo "LA FECHA DE INICIO ES: ".$row['fecha_ini_res'] . "<br>"; echo "LA FECHA DE FIN ES: ".$row['fecha_fin_res'] . "<br>"; echo "EL NOMBRE DEL RECURSO ES: ".strtoupper($row['nom_recurs']) . "<br>"; echo "EL NOMBRE DEL USUARIO QUE HA RESERVADO ES: ".strtoupper($name) . "<br>"; echo "EL NOMBRE DE LA SALA ES: ".strtoupper($row['nom_sala']) . "<br>"; echo "</div>"; echo "<a href='./incidencias.php'><p>ABRIR INCIDENCIA</p></a>"; echo "<a href='./borrar_reservas.php'><p>BORRAR RESERVA</p></a>"; } }else{echo "error";} ?> <!-- BOTON DE ABRIR INCIDENCIA --> <!-- ------------------ --> </body> </html><file_sep>/README.md # PR01 PROYECTO 01 DAW2 APP WEB CON INTRANET --2019/10/30. THIS PROJECT IS INTENDED TO BE AN INTRANET WEB APPLICATION FOR SOCIAL USES OF LOCAL GOVERMENT OR COUNCIL´S FACILITIES ALL AVAILABLE FOR PEOPLE TO USE FOR FREE. THE PURPOSE OF THIS WEB APP IS TO CREATE A PRIVATE PORTAL WHERE YOU CAN ACCESS VIA CREDENTIALS IDENTIFICATION WITH A LOGIN AND/OR REGISTER INPUT FORM. ONCE INSIDE THIS INTRANET, USERS/CUSTOMERS ARE ABLE TO BOOK DIFFERENT TYPE OF FACILITIES OR ROOMS, AND ALSO TO USE GOODS FOR PUBLIC SERVICE SUCH AS IT SUPPORT, FITNESS UTILITIES, ETC. THIS PROJECT WILL CONTAIN MANY TECHNOLOGIES SUCH AS MARKUP LANGUAGES LIKE HTML FOR THE WEB STRUCTURE, CASCADE STYLE SHEETS (CSS) FOR DESIGNING, PHP FOR BACK-END PURPOSES, SUCH AS DB CONNECTIONS, USERS´ CREDENTIALS VALIDATION. THIS VALIDATIONS WILL BE TARGETED TO MYSQL DATABASE INSERTED IN PHPMYADMIN WHERE WE WILL HOST THE DIFFERENT INFORMATION ABOUT ALL THE PROJECT. THIS PROJECT HAS BEEN MADE BY <NAME>, <NAME> AND <NAME>. ENDED ON NOVEMBER 8th, 2019. CONTACT LIST: [<NAME>](https://dcarballido.github.io) [<NAME>](https://edgaargodoy.github.io) [<NAME>](https://raulvazpe.github.io) _ _,---._ ,-',' `-.___ /-;' `._ /\/ ._ _,'o \ ( /\ _,--'\,','"`. ) |\ ,'o \' //\ | \ / ,--'""`-. : \_ _/ ,-' `-._ \ `--' / ) `. \`._ ,' ________,',' .--` ,' ,--` __\___,;' \`.,-- ,' ,`_)--' /`.,' \( ; | | ) (`-/ `--'| |) |-/ | | | | | | | |,.,-. | |_ | `./ / )---` ) _| / ,', ,-' ,'|_( /-<._,' |--, | `--'---. \/ \ | / \ /\ \ ,-^---._ | \ / \ \ ,-' \----' \/ \--`. / \ \ \ <file_sep>/borrar_reservas.php <?php session_start(); $iduser = $_SESSION['id_user']; $name = $_SESSION['nom_us']." ".$_SESSION['cognom_us']; ?> <!DOCTYPE html> <html> <head> <title></title> <meta charset="utf-8"> <link rel="stylesheet" type="text/css" href=""> </head> <body> <div style="margin-top: 10%"> <div style="text-align: center;"> <!-- MENSAJE BETA --> <!-- ------------ --> <!-- SALAS --> <h3>CREAR INCIDENCIA PARA SALAS</h3> <form action="./insert_incidencias_salas.php" method="POST"> ELIGE LA SALA:<br><select name="salas"> <!-- input donde se muestran las salas desde bbdd --> <?php include "./db_connection.php"; $qry = "SELECT * FROM tbl_salas"; $result = mysqli_query($conn,$qry); if (!empty($result) && mysqli_num_rows($result)>0) { while ($row = mysqli_fetch_array($result)) { echo "<br>"; echo "<option>".$row['nom_sala']."</option>"; } }else{echo "error";} ?> </select> <br><br> DESCRIBE LA INCIDENCIA:<br> <input type="text" name="desc_incidencia_sala" placeholder="Cuéntanos que pasa"><br><br> <input type="submit" name="submit" value="ENVIAR"> </form> </div> <!-- --> <!-- RECURSOS --> <div style="text-align: center;"> <h3>CREAR INCIDENCIA PARA RECURSOS</h3> <form> ELIGE EL RECURSO:<br><select name="recursos"> <!-- input donde se muestran los recursos desde bbdd --> <?php include "./db_connection.php"; $qry = "SELECT * FROM tbl_recursos"; $result = mysqli_query($conn,$qry); if (!empty($result) && mysqli_num_rows($result)>0) { while ($row = mysqli_fetch_array($result)) { echo "<br>"; echo "<option>".$row['nom_recurs']."</option>"; } }else{echo "error";} ?> </select><br><br> DESCRIBE LA INCIDENCIA:<br> <input type="text" name="desc_incidencia_recurso" placeholder="Cuéntanos que pasa"><br><br> <input type="submit" name="submit" value="ENVIAR"> </form> </div> <!-- --> </div> </body> </html><file_sep>/connection/db_connection.php <?php //asignación de variables de conexion a phpMyAdmin //<NAME> Edgar, cambiar credenciales para conexión a db $server = "localhost"; $user = "root"; $password = "<PASSWORD>"; $dbname = "bd_proyecto01"; //creación de la conexión con db $conn = new mysqli($server, $user, $password, $dbname) or die($conn -> connect_error); ?>
596179d79725e0eb633ec703210fe42c2565731b
[ "Markdown", "SQL", "PHP" ]
12
PHP
dcarballido/PR01
ec615eaac4373b4984a1ff677efe2fa0cb4c3929
6dfa2c2e662774b61cb1516e61deb97e8d09c2d5
refs/heads/master
<repo_name>k-utsubo/pointer-generator<file_sep>/run.sh #!/bin/bash #PBS -q APPLI #PBS -N run #PBS -l select=1:ncpus=1:mpiprocs=1 #PBS -j oe #PBS -v IMAGE=tf:16-gpu if [ "${PBS_O_WORKDIR}" != "" ];then cd ${PBS_O_WORKDIR} fi if [ -f ~/.bashrc ];then source ~/.bashrc fi export OMP_NUM_THREADS=1 export DIR=$DATA/cnn-dailymail/finished_files export WORK=$DATA/cnn-dailymail/work2 mkdir -p $WORK python run_summarization.py --mode=train --data_path=$DIR/train.bin --vocab_path=$DIR/vocab --log_root=$WORK --exp_name=myexperiment --epochs=20 <file_sep>/eval.sh #!/bin/bash #PBS -q GPU #PBS -N eval #PBS -l select=1:ncpus=1:mpiprocs=1 #PBS -j oe #PBS -v IMAGE=tf:16-gpu if [ "${PBS_O_WORKDIR}" != "" ];then cd ${PBS_O_WORKDIR} fi if [ -f ~/.bashrc ];then source ~/.bashrc fi export OMP_NUM_THREADS=1 export DIR=$DATA/cnn-dailymail/finished_files export WORK=$DATA/cnn-dailymail/work2 mkdir -p $WORK python run_summarization.py --mode=eval --data_path=$DIR/train.bin --vocab_path=$DIR/vocab --log_root=$WORK --exp_name=myexperiment
7c46092fb009a42c4d90d82cc087f496fbf3a00c
[ "Shell" ]
2
Shell
k-utsubo/pointer-generator
ab2b653ad1ca2b40ed5ed5335187f6c73925872b
2ec9ad27880d3b9b5f5999113a7f31335e7bf22c
refs/heads/master
<file_sep>import pyaudio import sys import wave def record_audio(RECORD_SECONDS, audio_path, to_update=None): p = pyaudio.PyAudio() # print(p.get_default_input_device_info()) FRAMES_PERBUFF = 2048 # number of frames per buffer FORMAT = pyaudio.paInt16 # 16 bit int CHANNELS = 1 # I guess this is for mono sounds FRAME_RATE = 44100 # sample rate stream = p.open(format=FORMAT, channels=CHANNELS, rate=FRAME_RATE, input=True, frames_per_buffer=FRAMES_PERBUFF) # buffer frames = [] nchunks = int(RECORD_SECONDS * FRAME_RATE / FRAMES_PERBUFF) for i in range(0, nchunks): data = stream.read(FRAMES_PERBUFF) frames.append(data) # 2 bytes(16 bits) per channel if to_update is not None: to_update.update() print("* done recording") stream.stop_stream() stream.close() p.terminate() wf = wave.open(audio_path, 'wb') wf.setnchannels(CHANNELS) wf.setsampwidth(p.get_sample_size(FORMAT)) wf.setframerate(FRAME_RATE) wf.writeframes(b''.join(frames)) wf.close() if __name__ == '__main__': # Import the necessary modules. import tkinter import tkinter as tk import tkinter.messagebox import pyaudio import wave import os class RecAUD: def __init__(self, chunk=3024, frmat=pyaudio.paInt16, channels=1, rate=44100, py=pyaudio.PyAudio()): # Start Tkinter and set Title self.main = tkinter.Tk() self.collections = [] self.main.geometry('500x300') self.main.title('Record') self.CHUNK = chunk self.FORMAT = frmat self.CHANNELS = channels self.RATE = rate self.p = py self.frames = [] self.st = 1 self.stream = self.p.open(format=self.FORMAT, channels=self.CHANNELS, rate=self.RATE, input=True, frames_per_buffer=self.CHUNK) # Set Frames self.buttons = tkinter.Frame(self.main, padx=120, pady=20) # Pack Frame self.buttons.pack(fill=tk.BOTH) # Start and Stop buttons self.strt_rec = tkinter.Button(self.buttons, width=10, padx=10, pady=5, text='Start Recording', command=lambda: self.start_record()) self.strt_rec.grid(row=0, column=0, padx=50, pady=5) self.stop_rec = tkinter.Button(self.buttons, width=10, padx=10, pady=5, text='Stop Recording', command=lambda: self.stop()) self.stop_rec.grid(row=1, column=0, columnspan=1, padx=50, pady=5) tkinter.mainloop() def start_record(self): self.st = 1 self.frames = [] stream = self.p.open(format=self.FORMAT, channels=self.CHANNELS, rate=self.RATE, input=True, frames_per_buffer=self.CHUNK) while self.st == 1: data = stream.read(self.CHUNK) self.frames.append(data) print("* recording") self.main.update() stream.close() wf = wave.open('test_recording.wav', 'wb') wf.setnchannels(self.CHANNELS) wf.setsampwidth(self.p.get_sample_size(self.FORMAT)) wf.setframerate(self.RATE) wf.writeframes(b''.join(self.frames)) wf.close() def stop(self): self.st = 0 # Create an object of the ProgramGUI class to begin the program. guiAUD = RecAUD() <file_sep>absl-py==0.11.0 astunparse==1.6.3 audioread==2.1.9 cachetools==4.1.1 certifi==2020.6.20 cffi==1.14.3 chardet==3.0.4 decorator==4.4.2 gast==0.3.3 google-auth==1.23.0 google-auth-oauthlib==0.4.2 google-pasta==0.2.0 grpcio==1.33.2 h5py==2.10.0 idna==2.10 importlib-metadata==2.0.0 joblib==0.17.0 Keras==2.4.3 Keras-Preprocessing==1.1.2 librosa==0.7.2 llvmlite==0.28.0 Markdown==3.3.3 numba==0.43.1 numpy==1.18.5 oauthlib==3.1.0 opt-einsum==3.3.0 pandas==1.0.3 protobuf==3.13.0 pyasn1==0.4.8 pyasn1-modules==0.2.8 PyAudio==0.2.11 pycparser==2.20 python-dateutil==2.8.1 pytz==2020.4 PyYAML==5.3.1 requests==2.24.0 requests-oauthlib==1.3.0 resampy==0.2.2 rsa==4.6 scikit-learn==0.23.2 scipy==1.4.1 six==1.15.0 SoundFile==0.10.3.post1 tensorboard==2.3.0 tensorboard-plugin-wit==1.7.0 tensorflow==2.3.0 tensorflow-addons==0.11.2 tensorflow-estimator==2.3.0 termcolor==1.1.0 threadpoolctl==2.1.0 tqdm==4.31.1 typeguard==2.10.0 urllib3==1.25.11 Werkzeug==1.0.1 wrapt==1.12.1 zipp==3.4.0 <file_sep># Demo voice verification ## Instructions * Install python3 and the requirements.txt packages * To run the app : `python3 main_app.py` <file_sep>import tkinter as tk from audio import record_audio import os from datetime import datetime import pandas as pd from model import vggvox_model import constants as c from scoring import get_embedding import numpy as np from scipy.spatial.distance import cdist class Main(tk.Frame): INRECORD = 'Recording...' WAIT = 'Waiting for a press' DB_ADD = 'Added to Database' RECORD_SECODNS = 3 # 5 FOLDER = "DEMO" def __init__(self, root): super().__init__(root) self.db_file = os.path.join(self.FOLDER, 'enroll_list.csv') self.embed_file = os.path.join(self.FOLDER, 'embed.npy') self.db = pd.read_csv(self.db_file) self.root = root self.status = self.WAIT self.lastname = '' self.last_embed = None self.model = self.load_model() self.embeding = self.load_embed() print(self.db.shape, self.embeding.shape) self.init_main() self.pack(fill=tk.BOTH, expand=1) def init_main(self): self.name_text = tk.Label(self, text="Specify your name:") self.name_text.place(relx=0.3, rely=0.1, anchor='n') self.name_edit = tk.Entry(self, text="") self.name_edit.place(relx=0.7, rely=0.1, relheight=0.1, relwidth=0.3, anchor='n') self.start_button = tk.Button(self, text="Start Record", compound=tk.TOP, command=self.start_record) self.start_button.place(relx=0.5, rely=0.3, relwidth=0.7, anchor='n') # self.stop_button = tk.Button(root, text="Stop Record", compound=tk.TOP, command=self.stop_record) # self.stop_button.place(relx=0.7, rely=0.3, anchor='n') self.status_text = tk.Label(self, text=self.status) self.status_text.place(relx=0.5, rely=0.5, anchor='n') self.db_button = tk.Button(self, text="Add last record in DB", compound=tk.TOP, command=self.add_to_db) self.db_button.place(relx=0.5, rely=0.7, relwidth=0.7, anchor='n') self.db_button_reset = tk.Button(self, text="Reset the DB", compound=tk.TOP, command=self.reset_db) self.db_button_reset.place(relx=0.5, rely=0.8, relwidth=0.7, anchor='n') self.db_button_predict = tk.Button(self, text="Predict the name", compound=tk.TOP, command=self.predict) self.db_button_predict.place(relx=0.5, rely=0.9, relwidth=0.7, anchor='n') if not os.path.exists(os.path.join(self.FOLDER, 'all_records')): os.mkdir(os.path.join(self.FOLDER, 'all_records')) def load_model(self): model = vggvox_model() model.load_weights("data/model/weights.h5") return model def load_embed(self): if os.path.exists(self.embed_file): return np.load(self.embed_file) return np.array([]) def predict(self): distances = pd.DataFrame(cdist(self.embeding, self.last_embed, metric=c.COST_METRIC)) print(distances) min_speaker = distances.iloc[:, 0].argmin() print(self.db['speaker'][min_speaker]) self.update_status('Predicted ' + self.db['speaker'][min_speaker] + '!') def reset_db(self): self.update_status('Reset the Database') db_back = self.db.copy() db_back.to_csv(os.path.join(self.FOLDER, 'enroll_list_back.csv'), index=False) self.db = self.db.iloc[:0] self.db.to_csv(self.db_file, index=False) np.save(os.path.join(self.FOLDER, 'embed_back_back.npy'), self.embeding) self.embeding = np.array([]) np.save(self.embed_file, self.embeding) def add_to_db(self): speaker = self.name_edit.get() if speaker != "" and self.lastname != "": self.update_status(speaker + ' ' + self.DB_ADD) print('Add to db') self.db = self.db.append({'filename': self.lastname, 'speaker': speaker}, ignore_index=True) self.embeding = np.vstack([self.embeding, self.last_embed]) if self.embeding.size else self.last_embed print(self.embeding.shape) self.db.to_csv(self.db_file, index=False) np.save(self.embed_file, self.embeding) print(self.db.head()) else: self.update_status('Specify the name!') print('Specify name') pass def start_record(self): if self.status == self.INRECORD: print("We are in record!") return # current date and time now = datetime.now() timestamp = datetime.timestamp(now) print("timestamp =", timestamp) self.update_status(self.INRECORD) self.start_button.configure(foreground='red') self.root.update() self.lastname = os.path.join(self.FOLDER, 'all_records', str(timestamp) + '.wav') record_audio(self.RECORD_SECODNS, self.lastname, self.root) self.start_button.configure(foreground='black') self.update_status('Loading...') self.last_embed = np.array(get_embedding(self.model, self.lastname, c.MAX_SEC)).reshape(1, -1) self.update_status('Recorded!') return def update_status(self, newstatus): print(newstatus) self.status = newstatus self.status_text.config(text=self.status) pass if __name__ == "__main__": root = tk.Tk() app = Main(root) # app.pack() root.title("Voice Demo") root.geometry("250x250+0+0") root.resizable(True, True) root.mainloop()
2cd62845d405fc585e94d61354dfdd8fe7a2d366
[ "Markdown", "Python", "Text" ]
4
Python
TheShasa/NigeriaDemo
e68521106a33ce4d8fa7b59dc45ed702019b2b52
a8eb8f97f22eb0304d9d10fe8fa44057b0777cbf
refs/heads/master
<file_sep>package main import ( "errors" "fmt" ) func addCategory(jd jsonData, catgr string) error { if _, err := jd.getIndex(catgr); err == nil { msg := fmt.Sprintf("Category named `%s` already exists", catgr) return errors.New(msg) } jd.AddCategory(category{Name: catgr}) err := writeJSONData(jd) if err != nil { return err } return nil } func addCommand(jd jsonData, catgr string) error { index, err := jd.getIndex(catgr) if err != nil { return err } name, err := readInput("Command Name: ", false) if err != nil { return err } use, err := readInput("Use (opt): ", true) if err != nil { return err } jd.AddCommand(index, command{Name: name, Use: use}) err = writeJSONData(jd) if err != nil { return err } return nil } <file_sep>package main import ( "fmt" "strings" ) // Returns lower cased string if ignoreCase is true // Else returns same string func corvo(st string, ignoreCase bool) string { if ignoreCase { return strings.ToLower(st) } return st } func search(jd jsonData, query string, ignoreCase bool) error { q := corvo(query, ignoreCase) for _, ct := range jd.Categories { ctName := corvo(ct.Name, ignoreCase) if strings.Contains(ctName, q) { cat := strings.Replace(ct.Name, query, highlightUse(query), -1) fmt.Printf("[Category: %s]\n", cat) } for _, cm := range ct.Commands { cmName := corvo(cm.Name, ignoreCase) cmUse := corvo(cm.Use, ignoreCase) if strings.Contains(cmName, q) || strings.Contains(cmUse, q) { name := strings.Replace(cm.coloredName(), query, highlightName(query), -1) use := strings.Replace(cm.Use, query, highlightUse(query), -1) fmt.Print(name) if use != "" { fmt.Print(" → ", use) } fmt.Println() } } } return nil } func highlightName(st string) string { red := "\x1b[31m" yellow := "\x1b[33m" return fmt.Sprintf("%s%s%s", red, st, yellow) } func highlightUse(st string) string { red := "\x1b[31m" reset := "\x1b[0m" return fmt.Sprintf("%s%s%s", red, st, reset) } <file_sep>## komi `komi` is a simple command saver with the ability to group commands in categories so they can be retrieved easily. Commands and their uses can be added, modified and deleted. They can quickly be copied to the system clipboard. All the data is saved in a JSON file which can be exported. [![komi demo](https://asciinema.org/a/92201.png)](https://asciinema.org/a/92201) Features: - Bash completion for categories - Command copying to system clipboard - Searching for string (includes case-insensitive search) - Exporting data file ## Dependency If you're on Linux, you would need the `xclip` package for copying commands. On Debian/Ubuntu you can install it with: ```bash sudo apt-get install xclip ``` Also note, if you're using `komi copy` command via ssh on a remote linux machine, you would need to enable X11 forwarding. You can do by adding the `-X` flag: ```bash ssh <user>@<ip> -X ``` ## Installation The default data directory is kept as: ``` /home/$USER/.komi ``` If you want a different data directory, you can export `KOMI_DATA_DIR` env variable to that directory. ```bash export KOMI_DATA_DIR="/home/$USER/diff_komi" ``` **Note**: If specifying data dir through env var, make sure to include the export statement in your `.bashrc`. ### Installation with Go ```bash go get github.com/shivammg/komi sudo cp data/bash_autocomplete /etc/bash_completion.d/komi source /etc/bash_completion.d/komi # If you want to see the example data file (Optional) mkdir /home/$USER/.komi cp data/komi.json /home/$USER/.komi/komi.json ``` ### Installation without Go ```bash git clone <EMAIL>:shivamMg/komi.git cd komi ./install.sh source /etc/bash_completion.d/komi ``` `install.sh` does the following: 1. Copies one of the following binaries to `/usr/local/bin` according to the platform. Binaries for other platforms are not included. - [linux/amd64](data/bin/linux_amd64) - [darwin/amd64](data/bin/darwin_amd64) **Note**: This requires sudo permissions. 2. Creates data directory at `/home/$USER/.komi` and copies example data file from `data/komi.json`. 3. Copies the bash completion script to `/etc/bash_completion.d/`. **Note**: This also requires sudo permissions. You can then source your komi bash completion script to update your current shell. ```bash source /etc/bash_completion.d/komi ``` <file_sep>package main import ( "encoding/json" "io/ioutil" "os" "path" ) var ( jsonFileDir string jsonFilePath string ) func init() { const filename = "komi.json" defaultDataDir := path.Join("/home", os.Getenv("USER"), ".komi") jsonFileDir = os.Getenv("KOMI_DATA_DIR") // If Env Variable not set if jsonFileDir == "" { jsonFileDir = defaultDataDir } jsonFilePath = path.Join(jsonFileDir, filename) } // Read and parse json data from `jsonFilePath` // If an error occurs, return it func readJSONData() (jsonData, error) { jd := jsonData{} content, err := ioutil.ReadFile(jsonFilePath) if err != nil { // return jd, &jsonFileError{err, "Error reading JSON file: " + jsonFilePath} // Create file err := setupDataDir(jd) if err != nil { return jd, err } // Skip parsing JSON since data is going to be `jd` return jd, nil } err = json.Unmarshal(content, &jd) if err != nil { return jd, &jsonFileError{err, "Error parsing JSON file: " + jsonFilePath} } return jd, nil } // Parse and write json data to `jsonFilePath` // If an error occurs, return it func writeJSONData(jd jsonData) error { content, err := json.Marshal(jd) if err != nil { return &jsonFileError{err, "Error parsing JSON file: " + jsonFilePath} } err = ioutil.WriteFile(jsonFilePath, content, 0644) if err != nil { return &jsonFileError{err, "Error writing to JSON file: " + jsonFilePath} } return nil } // Create data file with jd data func setupDataDir(jd jsonData) error { // Create data directory err := os.MkdirAll(jsonFileDir, 0744) if err != nil { return err } // Create data file err = writeJSONData(jd) if err != nil { return err } return nil } <file_sep>package main import ( "encoding/json" "errors" "fmt" ) // Display categories in a square matrix func displayCategories(jd jsonData) { categories := jd.GetCategoryList() l := len(categories) // Length of category with max length var maxCatLen int for _, c := range categories { if maxCatLen < len(c) { maxCatLen = len(c) } } // Calculate required order for square matrix n := 1 for l > n*n { n++ } // Display categories for i, c := range categories { fmt.Print(c) for j := 0; j <= maxCatLen-len(c); j++ { fmt.Print(" ") } if (i+1)%n == 0 { fmt.Println() } } // Required newline if categories do not form a // complete square matrix if l%n != 0 { fmt.Println() } } // Display commands and uses // Return error if category not found func displayCommands(jd jsonData, catgr string, namesOnly bool) error { coms, found := jd.GetCommands(catgr) if !found { msg := fmt.Sprintf("No such category as `%s`\n", catgr) return errors.New(msg) } if namesOnly { // Print serialized command names and return for i, c := range coms { fmt.Printf("%-2d %s\n", i+1, c.coloredName()) } return nil } for _, c := range coms { fmt.Print(c.coloredName()) if c.Use != "" { fmt.Print(" → ", c.Use) } fmt.Println() } return nil } func displayJSONData(jd jsonData) error { content, err := json.MarshalIndent(jd, "", "\t") if err != nil { return err } fmt.Println(string(content)) return nil } <file_sep>package main import ( "fmt" "strings" "github.com/carmark/pseudo-terminal-go/terminal" ) type command struct { Name string `json:"name"` Use string `json:"use"` } type category struct { Name string `json:"name"` Commands []command `json:"commands"` } type jsonData struct { Categories []category `json:"categories"` } type jsonFileError struct { err error msg string } func (e *jsonFileError) Error() string { return fmt.Sprintf("%s", e.msg) } // Read input in raw mode func readInput(prompt string, optional bool) (string, error) { // Save currect state of terminal oldState, err := terminal.MakeRaw(0) if err != nil { panic(err) } defer terminal.Restore(0, oldState) t, err := terminal.NewWithStdInOut() if err != nil { panic(err) } defer t.ReleaseFromStdInOut() for { fmt.Print(prompt) line, err := t.ReadLine() if err != nil { return "", err } input := strings.Trim(line, " ") if input != "" || optional { return input, nil } } } <file_sep>package main import ( "errors" "fmt" "strconv" ) // Returns list of category names func (jd jsonData) GetCategoryList() []string { var categories []string if jd.Categories == nil { return categories } for _, c := range jd.Categories { categories = append(categories, c.Name) } return categories } // Returns list of commands and true if category was found // else it returns an empty commands list with false func (jd jsonData) GetCommands(catgr string) ([]command, bool) { var commands []command if jd.Categories == nil { return commands, false } for _, c := range jd.Categories { if c.Name == catgr { return c.Commands, true } } return commands, false } // Add a category func (jd *jsonData) AddCategory(c category) { jd.Categories = append(jd.Categories, c) } // Add command to a category func (jd *jsonData) AddCommand(categoryIndex int, com command) { jd.Categories[categoryIndex].Commands = append(jd.Categories[categoryIndex].Commands, com) } // Modify a category's name func (jd *jsonData) ModifyCategory(categoryIndex int, newName string) { jd.Categories[categoryIndex].Name = newName } // Modify a command's name and use func (jd *jsonData) ModifyCommand(categoryIndex int, commandIndex int, newName string, newUse string) { com := &jd.Categories[categoryIndex].Commands[commandIndex] (*com).Name = newName (*com).Use = newUse } // Delete a category func (jd *jsonData) DeleteCategory(categoryIndex int) { cats := &jd.Categories l := len(*cats) // Swap with last category (*cats)[categoryIndex] = (*cats)[l-1] // Slice off last category *cats = (*cats)[:l-1] } // Delete a command func (jd *jsonData) DeleteCommand(categoryIndex int, commandIndex int) { coms := &jd.Categories[categoryIndex].Commands l := len(*coms) (*coms)[commandIndex] = (*coms)[l-1] *coms = (*coms)[:l-1] } // Returns index of a category name // Returns -1 if category name not found func (jd jsonData) getIndex(catgr string) (int, error) { for i, c := range jd.Categories { if c.Name == catgr { return i, nil } } msg := fmt.Sprintf("No such category as `%s`", catgr) return -1, errors.New(msg) } // Prints category names for Bash completion func (jd jsonData) printCategories() { for _, c := range jd.Categories { fmt.Println(c.Name) } } // Returns colored name for a command func (c command) coloredName() string { yellow := "\x1b[33m" reset := "\x1b[0m" return fmt.Sprintf("%s%s%s", yellow, c.Name, reset) } // Read Serial Number and validate func readSerialNo(upperBound int) (int, error) { input, err := readInput("Select Serial no: ", false) if err != nil { return -1, err } sno, err := strconv.Atoi(input) if err != nil || sno < 1 || sno > upperBound { return -1, errors.New("Invalid Serial no") } return sno, nil } <file_sep>package main import ( "fmt" "github.com/atotto/clipboard" ) func copyCommand(jd jsonData, catgr string, copyUse bool) error { index, err := jd.getIndex(catgr) if err != nil { return err } err = displayCommands(jd, catgr, true) if err != nil { return err } fmt.Println() sno, err := readSerialNo(len(jd.Categories[index].Commands)) if err != nil { return err } cm := jd.Categories[index].Commands[sno-1] var text string if copyUse { text = cm.Use } else { text = cm.Name } err = clipboard.WriteAll(text) if err != nil { // return errors.New("Command/Use not copied") return err } fmt.Printf("`%s` Copied!\n", text) return nil } <file_sep>package main import ( "errors" "fmt" "os" "strings" "github.com/urfave/cli" ) func main() { jd, err := readJSONData() if err != nil { fmt.Fprintln(os.Stderr, err) os.Exit(1) } app := cli.NewApp() app.EnableBashCompletion = true app.Name = "komi" app.Usage = "A simple command saver" app.Action = func(c *cli.Context) error { fmt.Println("Use `komi help` to get help") return nil } app.Commands = []cli.Command{ { Name: "show", Usage: "Show commands inside a category", Action: func(c *cli.Context) error { if c.NArg() == 0 { displayCategories(jd) return nil } catgr := c.Args().First() err = displayCommands(jd, catgr, false) if err != nil { return err } return nil }, BashComplete: func(c *cli.Context) { if c.NArg() > 0 { return } jd.printCategories() }, }, { Name: "add", Usage: "Add command to a category", Action: func(c *cli.Context) error { if c.NArg() < 1 { return errors.New("Please specify a category") } catgr := c.Args().First() err := addCommand(jd, catgr) return err }, BashComplete: func(c *cli.Context) { if c.NArg() > 0 { return } jd.printCategories() }, }, { Name: "mod", Usage: "Modify command in a category", Action: func(c *cli.Context) error { if c.NArg() < 1 { return errors.New("Please specify a category") } catgr := c.Args().First() err := modifyCommand(jd, catgr) return err }, BashComplete: func(c *cli.Context) { if c.NArg() > 0 { return } jd.printCategories() }, }, { Name: "del", Usage: "Delete command from a category", Action: func(c *cli.Context) error { if c.NArg() < 1 { return errors.New("Please specify a category") } catgr := c.Args().First() err := deleteCommand(jd, catgr) return err }, BashComplete: func(c *cli.Context) { if c.NArg() > 0 { return } jd.printCategories() }, }, { Name: "addcat", Usage: "Add a category", Action: func(c *cli.Context) error { if c.NArg() < 1 { return errors.New("Please specify category name") } catgr := c.Args().First() err := addCategory(jd, catgr) return err }, }, { Name: "modcat", Usage: "Modify a category name", Action: func(c *cli.Context) error { if c.NArg() < 1 { return errors.New("Please specify a category") } catgr := c.Args().First() err := modifyCategory(jd, catgr) return err }, BashComplete: func(c *cli.Context) { if c.NArg() > 0 { return } jd.printCategories() }, }, { Name: "delcat", Usage: "Delete a category", Action: func(c *cli.Context) error { if c.NArg() < 1 { return errors.New("Please specify a category") } catgr := c.Args().First() err := deleteCategory(jd, catgr) return err }, BashComplete: func(c *cli.Context) { if c.NArg() > 0 { return } jd.printCategories() }, }, { Name: "export", Usage: "Display all data in JSON", Action: func(c *cli.Context) error { err = displayJSONData(jd) return err }, }, { Name: "search", Usage: "Search for a string inside data", Action: func(c *cli.Context) error { query := strings.Join(c.Args(), " ") ignoreCase := c.Bool("ignore-case") err := search(jd, query, ignoreCase) return err }, Flags: []cli.Flag{ cli.BoolFlag{ Name: "ignore-case, i", Usage: "Ignore case for search query", }, }, }, { Name: "copy", Usage: "Copy a command or its use text", Action: func(c *cli.Context) error { if c.NArg() < 1 { return errors.New("Please specify a category") } catgr := c.Args().First() copyUse := c.Bool("copy-use") err := copyCommand(jd, catgr, copyUse) return err }, BashComplete: func(c *cli.Context) { if c.NArg() > 0 { return } jd.printCategories() }, Flags: []cli.Flag{ cli.BoolFlag{ Name: "copy-use, u", Usage: "Copy Command's Use text", }, }, }, } app.Run(os.Args) } <file_sep>#!/usr/bin/env bash if [ "$(uname -s)" == "Linux" ]; then sudo cp data/bin/linux_amd64 /usr/local/bin/komi elif [ "$(uname)" == "Darwin" ]; then sudo cp data/bin/darwin_amd64 /usr/local/bin/komi else echo "Unknown Operating System" exit 1 fi datadir="/home/$USER/.komi" mkdir $datadir # Copy example data file cp data/komi.json $datadir # bash autocomplete sudo cp data/bash_autocomplete /etc/bash_completion.d/komi <file_sep>package main import ( "errors" "fmt" ) func deleteCategory(jd jsonData, catgr string) error { index, err := jd.getIndex(catgr) if err != nil { return err } prompt := fmt.Sprintf("You sure want to delete `%s`? (y/N): ", catgr) choice, err := readInput(prompt, false) if err != nil || !(choice[0:1] == "y" || choice[0:1] == "Y") { msg := fmt.Sprintf("`%s` was not deleted", catgr) return errors.New(msg) } jd.DeleteCategory(index) err = writeJSONData(jd) if err != nil { return err } return nil } func deleteCommand(jd jsonData, catgr string) error { index, err := jd.getIndex(catgr) if err != nil { return err } err = displayCommands(jd, catgr, true) if err != nil { return err } fmt.Println() sno, err := readSerialNo(len(jd.Categories[index].Commands)) if err != nil { return err } fmt.Println(jd.Categories[index].Commands[sno-1].Name) choice, err := readInput("You sure want to delete above command? (y/N): ", false) if err != nil || !(choice[0:1] == "y" || choice[0:1] == "Y") { return errors.New("Command was not deleted") } jd.DeleteCommand(index, sno-1) err = writeJSONData(jd) if err != nil { return err } return nil } <file_sep>package main import ( "errors" "fmt" ) func modifyCategory(jd jsonData, catgr string) error { index, err := jd.getIndex(catgr) if err != nil { return err } input, err := readInput("Enter new category name: ", false) if err != nil { return err } if _, err := jd.getIndex(input); err == nil { msg := fmt.Sprintf("Category named `%s` already exists", input) return errors.New(msg) } jd.ModifyCategory(index, input) err = writeJSONData(jd) if err != nil { return err } return nil } func modifyCommand(jd jsonData, catgr string) error { index, err := jd.getIndex(catgr) if err != nil { return err } err = displayCommands(jd, catgr, true) if err != nil { return err } fmt.Println() sno, err := readSerialNo(len(jd.Categories[index].Commands)) if err != nil { return err } fmt.Println("Previous name:", jd.Categories[index].Commands[sno-1].Name) name, err := readInput("Enter new name: ", false) if err != nil { return err } fmt.Println("Previous use:", jd.Categories[index].Commands[sno-1].Use) use, err := readInput("Enter new use (opt): ", true) if err != nil { return err } jd.ModifyCommand(index, sno-1, name, use) err = writeJSONData(jd) if err != nil { return err } return nil }
ae35b3abb3808e41dbc3bbaba49fdde09dfb0424
[ "Markdown", "Go", "Shell" ]
12
Go
shivamMg/komi
a2560d0b826453ebcf29c55dfc85cbe70b9930c0
3d525732bc43589db1911a801d8b88c4af1e11ec
refs/heads/master
<file_sep>console.info([ '=========================================', '*** FantasticBoxCo is working :) ***', '=========================================', ].join('\n')); angular .module('app', []) .controller('OrderController', OrderController); function OrderController() { this.isValid = false; this.step1 = { title: "Step 1 - Dimensions &amp; Quantity", width: 0.0, height: 0.0, length: 0.0, quantity: 0, get isValid () { return this.area > 0 && this.quantity > 0; }, get area () { if (this.width <= 0 || this.height <= 0 || this.length <= 0) return 0; var hw = this.width * this.height; var hl = this.height * this.length; var wl = this.width * this.length; return (2 * hw) + (2 * hl) + (2 * wl); } }; this.step2 = { title: "Step 2 - Cardboard Grade", choice: null, options: [ { key: "A", name: "A Grade", price: 0.20 }, { key: "B", name: "B Grade", price: 0.10 }, { key: "C", name: "C Grade", price: 0.05, validation: function (area) { if (area <= 2) return { result: true }; return { result: false, code: -2.1, message: this.name + " cannot be chosen for box size of larger than 2 square metres", fix: "Go back to step 2 and choose a different grade." }; } } ], find: function (key) { var found = null; this.options.forEach(function (option){ if (option.key == key) { found = option; } }); return found; }, get chosen () { return this.find(this.choice); }, get price () { //per area var option = this.find(this.choice); if (option) return option.price; else return 0; } }; this.step3 = { title: "Step 3 - Print Quality", choice: null, options: [ { key: "3-color", name: "3 colours", price: 0.20 }, { key: "2-color", name: "2 colours", price: 0.10 }, { key: "black-only", name: "Black only", price: 0.05 }, { key: "no-printing", name: "No printing", price: 0 }, { key: "FantasticBoxCo-branding", name: "FantasticBoxCo branding", discount: 100 * 0.05 } ], find: function (key) { var found = null; this.options.forEach(function (option){ if (option.key == key) { found = option; } }); return found; }, get chosen () { return this.find(this.choice); }, get price () { var option = this.find(this.choice); if (option && option.price) return option.price; else return 0; }, get discount () { var option = this.find(this.choice); if (option && option.discount) return option.discount; else return 0; } }; this.step4 = { title: "Step 4 - Optional Extras", options: [ { key: "handles", name: "Handles", enabled: false, price: 0.10 }, { key: "reinforced-bottom", name: "Reinforced bottom", enabled: false, price: 0.05 } ], get price () { //per box var total = 0; this.options.forEach(function (option) { if (option.enabled) { total += option.price; } }); return total; } }; this.costPerBox = function () { var cost = (this.step1.area * this.step2.price) + (this.step1.area * this.step3.price) + this.step4.price; if (this.step3.discount) { cost = ((100 - this.step3.discount) / 100) * cost; } return cost; }; this.totalCost = function () { var total = this.costPerBox() * this.step1.quantity; return total.toFixed(3); }; this.finish = function () { var validation = this.validate(); this.isValid = validation.result; }; this.validate = function () { this.validation = { result: true, errors: [] }; if (!this.step1.isValid) { this.validation.errors.push({ code: -1, message: "Please ensure quantity and box dimensions are entered;", fix: "Go back to step 1 and fill out: Width, Height, Length and Quantity." }); } var step2_chosen = this.step2.chosen; if (!step2_chosen) { this.validation.errors.push({ code: -2, message: "Please ensure a cardboard grade is chosen;", fix: "Go back to step 2 and choose a grade." }); } if (this.step1 && step2_chosen && typeof step2_chosen.validation != "undefined" && !step2_chosen.validation(this.step1.area).result) { this.validation.errors.push(step2_chosen.validation()); } var step3_chosen = this.step3.chosen; if (!step3_chosen) { this.validation.errors.push({ code: -3, message: "Please ensure a print quality is chosen;", fix: "Go back to step 3 and choose a print quality." }); } if (this.validation.errors.length) { this.validation.result = false; } return this.validation; }; }
d52397f99355d51a0a98ce78350914c5eeea7782
[ "JavaScript" ]
1
JavaScript
fab1o/f-box-co
c843a9d0ec63ad3473c1a44d58d39df57d38877e
435791a443bd76745f398f3e4e241294e5ab351f
refs/heads/main
<file_sep>using Microsoft.AspNetCore.Mvc; using Microsoft.EntityFrameworkCore; using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using TBC.context; using TBC.model; // For more information on enabling Web API for empty projects, visit https://go.microsoft.com/fwlink/?LinkID=397860 namespace TBC.Controllers { [Route("api/[controller]")] [ApiController] public class StudentClassController : ControllerBase { private StudentDbContext _context; public StudentClassController(StudentDbContext context) { _context = context; } [HttpGet] public async Task<IEnumerable<StudentClass>> GetAllStudents() { IEnumerable<StudentClass> students = await _context.Students.ToListAsync(); return students; } [Route("Post")] [HttpPost] public async Task<IActionResult> Modify(StudentClass student) { if (student == null) return BadRequest(); var CurrentDate = DateTime.Now.Date; var TotalDays = CurrentDate - student.DateOfBirth.Date; var StudentAge = TotalDays.TotalDays * 0.00273785; bool a = _context.Students.Any( o => o.Id == student.Id ); if (a == true && student.IdNumber.Length == 11 && StudentAge > 16) { _context.Update(student); await _context.SaveChangesAsync(); return Ok(); } return BadRequest(); } //[HttpGet("{id}")] //public async Task<StudentClass> Get(StudentClass student) //{ // _context.Add(student); // await _context.SaveChangesAsync(); // return student; //} [Route("Put")] [HttpPut] public async Task<IActionResult> Add(StudentClass student) { if (student == null) return BadRequest(); var CurrentDate = DateTime.Now.Date; var TotalDays = CurrentDate - student.DateOfBirth.Date; var StudentAge = TotalDays.TotalDays * 0.00273785; //var IdNumberChecker = await _context.FindAsync<StudentClass>(student.IdNumber); bool a = _context.Students.Any( o => o.IdNumber == student.IdNumber ); if (a == false && student.IdNumber.Length == 11 && StudentAge > 16) { _context.Add(student); await _context.SaveChangesAsync(); return Ok(); } return BadRequest(); } [HttpDelete("{id:int}")] public async Task<IActionResult> Delete(int id) { bool a = _context.Students.Any( o => o.Id == id ); if (a == true) { _context.Students.Remove(_context.Students.FirstOrDefault(e => e.Id == id)); await _context.SaveChangesAsync(); return Ok(); } return BadRequest(); } } } <file_sep>using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.Linq; using System.Threading.Tasks; namespace TBC.model { public class StudentClass { public int Id { get; set; } [Required] public string IdNumber { get; set; } [Required] public string Name { get; set; } [Required] public string LastName { get; set; } [Required] public DateTime DateOfBirth { get; set; } [Required] public bool Sex { get; set; } } } <file_sep>using Microsoft.EntityFrameworkCore; using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using TBC.model; namespace TBC.context { public class StudentDbContext : DbContext { public StudentDbContext(DbContextOptions<StudentDbContext> options): base(options) { Database.EnsureCreated(); ////////modelBuilder.Entity<Event>().HasData( //////// new Event //////// { //////// Id = 1, //////// Name = "The International 10", //////// Location = "Bucharest, National Arena", //////// Time = TI10Date, //////// IsActive = false, //////// userId = 1 //////// } ////////); } public DbSet<StudentClass> Students { get; set; } //protected override void OnModelCreating(ModelBuilder modelBuilder) //{ // var date = new DateTime(2002, 7, 14); // for (int i = 0; i < 50; i++) // { // modelBuilder.Entity<StudentClass>().HasData( // new StudentClass // { // Id = 1, // Name = "Giga", // LastName = "Jachvadze", // DateOfBirth = date, // Sex = false, // IdNumber = "12345678912" // } // ); // } //} } }
d2d43e076e01c541010d9450aa0f6b35cc52b957
[ "C#" ]
3
C#
GigaJachvadze/TBC-backend
0e97c4822a208213c04a534d57da6ecec2a89819
5ff4257fc732b8fd8f4b30d8863d5ed3e32a1a1d
refs/heads/master
<file_sep>#include<iostream> using namespace std; int main(){ long long int a,b,c; int n; cin >>n; for(int i=1;i<=n;i++){ string s; cin >>a>>b>>c; a+b>c?s="true":s="false"; printf("Case #%d: %s\n",i,s.c_str()); } return 0; } <file_sep>#include<iostream> using namespace std; int main(){ float open ,high, low ,close; cin >>open>>high>>low>>close; if(close<open){ cout<<"BW-Solid"; } else if(close==open){ cout<<"R-Cross"; } else{ cout<<"R-Hollow"; } if(high>open&&high>close){ if(low<open&&low<close){ cout<<" with Lower Shadow and Upper Shadow"; } else{ cout<<" with Upper Shadow"; } } else { if(low<open&&low<close){ cout<<" with Lower Shadow"; } } return 0; } <file_sep>#include<iostream> #include<vector> #include<algorithm> using namespace std; int main(){ string N; cin >>N; vector<int> a(10); for(int i=0;i<N.length();i++){ a[N[i]-'0']++; } //sort(a.begin(),a.end()); for(int i=0;i<10;i++){ if(a[i]>0){ cout<< i<<":"<<a[i]<<endl; }} return 0; } <file_sep>#include<stdio.h> int main(){ char c; int a=0; scanf("%c",&c); while(c!='.'){ if(c==' '){ printf("%d ",a); a=0; } else{ a++; } scanf("%c",&c); } printf("%d ",a); return 0; } <file_sep>#include<iostream> #include<algorithm> #include<vector> using namespace std; int main(){ int n,m; cin >> n >> m; vector<int> a(n); for(int i=0;i<n;i++){ cin >> a[i]; } m%=n; if(m!=0){ reverse(begin(a),begin(a)+n); reverse(begin(a),begin(a)+m); reverse(begin(a)+m,begin(a)+n); } for(int i=0;i<n-1;i++){ cout<<a[i]<<" "; }cout<<a[n-1]; return 0; } <file_sep># PAT基础编程题目 练习记录 ## 2019/5/23 第一次提交 完成前26题 <file_sep>#include<iostream> using namespace std; int main(){ int t; int rabbit=0,turtle=0,minute,rest=-1,run=10; cin >>t; while(t){ turtle+=3; if (run-- > 0) rabbit += 9; if (run == 0 ){ //兔子跑10分钟回头看一下,如果比乌龟快就休息30分钟,反之再跑10分钟 if (rabbit > turtle) rest = 30; else run = 10 ; } if (rest-- == 0) //休息结束继续跑10分钟 run = 10; } if(turtle > rabbit) printf("@_@ %d",turtle); else if (rabbit > turtle) printf("^_^ %d",rabbit); else printf("-_- %d",rabbit); return 0; } <file_sep>#include<iostream> using namespace std; string shu[10]={"ling","yi","er","san","si","wu","liu","qi","ba","jiu"}; int wei=0; void dushu(int a){ wei++; if(a>10){ dushu(a/10); wei--; cout<<shu[a%10]; if(wei!=0){ cout<<' '; } } else{ wei--; cout<<shu[a%10]; if(wei!=0){ cout<<' '; } } } int main(){ int a; cin>>a; if(a<0){ cout<<"fu "; a=-a; } dushu(a); return 0; } <file_sep>#include<iostream> using namespace std; int main(){ int n,u,d; cin >>n>>u>>d; int i=0; while(n>0){ i++; if(i%2==0){ n+=d; } else{ n-=u; } } cout << i; return 0; } <file_sep>#include<iostream> using namespace std; int main(){ string s; int a,t=0,temp=0; cin >>s>>a; t=(s[0]-'0')/a; temp=(s[0]-'0')%a; int len=s.length(); if((t!=0&&len>1)||len==1)cout<< t; for(int i=1;i<len;i++){ t=(temp*10+s[i]-'0')/a; temp=(temp*10+s[i]-'0')%a; cout <<t; } cout <<" "<<temp; return 0; } <file_sep>#include <iostream> #include<string> using namespace std; int main() { string s; getline(cin,s); int i=s.size(); for(;i>0;i--){ if(s[i]==' ') { cout<<s.substr(i+1)<<' '; s=s.substr(0,i); } } cout<<s<<endl; } <file_sep>#include<iostream> using namespace std; int main(){ string a,c; int b,d; cin >> a>>b>>c>>d; int A=0,B=0; for(int i=0;i<a.size();i++){ if(a[i]-'0'==b){ A=A*10+b; } } for(int i=0;i<c.size();i++){ if(c[i]-'0'==d){ B=B*10+d; } } cout << A+B; return 0; } <file_sep>#include<iostream> #include<vector> #include<algorithm> using namespace std; struct stu{ int id; int de; int cai; }; int cmp(struct stu a,struct stu b){ if((a.de+a.cai)!=(b.de+b.cai)){ return (a.de+a.cai)>(b.de+b.cai); } else if(a.de!=b.de){ return a.de>b.de; } else{ return a.id<b.id; } } int main(){ int mun,low,high; scanf("%d %d %d", &mun, &low, &high); vector<stu> v[4]; int count =mun; stu temp; for(int i=0;i<mun;i++){ scanf("%d %d %d",&temp.id,&temp.de,&temp.cai); if(temp.de<low||temp.cai<low){ count--; } else if(temp.de>=high&&temp.cai>=high){ v[0].push_back(temp); } else if(temp.de>=high&&temp.cai<high){ v[1].push_back(temp); } else if(temp.de<high&&temp.cai<high&&temp.de>=temp.cai){ v[2].push_back(temp); } else{ v[3].push_back(temp); } } cout << count <<endl; for(int i=0;i<4;i++){ sort(v[i].begin(),v[i].end(),cmp); for(int j=0;j<v[i].size();j++){ printf("%d %d %d\n",v[i][j].id,v[i][j].de,v[i][j].cai); } } return 0; } <file_sep>#include<iostream> #include<math.h> using namespace std; int isprime(int x){ for(int i=2;i<=sqrt(x);i++){ if(x%i==0){ return 0; } } //cout<< x; return 1; } int main(){ int x; cin >> x; int sum=0; while(x>=5){ int a,b; a=isprime(x); b=isprime(x-2); //cout<<endl; if(a){ if(b){ cout<< x<<x-2<<endl; sum++; } } x=x-1; } cout << sum; return 0; } <file_sep>#include<iostream> using namespace std; int main(){ int y,f; int n; cin>>n; //n=98f-199y; for(f=0;f<100;f++){ for(y=0;y<100;y++){ if(n==98*f-199*y){ printf("%d.%d",y,f); return 0; } } } printf("No Solution"); return 0; } <file_sep>#include<iostream> using namespace std; int main(){ int n; cin >>n; int a,b,sum=0; for(a=1;a<=100;a++){ for(b=a;b<=100;b++){ if(a*a+b*b==n){ printf("%d %d\n",a,b); sum++; } } } if(sum==0){ printf("No Solution"); } return 0; } <file_sep>#include<iostream> using namespace std; int main(int argc, char const *argv[]) { float n; cin>>n; float sum=0; int i=0; int j=1; int yuzi=1; int yumu=1; float yu=1; while(yu>=n){ sum+=yu; i+=1; j+=2; cout<<i<<"00"<<j<<endl; yuzi*=i; yumu*=j; yu=(1.0*yuzi/yumu); } sum+=yu; printf("%.6f",2*sum); return 0; } <file_sep>#include<iostream> using namespace std; char shuzi[10]={'a','b','c','d','e','f','g','h','i','j'}; char weishu[9]={' ','S','B','Q','W','S','B','Q','Y'}; int wei=0; void shuchu(int a){ wei++; if(a>10){ shuchu(a/10); wei--; cout<<shuzi[a%10]; cout<<weishu[wei]; } else{ wei--; cout<<shuzi[a%10]; cout<<weishu[wei]; } } int main(){ int a; cin>>a; shuchu(a); } <file_sep>#include<iostream> using namespace std; int main(){ int a[10]={0}; int sum=0; for(int i=0;i<10;i++){ int b; cin >>b; sum+=b; a[i]=b; }//输入十个数和数字位数 //输出第一个 for(int i=1;i<10;i++){ if(a[i]>0){ cout<<i; a[i]--; sum--; break; } } int k=0; while(sum>0){ while(a[k]>0){ cout<<k; a[k]--; sum--; } k++; } return 0; } <file_sep>#include<iostream> #include<cctype> using namespace std; int main(){ string a,b,c,d; cin >> a>>b>>c>>d; char t[2]; int pos,i=0,j=0; while(i<a.length()&&i<b.length()){ if(a[i]==b[i]&&(a[i]>='A'&&a[i]<='G')){ t[0]=a[i]; break; } i++; } i++; while(i<a.length()&&i<b.length()){ if(a[i]==b[i]&&((a[i]>='A'&&a[i]<='N')||isdigit(a[i]))){ t[1]=a[i]; break; } i++; } while(j<c.length()&&j<d.length()){ if(c[j]==d[j]&&isalpha(c[j])){ pos=j; break; } j++; } string DAY[7]={"MON","TUE","WED","THU","FRI","SAT","SUN"}; int m=isdigit(t[1])?t[1]-'0':t[1]-'A'+10; printf("%s %02d:%02d",DAY[t[0]-'A'].c_str(),m,pos); return 0; } <file_sep>#include<iostream> #include<algorithm> using namespace std; int cmp(char a,char b){return a>b; } int main(){ string s; cin>>s; s.insert(0,4-s.length(),'0'); do{ string a=s,b=s; sort(a.begin(),a.end(),cmp); sort(b.begin(),b.end()); int result =stoi(a)-stoi(b); s=to_string(result); s.insert(0,4-s.length(),'0'); cout <<a<<" - "<<b<<" = "<<s<<endl; } while(s!="6174"&&s!="0000"); return 0; } <file_sep>#include<iostream> #include<vector> #include<algorithm> using namespace std; struct mooncake{ float mount=0,prize=0,value=0; }; int cmp(mooncake a,mooncake b){ return a.prize>b.prize; } int main(){ int n=0; float sum=0; float count=0.0; cin >>n>>sum; vector<mooncake>cake(n); for(int i=0;i<n;i++){ scanf(" %f",&cake[i].mount); } for(int i=0;i<n;i++){ scanf(" %f",&cake[i].value); } for(int i=0;i<n;i++){ if(cake[i].mount!=0) {cake[i].prize=cake[i].value/cake[i].mount; } else{ cake[i].prize=0; } } sort(cake.begin(),cake.end(),cmp); int i=0; for(int i=0;i<n;i++){//用while循环段错误,因为可能所有月饼都卖完了,需求也没有满足 if(sum<cake[i].mount){ //cout<< cake[i].prize<<endl; count+=cake[i].prize*sum; sum-=sum; } if(sum>=cake[i].mount){ //cout<< cake[i].prize<<endl; count+=cake[i].value; sum-=cake[i].mount; } } printf("%0.2f",count); return 0; } <file_sep>#include<iostream> #include<vector> using namespace std; struct node{ int address=0,data=0,next=-1,last=-1; }; int search(int address,vector<node>Node,int N){ int i=-1; for(int a=0;a<N;a++){ if(address==Node[a].next)return a; } return i; } int main(){ int Address=0; int N=0; int K=0; cin >>Address>>N>>K; vector<node> Node(N); for(int i=0;i<N;i++){ int address=0,data=0,next=-1,last=-1; cin>>Node[i].address>>Node[i].data>>Node[i].next; } for(int i=0;i<N;i++){ int last=-1; last=search(Node[i].address,Node,N); Node[i].last=last; } cout<<"½á¹û"<<endl; for(int i=0;i<N;i++){ cout<<Node[i].address<<" "<<Node[i].data<<" "<<Node[i].next<<" LAST: "<<Node[Node[i].last].address<<endl; } return 0; } <file_sep>#include<iostream> using namespace std; int main(){ string a,b; getline(cin,a); getline(cin,b); int c[300]={0}; for(int i=0;i<a.size();i++){ if(c[a[i]]==0){ cout<< a[i]; c[a[i]]++; } } for(int i=0;i<b.size();i++){ if(c[b[i]]==0){ cout<< b[i]; c[b[i]]++; } } return 0; } <file_sep>#include<iostream> #include<math.h> using namespace std; int isprime(int i){ int a; for(a=2;a<=sqrt(i);a++){ if(i%a==0){ return 0; } } return 1; } int main(){ int m,n; int i=1; int count =1; cin >> m >> n; while(count<=n+1){ if(isprime(i)){ if(count==n+1){ cout<<i; return 0; } if(count>m){ if(count>m&&(count-m)%10==0){ cout <<i<< endl; } else{ cout<<i<<" "; } } count++; } i++; } return 0; } <file_sep>#include<iostream> using namespace std; int main(){ int a,b; int flag=0; while(cin>>a>>b){ if(flag){ if(b!=0){ cout <<" "<<a*b<<" "<<b-1; }} else{ if(b!=0){ flag=1; cout <<a*b<<" "<<b-1; } }} if(flag==0)cout<<"0 0"; return 0; } <file_sep>#include<iostream> using namespace std; int yue(int a,int b){ int c=a; for(c;c>=1;c--){c if(a%c==0&&b%c==0){ return c; } } return 1; } int main(){ int a,b; scanf("%d/%d",&a,&b); int c=yue(a,b); printf("%d/%d",a/c,b/c);; return 0; } <file_sep>#include<stdio.h> double a3,a2,a1,a0; double f(double a){ return a3*a*a*a+a2*a*a+a1*a+a0; } int main(){ int ok=1; double a,b; scanf("%lf %lf %lf %lf",&a3,&a2,&a1,&a0); scanf("%lf %lf",&a,&b); double m=(a+b)*0.5; while((b-a)>0.001){ m=(a+b)*0.5; //printf("%.2f\n",f(a)); if(f(a)==0){ printf("%.2f",a); return 0; } else if(f(b)==0){ printf("%.2f",b); return 0; } else if(f(m)==0){ printf("%.2f",m); return 0; } else { if(f(a)*f(m)>0){ a=m; } else{ b=m; } } } printf("%.2f",m); return 0; } <file_sep>#include<iostream> using namespace std; int main(){ int n; int sum1=0; int count1=0; int flag=1; int sum2=0; int count2=0; int count3=0; int sum4=0; int count4=0; int count5=0; int max5=-1; int M; cin>>M; while(M>0){ M--; cin>>n; if(n%5==0){ if(n%2==0){ sum1+=n; count1++; } } else if(n%5==1){ count2++; if(flag%2==1){ sum2+=n; } else{ sum2-=n; } flag++; } else if(n%5==2){ count3++; } else if(n%5==3){ cout<<n<<endl; count4++; sum4+=n; } else if(n%5==4){ count5++; if(n>max5){ max5=n; } } } if(count1!=0){ cout << sum1<<" "; } else{ cout<<"N "; } if(count2!=0){ cout << sum2<<" "; } else{ cout<<"N "; } if(count3!=0){ cout << count3<<" "; } else{ cout<<"N "; } if(count4!=0){ printf("%.1f",sum4*1.0/count4); cout <<" "; } else{ cout<<"N "; } if(count5!=0){ cout <<max5; } else{ cout<<"N"; } } <file_sep>//1018 ´¸×Ó¼ôµ¶²¼ (20 ·Ö) #include<iostream> using namespace std; int main(){ int N; cin >>N; string a,b; int s[2][26]={0}; int jia=0,yi=0,p=0; int max1=0,max2=0; string j1,y1; for(int i=0;i<N;i++){ cin >>a>>b; if(a[0]==b[0])p++; else if((a[0]=='C'&&b[0]=='J')||(a[0]=='J'&&b[0]=='B')||(a[0]=='B'&&b[0]=='C')){ jia++; s[0][a[0]-'A']++; if(s[0][a[0]-'A']>max){ max=s[0][(a[0]-'A')]; j1=s[0][a[0]]; } } else{ yi++; s[1][b[0]-'A']++; if(s[1][b[0]-'A']>max){ max=s[1][b[0]-'A']; y1=s[1][b[0]]; } } } cout <<jia<<" "<<p<<" "<<yi<<endl; cout <<yi<<" "<<p<<" "<<jia<<endl; cout <<j1<<" "<<y1; return 0; } <file_sep>#include<iostream> using namespace std; int main(){ int a,b,c; cin>>a>>b>>c; if(c==0){ cout<<0; return 0; } long int sum=a+b; int N[31]={0};//30给的太少了第三个点出现了运行时错误、31就能够过 int n=0; while(sum>0){ N[n]=sum%c; sum=sum/c; n++; } n--; if(n<0){ cout<<0; } for(;n>=0;n--){ cout<<N[n]; } return 0; } <file_sep>#include<stdio.h> int main(){ int n; scanf("%d",&n); int a=1; int b=1; for(;a<=n;a++){ for(b=1;b<=a;b++){ printf("%d*%d=%-4d",b,a,a*b); } if(a<n) printf("\n"); } } <file_sep># 2019年5月16日21:23:06开始 边学习边上传 自己的代码碎片 ## 开始学习Github 开始学PAT ,练习C语言C++ # 加油吧 ## 也要学习学习markdown 咋用 了 <file_sep># PAT个人做题记录- *这文档主要记录自己PAT刷题的记录* 代码很有可能存在问题 主要用来记录自己的学习过程。 如果有问题希望指出。 <file_sep>#include<iostream> using namespace std; int main(){ int n; cin >> n; string a,b; int sum[2][3]={0}; int M1=0,M2=0;//M1,M2;³φΟΦΑΛΆΞ΄νΞσ int jia=0,yi=0,p=0; for(int i=0;i<n;i++){ cin >> a>>b; if(a==b){ p++; } else if(a=="C"&&b=="J"){ jia++; sum[0][1]++; } else if(a=="J"&&b=="B"){ jia++; sum[0][2]++; } else if(a=="B"&&b=="C"){ jia++; sum[0][0]++; } else if(b=="C"&&a=="J"){ yi++; sum[1][1]++; } else if(b=="J"&&a=="B"){ yi++; sum[1][2]++; } else if(b=="B"&&a=="C"){ yi++; sum[1][0]++; } } int max[2]={0}; for(int i=0;i<3;i++){ if(max[0]<sum[0][i]){max[0]=sum[0][i];M1=i; } if(max[1]<sum[1][i]) {max[1]=sum[1][i];M2=i; } } string N[3]={"B","C","J"}; cout <<jia<<" "<<p<<" "<<yi<<endl; cout <<yi<<" "<<p<<" "<<jia<<endl; cout <<N[M1]<<" "<<N[M2]; return 0; }
48d784df9fd0c466047804ae9e368600c7db6be7
[ "Markdown", "C++" ]
35
C++
HANXU2018/PAT_CODE
a6ead3567d3afd54f0758ef5c83e62190c64d5bb
6bf223152fa165ae8fd0e2afe2a2594a7a7dec63
refs/heads/master
<file_sep>package validAnagram; public class Test { public static void main(String[] args) throws Exception { Solution s = new Solution(); String str = "hello"; String t = "leloh"; System.out.println(s.isAnagram(str, t)); } } <file_sep>package linkedListCycleII142; import java.util.ArrayList; import java.util.List; public class Solution { public ListNode detectCycle(ListNode head) { List<ListNode> list = new ArrayList<>(); ListNode temp = head; while(temp != null) { if(list.contains(temp)) { return temp; } else { list.add(temp); temp = temp.next; } } return null; } } <file_sep>package minimumTimeDifference539; import java.util.ArrayList; import java.util.List; public class Test { public static void main(String[] args) { Solution s = new Solution(); List<String> list = new ArrayList<>(); list.add("14:49"); list.add("09:56"); // list.add("03:55"); list.add("01:02"); System.out.println(s.findMinDifference(list)); } } <file_sep>package sumRoottoLeafNumbers129; public class Solution { private int sum; public int sumNumbers(TreeNode root) { if(root == null) return 0; traverse(root,""); return sum; } private void traverse(TreeNode root, String str) { if(root.left == null && root.right == null) { sum += Integer.parseInt(str+root.val); return; } if(root.left != null) traverse(root.left, str+root.val); if(root.right != null) traverse(root.right, str+root.val); } } <file_sep>package matrixBlockSum1314; /** * [[67,64,78],[99,98,38],[82,46,46],[6,52,55],[55,99,45]] * 3 */ public class Test { public static void main(String[] args) { int[][] mat = new int[][]{ {67,64,78},{99,98,38},{82,46,46},{6,52,55},{55,99,45} }; Solution solution = new Solution(); int[][] result = solution.matrixBlockSum(mat, 3); for (int i = 0; i < result.length; i++) { for (int j = 0; j < result[0].length; j++) { System.out.print(result[i][j]+", "); } System.out.println(); } } } <file_sep>package recoverBinarySearchTree99; public class Test { public static void main(String[] args) { Solution s = new Solution(); TreeNode root = new TreeNode(5); TreeNode node1 = new TreeNode(2); TreeNode node2 = new TreeNode(7); TreeNode node3 = new TreeNode(1); TreeNode node4 = new TreeNode(4); TreeNode node5 = new TreeNode(6); TreeNode node6 = new TreeNode(9); TreeNode node7 = new TreeNode(3); root.left = node1; root.right = node2; node1.left = node3; node1.right = node4; node3.right = node7; node2.left = node5; node2.right = node6; System.out.println("before: "); in(root); s.recoverTree(root); System.out.println(); System.out.println("after:"); in(root); } private static void in(TreeNode root) { if(root == null) return; in(root.left); System.out.print(root.val+","); in(root.right); } } <file_sep>package firstBadVersion278; public class Solution extends VersionControl { public int firstBadVersion(int n) { int start = 1; int end = n; int mid = 1; while(end >= start) { if(end == start) { return start; } mid = start + (end - start) / 2; if(!isBadVersion(mid)) { start = mid+1; continue; } else { end = mid; continue; } } return mid; } } <file_sep>package singleNumberIII260; public class Test { public static void main(String[] args) { Solution s = new Solution(); int[] arr = new int[]{1,3,3,5,6,8,5,6,1,9}; int[] result = s.singleNumber(arr); for(int num : result) { System.out.println(num); } } } <file_sep>package copyListwithRandomPointer138; import java.util.ArrayList; import java.util.List; public class Solution { public RandomListNode copyRandomList(RandomListNode head) { if(head == null) { return null; } RandomListNode temp = head; List<RandomListNode> list = new ArrayList<>(); while(temp != null) { list.add(temp); temp = temp.next; } RandomListNode[] arr = new RandomListNode[list.size()]; for(int i=0;i<list.size();++i) { arr[i] = new RandomListNode(list.get(i).label); } for(int i=0;i<list.size()-1;++i) { arr[i].next = arr[i+1]; } for(int i=0;i<list.size();++i) { RandomListNode t = list.get(i); if(t.random == null) { arr[i].random = null; } else { int index = list.indexOf(t.random); arr[i].random = arr[index]; } } return arr[0]; } } <file_sep>package letterCombinationsOfaPhoneNumber17; import java.util.*; public class Solution { private static final Map<Character,List<String>> MAP = new HashMap<>(); private static List<String> result; static { MAP.put('2', Arrays.asList("a","b","c")); MAP.put('3', Arrays.asList("d","e","f")); MAP.put('4', Arrays.asList("g","h","i")); MAP.put('5', Arrays.asList("j","k","l")); MAP.put('6', Arrays.asList("m","n","o")); MAP.put('7', Arrays.asList("p","q","r","s")); MAP.put('8', Arrays.asList("t","u","v")); MAP.put('9', Arrays.asList("w","x","y","z")); } public List<String> letterCombinations(String digits) { result = new ArrayList<>(); if (digits == null || digits.isEmpty()){ return result; } char[] chars = digits.toCharArray(); List<Character> characters = new ArrayList<>(); for (char ch:chars){ characters.add(ch); } combination(characters,"",1); return result; } private void combination(List<Character> list, String preStr, int layer){ if (layer == list.size()){ char num = list.get(layer-1); List<String> charList = MAP.get(num); for (String s:charList){ result.add(preStr+s); } return; } char num = list.get(layer-1); List<String> charList = MAP.get(num); for (String s:charList){ combination(list,preStr+s,layer+1); } } } <file_sep>package addTwoNumbersII445; public class Test { public static void main(String[] args) { Solution s = new Solution(); ListNode l1 = new ListNode(7); ListNode l12 = new ListNode(2); ListNode l13 = new ListNode(4); ListNode l14 = new ListNode(3); l1.next = l12; l12.next = l13; l13.next = l14; ListNode l2 = new ListNode(5); ListNode l22 = new ListNode(6); ListNode l23 = new ListNode(4); l2.next = l22; l22.next = l23; ListNode result = s.addTwoNumbers(l1,l2); while(result != null) { System.out.println(result.val); result = result.next; } } } <file_sep>package predicttheWinner486; public class Test { public static void main(String[] args) { Solution s = new Solution(); int[] nums = new int[]{2,5,233,14}; System.out.println(s.PredictTheWinner(nums)); } } <file_sep>package balancedBinaryTree110; public class Solution { public boolean isBalanced(TreeNode root) { if(root == null) { return true; } int i = Math.abs(deepth(root.left) - deepth(root.right)); if(i > 1) { return false; } return isBalanced(root.left) && isBalanced(root.right); } public int deepth(TreeNode root) { if(root == null) { return 0; } int i = 1 + Math.max(deepth(root.left), deepth(root.right)); return i; } } <file_sep>package timeNeededtoInformAllEmployees1376; public class Test { public static void main(String[] args) { int n = 15; int head = 0; int[] manager = new int[]{-1,0,0,1,1,2,2,3,3,4,4,5,5,6,6}; int[] inform = new int[]{1,1,1,1,1,1,1,0,0,0,0,0,0,0,0}; Solution solution = new Solution(); System.out.println(solution.numOfMinutes(n,head,manager,inform)); } } <file_sep>package convertSortedArraytoBinarySearchTree108; public class Solution { public TreeNode sortedArrayToBST(int[] nums) { if(nums.length == 0) { return null; } int n = nums.length/2+nums.length%2-1; TreeNode root = new TreeNode(nums[n]); root.left = helper(nums,0,n-1); root.right = helper(nums,n+1,nums.length-1); return root; } private TreeNode helper(int[] list, int start,int end) { if(start > end) { return null; } if(start == end) { return new TreeNode(list[start]); } else { TreeNode root = new TreeNode(list[(start + end)/2]); root.left = helper(list,start,(start + end)/2-1); root.right = helper(list,(start + end)/2+1,end); return root; } } } <file_sep>package longestConsecutiveSequence128; import java.util.HashMap; import java.util.Map; /** * Created by <NAME> on 2017/9/21. */ public class Solution { public int longestConsecutive(int[] nums) { int max = 0; Map<Integer,Integer> map = new HashMap<>(); for (int i = 0; i < nums.length; i++) { int n = nums[i]; if(!map.containsKey(n)){ int left = map.containsKey(n-1)? map.get(n-1):0; int right = map.containsKey(n+1)? map.get(n+1):0; int sum = left+right+1; max = Math.max(sum,max); map.put(n,sum); map.put(n-left,sum); map.put(n+right,sum); } } return max; } } <file_sep>package reorderList143; public class Solution { public void reorderList(ListNode head) { if(head == null) { return; } if(head.next == null) { return; } ListNode temp = head; int sum = 0; while(temp != null) { sum += 1; temp = temp.next; } sum = (sum+1)/2; temp = head; ListNode temp2 = temp.next; while(sum > 1) { temp = temp.next; temp2 = temp2.next; sum -= 1; } temp.next = null; temp = temp2.next; temp2.next = null; while(temp != null) { ListNode next = temp.next; temp.next = temp2; temp2 = temp; temp = next; } ListNode l2 = temp2; ListNode l1 = head; while(l2 != null) { temp = l2; l2 = l2.next; temp2 = l1; l1 = l1.next; temp2.next = temp; temp.next = l1; } // while(curr != null) // { // ListNode temp = curr.next; // if(temp == null) // { // break; // } // ListNode before = curr; // while(temp.next != null) // { // before = before.next; // temp = temp.next; // } // before.next = null; // temp.next = curr.next; // curr.next = temp; // curr = temp.next; // // } } } <file_sep>package diameterofBinaryTree543; public class Test { public static void main(String[] args) { Solution s = new Solution(); TreeNode root = new TreeNode(1); TreeNode node1 = new TreeNode(1); TreeNode node2 = new TreeNode(1); TreeNode node3 = new TreeNode(1); TreeNode node4 = new TreeNode(1); root.right = node1; root.left = node2; node1.right = node3; node2.left = node4; System.out.println(s.diameterOfBinaryTree(root)); } } <file_sep>package palindromeLinkedList234; public class Solution { public boolean isPalindrome(ListNode head) { if(head == null) { return true; } if(head.next == null) { return true; } int sum = 0; ListNode temp = head; while(temp != null) { sum += 1; temp = temp.next; } int[] arr = new int[sum/2]; int mid = sum/2; int i = 0; temp = head; int j = 0; while(temp != null) { if(i < mid) { arr[i] = temp.val; temp = temp.next; i++; j = i-1; continue; } if(sum % 2 == 1) { temp = temp.next; sum = 0; continue; } if(temp.val == arr[j]) { temp = temp.next; j -= 1; continue; } else { return false; } } return true; } } <file_sep>package isomorphicStrings205; import java.util.HashMap; import java.util.Map; public class Solution { public boolean isIsomorphic(String s, String t) { Map<Character,Character> map = new HashMap<>(); for(int i=0;i<s.length();i++) { char ch2 = t.charAt(i); char ch1 = s.charAt(i); if(map.get(ch2) == null && map.containsValue(ch1) == true) { return false; } else if(map.get(ch2) == null) { map.put(ch2,ch1); } else if(map.get(ch2) != ch1) { return false; } } return true; } } <file_sep>package MaximumAverageSubarrayI643; /** * Created by zhaozhezijian on 2017/8/8. */ public class Test { public static void main(String[] args) { Solution s = new Solution(); int[] arr = new int[]{1,12,-5,-6,50,3}; System.out.println(s.findMaxAverage(arr,4)); } } <file_sep>package serializeandDeserializeBinaryTree297; import java.util.ArrayDeque; import java.util.Queue; public class Codec { // Encodes a tree to a single string. public String serialize(TreeNode root) { if(root == null) return ""; StringBuffer str = new StringBuffer(); Queue<TreeNode> queue = new ArrayDeque<>(); queue.add(root); while(!queue.isEmpty()) { root = queue.poll(); if(root.left != null) queue.add(root.left); if(root.right != null) queue.add(root.right); if(root.left == null && root.right==null) str.append(root.val+"z,"); if(root.left == null && root.right != null) str.append(root.val+"r,"); if(root.right == null && root.left != null) str.append(root.val+"l,"); if(root.left != null && root.right != null) str.append(root.val+"t,"); } str.delete(str.length()-1,str.length()); return str.toString(); } // Decodes your encoded data to tree. public TreeNode deserialize(String data) { if(data.equals("")) return null; String[] str = data.split(","); TreeNode root = null; Queue<TreeNode> que = new ArrayDeque<>(); Queue<TreeNode> que2 = new ArrayDeque<>(); Queue<String> queStr = new ArrayDeque<>(); for(int i=0;i<str.length;++i) { String s = str[i].substring(0,str[i].length()-1); TreeNode node = new TreeNode(Integer.parseInt(s)); if(!isLeaf(str[i])) { queStr.add(str[i]); que.add(node); } que2.add(node); } root = que2.poll(); while(!que.isEmpty()) { String cmp = queStr.poll(); TreeNode cur = que.poll(); if(cmp.endsWith("t")) { TreeNode left = que2.poll(); TreeNode right = que2.poll(); cur.left = left; cur.right = right; } else if(cmp.endsWith("l")) { TreeNode left = que2.poll(); cur.left = left; } else if(cmp.endsWith("r")) { TreeNode right = que2.poll(); cur.right = right; } } return root; } private boolean isLeaf(String str) { return str.endsWith("z"); } } <file_sep>package searchInRotatedSortedArray33; /** * Created by zhaozhezijian on 2018/10/14. */ public class Test { public static void main(String[] args) { Solution solution = new Solution(); int[] arr = new int[]{1,2,4,5,6,8}; System.out.println(solution.search(arr,1)); } } <file_sep>package binaryTreePreorderTraversal144; import java.util.List; public class Test { public static void main(String[] args) { Solution s = new Solution(); TreeNode root = new TreeNode(1); TreeNode node1 = new TreeNode(2); TreeNode node2 = new TreeNode(3); root.left = node1; node1.right = node2; List<Integer> list = s.preorderTraversal(root); for(int num : list) { System.out.println(num); } } } <file_sep>package constructBinaryTreefromPreorderandInorderTraversal105; public class Test { public static void main(String[] args) { Solution s = new Solution(); int[] pre = new int[]{1,2,4,5,7,3,6}; int[] in = new int[]{4,2,5,7,1,3,6}; TreeNode root = s.buildTree(pre,in); // System.out.println(root.left.right.right.right.val); pre(root); System.out.println(); in(root); } public static void pre(TreeNode root) { if(root == null) return; System.out.print(root.val+","); pre(root.left); pre(root.right); } public static void in(TreeNode root) { if(root == null) return; if(root.left != null) in(root.left); System.out.print(root.val+","); if(root.right != null) in(root.right); } } <file_sep>package removeDuplicatesfromSortedArray26; public class Test { public static void main(String[] args) { Solution s = new Solution(); int[] arr = new int[]{1,1,1,1,2}; int temp = s.removeDuplicates(arr); for(int i=0;i<temp;++i) { System.out.println(arr[i]); } } } <file_sep>package findtheDifference389; public class Solution { public char findTheDifference(String s, String t) { StringBuffer s1 = new StringBuffer(s); StringBuffer t1 = new StringBuffer(t); char result; for(int i=0;i<s1.length();++i) { result = s1.charAt(i); int index = t1.indexOf(Character.toString(result)); if(index == -1) { return result; } else { t1 = t1.deleteCharAt(index); } } return t1.charAt(0); } } <file_sep>package rotateArray189; public class Test { public static void main(String[] args) { Solution s = new Solution(); int[] arr = new int[]{1,2,3,4,5,6}; s.rotate(arr,3); for(int i=0;i<arr.length;++i) { System.out.println(arr[i]); } } } <file_sep>package stringtoInteger8; public class Solution { public int myAtoi(String str) { str = str.trim(); if(str.equals("")) { return 0; } boolean flag = false; long result = 0; long temps = 0; for(int i=0;i<str.length();++i) { char ch = str.charAt(i); if(ch == '-' && i == 0) { flag = true; } else if(ch == '+' && i == 0) { flag = false; } else if(Character.isDigit(ch) == false) { break; } else { int temp = Integer.parseInt(Character.toString(ch)); result = result * 10 + temp; if(flag == true) { temps = result * (-1); if(temps < Integer.MIN_VALUE) { return Integer.MIN_VALUE; } } else { temps = result; if(temps > Integer.MAX_VALUE) { return Integer.MAX_VALUE; } } } } return (int)temps; } } <file_sep>package maxDepthOfBinaryTree; public class Solution { public int maxDepth(TreeNode root) { if (null == root) { return 0; } else { int n = 1; int m = 1; if (null != root.left || null != root.right) { n = n + maxDepth(root.left); m = m + maxDepth(root.right); } if(n > m) { return n; } else { return m; } } } } <file_sep>package maximumSubarray53; /** * Created by zhaozhezijian on 2017/9/20. */ public class Solution { public int maxSubArray(int[] nums) { if(nums.length == 1) return nums[0]; int max = Integer.MIN_VALUE; int min = 0; int sum = 0; for (int i = 0; i < nums.length; i++) { sum += nums[i]; if(sum - min > max) max = sum-min; if(sum < min){ min = sum; } } return max; } } <file_sep>package pathSumII113; import java.util.List; public class Test { public static void main(String[] args) { Solution s = new Solution(); TreeNode root = new TreeNode(5); TreeNode node1 = new TreeNode(4); TreeNode node2 = new TreeNode(8); TreeNode node3 = new TreeNode(11); TreeNode node4 = new TreeNode(13); TreeNode node5 = new TreeNode(4); TreeNode node6 = new TreeNode(7); TreeNode node7 = new TreeNode(2); TreeNode node8 = new TreeNode(5); TreeNode node9 = new TreeNode(1); root.left = node1; root.right = node2; node1.left = node3; node2.left = node4; node2.right = node5; node3.left = node6; node3.right = node7; node5.left = node8; node5.right = node9; List<List<Integer>> lists = s.pathSum(root,22); for(List<Integer> list: lists) { for(int e : list) { System.out.print(e+","); } System.out.println(); } } } <file_sep>package combinationSum39; import java.util.List; /** * Created by zhaozhezijian on 2017/9/20. */ public class Test { public static void main(String[] args) { Solution s = new Solution(); int[] arr = new int[]{2}; List<List<Integer>> list = s.combinationSum(arr,1); for(List<Integer> l : list){ for(int i:l){ System.out.print(i+","); } System.out.println(); } } } <file_sep>package totalHammingDistance477; public class Test { public static void main(String[] args) { Solution s = new Solution(); int[] nums = new int[]{6,1,8,6,8}; System.out.println(s.totalHammingDistance(nums)); } } <file_sep>package kthSmallestElementinaBST230; import java.util.Stack; public class Solution { // private int sum = 0; private int result = 0; public int kthSmallest(TreeNode root, int k) { if(root == null) { return 0; } Stack<TreeNode> stack = new Stack<>(); TreeNode temp = root; while(temp != null) { stack.add(temp); temp = temp.left; } while(!stack.isEmpty()) { TreeNode curr = stack.pop(); k -= 1; if(k == 0) { result = curr.val; break; } if(curr.right != null) { curr = curr.right; while(curr != null) { stack.add(curr); curr = curr.left; } } } // order(root,k); return result; } // private void order(TreeNode root,int k) // { // if(root.left == null && root.right == null) // { // sum += 1; // if(sum == k) // { // result = root.val; // } // return; // } // if(root.left != null) // { // order(root.left,k); // } // sum += 1; // if(sum == k) // { // result = root.val; // return; // } // if(root.right != null) // { // order(root.right,k); // } // } } <file_sep>package deleteNodeinaBST450; public class Solution { public TreeNode deleteNode(TreeNode root, int key) { if(root == null) { return null; } if(root.val == key) { if(root.left == null && root.right == null) { return null; } if(root.left == null && root.right != null) { return root.right; } if(root.left != null && root.right == null) { return root.left; } } TreeNode temp = root; TreeNode prev = root; int dir = -1; while(temp != null && temp.val != key) { prev = temp; if(temp.val > key) { temp = temp.left; dir = 0; } else if(temp.val < key) { temp = temp.right; dir = 1; } } if(temp != null) { delete(prev,temp,dir); } return root; } private void delete(TreeNode prev,TreeNode root,int dir) { if(root.left == null && root.right == null) { if(dir == 0) { prev.left = null; } else { prev.right = null; } return; } if(root.left == null && root.right != null) { if(dir == 0) { prev.left = root.right; } else { prev.right = root.right; } return; } if(root.left != null && root.right == null) { if(dir == 0) { prev.left = root.left; } else { prev.right = root.left; } return; } TreeNode temp = root.left; TreeNode prevs = root; int t = 0; while(temp.right != null) { if(t == 0) { t = 1; } prevs = temp; temp = temp.right; } root.val = temp.val; delete(prevs,temp,t); } } <file_sep>package taskScheduler621; import java.util.*; public class Solution { public int leastInterval(char[] tasks, int n) { if(n == 0) return tasks.length; int num = tasks.length; int[] arr = new int[26]; for (int i = 0; i < num; i++) { int index = tasks[i] - 65; arr[index] = arr[index]+1; } Arrays.sort(arr); int i = 25; while(i >= 0 && arr[i] == arr[25]) i--; return Math.max(tasks.length, (arr[25] - 1) * (n + 1) + 25 - i); } } <file_sep>package decodeWays91; public class Test { public static void main(String[] args) { String str = "110"; Solution solution = new Solution(); System.out.println(solution.numDecodings(str)); } } <file_sep>package MinCostClimbingStairs746; public class Solution { public int minCostClimbingStairs(int[] cost) { if (cost == null || cost.length == 0) { return 0; } int len = cost.length; int[] dp = new int[len]; for (int i = 2; i < len; i++) { dp[i] = min(dp[i - 2] + cost[i - 2], dp[i - 1] + cost[i - 1]); } return min(dp[len - 2] + cost[len - 2], dp[len - 1] + cost[len - 1]); } private int min(int a, int b) { return a <= b ? a : b; } } <file_sep>package isomorphicStrings205; public class Test { public static void main(String[] args) { Solution solution = new Solution(); String s = "foo"; String t = "bar"; System.out.println(solution.isIsomorphic(s,t)); } } <file_sep>package reverse; public class TestReverse { public String reverse(String str) { int i = str.length(); char[] c = new char[i]; for (int j=0;j<str.length();++j) { c[j] = str.charAt(i-1); i-=1; } String str2 = new String(c); return str2; } } <file_sep>package findLargestValueinEachTreeRow515; import java.util.ArrayDeque; import java.util.ArrayList; import java.util.List; import java.util.Queue; public class Solution { public List<Integer> largestValues(TreeNode root) { List<Integer> list = new ArrayList<>(); Queue<TreeNode> que = new ArrayDeque<>(); if(root == null) { return list; } que.add(root); while(!que.isEmpty()) { int size = que.size(); for (int i=0;i<size;++i) { TreeNode temp = que.poll(); if(i == 0) { list.add(temp.val); } if(temp.val > list.get(list.size()-1)) { list.set(list.size()-1,temp.val); } if(temp.left != null) { que.add(temp.left); } if(temp.right != null) { que.add(temp.right); } } } return list; } } <file_sep>package bestTimetoBuyandSellStock121; public class Solution { public int maxProfit(int[] prices) { int imin = 0; int imax = 0; int mmax = 0; for(int i=0;i<prices.length;++i) { if(prices[i] < prices[imin]) { imin = i; imax = i; } if(prices[i] > prices[imax]) { imax = i; int temp = prices[imax] - prices[imin]; if(temp > mmax) { mmax = temp; } } } return mmax; } } <file_sep>package pascalsTriangle118; import java.util.ArrayList; import java.util.List; public class Solution { public List<List<Integer>> generate(int numRows) { List<List<Integer>> list = new ArrayList<>(); if(numRows == 0) { return list; } List<Integer> list2 = new ArrayList<>(); for(int i=0;i<numRows;++i) { List<Integer> listTemp = new ArrayList<>(); int itemp = 0; listTemp.add(1); while(itemp < list2.size()-1) { listTemp.add(list2.get(itemp) + list2.get(itemp+1)); itemp += 1; } if(i != 0) listTemp.add(1); list.add(listTemp); list2 = listTemp; } return list; } } <file_sep>package constructBinaryTreefromInorderandPostorderTraversal106; public class Test { public static void main(String[] args) { Solution s = new Solution(); int[] post = new int[]{4,7,5,2,6,3,1}; int[] in = new int[]{4,2,5,7,1,3,6}; TreeNode root = s.buildTree(in,post); post(root); System.out.println(); in(root); } public static void post(TreeNode root) { if(root == null) return; post(root.left); post(root.right); System.out.print(root.val+","); } public static void in(TreeNode root) { if(root == null) return; if(root.left != null) in(root.left); System.out.print(root.val+","); if(root.right != null) in(root.right); } } <file_sep>package topKFrequentElements347; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Set; public class Solution { public List<Integer> topKFrequent(int[] nums, int k) { Map<Integer,Integer> map = new HashMap<>(); for(int num : nums) { if(map.get(num) == null) { map.put(num,1); } else { map.put(num,map.get(num)+1); } } Collection<Integer> values = map.values(); Iterator<Integer> iter = values.iterator(); List<Integer> value = new ArrayList<>(); while(iter.hasNext()) { value.add(iter.next()); } Collections.sort(value); List<Integer> list = new ArrayList<>(); Set<Integer> set = map.keySet(); List<Integer> key = new ArrayList<>(); for(int num : set) { key.add(num); } while(k > 0) { boolean flag = false; for(Integer num : key) { if(map.get(num) == value.get(value.size()-1)) { list.add(num); value.remove(value.size()-1); k--; } if(k == 0) { flag = true; return list; } } if(flag == true) { break; } } return list; } } <file_sep>package excelSheetColumnNumber; public class Solution { public int titleToNumber(String s) { int sum = 0; for(int i=0;i<s.length();++i) { int temp = (int)s.charAt(i) - 64; sum = sum + (int)Math.pow(26, s.length()-i-1) * temp; } return sum; } } <file_sep>package intersectionOfTwoArrays; public class Test { public static void main(String[] args) { int[] s1 = new int[]{1, 2, 2, 3}; int[] s2 = new int[]{2, 2, 3}; Solution s = new Solution(); int[] s3 =s.intersection(s1,s2); for(int i=0;i<s3.length;++i) { System.out.println(s3[i]); } } } <file_sep>package binaryTreePreorderTraversal144; import java.util.ArrayList; import java.util.List; public class Solution { List<Integer> list = new ArrayList<>(); public List<Integer> preorderTraversal(TreeNode root) { traverse(root); return list; } private void traverse(TreeNode root) { if(root != null) { list.add(root.val); } else { return; } if(root.left != null) { traverse(root.left); } if(root.right != null) { traverse(root.right); } } } <file_sep>package pathSumIII437; import java.util.ArrayDeque; import java.util.ArrayList; import java.util.List; import java.util.Queue; import java.util.Stack; public class Solution { private int count = 0; public int pathSum(TreeNode root, int sum) { if(root == null) { return 0; } Queue<TreeNode> que = new ArrayDeque<>(); que.add(root); while(!que.isEmpty()) { TreeNode node = que.poll(); Stack<TreeNode> stack = new Stack<>(); List<TreeNode> visit = new ArrayList<>(); int sums = 0; TreeNode temp = node; while(temp != null) { stack.push(temp); sums += temp.val; temp = temp.left; } while(!stack.isEmpty()) { TreeNode cur = stack.peek(); if(cur.right != null) { if(visit.contains(cur.right)) { cur = stack.pop(); if(sums == sum) { count += 1; } sums = sums - cur.val; } else { cur = cur.right; visit.add(cur); while(cur != null) { stack.push(cur); sums += cur.val; cur = cur.left; } } } else { cur = stack.pop(); if(sums == sum) { count += 1; } sums = sums - cur.val; } } if(node.left != null) { que.add(node.left); } if(node.right != null) { que.add(node.right); } } return count; } } <file_sep>package addTwoNumbers2; public class Solution { public ListNode addTwoNumbers(ListNode l1, ListNode l2) { if(l1 == null || l2 == null) { return l1==null?l2:l1; } int mod = 0; int div = 0; ListNode h = null; ListNode l = h; boolean first = true; while(l1 != null && l2 != null) { div = (l1.val + l2.val + mod)%10; mod = (l1.val + l2.val + mod)/10; if(first) { h = new ListNode(div); l = h; first = false; } else { l.next = new ListNode(div); l = l.next; } l1 = l1.next; l2 = l2.next; } ListNode temp = l1==null ? l2:l1; while(temp != null) { div = (temp.val + mod)%10; mod = (temp.val + mod)/10; l.next = new ListNode(div); temp = temp.next; l = l.next; } if(mod != 0) { l.next = new ListNode(mod); } return h; } } <file_sep>package singleNumberIII260; import java.util.HashSet; import java.util.Set; public class Solution { public int[] singleNumber(int[] nums) { int[] result = new int[2]; Set<Integer> set = new HashSet<>(); for(int i=0;i<nums.length;i++) { if(set.contains(nums[i])) { set.remove(nums[i]); } else { set.add(nums[i]); } } Integer[] temp = set.toArray(new Integer[0]); result[0] = temp[0]; result[1] = temp[1]; return result; } } <file_sep>package productofArrayExceptSelf238; public class Solution { public int[] productExceptSelf(int[] nums) { int[] result = new int[nums.length]; int start = 1; int end = nums.length-2; int startSum = nums[0]; int endSum = nums[nums.length-1]; for(int i=0;i<result.length;++i) { result[i] = 1; } while(start < nums.length) { result[start] *= startSum; result[end] *= endSum; startSum = startSum * nums[start]; endSum = endSum * nums[end]; start += 1; end -= 1; } return result; } } <file_sep>package nextGreaterElementII503; public class Solution { public int[] nextGreaterElements(int[] nums) { int len = nums.length; int[] result = new int[len]; boolean flag = false; for(int i=0;i<len;++i) { int j = (i+1)%len; while(j != i) { flag = false; if(nums[j] > nums[i]) { flag = true; result[i] = nums[j]; break; } j = (j+1)%len; } if(flag == false) { result[i] = -1; } } return result; } } <file_sep>package balancedBinaryTree110; public class Test { public static void main(String[] args) { Solution s = new Solution(); TreeNode node1 = new TreeNode(1); TreeNode node2 = new TreeNode(1); TreeNode node3 = new TreeNode(1); TreeNode node4 = new TreeNode(1); TreeNode node5 = new TreeNode(1); TreeNode node6 = new TreeNode(1); TreeNode node7 = new TreeNode(1); node1.left = node2; node1.right = node3; node2.left = node4; node2.right = node5; node5.right = node6; node3.right = node7; System.out.println(s.deepth(node1)); System.out.println(s.isBalanced(node1)); } } <file_sep>package binaryTreeInorderTraversal94; import java.util.ArrayList; import java.util.List; public class Solution { private List<Integer> list = new ArrayList<>(); public List<Integer> inorderTraversal(TreeNode root) { traverse(root); return list; } public void traverse(TreeNode root) { if(root == null) { return; } if(root.left != null) traverse(root.left); list.add(root.val); if(root.right != null) traverse(root.right); } } <file_sep>package longestUnivaluePath687; public class Test { public static void main(String[] args) { TreeNode root = new TreeNode(1); TreeNode node1 = new TreeNode(4); TreeNode node2 = new TreeNode(5); TreeNode node3 = new TreeNode(4); TreeNode node4 = new TreeNode(4); TreeNode node6 = new TreeNode(5); root.left = node1; root.right = node2; node1.left = node3; node1.right = node4; node2.right = node6; Solution solution = new Solution(); System.out.println(solution.longestUnivaluePath(root)); } private static TreeNode buildTree(int[] arr) { if (arr == null || arr.length == 0) { return null; } TreeNode root = new TreeNode(arr[0]); int index = 0; while (index < arr.length){ } return root; } } <file_sep>package constructBinaryTreefromPreorderandInorderTraversal105; public class Solution { private int[] pre; private int[] in; public TreeNode buildTree(int[] preorder, int[] inorder) { this.in = inorder; this.pre = preorder; return build(0,0,in.length-1); } private TreeNode build(int start1, int start2, int end2) { if(start2 == end2) { return new TreeNode(in[start2]); } boolean isIn = false; TreeNode node = null; for(int i=start1;i<pre.length;++i) { for(int j=start2;j<=end2;++j) { if(pre[i] == in[j]) { isIn = true; node = new TreeNode(pre[i]); node.left = build(i+1,start2,j-1); node.right = build(i+1,j+1,end2); break; } } if(isIn == true) break; } return node; } } <file_sep>package constructBinaryTreefromInorderandPostorderTraversal106; public class Solution { private int[] post; private int[] in; public TreeNode buildTree(int[] inorder, int[] postorder) { this.in = inorder; this.post = postorder; return build(post.length-1,0,in.length-1); } private TreeNode build(int start1, int start2, int end2) { if(start2 == end2) { return new TreeNode(in[start2]); } boolean isIn = false; TreeNode node = null; for(int i=start1;i>=0;--i) { for(int j=start2;j<=end2;++j) { if(post[i] == in[j]) { isIn = true; node = new TreeNode(post[i]); node.right = build(i-1,j+1,end2); node.left = build(i-1,start2,j-1); break; } } if(isIn == true) break; } return node; } } <file_sep>package sameTree; public class Test { public static void main(String[] args) { TreeNode root1 = new TreeNode(2); TreeNode t1 = new TreeNode(5); TreeNode t2 = new TreeNode(4); TreeNode t3 = new TreeNode(1); TreeNode t4 = new TreeNode(1); TreeNode t5 = new TreeNode(3); root1.left = t1; root1.right = t2; t1.left = t3; t1.right = t4; t2.left = t5; TreeNode root2 = new TreeNode(2); TreeNode t12 = new TreeNode(5); TreeNode t22 = new TreeNode(4); TreeNode t32 = new TreeNode(1); TreeNode t42 = new TreeNode(1); TreeNode t52 = new TreeNode(3); root2.left = t12; root2.right = t32; t12.left = t22; t12.right = t42; t22.left = t52; Solution s = new Solution(); System.out.println(s.isSameTree(root1, root2)); } } <file_sep>package totalHammingDistance477; public class Solution { public int totalHammingDistance(int[] nums) { int sum = 0; for(int i=0;i<32;++i) { int count1 = 0; int count0 = 0; for(int j=0;j<nums.length;++j) { if(((nums[j] >> i) & 1 )== 1) { count1 += 1; } else { count0 += 1; } } sum += count1 * count0; } return sum; } } <file_sep>package integerBreak343; public class Solution { public int integerBreak(int n) { if(n == 2) { return 1; } if(n == 3) { return 2; } int product = 1; int mod = n % 3; int sub = n / 3; if(mod == 1) { sub -= 1; } for(int i=0;i<sub;++i) { product *= 3; } if(mod == 1) { product *= 4; } if(mod == 2) { product *= 2; } return product; } } <file_sep>package reverseNodesinkGroup25; public class Solution { public ListNode reverseKGroup(ListNode head, int k) { if(head == null) { return null; } int sum = 0; ListNode temp = head; while(temp != null) { sum += 1; temp = temp.next; } if(sum < k) { return head; } int num = sum / k; temp = head; ListNode l = head; while(temp != null) { if(num == 0) { break; } int index = k-1; if(num == sum/k) { while(index != 0) { ListNode curr = temp.next; temp.next = curr.next; curr.next = l; l = curr; index --; } num -= 1; head = l; } else { while(index != 0) { ListNode curr = temp.next; temp.next = curr.next; curr.next = l.next; l.next = curr; index --; } num -= 1; } l = temp; temp = temp.next; } return head; } } <file_sep>package subsetsII90; import java.util.List; /** * Created by zhaozhezijian on 2017/9/26. */ public class Test { public static void main(String[] args) { Solution s = new Solution(); int[] nums = new int[]{1,1,2,2}; List<List<Integer>> result = s.subsetsWithDup(nums); for (List<Integer> list : result){ for(int i : list){ System.out.print(i+","); } System.out.println(); } } } <file_sep>package romantoInteger13; public class Solution { public int romanToInt(String s) { int[] num = new int[s.length()]; for(int i=0;i<s.length();++i) { char ch = s.charAt(i); switch(ch) { case 'I': num[i] = 1; break; case 'V': num[i] = 5; break; case 'X': num[i] = 10; break; case 'L': num[i] = 50; break; case 'C': num[i] = 100; break; case 'D': num[i] = 500; break; case 'M': num[i] = 1000; break; } } int sum = num[num.length-1]; for(int i=num.length-1;i>0;--i) { if(num[i] > num[i-1]) { sum = sum - num[i-1]; } else { sum = sum + num[i-1]; } } return sum; } } <file_sep>package minesweeper529; public class Test { public static void main(String[] args) { Solution s = new Solution(); char[][] board = new char[][]{ {'E','E','E','E','E'}, {'E','E','M','E','E'}, {'E','E','E','E','E'}, {'E','E','E','E','E'}, }; int[] click = new int[2]; click[0] = 1; click[1] = 2; board = s.updateBoard(board,click); for(int i=0;i<board.length;++i) { String str = ""; for(int j=0;j<board[0].length;++j) { str = str + "," + Character.toString(board[i][j]); } System.out.println(str); } } } <file_sep>package findModeinBinarySearchTree501; import java.util.ArrayList; import java.util.List; public class Solution { private List<Integer> list = new ArrayList<>(); public int[] findMode(TreeNode root) { if(root == null) { return new int[]{}; } order(root); int max = 0; int count = 0; int curr = list.get(0); List<Integer> result = new ArrayList<>(); for(int i=0;i<list.size();++i) { if(list.get(i) == curr) { count += 1; if(i == list.size()-1) { if(count > max) { max = count; } } } else { if(count > max) { max = count; } count = 1; curr = list.get(i); } } count = 0; curr = list.get(0); System.out.println(max); for(int i=0;i<list.size();++i) { if(list.get(i) == curr) { count += 1; } else { count = 1; curr = list.get(i); } if(count == max) { result.add(list.get(i)); } } int[] arr = new int[result.size()]; for(int i=0;i<arr.length;++i) { arr[i] = result.get(i); } return arr; } private void order(TreeNode root) { if(root.left==null && root.right==null) { list.add(root.val); return; } if(root.left != null) { order(root.left); } list.add(root.val); if(root.right != null) { order(root.right); } } } <file_sep>package setMatrixZeroes73; import java.util.HashSet; import java.util.Set; /** * Created by zhaozhezijian on 2017/9/26. */ public class Solution { public void setZeroes(int[][] matrix) { if(matrix.length == 0 || matrix == null) return; int[] row = new int[matrix.length]; int[] col = new int[matrix[0].length]; for (int i = 0; i < matrix.length; i++) { for (int j = 0; j < matrix[0].length; j++) { if(matrix[i][j] == 0){ row[i] = 1; col[j] = 1; } } } for (int i = 0; i < row.length; i++) { if(row[i] == 1){ for (int j = 0; j < matrix[0].length; j++) { matrix[i][j] = 0; } } } for (int i = 0; i < col.length; i++) { if(col[i] == 1){ for (int j = 0; j < matrix.length; j++) { matrix[j][i] = 0; } } } } } <file_sep>package bullsAndCows299; public class Solution { public String getHint(String secret, String guess) { StringBuffer sec = new StringBuffer(secret); StringBuffer gue = new StringBuffer(guess); int bulls = 0; for(int i=0;i<sec.length();) { if(sec.charAt(i) == gue.charAt(i)) { bulls += 1; sec.deleteCharAt(i); gue.deleteCharAt(i); } else { i+=1; } } int cows = 0; for(int i=0;i<sec.length();) { boolean flag = false; for(int j=0;j<gue.length();) { if(sec.charAt(i) == gue.charAt(j)) { flag = true; cows += 1; sec.deleteCharAt(i); gue.deleteCharAt(j); break; } j += 1; } if(flag == false) i += 1; } String result = bulls + "A" + cows + "B"; return result; } } <file_sep>package validTriangleNumber611; import java.util.Arrays; public class Solution{ public int triangleNumber(int[] nums) { if(nums.length < 3) return 0; int sum = 0; Arrays.sort(nums); for (int i = 0; i < nums.length-2; i++) { for (int j = i+1; j < nums.length-1; j++) { int add = nums[i]+nums[j]; int k = j+1; while(k <= nums.length-1 && nums[k]<add){ sum+=1; k+=1; } } } return sum; } } <file_sep>package minimumDepthofBinaryTree111; public class Solution { public int minDepth(TreeNode root) { if(root == null) { return 0; } if(root.left == null && root.right == null) { return 1; } if(root.left == null) { return 1 + minDepth(root.right); } if(root.right == null) { return 1 + minDepth(root.left); } int i = 1 + minDepth(root.left); int j = 1 + minDepth(root.right); return i>j ? j : i; } // public int depth(TreeNode root) // { // if(root == null) // { // return 0; // } // if(root.left == null && root.right == null) // { // return 1; // } // if(root.left == null) // { // return 1 + depth(root.right); // } // if(root.right == null) // { // return 1 + depth(root.left); // } // int i = 1 + depth(root.left); // int j = 1 + depth(root.right); // // return i>j ? j : i; // // } } <file_sep>package binarySearchTreeIterator173; import java.util.Stack; public class BSTIterator { private Stack<TreeNode> stack = new Stack<>(); public BSTIterator(TreeNode root) { while(root != null) { stack.push(root); root = root.left; } } /** @return whether we have a next smallest number */ public boolean hasNext() { return stack.isEmpty()? false : true; } /** @return the next smallest number */ public int next() { TreeNode result = stack.pop(); TreeNode temp = result.right; while(temp != null) { stack.push(temp); temp = temp.left; } return result.val; } } <file_sep>package rotateList61; public class Solution { public ListNode rotateRight(ListNode head, int k) { if(head == null) { return null; } ListNode temp = head; int sum = 0; while(temp != null) { temp = temp.next; sum += 1; } k = k % sum; temp = head; ListNode curr = head; while(temp.next != null) { if(k <= 0) { curr = curr.next; } temp = temp.next; k -= 1; } temp.next = head; head = curr.next; curr.next = null; return head; } } <file_sep>package productofArrayExceptSelf238; public class Test { public static void main(String[] args) { Solution s = new Solution(); int[] arr = new int[]{0,1,2}; int[] result = s.productExceptSelf(arr); for(int num : result) { System.out.println(num); } } } <file_sep>package integerBreak343; public class Test { public static void main(String[] args) { Solution s = new Solution(); System.out.println(s.integerBreak(21)); } } <file_sep>package subsets78; import java.util.List; public class Test { public static void main(String[] args) { Solution s = new Solution(); int[] arr = new int[]{0}; List<List<Integer>> result = s.subsets(arr); for(List<Integer> list : result){ if(list.size() == 0){ System.out.println(","); continue; } for (int num : list) { System.out.print(num+","); } System.out.println(); } } } <file_sep>package uniqueBinarySearchTrees96; public class Solution { public int numTrees(int n) { if(n == 1) { return 1; } if(n == 2) { return 2; } int[] num = new int[n]; num[0] = 1; num[1] = 2; num[2] = 5; for(int i=3;i<n;++i) { int temp = 2*num[i-1]; int end = i-2; for(int j=0;j<=end;++j) { if(j == end) { temp += num[j]*num[j]; } else { temp += 2*num[j]*num[end]; } end -= 1; } num[i] = temp; System.out.println(temp); } return num[n-1]; } } <file_sep>package uniquePaths62; /** * Created by 赵喆子健 on 2017/8/30. */ public class Solution { public int uniquePaths(int m, int n) { if(m == 1 || n == 1) return 1; int[][] arr = new int[m][n]; for (int i = 0; i < n; i++) { arr[m-1][i] = 1; } for (int i = 0; i < m; i++) { arr[i][n-1] = 1; } for (int i = n-2; i >= 0; i--) { for (int j = m-2; j >= 0; j--) { arr[j][i] = arr[j+1][i]+arr[j][i+1]; } } return arr[0][0]; } } <file_sep>package linkedListRandomNode382; public class Solution { private ListNode head; private int length; /** @param head The linked list's head. Note that the head is guaranteed to be not null, so it contains at least one node. */ public Solution(ListNode head) { this.head = head; ListNode temp = head; while(temp != null) { length += 1; temp = temp.next; } } /** Returns a random node's value. */ public int getRandom() { int random = 1 + (int)(Math.random()*length); ListNode result = head; while(random > 1) { result = result.next; random -= 1; } return result.val; } } <file_sep>package numberof1Bits191; public class Solution { public int hammingWeight(int n) { int sum = 0; int i = 1; while(n != 0) { int temp = n&i; if(temp == 1) { sum+=1; } n = n >>> 1; } return sum; } } <file_sep>package sumII454; import java.util.HashMap; import java.util.Map; public class Solution { public int fourSumCount(int[] A, int[] B, int[] C, int[] D) { int sum = 0; Map<Integer,Integer> map = new HashMap<>(); for(int i=0;i<A.length;++i) { for(int j=0;j<B.length;++j) { if(map.containsKey(A[i]+B[j])) { map.put(A[i]+B[j],map.get(A[i]+B[j])+1); } else { map.put(A[i]+B[j],1); } } } for(int i=0;i<C.length;++i) { for(int j=0;j<D.length;++j) { int temp = C[i] + D[j]; if(map.containsKey(-temp)) { sum += map.get(-temp); } } } return sum; } } <file_sep>package binaryTreeRightSideView199; import java.util.ArrayDeque; import java.util.ArrayList; import java.util.List; import java.util.Queue; public class Solution { public List<Integer> rightSideView(TreeNode root) { List<Integer> list = new ArrayList<>(); if(root == null) { return list; } Queue<TreeNode> que = new ArrayDeque<>(); que.add(root); while(!que.isEmpty()) { int size = que.size(); for(int i=1;i<=size;++i) { TreeNode temp = que.poll(); if(i == size) { list.add(temp.val); } if(temp.left != null) que.add(temp.left); if(temp.right != null) que.add(temp.right); } } return list; } } <file_sep>package guessNumberHigherorLower374; public class Test { public static void main(String[] args) { Solution s = new Solution(1); System.out.println(s.guessNumber(3)); } } <file_sep>package rangeSumQueryImmutable303; public class Test { public static void main(String[] args) { int[] arr = new int[]{1,5,3,2,6}; NumArray numArray = new NumArray(arr); System.out.println(numArray.sumRange(3,3)); } } <file_sep>package pathSumII113; import java.util.ArrayList; import java.util.List; import java.util.Stack; public class Solution { public List<List<Integer>> pathSum(TreeNode root, int sum) { List<List<Integer>> list = new ArrayList<>(); if(root == null) return list; int cur = 0; TreeNode temp = root; Stack<TreeNode> stack = new Stack<>(); Stack<Integer> stack2 = new Stack<>(); List<TreeNode> visit = new ArrayList<>(); while(temp != null) { stack.push(temp); stack2.push(temp.val); cur += temp.val; temp = temp.left; } while(!stack.isEmpty()) { temp = stack.peek(); if(temp.right == null) { if(temp.left == null && cur == sum) { List<Integer> temps = new ArrayList<>(); temps.addAll(stack2); list.add(temps); } cur = cur - stack2.pop(); stack.pop(); } else if(temp.right != null) { if(visit.contains(temp.right)) { stack.pop(); cur -= stack2.pop(); continue; } temp = temp.right; visit.add(temp); while(temp != null) { stack.push(temp); stack2.push(temp.val); cur += temp.val; temp = temp.left; } } } return list; } } <file_sep>package beautifulArrangementII667; public class Test { public static void main(String[] args) { Solution s = new Solution(); int[] result = s.constructArray(7,6); for(int i : result) { System.out.println(i); } } } <file_sep>package numberOfIslands200; /** * Given a 2d grid map of '1's (land) and '0's (water), count the number of islands. * An island is surrounded by water and is formed by connecting adjacent lands horizontally or vertically. * You may assume all four edges of the grid are all surrounded by water. * * Example 1: * * Input: * 11110 * 11010 * 11000 * 00000 * * Output: 1 * Example 2: * * Input: * 11000 * 11000 * 00100 * 00011 * * Output: 3 */ public class Test { public static void main(String[] args) { char[][] arr = new char[][]{ {'1','0','0','1','0','1'}, }; Solution solution = new Solution(); System.out.println(solution.numIslands(arr)); } } <file_sep>package removeNthNodeFromEndofList19; public class Solution { public ListNode removeNthFromEnd(ListNode head, int n) { ListNode temp1 = head; ListNode temp2 = head; ListNode temp3 = head; for(int i=n;i>0;--i) { temp1 = temp1.next; } while(temp1 != null) { temp3 =temp2; temp1 = temp1.next; temp2 = temp2.next; } if(temp2 == head) { head = temp2.next; } else { temp3.next = temp2.next; } return head; } } <file_sep>package implementQueueusingStacks232; public class Test { public static void main(String[] args) { MyQueue queue = new MyQueue(); queue.push(12); queue.push(34); queue.push(56); System.out.println(queue.peek()); queue.pop(); System.out.println(queue.peek()); } } <file_sep>package convertBSTtoGreaterTree538; public class Test { public static void main(String[] args) { Solution s = new Solution(); TreeNode root = new TreeNode(10); TreeNode node1 = new TreeNode(7); TreeNode node2 = new TreeNode(11); TreeNode node3 = new TreeNode(6); TreeNode node4 = new TreeNode(8); TreeNode node5 = new TreeNode(4); TreeNode node6 = new TreeNode(15); TreeNode node7 = new TreeNode(21); root.left = node1; root.right = node2; node1.left = node3; node1.right = node4; node3.left = node5; node2.right = node6; node6.right = node7; TreeNode result = s.convertBST(root); System.out.println(result.val); } } <file_sep>package minimumMovestoEqualArrayElementsII462; public class Solution { public int minMoves2(int[] nums) { long min = 0; long sum = 0; for(int i=0;i<nums.length;++i) { for(int j=0;j<nums.length;++j) { sum += Math.abs(nums[i]-nums[j]); } System.out.println(sum); if(i == 0) { min = sum; } if(sum < min) { min = sum; } sum = 0; } return (int)min; } } <file_sep>package flattenBinaryTreetoLinkedList114; import java.util.ArrayList; import java.util.List; import java.util.Stack; public class Solution { public void flatten(TreeNode root) { if(root == null) return; if(root.left == null && root.right == null) return; Stack<TreeNode> stack = new Stack<>(); List<TreeNode> list = new ArrayList<>(); TreeNode temp = root; while(temp != null) { stack.push(temp); list.add(temp); temp = temp.left; } while(!stack.isEmpty()) { temp = stack.pop(); temp = temp.right; while(temp != null) { stack.push(temp); list.add(temp); temp = temp.left; } } for(int i=0;i<list.size()-1;++i) { temp = list.get(i); temp.left = null; temp.right = list.get(i+1); } } } <file_sep>package pascalsTriangle118; import java.util.List; public class Test { public static void main(String[] args) { Solution s = new Solution(); List<List<Integer>> list = s.generate(5); for(List<Integer> list2 : list) { System.out.println("["); for(Integer list3 : list2) { System.out.println(list3); } System.out.println("]"); } } } <file_sep>package findBottomLeftTreeValue513; import java.util.Stack; public class Solution { public int findBottomLeftValue(TreeNode root) { Stack<TreeNode> stack = new Stack<>(); int depth = 1; int maxDepth = 0; TreeNode maxNode = root; stack.push(root); TreeNode temp = root; while(temp.left != null) { stack.push(temp); depth += 1; temp = temp.left; } while(!stack.isEmpty()) { if(depth > maxDepth) { maxDepth = depth; maxNode = temp; } if(temp.right != null) { stack.push(temp.right); depth += 1; temp = temp.right; while(temp.left != null) { stack.push(temp); depth += 1; temp = temp.left; } } else { temp = stack.pop(); depth -= 1; } } return maxNode.val; } } <file_sep>package teemoAttacking495; public class Test { public static void main(String[] args) { Solution s = new Solution(); int[] arr = new int[]{1,65}; System.out.println(s.findPoisonedDuration(arr,23)); } } <file_sep>package intersectionOfTwoArrays; import java.util.ArrayList; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Set; public class Solution { public int[] intersection(int[] nums1, int[] nums2) { Set<Integer> num1 = new HashSet<Integer>(); Set<Integer> num2 = new HashSet<Integer>(); List<Integer> list = new ArrayList<Integer>(); for (int i=0;i<nums1.length;++i) { num1.add(nums1[i]); } for (int i=0;i<nums2.length;++i) { num2.add(nums2[i]); } Iterator<Integer> iter = num2.iterator(); while(iter.hasNext()) { int m = iter.next(); if(num1.contains(m)) { list.add(m); } } int sum = list.size(); int[] result = new int[sum]; for(int i=0;i<sum;++i) { result[i] = list.get(i).intValue(); } return result; } } <file_sep>package convertSortedListtoBinarySearchTree109; import java.util.ArrayList; import java.util.List; public class Solution { public TreeNode sortedListToBST(ListNode head) { if(head == null) { return null; } List<Integer> list = new ArrayList<>(); while(head != null) { list.add(head.val); head = head.next; } int n = list.size()/2+list.size()%2-1; TreeNode root = new TreeNode(list.get(n)); root.left = helper(list,0,n-1); root.right = helper(list,n+1,list.size()-1); return root; } private TreeNode helper(List<Integer> list, int start,int end) { if(start > end) { return null; } if(start == end) { return new TreeNode(list.get(start)); } else { TreeNode root = new TreeNode(list.get((start + end)/2)); root.left = helper(list,start,(start + end)/2-1); root.right = helper(list,(start + end)/2+1,end); return root; } } } <file_sep>package maximumSwap670; /** * Created by <NAME> on 2017/9/21. */ public class Test { public static void main(String[] args) { Solution s = new Solution(); System.out.println(s.maximumSwap(98368)); } } <file_sep>package pascalsTriangleII119; import java.util.List; public class Test { public static void main(String[] args) { Solution s = new Solution(); List<Integer> list = s.getRow(0); for(Integer num : list) { System.out.println(num); } } } <file_sep>package uniquePathsII63; public class Test { public static void main(String[] args) { int[][] arr = new int[][]{ {1,0,0,0,0}, {0,0,0,0,0}, {0,0,0,0,0}, {0,0,0,0,0}, }; Solution solution = new Solution(); System.out.println(solution.uniquePathsWithObstacles(arr)); for (int i = 0; i < arr.length; i++) { for (int j = 0; j < arr[0].length; j++) { System.out.print(arr[i][j]+","); } System.out.println(); } } } <file_sep>package validSudoku36; import java.util.ArrayList; import java.util.List; public class Solution { public boolean isValidSudoku(char[][] board) { for(int i=0;i<9;i++) { for(int j=0;j<8;++j) { if(board[i][j] == '.') { continue; } for(int k=j+1;k<9;++k) { if(board[i][k] == '.') { continue; } if(board[i][j] == board[i][k]) { return false; } } } } for(int i=0;i<9;i++) { for(int j=0;j<8;++j) { if(board[j][i] == '.') { continue; } for(int k=j+1;k<9;++k) { if(board[k][i] == '.') { continue; } if(board[j][i] == board[k][i]) { return false; } } } } for(int i=0;i<9;i+=3) { for(int j=0;j<9;j+=3) { List<Character> list = new ArrayList<>(); for(int k=i;k<i+3;++k) { for(int w=j;w<j+3;++w) { if(board[k][w] == '.') { continue; } if(list.contains(board[k][w])) { return false; } else { list.add(board[k][w]); } } } } } return true; } } <file_sep>package moveZeroes; import java.util.ArrayList; import java.util.List; public class Solution { public void moveZeroes(int[] nums) { int length = nums.length; List<Integer> list = new ArrayList<Integer>(); for (int i=0;i<length;++i) { if (0 != nums[i]) { list.add(nums[i]); } } for (int i=0;i<length;++i) { if (i < list.size()) { nums[i] = list.get(i); } else { nums[i] = 0; } } } } <file_sep>package reverse; public class Test { public static void main(String[] args) { TestReverse t = new TestReverse(); String str = t.reverse("hello world"); System.out.println(str); } } <file_sep>package twoSumIIInputarrayissorted167; public class Solution { public int[] twoSum(int[] numbers, int target) { int[] result = new int[2]; int start = 0; int end = numbers.length-1; while(start < end) { if(numbers[start] + numbers[end] == target) { result[0] = start + 1; result[1] = end + 1; break; } else if(numbers[start] + numbers[end] > target) { end = end-1; } else { start = start+1; } } return result; } } <file_sep>package printZeroEvenOdd1116; public class Test { public static void main(String[] args) throws Exception { ZeroEvenOdd zeroEvenOdd = new ZeroEvenOdd(100); Task zero = new Task(zeroEvenOdd,0); Task even = new Task(zeroEvenOdd,2); Task odd = new Task(zeroEvenOdd,1); zero.start(); Thread.sleep(200); even.start(); Thread.sleep(200); odd.start(); } static class Task extends Thread { private ZeroEvenOdd zeroEvenOdd; int mode = 0; private Printer printer = new Printer(); public Task(ZeroEvenOdd zeroEvenOdd, int mode) { this.mode = mode; this.zeroEvenOdd = zeroEvenOdd; } @Override public void run() { try { switch (mode) { case 0: zeroEvenOdd.zero(printer); break; case 1: zeroEvenOdd.odd(printer); break; default: zeroEvenOdd.even(printer); } } catch (Exception e) { } } } } <file_sep>package reverseLinkedList; public class Solution { public ListNode reverseList(ListNode head) { if (null == head) { return null; } else if(head.next == null) { return head; } ListNode now = head; ListNode next = head.next; ListNode temp = next.next; head.next = null; while(temp != null) { next.next = now; now = next; next = temp; temp = temp.next; } next.next = now; return next; } } <file_sep>package queueReconstructionbyHeight406; public class Test { public static void main(String[] args) { Solution s = new Solution(); int[][] people = new int[][]{ {7,0},{4,4},{7,1},{5,0},{6,1},{5,2}, }; int[][] result = s.reconstructQueue(people); for(int i=0;i<result.length;i++) { System.out.println(result[i][0]+","+result[i][1]); } } } <file_sep>package addBinary67; public class Test { public static void main(String[] args) { Solution s = new Solution(); System.out.println(s.addBinary("111","11101")); //temp } } <file_sep>package battleshipsinaBoard419; public class Test { public static void main(String[] args) { Solution s = new Solution(); char[][] board2 = new char[][]{{'X','.','X'},{'X','.','X'}}; int sum = s.countBattleships(board2); System.out.println(sum); } } <file_sep>package containsDuplicate; public class Test { public static void main(String[] args) { Solution s = new Solution(); int[] nums = new int[]{1, 2, 3, 4, 1}; System.out.println(s.containsDuplicate(nums)); } } <file_sep>package beautifulArrangement526; public class Solution { private int count; public int countArrangement(int N) { int[] arr = new int[N+1]; help(1,N,arr); return count; } public void help(int pos,int N, int[] arr) { if(pos == N+1) { count ++; return; } else { for(int i=1;i<=N;++i) { if(arr[i] == 0 && (i % pos == 0 || pos % i == 0)) { arr[i] = 1; help(pos+1,N,arr); arr[i] = 0; } } } } } <file_sep>package shuffleAnArray384; public class Test { public static void main(String[] args) { int[] arr = new int[]{1,2,3,4,5}; Solution s = new Solution(arr); int[] result = s.shuffle(); for(int num : result) { System.out.println(num); } result = s.reset(); for(int num : result) { System.out.println(num); } result = s.shuffle(); for(int num : result) { System.out.println(num); } } } <file_sep>package subarraySumEqualsK560; /** * Created by <NAME> on 2017/9/19. */ public class Test { public static void main(String[] args) { Solution s = new Solution(); int[] nums = new int[]{1,2,3,2,1,2,3,1}; nums = new int[]{}; System.out.println(s.subarraySum(nums,3)); } } <file_sep>package firstBadVersion278; public class VersionControl { public int[] arr = new int[]{0,0,0,0}; public boolean isBadVersion(int n) { if(arr[n-1] == 0) { return true; } else { return false; } } } <file_sep>package mergeSortedArray88; public class Solution { public void merge(int[] nums1, int m, int[] nums2, int n) { int itemp = 0; int jtemp = 0; if(m == 0) { while(jtemp < n) { nums1[itemp] = nums2[jtemp]; itemp += 1; jtemp += 1; } } while(jtemp < n && itemp < m) { boolean end = false; while(nums2[jtemp] >= nums1[itemp]) { if(itemp == m - 1) { end = true; break; } itemp += 1; } if(end) { while(jtemp < n) { nums1[m] = nums2[jtemp]; m += 1; jtemp += 1; } break; } int move = m-1; while(move >= itemp) { nums1[move+1] = nums1[move]; move -= 1; } nums1[itemp] = nums2[jtemp]; itemp += 1; jtemp += 1; m += 1; } } } <file_sep>package validateBinarySearchTree98; import java.util.Stack; public class Solution { public boolean isValidBST(TreeNode root) { if(root == null) { return true; } Stack<TreeNode> stack = new Stack<>(); TreeNode temp = root; while(temp != null) { stack.add(temp); temp = temp.left; } TreeNode pre = null; while(!stack.isEmpty()) { temp = stack.pop(); if(pre != null && temp.val < pre.val) return false; else pre = temp; if(temp.right != null) { temp = temp.right; while(temp != null) { stack.add(temp); temp = temp.left; } } } return true; } } <file_sep>package implementQueueusingStacks232; import java.util.Stack; public class MyQueue { private Stack<Integer> stack = new Stack<>(); public void push(int x) { Stack<Integer> temp = new Stack<>(); while(stack.isEmpty() == false) { int i = stack.pop(); temp.push(i); } stack.push(x); while(temp.isEmpty() == false) { int i = temp.pop(); stack.push(i); } } public void pop() { stack.pop(); } public int peek() { return stack.peek(); } public boolean empty() { return stack.isEmpty(); } } <file_sep>package subarraySumEqualsK560; /** * Created by <NAME> on 2017/9/19. */ public class Solution { public int subarraySum(int[] nums, int k) { int sum = 0; for (int i = 0; i < nums.length; i++) { int temp = 0; for (int j = i; j < nums.length; j++) { temp += nums[j]; if(temp == k) sum += 1; } } return sum; } } <file_sep>package diagonalTraverse498; public class Test { public static void main(String[] args) { Solution s = new Solution(); int[][] arr = new int[][]{ {1,2,3,4}, {5,6,7,8}, // {7,8,9}, // {10,11,12}, }; int[] result = s.findDiagonalOrder(arr); for(int n : result) { System.out.println(n); } } } <file_sep>package removeElement27; public class Test { public static void main(String[] args) { Solution s = new Solution(); int[] arr = new int[]{1,2}; int temp = s.removeElement(arr,2); System.out.println(temp); for(int i=0;i<temp;++i) { System.out.println(arr[i]); } } } <file_sep>package removeLinkedListElements203; public class Solution { public ListNode removeElements(ListNode head, int val) { if(head == null) { return null; } while(head.val == val) { head = head.next; if(head == null) { return null; } } ListNode l1 = head; ListNode before = head; while(l1 != null) { if(l1.val == val) { l1 = l1.next; before.next = l1; } else { before = l1; l1 = l1.next; } } return head; } } <file_sep>package missingNumber268; public class Solution { public int missingNumber(int[] nums) { /* * Method 1 */ int result = 0; for(int i=0;i<nums.length;i++) { result ^= i ^ nums[i]; } result ^= nums.length; return result; /* * Method 2 long sum1 = 0; long sum2 = 0; for(int i=0;i<nums.length;i++) { sum1 += nums[i]; sum2 += i; } sum2 += nums.length; return (int)(sum2 - sum1); */ } } <file_sep>package countingBits338; public class Solution { public int[] countBits(int num) { int[] result = new int[num+1]; result[0] = 0; if(num == 0) { return result; } if(num == 1) { result[1] = 1; return result; } result[1] = 1; int n = 2; boolean flag = false; while(true) { for(int i=n;i<2*n;++i) { if(i == num+1) { flag = true; break; } result[i] = 1 + result[i-n]; } if(flag == true) { break; } n = 2 * n; } return result; } } <file_sep>package surroundedRegions130; import java.util.*; /** * Created by zhaozhezijian on 2020/1/6. */ public class Solution { public void solve(char[][] board) { if (board == null || board.length <= 1 || board[0].length <= 1) { return; } Set<String> inValid = new HashSet<>(); for (int i = 0; i < board.length; i++) { for (int j = 0; j < board[0].length; j++) { if (!isBorder(i, j, board) || board[i][j] != 'O') { continue; } Deque<String> stack = new ArrayDeque<>(); Set<String> visited = new HashSet<>(); stack.push(i + "," + j); while (!stack.isEmpty()) { String string = stack.pop(); int iTemp = Integer.parseInt(string.split(",")[0]); int jTemp = Integer.parseInt(string.split(",")[1]); visited.add(string); inValid.add(string); if (iTemp - 1 >= 0 && board[iTemp - 1][jTemp] == 'O' && !visited.contains(iTemp - 1 + "," + jTemp)) { stack.push(iTemp - 1 + "," + jTemp); } if (iTemp + 1 < board.length && board[iTemp + 1][jTemp] == 'O' && !visited.contains(iTemp + 1 + "," + jTemp)) { stack.push(iTemp + 1 + "," + jTemp); } if (jTemp - 1 >= 0 && board[iTemp][jTemp - 1] == 'O' && !visited.contains(iTemp + "," + (jTemp - 1))) { stack.push(iTemp + "," + (jTemp - 1)); } if (jTemp + 1 < board[0].length && board[iTemp][jTemp + 1] == 'O' && !visited.contains(iTemp + "," + (jTemp + 1))) { stack.push(iTemp + "," + (jTemp + 1)); } } } } for (int i = 0; i < board.length; i++) { for (int j = 0; j < board[0].length; j++) { if (board[i][j] == 'O' && !inValid.contains(i + "," + j)) { board[i][j] = 'X'; } } } } private boolean isBorder(int i, int j, char[][] board) { return i * j == 0 || i == board.length - 1 || j == board[0].length - 1; } } <file_sep>package sumII454; public class Test { public static void main(String[] args) { Solution s = new Solution(); int[] A = new int[]{1,2,3}; int[] B = new int[]{-2,-1,-3}; int[] C = new int[]{-1,2,2}; int[] D = new int[]{0,2,1}; System.out.println(s.fourSumCount(A,B,C,D)); } } <file_sep>package setMatrixZeroes73; /** * Created by zhaozhezijian on 2017/9/26. */ public class Test { public static void main(String[] args) { Solution s = new Solution(); int[][] nums = new int[][]{{1,2,3,4},{1,0,2,3},{0,1,2,0}}; s.setZeroes(nums); for (int i = 0; i < nums.length; i++) { for (int j = 0; j < nums[0].length; j++) { System.out.print(nums[i][j]+","); } System.out.println(); } } } <file_sep>package isSubsequence392; public class Test { public static void main(String[] args) { Solution s = new Solution(); System.out.println(s.isSubsequence("axc","aojobkldljc")); } } <file_sep>package diagonalTraverse498; public class Solution { public int[] findDiagonalOrder(int[][] matrix) { if(matrix.length == 0) { return new int[0]; } int row = matrix.length; int col = matrix[0].length; int[] result = new int[col*row]; boolean trav = false; int i = 0; int j = 0; int index = 0; while(i != row && j != col) { if(trav == false) { while(i != 0 && j != col-1) { result[index] = matrix[i][j]; index ++; i -= 1; j += 1; } result[index] = matrix[i][j]; index ++; if(j == col-1) { i ++; } else if(i == 0) { j ++; } trav = true; } else { while(j != 0 && i != row-1) { result[index] = matrix[i][j]; index ++; i += 1; j -= 1; } result[index] = matrix[i][j]; index ++; if(i == row-1) { j ++; } else if(j == 0) { i ++; } trav = false; } } return result; } } <file_sep>package diameterofBinaryTree543; public class Solution { private int max = 0; public int diameterOfBinaryTree(TreeNode root) { if(root == null) { return 0; } depth(root); return max; } private int depth(TreeNode root) { if(root == null) { return 0; } if(root.left == null && root.right == null) { return 1; } int left = 0; int right = 0; if(root.left != null) { left = depth(root.left); } if(root.right != null) { right = depth(root.right); } if(left + right > max) { max = left + right; } return Math.max(left,right)+1; } } <file_sep>package battleshipsinaBoard419; public class Solution { public int countBattleships(char[][] board) { int row = board.length; int col = board[0].length; int sum = 0; if(row == 1 && col == 1) { return board[0][0] == 'X'? 1:0; } for(int i=0;i<row;i++) { for(int j=0;j<col;j++) { if(board[i][j] == 'X') { if(i!= row-1 && j!=col-1) { if(board[i][j+1] == 'X') { sum += 1; for(int k=j+1;k<col;++k) { if(board[i][k] == 'X') { board[i][k] = '.'; } else { break; } } } else if(board[i+1][j] == 'X') { sum += 1; for(int k=i+1;k<row;++k) { if(board[k][j] == 'X') { board[k][j] = '.'; } else { break; } } } else { sum += 1; } } else if(i == row-1 && j != col-1) { if(board[i][j+1] == 'X') { sum += 1; for(int k=j+1;k<col;++k) { if(board[i][k] == 'X') { board[i][k] = '.'; } else { break; } } } else { sum += 1; } } else if (j == col-1 && i != row-1) { if(board[i+1][j] == 'X') { sum += 1; for(int k=i+1;k<row;++k) { if(board[k][j] == 'X') { board[k][j] = '.'; } else { break; } } } else { sum += 1; } } else { if(board[i][j] == 'X') { sum += 1; } } } } } return sum; } } <file_sep>package sumofTwoIntegers; public class Solution { public int getSum(int a, int b) { int result; if(a == b) { result = 2 * a; } else { double temp = (double)a - (double)b; double num1 = Math.pow(a,2); double num2 = Math.pow(b,2); result = (int)((num1 - num2)/(temp)); } return result; } } <file_sep>package findMinimuminRotatedSortedArray153; /** * Created by <NAME> on 2017/9/19. */ public class Solution { public int findMin(int[] nums) { if (nums.length == 1) return nums[0]; if(nums[0] < nums[nums.length-1]) return nums[0]; int start = 0; int end = nums.length-1; while(Math.abs(start-end) != 1){ int mid = (start+end)/2; if(nums[mid] > nums[start] && nums[mid]>nums[end]){ start = mid; }else if(nums[mid] < nums[start] && nums[mid] < nums[end]){ end = mid; } } return nums[start] > nums[end]? nums[end]:nums[start]; } }
429bee7bf9801cb82daddb8f99a7572582f85706
[ "Java" ]
132
Java
Ral-Zhao/leetcode
5d0a060b64888645f4e765ec89cb9031b71697ee
113b0a0a344c6efbff3288ec506281f3c9276ce3
refs/heads/master
<repo_name>asrbrr/ProgrammingAssignment2<file_sep>/cachematrix.R ## Inverts matrices but caching resuts so as to not to have to repeat the ## operation makeCacheMatrix <- function(x = matrix()) { ## Crates a class of `matrix` that is able to lookup values in parent namespaces. ## This will be used to store the inverse (the first time is computed) into ## the global namespace and thus not re-copute it in next ocassions. inverse_matr <- NULL set <- function(y) { x <<- y inverse_matr <<- NULL } get <- function() x set_inverse <- function(inv) inverse_matr <<- inv #save to global namespace get_inverse <- function() inverse_matr list(set = set, get = get, set_inverse = set_inverse, get_inverse = get_inverse) } cacheSolve <- function(x, ...) { ## Gets the inverse of matrix x, where x is a makeCacheMatrix kind of object. ## In first time, the inverse is explicitly evaluated and stored. In the next ## evaluations, the inverse is retrieved form the makeCacheMatrix container. inv <- x$get_inverse() if(!is.null(inv)) { message("getting cached data") return(inv) #return cached data, and done. } data <- x$get() inv <- solve(data) #this is the actual computation of the inverse matrix x$set_inverse(inv) #this stores it inv }
3e1227aacb5a8a7e01f7ecabeb4e95f63b3dab8d
[ "R" ]
1
R
asrbrr/ProgrammingAssignment2
e5caff754c3dcee0a5be7221471ecc678dfa5484
2f9adb282ff7abf58dc2126c4bcab6aeb3518c56
refs/heads/master
<file_sep>package com.example.vetclinicapp.dtos; import com.example.vetclinicapp.domain.entities.Doctor; import lombok.Builder; import lombok.Value; import javax.validation.constraints.NotNull; import javax.validation.constraints.Size; import java.time.LocalDate; import java.time.LocalTime; @Value @Builder public class AppointmentRequest { @NotNull LocalDate dateOfAppointment; @NotNull LocalTime timeOfAppointment; @NotNull Doctor doctor; @NotNull @Size(max = 4, min = 4) String code; @NotNull @Size(max = 4, min = 4) String pin; } <file_sep>package com.example.vetclinicapp.services; import com.example.vetclinicapp.controllers.exceptions.ResourceNotFoundException; import com.example.vetclinicapp.controllers.exceptions.ResourceNotUniqueException; import com.example.vetclinicapp.domain.entities.Appointment; import com.example.vetclinicapp.domain.entities.Client; import com.example.vetclinicapp.domain.repositories.AppointmentRepository; import com.example.vetclinicapp.domain.repositories.ClientRepository; import com.example.vetclinicapp.dtos.AppointmentRequest; import com.example.vetclinicapp.dtos.AppointmentResponse; import com.example.vetclinicapp.mappers.AppointmentMapper; import lombok.RequiredArgsConstructor; import org.springframework.stereotype.Service; import javax.transaction.Transactional; import java.time.LocalDate; import java.util.List; import java.util.stream.Collectors; @Service @RequiredArgsConstructor public class AppointmentServiceImpl implements AppointmentService { private final AppointmentRepository appointmentRepository; private final ClientRepository clientRepository; @Override public List<AppointmentResponse> findAll() { return appointmentRepository.findAll().stream() .map(AppointmentMapper::mapToAppointmentResponse) .collect(Collectors.toList()); } @Override public List<AppointmentResponse> findAllByDoctorIdAndDateOfAppointment(Long doctorId, String dateOfAppointment) { return appointmentRepository.findByDoctorIdAndDate(doctorId, LocalDate.parse(dateOfAppointment)).stream() .map(AppointmentMapper::mapToAppointmentResponse) .collect(Collectors.toList()); } @Transactional @Override public AppointmentResponse create(AppointmentRequest appointmentRequest) { Client client = clientRepository.findByCodeAndPin(appointmentRequest.getCode(), appointmentRequest.getPin()); Appointment appointment = AppointmentMapper.mapRequestToEntity(appointmentRequest, client); if (!appointmentRepository.existsByDoctorAndDateOfAppointmentAndTimeOfAppointment(appointment.getDoctor(), appointment.getDateOfAppointment(), appointment.getTimeOfAppointment())) { appointmentRepository.save(appointment); } else throw new ResourceNotUniqueException("There is already exist an appointment on this time !"); return AppointmentMapper.mapToAppointmentResponse(appointment); } @Transactional @Override public void delete(Long id) { Appointment appointment = appointmentRepository.findById(id) .orElseThrow(() -> new ResourceNotFoundException("Appointment with id: " + id + " not found")); appointmentRepository.delete(appointment); } } <file_sep>package com.example.vetclinicapp.domain.entities; import lombok.*; import javax.persistence.*; import javax.validation.constraints.Size; import java.util.ArrayList; import java.util.List; import java.util.UUID; @Getter @Setter @ToString @EqualsAndHashCode(of = "uuid") @Entity @Table(name = "doctors") @Builder @NoArgsConstructor @AllArgsConstructor public class Doctor { @Id @GeneratedValue(strategy = GenerationType.AUTO) private Long id; private final String uuid = UUID.randomUUID().toString(); @Column(nullable = false) @Size(max = 30) private String firstName; @Column(nullable = false) @Size(max = 30) private String lastName; @OneToMany(targetEntity = Appointment.class, mappedBy = "doctor", orphanRemoval = true, cascade = CascadeType.PERSIST) private List<Appointment> appointments = new ArrayList<>(); } <file_sep>package com.example.vetclinicapp.mappers; import com.example.vetclinicapp.domain.entities.Appointment; import com.example.vetclinicapp.domain.entities.Client; import com.example.vetclinicapp.dtos.AppointmentRequest; import com.example.vetclinicapp.dtos.AppointmentResponse; import com.example.vetclinicapp.dtos.ClientResponse; import com.example.vetclinicapp.dtos.DoctorResponse; public class AppointmentMapper { public static Appointment mapRequestToEntity(AppointmentRequest request, Client client) { return Appointment.builder() .dateOfAppointment(request.getDateOfAppointment()) .timeOfAppointment(request.getTimeOfAppointment()) .doctor(request.getDoctor()) .client(client) .build(); } public static AppointmentResponse mapToAppointmentResponse(Appointment appointment) { final DoctorResponse doctorResponse = DoctorResponse.builder() .id(appointment.getDoctor().getId()) .firstName(appointment.getDoctor().getFirstName()) .lastName(appointment.getDoctor().getLastName()) .build(); final ClientResponse clientResponse = ClientResponse.builder() .id(appointment.getClient().getId()) .firstName(appointment.getClient().getFirstName()) .lastName(appointment.getClient().getLastName()) .animal(appointment.getClient().getAnimal()) .build(); return AppointmentResponse.builder() .id(appointment.getId()) .dateOfAppointment(appointment.getDateOfAppointment()) .timeOfAppointment(appointment.getTimeOfAppointment()) .doctor(doctorResponse) .client(clientResponse) .build(); } } <file_sep>package com.example.vetclinicapp.services.fixtures; import com.example.vetclinicapp.domain.entities.Appointment; import com.example.vetclinicapp.domain.entities.Client; import com.example.vetclinicapp.domain.entities.Doctor; import com.example.vetclinicapp.dtos.AppointmentRequest; import java.time.LocalDate; import java.time.LocalTime; import java.util.ArrayList; import java.util.Collections; import java.util.List; public class AppointmentFixture { public static List<Appointment> appointmentListFixture() { List<Appointment> appointments = new ArrayList<>(); appointments.add(appointmentFixture()); return appointments; } public static Appointment appointmentFixture() { return Appointment.builder() .id(1L) .dateOfAppointment(LocalDate.now().plusDays(5)) .timeOfAppointment(LocalTime.parse("12:00")) .doctor(doctorFixture()) .client(clientFixture()) .build(); } public static AppointmentRequest appointmentRequestFixture() { return AppointmentRequest.builder() .dateOfAppointment(LocalDate.now().plusDays(3)) .timeOfAppointment(LocalTime.parse("11:00")) .doctor(doctorFixture()) .code("1111") .pin("0101") .build(); } public static AppointmentRequest createAppointmentRequestFixture() { return AppointmentRequest.builder() .dateOfAppointment(LocalDate.now().plusDays(3)) .timeOfAppointment(LocalTime.parse("11:00")) .doctor(doctorFixture()) .code("0001") .pin("0011") .build(); } public static AppointmentRequest appointmentRequestFixtureWithExistingAppointmentInDatabase() { return AppointmentRequest.builder() .dateOfAppointment(LocalDate.now().plusDays(3)) .timeOfAppointment(LocalTime.parse("11:00")) .doctor(doctorFixture()) .code("1111") .pin("0101") .build(); } public static AppointmentRequest appointmentRequestFixtureWith(LocalDate date, LocalTime time, Doctor doctor, String code, String pin) { return AppointmentRequest.builder() .dateOfAppointment(date) .timeOfAppointment(time) .doctor(doctor) .code(code) .pin(pin) .build(); } public static Doctor doctorFixture() { return Doctor.builder() .id(1L) .firstName("Jan") .lastName("Kowalski") .appointments(Collections.emptyList()) .build(); } public static Client clientFixture() { return Client.builder() .id(1L) .firstName("Stefan") .lastName("Nowak") .animal("Kot") .code("1111") .pin("0101") .appointments(Collections.emptyList()) .build(); } } <file_sep>package com.example.vetclinicapp; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; @SpringBootApplication public class VetClinicAppApplication { public static void main(String[] args) { SpringApplication.run(VetClinicAppApplication.class, args); } } <file_sep># <NAME> - recruiting task - "Vet Clinic app" ## What you'll build - A simple Spring Boot REST application with H2 ## Stack - Java 8 - Spring Boot 2+ - Hibernate - H2 - Maven ## Run - Access to http://localhost:8080/api/v1/appointments - Database H2 - http://localhost:8080/h2-console Examples endpoints: POST - http://localhost:8080/api/v1/appointment { "dateOfAppointment": "2021-02-02", "timeOfAppointment": "14:30:00", "doctor": { "id": 1, "firstName": "Stefan", "lastName": "Nowak" }, "code": "0003", "pin": "0033" } GET - http://localhost:8080/api/v1/appointment/doctor/1?dateOfAppointment=2021-02-02<file_sep>package com.example.vetclinicapp.controllers; import com.example.vetclinicapp.dtos.AppointmentRequest; import io.restassured.http.ContentType; import org.junit.Test; import org.springframework.http.HttpStatus; import java.time.LocalDate; import java.time.LocalTime; import static com.example.vetclinicapp.services.fixtures.AppointmentFixture.*; import static io.restassured.module.mockmvc.RestAssuredMockMvc.given; import static io.restassured.module.mockmvc.RestAssuredMockMvc.when; public class AppointmentControllerTest extends AbstractControllerIntegrationTest { private static final String APPOINTMENTS_URL = BASE_API_URL + "/appointments"; private static final String APPOINTMENT_URL = BASE_API_URL + "/appointment"; @Test public void shouldReturnAppointmentList_whenCallGetAppointmentsApi_withStatus200() { when() .get(APPOINTMENTS_URL) .then() .statusCode(HttpStatus.OK.value()); } @Test public void shouldReturnCreatedAppointment_whenCallPostAppointmentsApi_withStatus201() { AppointmentRequest appointmentRequest = createAppointmentRequestFixture(); given() .body(appointmentRequest) .contentType(ContentType.JSON) .when() .post(APPOINTMENT_URL) .then() .statusCode(HttpStatus.CREATED.value()); } @Test public void shouldReturnConflictAppointment_whenCallPostAppointmentsApi_withExistingAppointmentInDatabase() { AppointmentRequest appointmentRequest = createAppointmentRequestFixture(); given() .body(appointmentRequest) .contentType(ContentType.JSON) .when() .post(APPOINTMENT_URL); given() .body(appointmentRequest) .contentType(ContentType.JSON) .when() .post(APPOINTMENT_URL) .then() .statusCode(HttpStatus.CONFLICT.value()); } @Test public void shouldReturnBadRequest_whenCallPostAppointmentsApi_withRequestWithoutDateOfAppointment() { AppointmentRequest appointmentRequest = appointmentRequestFixtureWith(null, LocalTime.parse("12:00"), doctorFixture(), "0011", "1100"); given().body(appointmentRequest) .contentType(ContentType.JSON) .when() .post(APPOINTMENT_URL) .then() .statusCode(HttpStatus.BAD_REQUEST.value()); } @Test public void shouldReturnBadRequest_whenCallPostAppointmentsApi_withRequestWithoutTimeOfAppointment() { AppointmentRequest appointmentRequest = appointmentRequestFixtureWith(LocalDate.now().plusDays(3), null, doctorFixture(), "0011", "1100"); given().body(appointmentRequest) .contentType(ContentType.JSON) .when() .post(APPOINTMENT_URL) .then() .statusCode(HttpStatus.BAD_REQUEST.value()); } @Test public void shouldReturnBadRequest_whenCallPostAppointmentsApi_withRequestWithoutDoctor() { AppointmentRequest appointmentRequest = appointmentRequestFixtureWith(LocalDate.now().plusDays(3), LocalTime.parse("12:00"), null, "0011", "1100"); given().body(appointmentRequest) .contentType(ContentType.JSON) .when() .post(APPOINTMENT_URL) .then() .statusCode(HttpStatus.BAD_REQUEST.value()); } @Test public void shouldReturnBadRequest_whenCallPostAppointmentsApi_withRequestWithoutCode() { AppointmentRequest appointmentRequest = appointmentRequestFixtureWith(LocalDate.now().plusDays(3), LocalTime.parse("12:00"), doctorFixture(), null, "1100"); given().body(appointmentRequest) .contentType(ContentType.JSON) .when() .post(APPOINTMENT_URL) .then() .statusCode(HttpStatus.BAD_REQUEST.value()); } @Test public void shouldReturnBadRequest_whenCallPostAppointmentsApi_withRequestWithoutPin() { AppointmentRequest appointmentRequest = appointmentRequestFixtureWith(LocalDate.now().plusDays(3), LocalTime.parse("12:00"), doctorFixture(), "0011", null); given().body(appointmentRequest) .contentType(ContentType.JSON) .when() .post(APPOINTMENT_URL) .then() .statusCode(HttpStatus.BAD_REQUEST.value()); } @Test public void shouldDeletedAppointment_whenCallDeleteAppointmentsApi_withStatus200() { AppointmentRequest appointmentRequest = createAppointmentRequestFixture(); given() .body(appointmentRequest) .contentType(ContentType.JSON) .when() .post(APPOINTMENT_URL); when() .delete(APPOINTMENT_URL + "/2") .then() .statusCode(HttpStatus.OK.value()); } @Test public void shouldReturn404_whenCallFindAppointmentByIdToDelete_withNonExistsId() { when() .delete(APPOINTMENT_URL + "/100") .then() .statusCode(HttpStatus.NOT_FOUND.value()); } }
e3b4aae15932a3fce13ec23b9330fbb89d6407e0
[ "Markdown", "Java" ]
8
Java
mackenziepl/vet-clinic-app
88baacb543f14cf8f9d2e91c297464e64fa81366
309089f9dcbaaa2b2009a6ff847364f9b9bd6fea
refs/heads/master
<repo_name>HenriqueOliveira07/Hero<file_sep>/client/src/app/mock-heroes.ts import { Hero } from "./hero"; export const HEROES: Hero[] = [ {id: 11, name: "Todoroki"}, {id: 12, name: "<NAME>"}, {id: 13, name: "Bakugo"} ];
14bec97ef4df5c1fe93ee7700470313333f62114
[ "TypeScript" ]
1
TypeScript
HenriqueOliveira07/Hero
10e43f07c307de4ab2150d7ba5dd4693346c8081
b9171f4927823b96c101c2a29c989cd5194da226
refs/heads/master
<file_sep><?php defined('BASEPATH') OR exit('No direct script access allowed'); ?> ERROR - 2015-09-16 12:16:52 --> 404 Page Not Found: ../../bonfire/modules/users/controllers/Users/messages ERROR - 2015-09-16 12:24:42 --> 404 Page Not Found: ../../bonfire/modules/users/controllers/Message/compose <file_sep><?php defined('BASEPATH') || exit('No direct script access allowed'); /** * Bonfire * * An open source project to allow developers to jumpstart their development of * CodeIgniter applications. * * @package Bonfire * @author Bonfire Dev Team * @copyright Copyright (c) 2011 - 2015, Bonfire Dev Team * @license http://opensource.org/licenses/MIT * @link http://cibonfire.com * @since Version 1.0 * @filesource */ /** * User Model. * * The central way to access and perform CRUD on users. * * @package Bonfire\Modules\Users\Models\User_model * @author Bonfire Dev Team * @link http://cibonfire.com/docs/developer */ class Trip_model extends BF_Model { /** @var string Name of the users table. */ protected $table_name = 'trips'; /** @var string Name of the roles table. */ protected $roles_table = 'roles'; /** @var boolean Use soft deletes or not. */ protected $soft_deletes = true; /** @var string The date format to use. */ protected $date_format = 'datetime'; /** @var boolean Set the modified time automatically. */ protected $set_modified = false; /** @var boolean Skip the validation. */ protected $skip_validation = true; //-------------------------------------------------------------------------- /** * Constructor * * @return void */ public function __construct() { parent::__construct(); } //-------------------------------------------------------------------------- // CRUD Method Overrides. //-------------------------------------------------------------------------- /** * Count the users in the system. * * @param boolean $get_deleted If true, count users which have been deleted, * else count users which have not been deleted. * * @return integer The number of users found. */ public function count_all($get_deleted = false) { if ($get_deleted) { // Get only the deleted users $this->db->where("{$this->table_name}.deleted !=", 0); } else { $this->db->where("{$this->table_name}.deleted", 0); } return $this->db->count_all_results($this->table_name); } /** * Perform a standard delete, but also allow a record to be purged. * * @param integer $id The ID of the user to delete. * @param boolean $purge If true, the account will be purged from the system. * If false, performs a standard delete (with soft-deletes enabled). * * @return boolean True on success, else false. */ public function delete($id = 0, $purge = false) { // Temporarily store the current setting for soft-deletes. $tempSoftDeletes = $this->soft_deletes; if ($purge === true) { // Temporarily set the soft_deletes to false to purge the account. $this->soft_deletes = false; } // Reset soft-deletes after deleting the account. $result = parent::delete($id); $this->soft_deletes = $tempSoftDeletes; return $result; } /** * Find a user's record and role information. * * @param integer $id The user's ID. * * @return boolean|object An object with the user's information. */ public function find($id = null) { return parent::find($id); } /** * Find all user records and the associated role information. * * @return boolean An array of objects with each user's information. */ public function find_all() { return parent::find_all(); } /** * Find a single user based on a field/value match, including role information. * * @param string $field The field to match. If 'both', attempt to find a user * with the $value field matching either the username or email. * @param string $value The value to search for. * @param string $type The type of where clause to create ('and' or 'or'). * * @return boolean|object An object with the user's info, or false on failure. */ public function find_by($field = null, $value = null, $type = 'and') { return parent::find_by($field, $value, $type); } /** * Create a new user in the database. * * @param array $data An array of user information. 'password' and either 'email' * or 'username' are required, depending on the 'auth.use_usernames' setting. * 'email' or 'username' must be unique. If 'role_id' is not included, the default * role from the Roles model will be assigned. * * @return boolean|integer The ID of the new user on success, else false. */ public function insert($data = array()) { $id = parent::insert($data); return $id; } /** * Update an existing user. Before saving, it will: * - Generate a new password/hash if both password and pass_confirm are provided. * - Store the country code. * * @param integer $id The user's ID. * @param array $data An array of key/value pairs to update for the user. * * @return boolean True if the update succeeded, null on invalid $id, or false * on failure. */ public function update($id = null, $data = array()) { if (empty($id)) { return null; } $result = parent::update($id, $data); return $result; } //-------------------------------------------------------------------------- // Other BF_Model Method Overrides. //-------------------------------------------------------------------------- } //end User_model <file_sep><!-- Footer ============================================= --> </div><!-- #wrapper end --> <!-- Go To Top ============================================= --> <div id="gotoTop" class="icon-angle-up"></div> <div id="debug"><!-- Stores the Profiler Results --></div> <script type="text/javascript" src="/themes/default/js/jquery.js"></script> <?php echo Assets::js(); ?> </body> </html><file_sep><?php echo theme_view('header'); ?> <?php echo theme_view('_sitenav'); ?> <!-- Content ============================================= --> <section id="content"> <div class="content-wrap"> <?php echo Template::message(); echo isset($content) ? $content : Template::content(); ?> </div> </section><!-- #content end --> <?php echo theme_view('footer'); ?><file_sep><?php defined('BASEPATH') OR exit('No direct script access allowed'); ?> ERROR - 2015-09-11 09:17:39 --> 404 Page Not Found: ../../bonfire/modules/users/controllers/Users/images ERROR - 2015-09-11 09:17:39 --> 404 Page Not Found: ../../bonfire/modules/users/controllers/Users/images ERROR - 2015-09-11 09:17:39 --> 404 Page Not Found: ../../bonfire/modules/users/controllers/Users/images ERROR - 2015-09-11 12:29:27 --> 404 Page Not Found: ../../bonfire/modules/users/controllers/Users/images ERROR - 2015-09-11 12:29:27 --> 404 Page Not Found: ../../bonfire/modules/users/controllers/Users/images ERROR - 2015-09-11 12:29:27 --> 404 Page Not Found: ../../bonfire/modules/users/controllers/Users/images ERROR - 2015-09-11 12:30:32 --> 404 Page Not Found: ../../bonfire/modules/users/controllers/Users/images ERROR - 2015-09-11 12:30:32 --> 404 Page Not Found: ../../bonfire/modules/users/controllers/Users/images ERROR - 2015-09-11 12:30:32 --> 404 Page Not Found: ../../bonfire/modules/users/controllers/Users/images ERROR - 2015-09-11 12:37:00 --> 404 Page Not Found: ../../bonfire/modules/users/controllers/Users/images ERROR - 2015-09-11 12:37:00 --> 404 Page Not Found: ../../bonfire/modules/users/controllers/Users/images ERROR - 2015-09-11 12:37:00 --> 404 Page Not Found: ../../bonfire/modules/users/controllers/Users/images <file_sep><?php if (!defined('BASEPATH')) exit('No direct script access allowed'); /* Copyright (c) 2011 <NAME> Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ $lang['us_account_deleted'] = 'Unfortunately your account has been deleted. It has not yet been purged and <strong>may still</strong> be restored. Contact the administrator at %s.'; $lang['us_bad_email_pass'] = 'Incorrect email or password.'; $lang['us_must_login'] = 'You must be logged in to view that page.'; $lang['us_no_permission'] = 'You do not have permission to access that page.'; $lang['us_fields_required'] = '%s and Password fields must be filled out.'; <file_sep><?php defined('BASEPATH') || exit('No direct script access allowed'); class Trip extends Front_Controller { /** @var array Site's settings to be passed to the view. */ private $siteSettings; /** * Setup the required libraries etc. * * @retun void */ public function __construct() { parent::__construct(); $this->load->helper('form'); $this->load->library('form_validation'); $this->load->model('trip/trip_model'); $this->load->library('users/auth'); $this->lang->load('trip'); $this->siteSettings = $this->settings_lib->find_all(); } } <file_sep><!-- Footer ============================================= --> <footer id="footer" class="dark" style="background-color: #222;"> <div class="container"> <!-- Footer Widgets ============================================= --> <div class="footer-widgets-wrap clearfix"> <div class="col_one_third"> <div class="widget clear-bottommargin-sm clearfix"> <div class="row"> <div class="col-md-12 bottommargin-sm"> <div class="footer-big-contacts"> <span>Call Us:</span> (91) 22 84551445 </div> </div> <div class="col-md-12 bottommargin-sm"> <div class="footer-big-contacts"> <span>Send an Enquiry:</span> <EMAIL> </div> </div> </div> </div> <div class="widget subscribe-widget clearfix"> <div class="row"> <div class="col-md-6 clearfix bottommargin-sm"> <a href="#" class="social-icon si-dark si-colored si-facebook nobottommargin" style="margin-right: 10px;"> <i class="icon-facebook"></i> <i class="icon-facebook"></i> </a> <a href="#"><small style="display: block; margin-top: 3px;"><strong>Like us</strong><br>on Facebook</small></a> </div> <div class="col-md-6 clearfix"> <a href="#" class="social-icon si-dark si-colored si-rss nobottommargin" style="margin-right: 10px;"> <i class="icon-rss"></i> <i class="icon-rss"></i> </a> <a href="#"><small style="display: block; margin-top: 3px;"><strong>Subscribe</strong><br>to RSS Feeds</small></a> </div> </div> </div> </div> <div class="col_one_third"> <div class="widget clearfix"> <h4>Featured Packages</h4> <div id="post-list-footer"> <div class="spost clearfix"> <div class="entry-image"> <a href="#">IMG</a> </div> <div class="entry-c"> <div class="entry-title"> <h4><a href="#">7 Nights/8 Days Europe</a></h4> </div> <ul class="entry-meta"> <li><strong>$599</strong> onwards</li> </ul> </div> </div> <div class="spost clearfix"> <div class="entry-image"> <a href="#">IMG</a> </div> <div class="entry-c"> <div class="entry-title"> <h4><a href="#">4 Nights/5 Days Thailand</a></h4> </div> <ul class="entry-meta"> <li><strong>$399</strong> onwards</li> </ul> </div> </div> <div class="spost clearfix"> <div class="entry-image"> <a href="#">IMG</a> </div> <div class="entry-c"> <div class="entry-title"> <h4><a href="#">11 Nights/12 Days America</a></h4> </div> <ul class="entry-meta"> <li><strong>$1299</strong> onwards</li> </ul> </div> </div> </div> </div> </div> <div class="col_one_third col_last"> <div class="widget widget_links clearfix"> <h4>Popular Destinations</h4> <div class="row clearfix"> <div class="col-xs-6"> <ul> <li><a href="#">Thailand</a></li> <li><a href="#">Indonesia</a></li> <li><a href="#">Italy</a></li> <li><a href="#">Spain</a></li> </ul> </div> <div class="col-xs-6"> <ul> <li><a href="#">India</a></li> <li><a href="#">France</a></li> <li><a href="#">Philippines</a></li> <li><a href="#">New Zealand</a></li> </ul> </div> </div> </div> <div class="widget subscribe-widget clearfix"> <h5>Get Latest <strong>Offers</strong> &amp; <strong>Coupons</strong> by Email:</h5> <div id="widget-subscribe-form-result" data-notify-type="success" data-notify-msg=""></div> <form id="widget-subscribe-form" action="include/subscribe.php" role="form" method="post" class="nobottommargin"> <div class="input-group divcenter"> <span class="input-group-addon"><i class="icon-email2"></i></span> <input type="email" id="widget-subscribe-form-email" name="widget-subscribe-form-email" class="form-control required email" placeholder="Enter your Email"> <span class="input-group-btn"> <button class="btn btn-danger bgcolor" type="submit">Subscribe</button> </span> </div> </form> </div> </div> </div><!-- .footer-widgets-wrap end --> </div> <!-- Copyrights ============================================= --> <div id="copyrights"> <div class="container clearfix"> <div class="col_half"> Copyrights &copy; 2014 All Rights Reserved by Canvas Inc.<br> <div class="copyright-links"><a href="#">Terms of Use</a> / <a href="#">Privacy Policy</a></div> </div> <div class="col_half col_last tright"> <div class="fright clearfix"> <a href="#" class="social-icon si-small si-borderless si-facebook"> <i class="icon-facebook"></i> <i class="icon-facebook"></i> </a> <a href="#" class="social-icon si-small si-borderless si-twitter"> <i class="icon-twitter"></i> <i class="icon-twitter"></i> </a> <a href="#" class="social-icon si-small si-borderless si-gplus"> <i class="icon-gplus"></i> <i class="icon-gplus"></i> </a> <a href="#" class="social-icon si-small si-borderless si-pinterest"> <i class="icon-pinterest"></i> <i class="icon-pinterest"></i> </a> <a href="#" class="social-icon si-small si-borderless si-vimeo"> <i class="icon-vimeo"></i> <i class="icon-vimeo"></i> </a> <a href="#" class="social-icon si-small si-borderless si-github"> <i class="icon-github"></i> <i class="icon-github"></i> </a> <a href="#" class="social-icon si-small si-borderless si-yahoo"> <i class="icon-yahoo"></i> <i class="icon-yahoo"></i> </a> <a href="#" class="social-icon si-small si-borderless si-linkedin"> <i class="icon-linkedin"></i> <i class="icon-linkedin"></i> </a> </div> <div class="clear"></div> <i class="icon-envelope2"></i> <EMAIL> <span class="middot">&middot;</span> <i class="icon-headphones"></i> +91-11-6541-6369 <span class="middot">&middot;</span> <i class="icon-skype2"></i> CanvasOnSkype </div> </div> </div><!-- #copyrights end --> </footer><!-- #footer end --> </div><!-- #wrapper end --> <!-- Go To Top ============================================= --> <div id="gotoTop" class="icon-angle-up"></div> <div id="debug"><!-- Stores the Profiler Results --></div> <script type="text/javascript" src="/themes/default/js/jquery.js"></script> <script>window.jQuery || document.write('<script src="<?php echo js_path(); ?>jquery-1.7.2.min.js"><\/script>');</script> <?php echo Assets::js(); ?> </body> </html><file_sep><?php defined('BASEPATH') OR exit('No direct script access allowed'); ?> ERROR - 2015-09-09 09:18:13 --> 404 Page Not Found: contact.html ERROR - 2015-09-09 12:32:03 --> 404 Page Not Found: index.html <file_sep><?php Assets::add_css(array('bootstrap.css','font-awesome.css','style.css','dark.css','travel.css','datepicker.css','font-icons.css','animate.css','magnific-popup.css','responsive.css','colors.css')); Assets::add_js(array('bootstrap.min.js','plugins.js','datepicker.js','functions.js')); ?> <!DOCTYPE html> <html dir="ltr" lang="en-US"> <head> <meta http-equiv="content-type" content="text/html; charset=utf-8" /> <title><?php echo isset($page_title) ? "{$page_title} : " : ''; e(class_exists('Settings_lib') ? settings_item('site.title') : 'Bonfire'); ?></title> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta name="description" content="<?php e(isset($meta_description) ? $meta_description : ''); ?>"> <meta name="author" content="<?php e(isset($meta_author) ? $meta_author : ''); ?>"> <?php /* Modernizr is loaded before CSS so CSS can utilize its features */ //echo Assets::js('modernizr-2.5.3.js'); ?> <link href="http://fonts.googleapis.com/css?family=Lato:300,400,400italic,600,700|Raleway:300,400,500,600,700|Crete+Round:400italic" rel="stylesheet" type="text/css" /> <?php echo Assets::css(); ?> <link rel="shortcut icon" href="<?php echo base_url(); ?>favicon.ico"> </head> <body class="stretched"><file_sep><!-- Document Wrapper ============================================= --> <div id="wrapper" class="clearfix"> <!-- Top Bar ============================================= --> <div id="top-bar" class="semi-transparent dark"> <div class="container clearfix"> <div class="col_half nobottommargin clearfix"> <!-- Top Links ============================================= --> <div class="top-links"> <ul> <li><a href="<?php echo site_url(); ?>"><?php e(lang('bf_home')); ?></a></li> <li><a href="faqs.html">FAQs</a></li> <li><a href="contact.html">Contact</a></li> <li><a href="#">USD</a> <ul> <li><a href="#">EUR</a></li> <li><a href="#">AUD</a></li> <li><a href="#">GBP</a></li> </ul> </li> </ul> </div><!-- .top-links end --> </div> <div class="col_half fright col_last clearfix nobottommargin"> <!-- Top Social ============================================= --> <div id="top-social"> <ul> <li><a href="#" class="si-facebook"><span class="ts-icon"><i class="icon-facebook"></i></span><span class="ts-text">Facebook</span></a></li> <li><a href="#" class="si-twitter"><span class="ts-icon"><i class="icon-twitter"></i></span><span class="ts-text">Twitter</span></a></li> <li><a href="#" class="si-pinterest"><span class="ts-icon"><i class="icon-pinterest"></i></span><span class="ts-text">Pinterest</span></a></li> <li><a href="#" class="si-instagram"><span class="ts-icon"><i class="icon-instagram2"></i></span><span class="ts-text">Instagram</span></a></li> <li><a href="tel:+91.11.85412542" class="si-call"><span class="ts-icon"><i class="icon-call"></i></span><span class="ts-text">+91.11.85412542</span></a></li> <li><a href="mailto:<EMAIL>" class="si-email3"><span class="ts-icon"><i class="icon-envelope-alt"></i></span><span class="ts-text"><EMAIL></span></a></li> </ul> </div><!-- #top-social end --> </div> </div> </div><!-- #top-bar end --> <!-- Header ============================================= --> <header id="header" class="transparent-header semi-transparent" data-sticky-class="not-dark" data-responsive-class="not-dark"> <div id="header-wrap"> <div class="container clearfix"> <div id="primary-menu-trigger"><i class="icon-reorder"></i></div> <!-- Logo ============================================= --> <div id="logo"> <a href="/" class="standard-logo" data-dark-logo="images/logo-dark.png">SITE</a> </div><!-- #logo end --> <!-- Primary Navigation ============================================= --> <nav id="primary-menu" class="style-4"> <ul> <li class="current"><a href="index.html"><div><i class="icon-home2"></i>Home</div></a> </li> <!--<li><a href="#"><div><i class="icon-plane"></i>Flights</div></a></li> <li><a href="#"><div><i class="icon-building"></i>Hotels</div></a></li> <li><a href="#"><div><i class="icon-gift"></i>Holidays</div></a></li> <li><a href="#"><div><i class="icon-pencil2"></i>Blog</div></a></li>--> <?php if (empty($current_user)) : ?> <li><a href="<?php echo site_url(LOGIN_URL); ?>">Sign In</a></li> <li><a href="<?php echo site_url(REGISTER_URL); ?>">Register</a></li> <?php else : ?> <li <?php echo check_method('profile'); ?>><a href="<?php echo site_url('users/profile'); ?>"><?php e(lang('bf_user_settings')); ?></a></li> <li><a href="<?php echo site_url('logout'); ?>"><?php e(lang('bf_action_logout')); ?></a></li> <?php endif; ?> <!--<li><a href="#"><div><i class="icon-phone3"></i>1800 105 2541</div></a></li>--> </ul> </nav><!-- #primary-menu end --> </div> </div> </header><!-- #header end --> <file_sep><!-- Document Wrapper ============================================= --> <div id="wrapper" class="clearfix"> <!-- Header ============================================= --> <header id="header" class="transparent-header semi-transparent" data-sticky-class="not-dark" data-responsive-class="not-dark"> <div id="header-wrap"> <div class="container clearfix"> <div id="primary-menu-trigger"><i class="icon-reorder"></i></div> <!-- Logo ============================================= --> <div id="logo"> <a href="/" class="standard-logo" data-dark-logo="images/logo-dark.png">SITE</a> </div><!-- #logo end --> <!-- Primary Navigation ============================================= --> <nav id="primary-menu" class="style-4"> <ul> <li class="current"><a href="/users/manage/dashboard"><div><i class="icon-home2"></i>Dashboard</div></a> </li> <?php if (empty($current_user)) : ?> <li><a href="<?php echo site_url(LOGIN_URL); ?>">Sign In</a></li> <li><a href="<?php echo site_url(REGISTER_URL); ?>">Register</a></li> <?php else : ?> <li><a href="<?php echo site_url('users/manage/users'); ?>"><div><i class="fa fa-user"></i> Users</div></a></li> <li><a href="<?php echo site_url('logout'); ?>"><div><?php e(lang('bf_action_logout')); ?></div></a></li> <?php endif; ?> <!--<li><a href="#"><div><i class="icon-phone3"></i>1800 105 2541</div></a></li>--> </ul> </nav><!-- #primary-menu end --> </div> </div> </header><!-- #header end --> <file_sep><?php defined('BASEPATH') OR exit('No direct script access allowed'); ?> ERROR - 2015-09-21 12:07:00 --> 404 Page Not Found: manage/users ERROR - 2015-09-21 12:26:32 --> Could not find the language line 'display_loading_msg' ERROR - 2015-09-21 12:26:33 --> Could not find the language line 'display_loading_msg' ERROR - 2015-09-21 12:26:33 --> 404 Page Not Found: themes/admin/images/icons/widget-link-dark.png ERROR - 2015-09-21 12:27:02 --> 404 Page Not Found: themes/admin/images/icons/widget-link-dark.png ERROR - 2015-09-21 12:27:22 --> 404 Page Not Found: themes/admin/images/icons/widget-link-dark.png ERROR - 2015-09-21 12:30:50 --> 404 Page Not Found: themes/admin/images/sort_desc.png ERROR - 2015-09-21 12:33:43 --> 404 Page Not Found: themes/admin/images/sort_desc.png ERROR - 2015-09-21 12:36:54 --> 404 Page Not Found: themes/admin/images/sort_desc.png ERROR - 2015-09-21 14:02:09 --> 404 Page Not Found: themes/admin/images/sort_desc.png ERROR - 2015-09-21 14:02:28 --> 404 Page Not Found: themes/admin/images/sort_desc.png
649b7a5bc3ba8ccf457d46336cd53150fc0887a9
[ "PHP" ]
13
PHP
vamsi683/offers
3e1e7756720de564bb98d635ad3e1ca20e2e4269
c3b41bfdf9b67e08da47f219ba348f01fb575e7b
refs/heads/master
<repo_name>DankoN91/Food-o-clock<file_sep>/food_o'clock/src/layout/private/components/Profile.js import React from 'react'; import Button from 'react-bootstrap/Button'; import Card from 'react-bootstrap/Card'; import Form from 'react-bootstrap/Form'; import Table from 'react-bootstrap/Table'; import NVD3Chart from 'react-nvd3'; import NavigbarHome from './NavigbarHome'; class Profile extends React.Component { constructor(props){ super(props); this.state = { user:{ id:1, name:'Danko', tags:[ {id:1, naziv:'rostilj'}, {id:2, naziv:'italijanska'}] } } } render(){ const datum = [{ key: "Money spent", values: [ { "label" : 1, "value" : 250 }, { "label" : 4, "value" : 500 }, { "label" : 5, "value" : 720 }, { "label" : 7, "value" : 400 }, { "label" : 10, "value" : 194 }, { "label" : 17, "value" : 498 }, { "label" : 25, "value" : 1000 }, { "label" : 26, "value" : 320 } ] }]; let currentTags=this.state.user.tags; let tagRow = currentTags.map((tag)=>{ window.localStorage.setItem(tag.id,tag.naziv); return (<tr> <td style={{textAlign:'center'}}>{tag.naziv}</td> <td style={{textAlign:'center'}}><Button variant='danger'> Remove </Button> </td> </tr> )}); return ( <div className="container"> <div className='row'> <div className='col-md-12'> <NavigbarHome /> </div> </div> <div className='row'> <div className='col-md-4'></div> <div style={{textAlign:'center'}} className='col-md-4'> <h2>Welcome {this.state.user.name}!</h2> </div> <div className='col-md-4'></div> </div> <div className='row' style={{height:'1rem'}}></div> <div className='row'> <div className='col-md-12'> <Card > <Card.Header><h2>Your tags</h2></Card.Header> <Table striped bordered hover> <tbody> {tagRow} </tbody> </Table> </Card> </div> </div> <div className="row" style={{height:'1rem'}}></div> <div className="row"> <div className="col-md-12"> <Card> <Card.Header><h2>Your stats</h2></Card.Header> <NVD3Chart id="barChart" type="lineChart" height='400' showValues="true" datum={datum} x="label" y="value"/> </Card> </div> </div> </div> ) } } export default Profile;<file_sep>/food_o'clock/src/layout/private/components/Home.js import React from 'react'; import getQuotes from '../../../services/quotesApi'; import Nav from 'react-bootstrap/Nav'; import DailyQuoteModal from './DailyQuoteModal'; import Button from 'react-bootstrap/Button'; import image from '../../../utilities/fortune-cookie-drawing.png'; import ActivePolls from './ActivePolls'; import ActiveOrders from './ActiveOrders'; import { BrowserRouter, Switch, Redirect, Route,Link } from "react-router-dom"; import NavigbarHome from './NavigbarHome'; class Home extends React.Component { constructor() { super(); this.state = { allQuotes:[], randomQuote:'', modalShow:false, activePolls:[], activeOrders:[] } } componentDidMount(){ } render() { return ( <div className="container"> <div className="row"> <div className="col-md-12"> <NavigbarHome /> </div> </div> <div className="row" style={{ height:"1rem" }}></div> <div className="row"> <div className="col-md-12"> <ActivePolls /> </div> </div> <div style={{height:'1rem'}} className="row"></div> <div className="row"> <div className="col-md-12"> <ActiveOrders /> </div> </div> </div> ) } } export default Home;<file_sep>/food_o'clock/src/layout/private/components/NavigbarHome.js import React from 'react'; import Navbar from 'react-bootstrap/Navbar'; import Nav from 'react-bootstrap/Nav'; import Button from 'react-bootstrap/Button'; import NavDropdown from 'react-bootstrap/NavDropdown'; import image from '../../../utilities/fortune-cookie-drawing.png'; import DailyQuoteModal from './DailyQuoteModal'; import getQuotes from '../../../services/quotesApi'; import { BrowserRouter, Switch, Redirect, Route,Link } from "react-router-dom"; import logoImage from '../../../utilities/logo.png'; class NavigbarHome extends React.Component { constructor() { super(); this.state = { allQuotes:[], randomQuote:'', modalShow:false, activePolls:[], activeOrders:[] } } initialQuotes=async()=>{ let data = await getQuotes(); this.setState({ allQuotes: data }); } componentDidMount(){ this.initialQuotes(); } setQuotes = async() => { this.setState({ randomQuote: this.state.allQuotes[Math.floor(Math.random()*this.state.allQuotes.length)] }); } setModalShow = () => { this.setState({ modalShow: !this.state.modalShow }); } render(){ return ( <div className="row"> <div className="col-md-1"> <Link to='/home'><img className="logo" src={logoImage} alt="logo"></img></Link> </div> <div className="col-md-11"> <Navbar bg="light" variant="light"> <Nav className="mr-auto"> <Nav.Link href="/home">Home</Nav.Link> <NavDropdown title="Polls" id="nav-dropdown"> <NavDropdown.Item href="/newpoll">New poll</NavDropdown.Item> <NavDropdown.Item>My polls</NavDropdown.Item> </NavDropdown> <NavDropdown title="History" id="nav-dropdown"> <NavDropdown.Item>Poll history</NavDropdown.Item> <NavDropdown.Item>Order history</NavDropdown.Item> </NavDropdown> <Nav.Link href="/profile">Profile</Nav.Link> </Nav> <div> <img className="fortuneCookie" src={image} onClick={()=>{this.setQuotes(); this.setModalShow()}} /> {<DailyQuoteModal show={this.state.modalShow} onHide={this.setModalShow} random={this.state.randomQuote} />} </div> <Link to="/login"> <Button variant="warning"> Log out </Button> </Link> </Navbar> </div> </div> )} } export default NavigbarHome; <file_sep>/food_o'clock/src/layout/private/components/NewPoll.js import React from "react"; import NavigbarHome from "./NavigbarHome"; import Button from "react-bootstrap/Button"; import Card from "react-bootstrap/Card"; import Form from "react-bootstrap/Form"; import Table from "react-bootstrap/Table"; import {getAllPossibleRestaurants} from '../../../services/mockApi'; class NewPoll extends React.Component { constructor() { super(); this.state = { currentPoll: [], suggestedRestaurants: [], possibleRestaurants: [] }; } componentDidMount(){ this.setAllPossibleRestaurants(); } setAllPossibleRestaurants = async()=>{ let allRestaurants=await getAllPossibleRestaurants(); this.setState({possibleRestaurants:allRestaurants}); this.setState({suggestedRestaurants:allRestaurants}); } render() { let suggestedRestaurants = this.state.suggestedRestaurants; let tRows = suggestedRestaurants.map((res) => { return ( <tr> <td>{res.name}</td> <td>{res.address}</td> <td>{res.minPrice}</td> <td> <Button onClick={(ev) => { let oldPoll = this.state.currentPoll; oldPoll.push(res); this.setState({ currentPoll: oldPoll }); }} > Add </Button> </td> </tr> ); }); let currentPoll = this.state.currentPoll.map((res,index) => { return ( <tr> <td>{res.name}</td> <td>{res.address}</td> <td>{res.minPrice}</td> <td> <Button variant="danger" onClick={(ev) => { let pollsAfterDelete = this.state.currentPoll; pollsAfterDelete.splice(index, 1); this.setState({ currentPoll: pollsAfterDelete }); }}> Remove </Button> </td> </tr> ); }); return ( <div className="container"> <div className="row"> <div className="col-md-12"> <NavigbarHome /> </div> </div> <div className="row" style={{ height: "1rem" }}></div> <div className="row"> <div className="col-md-12"> <Card> <Card.Header> <h2>Restaurants</h2> </Card.Header> <Form> <Form.Group> <Form.Control onChange={(ev) => { let searchValue = ev.target.value.split(" "); let searchTags = []; let searchName = ""; searchValue.forEach((it) => { let trimmedTerm = it.trim(); if (trimmedTerm.includes("#")) { searchTags.push(trimmedTerm.slice(1)); } else searchName = trimmedTerm; }); let newSuggested = []; this.state.possibleRestaurants.forEach((it) => { let searchTagsValid = true; searchTags.forEach((el) => { if (!it.tags.includes(el)) searchTagsValid = false; }); let searchNameValid = true; if (searchName.length > 0) { searchNameValid = it.name .toLowerCase() .includes(searchName.toLowerCase()); } if (searchTagsValid && searchNameValid) newSuggested.push(it); }); this.setState({ suggestedRestaurants: newSuggested }); }} placeholder="Type restaurant name or some food tag..." /> </Form.Group> </Form> <Table striped bordered hover> <thead> <tr> <th>Name</th> <th>Address</th> <th>Min. price</th> <th>Want it?</th> </tr> </thead> <tbody>{tRows}</tbody> </Table> </Card> </div> </div> <div className="row" style={{ height: "1rem" }}></div> <div className="row"> <div className="col-md-12"> <Card> <Card.Header> <h2>Current poll</h2> </Card.Header> <Table striped bordered hover> <thead> <tr> <th>Name</th> <th>Address</th> <th>Min. price</th> <th>Still want it?</th> </tr> </thead> <tbody>{currentPoll}</tbody> </Table> </Card> </div> </div> <div className="row"> <div className="col-md-12"> <Button variant="success" size="lg" block onClick={(ev) => { this.setState({ currentPoll: [] }); }}> Create poll </Button> </div> </div> </div> ); } } export default NewPoll; <file_sep>/README.md # Food-o-clock Application for creating group food orders (for workplaces, friends etc) Note: Local storage is currently used to simulate back-end. <file_sep>/food_o'clock/src/layout/private/components/Order.js import React from "react"; import Button from "react-bootstrap/Button"; import Card from "react-bootstrap/Card"; import Form from "react-bootstrap/Form"; import Table from "react-bootstrap/Table"; import NavigbarHome from "./NavigbarHome"; import { getAllPossibleMeals, getMyTags } from "../../../services/mockApi"; class Order extends React.Component { constructor() { super(); this.state = { currentOrder: [], currentOrderSum: 0, budget: 0, possibleMeals: [], value: "", suggestions: [], saltyMeals: [], sweetMeals: [], suggestedMeals: [], myTags: [], }; } isMealRecommended(mealTags){ let myTags=this.state.myTags; console.log(myTags) let isRecommended=false; mealTags.forEach((tag)=>{ if(myTags.includes(tag)) isRecommended=true; }) return isRecommended; } componentDidMount() { this.setMyTags(); this.setAllPossibleMeals(); } setAllPossibleMeals = async () => { let allMeals = await getAllPossibleMeals(); this.setState({ possibleMeals: allMeals }); this.setState({ suggestedMeals: allMeals }); let saltyFood = []; let sweetFood = []; let allFood = this.state.possibleMeals; allFood.forEach((meal) => { if (meal.tags.includes("slano")) { saltyFood.push(meal); } else { sweetFood.push(meal); } }); this.setState({ saltyMeals: saltyFood, sweetMeals: sweetFood }); }; setMyTags = async () => { let myTags = JSON.parse(await getMyTags()); this.setState({ myTags: myTags }); }; render() { let suggestedMeals = this.state.suggestedMeals; let suggestedMealsRecommended=suggestedMeals.map((meal)=>{ return this.isMealRecommended(meal.tags); }) let tRows = suggestedMeals.map((meal,mealIndex) => { return ( <tr> <td style={{ textAlign: "center" }}>{meal.name}</td> <td style={{ textAlign: "center" }}>{meal.price}</td> <td style={{ textAlign: "center" }}>{ suggestedMealsRecommended[mealIndex] ? "YES" : "NO" }</td> <td style={{ textAlign: "center" }}> <Button onClick={() => { console.log(this.state.myTags); let oldOrder = this.state.currentOrder; oldOrder.push(meal); this.setState({ currentOrder: oldOrder }); let currOrderSum = 0; oldOrder.forEach((order) => { currOrderSum += order.price; }); this.setState({ currentOrderSum: currOrderSum }); }} > Add </Button> </td> </tr> ); }); let salty = this.state.saltyMeals; let sweet = this.state.sweetMeals; let comboRow = []; salty.forEach((saltyMeal) => { sweet.forEach((sweetMeal) => { if (saltyMeal.price + sweetMeal.price <= this.state.budget) { comboRow.push( <tr> <td style={{ textAlign: "center" }}>{saltyMeal.name}</td> <td style={{ textAlign: "center" }}>{sweetMeal.name}</td> <td style={{ textAlign: "center" }}> {saltyMeal.price + sweetMeal.price} </td> <td style={{ textAlign: "center" }}> <Button onClick={() => { let oldOrder = this.state.currentOrder; oldOrder.push(saltyMeal, sweetMeal); this.setState({ currentOrder: oldOrder }); let currOrderSum = 0; oldOrder.forEach((order) => { currOrderSum += order.price; }); this.setState({ currentOrderSum: currOrderSum }); this.setState({ budget: 0 }); }} > Add combo </Button> </td> </tr> ); } }); }); let currOrder = this.state.currentOrder.map((meal, index) => { return ( <tr> <td style={{ textAlign: "center" }}>{meal.name}</td> <td style={{ textAlign: "center" }}>{meal.price}</td> <td style={{ textAlign: "center" }}> <input type="text"></input> </td> <td style={{ textAlign: "center" }}> <Button variant="danger" onClick={() => { let orderAfterDelete = this.state.currentOrder; orderAfterDelete.splice(index, 1); console.log(index); this.setState({ currentOrder: orderAfterDelete }); this.setState({ currentOrderSum: this.state.currentOrderSum - meal.price, }); }} > Remove </Button> </td> </tr> ); }); return ( <div className="container"> <div className="row"> <div className="col-md-12"> <NavigbarHome /> </div> </div> <div className="row" style={{ height: "1rem" }}></div> <div className="row"> <div className="col-md-12"> <Card> <Card.Header> <h2>Menu</h2> </Card.Header> <Form> <Form.Group controlId="formBasicEmail"> <Form.Control onChange={(ev) => { let searchValue = ev.target.value.split(" "); let searchTags = []; let searchName = ""; searchValue.forEach((it) => { let trimmedTerm = it.trim(); if (trimmedTerm.includes("#")) { searchTags.push(trimmedTerm.slice(1)); } else searchName = trimmedTerm; }); let newSuggested = []; this.state.possibleMeals.forEach((mealForCheck) => { let searchTagsValid = true; searchTags.forEach((typedTag) => { if (!mealForCheck.tags.includes(typedTag)) searchTagsValid = false; }); let searchNameValid = true; if (searchName.length > 0) { searchNameValid = mealForCheck.name .toLowerCase() .includes(searchName.toLowerCase()); } if (searchTagsValid && searchNameValid) newSuggested.push(mealForCheck); }); this.setState({ suggestedMeals: newSuggested }); }} type="text" placeholder="Type meal name or some food tag..." /> </Form.Group> </Form> <Table striped bordered hover> <thead> <tr> <th style={{ textAlign: "center" }}>Name</th> <th style={{ textAlign: "center" }}>RSD</th> <th style={{ textAlign: "center" }}>Recommended</th> <th style={{ textAlign: "center" }}>Want it?</th> </tr> </thead> <tbody>{tRows}</tbody> </Table> <Form.Group> <Card.Header> <h2>Perfect combo</h2> </Card.Header> <Form.Control type="text" placeholder="Insert your budget to get a recommended meal combo..." onChange={(ev) => { this.setState({ budget: ev.target.value }); this.setState({ comboInputValue: ev.target.value }); }} /> </Form.Group> <Table striped bordered hover> <thead> <tr> <th style={{ textAlign: "center" }}>Salty</th> <th style={{ textAlign: "center" }}>Sweet</th> <th style={{ textAlign: "center" }}>RSD</th> <th style={{ textAlign: "center" }}>Want the combo?</th> </tr> </thead> <tbody>{comboRow}</tbody> </Table> </Card> </div> </div> <div className="row" style={{ height: "1rem" }}></div> <div className="row"> <div className="col-md-12"> <Card> <Card.Header> <h2>Current order</h2> </Card.Header> <Table striped bordered hover> <thead> <tr> <th style={{ textAlign: "center" }}>Name</th> <th style={{ textAlign: "center" }}>RSD</th> <th style={{ textAlign: "center" }}>Additional note</th> <th style={{ textAlign: "center" }}>Still want it?</th> </tr> </thead> <tbody> {currOrder} <tr> <td> <h5>Current order sum:</h5> </td> <td style={{ textAlign: "center" }}> {this.state.currentOrderSum} </td> </tr> </tbody> </Table> </Card> </div> </div> <div className="row"> <div className="col-md-12"> <Button variant="success" size="lg" block onClick={() => { this.setState({ currentOrder: [] }); this.setState({ currentOrderSum: 0 }); }} > Submit order </Button> </div> </div> <div className="row" style={{ height: "1rem" }}></div> </div> ); } } export default Order;
b5106de28a945ae97a0666fe9e8711025e2f91aa
[ "JavaScript", "Markdown" ]
6
JavaScript
DankoN91/Food-o-clock
06084ef095135be9c4eca5a7f3f0bcbab82e9f5d
85bb8e8d5684062bac3044117ecaa32e30cb6e10
refs/heads/master
<file_sep>var retryCount = 0; var findElemIntervalId = setInterval(findElementForWait , 1000); function findElementForWait(){ retryCount++; if(retryCount > 60){ clearInterval(findElemIntervalId); findElemIntervalId = -1; } var td = document.querySelector('table[summary=contents]'); if(td){ clearInterval(findElemIntervalId); findElemIntervalId = -1; autoInput(); } console.log('wait loading...') } function autoInput(){ document.querySelectorAll('a').forEach( function(a){ if (a.textContent == "勤務実績入力"){ autoInputGetsuji(); } if (a.textContent == "勤務実績入力(日次用)"){ autoInputNichiji(); } } ) } function autoInputGetsuji(){ var $grid = document.querySelector('#APPROVALGRD'); $grid.querySelectorAll('tr').forEach( function ($row) { var shour = -1; var smin = -1; var ehour = -1; var emin = -1; var colidx = 0 $row.querySelectorAll('td.mg_normal').forEach( function ($col) { if (colidx == 7) { var lst = $col.querySelectorAll('span'); if (lst.length >= 3) { shour = lst[1].textContent; smin = lst[2].textContent; } if (lst.length >= 6) { ehour = lst[4].textContent; emin = lst[5].textContent; } } if (colidx == 8) { var inputs = $col.querySelectorAll('input'); if (shour >= 0 && smin >= 0) { inputs[2].value = shour + ':' + smin; } if (ehour >= 0 && emin >= 0) { inputs[5].value = ehour + ':' + emin; } } colidx += 1; } ); } ); } function autoInputNichiji(){ var shour = -1; var smin = -1; var ehour = -1; var emin = -1; var $grid = document.querySelector('#KNM'); var idx = 0; $grid.querySelectorAll('td.kinmu_normal').forEach( function ($col) { if (idx == 2) { var lst = $col.querySelectorAll('span'); if (lst.length >= 3) { shour = lst[1].textContent; smin = lst[2].textContent; } if (lst.length >= 6) { ehour = lst[4].textContent; emin = lst[5].textContent; } } idx += 1; } ); var update = false; if (shour >= 0) { document.querySelector('#KNMTMRNGSTH').value = shour; } if (smin >= 0) { document.querySelector('#KNMTMRNGSTM').value = smin; } if (shour >= 0 && smin >= 0) { var split = document.querySelector('[name=KNMTMRNGSTDI]').value.split(':'); var inputhour = parseInt(split[0]); var inputmin = parseInt(split[1]); var shnum = parseInt(shour); var smnum = parseInt(smin); if(inputhour != shnum || inputmin != smnum) { update = true; } document.querySelector('[name=KNMTMRNGSTDI]').value = shour + ':' + smin; } if (ehour >= 0) { document.querySelector('#KNMTMRNGETH').value = ehour; } if (emin >= 0) { document.querySelector('#KNMTMRNGETM').value = emin; } if (ehour >= 0 && emin >= 0) { var split = document.querySelector('[name=KNMTMRNGETDI]').value.split(':'); var inputhour = parseInt(split[0]); var inputmin = parseInt(split[1]); var ehnum = parseInt(ehour); var emnum = parseInt(emin); if(inputhour != ehnum || inputmin != emnum) { update = true; } document.querySelector('[name=KNMTMRNGETDI]').value = ehour + ':' + emin; } if (update) { document.querySelector('#btnCalc0').click(); } document.querySelector('select[name="GI_COMBOBOX38_Seq0S"]').value = 2 } <file_sep># amazon-history.js 1. chomeを開きます(chromeでしか試してません) 1. amazonの注文履歴を開きます https://www.amazon.co.jp/gp/css/order-history/ 1. F12を押します 1. Consoleタブを開きます 1. [ソース](https://raw.githubusercontent.com/yociya/test/master/amazon-history.js) をすべてコピーしてConsoleに貼り付けます ````` 結果サンプル 2014年 : xxx,xxx 円 xx件 最高額 : xx,xxx 円 2015年 : xxx,xxx 円 xxx件 最高額 : xx,xxx 円 2016年 : xxx,xxx 円 xxx件 最高額 : x,xxx 円 総合計 : x,xxx,xxx 円 ````` <file_sep>var historyUrl = 'https://www.amazon.co.jp/gp/css/order-history?orderFilter=year-$year$&startIndex=$index$'; function beforeSendHook(xhr){ xhr.setRequestHeader('X-Requested-With' , { toString: function(){ return ''; } } ); } function getPage(year,page){ var pageIndex = page * 10; var $deferred = $.Deferred(); $.Deferred().resolve().then( function(){ return $.ajax( { url:historyUrl.replace('$index$',pageIndex).replace('$year$',year) ,beforeSend:beforeSendHook } ); } ).then( function(data){ var dom = $.parseHTML(data); return $deferred.resolve(dom); } ).fail( function(jqXHR, msg){ return $deferred.reject(msg); } ); return $deferred.promise(); } function extract(results,dom,year){ var $page = $(dom); $page.find('span.value:contains(¥)').each( function(idx,priceTag){ var $priceTag = $(priceTag); var price = Number($priceTag.text().replace(',','').replace('¥','').trim()); results[year]['price'].push(price); if(price > results[year]['maxPrice']){ results[year]['maxPrice'] = price; } } ); var page = $page.find('div.pagination-full li.a-last').prev().text(); if(page !== ''){ results[year]['lastPage'] = Number(page); } var orderCount = $page.find('span.num-orders').text(); results[year]['orderCount'] = orderCount; } function process(results,year,page){ var $deferred = $.Deferred(); $.Deferred().resolve().then( function(){ return getPage(year,page); } ).then( function(dom){ extract(results,dom,year); console.log('----' + year + ' - ' + (page + 1) + '/' + results[year]['lastPage']); return recursiveCall(results,year,page+1); } ).then( function(){ return $deferred.resolve(); } ).fail( function(msg){ return $deferred.reject(msg); } ); return $deferred.promise(); } function recursiveCall(results,startYear,page){ var $deferred = $.Deferred(); $.Deferred().resolve().then( function(){ var nextYear = startYear; var nextPage = page; if(page >= results[startYear]['lastPage']){ nextYear = startYear + 1; nextPage = 0; } if(!!!results[nextYear]){ return $deferred.resolve(); } return process(results,nextYear,nextPage); } ).then( function(){ return $deferred.resolve(); } ).fail( function(msg){ return $deferred.reject(msg); } ); return $deferred.promise(); } function sumYearItems(item){ var sumPrice = 0; $.each(item, function(index,price){ sumPrice += price; } ); return sumPrice; } function print(results){ var resultText = ''; var allPrice = 0; $.each(results, function(index,item){ var price = sumYearItems(item['price']); allPrice += price; resultText = resultText + index + '年 : ' + (' ' + price.toLocaleString()).slice(-12) + ' 円 ' + (' ' + item['orderCount']).slice(-5) + ' 最高額 : ' + (' ' + item['maxPrice'].toLocaleString()).slice(-12) + ' 円 ' + '\r\n'; } ); resultText = resultText + '総合計 : ' + allPrice.toLocaleString() + ' 円'; console.log(resultText); } function start(){ var results = {}; var startYear = 0; $('form.time-period-chooser option:contains(年)').each( function(idx,yearTag){ var $yearTag = $(yearTag); var year = Number($yearTag.text().replace('年','').trim()); results[year] = {lastPage:1,price:[],orderCount:'0件',maxPrice:0}; startYear = year; } ); var $deferred = $.Deferred(); $.Deferred().resolve().then( function(){ return recursiveCall(results,startYear,0); } ).then( function(){ print(results); return $deferred.resolve(); } ).fail( function(msg){ return $deferred.reject(msg); } ); return $deferred.promise(); } var d=document; var s=d.createElement('script'); s.src='https://ajax.googleapis.com/ajax/libs/jquery/2.1.4/jquery.min.js'; s.onload=start; d.body.appendChild(s);
3cec3707e7479a07800b1192761587c26f5f0391
[ "JavaScript", "Markdown" ]
3
JavaScript
yociya/test
af055423150c4fc5a43c043587f507ecd4bbece7
7b5f6177688f95afc880b11f16e15fe38e7d0962
refs/heads/master
<file_sep>var request = require('./request'); exports = module.exports = Session; function Session (id) { this.id = id; } Session.prototype.path = function (complement) { complement = complement ? '/' + complement : ''; return '/session/' + this.id + complement; }; Session.prototype.get = function (callback) { var path = this.path(); return request.go('get', path, callback); }; Session.prototype.del = function (callback) { var path = this.path(); return request.go('del', path, callback); }; <file_sep>module.exports = require('./lib/selenium-sessions'); <file_sep>var superagent = require('superagent'); exports.baseUrl = 'http://localhost:444/wd/hub'; exports.go = function(method, path, callback) { var url = exports.baseUrl + path; var agent = superagent.agent(); agent[method](url) .end(function (err, res) { if (err) { return callback(err); } callback(null, res.body); }); }; <file_sep># selenium-sessions Get sesssions of selenium server with the [WebDriver Wire Protocol](https://code.google.com/p/selenium/wiki/JsonWireProtocol). --- ### Example ```js var Sessions = require(‘selenium-sessions’); var Session = Sessions.Session; var sessions = new Sessions({ url: "http://localhost:4444/wd/hub" }); sessions.all(function (err, data) { data.forEach(function (err, info){ var session = new Session(info.id); session.get(function (err, info){ session.del(); }); }); }); ```
9ca47b21201804e5c3e2b680ecec0271fecd39c6
[ "JavaScript", "Markdown" ]
4
JavaScript
archr/selenium-sessions
42805fb2f24e034041331179ed29179da43d6e2d
5034d409581c67440c4f1a308a3f4d13387b76c0
refs/heads/master
<repo_name>HishamElalawy/Developers_Project<file_sep>/users/views.py from django.shortcuts import render , redirect from .models import Profile , Skill , Message from projects.models import Project from django.contrib.auth import login, authenticate, logout from django.contrib.auth.models import User from .forms import CustomUserCreationForm , EditAccountForm , SkillsForm , MessageForm from django.contrib.auth.decorators import login_required from django.contrib import messages from django.db.models import Q from .utils import searchProfiles , paginateProfiles def profiles(request): profiles , search_query = searchProfiles(request) results = 3 custom_range, profiles = paginateProfiles(request , profiles , results) context = {'profiles':profiles , 'search_query':search_query , 'custom_range':custom_range } return render(request , 'users/profiles.html' , context) def userProfile(request , pk): profile = Profile.objects.get(id=pk) topSkills = profile.skill_set.exclude(description='') otherSkills = profile.skill_set.filter(description='') projects = profile.project_set.all() context = {'profile' : profile , 'topSkills' : topSkills ,'otherSkills' : otherSkills ,'projects':projects } return render (request , 'users/user-profile.html' , context) @login_required(login_url='login') def userAccount(request): profile = request.user.profile skills = profile.skill_set.all() projects = profile.project_set.all() context = {'profile':profile , 'skills':skills , 'projects':projects} return render(request , 'users/account.html' , context) @login_required(login_url='login') def editUserAccount(request): profile = request.user.profile form = EditAccountForm(instance=profile) if request.method =='POST': form = EditAccountForm(request.POST , request.FILES ,instance=profile) if form.is_valid(): profile = form.save(commit=False) profile.username = profile.username.lower() profile.save() messages.success(request , 'your Account Has been updated') return redirect('account') else: messages.error(request , 'Faild To Update The User') context = {'profile':profile , 'form':form} return render(request , 'users/edit-account.html' , context) def loginUser(request): page = 'login' if request.user.is_authenticated: return redirect('profiles') if request.method == 'POST': username = request.POST['username'].lower() password = request.POST['<PASSWORD>'] try: user = User.objects.get(username=username) except: messages.error(request, 'Username does not exist') user = authenticate(request, username=username, password=password) if user is not None: login(request, user) return redirect(request.GET['next'] if 'next' in request.GET else 'account') else: messages.error(request, 'Username OR password is incorrect') return render(request , 'users/login-register.html') def logoutUser(request): logout(request) return redirect('login') def registerUser(request): page = 'register' form = CustomUserCreationForm() if request.method == 'POST': form = CustomUserCreationForm(request.POST) if form.is_valid(): user = form.save(commit=False) user.username = user.username.lower() user.save() messages.success(request, 'User account was created!') login(request, user) return redirect('edit-account') else: messages.error( request, 'An error has occurred during registration') context = {'page': page, 'form': form} return render(request, 'users/login-register.html', context) @login_required(login_url='login') def createSkill(request): profile = request.user.profile form = SkillsForm() if request.method =='POST': form = SkillsForm(request.POST) if form.is_valid(): skill = form.save(commit=False) skill.owner = profile skill.save() messages.success(request, 'Skill was added successfully!') return redirect('account') context={'form':form} return render(request , 'users/skill-form.html',context) @login_required(login_url='login') def updateSkill(request , pk): profile = request.user.profile skill=profile.skill_set.get(id=pk) form = SkillsForm(instance=skill) if request.method =='POST': form = SkillsForm(request.POST ,instance=skill ) if form.is_valid(): skill = form.save(commit=False) skill.save() messages.success(request, 'Skill was updated successfully!') return redirect('account') context={'form':form} return render(request , 'users/skill-form.html',context) @login_required(login_url='login') def deleteSkill(request , pk): profile = request.user.profile skill = profile.skill_set.get(id=pk) if request.method == 'POST': skill.delete() messages.success(request, 'Skill was deleted successfully!') return redirect('account') context = {'object': skill} return render(request , 'delete-object.html' , context) @login_required(login_url='login') def inbox(request): profile = request.user.profile messageRequests = profile.messages.all() unReadmessagesCount = messageRequests.filter(is_read=False).count() context={'messageRequests':messageRequests,'unReadmessagesCount':unReadmessagesCount} return render(request , 'users/inbox.html',context) @login_required(login_url='login') def viewMessage(request , pk): profile = request.user.profile msg = profile.messages.get(id=pk) if msg.is_read == False: msg.is_read = True msg.save() context={'msg':msg} return render(request , 'users/message.html',context) def createMessage(request , pk): recipient = Profile.objects.get(id=pk) form = MessageForm() try: sender = request.user.profile except: sender = None if request.method == 'POST': form = MessageForm(request.POST) if form.is_valid(): msg = form.save(commit=False) msg.sender = sender msg.recipient = recipient if sender : msg.name = sender.name msg.email = sender.email msg.save() messages.success(request, 'Your message was successfully sent!') return redirect('profile', pk=recipient.id) context={'form':form , 'recipient':recipient} return render(request , 'users/msg-form.html' , context)<file_sep>/api/serializers.py from projects.models import Project , Tag , Review from users.models import Profile from rest_framework import serializers class TagSerializer(serializers.ModelSerializer): class Meta: model=Tag fields = '__all__' class ReviewSerializer(serializers.ModelSerializer): class Meta: model=Review fields = '__all__' class ProfileSerializer(serializers.ModelSerializer): class Meta: model=Profile fields='__all__' class ProjectSerializer(serializers.ModelSerializer): owner=ProfileSerializer(many=False) tags = TagSerializer(many=True) reviews = serializers.SerializerMethodField() class Meta: model=Project fields = '__all__' def get_reviews(self,obj): reviews = obj.review_set.all() serializer = ReviewSerializer(reviews, many=True) return serializer.data <file_sep>/projects/views.py from django.shortcuts import render , redirect from .models import Project , Tag from .forms import ProjectForm , ReviewForm from django.contrib.auth.decorators import login_required from .utils import searchProjects , paginateProjects from django.contrib import messages def projects(request): projects, search_query = searchProjects(request) paginate_results = 6 custom_range , projects = paginateProjects (request , projects , paginate_results) context = {'projects': projects, 'search_query': search_query , 'custom_range':custom_range } return render(request, 'projects/projects.html', context) def project(request , pk) : project = Project.objects.get(id=pk) form = ReviewForm() if request.method == 'POST': form = ReviewForm(request.POST) if form.is_valid(): review = form.save(commit=False) review.owner = request.user.profile review.project = project review.save() project.getVoteCount messages.success(request , 'Added Successfully') return redirect('project' , pk=project.id) context = {'project' : project, 'form':form} return render(request , 'projects/single-project.html' , context) @login_required(login_url='login') def createProject(request): profile = request.user.profile form = ProjectForm() if request.method =='POST' : newTags = request.POST.get('newtags').replace(',',' ').split() form = ProjectForm(request.POST , request.FILES) if form.is_valid(): project = form.save(commit=False) project.owner = profile project.save() for tag in newTags: tag , created = Tag.objects.get_or_create(name=tag) project.tags.add(tag) return redirect('projects') context = {'form' : form} return render (request , 'projects/project-form.html' , context) @login_required(login_url='login') def updateProject(request , pk): profile = request.user.profile project = profile.project_set.get(id=pk) form = ProjectForm(instance=project) if request.method == 'POST' : form = ProjectForm(request.POST , request.FILES, instance=project) newTags = request.POST.get('newtags').replace(',',' ').split() if form.is_valid(): project = form.save() for tag in newTags: tag, created = Tag.objects.get_or_create(name=tag) project.tags.add(tag) return redirect('projects') context = {'form' : form , 'project':project} return render(request , 'projects/project-form.html' , context) @login_required(login_url='login') def deleteProject(request , pk) : profile = request.user.profile project = profile.project_set.get(id=pk) if request.method == 'POST' : project.delete() return redirect('projects') context = {'object' : project} return render(request , 'delete-object.html' , context) <file_sep>/README.md # DevCommunity Online Developers Community To Allow Developers Share Their works And The other Devevelopers can rate and put a review on Their Projects ## Authors - [@HishamElalawy](https://www.github.com/HishamElalawy) ## Installation - 1- clone repo https://github.com/HishamElalawy/Developers_Project - 2- create a virtual environment and activate * pip install virtualenv * virtualenv envname * envname\scripts\activate - 3 - cd into project "cd Developers_Project" - 4 - pip install -r requirements.txt - 5 - python manage.py runserver ## Features - Share Projects - Message other developers - Rate others work - Search other developers ## Tech Stack **Backend:** Django , Postgres , Django Rest-Framework ## DataBase Design ![devcommunity_db](https://user-images.githubusercontent.com/61860186/136412738-f01c9622-8915-4e1d-8e5f-c667fa6ae340.png) ## Home Page ![developers](https://user-images.githubusercontent.com/61860186/135196858-26dec310-877d-498b-b660-3497b828a893.png) ## Projects Page ![projects](https://user-images.githubusercontent.com/61860186/135197072-1683c8d4-1322-4f85-8cd7-7fd9b58eeca1.png) ## Profile Page ![account](https://user-images.githubusercontent.com/61860186/135197320-c00de4c2-0477-4573-a47c-45b3c7e61801.png) ## User Inbox ![inbox](https://user-images.githubusercontent.com/61860186/135197420-e838f7db-43a1-4fdb-ab7b-e3c6a11945e9.png) ## SignUp Page ![signup](https://user-images.githubusercontent.com/61860186/135197529-8f7bf930-78d5-42e0-8195-6f9e88626c92.png) <file_sep>/users/urls.py from django.urls import path from . import views urlpatterns = [ path('',views.profiles , name="profiles"), path('profile/<str:pk>/' , views.userProfile , name="profile"), path('login/' , views.loginUser , name="login"), path('logout/' , views.logoutUser , name="logout"), path('signup/' , views.registerUser , name="signup"), path('account/' , views.userAccount , name="account"), path('edit-account/' , views.editUserAccount , name="edit-account"), path('create-skill/',views.createSkill , name="create-skill"), path('edit-skill/<str:pk>/',views.updateSkill,name="edit-skill"), path('delete-skill/<str:pk>/',views.deleteSkill,name="delete-skill"), path('inbox/',views.inbox,name="inbox"), path('view-message/<str:pk>/',views.viewMessage,name="view-message"), path('send-message/<str:pk>/',views.createMessage,name="send-message"), ]<file_sep>/projects/forms.py from django.forms import ModelForm , widgets from django import forms from .models import Project , Review class ProjectForm(ModelForm): class Meta: model=Project fields = ['title', 'image', 'description', 'demo_link', 'source_link' ] widgets = { 'tags' : forms.CheckboxSelectMultiple() } def __init__(self , *args , **kwargs): super(ProjectForm,self).__init__(*args,**kwargs) for name , field in self.fields.items(): field.widget.attrs.update({'class':'input'}) class ReviewForm(ModelForm): class Meta: model = Review fields = ['body' , 'value'] labels = { 'body' : 'Put your comment here', 'value' : 'place your vote' } def __init__(self , *args , **kwargs): super(ReviewForm,self).__init__(*args,**kwargs) for name , field in self.fields.items(): field.widget.attrs.update({'class':'input'})
e8d9a181235122d4225145cfb1c00eecbbaa1675
[ "Markdown", "Python" ]
6
Python
HishamElalawy/Developers_Project
2bfd8571ae1d9cb65a5e2b36228d9411f3894cab
6e6f34007915d990e2819cea9730cccbb9104098
refs/heads/master
<file_sep>//signal daemon - <NAME> //Starts a daemon that logs signals as they're received #include <signal.h> #include <stdio.h> #include <stdlib.h> #include <sys/types.h> #include <sys/stat.h> #include <unistd.h> #include <fcntl.h> #include <sys/time.h> #include <sys/resource.h> int daemonize() { int i, fd0, fd1, fd2, log_fd; pid_t pid; struct rlimit rl; struct sigaction sa; umask(0); log_fd = open("/home/gabrielm/signald.log", O_RDWR); if(getrlimit(RLIMIT_NOFILE, &rl) < 0) { printf("Unable to get file limit\n"); abort(); } if((pid = fork()) < 0) { printf("Fork error\n"); abort(); } else if(pid != 0) exit(0); setsid(); sa.sa_handler = SIG_IGN; sigemptyset(&sa.sa_mask); sa.sa_flags = 0; if(sigaction(SIGHUP, &sa, NULL) < 0) { printf("Cannot ignore SIGHUP\n"); abort(); } if((pid = fork()) < 0) { printf("Fork error (second fork)\n"); abort(); } else if(pid != 0) exit(0); if(chdir("/") < 0) { printf("Chdir error\n"); abort(); } if(rl.rlim_max == RLIM_INFINITY) rl.rlim_max = 1024; for(i = 0; i < rl.rlim_max; i++) close(i); fd0 = open("/dev/null", O_RDWR); fd1 = dup(0); fd2 = dup(0); dprintf(log_fd, "made it this far at least\n"); return log_fd; } int main(int argc, char **argv) { struct sigaction sa; int wait, signo, log_fd; sigset_t mask; log_fd = daemonize(); sigfillset(&mask); for(;;) { wait = sigwait(&mask, &signo); if(wait != 0) exit(0); switch(signo) { case SIGHUP: dprintf(log_fd, "Received SIGHUP\n"); case SIGTERM: dprintf(log_fd, "Received SIGTERM\n"); case SIGUSR1: dprintf(log_fd, "Received SIGUSR1\n"); default: dprintf(log_fd, "Received unsupported signal\n"); break; } } close(log_fd); exit(0); } <file_sep>#include <stdio.h> #include <dirent.h> void printType(struct stat *st) { switch(st->st_mode & S_IFMT) { case S_IFDIR: printf("d"); break; case S_IFREG: printf("-"); break; case S_IFCHR: printf("c"); break; case S_IFBLK: printf("b"); break; case S_IFIFO: printf("|"); break; // FIFO == PIPE case S_IFLNK: printf("l"); break; // tricky to get right case S_IFSOCK: printf("s"); break; } } void printMode(struct stat *st) { // TODO: add setuid/setgid, etc printf((st->st_mode & S_IRUSR)? "r":"-"); printf((st->st_mode & S_IWUSR)? "w":"-"); printf((st->st_mode & S_IXUSR)? "x":"-"); printf((st->st_mode & S_IRGRP)? "r":"-"); printf((st->st_mode & S_IWGRP)? "w":"-"); printf((st->st_mode & S_IXGRP)? "x":"-"); printf((st->st_mode & S_IROTH)? "r":"-"); printf((st->st_mode & S_IWOTH)? "w":"-"); printf((st->st_mode & S_IXOTH)? "x":"-"); } int processArgs() int main(int argc, char *argv[]) { struct dirent *direntp; DIR *dirp; struct stat st; if(argc <= 1) { dirp = opendir("."); }else{ dirp = opendir(argv[1]); } if(dirp == NULL) { printf("Error reading file\n"); } while((direntp = readdir(dirp)) != NULL) { if(stat(direntp->dname, st) == -1) { printf("Stat error\n"); exit(0); } printMode(&st); printf("%s ", direntp->d_name); } printf("\n"); closedir(dirp); exit(0); } <file_sep>#! /bin/bash xsetroot -solid "#FFFFFF" xrdb -load $HOME/.Xdefaults exec /usr/bin/scmwm <file_sep>//<NAME> - bit cipher assignment for ALSP //I ended up borrowing some code from the example and modifying it //to work with my code, hopefully that is alright. #include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <string.h> #include <sys/types.h> #include <errno.h> #include <sys/stat.h> #include <error.h> int op = 0; char *fname; char map[] = "07534621"; static void Fopen(char *name, char *mode, FILE **fp) { *fp = fopen(name, mode); if (*fp == NULL) error(EXIT_FAILURE, errno, "\"%s\"", name); } static void Fstat(int fd, struct stat *st) { if (fstat(fd, st) == -1) error(EXIT_FAILURE, errno, "stat failed"); } static void Malloc(char **buf, uint size) { *buf = malloc(size); if (buf == NULL) error(EXIT_FAILURE, 0, "malloc failed"); } char mapshifter(char byte) { unsigned int out = 0; unsigned int mask; if(op == 1) { for(int i = 0; i < 8; i++) { mask = byte & (1 << (map[7-i] - '0')); out |= ((mask ? 1 : 0) << i); } } else { for(int i = 0; i < 8; i++) { mask = (byte & (1 << i)) ? 1 : 0; out |= (mask << (map[7-i] - '0')); } } return out; } int processFile(char **fname) { long int bufSize; char *buf; long int count; FILE *fp; struct stat st; Fopen(*fname, "r", &fp); Fstat(fileno(fp), &st); Malloc(&buf, st.st_size + 1); memset(buf, 0, st.st_size + 1); count = fread(buf, sizeof(char), st.st_size, fp); fclose(fp); if (count != st.st_size) { fprintf(stderr, "In %s: asked for %ld and got %ld\n", __FUNCTION__, st.st_size, count); return -1; } bufSize = count; for(long int i = 0; i < bufSize; i++) { buf[i] = mapshifter(buf[i]); printf("%c", buf[i]); } free(buf); return 0; } int main(int argc, char *argv[]) { int c; if (argc != 4) exit(-1); while ((c = getopt(argc, argv, "dei:")) != -1) { switch (c) { case 'd': op = 0; break; case 'e': op = 1; break; case 'i': fname = optarg; break; default: exit(-1); } } if(processFile(&fname) != 0) { error(EXIT_FAILURE, 0, "Unable to encode."); } exit(0); } <file_sep>void write_to_log (char *msg); <file_sep>#include <string.h> #include <stdio.h> #include <stdlib.h> #include <fcntl.h> #include <unistd.h> int main (int argc, char **argv) { if (argc < 2) { printf("Wrong number of arguments. Usage:\nscmwmclient <command> <arguments>\nAvailable commands:\nteleport <window> <x_pos> <y_pos> <x_size> <y_size>\nminmax\n"); exit(EXIT_FAILURE); } int server = open("/tmp/scmwm", O_WRONLY); if (strcmp(argv[1], "minmax") == 0) { printf("Minmaxing\n"); if (write(server, "minimize", strlen("minimize")) == -1) exit(EXIT_FAILURE); } else if (strcmp(argv[1], "teleport") == 0 && argc == 7) { printf("Teleporting window %d to %d,%d, size %dx%d.\n", atoi(argv[2]), atoi(argv[3]), atoi(argv[4]), atoi(argv[5]), atoi(argv[6])); char buf[200]; sprintf(buf, "%d %d %d %d %d", atoi(argv[2]), atoi(argv[3]), atoi(argv[4]), atoi(argv[5]), atoi(argv[6])); if (write(server, buf, strlen(buf)) == -1) exit(EXIT_FAILURE); } close(server); return EXIT_SUCCESS; } <file_sep>#ifndef CLIENT_FIFO #define CLIENT_FIFO "/tmp/scmwm" #endif #ifndef MAX_EVENTS #define MAX_EVENTS 1 #endif #ifndef MAX_LINE_SIZE #define MAX_LINE_SIZE 200 #endif /* Internal constants * Modified from hootwm */ #ifndef XCB_MOVE #define XCB_MOVE XCB_CONFIG_WINDOW_X | XCB_CONFIG_WINDOW_Y #endif #ifndef XCB_RESIZE #define XCB_RESIZE XCB_CONFIG_WINDOW_WIDTH | XCB_CONFIG_WINDOW_HEIGHT #endif #ifndef XCB_MOVE_RESIZE #define XCB_MOVE_RESIZE XCB_MOVE | XCB_RESIZE #endif #ifndef NUM_WINDOWS #define NUM_WINDOWS 4 #endif /* User defined constants */ #ifndef PAD_LEFT #define PAD_LEFT 30 #endif #ifndef PAD_RIGHT #define PAD_RIGHT 0 #endif #ifndef PAD_BOTTOM #define PAD_BOTTOM 0 #endif #ifndef PAD_TOP #define PAD_TOP 30 #endif #ifndef NUM_TAGS #define NUM_TAGS 10 #endif #ifndef WINDOW_DEFAULT_SIZE #define WINDOW_DEFAULT_SIZE 800, 800 #endif #ifndef WINDOW_DEFAULT_POSITION #define WINDOW_DEFAULT_POSITION PAD_TOP, PAD_LEFT #endif #ifndef WINDOW_DEFAULTS #define WINDOW_DEFAULTS {WINDOW_DEFAULT_POSITION, WINDOW_DEFAULT_SIZE} #endif <file_sep>CC=gcc SOURCES = scmwm.c list.c log.c CLIENT_SOURCES = client.c FLAGS = -Wall -Werror -Ofast DEBUG_FLAGS = -g -Wall -lxcb -DDEBUG_BUILD -DDEBUG LINK_FLAGS = -lxcb -pthread -lxcb-keysyms BINARIES = scmwm scmwm-debug-build list-tests scmwmclient scmwmclient-debug all: $(SOURCES) $(CC) $(FLAGS) $(SOURCES) -o scmwm $(LINK_FLAGS) -DLOGGING_RELEASE $(CC) $(FLAGS) $(CLIENT_SOURCES) -o scmwmclient -DLOGGING_RELEASE $(CC) $(DEBUG_FLAGS) $(SOURCES) -o scmwm-debug-build $(LINK_FLAGS) $(CC) $(DEBUG_FLAGS) $(CLIENT_SOURCES) -o scmwmclient-debug release: $(SOURCES) $(CC) $(FLAGS) $(SOURCES) -o scmwm $(LINK_FLAGS) -DLOGGING_RELEASE debug: $(SOURCES) $(CC) $(DEBUG_FLAGS) $(SOURCES) -o scmwm-debug-build $(LINK_FLAGS) install: $(SOURCES) $(CC) $(FLAGS) $(SOURCES) -o /usr/bin/scmwm $(LINK_FLAGS) -DLOGGING_RELEASE $(CC) $(FLAGS) $(CLIENT_SOURCES) -o /usr/bin/scmwmclient -DLOGGING_RELEASE cp scmwm-session /usr/bin/scmwm-session chmod +x /usr/bin/scmwm-session cp scmwm.desktop /usr/share/xsessions/scmwm.desktop debug-install: $(SOURCES) $(CC) $(DEBUG_FLAGS) $(SOURCES) -o /usr/bin/scmwm $(LINK_FLAGS) $(CC) $(DEBUG_FLAGS) $(CLIENT_SOURCES) -o /usr/bin/scmwmclient cp scmwm-session /usr/bin/scmwm-session chmod +x /usr/bin/scmwm-session cp scmwm.desktop /usr/share/xsessions/scmwm.desktop tests: list.c $(CC) list.c -o list-tests -Wall -g $(LINK_FLAGS) -DDEBUG clean: rm -f $(BINARIES) <file_sep>#include <stdio.h> #include <stdlib.h> #include <sys/types.h> #include <sys/socket.h> #include <netdb.h> int main(int argc, char **argv) { struct addrinfo *addr, *a; int getinfo; char ip_addr[256]; getinfo = getaddrinfo("babbage.cs.pdx.edu", NULL, NULL, &addr); if(getinfo != 0) { printf("getaddrinfo error\n"); exit(0); } for (a = addr; a != NULL; a = a->ai_next) { getnameinfo(a->ai_addr, a->ai_addrlen, ip_addr, sizeof (ip_addr), NULL, 0, NI_NUMERICHOST); printf("%s\n", ip_addr); } exit(1); } <file_sep># alsp Assignments and projects from advanced linux systems programming Some are complete, others still have bugs ## Bitcipher Jumbles bits around for every byte of a file to encrypt then reverses the process. Bit jumbling determined by predetermined mapping. ## Daemon Attempt at writing a daemon, logging is not working correctly. ## Getaddr Small test program to use getaddr() ## Gls "Gabe ls", an ls clone. May have some lingering bugs, -F option is buggy as well. ## Locklesslog Demonstrates multiple processes writing to the same log file without using locks. ## scmwm Window manager developed by myself and <NAME> as a final project. See scmwm README for more. ## Shell A simple shell with some builtins and support for piping. ## Signal A test program to use signals. ## Uname Small clone of the uname command. <file_sep>// simple shell - Team members: <NAME>, <NAME> #include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <sys/wait.h> #include <errno.h> #include <string.h> #include <sys/types.h> #include <unistd.h> #include <error.h> static int Error(int status, int errnum, char *message) { fflush(stderr); errno = errnum; int err = fileno(stderr); char *errmsg = strerror(errnum); if (write(err, message, strlen(message)) == -1 || write(err, ": ", 2) == -1 || write(err, errmsg, strlen(errmsg)) == -1 || write(err, "\n", 1) == -1) exit(EXIT_FAILURE); exit(status); } static int Fork() { pid_t pid; if ((pid = fork()) < 0) Error(EXIT_FAILURE, errno, "fork error"); return(pid); } static int make_argv(char ***line, char *buf) { int buflen = strlen(buf); int argnum = 1; for(int i=0; i < buflen; i++) { if(buf[i] == ' ') argnum++; } *line = (char**) malloc(sizeof(char*)*argnum); char *command = strtok(buf, " "); for(int i=0; i < 20 && command != NULL; i++) { (*line)[i] = command; command = strtok(NULL, " "); } return argnum; } //Returns number of paths int get_paths(char ***paths) { char *PATH = getenv("PATH"); char *path_copy = (char*) malloc(strlen(PATH)+1); strcpy(path_copy, PATH); int numpaths = 1; int pathlen = strlen(path_copy); for(int i=0; i < pathlen; i++) { if(path_copy[i] == ':') numpaths++; } *paths = (char**) malloc(sizeof(char*)*numpaths); char *path = strtok(path_copy, ":"); for(int i=0; i < numpaths && path != NULL; i++) { (*paths)[i] = path; path = strtok(NULL, ":"); } return numpaths; } //Returns number of split commands that need to be piped int check_make_pipe(char ***line, char *buf) { int i; char *bufcpy = malloc(strlen(buf)*sizeof(char)+1); strcpy(bufcpy, buf); char *command = strtok(buf, "|"); //if no pipes then return, otherwise build commands to pipe if(!strcmp(command, bufcpy)) return -1; *line = (char**) malloc(strlen(command)*sizeof(char)+1); for(i=0; i < 20 && command != NULL; i++) { (*line)[i] = command; command = strtok(NULL, "|"); } free(bufcpy); return i; } void exec_pipe(int input_fd, int output_fd, char *command) { pid_t pid = Fork(); if(pid == 0) { //Child - setup fd's then exec if (input_fd != 0) { dup2(input_fd, 0); close(input_fd); } if(output_fd != 1) { dup2(output_fd, 1); close(output_fd); } char **args; char **paths; int numpaths = get_paths(&paths); int argnum = make_argv(&args, command); for(int i=0; i < numpaths; i++) { char *path = (char*) malloc(strlen(paths[i])+strlen(args[0]) + 1); strcpy(path, paths[i]); strcat(path, "/"); strcat(path, args[0]); if (access(path, X_OK) == 0) { if(execv(path, args) == -1) { free(path); printf("%s: command not found\n", args[0]); abort(); } } free(path); } printf("%s: command not found\n", args[0]); abort(); } } void pipe_commands(int numcommands, char **commands) { int pipe_fd[2]; int input_fd = 0; for(int i = 0; i < numcommands - 1; i++) { if(pipe(pipe_fd) < 0) { printf("Pipe error\n"); exit(0); //Should maybe abort here? } exec_pipe(input_fd, pipe_fd[1], commands[i]); close(pipe_fd[1]); input_fd = pipe_fd[0]; } if (input_fd != 0) { dup2(input_fd, 0); } close(input_fd); char **args; char **paths; int numpaths = get_paths(&paths); int argnum = make_argv(&args, commands[numcommands-1]); for(int i=0; i < numpaths; i++) { char *path = (char*) malloc(strlen(paths[i])+strlen(args[0]) + 1); strcpy(path, paths[i]); strcat(path, "/"); strcat(path, args[0]); if (access(path, X_OK) == 0) { if(execv(path, args) == -1) { free(path); printf("%s: command not found\n", args[0]); abort(); } } } printf("%s: command not found\n", args[0]); abort(); } int main(int argc, char **argv) { long MAX = sysconf(_SC_LINE_MAX); char buf[MAX]; pid_t pid; int status, pipes, argnum; char *prompt = "% "; int c; if(argc > 1) { while ((c = getopt (argc, argv, "p:")) != -1) switch (c) { case 'p': prompt = optarg; break; } } do { memset(&buf, 0, MAX); if(write(fileno(stdout), prompt, strlen(prompt)) == -1) exit(EXIT_FAILURE); fflush(0); if(read(fileno(stdin), &buf, MAX) == -1) break; // Avoid segfault on empty line if(buf[0] == '\0') printf("\nshell: CTRL-D is not supported to exit the shell. Instead, use 'exit'.\n"); if(strlen(buf) != 1 && buf[0] != '\0') { buf[strlen(buf)-1] = 0; // chomp '\n' if(strcmp(buf, "exit")) { char **line; char buf2[MAX]; strcpy(buf2, buf); // Break the buffer into an argvector. if((pipes = check_make_pipe(&line, buf2)) != -1) { pid = Fork(); if(pid == 0) { pipe_commands(pipes, line); } continue; }else{ argnum = make_argv(&line, buf); // Shell builtins if (!strcmp(line[0], "cd")) { // TODO: Better error message from this function. if (chdir(line[1]) == -1) printf("Failed to change directory.\n"); else printf("Changed dir to %s\n", line[1]); } else if (!strcmp(line[0], "set")) { // setenv if(setenv(line[1], line[2], 1) != 0) { printf("Failed to set env %s to %s\n", line[1], line[2]); }else{ printf("env %s set to %s\n", line[1], line[2]); } } else if (!strcmp(line[0], "get")) { // getenv for(int i = 1; i < argnum; i++) { char *env = getenv(line[i]); if(env == NULL) { printf("Could not get env: %s\n", line[i]); break; }else{ printf("%s ", env); } } printf("\n"); } else { pid = Fork(); if (pid == 0) { // child char **paths; int numpaths = get_paths(&paths); for(int i=0; i < numpaths; i++) { char *path = (char*) malloc(strlen(paths[i])+strlen(line[0]) + 1); strcpy(path, paths[i]); strcat(path, "/"); strcat(path, line[0]); if (access(path, X_OK) == 0) { if(execv(path, line) == -1) { free(path); printf("%s: command not found\n", line[0]); abort(); } } } printf("%s: command not found\n", line[0]); abort(); } // parent if ((pid = waitpid(pid, &status, 0)) < 0) Error(EXIT_FAILURE, errno, "waitpid error"); } free(line); } } } } while(strcmp(buf, "exit")); exit(EXIT_SUCCESS); } <file_sep>struct window_node { xcb_window_t window; struct window_node *next; }; typedef struct { uint32_t len; struct window_node *head; struct window_node *tail; pthread_mutex_t lock; } list; void init (list *self); void window_list_push (list *self, xcb_window_t w); int window_list_remove (list *self, xcb_window_t w); int window_list_modify (list *self, xcb_window_t w, xcb_connection_t *connection, uint32_t position[]); void window_list_destroy (list *self); void window_list_map_all (list *self, xcb_connection_t *connection); void window_list_unmap_all (list *self, xcb_connection_t *connection); <file_sep># SCMWM ## So what's this window manager? This window manager is a floating window manager with an emphasis on simplicity in design (everything is done through a client program), having as much of the code in one place as possible (our only non-UNIX dependency is XCB), and being keyboard-focused and easy to use. ## Design decisions * Pure floating: This has 2 reasons. It's much more straightforward to implement, which makes the code easier to read and doesn't require a tiling algorithm. The other is that many existing floating window managers tend to be huge and bundled with more complicated software (ex: GNOME). * Keyboard focus: If you need a mouse to use a window manager, the window manager is written wrong. This is because mice are imprecise and annoying, especially on laptops. * Controlled by a client: This one is taken from herbstluftwm and hootwm. It's convenient for building config files. ## Lower-level design (if you want to roll your own client) * Communication is done by a well-known FIFO currently specified in a config file. * The keyboard server: TBD. * Currently no calls to xlib, only to xcb. ## Installation ``` $ # Under Ubuntu $ apt install libxcb1-dev $ # Install the window manager $ make install ``` Then go back into your display manager or however else you start window managers. That *should* be all you have to do, but I've had some real problems with `gdm`. Commands can then be echoed to the FIFO, with some built in commands to allow movement and some default programs Code by <NAME> and <NAME> <file_sep>#include <xcb/xcb.h> #include <stdlib.h> #include <stdio.h> #include <pthread.h> #include "constants.h" #include "list.h" #include "log.h" void init (list *self) { pthread_mutex_init(&self->lock, NULL); self->len = 0; self->head = NULL; self->tail = NULL; } void window_list_push (list *self, xcb_window_t w) { if(self->head == NULL) { self->head = (struct window_node*) malloc(sizeof(struct window_node)); self->head->window = w; self->head->next = NULL; self->tail = self->head; } else { self->tail->next = (struct window_node*) malloc(sizeof(struct window_node)); self->tail->next->window = w; self->tail->next->next = NULL; self->tail = self->tail->next; } self->len++; } int window_list_remove (list *self, xcb_window_t w) { if(!self->head) { return 1; } else if(self->head->window == w) { struct window_node *temp = self->head; self->head = self->head->next; free(temp); self->len--; return 0; } else { struct window_node *previous = self->head; for(struct window_node *current = self->head; current != NULL; current = current->next) { if (current->window == w) { previous->next = current->next; free(current); self->len--; return 0; } previous = current; } return 1; } } int window_list_modify (list *self, xcb_window_t w, xcb_connection_t *connection, uint32_t position[]) { struct window_node *current = self->head; while(current != NULL) { if(current->window == w) { xcb_configure_window(connection, current->window, XCB_MOVE_RESIZE, position); xcb_map_window(connection, current->window); return 0; } else current = current->next; } return 1; } /* Note: Do not attempt to acquire a lock before destroying a list as it will deadlock. */ void window_list_destroy (list *self) { pthread_mutex_lock(&self->lock); while(self->head) { struct window_node *next = self->head->next; free(self->head); self->head = next; } pthread_mutex_unlock(&self->lock); pthread_mutex_destroy(&self->lock); self->len = 0; } void window_list_map_all (list *self, xcb_connection_t *connection) { struct window_node *current = self->head; while(current != NULL) { write_to_log("Mapping window\n"); xcb_map_window(connection, current->window); current = current->next; } } void window_list_unmap_all (list *self, xcb_connection_t *connection) { struct window_node *current = self->head; while(current != NULL) { write_to_log("Unmapping window\n"); xcb_unmap_window(connection, current->window); current = current->next; } } #ifdef DEBUG /* Note: Cannot test map and unmap all here. * Tests can be made using make list_tests */ int list_tests () { list test_list; pthread_mutex_lock(&test_list.lock); init(&test_list); pthread_mutex_unlock(&test_list.lock); xcb_window_t test; pthread_mutex_lock(&test_list.lock); window_list_push(&test_list, test); pthread_mutex_unlock(&test_list.lock); xcb_window_t test1; pthread_mutex_lock(&test_list.lock); window_list_push(&test_list, test1); pthread_mutex_unlock(&test_list.lock); xcb_window_t test2; pthread_mutex_lock(&test_list.lock); window_list_push(&test_list, test2); pthread_mutex_unlock(&test_list.lock); pthread_mutex_lock(&test_list.lock); printf("%d\n", window_list_remove(&test_list, test2)); printf("%d\n", window_list_remove(&test_list, test1)); printf("%d\n", window_list_remove(&test_list, test)); pthread_mutex_unlock(&test_list.lock); window_list_destroy(&test_list); return 0; } #ifndef DEBUG_BUILD int main () { return list_tests(); } #endif #endif <file_sep>#include <fcntl.h> #include <unistd.h> #include <stdio.h> #include <string.h> void write_to_log (char *msg) { int fd = open("/tmp/scmwm.log", O_RDWR | O_APPEND | O_CREAT, 0666); if(write(fd, msg, strlen(msg)) == -1) perror("Write to log error"); close(fd); } <file_sep>/* <NAME>, <NAME>, <NAME> * Lockless logging implementation */ // Length per process and its offset #include <stdio.h> #include <unistd.h> #include <stdlib.h> #include <fcntl.h> #include <time.h> #include <string.h> #include <stdint.h> #define OFFSET 1024 // Keep track of a single process this way typedef struct { int pid; // Starting offset uint64_t offset; // Current offset after any writes are done uint64_t current_offset; } proc; // Writes a single block of data // Needs to be updated to avoid spilling over into another log file uint64_t writeBlock(int fd, uint64_t offset, char *buf) { uint64_t new_offset = 0; // Changed to strlen because sizeof returns the wrong size for some reason? if((new_offset = pwrite(fd, buf, strlen(buf), offset)) < 0) { perror("Failed to write buf\n"); abort(); } return new_offset; } int main(int argc, char **argv) { // Defaults char *path = "logfile"; int num_proc = 5; /* Arguments: * -p <NUM>: Number of processes to use to write to the file. * -o <FILENAME>: File to write to. */ int c; while ((c = getopt(argc, argv, "p:o:h")) != -1) { switch(c) { case 'p': num_proc = atoi(optarg); break; case 'o': path = optarg; break; case 'h': printf("Concurrent log: Help\n\tAguments:\n\t-p <NUM>: Number of processes to use to write to the file.\n\t-o <FILENAME>: File to write to.\n"); return 0; default: break; } } int fd = open(path, O_RDWR | O_CREAT | O_TRUNC, 0666); proc *procs = (proc*) alloca(sizeof(proc)*num_proc); for (int i=0; i < num_proc; i++) { // Set initial offset procs[i].offset = OFFSET*i; // Start current offset at the same as initial offset procs[i].current_offset = OFFSET*i; // Set PID per process if ((procs[i].pid = fork()) < 0) { perror("Process creation failed.\n"); abort(); } else if (procs[i].pid == 0) { time_t t; struct tm *temp_time; temp_time = localtime(&t); char buf[OFFSET]; if((strftime(buf, OFFSET, "time and date: %r, %a %b %d, %Y\n", temp_time)) == 0) { perror("strftime error\n"); abort(); } // Write to logfile at correct location uint64_t written = writeBlock(fd, procs[i].current_offset, buf); // Update proc variables procs[i].current_offset += written; return 0; } } return 0; } <file_sep>#include <xcb/xcb.h> #include <xcb/xcb_aux.h> #include <xcb/xcb_event.h> #include <xcb/xcb_keysyms.h> #include <X11/keysym.h> #include <assert.h> #include <signal.h> #include <errno.h> #include <error.h> #include <stdio.h> #include <unistd.h> #include <stdlib.h> #include <stdarg.h> #include <fcntl.h> #include <sys/stat.h> #include <sys/epoll.h> #include <pthread.h> #include <string.h> #include "constants.h" #include "list.h" #include "log.h" /* Why is this a global? Globals are common design elements in window managers, which rely on manipulating global state. * Why is not behind a lock? Precisely 2 functions mutate it: setup() and quit(). Neither of these should happen at the same time. */ xcb_connection_t *connection; list windows; static int mod = 0; typedef struct { FILE *fifo; int fifofd; } ipc_info; static int Fork() { pid_t pid; if ((pid = fork()) < 0) { write_to_log("Fork error\n"); exit(0); } return(pid); } // int // check_mod(uint32_t mask, char ***keys) // { // int i, keys_pressed = 0; // // const char *MODIFIERS = { // "Shift", "Lock", "Ctrl", "Alt", // "Mod2", "Mod3", "Mod4", "Mod5", // "Button1", "Button2", "Button3", "Button4", "Button5" // }; // for (const char **modifier = MODIFIERS ; mask; mask >>= 1, ++modifier) { // if (mask & 1) { // keys_pressed++; // if(keys_pressed > 3) // continue; // (*keys)[i] = strdup(*modifier); // i++; // // printf (*modifier); // } // } // return keys_pressed; // } /* Thread driver * epoll() code taken primarily from epoll man page and rewritten to work with pipes instead of a socket. */ static void* handle_input (void *arg) { #ifndef LOGGING_RELEASE write_to_log("Started worker thread.\n"); #endif char **args = NULL; int pid, exec; ipc_info *ipc = (ipc_info*) arg; struct epoll_event ev, events[MAX_EVENTS]; int nfds, readsz; int epollfd = epoll_create1(0); if (epollfd == -1) { perror("epoll error"); exit(EXIT_FAILURE); } #ifndef LOGGING_RELEASE write_to_log("epoll service started.\n"); #endif ev.events = EPOLLIN | EPOLLET; int server_endpoint_fd = ipc->fifofd; ev.data.fd = server_endpoint_fd; if (epoll_ctl(epollfd, EPOLL_CTL_ADD, server_endpoint_fd, &ev) == -1) { perror("epoll error: epoll_ctl"); exit(EXIT_FAILURE); } int minimized = 0; char buf[MAX_LINE_SIZE]; for(;;) { #ifndef LOGGING_RELEASE write_to_log("Begin waiting for epoll.\n"); #endif memset(buf, 0, MAX_LINE_SIZE); nfds = epoll_wait(epollfd, events, MAX_EVENTS, -1); if (nfds == -1) { perror("epoll_wait"); exit(EXIT_FAILURE); } for(int n=0; n < nfds; n++) { if (events[n].data.fd == server_endpoint_fd) { if((readsz = read(ipc->fifofd, buf, MAX_LINE_SIZE)) < 0) { #ifndef LOGGING_RELEASE write_to_log("Read error.\n"); #endif perror("Read error"); } buf[readsz-1] = 0; if(strcmp(buf, "minimize") == 0) { if(minimized == 0) { pthread_mutex_lock(&windows.lock); window_list_unmap_all(&windows, connection); pthread_mutex_unlock(&windows.lock); xcb_flush(connection); minimized = 1; } else { pthread_mutex_lock(&windows.lock); window_list_map_all(&windows, connection); pthread_mutex_unlock(&windows.lock); xcb_flush(connection); minimized = 0; } } else if(strcmp(buf, "xterm") == 0){ pid = Fork(); if(pid == 0) { if((exec = execvp("/usr/bin/xterm", args)) == -1) { #ifndef LOGGING_RELEASE write_to_log("Exec error"); #endif exit(0); } } } else if(strcmp(buf, "chrome") == 0){ pid = Fork(); if(pid == 0) { if((exec = execvp("/usr/bin/google-chrome-stable", args)) == -1) { #ifndef LOGGING_RELEASE write_to_log("Exec error"); #endif exit(0); } } } else { int window_number = 0; int position_x = 0; int position_y = 0; int size_x = 500; int size_y = 500; sscanf(buf, "%d %d %d %d %d", &window_number, &position_x, &position_y, &size_x, &size_y); pthread_mutex_lock(&windows.lock); /* Traverse to the window_numberth place in the window list */ struct window_node *current = windows.head; for(int i=0; i < window_number && current != NULL; i++) { current = current->next; } if (current) { uint32_t target_position[] = {position_x, position_y, size_x, size_y}; xcb_configure_window(connection, current->window, XCB_MOVE_RESIZE, target_position); xcb_map_window(connection, current->window); xcb_flush(connection); } pthread_mutex_unlock(&windows.lock); } } } } } /* Quit the window manager in response to a signal. */ void quit (int signo) { xcb_disconnect(connection); } //Key handling adapted from i3 void handle_keypress(xcb_key_press_event_t *event) { char **args = NULL; int pid, exec; static xcb_key_symbols_t *symbols; int col = ((event->state) & XCB_MOD_MASK_SHIFT); xcb_keysym_t sym; sym = xcb_key_press_lookup_keysym(symbols, event, col); //Check if mod key, if so set mod and return if(sym == XK_Mode_switch){ mod = 1; return; } //Otherwise, check for some commands if(mod == 1) { if(sym == XK_Return) { pid = Fork(); if(pid == 0) { if((exec = execvp("/usr/bin/xterm", args)) == -1) { #ifndef LOGGING_RELEASE write_to_log("Exec error"); #endif exit(0); } } } } } void handle_keyrelease(xcb_key_release_event_t *event) { static xcb_key_symbols_t *symbols; xcb_keysym_t sym = xcb_key_press_lookup_keysym(symbols, event, event->state); //Check to see if a mod key was released and reset mod if(sym == XK_Mode_switch){ mod = 0; return; } } void handle_buttons (xcb_button_t detail) { /* Event handler. Register in switch/case statement. * Idea as a way to try things: fork/exec in here on keypress? */ switch (detail) { default: break; } } int handle_event (xcb_generic_event_t *event) { switch(event->response_type & ~0x80) { case XCB_MAP_REQUEST: /* What to do when windows are created * Note that we must cast the generic event to the correct type before using it. * XCB implements events as a union with a response_type attached to it. Since we know * the type of request, it's safe to cast. */ { #ifndef LOGGING_RELEASE write_to_log("Map request received\n"); #endif xcb_map_request_event_t *map_event = (xcb_map_request_event_t*)event; uint32_t default_position[] = WINDOW_DEFAULTS; xcb_configure_window(connection, map_event->window, XCB_MOVE_RESIZE, default_position); xcb_map_window(connection, map_event->window); /* Add to list of windows for the workspace */ pthread_mutex_lock(&windows.lock); window_list_push(&windows, map_event->window); pthread_mutex_unlock(&windows.lock); xcb_flush(connection); } break; case XCB_DESTROY_NOTIFY: /* What to do when windows are destroyed */ { xcb_destroy_notify_event_t *destroy_event = (xcb_destroy_notify_event_t*)event; /* Remove from list of windows for the workspace */ pthread_mutex_lock(&windows.lock); window_list_remove(&windows, destroy_event->window); pthread_mutex_unlock(&windows.lock); xcb_flush(connection); } break; case XCB_BUTTON_PRESS: { xcb_button_press_event_t *button_event = (xcb_button_press_event_t *) event; #ifndef LOGGING_RELEASE write_to_log("button handled"); #endif handle_buttons(button_event->detail); } break; case XCB_KEY_PRESS: { xcb_key_press_event_t *key_event = (xcb_key_press_event_t *) event; #ifndef LOGGING_RELEASE write_to_log("Key handled"); #endif handle_keypress(key_event); } break; case XCB_KEY_RELEASE: { xcb_key_release_event_t *key_event = (xcb_key_release_event_t *) event; #ifndef LOGGING_RELEASE write_to_log("Key handled"); #endif handle_keyrelease(key_event); } break; default: break; } free(event); return 0; } /* Set up substructure redirection on the root window * We assume we have a connection by now and don't bother to * get one. Written initially based off hootwm's setup function. * https://github.com/steinuil/hootwm */ void setup () { xcb_screen_t *screen = xcb_setup_roots_iterator(xcb_get_setup(connection)).data; /* Mask for substructure redirection requests */ uint32_t mask[1] = { XCB_EVENT_MASK_SUBSTRUCTURE_NOTIFY | XCB_EVENT_MASK_SUBSTRUCTURE_REDIRECT | XCB_EVENT_MASK_EXPOSURE | XCB_EVENT_MASK_BUTTON_PRESS | XCB_EVENT_MASK_BUTTON_RELEASE | XCB_EVENT_MASK_POINTER_MOTION | XCB_EVENT_MASK_ENTER_WINDOW | XCB_EVENT_MASK_LEAVE_WINDOW | XCB_EVENT_MASK_KEY_PRESS | XCB_EVENT_MASK_KEY_RELEASE }; xcb_change_window_attributes(connection, screen->root, XCB_CW_EVENT_MASK, mask); /* xcb_grab_keyboard_cookie_t cookie; xcb_grab_keyboard_reply_t *reply = NULL; int count = 0; while ((reply == NULL || reply->status != XCB_GRAB_STATUS_SUCCESS) && (count++ < 500)) { cookie = xcb_grab_keyboard(connection, 0, screen->root, XCB_CURRENT_TIME, XCB_GRAB_MODE_ASYNC, XCB_GRAB_MODE_ASYNC); reply = xcb_grab_keyboard_reply(connection, cookie, NULL); usleep(1000); } if (reply->status != XCB_GRAB_STATUS_SUCCESS) { fprintf(stderr, "Could not grab keyboard, status = %d\n", reply->status); exit(-1); } */ xcb_flush(connection); } int main () { /* Connect to X server */ connection = xcb_connect(NULL, NULL); if(connection == NULL) perror("Startup failed."); assert(connection); /* Setup signal handler so we can gracefully exit */ struct sigaction quit_sighandler, saved; quit_sighandler.sa_handler = &quit; sigaction(SIGINT, &quit_sighandler, &saved); /* Setup substructure redirection */ setup(); /* Set up communication with clients through a well known FIFO. */ #ifndef LOGGING_RELEASE write_to_log("Builing client FIFO.\n"); #endif char *server_endpoint = CLIENT_FIFO; mkfifo(server_endpoint, 0666); int server_endpoint_file = open(server_endpoint, O_RDONLY | O_NONBLOCK); #ifndef LOGGING_RELEASE write_to_log("Finished builing client FIFO.\n"); #endif ipc_info ipc; //ipc.fifo = server_endpoint_file; ipc.fifofd = server_endpoint_file; /* Note that there are several ways to do this. * Hootwm, which is credited in this source frequently, will poll instead. This is inefficient and uses * a lot of resources to constantly look for events occuring. Tinywm does it the correct way, but through xlib * instead of xcb. Herbstluftwm uses another approach where the client will actually connect to the display and * directly manipulate the environment. * * This pthread also doesn't exit, or shouldn't anyways. TODO: Make this detached. */ pthread_t input_handler; pthread_create(&input_handler, NULL, &handle_input, &ipc); int pid; char **args = NULL; char *start_loc = "/.config/scmwm/start"; char *env = getenv("HOME"); char *start = malloc(strlen(env) + strlen(start_loc)); strcat(start, env); strcat(start, start_loc); if (access(start, X_OK) == 0) { pid = Fork(); if(pid == 0){ if(execv(start, args) == -1) { free(start); #ifndef LOGGING_RELEASE write_to_log("Couldn't run start script\n"); #endif } exit(0); } } xcb_generic_event_t *ev; for (;;) { #ifndef LOGGING_RELEASE write_to_log("Handling event.\n"); #endif ev = xcb_wait_for_event(connection); handle_event(ev); #ifndef LOGGING_RELEASE write_to_log("Finished handling event.\n"); #endif } return 0; } <file_sep>// <NAME> - uname assignment for alsp // The options that are not included are kernel name, processor, and hardware platform // as this information is not provided in the utsname struct #include <sys/utsname.h> #include <stdio.h> #include <stdlib.h> #include <unistd.h> int print_all = 0; int print_osname = 0; int print_release = 0; int print_version = 0; int print_machine = 0; int print_nodename = 0; int processArgs(int argc, char* argv[]) { int c; while ((c = getopt(argc, argv, "aorvmn")) != -1) { switch (c) { case 'a': print_all = 1; return 0; case 'o': print_osname = 1; break; case 'r': print_release = 1; break; case 'v': print_version = 1; break; case 'm': print_machine = 1; break; case 'n': print_nodename = 1; break; default: printf("Unsupported argument, quitting\n"); return -1; } return 0; } } int main(int argc, char *argv[]) { struct utsname *buf = malloc(sizeof(struct utsname)); if(uname(buf) < 0) { printf("uname error\n"); exit(-1); } if(argc == 1) { printf("%s\n", buf->sysname); free(buf); exit(0); } if(processArgs(argc, argv) < 0) { printf("Arg error\n"); exit(-1); } if(print_all == 1) { printf("%s %s %s %s %s\n", buf->sysname, buf->nodename, buf->release, buf->version, buf->machine); } else { if(print_osname == 1) printf("%s", buf->sysname); if(print_nodename == 1) printf("%s", buf->nodename); if(print_release == 1) printf("%s", buf->release); if(print_version == 1) printf("%s", buf->version); if(print_machine == 1) printf("%s", buf->machine); printf("\n"); } free(buf); exit(0); }
40924b41cac2670df4bf56009e04c8c8be24f9fe
[ "Markdown", "C", "Makefile", "Shell" ]
18
C
GabMill/alsp
f276e90ae10a2788ad64ceecb6faa6d989b081e5
56945cfe4054bb4f6a2b016ab4cd3b4aa334c448
refs/heads/master
<repo_name>Phyxius/MMU-Simulator<file_sep>/Lab 3/MemoryReference.cs using System; using System.Collections.Generic; using System.Text; using System.Text.RegularExpressions; namespace Lab_3 { /// <summary> /// Reperesents a memory reference; usually corresponds to a single line a trace file. /// </summary> internal class MemoryReference { private readonly static Regex regex = new Regex(@"(?<pid>\d+) (?<type>[IWR]) (?<address>0x[0-9A-Fa-f]+)"); private readonly static Dictionary<string, MemoryAccessType> AccessTypeLookup = new Dictionary<string, MemoryAccessType>() { {"I", MemoryAccessType.InstructionFetch}, {"W", MemoryAccessType.Write}, {"R", MemoryAccessType.Read} }; public readonly uint PID; public readonly uint Address; public MemoryAccessType AccessType; public MemoryReference(uint pid, uint address, MemoryAccessType accessType) { PID = pid; Address = address; AccessType = accessType; } public static MemoryReference FromTraceLine(string traceLine) { var match = regex.Match(traceLine); if (!match.Success) throw new FormatException(traceLine); return new MemoryReference( uint.Parse(match.Groups["pid"].Value), Convert.ToUInt32(match.Groups["address"].Value, 16), AccessTypeLookup[match.Groups["type"].Value]); } } /// <summary> /// The types of memory accesses /// </summary> internal enum MemoryAccessType { Read, Write, InstructionFetch } /// <summary> /// The classes of memory accesses. /// Loads represent read operations, i.e. which do not set the 'dirty' flag /// on the corresponding page. /// Stores are write operations, i.e. which set the 'dirty' flag on the page. /// </summary> internal enum MemoryAccessClass { Load, Store } internal static class MemoryAccessTypeExtensions { /// <summary> /// Converts a specific memory access type to its corresponding class. /// </summary> /// <param name="type">This</param> /// <returns>The class of the operation</returns> internal static MemoryAccessClass GetAccessClass(this MemoryAccessType type) { switch(type) { case MemoryAccessType.Write: return MemoryAccessClass.Store; case MemoryAccessType.Read: case MemoryAccessType.InstructionFetch: return MemoryAccessClass.Load; default: throw new NotImplementedException(); } } /// <summary> /// Converts the memory access type to a friendly verb form for logging /// </summary> /// <param name="type">this</param> /// <returns>The friendly verb form</returns> internal static string GetFriendlyVerb(this MemoryAccessType type) { switch(type) { case MemoryAccessType.InstructionFetch: return "Instruction fetch from"; case MemoryAccessType.Read: return "Read from"; case MemoryAccessType.Write: return "Store to"; default: throw new NotImplementedException(); } } } } <file_sep>/Lab 3/Logger.cs using System; using System.IO; namespace Lab_3 { internal class Logger { public bool LoggingEnabled; public TextWriter Output = Console.Error; private void LogLine(string line) { if (!LoggingEnabled || Output == null) return; Output.WriteLine(line); } public void LogReference(uint pid, MemoryAccessType type, uint address, uint page, uint offset) { LogLine($"Process[{pid}]: {type.GetFriendlyVerb()} 0x{address.ToString("X")} (page: {page}, offset: {offset})"); } private void LogYesNo(string description, bool yesno, string prefix = "\t") => LogLine($"{prefix}{description}? {(yesno ? "yes" : "no")}"); public void LogTLBHit(bool hit) => LogYesNo("TLB hit", hit); public void LogPageFault(bool fault) => LogYesNo("Page fault", fault); public void LogTLBEviction(uint? evictedPage) { LogYesNo("TLB eviction", evictedPage != null); if (evictedPage != null) LogLine($"\tpage {evictedPage} evicted from TLB"); } public void LogMemoryEviction(PageTableInsertionResult? result) { LogYesNo("Main memory eviction", result != null); if (result != null) LogEvictedPage(result.Value.EvictedPagePID, result.Value.EvictedPageNumber, result.Value.EvictedPageDirty); } private void LogEvictedPage(uint pid, uint page, bool dirty) => LogLine( $"\tProcess {pid} page {page} ({(dirty ? "dirty" : "clean")}) evicted from memory"); public void LogPageFrame(uint page, uint frame) => LogLine($"\tpage {page} in frame {frame}"); } } <file_sep>/aux_files/vaddr_trace.cpp #include <stdio.h> #include "pin.H" int pid; FILE * trace; // Print a memory read record VOID MemRead(VOID * ip, VOID * addr) { fprintf(trace,"%6u R %p\n", pid, addr); } // Print a memory write record VOID MemWrite(VOID * ip, VOID * addr) { fprintf(trace,"%6u W %p\n", pid, addr); } VOID InstrFetch(VOID *ip) { fprintf(trace, "%6u I %p\n", pid, ip); } // Is called for every instruction and instruments reads and writes VOID Instruction(INS ins, VOID *v) { // Insert a call to printip before every instruction, and pass it the IP INS_InsertCall(ins, IPOINT_BEFORE, (AFUNPTR)InstrFetch, IARG_INST_PTR, IARG_END); // instruments loads using a predicated call, i.e. // the call happens iff the load will be actually executed // (this does not matter for ia32 but arm and ipf have predicated instructions) if (INS_IsMemoryRead(ins)) { INS_InsertPredicatedCall( ins, IPOINT_BEFORE, (AFUNPTR)MemRead, IARG_INST_PTR, IARG_MEMORYREAD_EA, IARG_END); } // instruments stores using a predicated call, i.e. // the call happens iff the store will be actually executed if (INS_IsMemoryWrite(ins)) { INS_InsertPredicatedCall( ins, IPOINT_BEFORE, (AFUNPTR)MemWrite, IARG_INST_PTR, IARG_MEMORYWRITE_EA, IARG_END); } } VOID Fini(INT32 code, VOID *v) { fprintf(trace, "#eof\n"); fclose(trace); } int main(int argc, char *argv[]) { pid = getpid(); PIN_Init(argc, argv); trace = fopen("pinatrace.out", "w"); // Register Instruction to be called to instrument instructions INS_AddInstrumentFunction(Instruction, 0); // Register Fini to be called when the application exits PIN_AddFiniFunction(Fini, 0); // Never returns PIN_StartProgram(); return 0; } <file_sep>/Lab 3/PageTable.cs using System; using System.Collections.Generic; using System.Linq; namespace Lab_3 { internal interface IPageTable { uint GetPageBits(); uint GetOffsetBits(); uint GetMaxFrames(); uint GetMemorySize(); uint GetMaxPages(); uint GetPageNumber(uint address); uint GetOffset(uint address); /// <summary> /// Looks up the given address in the page table, /// and (if found) returns the result of that lookup via a /// PageTableLookupResult. /// If not found (i.e. page not resident), returns null. /// </summary> /// <param name="address">The virtual address to look up</param> /// <param name="pid">The PID of the relevant process</param> /// <returns>The reseult of the lookup, or null if not found</returns> PageTableLookupResult? LookupAddress(uint address, uint pid); /// <summary> /// Sets the dirty flag on the page at the specified /// address/PID /// </summary> /// <param name="address">the address of the page</param> /// <param name="pid">the PID of the page</param> void SetPageDirty(uint address, uint pid); /// <summary> /// Inserts a page into the page table, including finding an open /// frame and evicting another page if necessary. /// </summary> /// <param name="address">The virtual address of the page to insert</param> /// <param name="pid">The PID of the owning process</param> /// <returns></returns> PageTableInsertionResult? InsertPage(uint address, uint pid); } internal class PageTable<T> : IPageTable { private readonly IPageReplacementPolicy<T> _replacementPolicy; private readonly Dictionary<PageTableKey, PageTableEntry<T>> _pageTable; private uint nextFreeFrame = 0; public readonly uint PageBits; public readonly uint OffsetBits; public readonly uint MaxFrames; public readonly uint MemorySize; public readonly uint MaxPages; public PageTable(IPageReplacementPolicy<T> replacementPolicy, uint memorySize, uint frameSize) { _pageTable = new Dictionary<PageTableKey, PageTableEntry<T>>(); _replacementPolicy = replacementPolicy; MaxFrames = memorySize / frameSize; OffsetBits = (uint)Math.Log(frameSize, 2); PageBits = (8 * sizeof(uint)) - OffsetBits; MemorySize = memorySize; MaxPages = (uint)1 << (int)PageBits; } public uint GetPageNumber(uint address) { return address >> (int)OffsetBits; } public uint GetOffset(uint address) { //(~0u) is a string of all 1's the size of a uint return ((~0u) >> (int)PageBits) & address; } public PageTableLookupResult? LookupAddress(uint address, uint pid) { var key = new PageTableKey { PageNumber = GetPageNumber(address), PID = pid }; if (!_pageTable.ContainsKey(key)) return null; TouchPage(key); return new PageTableLookupResult( GetPageNumber(address), _pageTable[key].FrameNumber, GetOffset(address)); } public void SetPageDirty(uint address, uint pid) { var key = new PageTableKey { PageNumber = GetPageNumber(address), PID = pid }; var page = _pageTable[key]; page.Dirty = true; _pageTable[key] = page; } public PageTableInsertionResult? InsertPage(uint address, uint pid) { var key = new PageTableKey { PageNumber = GetPageNumber(address), PID = pid }; var entry = new PageTableEntry<T>(); if (nextFreeFrame < MaxFrames) { entry.FrameNumber = nextFreeFrame; entry.ComparisonKey = _replacementPolicy.GetInitialKeyValue(); _pageTable[key] = entry; nextFreeFrame++; return null; } var evictedPage = _replacementPolicy.EvictPage( _pageTable.ToDictionary( pair => pair.Key, pair => pair.Value.ComparisonKey)); PageTableEntry<T> evictedEntry = _pageTable[evictedPage]; var evictedFrame = evictedEntry.FrameNumber; entry.FrameNumber = evictedFrame; entry.ComparisonKey = _replacementPolicy.GetInitialKeyValue(); _pageTable.Remove(evictedPage); _pageTable[key] = entry; return new PageTableInsertionResult(evictedPage.PageNumber, evictedPage.PID, evictedEntry.Dirty); } private void TouchPage(PageTableKey key) { var oldEntry = _pageTable[key]; oldEntry.ComparisonKey = _replacementPolicy.TouchPage(oldEntry.ComparisonKey); _pageTable[key] = oldEntry; } public uint GetPageBits() { return PageBits; } public uint GetOffsetBits() { return OffsetBits; } public uint GetMaxFrames() { return MaxFrames; } public uint GetMemorySize() { return MemorySize; } public uint GetMaxPages() { return MaxPages; } } /// <summary> /// The result of a page table lookup. /// Includes the page number looked up, the offset of the page, /// and the corresponding frame number /// </summary> internal struct PageTableLookupResult { public PageTableLookupResult(uint pageNumber, uint frameNumber, uint offset) { PageNumber = pageNumber; FrameNumber = frameNumber; Offset = offset; } public readonly uint PageNumber; public readonly uint FrameNumber; public readonly uint Offset; } /// <summary> /// The result of a page table insertion. /// Contains the evicted page's number, PID, and whether or not it was dirty. /// </summary> internal struct PageTableInsertionResult { public PageTableInsertionResult(uint evictedPageNumber, uint evictedPagePID, bool evictedPageDirty) { EvictedPageNumber = evictedPageNumber; EvictedPagePID = evictedPagePID; EvictedPageDirty = evictedPageDirty; } public readonly uint EvictedPageNumber; public readonly uint EvictedPagePID; public readonly bool EvictedPageDirty; } /// <summary> /// An entry in the page table. Contains both the PID of the process, /// and the address of the page. /// </summary> internal struct PageTableKey { /// <summary> /// The PID of the owning process /// </summary> public uint PID; /// <summary> /// The number of the page /// </summary> public uint PageNumber; } /// <summary> /// An entry in the page table. Contains a member indicating if the page is /// clean, and a type-variadic key used by the Page Replacement Policy /// to determine which pages to evict. /// </summary> /// <typeparam name="T">The type of the page replacement policy's key</typeparam> internal struct PageTableEntry<T> { /// <summary> /// True if the page is "dirty", i.e. has been written to /// </summary> public bool Dirty; /// <summary> /// The number of the corresponding phyiscal frame /// </summary> public uint FrameNumber; /// <summary> /// The key value used by the page replacement policy to decide /// which page to evict /// </summary> public T ComparisonKey; } /// <summary> /// Interface representing a page replacement policy for a Page Table. /// Each page has a key of type T that is created, updated, and used by /// the methods in the interface implementation to keep track of pages and /// determine which ones to evict when needed. /// </summary> /// <typeparam name="T">The type of the replacement policy's key</typeparam> internal interface IPageReplacementPolicy<T> { /// <summary> /// Update the key of a page, given the old one. /// </summary> /// <param name="prevKey">The previous key</param> /// <returns>The new key</returns> T TouchPage(T prevKey); /// <summary> /// Gets the initial value of a newly-created page's key /// </summary> /// <returns>The intial value of the key</returns> T GetInitialKeyValue(); /// <summary> /// Determines which page should be evicted based on the page-key mappings /// </summary> /// <param name="pages">The page-key mapping</param> /// <returns>Which page to evict</returns> PageTableKey EvictPage(Dictionary<PageTableKey, T> pages); } } <file_sep>/aux_files/README.md #`aux_files` This directory contains auxiliary files for the lab; in particular, [a memory trace generator](trace_gen.c) and the [lab assignment](lab3.pdf).<file_sep>/Lab 3/SettingsFile.cs using System; using System.Collections.Generic; using System.IO; using System.Text.RegularExpressions; using System.Linq; namespace Lab_3 { /// <summary> /// Loads a settings file based on the lab's specified format. /// </summary> internal static class SettingsFileLoader { private static readonly Regex SettingsValidationRegex = new Regex(@"(?<label>[a-z-]+): (?<value>\w+)"); private static readonly Dictionary<string, Settings.PageReplacementPolicies> PageReplacementPoliciesMapping; static SettingsFileLoader() { PageReplacementPoliciesMapping = new List<Settings.PageReplacementPolicies>( (Settings.PageReplacementPolicies[])Enum.GetValues(typeof(Settings.PageReplacementPolicies))) .ToDictionary(p => p.GetConfigName()); } /// <summary> /// Loads the settings from the file at the specified path. /// Throws FormatException for malformed settings files. /// </summary> /// <param name="path">The path of the file to load</param> /// <returns>The Settings object containing the loaded settings</returns> public static Settings LoadFromFile(string path) { var lines = File.ReadLines(path); var ret = new Settings(); foreach (var line in lines) { var match = SettingsValidationRegex.Match(line); if (match.Groups.Count < 2) throw new FormatException(line); string group = match.Groups["label"].Value; string value = match.Groups["value"].Value; switch (group) { case "physical-memory-size": ret.PhysicalMemorySize = uint.Parse(value); break; case "frame-size": ret.FrameSize = uint.Parse(value); break; case "memory-latency": ret.MemoryLatency = uint.Parse(value); break; case "page-replacement": ret.PageReplacementPolicy = PageReplacementPoliciesMapping[value]; break; case "tlb-size": ret.TLBSize = uint.Parse(value); break; case "tlb-latency": ret.TLBLatency = uint.Parse(value); break; case "disk-latency": ret.DiskLatency = uint.Parse(value); break; case "logging-output": ret.LoggingOutput = value == "on" ? true : value == "off" ? false : throw new FormatException(); break; } } return ret; } } internal static class PageReplacementPoliciesMethods { /// <summary> /// Gets the name of the policy as used in the settings file /// </summary> /// <param name="policy">this</param> /// <returns>The settings file name of the policy</returns> public static string GetConfigName(this Settings.PageReplacementPolicies policy) { return policy.ToString().ToUpper(); } } /// <summary> /// Represents the configurable options specifiable in the settings files. /// </summary> internal struct Settings { public const decimal MilliToNanoRatio = 1000000m; internal enum PageReplacementPolicies { Random, LRU, MRU, LFU, FIFO, MFU } public uint PhysicalMemorySize; public uint FrameSize; public uint MemoryLatency; public decimal MemoryLatencyMS { get { return MemoryLatency / MilliToNanoRatio; } } public uint TLBSize; public uint TLBLatency; public decimal TLBLatencyMS { get { return TLBLatency / MilliToNanoRatio; } } public uint DiskLatency; public bool LoggingOutput; public PageReplacementPolicies PageReplacementPolicy; } } <file_sep>/Lab 3/ProcessInfo.cs namespace Lab_3 { internal class ProcessInfo { public uint TotalMemoryReferences; public uint TLBMisses; public uint PageFaults; public uint CleanEvictions; public uint DirtyEvictions; public decimal TotalEvictions { get { return CleanEvictions + DirtyEvictions; } } public decimal PercentageDirtyEvictions { get { if (TotalEvictions == 0) return 0; return DirtyEvictions / TotalEvictions * 100; } } public static ProcessInfo operator +(ProcessInfo left, ProcessInfo right) { return new ProcessInfo { TotalMemoryReferences = left.TotalMemoryReferences + right.TotalMemoryReferences, TLBMisses = left.TLBMisses + right.TLBMisses, PageFaults = left.PageFaults + right.PageFaults, CleanEvictions = left.CleanEvictions + right.CleanEvictions, DirtyEvictions = left.DirtyEvictions + right.DirtyEvictions }; } } } <file_sep>/Lab 3/PageReplacementPolicies.cs using System; using System.Collections.Generic; using System.Linq; namespace Lab_3.PageReplacementPolicies { /// <summary> /// Helper class for "Most 'x' Page" based replacement policies /// Automatically finds the most 'x' and returns it in EvictPage using /// the natural ordering /// </summary> /// <typeparam name="T">The type of the comparison key to use</typeparam> internal abstract class MostPageReplacementPolicy<T> : IPageReplacementPolicy<T> where T : IComparable<T> { public PageTableKey EvictPage(Dictionary<PageTableKey, T > pages) { return pages .OrderByDescending(pair => pair.Value) .Select(pair => pair.Key) .First(); } public abstract T GetInitialKeyValue(); public abstract T TouchPage(T prevKey); } /// <summary> /// Helper class for "Least 'x' Page" based replacement policies /// Automatically finds the least 'x' and returns it in EvictPage using /// the natural ordering /// </summary> /// <typeparam name="T">The type of the comparison key to use</typeparam> internal abstract class LeastPageReplacementPolicy<T> : IPageReplacementPolicy<T> where T : IComparable<T> { public PageTableKey EvictPage(Dictionary<PageTableKey, T> pages) { return pages .OrderBy(pair => pair.Value) .Select(pair => pair.Key) .First(); } public abstract T GetInitialKeyValue(); public abstract T TouchPage(T prevKey); } /// <summary> /// Random page eviction policy. /// Key always returns null /// </summary> internal class Random : IPageReplacementPolicy<Object> { private readonly System.Random _r = new System.Random(); public PageTableKey EvictPage(Dictionary<PageTableKey, object> pages) { return pages.Keys.ToList()[_r.Next(pages.Keys.Count)]; } public object GetInitialKeyValue() { return null; } public object TouchPage(object prevKey) { return prevKey; } } /// <summary> /// Evicts the most frequently used pages /// </summary> internal class MostFrequentlyUsed : MostPageReplacementPolicy<uint> { public override uint GetInitialKeyValue() { return 0; } public override uint TouchPage(uint prevKey) { return prevKey + 1; } } /// <summary> /// Evicts the least frequently used pages /// </summary> internal class LeastFrequentlyUsed : LeastPageReplacementPolicy<uint> { public override uint GetInitialKeyValue() { return 0; } public override uint TouchPage(uint prevKey) { return prevKey + 1; } } /// <summary> /// Evicts the oldest pages /// </summary> internal class FIFO : LeastPageReplacementPolicy<uint> { private uint _pageCounter = 0; public override uint GetInitialKeyValue() { return _pageCounter++; } public override uint TouchPage(uint prevKey) { return prevKey; } } /// <summary> /// Evicts the least recently used pages /// </summary> internal class LeastRecentlyUsed : LeastPageReplacementPolicy<uint> { private uint _counter = 0; public override uint GetInitialKeyValue() { return _counter++; } public override uint TouchPage(uint prevKey) { return _counter++; } } /// <summary> /// Evicts the most recently used pages /// </summary> internal class MostRecentlyUsed : MostPageReplacementPolicy<uint> { private uint _counter = 0; public override uint GetInitialKeyValue() { return _counter++; } public override uint TouchPage(uint prevKey) { return _counter++; } } } <file_sep>/aux_files/trace_gen.c #include <stdio.h> #include <stdlib.h> #include <getopt.h> unsigned int num_references; unsigned int mem_stride; unsigned int num_procs; unsigned int max_proc_size; unsigned int slice; float rw_ratio; char * ref_pattern; void proc_args( int iargc, char ** iargv ); void generate_write_ref(); void generate_read_ref(); typedef struct{ int id; unsigned int last_ref; } proc_t; int main( int argc, char ** argv ) { unsigned int i, nreads=0, nwrites=0, cur_idx, addr; float f; char op; proc_t * procs, * p; srand48( 5 ); srand( 5 ); proc_args( argc, argv ); fprintf(stderr, "Number of references: %u\n", num_references ); fprintf(stderr, "Number of processes: %u\n", num_procs ); fprintf(stderr, "Maximum process size: %u\n", max_proc_size ); fprintf(stderr, "Memory reference pattern: %s ", ref_pattern ); if( strcmp(ref_pattern, "sequential") == 0 ) { fprintf(stderr, "(%u byte stride)", mem_stride ); } fprintf(stderr, "\nR/W ratio: %.2f\n", rw_ratio ); procs = (proc_t *)malloc( num_procs * sizeof(proc_t ) ); for( i=0; i<num_procs; i++ ) { procs[i].id = i; procs[i].last_ref = 0; } cur_idx = 0; for( i=0; i < num_references; i++ ) { if( i % slice == 0 ) { cur_idx = (cur_idx+1) % num_procs; p = &(procs[ cur_idx ]); } f = drand48(); if( f < rw_ratio ) { nreads++; op='R'; } else{ nwrites++; op='W'; } if( strcmp( ref_pattern, "random" ) == 0 ) { addr = (2 * rand()) % max_proc_size ; } else{ addr = (p->last_ref + mem_stride ) % max_proc_size ; } p->last_ref = addr; fprintf( stdout, "%u %c 0x%x\n", p->id, op, addr ); } //fprintf(stderr, "nreads: %u, nwrites: %u, r/w ratio: %.2f\n", nreads, nwrites, ((float)nreads)/(nreads+nwrites) ); return 0; } void proc_args( int iargc, char ** iargv ) { static struct option long_options[] = { {"num-references", 1, NULL, 'r'}, {"num-processes", 1, NULL, 'p'}, {"max-process-size", 1, NULL, 'm'}, {"reference-pattern", 1, NULL, 'f'}, {"rw-ratio", 1, NULL, 'a'}, {"mem-stride", 1, NULL, 's'}, {"time-slice", 1, NULL, 't'}, {0, 0, 0, 0} }; int option_index = 0; int c; unsigned int tmp_stride; ref_pattern = "sequential"; rw_ratio = 0.6; num_references = 1000000; mem_stride = 1024; num_procs = 5; max_proc_size = 1024*1024*1024; slice = 10000; while ( 1 ) { c = getopt_long ( iargc, iargv, "f:a:p:r:s:m:t:", long_options, &option_index ); if (c == -1) break; switch (c) { case 'f': ref_pattern = optarg; if( strcmp( ref_pattern, "sequential" ) != 0 && strcmp( ref_pattern, "random" ) != 0 ) { fprintf( stderr, "Error: reference-pattern must be \"sequential\" or \"random\"\n"); exit( -1 ); } break; case 'a': rw_ratio = atof( optarg ); break; case 'p': num_procs = atoi( optarg ); break; case 't': slice = atoi( optarg ); break; case 'r': num_references = atoi( optarg ); break; case 'm': max_proc_size = atoi( optarg ); /* tmp_stride = max_proc_size; while( tmp_stride > 1 ){ if(tmp_stride % 2 != 0 ){ fprintf(stderr, "maximum process size: %u must be a power of 2\n", max_proc_size); exit(-1); } tmp_stride /= 2; } */ break; case 's': mem_stride = atoi( optarg ); /* tmp_stride = mem_stride; while( tmp_stride > 1 ){ if(tmp_stride % 2 != 0 ){ fprintf(stderr, "memory stride: %u must be a power of 2\n", mem_stride); exit(-1); } tmp_stride /= 2; } */ break; default: break; } } } <file_sep>/Lab 3/TranslationLookasideBuffer.cs using System.Collections.Generic; using System.Linq; namespace Lab_3 { internal interface ITranslationLookasideBuffer { /// <summary> /// Looks up an entry in the TLB /// </summary> /// <param name="virtualAddress">the virtual address to lookup</param> /// <returns>the physical address corresponding to the given virtual address, or null if not present</returns> uint? LookupEntry(uint virtualAddress); /// <summary> /// Adds an entry to the TLB, possibly evicting and returning another entry /// </summary> /// <param name="virtualAddress">The virtual address to add</param> /// <param name="physicalAddress">The corresponding physical address</param> /// <returns>The evicted address, or null if no entry was evicted</returns> uint? AddEntry(uint virtualAddress, uint physicalAddress); void Flush(); } /// <summary> /// Implements a translation lookaside buffer using a Least-Recently-Used /// page replacement policy /// </summary> internal class LRUTranslationLookasideBuffer : ITranslationLookasideBuffer { private class TLBEntry { public uint Timestep; public readonly uint PhysicalAddress; public TLBEntry(uint timestep, uint physicalAddress) { Timestep = timestep; PhysicalAddress = physicalAddress; } } private uint _timestep; public readonly uint Size; private readonly Dictionary<uint, TLBEntry> _tlb = new Dictionary<uint, TLBEntry>(); public LRUTranslationLookasideBuffer(uint size) { Size = size; } public void Flush() { _tlb.Clear(); _timestep = 0; } public uint? LookupEntry(uint virtualAddress) { if (Size == 0) return null; if (!_tlb.ContainsKey(virtualAddress)) { return null; } _timestep++; _tlb[virtualAddress].Timestep = _timestep; return _tlb[virtualAddress].PhysicalAddress; } public uint? AddEntry(uint virtualAddress, uint physicalAddress) { if (Size == 0) return null; _tlb[virtualAddress] = new TLBEntry(physicalAddress, _timestep); _timestep++; if (_tlb.Count <= Size) return null; var evictedKey = _tlb.OrderBy(pair => pair.Key).First().Key; _tlb.Remove(evictedKey); return evictedKey; } } } <file_sep>/Lab 3/Program.cs using System; using System.Collections.Generic; using System.IO; using System.Linq; namespace Lab_3 { public class Program { public static void Main(string[] args) { if (args.Length != 2) { Console.Error.WriteLine("Usage: mmu config_file trace_file"); Environment.Exit(1); } var settings = SettingsFileLoader.LoadFromFile(args[0]); var tlb = new LRUTranslationLookasideBuffer(settings.TLBSize); var pageTable = CreatePageTable(settings); var logger = new Logger { LoggingEnabled = settings.LoggingOutput }; PrintPreSimulationOutput(settings, pageTable); decimal totalLatencyMS = 0; uint totalMemoryAccesses = 0; uint previousPID = 0; var processes = new Dictionary<uint, ProcessInfo>(); var trace = File.ReadLines(args[1]) .Select(MemoryReference.FromTraceLine); foreach (var m in trace) { totalMemoryAccesses++; if (!processes.ContainsKey(m.PID)) processes[m.PID] = new ProcessInfo(); processes[m.PID].TotalMemoryReferences++; if (m.PID != previousPID) tlb.Flush(); previousPID = m.PID; uint pageNumber = pageTable.GetPageNumber(m.Address); logger.LogReference(m.PID, m.AccessType, m.Address, pageNumber, pageTable.GetOffset(m.Address)); totalLatencyMS += settings.TLBLatencyMS; uint? tlbResult = tlb.LookupEntry(pageNumber); logger.LogTLBHit(tlbResult != null); if (tlbResult != null) { logger.LogPageFrame(pageNumber, tlbResult.Value); continue; } processes[m.PID].TLBMisses++; var lookupResult = pageTable.LookupAddress(m.Address, m.PID); totalLatencyMS += settings.MemoryLatencyMS; logger.LogPageFault(lookupResult != null); uint? tlbInsertionResult; if (lookupResult != null) { if (m.AccessType.GetAccessClass() == MemoryAccessClass.Store) pageTable.SetPageDirty(m.Address, m.PID); totalLatencyMS += settings.TLBLatencyMS; tlbInsertionResult = tlb.AddEntry(pageNumber, lookupResult.Value.FrameNumber); logger.LogTLBEviction(tlbInsertionResult); logger.LogPageFrame(lookupResult.Value.PageNumber, lookupResult.Value.FrameNumber); continue; } processes[m.PID].PageFaults++; totalLatencyMS += settings.MemoryLatency + settings.DiskLatency; var pageInsertionResult = pageTable.InsertPage(m.Address, m.PID); logger.LogMemoryEviction(pageInsertionResult); if (pageInsertionResult != null) { if (pageInsertionResult.Value.EvictedPageDirty) totalLatencyMS += settings.DiskLatency; if (pageInsertionResult.Value.EvictedPageDirty) processes[m.PID].DirtyEvictions++; else processes[m.PID].CleanEvictions++; } lookupResult = pageTable.LookupAddress(m.Address, m.PID); if (m.AccessType.GetAccessClass() == MemoryAccessClass.Store) pageTable.SetPageDirty(m.Address, m.PID); totalLatencyMS += settings.TLBLatencyMS; tlbInsertionResult = tlb.AddEntry(pageNumber, lookupResult.Value.FrameNumber); logger.LogTLBEviction(tlbInsertionResult); logger.LogPageFrame(lookupResult.Value.PageNumber, lookupResult.Value.FrameNumber); } PrintPostSimulationOutput(totalLatencyMS, totalMemoryAccesses, settings.MemoryLatencyMS, processes); } private static void PrintPreSimulationOutput(Settings s, IPageTable p) { Console.WriteLine($"Page bits: {p.GetPageBits()}"); Console.WriteLine($"Offset bits: {p.GetOffsetBits()}"); Console.WriteLine($"TLB size: {s.TLBSize}"); Console.WriteLine($"TLB latency (milliseconds): {s.TLBLatencyMS.ToString("0.000000")}"); Console.WriteLine($"Physical memory (bytes): {s.PhysicalMemorySize}"); Console.WriteLine($"Physical frame size (bytes) {s.FrameSize}"); Console.WriteLine($"Number of physical frames: {p.GetMaxFrames()}"); Console.WriteLine($"Memory latency (milliseconds): {s.MemoryLatencyMS.ToString("0.000000")}"); Console.WriteLine($"Number of page table entries: {p.GetMaxPages()}"); Console.WriteLine($"Page replacement strategy: {s.PageReplacementPolicy.GetConfigName()}"); Console.WriteLine($"Disk latency (milliseconds): {s.DiskLatency.ToString("0.00")}"); Console.WriteLine($"Logging: {(s.LoggingOutput ? "on" : "off")}"); } private static void PrintPostSimulationOutput(decimal overallLatencyMS, uint totalAccesses, decimal memoryLatencyMS, Dictionary<uint, ProcessInfo> processes) { Console.WriteLine($"Overall latency (milliseconds): {overallLatencyMS.ToString("0.000000")}."); decimal averageLatency = overallLatencyMS / totalAccesses; Console.WriteLine($"Average memory access latency (milliseconds/reference): {averageLatency.ToString("0.000000")}."); Console.WriteLine($"Slowdown: {averageLatency / memoryLatencyMS}"); PrintProcessInfo(null, processes.Values.Aggregate((l,r) => l + r)); foreach (var pid in processes.Keys.OrderBy(pid => pid)) PrintProcessInfo(pid, processes[pid]); } private static void PrintProcessInfo(uint? pid, ProcessInfo info) { Console.WriteLine(pid == null ? "Overall" : $"Process {pid.Value}"); Console.WriteLine($"\tMemory references: {info.TotalMemoryReferences}"); Console.WriteLine($"\tTLB misses: {info.TLBMisses}"); Console.WriteLine($"\tPage faults: {info.PageFaults}"); Console.WriteLine($"\tClean evictions: {info.CleanEvictions}"); Console.WriteLine($"\tDirty evictions: {info.DirtyEvictions}"); Console.WriteLine($"Percentage dirty evictions: {info.PercentageDirtyEvictions.ToString("0.00")}%"); } private static IPageTable CreatePageTable(Settings s) { uint memorySize = s.PhysicalMemorySize; uint frameSize = s.FrameSize; switch (s.PageReplacementPolicy) { case Settings.PageReplacementPolicies.FIFO: return new PageTable<uint>(new PageReplacementPolicies.FIFO(), memorySize, frameSize); case Settings.PageReplacementPolicies.LRU: return new PageTable<uint>(new PageReplacementPolicies.LeastRecentlyUsed(), memorySize, frameSize); case Settings.PageReplacementPolicies.LFU: return new PageTable<uint>(new PageReplacementPolicies.LeastFrequentlyUsed(), memorySize, frameSize); case Settings.PageReplacementPolicies.MFU: return new PageTable<uint>(new PageReplacementPolicies.MostFrequentlyUsed(), memorySize, frameSize); case Settings.PageReplacementPolicies.MRU: return new PageTable<uint>(new PageReplacementPolicies.MostRecentlyUsed(), memorySize, frameSize); case Settings.PageReplacementPolicies.Random: return new PageTable<object>(new PageReplacementPolicies.Random(), memorySize, frameSize); default: throw new NotImplementedException(s.PageReplacementPolicy.ToString()); } } } }<file_sep>/README.md # MMU Simulator This project is a Memory Management Unit (MMU) simulator, written as a programming lab for CS481 (Operating Systems). It simulates a 32-bit MMU with a 1 layer fully associative Translation Lookaside Buffer, complete with detailed access times and per-operation tracing. It uses `valgrind` memory traces as inputs. See [the lab assignment](aux_files/lab3.pdf) for details.
79359b762c4004cec458528702dd77b01d1d8e30
[ "Markdown", "C#", "C", "C++" ]
12
C#
Phyxius/MMU-Simulator
39d25db1cfd18189cdc0ba0e079335e99b5113c6
da90f69f084d1d03f814d527ee4d716580761917
refs/heads/master
<repo_name>MrPrimate/aws_role_keys<file_sep>/lib/aws_role_creds.rb require 'aws-sdk' require 'yaml' require 'time' require 'inifile' require 'fileutils' IN_FILE = "#{ENV['HOME']}/.aws/config.yaml" # The config file we write out CONFIG_OUT_FILE = "#{ENV['HOME']}/.aws/config" CREDENTIALS_OUT_FILE = "#{ENV['HOME']}/.aws/credentials" SESSION_CREDS_FILE = "#{ENV['HOME']}/.aws/session.yaml" SESSION_DURATION = 86400 ROLE_DURATION = 3600 REGION = 'eu-west-1' class AwsRoleCreds # Options hash should be: # config_in_file # config_out_file # credentials_out_file # logger def initialize( options ) @log = options[:logger] or Logger.new( STDERR ) if File.exists?( options[:config_in_file] ) @config = YAML::load( File.open( options[:config_in_file] ) ) else @log.error "Please create a yaml config file in #{options[:config_in_file]}" exit!(1) end if File.exists?(SESSION_CREDS_FILE) @session_credentials = YAML::load( File.open( SESSION_CREDS_FILE ) ) || {} else @session_credentials = {} end @role_credentials = {} @config_out_file = options[:config_out_file] || CONFIG_OUT_FILE @credentials_out_file = options[:credentials_out_file] || CREDENTIALS_OUT_FILE end attr :session_credentials attr :role_credentials attr :config_out_file attr :credentials_out_file attr :config def run() self.generate self.save end def generate() # Get session credentials for each 'master' account @config['default'].each do |p| name = p['name'] region = p['region'] || REGION duration = p['duration'] || SESSION_DURATION if @session_credentials.key?(name) next if @session_credentials[name]['expiration'] > Time.now end if p['id'] and p['key'] client = Aws::STS::Client.new( access_key_id: p['id'], secret_access_key: p['key'], region: region ) else client = Aws::STS::Client.new(region: region) end if p['mfa_arn'] puts "Enter MFA token code for #{name} using #{p['mfa_arn']}" token = gets session_credentials = client.get_session_token( duration_seconds: duration, serial_number: p['mfa_arn'], token_code: token.chomp ) else session_credentials = client.get_session_token( duration_seconds: duration ) end @session_credentials[name] = { 'access_key_id' => session_credentials.credentials.access_key_id, 'secret_access_key' => session_credentials.credentials.secret_access_key, 'session_token' => session_credentials.credentials.session_token, 'expiration' => session_credentials.credentials.expiration, 'region' => region } end # Cache session credentials File.open( SESSION_CREDS_FILE, 'w' ) { |f| f.write @session_credentials.to_yaml } # For each role we want to assume grab some assumed credentials using approriate session @config['profiles'].each do |p| name = p['name'] default = p['default'] region = p['region'] || REGION duration = p['duration'] || ROLE_DURATION session_credentials = @session_credentials[default] @log.debug "Getting credentials for #{name} using #{p['role_arn']}" client = Aws::STS::Client.new( access_key_id: session_credentials['access_key_id'], secret_access_key: session_credentials['secret_access_key'], session_token: session_credentials['session_token'], region: region ) role_credentials = client.assume_role( role_arn: p['role_arn'], role_session_name: name, duration_seconds: duration, ) @role_credentials[name] = { 'role' => p['role_arn'], 'access_key_id' => role_credentials.credentials.access_key_id, 'secret_access_key' => role_credentials.credentials.secret_access_key, 'session_token' => role_credentials.credentials.session_token, 'expiration' => role_credentials.credentials.expiration, 'region' => region } end end def save() # Write out config file # first make a backup FileUtils.cp( config_out_file, "#{config_out_file}.backup" ) FileUtils.cp( credentials_out_file, "#{credentials_out_file}.backup" ) # create a new ini file object config = IniFile.new config.filename = config_out_file credentials = IniFile.new credentials.filename = credentials_out_file config['default'] = { "region" => REGION } # set properties @session_credentials.each do |k, c| profile = { "aws_access_key_id" => "#{c['access_key_id']}", "aws_secret_access_key" => "#{c['secret_access_key']}", "aws_session_token" => "#{c['session_token']}", "region" => "#{c['region']}", } config["profile #{k}"] = profile credentials["#{k}"] = profile end @role_credentials.each do |k, c| profile = { "aws_access_key_id" => "#{c['access_key_id']}", "aws_secret_access_key" => "#{c['secret_access_key']}", "aws_session_token" => "#{c['session_token']}", "region" => "#{c['region']}", } config["profile #{k}"] = profile credentials["#{k}"] = profile end exist_optional_configs = [ 'region', 'mfa_serial', 'role_arn', 'source_profile', 'external_id', 'role_session_name', ] @config['exists'].each do |p| profile = { "aws_access_key_id" => "#{p['id']}", "aws_secret_access_key" => "#{p['key']}", } exist_optional_configs.each do |i| profile[i] = p[i] if p.key?(i) end config["profile #{p['name']}"] = profile credentials["#{p['name']}"] = profile end # save file config.write() @log.debug "#{config_out_file} updated" credentials.write() @log.debug "#{credentials_out_file} updated" end end <file_sep>/README.md # AwsRoleCreds *PLEASE DON'T USE THIS, CONSIDER aws-vault* Have several AWS accounts that you access through delegation? Want a id/key combo for each one? Need to use MFA? But want to use the cli? It can get frustrating managing so many accounts. If you have one (or even more) 'master' account that you assume roles in other accounts then this script will handle generating profiles and temporary session credentials, and keeping your MFA logins to a minimum. You might also be interested in [aws-assume-role](https://github.com/scalefactory/aws-assume-role) to store credentials securely in Gnome or OSX Keychain. ## Installation Install with $ gem install aws_role_creds ## Usage Create a YAML file to manage your profiles, and MFA device, at `~/.aws/config.yaml` ``` --- default: - name: id: key: mfa_arn: (optional) region: (optional) profiles: - name: role_arn: region: (optional) default: default profile to use exists: - name: id: key: mfa_serial: (optional) region: (optional) role_arn: (optional) source_profile: (optional) external_id: (optional) role_session_name: (optional) ``` Run `aws_role_creds` and it will get credentials for your default accounts. It will then use these credentials to Assume Roles and get credentials for each of your profiles. Default accounts get creds lasting 24 hours, and assumed role profiles can last an hour. If your credentials expire, run the script again and it will refresh them. It will ask for you MFA if its required, i.e. your session credentials have expired. Any `exists` items are added to the credentials and config file as is, no role stuff will happen to them. These correspond to the names [here](https://docs.aws.amazon.com/cli/latest/topic/config-vars.html#using-aws-iam-roles). ## Development After checking out the repo, run `bin/setup` to install dependencies. 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). ## Contributing Bug reports and pull requests are welcome on GitHub at https://github.com/MrPrimate/aws_role_creds. ## License The gem is available as open source under the terms of the [MIT License](http://opensource.org/licenses/MIT). <file_sep>/bin/aws_role_creds #!/usr/bin/env ruby require 'optparse' require 'logger' require 'aws_role_creds' options = {} optparse = OptionParser.new do |opts| options[:in_config] = "#{ENV['HOME']}/.aws/config.yaml" opts.on('-c', '--config file', 'Config file.') do |c| options[:config] = c end options[:out_config] = "#{ENV['HOME']}/.aws/config" opts.on('--out-config file', 'AWS config file to use') do |c| options[:out_config] = c end options[:cred_config] = "#{ENV['HOME']}/.aws/credentials" opts.on('--credentials-out file', 'AWS credentials file to use') do |c| options[:cred_config] = c end options[:debug] = false opts.on('-d', '--debug', 'Enable debugging') do options[:debug] = true end end optparse.parse! log = Logger.new(STDERR) if options[:debug] log.level = Logger::DEBUG else log.level = Logger::INFO end arc = AwsRoleCreds.new( :config_in_file => options[:in_config], :config_out_file => options[:out_config], :credentials_out_file => options[:cred_config], :logger => log) arc.run() <file_sep>/aws_role_creds.gemspec # coding: utf-8 lib = File.expand_path('../lib', __FILE__) $LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib) Gem::Specification.new do |spec| spec.name = "aws_role_creds" spec.version = "0.0.6" spec.authors = ["<NAME>"] spec.email = ["<EMAIL>"] spec.description = %q{Used to fetch multiple AWS Role Credential Keys using different Session Keys} spec.summary = %q{Manage AWS STS credentials with MFA} spec.homepage = "https://github.com/MrPrimate/aws_role_keys" spec.license = "MIT" spec.files = `git ls-files -z`.split("\x0").reject { |f| f.match(%r{^(test|spec|features)/}) } spec.bindir = "bin" spec.executables = spec.files.grep(%r{^bin/aws}) { |f| File.basename(f) } spec.require_paths = ["lib"] spec.add_runtime_dependency "aws-sdk" spec.add_runtime_dependency "inifile" spec.add_development_dependency "bundler", "~> 1.12" spec.add_development_dependency "rake", "~> 10.0" end
676ac23ccadb2e426e0872b3f14aad5285e367b1
[ "Markdown", "Ruby" ]
4
Ruby
MrPrimate/aws_role_keys
cd7d37089f79f1306b43db2187749671526d492a
b1a60e0cac602e755a5b3f9e2946061a3cb1032b
refs/heads/master
<repo_name>gomel-tdl1/blockchain-samples<file_sep>/raffle/README.md # Raffle game ## Description Kind of a Raffle lottery game. <br/> Some requirements/assumptions: - a user should deposit ERC20 tokens to have a higher chance to win; - all the ERC20 tokens and fees collected will become a prize for a winner later on; - chance to win = ETH equality of ERC20 tokens a player has deposited to the game vs the sum of all the tokens deposited to the game; - Token/ETH price should be fetched via oracle; - the wheel is rolled manually (requires an admin panel or a background service on a server, has some trade-offs); - when the wheel is rolled, gameStatus becomes "Rolling", so that no one was able to deposit or roll the wheel; - two ways of generating a random number: - manual, via manual input of a 'random' number (`function rollTheDice(uint256 randomNumber)`); - via randomness oracle (`function rollTheDice()`); - when a valid random number is found, sumOfUsersChances is calculated. To find a winner, the game simply summs personalChances one by one, until the number reaches (`randomNumber % sumOfUsersChances`); - when a winner is found, accumulated fee and all the tokens are assigned to a winner; - the winner needs to manually withdraw its tokens (to avoid some vulnerabilities); - when tokens are re-assigned, the game is open to play again. Example. <br/> User deposits 1 LINK to the game. LINK / ETH = 0.008, fee applied = 0.0001 ETH, personalChanceToWin = 0.008 ETH. <br/> User additionally deposits 1 BNB. BNB / ETH 0.12, fee applied = 0.0001 ETH, personalChanceToWin = 0.128 ETH. <br/> Other users deposit coins for 5 ETH in sum. Final chanceToWin for our user is 0.128 / 5 = 0.0256, what is 2.56%. Final value of tokens = 5 ETH + fee * numberOfDeposits. <br/> <br/> Further notes. - Randomness oracle. Chainlink randomness oracle asks for 2 LINK per request to run on ETH Mainnet, what is not so cheap. To make it cheaper, a separate contract might be created, which will collect requests for randomness (example in milestone [99c6fe8](https://github.com/artem-bayandin/blockchain-samples/commit/99c6fe8fa48f71540510fbe165a3ae545dd35ea7) - [ChainlinkRandomnessOracle](https://github.com/artem-bayandin/blockchain-samples/blob/99c6fe8fa48f71540510fbe165a3ae545dd35ea7/raffle/contracts/RandomnessOracle.sol)). Then some web service will query this contract against new requests received, and if any found, then web service will fill these requests with random values. - Price oracle. Current chainlink price oracle is abstracted with an interface, but is limited by the number of proxies for tokens and just ETH, Kovan and Rinkeby networks. It'd be nice to implement IPriceOracle for at least Uniswap, 1inch. ## Release increments ### milestone [d4503c6](https://github.com/artem-bayandin/blockchain-samples/commit/d4503c63119c2e5f5f601d2b9430e8f272b097e2) - samples of tests for `deposit()` were added (validates amounts of tokens deposited, and collected fee); - RaffleExtended contract was extracted from Raffle not to pollute Raffle with getters/setters for tests; - interfaces and implementations of oracles were split into separate files. Notes. Most likely, there will be a pause in development after this milestone, as all the major practices are implemented. To the moment, game contracts contain around 1k lines of code, plus test files contain another 1k lines of code. ### milestone [99c6fe8](https://github.com/artem-bayandin/blockchain-samples/commit/99c6fe8fa48f71540510fbe165a3ae545dd35ea7) _An outstanding milestone: Raffle game contract is from now abstracted from oracles, both price oracle and randomness oracle via its interfaces, what makes it easy to implemented a new oracle and switch the game to a new address. And all you need - just implement oracles as [IPriceOracle](https://github.com/artem-bayandin/blockchain-samples/blob/99c6fe8fa48f71540510fbe165a3ae545dd35ea7/raffle/contracts/PriceOracle.sol) and [IRandomnessOracle](https://github.com/artem-bayandin/blockchain-samples/blob/99c6fe8fa48f71540510fbe165a3ae545dd35ea7/raffle/contracts/RandomnessOracle.sol), and for randomness Raffle needs to implement [IRandomnessReceiver](https://github.com/artem-bayandin/blockchain-samples/blob/99c6fe8fa48f71540510fbe165a3ae545dd35ea7/raffle/contracts/RandomnessOracle.sol), as its functions are called when a number is generated._ <br/> <br/> Migration file was updated. Test environment setup was updated. `truffle compile` succeeds. `truffle migrate --network development [--reset]` succeeds. `truffle test --network devtest` succeeds. <br/> <br/> Next to do: code tests, refactor contracts if needed. ### milestone [a900a1f](https://github.com/artem-bayandin/blockchain-samples/commit/a900a1f1b1230b6f896e4f7f2a5534b0b3df79d4) Improved: - obsolete Raffle3.sol file was deleted; - added test mocks for erc20 tokens; - added test mocks for chainlink price oracles; - migration migrates (`truffle migrate --network development --reset`) - environment for tests is done (`truffle test --network devtest`) (does not include open issue with mocking randomizer) Next: - extract interfaces and create an abstraction over chainlink randomizer, so that it could be possible to switch and/or mock a randomizer; - tests. ### milestone [492018f](https://github.com/artem-bayandin/blockchain-samples/commit/492018f92d33e8eb6c526953753acfed4da9b48a) - [done] added `withdraw` functionality for a winner; - [done] refactored rolling the wheel, so that manually it'll require 2 steps: a) set the game status to 'rolling'; b) input 'random' number and trigger selection of a winner; - [done] created a custom ERC20 token to be able to test the code; - [almost] refactored roles (move method locks into Adminable.sol); ### milestone [407967a](https://github.com/artem-bayandin/blockchain-samples/commit/407967af9e59f8cb3a1bef8448776fa6e21dc76c) Chainlink data providers refactored: - two oracles are prepared for EHT Mainnet and Rankeby Testnet; - it's now possible to add a chainlink proxy address for a token; - Token-ETH value is now calculated right; - Rankeby price oracle successfully tested on Rankeby. Next steps: - add `withdraw` functionality for a winner; - refactor rolling the wheel, so that manually it'll require 2 steps: a) set the game status to 'rolling'; b) input 'random' number and trigger selection of a winner; - create a custom ERC20 token to be able to test the code; - refactor more (move roles management (admin rights) into an abstract base class); - code truffle tests; - code minimal UI. ### milestone [6fbe5d0](https://github.com/artem-bayandin/blockchain-samples/tree/6fbe5d0c9fd517066e5f2f643ef18160debf91dc) - [Raffle3.sol](https://github.com/artem-bayandin/blockchain-samples/blob/6fbe5d0c9fd517066e5f2f643ef18160debf91dc/raffle/contracts/Raffle3.sol) - a playground to manually test the logic and oracles. Manually, it works, being deployed to Rinkeby; - [Raffle.sol](https://github.com/artem-bayandin/blockchain-samples/blob/6fbe5d0c9fd517066e5f2f643ef18160debf91dc/raffle/contracts/Raffle.sol) - a cleaned version of Raffle3.sol, not yet tested, but ready to; - token allowance should be covered on a frontend, unlimited permissions will be requested (approve 2 ** 256 - 1); - `withdraw` function is not yet implemented; - chainlink data providers should be later moved into separate files, notations are to be added; - no tests at the moment; (sample of truffle tests might be found [here](https://github.com/artem-bayandin/blockchain-satisfactor/tree/master/test), although it will be refactored soon); - no UI at the moment (sample of React UI folder structure might be found [here](https://github.com/artem-bayandin/blockchain-satisfactor/tree/master/src), although it will be refactored soon). <file_sep>/raffle/test/raffle.test.js // const Raffle = artifacts.require('Raffle') // replaced with RaffleExtended const RaffleExtended = artifacts.require('RaffleExtended') const ChainlinkPriceOracle = artifacts.require('ChainlinkPriceOracle') const ChainlinkRandomnessOracle = artifacts.require('ChainlinkRandomnessOracle') // this one won't be needed for local test deployment, i assume // the next contracts are needed for tests const EthAggregatorMock = artifacts.require('EthAggregatorMock') const LinkAggregatorMock = artifacts.require('LinkAggregatorMock') const DaiAggregatorMock = artifacts.require('DaiAggregatorMock') const BnbAggregatorMock = artifacts.require('BnbAggregatorMock') // some tokens for price proxies const LinkMock = artifacts.require('LinkMock') const DaiMock = artifacts.require('DaiMock') const BnbMock = artifacts.require('BnbMock') // randomness oracle mock const RandomnessOracleMock = artifacts.require('RandomnessOracleMock') const { assert, expect } = require('chai') const BN = require('bn.js') const { deploymentSettings } = require('../common/deployment') require('chai') .use(require('chai-bn')(web3.utils.BN)) .use(require('chai-as-promised')) .should() // as truffle runs migration and deploys all the contracts from there, // I cannot say how to get its addresses in here, // as okay, for a single instance it might be MiContract.deployed() or so, // but for contracts that are being publiched multiple times, then how to get its addresses? contract('Raffle', async accounts => { try { // cut the number of accounts to 5 accounts = accounts.slice(0, 5) const [ owner ] = accounts const maxPlayers = 100 const maxTokens = 100 const ticketFee = 1 * 10 ** 9 const MAX_ALLOWANCE = 100 * 10 ** 18; const tokensToMint = 1000 * 10 ** 8 console.log('ticketfee', ticketFee, 'max-allowance', MAX_ALLOWANCE, 'tokensToMint', tokensToMint) let raffle let raffleAddress let priceOracle let priceOracleAddress let randomnessOracle let randomnessOracleAddress const setupTokenAndProxy = async (mock, token, proxy) => { mock.token = await token.deployed() mock.proxy = await proxy.deployed() mock.tokenAddress = mock.token.address mock.proxyAddress = mock.proxy.address } const assignProxyToOracle = async (mock, oracle) => { if (mock.isUsd) { await oracle.addTokenToUsd(mock.tokenAddress, mock.symbol, mock.proxyAddress, mock.decimals) } else { await oracle.addTokenToEth(mock.tokenAddress, mock.symbol, mock.proxyAddress, mock.decimals) } } const mintToken = async (account, mock, owner) => { await mock.token.mint(account, tokensToMint.toString(), { from: owner }) if (!mock.minted) { mock.minted = { } } mock.minted[account] = tokensToMint } const approveToken = async (mock, account, raffleAddress) => { const balance = await mock.token.balanceOf(account) const balanceTS = balance.toString() // console.log(`approving ${balanceTS} from ${account} to ${raffleAddress}`) await mock.token.approve(raffleAddress, balanceTS, { from: account }) } before(async () => { // deploy Chainlinkdatafeeder, if not deployed console.log('setting up price oracles...') priceOracle = await ChainlinkPriceOracle.deployed() priceOracleAddress = priceOracle.address await Promise.all([ setupTokenAndProxy(deploymentSettings.link, LinkMock, LinkAggregatorMock), setupTokenAndProxy(deploymentSettings.dai, DaiMock, DaiAggregatorMock), setupTokenAndProxy(deploymentSettings.bnb, BnbMock, BnbAggregatorMock) ]) const ethProxy = await EthAggregatorMock.deployed() await priceOracle.setEthTokenProxy(ethProxy.address, await ethProxy.decimals()); await Promise.all([ assignProxyToOracle(deploymentSettings.link, priceOracle), assignProxyToOracle(deploymentSettings.dai, priceOracle), assignProxyToOracle(deploymentSettings.bnb, priceOracle) ]) console.log(`price oracles set up at ${priceOracleAddress}`) // setup randomness oracle console.log('setting up randomness oracle...') randomnessOracle = await RandomnessOracleMock.deployed() randomnessOracleAddress = randomnessOracle.address console.log(`randomness oracle set up at ${randomnessOracleAddress}`) // mint some tokenss console.log('minting tokens...') await Promise.all(accounts.map(async account => { await mintToken(account, deploymentSettings.link, owner) await mintToken(account, deploymentSettings.dai, owner) await mintToken(account, deploymentSettings.bnb, owner) })) console.log('tokens minted') }) beforeEach(async () => { // deploy Raffle console.log('deploying raffle contract...') raffle = await RaffleExtended.new( maxPlayers , maxTokens , ticketFee.toString() // 1,000,000,000 / 1,000,000,000,000,000,000 , randomnessOracleAddress , priceOracleAddress ) raffleAddress = raffle.address console.log(`raffle is deployed at ${raffleAddress}`) // allow raffle to spend all tokens console.log('approving tokens...') await Promise.all(accounts.map(async account => { await approveToken(deploymentSettings.link, account, raffle.address) await approveToken(deploymentSettings.dai, account, raffle.address) await approveToken(deploymentSettings.bnb, account, raffle.address) })) console.log('tokens approved') }) describe('deployment', async () => { it('sets ctor parameters', async () => { // (await raffle.__getMaxPlayers()).toString().eq(maxPlayers.toString()).should.be.true // (await raffle.__getMaxTokens()).toString().eq(maxTokens.toString()).should.be.true // (await raffle.__getTicketFee()).toString().eq(ticketFee.toString()).should.be.true // expect(await raffle.__getMaxPlayers(), 'maxPlayers').to.eq.BN(new BN(maxPlayers)) // expect(await raffle.__getMaxTokens(), 'maxTokens').to.eq.BN(new BN(maxTokens)) // expect(await raffle.__getTicketFee(), 'ticketFee').to.eq.BN(new BN(ticketFee)) assert.isTrue((await raffle.__getMaxPlayers()).eq(new BN(maxPlayers)), 'maxPlayers') assert.isTrue((await raffle.__getMaxTokens()).eq(new BN(maxTokens)), 'maxTokens') assert.isTrue((await raffle.__getTicketFee()).eq(new BN(ticketFee)), 'ticketFee') assert.equal(await raffle.__getRandomnessOracleAddress(), randomnessOracleAddress, 'randomnessOracleAddress') assert.equal(await raffle.__getPriceOracleAddress(), priceOracleAddress, 'priceOracleAddress') }) }) describe('deposit', async () => { const deposits1 = { account0: { linkAmount: 1000, // daiAmount: 3000, bnbAmount: 5000 }, account1: { linkAmount: 7000, daiAmount: 11000, // bnbAmount: 13000 }, account2: { // linkAmount: 17000, daiAmount: 19000, bnbAmount: 23000 }, account3: { linkAmount: 29000, daiAmount: 31000, bnbAmount: 37000 }, account4: { linkAmount: 37000, // daiAmount: 41000, // bnbAmount: 43000 } } const deposits2 = { account3: { linkAmount: 101000, // daiAmount: 31000, bnbAmount: 107000 }, account4: { linkAmount: 111000, // daiAmount: 41000, bnbAmount: 117000 } } const deposits3 = { account3: { linkAmount: 555, daiAmount: 777, bnbAmount: 999 } } const deposit = async (account, { linkAmount, daiAmount, bnbAmount }, value) => { let resultValue = new BN() if (linkAmount) { const { tx, logs, receipt } = await raffle.deposit(deploymentSettings.link.tokenAddress, linkAmount, { from: account, value: value }) resultValue = resultValue.add(new BN(value)) } if (daiAmount) { const { tx, logs, receipt } = await raffle.deposit(deploymentSettings.dai.tokenAddress, daiAmount, { from: account, value: value }) resultValue = resultValue.add(new BN(value)) } if (bnbAmount) { const { tx, logs, receipt } = await raffle.deposit(deploymentSettings.bnb.tokenAddress, bnbAmount, { from: account, value: value }) resultValue = resultValue.add(new BN(value)) } return resultValue } const assertTokensBeforeAfterDepositing = async (account, depo1, depo2, depo3, initialBalance) => { let expectedLink = initialBalance.link const linkSubN = (depo1 && depo1.linkAmount ? depo1.linkAmount : 0) + (depo2 && depo2.linkAmount ? depo2.linkAmount : 0) + (depo3 && depo3.linkAmount ? depo3.linkAmount : 0) expectedLink = expectedLink.subn(linkSubN) const actualLink = await deploymentSettings.link.token.balanceOf(account) let expectedDai = initialBalance.dai const daiSubN = (depo1 && depo1.daiAmount ? depo1.daiAmount : 0) + (depo2 && depo2.daiAmount ? depo2.daiAmount : 0) + (depo3 && depo3.daiAmount ? depo3.daiAmount : 0) expectedDai = expectedDai.subn(daiSubN) const actualDai = await deploymentSettings.dai.token.balanceOf(account) let expectedBnb = initialBalance.bnb const bnbSubN = (depo1 && depo1.bnbAmount ? depo1.bnbAmount : 0) + (depo2 && depo2.bnbAmount ? depo2.bnbAmount : 0) + (depo3 && depo3.bnbAmount ? depo3.bnbAmount : 0) expectedBnb = expectedBnb.subn(bnbSubN) const actualBnb = await deploymentSettings.bnb.token.balanceOf(account) // (actualLink.toString().eq(expectedLink.toString())).should.be.true // (actualDai.toString().eq(expectedDai.toString())).should.be.true // (actualBnb.toString().eq(expectedBnb.toString())).should.be.true // expect(actualLink, 'LINK').to.eq.BN(expectedLink) // expect(actualDai, 'DAI').to.eq.BN(expectedDai) // expect(actualBnb, 'BNB').to.eq.BN(expectedBnb) assert.isTrue(actualLink.eq(expectedLink), 'LINK') assert.isTrue(actualDai.eq(expectedDai), 'DAI') assert.isTrue(actualBnb.eq(expectedBnb), 'BNB') return { link: { actual: actualLink, expected: expectedLink, linkSub: linkSubN || 0 }, dai: { actual: actualDai, expected: expectedDai, daiSub: daiSubN || 0 }, bnb: { actual: actualBnb, expected: expectedBnb, bnbSub: bnbSubN || 0 } } } let feesPaid = new BN(), initialCollectedFee = new BN() let initialBalances = { account0: { link: new BN(0), dai: new BN(0), bnb: new BN(0) }, account1: { link: new BN(0), dai: new BN(0), bnb: new BN(0) }, account2: { link: new BN(0), dai: new BN(0), bnb: new BN(0) }, account3: { link: new BN(0), dai: new BN(0), bnb: new BN(0) }, account4: { link: new BN(0), dai: new BN(0), bnb: new BN(0) }, } const recordInitialBalancePerAccount = async (account, initialBalance) => { await Promise.all([ initialBalance.link = await deploymentSettings.link.token.balanceOf(account), initialBalance.dai = await deploymentSettings.dai.token.balanceOf(account), initialBalance.bnb = await deploymentSettings.bnb.token.balanceOf(account), ]) } const recordInitialBalances = async () => { console.log('recording initial balances...') await Promise.all([ recordInitialBalancePerAccount(accounts[0], initialBalances.account0), recordInitialBalancePerAccount(accounts[1], initialBalances.account1), recordInitialBalancePerAccount(accounts[2], initialBalances.account2), recordInitialBalancePerAccount(accounts[3], initialBalances.account3), recordInitialBalancePerAccount(accounts[4], initialBalances.account4), ]) console.log('initial balances are recorded') } beforeEach(async () => { await recordInitialBalances() initialCollectedFee = initialCollectedFee.add(await raffle.__getCollectedFee()); // let all accounts take participation feesPaid = feesPaid.add(await deposit(accounts[0], deposits1.account0, ticketFee + 1000)) feesPaid = feesPaid.add(await deposit(accounts[1], deposits1.account1, ticketFee + 3000)) feesPaid = feesPaid.add(await deposit(accounts[2], deposits1.account2, ticketFee + 7000)) feesPaid = feesPaid.add(await deposit(accounts[3], deposits1.account3, ticketFee + 11000)) feesPaid = feesPaid.add(await deposit(accounts[4], deposits1.account4, ticketFee + 13000)) // secondary deposits feesPaid = feesPaid.add(await deposit(accounts[3], deposits2.account3, ticketFee + 17000)) feesPaid = feesPaid.add(await deposit(accounts[4], deposits2.account4, ticketFee + 19000)) // third time deposits feesPaid = feesPaid.add(await deposit(accounts[3], deposits3.account3, ticketFee + 23000)) console.log('tokens deposited') }) it('numbers are valid after depositing', async () => { const data = [ await assertTokensBeforeAfterDepositing( accounts[0], deposits1.account0, deposits2.account0, deposits3.account0, initialBalances.account0 ), await assertTokensBeforeAfterDepositing( accounts[1], deposits1.account1, deposits2.account1, deposits3.account1, initialBalances.account1 ), await assertTokensBeforeAfterDepositing( accounts[2], deposits1.account2, deposits2.account2, deposits3.account2, initialBalances.account2 ), await assertTokensBeforeAfterDepositing( accounts[3], deposits1.account3, deposits2.account3, deposits3.account3, initialBalances.account3 ), await assertTokensBeforeAfterDepositing( accounts[4], deposits1.account4, deposits2.account4, deposits3.account4, initialBalances.account4 ), ] // check the contract's balances const ctrLinkExpected = data.reduce((prev, current) => { return prev + current.link.linkSub }, 0) const ctrLinkAmount = await deploymentSettings.link.token.balanceOf(raffleAddress) const ctrDaiExpected = data.reduce((prev, current) => { return prev + current.dai.daiSub }, 0) const ctrDaiAmount = await deploymentSettings.dai.token.balanceOf(raffleAddress) const ctrBnbExpected = data.reduce((prev, current) => { return prev + current.bnb.bnbSub }, 0) const ctrBnbAmount = await deploymentSettings.bnb.token.balanceOf(raffleAddress) assert.isTrue(ctrLinkAmount.eq(new BN(ctrLinkExpected)), 'LINK on raffle') assert.isTrue(ctrDaiAmount.eq(new BN(ctrDaiExpected)), 'DAI on raffle') assert.isTrue(ctrBnbAmount.eq(new BN(ctrBnbExpected)), 'BNB on raffle') // check collectedFee const collectedFee = await raffle.__getCollectedFee() assert.isTrue(collectedFee.eq(feesPaid), 'collected fee') // check chances }) }) /* describe('withdrawThePrize', async () => { it('test', async () => { assert(true, true) }) }) describe('rollTheDice', async () => { it('test', async () => { assert(true, true) }) }) describe('rollTheDiceManually', async () => { it('test', async () => { assert(true, true) }) }) describe('inputRandomNumberManually', async () => { it('test', async () => { assert(true, true) }) }) describe('fixRolling', async () => { it('test', async () => { assert(true, true) }) }) */ } catch(err) { console.log('ERR!!', err) } }) <file_sep>/README.md Choose a folder above and enjoy. <file_sep>/raffle/common/deployment.js // proxy addresses are taken from https://docs.chain.link/docs/ethereum-addresses/ for Rinkeby network. // if deployed locally, proxy addresses should be updated to point to appropriate local AggregatorV3Mock // tokens are named similar to its originals to have less confusion // 'token' and 'tokenAddress' should be filled on deployment // 'initialProxyValue' is used for locally deployed proxies to set some initial value to be returned const deploymentSettings = { eth: { decimals: 8, initialProxyValue: (3800 * 10 ** 8).toString() }, link: { name: 'LINK mock', symbol: 'LINKM', proxyAddress: '0xd8bD0a1cB028a31AA859A21A3758685a95dE4623', decimals: 8, isUsd: true, tokenAddress: null, initialProxyValue: (25 * 10 ** 8).toString() }, dai: { name: 'DAI mock', symbol: 'DAIM', proxyAddress: '0x74825DbC8BF76CC4e9494d0ecB210f676Efa001D', decimals: 18, isUsd: false, tokenAddress: null, initialProxyValue: (1 * 10 ** 18).toString() }, bnb: { name: 'BNB mock', symbol: 'BNBM', proxyAddress: '0xcf0f51ca2cDAecb464eeE4227f5295F2384F84ED', decimals: 8, isUsd: true, tokenAddress: null, initialProxyValue: (367 * 10 ** 8).toString() } } /* [, , , { name: 'TRX mock', symbol: 'TRXM', proxyAddress: '0xb29f616a0d54FF292e997922fFf46012a63E2FAe', decimals: 8, isUsd: true, tokenAddress: null, initialProxyValue: (0.09 * 10 ** 8).toString() }, { name: '<NAME>', symbol: 'ZRXM', proxyAddress: '0xF7Bbe4D7d13d600127B6Aa132f1dCea301e9c8Fc', decimals: 8, isUsd: true, tokenAddress: null, initialProxyValue: (0.92 * 10 ** 8).toString() }] */ module.exports = { deploymentSettings }
a8faa5a0523232138514ff521aeff11828441364
[ "Markdown", "JavaScript" ]
4
Markdown
gomel-tdl1/blockchain-samples
7c3da63b9c88e3351f53b4f4bb64302e9aafbb2e
65054cf5621ca4872356e15b09066e485c676045
refs/heads/master
<repo_name>anonyauth2020/batchcrypt<file_sep>/FATE_plugin/federatedml/transfer_variable/transfer_class/homo_zcl_alex_transfer_variable.py #!/usr/bin/env python # -*- coding: utf-8 -*- # # Copyright 2019 The FATE Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ################################################################################ # # AUTO GENERATED TRANSFER VARIABLE CLASS. DO NOT MODIFY # ################################################################################ from federatedml.transfer_variable.transfer_class.base_transfer_variable import BaseTransferVariable, Variable # noinspection PyAttributeOutsideInit class HomoZclAlexTransferVariable(BaseTransferVariable): def define_transfer_variable(self): self.guest_uuid = Variable(name='HomoZclAlexTransferVariable.guest_uuid', auth=dict(src='guest', dst=['arbiter']), transfer_variable=self) self.host_uuid = Variable(name='HomoZclAlexTransferVariable.host_uuid', auth=dict(src='host', dst=['arbiter']), transfer_variable=self) self.uuid_conflict_flag = Variable(name='HomoZclAlexTransferVariable.uuid_conflict_flag', auth=dict(src='arbiter', dst=['guest', 'host']), transfer_variable=self) self.dh_pubkey = Variable(name='HomoZclAlexTransferVariable.dh_pubkey', auth=dict(src='arbiter', dst=['guest', 'host']), transfer_variable=self) self.dh_ciphertext_host = Variable(name='HomoZclAlexTransferVariable.dh_ciphertext_host', auth=dict(src='host', dst=['arbiter']), transfer_variable=self) self.dh_ciphertext_guest = Variable(name='HomoZclAlexTransferVariable.dh_ciphertext_guest', auth=dict(src='guest', dst=['arbiter']), transfer_variable=self) self.dh_ciphertext_bc = Variable(name='HomoZclAlexTransferVariable.dh_ciphertext_bc', auth=dict(src='arbiter', dst=['guest', 'host']), transfer_variable=self) self.paillier_pubkey = Variable(name='HomoZclAlexTransferVariable.paillier_pubkey', auth=dict(src='arbiter', dst=['host', 'guest']), transfer_variable=self) self.guest_model = Variable(name='HomoZclAlexTransferVariable.guest_model', auth=dict(src='guest', dst=['arbiter']), transfer_variable=self) self.host_model = Variable(name='HomoZclAlexTransferVariable.host_model', auth=dict(src='host', dst=['arbiter']), transfer_variable=self) self.aggregated_model = Variable(name='HomoZclAlexTransferVariable.aggregated_model', auth=dict(src='arbiter', dst=['guest', 'host']), transfer_variable=self) self.to_encrypt_model = Variable(name='HomoZclAlexTransferVariable.to_encrypt_model', auth=dict(src='host', dst=['arbiter']), transfer_variable=self) self.re_encrypted_model = Variable(name='HomoZclAlexTransferVariable.re_encrypted_model', auth=dict(src='arbiter', dst=['host']), transfer_variable=self) self.re_encrypt_times = Variable(name='HomoZclAlexTransferVariable.re_encrypt_times', auth=dict(src='host', dst=['arbiter']), transfer_variable=self) self.is_converge = Variable(name='HomoZclAlexTransferVariable.is_converge', auth=dict(src='arbiter', dst=['guest', 'host']), transfer_variable=self) self.guest_loss = Variable(name='HomoZclAlexTransferVariable.guest_loss', auth=dict(src='guest', dst=['arbiter']), transfer_variable=self) self.host_loss = Variable(name='HomoZclAlexTransferVariable.host_loss', auth=dict(src='host', dst=['arbiter']), transfer_variable=self) self.use_encrypt = Variable(name='HomoZclAlexTransferVariable.use_encrypt', auth=dict(src='host', dst=['arbiter']), transfer_variable=self) self.guest_party_weight = Variable(name='HomoZclAlexTransferVariable.guest_party_weight', auth=dict(src='guest', dst=['arbiter']), transfer_variable=self) self.host_party_weight = Variable(name='HomoZclAlexTransferVariable.host_party_weight', auth=dict(src='host', dst=['arbiter']), transfer_variable=self) self.predict_wx = Variable(name='HomoZclAlexTransferVariable.predict_wx', auth=dict(src='host', dst=['arbiter']), transfer_variable=self) self.predict_result = Variable(name='HomoZclAlexTransferVariable.predict_result', auth=dict(src='arbiter', dst=['host']), transfer_variable=self) self.paillier_prikey = Variable(name='HomoZclAlexTransferVariable.paillier_prikey', auth=dict(src='arbiter', dst=['host', 'guest']), transfer_variable=self) self.guest_grad = Variable(name='HomoZclAlexTransferVariable.guest_grad', auth=dict(src='guest', dst=['arbiter']), transfer_variable=self) self.host_grad = Variable(name='HomoZclAlexTransferVariable.host_grad', auth=dict(src='host', dst=['arbiter']), transfer_variable=self) self.aggregated_loss = Variable(name='HomoZclAlexTransferVariable.aggregated_loss', auth=dict(src='arbiter', dst=['host', 'guest']), transfer_variable=self) self.aggregated_grad = Variable(name='HomoZclAlexTransferVariable.aggregated_grad', auth=dict(src='arbiter', dst=['host', 'guest']), transfer_variable=self) self.num_party = Variable(name='HomoZclAlexTransferVariable.num_party', auth=dict(src='arbiter', dst=['host', 'guest']), transfer_variable=self) self.clipping_threshold = Variable(name='HomoZclAlexTransferVariable.clipping_threshold', auth=dict(src='guest', dst=['host']), transfer_variable=self) self.grad_token = Variable(name='HomoZclAlexTransferVariable.grad_token', auth=dict(src='arbiter', dst=['host']), transfer_variable=self) self.host_grad_min = Variable(name='HomoZclAlexTransferVariable.host_grad_min', auth=dict(src='host', dst=['guest']), transfer_variable=self) self.host_grad_max = Variable(name='HomoZclAlexTransferVariable.host_grad_max', auth=dict(src='host', dst=['guest']), transfer_variable=self) self.epoch_end = Variable(name='HomoZclAlexTransferVariable.epoch_end', auth=dict(src='guest', dst=['arbiter']), transfer_variable=self) pass <file_sep>/accuracy_eval/test_10parties/federated_lr_lstm_experiments.py import time import argparse import tensorflow as tf from tensorflow import keras import numpy as np import matplotlib.pyplot as plt import pysnooper import copy from functools import reduce, partial from ftl.encryption import paillier, encryption tf.enable_eager_execution() from tensorflow import contrib from joblib import Parallel, delayed import multiprocessing N_JOBS = multiprocessing.cpu_count() tfe = contrib.eager print("TensorFlow version: {}".format(tf.__version__)) print("Eager execution: {}".format(tf.executing_eagerly())) path_to_file = tf.keras.utils.get_file('shakespeare.txt', 'https://storage.googleapis.com/download.tensorflow.org/data/shakespeare.txt') # Read, then decode for py2 compat. text = open(path_to_file, 'rb').read().decode(encoding='utf-8') # length of text is the number of characters in it print('Length of text: {} characters'.format(len(text))) # print(text[:250]) # The unique characters in the file vocab = sorted(set(text)) print('{} unique characters'.format(len(vocab))) # Creating a mapping from unique characters to indices char2idx = {u: i for i, u in enumerate(vocab)} idx2char = np.array(vocab) text_as_int = np.array([char2idx[c] for c in text]) print('{') for char, _ in zip(char2idx, range(20)): print(' {:4s}: {:3d},'.format(repr(char), char2idx[char])) print(' ...\n}') print('{} ---- characters mapped to int ---- > {}'.format(repr(text[:13]), text_as_int[:13])) # The maximum length sentence we want for a single input in characters seq_length = 100 examples_per_epoch = len(text) // seq_length # Create training examples / targets char_dataset = tf.data.Dataset.from_tensor_slices(text_as_int) for i in char_dataset.take(5): print(idx2char[i.numpy()]) sequences = char_dataset.batch(seq_length + 1, drop_remainder=True) for item in sequences.take(5): print(repr(''.join(idx2char[item.numpy()]))) def split_input_target(chunk): input_text = chunk[:-1] target_text = chunk[1:] return input_text, target_text dataset_0 = sequences.map(split_input_target) for input_example, target_example in dataset_0.take(1): print('Input data: ', repr(''.join(idx2char[input_example.numpy()]))) print('Target data:', repr(''.join(idx2char[target_example.numpy()]))) for i, (input_idx, target_idx) in enumerate(zip(input_example[:5], target_example[:5])): print("Step {:4d}".format(i)) print(" input: {} ({:s})".format(input_idx, repr(idx2char[input_idx]))) print(" expected output: {} ({:s})".format(target_idx, repr(idx2char[target_idx]))) # Batch size BATCH_SIZE = 64 steps_per_epoch = examples_per_epoch // BATCH_SIZE # Buffer size to shuffle the dataset # (TF data is designed to work with possibly infinite sequences, # so it doesn't attempt to shuffle the entire sequence in memory. Instead, # it maintains a buffer in which it shuffles elements). BUFFER_SIZE = 10000 dataset_0 = dataset_0.shuffle(BUFFER_SIZE).batch(BATCH_SIZE, drop_remainder=True) # Length of the vocabulary in chars vocab_size = len(vocab) # The embedding dimension embedding_dim = 256 # Number of RNN units rnn_units = 1024 if tf.test.is_gpu_available(): rnn = tf.keras.layers.CuDNNGRU else: rnn = partial( tf.keras.layers.GRU, recurrent_activation='sigmoid') def build_model(vocab_size, embedding_dim, rnn_units, batch_size): model = tf.keras.Sequential([ tf.keras.layers.Embedding(vocab_size, embedding_dim, batch_input_shape=[batch_size, None]), rnn(rnn_units, return_sequences=True, recurrent_initializer='glorot_uniform', stateful=True), tf.keras.layers.Dense(vocab_size) ]) return model model = build_model( vocab_size=len(vocab), embedding_dim=embedding_dim, rnn_units=rnn_units, batch_size=BATCH_SIZE) model.summary() for input_example_batch, target_example_batch in dataset_0.take(1): example_batch_predictions = model(input_example_batch) print(example_batch_predictions.shape, "# (batch_size, sequence_length, vocab_size)") sampled_indices = tf.random.categorical(example_batch_predictions[0], num_samples=1) sampled_indices = tf.squeeze(sampled_indices, axis=-1).numpy() print("Input: \n", repr("".join(idx2char[input_example_batch[0]]))) print() print("Next Char Predictions: \n", repr("".join(idx2char[sampled_indices]))) def build_datasets(num_clients): dataset_raw = sequences.map(split_input_target) train_dataset_clients = [dataset_raw.shuffle(BUFFER_SIZE).batch(BATCH_SIZE, drop_remainder=True) for _ in range(num_clients)] return train_dataset_clients def loss(model, x, y): y_ = model(x) return tf.keras.losses.sparse_categorical_crossentropy(y, y_, from_logits=True) def grad(model, inputs, targets): with tf.GradientTape() as tape: loss_value = loss(model, inputs, targets) return loss_value, tape.gradient(loss_value, model.trainable_variables) optimizer = tf.train.AdamOptimizer() global_step = tf.Variable(0) def clip_gradients(grads, min_v, max_v): results = [tf.clip_by_value(t, min_v, max_v).numpy() for t in grads] return results def do_sum(x1, x2): results = [] for i in range(len(x1)): if isinstance(x1[i], tf.IndexedSlices) and isinstance(x2[i], tf.IndexedSlices): results.append(tf.IndexedSlices(values=tf.concat([x1[i].values, x2[i].values], axis=0), indices=tf.concat([x1[i].indices, x2[i].indices], axis=0), dense_shape=x1[i].dense_shape)) else: results.append(x1[i] + x2[i]) return results def aggregate_gradients(gradient_list, weight=0.5): # def multiply_by_weight(party, w): # for i in range(len(party)): # party[i] = w * party[i] # return party # gradient_list = Parallel(n_jobs=2)(delayed(multiply_by_weight)(party, weight) for party in gradient_list) results = reduce(do_sum, gradient_list) return results def aggregate_losses(loss_list): return np.mean(loss_list) def quantize_per_layer(party, r_maxs, bit_width=16): # result = [] # for component, r_max in zip(party, r_maxs): # x, _ = encryption.quantize_matrix_stochastic(component, bit_width=bit_width, r_max=r_max) # result.append(x) result = Parallel(n_jobs=N_JOBS)( delayed(encryption.quantize_matrix_stochastic)(component, bit_width=bit_width, r_max=r_max) for component, r_max in zip(party, r_maxs)) result = np.array(result)[:, 0] return result def unquantize_per_layer(party, r_maxs, bit_width=16): # result = [] # for component, r_max in zip(party, r_maxs): # result.append(encryption.unquantize_matrix(component, bit_width=bit_width, r_max=r_max).astype(np.float32)) result = Parallel(n_jobs=N_JOBS)( delayed(encryption.unquantize_matrix)(component, bit_width=bit_width, r_max=r_max) for component, r_max in zip(party, r_maxs) ) return np.array(result) def sparse_to_dense(gradients): result = [] for layer in gradients: if isinstance(layer, tf.IndexedSlices): result.append(tf.convert_to_tensor(layer).numpy()) else: result.append(layer.numpy()) return result if __name__ == '__main__': seed = 123 tf.random.set_random_seed(seed) np.random.seed(seed) parser = argparse.ArgumentParser() parser.add_argument('--experiment', type=str, default='plain', choices=["plain", "quan", "aciq_quan"]) parser.add_argument('--num_clients', type=int, default=10) parser.add_argument('--num_epochs', type=int, default=10) parser.add_argument('--batch_size', type=int, default=100) parser.add_argument('--q_width', type=int, default=16) parser.add_argument('--clip', type=float, default=0.5) args = parser.parse_args() options = vars(args) output_name = "lstm_" + "_".join([ "{}_{}".format(key, options[key]) for key in options ]) num_epochs = args.num_epochs clip = args.clip num_clients = args.num_clients q_width = args.q_width # keep results for plotting train_loss_results = [] train_accuracy_results = [] # num_epochs = 100 publickey, privatekey = paillier.PaillierKeypair.generate_keypair(n_length=2048) # with pysnooper.snoop('no_batch_log_sto_c05.log'): for epoch in range(num_epochs): epoch_loss_avg = tfe.metrics.Mean() # train_dataset_1_iter = iter(dataset_0) train_dataset_clients = build_datasets(num_clients) # for x_0, y_0 in dataset_0: # x_1, y_1 = next(train_dataset_1_iter) for data_clients in zip(*train_dataset_clients): print("{} clients are in federated training".format(len(data_clients))) loss_batch_clients = [] grads_batch_clients = [] start_t = time.time() # # Optimize the model # loss_value_0, grads_0 = grad(model, x_0, y_0) # loss_value_1, grads_1 = grad(model, x_1, y_1) # calculate loss and grads locally for x, y in data_clients: loss_temp, grads_temp = grad(model, x, y) loss_batch_clients.append(loss_temp.numpy()) grads_batch_clients.append(grads_temp) # federated_lr_plain_lstm.py if args.experiment == "plain": # loss_value_0 = loss_value_0.numpy() # loss_value_1 = loss_value_1.numpy() print # grads = aggregate_gradients([grads_0, grads_1]) # loss_value = aggregate_losses([0.5 * loss_value_0, 0.5 * loss_value_1]) start = time.time() grads = aggregate_gradients(grads_batch_clients) end_enc = time.time() print("aggregation finished in %f" % (end_enc - start)) client_weight = 1.0 / num_clients loss_value = aggregate_losses([item * client_weight for item in loss_batch_clients]) # federated_lr_quan_lstm.py elif args.experiment == "quan": # clipping_thresholds = encryption.calculate_clip_threshold_sparse(grads_0) theta = 2.5 grads_batch_clients_mean = [] grads_batch_clients_mean_square = [] for client_idx in range(len(grads_batch_clients)): temp_mean = [] temp_mean_square = [] for layer_idx in range(len(grads_batch_clients[client_idx])): if isinstance(grads_batch_clients[client_idx][layer_idx], tf.IndexedSlices): temp_mean.append( np.mean(grads_batch_clients[client_idx][layer_idx].values.numpy()) ) temp_mean_square.append( np.mean(grads_batch_clients[client_idx][layer_idx].values.numpy()**2) ) else: temp_mean.append( np.mean(grads_batch_clients[client_idx][layer_idx].numpy()) ) temp_mean_square.append( np.mean(grads_batch_clients[client_idx][layer_idx].numpy()**2) ) grads_batch_clients_mean.append(temp_mean) grads_batch_clients_mean_square.append(temp_mean_square) grads_batch_clients_mean = np.array(grads_batch_clients_mean) grads_batch_clients_mean_square = np.array(grads_batch_clients_mean_square) layers_size = [] for layer in grads_batch_clients[0]: if isinstance(layer, tf.IndexedSlices): layers_size.append(layer.values.numpy().size) else: layers_size.append(layer.numpy().size) layers_size = np.array(layers_size) clipping_thresholds = theta * ( np.sum(grads_batch_clients_mean_square * layers_size, 0) / (layers_size * num_clients) - (np.sum(grads_batch_clients_mean * layers_size, 0) / (layers_size * num_clients)) ** 2) ** 0.5 print("clipping_thresholds", clipping_thresholds) # r_maxs = [x * 2 for x in clipping_thresholds] r_maxs = [x * num_clients for x in clipping_thresholds] # grads_0 = encryption.clip_with_threshold(sparse_to_dense(grads_0), clipping_thresholds) # grads_1 = encryption.clip_with_threshold(sparse_to_dense(grads_1), clipping_thresholds) grads_batch_clients = [encryption.clip_with_threshold(sparse_to_dense(item), clipping_thresholds) for item in grads_batch_clients] # grads_0 = quantize_per_layer(grads_0, r_maxs, bit_width=q_width) # grads_1 = quantize_per_layer(grads_1, r_maxs, bit_width=q_width) grads_batch_clients = [quantize_per_layer(item, r_maxs, bit_width=q_width) for item in grads_batch_clients] # grads = aggregate_gradients([grads_0, grads_1]) # loss_value = aggregate_losses([0.5 * loss_value_0, 0.5 * loss_value_1]) grads = aggregate_gradients(grads_batch_clients) client_weight = 1.0 / num_clients loss_value = aggregate_losses([item * client_weight for item in loss_batch_clients]) grads = unquantize_per_layer(grads, r_maxs, bit_width=q_width) elif args.experiment == "aciq_quan": grads_batch_clients_values = copy.deepcopy(grads_batch_clients) for client_idx in range(len(grads_batch_clients)): for layer_idx in range(len(grads_batch_clients[client_idx])): if isinstance(grads_batch_clients[client_idx][layer_idx], tf.IndexedSlices): grads_batch_clients_values[client_idx][layer_idx] = grads_batch_clients[client_idx][layer_idx].values.numpy() else: grads_batch_clients_values[client_idx][layer_idx] = grads_batch_clients[client_idx][layer_idx].numpy() sizes = [item.size * num_clients for item in grads_batch_clients_values[0]] max_values = [] min_values = [] for layer_idx in range(len(grads_batch_clients_values[0])): max_values.append([np.max([item[layer_idx] for item in grads_batch_clients_values])]) min_values.append([np.min([item[layer_idx] for item in grads_batch_clients_values])]) grads_max_min = np.concatenate([np.array(max_values),np.array(min_values)], axis=1) clipping_thresholds = encryption.calculate_clip_threshold_aciq_g(grads_max_min, sizes, bit_width=q_width) r_maxs = [x * num_clients for x in clipping_thresholds] grads_batch_clients = [encryption.clip_with_threshold(sparse_to_dense(item), clipping_thresholds) for item in grads_batch_clients] grads_batch_clients = [quantize_per_layer(item, r_maxs, bit_width=q_width) for item in grads_batch_clients] grads = aggregate_gradients(grads_batch_clients) client_weight = 1.0 / num_clients loss_value = aggregate_losses([item * client_weight for item in loss_batch_clients]) grads = unquantize_per_layer(grads, r_maxs, bit_width=q_width) optimizer.apply_gradients(zip(grads, model.trainable_variables), global_step) # Track progress epoch_loss_avg(loss_value) # add current batch loss # compare predicted label to actual label # epoch_accuracy(tf.argmax(model(tf.concat([x_0, x_1], axis=0)), axis=1, output_type=tf.int32), # tf.concat([y_0, y_1], axis=0)) elapsed_time = time.time() - start_t print( "loss: {} \telapsed time: {}".format(loss_value, elapsed_time) ) # end epoch train_loss_results.append(epoch_loss_avg.result()) print("Epoch {:03d}: Loss: {:.3f}".format(epoch, epoch_loss_avg.result())) # checkpoint # model.save_weights( 'plain/easy_checkpoint_{:03d}'.format(epoch) ) model.save_weights( '{}/easy_checkpoint_{:03d}'.format(args.experiment, epoch) ) # np.savetxt('alex_v_loss_plain_lstm.txt', train_loss_results) np.savetxt('lstm_v_loss_{}.txt'.format(output_name), train_loss_results) # serialize model to JSON model_json = model.to_json() with open("model_{}.json".format(output_name), "w") as json_file: json_file.write(model_json) # serialize weights to HDF5 model.save_weights("model_{}.h5".format(output_name)) print("Saved model to disk") # diskfig, axes = plt.subplots(2, sharex=True, figsize=(12, 8)) # fig.suptitle('Training Metrics') # # axes[0].set_ylabel("Loss", fontsize=14) # axes[0].plot(loss_array) # # axes[1].set_ylabel("Accuracy", fontsize=14) # axes[1].set_xlabel("Batch", fontsize=14) # axes[1].plot(accuracy_array) # plt.show() <file_sep>/accuracy_eval/test_10parties/federated_lr_fmnist_experiments.py import time import tensorflow as tf from tensorflow import keras import numpy as np from sklearn.metrics import accuracy_score import matplotlib.pyplot as plt import pysnooper import argparse from functools import reduce from ftl.encryption import paillier, encryption from joblib import Parallel, delayed tf.enable_eager_execution() from tensorflow import contrib tfe = contrib.eager print("TensorFlow version: {}".format(tf.__version__)) # expected tensorflow 1.14 print("Eager execution: {}".format(tf.executing_eagerly())) # load fashion mnist dataset fashion_mnist = keras.datasets.fashion_mnist (train_images, train_labels), (test_images, test_labels) = fashion_mnist.load_data() train_labels = train_labels.astype(np.int32) test_labels = test_labels.astype(np.int32) train_images = train_images / 255.0 test_images = test_images / 255.0 def build_datasets(num_clients): # split_idx = int(len(x_train) / num_clients) avg_length = int(len(train_images) / num_clients) split_idx = [_ * avg_length for _ in range(1, num_clients)] # [train_images_0, train_images_1] = np.split(train_images, [split_idx]) # [train_labels_0, train_labels_1] = np.split(train_labels, [split_idx]) x_train_clients = np.split(train_images, split_idx) y_train_clients = np.split(train_labels, split_idx) # # party A # train_dataset_0 = tf.data.Dataset.from_tensor_slices((train_images_0, train_labels_0)) # # party B # train_dataset_1 = tf.data.Dataset.from_tensor_slices((train_images_1, train_labels_1)) train_dataset_clients = [tf.data.Dataset.from_tensor_slices(item) for item in zip(x_train_clients, y_train_clients)] BATCH_SIZE = 128 SHUFFLE_BUFFER_SIZE = 100 # train_dataset_0 = train_dataset_0.shuffle(SHUFFLE_BUFFER_SIZE).batch(BATCH_SIZE) # train_dataset_1 = train_dataset_1.shuffle(SHUFFLE_BUFFER_SIZE).batch(BATCH_SIZE) for i in range(len(train_dataset_clients)): train_dataset_clients[i] = train_dataset_clients[i].shuffle(SHUFFLE_BUFFER_SIZE).batch(BATCH_SIZE) return train_dataset_clients # build the model model = keras.Sequential([ keras.layers.Flatten(input_shape=(28, 28)), keras.layers.Dense(128, activation=tf.nn.relu), keras.layers.Dense(10, activation=tf.nn.softmax) ]) model.summary() # predictions = model(features) # print(predictions[:5]) cce = tf.keras.losses.SparseCategoricalCrossentropy() def loss(model, x, y): y_ = model(x) return cce(y_true=y, y_pred=y_) # l = loss(model, features, labels) # print("Loss test: {}".format(l)) def grad(model, inputs, targets): with tf.GradientTape() as tape: loss_value = loss(model, inputs, targets) return loss_value, tape.gradient(loss_value, model.trainable_variables) optimizer = tf.train.AdamOptimizer(learning_rate=0.005) global_step = tf.Variable(0) def clip_gradients(grads, min_v, max_v): results = [tf.clip_by_value(t, min_v, max_v) for t in grads] return results def do_sum(x1, x2): results = [] for i in range(len(x1)): results.append(x1[i] + x2[i]) return results def aggregate_gradients(gradient_list): results = reduce(do_sum, gradient_list) return results def aggregate_losses(loss_list): return np.sum(loss_list) def quantize(party, bit_width=16): result = [] for component in party: x, _ = encryption.quantize_matrix(component, bit_width=bit_width) result.append(x) return np.array(result) def quantize_per_layer(party, r_maxs, bit_width=16): result = [] for component, r_max in zip(party, r_maxs): x, _ = encryption.quantize_matrix_stochastic(component, bit_width=bit_width, r_max=r_max) result.append(x) return np.array(result) def unquantize(party, bit_width=16, r_max=0.5): result = [] for component in party: result.append(encryption.unquantize_matrix(component, bit_width=bit_width, r_max=r_max).astype(np.float32)) return np.array(result) def unquantize_per_layer(party, r_maxs, bit_width=16): result = [] for component, r_max in zip(party, r_maxs): result.append(encryption.unquantize_matrix(component, bit_width=bit_width, r_max=r_max).astype(np.float32)) return np.array(result) if __name__ == '__main__': seed = 123 tf.random.set_random_seed(seed) np.random.seed(seed) parser = argparse.ArgumentParser() # parser.add_argument('--experiment', type=str, required=True, # choices=["plain", "batch", "only_quan", "aciq_quan"]) parser.add_argument('--experiment', type=str, default="plain", choices=["plain", "batch", "only_quan", "aciq_quan"]) parser.add_argument('--num_clients', type=int, default=10) parser.add_argument('--num_epochs', type=int, default=10) parser.add_argument('--batch_size', type=int, default=100) parser.add_argument('--q_width', type=int, default=16) parser.add_argument('--clip', type=float, default=0.5) args = parser.parse_args() options = vars(args) output_name = "fmnist_" + "_".join([ "{}_{}".format(key, options[key]) for key in options ]) # keep results for plotting train_loss_results = [] train_accuracy_results = [] test_loss_results = [] test_accuracy_results = [] num_epochs = args.num_epochs clip = args.clip num_clients = args.num_clients q_width = args.q_width # this key pair should be shared by party A and B publickey, privatekey = paillier.PaillierKeypair.generate_keypair(n_length=2048) loss_array = [] accuracy_array = [] for epoch in range(num_epochs): epoch_loss_avg = tfe.metrics.Mean() epoch_accuracy = tfe.metrics.Accuracy() train_dataset_clients = build_datasets(num_clients) for data_clients in zip(*train_dataset_clients): print("{} clients are in federated training".format(len(data_clients))) loss_batch_clients = [] grads_batch_clients = [] start_t = time.time() # calculate loss and grads locally for x, y in data_clients: loss_temp, grads_temp = grad(model, x, y) loss_batch_clients.append(loss_temp.numpy()) grads_batch_clients.append([x.numpy() for x in grads_temp]) # federated_lr_plain.py if args.experiment == "plain": # NOTE: The clip value here is "1" in federated_lr_plain.py # grads_0 = clip_gradients(grads_0, -1 * clip, clip) # grads_1 = clip_gradients(grads_1, -1 * clip, clip) # in plain version, no clipping before applying # grads_batch_clients = [clip_gradients(item, -1 * clip, clip) # for item in grads_batch_clients] client_weight = 1.0 / num_clients start = time.time() grads = aggregate_gradients(grads_batch_clients) end_enc = time.time() print("aggregation finished in %f" % (end_enc - start)) loss_value = aggregate_losses([item * client_weight for item in loss_batch_clients]) # federated_lr_batch.py elif args.experiment == "batch": # # party A # grads_0 = clip_gradients(grads_0, -1 * clip / num_clients, clip / num_clients) # # party B # grads_1 = clip_gradients(grads_1, -1 * clip / num_clients, clip / num_clients) grads_batch_clients = [clip_gradients(item, -1 * clip / num_clients, clip / num_clients) for item in grads_batch_clients] # # party A # enc_grads_0 = [] # enc_grads_shape_0 = [] # for component in grads_0: # enc_g, enc_g_s = encryption.encrypt_matrix_batch(publickey, component.numpy(), # bit_width=q_width, r_max=clip) # enc_grads_0.append(enc_g) # enc_grads_shape_0.append(enc_g_s) # loss_value_0 = encryption.encrypt(publickey, loss_value_0) # # party B # enc_grads_1 = [] # enc_grads_shape_1 = [] # for component in grads_1: # enc_g, enc_g_s = encryption.encrypt_matrix_batch(publickey, component.numpy(), # bit_width=q_width, r_max=clip) # enc_grads_1.append(enc_g) # enc_grads_shape_1.append(enc_g_s) # loss_value_1 = encryption.encrypt(publickey, loss_value_1) enc_grads_batch_clients = [] enc_grads_shape_batch_clients = [] for grad_client in grads_batch_clients: enc_grads_client = [] enc_grads_shape_client = [] for component in grad_client: enc_g, enc_g_s = encryption.encrypt_matrix_batch(publickey, component.numpy(), bit_width=q_width, r_max=clip) enc_grads_client.append(enc_g) enc_grads_shape_client.append(enc_g_s) enc_grads_batch_clients.append(enc_grads_client) enc_grads_shape_batch_clients.append(enc_grads_shape_client) loss_batch_clients = [encryption.encrypt(publickey, item) for item in loss_batch_clients] # arbiter aggregate gradients # enc_grads = aggregate_gradients([enc_grads_0, enc_grads_1]) # loss_value = aggregate_losses([loss_value_0, loss_value_1]) enc_grads = aggregate_gradients(enc_grads_batch_clients) client_weight = 1.0 / num_clients loss_value = aggregate_losses([item * client_weight for item in loss_batch_clients]) # on party A and B individually loss_value = encryption.decrypt(privatekey, loss_value) grads = [] for i in range(len(enc_grads)): # plain_g = encryption.decrypt_matrix_batch(privatekey, enc_grads_0[i], enc_grads_shape_0[i]) plain_g = encryption.decrypt_matrix_batch(privatekey, enc_grads[i], enc_grads_shape_batch_clients[0][i]) grads.append(plain_g) # federated_lr_only_quan.py elif args.experiment == "only_quan": for idx in range(len(grads_batch_clients)): grads_batch_clients[idx] = [x.numpy() for x in grads_batch_clients[idx]] # clipping_thresholds = encryption.calculate_clip_threshold(grads_0) theta = 2.5 grads_batch_clients_mean = [] grads_batch_clients_mean_square = [] for client_idx in range(len(grads_batch_clients)): temp_mean = [np.mean(grads_batch_clients[client_idx][layer_idx]) for layer_idx in range(len(grads_batch_clients[client_idx]))] temp_mean_square = [np.mean(grads_batch_clients[client_idx][layer_idx] ** 2) for layer_idx in range(len(grads_batch_clients[client_idx]))] grads_batch_clients_mean.append(temp_mean) grads_batch_clients_mean_square.append(temp_mean_square) grads_batch_clients_mean = np.array(grads_batch_clients_mean) grads_batch_clients_mean_square = np.array(grads_batch_clients_mean_square) layers_size = np.array([_.size for _ in grads_batch_clients[0]]) clipping_thresholds = theta * ( np.sum(grads_batch_clients_mean_square * layers_size, 0) / (layers_size * num_clients) - (np.sum(grads_batch_clients_mean * layers_size, 0) / (layers_size * num_clients)) ** 2) ** 0.5 print("clipping_thresholds", clipping_thresholds) # r_maxs = [x * 2 for x in clipping_thresholds] r_maxs = [x * num_clients for x in clipping_thresholds] # grads_0 = encryption.clip_with_threshold(grads_0, clipping_thresholds) # grads_1 = encryption.clip_with_threshold(grads_1, clipping_thresholds) # grads_0 = quantize_per_layer(grads_0, r_maxs, bit_width=q_width) # grads_1 = quantize_per_layer(grads_1, r_maxs, bit_width=q_width) grads_batch_clients = [encryption.clip_with_threshold(item, clipping_thresholds) for item in grads_batch_clients] grads_batch_clients = [quantize_per_layer(item, r_maxs, bit_width=q_width) for item in grads_batch_clients] # grads = aggregate_gradients([grads_0, grads_1], weight=0.5) # loss_value = aggregate_losses([0.5 * loss_value_0, 0.5 * loss_value_1]) # grads = unquantize_per_layer(grads, r_maxs, bit_width=q_width) client_weight = 1.0 / num_clients grads = aggregate_gradients(grads_batch_clients) loss_value = aggregate_losses([item * client_weight for item in loss_batch_clients]) grads = unquantize_per_layer(grads, r_maxs, bit_width=q_width) elif args.experiment == "aciq_quan": sizes = [tf.size(item).numpy() * num_clients for item in grads_batch_clients[0]] max_values = [] min_values = [] for layer_idx in range(len(grads_batch_clients[0])): max_values.append([np.max([item[layer_idx] for item in grads_batch_clients])]) min_values.append([np.min([item[layer_idx] for item in grads_batch_clients])]) grads_max_min = np.concatenate([np.array(max_values),np.array(min_values)], axis=1) clipping_thresholds = encryption.calculate_clip_threshold_aciq_g(grads_max_min, sizes, bit_width=q_width) r_maxs = [x * num_clients for x in clipping_thresholds] grads_batch_clients = [encryption.clip_with_threshold(item, clipping_thresholds) for item in grads_batch_clients] grads_batch_clients = [quantize_per_layer(item, r_maxs, bit_width=q_width) for item in grads_batch_clients] grads = aggregate_gradients(grads_batch_clients) client_weight = 1.0 / num_clients loss_value = aggregate_losses([item * client_weight for item in loss_batch_clients]) grads = unquantize_per_layer(grads, r_maxs, bit_width=q_width) ###### optimizer.apply_gradients(zip(grads, model.trainable_variables), global_step) # Track progress epoch_loss_avg(loss_value) # add current batch loss # compare predicted label to actual label # epoch_accuracy(tf.argmax(model(x), axis=1, output_type=tf.int32), y) epoch_accuracy(tf.argmax(model(test_images), axis=1, output_type=tf.int32), test_labels) loss_array.append(loss_value) accuracy_value = epoch_accuracy.result().numpy() accuracy_array.append(accuracy_value) elapsed_time = time.time() - start_t print( "loss: {} \taccuracy: {} \telapsed time: {}".format(loss_value, accuracy_value, elapsed_time) ) # end epoch train_loss_results.append(epoch_loss_avg.result()) train_accuracy_results.append(epoch_accuracy.result()) test_loss_v = loss(model, test_images, test_labels) test_accuracy_v = accuracy_score(test_labels, tf.argmax(model(test_images), axis=1, output_type=tf.int32)) test_loss_results.append(test_loss_v) test_accuracy_results.append(test_accuracy_v) if epoch % 1 == 0: print("Epoch {:03d}: Loss: {:.3f}, Accuracy: {:.3%}".format(epoch, epoch_loss_avg.result(), epoch_accuracy.result())) model.save_weights("model_{}_e{:03d}.h5".format(output_name, epoch)) print("Saved model to disk") np.savetxt('train_loss_{}.txt'.format(output_name), train_loss_results) np.savetxt('train_accuracy_{}.txt'.format(output_name), train_accuracy_results) np.savetxt('test_loss_{}.txt'.format(output_name), test_loss_results) np.savetxt('test_accuracy_{}.txt'.format(output_name), test_accuracy_results) # serialize model to JSON model_json = model.to_json() with open("model_{}.json".format(output_name), "w") as json_file: json_file.write(model_json) # serialize weights to HDF5 model.save_weights("model_{}.h5".format(output_name)) print("Saved model to disk") fig, axes = plt.subplots(2, sharex=True, figsize=(12, 8)) fig.suptitle('Training Metrics') axes[0].set_ylabel("Loss", fontsize=14) axes[0].plot(train_loss_results) axes[1].set_ylabel("Accuracy", fontsize=14) axes[1].set_xlabel("Epoch", fontsize=14) axes[1].plot(train_accuracy_results) plt.show() <file_sep>/accuracy_eval/test_10parties/federated_lr_alex_experiments.py import time import argparse import tensorflow as tf from tensorflow import keras import numpy as np from sklearn.metrics import accuracy_score import pysnooper from functools import reduce from ftl import augmentation from ftl.encryption import paillier, encryption tf.enable_eager_execution() from tensorflow import contrib from joblib import Parallel, delayed import multiprocessing N_JOBS = multiprocessing.cpu_count() tfe = contrib.eager print("TensorFlow version: {}".format(tf.__version__)) print("Eager execution: {}".format(tf.executing_eagerly())) # epochs = 200 num_classes = 10 # The data, split between train and test sets: (x_train, y_train), (x_test, y_test) = keras.datasets.cifar10.load_data() print('x_train shape:', x_train.shape) print('y_train shape:', y_train.shape) print(x_train.shape[0], 'train samples') print(x_test.shape[0], 'test samples') # x_train = x_train[:1000] # y_train = y_train[:1000] x_train = x_train.astype('float32') x_test = x_test.astype('float32') x_train /= 255 x_test /= 255 y_train = y_train.squeeze().astype(np.int32) y_test = y_test.squeeze().astype(np.int32) def build_datasets(num_clients): # split_idx = int(len(x_train) / num_clients) avg_length = int(len(x_train) / num_clients) split_idx = [_ * avg_length for _ in range(1, num_clients)] # [x_train_0, x_train_1] = np.split(x_train, [split_idx]) # [y_train_0, y_train_1] = np.split(y_train, [split_idx]) x_train_clients = np.split(x_train, split_idx) y_train_clients = np.split(y_train, split_idx) print("{} clients building datasets.".format(len(x_train_clients))) for idx, x_train_client in enumerate(x_train_clients): print("{} client has {} data items.".format(idx, len(x_train_client))) # train_dataset_0 = tf.data.Dataset.from_tensor_slices((x_train_0, y_train_0)) # train_dataset_1 = tf.data.Dataset.from_tensor_slices((x_train_1, y_train_1)) train_dataset_clients = [tf.data.Dataset.from_tensor_slices(item) for item in zip(x_train_clients, y_train_clients)] # train_dataset_0 = train_dataset_0.map( # augmentation.augment_img, # num_parallel_calls=N_JOBS) # train_dataset_0 = train_dataset_0.map(lambda x, y: (tf.clip_by_value(x, 0, 1), y)) # train_dataset_1 = train_dataset_1.map( # augmentation.augment_img, # num_parallel_calls=N_JOBS) # train_dataset_1 = train_dataset_1.map(lambda x, y: (tf.clip_by_value(x, 0, 1), y)) BATCH_SIZE = 128 SHUFFLE_BUFFER_SIZE = 1000 # train_dataset_0 = train_dataset_0.shuffle(SHUFFLE_BUFFER_SIZE, reshuffle_each_iteration=True).batch(BATCH_SIZE) # train_dataset_1 = train_dataset_1.shuffle(SHUFFLE_BUFFER_SIZE, reshuffle_each_iteration=True).batch(BATCH_SIZE) for i in range(len(train_dataset_clients)): train_dataset_clients[i] = train_dataset_clients[i].map( augmentation.augment_img, num_parallel_calls=N_JOBS) train_dataset_clients[i] = train_dataset_clients[i].map(lambda x, y: (tf.clip_by_value(x, 0, 1), y)) train_dataset_clients[i] = train_dataset_clients[i].shuffle(SHUFFLE_BUFFER_SIZE, reshuffle_each_iteration=True).batch(BATCH_SIZE) # return train_dataset_0, train_dataset_1 return train_dataset_clients model = keras.Sequential() model.add(keras.layers.Conv2D(32, (3, 3), padding='same', input_shape=x_train.shape[1:])) model.add(keras.layers.Activation('relu')) model.add(keras.layers.Conv2D(32, (3, 3))) model.add(keras.layers.Activation('relu')) model.add(keras.layers.MaxPooling2D(pool_size=(2, 2))) model.add(keras.layers.Dropout(0.25)) model.add(keras.layers.Conv2D(64, (3, 3), padding='same')) model.add(keras.layers.Activation('relu')) model.add(keras.layers.Conv2D(64, (3, 3))) model.add(keras.layers.Activation('relu')) model.add(keras.layers.MaxPooling2D(pool_size=(2, 2))) model.add(keras.layers.Dropout(0.25)) model.add(keras.layers.Flatten()) model.add(keras.layers.Dense(512)) model.add(keras.layers.Activation('relu')) model.add(keras.layers.Dropout(0.5)) model.add(keras.layers.Dense(num_classes)) model.add(keras.layers.Activation('softmax')) model.summary() cce = tf.keras.losses.SparseCategoricalCrossentropy() def loss(model, x, y): y_ = model(x) return cce(y_true=y, y_pred=y_) def grad(model, inputs, targets): with tf.GradientTape() as tape: loss_value = loss(model, inputs, targets) return loss_value, tape.gradient(loss_value, model.trainable_variables) optimizer = keras.optimizers.RMSprop(learning_rate=0.0001, decay=1e-6) global_step = tf.Variable(0) def clip_gradients(grads, min_v, max_v): results = [tf.clip_by_value(t, min_v, max_v).numpy() for t in grads] return results def do_sum(x1, x2): results = [] for i in range(len(x1)): results.append(x1[i] + x2[i]) return results def aggregate_gradients(gradient_list, weight=0.5): # def multiply_by_weight(party, w): # for i in range(len(party)): # party[i] = w * party[i] # return party # gradient_list = Parallel(n_jobs=2)(delayed(multiply_by_weight)(party, weight) for party in gradient_list) results = reduce(do_sum, gradient_list) return results def aggregate_losses(loss_list): return np.sum(loss_list) def batch_enc_per_layer(publickey, party, r_maxs, bit_width=16, batch_size=100): result = [] og_shapes = [] for layer, r_max in zip(party, r_maxs): enc, shape_ = encryption.encrypt_matrix_batch(publickey, layer, batch_size=batch_size, bit_width=bit_width, r_max=r_max) result.append(enc) og_shapes.append(shape_) return result, og_shapes def batch_dec_per_layer(privatekey, party, og_shapes, r_maxs, bit_width=16, batch_size=100): result = [] for layer, r_max, og_shape in zip(party, r_maxs, og_shapes): result.append( encryption.decrypt_matrix_batch(privatekey, layer, og_shape, batch_size=batch_size, bit_width=bit_width, r_max=r_max).astype(np.float32)) return np.array(result) def quantize(party, bit_width=16, r_max=0.5): result = [] for component in party: x, _ = encryption.quantize_matrix(component, bit_width=bit_width, r_max=r_max) result.append(x) return np.array(result) def quantize_per_layer(party, r_maxs, bit_width=16): # result = [] # for component, r_max in zip(party, r_maxs): # x, _ = encryption.quantize_matrix_stochastic(component, bit_width=bit_width, r_max=r_max) # result.append(x) result = Parallel(n_jobs=N_JOBS)( delayed(encryption.quantize_matrix_stochastic)(component, bit_width=bit_width, r_max=r_max) for component, r_max in zip(party, r_maxs)) result = np.array(result)[:, 0] return result def unquantize(party, bit_width=16, r_max=0.5): result = [] for component in party: result.append(encryption.unquantize_matrix(component, bit_width=bit_width, r_max=r_max).astype(np.float32)) return np.array(result) def unquantize_per_layer(party, r_maxs, bit_width=16): # result = [] # for component, r_max in zip(party, r_maxs): # result.append(encryption.unquantize_matrix(component, bit_width=bit_width, r_max=r_max).astype(np.float32)) result = Parallel(n_jobs=N_JOBS)( delayed(encryption.unquantize_matrix)(component, bit_width=bit_width, r_max=r_max) for component, r_max in zip(party, r_maxs) ) return np.array(result) if __name__ == '__main__': seed = 123 tf.random.set_random_seed(seed) np.random.seed(seed) parser = argparse.ArgumentParser() parser.add_argument('--experiment', type=str, default='plain_alex', choices=["plain_alex", "plain_alex_en", "en_alex_batch", "aciq_quan"]) parser.add_argument('--num_clients', type=int, default=10) parser.add_argument('--num_epochs', type=int, default=10) parser.add_argument('--batch_size', type=int, default=100) parser.add_argument('--q_width', type=int, default=16) args = parser.parse_args() print(args) # keep results for plotting train_loss_results = [] train_accuracy_results = [] test_loss_results = [] test_accuracy_results = [] num_epochs = args.num_epochs publickey, privatekey = paillier.PaillierKeypair.generate_keypair(n_length=2048) for epoch in range(num_epochs): epoch_train_loss_avg = tfe.metrics.Mean() epoch_train_accuracy = tfe.metrics.Accuracy() # train_dataset_0, train_dataset_1 = build_datasets() train_dataset_clients = build_datasets(args.num_clients) # for (x_0, y_0), (x_1, y_1) in zip(train_dataset_0, train_dataset_1): for data_clients in zip(*train_dataset_clients): print("{} clients are in federated training".format(len(data_clients))) loss_batch_clients = [] grads_batch_clients = [] start_t = time.time() # Optimize the model # loss_value_0, grads_0 = grad(model, x_0, y_0) # loss_value_1, grads_1 = grad(model, x_1, y_1) # loss_value_0 = loss_value_0.numpy() # loss_value_1 = loss_value_1.numpy() # grads = [x.numpy() for x in grads] # grads_0 = [x.numpy() for x in grads_0] # grads_1 = [x.numpy() for x in grads_1] # calculate loss and grads locally for x, y in data_clients: loss_temp, grads_temp = grad(model, x, y) loss_batch_clients.append(loss_temp.numpy()) grads_batch_clients.append([x.numpy() for x in grads_temp]) if args.experiment == "plain_alex": start = time.time() grads = aggregate_gradients(grads_batch_clients) end_enc = time.time() print("aggregation finished in %f" % (end_enc - start)) client_weight = 1.0 / args.num_clients loss_value = aggregate_losses([item * client_weight for item in loss_batch_clients]) elif args.experiment == "plain_alex_en": # grads_0 = [encryption.encrypt_matrix(publickey, x) for x in grads_0] # grads_1 = [encryption.encrypt_matrix(publickey, x) for x in grads_1] # loss_value_0 = encryption.encrypt(publickey, loss_value_0) # loss_value_1 = encryption.encrypt(publickey, loss_value_1) loss_batch_clients = [encryption.encrypt(publickey, item) for item in loss_batch_clients] grads_batch_clients = [[encryption.encrypt_matrix(publickey, x) for x in item] for item in grads_batch_clients] # grads = aggregate_gradients([grads_0, grads_1]) # loss_value = aggregate_losses([0.5 * loss_value_0, 0.5 * loss_value_1]) grads = aggregate_gradients(grads_batch_clients) client_weight = 1.0 / args.num_clients loss_value = aggregate_losses([item * client_weight for item in loss_batch_clients]) loss_value = encryption.decrypt(privatekey, loss_value) grads = [encryption.decrypt_matrix(privatekey, x).astype(np.float32) for x in grads] # federated_lr_en_alex_batch.py part elif args.experiment == "en_alex_batch": theta = 2.5 # clipping_thresholds = encryption.calculate_clip_threshold(grads_0) return [theta * np.std(x) for x in grads] # theta = 2.5 # calculate global std by combination, clients send E(X^2), E(X), and layerwise sizes to the server # std = E(X^2) - (E(X))^2 grads_batch_clients_mean = [] grads_batch_clients_mean_square = [] for client_idx in range(len(grads_batch_clients)): temp_mean = [np.mean(grads_batch_clients[client_idx][layer_idx]) for layer_idx in range(len(grads_batch_clients[client_idx]))] temp_mean_square = [np.mean(grads_batch_clients[client_idx][layer_idx] ** 2) for layer_idx in range(len(grads_batch_clients[client_idx]))] grads_batch_clients_mean.append(temp_mean) grads_batch_clients_mean_square.append(temp_mean_square) grads_batch_clients_mean = np.array(grads_batch_clients_mean) grads_batch_clients_mean_square = np.array(grads_batch_clients_mean_square) layers_size = np.array([_.size for _ in grads_batch_clients[0]]) clipping_thresholds = theta * ( np.sum(grads_batch_clients_mean_square * layers_size, 0) / (layers_size * num_clients) - (np.sum(grads_batch_clients_mean * layers_size, 0) / (layers_size * num_clients)) ** 2) ** 0.5 print("clipping_thresholds", clipping_thresholds) r_maxs = [x * args.num_clients for x in clipping_thresholds] # grads_0 = encryption.clip_with_threshold(grads_0, clipping_thresholds) # grads_1 = encryption.clip_with_threshold(grads_1, clipping_thresholds) grads_batch_clients = [encryption.clip_with_threshold(item, clipping_thresholds) for item in grads_batch_clients] # enc_grads_0, og_shape_0 = batch_enc_per_layer(publickey=publickey, party=grads_0, r_maxs=r_maxs, bit_width=q_width, # batch_size=batch_size) # enc_grads_1, og_shape_1 = batch_enc_per_layer(publickey=publickey, party=grads_1, r_maxs=r_maxs, bit_width=q_width, # batch_size=batch_size) enc_grads_batch_clients = [] og_shape_batch_clients = [] for item in grads_batch_clients: enc_grads_temp, og_shape_temp = batch_enc_per_layer(publickey=publickey, party=item, r_maxs=r_maxs, bit_width=args.q_width, batch_size=args.batch_size) enc_grads_batch_clients.append(enc_grads_temp) og_shape_batch_clients.append(og_shape_temp) # loss_value_0 = publickey.encrypt(loss_value_0) # loss_value_1 = publickey.encrypt(loss_value_1) loss_batch_clients = [publickey.encrypt(item) for item in loss_batch_clients] # grads = aggregate_gradients([enc_grads_0, enc_grads_1]) # loss_value = aggregate_losses([0.5 * loss_value_0, 0.5 * loss_value_1]) grads = aggregate_gradients(enc_grads_batch_clients) client_weight = 1.0 / args.num_clients loss_value = aggregate_losses([item * client_weight for item in loss_batch_clients]) # loss_value = encryption.decrypt(privatekey, loss_value) # grads = batch_dec_per_layer(privatekey=privatekey, party=grads, og_shapes=og_shape_0, r_maxs=r_maxs, bit_width=q_width, batch_size=batch_size) loss_value = encryption.decrypt(privatekey, loss_value) grads = batch_dec_per_layer(privatekey=privatekey, party=grads, og_shapes=og_shape_batch_clients[0], r_maxs=r_maxs, bit_width=args.q_width, batch_size=args.batch_size) # federated_lr_quan_alex.py elif args.experiment == "aciq_quan": sizes = [item.size * args.num_clients for item in grads_batch_clients[0]] max_values = [] min_values = [] for layer_idx in range(len(grads_batch_clients[0])): max_values.append([np.max([item[layer_idx] for item in grads_batch_clients])]) min_values.append([np.min([item[layer_idx] for item in grads_batch_clients])]) grads_max_min = np.concatenate([np.array(max_values),np.array(min_values)],axis=1) clipping_thresholds = encryption.calculate_clip_threshold_aciq_g(grads_max_min, sizes, bit_width=args.q_width) r_maxs = [x * args.num_clients for x in clipping_thresholds] # grads_0 = encryption.clip_with_threshold(grads_0, clipping_thresholds) # grads_1 = encryption.clip_with_threshold(grads_1, clipping_thresholds) grads_batch_clients = [encryption.clip_with_threshold(item, clipping_thresholds) for item in grads_batch_clients] # grads_0 = quantize_per_layer(grads_0, r_maxs, bit_width=q_width) # grads_1 = quantize_per_layer(grads_1, r_maxs, bit_width=q_width) grads_batch_clients = [quantize_per_layer(item, r_maxs, bit_width=args.q_width) for item in grads_batch_clients] # grads = aggregate_gradients([grads_0, grads_1]) # loss_value = aggregate_losses([0.5 * loss_value_0, 0.5 * loss_value_1]) grads = aggregate_gradients(grads_batch_clients) client_weight = 1.0 / args.num_clients loss_value = aggregate_losses([item * client_weight for item in loss_batch_clients]) # grads = unquantize_per_layer(grads, r_maxs, bit_width=q_width) grads = unquantize_per_layer(grads, r_maxs, bit_width=args.q_width) ####### optimizer.apply_gradients(zip(grads, model.trainable_variables), global_step) elapsed_time = time.time() - start_t print('loss: {} \telapsed time: {}'.format(loss_value, elapsed_time)) # Track progress epoch_train_loss_avg(loss_value) # add current batch loss # compare predicted label to actual label # epoch_train_accuracy(tf.argmax(model(tf.concat([x_0, x_1], axis=0)), axis=1, output_type=tf.int32), # tf.concat([y_0, y_1], axis=0)) epoch_train_accuracy( tf.argmax(model(tf.concat([data_item[0] for data_item in data_clients], axis=0)), axis=1, output_type=tf.int32), tf.concat([data_item[1] for data_item in data_clients], axis=0)) # end epoch train_loss_v = epoch_train_loss_avg.result() train_accuracy_v = epoch_train_accuracy.result() test_loss_v = loss(model, x_test, y_test) test_accuracy_v = accuracy_score(y_test, tf.argmax(model(x_test), axis=1, output_type=tf.int32)) train_loss_results.append(train_loss_v) train_accuracy_results.append(train_accuracy_v) test_loss_results.append(test_loss_v) test_accuracy_results.append(test_accuracy_v) print( "Epoch {:03d}: train_loss: {:.3f}, train_accuracy: {:.3%}, test_loss: {:.3f}, test_accuracy: {:.3%}".format( epoch, train_loss_v, train_accuracy_v, test_loss_v, test_accuracy_v)) # serialize weights to HDF5 model.save_weights("model_alex_b{:02d}_{}_e{:03d}.h5".format(args.q_width, args.experiment, epoch)) print("Saved model to disk") np.savetxt('alex_v_train_loss_b{:02d}_final_{}.txt'.format(args.q_width, args.experiment), train_loss_results) np.savetxt('alex_v_train_accuracy_b{:02d}_final_{}.txt'.format(args.q_width, args.experiment), train_accuracy_results) np.savetxt('alex_v_test_loss_b{:02d}_final_{}.txt'.format(args.q_width, args.experiment), test_loss_results) np.savetxt('alex_v_test_accuracy_b{:02d}_final_{}.txt'.format(args.q_width, args.experiment), test_accuracy_results) # serialize model to JSON model_json = model.to_json() with open("model_alex_b{:02d}_{}.json".format(args.q_width, args.experiment), "w") as json_file: json_file.write(model_json) # serialize weights to HDF5 model.save_weights("model_alex_b{:02d}_{}.h5".format(args.q_width, args.experiment)) print("Saved model to disk") <file_sep>/FATE_plugin/federatedml/linear_model/logistic_regression/homo_zcl_fmnist_batch/homo_lr_arbiter.py #!/usr/bin/env python # -*- coding: utf-8 -*- # # Copyright 2019 The FATE Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import numpy as np from functools import reduce from arch.api.utils import log_utils from federatedml.framework.gradients import Gradients from federatedml.framework.homo.procedure import aggregator from federatedml.framework.homo.procedure import paillier_cipher from federatedml.linear_model.linear_model_weight import LinearModelWeights as LogisticRegressionWeights from federatedml.linear_model.logistic_regression.homo_zcl_fmnist_batch.homo_lr_base import HomoLRBase from federatedml.optim import activation from federatedml.secureprotol import PaillierEncrypt, batch_encryption from federatedml.util import consts LOGGER = log_utils.getLogger() class HomoLRArbiter(HomoLRBase): def __init__(self): super(HomoLRArbiter, self).__init__() self.re_encrypt_times = [] # Record the times needed for each host self.loss_history = [] self.is_converged = False self.role = consts.ARBITER self.aggregator = aggregator.Arbiter() self.model_weights = None self.cipher = paillier_cipher.Arbiter() self.host_predict_results = [] def _init_model(self, params): super()._init_model(params) self.cipher.register_paillier_cipher(self.transfer_variable) def fit(self, data_instances=None, validate_data=None): host_ciphers = self.cipher.paillier_keygen(key_length=self.model_param.encrypt_param.key_length, suffix=('fit',)) num_host = len(host_ciphers) host_has_no_cipher_ids = [idx for idx, cipher in host_ciphers.items() if cipher is None] self.re_encrypt_times = self.cipher.set_re_cipher_time(host_ciphers) max_iter = self.max_iter validation_strategy = self.init_validation_strategy() self.__synchronize_encryption() self.transfer_variable.num_party.remote(obj=(0, num_host + 1), role=consts.GUEST, idx=0, suffix=('train',)) # self.transfer_variable.num_party.remote(num_host + 1, role=consts.HOST, idx=-1, suffix=('train',)) for _idx, _cipher in enumerate(host_ciphers): self.transfer_variable.num_party.remote((_idx + 1, num_host + 1), role=consts.HOST, idx=_idx, suffix=('train',)) for iter_num in range(self.max_iter): # re_encrypt host models # self.__re_encrypt(iter_num) batch_num = 0 while batch_num >= 0: LOGGER.info("Staring batch {}".format(batch_num)) LOGGER.info("Collecting grads & loss") guest_grad = self.transfer_variable.guest_grad.get(idx=0, suffix=(iter_num, batch_num)) # guest_grad = np.array(guest_grad.unboxed) guest_grad = np.array(guest_grad) # LOGGER.debug(guest_grad.shape) guest_loss = self.transfer_variable.guest_loss.get(idx=0, suffix=(iter_num, batch_num)) # guest_model = np.array(guest_model) LOGGER.info("received guest grads & loss") host_grads = self.transfer_variable.host_grad.get(idx=-1, suffix=(iter_num, batch_num)) # host_grads = [np.array(x.unboxed) for x in host_grads] host_grads = [np.array(x) for x in host_grads] # [LOGGER.debug(x.shape) for x in host_grads] host_losses = self.transfer_variable.host_loss.get(idx=-1, suffix=(iter_num, batch_num)) LOGGER.info("received host grads & loss") host_grads.append(guest_grad) # LOGGER.debug(host_grads.shape) host_losses.append(guest_loss) sum_grads = self.__aggregate_grads(host_grads) # sum_grads = batch_encryption.aggregate_gradients_old(host_grads) sum_loss = self.__aggregate_losses(host_losses) LOGGER.info("Grads and loss aggregated") # sum_grads = Gradients(sum_grads) self.transfer_variable.aggregated_grad.remote(obj=sum_grads, role=consts.GUEST, idx=0, suffix=(iter_num, batch_num)) self.transfer_variable.aggregated_grad.remote(obj=sum_grads, role=consts.HOST, idx=-1, suffix=(iter_num, batch_num)) # self.transfer_variable.aggregated_grad.remote(obj=sum_grads.for_remote(), role=consts.GUEST, idx=0, suffix=(iter_num, batch_num)) # self.transfer_variable.aggregated_grad.remote(obj=sum_grads.for_remote(), role=consts.HOST, idx=-1, suffix=(iter_num, batch_num)) LOGGER.info("Dispatched all grads") self.transfer_variable.aggregated_loss.remote(obj=sum_loss, role=consts.GUEST, idx=0, suffix=(iter_num, batch_num)) self.transfer_variable.aggregated_loss.remote(obj=sum_loss, role=consts.HOST, idx=-1, suffix=(iter_num, batch_num)) LOGGER.info("Dispatched all losses") batch_num += 1 # if batch_num >= self.zcl_early_stop_batch: # return def __synchronize_encryption(self, mode='train'): """ Communicate with hosts. Specify whether use encryption or not and transfer the public keys. """ # 2. Send pubkey to those use-encryption guest & hosts encrypter = PaillierEncrypt() encrypter.generate_key(self.key_length) pub_key = encrypter.get_public_key() # LOGGER.debug("Start to remote pub_key: {}, transfer_id: {}".format(pub_key, pubkey_id)) self.transfer_variable.paillier_pubkey.remote(obj=pub_key, role=consts.GUEST, idx=0, suffix=(mode,)) LOGGER.info("send pubkey to guest") pri_key = encrypter.get_privacy_key() self.transfer_variable.paillier_prikey.remote(obj=pri_key, role=consts.GUEST, idx=0, suffix=(mode,)) # LOGGER.debug("Start to remote pri_key: {}, transfer_id: {}".format(pri_key, prikey_id)) LOGGER.info("send prikey to guest") self.transfer_variable.paillier_pubkey.remote(obj=pub_key, role=consts.HOST, idx=-1, suffix=(mode,)) LOGGER.info("send pubkey to host") self.transfer_variable.paillier_prikey.remote(obj=pri_key, role=consts.HOST, idx=-1, suffix=(mode,)) LOGGER.info("send prikey to host") def __aggregate_grads(self, grad_list): def do_sum(x1, x2): results = [] for i in range(len(x1)): results.append(x1[i] + x2[i]) return results results_ = reduce(do_sum, grad_list) return results_ def __aggregate_grads_(self, gradient_list, weight=0.5): results = np.add.reduce(gradient_list) return results def __aggregate_losses(self, loss_list): return np.sum(loss_list) def predict(self, data_instantces=None): LOGGER.info(f'Start predict task') current_suffix = ('predict',) host_ciphers = self.cipher.paillier_keygen(key_length=self.model_param.encrypt_param.key_length, suffix=current_suffix) LOGGER.debug("Loaded arbiter model: {}".format(self.model_weights.unboxed)) for idx, cipher in host_ciphers.items(): if cipher is None: continue encrypted_model_weights = self.model_weights.encrypted(cipher, inplace=False) self.transfer_variable.aggregated_model.remote(obj=encrypted_model_weights.for_remote(), role=consts.HOST, idx=idx, suffix=current_suffix) # Receive wx results for idx, cipher in host_ciphers.items(): if cipher is None: continue encrypted_predict_wx = self.transfer_variable.predict_wx.get(idx=idx, suffix=current_suffix) predict_wx = cipher.distribute_decrypt(encrypted_predict_wx) prob_table = predict_wx.mapValues(lambda x: activation.sigmoid(x)) predict_table = prob_table.mapValues(lambda x: 1 if x > self.model_param.predict_param.threshold else 0) self.transfer_variable.predict_result.remote(predict_table, role=consts.HOST, idx=idx, suffix=current_suffix) self.host_predict_results.append((prob_table, predict_table)) def run(self, component_parameters=None, args=None): self._init_runtime_parameters(component_parameters) data_sets = args["data"] data_statement_dict = list(data_sets.values())[0] need_eval = False for data_key in data_sets: if 'eval_data' in data_sets[data_key]: need_eval = True LOGGER.debug("data_sets: {}, data_statement_dict: {}".format(data_sets, data_statement_dict)) if self.need_cv: LOGGER.info("Task is cross validation.") self.cross_validation(None) return elif not "model" in args: LOGGER.info("Task is fit") self.set_flowid('fit') self.fit() self.set_flowid('predict') self.predict() if need_eval: self.set_flowid('validate') self.predict() else: LOGGER.info("Task is predict") self._load_model(args) self.set_flowid('predict') self.predict() <file_sep>/accuracy_eval/test_10parties/utils.py def assert_matrix(X, Y): assert X.shape[0] == X.shape[0] assert Y.shape[1] == Y.shape[1] row_num = X.shape[0] col_num = Y.shape[1] for row in range(row_num): for col in range(col_num): assert X[row][col] == Y[row][col] <file_sep>/FATE_plugin/federatedml/framework/gradients.py # # Copyright 2019 The FATE Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # import abc import operator from arch.api.utils import log_utils import numpy as np from arch.api.utils.splitable import segment_transfer_enabled from federatedml.secureprotol.encrypt import Encrypt LOGGER = log_utils.getLogger() FRAGMENT_16M = 0x1000000 FRAGMENT_24M = 0x1100000 class TransferableGradients(metaclass=segment_transfer_enabled(max_part_size=FRAGMENT_24M)): def __init__(self, gradients, cls, *args, **kwargs): self._gradients = gradients self._cls = cls if args: self._args = args if kwargs: self._kwargs = kwargs @property def unboxed(self): return self._gradients @property def gradients(self): if not hasattr(self, "_args") and not hasattr(self, "_kwargs"): return self._cls(self._gradients) else: args = self._args if hasattr(self, "_args") else () kwargs = self._kwargs if hasattr(self, "_kwargs") else {} return self._cls(self._gradients, *args, **kwargs) class Gradients(object): def __init__(self, g): self._gradients = g def for_remote(self): return TransferableGradients(self._gradients, self.__class__) @property def unboxed(self): return self._gradients <file_sep>/FATE_plugin/profile/net_tools.py import os import json import fcntl import datetime from pympler import asizeof OUTPUT_PATH = '/data/profile/network_logs/latest' LOGS_PATH = '/data/profile/network_logs/latest/logs.txt' def sz(size): units = ['b', 'kb', 'mb', 'gb', 'tb'] unit_index = 0 while size >= 1024.0 and unit_index < 4: unit_index += 1 size /= 1024.0 return f'{size:.3f} {units[unit_index]}' class netstat: def __init__(self, job_id, job_name, action, tag, src, src_role, dst, dst_role): """ Add a log record to preset file :param job_id: id of the overall job :param job_name: name of the transmission job :param action: can be "recv" or "send" :param tag: identifier of the transmission job :param src: initiator of the transmission :param src_role: role of the initiator :param dst: receiver of the transmission :param dst_role: role of the receiver """ self.job_id = job_id self.job_name = job_name self.action = action self.tag = tag self.src = f'[{src_role}] {src}' self.dst = f'[{dst_role}] {dst}' self.size = 0 def tick(self): self.start = datetime.datetime.now() def tock(self): self.end = datetime.datetime.now() def add_size(self, obj): self.size += asizeof.asizeof(obj) def add_log(self): filename = os.path.join(OUTPUT_PATH, f'{self.job_id}.log') lockname = os.path.join(OUTPUT_PATH, f'{self.job_id}.lock') if not os.path.exists(lockname): with open(lockname, 'w') as f: f.write('') with open(lockname, 'r') as lock: fcntl.flock(lock.fileno(), fcntl.LOCK_EX) if not os.path.exists(filename): with open(filename, 'w') as f: init_data = { 'job' : self.job_id, 'logs' : [], } json.dump(init_data, f) data = None with open(filename, 'r') as f: data = json.load(f) with open(filename, 'w') as f: det = { 'job_name' : str(self.job_name), 'action' : str(self.action), 'tag' : str(self.tag), 'src' : str(self.src), 'dst' : str(self.dst), 'start' : str(self.start), 'elapse' : str(self.end - self.start), 'size' : sz(self.size), 'bsize' : self.size } data['logs'].append(det) json.dump(data, f)<file_sep>/FATE_plugin/profile/mem_stat.py import os import datetime import threading import random PATH = '/data/profile/network_logs/memory_usage.log' last_used = -100.0 last_free = -100.0 def run(sec): global last_used global last_free t = threading.Timer(sec, run, [sec]) tot_m, used_m, free_m = map(int, os.popen('free -t -m').readlines()[-1].split()[1:]) ratio_used = used_m * 100.0 / tot_m ratio_free = free_m * 100.0 / tot_m if abs(ratio_used - last_used) > 0.1 or abs(ratio_free - last_free) > 0.1: last_used = ratio_used last_free = ratio_free with open(PATH, 'a+') as f: f.write(f'[{str(datetime.datetime.now())}] Used: {ratio_used:.2f}% | Free: {ratio_free:.2f}%\n') t.start() if __name__ == '__main__': run(3.0) <file_sep>/FATE_plugin/federatedml/linear_model/logistic_regression/homo_zcl_fmnist/homo_lr_guest.py #!/usr/bin/env python # -*- coding: utf-8 -*- # # Copyright 2019 The FATE Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import os import time import functools import multiprocessing import numpy as np import tensorflow as tf from tensorflow import keras from tensorflow import contrib from sklearn.metrics import accuracy_score from arch.api.utils import log_utils from federatedml.framework.gradients import Gradients from federatedml.framework.homo.procedure import aggregator from federatedml.linear_model.linear_model_weight import LinearModelWeights as LogisticRegressionWeights from federatedml.linear_model.logistic_regression.homo_zcl_fmnist.homo_lr_base import HomoLRBase from federatedml.model_selection import MiniBatch from federatedml.optim.gradient.homo_lr_gradient import LogisticGradient from federatedml.secureprotol import PaillierEncrypt, batch_encryption from federatedml.util import consts from federatedml.util import fate_operator tf.enable_eager_execution() tfe = contrib.eager LOGGER = log_utils.getLogger() N_JOBS = multiprocessing.cpu_count() LEARNING_RATE = 0.005 CUR_DIR = os.path.dirname(os.path.abspath(__file__)) MODEL_JSON_DIR = CUR_DIR + '/fmnist_init.json' MODEL_WEIGHT_DIR = CUR_DIR + '/fmnist_init.h5' class HomoLRGuest(HomoLRBase): def __init__(self): super(HomoLRGuest, self).__init__() self.gradient_operator = LogisticGradient() self.loss_history = [] self.role = consts.GUEST self.aggregator = aggregator.Guest() self.zcl_encrypt_operator = PaillierEncrypt() def _init_model(self, params): super()._init_model(params) def fit(self, data_instances, validate_data=None): self._abnormal_detection(data_instances) self.init_schema(data_instances) validation_strategy = self.init_validation_strategy(data_instances, validate_data) self.model_weights = self._init_model_variables(data_instances) max_iter = self.max_iter total_data_num = data_instances.count() mini_batch_obj = MiniBatch(data_inst=data_instances, batch_size=self.batch_size) model_weights = self.model_weights self.__synchronize_encryption() self.zcl_idx, self.zcl_num_party = self.transfer_variable.num_party.get(idx=0, suffix=('train',)) LOGGER.debug("party num:" + str(self.zcl_num_party)) self.__init_model() self.train_loss_results = [] self.train_accuracy_results = [] self.test_loss_results = [] self.test_accuracy_results = [] for iter_num in range(self.max_iter): total_loss = 0 batch_num = 0 epoch_train_loss_avg = tfe.metrics.Mean() epoch_train_accuracy = tfe.metrics.Accuracy() for train_x, train_y in self.zcl_dataset: LOGGER.info("Staring batch {}".format(batch_num)) start_t = time.time() loss_value, grads = self.__grad(self.zcl_model, train_x, train_y) loss_value = loss_value.numpy() grads = [x.numpy() for x in grads] LOGGER.info("Start encrypting") loss_value = batch_encryption.encrypt(self.zcl_encrypt_operator.get_public_key(), loss_value) grads = [batch_encryption.encrypt_matrix(self.zcl_encrypt_operator.get_public_key(), x) for x in grads] grads = Gradients(grads) LOGGER.info("Finish encrypting") # grads = self.encrypt_operator.get_public_key() self.transfer_variable.guest_grad.remote(obj=grads.for_remote(), role=consts.ARBITER, idx=0, suffix=(iter_num, batch_num)) LOGGER.info("Sent grads") self.transfer_variable.guest_loss.remote(obj=loss_value, role=consts.ARBITER, idx=0, suffix=(iter_num, batch_num)) LOGGER.info("Sent loss") sum_grads = self.transfer_variable.aggregated_grad.get(idx=0, suffix=(iter_num, batch_num)) LOGGER.info("Got grads") sum_loss = self.transfer_variable.aggregated_loss.get(idx=0, suffix=(iter_num, batch_num)) LOGGER.info("Got loss") sum_loss = batch_encryption.decrypt(self.zcl_encrypt_operator.get_privacy_key(), sum_loss) sum_grads = [ batch_encryption.decrypt_matrix(self.zcl_encrypt_operator.get_privacy_key(), x).astype(np.float32) for x in sum_grads.unboxed] LOGGER.info("Finish decrypting") # sum_grads = np.array(sum_grads) / self.zcl_num_party self.zcl_optimizer.apply_gradients(zip(sum_grads, self.zcl_model.trainable_variables), self.zcl_global_step) elapsed_time = time.time() - start_t # epoch_train_loss_avg(loss_value) # epoch_train_accuracy(tf.argmax(self.zcl_model(train_x), axis=1, output_type=tf.int32), # train_y) self.train_loss_results.append(sum_loss) train_accuracy_v = accuracy_score(train_y, tf.argmax(self.zcl_model(train_x), axis=1, output_type=tf.int32)) self.train_accuracy_results.append(train_accuracy_v) test_loss_v = self.__loss(self.zcl_model, self.zcl_x_test, self.zcl_y_test) self.test_loss_results.append(test_loss_v) test_accuracy_v = accuracy_score(self.zcl_y_test, tf.argmax(self.zcl_model(self.zcl_x_test), axis=1, output_type=tf.int32)) self.test_accuracy_results.append(test_accuracy_v) LOGGER.info( "Epoch {:03d}, iteration {:03d}: train_loss: {:.3f}, train_accuracy: {:.3%}, test_loss: {:.3f}, " "test_accuracy: {:.3%}, elapsed_time: {:.4f}".format( iter_num, batch_num, sum_loss, train_accuracy_v, test_loss_v, test_accuracy_v, elapsed_time) ) batch_num += 1 if batch_num >= self.zcl_early_stop_batch: return self.n_iter_ = iter_num def __synchronize_encryption(self, mode='train'): """ Communicate with hosts. Specify whether use encryption or not and transfer the public keys. """ pub_key = self.transfer_variable.paillier_pubkey.get(idx=0, suffix=(mode,)) LOGGER.debug("Received pubkey") self.zcl_encrypt_operator.set_public_key(pub_key) pri_key = self.transfer_variable.paillier_prikey.get(idx=0, suffix=(mode,)) LOGGER.debug("Received prikey") self.zcl_encrypt_operator.set_privacy_key(pri_key) def __init_model(self): # self.zcl_model = keras.Sequential([ # keras.layers.Flatten(input_shape=(28, 28)), # keras.layers.Dense(128, activation=tf.nn.relu), # keras.layers.Dense(10, activation=tf.nn.softmax) # ]) # json_file = open(MODEL_JSON_DIR, 'r') loaded_model_json = json_file.read() json_file.close() loaded_model = keras.models.model_from_json(loaded_model_json) loaded_model.load_weights(MODEL_WEIGHT_DIR) self.zcl_model = loaded_model LOGGER.info("Initialed model") # The data, split between train and test sets: (x_train, y_train), (x_test, y_test) = keras.datasets.fashion_mnist.load_data() x_train = x_train.astype('float32') x_test = x_test.astype('float32') x_train /= 255.0 x_test /= 255.0 y_train = y_train.squeeze().astype(np.int32) y_test = y_test.squeeze().astype(np.int32) avg_length = int(len(x_train) / self.zcl_num_party) split_idx = [_ * avg_length for _ in range(1, self.zcl_num_party)] x_train = np.split(x_train, split_idx)[self.zcl_idx] y_train = np.split(y_train, split_idx)[self.zcl_idx] train_dataset = tf.data.Dataset.from_tensor_slices((x_train, y_train)) BATCH_SIZE = 128 SHUFFLE_BUFFER_SIZE = 1000 train_dataset = train_dataset.shuffle(SHUFFLE_BUFFER_SIZE, reshuffle_each_iteration=True).batch(BATCH_SIZE) self.zcl_dataset = train_dataset self.zcl_x_test = x_test self.zcl_y_test = y_test self.zcl_cce = tf.keras.losses.SparseCategoricalCrossentropy() self.zcl_optimizer = tf.train.AdamOptimizer(learning_rate=LEARNING_RATE) self.zcl_global_step = tf.Variable(0) def __loss(self, model, x, y): y_ = model(x) return self.zcl_cce(y_true=y, y_pred=y_) def __grad(self, model, inputs, targets): with tf.GradientTape() as tape: loss_value = self.__loss(model, inputs, targets) return loss_value, tape.gradient(loss_value, model.trainable_variables) def __clip_gradients(self, grads, min_v, max_v): results = [tf.clip_by_value(t, min_v, max_v).numpy() for t in grads] return results def predict(self, data_instances): self._abnormal_detection(data_instances) self.init_schema(data_instances) predict_wx = self.compute_wx(data_instances, self.model_weights.coef_, self.model_weights.intercept_) pred_table = self.classify(predict_wx, self.model_param.predict_param.threshold) predict_result = data_instances.mapValues(lambda x: x.label) predict_result = pred_table.join(predict_result, lambda x, y: [y, x[1], x[0], {"1": x[0], "0": 1 - x[0]}]) return predict_result <file_sep>/accuracy_eval/regularization.py import numpy as np # We create a simple class, called EarlyStoppingCheckPoint, that combines simplified version of Early Stoping and ModelCheckPoint classes from Keras. # References: # https://keras.io/callbacks/ # https://github.com/keras-team/keras/blob/master/keras/callbacks.py#L458 # https://github.com/keras-team/keras/blob/master/keras/callbacks.py#L358 class EarlyStoppingCheckPoint(object): def __init__(self, monitor, patience, file_path=None): self.model = None self.monitor = monitor self.patience = patience self.file_path = file_path self.wait = 0 self.stopped_epoch = 0 def set_model(self, model): self.model = model def on_train_begin(self): self.wait = 0 self.stopped_epoch = 0 self.best = -np.Inf def on_iteration_end(self, epoch, batch, logs=None): current = logs.get(self.monitor) if current is None: print('monitor does not available in logs') return if current > self.best: self.best = current print("find best acc: ", self.best, "at epoch:", epoch, "batch:", batch) if self.file_path is not None: self.model.save_model(self.file_path) self.wait = 0 else: self.wait += 1 if self.wait >= self.patience: self.stopped_epoch = epoch self.model.stop_training = True <file_sep>/FATE_plugin/federatedml/secureprotol/batch_encryption.py import datetime import os import shutil import tempfile import tensorflow as tf import numpy as np from numba import njit, prange import math import random from federatedml.secureprotol.fate_paillier import PaillierPublicKey, PaillierPrivateKey from federatedml.secureprotol import aciq import multiprocessing from joblib import Parallel, delayed, dump, load import warnings # import pysnooper from arch.api.utils import log_utils LOGGER = log_utils.getLogger() N_JOBS = multiprocessing.cpu_count() def encrypt(public_key: PaillierPublicKey, x): return public_key.encrypt(x) def encrypt_array(public_key: PaillierPublicKey, A): # encrypt_A = [] # for i in range(len(A)): # encrypt_A.append(public_key.encrypt(float(A[i]))) encrypt_A = Parallel(n_jobs=N_JOBS)(delayed(public_key.encrypt)(num) for num in A) return np.array(encrypt_A) def encrypt_matrix(public_key: PaillierPublicKey, A): og_shape = A.shape if len(A.shape) == 1: A = np.expand_dims(A, axis=0) # print('encrypting matrix shaped ' + str(og_shape)) A = np.reshape(A, (1, -1)) A = np.squeeze(A) # print('max = ' + str(np.amax(A))) # print('min = ' + str(np.amin(A))) # encrypt_A = [] # for i in range(len(A)): # row = [] # for j in range(len(A[i])): # if len(A.shape) == 3: # row.append([public_key.encrypt(float(A[i, j, k])) for k in range(len(A[i][j]))]) # else: # row.append(public_key.encrypt(float(A[i, j]))) # # encrypt_A.append(row) LOGGER.info("encrypt 1 matrix") encrypt_A = Parallel(n_jobs=N_JOBS)(delayed(public_key.encrypt)(num) for num in A) encrypt_A = np.expand_dims(encrypt_A, axis=0) encrypt_A = np.reshape(encrypt_A, og_shape) return np.array(encrypt_A) @njit(parallel=True) def stochastic_r(ori, frac, rand): result = np.zeros(len(ori), dtype=np.int32) for i in prange(len(ori)): if frac[i] >= 0: result[i] = np.floor(ori[i]) if frac[i] <= rand[i] else np.ceil(ori[i]) else: result[i] = np.floor(ori[i]) if (-1 * frac[i]) > rand[i] else np.ceil(ori[i]) return result def stochastic_round(ori): rand = np.random.rand(len(ori)) frac, decim = np.modf(ori) # result = np.zeros(len(ori)) # for i in range(len(ori)): # if frac[i] >= 0: # result[i] = np.floor(ori[i]) if frac[i] <= rand[i] else np.ceil(ori[i]) # else: # result[i] = np.floor(ori[i]) if (-1 * frac[i]) > rand[i] else np.ceil(ori[i]) result = stochastic_r(ori, frac, rand) return result.astype(np.int) def stochastic_round_matrix(ori): _shape = ori.shape ori = np.reshape(ori, (1, -1)) ori = np.squeeze(ori) # rand = np.random.rand(len(ori)) # frac, decim = np.modf(ori) # result = np.zeros(len(ori)) # # for i in range(len(ori)): # if frac[i] >= 0: # result[i] = np.floor(ori[i]) if frac[i] <= rand[i] else np.ceil(ori[i]) # else: # result[i] = np.floor(ori[i]) if (-1 * frac[i]) > rand[i] else np.ceil(ori[i]) result = stochastic_round(ori) result = result.reshape(_shape) return result def quantize_matrix(matrix, bit_width=8, r_max=0.5): og_sign = np.sign(matrix) uns_matrix = matrix * og_sign uns_result = (uns_matrix * (pow(2, bit_width - 1) - 1.0) / r_max) result = (og_sign * uns_result) # result = np.reshape(result, (1, -1)) # result = np.squeeze(result) # # print(result) # result = stochastic_round(result) # print(result) return result, og_sign def quantize_matrix_stochastic(matrix, bit_width=8, r_max=0.5): og_sign = np.sign(matrix) uns_matrix = matrix * og_sign uns_result = (uns_matrix * (pow(2, bit_width - 1) - 1.0) / r_max) result = (og_sign * uns_result) # result = np.reshape(result, (1, -1)) # result = np.squeeze(result) # # print(result) result = stochastic_round_matrix(result) # print(result) return result, og_sign def unquantize_matrix(matrix, bit_width=8, r_max=0.5): matrix = matrix.astype(int) og_sign = np.sign(matrix) uns_matrix = matrix * og_sign uns_result = uns_matrix * r_max / (pow(2, bit_width - 1) - 1.0) result = og_sign * uns_result return result.astype(np.float32) def true_to_two_comp(input, bit_width): def true_to_two(value, bit_width): if value < 0: return 2 ** (bit_width + 1) + value else: return value # two_strings = [np.binary_repr(x, bit_width) for x in input] # # use 2 bits for sign # result = [int(x[0] + x, 2) for x in two_strings] result = Parallel(n_jobs=N_JOBS)(delayed(true_to_two)(x, bit_width) for x in input) return np.array(result) @njit(parallel=True) def true_to_two_comp_(input, bit_width): result = np.zeros(len(input), dtype=np.int32) for i in prange(len(input)): if input[i] >= 0: result[i] = input[i] else: result[i] = 2 ** (bit_width + 1) + input[i] return result # @pysnooper.snoop('en_batch.log') def encrypt_matrix_batch(public_key: PaillierPublicKey, A, batch_size=16, bit_width=8, pad_zero=3, r_max=0.5): og_shape = A.shape if len(A.shape) == 1: A = np.expand_dims(A, axis=0) # print('encrypting matrix shaped ' + str(og_shape) + ' ' + str(datetime.datetime.now().time())) A, og_sign = quantize_matrix(A, bit_width, r_max) A = np.reshape(A, (1, -1)) A = np.squeeze(A) A = stochastic_round(A) # print("encrpting # " + str(len(A)) + " shape" + str(og_shape)+' ' + str(datetime.datetime.now().time())) A_len = len(A) # pad array at the end so tha the array is the size of A = A if (A_len % batch_size) == 0 \ else np.pad(A, (0, batch_size - (A_len % batch_size)), 'constant', constant_values=(0, 0)) # print('padded ' + str(datetime.datetime.now().time())) A = true_to_two_comp_(A, bit_width) # print([bin(x) for x in A]) # print("encrpting padded # " + str(len(A))+' ' + str(datetime.datetime.now().time())) idx_range = int(len(A) / batch_size) idx_base = list(range(idx_range)) # batched_nums = np.zeros(idx_range, dtype=int) batched_nums = np.array([pow(2, 2048)] * idx_range) batched_nums *= 0 # print(batched_nums.dtype) for i in range(batch_size): idx_filter = [i + x * batch_size for x in idx_base] # print(idx_filter) filted_num = A[idx_filter] # print([bin(x) for x in filted_num]) batched_nums = (batched_nums * pow(2, (bit_width + pad_zero))) + filted_num # print([bin(x) for x in batched_nums]) # print("encrpting batched # " + str(len(batched_nums))+' ' + str(datetime.datetime.now().time())) # print([bin(x).zfill(batch_size*(bit_width+pad_zero) + 2) + ' ' for x in batched_nums]) encrypt_A = Parallel(n_jobs=N_JOBS)(delayed(public_key.encrypt)(num) for num in batched_nums) # print('encryption done'+' ' + str(datetime.datetime.now().time())) return encrypt_A, og_shape def encrypt_matmul(public_key: PaillierPublicKey, A, encrypted_B): """ matrix multiplication between a plain matrix and an encrypted matrix :param public_key: :param A: :param encrypted_B: :return: """ if A.shape[-1] != encrypted_B.shape[0]: print("A and encrypted_B shape are not consistent") exit(1) # TODO: need a efficient way to do this? res = [[public_key.encrypt(0) for _ in range(encrypted_B.shape[1])] for _ in range(len(A))] for i in range(len(A)): for j in range(encrypted_B.shape[1]): for m in range(len(A[i])): res[i][j] += A[i][m] * encrypted_B[m][j] return np.array(res) def encrypt_matmul_3(public_key: PaillierPublicKey, A, encrypted_B): if A.shape[0] != encrypted_B.shape[0]: print("A and encrypted_B shape are not consistent") print(A.shape) print(encrypted_B.shape) exit(1) res = [] for i in range(len(A)): res.append(encrypt_matmul(public_key, A[i], encrypted_B[i])) return np.array(res) def decrypt(private_key: PaillierPrivateKey, x): return private_key.decrypt(x) def decrypt_scalar(private_key: PaillierPrivateKey, x): return private_key.decrypt(x) def decrypt_array(private_key: PaillierPrivateKey, X): decrypt_x = [] for i in range(X.shape[0]): elem = private_key.decrypt(X[i]) decrypt_x.append(elem) return decrypt_x def encrypt_array(private_key: PaillierPrivateKey, X): decrpt_X = Parallel(n_jobs=N_JOBS)(delayed(private_key.decrypt())(num) for num in X) return np.array(decrpt_X) def decrypt_matrix(private_key: PaillierPrivateKey, A): og_shape = A.shape if len(A.shape) == 1: A = np.expand_dims(A, axis=0) A = np.reshape(A, (1, -1)) A = np.squeeze(A) # decrypt_A = [] # for i in range(len(A)): # row = [] # for j in range(len(A[i])): # if len(A.shape) == 3: # row.append([private_key.decrypt(A[i, j, k]) for k in range(len(A[i][j]))]) # else: # row.append(private_key.decrypt(A[i, j])) # decrypt_A.append(row) decrypt_A = Parallel(n_jobs=N_JOBS)(delayed(private_key.decrypt)(num) for num in A) decrypt_A = np.expand_dims(decrypt_A, axis=0) decrypt_A = np.reshape(decrypt_A, og_shape) return np.array(decrypt_A) def two_comp_to_true(two_comp, bit_width=8, pad_zero=3): def binToInt(s, _bit_width=8): return int(s[1:], 2) - int(s[0]) * (1 << (_bit_width - 1)) if two_comp < 0: raise Exception("Error: not expecting negtive value") two_com_string = bin(two_comp)[2:].zfill(bit_width + pad_zero) sign = two_com_string[0:pad_zero + 1] literal = two_com_string[pad_zero + 1:] if sign == '0' * (pad_zero + 1): # positive value value = int(literal, 2) return value elif sign == '0' * (pad_zero - 2) + '1' + '0' * 2: # positive value value = int(literal, 2) return value elif sign == '0' * pad_zero + '1': # positive overflow value = pow(2, bit_width - 1) - 1 return value elif sign == '0' * (pad_zero - 1) + '1' * 2: # negtive value # if literal == '0' * (bit_width - 1): # return 0 return binToInt('1' + literal, bit_width) elif sign == '0' * (pad_zero - 2) + '1' * 3: # negtive value # if literal == '0' * (bit_width - 1): # return 0 return binToInt('1' + literal, bit_width) elif sign == '0' * (pad_zero - 2) + '110': # negtive overflow print('neg overflow: ' + two_com_string) return - (pow(2, bit_width - 1) - 1) else: # unrecognized overflow print('unrecognized overflow: ' + two_com_string) # warnings.warn('Overflow detected, consider using longer r_max') return - (pow(2, bit_width - 1) - 1) def two_comp_to_true_(two_comp, bit_width=8, pad_zero=3): def two_comp_lit_to_ori(lit, _bit_width): # convert 2's complement coding of neg value to its original form return - 1 * (2 ** (_bit_width - 1) - lit) if two_comp < 0: raise Exception("Error: not expecting negtive value") # two_com_string = bin(two_comp)[2:].zfill(bit_width+pad_zero) sign = two_comp >> (bit_width - 1) literal = two_comp & (2 ** (bit_width - 1) - 1) if sign == 0: # positive value return literal elif sign == 4: # positive value, 0100 return literal elif sign == 1: # positive overflow, 0001 return pow(2, bit_width - 1) - 1 elif sign == 3: # negtive value, 0011 return two_comp_lit_to_ori(literal, bit_width) elif sign == 7: # negtive value, 0111 return two_comp_lit_to_ori(literal, bit_width) elif sign == 6: # negtive overflow, 0110 print('neg overflow: ' + str(two_comp)) return - (pow(2, bit_width - 1) - 1) else: # unrecognized overflow print('unrecognized overflow: ' + str(two_comp)) warnings.warn('Overflow detected, consider using longer r_max') return - (pow(2, bit_width - 1) - 1) def restore_shape(component, shape, batch_size=16, bit_width=8, pad_zero=3): num_ele = np.prod(shape) num_ele_w_pad = batch_size * len(component) # print("restoring shape " + str(shape)) # print(" num_ele %d, num_ele_w_pad %d" % (num_ele, num_ele_w_pad)) un_batched_nums = np.zeros(num_ele_w_pad, dtype=int) for i in range(batch_size): filter_ = (pow(2, bit_width + pad_zero) - 1) << ((bit_width + pad_zero) * i) # print(bin(filter)) # filtered_nums = [x & filter for x in component] for j in range(len(component)): two_comp = (filter_ & component[j]) >> ((bit_width + pad_zero) * i) # print(bin(two_comp)) un_batched_nums[batch_size * j + batch_size - 1 - i] = two_comp_to_true_(two_comp, bit_width, pad_zero) un_batched_nums = un_batched_nums[:num_ele] re = np.reshape(un_batched_nums, shape) # print("reshaped " + str(re.shape)) return re # @pysnooper.snoop('de_batch.log') def decrypt_matrix_batch(private_key: PaillierPrivateKey, A, og_shape, batch_size=16, bit_width=8, pad_zero=3, r_max=0.5): # A = [x.ciphertext(be_secure=False) if x.exponent == 0 else # (x.decrease_exponent_to(0).ciphertext(be_secure=False) if x.exponent > 0 else # x.increase_exponent_to(0).ciphertext(be_secure=False)) for x in A] # print("decrypting # " + str(len(A)) + " shape " + str(og_shape)) decrypt_A = Parallel(n_jobs=N_JOBS)(delayed(private_key.decrypt)(num) for num in A) decrypt_A = np.array(decrypt_A) # print([bin(x).zfill(batch_size*(bit_width+pad_zero) + 2) for x in decrypt_A]) result = restore_shape(decrypt_A, og_shape, batch_size, bit_width, pad_zero) result = unquantize_matrix(result, bit_width, r_max) return result def calculate_clip_threshold(grads, theta=2.5): return [theta * np.std(x) for x in grads] def calculate_clip_threshold_sparse(grads, theta=2.5): result = [] for layer in grads: if isinstance(layer, tf.IndexedSlices): result.append(theta * np.std(layer.values.numpy())) else: result.append(theta * np.std(layer.numpy())) return result def clip_with_threshold(grads, thresholds): return [np.clip(x, -1 * y, y) for x, y in zip(grads, thresholds)] def clip_gradients_std(grads, std_theta=2.5): results = [] thresholds = [] for component in grads: clip_T = np.std(component) * std_theta thresholds.append(clip_T) results.append(np.clip(component, -1 * clip_T, clip_T)) return results, thresholds # def calculate_clip_threshold_aciq_g(grads, bit_width=8): # return [aciq.get_alpha_gaus(x, bit_width) for x in grads] def calculate_clip_threshold_aciq_g(grads, grads_sizes, bit_width=8): res = [] for idx in range(len(grads)): res.append(aciq.get_alpha_gaus(grads[idx], grads_sizes[idx], bit_width)) # return [aciq.get_alpha_gaus(x, bit_width) for x in grads] return res def calculate_clip_threshold_aciq_l(grads, bit_width=8): return [aciq.get_alpha_laplace(x, bit_width) for x in grads] def batch_enc_per_layer(publickey, party, r_maxs, bit_width=16, batch_size=100, pad_zeros=3): result = [] og_shapes = [] for layer, r_max in zip(party, r_maxs): enc, shape_ = encrypt_matrix_batch(publickey, layer, batch_size=batch_size, bit_width=bit_width, r_max=r_max, pad_zero=pad_zeros) # result.append(np.array(enc)) result.append(enc) og_shapes.append(shape_) return result, og_shapes def batch_dec_per_layer(privatekey, party, og_shapes, r_maxs, bit_width=16, batch_size=100, pad_zeros=3): result = [] for layer, r_max, og_shape in zip(party, r_maxs, og_shapes): result.append( decrypt_matrix_batch(privatekey, layer, og_shape, batch_size=batch_size, bit_width=bit_width, r_max=r_max, pad_zero=pad_zeros).astype(np.float32)) return np.array(result) def sparse_to_dense(gradients): result = [] for layer in gradients: if isinstance(layer, tf.IndexedSlices): result.append(tf.convert_to_tensor(layer).numpy()) else: result.append(layer.numpy()) return result def aggregate_gradients_old(gradient_list, weight=0.5): def aggregate_layer(alllayers, weight=0.5): layer = np.add.reduce(alllayers, 0) return layer gradient_list = np.array(gradient_list) results = Parallel(n_jobs=len(gradient_list[0]), prefer="threads")(delayed(aggregate_layer)(gradient_list[:, i]) for i in range(len(gradient_list[0]))) results = np.array(results) return results # def aggregate_gradients_threading(gradient_list, weight=1): # def process_chunk(grad_flat, st, ed, w): # m_slice = grad_flat[:, st:ed] # return w * np.sum(m_slice, axis=0) # # size = np.array([len(layer.flatten()) for layer in gradient_list[0]]) # shape = [np.shape(layer) for layer in gradient_list[0]] # total = np.sum(size) # job_n = min(N_JOBS, total) # chunk_size = np.array([total // job_n] * job_n) # chunk_size[:total % job_n] += 1 # # grad_flat = [] # for party in gradient_list: # host_grad_flat = [layer.flatten() for layer in party] # grad_flat.append(np.concatenate(host_grad_flat)) # grad_flat = np.array(grad_flat) # # ret = Parallel(n_jobs=job_n, backend='threading')( # delayed(process_chunk)(grad_flat, np.sum(chunk_size[:i]), np.sum(chunk_size[:i + 1]), weight) # for i in range(job_n) # ) # # split_index = [np.sum(size[:i + 1]) for i in range(len(size) - 1)] # result = np.split(np.concatenate(ret), split_index) # result = np.array([result[i].reshape(shape[i]) for i in range(len(shape))]) # return result # def aggregate_gradients_(gradient_list, weight=1): # def process_chunk(grad_flat, st, ed, w): # m_slice = grad_flat[:, st:ed] # return w * np.sum(m_slice, axis=0) # # size = np.array([len(layer.flatten()) for layer in gradient_list[0]]) # shape = [np.shape(layer) for layer in gradient_list[0]] # total = np.sum(size) # job_n = min(N_JOBS, total) # chunk_size = np.array([total // job_n] * job_n) # chunk_size[:total % job_n] += 1 # # grad_flat = [] # for party in gradient_list: # host_grad_flat = [layer.flatten() for layer in party] # grad_flat.append(np.concatenate(host_grad_flat)) # grad_flat = np.array(grad_flat) # # temp_folder = tempfile.mkdtemp() # filename = os.path.join(temp_folder, 'joblib_test.mmap') # if os.path.exists(filename): os.unlink(filename) # _ = dump(grad_flat, filename) # grad_flat = load(filename, mmap_mode='r') # # ret = Parallel(n_jobs=job_n, max_nbytes=None)( # delayed(process_chunk)(grad_flat, np.sum(chunk_size[:i]), np.sum(chunk_size[:i + 1]), weight) # for i in range(job_n) # ) # # try: # shutil.rmtree(temp_folder) # except OSError: # print('clean memmap failed') # pass # # split_index = [np.sum(size[:i + 1]) for i in range(len(size) - 1)] # result = np.split(np.concatenate(ret), split_index) # result = np.array([result[i].reshape(shape[i]) for i in range(len(shape))]) # return result def aggregate_gradients(gradient_list, weight=1, mem_factor=1): def process_chunk(m_slice, w): # LOGGER.debug('start aggregating slice') re = np.sum(m_slice, axis=0) # LOGGER.debug('stop aggregating slice') return re gradient_list = [[np.array(layer) for layer in party] for party in gradient_list] size = np.array([len(layer.flatten()) for layer in gradient_list[0]]) shape = [np.shape(layer) for layer in gradient_list[0]] total = np.sum(size) job_n = min(N_JOBS, total) # LOGGER.debug('aggregation job n ' + str(job_n)) chunk_size = np.array([total // job_n] * job_n) chunk_size[:total % job_n] += 1 grad_flat = [] for party in gradient_list: host_grad_flat = [layer.flatten() for layer in party] grad_flat.append(np.concatenate(host_grad_flat)) grad_flat = np.array(grad_flat) m_slices = [] # temp_folder = tempfile.mkdtemp() for i in range(job_n): # filename = os.path.join(temp_folder, str(i) + 'joblib_test.mmap') st = np.sum(chunk_size[:i]) ed = np.sum(chunk_size[:i + 1]) m_slice = grad_flat[:, st:ed] # if os.path.exists(filename): os.unlink(filename) # _ = dump(m_slice, filename) # m_slice = load(filename, mmap_mode='r') m_slices.append(m_slice) del grad_flat ret = Parallel(n_jobs=job_n // mem_factor)( delayed(process_chunk)(m_slice, weight) for m_slice in m_slices ) # try: # shutil.rmtree(temp_folder) # except OSError: # print('clean memmap failed') # pass split_index = [np.sum(size[:i + 1]) for i in range(len(size) - 1)] result = np.split(np.concatenate(ret), split_index) del ret result = np.array([result[i].reshape(shape[i]) for i in range(len(shape))]) return result def calculate_clip_threshold_aciq_dis(layer_size, grads_mean, grads_mean_sqr, num_party, theta=2.5): clipping_thresholds = theta * ( np.sum(grads_mean_sqr * layer_size, 0) / (layer_size * num_party) - (np.sum(grads_mean * layer_size, 0) / (layer_size * num_party)) ** 2) ** 0.5 return clipping_thresholds <file_sep>/accuracy_eval/encryption/aciq.py import math import numpy as np # from scipy.special import erf # import matplotlib.pyplot as plt # # plt.rcParams['figure.figsize'] = [16, 12] import scipy.optimize as opt def mse_laplace(alpha, b, num_bits): ''' Calculating the sum of clipping error and quantization error for Laplace case Args: alpha: the clipping value b: location parameter of Laplace distribution num_bits: number of bits used for quantization Return: The sum of clipping error and quantization error ''' return 2 * (b ** 2) * np.exp(-alpha / b) + (2 * alpha ** 2 * (2 ** num_bits - 2)) / (3 * (2 ** (3 * num_bits))) def mse_gaussian(alpha, sigma, num_bits): ''' Calculating the sum of clipping error and quantization error for Gaussian case Args: alpha: the clipping value sigma: scale parameter parameter of Gaussian distribution num_bits: number of bits used for quantization Return: The sum of clipping error and quantization error ''' clipping_err = (sigma ** 2 + (alpha ** 2)) * (1 - math.erf(alpha / (sigma * np.sqrt(2.0)))) - \ np.sqrt(2.0 / np.pi) * alpha * sigma * (np.e ** ((-1) * (0.5 * (alpha ** 2)) / sigma ** 2)) quant_err = (2 * alpha ** 2 * (2 ** num_bits - 2)) / (3 * (2 ** (3 * num_bits))) return clipping_err + quant_err # To facilitate calculations, we avoid calculating MSEs from scratch each time. # Rather, as N (0, sigma^2) = sigma * N (0, 1) and Laplace(0, b) = b * Laplace(0, 1), # it is sufficient to store the optimal clipping values for N (0, 1) and Laplace(0, 1) and scale these # values by sigma and b, which are estimated from the tensor values. # Given b = 1, for laplace distribution b = 1. # print("Optimal alpha coeficients for laplace case, while num_bits falls in [2, 8].") alphas = [] for m in range(2, 33, 1): alphas.append(opt.minimize_scalar(lambda x: mse_laplace(x, b=b, num_bits=m)).x) # print(np.array(alphas)) # Given sigma = 1, for Gaussian distribution sigma = 1. # print("Optimal alpha coeficients for gaussian clipping, while num_bits falls in [2, 8]") alphas = [] for m in range(2, 33, 1): alphas.append(opt.minimize_scalar(lambda x: mse_gaussian(x, sigma=sigma, num_bits=m)).x) # print(np.array(alphas)) def get_alpha_laplace(values, num_bits): ''' Calculating optimal alpha(clipping value) in Laplace case Args: values: input ndarray num_bits: number of bits used for quantization Return: Optimal clipping value ''' # Dictionary that stores optimal clipping values for Laplace(0, 1) alpha_laplace = { 2: 2.83068299, 3: 3.5773953, 4: 4.56561968, 5: 5.6668432, 6: 6.83318852, 7: 8.04075143, 8: 9.27621011, 9: 10.53164388, 10: 11.80208734, 11: 13.08426947, 12: 14.37593053, 13: 15.67544068, 14: 16.98157905, 15: 18.29340105, 16: 19.61015778, 17: 20.93124164, 18: 22.25615278, 19: 23.58447327, 20: 24.91584992, 21: 26.24998231, 22: 27.58661098, 23: 28.92551169, 24: 30.26648869, 25: 31.60937055, 26: 32.9540057, 27: 34.30026003, 28: 35.64801378, 29: 36.99716035, 30: 38.3476039, 31: 39.69925781, 32: 41.05204406} # That's how ACIQ paper calcualte b b = np.mean(np.abs(values - np.mean(values))) return alpha_laplace[num_bits] * b def get_alpha_gaus(values, values_size, num_bits): ''' Calculating optimal alpha(clipping value) in Gaussian case Args: values: input ndarray num_bits: number of bits used for quantization Return: Optimal clipping value ''' # Dictionary that stores optimal clipping values for N(0, 1) alpha_gaus = { 2: 1.71063516, 3: 2.02612148, 4: 2.39851063, 5: 2.76873681, 6: 3.12262004, 7: 3.45733738, 8: 3.77355322, 9: 4.07294252, 10: 4.35732563, 11: 4.62841243, 12: 4.88765043, 13: 5.1363822, 14: 5.37557768, 15: 5.60671468, 16: 5.82964388, 17: 6.04501354, 18: 6.25385785, 19: 6.45657762, 20: 6.66251328, 21: 6.86053901, 22: 7.04555454, 23: 7.26136857, 24: 7.32861916, 25: 7.56127906, 26: 7.93151212, 27:7.79833847, 28: 7.79833847, 29: 7.9253003, 30: 8.37438905, 31: 8.37438899, 32: 8.37438896} # That's how ACIQ paper calculate sigma, based on the range (efficient but not accurate) gaussian_const = (0.5 * 0.35) * (1 + (np.pi * np.log(4)) ** 0.5) # sigma = ((np.max(values) - np.min(values)) * gaussian_const) / ((2 * np.log(values.size)) ** 0.5) sigma = ((np.max(values) - np.min(values)) * gaussian_const) / ((2 * np.log(values_size)) ** 0.5) return alpha_gaus[num_bits] * sigma if __name__ == '__main__': values = np.array([[[0.1, 0.2], [0.3, 0.4]], [[0.05, 0.01], [0.06, 0]], [[-0.05, -0.06], [-0.01, 0.03]]]) print("----Test----") for num_bits in range(2, 33): print("num of bits == {}".format(num_bits)) print("Laplace clipping value: {}".format(get_alpha_laplace(values, num_bits))) print("Gaussian clipping value: {}".format(get_alpha_gaus(values, 10, num_bits))) print("------") <file_sep>/accuracy_eval/augmentation.py import tensorflow as tf import numpy as np def flip(x): """Flip augmentation Args: x: Image to flip Returns: Augmented image """ x = tf.image.random_flip_left_right(x) # x = tf.image.random_flip_up_down(x) return x def color(x): """Color augmentation Args: x: Image Returns: Augmented image """ x = tf.image.random_hue(x, 0.08) x = tf.image.random_saturation(x, 0.6, 1.6) x = tf.image.random_brightness(x, 0.05) x = tf.image.random_contrast(x, 0.7, 1.3) return x def zoom(x): """Zoom augmentation Args: x: Image Returns: Augmented image """ scale = np.random.uniform(0.8, 1.0) x1 = y1 = 0.5 - (0.5 * scale) x2 = y2 = 0.5 + (0.5 * scale) box = [x1, y1, x2, y2] def random_crop(img): # Create different crops for an image crops = tf.image.crop_and_resize([img], boxes=[box], box_indices=[0], crop_size=(32, 32)) # Return a random crop return crops[0] x = random_crop(x) return x def augment_img(x, y): if np.random.uniform(0.0, 1.0) > 0.5: x = flip(x) if np.random.uniform(0.0, 1.0) > 0.5: x = color(x) if np.random.uniform(0.0, 1.0) > 0.75: x = zoom(x) return x, y
2c1f19fce423a68311f4a5df42d77b8f7cb18845
[ "Python" ]
14
Python
anonyauth2020/batchcrypt
f9c1b3397bc9b652d43140bbe21ef011b0298599
7e07db0e8ef7c4e1b460200d502128ad82b68fbd
refs/heads/master
<repo_name>cran/GeNetIt<file_sep>/R/dmatrix.df.R #' @title Distance matrix to data.frame #' @description Coerces distance matrix to a data.frame object #' #' @param x Symmetrical distance matrix #' @param rm.diag (TRUE/FALSE) remove matrix diagonal, self values. #' @return data.frame object representing to and from values #' #' @note #' Function results in data.frame object with "X1" (FROM), "X2" (TO) and #' "distance" columns. The FROM column represents to origin ID, TO represents #' destination ID and distance is the associated matrix distance. These #' results can be joined back to the graph object using either the origin or #' destination ID's. #' #' @author <NAME> <<EMAIL>> and #' <NAME> <<EMAIL>> #' #' @examples #' library(sf) #' pts <- data.frame(ID=paste0("ob",1:15), x=runif(15, 480933, 504250), #' y=runif(15, 4479433, 4535122)) #' pts <- st_as_sf(pts, coords = c("x", "y"), #' crs = 32611, agr = "constant") #' #' # Create distance matrix #' dm <- st_distance(pts) #' class(dm) <- setdiff(class(dm), "units") #' attr(dm, "units") <- NULL #' colnames(dm) <- pts$ID #' rownames(dm) <- pts$ID #' #' # Coerce to data.frame with TO and FROM ID's and associated distance #' dm.df <- dmatrix.df(dm) #' head(dm.df) #' #' @export dmatrix.df <- function(x, rm.diag = TRUE) { if( nrow(x) != ncol(x)) stop("Matrix is not symmetrical") if(rm.diag == TRUE) { diag(x) <- NA } if(is.null(rownames(x)) && is.null(colnames(x))) stop("Either rows or columns need names") if(is.null(rownames(x))) { rownames(x) <- colnames(x) } if(is.null(colnames(x))) { colnames(x) <- rownames(x) } if(any(rownames(x) != colnames(x))){ message("names do not match; defaulting to column names") rownames(x) <- colnames(x) } varnames = list(colnames(x),colnames(x)) values <- as.vector(x) dn <- dimnames(x) char <- sapply(dn, is.character) dn[char] <- lapply(dn[char], utils::type.convert, as.is=TRUE) indices <- do.call(expand.grid, dn) names(indices) <- c("from","to") indices <- data.frame(indices, distance = values) indices <- stats::na.omit(indices) return( indices ) } <file_sep>/R/compare.models.R #' @title Compare gravity models #' @description Prints diagnostic statistics for comparing gravity models #' #' @param ... gravity model objects #' #' @return data.frame of competing model statistics #' #' @details #' Results include model name, AIX, BIC, log likelihood, RMSE and number of parameters #' #' @author <NAME> <<EMAIL>> and #' <NAME> <<EMAIL>> #' #' @references #' <NAME>., <NAME>, <NAME> & <NAME> (2010) Landscape genetics of #' high mountain frog metapopulations. Molecular Ecology 19(17):3634-3649 #' #' @examples #' library(nlme) #' data(ralu.model) #' #' x = c("DEPTH_F", "HLI_F", "CTI_F", "cti", "ffp") #' ( null <- gravity(y = "DPS", x = c("DISTANCE"), d = "DISTANCE", #' group = "FROM_SITE", data = ralu.model, fit.method = "ML") ) #' ( gm_h1 <- gravity(y = "DPS", x = x, d = "DISTANCE", group = "FROM_SITE", #' data = ralu.model, ln = FALSE, fit.method="ML") ) #' ( gm_h2 <- gravity(y = "DPS", x = x[1:3], d = "DISTANCE", group = "FROM_SITE", #' data = ralu.model, ln = FALSE, fit.method="ML") ) #' ( gm_h3 <- gravity(y = "DPS", x = x[c(4:5)], d = "DISTANCE", group = "FROM_SITE", #' data = ralu.model, ln = FALSE, fit.method="ML") ) #' #( gm_h4 <- gravity(y = "DPS", x = x[c(4:5)], d = "DISTANCE", group = "FROM_SITE", #' # data = ralu.model, ln = FALSE, fit.method="REML") ) #' #' compare.models(null, gm_h1, gm_h2, gm_h3) #' #' @export compare.models compare.models <- function(...) { dots <- list(...) #mn <- deparse(substitute(list(...))) #mn <- regmatches(mn, gregexpr("(?<=\\().*?(?=\\))", mn, perl=TRUE))[[1]] #mn <- trimws(unlist(strsplit(mn, ","))) varnames = lapply(substitute(list(...))[-1], deparse) mn <- unlist(lapply(varnames, as.character)) for(i in 1:length(dots)){ if(!inherits(dots[[i]], "gravity")) stop(paste0(mn[i], " is not a valid gravity model object") ) dots[[i]]$gravity$y <- dots[[i]]$y dots[[i]]$gravity$np <- ncol(dots[[i]]$x) dots[[i]] <- dots[[i]]$gravity } method <- unique(unlist(lapply(dots, function(x) x$method))) if( length(method) > 1 ) { cat(paste(mn, unlist(lapply(dots, function(x) x$method)), sep="-"), "\n") stop("Models were fit with ML and REML and are not comparable") } if( any(method == "REML") ) { warning("AIC/BIC not valid under REML and will not be reported") } back.transform <- function(y) exp(y + 0.5 * stats::var(y)) rmse <- function(y, x) { sqrt(mean((y - x)^2)) } mfun <- function(x) { method <- x$method np = ncol(x$data)-1 if( method == "REML" ) { xdf <- data.frame(log.likelihood = x$logLik, RMSE = round(rmse(back.transform(x$y), back.transform(x$fit[,"fixed"])),4), nparms = np, fit.method=method) } else if( method == "ML" ) { xdf <- data.frame(AIC = stats::AIC(x), BIC = stats::BIC(x), log.likelihood = x$logLik, RMSE = round(rmse(back.transform(x$y), back.transform(x$fit[,"fixed"])),4), nparms = np, fit.method=method) } return(xdf) } ldf <- do.call("rbind", lapply(dots, mfun)) if(method == "ML") { ldf$deltaAIC = ldf$AIC - min(ldf$AIC) ldf$deltaBIC = ldf$BIC - min(ldf$BIC) } return( data.frame(model = as.character(mn), ldf) ) } <file_sep>/R/summary.gravity.R #' @title Summarizing Gravity Model Fits #' @description Summary method for class "gravity". #' @param object Object of class gravity #' @param ... Ignored #' @note Summary of lme or lm gravity model, AIC, log likelihood and Root Mean Square Error (RMSE) of observed verses predicted #' @method summary gravity #' @export summary.gravity <- function(object, ...) { rmse <- function(y, x) { sqrt(mean((y - x)^2)) } message("Gravity model summary\n\n") print(object$formula) print(summary(object$gravity)) message( paste("AIC = ", round(object$AIC,3), sep="")) message( paste("log likelihood = ", round(object$log.likelihood,3), sep="")) message( paste("RMSE = ", round(rmse(object$y, object$fit),4), sep="")) } <file_sep>/R/adj_matrix.R #' @title Binary adjacency matrix #' @description Creates a binary matrix of adjacencies based on #' from-to graph relationships (joins) #' #' @param i a vector or, if j = NULL a data.frame with two #' columns indicating from-to relationships (joins) #' @param j If specified, i must be a vector of same length and #' the i,j vectors must represent joins #' #' @return A binary matrix #' #' @author <NAME> <<EMAIL>> and #' <NAME> <<EMAIL>> #' #' @examples #' library(sf) #' data(ralu.site, package="GeNetIt") #' #' p <- as(ralu.site, "sf") #' g <- knn.graph(p[c(1,5,8,10,20,31),]) #' plot(st_geometry(g)) #' #' ( ind <- sf::st_drop_geometry(g[,1:2])[1:10,] ) #' #' adj_matrix(ind) #' #' adj_matrix(g$i[1:10], g$j[1:10]) #' #' @export adj_matrix <- function(i, j=NULL) { if(missing(i)) stop("i must be defined") if(class(i)[1] == "data.frame") { if(ncol(i) < 2) stop("Incorrect dim, need 2 columns") ind <- i[,1:2] names(ind) <- c("i","j") } if(!missing(i) & !is.null(j)) { if(!any(c(is.vector(i),is.vector(j)))) stop("Data is not vector") if(length(i) != length(j)) stop("From-To vectors are not equal") ind <- data.frame(i=i, j=j) names(ind) <- c("i","j") } adj <- matrix(0, nrow(ind), nrow(ind)) for (p in 1:nrow(ind)){ adj[ind[p,1], ind[p,2]] <- 1 adj[ind[p,2], ind[p,1]] <- 1 } return(adj) } <file_sep>/R/ralu.site-data.R #' @name ralu.site #' @docType data #' #' @title Subset of site-level spatial point data for Columbia spotted frog (Rana luteiventris) #' #' @description Subset of data used in Murphy et al., (2010) #' #' @format An sf POINT object with 31 obs. of 17 variables: #' \describe{ #' \item{SiteName}{Unique site name} #' \item{Drainage}{Source drainage} #' \item{Basin}{source basin} #' \item{Substrate}{Wetland substrate} #' \item{NWI}{USFWS NWI Wetland type} #' \item{AREA_m2}{Area of wetland} #' \item{PERI_m}{Perimeter of wetland} #' \item{Depth_m}{Depth of wetland} #' \item{TDS}{...} #' \item{FISH}{Fish present} #' \item{ACB}{...} #' \item{AUC}{...} #' \item{AUCV}{...} #' \item{AUCC}{...} #' \item{AUF}{...} #' \item{AWOOD}{...} #' \item{AUFV}{...} #' } #' #' @references #' <NAME>., <NAME>, <NAME> & <NAME> (2010) Landscape genetics of high mountain frog metapopulations. Molecular Ecology 19(17):3634-3649 #' NULL <file_sep>/R/plot.gravity.R #' @title Plot gravity model #' @description Diagnostic plots gravity model with 6 optional plots. #' #' @param x Object of class gravity #' @param type Type of plot (default 1, model structure I) #' @param ... Ignored #' #' @return defined plot #' #' @note Plot types available: 1 - Model structure I, 2 - Model structure II, 3 - Q-Q Normal - Origin random effects, 4 - Q-Q Normal - Residuals , 5 - Fitted values, 6 - Distribution of observed verses predicted #' @note Depends: nlme, lattice #' #' @author <NAME> <<EMAIL>> and #' <NAME> <<EMAIL>> #' #' @references #' <NAME>. & <NAME>. (in prep). "GenNetIt: gravity analysis in R for landscape genetics" #' @references #' <NAME>., <NAME>, <NAME> & <NAME> (2010) Landscape genetics of high mountain frog metapopulations. Molecular Ecology 19(17):3634-3649 #' #' @method plot gravity #' @export plot.gravity <- function(x, type = 1, ...) { options(warn=-1) if(type == 1) { # MODEL STRUCTURE I graphics::plot(stats::fitted(x$gravity, level=0), x$y, xlab = "Fitted Values (DPS)", ylab="Observed Values", main="Model Structure (I)", pch=16, ...) graphics::abline(0, 1, col = "blue") } if(type == 2) { # MODEL STRUCTURE II stats::scatter.smooth(stats::fitted(x$gravity), stats::residuals(x$gravity, type="pearson"), ylab="Innermost Residuals", main="Model Structure (II)", xlab="Fitted Values", pch=16) graphics::abline(h = 0, col = "red") } if(type == 3) { # Q-Q NORMAL - ORIGIN RANDOM EFFECTS stats::qqnorm(nlme::ranef(x$gravity)[[1]], main="Q-Q Normal - Origin Random Effects", pch=16) stats::qqline(nlme::ranef(x$gravity)[[1]], col="red") } if(type == 4) { # Q-Q NORMAL - RESIDUALS stats::qqnorm(stats::residuals(x$gravity, type="pearson"), main="Q-Q Normal - Residuals", pch=16) stats::qqline(stats::residuals(x$gravity, type="pearson"), col="red") } if(type == 5) { # FITTED VALUES graphics::boxplot(stats::residuals(x$gravity, type="pearson", level=1) ~ x$groups, ylab="Innermost Residuals", xlab="Origin", notch=T, varwidth = T, at=rank(nlme::ranef(x$gravity)[[1]])) graphics::axis(3, labels=format(nlme::ranef(x$gravity)[[1]], dig=2), cex.axis=0.8, at=rank(nlme::ranef(x$gravity)[[1]])) graphics::abline(h=0, col="darkgreen") } if(type == 6) { # DISTRIBUTION OF OBSERVED VS.PRED #yname = strsplit(as.character(as.list(x$gravity$call)$fixed), "[~]")[[2]] oden <- stats::density(x$y) pden <- stats::density(stats::predict(x$gravity)) graphics::plot(oden, type="n", main="", xlim=c(min(x$y), max(x$y)), ylim=c(min(oden$y,pden$y), max(oden$y,pden$y))) graphics::polygon(oden, col=grDevices::rgb(1,0,0,0.5)) graphics::polygon(pden, col=grDevices::rgb(0,0,1,0.5)) graphics::legend("topright", legend=c("Obs","Pred"), fill=c(grDevices::rgb(1,0,0,0.4), grDevices::rgb(0,0,1,0.4))) } options(warn=0) } <file_sep>/R/graph.metrics.R #' @title Graph Metrics #' @description Metrics on structural properties of graph (at nodes) #' #' @param x knn graph object from GeNetIt::knn.graph (sf LINESTRING) #' @param node.pts sf POINT or sp SpatialPointsDataFrame object used as nodes to build x #' @param node.name Column name in node.pts object that acts as the provides the unique ID. #' If not defined, defaults to row.names of node.pts #' @param direct (FALSE/TRUE) Evaluate directed graph #' @param metric ... #' #' @note Please note; graph metrics are not valid for a saturated graph (all connections) #' #' @author <NAME> <<EMAIL>> and #' <NAME> <<EMAIL>> #' #' @examples #' library(sf) #' data(ralu.site, package="GeNetIt") #' #' graph <- knn.graph(ralu.site, row.names=ralu.site$SiteName, #' max.dist = 2500) #' plot(st_geometry(graph)) #' #' ( m <- graph.metrics(graph, ralu.site, "SiteName") ) #' #' ralu.site <- merge(ralu.site, m, by="SiteName") #' # plot node betweenness #' plot(st_geometry(graph), col="grey") #' plot(ralu.site["betweenness"], pch=19, cex=1.25, add=TRUE) #' # plot node degree #' plot(st_geometry(graph), col="grey") #' plot(ralu.site["degree"], pch=19, cex=1.25, add=TRUE) #' #' @export graph.metrics <- function(x, node.pts, node.name=NULL, direct = FALSE, metric = c("betweenness", "degree", "closeness")) { if(!any(which(utils::installed.packages()[,1] %in% c("igraph", "sfnetworks") ))) stop("please install igraph and sfnetworks packages before running this function") m <- c("betweenness", "degree", "closeness") m <- m[m %in% metric] if(!inherits(x, "sf")) stop("x must be a sf LINESTRING object") if(attributes(x$geometry)$class[1] != "sfc_LINESTRING") stop("x must be a sf sfc_LINE object") if (!inherits(node.pts, "sf")) stop("x must be a sf POINT object") if(attributes(node.pts$geometry)$class[1] != "sfc_POINT") stop("node.pts must be a sf sfc_LINE object") if(is.null(node.name)) { node.name = row.names(node.pts) } else { if(!node.name %in% names(node.pts)) stop("specified node.name not in node.pts") } g <- sfnetworks::as_sfnetwork(x = x, edges = x, nodes = node.pts, directed = direct, node_key = node.name, length_as_weight = TRUE, edges_as_lines = TRUE) gm <- data.frame(sf::st_drop_geometry(node.pts[,node.name])) # w <- g$weight/sum(g$weight) w <- g |> tidygraph::activate("edges") |> dplyr::pull("weight") |> as.numeric() w[w <= 0] <- 1 w = w / sum(w) if("betweenness" %in% m) gm$betweenness <- igraph::betweenness(g, directed=FALSE, weights=w) if("degree" %in% m) gm$degree <- igraph::degree(g) if("closeness" %in% m) gm$closeness <- igraph::closeness(g, weights=w) return(gm) } <file_sep>/R/graph.statistics.R #' @title Statistics for edges (lines) #' @description Extracts raster values for each edge and calculates specified statistics #' #' @param x sp SpatialLinesDataFrame or sf LINE object #' @param r A terra SpatRast or raster rasterLayer, rasterStack, rasterBrick object #' @param stats Statistics to calculate. If vectorized, can pass a custom #' statistic function. #' @param buffer Buffer distance, radius in projection units. For statistics #' based on edge buffer distance #' #' @return data.frame object of statistics #' #' @note #' If the buffer argument is specified that, raster values within the specified #' buffer radius are extracted and included in the derived statistic(s). Else-wise, #' the statistics are derived from raster values that directly intersect each edge. #' #' @author <NAME> <<EMAIL>> and #' <NAME> <<EMAIL>> #' #' @examples #' \donttest{ #' library(sf) #' library(terra) #' #' data(ralu.site) #' xvars <- rast(system.file("extdata/covariates.tif", package="GeNetIt")) #' #' ( dist.graph <- knn.graph(ralu.site, row.names = ralu.site$SiteName, #' max.dist = 1500) ) #' #' skew <- function(x, na.rm = TRUE) { #' if (na.rm) x <- x[!is.na(x)] #' sum( (x - mean(x)) ^ 3) / ( length(x) * sd(x) ^ 3 ) #' } #' #' # Moments on continuous raster data #' system.time( { #' stats <- graph.statistics(dist.graph, r = xvars[[-6]], #' stats = c("min", "median", "max", "var", "skew")) #' } ) #' #' # Proportional function on nominal raster data #' p <- function(x) { length(x[x < 52]) / length(x) } #' #' system.time( { #' nstats <- graph.statistics(dist.graph, r = xvars[[6]], #' stats = "p") #' } ) #' #' # Based on 500m buffer distance around line(s) #' system.time( { #' stats <- graph.statistics(dist.graph, r = xvars[[-6]], #' stats = c("min", "median", "max", "var", "skew"), #' buffer = 500) #' } ) #' #' } #' #' @export graph.statistics graph.statistics <- function(x, r, stats = c("min", "mean", "max"), buffer = NULL) { if (!inherits(r, "SpatRaster")) stop("r must be a terra SpatRaster class object") if(attributes(x$geometry)$class[1] != "sfc_LINESTRING") stop("x must be a sf sfc_LINE object") if(sf::st_is_longlat(x)) warning("Projection is not defined or in lat/long, is it recommended that you project your data to prevent planar distortions in the buffer") if(!sf::st_crs(x) == sf::st_crs(terra::crs(r))) warning("x and r projections do not match") #### Extract all values intersecting lines if(is.null(buffer)) { ldf <- terra::extract(r, terra::vect(x)) ldf <- lapply(unique(ldf$ID), function(i) { j <- as.data.frame(ldf[ldf$ID == i,][,-1]) names(j) <- names(r) return(j)} ) } else { message(paste0("Using ", buffer, " distance for statistics")) b <- sf::st_buffer(x, dist = buffer) if(!nrow(b) == nrow(x)) stop("Sorry, something went wrong with buffering, features do not match") ldf <- exactextractr::exact_extract(r, b, progress = FALSE) ldf <- lapply(ldf, FUN = function(x) { j <- as.data.frame(x[,-which(names(x) %in% "coverage_fraction")]) names(j) <- names(r) return(j)}) names(ldf) <- row.names(x) } stats.fun <- function(x, m = stats) { slist <- list() for(i in 1:length(m)) { slist[[i]] <- apply(x, MARGIN=2, m[i]) } return( as.data.frame(t(unlist(slist))) ) } results <- lapply(ldf, FUN=stats.fun) results <- do.call("rbind", results) rn <- vector() for(n in stats) { rn <- append(rn, paste(n, names(r), sep="."))} names(results) <- rn return( results ) } <file_sep>/R/gravity.R #' @title Gravity model #' @description Implements Murphy et al., (2010) gravity model via a #' linear mixed effects model #' #' @param y Name of dependent variable #' @param x Character vector of independent variables #' @param d Name of column containing distance #' @param group Name of grouping column (from or to) #' @param data data.frame object containing model data #' @param fit.method Method used to fit model c("REML", "ML") #' @param ln Natural log transform data (TRUE/FALSE) #' @param constrained Specify constrained model, if FALSE a linear model (lm) #' is run (TRUE/FALSE) #' @param ... Additional argument passed to nlme or lm #' #' @return formula Model formula call #' @return fixed.formula Model formula for fixed effects #' @return random.formula Model formula for random (group) effects #' (only for constrained models) #' @return gravity Gravity model #' @return fit Model Fitted Values #' @return AIC AIC value for selected model #' @return RMSE Root Mean Squared Error (based on bias corrected back transform) #' @return log.likelihood Restricted log-likelihood at convergence #' @return group.names Column name of grouping variable #' @return groups Values of grouping variable #' @return x data.frame of x variables #' @return y Vector of y variable #' @return constrained TRUE/FALSE indicating if model is constrained #' #' @details #' The "group" factor defines the singly constrained direction (from or to) and the #' grouping structure for the origins. To specify a null (distance only or IBD) #' model just omit the x argument. #' #' By default constrained models are fit by maximizing the restricted log-likelihood #' (REML), for maximum likelihood use the type="ML" argument which is passed to the #' lme function. If ln=TRUE the input data will be log transformed #' #' @note Depends: nlme, lattice #' #' @author <NAME> <<EMAIL>> and #' <NAME> <<EMAIL>> #' #' @references #' <NAME>. & <NAME>. (in prep). GenNetIt: graph theoretical gravity modeling #' for landscape genetics #' @references #' <NAME>., <NAME>, <NAME> & <NAME> (2010) Landscape genetics of #' high mountain frog metapopulations. Molecular Ecology 19(17):3634-3649 #' #' @examples #' library(nlme) #' data(ralu.model) #' #' # Gravity model #' x = c("DEPTH_F", "HLI_F", "CTI_F", "cti", "ffp") #' ( gm <- gravity(y = "DPS", x = x, d = "DISTANCE", group = "FROM_SITE", #' data = ralu.model, ln = FALSE) ) #' #'#' # Plot gravity results #' par(mfrow=c(2,3)) #' for (i in 1:6) { plot(gm, type=i) } #' #' # log likelihood of competing models #' x = c("DEPTH_F", "HLI_F", "CTI_F", "cti", "ffp") #' for(i in x[-1]) { #' x1 = c(x[1], x[-which(x %in% i)]) #' ll <- gravity(y = "DPS", x = x1, d = "DISTANCE", group = "FROM_SITE", #' data = ralu.model, ln = FALSE)$log.likelihood #' cat("log likelihood for parameter set:", "(",x1,")", "=", ll, "\n") #' } #' #' # Distance only (IBD) model #' gravity(y = "DPS", d = "DISTANCE", group = "FROM_SITE", #' data = ralu.model, ln = FALSE) #' #' @seealso \code{\link[nlme]{groupedData}} for how grouping works in constrained model #' @seealso \code{\link[nlme]{lme}} for constrained model ... options #' @seealso \code{\link[stats]{lm}} for linear model ... options #' #' @import nlme #' @export gravity #' @export gravity <- function (y, x, d, group, data, fit.method = c("REML", "ML"), ln = TRUE, constrained = TRUE, ...) { fit.method = fit.method[1] if (missing(d)) stop("Distance must be included") if (missing(x)) { x = d } back.transform <- function(y) exp(y + 0.5 * stats::var(y)) rmse = function(p, o){ sqrt(mean((p - o)^2)) } x <- unique(c(x, d)) fixed.call <- stats::as.formula(paste(paste(y, "~", sep = ""), paste(x, collapse = "+"))) random.call <- stats::as.formula(paste(paste(y, 1, sep = " ~ "), group, sep = " | ")) gdata <- data[,c(group, y, x)] if (ln == TRUE) { gdata[, x] <- log(abs(gdata[, x])) gdata[, y] <- log(abs(gdata[, y])) gdata[gdata == -Inf] <- 0 gdata[gdata == Inf] <- 0 } if (constrained == TRUE) { print("Running singly-constrained gravity model") gvlmm <- nlme::lme(fixed = stats::as.formula(paste(paste(y, "~", sep = ""), paste(x, collapse = "+"))), data = gdata, random=stats::as.formula(paste(paste(y, 1, sep = " ~ "), group, sep = " | "))) if(fit.method == "ML") gvlmm <- stats::update(gvlmm, method="ML") gm <- list(fixed.formula = fixed.call, random.formula = random.call, gravity = gvlmm, fit = stats::fitted(gvlmm), AIC = stats::AIC(gvlmm), RMSE = rmse(back.transform(stats::fitted(gvlmm)), back.transform(gdata[,y])), log.likelihood = gvlmm$logLik, group.names = group, groups = gdata[,group], x = data[,x], y = data[,y], constrained = constrained) } else { print("Running unconstrained gravity model, defaulting to OLS. Please check assumptions") gvlmm <- stats::lm(stats::as.formula(paste(paste(y, "~", sep = ""), paste(x, collapse = "+"))), data = gdata) gm <- list(formula = fixed.call, gravity = gvlmm, fit = stats::fitted(gvlmm), AIC = stats::AIC(gvlmm), RMSE = rmse(back.transform(stats::fitted(gvlmm)), back.transform(gdata[,y])), x = data[,x], y = data[,y], constrained = constrained) } class(gm) <- "gravity" return(gm) } <file_sep>/R/build.node.data.R #' @title Build node data #' @description Helper function to build the origin/destination node data structure. #' #' @param x A data.frame containing node (site) data #' @param group.ids Character vector of unique identifier that can be used to join #' to graph #' @param from.parms Character vector of independent "from" variables #' @param to.parms Character vector of independent "to" variables. If NULL is #' the same as from.parms #' #' @return data.frame #' #' @note #' Unless a different set of parameters will be used as the destination (to) there #' is no need to define the argument "to.parms" and the "from.parm" will be used to #' define both set of parameters. #' @note #' The resulting data.frame represents the origin (from) and destination (to) data #' structure for use in gravity model. This is node structure is also know in the #' gravity literature as producer (from) and attractor (to). #' #' @author <NAME> <<EMAIL>> and #' <NAME> <<EMAIL>> #' #' @examples #' data(ralu.site) #' #' # Build from/to site (node) level data structure #' site.parms = c("AREA_m2", "PERI_m", "Depth_m", "TDS") #' site <- build.node.data(sf::st_drop_geometry(ralu.site), #' group.ids = c("SiteName"), #' from.parms = site.parms ) #' #' @export build.node.data <- function(x, group.ids, from.parms, to.parms = NULL) { if(!inherits(x, "data.frame")) stop("x is not a data.frame") for(i in from.parms) { if (is.na(charmatch(i, names(x)))) stop(i, " is not a column in the data.frame") } if(is.null(to.parms)) to.parms = from.parms id.col <- which( names(x) %in% group.ids ) from.col <- which( names(x) %in% from.parms ) to.col <- which( names(x) %in% to.parms ) from <- x[,c(id.col,from.col)] names(from) <- c(group.ids, paste("from", from.parms, sep=".")) to <- x[,c(id.col,to.col)] names(to) <- c(group.ids, paste("to", to.parms, sep=".")) site <- data.frame(from, to) site <- site[,-(dim(to)[2]+1)] return( site ) } <file_sep>/R/flow.R #' @title Convert distance to flow #' #' @description Converts distance to flow (1-d) with or without data standardization #' #' @param x A numeric vector or matrix object representing distances #' @param standardize (FALSE/TRUE) Row-standardize the data before calculating flow #' @param rm.na (TRUE/FALSE) Should NA's be removed, if FALSE (default) the #' will be retained in the results #' @param diag.value If x is a matrix, what diagonal matrix values should be #' used (default is NA) #' #' @return A vector or matrix representing flow values #' #' @author <NAME> <<EMAIL>> and #' <NAME> <<EMAIL>> #' #' @examples #' #### On a distance vector #' flow(runif(10,0,1)) #' flow(runif(10,0,500), standardize = TRUE) #' #' # With NA's #' d <- runif(10, 0,1) #' d[2] <- NA #' flow(d) #' flow(d, rm.na=TRUE) #' #' #### On a distance matrix #' dm <- as.matrix(dist(runif(5,0,1), diag = TRUE, upper = TRUE)) #' flow(dm) #' #' @export flow flow <- function(x, standardize = FALSE, rm.na = FALSE, diag.value = NA) { if(!inherits(x, "numeric") & !inherits(x, "matrix")) stop(deparse(substitute(x)), "x must be a vector or matrix") if(inherits(x, "numeric")) { if(standardize) { d = 1 - (x[!is.na(x)] / max(x, na.rm=TRUE)) } else { d = 1 - x[!is.na(x)] } if(rm.na == FALSE) { na.idx <- which(is.na(x)) if(length(na.idx) > 0) { z <- numeric(length(d) + length(na.idx)) z[na.idx] <- NA z[-na.idx] <- d d <- z } } } if(inherits(x, "matrix")) { if(standardize) { d = 1 - (x / max(x, na.rm=TRUE)) } else { d = 1 - x } diag(d) <- diag.value } return(d) } <file_sep>/R/print.gravity.R #' @title Print gravity model #' @description summary method for class "gravity" #' @param x Object of class gravity #' @param ... Ignored #' @method print gravity #' @export "print.gravity" <- function(x, ...) { cat("Gravity model\n\n") print(summary(x$gravity)) } <file_sep>/R/gravity.es.R #' @title Effect Size #' @description Cohen's D effect size for gravity models #' #' @param x gravity model object #' @param alpha confidence interval #' @param actual.n (FALSE/TRUE) Use actual N or degrees of freedom #' in calculating Confidence Interval #' #' @return data.frame of parameter effect size #' #' @details #' Calculate Cohen's D statistic for each effect in a gravity model object #' #' @author <NAME> <<EMAIL>> and #' <NAME> <<EMAIL>> #' #' @references #' <NAME>., <NAME>, <NAME> & <NAME> (2010) Landscape genetics of #' high mountain frog metapopulations. Molecular Ecology 19(17):3634-3649 #' @references #' <NAME>. (1988) Statistical power for the behavioral sciences (2nd ed.). #' Hillsdale, NJ: Erlbaum #' #' @examples #' library(nlme) #' data(ralu.model) #' #' x = c("DEPTH_F", "HLI_F", "CTI_F", "cti", "ffp") #' gm_h1 <- gravity(y = "DPS", x = x, d = "DISTANCE", group = "FROM_SITE", #' data = ralu.model, ln = FALSE, method="ML") #' #' gravity.es(gm_h1) #' #' @export gravity.es gravity.es <- function(x, actual.n = FALSE, alpha = 0.95) { if(!inherits(x, "gravity")) stop(x, " is not a valid gravity model object") cohen.ci <- function(d, n, conf.level = alpha) { deg.f = n + n - 2 SD <- sqrt(((n + n)/(n * n) + 0.5 * d ^ 2 / deg.f) * ((n + n) / deg.f)) Z <- -stats::qt((1 - alpha) / 2, deg.f) conf.int <- c(d - Z * SD, d + Z * SD) ci <- c(low.ci=conf.int[1], up.ci=conf.int[2]) return(ci) } if(x$constrained == TRUE) { eff <- data.frame(t.value = summary(x$gravity)$tTable[,4], df = summary(x$gravity)$fixDF$terms) eff$cohen.d <- (2 * eff$t.value) / sqrt(eff$df) eff <- eff[-1,] eff <- data.frame(eff, p.value=round(summary(x$gravity)$tTable[,5],6)[-1]) } else { daf <- x$gravity$df.residual tv <- stats::coef(summary(x$gravity))[,"t value"] p <- stats::coef(summary(x$gravity))[, "Pr(>|t|)"] eff <- data.frame(t.value = tv, df = daf)[-1,] eff <- data.frame(eff, p.value=round(p, 6)[-1]) } ci <- list() for(i in 1:nrow(eff)) { if(actual.n) N = length(x$y) else N = eff[,2][i] ci[[i]] <- cohen.ci(d = eff[,3][i], n = N) } ci <- as.data.frame(do.call("rbind", ci)) return(data.frame(eff, ci)) } <file_sep>/R/knn.graph.R #' @title Saturated or K Nearest Neighbor Graph #' @description Creates a kNN or saturated graph SpatialLinesDataFrame object #' #' @param x sf POINTS object #' @param row.names Unique row.names assigned to results #' @param k K nearest neighbors, defaults to saturated (n(x) - 1) #' @param max.dist Maximum length of an edge (used for distance constraint) #' @param drop.lower (FALSE/TRUE) Drop lower triangle of matrix representing #' duplicate edges ie, from-to and to-from #' @param long.lat (FALSE/TRUE) Coordinates are longitude-latitude decimal degrees, #' in which case distances are measured in kilometers #' #' @return SpatialLinesDataFrame object with: #' * i Name of column in x with FROM (origin) index #' * j Name of column in x with TO (destination) index #' * from_ID Name of column in x with FROM (origin) region ID #' * to_ID Name of column in x with TO (destination) region ID #' * length Length of each edge (line) in projection units or kilometers if not projected #' @md #' #' @note ... #' #' @author <NAME> <<EMAIL>> and #' <NAME> <<EMAIL>> #' #' @references #' Murphy, <NAME>. & <NAME>. (in prep). "GenNetIt: gravity analysis in R for landscape #' genetics" #' @references #' <NAME>., <NAME>, <NAME> & <NAME> (2010) Landscape genetics of #' high mountain frog metapopulations. Molecular Ecology 19(17):3634-3649 #' #' @examples #' library(sf) #' data(ralu.site, package="GeNetIt") #' #' # Saturated spatial graph #' sat.graph <- knn.graph(ralu.site, row.names=ralu.site$SiteName) #' head(sat.graph) #' #' # Distanced constrained spatial graph #' dist.graph <- knn.graph(ralu.site, row.names=ralu.site$SiteName, #' max.dist = 5000) #' #' opar <- par(no.readonly=TRUE) #' par(mfrow=c(1,2)) #' plot(st_geometry(sat.graph), col="grey") #' points(st_coordinates(ralu.site), col="red", pch=20, cex=1.5) #' box() #' title("Saturated graph") #' plot(st_geometry(dist.graph), col="grey") #' points(st_coordinates(ralu.site), col="red", pch=20, cex=1.5) #' box() #' title("Distance constrained graph") #' par(opar) #' #' @export knn.graph <- function (x, row.names = NULL, k = NULL, max.dist = NULL, long.lat = FALSE, drop.lower = FALSE) { if (!inherits(x, "sf")) stop("x must be a sf POINT object") if(attributes(x$geometry)$class[1] != "sfc_POINT") stop("x must be a sf sfc_POINT object") if(is.null(k)) k=(dim(x)[1] - 1) knn <- suppressWarnings( spdep::knearneigh(sf::st_coordinates(x), k = k, longlat = long.lat) ) knn.nb <- suppressWarnings( spdep::knn2nb(knn, row.names = row.names, sym = FALSE) ) if(!is.na(sf::st_crs(x))) { prj <- sf::st_crs(x) } else { prj <- sf::st_crs(NA) } if (!is.null(row.names)) { if (length(row.names) != knn$np) stop("row.names wrong length") if (length(unique(row.names)) != length(row.names)) stop("non-unique row.names given") } if (knn$np < 1) stop("non-positive number of spatial units") if (is.null(row.names)) row.names <- as.character(1:knn$np) graph <- spdep::nb2lines(knn.nb, coords = sf::st_coordinates(x), proj4string = prj, as_sf=TRUE) graph$length <- as.numeric(sf::st_length(graph)) names(graph)[3:4] <- c("from_ID","to_ID") graph$from_ID <- as.character(graph$from_ID) graph$to_ID <- as.character(graph$to_ID) rm.lower <- function(x) { ldiag <- function (x, diag=FALSE) { x <- as.matrix(x) if (diag) row(x) >= col(x) else row(x) > col(x) } ctmx <- table(x$i, x$j) ctmx[ldiag(ctmx)] <- 0 ctmx <- dmatrix.df(as.matrix(ctmx)) ctmx <- data.frame(ij=paste(ctmx[,1], ctmx[,2], sep="."), dup=ctmx[,3]) x$ij <- paste(x$i, x$j, sep=".") x <- merge(x, ctmx, by="ij") x <- x[x$dup == 1,] x <- x[,-which(names(x) %in% c("ij","dup"))] return(x) } if(drop.lower == TRUE) { graph <- rm.lower(graph) } if(!is.null(max.dist)) graph <- graph[graph$length <= max.dist,] return( graph ) } <file_sep>/R/covariates-data.R #' @name covariates #' @docType data #' #' @title Subset of raster data for Columbia spotted frog (Rana luteiventris) #' #' @description Subset of data used in Murphy et al., (2010) #' #' @format A 30m LZW compressed tiff: #' \describe{ #' \item{rows}{426} #' \item{columns}{358} #' \item{resoultion}{30 meter} #' \item{projection}{"+proj=utm +zone=11 +datum=NAD83 +units=m +no_defs +ellps=GRS80 +towgs84=0,0,0"} #' \item{cti}{Compound Topographic Index ("wetness")} #' \item{err27}{Elevation Relief Ratio} #' \item{ffp}{Frost Free Period} #' \item{gsp}{Growing Season Precipitation} #' \item{hil}{Heat Load Index} #' \item{nlcd}{USGS Landcover} #' } #' #' @references #' <NAME>., <NAME>, <NAME> & <NAME> (2010) Landscape genetics of high mountain frog metapopulations. Molecular Ecology 19(17):3634-3649 #' NULL<file_sep>/R/ralu.model-data.R #' @name ralu.model #' @docType data #' #' @title Columbia spotted frog (Rana luteiventris) data for specifying gravity model. Note, the data.frame is already log transformed. #' #' @description Subset of data used in Murphy et al., (2010) #' #' @format A data.frame with 190 rows (sites) and 19 columns (covariates): #' \describe{ #' \item{ARMI_ID}{Unique ID} #' \item{FROM_SITE}{Unique from site ID} #' \item{TO_SITE}{Unique to site ID} #' \item{FST}{FST genetic distance} #' \item{DPS}{DPS genetic distance} #' \item{DISTANCE}{Graph edge distance} #' \item{DEPTH_F}{At site water depth} #' \item{HLI_F}{Heat Load Index} #' \item{CTI_F}{Wetness Index} #' \item{DEPTH_T}{At site water depth} #' \item{HLI_T}{Heat Load Index} #' \item{CTI_T}{Wetness Index} #' \item{hli}{Heat Load Index} #' \item{cti}{Wetness Index} #' \item{ffp}{Frost Free Period} #' \item{err27}{Roughness at 27x27 scale} #' \item{rsp}{Relative Slope Position} #' \item{ridge}{Percent Ridge Line} #' \item{hab_ratio}{Ratio of suitable dispersal habitat} #' } #' #' @references #' <NAME>., <NAME>, <NAME> & <NAME> (2010) Landscape genetics of high mountain frog metapopulations. Molecular Ecology 19(17):3634-3649 #' NULL <file_sep>/R/node.statistics.R #' @title raster statistics for nodes #' @description returns raster value or statistics #' (based on specified radius) for node #' #' @param x sp class SpatialPointsDataFrame object #' @param r A rasterLayer, rasterStack or rasterBrick object #' @param buffer Buffer distance, radius in projection units #' @param stats Statistics to calculate. If vectorized, can pass a #' custom statistic function. #' #' #' @return data.frame object of at-node raster values or statistics #' #' @note #' If no buffer is specified, at-node raster values are returned #' #' @author <NAME> <<EMAIL>> and #' <NAME> <<EMAIL>> #' #' @examples #' \donttest{ #' library(sf) #' library(terra) #' #' data(ralu.site) #' xvars <- rast(system.file("extdata/covariates.tif", package="GeNetIt")) #' #' skew <- function(x, na.rm = TRUE) { #' if (na.rm) x <- x[!is.na(x)] #' sum( (x - mean(x)) ^ 3) / ( length(x) * sd(x) ^ 3 ) #' } #' #' # without buffer (values at point) #' system.time( { #' stats <- node.statistics(ralu.site, r = xvars[[-6]]) #' } ) #' #' # with 1000m buffer (values around points) #' system.time( { #' stats <- node.statistics(ralu.site, r = xvars[[-6]], buffer = 1000, #' stats = c("min", "median", "max", "var", "skew")) #' } ) #' } #' #' @export node.statistics node.statistics <- function(x, r, buffer = NULL, stats = c("min", "median", "max") ) { if (!inherits(r, "SpatRaster")) stop("r must be a terra SpatRaster class object") if (!inherits(x, "sf")) stop("x must be a sf POINT object") if(attributes(x$geometry)$class[1] != "sfc_POINT") stop("x must be a sf sfc_POINT object") if(sf::st_is_longlat(x)) warning("Projection is not defined or in lat/long, is it recommended that you project your data to prevent planar distortions in the buffer") if(!sf::st_crs(x) == sf::st_crs(terra::crs(r))) warning("x and r projections do not match") #### Extract raster values intersecting points or buffers if(is.null(buffer)) { message("At-node ([x,y] point) values being returned") results <- terra::extract(r, terra::vect(x)) } else { message(paste0("Using ", buffer, " distance for statistics")) b <- sf::st_buffer(x, dist = buffer) if(!nrow(b) == nrow(x)) stop("Sorry, something went wrong with buffering, features do not match") ldf <- exactextractr::exact_extract(r, b, progress = FALSE) ldf <- lapply(ldf, FUN = function(x) { j <- as.data.frame(x[,-which(names(x) %in% "coverage_fraction")]) names(j) <- names(r) return(j)}) names(ldf) <- row.names(x) stats.fun <- function(x, m = stats) { slist <- list() for(i in 1:length(m)) { slist[[i]] <- apply(x, MARGIN=2, m[i]) } return( as.data.frame(t(unlist(slist))) ) } results <- lapply(ldf, FUN=stats.fun) results <- do.call("rbind", results) rn <- vector() for(n in stats) { rn <- append(rn, paste(n, names(r), sep="."))} names(results) <- rn } return( results ) } <file_sep>/R/predict.gravity.R #' @title Predict gravity model #' @description predict method for class "gravity" #' #' @param object Object of class gravity #' @param newdata New data used for obtaining the predictions, can #' be a data.frame or nffGroupedData #' @param groups Grouping factor acting as random effect. If used, #' must match levels used in model, otherwise leave it #' null and do not convert to groupedData #' @param back.transform Method to back transform data, default is none and #' log predictions will be returned. #' #' @param ... Arguments passed to predict.lme or predict.lm #' #' @return Vector of model predictions #' #' @details #' Please note that the entire gravity equation is log transformed so, #' your parameter space is on a log scale, not just y. This means that for #' a meaningful prediction the "newdata" also needs to be on a log scale. #' #' For the back.transform argument, the simple back-transform method uses the #' form exp(y-hat)0.5*variance whereas Miller uses exp(sigma)*0.5 as the #' multiplicative bias factor. Naihua regresses y~exp(y-hat) with no intercept #' and uses the resulting coefficient as the multiplicative bias factor. The #' Naihua method is intended for results with non-normal errors. You can check #' the functional form by simply plotting y (non-transformed) against the fit. #' The default is to output the log scaled predictions. #' #' @references #' <NAME>. (1984) Reducing Transformation Bias in Curve Fitting #' The American Statistician. 38(2):124-126 #' @references #' <NAME>. (1983) Smearing Estimate: A Nonparametric Retransformation Method #' Journal of the American Statistical Association, 78(383):605–610. #' #' @author <NAME> <<EMAIL>> and #' <NAME> <<EMAIL>> #' #' @examples #' library(nlme) #' data(ralu.model) #' #' back.transform <- function(y) exp(y + 0.5 * stats::var(y, na.rm=TRUE)) #' rmse = function(p, o){ sqrt(mean((p - o)^2)) } #' #' x = c("DEPTH_F", "HLI_F", "CTI_F", "cti", "ffp") #' #' sidx <- sample(1:nrow(ralu.model), 100) #' train <- ralu.model[sidx,] #' test <- ralu.model[-sidx,] #' #' # Specify constrained gravity model #' ( gm <- gravity(y = "DPS", x = x, d = "DISTANCE", group = "FROM_SITE", #' data = train, ln = FALSE) ) #' #' ( p <- predict(gm, test[,c(x, "DISTANCE")]) ) #' rmse(back.transform(p), back.transform(ralu.model[,"DPS"][-sidx])) #' #' # WIth model sigma-based back transformation #' ( p <- predict(gm, test[,c(x, "DISTANCE")], back.transform = "simple") ) #' ( p <- predict(gm, test[,c(x, "DISTANCE")], back.transform = "Miller") ) #' ( p <- predict(gm, test[,c(x, "DISTANCE")], back.transform = "Naihua") ) #' #' # Using grouped data #' test <- nlme::groupedData(stats::as.formula(paste(paste("DPS", 1, sep = " ~ "), #' "FROM_SITE", sep = " | ")), #' data = test[,c("DPS", "FROM_SITE", x, "DISTANCE")]) #' #' ( p <- predict(gm, test, groups = "FROM_SITE") ) #' ( y.hat <- back.transform(ralu.model[,"DPS"][-sidx]) ) #' na.idx <- which(is.na(p)) #' rmse(back.transform(p)[-na.idx], y.hat[-na.idx]) #' #' # Specify unconstrained gravity model (generally, not recommended) #' ( gm <- gravity(y = "DPS", x = x, d = "DISTANCE", group = "FROM_SITE", #' data = train, ln = FALSE, constrained=TRUE) ) #' #' ( p <- predict(gm, test[,c(x, "DISTANCE")]) ) #' rmse(back.transform(p), back.transform(ralu.model[,"DPS"][-sidx])) #' #' @import nlme #' @method predict gravity #' @export predict.gravity <- function(object, newdata, groups = NULL, back.transform = c("none", "simple", "Miller", "Naihua"), ...) { back.transform = back.transform[1] if(inherits(object$gravity, "lme")) { fixed.fml <- object$fixed.formula random.fml <- object$random.formula m <- do.call(nlme::lme.formula, list(fixed = object$fixed.formula, data = object$gravity$data, random = object$random.formula)) if(!is.null(groups)) { message("Making individual-level (per-slope group) constrained predictions") p <- stats::predict(m, newdata, Q = groups) } else { message("Making population-level constrained predictions") # p <- nlme:::predict.lme(m, newdata, level = 0) p <- stats::predict(m, newdata, level = 0) } } else if(!inherits(object$gravity, "lm")) { message("Making population-level unconstrained predictions") p <- stats::predict(object, newdata) } if(back.transform != "none") { if(back.transform == "simple") { message("Back-transforming exp(y-hat)*0.5*variance(y-hat), assumes normally distributed errors") p <- exp(p + 0.5 * stats::var(p)) } else if(back.transform == "Miller") { message("Miller back-transformation using: exp(sigma)*0.5*exp(y-hat)0.5*variance(y-hat), assumes normally distributed errors") p <- exp((summary(object$gravity)$sigma)*0.5) * exp(p + 0.5 * stats::var(p)) } else if(back.transform == "Naihua") { message("Naihua back-transformation using: y ~ exp(y-hat) regression with no intercept, does not assume normally distributed errors") p1 <- exp(object$gravity$fitted[,1]) y <- stats::coef(stats::lm(object$y-0 ~ p1))[2] p <- y * exp(p) } } return(p) } <file_sep>/R/area.graph.statistics.R #' @title Statistics for edges (lines) based on a defined scale (area). #' @description Samples rasters for each edge and calculates specified #' statistics for buffer distance #' #' @param ... Parameters to be passed to the modern version of the function #' #' @note Please note that this function has been deprecated, please use graph.statistics #' with the buffer argument. #' #' @export area.graph.statistics <- function(...) { .Deprecated("area.graph.statistics", package="GeNetIt", msg="this function is depreciated, please use graph.statistics with buffer argument") graph.statistics(...) } <file_sep>/R/dps-data.R #' @name dps #' @docType data #' #' @title dps genetic distance matrix for Columbia spotted frog (Rana luteiventris) #' #' @description Subset of data used in Murphy et al., (2010) #' #' @format A 29 x 29 genetic distance matrix: #' #' @references #' <NAME>., <NAME>, <NAME> & <NAME> (2010) Landscape genetics of high mountain frog metapopulations. Molecular Ecology 19(17):3634-3649 #' NULL
d181febd82e6c87497392b1c213049ec01512505
[ "R" ]
20
R
cran/GeNetIt
3c45465d55d7f69eae5be7cb990e73570132365f
f97a231de40195feb312f93e65ed343205c72564
refs/heads/main
<repo_name>paidibonan/origami-lamp<file_sep>/README.md # origami-lamp Arduino code for color changing origami lamp Arduino board is placed into the center of a stellated icosahedron made from origami sonobe units. <file_sep>/gradientLED.ino const int greenLEDpin = 9; const int redLEDpin = 10; const int blueLEDpin = 11; int redValue = 125; int greenValue = 190; int blueValue = 255; boolean redIncr = false; boolean greenIncr = false; boolean blueIncr = false; void setup() { // put your setup code here, to run once: Serial.begin(9600); pinMode(greenLEDpin, OUTPUT); pinMode(blueLEDpin, OUTPUT); pinMode(redLEDpin, OUTPUT); } void loop() { // put your main code here, to run repeatedly: if (redIncr) { if (redValue >= 255) { redIncr = false; } else { redValue = redValue + 5; } } else { if (redValue <= 0) { redIncr = true; } else { redValue = redValue - 5; } } if (blueIncr) { if (blueValue >= 255) { blueIncr = false; } else { blueValue = blueValue + 5; } } else { if (blueValue <= 0) { blueIncr = true; } else { blueValue = blueValue - 5; } } if (greenIncr) { if (greenValue >= 255) { greenIncr = false; } else { greenValue = greenValue + 5; } } else { if (greenValue <= 0) { greenIncr = true; } else { greenValue = greenValue - 5; } } analogWrite(redLEDpin, redValue); analogWrite(blueLEDpin, blueValue); analogWrite(greenLEDpin, greenValue); delay(1000); }
6137eeef89bfb7d7d43c781b48ee8a2f87dc3481
[ "Markdown", "C++" ]
2
Markdown
paidibonan/origami-lamp
5dccb7691e1254872dfce7c3ade2ded7b11ba179
f7e74995cec6dbda669c1e9aae1dccc0858d1531
refs/heads/master
<file_sep><?php namespace App\Controller; use App\Model\Entity\Exchangerates; use \Cake\Database\Expression\QueryExpression; use Cake\I18n\Number; use Cake\Event\Event; use Cake\Log\Log; use Cake\Validation\Validator; class AdminController extends AppController{ public function beforeFilter(Event $event) { $this->loadModel('Exchangerates'); $this->loadModel('Users'); parent::beforeFilter($event); } private function userLogFile(){ Log::config('currencies', [ 'className' => 'File', 'path' => LOGS, 'levels' => ['debug'], 'scopes' => ['currencies'], 'file' => 'currencies.log', ]); } // Fetch all users public function index(){ $results = $this->Users->find('all'); foreach($results as $key=>$value){ $users[] = $value; } $this->set('user', $users); $this->render(); } //Fetch user detail to edit public function edit($id){ $results = $this->Users->get($id); $this->set('user', $results); $this->render(); } //Update the user public function update($id){ $user = $this->Users->get($id); $this->Users->patchEntity($user, $this->request->getData()); if ($this->Users->save($user)) { $this->Flash->success(__('User has been updated.')); }else{ $this->Flash->error(__('Unable to update user.')); } return $this->redirect([ 'controller' => 'admin', 'action' => 'edit/'.$id ]); } //Delete the user public function delete($id){ $delete_user = $this->Users->get($id); $result = $this->Users->delete($delete_user); if($result){ $this->Flash->success(__('User has been deleted')); }else{ $this->Flash->error(__('Unable to delete the user')); } return $this->redirect([ 'controller' => 'admin', 'action' => 'index' ]); } }<file_sep><?php /** * CakePHP(tm) : Rapid Development Framework (https://cakephp.org) * Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org) * * Licensed under The MIT License * For full copyright and license information, please see the LICENSE.txt * Redistributions of files must retain the above copyright notice. * * @copyright Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org) * @link https://cakephp.org CakePHP(tm) Project * @since 0.10.0 * @license https://opensource.org/licenses/mit-license.php MIT License */ use Cake\Cache\Cache; use Cake\Core\Configure; use Cake\Core\Plugin; use Cake\Datasource\ConnectionManager; use Cake\Error\Debugger; use Cake\Http\Exception\NotFoundException; $this->layout = 'default'; ?> <!DOCTYPE html> <html> <head> <?= $this->Html->charset() ?> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title> <?= $cakeDescription ?> </title> <?= $this->Html->meta('icon') ?> <?= $this->Html->css('base.css') ?> <?= $this->Html->css('style.css') ?> <?= $this->Html->css('home.css') ?> <link href="https://fonts.googleapis.com/css?family=Raleway:500i|Roboto:300,400,700|Roboto+Mono" rel="stylesheet"> </head> <body class="home"> <?php echo $this->Form->create(null, ['url' => ['controller' => 'Exchangerates', 'action' => 'import']]); ?> <!-- <form action="conversions/convert" method="post" style="width: 320px;padding-left: 100px;"> --> <div> <label>Import Json: </label> <input type="file" name=jsonFile> </div> <div> <label for="">Import: </label> <input type="submit" value="Import" name="Import"> </div> </form> </body> </html> <file_sep><?php namespace App\Shell; use Cake\Console\Shell; class UserShell extends Shell { public $tasks = ['Sound']; public function initialize() { parent::initialize(); $this->loadModel('Users'); } public function main() { $this->out("Hello World"); } public function show() { if (empty($this->args[0])) { return $this->abort('Please enter a username.'); } $user = $this->Users->findByUsername($this->args[0])->first(); $this->out(print_r($user, true)); } }<file_sep>## Installation After taking clone of the project run `composer update` command from you project's root directory. You can now either use your machine's webserver to view the default home page, or start up the built-in webserver with: ```bash bin/cake server -p 8765 ``` Then visit `http://localhost:8765` to see the welcome page. OR Visit `localhost/project_dir_name/` ## MYSQL 1) Import currency_converter.sql database file from root directory to your phpmyadmin. 2) Go to localhost/project_dir_name. You will get this configuration error - `Could not load configuration file: C:\xampp\htdocs\project_name_dir\config\app.php` 3) For this go to project_name_dir/config create app.php file and copy the content from app.default.php to app.php 4) In app.php search for Datasources and add the database connection information. ## Links By using this link `localhost/conversions/login` user and admin can login to the application. <file_sep><?php namespace App\Controller; use Cake\I18n\Time; use Cake\Datasource\ConnectionManager; class ExchangeratesController extends AppController { public function index(){ $this->set('rates', $this->Exchangerates->find('all')); $this->render(); } public function import(){ $conn = ConnectionManager::get('default'); $datetime = Time::now(); $results = $conn ->execute('SELECT `country_code` FROM countries') ->fetchAll('assoc'); foreach($results as $value){ $base_code = strtolower($value['country_code']); $exchangerates_url = "http://www.floatrates.com/daily/"."$base_code".".json"; $content = json_decode(file_get_contents($exchangerates_url), true); $baseCurr[] = $value['country_code']; foreach($content as $new){ echo "already inserted"; // $conn->insert('exchangerates', [ // 'base_currency' => $value['country_code'], // 'target_currency' => (string)$new['code'], // 'rates' => (float)$new['rate'], // 'created' => $datetime, // 'updated' => $datetime // ]); // $values[] = '("'. $value['country_code'].$new['code'] .'","' . (string)$new['code'] . '", ' . (float)$new['rate'] . ', '.$datetime.', '.$datetime.')'; } }d } } ?><file_sep><?php /** * CakePHP(tm) : Rapid Development Framework (https://cakephp.org) * Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org) * * Licensed under The MIT License * For full copyright and license information, please see the LICENSE.txt * Redistributions of files must retain the above copyright notice. * * @copyright Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org) * @link https://cakephp.org CakePHP(tm) Project * @since 0.10.0 * @license https://opensource.org/licenses/mit-license.php MIT License */ use Cake\Cache\Cache; use Cake\Core\Configure; use Cake\Core\Plugin; use Cake\Datasource\ConnectionManager; use Cake\Error\Debugger; use Cake\Http\Exception\NotFoundException; $this->layout = 'default'; ?> <?= $this->Flash->render('error');?> <div class="row"> <?php $current_user = $this->request->session()->read('Auth.User'); if($current_user['role'] == 'admin') { ?> <span style="float:right;font-size:15px;"> <?php echo $this->Html->link( 'Show All Users', ['controller' => 'admin', 'action' => 'index'] ); ?> </span> <?php }?> <div class="col-md-offset-3 col-md-6"> <?php echo $this->Form->create(null, ['url' => ['controller' => 'Conversions', 'action' => 'convert']]); ?> <fieldset> <h1 class="display-4 text-center">Convert Currencies</h1> <?= $this->Form->input('from', ['options' => $country,'label' => 'From', 'value' => $country, 'empty' => 'Select Currency']); ?> <?= $this->Form->control('amount', ['class' => 'form-group']) ?> </fieldset> <?= $this->Form->button(__('Convert'), ['class' => 'btn btn-lg btn-primary btn-block', 'style' => 'margin-top:14px']); ?> <?= $this->Form->end() ?> </div> </div> <file_sep><?php $this->layout = "default"; ?> <div class="row"> <div class="col-md-offset-3 col-md-6"> <?= $this->Flash->render() ?> <?= $this->Form->create($user) ?> <fieldset> <h1 class="display-4 text-center">Add User <?php $current_user = $this->request->session()->read('Auth.User'); if($current_user['role'] == 'admin') { ?> <span style="float:right;font-size:13px;"> <?php echo $this->Html->link('Go Back To Admin Page', array('controller' => 'admin', 'action' => 'index')); ?> </span> <?php } ?> </h1> <?= $this->Form->control('username', ['class' => 'form-group']) ?> <?= $this->Form->control('password', ['class' => 'form-group']) ?> <?= $this->Form->control('client_ip', ['type' => 'hidden', 'value' => $client_ip]) ?> <?= $this->Form->control('role', [ 'options' => ['' => 'Select Role', 'admin' => 'Admin', 'user' => 'User'] ]) ?> </fieldset> <?= $this->Form->button(__('Submit'), ['class' => 'btn btn-lg btn-primary btn-block', 'style' => 'margin-top:14px']); ?> <?= $this->Form->end() ?> <div class="col-md-offset-3 col-md-6" style="margin-top:10px;"> <div class="d-flex justify-content-center links"> Already have an account? <a href="/users/login" class="ml-2"> <?php echo $this->Html->link('Login', array('controller' => 'users', 'action' => 'login')); ?> </a> </div> </div> </div> </div><file_sep><?php $this->layout = "default"; ?> <div class="container"> <?php //echo '<pre>';print_r($user);die;?> <h2>Users List <span style="float:right;font-size:15px;"> <?= $this->Html->link( 'Add New User', ['controller' => 'users', 'action' => 'add'] );?> </span> </h2> <table class="table"> <thead> <tr> <th>Username</th> <th>IP</th> <th>Action</th> </tr> </thead> <tbody> <?php foreach($user as $user_detail) { ?> <tr> <td><?= $user_detail['username']; ?></td> <td><?= $user_detail['client_ip']; ?></td> <td><?= $this->Html->link( 'Delete User', ['controller' => 'admin', 'action' => 'delete/'.$user_detail['id']] );?> | <?= $this->Html->link( 'Edit User', ['controller' => 'admin', 'action' => 'edit/'.$user_detail['id']] );?> </td> </tr> <?php } ?> </tbody> </table> </div><file_sep><!-- File: src/Template/Users/login.ctp --> <?php $this->layout = "default"; ?> <div class="row"> <div class="col-md-offset-3 col-md-6"> <?= $this->Flash->render() ?> <?= $this->Form->create() ?> <fieldset> <h1 class="display-4 text-center">Login </h1> <?= $this->Form->control('username', ['class' => 'form-group']) ?> <?= $this->Form->control('password', ['class' => 'form-group']) ?> <?= $this->Form->checkbox('remember_me'); ?> Remember Me </fieldset> <?= $this->Form->button(__('Login'), ['class' => 'btn btn-lg btn-primary btn-block', 'style' => 'margin-top:14px']); ?> <?= $this->Form->end() ?> <div class="col-md-offset-3 col-md-6" style="margin-top:10px;"> <div class="d-flex justify-content-center links"> Don't have an account? <a href="/users/add" class="ml-2"> <?php echo $this->Html->link('Sign Up', array('controller' => 'users', 'action' => 'add')); ?> </a> </div> </div> </div> </div> <file_sep><?php namespace App\Model\Table; use Cake\ORM\Table; // use Cake\ORM\Rule\IsUnique; use Cake\Validation\Validator; class UsersTable extends Table{ public function initialize(array $config) { $this->addBehavior('Timestamp'); } //Added some custom validation rules for unique username and length of passwords public function validationDefault(Validator $validator){ return $validator ->notEmpty('username', 'Please enter username') ->notEmpty('password', 'Please enter password') ->add('username', 'uniqueUsername', [ 'rule' => function($value, $context){ if(isset($context['data']['id'])) { return !$this->exists(['username' => $value, 'id !=' => $context['data']['id']]); } return !$this->exists(['username' => $value]); }, 'message' => 'Username already registered', ]) ->add('password', 'length', ['rule' => ['lengthBetween', 8, 10]]) ->notEmpty('role', 'inList', [ 'rule' => ['inList', ['admin', 'user']], 'message' => 'Please enter a valid role' ]); } } ?><file_sep><?php /** * CakePHP(tm) : Rapid Development Framework (https://cakephp.org) * Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org) * * Licensed under The MIT License * For full copyright and license information, please see the LICENSE.txt * Redistributions of files must retain the above copyright notice. * * @copyright Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org) * @link https://cakephp.org CakePHP(tm) Project * @since 0.10.0 * @license https://opensource.org/licenses/mit-license.php MIT License */ use Cake\Cache\Cache; use Cake\Core\Configure; use Cake\Core\Plugin; use Cake\Datasource\ConnectionManager; use Cake\Error\Debugger; use Cake\Http\Exception\NotFoundException; $this->layout = 'default'; ?> <h1 class="display-4 text-center">Converted Values</h1> <div class="table-responsive"> <table class="table table-bordered"> <thead> <tr> <th scope="col">#</th> <?php foreach($converted_currency as $values) { ?> <th scope="col"><?= $values['fromcurr']; ?></th> <?php } ?> </tr> </thead> <tbody> <tr> <th scope="row"></th> <?php foreach($converted_currency as $values) { ?> <td><?= $values['newvalue']; ?></td> <?php } ?> </tr> </tbody> </table> </div> <file_sep><?php namespace App\Controller; use App\Model\Entity\Exchangerates; use \Cake\Database\Expression\QueryExpression; use Cake\I18n\Number; use Cake\Event\Event; use Cake\Log\Log; use Cake\Validation\Validator; class ConversionsController extends AppController{ public function beforeFilter(Event $event) { $this->loadModel('Exchangerates'); $this->loadModel('Countries'); parent::beforeFilter($event); } private function currenciesLogFile(){ Log::config('currencies', [ 'className' => 'File', 'path' => LOGS, 'levels' => ['debug'], 'scopes' => ['currencies'], 'file' => 'currencies.log', ]); } /* Load all the countries and country code from `countries` database table and send to index view file */ public function index(){ $results = $this->Countries->find('all'); foreach($results as $key=>$value){ $country[$value['country_code']] = $value['country_name']; } $this->set('country', $country); $this->render(); } //Convert the user selected currencies to other public function convert(){ //Validation for float values $validator = new Validator(); $validator ->notEmpty('from', 'Please select field') ->notEmpty('amount', 'Please enter amount') ->notEmpty('amount', array( 'rule' => array('decimal', 2), 'message' => 'Please enter only numbers', ) ); $this->currenciesLogFile(); $errors = $validator->errors($this->request->getData()); if(empty($errors)){ if($this->request->data){ $data = $this->request->data; $results = $this->Countries->find('all'); $results->select(['country_code']); Log::debug('User is trying to Convert Currencies:'.print_r(json_encode($this->request->data), true), ['scope' => ['currencies']]); foreach($results as $tarcountry){ $query = $this->Exchangerates->find('all') ->where(function (QueryExpression $exp) use($tarcountry) { $orConditions = $exp->or_(['target_currency' => $tarcountry['country_code']]) ->eq('target_currency', $tarcountry['country_code']); return $exp ->add($orConditions) ->eq('base_currency', $this->request->data['from']); }); $query->select(['target_currency','rates']); if(isset($query)){ foreach ($query as $row) { $converted_currency[] = [ 'fromcurr' => $row['target_currency'], 'newvalue' => Number::precision($data['amount'] * ($row['rates']),2) ]; } Log::debug('Converted value'.print_r(json_encode($converted_currency), true), ['scope' => ['currencies']]); }else{ Log::debug('Not able to convert currencies', ['scope' => ['currencies']]); } } } $this->set('converted_currency', $converted_currency); $this->render(); }else{ Log::debug('User did not entered any values', ['scope' => ['currencies']]); $this->Flash->error(__('Please enter values')); return $this->redirect([ 'controller' => 'conversions', 'action' => 'index' ]); } } } ?><file_sep><?php namespace App\Controller; use App\Controller\AppController; use Cake\Http\Exception\ForbiddenException; use Cake\Http\Exception\NotFoundException; use Cake\Event\Event; use Cake\Log\Log; class UsersController extends AppController{ public $components = ['Cookie']; public function beforFilter(Event $event){ parent::beforFilter($event); $this->Auth->allow(['add', 'logout']); } //Function to create log file for user private function usersLogFile(){ Log::config('users', [ 'className' => 'File', 'path' => LOGS, 'levels' => ['debug'], 'scopes' => ['users'], 'file' => 'users.log', ]); } /* Checks user entered credentials along with IP address if successfull allow the user to login */ public function login(){ $is_user_loggedin = $this->request->session()->read('Auth.User'); if(!empty($is_user_loggedin)){ $this->redirect([ 'controller' => 'conversions', 'action' => 'index' ]); } if($this->request->is('post')){ $this->usersLogFile(); Log::debug('User is trying to login:'.print_r(json_encode($this->request->data), true), ['scope' => ['users']]); $user = $this->Auth->identify(); if($user){ if($user['client_ip'] == $this->request->clientIp()){ Log::debug('User logged in successfully', ['scope' => ['users']]); $this->Auth->setUser($user); $this->_setCookie(); return $this->redirect($this->Auth->redirectUrl()); }else{ $this->Flash->error(__('Due to invalid IP, You are not authorized to Login. ')); } }else{ $this->Flash->error(__('Invalid Username or Password, Please try again')); } } } // If remember me field is true it sets the cookie for 1 week protected function _setCookie() { if (!$this->request->data('remember_me')) { return false; } $data = [ 'username' => $this->request->data('username'), 'password' => $this->request->data('<PASSWORD>') ]; $this->Cookie->write('RememberMe', $data, true, '+1 week'); return true; } //After logout redirect user to login page public function logout(){ $this->usersLogFile(); Log::debug('User is trying to logout:', ['scope' => ['users']]); return $this->redirect($this->Auth->logout()); } //Add the user in database along with the Ip address public function add(){ $client_ip = $this->request->clientIp(); $this->set('client_ip', $client_ip); $user = $this->Users->newEntity(); if($this->request->is('post')){ $this->usersLogFile(); Log::debug('New user is being signing Up', ['scope' => ['users']]); $user = $this->Users->patchEntity($user, $this->request->getData()); if($this->Users->save($user)){ Log::debug('New User has been added'.print_r(json_encode($this->request->data), true), ['scope' => 'users']); $this->Flash->success(__('The user has been saved.')); return $this->redirect(['action' => 'add']); }else{ Log::debug('New User has been added'.print_r(json_encode($this->request->data), true), ['scope' => 'users']); } $this->Flash->error(__('Cannot save the user')); } $this->set('user', $user); } } ?><file_sep><?php $this->layout = "default"; ?> <div class="row"> <div class="col-md-offset-3 col-md-6"> <?= $this->Flash->render() ?> <!-- <form method="post" action="<?php //'/admin/update/'.$user['id']; ?>"> --> <?= $this->Form->create(null, ['url' => ['action' => 'update/'.$user['id']]]) ?> <fieldset> <h1 class="display-4 text-center">Edit User </h1> <?= $this->Form->control('username', ['class' => 'form-group', 'value' => $user['username']]) ?> <?= $this->Form->control('client_ip', ['class' => 'form-group', 'value' => $user['client_ip']]) ?> </fieldset> <?= $this->Form->button(__('Update'), ['class' => 'btn btn-lg btn-primary btn-block', 'style' => 'margin-top:14px']); ?> <?= $this->Form->end() ?> </div> </div>
8314aa33709c661f42f68c9b3dc44892e33d8b26
[ "Markdown", "PHP" ]
14
PHP
mshende-project/currencyconversion
8b6ead7b743a131492b61fa8b5b11ffe48b982d0
efa7bb2c9e1dce596fe40f6df2eabe9318f81eb2
refs/heads/master
<file_sep>README.md # UseJunit5 Test With JUnit 5 To create a simple test Create a class in the class create a void method use the @Test use the basics assertEquals expected / actual check is a object is not null assertNotNull check is a object is null assertNull for boolean values check is actual is false assertFalse check is actual is true assertTrue to Array check is one array is same than another assertArrayEquals( expected , actual ); this check all position same equals and the size is the same the annotation @BeforeEach is execute before (antes) all test if you has 3 test the method is run 3 times the annotation @AfterEach is execute after (depois) all test if you has 3 test the method is run 3 times the methods with @BeforeEach and @AfterEach you can use a parameter TestInfo with a instance o TestInfo you can get the name of method With the JUnit 4 use @Before and @After but the TestInfo not present TestInfo is only in JUnit 5 You can use the @BeforeAll to connect the database for exemple this method need to be static the method is call frist before than all tests You can use the @AfterAll to close connect the database for exemple this method need to be static the method is call after before than all tests In JUnit 5 the word public is not required in test's the annotation @DisplayName show the message that you put in before run the test @ParameterizedTest you can use multiple values with this annotation use with the @ValueSource sample @ParameterizedTest @ValueSource(strings= { "ABCD" , "ABC", "AB" } ) void lengthMoreThanZeroParametrize(String string) { assertTrue( string.length() > 0 ); } //Sample to give name to ParameterizedTest I can change the output of test with @ParameterizedTest( name = "the string {0} length is {1}") //change de out put {0} before ',' and {1} after ', I can repeat many time with RepeatedTest @RepeatedTest( 3 ) I can try de performace with assertTimeout Use a the aegs : aTime, () -> { <my source> } assertTimeout( Duration.ofSeconds(5), () -> { for (int i = 0; i < 100; i++ ) { System.out.println( i ); } }); I can disable a test @Disabled in JUnit 5 with 4 use @Ignored If I can not run any Test in a class I use @Disable in the class when I use in classe any test not run the annotation @Nested I can use to use a nested class when a run a test JUnit 5 x JUnit 4 != @BeforeAll instead of @BeforeClass @AfterAll instead of @AfterClass @BeforeEach instead of @Before @AfterEach instead of @After @Disable instead of @Ignote @Tag instead of @Category assertThrows instead of expected attibute assertTimeout instead of timeout attibute New in JUnit 5 @Nested for nested tests @RepeatedTest to execute tests mulpiple times Best pratices for good unit test 1 Readable Look at the test and you know what is begin tested (I can read the class test and know what the test is do in 15 seconds) 2 Fast what happerns if unit tests take a long time to run? (think abaout what the advantage of unit test is lost 2 hours?) 3 Isolated Fails only when there is an issue whith code! (is not good if they star failing because of an external depedency not avaliable then the fail) 4 Run often What is the use having unit test which are note run frenquently? What happens if you do not commit code often? <file_sep>import org.junit.jupiter.api.*; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.*; import static org.junit.jupiter.api.Assertions.assertNotNull; /** * Created by Artur on 04/06/18. * Simple test for use JUnit 5 and new features */ public class EnunTest { enum Pet { CAT, DOG, WOLF; } @DisplayName("Should pass only the specified enum value as a method parameter") @ParameterizedTest(name = "{index} => pet=''{0}''") @EnumSource(value = Pet.class, names = {"CAT"}) void shouldPassNonNullEnumValueAsMethodParameter(Pet pet) { assertNotNull(pet); } } <file_sep>import org.junit.jupiter.api.*; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.CsvSource; import org.junit.jupiter.params.provider.ValueSource; import java.time.Duration; import static org.junit.jupiter.api.Assertions.*; /** * Created by Artur on 04/06/18. * Simple test for use JUnit 5 and new features */ //@Disabled if I can run any test in this class I can use @Disabled in a class public class StringTest { private String aString = null; @BeforeAll public static void useBeforAll() { System.out.println("Initialize the connection of DataBase "); } @AfterAll public static void useAfterAll() { System.out.println("Close the connection of DataBase "); } @BeforeEach public void initTest(TestInfo info ) { System.out.println("Test method " + info.getDisplayName() ); } @AfterEach public void closeTest(TestInfo info) { System.out.println("End test method " + info.getDisplayName() ); } @Test public void lengthTestBasic() { int actualLength = "ABCD".length(); int expectedLength = 4; assertEquals( expectedLength, actualLength ); //Assert is lenght == 4 //write test code //Invoke method square(4) => 4 x 4 = 16 CUT Core Under Test //check in place - 16 => Assertions } @Test public void toUpperCaseBasic() { String str = "abcd"; String result = str.toUpperCase(); assertNotNull( result ); //assertNull(); assertEquals( "ABCD" , result); } @Test public void checkIsObjectNull() { String str = null; assertNull( str ); } @Test public void containsBasic() { String str = "abcd"; //not has 'efg' in str boolean result = str.contains("efg"); assertEquals( false , result); //or use assertFalse( result ); //or use for boolean expected true value //assertTrue( result ); } @Test public void slipeBasic() { String str = "abc dfg hij"; String actual[] = str.split(" "); String expected[] = new String[] { "abc", "dfg", "hij" }; assertArrayEquals( expected , actual ); } @Test @DisplayName("when the thowException thow a NullPointerException") public void thowException() { String str = null; assertThrows( NullPointerException.class, () -> { str.length(); }); } @Test public void lengthMoreThanZero() { assertTrue( "ABCDE".length() > 0 ); assertTrue( "ABCD".length() > 0 ); assertTrue( "ABC".length() > 0 ); assertTrue( "AB".length() > 0 ); assertTrue( "A".length() > 0 ); } @ParameterizedTest @ValueSource(strings= { "ABCD" , "ABC", "AB" } ) public void lengthMoreThanZeroParametrize(String string) { assertTrue( string.length() > 0 ); } @ParameterizedTest @CsvSource( value = { "abcd,ABCD", "abc,ABC", "ab,AB", "a,A"}) // to default delimiter is ',' public void multipleUpperCaseCheck(String str, String capitalized) { assertEquals( capitalized, str.toUpperCase() ); } //Sample to give name to ParameterizedTest @ParameterizedTest( name = "the string {0} length is {1}") //change de out put {0} before ',' and {1} after ', @CsvSource( value = { "abcd,4", "abc,3", "ab,2", "a,1", "'',0"}) public void multipleUpperLenght(String str, int expectedLength) { assertEquals( str.length(), expectedLength ); } @Test @RepeatedTest( 3 ) // only in JUnit 5 @DisplayName("repatManyTimesTest") public void repatManyTimesTest() { assertEquals("same", "same"); } @Test public void performedTest() { assertTimeout( Duration.ofSeconds(5), () -> { for (int i = 0; i < 100; i++ ) { System.out.println( i ); } }); } @Test @Disabled @DisplayName("noRun") public void noRun() { assertTrue( true ); } @Nested @DisplayName("For a empty String") class EmptyStringTest { @BeforeEach void setEmpty() { aString = ""; } @Test @DisplayName("length should be 0 ") void lengthZero() { assertEquals( 0 , aString.length() ); } @Test @DisplayName("upper case is zero should be 0 ") void toUpperCaseNested(){ assertEquals( "", aString.toUpperCase() ); } } @Nested @DisplayName("For large strings") class LargeStringTest { @BeforeEach @DisplayName("init aString") void setLargeString() { StringBuilder stringBuilderTableAscii = new StringBuilder(); for ( int i = 32; i < 127 ; i++ ) { stringBuilderTableAscii.append( (char) i ); } aString = stringBuilderTableAscii.toString(); } @Test void test() { } } }
d275c8655cc51f7a02b4557d690e089dafbf067f
[ "Markdown", "Java" ]
3
Markdown
artodeschini/UseJunit5
8f38a9c5a9cf4c8dc3b5a0450c034f5ae08cdfd9
1c7ea75d7c014dbc9fd08d35817190a12cad79a8
refs/heads/main
<file_sep>// Bring in the database configuration const userdb = require("../data/dbConfig"); // Create the helper functions for the user database module.exports = { addUser, getUserBy, getUser, getUserById }; function addUser({ email, first_name, last_name, password, is_admin, is_Landlord, is_agent, username }) { // This is the SQL equivalent of INSERT INTO users(columns) VALUES(data to be added) return userdb("users").insert({ email, first_name, last_name, password, is_admin, is_Landlord, is_agent, username }).then(ids=>{ }); } function getUserBy(username) { return userdb("users").where({ username }); } function getUserById(id) { return userdb("users").where({ id }).first(); } function getUser() { return userdb("users"); } // const userdb = require("../data/dbConfig"); // module.exports = { // getUser, // addUser, // getUserBy, // getUserById, // deleteUser, // }; // function getUser() { // const query = userdb("users").select("id", "username"); // return query; // } // async function addUser(user) { // const [id] = await userdb("users").insert(user, "id"); // return getUserById(id); // } // function getUserById(id) { // return userdb("users").where({ id }).first(); // } // function getUserBy(filter) { // return userdb("users").where(filter); // } // function deleteUser(id) { // return userdb("users").where({ id }).del(); // } <file_sep>module.exports = (req, res, next) => { console.log(`KOKO`, req.decodedToken); if (req.decodedToken.is_agent) { next(); } else { res.status(403).json({ message: "You are not an agent" }); } }; <file_sep>// Bring in express const express = require("express"); // Bring in the helper functions from userDB.js const users = require("./userDB"); // Import the router const router = express.Router(); // Bring in bcrypt const bcrypt = require("bcryptjs"); // Bring in the token generation function from the token folder const genToken = require("../auth/token"); // Bring in express router for validation const { check, validationResult } = require("express-validator"); // Bring in nodemailer for sending emails var nodemailer = require("nodemailer"); var transporter = nodemailer.createTransport({ service: "gmail", auth: { user: "<EMAIL>", pass: "<PASSWORD>", }, tls: { rejectUnauthorized: false }, }); // Users endpoints here 👇👇👇 // This is the register endpoint router.post( "/register", check("email", "Email is Required").isEmail(), check("first_name").not().isEmpty().withMessage("First name is required"), check("last_name").not().isEmpty().withMessage("Last name is required"), check("password", "<PASSWORD>").isLength({ min: 5 }), check("username").not().isEmpty().withMessage("Username is required"), check("is_agent", "Are you an agent?").isBoolean(), check("is_Landlord", "Are you a Landlord?").isBoolean(), (req, res) => { const errors = validationResult(req); if (!errors.isEmpty()) { return res.status(400).json({ errors: errors.array() }); } const { email, first_name, last_name, password, username, is_agent, is_Landlord, } = req.body; var mailOptions = { from: "<EMAIL>", to: req.body.email, subject: "HOMIFY ACCOUNT CREATED SUCCESSFULLY", text: `You have successfully created an account`, }; // The password has to be hashed const hashedPassword = bcrypt.hashSync(password, 10); // Add a new user const newUser = { email, first_name, last_name, password: <PASSWORD>, is_admin: false, username, is_agent, is_Landlord, }; users .addUser(newUser) .then((member) => { transporter.sendMail(mailOptions, function (error, info) { if (error) { console.log(`JJ`, error); } else { console.log("Email sent: " + info.response); } }); res.status(200).json({ message: `Success`, newUser }); }) .catch((error) => { res.status(500).json({ message: error.message, stack: error.stack }); }); } ); // This is the login endpoint router.post( "/login", check("username").not().isEmpty().withMessage("Username is required"), check("password", "<PASSWORD>").isLength({ min: 5 }), (req, res) => { const errors = validationResult(req); if (!errors.isEmpty()) { return res.status(400).json({ errors: errors.array() }); } let { username, password } = req.body; // We need to first fish out the user from the db users .getUserBy(username) .first() .then((member) => { // Get the user from the database and compare input password to hashed password if (member && bcrypt.compareSync(password, member.password)) { //If the user exists and password is okay, a token should be generated const token = genToken(member); res.status(200).json({ message: `Login success, ${member.username}`, token, member, }); } else { res.status(401).json({ message: `Credentials are not valid` }); } }) .catch((error) => { res.status(500).json({ message: error.message, stack: error.stack, }); }); } ); // Middleware for validating user inputs // function validateUser(req, res, next) { // const addedUser = req.body; // console.log(`BUBU`, addedUser); // if (Object.keys(addedUser).length === 0) { // res.status(400).json({ message: "Invalid inputs" }); // } else if (!addedUser.email) { // res.status(400).json({ message: "Please enter a valid email" }); // } else if (!addedUser.first_name) { // res.status(400).json({ message: "Please input your first name" }); // } else if (!addedUser.username) { // res.status(400).json({ message: "You have not chosen a username" }); // } else if (!addedUser.last_name) { // res.status(400).json({ message: "Please input your last name" }); // } else if (!addedUser.password) { // res.status(400).json({ message: "You have not chosen a password" }); // } else { // next(); // } // } // Export the router to be seen by the server module.exports = router; <file_sep>// The db-config has knowledge of our knex file. It is where our configuration is done const knex = require("knex"); const config = require("../knexfile"); const env = process.env.NODE._ENV || "development"; const configOptions = config[env]; // Export the configuration file module.exports = knex(configOptions); <file_sep>// Import the pre-baked middleware const express = require("express"); const helmet = require("helmet"); const cors = require("cors"); // Instantiate the server by invoking express const server = express(); // Bring in the houseRouter const houseRouter = require("./houses/houseRouter"); // Import the user router const userRouter = require("./users/userRouter"); // We use the middleware server.use(express.json()); server.use(cors()); server.use(helmet()); server.use(logger); server.use("/api/house", houseRouter); server.use("/api/user", userRouter); // Flesh out a dummy API server.get("/", (req, res) => { res.send("<h2>Welcome to Homify!</h2>"); }); // If the endpoint is invalid server.get("*", (req, res) => { res.send(`message: This is an invalid path`); }); // Create a custom logger middleware function logger(req, res, next) { console.log( `[${new Date().toISOString}] ${req.method} ${req.url} from ${req.get( "Origin" )}` ); next(); } // Export the server to be seen by other files module.exports = server; <file_sep>const express = require("express"); const authentication = require("../auth/middleware/authenticate-middleware"); // To check if the user is an agent or not const checkAgent = require("../auth/middleware/checkAgent"); // Import the helper functions and save it in a variable const house = require("./houseDB"); // Bring in the router const router = express.Router(); // Endpoint for getting houses router.get("/", authentication, (req, res) => { house .getHouses() .then((house) => { res.status(200).json(house); }) .catch((error) => { res.status(404).json({ stack: error.stack, message: error.message }); }); }); router.post("/", authentication, checkAgent, (req, res) => { // We are adding a new house so we need req.body const { id, house_type, house_address, house_description, house_price, for_rent, } = req.body; const newHouse = { id, house_type, house_address, house_description, house_price, for_rent, }; house .addHouse(newHouse) .then((house) => { res.status(200).json({ message: `House added successfully`, newHouse }); }) .catch((error) => { res.status(500).json({ message: error.message, stack: error.stack }); }); }); router.put("/:id", authentication, checkAgent, (req, res) => { const replacementHouse = req.body; const { id } = req.params; house .updateHouse({ id, house_type: replacementHouse.house_type, house_address: replacementHouse.house_address, house_description: replacementHouse.house_description, house_price: replacementHouse.house_price, for_rent: replacementHouse.for_rent, }) .then((house) => { if (house) { res.status(200).json({ message: `House updated successfully` }); } else { res.status(404).json({ message: `The house ${id} does not exist. Hence update could not be done`, }); } }) .catch((error) => { res.status(500).json({ message: error.message, stack: error.stack }); }); }); router.delete("/:id", authentication, checkAgent, (req, res) => { const id = req.params.id; house .removeHouse(id) .then((deletedHouse) => { if (house) { res .status(200) .json({ message: `The house with id ${id} has been deleted` }); } else { res .status(404) .json({ message: `The house with id ${id} does not exist` }); } }) .catch((error) => { res.status(500).json({ message: error.message, stack: error.stack }); }); }); module.exports = router; <file_sep>const houseDB = require("../data/dbConfig"); function getHouses() { // This is the equivalent of select * from houses return houseDB("houses"); } function addHouse({ house_type, house_address, house_description, house_price, for_rent, }) { // This is the SQL equivalent of INSERT INTO houses (house_type, house_address, house_description,house_price, for_rent) VALUES (data to be added) return houseDB("houses").insert({ house_type, house_address, house_description, house_price, for_rent, }); } function removeHouse(id) { // This is the SQL equivalent of DELETE FROM houses WHERE id =id return houseDB("houses").where({ id }).del(); } function getHouseById(id) { return houseDB("houses").where({ id }).first(); } // Helper function to edit a house function updateHouse({ id, house_type, house_address, house_description, house_price, for_rent, }) { return houseDB("houses").where({ id }).update({ house_type, house_address, house_description, house_price, for_rent, }); } module.exports = { getHouses, addHouse, removeHouse, getHouseById, updateHouse, };
708032813924f25b9df1826135d52d287fe508ff
[ "JavaScript" ]
7
JavaScript
TUNESHMAN/homify-BE
a7eb41aa98cc70efcdbe6def1cd4e3639af2ec16
6ad1e1c16be26fc4c5a01bc5082288ddc4f1baec
refs/heads/master
<repo_name>aldera/memes<file_sep>/README.md # Hall of memes<file_sep>/memes.py #!/usr/bin/env python # -*- coding: utf-8 -*- from __future__ import unicode_literals, print_function import random from flask import current_app as app from path import Path def get_memes(filter=None): """Get the memes from the filesystem.""" if filter: return [] else: d = Path(app.config['UPLOADS_DEFAULT_DEST']) res = complete_memes_tags(d.files()) random.shuffle(res) return res def complete_memes_tags(data): res = [] for item in data: filename = item.name ext = item.ext.lower() if ext in app.config['IMAGE_EXT']: res.append('<img src="/meme/{0}" alt="{0}">'.format(filename)) elif ext in app.config['VIDEO_EXT']: res.append('<video src="/meme/{0}" autoplay loop controls muted>' "C'est la PLS ! Votre navigateur ne semble pas supporter les vidéos intégrées.\n" 'Vous pouvez toujours <a href="/meme/{0}">la télécharger</a> ' 'et la visionner avec votre lecteur vidéo préféré !' '</video>'.format(filename)) elif ext in app.config['AUDIO_EXT']: res.append('<audio src="/meme/{0}" controls>' "C'est la PLS ! Votre navigateur ne semble pas supporter la balise <code>audio</code>.\n" 'Vous pouvez toujours <a href="/meme/{0}">la télécharger</a> ' 'et la visionner avec votre lecteur vidéo préféré !' '</audio>'.format(filename)) return res <file_sep>/app.py #!/usr/bin/env python # -*- coding: utf-8 -*- from __future__ import unicode_literals, print_function from flask import Flask, render_template, send_from_directory, abort from flask.ext.uploads import UploadSet, ALL, configure_uploads, patch_request_class from werkzeug import secure_filename from memes import get_memes # Flask app = Flask(__name__) app.config.from_pyfile('config.py') # Flask-Uploads memes_up = UploadSet('memes', ALL) configure_uploads(app, memes_up) patch_request_class(app, app.config['MAX_CONTENT_LENGTH']) @app.route('/') @app.route('/<filter>') def index(filter=None): """Hall of memes""" if filter not in [None, 'audio', 'video']: abort(404) return render_template('index.html', memes=get_memes(filter)) @app.route('/meme/<filename>') def get_meme(filename): return send_from_directory(app.config['UPLOADS_DEFAULT_DEST'], secure_filename(filename)) @app.route('/favicon.ico') def favicon(): return app.send_static_file('img/favicon.ico') @app.route('/robots.txt') def robots(): return app.send_static_file('robots.txt') # Error handling @app.errorhandler(404) def page_not_found(e): return render_template('error.html', error="T'es en PLS ? Meme not found."), 404 @app.errorhandler(413) def upload_too_big(e): error = ("Maximum upload size exceeded. T'as mis le serveur en PLS. " "You can't upload more than %s MB." % app.config['MAX_CONTENT_LENGTH']) return render_template('error.html', error=error), 413 # Template functions def list_navbar(): """Return the links for the navbar.""" return [(name, url) for name, url in app.config['SITE_MENU']] app.jinja_env.globals.update(list_navbar=list_navbar) # Go! if __name__ == '__main__': app.run(host='0.0.0.0', threaded=True) <file_sep>/config.py #!/usr/bin/env python # -*- coding: utf-8 -*- from __future__ import unicode_literals, print_function import os # app DEBUG = True SITE_NAME = 'Memes by Aldera #MST' SITE_MENU = [('Audio', '/audio'), ('Video', '/video')] VIDEO_EXT = ['.mp4', '.webm'] IMAGE_EXT = ['.jpg', '.jpe', '.jpeg', '.png', '.gif', '.svg', '.bmp'] AUDIO_EXT = ['.wav', '.mp3', '.aac', '.ogg', '.oga', '.flac'] # Flask-Uploads APP_ROOT = os.path.dirname(os.path.abspath(__file__)) UPLOADS_DEFAULT_DEST = os.path.join(APP_ROOT, 'uploads') MAX_CONTENT_LENGTH = 25 * 1024 * 1024 # 25 MB
8ad7ec6fdf0f949770d740561de4beee70cc9b2c
[ "Markdown", "Python" ]
4
Markdown
aldera/memes
171ace69e519fd843862d5fd1507c935fa6f7077
0e6bdbae2831949c89a5273af4581fcb71f3e46c
refs/heads/master
<repo_name>actuarialvoodoo/TeachMyselfShiny01<file_sep>/PlotDistribution.R library(shiny) library(ggplot2) library(tibble) library(colourpicker) library(stringr) source("plot_data.R") ui <- fluidPage( column(3, selectInput("dist", label = "Distribution", choices = c("Select a distribution" = "", "Normal" = "norm", "Lognormal" = "lnorm", "Expontential" = "exp")), uiOutput("params"), colourInput("color", label = "What color should it be?", value = "black", showColour = "both"), ), column(9, plotOutput("density")) ) server <- function(input, output, session) { source("reactive_logic.R", local = TRUE) } shinyApp(ui, server)<file_sep>/plot_data.R make_plot_data <- function(dist_name, arg_list) { dfun <- get(paste0("d", dist_name)) qfun <- get(paste0("q", dist_name)) percentiles <- seq_len(100)/100 - 0.005 vals <- do.call(qfun, args = c(list(p = percentiles), arg_list)) probs <- do.call(dfun, args = c(list(x = vals), arg_list)) tibble(vals = vals, probs = probs) } set_param_range <- function(dist_name) { if (dist_name == "exp") { return(list(rate = list(min = 0, max = Inf))) } if (dist_name == "lnorm") { return(list( meanlog = list(min = -Inf, max = Inf), sdlog = list(min = 0, max = Inf) )) } # norm list(mean = list(min = -Inf, max = Inf), sd = list(min = 0, max = Inf)) } extract_dist_params <- function(dist_name) { dfun <- get(paste0("d", dist_name)) params <- names(formals(dfun)) params[!(params %in% c("x", "log"))] }<file_sep>/reactive_logic.R output$params <- renderUI({ req(input$dist) use_params <- extract_dist_params(input$dist) params_range <- set_param_range(input$dist) numInputs <- list() for(i in seq_along(use_params)) { numInputs[[i]] <- numericInput( paste0("param_", use_params[i]), label = paste("Enter ", use_params[i], ": "), value = 1, min = params_range[[use_params[i]]]$min, max = params_range[[use_params[i]]]$max ) } numInputs[[length(use_params) + 1]] <- actionButton("update", "Update Plot") class(numInputs) <- c("shiny.tag.list", "list") numInputs }) output$density <- renderPlot({ req(input$dist) req(input$update) color <- input$color use_params <- extract_dist_params(input$dist) arg_list <- vector("list", length = length(use_params)) input_names <- paste0("param_", use_params) for(i in seq_along(arg_list)) { arg_list[[i]] <- input[[input_names[i]]] } names(arg_list) <- use_params dat <- make_plot_data(input$dist, arg_list) ggplot(dat, aes(x = vals, y = probs)) + geom_line(color = color) }) options(shiny.reactlog = TRUE)
876711c5adc52a1e5ec9ba5ec7178c762dc31c53
[ "R" ]
3
R
actuarialvoodoo/TeachMyselfShiny01
8534306b64f3ed4d636b9cf532bdc97834d59594
1665bd7baebd78a3bf283941c3610813c7963da4
refs/heads/master
<file_sep>// // AdminPanelViewControllerTests.swift // ShoppingLandTests // // Created by <NAME> on 09/07/2018. // Copyright © 2018 <NAME>. All rights reserved. // import XCTest @testable import ShoppingLand class AdminPanelViewControllerTests: XCTestCase { var components: AdminPanelViewController! override func setUp() { super.setUp() } func testProductNameTextFieldLimit() { let storyboard = UIStoryboard(name: "AdminPanel", bundle: Bundle(for: type(of: self))) let vc = storyboard.instantiateViewController(withIdentifier: "AdminPanelViewController") as! AdminPanelViewController vc.loadView() // Test maximum number of allowable characters let atTheLimitString = String(repeating: String("a") as String, count: 20) let atTheLimitResult = vc.textField(vc.productNameTextfield, shouldChangeCharactersIn: NSRange(location: 0, length: 0), replacementString: atTheLimitString) XCTAssertTrue(atTheLimitResult, "The text field should allow \(20) characters") // Test one more than the maximum number of allowable characters let overTheLimitString = String(repeating: String("a") as String, count: 20+1) let overTheLimitResult = vc.textField(vc.productNameTextfield, shouldChangeCharactersIn: NSRange(location: 0, length: 0), replacementString: overTheLimitString) XCTAssertFalse(overTheLimitResult, "The text field should not allow \(20+1) characters") } func testDescriptionNameTextFieldLimit() { let storyboard = UIStoryboard(name: "AdminPanel", bundle: Bundle(for: type(of: self))) let vc = storyboard.instantiateViewController(withIdentifier: "AdminPanelViewController") as! AdminPanelViewController vc.loadView() // Test maximum number of allowable characters let atTheLimitString = String(repeating: String("a") as String, count: 150) let atTheLimitResult = vc.textField(vc.productNameTextfield, shouldChangeCharactersIn: NSRange(location: 0, length: 0), replacementString: atTheLimitString) XCTAssertTrue(atTheLimitResult, "The text field should allow \(150) characters") // Test one more than the maximum number of allowable characters let overTheLimitString = String(repeating: String("a") as String, count: 150+1) let overTheLimitResult = vc.textField(vc.productNameTextfield, shouldChangeCharactersIn: NSRange(location: 0, length: 0), replacementString: overTheLimitString) XCTAssertFalse(overTheLimitResult, "The text field should not allow \(150+1) characters") } } <file_sep>// // CartViewController.swift // ComputersLand // // Created by <NAME> on 21/06/2018. // Copyright © 2018 <NAME>. All rights reserved. // import UIKit import KRProgressHUD import SCLAlertView import Kingfisher class CartViewController: UIViewController, ButtonInCellDelegate { // Interface Links @IBOutlet weak var cartTableView: UITableView! // Properties var productsInCartArray = [Product]() var productPricesArray = [Float]() var getProductsPhotosArray = [Item]() var totalSum: Float? // Life Cycle States override func viewDidAppear(_ animated: Bool) { super.viewDidAppear(animated) KRProgressHUD.show(withMessage: Constants.loadingMessage) } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) updateCartTableView() DispatchQueue.main.asyncAfter(deadline: .now()+1) { KRProgressHUD.dismiss() } } override func viewDidLoad() { super.viewDidLoad() updateCartTableView() } // Append the selectedProducts into productsInCartArray using the TabBarController func fetchSelectedProducts() { let firstTabVC = ((self.tabBarController?.viewControllers![0] as! UINavigationController).viewControllers[0] as! ProductsViewController) productsInCartArray = firstTabVC.selectedProductsArray productPricesArray = firstTabVC.priceForSelectedProductsArray getProductsPhotosArray = firstTabVC.googlePhotosArray totalSum = productPricesArray.reduce(0, +) } // Function to update the Cart table view func updateCartTableView(){ fetchSelectedProducts() cartTableView.tableFooterView = UIView(frame: CGRect(x: 0, y: 0, width: cartTableView.frame.size.width, height: 1)) // Remove last cell from TableView cartTableView.reloadData() } // Function to redirect you on Amazon if you want to buy the specific product func didTouchBuyButton(_ button: UIButton, inCell: UITableViewCell) { if let indexPath = cartTableView.indexPath(for: inCell){ let productNameWithSpaces = productsInCartArray[indexPath.row].name! var productNameWithoutSpaces = productNameWithSpaces.replacingOccurrences(of: " ", with: "+", options: .literal, range: nil) guard let amazonLink = URL(string: Constants.amazonURL + productNameWithoutSpaces) else { productNameWithoutSpaces = Constants.amazonDefaultSearch return } UIApplication.shared.open(amazonLink, options: [:], completionHandler: nil) } else{ SCLAlertView().showError(Constants.error, subTitle: Constants.urlNotFound) } } // In the future here can be a form with all user details to complete the payment. @IBAction func cartCheckoutButton(_ sender: Any) { UIApplication.shared.open(URL(string: Constants.payPalURL)!, options: [:], completionHandler: nil) } // Clear all products from the cart @IBAction func clearAllProducts(_ sender: Any) { // Reset Cart tableView productsInCartArray = [Product]() productPricesArray = [Float]() totalSum = 0 self.tabBarController?.tabBar.items?[1].badgeValue = String(0) // Remove selected products from ProductsViewController let firstTabTVC = ((self.tabBarController?.viewControllers![0] as! UINavigationController).topViewController as! ProductsViewController) firstTabTVC.selectedProductsArray = [Product]() firstTabTVC.priceForSelectedProductsArray = [Float]() firstTabTVC.counterItem = 0 firstTabTVC.numberOfProductsInCartLabel.text = String(0) UIApplication.shared.applicationIconBadgeNumber = 0 cartTableView.reloadData() } } // Protocol functions for Cart TableView extension CartViewController: UITableViewDelegate, UITableViewDataSource{ func numberOfSections(in tableView: UITableView) -> Int { return 2 } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { switch indexPath.section { case 0: // Section with Qty + ProdName + Price cartTableView.rowHeight = 100 cartTableView.estimatedRowHeight = 100 let cell = cartTableView.dequeueReusableCell(withIdentifier: Constants.identifierCartProductDetailsCell, for: indexPath) as! CartTableViewCell let productQuantity = 1 // hardcoded DispatchQueue.main.async { let productPhotoURL = self.getProductsPhotosArray.first?.link ?? Constants.defaultProductPhotoURL let resourcePhoto = ImageResource(downloadURL: URL(string: productPhotoURL)!, cacheKey: productPhotoURL) cell.cartProductImageView.kf.setImage(with: resourcePhoto) cell.cartProductQuantityLabel.text = Constants.quantityLabel + String(productQuantity) cell.cartProductNameLabel.text = self.productsInCartArray[indexPath.row].name cell.cartProductPriceLabel.text = String(format: Constants.floatTwoDecimals, self.productsInCartArray[indexPath.row].price) + Constants.currencyPound } // Customize Amazon Button cell.buyFromAmazonBtn.layer.cornerRadius = 8 cell.buyFromAmazonBtn.layer.borderWidth = 2 cell.buyFromAmazonBtn.layer.borderColor = UIColor.white.cgColor cell.delegate = self return cell case 1: // Section with Total Price + Checkout Btn cartTableView.rowHeight = 70 cartTableView.estimatedRowHeight = 70 let cell = cartTableView.dequeueReusableCell(withIdentifier: Constants.identifierCartTotalPriceCell, for: indexPath) as! CartTableViewCell if let finalPrice = totalSum, finalPrice > 0 { cell.cartTotalPriceLabel.text = String(format: Constants.floatTwoDecimals, finalPrice) + Constants.currencyPound } else{ cell.cartTotalPriceLabel.text = String(0.00) + Constants.currencyPound } // Customize Checkout Button cell.checkoutBtnOutlet.layer.cornerRadius = 8 cell.checkoutBtnOutlet.layer.borderWidth = 2 cell.checkoutBtnOutlet.layer.borderColor = UIColor.white.cgColor return cell default: return UITableViewCell() } } func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { switch section { case 0: return productsInCartArray.count case 1: return 1 default: return 0 } } // Function to delete a product from the cart func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) { if editingStyle == .delete { let firstTabVC = ((self.tabBarController?.viewControllers![0] as! UINavigationController).viewControllers[0] as! ProductsViewController) firstTabVC.selectedProductsArray.remove(at: indexPath.row) firstTabVC.priceForSelectedProductsArray.remove(at: indexPath.row) productsInCartArray.remove(at: indexPath.row) productPricesArray.remove(at: indexPath.row) cartTableView.deleteRows(at: [indexPath], with: .fade) totalSum = productPricesArray.reduce(0, +) self.tabBarController?.tabBar.items?[1].badgeValue = String(productsInCartArray.count) cartTableView.reloadData() } } } <file_sep>// // ProductsViewControllerTests.swift // ShoppingLandTests // // Created by <NAME> on 09/07/2018. // Copyright © 2018 <NAME>. All rights reserved. // import XCTest @testable import ShoppingLand class ProductsViewControllerTests: XCTestCase { // Test if fetchPhotosForProductsFromGoogle is returning an OK status. func testFetchPhotosForProductsFromGoogleGetsHTTPStatusCode200(){ let url = URL(string: "https://www.googleapis.com/customsearch/v1?q=iPhone_X&imgType=photo&imgSize=medium&searchType=image&cx=004797504301667307438:v974oybby28&key=<KEY>") let promise = expectation(description: "Status code: 200") let dataTask = URLSession.shared.dataTask(with: url!) { data, response, error in if let error = error { XCTFail("Error: \(error.localizedDescription)") return } else if let statusCode = (response as? HTTPURLResponse)?.statusCode { if statusCode == 200 { promise.fulfill() } else { // If there are more then 100 API requests then will return Status Code 403 XCTFail("Status code: \(statusCode)") } } } dataTask.resume() waitForExpectations(timeout: 5, handler: nil) } // Test if the badge will be updated with the number of items in the cart func testUpdateNoOfProductsOnIcons(){ let counterItem = 3 UIApplication.shared.applicationIconBadgeNumber = counterItem XCTAssertEqual(counterItem, 3) XCTAssertEqual(UIApplication.shared.applicationIconBadgeNumber, counterItem) } } <file_sep>// // CoreDataStack.swift // ShoppingLand // // Created by <NAME> on 24/06/2018. // Copyright © 2018 <NAME>. All rights reserved. // import Foundation import CoreData class CoreDataStack: NSObject{ // We created a Singleton for CoreDataStack static let sharedInstance = CoreDataStack() private override init() {} } <file_sep>// // Constants.swift // ShoppingLand // // Created by <NAME> on 29/06/2018. // Copyright © 2018 <NAME>. All rights reserved. // import Foundation import UIKit enum Constants { static let defaultPhotoUser = "DefaultImageUser" static let defaultPhotoProduct = "DefaultImageProduct" static let nameOfSavedUserPhoto = "saveUserImage" static let adminPanelTitle = "Admin Panel" static let silverThemeKey = "SilverThemeKey" static let silverBackgroundImage = "silverBackground.jpg" static let googleAPIUrl = "https://www.googleapis.com/customsearch/v1?q=" static let googleSearchPhotosOnly = "&imgType=photo&imgSize=medium&searchType=image" static let googleSearchEngineID = "&cx=004797504301667307438:v974oybby28" static let googleAPIKey = "&key=<KEY>" static let websiteAppExperts = "https://theappexperts.co.uk" static let productDetailsTitle = "Product Details" static let currentUser = "Current user:" static let nameRequired = "Name required" static let messageNameRequired = "Product name is required !" static let categoryRequired = "Category required" static let messageCategoryRequired = "Product Category required !" static let descriptionRequired = "Description required" static let messageDescriptionRequired = "Product Description required !" static let priceRequired = "Price required" static let messagePriceRequired = "Product Price required !" static let done = "Done" static let error = "Error" static let success = "Success" static let messageProductAdded = "Product was added with success !" static let messagePhotoSaved = "Photo was saved." static let defaultGoogleImage = "ChihuahuaExtreme" static let errorURLSesion = "Error URL Session." static let urlNotFound = "URL can't be found." static let adminPanelStoryboard = "AdminPanelStoryboard" static let segueForDetailsPage = "goToDetails" static let identifierProductCell = "ProductCell" static let errorMessage = "Error. Something is wrong !" static let adminSB = "AdminPanel" static let productNameLabel = "Name: " static let productCategoryLabel = "Category: " static let productDescriptionLabel = "Description: " static let floatTwoDecimals = "%.2f" static let productPriceLabel = "Price: " static let amazonURL = "https://www.amazon.co.uk/s/field-keywords=" static let amazonDefaultSearch = "Learn+Swift+4" static let inProgress = "In progress" static let messageInProgress = "This feature is under construction..." static let identifierCartProductDetailsCell = "cartProductDetailsCell" static let identifierCartTotalPriceCell = "cartTotalPriceCell" static let currencyPound = " £" static let quantityLabel = "Quantity: " static let resetAppKey = "RESET_APP_KEY" static let buildVersionKey = "BuildVersionKey" static let appVersionKey = "AppVersionKey" static let productEntity = "Product" static let errorDeletingProduct = "Error While Deleting Product: " static let errorFetchingData = "Error While Fetching Data From DB: " static let loadingMessage = "ShoppingLoad..." static let payPalURL = "https://www.paypal.com/uk/home" static let allowedCharacters = "0123456789." static let accessDeniedCalendar = "Access to use calendar was denied." static let reminderTitleBuyProduct = "Reminder to buy: " static let reminderMessageBuyProduct = "Don't forget to buy from ShoppingLand your favorite product: " static let errorSavingEvent = "Error: Failed while saving event." static let eventSavedSuccessfull = "The event was saved successfull. \nCheck you calendar for more details." static let requireInternetMessage = "ShoppingLand require Internet Connection" static let errorJSONDecode = "Error on JSON Decoding." static let defaultProductPhotoURL = "https://s3.amazonaws.com/MarketingFromScratch/images/are-you-missing-something-from-sales.jpg" static let pathCoreDB = "\nPath for temporary CoreData DB:\n" static let cfBundleShort = "CFBundleShortVersionString" static let versionPreference = "version_preference" static let cfBundleVersion = "CFBundleVersion" static let buildPreference = "build_preference" static let lightThemeNotificationKey = "themeSelected.light" static let darkThemeNotificationKey = "themeSelected.dark" static let accountBalance = "Account Balance: £" static let identifierThemeSelection = "ThemeSelection" } <file_sep>// // SettingsBundleHelper.swift // ShoppingLand // // Created by <NAME> on 27/06/2018. // Copyright © 2018 <NAME>. All rights reserved. // import Foundation import CoreData import UIKit class SettingsBundleHelper { struct SettingsBundleKeys { static let Reset = Constants.resetAppKey static let BuildVersionKey = Constants.buildVersionKey static let AppVersionKey = Constants.appVersionKey } // Function executed when we reset the app from Settings class func checkAndExecuteSettings() { if UserDefaults.standard.bool(forKey: SettingsBundleKeys.Reset) { UserDefaults.standard.set(false, forKey: SettingsBundleKeys.Reset) let appDomain: String? = Bundle.main.bundleIdentifier UserDefaults.standard.removePersistentDomain(forName: appDomain!) } } // Set version for App and Build class func setVersionAndBuildNumber() { let version: String = Bundle.main.object(forInfoDictionaryKey: Constants.cfBundleShort) as! String UserDefaults.standard.set(version, forKey: Constants.versionPreference) let build: String = Bundle.main.object(forInfoDictionaryKey: Constants.cfBundleVersion) as! String UserDefaults.standard.set(build, forKey: Constants.buildPreference) } } <file_sep>// // ViewController.swift // ComputersLand // // Created by <NAME> on 21/06/2018. // Copyright © 2018 <NAME>. All rights reserved. // import UIKit import Foundation import Kingfisher import CoreData import KRProgressHUD import SCLAlertView import EFInternetIndicator class ProductsViewController: UIViewController, CellDelegate, InternetStatusIndicable { // Interface Links @IBOutlet weak var productsTableView: UITableView! @IBOutlet weak var numberOfProductsInCartLabel: UILabel! @IBOutlet weak var shoppingCartButton: UIButton! @IBOutlet weak var userAvatarImageView: UIImageView! @IBOutlet weak var helloUserLabel: UILabel! // Properties var counterItem = 0 var query: String? var googlePhotosArray = [Item]() var selectedProductsArray = [Product]() var priceForSelectedProductsArray = [Float]() var internetConnectionIndicator:InternetViewIndicator? // Life Cycle States override func viewDidAppear(_ animated: Bool) { super.viewDidAppear(animated) KRProgressHUD.show(withMessage: Constants.loadingMessage) } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) updateProducts() DispatchQueue.main.asyncAfter(deadline: .now()+1) { KRProgressHUD.dismiss() } } override func viewDidLoad() { super.viewDidLoad() registerSettingsBundle() // Use Notification Pattern to detect when the background was changed NotificationCenter.default.addObserver(self, selector: #selector(ProductsViewController.defaultsChanged), name: UserDefaults.didChangeNotification, object: nil) defaultsChanged() updateProducts() self.startMonitoringInternet(backgroundColor:UIColor.red, style: .statusLine, textColor:UIColor.white, message:Constants.requireInternetMessage) } // Function to update the Products Table View func updateProducts(){ getUserPhoto() updateNoOfProductsOnIcons() accessToAdminPanel() fetchPhotosForProductsFromGoogle() numberOfProductsInCartLabel.layer.cornerRadius = numberOfProductsInCartLabel.frame.size.height / 2 do{ productsArray = try context.fetch(Product.fetchRequest()) // Remove last cell from TableView productsTableView.tableFooterView = UIView(frame: CGRect(x: 0, y: 0, width: productsTableView.frame.size.width, height: 1)) productsTableView.rowHeight = 150 productsTableView.estimatedRowHeight = 150 productsTableView.reloadData() } catch{ DispatchQueue.main.async { SCLAlertView().showError(Constants.error, subTitle: Constants.errorMessage) } } } // Download photos from Google for products avatar func fetchPhotosForProductsFromGoogle(){ for eachProduct in productsArray{ let productNameWithSpaces = eachProduct.name! query = productNameWithSpaces.replacingOccurrences(of: " ", with: "_", options: .literal, range: nil) } guard let requestURL = URL(string: URLGoogle.googleAPIUrl + "\(query ?? Constants.defaultGoogleImage)" + URLGoogle.googleSearchPhotosOnly + URLGoogle.googleSearchEngineID + URLGoogle.googleAPIKey) else { fatalError(Constants.urlNotFound) } print(requestURL) URLSession.shared.dataTask(with: requestURL) { (data, response, error) in guard error == nil else { DispatchQueue.main.async { SCLAlertView().showError(Constants.error, subTitle: Constants.errorURLSesion) } return } do { let googlePhotosList = try JSONDecoder().decode(GoogleSearchModel.self, from: data!) self.googlePhotosArray = self.googlePhotosArray + googlePhotosList.items } catch { // When the limit of 100 requests for Google Photos was reached then this Alert will pop-up every time when you click on Products Tab so leave this line commented until you subscribe at Google for more requests per day. //DispatchQueue.main.async { SCLAlertView().showError(Constants.error, subTitle: Constants.errorJSONDecode) } } DispatchQueue.main.async { self.productsTableView.reloadData() } }.resume() } // Function used to load the selected User Photo func getUserPhoto(){ // Decode the selected user photo guard let data = UserDefaults.standard.object(forKey: Constants.nameOfSavedUserPhoto) as? NSData else{ userAvatarImageView.image = UIImage(named: Constants.defaultPhotoUser) return } userAvatarImageView.image = UIImage(data: data as Data) userAvatarImageView.contentMode = .scaleToFill } // Function to send details about a product from this VC to another VC override func prepare(for segue: UIStoryboardSegue, sender: Any?) { if let selectedIndexPath = productsTableView.indexPathForSelectedRow{ let detailsVC = segue.destination as! ProductDetailsViewController detailsVC.selectedProduct = productsArray[selectedIndexPath.row] detailsVC.getGooglePhotosArray = self.googlePhotosArray } } // Func to update the number of products on the carts func updateNoOfProductsOnIcons(){ counterItem = ((self.tabBarController?.viewControllers![1] as! UINavigationController).topViewController as! CartViewController).productsInCartArray.count UIApplication.shared.applicationIconBadgeNumber = counterItem numberOfProductsInCartLabel.text = String(counterItem) } // Navigate to Cart when you click the basket icon @IBAction func shoppingCartButton(_ sender: UIButton) { tabBarController?.selectedIndex = 1 } // Func which is using GestureRecognition to access the Admin Panel when we press on User Avatar func accessToAdminPanel(){ let tapGesture = UITapGestureRecognizer(target: self, action: #selector(ProductsViewController.adminImageTapped(gesture:))) userAvatarImageView.addGestureRecognizer(tapGesture) } // Function to open the AdminPanelViewController @objc func adminImageTapped(gesture: UIGestureRecognizer) { let storyBoard : UIStoryboard = UIStoryboard(name: Constants.adminSB, bundle:nil) let adminPanelVC = storyBoard.instantiateViewController(withIdentifier: Constants.adminPanelStoryboard) as! AdminPanelViewController self.navigationController?.pushViewController(adminPanelVC, animated: true) } // Func to register the Settings Bundle when the app start func registerSettingsBundle(){ let appDefaults = [String:AnyObject]() UserDefaults.standard.register(defaults: appDefaults) } // Func which is called when we modify the default settings in the bundle @objc func defaultsChanged(){ if UserDefaults.standard.bool(forKey: Constants.silverThemeKey) { let silverBackground = UIImageView(image: UIImage(named: Constants.silverBackgroundImage)) silverBackground.frame = self.productsTableView.frame self.productsTableView.backgroundView = silverBackground self.view.backgroundColor = UIColor.lightGray } else { self.productsTableView.backgroundView = UIImageView() self.view.backgroundColor = UIColor.white } } // Function to get the CGPoint position of Add To Cart buton. func addProductToCartButton(_ sender: UIButton) { let buttonPosition : CGPoint = sender.convert(sender.bounds.origin, to: self.productsTableView) let indexPath = self.productsTableView.indexPathForRow(at: buttonPosition)! addProduct(at: indexPath) } // Function to animate the product from respective position to the Cart icon position. func addProduct(at indexPath: IndexPath) { let cell = productsTableView.cellForRow(at: indexPath) as! ProductTableViewCell let imageViewPosition : CGPoint = cell.productImageView.convert(cell.productImageView.bounds.origin, to: self.view) let imgViewTemp = UIImageView(frame: CGRect(x: imageViewPosition.x, y: imageViewPosition.y, width: cell.productImageView.frame.size.width, height: cell.productImageView.frame.size.height)) imgViewTemp.image = cell.productImageView.image animationProduct(tempView: imgViewTemp) } // Function to animate the product into the Cart func animationProduct(tempView : UIView) { self.view.addSubview(tempView) UIView.animate(withDuration: 1.0, animations: { tempView.animationZoom(scaleX: 1.5, y: 1.5) }, completion: { _ in UIView.animate(withDuration: 0.5, animations: { tempView.animationZoom(scaleX: 0.2, y: 0.2) tempView.animationRoted(angle: CGFloat(Double.pi)) tempView.frame.origin.x = self.shoppingCartButton.frame.origin.x tempView.frame.origin.y = self.shoppingCartButton.frame.origin.y }, completion: { _ in tempView.removeFromSuperview() UIView.animate(withDuration: 1.0, animations: { self.counterItem += 1 self.numberOfProductsInCartLabel.text = String(self.counterItem) self.tabBarController?.tabBar.items?[1].badgeValue = String(self.counterItem) self.shoppingCartButton.animationZoom(scaleX: 1.3, y: 1.3) }, completion: {_ in self.shoppingCartButton.animationZoom(scaleX: 1.0, y: 1.0) }) }) }) } // Func which will add the product into an array of products when the user press Add To Cart func didTapAddToCart(_ cell: ProductTableViewCell) { let indexPath = self.productsTableView.indexPath(for: cell) addProduct(at: indexPath!) selectedProductsArray.append(productsArray[(indexPath?.row)!]) // Append products for cart priceForSelectedProductsArray.append(productsArray[(indexPath?.row)!].price) // Append prices for selected products } } // ProductsTableView Protocols extension ProductsViewController: UITableViewDelegate, UITableViewDataSource{ func numberOfSections(in tableView: UITableView) -> Int { return 1 } func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return productsArray.count } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = productsTableView.dequeueReusableCell(withIdentifier: Constants.identifierProductCell, for: indexPath) as! ProductTableViewCell cell.delegate = self cell.productTitleLabel.text = productsArray[indexPath.row].name! cell.productDescriptionLabel.text = productsArray[indexPath.row].prodDescription! cell.productPriceLabel.text = String(format: Constants.floatTwoDecimals, productsArray[indexPath.row].price) + Constants.currencyPound DispatchQueue.main.async { let productPhotoURL = self.googlePhotosArray.first?.link ?? Constants.defaultProductPhotoURL let resourcePhoto = ImageResource(downloadURL: URL(string: productPhotoURL)!, cacheKey: productPhotoURL) cell.productImageView.kf.setImage(with: resourcePhoto) } // Customize AddToCart btn cell.addToCartBtn.layer.cornerRadius = 8 cell.addToCartBtn.layer.borderWidth = 2 cell.addToCartBtn.layer.borderColor = UIColor.white.cgColor return cell } func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { self.performSegue(withIdentifier: Constants.segueForDetailsPage, sender: indexPath) } // Remove all products from the cart when one ore more products are deleted from the CoreData. func removeAllProductsFromCart(){ selectedProductsArray = [Product]() priceForSelectedProductsArray = [Float]() counterItem = 0 numberOfProductsInCartLabel.text = String(0) self.tabBarController?.tabBar.items?[1].badgeValue = String(0) UIApplication.shared.applicationIconBadgeNumber = 0 } // Function to delete a Product from the table view and also from CoreData func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) { let productEntity = Constants.productEntity let product = productsArray[indexPath.row] if editingStyle == .delete { context.delete(product) do { try context.save() removeAllProductsFromCart() } catch _ as NSError { DispatchQueue.main.async { SCLAlertView().showError(Constants.error, subTitle: Constants.errorDeletingProduct) } } } // fetch new data from DB and reload products table view let fetchRequest = NSFetchRequest<NSFetchRequestResult>(entityName: productEntity) do { productsArray = try context.fetch(fetchRequest) as! [Product] } catch _ as NSError { DispatchQueue.main.async { SCLAlertView().showError(Constants.error, subTitle: Constants.errorFetchingData) } } productsTableView.reloadData() } } // Extension for zoom animation when the user add a product in the Cart extension UIView{ func animationZoom(scaleX: CGFloat, y: CGFloat) { self.transform = CGAffineTransform(scaleX: scaleX, y: y) } func animationRoted(angle : CGFloat) { self.transform = self.transform.rotated(by: angle) } } // Set URL Google extension URLGoogle{ static let googleAPIUrl = Constants.googleAPIUrl static let googleSearchPhotosOnly = Constants.googleSearchPhotosOnly static let googleSearchEngineID = Constants.googleSearchEngineID static let googleAPIKey = Constants.googleAPIKey } <file_sep>// // CartTableViewCell.swift // ComputersLand // // Created by <NAME> on 22/06/2018. // Copyright © 2018 <NAME>. All rights reserved. // import UIKit protocol ButtonInCellDelegate: class { // Function to detect when the user press the Buy button on a cell in the CartViewController func didTouchBuyButton(_ button: UIButton, inCell: UITableViewCell) } class CartTableViewCell: UITableViewCell { // Components of CartTableView Cell @IBOutlet weak var cartProductImageView: UIImageView! @IBOutlet weak var cartProductQuantityLabel: UILabel! @IBOutlet weak var cartProductNameLabel: UILabel! @IBOutlet weak var cartProductPriceLabel: UILabel! @IBOutlet weak var cartTotalPriceLabel: UILabel! @IBOutlet weak var buyFromAmazonBtn: UIButton! @IBOutlet weak var checkoutBtnOutlet: UIButton! weak var delegate: ButtonInCellDelegate? @IBAction func buySelectedProductBtn(_ sender: UIButton) { delegate?.didTouchBuyButton(sender, inCell: self) } override func awakeFromNib() { super.awakeFromNib() } override func setSelected(_ selected: Bool, animated: Bool) { super.setSelected(selected, animated: animated) } } <file_sep>// // ThemeSelectionViewController.swift // ShoppingLand // // Created by <NAME> on 06/07/2018. // Copyright © 2018 <NAME>. All rights reserved. // import UIKit class ThemeSelectionViewController: UIViewController { @IBOutlet weak var lightThemeBtnOutlet: UIButton! @IBOutlet weak var darkThemeBtnOutlet: UIButton! override func viewDidLoad() { super.viewDidLoad() // Customize Buttons lightThemeBtnOutlet.layer.cornerRadius = lightThemeBtnOutlet.frame.size.height/2 darkThemeBtnOutlet.layer.cornerRadius = darkThemeBtnOutlet.frame.size.height/2 } // Change the Profit page theme into Light @IBAction func lightThemeButton(_ sender: UIButton) { let name = Notification.Name(rawValue: lightThemeNotificationKey) NotificationCenter.default.post(name: name, object: nil) dismiss(animated: true, completion: nil) } // Change the Profit page theme into Dark @IBAction func darkThemeButton(_ sender: UIButton) { let name = Notification.Name(rawValue: darkThemeNotificationKey) NotificationCenter.default.post(name: name, object: nil) dismiss(animated: true, completion: nil) } } <file_sep>// // AdminPanelViewController.swift // ComputersLand // // Created by <NAME> on 22/06/2018. // Copyright © 2018 <NAME>. All rights reserved. // import UIKit import CoreData import KRProgressHUD import SCLAlertView var productsArray = [Product]() class AdminPanelViewController: UITableViewController { // Interface Links @IBOutlet var adminTableView: UITableView! @IBOutlet weak var adminUsernameLabel: UILabel! @IBOutlet weak var productNameTextfield: UITextField! @IBOutlet weak var productCategoryTextField: UITextField! @IBOutlet weak var productDescriptionTextView: UITextView! @IBOutlet weak var productPriceTextfield: UITextField! @IBOutlet weak var userPhotoImageView: UIImageView! @IBOutlet weak var saveBtnOutlet: UIButton! @IBOutlet weak var resetBtnOutlet: UIButton! @IBOutlet weak var checkProfitBtnOutlet: UIButton! // Properties var currentUser = UIDevice.current.name // Life Cycle States override func viewDidAppear(_ animated: Bool) { super.viewDidAppear(animated) KRProgressHUD.show(withMessage: Constants.loadingMessage) } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) resetAllFields() userPhotoImageView.contentMode = .scaleToFill DispatchQueue.main.asyncAfter(deadline: .now()+1) { KRProgressHUD.dismiss() } } override func viewDidLoad() { super.viewDidLoad() updateInterface() } // Function to update the properties of AdminVC func updateInterface(){ loadUserPhoto() initializeFields() customizeLayout() dismissKeyboard() } // Function to initalize the textfields func initializeFields(){ title = Constants.adminPanelTitle userPhotoImageView.backgroundColor = .lightGray adminUsernameLabel.text = Constants.currentUser + currentUser productNameTextfield.delegate = self productCategoryTextField.delegate = self productDescriptionTextView.delegate = self productPriceTextfield.delegate = self productPriceTextfield.keyboardType = .decimalPad } // Func to customize the layout interface func customizeLayout(){ // Customize Save Btn saveBtnOutlet.layer.cornerRadius = 10 saveBtnOutlet.layer.borderWidth = 2 saveBtnOutlet.layer.borderColor = UIColor.white.cgColor // Customize Reset Btn resetBtnOutlet.layer.cornerRadius = 10 resetBtnOutlet.layer.borderWidth = 2 resetBtnOutlet.layer.borderColor = UIColor.white.cgColor // Customize Description TextView productDescriptionTextView.layer.cornerRadius = 5.0 productDescriptionTextView.layer.borderWidth = 1 productDescriptionTextView.layer.borderColor = UIColor.black.cgColor // Customize CheckProfit Btn checkProfitBtnOutlet.layer.cornerRadius = 10 checkProfitBtnOutlet.layer.borderWidth = 2 checkProfitBtnOutlet.layer.borderColor = UIColor.white.cgColor // Remove last cell from TableView adminTableView.tableFooterView = UIView(frame: CGRect(x: 0, y: 0, width: adminTableView.frame.size.width, height: 1)) } // Close the keyboard when you press outside of textfields override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) { self.view.endEditing(true) } // Close the keyboard when you press outside of textfields func dismissKeyboard(){ let tap = UITapGestureRecognizer(target: self.view, action: #selector(UIView.endEditing(_:))) tap.cancelsTouchesInView = false self.view.addGestureRecognizer(tap) } // Save the new product in the CoreData @IBAction func saveProductButton(_ sender: UIButton) { insertProduct() } // Func to insert data from TextFields into CoreData func insertProduct(){ guard let productName = productNameTextfield.text, productName != "" else{ SCLAlertView().showError(Constants.nameRequired, subTitle: Constants.messageNameRequired) return } guard let productCategory = productCategoryTextField.text, productCategory != "" else{ SCLAlertView().showError(Constants.categoryRequired, subTitle: Constants.messageCategoryRequired) return } guard let productPrice = productPriceTextfield.text, productPrice != "" else{ SCLAlertView().showError(Constants.priceRequired, subTitle: Constants.messagePriceRequired) return } guard let productDescription = productDescriptionTextView.text, productDescription != ""else{ SCLAlertView().showError(Constants.descriptionRequired, subTitle: Constants.messageDescriptionRequired) return } let product = Product(context: context) // Start inserting in Core Data let productUUID = UUID().uuidString product.id = productUUID product.name = productName product.category = productCategory product.price = Float(productPrice)! product.prodDescription = productDescription appDelegate.saveContext() // End inserting and save the content in Core Data resetAllFields() SCLAlertView().showSuccess(Constants.done, subTitle: Constants.messageProductAdded) } // Reset All Fields @IBAction func resetFieldsButton(_ sender: UIButton) { resetAllFields() } // Reset All Fields func resetAllFields(){ productNameTextfield.text = "" productCategoryTextField.text = "" productDescriptionTextView.text = "" productPriceTextfield.text = "" } // Button to change User Photo @IBAction func changeUserPhoto(_ sender: UIButton) { let imagePicker = UIImagePickerController() imagePicker.delegate = self imagePicker.allowsEditing = false imagePicker.sourceType = .photoLibrary present(imagePicker, animated: true, completion: nil) } // Button to save User Photo @IBAction func saveUserPhoto(_ sender: UIButton) { // Encode the user photo let image = userPhotoImageView.image let imageData:NSData = UIImagePNGRepresentation(image!)! as NSData // Save the selected user photo UserDefaults.standard.set(imageData, forKey: Constants.nameOfSavedUserPhoto) loadUserPhoto() SCLAlertView().showSuccess(Constants.done, subTitle: Constants.messagePhotoSaved) } // Function used to load the selected User Photo func loadUserPhoto(){ // Decode the selected user photo guard let data = UserDefaults.standard.object(forKey: Constants.nameOfSavedUserPhoto) as? NSData else{ userPhotoImageView.image = UIImage(named: Constants.defaultPhotoUser) return } userPhotoImageView.image = UIImage(data: data as Data) userPhotoImageView.contentMode = .scaleToFill } } extension AdminPanelViewController: UITextFieldDelegate, UITextViewDelegate{ // Function to verify the TextFields input func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool { // Don't allow user to enter spaces in textfields at beginning if textField == productNameTextfield || textField == productCategoryTextField { if Int(range.location) == 0 && (string == " ") { return false } else{ return true } } //allow the user to enter only digits and punctuation for Price textfield if (textField == productPriceTextfield) { let allowedCharacters = Constants.allowedCharacters return allowedCharacters.contains(string) || range.length == 1 } return true } // Function to verify the TextViews input func textView(_ textView: UITextView, shouldChangeTextIn range: NSRange, replacementText text: String) -> Bool { if textView == productDescriptionTextView{ if Int(range.location) == 0 && (text == " ") { return false } else{ return true } } return true } } // Extension for UserPhoto ImageView to dismiss the Controller when you press Cancel or to load the selected image from library extension AdminPanelViewController: UIImagePickerControllerDelegate, UINavigationControllerDelegate{ func imagePickerControllerDidCancel(_ picker: UIImagePickerController) { dismiss(animated: true, completion: nil) } func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) { if let selectedImage = info[UIImagePickerControllerOriginalImage] as? UIImage { userPhotoImageView.contentMode = .scaleAspectFit userPhotoImageView.image = selectedImage } dismiss(animated: true, completion: nil) } } <file_sep>// // DetailsViewController.swift // ComputersLand // // Created by <NAME> on 21/06/2018. // Copyright © 2018 <NAME>. All rights reserved. // import UIKit import Social import KRProgressHUD import EventKit import SCLAlertView import Kingfisher class ProductDetailsViewController: UITableViewController { // Interface Links @IBOutlet var detailsTableView: UITableView! @IBOutlet weak var productImageView: UIImageView! @IBOutlet weak var productNameLabel: UILabel! @IBOutlet weak var productCategoryLabel: UILabel! @IBOutlet weak var productDescriptionLabel: UILabel! @IBOutlet weak var productPriceLabel: UILabel! @IBOutlet weak var shareBtnOutlet: UIButton! @IBOutlet weak var preorderBtnOutlet: UIButton! // Properties var selectedProduct: Product! var getGooglePhotosArray = [Item]() // Life Cycles States override func viewDidAppear(_ animated: Bool) { super.viewDidAppear(animated) KRProgressHUD.show(withMessage: Constants.loadingMessage) } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) DispatchQueue.main.asyncAfter(deadline: .now()+1) { KRProgressHUD.dismiss() } } override func viewDidLoad() { super.viewDidLoad() customizeLayout() } func customizeLayout(){ title = Constants.productDetailsTitle DispatchQueue.main.async { let productPhotoURL = self.getGooglePhotosArray.first?.link ?? Constants.defaultProductPhotoURL let resourcePhoto = ImageResource(downloadURL: URL(string: productPhotoURL)!, cacheKey: productPhotoURL) self.productImageView.kf.setImage(with: resourcePhoto) self.productNameLabel.text = Constants.productNameLabel + self.selectedProduct.name! self.productCategoryLabel.text = Constants.productCategoryLabel + self.selectedProduct.category! self.productDescriptionLabel.text = Constants.productDescriptionLabel + self.selectedProduct.prodDescription! self.productPriceLabel.text = Constants.productPriceLabel + String(format: Constants.floatTwoDecimals, self.selectedProduct.price) } // Customize Share Btn shareBtnOutlet.layer.cornerRadius = 8 shareBtnOutlet.layer.borderWidth = 2 shareBtnOutlet.layer.borderColor = UIColor.white.cgColor // Customize PreOrder Btn preorderBtnOutlet.layer.cornerRadius = 8 preorderBtnOutlet.layer.borderWidth = 2 preorderBtnOutlet.layer.borderColor = UIColor.white.cgColor } // Share the ProductName, ProductImage and Website on Socials @IBAction func shareProductButton(_ sender: UIButton) { guard let text = productNameLabel.text else { productNameLabel.text = "" return } guard let image = productImageView.image else { productImageView.image = UIImage() return } guard let myWebsite = NSURL(string: Constants.websiteAppExperts) else { return } let shareAll = [text, image, myWebsite] as [Any] let activityViewController = UIActivityViewController(activityItems: shareAll, applicationActivities: nil) activityViewController.popoverPresentationController?.sourceView = self.view self.present(activityViewController, animated: true, completion: nil) } // Function to create an event in the callendar to remember you to buy a product @IBAction func createRemindToBuyEvent(_ sender: Any) { let eventStore: EKEventStore = EKEventStore() eventStore.requestAccess(to: .event) { (granted, error) in if(granted) && (error == nil){ let event:EKEvent = EKEvent(eventStore: eventStore) event.title = Constants.reminderTitleBuyProduct + self.selectedProduct.name! event.startDate = Date() event.endDate = Date() event.notes = Constants.reminderMessageBuyProduct + self.selectedProduct.name! event.calendar = eventStore.defaultCalendarForNewEvents do{ try eventStore.save(event, span: .thisEvent) }catch _ as NSError{ DispatchQueue.main.async { SCLAlertView().showError(Constants.error, subTitle: Constants.errorSavingEvent) } } DispatchQueue.main.async { SCLAlertView().showSuccess(Constants.success, subTitle: Constants.eventSavedSuccessfull) } } else{ DispatchQueue.main.async { SCLAlertView().showError(Constants.error, subTitle: Constants.accessDeniedCalendar) } } } } } <file_sep>// // IntentHandler.swift // Siri ShoppingLand // // Created by <NAME> on 04/07/2018. // Copyright © 2018 <NAME>. All rights reserved. // import Intents class IntentHandler: INExtension {} // This extensions are used to speak with Siri technology extension IntentHandler: INSendPaymentIntentHandling{ // This function will send money from your ShoppingLand account using Siri technology func handle(intent: INSendPaymentIntent, completion: @escaping (INSendPaymentIntentResponse) -> Void) { guard let amount = intent.currencyAmount?.amount?.doubleValue else { completion(INSendPaymentIntentResponse(code: .failure, userActivity: nil)) return } BankAccount.withdraw(amount: amount) completion(INSendPaymentIntentResponse(code: .success, userActivity: nil)) } } extension IntentHandler: INRequestPaymentIntentHandling{ // This function will request money to your ShoppingLand account using Siri technology func handle(intent: INRequestPaymentIntent, completion: @escaping (INRequestPaymentIntentResponse) -> Void) { guard let amount = intent.currencyAmount?.amount?.doubleValue else { completion(INRequestPaymentIntentResponse(code: .failure, userActivity: nil)) return } BankAccount.deposit(amount: amount) completion(INRequestPaymentIntentResponse(code: .success, userActivity: nil)) } } <file_sep>// // BankAccount.swift // ShoppingLand // // Created by <NAME> on 04/07/2018. // Copyright © 2018 <NAME>. All rights reserved. // import Foundation class BankAccount { private init() {} static let bankAccountKey = "Bank Account" static let suiteName = "group.com.tae.Florentin.ShoppingLand" // Function to set the balance for ShoppingLand Account static func setBalance(toAmount amount: Double) { guard let defaults = UserDefaults(suiteName: suiteName) else { return } defaults.set(amount, forKey: bankAccountKey) defaults.synchronize() } // Function to check the balance of ShoppingLand Account static func checkBalance() -> Double? { guard let defaults = UserDefaults(suiteName: suiteName) else { return nil } defaults.synchronize() let balance = defaults.double(forKey: bankAccountKey) return balance } // Function to withdraw money from ShoppingLand Account @discardableResult static func withdraw(amount: Double) -> Double? { guard let defaults = UserDefaults(suiteName: suiteName) else { return nil } let balance = defaults.double(forKey: bankAccountKey) let newBalance = balance - amount setBalance(toAmount: newBalance) return newBalance } // Function to deposit money in the ShoppingLand Account @discardableResult static func deposit(amount: Double) -> Double? { guard let defaults = UserDefaults(suiteName: suiteName) else { return nil } let balance = defaults.double(forKey: bankAccountKey) let newBalance = balance + amount setBalance(toAmount: newBalance) return newBalance } } <file_sep>// // ProductTableViewCell.swift // ComputersLand // // Created by <NAME> on 21/06/2018. // Copyright © 2018 <NAME>. All rights reserved. // import UIKit protocol CellDelegate: class { // Function to detect when the user press the Add To Cart button. func didTapAddToCart(_ cell: ProductTableViewCell) } class ProductTableViewCell: UITableViewCell { // Components of ProductTableView Cell @IBOutlet weak var productImageView: UIImageView! @IBOutlet weak var productTitleLabel: UILabel! @IBOutlet weak var productDescriptionLabel: UILabel! @IBOutlet weak var productPriceLabel: UILabel! @IBOutlet weak var addToCartBtn: UIButton! weak var delegate: CellDelegate? @IBAction func addToCartPressed(_ sender: Any) { delegate?.didTapAddToCart(self) } override func awakeFromNib() { super.awakeFromNib() } override func setSelected(_ selected: Bool, animated: Bool) { super.setSelected(selected, animated: animated) } } <file_sep>// // ProfitViewController.swift // ShoppingLand // // Created by <NAME> on 04/07/2018. // Copyright © 2018 <NAME>. All rights reserved. // import UIKit import Intents let lightThemeNotificationKey = Constants.lightThemeNotificationKey let darkThemeNotificationKey = Constants.darkThemeNotificationKey class ProfitViewController: UIViewController { // Interface Links @IBOutlet weak var titlePageLabel: UILabel! @IBOutlet weak var balanceLabel: UILabel! @IBOutlet weak var checkBalanceBtnOutlet: UIButton! @IBOutlet weak var changeThemeBtnOutlet: UIButton! let lightTheme = Notification.Name(rawValue: lightThemeNotificationKey) let darkTheme = Notification.Name(rawValue: darkThemeNotificationKey) // Remove observer from memory after we use it deinit { NotificationCenter.default.removeObserver(self) } // Life Cycles override func viewDidLoad() { super.viewDidLoad() // Customize Reset Btn checkBalanceBtnOutlet.layer.cornerRadius = 8 checkBalanceBtnOutlet.layer.borderWidth = 2 checkBalanceBtnOutlet.layer.borderColor = UIColor.white.cgColor // Customize ChangeTheme Btn changeThemeBtnOutlet.layer.cornerRadius = changeThemeBtnOutlet.frame.size.height/2 INPreferences.requestSiriAuthorization { (status) in } if BankAccount.checkBalance()!.isZero { BankAccount.setBalance(toAmount: 100) } createObservers() } // Function to create the observers func createObservers(){ // Light Theme NotificationCenter.default.addObserver(self, selector: #selector(ProfitViewController.updateTitleColor(notification:)), name: lightTheme, object: nil) NotificationCenter.default.addObserver(self, selector: #selector(ProfitViewController.updateBalanceLabelColor(notification:)), name: lightTheme, object: nil) NotificationCenter.default.addObserver(self, selector: #selector(ProfitViewController.updateCheckBalanceBtnColor(notification:)), name: lightTheme, object: nil) NotificationCenter.default.addObserver(self, selector: #selector(ProfitViewController.updateBackground(notification:)), name: lightTheme, object: nil) // Dark Theme NotificationCenter.default.addObserver(self, selector: #selector(ProfitViewController.updateTitleColor(notification:)), name: darkTheme, object: nil) NotificationCenter.default.addObserver(self, selector: #selector(ProfitViewController.updateBalanceLabelColor(notification:)), name: darkTheme, object: nil) NotificationCenter.default.addObserver(self, selector: #selector(ProfitViewController.updateCheckBalanceBtnColor(notification:)), name: darkTheme, object: nil) NotificationCenter.default.addObserver(self, selector: #selector(ProfitViewController.updateBackground(notification:)), name: darkTheme, object: nil) } @objc func updateTitleColor(notification: NSNotification){ let isLightTheme = notification.name == lightTheme isLightTheme ? (titlePageLabel.textColor = .black) : (titlePageLabel.textColor = .white) } @objc func updateBalanceLabelColor(notification: NSNotification){ let isLightTheme = notification.name == lightTheme isLightTheme ? (balanceLabel.textColor = .red) : (balanceLabel.textColor = .green) } @objc func updateCheckBalanceBtnColor(notification: NSNotification){ let isLightTheme = notification.name == lightTheme isLightTheme ? (checkBalanceBtnOutlet.backgroundColor = .black) : (checkBalanceBtnOutlet.backgroundColor = .blue) isLightTheme ? (checkBalanceBtnOutlet.setTitleColor(.green, for: .normal)) : (checkBalanceBtnOutlet.setTitleColor(.white, for: .normal)) } @objc func updateBackground(notification: NSNotification){ let isLightTheme = notification.name == lightTheme let color = isLightTheme ? UIColor.white : UIColor.black view.backgroundColor = color } // Btn to check the balance of the bank account @IBAction func checkBalance(){ guard let balance = BankAccount.checkBalance() else { return } balanceLabel.text = Constants.accountBalance + String(balance) } @IBAction func changeThemeBtn(_ sender: UIButton) { let selectionVC = storyboard?.instantiateViewController(withIdentifier: Constants.identifierThemeSelection) as! ThemeSelectionViewController present(selectionVC, animated: true, completion: nil) } } <file_sep>// // GoogleSearchModel.swift // ShoppingLand // // Created by <NAME> on 25/06/2018. // Copyright © 2018 <NAME>. All rights reserved. // import Foundation // Structure for Google JSON Response for Images Search struct GoogleSearchModel: Codable { // Codable is a new technology from iOS 11 (Swift 4) let kind: String let url: URLGoogle let queries: Queries let context: Context let searchInformation: SearchInformation let spelling: Spelling let items: [Item] } struct Context: Codable { let title: String } struct Item: Codable { let kind: Kind let title, htmlTitle, link, displayLink: String let snippet, htmlSnippet: String let mime: MIME let image: Image } struct Image: Codable { let contextLink: String let height, width, byteSize: Int let thumbnailLink: String let thumbnailHeight, thumbnailWidth: Int } enum Kind: String, Codable { case customsearchResult = "customsearch#result" } enum MIME: String, Codable { case image = "image/" case imageJPEG = "image/jpeg" case imagePNG = "image/png" } struct Queries: Codable { let request, nextPage: [NextPage] } struct NextPage: Codable { let title, totalResults, searchTerms: String let count, startIndex: Int let inputEncoding, outputEncoding, safe, cx: String let searchType, imgSize, imgType: String } struct SearchInformation: Codable { let searchTime: Double let formattedSearchTime, totalResults, formattedTotalResults: String } struct Spelling: Codable { let correctedQuery, htmlCorrectedQuery: String } struct URLGoogle: Codable { let type, template: String }
d01d3efe5b26139cd7a108d332d01b1adfea0b04
[ "Swift" ]
16
Swift
florentin89/ShoppingLand
865567bf52fac8ebff9e3590fce899f3e474fb2e
967794338647291bb0c3fbadbf76bdecd137feb9
refs/heads/main
<file_sep>Flask==1.1.2 Flask-Bootstrap==3.3.7.1 Flask-CKEditor==0.4.4.1 Flask-Gravatar==0.5.0 Flask-Login==0.5.0 Flask-SQLAlchemy==2.4.4 Flask-WTF==0.14.3 Flask-Gunicorn==0.1.1 gunicorn==20.0.4 Jinja2==2.11.3 MarkupSafe==1.1.1 SQLAlchemy==1.3.23 WTForms==2.3.3 Werkzeug==1.0.1 certifi==2020.12.5 chardet==4.0.0 click==7.1.2 dominate==2.6.0 idna==2.10 itsdangerous==1.1.0 pip==21.0.1 psycopg2-binary==2.8.6 python-dotenv==0.15.0 requests==2.25.1 setuptools==54.1.1 urllib3==1.26.3 visitor==0.1.3<file_sep>import smtplib from dotenv import load_dotenv import os load_dotenv(".env.txt") my_email = os.getenv("FROM_EMAIL") password = os.getenv("<PASSWORD>") to_email = os.getenv("TO_EMAIL") def send_email(name, email, phone, message): with smtplib.SMTP("smtp.gmail.com", 587) as connection: connection.starttls() connection.login(user=my_email, password=<PASSWORD>) connection.sendmail(from_addr=my_email, to_addrs=to_email, msg=f"Subject:hello\n\n Name:{name}\nEmail:{email}\nPhone:{phone}\nMessage:{message}")
2491f991b30fde0717c0b558ab33c85e104f4497
[ "Python", "Text" ]
2
Text
andrewnashed/Blog
670c7daaa990ef19958f5c65f8a4d60379c0f797
5e56225a2bcb2e0afd2c7889e52969b1944613d1
refs/heads/master
<file_sep>#!/bin/sh ARCHIVE_PATH="$1" function is_empty { local dir="$1" shopt -s nullglob local files=( "$dir"/* "$dir"/.* ) [[ ${#files[@]} -eq 2 ]] } # setup tmp unzip folder tempzipdir=/private/tmp/unzipped if [ -d "$tempzipdir" ]; then echo "$tempzipdir is a directory, erasing and creating new directory" rm -r $tempzipdir mkdir $tempzipdir else mkdir $tempzipdir echo "$tempzipdir is now a new directory" fi # check if passed file exists, if it does unzip it. if [[ (-f "$ARCHIVE_PATH") && (${ARCHIVE_PATH: -4} == ".zip") ]]; then echo "@ARCHIVE_PATH is a .zip file" unzip "$ARCHIVE_PATH" -d $tempzipdir echo "unzip complete" else echo "File does not exist, or is not a .zip file!" rm -r $tempzipdir exit fi # check if unzip produced any files. if is_empty "$tempzipdir"; then echo "Nothing to extract from .zip" rm -r $tempzipdir exit else # convert to tar gz and drop in Downloads folder cd /Users/"$USER"/Downloads echo "moved to $PWD for conversion" if [ -f /Users/"$USER"/Downloads/temp.tar.gz ]; then rm temp.tar.gz fi FILE_NAME=$(basename "$ARCHIVE_PATH" ".zip") tar czvf "$FILE_NAME.tar.gz" $tempzipdir echo "file converted to Downloads folder." cd $OLDPWD echo "moved back to $PWD" fi # cleanup private unzipp rm -r $tempzipdir if [ -d "$tempzipdir" ]; then rm -r $tempzipdir echo "$tempzipdir removed" fi echo "Conversion complete!"
667e7cdb1cc3deae96ccf127d924c2e22052594e
[ "Shell" ]
1
Shell
paperclip360/convert_compression
934f14d2d9ddfec9ee59ad764d9645b8e742fa3d
5c2a372fe89044647e55a54fe7656c0df64c62c5
refs/heads/master
<file_sep>/** * alert tag * * Syntax: * {% ut_aside title%} * Alet content * {% endut_aside %} */ module.exports = function(ctx) { return function ut_aside_tag(args, content) { content = ctx.render.renderSync({text: content, engine: 'markdown'}); return '<aside class="ut_aside"><h3>' + args[0] + '</h3><div class="collapsed">' + content +'</div></aside>'; }; }; <file_sep># hexo-tag-usingtheirs Hexo tags for my blog ## ut_img An extension of asset_img tag which uses one parameter for title and alt. I created this because I usually use the same string for title and alt. ## ut_aside Collapsible aside. You need css and javascript snippets to support this. (TODO: paste a sample css and javascript snippets) ## ut_gfycat Gfycat video support. ## ut_comment You can use this tag for texts that you don't want to render. <file_sep>'use strict'; /** * Figure Tag * * Syntax: * {% ut_figure_open %} * {% ut_figure_close [caption] %} */ module.exports.open = ctx => { return function ut_figureOpenTag(args, content) { return '<figure>' } }; module.exports.close = ctx => { return function ut_figureCloseTag(args, content) { const caption = args.join(' '); return `<figcaption>${caption}</figcaption></figure>`; } }; <file_sep>'use strict'; const ctx = hexo; const tag = ctx.extend.tag; tag.register('ut_img', require('./ut_img')(ctx)); tag.register('ut_aside', require('./ut_aside')(ctx), true); tag.register('ut_gfycat', require('./ut_gfycat')(ctx)); const ut_figure = require('./ut_figure'); tag.register('ut_figure_open', ut_figure.open(ctx)); tag.register('ut_figure_close', ut_figure.close(ctx)); tag.register('ut_comment', require('./ut_comment')(ctx), true); <file_sep>'use strict'; /** * Gfycat Tag * * Syntax: * {% ut_gfycat [width] [height] [video name] %} */ module.exports = ctx => { return function ut_gfycatTag(args, content) { const len = args.length; let width, height, name; // Find image width and height if (args && args.length) { if (!/\D+/.test(args[0])) { width = args.shift(); if (args.length && !/\D+/.test(args[0])) { height = args.shift(); } } name = args.join(' '); } return `<div class="ut_gfycat" style="width: ${width}px; height: ${height}px;"><iframe src="https://gfycat.com/ifr/${name}"/></div>`; } };
4445ffe3fbed63b30a0f61d733570d7ee503d528
[ "JavaScript", "Markdown" ]
5
JavaScript
usingtheirs/hexo-tag-usingtheirs
45ac5ef1c9631c73dce1059a4c4f5b03f9fa9d71
3f79ec1083564bc04ee15a5d9792fd0fd8a65256
refs/heads/master
<file_sep>import java.io.FileNotFoundException; import java.io.IOException; public class OutputToExcel { public static void main(String[] args) { if (args.length != 4 && args.length != 3) { System.err.println("arguments is not 3 or 4."); System.err.println("Usage: java OutputToExcel [text file] [excel file name] [space row] [sheet name (default is sheet1)]"); System.exit(1); } String sheet_name; if (args.length == 3) { sheet_name = "sheet1"; } else { sheet_name = args[3]; } InputDatas input = null; try { input = new InputDatas(args[0]); } catch (FileNotFoundException e1) { e1.printStackTrace(); } try { input.execute(); } catch (IOException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } ExcelDoc doc1 = new ExcelDoc(args[1]); String output_msg; if (doc1.checkFileExists() == false) { // File is not exist. // Create new excel file. doc1.createWorkbook(); doc1.createSheet(sheet_name); doc1.writeGroup(input.getGroups()); output_msg = "Write the excel file successful."; } else { // File is exist. // append the excel file. doc1.setWorkbookCursor(); if (doc1.setSheetCursor(sheet_name) == true) { // New Sheet. doc1.writeGroup(input.getGroups(), 0, 0); } else { // Exist Sheet. int index = doc1.getExistsIndex(); doc1.writeGroup(input.getGroups(), index, Integer.valueOf(args[2])); } output_msg = "Append the excel file successful."; } doc1.setColumnAutoSize(0, 11); try { doc1.writeToFile(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } System.out.println(output_msg); } } <file_sep>import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.util.ArrayList; import org.apache.poi.openxml4j.exceptions.InvalidFormatException; import org.apache.poi.ss.usermodel.Sheet; import org.apache.poi.ss.usermodel.Workbook; import org.apache.poi.ss.usermodel.WorkbookFactory; import org.apache.poi.xssf.usermodel.XSSFWorkbook; public class ExcelDoc { private File _file; private Workbook _workbook; private Sheet _sheet1; private boolean exists; public ExcelDoc(String _fileName) { _file = new File(_fileName); exists = checkFileExists(); } public boolean checkFileExists() { return _file.exists(); } public void createWorkbook() { _workbook = new XSSFWorkbook(); } public void createSheet(String name) { _sheet1 = _workbook.createSheet(name); } public void writeGroup(ArrayList<Group> groups) { writeGroup(groups, 0, 0); } /* * start_row is not added the space row already. * if start_row == 5, space == 4 * * graph: X is previous data * X * X * X * X * X * space row * space row * space row * space row * data * . * . * . */ public void writeGroup(ArrayList<Group> groups, int start_row, int space) { // Create the space(null) rows for (int i=start_row; i < start_row+space; i++) { _sheet1.createRow(i); } int data_start_row = start_row + space; for (int i=0; i < groups.size(); i++) { ArrayList<String> lines = groups.get(i).getGroup(); for (int j=0; j < lines.size(); j++) { writeToCell(j+data_start_row, i, Double.valueOf(lines.get(j))); } } } private void writeToCell(int row, int col, double data) { if (_sheet1.getRow(row) == null) { _sheet1.createRow(row).createCell(col).setCellValue(data); } else { _sheet1.getRow(row).createCell(col).setCellValue(data); } } public void writeToFile() throws IOException { FileOutputStream FOS = new FileOutputStream(_file); _workbook.write(FOS); FOS.close(); } public void setColumnAutoSize(int from, int to) { for (int i=from; i < to; i++) _sheet1.autoSizeColumn(i); } /* * May have some bug issue. */ public int getExistsIndex() { int index = 0; while (_sheet1.getRow(index) != null) { index++; } return index; } /* * new sheet returns true. * exist sheet returns false. */ public boolean setSheetCursor(String name) { _sheet1 = _workbook.getSheet(name); if (_sheet1 == null) { _sheet1 = _workbook.createSheet(name); return true; } return false; } public void setWorkbookCursor() { FileInputStream FIS = null; try { FIS = new FileInputStream(_file); } catch (FileNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } try { _workbook = WorkbookFactory.create(FIS); } catch (InvalidFormatException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } <file_sep>Output-Data-to-Excel ==================== Output the data to excel file. Let the text file output to the file of excel format. <pre>Alpha Stage Author: <NAME> Date: 2014/04/25</pre> <h2>Support type</h2> <pre>Support 'double type' only right now. The 'string type' will be supported in the future.</pre> <h2>Usage</h2> javac OutputToExcel.java<br /> <b>java OutputToExcel [text file] [excel file name]</b> <h2>Features</h2> * Append mode and write mode. <h2>Known Issues</h2>
8defa72760a00dcc3796679b231df6dc7c9efd79
[ "Markdown", "Java" ]
3
Java
jackzzjack/Output-Data-to-Excel
942d14bd08ff9f28a8f95aa7d1a7d2662108069a
e29e6a402cda453022626b94d7c63e89fbe7f0bd
refs/heads/master
<file_sep>package models import ( "database/sql" "fmt" "time" ) const ( CURRENT_MIGRATION_VERSION = 1 ) type Migration struct { ID int Time time.Time } func GetLatestMigration(db *sql.DB) (*Migration, error) { migration := &Migration{} stm := fmt.Sprintf(`select id, time from migrations order by time desc`) err := db.QueryRow(stm).Scan(&migration.ID, &migration.Time) if err == sql.ErrNoRows { return migration, nil } if err != nil { return migration, err } return migration, nil } func CreateMigrationTable(db *sql.DB) error { stm := fmt.Sprintf(`create table migrations (id integer not null primary key, time datetime)`) _, err := db.Exec(stm) return err } func (m *Migration) Write(db *sql.DB) error { _, err := db.Exec( `insert into migrations(id, time) values(:id, :time)`, sql.Named("id", m.ID), sql.Named("time", m.Time), ) return err } <file_sep>godestroy ========= > WIP Install: -------- ```bash go get -u github.com/baopham/godestroy ``` Usage: ------ ```bash godestroy help ``` ```bash NAME: godestroy - Schedule to destroy file(s) USAGE: godestroy [global options] command [command options] [arguments...] VERSION: 1.0.0 COMMANDS: files godestroy files ~/Desktop/Screen*.png --in 10days what?, list godestroy what? not, deschedule godestroy not files ~/Desktop/Screen*.png now!, destroy godestroy now! help, h Shows a list of commands or help for one command GLOBAL OPTIONS: --help, -h show help --version, -v print the version ``` Requirements: ------------- * Go Author: ------- <NAME> <file_sep>package cli import ( "database/sql" "github.com/baopham/godestroy/models" "github.com/fatih/color" "github.com/urfave/cli" "os" ) func Destroy(c *cli.Context, db *sql.DB) error { schedules, err := models.GetDueSchedules(db) if err != nil { return err } for _, schedule := range schedules { err := moveToTrash(schedule) if err != nil { color.Yellow("Failed to delete %s", schedule.Path) } color.Green("%s is deleted", schedule.Path) } return nil } func moveToTrash(schedule *models.Schedule) error { path := schedule.Path valid, info, err := isValidFile(path) if !valid { color.Yellow("%s is not a valid file anymore. Cannot delete it", path) return nil } if err != nil { return err } if info.Size() != schedule.Size { color.Yellow("Size of %s has changed. Cannot delete it", path) return nil } if !info.ModTime().Equal(schedule.ModTime) { color.Yellow("%s has been modified since it was last scheduled for deletion. Cannot delete it", path) return nil } // TODO: an option to do a soft delete (e.g. move to Trash folder) // TODO: build a report of files being deleted return os.Remove(path) } <file_sep>package cli import ( "database/sql" "github.com/baopham/godestroy/models" "github.com/fatih/color" "github.com/urfave/cli" "os" ) func Deschedule(c *cli.Context, db *sql.DB) error { for _, path := range c.Args()[1:] { info, err := os.Stat(path) if os.IsNotExist(err) || info.IsDir() { color.Yellow("%s is not a valid file", path) continue } schedule, err := models.FindSchedule(path, db) if err != nil { if err == sql.ErrNoRows { // be forgiving... color.Yellow("%s has not been scheduled", path) continue } return err } err = schedule.Remove(db) if err != nil { return err } color.Green("%s has been descheduled", path) } return nil } <file_sep>package models import ( "database/sql" "fmt" "github.com/mattes/migrate" "github.com/mattes/migrate/database/sqlite3" _ "github.com/mattes/migrate/source/file" _ "github.com/mattn/go-sqlite3" "log" "os" "os/user" "path" "time" ) func PrepareDB() *sql.DB { dir := prepareDBDir() dbPath := path.Join(dir, "godestroy.db") _, err := os.Stat(dbPath) isNew := os.IsNotExist(err) db, err := sql.Open("sqlite3", dbPath) exitIfError(err) prepareMigrations(db, isNew) return db } func prepareMigrations(db *sql.DB, createTable bool) { if createTable { err := CreateMigrationTable(db) exitIfError(err) } latestMigration, err := GetLatestMigration(db) exitIfError(err) if CURRENT_MIGRATION_VERSION == latestMigration.ID { return } driver, err := sqlite3.WithInstance(db, &sqlite3.Config{}) exitIfError(err) currentDir, err := os.Getwd() exitIfError(err) m, err := migrate.NewWithDatabaseInstance( fmt.Sprintf("file:///%s/migrations", currentDir), "sqlite3", driver, ) exitIfError(err) step := CURRENT_MIGRATION_VERSION - latestMigration.ID // ensure we always migrate up if step < 0 { step = 1 } err = m.Steps(step) exitIfError(err) latestMigration.ID = CURRENT_MIGRATION_VERSION latestMigration.Time = time.Now() err = latestMigration.Write(db) exitIfError(err) } func prepareDBDir() string { currentUser, err := user.Current() exitIfError(err) dir := path.Join(currentUser.HomeDir, ".godestroy") if _, err = os.Stat(dir); os.IsNotExist(err) { err = os.MkdirAll(dir, 0755) exitIfError(err) } return dir } func exitIfError(err error) { if err != nil { log.Fatal(err) } } <file_sep>package cli import ( "database/sql" "github.com/baopham/godestroy/models" "github.com/olekukonko/tablewriter" "github.com/urfave/cli" "os" ) func List(c *cli.Context, db *sql.DB) error { fn := models.GetAllSchedules if c.Bool("now") { fn = models.GetDueSchedules } schedules, err := fn(db) if err != nil { return err } table := tablewriter.NewWriter(os.Stdout) table.SetHeader([]string{"Path", "Time To Destroy"}) for _, schedule := range schedules { table.Append([]string{schedule.Path, schedule.TimeToDestroy.String()}) } table.Render() return nil } <file_sep>package cli import ( "database/sql" "errors" "fmt" "github.com/baopham/godestroy/models" "github.com/fatih/color" "github.com/urfave/cli" "time" ) func Schedule(c *cli.Context, db *sql.DB) error { timeToDestroy, err := parseTimeOption(c) if err != nil { return err } var schedules []*models.Schedule for _, path := range c.Args() { valid, info, err := isValidFile(path) if !valid { color.Yellow("%s is not a valid file", path) continue } if err != nil { return err } if schedule, _ := models.FindSchedule(path, db); schedule != nil { color.Yellow("%s is already scheduled to be destroyed", path) continue } schedule := &models.Schedule{ Path: path, Size: info.Size(), ModTime: info.ModTime(), TimeToDestroy: *timeToDestroy, } schedules = append(schedules, schedule) } color.Green("Scheduling to destroy %d files...", len(schedules)) err = models.WriteSchedules(schedules, db) color.Green("Done") return err } func parseTimeOption(c *cli.Context) (*time.Time, error) { tParser := getTimeParser() if in := c.String("in"); in != "" { timeToDestroy, err := tParser.Parse("in "+in, time.Now()) if timeToDestroy == nil { return nil, errors.New(fmt.Sprintf("Could not parse %s", in)) } return &timeToDestroy.Time, err } if at := c.String("at"); at != "" { timeToDestroy, err := tParser.Parse("at "+at, time.Now()) if timeToDestroy == nil { return nil, errors.New(fmt.Sprintf("Could not parse %s", at)) } return &timeToDestroy.Time, err } return nil, errors.New("No time provided") } <file_sep>drop if exists schedules; <file_sep>package main import ( "database/sql" destroyCli "github.com/baopham/godestroy/cli" "github.com/baopham/godestroy/models" "github.com/fatih/color" "github.com/urfave/cli" "os" ) func main() { db := models.PrepareDB() defer db.Close() action := func(fn func(c *cli.Context, db *sql.DB) error) func(c *cli.Context) error { actor := func(c *cli.Context) error { err := fn(c, db) if err != nil { color.Red(err.Error()) } return err } return actor } app := cli.NewApp() app.Version = "1.0.0" app.Name = "godestroy" app.Usage = "Schedule to destroy file(s)" app.EnableBashCompletion = true app.Commands = []cli.Command{ { Name: "files", Usage: "godestroy files ~/Desktop/Screen*.png --in 10days", Description: "Schedule to destroy the provided files", Action: action(destroyCli.Schedule), Flags: []cli.Flag{ cli.StringFlag{ Name: "in", Usage: "Time to wait to destroy the files (e.g. --in 2seconds, 2mins, 2hours, etc.)", }, cli.StringFlag{ Name: "at", Usage: `Specific time when to destroy the files (e.g. --at "November 11, 2020")`, }, }, }, { Name: "what?", Usage: "godestroy what?", Description: "List all the scheduled files", Aliases: []string{"list"}, Action: action(destroyCli.List), Flags: []cli.Flag{ cli.BoolFlag{ Name: "now", Usage: "List files that should be destroyed now", }, }, }, { Name: "not", Usage: "godestroy not files ~/Desktop/Screen*.png", Description: "Don't destroy the provided files", Aliases: []string{"deschedule"}, Action: action(destroyCli.Deschedule), }, { Name: "now!", Usage: "godestroy now!", Description: "Destroy the files that are scheduled to be deleted now", Aliases: []string{"destroy"}, Action: action(destroyCli.Destroy), }, } app.Run(os.Args) } <file_sep>package models import ( "database/sql" "time" ) type Schedule struct { ID int Path string Size int64 ModTime time.Time TimeToDestroy time.Time } func (s *Schedule) Remove(db *sql.DB) error { _, err := db.Exec("delete from schedules where id = ?", s.ID) return err } func FindSchedule(path string, db *sql.DB) (*Schedule, error) { row := db.QueryRow("select id, path, size, mod_time, time_to_destroy from schedules where path = ?", path) schedule := &Schedule{} err := row.Scan(&schedule.ID, &schedule.Path, &schedule.Size, &schedule.ModTime, &schedule.TimeToDestroy) if err != nil { return nil, err } return schedule, nil } func WriteSchedules(schedules []*Schedule, db *sql.DB) error { tx, err := db.Begin() if err != nil { return err } for _, schedule := range schedules { _, err = tx.Exec(` insert into schedules(path, size, mod_time, time_to_destroy) values(?, ?, ?, ?) `, schedule.Path, schedule.Size, schedule.ModTime, schedule.TimeToDestroy) } return tx.Commit() } func GetDueSchedules(db *sql.DB) ([]*Schedule, error) { rows, err := db.Query( "select id, path, size, mod_time, time_to_destroy from schedules where time_to_destroy <= ?", time.Now(), ) if err != nil { return []*Schedule{}, err } return rowsToSchedules(rows) } func GetAllSchedules(db *sql.DB) ([]*Schedule, error) { rows, err := db.Query("select id, path, size, mod_time, time_to_destroy from schedules") if err != nil { return []*Schedule{}, err } return rowsToSchedules(rows) } func rowsToSchedules(rows *sql.Rows) ([]*Schedule, error) { var schedules []*Schedule for rows.Next() { schedule := &Schedule{} err := rows.Scan(&schedule.ID, &schedule.Path, &schedule.Size, &schedule.ModTime, &schedule.TimeToDestroy) if err != nil { return schedules, err } schedules = append(schedules, schedule) } return schedules, rows.Close() } <file_sep>create table schedules ( id integer primary key autoincrement, path string not null unique, size integer, mod_time datetime, time_to_destroy datetime ); create index file_path_index on schedules(path); <file_sep>package cli import ( "github.com/olebedev/when" "github.com/olebedev/when/rules/common" "github.com/olebedev/when/rules/en" "os" ) func getTimeParser() *when.Parser { w := when.New(nil) w.Add(en.All...) w.Add(common.All...) return w } func isValidFile(path string) (bool, os.FileInfo, error) { info, err := os.Stat(path) if os.IsNotExist(err) || info.IsDir() { return false, info, nil } if err != nil { return false, info, err } return true, info, nil }
78230c4999b6bfc5adf582d68c165d6b6ce22bb3
[ "Markdown", "SQL", "Go" ]
12
Go
baopham/godestroy
308814154a29f9efd5f8fa65ec77eacad9ece3f4
2681675ab937f4420713bb34e3f14014bf0fe4f3
refs/heads/master
<file_sep>'use strict'; /** * @ngdoc function * @name projetoFortesApp.controller:MainCtrl * @description * # MainCtrl * Controller of the projetoFortesApp */ angular.module('projetoFortesApp') .controller('MainCtrl', function ($scope,alert) { $scope.alert = function(){ // alert.sucess('Salvo','Salvo com sucess',"success"); alert.confirmarDoacao(); } }); <file_sep>'use strict'; /** * @ngdoc service * @name projetoFortesApp.alert * @description * # alert * Service in the projetoFortesApp. */ angular.module('projetoFortesApp') .service('alert', function(SweetAlert) { var alter = function(titulo, text, type) { var object = { title: titulo, text: text, type: type, closeOnConfirm: false }; SweetAlert.swal(object); }; var sucess = function() { return alter('Salvo', 'Dados salvo com sucesso', 'success'); }; var error = function(error) { return alter('Ocorreu um erro', error, 'erro'); }; var confirmarDoacao = function() { SweetAlert.swal({ title: 'Confirmação de doação!', text: 'Você desseja fazer a doação para esse paciente', type: "warning", showCancelButton: true, confirmButtonColor: "#DD6B55", confirmButtonText: "Sim, Desejo doar!", cancelButtonText: "Não, doar!!", closeOnConfirm: false, closeOnCancel: false }, function(isConfirm) { if (isConfirm) { SweetAlert.swal("Doação Feita", "Sua doação foi feita com sucesso", "success"); } else { SweetAlert.swal("Doação não realizada", "Sua doação não foi cancelada :(", "error"); } }); }; return { sucess: sucess, error: error, confirmarDoacao: confirmarDoacao }; });<file_sep>'use strict'; /** * @ngdoc function * @name projetoFortesApp.controller:PacienteCtrl * @description * # PacienteCtrl * Controller of the projetoFortesApp */ angular.module('projetoFortesApp') .controller('PacienteCtrl', function($scope) { $scope.paciente = { "Nome": "Paciente", "Hospital": { "Nome": "Hospital" }, "NumeroDoadores": 2, "Prazo": "2015-08-01T12:31:29.4975515-03:00", "Cidade": { "Nome": "Fortaleza", "Estado": "Ceará" }, "Email": "<EMAIL>", "Id": 5 }; });<file_sep>'use strict'; /** * @ngdoc function * @name projetoFortesApp.controller:DoadorCtrl * @description * # DoadorCtrl * Controller of the projetoFortesApp */ angular.module('projetoFortesApp') .controller('DoadorCtrl', function($scope,alert) { $scope.listaPaciente = [{ "Nome": "Francisco", "Hospital": { "Nome": "Hospital" }, "TipoSanguineo": 'AB+', "NumeroDoadores": 2, "Prazo": "2015-08-01T12:31:29.4975515-03:00", "Cidade": { "Nome": "Fortaleza", "Estado": "Ceará" }, "Email": "<EMAIL>", "Id": 5 }, { "Nome": "Daniel", "TipoSanguineo": 'A+', "Hospital": { "Nome": "Hospital" }, "NumeroDoadores": 2, "Prazo": "2015-08-01T12:31:29.4975515-03:00", "Cidade": { "Nome": "Natal", "Estado": "Ceará" }, "Email": "<EMAIL>", "Id": 5 },{ "Nome": "felipe", "TipoSanguineo": 'A+', "Hospital": { "Nome": "Hospital test" }, "NumeroDoadores": 2, "Prazo": "2015-08-01T12:31:29.4975515-03:00", "Cidade": { "Nome": "Natal", "Estado": "Ceará" }, "Email": "<EMAIL>", "Id": 5 }]; $scope.alert = function(id) { alert.confirmarDoacao(); }; });<file_sep>'use strict'; /** * @ngdoc overview * @name projetoFortesApp * @description * # projetoFortesApp * * Main module of the application. */ angular .module('projetoFortesApp', [ 'ngAnimate', 'ngCookies', 'ngResource', 'ngRoute', 'ngSanitize', 'ngTouch', 'oitozero.ngSweetAlert' ]) .config(function ($routeProvider) { $routeProvider .when('/', { templateUrl: 'views/main.html', controller: 'MainCtrl' }) .when('/about', { templateUrl: 'views/about.html', controller: 'AboutCtrl' }) .when('/doador', { templateUrl: 'views/doador.html', controller: 'DoadorCtrl' }) .when('/paciente', { templateUrl: 'views/paciente.html', controller: 'PacienteCtrl' }) .otherwise({ redirectTo: '/' }); });
c5b9476b147c824e2716298d76914a1c1ac6c1e7
[ "JavaScript" ]
5
JavaScript
Brunoalcau/trueblood-angularjs
f3fc654aa015b919c615eaf43f397d7513ad2f33
fa6910a65e2abe9841ddb72c3836abed58ddcd9a
refs/heads/master
<file_sep># %% import tensorflow as tf import matplotlib.pyplot as plt from tensorflow.python.keras.preprocessing.image_dataset import image_dataset_from_directory print(tf.__version__) # %% BATCH_SIZE = 32 IMG_SIZE = (100, 120) # %% CLASS = ('E', 'I') TARGET_PATH = lambda x: f"data/{CLASS[0]}{CLASS[1]}/{x}" # %% train_dataset = image_dataset_from_directory(TARGET_PATH("train"), shuffle=True, batch_size=BATCH_SIZE, image_size=IMG_SIZE) validation_dataset = image_dataset_from_directory(TARGET_PATH("validation"), shuffle=True, batch_size=BATCH_SIZE, image_size=IMG_SIZE) # %% class_names = train_dataset.class_names # Create test dataset from validation dataset val_batches = tf.data.experimental.cardinality(validation_dataset) test_dataset = validation_dataset.take(val_batches // 5) validation_dataset = validation_dataset.skip(val_batches // 5) # prefetch image for faster I/O during model traning AUTOTUNE = tf.data.experimental.AUTOTUNE train_dataset = train_dataset.prefetch(buffer_size=AUTOTUNE) validation_dataset = validation_dataset.prefetch(buffer_size=AUTOTUNE) test_dataset = test_dataset.prefetch(buffer_size=AUTOTUNE) # data augmentation data_augmentation = tf.keras.Sequential([ tf.keras.layers.experimental.preprocessing.RandomFlip('horizontal'), tf.keras.layers.experimental.preprocessing.RandomRotation(0.2), ]) # Rescal pixel value between [0, 255] to [-1, 1] preprocess_input = tf.keras.applications.mobilenet_v2.preprocess_input rescale = tf.keras.layers.experimental.preprocessing.Rescaling(1. / 127.5, offset=-1) # Create the base model from the pre-trained model Xception # To use other model simply change Xception to other model name # check out all available model in https://keras.io/api/applications/ IMG_SHAPE = IMG_SIZE + (3,) base_model = tf.keras.applications.Xception(input_shape=IMG_SHAPE, include_top=False, weights='imagenet') # %% # create batch data image_batch, label_batch = next(iter(train_dataset)) feature_batch = base_model(image_batch) print(feature_batch.shape) # Freeze the convolutional base base_model.trainable = False print(base_model.summary()) # Add top to the model global_average_layer = tf.keras.layers.GlobalAveragePooling2D() feature_batch_average = global_average_layer(feature_batch) print(feature_batch_average.shape) # Add prediction layer to base model prediction_layer = tf.keras.layers.Dense(1) prediction_batch = prediction_layer(feature_batch_average) print(prediction_batch.shape) inputs = tf.keras.Input(shape=(IMG_SIZE[0], IMG_SIZE[1], 3)) x = data_augmentation(inputs) x = preprocess_input(x) x = base_model(x, training=False) x = global_average_layer(x) x = tf.keras.layers.Dropout(0.2)(x) outputs = prediction_layer(x) model = tf.keras.Model(inputs, outputs) base_learning_rate = 0.0001 model.compile(optimizer=tf.keras.optimizers.Adam(lr=base_learning_rate), loss=tf.keras.losses.BinaryCrossentropy(from_logits=True), metrics=['accuracy']) # Compile and evaluate model initial_epochs = 10 loss0, accuracy0 = model.evaluate(validation_dataset) print("initial loss: {:.2f}".format(loss0)) print("initial accuracy: {:.2f}".format(accuracy0)) history = model.fit(train_dataset, epochs=initial_epochs, validation_data=validation_dataset) # Plot training result acc = history.history['accuracy'] val_acc = history.history['val_accuracy'] loss = history.history['loss'] val_loss = history.history['val_loss'] plt.figure(figsize=(8, 8)) plt.subplot(2, 1, 1) plt.plot(acc, label='Training Accuracy') plt.plot(val_acc, label='Validation Accuracy') plt.legend(loc='lower right') plt.ylabel('Accuracy') plt.ylim([min(plt.ylim()), 1]) plt.title('Training and Validation Accuracy') plt.subplot(2, 1, 2) plt.plot(loss, label='Training Loss') plt.plot(val_loss, label='Validation Loss') plt.legend(loc='upper right') plt.ylabel('Cross Entropy') plt.ylim([0, 1.0]) plt.title('Training and Validation Loss') plt.xlabel('epoch') plt.show() # FINE TUNING base_model.trainable = True print("Number of layers in the base model: ", len(base_model.layers)) # Choose how many layers to train in pretrained model fine_tune_at = 100 # Freeze all the layers before the `fine_tune_at` layer for layer in base_model.layers[:fine_tune_at]: layer.trainable = False # Compile fine tuning model model.compile(loss=tf.keras.losses.BinaryCrossentropy(from_logits=True), optimizer=tf.keras.optimizers.RMSprop(lr=base_learning_rate / 10), metrics=['accuracy']) model.summary() # 10 epochs after init 10 epochs fine_tune_epochs = 10 total_epochs = initial_epochs + fine_tune_epochs history_fine = model.fit(train_dataset, epochs=total_epochs, initial_epoch=history.epoch[-1], validation_data=validation_dataset) # Replot training result acc += history_fine.history['accuracy'] val_acc += history_fine.history['val_accuracy'] loss += history_fine.history['loss'] val_loss += history_fine.history['val_loss'] plt.figure(figsize=(8, 8)) plt.subplot(2, 1, 1) plt.plot(acc, label='Training Accuracy') plt.plot(val_acc, label='Validation Accuracy') plt.ylim([0.8, 1]) plt.plot([initial_epochs - 1, initial_epochs - 1], plt.ylim(), label='Start Fine Tuning') plt.legend(loc='lower right') plt.title('Training and Validation Accuracy') plt.subplot(2, 1, 2) plt.plot(loss, label='Training Loss') plt.plot(val_loss, label='Validation Loss') plt.ylim([0, 1.0]) plt.plot([initial_epochs - 1, initial_epochs - 1], plt.ylim(), label='Start Fine Tuning') plt.legend(loc='upper right') plt.title('Training and Validation Loss') plt.xlabel('epoch') plt.show() # Evaluation of model loss, accuracy = model.evaluate(test_dataset) print('Test accuracy :', accuracy) # Retrieve a batch of images from the test set image_batch, label_batch = test_dataset.as_numpy_iterator().next() predictions = model.predict_on_batch(image_batch).flatten() # Apply a sigmoid since our model returns logits predictions = tf.nn.sigmoid(predictions) predictions = tf.where(predictions < 0.5, 0, 1) print('Predictions:\n', predictions.numpy()) print('Labels:\n', label_batch) plt.figure(figsize=(10, 10)) for i in range(9): ax = plt.subplot(3, 3, i + 1) plt.imshow(image_batch[i].astype("uint8")) plt.title(class_names[predictions[i]]) plt.axis("off") <file_sep># 2020-ugrp-Face-analysis-MBTI This repo is currenlty under refactoring and collecting fragmented code among teammates
634847505642ae88922c20d9aef34e2c97876a79
[ "Markdown", "Python" ]
2
Python
happyhappy-jun/2020-ugrp-Face-analysis-MBTI
7141fd6d69ea74b79da4cdd35e271992aa35e1eb
12f3106165acbafced9b2952fe7e16b222ac6f34
refs/heads/master
<repo_name>michellemoon236/disney-movies-cli<file_sep>/lib/disney-movies/movie.rb class Movie attr_accessor :name, :url, :release_date, :runtime, :director, :writer, :description @@all = [] def initialize @@all << self end def self.all @@all end def self.alphabetized_list @@all.each.sort_by { |movie| movie.name} end end<file_sep>/lib/disney-movies/scraper.rb class Scraper def self.scrape_movie_list doc = Nokogiri::HTML(open("https://www.rottentomatoes.com/guides/best_disney_animated_movies/#")) doc.css("div.rank_item_row div.details").each do |i| movie = Movie.new movie.name = i.css("h3 a")[0].text.gsub(/\s[(]\d\d\d\d[)]/,"").strip movie.url = i.css("h3 a")[0].attribute("href").value end end def self.scrape_single_movie(movie) doc = Nokogiri::HTML(open("https://www.rottentomatoes.com#{movie.url}")) movie.release_date = doc.css("ul.content-meta time")[0].text.strip movie.runtime = doc.css("ul.content-meta time")[2].text.strip movie.director = doc.css("ul.content-meta li.meta-row")[2].css("div.meta-value a").collect { |i| i.text}.join(", ") movie.writer = doc.css("ul.content-meta li.meta-row")[3].css("div.meta-value a").collect { |i| i.text}.join(", ") movie.description = doc.css("div#movieSynopsis")[0].text.strip end end<file_sep>/README.md # Disney Movies CLI This CLI program lists Disney's 50 best animated movies per the website Rotten Tomatoes. It also provides more information for each movie as requested by the user including movie description, release date, runtime, director(s), and writer(s). ## Installation You can clone from the git repository by typing the following command in your terminal: git clone git@github.com:michellemoon236/disney-movies-cli.git To run, type the following: ruby bin/run ## Contributing Bug reports and pull requests are welcome on GitHub at https://github.com/'michellem'/disney-movies-cli. This project is intended to be a safe, welcoming space for collaboration, and contributors are expected to adhere to the [Contributor Covenant](http://contributor-covenant.org) code of conduct. ## License The gem is available as open source under the terms of the [MIT License](https://opensource.org/licenses/MIT). <file_sep>/lib/disney-movies.rb require 'pry' require 'open-uri' require 'nokogiri' require 'colorize' require_relative './disney-movies/cli' require_relative './disney-movies/movie' require_relative './disney-movies/scraper'<file_sep>/lib/disney-movies/cli.rb class CLI def run welcome Scraper.scrape_movie_list print_movie_list menu puts "Goodbye!" end def welcome puts "" puts "Welcome to Disney Movies!".colorize(:light_blue) puts "Here is a list of Disney's best animated movies:".colorize(:light_blue) end def menu input = "" while input != "exit" do puts "---------------------------------------------------------".colorize(:light_blue) puts "MENU".colorize(:light_blue) puts "To see details of a movie, enter the number of the movie." puts "To see the movie list again, enter 'list'." puts "To exit the program, enter 'exit'." puts "---------------------------------------------------------".colorize(:light_blue) input = gets.strip.downcase if (1..50).include?(input.to_i) single_movie = Movie.alphabetized_list[input.to_i-1] Scraper.scrape_single_movie(single_movie) if !single_movie.runtime print_single_movie(single_movie) elsif input == "list" print_movie_list elsif input != "exit" puts "I'm sorry I didn't recognize that option. Please enter a valid option from the menu." end end end def print_movie_list puts "---------------------------------------------------------".colorize(:light_blue) Movie.alphabetized_list.each.with_index(1) do |movie, index| puts "#{index}. #{movie.name}" end end def print_single_movie(movie) puts "---------------------------------------------------------".colorize(:light_blue) puts "" puts "#{movie.name.upcase}".colorize(:light_blue) puts "" puts "Description:".colorize(:light_blue) puts "#{movie.description}" puts "" puts "Release Date:".colorize(:light_blue) + " #{movie.release_date}" puts "" puts "Runtime:".colorize(:light_blue) + " #{movie.runtime}" puts "" puts "Director(s):".colorize(:light_blue) + " #{movie.director}" puts "" puts "Writer(s):".colorize(:light_blue) + " #{movie.writer}" puts "" end end <file_sep>/bin/run #!/usr/bin/env ruby require_relative '../lib/disney-movies' CLI.new.run
09a3588ec05a1e44ee495f2321f6260f1dae70fd
[ "Markdown", "Ruby" ]
6
Ruby
michellemoon236/disney-movies-cli
30c402d0366c0a350c4e93ae21ce4de45a4d271d
54f66869c94d02f66dcf2a0a08a241bace84659f
refs/heads/master
<repo_name>Daanvdhof/Chili-Framework-2016-Top-Down-game<file_sep>/Engine/Game.cpp /****************************************************************************************** * Chili DirectX Framework Version 16.07.20 * * Game.cpp * * Copyright 2016 PlanetChili.net <http://www.planetchili.net> * * * * This file is part of The Chili DirectX Framework. * * * * The Chili DirectX Framework is free software: you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation, either version 3 of the License, or * * (at your option) any later version. * * * * The Chili DirectX Framework is distributed in the hope that it will be useful, * * but WITHOUT ANY WARRANTY; without even the implied warranty of * * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * * GNU General Public License for more details. * * * * You should have received a copy of the GNU General Public License * * along with The Chili DirectX Framework. If not, see <http://www.gnu.org/licenses/>. * ******************************************************************************************/ #include "MainWindow.h" #include "Game.h" Game::Game( MainWindow& wnd ) : wnd( wnd ), gfx( wnd ) { player = new Player(100, 100, &gfx, &wnd.kbd, &wnd.mouse, this); int i; for (i = 0; i < nEnemies; i++) { enemies[i] = new Enemy(100 + 100 * i, 500, &gfx,this); enemies[i]->SetTarget(player); } gameIsOver = false; } void Game::Go() { gfx.BeginFrame(); if (gameIsOver == false) { UpdateModel(); } ComposeFrame(); gfx.EndFrame(); } void Game::InvokeGameOver() { gameIsOver = true; player = NULL; } void Game::UpdateModel() { player->Update(); if (!player) return; int i; for (i = 0; i < nEnemies; i++) { if (enemies[i]) enemies[i]->Update(); } } void Game::ComposeFrame() { if (!player) { gfx.DrawCircle(400, 300, 60, Colors::White); return; } player->Draw(); int i; for (i = 0; i < nEnemies; i++) { if(enemies[i]) enemies[i]->Draw(); } gfx.DrawLine(0, 0, 800, 600, Colors::Blue); } void Game::RemoveEnemy(Enemy* toRemove) { int i; for (i = 0; i < nEnemies; i++) { if (enemies[i] == toRemove) { enemies[i] = NULL; } } }<file_sep>/Engine/Player.h #pragma once #include "Includes.h" #include "Bullet.h" #include "Shooter.h" class Game; class Player: public Shooter { public: Player(int startX, int startY, Graphics* inGfx, Keyboard* inKbd, Mouse* inMouse, Game* pInMyGame); Player::~Player(); const void Draw(); void Update(); void KeyboardActions(); void MouseActions(); //Newly added, temp bullet system void AddHostileBullets(Bullet* newBullet); void DeleteHostileBullets(Bullet* toDelete); private: //Player data int speed; int healthPoints = 10; const int width = 20; const int height = 20; //Bullet Tracker Bullet** bulletList; //Pointers to game objects Keyboard * kbd; Graphics * gfx; Mouse * mouse; //Newly added, temp bullet system int nHostileBullets; Bullet** hostileBullets; //pointer to game Game* pMyGame; };<file_sep>/Engine/Utilities.cpp #include "Utilities.h" int Constraint(int n, int lower, int upper) { if (n > upper) return upper; if (n < lower) return lower; return n; } float Constraint(float n, float lower, float upper) { if (n > upper) return upper; if (n < lower) return lower; return n; } void Swap(int* n1, int* n2) { int buffer = *n1; *n1 = *n2; *n2 = buffer; } void Swap(float* n1, float* n2) { float buffer = *n1; *n1 = *n2; *n2 = buffer; } bool CheckCollision(int x1, int y1,int width1,int height1, int x2, int y2,int width2, int height2) { return x1 + width1 > x2 && x1 < x2 + width2 && y1 + height1 > y2 && y1 < y2 + height2; }<file_sep>/Engine/Enemy.cpp #include "Enemy.h" #include "Game.h" Enemy::~Enemy() { int i; for (i = 0; i < nBullets; i++) { DeleteBullet(bulletList[i]); } myGame->RemoveEnemy(this); } Enemy::Enemy(int startX, int startY, Graphics* inGfx, Game* inMyGame) { myGame = inMyGame; x = startX; y = startY; speed = 5; gfx = inGfx; target = NULL; width = 20; height = 20; healthPoints = 10; ShooterInits(inGfx); } const void Enemy::Draw() { gfx->DrawCircle(x, y, 10, Colors::Blue); DrawBullets(); } void Enemy::SetTarget(Player* newTarget) { target = newTarget; } void Enemy::Shoot(float angle) { Shooter::Shoot(angle); target->AddHostileBullets(GetLastBullet()); } void Enemy::Update() { if (target) { float angle; float dx = (float)(x - target->GetX()); float dy = (float)(y - target->GetY()); angle = atan(dy / dx); if (x >= target->GetX()) { angle = angle + 3.14159; } if(canShoot) Shoot(angle); } Bullet** playerBullets = target->GetBullets(); int i = 0; while (playerBullets[i] != NULL) { if(CheckCollision(x, y, width, height, playerBullets[i]->GetX(), playerBullets[i]->GetY(), 5, 5) == true) { delete playerBullets[i]; healthPoints--; if (healthPoints <= 0) delete this; } i++; } BulletActions(); } <file_sep>/Engine/Enemy.h #pragma once #include "Includes.h" #include "Player.h" #include "Shooter.h" class Game; class Enemy: public Shooter { public: Enemy(int startX, int startY, Graphics* inGfx, Game* inMyGame); const void Draw(); void SetTarget(Player* newTarget); void Update(); ~Enemy(); void Shoot(float angle); private: Bullet** bulletList; int nBullets; int width; int height; int speed; int healthPoints; Player* target; Graphics* gfx; Game* myGame; };<file_sep>/Engine/Bullet.h #pragma once #include "Includes.h" class Shooter; class Bullet { public: Bullet(float startX, float startY, float angleIn, Graphics* inGfx, Shooter* myShooterIn); ~Bullet(); const int GetX(); const int GetY(); void Update(); void Draw(); private: float x; float y; float speed; float angle; //Pointers to game objects Graphics* gfx; Shooter* myShooter; };<file_sep>/Engine/Utilities.h #pragma once float Constraint(float n, float lower, float upper); int Constraint(int n, int lower, int upper); void Swap(int* n1, int* n2); void Swap(float* n1, float* n2); bool CheckCollision(int x1, int y1, int width1, int height1, int x2, int y2, int width2, int height2);<file_sep>/Engine/Shooter.cpp #include "Shooter.h" void Shooter::Shoot(float angle) { Bullet* newBullet = new Bullet(x, y, angle, gfx, this); bulletList[nBullets] = newBullet; nBullets++; bulletList = (Bullet**)realloc(bulletList, sizeof(Bullet*)*(nBullets + 1)); bulletList[nBullets] = NULL; bulletTimer = bulletCooldown; canShoot = false; } Bullet* Shooter::GetLastBullet() { return bulletList[nBullets - 1]; } void Shooter::DeleteBullet(Bullet* toDelete) { int i; for (i = 0; i < nBullets; i++) { if (bulletList[i] == toDelete) { bulletList[i] = 0; int j; for (j = 0; j < nBullets - i - 1; j++) { bulletList[i + j] = bulletList[i + j + 1]; } nBullets--; } } } void Shooter::ShooterInits(Graphics* inGfx) { canShoot = true; bulletTimer = 0; bulletCooldown = 60; bulletList = (Bullet**)malloc(sizeof(Bullet*)); bulletList[0] = NULL; nBullets = 0; gfx = inGfx; } void Shooter::TestDraw() { gfx->DrawCircle(x, y, 40, Colors::Yellow); } const int Shooter::GetX() { return x; } const int Shooter::GetY() { return y; } void Shooter::BulletActions() { int i; for (i = 0; i < nBullets; i++) { if (&bulletList[i] != 0) bulletList[i]->Update(); } if (bulletTimer > 0) { bulletTimer--; } else { canShoot = true; } } void Shooter::DrawBullets() { int i; for (i = 0; i < nBullets; i++) { if (&bulletList[i] != 0) bulletList[i]->Draw(); } } Bullet** Shooter::GetBullets() { return bulletList; }<file_sep>/Engine/Player.cpp #include "Player.h" #include "Game.h" /* Player constructor Give in the start position for the player and the pointers to the game objects */ Player::Player(int startX, int startY, Graphics* inGfx, Keyboard* inKbd, Mouse* inMouse, Game* pInMyGame) { x = startX; y = startY; gfx = inGfx; kbd = inKbd; mouse = inMouse; speed = 5; hostileBullets = (Bullet**)malloc(sizeof(Bullet*)); hostileBullets[0] = NULL; nHostileBullets = 0; ShooterInits(inGfx); pMyGame = pInMyGame; } Player::~Player() { pMyGame->InvokeGameOver(); } void Player::AddHostileBullets(Bullet* newBullet) { hostileBullets[nHostileBullets] = newBullet; nHostileBullets++; hostileBullets = (Bullet**)realloc(hostileBullets, sizeof(Bullet*)*(nHostileBullets + 1)); hostileBullets[nHostileBullets] = NULL; } void Player::DeleteHostileBullets(Bullet* toDelete) { int i; for (i = 0; i < nHostileBullets; i++) { if (hostileBullets[i] == toDelete) { hostileBullets[i] = 0; int j; for (j = 0; j < nBullets - i - 1; j++) { hostileBullets[i + j] = hostileBullets[i + j + 1]; } hostileBullets--; } } } void Player::Update() { int i = 0; while (hostileBullets[i] != NULL) { if (CheckCollision(x, y, width, height, hostileBullets[i]->GetX(), hostileBullets[i]->GetY(), 5, 5) == true) { delete hostileBullets[i]; healthPoints--; if (healthPoints <= 0) { delete this; return; } } i++; } KeyboardActions(); MouseActions(); BulletActions(); } void Player::KeyboardActions() { if (kbd->KeyIsPressed('A')) { x -= speed; } else if (kbd->KeyIsPressed('D')) { x += speed; } if (kbd->KeyIsPressed('W')) { y -= speed; } else if (kbd->KeyIsPressed('S')) { y += speed; } } void Player::MouseActions() { if (mouse->LeftIsPressed()) { float angle = atan((float)(y - mouse->GetPosY()) / (float)(x - mouse->GetPosX())); if (x >= mouse->GetPosX()) { angle = angle + 3.14159; } if (canShoot) { Shoot(angle); } } else if (mouse->RightIsPressed()) { speed--; } speed = Constraint(speed, 0, 10); } const void Player::Draw() { gfx->DrawCircle(x, y, 10, Colors::White); DrawBullets(); } <file_sep>/Engine/Includes.h #pragma once #include "Graphics.h" #include "Keyboard.h" #include "Mouse.h" #include "DXErr.h" #include "Utilities.h" <file_sep>/Engine/Shooter.h #pragma once #include "Bullet.h" class Shooter { public: const int GetX(); const int GetY(); void BulletActions(); void DeleteBullet(Bullet* toDelete); void ShooterInits(Graphics* inGfx); void Shoot(float angle); void DrawBullets(); void TestDraw(); Bullet** GetBullets(); Bullet* GetLastBullet(); protected: int x; int y; int nBullets; int bulletCooldown; int bulletTimer; bool canShoot; //Bullet Tracker Bullet** bulletList; //Graphics pointer Graphics* gfx; };<file_sep>/Engine/Bullet.cpp #include "Bullet.h" #include "Shooter.h" Bullet::Bullet(float startX, float startY, float angleIn, Graphics* inGfx, Shooter* myShooterIn) { x = startX; y = startY; angle = angleIn; speed = 20; myShooter= myShooterIn; gfx = inGfx; } Bullet::~Bullet() { myShooter->DeleteBullet(this); } void Bullet::Update() { x += speed*cos(angle); y += speed*sin(angle); if (x < 0 || x > Graphics::ScreenWidth || y < 0 || y > Graphics::ScreenHeight) { delete this; } } void Bullet::Draw() { gfx->DrawCircle((int)x, (int)y, 2, Colors::Yellow); } const int Bullet::GetX() { return (int)x; } const int Bullet::GetY() { return (int)y; }<file_sep>/Engine/Board.h #pragma once #include "Player.h" #include "Enemy.h" class Board { public: private: int roomWidth; int roomHeight; };
e59090e200c7abd0d97c28d21ec39c7e3d2b9b8b
[ "C", "C++" ]
13
C++
Daanvdhof/Chili-Framework-2016-Top-Down-game
49f81d430bc93f8592a7882c3f28b64b057fc2e0
2d4265d2ece1f68c2b865c3b79794ff82fa1f012
refs/heads/master
<file_sep>var myLayer = { alert: function(content,time,callback){ if($(".c-alert-box").is(":visible")){ $(".c-alert-box").remove(); } if(time == undefined || time == "" || time == null){ time = 2000; } var ahtml = '<div class="c-alert-box">'+content+'</div><div class="c-al-screen"></div>'; $("body").append(ahtml); if(typeof jQuery == 'undefined'){ var aleL = ($(window).width() - $(".c-alert-box").width()) / 2; }else{ var aleL = ($(window).width() - $(".c-alert-box").width() - 20) / 2; } $(".c-alert-box").css('left', aleL + "px"); setTimeout(function(){ $(".c-alert-box,.c-al-screen").remove(); if (callback){callback();} },time); }, load: function(content){ if($(".c-load-box").is(":visible")){ $(".c-load-box").remove(); } if(content == undefined || content == "" || content == null){ content = "\u52a0\u8f7d\u4e2d..." } var lhtml = '<div class="c-load-box"><span class="loadgif"></span><p>'+content+'</p></div><div class="c-al-screen"></div>'; $("body").append(lhtml); var totW = $(window).width(); if(typeof jQuery == 'undefined'){ var aleL = (totW - $(".c-load-box").width()) / 2; }else{ var aleL = (totW - $(".c-load-box").width() - 60) / 2; } $(".c-load-box").css('left', aleL + "px"); }, clear: function(){ $(".c-load-box,.c-al-screen").remove(); }, confirm: function(options){ var dft= { title:'', con:'', cancel: null, cancelValue:'\u53d6\u6d88', ok: null, okValue:'\u786e\u5b9a' } var ops = $.extend(dft,options); var chtml = '<div class="c-conf-screen"></div>'; chtml += '<div class="c-conf-box">'; if(ops.title != ""){ chtml += '<div class="conftitle">'+ops.title+'</div>'; } chtml += '<div class="confcontent">'+ops.con+'</div>'; if(ops.cancel != null){ chtml += '<div class="c-confbtn"><a href="javascript:;" class="c-twobtn" id="popcanclebtn">'+ops.cancelValue+'</a><a href="javascript:;" class="c-twobtn" id="popsurebtn">'+ops.okValue+'</a></div>'; }else{ chtml += '<div class="c-confbtn"><a href="javascript:;" class="c-onebtn" id="popsurebtn">'+ops.okValue+'</a></div>'; } chtml += '</div></div>'; $("body").append(chtml); if(typeof jQuery == 'undefined'){ var aleT = ($(".c-conf-box").height() + 80) / 2; }else{ var aleT = ($(".c-conf-box").height() + 15) / 2; } $(".c-conf-box").css('margin-top', -aleT); $("#popcanclebtn").click(function(){ if (ops.cancel){ops.cancel();} $(".c-conf-box,.c-conf-screen").remove(); }); $("#popsurebtn").click(function(){ if (ops.ok){ops.ok();} $(".c-conf-box,.c-conf-screen").remove(); }); } } function throttle(fn, delay){ var timer = null; return function(){ var context = this, args = arguments; clearTimeout(timer); timer = setTimeout(function(){ fn.apply(context, args); }, delay); }; }; //分享 function sharepop(content) { var shtml = '<div class="share-pop-hold">'+ '<div class="share-pop c-hide">'+ '<h2>分享赚</h2>'+ '<h4>当小伙伴复制您分享的靓粉吧口令进入靓粉吧,购买了该商品,您可获得靓粉吧钱包收益奖励!如小伙伴是靓粉吧的新用户,TA将成为您的邀请用户,小伙伴今后每一笔订单,您都将获得钱包收益奖励。</h4>'+ '<div class="share-con">'+ '<p>'+content+'</p>'+ '<p>下载靓粉吧:https://w.wwww.com</p>'+ '</div>'+ '<div class="share-road mt10">'+ '<a href="javascript:;"><p><i class="share-tb-wx"></i></p><p>微信</p></a>'+ '<a href="javascript:;"><p><i class="share-tb-pyq"></i></p><p>朋友圈</p></a>'+ '</div>'+ '<div class="mt10">'+ '<a href="javascript:;" class="c-btn c-btn-gray btn-radius-lit share-close">取消</a></a>'+ '</div>'+ '</div>'+ '<div class="share-pop-mb"></div>'+ '</div>'; $('body').append(shtml); setTimeout(function(){ $('.share-pop').removeClass('c-hide'); },10); $('.share-pop-mb,.share-close').click(function(){ $('.share-pop-hold').remove(); }); } //分享 $('.mui-content').on('click','.sn-share',function(){ var con = '【同仁堂珍珠粉0.3g*60瓶天然同仁堂食用珍珠粉内服外用可制面膜粉),原价15.9元,抢券省10元】复制这条信息¥Uqxc0Qm4hwI¥后打开靓粉吧'; sharepop(con); }); //普通分享 function shareplain() { var shtml = '<div class="share-pop-hold">'+ '<div class="share-pop c-hide">'+ '<h2>分享</h2>'+ '<div class="share-road mt10">'+ '<a href="javascript:;"><p><i class="share-tb-wx"></i></p><p>微信</p></a>'+ '<a href="javascript:;"><p><i class="share-tb-pyq"></i></p><p>朋友圈</p></a>'+ '</div>'+ '<div class="mt20">'+ '<a href="javascript:;" class="c-btn c-btn-gray btn-radius-lit share-close">取消</a></a>'+ '</div>'+ '</div>'+ '<div class="share-pop-mb"></div>'+ '</div>'; $('body').append(shtml); setTimeout(function(){ $('.share-pop').removeClass('c-hide'); },10); $('.share-pop-mb,.share-close').click(function(){ $('.share-pop-hold').remove(); }); } //普通分享 $('.mui-content').on('click','.pt-share',function(){ shareplain(); }); //收藏 $('.mui-content').on('click','a[data-opera=collect],div[data-opera=collect]',function(){ var checked = $(this).hasClass('checked'); if(checked){ myLayer.alert('已取消收藏'); $(this).removeClass('checked'); }else{ myLayer.alert('收藏成功'); $(this).addClass('checked'); } }); $(function(){ $('.full-page').height($(window).height()); $(window).resize(function(){ $('.full-page').height($(window).height()); }); }); document.body.addEventListener('touchstart', function () {});
0b62b75c50bdeaefa7dfc9f55a01eb62b3bd2894
[ "JavaScript" ]
1
JavaScript
kua654/game
3353e63a32f68f27ef3f911ea7447bcb5d94bc67
63efb43259665a6b3202baa330a3bdd3012bc6c5
refs/heads/master
<file_sep>require 'protobuf/message/message' require 'protobuf/message/enum' require 'protobuf/message/service' require 'protobuf/message/extend' module Proto class User < ::Protobuf::Message optional :string, :guid, 1 end class UserList < ::Protobuf::Message repeated :User, :users, 1 end class UserFindRequest < ::Protobuf::Message repeated :string, :guids, 1 end end<file_sep>require 'protobuf/rpc/client' require './proto/user.pb' require './user_service' require './logger' Protobuf::Logger.configure :file => STDOUT, :level => ::Logger::INFO # $logger.debug '[c] setting up client' request = Proto::UserFindRequest.new.tap do |req| req.guids << 'USER_GUID_1' req.guids << 'USER_GUID_2' req.guids << 'USER_GUID_3' req.guids << 'USER_GUID_4' req.guids << 'USER_GUID_5' end # begin # $logger.debug '[c] before client.find [new]' Proto::UserService.client.find request do |client| # $logger.debug '[c] inside client callback' client.on_failure do |error| $logger.debug '[c] inside client on_error' $logger.debug error.code.name $logger.debug error.message end client.on_success do |user| $logger.debug '[c] inside client on_success' $logger.debug '[c] user.guid = %s' % user.guid end end # $logger.debug '[c] after client.find [new]' # rescue # $logger.error '[c] ERROR in calling client find request' # $logger.error $!.message # $logger.error $!.backtrace.join("\n") # end <file_sep>require 'eventmachine' require './logger' require 'protobuf/rpc/server' require 'protobuf/common/logger' require './user_service' $logger.debug '[S] Setting up server 1' Protobuf::Logger.configure :file => STDOUT, :level => ::Logger::INFO trap("INT") { $logger.info '[S] Server 1 shutting down'; EM.stop_event_loop } EM.run do $logger.debug '[S] starting' EM.start_server '127.0.0.1', 9939, Protobuf::Rpc::Server $logger.debug '[S] after start' end <file_sep>source :rubygems gem 'eventmachine' gem 'ruby_protobuf', path: '/code/src/ruby_protobuf' gem 'ruby-debug19', '0.11.6' <file_sep>require './proto/user.pb' require './proto/user_service' require './client_service' require './logger' module Proto class UserService located_at '127.0.0.1:9939' # request -> Proto::UserFindRequest # response -> Proto::UserList def find self.async_responder = true $logger.debug '[S] in Proto::UserService#find' $logger.debug '[S] calling client service find' Proto::ClientService.client(async: true).find(request) do |c| c.on_success do |s| $logger.debug '[S] in client.on_success for ClientService#find = %s' % s.inspect response.users = request.guids.map do |guid| Proto::User.new.tap do |user| user.guid = guid end end send_response end c.on_failure do |e| $logger.debug '[S] in client.on_failure for ClientService#find = %s' % e.inspect rpc_failed e end end end # request -> Proto::User # response -> Proto::User def create $logger.debug '[S] in Proto::UserService#create' # rpc_failed 'not implemented' end end end <file_sep>require 'eventmachine' require './logger' require 'protobuf/rpc/server' require './client_service' Protobuf::Logger.configure :file => STDOUT, :level => ::Logger::INFO $logger.debug '[S] Setting up server 2' trap("INT") { $logger.info '[S] Server 2 shutting down'; EM.stop_event_loop } EM.run do EM.start_server '127.0.0.1', 9940, Protobuf::Rpc::Server end <file_sep>require 'protobuf/rpc/service' require File.expand_path 'user.pb', File.dirname(__FILE__) ## !! DO NOT EDIT THIS FILE !! ## ## To implement this service as defined by the protobuf, simply ## reopen Proto::ClientService and implement each service method: ## ## module Proto ## class ClientService ## ## # request -> Proto::UserFindRequest ## # response -> Proto::UserList ## def find ## # TODO: implement find ## end ## ## # request -> Proto::User ## # response -> Proto::User ## def create ## # TODO: implement create ## end ## ## end ## end ## module Proto class ClientService < Protobuf::Rpc::Service rpc :find, UserFindRequest, UserList rpc :create, User, User end end <file_sep>require './proto/client_service' require './logger' module Proto class ClientService located_at '127.0.0.1:9940' # request -> Proto::UserFindRequest # response -> Proto::UserList def find rpc_failed 'this came from the client service#find' end end end
2a1f070651851bfe7b79567412c3c57854ef1b78
[ "Ruby" ]
8
Ruby
localshred/pb_playground
5f88fac716c18b71d870d49f0ced34d3d6fb44e6
b5a902296ce8d0182e4793cd0e7e1d12e9326c44
refs/heads/master
<repo_name>akshaymodi9/todo<file_sep>/client/src/app/components/view-task/view-task.component.ts import { Component, OnInit } from '@angular/core'; import { TaskService } from '../../services/task.service'; import { taskInfo } from '../../models/taskInfo'; import { Observable } from 'rxjs/Observable'; @Component({ selector: 'app-view-task', templateUrl: './view-task.component.html', styleUrls: ['./view-task.component.css'] }) export class ViewTaskComponent { private task:taskInfo[] constructor(private taskSvc:TaskService) { this.taskSvc.getTask() .subscribe( data=>{ console.log(data) this.task=data }, err=>{ console.log(err) } ) } } <file_sep>/client/src/app/modules/task-route/task-route.module.ts import { NgModule } from '@angular/core'; import { Routes, RouterModule } from '@angular/router' import { HomeComponent } from '../../components/home/home.component'; import { ViewTaskComponent } from '../../components/view-task/view-task.component'; import { AddTaskComponent } from '../../components/add-task/add-task.component'; import { NotFoundComponent } from '../../components/not-found/not-found.component'; import { EditTaskComponent } from '../../components/edit-task/edit-task.component'; import { TaskResolverService } from '../../services/task-resolver.service'; import { DeleteTaskComponent } from '../../components/delete-task/delete-task.component'; import { SearchTaskComponent } from '../../components/search-task/search-task.component'; const routes:Routes=[ { path:'', component:HomeComponent },{ path:'view', component:ViewTaskComponent },{ path:'add', component:AddTaskComponent },{ path:'edit/:id', component:EditTaskComponent, resolve:{ task:TaskResolverService } }, { path:'delete/:id', component:DeleteTaskComponent },{ path:'search', component:SearchTaskComponent }, { path:'**', component:NotFoundComponent } ] @NgModule({ imports: [ RouterModule.forRoot(routes) ], exports:[ RouterModule ], declarations: [] }) export class TaskRouteModule { } <file_sep>/client/src/app/components/add-task/add-task.component.ts import { Component, OnInit } from '@angular/core'; import { FormGroup, FormBuilder, Validators } from "@angular/forms"; import { TaskService } from '../../services/task.service'; @Component({ selector: 'app-add-task', templateUrl: './add-task.component.html', styleUrls: ['./add-task.component.css'] }) export class AddTaskComponent implements OnInit { private form: FormGroup constructor(private fb:FormBuilder,private taskSvc:TaskService) { this.form=this.fb.group({ taskname:['',Validators.required], description:['',Validators.required], status:['',Validators.required] }) } public add() { if(this.form.valid) { var obj={ taskname:this.form.value.taskname, description:this.form.value.description, status:this.form.value.status } this.taskSvc.addTask(obj) .subscribe( data=>{alert("Added")}, err=>{alert("Error")} ) } else { alert("Form Invalid") } } ngOnInit() { } } <file_sep>/client/src/app/app.module.ts import { BrowserModule } from '@angular/platform-browser'; import { NgModule } from '@angular/core'; import { AppComponent } from './app.component'; import { HomeComponent } from './components/home/home.component'; import { ViewTaskComponent } from './components/view-task/view-task.component'; import { TaskService } from './services/task.service'; import { TaskRouteModule } from './modules/task-route/task-route.module'; import { HttpModule } from "@angular/http"; import { AddTaskComponent } from './components/add-task/add-task.component'; import { FormsModule, ReactiveFormsModule } from '@angular/forms'; import { NotFoundComponent } from './components/not-found/not-found.component'; import { EditTaskComponent } from './components/edit-task/edit-task.component'; import { TaskResolverService } from './services/task-resolver.service'; import { DeleteTaskComponent } from './components/delete-task/delete-task.component'; import { SearchTaskComponent } from './components/search-task/search-task.component'; @NgModule({ declarations: [ AppComponent, HomeComponent, ViewTaskComponent, AddTaskComponent, NotFoundComponent, EditTaskComponent, DeleteTaskComponent, SearchTaskComponent, ], imports: [ BrowserModule, TaskRouteModule, HttpModule, ReactiveFormsModule, FormsModule ], providers: [TaskService,TaskResolverService], bootstrap: [AppComponent] }) export class AppModule { } <file_sep>/client/src/app/services/task.service.ts import { Injectable } from '@angular/core'; import { taskInfo } from '../models/taskInfo'; import { Http } from "@angular/http"; import { Observable } from 'rxjs/Observable'; import 'rxjs/add/operator/map'; import 'rxjs/add/operator/catch'; @Injectable() export class TaskService { readonly API_URL: string = "http://localhost:3500/api/" constructor(private http:Http) { } public getTask():Observable<taskInfo[]>{ return this.http.get(this.API_URL) .map(res => res.json()) .catch(err => Observable.throw(err)) } public addTask(data):Observable<any>{ return this.http.post(this.API_URL,data) .map(res=>res.json()) .catch(err=>Observable.throw(err)) } public getTaskById(id:string):Observable<taskInfo>{ var url=`${this.API_URL}/${id}`; return this.http.get(url) .map(res=> res.json()) .catch(err=> Observable.throw(err)) } public updateTask(id:string,data):Observable<taskInfo>{ var url=`${this.API_URL}/${id}`; return this.http.put(url,data) .map(res=>res.json()) .catch(err=>Observable.throw(err)) } public deleteTask(id:string):Observable<any>{ var url=`${this.API_URL}/${id}`; return this.http.delete(url) .map(res=>res.json()) .catch(err=>Observable.throw(err)) } public findTaskByName(name:string):Observable<any>{ var path="task" var url=`${this.API_URL}/${path}/${name}` return this.http.get(url) .map(res=>res.json()) .catch(err=>Observable.throw(err)) } } <file_sep>/client/src/app/components/search-task/search-task.component.ts import { Component, OnInit } from '@angular/core'; import { TaskService } from '../../services/task.service'; import { taskInfo } from '../../models/taskInfo'; @Component({ selector: 'app-search-task', templateUrl: './search-task.component.html', styleUrls: ['./search-task.component.css'] }) export class SearchTaskComponent implements OnInit { private task:taskInfo constructor(private taskSvc:TaskService) { } ngOnInit() { } public search(data){ console.log(data) this.taskSvc.findTaskByName(data) .subscribe( data=>{this.task=data console.log(this.task) }, err=>{ console.log(err)} ) } } <file_sep>/models/todotask.js // importing dependicies var mongoose=require('mongoose') var schema=mongoose.Schema //create schema of mongodb collection var todoSchema=new schema({ taskname:{type:String,required:true}, description:{type:String,required:true}, status:{type:String,required:true} }) //exporting the schema module.exports=mongoose.model('todotask',todoSchema)<file_sep>/app.js //importing dependicies var express =require('express') var bodyParser=require('body-parser') var mongoose=require('mongoose') var todoroute=require('./routes/todo') //Instantiation var app=express() //configuration app.set('port',3500) app.set('mongodbUrl','mongodb://localhost:27017/todo') //cors app.use(function(req,res,next){ res.header("Access-control-Allow-Origin","*"); res.header("Access-control-Allow-Headers","Origin,X-Requested-with,Content-Type,Accept") res.header("Access-control-Allow-Methods","PUT,POST,GET,DELETE") next() }) //middleware app.use(bodyParser.json()) app.use(bodyParser.urlencoded({extended:true})) //setting routes app.use('/api',todoroute) //mongodb connection mongoose.connect(app.get('mongodbUrl'), { useMongoClient: true }) //connection success mongoose.connection.on("connected", () => { console.log("Connected to MongoDB: "+app.get('mongodbUrl')) }) //connection failure mongoose.connection.on("error", (err) => { if (err) console.log("Connection failed " + err) }) //start server app.listen(app.get('port'),function(req,res,next){ console.log("Rest api server running on port: "+app.get('port')) }) <file_sep>/client/src/app/models/taskInfo.ts export class taskInfo{ taskname:string description:string status:string }<file_sep>/client/src/app/components/edit-task/edit-task.component.ts import { Component, OnInit } from '@angular/core'; import { FormBuilder, FormGroup, Validators } from '@angular/forms'; import { TaskService } from '../../services/task.service'; import { ActivatedRoute,Router } from '@angular/router'; @Component({ selector: 'app-edit-task', templateUrl: './edit-task.component.html', styleUrls: ['./edit-task.component.css'] }) export class EditTaskComponent implements OnInit { private form:FormGroup constructor(private fb:FormBuilder,private taskSvc:TaskService,private route: ActivatedRoute,private router:Router) { } ngOnInit() { let taskId = this.route.snapshot.params.id let task=this.route.snapshot.data['task'] this.form=this.fb.group({ id:[taskId], taskname:[task.taskname], description:[task.description], status:[task.status,Validators.required] }) } public update(){ if(this.form.valid){ let taskId=this.form.value.id let s={ status:this.form.value.status } this.taskSvc.updateTask(taskId,s) .subscribe( data=>{ this.router.navigate(['/view']) }, err=>{alert('Error')} ) } else{ alert('Invalid') } } } <file_sep>/routes/todo.js var todo=require('../models/todotask') var express=require('express') var router = express.Router(); //REST api //get all task router.get('/',function(req,res,next){ todo.find((err,doc)=>{ if(err) res.json(err) else res.json(doc) }) }) //find task by id router.get('/:id',function(req,res,next){ todo.findById(req.params.id,(err,doc)=>{ if(err) res.json(err) else res.json(doc) }) }) //find task by name router.get('/task/:name',function(req,res,next){ todo.find({'taskname':req.params.name},(err,doc)=>{ if(err) res.json(err) else res.json(doc) }) }) //add new task router.post('/',function(req,res,next){ var newtask=new todo(req.body) newtask.save((err,doc)=>{ if(err) res.json(err) else res.json({msg:'task added',data:doc}) }) }) //update task router.put('/:id',function(req,res,next){ todo.findByIdAndUpdate({_id:req.params.id},{status:req.body.status},(err,doc)=>{ if(err) res.json(err) else res.json({msg:"Status Updated",data:doc}) }) }) //delete task router.delete('/:id',function(req,res,next){ todo.findByIdAndRemove(req.params.id,(err,doc)=>{ if(err) res.json() else res.json({msg:"Task deleted"}) }) }) module.exports=router<file_sep>/client/src/app/components/delete-task/delete-task.component.ts import { Component, OnInit } from '@angular/core'; import { TaskService } from '../../services/task.service'; import { ActivatedRoute, Router } from '@angular/router'; @Component({ selector: 'app-delete-task', templateUrl: './delete-task.component.html', styleUrls: ['./delete-task.component.css'] }) export class DeleteTaskComponent implements OnInit { constructor(private taskSvc:TaskService,private route: ActivatedRoute,private router:Router) { } ngOnInit() { let taskId = this.route.snapshot.params.id this.taskSvc.deleteTask(taskId) .subscribe( data=>{ this.router.navigate(['/view'])}, err=>{alert('Error')} ) } }
f4bd74de6a72b6b4d4d58745a05c987f9666b11c
[ "JavaScript", "TypeScript" ]
12
TypeScript
akshaymodi9/todo
7a169671103bb2dc6fff255c187f770888db25b6
ac3243de8501ad65a03f59b64e9d52b02bf62c7b
refs/heads/master
<file_sep>module.exports={ name:'ping', description:'ping to check if onine', execute(message,args){ message.channel.send("oh hello there ಠᴗಠ"); } }<file_sep># mute-em A simple discord bot to mute everyone in a voice channel # Usage type -help to get list of commands type -mute to mute all in the voice channel you are connected to type -unmute to unmute all in the voice channel you are connected to # Adding this bot to your server This bot is currently hosted on my laptop so I can not guarantee how much time during the day it will be online . If you want to host it please feel to contact me :3 for now go to this [Link](https://discord.com/oauth2/authorize?client_id=770371428640882718&scope=bot&permissions=315632640) Thanks <file_sep>module.exports={ name:'unmute', description:'unmutes everyone in a voice chat', execute(message,args){ if (message.member.voice.channel) { //const connection = await message.member.voice.channel.join(); let channel = message.member.voice.channel; for (let member of channel.members) { member[1].voice.setMute('false'); } } else { message.reply('You need to join a voice channel first!'); } } }
dc1d513d9450c0992a27e86c9d9472fcceeb8b63
[ "JavaScript", "Markdown" ]
3
JavaScript
shoccho/mute-em
af1e7122dc7a792e238c799a52b482628bf18bdb
5e73d9ae9dfe736e9d8fb6f55526a736468688da
refs/heads/master
<file_sep>'use strict'; var path = require('path'); var glob = require('glob'); var cwd = process.cwd(); module.exports = { bootstrap : function(folder, regex, cb) { try { var files = glob.sync(path.join(cwd, folder) + regex); files.forEach(function(file) { cb(file); }); } catch (err) { throw err; } } }; <file_sep>'use strict'; var util = require('util'); var Rabbus = require('rabbus'); var Rabbit = require('wascally'); var ProductResponder = function(options) { Rabbus.Responder.call(this, Rabbit, { exchange : 'req-res.product-exchange', queue : 'req-res.product-queue', messageType : options.messageType, limit : 1 }); }; util.inherits(ProductResponder, Rabbus.Responder); module.exports = function(options) { return new ProductResponder(options); }; <file_sep>'use strict'; var Product = require('../../models').Product; var Responder = require('../../responders/product-responder'); var responder = Responder({ 'messageType' : 'req-res.api.v1.products.create' }); responder.handle(function(message, respond) { Product.create(message) .then(function(product) { respond(product) }) .catch(function(error) { respond(error); }); }); module.exports = responder; <file_sep>#Sample service ## Notes - Create `platform` database on local Postgres server - Run `sequelize db:migrate` ``` npm install node index.js ```<file_sep>'use strict'; module.exports = { up : function(migration, DataTypes, done) { migration .createTable( 'Products', { id : { type : DataTypes.UUID, primaryKey : true, defaultValue : DataTypes.UUIDV4 }, name : { type : DataTypes.STRING, allowNull : false }, description : { type : DataTypes.TEXT, allowNull : true }, createdAt : DataTypes.DATE, updatedAt : DataTypes.DATE, deletedAt : DataTypes.DATE }) .complete(done); }, down : function(migration, DataTypes, done) { migration .dropTable( 'Products' ) .complete( done ); } }; <file_sep>'use strict'; if (!module.parent) { throw new Error('Do not run this file directly, instead run index.js'); } var util = require('util'); var Rabbit = require('wascally'); var env = process.env.NODE_ENV || 'development'; var config = require('config/rabbitmq.json')[env]; var mixins = require('utils/mixins'); var start = function(done) { Rabbit.configure({ connection : config }) .then(function() { mixins.bootstrap('controllers', '/**/*-handler.js', function(file) { require(file); }); if (typeof done === 'function') { done(); } }) .then(null, function(err) { setImmediate(function() { throw err; }); }); }; function exit() { console.log(''); console.log('shutting down ...'); Rabbit.closeAll().then(function() { process.exit(); }); }; process.once('SIGINT', function() { exit(); }); process.on('unhandledException', function(err) { console.log(err); }); module.exports.start = start; <file_sep>'use strict'; require('./require-hack'); require('server').start();
1524d75d6e0009e0e72501e3374d5f37615f56ed
[ "JavaScript", "Markdown" ]
7
JavaScript
rtorino/product-service
73e92f7874200493c0fb603e18b1369b8c384329
26235a3018ac332806fedd9782e9f6b7eae4454c
refs/heads/master
<repo_name>JustinFerriere/rock-paper-scissors<file_sep>/script.js // Global variables const rockBtn = document.getElementById('rock'); const paperBtn = document.getElementById('paper'); const scissorsBtn = document.getElementById('scissors'); const printResult = document.getElementById('print-result'); const score = document.getElementById('score'); const round = document.getElementById('game-round'); let gameRound = 0; let playerScore = 0; let computerScore = 0; // Have the computer make a random choice. function computerChoice() { let randomizer = Math.floor(Math.random() * 3); switch (randomizer) { case 0: return 'rock'; break; case 1: return 'paper'; break; case 2: return 'scissors'; } } // Determine a winner of each round! function playRound(player, computer) { if (player === 'rock' && computer === 'scissors') { printResult.innerHTML = `You win! Because ${player} beats ${computer}!`; playerScore++; } else if (player === 'rock' && computer === 'paper') { printResult.innerHTML = `You lose! Because ${computer} beats ${player}!`; computerScore++; } else if (player === 'paper' && computer === 'rock') { printResult.innerHTML = `You win! Because ${player} beats ${computer}!`; playerScore++; } else if (player === 'paper' && computer === 'scissors') { printResult.innerHTML = `You lose! Because ${computer} beats ${player}!`; computerScore++; } else if (player === 'scissors' && computer === 'paper') { printResult.innerHTML = `You win! Because ${player} beats ${computer}!`; playerScore++; } else if (player === 'scissors' && computer === 'rock') { printResult.innerHTML = `You lose! Because ${computer} beats ${player}!`; computerScore++; } else if (player === computer) { printResult.innerHTML = `It's a draw!`; computerScore++; playerScore++; } } function resetGame() { gameRound = 0; playerScore = 0; computerScore = 0; score.innerHTML = `PLAYER: ${playerScore} COMPUTER: ${computerScore}`; round.innerHTML = `ROUND: ${gameRound}`; printResult.innerHTML = ''; } function playGame() { gameRound++; player = this.id; computer = computerChoice(); playRound(player, computer); round.innerHTML = `ROUND: ${gameRound}`; score.innerHTML = `PLAYER: ${playerScore} | COMPUTER: ${computerScore}`; if (gameRound === 3) { if (playerScore < computerScore) { alert('Congratulations! You won the game!'); resetGame(); } else if (playerScore > computerScore) { alert('You lost the game. Better luck next time!') resetGame(); } } } rockBtn.addEventListener('click', playGame); paperBtn.addEventListener('click', playGame); scissorsBtn.addEventListener('click', playGame);<file_sep>/README.md # rock-paper-scissors A typical game of rock paper scissors Beginner's project. Goal is to create a five round game of rock paper scissors, played against the computer. Requirements: Player can choose to play either rock, paper or scissors using buttons in the browser. The game ends after five rounds.
26a4f900ecdaec39c4d63e65e443fddb5ef28a17
[ "JavaScript", "Markdown" ]
2
JavaScript
JustinFerriere/rock-paper-scissors
a8577cbbcc88431a04777223d0dfc85a1815a87d
e1c409f27a675ba4bd06d8b2f4015ab409c23342
refs/heads/master
<repo_name>ashishmahi/zipkin-javascript-opentracing<file_sep>/customTracer/Span.js /* eslint-disable class-methods-use-this */ const { uniqueId, getTimeStamp } = require("./helpers"); class Span { // name = ""; // id = ""; // traceId = ""; // duration = ""; // startTime = ""; // callBackOnFinish; // tags = {}; // logs = []; constructor(name, callBackOnFinish) { this.name = name; const uID = uniqueId(); this.id = uID; this.traceId = uID; this.startTime = Date.now(); this.logs = []; this.tags = []; this.callBackOnFinish = callBackOnFinish; } setTag(key, value) { this.tags.push({ key, value }); } log(logString) { this.logs.push({ timestamp: getTimeStamp(), value: logString, endpoint: { serviceName: "Custom Tracer" } }); } // get id() { // return { // traceId: this.traceId, // spanId: this.id // }; // } finish() { this.duration = Date.now() - this.startTime; this.callBackOnFinish({ name: this.name, duration: this.duration, timestamp: Number(`${this.startTime}000`), traceId: this.traceId, id: this.id, annotations: this.logs, binaryAnnotations: this.tags }); } } module.exports = Span; <file_sep>/customTracer/Tracer.js /* eslint-disable class-methods-use-this */ const Span = require("./Span"); const { sendTrace } = require("./helpers"); class Tracer { // queue = []; // sendSpanCallback = this.sendSpan.bind(this); // finishCallback = this.finishSpan.bind(this); // config = {}; constructor(config) { this.config = config; this.queue = []; this.sendSpanCallback = this.sendSpan.bind(this); this.finishCallback = this.finishSpan.bind(this); setInterval(this.sendSpanCallback, config.interval); } startSpan(name) { return new Span(name, this.finishCallback); } finishSpan(spanContext) { this.queue.push(spanContext); } async sendSpan() { if (this.queue.length) { const tempQueue = this.queue; this.queue = []; try { await sendTrace(this.config, tempQueue); } catch (error) { console.log("error while sending trace to collector", error); // this.queue.push(...tempQueue); } } } } module.exports = Tracer; <file_sep>/customTracer/helpers.js const axios = require("axios"); const uniqueId = () => { const digits = "0123456789abcdef"; let n = ""; for (let i = 0; i < 16; i++) { const rand = Math.floor(Math.random() * 16); n += digits[rand]; } return n; }; const getTimeStamp = () => { return Number(`${Date.now()}000`); }; const createTracingRequestBody = (config, queue) => { return queue.map(span => { return { ...span }; }); }; const sendTrace = (config, queue) => { const requestBody = createTracingRequestBody(config, queue); return axios.post(config.url, requestBody); }; module.exports = { sendTrace, getTimeStamp, uniqueId };
44cd2d505e489d89382c32f9aad436aec7a39f24
[ "JavaScript" ]
3
JavaScript
ashishmahi/zipkin-javascript-opentracing
4ad3871e65cad4f33695171f331dda1d32c34153
41d60b3ca801a91205dcf786cb63909c562acd47
refs/heads/master
<file_sep>package com.tan.forfun.observer; import com.tan.forfun.observer.display.CurrentConditionsDisplay; import com.tan.forfun.observer.subject.WeatherDate; class WeatherStation { public static void main(String[] args) { WeatherDate weatherData = new WeatherDate(); CurrentConditionsDisplay currentDisplay = new CurrentConditionsDisplay(weatherData); // StatisticsDisplay statisticsDisplay = new StatisticsDisplay(weatherData); // ForecastDisplay forecastDisplay = new ForecastDisplay(weatherData); weatherData.setMeasurements("80", "65", "30.4"); weatherData.setMeasurements("82", "70", "29.2"); weatherData.setMeasurements("78", "90", "29.2"); } } <file_sep>package com.tan.forfun; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.boot.builder.SpringApplicationBuilder; import org.springframework.boot.web.servlet.support.SpringBootServletInitializer; @SpringBootApplication public class ForFunApplication extends SpringBootServletInitializer { public static void main(String[] args) { SpringApplication.run(ForFunApplication.class, args); } @Override protected SpringApplicationBuilder configure(SpringApplicationBuilder application) { return application.sources(ForFunApplication.class); } } <file_sep>package com.tan.forfun.controller; import java.util.HashMap; import java.util.List; import java.util.Map; import com.tan.forfun.model.TestVo; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.*; import com.tan.forfun.model.ResponseObject; import com.tan.forfun.model.TreeModel; import com.tan.forfun.service.TestService; @RestController @RequestMapping("/api") public class TestController { @Autowired TestService testService; @RequestMapping(value = "test",method = RequestMethod.GET) public ResponseObject<Object> index (@RequestBody TestVo params ) { ResponseObject<Object> responseObject = new ResponseObject<>(); responseObject.setMessage(params.getMessage()); responseObject.setData(params.getIds()); return responseObject; } @RequestMapping("treesGet") public ResponseObject<Object> getTree () { ResponseObject<Object> responseObject = new ResponseObject<>(); List<TreeModel> tree = testService.getTree(); responseObject.setData(tree); responseObject.setMessage("6666"); return responseObject; } } <file_sep>spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver spring.datasource.url=jdbc:mysql://localhost:3306/ictors?useSSl=true&serverTimezone=UTC spring.datasource.username=root spring.datasource.password=tan server.port=8088 mybatis.type-aliases-package=com.tan.forfun.model mybatis.mapperLocations=classpath:/mapper/*.xml spring.jpa.show-sql = true<file_sep>package com.tan.forfun.service.impl; import java.util.ArrayList; import java.util.List; import java.util.concurrent.ConcurrentHashMap; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.util.CollectionUtils; import org.springframework.util.StringUtils; import com.tan.forfun.dao.TestDao; import com.tan.forfun.model.TreeModel; import com.tan.forfun.service.TestService; import com.tan.forfun.utils.TreeUtils; import javax.annotation.Resource; @Service public class TestServiceImpl implements TestService { @Resource TestDao testDao; @Override public List<TreeModel> getTree() { List<TreeModel> list = testDao.getTree(); List<TreeModel> bulidTree = TreeUtils.bulid(list); for (TreeModel treeModel : bulidTree) { calcTree(treeModel); } return bulidTree; } private void calcTree(TreeModel treeModel) { if(null != treeModel) { List<TreeModel> children = treeModel.getChildren(); if(!CollectionUtils.isEmpty(children)) { for (TreeModel treeModel2 : children) { calcTree(treeModel2); } int intValue = children.stream().map(map -> { if(!StringUtils.isEmpty(map.getMoney())) { return Integer.parseInt(map.getMoney()); } return 0; }).reduce(0,(a,b) -> a+b).intValue(); treeModel.setMoney(String.valueOf(intValue)); } } } } <file_sep>package com.tan.forfun.observer.subject; import com.tan.forfun.observer.Observer; import java.util.ArrayList; import java.util.List; public class WeatherDate implements Subject { private List<Observer> observers; private String temp ; private String humidity ; private String pressure ; public WeatherDate() { this.observers = new ArrayList<Observer>(); } @Override public void registerObserver(Observer o) { observers.add(o); } @Override public void removeObserver(Observer o) { int i = observers.indexOf(o); if(i>0) observers.remove(i); } @Override public void notifyObservers() { for (int i = 0; i < observers.size(); i++) { Observer observer = observers.get(i); observer.update(temp, humidity, pressure); } } public void measurementsChanged() { notifyObservers(); } public void setMeasurements(String temp, String humidity, String pressure) { this.temp = temp; this.humidity = humidity; this.pressure = pressure; measurementsChanged(); } } <file_sep>package com.tan.forfun.model; import java.util.List; public class TreeModel { private String id; private String parentId; private String itemName; private String money; private List<TreeModel> children; public TreeModel() { super(); // TODO Auto-generated constructor stub } public TreeModel(String id, String parentId, String itemName, String money) { super(); this.id = id; this.parentId = parentId; this.itemName = itemName; this.money = money; } public String getId() { return id; } public void setId(String id) { this.id = id; } public String getParentId() { return parentId; } public void setParentId(String parentId) { this.parentId = parentId; } public String getItemName() { return itemName; } public void setItemName(String itemName) { this.itemName = itemName; } public String getMoney() { return money; } public void setMoney(String money) { this.money = money; } public List<TreeModel> getChildren() { return children; } public void setChildren(List<TreeModel> children) { this.children = children; } } <file_sep>package com.tan.forfun.jdkobserver; import java.util.Observable; public class JWeatherData extends Observable { private String temp ; private String humidity ; private String pressure ; public String getTemp() { return temp; } public void setTemp(String temp) { this.temp = temp; } public String getHumidity() { return humidity; } public void setHumidity(String humidity) { this.humidity = humidity; } public String getPressure() { return pressure; } public void setPressure(String pressure) { this.pressure = pressure; } public void measurementsChanged() { setChanged(); notifyObservers(); } public void setMeasurements(String temp, String humidity, String pressure) { this.temp = temp; this.humidity = humidity; this.pressure = pressure; measurementsChanged(); } }
6e49d95216e82bd9fd071baa78fc7627622572c3
[ "Java", "INI" ]
8
Java
tanqichao666/forFun
acd4786c713c558f619db5b672f41da530cb7945
585241e23e151524eb37e800160069219a10dba9
refs/heads/master
<repo_name>alliethu/aetcoff.github.io<file_sep>/allieetcoff.js $('.inline-popups').magnificPopup({ delegate: 'a', removalDelay: 300, callbacks: { beforeOpen: function() { this.st.mainClass = this.st.el.attr('data-effect'); } }, mainClass: 'mfp-fade', midClick: true }); // FOR RETINA DISPLAY // $('.image-link').magnificPopup({ // type: 'image', // retina: { // ratio: 2 // can also be function that should retun this number // } // }); // FOR GALLERY ITEM $('.gallery').magnificPopup({ delegate: 'image', gallery:{ enabled:true}, callbacks: { buildControls: function() { // re-appends controls inside the main container this.contentContainer.append(this.arrowLeft.add(this.arrowRight)); } } }); $('.project-image').slick({ dots: true, infinite: true, speed: 300, slidesToShow: 1, slidesToScroll: 1, responsive: [ { breakpoint: 1024, settings: { slidesToShow: 1, slidesToScroll: 1, dots: true } }, { breakpoint: 600, settings: { slidesToShow: 1, slidesToScroll: 1, dots: true } }, { breakpoint: 480, settings: { slidesToShow: 1, slidesToScroll: 1, dots: true } } // You can unslick at a given breakpoint now by adding: // settings: "unslick" // instead of a settings object ] });
f041582a07c86475cfe254bf46d31992d85f91fb
[ "JavaScript" ]
1
JavaScript
alliethu/aetcoff.github.io
c6fbe300c35c94fe5db38e27fc1cc34031303d1a
61416d37a9df2e893240e059dbf6bfdfa4919ec7
refs/heads/master
<file_sep><?php // appphp if (file_exists(__DIR__ . '/Libraries/autoload.php')) { require __DIR__ . '/Libraries/autoload.php'; } else { echo 'Missing autoload.php, update by the composer.' . PHP_EOL; exit(2); } define('ROOT_DIR', __DIR__); if (is_dir(__DIR__ . '/.git')) { exec('git --git-dir=' . __DIR__ . '/.git rev-parse --verify HEAD 2> /dev/null', $output); $version = substr($output[0], 0, 10); } else { $version = '1.0'; } $application = new \Symfony\Component\Console\Application('MOC AWS Manager', $version); $application->add(new \AWSManager\Command\SnapshotCommand()); //$application->add(new Rosemary\Command\AboutCommand()); $application->run();<file_sep>MOC AWS Manager =============== Various manager commands for MOC AWS Setup. Examples -------- php app.php snapshot pruneSnapshots php app.php snapshot takeSnapshot <VolumeID> php app.php snapshot listSnapshots <VolumneId> php app.php snapshot listVolumes php app.php snapshot backupAllVolumes <file_sep><?php namespace AWSManager\Command; use Aws\Ec2\Ec2Client; use Aws\Ec2\Exception\Ec2Exception; use Symfony\Component\Console\Command\Command; use Aws\S3\S3Client; use Symfony\Component\Console\Exception\InvalidArgumentException; use Symfony\Component\Console\Input\InputArgument; class SnapshotCommand extends Command { /** * @var \Symfony\Component\Console\Input\InputInterface */ protected $input; /** * @var \Symfony\Component\Console\Output\OutputInterface */ protected $output; /** * @var Ec2Client */ protected $ec2Client; public function __construct($name = NULL) { parent::__construct($name); $options = [ 'region' => 'eu-west-1', 'version' => '2015-10-01', ]; $this->ec2Client = new Ec2Client($options); } /** * */ protected function configure() { parent::configure(); $this->setName('snapshot') ->setDescription('AWS Snapshow handling') ->addArgument('action', \Symfony\Component\Console\Input\InputArgument::REQUIRED, 'Set the action to do') ->addArgument('volume', InputArgument::OPTIONAL, 'Volume to snapshot'); } /** * @param \Symfony\Component\Console\Input\InputInterface $input * @param \Symfony\Component\Console\Output\OutputInterface $output * @throws \Exception * @return null */ protected function execute(\Symfony\Component\Console\Input\InputInterface $input, \Symfony\Component\Console\Output\OutputInterface $output) { $this->input = $input; $this->output = $output; $actions = array('listVolumes', 'takeSnapshot', 'listSnapshots', 'pruneSnapshots', 'backupAllVolumes'); if (in_array($this->input->getArgument('action'), $actions)) { call_user_func(array($this, $this->input->getArgument('action') . 'Action')); } } /** * */ protected function listSnapshotsAction() { if ($this->input->hasArgument('volume') === FALSE) { throw new InvalidArgumentException('Please specify the volume to list existing snapshots for'); } $volumeId = $this->input->getArgument('volume'); $this->output->write(sprintf('Listing snapshot of %s' . PHP_EOL, $volumeId)); $result = $this->ec2Client->describeSnapshots(array( 'Filters' => array( array('Name' => 'volume-id', 'Values' => array($volumeId)) ) )); $this->output->writeln(sprintf('The volume %s has %d snapshots', $volumeId, count($result['Snapshots']))); foreach ($result['Snapshots'] as $snapshot) { $this->output->writeln(sprintf(' - %s (%s) on %s Description %s', $snapshot['SnapshotId'], $snapshot['State'], $snapshot['StartTime']->format('d/m-Y H:i'), $snapshot['Description'])); } } /** * Find all volumes marked with AutoSnapshot=True and ensure a snapshot is created * */ public function backupAllVolumesAction() { $options = array( 'Filters' => array( array('Name' => 'tag:AutoSnapshot', 'Values' => array('True')) ) ); $this->output->writeln('Finding all volumes tagged with AutoSnapshot=True'); foreach ($this->ec2Client->describeVolumes($options)['Volumes'] as $volumeInformation) { $this->output->write(sprintf(' - VolumeID: %s is marked for automatic snapshot' . PHP_EOL, $volumeInformation['VolumeId'])); $this->takeSnaphotOfVolume($volumeInformation['VolumeId']); } } /** * */ protected function pruneSnapshotsAction() { $this->output->writeln('Finding all snapshots that are tagged with AutoPrune=True'); $result = $this->ec2Client->describeSnapshots(array( 'Filters' => array( array('Name' => 'tag:AutoPrune', 'Values' => array('True')) ) )); $offsetInSeconds = 86400 * 7; foreach ($result['Snapshots'] as $snapshot) { $this->output->writeln(sprintf(' - %s (%s) on %s Description "%s"', $snapshot['SnapshotId'], $snapshot['State'], $snapshot['StartTime']->format('d/m-Y H:i'), $snapshot['Description'])); if (time() - $snapshot['StartTime']->getTimestamp() > $offsetInSeconds) { $this->output->writeln('-- Snapshot overdue. Deleting'); $this->ec2Client->deleteSnapshot(array( 'DryRun' => false, 'SnapshotId' => $snapshot['SnapshotId'] )); } else { $this->output->writeln(' -- Snapshot is still valid. Keeping.'); } } } /** * */ protected function takeSnapshotAction() { if ($this->input->hasArgument('volume') === FALSE) { throw new InvalidArgumentException('Please specify the volume to snapshot'); } $volumeId = $this->input->getArgument('volume'); try { $this->output->write(sprintf('Taking snapshot of %s' . PHP_EOL, $volumeId)); $this->takeSnaphotOfVolume($volumeId); } catch (Ec2Exception $e) { if ($e->getAwsErrorCode() == 'InvalidVolume.NotFound') { $this->output->writeln('Unable to finde volue' . $volumeId); } else { $this->output->writeln('General AWS Error ' . $e->getMessage()); } } } /** * Given a VolumneID, create a new snapshot. * * Will test if an ealier snaptshot was created within the last 23 hours, and abort if true. * * @param string $volumeId */ protected function takeSnaphotOfVolume($volumeId) { // Throws exception if no volume is found $volumeInformation = $this->ec2Client->describeVolumes(array('VolumeIds' => array($volumeId))); $result = $this->ec2Client->describeSnapshots(array( 'Filters' => array( array('Name' => 'volume-id', 'Values' => array($volumeId)), array('Name' => 'tag:AutoPrune', 'Values' => array('True')) ) )); $offsetInSeconds = 3600 * 23; // 23 Hours foreach ($result['Snapshots'] as $snapshot) { if (time() - $snapshot['StartTime']->getTimestamp() < $offsetInSeconds) { $this->output->writeln(sprintf('--- Snapshot %s was taken %s, so not taking new snapshot.', $snapshot['SnapshotId'], $snapshot['StartTime']->format('d/m-Y H:i'))); return; } } $now = new \DateTime(); $result = $this->ec2Client->createSnapshot(array( 'VolumeId' => $volumeId, 'Description' => sprintf('Automatic snapshot of volume %s taken on %s', $volumeId, $now->format('d/m-Y H:i')), 'DryRun' => false )); $newSnapshotId = $result['SnapshotId']; $this->output->writeln(sprintf('--- New snapshot scheduled. Id: %s', $newSnapshotId )); $this->ec2Client->createTags(array( 'Resources' => array($newSnapshotId), 'Tags' => array( array('Key' => 'AutoPrune', 'Value' => 'True') ) )); } /** * */ protected function listVolumesAction() { $this->output->write('Volumes available ' . PHP_EOL); $options = [ 'region' => 'eu-west-1', 'version' => '2015-10-01', ]; foreach ($this->ec2Client->describeVolumes()['Volumes'] as $volumeInformation) { $this->output->write(sprintf(' - VolumeID: %s' . PHP_EOL, $volumeInformation['VolumeId'])); if (is_array($volumeInformation['Tags'])) { foreach ($volumeInformation['Tags'] as $tagInformation) { $this->output->write(sprintf(' -- Tag: %s => %s' . PHP_EOL, $tagInformation['Key'], $tagInformation['Value'])); } } if (isset($volumeInformation['Attachments']) and is_array($volumeInformation['Attachments'])) { foreach($volumeInformation['Attachments'] as $attachmentInformation) { $this->output->write(sprintf(' -- Attached to %s (%s)' . PHP_EOL, $attachmentInformation['InstanceId'], $attachmentInformation['Device'])); } } else { $this->output->write(' -- Not attached.' . PHP_EOL); } } } }
1fb39f5a0636298808e2439a1bb895ad2fd75eb4
[ "Markdown", "PHP" ]
3
PHP
mocdk/devops-AWSManager
36665ce5b4fe78da11caa1a8e023a592166de8aa
b3be224365a76672a38a6abaebebdbdfed15f12f
refs/heads/main
<file_sep>import { IGVAListService } from "../../Shared/Model/IGVAListService"; export interface IAccordionProps { description: string; listName:string; listService: IGVAListService; webUrl:string } <file_sep>import * as React from 'react'; import * as ReactDom from 'react-dom'; import { Version } from '@microsoft/sp-core-library'; import { IPropertyPaneConfiguration, PropertyPaneTextField } from '@microsoft/sp-property-pane'; import { BaseClientSideWebPart } from '@microsoft/sp-webpart-base'; import { Provider, teamsTheme } from '@fluentui/react-northstar' import * as strings from 'AccordionWebPartStrings'; import Accordion from './components/Accordion'; import { IAccordionProps } from './components/IAccordionProps'; import AccordionWP from './components/Accordion'; import { IGVAListService } from '../Shared/Model/IGVAListService'; import { GVAListDataService } from '../Shared/Services/GVAListDataService'; export interface IAccordionWebPartProps { description: string; } export default class AccordionWebPart extends BaseClientSideWebPart<IAccordionWebPartProps> { public render(): void { var listProvider: IGVAListService; listProvider = this.context.serviceScope.consume(GVAListDataService.serviceKey); const element: React.ReactElement<IAccordionProps> = React.createElement( AccordionWP, { description: this.properties.description, listName:'NewDocLib', listService: listProvider, webUrl:this.context.pageContext.web.absoluteUrl, } ); ReactDom.render(element, this.domElement); } protected onDispose(): void { ReactDom.unmountComponentAtNode(this.domElement); } protected get dataVersion(): Version { return Version.parse('1.0'); } protected getPropertyPaneConfiguration(): IPropertyPaneConfiguration { return { pages: [ { header: { description: strings.PropertyPaneDescription }, groups: [ { groupName: strings.BasicGroupName, groupFields: [ PropertyPaneTextField('description', { label: strings.DescriptionFieldLabel }) ] } ] } ] }; } } <file_sep> export interface IHelix{ Title:string; URL:any; Id:number; Category:String; } export interface IDocLibrary{ FileRef: string, FileLeafRef:string; FileSystemObjectType: Number; }<file_sep>import {ServiceKey,ServiceScope,Text} from '@microsoft/sp-core-library'; import {SPHttpClient,SPHttpClientResponse} from '@microsoft/sp-http'; import { PageContext } from '@microsoft/sp-page-context'; import { IGVAListService } from '../Model/IGVAListService'; export class GVAListDataService implements IGVAListService { public static readonly serviceKey: ServiceKey<IGVAListService> = ServiceKey.create<IGVAListService>('GVA.IGVAListService', GVAListDataService); private _spHttpClient: SPHttpClient; private _pageContext: PageContext; private _currentWebUrl: string; constructor(serviceScope: ServiceScope) { serviceScope.whenFinished(() => { this._spHttpClient = serviceScope.consume(SPHttpClient.serviceKey); this._pageContext = serviceScope.consume(PageContext.serviceKey); this._currentWebUrl = this._pageContext.web.absoluteUrl; }); } public getAllItems(listName: string): Promise<any>{ //FileSystemObjectType=0 file 1 folder if(listName==null){return null;} const serviceUrl: string = Text.format("{0}/_api/Lists/getByTitle('{1}')/items?$select=FileLeafRef,FileRef,FileSystemObjectType", this._currentWebUrl, listName); return this._spHttpClient.get(serviceUrl, SPHttpClient.configurations.v1) .then((response: SPHttpClientResponse) => { return response.json() .then(data => { var res=data.value; return res; }); }); } } <file_sep>import { IHelix } from "./IGVAListsInterfaces"; export interface IGVAListService { getAllItems(listName: string): Promise<Array<any>>; }
d666a524255c039ad65a08b08c583961a9ebb49a
[ "TypeScript" ]
5
TypeScript
prerak13/accordian
3e8b757f553e0eafd1f832bebb2e29e8c1d54bf2
ec876962c341638eee9b8441263d2d243c7cc5cc
refs/heads/master
<repo_name>muskanmahajan37/App_VF<file_sep>/src/pages/objetivopt2/objetivopt2.ts import { Component } from '@angular/core'; import { IonicPage, NavController, NavParams } from 'ionic-angular'; import { Objetivopt3Page } from '../objetivopt3/objetivopt3'; /** * Generated class for the Objetivopt2Page page. * * See https://ionicframework.com/docs/components/#navigation for more info on * Ionic pages and navigation. */ @IonicPage() @Component({ selector: 'page-objetivopt2', templateUrl: 'objetivopt2.html', }) export class Objetivopt2Page { constructor(public navCtrl: NavController, public navParams: NavParams) { } ionViewDidLoad() { console.log('ionViewDidLoad Objetivopt2Page'); } gonext(){ this.navCtrl.push(Objetivopt3Page); } } <file_sep>/src/pages/configurarnotificacao/configurarnotificacao.module.ts import { NgModule } from '@angular/core'; import { IonicPageModule } from 'ionic-angular'; import { ConfigurarnotificacaoPage } from './configurarnotificacao'; @NgModule({ declarations: [ ConfigurarnotificacaoPage, ], imports: [ IonicPageModule.forChild(ConfigurarnotificacaoPage), ], }) export class ConfigurarnotificacaoPageModule {} <file_sep>/src/pages/objetivopt4/objetivopt4.ts import { Component } from '@angular/core'; import { IonicPage, NavController, NavParams } from 'ionic-angular'; import { Objetivopt5Page } from '../objetivopt5/objetivopt5'; /** * Generated class for the Objetivopt4Page page. * * See https://ionicframework.com/docs/components/#navigation for more info on * Ionic pages and navigation. */ @IonicPage() @Component({ selector: 'page-objetivopt4', templateUrl: 'objetivopt4.html', }) export class Objetivopt4Page { constructor(public navCtrl: NavController, public navParams: NavParams) { } ionViewDidLoad() { console.log('ionViewDidLoad Objetivopt4Page'); } goPro(){ this.navCtrl.push(Objetivopt5Page); } } <file_sep>/src/pages/ajustes/ajustes.ts import { Component } from '@angular/core'; import { IonicPage, NavController, NavParams } from 'ionic-angular'; import { MinhacontaPage } from '../minhaconta/minhaconta'; import { NotificacoesPage } from '../notificacoes/notificacoes'; import { ContactPage } from '../contact/contact'; /** * Generated class for the AjustesPage page. * * See https://ionicframework.com/docs/components/#navigation for more info on * Ionic pages and navigation. */ @IonicPage() @Component({ selector: 'page-ajustes', templateUrl: 'ajustes.html', }) export class AjustesPage { constructor(public navCtrl: NavController, public navParams: NavParams) { } ionViewDidLoad() { console.log('ionViewDidLoad AjustesPage'); } gominhaconta(){ this.navCtrl.push(MinhacontaPage); } gonotificacao(){ this.navCtrl.push(NotificacoesPage); } gocontato(){ this.navCtrl.push(ContactPage); } } <file_sep>/src/pages/perfilquestionario/perfilquestionario.module.ts import { NgModule } from '@angular/core'; import { IonicPageModule } from 'ionic-angular'; import { PerfilquestionarioPage } from './perfilquestionario'; @NgModule({ declarations: [ PerfilquestionarioPage, ], imports: [ IonicPageModule.forChild(PerfilquestionarioPage), ], }) export class PerfilquestionarioPageModule {} <file_sep>/src/pages/editarcarteira/editarcarteira.html <!-- Generated template for the EditarcarteiraPage page. See http://ionicframework.com/docs/components/#navigation for more info on Ionic pages and navigation. --> <ion-header> <ion-navbar> <ion-title>Renda Mensal</ion-title> </ion-navbar> </ion-header> <ion-content > <ion-grid> <ion-row text-center> <ion-col> <p ion-text color="light">Selecione uma opção</p> </ion-col> </ion-row> <ion-card (tap)="gonext()"> <ion-card-content text-center> 100% renda fixa<br>0% </ion-card-content> </ion-card> <ion-card> <ion-card-content text-center> 90% renda fixa<br>0% </ion-card-content> </ion-card> <ion-card> <ion-card-content text-center> 90% renda fixa<br>0% </ion-card-content> </ion-card> <ion-card> <ion-card-content text-center> 90% renda fixa<br>0% </ion-card-content> </ion-card> <ion-card> <ion-card-content text-center> 90% renda fixa<br>0% </ion-card-content> </ion-card> </ion-grid> </ion-content> <file_sep>/src/pages/reserva4/reserva4.ts import { Component } from '@angular/core'; import { IonicPage, NavController, NavParams } from 'ionic-angular'; import { Reserva5Page } from '../reserva5/reserva5'; /** * Generated class for the Reserva4Page page. * * See https://ionicframework.com/docs/components/#navigation for more info on * Ionic pages and navigation. */ @IonicPage() @Component({ selector: 'page-reserva4', templateUrl: 'reserva4.html', }) export class Reserva4Page { constructor(public navCtrl: NavController, public navParams: NavParams) { } ionViewDidLoad() { console.log('ionViewDidLoad Reserva4Page'); } goPro(){ this.navCtrl.push(Reserva5Page); } } <file_sep>/src/pages/minhaconta/minhaconta.ts import { Component } from '@angular/core'; import { IonicPage, NavController, NavParams } from 'ionic-angular'; import { DadoscadastraisPage } from '../dadoscadastrais/dadoscadastrais'; import { PerfildeinvestimentoPage } from '../perfildeinvestimento/perfildeinvestimento'; import { MudaremailPage } from '../mudaremail/mudaremail'; import { TrocarsenhaPage } from '../trocarsenha/trocarsenha'; /** * Generated class for the MinhacontaPage page. * * See https://ionicframework.com/docs/components/#navigation for more info on * Ionic pages and navigation. */ @IonicPage() @Component({ selector: 'page-minhaconta', templateUrl: 'minhaconta.html', }) export class MinhacontaPage { constructor(public navCtrl: NavController, public navParams: NavParams) { } ionViewDidLoad() { console.log('ionViewDidLoad MinhacontaPage'); } godadoscadastrais(){ this.navCtrl.push(DadoscadastraisPage); } goperfilinvestimento(){ this.navCtrl.push(PerfildeinvestimentoPage); } gomudaremail(){ this.navCtrl.push(MudaremailPage); } gomudarsenha(){ this.navCtrl.push(TrocarsenhaPage); } } <file_sep>/src/pages/objetivopt6/objetivopt6.module.ts import { NgModule } from '@angular/core'; import { IonicPageModule } from 'ionic-angular'; import { Objetivopt6Page } from './objetivopt6'; @NgModule({ declarations: [ Objetivopt6Page, ], imports: [ IonicPageModule.forChild(Objetivopt6Page), ], }) export class Objetivopt6PageModule {} <file_sep>/src/pages/objetivopt5/objetivopt5.ts import { Component } from '@angular/core'; import { IonicPage, NavController, NavParams } from 'ionic-angular'; import { Objetivopt6Page } from '../objetivopt6/objetivopt6'; /** * Generated class for the Objetivopt5Page page. * * See https://ionicframework.com/docs/components/#navigation for more info on * Ionic pages and navigation. */ @IonicPage() @Component({ selector: 'page-objetivopt5', templateUrl: 'objetivopt5.html', }) export class Objetivopt5Page { constructor(public navCtrl: NavController, public navParams: NavParams) { } ionViewDidLoad() { console.log('ionViewDidLoad Objetivopt5Page'); } goPro(){ this.navCtrl.push(Objetivopt6Page); } } <file_sep>/src/pages/questionario1/questionario1.ts import { Component } from '@angular/core'; import { IonicPage, NavController, NavParams } from 'ionic-angular'; import { Questionario2Page } from '../questionario2/questionario2'; import { RendaPage } from '../renda/renda'; /** * Generated class for the Questionario1Page page. * * See https://ionicframework.com/docs/components/#navigation for more info on * Ionic pages and navigation. */ @IonicPage() @Component({ selector: 'page-questionario1', templateUrl: 'questionario1.html', }) export class Questionario1Page { constructor(public navCtrl: NavController, public navParams: NavParams) { } ionViewDidLoad() { console.log('ionViewDidLoad Questionario1Page'); } gonext(){ this.navCtrl.push(RendaPage); } } <file_sep>/src/pages/idade/idade.module.ts import { NgModule } from '@angular/core'; import { IonicPageModule } from 'ionic-angular'; import { IdadePage } from './idade'; @NgModule({ declarations: [ IdadePage, ], imports: [ IonicPageModule.forChild(IdadePage), ], }) export class IdadePageModule {} <file_sep>/src/pages/reserva2/reserva2.module.ts import { NgModule } from '@angular/core'; import { IonicPageModule } from 'ionic-angular'; import { Reserva2Page } from './reserva2'; @NgModule({ declarations: [ Reserva2Page, ], imports: [ IonicPageModule.forChild(Reserva2Page), ], }) export class Reserva2PageModule {} <file_sep>/src/pages/listabanco/listabanco.module.ts import { NgModule } from '@angular/core'; import { IonicPageModule } from 'ionic-angular'; import { ListabancoPage } from './listabanco'; @NgModule({ declarations: [ ListabancoPage, ], imports: [ IonicPageModule.forChild(ListabancoPage), ], }) export class ListabancoPageModule {} <file_sep>/src/pages/objetivopt1/objetivopt1.module.ts import { NgModule } from '@angular/core'; import { IonicPageModule } from 'ionic-angular'; import { Objetivopt1Page } from './objetivopt1'; @NgModule({ declarations: [ Objetivopt1Page, ], imports: [ IonicPageModule.forChild(Objetivopt1Page), ], }) export class Objetivopt1PageModule {} <file_sep>/src/pages/objetivopt6/objetivopt6.ts import { Component } from '@angular/core'; import { IonicPage, NavController, NavParams } from 'ionic-angular'; import { Objetivopt7Page } from '../objetivopt7/objetivopt7'; /** * Generated class for the Objetivopt6Page page. * * See https://ionicframework.com/docs/components/#navigation for more info on * Ionic pages and navigation. */ @IonicPage() @Component({ selector: 'page-objetivopt6', templateUrl: 'objetivopt6.html', }) export class Objetivopt6Page { constructor(public navCtrl: NavController, public navParams: NavParams) { } ionViewDidLoad() { console.log('ionViewDidLoad Objetivopt6Page'); } goPro(){ this.navCtrl.push(Objetivopt7Page); } } <file_sep>/src/pages/enderecotelefone/enderecotelefone.module.ts import { NgModule } from '@angular/core'; import { IonicPageModule } from 'ionic-angular'; import { EnderecotelefonePage } from './enderecotelefone'; @NgModule({ declarations: [ EnderecotelefonePage, ], imports: [ IonicPageModule.forChild(EnderecotelefonePage), ], }) export class EnderecotelefonePageModule {} <file_sep>/src/pages/dadoscadastrais/dadoscadastrais.ts import { Component } from '@angular/core'; import { IonicPage, NavController, NavParams } from 'ionic-angular'; import { DadospessoaisPage } from '../dadospessoais/dadospessoais'; import { EnderecotelefonePage } from '../enderecotelefone/enderecotelefone'; import { DadosbancariosPage } from '../dadosbancarios/dadosbancarios'; import { DocumentosPage } from '../documentos/documentos'; /** * Generated class for the DadoscadastraisPage page. * * See https://ionicframework.com/docs/components/#navigation for more info on * Ionic pages and navigation. */ @IonicPage() @Component({ selector: 'page-dadoscadastrais', templateUrl: 'dadoscadastrais.html', }) export class DadoscadastraisPage { constructor(public navCtrl: NavController, public navParams: NavParams) { } ionViewDidLoad() { console.log('ionViewDidLoad DadoscadastraisPage'); } godadospessoais(){ this.navCtrl.push(DadospessoaisPage); } goenderecotelefone(){ this.navCtrl.push(EnderecotelefonePage); } godadosbancarios(){ this.navCtrl.push(DadosbancariosPage); } godocumentos(){ this.navCtrl.push(DocumentosPage); } } <file_sep>/src/pages/reserva5/reserva5.module.ts import { NgModule } from '@angular/core'; import { IonicPageModule } from 'ionic-angular'; import { Reserva5Page } from './reserva5'; @NgModule({ declarations: [ Reserva5Page, ], imports: [ IonicPageModule.forChild(Reserva5Page), ], }) export class Reserva5PageModule {} <file_sep>/src/pages/objetivopt5/objetivopt5.module.ts import { NgModule } from '@angular/core'; import { IonicPageModule } from 'ionic-angular'; import { Objetivopt5Page } from './objetivopt5'; @NgModule({ declarations: [ Objetivopt5Page, ], imports: [ IonicPageModule.forChild(Objetivopt5Page), ], }) export class Objetivopt5PageModule {} <file_sep>/src/pages/objetivopt4/objetivopt4.module.ts import { NgModule } from '@angular/core'; import { IonicPageModule } from 'ionic-angular'; import { Objetivopt4Page } from './objetivopt4'; @NgModule({ declarations: [ Objetivopt4Page, ], imports: [ IonicPageModule.forChild(Objetivopt4Page), ], }) export class Objetivopt4PageModule {} <file_sep>/src/pages/jornada1/jornada1.ts import { Component } from '@angular/core'; import { IonicPage, NavController, NavParams } from 'ionic-angular'; /** * Generated class for the Jornada1Page page. * * See https://ionicframework.com/docs/components/#navigation for more info on * Ionic pages and navigation. */ @IonicPage() @Component({ selector: 'page-jornada1', templateUrl: 'jornada1.html', }) export class Jornada1Page { constructor(public navCtrl: NavController, public navParams: NavParams) { } ionViewDidLoad() { console.log('ionViewDidLoad Jornada1Page'); } } <file_sep>/src/pages/editarcarteiraopcao/editarcarteiraopcao.module.ts import { NgModule } from '@angular/core'; import { IonicPageModule } from 'ionic-angular'; import { EditarcarteiraopcaoPage } from './editarcarteiraopcao'; @NgModule({ declarations: [ EditarcarteiraopcaoPage, ], imports: [ IonicPageModule.forChild(EditarcarteiraopcaoPage), ], }) export class EditarcarteiraopcaoPageModule {} <file_sep>/src/pages/renda/renda.ts import { Component } from '@angular/core'; import { IonicPage, NavController, NavParams } from 'ionic-angular'; import { Questionario1Page } from '../questionario1/questionario1'; import { Questionario2Page } from '../questionario2/questionario2'; /** * Generated class for the RendaPage page. * * See https://ionicframework.com/docs/components/#navigation for more info on * Ionic pages and navigation. */ @IonicPage() @Component({ selector: 'page-renda', templateUrl: 'renda.html', }) export class RendaPage { constructor(public navCtrl: NavController, public navParams: NavParams) { } ionViewDidLoad() { console.log('ionViewDidLoad RendaPage'); } goPro(){ this.navCtrl.push(Questionario2Page); } } <file_sep>/src/pages/editarcarteira/editarcarteira.module.ts import { NgModule } from '@angular/core'; import { IonicPageModule } from 'ionic-angular'; import { EditarcarteiraPage } from './editarcarteira'; @NgModule({ declarations: [ EditarcarteiraPage, ], imports: [ IonicPageModule.forChild(EditarcarteiraPage), ], }) export class EditarcarteiraPageModule {} <file_sep>/src/pages/reserva3/reserva3.module.ts import { NgModule } from '@angular/core'; import { IonicPageModule } from 'ionic-angular'; import { Reserva3Page } from './reserva3'; @NgModule({ declarations: [ Reserva3Page, ], imports: [ IonicPageModule.forChild(Reserva3Page), ], }) export class Reserva3PageModule {} <file_sep>/src/pages/rendamensalvisao/rendamensalvisao.module.ts import { NgModule } from '@angular/core'; import { IonicPageModule } from 'ionic-angular'; import { RendamensalvisaoPage } from './rendamensalvisao'; @NgModule({ declarations: [ RendamensalvisaoPage, ], imports: [ IonicPageModule.forChild(RendamensalvisaoPage), ], }) export class RendamensalvisaoPageModule {} <file_sep>/src/pages/questionario1/questionario1.module.ts import { NgModule } from '@angular/core'; import { IonicPageModule } from 'ionic-angular'; import { Questionario1Page } from './questionario1'; @NgModule({ declarations: [ Questionario1Page, ], imports: [ IonicPageModule.forChild(Questionario1Page), ], }) export class Questionario1PageModule {} <file_sep>/src/pages/objetivopt3/objetivopt3.ts import { Component } from '@angular/core'; import { IonicPage, NavController, NavParams } from 'ionic-angular'; import { Objetivopt4Page } from '../objetivopt4/objetivopt4'; /** * Generated class for the Objetivopt3Page page. * * See https://ionicframework.com/docs/components/#navigation for more info on * Ionic pages and navigation. */ @IonicPage() @Component({ selector: 'page-objetivopt3', templateUrl: 'objetivopt3.html', }) export class Objetivopt3Page { constructor(public navCtrl: NavController, public navParams: NavParams) { } ionViewDidLoad() { console.log('ionViewDidLoad Objetivopt3Page'); } goPro(){ this.navCtrl.push(Objetivopt4Page); } } <file_sep>/src/pages/dadoscadastrais/dadoscadastrais.module.ts import { NgModule } from '@angular/core'; import { IonicPageModule } from 'ionic-angular'; import { DadoscadastraisPage } from './dadoscadastrais'; @NgModule({ declarations: [ DadoscadastraisPage, ], imports: [ IonicPageModule.forChild(DadoscadastraisPage), ], }) export class DadoscadastraisPageModule {} <file_sep>/src/pages/opiniao/opiniao.module.ts import { NgModule } from '@angular/core'; import { IonicPageModule } from 'ionic-angular'; import { OpiniaoPage } from './opiniao'; @NgModule({ declarations: [ OpiniaoPage, ], imports: [ IonicPageModule.forChild(OpiniaoPage), ], }) export class OpiniaoPageModule {} <file_sep>/src/app/app.component.ts import { Component } from '@angular/core'; import { Platform } from 'ionic-angular'; import { StatusBar } from '@ionic-native/status-bar'; import { SplashScreen } from '@ionic-native/splash-screen'; import { TabsPage } from '../pages/tabs/tabs'; import { LoginPage } from '../pages/login/login'; import { CadastroPage } from '../pages/cadastro/cadastro'; import { IdadePage } from '../pages/idade/idade'; import { Questionario1Page } from '../pages/questionario1/questionario1'; import { RendaPage } from '../pages/renda/renda'; import { Questionario2Page } from '../pages/questionario2/questionario2'; import { PerfilquestionarioPage } from '../pages/perfilquestionario/perfilquestionario'; import { AjustesPage } from '../pages/ajustes/ajustes'; import { MinhacontaPage } from '../pages/minhaconta/minhaconta'; import { DadospessoaisPage } from '../pages/dadospessoais/dadospessoais'; import { ReservaPage } from '../pages/reserva/reserva'; @Component({ templateUrl: 'app.html' }) export class MyApp { rootPage:any = LoginPage; constructor(platform: Platform, statusBar: StatusBar, splashScreen: SplashScreen) { platform.ready().then(() => { // Okay, so the platform is ready and our plugins are available. // Here you can do any higher level native things you might need. statusBar.styleDefault(); splashScreen.hide(); }); } } <file_sep>/src/pages/reserva4/reserva4.module.ts import { NgModule } from '@angular/core'; import { IonicPageModule } from 'ionic-angular'; import { Reserva4Page } from './reserva4'; @NgModule({ declarations: [ Reserva4Page, ], imports: [ IonicPageModule.forChild(Reserva4Page), ], }) export class Reserva4PageModule {} <file_sep>/src/pages/perfildeinvestimento/perfildeinvestimento.module.ts import { NgModule } from '@angular/core'; import { IonicPageModule } from 'ionic-angular'; import { PerfildeinvestimentoPage } from './perfildeinvestimento'; @NgModule({ declarations: [ PerfildeinvestimentoPage, ], imports: [ IonicPageModule.forChild(PerfildeinvestimentoPage), ], }) export class PerfildeinvestimentoPageModule {} <file_sep>/src/pages/objetivos/objetivos.ts import { ReservaPage } from './../reserva/reserva'; import { Component } from '@angular/core'; import { IonicPage, NavController, NavParams } from 'ionic-angular'; /** * Generated class for the ObjetivosPage page. * * See https://ionicframework.com/docs/components/#navigation for more info on * Ionic pages and navigation. */ @IonicPage() @Component({ selector: 'page-objetivos', templateUrl: 'objetivos.html', }) export class ObjetivosPage { constructor(public navCtrl: NavController, public navParams: NavParams) { } ionViewDidLoad() { console.log('ionViewDidLoad ObjetivosPage'); } goPro(){ this.navCtrl.push(ReservaPage); } } <file_sep>/src/pages/perfilquestionario/perfilquestionario.ts import { Component } from '@angular/core'; import { IonicPage, NavController, NavParams } from 'ionic-angular'; import { OpiniaoPage } from '../opiniao/opiniao'; /** * Generated class for the PerfilquestionarioPage page. * * See https://ionicframework.com/docs/components/#navigation for more info on * Ionic pages and navigation. */ @IonicPage() @Component({ selector: 'page-perfilquestionario', templateUrl: 'perfilquestionario.html', }) export class PerfilquestionarioPage { constructor(public navCtrl: NavController, public navParams: NavParams) { } ionViewDidLoad() { console.log('ionViewDidLoad PerfilquestionarioPage'); } goPros(){ this.navCtrl.push(OpiniaoPage); } } <file_sep>/src/app/app.module.ts import { NgModule, ErrorHandler } from '@angular/core'; import { BrowserModule } from '@angular/platform-browser'; import { IonicApp, IonicModule, IonicErrorHandler, Menu } from 'ionic-angular'; import { MyApp } from './app.component'; import { HttpModule } from '@angular/http'; import 'rxjs/add/operator/map'; import { AboutPage } from '../pages/about/about'; import { ContactPage } from '../pages/contact/contact'; import { HomePage } from '../pages/home/home'; import { TabsPage } from '../pages/tabs/tabs'; import { StatusBar } from '@ionic-native/status-bar'; import { SplashScreen } from '@ionic-native/splash-screen'; import { LoginPage } from '../pages/login/login'; import { CadastroPage } from '../pages/cadastro/cadastro'; import { IdadePage } from '../pages/idade/idade'; import { Questionario1Page } from '../pages/questionario1/questionario1'; import { RendaPage } from '../pages/renda/renda'; import { Questionario2Page } from '../pages/questionario2/questionario2'; import { PerfilquestionarioPage } from '../pages/perfilquestionario/perfilquestionario'; import { OpiniaoPage } from '../pages/opiniao/opiniao'; import { DadoscadastraisPage } from '../pages/dadoscadastrais/dadoscadastrais'; import { DadospessoaisPage } from '../pages/dadospessoais/dadospessoais'; import { MinhacontaPage } from '../pages/minhaconta/minhaconta'; import { AjustesPage } from '../pages/ajustes/ajustes'; import { EnderecotelefonePage } from '../pages/enderecotelefone/enderecotelefone'; import { DadosbancariosPage } from '../pages/dadosbancarios/dadosbancarios'; import { ListabancoPage } from '../pages/listabanco/listabanco'; import { DocumentosPage } from '../pages/documentos/documentos'; import { MudaremailPage } from '../pages/mudaremail/mudaremail'; import { NotificacoesPage } from '../pages/notificacoes/notificacoes'; import { TrocarsenhaPage } from '../pages/trocarsenha/trocarsenha'; import { PerfildeinvestimentoPage } from '../pages/perfildeinvestimento/perfildeinvestimento'; import { ConfigurarnotificacaoPage } from '../pages/configurarnotificacao/configurarnotificacao'; import { AvaliarappPage } from '../pages/avaliarapp/avaliarapp'; import { Objetivopt1Page } from '../pages/objetivopt1/objetivopt1'; import { Objetivopt2Page } from '../pages/objetivopt2/objetivopt2'; import { Objetivopt3Page } from '../pages/objetivopt3/objetivopt3'; import { Objetivopt4Page } from '../pages/objetivopt4/objetivopt4'; import { Objetivopt5Page } from '../pages/objetivopt5/objetivopt5'; import { Objetivopt6Page } from '../pages/objetivopt6/objetivopt6'; import { Objetivopt7Page } from '../pages/objetivopt7/objetivopt7'; import { ObjetivosPage } from '../pages/objetivos/objetivos'; import { EditarcarteiraPage } from '../pages/editarcarteira/editarcarteira'; import { EditarcarteiraopcaoPage } from '../pages/editarcarteiraopcao/editarcarteiraopcao'; import { EditarcarteirafinalPage } from '../pages/editarcarteirafinal/editarcarteirafinal'; import { ReservaPage } from '../pages/reserva/reserva'; import { Reserva2Page } from '../pages/reserva2/reserva2'; import { Reserva3Page } from '../pages/reserva3/reserva3'; import { Reserva4Page } from '../pages/reserva4/reserva4'; import { Reserva5Page } from '../pages/reserva5/reserva5'; @NgModule({ declarations: [ MyApp, AboutPage, ContactPage, HomePage, TabsPage, LoginPage, CadastroPage, IdadePage, Questionario1Page, Questionario2Page, RendaPage, PerfilquestionarioPage, OpiniaoPage, AjustesPage, DadoscadastraisPage, DadospessoaisPage, MinhacontaPage, EnderecotelefonePage, DadosbancariosPage, ListabancoPage, DocumentosPage, MudaremailPage, NotificacoesPage, TrocarsenhaPage, PerfildeinvestimentoPage, ConfigurarnotificacaoPage, AvaliarappPage, Objetivopt1Page, Objetivopt2Page, Objetivopt3Page, Objetivopt4Page, Objetivopt5Page, Objetivopt6Page, Objetivopt7Page, ObjetivosPage, EditarcarteiraPage, EditarcarteiraopcaoPage, EditarcarteirafinalPage, ReservaPage, Reserva2Page, Reserva3Page, Reserva4Page, Reserva5Page ], imports: [ BrowserModule, IonicModule.forRoot(MyApp, { backButtonText: '', tabsHideonSubPages: true }), HttpModule ], bootstrap: [IonicApp], entryComponents: [ MyApp, AboutPage, ContactPage, HomePage, TabsPage, LoginPage, CadastroPage, IdadePage, Questionario1Page, Questionario2Page, RendaPage, PerfilquestionarioPage, OpiniaoPage, AjustesPage, DadoscadastraisPage, DadospessoaisPage, MinhacontaPage, EnderecotelefonePage, DadosbancariosPage, ListabancoPage, DocumentosPage, MudaremailPage, NotificacoesPage, TrocarsenhaPage, PerfildeinvestimentoPage, ConfigurarnotificacaoPage, AvaliarappPage, Objetivopt1Page, Objetivopt2Page, Objetivopt3Page, Objetivopt4Page, Objetivopt5Page, Objetivopt6Page, Objetivopt7Page, ObjetivosPage, EditarcarteiraPage, EditarcarteiraopcaoPage, EditarcarteirafinalPage, ReservaPage, Reserva2Page, Reserva3Page, Reserva4Page, Reserva5Page ], providers: [ StatusBar, SplashScreen, {provide: ErrorHandler, useClass: IonicErrorHandler} ] }) export class AppModule {} <file_sep>/src/pages/jornada1/jornada1.module.ts import { NgModule } from '@angular/core'; import { IonicPageModule } from 'ionic-angular'; import { Jornada1Page } from './jornada1'; @NgModule({ declarations: [ Jornada1Page, ], imports: [ IonicPageModule.forChild(Jornada1Page), ], }) export class Jornada1PageModule {} <file_sep>/src/pages/objetivopt1/objetivopt1.ts import { Component } from '@angular/core'; import { IonicPage, NavController, NavParams } from 'ionic-angular'; import { Objetivopt2Page } from '../objetivopt2/objetivopt2'; /** * Generated class for the Objetivopt1Page page. * * See https://ionicframework.com/docs/components/#navigation for more info on * Ionic pages and navigation. */ @IonicPage() @Component({ selector: 'page-objetivopt1', templateUrl: 'objetivopt1.html', }) export class Objetivopt1Page { constructor(public navCtrl: NavController, public navParams: NavParams) { } ionViewDidLoad() { console.log('ionViewDidLoad Objetivopt1Page'); } gocriar(){ this.navCtrl.push(Objetivopt2Page); } }
4e1bd89b4acbcc3533c3849050fdb0553fcceeb5
[ "TypeScript", "HTML" ]
39
TypeScript
muskanmahajan37/App_VF
d156eacaf96cc6e3e2ac78c3e7cf85451d9dc0d3
790b432773f15c79d437f027175fea7d6077d6b7
refs/heads/master
<file_sep>package com.silverbars.marketplace; import com.silverbars.domain.Order; import com.silverbars.domain.OrderType; import com.silverbars.persistence.InMemoryOrderRepository; import com.silverbars.persistence.OrderRepository; /** * Quick app to show the functionality of the OrderBoard. */ public class App { public static void main(String[] args){ OrderRepository orderRepository = new InMemoryOrderRepository(); OrderValidationHelper validationHelper = new OrderValidationHelper(); OrderSummaryBuilder orderSummaryBuilder = new CombinedOrderSummaryBuilder(orderRepository); Display display = new ConsoleDisplay(); Order.OrderBuilder orderBuilder = new Order.OrderBuilder(); OrderBoard orderBoard = new OrderBoard(orderRepository, validationHelper, orderSummaryBuilder, display); orderBoard.registerOrder(orderBuilder.userid("km").orderType(OrderType.BUY).quantity(1d).unitPrice(1.1d).build()); orderBoard.registerOrder(orderBuilder.userid("qw").orderType(OrderType.BUY).quantity(3d).unitPrice(1.5d).build()); orderBoard.registerOrder(orderBuilder.userid("ww").orderType(OrderType.BUY).quantity(3d).unitPrice(2.1d).build()); orderBoard.registerOrder(orderBuilder.userid("xx").orderType(OrderType.BUY).quantity(4d).unitPrice(1.5d).build()); orderBoard.registerOrder(orderBuilder.userid("cc").orderType(OrderType.BUY).quantity(5d).unitPrice(3.1d).build()); orderBoard.registerOrder(orderBuilder.userid("km").orderType(OrderType.BUY).quantity(5d).unitPrice(4.1d).build()); orderBoard.registerOrder(orderBuilder.userid("ds").orderType(OrderType.BUY).quantity(1d).unitPrice(1.5d).build()); orderBoard.registerOrder(orderBuilder.userid("as").orderType(OrderType.BUY).quantity(2d).unitPrice(1.1d).build()); orderBoard.registerOrder(orderBuilder.userid("km").orderType(OrderType.BUY).quantity(3d).unitPrice(3.1d).build()); orderBoard.registerOrder(orderBuilder.userid("km").orderType(OrderType.SELL).quantity(1d).unitPrice(1.1d).build()); orderBoard.registerOrder(orderBuilder.userid("qw").orderType(OrderType.SELL).quantity(3d).unitPrice(1.5d).build()); orderBoard.registerOrder(orderBuilder.userid("ww").orderType(OrderType.SELL).quantity(3d).unitPrice(2.1d).build()); orderBoard.registerOrder(orderBuilder.userid("xx").orderType(OrderType.SELL).quantity(4d).unitPrice(1.5d).build()); orderBoard.registerOrder(orderBuilder.userid("cc").orderType(OrderType.SELL).quantity(5d).unitPrice(3.1d).build()); orderBoard.registerOrder(orderBuilder.userid("km").orderType(OrderType.SELL).quantity(5d).unitPrice(4.1d).build()); orderBoard.registerOrder(orderBuilder.userid("ds").orderType(OrderType.SELL).quantity(1d).unitPrice(1.5d).build()); orderBoard.registerOrder(orderBuilder.userid("as").orderType(OrderType.SELL).quantity(2d).unitPrice(1.1d).build()); orderBoard.registerOrder(orderBuilder.userid("km").orderType(OrderType.SELL).quantity(3d).unitPrice(3.1d).build()); orderBoard.displayOrderBoard(); } } <file_sep>package com.silverbars.marketplace; /** * Base exception class for all exceptions. */ public class MarketPlaceException extends RuntimeException{ /** * Constructs a MarketPlaceException with message and root cause. * @param msg * @param rootCause */ public MarketPlaceException(String msg, Throwable rootCause){ super(msg, rootCause); } /** * Constructs a MarketPlaceException with just a message. * @param msg */ public MarketPlaceException(String msg){ this(msg, null); } } <file_sep>package com.silverbars.domain; import org.hibernate.validator.constraints.NotBlank; import javax.validation.constraints.NotNull; import java.util.UUID; import static java.lang.String.format; /** * Representation of an order. */ public class Order implements Comparable{ // Ideally we want the order id to be sequential and unique. // Typically this would be either set by the DB on insertion or from from some distributed order id generator; // A DB or a Order Id generator is assumed to be outside of scope for this exercise and therefore I'm just using // a UUID. private final UUID id; @NotBlank(message = "USERID must be provided") private final String userid; @NotNull(message = "ORDER TYPE must be provided") private final OrderType orderType; @NotNull(message = "QUANTITY must be provided") private Double quantity; @NotNull(message = "UNIT PRICE must be provided") private final Double unitPrice; public Order(UUID id, String userid, OrderType orderType, Double quantity, Double unitPrice) { this.id = id; this.userid = userid; this.quantity = quantity; this.unitPrice = unitPrice; this.orderType = orderType; } public UUID getId() { return id; } public String getUserid() { return userid; } public Double getQuantity() { return quantity; } public Double getUnitPrice() { return unitPrice; } public OrderType getOrderType() { return orderType; } /** * Combines the quantity of this order with that of another one od matching unit price. * @param order */ public void combineWith(Order order){ quantity = quantity + order.getQuantity(); } @Override public String toString(){ return format("%.2f kg for £ %.2f", quantity, unitPrice); } @Override public int compareTo(Object o) { // AC1: Display BUY orders before SELL orders // AC2: For SELL orders the orders with lowest prices are displayed first // AC3: For BUY orders the orders with highest prices are displayed first Order order = (Order)o; if (this.orderType.equals(order.orderType)) { if (this.orderType.equals(OrderType.BUY)){ return order.getUnitPrice().compareTo(this.getUnitPrice()); } else{ return this.getUnitPrice().compareTo(order.getUnitPrice()); } } else { // Show BUY orders first, therefore order by orderType alphabetically return this.getOrderType().compareTo(order.getOrderType()); } } public static class OrderBuilder{ private String userid; private Double quantity; private Double unitPrice; private OrderType orderType; public OrderBuilder userid(String userid){ this.userid = userid; return this; } public OrderBuilder quantity(Double quantity){ this.quantity = quantity; return this; } public OrderBuilder unitPrice(Double unitPrice){ this.unitPrice = unitPrice; return this; } public OrderBuilder orderType(OrderType orderType){ this.orderType = orderType; return this; } public Order build(){ return new Order(UUID.randomUUID(), userid, orderType, quantity, unitPrice); } } } <file_sep>package com.silverbars.persistence; import com.silverbars.domain.Order; import java.util.Collection; import java.util.UUID; import java.util.concurrent.ConcurrentHashMap; /** * In memory implementation of a Order Repository. Uses a ConcurrentHashMap to allow multithreaded access to the order store. */ public class InMemoryOrderRepository implements OrderRepository { private final ConcurrentHashMap<UUID, Order> orders = new ConcurrentHashMap<UUID, Order>(); public void addOrder(Order order) { orders.put(order.getId(), order); } public void removeOrder(UUID orderId) { orders.remove(orderId); } public Order getOrder(UUID orderId) { return orders.get(orderId); } public Collection<Order> getAllOrders() { return orders.values(); } } <file_sep>package com.silverbars.marketplace; import com.silverbars.domain.Order; import javax.validation.ConstraintViolation; import javax.validation.Validation; import javax.validation.Validator; import javax.validation.ValidatorFactory; import java.util.Set; import java.util.stream.Collectors; /** * Helper class to assist with the validation of Order creation requests. */ public class OrderValidationHelper { private final Validator validator; public OrderValidationHelper(){ ValidatorFactory factory = Validation.buildDefaultValidatorFactory(); validator = factory.getValidator(); } /** * Validates the given order. * @throws MarketPlaceException if the Order is deemed to be invalid. * @param order */ public void validate(Order order) { Set<ConstraintViolation<Order>> violations = validator.validate(order); if (!violations.isEmpty()) { StringBuilder sb = new StringBuilder("Invalid Order: "); sb.append(violations.stream().map(v -> v.getMessage()).collect(Collectors.joining(","))); // Typically would actually throw a subclass of this - ie ValidationException // But as we have no other exceptions in this small example we will just // use the base class. throw new MarketPlaceException(sb.toString()); } } }
6c7cfd946f6a8ba3386f79cafa52d443bb2adffa
[ "Java" ]
5
Java
k8son/marketplace
4942ba3423a9ac95e8ad28396a6fdfb8ec358b20
5d54f3140ad87f60fde2829ea6ab4349ec4400c8
refs/heads/main
<file_sep># React-Project # React-Assignment # React <file_sep>import { CAMPSITES } from '../shared/campsites'; import { COMMENTS } from '../shared/comments'; import { PARTNERS } from '../shared/partners'; import { PROMOTIONS } from '../shared/promotions'; export const initialState = { campsites: CAMPSITES, comments: COMMENTS, partners: PARTNERS, promotions: PROMOTIONS }; export const Reducer = (state = initialState, action) => { return state; }
ddb6d0a76e9bc8600eac26a0b63edfc029659372
[ "Markdown", "JavaScript" ]
2
Markdown
BluHuskii/React
1237d50a0621bfddfb72d258e6d741845441e64a
62d6e8140ce369c63a8eac762662db06859f3427
refs/heads/master
<file_sep>// import { dispatch } from "rxjs/internal/observable/range"; const ADD_GUN = 'add'; const REMOVE_GUN = 'reduce'; export function counter(state=10, action) { switch(action.type) { case 'add': return state + 1; case 'reduce': return state - 1; default: return 10; } } // actionCreator export function addGun() { return { type: ADD_GUN }; } export function removeGun() { return { type: REMOVE_GUN }; } export function addGunAsync() { return dispatch => { setTimeout(() => { dispatch({type: ADD_GUN}) },2000) } } <file_sep>import React from 'react'; import { connect } from 'react-redux'; import { Link,Route,Redirect } from 'react-router-dom'; import App from './App'; import { Login,Logout } from './Auth.redux'; function Erying() { return <div>二营</div> } function Qibinglian() { return (<div>骑兵连</div>) } export default class Dashboard extends React.Component { render() { console.log(this.props); const redirectToLogin = <Redirect to='/login'></Redirect> const app = ( <div> <h1>独立团</h1> <button onClick={()=>{this.props.Logout()}}>注销</button> <ul> <li> <Link to='/dashboard'>一营</Link> </li> <li> <Link to='/dashboard/erying'>二营</Link> </li> <li> <Link to='/dashboard/qibinglian'>骑兵连</Link> </li> </ul> {/* Switch只渲染一个子组件 */} <Route path='/dashboard' exact component={App}></Route> <Route path='/dashboard/erying' component={Erying}></Route> <Route path='/dashboard/qibinglian' component={Qibinglian}></Route> {/* <Route path='/:loaction' component={Test}></Route> */} <Redirect to='/dashboard'></Redirect> </div> ) return this.props.isAuth ? app : redirectToLogin } } const mapStatetoProps = function(state) { return { isAuth: state.auth.isAuth, user: state.auth.user } } const actionCreators = { Login, Logout }; Dashboard = connect(mapStatetoProps,actionCreators)(Dashboard); <file_sep>import React from 'react'; import { connect } from 'react-redux'; import { Login, Logout } from './Auth.redux'; import { Redirect } from 'react-router-dom' export default class Auth extends React.Component { render() { return ( <div> {this.props.isAuth ? <Redirect to='/dashboard' /> : null} <h2>Auth Page...您当前处于未登录状态,请先登录。。</h2> <button onClick = {() => this.props.Login()}>登录</button> </div> ) } } const mapStatetoProps = function(state) { return { isAuth: state.auth.isAuth, user: state.auth.user } } const actionCreators = { Login, Logout } Auth = connect(mapStatetoProps,actionCreators)(Auth)<file_sep>import React from 'react'; import ReactDOM from 'react-dom'; import { createStore,applyMiddleware,compose } from 'redux'; import { Provider } from 'react-redux'; import { BrowserRouter, Route, Redirect, Switch } from 'react-router-dom'; import thunk from 'redux-thunk'; // import App from './App.js'; import reducers from './reducers' // import { counter } from './index.redux'; import Auth from './Auth' import Dashboard from './Dashboard' const store = createStore(reducers,compose( applyMiddleware(thunk), window.devToolsExtension ? window.devToolsExtension() : f => f )); // console.log(store.getState()); // function Erying() { // return <div>二营</div> // } // function Qibinglian() { // return (<div>骑兵连</div>) // } // function Test(props) { // console.log(this.props); // return (<h2>测试组件</h2>) // } // class Test extends React.Component { // render() { // console.log(this.props); // return <h2>测试组件{this.props.location.pathname}</h2> // } // } // ReactDOM.render( // <Provider store={ store }> // <BrowserRouter> // <ul> // <li> // <Link to='/'>一营</Link> // </li> // <li> // <Link to='/erying'>二营</Link> // </li> // <li> // <Link to='/qibinglian'>骑兵连</Link> // </li> // </ul> // <Switch> // {/* 只渲染命中的第一个组件 */} // <Route path='/' exact component={App}></Route> // {/* <Route path='/:location' component={Test}></Route> */} // <Route path='/erying' component={Erying}></Route> // <Route path='/qibinglian' component={Qibinglian}></Route> // <Route path='/:loaction' component={Test}></Route> // <Redirect to='/qibinglian'></Redirect> // </Switch> // </BrowserRouter> // </Provider>, // document.getElementById("root")); ReactDOM.render( <Provider store = { store }> <BrowserRouter> <Switch> {/* index中只放两个路由,login和dashboard分别跳认证和dashboard页面,dashboard页面逻辑在Dashboard中去实现 */} <Route path='/login' component={Auth}></Route> <Route path='/dashboard' component={Dashboard}></Route> <Redirect to='/dashboard'></Redirect> </Switch> </BrowserRouter> </Provider>, document.getElementById('root') ) <file_sep>const LOGIN = 'login'; const LOGOUT = 'logout'; export function auth(state={isAuth: false,user:'liyunlong'},action) { switch(action.type) { case LOGIN: return {...state, isAuth: true}; case LOGOUT: return {...state,isAuth: false}; default: return state; } } // actionCreator export function Login() { return {type: LOGIN} } export function Logout() { return {type: LOGOUT} }<file_sep>const express = require('express'); const mongoose = require('mongoose'); // 连接mongo,并且使用imooc这个集合 const DB_URL = 'mongodb://127.0.0.1:27017/?gssapiServiceName=mongodb/imooc'; mongoose.connect(DB_URL); mongoose.connection.on('connected',() => { console.log("connected success...") }); // 类似于mysql的表,mongo里有文档、字段的概念 const User = mongoose.model('user',new mongoose.Schema({ user: {type: String,require: true}, age: {type: Number,require: true} })) // 新增数据 // User.create({ // user: 'xiaomin', // age: 15 // },(err,doc) => { // if(!err) { // console.log(doc); // } else { // console.log(err); // } // }) // User.remove({age:23},(err,doc) => { // if(!err) { // console.log(doc) // } // }) User.update({'user':'xiaomin'},{'$set': {age: 23}},(err,doc) => { if(!err) { console.log(doc); } }) const server = express(); server.get('/',(req,res) => { res.send('<h1>Hello world!!</h1>'); }) server.get('/data',(req,res) => { res.json({'name': 'luohuayu &&','age': 23,'hobby': 'coding'}); }) server.get('/info',(req,res) => { User.find({'user': 'xiaomin'},(err,doc) => { res.json(doc) }) }) server.listen(8080,() => { console.log("Node server started at port 8080"); })<file_sep>import React from 'react'; import { connect } from 'react-redux'; import { addGun,removeGun,addGunAsync } from './index.redux' // import { ReactDOM } from 'react-dom'; export default class App extends React.Component { render() { const { num,addGun,removeGun,addGunAsync } = this.props; return ( <div> <h1>{`现在有机枪${num}把`}</h1> <button onClick = {() => {addGun()}}>Add gun</button> <button onClick = {() => {removeGun()}}>remove gun</button> <button onClick = {() => {addGunAsync()}}>addGunAsync</button> </div> ) } } const mapStatetoProps = function(state) { return { num:state.counter } } const actionCreators = { addGun,removeGun,addGunAsync } // connect将state和方法注册到组件props中,在组件中直接通过this.props获得 App = connect(mapStatetoProps,actionCreators)(App)
c3923f56054e1c5711ba4cc40837a65d2c464923
[ "JavaScript" ]
7
JavaScript
sklccchenchen/imoocc
6a5651cd9f4bfca62cfaca1b67fe51d5f7e12adb
b8887edbacce3a926348da6aa1e49aa72e2015fe
refs/heads/master
<repo_name>romanbr1/JS<file_sep>/OOP/OOP protype.js function Robot(name, works) { this.name = name; this.works = works; } Robot.prototype.work = function() { console.log('Im a ' + this.name + ' - Im ' + this.works); } function CoffeRobot(name, works) { Robot.call(this, name, works); } CoffeRobot.prototype = Object.create(Robot.prototype); function RobotDancer(name, works) { Robot.call(this, name, works); } RobotDancer.prototype = Object.create(Robot.prototype); function RobotCoocker(name, works) { Robot.call(this, name, works); } RobotCoocker.prototype = Object.create(Robot.prototype); var r = new Robot('Robot', 'just work'); var cfr = new CoffeRobot('CoffeRobot', 'make coffee'); var dnr = new RobotDancer('RobotDancer', 'just dance'); var ckr = new RobotCoocker('RobotCoocker', 'just cook'); var robots = []; robots.push(r, cfr, ckr, dnr); for (i = 0; i < robots.length; i++) { robots[i].work(); } <file_sep>/jquery/jqueryScripts.js $(document).ready(function() { $('#userAgeGet').focusout(function() { if($("#userAgeGet").val()>100||$("#userAgeGet").val()<1||isNaN($("#userAgeGet").val())){ alert("wrong age input"); $('#userAgeGet').addClass('error'); $('#getButt').attr("disabled", "disabled");; } else{ $('#userAgeGet').removeClass('error'); $('#getButt').removeAttr("disabled"); } }); $('#userAgePost').focusout(function() { if($("#userAgePost").val()>100||$("#userAgePost").val()<1||isNaN($("#userAgePost").val())){ alert("wrong age input"); $('#userAgePost').addClass('error'); $('#postButt').attr("disabled", "disabled");; } else{ $('#userAgePost').removeClass('error'); $('#postButt').removeAttr("disabled"); } }); $('#getButt').bind('click', function() { $.ajax({ type: 'GET', contentType: 'application/json', url: 'http://localhost:3001/userGet?userName='+$('#userNameGet').val()+'&userAge='+$('#userAgeGet').val()+'&userAddress='+$('#userAddressGet').val(), success: function(data) { console.log('success'); console.log(JSON.stringify(data)); $('#getResult').html(JSON.stringify(data)); } }); }); $('#postButt').bind('click', function() { var fields = { userName:$('#userNamePost').val(), userAge:$('#userAgePost').val(), userAddress:$('#userAddressPost').val(), }; $.ajax({ type: 'POST', data: JSON.stringify(fields), contentType: 'application/json', url: 'http://localhost:3001/userPost', success: function(data) { console.log('success'); console.log(JSON.stringify(data)); $('#postResult').html(JSON.stringify(data)); } }); }); }); <file_sep>/arrays/Arrays.js //task 1 let products = [ 'Apple', 'Orange', 'Plum' ]; console.log(products[products.length - 1]); // task 2 console.log('----task 2------------------'); let styles = [ 'Jaz', 'Bluz' ]; styles.push('Rock n Roll'); styles.splice(-2, 1, 'Classic'); console.log(styles.shift()); styles.unshift('Rep', 'Reggi'); console.log(styles); // task 3 console.log('----task 3------------------'); let fruits = [ 'Apple', 'Orange', 'Plum' ]; function find(arr, value) { for (i = 0; i < arr.length; i++) { if (arr[i] == value) return i; } return -1; } console.log(find(fruits, 'Plum')); //task 4 console.log('----task 4------------------'); let cars = [ 'Audi', 'Mersedes', 'BMW','Toyota','Mazda','Ford','Subaru','VW' ]; function filterRange(arr, a, b) { if (a>b){ let c; c=a; a=b; b=c; } if ((a<0)||(a>arr.length)||(b<0)||(b>arr.length)){ console.log('Out of range'); } return arr.slice(a-1,b); } console.log(filterRange(cars,2,4)); //task 5 console.log('----task 5------------------'); function camelize (str){ str=str.toLowerCase(); let arr = str.split('-'); for(i=1;i<arr.length;i++){ arr[i]=arr[i][0].toUpperCase() + arr[i].slice(1); } return str = arr.join(''); } console.log(camelize('my-short-string')); console.log(camelize('new-variable-contains-array-of-string')); <file_sep>/OOP/OOP functional.js function Robot(name, works) { this.name=name; this.works=works; this.work= function() { console.log('Im a '+ this.name+' - Im '+this.works); } } function CoffeRobot(name,works) { Robot.call(this,name,works); } function RobotDancer(name,works) { Robot.call(this,name,works); } function RobotCoocker(name,works) { Robot.call(this,name,works); } var r= new Robot('Robot', 'just work'); var cfr= new CoffeRobot('CoffeRobot', 'make coffee'); var dnr= new RobotDancer('RobotDancer', 'just dance'); var ckr= new RobotCoocker('RobotCoocker', 'just cook'); var robots=[]; robots.push(r,cfr,ckr,dnr); for(i=0;i<robots.length;i++){ robots[i].work(); } <file_sep>/object, function, exception/homework2.js //task1 let user = {}; user.name = "Pulup"; user.surname = "Shevchenko"; user.name = "Sergiy"; console.log(user); delete (user.name); console.log(user); // task2 console.log("-----------------"); employeeSalaries = {}; employeeSalaries.e1 = 1000; employeeSalaries.e2 = 2000; employeeSalaries.e3 = 3000; employeeSalaries.e4 = 4000; employeeSalaries.e5 = 5000; console.log(employeeSalaries); let summ = 0; for ( let salary in employeeSalaries) { summ += employeeSalaries[salary]; } console.log(summ); // task3 console.log("-----------------"); function calc(a, operator, b) { let x; console.log(a+operator+b+"="); try { switch (operator) { case ("+"): { x = a + b; break; } case ("-"): { x = a - b; break; } case ("*"): { x = a * b; break; } case ("/"): { x = a / b; break; } } if (typeof (x) === 'undefined') throw "wrong operator"; if(isNaN(a)) throw "a is not a number"; if(isNaN(b)) throw "b is not a number"; } catch (err) { console.log(err); return 0; } return x; } console.log(calc(5, "+", 8)); console.log(calc(5, "-", 8)); console.log(calc(5, "*", 8)); console.log(calc(5, "/", 8)); console.log(calc(5, "f", 8)); console.log(calc("a", "+", 8)); console.log(calc(5, "+", "a"));<file_sep>/Client JS/script.js function printDataToListElements() { var elements = document.querySelectorAll('.List1>ul>li'); for (var i = 0; i < elements.length; i++) { var currentElement = elements[i]; currentElement.innerHTML = 'information ' + (i + 1); } } function countListElements() { var elements = document.querySelectorAll('.List1>ul>li'); var paragraph = document.getElementById("Count"); paragraph.textContent = 'List contains ' + elements.length + ' elements'; } function markExternalLinks() { var linkElements = document.querySelectorAll('li>a'); for (var i = 0; i < linkElements.length; i++) { var currentElement = linkElements[i]; if (currentElement.innerHTML.includes('http://') || currentElement.innerHTML.includes('ftp://')) { currentElement.classList.add("external-red"); // currentElement.style.color = 'red'; // currentElement.style.backgroundColor = 'white' } } var x = document.getElementsByClassName("external-red"); for (var j = 0; j < x.length; j++) { x[j].style.color = 'red'; x[j].style.backgroundColor = 'white' } } <file_sep>/closures/closuresHomework.js function makeBuffer() { var bufferVelue = ''; function buffer(value) { if (value === undefined) value = ''; return bufferVelue += value; }; buffer.clear = function() { bufferVelue = ''; } return buffer; } var buffer = makeBuffer(); buffer('JavaScript'); buffer('Вчити'); buffer('Потрібно!'); console.log(buffer()); var buffer = makeBuffer(); buffer(0); buffer(1); buffer(0); console.log(buffer()); var buffer = makeBuffer(); buffer("Тест "); buffer("тебе не з'їсть"); console.log(buffer()); buffer.clear(); console.log(buffer());
9115a4d2f3223b1e3008f522b86b98992dcf5b04
[ "JavaScript" ]
7
JavaScript
romanbr1/JS
a804a6c8dbe8396bb3c8fd2d0d4f923902dc2b0e
0d2566e6fb5932a43501487f9aac36edda400125
refs/heads/master
<file_sep><?php namespace App\Services; class GetPopularCurrenciesCommandHandler { const POPULAR_COUNT = 3; private $currencyRepository; public function __construct(CurrencyRepositoryInterface $currencyRepository) { $this->currencyRepository = $currencyRepository; } public function handle(int $count = self::POPULAR_COUNT): array { $currencies = $this->currencyRepository->findAll(); usort($currencies, function($firstCurrency, $secondCurrency) { return (float)$firstCurrency->getPrice() < (float)$secondCurrency->getPrice(); }); return array_slice($currencies, 0, $count); } }<file_sep><?php namespace App\Services; use App\Services\Currency; class CurrencyGenerator { public static function generate(): array { return [ new Currency(1, "Bitcoin", 6658.28, "https://s2.coinmarketcap.com/static/img/coins/16x16/1.png", 1.35), new Currency(2, "Ethereum", 473.71, "https://s2.coinmarketcap.com/static/img/coins/16x16/1027.png", 2.15), new Currency(3, "XRP", 0.473783, "https://s2.coinmarketcap.com/static/img/coins/16x16/52.png", 1.60), new Currency(4, "Bitcoin Cash", 728.74, "https://s2.coinmarketcap.com/static/img/coins/16x16/1.png", 1.30), new Currency(5, "EOS", 8.66, "https://s2.coinmarketcap.com/static/img/coins/16x16/1.png", 2.49), new Currency(6, "Litecoin", 83.13, "https://s2.coinmarketcap.com/static/img/coins/16x16/1.png", 1.04), new Currency(7, "Stellar", 0.207120, "https://s2.coinmarketcap.com/static/img/coins/16x16/1.png", 2.95), new Currency(8, "Cardano", 0.143530, "https://s2.coinmarketcap.com/static/img/coins/16x16/1.png", 1.25), new Currency(9, "IOTA", 1.08, "https://s2.coinmarketcap.com/static/img/coins/16x16/1.png", -2.03), new Currency(10, "Tether", 1.00, "https://s2.coinmarketcap.com/static/img/coins/16x16/1.png", -0.18) ]; } }<file_sep><?php namespace App\Http\Controllers; use App\Services\CurrencyRepositoryInterface; use App\Services\GetMostChangedCurrencyCommandHandler; use App\Services\GetPopularCurrenciesCommandHandler; use App\Services\CurrencyPresenter; class CurrenciesController extends Controller { private $currencyRepository; public function __construct(CurrencyRepositoryInterface $currencyRepository) { $this->currencyRepository = $currencyRepository; } public function getCurrencies() { $jsonCurrencies = []; foreach ($this->currencyRepository->findAll() as $currency) { $jsonCurrencies[] = CurrencyPresenter::present($currency); } return response()->json($jsonCurrencies); } public function getUnstableCurrency() { $unstableCurrency = (new GetMostChangedCurrencyCommandHandler($this->currencyRepository))->handle(); $jsonCurrency = CurrencyPresenter::present($unstableCurrency); return response()->json($jsonCurrency); } public function getPopularCurrencies() { $popularCurrencies = (new GetPopularCurrenciesCommandHandler($this->currencyRepository))->handle(); return view("popular_currencies", compact("popularCurrencies")); } } <file_sep><?php namespace App\Services; class GetMostChangedCurrencyCommandHandler { private $currencyRepository; public function __construct(CurrencyRepositoryInterface $currencyRepository) { $this->currencyRepository = $currencyRepository; } public function handle(): Currency { $currencies = $this->currencyRepository->findAll(); usort($currencies, function($firstCurrency, $secondCurrency) { return (float)$firstCurrency->getDailyChangePercent() < (float)$secondCurrency->getDailyChangePercent(); }); return $currencies[0]; } }
f94d920e902f108b3667fadb4d57514d93575caa
[ "PHP" ]
4
PHP
Serhii32/bsa-2018-php-5
8eb1b998e024ea9263241a9a5e0d97a1f847240e
80abd2276046af33bf1715ab45a3a9703d1d6c52
refs/heads/main
<repo_name>faresdibany/Data-Extraction-Processing-Visualzing-and-Curve-Fitting-Pipeline-for-Mass-Spectrometry-<file_sep>/shifting_efficiency.py # -*- coding: utf-8 -*- """ Created on Thu May 27 09:26:58 2021 @author: Stefan """ #this code is to import the created histograms from the previous "Automatic_Data_Extraction" #code, and shift the efficiency profile, according to the expected shift of M/z from the program import pandas as pd import numpy as np #importing the efficiency matrix eff = pd.read_csv(r'D:\G210528_001_Slot1-9_1_1760.d\Analysis1_251\ef10.csv',index_col=0) eff.columns = eff.columns.map(str) counter = 0 #running the loop over all scans for i in range(0,901): #shifting the columns, corresponding to the scan number by 10 multiplied by the scan number. #the value 10 changes, with respect to the M/z binning increment done in creating the histograms. #in this case, the increment was 0,125, and the expected shifting was 1.25 Th eff[str(counter)]=eff[str(counter)].shift(10*i) #runs over the next scan counter+=1 #converts any NaNs to 0 eff.fillna(0) #saves file to csv eff.to_csv(r'D:\G210528_001_Slot1-9_1_1760.d\Analysis1_251\Shifted\ef10 shifted.csv')<file_sep>/Automatic_Data_extraction.py # -*- coding: utf-8 -*- """ Created on Wed May 26 12:21:46 2021 @author: Stefan """ #This script is to extract data from the raw data, and implement a histogram, binning the intensity signals #with respect to the M/z range, and the scan range. This is to give a midia profile, for the assesment of #experiment import pathlib from pprint import pprint import pandas as pd from timspy.df import TimsPyDF # from timspy.dia import TimsPyDIA import numpy as np import itertools from fast_histogram import histogram2d import functools from functools import partial import matplotlib as plt #directs to the path of the experiment path = pathlib.Path(r'D:\G210624_003_Slot1-8_1_2008.d') #imports rawdata, using Timspy D = TimsPyDF(path) #acquiring MS1 frames as an array y = D.ms1_frames #converting array to Dataframe, with the column named "Frame" y = pd.DataFrame(y, columns = ['frame']) #extracting data from raw data for retention time between 20 and 40 minutes, or 1200 and 2400 seconds #this is just to check for the minimum and maximum frame and scan numbers, for the binning. #it is then commented, and the program is re-run #X = D.rt_query(1200,2400) #extracting data from raw data, with specific frames frames in mind. #in this case, ms1 data is extracted, by slicing the data for every ms1 frame ms_one = D.query(frames=slice(1,42778,21), columns=['frame','scan','mz','intensity','retention_time']) #this is to extract the sub matrix from the one above, for only the retention time between 20 and 40 minutes ms_one = ms_one[(ms_one['retention_time']>=1200) & (ms_one['retention_time']<=2400)] #binning for the m/z range, with 0.2 Th increment, where the minimum and maximum are 50 and 1700, respectively. xedges = np.arange(50,1700.2,0.2) #binning for the scan range, with 1 increment yedges = np.arange(0,451) #creating histogram, taking into consideration the binning edges, from above, and #extracting the m/z and the scans, from the MS1 data, extracted above, while the weights for the #histogram, or the values for each m/z and scan bin, are the intensities, from the MS1 file. #binning, basically, adds the intensities in the same bin of scan and m/z H, xedges, yedges = np.histogram2d(ms_one.mz, ms_one.scan, bins=(xedges, yedges),weights=ms_one.intensity) #as it is low collision energy experiment, to eliminate the noise, we eliminate signals below 200 #and make them equal to 0 w = np.where(H<=200) H[w] = 0 #converting the MS1 histogram, H, to a dataframe, so we could save it as a csv file ms1 = pd.DataFrame(H) ms1.to_csv(r'D:\G210624_003_Slot1-8_1_2008.d\Analysis\ms1.csv') #initializing the list for the extraction of the data for all midia groups, and for the binning #and histogram creation for each midia group midia = [] midia_histograms=[] #given that for this experiment,MS1 frames repeat after 21 frames, MS2 frames start from 2 and end at 21 #python always ends at the value less than the maximum by 1 e = np.arange(2,22) # e = 2 #initializing the list for transmission efficiency efficiency = [] for i in range(len(e)): #j runs over the values of the array, e. j = e[i] #as mentioned before, same procedure of extracting MS1 data, however, here we run over #the values of j, which starts at 2, and ends at 21 ms2 = D.query(frames=slice(j,42798,21), columns=['frame','scan','mz','intensity','retention_time']) ms2 = ms2[(ms2['retention_time']>=1200) & (ms2['retention_time']<=2400)] # midia.append([j-1,ms2]) #here we add the MS2 matrices to the "midia" list, where we would have 20 MS2 groups or datasets midia.append(ms2) #k runs over each MS2 group, or each element of the midia list for k in range(len(midia)): #creating a histogram, as in MS1, but runs over each dataset from the midia list. HH,xedges,yedges=np.histogram2d(midia[k].mz,midia[k].scan,bins=(xedges,yedges),weights=midia[k].intensity) #eliminating the signals below 200, for noise elimination HH[np.where(HH<=200)]=0 #adding MS2 group histograms to the midia_histograms list midia_histograms.append([HH]) #u runs over each histogram in the midia_histograms list for u in range(len(midia_histograms)): #to get the transmission efficiency, we divide the MS2 histogram by the MS1 histogram #this is where the loop runs over each histogram, in accordance with "u" eff = midia_histograms[u][0]/H #finding the NaNs in the matrix, in case of a 0 in MS2 being divided by MS1 a = np.isnan(eff) eff[a] = 0 #finding the infinities in the matrix, as a nonzero MS2 signal can be divided by a 0 in MS1 b = np.isinf(eff) eff[b]=0 #adds the transmission efficiency matrices to the efficiency list efficiency.append(eff) #save transmission efficiency matrices to specified path as csv file, in a loop path1= "D:\G210624_003_Slot1-8_1_2008.d\Analysis" for o in range(len(efficiency)): eff9 = pd.DataFrame(efficiency[o]) eff9.to_csv(path1+'\ef'+str(o+1)+'.csv') #save binned midia groups to the specified path as csv file, in a loop # for w in range(len(midia_histograms)): # midi = pd.DataFrame(midia_histograms[w][0]) # midi.to_csv(path1+'\midia'+str(w+1)+'.csv') <file_sep>/Histogram_per_frame.py # -*- coding: utf-8 -*- """ Created on Fri May 21 11:16:42 2021 @author: stefan """ #this code extracts raw data, and creates 1d arrays of intensities for all scans, for each single frame #this is to show whether, following an MS1 frame, the three consecutive MS2 frames pick up the signals of the MS1 import pathlib from pprint import pprint import pandas as pd from timspy.df import TimsPyDF # from timspy.dia import TimsPyDIA import numpy as np import itertools import functools from functools import partial import matplotlib as plt #direct to specified path path = pathlib.Path(r'D:\G210528_001_Slot1-9_1_1760.d') D = TimsPyDF(path) #extracting data from raw data between specified retention time X = D.rt_query(1800,2400,columns = ['frame','scan','mz','intensity','retention_time']) # scans = pd.DataFrame(np.arange(340,401)) # scans.columns = ['scan'] # X = X.merge(scans,on='scan') # X = X[(X['mz']>=462.98) & (X['mz']<=467.02)] # X = X[(X['mz']>=462.98) & (X['mz']<=500.02)] # X = X[(X['scan']>=340)&(X['scan']<401)] #specifying frame range. Starting value depends on the minimum value, changes with respect to #midia group, and MS1 frame, from a certain retention time Frames = np.arange(17010,22617,21) # sca = np.arange(220,301) results = [] for i in range(len(Frames)): #binning edges, with respect to scans xedges = np.arange(0,901) #slicing the data file with respect to the specified frames above Y = X[(X['frame']==Frames[i])] # X.frame=Frames[i] #creating histogram, with respect to frames and scans, where we would get a 1d Array for each frame, running over all scan #this histogram would add all intensities in each specific scan, for all frames in single group, whether MS1 or MS2 H,xedges = np.histogram(Y.scan,bins = xedges,weights = Y.intensity) #appending histograms for each frame to the results list results.append((Frames[i],H)) #initializing list midia10 = [] # k = np.arange(21423,41202,21) #scan numbers e = np.arange(0,267) for j in range(len(e)): #extracting all intensities for the scans and saving them as MS2 frame histograms midia10.append(results[j][1]) #summing intensity values for each frame, and getting the result in a 1d Array o = [sum(i) for i in zip(*midia10)] p=pd.DataFrame(o) p.columns=['MIDIA20'] p.to_csv(r'D:\G210528_001_Slot1-9_1_1760.d\Frame by Frame\MIDIA20.csv') <file_sep>/README.md # Data-Extraction-and-Processing-Pipeline-for-Mass-Spectrometry- This repository is for python scripts to extract raw mass spectrometry data and create histograms for MS1 and MS2 frames and groups, summing the intensities, with respect to binned M/z and Scan. Recommended order of viewing the scripts: 1-Automatic_Data_Extraction.py 2-Shifting_efficiency.py 3-Histogram_per_Frame.py First file extracts data from raw mass spectrometry data, using Timspy, and then creates histograms of MS1 and MS2 groups, and calculates transmission efficiency for each MS2 group. Second file imports the transmission efficiency matrices, and starts shifting each scan by a specified value, depending on the programmed and the expected shift of the scans, in the m/z value Third file extracts data from raw mass spectrometry data, using Timspy, and then creates histograms of single frames of binned intensities, with the goal to check whether following each MS1 frame, the first 3 frames pick up the signal or not. Detailed description of the code is in each script. The added matlab scripts are for fitting transmission efficiency curves to measured transmission efficiency curve, with the goal of acquiring the position of the ideal transmission efficiency, for each scan, in a specific midia group of an experiment, and also for visualizing the difference between fitted values and the isolation m/z. Recommended order of viewing the scripts: 1-lsq.m 2-visualizing_position_difference_ideal_and_programmed.m 3-visualizing_position_difference_ideal_and_programmed_same_midia_different_experiment.m The fitting is done using least squares method, where it is optimized, until the minimum of the objective function is reached. The optimized parameters are the beginning position of the left and right edges of the ideal transmission curve, and the edge width, in m/z values. Correlation between the left, right, and full curve, and the measured transmission efficiency curve is also calculated. After fitting is done, the parameter values for each scan and the correlations get saved into an excel sheet, for each midia group.
25ee0cf251943f5676c8d6c053aa10e285df8ccf
[ "Markdown", "Python" ]
4
Python
faresdibany/Data-Extraction-Processing-Visualzing-and-Curve-Fitting-Pipeline-for-Mass-Spectrometry-
48b1bb1523815ebc5ba2af057241183252bb20be
5b72652b8cd194810da403506d643e8984eed153
refs/heads/main
<file_sep># lists lists <file_sep>require 'sinatra' require 'slim' get '/' do slim :index end get '/:list' do @task = params[:list] slim :list end # # # # # # class List < ActiveRecord::Base # has_one :authorization # end # # class AccountsController < ApplicationController # def authorize # end # # all our CRUD actions # end # # class Authorization < ActiveRecord::Base # belongs_to :accountq # belongs_to :user # endqq # end # # class List < ActiveRecord::Base # end # # # # # # List (id, name, body) # authorizations (id, account_id, user_id, created_on) # # # class AccountsController < ApplicationController # end # class UsersController < ApplicationController # end # # class ListsController < ApplicationController # # def new # @list = List.find params[:id] # end # # def create # @list = List.find params[:id] # if @list.update_attributes params[:list] # redirect_to :controller => 'lists', :action => :show, :id => @list.id # else # render :action => :new # end # end # # end # # class ListController < ApplicationController # # def new # end # # def create # end # # end
13d9f190a021786653303d46ae4d21e4830db067
[ "Markdown", "Ruby" ]
2
Markdown
daamnathaniel/lists
6b148062beb7917f95c669af9e8008e51ad1c831
6c9daf113097c17710ce0ef4c49bb9aa76650713
refs/heads/master
<repo_name>sakshityagi/mediaCenterMigrator<file_sep>/app.js "use strict"; var mediaData = require("./oldData"); var MediaCenterMigrator = require("./converterScript"); var express = require('express'); var app = express(); app.get('/', function (req, res) { MediaCenterMigrator.convert(mediaData, function (list) { res.send(list); }); }); var server = app.listen(3000, function () { var host = server.address().address; var port = server.address().port; console.log('Converter app listening at http://%s:%s', host, port); }); <file_sep>/oldData.js exports = module.exports = { "Id": 19877700, "Content": { "Sections": [ { "Id": 19877810, "Summary": "Can be video or audio", "RssUrl": "http://api.kaleoapps.com/designer/appContent/19862305/RssFeed.xml/19877810", "EventSource": "manual", "ImageUrl": "icon-sound", "Title": "Manual", "Items": [ { "Id": 19875743, "Title": null, "ListImageUrl": "https://s3.amazonaws.com/kaleo.live/mobile/19846880/b37c8642-e832-4a01-89b9-c57adfb408e9.png", "Body": null, "Summary": null, "ImageUrl": null, "ArticleUrl": null, "VideoUrl": null, "AudioUrl": null, "AudioThumbnail": null, "SortOrder": 0 } ], "SortOrder": 0 }, { "Id": 20172807, "Summary": null, "RssUrl": "https://gdata.youtube.com/feeds/base/users/Vsauce/uploads", "EventSource": "feed", "ImageUrl": "icon-play2", "Title": "YouTube", "Items": [], "SortOrder": 1 }, { "Id": 20172809, "Summary": "Summary", "RssUrl": "https://vimeo.com/example/videos/rss", "EventSource": "feed", "ImageUrl": "icon-image", "Title": "Vimeo", "Items": [], "SortOrder": 2 } ], "Layout": null }, "Info": { "Name": "Media Center", "Type": "Rss", "Icon": "icon-music", "IconType": "None", "SubTitle": null, "ShowOnHomePage": true, "SocialEnabled": false, "SortOrder": 0, "InstanceId": "5d4cb954-424f-40d2-8214-d97551e86b58", "IsParentWidget": false } }; <file_sep>/README.md # mediaCenterMigrator Script to migrate BuildFire existing media center data to the new plugins data ### How to run * node app * Go to browser and you will get your data on `http://localhost:3000/`
91a7b3cb5f559123316e13580e2fefea08eb805c
[ "JavaScript", "Markdown" ]
3
JavaScript
sakshityagi/mediaCenterMigrator
7149975ef1f310956c5c216d53bb73900542048b
6a908269802402ae48324f5f5c38f24f007edb72
refs/heads/master
<file_sep>import { Component, OnInit, Input, OnChanges } from '@angular/core'; @Component({ selector: 'msg-in-list', templateUrl: './msg.in.list.component.html' }) export class MsgInListComponent implements OnInit { @Input() lastMsg: any; @Input() name: string; @Input() avatar: string; @Input() writes: boolean; @Input() read: boolean; @Input() isNewChat: boolean = false; msg: string; IAM: boolean = false; time: Date; constructor() { } ngOnInit() { } checkMsg() { if (this.msg.length > 75) { this.msg = this.msg.substr(0, 75) + '..'; } this.IAM = !!(this.lastMsg.go === 'out') // if (this.lastMsg.go === 'out') { // this.IAM = true; // } else { // } } ngOnChanges() { // console.log(this.lastMsg); if (this.lastMsg){ this.msg = this.lastMsg.messages[this.lastMsg.messages.length-1]; this.time = this.lastMsg.date; this.checkMsg(); } else { this.msg = 'Это новый чат с другом..'; this.isNewChat = true; } } } <file_sep>import { BrowserModule } from '@angular/platform-browser'; import { NgModule } from '@angular/core'; import { FormsModule } from '@angular/forms'; import { AppComponent } from './app.component'; import { AuthComponent } from './auth/auth.component'; import { DesktopComponent } from './desktop/desktop.component'; import { Routes, RouterModule } from '@angular/router'; import { AuthService } from './service/auth.service'; import { AuthGuard } from './service/auth.guard.service'; import { MainService } from './service/main.service'; import { MessagesComponent } from './messages/messages.component'; import { MsgComponent } from './msg/msg.component'; import { MsgInListComponent } from './msg.in.list/msg.in.list.component'; import { EditlabelComponent } from './editlabel/editlabel.component'; const appRoutes: Routes = [ { path: '', component: AuthComponent }, { path: 'desk', component: DesktopComponent, canActivate: [AuthGuard] }, { path: 'messages', component: MessagesComponent, canActivate: [AuthGuard] } ]; @NgModule({ declarations: [ AppComponent, AuthComponent, DesktopComponent, MessagesComponent, MsgComponent, MsgInListComponent, EditlabelComponent ], imports: [ BrowserModule, FormsModule, RouterModule.forRoot(appRoutes) ], providers: [MainService, AuthService, AuthGuard], bootstrap: [AppComponent] }) export class AppModule { } <file_sep>import { Injectable } from '@angular/core'; import { MainService } from './main.service'; @Injectable() export class AuthService { constructor(private service: MainService){} public isLoggedIn = false; isAuth(){ return new Promise((resolve,reject)=>{ if (this.isLoggedIn) { resolve(this.isLoggedIn); } else { if (this.service.firstPageIsAuth && this.logIn()) { setTimeout(()=>{ resolve(this.isLoggedIn); }, 1500); } else { resolve(false); } } }); } logIn(){ this.isLoggedIn = true; return true; } logOut(){ this.isLoggedIn = false; } }<file_sep>import { Component, OnInit, Input, ViewChild, EventEmitter, Output } from '@angular/core'; import { NgModel } from '@angular/forms'; @Component({ selector: 'editlabel', templateUrl: './editlabel.component.html' }) export class EditlabelComponent implements OnInit { @Input() value: string; @Input() name: string; @Output() onSave = new EventEmitter(); disabled: boolean = true; constructor() { } ngOnInit() { } edit(e){ this.disabled = false; setTimeout(()=>{e.select()},50); } save(e){ this.disabled = true; this.onSave.emit({ value: this.value, name: this.name }); } } <file_sep>import { Component, ViewEncapsulation } from '@angular/core'; import { Router } from '@angular/router'; import { MainService } from './service/main.service'; import { AuthService } from './service/auth.service'; @Component({ selector: 'app-root', templateUrl: './app.component.html', styleUrls: ['./main.style.less'], encapsulation: ViewEncapsulation.None }) export class AppComponent { constructor(private service: MainService, private auth: AuthService, private router: Router){} exit(): void{ this.service.firstPageIsAuth = false; this.service.viewMenu = false; this.auth.logOut(); this.router.navigate(['/']); } } <file_sep>import { Component, OnInit } from '@angular/core'; import { NgModel } from '@angular/forms'; import { Router, ActivatedRoute, Params } from '@angular/router'; import { MainService } from '../service/main.service'; import * as _ from 'underscore'; @Component({ selector: 'app-messages', templateUrl: './messages.component.html' }) export class MessagesComponent implements OnInit { flagList: boolean = true; id: number; contact: any; messageArray: any; temp: string; answerText: string; constructor(private route: ActivatedRoute, private service: MainService, private router: Router) { } ngOnInit() { this.route.queryParams.subscribe((params: Params)=>{ if (params['id']) { this.id = +params['id']; // Получаем информацию о контакте this.contact = this.service.refContacts[this.id];//this.service.getContactInfo(this.id); if (!this.contact) { // Если информацию о контакте получить не удалось this.router.navigate(['/messages']); } else { // Получили this.flagList = false; // Мы можем читать новые сообщения this.service.read = this.id; this.service.refContacts[this.id].read = true; // Обновляем количество нечитанных диалогов this.service.numNewMsg = this.service.countNewMsg(this.service.sortedList); this.service.getMessages(this.id); setTimeout(() => document.getElementById('input').focus(), 100); } } else { // ID нет -> Список сообщений this.flagList = true; // Мы не можем читать новые сообщения this.service.read = null; this.id = null; this.service.getLastMessages(); } }); } // Отправляем сообщение enter(e): void{ if (e.code.toLowerCase() === 'enter' && this.service.refContacts[this.id].newMsg) { this.service.sendMsg(this.id); } } } <file_sep>import { Component, OnInit } from '@angular/core'; import { Router } from '@angular/router'; import { MainService } from '../service/main.service'; // import { DoCheck } from '@angular/core'; @Component({ selector: 'app-desktop', templateUrl: './desktop.component.html' }) export class DesktopComponent implements OnInit { constructor(private router: Router, private service: MainService) { } ngOnInit() { setTimeout(()=>{this.service.viewLoader = false;},100); } newValue(e):void { if (e.name === 'name'){ this.service.myName = e.value; }; } } <file_sep>import { Component, OnInit, Input } from '@angular/core'; @Component({ selector: 'msg', templateUrl: './msg.component.html' }) export class MsgComponent implements OnInit { @Input() msgArray: string[]; @Input() author: string; @Input() time: Date = new Date(); @Input() avatar: string; constructor() { } ngOnInit() { } } <file_sep>import { Component, OnInit } from '@angular/core'; import { Router } from '@angular/router'; import { AuthService } from '../service/auth.service'; import { MainService } from '../service/main.service'; @Component({ selector: 'auth', templateUrl: './auth.component.html' }) export class AuthComponent implements OnInit { viewLoader = false; visibleAvatar = false; pass: string = ''; name: string = ''; alert: boolean = false; alertPass: boolean = false; alertName: boolean = false; alertBr: boolean = false; constructor(private router: Router, private auth: AuthService, private service: MainService) { } ngOnInit(): void { this.service.firstPageIsAuth = true; } logIn(): void { if (this.name === '' || this.pass === '') { this.check(); } else { this.alert = false; this.service.viewLoader = true; this.service.myName = this.name; this.router.navigate(['/desk']); setTimeout(()=>{ this.visibleAvatar = true; this.service.answerMsg(6, null, 5000, ['Эй, друг','куда пропал?)']); this.service.answerMsg(5, null, 7300, ['Привет!','У меня тут кошка рожает','Нужна срочно твоя помощь!']); }, 400); } } enter(e): void { this.alert = false; if (e.code.toLowerCase() === 'enter'){ this.logIn(); } } check(): void { this.alert = true; this.alertName = this.name === '' ? true : false; this.alertPass = this.pass === '' ? true : false; this.alertBr = this.alertName && this.alertPass; } } <file_sep>import { CanActivate, ActivatedRouteSnapshot, RouterStateSnapshot, Router } from '@angular/router'; import { Observable } from 'rxjs/Observable'; import { AuthService } from './auth.service'; import { MainService } from './main.service'; import { Injectable } from '@angular/core'; @Injectable() export class AuthGuard implements CanActivate { constructor(private auth: AuthService, private service: MainService, private router: Router){} canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot) : Observable<boolean> | Promise<boolean> | boolean { return this.auth.isAuth().then((isLoggedIn: boolean)=>{ if (isLoggedIn) { this.service.viewMenu = true; } else { console.log('Unauthorized'); this.router.navigate(['/']); } return isLoggedIn; }); } }<file_sep>import { Injectable } from '@angular/core'; import * as _ from 'underscore'; @Injectable() // Класс шагов class Stages { check: Array<number>; end: boolean; constructor(){ this[1] = this[2] = this[3] = this[4] = this[5] = this[6] = this[7] = this[8] = this.end = false; this.check = [0,0,0,0,0,0,0,0]; } } type User = { id: number, name: string, avatar: string, lastMsg: Msg | null, writes: boolean, newMsg: string, read: boolean stages?: Stages }; type Msg = { go: string, date: Date, messages: Array<string> } type LastMsg = { msg: string | null } export class MainService { viewLoader: boolean = false; viewMenu: boolean = false; myName: string = 'Basil'; myAvatar: string = 'img/logo-0.jpg'; // Флаг попал ли пользователь на страницу авторизации firstPageIsAuth: boolean; // Список с последними сообщениями listLastMessage: any = {}; // Отсортированный список контактов в зависимости от списка последних сообщений sortedList: any = []; // Количество новых сообщений numNewMsg: number = 0; // Флаг можем ли мы читать сейчас сообщения от кого-то read: number = null; listContacts: Array<User> = [ {id: 1, name: 'Виктория', avatar: 'img/logo-4.jpg', lastMsg: null, writes: false, newMsg: '', read: true}, {id: 2, name: 'Павел', avatar: 'img/logo-1.jpg', lastMsg: null, writes: false, newMsg: '', read: true}, {id: 3, name: 'Йода', avatar: 'img/logo-2.jpg', lastMsg: null, writes: false, newMsg: '', read: true}, {id: 4, name: 'Денис', avatar: 'img/logo-3.jpg', lastMsg: null, writes: false, newMsg: '', read: true}, {id: 5, name: 'Ева', avatar: 'img/logo-5.jpg', lastMsg: null, writes: false, newMsg: '', read: true}, {id: 6, name: 'Журавль', avatar: 'img/logo-6.jpg', lastMsg: null, writes: false, newMsg: '', read: true}, ]; messages: any = { '3': [ {go: 'out', date: new Date(2011, 0, 1, 2, 3, 4, 567), messages: ['Lorem ipsum dolor.']}, {go: 'in', date: new Date(2011, 0, 1, 4, 10, 4, 567), messages: ['Lorem ipsum dolor sit amet, consectetur adipisicing elit. Nihil.','Lorem ipsum.']}, {go: 'out', date: new Date(2011, 0, 1, 4, 12, 4, 567), messages: ['Lorem ipsum dolor sit amet, consectetur.','Lorem ipsum.']}, {go: 'in', date: new Date(2011, 0, 1, 17, 20, 4, 567), messages: ['Lorem ipsum dolor sit amet, consectetur adipisicing elit. Obcaecati dicta mollitia sint illo nemo at?']} ], } // Массив ссылок на аккаунты refContacts: any = this.initRefsContacts(); initRefsContacts(): any { let temp = []; this.listContacts.forEach((el)=>{ temp[el.id] = el; el.stages = new Stages; }); return temp; } // Возвращает список последних сообщений createListLastMsg(contacts: Array<User>, messeges: any): Array<LastMsg> { let temp = []; contacts.forEach((el) => { let tempMsg = messeges[el.id]; temp[el.id] = {}; temp[el.id].msg = tempMsg ? tempMsg[tempMsg.length-1] : null; }); return temp; } // Возвращает отсортированный список createSortedList(contacts: Array<User>, listLastMsg: Array<LastMsg>){ return _.sortBy(this.listContacts, (el) => { return this.listLastMessage[el.id].msg ? -this.listLastMessage[el.id].msg.date.getTime() : -1; }); } // Подсчитывает количество нечитанных диалогов countNewMsg(sortedList: Array<any>): number{ return _.reduce(sortedList, (num, item) =>{ // console.log(item.read); return item.read ? num : num + 1; }, 0); } // Получаем список последних сообщений и сортированный список getLastMessages(): void { this.listLastMessage = this.createListLastMsg(this.listContacts, this.messages); this.sortedList = this.createSortedList(this.listContacts, this.listLastMessage); this.numNewMsg = this.countNewMsg(this.sortedList); } // Получаем последнее сообщение по ID getMessages(id: number): void { this.refContacts[id].lastMsg = this.messages[id] ? this.getLastMessage(id) : null; } // Получаем ссылку на последнее сообщение getLastMessage(id: number): void { return this.getLastElement(this.messages[id]); } // Возвращает последний элемент массива getLastElement(arr: Array<any>): void { return arr[arr.length - 1]; } sendMsg(id): void { if (this.refContacts[id].lastMsg && this.refContacts[id].lastMsg.go === 'out'){ this.pushMsg(this.refContacts[id].newMsg, id); } else { this.createNewMsg(this.refContacts[id].newMsg, id, 'out'); } this.answerMsg(id, this.refContacts[id].newMsg, 1200, null); this.refContacts[id].newMsg = ''; } // (id, схематичное сообщение, задержка, заданный ответ) answerMsg(id: number, msg: string, delay: number, customAnsw: Array<string>): void { let answArray: any, period: number; if (msg) { // Если попрощались то не ответит;) if (this.refContacts[id].stages.end) return; // Массив с ответами answArray = this.respondTo(id, msg); } else { answArray = customAnsw; } // Если вообще никакого ответа нету, то выкидываем if (!answArray) return; setTimeout(() => this.writesFlag(id, true), delay); period = (delay + 4000) / answArray.length; answArray.forEach((e, ind)=>{ setTimeout(() => { if ((ind === 0 && !this.refContacts[id].lastMsg) || (ind === 0 && this.refContacts[id].lastMsg.go === 'out') || this.refContacts[id].lastMsg.go === 'out' ) { this.createNewMsg(e, id, 'in'); } else { // Сообщение его последнее, поэтому добавляем к нему this.pushMsg(e, id); } // Скидываем флаг, что кто то пишет if (ind === answArray.length - 1) { this.writesFlag(id, false); // Отмечаем прочитались ли сообщения this.refContacts[id].read = this.read === id ? true : false; this.getLastMessages(); } }, period*(ind + 1)); }); } // Меняем флаг написания сообщения для ID writesFlag(id: number, flag: boolean): void { this.refContacts[id].writes = flag; } // Создаем новое сообщение createNewMsg(msg: string, id: number, go: string): void { this.checkLastMsg(id); this.messages[id].push({ go, messages: [msg], date: new Date() }); this.refContacts[id].lastMsg = this.getLastMessage(id); } // Добавляем в последнее сообщение pushMsg(msg: string, id: number): void { this.refContacts[id].lastMsg.messages.push(msg); } // Проверяем есть ли последнее сообщение checkLastMsg(id: number): void { if (!this.refContacts[id].lastMsg) { this.messages[id] = []; } } respondTo(id, input): string[] { let answer: string[] = []; input = input.toLowerCase(); if (this.match('(привет|здравствуй|приветствую|здрасте|здарова|хай|hi|прива|прив|здоров)(\\s|!|\\.|$)', input)) answer.push(this.testAnswer(id, 1, this.getRandomInt(1, 5))); if(this.match('как дела', input) || this.match('как жизнь', input) || this.match('как поживаешь', input) || this.match('как ты', input)) answer.push(this.testAnswer(id, 2, this.getRandomInt(1, 6))); if (this.match('(хорошо|отлично|прекрасно|здоровски)(\\s|!|\\.|$)', input)) answer.push(this.testAnswer(id, 3, this.getRandomInt(1, 3))); if(this.match('молоко', input)) answer.push(this.testAnswer(id, 4, 1)); if(this.match('ха', input) || this.match('хи', input) || this.match('лол', input) || this.match('смешной', input)) answer.push(this.testAnswer(id, 5, this.getRandomInt(1, 4))); if(this.match('нет', input)) answer.push(this.testAnswer(id, 6, 1)); if(this.match('бот', input)) answer.push(this.testAnswer(id, 7, this.getRandomInt(1, 2))); if (this.match('(пока|досвид|прощай|покеда|bye)(\\s|!|\\.|$)', input)) answer.push(this.testAnswer(id, 8, this.getRandomInt(1, 6))); if (!answer.length) {answer.push(this.testAnswer(id, 9, this.getRandomInt(1, 3)));} return answer; } match(regex, input): any { return new RegExp(regex).test(input); } getRandomInt(min, max): number { return Math.floor(Math.random() * (max - min)) + min; } answers = { new: { 1: { 1: 'Привет)', 2: 'Привет!', 3: 'Хаюшки))', 4: 'Ооо, давно не списывались, ну привет))', 5: 'приветствую, друг!' }, 2: { 1: 'у меня отличн, устаю только немного) а ты как?', 2: 'у меня молоко убежало:\'(', 3: 'да я только и делаю что жду тебя;)', 4: 'да хорошо, такая радость что списались спустя долгое время', 5: 'нормик, только что молоко на кухне было спасен:)', 6: 'Живу жизнь нелегкую. Как ты?' }, 3: { 1: 'славно)', 2: 'душа радуется за тебя)', 3: 'прекрасно))', }, 4: { 1: 'Ну у меня чуть молоко не убежало, а моих сил хватило, чтобы с ним совладать' }, 5: { 1: 'чего смешного?)', 2: 'чего это тебя развеселило?', 3: 'чтооо?))', 4: 'и что было сказано такого смешного, а?' }, 6: { 1: 'Никак нет!' }, 7: { 1: 'бот? кто бот? я не бот!', 2: 'о каком боте идет речь?' }, 8: { 1: 'Ну пока)', 2: 'Окей, тоже побегу', 3: 'пока пока;)', 4: 'до связи!', 5: 'До скорого!', 6: 'всего хорошего)' }, 9: { 1: 'не понятно как то увы))', 2: 'что??', 3: 'и к чему это?)' } }, yet: { 1: { 1: 'уже ведь поздоровались)', 2: 'не путайся, здоровались ведь!', 3: 'мб хочешь наоборот попращаться?))', 4: 'как ты мог забыть а? мы ведь здоровались', 5: 'и еще раз привет)) ага)' }, 2: { 1: 'узнавал бедняга.', 2: 'ну давай еще раз поспрашивает как мы))', 3: 'да и я конечно тоже за пару минут забыл как у тебя дела;)', 4: 'пропить таблетки для памяти?', 5: 'повторюсь, еще в мире живых!)', 6: 'эх, друг мой друг' }, 3: { 1: 'славно)', 2: 'душа радуется за тебя)', 3: 'прекрасно))', }, 4: { 1: 'Да все хорошо с этим молоком, опять ты меня не слушаешь!' }, 5: { 1: 'ну хватит хихикать тут!', 2: 'я так обижусь!', 3: 'перестань ржать там', 4: 'ну все, больше ни слова от меня' }, 6: { 1: 'а вот и ДА!' }, 7: { 1: 'не буду больше про бота говорить)', 2: 'Так чтобы я больше не слышал слова \'бот\'!' }, 9: { 1: 'не понятно как то увы))', 2: 'что??', 3: 'и к чему это?)' } } } testAnswer(id, stage, number): string { if (this.refContacts[id].stages[stage] && !this.refContacts[id].stages.end){ if (this.refContacts[id].stages.check[stage-1] === 0) { this.refContacts[id].stages.check[stage-1]++; return this.answers.yet[stage][number]; } else { return 'куриные мозги?;)'; } } else { this.refContacts[id].stages[stage] = true; if (stage === 8) this.refContacts[id].stages.end = true; return this.answers.new[stage][number]; } } }
1fc0cf1282d057735ba2c5b20646cf8a153d545a
[ "TypeScript" ]
11
TypeScript
MozgoK/testRep
fcd7d6d3a527c87307905c689da5088aef2a0ae7
67114870e48b0d4c2392d8bcf34abca4fe7ea6e5
refs/heads/master
<file_sep>/* Copyright 2019 The TensorFlow Authors. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ==============================================================================*/ namespace tf.graph.loader { Polymer({ is: 'tf-graph-loader', _template: null, // strictTemplatePolicy requires a template (even a null one). properties: { /** * @type {Array<{name: string, path: string}>} */ datasets: Array, selectedData: { type: Number, value: 0, }, selectedFile: Object, compatibilityProvider: { type: Object, value: () => new tf.graph.op.TpuCompatibilityProvider(), }, /** * If this optional object is provided, graph logic will override * the HierarchyParams it uses to build the graph with properties within * this object. For possible properties that this object can have, please * see documentation on the HierarchyParams TypeScript interface. * @type {Object} */ overridingHierarchyParams: { type: Object, value: () => ({}), }, /** * @type {{value: number, msg: string}} * * A number between 0 and 100 denoting the % of progress * for the progress bar and the displayed message. */ progress: { type: Object, notify: true, }, outGraphHierarchy: { type: Object, readOnly: true, //readonly so outsider can't change this via binding notify: true, }, outGraph: { type: Object, readOnly: true, //readonly so outsider can't change this via binding notify: true, }, outHierarchyParams: { type: Object, readOnly: true, notify: true, }, }, observers: [ '_loadData(datasets, selectedData, overridingHierarchyParams, compatibilityProvider)', '_loadFile(selectedFile, overridingHierarchyParams, compatibilityProvider)', ], _loadData(): void { // Input can change a lot within a microtask. // Don't fetch too much too fast and introduce race condition. this.debounce('load', () => { const dataset = this.datasets[this.selectedData]; if (!dataset) return; this._parseAndConstructHierarchicalGraph(dataset.path); }); }, _parseAndConstructHierarchicalGraph( path: string | null, pbTxtFile?: Blob ): void { const {overridingHierarchyParams, compatibilityProvider} = this; // Reset the progress bar to 0. this.progress = {value: 0, msg: ''}; const tracker = tf.graph.util.getTracker(this); const hierarchyParams = Object.assign( {}, tf.graph.hierarchy.DefaultHierarchyParams, overridingHierarchyParams ); tf.graph.loader .fetchAndConstructHierarchicalGraph( tracker, path, pbTxtFile, compatibilityProvider, hierarchyParams ) .then(({graph, graphHierarchy}) => { this._setOutHierarchyParams(hierarchyParams); this._setOutGraph(graph); this._setOutGraphHierarchy(graphHierarchy); }); }, _loadFile(e: Event | null): void { if (!e) { return; } const target = e.target as HTMLInputElement; const file = target.files[0]; if (!file) { return; } // Clear out the value of the file chooser. This ensures that if the user // selects the same file, we'll re-read it. target.value = ''; this._parseAndConstructHierarchicalGraph(null, file); }, }); } // namespace tf.graph.loader <file_sep>/* Copyright 2015 The TensorFlow Authors. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ==============================================================================*/ namespace tf_dashboard_common { type CacheKey = string; // NOT_LOADED is implicit enum LoadState { LOADING, LOADED, } /** * @polymerBehavior */ export const DataLoaderBehavior = { properties: { active: { type: Boolean, observer: '_loadDataIfActive', }, /** * A unique identifiable string. When changes, it expunges the data * cache. */ loadKey: { type: String, value: '', }, // List of data to be loaded. By default, a datum is passed to // `requestData` to fetch data. When the request resolves, invokes // `loadDataCallback` with the datum and its response. dataToLoad: { type: Array, value: () => [], }, /** * A function that takes a datum as an input and returns a unique * identifiable string. Used for caching purposes. */ getDataLoadName: { type: Function, value: () => (datum): CacheKey => String(datum), }, /** * A function that takes as inputs: * 1. Implementing component of data-loader-behavior. * 2. datum of the request. * 3. The response received from the data URL. * This function will be called when a response from a request to that * data URL is successfully received. */ loadDataCallback: Function, // A function that takes a datum as argument and makes the HTTP // request to fetch the data associated with the datum. It should return // a promise that either fullfills with the data or rejects with an error. // If the function doesn't bind 'this', then it will reference the element // that includes this behavior. // The default implementation calls this.requestManager.request with // the value returned by this.getDataLoadUrl(datum) (see below). // The only place getDataLoadUrl() is called is in the default // implementation of this method. So if you override this method with // an implementation that doesn't call getDataLoadUrl, it need not be // provided. requestData: { type: Function, value: function() { return (datum) => this.requestManager.request(this.getDataLoadUrl(datum)); }, }, // A function that takes a datum and returns a string URL for fetching // data. getDataLoadUrl: Function, dataLoading: { type: Boolean, readOnly: true, reflectToAttribute: true, value: false, }, /* * A map of a cache key to LoadState. If a cacheKey does not exist in the * map, it is considered NOT_LOADED. * Invoking `reload` or a change in `loadKey` clears the cache. */ _dataLoadState: { type: Object, value: () => new Map<CacheKey, LoadState>(), }, _canceller: { type: Object, value: () => new tf_backend.Canceller(), }, _loadDataAsync: { type: Number, value: null, }, }, observers: ['_dataToLoadChanged(isAttached, dataToLoad.*)'], onLoadFinish() { // Override to do something useful. }, reload() { this._dataLoadState.clear(); this._loadData(); }, reset() { // https://github.com/tensorflow/tensorboard/issues/1499 // Cannot use the observer to observe `loadKey` changes directly. if (this._loadDataAsync != null) { this.cancelAsync(this._loadDataAsync); this._loadDataAsync = null; } if (this._canceller) this._canceller.cancelAll(); if (this._dataLoadState) this._dataLoadState.clear(); if (this.isAttached) this._loadData(); }, _dataToLoadChanged() { if (this.isAttached) this._loadData(); }, created() { this._loadData = _.throttle(this._loadDataImpl, 100, { leading: true, trailing: true, }); }, detached() { // Note: Cannot call canceller.cancelAll since it will poison the cache. // detached gets called when a component gets unmounted from the document // but it can be re-mounted. When remounted, poisoned cache will manifest. // t=0: dataLoadState: 'a' = loading // t=10: unmount // t=20: request for 'a' resolves but we do not change the loadState // because we do not want to set one if, instead, it was resetted at t=10. if (this._loadDataAsync != null) { this.cancelAsync(this._loadDataAsync); this._loadDataAsync = null; } }, _loadDataIfActive() { if (this.active) { this._loadData(); } }, _loadDataImpl() { if (!this.active) return; this.cancelAsync(this._loadDataAsync); this._loadDataAsync = this.async( this._canceller.cancellable((result) => { if (result.cancelled) { return; } // Read-only property have a special setter. this._setDataLoading(true); // Promises return cacheKeys of the data that were fetched. const promises = this.dataToLoad .filter((datum) => { const cacheKey = this.getDataLoadName(datum); return !this._dataLoadState.has(cacheKey); }) .map((datum) => { const cacheKey = this.getDataLoadName(datum); this._dataLoadState.set(cacheKey, LoadState.LOADING); return this.requestData(datum).then( this._canceller.cancellable((result) => { // It was resetted. Do not notify of the response. if (!result.cancelled) { this._dataLoadState.set(cacheKey, LoadState.LOADED); this.loadDataCallback(this, datum, result.value); } return cacheKey; }) ); }); return Promise.all(promises) .then( this._canceller.cancellable((result) => { // It was resetted. Do not notify of the data load. if (!result.cancelled) { const keysFetched = result.value; const fetched = new Set(keysFetched); const shouldNotify = this.dataToLoad.some((datum) => fetched.has(this.getDataLoadName(datum)) ); if (shouldNotify) { this.onLoadFinish(); } } const isDataFetchPending = Array.from( this._dataLoadState.values() ).some((loadState) => loadState === LoadState.LOADING); if (!isDataFetchPending) { // Read-only property have a special setter. this._setDataLoading(false); } }), // TODO(stephanwlee): remove me when we can use Promise.prototype.finally // instead () => {} ) .then( this._canceller.cancellable(({cancelled}) => { if (cancelled) { return; } this._loadDataAsync = null; }) ); }) ); }, }; } // namespace tf_dashboard_common <file_sep>/* Copyright 2020 The TensorFlow Authors. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ==============================================================================*/ /** * Implements core plugin APIs. */ tb_plugin.host.listen('experimental.GetURLPluginData', (context) => { if (!context) { return; } const prefix = `p.${context.pluginName}.`; const result: {[key: string]: string} = {}; for (let key in tf_storage.urlDict) { if (key.startsWith(prefix)) { const pluginKey = key.substring(prefix.length); result[pluginKey] = tf_storage.urlDict[key]; } } return result; }); <file_sep>/* Copyright 2019 The TensorFlow Authors. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ==============================================================================*/ import {Component, OnInit, OnDestroy} from '@angular/core'; import { FormControl, Validators, AbstractControl, ValidatorFn, } from '@angular/forms'; import {Store, select, createSelector} from '@ngrx/store'; import {Subject} from 'rxjs'; import {takeUntil, debounceTime, filter} from 'rxjs/operators'; import { getReloadEnabled, getReloadPeriodInMs, State, getPageSize, } from '../core/store'; import { toggleReloadEnabled, changeReloadPeriod, changePageSize, } from '../core/actions'; /** @typehack */ import * as _typeHackRxjs from 'rxjs'; const getReloadPeriodInSec = createSelector( getReloadPeriodInMs, (periodInMs) => Math.round(periodInMs / 1000) ); export function createIntegerValidator(): ValidatorFn { return (control: AbstractControl): {[key: string]: any} | null => { const numValue = Number(control.value); const valid = Math.round(numValue) === control.value; return valid ? null : {integer: {value: control.value}}; }; } @Component({ selector: 'settings-dialog', template: ` <h3>Settings</h3> <div> <div class="reload-toggle"> <mat-checkbox [checked]="reloadEnabled$ | async" (change)="onReloadToggle()" >Reload data</mat-checkbox > </div> <div> <mat-form-field> <input class="reload-period" matInput type="number" placeholder="Reload Period" [formControl]="reloadPeriodControl" /> </mat-form-field> <mat-error *ngIf=" reloadPeriodControl.hasError('min') || reloadPeriodControl.hasError('required') " > Reload period has to be minimum of 15 seconds. </mat-error> </div> </div> <div> <mat-form-field> <input class="page-size" matInput type="number" placeholder="Pagination Limit" [formControl]="paginationControl" /> </mat-form-field> <mat-error *ngIf="paginationControl.invalid"> Page size has to be a positive integer. </mat-error> </div> `, styleUrls: ['./dialog_component.css'], }) export class SettingsDialogComponent implements OnInit, OnDestroy { readonly reloadEnabled$ = this.store.pipe(select(getReloadEnabled)); readonly pageSize$ = this.store.pipe(select(getPageSize)); private readonly reloadPeriodInSec$ = this.store.pipe( select(getReloadPeriodInSec) ); readonly reloadPeriodControl = new FormControl(15, [ Validators.required, Validators.min(15), ]); readonly paginationControl = new FormControl(1, [ Validators.required, Validators.min(1), createIntegerValidator(), ]); private ngUnsubscribe = new Subject(); constructor(private store: Store<State>) {} ngOnInit() { this.reloadPeriodInSec$ .pipe( takeUntil(this.ngUnsubscribe), filter((value) => value !== this.reloadPeriodControl.value) ) .subscribe((value) => { this.reloadPeriodControl.setValue(value); }); this.reloadEnabled$ .pipe(takeUntil(this.ngUnsubscribe)) .subscribe((value) => { if (value) this.reloadPeriodControl.enable(); else this.reloadPeriodControl.disable(); }); this.reloadPeriodControl.valueChanges .pipe( takeUntil(this.ngUnsubscribe), debounceTime(500), filter(() => this.reloadPeriodControl.valid) ) .subscribe(() => { if (!this.reloadPeriodControl.valid) { return; } const periodInMs = this.reloadPeriodControl.value * 1000; this.store.dispatch(changeReloadPeriod({periodInMs})); }); this.pageSize$ .pipe( takeUntil(this.ngUnsubscribe), filter((value) => value !== this.paginationControl.value) ) .subscribe((value) => { this.paginationControl.setValue(value); }); this.paginationControl.valueChanges .pipe( takeUntil(this.ngUnsubscribe), debounceTime(500), filter(() => this.paginationControl.valid) ) .subscribe(() => { this.store.dispatch( changePageSize({size: this.paginationControl.value}) ); }); } ngOnDestroy() { this.ngUnsubscribe.next(); this.ngUnsubscribe.complete(); } onReloadToggle(): void { this.store.dispatch(toggleReloadEnabled()); } } <file_sep>/* Copyright 2020 The TensorFlow Authors. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ==============================================================================*/ /** * Utility functions for the NgRx store of Debugger V2. */ import {SourceFileSpec} from './debugger_types'; /** * Find the index of a file spec among an array of file specs. * @param fileList * @param fileSpec * @returns The index of `fileSpec` in `fileList`. If not found, `-1`. */ export function findFileIndex( fileList: SourceFileSpec[], fileSpec: SourceFileSpec ): number { return fileList.findIndex( (item: SourceFileSpec) => item.host_name === fileSpec.host_name && item.file_path === fileSpec.file_path ); } <file_sep>/* Copyright 2019 The TensorFlow Authors. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ==============================================================================*/ /** The MIT License (MIT) Copyright (c) 2014-2017 <NAME>, Inc. Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ /** * Reason for the fork: Plottable interactions are not compatible with the Web * Componenets due to the changes in: * 1. how events work: i.e., parent components cannot introspect into DOM * where an event originates from. Instead, they see originating * WebComponents. * 2. DOM traversal: parentElement on shadowRoot is null. * Please refer to https://github.com/palantir/plottable/issues/3350 for more * detail. * * To override few quick private/protected methods, we had to use JavaScript to * bypass TypeScript typechecks. */ var vz_chart_helpers; (function(vz_chart_helpers) { // HACK: parentElement does not work for webcomponents. function getHtmlElementAncestors(elem) { const elems = []; while (elem && elem instanceof HTMLElement) { elems.push(elem); if (elem.assignedSlot) { elem = elem.assignedSlot; } else if (!elem.parentElement) { const parentNode = elem.parentNode; if (parentNode instanceof DocumentFragment) { elem = parentNode.host; } else { // <html>.parentNode == <html> elem = parentNode !== elem ? parentNode : null; } } else { elem = elem.parentElement; } } return elems; } const _IDENTITY_TRANSFORM = [1, 0, 0, 1, 0, 0]; // Forked from https://github.com/palantir/plottable/blob/b6e36fbd4d8d7cba579d853b9f35cc260d1243bf/src/utils/mathUtils.ts#L173-L202 // The only difference is the implementation of the getHtmlElementAncestors. function getCumulativeTransform(element) { const elems = getHtmlElementAncestors(element); let transform = _IDENTITY_TRANSFORM; let offsetParent = null; for (const elem of elems) { // apply css transform from any ancestor element const elementTransform = Plottable.Utils.DOM.getElementTransform(elem); if (elementTransform != null) { const midX = elem.clientWidth / 2; const midY = elem.clientHeight / 2; transform = Plottable.Utils.Math.multiplyTranslate(transform, [ midX, midY, ]); transform = Plottable.Utils.Math.multiplyMatrix( transform, Plottable.Utils.Math.invertMatrix(elementTransform) ); transform = Plottable.Utils.Math.multiplyTranslate(transform, [ -midX, -midY, ]); } // apply scroll offsets from any ancestor element let offsetX = elem.scrollLeft; let offsetY = elem.scrollTop; // apply client+offset from only acenstor "offsetParent" if (offsetParent === null || elem === offsetParent) { offsetX -= elem.offsetLeft + elem.clientLeft; offsetY -= elem.offsetTop + elem.clientTop; offsetParent = elem.offsetParent; } transform = Plottable.Utils.Math.multiplyTranslate(transform, [ offsetX, offsetY, ]); } return transform; } class CustomTranslator extends Plottable.Utils.Translator { computePosition(clientX, clientY) { const clientPosition = { x: clientX, y: clientY, }; const transform = getCumulativeTransform(this._rootElement); if (transform == null) { return clientPosition; } const transformed = Plottable.Utils.Math.applyTransform( transform, clientPosition ); return transformed; } } class MouseDispatcher extends Plottable.Dispatchers.Mouse { constructor(component) { super(component); // eventTarget is `document` by default. Change it to the root of chart. this._eventTarget = component .root() .rootElement() .node(); // Requires custom translator that uses correct DOM traversal (with // WebComponents) to change pointer position to relative to the root node. this._translator = new CustomTranslator( component .root() .rootElement() .node() ); } static getDispatcher(component) { const element = component.root().rootElement(); let dispatcher = element[MouseDispatcher._DISPATCHER_KEY]; if (!dispatcher) { dispatcher = new MouseDispatcher(component); element[MouseDispatcher._DISPATCHER_KEY] = dispatcher; } return dispatcher; } } class TouchDispatcher extends Plottable.Dispatchers.Touch { constructor(component) { super(component); // eventTarget is `document` by default. Change it to the root of chart. this._eventTarget = component .root() .rootElement() .node(); // Requires custom translator that uses correct DOM traversal (with // WebComponents) to change pointer position to relative to the root node. this._translator = new CustomTranslator( component .root() .rootElement() .node() ); } static getDispatcher(component) { const element = component.root().rootElement(); let dispatcher = element[TouchDispatcher._DISPATCHER_KEY]; if (!dispatcher) { dispatcher = new TouchDispatcher(component); element[TouchDispatcher._DISPATCHER_KEY] = dispatcher; } return dispatcher; } } /** * Fixes #3282. * * Repro: when tooltip is shown, slowly move the mouse to an edge of a chart. * We expect the tooltip the disappear when the cursor is on the edge of the * chart. * * Cause: * 1. For Polymer 2 and its Shadow DOM compatibility, TensorBoard opted out of * the event delegation of Plottable. Plottable, by default, attaches a set of * event listeners on document.body and invokes appropriate callbacks * depending on the circumstances. However, with the Shadow DOM, the event * re-targetting broke (harder to identify `event.target`), so TensorBoard, * instead, attaches the event listeners on every Plottable container, SVGs. * * 2. When mouse leaves (mouseout) the container, Plottable remaps the event * as mouse move and calculate whether the cursor is inside a component * (Interaction.prototype._isInsideComponent, specifically) to trigger * appropriate callback. The method, however is flawed since it returns, for a * component that is, for instance, at <0, 0> with size of <100, 100>, true * when pointer is at <100, 100>. It should only return true for [0, 100) for * a given dimension, instead. As a result, the mouseout event occurred at * <100, 100> was treated as an event inside the component but all the * subsequent mouse movements are not captured since they are events that * occurred outside of the event target. In vanilla Plottable, this bug do not * manifest since event delegation on the entire document will eventually * trigger mouse out when cursor is at, for instance, <101, 100>. */ Plottable.Interaction.prototype._isInsideComponent = function(p) { return ( 0 <= p.x && 0 <= p.y && // Delta: `<` instead of `<=` here and below. p.x < this._componentAttachedTo.width() && p.y < this._componentAttachedTo.height() ); }; class PointerInteraction extends Plottable.Interactions.Pointer { _anchor(component) { this._isAnchored = true; this._mouseDispatcher = MouseDispatcher.getDispatcher( this._componentAttachedTo ); this._mouseDispatcher.onMouseMove(this._mouseMoveCallback); this._touchDispatcher = TouchDispatcher.getDispatcher( this._componentAttachedTo ); this._touchDispatcher.onTouchStart(this._touchStartCallback); } } // export only PointerInteraction. vz_chart_helpers.PointerInteraction = PointerInteraction; })(vz_chart_helpers || (vz_chart_helpers = {})); <file_sep>/* Copyright 2019 The TensorFlow Authors. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ==============================================================================*/ import {TestBed} from '@angular/core/testing'; import {By} from '@angular/platform-browser'; import {Store} from '@ngrx/store'; import {provideMockStore, MockStore} from '@ngrx/store/testing'; import {PluginsContainer} from './plugins_container'; import {PluginsComponent} from './plugins_component'; import {PluginId, LoadingMechanismType} from '../types/api'; import {DataLoadState} from '../types/data'; import {createState, createCoreState} from '../core/testing'; import {State} from '../core/store'; // store/index.ts doesn't export this, but it's OK to use for testing import {CoreState} from '../core/store/core_types'; import {TestingDebuggerModule} from '../../plugins/debugger_v2/tf_debugger_v2_plugin/testing'; /** @typehack */ import * as _typeHackStore from '@ngrx/store'; import {PluginRegistryModule} from './plugin_registry_module'; import {ExtraDashboardComponent, ExtraDashboardModule} from './testing'; function expectPluginIframe(element: HTMLElement, name: string) { expect(element.tagName).toBe('IFRAME'); expect((element as HTMLIFrameElement).src).toContain( `data/plugin_entry.html?name=${name}` ); } describe('plugins_component', () => { let store: MockStore<State>; const INITIAL_CORE_STATE: Partial<CoreState> = { plugins: { bar: { disable_reload: false, enabled: true, loading_mechanism: { type: LoadingMechanismType.CUSTOM_ELEMENT, element_name: 'tb-bar', }, tab_name: 'Bar', remove_dom: false, }, 'extra-plugin': { disable_reload: false, enabled: true, loading_mechanism: { type: LoadingMechanismType.NG_COMPONENT, }, tab_name: 'Extra', remove_dom: false, }, foo: { disable_reload: false, enabled: true, loading_mechanism: { type: LoadingMechanismType.IFRAME, // This will cause 404 as test bundles do not serve // data file in the karma server. module_path: 'random_esmodule.js', }, tab_name: 'Bar', remove_dom: false, }, }, }; beforeEach(async () => { const initialState = createState( createCoreState({ ...INITIAL_CORE_STATE, }) ); await TestBed.configureTestingModule({ providers: [ provideMockStore({initialState}), PluginsContainer, PluginRegistryModule, ], declarations: [PluginsContainer, PluginsComponent], imports: [TestingDebuggerModule, ExtraDashboardModule], }).compileComponents(); store = TestBed.get(Store); }); describe('plugin DOM creation', () => { function setActivePlugin(plugin: PluginId) { store.setState( createState( createCoreState({ ...INITIAL_CORE_STATE, activePlugin: plugin, }) ) ); } it('creates no plugin when there is no activePlugin', () => { const fixture = TestBed.createComponent(PluginsContainer); const el = fixture.debugElement.query(By.css('.plugins')); expect(el.nativeElement.childElementCount).toBe(0); }); it('creates an element for CUSTOM_ELEMENT type of plugin', async () => { const fixture = TestBed.createComponent(PluginsContainer); fixture.detectChanges(); setActivePlugin('bar'); fixture.detectChanges(); await fixture.whenStable(); const {nativeElement} = fixture.debugElement.query(By.css('.plugins')); expect(nativeElement.childElementCount).toBe(1); const pluginElement = nativeElement.children[0]; expect(pluginElement.tagName).toBe('TB-BAR'); }); it('creates an element for IFRAME type of plugin', async () => { const fixture = TestBed.createComponent(PluginsContainer); fixture.detectChanges(); setActivePlugin('foo'); fixture.detectChanges(); await fixture.whenStable(); const {nativeElement} = fixture.debugElement.query(By.css('.plugins')); expect(nativeElement.childElementCount).toBe(1); const pluginElement = nativeElement.children[0]; expectPluginIframe(pluginElement, 'foo'); }); it('keeps instance of plugin after being inactive but hides it', async () => { const fixture = TestBed.createComponent(PluginsContainer); fixture.detectChanges(); setActivePlugin('foo'); fixture.detectChanges(); await fixture.whenStable(); expect( fixture.debugElement.query(By.css('.plugins')).nativeElement .childElementCount ).toBe(1); setActivePlugin('bar'); fixture.detectChanges(); await fixture.whenStable(); const {nativeElement} = fixture.debugElement.query(By.css('.plugins')); expect(nativeElement.childElementCount).toBe(2); const [fooElement, barElement] = nativeElement.children; expectPluginIframe(fooElement, 'foo'); expect(fooElement.style.display).toBe('none'); expect(barElement.tagName).toBe('TB-BAR'); expect(barElement.style.display).not.toBe('none'); }); it('does not create same instance of plugin', async () => { const fixture = TestBed.createComponent(PluginsContainer); fixture.detectChanges(); setActivePlugin('foo'); fixture.detectChanges(); await fixture.whenStable(); setActivePlugin('bar'); fixture.detectChanges(); await fixture.whenStable(); setActivePlugin('foo'); fixture.detectChanges(); await fixture.whenStable(); const {nativeElement} = fixture.debugElement.query(By.css('.plugins')); expect(nativeElement.childElementCount).toBe(2); const [fooElement, barElement] = nativeElement.children; expectPluginIframe(fooElement, 'foo'); expect(fooElement.style.display).not.toBe('none'); }); it('creates components for plugins registered dynamically', async () => { const fixture = TestBed.createComponent(PluginsContainer); fixture.detectChanges(); setActivePlugin('extra-plugin'); fixture.detectChanges(); await fixture.whenStable(); const {nativeElement} = fixture.debugElement.query(By.css('.plugins')); expect(nativeElement.childElementCount).toBe(1); const pluginElement = nativeElement.children[0]; expect(pluginElement.tagName).toBe('EXTRA-DASHBOARD'); }); }); describe('updates', () => { function setLastLoadedTime( timeInMs: number | null, state = DataLoadState.LOADED ) { store.setState( createState( createCoreState({ ...INITIAL_CORE_STATE, activePlugin: 'bar', pluginsListLoaded: { state, lastLoadedTimeInMs: timeInMs, }, }) ) ); } it('invokes reload method on the dashboard DOM', () => { const fixture = TestBed.createComponent(PluginsContainer); setLastLoadedTime(null, DataLoadState.NOT_LOADED); fixture.detectChanges(); const {nativeElement} = fixture.debugElement.query(By.css('.plugins')); const [barElement] = nativeElement.children; const reloadSpy = jasmine.createSpy(); barElement.reload = reloadSpy; setLastLoadedTime(1); fixture.detectChanges(); expect(reloadSpy).toHaveBeenCalledTimes(1); setLastLoadedTime(1); fixture.detectChanges(); expect(reloadSpy).toHaveBeenCalledTimes(1); setLastLoadedTime(2); fixture.detectChanges(); expect(reloadSpy).toHaveBeenCalledTimes(2); }); }); }); <file_sep># Copyright 2019 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================== # Lint as: python3 """Tests for tensorboard.uploader.auth.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function import json import os import google.auth.credentials import google.oauth2.credentials from tensorboard.uploader import auth from tensorboard import test as tb_test class CredentialsStoreTest(tb_test.TestCase): def test_no_config_dir(self): store = auth.CredentialsStore(user_config_directory=None) self.assertIsNone(store.read_credentials()) creds = google.oauth2.credentials.Credentials(token=None) store.write_credentials(creds) store.clear() def test_clear_existent_file(self): root = self.get_temp_dir() path = os.path.join( root, "tensorboard", "credentials", "uploader-creds.json" ) os.makedirs(os.path.dirname(path)) open(path, mode="w").close() self.assertTrue(os.path.exists(path)) auth.CredentialsStore(user_config_directory=root).clear() self.assertFalse(os.path.exists(path)) def test_clear_nonexistent_file(self): root = self.get_temp_dir() path = os.path.join( root, "tensorboard", "credentials", "uploader-creds.json" ) self.assertFalse(os.path.exists(path)) auth.CredentialsStore(user_config_directory=root).clear() self.assertFalse(os.path.exists(path)) def test_write_wrong_type(self): creds = google.auth.credentials.AnonymousCredentials() with self.assertRaisesRegex(TypeError, "google.auth.credentials"): auth.CredentialsStore(user_config_directory=None).write_credentials( creds ) def test_write_creates_private_file(self): root = self.get_temp_dir() auth.CredentialsStore(user_config_directory=root).write_credentials( google.oauth2.credentials.Credentials( token=None, refresh_token="<PASSWORD>" ) ) path = os.path.join( root, "tensorboard", "credentials", "uploader-creds.json" ) self.assertTrue(os.path.exists(path)) # Skip permissions check on Windows. if os.name != "nt": self.assertEqual(0o600, os.stat(path).st_mode & 0o777) with open(path) as f: contents = json.load(f) self.assertEqual("12345", contents["refresh_token"]) def test_write_overwrites_file(self): root = self.get_temp_dir() store = auth.CredentialsStore(user_config_directory=root) # Write twice to ensure that we're overwriting correctly. store.write_credentials( google.oauth2.credentials.Credentials( token=None, refresh_token="<PASSWORD>" ) ) store.write_credentials( google.oauth2.credentials.Credentials( token=None, refresh_token="<PASSWORD>" ) ) path = os.path.join( root, "tensorboard", "credentials", "uploader-creds.json" ) self.assertTrue(os.path.exists(path)) with open(path) as f: contents = json.load(f) self.assertEqual("67890", contents["refresh_token"]) def test_write_and_read_roundtrip(self): orig_creds = google.oauth2.credentials.Credentials( token="<PASSWORD>5", refresh_token="<PASSWORD>", token_uri="https://oauth2.googleapis.com/token", client_id="my-client", client_secret="<KEY>", scopes=["userinfo", "email"], ) root = self.get_temp_dir() store = auth.CredentialsStore(user_config_directory=root) store.write_credentials(orig_creds) creds = store.read_credentials() self.assertEqual(orig_creds.refresh_token, creds.refresh_token) self.assertEqual(orig_creds.token_uri, creds.token_uri) self.assertEqual(orig_creds.client_id, creds.client_id) self.assertEqual(orig_creds.client_secret, creds.client_secret) def test_read_nonexistent_file(self): root = self.get_temp_dir() store = auth.CredentialsStore(user_config_directory=root) self.assertIsNone(store.read_credentials()) def test_read_non_json_file(self): root = self.get_temp_dir() store = auth.CredentialsStore(user_config_directory=root) path = os.path.join( root, "tensorboard", "credentials", "uploader-creds.json" ) os.makedirs(os.path.dirname(path)) with open(path, mode="w") as f: f.write("foobar") with self.assertRaises(ValueError): store.read_credentials() def test_read_invalid_json_file(self): root = self.get_temp_dir() store = auth.CredentialsStore(user_config_directory=root) path = os.path.join( root, "tensorboard", "credentials", "uploader-creds.json" ) os.makedirs(os.path.dirname(path)) with open(path, mode="w") as f: f.write("{}") with self.assertRaises(ValueError): store.read_credentials() if __name__ == "__main__": tb_test.main() <file_sep>/* Copyright 2019 The TensorFlow Authors. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ==============================================================================*/ /** * @fileoverview MeshLoader provides UI functionality and placeholder to render * 3D data. */ var vz_mesh; (function(vz_mesh) { /** Polymer wrapper around MeshLoader. */ Polymer({ is: 'tf-mesh-loader', properties: { /** @type {string} Current run. */ run: String, /** @type {string} Current tag. */ tag: String, /** @type {number} Index of current sample. */ sample: Number, /** @type {number} Total number of samples. */ ofSamples: Number, /** * Defines behavior for camera location during redraw. * @type {string} */ selectedView: {type: String, value: 'all'}, /** @type {!bool} Defines if component is active and should get data to * display. */ active: { type: Boolean, value: false, }, /** @type {!Object} Request manager to communicate with the server. */ requestManager: Object, /** * @type {!Object} Component to render meshes and point * clouds. */ _meshViewer: {type: Object}, /** * @type {!Object} Data provider to * communicate with the server and parse raw data. */ _dataProvider: {type: Object}, /**@type {!Object} Wrapper to function to transform value into color.*/ _colorScaleFunction: { type: Object, // function: string => string value: () => tf_color_scale.runsColorScale, }, /**@type {string} Wrapper around function to compute color for a run.*/ _runColor: { type: String, computed: '_computeRunColor(run)', }, /** @type {!Array} Contains datums for each step. */ _steps: { type: Array, value: () => [], notify: true, }, /** @type {number} Contains index of current step. */ _stepIndex: { type: Number, notify: true, }, /** @type {!Object} Contains datum of current step. */ _currentStep: { type: Object, computed: '_computeCurrentStep(_steps, _stepIndex)', }, /** @type {!bool} Determines if mesh viewer attached to dom. */ _meshViewerAttached: {type: Boolean, value: false}, /** * @type {!bool} Determines if camera position was initially set to * defaults. */ _cameraPositionInitialized: {type: Boolean, value: false}, /** * @type {number} Contains current step value (step number assigned * during training). */ _stepValue: { type: Number, computed: '_computeStepValue(_currentStep)', }, /** @type {string} Contains formatted wall time. */ _currentWallTime: { type: String, computed: '_computeCurrentWallTime(_currentStep)', }, /** @type {!bool} Defines if browser still loading data. */ _isMeshLoading: { type: Boolean, value: false, }, }, observers: [ 'reload(run, tag, active, _dataProvider, _meshViewer)', '_updateScene(_currentStep.*, _meshViewer)', '_debouncedFetchMesh(_currentStep)', '_updateView(selectedView)', ], _computeRunColor: function(run) { return this._colorScaleFunction(run); }, /** * Called by parent when component attached to DOM. * @public */ attached: function() { // Defer reloading until after we're attached, because that ensures that // the requestManager has been set from above. (Polymer is tricky // sometimes) this._dataProvider = new vz_mesh.ArrayBufferDataProvider( this.requestManager ); const meshViewer = new vz_mesh.MeshViewer(this._runColor); meshViewer.addEventListener( 'beforeUpdateScene', this._updateCanvasSize.bind(this) ); meshViewer.addEventListener( 'cameraPositionChange', this._onCameraPositionChange.bind(this) ); this._meshViewer = meshViewer; }, /** * Function to call when component must be reloaded. */ reload: function() { if (!this.active || !this._dataProvider) { return; } this.set('_isMeshLoading', true); this._dataProvider .reload(this.run, this.tag, this.sample) .then((steps) => { if (!steps) return; // Happens when request was cancelled at some point. this.set('_steps', steps); this.set('_stepIndex', steps.length - 1); }) .catch((error) => { if ( !error || !error.code || error.code != vz_mesh.ErrorCodes.CANCELLED ) { error = error || 'Response processing failed.'; throw new Error(error); } }); }, /** * Updates the scene. * @private */ _updateScene: function() { const currentStep = this._currentStep; // Mesh data is not fetched yet. Please see `_maybeFetchMesh`. if (!currentStep || !currentStep.mesh) return; this._meshViewer.updateScene(currentStep, this); if (!this._cameraPositionInitialized) { this._meshViewer.resetView(); this._cameraPositionInitialized = true; } if (!this._meshViewerAttached) { // Mesh viewer should be added to the dom once. this.root.appendChild(this._meshViewer.getRenderer().domElement); this._meshViewerAttached = true; } }, _debouncedFetchMesh() { this.debounce('fetchMesh', () => this._maybeFetchMesh(), 100); }, async _maybeFetchMesh() { const currentStep = this._currentStep; if (!currentStep || currentStep.mesh || currentStep.meshFetching) return; currentStep.meshFetching = true; this._isMeshLoading = true; try { const meshData = await this._dataProvider.fetchData( currentStep, this.run, this.tag, this.sample, this._stepIndex ); currentStep.mesh = meshData[0]; this.notifyPath('_currentStep.mesh'); } catch (error) { if ( !error || !error.code || error.code != vz_mesh.ErrorCodes.CANCELLED ) { error = error || 'Response processing failed.'; throw new Error(error); } } finally { this._isMeshLoading = false; currentStep.meshFetching = false; } }, /** * Propagates camera position change event outside of the loader. * @private */ _onCameraPositionChange: function() { if (!this._meshViewer.isReady()) return; const event = new CustomEvent('camera-position-change', { detail: this._meshViewer.getCameraPosition(), }); this.dispatchEvent(event); }, /** * Creates mesh geometry for current step data. * @param {!THREE.Vector3} position Position of the camera. * @param {number} far Camera frustum far plane. * @param {!THREE.Vector3} target Point in space for camera to look at. * @public */ setCameraViewpoint: function(position, far, target) { this._meshViewer.setCameraViewpoint(position, far, target); }, /** * Updates size of the canvas. * @private */ _updateCanvasSize: function() { const width = this.offsetWidth; const height = width; // Keep the whole mesh viewer square at all times. const headerHeight = this.$$('.tf-mesh-loader-header').offsetHeight; const canvasSize = { width: width, height: height - headerHeight, }; this._meshViewer.setCanvasSize(canvasSize); }, /** * Re-renders component in the browser. * @public */ redraw: function() { this._updateCanvasSize(); // Do not render if not in the DOM. if (!this.isConnected) return; this._meshViewer.draw(); }, _hasAtLeastOneStep: function(steps) { return !!steps && steps.length > 0; }, _hasMultipleSteps: function(steps) { return !!steps && steps.length > 1; }, _computeCurrentStep: function(steps, stepIndex) { return steps[stepIndex] || null; }, _computeStepValue: function(currentStep) { if (!currentStep) return 0; return currentStep.step; }, _computeCurrentWallTime: function(currentStep) { if (!currentStep) return ''; return tf_card_heading.formatDate(currentStep.wall_time); }, _getMaxStepIndex: function(steps) { return steps.length - 1; }, _getSampleText: function(sample) { return String(sample + 1); }, _hasMultipleSamples: function(ofSamples) { return ofSamples > 1; }, _updateView: function(selectedView) { if (this._meshViewer && selectedView == 'all') { this._meshViewer.resetView(); } }, toLocaleString_: function(number) { // Shows commas (or locale-appropriate punctuation) for large numbers. return number.toLocaleString(); }, }); })(vz_mesh || (vz_mesh = {})); // end of vz_mesh namespace <file_sep>/* Copyright 2019 The TensorFlow Authors. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ==============================================================================*/ import {Injectable} from '@angular/core'; import {Action, Store} from '@ngrx/store'; import {Actions, ofType, createEffect} from '@ngrx/effects'; import {Observable, of, zip} from 'rxjs'; import { map, mergeMap, catchError, withLatestFrom, filter, tap, } from 'rxjs/operators'; import { coreLoaded, manualReload, reload, pluginsListingRequested, pluginsListingLoaded, pluginsListingFailed, } from '../actions'; import {getPluginsListLoaded} from '../store'; import {DataLoadState} from '../../types/data'; import {State} from '../store/core_types'; import {TBServerDataSource} from '../../webapp_data_source/tb_server_data_source'; /** @typehack */ import * as _typeHackRxjs from 'rxjs'; /** @typehack */ import * as _typeHackNgrx from '@ngrx/store/src/models'; /** @typehack */ import * as _typeHackNgrxEffects from '@ngrx/effects'; @Injectable() export class CoreEffects { /** * Requires to be exported for JSCompiler. JSCompiler, otherwise, * think it is unused property and deadcode eliminate away. */ /** @export */ readonly loadPluginsListing$ = createEffect(() => this.actions$.pipe( ofType(coreLoaded, reload, manualReload), withLatestFrom(this.store.select(getPluginsListLoaded)), filter(([, {state}]) => state !== DataLoadState.LOADING), tap(() => this.store.dispatch(pluginsListingRequested())), mergeMap(() => { return zip( this.webappDataSource.fetchPluginsListing(), this.webappDataSource.fetchRuns(), this.webappDataSource.fetchEnvironments() ).pipe( map(([plugins]) => { return pluginsListingLoaded({plugins}); }, catchError(() => of(pluginsListingFailed()))) ) as Observable<Action>; }) ) ); constructor( private actions$: Actions, private store: Store<State>, private webappDataSource: TBServerDataSource ) {} } <file_sep># Copyright 2020 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================== """Tests for `tensorboard.dataclass_compat`.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function import os import numpy as np import tensorflow as tf from tensorboard import dataclass_compat from tensorboard.backend.event_processing import event_file_loader from tensorboard.compat.proto import event_pb2 from tensorboard.compat.proto import graph_pb2 from tensorboard.compat.proto import summary_pb2 from tensorboard.plugins.graph import metadata as graphs_metadata from tensorboard.plugins.histogram import metadata as histogram_metadata from tensorboard.plugins.histogram import summary as histogram_summary from tensorboard.plugins.hparams import metadata as hparams_metadata from tensorboard.plugins.hparams import summary_v2 as hparams_summary from tensorboard.plugins.scalar import metadata as scalar_metadata from tensorboard.plugins.scalar import summary as scalar_summary from tensorboard.util import tensor_util from tensorboard.util import test_util class MigrateEventTest(tf.test.TestCase): """Tests for `migrate_event`.""" def _migrate_event(self, old_event): """Like `migrate_event`, but performs some sanity checks.""" old_event_copy = event_pb2.Event() old_event_copy.CopyFrom(old_event) new_events = dataclass_compat.migrate_event(old_event) for event in new_events: # ensure that wall time and step are preserved self.assertEqual(event.wall_time, old_event.wall_time) self.assertEqual(event.step, old_event.step) return new_events def test_irrelevant_event_passes_through(self): old_event = event_pb2.Event() old_event.file_version = "brain.Event:wow" new_events = self._migrate_event(old_event) self.assertLen(new_events, 1) self.assertIs(new_events[0], old_event) def test_unknown_summary_passes_through(self): old_event = event_pb2.Event() value = old_event.summary.value.add() value.metadata.plugin_data.plugin_name = "magic" value.metadata.plugin_data.content = b"123" value.tensor.CopyFrom(tensor_util.make_tensor_proto([1, 2])) new_events = self._migrate_event(old_event) self.assertLen(new_events, 1) self.assertIs(new_events[0], old_event) def test_already_newstyle_summary_passes_through(self): # ...even when it's from a known plugin and would otherwise be migrated. old_event = event_pb2.Event() old_event.summary.ParseFromString( scalar_summary.pb( "foo", 1.25, display_name="bar", description="baz" ).SerializeToString() ) metadata = old_event.summary.value[0].metadata metadata.data_class = summary_pb2.DATA_CLASS_TENSOR # note: not scalar new_events = self._migrate_event(old_event) self.assertLen(new_events, 1) self.assertIs(new_events[0], old_event) def test_scalar(self): old_event = event_pb2.Event() old_event.step = 123 old_event.wall_time = 456.75 old_event.summary.ParseFromString( scalar_summary.pb( "foo", 1.25, display_name="bar", description="baz" ).SerializeToString() ) new_events = self._migrate_event(old_event) self.assertLen(new_events, 1) self.assertLen(new_events[0].summary.value, 1) value = new_events[0].summary.value[0] tensor = tensor_util.make_ndarray(value.tensor) self.assertEqual(tensor.shape, ()) self.assertEqual(tensor.item(), 1.25) self.assertEqual( value.metadata.data_class, summary_pb2.DATA_CLASS_SCALAR ) self.assertEqual( value.metadata.plugin_data.plugin_name, scalar_metadata.PLUGIN_NAME ) def test_histogram(self): old_event = event_pb2.Event() old_event.step = 123 old_event.wall_time = 456.75 histogram_pb = histogram_summary.pb( "foo", [1.0, 2.0, 3.0, 4.0], bucket_count=12, display_name="bar", description="baz", ) old_event.summary.ParseFromString(histogram_pb.SerializeToString()) new_events = self._migrate_event(old_event) self.assertLen(new_events, 1) self.assertLen(new_events[0].summary.value, 1) value = new_events[0].summary.value[0] tensor = tensor_util.make_ndarray(value.tensor) self.assertEqual(tensor.shape, (12, 3)) np.testing.assert_array_equal( tensor, tensor_util.make_ndarray(histogram_pb.value[0].tensor) ) self.assertEqual( value.metadata.data_class, summary_pb2.DATA_CLASS_TENSOR ) self.assertEqual( value.metadata.plugin_data.plugin_name, histogram_metadata.PLUGIN_NAME, ) def test_hparams(self): old_event = event_pb2.Event() old_event.step = 0 old_event.wall_time = 456.75 hparams_pb = hparams_summary.hparams_pb({"optimizer": "adam"}) # Simulate legacy event with no tensor content for v in hparams_pb.value: v.ClearField("tensor") old_event.summary.CopyFrom(hparams_pb) new_events = self._migrate_event(old_event) self.assertLen(new_events, 1) self.assertLen(new_events[0].summary.value, 1) value = new_events[0].summary.value[0] self.assertEqual(value.tensor, hparams_metadata.NULL_TENSOR) self.assertEqual( value.metadata.data_class, summary_pb2.DATA_CLASS_TENSOR ) self.assertEqual( value.metadata.plugin_data, hparams_pb.value[0].metadata.plugin_data, ) def test_graph_def(self): # Create a `GraphDef` and write it to disk as an event. logdir = self.get_temp_dir() writer = test_util.FileWriter(logdir) graph_def = graph_pb2.GraphDef() graph_def.node.add(name="alice", op="Person") graph_def.node.add(name="bob", op="Person") graph_def.node.add( name="friendship", op="Friendship", input=["alice", "bob"] ) writer.add_graph(graph=None, graph_def=graph_def, global_step=123) writer.flush() # Read in the `Event` containing the written `graph_def`. files = os.listdir(logdir) self.assertLen(files, 1) event_file = os.path.join(logdir, files[0]) self.assertIn("tfevents", event_file) loader = event_file_loader.EventFileLoader(event_file) events = list(loader.Load()) self.assertLen(events, 2) self.assertEqual(events[0].WhichOneof("what"), "file_version") self.assertEqual(events[1].WhichOneof("what"), "graph_def") old_event = events[1] new_events = self._migrate_event(old_event) self.assertLen(new_events, 2) self.assertIs(new_events[0], old_event) new_event = new_events[1] self.assertEqual(new_event.WhichOneof("what"), "summary") self.assertLen(new_event.summary.value, 1) tensor = tensor_util.make_ndarray(new_event.summary.value[0].tensor) self.assertEqual( new_event.summary.value[0].metadata.data_class, summary_pb2.DATA_CLASS_BLOB_SEQUENCE, ) self.assertEqual( new_event.summary.value[0].metadata.plugin_data.plugin_name, graphs_metadata.PLUGIN_NAME, ) self.assertEqual(tensor.shape, (1,)) new_graph_def_bytes = tensor[0] self.assertIsInstance(new_graph_def_bytes, bytes) self.assertGreaterEqual(len(new_graph_def_bytes), 16) new_graph_def = graph_pb2.GraphDef.FromString(new_graph_def_bytes) self.assertProtoEquals(graph_def, new_graph_def) if __name__ == "__main__": tf.test.main() <file_sep># Copyright 2019 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from __future__ import absolute_import from __future__ import division from __future__ import print_function import pkg_resources from tensorboard import test as tb_test from tensorboard import version class VersionTest(tb_test.TestCase): def test_valid_pep440_version(self): """Ensure that our version is PEP 440-compliant.""" # `Version` and `LegacyVersion` are vendored and not publicly # exported; get handles to them. compliant_version = pkg_resources.parse_version("1.0.0") legacy_version = pkg_resources.parse_version("some arbitrary string") self.assertNotEqual(type(compliant_version), type(legacy_version)) tensorboard_version = pkg_resources.parse_version(version.VERSION) self.assertIsInstance(tensorboard_version, type(compliant_version)) if __name__ == "__main__": tb_test.main() <file_sep>/* Copyright 2015 The TensorFlow Authors. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the 'License'); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an 'AS IS' BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ==============================================================================*/ describe('parser', () => { const {assert, expect} = chai; describe('parsing GraphDef pbtxt', () => { it('parses a simple pbtxt', () => { const pbtxt = tf.graph.test.util.stringToArrayBuffer(`node { name: "Q" op: "Input" } node { name: "W" op: "Input" } node { name: "X" op: "MatMul" input: "Q" input: "W" }`); return tf.graph.parser.parseGraphPbTxt(pbtxt).then((graph) => { let nodes = graph.node; assert.isTrue(nodes != null && nodes.length === 3); assert.equal('Q', nodes[0].name); assert.equal('Input', nodes[0].op); assert.equal('W', nodes[1].name); assert.equal('Input', nodes[1].op); assert.equal('X', nodes[2].name); assert.equal('MatMul', nodes[2].op); assert.equal('Q', nodes[2].input[0]); assert.equal('W', nodes[2].input[1]); }); }); it('parses function def library', () => { const pbtxt = tf.graph.test.util.stringToArrayBuffer(`library { function { signature { name: "foo" input_arg { name: "placeholder_1" type: DT_INT32 } input_arg { name: "placeholder_2" type: DT_BOOL } output_arg { name: "identity" type: DT_BOOL } } node_def { name: "NoOp" op: "NoOp" attr { key: "_output_shapes" value { list { } } } } node_def { name: "Identity" op: "Identity" input: "placeholder_1" input: "^NoOp" attr { key: "T" value { type: DT_BOOL } } attr { key: "_output_shapes" value { list { shape { } } } } } } }`); return tf.graph.parser.parseGraphPbTxt(pbtxt).then((graph) => { expect(graph) .to.have.property('library') .that.has.property('function') .that.is.an('array') .and.that.has.length(1); const firstFunc = graph.library.function[0]; expect(firstFunc) .to.have.property('signature') .that.has.property('name', 'foo'); expect(firstFunc) .to.have.property('node_def') .that.is.an('array') .and.that.has.length(2); expect(firstFunc.node_def[0]).to.have.property('name', 'NoOp'); expect(firstFunc.node_def[0]).to.not.have.property('input'); expect(firstFunc.node_def[0]) .to.have.property('attr') .that.deep.equal([{key: '_output_shapes', value: {list: {}}}]); expect(firstFunc.node_def[1]).to.have.property('name', 'Identity'); expect(firstFunc.node_def[1]) .to.have.property('input') .that.deep.equal(['placeholder_1', '^NoOp']); expect(firstFunc.node_def[1]) .to.have.property('attr') .that.deep.equal([ {key: 'T', value: {type: 'DT_BOOL'}}, {key: '_output_shapes', value: {list: {shape: [{}]}}}, ]); }); }); // TODO: fail hard on malformed pbtxt. // Expected it to fail but our parser currently handles it in // unpredictable way... // These specs are describing behavior as implemented. describe('malformed cases', () => { // Then it becomes unpredictable. it('parses upto an empty node', () => { const pbtxt = tf.graph.test.util.stringToArrayBuffer(`node { name: "Q" op: "Input" } node {}`); return tf.graph.parser.parseGraphPbTxt(pbtxt).then((graph) => { const nodes = graph.node; assert.isArray(nodes); assert.lengthOf(nodes, 1); assert.equal('Q', nodes[0].name); assert.equal('Input', nodes[0].op); }); }); it('fails to parse a node when an empty node appears before', () => { const pbtxt = tf.graph.test.util.stringToArrayBuffer(`node {} node { name: "Q" op: "Input" }`); return tf.graph.parser.parseGraphPbTxt(pbtxt).then( () => assert.fail('Should NOT resolve'), () => { // Expected to fail and reject the promise. } ); }); it('parses pbtxt without newlines as errorneously empty', () => { const pbtxt = tf.graph.test.util.stringToArrayBuffer( `node { name: "Q" op: "Input" } node { name: "A" op: "Input" }` ); return tf.graph.parser.parseGraphPbTxt(pbtxt).then((graph) => { assert.notProperty(graph, 'node'); }); }); it('parses malformed pbtxt upto the correct declaration', () => { const pbtxt = tf.graph.test.util.stringToArrayBuffer(`node { name: "Q" op: "Input" } node { name: "W" op: "Input" } node { name: "X" op: "MatMul" input: "Q" input: "W" }`); return tf.graph.parser.parseGraphPbTxt(pbtxt).then((graph) => { const nodes = graph.node; assert.isArray(nodes); assert.lengthOf(nodes, 1); assert.equal('Q', nodes[0].name); assert.equal('Input', nodes[0].op); }); }); it('cannot parse when pbtxt is malformed', () => { const pbtxt = tf.graph.test.util.stringToArrayBuffer(`node { name: "Q" op: "Input } node { name: "W" op: "Input" node { name: "X" op: "MatMul" input: "Q" input: "W" } node { name: A" op: "Input" }`); return tf.graph.parser.parseGraphPbTxt(pbtxt).then( () => assert.fail('Should NOT resolve'), () => { // Expected to fail and reject the promise. } ); }); }); }); it('parses stats pbtxt', () => { let statsPbtxt = tf.graph.test.util.stringToArrayBuffer(`step_stats { dev_stats { device: "cpu" node_stats { node_name: "Q" all_start_micros: 10 all_end_rel_micros: 4 } node_stats { node_name: "Q" all_start_micros: 12 all_end_rel_micros: 4 } } }`); return tf.graph.parser.parseStatsPbTxt(statsPbtxt).then((stepStats) => { assert.equal(stepStats.dev_stats.length, 1); assert.equal(stepStats.dev_stats[0].device, 'cpu'); assert.equal(stepStats.dev_stats[0].node_stats.length, 2); assert.equal(stepStats.dev_stats[0].node_stats[0].all_start_micros, 10); assert.equal(stepStats.dev_stats[0].node_stats[1].node_name, 'Q'); assert.equal(stepStats.dev_stats[0].node_stats[1].all_end_rel_micros, 4); }); }); it('d3 exists', () => { assert.isTrue(d3 != null); }); // TODO(nsthorat): write tests. }); <file_sep># Copyright 2019 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================== """Simple demo which displays constant 3D mesh.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function import os from absl import app from absl import flags import numpy as np import tensorflow as tf from tensorboard.plugins.mesh import summary as mesh_summary from tensorboard.plugins.mesh import demo_utils flags.DEFINE_string( "logdir", "/tmp/mesh_demo", "Directory to write event logs to." ) flags.DEFINE_string("mesh_path", None, "Path to PLY file to visualize.") FLAGS = flags.FLAGS tf.compat.v1.disable_v2_behavior() # Max number of steps to run training with. _MAX_STEPS = 10 def run(): """Runs session with a mesh summary.""" # Mesh summaries only work on TensorFlow 1.x. if int(tf.__version__.split(".")[0]) > 1: raise ImportError("TensorFlow 1.x is required to run this demo.") # Flag mesh_path is required. if FLAGS.mesh_path is None: raise ValueError( "Flag --mesh_path is required and must contain path to PLY file." ) # Camera and scene configuration. config_dict = {"camera": {"cls": "PerspectiveCamera", "fov": 75}} # Read sample PLY file. vertices, colors, faces = demo_utils.read_ascii_ply(FLAGS.mesh_path) # Add batch dimension. vertices = np.expand_dims(vertices, 0) faces = np.expand_dims(faces, 0) colors = np.expand_dims(colors, 0) # Create placeholders for tensors representing the mesh. step = tf.placeholder(tf.int32, ()) vertices_tensor = tf.placeholder(tf.float32, vertices.shape) faces_tensor = tf.placeholder(tf.int32, faces.shape) colors_tensor = tf.placeholder(tf.int32, colors.shape) # Change colors over time. t = tf.cast(step, tf.float32) / _MAX_STEPS transformed_colors = t * (255 - colors) + (1 - t) * colors meshes_summary = mesh_summary.op( "mesh_color_tensor", vertices=vertices_tensor, faces=faces_tensor, colors=transformed_colors, config_dict=config_dict, ) # Create summary writer and session. writer = tf.summary.FileWriter(FLAGS.logdir) sess = tf.Session() for i in range(_MAX_STEPS): summary = sess.run( meshes_summary, feed_dict={ vertices_tensor: vertices, faces_tensor: faces, colors_tensor: colors, step: i, }, ) writer.add_summary(summary, global_step=i) def main(unused_argv): print("Saving output to %s." % FLAGS.logdir) run() print("Done. Output saved to %s." % FLAGS.logdir) if __name__ == "__main__": app.run(main) <file_sep>/* Copyright 2019 The TensorFlow Authors. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ==============================================================================*/ /** * Unit tests for the Debugger Container. */ import {CommonModule} from '@angular/common'; import {TestBed} from '@angular/core/testing'; import {By} from '@angular/platform-browser'; import {Store} from '@ngrx/store'; import {provideMockStore, MockStore} from '@ngrx/store/testing'; import { debuggerLoaded, executionScrollLeft, executionScrollRight, executionScrollToIndex, } from './actions'; import {DebuggerComponent} from './debugger_component'; import {DebuggerContainer} from './debugger_container'; import { DataLoadState, State, TensorDebugMode, AlertType, } from './store/debugger_types'; import { createAlertsState, createDebuggerState, createState, createDebuggerExecutionsState, createDebuggerStateWithLoadedExecutionDigests, createTestExecutionData, createTestStackFrame, } from './testing'; import {AlertsModule} from './views/alerts/alerts_module'; import {ExecutionDataContainer} from './views/execution_data/execution_data_container'; import {ExecutionDataModule} from './views/execution_data/execution_data_module'; import {InactiveModule} from './views/inactive/inactive_module'; import {TimelineContainer} from './views/timeline/timeline_container'; import {StackTraceContainer} from './views/stack_trace/stack_trace_container'; import {StackTraceModule} from './views/stack_trace/stack_trace_module'; import {TimelineModule} from './views/timeline/timeline_module'; /** @typehack */ import * as _typeHackStore from '@ngrx/store'; describe('Debugger Container', () => { let store: MockStore<State>; let dispatchSpy: jasmine.Spy; beforeEach(async () => { await TestBed.configureTestingModule({ declarations: [DebuggerComponent, DebuggerContainer], imports: [ AlertsModule, CommonModule, ExecutionDataModule, InactiveModule, StackTraceModule, TimelineModule, ], providers: [ provideMockStore({ initialState: createState(createDebuggerState()), }), DebuggerContainer, TimelineContainer, ], }).compileComponents(); store = TestBed.get(Store); dispatchSpy = spyOn(store, 'dispatch'); }); it('renders debugger component initially with inactive component', () => { const fixture = TestBed.createComponent(DebuggerContainer); fixture.detectChanges(); const inactiveElement = fixture.debugElement.query( By.css('tf-debugger-v2-inactive') ); expect(inactiveElement).toBeTruthy(); const alertsElement = fixture.debugElement.query( By.css('tf-debugger-v2-alerts') ); expect(alertsElement).toBeNull(); }); it('rendering debugger component dispatches debuggeRunsRequested', () => { const fixture = TestBed.createComponent(DebuggerContainer); fixture.detectChanges(); expect(dispatchSpy).toHaveBeenCalledWith(debuggerLoaded()); }); it('updates the UI to hide inactive component when store has 1 run', () => { const fixture = TestBed.createComponent(DebuggerContainer); fixture.detectChanges(); store.setState( createState( createDebuggerState({ runs: { foo_run: { start_time: 111, }, }, runsLoaded: { state: DataLoadState.LOADED, lastLoadedTimeInMs: Date.now(), }, }) ) ); fixture.detectChanges(); const inactiveElement = fixture.debugElement.query( By.css('tf-debugger-v2-inactive') ); expect(inactiveElement).toBeNull(); const alertsElement = fixture.debugElement.query( By.css('tf-debugger-v2-alerts') ); expect(alertsElement).toBeTruthy(); }); it('updates the UI to hide inactive component when store has no run', () => { const fixture = TestBed.createComponent(DebuggerContainer); fixture.detectChanges(); store.setState( createState( createDebuggerState({ runs: {}, runsLoaded: { state: DataLoadState.LOADED, lastLoadedTimeInMs: Date.now(), }, }) ) ); fixture.detectChanges(); const inactiveElement = fixture.debugElement.query( By.css('tf-debugger-v2-inactive') ); expect(inactiveElement).toBeTruthy(); const alertsElement = fixture.debugElement.query( By.css('tf-debugger-v2-alerts') ); expect(alertsElement).toBeNull(); }); describe('Timeline module', () => { it('shows loading number of executions', () => { const fixture = TestBed.createComponent(TimelineContainer); fixture.detectChanges(); store.setState( createState( createDebuggerState({ runs: {}, runsLoaded: { state: DataLoadState.LOADED, lastLoadedTimeInMs: Date.now(), }, executions: createDebuggerExecutionsState({ numExecutionsLoaded: { state: DataLoadState.LOADING, lastLoadedTimeInMs: null, }, }), }) ) ); fixture.detectChanges(); const loadingElements = fixture.debugElement.queryAll( By.css('.loading-num-executions') ); expect(loadingElements.length).toEqual(1); }); it('hides loading number of executions', () => { const fixture = TestBed.createComponent(TimelineContainer); fixture.detectChanges(); store.setState( createState( createDebuggerState({ runs: {}, runsLoaded: { state: DataLoadState.LOADED, lastLoadedTimeInMs: Date.now(), }, executions: createDebuggerExecutionsState({ numExecutionsLoaded: { state: DataLoadState.LOADED, lastLoadedTimeInMs: 111, }, }), }) ) ); fixture.detectChanges(); const loadingElements = fixture.debugElement.queryAll( By.css('.loading-num-executions') ); expect(loadingElements.length).toEqual(0); }); it('shows correct display range for executions', () => { const fixture = TestBed.createComponent(TimelineContainer); fixture.detectChanges(); const scrollBeginIndex = 977; const dislpaySize = 100; store.setState( createState( createDebuggerStateWithLoadedExecutionDigests( scrollBeginIndex, dislpaySize ) ) ); fixture.detectChanges(); const navigationPositionInfoElement = fixture.debugElement.query( By.css('.navigation-position-info') ); expect(navigationPositionInfoElement.nativeElement.innerText).toBe( 'Execution: 977 ~ 1076 of 1500' ); }); it('left-button click dispatches executionScrollLeft action', () => { const fixture = TestBed.createComponent(TimelineContainer); fixture.detectChanges(); store.setState( createState(createDebuggerStateWithLoadedExecutionDigests(0, 50)) ); fixture.detectChanges(); const leftBUtton = fixture.debugElement.query( By.css('.navigation-button-left') ); leftBUtton.nativeElement.click(); fixture.detectChanges(); expect(dispatchSpy).toHaveBeenCalledWith(executionScrollLeft()); }); it('right-button click dispatches executionScrollRight action', () => { const fixture = TestBed.createComponent(TimelineContainer); fixture.detectChanges(); store.setState( createState(createDebuggerStateWithLoadedExecutionDigests(0, 50)) ); fixture.detectChanges(); const rightButton = fixture.debugElement.query( By.css('.navigation-button-right') ); rightButton.nativeElement.click(); fixture.detectChanges(); expect(dispatchSpy).toHaveBeenCalledWith(executionScrollRight()); }); it('displays correct op names', () => { const fixture = TestBed.createComponent(TimelineContainer); fixture.detectChanges(); const scrollBeginIndex = 100; const displayCount = 40; const opTypes: string[] = []; for (let i = 0; i < 200; ++i) { opTypes.push(`${i}Op`); } store.setState( createState( createDebuggerStateWithLoadedExecutionDigests( scrollBeginIndex, displayCount, opTypes ) ) ); fixture.detectChanges(); const executionDigests = fixture.debugElement.queryAll( By.css('.execution-digest') ); expect(executionDigests.length).toEqual(40); const strLen = 1; for (let i = 0; i < 40; ++i) { expect(executionDigests[i].nativeElement.innerText).toEqual( opTypes[i + 100].slice(0, strLen) ); } }); it('displays correct InfNanAlert alert type', () => { const fixture = TestBed.createComponent(TimelineContainer); fixture.detectChanges(); const scrollBeginIndex = 5; const displayCount = 4; const opTypes: string[] = []; for (let i = 0; i < 200; ++i) { opTypes.push(`${i}Op`); } const debuggerState = createDebuggerStateWithLoadedExecutionDigests( scrollBeginIndex, displayCount, opTypes ); debuggerState.alerts = createAlertsState({ focusType: AlertType.INF_NAN_ALERT, executionIndices: { [AlertType.INF_NAN_ALERT]: [ 4, // Outside the viewing window. 6, // Inside the viewing window; same below. 8, ], }, }); store.setState(createState(debuggerState)); fixture.detectChanges(); const digestsWithAlert = fixture.debugElement.queryAll( By.css('.execution-digest.InfNanAlert') ); expect(digestsWithAlert.length).toBe(2); expect(digestsWithAlert[0].nativeElement.innerText).toEqual('6'); expect(digestsWithAlert[1].nativeElement.innerText).toEqual('8'); }); for (const numExecutions of [1, 9, 10]) { it(`hides slider if # of executions ${numExecutions} <= display count`, () => { const fixture = TestBed.createComponent(TimelineContainer); fixture.detectChanges(); const scrollBeginIndex = 0; const displayCount = 10; const opTypes: string[] = new Array<string>(numExecutions); opTypes.fill('MatMul'); const debuggerState = createDebuggerStateWithLoadedExecutionDigests( scrollBeginIndex, displayCount, opTypes ); store.setState(createState(debuggerState)); fixture.detectChanges(); const sliders = fixture.debugElement.queryAll( By.css('.timeline-slider') ); expect(sliders.length).toBe(0); }); } for (const numExecutions of [11, 12, 20]) { const displayCount = 10; for (const scrollBeginIndex of [0, 1, numExecutions - displayCount]) { it( `shows slider if # of executions ${numExecutions} > display count, ` + `scrollBeginIndex = ${scrollBeginIndex}`, () => { const fixture = TestBed.createComponent(TimelineContainer); fixture.detectChanges(); const opTypes: string[] = new Array<string>(numExecutions); opTypes.fill('MatMul'); const debuggerState = createDebuggerStateWithLoadedExecutionDigests( scrollBeginIndex, displayCount, opTypes ); store.setState(createState(debuggerState)); fixture.detectChanges(); const sliders = fixture.debugElement.queryAll( By.css('.timeline-slider') ); expect(sliders.length).toBe(1); const [slider] = sliders; expect(slider.attributes['aria-valuemin']).toBe('0'); expect(slider.attributes['aria-valuemax']).toBe( String(numExecutions - displayCount) ); expect(slider.attributes['aria-valuenow']).toBe( String(scrollBeginIndex) ); } ); } } }); for (const scrollBeginIndex of [0, 1, 5]) { it(`changes slider dispatches executionToScrollIndex (${scrollBeginIndex})`, () => { const fixture = TestBed.createComponent(TimelineContainer); fixture.detectChanges(); const numExecutions = 10; const displayCount = 5; const opTypes: string[] = new Array<string>(numExecutions); opTypes.fill('MatMul'); const debuggerState = createDebuggerStateWithLoadedExecutionDigests( scrollBeginIndex, displayCount, opTypes ); store.setState(createState(debuggerState)); fixture.detectChanges(); const slider = fixture.debugElement.query(By.css('.timeline-slider')); slider.triggerEventHandler('change', {value: scrollBeginIndex}); fixture.detectChanges(); expect(dispatchSpy).toHaveBeenCalledWith( executionScrollToIndex({index: scrollBeginIndex}) ); }); } describe('Execution Data module', () => { it('CURT_HEALTH TensorDebugMode, One Output', () => { const fixture = TestBed.createComponent(ExecutionDataContainer); fixture.detectChanges(); store.setState( createState( createDebuggerState({ executions: { numExecutionsLoaded: { state: DataLoadState.LOADED, lastLoadedTimeInMs: 111, }, executionDigestsLoaded: { state: DataLoadState.LOADED, lastLoadedTimeInMs: 222, pageLoadedSizes: {0: 100}, numExecutions: 1000, }, executionDigests: {}, pageSize: 100, displayCount: 50, scrollBeginIndex: 90, focusIndex: 98, executionData: { 98: createTestExecutionData({ op_type: 'Inverse', tensor_debug_mode: TensorDebugMode.NO_TENSOR, debug_tensor_values: null, }), }, }, }) ) ); fixture.detectChanges(); const opTypeElement = fixture.debugElement.query(By.css('.op-type')); expect(opTypeElement.nativeElement.innerText).toEqual('Inverse'); const inputTensorsElement = fixture.debugElement.query( By.css('.input-tensors') ); expect(inputTensorsElement.nativeElement.innerText).toEqual('1'); const outputTensorsElement = fixture.debugElement.query( By.css('.output-tensors') ); expect(outputTensorsElement.nativeElement.innerText).toEqual('1'); const debugTensorValuesContainers = fixture.debugElement.queryAll( By.css('.debug-tensor-values-container') ); expect(debugTensorValuesContainers.length).toEqual(0); }); it('CURT_HEALTH TensorDebugMode, One Output', () => { const fixture = TestBed.createComponent(ExecutionDataContainer); fixture.detectChanges(); store.setState( createState( createDebuggerState({ executions: { numExecutionsLoaded: { state: DataLoadState.LOADED, lastLoadedTimeInMs: 111, }, executionDigestsLoaded: { state: DataLoadState.LOADED, lastLoadedTimeInMs: 222, pageLoadedSizes: {0: 100}, numExecutions: 1000, }, executionDigests: {}, pageSize: 100, displayCount: 50, scrollBeginIndex: 90, focusIndex: 98, executionData: { 98: createTestExecutionData({ op_type: 'Inverse', tensor_debug_mode: TensorDebugMode.CURT_HEALTH, debug_tensor_values: [[-1, 1]], }), }, }, }) ) ); fixture.detectChanges(); const opTypeElement = fixture.debugElement.query(By.css('.op-type')); expect(opTypeElement.nativeElement.innerText).toEqual('Inverse'); const inputTensorsElement = fixture.debugElement.query( By.css('.input-tensors') ); expect(inputTensorsElement.nativeElement.innerText).toEqual('1'); const outputTensorsElement = fixture.debugElement.query( By.css('.output-tensors') ); expect(outputTensorsElement.nativeElement.innerText).toEqual('1'); const outputSlotElements = fixture.debugElement.queryAll( By.css('.output-slot') ); expect(outputSlotElements.length).toEqual(1); expect(outputSlotElements[0].nativeElement.innerText).toEqual('0'); const anyInfNanElements = fixture.debugElement.queryAll( By.css('.curt-health-contains-inf-nan') ); expect(anyInfNanElements.length).toEqual(1); expect(anyInfNanElements[0].nativeElement.innerText).toEqual('Yes'); }); it('CONCISE_HEALTH TensorDebugMode, Two Outputs', () => { const fixture = TestBed.createComponent(ExecutionDataContainer); fixture.detectChanges(); store.setState( createState( createDebuggerState({ executions: { numExecutionsLoaded: { state: DataLoadState.LOADED, lastLoadedTimeInMs: 111, }, executionDigestsLoaded: { state: DataLoadState.LOADED, lastLoadedTimeInMs: 222, pageLoadedSizes: {0: 100}, numExecutions: 1000, }, executionDigests: {}, pageSize: 100, displayCount: 50, scrollBeginIndex: 90, focusIndex: 98, executionData: { 98: createTestExecutionData({ op_type: 'FooOp', output_tensor_device_ids: ['d0', 'd0'], output_tensor_ids: [123, 124], tensor_debug_mode: TensorDebugMode.CONCISE_HEALTH, debug_tensor_values: [[-1, 100, 0, 0, 0], [-1, 10, 1, 2, 3]], }), }, }, }) ) ); fixture.detectChanges(); const opTypeElement = fixture.debugElement.query(By.css('.op-type')); expect(opTypeElement.nativeElement.innerText).toEqual('FooOp'); const inputTensorsElement = fixture.debugElement.query( By.css('.input-tensors') ); expect(inputTensorsElement.nativeElement.innerText).toEqual('1'); const outputTensorsElement = fixture.debugElement.query( By.css('.output-tensors') ); expect(outputTensorsElement.nativeElement.innerText).toEqual('2'); const outputSlotElements = fixture.debugElement.queryAll( By.css('.output-slot') ); expect(outputSlotElements.length).toEqual(2); expect(outputSlotElements[0].nativeElement.innerText).toEqual('0'); expect(outputSlotElements[1].nativeElement.innerText).toEqual('1'); const sizeElements = fixture.debugElement.queryAll( By.css('.concise-health-size') ); expect(sizeElements.length).toEqual(2); expect(sizeElements[0].nativeElement.innerText).toEqual('100'); expect(sizeElements[1].nativeElement.innerText).toEqual('10'); const negInfsElements = fixture.debugElement.queryAll( By.css('.concise-health-neg-infs') ); expect(negInfsElements.length).toEqual(2); expect(negInfsElements[0].nativeElement.innerText).toEqual('0'); expect(negInfsElements[1].nativeElement.innerText).toEqual('1'); const posInfsElements = fixture.debugElement.queryAll( By.css('.concise-health-pos-infs') ); expect(posInfsElements.length).toEqual(2); expect(posInfsElements[0].nativeElement.innerText).toEqual('0'); expect(posInfsElements[1].nativeElement.innerText).toEqual('2'); const nanElements = fixture.debugElement.queryAll( By.css('.concise-health-nans') ); expect(nanElements.length).toEqual(2); expect(nanElements[0].nativeElement.innerText).toEqual('0'); expect(nanElements[1].nativeElement.innerText).toEqual('3'); }); it('CONCISE_HEALTH TensorDebugMode, Two Outputs, Only One With Data', () => { const fixture = TestBed.createComponent(ExecutionDataContainer); fixture.detectChanges(); store.setState( createState( createDebuggerState({ executions: { numExecutionsLoaded: { state: DataLoadState.LOADED, lastLoadedTimeInMs: 111, }, executionDigestsLoaded: { state: DataLoadState.LOADED, lastLoadedTimeInMs: 222, pageLoadedSizes: {0: 100}, numExecutions: 1000, }, executionDigests: {}, pageSize: 100, displayCount: 50, scrollBeginIndex: 90, focusIndex: 98, executionData: { 98: createTestExecutionData({ op_type: 'BarOp', output_tensor_device_ids: ['d0', 'd0'], output_tensor_ids: [123, 124], tensor_debug_mode: TensorDebugMode.CONCISE_HEALTH, // First output slot has no data (e.g., due to non-floating // dtype). debug_tensor_values: [null, [-1, 10, 1, 2, 3]], }), }, }, }) ) ); fixture.detectChanges(); const opTypeElement = fixture.debugElement.query(By.css('.op-type')); expect(opTypeElement.nativeElement.innerText).toEqual('BarOp'); const inputTensorsElement = fixture.debugElement.query( By.css('.input-tensors') ); expect(inputTensorsElement.nativeElement.innerText).toEqual('1'); const outputTensorsElement = fixture.debugElement.query( By.css('.output-tensors') ); expect(outputTensorsElement.nativeElement.innerText).toEqual('2'); const outputSlotElements = fixture.debugElement.queryAll( By.css('.output-slot') ); expect(outputSlotElements.length).toEqual(2); expect(outputSlotElements[0].nativeElement.innerText).toEqual('0'); expect(outputSlotElements[1].nativeElement.innerText).toEqual('1'); const sizeElements = fixture.debugElement.queryAll( By.css('.concise-health-size') ); expect(sizeElements.length).toEqual(1); expect(sizeElements[0].nativeElement.innerText).toEqual('10'); const negInfsElements = fixture.debugElement.queryAll( By.css('.concise-health-neg-infs') ); expect(negInfsElements.length).toEqual(1); expect(negInfsElements[0].nativeElement.innerText).toEqual('1'); const posInfsElements = fixture.debugElement.queryAll( By.css('.concise-health-pos-infs') ); expect(posInfsElements.length).toEqual(1); expect(posInfsElements[0].nativeElement.innerText).toEqual('2'); const nanElements = fixture.debugElement.queryAll( By.css('.concise-health-nans') ); expect(nanElements.length).toEqual(1); expect(nanElements[0].nativeElement.innerText).toEqual('3'); }); it('FULL_HEALTH TensorDebugMode, One outputs', () => { const fixture = TestBed.createComponent(ExecutionDataContainer); fixture.detectChanges(); store.setState( createState( createDebuggerState({ executions: { numExecutionsLoaded: { state: DataLoadState.LOADED, lastLoadedTimeInMs: 111, }, executionDigestsLoaded: { state: DataLoadState.LOADED, lastLoadedTimeInMs: 222, pageLoadedSizes: {0: 100}, numExecutions: 1000, }, executionDigests: {}, pageSize: 100, displayCount: 50, scrollBeginIndex: 90, focusIndex: 98, executionData: { 98: createTestExecutionData({ op_type: 'FooOp', output_tensor_device_ids: ['d0'], output_tensor_ids: [123], tensor_debug_mode: TensorDebugMode.FULL_HEALTH, debug_tensor_values: [ // [tensor_id, device_id, dtype, rank, element_count, // neg_inf_count, pos_inf_count, nan_count, // neg_finite_count, zero_count, pos_finite_count]. [-1, -1, 1, 2, 6, 0, 0, 1, 2, 3, 0], ], }), }, }, }) ) ); fixture.detectChanges(); const opTypeElement = fixture.debugElement.query(By.css('.op-type')); expect(opTypeElement.nativeElement.innerText).toEqual('FooOp'); const inputTensorsElement = fixture.debugElement.query( By.css('.input-tensors') ); expect(inputTensorsElement.nativeElement.innerText).toEqual('1'); const outputTensorsElement = fixture.debugElement.query( By.css('.output-tensors') ); expect(outputTensorsElement.nativeElement.innerText).toEqual('1'); const outputSlotElements = fixture.debugElement.queryAll( By.css('.output-slot') ); expect(outputSlotElements.length).toEqual(1); expect(outputSlotElements[0].nativeElement.innerText).toEqual('0'); const dtypeElements = fixture.debugElement.queryAll( By.css('.full-health-dtype') ); expect(dtypeElements.length).toEqual(1); expect(dtypeElements[0].nativeElement.innerText).toEqual('float32'); const rankElements = fixture.debugElement.queryAll( By.css('.full-health-rank') ); expect(rankElements.length).toEqual(1); expect(rankElements[0].nativeElement.innerText).toEqual('2'); const sizeElements = fixture.debugElement.queryAll( By.css('.full-health-size') ); expect(sizeElements.length).toEqual(1); expect(sizeElements[0].nativeElement.innerText).toEqual('6'); const negInfElements = fixture.debugElement.queryAll( By.css('.full-health-neg-inf') ); expect(negInfElements.length).toEqual(1); expect(negInfElements[0].nativeElement.innerText).toEqual('0'); const posInfElements = fixture.debugElement.queryAll( By.css('.full-health-pos-inf') ); expect(posInfElements.length).toEqual(1); expect(posInfElements[0].nativeElement.innerText).toEqual('0'); const nanElements = fixture.debugElement.queryAll( By.css('.full-health-nan') ); expect(nanElements.length).toEqual(1); expect(nanElements[0].nativeElement.innerText).toEqual('1'); const negFiniteElements = fixture.debugElement.queryAll( By.css('.full-health-neg-finite') ); expect(negFiniteElements.length).toEqual(1); expect(negFiniteElements[0].nativeElement.innerText).toEqual('2'); const zeroElements = fixture.debugElement.queryAll( By.css('.full-health-zero') ); expect(zeroElements.length).toEqual(1); expect(zeroElements[0].nativeElement.innerText).toEqual('3'); const posFiniteElements = fixture.debugElement.queryAll( By.css('.full-health-pos-finite') ); expect(posFiniteElements.length).toEqual(1); expect(posFiniteElements[0].nativeElement.innerText).toEqual('0'); }); it('SHAPE TensorDebugMode, Two Outputs', () => { const fixture = TestBed.createComponent(ExecutionDataContainer); fixture.detectChanges(); store.setState( createState( createDebuggerState({ executions: { numExecutionsLoaded: { state: DataLoadState.LOADED, lastLoadedTimeInMs: 111, }, executionDigestsLoaded: { state: DataLoadState.LOADED, lastLoadedTimeInMs: 222, pageLoadedSizes: {0: 100}, numExecutions: 1000, }, executionDigests: {}, pageSize: 100, displayCount: 50, scrollBeginIndex: 90, focusIndex: 98, executionData: { 98: createTestExecutionData({ op_type: 'FooOp', output_tensor_device_ids: ['d0', 'd0'], output_tensor_ids: [123, 124], tensor_debug_mode: TensorDebugMode.SHAPE, debug_tensor_values: [ [-1, 1, 0, 1, 0, 0, 0, 0, 0, 0], // Use -1337 dtype enum value to test the unknown-dtype logic. [-1, -1337, 2, 20, 4, 5, 0, 0, 0, 0], ], }), }, }, }) ) ); fixture.detectChanges(); const opTypeElement = fixture.debugElement.query(By.css('.op-type')); expect(opTypeElement.nativeElement.innerText).toEqual('FooOp'); const inputTensorsElement = fixture.debugElement.query( By.css('.input-tensors') ); expect(inputTensorsElement.nativeElement.innerText).toEqual('1'); const outputTensorsElement = fixture.debugElement.query( By.css('.output-tensors') ); expect(outputTensorsElement.nativeElement.innerText).toEqual('2'); const outputSlotElements = fixture.debugElement.queryAll( By.css('.output-slot') ); expect(outputSlotElements.length).toEqual(2); expect(outputSlotElements[0].nativeElement.innerText).toEqual('0'); expect(outputSlotElements[1].nativeElement.innerText).toEqual('1'); const dtypeElements = fixture.debugElement.queryAll( By.css('.shape-dtype') ); expect(dtypeElements.length).toEqual(2); expect(dtypeElements[0].nativeElement.innerText).toEqual('float32'); expect(dtypeElements[1].nativeElement.innerText).toEqual('Unknown dtype'); const rankElements = fixture.debugElement.queryAll(By.css('.shape-rank')); expect(rankElements.length).toEqual(2); expect(rankElements[0].nativeElement.innerText).toEqual('0'); expect(rankElements[1].nativeElement.innerText).toEqual('2'); const sizeElements = fixture.debugElement.queryAll(By.css('.shape-size')); expect(sizeElements.length).toEqual(2); expect(sizeElements[0].nativeElement.innerText).toEqual('1'); expect(sizeElements[1].nativeElement.innerText).toEqual('20'); const shapeElements = fixture.debugElement.queryAll( By.css('.shape-shape') ); expect(shapeElements.length).toEqual(2); expect(shapeElements[0].nativeElement.innerText).toEqual('()'); expect(shapeElements[1].nativeElement.innerText).toEqual('(4,5)'); }); }); describe('Stack Trace module', () => { it('Shows non-empty stack frames correctly', () => { const fixture = TestBed.createComponent(StackTraceContainer); fixture.detectChanges(); const stackFrame0 = createTestStackFrame(); const stackFrame1 = createTestStackFrame(); const stackFrame2 = createTestStackFrame(); store.setState( createState( createDebuggerState({ executions: { numExecutionsLoaded: { state: DataLoadState.LOADED, lastLoadedTimeInMs: 111, }, executionDigestsLoaded: { state: DataLoadState.LOADED, lastLoadedTimeInMs: 222, pageLoadedSizes: {0: 100}, numExecutions: 1000, }, executionDigests: {}, pageSize: 100, displayCount: 50, scrollBeginIndex: 90, focusIndex: 98, executionData: { 98: createTestExecutionData({ stack_frame_ids: ['a0', 'a1', 'a2'], }), }, }, stackFrames: { a0: stackFrame0, a1: stackFrame1, a2: stackFrame2, }, }) ) ); fixture.detectChanges(); const hostNameElement = fixture.debugElement.query( By.css('.stack-trace-host-name') ); expect(hostNameElement.nativeElement.innerText).toEqual('(on localhost)'); const stackFrameContainers = fixture.debugElement.queryAll( By.css('.stack-frame-container') ); expect(stackFrameContainers.length).toEqual(3); const filePathElements = fixture.debugElement.queryAll( By.css('.stack-frame-file-path') ); expect(filePathElements.length).toEqual(3); expect(filePathElements[0].nativeElement.innerText).toEqual( stackFrame0[1].slice(stackFrame0[1].lastIndexOf('/') + 1) ); expect(filePathElements[0].nativeElement.title).toEqual(stackFrame0[1]); expect(filePathElements[1].nativeElement.innerText).toEqual( stackFrame1[1].slice(stackFrame1[1].lastIndexOf('/') + 1) ); expect(filePathElements[1].nativeElement.title).toEqual(stackFrame1[1]); expect(filePathElements[2].nativeElement.innerText).toEqual( stackFrame2[1].slice(stackFrame2[1].lastIndexOf('/') + 1) ); expect(filePathElements[2].nativeElement.title).toEqual(stackFrame2[1]); const linenoElements = fixture.debugElement.queryAll( By.css('.stack-frame-lineno') ); expect(linenoElements.length).toEqual(3); expect(linenoElements[0].nativeElement.innerText).toEqual( `Line ${stackFrame0[2]}:` ); expect(linenoElements[1].nativeElement.innerText).toEqual( `Line ${stackFrame1[2]}:` ); expect(linenoElements[2].nativeElement.innerText).toEqual( `Line ${stackFrame2[2]}:` ); const functionElements = fixture.debugElement.queryAll( By.css('.stack-frame-function') ); expect(functionElements.length).toEqual(3); expect(functionElements[0].nativeElement.innerText).toEqual( stackFrame0[3] ); expect(functionElements[1].nativeElement.innerText).toEqual( stackFrame1[3] ); expect(functionElements[2].nativeElement.innerText).toEqual( stackFrame2[3] ); }); it('Shows loading state when stack-trace data is unavailable', () => { const fixture = TestBed.createComponent(StackTraceContainer); fixture.detectChanges(); store.setState( createState( createDebuggerState({ executions: { numExecutionsLoaded: { state: DataLoadState.LOADED, lastLoadedTimeInMs: 111, }, executionDigestsLoaded: { state: DataLoadState.LOADED, lastLoadedTimeInMs: 222, pageLoadedSizes: {0: 100}, numExecutions: 1000, }, executionDigests: {}, pageSize: 100, displayCount: 50, scrollBeginIndex: 90, focusIndex: 98, executionData: { 98: createTestExecutionData({ stack_frame_ids: ['a0', 'a1', 'a2'], }), }, }, stackFrames: {}, // Note the empty stackFrames field. }) ) ); fixture.detectChanges(); const stackFrameContainers = fixture.debugElement.queryAll( By.css('.stack-frame-container') ); expect(stackFrameContainers.length).toEqual(0); }); }); }); <file_sep>/* Copyright 2019 The TensorFlow Authors. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ==============================================================================*/ import {TestBed, fakeAsync, tick} from '@angular/core/testing'; import {Store} from '@ngrx/store'; import {provideMockStore, MockStore} from '@ngrx/store/testing'; import {ReloaderComponent} from './reloader_component'; import {reload} from '../core/actions'; import {State} from '../core/store'; import {createState, createCoreState} from '../core/testing'; /** @typehack */ import * as _typeHackStore from '@ngrx/store'; describe('reloader_component', () => { let store: MockStore<State>; let dispatchSpy: jasmine.Spy; beforeEach(async () => { await TestBed.configureTestingModule({ providers: [ provideMockStore({ initialState: createState( createCoreState({ reloadPeriodInMs: 5, reloadEnabled: true, }) ), }), ReloaderComponent, ], declarations: [ReloaderComponent], }).compileComponents(); store = TestBed.get(Store); dispatchSpy = spyOn(store, 'dispatch'); }); it('dispatches reload action every reload period', fakeAsync(() => { store.setState( createState( createCoreState({ reloadPeriodInMs: 5, reloadEnabled: true, }) ) ); const fixture = TestBed.createComponent(ReloaderComponent); fixture.detectChanges(); expect(dispatchSpy).not.toHaveBeenCalled(); tick(5); expect(dispatchSpy).toHaveBeenCalledTimes(1); expect(dispatchSpy).toHaveBeenCalledWith(reload()); tick(5); expect(dispatchSpy).toHaveBeenCalledTimes(2); expect(dispatchSpy).toHaveBeenCalledWith(reload()); // // Manually invoke destruction of the component so we can cleanup the timer. fixture.destroy(); })); it('disables reload when it is not enabled', fakeAsync(() => { store.setState( createState( createCoreState({ reloadPeriodInMs: 5, reloadEnabled: false, }) ) ); const fixture = TestBed.createComponent(ReloaderComponent); fixture.detectChanges(); tick(10); expect(dispatchSpy).not.toHaveBeenCalled(); fixture.destroy(); })); it('respects reload period', fakeAsync(() => { store.setState( createState( createCoreState({ reloadPeriodInMs: 50, reloadEnabled: true, }) ) ); const fixture = TestBed.createComponent(ReloaderComponent); fixture.detectChanges(); expect(dispatchSpy).not.toHaveBeenCalled(); tick(5); expect(dispatchSpy).not.toHaveBeenCalled(); tick(45); expect(dispatchSpy).toHaveBeenCalledTimes(1); expect(dispatchSpy).toHaveBeenCalledWith(reload()); fixture.destroy(); })); it('only resets timer when store values changes', fakeAsync(() => { store.setState( createState( createCoreState({ reloadPeriodInMs: 5, reloadEnabled: true, }) ) ); const fixture = TestBed.createComponent(ReloaderComponent); fixture.detectChanges(); tick(4); store.setState( createState( createCoreState({ reloadPeriodInMs: 5, reloadEnabled: true, }) ) ); fixture.detectChanges(); expect(dispatchSpy).not.toHaveBeenCalled(); tick(1); expect(dispatchSpy).toHaveBeenCalledTimes(1); tick(4); store.setState( createState( createCoreState({ reloadPeriodInMs: 3, reloadEnabled: true, }) ) ); tick(1); expect(dispatchSpy).toHaveBeenCalledTimes(1); tick(2); expect(dispatchSpy).toHaveBeenCalledTimes(2); fixture.destroy(); })); }); <file_sep>#!/bin/sh # Copyright 2019 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================== # Check that any Markdown lists in IPython notebooks are preceded by a # blank line, which is required for the Google-internal docs processor # to interpret them as lists. set -e if ! [ -f WORKSPACE ]; then printf >&2 'fatal: no WORKSPACE file found (are you at TensorBoard root?)\n' exit 2 fi git ls-files -z '*.ipynb' | xargs -0 awk ' { is_list = /"([-*]|[0-9]+\.) / } is_list && !last_list && !last_blank { printf "%s:%s:%s\n", FILENAME, FNR, $0; status = 1; } { last_blank = /"\\n",/; last_list = is_list } END { exit status } ' <file_sep># Copyright 2019 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================== """Simple demo which displays constant 3D mesh.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function import os from absl import app from absl import flags import numpy as np import tensorflow.compat.v2 as tf from tensorboard.plugins.mesh import summary_v2 as mesh_summary from tensorboard.plugins.mesh import demo_utils flags.DEFINE_string( "logdir", "/tmp/mesh_demo", "Directory to write event logs to." ) flags.DEFINE_string("mesh_path", None, "Path to PLY file to visualize.") FLAGS = flags.FLAGS tf.enable_v2_behavior() # Max number of steps to run training with. _MAX_STEPS = 10 def train_step(vertices, faces, colors, config_dict, step): """Executes summary as a train step.""" # Change colors over time. t = float(step) / _MAX_STEPS transformed_colors = t * (255 - colors) + (1 - t) * colors mesh_summary.mesh( "mesh_color_tensor", vertices=vertices, faces=faces, colors=transformed_colors, config_dict=config_dict, step=step, ) def run(): """Runs training steps with a mesh summary.""" # Mesh summaries only work on TensorFlow 2.x. if int(tf.__version__.split(".")[0]) < 1: raise ImportError("TensorFlow 2.x is required to run this demo.") # Flag mesh_path is required. if FLAGS.mesh_path is None: raise ValueError( "Flag --mesh_path is required and must contain path to PLY file." ) # Camera and scene configuration. config_dict = {"camera": {"cls": "PerspectiveCamera", "fov": 75}} # Read sample PLY file. vertices, colors, faces = demo_utils.read_ascii_ply(FLAGS.mesh_path) # Add batch dimension. vertices = np.expand_dims(vertices, 0) faces = np.expand_dims(faces, 0) colors = np.expand_dims(colors, 0) # Create summary writer. writer = tf.summary.create_file_writer(FLAGS.logdir) with writer.as_default(): for step in range(_MAX_STEPS): train_step(vertices, faces, colors, config_dict, step) def main(unused_argv): print("Saving output to %s." % FLAGS.logdir) run() print("Done. Output saved to %s." % FLAGS.logdir) if __name__ == "__main__": app.run(main) <file_sep>/* Copyright 2019 The TensorFlow Authors. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ==============================================================================*/ namespace tb_plugin.lib.DO_NOT_USE_INTERNAL { const {expect} = chai; const template = document.getElementById( 'iframe-template' ) as HTMLTemplateElement; describe('plugin-util', () => { beforeEach(function(done) { const iframeFrag = document.importNode(template.content, true); const iframe = iframeFrag.firstElementChild as HTMLIFrameElement; document.body.appendChild(iframe); this.guestFrame = iframe; this.guestWindow = iframe.contentWindow; // Must wait for the JavaScript to be loaded on the child frame. this.guestWindow.addEventListener('load', () => done()); this.sandbox = sinon.sandbox.create(); }); afterEach(function() { document.body.removeChild(this.guestFrame); this.sandbox.restore(); }); it('setUp sanity check', function() { expect(this.guestWindow.plugin_internal) .to.have.property('sendMessage') .that.is.a('function'); expect(this.guestWindow.plugin_internal) .to.have.property('listen') .that.is.a('function'); expect(this.guestWindow.plugin_internal) .to.have.property('unlisten') .that.is.a('function'); }); [ { spec: 'host (src) to guest (dest)', beforeEachFunc: function() { this.destWindow = this.guestWindow; this.destListen = this.guestWindow.plugin_internal.listen; this.destUnlisten = this.guestWindow.plugin_internal.unlisten; this.destSendMessage = this.guestWindow.plugin_internal.sendMessage; this.srcSendMessage = (type, payload) => { return tb_plugin.host .broadcast(type, payload) .then(([result]) => result); }; }, }, { spec: 'guest (src) to host (dest)', beforeEachFunc: function() { this.destWindow = window; this.destListen = ( type: lib.DO_NOT_USE_INTERNAL.MessageType, callback: Function ) => { tb_plugin.host.listen(type, (context, data) => { return callback(data); }); }; this.destUnlisten = tb_plugin.host.unlisten; this.destSendMessage = ( type: lib.DO_NOT_USE_INTERNAL.MessageType, payload: lib.DO_NOT_USE_INTERNAL.PayloadType ) => { return tb_plugin.host .broadcast(type, payload) .then(([result]) => result); }; this.srcSendMessage = this.guestWindow.plugin_internal.sendMessage; }, }, ].forEach(({spec, beforeEachFunc}) => { describe(spec, () => { beforeEach(beforeEachFunc); beforeEach(function() { this.onMessage = this.sandbox.stub(); this.destListen('messageType', this.onMessage); }); it('sends a message to dest', async function() { await this.srcSendMessage('messageType', 'hello'); expect(this.onMessage.callCount).to.equal(1); expect(this.onMessage.firstCall.args).to.deep.equal(['hello']); }); it('sends a message a random payload not by ref', async function() { const payload = { foo: 'foo', bar: { baz: 'baz', }, }; await this.srcSendMessage('messageType', payload); expect(this.onMessage.callCount).to.equal(1); expect(this.onMessage.firstCall.args[0]).to.not.equal(payload); expect(this.onMessage.firstCall.args[0]).to.deep.equal(payload); }); it('resolves when dest replies with ack', async function() { const sendMessageP = this.srcSendMessage('messageType', 'hello'); expect(this.onMessage.callCount).to.equal(0); await sendMessageP; expect(this.onMessage.callCount).to.equal(1); expect(this.onMessage.firstCall.args).to.deep.equal(['hello']); }); it('triggers, on dest, a cb for the matching type', async function() { const barCb = this.sandbox.stub(); this.destListen('bar', barCb); await this.srcSendMessage('bar', 'soap'); expect(this.onMessage.callCount).to.equal(0); expect(barCb.callCount).to.equal(1); expect(barCb.firstCall.args).to.deep.equal(['soap']); }); it('supports single listener for a type', async function() { const barCb1 = this.sandbox.stub(); const barCb2 = this.sandbox.stub(); this.destListen('bar', barCb1); this.destListen('bar', barCb2); await this.srcSendMessage('bar', 'soap'); expect(barCb1.callCount).to.equal(0); expect(barCb2.callCount).to.equal(1); expect(barCb2.firstCall.args).to.deep.equal(['soap']); }); describe('dest message handling', () => { [ {specName: 'undefined', payload: null, expectDeep: false}, {specName: 'null', payload: undefined, expectDeep: false}, {specName: 'string', payload: 'something', expectDeep: false}, {specName: 'number', payload: 3.14, expectDeep: false}, {specName: 'object', payload: {some: 'object'}, expectDeep: true}, {specName: 'array', payload: ['a', 'b', 'c'], expectDeep: true}, ].forEach(({specName, payload, expectDeep}) => { it(specName, async function() { this.destListen('bar', () => payload); const response = await this.srcSendMessage('bar', 'soap'); if (expectDeep) { expect(response).to.deep.equal(payload); } else { expect(response).to.equal(payload); } }); }); }); it('unregister a callback with unlisten', async function() { const barCb = this.sandbox.stub(); this.destListen('bar', barCb); await this.srcSendMessage('bar', 'soap'); expect(barCb.callCount).to.equal(1); this.destUnlisten('bar'); await this.srcSendMessage('bar', 'soap'); expect(barCb.callCount).to.equal(1); }); it('ignores foreign postMessages', async function() { const barCb = this.sandbox.stub(); this.destListen('bar', barCb); const fakeMessage: Message = { type: 'bar', id: 0, payload: '', error: null, isReply: false, }; this.destWindow.postMessage(JSON.stringify(fakeMessage), '*'); // Await another message to ensure fake message was handled in dest. await this.srcSendMessage('not-bar'); expect(barCb).to.not.have.been.called; }); it('processes messages while waiting for a reponse', async function() { let resolveLongTask = null; this.destListen('longTask', () => { return new Promise((resolve) => { resolveLongTask = resolve; }); }); const longTaskStub = this.sandbox.stub(); const longTaskPromise = this.srcSendMessage('longTask', 'hello').then( longTaskStub ); await this.srcSendMessage('foo'); await this.destSendMessage('bar'); expect(longTaskStub).to.not.have.been.called; resolveLongTask('payload'); const longTaskResult = await longTaskPromise; expect(longTaskStub).to.have.been.calledOnce; expect(longTaskStub).to.have.been.calledWith('payload'); }); }); }); }); } // namespace tf_plugin.lib.DO_NOT_USE_INTERNAL <file_sep># Copyright 2019 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================== """A wrapper around DebugDataReader used for retrieving tfdbg v2 data.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function import threading from tensorboard import errors # Dummy run name for the debugger. # Currently, the `DebuggerV2ExperimentMultiplexer` class is tied to a single # logdir, which holds at most one DebugEvent file set in the tfdbg v2 (tfdbg2 # for short) format. # TODO(cais): When tfdbg2 allows there to be multiple DebugEvent file sets in # the same logdir, replace this magic string with actual run names. DEFAULT_DEBUGGER_RUN_NAME = "__default_debugger_run__" # Default number of alerts per monitor type. # Limiting the number of alerts is based on the consideration that usually # only the first few alerting events are the most critical and the subsequent # ones are either repetitions of the earlier ones or caused by the earlier ones. DEFAULT_PER_TYPE_ALERT_LIMIT = 1000 def run_in_background(target): """Run a target task in the background. In the context of this module, `target` is the `update()` method of the underlying reader for tfdbg2-format data. This method is mocked by unit tests for deterministic behaviors during testing. Args: target: The target task to run in the background, a callable with no args. """ # TODO(cais): Implement repetition with sleeping periods in between. # TODO(cais): Add more unit tests in debug_data_multiplexer_test.py when the # the behavior gets more complex. thread = threading.Thread(target=target) thread.start() def _alert_to_json(alert): # TODO(cais): Replace this with Alert.to_json() when supported by the # backend. from tensorflow.python.debug.lib import debug_events_monitors if isinstance(alert, debug_events_monitors.InfNanAlert): return { "alert_type": "InfNanAlert", "op_type": alert.op_type, "output_slot": alert.output_slot, # TODO(cais): Once supported by backend, add 'op_name' key # for intra-graph execution events. "size": alert.size, "num_neg_inf": alert.num_neg_inf, "num_pos_inf": alert.num_pos_inf, "num_nan": alert.num_nan, "execution_index": alert.execution_index, "graph_execution_trace_index": alert.graph_execution_trace_index, } else: raise TypeError("Unrecognized alert subtype: %s" % type(alert)) class DebuggerV2EventMultiplexer(object): """A class used for accessing tfdbg v2 DebugEvent data on local filesystem. This class is a short-term hack, mirroring the EventMultiplexer for the main TensorBoard plugins (e.g., scalar, histogram and graphs.) As such, it only implements the methods relevant to the Debugger V2 pluggin. TODO(cais): Integrate it with EventMultiplexer and use the integrated class from MultiplexerDataProvider for a single path of accessing debugger and non-debugger data. """ def __init__(self, logdir): """Constructor for the `DebugEventMultiplexer`. Args: logdir: Path to the directory to load the tfdbg v2 data from. """ self._logdir = logdir self._reader = None def FirstEventTimestamp(self, run): """Return the timestamp of the first DebugEvent of the given run. This may perform I/O if no events have been loaded yet for the run. Args: run: A string name of the run for which the timestamp is retrieved. This currently must be hardcoded as `DEFAULT_DEBUGGER_RUN_NAME`, as each logdir contains at most one DebugEvent file set (i.e., a run of a tfdbg2-instrumented TensorFlow program.) Returns: The wall_time of the first event of the run, which will be in seconds since the epoch as a `float`. """ if self._reader is None: raise ValueError("No tfdbg2 runs exists.") if run != DEFAULT_DEBUGGER_RUN_NAME: raise ValueError( "Expected run name to be %s, but got %s" % (DEFAULT_DEBUGGER_RUN_NAME, run) ) return self._reader.starting_wall_time() def PluginRunToTagToContent(self, plugin_name): raise NotImplementedError( "DebugDataMultiplexer.PluginRunToTagToContent() has not been " "implemented yet." ) def Runs(self): """Return all the run names in the `EventMultiplexer`. The `Run()` method of this class is specialized for the tfdbg2-format DebugEvent files. It only returns runs Returns: If tfdbg2-format data exists in the `logdir` of this object, returns: ``` {runName: { "debugger-v2": [tag1, tag2, tag3] } } ``` where `runName` is the hard-coded string `DEFAULT_DEBUGGER_RUN_NAME` string. This is related to the fact that tfdbg2 currently contains at most one DebugEvent file set per directory. If no tfdbg2-format data exists in the `logdir`, an empty `dict`. """ if self._reader is None: try: from tensorflow.python.debug.lib import debug_events_reader from tensorflow.python.debug.lib import debug_events_monitors self._reader = debug_events_reader.DebugDataReader(self._logdir) self._monitors = [ debug_events_monitors.InfNanMonitor( self._reader, limit=DEFAULT_PER_TYPE_ALERT_LIMIT ) ] # NOTE(cais): Currently each logdir is enforced to have only one # DebugEvent file set. So we add hard-coded default run name. run_in_background(self._reader.update) # TODO(cais): Start off a reading thread here, instead of being # called only once here. except ImportError: # This ensures graceful behavior when tensorflow install is # unavailable. return {} except AttributeError: # Gracefully fail for users without the required API changes to # debug_events_reader.DebugDataReader introduced in # TF 2.1.0.dev20200103. This should be safe to remove when # TF 2.2 is released. return {} except ValueError: # When no DebugEvent file set is found in the logdir, a # `ValueError` is thrown. return {} return { DEFAULT_DEBUGGER_RUN_NAME: { # TODO(cais): Add the semantically meaningful tag names such as # 'execution_digests_book', 'alerts_book' "debugger-v2": [] } } def _checkBeginEndIndices(self, begin, end, total_count): if begin < 0: raise errors.InvalidArgumentError( "Invalid begin index (%d)" % begin ) if end > total_count: raise errors.InvalidArgumentError( "end index (%d) out of bounds (%d)" % (end, total_count) ) if end >= 0 and end < begin: raise errors.InvalidArgumentError( "end index (%d) is unexpectedly less than begin index (%d)" % (end, begin) ) if end < 0: # This means all digests. end = total_count return end def Alerts(self, run, begin, end, alert_type_filter=None): """Get alerts from the debugged TensorFlow program. Args: run: The tfdbg2 run to get Alerts from. begin: Beginning alert index. end: Ending alert index. alert_type_filter: Optional filter string for alert type, used to restrict retrieved alerts data to a single type. If used, `begin` and `end` refer to the beginning and ending indices within the filtered alert type. """ from tensorflow.python.debug.lib import debug_events_monitors runs = self.Runs() if run not in runs: return None alerts = [] alerts_breakdown = dict() alerts_by_type = dict() for monitor in self._monitors: monitor_alerts = monitor.alerts() if not monitor_alerts: continue alerts.extend(monitor_alerts) # TODO(cais): Replace this with Alert.to_json() when # monitor.alert_type() is available. if isinstance(monitor, debug_events_monitors.InfNanMonitor): alert_type = "InfNanAlert" else: alert_type = "__MiscellaneousAlert__" alerts_breakdown[alert_type] = len(monitor_alerts) alerts_by_type[alert_type] = monitor_alerts num_alerts = len(alerts) if alert_type_filter is not None: if alert_type_filter not in alerts_breakdown: raise errors.InvalidArgumentError( "Filtering of alerts failed: alert type %s does not exist" % alert_type_filter ) alerts = alerts_by_type[alert_type_filter] end = self._checkBeginEndIndices(begin, end, len(alerts)) return { "begin": begin, "end": end, "alert_type": alert_type_filter, "num_alerts": num_alerts, "alerts_breakdown": alerts_breakdown, "per_type_alert_limit": DEFAULT_PER_TYPE_ALERT_LIMIT, "alerts": [_alert_to_json(alert) for alert in alerts[begin:end]], } def ExecutionDigests(self, run, begin, end): """Get ExecutionDigests. Args: run: The tfdbg2 run to get `ExecutionDigest`s from. begin: Beginning execution index. end: Ending execution index. Returns: A JSON-serializable object containing the `ExecutionDigest`s and related meta-information """ runs = self.Runs() if run not in runs: return None # TODO(cais): For scalability, use begin and end kwargs when available in # `DebugDataReader.execution()`.` execution_digests = self._reader.executions(digest=True) end = self._checkBeginEndIndices(begin, end, len(execution_digests)) return { "begin": begin, "end": end, "num_digests": len(execution_digests), "execution_digests": [ digest.to_json() for digest in execution_digests[begin:end] ], } def ExecutionData(self, run, begin, end): """Get Execution data objects (Detailed, non-digest form). Args: run: The tfdbg2 run to get `ExecutionDigest`s from. begin: Beginning execution index. end: Ending execution index. Returns: A JSON-serializable object containing the `ExecutionDigest`s and related meta-information """ runs = self.Runs() if run not in runs: return None # TODO(cais): For scalability, use begin and end kwargs when available in # `DebugDataReader.execution()`.` execution_digests = self._reader.executions(digest=True) end = self._checkBeginEndIndices(begin, end, len(execution_digests)) execution_digests = execution_digests[begin:end] executions = [ self._reader.read_execution(digest) for digest in execution_digests ] return { "begin": begin, "end": end, "executions": [execution.to_json() for execution in executions], } def SourceFileList(self, run): runs = self.Runs() if run not in runs: return None return self._reader.source_file_list() def SourceLines(self, run, index): runs = self.Runs() if run not in runs: return None try: host_name, file_path = self._reader.source_file_list()[index] except IndexError: raise errors.NotFoundError( "There is no source-code file at index %d" % index ) return { "host_name": host_name, "file_path": file_path, "lines": self._reader.source_lines(host_name, file_path), } def StackFrames(self, run, stack_frame_ids): runs = self.Runs() if run not in runs: return None stack_frames = [] for stack_frame_id in stack_frame_ids: if stack_frame_id not in self._reader._stack_frame_by_id: raise errors.NotFoundError( "Cannot find stack frame with ID %s" % stack_frame_id ) # TODO(cais): Use public method (`stack_frame_by_id()`) when # available. # pylint: disable=protected-access stack_frames.append(self._reader._stack_frame_by_id[stack_frame_id]) # pylint: enable=protected-access return {"stack_frames": stack_frames} <file_sep>/* Copyright 2019 The TensorFlow Authors. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ==============================================================================*/ namespace tf.graph.controls { interface DeviceNameExclude { regex: RegExp; } const DEVICE_NAME_REGEX = /device:([^:]+:[0-9]+)$/; /** * Display only devices matching one of the following regex. */ const DEVICE_NAMES_INCLUDE: DeviceNameExclude[] = [ { // Don't include GPU stream, memcpy, etc. devices regex: DEVICE_NAME_REGEX, }, ]; interface StatsDefaultOff { regex: RegExp; msg: string; // 'Excluded by default since...' } /** * Stats from device names that match these regexes will be disabled by default. * The user can still turn on a device by selecting the checkbox in the device list. */ const DEVICE_STATS_DEFAULT_OFF: StatsDefaultOff[] = []; export interface Selection { run: string; tag: string | null; type: tf.graph.SelectionType; } export interface DeviceForStats { [key: string]: boolean; } // TODO(stephanwlee): Move this to tf-graph-dashboard export interface TagItem { tag: string | null; displayName: string; conceptualGraph: boolean; opGraph: boolean; profile: boolean; } // TODO(stephanwlee): Move this to tf-graph-dashboard export interface RunItem { name: string; tags: TagItem[]; } // TODO(stephanwlee): Move this to tf-graph-dashboard export type Dataset = Array<RunItem>; interface CurrentDevice { device: string; suffix: string; used: boolean; ignoredMsg: string | null; } export enum ColorBy { COMPUTE_TIME = 'compute_time', MEMORY = 'memory', STRUCTURE = 'structure', XLA_CLUSTER = 'xla_cluster', OP_COMPATIBILITY = 'op_compatibility', } interface ColorParams { minValue: number; maxValue: number; // HEX value describing color. startColor: string; // HEX value describing color. endColor: string; } interface DeviceColor { device: string; color: string; } interface XlaClusterColor { xla_cluster: string; color: string; } // TODO(stephanwlee) Move this to tf-graph.html when it becomes TypeScript. interface ColorByParams { compute_time: ColorParams; memory: ColorParams; device: DeviceColor[]; xla_cluster: XlaClusterColor[]; } const GRADIENT_COMPATIBLE_COLOR_BY: Set<ColorBy> = new Set([ ColorBy.COMPUTE_TIME, ColorBy.MEMORY, ]); Polymer({ is: 'tf-graph-controls', properties: { // Public API. /** * @type {?tf.graph.proto.StepStats} */ stats: { value: null, type: Object, observer: '_statsChanged', }, /** * @type {?Object<string, boolean>} */ devicesForStats: { value: null, type: Object, notify: true, // TODO(stephanwlee): Change readonly -> readOnly and fix the setter. readonly: true, }, /** * @type {!tf.graph.controls.ColorBy} */ colorBy: { type: String, value: ColorBy.STRUCTURE, notify: true, }, colorByParams: { type: Object, notify: true, // TODO(stephanwlee): Change readonly -> readOnly and fix the setter. readonly: true, }, datasets: { type: Array, observer: '_datasetsChanged', value: () => [], }, /** * @type {tf.graph.render.RenderGraphInfo} */ renderHierarchy: { type: Object, }, /** * @type {!Selection} */ selection: { type: Object, notify: true, readOnly: true, computed: '_computeSelection(datasets, _selectedRunIndex, _selectedTagIndex, _selectedGraphType)', }, selectedFile: { type: Object, notify: true, }, _selectedRunIndex: { type: Number, value: 0, observer: '_selectedRunIndexChanged', }, traceInputs: { type: Boolean, notify: true, value: false, }, _selectedTagIndex: { type: Number, value: 0, observer: '_selectedTagIndexChanged', }, /** * @type {tf.graph.SelectionType} */ _selectedGraphType: { type: String, value: tf.graph.SelectionType.OP_GRAPH, }, selectedNode: { type: String, notify: true, }, _currentDevices: { type: Array, computed: '_getCurrentDevices(devicesForStats)', }, _currentDeviceParams: { type: Array, computed: '_getCurrentDeviceParams(colorByParams)', }, _currentXlaClusterParams: { type: Array, computed: '_getCurrentXlaClusterParams(colorByParams)', }, _currentGradientParams: { type: Object, computed: '_getCurrentGradientParams(colorByParams, colorBy)', }, showSessionRunsDropdown: { type: Boolean, value: true, }, showUploadButton: { type: Boolean, value: true, }, // This stores whether the feature for showing health pills is enabled in the first place. healthPillsFeatureEnabled: Boolean, // This stores whether to show health pills. Only relevant if healthPillsFeatureEnabled. The // user can toggle this value. healthPillsToggledOn: { type: Boolean, notify: true, }, _legendOpened: { type: Boolean, value: true, }, }, _xlaClustersProvided: function( renderHierarchy: tf.graph.render.RenderGraphInfo | null ) { return ( renderHierarchy && renderHierarchy.hierarchy && renderHierarchy.hierarchy.xlaClusters.length > 0 ); }, _statsChanged: function(stats: tf.graph.proto.StepStats): void { if (stats == null) { return; } var devicesForStats = {}; var devices = _.each(stats.dev_stats, function(d) { // Only considered included devices. var include = _.some(DEVICE_NAMES_INCLUDE, function(rule) { return rule.regex.test(d.device); }); // Exclude device names that are ignored by default. var exclude = _.some(DEVICE_STATS_DEFAULT_OFF, function(rule) { return rule.regex.test(d.device); }); if (include && !exclude) { devicesForStats[d.device] = true; } }); this.set('devicesForStats', devicesForStats); }, _getCurrentDevices: function( devicesForStats: DeviceForStats ): CurrentDevice[] { const stats: tf.graph.proto.StepStats | null = this.stats; const devStats: tf.graph.proto.DevStat[] = stats ? stats.dev_stats : []; const allDevices = devStats.map((d) => d.device); const devices = allDevices.filter((deviceName) => { return DEVICE_NAMES_INCLUDE.some((rule) => { return rule.regex.test(deviceName); }); }); // Devices names can be long so we remove the longest common prefix // before showing the devices in a list. const suffixes = tf.graph.util.removeCommonPrefix(devices); if (suffixes.length == 1) { const found = suffixes[0].match(DEVICE_NAME_REGEX); if (found) { suffixes[0] = found[1]; } } return devices.map((device, i) => { let ignoredMsg = null; // TODO(stephanwlee): this should probably bail on the first match or // do something useful with multiple rule.msgs. DEVICE_STATS_DEFAULT_OFF.forEach((rule) => { if (rule.regex.test(device)) { ignoredMsg = rule.msg; } }); return { device: device, suffix: suffixes[i], used: devicesForStats[device], ignoredMsg: ignoredMsg, }; }); }, _deviceCheckboxClicked: function(event: Event): void { // Update the device map. const input = event.target as HTMLInputElement; const devicesForStats: DeviceForStats = Object.assign( {}, this.devicesForStats ); const device = input.value; if (input.checked) { devicesForStats[device] = true; } else { delete devicesForStats[device]; } this.set('devicesForStats', devicesForStats); }, _numTags: function(datasets: Dataset, _selectedRunIndex: number): number { return this._getTags(datasets, _selectedRunIndex).length; }, _getTags: function( datasets: Dataset, _selectedRunIndex: number ): TagItem[] { if (!datasets || !datasets[_selectedRunIndex]) { return []; } return datasets[_selectedRunIndex].tags; }, _fit: function(): void { this.fire('fit-tap'); }, _isGradientColoring: function( stats: tf.graph.proto.StepStats, colorBy: ColorBy ): boolean { return GRADIENT_COMPATIBLE_COLOR_BY.has(colorBy) && stats != null; }, _equals: function(a: any, b: any): boolean { return a === b; }, _getCurrentDeviceParams: function( colorByParams: ColorByParams ): DeviceColor[] { const deviceParams = colorByParams.device.filter((param) => { return DEVICE_NAMES_INCLUDE.some((rule) => { return rule.regex.test(param.device); }); }); // Remove common prefix and merge back corresponding color. If // there is only one device then remove everything up to "/device:". const suffixes = tf.graph.util.removeCommonPrefix( deviceParams.map((d) => d.device) ); if (suffixes.length == 1) { var found = suffixes[0].match(DEVICE_NAME_REGEX); if (found) { suffixes[0] = found[1]; } } return deviceParams.map((d, i) => { return {device: suffixes[i], color: d.color}; }); }, _getCurrentXlaClusterParams: function( colorByParams: ColorByParams ): XlaClusterColor[] { return colorByParams.xla_cluster; }, _getCurrentGradientParams: function( colorByParams: ColorByParams, colorBy: ColorBy ): ColorParams | void { if (!this._isGradientColoring(this.stats, colorBy)) { return; } const params: ColorParams = colorByParams[colorBy]; let minValue = params.minValue; let maxValue = params.maxValue; if (colorBy === ColorBy.MEMORY) { minValue = tf.graph.util.convertUnitsToHumanReadable( minValue, tf.graph.util.MEMORY_UNITS ); maxValue = tf.graph.util.convertUnitsToHumanReadable( maxValue, tf.graph.util.MEMORY_UNITS ); } else if (colorBy === ColorBy.COMPUTE_TIME) { minValue = tf.graph.util.convertUnitsToHumanReadable( minValue, tf.graph.util.TIME_UNITS ); maxValue = tf.graph.util.convertUnitsToHumanReadable( maxValue, tf.graph.util.TIME_UNITS ); } return { minValue, maxValue, startColor: params.startColor, endColor: params.endColor, }; }, download: function(): void { this.$.graphdownload.click(); }, _updateFileInput: function(e: Event): void { const file = (e.target as HTMLInputElement).files[0]; if (!file) return; // Strip off everything before the last "/" and strip off the file // extension in order to get the name of the PNG for the graph. let filePath = file.name; const dotIndex = filePath.lastIndexOf('.'); if (dotIndex >= 0) { filePath = filePath.substring(0, dotIndex); } const lastSlashIndex = filePath.lastIndexOf('/'); if (lastSlashIndex >= 0) { filePath = filePath.substring(lastSlashIndex + 1); } this._setDownloadFilename(filePath); this.set('selectedFile', e); }, _datasetsChanged: function(newDatasets: Dataset, oldDatasets: Dataset) { if (oldDatasets != null) { // Select the first dataset by default. this._selectedRunIndex = 0; } }, _computeSelection: function( datasets: Dataset, _selectedRunIndex: number, _selectedTagIndex: number, _selectedGraphType: tf.graph.SelectionType ) { if ( !datasets[_selectedRunIndex] || !datasets[_selectedRunIndex].tags[_selectedTagIndex] ) { return null; } return { run: datasets[_selectedRunIndex].name, tag: datasets[_selectedRunIndex].tags[_selectedTagIndex].tag, type: _selectedGraphType, }; }, _selectedRunIndexChanged: function(runIndex: number): void { if (!this.datasets) return; // Reset the states when user pick a different run. this.colorBy = ColorBy.STRUCTURE; this._selectedTagIndex = 0; this._selectedGraphType = this._getDefaultSelectionType(); this.traceInputs = false; // Set trace input to off-state. this._setDownloadFilename( this.datasets[runIndex] ? this.datasets[runIndex].name : '' ); }, _selectedTagIndexChanged(): void { this._selectedGraphType = this._getDefaultSelectionType(); }, _getDefaultSelectionType(): tf.graph.SelectionType { const {datasets, _selectedRunIndex: run, _selectedTagIndex: tag} = this; if ( !datasets || !datasets[run] || !datasets[run].tags[tag] || datasets[run].tags[tag].opGraph ) { return tf.graph.SelectionType.OP_GRAPH; } if (datasets[run].tags[tag].profile) { return tf.graph.SelectionType.PROFILE; } if (datasets[run].tags[tag].conceptualGraph) { return tf.graph.SelectionType.CONCEPTUAL_GRAPH; } return tf.graph.SelectionType.OP_GRAPH; }, _getFile: function(): void { this.$$('#file').click(); }, _setDownloadFilename: function(name: string): void { this.$.graphdownload.setAttribute('download', name + '.png'); }, _statsNotNull: function(stats: tf.graph.proto.StepStats): boolean { return stats !== null; }, _toggleLegendOpen(): void { this.set('_legendOpened', !this._legendOpened); }, _getToggleText(legendOpened: boolean): string { return legendOpened ? 'Close legend.' : 'Expand legend.'; }, _getToggleLegendIcon(legendOpened: boolean): string { // This seems counter-intuitive, but actually makes sense because the // expand-more button points downwards, and the expand-less button points // upwards. For most collapsibles, this works because the collapsibles // expand in the downwards direction. This collapsible expands upwards // though, so we reverse the icons. return legendOpened ? 'expand-more' : 'expand-less'; }, _getSelectionOpGraphDisabled( datasets: Dataset, _selectedRunIndex: number, _selectedTagIndex: number ) { return ( !datasets[_selectedRunIndex] || !datasets[_selectedRunIndex].tags[_selectedTagIndex] || !datasets[_selectedRunIndex].tags[_selectedTagIndex].opGraph ); }, _getSelectionProfileDisabled( datasets: Dataset, _selectedRunIndex: number, _selectedTagIndex: number ) { return ( !datasets[_selectedRunIndex] || !datasets[_selectedRunIndex].tags[_selectedTagIndex] || !datasets[_selectedRunIndex].tags[_selectedTagIndex].profile ); }, _getSelectionConceptualGraphDisabled( datasets: Dataset, _selectedRunIndex: number, _selectedTagIndex: number ) { return ( !datasets[_selectedRunIndex] || !datasets[_selectedRunIndex].tags[_selectedTagIndex] || !datasets[_selectedRunIndex].tags[_selectedTagIndex].conceptualGraph ); }, }); } // namespace tf.graph.controls <file_sep># How to write your own plugin You can extend TensorBoard to show custom visualizations and connect to custom backends by writing a custom plugin. Clone and tinker with one of the [examples][plugin-examples], or learn about the plugin system by following the [ADDING_A_PLUGIN](./ADDING_A_PLUGIN.md) guide. Custom plugins can be [published][plugin-distribution] on PyPI to be shared with the community. Developing a custom plugin does not require Bazel or building TensorBoard. [plugin-examples]: ./tensorboard/examples/plugins [plugin-distribution]: ./ADDING_A_PLUGIN.md#distribution # How to Develop TensorBoard TensorBoard at HEAD relies on the nightly installation of TensorFlow: this allows plugin authors to use the latest features of TensorFlow, but it means release versions of TensorFlow may not suffice for development. We recommend installing TensorFlow nightly in a [Python virtualenv](https://virtualenv.pypa.io), and then running your modified development copy of TensorBoard within that virtualenv. To install TensorFlow nightly within the virtualenv, as well as TensorBoard's runtime and tooling dependencies, you can run: ```sh $ virtualenv tf $ source tf/bin/activate (tf)$ pip install --upgrade pip (tf)$ pip install tf-nightly -r tensorboard/pip_package/requirements.txt -r tensorboard/pip_package/requirements_dev.txt ``` TensorBoard builds are done with [Bazel](https://bazel.build), so you may need to [install Bazel](https://docs.bazel.build/versions/master/install.html). The Bazel build will automatically "vulcanize" all the HTML files and generate a "binary" launcher script. When HTML is vulcanized, it means all the script tags and HTML imports are inlined into one big HTML file. Then the Bazel build puts that index.html file inside a static assets zip. The python HTTP server then reads static assets from that zip while serving. You can build and run TensorBoard via Bazel (from within the TensorFlow nightly virtualenv) as follows: ```sh (tf)$ bazel run //tensorboard -- --logdir /path/to/logs ``` You may see warnings about “Limited tf.compat.v2.summary API due to missing TensorBoard installation” appear when you run TensorBoard. These are spurious: you can ignore them. (See [an explanation of why these warnings occur][why-warnings] if you’re curious.) [why-warnings]: https://github.com/tensorflow/tensorboard/issues/2968#issuecomment-558405994 For any changes to the frontend, you’ll need to install [Yarn][yarn] to lint your code (`yarn lint`, `yarn fix-lint`). You’ll also need Yarn to add or remove any NPM dependencies. For any changes to the backend, you’ll need to install [Black][black] to lint your code (run `black .`). Our `black` version is specified in `requirements_dev.txt` in this repository. Black only runs on Python 3.6 or higher, so you may want to install it into a separate virtual environment and use a [wrapper script to invoke it from any environment][black-wrapper]. You may wish to configure your editor to automatically run Prettier and Black on save. To generate fake log data for a plugin, run its demo script. For instance, this command generates fake scalar data in `/tmp/scalars_demo`: ```sh (tf)$ bazel run //tensorboard/plugins/scalar:scalars_demo ``` If you have Bazel≥0.16 and want to build any commit of TensorBoard prior to 2018-08-07, then you must first cherry-pick [pull request #1334][pr-1334] onto your working tree: ``` $ git cherry-pick bc4e7a6e5517daf918433a8f5983fc6bd239358f ``` [black]: https://github.com/psf/black [black-wrapper]: https://gist.github.com/wchargin/d65820919f363d33545159138c86ce31 [pr-1334]: https://github.com/tensorflow/tensorboard/pull/1334 [yarn]: https://yarnpkg.com/ ## Pro tips You may find the following optional tips useful for development. ### Ignoring large cleanup commits in `git blame` ```shell git config blame.ignoreRevsFile .git-blame-ignore-revs # requires Git >= 2.23 ``` We maintain a list of commits with large diffs that are known to not have any semantic effect, like mass code reformattings. As of Git 2.23, you can configure Git to ignore these commits in the output of `git blame`, so that lines are blamed to the most recent “real” change. Set the `blame.ignoreRevsFile` Git config option to `.git-blame-ignore-revs` to enable this by default, or pass `--ignore-revs-file .git-blame-ignore-revs` to enable it for a single command. When enabled by default, this also works with editor plugins like [vim-fugitive]. See `git help blame` and `git help config` for more details. [vim-fugitive]: https://github.com/tpope/vim-fugitive ### iBazel: A file watcher for Bazel. Bazel is capable of performing incremental builds where it builds only the subset of files that are impacted by file changes. However, it does not come with a file watcher. For an improved developer experience, start TensorBoard with `ibazel` instead of `bazel` which will automatically re-build and start the server when files change. If you do not have the ibazel binary on your system, you can use the command below. ```sh # Optionally run `yarn` to keep `node_modules` up-to-date. yarn run ibazel run tensorboard -- -- --logdir [LOG_DIR] ``` ### Debugging UI Tests Locally Our UI tests (e.g., //tensorboard/components/vz_sorting/test) use HTML import which is now deprecated from all browsers (Chrome 79- had the native support) and is run without any polyfills. In order to debug tests, you may want to run a a Chromium used by our CI that supports HTML import. It can be found in `./bazel-bin/third_party/chromium/chromium.out` (exact path to binary will differ by OS you are on; for Linux, the full path is `./bazel-bin/third_party/chromium/chromium.out/chrome-linux/chrome`). For example of the vz_sorting test, ```sh # Run the debug instance of the test. It should run a web server at a dynamic # port. bazel run tensorboard/components/vz_sorting/test:test_web_library # In another tab: # Fetch, if missing, the Chromium bazel build third_party/chromium ./bazel-bin/third_party/chromium/chromium.out/chrome-linux/chrome # Lastly, put the address returnd by the web server into the Chromium. ``` <file_sep>/* Copyright 2019 The TensorFlow Authors. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ==============================================================================*/ async function createIframe(): Promise<HTMLIFrameElement> { return new Promise<HTMLIFrameElement>((resolve) => { const iframe = document.createElement('iframe') as HTMLIFrameElement; document.body.appendChild(iframe); tb_plugin.host.registerPluginIframe(iframe, 'sample_plugin'); iframe.src = './testable-iframe.html?name=sample_plugin'; iframe.onload = () => resolve(iframe); }); } describe('plugin lib integration', () => { const {expect} = chai; beforeEach(async function() { this.sandbox = sinon.sandbox.create({useFakeServer: true}); this.sandbox.server.respondImmediately = true; this.iframe = await createIframe(); this.lib = (this.iframe.contentWindow as any).tb_plugin_lib.experimental; }); afterEach(function() { document.body.removeChild(this.iframe); this.sandbox.restore(); }); describe('lib.run', () => { describe('#getRuns', () => { it('returns list of runs', async function() { this.sandbox .stub(tf_backend.runsStore, 'getRuns') .returns(['foo', 'bar', 'baz']); const runs = await this.lib.runs.getRuns(); expect(runs).to.deep.equal(['foo', 'bar', 'baz']); }); }); describe('#setOnRunsChanged', () => { it('lets plugins subscribe to runs change', async function() { const runsChanged = this.sandbox.stub(); const promise = new Promise((resolve) => { this.lib.runs.setOnRunsChanged(resolve); }).then(runsChanged); this.sandbox.server.respondWith([ 200, {'Content-Type': 'application/json'}, '["foo", "bar"]', ]); await tf_backend.runsStore.refresh(); await promise; expect(runsChanged).to.have.been.calledOnce; expect(runsChanged).to.have.been.calledWith(['foo', 'bar']); }); it('lets plugins unsubscribe to runs change', async function() { const runsChanged = this.sandbox.stub(); const promise = new Promise((resolve) => { this.lib.runs.setOnRunsChanged(resolve); }).then(runsChanged); this.lib.runs.setOnRunsChanged(); this.sandbox.server.respondWith([ 200, {'Content-Type': 'application/json'}, '["foo", "bar"]', ]); await tf_backend.runsStore.refresh(); // Await another message to ensure the iframe processed the next message // (if any). await this.lib.runs.getRuns(); expect(runsChanged).to.not.have.been.called; }); }); }); describe('lib.core', () => { describe('#getURLPluginData', () => { /** * These tests use tf_globals' fake hash to make tf_storage think that the * host's URL has been updated. */ it('returns URL data', async function() { const hash = [ 'sample_plugin', 'p.sample_plugin.foo=bar', 'p.sample_plugin.foo2=bar2', ].join('&'); tf_globals.setFakeHash(hash); window.dispatchEvent(new Event('hashchange')); const data = await this.lib.core.getURLPluginData(); expect(data).to.deep.equal({ foo: 'bar', foo2: 'bar2', }); }); it('ignores unrelated URL data', async function() { const hash = [ 'sample_plugin', 'tagFilter=loss', 'p.sample_plugin.foo=bar', 'p.sample_plugin.foo=bar_from_duplicate', 'smoothing=0.5', 'p.sample_plugin.foo2=bar2', 'p.sample_plugin2.foo=bar', ].join('&'); tf_globals.setFakeHash(hash); window.dispatchEvent(new Event('hashchange')); const data = await this.lib.core.getURLPluginData(); expect(data).to.deep.equal({ foo: 'bar_from_duplicate', foo2: 'bar2', }); }); it('handles incomplete URL data', async function() { const hash = [ 'sample_plugin', 'tagFilter=loss', 'p.sample_plugin', 'p.sample_plugin.', ].join('&'); tf_globals.setFakeHash(hash); window.dispatchEvent(new Event('hashchange')); const data = await this.lib.core.getURLPluginData(); expect(data).to.deep.equal({}); }); it('handles non alphanumeric data', async function() { const hash = [ 'sample_plugin', 'p.sample_plugin.foo=bar%20baz', 'p.sample_plugin.foo2=0.123', 'p.sample_plugin.foo3=false', 'p.sample_plugin.foo4=', 'p.sample_plugin.foo5', 'p.sample_plugin.foo.with.dots=bar.dotted', ].join('&'); tf_globals.setFakeHash(hash); window.dispatchEvent(new Event('hashchange')); const data = await this.lib.core.getURLPluginData(); expect(data).to.deep.equal({ foo: 'bar baz', foo2: '0.123', foo3: 'false', foo4: '', 'foo.with.dots': 'bar.dotted', }); }); }); }); }); <file_sep># Copyright 2019 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Tests for some very basic Beholder functionality.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function import numpy as np from tensorboard.plugins import beholder from tensorboard.util import test_util import tensorflow as tf class BeholderTest(tf.test.TestCase): def setUp(self): self._current_time_seconds = 1554232353 def advance_time(self, delta_seconds): self._current_time_seconds += delta_seconds def get_time(self): return self._current_time_seconds @test_util.run_v1_only("Requires sessions") def test_update(self): with tf.test.mock.patch("time.time", self.get_time): b = beholder.Beholder(self.get_temp_dir()) array = np.array([[0, 1], [1, 0]]) with tf.Session() as sess: v = tf.Variable([0, 0], trainable=True) sess.run(tf.global_variables_initializer()) # Beholder only updates if at least one frame has passed. The # default FPS value is 10, but in any case 100 seconds ought to # do it. self.advance_time(delta_seconds=100) b.update(session=sess, arrays=[array]) if __name__ == "__main__": tf.test.main() <file_sep>/* Copyright 2019 The TensorFlow Authors. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ==============================================================================*/ module tf.graph.loader { export type GraphAndHierarchy = { graph: SlimGraph; graphHierarchy: hierarchy.Hierarchy; }; export function fetchAndConstructHierarchicalGraph( tracker: tf.graph.util.Tracker, remotePath: string | null, pbTxtFile: Blob | null, compatibilityProvider: op.CompatibilityProvider = new op.TpuCompatibilityProvider(), hierarchyParams: hierarchy.HierarchyParams = hierarchy.DefaultHierarchyParams ): Promise<GraphAndHierarchy> { const dataTracker = util.getSubtaskTracker(tracker, 30, 'Data'); const graphTracker = util.getSubtaskTracker(tracker, 20, 'Graph'); const hierarchyTracker = util.getSubtaskTracker( tracker, 50, 'Namespace hierarchy' ); return parser .fetchAndParseGraphData(remotePath, pbTxtFile, dataTracker) .then( function(graph) { if (!graph.node) { throw new Error( 'The graph is empty. This can happen when ' + 'TensorFlow could not trace any graph. Please refer to ' + 'https://github.com/tensorflow/tensorboard/issues/1961 for more ' + 'information.' ); } return build(graph, DefaultBuildParams, graphTracker); }, () => { throw new Error( 'Malformed GraphDef. This can sometimes be caused by ' + 'a bad network connection or difficulty reconciling multiple ' + 'GraphDefs; for the latter case, please refer to ' + 'https://github.com/tensorflow/tensorboard/issues/1929.' ); } ) .then(async (graph) => { // Populate compatibile field of OpNode based on whitelist op.checkOpsForCompatibility(graph, compatibilityProvider); const graphHierarchy = await hierarchy.build( graph, hierarchyParams, hierarchyTracker ); return {graph, graphHierarchy}; }) .catch((e) => { // Generic error catch, for errors that happened outside // asynchronous tasks. const msg = `Graph visualization failed.\n\n${e}`; tracker.reportError(msg, e); // Don't swallow the error. throw e; }); } } // module tf.graph.loader <file_sep>/* Copyright 2015 The TensorFlow Authors. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the 'License'); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an 'AS IS' BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ==============================================================================*/ namespace tf_tensorboard { const {expect} = chai; declare function fixture(id: string): void; declare function flush(callback: Function): void; declare const Polymer: any; declare const TEST_ONLY: any; function checkSlottedUnderAncestor(element: Element, ancestor: Element) { expect(!!element.assignedSlot).to.be.true; const slot = element.assignedSlot as Element; const isContained = Polymer.dom(ancestor).deepContains(slot); expect(isContained).to.be.true; } describe('tf-tensorboard tests', () => { window.HTMLImports.whenReady(() => { let tensorboard: any; describe('base tests', () => { beforeEach((done) => { tensorboard = fixture('tensorboardFixture'); tensorboard.demoDir = 'data'; tensorboard.autoReloadEnabled = false; flush(done); }); it('renders injected content', function() { const overview = tensorboard.querySelector('#custom-overview'); const contentPane = tensorboard.$$('#content-pane'); checkSlottedUnderAncestor(overview, contentPane); const headerItem1 = tensorboard.querySelector('#custom-header-item1'); const headerItem2 = tensorboard.querySelector('#custom-header-item2'); const header = tensorboard.$$('.header'); checkSlottedUnderAncestor(headerItem1, header); checkSlottedUnderAncestor(headerItem2, header); }); it('uses "TensorBoard-X" for title text by default', () => { const title = tensorboard.shadowRoot.querySelector('.toolbar-title'); chai.assert.equal(title.textContent, 'TensorBoard-X'); }); it('uses div for title element by default ', () => { const title = tensorboard.shadowRoot.querySelector('.toolbar-title'); chai.assert.equal(title.nodeName, 'DIV'); chai.assert.isUndefined(title.href); }); // TODO(psybuzz): Restore/remove these old tests, which fail due to broken // DOM ids that changed. Previously this folder's tests did not run. xit('reloads the active dashboard on request', (done) => { tensorboard.$.tabs.set('selected', 'scalars'); setTimeout(() => { let called = false; tensorboard._selectedDashboardComponent().reload = () => { called = true; }; tensorboard.reload(); chai.assert.isTrue(called, 'reload was called'); done(); }); }); // TODO(psybuzz): Restore/remove these old tests, which fail due to broken // DOM ids that changed. Previously this folder's tests did not run. xdescribe('top right global icons', function() { it('Clicking the reload button will call reload', function() { let called = false; tensorboard.reload = function() { called = true; }; tensorboard.$$('#reload-button').click(); chai.assert.isTrue(called); }); it('settings pane is hidden', function() { chai.assert.equal(tensorboard.$.settings.style['display'], 'none'); }); it('settings icon button opens the settings pane', function(done) { tensorboard.$$('#settings-button').click(); // This test is a little hacky since we depend on polymer's // async behavior, which is difficult to predict. // keep checking until the panel is visible. error with a timeout if it // is broken. function verify() { if (tensorboard.$.settings.style['display'] !== 'none') { done(); } else { setTimeout(verify, 3); // wait and see if it becomes true } } verify(); }); it('Autoreload checkbox toggle works', function() { let checkbox = tensorboard.$$('#auto-reload-checkbox'); chai.assert.equal(checkbox.checked, tensorboard.autoReloadEnabled); let oldValue = checkbox.checked; checkbox.click(); chai.assert.notEqual(oldValue, checkbox.checked); chai.assert.equal(checkbox.checked, tensorboard.autoReloadEnabled); }); it('Autoreload checkbox contains correct interval info', function() { let checkbox = tensorboard.$$('#auto-reload-checkbox'); let timeInSeconds = tensorboard.autoReloadIntervalSecs + 's'; chai.assert.include(checkbox.innerText, timeInSeconds); }); }); }); describe('custom path', () => { let sandbox: any; beforeEach((done) => { sandbox = sinon.sandbox.create(); sandbox.stub(TEST_ONLY.lib, 'getLocation').returns({ href: 'https://tensorboard.is/cool', origin: 'https://tensorboard.is', }); tensorboard = fixture('tensorboardFixture'); tensorboard.demoDir = 'data'; tensorboard.brand = 'Custom Brand'; tensorboard.autoReloadEnabled = false; tensorboard.homePath = '/awesome'; // Branding and other components use `dom-if` which updates the dom in an // animation frame. Flush and remove the asynchronicity. flush(done); }); afterEach(() => { sandbox.restore(); }); it('uses customized brand for title', () => { const title = tensorboard.shadowRoot.querySelector('.toolbar-title'); chai.assert.equal(title.textContent, 'Custom Brand'); }); it('uses customized path for title element ', () => { const title = tensorboard.shadowRoot.querySelector('.toolbar-title'); chai.assert.equal(title.nodeName, 'A'); chai.assert.equal(title.href, 'https://tensorboard.is/awesome'); }); it('throws when homePath is one of bad wrong protocols', () => { const expectedError1 = "Expect 'homePath' to be of http: or https:. " + 'javascript:alert("PWNED!")'; chai.assert.throws(() => { tensorboard.homePath = 'javascript:alert("PWNED!")'; }, expectedError1); const expectedError2 = "Expect 'homePath' to be of http: or https:. " + 'data:text/html,<img src="HEHE" onerror="alert(\'PWNED!\')" />'; chai.assert.throws(() => { tensorboard.homePath = 'data:text/html,<img src="HEHE" onerror="alert(\'PWNED!\')" />'; }, expectedError2); }); it('throws when homePath is not a path', () => { const expectedError1 = "Expect 'homePath' be a path or have the same origin. " + 'https://tensorboard.was/good vs. https://tensorboard.is'; chai.assert.throws(() => { tensorboard.homePath = 'https://tensorboard.was/good'; }, expectedError1); }); }); }); }); } // namespace tf_tensorboard <file_sep>/* Copyright 2020 The TensorFlow Authors. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ==============================================================================*/ import {Injectable} from '@angular/core'; import {HttpClient} from '@angular/common/http'; import {Observable} from 'rxjs'; import { DeleteOptions, GetOptions, PostOptions, PutOptions, TBHttpClientInterface, } from './tb_http_client_types'; @Injectable() export class TBHttpClient implements TBHttpClientInterface { constructor(private http: HttpClient) {} get<ResponseType>( path: string, options: GetOptions = {} ): Observable<ResponseType> { return this.http.get<ResponseType>(path, options); } post<ResponseType>( path: string, body: any, options: PostOptions = {} ): Observable<ResponseType> { return this.http.post<ResponseType>(path, body, options); } put<ResponseType>( path: string, body: any, options: PutOptions = {} ): Observable<ResponseType> { return this.http.put<ResponseType>(path, body, options); } delete<ResponseType>( path: string, options: DeleteOptions = {} ): Observable<ResponseType> { return this.http.delete<ResponseType>(path, options); } } <file_sep># What-If Tool The What-If Tool code and documentation has moved to https://github.com/pair-code/what-if-tool. The What-If Tool TensorBoard plugin has been converted to a dynamic plugin, through the tensorboard-plugin-wit pip package. <file_sep>/* Copyright 2019 The TensorFlow Authors. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ==============================================================================*/ import * as tensorWidget from '../tensor-widget'; import {TensorViewSlicingSpec, TensorView} from '../types'; import { BaseTensorNumericSummary, BooleanOrNumericTensorNumericSummary, } from '../health-pill-types'; // TODO(cais): Find a way to import tfjs-core here, instead of depending on // a global variable. declare const tf: any; /** Check horizontal and vertical ranges are fully specified in slicing spec. */ function checkSpecifiedHorizontalAndVerticalRanges( slicingSpec: TensorViewSlicingSpec, rank: number, verticalOnly = false ) { if (!verticalOnly) { if ( slicingSpec.horizontalRange === null || slicingSpec.horizontalRange[0] === null || slicingSpec.horizontalRange[1] === null ) { throw new Error( `Missing or incomplete horizontalRange range for ${rank}D tensor.` ); } } if ( slicingSpec.verticalRange === null || slicingSpec.verticalRange[0] === null || slicingSpec.verticalRange[1] === null ) { throw new Error( `Missing or incomplete verticalRange range for ${rank}D tensor.` ); } } /** * Convert a TensorFlow.js tensor to a TensorView. */ export function tensorToTensorView(x: any): tensorWidget.TensorView { // TODO(cais): Do this lazily. const buffer = x.bufferSync(); return { spec: { dtype: x.dtype as string, shape: x.shape as tensorWidget.Shape, }, get: async (...indices: number[]) => { if (indices.length !== x.rank) { throw new Error( `indices length ${indices.length} does not match ` + `rank ${x.rank}` ); } return buffer.get(...indices); }, view: async (slicingSpec: TensorViewSlicingSpec) => { if (slicingSpec.depthDim != null) { throw new Error(`depthDim view is not supported yet.`); } const slicingDims = slicingSpec.slicingDimsAndIndices.map( (dimAndIndex) => dimAndIndex.dim ); const slicingIndices = slicingSpec.slicingDimsAndIndices.map( (dimAndIndex) => { if (dimAndIndex.index === null) { throw new Error( 'Unspecified index encountered in slicing spec: ' + JSON.stringify(slicingSpec, null, 2) ); } return dimAndIndex.index; } ); const begins: number[] = []; const sizes: number[] = []; if (x.rank === 1) { checkSpecifiedHorizontalAndVerticalRanges(slicingSpec, x.rank, true); const verticalRange = slicingSpec.verticalRange as [number, number]; begins.push(verticalRange[0]); sizes.push(verticalRange[1] - verticalRange[0]); } else if (x.rank > 1) { checkSpecifiedHorizontalAndVerticalRanges(slicingSpec, x.rank); for (let i = 0; i < x.rank; ++i) { if (slicingDims.indexOf(i) !== -1) { // This is a slicing dimension. Get the slicing index. begins.push(slicingIndices[slicingDims.indexOf(i)]); sizes.push(1); } else { // This is one of the viewing dimension(s). if (slicingSpec.viewingDims.indexOf(i) === 0) { const verticalRange = slicingSpec.verticalRange as [ number, number ]; begins.push(verticalRange[0]); sizes.push(verticalRange[1] - verticalRange[0]); } else { const horizontalRange = slicingSpec.horizontalRange as [ number, number ]; begins.push(horizontalRange[0]); sizes.push(horizontalRange[1] - horizontalRange[0]); } } } } // TODO(cais): Doesn't work when slicing dimensions is not the first few // yet. const sliced = x.rank === 0 ? x : tf.tidy(() => { if (x.dtype === 'string') { // Work around the TensorFlow.js limitation that `tf.slice()` // doesn't support the string dtype yet. Remove this workaround // once this feature request is fulfilled: // https://github.com/tensorflow/tfjs/issues/2010 if (x.rank === 2) { const array = x.arraySync(); let strMatrix: string[][] = array.slice( begins[0], begins[0] + sizes[0] ); strMatrix = strMatrix.map((strArray) => strArray.slice(begins[1], begins[1] + sizes[1]) ); return tf.tensor2d(strMatrix); } else { throw new Error( `Slicing ${x.rank}D string tensor is not implemented` ); } } else { let output = x.slice(begins, sizes); if (slicingDims != null) { output = output.squeeze(slicingDims); } return output; } }); const retval = (await sliced.array()) as | boolean | number | string | boolean[][] | number[][] | string[][]; if (sliced !== x) { tf.dispose(sliced); } // TODO(cais): Check memory leak. return retval; }, getNumericSummary: async () => { if (x.dtype === 'float32' || x.dtype === 'int32' || x.dtype == 'bool') { // This is not an efficient way to compute the maximum and minimum of // finite values in a tensor. But it is okay as this is just a demo. const data = x.dataSync() as Float32Array; let minimum = Infinity; let maximum = -Infinity; for (let i = 0; i < data.length; ++i) { const value = data[i]; if (!isFinite(value)) { continue; } if (value < minimum) { minimum = value; } if (value > maximum) { maximum = value; } } return { elementCount: x.size, minimum, maximum, }; } else { return {elementCount: x.size}; } }, }; } function demo() { (document.getElementById( 'tensor-widget-version' ) as HTMLDivElement).textContent = tensorWidget.VERSION; ///////////////////////////////////////////////////////////// // float32 scalar. const tensorDiv0 = document.getElementById('tensor0') as HTMLDivElement; // TODO(cais): Replace this with a TensorFlow.js-based TensorView. const tensorView0 = tensorToTensorView(tf.scalar(28)); const tensorWidget0 = tensorWidget.tensorWidget(tensorDiv0, tensorView0, { name: 'scalar1', }); tensorWidget0.render(); ///////////////////////////////////////////////////////////// // 1D int32 tensor. const tensorDiv1 = document.getElementById('tensor1') as HTMLDivElement; // TODO(cais): Replace this with a TensorFlow.js-based TensorView. const tensorView1 = tensorToTensorView( tf.linspace(0, 190, 20).asType('int32') ); const tensorWidget1 = tensorWidget.tensorWidget(tensorDiv1, tensorView1, { name: 'Tensor1DOutputByAnOpWithAVeryLongName:0', }); tensorWidget1.render(); ///////////////////////////////////////////////////////////// // 2D float32 tensor. const tensor2Div = document.getElementById('tensor2') as HTMLDivElement; const tensorView2 = tensorToTensorView(tf.randomNormal([128, 64])); const tensorWidget2 = tensorWidget.tensorWidget(tensor2Div, tensorView2, { name: 'Float32_2D_Tensor:0', }); tensorWidget2.render(); ///////////////////////////////////////////////////////////// // 2D float32 tensor with NaN and Infinities in it. const tensorDiv3 = document.getElementById('tensor3') as HTMLDivElement; const tensorView3 = tensorToTensorView( tf.tensor2d([[NaN, -Infinity], [Infinity, 0]]) ); // const tensorView3 = tensorToTensorView(tf.tensor2d([[3, 4], [5, 6]])); const tensorWidget3 = tensorWidget.tensorWidget(tensorDiv3, tensorView3, { name: 'Tensor2D_w_badValues', }); tensorWidget3.render(); ///////////////////////////////////////////////////////////// // 3D float32 tensor, without the optional name. const tensorDiv4 = document.getElementById('tensor4') as HTMLDivElement; const tensorView4 = tensorToTensorView( tf.linspace(0, (64 * 32 * 50 - 1) / 100, 64 * 32 * 50).reshape([64, 32, 50]) ); const tensorWidget4 = tensorWidget.tensorWidget(tensorDiv4, tensorView4); // No name. tensorWidget4.render(); ///////////////////////////////////////////////////////////// // 4D float32 tensor, without the optional name. const tensorDiv5 = document.getElementById('tensor5') as HTMLDivElement; const tensorView5 = tensorToTensorView( tf .linspace(0, (2 * 4 * 15 * 20 - 1) / 100, 2 * 4 * 15 * 20) .reshape([2, 4, 15, 20]) ); const tensorWidget5 = tensorWidget.tensorWidget(tensorDiv5, tensorView5, { name: 'FourDimensionalTensor', }); tensorWidget5.render(); ///////////////////////////////////////////////////////////// // 3D boolean tensor. const tensorDiv6 = document.getElementById('tensor6') as HTMLDivElement; const tensorView6 = tensorToTensorView( tf.tensor3d([false, true, false, true, true, false, true, false], [2, 2, 2]) ); const tensorWidget6 = tensorWidget.tensorWidget(tensorDiv6, tensorView6, { name: 'booleanTensor', }); tensorWidget6.render(); ///////////////////////////////////////////////////////////// // 2D string tensor. const tensorDiv7 = document.getElementById('tensor7') as HTMLDivElement; const tensorView7 = tensorToTensorView( tf.tensor2d( [ 'Lorem', 'Жят', 'العناد', '永和九年', 'ipsum', 'ыт', 'الشمال', '岁在癸丑', 'dolor', 'жольюта', 'بزمام', '暮春之初', 'sit', 'льаорыыт', 'مهمّات,', '会于会稽山阴之兰亭', 'amet', '.', 'دارت', '修稧事也', ',', 'Ыльит', 'يكن', '群贤毕至', 'consectetur', 'компрэхэнжам', 'أي', '少长咸集', 'adipiscing', 'ад', 'حدى', '此地有崇山峻领', 'elit', 'мыа', 'من', '茂林修竹', ',', 'Фачтидёе', 'الدّفاع', '又有清流激湍', 'sed', 'атоморюм', 'ونتج', '映带左右', 'do', 'конжтетуто', 'إذ', '引以为流觞曲水', 'eiusmod', 'нэ', 'نفس', '列坐其次', 'tempor', 'хаж', 'ويكيبيديا', '', 'incididunt', ',', 'والمعدات', '', 'ut', 'ед', 'بـ', '', ], [16, 4] ) ); const tensorWidget7 = tensorWidget.tensorWidget(tensorDiv7, tensorView7, { name: 'LoremIpsum 兰亭集序', }); tensorWidget7.render(); } demo(); <file_sep># Copyright 2020 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================== """Utilities to migrate legacy summaries/events to generic data form. For legacy summaries, this populates the `SummaryMetadata.data_class` field and makes any necessary transformations to the tensor value. For `graph_def` events, this creates a new summary event. This should be effected after the `data_compat` transformation. """ from __future__ import absolute_import from __future__ import division from __future__ import print_function from tensorboard.compat.proto import event_pb2 from tensorboard.compat.proto import summary_pb2 from tensorboard.compat.proto import types_pb2 from tensorboard.plugins.graph import metadata as graphs_metadata from tensorboard.plugins.histogram import metadata as histograms_metadata from tensorboard.plugins.hparams import metadata as hparams_metadata from tensorboard.plugins.image import metadata as images_metadata from tensorboard.plugins.scalar import metadata as scalars_metadata from tensorboard.plugins.text import metadata as text_metadata from tensorboard.util import tensor_util def migrate_event(event): """Migrate an event to a sequence of events. Args: event: An `event_pb2.Event`. The caller transfers ownership of the event to this method; the event may be mutated, and may or may not appear in the returned sequence. Returns: A sequence of `event_pb2.Event`s to use instead of `event`. """ if event.HasField("graph_def"): return _migrate_graph_event(event) if event.HasField("summary"): return _migrate_summary_event(event) return (event,) def _migrate_graph_event(old_event): result = event_pb2.Event() result.wall_time = old_event.wall_time result.step = old_event.step value = result.summary.value.add(tag=graphs_metadata.RUN_GRAPH_NAME) graph_bytes = old_event.graph_def value.tensor.CopyFrom(tensor_util.make_tensor_proto([graph_bytes])) value.metadata.plugin_data.plugin_name = graphs_metadata.PLUGIN_NAME # `value.metadata.plugin_data.content` left as the empty proto value.metadata.data_class = summary_pb2.DATA_CLASS_BLOB_SEQUENCE # In the short term, keep both the old event and the new event to # maintain compatibility. return (old_event, result) def _migrate_summary_event(event): values = event.summary.value new_values = [new for old in values for new in _migrate_value(old)] # Optimization: Don't create a new event if there were no shallow # changes (there may still have been in-place changes). if len(values) == len(new_values) and all( x is y for (x, y) in zip(values, new_values) ): return (event,) del event.summary.value[:] event.summary.value.extend(new_values) return (event,) def _migrate_value(value): """Convert an old value to a stream of new values. May mutate.""" if value.metadata.data_class != summary_pb2.DATA_CLASS_UNKNOWN: return (value,) plugin_name = value.metadata.plugin_data.plugin_name if plugin_name == histograms_metadata.PLUGIN_NAME: return _migrate_histogram_value(value) if plugin_name == images_metadata.PLUGIN_NAME: return _migrate_image_value(value) if plugin_name == scalars_metadata.PLUGIN_NAME: return _migrate_scalar_value(value) if plugin_name == text_metadata.PLUGIN_NAME: return _migrate_text_value(value) if plugin_name == hparams_metadata.PLUGIN_NAME: return _migrate_hparams_value(value) return (value,) def _migrate_scalar_value(value): value.metadata.data_class = summary_pb2.DATA_CLASS_SCALAR return (value,) def _migrate_histogram_value(value): value.metadata.data_class = summary_pb2.DATA_CLASS_TENSOR return (value,) def _migrate_image_value(value): value.metadata.data_class = summary_pb2.DATA_CLASS_BLOB_SEQUENCE return (value,) def _migrate_text_value(value): value.metadata.data_class = summary_pb2.DATA_CLASS_TENSOR return (value,) def _migrate_hparams_value(value): value.metadata.data_class = summary_pb2.DATA_CLASS_TENSOR if not value.HasField("tensor"): value.tensor.CopyFrom(hparams_metadata.NULL_TENSOR) return (value,) <file_sep>/* Copyright 2017 The TensorFlow Authors. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the 'License'); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an 'AS IS' BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ==============================================================================*/ namespace tf_categorization_utils { const {assert, expect} = chai; describe('categorizationUtils', () => { const {CategoryType} = tf_categorization_utils; describe('categorizeByPrefix', () => { const {categorizeByPrefix} = tf_categorization_utils; const metadata = {type: CategoryType.PREFIX_GROUP}; it('returns empty array on empty tags', () => { assert.lengthOf(categorizeByPrefix([]), 0); }); it('handles the singleton case', () => { const input = ['a']; const actual = categorizeByPrefix(input); const expected = [ { name: 'a', metadata, items: ['a'], }, ]; assert.deepEqual(categorizeByPrefix(input), expected); }); it('handles a simple case', () => { const input = [ 'foo1/bar', 'foo1/zod', 'foo2/bar', 'foo2/zod', 'gosh/lod/mar', 'gosh/lod/ned', ]; const actual = categorizeByPrefix(input); const expected = [ {name: 'foo1', metadata, items: ['foo1/bar', 'foo1/zod']}, {name: 'foo2', metadata, items: ['foo2/bar', 'foo2/zod']}, {name: 'gosh', metadata, items: ['gosh/lod/mar', 'gosh/lod/ned']}, ]; assert.deepEqual(actual, expected); }); it('presents categories in first-occurrence order', () => { const input = ['e', 'f/1', 'g', 'a', 'f/2', 'b', 'c']; const actual = categorizeByPrefix(input); const expected = [ {name: 'e', metadata, items: ['e']}, {name: 'f', metadata, items: ['f/1', 'f/2']}, {name: 'g', metadata, items: ['g']}, {name: 'a', metadata, items: ['a']}, {name: 'b', metadata, items: ['b']}, {name: 'c', metadata, items: ['c']}, ]; assert.deepEqual(actual, expected); }); it('handles cases where category names overlap item names', () => { const input = ['a', 'a/a', 'a/b', 'a/c', 'b', 'b/a']; const actual = categorizeByPrefix(input); const expected = [ {name: 'a', metadata, items: ['a', 'a/a', 'a/b', 'a/c']}, {name: 'b', metadata, items: ['b', 'b/a']}, ]; assert.deepEqual(actual, expected); }); }); describe('categorizeBySearchQuery', () => { const {categorizeBySearchQuery} = tf_categorization_utils; const baseMetadata = { type: CategoryType.SEARCH_RESULTS, validRegex: true, universalRegex: false, }; it('properly selects just the items matching the query', () => { const query = 'cd'; const items = ['def', 'cde', 'bcd', 'abc']; const actual = categorizeBySearchQuery(items, query); const expected = { name: query, metadata: baseMetadata, items: ['cde', 'bcd'], }; assert.deepEqual(actual, expected); }); it('treats the query as a regular expression', () => { const query = 'ba(?:na){2,}s'; const items = [ 'apples', 'bananas', 'pears', 'more bananananas more fun', ]; const actual = categorizeBySearchQuery(items, query); const expected = { name: query, metadata: baseMetadata, items: ['bananas', 'more bananananas more fun'], }; assert.deepEqual(actual, expected); }); it('yields an empty category when there are no items', () => { const query = 'ba(?:na){2,}s'; const items = []; const actual = categorizeBySearchQuery(items, query); const expected = {name: query, metadata: baseMetadata, items: []}; assert.deepEqual(actual, expected); }); it('yields a universal category when the query is empty', () => { const query = ''; const items = ['apples', 'bananas', 'pears', 'bananananas']; const actual = categorizeBySearchQuery(items, query); const expected = {name: query, metadata: baseMetadata, items}; assert.deepEqual(actual, expected); }); it('notes when the query is invalid', () => { const query = ')))'; const items = ['abc', 'bar', 'zod']; const actual = categorizeBySearchQuery(items, query); const expected = { name: query, metadata: {...baseMetadata, validRegex: false}, items: [], }; assert.deepEqual(actual, expected); }); it('notes when the query is ".*"', () => { const query = '.*'; const items = ['abc', 'bar', 'zod']; const actual = categorizeBySearchQuery(items, query); const expected = { name: query, metadata: {...baseMetadata, universalRegex: true}, items, }; assert.deepEqual(actual, expected); }); }); describe('categorize', () => { const {categorize} = tf_categorization_utils; it('merges the results of the query and the prefix groups', () => { const query = 'ba(?:na){2,}s'; const items = [ 'vegetable/asparagus', 'vegetable/broccoli', 'fruit/apples', 'fruit/bananas', 'fruit/bananananas', 'fruit/pears', 'singleton', ]; const actual = categorize(items, query); const expected = [ { name: query, metadata: { type: CategoryType.SEARCH_RESULTS, validRegex: true, universalRegex: false, }, items: ['fruit/bananas', 'fruit/bananananas'], }, { name: 'vegetable', metadata: {type: CategoryType.PREFIX_GROUP}, items: ['vegetable/asparagus', 'vegetable/broccoli'], }, { name: 'fruit', metadata: {type: CategoryType.PREFIX_GROUP}, items: [ 'fruit/apples', 'fruit/bananas', 'fruit/bananananas', 'fruit/pears', ], }, { name: 'singleton', metadata: {type: CategoryType.PREFIX_GROUP}, items: ['singleton'], }, ]; assert.deepEqual(actual, expected); }); }); }); } // namespace tf_categorization_utils <file_sep># Copyright 2019 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================== import six from google.protobuf import text_format import tensorflow as tf from tensorboard.compat.proto.graph_pb2 import GraphDef from tensorboard.plugins.graph import graph_util class GraphUtilTest(tf.test.TestCase): def test_combine_graph_defs(self): expected_proto = """ node { name: "X" op: "Input" } node { name: "W" op: "Input" } node { name: "Y" op: "MatMul" input: "X" input: "W" } node { name: "A" op: "Input" } node { name: "B" op: "Input" } node { name: "C" op: "MatMul" input: "A" input: "B" } versions { producer: 21 } """ graph_def_a = GraphDef() text_format.Merge( """ node { name: "X" op: "Input" } node { name: "W" op: "Input" } node { name: "Y" op: "MatMul" input: "X" input: "W" } versions { producer: 21 } """, graph_def_a, ) graph_def_b = GraphDef() text_format.Merge( """ node { name: "A" op: "Input" } node { name: "B" op: "Input" } node { name: "C" op: "MatMul" input: "A" input: "B" } versions { producer: 21 } """, graph_def_b, ) self.assertProtoEquals( expected_proto, graph_util.combine_graph_defs(graph_def_a, graph_def_b), ) def test_combine_graph_defs_name_collided_but_same_content(self): expected_proto = """ node { name: "X" op: "Input" } node { name: "W" op: "Input" } node { name: "Y" op: "MatMul" input: "X" input: "W" } node { name: "A" op: "Input" } versions { producer: 21 } """ graph_def_a = GraphDef() text_format.Merge( """ node { name: "X" op: "Input" } node { name: "W" op: "Input" } node { name: "Y" op: "MatMul" input: "X" input: "W" } versions { producer: 21 } """, graph_def_a, ) graph_def_b = GraphDef() text_format.Merge( """ node { name: "X" op: "Input" } node { name: "A" op: "Input" } versions { producer: 21 } """, graph_def_b, ) self.assertProtoEquals( expected_proto, graph_util.combine_graph_defs(graph_def_a, graph_def_b), ) def test_combine_graph_defs_name_collided_different_content(self): graph_def_a = GraphDef() text_format.Merge( """ node { name: "X" op: "Input" } node { name: "W" op: "Input" } node { name: "Y" op: "MatMul" input: "X" input: "W" } versions { producer: 21 } """, graph_def_a, ) graph_def_b = GraphDef() text_format.Merge( """ node { name: "X" op: "Input" device: "cpu:0" } node { name: "Z" op: "Input" } node { name: "Q" op: "MatMul" input: "X" input: "Z" } versions { producer: 21 } """, graph_def_b, ) with six.assertRaisesRegex( self, ValueError, ( "Cannot combine GraphDefs because nodes share a name but " "contents are different: X" ), ): graph_util.combine_graph_defs(graph_def_a, graph_def_b) def test_combine_graph_defs_dst_nodes_duplicate_keys(self): graph_def_a = GraphDef() text_format.Merge( """ node { name: "X" op: "Input" } node { name: "X" op: "Input" } versions { producer: 21 } """, graph_def_a, ) graph_def_b = GraphDef() text_format.Merge( """ node { name: "X" op: "Input" } node { name: "Z" op: "Input" } versions { producer: 21 } """, graph_def_b, ) with six.assertRaisesRegex( self, ValueError, "A GraphDef contains non-unique node names: X" ): graph_util.combine_graph_defs(graph_def_a, graph_def_b) def test_combine_graph_defs_src_nodes_duplicate_keys(self): graph_def_a = GraphDef() text_format.Merge( """ node { name: "X" op: "Input" } node { name: "Y" op: "Input" } versions { producer: 21 } """, graph_def_a, ) graph_def_b = GraphDef() text_format.Merge( """ node { name: "W" op: "Input" device: "cpu:0" } node { name: "W" op: "Input" } versions { producer: 21 } """, graph_def_b, ) with six.assertRaisesRegex( self, ValueError, "A GraphDef contains non-unique node names: W" ): graph_util.combine_graph_defs(graph_def_a, graph_def_b) def test_combine_graph_defs_function(self): expected_proto = """ library { function { signature { name: "foo" input_arg { name: "x" type: DT_HALF } output_arg { name: "identity" type: DT_HALF } } node_def { name: "add" op: "Add" input: "x" input: "y" } } function { signature { name: "foo_1" input_arg { name: "x" type: DT_HALF } output_arg { name: "identity" type: DT_HALF } } node_def { name: "add" op: "Add" input: "x" input: "y" } } } """ graph_def_a = GraphDef() text_format.Merge( """ library { function { signature { name: "foo" input_arg { name: "x" type: DT_HALF } output_arg { name: "identity" type: DT_HALF } } node_def { name: "add" op: "Add" input: "x" input: "y" } } } """, graph_def_a, ) graph_def_b = GraphDef() text_format.Merge( """ library { function { signature { name: "foo" input_arg { name: "x" type: DT_HALF } output_arg { name: "identity" type: DT_HALF } } node_def { name: "add" op: "Add" input: "x" input: "y" } } function { signature { name: "foo_1" input_arg { name: "x" type: DT_HALF } output_arg { name: "identity" type: DT_HALF } } node_def { name: "add" op: "Add" input: "x" input: "y" } } } """, graph_def_b, ) self.assertProtoEquals( expected_proto, graph_util.combine_graph_defs(graph_def_a, graph_def_b), ) def test_combine_graph_defs_function_collison(self): graph_def_a = GraphDef() text_format.Merge( """ library { function { signature { name: "foo" input_arg { name: "x" type: DT_HALF } output_arg { name: "identity" type: DT_HALF } } node_def { name: "add" op: "Add" input: "x" input: "y" } } } """, graph_def_a, ) graph_def_b = GraphDef() text_format.Merge( """ library { function { signature { name: "foo" input_arg { name: "x" type: DT_HALF } output_arg { name: "identity" type: DT_HALF } } node_def { name: "div" op: "Div" input: "x" input: "y" } } function { signature { name: "foo_1" input_arg { name: "x" type: DT_HALF } output_arg { name: "identity" type: DT_HALF } } node_def { name: "add" op: "Add" input: "x" input: "y" } } } """, graph_def_b, ) with six.assertRaisesRegex( self, ValueError, ( "Cannot combine GraphDefs because functions share a name but " "are different: foo" ), ): graph_util.combine_graph_defs(graph_def_a, graph_def_b) def test_combine_graph_defs_dst_function_duplicate_keys(self): graph_def_a = GraphDef() text_format.Merge( """ library { function { signature { name: "foo" input_arg { name: "x" type: DT_HALF } output_arg { name: "identity" type: DT_HALF } } node_def { name: "add" op: "Add" input: "x" input: "y" } } function { signature { name: "foo" input_arg { name: "y" type: DT_HALF } output_arg { name: "identity" type: DT_HALF } } } } """, graph_def_a, ) graph_def_b = GraphDef() text_format.Merge( """ library { function { signature { name: "bar" input_arg { name: "x" type: DT_HALF } output_arg { name: "identity" type: DT_HALF } } node_def { name: "div" op: "Div" input: "x" input: "y" } } } """, graph_def_b, ) with six.assertRaisesRegex( self, ValueError, ("A GraphDef contains non-unique function names: foo"), ): graph_util.combine_graph_defs(graph_def_a, graph_def_b) def test_combine_graph_defs_src_function_duplicate_keys(self): graph_def_a = GraphDef() text_format.Merge( """ library { function { signature { name: "foo" input_arg { name: "x" type: DT_HALF } output_arg { name: "identity" type: DT_HALF } } node_def { name: "add" op: "Add" input: "x" input: "y" } } } """, graph_def_a, ) graph_def_b = GraphDef() text_format.Merge( """ library { function { signature { name: "bar" input_arg { name: "x" type: DT_HALF } output_arg { name: "identity" type: DT_HALF } } } function { signature { name: "bar" input_arg { name: "y" type: DT_HALF } output_arg { name: "identity" type: DT_HALF } } } } """, graph_def_b, ) with six.assertRaisesRegex( self, ValueError, "A GraphDef contains non-unique function names: bar", ): graph_util.combine_graph_defs(graph_def_a, graph_def_b) def test_combine_graph_defs_gradient(self): expected_proto = """ library { gradient { function_name: "foo" gradient_func: "foo_grad" } gradient { function_name: "bar" gradient_func: "bar_grad" } } """ graph_def_a = GraphDef() text_format.Merge( """ library { gradient { function_name: "foo" gradient_func: "foo_grad" } } """, graph_def_a, ) graph_def_b = GraphDef() text_format.Merge( """ library { gradient { function_name: "foo" gradient_func: "foo_grad" } gradient { function_name: "bar" gradient_func: "bar_grad" } } """, graph_def_b, ) self.assertProtoEquals( expected_proto, graph_util.combine_graph_defs(graph_def_a, graph_def_b), ) def test_combine_graph_defs_gradient_collison(self): graph_def_a = GraphDef() text_format.Merge( """ library { gradient { function_name: "foo" gradient_func: "foo_grad" } } """, graph_def_a, ) graph_def_b = GraphDef() text_format.Merge( """ library { gradient { function_name: "bar" gradient_func: "bar_grad" } gradient { function_name: "foo_1" gradient_func: "foo_grad" } } """, graph_def_b, ) with six.assertRaisesRegex( self, ValueError, ( "share a gradient_func name but map to different functions: " "foo_grad" ), ): graph_util.combine_graph_defs(graph_def_a, graph_def_b) def test_combine_graph_defs_dst_gradient_func_non_unique(self): graph_def_a = GraphDef() text_format.Merge( """ library { gradient { function_name: "foo" gradient_func: "foo_grad" } gradient { function_name: "foo_bar" gradient_func: "foo_grad" } } """, graph_def_a, ) graph_def_b = GraphDef() text_format.Merge( """ library { gradient { function_name: "bar" gradient_func: "bar_grad" } } """, graph_def_b, ) with six.assertRaisesRegex( self, ValueError, "A GraphDef contains non-unique gradient function names: foo_grad", ): graph_util.combine_graph_defs(graph_def_a, graph_def_b) def test_combine_graph_defs_src_gradient_func_non_unique(self): graph_def_a = GraphDef() text_format.Merge( """ library { gradient { function_name: "foo" gradient_func: "foo_grad" } } """, graph_def_a, ) graph_def_b = GraphDef() text_format.Merge( """ library { gradient { function_name: "bar" gradient_func: "bar_grad" } gradient { function_name: "bar_baz" gradient_func: "bar_grad" } } """, graph_def_b, ) with six.assertRaisesRegex( self, ValueError, "A GraphDef contains non-unique gradient function names: bar_grad", ): graph_util.combine_graph_defs(graph_def_a, graph_def_b) if __name__ == "__main__": tf.test.main() <file_sep># Copyright 2019 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================== """Tests for tensorboard.errors.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function from tensorboard import errors from tensorboard import test as tb_test class InvalidArgumentErrorTest(tb_test.TestCase): def test_no_details(self): e = errors.InvalidArgumentError() expected_msg = "Invalid argument" self.assertEqual(str(e), expected_msg) def test_with_details(self): e = errors.InvalidArgumentError("expected absolute path; got './foo'") expected_msg = "Invalid argument: expected absolute path; got './foo'" self.assertEqual(str(e), expected_msg) def test_http_code(self): self.assertEqual(errors.InvalidArgumentError().http_code, 400) class NotFoundErrorTest(tb_test.TestCase): def test_no_details(self): e = errors.NotFoundError() expected_msg = "Not found" self.assertEqual(str(e), expected_msg) def test_with_details(self): e = errors.NotFoundError("no scalar data for run=foo, tag=bar") expected_msg = "Not found: no scalar data for run=foo, tag=bar" self.assertEqual(str(e), expected_msg) def test_http_code(self): self.assertEqual(errors.NotFoundError().http_code, 404) class PermissionDeniedErrorTest(tb_test.TestCase): def test_no_details(self): e = errors.PermissionDeniedError() expected_msg = "Permission denied" self.assertEqual(str(e), expected_msg) def test_with_details(self): e = errors.PermissionDeniedError("this data is top secret") expected_msg = "Permission denied: this data is top secret" self.assertEqual(str(e), expected_msg) def test_http_code(self): self.assertEqual(errors.PermissionDeniedError().http_code, 403) if __name__ == "__main__": tb_test.main() <file_sep># Copyright 2019 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================== # Non-vendored runtime dependencies of TensorBoard. absl-py >= 0.4 # futures is a backport of the python 3.2+ concurrent.futures module futures >= 3.1.1; python_version < "3" grpcio >= 1.24.3 google-auth >= 1.6.3, < 2 google-auth-oauthlib >= 0.4.1, < 0.5 markdown >= 2.6.8 numpy >= 1.12.0 protobuf >= 3.6.0 requests >= 2.21.0, < 3 setuptools >= 41.0.0 six >= 1.10.0 tensorboard-plugin-wit >= 1.6.0 werkzeug >= 0.11.15 # python3 specifically requires wheel 0.26 wheel; python_version < "3" wheel >= 0.26; python_version >= "3" <file_sep>#!/bin/bash # Copyright 2019 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================== # Exposes input SVGs as definitions with filename, without extension, as the # ids. # Usage: mat_bundle_icon_svg.sh [output.svg] [in_1.svg] [in_2.svg] ... OUTPUT_PATH=$1 shift PREAMBLE='<svg><defs>' POSTAMBLE='</defs></svg>' { echo "${PREAMBLE}" for file in "$@"; do svg_id="$(basename $file | sed 's|\.svg$||g')" sed "s|<svg|<svg id=\"$svg_id\"|g" "$file" done echo "${POSTAMBLE}" } > "${OUTPUT_PATH}" <file_sep>/* Copyright 2019 The TensorFlow Authors. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ==============================================================================*/ // TODO(@andycoenen): Figure out a way to properly import the .d.ts file. // This version is currently a hand-picked subset of the API that is sufficient // for what we use. type DistanceFn = (x: Vector, y: Vector) => number; type EpochCallback = (epoch: number) => boolean | void; type Vector = number[]; type Vectors = Vector[]; interface UMAPParameters { nComponents?: number; nEpochs?: number; nNeighbors?: number; random?: () => number; } interface UMAP { new (params?: UMAPParameters): UMAP; fit(X: Vectors): number[][]; fitAsync( X: Vectors, callback?: (epochNumber: number) => void | boolean ): Promise<number[][]>; initializeFit(X: Vectors): number; setPrecomputedKNN(knnIndices: number[][], knnDistances: number[][]): void; step(): number; getEmbedding(): number[][]; } declare let UMAP: UMAP; <file_sep>/* Copyright 2017 The TensorFlow Authors. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ==============================================================================*/ /** * Implements run related plugin APIs. */ tb_plugin.host.listen('experimental.GetRuns', () => { return tf_backend.runsStore.getRuns(); }); tf_backend.runsStore.addListener(() => { return tb_plugin.host.broadcast( 'experimental.RunsChanged', tf_backend.runsStore.getRuns() ); }); <file_sep># Copyright 2019 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================== """The TensorBoard Debugger V2 plugin.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function from werkzeug import wrappers from tensorboard import errors from tensorboard import plugin_util from tensorboard.plugins import base_plugin from tensorboard.plugins.debugger_v2 import debug_data_provider from tensorboard.backend import http_util def _error_response(request, error_message): return http_util.Respond( request, {"error": error_message}, "application/json", code=400, ) def _missing_run_error_response(request): return _error_response(request, "run parameter is not provided") class DebuggerV2Plugin(base_plugin.TBPlugin): """Debugger V2 Plugin for TensorBoard.""" plugin_name = debug_data_provider.PLUGIN_NAME def __init__(self, context): """Instantiates Debugger V2 Plugin via TensorBoard core. Args: context: A base_plugin.TBContext instance. """ super(DebuggerV2Plugin, self).__init__(context) self._logdir = context.logdir # TODO(cais): Implement factory for DataProvider that takes into account # the settings. self._data_provider = debug_data_provider.LocalDebuggerV2DataProvider( self._logdir ) def get_plugin_apps(self): # TODO(cais): Add routes as they are implemented. return { "/runs": self.serve_runs, "/alerts": self.serve_alerts, "/execution/digests": self.serve_execution_digests, "/execution/data": self.serve_execution_data, "/source_files/list": self.serve_source_files_list, "/source_files/file": self.serve_source_file, "/stack_frames/stack_frames": self.serve_stack_frames, } def is_active(self): """Check whether the Debugger V2 Plugin is always active. When no data in the tfdbg v2 format is available, a custom information screen is displayed to instruct the user on how to generate such data to be able to use the plugin. Returns: `True` if and only if data in tfdbg v2's DebugEvent format is available. """ return bool(self._data_provider.list_runs("")) def frontend_metadata(self): return base_plugin.FrontendMetadata( is_ng_component=True, tab_name="Debugger V2", disable_reload=True ) @wrappers.Request.application def serve_runs(self, request): experiment = plugin_util.experiment_id(request.environ) runs = self._data_provider.list_runs(experiment) run_listing = dict() for run in runs: run_listing[run.run_id] = {"start_time": run.start_time} return http_util.Respond(request, run_listing, "application/json") @wrappers.Request.application def serve_alerts(self, request): experiment = plugin_util.experiment_id(request.environ) run = request.args.get("run") if run is None: return _missing_run_error_response(request) begin = int(request.args.get("begin", "0")) end = int(request.args.get("end", "-1")) alert_type = request.args.get("alert_type", None) run_tag_filter = debug_data_provider.alerts_run_tag_filter( run, begin, end, alert_type=alert_type ) blob_sequences = self._data_provider.read_blob_sequences( experiment, self.plugin_name, run_tag_filter=run_tag_filter ) tag = next(iter(run_tag_filter.tags)) try: return http_util.Respond( request, self._data_provider.read_blob( blob_sequences[run][tag][0].blob_key ), "application/json", ) except errors.InvalidArgumentError as e: return _error_response(request, str(e)) @wrappers.Request.application def serve_execution_digests(self, request): experiment = plugin_util.experiment_id(request.environ) run = request.args.get("run") if run is None: return _missing_run_error_response(request) begin = int(request.args.get("begin", "0")) end = int(request.args.get("end", "-1")) run_tag_filter = debug_data_provider.execution_digest_run_tag_filter( run, begin, end ) blob_sequences = self._data_provider.read_blob_sequences( experiment, self.plugin_name, run_tag_filter=run_tag_filter ) tag = next(iter(run_tag_filter.tags)) try: return http_util.Respond( request, self._data_provider.read_blob( blob_sequences[run][tag][0].blob_key ), "application/json", ) except errors.InvalidArgumentError as e: return _error_response(request, str(e)) @wrappers.Request.application def serve_execution_data(self, request): experiment = plugin_util.experiment_id(request.environ) run = request.args.get("run") if run is None: return _missing_run_error_response(request) begin = int(request.args.get("begin", "0")) end = int(request.args.get("end", "-1")) run_tag_filter = debug_data_provider.execution_data_run_tag_filter( run, begin, end ) blob_sequences = self._data_provider.read_blob_sequences( experiment, self.plugin_name, run_tag_filter=run_tag_filter ) tag = next(iter(run_tag_filter.tags)) try: return http_util.Respond( request, self._data_provider.read_blob( blob_sequences[run][tag][0].blob_key ), "application/json", ) except errors.InvalidArgumentError as e: return _error_response(request, str(e)) @wrappers.Request.application def serve_source_files_list(self, request): """Serves a list of all source files involved in the debugged program.""" experiment = plugin_util.experiment_id(request.environ) run = request.args.get("run") if run is None: return _missing_run_error_response(request) run_tag_filter = debug_data_provider.source_file_list_run_tag_filter( run ) blob_sequences = self._data_provider.read_blob_sequences( experiment, self.plugin_name, run_tag_filter=run_tag_filter ) tag = next(iter(run_tag_filter.tags)) return http_util.Respond( request, self._data_provider.read_blob(blob_sequences[run][tag][0].blob_key), "application/json", ) @wrappers.Request.application def serve_source_file(self, request): """Serves the content of a given source file. The source file is referred to by the index in the list of all source files involved in the execution of the debugged program, which is available via the `serve_source_files_list()` serving route. Args: request: HTTP request. Returns: Response to the request. """ experiment = plugin_util.experiment_id(request.environ) run = request.args.get("run") if run is None: return _missing_run_error_response(request) index = request.args.get("index") # TOOD(cais): When the need arises, support serving a subset of a # source file's lines. if index is None: return _error_response( request, "index is not provided for source file content" ) index = int(index) run_tag_filter = debug_data_provider.source_file_run_tag_filter( run, index ) blob_sequences = self._data_provider.read_blob_sequences( experiment, self.plugin_name, run_tag_filter=run_tag_filter ) tag = next(iter(run_tag_filter.tags)) try: return http_util.Respond( request, self._data_provider.read_blob( blob_sequences[run][tag][0].blob_key ), "application/json", ) except errors.NotFoundError as e: return _error_response(request, str(e)) @wrappers.Request.application def serve_stack_frames(self, request): """Serves the content of stack frames. The source frames being requested are referred to be UUIDs for each of them, separated by commas. Args: request: HTTP request. Returns: Response to the request. """ experiment = plugin_util.experiment_id(request.environ) run = request.args.get("run") if run is None: return _missing_run_error_response(request) stack_frame_ids = request.args.get("stack_frame_ids") if stack_frame_ids is None: return _error_response(request, "Missing stack_frame_ids parameter") if not stack_frame_ids: return _error_response(request, "Empty stack_frame_ids parameter") stack_frame_ids = stack_frame_ids.split(",") run_tag_filter = debug_data_provider.stack_frames_run_tag_filter( run, stack_frame_ids ) blob_sequences = self._data_provider.read_blob_sequences( experiment, self.plugin_name, run_tag_filter=run_tag_filter ) tag = next(iter(run_tag_filter.tags)) try: return http_util.Respond( request, self._data_provider.read_blob( blob_sequences[run][tag][0].blob_key ), "application/json", ) except errors.NotFoundError as e: return _error_response(request, str(e)) <file_sep># Copyright 2015 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================== """Tests for event_file_loader.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function import abc import io import os import six import tensorflow as tf from tensorboard.backend.event_processing import event_file_loader from tensorboard.compat.proto import event_pb2 from tensorboard.summary.writer import record_writer FILENAME = "test.events" @six.add_metaclass(abc.ABCMeta) class EventFileLoaderTestBase(object): def _append_record(self, data): with open(os.path.join(self.get_temp_dir(), FILENAME), "ab") as f: record_writer.RecordWriter(f).write(data) def _make_loader(self): return self._loader_class(os.path.join(self.get_temp_dir(), FILENAME)) @abc.abstractproperty def _loader_class(self): """Returns the Loader class under test.""" raise NotImplementedError() @abc.abstractmethod def assertEventWallTimes(self, load_result, event_wall_times_in_order): """Asserts that loader.Load() result has specified event wall times.""" raise NotImplementedError() def testLoad_emptyEventFile(self): with open(os.path.join(self.get_temp_dir(), FILENAME), "ab") as f: f.write(b"") loader = self._make_loader() self.assertEmpty(list(loader.Load())) def testLoad_staticEventFile(self): self._append_record(_make_event(wall_time=1.0)) self._append_record(_make_event(wall_time=2.0)) self._append_record(_make_event(wall_time=3.0)) loader = self._make_loader() self.assertEventWallTimes(loader.Load(), [1.0, 2.0, 3.0]) def testLoad_dynamicEventFile(self): self._append_record(_make_event(wall_time=1.0)) loader = self._make_loader() self.assertEventWallTimes(loader.Load(), [1.0]) self._append_record(_make_event(wall_time=2.0)) self.assertEventWallTimes(loader.Load(), [2.0]) self.assertEmpty(list(loader.Load())) def testLoad_dynamicEventFileWithTruncation(self): self._append_record(_make_event(wall_time=1.0)) self._append_record(_make_event(wall_time=2.0)) loader = self._make_loader() # Use memory file to get at the raw record to emit. with io.BytesIO() as mem_f: record_writer.RecordWriter(mem_f).write(_make_event(wall_time=3.0)) record = mem_f.getvalue() filepath = os.path.join(self.get_temp_dir(), FILENAME) with open(filepath, "ab", buffering=0) as f: # Record missing the last byte should result in data loss error # that we log and swallow. f.write(record[:-1]) self.assertEventWallTimes(loader.Load(), [1.0, 2.0]) # Retrying against the incomplete record has no effect. self.assertEmpty(list(loader.Load())) # Retrying after completing the record should return the new event. f.write(record[-1:]) self.assertEventWallTimes(loader.Load(), [3.0]) def testLoad_noIterationDoesNotConsumeEvents(self): self._append_record(_make_event(wall_time=1.0)) loader = self._make_loader() loader.Load() loader.Load() self.assertEventWallTimes(loader.Load(), [1.0]) class RawEventFileLoaderTest(EventFileLoaderTestBase, tf.test.TestCase): @property def _loader_class(self): return event_file_loader.RawEventFileLoader def assertEventWallTimes(self, load_result, event_wall_times_in_order): self.assertEqual( [ event_pb2.Event.FromString(record).wall_time for record in load_result ], event_wall_times_in_order, ) class EventFileLoaderTest(EventFileLoaderTestBase, tf.test.TestCase): @property def _loader_class(self): return event_file_loader.EventFileLoader def assertEventWallTimes(self, load_result, event_wall_times_in_order): self.assertEqual( [event.wall_time for event in load_result], event_wall_times_in_order, ) class TimestampedEventFileLoaderTest(EventFileLoaderTestBase, tf.test.TestCase): @property def _loader_class(self): return event_file_loader.TimestampedEventFileLoader def assertEventWallTimes(self, load_result, event_wall_times_in_order): transposed = list(zip(*load_result)) wall_times, events = transposed if transposed else ([], []) self.assertEqual( list(wall_times), event_wall_times_in_order, ) self.assertEqual( [event.wall_time for event in events], event_wall_times_in_order, ) def _make_event(**kwargs): return event_pb2.Event(**kwargs).SerializeToString() if __name__ == "__main__": tf.test.main() <file_sep>/* Copyright 2019 The TensorFlow Authors. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ==============================================================================*/ namespace tf.graph.loader { interface GraphRunTag { run: string; tag?: string; } Polymer({ is: 'tf-graph-dashboard-loader', _template: null, // strictTemplatePolicy requires a template (even a null one). properties: { datasets: Array, /** * @type {{value: number, msg: string}} * * A number between 0 and 100 denoting the % of progress * for the progress bar and the displayed message. */ progress: { type: Object, notify: true, }, selection: Object, /** * TODO(stephanwlee): This should be changed to take in FileList or * the prop should be changed to `fileInput`. * @type {?Event} */ selectedFile: Object, compatibilityProvider: { type: Object, value: () => new tf.graph.op.TpuCompatibilityProvider(), }, hierarchyParams: { type: Object, value: () => tf.graph.hierarchy.DefaultHierarchyParams, }, outGraphHierarchy: { type: Object, readOnly: true, //readonly so outsider can't change this via binding notify: true, }, outGraph: { type: Object, readOnly: true, //readonly so outsider can't change this via binding notify: true, }, /** @type {Object} */ outStats: { type: Object, readOnly: true, // This property produces data. notify: true, }, /** * @type {?GraphRunTag} */ _graphRunTag: Object, }, observers: [ '_selectionChanged(selection, compatibilityProvider)', '_selectedFileChanged(selectedFile, compatibilityProvider)', ], _selectionChanged(): void { // selection can change a lot within a microtask. // Don't fetch too much too fast and introduce race condition. this.debounce('selectionchange', () => { this._load(this.selection); }); }, _load: function(selection: tf.graph.controls.Selection): Promise<void> { const {run, tag, type: selectionType} = selection; switch (selectionType) { case tf.graph.SelectionType.OP_GRAPH: case tf.graph.SelectionType.CONCEPTUAL_GRAPH: { // Clear stats about the previous graph. this._setOutStats(null); const params = new URLSearchParams(); params.set('run', run); params.set( 'conceptual', String(selectionType === tf.graph.SelectionType.CONCEPTUAL_GRAPH) ); if (tag) params.set('tag', tag); const graphPath = tf_backend .getRouter() .pluginRoute('graphs', '/graph', params); return this._fetchAndConstructHierarchicalGraph(graphPath).then( () => { this._graphRunTag = {run, tag}; } ); } case tf.graph.SelectionType.PROFILE: { const {tags} = this.datasets.find(({name}) => name === run); const tagMeta = tags.find((t) => t.tag === tag); // In case current tag misses opGraph but has profile information, // we fallback to the v1 behavior of fetching the run graph. const requiredOpGraphTag = tagMeta.opGraph ? tag : null; console.assert( tags.find((t) => t.tag === requiredOpGraphTag), `Required tag (${requiredOpGraphTag}) is missing.` ); const shouldFetchGraph = !this._graphRunTag || this._graphRunTag.run !== run || this._graphRunTag.tag !== requiredOpGraphTag; const maybeFetchGraphPromise = shouldFetchGraph ? this._load({ run, tag: requiredOpGraphTag, type: tf.graph.SelectionType.OP_GRAPH, }) : Promise.resolve(); const params = new URLSearchParams(); params.set('tag', tag); params.set('run', run); const metadataPath = tf_backend .getRouter() .pluginRoute('graphs', '/run_metadata', params); return maybeFetchGraphPromise.then(() => this._readAndParseMetadata(metadataPath) ); } default: return Promise.reject( new Error(`Unknown selection type: ${selectionType}`) ); } }, _readAndParseMetadata: function(path: string): void { // Reset the progress bar to 0. this.set('progress', { value: 0, msg: '', }); var tracker = tf.graph.util.getTracker(this); tf.graph.parser.fetchAndParseMetadata(path, tracker).then((stats) => { this._setOutStats(stats); }); }, _fetchAndConstructHierarchicalGraph: async function( path: string | null, pbTxtFile?: Blob ): Promise<void> { // Reset the progress bar to 0. this.set('progress', { value: 0, msg: '', }); const tracker = tf.graph.util.getTracker(this); return tf.graph.loader .fetchAndConstructHierarchicalGraph( tracker, path, pbTxtFile, this.compatibilityProvider, this.hierarchyParams ) .then(({graph, graphHierarchy}) => { this._setOutGraph(graph); this._setOutGraphHierarchy(graphHierarchy); }); }, _selectedFileChanged: function(e: Event | null): void { if (!e) { return; } const target = e.target as HTMLInputElement; const file = target.files[0]; if (!file) { return; } // Clear out the value of the file chooser. This ensures that if the user // selects the same file, we'll re-read it. target.value = ''; this._fetchAndConstructHierarchicalGraph(null, file); }, }); } // namespace tf.graph.loader <file_sep>/* Copyright 2019 The TensorFlow Authors. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the 'License'); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an 'AS IS' BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ==============================================================================*/ namespace tf.graph.icon { export enum GraphIconType { CONST = 'CONST', META = 'META', OP = 'OP', SERIES = 'SERIES', SUMMARY = 'SUMMARY', } Polymer({ is: 'tf-graph-icon', properties: { /** * Type of node to draw. * @param {GraphIconType} */ type: String, /** Direction for series. */ vertical: { type: Boolean, value: false, }, /** * Fill for the icon, optional. If fill is specified and node is not * specified, then this value will override the default for the * element. However, if node is specified, this value will be ignored. */ fillOverride: { type: String, value: null, }, strokeOverride: { type: String, value: null, }, /** Height of the SVG element in pixels, used for scaling. */ height: { type: Number, value: 20, }, faded: { type: Boolean, value: false, }, _fill: { type: String, computed: '_computeFill(type, fillOverride)', }, _stroke: { type: String, computed: '_computeStroke(type, strokeOverride)', }, }, getSvgDefinableElement(): HTMLElement { return this.$.svgDefs; }, _computeFill(type: GraphIconType, fillOverride: string): string { if (fillOverride != null) return fillOverride; switch (type) { case GraphIconType.META: return tf.graph.render.MetanodeColors.DEFAULT_FILL; case GraphIconType.SERIES: return tf.graph.render.SeriesNodeColors.DEFAULT_FILL; default: return tf.graph.render.OpNodeColors.DEFAULT_FILL; } }, /** * Get the stroke value for the element, or if that's not possible, * return the default stroke value for the node type. */ _computeStroke(type: GraphIconType, strokeOverride): string { if (strokeOverride != null) return strokeOverride; switch (type) { case GraphIconType.META: return tf.graph.render.MetanodeColors.DEFAULT_STROKE; case GraphIconType.SERIES: return tf.graph.render.SeriesNodeColors.DEFAULT_STROKE; default: return tf.graph.render.OpNodeColors.DEFAULT_STROKE; } }, /** * Test whether the specified node's type, or the literal type string, * match a particular other type. */ _isType(type: GraphIconType, targetType: GraphIconType): boolean { return type === targetType; }, _fadedClass: function(faded: boolean, shape: string): string { return faded ? 'faded-' + shape : ''; }, }); } <file_sep>/* Copyright 2017 The TensorFlow Authors. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the 'License'); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an 'AS IS' BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ==============================================================================*/ namespace tf_paginated_view { const {expect} = chai; declare function fixture(id: string): void; type Item = { id: String; content: String; }; type ItemCategory = tf_categorization_utils.Category<Item>; function createCategory(numItems: Number): ItemCategory { const items = Array.from(Array(numItems)).map((_, i) => ({ id: `id${i}`, content: `content_${i}`, })); return { name: 'Category1', metadata: { type: tf_categorization_utils.CategoryType.PREFIX_GROUP, }, items, }; } function flushP(): Promise<void> { return new Promise((resolve) => window.flush(resolve)); } function flushAnimationFrameP(): Promise<void> { return new Promise((resolve) => window.animationFrameFlush(resolve)); } function flushAllP(): Promise<[void, void]> { return Promise.all([flushP(), flushAnimationFrameP()]); } describe('tf-paginated-view tests', () => { let view: any; /** * Returns stamped template item. */ function getItem(id: string): HTMLElement { return view.$.view.querySelector(`#${id}`); } /** * Returns element inside shadowRoot of tf-category-paginated-view. */ function querySelector(cssSelector: string): HTMLElement { return view.$.view.root.querySelector(cssSelector); } async function goNext() { querySelector('.big-page-buttons paper-button:last-of-type').click(); await flushAllP(); } beforeEach(async () => { view = fixture('paginatedViewFixture'); view._limit = 2; view.category = createCategory(5); view.randomNumber = 42; // allow dom-if to be flushed. await flushAllP(); }); it('renders a page', () => { expect(getItem('id0')).to.be.not.null; expect(getItem('id1')).to.be.not.null; // 2-4 should be in another page. expect(getItem('id2')).to.be.null; }); it('responds to ancestor prop change that is bound on template', () => { expect(getItem('id0').getAttribute('number')).to.equal('42'); view.randomNumber = 7; expect(getItem('id0').getAttribute('number')).to.equal('7'); }); it('navigates to next page when clicked on a button', async () => { // Sanity check expect(getItem('id2')).to.be.null; expect(getItem('id4')).to.be.null; expect(querySelector('paper-input')).to.have.property('value', '1'); await goNext(); expect(getItem('id1')).to.be.null; expect(getItem('id2')).to.be.not.null; expect(getItem('id3')).to.be.not.null; expect(getItem('id4')).to.be.null; expect(querySelector('paper-input')).to.have.property('value', '2'); await goNext(); expect(getItem('id3')).to.be.null; expect(getItem('id4')).to.be.not.null; expect(querySelector('paper-input')).to.have.property('value', '3'); }); it('reacts to limit change', () => { // 2-4 should be in another page, initially. expect(getItem('id2')).to.be.null; view._limit = 4; expect(getItem('id2')).to.be.not.null; expect(getItem('id3')).to.be.not.null; expect(getItem('id4')).to.be.null; }); it('reacts to category update', async () => { view.category = Object.assign({}, view.category, { items: view.category.items.slice().reverse(), }); await flushAllP(); expect(getItem('id4')).to.be.not.null; expect(getItem('id3')).to.be.not.null; }); it('reacts to items update', async () => { // Mutate the property of category in Polymeric way. view.set('category.items', view.category.items.slice().reverse()); await flushAllP(); expect(getItem('id4')).to.be.not.null; expect(getItem('id3')).to.be.not.null; }); it('handles shrinking the number of pages', async () => { view.category = createCategory(1); await flushAllP(); expect(getItem('id0')).to.be.not.null; expect(getItem('id1')).to.be.null; expect(_getPageCount()).to.equal(1); }); it('handles growing the number of pages', async () => { expect(_getPageCount()).to.equal(3); view.category = createCategory(10); await flushAllP(); expect(_getPageCount()).to.equal(5); }); it('sets all items to active=true when opened is true', () => { expect(getItem('id0').hasAttribute('active')).to.be.true; expect(getItem('id1').hasAttribute('active')).to.be.true; }); it('sets all items to active=false when opened is false', async () => { querySelector('button').click(); await flushAllP(); expect(getItem('id0').hasAttribute('active')).to.be.false; expect(getItem('id1').hasAttribute('active')).to.be.false; }); it('sets item to inactive when it is out of view', async () => { // The DOM will be removed from document but it will be updated. Hold // references to them here. const item0 = getItem('id0'); const item1 = getItem('id1'); await goNext(); expect(item0.hasAttribute('active')).to.be.false; expect(item1.hasAttribute('active')).to.be.false; expect(getItem('id2').hasAttribute('active')).to.be.true; expect(getItem('id3').hasAttribute('active')).to.be.true; }); function _getPageCount(): number { return view.$.view._pageCount; } }); } // namespace tf_paginated_view <file_sep>/* Copyright 2019 The TensorFlow Authors. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ==============================================================================*/ import {Component} from '@angular/core'; @Component({ selector: 'app-header', template: ` <mat-toolbar color="primary"> <span class="brand">TensorBoard</span> <plugin-selector class="plugins"></plugin-selector> <app-header-reload></app-header-reload> <settings-button></settings-button> <a class="readme" mat-icon-button href="https://github.com/tensorflow/tensorboard/blob/master/README.md" rel="noopener noreferrer" target="_blank" aria-label="Help" > <mat-icon svgIcon="help_outline_24px"></mat-icon> </a> </mat-toolbar> `, styles: [ ` mat-toolbar { align-items: center; display: flex; height: 64px; overflow: hidden; width: 100%; } .brand, .readme, app-header-reload, settings-button { flex: 0 0 auto; } .plugins { align-items: center; display: flex; flex: 1 1 auto; font-size: 14px; height: 100%; overflow: hidden; } `, ], }) export class HeaderComponent {} <file_sep>/* Copyright 2019 The TensorFlow Authors. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ==============================================================================*/ import {createSelector, createFeatureSelector} from '@ngrx/store'; import {findFileIndex} from './debugger_store_utils'; import { AlertsBreakdown, AlertsByIndex, AlertType, DEBUGGER_FEATURE_KEY, DebuggerRunListing, DebuggerState, Execution, ExecutionDigest, ExecutionDigestLoadState, LoadState, SourceFileContent, SourceFileSpec, StackFrame, StackFramesById, State, } from './debugger_types'; // HACK: These imports are for type inference. // https://github.com/bazelbuild/rules_nodejs/issues/1013 /** @typehack */ import * as _typeHackSelector from '@ngrx/store/src/selector'; /** @typehack */ import * as _typeHackStore from '@ngrx/store/store'; const selectDebuggerState = createFeatureSelector<State, DebuggerState>( DEBUGGER_FEATURE_KEY ); export const getDebuggerRunListing = createSelector( selectDebuggerState, (state: DebuggerState): DebuggerRunListing => { return state.runs; } ); export const getDebuggerRunsLoaded = createSelector( selectDebuggerState, (state: DebuggerState): LoadState => state.runsLoaded ); export const getActiveRunId = createSelector( selectDebuggerState, (state: DebuggerState): string | null => state.activeRunId ); export const getAlertsLoaded = createSelector( selectDebuggerState, (state: DebuggerState): LoadState => { return state.alerts.alertsLoaded; } ); export const getNumAlerts = createSelector( selectDebuggerState, (state: DebuggerState): number => { return state.alerts.numAlerts; } ); export const getAlertsFocusType = createSelector( selectDebuggerState, (state: DebuggerState): AlertType | null => { return state.alerts.focusType; } ); /** * Get number of alerts of the alert type being focused on. * * If no alert type focus exists, returns 0. * The returned number is regardless of whether the detailed Alerts * data have been loaded by the front end. */ export const getNumAlertsOfFocusedType = createSelector( selectDebuggerState, (state: DebuggerState): number => { if (state.alerts.focusType === null) { return 0; } return state.alerts.alertsBreakdown[state.alerts.focusType] || 0; } ); /** * Get the Alerts that are 1) of the type being focused on, and * 2) already loaded by the front end. * * If no alert type focus exists, returns null. */ export const getLoadedAlertsOfFocusedType = createSelector( selectDebuggerState, (state: DebuggerState): AlertsByIndex | null => { if (state.alerts.focusType === null) { return null; } if (state.alerts.alerts[state.alerts.focusType] === undefined) { return null; } return state.alerts.alerts[state.alerts.focusType]; } ); export const getAlertsBreakdown = createSelector( selectDebuggerState, (state: DebuggerState): AlertsBreakdown => { return state.alerts.alertsBreakdown; } ); export const getNumExecutionsLoaded = createSelector( selectDebuggerState, (state: DebuggerState): LoadState => { return state.executions.numExecutionsLoaded; } ); export const getExecutionDigestsLoaded = createSelector( selectDebuggerState, (state: DebuggerState): ExecutionDigestLoadState => { return state.executions.executionDigestsLoaded; } ); export const getNumExecutions = createSelector( selectDebuggerState, (state: DebuggerState): number => { return state.executions.executionDigestsLoaded.numExecutions; } ); export const getExecutionScrollBeginIndex = createSelector( selectDebuggerState, (state: DebuggerState): number => { return state.executions.scrollBeginIndex; } ); export const getExecutionPageSize = createSelector( selectDebuggerState, (state: DebuggerState): number => { return state.executions.pageSize; } ); export const getDisplayCount = createSelector( selectDebuggerState, (state: DebuggerState): number => { return state.executions.displayCount; } ); export const getVisibleExecutionDigests = createSelector( selectDebuggerState, (state: DebuggerState): Array<ExecutionDigest | null> => { const digests: Array<ExecutionDigest | null> = []; for ( let executionIndex = state.executions.scrollBeginIndex; executionIndex < state.executions.scrollBeginIndex + state.executions.displayCount; ++executionIndex ) { if (executionIndex in state.executions.executionDigests) { digests.push(state.executions.executionDigests[executionIndex]); } else { digests.push(null); } } return digests; } ); /** * Get the focused alert types (if any) of the execution digests current being * displayed. For each displayed execution digest, there are two possibilities: * - `null` represents no alert. * - An instance of the `AlertType` */ export const getFocusAlertTypesOfVisibleExecutionDigests = createSelector( selectDebuggerState, (state: DebuggerState): Array<AlertType | null> => { const beginExecutionIndex = state.executions.scrollBeginIndex; const endExecutionIndex = state.executions.scrollBeginIndex + state.executions.displayCount; const alertTypes: Array<AlertType | null> = new Array( endExecutionIndex - beginExecutionIndex ).fill(null); const focusType = state.alerts.focusType; if (focusType === null) { return alertTypes; } const executionIndices = state.alerts.executionIndices[focusType]; if (executionIndices === undefined) { return alertTypes; } // TODO(cais): Explore using a Set for execution indices if this // part becomes a performance bottleneck in the future. for (let i = beginExecutionIndex; i < endExecutionIndex; ++i) { if (executionIndices.includes(i)) { alertTypes[i - beginExecutionIndex] = state.alerts.focusType; } } return alertTypes; } ); export const getFocusedExecutionIndex = createSelector( selectDebuggerState, (state: DebuggerState): number | null => { return state.executions.focusIndex; } ); /** * Get the display index of the execution digest being focused on (if any). */ export const getFocusedExecutionDisplayIndex = createSelector( selectDebuggerState, (state: DebuggerState): number | null => { if (state.executions.focusIndex === null) { return null; } const {focusIndex, scrollBeginIndex, displayCount} = state.executions; if ( focusIndex < scrollBeginIndex || focusIndex >= scrollBeginIndex + displayCount ) { return null; } return focusIndex - scrollBeginIndex; } ); export const getLoadedExecutionData = createSelector( selectDebuggerState, (state: DebuggerState): {[index: number]: Execution} => state.executions.executionData ); export const getLoadedStackFrames = createSelector( selectDebuggerState, (state: DebuggerState): StackFramesById => state.stackFrames ); export const getFocusedExecutionData = createSelector( selectDebuggerState, (state: DebuggerState): Execution | null => { const {focusIndex, executionData} = state.executions; if (focusIndex === null || executionData[focusIndex] === undefined) { return null; } return executionData[focusIndex]; } ); /** * Get the stack trace (frames) of the execution event currently focused on * (if any). * * If no execution is focused on, returns null. * If any of the stack frames is missing (i.e., hasn't been loaded from * the data source yet), returns null. */ export const getFocusedExecutionStackFrames = createSelector( selectDebuggerState, (state: DebuggerState): StackFrame[] | null => { const {focusIndex, executionData} = state.executions; if (focusIndex === null || executionData[focusIndex] === undefined) { return null; } const stackFrameIds = executionData[focusIndex].stack_frame_ids; const stackFrames: StackFrame[] = []; for (const stackFrameId of stackFrameIds) { if (state.stackFrames[stackFrameId] != null) { stackFrames.push(state.stackFrames[stackFrameId]); } else { return null; } } return stackFrames; } ); export const getSourceFileListLoaded = createSelector( selectDebuggerState, (state: DebuggerState): LoadState => { return state.sourceCode.sourceFileListLoaded; } ); export const getSourceFileList = createSelector( selectDebuggerState, (state: DebuggerState): SourceFileSpec[] => { return state.sourceCode.sourceFileList; } ); export const getFocusedSourceFileIndex = createSelector( selectDebuggerState, (state: DebuggerState): number => { const {sourceFileList, focusLineSpec} = state.sourceCode; if (focusLineSpec === null) { return -1; } return findFileIndex(sourceFileList, focusLineSpec); } ); export const getFocusedSourceFileContent = createSelector( selectDebuggerState, getFocusedSourceFileIndex, (state: DebuggerState, fileIndex: number): SourceFileContent | null => { if (fileIndex === -1) { return null; } return state.sourceCode.fileContents[fileIndex] || null; } ); <file_sep>/* Copyright 2020 The TensorFlow Authors. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ==============================================================================*/ /** * Unit tests for the Timeline Container. */ import {TEST_ONLY} from './timeline_container'; describe('getExecutionDigestForDisplay', () => { for (const [opType, strLen, expectedShortOpType, isGraph] of [ ['MatMul', 1, 'M', false], ['MatMul', 2, 'Ma', false], ['MatMul', 3, 'Mat', false], ['MatMul', 100, 'MatMul', false], ['__inference_batchnorm_1357', 1, 'b', true], ['__forward_batchnorm_1357', 2, 'ba', true], ['__backward_attention_1357', 3, 'att', true], ['__backward_attention_1357', 99, 'attention_1357', true], ] as Array<[string, number, string, boolean]>) { it(`outputs correct results for op ${opType}, strLen=${strLen}`, () => { const display = TEST_ONLY.getExecutionDigestForDisplay( { op_type: opType, output_tensor_device_ids: ['d0'], }, strLen ); expect(display.short_op_type).toEqual(expectedShortOpType); expect(display.op_type).toEqual(opType); expect(display.is_graph).toBe(isGraph); }); } it(`outputs ellipses for unavailable op`, () => { const display = TEST_ONLY.getExecutionDigestForDisplay(null); expect(display.short_op_type).toEqual('..'); expect(display.op_type).toEqual('(N/A)'); expect(display.is_graph).toEqual(false); }); }); <file_sep>[tool.black] line-length = 80 # TODO(@wchargin): Drop `py35` here once we drop support for Python 3.5 # and aren't affected by <https://bugs.python.org/issue9232>. target-version = ["py27", "py35", "py36", "py37", "py38"] <file_sep>/* Copyright 2019 The TensorFlow Authors. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ==============================================================================*/ import { ChangeDetectionStrategy, Component, Input, OnChanges, SimpleChanges, OnInit, OnDestroy, Output, EventEmitter, } from '@angular/core'; export enum ChangedProp { ACTIVE_PLUGIN, } // TODO(tensorboard-team): remove below when storage.ts is pure TypeScript // module. const TAB = '__tab__'; interface TfGlobalsElement extends HTMLElement { tf_globals: { setUseHash(use: boolean): void; }; } interface SetStringOption { defaultValue?: string; useLocationReplace?: boolean; } interface TfStorageElement extends HTMLElement { tf_storage: { setString(key: string, value: string, options: SetStringOption): void; getString(key: string): string; }; } @Component({ selector: 'hash-storage-component', template: '', changeDetection: ChangeDetectionStrategy.OnPush, }) export class HashStorageComponent implements OnInit, OnChanges, OnDestroy { private readonly tfGlobals = (document.createElement( 'tf-globals' ) as TfGlobalsElement).tf_globals; private readonly tfStorage = (document.createElement( 'tf-storage' ) as TfStorageElement).tf_storage; private readonly onHashChange = this.onHashChangedImpl.bind(this); @Input() activePluginId!: string; @Output() onValueChange = new EventEmitter<{prop: ChangedProp; value: string}>(); private onHashChangedImpl() { const activePluginId = this.tfStorage.getString(TAB); if (activePluginId !== this.activePluginId) { this.onValueChange.emit({ prop: ChangedProp.ACTIVE_PLUGIN, value: activePluginId, }); } } ngOnInit() { // As opposed to fake hash that does not modify the URL. this.tfGlobals.setUseHash(true); // Cannot use the tf_storage hash listener because it binds to event before the // zone.js patch. According to [1], zone.js patches various asynchronos calls and // event listeners to detect "changes" and mark components as dirty for re-render. // When using tf_storage hash listener, it causes bad renders in Angular due to // missing dirtiness detection. // [1]: https://blog.angular-university.io/how-does-angular-2-change-detection-really-work/ window.addEventListener('hashchange', this.onHashChange); } ngOnDestroy() { window.removeEventListener('hashchange', this.onHashChange); } ngOnChanges(changes: SimpleChanges) { if (changes['activePluginId']) { const activePluginIdChange = changes['activePluginId']; const option: SetStringOption = {}; if (activePluginIdChange.firstChange) { option.useLocationReplace = true; } this.tfStorage.setString(TAB, activePluginIdChange.currentValue, option); } } }
6a60147e471d429df03b9a2a1d9ebe8217df1667
[ "JavaScript", "Markdown", "TOML", "Python", "Text", "TypeScript", "Shell" ]
47
TypeScript
DebeshJha/tensorboard
bd388e98c6ce605f8090f19da37c4d97fc5c2ae4
7539174c811b11f9215e3a1b1e57df394d22fdde
refs/heads/master
<file_sep>// // ContentView.swift // Time Lines // // Created by <NAME> on 02/04/2020. // Copyright © 2020 <NAME>. All rights reserved. // import SwiftUI import TimeLineShared import CoreLocation enum AlertType { case noProducts case cantBuy case cantRestore case didRestore case upsell } struct MeRow: View { @Environment(\.editMode) var editMode var contacts: FetchedResults<Contact> private let currentTimeZone = TimeZone.autoupdatingCurrent private let roughLocation = TimeZone.autoupdatingCurrent.roughLocation var body: some View { Group { if editMode?.wrappedValue == EditMode.inactive || contacts.count == 0 { ContactRow( name: "Me", timezone: currentTimeZone, coordinate: roughLocation ).padding(.trailing, 15) } } } } struct BindedContactRow: View { @Environment(\.editMode) var editMode @EnvironmentObject var routeState: RouteState var contact: Contact @Binding var search: String @Binding var searchTokens: [Tag] var destination: some View { ContactDetails(contact: contact, onSelectTag: { tag, presentationMode in self.routeState.navigate(.list) presentationMode.dismiss() self.searchTokens = [tag] self.search = "" }, editView: { Button(action: { self.routeState.navigate(.editContact(contact: self.contact)) }) { Text("Edit") } .padding(.init(top: 10, leading: 15, bottom: 10, trailing: 15)) .background(Color(UIColor.systemBackground)) .cornerRadius(5) }) } var body: some View { NavigationLink(destination: destination, tag: contact, selection: $routeState.contactDetailed) { ContactRow( name: contact.name ?? "", timezone: contact.timeZone, coordinate: contact.location, startTime: contact.startTime, endTime: contact.endTime, hideLine: editMode?.wrappedValue == .active ) }.onAppear(perform: { self.contact.refreshTimeZone() }) } } struct ContentView: View { @Environment(\.managedObjectContext) var context @Environment(\.inAppPurchaseContext) var iapManager @EnvironmentObject var routeState: RouteState @FetchRequest( entity: Contact.entity(), sortDescriptors: [NSSortDescriptor(keyPath: \Contact.index, ascending: true)] ) var contacts: FetchedResults<Contact> @State private var showingSheet = false @State private var showingRestoreAlert = false @State private var showingAlert = false @State private var alertType: AlertType? @State private var errorMessage: String? @State private var search = "" @State private var searchTokens: [Tag] = [] var addNewContact: some View { Button(action: { if (!self.iapManager.hasAlreadyPurchasedUnlimitedContacts && self.contacts.count >= self.iapManager.contactsLimit) { self.showAlert(.upsell) } else { self.routeState.navigate(.editContact(contact: nil)) } }) { HStack { Image(systemName: "plus").padding() Text("Add a new contact") } }.disabled(!iapManager.hasAlreadyPurchasedUnlimitedContacts && !iapManager.canBuy()) } var body: some View { NavigationView { List { SearchBar(search: $search, tokens: $searchTokens) if search.count == 0 { addNewContact.foregroundColor(Color(UIColor.secondaryLabel)) } MeRow(contacts: contacts) ForEach(contacts.filter { filterContact($0) }, id: \Contact.name) { (contact: Contact) in BindedContactRow(contact: contact, search: self.$search, searchTokens: self.$searchTokens) } .onDelete(perform: self.deleteContact) .onMove(perform: self.moveContact) } .resignKeyboardOnDragGesture() .navigationBarTitle(Text("Contacts")) .navigationBarItems(leading: contacts.count > 0 ? EditButton() : nil, trailing: Button(action: { self.showingSheet = true }) { Image(systemName: "person").padding() } .actionSheet(isPresented: $showingSheet) { ActionSheet(title: Text("Settings"), buttons: [ .default(Text("Manage Tags"), action: { self.routeState.navigate(.tags) }), .default(Text("Send Feedback"), action: { UIApplication.shared.open(App.feedbackPage) }), .default(Text("Restore Purchases"), action: tryAgainRestore), .cancel() ]) }) .alert(isPresented: $showingAlert) { switch self.alertType { case .noProducts: return Alert( title: Text("Error while trying to get the In App Purchases"), message: Text(self.errorMessage ?? "Seems like there was an issue with the Apple's servers."), primaryButton: .cancel(Text("Cancel"), action: self.dismissAlert), secondaryButton: .default(Text("Try Again"), action: self.tryAgainBuyWithNoProduct) ) case .cantBuy: return Alert( title: Text("Error while trying to purchase the product"), message: Text(self.errorMessage ?? "Seems like there was an issue with the Apple's servers."), primaryButton: .cancel(Text("Cancel"), action: self.dismissAlert), secondaryButton: .default(Text("Try Again"), action: self.tryAgainBuy) ) case .cantRestore: return Alert( title: Text(self.errorMessage ?? "Error while trying to restore the purchases"), primaryButton: .cancel(Text("Cancel"), action: self.dismissAlert), secondaryButton: .default(Text("Try Again"), action: self.tryAgainRestore) ) case .didRestore: return Alert(title: Text("Purchases restored successfully!"), dismissButton: .default(Text("OK"))) case .upsell: return Alert( title: Text("You've reached the limit of the free Time Lines version"), message: Text("Unlock the full version to add an unlimited number of contacts."), primaryButton: .default(Text("Unlock Full Version"), action: self.tryAgainBuy), secondaryButton: .cancel(Text("Cancel"), action: self.dismissAlert) ) case nil: return Alert(title: Text("Unknown Error"), dismissButton: .default(Text("OK"))) } } // default view on iPad if contacts.count > 0 { ContactDetails(contact: contacts[0]) { Button(action: { self.routeState.navigate(.editContact(contact: self.contacts[0])) }) { Text("Edit") } .padding(.init(top: 10, leading: 15, bottom: 10, trailing: 15)) .background(Color(UIColor.systemBackground)) .cornerRadius(5) } } else { VStack { Text("Get started by adding a new contact") addNewContact.padding(.trailing, 20).foregroundColor(Color.accentColor).border(Color.accentColor) } } }.sheet(isPresented: self.$routeState.isShowingSheetFromList) { if self.routeState.isEditing { ContactEdition().environment(\.managedObjectContext, self.context).environmentObject(self.routeState) } else if self.routeState.isShowingTags { Tags().environment(\.managedObjectContext, self.context).environmentObject(self.routeState) } } } private func filterContact(_ contact: Contact) -> Bool { guard search.count == 0 || NSPredicate(format: "name contains[c] %@", argumentArray: [search]).evaluate(with: contact) || contact.tags?.first(where: { tag in guard let tag = tag as? Tag else { return false } return tag.name?.lowercased().contains(search.lowercased()) ?? false }) != nil else { return false } if searchTokens.count == 0 { return true } return searchTokens.allSatisfy { token in contact.tags?.first(where: { tag in guard let tag = tag as? Tag else { return false } return tag.name?.lowercased() == token.name?.lowercased() }) != nil } } private func deleteContact(at indexSet: IndexSet) { for index in indexSet { CoreDataManager.shared.deleteContact(contacts[index]) } } private func moveContact(from source: IndexSet, to destination: Int) { for index in source { CoreDataManager.shared.moveContact(from: index, to: destination) } } private func showAlert(_ type: AlertType, withMessage message: String? = nil) { self.alertType = type self.errorMessage = message self.showingAlert = true } private func dismissAlert() { self.showingAlert = false self.alertType = nil self.errorMessage = nil } private func tryAgainBuyWithNoProduct() { dismissAlert() self.iapManager.getProducts(withHandler: { result in switch result { case .success(_): self.tryAgainBuy() break case .failure(let error): self.showAlert(.noProducts, withMessage: error.localizedDescription) break } }) } private func tryAgainBuy() { dismissAlert() DispatchQueue.main.async { if let unlimitedContactsProduct = self.iapManager.unlimitedContactsProduct { self.iapManager.buy(product: unlimitedContactsProduct) { result in switch result { case .success(_): self.routeState.navigate(.editContact(contact: nil)) break case .failure(let error): if let customError = error as? IAPManager.IAPManagerError, customError == .paymentWasCancelled { // don't do anything if it's cancelled return } self.showAlert(.cantBuy, withMessage: error.localizedDescription) } } } else { self.showAlert(.noProducts) } } } private func tryAgainRestore() { dismissAlert() DispatchQueue.main.async { self.iapManager.restorePurchases() { res in switch res { case .success(_): self.showAlert(.didRestore) break case .failure(let error): print(error) self.showAlert(.cantRestore, withMessage: error.localizedDescription) } } } } } struct ContentView_Previews: PreviewProvider { static var previews: some View { ContentView() } } <file_sep>// // ContactDetails.swift // Time Lines Shared // // Created by <NAME> on 07/04/2020. // Copyright © 2020 <NAME>. All rights reserved. // import SwiftUI public struct TagView: View { @Environment(\.presentationMode) var presentationMode @ObservedObject var tag: Tag public var onSelectTag: (_ tag: Tag, _ presentationMode: inout PresentationMode) -> Void public init(tag: Tag, onSelectTag: @escaping (_ tag: Tag, _ presentationMode: inout PresentationMode) -> Void = { _, _ in }) { self.tag = tag self.onSelectTag = onSelectTag } public var body: some View { Button(action: { self.onSelectTag(self.tag, &self.presentationMode.wrappedValue) }) { HStack { tag.swiftCircle .frame(width: 15, height: 15) .padding(.leading, 4) Text(tag.name ?? "").font(.subheadline).foregroundColor(Color.white) .padding(.init(top: 2, leading: 0, bottom: 2, trailing: 4)) }.background(Color.gray) .cornerRadius(3) } } } struct Main: View { @ObservedObject var contact: Contact @ObservedObject var currentTime = CurrentTime.shared var onSelectTag: (_ tag: Tag, _ presentationMode: inout PresentationMode) -> Void var body: some View { VStack(alignment: .leading) { HStack(alignment: .top) { Text(contact.name ?? "No Name") .font(.title) Spacer() Text(contact.timeZone?.prettyPrintTimeDiff() ?? "") .font(.title) } HStack(alignment: .top) { Text(contact.locationName ?? "No location") .font(.subheadline) Spacer() Text(contact.timeZone?.prettyPrintTime(currentTime.now) ?? "") .font(.subheadline) } ScrollView(.horizontal) { HStack(spacing: 10) { ForEach(contact.arrayTags, id: \Tag.name) { tag in TagView(tag: tag, onSelectTag: self.onSelectTag) } } } Line(coordinate: contact.location, timezone: contact.timeZone, startTime: contact.startTime, endTime: contact.endTime) .frame(height: 80) .padding() } .padding() } } public struct ContactDetails<EditView>: View where EditView: View { @ObservedObject var contact: Contact var editView: () -> EditView var onSelectTag: (_ tag: Tag, _ presentationMode: inout PresentationMode) -> Void private var dateFormatter: DateFormatter { let formatter = DateFormatter() formatter.dateStyle = .none formatter.timeStyle = .short return formatter } public init(contact: Contact, onSelectTag: @escaping (_ tag: Tag, _ presentationMode: inout PresentationMode) -> Void = { _, _ in }, @ViewBuilder editView: @escaping () -> EditView) { self.contact = contact self.editView = editView self.onSelectTag = onSelectTag } #if os(iOS) || os(tvOS) || os(watchOS) public var body: some View { VStack { MapView(coordinate: contact.location) .edgesIgnoringSafeArea(.top) .frame(height: 300) Main(contact: contact, onSelectTag: onSelectTag) Spacer() } .navigationBarItems(trailing: editView()) } #elseif os(macOS) public var body: some View { VStack { ZStack(alignment: .topTrailing) { MapView(coordinate: contact.location).edgesIgnoringSafeArea(.top) editView().padding() } .frame(height: 300) Main(contact: contact, onSelectTag: onSelectTag) Spacer() } } #endif } struct ContactDetails_Previews: PreviewProvider { static var previews: some View { let dummyContact = Contact() dummyContact.name = "Mathieu" dummyContact.latitude = 34.011286 dummyContact.longitude = -116.166868 return ContactDetails(contact: dummyContact) { Button(action: { print("edit") }) { Text("Edit") } } } } <file_sep>// // ContentView.swift // Time Lines WatchOS Extension // // Created by <NAME> on 13/04/2020. // Copyright © 2020 <NAME>. All rights reserved. // import SwiftUI import TimeLineSharedWatchOS struct ContentView: View { @Environment(\.managedObjectContext) var context @FetchRequest( entity: Contact.entity(), sortDescriptors: [NSSortDescriptor(keyPath: \Contact.index, ascending: true)] ) var contacts: FetchedResults<Contact> var body: some View { List { ForEach(contacts, id: \.self) { (contact: Contact) in ContactRow( name: contact.name ?? "", timezone: contact.timeZone, coordinate: contact.location, startTime: contact.startTime, endTime: contact.endTime ) .onAppear(perform: { contact.refreshTimeZone() }) } Group { Text("To add a new contact or edit existing ones, use the iOS or macOS app.").padding() } } } } struct ContentView_Previews: PreviewProvider { static var previews: some View { ContentView() } } <file_sep>// // TagEdition.swift // Time Lines // // Created by <NAME> on 26/04/2020. // Copyright © 2020 <NAME>. All rights reserved. // import SwiftUI import TimeLineShared import MapKit import CoreLocation struct TagEdition: View { private var tag: Tag? @State private var tagName: String @State private var color: UIColor private var colors: [Color] = { let hueValues = Array(0...359) return hueValues.map { Color(Tag.colorWithHue(CGFloat($0) / 359.0)) } }() private let linearGradientWidth: CGFloat = 200 init() { self.tag = RouteState.shared.editingTag _tagName = State(initialValue: tag?.name ?? "") _color = State(initialValue: tag?.color ?? Tag.randomColor()) } var body: some View { NavigationView { List { Section { HStack { Text("Name") TextField("Family", text: $tagName) .multilineTextAlignment(.trailing) .frame(alignment: .trailing) } HStack { Text("Color") Circle().foregroundColor(Color(color)).frame(width: 16, height: 16) Spacer() LinearGradient(gradient: Gradient(colors: colors), startPoint: .leading, endPoint: .trailing) .frame(width: linearGradientWidth, height: 10) .cornerRadius(5) .shadow(radius: 8) .gesture( DragGesture(minimumDistance: 0, coordinateSpace: .local).onChanged({ value in self.color = UIColor( hue: min(max(value.location.x, 0), self.linearGradientWidth) / self.linearGradientWidth, saturation: 1.0, brightness: 1.0, alpha: 1.0 ) }) ) } } } .listStyle(GroupedListStyle()) .keyboardAdaptive() .resignKeyboardOnDragGesture() .navigationBarTitle(Text(tag == nil ? "New Tag" : "Edit Tag")) .navigationBarItems(leading: Button(action: back) { Text("Cancel") }, trailing: Button(action: { self.save() }) { Text("Done") } .disabled(!didUpdateTag() || !valid()) ) }.navigationViewStyle(StackNavigationViewStyle()) } func back() { RouteState.shared.navigate(.tags) } func didChangeColor() -> Bool { return color != tag?.color } func didChangeName() -> Bool { return tagName.count > 0 && tagName != tag?.name } func didUpdateTag() -> Bool { return didChangeName() || didChangeColor() } func valid() -> Bool { return tagName.count > 0 } func save() { if let tag = tag { tag.name = tagName let components = color.rgba tag.red = Double(components.red) tag.green = Double(components.green) tag.blue = Double(components.blue) CoreDataManager.shared.saveContext() } else { CoreDataManager.shared.createTag( name: tagName, color: color ) } back() } } struct TagEdition_Previews: PreviewProvider { static var previews: some View { return TagEdition() } } <file_sep>// // WatchHandler.swift // Time Lines // // Created by <NAME> on 11/05/2020. // Copyright © 2020 <NAME>. All rights reserved. // import Foundation import WatchConnectivity import TimeLineShared class WatchHandler : NSObject, WCSessionDelegate { static let shared = WatchHandler() private var session = WCSession.default override init() { super.init() if WCSession.isSupported() { session.delegate = self session.activate() } print("isPaired?: \(session.isPaired), isWatchAppInstalled?: \(session.isWatchAppInstalled)") } // MARK: - WCSessionDelegate func session(_ session: WCSession, activationDidCompleteWith activationState: WCSessionActivationState, error: Error?) { print("activationDidCompleteWith activationState:\(activationState) error:\(String(describing: error))") } func sessionDidBecomeInactive(_ session: WCSession) {} func sessionDidDeactivate(_ session: WCSession) { /** * This is to re-activate the session on the phone when the user has switched from one * paired watch to second paired one. Calling it like this assumes that you have no other * threads/part of your code that needs to be given time before the switch occurs. */ self.session.activate() } /// Observer to receive messages from watch and we be able to response it /// /// - Parameters: /// - session: session /// - message: message received /// - replyHandler: response handler func session(_ session: WCSession, didReceiveMessage message: [String : Any], replyHandler: @escaping ([String : Any]) -> Void) { if message["request"] as? String != "contacts" { return replyHandler([:]) } let contacts = CoreDataManager.shared.fetch() let tags = CoreDataManager.shared.fetchTags() let serializedContacts = contacts.map({ contact in [ "latitude": contact.latitude, "longitude": contact.longitude, "timezone": contact.timezone, "name": contact.name ?? NO_VALUE, "locationName": contact.locationName ?? NO_VALUE, "startTime": contact.startTime?.timeIntervalSince1970 ?? NO_VALUE, "endTime": contact.endTime?.timeIntervalSince1970 ?? NO_VALUE, "favorite": contact.favorite, "index": contact.index, "tags": ((contact.tags?.allObjects ?? []) as [Tag]).map { $0.name ?? NO_VALUE } ] }) let serializedTags = tags.map({ tag in [ "name": tag.name ?? NO_VALUE, "red": tag.red, "green": tag.green, "blue": tag.blue, ] }) replyHandler([ "contacts" : serializedContacts, "tags" : serializedTags ]) } } <file_sep>// // Line.swift // Time Lines Shared // // Created by <NAME> on 04/04/2020. // Copyright © 2020 <NAME>. All rights reserved. // import SwiftUI import CoreLocation #if os(iOS) || os(tvOS) || os(watchOS) import UIKit public typealias CPFont = UIFont #elseif os(macOS) import Cocoa public typealias CPFont = NSFont #endif fileprivate func pointFraction(_ date: Date?, _ timezone: TimeZone?) -> CGFloat? { guard let date = date else { return nil } return CGFloat(date.fractionOfToday(timezone)) } fileprivate let defaultLineWidth: CGFloat = 2 fileprivate let defaultMaxHeight: CGFloat = 25 fileprivate func pointInFrame(frame: CGRect, point: CGFloat, now: Date, timezone: TimeZone?, startTime: Date?, endTime: Date?, preSunset: Date?, postSunrise: Date?) -> CGPoint { guard let startTime = startTime, let endTime = endTime, var startPoint = pointFraction(startTime, timezone), var endPoint = pointFraction(endTime, timezone) else { // complete night time so always at the bottom return CGPoint( x: frame.origin.x + frame.width * CGFloat(point), y: frame.origin.y + frame.height ) } if !startTime.isSameDay(now, timezone) { startPoint -= 1 } if !endTime.isSameDay(now, timezone) { endPoint += 1 } if startPoint < 0 && endPoint > 1 { // complete day time return CGPoint( x: frame.origin.x + frame.width * CGFloat(point), y: frame.origin.y ) } var y: CGFloat = frame.origin.y + frame.height if let preSunsetPoint = pointFraction(preSunset, timezone), point < preSunsetPoint { // find the position on the pre parabola let w = 2 * frame.width * preSunsetPoint let x1 = frame.width * -preSunsetPoint let c = y let b = -4 * frame.height / w let a = -b / w let x = frame.width * point - x1 y = a * x * x + b * x + c } else if let postSunrisePoint = pointFraction(postSunrise, timezone), point > postSunrisePoint { // find the position on the post parabola let w = 2 * frame.width * (1 - postSunrisePoint) let x1 = frame.width * postSunrisePoint let c = y let b = -4 * frame.height / w let a = -b / w let x = frame.width * point - x1 y = a * x * x + b * x + c } else if point < endPoint && point > startPoint { // find the position on the parabola let w = endPoint > 1 ? 2 * frame.width * (1 - startPoint) : startPoint < 0 ? 2 * frame.width * endPoint : frame.width * (endPoint - startPoint) let x1 = startPoint < 0 ? 0 : frame.width * startPoint let c = y let b = -4 * frame.height / w let a = -b / w let x = frame.width * point - x1 y = a * x * x + b * x + c } return CGPoint( x: frame.origin.x + frame.width * point, y: y ) } fileprivate func circlePosition(frame: CGRect, time: Date, timezone: TimeZone?, startTime: Date?, endTime: Date?, preSunset: Date?, postSunrise: Date?) -> CGPoint { guard let timePoint = pointFraction(time, timezone) else { // that can't happen return CGPoint(x: 0, y: 0) } return pointInFrame(frame: frame, point: timePoint, now: time, timezone: timezone, startTime: startTime, endTime: endTime, preSunset: preSunset, postSunrise: postSunrise) } struct ParabolaLine: Shape { var now: Date var timezone: TimeZone? var startTime: Date? var endTime: Date? var preSunset: Date? var postSunrise: Date? func path(in frame: CGRect) -> Path { var path = Path() guard let startTime = startTime, let endTime = endTime, var startPoint = pointFraction(startTime, timezone), var endPoint = pointFraction(endTime, timezone) else { // complete night time path.move(to: CGPoint( x: frame.origin.x, y: frame.origin.y + frame.height) ) path.addLine(to: CGPoint( x: frame.origin.x + frame.width, y: frame.origin.y + frame.height) ) return path } if !startTime.isSameDay(now, timezone) { startPoint -= 1 } if !endTime.isSameDay(now, timezone) { endPoint += 1 } if startPoint < 0 && endPoint > 1 { // complete day time path.move(to: CGPoint( x: frame.origin.x, y: frame.origin.y) ) path.addLine(to: CGPoint( x: frame.origin.x + frame.width, y: frame.origin.y) ) return path } if let preSunsetPoint = pointFraction(preSunset, timezone) { // we have a sunset from the previous day path.move(to: CGPoint( x: frame.origin.x, y: frame.origin.y) ) path.addCurve( to: CGPoint( x: frame.origin.x + frame.width * preSunsetPoint, y: frame.origin.y + frame.height ), control1: CGPoint( x: frame.origin.x + frame.width * (preSunsetPoint * 4 / 5), y: frame.origin.y ), control2: CGPoint( x: frame.origin.x + frame.width * preSunsetPoint, y: frame.origin.y + frame.height ) ) } else if startPoint < 0 { path.move(to: CGPoint( x: frame.origin.x, y: frame.origin.y) ) } else { path.move(to: CGPoint( x: frame.origin.x, y: frame.origin.y + frame.height) ) } if startPoint < 0 { path.addCurve( to: CGPoint( x: frame.origin.x + frame.width * endPoint, y: frame.origin.y + frame.height ), control1: CGPoint( x: frame.origin.x + frame.width * (endPoint * 4 / 5), y: frame.origin.y ), control2: CGPoint( x: frame.origin.x + frame.width * endPoint, y: frame.origin.y + frame.height ) ) } else { path.addLine(to: CGPoint( x: frame.origin.x + frame.width * startPoint, y: frame.origin.y + frame.height )) } if endPoint > 1 { path.addCurve( to: CGPoint( x: frame.origin.x + frame.width, y: frame.origin.y ), control1: CGPoint( x: frame.origin.x + frame.width * startPoint, y: frame.origin.y + frame.height ), control2: CGPoint( x: frame.origin.x + frame.width * (2 * (1 - startPoint) / 5 + startPoint), y: frame.origin.y ) ) return path } path.addCurve( to: CGPoint( x: frame.origin.x + frame.width * ((endPoint - startPoint) / 2 + startPoint), y: frame.origin.y ), control1: CGPoint( x: frame.origin.x + frame.width * startPoint, y: frame.origin.y + frame.height ), control2: CGPoint( x: frame.origin.x + frame.width * ((endPoint - startPoint) / 5 + startPoint), y: frame.origin.y ) ) path.addCurve( to: CGPoint( x: frame.origin.x + frame.width * endPoint, y: frame.origin.y + frame.height ), control1: CGPoint( x: frame.origin.x + frame.width * ((endPoint - startPoint) * 4 / 5 + startPoint), y: frame.origin.y ), control2: CGPoint( x: frame.origin.x + frame.width * endPoint, y: frame.origin.y + frame.height ) ) if let postSunrisePoint = pointFraction(postSunrise, timezone) { path.addLine(to: CGPoint( x: frame.origin.x + frame.width * postSunrisePoint, y: frame.origin.y + frame.height )) path.addCurve( to: CGPoint( x: frame.origin.x + frame.width, y: frame.origin.y ), control1: CGPoint( x: frame.origin.x + frame.width * postSunrisePoint, y: frame.origin.y + frame.height ), control2: CGPoint( x: frame.origin.x + frame.width * (2 * (1 - postSunrisePoint) / 5 + postSunrisePoint), y: frame.origin.y ) ) } else { path.addLine(to: CGPoint( x: frame.origin.x + frame.width, y: frame.origin.y + frame.height )) } return path } } struct CurrentTimeCircle: Shape { var now: Date var timezone: TimeZone? var startTime: Date? var endTime: Date? var preSunset: Date? var postSunrise: Date? var lineWidth: CGFloat? func path(in frame: CGRect) -> Path { var path = Path() let pos = circlePosition(frame: frame, time: now, timezone: timezone, startTime: startTime, endTime: endTime, preSunset: preSunset, postSunrise: postSunrise) path.addArc(center: pos, radius: (lineWidth ?? defaultLineWidth) * 1.5, startAngle: Angle.zero, endAngle: Angle.degrees(360), clockwise: true) return path } } struct CurrentTimeText: View { var now: Date var timezone: TimeZone? var startTime: Date? var endTime: Date? var preSunset: Date? var postSunrise: Date? private let font = CPFont.systemFont(ofSize: 18) func getSize(_ string: String) -> (height: CGFloat, exact: CGFloat, ceil: CGFloat, floor: CGFloat) { let size = NSString(string: string).size(withAttributes: [NSAttributedString.Key.font: font]) return (size.height, size.width, ceil(size.width / 10) * 10, floor(size.width / 10) * 10) } func getPosition(_ frame: CGRect, _ text: String?) -> CGRect { guard let string = text else { return .zero } let pos = circlePosition(frame: frame, time: now, timezone: timezone, startTime: startTime, endTime: endTime, preSunset: preSunset, postSunrise: postSunrise) let stringSize = getSize(string) var x = pos.x var y = pos.y - 25 var middle = frame.width / 2 if let startTime = startTime, let endTime = endTime, let middleFraction = pointFraction(startTime.addingTimeInterval(endTime.timeIntervalSince(startTime) / 2), timezone) { middle = frame.width * middleFraction } if x < middle { if x < stringSize.ceil { if preSunset != nil || (startTime != nil && !startTime!.isSameDay(now, timezone)) { y = frame.origin.y - 25 } else { let rightCorner = stringSize.ceil y = pointInFrame( frame: frame, point: rightCorner / frame.width, now: now, timezone: timezone, startTime: startTime, endTime: endTime, preSunset: preSunset, postSunrise: postSunrise ).y - 20 } } x = x - stringSize.exact } else { if x > frame.width - stringSize.floor { if postSunrise != nil || (endTime != nil && !endTime!.isSameDay(now, timezone)) { y = frame.origin.y - 25 } else { let leftCorner = frame.width - stringSize.floor y = pointInFrame( frame: frame, point: leftCorner / frame.width, now: now, timezone: timezone, startTime: startTime, endTime: endTime, preSunset: preSunset, postSunrise: postSunrise ).y - 20 } } } return CGRect( x: max(min(x, frame.width - stringSize.exact + 5), 0), y: y, width: stringSize.exact + 5, height: stringSize.height + 5 ) } var body: some View { let string = self.timezone?.prettyPrintTime(now) ?? "" return LineGeometryReader { p in VStack { HStack { Text(string) .font(Font(self.font as CTFont)) .offset(x: self.getPosition(p, string).origin.x, y: self.getPosition(p, string).origin.y) Spacer() } Spacer() } } } } struct LineGeometryReader<Content: View>: View { var lineWidth: CGFloat? var maxHeight: CGFloat? var content: (CGRect) -> Content func lineFrame(_ w: CGFloat, _ h: CGFloat) -> CGRect { let length = w - (lineWidth ?? defaultLineWidth) * 2 let height = min(h - (lineWidth ?? defaultLineWidth) * 2, maxHeight ?? defaultMaxHeight) let startHeight = height == maxHeight ? (h - height) / 2 : (lineWidth ?? defaultLineWidth) return CGRect(x: lineWidth ?? defaultLineWidth, y: startHeight, width: length, height: height) } var body: some View { GeometryReader { p in self.content(self.lineFrame(p.size.width, p.size.height)) } } } public struct Line: View { @ObservedObject var currentTime = CurrentTime.shared var coordinate: CLLocationCoordinate2D? var timezone: TimeZone? var startTime: Date? var endTime: Date? var lineWidth: CGFloat? var maxHeight: CGFloat? public init(coordinate: CLLocationCoordinate2D?, timezone: TimeZone?, startTime: Date? = nil, endTime: Date? = nil) { self.coordinate = coordinate self.timezone = timezone self.startTime = startTime self.endTime = endTime } public var body: some View { let solar = (startTime == nil || endTime == nil) && coordinate != nil ? Solar(for: currentTime.now.inTimeZone(timezone), coordinate: coordinate!) : nil var start = startTime?.staticTime(currentTime.now, timezone) ?? solar?.sunrise var end = endTime?.staticTime(currentTime.now, timezone) ?? solar?.sunset var postSunrise: Date? = nil var preSunset: Date? = nil if start != nil && !start!.isSameDay(currentTime.now, timezone) { // that means the sunrise was yesterday, and that there will be another one // sometimes tonight // so we try to get the sunrise of tomorrow which should be the one of tonight let tomorrow = currentTime.now.inTimeZone(timezone).addingTimeInterval(24 * 3600) let tomorrowSolar = coordinate != nil ? Solar(for: tomorrow, coordinate: coordinate!) : nil if tomorrowSolar?.sunrise?.isSameDay(currentTime.now, timezone) ?? false { postSunrise = tomorrowSolar?.sunrise } } if end != nil && !end!.isSameDay(currentTime.now, timezone) { // that means the sunset is tomorrow, and that there was be another one // sometimes this morning // so we try to get the sunset of yesterday which should be the one of this morning let yesterday = currentTime.now.inTimeZone(timezone).addingTimeInterval(-24 * 3600) let yesterdaySolar = coordinate != nil ? Solar(for: yesterday, coordinate: coordinate!) : nil if yesterdaySolar?.sunset?.isSameDay(currentTime.now, timezone) ?? false { preSunset = yesterdaySolar?.sunset } } if start == nil, end == nil { let month = cal.component(.month, from: Date()) let isSummer = month >= 4 && month < 10 if coordinate?.latitude ?? 0 > 0 && isSummer { // if we are in summer in the northern emisphere start = Date().addingTimeInterval(-48 * 3600) end = Date().addingTimeInterval(48 * 3600) } else if coordinate?.latitude ?? 0 < 0 && !isSummer { // if we are in summer in the southern emisphere start = Date().addingTimeInterval(-48 * 3600) end = Date().addingTimeInterval(48 * 3600) } } let diff = Double(timezone?.secondsFromGMT() ?? 0) / (24 * 3600) return LineGeometryReader { p in ZStack(alignment: .topLeading) { ParabolaLine(now: self.currentTime.now, timezone: self.timezone, startTime: start, endTime: end, preSunset: preSunset, postSunrise: postSunrise) .stroke(style: StrokeStyle(lineWidth: self.lineWidth ?? defaultLineWidth, lineCap: .round, lineJoin: .round)) CurrentTimeCircle(now: self.currentTime.now, timezone: self.timezone, startTime: start, endTime: end, preSunset: preSunset, postSunrise: postSunrise) CurrentTimeText(now: self.currentTime.now, timezone: self.timezone, startTime: start, endTime: end, preSunset: preSunset, postSunrise: postSunrise) } .frame(width: p.width, height: p.height) .gesture( DragGesture() .onChanged { value in self.currentTime.customTime(Date.fractionOfToday(Double(value.location.x / p.width) - diff)) } ) .gesture( TapGesture() .onEnded { value in self.currentTime.releaseCustomTime() }, including: self.currentTime.customTime ? .all : .subviews ) } } } public struct Line_Previews: PreviewProvider { public static var previews: some View { let customDate = Date().addingTimeInterval(9 * 3600) CurrentTime.shared.customTime(customDate) return Group { Line(coordinate: CLLocationCoordinate2D(latitude: 0, longitude: 0), timezone: TimeZone(secondsFromGMT: 0), startTime: Date(timeIntervalSince1970: 16000)) Line(coordinate: CLLocationCoordinate2D(latitude: 10, longitude: 10), timezone: TimeZone(secondsFromGMT: 3600)) Line(coordinate: CLLocationCoordinate2D(latitude: 45, longitude: 45), timezone: TimeZone(secondsFromGMT: 9200)) Line(coordinate: CLLocationCoordinate2D(latitude: 45, longitude: -70), timezone: TimeZone(secondsFromGMT: -14000)) Line(coordinate: CLLocationCoordinate2D(latitude: 80, longitude: 80), timezone: TimeZone(secondsFromGMT: -8000)) // https://github.com/mathieudutour/TimeLines/issues/39 Line(coordinate: CLLocationCoordinate2D(latitude: 41.85, longitude: -87.65), timezone: TimeZone(secondsFromGMT: -5 * 3600)) } .previewLayout(.fixed(width: 300, height: 80)) } } <file_sep>// // SceneDelegate.swift // Time Lines // // Created by <NAME> on 02/04/2020. // Copyright © 2020 <NAME>. All rights reserved. // import UIKit import SwiftUI import TimeLineShared import CoreData class SceneDelegate: UIResponder, UIWindowSceneDelegate { var window: UIWindow? func scene(_ scene: UIScene, willConnectTo session: UISceneSession, options connectionOptions: UIScene.ConnectionOptions) { // Use this method to optionally configure and attach the UIWindow `window` to the provided UIWindowScene `scene`. // If using a storyboard, the `window` property will automatically be initialized and attached to the scene. // This delegate does not imply the connecting scene or session are new (see `application:configurationForConnectingSceneSession` instead). let contentView = ContentView() .environment(\.managedObjectContext, CoreDataManager.shared.viewContext) .environment(\.inAppPurchaseContext, IAPManager.shared) .environmentObject(RouteState.shared) // Use a UIHostingController as window root view controller. if let windowScene = scene as? UIWindowScene { let window = UIWindow(windowScene: windowScene) window.rootViewController = UIHostingController(rootView: contentView) self.window = window window.makeKeyAndVisible() } } func scene(_ scene: UIScene, openURLContexts URLContexts: Set<UIOpenURLContext>) { URLContexts.forEach { urlContext in switch urlContext.url.host { case "contact": let objectIDString = urlContext.url.path.replacingOccurrences(of: "/", with: "", options: .anchored) if let contact = CoreDataManager.shared.findContact(objectIDString) { RouteState.shared.navigate(.contact(contact: contact)) } else { RouteState.shared.navigate(.list) } break default: break } } } func sceneDidDisconnect(_ scene: UIScene) { // Called as the scene is being released by the system. // This occurs shortly after the scene enters the background, or when its session is discarded. // Release any resources associated with this scene that can be re-created the next time the scene connects. // The scene may re-connect later, as its session was not neccessarily discarded (see `application:didDiscardSceneSessions` instead). } func sceneDidBecomeActive(_ scene: UIScene) { // Called when the scene has moved from an inactive state to an active state. // Use this method to restart any tasks that were paused (or not yet started) when the scene was inactive. } func sceneWillResignActive(_ scene: UIScene) { // Called when the scene will move from an active state to an inactive state. // This may occur due to temporary interruptions (ex. an incoming phone call). } func sceneWillEnterForeground(_ scene: UIScene) { // Called as the scene transitions from the background to the foreground. // Use this method to undo the changes made on entering the background. } func sceneDidEnterBackground(_ scene: UIScene) { // Called as the scene transitions from the foreground to the background. // Use this method to save data, release shared resources, and store enough scene-specific state information // to restore the scene back to its current state. // Save changes in the application's managed object context when the application transitions to the background. CoreDataManager.shared.saveContext() } } <file_sep>// // MenuView.swift // Time Lines macOS // // Created by <NAME> on 04/04/2020. // Copyright © 2020 <NAME>. All rights reserved. // import SwiftUI import AppKit import TimeLineSharedMacOS import CoreLocation struct MenuView: View { @Environment(\.managedObjectContext) var context @FetchRequest( entity: Contact.entity(), sortDescriptors: [NSSortDescriptor(keyPath: \Contact.index, ascending: true)], predicate: NSPredicate(format: "favorite == YES", argumentArray: []) ) var contacts: FetchedResults<Contact> var body: some View { ZStack { List { ForEach(contacts, id: \.self) { (contact: Contact) in VStack { ContactRow( name: contact.name ?? "", timezone: contact.timeZone, coordinate: contact.location, startTime: contact.startTime, endTime: contact.endTime ) if self.contacts.last != contact { Divider() } }.onAppear(perform: { contact.refreshTimeZone() }) } } .listStyle(SidebarListStyle()) VStack { HStack { Spacer() Button(action: { guard let delegate = NSApp.delegate as? AppDelegate else { return } delegate.statusBar?.showRightClickMenu(delegate) }) { Image(nsImage: NSImage(named: NSImage.actionTemplateName)!) .colorMultiply(Color(NSColor.secondaryLabelColor)) } .buttonStyle(ButtonThatLookLikeNothingStyle()) .padding(.init(top: 8, leading: 8, bottom: 8, trailing: 8)) } Spacer() } } } } struct MenuView_Previews: PreviewProvider { static var previews: some View { MenuView() } } <file_sep>/* Copyright © 2020 Apple Inc. Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. Abstract: A view that hosts an `MKMapView`. */ import SwiftUI import MapKit class MapViewDelegate: NSObject, MKMapViewDelegate {} public struct MapView { public var coordinate: CLLocationCoordinate2D public var span: Double private let delegate = MapViewDelegate() public init(coordinate: CLLocationCoordinate2D, span: Double = 0.02) { self.coordinate = coordinate self.span = span } func makeMapView() -> MKMapView { let view = MKMapView(frame: .zero) view.delegate = delegate return view } func updateMapView(_ uiView: MKMapView) { let coordSpan = MKCoordinateSpan(latitudeDelta: span, longitudeDelta: span) let region = MKCoordinateRegion(center: coordinate, span: coordSpan) uiView.setRegion(region, animated: true) } } #if os(iOS) || os(tvOS) || os(watchOS) extension MapView: UIViewRepresentable { public func makeUIView(context: Context) -> MKMapView { makeMapView() } public func updateUIView(_ uiView: MKMapView, context: Context) { updateMapView(uiView) } } #elseif os(macOS) extension MapView: NSViewRepresentable { public func makeNSView(context: Context) -> MKMapView { makeMapView() } public func updateNSView(_ uiView: MKMapView, context: Context) { updateMapView(uiView) } } #endif struct MapView_Previews: PreviewProvider { static var previews: some View { return MapView(coordinate: CLLocationCoordinate2D(latitude: 34.011286, longitude: -116.166868)) } } <file_sep># Time Lines Know <strong><em>when</em></strong> all your friends, colleagues, and family are. ![Time Lines screenshots](./assets/illustration.png) Time Lines is a practical app to know <strong><em>when</em></strong> all your friends, colleagues and family are. With a quick glance, you can check the time of the day anywhere in the world. - Sync across all your devices automatically with iCloud - Completely private - your data are yours only - Innovative line overview of the day, aligned with the sunrise and sunset [![Download on the App Store](./assets/as-button.png)](https://apps.apple.com/app/time-lines-world-clock/id1506203873) [![Download on the Mac App Store](./assets/mas-button.png)](https://apps.apple.com/app/time-lines-world-clock/id1506203873) ## Inspiration [<NAME>'s tweet](https://twitter.com/rjonesy/status/1236706277750906882) <file_sep>// // State.swift // TimeLine // // Created by <NAME> on 25/04/2020. // Copyright © 2020 <NAME>. All rights reserved. // import SwiftUI import Combine import TimeLineShared enum Route { case list case editContact(contact: Contact?) case contact(contact: Contact) case tags case editTag(tag: Tag?) } class RouteState: ObservableObject { static let shared = RouteState() @Published private(set) var route: Route = .list // derived data @Published var isShowingSheetFromList: Bool = false { didSet { if isShowingSheetFromList == oldValue { return } if !isShowingSheetFromList { if case .list = route {} else { navigate(.list) } } } } @Published var contactDetailed: Contact? = nil { didSet { if contactDetailed == oldValue { return } if let contact = contactDetailed { if case .contact(_) = route {} else { navigate(.contact(contact: contact)) } } else { if case .contact(_) = route { navigate(.list) } } } } @Published var isEditing: Bool = false { didSet { if isEditing == oldValue { return } if !isEditing, case let .editContact(contact) = route { if let contactUnwrap = contact { navigate(.contact(contact: contactUnwrap)) } else { navigate(.list) } } } } @Published private(set) var editingContact: Contact? = nil @Published var isShowingTags: Bool = false { didSet { if isShowingTags == oldValue { return } if !isShowingTags, case .tags = route { navigate(.list) } } } @Published var isEditingTag: Bool = false { didSet { if isEditingTag == oldValue { return } if !isEditingTag, case .editTag(_) = route { navigate(.tags) } } } @Published private(set) var editingTag: Tag? = nil func navigate(_ route: Route) { self.route = route if case let .editContact(contact) = route { isEditing = true editingContact = contact isEditingTag = false editingTag = nil isShowingTags = false isShowingSheetFromList = true contactDetailed = contact } else if case let .contact(contact: contact) = route { isEditing = false editingContact = nil isEditingTag = false editingTag = nil isShowingTags = false isShowingSheetFromList = false contactDetailed = contact } else if case let .editTag(tag: tag) = route { isEditing = false editingContact = nil isEditingTag = true editingTag = tag isShowingTags = true isShowingSheetFromList = true contactDetailed = nil } else if case .tags = route { isEditing = false editingContact = nil isEditingTag = false editingTag = nil isShowingTags = true isShowingSheetFromList = true contactDetailed = nil } else { isEditing = false editingContact = nil isEditingTag = false editingTag = nil isShowingTags = false isShowingSheetFromList = false } } } <file_sep>// // CurrentTime.swift // Time Lines Shared // // Created by <NAME> on 14/04/2020. // Copyright © 2020 <NAME>. All rights reserved. // import Foundation import SwiftUI struct CurrentTimeEnvironmentKey: EnvironmentKey { public static let defaultValue = CurrentTime.shared } extension EnvironmentValues { public var currentTime : CurrentTime { set { self[CurrentTimeEnvironmentKey.self] = newValue } get { self[CurrentTimeEnvironmentKey.self] } } } public class CurrentTime: NSObject, ObservableObject { public static let shared = CurrentTime() @Published public var now: Date = Date() @Published public var customTime = false private var timer: Timer? private override init() { super.init() timer = Timer.scheduledTimer(withTimeInterval: 1, repeats: true) { _ in if !self.customTime { self.now = Date() } } } deinit { timer?.invalidate() } public func customTime(_ date: Date) { self.customTime = true self.now = date } public func releaseCustomTime() { self.customTime = false self.now = Date() } } <file_sep>// // TodayViewController.swift // Time Lines Widget // // Created by <NAME> on 02/04/2020. // Copyright © 2020 <NAME>. All rights reserved. // import UIKit import NotificationCenter import SwiftUI import TimeLineShared import CoreData class TodayViewController: UIViewController, NCWidgetProviding { override func viewDidLoad() { super.viewDidLoad() extensionContext?.widgetLargestAvailableDisplayMode = .expanded self.preferredContentSize = CGSize(width: 0, height: CoreDataManager.shared.count() * (80 + 13)) } func widgetActiveDisplayModeDidChange(_ activeDisplayMode: NCWidgetDisplayMode, withMaximumSize maxSize: CGSize) { if activeDisplayMode == NCWidgetDisplayMode.compact { self.preferredContentSize = CGSize(width: maxSize.width, height: 80) } else { self.preferredContentSize = CGSize(width: maxSize.width, height: CGFloat(CoreDataManager.shared.count() * (80 + 13))) } } @IBSegueAction func addSwiftUIView(_ coder: NSCoder) -> UIViewController? { // Get the managed object context from the shared persistent container. let context = CoreDataManager.shared.viewContext // Create the SwiftUI view and set the context as the value for the managedObjectContext environment keyPath. // Add `@Environment(\.managedObjectContext)` in the views that will need the context. let contentView = WidgetView(extensionContext: extensionContext) .environment(\.managedObjectContext, context) .background(Color.clear) let vc = UIHostingController(coder: coder, rootView: contentView) vc?.view.backgroundColor = .clear return vc } func widgetPerformUpdate(completionHandler: (@escaping (NCUpdateResult) -> Void)) { // Perform any setup necessary in order to update the view. // If an error is encountered, use NCUpdateResult.Failed // If there's no update required, use NCUpdateResult.NoData // If there's an update, use NCUpdateResult.NewData completionHandler(NCUpdateResult.newData) } } <file_sep>import Foundation import ServiceManagement import SwiftUI import TimeLineSharedMacOS public struct LaunchAtLogin { private static let id = "\(App.id)MacOS-launchagent" public static var isEnabled: Bool { get { guard let jobs = (SMCopyAllJobDictionaries(kSMDomainUserLaunchd).takeRetainedValue() as? [[String: AnyObject]]) else { return false } let job = jobs.first { $0["Label"] as! String == id } return job?["OnDemand"] as? Bool ?? false } set { SMLoginItemSetEnabled(id as CFString, newValue) } } } extension LaunchAtLogin { struct Toggle: View { @State private var launchAtLogin = isEnabled var body: some View { SwiftUI.Toggle( "Launch at Login", isOn: $launchAtLogin.onChange { isEnabled = $0 } ) } } } <file_sep>// // SearchBar.swift // TimeLine // // Created by <NAME> on 24/04/2020. // Copyright © 2020 <NAME>. All rights reserved. // import SwiftUI import TimeLineShared import Combine protocol TagPickerDelegate { func didSelectTag(_ tag: Tag) -> Void } struct AccessoryView : View { @Environment(\.managedObjectContext) var context @FetchRequest( entity: Tag.entity(), sortDescriptors: [NSSortDescriptor(keyPath: \Tag.name, ascending: true)] ) var existingTokens: FetchedResults<Tag> var delegate: TagPickerDelegate @Binding var search: String @Binding var tokens: [Tag] func filterTag(_ tag: Tag) -> Bool { return (search.count == 0 || NSPredicate(format: "name contains[c] %@", argumentArray: [search]).evaluate(with: tag)) && tokens.first(where: { token in return (tag.name?.lowercased() ?? "") == (token.name?.lowercased() ?? "") }) == nil } var body: some View { ScrollView(.horizontal, showsIndicators: false) { HStack(spacing: 5) { ForEach(existingTokens.filter { filterTag($0) }, id: \Tag.name) { tag in TagView(tag: tag, onSelectTag: { tag, _ in self.delegate.didSelectTag(tag) }) } .padding(.leading, 5) .padding(.trailing, 5) } }.frame(maxWidth: UIScreen.main.bounds.width, minHeight: 45, maxHeight: 45) } } struct SearchBar: UIViewRepresentable { @Environment(\.managedObjectContext) var context @FetchRequest( entity: Tag.entity(), sortDescriptors: [NSSortDescriptor(keyPath: \Tag.name, ascending: true)] ) var existingTokens: FetchedResults<Tag> var placeholder: String = "Search..." @Binding var search: String @Binding var tokens: [Tag] var allowCreatingTokens: Bool = false let scroll: UIScrollView = { let scroll = UIScrollView(frame: .zero) return scroll }() let accessory: UIInputView = { let accessoryView = UIInputView(frame: .zero, inputViewStyle: .keyboard) accessoryView.translatesAutoresizingMaskIntoConstraints = false return accessoryView }() func makeUIView(context: Context) -> UISearchBar { let bar = UISearchBar() bar.placeholder = placeholder bar.delegate = context.coordinator bar.text = search bar.returnKeyType = .next bar.searchBarStyle = .minimal accessory.frame = CGRect(x: 0, y: 0, width: UIScreen.main.bounds.width, height: 45) bar.inputAccessoryView = accessory return bar } func updateUIView(_ uiView: UISearchBar, context: Context) { uiView.placeholder = placeholder uiView.text = search uiView.searchTextField.allowsCopyingTokens = false uiView.searchTextField.allowsDeletingTokens = true uiView.searchTextField.tokens = tokens.map { token in let res = UISearchToken( icon: token.image, text: token.name ?? "" ) res.representedObject = token return res } } } class SearchBarCoordinator: NSObject, UISearchBarDelegate, TagPickerDelegate { var parent: SearchBar init(_ parent: SearchBar) { self.parent = parent super.init() } // MARK: - UISearchBarDelegate func searchBarCancelButtonClicked(_ searchBar: UISearchBar) { parent.search = "" parent.tokens = [] } func searchBarTextDidBeginEditing(_ searchBar: UISearchBar) { let child = UIHostingController(rootView: AccessoryView(delegate: self, search: parent.$search, tokens: parent.$tokens).environment(\.managedObjectContext, parent.context)) child.view.translatesAutoresizingMaskIntoConstraints = false child.view.frame = parent.accessory.bounds child.view.backgroundColor = .clear parent.accessory.addSubview(child.view) } func searchBarTextDidEndEditing(_ searchBar: UISearchBar) { // remove the UIHostingController parent.accessory.subviews.last?.removeFromSuperview() } func searchBar(_ searchBar: UISearchBar, textDidChange searchText: String) { parent.search = searchText parent.tokens = searchBar.searchTextField.tokens.map { $0.representedObject as! Tag } } func searchBarSearchButtonClicked(_ searchBar: UISearchBar) { guard let text = searchBar.text, text.count > 0 else { return } let existingToken = parent.existingTokens.first(where: { $0.name?.lowercased() == text.lowercased() }) if !parent.allowCreatingTokens && existingToken == nil { return } parent.search = "" guard let newToken = existingToken ?? CoreDataManager.shared.createTag(name: text) else { return } if parent.tokens.first(where: { $0.name?.lowercased() == newToken.name?.lowercased() }) == nil { parent.tokens.append(newToken) } } func didSelectTag(_ tag: Tag) { parent.tokens.append(tag) } } extension SearchBar { func makeCoordinator() -> SearchBarCoordinator { SearchBarCoordinator(self) } } <file_sep>// // ManageContacts.swift // Time LinesMacOS // // Created by <NAME> on 07/04/2020. // Copyright © 2020 <NAME>. All rights reserved. // import SwiftUI import TimeLineSharedMacOS import CoreLocation enum AlertType { case noProducts case cantBuy case upsell } struct ManageContacts: View { @Environment(\.managedObjectContext) var context @Environment(\.inAppPurchaseContext) var iapManager @FetchRequest( entity: Contact.entity(), sortDescriptors: [NSSortDescriptor(keyPath: \Contact.index, ascending: true)] ) var contacts: FetchedResults<Contact> @State var selectedContact: Contact? @State private var showingEdit = false @State private var showingSheet = false @State private var showingAlert = false @State private var alertType: AlertType? @State private var errorMessage: String? var body: some View { NavigationView { List(selection: $selectedContact) { Button(action: { if (!self.iapManager.hasAlreadyPurchasedUnlimitedContacts && self.contacts.count >= self.iapManager.contactsLimit) { self.showAlert(.upsell) } else { self.selectedContact = nil self.showingEdit = true } }) { HStack { Image(nsImage: NSImage(named: NSImage.addTemplateName)!) Text("Add a new contact") } }.disabled(!iapManager.hasAlreadyPurchasedUnlimitedContacts && !iapManager.canBuy()) ForEach(contacts, id: \.self) { (contact: Contact) in VStack { HStack { Text(contact.name ?? "") .font(.system(size: 20)) .lineLimit(1) Spacer() Text(contact.timeZone?.prettyPrintTimeDiff() ?? "").padding() } Divider() } .tag(contact) .onAppear(perform: { contact.refreshTimeZone() }) .contextMenu(menuItems: { Button(action: { self.selectedContact = contact self.showingEdit = true }) { Text("Edit Contact") } Button(action: { self.selectedContact = nil self.showingEdit = false CoreDataManager.shared.deleteContact(contact) }) { Text("Delete Contact") } }) } .onDelete(perform: self.deleteContact) .onMove(perform: self.moveContact) } .padding(.top) .frame(minWidth: 200) .listStyle(SidebarListStyle()) if showingEdit { ContactEdition(contact: $selectedContact, showingEdit: $showingEdit) } else if selectedContact != nil { ContactDetails(contact: selectedContact!) { Button(action: { self.showingEdit = true }) { Text("Edit") } } } } .edgesIgnoringSafeArea(.top) .navigationViewStyle(DoubleColumnNavigationViewStyle()) .background(Blur().edgesIgnoringSafeArea(.top)) .alert(isPresented: $showingAlert) { switch self.alertType { case .noProducts: return Alert( title: Text("Error while trying to get the In App Purchases"), message: Text(self.errorMessage ?? "Seems like there was an issue with the Apple's servers."), primaryButton: .cancel(Text("Cancel"), action: self.dismissAlert), secondaryButton: .default(Text("Try Again"), action: self.tryAgainBuyWithNoProduct) ) case .cantBuy: return Alert( title: Text("Error while trying to purchase the product"), message: Text(self.errorMessage ?? "Seems like there was an issue with the Apple's servers."), primaryButton: .cancel(Text("Cancel"), action: self.dismissAlert), secondaryButton: .default(Text("Try Again"), action: self.tryAgainBuy) ) case .upsell: return Alert( title: Text("You've reached the limit of the free Time Lines version"), message: Text("Unlock the full version to add an unlimited number of contacts."), primaryButton: .default(Text("Unlock Full Version"), action: self.tryAgainBuy), secondaryButton: .cancel(Text("Cancel"), action: self.dismissAlert) ) case nil: return Alert(title: Text("Unknown Error"), dismissButton: .default(Text("OK"))) } } } private func deleteContact(at indexSet: IndexSet) { for index in indexSet { CoreDataManager.shared.deleteContact(contacts[index]) } } private func moveContact(from source: IndexSet, to destination: Int) { for index in source { CoreDataManager.shared.moveContact(from: index, to: destination) } } private func showAlert(_ type: AlertType, withMessage message: String? = nil) { self.alertType = type self.errorMessage = message self.showingAlert = true } private func dismissAlert() { self.showingAlert = false self.alertType = nil self.errorMessage = nil } private func tryAgainBuyWithNoProduct() { dismissAlert() self.iapManager.getProducts(withHandler: { result in switch result { case .success(_): self.tryAgainBuy() break case .failure(let error): self.showAlert(.noProducts, withMessage: error.localizedDescription) break } }) } private func tryAgainBuy() { dismissAlert() DispatchQueue.main.async { if let unlimitedContactsProduct = self.iapManager.unlimitedContactsProduct { self.iapManager.buy(product: unlimitedContactsProduct) { result in switch result { case .success(_): self.selectedContact = nil self.showingEdit = true break case .failure(let error): print(error) self.showAlert(.cantBuy, withMessage: error.localizedDescription) } } } else { self.showAlert(.noProducts) } } } } struct ManageContacts_Previews: PreviewProvider { static var previews: some View { ManageContacts() } } <file_sep>// // ContactEdition.swift // Time LinesMacOS // // Created by <NAME> on 08/04/2020. // Copyright © 2020 <NAME>. All rights reserved. // import SwiftUI import TimeLineSharedMacOS import MapKit import CoreLocation struct CustomTimePicker: View { var text: String @Binding var custom: Bool @Binding var time: Date var body: some View { HStack { Toggle(isOn: $custom) { Text(text) } Spacer() if custom { DatePicker(selection: $time, displayedComponents: .hourAndMinute) { Text("") }.labelsHidden() } } } } struct ButtonThatLookLikeTextFieldStyle: ButtonStyle { var locationText: String func makeBody(configuration: Self.Configuration) -> some View { configuration.label .font(.headline) .padding(10) .foregroundColor(Color(self.locationText == "" ? NSColor.placeholderTextColor : NSColor.labelColor)) .background(Color(NSColor.controlBackgroundColor)) .border(Color(NSColor.controlShadowColor), width: 0.5) } } struct ContactEdition: View { @Environment(\.presentationMode) var presentationMode @Binding var contact: Contact? @Binding var showingEdit: Bool @State private var saving = false @State private var contactName: String @State private var locationText = "" @State private var location: CLLocationCoordinate2D = CLLocationCoordinate2D(latitude: 0, longitude: 0) @State private var showModal = false @State private var timezone: TimeZone? @State private var customStartTime = false @State private var customEndTime = false @State private var startTime: Date @State private var endTime: Date @State private var favorite = true @State private var locationCompletion: MKLocalSearchCompletion? init(contact: Binding<Contact?>, showingEdit: Binding<Bool>) { let today = Calendar.current.startOfDay(for: Date()) self._contact = contact self._showingEdit = showingEdit _contactName = State(initialValue: contact.wrappedValue?.name ?? "") _locationText = State(initialValue: contact.wrappedValue?.locationName ?? "") _location = State(initialValue: contact.wrappedValue?.location ?? CLLocationCoordinate2D(latitude: 0, longitude: 0)) _timezone = State(initialValue: contact.wrappedValue?.timeZone) _customStartTime = State(initialValue: contact.wrappedValue?.startTime != nil) _customEndTime = State(initialValue: contact.wrappedValue?.endTime != nil) _startTime = State(initialValue: contact.wrappedValue?.startTime?.inTodaysTime().addingTimeInterval(-TimeInterval(TimeZone.autoupdatingCurrent.secondsFromGMT())) ?? today.addingTimeInterval(3600 * 9)) _endTime = State(initialValue: contact.wrappedValue?.endTime?.inTodaysTime().addingTimeInterval(-TimeInterval(TimeZone.autoupdatingCurrent.secondsFromGMT())) ?? today.addingTimeInterval(3600 * 18)) _favorite = State(initialValue: contact.wrappedValue?.favorite ?? true) } var body: some View { VStack { Spacer() VStack(alignment: .leading) { HStack { Text("Name") .font(.title) TextField("<NAME>", text: $contactName) .font(.title) .multilineTextAlignment(.trailing) .frame(alignment: .trailing) } HStack { Text("Location") .font(.title) GeometryReader { p in Button(action: { self.showModal = true }) { Text(self.locationText == "" ? "San Francisco" : self.locationText) .multilineTextAlignment(.trailing) .font(.title) .frame(width: p.size.width - 20, height: 22, alignment: .trailing) .foregroundColor(Color(self.locationText == "" ? NSColor.placeholderTextColor : NSColor.labelColor)) } .frame(height: 22, alignment: .trailing) .buttonStyle(ButtonThatLookLikeTextFieldStyle(locationText: self.locationText)) .sheet(isPresented: self.$showModal) { SearchController(resultView: { mapItem in Button(action: { self.locationCompletion = mapItem self.locationText = mapItem.title self.showModal = false }) { Text(mapItem.title) } .buttonStyle(ButtonThatLookLikeRowStyle()) }) } }.frame(height: 30) } Text("Your favorite contacts will show up in the main popover.") .padding(.top, 50) .foregroundColor(Color.secondary) HStack { Toggle(isOn: $favorite) { Text("Favorite") } Spacer() } Text("A time line will show the dawn and twilight times at the location of the contact by default. You can customize those times if you'd like to show working hours for example.") .padding(.top, 50) .foregroundColor(Color.secondary) CustomTimePicker(text: "Customize rise time", custom: $customStartTime, time: $startTime) CustomTimePicker(text: "Customize set time", custom: $customEndTime, time: $endTime) HStack { Spacer() Button(action: { self.save() }) { Text("Done") } .padding(.top) .disabled(contactName == "" || locationText == "") } Spacer() } .padding() Spacer() } } func didChangeTime(_ previousTime: Date?, _ custom: Bool, _ newTime: Date) -> Bool { return (previousTime == nil && custom) || (previousTime != nil && !custom) || (previousTime != nil && previousTime?.inTodaysTime().addingTimeInterval(-TimeInterval(TimeZone.autoupdatingCurrent.secondsFromGMT())) != newTime) } func didChangeLocation() -> Bool { return locationCompletion != nil && locationCompletion?.title != contact?.locationName } func didChangeName() -> Bool { return contactName.count > 0 && contactName != contact?.name } // func didChangeTags() -> Bool { // if let previousTags = contact?.arrayTags { // return tags != previousTags // } else { // return tags.count > 0 // } // } func didChangeFavorite() -> Bool { if let previous = contact?.favorite { return previous != favorite } return false } func didUpdateUser() -> Bool { return didChangeLocation() || didChangeName() || didChangeTime(contact?.startTime, customStartTime, startTime) || didChangeTime(contact?.endTime, customEndTime, endTime) || didChangeFavorite() // || didChangeTags() } func valid() -> Bool { return (locationCompletion != nil || contact?.locationName != nil) && contactName.count > 0 } func save() { if let locationCompletion = locationCompletion, didChangeLocation() { // need to fetch the new location let request = MKLocalSearch.Request(completion: locationCompletion) request.resultTypes = .address let search = MKLocalSearch(request: request) search.start { response, _ in guard let response = response, let mapItem = response.mapItems.first else { return } self.timezone = mapItem.timeZone self.location = mapItem.placemark.location?.coordinate ?? CLLocationCoordinate2D(latitude: 0, longitude: 0) self.updateContact() } } else if didUpdateUser() { self.updateContact() } else { showingEdit = false } } func updateContact() { let resolvedStartTime = customStartTime ? startTime.addingTimeInterval(TimeInterval(TimeZone.autoupdatingCurrent.secondsFromGMT())) : nil let resolvedEndTime = customEndTime ? endTime.addingTimeInterval(TimeInterval(TimeZone.autoupdatingCurrent.secondsFromGMT())) : nil if let contact = contact { contact.name = contactName contact.latitude = location.latitude contact.longitude = location.longitude contact.locationName = locationText contact.timezone = Int32(timezone?.secondsFromGMT() ?? 0) contact.startTime = resolvedStartTime contact.endTime = resolvedEndTime contact.favorite = favorite CoreDataManager.shared.saveContext() } else { contact = CoreDataManager.shared.createContact( name: contactName, latitude: location.latitude, longitude: location.longitude, locationName: locationText, timezone: Int32(timezone?.secondsFromGMT() ?? 0), startTime: resolvedStartTime, endTime: resolvedEndTime, tags: NSSet(), favorite: favorite ) } showingEdit = false } } struct ContactEdition_Previews: PreviewProvider { static var previews: some View { var contact: Contact? = nil var showingEdit = true return ContactEdition(contact: Binding(get: { contact }, set: { new in contact = new }), showingEdit: Binding(get: { showingEdit }, set: { new in showingEdit = new })) } } <file_sep>// // Tag+image.swift // TimeLineShared // // Created by <NAME> on 24/04/2020. // Copyright © 2020 <NAME>. All rights reserved. // import SwiftUI extension Tag { public var swiftCircle: some View { Circle().foregroundColor(Color(red: self.red, green: self.green, blue: self.blue)) } public static func colorWithHue(_ hue: CGFloat) -> CPColor { CPColor( hue: hue, saturation: 1.0, brightness: 1.0, alpha: 1.0 ) } public static func randomColor() -> CPColor { Tag.colorWithHue(CGFloat(Double.random(in: 0 ... 359))) } } #if canImport(UIKit) import UIKit public typealias CPColor = UIColor public extension UIColor { var rgba: (red: CGFloat, green: CGFloat, blue: CGFloat, alpha: CGFloat) { var red: CGFloat = 0 var green: CGFloat = 0 var blue: CGFloat = 0 var alpha: CGFloat = 0 getRed(&red, green: &green, blue: &blue, alpha: &alpha) return (red, green, blue, alpha) } } extension Tag { public var color: UIColor { UIColor( red: CGFloat(self.red), green: CGFloat(self.green), blue: CGFloat(self.blue), alpha: 1 ) } public var image: UIImage { UIImage(systemName: "circle.fill")!.withTintColor(self.color, renderingMode: .alwaysOriginal) } } #elseif canImport(AppKit) import AppKit public typealias CPColor = NSColor public extension NSColor { var rgba: (red: CGFloat, green: CGFloat, blue: CGFloat, alpha: CGFloat) { let color = self.usingColorSpace(NSColorSpace.deviceRGB) ?? self return (color.redComponent, color.greenComponent, color.blueComponent, color.alphaComponent) } } #endif <file_sep>// // HostingController.swift // Time Lines WatchOS Extension // // Created by <NAME> on 13/04/2020. // Copyright © 2020 <NAME>. All rights reserved. // import WatchKit import WatchConnectivity import SwiftUI import TimeLineSharedWatchOS import CoreData struct WrapperView: View { var context: NSManagedObjectContext var body: some View { ContentView().environment(\.managedObjectContext, context) } } class HostingController: WKHostingController<WrapperView> { let context = CoreDataManager.shared.viewContext private var session = WCSession.default override var body: WrapperView { return WrapperView(context: context) } override func willActivate() { // This method is called when watch view controller is about to be visible to user super.willActivate() // 2: Initialization of session and set as delegate this InterfaceController if it's supported if WCSession.isSupported() { session.delegate = self session.activate() } } func sendMessage() { /** * The iOS device is within range, so communication can occur and the WatchKit extension is running in the * foreground, or is running with a high priority in the background (for example, during a workout session * or when a complication is loading its initial timeline data). */ guard session.isReachable else { print("iPhone is not reachable!!") return } session.sendMessage(["request" : "contacts"], replyHandler: { (response) in if let tags = response["tags"] as? [[String: Any]] { tags.forEach { tag in guard let name = tag["name"] as? String, name != NO_VALUE, let red = tag["red"] as? Double, let green = tag["green"] as? Double, let blue = tag["blue"] as? Double else { return } if let existingTag = CoreDataManager.shared.findTag(name) { existingTag.red = red existingTag.green = green existingTag.blue = blue } else { let color = UIColor(red: CGFloat(red), green: CGFloat(green), blue: CGFloat(blue), alpha: 1) CoreDataManager.shared.createTag( name: name, color: color ) } } } if let contacts = response["contacts"] as? [[String: Any]] { contacts.forEach { contact in guard let name = contact["name"] as? String, name != NO_VALUE, let latitude = contact["latitude"] as? Double, let longitude = contact["longitude"] as? Double, let timezone = contact["timezone"] as? Int32, let locationName = contact["locationName"] as? String, let startTime = contact["startTime"], let endTime = contact["endTime"], let favorite = contact["favorite"] as? Bool, let index = contact["index"] as? Int16, let tags = contact["tags"] as? [String] else { return } let fetchedTags = CoreDataManager.shared.findTags(tags) let resolvedStartTime = (startTime as? String == NO_VALUE || startTime as? Double == nil) ? nil : Date(timeIntervalSince1970: startTime as! Double) let resolvedEndTime = (endTime as? String == NO_VALUE || endTime as? Double == nil) ? nil : Date(timeIntervalSince1970: endTime as! Double) if let existingContact = CoreDataManager.shared.findContact(withName: name) { existingContact.latitude = latitude existingContact.longitude = longitude if locationName != NO_VALUE { existingContact.locationName = locationName } existingContact.timezone = timezone existingContact.startTime = resolvedStartTime existingContact.endTime = resolvedEndTime existingContact.tags = NSSet(array: fetchedTags) existingContact.favorite = favorite existingContact.index = index } else { let existingContact = CoreDataManager.shared.createContact( name: name, latitude: latitude, longitude: longitude, locationName: locationName != NO_VALUE ? locationName : "", timezone: timezone, startTime: resolvedStartTime, endTime: resolvedEndTime, tags: NSSet(array: fetchedTags), favorite: favorite ) existingContact?.index = index } } } CoreDataManager.shared.saveContext() }, errorHandler: { (error) in print("Error sending message: %@", error) }) } } extension HostingController: WCSessionDelegate { func session(_ session: WCSession, activationDidCompleteWith activationState: WCSessionActivationState, error: Error?) { print("activationDidCompleteWith activationState:\(activationState) error:\(String(describing: error))") sendMessage() } } <file_sep>// // TimeZone+location.swift // TimeLineShared // // Created by <NAME> on 23/04/2020. // Copyright © 2020 <NAME>. All rights reserved. // import Foundation import CoreLocation fileprivate var identifiersToLocation: [String: [Double]]? public extension TimeZone { private static func importTimeZoneData() -> [String: [Double]] { if let existingData = identifiersToLocation { return existingData } let currentBundle = Bundle(for: CoreDataManager.self) let filePath = currentBundle.url(forResource: "timezone-data", withExtension: ".json") do { if let filePath = filePath, let jsonData = try? Data(contentsOf: filePath), let timeZones = try JSONSerialization.jsonObject(with: jsonData, options: .allowFragments) as? [String: [Double]] { return timeZones } } catch let error as NSError { NSLog("Invalid timezoneDB format %@", error.localizedDescription) } return [String: [Double]]() } var roughLocation: CLLocationCoordinate2D? { guard let matchedLocation = TimeZone.importTimeZoneData().first(where: { $0.key == self.identifier }) else { return nil } return CLLocationCoordinate2D(latitude: matchedLocation.value[0], longitude: matchedLocation.value[1]) } } <file_sep>// // Contact+location.swift // Time Lines Shared // // Created by <NAME> on 02/04/2020. // Copyright © 2020 <NAME>. All rights reserved. // import Foundation import CoreLocation public extension Contact { var location: CLLocationCoordinate2D { CLLocationCoordinate2D( latitude: latitude, longitude: longitude ) } var timeZone: TimeZone? { TimeZone(secondsFromGMT: Int(self.timezone)) } func refreshTimeZone() { CLGeocoder().reverseGeocodeLocation(CLLocation(latitude: latitude, longitude: longitude)) { placemarks, error in if let placemarks = placemarks, placemarks.count > 0, let timezone = placemarks[0].timeZone, timezone.secondsFromGMT() != Int(self.timezone) { self.timezone = Int32(timezone.secondsFromGMT()) } } } } <file_sep>// // ContactRow.swift // Time Lines SharedWatchOS // // Created by <NAME> on 13/04/2020. // Copyright © 2020 <NAME>. All rights reserved. // import SwiftUI import CoreLocation public struct ContactRow: View { public var name: String public var timezone: TimeZone? public var coordinate: CLLocationCoordinate2D? public var startTime: Date? public var endTime: Date? public init(name: String, timezone: TimeZone?, coordinate: CLLocationCoordinate2D?, startTime: Date? = nil, endTime: Date? = nil) { self.name = name self.timezone = timezone self.coordinate = coordinate self.startTime = startTime self.endTime = endTime } public var body: some View { VStack { HStack { Text(name) .font(.system(size: 20)) .lineLimit(1) Spacer() Text(timezone?.prettyPrintTimeDiff() ?? "") .font(.caption) .foregroundColor(Color(UIColor.gray)) } Spacer() Line(coordinate: coordinate, timezone: timezone, startTime: startTime, endTime: endTime) .frame(height: 80) } } } public struct ContactRow_Previews: PreviewProvider { public static var previews: some View { Group { ContactRow(name: "Mathieu", timezone: TimeZone(secondsFromGMT: 0), coordinate: CLLocationCoordinate2D(latitude: 0, longitude: 0)) ContactRow(name: "Paul", timezone: TimeZone(secondsFromGMT: -3600), coordinate: CLLocationCoordinate2D(latitude: 0, longitude: 0)) ContactRow(name: "Paul", timezone: TimeZone(secondsFromGMT: +7800), coordinate: CLLocationCoordinate2D(latitude: 0, longitude: 0)) } .previewDevice("Apple Watch Series 4 - 44mm") } } <file_sep>// // CoreDataManager.swift // Time Lines Shared // // Created by <NAME> on 02/04/2020. // Copyright © 2020 <NAME>. All rights reserved. // import CoreData import SwiftUI public let NO_VALUE = "__no_value__" public class CoreDataManager { public static let shared = CoreDataManager() let groupIdentifier = "group.me.dutour.mathieu.TimeLine" let cloudkitIdentifier = "iCloud.me.dutour.mathieu.TimeLine" let model = "Model" lazy var persistentContainer: NSPersistentCloudKitContainer = { let messageKitBundle = Bundle(for: CoreDataManager.self) let modelURL = messageKitBundle.url(forResource: self.model, withExtension: "momd")! let managedObjectModel = NSManagedObjectModel(contentsOf: modelURL) /* The persistent container for the application. This implementation creates and returns a container, having loaded the store for the application to it. This property is optional since there are legitimate error conditions that could cause the creation of the store to fail. */ let container = NSPersistentCloudKitContainer(name: self.model, managedObjectModel: managedObjectModel!) let store = storeURL(for: groupIdentifier, databaseName: "TimeLine") let storeDescription = NSPersistentStoreDescription(url: store) storeDescription.cloudKitContainerOptions = NSPersistentCloudKitContainerOptions(containerIdentifier: cloudkitIdentifier) container.persistentStoreDescriptions = [storeDescription] container.loadPersistentStores(completionHandler: { (storeDescription, error) in if let error = error as NSError? { // Replace this implementation with code to handle the error appropriately. // fatalError() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development. /* Typical reasons for an error here include: * The parent directory does not exist, cannot be created, or disallows writing. * The persistent store is not accessible, due to permissions or data protection when the device is locked. * The device is out of space. * The store could not be migrated to the current model version. Check the error message to determine what the actual problem was. */ fatalError("Unresolved error \(error), \(error.userInfo)") } // set up cloud sync container.viewContext.automaticallyMergesChangesFromParent = true }) return container }() public lazy var viewContext: NSManagedObjectContext = { return self.persistentContainer.viewContext }() public func saveContext () { let context = persistentContainer.viewContext if context.hasChanges { do { try context.save() } catch { // Replace this implementation with code to handle the error appropriately. // fatalError() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development. let nserror = error as NSError fatalError("Unresolved error \(nserror), \(nserror.userInfo)") } } } public func findContact(_ uriRepresentation: String) -> Contact? { guard let url = URL(string: uriRepresentation), let objectID = persistentContainer.persistentStoreCoordinator.managedObjectID(forURIRepresentation: url) else { return nil } return viewContext.object(with: objectID) as? Contact } public func findContact(withName name: String) -> Contact? { let context = persistentContainer.viewContext let fetchRequest = NSFetchRequest<Contact>(entityName: "Contact") fetchRequest.sortDescriptors = [NSSortDescriptor(keyPath: \Contact.index, ascending: true)] fetchRequest.predicate = NSPredicate(format: "name == %@", name) do { let contacts = try context.fetch(fetchRequest) return contacts.first } catch let fetchErr { print("❌ Failed to fetch Contact:", fetchErr) return nil } } public func findTag(_ name: String) -> Tag? { let context = persistentContainer.viewContext let fetchRequest = NSFetchRequest<Tag>(entityName: "Tag") fetchRequest.sortDescriptors = [NSSortDescriptor(keyPath: \Tag.name, ascending: true)] fetchRequest.predicate = NSPredicate(format: "name == %@", name) do { let tags = try context.fetch(fetchRequest) return tags.first } catch let fetchErr { print("❌ Failed to fetch Tag:", fetchErr) return nil } } public func findTags(_ names: [String]) -> [Tag] { let context = persistentContainer.viewContext let fetchRequest = NSFetchRequest<Tag>(entityName: "Tag") fetchRequest.sortDescriptors = [NSSortDescriptor(keyPath: \Tag.name, ascending: true)] fetchRequest.predicate = NSPredicate(format: "name IN %@", names) do { let tags = try context.fetch(fetchRequest) return tags } catch let fetchErr { print("❌ Failed to fetch Tags:", fetchErr) return [] } } @discardableResult public func createContact(name: String, latitude: Double, longitude: Double, locationName: String, timezone: Int32, startTime: Date?, endTime: Date?, tags: NSSet?, favorite: Bool) -> Contact? { let index = self.count() let context = persistentContainer.viewContext let contact = NSEntityDescription.insertNewObject(forEntityName: "Contact", into: context) as! Contact contact.name = name contact.longitude = longitude contact.latitude = latitude contact.locationName = locationName contact.timezone = timezone contact.index = Int16(index) contact.startTime = startTime contact.endTime = endTime contact.tags = tags contact.favorite = favorite do { try context.save() print("✅ Contact saved succesfuly") return contact } catch let error { print("❌ Failed to create Contact: \(error.localizedDescription)") return nil } } @discardableResult public func createTag(name: String, color: CPColor = Tag.randomColor()) -> Tag? { let context = persistentContainer.viewContext let tag = NSEntityDescription.insertNewObject(forEntityName: "Tag", into: context) as! Tag tag.name = name let components = color.rgba tag.red = Double(components.red) tag.green = Double(components.green) tag.blue = Double(components.blue) do { try context.save() print("✅ Tag saved succesfuly") return tag } catch let error { print("❌ Failed to create Tag: \(error.localizedDescription)") return nil } } public func deleteContact(_ contact: Contact) { let context = persistentContainer.viewContext context.delete(contact) do { try context.save() print("✅ Contact deleted succesfuly") } catch let error { print("❌ Failed to delete Contact: \(error.localizedDescription)") } } public func deleteTag(_ tag: Tag) { let context = persistentContainer.viewContext context.delete(tag) do { try context.save() print("✅ Tag deleted succesfuly") } catch let error { print("❌ Failed to delete Tag: \(error.localizedDescription)") } } public func moveContact(from source: Int, to destination: Int) { if source == destination { return } let context = persistentContainer.viewContext context.performAndWait { var contacts = self.fetch() let sourceContact = contacts[source] contacts.remove(at: source) // for some reason, we need this var realDestination = destination if source < destination { realDestination -= 1 } if realDestination > contacts.count { contacts.append(sourceContact) } else { contacts.insert(sourceContact, at: realDestination) } var i = 0 for contact in contacts { contact.index = Int16(i) i += 1 } } do { try context.save() print("✅ Contact moved succesfuly") } catch let error { print("❌ Failed to moved Contact: \(error.localizedDescription)") } } public func fetch() -> [Contact] { let context = persistentContainer.viewContext let fetchRequest = NSFetchRequest<Contact>(entityName: "Contact") fetchRequest.sortDescriptors = [NSSortDescriptor(keyPath: \Contact.index, ascending: true)] do { let contacts = try context.fetch(fetchRequest) return contacts } catch let fetchErr { print("❌ Failed to fetch Contacts:", fetchErr) return [] } } public func fetchTags() -> [Tag] { let context = persistentContainer.viewContext let fetchRequest = NSFetchRequest<Tag>(entityName: "Tag") fetchRequest.sortDescriptors = [NSSortDescriptor(keyPath: \Tag.name, ascending: true)] do { let tags = try context.fetch(fetchRequest) return tags } catch let fetchErr { print("❌ Failed to fetch Tags:", fetchErr) return [] } } public func count() -> Int { let context = persistentContainer.viewContext let fetchRequest = NSFetchRequest<Contact>(entityName: "Contact") return (try? context.count(for: fetchRequest)) ?? 0 } /// Returns a URL for the given app group and database pointing to the sqlite database. private func storeURL(for appGroup: String, databaseName: String) -> URL { guard let fileContainer = FileManager.default.containerURL(forSecurityApplicationGroupIdentifier: appGroup) else { fatalError("Shared file container could not be created.") } return fileContainer.appendingPathComponent("\(databaseName).sqlite") } } <file_sep>// // Tags.swift // TimeLine // // Created by <NAME> on 26/04/2020. // Copyright © 2020 <NAME>. All rights reserved. // import SwiftUI import TimeLineShared struct Tags: View { @Environment(\.managedObjectContext) var context @EnvironmentObject var routeState: RouteState @FetchRequest( entity: Tag.entity(), sortDescriptors: [NSSortDescriptor(keyPath: \Tag.name, ascending: true)] ) var tags: FetchedResults<Tag> var body: some View { NavigationView { List { Button(action: { RouteState.shared.navigate(.editTag(tag: nil)) }) { HStack { Image(systemName: "plus").padding() Text("Add a new tag") } }.foregroundColor(Color(UIColor.secondaryLabel)) ForEach(tags, id: \Tag.name) { (tag: Tag) in Button(action: { RouteState.shared.navigate(.editTag(tag: tag)) }) { HStack { tag.swiftCircle.frame(width: 16, height: 16) Text(tag.name ?? "") Spacer() Text("\(tag.contacts?.count ?? 0) contacts").foregroundColor(Color(UIColor.secondaryLabel)) } } } .onDelete(perform: self.deleteTag) } .sheet(isPresented: self.$routeState.isEditingTag) { TagEdition().environment(\.managedObjectContext, self.context).environmentObject(self.routeState) } .navigationBarTitle(Text("Tags")) .navigationBarItems(leading: EditButton(), trailing: Button(action: { RouteState.shared.navigate(.list) }) { Text("Cancel") } ) }.navigationViewStyle(StackNavigationViewStyle()) } func deleteTag(at indexSet: IndexSet) { for index in indexSet { CoreDataManager.shared.deleteTag(tags[index]) } } } <file_sep>// // SearchController.swift // Time LinesMacOS // // Created by <NAME> on 08/04/2020. // Copyright © 2020 <NAME>. All rights reserved. // import SwiftUI import MapKit import Combine struct ButtonThatLookLikeRowStyle: ButtonStyle { func makeBody(configuration: Self.Configuration) -> some View { configuration.label .font(.body) .padding(10) .foregroundColor(Color(NSColor.labelColor)) .background(Color(NSColor.controlBackgroundColor)) .border(Color(NSColor.controlShadowColor), width: 0) } } struct ButtonThatLookLikeNothingStyle: ButtonStyle { func makeBody(configuration: Self.Configuration) -> some View { configuration.label .font(.body) .padding(.trailing, 3) .foregroundColor(Color(NSColor.secondaryLabelColor)) .background(Color(NSColor.clear)) .border(Color(NSColor.controlShadowColor), width: 0) } } class ObservableArray<T>: ObservableObject { @Published var array:[T] = [] var cancellables = [AnyCancellable]() init(array: [T]) { self.array = array } func observeChildrenChanges<T: ObservableObject>() -> ObservableArray<T> { let array2 = array as! [T] array2.forEach({ let c = $0.objectWillChange.sink(receiveValue: { _ in self.objectWillChange.send() }) // Important: You have to keep the returned value allocated, // otherwise the sink subscription gets cancelled self.cancellables.append(c) }) return self as! ObservableArray<T> } } struct SearchController<Result>: View where Result: View { var resultView: (_ mapItem: MKLocalSearchCompletion) -> Result @Environment(\.presentationMode) var presentationMode @ObservedObject var matchingItems: ObservableArray<MKLocalSearchCompletion> = ObservableArray(array: []) @State private var searchText = "" @State private var error: String? = nil var body: some View { VStack { // Search view HStack { ZStack(alignment: .leading) { AutoFocusTextField(placeholder: "Location", error: $error, text: $searchText, matchingItems: $matchingItems.array) .foregroundColor(.primary) .padding(.leading, 18) Image(nsImage: NSImage(named: NSImage.revealFreestandingTemplateName)!) if self.searchText != "" { HStack { Spacer() Button(action: { self.searchText = "" }) { Image(nsImage: NSImage(named: NSImage.stopProgressFreestandingTemplateName)!).opacity(searchText == "" ? 0 : 1) }.buttonStyle(ButtonThatLookLikeNothingStyle()) } } } .padding(EdgeInsets(top: 8, leading: 6, bottom: 8, trailing: 6)) .foregroundColor(.secondary) Button("Cancel") { self.presentationMode.wrappedValue.dismiss() } } .background(Color(.windowBackgroundColor)) .padding(.horizontal) GeometryReader { p in ScrollView(.vertical, showsIndicators: false) { VStack() { if self.error != nil { HStack { Text(self.error ?? "").padding().foregroundColor(.red) Spacer() } Divider() } ForEach(self.matchingItems.array, id:\.self) { searchText in VStack { HStack { self.resultView(searchText).listRowInsets(EdgeInsets()) Spacer() } Divider() } } Spacer() }.frame(width: p.size.width) }.background(Color(NSColor.controlBackgroundColor)).frame(width: p.size.width, height: p.size.height) } }.frame(minWidth: 300, minHeight: 250).background(Color(.windowBackgroundColor)) } } <file_sep>// // StatusBarController.swift // Time Lines macOS // // Created by <NAME> on 04/04/2020. // Copyright © 2020 <NAME>. All rights reserved. // import AppKit import SwiftUI import TimeLineSharedMacOS class StatusBarController: NSObject { private var statusItem: NSStatusItem private var popover: NSPopover private var statusBarButton: NSStatusBarButton private var eventMonitor: EventMonitor? private let menu = SSMenu() private var contentView: NSWindowController private var showingMenu = false init(_ popover: NSPopover, item: NSStatusItem, windowController: NSWindowController) { statusItem = item contentView = windowController statusBarButton = statusItem.button! self.popover = popover super.init() statusItem.behavior = [.removalAllowed, .terminationOnRemoval] statusBarButton.image = #imageLiteral(resourceName: "menu-bar") statusBarButton.image?.size = NSSize(width: 18.0, height: 18.0) statusBarButton.image?.isTemplate = true statusBarButton.toolTip = "Time Lines" statusBarButton.action = #selector(togglePopover(sender:)) statusBarButton.sendAction(on: NSEvent.EventTypeMask.leftMouseUp.union(.rightMouseUp)) statusBarButton.target = self eventMonitor = EventMonitor(mask: [.leftMouseDown, .rightMouseDown], handler: mouseEventHandler) menu.onUpdate = { _ in self.updateMenu() } menu.delegate = self } /** Quickly cycles through random colors to make a rainbow animation so the user will notice it. - Note: It will do nothing if the user has enabled the “Reduce motion” accessibility preference. */ func playRainbowAnimation(duration: TimeInterval = 5) { guard !NSWorkspace.shared.accessibilityDisplayShouldReduceMotion else { return } let originalTintColor = statusBarButton.contentTintColor Timer.scheduledRepeatingTimer( withTimeInterval: 0.1, duration: duration, onRepeat: { _ in self.statusBarButton.contentTintColor = NSColor.uniqueRandomSystemColor() }, onFinish: { self.statusBarButton.contentTintColor = originalTintColor } ) } } // MARK: Popover extension StatusBarController { @objc func togglePopover(sender: AnyObject) { if let event = NSApplication.shared.currentEvent, event.modifierFlags.contains(.control) || event.type == .rightMouseUp { // Handle right mouse click if popover.isShown { hidePopover(sender) } if showingMenu { hideRightClickMenu(sender) } else { showRightClickMenu(sender) } return } // Handle left mouse click if popover.isShown { hidePopover(sender) } else { showPopover(sender) } } func showPopover(_ sender: AnyObject) { let contacts = CoreDataManager.shared.count() // show the manage window when we don't have any contact if contacts == 0 { self.contentView.showWindow(self) return } let rowSize = 80 let dividerSize = 29 popover.contentSize = NSSize( width: 400, height: max(min(CGFloat(contacts * rowSize + (contacts - 1) * dividerSize), CGFloat(rowSize * 5 + dividerSize * 4)), 50) ) popover.show(relativeTo: statusBarButton.bounds, of: statusBarButton, preferredEdge: NSRectEdge.maxY) eventMonitor?.start() } func hidePopover(_ sender: AnyObject) { popover.performClose(sender) eventMonitor?.stop() } func mouseEventHandler(_ event: NSEvent?) { if popover.isShown { hidePopover(event ?? self) } if showingMenu { hideRightClickMenu(event ?? self) } } } // MARK: right click menu extension StatusBarController: NSMenuDelegate { func showRightClickMenu(_ sender: AnyObject) { hidePopover(sender) showingMenu = true statusItem.menu = menu // add menu to button... statusItem.button?.performClick(nil) // ...and click eventMonitor?.start() } func hideRightClickMenu(_ sender: AnyObject) { statusItem.menu?.cancelTracking() } func updateMenu() { menu.removeAllItems() menu.addCallbackItem("Manage Contacts…", key: ",") { _ in self.contentView.showWindow(self) } menu.addCallbackItem("Restore Purchases") { _ in IAPManager.shared.restorePurchases() { _ in } } let item = menu.addCallbackItem("Start at Login") { menuItem in LaunchAtLogin.isEnabled = !LaunchAtLogin.isEnabled menuItem.isChecked = LaunchAtLogin.isEnabled } item.isChecked = LaunchAtLogin.isEnabled menu.addSeparator() menu.addUrlItem("Send Feedback…", url: App.feedbackPage) menu.addQuitItem() } @objc func menuDidClose(_ menu: NSMenu) { showingMenu = false statusItem.menu = nil // remove menu so button works as before eventMonitor?.stop() statusBarButton.cell?.isHighlighted = false } } <file_sep>// // SearchBar.swift // Time Lines // // Created by <NAME> on 02/04/2020. // Copyright © 2020 <NAME>. All rights reserved. // import SwiftUI import MapKit struct LocationSearchController: UIViewControllerRepresentable { @State var matchingItems: [MKLocalSearchCompletion] = [] @State var error: String? = nil var searchBarPlaceholder: String var resultView: (_ mapItem: MKLocalSearchCompletion) -> Button<Text> func makeUIViewController(context: Context) -> UINavigationController { let contentViewController = UIHostingController(rootView: LocationSearchResultView(result: $matchingItems, error: $error, content: resultView)) let navigationController = UINavigationController(rootViewController: contentViewController) let searchController = UISearchController(searchResultsController: nil) searchController.searchResultsUpdater = context.coordinator searchController.delegate = context.coordinator searchController.obscuresBackgroundDuringPresentation = false // for results searchController.searchBar.placeholder = searchBarPlaceholder contentViewController.title = "Location" contentViewController.navigationItem.searchController = searchController contentViewController.navigationItem.hidesSearchBarWhenScrolling = true contentViewController.definesPresentationContext = true searchController.searchBar.delegate = context.coordinator return navigationController } func updateUIViewController(_ uiViewController: UINavigationController, context: UIViewControllerRepresentableContext<LocationSearchController>) { uiViewController.visibleViewController?.navigationItem.searchController?.searchBar.placeholder = searchBarPlaceholder if !context.coordinator.didBecomeFirstResponder, uiViewController.view.window != nil { context.coordinator.didBecomeFirstResponder = true uiViewController.visibleViewController?.navigationItem.searchController?.isActive = true } } } class LocationSearchControllerCoordinator: NSObject, UISearchResultsUpdating, UISearchBarDelegate, MKLocalSearchCompleterDelegate, UISearchControllerDelegate { var parent: LocationSearchController var didBecomeFirstResponder = false var searchCompleter = MKLocalSearchCompleter() init(_ parent: LocationSearchController) { self.parent = parent super.init() searchCompleter.delegate = self searchCompleter.resultTypes = .address } // MARK: - UISearchResultsUpdating func updateSearchResults(for searchController: UISearchController) { guard let text = searchController.searchBar.text, text.count > 0 else { self.parent.error = nil self.parent.matchingItems = [] return } searchCompleter.queryFragment = text } // MARK: - UISearchBarDelegate func searchBarCancelButtonClicked(_ searchBar: UISearchBar) { self.parent.error = nil self.parent.matchingItems = [] } func searchBarShouldBeginEditing(_ searchBar: UISearchBar) -> Bool { self.parent.error = nil self.parent.matchingItems = [] return true } // MARK: - UISearchControllerDelegate func didPresentSearchController(_ searchController: UISearchController) { DispatchQueue.main.async { searchController.searchBar.becomeFirstResponder() } } // MARK: - MKLocalSearchCompleterDelegate func completerDidUpdateResults(_ completer: MKLocalSearchCompleter) { self.parent.error = nil self.parent.matchingItems = completer.results } func completer(_ completer: MKLocalSearchCompleter, didFailWithError error: Error) { self.parent.error = error.localizedDescription } } extension LocationSearchController { func makeCoordinator() -> LocationSearchControllerCoordinator { LocationSearchControllerCoordinator(self) } } // "nofity" the result content about the searchText struct LocationSearchResultView<Content: View>: View { @Binding var matchingItems: [MKLocalSearchCompletion] @Binding var error: String? private var content: (_ mapItem: MKLocalSearchCompletion) -> Content init(result matchingItems: Binding<[MKLocalSearchCompletion]>, error: Binding<String?>, @ViewBuilder content: @escaping (_ mapItem: MKLocalSearchCompletion) -> Content) { self._matchingItems = matchingItems self._error = error self.content = content } var body: some View { List { if error != nil { Text(error ?? "").foregroundColor(.red) } ForEach(matchingItems, id: \.self) { (item: MKLocalSearchCompletion) in self.content(item) } } } } #if DEBUG struct TestSearchController: View { var body: some View { LocationSearchController(searchBarPlaceholder: "placeholder") { res in Button(action: {}) { Text(res.title) } } } } struct TestSearchController_Previews: PreviewProvider { static var previews: some View { TestSearchController() } } #endif <file_sep>// // ContactEdition.swift // Time Lines // // Created by <NAME> on 02/04/2020. // Copyright © 2020 <NAME>. All rights reserved. // import SwiftUI import TimeLineShared import MapKit import CoreLocation struct CustomTimePicker: View { var text: String @Binding var custom: Bool @Binding var time: Date var body: some View { VStack { Toggle(isOn: $custom) { Text(text) } if custom { DatePicker(selection: $time, displayedComponents: .hourAndMinute) { Text("") }.labelsHidden() } } } } struct ContactEdition: View { private var contact: Contact? @State private var contactName: String @State private var locationText = "" @State private var location: CLLocationCoordinate2D? @State private var showModal = false @State private var saving = false @State private var customStartTime = false @State private var customEndTime = false @State private var startTime: Date @State private var endTime: Date @State private var search = "" @State private var tags: [Tag] @State private var favorite = true @State private var timezone: TimeZone? @State private var locationCompletion: MKLocalSearchCompletion? init() { self.contact = RouteState.shared.editingContact let today = Calendar.current.startOfDay(for: Date()) _contactName = State(initialValue: contact?.name ?? "") _locationText = State(initialValue: contact?.locationName ?? "") _location = State(initialValue: contact?.location) _timezone = State(initialValue: contact?.timeZone) _customStartTime = State(initialValue: contact?.startTime != nil) _customEndTime = State(initialValue: contact?.endTime != nil) _startTime = State(initialValue: contact?.startTime?.inTodaysTime().addingTimeInterval(-TimeInterval(TimeZone.autoupdatingCurrent.secondsFromGMT())) ?? today.addingTimeInterval(3600 * 9)) _endTime = State(initialValue: contact?.endTime?.inTodaysTime().addingTimeInterval(-TimeInterval(TimeZone.autoupdatingCurrent.secondsFromGMT())) ?? today.addingTimeInterval(3600 * 18)) _tags = State(initialValue: contact?.tags?.map({ $0 as! Tag }) ?? []) _favorite = State(initialValue: contact?.favorite ?? true) } var body: some View { NavigationView { List { Section(footer: MapView(coordinate: location ?? CLLocationCoordinate2D(latitude: 0, longitude: 0), span: location == nil ? 45 : 0.02).frame(height: 150).padding(.init(top: -6, leading: -16, bottom: 0, trailing: -16))) { HStack { Text("Name") TextField("<NAME>", text: $contactName) .multilineTextAlignment(.trailing) .frame(alignment: .trailing) } HStack { Text("Location") Spacer() Button(action: { UIApplication.shared.endEditing(true) self.showModal = true }) { Text(locationText == "" ? "San Francisco" : locationText) .foregroundColor(Color(locationText == "" ? UIColor.placeholderText : UIColor.label)) .frame(alignment: .trailing) }.sheet(isPresented: self.$showModal) { LocationSearchController(searchBarPlaceholder: "Search for a place") { mapItem in Button(action: { self.locationCompletion = mapItem self.locationText = mapItem.title self.updateLocation(mapItem) self.showModal = false }) { Text(mapItem.title) } } } } } Section(footer: Text("Your favorite contacts will show up in the Today Widget.")) { Toggle(isOn: $favorite) { Text("Favorite") } } Section(footer: Text("You can add different tags to a contact to easily search for it in the list.")) { HStack { Text("Tags") SearchBar(placeholder: "Add tags...", search: $search, tokens: $tags, allowCreatingTokens: true) } } Section(footer: Text("A time line will show the dawn and twilight times at the location of the contact by default. You can customize those times if you'd like to show working hours for example.")) { CustomTimePicker(text: "Customize rise time", custom: $customStartTime, time: $startTime) CustomTimePicker(text: "Customize set time", custom: $customEndTime, time: $endTime) } } .listStyle(GroupedListStyle()) .keyboardAdaptive() .resignKeyboardOnDragGesture() .navigationBarTitle(Text(contact == nil ? "New Contact" : "Edit Contact")) .navigationBarItems(leading: Button(action: back) { Text("Cancel") }, trailing: Button(action: { if !self.saving { self.save() } }) { if self.saving { ActivityIndicator(isAnimating: true) } else { Text("Done") } } .disabled(!didUpdateUser() || !valid()) ) }.navigationViewStyle(StackNavigationViewStyle()) } func back() { if let contact = contact { RouteState.shared.navigate(.contact(contact: contact)) } else { RouteState.shared.navigate(.list) } } func didChangeTime(_ previousTime: Date?, _ custom: Bool, _ newTime: Date) -> Bool { return (previousTime == nil && custom) || (previousTime != nil && !custom) || (previousTime != nil && previousTime?.inTodaysTime().addingTimeInterval(-TimeInterval(TimeZone.autoupdatingCurrent.secondsFromGMT())) != newTime) } func didChangeLocation() -> Bool { return locationCompletion != nil && locationCompletion?.title != contact?.locationName } func didChangeName() -> Bool { return contactName.count > 0 && contactName != contact?.name } func didChangeTags() -> Bool { if let previousTags = contact?.arrayTags { return tags != previousTags } else { return tags.count > 0 } } func didChangeFavorite() -> Bool { if let previous = contact?.favorite { return previous != favorite } return false } func didUpdateUser() -> Bool { return didChangeLocation() || didChangeName() || didChangeTime(contact?.startTime, customStartTime, startTime) || didChangeTime(contact?.endTime, customEndTime, endTime) || didChangeTags() || didChangeFavorite() } func valid() -> Bool { return (locationCompletion != nil || contact?.locationName != nil) && contactName.count > 0 } func updateLocation(_ locationCompletion: MKLocalSearchCompletion) { let request = MKLocalSearch.Request(completion: locationCompletion) request.resultTypes = .address let search = MKLocalSearch(request: request) search.start { response, _ in guard let response = response, let mapItem = response.mapItems.first else { return } self.location = mapItem.placemark.location?.coordinate ?? CLLocationCoordinate2D(latitude: 0, longitude: 0) } } func save() { if let locationCompletion = locationCompletion, didChangeLocation() { saving = true // need to fetch the new location let request = MKLocalSearch.Request(completion: locationCompletion) request.resultTypes = .address let search = MKLocalSearch(request: request) search.start { response, _ in guard let response = response, let mapItem = response.mapItems.first else { return } self.timezone = mapItem.timeZone self.location = mapItem.placemark.location?.coordinate ?? CLLocationCoordinate2D(latitude: 0, longitude: 0) self.updateContact() self.back() } } else if didUpdateUser() { saving = true self.updateContact() back() } } func updateContact() { let resolvedStartTime = customStartTime ? startTime.addingTimeInterval(TimeInterval(TimeZone.autoupdatingCurrent.secondsFromGMT())) : nil let resolvedEndTime = customEndTime ? endTime.addingTimeInterval(TimeInterval(TimeZone.autoupdatingCurrent.secondsFromGMT())) : nil if let contact = contact { contact.name = contactName contact.latitude = location?.latitude ?? 0 contact.longitude = location?.longitude ?? 0 contact.locationName = locationText contact.timezone = Int32(timezone?.secondsFromGMT() ?? 0) contact.startTime = resolvedStartTime contact.endTime = resolvedEndTime contact.tags = NSSet(array: tags) contact.favorite = favorite CoreDataManager.shared.saveContext() } else { CoreDataManager.shared.createContact( name: contactName, latitude: location?.latitude ?? 0, longitude: location?.longitude ?? 0, locationName: locationText, timezone: Int32(timezone?.secondsFromGMT() ?? 0), startTime: resolvedStartTime, endTime: resolvedEndTime, tags: NSSet(array: tags), favorite: favorite ) } saving = false } } struct ContactEdition_Previews: PreviewProvider { static var previews: some View { return ContactEdition() } } <file_sep>// // AppDelegate.swift // Time LinesMacOS // // Created by <NAME> on 04/04/2020. // Copyright © 2020 <NAME>. All rights reserved. // import Cocoa import TimeLineSharedMacOS import SwiftUI import CoreData @NSApplicationMain class AppDelegate: NSObject, NSApplicationDelegate { var iapManager: IAPManager? var context: NSManagedObjectContext? var popover = NSPopover() var windowController = NSWindowController(window: NSWindow( contentRect: NSRect(x: 0, y: 0, width: 600, height: 400), styleMask: [.titled, .closable, .miniaturizable, .resizable, .fullSizeContentView], backing: .buffered, defer: false )) var statusItem = NSStatusBar.system.statusItem(withLength: NSStatusItem.squareLength) var statusBar: StatusBarController? func applicationDidFinishLaunching(_ aNotification: Notification) { iapManager = IAPManager.shared IAPManager.shared.startObserving() context = CoreDataManager.shared.viewContext let contentView = MenuView() .background(Color.clear) .environment(\.managedObjectContext, context!) .environment(\.inAppPurchaseContext, iapManager!) let vc = NSHostingController(rootView: contentView) popover.contentViewController = vc let manageView = ManageContacts() .background(Color.clear) .environment(\.managedObjectContext, context!) .environment(\.inAppPurchaseContext, iapManager!) if let window = windowController.window { window.delegate = self window.center() window.contentView = NSHostingView(rootView: manageView) window.setFrameAutosaveName("me.dutour.mathieu.timelinemacos.managecontacts") window.title = "" window.titlebarAppearsTransparent = true window.backgroundColor = NSColor.clear } // Create the Status Bar Item with the Popover statusBar = StatusBarController(popover, item: statusItem, windowController: windowController) showWelcomeScreenIfNeeded() } func showWelcomeScreenIfNeeded() { guard App.isFirstLaunch else { return } LaunchAtLogin.isEnabled = false NSApp.activate(ignoringOtherApps: true) NSAlert.showModal( message: "Welcome to Time Lines!", informativeText: """ Time Lines lives in the menu bar. Left-click it to see your contacts, right-click to see the options. See the project page for what else is planned: https://github.com/mathieudutour/TimeLines/issues If you have any feedback, bug reports, or feature requests, kindly use the “Send Feedback” button in the Time Lines menu. We respond to all submissions and reported issues will be dealt with swiftly. It's preferable that you report bugs this way rather than as an App Store review, since the App Store will not allow us to contact you for more information. """ ) statusBar?.playRainbowAnimation() } func applicationShouldTerminateAfterLastWindowClosed(_ sender: NSApplication) -> Bool { return false } func applicationWillTerminate(_ aNotification: Notification) { // Insert code here to tear down your application } } extension AppDelegate: NSWindowDelegate { func windowWillClose(_ notification: Notification) { // terminate the app if closing the manage contacts window without adding contacts if CoreDataManager.shared.count() <= 0 { NSApp.terminate(nil) } } } <file_sep>// // VisualEffectView.swift // Time Lines SharedMacOS // // Created by <NAME> on 07/04/2020. // Copyright © 2020 <NAME>. All rights reserved. // import SwiftUI public struct Blur: NSViewRepresentable { public var blendingMode: NSVisualEffectView.BlendingMode = .behindWindow public var material: NSVisualEffectView.Material = .windowBackground public init(blendingMode: NSVisualEffectView.BlendingMode = .behindWindow, material: NSVisualEffectView.Material = .windowBackground) { self.blendingMode = blendingMode self.material = material } public func makeNSView(context: Context) -> NSVisualEffectView { let view = NSVisualEffectView() view.blendingMode = blendingMode view.material = material view.state = NSVisualEffectView.State.active return view } public func updateNSView(_ uiView: NSVisualEffectView, context: Context) { uiView.blendingMode = blendingMode uiView.material = material } } <file_sep>// // InAppPurchases.swift // Time Lines Shared // // Created by <NAME> on 05/04/2020. // Copyright © 2020 <NAME>. All rights reserved. // import Foundation import StoreKit import SwiftUI public let sharedIAPPassword = "<PASSWORD>" let unlimitedContactsProductId = "unlimitedcontacts" struct IAPEnvironmentKey: EnvironmentKey { public static let defaultValue = IAPManager.shared } extension EnvironmentValues { public var inAppPurchaseContext : IAPManager { set { self[IAPEnvironmentKey.self] = newValue } get { self[IAPEnvironmentKey.self] } } } public class IAPManager: NSObject, ObservableObject { public static let shared = IAPManager() var onReceiveProductsHandler: ((Result<[SKProduct], IAPManagerError>) -> Void)? var onBuyProductHandler: ((Result<Bool, Error>) -> Void)? var totalRestoredPurchases = 0 @Published public var unlimitedContactsProduct: SKProduct? @Published public var hasAlreadyPurchasedUnlimitedContacts = UserDefaults.standard.bool(forKey: "\(unlimitedContactsProductId)_purchased") @Published public var contactsLimit = 3 public enum IAPManagerError: Error { case noProductIDsFound case noProductsFound case paymentWasCancelled case productRequestFailed } private override init() { super.init() getProducts { result in switch result { case .success(_): break case .failure(let error): print(error.errorDescription ?? error) } } } public func startObserving() { SKPaymentQueue.default().add(self) } public func stopObserving() { SKPaymentQueue.default().remove(self) } public func canBuy() -> Bool { return SKPaymentQueue.canMakePayments() } public func getProducts(withHandler productsReceiveHandler: @escaping (_ result: Result<[SKProduct], IAPManagerError>) -> Void) { onReceiveProductsHandler = productsReceiveHandler let request = SKProductsRequest(productIdentifiers: [unlimitedContactsProductId]) request.delegate = self request.start() } public func getPriceFormatted(for product: SKProduct) -> String? { let formatter = NumberFormatter() formatter.numberStyle = .currency formatter.locale = product.priceLocale return formatter.string(from: product.price) } public func buy(product: SKProduct, withHandler handler: @escaping ((_ result: Result<Bool, Error>) -> Void)) { let payment = SKPayment(product: product) SKPaymentQueue.default().add(payment) // Keep the completion handler. onBuyProductHandler = handler } public func restorePurchases(withHandler handler: @escaping ((_ result: Result<Bool, Error>) -> Void)) { onBuyProductHandler = handler totalRestoredPurchases = 0 SKPaymentQueue.default().restoreCompletedTransactions() } } extension IAPManager.IAPManagerError: LocalizedError { public var errorDescription: String? { switch self { case .noProductIDsFound: return "No In-App Purchase product identifiers were found." case .noProductsFound: return "No In-App Purchases were found." case .productRequestFailed: return "Unable to fetch available In-App Purchase products at the moment." case .paymentWasCancelled: return "In-App Purchase process was cancelled." } } } extension IAPManager: SKProductsRequestDelegate { public func productsRequest(_ request: SKProductsRequest, didReceive response: SKProductsResponse) { let products = response.products if products.count > 0 { self.unlimitedContactsProduct = products.first(where: { p in p.productIdentifier == unlimitedContactsProductId}) onReceiveProductsHandler?(.success(products)) } else { onReceiveProductsHandler?(.failure(.noProductsFound)) } } public func request(_ request: SKRequest, didFailWithError error: Error) { onReceiveProductsHandler?(.failure(.productRequestFailed)) } } extension IAPManager: SKPaymentTransactionObserver { public func paymentQueue(_ queue: SKPaymentQueue, updatedTransactions transactions: [SKPaymentTransaction]) { let defaults = UserDefaults.standard transactions.forEach { (transaction) in switch transaction.transactionState { case .purchased: defaults.set(true, forKey: "\(transaction.payment.productIdentifier)_purchased") if transaction.payment.productIdentifier == unlimitedContactsProductId { self.hasAlreadyPurchasedUnlimitedContacts = true } onBuyProductHandler?(.success(true)) SKPaymentQueue.default().finishTransaction(transaction) case .restored: defaults.set(true, forKey: "\(transaction.payment.productIdentifier)_purchased") if transaction.payment.productIdentifier == unlimitedContactsProductId { self.hasAlreadyPurchasedUnlimitedContacts = true } totalRestoredPurchases += 1 SKPaymentQueue.default().finishTransaction(transaction) case .failed: #if os(iOS) if let error = transaction.error as? SKError { if error.code != .paymentCancelled { onBuyProductHandler?(.failure(error)) } else { onBuyProductHandler?(.failure(IAPManagerError.paymentWasCancelled)) } print("IAP Error:", error.localizedDescription) } #else if let error = transaction.error { onBuyProductHandler?(.failure(error)) print("IAP Error:", error.localizedDescription) } #endif SKPaymentQueue.default().finishTransaction(transaction) case .deferred, .purchasing: break @unknown default: break } } } public func paymentQueueRestoreCompletedTransactionsFinished(_ queue: SKPaymentQueue) { if totalRestoredPurchases != 0 { onBuyProductHandler?(.success(true)) } else { print("IAP: No purchases to restore!") onBuyProductHandler?(.success(false)) } } public func paymentQueue(_ queue: SKPaymentQueue, restoreCompletedTransactionsFailedWithError error: Error) { print("IAP Restore Error:", error.localizedDescription) onBuyProductHandler?(.failure(error)) } } <file_sep># A list of devices you want to take the screenshots from devices([ "iPhone 8 Plus", "iPhone 11 Pro Max", "iPad Pro (12.9-inch) (2nd generation)", "iPad Pro (12.9-inch) (3rd generation)", ]) languages([ "en-US", "fr-FR", "es-ES", ]) # don't use concurrent simulators otherwise it fails with # "Lost connection to the application". (https://github.com/fastlane/fastlane/issues/13657) concurrent_simulators(false) # Choose which project/workspace to use workspace "./TimeLine.xcodeproj" # The name of the scheme which contains the UI Tests scheme("TimeLineUITests") # Pass some args to xcodebuild so that we can skip linting and such xcargs("\"FASTLANE_SNAPSHOT\"=\"YES\"") # Where should the resulting screenshots be stored? output_directory("./screenshots") # remove the '#' to clear all previously generated screenshots before creating new ones clear_previous_screenshots(true) # For more information about all available options run # fastlane action snapshot <file_sep>// // Contact+tags.swift // TimeLineShared // // Created by <NAME> on 24/04/2020. // Copyright © 2020 <NAME>. All rights reserved. // import Foundation extension Contact { public var arrayTags: [Tag] { return (self.tags?.allObjects as? [Tag] ?? []).sorted { ($0.name?.lowercased() ?? "") < ($1.name?.lowercased() ?? "") } } } <file_sep>// // Utils.swift // Time LinesMacOS // // Created by <NAME> on 05/04/2020. // Copyright © 2020 <NAME>. All rights reserved. // import Cocoa import SystemConfiguration import SwiftUI import TimeLineSharedMacOS final class SSMenu: NSMenu, NSMenuDelegate { var onOpen: (() -> Void)? var onClose: (() -> Void)? var onUpdate: ((NSMenu) -> Void)? { didSet { // Need to update it here, otherwise it's // positioned incorrectly on the first open. self.onUpdate?(self) } } private(set) var isOpen = false override init(title: String) { super.init(title: title) self.delegate = self self.autoenablesItems = false } @available(*, unavailable) required init(coder decoder: NSCoder) { fatalError("notYetImplemented") } func menuWillOpen(_ menu: NSMenu) { isOpen = true onOpen?() } func menuDidClose(_ menu: NSMenu) { isOpen = false onClose?() } func menuNeedsUpdate(_ menu: NSMenu) { onUpdate?(menu) } } extension NSAlert { /// Show an alert as a window-modal sheet, or as an app-modal (window-indepedendent) alert if the window is `nil` or not given. @discardableResult static func showModal( for window: NSWindow? = nil, message: String, informativeText: String? = nil, style: Style = .warning ) -> NSApplication.ModalResponse { NSAlert( message: message, informativeText: informativeText, style: style ).runModal(for: window) } convenience init( message: String, informativeText: String? = nil, style: Style = .warning ) { self.init() self.messageText = message self.alertStyle = style if let informativeText = informativeText { self.informativeText = informativeText } } /// Runs the alert as a window-modal sheet, or as an app-modal (window-indepedendent) alert if the window is `nil` or not given. @discardableResult func runModal(for window: NSWindow? = nil) -> NSApplication.ModalResponse { guard let window = window else { return runModal() } beginSheetModal(for: window) { returnCode in NSApp.stopModal(withCode: returnCode) } return NSApp.runModal(for: window) } } extension Timer { /// Creates a repeating timer that runs for the given `duration`. @discardableResult open class func scheduledRepeatingTimer( withTimeInterval interval: TimeInterval, duration: TimeInterval, onRepeat: @escaping (Timer) -> Void, onFinish: @escaping () -> Void ) -> Timer { let startDate = Date() return Timer.scheduledTimer(withTimeInterval: interval, repeats: true) { timer in guard Date() <= startDate.addingTimeInterval(duration) else { timer.invalidate() onFinish() return } onRepeat(timer) } } } extension Collection { /** Returns a infinite sequence with consecutively unique random elements from the collection. ``` let x = [1, 2, 3].uniqueRandomElementIterator() x.next() //=> 2 x.next() //=> 1 for element in x.prefix(2) { print(element) } //=> 3 //=> 1 ``` */ func uniqueRandomElementIterator() -> AnyIterator<Element> { var previousNumber: Int? return AnyIterator { var offset: Int repeat { offset = Int.random(in: 0..<self.count) } while offset == previousNumber previousNumber = offset let index = self.index(self.startIndex, offsetBy: offset) return self[index] } } } extension NSColor { static let systemColors: Set<NSColor> = [ .systemBlue, .systemBrown, .systemGray, .systemGreen, .systemOrange, .systemPink, .systemPurple, .systemRed, .systemYellow, .systemTeal, .systemIndigo ] private static let uniqueRandomSystemColors = systemColors.uniqueRandomElementIterator() static func uniqueRandomSystemColor() -> NSColor { uniqueRandomSystemColors.next()! } } extension Binding where Value: Equatable { /** Get notified when the binding value changes to a different one. Can be useful to manually update non-reactive properties. ``` Toggle( "Foo", isOn: $foo.onChange { bar.isEnabled = $0 } ) ``` */ func onChange(_ action: @escaping (Value) -> Void) -> Self { .init( get: { self.wrappedValue }, set: { let oldValue = self.wrappedValue self.wrappedValue = $0 let newValue = self.wrappedValue if newValue != oldValue { action(newValue) } } ) } /** Update the given property when the binding value changes to a different one. Can be useful to manually update non-reactive properties. - Note: Static key paths are not yet supported in Swift: https://forums.swift.org/t/key-path-cannot-refer-to-static-member/28055/2 ``` Toggle("Foo", isOn: $foo.onChange(for: bar, keyPath: \.isEnabled)) ``` */ func onChange<Object: AnyObject>( for object: Object, keyPath: ReferenceWritableKeyPath<Object, Value> ) -> Self { onChange { [weak object] newValue in object?[keyPath: keyPath] = newValue } } } extension Binding { /** Convert a binding with an optional value to a binding with a non-optional value by using the given default value if the binding value is `nil`. ``` struct ContentView: View { private static let defaultInterval = 60.0 private var interval: Binding<Double> { $optionalInterval.withDefaultValue(Self.defaultInterval) } var body: some View {} } ``` */ func withDefaultValue<T>(_ defaultValue: T) -> Binding<T> where Value == T? { .init( get: { self.wrappedValue ?? defaultValue }, set: { self.wrappedValue = $0 } ) } } extension Binding { /** Convert a binding with an optional value to a binding with a boolean value representing whether the original binding value is `nil`. - Parameter falseSetValue: The value used when the binding value is set to `false`. ``` struct ContentView: View { private static let defaultInterval = 60.0 private var doesNotHaveInterval: Binding<Bool> { $optionalInterval.isNil(falseSetValue: Self.defaultInterval) } var body: some View {} } ``` */ func isNil<T>(falseSetValue: T) -> Binding<Bool> where Value == T? { .init( get: { self.wrappedValue == nil }, set: { self.wrappedValue = $0 ? nil : falseSetValue } ) } /** Convert a binding with an optional value to a binding with a boolean value representing whether the original binding value is not `nil`. - Parameter trueSetValue: The value used when the binding value is set to `true`. ``` struct ContentView: View { private static let defaultInterval = 60.0 private var hasInterval: Binding<Bool> { $optionalInterval.isNotNil(trueSetValue: Self.defaultInterval) } var body: some View {} } ``` */ func isNotNil<T>(trueSetValue: T) -> Binding<Bool> where Value == T? { .init( get: { self.wrappedValue != nil }, set: { self.wrappedValue = $0 ? trueSetValue : nil } ) } } final class CallbackMenuItem: NSMenuItem { private static var validateCallback: ((NSMenuItem) -> Bool)? static func validate(_ callback: @escaping (NSMenuItem) -> Bool) { validateCallback = callback } init( _ title: String, key: String = "", keyModifiers: NSEvent.ModifierFlags? = nil, data: Any? = nil, isEnabled: Bool = true, isChecked: Bool = false, isHidden: Bool = false, callback: @escaping (NSMenuItem) -> Void ) { self.callback = callback super.init(title: title, action: #selector(action(_:)), keyEquivalent: key) self.target = self self.isEnabled = isEnabled self.isChecked = isChecked self.isHidden = isHidden if let keyModifiers = keyModifiers { self.keyEquivalentModifierMask = keyModifiers } } @available(*, unavailable) required init(coder decoder: NSCoder) { fatalError("notYetImplemented") } private let callback: (NSMenuItem) -> Void @objc func action(_ sender: NSMenuItem) { callback(sender) } } extension CallbackMenuItem: NSMenuItemValidation { func validateMenuItem(_ menuItem: NSMenuItem) -> Bool { Self.validateCallback?(menuItem) ?? true } } extension NSMenuItem { convenience init( _ title: String, action: Selector? = nil, key: String = "", keyModifiers: NSEvent.ModifierFlags? = nil, data: Any? = nil, isEnabled: Bool = true, isChecked: Bool = false, isHidden: Bool = false ) { self.init(title: title, action: action, keyEquivalent: key) self.representedObject = data self.isEnabled = isEnabled self.isChecked = isChecked self.isHidden = isHidden if let keyModifiers = keyModifiers { self.keyEquivalentModifierMask = keyModifiers } } convenience init( _ attributedTitle: NSAttributedString, action: Selector? = nil, key: String = "", keyModifiers: NSEvent.ModifierFlags? = nil, data: Any? = nil, isEnabled: Bool = true, isChecked: Bool = false, isHidden: Bool = false ) { self.init( "", action: action, key: key, keyModifiers: keyModifiers, data: data, isEnabled: isEnabled, isChecked: isChecked, isHidden: isHidden ) self.attributedTitle = attributedTitle } var isChecked: Bool { get { state == .on } set { state = newValue ? .on : .off } } } extension NSMenu { /// Get the `NSMenuItem` that has this menu as a submenu. var parentMenuItem: NSMenuItem? { guard let supermenu = supermenu else { return nil } let index = supermenu.indexOfItem(withSubmenu: self) return supermenu.item(at: index) } /// Get the item with the given identifier. func item(withIdentifier identifier: NSUserInterfaceItemIdentifier) -> NSMenuItem? { for item in items where item.identifier == identifier { return item } return nil } /// Remove the first item in the menu. func removeFirstItem() { removeItem(at: 0) } /// Remove the last item in the menu. func removeLastItem() { removeItem(at: numberOfItems - 1) } func addSeparator() { addItem(.separator()) } @discardableResult func add(_ menuItem: NSMenuItem) -> NSMenuItem { addItem(menuItem) return menuItem } @discardableResult func addDisabled(_ title: String) -> NSMenuItem { let menuItem = NSMenuItem(title) menuItem.isEnabled = false addItem(menuItem) return menuItem } @discardableResult func addDisabled(_ attributedTitle: NSAttributedString) -> NSMenuItem { let menuItem = NSMenuItem(attributedTitle) menuItem.isEnabled = false addItem(menuItem) return menuItem } @discardableResult func addItem( _ title: String, action: Selector? = nil, key: String = "", keyModifiers: NSEvent.ModifierFlags? = nil, data: Any? = nil, isEnabled: Bool = true, isChecked: Bool = false, isHidden: Bool = false ) -> NSMenuItem { let menuItem = NSMenuItem( title, action: action, key: key, keyModifiers: keyModifiers, data: data, isEnabled: isEnabled, isChecked: isChecked, isHidden: isHidden ) addItem(menuItem) return menuItem } @discardableResult func addItem( _ attributedTitle: NSAttributedString, action: Selector? = nil, key: String = "", keyModifiers: NSEvent.ModifierFlags? = nil, data: Any? = nil, isEnabled: Bool = true, isChecked: Bool = false, isHidden: Bool = false ) -> NSMenuItem { let menuItem = NSMenuItem( attributedTitle, action: action, key: key, keyModifiers: keyModifiers, data: data, isEnabled: isEnabled, isChecked: isChecked, isHidden: isHidden ) addItem(menuItem) return menuItem } @discardableResult func addCallbackItem( _ title: String, key: String = "", keyModifiers: NSEvent.ModifierFlags? = nil, data: Any? = nil, isEnabled: Bool = true, isChecked: Bool = false, isHidden: Bool = false, callback: @escaping (NSMenuItem) -> Void ) -> NSMenuItem { let menuItem = CallbackMenuItem( title, key: key, keyModifiers: keyModifiers, data: data, isEnabled: isEnabled, isChecked: isChecked, isHidden: isHidden, callback: callback ) addItem(menuItem) return menuItem } @discardableResult func addCallbackItem( _ title: NSAttributedString, key: String = "", keyModifiers: NSEvent.ModifierFlags? = nil, data: Any? = nil, isEnabled: Bool = true, isChecked: Bool = false, isHidden: Bool = false, callback: @escaping (NSMenuItem) -> Void ) -> NSMenuItem { let menuItem = CallbackMenuItem( "", key: key, keyModifiers: keyModifiers, data: data, isEnabled: isEnabled, isChecked: isChecked, isHidden: isHidden, callback: callback ) menuItem.attributedTitle = title addItem(menuItem) return menuItem } @discardableResult func addUrlItem(_ title: String, url: URL) -> NSMenuItem { addCallbackItem(title) { _ in NSWorkspace.shared.open(url) } } @discardableResult func addAboutItem() -> NSMenuItem { addCallbackItem("About") { NSApp.activate(ignoringOtherApps: true) NSApp.orderFrontStandardAboutPanel($0) } } @discardableResult func addQuitItem() -> NSMenuItem { addSeparator() return addCallbackItem("Quit \(App.name)", key: "q") { _ in NSApp.terminate(nil) } } } <file_sep>// // AutoFocusTextField.swift // Time LinesMacOS // // Created by <NAME> on 20/04/2020. // Copyright © 2020 <NAME>. All rights reserved. // import SwiftUI import AppKit import MapKit struct AutoFocusTextField: NSViewRepresentable { var placeholder: String? @Binding var error: String? @Binding var text: String @Binding var matchingItems: [MKLocalSearchCompletion] func makeCoordinator() -> Coordinator { Coordinator(self) } func makeNSView(context: NSViewRepresentableContext<AutoFocusTextField>) -> NSTextField { let textField = NSTextField() textField.delegate = context.coordinator textField.placeholderString = placeholder return textField } func updateNSView(_ uiView: NSTextField, context: NSViewRepresentableContext<AutoFocusTextField>) { uiView.stringValue = text uiView.placeholderString = placeholder if !context.coordinator.didSetFirstResponder, let window = uiView.window, window.firstResponder != uiView { context.coordinator.didSetFirstResponder = true uiView.becomeFirstResponder() } } class Coordinator: NSObject, NSTextFieldDelegate, MKLocalSearchCompleterDelegate { var parent: AutoFocusTextField var searchCompleter = MKLocalSearchCompleter() var didSetFirstResponder = false init(_ autoFocusTextField: AutoFocusTextField) { self.parent = autoFocusTextField super.init() searchCompleter.delegate = self searchCompleter.resultTypes = .address } // MARK: - MKLocalSearchCompleterDelegate func completerDidUpdateResults(_ completer: MKLocalSearchCompleter) { parent.error = nil parent.matchingItems = completer.results } func completer(_ completer: MKLocalSearchCompleter, didFailWithError error: Error) { print(error) parent.error = error.localizedDescription } // MARK: - NSTextFieldDelegate func controlTextDidChange(_ notification: Notification) { if let textField = notification.object as? NSTextField { parent.text = textField.stringValue if textField.stringValue.count > 0 { searchCompleter.queryFragment = textField.stringValue } else { parent.error = nil parent.matchingItems = [] } } } } } <file_sep>// // WidgetView.swift // Time Lines Widget // // Created by <NAME> on 03/04/2020. // Copyright © 2020 <NAME>. All rights reserved. // import SwiftUI import TimeLineShared import CoreLocation struct WidgetView : View { @Environment(\.managedObjectContext) var context @FetchRequest( entity: Contact.entity(), sortDescriptors: [NSSortDescriptor(keyPath: \Contact.index, ascending: true)], predicate: NSPredicate(format: "favorite == YES", argumentArray: []) ) var contacts: FetchedResults<Contact> var extensionContext: NSExtensionContext? var body: some View { List { ForEach(contacts, id: \.self) { (contact: Contact) in Button(action: { guard let url = URL(string: "timelines://contact/\(contact.objectID.uriRepresentation())") else { return } self.extensionContext?.open(url) }) { ContactRow( name: contact.name ?? "", timezone: contact.timeZone, coordinate: contact.location, startTime: contact.startTime, endTime: contact.endTime ).onAppear(perform: { contact.refreshTimeZone() }) } } } } } <file_sep>// // Date+timezone.swift // TimeLineShared // // Created by <NAME> on 23/04/2020. // Copyright © 2020 <NAME>. All rights reserved. // import Foundation let cal: Calendar = { var _cal = Calendar(identifier: .gregorian) _cal.timeZone = TimeZone(identifier: "UTC")! return _cal }() public extension Date { func inTimeZone(_ timezone: TimeZone?) -> Date { return self.addingTimeInterval(TimeInterval(timezone?.secondsFromGMT() ?? 0)) } func inTodaysTime(_ date: Date = Date()) -> Date { return cal.startOfDay(for: date).addingTimeInterval(self.timeIntervalSince(cal.startOfDay(for: self))) } static func fractionOfToday(_ fraction: Double) -> Date { let time = fraction >= 0 && fraction <= 1 ? 24 * 3600 * fraction : 24 * 3600 * fraction.truncatingRemainder(dividingBy: 1) return cal.startOfDay(for: Date()).addingTimeInterval(time) } func fractionOfToday(_ timezone: TimeZone?) -> Double { let inTZ = self.inTimeZone(timezone) return inTZ.timeIntervalSince(cal.startOfDay(for: inTZ)) / (3600 * 24) } func staticTime(_ now: Date, _ timezone: TimeZone?) -> Date { return self.inTodaysTime(now.inTimeZone(timezone)).addingTimeInterval(-TimeInterval(timezone?.secondsFromGMT() ?? 0)) } func isToday(_ timezone: TimeZone?) -> Bool { return cal.isDateInToday(self.inTimeZone(timezone)) } func isSameDay(_ date: Date, _ timezone: TimeZone?) -> Bool { return cal.isDate(self.inTimeZone(timezone), inSameDayAs: date.inTimeZone(timezone)) } } <file_sep>// // Utils.swift // Time Lines Shared // // Created by <NAME> on 06/04/2020. // Copyright © 2020 <NAME>. All rights reserved. // import SwiftUI import SystemConfiguration struct System { static let osVersion: String = { let os = ProcessInfo.processInfo.operatingSystemVersion return "\(os.majorVersion).\(os.minorVersion).\(os.patchVersion)" }() static let hardwareModel: String = { var size = 0 sysctlbyname("hw.model", nil, &size, nil, 0) var model = [CChar](repeating: 0, count: size) sysctlbyname("hw.model", &model, &size, nil, 0) return String(cString: model) }() } private func escapeQuery(_ query: String) -> String { // From RFC 3986 let generalDelimiters = ":#[]@" let subDelimiters = "!$&'()*+,;=" var allowedCharacters = CharacterSet.urlQueryAllowed allowedCharacters.remove(charactersIn: generalDelimiters + subDelimiters) return query.addingPercentEncoding(withAllowedCharacters: allowedCharacters) ?? query } extension Dictionary where Key: ExpressibleByStringLiteral, Value: ExpressibleByStringLiteral { var asQueryItems: [URLQueryItem] { map { URLQueryItem( name: escapeQuery($0 as! String), value: escapeQuery($1 as! String) ) } } var asQueryString: String { var components = URLComponents() components.queryItems = asQueryItems return components.query! } } extension URLComponents { mutating func addDictionaryAsQuery(_ dict: [String: String]) { percentEncodedQuery = dict.asQueryString } } extension URL { func addingDictionaryAsQuery(_ dict: [String: String]) -> Self { var components = URLComponents(url: self, resolvingAgainstBaseURL: false)! components.addDictionaryAsQuery(dict) return components.url ?? self } } public struct App { public static let id = Bundle.main.bundleIdentifier! public static let name = Bundle.main.object(forInfoDictionaryKey: kCFBundleNameKey as String) as! String static let version = Bundle.main.object(forInfoDictionaryKey: "CFBundleShortVersionString") as! String static let build = Bundle.main.object(forInfoDictionaryKey: kCFBundleVersionKey as String) as! String static let versionWithBuild = "\(version) (\(build))" static let url = Bundle.main.bundleURL public static let isFirstLaunch: Bool = { let key = "SS_hasLaunched" if UserDefaults.standard.bool(forKey: key) { return false } else { UserDefaults.standard.set(true, forKey: key) return true } }() public static var feedbackPage: URL = { #if os(iOS) let osName = "iOS" #elseif os(watchOS) let osName = "watchOS" #else let osName = "macOS" #endif let metadata = """ --- \(App.name) \(App.versionWithBuild) - \(App.id) \(osName) \(System.osVersion) \(System.hardwareModel) Timezone \(TimeZone.autoupdatingCurrent.identifier) """ let query: [String: String] = [ "title": "[Feedback] ", "body": metadata ] return URL(string: "https://github.com/mathieudutour/TimeLines/issues/new")!.addingDictionaryAsQuery(query) }() } <file_sep>// // TimeZone+print.swift // Time Lines Shared // // Created by <NAME> on 02/04/2020. // Copyright © 2020 <NAME>. All rights reserved. // import Foundation public extension TimeZone { private var dateFormatter: DateFormatter { let formatter = DateFormatter() formatter.dateStyle = .none formatter.timeStyle = .short return formatter } func diffInSecond() -> Int { return self.secondsFromGMT() - TimeZone.autoupdatingCurrent.secondsFromGMT() } func prettyPrintTimeDiff() -> String { let diff = self.diffInSecond() let formatter = NumberFormatter() formatter.usesSignificantDigits = true formatter.minimumSignificantDigits = 1 // default formatter.maximumSignificantDigits = 2 // default return "\(diff >= 0 ? "+" : "")\(formatter.string(from: NSNumber(value: Double(diff) / 3600)) ?? "")HRS" } func prettyPrintTime(_ time: Date) -> String { return dateFormatter.string(from: time.addingTimeInterval(TimeInterval(self.diffInSecond()))) } }
4f929dc47739e44c18ecac7d017d02826ecd39a0
[ "Swift", "Ruby", "Markdown" ]
39
Swift
ajunlonglive/TimeLines
383a2f8808711ff84c50b8762b1af1a790567029
189614863a13f3e95329198af38801400c25f88b
refs/heads/main
<repo_name>WJKwok/OMDbSearch<file_sep>/src/App.js import { BrowserRouter, Route } from 'react-router-dom'; import Container from '@material-ui/core/Container'; import { Nomination } from './Pages/Nomination'; import { Results } from './Pages/Results'; import { Banner } from './Components/Banner'; import { BannerContextProvider } from './Context/BannerContext'; function App() { return ( <BannerContextProvider> <Banner /> <Container> <BrowserRouter> <Route exact path="/" component={Nomination} /> <Route exact path="/results" component={Results} /> </BrowserRouter> </Container> </BannerContextProvider> ); } export default App; <file_sep>/src/Components/ClearLocalStorageButton.js import React from 'react'; import Button from '@material-ui/core/Button'; import { makeStyles } from '@material-ui/core/styles'; const useStyles = makeStyles({ root: { display: 'flex', justifyContent: 'flex-end', }, }); export const ClearLocalStorageButton = ({ additionalAction }) => { const classes = useStyles(); const clearLocalStorageHandler = () => { additionalAction(); localStorage.clear(); }; return ( <div className={classes.root}> <Button data-testid="clear-local-storage-button" variant="outlined" onClick={clearLocalStorageHandler} > Clear Local Storage </Button> </div> ); }; <file_sep>/src/ApolloProvider.js import React from 'react'; import App from './App'; import { ApolloProvider, ApolloClient, InMemoryCache } from '@apollo/client'; const client = new ApolloClient({ uri: process.env.NODE_ENV === 'production' ? 'https://shopify-code-challenge-backend.herokuapp.com/' : 'http://localhost:4000/', cache: new InMemoryCache(), }); export default ( <ApolloProvider client={client}> <React.StrictMode> <App /> </React.StrictMode> </ApolloProvider> ); <file_sep>/src/Components/ProgressBar.js import React, { useEffect } from 'react'; import { BannerCodeTypes, useSetBannerMessage } from '../Context/BannerContext'; import { makeStyles } from '@material-ui/core/styles'; import LinearProgress from '@material-ui/core/LinearProgress'; import Button from '@material-ui/core/Button'; import Typography from '@material-ui/core/Typography'; const useStyles = makeStyles({ root: { marginBottom: 10, }, progressDiv: { display: 'flex', alignItems: 'center', }, progressNumber: { margin: '0px 10px', }, progressBar: { flex: 1, }, }); export const ProgressBar = ({ goal, current, submitHandler }) => { const classes = useStyles(); const setBannerMessage = useSetBannerMessage(); const exceededGoal = current > goal; const reachedGoal = current === goal; const progress = exceededGoal ? 100 : (current / goal) * 100; const errorMessage = `🚨 You can only nominate 5 movies, please remove ${ current - goal }`; useEffect(() => { if (reachedGoal) { setBannerMessage({ text: 'You have nominated 5 movies, you may submit it now 😌', code: BannerCodeTypes.Success, }); } if (exceededGoal) { setBannerMessage({ text: errorMessage, code: BannerCodeTypes.Error, }); } }, [goal, current]); return ( <div className={classes.root}> <div className={classes.progressDiv}> <LinearProgress className={classes.progressBar} variant="determinate" color={exceededGoal ? 'secondary' : 'primary'} value={progress} /> <Typography className={classes.progressNumber} variant="body1"> {current}/{goal} </Typography> <Button data-testid="submit-nomination-button" variant="outlined" onClick={submitHandler} disabled={current !== goal} > Submit </Button> </div> {exceededGoal && ( <Typography variant="body1" color="secondary"> {errorMessage} </Typography> )} </div> ); }; <file_sep>/src/Pages/Nomination.js import React, { useState, useEffect } from 'react'; import debounce from 'lodash/debounce'; import { gql, useMutation } from '@apollo/client'; import { SearchBar } from '../Components/SearchBar'; import { SearchResultCards } from '../Components/SearchResultCards'; import { NominatedList } from '../Components/NominatedList'; import { ProgressBar } from '../Components/ProgressBar'; import { NextPageButton } from '../Components/NextPageButton'; import { OMDdBySearch, createOMDbURL } from '../Services/OMDbRequests'; import { useSetBannerMessage, BannerCodeTypes } from '../Context/BannerContext'; import { makeStyles } from '@material-ui/core/styles'; const useStyles = makeStyles({ root: { paddingTop: 20, }, horizontalScroll: { display: 'flex', overflowX: 'auto', padding: '20px 0px', }, }); export const Nomination = (props) => { const classes = useStyles(); const setBannerMessage = useSetBannerMessage(); const [searchInput, setSearchInput] = useState(''); const setSearchInputDebounced = debounce(setSearchInput, 500); const [currentResultPage, setCurrentResultPage] = useState(1); const [searchResults, setSearchResults] = useState({}); const [nominatedMovies, setNominatedMovies] = useState({}); const minNominatedMoviesLength = 5; useEffect(() => { if (localStorage.getItem('userNomination')) { const nominatedMoviesLocalStorage = JSON.parse( localStorage.getItem('userNomination') ); setNominatedMovies(nominatedMoviesLocalStorage); } if (localStorage.getItem('nominationSubmitted')) { setBannerMessage({ text: 'You have already submitted your nomination 🚨', code: BannerCodeTypes.Error, }); props.history.push('/results'); } }, []); useEffect(async () => { if (searchInput) { const OMDbRequestUrl = createOMDbURL(searchInput); const results = await OMDdBySearch(OMDbRequestUrl); setSearchResults(results); setCurrentResultPage(1); console.log(results); } }, [searchInput]); const nominationClickHandler = (movie) => { const newNominatedMovies = { ...nominatedMovies, ...movie }; setNominatedMovies(newNominatedMovies); localStorage.setItem('userNomination', JSON.stringify(newNominatedMovies)); }; const removeNominationHandler = (movieId) => { const nominatedMoviesCopy = { ...nominatedMovies, }; delete nominatedMoviesCopy[movieId]; setNominatedMovies(nominatedMoviesCopy); localStorage.setItem('userNomination', JSON.stringify(nominatedMoviesCopy)); }; const getNextPageOfResults = async () => { const nextPageToQuery = currentResultPage + 1; const OMDbRequestUrl = createOMDbURL(searchInput, nextPageToQuery); const results = await OMDdBySearch(OMDbRequestUrl); if (results.Response === 'True') { const appendedSearchResults = { ...searchResults, Search: [...searchResults.Search, ...results.Search], }; setSearchResults(appendedSearchResults); setCurrentResultPage((prev) => prev + 1); } }; const [submitNominations] = useMutation(NOMINATE_MOVIES, { onCompleted() { setBannerMessage({ text: 'Submission completed 🥳 Your nominations have a 👍 sign', code: BannerCodeTypes.Success, }); localStorage.setItem('nominationSubmitted', JSON.stringify(true)); props.history.push('/results'); }, variables: { movieInputs: Object.keys(nominatedMovies).map((movieKey) => { const movieData = nominatedMovies[movieKey]; delete movieData.Type; return movieData; }), }, onError({ graphQLErrors, networkError }) { if (graphQLErrors) { console.log('graphQLErrors', graphQLErrors); } if (networkError) { setBannerMessage({ text: `[Network Error]: ${networkError}`, code: BannerCodeTypes.Error, }); } }, }); return ( <div className={classes.root}> <SearchBar searchInputUpdate={setSearchInputDebounced} /> <div className={classes.horizontalScroll}> {searchResults.Response === 'True' ? ( <> <SearchResultCards searchResults={searchResults.Search} nominationClickHandler={nominationClickHandler} nominatedMovies={nominatedMovies} /> <NextPageButton onClick={getNextPageOfResults} /> </> ) : ( <p>{searchResults.Error}</p> )} </div> <ProgressBar current={Object.keys(nominatedMovies).length} goal={minNominatedMoviesLength} submitHandler={submitNominations} /> <NominatedList nominatedMovies={nominatedMovies} removeNominationHandler={removeNominationHandler} /> </div> ); }; const NOMINATE_MOVIES = gql` mutation nominateMovies($movieInputs: [MovieInput]!) { nominateMovies(movieInputs: $movieInputs) { Title voteCount } } `; <file_sep>/cypress/integration/my tests/fullTest.spec.js it('End to end test', () => { cy.visit('http://localhost:3000/'); // OMDb search const initialResultCardsLength = 0; cy.get('[data-testid=search-result-card]').should( 'have.length', initialResultCardsLength ); const initialSearchInput = 'funny'; const secondSearchInput = 'hell'; cy.get('[data-testid=search-bar]') .type(initialSearchInput) .then(() => { cy.get('[data-testid=search-result-card]').should((resultCards) => { expect(resultCards).to.have.length.greaterThan( initialResultCardsLength ); }); }) .then((resultCards) => { cy.log(resultCards.length); // next result page button cy.get('[data-testid=next-page-button]') .click() .wait(1000) .then(() => { cy.get('[data-testid=search-result-card]') .its('length') .should('be.greaterThan', resultCards.length); }); cy.get('[data-testid=search-result-card]'); }) .then((resultCards2) => { cy.log(resultCards2.length); cy.get('[data-testid=search-bar]').type( `${'{backspace}'.repeat(initialSearchInput.length)}${secondSearchInput}` ); cy.wait(1000).then(() => { cy.get('[data-testid=search-result-card]') .its('length') .should('be.lessThan', resultCards2.length); }); }); // nominating movies check state of submit button cy.get('[data-testid=submit-nomination-button]').should('be.disabled'); cy.get('[data-testid=nominate-button]').first().click(); cy.get('[data-testid=nominate-button]').first().click(); cy.get('[data-testid=nominate-button]').first().click(); cy.get('[data-testid=nominate-button]').first().click(); cy.get('[data-testid=submit-nomination-button]').should('be.disabled'); cy.get('[data-testid=nominate-button]').first().click(); cy.get('[data-testid=submit-nomination-button]').should('not.be.disabled'); // banner shows when 5 movies are nominated cy.get('[data-testid=banner]') .contains('You have nominated 5 movies') .should('have.length', 1); // error banner shows when > 5 movies are nominated cy.get('[data-testid=nominate-button]').first().click(); cy.get('[data-testid=submit-nomination-button]').should('be.disabled'); cy.get('[data-testid=banner]') .contains('🚨 You can only nominate 5 movies') .should('have.length', 1); // remove nomination button cy.get('[data-testid=remove-nomination-button]').first().click(); cy.get('[data-testid=banner]') .contains('You have nominated 5 movies') .should('have.length', 1); // submit nominations cy.get('[data-testid=submit-nomination-button]').should('not.be.disabled'); cy.get('[data-testid=submit-nomination-button]').click(); cy.get('[data-testid=nomination-result-card]') .its('length') .should('be.greaterThan', 4); cy.get('[data-testid=voted-emoji]').should('have.length', 5); //try returning to nomination page when nomination has been submitted cy.wait(1000).visit('http://localhost:3000/'); cy.get('[data-testid=banner]') .contains('You have already submitted your nomination') .should('have.length', 1); //clearing cache cy.get('[data-testid=clear-local-storage-button]').click(); cy.get('[data-testid=search-bar]').should('have.length', 1); //try viewing results page without nomination submission cy.wait(1000).visit('http://localhost:3000/results'); cy.get('[data-testid=banner]') .contains('Please submit nominations before viewing the result page') .should('have.length', 1); }); <file_sep>/src/Components/Banner.js import React, { useContext } from 'react'; import { makeStyles } from '@material-ui/core/styles'; import { red, green } from '@material-ui/core/colors/'; import Typography from '@material-ui/core/Typography'; import Slide from '@material-ui/core/Slide'; import { BannerContext } from '../Context/BannerContext'; const useStyles = makeStyles({ banner: (props) => ({ width: '100%', backgroundColor: props.backgroundColor, color: 'white', textAlign: 'center', position: 'absolute', top: 0, left: 0, zIndex: 1000, }), }); const bannerColorCode = { Error: red[500], Success: green[500], }; export const Banner = () => { const { bannerMessage } = useContext(BannerContext); const props = { backgroundColor: bannerColorCode[bannerMessage.code] }; const classes = useStyles(props); return ( <Slide data-testid="banner" direction="right" in={!!bannerMessage.text}> <Typography className={classes.banner} variant="body1" color="secondary"> {bannerMessage.text} </Typography> </Slide> ); }; <file_sep>/src/Components/NextPageButton.js import { makeStyles } from '@material-ui/core/styles'; import IconButton from '@material-ui/core/IconButton'; import AddCircleOutlineRoundedIcon from '@material-ui/icons/AddCircleOutlineRounded'; const useStyles = makeStyles((theme) => ({ iconButton: { padding: 20, alignSelf: 'center', }, })); export const NextPageButton = ({ onClick }) => { const classes = useStyles(); return ( <IconButton data-testid="next-page-button" className={classes.iconButton} aria-label="next result page" onClick={onClick} > <AddCircleOutlineRoundedIcon /> </IconButton> ); };
6ba10e2aebca6f5c4d66baa328fe42bf9c648d05
[ "JavaScript" ]
8
JavaScript
WJKwok/OMDbSearch
5a34829673182015ffe9e537327b6af79a05d7ae
768ecf145820349e271850836c96a462d9b649f4
refs/heads/master
<repo_name>ipsorus/xml_generator_FGIS2020<file_sep>/tets2.py # import xmlschema # schema_xsd = open('D:/load_testing/log/import.2020-04-14.xsd', encoding='utf-8').read() # schema = xmlschema.XMLSchema(schema_xsd) # result = schema.is_valid('D:/load_testing/single_test/5000/17-07_load_single_5000_1_signCipher_М.xml') # res = schema.validate('D:/load_testing/single_test/5000/17-07_load_single_5000_1_signCipher_М.xml') # print(result, res) # #print(schema, schema_xsd) # ===================== # import random # list = ['82', '81', '80', '79', '78', '77', '76', '75', '74', '73', '72', '71'] # print(list) # random.shuffle(list) # print(list) #================================ # from PyQt5.QtWidgets import * # import sys # class Window(QWidget): # def __init__(self): # QWidget.__init__(self) # layout = QGridLayout() # self.setLayout(layout) # radiobutton = QRadioButton("Australia") # radiobutton.setChecked(True) # radiobutton.country = "Australia" # radiobutton.toggled.connect(self.onClicked) # layout.addWidget(radiobutton, 0, 0) # radiobutton = QRadioButton("China") # radiobutton.country = "China" # radiobutton.toggled.connect(self.onClicked) # layout.addWidget(radiobutton, 0, 1) # radiobutton = QRadioButton("Japan") # radiobutton.country = "Japan" # radiobutton.toggled.connect(self.onClicked) # layout.addWidget(radiobutton, 0, 2) # def onClicked(self): # radioButton = self.sender() # if radioButton.isChecked(): # print("Country is %s" % (radioButton.country)) # app = QApplication(sys.argv) # screen = Window() # screen.show() # sys.exit(app.exec_()) #====================== # from PyQt5 import QtCore, QtGui, QtWidgets # import sys # class mainForm(QtWidgets.QWidget): # def __init__(self): # super().__init__() # self.runUi() # def runUi(self): # self.resize(250, 150) # self.move(300, 300) # self.setWindowTitle('Let\ Rock!') # self.setWindowIcon(QtGui.QIcon('icon.png')) # self.setMaximumSize(QtCore.QSize(560, 522)) # self.setMinimumSize(QtCore.QSize(560, 522)) # layout = QtWidgets.QVBoxLayout(self) # groupBoxGD = QtWidgets.QGroupBox('Соединение с ГД', self) # layout2 = QtWidgets.QVBoxLayout(groupBoxGD) # hrLWGDLink = QtWidgets.QWidget(groupBoxGD) # hrLGD = QtWidgets.QVBoxLayout(hrLWGDLink) # hrLGD.setContentsMargins(0, 0, 0, 0) # btnAddTab = QtWidgets.QPushButton(hrLWGDLink) # btnAddTab.setText('Add tab') # hrLGD.addWidget(btnAddTab) # self.tabWidget = QtWidgets.QTabWidget(hrLWGDLink) # hrLGD.addWidget(self.tabWidget) # layout2.addWidget(hrLWGDLink) # layout.addWidget(groupBoxGD) # btnAddTab.clicked.connect(self.addProjectTab) # def addProjectTab(self): # tab = QtWidgets.QWidget() # self.tabWidget.addTab(tab, "tab") # app = QtWidgets.QApplication(sys.argv) # w = mainForm() # w.show() # sys.exit(app.exec_()) #======================== # import sys # import os # from PyQt5 import (QtCore, QtWidgets, QtGui) # from PyQt5.QtGui import (QIcon) # from PyQt5.QtWidgets import (QMainWindow, QPushButton, QLabel, QLineEdit, QTextEdit) # from PyQt5.QtWidgets import (QWidget, QHBoxLayout, QVBoxLayout, QGroupBox, QGridLayout) # from PyQt5.QtWidgets import (QFormLayout, QSizePolicy, QAction, QToolBar) # from PyQt5.QtCore import (QSize, QProcess) # class MainWindow(QMainWindow): # def __init__(self): # super().__init__() # self.setWindowTitle('tabs mgmnt test') # self.setGeometry(50, 50, 600, 600) # self.toolbar = QToolBar('My Main Tool Bar') # self.addToolBar(self.toolbar) # newTabAct = QAction('New Tab', self) # self.toolbar.addAction(newTabAct) # newTabAct.triggered.connect(self.newTabHandler) # # ----------------------- newTabHandler() ------------------------ # def newTabHandler(self): # tab_widget = self.parentWidget().parentWidget() # # QStackedLayout QStackedWidget # # or # # tab_widget = self.window() # print(tab_widget) # count = tab_widget.count() # win = MainWindow() # tab_widget.addTab(win, "Tab-{}".format(count + 1)) # # ================================= main() ========================== # if (__name__ == "__main__"): # app = QtWidgets.QApplication(sys.argv) # tabs = QtWidgets.QTabWidget() # win = MainWindow() # tabs.addTab(win, "Tab-1" ) # tabs.show() # sys.exit ( app.exec_() ) #================================== # import sys # from PyQt5 import QtCore, QtWidgets, QtGui # from PyQt5.QtWidgets import (QLineEdit, QLabel, QSpinBox, QWidget, QProgressBar, QPushButton, QApplication) # from PyQt5.QtCore import QRect # from PyQt5.QtGui import QFont # class TabPage(QtWidgets.QWidget): # def __init__(self, parent=None): # super().__init__(parent) # self.initUI() # def initUI(self): # font_8 = QFont() # font_8.setFamily("MS Shell Dlg 2") # font_8.setPointSize(8) # font_8.setBold(False) # font_8.setWeight(50) # font_12 = QFont() # font_12.setFamily("Calibri") # font_12.setPointSize(12) # font_12.setBold(False) # font_12.setWeight(50) # self.label = QLabel("№ типа", self) # self.label.setGeometry(QRect(10, 10, 141, 16)) # self.label.setFont(font_8) # self.lineEdit = QLineEdit(self) # self.lineEdit.setGeometry(QRect(10, 30, 191, 31)) # self.lineEdit.setFont(font_12) # self.lineEdit.setFocusPolicy(QtCore.Qt.ClickFocus) # self.lineEdit.setClearButtonEnabled(True) # self.spinBox = QSpinBox(self) # self.spinBox.setGeometry(QRect(240, 30, 191, 31)) # self.spinBox.setFont(font_12) # self.spinBox.setCursor(QtGui.QCursor(QtCore.Qt.ArrowCursor)) # self.spinBox.setFocusPolicy(QtCore.Qt.ClickFocus) # self.spinBox.setWhatsThis("") # self.spinBox.setAccessibleName("") # self.spinBox.setAlignment(QtCore.Qt.AlignCenter) # self.spinBox.setMinimum(1917) # self.spinBox.setMaximum(2060) # self.spinBox.setProperty("value", 2020) # self.label = QLabel("Год выпуска *", self) # self.label.setGeometry(QRect(240, 10, 141, 16)) # self.label.setFont(font_8) # self.label = QLabel("Зав №", self) # self.label.setGeometry(QRect(470, 10, 141, 16)) # self.label.setFont(font_8) # self.lineEdit = QLineEdit(self) # self.lineEdit.setGeometry(QRect(470, 30, 191, 31)) # self.lineEdit.setFont(font_12) # self.lineEdit.setFocusPolicy(QtCore.Qt.ClickFocus) # self.lineEdit.setClearButtonEnabled(True) # self.lineEdit = QLineEdit(self) # self.lineEdit.setGeometry(QRect(10, 90, 651, 31)) # self.lineEdit.setFont(font_12) # self.lineEdit.setFocusPolicy(QtCore.Qt.ClickFocus) # self.lineEdit.setClearButtonEnabled(True) # self.label = QLabel("Характеристики СО", self) # self.label.setGeometry(QRect(10, 70, 211, 16)) # self.label.setFont(font_8) # self.btn = QPushButton('Печать в консоль', self) # self.btn.move(40, 150) # self.btn.clicked.connect(self.doAction) # self.show() # def doAction(self): # print(self.lineEdit.text()) # class Window(QtWidgets.QWidget): # def __init__(self): # super().__init__() # self.tabs = QtWidgets.QTabWidget() # layout = QtWidgets.QVBoxLayout(self) # layout.addWidget(self.tabs) # button = QtWidgets.QToolButton() # button.setToolTip('Add New Tab') # button.clicked.connect(self.addNewTab) # button.setIcon(self.style().standardIcon( # QtWidgets.QStyle.SP_DialogYesButton)) # self.tabs.setCornerWidget(button, QtCore.Qt.TopRightCorner) # self.addNewTab() # def addNewTab(self): # text = 'Tab %d' % (self.tabs.count() + 1) # self.tabs.addTab(TabPage(self.tabs), text) # if __name__ == '__main__': # app = QtWidgets.QApplication(sys.argv) # window = Window() # window.setGeometry(700, 300, 700, 300) # window.show() # sys.exit(app.exec_()) #=============================== import sys # from PyQt5 import QtCore, QtGui, QtWidgets # from PyQt5.Qt import * # class TabPage_SO(QWidget): # def __init__(self, parent=None): # super().__init__(parent) # self.labelType = QLabel("№ типа", self) # self.lineEditType = QLineEdit(self) # self.lineEditType.setClearButtonEnabled(True) # self.labelYearOfIssue = QLabel("Год выпуска *", self) # self.spinBox = QSpinBox(self) # self.spinBox.setCursor(QtGui.QCursor(QtCore.Qt.ArrowCursor)) # self.spinBox.setAlignment(QtCore.Qt.AlignCenter) # self.spinBox.setMinimum(1917) # self.spinBox.setMaximum(2060) # self.spinBox.setProperty("value", 2020) # self.labelSerialNumber = QLabel("Заводской №", self) # self.lineEditSerialNumber = QLineEdit(self) # self.lineEditSerialNumber.setClearButtonEnabled(True) # self.labelSpecifications = QLabel("Характеристики", self) # self.lineEditSpecifications = QLineEdit(self) # self.lineEditSpecifications.setClearButtonEnabled(True) # grid = QGridLayout(self) # grid.addWidget(self.labelType, 0, 0) # grid.addWidget(self.labelYearOfIssue, 0, 1) # grid.addWidget(self.labelSerialNumber, 0, 2) # grid.addWidget(self.lineEditType, 1, 0) # grid.addWidget(self.spinBox, 1, 1) # grid.addWidget(self.lineEditSerialNumber, 1, 2) # grid.addWidget(self.labelSpecifications, 2, 0) # grid.addWidget(self.lineEditSpecifications, 3, 0, 1, 3) # grid.setRowStretch(4, 1) # class TabWidget(QTabWidget): # def __init__(self): # super().__init__() # self.addTab(TabPage_SO(self), "Tab Zero") # count = self.count() # nb = QToolButton(text="Добавить", autoRaise=True) # nb.clicked.connect(self.new_tab) # self.insertTab(count, QWidget(), "") # self.tabBar().setTabButton(count, QTabBar.RightSide, nb) # def new_tab(self): # index = self.count() - 1 # self.insertTab(index, TabPage_SO(self), "Tab %d" % index) # self.setCurrentIndex(index) # class MainWindow(QMainWindow): # def __init__(self): # super().__init__() # self.centralWidget = QWidget() # self.setCentralWidget(self.centralWidget) # self.tabWidget = TabWidget() # self.tableWidget = QTableWidget(0, 4) # self.tableWidget.setHorizontalHeaderLabels( # ["№ типа", "Год выпуска *", "Заводской №", "Характеристики"]) # self.tableWidget.horizontalHeader().setSectionResizeMode(3, QHeaderView.Stretch) # self.tableWidget.setSortingEnabled(True) # self.tableWidget.setAlternatingRowColors(True) # self.buttonAdd = QPushButton('Добавить из текущей вкладки в таблицу') # self.buttonAdd.clicked.connect(self.addRowTable) # self.buttonDel = QPushButton('Удалить выбранную строку в таблице') # self.buttonDel.clicked.connect(self.delRowTable) # vbox = QGridLayout(self.centralWidget) # vbox.addWidget(self.tabWidget, 0, 0, 1, 2) # vbox.addWidget(self.tableWidget, 1, 0, 1, 2) # vbox.addWidget(self.buttonAdd, 2, 0) # vbox.addWidget(self.buttonDel, 2, 1) # def addRowTable(self): # editType = self.tabWidget.currentWidget().lineEditType.text() # spinYearOfIssue = str(self.tabWidget.currentWidget().spinBox.value()) # editSerialNumber = self.tabWidget.currentWidget().lineEditSerialNumber.text() # editSpecifications = self.tabWidget.currentWidget().lineEditSpecifications.text() # if not editType or not editSerialNumber or not editSpecifications: # msg = QMessageBox.information(self, 'Внимание', 'Заполните все поля!') # return # self.tableWidget.setSortingEnabled(False) # rows = self.tableWidget.rowCount() # self.tableWidget.insertRow(rows) # self.tableWidget.setItem(rows, 0, QTableWidgetItem(editType)) # self.tableWidget.setItem(rows, 1, QTableWidgetItem(spinYearOfIssue)) # self.tableWidget.setItem(rows, 2, QTableWidgetItem(editSerialNumber)) # self.tableWidget.setItem(rows, 3, QTableWidgetItem(editSpecifications)) # self.tableWidget.setSortingEnabled(True) # #print(editType, spinYearOfIssue, editSerialNumber, editSpecifications) # def delRowTable(self): # row = self.tableWidget.currentRow() # if row == -1: # msg = QMessageBox.information(self, 'Внимание', 'Выберите строку для удаления') # return # self.tableWidget.removeRow(row) # qss = """ # QLabel { # font: 8pt "MS Shell Dlg 2"; # } # QLineEdit { # font: 12pt "Calibri"; # } # QSpinBox { # font: 12pt "Calibri"; # } # """ # if __name__ == "__main__": # import sys # app = QApplication(sys.argv) # app.setStyleSheet(qss) # window = MainWindow() # window.show() # sys.exit(app.exec_()) #====================== # import sys # from PyQt5 import QtCore, QtGui, QtWidgets # from PyQt5.Qt import * # import time as timer # class MainWindow(QMainWindow): # def __init__(self): # super().__init__() # self.centralWidget = QWidget() # self.setCentralWidget(self.centralWidget) # self.textEdit = QTextEdit() # self.buttonAdd = QPushButton('Старт') # self.buttonAdd.clicked.connect(self.add_text) # vbox = QGridLayout(self.centralWidget) # vbox.addWidget(self.textEdit, 0, 0, 1, 2) # vbox.addWidget(self.buttonAdd, 2, 1) # def add_text(self): # for i in range(5): # timer.sleep(2) # self.insert_text(i) # QApplication.processEvents() # def insert_text(self, i): # self.textEdit.append(str(i)) # if __name__ == "__main__": # app = QApplication(sys.argv) # window = MainWindow() # window.show() # sys.exit(app.exec_()) #====================== # from PyQt5.QtWidgets import * # import sys # class MainWindow(QMainWindow): # def __init__(self): # super().__init__() # self.red_warning = "border-color: red; border-style: solid; border-width: 2px; font-weight: normal;" # self.centralWidget = QWidget() # self.setCentralWidget(self.centralWidget) # # Add toolbar and items # self.toolbox = QToolBox() # self.lineEdit_1 = QLineEdit() # self.toolbox.addItem(self.lineEdit_1, "Вкладка 1") # self.lineEdit_2 = QLineEdit() # self.toolbox.addItem(self.lineEdit_2, "Вкладка 2") # self.lineEdit_3 = QLineEdit() # self.toolbox.addItem(self.lineEdit_3, "Вкладка 3") # self.buttonAdd = QPushButton('Проверить') # self.buttonAdd.clicked.connect(self.check) # vbox = QGridLayout(self.centralWidget) # vbox.addWidget(self.toolbox, 0, 0, 1, 2) # vbox.addWidget(self.buttonAdd, 2, 1) # def check(self): # fields = [self.lineEdit_1, self.lineEdit_2, self.lineEdit_3] # for field in fields: # if field.text() != '' and field.text().isspace(): # field.setStyleSheet(self.red_warning) # elif field.text() == '': # field.setStyleSheet(self.red_warning) # else: # field.setStyleSheet('') # app = QApplication(sys.argv) # window = MainWindow() # window.show() # sys.exit(app.exec_()) #==================== # import sys # from PyQt5 import QtWidgets, QtCore, QtGui # from PyQt5.Qt import * # class MyToolBoxWidget(QtWidgets.QWidget): # def __init__(self, parent=None): # QtWidgets.QWidget.__init__(self, parent=parent) # self.vertical_layout = QtWidgets.QVBoxLayout(self) # self.vertical_layout.setContentsMargins(0, 0, 0, 0) # self.vertical_layout.setSpacing(0) # self.pages = [] # self.tabs = [] # self._first_v_spacerItem = QtWidgets.QSpacerItem( # 20, 40, QtWidgets.QSizePolicy.Minimum, QtWidgets.QSizePolicy.Expanding) # def addItem(self, page, name, color=None): # tab_button = QtWidgets.QPushButton(name) # font = QtGui.QFont() # font.setBold(True) # tab_button.setFont(font) # page.setSizePolicy(QtWidgets.QSizePolicy( # QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Expanding)) # page.hide() # self.pages.append(page) # self.tabs.append(tab_button) # self.vertical_layout.addWidget(tab_button) # self.vertical_layout.addWidget(page) # tab_button.clicked.connect(self._button_clicked) # if color: # self.setColor( (len(self.pages) - 1), color ) # def setColor(self, index, color): # palette = self.get_palette(color) # self.pages[index].setPalette(palette) # self.tabs[index].setPalette(palette) # self.pages[index].setAutoFillBackground(True) # def check_if_all_pages_are_hidden(self): # areHidden = True # for page in self.pages: # if not page.isHidden(): # areHidden = False # break # if areHidden: # self.vertical_layout.addItem(self._first_v_spacerItem) # else: # self.vertical_layout.removeItem(self._first_v_spacerItem) # def _button_clicked(self): # i = self.tabs.index(self.sender()) # if self.pages[i].isHidden(): # self.pages[i].show() # else: # self.pages[i].hide() # self.check_if_all_pages_are_hidden() # def get_palette(self, color): # palette = QtGui.QPalette() # brush = QtGui.QBrush(QtGui.QColor(0, 0, 0)) # brush.setStyle(QtCore.Qt.SolidPattern) # palette.setBrush(QtGui.QPalette.Active, QtGui.QPalette.WindowText, brush) # brush = QtGui.QBrush(QtGui.QColor(color)) # brush.setStyle(QtCore.Qt.SolidPattern) # palette.setBrush(QtGui.QPalette.Active, QtGui.QPalette.Button, brush) # brush = QtGui.QBrush(QtGui.QColor(color)) # brush.setStyle(QtCore.Qt.SolidPattern) # palette.setBrush(QtGui.QPalette.Active, QtGui.QPalette.Light, brush) # brush = QtGui.QBrush(QtGui.QColor(color)) # brush.setStyle(QtCore.Qt.SolidPattern) # palette.setBrush(QtGui.QPalette.Active, QtGui.QPalette.Midlight, brush) # brush = QtGui.QBrush(QtGui.QColor(color)) # brush.setStyle(QtCore.Qt.SolidPattern) # palette.setBrush(QtGui.QPalette.Active, QtGui.QPalette.Dark, brush) # brush = QtGui.QBrush(QtGui.QColor(color)) # brush.setStyle(QtCore.Qt.SolidPattern) # palette.setBrush(QtGui.QPalette.Active, QtGui.QPalette.Mid, brush) # brush = QtGui.QBrush(QtGui.QColor(0, 0, 0)) # brush.setStyle(QtCore.Qt.SolidPattern) # palette.setBrush(QtGui.QPalette.Active, QtGui.QPalette.Text, brush) # brush = QtGui.QBrush(QtGui.QColor(255, 255, 255)) # brush.setStyle(QtCore.Qt.SolidPattern) # palette.setBrush(QtGui.QPalette.Active, QtGui.QPalette.BrightText, brush) # brush = QtGui.QBrush(QtGui.QColor(0, 0, 0)) # brush.setStyle(QtCore.Qt.SolidPattern) # palette.setBrush(QtGui.QPalette.Active, QtGui.QPalette.ButtonText, brush) # brush = QtGui.QBrush(QtGui.QColor(color)) # brush.setStyle(QtCore.Qt.SolidPattern) # palette.setBrush(QtGui.QPalette.Active, QtGui.QPalette.Base, brush) # brush = QtGui.QBrush(QtGui.QColor(color)) # brush.setStyle(QtCore.Qt.SolidPattern) # palette.setBrush(QtGui.QPalette.Active, QtGui.QPalette.Window, brush) # brush = QtGui.QBrush(QtGui.QColor(color)) # brush.setStyle(QtCore.Qt.SolidPattern) # palette.setBrush(QtGui.QPalette.Active, QtGui.QPalette.Shadow, brush) # brush = QtGui.QBrush(QtGui.QColor(color)) # brush.setStyle(QtCore.Qt.SolidPattern) # palette.setBrush(QtGui.QPalette.Active, QtGui.QPalette.AlternateBase, brush) # brush = QtGui.QBrush(QtGui.QColor(color)) # brush.setStyle(QtCore.Qt.SolidPattern) # palette.setBrush(QtGui.QPalette.Active, QtGui.QPalette.ToolTipBase, brush) # brush = QtGui.QBrush(QtGui.QColor(0, 0, 0)) # brush.setStyle(QtCore.Qt.SolidPattern) # palette.setBrush(QtGui.QPalette.Active, QtGui.QPalette.ToolTipText, brush) # brush = QtGui.QBrush(QtGui.QColor(0, 0, 0)) # brush.setStyle(QtCore.Qt.SolidPattern) # palette.setBrush(QtGui.QPalette.Inactive, QtGui.QPalette.WindowText, brush) # brush = QtGui.QBrush(QtGui.QColor(color)) # brush.setStyle(QtCore.Qt.SolidPattern) # palette.setBrush(QtGui.QPalette.Inactive, QtGui.QPalette.Button, brush) # brush = QtGui.QBrush(QtGui.QColor(color)) # brush.setStyle(QtCore.Qt.SolidPattern) # palette.setBrush(QtGui.QPalette.Inactive, QtGui.QPalette.Light, brush) # brush = QtGui.QBrush(QtGui.QColor(color)) # brush.setStyle(QtCore.Qt.SolidPattern) # palette.setBrush(QtGui.QPalette.Inactive, QtGui.QPalette.Midlight, brush) # brush = QtGui.QBrush(QtGui.QColor(color)) # brush.setStyle(QtCore.Qt.SolidPattern) # palette.setBrush(QtGui.QPalette.Inactive, QtGui.QPalette.Dark, brush) # brush = QtGui.QBrush(QtGui.QColor(color)) # brush.setStyle(QtCore.Qt.SolidPattern) # palette.setBrush(QtGui.QPalette.Inactive, QtGui.QPalette.Mid, brush) # brush = QtGui.QBrush(QtGui.QColor(0, 0, 0)) # brush.setStyle(QtCore.Qt.SolidPattern) # palette.setBrush(QtGui.QPalette.Inactive, QtGui.QPalette.Text, brush) # brush = QtGui.QBrush(QtGui.QColor(255, 255, 255)) # brush.setStyle(QtCore.Qt.SolidPattern) # palette.setBrush(QtGui.QPalette.Inactive, QtGui.QPalette.BrightText, brush) # brush = QtGui.QBrush(QtGui.QColor(0, 0, 0)) # brush.setStyle(QtCore.Qt.SolidPattern) # palette.setBrush(QtGui.QPalette.Inactive, QtGui.QPalette.ButtonText, brush) # brush = QtGui.QBrush(QtGui.QColor(color)) # brush.setStyle(QtCore.Qt.SolidPattern) # palette.setBrush(QtGui.QPalette.Inactive, QtGui.QPalette.Base, brush) # brush = QtGui.QBrush(QtGui.QColor(color)) # brush.setStyle(QtCore.Qt.SolidPattern) # palette.setBrush(QtGui.QPalette.Inactive, QtGui.QPalette.Window, brush) # brush = QtGui.QBrush(QtGui.QColor(color)) # brush.setStyle(QtCore.Qt.SolidPattern) # palette.setBrush(QtGui.QPalette.Inactive, QtGui.QPalette.Shadow, brush) # brush = QtGui.QBrush(QtGui.QColor(color)) # brush.setStyle(QtCore.Qt.SolidPattern) # palette.setBrush(QtGui.QPalette.Inactive, QtGui.QPalette.AlternateBase, brush) # brush = QtGui.QBrush(QtGui.QColor(color)) # brush.setStyle(QtCore.Qt.SolidPattern) # palette.setBrush(QtGui.QPalette.Inactive, QtGui.QPalette.ToolTipBase, brush) # brush = QtGui.QBrush(QtGui.QColor(color)) # brush.setStyle(QtCore.Qt.SolidPattern) # palette.setBrush(QtGui.QPalette.Inactive, QtGui.QPalette.ToolTipText, brush) # brush = QtGui.QBrush(QtGui.QColor(42, 85, 0)) # brush.setStyle(QtCore.Qt.SolidPattern) # palette.setBrush(QtGui.QPalette.Disabled, QtGui.QPalette.WindowText, brush) # brush = QtGui.QBrush(QtGui.QColor(color)) # brush.setStyle(QtCore.Qt.SolidPattern) # palette.setBrush(QtGui.QPalette.Disabled, QtGui.QPalette.Button, brush) # brush = QtGui.QBrush(QtGui.QColor(color)) # brush.setStyle(QtCore.Qt.SolidPattern) # palette.setBrush(QtGui.QPalette.Disabled, QtGui.QPalette.Light, brush) # brush = QtGui.QBrush(QtGui.QColor(color)) # brush.setStyle(QtCore.Qt.SolidPattern) # palette.setBrush(QtGui.QPalette.Disabled, QtGui.QPalette.Midlight, brush) # brush = QtGui.QBrush(QtGui.QColor(color)) # brush.setStyle(QtCore.Qt.SolidPattern) # palette.setBrush(QtGui.QPalette.Disabled, QtGui.QPalette.Dark, brush) # brush = QtGui.QBrush(QtGui.QColor(color)) # brush.setStyle(QtCore.Qt.SolidPattern) # palette.setBrush(QtGui.QPalette.Disabled, QtGui.QPalette.Mid, brush) # brush = QtGui.QBrush(QtGui.QColor(42, 85, 0)) # brush.setStyle(QtCore.Qt.SolidPattern) # palette.setBrush(QtGui.QPalette.Disabled, QtGui.QPalette.Text, brush) # brush = QtGui.QBrush(QtGui.QColor(255, 255, 255)) # brush.setStyle(QtCore.Qt.SolidPattern) # palette.setBrush(QtGui.QPalette.Disabled, QtGui.QPalette.BrightText, brush) # brush = QtGui.QBrush(QtGui.QColor(42, 85, 0)) # brush.setStyle(QtCore.Qt.SolidPattern) # palette.setBrush(QtGui.QPalette.Disabled, QtGui.QPalette.ButtonText, brush) # brush = QtGui.QBrush(QtGui.QColor(color)) # brush.setStyle(QtCore.Qt.SolidPattern) # palette.setBrush(QtGui.QPalette.Disabled, QtGui.QPalette.Base, brush) # brush = QtGui.QBrush(QtGui.QColor(color)) # brush.setStyle(QtCore.Qt.SolidPattern) # palette.setBrush(QtGui.QPalette.Disabled, QtGui.QPalette.Window, brush) # brush = QtGui.QBrush(QtGui.QColor(color)) # brush.setStyle(QtCore.Qt.SolidPattern) # palette.setBrush(QtGui.QPalette.Disabled, QtGui.QPalette.Shadow, brush) # brush = QtGui.QBrush(QtGui.QColor(color)) # brush.setStyle(QtCore.Qt.SolidPattern) # palette.setBrush(QtGui.QPalette.Disabled, QtGui.QPalette.AlternateBase, brush) # brush = QtGui.QBrush(QtGui.QColor(color)) # brush.setStyle(QtCore.Qt.SolidPattern) # palette.setBrush(QtGui.QPalette.Disabled, QtGui.QPalette.ToolTipBase, brush) # brush = QtGui.QBrush(QtGui.QColor(color)) # brush.setStyle(QtCore.Qt.SolidPattern) # palette.setBrush(QtGui.QPalette.Disabled, QtGui.QPalette.ToolTipText, brush) # return palette # class MainWindow(QMainWindow): # def __init__(self): # super().__init__() # self.centralWidget = QWidget() # self.setCentralWidget(self.centralWidget) # self.my_tool_box = MyToolBoxWidget() # page1 = QtWidgets.QLineEdit() # self.my_tool_box.addItem(page=page1, name="Вкладка 1", color="#4ade00") # page2 = QtWidgets.QLineEdit() # self.my_tool_box.addItem(page=page2, name="Вкладка 2", color="#009deb") # page3 = QtWidgets.QLineEdit() # self.my_tool_box.addItem(page=page3, name="Вкладка 3", color="#f95300") # page4 = QtWidgets.QLineEdit() # self.my_tool_box.addItem(page=page4, name="Вкладка 4", color="#ccc") # # Добавить проставку в конце # self.my_tool_box.check_if_all_pages_are_hidden() # self.buttonAdd = QPushButton('Проверить') # self.buttonAdd.clicked.connect(self.check) # vbox = QGridLayout(self.centralWidget) # vbox.addWidget(self.my_tool_box, 0, 0, 1, 2) # vbox.addWidget(self.buttonAdd, 2, 1) # self.red_warning = """ # border-color: red; # border-style: solid; # border-width: 2px; # font-weight: normal; # """ # self.fields = [page1, page2, page3, page4] # def check(self): # # fields = [page1, page2, page3, page4] # # for field in self.fields: # for index, field in enumerate(self.fields): # if field.text() == '' or (field.text() != '' and field.text().isspace()): # field.setStyleSheet(self.red_warning) # self.my_tool_box.setColor(index, 'red') # # elif field.text() == '': # # field.setStyleSheet(self.red_warning) # else: # field.setStyleSheet('') # self.my_tool_box.setColor(index, '#00FF00') # if __name__ == '__main__': # import sys # app = QApplication(sys.argv) # app.setStyle('Fusion') # !!! Важно !!! # window = MainWindow() # window.show() # sys.exit(app.exec_()) #====================== # import sys # from PyQt5 import QtCore, QtGui, QtWidgets # from PyQt5.Qt import * # class TabPage_SO(QWidget): # def __init__(self, parent=None): # super().__init__(parent) # self.labelType = QLabel("№ типа", self) # self.lineEditType = QLineEdit(self) # self.lineEditType.setClearButtonEnabled(True) # self.labelYearOfIssue = QLabel("Год выпуска *", self) # self.spinBox = QSpinBox(self) # self.spinBox.setCursor(QtGui.QCursor(QtCore.Qt.ArrowCursor)) # self.spinBox.setAlignment(QtCore.Qt.AlignCenter) # self.spinBox.setMinimum(1917) # self.spinBox.setMaximum(2060) # self.spinBox.setProperty("value", 2020) # self.labelSerialNumber = QLabel("Заводской №", self) # self.lineEditSerialNumber = QLineEdit(self) # self.lineEditSerialNumber.setClearButtonEnabled(True) # self.labelSpecifications = QLabel("Характеристики", self) # self.lineEditSpecifications = QLineEdit(self) # self.lineEditSpecifications.setClearButtonEnabled(True) # grid = QGridLayout(self) # grid.addWidget(self.labelType, 0, 0) # grid.addWidget(self.labelYearOfIssue, 0, 1) # grid.addWidget(self.labelSerialNumber, 0, 2) # grid.addWidget(self.lineEditType, 1, 0) # grid.addWidget(self.spinBox, 1, 1) # grid.addWidget(self.lineEditSerialNumber, 1, 2) # grid.addWidget(self.labelSpecifications, 2, 0) # grid.addWidget(self.lineEditSpecifications, 3, 0, 1, 3) # grid.setRowStretch(4, 1) # class TabWidget(QTabWidget): # def __init__(self): # super().__init__() # self.addTab(TabPage_SO(self), "Tab Zero") # count = self.count() # nb = QToolButton(text="Добавить", autoRaise=True) # nb.clicked.connect(self.new_tab) # self.insertTab(count, QWidget(), "") # self.tabBar().setTabButton(count, QTabBar.RightSide, nb) # def new_tab(self): # index = self.count() - 1 # self.insertTab(index, TabPage_SO(self), "Tab %d" % index) # self.setCurrentIndex(index) # class MainWindow(QMainWindow): # def __init__(self): # super().__init__() # self.centralWidget = QWidget() # self.setCentralWidget(self.centralWidget) # self.red_warning = "border-color: red; border-style: solid; border-width: 2px; font-weight: normal;" # self.tableWidget = QTableWidget(0, 4) # self.tableWidget.setHorizontalHeaderLabels( # ["№ типа", "Год выпуска *", "Заводской №", "Характеристики"]) # self.tableWidget.horizontalHeader().setSectionResizeMode(3, QHeaderView.Stretch) # self.tableWidget.setSortingEnabled(True) # self.tableWidget.setAlternatingRowColors(True) # self.buttonAdd = QPushButton('Добавить из всех вкладок в таблицу') # self.buttonAdd.clicked.connect(self.addRowTable) # self.buttonDel = QPushButton('Удалить выбранную строку в таблице') # self.buttonDel.clicked.connect(self.delRowTable) # self.tabWidget = QTabWidget() # self.tabWidget.setTabsClosable(True) # count = self.tabWidget.count() # self.nb = QToolButton(text="Добавить", autoRaise=True) # self.nb.clicked.connect(self.new_tab) # self.tabWidget.insertTab(count, QWidget(), "") # self.tabWidget.tabBar().setTabButton(count, QTabBar.RightSide, self.nb) # self.new_tab() # self.tabWidget.tabCloseRequested.connect(self.closeTab_SO) # self.button_activate() # vbox = QGridLayout(self.centralWidget) # vbox.addWidget(self.tabWidget, 0, 0, 1, 2) # vbox.addWidget(self.tableWidget, 1, 0, 1, 2) # vbox.addWidget(self.buttonAdd, 2, 0) # vbox.addWidget(self.buttonDel, 2, 1) # def new_tab(self): # ''' # Создание нового ТАБа # ''' # index = self.tabWidget.count() - 1 # self.tabWidget.insertTab(index, TabPage_SO(self), "Tab %d" % index) # self.tabWidget.setCurrentIndex(index) # self.nb.setEnabled(False) # self.count = 0 # self.button_activate() # self.tabWidget.currentWidget().lineEditType.textChanged.connect(self.check_tabs) # self.tabWidget.currentWidget().lineEditSerialNumber.textChanged.connect(self.check_tabs) # self.tabWidget.currentWidget().lineEditSpecifications.textChanged.connect(self.check_tabs) # def closeTab_SO(self, currentIndex): # ''' # Удаление ТАБов # ''' # self.tabWidget.removeTab(currentIndex) # self.tabWidget.setCurrentIndex(self.tabWidget.count() - 2) # self.check_tabs() # def addRowTable(self): # for i in range(self.tabWidget.count()-1): # self.tabWidget.setCurrentIndex(i) # editType = self.tabWidget.currentWidget().lineEditType.text() # spinYearOfIssue = str(self.tabWidget.currentWidget().spinBox.value()) # editSerialNumber = self.tabWidget.currentWidget().lineEditSerialNumber.text() # editSpecifications = self.tabWidget.currentWidget().lineEditSpecifications.text() # if not editType: # msg = QMessageBox.information(self, 'Внимание', 'Заполните поле!') # return # self.tableWidget.setSortingEnabled(False) # rows = self.tableWidget.rowCount() # self.tableWidget.insertRow(rows) # self.tableWidget.setItem(rows, 0, QTableWidgetItem(editType)) # self.tableWidget.setItem(rows, 1, QTableWidgetItem(spinYearOfIssue)) # self.tableWidget.setItem(rows, 2, QTableWidgetItem(editSerialNumber)) # self.tableWidget.setItem(rows, 3, QTableWidgetItem(editSpecifications)) # self.tableWidget.setSortingEnabled(True) # def delRowTable(self): # row = self.tableWidget.currentRow() # if row == -1: # msg = QMessageBox.information(self, 'Внимание', 'Выберите строку для удаления') # return # self.tableWidget.removeRow(row) # def check_tabs(self): # ''' # Проверка заполнения поля lineEditType и проход по всем вкладкам для проверки заполнения # ''' # for i in range(self.tabWidget.count()-1): # self.tabWidget.setCurrentIndex(i) # if self.tabWidget.currentWidget().lineEditType.text() == '' or self.tabWidget.currentWidget().lineEditType.text().isspace(): # self.tabWidget.currentWidget().lineEditType.setStyleSheet(self.red_warning) # self.nb.setEnabled(False) # self.count = 0 # self.button_activate() # return # else: # self.tabWidget.currentWidget().lineEditType.setStyleSheet('') # self.nb.setEnabled(True) # self.count = 1 # self.button_activate() # def button_activate(self): # ''' # Активация кнопки self.buttonAdd # ''' # if self.count == 1: # self.buttonAdd.setEnabled(True) # else: # self.buttonAdd.setEnabled(False) # qss = """ # QLabel { # font: 8pt "MS Shell Dlg 2"; # } # QLineEdit { # font: 12pt "Calibri"; # } # QSpinBox { # font: 12pt "Calibri"; # } # """ # if __name__ == "__main__": # import sys # app = QApplication(sys.argv) # app.setStyleSheet(qss) # window = MainWindow() # window.show() # sys.exit(app.exec_()) #=========================== import sys from PyQt5 import QtCore, QtGui, QtWidgets from PyQt5.Qt import * class TabPage_SO(QWidget): def __init__(self, parent=None): super().__init__(parent) self.labelType = QLabel("№ типа", self) self.lineEditType = QLineEdit(self) self.lineEditType.setClearButtonEnabled(True) self.labelYearOfIssue = QLabel("Год выпуска *", self) self.spinBox = QSpinBox(self) self.spinBox.setCursor(QtGui.QCursor(QtCore.Qt.ArrowCursor)) self.spinBox.setAlignment(QtCore.Qt.AlignCenter) self.spinBox.setMinimum(1917) self.spinBox.setMaximum(2060) self.spinBox.setProperty("value", 2020) self.labelSerialNumber = QLabel("Заводской №", self) self.lineEditSerialNumber = QLineEdit(self) self.lineEditSerialNumber.setClearButtonEnabled(True) self.labelSpecifications = QLabel("Характеристики", self) self.lineEditSpecifications = QLineEdit(self) self.lineEditSpecifications.setClearButtonEnabled(True) grid = QGridLayout(self) grid.addWidget(self.labelType, 0, 0) grid.addWidget(self.labelYearOfIssue, 0, 1) grid.addWidget(self.labelSerialNumber, 0, 2) grid.addWidget(self.lineEditType, 1, 0) grid.addWidget(self.spinBox, 1, 1) grid.addWidget(self.lineEditSerialNumber, 1, 2) grid.addWidget(self.labelSpecifications, 2, 0) grid.addWidget(self.lineEditSpecifications, 3, 0, 1, 3) grid.setRowStretch(4, 1) class MainWindow(QMainWindow): def __init__(self): super().__init__() self.centralWidget = QWidget() self.setCentralWidget(self.centralWidget) self.red_warning = "border-color: red; border-style: solid; border-width: 2px; font-weight: normal;" self.tableWidget = QTableWidget(0, 4) self.tableWidget.setHorizontalHeaderLabels( ["№ типа", "Год выпуска *", "Заводской №", "Характеристики"]) self.tableWidget.horizontalHeader().setSectionResizeMode(3, QHeaderView.Stretch) self.tableWidget.setSortingEnabled(True) self.tableWidget.setAlternatingRowColors(True) self.buttonAdd = QPushButton('Добавить из всех вкладок в таблицу') self.buttonAdd.clicked.connect(self.addRowTable) self.buttonDel = QPushButton('Удалить выбранную строку в таблице') self.buttonDel.clicked.connect(self.delRowTable) self.tabWidget = QTabWidget() self.tabWidget.setTabsClosable(True) count = self.tabWidget.count() self.nb = QToolButton(text="Добавить", autoRaise=True) self.nb.clicked.connect(self.new_tab) self.tabWidget.insertTab(count, QWidget(), "") self.tabWidget.tabBar().setTabButton(count, QTabBar.RightSide, self.nb) self.new_tab() self.tabWidget.tabCloseRequested.connect(self.closeTab_SO) # - self.button_activate() vbox = QGridLayout(self.centralWidget) vbox.addWidget(self.tabWidget, 0, 0, 1, 2) vbox.addWidget(self.tableWidget, 1, 0, 1, 2) vbox.addWidget(self.buttonAdd, 2, 0) vbox.addWidget(self.buttonDel, 2, 1) # +++ vvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvv self.timer = QTimer() self.timer.setInterval(200) self.timer.timeout.connect(self.check_tabs) self.timer.start() # +++ ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ def new_tab(self): ''' Создание нового ТАБа ''' index = self.tabWidget.count() - 1 # self.tabWidget.insertTab(index, TabPage_SO(self), "Tab %d" % index) tabPage_SO = TabPage_SO(self) # + self.tabWidget.insertTab(index, tabPage_SO, "Tab %d" % index) # + self.tabWidget.setCurrentIndex(index) self.nb.setEnabled(False) self.count = 0 self.button_activate(False) # +++ False ### #- self.tabWidget.currentWidget().lineEditType.textChanged.connect(self.check_tabs) #? self.tabWidget.currentWidget().lineEditSerialNumber.textChanged.connect(self.check_tabs) #? self.tabWidget.currentWidget().lineEditSpecifications.textChanged.connect(self.check_tabs) def closeTab_SO(self, currentIndex): ''' Удаление ТАБов ''' self.tabWidget.removeTab(currentIndex) self.tabWidget.setCurrentIndex(self.tabWidget.count() - 2) #- self.check_tabs() def addRowTable(self): for i in range(self.tabWidget.count()-1): self.tabWidget.setCurrentIndex(i) editType = self.tabWidget.currentWidget().lineEditType.text() spinYearOfIssue = str(self.tabWidget.currentWidget().spinBox.value()) editSerialNumber = self.tabWidget.currentWidget().lineEditSerialNumber.text() editSpecifications = self.tabWidget.currentWidget().lineEditSpecifications.text() if not editType: msg = QMessageBox.information(self, 'Внимание', 'Заполните поле!') return self.tableWidget.setSortingEnabled(False) rows = self.tableWidget.rowCount() self.tableWidget.insertRow(rows) self.tableWidget.setItem(rows, 0, QTableWidgetItem(editType)) self.tableWidget.setItem(rows, 1, QTableWidgetItem(spinYearOfIssue)) self.tableWidget.setItem(rows, 2, QTableWidgetItem(editSerialNumber)) self.tableWidget.setItem(rows, 3, QTableWidgetItem(editSpecifications)) self.tableWidget.setSortingEnabled(True) def delRowTable(self): row = self.tableWidget.currentRow() if row == -1: msg = QMessageBox.information(self, 'Внимание', 'Выберите строку для удаления') return self.tableWidget.removeRow(row) # !!! def check_tabs(self): ''' Проверка заполнения поля lineEditType и проход по всем вкладкам для проверки заполнения ''' print('timer') # +++ vvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvv flag = True for i in range(self.tabWidget.count()-1): line_edit_type = self.tabWidget.widget(i).lineEditType.text() if not line_edit_type: flag = False self.nb.setEnabled(False) break if flag: self.nb.setEnabled(True), self.tabWidget.currentWidget().lineEditType.setStyleSheet('') else: self.nb.setEnabled(False), self.tabWidget.currentWidget().lineEditType.setStyleSheet(self.red_warning) self.button_activate(flag) # +++ ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ ''' for i in range(self.tabWidget.count()-1): self.tabWidget.setCurrentIndex(i) if self.tabWidget.currentWidget().lineEditType.text() == '' or self.tabWidget.currentWidget().lineEditType.text().isspace(): self.tabWidget.currentWidget().lineEditType.setStyleSheet(self.red_warning) self.nb.setEnabled(False) self.count = 0 self.button_activate() return else: self.tabWidget.currentWidget().lineEditType.setStyleSheet('') self.nb.setEnabled(True) self.count = 1 self.button_activate() ''' def button_activate(self, flag): # +++ flag ''' Активация кнопки self.buttonAdd ''' if flag: # flag self.buttonAdd.setEnabled(True) # показать else: self.buttonAdd.setEnabled(False) qss = """ QLabel { font: 8pt "MS Shell Dlg 2"; } QLineEdit { font: 12pt "Calibri"; } QSpinBox { font: 12pt "Calibri"; } """ if __name__ == "__main__": import sys app = QApplication(sys.argv) app.setStyleSheet(qss) window = MainWindow() window.show() sys.exit(app.exec_())<file_sep>/MainWindow_poverki_2020.py # -*- coding: utf-8 -*- # Form implementation generated from reading ui file 'MainWindow_poverki_2020.ui' # # Created by: PyQt5 UI code generator 5.9.2 # # WARNING! All changes made in this file will be lost! from PyQt5 import QtCore, QtGui, QtWidgets class Ui_MainWindow(object): def setupUi(self, MainWindow): MainWindow.setObjectName("MainWindow") MainWindow.setEnabled(True) MainWindow.resize(730, 720) sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Preferred, QtWidgets.QSizePolicy.Preferred) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth(MainWindow.sizePolicy().hasHeightForWidth()) MainWindow.setSizePolicy(sizePolicy) MainWindow.setMinimumSize(QtCore.QSize(730, 720)) MainWindow.setMaximumSize(QtCore.QSize(730, 720)) font = QtGui.QFont() font.setFamily("Calibri") font.setPointSize(12) MainWindow.setFont(font) MainWindow.setContextMenuPolicy(QtCore.Qt.NoContextMenu) icon = QtGui.QIcon() icon.addPixmap(QtGui.QPixmap(":/icons/IconBook.ico"), QtGui.QIcon.Normal, QtGui.QIcon.Off) MainWindow.setWindowIcon(icon) MainWindow.setStyleSheet("") MainWindow.setToolButtonStyle(QtCore.Qt.ToolButtonIconOnly) MainWindow.setDocumentMode(False) MainWindow.setTabShape(QtWidgets.QTabWidget.Rounded) MainWindow.setUnifiedTitleAndToolBarOnMac(False) self.centralwidget = QtWidgets.QWidget(MainWindow) sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Fixed, QtWidgets.QSizePolicy.Fixed) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth(self.centralwidget.sizePolicy().hasHeightForWidth()) self.centralwidget.setSizePolicy(sizePolicy) self.centralwidget.setMinimumSize(QtCore.QSize(730, 720)) self.centralwidget.setMaximumSize(QtCore.QSize(730, 720)) self.centralwidget.setObjectName("centralwidget") self.tabWidget = QtWidgets.QTabWidget(self.centralwidget) self.tabWidget.setGeometry(QtCore.QRect(10, 140, 711, 531)) font = QtGui.QFont() font.setFamily("Calibri") font.setPointSize(12) font.setBold(True) font.setItalic(False) font.setWeight(75) self.tabWidget.setFont(font) self.tabWidget.setFocusPolicy(QtCore.Qt.ClickFocus) self.tabWidget.setAutoFillBackground(False) self.tabWidget.setStyleSheet("") self.tabWidget.setInputMethodHints(QtCore.Qt.ImhNone) self.tabWidget.setObjectName("tabWidget") self.tab = QtWidgets.QWidget() self.tab.setObjectName("tab") self.groupBox = QtWidgets.QGroupBox(self.tab) self.groupBox.setGeometry(QtCore.QRect(10, 310, 681, 181)) font = QtGui.QFont() font.setFamily("Calibri") font.setPointSize(12) font.setBold(True) font.setItalic(False) font.setWeight(75) self.groupBox.setFont(font) self.groupBox.setObjectName("groupBox") self.line = QtWidgets.QFrame(self.groupBox) self.line.setGeometry(QtCore.QRect(10, 30, 661, 16)) self.line.setFrameShape(QtWidgets.QFrame.HLine) self.line.setFrameShadow(QtWidgets.QFrame.Sunken) self.line.setObjectName("line") self.label_15 = QtWidgets.QLabel(self.groupBox) self.label_15.setGeometry(QtCore.QRect(470, 80, 201, 31)) font = QtGui.QFont() font.setFamily("MS Shell Dlg 2") font.setPointSize(8) font.setBold(False) font.setItalic(False) font.setWeight(50) self.label_15.setFont(font) self.label_15.setAutoFillBackground(False) self.label_15.setLineWidth(1) self.label_15.setMidLineWidth(1) self.label_15.setObjectName("label_15") self.label_12 = QtWidgets.QLabel(self.groupBox) self.label_12.setGeometry(QtCore.QRect(10, 80, 191, 31)) font = QtGui.QFont() font.setFamily("MS Shell Dlg 2") font.setPointSize(8) font.setBold(False) font.setItalic(False) font.setWeight(50) self.label_12.setFont(font) self.label_12.setAutoFillBackground(False) self.label_12.setLineWidth(1) self.label_12.setMidLineWidth(1) self.label_12.setObjectName("label_12") self.label_14 = QtWidgets.QLabel(self.groupBox) self.label_14.setGeometry(QtCore.QRect(240, 80, 151, 31)) font = QtGui.QFont() font.setFamily("MS Shell Dlg 2") font.setPointSize(8) font.setBold(False) font.setItalic(False) font.setWeight(50) self.label_14.setFont(font) self.label_14.setAutoFillBackground(False) self.label_14.setLineWidth(1) self.label_14.setMidLineWidth(1) self.label_14.setObjectName("label_14") self.lineEdit_3 = QtWidgets.QLineEdit(self.groupBox) self.lineEdit_3.setGeometry(QtCore.QRect(10, 110, 201, 31)) font = QtGui.QFont() font.setFamily("Calibri") font.setPointSize(12) font.setBold(False) font.setItalic(False) font.setWeight(50) self.lineEdit_3.setFont(font) self.lineEdit_3.setFocusPolicy(QtCore.Qt.ClickFocus) self.lineEdit_3.setStyleSheet("") self.lineEdit_3.setMaxLength(64) self.lineEdit_3.setClearButtonEnabled(True) self.lineEdit_3.setObjectName("lineEdit_3") self.lineEdit_4 = QtWidgets.QLineEdit(self.groupBox) self.lineEdit_4.setGeometry(QtCore.QRect(240, 110, 201, 31)) font = QtGui.QFont() font.setFamily("Calibri") font.setPointSize(12) font.setBold(False) font.setItalic(False) font.setWeight(50) self.lineEdit_4.setFont(font) self.lineEdit_4.setFocusPolicy(QtCore.Qt.ClickFocus) self.lineEdit_4.setStyleSheet("") self.lineEdit_4.setInputMethodHints(QtCore.Qt.ImhDigitsOnly) self.lineEdit_4.setMaxLength(64) self.lineEdit_4.setClearButtonEnabled(True) self.lineEdit_4.setObjectName("lineEdit_4") self.lineEdit_5 = QtWidgets.QLineEdit(self.groupBox) self.lineEdit_5.setGeometry(QtCore.QRect(470, 110, 201, 31)) font = QtGui.QFont() font.setFamily("Calibri") font.setPointSize(12) font.setBold(False) font.setItalic(False) font.setWeight(50) self.lineEdit_5.setFont(font) self.lineEdit_5.setFocusPolicy(QtCore.Qt.ClickFocus) self.lineEdit_5.setStyleSheet("") self.lineEdit_5.setMaxLength(64) self.lineEdit_5.setFrame(True) self.lineEdit_5.setClearButtonEnabled(True) self.lineEdit_5.setObjectName("lineEdit_5") self.label_9 = QtWidgets.QLabel(self.groupBox) self.label_9.setGeometry(QtCore.QRect(270, 140, 201, 16)) font = QtGui.QFont() font.setFamily("MS Shell Dlg 2") font.setPointSize(8) font.setBold(False) font.setItalic(False) font.setWeight(50) self.label_9.setFont(font) self.label_9.setStyleSheet("color: red;") self.label_9.setObjectName("label_9") self.radioButton_5 = QtWidgets.QRadioButton(self.groupBox) self.radioButton_5.setGeometry(QtCore.QRect(10, 50, 131, 17)) font = QtGui.QFont() font.setFamily("Calibri") font.setPointSize(12) font.setBold(True) font.setWeight(75) self.radioButton_5.setFont(font) self.radioButton_5.setCursor(QtGui.QCursor(QtCore.Qt.ArrowCursor)) self.radioButton_5.setChecked(True) self.radioButton_5.setObjectName("radioButton_5") self.buttonGroup_3 = QtWidgets.QButtonGroup(MainWindow) self.buttonGroup_3.setObjectName("buttonGroup_3") self.buttonGroup_3.addButton(self.radioButton_5) self.radioButton_6 = QtWidgets.QRadioButton(self.groupBox) self.radioButton_6.setEnabled(True) self.radioButton_6.setGeometry(QtCore.QRect(180, 50, 281, 16)) font = QtGui.QFont() font.setFamily("Calibri") font.setPointSize(12) font.setBold(True) font.setWeight(75) self.radioButton_6.setFont(font) self.radioButton_6.setChecked(False) self.radioButton_6.setObjectName("radioButton_6") self.buttonGroup_3.addButton(self.radioButton_6) self.groupBox_2 = QtWidgets.QGroupBox(self.tab) self.groupBox_2.setGeometry(QtCore.QRect(10, 10, 681, 291)) font = QtGui.QFont() font.setFamily("Calibri") font.setPointSize(12) font.setBold(True) font.setItalic(False) font.setWeight(75) self.groupBox_2.setFont(font) self.groupBox_2.setStyleSheet("") self.groupBox_2.setFlat(False) self.groupBox_2.setCheckable(False) self.groupBox_2.setObjectName("groupBox_2") self.lineEdit_2 = QtWidgets.QLineEdit(self.groupBox_2) self.lineEdit_2.setGeometry(QtCore.QRect(10, 170, 661, 31)) font = QtGui.QFont() font.setFamily("Calibri") font.setPointSize(12) font.setBold(False) font.setWeight(50) self.lineEdit_2.setFont(font) self.lineEdit_2.setFocusPolicy(QtCore.Qt.ClickFocus) self.lineEdit_2.setAcceptDrops(False) self.lineEdit_2.setStyleSheet("") self.lineEdit_2.setMaxLength(256) self.lineEdit_2.setFrame(True) self.lineEdit_2.setClearButtonEnabled(True) self.lineEdit_2.setObjectName("lineEdit_2") self.lineEdit = QtWidgets.QLineEdit(self.groupBox_2) self.lineEdit.setGeometry(QtCore.QRect(10, 100, 661, 31)) font = QtGui.QFont() font.setFamily("Calibri") font.setPointSize(12) font.setBold(False) font.setWeight(50) self.lineEdit.setFont(font) self.lineEdit.setFocusPolicy(QtCore.Qt.ClickFocus) self.lineEdit.setStyleSheet("") self.lineEdit.setMaxLength(32) self.lineEdit.setFrame(True) self.lineEdit.setClearButtonEnabled(True) self.lineEdit.setObjectName("lineEdit") self.radioButton_9 = QtWidgets.QRadioButton(self.groupBox_2) self.radioButton_9.setGeometry(QtCore.QRect(380, 50, 151, 17)) font = QtGui.QFont() font.setFamily("Calibri") font.setPointSize(12) font.setBold(True) font.setItalic(False) font.setWeight(75) self.radioButton_9.setFont(font) self.radioButton_9.setObjectName("radioButton_9") self.buttonGroup_4 = QtWidgets.QButtonGroup(MainWindow) self.buttonGroup_4.setObjectName("buttonGroup_4") self.buttonGroup_4.addButton(self.radioButton_9) self.radioButton_8 = QtWidgets.QRadioButton(self.groupBox_2) self.radioButton_8.setGeometry(QtCore.QRect(120, 50, 241, 17)) font = QtGui.QFont() font.setFamily("Calibri") font.setPointSize(12) font.setBold(True) font.setItalic(False) font.setWeight(75) self.radioButton_8.setFont(font) self.radioButton_8.setObjectName("radioButton_8") self.buttonGroup_4.addButton(self.radioButton_8) self.label_5 = QtWidgets.QLabel(self.groupBox_2) self.label_5.setGeometry(QtCore.QRect(10, 150, 141, 16)) font = QtGui.QFont() font.setFamily("Calibri") font.setPointSize(11) font.setBold(False) font.setItalic(False) font.setWeight(50) self.label_5.setFont(font) self.label_5.setObjectName("label_5") self.label_4 = QtWidgets.QLabel(self.groupBox_2) self.label_4.setGeometry(QtCore.QRect(10, 80, 281, 16)) font = QtGui.QFont() font.setFamily("Calibri") font.setPointSize(11) font.setBold(False) font.setItalic(False) font.setWeight(50) self.label_4.setFont(font) self.label_4.setObjectName("label_4") self.radioButton_7 = QtWidgets.QRadioButton(self.groupBox_2) self.radioButton_7.setGeometry(QtCore.QRect(10, 50, 91, 17)) font = QtGui.QFont() font.setFamily("Calibri") font.setPointSize(12) font.setBold(True) font.setItalic(False) font.setWeight(75) self.radioButton_7.setFont(font) self.radioButton_7.setChecked(True) self.radioButton_7.setObjectName("radioButton_7") self.buttonGroup_4.addButton(self.radioButton_7) self.spinBox_3 = QtWidgets.QSpinBox(self.groupBox_2) self.spinBox_3.setGeometry(QtCore.QRect(10, 240, 191, 31)) font = QtGui.QFont() font.setFamily("Calibri") font.setPointSize(12) font.setBold(False) font.setWeight(50) self.spinBox_3.setFont(font) self.spinBox_3.setCursor(QtGui.QCursor(QtCore.Qt.ArrowCursor)) self.spinBox_3.setMouseTracking(True) self.spinBox_3.setTabletTracking(True) self.spinBox_3.setFocusPolicy(QtCore.Qt.ClickFocus) self.spinBox_3.setContextMenuPolicy(QtCore.Qt.DefaultContextMenu) self.spinBox_3.setAcceptDrops(False) self.spinBox_3.setWhatsThis("") self.spinBox_3.setAccessibleName("") self.spinBox_3.setAutoFillBackground(False) self.spinBox_3.setStyleSheet("") self.spinBox_3.setWrapping(False) self.spinBox_3.setFrame(True) self.spinBox_3.setAlignment(QtCore.Qt.AlignCenter) self.spinBox_3.setReadOnly(False) self.spinBox_3.setButtonSymbols(QtWidgets.QAbstractSpinBox.UpDownArrows) self.spinBox_3.setAccelerated(False) self.spinBox_3.setProperty("showGroupSeparator", False) self.spinBox_3.setMinimum(1917) self.spinBox_3.setMaximum(2060) self.spinBox_3.setProperty("value", 1917) self.spinBox_3.setObjectName("spinBox_3") self.label_6 = QtWidgets.QLabel(self.groupBox_2) self.label_6.setGeometry(QtCore.QRect(10, 220, 101, 16)) font = QtGui.QFont() font.setFamily("Calibri") font.setPointSize(11) font.setBold(False) font.setItalic(False) font.setWeight(50) self.label_6.setFont(font) self.label_6.setObjectName("label_6") self.line_2 = QtWidgets.QFrame(self.groupBox_2) self.line_2.setGeometry(QtCore.QRect(10, 30, 661, 16)) self.line_2.setFrameShape(QtWidgets.QFrame.HLine) self.line_2.setFrameShadow(QtWidgets.QFrame.Sunken) self.line_2.setObjectName("line_2") self.tabWidget.addTab(self.tab, "") self.tab_2 = QtWidgets.QWidget() self.tab_2.setObjectName("tab_2") self.dateEdit = QtWidgets.QDateEdit(self.tab_2) self.dateEdit.setGeometry(QtCore.QRect(20, 120, 201, 31)) font = QtGui.QFont() font.setFamily("Calibri") font.setPointSize(12) font.setBold(False) font.setItalic(False) font.setWeight(50) self.dateEdit.setFont(font) self.dateEdit.setCursor(QtGui.QCursor(QtCore.Qt.IBeamCursor)) self.dateEdit.setFocusPolicy(QtCore.Qt.ClickFocus) self.dateEdit.setStyleSheet("") self.dateEdit.setButtonSymbols(QtWidgets.QAbstractSpinBox.UpDownArrows) self.dateEdit.setSpecialValueText("") self.dateEdit.setAccelerated(False) self.dateEdit.setProperty("showGroupSeparator", False) self.dateEdit.setDateTime(QtCore.QDateTime(QtCore.QDate(2020, 7, 8), QtCore.QTime(0, 0, 0))) self.dateEdit.setMinimumDateTime(QtCore.QDateTime(QtCore.QDate(1917, 9, 14), QtCore.QTime(0, 0, 0))) self.dateEdit.setCalendarPopup(True) self.dateEdit.setObjectName("dateEdit") self.label_7 = QtWidgets.QLabel(self.tab_2) self.label_7.setGeometry(QtCore.QRect(20, 30, 231, 16)) font = QtGui.QFont() font.setFamily("Calibri") font.setPointSize(11) font.setBold(False) font.setItalic(False) font.setWeight(50) self.label_7.setFont(font) self.label_7.setObjectName("label_7") self.label_8 = QtWidgets.QLabel(self.tab_2) self.label_8.setGeometry(QtCore.QRect(20, 100, 201, 16)) font = QtGui.QFont() font.setFamily("Calibri") font.setPointSize(11) font.setBold(False) font.setItalic(False) font.setWeight(50) self.label_8.setFont(font) self.label_8.setObjectName("label_8") self.label_13 = QtWidgets.QLabel(self.tab_2) self.label_13.setGeometry(QtCore.QRect(250, 100, 201, 16)) font = QtGui.QFont() font.setFamily("Calibri") font.setPointSize(11) font.setBold(False) font.setItalic(False) font.setWeight(50) self.label_13.setFont(font) self.label_13.setObjectName("label_13") self.label_11 = QtWidgets.QLabel(self.tab_2) self.label_11.setGeometry(QtCore.QRect(20, 170, 151, 16)) font = QtGui.QFont() font.setFamily("Calibri") font.setPointSize(11) font.setBold(False) font.setItalic(False) font.setWeight(50) self.label_11.setFont(font) self.label_11.setObjectName("label_11") self.checkBox = QtWidgets.QCheckBox(self.tab_2) self.checkBox.setGeometry(QtCore.QRect(250, 360, 201, 31)) font = QtGui.QFont() font.setFamily("Calibri") font.setPointSize(11) font.setBold(False) font.setItalic(False) font.setWeight(50) self.checkBox.setFont(font) self.checkBox.setObjectName("checkBox") self.checkBox_2 = QtWidgets.QCheckBox(self.tab_2) self.checkBox_2.setGeometry(QtCore.QRect(480, 360, 161, 31)) font = QtGui.QFont() font.setFamily("Calibri") font.setPointSize(11) font.setBold(False) font.setItalic(False) font.setWeight(50) self.checkBox_2.setFont(font) self.checkBox_2.setObjectName("checkBox_2") self.lineEdit_6 = QtWidgets.QLineEdit(self.tab_2) self.lineEdit_6.setGeometry(QtCore.QRect(250, 120, 201, 31)) font = QtGui.QFont() font.setFamily("Calibri") font.setPointSize(12) font.setBold(False) font.setWeight(50) self.lineEdit_6.setFont(font) self.lineEdit_6.setFocusPolicy(QtCore.Qt.StrongFocus) self.lineEdit_6.setStyleSheet("") self.lineEdit_6.setInputMask("") self.lineEdit_6.setText("") self.lineEdit_6.setMaxLength(10) self.lineEdit_6.setClearButtonEnabled(False) self.lineEdit_6.setObjectName("lineEdit_6") self.lineEdit_7 = QtWidgets.QLineEdit(self.tab_2) self.lineEdit_7.setGeometry(QtCore.QRect(20, 50, 201, 31)) font = QtGui.QFont() font.setFamily("Calibri") font.setPointSize(12) font.setBold(False) font.setWeight(50) self.lineEdit_7.setFont(font) self.lineEdit_7.setFocusPolicy(QtCore.Qt.ClickFocus) self.lineEdit_7.setStyleSheet("") self.lineEdit_7.setMaxLength(32) self.lineEdit_7.setClearButtonEnabled(True) self.lineEdit_7.setObjectName("lineEdit_7") self.lineEdit_8 = QtWidgets.QLineEdit(self.tab_2) self.lineEdit_8.setGeometry(QtCore.QRect(20, 360, 201, 31)) font = QtGui.QFont() font.setFamily("Calibri") font.setPointSize(12) font.setBold(False) font.setWeight(50) self.lineEdit_8.setFont(font) self.lineEdit_8.setFocusPolicy(QtCore.Qt.ClickFocus) self.lineEdit_8.setStyleSheet("") self.lineEdit_8.setMaxLength(128) self.lineEdit_8.setClearButtonEnabled(True) self.lineEdit_8.setObjectName("lineEdit_8") self.lineEdit_9 = QtWidgets.QLineEdit(self.tab_2) self.lineEdit_9.setEnabled(False) self.lineEdit_9.setGeometry(QtCore.QRect(20, 460, 661, 31)) font = QtGui.QFont() font.setFamily("Calibri") font.setPointSize(12) font.setBold(False) font.setWeight(50) self.lineEdit_9.setFont(font) self.lineEdit_9.setFocusPolicy(QtCore.Qt.ClickFocus) self.lineEdit_9.setStyleSheet("") self.lineEdit_9.setInputMask("") self.lineEdit_9.setMaxLength(1024) self.lineEdit_9.setFrame(True) self.lineEdit_9.setPlaceholderText("") self.lineEdit_9.setClearButtonEnabled(True) self.lineEdit_9.setObjectName("lineEdit_9") self.lineEdit_10 = QtWidgets.QLineEdit(self.tab_2) self.lineEdit_10.setGeometry(QtCore.QRect(250, 50, 201, 31)) font = QtGui.QFont() font.setFamily("Calibri") font.setPointSize(12) font.setBold(False) font.setWeight(50) self.lineEdit_10.setFont(font) self.lineEdit_10.setFocusPolicy(QtCore.Qt.ClickFocus) self.lineEdit_10.setStyleSheet("") self.lineEdit_10.setMaxLength(512) self.lineEdit_10.setClearButtonEnabled(True) self.lineEdit_10.setObjectName("lineEdit_10") self.lineEdit_11 = QtWidgets.QLineEdit(self.tab_2) self.lineEdit_11.setGeometry(QtCore.QRect(20, 190, 661, 31)) font = QtGui.QFont() font.setFamily("Calibri") font.setPointSize(12) font.setBold(False) font.setWeight(50) self.lineEdit_11.setFont(font) self.lineEdit_11.setFocusPolicy(QtCore.Qt.ClickFocus) self.lineEdit_11.setAcceptDrops(False) self.lineEdit_11.setStyleSheet("") self.lineEdit_11.setMaxLength(128) self.lineEdit_11.setFrame(True) self.lineEdit_11.setPlaceholderText("") self.lineEdit_11.setClearButtonEnabled(True) self.lineEdit_11.setObjectName("lineEdit_11") self.pushButton_2 = QtWidgets.QPushButton(self.tab_2) self.pushButton_2.setGeometry(QtCore.QRect(430, 120, 21, 31)) self.pushButton_2.setFocusPolicy(QtCore.Qt.ClickFocus) self.pushButton_2.setAutoFillBackground(False) self.pushButton_2.setStyleSheet("border-style: none;") self.pushButton_2.setText("") icon1 = QtGui.QIcon() icon1.addPixmap(QtGui.QPixmap(":/icons/strelka.ico"), QtGui.QIcon.Normal, QtGui.QIcon.Off) self.pushButton_2.setIcon(icon1) self.pushButton_2.setIconSize(QtCore.QSize(10, 10)) self.pushButton_2.setCheckable(True) self.pushButton_2.setAutoDefault(False) self.pushButton_2.setDefault(False) self.pushButton_2.setFlat(False) self.pushButton_2.setObjectName("pushButton_2") self.calendarWidget = QtWidgets.QCalendarWidget(self.tab_2) self.calendarWidget.setGeometry(QtCore.QRect(250, 150, 281, 191)) font = QtGui.QFont() font.setFamily("Segoe UI") font.setPointSize(9) font.setBold(False) font.setItalic(False) font.setWeight(50) self.calendarWidget.setFont(font) self.calendarWidget.setAutoFillBackground(False) self.calendarWidget.setStyleSheet("") self.calendarWidget.setInputMethodHints(QtCore.Qt.ImhNone) self.calendarWidget.setMinimumDate(QtCore.QDate(1917, 9, 14)) self.calendarWidget.setGridVisible(False) self.calendarWidget.setSelectionMode(QtWidgets.QCalendarWidget.SingleSelection) self.calendarWidget.setVerticalHeaderFormat(QtWidgets.QCalendarWidget.NoVerticalHeader) self.calendarWidget.setNavigationBarVisible(True) self.calendarWidget.setDateEditEnabled(True) self.calendarWidget.setObjectName("calendarWidget") self.pushButton_3 = QtWidgets.QPushButton(self.tab_2) self.pushButton_3.setGeometry(QtCore.QRect(430, 120, 21, 31)) self.pushButton_3.setFocusPolicy(QtCore.Qt.ClickFocus) self.pushButton_3.setAutoFillBackground(False) self.pushButton_3.setStyleSheet("border-style: none;") self.pushButton_3.setText("") self.pushButton_3.setIcon(icon1) self.pushButton_3.setIconSize(QtCore.QSize(10, 10)) self.pushButton_3.setCheckable(True) self.pushButton_3.setAutoDefault(False) self.pushButton_3.setDefault(False) self.pushButton_3.setFlat(False) self.pushButton_3.setObjectName("pushButton_3") self.label_19 = QtWidgets.QLabel(self.tab_2) self.label_19.setGeometry(QtCore.QRect(140, 151, 181, 20)) font = QtGui.QFont() font.setFamily("MS Shell Dlg 2") font.setPointSize(8) font.setBold(False) font.setItalic(False) font.setWeight(50) self.label_19.setFont(font) self.label_19.setStyleSheet("color: red;") self.label_19.setObjectName("label_19") self.label_20 = QtWidgets.QLabel(self.tab_2) self.label_20.setGeometry(QtCore.QRect(250, 151, 231, 20)) font = QtGui.QFont() font.setFamily("MS Shell Dlg 2") font.setPointSize(8) font.setBold(False) font.setItalic(False) font.setWeight(50) self.label_20.setFont(font) self.label_20.setStyleSheet("color: red;") self.label_20.setObjectName("label_20") self.lineEdit_20 = QtWidgets.QLineEdit(self.tab_2) self.lineEdit_20.setGeometry(QtCore.QRect(480, 50, 201, 31)) font = QtGui.QFont() font.setFamily("Calibri") font.setPointSize(12) font.setBold(False) font.setWeight(50) self.lineEdit_20.setFont(font) self.lineEdit_20.setFocusPolicy(QtCore.Qt.ClickFocus) self.lineEdit_20.setAcceptDrops(False) self.lineEdit_20.setStyleSheet("") self.lineEdit_20.setMaxLength(128) self.lineEdit_20.setFrame(True) self.lineEdit_20.setClearButtonEnabled(True) self.lineEdit_20.setObjectName("lineEdit_20") self.label_22 = QtWidgets.QLabel(self.tab_2) self.label_22.setGeometry(QtCore.QRect(480, 30, 151, 16)) font = QtGui.QFont() font.setFamily("Calibri") font.setPointSize(11) font.setBold(False) font.setItalic(False) font.setWeight(50) self.label_22.setFont(font) self.label_22.setObjectName("label_22") self.label_16 = QtWidgets.QLabel(self.tab_2) self.label_16.setGeometry(QtCore.QRect(20, 230, 91, 31)) font = QtGui.QFont() font.setFamily("Calibri") font.setPointSize(12) font.setBold(True) font.setItalic(False) font.setWeight(75) self.label_16.setFont(font) self.label_16.setObjectName("label_16") self.radioButton = QtWidgets.QRadioButton(self.tab_2) self.radioButton.setGeometry(QtCore.QRect(120, 230, 101, 31)) font = QtGui.QFont() font.setFamily("Calibri") font.setPointSize(11) font.setBold(False) font.setItalic(False) font.setWeight(50) self.radioButton.setFont(font) self.radioButton.setChecked(True) self.radioButton.setAutoExclusive(True) self.radioButton.setObjectName("radioButton") self.buttonGroup_2 = QtWidgets.QButtonGroup(MainWindow) self.buttonGroup_2.setObjectName("buttonGroup_2") self.buttonGroup_2.addButton(self.radioButton) self.radioButton_2 = QtWidgets.QRadioButton(self.tab_2) self.radioButton_2.setGeometry(QtCore.QRect(230, 230, 121, 31)) font = QtGui.QFont() font.setFamily("Calibri") font.setPointSize(11) font.setBold(False) font.setItalic(False) font.setWeight(50) self.radioButton_2.setFont(font) self.radioButton_2.setChecked(False) self.radioButton_2.setAutoExclusive(True) self.radioButton_2.setObjectName("radioButton_2") self.buttonGroup_2.addButton(self.radioButton_2) self.checkBox_3 = QtWidgets.QCheckBox(self.tab_2) self.checkBox_3.setGeometry(QtCore.QRect(20, 270, 321, 17)) font = QtGui.QFont() font.setFamily("Calibri") font.setPointSize(11) font.setBold(False) font.setItalic(False) font.setWeight(50) self.checkBox_3.setFont(font) self.checkBox_3.setObjectName("checkBox_3") self.radioButton_3 = QtWidgets.QRadioButton(self.tab_2) self.radioButton_3.setGeometry(QtCore.QRect(20, 310, 111, 17)) font = QtGui.QFont() font.setFamily("Calibri") font.setPointSize(12) font.setBold(True) font.setItalic(False) font.setWeight(75) self.radioButton_3.setFont(font) self.radioButton_3.setChecked(True) self.radioButton_3.setAutoExclusive(True) self.radioButton_3.setObjectName("radioButton_3") self.buttonGroup = QtWidgets.QButtonGroup(MainWindow) self.buttonGroup.setObjectName("buttonGroup") self.buttonGroup.addButton(self.radioButton_3) self.label_17 = QtWidgets.QLabel(self.tab_2) self.label_17.setGeometry(QtCore.QRect(20, 340, 151, 16)) font = QtGui.QFont() font.setFamily("Calibri") font.setPointSize(11) font.setBold(False) font.setItalic(False) font.setWeight(50) self.label_17.setFont(font) self.label_17.setObjectName("label_17") self.radioButton_4 = QtWidgets.QRadioButton(self.tab_2) self.radioButton_4.setGeometry(QtCore.QRect(20, 410, 111, 17)) font = QtGui.QFont() font.setFamily("Calibri") font.setPointSize(12) font.setBold(True) font.setItalic(False) font.setWeight(75) self.radioButton_4.setFont(font) self.radioButton_4.setChecked(False) self.radioButton_4.setAutoExclusive(True) self.radioButton_4.setObjectName("radioButton_4") self.buttonGroup.addButton(self.radioButton_4) self.label_18 = QtWidgets.QLabel(self.tab_2) self.label_18.setGeometry(QtCore.QRect(20, 440, 201, 16)) font = QtGui.QFont() font.setFamily("Calibri") font.setPointSize(11) font.setBold(False) font.setItalic(False) font.setWeight(50) self.label_18.setFont(font) self.label_18.setObjectName("label_18") self.label_55 = QtWidgets.QLabel(self.tab_2) self.label_55.setGeometry(QtCore.QRect(250, 30, 231, 16)) font = QtGui.QFont() font.setFamily("Calibri") font.setPointSize(11) font.setBold(False) font.setItalic(False) font.setWeight(50) self.label_55.setFont(font) self.label_55.setObjectName("label_55") self.dateEdit.raise_() self.label_7.raise_() self.label_8.raise_() self.label_13.raise_() self.label_11.raise_() self.checkBox.raise_() self.checkBox_2.raise_() self.lineEdit_6.raise_() self.lineEdit_7.raise_() self.lineEdit_8.raise_() self.lineEdit_9.raise_() self.lineEdit_10.raise_() self.lineEdit_11.raise_() self.pushButton_2.raise_() self.pushButton_3.raise_() self.label_19.raise_() self.label_20.raise_() self.lineEdit_20.raise_() self.label_22.raise_() self.label_16.raise_() self.radioButton.raise_() self.radioButton_2.raise_() self.checkBox_3.raise_() self.radioButton_3.raise_() self.label_17.raise_() self.radioButton_4.raise_() self.label_18.raise_() self.calendarWidget.raise_() self.label_55.raise_() self.tabWidget.addTab(self.tab_2, "") self.tab_3 = QtWidgets.QWidget() self.tab_3.setObjectName("tab_3") self.toolBox = QtWidgets.QToolBox(self.tab_3) self.toolBox.setEnabled(True) self.toolBox.setGeometry(QtCore.QRect(10, 30, 681, 381)) font = QtGui.QFont() font.setFamily("Calibri") font.setPointSize(12) font.setBold(True) font.setItalic(False) font.setWeight(75) self.toolBox.setFont(font) self.toolBox.setCursor(QtGui.QCursor(QtCore.Qt.ArrowCursor)) self.toolBox.setStyleSheet("") self.toolBox.setFrameShape(QtWidgets.QFrame.NoFrame) self.toolBox.setFrameShadow(QtWidgets.QFrame.Raised) self.toolBox.setLineWidth(1) self.toolBox.setMidLineWidth(0) self.toolBox.setObjectName("toolBox") self.page = QtWidgets.QWidget() self.page.setGeometry(QtCore.QRect(0, 0, 681, 201)) self.page.setObjectName("page") self.label_28 = QtWidgets.QLabel(self.page) self.label_28.setGeometry(QtCore.QRect(10, 20, 151, 16)) font = QtGui.QFont() font.setFamily("MS Shell Dlg 2") font.setPointSize(10) font.setBold(False) font.setItalic(False) font.setWeight(50) self.label_28.setFont(font) self.label_28.setObjectName("label_28") self.lineEdit_12 = QtWidgets.QLineEdit(self.page) self.lineEdit_12.setGeometry(QtCore.QRect(10, 40, 661, 31)) font = QtGui.QFont() font.setFamily("Calibri") font.setPointSize(12) font.setBold(False) font.setWeight(50) self.lineEdit_12.setFont(font) self.lineEdit_12.setFocusPolicy(QtCore.Qt.ClickFocus) self.lineEdit_12.setStyleSheet("") self.lineEdit_12.setMaxLength(512) self.lineEdit_12.setClearButtonEnabled(True) self.lineEdit_12.setObjectName("lineEdit_12") self.label_45 = QtWidgets.QLabel(self.page) self.label_45.setGeometry(QtCore.QRect(10, 80, 341, 16)) font = QtGui.QFont() font.setFamily("MS Shell Dlg 2") font.setPointSize(10) font.setBold(False) font.setItalic(False) font.setWeight(50) self.label_45.setFont(font) self.label_45.setObjectName("label_45") self.label_46 = QtWidgets.QLabel(self.page) self.label_46.setGeometry(QtCore.QRect(10, 100, 341, 16)) font = QtGui.QFont() font.setFamily("MS Shell Dlg 2") font.setPointSize(10) font.setBold(False) font.setItalic(False) font.setWeight(50) self.label_46.setFont(font) self.label_46.setObjectName("label_46") self.toolBox.addItem(self.page, "") self.page_3 = QtWidgets.QWidget() self.page_3.setGeometry(QtCore.QRect(0, 0, 98, 28)) self.page_3.setObjectName("page_3") self.label_31 = QtWidgets.QLabel(self.page_3) self.label_31.setGeometry(QtCore.QRect(10, 10, 191, 16)) font = QtGui.QFont() font.setFamily("MS Shell Dlg 2") font.setPointSize(10) font.setBold(False) font.setItalic(False) font.setWeight(50) self.label_31.setFont(font) self.label_31.setObjectName("label_31") self.lineEdit_13 = QtWidgets.QLineEdit(self.page_3) self.lineEdit_13.setGeometry(QtCore.QRect(10, 30, 661, 31)) font = QtGui.QFont() font.setFamily("Calibri") font.setPointSize(12) font.setBold(False) font.setWeight(50) self.lineEdit_13.setFont(font) self.lineEdit_13.setFocusPolicy(QtCore.Qt.ClickFocus) self.lineEdit_13.setStyleSheet("") self.lineEdit_13.setMaxLength(512) self.lineEdit_13.setClearButtonEnabled(True) self.lineEdit_13.setObjectName("lineEdit_13") self.label_47 = QtWidgets.QLabel(self.page_3) self.label_47.setGeometry(QtCore.QRect(10, 90, 431, 16)) font = QtGui.QFont() font.setFamily("MS Shell Dlg 2") font.setPointSize(10) font.setBold(False) font.setItalic(False) font.setWeight(50) self.label_47.setFont(font) self.label_47.setObjectName("label_47") self.label_48 = QtWidgets.QLabel(self.page_3) self.label_48.setGeometry(QtCore.QRect(10, 70, 341, 16)) font = QtGui.QFont() font.setFamily("MS Shell Dlg 2") font.setPointSize(10) font.setBold(False) font.setItalic(False) font.setWeight(50) self.label_48.setFont(font) self.label_48.setObjectName("label_48") self.toolBox.addItem(self.page_3, "") self.page_2 = QtWidgets.QWidget() self.page_2.setGeometry(QtCore.QRect(0, 0, 98, 28)) self.page_2.setObjectName("page_2") self.tabWidget_2 = QtWidgets.QTabWidget(self.page_2) self.tabWidget_2.setGeometry(QtCore.QRect(0, 10, 681, 181)) font = QtGui.QFont() font.setFamily("Calibri") font.setPointSize(11) font.setBold(False) font.setItalic(False) font.setWeight(50) self.tabWidget_2.setFont(font) self.tabWidget_2.setTabPosition(QtWidgets.QTabWidget.North) self.tabWidget_2.setTabShape(QtWidgets.QTabWidget.Rounded) self.tabWidget_2.setElideMode(QtCore.Qt.ElideNone) self.tabWidget_2.setUsesScrollButtons(True) self.tabWidget_2.setDocumentMode(False) self.tabWidget_2.setTabsClosable(True) self.tabWidget_2.setMovable(False) self.tabWidget_2.setTabBarAutoHide(False) self.tabWidget_2.setObjectName("tabWidget_2") self.toolBox.addItem(self.page_2, "") self.page_4 = QtWidgets.QWidget() self.page_4.setGeometry(QtCore.QRect(0, 0, 98, 28)) self.page_4.setObjectName("page_4") self.label_32 = QtWidgets.QLabel(self.page_4) self.label_32.setGeometry(QtCore.QRect(10, 10, 141, 16)) font = QtGui.QFont() font.setFamily("MS Shell Dlg 2") font.setPointSize(10) font.setBold(False) font.setItalic(False) font.setWeight(50) self.label_32.setFont(font) self.label_32.setObjectName("label_32") self.lineEdit_16 = QtWidgets.QLineEdit(self.page_4) self.lineEdit_16.setGeometry(QtCore.QRect(10, 30, 661, 31)) font = QtGui.QFont() font.setFamily("Calibri") font.setPointSize(12) font.setBold(False) font.setWeight(50) self.lineEdit_16.setFont(font) self.lineEdit_16.setStyleSheet("") self.lineEdit_16.setMaxLength(512) self.lineEdit_16.setClearButtonEnabled(True) self.lineEdit_16.setObjectName("lineEdit_16") self.label_49 = QtWidgets.QLabel(self.page_4) self.label_49.setGeometry(QtCore.QRect(10, 90, 411, 16)) font = QtGui.QFont() font.setFamily("MS Shell Dlg 2") font.setPointSize(10) font.setBold(False) font.setItalic(False) font.setWeight(50) self.label_49.setFont(font) self.label_49.setObjectName("label_49") self.label_50 = QtWidgets.QLabel(self.page_4) self.label_50.setGeometry(QtCore.QRect(10, 70, 411, 16)) font = QtGui.QFont() font.setFamily("MS Shell Dlg 2") font.setPointSize(10) font.setBold(False) font.setItalic(False) font.setWeight(50) self.label_50.setFont(font) self.label_50.setObjectName("label_50") self.toolBox.addItem(self.page_4, "") self.page_5 = QtWidgets.QWidget() self.page_5.setGeometry(QtCore.QRect(0, 0, 98, 28)) self.page_5.setObjectName("page_5") self.tabWidget_3 = QtWidgets.QTabWidget(self.page_5) self.tabWidget_3.setGeometry(QtCore.QRect(0, 10, 681, 181)) font = QtGui.QFont() font.setFamily("Calibri") font.setPointSize(11) font.setBold(False) font.setItalic(False) font.setWeight(50) self.tabWidget_3.setFont(font) self.tabWidget_3.setTabsClosable(True) self.tabWidget_3.setObjectName("tabWidget_3") self.toolBox.addItem(self.page_5, "") self.page_6 = QtWidgets.QWidget() self.page_6.setGeometry(QtCore.QRect(0, 0, 98, 28)) self.page_6.setObjectName("page_6") self.label_38 = QtWidgets.QLabel(self.page_6) self.label_38.setGeometry(QtCore.QRect(10, 0, 201, 21)) font = QtGui.QFont() font.setFamily("MS Shell Dlg 2") font.setPointSize(10) font.setBold(False) font.setItalic(False) font.setWeight(50) self.label_38.setFont(font) self.label_38.setObjectName("label_38") self.lineEdit_19 = QtWidgets.QLineEdit(self.page_6) self.lineEdit_19.setGeometry(QtCore.QRect(10, 20, 661, 31)) font = QtGui.QFont() font.setFamily("Calibri") font.setPointSize(12) font.setBold(False) font.setWeight(50) self.lineEdit_19.setFont(font) self.lineEdit_19.setFocusPolicy(QtCore.Qt.ClickFocus) self.lineEdit_19.setStyleSheet("") self.lineEdit_19.setMaxLength(512) self.lineEdit_19.setClearButtonEnabled(True) self.lineEdit_19.setObjectName("lineEdit_19") self.label_51 = QtWidgets.QLabel(self.page_6) self.label_51.setGeometry(QtCore.QRect(10, 80, 391, 16)) font = QtGui.QFont() font.setFamily("MS Shell Dlg 2") font.setPointSize(10) font.setBold(False) font.setItalic(False) font.setWeight(50) self.label_51.setFont(font) self.label_51.setObjectName("label_51") self.label_52 = QtWidgets.QLabel(self.page_6) self.label_52.setGeometry(QtCore.QRect(10, 60, 341, 16)) font = QtGui.QFont() font.setFamily("MS Shell Dlg 2") font.setPointSize(10) font.setBold(False) font.setItalic(False) font.setWeight(50) self.label_52.setFont(font) self.label_52.setObjectName("label_52") self.toolBox.addItem(self.page_6, "") self.comboBox = QtWidgets.QComboBox(self.tab_3) self.comboBox.setGeometry(QtCore.QRect(10, 460, 681, 31)) font = QtGui.QFont() font.setFamily("Calibri") font.setPointSize(12) font.setBold(False) font.setWeight(50) self.comboBox.setFont(font) self.comboBox.setMouseTracking(False) self.comboBox.setFocusPolicy(QtCore.Qt.ClickFocus) self.comboBox.setContextMenuPolicy(QtCore.Qt.DefaultContextMenu) self.comboBox.setAcceptDrops(False) self.comboBox.setToolTipDuration(-1) self.comboBox.setAutoFillBackground(False) self.comboBox.setStyleSheet("background-color: #ffffff; border: 1px solid gray;\n" "border-radius: 3px;") self.comboBox.setEditable(False) self.comboBox.setCurrentText("") self.comboBox.setMaxVisibleItems(5) self.comboBox.setMaxCount(5) self.comboBox.setInsertPolicy(QtWidgets.QComboBox.InsertAtCurrent) self.comboBox.setFrame(True) self.comboBox.setObjectName("comboBox") self.comboBox.addItem("") self.comboBox.setItemText(0, "") self.comboBox.addItem("") self.comboBox.addItem("") self.comboBox.addItem("") self.comboBox.addItem("") self.label_21 = QtWidgets.QLabel(self.tab_3) self.label_21.setGeometry(QtCore.QRect(10, 440, 331, 16)) font = QtGui.QFont() font.setFamily("Calibri") font.setPointSize(11) font.setBold(False) font.setItalic(False) font.setWeight(50) self.label_21.setFont(font) self.label_21.setObjectName("label_21") self.label_30 = QtWidgets.QLabel(self.tab_3) self.label_30.setGeometry(QtCore.QRect(10, 0, 681, 21)) font = QtGui.QFont() font.setFamily("MS Shell Dlg 2") font.setPointSize(10) font.setBold(False) font.setItalic(False) font.setWeight(50) self.label_30.setFont(font) self.label_30.setStyleSheet("color: red;") self.label_30.setAlignment(QtCore.Qt.AlignCenter) self.label_30.setObjectName("label_30") self.line_8 = QtWidgets.QFrame(self.tab_3) self.line_8.setGeometry(QtCore.QRect(10, 420, 681, 16)) self.line_8.setFrameShape(QtWidgets.QFrame.HLine) self.line_8.setFrameShadow(QtWidgets.QFrame.Sunken) self.line_8.setObjectName("line_8") self.tabWidget.addTab(self.tab_3, "") self.tab_4 = QtWidgets.QWidget() self.tab_4.setObjectName("tab_4") self.groupBox_4 = QtWidgets.QGroupBox(self.tab_4) self.groupBox_4.setGeometry(QtCore.QRect(10, 10, 681, 201)) font = QtGui.QFont() font.setFamily("Calibri") font.setPointSize(12) font.setBold(True) font.setItalic(False) font.setWeight(75) self.groupBox_4.setFont(font) self.groupBox_4.setObjectName("groupBox_4") self.line_7 = QtWidgets.QFrame(self.groupBox_4) self.line_7.setGeometry(QtCore.QRect(10, 30, 661, 16)) self.line_7.setFrameShape(QtWidgets.QFrame.HLine) self.line_7.setFrameShadow(QtWidgets.QFrame.Sunken) self.line_7.setObjectName("line_7") self.label_37 = QtWidgets.QLabel(self.groupBox_4) self.label_37.setGeometry(QtCore.QRect(10, 40, 191, 31)) font = QtGui.QFont() font.setFamily("Calibri") font.setPointSize(11) font.setBold(False) font.setItalic(False) font.setWeight(50) self.label_37.setFont(font) self.label_37.setAutoFillBackground(False) self.label_37.setLineWidth(1) self.label_37.setMidLineWidth(1) self.label_37.setObjectName("label_37") self.label_39 = QtWidgets.QLabel(self.groupBox_4) self.label_39.setGeometry(QtCore.QRect(240, 40, 231, 31)) font = QtGui.QFont() font.setFamily("Calibri") font.setPointSize(11) font.setBold(False) font.setItalic(False) font.setWeight(50) self.label_39.setFont(font) self.label_39.setAutoFillBackground(False) self.label_39.setLineWidth(1) self.label_39.setMidLineWidth(1) self.label_39.setObjectName("label_39") self.label_40 = QtWidgets.QLabel(self.groupBox_4) self.label_40.setGeometry(QtCore.QRect(470, 40, 201, 31)) font = QtGui.QFont() font.setFamily("Calibri") font.setPointSize(11) font.setBold(False) font.setItalic(False) font.setWeight(50) self.label_40.setFont(font) self.label_40.setAutoFillBackground(False) self.label_40.setLineWidth(1) self.label_40.setMidLineWidth(1) self.label_40.setObjectName("label_40") self.lineEdit_21 = QtWidgets.QLineEdit(self.groupBox_4) self.lineEdit_21.setGeometry(QtCore.QRect(10, 70, 201, 31)) font = QtGui.QFont() font.setFamily("Calibri") font.setPointSize(12) font.setBold(False) font.setWeight(50) self.lineEdit_21.setFont(font) self.lineEdit_21.setMouseTracking(False) self.lineEdit_21.setFocusPolicy(QtCore.Qt.ClickFocus) self.lineEdit_21.setAcceptDrops(False) self.lineEdit_21.setStyleSheet("") self.lineEdit_21.setMaxLength(128) self.lineEdit_21.setClearButtonEnabled(True) self.lineEdit_21.setObjectName("lineEdit_21") self.lineEdit_22 = QtWidgets.QLineEdit(self.groupBox_4) self.lineEdit_22.setGeometry(QtCore.QRect(240, 70, 201, 31)) font = QtGui.QFont() font.setFamily("Calibri") font.setPointSize(12) font.setBold(False) font.setWeight(50) self.lineEdit_22.setFont(font) self.lineEdit_22.setMouseTracking(False) self.lineEdit_22.setFocusPolicy(QtCore.Qt.ClickFocus) self.lineEdit_22.setAcceptDrops(False) self.lineEdit_22.setStyleSheet("") self.lineEdit_22.setMaxLength(128) self.lineEdit_22.setClearButtonEnabled(True) self.lineEdit_22.setObjectName("lineEdit_22") self.lineEdit_23 = QtWidgets.QLineEdit(self.tab_4) self.lineEdit_23.setGeometry(QtCore.QRect(480, 80, 201, 31)) font = QtGui.QFont() font.setFamily("Calibri") font.setPointSize(12) font.setBold(False) font.setWeight(50) self.lineEdit_23.setFont(font) self.lineEdit_23.setMouseTracking(False) self.lineEdit_23.setFocusPolicy(QtCore.Qt.ClickFocus) self.lineEdit_23.setAcceptDrops(False) self.lineEdit_23.setStyleSheet("") self.lineEdit_23.setMaxLength(128) self.lineEdit_23.setClearButtonEnabled(True) self.lineEdit_23.setObjectName("lineEdit_23") self.textEdit_24 = QtWidgets.QTextEdit(self.tab_4) self.textEdit_24.setGeometry(QtCore.QRect(20, 150, 661, 51)) font = QtGui.QFont() font.setFamily("Calibri") font.setPointSize(12) font.setBold(False) font.setWeight(50) self.textEdit_24.setFont(font) self.textEdit_24.viewport().setProperty("cursor", QtGui.QCursor(QtCore.Qt.IBeamCursor)) self.textEdit_24.setFocusPolicy(QtCore.Qt.ClickFocus) self.textEdit_24.setStyleSheet("") self.textEdit_24.setHorizontalScrollBarPolicy(QtCore.Qt.ScrollBarAlwaysOff) self.textEdit_24.setObjectName("textEdit_24") self.label_41 = QtWidgets.QLabel(self.tab_4) self.label_41.setGeometry(QtCore.QRect(20, 120, 191, 31)) font = QtGui.QFont() font.setFamily("Calibri") font.setPointSize(11) font.setBold(False) font.setItalic(False) font.setWeight(50) self.label_41.setFont(font) self.label_41.setAutoFillBackground(False) self.label_41.setLineWidth(1) self.label_41.setMidLineWidth(1) self.label_41.setObjectName("label_41") self.textEdit_25 = QtWidgets.QTextEdit(self.tab_4) self.textEdit_25.setGeometry(QtCore.QRect(20, 240, 661, 51)) font = QtGui.QFont() font.setFamily("Calibri") font.setPointSize(12) font.setBold(False) font.setWeight(50) self.textEdit_25.setFont(font) self.textEdit_25.viewport().setProperty("cursor", QtGui.QCursor(QtCore.Qt.IBeamCursor)) self.textEdit_25.setFocusPolicy(QtCore.Qt.ClickFocus) self.textEdit_25.setStyleSheet("") self.textEdit_25.setHorizontalScrollBarPolicy(QtCore.Qt.ScrollBarAlwaysOff) self.textEdit_25.setObjectName("textEdit_25") self.label_42 = QtWidgets.QLabel(self.tab_4) self.label_42.setGeometry(QtCore.QRect(20, 210, 291, 31)) font = QtGui.QFont() font.setFamily("Calibri") font.setPointSize(11) font.setBold(False) font.setItalic(False) font.setWeight(50) self.label_42.setFont(font) self.label_42.setAutoFillBackground(False) self.label_42.setLineWidth(1) self.label_42.setMidLineWidth(1) self.label_42.setObjectName("label_42") self.textEdit_26 = QtWidgets.QTextEdit(self.tab_4) self.textEdit_26.setGeometry(QtCore.QRect(20, 440, 661, 51)) font = QtGui.QFont() font.setFamily("Calibri") font.setPointSize(12) font.setBold(False) font.setWeight(50) self.textEdit_26.setFont(font) self.textEdit_26.viewport().setProperty("cursor", QtGui.QCursor(QtCore.Qt.IBeamCursor)) self.textEdit_26.setFocusPolicy(QtCore.Qt.ClickFocus) self.textEdit_26.setStyleSheet("") self.textEdit_26.setHorizontalScrollBarPolicy(QtCore.Qt.ScrollBarAlwaysOff) self.textEdit_26.setObjectName("textEdit_26") self.textEdit_27 = QtWidgets.QTextEdit(self.tab_4) self.textEdit_27.setEnabled(False) self.textEdit_27.setGeometry(QtCore.QRect(20, 350, 661, 51)) font = QtGui.QFont() font.setFamily("Calibri") font.setPointSize(12) font.setBold(False) font.setWeight(50) self.textEdit_27.setFont(font) self.textEdit_27.viewport().setProperty("cursor", QtGui.QCursor(QtCore.Qt.IBeamCursor)) self.textEdit_27.setFocusPolicy(QtCore.Qt.ClickFocus) self.textEdit_27.setAcceptDrops(False) self.textEdit_27.setStyleSheet("") self.textEdit_27.setFrameShape(QtWidgets.QFrame.StyledPanel) self.textEdit_27.setHorizontalScrollBarPolicy(QtCore.Qt.ScrollBarAlwaysOff) self.textEdit_27.setUndoRedoEnabled(False) self.textEdit_27.setObjectName("textEdit_27") self.label_43 = QtWidgets.QLabel(self.tab_4) self.label_43.setGeometry(QtCore.QRect(20, 410, 131, 31)) font = QtGui.QFont() font.setFamily("Calibri") font.setPointSize(11) font.setBold(False) font.setItalic(False) font.setWeight(50) self.label_43.setFont(font) self.label_43.setAutoFillBackground(False) self.label_43.setLineWidth(1) self.label_43.setMidLineWidth(1) self.label_43.setObjectName("label_43") self.label_44 = QtWidgets.QLabel(self.tab_4) self.label_44.setEnabled(False) self.label_44.setGeometry(QtCore.QRect(20, 320, 291, 31)) font = QtGui.QFont() font.setFamily("Calibri") font.setPointSize(11) font.setBold(False) font.setItalic(False) font.setWeight(50) self.label_44.setFont(font) self.label_44.setAutoFillBackground(False) self.label_44.setLineWidth(1) self.label_44.setMidLineWidth(1) self.label_44.setObjectName("label_44") self.checkBox_4 = QtWidgets.QCheckBox(self.tab_4) self.checkBox_4.setGeometry(QtCore.QRect(20, 300, 251, 31)) font = QtGui.QFont() font.setFamily("Calibri") font.setPointSize(11) font.setBold(False) font.setItalic(False) font.setWeight(50) self.checkBox_4.setFont(font) self.checkBox_4.setObjectName("checkBox_4") self.tabWidget.addTab(self.tab_4, "") self.groupBox_3 = QtWidgets.QGroupBox(self.centralwidget) self.groupBox_3.setGeometry(QtCore.QRect(10, 10, 711, 121)) font = QtGui.QFont() font.setFamily("Calibri") font.setPointSize(12) font.setBold(True) font.setWeight(75) self.groupBox_3.setFont(font) self.groupBox_3.setFocusPolicy(QtCore.Qt.ClickFocus) self.groupBox_3.setAutoFillBackground(False) self.groupBox_3.setStyleSheet("") self.groupBox_3.setObjectName("groupBox_3") self.label_3 = QtWidgets.QLabel(self.groupBox_3) self.label_3.setGeometry(QtCore.QRect(250, 90, 141, 16)) font = QtGui.QFont() font.setFamily("MS Shell Dlg 2") font.setPointSize(8) font.setBold(False) font.setWeight(50) self.label_3.setFont(font) self.label_3.setObjectName("label_3") self.spinBox = QtWidgets.QSpinBox(self.groupBox_3) self.spinBox.setGeometry(QtCore.QRect(20, 50, 201, 31)) font = QtGui.QFont() font.setFamily("Calibri") font.setPointSize(12) font.setBold(False) font.setItalic(False) font.setWeight(50) self.spinBox.setFont(font) self.spinBox.setCursor(QtGui.QCursor(QtCore.Qt.ArrowCursor)) self.spinBox.setFocusPolicy(QtCore.Qt.ClickFocus) self.spinBox.setWhatsThis("") self.spinBox.setAccessibleName("") self.spinBox.setStyleSheet("") self.spinBox.setKeyboardTracking(True) self.spinBox.setMinimum(1) self.spinBox.setMaximum(400000) self.spinBox.setObjectName("spinBox") self.spinBox_2 = QtWidgets.QSpinBox(self.groupBox_3) self.spinBox_2.setGeometry(QtCore.QRect(250, 50, 211, 31)) font = QtGui.QFont() font.setFamily("Calibri") font.setPointSize(12) font.setBold(False) font.setWeight(50) self.spinBox_2.setFont(font) self.spinBox_2.setCursor(QtGui.QCursor(QtCore.Qt.ArrowCursor)) self.spinBox_2.setMouseTracking(False) self.spinBox_2.setTabletTracking(False) self.spinBox_2.setFocusPolicy(QtCore.Qt.ClickFocus) self.spinBox_2.setStyleSheet("") self.spinBox_2.setAccelerated(True) self.spinBox_2.setProperty("showGroupSeparator", False) self.spinBox_2.setMinimum(1) self.spinBox_2.setMaximum(5000) self.spinBox_2.setObjectName("spinBox_2") self.label_2 = QtWidgets.QLabel(self.groupBox_3) self.label_2.setGeometry(QtCore.QRect(250, 30, 211, 16)) font = QtGui.QFont() font.setFamily("Calibri") font.setPointSize(11) font.setBold(False) font.setWeight(50) self.label_2.setFont(font) self.label_2.setObjectName("label_2") self.label = QtWidgets.QLabel(self.groupBox_3) self.label.setGeometry(QtCore.QRect(20, 30, 201, 16)) font = QtGui.QFont() font.setFamily("Calibri") font.setPointSize(11) font.setBold(False) font.setWeight(50) self.label.setFont(font) self.label.setObjectName("label") self.label_10 = QtWidgets.QLabel(self.groupBox_3) self.label_10.setGeometry(QtCore.QRect(20, 90, 191, 16)) font = QtGui.QFont() font.setFamily("MS Shell Dlg 2") font.setPointSize(8) font.setBold(False) font.setWeight(50) self.label_10.setFont(font) self.label_10.setObjectName("label_10") self.pushButton = QtWidgets.QPushButton(self.groupBox_3) self.pushButton.setGeometry(QtCore.QRect(490, 50, 191, 31)) font = QtGui.QFont() font.setFamily("Calibri") font.setPointSize(12) font.setBold(True) font.setItalic(False) font.setWeight(75) self.pushButton.setFont(font) self.pushButton.setAutoFillBackground(False) self.pushButton.setStyleSheet("") self.pushButton.setAutoDefault(False) self.pushButton.setDefault(False) self.pushButton.setFlat(False) self.pushButton.setObjectName("pushButton") self.progressBar = QtWidgets.QProgressBar(self.groupBox_3) self.progressBar.setEnabled(True) self.progressBar.setGeometry(QtCore.QRect(490, 50, 191, 31)) self.progressBar.setStyleSheet("QProgressBar {\n" " border: 1px solid grey;\n" " }\n" "\n" "QProgressBar::chunk {\n" " background-color: #03d85c;\n" " width: 20px;\n" "}") self.progressBar.setProperty("value", 100) self.progressBar.setTextVisible(False) self.progressBar.setOrientation(QtCore.Qt.Horizontal) self.progressBar.setInvertedAppearance(False) self.progressBar.setObjectName("progressBar") self.progressBar.raise_() self.label_3.raise_() self.spinBox.raise_() self.spinBox_2.raise_() self.label_2.raise_() self.label.raise_() self.label_10.raise_() self.pushButton.raise_() self.line_3 = QtWidgets.QFrame(self.centralwidget) self.line_3.setEnabled(False) self.line_3.setGeometry(QtCore.QRect(60, 130, 21, 20)) self.line_3.setStyleSheet("color: red;") self.line_3.setFrameShadow(QtWidgets.QFrame.Plain) self.line_3.setLineWidth(5) self.line_3.setFrameShape(QtWidgets.QFrame.HLine) self.line_3.setObjectName("line_3") self.line_4 = QtWidgets.QFrame(self.centralwidget) self.line_4.setEnabled(False) self.line_4.setGeometry(QtCore.QRect(210, 130, 21, 20)) self.line_4.setStyleSheet("color: red;") self.line_4.setFrameShadow(QtWidgets.QFrame.Plain) self.line_4.setLineWidth(5) self.line_4.setFrameShape(QtWidgets.QFrame.HLine) self.line_4.setObjectName("line_4") self.line_5 = QtWidgets.QFrame(self.centralwidget) self.line_5.setEnabled(False) self.line_5.setGeometry(QtCore.QRect(370, 130, 21, 20)) self.line_5.setStyleSheet("color: red;") self.line_5.setFrameShadow(QtWidgets.QFrame.Plain) self.line_5.setLineWidth(5) self.line_5.setFrameShape(QtWidgets.QFrame.HLine) self.line_5.setObjectName("line_5") self.line_6 = QtWidgets.QFrame(self.centralwidget) self.line_6.setEnabled(False) self.line_6.setGeometry(QtCore.QRect(520, 130, 21, 20)) self.line_6.setStyleSheet("color: red;") self.line_6.setFrameShadow(QtWidgets.QFrame.Plain) self.line_6.setLineWidth(5) self.line_6.setFrameShape(QtWidgets.QFrame.HLine) self.line_6.setObjectName("line_6") self.label_23 = QtWidgets.QLabel(self.centralwidget) self.label_23.setGeometry(QtCore.QRect(230, 180, 271, 221)) self.label_23.setText("") self.label_23.setPixmap(QtGui.QPixmap(":/logo/vniims_logo.jpg")) self.label_23.setAlignment(QtCore.Qt.AlignJustify|QtCore.Qt.AlignVCenter) self.label_23.setObjectName("label_23") self.label_26 = QtWidgets.QLabel(self.centralwidget) self.label_26.setGeometry(QtCore.QRect(230, 640, 271, 21)) font = QtGui.QFont() font.setFamily("Segoe UI") font.setPointSize(9) self.label_26.setFont(font) self.label_26.setStyleSheet("") self.label_26.setAlignment(QtCore.Qt.AlignCenter) self.label_26.setObjectName("label_26") self.pushButton_4 = QtWidgets.QPushButton(self.centralwidget) self.pushButton_4.setGeometry(QtCore.QRect(320, 640, 91, 31)) self.pushButton_4.setObjectName("pushButton_4") self.label_25 = QtWidgets.QLabel(self.centralwidget) self.label_25.setGeometry(QtCore.QRect(230, 370, 271, 21)) font = QtGui.QFont() font.setFamily("Segoe UI") font.setPointSize(9) self.label_25.setFont(font) self.label_25.setStyleSheet("color: white;") self.label_25.setAlignment(QtCore.Qt.AlignCenter) self.label_25.setObjectName("label_25") self.label_24 = QtWidgets.QLabel(self.centralwidget) self.label_24.setGeometry(QtCore.QRect(0, -270, 730, 1000)) self.label_24.setMaximumSize(QtCore.QSize(730, 1000)) font = QtGui.QFont() font.setPointSize(9) self.label_24.setFont(font) self.label_24.setStyleSheet("background-color: white;") self.label_24.setText("") self.label_24.setObjectName("label_24") self.label_27 = QtWidgets.QLabel(self.centralwidget) self.label_27.setGeometry(QtCore.QRect(230, 610, 271, 20)) font = QtGui.QFont() font.setFamily("Segoe UI") font.setPointSize(9) self.label_27.setFont(font) self.label_27.setAlignment(QtCore.Qt.AlignCenter) self.label_27.setObjectName("label_27") self.label_29 = QtWidgets.QLabel(self.centralwidget) self.label_29.setGeometry(QtCore.QRect(-10, -20, 751, 731)) self.label_29.setStyleSheet("background-color: white;") self.label_29.setText("") self.label_29.setObjectName("label_29") self.listWidget = QtWidgets.QListWidget(self.centralwidget) self.listWidget.setGeometry(QtCore.QRect(10, 20, 710, 600)) self.listWidget.setMinimumSize(QtCore.QSize(710, 600)) self.listWidget.setMaximumSize(QtCore.QSize(710, 600)) self.listWidget.setMouseTracking(True) self.listWidget.setTabletTracking(False) self.listWidget.setFocusPolicy(QtCore.Qt.NoFocus) self.listWidget.setContextMenuPolicy(QtCore.Qt.NoContextMenu) self.listWidget.setFrameShape(QtWidgets.QFrame.StyledPanel) self.listWidget.setLineWidth(1) self.listWidget.setHorizontalScrollBarPolicy(QtCore.Qt.ScrollBarAlwaysOff) self.listWidget.setSizeAdjustPolicy(QtWidgets.QAbstractScrollArea.AdjustToContents) self.listWidget.setAutoScroll(False) self.listWidget.setEditTriggers(QtWidgets.QAbstractItemView.NoEditTriggers) self.listWidget.setProperty("showDropIndicator", False) self.listWidget.setSelectionMode(QtWidgets.QAbstractItemView.NoSelection) self.listWidget.setTextElideMode(QtCore.Qt.ElideLeft) self.listWidget.setVerticalScrollMode(QtWidgets.QAbstractItemView.ScrollPerPixel) self.listWidget.setHorizontalScrollMode(QtWidgets.QAbstractItemView.ScrollPerItem) self.listWidget.setProperty("isWrapping", False) self.listWidget.setWordWrap(True) self.listWidget.setSelectionRectVisible(False) self.listWidget.setObjectName("listWidget") item = QtWidgets.QListWidgetItem() self.listWidget.addItem(item) item = QtWidgets.QListWidgetItem() item.setTextAlignment(QtCore.Qt.AlignCenter) font = QtGui.QFont() font.setFamily("Calibri") font.setPointSize(14) font.setBold(True) font.setWeight(75) item.setFont(font) self.listWidget.addItem(item) item = QtWidgets.QListWidgetItem() self.listWidget.addItem(item) item = QtWidgets.QListWidgetItem() font = QtGui.QFont() font.setUnderline(True) item.setFont(font) self.listWidget.addItem(item) item = QtWidgets.QListWidgetItem() font = QtGui.QFont() font.setBold(False) font.setWeight(50) item.setFont(font) self.listWidget.addItem(item) item = QtWidgets.QListWidgetItem() self.listWidget.addItem(item) item = QtWidgets.QListWidgetItem() self.listWidget.addItem(item) item = QtWidgets.QListWidgetItem() self.listWidget.addItem(item) item = QtWidgets.QListWidgetItem() self.listWidget.addItem(item) item = QtWidgets.QListWidgetItem() font = QtGui.QFont() font.setUnderline(True) item.setFont(font) self.listWidget.addItem(item) item = QtWidgets.QListWidgetItem() self.listWidget.addItem(item) item = QtWidgets.QListWidgetItem() self.listWidget.addItem(item) item = QtWidgets.QListWidgetItem() self.listWidget.addItem(item) item = QtWidgets.QListWidgetItem() font = QtGui.QFont() font.setBold(False) font.setWeight(50) item.setFont(font) self.listWidget.addItem(item) item = QtWidgets.QListWidgetItem() self.listWidget.addItem(item) item = QtWidgets.QListWidgetItem() self.listWidget.addItem(item) item = QtWidgets.QListWidgetItem() self.listWidget.addItem(item) item = QtWidgets.QListWidgetItem() self.listWidget.addItem(item) item = QtWidgets.QListWidgetItem() self.listWidget.addItem(item) item = QtWidgets.QListWidgetItem() self.listWidget.addItem(item) item = QtWidgets.QListWidgetItem() self.listWidget.addItem(item) item = QtWidgets.QListWidgetItem() self.listWidget.addItem(item) item = QtWidgets.QListWidgetItem() self.listWidget.addItem(item) item = QtWidgets.QListWidgetItem() self.listWidget.addItem(item) item = QtWidgets.QListWidgetItem() self.listWidget.addItem(item) item = QtWidgets.QListWidgetItem() self.listWidget.addItem(item) item = QtWidgets.QListWidgetItem() self.listWidget.addItem(item) item = QtWidgets.QListWidgetItem() self.listWidget.addItem(item) item = QtWidgets.QListWidgetItem() self.listWidget.addItem(item) item = QtWidgets.QListWidgetItem() self.listWidget.addItem(item) item = QtWidgets.QListWidgetItem() self.listWidget.addItem(item) item = QtWidgets.QListWidgetItem() self.listWidget.addItem(item) item = QtWidgets.QListWidgetItem() self.listWidget.addItem(item) item = QtWidgets.QListWidgetItem() self.listWidget.addItem(item) item = QtWidgets.QListWidgetItem() self.listWidget.addItem(item) item = QtWidgets.QListWidgetItem() self.listWidget.addItem(item) item = QtWidgets.QListWidgetItem() self.listWidget.addItem(item) item = QtWidgets.QListWidgetItem() self.listWidget.addItem(item) item = QtWidgets.QListWidgetItem() self.listWidget.addItem(item) item = QtWidgets.QListWidgetItem() self.listWidget.addItem(item) item = QtWidgets.QListWidgetItem() self.listWidget.addItem(item) item = QtWidgets.QListWidgetItem() self.listWidget.addItem(item) item = QtWidgets.QListWidgetItem() self.listWidget.addItem(item) item = QtWidgets.QListWidgetItem() self.listWidget.addItem(item) item = QtWidgets.QListWidgetItem() self.listWidget.addItem(item) item = QtWidgets.QListWidgetItem() self.listWidget.addItem(item) item = QtWidgets.QListWidgetItem() self.listWidget.addItem(item) self.groupBox_3.raise_() self.line_5.raise_() self.line_4.raise_() self.line_6.raise_() self.line_3.raise_() self.tabWidget.raise_() self.label_29.raise_() self.listWidget.raise_() self.pushButton_4.raise_() self.label_24.raise_() self.label_27.raise_() self.label_26.raise_() self.label_23.raise_() self.label_25.raise_() MainWindow.setCentralWidget(self.centralwidget) self.menuBar = QtWidgets.QMenuBar(MainWindow) self.menuBar.setGeometry(QtCore.QRect(0, 0, 730, 21)) self.menuBar.setObjectName("menuBar") self.menu = QtWidgets.QMenu(self.menuBar) self.menu.setObjectName("menu") MainWindow.setMenuBar(self.menuBar) self.action = QtWidgets.QAction(MainWindow) self.action.setObjectName("action") self.action_3 = QtWidgets.QAction(MainWindow) self.action_3.setObjectName("action_3") self.action_2 = QtWidgets.QAction(MainWindow) self.action_2.setObjectName("action_2") self.menu.addAction(self.action) self.menu.addAction(self.action_2) self.menu.addSeparator() self.menu.addAction(self.action_3) self.menuBar.addAction(self.menu.menuAction()) self.retranslateUi(MainWindow) self.tabWidget.setCurrentIndex(0) self.toolBox.setCurrentIndex(0) self.toolBox.layout().setSpacing(3) self.tabWidget_2.setCurrentIndex(-1) self.tabWidget_3.setCurrentIndex(-1) self.comboBox.setCurrentIndex(0) QtCore.QMetaObject.connectSlotsByName(MainWindow) def retranslateUi(self, MainWindow): _translate = QtCore.QCoreApplication.translate MainWindow.setWindowTitle(_translate("MainWindow", "Генератор xml-файлов для партий СИ")) self.groupBox.setTitle(_translate("MainWindow", "Заводской номер/Буквенно-цифровое обозначение")) self.label_15.setText(_translate("MainWindow", "Конец номера после изменяемой части")) self.label_12.setText(_translate("MainWindow", "Начало номера до изменяемой части")) self.label_14.setText(_translate("MainWindow", "Изменяемая часть номера *")) self.lineEdit_4.setWhatsThis(_translate("MainWindow", "Разрешен ввод чисел с ведущими нулям (например 0001)")) self.lineEdit_4.setPlaceholderText(_translate("MainWindow", "Начальное значение")) self.label_9.setText(_translate("MainWindow", "Только числовое значение")) self.radioButton_5.setText(_translate("MainWindow", "Заводской № *")) self.radioButton_6.setText(_translate("MainWindow", "Буквенно-цифровое обозначение*")) self.groupBox_2.setTitle(_translate("MainWindow", "Тип СИ и модификация СИ")) self.radioButton_9.setText(_translate("MainWindow", "СИ ВН или СН *")) self.radioButton_8.setText(_translate("MainWindow", "Метрологическая аттестация *")) self.label_5.setText(_translate("MainWindow", "Модификация СИ *")) self.label_4.setText(_translate("MainWindow", "Тип СИ *")) self.radioButton_7.setText(_translate("MainWindow", "Тип СИ *")) self.spinBox_3.setSpecialValueText(_translate("MainWindow", "-")) self.label_6.setText(_translate("MainWindow", "Год выпуска")) self.tabWidget.setTabText(self.tabWidget.indexOf(self.tab), _translate("MainWindow", "Сведения о СИ")) self.dateEdit.setDisplayFormat(_translate("MainWindow", "yyyy-MM-dd")) self.label_7.setText(_translate("MainWindow", "Условный шифр знака поверки *")) self.label_8.setText(_translate("MainWindow", "Дата поверки СИ *")) self.label_13.setText(_translate("MainWindow", "Действительна до")) self.label_11.setText(_translate("MainWindow", "Методика поверки *")) self.checkBox.setText(_translate("MainWindow", "Знак поверки в паспорте")) self.checkBox_2.setText(_translate("MainWindow", "Знак поверки на СИ")) self.lineEdit_6.setPlaceholderText(_translate("MainWindow", "ГГГГ-ММ-ДД")) self.label_19.setText(_translate("MainWindow", "Даты не могут быть одинаковыми")) self.label_20.setText(_translate("MainWindow", "Дата не может быть меньше даты поверки")) self.label_22.setText(_translate("MainWindow", "Ф.И.О. поверителя")) self.label_16.setText(_translate("MainWindow", "Тип поверки")) self.radioButton.setText(_translate("MainWindow", "Первичная")) self.radioButton_2.setText(_translate("MainWindow", "Периодическая")) self.checkBox_3.setText(_translate("MainWindow", "Использование результатов калибровки")) self.radioButton_3.setText(_translate("MainWindow", "Пригодно")) self.label_17.setText(_translate("MainWindow", "Номер наклейки")) self.radioButton_4.setText(_translate("MainWindow", "Непригодно")) self.label_18.setText(_translate("MainWindow", "Причина непригодности")) self.label_55.setText(_translate("MainWindow", "Владелец СИ *")) self.tabWidget.setTabText(self.tabWidget.indexOf(self.tab_2), _translate("MainWindow", "Сведения о поверке")) self.label_28.setText(_translate("MainWindow", "№ ГПЭ по реестру")) self.label_45.setText(_translate("MainWindow", "Значения перечисляются подряд и разделяются \";\"")) self.label_46.setText(_translate("MainWindow", "Пример: гэт000-2011;гэт001-2018;гэт002-77 ")) self.toolBox.setItemText(self.toolBox.indexOf(self.page), _translate("MainWindow", "Государственный первичный эталон")) self.label_31.setText(_translate("MainWindow", "№ эталона по реестру")) self.label_47.setText(_translate("MainWindow", "Пример: 3.2.ХХХ.0001.2018;3.2.ХХХ.0004.2015;3.2.ХХХ.0005.2019")) self.label_48.setText(_translate("MainWindow", "Значения перечисляются подряд и разделяются \";\"")) self.toolBox.setItemText(self.toolBox.indexOf(self.page_3), _translate("MainWindow", "Эталон единицы величины")) self.toolBox.setItemText(self.toolBox.indexOf(self.page_2), _translate("MainWindow", "Стандартные образцы, применяемые при поверке")) self.label_32.setText(_translate("MainWindow", "№ СИ по перечню")) self.label_49.setText(_translate("MainWindow", "Пример: 10597.86.5Р.00024;10457.86.2Р.00034;10597.86.0Р.00023")) self.label_50.setText(_translate("MainWindow", "Значения перечисляются подряд и разделяются \";\"")) self.toolBox.setItemText(self.toolBox.indexOf(self.page_4), _translate("MainWindow", "СИ, применяемое в качестве эталона")) self.toolBox.setItemText(self.toolBox.indexOf(self.page_5), _translate("MainWindow", "СИ, применяемые при поверке")) self.label_38.setText(_translate("MainWindow", "Наименование, № по перечню")) self.label_51.setText(_translate("MainWindow", "Пример: ДРГ.1;РКТ.10")) self.label_52.setText(_translate("MainWindow", "Значения перечисляются подряд и разделяются \";\"")) self.toolBox.setItemText(self.toolBox.indexOf(self.page_6), _translate("MainWindow", "Вещество (материал), применяемое при поверке")) self.comboBox.setItemText(1, _translate("MainWindow", "поверка имитационным методом")) self.comboBox.setItemText(2, _translate("MainWindow", "самоповерка")) self.comboBox.setItemText(3, _translate("MainWindow", "поверка расчетным методом")) self.comboBox.setItemText(4, _translate("MainWindow", "поверка с использованием первичной референтной методики измерений")) self.label_21.setText(_translate("MainWindow", "Методы поверки без применения средств поверки\n" "")) self.label_30.setText(_translate("MainWindow", "Необходимо заполнить хотя бы одно поле")) self.tabWidget.setTabText(self.tabWidget.indexOf(self.tab_3), _translate("MainWindow", "Средства поверки")) self.groupBox_4.setTitle(_translate("MainWindow", "Условия проведения поверки")) self.label_37.setText(_translate("MainWindow", "Температура, °C *")) self.label_39.setText(_translate("MainWindow", "Атмосферное давление, кПа *")) self.label_40.setText(_translate("MainWindow", "Относительная влажность, % *")) self.label_41.setText(_translate("MainWindow", "Другие факторы")) self.label_42.setText(_translate("MainWindow", "Состав СИ, представленного на поверку")) self.label_43.setText(_translate("MainWindow", "Прочие сведения")) self.label_44.setText(_translate("MainWindow", "Краткая характеристика объема поверки")) self.checkBox_4.setText(_translate("MainWindow", "Поверка в сокращенном объеме")) self.tabWidget.setTabText(self.tabWidget.indexOf(self.tab_4), _translate("MainWindow", "Прочие сведения")) self.groupBox_3.setTitle(_translate("MainWindow", "Сведения о заявках")) self.label_3.setText(_translate("MainWindow", "Максимально 5000 записей")) self.label_2.setText(_translate("MainWindow", "Поверок в одном файле")) self.label.setText(_translate("MainWindow", "Всего СИ в партии")) self.label_10.setText(_translate("MainWindow", "Максимально 400000 записей")) self.pushButton.setText(_translate("MainWindow", "Создать xml-файл")) self.label_26.setText(_translate("MainWindow", "Разработано ФГУП \"ВНИИМС\", 2020 г.")) self.pushButton_4.setText(_translate("MainWindow", "Закрыть")) self.label_25.setText(_translate("MainWindow", "Версия ПО 2.0")) self.label_27.setText(_translate("MainWindow", "Программа распространяется бесплатно")) __sortingEnabled = self.listWidget.isSortingEnabled() self.listWidget.setSortingEnabled(False) item = self.listWidget.item(1) item.setText(_translate("MainWindow", "Краткая инструкция")) item = self.listWidget.item(3) item.setText(_translate("MainWindow", "Предупреждение:")) item = self.listWidget.item(4) item.setText(_translate("MainWindow", "Объем xml-файла, загружаемого в модуль \"Поверки\", не должен превышать объем, равный 5 МБ.")) item = self.listWidget.item(5) item.setText(_translate("MainWindow", "При формировании xml-файла в программе следует учитывать, что итоговый размер файла зависит не только от количества записей в одном xml-файле, а также от количества вносимой информации в одной записи о поверке СИ.")) item = self.listWidget.item(6) item.setText(_translate("MainWindow", "Сгенерированному xml-файлу с записями автоматически присваивается наименование, в котором содержатся: дата, наименование типа СИ, количество записей в заявке, порядковый номер заявки и условный шифр знака поверки.")) item = self.listWidget.item(7) item.setText(_translate("MainWindow", "Сформированные файлы по структуре отвечают требованиям схемы. За корректность сведений в сформированных xml-файлах ответственность несет лицо, вносившее сведения.")) item = self.listWidget.item(9) item.setText(_translate("MainWindow", "Рекомендации по заполнению формы:")) item = self.listWidget.item(10) item.setText(_translate("MainWindow", "1. В поле \"Всего СИ в партии\" указывается общее количество СИ в партии, для которых создаются записи о поверке.")) item = self.listWidget.item(11) item.setText(_translate("MainWindow", "2. В поле \"Поверок в одном файле\" указывается количество записей, которое будет сформировано в однм xml-файле (не более 5000 записей).")) item = self.listWidget.item(12) item.setText(_translate("MainWindow", "=====================================================================================")) item = self.listWidget.item(13) item.setText(_translate("MainWindow", "Пример: пользователю необходимо внести сведения о 13000 шт. средств измерений, чтобы в одной заявке содержались сведения о 3000 СИ.")) item = self.listWidget.item(14) item.setText(_translate("MainWindow", "Пользователь в поле \"Всего СИ в партии\" указывает 13000, а в поле \"Поверок в одном файле\" указывает 3000.")) item = self.listWidget.item(15) item.setText(_translate("MainWindow", "В результате, после нажатия кнопки \"Создать xml-файл\", сформируется 5 xml-файлов, 4 файла будут содержать по 3000 записей, 5-й файл - 1000 записей.")) item = self.listWidget.item(16) item.setText(_translate("MainWindow", "=====================================================================================")) item = self.listWidget.item(17) item.setText(_translate("MainWindow", "3. Далее необходимо заполнить все обязательные поля, находящиеся во вкладках \"Сведения о СИ\", \"Сведения о поверке\", \"Средства поверки\", \"Прочие сведения\".")) item = self.listWidget.item(18) item.setText(_translate("MainWindow", "3.1. Вкладка \"Сведения о СИ\".")) item = self.listWidget.item(19) item.setText(_translate("MainWindow", " а. Заполнить обязательное поле Тип СИ (Метрологическая аттестация, СИ ВН или СН), подробнее в примечании ниже;")) item = self.listWidget.item(20) item.setText(_translate("MainWindow", " б. Указать модификацию СИ (если нет информации о модификации, нужно указать \"Нет\", \"Модификации нет\" или что-то подобное);")) item = self.listWidget.item(21) item.setText(_translate("MainWindow", " в. Заполнить поле \"Заводской номер/Буквенно-цифровое обозначение\" (пример ниже):")) item = self.listWidget.item(22) item.setText(_translate("MainWindow", "=====================================================================================")) item = self.listWidget.item(23) item.setText(_translate("MainWindow", "Пример: пользователю необходимо внести сведения о партии СИ в количестве 1000 шт. Диапазон заводских номеров начинается с заводского номера А102-Б/Е-000001/2020 и заканчивается номером А102-Б/Е-001000/2020. Изменяемая часть в этом примере является 000001. Также в примере есть неизменяемая часть номера: \"А102-Б/Е-\", данная часть указывается в поле \"Начало номера до изменяемой части\" и \"/2020\" - эта часть (окончание номера) указывается в поле \"Конец номера после изменяемой части\". После заполнения у пользователя должно получится следующее: \"А102-Б/Е-\" \"000001\" \"/2020\". Важное замечание: поле \"Изменяемая часть номера\" может содержать только числовые значения (возможно указание числа с ведущими нулям, как в примере). ")) item = self.listWidget.item(24) item.setText(_translate("MainWindow", "=====================================================================================")) item = self.listWidget.item(25) item.setText(_translate("MainWindow", "Примечание: для внесения сведений о единственном СИ, необходимо выбрать одну из трех опций:\n" "− «Тип СИ» для внесения сведений о результатах поверки СИ утвержденного типа, при заполнении поля в данном случае выбирается значение из реестра утвержденных типов СИ ФИФ ОЕИ.\n" "− «Метрологическая аттестация» для внесения сведений о результатах поверки средства измерений неутвержденного типа, но прошедшего метрологическую аттестацию в соответствии с ГОСТ 8.326-89 «Государственная система обеспечения единства измерений (ГСИ). Метрологическая аттестация средств измерений», в рамках которой на данное СИ была утверждена Методика метрологической аттестации, при заполнении поля в данном случае указывается наименование СИ.\n" "− «СИ ВН или СН» для внесения сведений о результатах поверки средства измерений военного назначения или специального назначения, при заполнении поля в данном случае указывается наименование типа СИ, а также номер в реестре утвержденных типов СИ раздела ФИФ ОЕИ в области обороны и безопасности государства.")) item = self.listWidget.item(26) item.setText(_translate("MainWindow", "3.2. Вкладка \"Сведения о поверке\".")) item = self.listWidget.item(27) item.setText(_translate("MainWindow", " а. Необходимо убедиться, что в поле \"Дата поверки\" выбрана нужная пользователю дата, если нужно изменить дату, нужно нажать пиктограмму \"стрелка\" в правой части поля для вызова календаря;")) item = self.listWidget.item(28) item.setText(_translate("MainWindow", " б. При необходимости можно заполнить поле \"Действительна до\" (необязательно поле), для этого также нужно нажать по пиктограмме \"стрелка\" для вызова календаря. Важное замечание: дата в поле \"Дата поверки\" не должна быть большей или равной дате, указанной в поле \"Действительна до\";")) item = self.listWidget.item(29) item.setText(_translate("MainWindow", " в. Обязательно указать в поле \"Условный шифр знака поверки организации-поверителя\" значение шифра организации, от имени которой публикуются сведения из формируемой заявки (ввод на русском языке);")) item = self.listWidget.item(30) item.setText(_translate("MainWindow", " г. Заполнить поле \"Владелец СИ\" (обязательное поле);")) item = self.listWidget.item(31) item.setText(_translate("MainWindow", " д. Указать наименование методики поверки, в соответствии с которой проводится поверка СИ, не более 128 символов (обязательно поле);")) item = self.listWidget.item(32) item.setText(_translate("MainWindow", " е. Если имеется необходимость указывать знак поверки на СИ или в паспорте на СИ, нужно проставить галки в соответствующих пунктах (необязательно);")) item = self.listWidget.item(33) item.setText(_translate("MainWindow", " ж. Выбрать тип поверки;")) item = self.listWidget.item(34) item.setText(_translate("MainWindow", " з. При необходимости указать об использовании результатов калибровки;")) item = self.listWidget.item(35) item.setText(_translate("MainWindow", " и. Если по результатам проведения поверки СИ признано непригодным, выбрать пункт \"Непригодно\" и указать причину непригодности (обязательное поле);")) item = self.listWidget.item(36) item.setText(_translate("MainWindow", "3.3. Вкладка \"Средства поверки\".")) item = self.listWidget.item(37) item.setText(_translate("MainWindow", " а. Обязательно заполнить хотя бы одно из полей, указав одно из средств поверки: номер ГПЭ/ номер эталона/ СО, применяемые при поверке/ СИ, применяемые в качестве эталона/ СИ, применяемое при поверке / Вещество (материал);")) item = self.listWidget.item(38) item.setText(_translate("MainWindow", " б. В случае проведения поверки без применения средств поверки, необходимо выбрать один из методов поверки из выпадающего списка.")) item = self.listWidget.item(39) item.setText(_translate("MainWindow", " При этом заполнение других полей будет недоступно. Чтобы активировать возможность внесения средств поверки в другие поля, необходимо в выпадающем списке \"Методы поверки без применения средств поверки\" выбрать пустую строку (первая строка в выпадающем списке).")) item = self.listWidget.item(40) item.setText(_translate("MainWindow", " Для внесения нескольких средств поверки в поля \"Государственный первичный эталон\", \"Эталон единицы величины\", \"СИ, применяемое в качестве эталона\", \"Вещество (материал), применяемое при поверке\", необходимо разделять записи символом \";\" (точка с запятой).")) item = self.listWidget.item(41) item.setText(_translate("MainWindow", " При заполнении полей \"Стандартные образцы, применяемые при поверке\" и \"СИ, применяемые при поверке\" для добавления нескольких средств поверки нужно добавить вкладки, нажав кнопку \"Добавить\" и заполнить нужные поля.")) item = self.listWidget.item(42) item.setText(_translate("MainWindow", "3.4. Вкладка \" Прочие сведения\".")) item = self.listWidget.item(43) item.setText(_translate("MainWindow", " а. Обязательно заполнить поля в разделе \"Условия проведения поверки\" (обязательные поля).")) item = self.listWidget.item(44) item.setText(_translate("MainWindow", " б. При проведении поверки в сокращенном объеме, нужно установить галку на пункте \"Поверка в сокращенном объеме\" и заполнить поле \"Краткая характеристика объема поверки\".")) item = self.listWidget.item(45) item.setText(_translate("MainWindow", " в. Остальные поля заполняются по необходимости. ")) self.listWidget.setSortingEnabled(__sortingEnabled) self.menu.setTitle(_translate("MainWindow", "Справка")) self.action.setText(_translate("MainWindow", "Информация")) self.action_3.setText(_translate("MainWindow", "Закрыть")) self.action_2.setText(_translate("MainWindow", "Инструкция")) import res_rc <file_sep>/xml_generator.py # Владелец интеллектуальной собственности и разработчик данного программного обеспечения: <NAME> import sys import os import errno import res_rc #файл ресурсов (иконки, стрелки) import MainWindow_poverki_2020 #модуль главного окна PyQt from datetime import datetime, date, time from PyQt5 import QtCore, QtGui, QtWidgets from PyQt5.Qt import * class TabPage_SO(QtWidgets.QWidget): def __init__(self, parent=None): super().__init__(parent) self.labelType = QtWidgets.QLabel("№ типа СО по реестру *", self) self.labelType.setGeometry(QtCore.QRect(10, 10, 191, 16)) self.lineEditType = QtWidgets.QLineEdit(self) self.lineEditType.setGeometry(QtCore.QRect(10, 30, 191, 31)) self.lineEditType.setClearButtonEnabled(True) self.labelYearOfIssue = QtWidgets.QLabel("Год выпуска *", self) self.labelYearOfIssue.setGeometry(QtCore.QRect(240, 10, 191, 16)) self.spinBoxManufYear = QtWidgets.QSpinBox(self) self.spinBoxManufYear.setGeometry(QtCore.QRect(240, 30, 191, 31)) self.spinBoxManufYear.setCursor(QtGui.QCursor(QtCore.Qt.ArrowCursor)) self.spinBoxManufYear.setAlignment(QtCore.Qt.AlignCenter) self.spinBoxManufYear.setMinimum(1917) self.spinBoxManufYear.setMaximum(2060) current_date = date.today() self.spinBoxManufYear.setProperty("value", current_date.year) self.labelSerialNumber = QtWidgets.QLabel("Заводской №/№ партии", self) self.labelSerialNumber.setGeometry(QtCore.QRect(470, 10, 191, 16)) self.lineEditSerialNumber = QtWidgets.QLineEdit(self) self.lineEditSerialNumber.setGeometry(QtCore.QRect(470, 30, 191, 31)) self.lineEditSerialNumber.setClearButtonEnabled(True) self.labelSpecifications = QtWidgets.QLabel("Метрологические характеристики СО", self) self.labelSpecifications.setGeometry(QtCore.QRect(10, 70, 261, 16)) self.lineEditSpecifications = QtWidgets.QLineEdit(self) self.lineEditSpecifications.setGeometry(QtCore.QRect(10, 90, 651, 31)) self.lineEditSpecifications.setClearButtonEnabled(True) class TabPage_SI(QtWidgets.QWidget): def __init__(self, parent=None): super().__init__(parent) self.labelTypeSI = QtWidgets.QLabel("Регистрационный № типа СИ *", self) self.labelTypeSI.setGeometry(QtCore.QRect(10, 5, 200, 21)) self.lineEditTypeSI = QtWidgets.QLineEdit(self) self.lineEditTypeSI.setGeometry(QtCore.QRect(10, 30, 191, 31)) self.lineEditTypeSI.setClearButtonEnabled(True) self.labelZavNumber = QtWidgets.QLabel("Заводской номер *", self) self.labelZavNumber.setGeometry(QtCore.QRect(10, 70, 151, 16)) self.lineEditZavNumber = QtWidgets.QLineEdit(self) self.lineEditZavNumber.setGeometry(QtCore.QRect(10, 90, 191, 31)) self.lineEditZavNumber.setClearButtonEnabled(True) self.labelInventory = QtWidgets.QLabel("Буквенно-цифровое обозначение *", self) self.labelInventory.setGeometry(QtCore.QRect(250, 70, 240, 16)) self.lineEditInventory = QtWidgets.QLineEdit(self) self.lineEditInventory.setGeometry(QtCore.QRect(250, 90, 191, 31)) self.lineEditInventory.setClearButtonEnabled(True) class main_window(QtWidgets.QMainWindow, MainWindow_poverki_2020.Ui_MainWindow): def __init__(self, parent = None): super(main_window, self).__init__() self.setupUi(self) #Указатель версии ПО (для заставки и раздела Информация) self.label_25.setText("Версия программы: 2.0") self.menuBar.setVisible(False) self.setWindowTitle("") self.logoTimer() self.font_tab3 = QtGui.QFont() self.font_tab3.setFamily("Calibri") self.font_tab3.setPointSize(12) self.font_tab3.setBold(False) self.font_tab3.setWeight(50) self.red_warning = "background-color: #FFC0CB; border-color: red; border-style: solid; border-width: 2px; font-weight: normal;" self.label_29.setVisible(False) self.progressBar.setVisible(False) self.listWidget.setVisible(False) self.pushButton_4.setVisible(False) self.dateEdit.setDate(QtCore.QDate.currentDate()) self.line_3.setVisible(False) #self.line_3.setStyleSheet('color: red;') self.line_4.setVisible(False) #self.line_4.setStyleSheet('color: red;') self.line_5.setVisible(False) #self.line_5.setStyleSheet('color: red;') self.line_6.setVisible(False) #self.line_6.setStyleSheet('color: red;') self.label_9.setVisible(False) #self.label_9.setStyleSheet('color: red;') self.label_19.setVisible(False) #self.label_19.setStyleSheet('color: red;') self.label_20.setVisible(False) #self.label_20.setStyleSheet('color: red;') self.label_30.setVisible(False) #self.label_30.setStyleSheet('color: red;') self.calendarWidget.setVisible(False) self.pushButton_3.setVisible(False) self.pushButton.setEnabled(False) self.pushButton.clicked.connect(self.create) #Запуск self.pushButton_2.clicked.connect(self.open_calend) self.pushButton_3.clicked.connect(self.close_calend) self.pushButton_4.clicked.connect(self.instruction_page_close) self.action.triggered.connect(self.info_page) self.action_2.triggered.connect(self.instruction_page_open) self.action_3.triggered.connect(self.close) self.radioButton_3.toggled.connect(self.onClicked_applic_inapplic) self.radioButton_7.toggled.connect(self.onClicked_type_SI) self.radioButton_8.toggled.connect(self.onClicked_type_SI) self.radioButton_9.toggled.connect(self.onClicked_type_SI) self.checkBox_4.toggled.connect(self.onClicked_checkBox_4) self.comboBox.activated.connect(self.onClicked_comboBox) self.tabWidget.currentChanged.connect(self.test_filled_tabs) self.toolBox.currentChanged.connect(self.create_first_tabs) self.tabWidget_2.tabCloseRequested.connect(self.closeTab_SO) self.tabWidget_3.tabCloseRequested.connect(self.closeTab_SI) self.tabCurrIndex = self.tabWidget.currentIndex() #Проверка на-лету вкладка 1 self.lineEdit.textChanged.connect(self.check_tab_1) self.lineEdit_2.textChanged.connect(self.check_tab_1) self.lineEdit_4.textChanged.connect(self.check_tab_1) self.spinBox_3.valueChanged.connect(self.check_tab_1) #Проверка на-лету вкладка 2 self.dateEdit.dateChanged.connect(self.check_tab_2) self.lineEdit_6.textChanged.connect(self.check_tab_2) self.lineEdit_7.textChanged.connect(self.check_tab_2) self.lineEdit_9.textChanged.connect(self.check_tab_2) self.lineEdit_10.textChanged.connect(self.check_tab_2) self.lineEdit_11.textChanged.connect(self.check_tab_2) #Проверка на-лету вкладка 3 self.lineEdit_12.textChanged.connect(self.check_tab_3) self.lineEdit_13.textChanged.connect(self.check_tab_3) self.lineEdit_16.textChanged.connect(self.check_tab_3) self.lineEdit_19.textChanged.connect(self.check_tab_3) #Проверка на-лету вкладка 4 self.lineEdit_21.textChanged.connect(self.check_tab_4) self.lineEdit_22.textChanged.connect(self.check_tab_4) self.lineEdit_23.textChanged.connect(self.check_tab_4) self.textEdit_27.textChanged.connect(self.check_tab_4) self.indicator_1 = False self.indicator_2 = False self.indicator_3 = False self.indicator_4 = False self.count_1 = 0 self.count_2 = 0 self.count_3 = 0 self.count_4 = 0 #Служебные функции def instruction_page_open(self): self.listWidget.setVisible(True) self.label_29.setVisible(True) self.pushButton_4.setVisible(True) def instruction_page_close(self): self.listWidget.setVisible(False) self.label_29.setVisible(False) self.pushButton_4.setVisible(False) def info_page(self): msg = QtWidgets.QMessageBox() msg.setWindowTitle("Информация") msg.setText("Программное обеспечение: Генератор файлов в формате XML для партий СИ") msg.setInformativeText(f"Разработчик: ФГУП \"ВНИИМС\"\nРаспространяется на безвозмездной основе\n{self.label_25.text()}\n\nТехническая поддержка: <EMAIL>") #msg.setDetailedText(f"Распространяется на безвозмездной основе\nВерсия программы: 2.0") okButton = msg.addButton('Закрыть', QtWidgets.QMessageBox.AcceptRole) #msg.addButton('Отмена', QMessageBox.RejectRole) msg.exec() def logoTimer(self): self.timer = QtCore.QTimer() self.timer.start(5000) self.timer.timeout.connect(self.label_image) self.timer.setSingleShot(True) def label_image(self): self.label_23.setVisible(False) self.label_24.setVisible(False) self.label_25.setVisible(False) self.label_26.setVisible(False) self.label_27.setVisible(False) self.menuBar.setVisible(True) self.setWindowTitle("Генератор xml-файлов для партий СИ") #========================= #Создание и удаление табов (вкладок) def create_first_tabs(self): if self.toolBox.currentIndex() == 2 and self.tabWidget_2.count() == 0: self.comboBox.setEnabled(False) count = self.tabWidget_2.count() self.nb_SO = QtWidgets.QToolButton(text="Добавить СО", autoRaise=True) self.nb_SO.clicked.connect(self.add_tab_SO) self.tabWidget_2.insertTab(count, QtWidgets.QWidget(), "") self.tabWidget_2.tabBar().setTabButton(count, QtWidgets.QTabBar.RightSide, self.nb_SO) self.toolBox.setItemText(2, '> Стандартные образцы, применяемые при поверке') self.add_tab_SO() elif self.toolBox.currentIndex() == 4 and self.tabWidget_3.count() == 0: self.comboBox.setEnabled(False) count_SI = self.tabWidget_3.count() self.nb_SI = QtWidgets.QToolButton(text="Добавить СИ", autoRaise=True) self.nb_SI.clicked.connect(self.add_tab_SI) self.tabWidget_3.insertTab(count_SI, QtWidgets.QWidget(), "") self.tabWidget_3.tabBar().setTabButton(count_SI, QtWidgets.QTabBar.RightSide, self.nb_SI) self.toolBox.setItemText(4, '> СИ, применяемые при поверке') self.add_tab_SI() def add_tab_SO(self): self.nb_SO.setEnabled(False) self.count_3 = 0 self.start_to_create_application() text = f'Образец' index = self.tabWidget_2.count() - 1 tabPage_SO = TabPage_SO(self) self.tabWidget_2.insertTab(index, tabPage_SO, text) self.tabWidget_2.setCurrentIndex(self.tabWidget_2.count() - 2) self.tabWidget_2.currentWidget().lineEditType.textChanged.connect(self.check_tab_3) def add_tab_SI(self): self.nb_SI.setEnabled(False) self.count_3 = 0 self.start_to_create_application() text = f'СИ' index = self.tabWidget_3.count() - 1 tabPage_SI = TabPage_SI(self) self.tabWidget_3.insertTab(index, tabPage_SI, text) self.tabWidget_3.setCurrentIndex(self.tabWidget_3.count() - 2) self.tabWidget_3.currentWidget().lineEditTypeSI.textChanged.connect(self.check_tab_3) self.tabWidget_3.currentWidget().lineEditZavNumber.textChanged.connect(self.check_tab_3) self.tabWidget_3.currentWidget().lineEditInventory.textChanged.connect(self.check_tab_3) def closeTab_SO (self, currentIndex): self.tabWidget_2.removeTab(currentIndex) self.tabWidget_2.setCurrentIndex(self.tabWidget_2.count() - 2) if self.tabWidget_2.count() == 1: self.tabWidget_2.removeTab(currentIndex) self.toolBox.setItemText(2, 'Стандартные образцы, применяемые при поверке') self.toolBox.setCurrentIndex(0) self.label_30.setText("Необходимо заполнить хотя бы одно поле") self.comboBox.setEnabled(True) self.check_tab_3() self.check_tab_3() def closeTab_SI (self, currentIndex): self.tabWidget_3.removeTab(currentIndex) self.tabWidget_3.setCurrentIndex(self.tabWidget_3.count() - 2) if self.tabWidget_3.count() == 1: self.tabWidget_3.removeTab(currentIndex) self.toolBox.setItemText(4, 'СИ, применяемые при поверке') self.toolBox.setCurrentIndex(0) self.label_30.setText("Необходимо заполнить хотя бы одно поле") self.comboBox.setEnabled(True) self.check_tab_3() self.check_tab_3() #========================== #Тестирование табов на заполнение полей def test_filled_tabs(self): ''' При переходе от одного таба к другому происходит проверка того таба, с которого пользователь ушел ''' if self.tabCurrIndex == 0: self.indicator_1 = True self.check_tab_1() elif self.tabCurrIndex == 1: self.indicator_2 = True self.check_tab_2() elif self.tabCurrIndex == 2: self.indicator_3 = True self.check_tab_3() elif self.tabCurrIndex == 3: self.indicator_4 = True self.check_tab_4() self.tabCurrIndex = self.tabWidget.currentIndex() #========================= #Действия по нажатию на радиобаттоны, чекбоксы и комбобоксы def onClicked_type_SI(self): if self.radioButton_7.isChecked(): self.label_4.setText("Тип СИ*") elif self.radioButton_8.isChecked(): self.label_4.setText("Метрологическая аттестация*") elif self.radioButton_9.isChecked(): self.label_4.setText("СИ ВН или СН*") def onClicked_applic_inapplic(self): if self.radioButton_3.isChecked(): self.label_17.setEnabled(True) self.lineEdit_8.setEnabled(True) self.checkBox.setEnabled(True) self.checkBox_2.setEnabled(True) self.lineEdit_9.setEnabled(False) self.lineEdit_9.setStyleSheet("") self.label_18.setEnabled(False) self.check_tab_2() else: self.check_tab_2() self.label_18.setEnabled(True) self.lineEdit_9.setEnabled(True) self.label_17.setEnabled(False) self.lineEdit_8.setEnabled(False) self.checkBox.setEnabled(False) self.checkBox_2.setEnabled(False) def onClicked_comboBox(self): if self.comboBox.currentIndex() > 0: self.toolBox.setEnabled(False) self.label_30.setVisible(False) self.line_5.setVisible(False) else: self.toolBox.setEnabled(True) self.check_tab_3() def onClicked_checkBox_4(self): if self.checkBox_4.isChecked(): self.label_44.setEnabled(True) self.textEdit_27.setEnabled(True) self.check_tab_4() else: self.textEdit_27.setStyleSheet("") self.label_44.setEnabled(False) self.textEdit_27.setEnabled(False) self.textEdit_27.clear() #============================= #Открытие и закрытие календаря для поля Действительна до def open_calend(self): self.label_19.setVisible(False) self.label_20.setVisible(False) self.pushButton_3.setVisible(True) self.calendarWidget.setVisible(True) self.pushButton_2.setVisible(False) self.calendarWidget.clicked.connect(self.valid_date) def close_calend(self): self.pushButton_2.setVisible(True) self.calendarWidget.setVisible(False) self.pushButton_3.setVisible(False) #============================= #Установка даты в формате "yyyy-MM-dd" в поле Действительна до def valid_date(self): self.close_calend() self.lineEdit_6.setText(self.calendarWidget.selectedDate().toString("yyyy-MM-dd")) #============================= #Сбор данных для дальнейшей сборки заявки в цикле def collecting_data(self): ''' Функция создана с целью оптимизации процесса формирования файлов, т.к. единожды записывает все данные в переменные (self.body_part_1, self.body_part_2 - для записи изменяемой части зав. номера, self.body_part_3) и далее в цикле уже подставляет готовые данные, вместо постоянного прохода по строкам и дозапись в переменную self.main_body ''' self.body_part_1 = '' self.body_part_3 = '' #Первая часть формируемой заявки self.body_part_1 = f'<result>\n'+ f'<miInfo>\n' + f'<singleMI>\n' if self.radioButton_7.isChecked(): self.body_part_1 += f'<mitypeNumber>{self.mitypeNumber.strip(" ")}</mitypeNumber>\n' elif self.radioButton_8.isChecked(): self.body_part_1 += f'<crtmitypeTitle>{self.mitypeNumber.strip(" ")}</crtmitypeTitle>\n' elif self.radioButton_9.isChecked(): self.body_part_1 += f'<milmitypeTitle>{self.mitypeNumber.strip(" ")}</milmitypeTitle>\n' #Третья часть формируемой заявки if self.manufactureYear != '': self.body_part_3 += f'<manufactureYear>{self.manufactureYear}</manufactureYear>\n' self.body_part_3 += f'<modification>{self.modification.strip(" ")}</modification>\n' self.body_part_3 += f'</singleMI>\n' self.body_part_3 += f'</miInfo>\n' self.body_part_3 += f'<signCipher>{self.signCipher.strip(" ")}</signCipher>\n' self.body_part_3 += f'<miOwner>{self.miOwner.strip(" ")}</miOwner>\n' self.body_part_3 += f'<vrfDate>{self.vrfDate}+03:00</vrfDate>\n' if self.validDate != '': self.body_part_3 += f'<validDate>{self.validDate}+03:00</validDate>\n' if self.radioButton.isChecked(): self.body_part_3 += f'<type>1</type>\n' else: self.body_part_3 += f'<type>2</type>\n' self.body_part_3 += f'<calibration>{self.calibration}</calibration>\n' if self.radioButton_3.isChecked(): self.body_part_3 += f'<applicable>\n' if self.stickerNum != '': self.body_part_3 += f'<stickerNum>{self.stickerNum.strip(" ")}</stickerNum>\n' self.body_part_3 += f'<signPass>{self.signPass}</signPass>\n' self.body_part_3 += f'<signMi>{self.signMi}</signMi>\n' self.body_part_3 += f'</applicable>\n' else: self.body_part_3 += f'<inapplicable>\n' self.body_part_3 += f'<reasons>{self.reasons.strip(" ")}</reasons>\n' self.body_part_3 += f'</inapplicable>\n' self.body_part_3 += f'<docTitle>{self.method.strip(" ")}</docTitle>\n' if self.metrologist != '': self.body_part_3 += f'<metrologist>{self.metrologist.strip(" ")}</metrologist>\n' self.body_part_3 += f'<means>\n' if self.comboBox.currentIndex() == 0: if self.npe_number != '': text = self.npe_number.strip(' ') text = text.split(';') self.body_part_3 += f'<npe>\n' for t in text: if t != '' and not t.isspace(): self.body_part_3 += f'<number>{t.strip(" ")}</number>\n' self.body_part_3 += f'</npe>\n' if self.uve_number != '': text = self.uve_number.strip(' ') text = text.split(';') self.body_part_3 += f'<uve>\n' for t in text: if t != '' and not t.isspace(): self.body_part_3 += f'<number>{t.strip(" ")}</number>\n' self.body_part_3 += f'</uve>\n' if self.tabWidget_2.count() > 1: self.body_part_3 += f'<ses>\n' for i in range(self.tabWidget_2.count() - 1): self.body_part_3 += F'<se>\n' self.body_part_3 += f'<typeNum>{self.tabWidget_2.widget(i).lineEditType.text().strip(" ")}</typeNum>\n' self.body_part_3 += f'<manufactureYear>{self.tabWidget_2.widget(i).spinBoxManufYear.value()}</manufactureYear>\n' if self.tabWidget_2.widget(i).lineEditSerialNumber.text() != '' and not self.tabWidget_2.widget(i).lineEditSerialNumber.text().isspace(): self.body_part_3 += f'<manufactureNum>{self.tabWidget_2.widget(i).lineEditSerialNumber.text().strip(" ")}</manufactureNum>\n' if self.tabWidget_2.widget(i).lineEditSpecifications.text() != '' and not self.tabWidget_2.widget(i).lineEditSpecifications.text().isspace(): self.body_part_3 += f'<metroChars>{self.tabWidget_2.widget(i).lineEditSpecifications.text().strip(" ")}</metroChars>\n' self.body_part_3 += F'</se>\n' self.body_part_3 += f'</ses>\n' if self.mieta_number != '': text = self.mieta_number.strip(' ') text = text.split(';') self.body_part_3 += f'<mieta>\n' for t in text: if t != '' and not t.isspace(): self.body_part_3 += f'<number>{t.strip(" ")}</number>\n' self.body_part_3 += f'</mieta>\n' if self.tabWidget_3.count() > 1: self.body_part_3 += f'<mis>\n' for i in range(self.tabWidget_3.count() - 1): self.body_part_3 += F'<mi>\n' self.body_part_3 += f'<typeNum>{self.tabWidget_3.widget(i).lineEditTypeSI.text().strip(" ")}</typeNum>\n' if self.tabWidget_3.widget(i).lineEditZavNumber.text() != '': self.body_part_3 += f'<manufactureNum>{self.tabWidget_3.widget(i).lineEditZavNumber.text().strip(" ")}</manufactureNum>\n' elif self.tabWidget_3.widget(i).lineEditInventory.text() != '': self.body_part_3 += f'<inventoryNum>{self.tabWidget_3.widget(i).lineEditInventory.text().strip(" ")}</inventoryNum>\n' self.body_part_3 += F'</mi>\n' self.body_part_3 += f'</mis>\n' if self.reagent_number != '': text = self.reagent_number.strip(' ') text = text.split(';') self.body_part_3 += f'<reagent>\n' for t in text: if t != '' and not t.isspace(): self.body_part_3 += f'<number>{t.strip(" ")}</number>\n' self.body_part_3 += f'</reagent>\n' else: self.body_part_3 += f'<oMethod>{self.oMethod}</oMethod>\n' self.body_part_3 += f'</means>\n' self.body_part_3 += f'<conditions>\n' self.body_part_3 += f'<temperature>{self.temperature.strip(" ")}</temperature>\n' self.body_part_3 += f'<pressure>{self.pressure.strip(" ")}</pressure>\n' self.body_part_3 += f'<hymidity>{self.hymidity.strip(" ")}</hymidity>\n' if self.other != '': self.body_part_3 += f'<other>{self.other.strip(" ")}</other>\n' self.body_part_3 += f'</conditions>\n' if self.structure != '': self.body_part_3 += f'<structure>{self.structure.strip(" ")}</structure>\n' if self.checkBox_4.isChecked(): self.body_part_3 += f'<brief_procedure>\n' self.body_part_3 += f'<characteristics>{self.characteristics.strip(" ")}</characteristics>\n' self.body_part_3 += f'</brief_procedure>\n' if self.additional_info != '': self.body_part_3 += f'<additional_info>{self.additional_info.strip(" ")}</additional_info>\n' self.body_part_3 += f'</result>\n' def applic_constructor(self, filepath, result, part, counter_zav): ''' Сборка записи о поверке и сохранение данных в файл ''' date_stamp = datetime.now().strftime("%Y-%m-%d") #Название файла name_of_file = date_stamp + '_' + self.mitypeNumber.strip(' ') + '_часть_' + str(part) + '_записей_' + str(result) + '_шифр_' + self.signCipher.strip(' ') + '.xml' #Путь сохранения файла FileFullPath = os.path.join(filepath, name_of_file) with open (FileFullPath, 'w', encoding='utf-8') as sample: header_1 = f'<?xml version="1.0" encoding="utf-8" ?>\n' header_comment_1 = f'<!--\n' header_comment_2 = f'Данный xml-файл создан при помощи ПО "Генератор заявок для партий СИ"\n' header_comment_3 = f'Версия ПО 2.0\n' header_comment_4 = f'-->\n' header_2 = f'<application xmlns="urn://fgis-arshin.gost.ru/module-verifications/import/2020-06-19">\n' header = header_1 + header_comment_1 + header_comment_2 + header_comment_3 + header_comment_4 + header_2 sample.write(header) for n in range(result): #Основное тело записи о поверке self.main_body = '' self.body_part_2 = '' #self.body_part_3 = '' manufactureNum = self.prefix_zav_number.lstrip(' ') + str(counter_zav).zfill(self.zav_len) + self.tail_zav_number.rstrip(' ') #Вторая часть формируемой заявки if self.radioButton_5.isChecked(): self.body_part_2 += f'<manufactureNum>{manufactureNum}</manufactureNum>\n' else: self.body_part_2 += f'<inventoryNum>{manufactureNum}</inventoryNum>\n' with open (FileFullPath, 'a', encoding='utf-8') as sample_body: self.main_body += self.body_part_1 self.main_body += self.body_part_2 self.main_body += self.body_part_3 sample_body.write(self.main_body) counter_zav += 1 with open (FileFullPath, 'a', encoding='utf-8') as sample: footer = f'</application>\n' sample.write(footer) return counter_zav #Проверка что введенное значение в поле Заводской номер является числом def check_zav_number_is_int(self): try: self.counter_zav_number = int(self.counter_zav_number) self.label_9.setVisible(False) except ValueError: pass #Проверка таб 1 def check_tab_1(self): #Тип СИ self.mitypeNumber = self.lineEdit.text() #Модификация СИ self.modification = self.lineEdit_2.text() #Дата производства СИ self.manufactureYear = self.spinBox_3.text() if self.manufactureYear == '-': self.manufactureYear = '' else: self.manufactureYear = int(self.spinBox_3.text()) #Заводской номер СИ self.prefix_zav_number = self.lineEdit_3.text() self.counter_zav_number = self.lineEdit_4.text() self.zav_len = len(self.counter_zav_number.strip(' ')) if self.counter_zav_number != '': self.check_zav_number_is_int() self.tail_zav_number = self.lineEdit_5.text() if self.indicator_1 == False: self.universal_fields_checker_with_sender() if self.mitypeNumber != '' and self.modification != '' and type(self.counter_zav_number) is int: self.count_1 = 1 else: self.count_1 = 0 else: field_tab_1 = {'self.mitypeNumber': [self.mitypeNumber, self.lineEdit, self.line_3], 'self.modification': [self.modification, self.lineEdit_2, self.line_3], 'self.counter_zav_number': [str(self.counter_zav_number), self.lineEdit_4, self.line_3]} self.check_zav_number_is_int() if not type(self.counter_zav_number) is int: self.label_9.setVisible(True) self.universal_fields_checker(field_tab_1) if self.mitypeNumber != '' and self.modification != '' and type(self.counter_zav_number) is int: self.line_3.setVisible(False) self.count_1 = 1 else: self.line_3.setVisible(True) self.count_1 = 0 self.start_to_create_application() #Проверка таб 2 def check_tab_2(self): #Условный шифр знака поверки signCipher = self.lineEdit_7.text() self.signCipher = signCipher.upper() #Владелец СИ self.miOwner = self.lineEdit_10.text() #Дата поверки (формат гггг-мм-дд) self.vrfDate = self.dateEdit.text() #Дата действия поверки (формат гггг-мм-дд) self.validDate = self.lineEdit_6.text() #Методика поверки self.method = self.lineEdit_11.text() #Ф.И.О. поверителя self.metrologist = self.lineEdit_20.text() #Результаты калибровки (true/false) calibration = f'{self.checkBox_3.isChecked()}' self.calibration = calibration.lower() #Номер наклейки self.stickerNum = self.lineEdit_8.text() #Знак поверки в паспорте (true/false) signPass = f'{self.checkBox.isChecked()}' self.signPass = signPass.lower() #Знак поверки на СИ (true/false) signMi = f'{self.checkBox_2.isChecked()}' self.signMi = signMi.lower() #Причина непригодности self.reasons = self.lineEdit_9.text() if self.indicator_2 == False: self.universal_fields_checker_with_sender() if self.radioButton_3.isChecked() and self.method != '' and self.signCipher != '' and self.miOwner != '': self.count_2 = 1 elif self.radioButton_4.isChecked() and self.reasons != '' and self.method != '' and self.signCipher != '' and self.miOwner != '': self.count_2 = 1 else: self.count_2 = 0 else: field_tab_2 = {'self.method': [self.method, self.lineEdit_11, self.line_4], 'self.signCipher': [self.signCipher, self.lineEdit_7, self.line_4], 'self.miOwner': [self.miOwner, self.lineEdit_10, self.line_4], 'self.reasons': [self.reasons, self.lineEdit_9, self.line_4]} self.universal_fields_checker(field_tab_2) if (self.radioButton_3.isChecked() and self.method != '' and self.signCipher != '' and self.miOwner != '') or (self.radioButton_4.isChecked() and self.reasons != '' and self.method != '' and self.signCipher != '' and self.miOwner != ''): self.line_4.setVisible(False) self.count_2 = 1 if self.validDate != '' and self.vrfDate == self.validDate: self.label_20.setVisible(False) self.label_19.setVisible(True) self.line_4.setVisible(True) self.count_2 = 0 elif self.validDate != '' and self.vrfDate > self.validDate: self.label_19.setVisible(False) self.label_20.setVisible(True) self.line_4.setVisible(True) self.count_2 = 0 else: self.label_19.setVisible(False) self.label_20.setVisible(False) self.count_2 = 1 else: self.line_4.setVisible(True) self.count_2 = 0 self.start_to_create_application() #Проверка таб 3 def check_tab_3(self): #ГПЭ self.npe_number = self.lineEdit_12.text() #Эталоны self.uve_number = self.lineEdit_13.text() #СИ, применяемые в качестве эталонов self.mieta_number = self.lineEdit_16.text() #Вещества (материалы) self.reagent_number = self.lineEdit_19.text() #Методы поверки без применения средств поверки self.oMethod = self.comboBox.currentIndex() if self.comboBox.currentIndex() == 0: if self.npe_number != '' or self.uve_number != '' or self.tabWidget_2.count() > 0 or self.mieta_number != '' or self.tabWidget_3.count() > 0 or self.reagent_number != '': self.line_5.setVisible(False) self.label_30.setVisible(False) self.comboBox.setEnabled(False) self.count_3 = 1 self.count_3_1 = True self.count_3_2 = True else: self.comboBox.setEnabled(True) self.line_5.setVisible(True) self.label_30.setVisible(True) self.comboBox.setEnabled(True) self.count_3 = 0 self.count_3_1 = False self.count_3_2 = False # #Проверка: Если создана вкладка СО, применяемые при поверке. if self.tabWidget_2.count() > 0: for i in range(self.tabWidget_2.count() - 1): if self.tabWidget_2.widget(i).lineEditType.text() == '' or self.tabWidget_2.widget(i).lineEditType.text().isspace(): self.tabWidget_2.widget(i).lineEditType.setStyleSheet(self.red_warning) self.nb_SO.setEnabled(False) self.line_5.setVisible(True) self.label_30.setVisible(True) self.label_30.setText("Необходимо проверить вкладку Стандартные образцы, применяемые при поверке") self.tabWidget_2.setTabText(i, '!Образец!') self.count_3_1 = False self.start_to_create_application() break else: self.tabWidget_2.widget(i).lineEditType.setStyleSheet('') self.tabWidget_2.widget(i).lineEditType.setFont(self.font_tab3) self.tabWidget_2.setTabText(i, 'Образец') self.nb_SO.setEnabled(True) self.line_5.setVisible(False) self.label_30.setVisible(False) self.count_3_1 = True self.start_to_create_application() #Проверка: Если создана вкладка СИ, применяемые при поверке. if self.tabWidget_3.count() > 0: for i in range(self.tabWidget_3.count() - 1): if self.tabWidget_3.widget(i).lineEditTypeSI.text() == '' or self.tabWidget_3.widget(i).lineEditTypeSI.text().isspace(): self.tabWidget_3.widget(i).lineEditTypeSI.setStyleSheet(self.red_warning) self.nb_SI.setEnabled(False) self.line_5.setVisible(True) self.label_30.setVisible(True) self.label_30.setText("Необходимо проверить вкладку СИ, применяемые при поверке") self.tabWidget_3.setTabText(i, '!СИ!') self.count_3_2 = False self.start_to_create_application() break else: self.tabWidget_3.widget(i).lineEditZavNumber.setStyleSheet('') self.tabWidget_3.widget(i).lineEditZavNumber.setFont(self.font_tab3) self.tabWidget_3.widget(i).lineEditInventory.setStyleSheet('') self.tabWidget_3.widget(i).lineEditInventory.setFont(self.font_tab3) self.tabWidget_3.widget(i).lineEditTypeSI.setStyleSheet('') self.tabWidget_3.widget(i).lineEditTypeSI.setFont(self.font_tab3) self.nb_SI.setEnabled(True) self.line_5.setVisible(False) self.label_30.setVisible(False) self.tabWidget_3.setTabText(i, 'СИ') self.count_3_2 = True self.start_to_create_application() #Если заполнено поле Тип СИ, то проверка заполнения зав. № или буквенно-цифрового обозначения if self.tabWidget_3.widget(i).lineEditTypeSI.text() != '' and (self.tabWidget_3.widget(i).lineEditZavNumber.text() == '' and self.tabWidget_3.widget(i).lineEditInventory.text() == ''): self.tabWidget_3.widget(i).lineEditInventory.setEnabled(True) self.tabWidget_3.widget(i).lineEditZavNumber.setEnabled(True) self.tabWidget_3.widget(i).lineEditZavNumber.setStyleSheet(self.red_warning) self.tabWidget_3.widget(i).lineEditInventory.setStyleSheet(self.red_warning) self.nb_SI.setEnabled(False) self.line_5.setVisible(True) self.label_30.setVisible(True) self.label_30.setText("Необходимо заполнить либо буквенно-цифровое обозначение, либо заводской номер") self.tabWidget_3.setTabText(i, '!СИ!') self.count_3_2 = False self.start_to_create_application() break if self.tabWidget_3.widget(i).lineEditZavNumber.text() != '': self.tabWidget_3.widget(i).lineEditInventory.setEnabled(False) elif self.tabWidget_3.widget(i).lineEditInventory.text() != '': self.tabWidget_3.widget(i).lineEditZavNumber.setEnabled(False) if self.count_3_1 and self.count_3_2: self.count_3 = 1 else: self.line_5.setVisible(True) self.label_30.setVisible(True) self.count_3 = 0 else: self.line_5.setVisible(False) self.label_30.setVisible(False) self.count_3 = 1 self.start_to_create_application() #Проверка таб 4 def check_tab_4(self): #Условия проведения поверки self.temperature = self.lineEdit_21.text() self.pressure = self.lineEdit_22.text() self.hymidity = self.lineEdit_23.text() #Другие факторы self.other = self.textEdit_24.toPlainText() #Состав СИ, представленного на поверку self.structure = self.textEdit_25.toPlainText() #Краткая характеристика объема поверки self.characteristics = self.textEdit_27.toPlainText() #Прочие сведения self.additional_info = self.textEdit_26.toPlainText() if self.indicator_4 == False: self.universal_fields_checker_with_sender() if self.checkBox_4.checkState() == 0 and self.temperature != '' and self.pressure != '' and self.hymidity != '': self.count_4 = 1 elif self.checkBox_4.isChecked() and self.characteristics != '' and self.temperature != '' and self.pressure != '' and self.hymidity != '': self.count_4 = 1 else: self.count_4 = 0 else: field_tab_4 = {'self.temperature': [self.temperature, self.lineEdit_21, self.line_6], 'self.pressure': [self.pressure, self.lineEdit_22, self.line_6], 'self.hymidity': [self.hymidity, self.lineEdit_23, self.line_6], 'self.characteristics': [self.characteristics, self.textEdit_27, self.line_6]} self.universal_fields_checker(field_tab_4) if self.checkBox_4.checkState() == 0 and self.temperature != '' and self.pressure != '' and self.hymidity != '': self.line_6.setVisible(False) self.count_4 = 1 elif self.checkBox_4.isChecked() and self.characteristics != '' and self.temperature != '' and self.pressure != '' and self.hymidity != '': self.line_6.setVisible(False) self.count_4 = 1 else: self.line_6.setVisible(True) self.count_4 = 0 self.start_to_create_application() def universal_fields_checker(self, field_tab): ''' Универсальная функция проверки заполнения полей использующая словари с указанными полями (переменные, виджеты, сигнальные линии над вкладками) ''' for field in field_tab.keys(): required_field = field_tab[field][1] alert_field = field_tab[field][2] #Проход циклом по всем обязательным полям, выявление незаполненных обязательных полей if (field != 'self.reasons' and field != 'self.characteristics') and field_tab[field][0] == '' or field_tab[field][0].isspace(): required_field.setStyleSheet(self.red_warning) alert_field.setVisible(True) elif (field == 'self.reasons' and self.radioButton_4.isChecked()) and (field_tab[field][0] == '' or field_tab[field][0].isspace()): required_field.setStyleSheet(self.red_warning) alert_field.setVisible(True) elif (field == 'self.characteristics' and self.checkBox_4.isChecked()) and (field_tab[field][0] == '' or field_tab[field][0].isspace()): required_field.setStyleSheet(self.red_warning) alert_field.setVisible(True) else: required_field.setStyleSheet('') alert_field.setVisible(False) def universal_fields_checker_with_sender(self): ''' Универсальная функция проверки заполнения полей использующая sender в качестве источника сигнала (sender получает данные от разных переменных) ''' sender = self.sender() is_lineEdit = isinstance(sender, QtWidgets.QLineEdit) is_textEdit = isinstance(sender, QtWidgets.QTextEdit) if is_lineEdit and (sender.text() == '' or sender.text().isspace()): sender.setStyleSheet(self.red_warning) elif (is_textEdit and self.checkBox_4.isChecked()) and (sender.toPlainText() == '' or sender.toPlainText().isspace()): sender.setStyleSheet(self.red_warning) else: sender.setStyleSheet('') if sender == self.lineEdit_4 and not type(self.counter_zav_number) is int: self.check_zav_number_is_int() sender.setStyleSheet(self.red_warning) self.label_9.setVisible(True) elif sender == self.lineEdit_4 and type(self.counter_zav_number) is int: self.label_9.setVisible(False) def start_to_create_application(self): ''' Функция проверяет все ли условия выполнены для допуска к формированию xml-файла ''' self.result = 0 self.result = self.count_1 + self.count_2 + self.count_3 + self.count_4 if self.result == 4: self.pushButton.setText("Создать xml-файл") self.pushButton.setEnabled(True) else: self.pushButton.setText("Заполнить форму") self.pushButton.setEnabled(False) def update_data(self): ''' Обновление содержимого переменных (для случая, если после формирования файлов внесены изменения в необязательные поля, т.к. для этих полей нет проверки изменения содержимого на-лету) ''' #Тип СИ self.mitypeNumber = self.lineEdit.text() #Модификация СИ self.modification = self.lineEdit_2.text() #Дата производства СИ self.manufactureYear = self.spinBox_3.text() if self.manufactureYear == '-': self.manufactureYear = '' else: self.manufactureYear = int(self.spinBox_3.text()) #Заводской номер СИ self.prefix_zav_number = self.lineEdit_3.text() self.counter_zav_number = self.lineEdit_4.text() self.zav_len = len(self.counter_zav_number.strip(' ')) if self.counter_zav_number != '': self.check_zav_number_is_int() self.tail_zav_number = self.lineEdit_5.text() #Условный шифр знака поверки signCipher = self.lineEdit_7.text() self.signCipher = signCipher.upper() #Владелец СИ self.miOwner = self.lineEdit_10.text() #Дата поверки (формат гггг-мм-дд) self.vrfDate = self.dateEdit.text() #Дата действия поверки (формат гггг-мм-дд) self.validDate = self.lineEdit_6.text() #Методика поверки self.method = self.lineEdit_11.text() #Ф.И.О. поверителя self.metrologist = self.lineEdit_20.text() #Результаты калибровки (true/false) calibration = f'{self.checkBox_3.isChecked()}' self.calibration = calibration.lower() #Номер наклейки self.stickerNum = self.lineEdit_8.text() #Знак поверки в паспорте (true/false) signPass = f'{self.checkBox.isChecked()}' self.signPass = signPass.lower() #Знак поверки на СИ (true/false) signMi = f'{self.checkBox_2.isChecked()}' self.signMi = signMi.lower() #Причина непригодности self.reasons = self.lineEdit_9.text() #ГПЭ self.npe_number = self.lineEdit_12.text() #Эталоны self.uve_number = self.lineEdit_13.text() #СИ, применяемые в качестве эталонов self.mieta_number = self.lineEdit_16.text() #Вещества (материалы) self.reagent_number = self.lineEdit_19.text() #Методы поверки без применения средств поверки self.oMethod = self.comboBox.currentIndex() #Условия проведения поверки self.temperature = self.lineEdit_21.text() self.pressure = self.lineEdit_22.text() self.hymidity = self.lineEdit_23.text() #Другие факторы self.other = self.textEdit_24.toPlainText() #Состав СИ, представленного на поверку self.structure = self.textEdit_25.toPlainText() #Краткая характеристика объема поверки self.characteristics = self.textEdit_27.toPlainText() #Прочие сведения self.additional_info = self.textEdit_26.toPlainText() def create(self): #Обновление содержимого переменных self.update_data() #Сбор данных в переменные self.collecting_data() #Финишная проверка всех вкладок self.check_tab_1() self.check_tab_2() self.check_tab_3() self.check_tab_4() #Общее количество записей о поверках СИ TOTAL_RESULTS = int(self.spinBox.text()) #Количество записей о поверках СИ в одной заявке (не более 5000 записей) RESULTS_IN_APP = int(self.spinBox_2.text()) filepath = QtWidgets.QFileDialog.getExistingDirectory(self, "Каталог сохранения файлов") if filepath != '': # self.pushButton.setText("Подготовка данных") # self.timer.start(2500) # self.pushButton.setText("Создание xml-файла") self.pushButton.setVisible(False) self.progressBar.setVisible(True) parts = TOTAL_RESULTS // RESULTS_IN_APP # Вычисление количества заявок (Общее количество заявок делится без остатка на желаемое количество в одной заявке) if TOTAL_RESULTS % RESULTS_IN_APP != 0: # Если остаток от деления заявок на части не равен 0, то количество заявок увеличивается на 1. parts += 1 set_progress = 0 progress_value = 100 / (TOTAL_RESULTS / RESULTS_IN_APP) #Заводской номер СИ counter_zav_number = self.counter_zav_number for j in range(parts): if TOTAL_RESULTS <= RESULTS_IN_APP: zav = self.applic_constructor(filepath, TOTAL_RESULTS, j + 1, counter_zav_number) elif TOTAL_RESULTS > RESULTS_IN_APP: zav = self.applic_constructor(filepath, RESULTS_IN_APP, j + 1, counter_zav_number) TOTAL_RESULTS -= RESULTS_IN_APP counter_zav_number = zav set_progress += progress_value if set_progress > 100: set_progress = 100 self.progressBar.setValue(round(set_progress)) self.statusBar().showMessage('Формирование файлов завершено!') self.pushButton.setText("Создать xml-файл") self.pushButton.setVisible(True) self.progressBar.setVisible(False) self.statusTimer() def statusTimer(self): self.timer = QtCore.QTimer() self.timer.start(2500) self.timer.timeout.connect(self.clearStatusBar) self.timer.setSingleShot(True) #Таймер выполняется один раз def clearStatusBar(self): self.statusBar().clearMessage() def closeEvent(self, event): #Запрос на закрытие программы reply = QtWidgets.QMessageBox.question(self, 'Предупреждение', "Закрыть приложение?", QtWidgets.QMessageBox.No | QtWidgets.QMessageBox.No, QtWidgets.QMessageBox.Yes) if reply == QtWidgets.QMessageBox.Yes: event.accept() else: event.ignore() def keyPressEvent(self, e): #Выход из программы по Esc if e.key() == QtCore.Qt.Key_Escape: self.close() if e.key() in [QtCore.Qt.Key_Enter, QtCore.Qt.Key_Return]: self.start_to_create_application() if __name__ == '__main__': app = QtWidgets.QApplication(sys.argv) window = main_window() window.show() sys.exit(app.exec_())
920e69cc7fc62c7daa6c137fbc93d401842c9969
[ "Python" ]
3
Python
ipsorus/xml_generator_FGIS2020
f6c165db7510f8e891b1ce1cd43b49e9bc6c07bb
dffbf81b75fbc7e35979305cea7c9895eb64c836
refs/heads/master
<file_sep>package com.employee.service; import java.util.List; import com.employee.entity.Employee; public interface EmployeeService { public void addEmployee(Employee employee); public List<Employee> findAll(); public void deleteEmployee(Employee employee, String name); public Employee Find(String name); void editEmployee(Employee employee, String name); } <file_sep>jdbc.driverClassName=com.mysql.cj.jdbc.Driver jdbc.url=jdbc:mysql://localhost:3306/db_with_jdbctemplate jdbc.username=root jdbc.password=<PASSWORD><file_sep>package com.employee.config; import javax.sql.DataSource; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.ComponentScan; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.PropertySource; import org.springframework.core.env.Environment; import org.springframework.jdbc.core.JdbcTemplate; import org.springframework.jdbc.datasource.DriverManagerDataSource; import org.springframework.web.servlet.config.annotation.EnableWebMvc; import org.springframework.web.servlet.view.InternalResourceViewResolver; import org.springframework.web.servlet.view.JstlView; @Configuration @ComponentScan(basePackages="com.employee") @PropertySource(value= {"classpath:application.properties"}) @EnableWebMvc public class AppConfig { @Autowired private Environment env; @Bean public InternalResourceViewResolver resolver() { InternalResourceViewResolver resolver= new InternalResourceViewResolver(); resolver.setViewClass(JstlView.class); resolver.setPrefix("/WEB-INF/views/"); resolver.setSuffix(".jsp"); return resolver; } @Bean public DataSource datasources() { DriverManagerDataSource datasources= new DriverManagerDataSource(); datasources.setDriverClassName(env.getRequiredProperty("jdbc.driverClassName")); datasources.setUrl(env.getRequiredProperty("jdbc.url")); datasources.setUsername(env.getRequiredProperty("jdbc.username")); datasources.setPassword(env.getRequiredProperty("jdbc.password")); return datasources; } @Bean public JdbcTemplate jdbcTemplate(DataSource dataSources) { JdbcTemplate jdbcTemplate = new JdbcTemplate(dataSources); jdbcTemplate.setResultsMapCaseInsensitive(true); return jdbcTemplate; } } <file_sep>package com.employee.dao; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.jdbc.core.BeanPropertyRowMapper; import org.springframework.jdbc.core.JdbcTemplate; import org.springframework.stereotype.Repository; import com.employee.entity.Employee; @Repository @Qualifier("EmployeeDao") public class EmployeeDataImpl implements EmployeeDao { @Autowired JdbcTemplate jdbcTemplate; @Override public void addEmployee(Employee employee) { jdbcTemplate.update("insert into employee(first_name,last_name,departement) values(?,?,?)", employee.getFirstName(),employee.getLastName(),employee.getDepartement()); System.out.println("employee data added"); // TODO Auto-generated method stub } @Override public void editEmployee(Employee employee,String name) { // TODO Auto-generated method stub jdbcTemplate.update("update employee set last_name=?,departement=? where first_name=?", employee.getLastName(),employee.getDepartement(),employee.getFirstName()); System.out.println("employee data updated"); } @Override public void deleteEmployee(Employee employee,String name) { // TODO Auto-generated method stub jdbcTemplate.update("delete from employee where first_name=?",name); System.out.println("employee data deleted"); } @Override public Employee Find(String name) { @SuppressWarnings({ "unchecked", "rawtypes" }) Employee employee =(Employee) jdbcTemplate.queryForObject("select first_name,last_name,departement from employee where first_name=?", new Object[] {name},new BeanPropertyRowMapper(Employee.class)); return employee; // TODO Auto-generated method stub } @Override public List<Employee> findAll() { @SuppressWarnings({ "unchecked", "rawtypes" }) List<Employee> employee =jdbcTemplate.query("select first_name,last_name,departement from employee", new BeanPropertyRowMapper(Employee.class)); System.out.println(employee); return employee; } }
08d779fc147287290c2ab336d1511de4906a68cd
[ "Java", "INI" ]
4
Java
nikita728/gitexmple
50c994f3326967e511a5f115a7dd86d7fae757ed
ea4836fd18e712ef19ce47346c75b737558b0bef
refs/heads/master
<repo_name>Brazilian-Institute-of-Robotics/image_processing-orogen-apriltags<file_sep>/tasks/CMakeLists.txt # Generated from orogen/lib/orogen/templates/tasks/CMakeLists.txt include(apriltags2TaskLib) ADD_LIBRARY(${APRILTAGS2_TASKLIB_NAME} SHARED ${APRILTAGS2_TASKLIB_SOURCES}) add_dependencies(${APRILTAGS2_TASKLIB_NAME} regen-typekit) TARGET_LINK_LIBRARIES(${APRILTAGS2_TASKLIB_NAME} ${OrocosRTT_LIBRARIES} ${APRILTAGS2_TASKLIB_DEPENDENT_LIBRARIES}) SET_TARGET_PROPERTIES(${APRILTAGS2_TASKLIB_NAME} PROPERTIES LINK_INTERFACE_LIBRARIES "${APRILTAGS2_TASKLIB_INTERFACE_LIBRARIES}") SET_TARGET_PROPERTIES(${APRILTAGS2_TASKLIB_NAME} PROPERTIES INTERFACE_LINK_LIBRARIES "${APRILTAGS2_TASKLIB_INTERFACE_LIBRARIES}") INSTALL(TARGETS ${APRILTAGS2_TASKLIB_NAME} RUNTIME DESTINATION bin LIBRARY DESTINATION lib/orocos) INSTALL(FILES ${APRILTAGS2_TASKLIB_HEADERS} DESTINATION include/orocos/apriltags2) <file_sep>/tasks/Task.cpp /* Generated from orogen/lib/orogen/templates/tasks/Task.cpp */ #include "Task.hpp" using namespace apriltags2; Task::Task(std::string const& name) : TaskBase(name), out_frame_ptr(new base::samples::frame::Frame()) { } Task::Task(std::string const& name, RTT::ExecutionEngine* engine) : TaskBase(name, engine), out_frame_ptr(new base::samples::frame::Frame()) { } Task::~Task() { } /// The following lines are template definitions for the various state machine // hooks defined by Orocos::RTT. See Task.hpp for more detailed // documentation about them. bool Task::configureHook() { if (! TaskBase::configureHook()) return false; // setting camera matrix and distortion matrix frame_helper::CameraCalibration cal = _camera_calibration.get(); camera_k = (cv::Mat_<double>(3,3) << cal.fx, 0, cal.cx, 0, cal.fy, cal.cy, 0, 0, 1); camera_dist = (cv::Mat_<double>(1,4) << cal.d0, cal.d1, cal.d2, cal.d3); // setting immutable parameters tag_code = _tag_code.get(); rvec.create(3,1,CV_32FC1); tvec.create(3,1,CV_32FC1); return true; } bool Task::startHook() { if (! TaskBase::startHook()) return false; return true; } void Task::updateHook() { TaskBase::updateHook(); RTT::extras::ReadOnlyPointer<base::samples::frame::Frame> current_frame_ptr; //main loop for detection in each input frame for(int count=0; _image.read(current_frame_ptr) == RTT::NewData; ++count) { //convert base::samples::frame::Frame to grayscale cv::Mat cv::Mat image; base::samples::frame::Frame temp_frame; if (current_frame_ptr->isBayer()) { frame_helper::FrameHelper::convertBayerToRGB24(*current_frame_ptr, temp_frame); image = frame_helper::FrameHelper::convertToCvMat(temp_frame); cv::cvtColor(image, image, cv::COLOR_BGR2RGB); } else image = frame_helper::FrameHelper::convertToCvMat(*current_frame_ptr); // convert to grayscale and undistort both images cv::Mat image_gray; if(image.channels() == 3) { cv::cvtColor(image, image_gray, cv::COLOR_RGB2GRAY); cv::Mat temp; cv::undistort(image_gray, temp, camera_k, camera_dist); image_gray = temp; cv::Mat temp2; cv::undistort(image, temp2, camera_k, camera_dist); image = temp2; } else { cv::undistort(image, image_gray, camera_k, camera_dist); cv::Mat temp; cv::undistort(image, temp, camera_k, camera_dist); image = temp; } //TODO: Create a enum with the tag_codes; //set the apriltag family apriltag_family_t *tf = NULL; (tag_code == "36h11") ? tf = tag36h11_create() : throw std::runtime_error("The desired apriltag family code is not implemented"); //TODO: Create orogen properties to set all these values. // create a apriltag detector and add the current family apriltag_detector_t *td = apriltag_detector_create(); apriltag_detector_add_family(td, tf); td->quad_decimate = 1.0; td->quad_sigma = 0.0; td->nthreads = 4; td->debug = 0; td->refine_decode = 0; td->refine_pose = 0; //Repeat processing on input set this many int maxiters = 1; const int hamm_hist_max = 10; //main loop for (int iter = 0; iter < maxiters; iter++) { if (maxiters > 1) printf("iter %d / %d\n", iter + 1, maxiters); int hamm_hist[hamm_hist_max]; memset(hamm_hist, 0, sizeof(hamm_hist)); //convert cv::Mat to image_u8_t image_u8_t *im = image_u8_create(image_gray.cols, image_gray.rows); memcpy(im->buf, image_gray.data, image_gray.total()*image_gray.elemSize()); //detect markers zarray_t *detections = apriltag_detector_detect(td, im); if (zarray_size(detections)) std::cout << "//////////////////////////" << std::endl; //build the rbs_vector and draw detected markers std::vector<base::samples::RigidBodyState> rbs_vector; for (int i = 0; i < zarray_size(detections); i++) { apriltag_detection_t *det; zarray_get(detections, i, &det); //estimate pose and push_back to rbs_vector base::samples::RigidBodyState rbs; getRbs(rbs, _marker_size.get(), det->p, camera_k, cv::Mat()); rbs.sourceFrame = _source_frame.get(); rbs.time = current_frame_ptr->time; rbs_vector.push_back(rbs); std::cout << "ID: " << det->id << " x: " << rbs.position.x() << " y: " << rbs.position.y() << " z: " << rbs.position.z() << " roll: " << rbs.getRoll()*180/M_PI << " pitch: " << rbs.getPitch()*180/M_PI << " yaw: " << rbs.getYaw()*180/M_PI << std::endl; if (!_quiet.get()) printf("detection %3d: id (%2dx%2d)-%-4d, hamming %d, goodness %8.3f, margin %8.3f\n", i, det->family->d*det->family->d, det->family->h, det->id, det->hamming, det->goodness, det->decision_margin); if (_draw_image.get()) { draw(image,det->p, det->c, det->id, cv::Scalar(0,0,255), 2); draw3dAxis(image, _marker_size.get(), camera_k, cv::Mat()); draw3dCube(image, _marker_size.get(), camera_k, cv::Mat()); } hamm_hist[det->hamming]++; apriltag_detection_destroy(det); } zarray_destroy(detections); if (!_quiet.get()) { timeprofile_display(td->tp); printf("nedges: %d, nsegments: %d, nquads: %d\n", td->nedges, td->nsegments, td->nquads); printf("Hamming histogram: "); for (int i = 0; i < hamm_hist_max; i++) printf("%5d", hamm_hist[i]); printf("%12.3f", timeprofile_total_utime(td->tp) / 1.0E3); printf("\n"); } image_u8_destroy(im); //write the the image in the output port if (_draw_image.get()) { base::samples::frame::Frame *pframe = out_frame_ptr.write_access(); frame_helper::FrameHelper::copyMatToFrame(image,*pframe); pframe->time = base::Time::now(); out_frame_ptr.reset(pframe); _output_image.write(out_frame_ptr); } //write the markers in the output port if (rbs_vector.size() != 0) { rbs_vector.clear(); _marker_poses.write(rbs_vector); } } apriltag_detector_destroy(td); tag36h11_destroy(tf); } } void Task::errorHook() { TaskBase::errorHook(); } void Task::stopHook() { TaskBase::stopHook(); } void Task::cleanupHook() { TaskBase::cleanupHook(); } void Task::getRbs(base::samples::RigidBodyState &rbs, float markerSizeMeters, double points[][2], cv::Mat camMatrix,cv::Mat distCoeff)throw(cv::Exception) { if (markerSizeMeters<=0)throw cv::Exception(9004,"markerSize<=0: invalid markerSize","getRbs",__FILE__,__LINE__); if (camMatrix.rows==0 || camMatrix.cols==0) throw cv::Exception(9004,"CameraMatrix is empty","getRbs",__FILE__,__LINE__); double halfSize=markerSizeMeters/2.; //set objects points clockwise starting from (-1,+1,0) cv::Mat ObjPoints(4,3,CV_32FC1); ObjPoints.at<float>(0,0)=-halfSize; ObjPoints.at<float>(0,1)=+halfSize; ObjPoints.at<float>(0,2)=0; ObjPoints.at<float>(1,0)=+halfSize; ObjPoints.at<float>(1,1)=+halfSize; ObjPoints.at<float>(1,2)=0; ObjPoints.at<float>(2,0)=+halfSize; ObjPoints.at<float>(2,1)=-halfSize; ObjPoints.at<float>(2,2)=0; ObjPoints.at<float>(3,0)=-halfSize; ObjPoints.at<float>(3,1)=-halfSize; ObjPoints.at<float>(3,2)=0; //set image points from the detected points cv::Mat ImagePoints(4,2,CV_32FC1); for (int c=0;c<4;c++) { ImagePoints.at<float>(c,0)=points[c][0]; ImagePoints.at<float>(c,1)=points[c][1]; } cv::Mat raux,taux; cv::solvePnP(ObjPoints, ImagePoints, camMatrix, distCoeff,raux,taux); raux.convertTo(rvec,CV_32F); taux.convertTo(tvec,CV_32F); cv::Mat R,t; cv::Rodrigues(rvec,R); R = R.t(); t = -R*tvec; // //TODO z_forward // if (_z_forward.get()) // { // double temp = t.at<float>(0); // t.at<float>(0) = t.at<float>(2); // t.at<float>(2) = -t.at<float>(1); // t.at<float>(1) = -temp; // cv::Mat rvec2(3,1,CV_64FC1); // rvec2.at<float>(0) = rvec.at<float>(2); // rvec2.at<float>(2) = -rvec.at<float>(1); // rvec2.at<float>(1) = -rvec.at<float>(0); // cv::Rodrigues(rvec2,R); // R = R.t(); // } base::Matrix3d m; cv::cv2eigen(R,m); base::Quaterniond quat(m); rbs.orientation = quat; rbs.position.x() = t.at<float>(0); rbs.position.y() = t.at<float>(1); rbs.position.z() = t.at<float>(2); } void Task::draw(cv::Mat &in, double p[][2], double c[], int id, cv::Scalar color, int lineWidth)const { cv::line( in,cv::Point(p[0][0], p[0][1]),cv::Point(p[1][0], p[1][1]),color,lineWidth,cv::LINE_AA); cv::line( in,cv::Point(p[1][0], p[1][1]),cv::Point(p[2][0], p[2][1]),color,lineWidth,cv::LINE_AA); cv::line( in,cv::Point(p[2][0], p[2][1]),cv::Point(p[3][0], p[3][1]),color,lineWidth,cv::LINE_AA); cv::line( in,cv::Point(p[3][0], p[3][1]),cv::Point(p[0][0], p[0][1]),color,lineWidth,cv::LINE_AA); cv::rectangle( in,cv::Point(p[0][0], p[0][1]) - cv::Point(2,2),cv::Point(p[0][0], p[0][1])+cv::Point(2,2),cv::Scalar(0,0,255,255),lineWidth,cv::LINE_AA); cv::rectangle( in,cv::Point(p[1][0], p[1][1]) - cv::Point(2,2),cv::Point(p[1][0], p[1][1])+cv::Point(2,2),cv::Scalar(0,255,0,255),lineWidth,cv::LINE_AA); cv::rectangle( in,cv::Point(p[2][0], p[2][1]) - cv::Point(2,2),cv::Point(p[2][0], p[2][1])+cv::Point(2,2),cv::Scalar(255,0,0,255),lineWidth,cv::LINE_AA); char cad[100]; sprintf(cad,"id=%d",id); //determine the centroid cv::Point cent(0,0); for (int i=0;i<4;i++) { cent.x+=c[0]; cent.y+=c[1]; } cent.x/=4.; cent.y/=4.; cv::putText(in,cad, cent,cv::FONT_HERSHEY_SIMPLEX, 1, cv::Scalar(255-color[0],255-color[1],255-color[2],255),2); } void Task::draw3dCube(cv::Mat &Image,float marker_size,cv::Mat camMatrix,cv::Mat distCoeff) { cv::Mat objectPoints (8,3,CV_32FC1); double halfSize=marker_size/2; objectPoints.at<float>(0,0)=-halfSize; objectPoints.at<float>(0,1)=-halfSize; objectPoints.at<float>(0,2)=0; objectPoints.at<float>(1,0)=-halfSize; objectPoints.at<float>(1,1)=halfSize; objectPoints.at<float>(1,2)=0; objectPoints.at<float>(2,0)=halfSize; objectPoints.at<float>(2,1)=halfSize; objectPoints.at<float>(2,2)=0; objectPoints.at<float>(3,0)=halfSize; objectPoints.at<float>(3,1)=-halfSize; objectPoints.at<float>(3,2)=0; objectPoints.at<float>(4,0)=-halfSize; objectPoints.at<float>(4,1)=-halfSize; objectPoints.at<float>(4,2)=marker_size; objectPoints.at<float>(5,0)=-halfSize; objectPoints.at<float>(5,1)=halfSize; objectPoints.at<float>(5,2)=marker_size; objectPoints.at<float>(6,0)=halfSize; objectPoints.at<float>(6,1)=halfSize; objectPoints.at<float>(6,2)=marker_size; objectPoints.at<float>(7,0)=halfSize; objectPoints.at<float>(7,1)=-halfSize; objectPoints.at<float>(7,2)=marker_size; std::vector<cv::Point2f> imagePoints; cv::projectPoints(objectPoints, rvec,tvec, camMatrix ,distCoeff, imagePoints); //draw lines of different colours for (int i=0;i<4;i++) cv::line(Image,imagePoints[i],imagePoints[(i+1)%4],cv::Scalar(0,0,255,255),1,cv::LINE_AA); for (int i=0;i<4;i++) cv::line(Image,imagePoints[i+4],imagePoints[4+(i+1)%4],cv::Scalar(0,0,255,255),1,cv::LINE_AA); for (int i=0;i<4;i++) cv::line(Image,imagePoints[i],imagePoints[i+4],cv::Scalar(0,0,255,255),1,cv::LINE_AA); } void Task::draw3dAxis(cv::Mat &Image, float marker_size, cv::Mat camera_matrix, cv::Mat dist_matrix) { float size=marker_size*2; cv::Mat objectPoints (4,3,CV_32FC1); objectPoints.at<float>(0,0)=0; objectPoints.at<float>(0,1)=0; objectPoints.at<float>(0,2)=0; objectPoints.at<float>(1,0)=size; objectPoints.at<float>(1,1)=0; objectPoints.at<float>(1,2)=0; objectPoints.at<float>(2,0)=0; objectPoints.at<float>(2,1)=size; objectPoints.at<float>(2,2)=0; objectPoints.at<float>(3,0)=0; objectPoints.at<float>(3,1)=0; objectPoints.at<float>(3,2)=size; std::vector<cv::Point2f> imagePoints; cv::projectPoints( objectPoints, rvec, tvec, camera_matrix, dist_matrix, imagePoints); //draw lines of different colours cv::line(Image,imagePoints[0],imagePoints[1],cv::Scalar(0,0,255,255),1,cv::LINE_AA); cv::line(Image,imagePoints[0],imagePoints[2],cv::Scalar(0,255,0,255),1,cv::LINE_AA); cv::line(Image,imagePoints[0],imagePoints[3],cv::Scalar(255,0,0,255),1,cv::LINE_AA); cv::putText(Image,"x", imagePoints[1],cv::FONT_HERSHEY_SIMPLEX, 0.6, cv::Scalar(0,0,255,255),2); cv::putText(Image,"y", imagePoints[2],cv::FONT_HERSHEY_SIMPLEX, 0.6, cv::Scalar(0,255,0,255),2); cv::putText(Image,"z", imagePoints[3],cv::FONT_HERSHEY_SIMPLEX, 0.6, cv::Scalar(255,0,0,255),2); }
992820beaf30bd2f959772efd890dbc206b3c41f
[ "CMake", "C++" ]
2
CMake
Brazilian-Institute-of-Robotics/image_processing-orogen-apriltags
c87d9fd1d540b4be3145f46409c826e6c16117e8
a20b3553c596a3f0eba93a4e9105c26b8f8cf627
refs/heads/master
<repo_name>ByrenHiggin/VB-C-Code-Snippets<file_sep>/README.md # VB-C-Code-Snippets ## Code snippets written for VB and C# Current Files: >XML Traversal A recursive node system to build a data representation of an XML document and storing on a database or other format >Markdown A regex based markdown to other format converter. Extracts the text from between markdown tags and converts it to a HTML representation. <file_sep>/XML-Traversal/C#.cs //Names for nodes to scan for string XMLNodeName = "entry"; //A class scoped variable to increment an arbitrary surrogate key for each valid scanned record. int uid; //Function: Read through the XML doc specified in _GetTOCFilepath() and attemtp to build a database from it. If an exception occurs, catch exception and build an error message. protected void BTN_genXML_Click(object sender, System.EventArgs e) { try { _XMLTraversalAndBuilder(); } catch (Exception ex) { //errortext = _getlinepreview(_GetTOCFileLocation, CType(L_linenum.Text, Integer)) } } //Function: access the broken file and return a preview of the error generated from _XMLTRAVERSALANDBUILDER private string _getlinepreview(string filepath, int linenum) { string s = ""; using (StreamReader File = new StreamReader(_GetTOCFileLocation())) { for (int i = 1; i <= linenum - 2; i++) { if ((File.ReadLine() == null)) { throw new ArgumentOutOfRangeException("Line Number is not valid, ensure the file is not empty"); } } try { string line = null; for (int i = 1; i <= 3; i++) { line = File.ReadLine(); if (line == null) { throw new ArgumentOutOfRangeException("Line Number is not valid, ensure the file is not empty"); } line = line.Replace("<", "&lt;").Replace(">", "&gt;"); if ((i == 2)) { line = "<strong>" + line + "</strong>"; } s = s + line + "<br />"; } } catch (Exception ex) { } } return s; } //Function: Load the XML document, and begin lateral traversal. private void _XMLTraversalAndBuilder() { XmlDocument xmlDoc = new XmlDocument(); using (FileStream fs = new FileStream(_GetTOCFileLocation(), FileMode.Open, FileAccess.Read, FileShare.Read)) { xmlDoc.Load(fs); XmlNode root = xmlDoc.DocumentElement; _scanChildRecursive(root, 0, uid); } //Show success } //Function to return file when loaded. abstracted if we need to go cross-server etc. private string _GetTOCFileLocation() { return Server.MapPath("toc.xml"); } //Recursive depth-breadth node search private void _scanChildRecursive(XmlNode node, int level, int parentid) { foreach (XmlNode n in node.ChildNodes) { if ((n.Name.ToLower() == XMLNodeName)) { _GetNodeData(ref n, level, parentid); } if ((n.HasChildNodes)) { //Use logic here to remove nodes you do not with to scan, i.e. disabled=true etc. _scanChildRecursive(n, level + 1, uid); } } } private void _GetNodeData(ref XmlNode xml, int level, int parentid) { //Logic for removing potentially invalid records from bieng added, i.e. duplicate values, etc. string label = xml.Attributes("label") == null ? xml.Attributes("layer").Value : xml.Attributes("label").Value; uid += 1; _InsertRecord(uid, label, parentid, xml.Attributes("id").Value); } private void _InsertRecord(int uid, string label, int parentid, string l_id) { //Add to records system }
6b548ce7222c9f07d0cc966f4987438376fc9e3d
[ "Markdown", "C#" ]
2
Markdown
ByrenHiggin/VB-C-Code-Snippets
aa349529aefcdcac689fffad64f1bcc09a82939b
54becc966a8c6564a19a8a7bb596a858c03b3adb
refs/heads/master
<file_sep># audioplayer reactnative audioplayer demo ``` npm install --registry=https://registry.npm.taobao.org ``` Xcode open AudioPlayer.xcodeproj run <file_sep>/** * Sample React Native App * https://github.com/facebook/react-native */ 'use strict'; var React = require('react-native'); var { AppRegistry, StyleSheet, Text, View, Image, TextInput, ListView, TouchableHighlight, PixelRatio, ActivityIndicatorIOS, } = React; var AudioPlayerManager = require('./components/AudioPlayerManager'); var BASE_URL = 'http://www.xiami.com/web/search-songs?spm=0.0.0.0.I0JoOx&key=Intro&_xiamitoken=<KEY>'; var AudioPlayer = React.createClass({ componentWillMount: function () { var queryURL = BASE_URL; fetch(queryURL) .then((response) => response.json()) .then((responseData) => { if (responseData) { this.setState({ dataSource: this.state.dataSource.cloneWithRows(responseData) }); } }) .done(); }, getInitialState: function() { return { dataSource: new ListView.DataSource({ rowHasChanged: (row1, row2) => row1 !== row2, }), } }, onPress: function(music) { AudioPlayerManager.play(music); }, renderRow: function(repo: Object) { return ( <TouchableHighlight onPress={ this.onPress.bind(this, repo.src) }> <View> <View style={styles.row}> <Image source={{uri: repo.cover}} style={styles.profpic} /> <View style={styles.textcontainer}> <Text style={styles.title}>{repo.author}</Text> <Text style={styles.subtitle}>{repo.title}</Text> </View> </View> <View style={styles.cellBorder} /> </View> </TouchableHighlight> ); }, render: function() { var content; if (this.state.dataSource.getRowCount() === 0) { content = <View style={ styles.loading }> <Text style={ styles.loadingText }>音乐加载中</Text> <ActivityIndicatorIOS /> </View> } else { content = <ListView ref="listview" style={styles.listview} dataSource={this.state.dataSource} renderRow={this.renderRow} automaticallyAdjustContentInsets={false} keyboardDismissMode="onDrag" keyboardShouldPersistTaps={true} showVerticalScrollIndicator={true} /> } return ( <View style={styles.container}> {content} </View> ); } }); var styles = StyleSheet.create({ container: { flex: 1, backgroundColor: 'white', }, listview: { marginTop: 30, }, row: { alignItems: 'center', backgroundColor: 'white', flexDirection: 'row', padding: 5, }, cellBorder: { backgroundColor: '#F2F2F2', height: 1 / PixelRatio.get(), marginLeft: 4, }, profpic: { width: 50, height: 50, }, title: { fontSize: 20, marginBottom: 8, fontWeight: 'bold', }, subtitle: { fontSize: 16, marginBottom: 8, }, textcontainer: { paddingLeft: 10, }, blanktext: { padding: 10, fontSize: 20, }, loading: { flex: 1, backgroundColor: '#fff', justifyContent: 'center', alignItems: 'center' }, }); AppRegistry.registerComponent('AudioPlayer', () => AudioPlayer);
58826237afcc00a7dcf256b68d858744788a6a89
[ "Markdown", "JavaScript" ]
2
Markdown
LC2010/audioplayer
5f2f200cd61468c693a3a3069441c2b839e4bbe5
81f482173cc100e96e2f74f9351fa2fe2e0f388c
refs/heads/master
<repo_name>Tmac-Jan/parking-alfred-frontend<file_sep>/src/store/mutaions.js import { CHANGE_MOBILE_TAB_ITEM, SELECT_ROLE } from './const-types' const mutations = { [CHANGE_MOBILE_TAB_ITEM]: function(state, payload) { state.tabItemsSelected = payload.tabItemsSelected }, [SELECT_ROLE]: function(state, payload) { state.roleSelected = payload.roleSelected }, getOders(state, orders) { const toDisplayTime = time => { const date = new Date() date.setTime(time) return date.toLocaleString() } let result = orders.data.map(order => ({ carNumber: order.car.carNumber, customerAddress: order.customerAddress, reservationTime: toDisplayTime(order.reservationTime) })) state.grabbingOrders.splice(0) state.grabbingOrders.push(...result) } } export default mutations <file_sep>/src/config/const-values.js export const DEFAULT_MOBILE_BOY_TAB_ITEM = '抢单' export const DEFAULT_MOBILE_CUSTOMER_TAB_ITEM = '预约' export const MOBILE_TAB_ITEM_ORDER = '订单' export const MOBILE_TAB_ITEM_MY_INFO = '用户信息' <file_sep>/src/store/actions.js import {} from './const-types' import axios from '../api/config' const actions = { getOders({ commit }) { axios.get('/orders').then(function(response) { commit('getOders', response.data) }) } } export default actions <file_sep>/src/router/router.js import Vue from 'vue' import VueRouter from 'vue-router' import Login from '../page/Login' import MobileHome from '../page/mobilePage/Home' import WebHome from '../page/webPage/Home' import ParkingBodyOrders from '../page/mobilePage/ParkingBodyOrders' import CreatingOrder from '../page/mobilePage/CreatingOrder' import GrabbingOrder from '../page/mobilePage/GrabbingOrder' import ParkingLotList from '../page/mobilePage/ParkingLotList' import OrderDetails from '../page/mobilePage/ParkingBoyOrderDetails' import CustomerOrders from '../page/mobilePage/CustomerOrders' import CustomerInfo from '../page/mobilePage/CustomerInformation' Vue.use(VueRouter) const routes = [ { path: '/login', name: 'login', component: Login }, { path: '/mobile-home', name: 'mobile-home', component: MobileHome, children: [ { path: '/parking-boy-orders', name: 'parking-boy-orders', component: ParkingBodyOrders }, { path: '/created-order', name: 'created-order', component: CreatingOrder }, { path: '/grabbed-order', name: 'grabbed-order', component: GrabbingOrder }, { path: '/parking-lot', name: 'parking-lot', component: ParkingLotList }, { path: '/order-details', name: 'order-details', component: OrderDetails }, { path: '/customer-orders', name: 'customer-orders', component: CustomerOrders }, { path: '/customer-info', name: 'customer-info', component: CustomerInfo } ] }, { path: '/web-home', name: 'web-home', component: WebHome } ] const router = new VueRouter({ routes }) export default router
47aabf213af3c623cff6a1ed28db794dfafdc71d
[ "JavaScript" ]
4
JavaScript
Tmac-Jan/parking-alfred-frontend
fab1a34d1137bdb142f1ba877d59504bcba3111a
59f3dc07e32eae20b464c30d83edb4e840869d66
refs/heads/master
<file_sep>#ifndef UTIL_INPUT_H_ #define UTIL_INPUT_H_ #include "common.h" namespace util { class Input { public: Input(); ~Input(); void key_pressed(int, int, int); void key_released(int, int, int); void mouse_pressed(int, int); void mouse_released(int, int); bool operator[](int); private: std::map<int, bool> keystate; bool lmb = false, rmb = false; }; } #endif /* UTIL_INPUT_H_ */ <file_sep>#ifndef __VERTEXBUFFER_H #define __VERTEXBUFFER_H #include "common.h" #include "gl_base.h" namespace graphics { namespace gl { class VertexBuffer : public Gl { public: VertexBuffer(GLenum type); ~VertexBuffer(); void bind() const; void unbind() const; template<typename T> void upload(const std::vector<T>&, GLenum usage); unsigned size() const; private: GLenum m_type; unsigned m_size; }; } } #endif /* __VERTEXBUFFER_H */ <file_sep>#include "layer.h" graphics::layers::Layer::Layer(renderer_ptr renderer, program_ptr program) : m_renderer(std::move(renderer)), m_program(program), m_camera((float)WIDTH / (float)HEIGHT) { } graphics::layers::Layer::~Layer() { } void graphics::layers::Layer::add(image_buffer_ptr buffer) { glActiveTexture(GL_TEXTURE0 + this->m_textures.size()); auto texture = std::make_unique<gl::Texture>(GL_TEXTURE_2D); texture->bind(); texture->upload(buffer); this->m_textures.push_back(std::move(texture)); } void graphics::layers::Layer::add(renderable_ptr renderable) { this->m_renderables.push_back(renderable); } void graphics::layers::Layer::render() { this->m_program->use(); this->m_renderer->submit(this->m_renderables); this->m_renderer->draw(this->m_camera); } graphics::Camera& graphics::layers::Layer::camera() { return this->m_camera; } <file_sep>#include "objmodel.h" util::ObjModel::ObjModel(std::string base_path, std::string rel_path) { std::vector<tinyobj::shape_t> shapes; std::vector<tinyobj::material_t> materials; std::string err; if (!tinyobj::LoadObj(shapes, materials, err, (base_path + rel_path).c_str(), base_path.c_str())) throw BaseException("Failed to load obj: " + err); for (auto shape : shapes) { this->m_shapes.push_back(shape); fmt::print(" shape name: {}\n", shape.name); fmt::print(" shape size: {}\n", shape.mesh.positions.size()); } fmt::print("# shapes : {}\n", m_shapes.size()); for (auto material : materials) { Material mat(material, base_path); this->m_materials.push_back(mat); } fmt::print("# materials: {}\n", m_materials.size()); } util::ObjModel::~ObjModel() { } <file_sep>#version 450 core layout(location=0) out vec3 frag_color; in vec2 frag_texcoord; flat in uint frag_texid; uniform sampler2D tex[16]; void main() { frag_color = texture(tex[frag_texid], frag_texcoord).rgb; } <file_sep>#ifndef GL_GL_H_ #define GL_GL_H_ namespace graphics { namespace gl { class Gl { public: virtual ~Gl() {}; const GLuint getId() const { return this->m_id; } GLuint& getId() { return this->m_id; } private: GLuint m_id; }; } } #endif /* GL_GL_H_ */ <file_sep>#ifndef GL_UNIFORM_H_ #define GL_UNIFORM_H_ #include "common.h" namespace graphics { namespace gl { class Uniform { public: Uniform(unsigned program, std::string name, GLenum type, int size); ~Uniform(); void set(glm::mat4&) const; void set(unsigned texture) const; const Uniform& operator[](unsigned idx) const; friend std::ostream& operator<<(std::ostream& os, const Uniform& uniform); std::string name; GLuint location; GLenum type; int size; std::vector<Uniform> uniforms; }; std::ostream& operator<<(std::ostream& os, const Uniform& uniform); } } #endif /* GL_UNIFORM_H_ */ <file_sep>#include "program.h" graphics::gl::Program::Program() { this->getId() = glCreateProgram(); check("Error creating program."); } graphics::gl::Program::~Program() { fmt::print("Destroying program.\n"); glDeleteProgram(this->getId()); check("Error deleting program."); } void graphics::gl::Program::load(Shader& vertex, Shader& fragment) const { this->attach(vertex); this->attach(fragment); this->link(); this->detach(vertex); this->detach(fragment); } void graphics::gl::Program::attach(Shader& shader) const { glAttachShader(this->getId(), shader.getId()); check("Error attaching shader to program."); } void graphics::gl::Program::detach(Shader& shader) const { glDetachShader(this->getId(), shader.getId()); check("Error detaching shader from program."); } void graphics::gl::Program::link() const { int result = 0; int log_size = 0; // Link the program fmt::print("Linking program.\n"); glLinkProgram(this->getId()); // Check the program glGetProgramiv(this->getId(), GL_LINK_STATUS, &result); glGetProgramiv(this->getId(), GL_INFO_LOG_LENGTH, &log_size); glValidateProgram(this->getId()); if (log_size > 1) { std::vector<char> program_log(log_size + 1); glGetProgramInfoLog(this->getId(), log_size, NULL, &program_log.front()); fmt::print("{}\n", program_log[0]); } if (result == GL_FALSE) throw BaseException("Error linking program."); } void graphics::gl::Program::resolve() { int no_uniform = 0; int max_name_size = 0; glGetProgramiv(this->getId(), GL_ACTIVE_UNIFORMS, &no_uniform); glGetProgramiv(this->getId(), GL_ACTIVE_UNIFORM_MAX_LENGTH, &max_name_size); fmt::print("Found {} uniforms.\n", no_uniform); char buf[max_name_size]; for (auto i = 0; i < no_uniform; i++) { int size; GLenum type; glGetActiveUniform(this->getId(), i, max_name_size, NULL, &size, &type, buf); auto name = std::string(buf); Uniform uniform(this->getId(), name, type, size); this->m_uniforms.insert(entry(uniform.name, uniform)); } // FIXME: DEBUG CODE fmt::print("Program uniforms:\n"); for (auto uniform : this->m_uniforms) for (auto entry : uniform.second.uniforms) fmt::print(" ({}, {})\n", uniform.first, entry); } void graphics::gl::Program::use() const { glUseProgram(this->getId()); check("Error using program."); } graphics::gl::Uniform graphics::gl::Program::operator[](std::string uniform) const { return this->m_uniforms.at(uniform); } <file_sep>TARGET=bin mkdir ${TARGET} cd ${TARGET} cmake -G "Eclipse CDT4 - Unix Makefiles" -DCMAKE_CXX_COMPILER_ARG1=-std=c++14 -DCMAKE_BUILD_TYPE=Debug -DCMAKE_ECLIPSE_GENERATE_SOURCE_PROJECT=TRUE -DCMAKE_ECLIPSE_MAKE_ARGUMENTS=-j8 ../src/ <file_sep>#include "uniform.h" std::ostream& graphics::gl::operator<<(std::ostream& os, const Uniform& uniform) { os << "[name: \"" << uniform.name << "\"," << " location: \"" << uniform.location << "\"," << " type: \"" << std::hex << uniform.type << "\"," << " size: \"" << std::dec << uniform.size << "\"]"; return os; } graphics::gl::Uniform::Uniform(unsigned program, std::string name, GLenum type, int size) : name(name.substr(0, name.rfind("[0]"))), type(type), size(size) { location = glGetUniformLocation(program, this->name.c_str()); uniforms.push_back(*this); for (auto i = 1; i < size; i++) { Uniform uniform(program, fmt::format("{}[{}]", this->name, i), type, 1); uniforms.push_back(uniform); } } graphics::gl::Uniform::~Uniform() { } void graphics::gl::Uniform::set(glm::mat4& uniform) const { glUniformMatrix4fv(this->location, 1, GL_FALSE, &uniform[0][0]); check("Error setting glm::mat4 uniform."); } void graphics::gl::Uniform::set(unsigned texture) const { glUniform1i(this->location, texture); check("Error setting texture uniform."); } const graphics::gl::Uniform& graphics::gl::Uniform::operator[](unsigned idx) const { if (idx >= this->size) throw new BaseException("Index out of range"); return uniforms[idx]; } <file_sep># -- msg/CMakeLists.txt # file (GLOB MSG_SOURCES *.cpp) add_library (msg ${MSG_SOURCES}) <file_sep>#ifndef UTIL_FILE_H_ #define UTIL_FILE_H_ #include "common.h" namespace util { class File { public: File(std::string path); ~File(); std::string read(); private: std::ifstream stream; }; } #endif /* UTIL_FILE_H_ */ <file_sep>#ifndef GL_RENDERER_H_ #define GL_RENDERER_H_ #include "gl/gl.h" #include "renderer.h" #include "simplerenderable3d.h" #include "simplerenderer3d.h" namespace graphics { class SimpleRenderer3D : public Renderer { public: SimpleRenderer3D(); ~SimpleRenderer3D(); void submit(std::vector<renderable_ptr>& renderables) override; void draw(Camera &) override; private: std::list<simple_renderable_ptr> m_renderables; }; } #endif /* GL_RENDERER_H_ */ <file_sep>#include "camera.h" #include <glm/gtc/matrix_transform.hpp> #include "msg/movement.h" graphics::Camera::Camera (float aspect_ratio) : m_pos(0, 2, 5), m_dir(0, 0, -1), m_up(0, 1, 0) { this->m_projection = glm::perspective(glm::radians(45.0f), aspect_ratio, 0.1f, 100.0f); } graphics::Camera::~Camera () { } glm::mat4 graphics::Camera::matrix() { this->m_view = glm::lookAt( this->m_pos, this->m_pos + this->m_dir, this->m_up ); return m_projection * m_view; } void graphics::Camera::apply(const Movement * movement) { m_pos += movement->m_movement; } <file_sep># -- graphics/CMakeLists.txt # add_subdirectory (gl) add_subdirectory (layers) file (GLOB GRAPHICS_SOURCES *.cpp) add_library (graphics ${GRAPHICS_SOURCES}) target_link_libraries (graphics layers gl fmt epoxy ${GLFW_LIBRARIES} ${OPENGL_LIBRARIES}) <file_sep>#include "window.h" #include <unistd.h> void key_callback(GLFWwindow* gl_window, int key, int scancode, int action, int mods) { static std::map<int, void (util::Input::*)(int, int, int)> cbmap { std::make_pair(GLFW_PRESS, &util::Input::key_pressed), std::make_pair(GLFW_REPEAT, &util::Input::key_pressed), std::make_pair(GLFW_RELEASE, &util::Input::key_released), }; graphics::Window* window = (graphics::Window*)glfwGetWindowUserPointer(gl_window); (window->input().*cbmap[action])(key, scancode, mods); } void mouse_callback(GLFWwindow* gl_window, int button, int action, int mods) { static std::map<bool, void (util::Input::*)(int, int)> cbmap { std::make_pair(GLFW_PRESS, &util::Input::mouse_pressed), std::make_pair(GLFW_RELEASE, &util::Input::mouse_released), }; graphics::Window* window = (graphics::Window*)glfwGetWindowUserPointer(gl_window); (window->input().*cbmap[action])(button, mods); } graphics::Window::Window() { if (!glfwInit()) throw BaseException("Failed to initialize GLFW"); glfwWindowHint(GLFW_SAMPLES, 4); // 4x antialiasing glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 4); // We want OpenGL 3.3 glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 3); glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE); // We don't want the old OpenGL // Open a window and create its OpenGL context this->p_window = glfwCreateWindow(WIDTH, HEIGHT, "Renderer", NULL, NULL); if (!this->p_window) { glfwTerminate(); throw BaseException("Failed to open GLFW window."); } glfwSetWindowUserPointer(this->p_window, this); glfwSetInputMode(this->p_window, GLFW_STICKY_KEYS, GL_TRUE); glfwSetTime(0.0); glfwSetKeyCallback(this->p_window, &key_callback); glfwSetMouseButtonCallback(this->p_window, &mouse_callback); // glfwSetWindowSizeCallback? } graphics::Window::~Window() { glfwTerminate(); } void graphics::Window::close() { glfwSetWindowShouldClose(this->p_window, true); } bool graphics::Window::should_close() { return glfwWindowShouldClose(this->p_window); } util::Input& graphics::Window::input() { return this->m_input; } void graphics::Window::activate() { glfwMakeContextCurrent(this->p_window); } void graphics::Window::update() { GLenum error = glGetError(); if (error != GL_NO_ERROR) fmt::print("GL error: {}\n", error); glfwPollEvents(); glfwSwapBuffers(this->p_window); } <file_sep>#ifndef __VERTEXARRAY_H #define __VERTEXARRAY_H #include "common.h" #include "gl_base.h" namespace graphics { namespace gl { class VertexArray : public Gl { public: VertexArray(); ~VertexArray(); void bind() const; void unbind() const; void bindattrib(unsigned pos, unsigned elemcount, GLenum type) const; void unbindattrib(unsigned pos) const; unsigned m_size; GLuint texture_idx; private: }; } } #endif /* __VERTEXARRAY_H */ <file_sep>#ifndef __COMMON_H__ #define __COMMON_H__ #define WIDTH 1920 #define HEIGHT 1080 #include <epoxy/gl.h> #include <epoxy/glx.h> #include <fmt/format.h> #include <fmt/printf.h> #include <fmt/ostream.h> #include <glm/glm.hpp> #include <exception> #include <fstream> #include <list> #include <map> #include <memory> #include <string> #include <vector> class BaseException : public std::exception { public: BaseException(std::string msg) : msg(msg) { }; virtual const char* what() const throw() { return this->msg.c_str(); }; private: std::string msg; }; inline void check(std::string msg) { GLenum err = glGetError(); if (err != GL_NO_ERROR) throw BaseException(msg); }; #endif /* __COMMON_H__ */ <file_sep>#ifndef GL_SHADER_H_ #define GL_SHADER_H_ #include "common.h" #include "gl_base.h" namespace graphics { namespace gl { class Shader : public Gl { public: Shader(GLenum type); ~Shader(); void load(std::string text) const; private: void read(std::string path) const; void compile() const; GLenum m_type; }; } } #endif /* GL_SHADER_H_ */ <file_sep>#include "shader.h" graphics::gl::Shader::Shader(GLenum type) : m_type(type) { this->getId() = glCreateShader(type); check("Error creating shader."); } graphics::gl::Shader::~Shader() { fmt::print("Destroying shader.\n"); glDeleteShader(this->getId()); check("Error deleting shader."); } void graphics::gl::Shader::load(std::string text) const { this->read(text); this->compile(); } void graphics::gl::Shader::read(std::string text) const { char const* source = text.c_str(); glShaderSource(this->getId(), 1, &source, NULL); check("Failed to upload file: " + text); } void graphics::gl::Shader::compile() const { int result = 0; int log_size = 0; fmt::print("Compiling shader.\n"); glCompileShader(this->getId()); glGetShaderiv(this->getId(), GL_COMPILE_STATUS, &result); glGetShaderiv(this->getId(), GL_INFO_LOG_LENGTH, &log_size); if (log_size > 1) { std::vector<char> shader_log(log_size + 1); glGetShaderInfoLog(this->getId(), log_size, NULL, &shader_log.front()); fmt::print("Shader log: {}\n", &shader_log.front()); } if (result == GL_FALSE) throw BaseException("Failed to compile shader."); } <file_sep>#ifndef GRAPHICS_RENDERER_H_ #define GRAPHICS_RENDERER_H_ #include "gl/gl.h" #include "camera.h" namespace graphics { class Renderer; class Renderable3D; class SimpleRenderable3D; typedef std::shared_ptr<Renderable3D> renderable_ptr; typedef std::shared_ptr<SimpleRenderable3D> simple_renderable_ptr; typedef std::unique_ptr<Renderer> renderer_ptr; class Renderer { public: virtual ~Renderer() {}; virtual void draw(Camera& camera) = 0; virtual void submit(std::vector<renderable_ptr>& renderables) = 0; private: std::vector<texture_ptr> m_textures; }; } #endif /* GRAPHICS_RENDERER_H_ */ <file_sep>#include "channel.h" class Movement; template Channel<Movement>::Channel(); template Channel<Movement>::~Channel(); template void Channel<Movement>::emit(const Movement*); template void Channel<Movement>::listen(Sink<Movement>*); template<class T> Channel<T>::Channel() { } template<class T> Channel<T>::~Channel () { } template<class T> void Channel<T>::emit(const T * msg) { for (auto sink : this->sinks) { sink->apply(msg); } } template<class T> void Channel<T>::listen(Sink<T>* sink) { sinks.push_back(sink); } <file_sep>#ifndef GL_TEXTURE_H_ #define GL_TEXTURE_H_ #include "common.h" #include "gl_base.h" namespace graphics { namespace gl { typedef struct image_buffer { int w, h; std::vector<unsigned char> data; unsigned size() { return w * h * 3; }; } image_buffer; class Texture : public Gl { public: Texture(GLenum type); ~Texture(); void bind() const; void upload(std::shared_ptr<image_buffer>) const; void unbind() const; private: GLenum m_type; }; } } #endif /* GL_TEXTURE_H_ */ <file_sep>#ifndef GRAPHICS_GL_GL_H_ #define GRAPHICS_GL_GL_H_ #include "common.h" #include "program.h" #include "shader.h" #include "texture.h" #include "uniform.h" #include "vertexarray.h" #include "vertexbuffer.h" typedef std::shared_ptr<graphics::gl::image_buffer> image_buffer_ptr; typedef std::shared_ptr<graphics::gl::Program> program_ptr; typedef std::unique_ptr<graphics::gl::Texture> texture_ptr; #endif /* GRAPHICS_GL_GL_H_ */ <file_sep>#include "simplerenderer3d.h" graphics::SimpleRenderer3D::SimpleRenderer3D() { glEnable(GL_DEPTH_TEST); glDepthFunc(GL_LESS); } graphics::SimpleRenderer3D::~SimpleRenderer3D() { } void graphics::SimpleRenderer3D::submit(std::vector<renderable_ptr>& renderables) { for (auto& renderable : renderables) this->m_renderables.push_back(std::static_pointer_cast<SimpleRenderable3D>(renderable)); } // FIXME: Camera should be const, but camera.matrix() updates stuff. // Might therefore move updating the camera into the main render loop. void graphics::SimpleRenderer3D::draw(graphics::Camera& camera) { auto model = glm::mat4(1.0f); auto mvp = camera.matrix() * model; glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); auto it = this->m_renderables.begin(); while (it != this->m_renderables.end()) { auto& renderable = *it++; auto& program = *(renderable->program()); auto& vao = renderable->vao(); program.use(); program["mvp"].set(mvp); program["tex"][15].set(vao.texture_idx); vao.bind(); glDrawElements( GL_TRIANGLES, // mode vao.m_size, // count GL_UNSIGNED_INT, // type (void*)0 // element array buffer offset ); vao.unbind(); this->m_renderables.pop_front(); } } <file_sep>#ifndef UTIL_MATERIAL_H_ #define UTIL_MATERIAL_H_ #include "common.h" #include "graphics/gl/gl.h" #include "tiny_obj_loader.h" namespace util { enum IMAGE_MAP { AMBIENT, DIFFUSE, SPECULAR, SPECULAR_HIGH, BUMP, DISPLACEMENT, ALPHA, }; typedef std::pair<IMAGE_MAP, std::string> image_path_entry; class Material { public: Material(tinyobj::material_t, std::string = ""); ~Material(); void load(); std::shared_ptr<graphics::gl::image_buffer> get_buffer(IMAGE_MAP) const; private: tinyobj::material_t m_material; std::map<IMAGE_MAP, std::shared_ptr<graphics::gl::image_buffer>> m_buffers; }; } #endif /* UTIL_MATERIAL_H_ */ <file_sep># -- util/CMakeLists.txt # file (GLOB UTIL_SOURCES *.cpp) add_library (util ${UTIL_SOURCES}) target_link_libraries (util fmt freeimage) <file_sep>#include "input.h" util::Input::Input() { } util::Input::~Input() { } void util::Input::key_pressed(int key, int scancode, int modifiers) { this->keystate[key] = true; } void util::Input::key_released(int key, int scancode, int modifiers) { this->keystate[key] = false; } void util::Input::mouse_pressed(int button, int modifiers) { } void util::Input::mouse_released(int button, int modifiers) { } bool util::Input::operator[](int key) { return this->keystate[key]; } <file_sep>#ifndef GRAPHICS_LAYER_H_ #define GRAPHICS_LAYER_H_ #include "graphics/gl/gl.h" #include "graphics/camera.h" #include "graphics/renderer.h" namespace graphics { namespace layers { class Layer { public: Layer(renderer_ptr renderer, program_ptr program); virtual ~Layer(); void add(image_buffer_ptr buffer); void add(renderable_ptr renderable); void render(); Camera& camera(); private: std::vector<renderable_ptr> m_renderables; std::vector<texture_ptr> m_textures; renderer_ptr m_renderer; program_ptr m_program; Camera m_camera; }; } } #endif /* GRAPHICS_LAYER_H_ */ <file_sep>#include "simplerenderable3d.h" graphics::SimpleRenderable3D::SimpleRenderable3D(program_ptr& program, tinyobj::shape_t& shape, glm::vec3 pos) : Renderable3D(pos), m_program(program), m_vao(), m_vbo(GL_ARRAY_BUFFER), m_uv(GL_ARRAY_BUFFER), m_ibo(GL_ELEMENT_ARRAY_BUFFER) { m_vao.bind(); m_vbo.bind(); m_vbo.upload<float>(shape.mesh.positions, GL_STATIC_DRAW); m_vao.bindattrib(0, 3, GL_FLOAT); m_uv.bind(); m_uv.upload<float>(shape.mesh.texcoords, GL_STATIC_DRAW); m_vao.bindattrib(1, 2, GL_FLOAT); m_ibo.bind(); m_ibo.upload<unsigned>(shape.mesh.indices, GL_STATIC_DRAW); // FIXME: These attributes should not be part of the vao. // Might consider mirroring opengl vbo binding state though. m_vao.m_size = m_ibo.size(); m_vao.texture_idx = shape.mesh.material_ids.front(); m_vao.unbind(); m_vbo.unbind(); m_uv.unbind(); m_ibo.unbind(); } graphics::SimpleRenderable3D::~SimpleRenderable3D() { } std::shared_ptr<graphics::gl::Program>& graphics::SimpleRenderable3D::program() { return this->m_program; } graphics::gl::VertexArray& graphics::SimpleRenderable3D::vao() { return this->m_vao; } <file_sep>#ifndef CHANNEL_H_ #define CHANNEL_H_ #include "common.h" template<class T> class Sink { public: virtual ~Sink() {}; virtual void apply(const T*) = 0; }; template <class T> class Channel { public: Channel(); ~Channel(); void emit(const T*); void listen(Sink<T> *); private: std::vector<Sink<T>*> sinks; }; #endif /* CHANNEL_H_ */ <file_sep>#version 450 core layout(location = 0) in vec3 vert_pos; layout(location = 1) in vec2 vert_texcoord; layout(location = 2) in uint vert_texid; out vec2 frag_texcoord; out uint frag_texid; uniform mat4 mvp; uniform sampler2D tex[16]; void main() { frag_texcoord = vert_texcoord; frag_texid = 15; gl_Position = mvp * vec4(vert_pos, 1); } <file_sep>#include "vertexbuffer.h" template void graphics::gl::VertexBuffer::upload<float>(const std::vector<float>&, GLenum); template void graphics::gl::VertexBuffer::upload<unsigned>(const std::vector<unsigned>&, GLenum); graphics::gl::VertexBuffer::VertexBuffer(GLenum type) : m_type(type), m_size(0) { glGenBuffers(1, &this->getId()); check("Error creating vertex buffer."); } graphics::gl::VertexBuffer::~VertexBuffer() { fmt::print("Destroying vbo.\n"); glDeleteBuffers(1, &this->getId()); check("Error deleting vertex buffer."); } void graphics::gl::VertexBuffer::bind() const { glBindBuffer(this->m_type, this->getId()); check("Error binding vertex buffer."); } void graphics::gl::VertexBuffer::unbind() const { glBindBuffer(this->m_type, 0); check("Error unbinding vertex buffers."); } template<typename T> void graphics::gl::VertexBuffer::upload(const std::vector<T>& data, GLenum usage) { this->m_size = data.size(); glBufferData(this->m_type, sizeof(T) * data.size(), &data.front(), usage); check("Error uploading to vertex buffer."); } unsigned graphics::gl::VertexBuffer::size() const { return this->m_size; } <file_sep># -- graphics/gl/CMakeLists.txt # file (GLOB GL_SOURCES *.cpp) add_library (gl ${GL_SOURCES}) <file_sep># -- CMakeLists.txt # cmake_minimum_required (VERSION 2.6) project (renderer) add_definitions(-std=c++14 -g) find_package (OpenGL REQUIRED) find_package (PkgConfig REQUIRED) pkg_search_module (GLFW REQUIRED glfw3) # Please note the following implicit dependencies: # - epoxy (src/gl/CMakeLists.txt) # - freeimage (src/gl/CMakeLists.txt) include_directories (external/format) add_subdirectory (external/format) include_directories (external/tinyobjloader) add_subdirectory (external/tinyobjloader) include_directories (${PROJECT_SOURCE_DIR}) add_subdirectory (msg) add_subdirectory (graphics) add_subdirectory (util) file (GLOB SOURCES *.cpp) add_executable (renderer ${SOURCES}) target_link_libraries (renderer graphics msg util tinyobjloader) <file_sep>#include "renderable3d.h" graphics::Renderable3D::Renderable3D(glm::vec3 pos) : m_pos(pos) { } graphics::Renderable3D::~Renderable3D() { } <file_sep>#include "vertexarray.h" graphics::gl::VertexArray::VertexArray() : m_size(0), texture_idx(0) { glGenVertexArrays(1, &this->getId()); check("Error creating vertexarray."); } graphics::gl::VertexArray::~VertexArray() { fmt::print("Destroying vao.\n"); glDeleteVertexArrays(1, &this->getId()); check("Error deleting vertexarray."); } void graphics::gl::VertexArray::bind() const { glBindVertexArray(this->getId()); check("Error binding vertexarray."); } void graphics::gl::VertexArray::unbind() const { glBindVertexArray(0); check("Error unbinding vertexarrays."); } void graphics::gl::VertexArray::bindattrib(unsigned pos, unsigned elemcount, GLenum type) const { glEnableVertexAttribArray(pos); glVertexAttribPointer( pos, // attribute 0 elemcount, // size type, // type GL_FALSE, // normalized? 0, // stride (void*)0 // array buffer offset ); check("Error binding vertexarray attrib."); } void graphics::gl::VertexArray::unbindattrib(unsigned pos) const { glDisableVertexAttribArray(pos); check("Error unbinding attribs[" + std::to_string(pos) + "]."); } <file_sep>#ifndef GRAPHICS_RENDERABLE3D_H_ #define GRAPHICS_RENDERABLE3D_H_ #include "gl/gl.h" namespace graphics { class Renderable3D { public: Renderable3D(glm::vec3 pos = glm::vec3(0)); virtual ~Renderable3D(); private: glm::vec3 m_pos; }; } #endif /* GRAPHICS_RENDERABLE3D_H_ */ <file_sep>#ifndef MOVEMENT_H_ #define MOVEMENT_H_ #include "common.h" class Movement { public: Movement(glm::vec3 movement) : m_movement(movement) {}; ~Movement() {}; glm::vec3 m_movement; }; const Movement FORWARD = Movement(glm::vec3(0, 0, -.1)); const Movement BACKWARD = Movement(glm::vec3(0, 0, .1)); const Movement LEFT = Movement(glm::vec3(-.1, 0, 0)); const Movement RIGHT = Movement(glm::vec3( .1, 0, 0)); #endif /* MOVEMENT_H_ */ <file_sep># Renderer This is a hobby project of mine aimed at learning OpenGL. A first screenshot: ![](/screenshots/altair_basic.png?raw=true) <file_sep>#ifndef OBJMODEL_H_ #define OBJMODEL_H_ #include "common.h" #include "material.h" #include "tiny_obj_loader.h" namespace util { class ObjModel { public: ObjModel(std::string, std::string); ~ObjModel(); std::vector<tinyobj::shape_t> m_shapes; std::vector<Material> m_materials; }; } #endif /* OBJMODEL_H_ */ <file_sep>#ifndef __PROGRAM_H #define __PROGRAM_H #include "common.h" #include "gl_base.h" #include "shader.h" #include "uniform.h" namespace graphics { namespace gl { typedef std::pair<std::string, Uniform> entry; class Program : public Gl { public: Program(); ~Program(); void load(Shader&, Shader&) const; void resolve(); void use() const; Uniform operator[](std::string) const; private: void attach(Shader&) const; void detach(Shader&) const; void link() const; std::map<std::string, Uniform> m_uniforms; }; } } #endif /* __PROGRAM_H */ <file_sep>#include "texture.h" graphics::gl::Texture::Texture(GLenum type) : m_type(type) { glGenTextures(1, &this->getId()); check("Error creating texture."); } graphics::gl::Texture::~Texture() { fmt::print("Destroying texture.\n"); glDeleteTextures(1, &this->getId()); check("Error deleting texture."); } void graphics::gl::Texture::bind() const { glBindTexture(this->m_type, this->getId()); check("Error binding texture."); } void graphics::gl::Texture::unbind() const { glBindTexture(this->m_type, 0); check("Error unbinding textures."); } void graphics::gl::Texture::upload(std::shared_ptr<image_buffer> img) const { fmt::print("Loaded texture. Dimensions: ({}, {})\n", img->w, img->h); glTexImage2D( this->m_type, // GL_TEXTURE_2D 0, // mipmap level GL_RGB, // internal format img->w, img->h, 0,// width, height, border GL_BGR, // format GL_UNSIGNED_BYTE, // data type img->data.data() ); glTexParameteri(this->m_type, GL_TEXTURE_MAG_FILTER, GL_NEAREST); glTexParameteri(this->m_type, GL_TEXTURE_MIN_FILTER, GL_NEAREST); check("Error uploading texture."); } <file_sep>#include "file.h" util::File::File(std::string path) : stream(path, std::ios::in) { if(!this->stream.is_open()) throw BaseException("Failed to open file: " + path); } util::File::~File() { if (this->stream.is_open()) this->stream.close(); } std::string util::File::read() { std::string text; std::string line = ""; while(getline(this->stream, line)) { text += "\n" + line; } return text; } <file_sep>#ifndef GRAPHICS_SIMPLERENDERABLE3D_H_ #define GRAPHICS_SIMPLERENDERABLE3D_H_ #include "gl/gl.h" #include "renderable3d.h" #include "tiny_obj_loader.h" namespace graphics { class SimpleRenderable3D : public Renderable3D { public: SimpleRenderable3D(program_ptr& program, tinyobj::shape_t& shape, glm::vec3 pos = glm::vec3(0)); virtual ~SimpleRenderable3D(); std::shared_ptr<gl::Program>& program(); gl::VertexArray& vao(); private: std::shared_ptr<gl::Program> m_program; gl::VertexArray m_vao; gl::VertexBuffer m_vbo; gl::VertexBuffer m_uv; gl::VertexBuffer m_ibo; }; } #endif /* GRAPHICS_SIMPLERENDERABLE3D_H_ */ <file_sep>#include "material.h" #include <FreeImage.h> std::vector<util::image_path_entry> image_paths(tinyobj::material_t material) { using namespace util; return std::vector<image_path_entry>({ image_path_entry(AMBIENT, material.ambient_texname), image_path_entry(DIFFUSE, material.diffuse_texname), image_path_entry(SPECULAR, material.specular_texname), image_path_entry(SPECULAR_HIGH, material.specular_highlight_texname), image_path_entry(BUMP, material.bump_texname), image_path_entry(DISPLACEMENT, material.displacement_texname), image_path_entry(ALPHA, material.alpha_texname), }); } std::shared_ptr<graphics::gl::image_buffer> load_img(std::string path) { FREE_IMAGE_FORMAT format = FreeImage_GetFileType(path.c_str()); FIBITMAP* img = FreeImage_Load(format, path.c_str()); if (!img || format == FIF_UNKNOWN) throw BaseException("Error loading material file: " + path); std::shared_ptr<graphics::gl::image_buffer> buf(new graphics::gl::image_buffer); buf->w = FreeImage_GetWidth(img); buf->h = FreeImage_GetHeight(img); buf->data = std::vector<unsigned char>(buf->size()); FreeImage_ConvertToRawBits(buf->data.data(), img, buf->w * 3, 24, 0, 0, 0); FreeImage_Unload(img); return buf; } util::Material::Material(tinyobj::material_t material, std::string base_path) : m_material(material) { fmt::print(" mat name: {}\n", this->m_material.name); for (auto image_path : image_paths(this->m_material)) { if (image_path.second.size() == 0) continue; std::string path = base_path + image_path.second; this->m_buffers[image_path.first] = load_img(path); fmt::print(" mat path: {}\n", path); } } util::Material::~Material() { } std::shared_ptr<graphics::gl::image_buffer> util::Material::get_buffer(IMAGE_MAP tex) const { return this->m_buffers.at(tex); } <file_sep># -- graphics/layers/CMakeLists.txt # file (GLOB LAYERS_SOURCES *.cpp) add_library (layers ${LAYERS_SOURCES}) <file_sep>#ifndef CAMERA_H_ #define CAMERA_H_ #include "common.h" #include "msg/channel.h" class Movement; namespace graphics { class Camera : public Sink<Movement> { public: Camera(float aspect_ratio); ~Camera(); glm::mat4 matrix(); void apply(const Movement *); private: glm::vec3 m_pos; glm::vec3 m_dir; glm::vec3 m_up; glm::mat4 m_projection; glm::mat4 m_view; }; } #endif /* CAMERA_H_ */ <file_sep>#include <chrono> #include <iostream> #include <thread> #include "common.h" #include "graphics/layers/layer.h" #include "graphics/window.h" #include "msg/channel.h" #include "msg/movement.h" #include "util/file.h" #include "util/objmodel.h" using namespace graphics; int main(int argc, char** argv) { Channel<Movement> channel; graphics::Window window; window.activate(); util::ObjModel model("../Desmond_Miles/", "Desmond_Miles.obj"); gl::Shader vertexshader(GL_VERTEX_SHADER); gl::Shader fragmentshader(GL_FRAGMENT_SHADER); vertexshader.load(util::File("../src/shaders/shader.vertex.c").read()); fragmentshader.load(util::File("../src/shaders/shader.fragment.c").read()); auto program = std::make_shared<gl::Program>(); program->load(vertexshader, fragmentshader); program->resolve(); graphics::layers::Layer layer(std::make_unique<SimpleRenderer3D>(), program); for (auto& material : model.m_materials) layer.add(material.get_buffer(util::IMAGE_MAP::DIFFUSE)); for (auto& shape : model.m_shapes) layer.add(std::make_shared<SimpleRenderable3D>(program, shape)); channel.listen(&layer.camera()); do { double frame_end = glfwGetTime() + 1.0 / 60.0; if (window.input()[GLFW_KEY_A]) channel.emit(&LEFT); if (window.input()[GLFW_KEY_D]) channel.emit(&RIGHT); if (window.input()[GLFW_KEY_W]) channel.emit(&FORWARD); if (window.input()[GLFW_KEY_S]) channel.emit(&BACKWARD); if (window.input()[GLFW_KEY_ESCAPE]) window.close(); double start = glfwGetTime(); window.activate(); layer.render(); window.update(); double end = glfwGetTime(); printf("Frame draw took %f ms.\r", (end - start) * 1e3); std::flush(std::cout); unsigned ns = std::max(0., (frame_end - glfwGetTime()) * 1e9); std::this_thread::sleep_for(std::chrono::nanoseconds(ns)); } while (!window.should_close()); return EXIT_SUCCESS; } <file_sep>#ifndef __WINDOW_H #define __WINDOW_H #include "common.h" #include <GLFW/glfw3.h> #include "util/input.h" #include "camera.h" #include "simplerenderer3d.h" namespace graphics { class Window { public: Window(); ~Window(); void close(); bool should_close(); util::Input& input(); void activate(); void update(); private: GLFWwindow* p_window; util::Input m_input; }; } #endif /* __WINDOW_H */
7425e9f2383c8bb255897e1232b74254e5bc800f
[ "CMake", "Markdown", "C", "C++", "Shell" ]
50
C++
gfokkema/renderer
fe1ee84d0a54d100df63034691438115822153df
bff44a0c191e7ff78613107df1c1c5c5f958d4eb
refs/heads/master
<file_sep>package Pamyat; public class Something { int x; int y; } class Something2 { public static void main() { Something n1=new Something(); n1.x=0; n1.y=0; Something n2=n1; n2.x=1; n2.x=1; System.out.println(n1); System.out.println(n2); } } <file_sep>package RGBgray; import javax.imageio.ImageIO; import javax.swing.*; import javax.swing.filechooser.FileFilter; import java.awt.*; import java.awt.event.ActionEvent; import java.awt.event.ComponentAdapter; import java.awt.event.ComponentListener; import java.awt.image.BufferedImage; import java.io.File; import java.io.IOException; import static RGBgray.MainWin.d3; import static RGBgray.MainWin.imag; public class GrayWin { static MyFrame f1; static MyPanel pic1; boolean loading=false; String fileName; public GrayWin() { f1=new MyFrame("RGB to Gray"); f1.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); f1.setSize(imag.getWidth(),imag.getHeight()); JMenuBar menuBar = new JMenuBar(); f1.setJMenuBar(menuBar); JMenu fileMenu = new JMenu("Файл"); menuBar.add(fileMenu); final BufferedImage[] buff = {new BufferedImage(d3.getWidth(), d3.getHeight(), BufferedImage.TYPE_BYTE_GRAY)}; Action saveasAction = new AbstractAction("Сохранить как...") { public void actionPerformed(ActionEvent event) { try { JFileChooser jf= new JFileChooser(); TextFileFilter pngFilter = new TextFileFilter(".png"); TextFileFilter jpgFilter = new TextFileFilter(".jpg"); jf.addChoosableFileFilter(pngFilter); jf.addChoosableFileFilter(jpgFilter); int result = jf.showSaveDialog(null); if(result==JFileChooser.APPROVE_OPTION) { fileName = jf.getSelectedFile().getAbsolutePath(); } if(jf.getFileFilter()==pngFilter) { ImageIO.write(d3, "png", new File(fileName+".png")); } else { ImageIO.write(d3, "jpeg", new File(fileName+".jpg")); } } catch(IOException ex) { JOptionPane.showMessageDialog(f1, "Ошибка ввода-вывода"); } } }; JMenuItem saveasMenu = new JMenuItem(saveasAction); fileMenu.add(saveasMenu); pic1 = new MyPanel(); pic1.setBounds(30,0,260,260); pic1.setOpaque(true); f1.add(pic1); f1.addComponentListener(new ComponentAdapter() { public void componentResized(java.awt.event.ComponentEvent evt) { if(loading==false) { BufferedImage tempImage = new BufferedImage(imag.getWidth(), imag.getHeight(), BufferedImage.TYPE_BYTE_GRAY); pic1.setSize(f1.getWidth(), f1.getHeight()); Graphics2D out = (Graphics2D) tempImage.getGraphics(); out.drawImage(d3, 0,0, null); d3=tempImage; buff[0] =tempImage; pic1.repaint(); } loading=false; } }); f1.setLayout(null); f1.setVisible(true); } public static void main(String[] args) { SwingUtilities.invokeLater(new Runnable() { public void run() { new GrayWin(); } }); } class MyFrame extends JFrame { public void paint(Graphics g) { super.paint(g); } public MyFrame(String title) { super(title); } } class MyPanel extends JPanel { public MyPanel() { } public void paintComponent (Graphics g) { if(imag==null) { imag = new BufferedImage(this.getWidth(), this.getHeight(), BufferedImage.TYPE_INT_RGB); Graphics2D d2 = (Graphics2D) imag.createGraphics(); d2.setColor(Color.white); d2.fillRect(0, 0, this.getWidth(), this.getHeight()); } super.paintComponent(g); BufferedImage tempImage =new BufferedImage(d3.getWidth(),d3.getHeight(),BufferedImage.TYPE_BYTE_GRAY); Graphics2D out = (Graphics2D) tempImage.getGraphics(); out.drawImage(d3, 0,0, null); d3=tempImage; g.drawImage(tempImage, 0, 0,this); } } class TextFileFilter extends FileFilter { private String ext; public TextFileFilter(String ext) { this.ext=ext; } public boolean accept(java.io.File file) { if (file.isDirectory()) return true; return (file.getName().endsWith(ext)); } public String getDescription() { return "*"+ext; } } }<file_sep>package PloshadKruga; import java.util.*; public class Okruzhnost { public static void main(String[] args) { double cq; Scanner vd = new Scanner(System.in); System.out.print("Введите длинну окружности C="); cq=vd.nextDouble(); double x; x=2*cq*Math.PI; System.out.print("Площадь круга="); System.out.print(x); } } <file_sep>package RGBgray; import javax.imageio.ImageIO; import java.awt.event.ComponentEvent; import java.awt.image.RescaleOp; import java.lang.String; import javax.swing.*; import javax.swing.event.ChangeEvent; import javax.swing.event.ChangeListener; import javax.swing.filechooser.FileFilter; import java.awt.*; import java.awt.event.ActionEvent; import java.awt.event.ComponentAdapter; import java.awt.image.BufferedImage; import java.io.File; import java.io.FileNotFoundException; import java.io.IOException; public class MainWin extends JFrame{ static MyFrame f; MyPanel pic; static BufferedImage imag; boolean loading = false; String fileName; MyPanel pan; float br; static BufferedImage d3; public MainWin() { f = new MyFrame("Выберите изображение"); f.setSize(480, 480); JMenuBar menuBar = new JMenuBar(); f.setJMenuBar(menuBar); menuBar.setBounds(0,0,350,30); f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); JToolBar toolbar = new JToolBar("Toolbar", JToolBar.VERTICAL); toolbar.setBounds(0, 0, 30, 300); f.add(toolbar); JSlider bright = new JSlider(JSlider.VERTICAL,1,200,100); toolbar.add(bright); ChangeListener listener = new ChangeListener() { public void stateChanged(ChangeEvent event) { JSlider bright = (JSlider) event.getSource(); event.getSource(); br=bright.getValue(); pic.repaint(); GrayWin.pic1.repaint(); } }; bright.addChangeListener(listener); JMenu fileMenu = new JMenu("Файл"); menuBar.add(fileMenu); Action loadAction = new AbstractAction("Загрузить") { public void actionPerformed(ActionEvent event) { JFileChooser jf = new JFileChooser(); int result = jf.showOpenDialog(null); if (result == JFileChooser.APPROVE_OPTION) { try { fileName = jf.getSelectedFile().getAbsolutePath(); File iF = new File(fileName); jf.addChoosableFileFilter(new TextFileFilter(".png")); jf.addChoosableFileFilter(new TextFileFilter(".jpg")); imag = ImageIO.read(iF); loading = true; f.setSize(imag.getWidth(), imag.getWidth()); pic.setSize(imag.getWidth(), imag.getWidth()); pic.repaint(); } catch (FileNotFoundException ex) { JOptionPane.showMessageDialog(f, "Такого файла не существует"); } catch (IOException ex) { JOptionPane.showMessageDialog(f, "Исключение ввода-вывода"); } catch (Exception ex) { } } } }; JMenuItem loadMenu = new JMenuItem(loadAction); fileMenu.add(loadMenu); Action grayAction = new AbstractAction("Сделать чернобелым") { public void actionPerformed(ActionEvent event) { if(true) { new GrayWin(); } } }; JMenuItem grayMenu = new JMenuItem(grayAction); fileMenu.add(grayMenu); Action saveasAction = new AbstractAction("Сохранить как...") { public void actionPerformed(ActionEvent event) { try { JFileChooser jf = new JFileChooser(); TextFileFilter pngFilter = new TextFileFilter(".png"); TextFileFilter jpgFilter = new TextFileFilter(".jpg"); jf.addChoosableFileFilter(pngFilter); jf.addChoosableFileFilter(jpgFilter); int result = jf.showSaveDialog(null); if (result == JFileChooser.APPROVE_OPTION) { fileName = jf.getSelectedFile().getAbsolutePath(); } // Смотрим какой фильтр выбран if (jf.getFileFilter() == pngFilter) { ImageIO.write(imag, "png", new File(fileName + ".png")); } else { ImageIO.write(imag, "jpeg", new File(fileName + ".jpg")); } } catch (IOException ex) { JOptionPane.showMessageDialog(f, "Ошибка ввода-вывода"); } } }; JMenuItem saveasMenu = new JMenuItem(saveasAction); fileMenu.add(saveasMenu); pic = new MyPanel(); pic.setBackground(Color.white); pic.setBounds(30,30,260,260); pic.setOpaque(true); f.add(pic); f.addComponentListener(new ComponentAdapter() { public void componentResized(ComponentEvent evt) { if (loading == false) { pic.setSize(f.getWidth(), f.getHeight()); BufferedImage tempImage = new BufferedImage(pic.getWidth(), pic.getHeight(), BufferedImage.TYPE_INT_RGB); Graphics2D d2 = (Graphics2D) tempImage.createGraphics(); d2.setColor(Color.white); d2.fillRect(0, 0, pic.getWidth(), pic.getHeight()); tempImage.setData(imag.getRaster()); imag = tempImage; pic.repaint(); } loading = false; } }); f.setLayout(null); f.setVisible(true); } public static void main(String[] args) { SwingUtilities.invokeLater(new Runnable() { public void run() { new MainWin(); } }); } class MyFrame extends JFrame { public void paint(Graphics g) { super.paint(g); } public MyFrame(String title) { super(title); } } class MyPanel extends JPanel { public MyPanel() { } public void paintComponent(Graphics g) { if (imag == null) { imag = new BufferedImage(this.getWidth(), this.getHeight(), BufferedImage.TYPE_INT_RGB); Graphics2D d2 = (Graphics2D) imag.createGraphics(); d2.setColor(Color.white); d2.fillRect(0, 0, this.getWidth(), this.getHeight()); } super.paintComponent(g); float x =br/100; RescaleOp rop = new RescaleOp(x, 0, null); d3 = rop.filter(imag, null); g.drawImage(d3, 0, 0, this); } } // Фильтр картинок class TextFileFilter extends FileFilter { private String ext; public TextFileFilter(String ext) { this.ext = ext; } public boolean accept(java.io.File file) { if (file.isDirectory()) return true; return (file.getName().endsWith(ext)); } public String getDescription() { return "*" + ext; } } } <file_sep>package RGBtoGRAY; import javax.swing.*; import java.awt.*; import java.awt.image.BufferedImage; public class Gray { static RGBtoGRAY.Gray.GrayFrame f; // поверхность рисования BufferedImage grey; public Gray() { f = new RGBtoGRAY.Gray.GrayFrame("RGB to Gray"); f.setSize(480, 480); f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); JMenuBar menuBar = new JMenuBar(); f.setJMenuBar(menuBar); JMenu fileMenu = new JMenu("Файл"); menuBar.add(fileMenu); f.setVisible(true); } class GrayFrame extends JFrame { public void paint(Graphics g) { super.paint(g); } public GrayFrame(String title) { super(title); } } class GrayPanel extends JPanel { public GrayPanel() { } public void paintComponent(Graphics g) { grey = new BufferedImage(this.getWidth(), this.getHeight(), BufferedImage.TYPE_BYTE_GRAY); Graphics2D out = (Graphics2D) grey.getGraphics(); out.drawImage(grey, 0,0, null); } } }<file_sep>package RGBtoGRAY; import javax.imageio.ImageIO; import java.awt.*; import java.awt.image.BufferedImage; import java.io.File; import java.io.IOException; public class Test { public static void main(String[] args) throws IOException { BufferedImage img=ImageIO.read(new File( "C:\\Users\\ximik\\Pictures\\Saved Pictures\\unnamed.png")); BufferedImage grey = new BufferedImage(img.getWidth(), img.getHeight(), BufferedImage.TYPE_BYTE_GRAY); Graphics2D out = (Graphics2D) grey.getGraphics(); out.drawImage(img, 0,0, null); File output = new File("C:\\Users\\ximik\\Pictures\\Saved Pictures\\Greyunnamed.png"); ImageIO.write(grey, "png", output); } }
3c81b3d543924806815486bd8b213c2aa93f4745
[ "Java" ]
6
Java
ximik53/Tasks
a2c87cc0fe7342ea467c51a9f8160c1373f48ad5
369b5e093ea33048b119374e39cb06a3f6475fd0
refs/heads/master
<repo_name>kaileeagray/oo-tic-tac-toe-v-000<file_sep>/lib/tic_tac_toe.rb class TicTacToe WIN_COMBINATIONS = [ [0,1,2], [3,4,5], [6,7,8], [0,3,6], [1,4,7], [2,5,8], [0,4,8], [6,4,2] ] def initialize(board = nil) @board = board || Array.new(9, " ") end def move(location, current_player) @board[location.to_i-1] = current_player end def current_player turn_count % 2 == 0 ? "X" : "O" end def turn_count @board.count{|token| token == "X" || token == "O"} end def display_board puts " #{@board[0]} | #{@board[1]} | #{@board[2]} " puts "-----------" puts " #{@board[3]} | #{@board[4]} | #{@board[5]} " puts "-----------" puts " #{@board[6]} | #{@board[7]} | #{@board[8]} " end def position_taken?(position) !(@board[position].nil? || @board[position] == " ") end def won? wincomb = [] WIN_COMBINATIONS.each do |comb| (@board[comb[0]] == "X" && @board[comb[1]] == "X" && @board[comb[2]] == "X") || (@board[comb[0]] == "O" && @board[comb[1]] == "O" && @board[comb[2]] == "O") ? wincomb.push(true) : wincomb.push(false) end if wincomb.include?(true) WIN_COMBINATIONS[wincomb.index(true)] else false end end def full? @board.count("X") + @board.count("O") == 9 ? true : false end def draw? if won? false elsif !full? false else true end end def over? if draw? || won? true else false end end def winner if won? loc = won?[0] return @board[loc] else nil end end def valid_move?(position) position.to_i.between?(1,9) && !position_taken?(position.to_i-1) end def turn puts "Please enter 1-9:" input = gets.strip if valid_move?(input) move(input, current_player) else turn end display_board end def play until over? turn end if winner != nil puts "Congratulations #{winner}!" else draw? puts "Cats Game!" end end end
6f7d0a91f26f9cf879c73afa8a40a32cab0c70b0
[ "Ruby" ]
1
Ruby
kaileeagray/oo-tic-tac-toe-v-000
ae479509bcd5eaf6a99b02619c41d363ab2ccae4
6ede18b321cb68715011460bdb7bbdf95b5f00ac
refs/heads/master
<file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Linq.Expressions; using WorkShop.Models; namespace WorkShop.Web.ViewModels { public class SkillViewModel { public static Expression<Func<UserSkill, SkillViewModel>> ViewModel { get { return x => new SkillViewModel { Id = x.Id, Name = x.Skill.Name, Endorsments = x.Endorsments.Count, Endorcers = x.Endorsments.Select(e => e.User.UserName) }; } } public int Id { get; set; } public string Name { get; set; } public int Endorsments { get; set; } public IEnumerable<string> Endorcers { get; set; } } } <file_sep>ASP.NET-MVC =========== - ASP.NET-MVC SoftUni Howmeorks - ASP.NET-MVC SoftUni WorkShop <file_sep>using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.Linq; using System.Text; using System.Threading.Tasks; namespace WorkShop.Models { public class AdministrationLog { [Key] public long Id { get; set; } [Required] public string UserId { get; set; } public virtual User User { get; set; } public string IpAddress { get; set; } public string RequestType { get; set; } public string Url { get; set; } public string PostParams { get; set; } } } <file_sep>using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.Linq; using System.Text; using System.Threading.Tasks; namespace WorkShop.Models { public class UserSkill { public int Id { get; set; } [Required] public string UserId { get; set; } public virtual User User { get; set; } public int SkillId { get; set; } public virtual Skill Skill { get; set; } public virtual ICollection<Endorsment> Endorsments { get; set; } } } <file_sep>using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations.Schema; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Twitter.Model { public class Tweet { private ICollection<ApplicationUser> usersFavouriteList; private ICollection<Tweet> tweetRepliesList; public Tweet() { this.UsersFavouriteList = new HashSet<ApplicationUser>(); this.TweetRepliesList = new HashSet<Tweet>(); } [Key] public int Id { get; set; } public string Title { get; set; } public string Text { get; set; } public string URL { get; set; } public DateTime Date { get; set; } public int AuthorId { get; set; } [ForeignKey("AuthorId")] public virtual ApplicationUser Author { get; set; } public virtual ICollection<ApplicationUser> UsersFavouriteList { get { return this.usersFavouriteList; } set { this.usersFavouriteList = value; } } public virtual ICollection<Tweet> TweetRepliesList { get { return this.tweetRepliesList; } set { this.tweetRepliesList = value; } } } } <file_sep>namespace WorkShop.Web.Controllers { using System.Web.Mvc; using WorkShop.Data.UnitOfWork; using System.Web.Mvc.Expressions; public class HomeController : BaseController { public HomeController(IWorkShopData data) : base(data) { } public ActionResult Index() { return this.View(); } public ActionResult About() { ViewBag.Message = "Your application description page."; return this.View(); } public ActionResult Contact() { ViewBag.Message = "Your contact page."; return this.View(); } } }<file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Twitter.Data.Repository; using Twitter.Model; namespace Twitter.Data.UnitOfWork { public interface ITwitterUnitOfWork { IRepository<ApplicationUser> Users { get; } IRepository<Tweet> Tweets { get; } IRepository<Profile> Profiles { get; } IRepository<Notification> Notifications { get; } IRepository<Message> Messages { get; } void SaveChanges(); } } <file_sep>using System; using System.Collections.Generic; using System.Data.Entity; using Microsoft.AspNet.Identity; using Microsoft.AspNet.Identity.EntityFramework; using WorkShop.Data.Repositories; using WorkShop.Models; namespace WorkShop.Data.UnitOfWork { public class WorkShopData : IWorkShopData { private readonly IWorkShopDbContext dbContext; private readonly IDictionary<Type, object> repositories; public WorkShopData(IWorkShopDbContext dbContext) { this.dbContext = dbContext; this.repositories = new Dictionary<Type, object>(); } public IRepository<User> Users { get { return this.GetRepository<User>(); } } public IRepository<Certification> Certifications { get { return this.GetRepository<Certification>(); } } public IRepository<Discussion> Discussions { get { return this.GetRepository<Discussion>(); } } public IRepository<Experience> Experiences { get { return this.GetRepository<Experience>(); } } public IRepository<Group> Groups { get { return this.GetRepository<Group>(); } } public IRepository<Project> Projects { get { return this.GetRepository<Project>(); } } public IRepository<Skill> Skills { get { return this.GetRepository<Skill>(); } } public IRepository<Endorsment> Endorsments { get { return this.GetRepository<Endorsment>(); } } public IRepository<AdministrationLog> AdministrationLogs { get { return this.GetRepository<AdministrationLog>(); } } public int SaveChanges() { return this.dbContext.SaveChanges(); } private IRepository<T> GetRepository<T>() where T : class { var type = typeof (T); if (!this.repositories.ContainsKey(type)) { var typeOfRepository = typeof(GenericRepository<T>); var repository = Activator.CreateInstance(typeOfRepository, this.dbContext); this.repositories.Add(typeof(T), repository); } return (IRepository<T>)this.repositories[type]; } } }<file_sep>namespace Twitter.Data.Migrations { using System; using System.Collections.Generic; using System.Data.Entity; using System.Data.Entity.Migrations; using System.Linq; using Twitter.Models; public sealed class Configuration : DbMigrationsConfiguration<TwitterDBContext> { public Configuration() { this.AutomaticMigrationsEnabled = true; this.AutomaticMigrationDataLossAllowed = true; } protected override void Seed(TwitterDBContext context) { var userDbonev = new User { Username = "dbonev", Password = "<PASSWORD>", Email = "<EMAIL>" }; var userKibork = new User { Username = "Kibork", Password = "<PASSWORD>", Email = "<EMAIL>" }; var userSomeUser = new User { Username = "SomeUser", Password = "<PASSWORD>", Email = "<EMAIL>" }; userKibork.Following = new List<User>() { userDbonev, userSomeUser }; userSomeUser.Following = new List<User>() { userDbonev }; var tweetSomeTweet = new Tweet { URL = "http://dbonev.com" }; userDbonev.FavouriteTweets = new List<Tweet>() { tweetSomeTweet }; // This method will be called after migrating to the latest version. // You can use the DbSet<T>.AddOrUpdate() helper extension method // to avoid creating duplicate seed data. E.g. // // context.People.AddOrUpdate( // p => p.FullName, // new Person { FullName = "<NAME>" }, // new Person { FullName = "<NAME>" }, // new Person { FullName = "<NAME>" } // ); // } } } <file_sep>using Microsoft.AspNet.Identity; using Microsoft.AspNet.Identity.EntityFramework; using System; using System.Collections.Generic; using System.Linq; using System.Security.Claims; using System.Text; using System.Threading.Tasks; namespace Twitter.Model { public class ApplicationUser : IdentityUser { public async Task<ClaimsIdentity> GenerateUserIdentityAsync(UserManager<ApplicationUser> manager) { // Note the authenticationType must match the one defined in CookieAuthenticationOptions.AuthenticationType var userIdentity = await manager.CreateIdentityAsync(this, DefaultAuthenticationTypes.ApplicationCookie); // Add custom user claims here return userIdentity; } private ICollection<ApplicationUser> followersList; private ICollection<ApplicationUser> followingList; private ICollection<Tweet> ownTweetsList; private ICollection<Tweet> favouriteTweetsList; public ApplicationUser() { this.OwnTweetsList = new HashSet<Tweet>(); this.FavouriteTweetsList = new HashSet<Tweet>(); this.FollowersList = new HashSet<ApplicationUser>(); this.FollowingList = new HashSet<ApplicationUser>(); } public virtual ICollection<ApplicationUser> FollowersList { get { return this.followersList; } set { this.followersList = value; } } public virtual ICollection<ApplicationUser> FollowingList { get { return this.followingList; } set { this.followingList = value; } } public virtual ICollection<Tweet> OwnTweetsList { get { return this.ownTweetsList; } set { this.ownTweetsList = value; } } public virtual ICollection<Tweet> FavouriteTweetsList { get { return this.favouriteTweetsList; } set { this.favouriteTweetsList = value; } } public int ProfileId { get; set; } public virtual Profile Profile { get; set; } } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; using Twitter.Data.UnitOfWork; namespace Twitter.Web.Controllers { public class BaseController : Controller { private readonly ITwitterUnitOfWork data; public BaseController(ITwitterUnitOfWork data) { this.data = data; } public BaseController() { new BaseController(); } protected ITwitterUnitOfWork Data { get { return this.data; } } } }<file_sep>using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.Linq; using System.Text; using System.Threading.Tasks; namespace WorkShop.Models { public class Certification { [Key] public int Id { get; set; } public string Name { get; set; } public string LicenseNumber { get; set; } public string Url { get; set; } public DateTime TakenDate { get; set; } public DateTime ExpirationDate { get; set; } [Required] public string UserId { get; set; } public User User { get; set; } } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace WorkShop.Models { public enum GroupType { Professional, Networking, NonProfit, Conference, Corporate } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Twitter.Model { public enum NotificationType { NewFollower, FavouriteTweet, RetweetTweet } } <file_sep>using Microsoft.AspNet.Identity.EntityFramework; using System; using System.Collections.Generic; using System.Data.Entity; using System.Linq; using System.Text; using System.Threading.Tasks; using Twitter.Model; namespace Twitter.Data { public class TwitterDBContext : IdentityDbContext<ApplicationUser> { public TwitterDBContext() : base("TwitterDB", throwIfV1Schema: false) { } public static TwitterDBContext Create() { return new TwitterDBContext(); } // public IDbSet<User> Users { get; set; } public IDbSet<Tweet> Tweets { get; set; } public IDbSet<Profile> Profiles { get; set; } public IDbSet<Notification> Notifications { get; set; } public IDbSet<Message> Messages { get; set; } public new IDbSet<T> Set<T>() where T : class { return base.Set<T>(); } } } <file_sep>namespace Twitter.Models { using Microsoft.AspNet.Identity; using Microsoft.AspNet.Identity.EntityFramework; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.Security.Claims; using System.Threading.Tasks; public class User : IdentityUser { private ICollection<User> followers; private ICollection<User> following; private ICollection<Tweet> favouriteTweets; public async Task<ClaimsIdentity> GenerateUserIdentityAsync(UserManager<User> manager) { // Note the authenticationType must match the one defined in CookieAuthenticationOptions.AuthenticationType var userIdentity = await manager.CreateIdentityAsync(this, DefaultAuthenticationTypes.ApplicationCookie); // Add custom user claims here return userIdentity; } public User() { this.Followers = new HashSet<User>(); this.Following = new HashSet<User>(); this.FavouriteTweets = new HashSet<Tweet>(); } [Key] public int Id { get; set; } [Required] [MaxLength(45)] [MinLength(3)] public string Username { get; set; } [Required] [MaxLength(45)] [MinLength(6)] public string Password { get; set; } [Required] [MinLength(9)] public string Email { get; set; } public int UserPublicProfileId { get; set; } public virtual ICollection<User> Followers { get { return this.followers; } set { this.followers = value; } } public virtual ICollection<User> Following { get { return this.following; } set { this.following = value; } } public virtual ICollection<Tweet> FavouriteTweets { get { return this.favouriteTweets; } set { this.favouriteTweets = value; } } } /*public class User { private ICollection<User> followers; private ICollection<User> following; private ICollection<Tweet> favouriteTweets; public User() { this.Followers = new HashSet<User>(); this.Following = new HashSet<User>(); this.FavouriteTweets = new HashSet<Tweet>(); } [Key] public int Id { get; set; } [Required] [MaxLength(45)] [MinLength(3)] public string Username { get; set; } [Required] [MaxLength(45)] [MinLength(6)] public string Password { get; set; } [Required] [MinLength(9)] public string Email { get; set; } public int UserPublicProfileId { get; set; } public virtual ICollection<User> Followers { get { return this.followers; } set { this.followers = value; } } public virtual ICollection<User> Following { get { return this.following; } set { this.following = value; } } public virtual ICollection<Tweet> FavouriteTweets { get { return this.favouriteTweets; } set { this.favouriteTweets = value; } } }*/ } <file_sep>using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations.Schema; using System.Linq; using System.Text; using System.Threading.Tasks; namespace WorkShop.Models { [ComplexType] public class ContactInfo { public string Phone { get; set; } public string Twitter { get; set; } public string Website { get; set; } public string Facebook { get; set; } } }
41c14295fad465f40c9441ebb05cf2fdfa78e9db
[ "Markdown", "C#" ]
17
C#
dbonev91/ASP.NET-MVC
57530f663a9ed956a35cbbb762bb965155deb008
61b5f15dd63a6ed56cc2192bfa89a50c6c9e5d4a
refs/heads/master
<file_sep>#!/usr/bin/env jython ### JMLbot is a MSN chatbot framework written in jython that makes use of ### the java messenger library (http://jml.blathersource.org/). Based on the ### orignal work by <NAME> (<EMAIL>). __author__ = "<NAME> (<EMAIL>)" __version__ = "$Revision: 1.0 $" __date__ = "$Date: 2010/011/14 $" __license__ = "GPL2" #from time import sleep import sys import os import time from time import sleep import urllib import getopt import ConfigParser import random import linecache import threading #setup the path and add JML current_path= os.getcwd() sys.path.append(os.path.join(current_path,'jml-1.05b-full_http.jar')) from net.sf.jml import MsnMessenger from net.sf.jml import MsnUserStatus from net.sf.jml.impl import MsnMessengerFactory from net.sf.jml import MsnSwitchboard from net.sf.jml.event import MsnAdapter from net.sf.jml.message import MsnControlMessage from net.sf.jml.message import MsnDatacastMessage from net.sf.jml.message import MsnInstantMessage from net.sf.jml import MsnContact from net.sf.jml import Email from net.sf.jml import MsnObject from net.sf.jml import MsnProtocol from org.apache.http.params import HttpParams class MSNEventHandler(MsnAdapter): #overridden call back functions def instantMessageReceived(self, switchboard,message,contact): receivedText = message.getContent() #set the switchboard, so that we can send messages self.switchboard = switchboard if Config.get('System', 'auto_idle_events') == "yes": setIdleTimer.stop() ext_handler = Config.get('System','event_handler') + " " contact_id = str(contact.getEmail()) + " " contact_name = str(contact.getFriendlyName()) + " " if Config.get('System','send_typing') == "yes": # Send typing notify typingMessage = MsnControlMessage() typingMessage.setTypingUser(switchboard.getMessenger().getOwner().getDisplayName()); self.sendMessage(typingMessage) time.sleep(2) cmdline = ext_handler + contact_id + "'" + receivedText + "'" output = os.popen(cmdline).read() #send the msg to the buddy msnMessage = MsnInstantMessage() msnMessage.setContent(output) self.sendMessage(msnMessage) if Config.get('System', 'auto_idle_events') == "yes": setIdleTimer.start() def contactAddedMe(self,messenger,contact): messenger.addFriend(contact.getEmail(),contact.getFriendlyName()) #non overridden functions def sendMessage(self,message): self.switchboard.sendMessage(message) class msnWatchDog(threading.Thread): def __init__ (self,messenger): self.messenger = messenger self._stopevent = threading.Event() threading.Thread.__init__ (self,name="msnWatchdog") def run(self): while 1: if str(self.messenger.getConnection()) == "None": print "\n My connection died. Will attempt to restart ..." print " Closing active threads ..." setIdleTimer.stop() setStatusTimer.stop() print " Restarting ..." start() threading.Thread.__init__(self) sys.exit() else: sleep(10) class RandomStatus(threading.Thread): def __init__ (self, messenger,Config): self.messenger = messenger self.Config = Config self._stopevent = threading.Event() threading.Thread.__init__ (self) def run(self): status_sleep = self.Config.get('Details','status_time') status_file = self.Config.get('Details','status_file') status_num_lines = sum(1 for line in open(status_file)) self._stopevent.clear() statusmsg = linecache.getline(status_file, random.randint(1,status_num_lines)) self.messenger.getOwner().setPersonalMessage(statusmsg) count = 0 while not self._stopevent.isSet(): count += 1 if count == int(status_sleep): statusmsg = linecache.getline(status_file, random.randint(1,status_num_lines)) self.messenger.getOwner().setPersonalMessage(statusmsg) # Reset the counter count = 0 time.sleep(1) threading.Thread.__init__(self) def stop(self): self._stopevent.set() threading.Thread.join(self, timeout=0.1) self.join() class IdleStatus(threading.Thread): def __init__ (self, messenger,Config,BotStatus): self.messenger = messenger self.Config = Config self.BotStatus = BotStatus self._stopevent = threading.Event() threading.Thread.__init__ (self,name="idleCounter") def run(self): idle_time = self.Config.get('System','idle_time') away_time = self.Config.get('System','away_time') self._stopevent.clear() count = 0 while not self._stopevent.isSet(): count += 1 if count == int(idle_time): self.messenger.getOwner().setStatus(MsnUserStatus.IDLE) elif count == int(away_time): self.messenger.getOwner().setStatus(MsnUserStatus.AWAY) time.sleep(1) threading.Thread.__init__(self) def stop(self): self.messenger.getOwner().setStatus(self.BotStatus) self._stopevent.set() threading.Thread.join(self, timeout=0.1) self.join() class MSNMessenger: def initMessenger(self,messenger): print "Initializing...." listener = MSNEventHandler() messenger.addMessageListener(listener) messenger.addContactListListener(listener) def PostLoginSetup(self,messenger): # Hide until we are ready to take events messenger.getOwner().setInitStatus(MsnUserStatus.HIDE) print " Setting up bot indenity ..." # Lets do some client setup before moving on delay = Config.get('System','login_delay') print " Waiting " + delay + "secs for connection to settle ..." time.sleep(int(delay)) # Set screen name bot_screenname = Config.get('Details','screenname') print " Setting screen name to " + bot_screenname + " ..." messenger.getOwner().setDisplayName(bot_screenname) # Set avatar bot_avatar = Config.get('Details','avatar') print " Setting avatar using " + bot_avatar + " ..." displayPicture = MsnObject.getInstance(messenger.getOwner().getEmail().getEmailAddress(), bot_avatar) messenger.getOwner().setInitDisplayPicture(displayPicture) # Set personal message if Config.get('Details','random_status') == "yes": print " Setting random status message ..." global setStatusTimer setStatusTimer = RandomStatus(messenger,Config) setStatusTimer.start() else: print " Setting status message ..." statusmsg = Config.get('Details','status_message') messenger.getOwner().setPersonalMessage(statusmsg) # Set Status initStatus = Config.get('Details', 'status') print " Setting status to " + initStatus + " ..." if initStatus == "away": BotStatus = MsnUserStatus.AWAY elif initStatus == "busy": BotStatus = MsnUserStatus.BUSY elif initStatus == "hide": BotStatus = MsnUserStatus.HIDE elif initStatus == "brb": BotStatus = MsnUserStatus.BE_RIGHT_BACK elif initStatus == "phone": BotStatus = MsnUserStatus.ON_THE_PHONE elif initStatus == "lunch": BotStatus = MsnUserStatus.OUT_TO_LUNCH else: # Default to online BotStatus = MsnUserStatus.ONLINE messenger.getOwner().setStatus(BotStatus) if Config.get('System', 'auto_idle_events') == "yes": global setIdleTimer setIdleTimer = IdleStatus(messenger,Config,BotStatus) setIdleTimer.start() msnWatchDog(messenger).start() def connect(self,email,password): messenger = MsnMessengerFactory.createMsnMessenger(email,password) self.initMessenger(messenger) print " Connecting ..." try: messenger.login() except: print " Login failed. Aborting ..." sys.exit(100) MSNMessenger.PostLoginSetup(self,messenger) class MSNConnector: def connect(self,username,password): messenger = MSNMessenger() messenger.connect(username,password) def usage(): output = "Usage: \n" output = output + "--config <file> ::: Specify JMLbot config file \n" output = output + "-h/--help ::: This message \n" output = output + "\n" print output def LoadConfig(config_file): if os.path.exists(config_file): load_msg = "Using config file: " + config_file print load_msg global Config Config = ConfigParser.ConfigParser() Config.read(config_file) else: print "The specified config file does not exist!" sys.exit(1) def start(): connector = MSNConnector() bot_username = Config.get('Account','username') bot_password = Config.get('Account','password') connector.connect(bot_username,bot_password) print "Initializing complete. Listening for events ..." def main(argv): config_file="" try: opts, args = getopt.getopt(argv, "h", ["help", "config="]) except getopt.GetoptError: usage() sys.exit(2) for opt, arg in opts: if opt in ("-h", "--help"): usage() sys.exit() elif opt in ("--config"): config_file = arg if config_file: LoadConfig(config_file) else: print "Please give a config file to load. see --help\n" sys.exit(1) start() while 1: time.sleep(10) if __name__ == "__main__": main(sys.argv[1:]) <file_sep>#!/bin/bash ###################################### Init ###################################### JAVA=$(which java) if [ -n "$JAVA" ]; then BASE_DIR="$(dirname $(readlink -f $(type -a "$0" |awk '{print $3}'|head -n1)))" CONFIG="${BASE_DIR}/jmlbot.conf" PIDFILE="${BASE_DIR}/JMLbot.pid" NAME=JMLbot MEM=16 cd ${BASE_DIR}/sys/ else echo "Java not found! Aborting ..." exit 1 fi #################################### END Init #################################### case "$1" in start) echo -n "Starting ${NAME} .." java -Xmx${MEM}m -jar jython.jar ${NAME}.py --config "$CONFIG" 2>&1 >/dev/null & PID=$! echo ".... done. [${PID}]" ;; stop) PID=$(ps ax |grep java |grep ${NAME}.py|grep -v grep |awk '{print $1}') if [ -n "$PID" ]; then echo -n "Stoping $NAME ..." kill -9 $PID rm -f $PIDFILE echo "... done" exit 0 else echo "$NAME is not running." exit 1 fi ;; restart) ${BASE_DIR}/$(basename $0) stop sleep 2 ${BASE_DIR}/$(basename $0) start ;; *) echo "Usage: $0 <start|stop>" ;; esac <file_sep>#!/bin/bash ## ## This is a very bare example of a event handler for jmlbot ## ############################################################################### ################################### INIT ###################################### BASE_DIR="$(dirname $(readlink -f $(type -a "$0" |awk '{print $3}'|head -n1)))" if [ "$1" ]; then TMP="$(echo $1 |grep "@")" if [ -n "$TMP" ]; then EVENT_NICK="$1" shift 1 EVENT_CONTENT="${@}" else # Incorrect args passed to the handler. Should be # <<EMAIL>> <message content> exit 100 fi else # No args passed to event handler exit 1 fi cd $BASE_DIR ############################################################################## do_fortune() { echo "You will be happy with this bot :)" } do_help() { cat <<EOF General commands: fortune - Display a fortune help - this message EOF } ################## End Helper functions ############################################ ########## Main event function - All others should be called from here ############## ##################################################################################### do_event() { EVENT_NICK="$1" shift 1 EVENT_CONTENT="${@}" case "$1" in help) echo "" do_help ;; fortune) echo "" do_fortune ;; esac } # Dont quote $EVENT_CONTENT so it may be parameterized. do_event "$EVENT_NICK" $EVENT_CONTENT
689fa7fa33a3982b42cfd4081a584ff3cb2fdf57
[ "Python", "Shell" ]
3
Python
onemyndseye/JMLbot
ed40b566773e1a90ad9ad7ea1d654f88dc0a8db2
ba283e9a389c3447eaea2df224a860c5e35ee1f1
refs/heads/main
<repo_name>HamzaARZ/react-demo-app<file_sep>/src/store/reducers/result.js import * as actionTypes from '../actions/actionTypes'; const initialState = { result: [] }; // const deleteResult = (state, action) => { // const newResults = [...state.result]; // newResults.splice(action.index, 1); // return { // ...state, // result: newResults // } // } const reducer = (state = initialState, action) => { switch (action.type) { case actionTypes.STORE_RESULT: return { ...state, // concat creats a new array than add the new item result: state.result.concat(action.counter) } case 'DELETE_RESULT': // const itemIndexToDelete = 3; // const updatedResult = state.result.filter((_, index) => index !== itemIndexToDelete); const newResults = [...state.result]; newResults.splice(action.index, 1); return { ...state, result: newResults } // return deleteResult (state, action); default: return state; } }; export default reducer; <file_sep>/src/components/TestIf/TestIf.js import React, { useEffect } from 'react' const TestIf = () => { useEffect(() => { console.log("creation of TestIf component"); const timer = setTimeout(() => { alert("after 1s...") }, 1000) return () => { clearTimeout(timer); console.log("clean up TestIf component"); } }, []) return ( <div> <h3>test if</h3> </div> ) } export default TestIf; <file_sep>/src/context/testIf-context.js import React from 'react'; const testIfContext = React.createContext({ testIf : false, showIfTest: () => {} }); export default testIfContext; <file_sep>/src/store/actions/result.js import * as actionTypes from './actionTypes'; export const storeResult = (res) => { return { type: actionTypes.STORE_RESULT, counter: res }; }; // using async function export const storeAsyncResult = (res) => { return (dispatch, getState) => { console.log("----------"); console.log(getState().ctr.counter); setTimeout(() => { dispatch(storeResult(res)); }, 2000); } }; export const deleteResult = (resElId) => { return { type: actionTypes.DELETE_RESULT, index: resElId }; }; <file_sep>/src/components/person/Person.js import React, { useState } from "react"; const Person = props => { const [personState, setPersonState] = useState({ persons: [ { name: 'hamza', age: 23 }, { name: 'hsdvq', age: 13 } ] }); const onClickButton = () => { setPersonState({ persons: [ { name: 'hamza', age: 33 }, { name: 'hsdaa', age: 22 } ] }) }; console.log(personState); return ( <div> <h3 className="person">this is a person component</h3> <p>name : {personState.persons[0].name}, age : {personState.persons[0].age}.</p> <p>name : {personState.persons[1].name}, age : {personState.persons[1].age}.</p> <p>{5 + 1}</p> <button onClick={onClickButton}>click me</button> <p>{props.children}</p> </div> ); } export default Person;<file_sep>/src/App.js import './App.css'; import React, { useState } from 'react'; import { Route, BrowserRouter as Router, Switch, NavLink } from 'react-router-dom'; // import { BrowserRouter as Router, Route, Switch } from 'react-router-dom'; import Person2 from './components/person2/Person2'; import TestIfContext from './context/testIf-context'; import Counter from './containers/Counter/Counter'; import Users from './containers/users/Users'; import About from './containers/users/About'; const App = () => { const [personState, setPersonState] = useState({ persons: [ { name: 'hamza', age: 23 }, { name: 'hsdvq', age: 13 } ], testIf: false }); const [toggle, setToggle] = useState(false); const onClickButton = (newName) => { setPersonState({ persons: [ { name: 'hamza', age: 33 }, { name: newName, age: 22 } ], // testIf: personState.testIf }); }; const onNameChange = (event) => { setPersonState({ persons: [ { name: event.target.value, age: 23 }, { name: event.target.value, age: 13 } ] }) }; const showIfTest = () => { setPersonState((prevState, props) => { return { persons: prevState.persons, testIf: !prevState.testIf } }) }; const showState = () => { console.log(personState); }; const toggleLink = () => { setToggle(!toggle); } return ( <> {/* routing */} <Router> <Switch> <Route path="/users"> <Users /> </Route> <Route path="/about"> <About /> </Route> </Switch> {/* <NavLink to="/users"> Users Link </NavLink> */} <NavLink onClick={toggleLink} to={ { pathname: toggle ? "/": "/users", userProps: "props..." } } > Users Link </NavLink> </Router> {/* /routing */} <div className="App"> <h1 className="person">This is the app component</h1> {/* <Person name="hamza" age="23">additional content</Person> */} <TestIfContext.Provider value={{ testIf: personState.testIf, showIfTest: showIfTest }}> <Person2 name={personState.persons[0].name} age={personState.persons[0].age} click={onClickButton} changed={onNameChange} ></Person2> <Person2 name={personState.persons[1].name} age={personState.persons[1].age} click={onClickButton} changed={onNameChange} ></Person2> </TestIfContext.Provider> <button onClick={showState}>show state</button> {/* <button ref={buttonTestIfRef} onClick={showIfTest}>show if test</button> */} {/* <Person2 name={personState.persons[1].name} age={personState.persons[1].age}></Person2> */} {/* <Person /> */} {/* { personState.testIf ? <TestIf /> : null } */} <h2>-------------- Redux --------------</h2> <Counter /> </div> </> ); } export default App;
04a4e3fa142e60e4e46e94ff6790db4d82e8d626
[ "JavaScript" ]
6
JavaScript
HamzaARZ/react-demo-app
3e6ff650dbdfcbb3e6c4dedcec34490161d1384d
545ceba929eb69951ef869f55ceb141e8f425541
refs/heads/master
<repo_name>jamalsoueidan/LobbyFlexApplication<file_sep>/html-template/cookie.js function start_match(room) { alert(room); }
ae6c58a510c6ad77735cb20a02c22862596e07c6
[ "JavaScript" ]
1
JavaScript
jamalsoueidan/LobbyFlexApplication
3c54da4d5765b64bfde03d58e33c0ea1a59f6aa9
1e0ce70d317615c520755b297ada3756f0b346f6
refs/heads/master
<repo_name>hanjiwon1/Capstone_Dayspirit<file_sep>/dao/DBConnection.py import pymysql def getConnection(): return pymysql.connect(host='localhost', user='root', password='<PASSWORD>', db='dayspirit',charset='utf8') <file_sep>/model.py import numpy as np import fasttext from PyKomoran import * import re from random import randint komoran=Komoran("EXP") model=fasttext.load_model("model_0602.bin") #코사인 유사도 def similarity(v1,v2): n1=np.linalg.norm(v1) n2=np.linalg.norm(v2) simy=np.dot(v1,v2)/n1/n2 if simy>1: return 1.0 elif simy<0: return 0.0 else: return simy #유사한 단어 리스트 생성 #fa_model = 신경망 모델 #sentence = 유저가 입력한 문장 전처리한 다차원 리스트([n][0]:형태소,[n][1]:품사) #pre_vocab = 감정 키워드 리스트 def findmaxsim(input_type, fa_model, sentence, pre_vocab): diary=[] #diary 리스트 선언 for i in range(len(sentence)): diary.append(sentence[i][0]) #diary리스트에 형태소만 넣어준다. sim_list=list()#유사도가 최대로 나온 키워드들 넣어줄 리스트 선언 for i in range(len(diary)): max=0 for j in range(len(pre_vocab)): #한 형태소 별로 모든 감정 키워드와 유사도 측정하기 위해서 이중포문 #similarity(형태소, 키워드) : 형태소와 키워드 유사도 측정 temp=similarity(fa_model.get_word_vector(diary[i]),fa_model.get_word_vector(pre_vocab[j])) if temp>max: max=temp word=pre_vocab[j] if input_type == 'plan': sim_list.append((word, max)) else: #해당 형태소가 명사라면 유사도가 0.4이상인 경우에만 sim_list에 넣어줌. #명사일 때 유사도 max값 0.4 안넘으면 해당 키워드는 감정분석에 사용 안함 if(sentence[i][1] == 'NNG' or sentence[i][1] == 'NNP' or sentence[i][1] == 'NA' or sentence[i][1] == 'XR'): if(max >0.4): sim_list.append((word,max)) #명사 아니면 유사도와 상관없이 sim_list에 추가시켜준다. else: sim_list.append((word, max)) #print('유사도 전체', sim_list) return sim_list #전처리 #인자로 들어오는 diary: 유저 입력 문장 전처리 시키기 위해 호출할 때는 str타입 # : 최종 결과 리스트 만들기 위해 호출할 때는 list타입-감정 분석에 사용 한 키워드들 리스트 def preprocessing(input_type, diary): #유저 입력 문장 전처리할 때 실행되는 코드 if input_type == 'diary': diary=komoran.get_plain_text(diary) #print('전처리함수 문장 전처리:', diary) morp_list = [] morp_list = diary.split(' ') final_list = [] for i in range(len(morp_list)): #print(morp_list[i]) token = morp_list[i].split('/') #print('스플릿한 토큰: ', token) #print('token타입', type(token)) if token[0] == morp_list[i]: token = [morp_list[i], 'NA'] #print('스플릿한 토큰2: ', token) final_list.append(token) #print('line67 전처리함수 final_list', final_list) emotion = [] for i in range(len(final_list)): if(final_list [i][1] == 'NA' or final_list[i][1] == 'MAG' or final_list[i][1]=='VA' or final_list[i][1]=='XR' or final_list[i][1]=='NNG' or final_list[i][1]=='VV' or final_list[i][1]=='NNP'): if final_list[i][0] != '오늘': if(len(final_list[i][0])>0): if final_list[i][1] == 'VV': if final_list[i][0]=='하' or final_list[i][0]=='오' or final_list[i][0]=='가': continue emotion.append((final_list[i][0], final_list[i][1])) #print(emotion) return emotion else: diary=komoran.get_plain_text(diary) morp_list = [] morp_list = diary.split(' ') final_list = [] for i in range(len(morp_list)): #print(morp_list[i]) token = morp_list[i].split('/') #print('스플릿한 토큰: ', token) #print('token타입', type(token)) if token[0] == morp_list[i]: token = [morp_list[i], 'NA'] #print('스플릿한 토큰2: ', token) final_list.append(token) #print('line67 전처리함수 final_list', final_list) plan = [] for i in range(len(final_list)): if(final_list [i][1] == 'NA' or final_list[i][1]=='XR' or final_list[i][1]=='NNG' or final_list[i][1]=='NNP'): if(len(final_list[i][0])>0): plan.append((final_list[i][0], final_list[i][1])) #print(plan) return plan #감정 정도 계산 def pointwithweight(res_dict,cnt_dict, dict_sim): emo_deg = [0, 0, 0, 0, 0] emo_sum = 0 for word in cnt_dict: if res_dict[word]== -5: emo_deg[0] += (cnt_dict[word]*dict_sim[word]) elif res_dict[word]== -3: emo_deg[1] += (cnt_dict[word]*dict_sim[word]) elif res_dict[word]== 1: emo_deg[2] += (cnt_dict[word]*dict_sim[word]) elif res_dict[word]== 3: emo_deg[3] += (cnt_dict[word]*dict_sim[word]) else: emo_deg[4] += (cnt_dict[word]*dict_sim[word]) for i in range(len(emo_deg)): emo_sum += emo_deg[i] for i in range(len(emo_deg)): emo_deg[i] = 100.0*(emo_deg[i]/emo_sum) #print(emo_deg) return emo_deg #몇 번 나왔는지 계산(튜플 형태라 .count 메소드 사용 불가한 경우) def countw(slist, word): cnt=0 for i in range(len(slist)): if wd(slist[i])==word: cnt=cnt+1 return cnt #튜플의 두 번째 인자 def sim(t): return t[1] #튜플의 첫 번째 인자 def wd(t): return t[0] #해당 단어가 가지는 가장 높은 유사도 def maxsim(slist,word): for i in range(len(slist)): if wd(slist[i])==word: return sim(slist[i])#유사도 기준으로 정렬했으니까 제일 앞에 나오는게 max값 #0.5 이상인 경우만 집계 def morethanhalf(slist): t_list=list() for i in range(len(slist)): if sim(slist[i])>=0.5: t_list.append(slist[i]) else: return t_list#유사도 기준으로 정렬했으니까 한번 0.5 미만이라면 그 뒤도 계속 0.5 미만 #일기->감정 def feeling(diary,fa_model): #리스트-감정 fllist=['화나', '참담', '배신', '증오', '서럽', '분노', '공포', '무섭', '겁', '미워', '미움', '미워하', '흑역사', '짜증', '어이없', '화', '지랄', '찝찝하다', '찝찝', '싸우', '싸움', '망', '아쉽', '눈물', '지루', '지치', '지침', '혼란', '당황', '의심', '외롭', '외로움', '슬프', '슬픔', '성가시', '성가심', '서운', '부끄럽', '수치', '수치심', '부끄러움', '곤란', '허탈', '허전', '속상하', '속상', '더럽', '복잡', '미안', '후회', '아파서', '아프', '어쩌', '비밀', '존경', '평화', '차분', '진정', '온순', '조용', '확고', '장난', '이성', '평온', '마지막', '위로', '기대', '응원','성공', '잘', '해결', '이쁘', '예쁘', '매력', '자랑', '통쾌', '낙관', '유머', '재치', '우정', '감사', '재밌', '고맙', '좋', '좋아서', '설레', '유쾌', '시원', '홀가분', '유머러스', '공손', '귀여움', '귀여워', '날라가', '날아가', '웃기', '반하', '맛있', '멋지', '멋있', '따뜻', '쏠쏠', '행복', '사랑', '입맞춤', '애정', '즐겁', '활기차', '신나', '미치', '황홀', '발랄', '쾌활', '존예', '존잼', '존맛', '좋아하', '최고'] #딕셔너리-감정 fldict={#아주 나쁨-(분노/절망/짜증) '화나':-5, '참담':-5, '배신':-5, '증오':-5, '서럽':-5, '분노':-5, '공포':-5, '겁':-5, '미워':-5, '미움':-5, '미워하':-5, '흑역사':-5, '짜증':-5, #나쁨-(불안/슬픔/걱정) '어이없':-3, '화':-3, '지랄':-3, '찝찝하다':-3, '찝찝':-3, '싸우':-3, '싸움':-3,'무섭':-3, '망':-3, '아쉽':-3, '눈물':-3, '지루':-3, '지치':-3, '지침':-3, '혼란':-3, '당황':-3, '의심':-3, '외롭':-3, '외로움':-3, '슬프':-3, '슬픔':-3, '성가시':-3, '성가심':-3, '서운':-3, '부끄럽':-3, '수치':-3, '수치심':-3, '부끄러움':-3, '곤란':-3, '허탈':-3, '허전':-3, '속상하':-3, '속상':-3, '더럽':-3, '복잡':-3, '미안':-3, '후회':-3, '아파서':-3, '아프':-3, '어쩌':-3, #보통-(평온/관심/수용) '비밀':1, '존경':1, '평화':1, '차분':1, '진정':1, '온순':1, '조용':1, '확고':1, '괜찮':1, '장난':1, '이성':1, '평온':1, '마지막':1, '위로':1, '기대':1, #좋음-(기쁨/ 낙천/ 기대) '응원':3, '성공':3, '잘':3, '해결':3, '이쁘':3, '예쁘':3, '매력':3, '자랑':3, '통쾌':3, '낙관':3, '유머':3, '재치':3, '우정':3, '감사':3, '재밌':3, '고맙':3,'좋':3, '좋아서':3, '설레':3, '유쾌':3, '시원':3, '홀가분':3, '유머러스':3, '공손':3, '귀여움':3, '귀여워':3, '날라가':3, '날아가':3, '웃기':3, '반하':3, '맛있':3, '멋지':3, '멋있':3, '따뜻':3, '쏠쏠':3, #아주 좋음-(사랑/황홀/즐거움) '행복':5, '사랑':5, '입맞춤':5, '애정':5, '즐겁':5, '활기차':5, '신나':5, '미치':5, '황홀':5, '발랄':5, '졸귀':5, '쾌활':5, '존예':5, '존잼':5, '존맛':5, '좋아하':5, '최고':5}#감정-정도 resfl=['분노/절망/짜증','불안/슬픔/걱정','평온/관심/수용','기쁨/ 낙천/ 기대','사랑/황홀/즐거움'] #스트링 전처리: (띄어쓰기->)형태소 sentence=preprocessing('diary', diary) #print('line 181 sentence전처리: ',sentence) #print() if len(sentence)==0: return 'ERROR' #유사도 비교 및 결과 저장 simlist=findmaxsim('diary', fa_model, sentence,fllist) #print('line187 키워드별 유사도:',simlist) if len(simlist)==0: return 'ERROR' simlist.sort(key=sim,reverse=True) finlist=simlist#[:(int)(len(simlist)/2)] #print() result_list=list() for i in range(len(finlist)): result_list.append(finlist[i][0]) last_keyword_list = result_list dict_fin=dict() cnt=0 #count해서 dictionary 생성 for i in range(len(fllist)): if result_list.count(fllist[i])!=0: dict_fin[fllist[i]]=result_list.count(fllist[i]) cnt += result_list.count(fllist[i]) #각 키워드별 유사도 합 dict_sim = dict() for i in range(len(fllist)): if result_list.count(fllist[i])!=0: dict_sim[fllist[i]]=0 for i in range(len(dict_sim)): for j in range(cnt): dict_sim[finlist[j][0]] += finlist[j][1] respoint = [] #pointweight respoint=pointwithweight(fldict,dict_fin, dict_sim) emo={} for obj in range(len(respoint)): if obj == 0: emo['분노/절망/짜증']=(round(respoint[obj],1)) elif obj == 1: emo['불안/슬픔/걱정']=(round(respoint[obj],1)) elif obj == 2: emo['평온/관심/수용']=(round(respoint[obj],1)) elif obj == 3: emo['기쁨/낙천/기대']=(round(respoint[obj],1)) else: emo['사랑/황홀/즐거움']=(round(respoint[obj],1)) return emo #다이어리로 들어갔지만 계획 def planning(diary,fa_model): pllist=['회의', '면접', '미팅', '회사', '거래처', '발표', '소개팅', '상견례', '병문안', '장례식', '결혼식', '돌잔치', '출장', '수업', '학원', '학교', '컨퍼런스', '생일', '쇼핑', '카페', '바다', '등산', '맛집', '데이트', '파티', '술집', '클럽', '산책', '운동', '노래방', '축제', '미용', '공원', '공연', '미술관', '영화', '뮤지컬', '연극'] pldict = {'회의':1, '면접':2, '미팅':1, '회사':1, '거래처':1, '발표':2, '소개팅':2, '상견례':2, '병문안':3, '장례식':4, '결혼식':4, '돌잔치':2, '출장':1, '수업':1, '학원':1, '학교':1, '컨퍼런스':3, '생일':3, '쇼핑':1, '카페':1, '바다':1, '등산':2, '맛집':1, '데이트':1, '파티':3, '술집':1, '클럽':3, '산책':1, '운동':1, '노래방':2, '축제':3, '미용':1, '공원':1, '공연':1, '미술관':2, '영화':1, '뮤지컬':2, '연극':2} #스트링 전처리: 띄어쓰기->형태소 sentence=preprocessing('plan', diary) if len(sentence) == 0: random_index = randint(0, 37) random_keyword = pllist[random_index] return random_keyword #유사도 비교 및 결과 저장 simlist=findmaxsim('plan', fa_model,sentence,pllist) sim_weight_list = [] for i in range(len(simlist)): sim_weight_list.append((simlist[i][0], simlist[i][1]*pldict[simlist[i][0]])) sim_weight_list.sort(key=sim,reverse=True)#유사도 기준으로 내림차순 정렬 #print('가중치 준 시밀러리스트: ',sim_weight_list) '''#만일 제일 높은 유사도가 0.5 이상이라면 0.5 이상만 집계 그렇지 못할 시에는 그냥 전체에서 반 자르기 if sim(simlist[0])>=0.5: finlist=morethanhalf(simlist) else: finlist=simlist[:(int)(len(simlist)/2)]''' finlist= [] finlist = sim_weight_list #여기까지 하면 제일 유사도가 높은 단어들이 전체의 반만큼 만들어짐. '''set_list=list() for i in range(len(finlist)): set_list.append(finlist[i][0]) set_list=list(set(set_list)) if len(set_list)==1: #한 종류라면 바로 반환 return set_list[0] result_list=list() for i in range(len(set_list)): result_list.append((set_list[i],countw(finlist,set_list[i]),maxsim(finlist,set_list[i]))) #위 작업으로 (단어, 카운트, max유사도)를 갖는 리스트 형성 result_list.sort(key=sim,reverse=True)#key=sim인데 그냥 튜플 두 번째 인자라 실제로는 카운트 기준으로 정렬 #그다음 제일 첫번째 원소의 카운트랑 비교해서 카운트가 같은 값이 있다면 temp_most=result_list[0] for i in range(len(result_list)): if temp_most[1]==result_list[i][1]: if temp_most[2]<result_list[i][2]: temp_most=result_list[i] #유사도를 비교한다 else: return wd(temp_most)#카운트가 같은 값이 아니라면 빈도가 더 낮을 것이므로 바로 반환 ''' return finlist[0][0] def analyze_diary(content): emotion_list=feeling(content,model) print(emotion_list) return emotion_list def analyze_plan(content): keyword=planning(content,model) print(keyword) return keyword ##실험용 # #sent = input("[일기 입력]") # ##이모티콘, 특수문자 제거 #emoji_pattern = re.compile("[" # u"\U00010000-\U0010FFFF" # "]+", flags = re.UNICODE) #han = re.compile(r'[ㄱ-ㅎㅏ-ㅣ!?~,".\n\r#\ufeff\u200d]') # #tokens = re.sub(emoji_pattern, " ", sent) #tokens = re.sub(han, " ", tokens) # #sent = tokens # # #print(feeling(sent,model)) #print() #print(planning(sent,model))<file_sep>/dao/DiaryDAO.py import json import pymysql from dao import DBConnection def manipulate_diary(_type, loginId, date, content, emotionId, emotion_list): conn = DBConnection.getConnection() try: cursor = conn.cursor() if _type=="EDIT": sql = "update diary set content=%s,emotionId=(select emotionId from emotion where emotionName=%s),items=%s where memberId=%s and date=%s" value = (content, emotionId, emotion_list,loginId, date) else: sql = "delete from diary where memberId=%s and date=%s" value=(loginId, date) cursor.execute(sql,value) data = cursor.fetchall() conn.commit() finally: conn.close() return "" def addDiary(content, loginId, date,emotionId, emotion_list): conn = DBConnection.getConnection() try: cursor = conn.cursor() sql = "insert into diary(content, memberID, date,emotionId,items) values(%s,%s,%s,(select emotionId from emotion where emotionName=%s),%s)" value=(content, loginId, date,emotionId,emotion_list) cursor.execute(sql,value) data = cursor.fetchall() conn.commit() print("일기가 추가되었습니다") finally: conn.close() return "" def isExistDiary(date, loginId): content=False conn = DBConnection.getConnection() try: cursor = conn.cursor() sql="select content from diary where date=%s and memberId=%s" value=(date, loginId) cursor.execute(sql, value) data = cursor.fetchall() # 만약 다이어리가 존재하면 cnt++ for i in data: content=i[0] finally: conn.close() #다이어리가 존재하지 않으면 False를 반환 return content def getDiary(loginId): conn = DBConnection.getConnection() try: cursor = conn.cursor() sql = "select diary.date, emotion.emotionImg from diary, emotion where diary.emotionId = emotion.emotionId and diary.memberId = %s" cursor.execute(sql, loginId) row = cursor.fetchall() data_list=[] for obj in row: data_dic = { 'date' : obj[0], 'img' : obj[1] } data_list.append(data_dic) finally: conn.close() return data_list def getEmotion(date, loginId): conn = DBConnection.getConnection() find=False; try: cursor = conn.cursor() sql = "select emotionName,items from emotion, diary where emotion.emotionId=diary.emotionId and diary.date=%s and diary.memberId=%s" value=(date, loginId) cursor.execute(sql,value) row = cursor.fetchall() for obj in row: data_dic={ 'emotionName':obj[0], 'items' : obj[1] } finally: conn.close() return data_dic <file_sep>/app.py import json from flask import Flask, request, render_template,session,redirect,url_for,flash from dao import MemberDAO, DiaryDAO, PlanDAO import model app = Flask(__name__) app.secret_key='id' # 기본 페이지 접속 @app.route("/") def index(): return render_template("index.html") # 화면 렌더링 함수 @app.route("/current") def current(): if(session['login']==False): return redirect(url_for("index")) else : return redirect(url_for("calendar")) @app.route("/home_header") def home_header(): return render_template("home_header.html") @app.route("/sign_in") def sign_in(): return render_template("sign_in.html") @app.route("/sign_up") def sign_up(): return render_template("sign_up.html") @app.route("/find_id") def find_id(): return render_template("find_id.html") @app.route("/find_pw") def find_pw(): return render_template("find_pw.html") @app.route("/find_idpw") def find_idpw(): return render_template("find_idpw.html") @app.route("/diary") def diary(): content=False date = request.args.get('date', "") content=DiaryDAO.isExistDiary(date, session['login']) if (content!=False): return render_template("keep_diary.html", tmp=content, data=date) else: return render_template("keep_diary.html", tmp="",data=date) @app.route("/plan") def plan(): content=False date = request.args.get('date',"") content=PlanDAO.isExistPlan(date, session['login']) if (content!=False): return render_template("make_plan.html", tmp=content, data=date) else: return render_template("make_plan.html", tmp="",data=date) @app.route("/calendar") def calendar(): diary_list = DiaryDAO.getDiary(session['login']) if len(diary_list)==0: return render_template("calendar.html") else: return render_template("calendar.html", data_list = diary_list) @app.route("/logout") def logout(): session['login']=False return redirect(url_for("index")) @app.route("/result_diary") def result_diary(): date = request.args.get('date', "")#2010-05-05 emotion_list = DiaryDAO.getEmotion(date, session['login']) name = emotion_list['emotionName'] emotion_items=json.loads(emotion_list['items'])#{"기쁘고 행복한": 37.6, "고요하고 편안한": 0.6, "화나고 적대적인": 37.9, "슬프고 불만족스러운": 11.0, "활기차고 사랑스러운": 12.8} => 딕셔너리 형태 result_list=[] for i in emotion_items.items(): data_dic={ 'name':i[0], 'percent':i[1] } result_list.append(data_dic) return render_template("result_diary.html",data_list=result_list) @app.route("/result_plan") def result_plan(): date=request.args.get('date',"") colorImg=PlanDAO.getColor(date,session['login']) return render_template("result_plan.html",tmp=colorImg) # DB 동작 함수 @app.route("/check_dup_chk", methods=['post']) def check_dup_chk(): isExist=0 result="사용불가" data= request.get_json() print("[check_dup_chk: 받은 데이터]") print(data) # 만약 해당 objectId의 object가 존재하면 isExist = 1 isExist = MemberDAO.isExist(data['objectId'], data['object']) if (isExist==0): print("사용가능한 " + data['objectId'][4:] + " 입니다!") result="사용가능" else: print("[사용불가]이미 존재하는 " + data['objectId'][4:] + " 입니다!") return result @app.route("/check_find_id", methods=['post']) def check_find_id(): data=request.get_json() find_id = MemberDAO.findInfo("ID",data['userName'],data['userEmail']) if(find_id==False): find_id="이름 혹은 이메일이 옳지 않습니다." return find_id @app.route("/check_find_pw", methods=['post']) def check_find_pw(): data=request.get_json() find_pw = MemberDAO.findInfo("PASSWORD", data['userId'], data['userEmail']) if(find_pw==False): find_pw = "아이디 혹은 이메일이 옳지 않습니다" return find_pw @app.route("/sign_in_check", methods=['post']) def sign_in_check(): data = request.get_json() print(data) isLogin=False member={'id': data['loginId'], 'password' : data['loginPw']} isLogin = MemberDAO.login(member) if(isLogin!=False): session['login']=data['loginId'] return "SUCCESS" else: return "FAILED" @app.route("/sign_up_check", methods=['post']) def sign_up_check(): data = request.get_json() member = {'id': data['userId'], 'password' : data['<PASSWORD>'], 'name':data['userName'], 'email' : data['userEmail']} MemberDAO.signup(member) return "" def emotion_rank(emotion): pos = emotion['사랑/황홀/즐거움']+emotion['기쁨/낙천/기대'] neg = emotion['분노/절망/짜증']+emotion['불안/슬픔/걱정'] nor = emotion['평온/관심/수용']*2 tmp = max(pos, neg, nor) if(tmp==pos): if(emotion['기쁨/낙천/기대']> emotion['사랑/황홀/즐거움']): result = "기쁨/낙천/기대" else: result = "사랑/황홀/즐거움" elif(tmp==neg): if(emotion['분노/절망/짜증']>emotion['불안/슬픔/걱정']): result="분노/절망/짜증" else: result="불안/슬픔/걱정" else: result="평온/관심/수용" return result @app.route("/diary_check", methods=['POST']) def diary_check(): data = request.get_json() emotion_list=model.analyze_diary(data['diarycontent']) #활기차고 사랑스러운 if emotion_list=="ERROR": return "ERROR" emotion = emotion_rank(emotion_list) DiaryDAO.addDiary(data['diarycontent'], session['login'],data['date'], emotion, json.dumps(emotion_list)) return "" @app.route("/diary_manipulate", methods=['post']) def diary_manipulate(): data= request.get_json()#type, content, date if data['type']=='EDIT': emotion_list = model.analyze_diary(data['diarycontent']) if emotion_list=="ERROR": return "ERROR" emotion=emotion_rank(emotion_list) DiaryDAO.manipulate_diary("EDIT", session['login'],data['date'],data['diarycontent'], emotion, json.dumps(emotion_list)) else: DiaryDAO.manipulate_diary("DELETE", session['login'], data['date'],"","","") return "COMPLETE" @app.route("/plan_check", methods=['post']) def plan_check(): data = request.get_json() plan_keyword=model.analyze_plan(data['plancontent']) PlanDAO.addPlan(data['plancontent'],session['login'],data['date'],plan_keyword) return "" @app.route("/plan_manipulate", methods=['post']) def plan_manipulate(): data= request.get_json()#type, content, date if data['type']=='EDIT': plan_keyword = model.analyze_plan(data['plancontent']) if plan_keyword=="ERROR": return "ERROR" PlanDAO.manipulate_plan("EDIT", session['login'],data['date'],data['plancontent'], plan_keyword) else: PlanDAO.manipulate_plan("DELETE", session['login'], data['date'],"","") return "COMPLETE" if __name__ =='__main__': app.run(host='0.0.0.0') <file_sep>/README.md # Daysprit (데이스피릿) ## 두 단어의 유사도를 추정하는 인공신경망을 이용한 감정 분석 다이어리 <file_sep>/dao/MemberDAO.py import pymysql from dao import DBConnection def isExist(objectType, objectItem): cnt=0 conn = DBConnection.getConnection() try: cursor = conn.cursor() if objectType=="userId" : sql = "select * from member where id = %s" elif objectType == "userEmail" : sql = "select * from member where email= %s" cursor.execute(sql, objectItem) data = cursor.fetchall() # 만약 아이디가 기존에 존재하면 cnt++ for i in data: cnt = cnt+1 finally: conn.close() # isExist = 0 이면 존재하지 않는 아이디이기 때문에 회원가입 가능 return cnt def findInfo(findType, obj1, obj2): conn = DBConnection.getConnection() find=False try: cursor = conn.cursor() if findType == "ID": sql = "select id from member where name=%s and email=%s " else : sql = "select password from member where id=%s and email= %s" value=(obj1,obj2) cursor.execute(sql, value) data = cursor.fetchall() for i in data: find=i[0] finally: conn.close() print(find) return find def login(member): name = False; cnt=0 conn = DBConnection.getConnection() cursor = conn.cursor() sql = "select name from member where id=%s and password=%s" value=(member['id'], member['password']) cursor.execute(sql, value) data = cursor.fetchall() for i in data: cnt = cnt+1 conn.close() return cnt def signup(member): conn = DBConnection.getConnection() try: cursor = conn.cursor() sql = "insert into member values(%s, %s, %s, %s)" value = (member['id'], member['password'], member['name'], member['email']) cursor.execute(sql,value) data = cursor.fetchall() conn.commit() finally: conn.close() return "" <file_sep>/static/js/script.js function post_manipulate_plan(type) { var dateId = $(location).attr('search').slice($(location).attr('search').indexOf('=') + 1); let data = { 'type': type, 'plancontent': document.getElementById("plancontent").value, 'date': dateId }; fetch('/plan_manipulate', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(data) }) .then(res => res.text()) .then((res) => { if (res == "ERROR") alert("분석에 실패하였습니다."); else if (type == "DELETE") { alert("삭제가 완료되었습니다."); window.location.href = "/calendar"; } else { alert("수정이 완료되었습니다."); window.location.href = "/result_plan?date=" + dateId; } }).catch((err) => { console.error("에러: ", err); }); } function post_manipulate_diary(type) { var dateId = $(location).attr('search').slice($(location).attr('search').indexOf('=') + 1); let data = { 'type': type, 'diarycontent': document.getElementById("diarycontent").value, 'date': dateId }; fetch('/diary_manipulate', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(data) }) .then(res => res.text()) .then((res) => { if (res == "ERROR") alert("감정분석에 실패하였습니다."); else if (type == "DELETE") { alert("삭제가 완료되었습니다."); window.location.href = "/calendar"; } else { alert("수정이 완료되었습니다."); window.location.href = "/result_diary?date=" + dateId; } }).catch((err) => { console.error("에러: ", err); }); } function post_find_id() { let data = { 'userName': document.getElementById("find_userName").value, 'userEmail': document.getElementById("find_userEmail").value }; fetch('/check_find_id', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(data) }).then(res => res.text()) .then((res) => { alert("당신의 ID는 [" + res + "] 입니다"); }).catch((err) => { console.error("에러: ", err); }); } function post_find_pw() { let data = { 'userId': document.getElementById("find_userId").value, 'userEmail': document.getElementById("find_userEmail").value }; fetch('/check_find_pw', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(data) }).then(res => res.text()) .then((res) => { alert("당신의 PASSWORD는 [" + res + "] 입니다"); }).catch((err) => { console.error("에러: ", err); }); } function chk_same_mon(object1, object2, object3) { var arr = object1.split('-'); arr[0] *= 1; arr[1] *= 1; object2 *= 1; object3 *= 1; if (arr[0] == object2 && arr[1] == object3) return true; else return false; } function add_emoticon(cell, jsonData) { var cell_str, emo_str, emo, day, arr; var arr_str = jsonData.substring(1, jsonData.length - 1); arr = arr_str.split(','); for (var i = 0; i < (arr.length) / 2; i++) { cell_str = arr[i * 2].split(':')[1]; if (cell.id == cell_str.substring(1, cell_str.length - 1)) { emo_str = arr[i * 2 + 1].split(':')[1]; emo = emo_str.substring(1, emo_str.length - 2); day = cell_str.substring(1, cell_str.length - 1).split('-')[2]; cell.innerHTML = day + "<img src='." + emo + "'alt='' />"; } } } function add_emo(jsonData, year, month) { var cell_str, emo_str, cell, emo, day, arr; var arr_str = jsonData.substring(1, jsonData.length - 1); arr = arr_str.split(','); //arr = {'date':'','img':''} for (var i = 0; i < (arr.length) / 2; ++i) { cell_str = arr[i * 2].split(':')[1]; cell = cell_str.substring(1, cell_str.length - 1); //cell = 2020-05-27 emo_str = arr[i * 2 + 1].split(':')[1]; emo = emo_str.substring(1, emo_str.length - 2); //emo = /static/... if (chk_same_mon(cell, year, month)) { day = cell.split('-')[2]; document.getElementById(cell).innerHTML = day + "<img src='." + emo + "'alt='' />"; } } } var today = new Date(); var date = new Date(); function prevCalendar(jsonData) { today = new Date(today.getFullYear(), today.getMonth() - 1, today.getDate()); buildCalendar(jsonData); get_modal(); } function nextCalendar(jsonData) { today = new Date(today.getFullYear(), today.getMonth() + 1, today.getDate()); buildCalendar(jsonData); get_modal(); } function get_modal() { // 모달 버튼에 이벤트를 건다. $('.date').on('click', function () { $('#modalBox').modal('show'); post_dateId(this.id); }); // 모달 안의 취소 버튼에 이벤트를 건다. $('#closeModalBtn').on('click', function () { $('#modalBox').modal('hide'); }); $('#diary_res').on('click', function () { $('#modalBox').modal('show'); post_dateId(this.id); }); $('#closeModalBtn').on('click', function () { $('#modalBox').modal('hide'); }); } function buildCalendar(jsonData) { var doMonth = new Date(today.getFullYear(), today.getMonth(), 1); var lastDate = new Date(today.getFullYear(), today.getMonth() + 1, 0); var tbCalendar = document.getElementById("calendar"); var tbCalendarYM = document.getElementById("tbCalendarYM"); if ((today.getMonth() + 1) == 1) { tbCalendarYM.innerHTML = "January " + today.getFullYear(); } else if ((today.getMonth() + 1) == 2) { tbCalendarYM.innerHTML = "February " + today.getFullYear(); } else if ((today.getMonth() + 1) == 3) { tbCalendarYM.innerHTML = "March " + today.getFullYear(); } else if ((today.getMonth() + 1) == 4) { tbCalendarYM.innerHTML = "April " + today.getFullYear(); } else if ((today.getMonth() + 1) == 5) { tbCalendarYM.innerHTML = "May " + today.getFullYear(); } else if ((today.getMonth() + 1) == 6) { tbCalendarYM.innerHTML = "June " + today.getFullYear(); } else if ((today.getMonth() + 1) == 7) { tbCalendarYM.innerHTML = "July " + today.getFullYear(); } else if ((today.getMonth() + 1) == 8) { tbCalendarYM.innerHTML = "August " + today.getFullYear(); } else if ((today.getMonth() + 1) == 9) { tbCalendarYM.innerHTML = "September " + today.getFullYear(); } else if ((today.getMonth() + 1) == 10) { tbCalendarYM.innerHTML = "February " + today.getFullYear(); } else if ((today.getMonth() + 1) == 11) { tbCalendarYM.innerHTML = "November " + today.getFullYear(); } else if ((today.getMonth() + 1) == 12) { tbCalendarYM.innerHTML = "December " + today.getFullYear(); } while (tbCalendar.rows.length > 2) { tbCalendar.deleteRow(tbCalendar.rows.length - 1); } var row = null; row = tbCalendar.insertRow(); var cnt = 0; for (i = 0; i < doMonth.getDay(); i++) { cell = row.insertCell(); cnt = cnt + 1; } /*달력 출력*/ for (i = 1; i <= lastDate.getDate(); i++) { cell = row.insertCell(); cell.innerHTML = i; cell.classList.add("date"); if ((today.getMonth() + 1) > 0 && (today.getMonth() + 1) < 10 && i > 0 && i < 10) { cell.id = today.getFullYear() + "-0" + (today.getMonth() + 1) + "-0" + i; } else if ((today.getMonth() + 1) > 9 && i > 0 && i < 10) { cell.id = today.getFullYear() + "-" + (today.getMonth() + 1) + "-0" + i; } else if ((today.getMonth() + 1) > 0 && (today.getMonth() + 1) < 10 && i > 9) { cell.id = today.getFullYear() + "-0" + (today.getMonth() + 1) + "-" + i; } else { cell.id = today.getFullYear() + "-" + (today.getMonth() + 1) + "-" + i; } cnt = cnt + 1; if (cnt % 7 == 1) { cell.style.color = "#F79DC2" //1번째의 cell에만 색칠 } if (cnt % 7 == 0) { cell.style.color = "skyblue" row = calendar.insertRow(); } if (jsonData.length != 2) add_emoticon(cell, jsonData); } // add_emo(jsonData, today.getFullYear().toString(), today.getMonth().toString()); } // #header-iframe 배경 바뀌는 함수 수정! function chg_if_bg() { parent.document.getElementById('header-iframe').style.background = "url('static/img/header_bg_half.png'), url('static/img/header_bg_navy.png')"; parent.document.getElementById('header-iframe').style.backgroundPosition = "bottom right, bottom"; parent.document.getElementById('header-iframe').style.backgroundRepeat = "no-repeat, no-repeat"; if (parent.screen.width < 767.98) { parent.document.getElementById('header-iframe').style.backgroundSize = "auto 16.25em, contain"; } else if (parent.screen.width >= 768 && parent.screen.width <= 1024) { parent.document.getElementById('header-iframe').style.backgroundSize = "auto 27.5em, contain"; } else { parent.document.getElementById('header-iframe').style.backgroundSize = "auto 33em, contain"; } }; function chg_if_bg_def() { parent.document.getElementById('header-iframe').style.background = "url('static/img/header_bg.png'), url('static/img/header_bg_navy.png')"; parent.document.getElementById('header-iframe').style.backgroundPosition = "bottom right, bottom"; parent.document.getElementById('header-iframe').style.backgroundRepeat = "no-repeat, no-repeat"; if (parent.screen.width < 767.98) { parent.document.getElementById('header-iframe').style.backgroundSize = "17.5em auto, contain"; } else if (parent.screen.width >= 768 && parent.screen.width <= 1024) { parent.document.getElementById('header-iframe').style.backgroundSize = "33.5em auto, contain"; } else { parent.document.getElementById('header-iframe').style.backgroundSize = "auto 32.5em, contain"; } }; function post_dup_chk(objectId) { let data = { 'objectId': objectId, 'object': document.getElementById(objectId).value }; fetch('/check_dup_chk', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(data) }).then(res => res.text()) .then((res) => { alert(res); }).catch((err) => { console.error("에러: ", err); }); } function post_login() { let data = { 'loginId': document.getElementById("loginId").value, 'loginPw': document.getElementById("loginPw").value }; fetch('/sign_in_check', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(data) }) .then(res => res.text()) .then((res) => { if(res=="FAILED") alert("[로그인실패]아이디 혹은 패스워드를 확인하십시오."); }).catch((err) => { console.error("에러: ", err); }).finally(() => { window.parent.location.href = "/current"; }); } function post_signup() { let data = { 'userName': document.getElementById("userName").value, 'userEmail': document.getElementById("userEmail").value, 'userId': document.getElementById("userId").value, 'userPw': document.getElementById("userPw").value, 'userPwCheck': document.getElementById("userPwCheck").value }; fetch('/sign_up_check', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(data) }).then(res => res.json()) .then((res) => { alert("회원가입에 성공하였습니다."); console.log("성공: ", res); }).catch((err) => { console.error("에러: ", err); }).finally(() => { window.parent.location.href = "/"; }); } function post_dateId(dateId) { var opt1 = document.getElementById('diary_select'); var opt2 = document.getElementById('plan_select'); opt1.addEventListener('click', function () { window.location.href = "/diary?date=" + dateId; }); opt2.addEventListener('click', function () { window.location.href = "/plan?date=" + dateId; }); } function post_diary() { var dateId = $(location).attr('search').slice($(location).attr('search').indexOf('=') + 1); let data = { 'diarycontent': document.getElementById("diarycontent").value, 'date': dateId }; fetch('/diary_check', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(data) }) .then(res => res.text()) .then((res) => { if (res == "ERROR") alert("감정분석이 불가능합니다."); else{ alert("다이어리 입력 완료"); window.location.href = "/result_diary?date=" + dateId; } }).catch((err) => { console.error("에러: ", err); }); } function post_plan() { var dateId = $(location).attr('search').slice($(location).attr('search').indexOf('=') + 1); let data = { 'date': dateId, 'plancontent': document.getElementById("plancontent").value }; // wait_res('plan'); fetch('/plan_check', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(data) }).then(res => res.text()) .then((res) => { if (res == "ERROR") alert("분석이 불가능합니다."); else{ alert("계획 입력 완료"); window.location.href = "/result_plan?date=" + dateId; } }).catch((err) => { console.error("에러: ", err); }); } $(document).ready(function () { var btn = document.getElementsByClassName('chk_btn'); for (var i = 0; btn.length; ++i) { btn[i].addEventListener('click', function () { var arr = (this.id).split('_'); post_dup_chk(arr[0]); }); } }); $(document).ready(function () { var btn = document.getElementById('login_btn'); btn.addEventListener('click', function () { post_login(); }); }); $(document).ready(function () { var btn = document.getElementById('signup_btn'); btn.addEventListener('click', function () { post_signup(); }); }); $(document).ready(function () { var val = location.href.substr( location.href.lastIndexOf('=') + 1 ); var btn = document.getElementById('diary_sv_btn'); btn.addEventListener('click', function () { post_diary(); }); }); $(document).ready(function () { var val = location.href.substr( location.href.lastIndexOf('=') + 1 ); var btn = document.getElementById('plan_sv_btn'); btn.addEventListener('click', function () { post_plan(); }); }); $(document).ready(function () { var val = location.href.substr( location.href.lastIndexOf('=') + 1 ); var btn = document.getElementById('find_id_btn'); btn.addEventListener('click', function () { post_find_id(); }); }); $(document).ready(function () { var val = location.href.substr( location.href.lastIndexOf('=') + 1 ); var btn = document.getElementById('find_pw_btn'); btn.addEventListener('click', function () { post_find_pw(); }); }); $(document).ready(function () { var val = location.href.substr( location.href.lastIndexOf('=') + 1 ); var btn = document.getElementById('diary_edit_btn'); btn.addEventListener('click', function () { post_manipulate_diary("EDIT"); }); }); $(document).ready(function () { var val = location.href.substr( location.href.lastIndexOf('=') + 1 ); var btn = document.getElementById('diary_del_btn'); btn.addEventListener('click', function () { post_manipulate_diary("DELETE"); }); }); $(document).ready(function () { var val = location.href.substr( location.href.lastIndexOf('=') + 1 ); var btn = document.getElementById('plan_edit_btn'); btn.addEventListener('click', function () { post_manipulate_plan("EDIT"); }); }); $(document).ready(function () { var val = location.href.substr( location.href.lastIndexOf('=') + 1 ); var btn = document.getElementById('plan_del_btn'); btn.addEventListener('click', function () { post_manipulate_plan("DELETE"); }); }); <file_sep>/dao/PlanDAO.py import pymysql from dao import DBConnection def manipulate_plan(_type, loginId, date, content, keyword): conn = DBConnection.getConnection() month=int(date[5:7]) try: cursor = conn.cursor() if _type=="EDIT": if(month>=3 and month <6): sql = "update plan set content=%s, colorId=(select color from spring where name=%s) where memberId=%s and date=%s" elif (month>=6 and month<9): sql = "update plan set content=%s, colorId=(select color from summer where name=%s) where memberId=%s and date=%s" elif (month >=9 and month <12): sql = "update plan set content=%s, colorId=(select color from fall where name=%s) where memberId=%s and date=%s" else: sql = "update plan set content=%s, colorId=(select color from winter where name=%s) where memberId=%s and date=%s" value = (content, keyword, loginId, date) else: sql = "delete from plan where memberId=%s and date=%s" value=(loginId, date) cursor.execute(sql,value) data = cursor.fetchall() conn.commit() finally: conn.close() return "" def getColor(date, loginId): conn = DBConnection.getConnection() find=False; try: cursor = conn.cursor() sql = "select colorImg from color, plan where color.colorId=plan.colorId and plan.date=%s and plan.memberId=%s" value=(date, loginId) cursor.execute(sql, value) data = cursor.fetchall() for i in data: find = i[0] finally: conn.close() return find def addPlan(content, loginId, date, keyword): conn = DBConnection.getConnection() month=int(date[5:7]) try: cursor = conn.cursor() if(month>=3 and month <6): sql = "insert into plan(content, memberId, date, colorId) values(%s,%s,%s,(select color from spring where name=%s))" elif (month>=6 and month<9): sql = "insert into plan(content, memberId, date, colorId) values(%s,%s,%s,(select color from summer where name=%s))" elif (month >=9 and month <12): sql = "insert into plan(content, memberId, date, colorId) values(%s,%s,%s,(select color from fall where name=%s))" else: sql = "insert into plan(content, memberId, date, colorId) values(%s,%s,%s,(select color from winter where name=%s))" value=(content, loginId, date, keyword) cursor.execute(sql,value) data = cursor.fetchall() conn.commit() print("계획이 추가되었습니다") finally: conn.close() return "" def isExistPlan(date, loginId): content=False conn = DBConnection.getConnection() try: cursor = conn.cursor() sql="select content from plan where date=%s and memberId=%s" value=(date, loginId) cursor.execute(sql, value) data = cursor.fetchall() # 만약 다이어리가 존재하면 cnt++ for i in data: content=i[0] finally: conn.close() #다이어리가 존재하지 않으면 False를 반환 return content
dba99ba5593279a351ec91ee924ab779e8f3c11e
[ "Markdown", "Python", "JavaScript" ]
8
Python
hanjiwon1/Capstone_Dayspirit
2f34e7c92c90c2bdfded24fff278b08a61097c81
f92f34a642a15c309e41a2b9fb4c530cf1793453
refs/heads/master
<file_sep><?php defined('BASEPATH') OR exit('No direct script access allowed'); class Datagathering extends CI_Controller { public function __construct() { parent::__construct(); $this->load->model('Datagathering_model', 'nbdata'); } /** * Function to gather zip files. Currently hard coded to button post, but each button can be linked to a * different URL, or input could be adjusted to a function call with a url input * */ public function downloadZipFile() { set_time_limit(2400); $urls = $this->nbdata->getDataUrls(); if(isset($urls) && $urls != null) { foreach($urls->result() as $key => $value) { $filename = './uploads/' . $value->name . '-eng.zip'; if (file_exists($filename)) { chmod($filename, 0777); //flock($filename, LOCK_UN); unlink($filename); } //$filepath = './uploads/02820002-eng.zip'; $fp_header = './uploads/' . $value->name . '-header_data.txt'; $ch = curl_init($value->url); curl_setopt($ch, CURLOPT_HEADER, 1); curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); curl_setopt($ch, CURLOPT_BINARYTRANSFER, 1); curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 0); $raw_file_data = curl_exec($ch); //get header data to compare for last update $header_size = curl_getinfo($ch, CURLINFO_HEADER_SIZE); $header = substr($raw_file_data, 0, $header_size); $body = substr($raw_file_data, $header_size); if(curl_errno($ch)){ echo 'error:' . curl_error($ch); } curl_close($ch); file_put_contents($filename, $body); file_put_contents($fp_header, $header); $header_data = array ( 'header' => $fp_header, 'source_id' => $value->id, 'name' => $value->name ); $file_data = $this->processHeaderText($header_data); if($file_data) { // if exists, process file if (filesize($filename) > 0) { $data = array( 'filepath' => $filename, 'name' => $value->name, 'source_id' => $value->id ); $processed_csv = $this->processZipFile($data); if($processed_csv) { $result = $this->nbdata->processZipFile($file_data); if($result > 0) { echo $result . ' records saved for file ' . $value->name .' '; } else { echo 'File current. 0 new records processed for ' . $value->name; } } else { echo 'Error processing ' . $value->name . ' csv'; } } else { echo 'Error: ' . $value->name . ' contains no data'; } } } } else { echo 'Error retrieving URLs'; } } /** * Unzip the source_file in the destination dir * * @param string The path to the ZIP-file. * @param string The path where the zipfile should be unpacked, if false the directory of the zip-file * is used * @param boolean Indicates if the files will be unpacked in a directory with the name of the zip-file (true) * or not (false) (only if the destination directory is set to false!) * @param boolean Overwrite existing files (true) or not (false) * * @return boolean Succesful or not */ function processZipFile($data, $dest_dir=false, $create_zip_name_dir=true, $overwrite=true) { ini_set('memory_limit','2000M'); set_time_limit(600); if ($zip = zip_open($data['filepath'])) { if (is_resource($zip)) { $splitter = ($create_zip_name_dir === true) ? "." : "/"; if ($dest_dir === false) $dest_dir = substr($data['filepath'], 0, strrpos($data['filepath'], $splitter))."/"; // Create the directories to the destination dir if they don't already exist $this->create_dirs($dest_dir); // For every file in the zip-packet while ($zip_entry = zip_read($zip)) { // Now we're going to create the directories in the destination directories // If the file is not in the root dir $pos_last_slash = strrpos(zip_entry_name($zip_entry), "/"); if ($pos_last_slash !== false) { // Create the directory where the zip-entry should be saved (with a "/" at the end) $this->create_dirs($dest_dir.substr(zip_entry_name($zip_entry), 0, $pos_last_slash+1)); } // Open the entry if (zip_entry_open($zip,$zip_entry,"r")) { // The name of the file to save on the disk $file_name = $dest_dir.zip_entry_name($zip_entry); // Check if the files should be overwritten or not if ($overwrite === true || $overwrite === false && !is_file($file_name)) { // Get the content of the zip entry $fstream = zip_entry_read($zip_entry, zip_entry_filesize($zip_entry)); // Convert to UTF-8 for further processing $cleaned = mb_convert_encoding($fstream, 'UTF-8', 'ISO-8859-1'); file_put_contents($file_name, $cleaned); // Set the rights chmod($file_name, 0777); //echo "save: ".$file_name."<br />"; } // Close the entry zip_entry_close($zip_entry); } } // Close the zip-file zip_close($zip); } else { $data = array ( 'heading' => 'Zip Error', 'message' => 'There was an error with the Zip file, please try again' ); redirect(base_url('Gather/error'), $data); } } else { $data = array ( 'heading' => 'Zip Error', 'message' => 'There was an error with the Zip file, please try again' ); redirect(base_url('Gather/error'), $data); } $csv = './uploads/'. $data['name'] .'-eng/' . $data['name'] . '-eng.csv'; $csv_pack = array( 'csv' => $csv, 'name' => $data['name'], 'source_id' => $data['source_id'] ); if(file_exists($csv)) { $processed_csv = $this->processCsv($csv_pack); if($processed_csv) { return true; } } else { return false; } } /** * This function creates recursive directories if it doesn't already exist * * @param String The path that should be created * * @return void */ function create_dirs($path) { if (!is_dir($path)) { $directory_path = ""; $directories = explode("/",$path); array_pop($directories); foreach($directories as $directory) { $directory_path .= $directory."/"; if (!is_dir($directory_path)) { mkdir($directory_path); chmod($directory_path, 0777); } } } } /** * Function takes a CSV and processes it to remove not relevant entries ($age). * @param $csv * @param $age * @return bool */ function processCsv($csv_pack, $age = 12) { set_time_limit(1200); $cutoffYear = (int)date('Y') - $age; $outfile = './uploads/' . $csv_pack['name'] . '-eng/' . $csv_pack['name'] . '.csv'; if (file_exists($outfile)) { chmod($outfile, 0766); //flock($outfile, LOCK_UN); unlink($outfile); } if(($handle = fopen($csv_pack['csv'], 'r')) !== false) { $csv = new SplFileObject($csv_pack['csv']); $csv->setFlags(SplFileObject::READ_CSV); $start = 0; $batch = 1000000; $output = fopen('./uploads/' . $csv_pack['name'] .'-eng/' . $csv_pack['name'] . '.csv', 'w'); // get the first row, which contains the column-titles (if necessary) $header = fgetcsv($handle); array_push($header, 'hash_value'); fputcsv($output, $header); while (!$csv->eof()) { foreach (new LimitIterator($csv, $start, $batch) as $line) { //get line and ensure first entry is cast as int for comparison $year = (int)$line[0]; //verify within year range if (!($year <= $cutoffYear)) { $data = $line; //create unique record for each line $hash = hash('md5', implode($line)); array_push($data, $hash); fputcsv($output, $data); } } $start += $batch; chmod($outfile, 0766); } return true; } else { return false; } } /** * Reads header file data and creates a unique hash code based on length and date created. Then checks it against * the database of hash records. If the hash exists, the process exits. Otherwise it goes to the next stage of * processing * @param $header * @return bool|string */ function processHeaderText($header_data) { $file = $header_data['header']; $fopen = fopen($file, 'r'); $fread = fread($fopen,filesize($file)); fclose($fopen); $remove = "\n"; $split = explode($remove, $fread); $array[] = null; $colon = ":"; foreach ($split as $string) { $row = explode($colon, $string, 2); array_push($array,$row); } $save_data = ""; foreach($array as $value) { switch ($value[0]) { case "Last-Modified": $save_data .= $value[1] . ','; $last_modified = $value[1]; break; case "Content-Length": $save_data .= $value[1]; break; } } $header_hash = hash('md5', $save_data); $file_data = array ( 'last_modified' => $header_hash, 'source_id' => $header_data['source_id'], 'file_path' => './uploads/' . $header_data['name'] .'-eng/' . $header_data['name'] . '.csv', 'name' => $header_data['name'] ); //check for existing hash $last_processed = $this->nbdata->getLastProcessed($header_hash); if($last_processed == null ) { return $file_data; } else { $exists_data = array ('last_modified' => null, 'source_id' => $header_data['source_id']); $this->nbdata->saveLastProcessed($exists_data); echo 'A current record already exists for ' . $header_data['name'] . '. Last modified on ' . $last_modified . '. The database has been updated with scan date.' . "\r\n"; return false; } } } <file_sep><?php defined('BASEPATH') OR exit('No direct script access allowed'); class Charts extends CI_Controller { public function __construct() { parent::__construct(); $this->load->model('Datagathering_model', 'nbdata'); } public function selectChart() { $this->load->view('select_chart'); } public function participation() { $this->form_validation->set_rules('date', 'Date', 'required|min_length[7]|max_length[7]'); if ($this->form_validation->run() == TRUE) { $date = $this->input->post('date'); $data['participation'] = $this->nbdata->getParticipationRate($date); $data['participation_mm'] = $this->nbdata->getParticipationRateMM($date); } if(isset($data)) { $this->load->view('participation', $data); } } public function participationMM() { $this->form_validation->set_rules('startdate', 'Start Date', 'required|min_length[7]|max_length[7]'); $this->form_validation->set_rules('enddate', 'End Date', 'required|min_length[7]|max_length[7]'); if ($this->form_validation->run() == TRUE) { $startdate = $this->input->post('startdate'); $enddate = $this->input->post('enddate'); $dates = array ( 'startdate' => $startdate, 'enddate' => $enddate ); $data['participation_mm'] = $this->nbdata->getParticipationRateMM($dates); } if(isset($data)) { $this->load->view('participation', $data); } } public function participationYY() { $this->form_validation->set_rules('startyear', 'Start Year', 'required|min_length[4]|max_length[4]'); $this->form_validation->set_rules('startmonth', 'Start Month', 'required|min_length[2]|max_length[2]'); if ($this->form_validation->run() == TRUE) { $startyear = $this->input->post('startyear'); $startmonth = $this->input->post('startmonth'); $startdate = $startyear . '/' .$startmonth; $enddate = ((int)$startyear + 1) . '/' . $startmonth; $dates = array ( 'startdate' => $startdate, 'enddate' => $enddate ); $data['participation_yy'] = $this->nbdata->getParticipationRateYY($dates); } if(isset($data)) { $this->load->view('participation', $data); } } public function getAllParticipationCharts() { $this->form_validation->set_rules('startyear', 'Start Year', 'required|min_length[4]|max_length[4]'); $this->form_validation->set_rules('startmonth', 'Start Month', 'required|min_length[2]|max_length[2]|callback_monthCheck'); if ($this->form_validation->run() == TRUE) { $startyear = $this->input->post('startyear'); $startmonth = $this->input->post('startmonth'); // dates for y-y $startdate = $startyear . '/' .$startmonth; $enddate = ((int)$startyear - 1) . '/' . $startmonth; $dates = array ( 'startdate' => $enddate, 'enddate' => $startdate ); // dates for m-m if($startmonth <= 12 && $startmonth > 1) { $mo = $startmonth - 1; $mmDates = array( 'startdate' => $startyear . '/' . $startmonth, 'enddate' => $startyear . '/' . $mo ); } elseif($startmonth == 1) { $mo = 12; $yr = $startyear - 1; $mmDates = array( 'startdate' => $startyear . '/' . $startmonth, 'enddate' => $yr . '/' . $mo ); } // dates for Unemployment m-m if($startmonth <= 12 && $startmonth > 1) { $mo = $startmonth - 1; $urMmDates = array( 'startdate' => $startyear . '/' . $mo, 'enddate' => $startyear . '/' . $startmonth ); } elseif($startmonth == 1) { $mo = 12; $yr = $startyear - 1; $urMmDates = array( 'startdate' => $yr . '/' . $mo, 'enddate' => $startyear . '/' . $startmonth ); } // alternative dates for Employment Rate $erDates = array ( 'startdate' => $startdate, 'enddate' => $enddate, 'characteristics' => 'Employment (x 1,000)', 'datatype' => 'Seasonally adjusted' ); //alternative dates for Employment Rate m-m - Trying to find what data is being pulled if($startmonth <= 12 && $startmonth > 1) { $mo = $startmonth - 1; $erMMDates = array( 'startdate' => $startyear . '/' . $startmonth, 'enddate' => $startyear . '/' . $mo, 'characteristics' => 'Employment (x 1,000)', 'datatype' => 'Seasonally adjusted' ); } elseif($startmonth == 1) { $mo = 12; $yr = $startyear - 1; $erMMDates = array( 'startdate' => $startyear . '/' . $startmonth, 'enddate' => $yr . '/' . $mo, 'characteristics' => 'Employment (x 1,000)', 'datatype' => 'Seasonally adjusted' ); } // dates for 10 year growth $endyear = ((int)$startyear - 10) . '/' . $startmonth; $dataGrowth = array( 'startdate' => $startdate, 'enddate' => $endyear, 'characteristics' => 'Employment (x 1,000)', 'datatype' => 'Seasonally adjusted' ); $dataParticipation = array ( 'date' => $startdate, 'characteristics' => 'Participation rate (percent)' ); $dataUnemployment = array ( 'date' => $startdate, 'characteristics' => 'Unemployment rate (percent)' ); $dataUR_MM = $urMmDates; $dataUR_MM['characteristics'] = 'Unemployment rate (percent)'; $dataUR_MM['datatype'] = 'Seasonally adjusted'; $dataUR_YY = $dates; $dataUR_YY['characteristics'] = 'Unemployment rate (percent)'; $dataUR_YY['datatype'] = 'Seasonally adjusted'; $dataPR_MM = $mmDates; $dataPR_MM['characteristics'] = 'Participation rate (percent)'; $dataPR_MM['datatype'] = 'Seasonally adjusted'; $dataPR_YY = $dates; $dataPR_YY['characteristics'] = 'Participation rate (percent)'; $dataPR_YY['datatype'] = 'Seasonally adjusted'; // Common to all queries $common_settings = array ('agegroup' => '15 years and over', 'sex' => 'Both sexes', 'statistics' => 'Estimate' ); foreach($common_settings as $key => $value) { $erDates[$key] = $value; $dataGrowth[$key] = $value; $erMMDates[$key] = $value; $dataUR_MM[$key] = $value; $dataUR_YY[$key] = $value; $dataPR_MM[$key] = $value; $dataPR_YY[$key] = $value; } $data['participation_yy'] = $this->nbdata->getComparisonBarChart($dataPR_YY); $data['participation'] = $this->nbdata->getBarChart($dataParticipation); $data['participation_mm'] = $this->nbdata->getComparisonBarChart($dataPR_MM); $data['employment_mm'] = $this->nbdata->getEmploymentRate($erMMDates); $data['employment_yy'] = $this->nbdata->getEmploymentRate($erDates); $data['employment_ur'] = $this->nbdata->getBarChart($dataUnemployment); $data['employment_urMM'] = $this->nbdata->getComparisonBarChart($dataUR_MM); $data['employment_urYY'] = $this->nbdata->getComparisonBarChart($dataUR_YY); $data['growth_10yr'] = $this->nbdata->getEmploymentRate($dataGrowth); } if(isset($data)) { $this->load->view('participation', $data); } } public function getLabourForceCharts() { $this->form_validation->set_rules('startyear', 'Start Year', 'required|min_length[4]|max_length[4]'); $this->form_validation->set_rules('startmonth', 'Start Month', 'required|min_length[2]|max_length[2]|callback_monthCheck'); if ($this->form_validation->run() == TRUE) { $startyear = $this->input->post('startyear'); $startmonth = $this->input->post('startmonth'); // for Month to Month trends $MM = array(); if ($startmonth <= 12 && $startmonth >= 1) { $month = $startmonth; $yr = $startyear; for ($i = 0; $i <= 13; $i++) { if ($month > 0) { $mo_padded = sprintf('%02d', $month); $MM[$i] = $yr . '/' . $mo_padded; $month--; } else { $month = 12; $yr--; } } } // for Year to Year trends $YY = array(); if ($startmonth <= 12 && $startmonth >= 1) { $month = $startmonth; $yr = $startyear; for ($i = 0; $i <= 9; $i++) { $mo_padded = sprintf('%02d', $month); $YY[$i] = $yr . '/' . $mo_padded; $yr--; } } // for Year over year and last month to current month data table $mo = $startmonth - 1; if($mo == 0) { $mo = 12; } if($startmonth == 1) { $prevMonthYear = $startyear -1; } else { $prevMonthYear = $startyear; } $mo_pad = sprintf('%02d', $startmonth); $dataTable = array ( 'startyear' => $startyear . '/' . $mo_pad, 'prevyear' => ($startyear - 1) . '/' . $mo_pad, 'prevmonth' => $prevMonthYear . '/' . sprintf( '%02d', $mo), 'characteristics' => array ( 'Population (x 1,000)', 'Labour force (x 1,000)', 'Employment (x 1,000)', 'Employment full-time (x 1,000)', 'Employment part-time (x 1,000)', 'Unemployment (x 1,000)', 'Participation rate (percent)', 'Employment rate (percent)', 'Unemployment rate (percent)' ), 'math_array' => array ( 'Population (x 1,000)', 'Labour force (x 1,000)', 'Employment (x 1,000)', 'Employment full-time (x 1,000)', 'Employment part-time (x 1,000)', 'Unemployment (x 1,000)' ) ); $dataLF_MM = array ( 'where_in' => $MM, 'characteristics' => 'Labour force (x 1,000)' ) ; $dataLF_YY = array ( 'where_in' => $YY, 'characteristics' => 'Labour force (x 1,000)' ); $dataEM_MM = array ( 'where_in' => $MM, 'characteristics' => 'Employment (x 1,000)' ); $dataEM_YY = array ( 'where_in' => $YY, 'characteristics' => 'Employment (x 1,000)' ); $dataUM_MM = array ( 'where_in' => $MM, 'characteristics' => 'Unemployment rate (percent)' ); $dataUM_YY = array ( 'where_in' => $YY, 'characteristics' => 'Unemployment rate (percent)' ); $dateObj = DateTime::createFromFormat('!m', $startmonth); $monthName = $dateObj->format('F'); $data['labour_force_statistics'] = array( 'data' => $this->nbdata->getLabourForceStatistics($dataTable), 'date' => $monthName . ' ' . $startyear); $data['labour_force_mm'] = $this->nbdata->getLabourForceData($dataLF_MM); $data['labour_force_yy'] = $this->nbdata->getLabourForceData($dataLF_YY); $data['employment_mm'] = $this->nbdata->getLabourForceData($dataEM_MM); $data['employment_yy'] = $this->nbdata->getLabourForceData($dataEM_YY); $data['unemployment_mm'] = $this->nbdata->getLabourForceData($dataUM_MM); $data['unemployment_yy'] = $this->nbdata->getLabourForceData($dataUM_YY); } if (isset($data)) { $this->load->view('labour_force', $data); } } function monthCheck($num) { if($num > 12 || $num < 1) { $this->form_validation->set_message( 'startmonth', 'The %s field must be a valid month' ); return FALSE; } else { return TRUE; } } }<file_sep>CREATE TABLE `02820087` ( `ref_date` varchar(20) DEFAULT NULL, `geography` varchar(255) DEFAULT NULL, `characteristics` varchar(255) DEFAULT NULL, `sex` varchar(255) DEFAULT NULL, `agegroup` varchar(255) DEFAULT NULL, `statistics` varchar(255) DEFAULT NULL, `datatype` varchar(255) DEFAULT NULL, `vector` varchar(50) DEFAULT NULL, `coordinate` varchar(50) DEFAULT NULL, `value` decimal(10,1) DEFAULT NULL, `hash_value` varchar(255) NOT NULL, PRIMARY KEY (`hash_value`), KEY `hash_value` (`hash_value`), KEY `ref_date` (`ref_date`), KEY `character` (`characteristics`), KEY `geo` (`geography`), KEY `sex` (`sex`), KEY `age` (`agegroup`), KEY `stats` (`statistics`), KEY `datatype` (`datatype`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8; CREATE TABLE `02820002` ( `ref_date` varchar(20) DEFAULT NULL, `geography` varchar(255) DEFAULT NULL, `characteristics` varchar(255) DEFAULT NULL, `sex` varchar(255) DEFAULT NULL, `agegroup` varchar(255) DEFAULT NULL, `vector` varchar(50) DEFAULT NULL, `coordinate` varchar(50) DEFAULT NULL, `value` DECIMAL (10,1) DEFAULT NULL, `hash_value` varchar(255) NOT NULL, PRIMARY KEY (`hash_value`), KEY `hash_value` (`hash_value`), KEY `ref_date` (`ref_date`), KEY `character` (`characteristics`), KEY `geo` (`geography`), KEY `sex` (`sex`), KEY `age` (`agegroup`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8; CREATE TABLE `02820008` ( `ref_date` varchar(20) DEFAULT NULL, `geography` varchar(255) DEFAULT NULL, `characteristics` varchar(255) DEFAULT NULL, `industry` varchar(255) DEFAULT NULL, `sex` varchar(255) DEFAULT NULL, `age` varchar(255) DEFAULT NULL, `vector` varchar(50) DEFAULT NULL, `coordinate` varchar(50) DEFAULT NULL, `value` DECIMAL (10,1) DEFAULT NULL, `hash_value` varchar(255) NOT NULL, PRIMARY KEY (`hash_value`), KEY `hash_value` (`hash_value`), KEY `ref_date` (`ref_date`), KEY `character` (`characteristics`), KEY `geo` (`geography`), KEY `sex` (`sex`), KEY `age` (`age`), KEY `industry` (`industry`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8; CREATE TABLE `02820088` ( `ref_date` varchar(20) DEFAULT NULL, `geography` varchar(255) DEFAULT NULL, `industry` varchar(255) DEFAULT NULL, `statistics` varchar(255) DEFAULT NULL, `datatype` varchar(255) DEFAULT NULL, `vector` varchar(50) DEFAULT NULL, `coordinate` varchar(50) DEFAULT NULL, `value` DECIMAL (10,1) DEFAULT NULL, `hash_value` varchar(255) NOT NULL, PRIMARY KEY (`hash_value`), KEY `hash_value` (`hash_value`), KEY `ref_date` (`ref_date`), KEY `geo` (`geography`), KEY `stats` (`statistics`), KEY `datatype` (`datatype`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8; CREATE TABLE `02820122` ( `ref_date` varchar(20) DEFAULT NULL, `geo` varchar(255) DEFAULT NULL, `geographical_classification` varchar(255) DEFAULT NULL, `characteristics` varchar(255) DEFAULT NULL, `statistics` varchar(255) DEFAULT NULL, `vector` varchar(50) DEFAULT NULL, `coordinate` varchar(50) DEFAULT NULL, `value` DECIMAL (10,1) DEFAULT NULL, `hash_value` varchar(255) NOT NULL, PRIMARY KEY (`hash_value`), KEY `hash_value` (`hash_value`), KEY `ref_date` (`ref_date`), KEY `character` (`characteristics`), KEY `geo` (`geo`), KEY `stats` (`statistics`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8; CREATE TABLE `02820123` ( `ref_date` varchar(20) DEFAULT NULL, `geo` varchar(255) DEFAULT NULL, `geographical_classification` varchar(255) DEFAULT NULL, `characteristics` varchar(255) DEFAULT NULL, `vector` varchar(50) DEFAULT NULL, `coordinate` varchar(50) DEFAULT NULL, `value` DECIMAL (10,1) DEFAULT NULL, `hash_value` varchar(255) NOT NULL, PRIMARY KEY (`hash_value`), KEY `hash_value` (`hash_value`), KEY `ref_date` (`ref_date`), KEY `character` (`characteristics`), KEY `geo` (`geo`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8; CREATE TABLE `02820128` ( `ref_date` varchar(20) DEFAULT NULL, `geo` varchar(255) DEFAULT NULL, `geographical_classification` varchar(255) DEFAULT NULL, `characteristics` varchar(255) DEFAULT NULL, `sex` varchar(255) DEFAULT NULL, `agegroup` varchar(255) DEFAULT NULL, `vector` varchar(50) DEFAULT NULL, `coordinate` varchar(50) DEFAULT NULL, `value` DECIMAL (10,1) DEFAULT NULL, `hash_value` varchar(255) NOT NULL, PRIMARY KEY (`hash_value`), KEY `hash_value` (`hash_value`), KEY `ref_date` (`ref_date`), KEY `character` (`characteristics`), KEY `geo` (`geo`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8; CREATE TABLE `02820129` ( `ref_date` varchar(20) DEFAULT NULL, `geo` varchar(255) DEFAULT NULL, `geographical_classification` varchar(255) DEFAULT NULL, `characteristics` varchar(255) DEFAULT NULL, `sex` varchar(255) DEFAULT NULL, `agegroup` varchar(255) DEFAULT NULL, `vector` varchar(50) DEFAULT NULL, `coordinate` varchar(50) DEFAULT NULL, `value` DECIMAL (10,1) DEFAULT NULL, `hash_value` varchar(255) NOT NULL, PRIMARY KEY (`hash_value`), KEY `hash_value` (`hash_value`), KEY `ref_date` (`ref_date`), KEY `character` (`characteristics`), KEY `geo` (`geo`), KEY `sex` (`sex`), KEY `age` (`agegroup`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8; CREATE TABLE `nbdata_sources` ( `id` int(6) unsigned NOT NULL AUTO_INCREMENT, `url` VARCHAR(255) DEFAULT NULL, `name` VARCHAR(50) DEFAULT NULL, `current_version` VARCHAR(255) DEFAULT NULL, PRIMARY KEY (`id`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8; INSERT INTO `nbdata_sources` (`url`, `name`, `current_version`) VALUES ('http://www20.statcan.gc.ca/tables-tableaux/cansim/csv/02820087-eng.zip', '02820087', NULL), ('http://www20.statcan.gc.ca/tables-tableaux/cansim/csv/02820002-eng.zip', '02820002', NULL), ('http://www20.statcan.gc.ca/tables-tableaux/cansim/csv/02820088-eng.zip', '02820088', NULL), ('http://www20.statcan.gc.ca/tables-tableaux/cansim/csv/02820008-eng.zip', '02820008', NULL), ('http://www20.statcan.gc.ca/tables-tableaux/cansim/csv/02820122-eng.zip', '02820122', NULL), ('http://www20.statcan.gc.ca/tables-tableaux/cansim/csv/02820123-eng.zip', '02820123', NULL), ('http://www20.statcan.gc.ca/tables-tableaux/cansim/csv/02820128-eng.zip', '02820128', NULL), ('http://www20.statcan.gc.ca/tables-tableaux/cansim/csv/02820129-eng.zip', '02820129', NULL); CREATE TABLE `nbdata_last_update` ( `id` int(6) unsigned NOT NULL AUTO_INCREMENT, `scan_date` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, `last_modified` varchar(255) DEFAULT NULL, `source_id` int(11) DEFAULT NULL, PRIMARY KEY (`id`) ) ENGINE=InnoDB AUTO_INCREMENT=7 DEFAULT CHARSET=utf8;<file_sep><?php class Datagathering_model extends CI_Model { /** * Inserts last scan data into database * @param $data */ public function saveLastProcessed($data) { $this->db->insert('nbdata_last_update', $data); } public function updateCsvVersion($data) { $update = array ( 'current_version' => $data['last_modified'] ); $this->db->where('id', $data['source_id']) ->update('nbdata_sources', $update); } /** * Gets hash record from database if it exists * @param $header_hash * @return mixed */ public function getLastProcessed($header_hash) { $this->db->select('current_version') ->from('nbdata_sources') ->where('current_version =', $header_hash); $query = $this->db->get()->row(); return $query; } /** * Get urls for processing * @param $name optional to get a single record id */ public function getDataUrls($name = null) { if($name == null) { $this->db->select('*') ->from('nbdata_sources'); } else { $this->db->select('id') ->from('nbdata_sources') ->where('name =', $name); } $query = $this->db->get(); return $query; } /** * Get hashcodes to see if they need to be updated * */ public function getCurrentHashCodes() { $this->db->select('id, last_modified, source_id') ->from('nbdata_last_update') ->where('last_modified IS NOT NULL'); $query = $this->db->get(); return $query; } /** * Processes large CSV file and inserts it. Returns a count if records successfully inserted * @param $file_data array containing last_modified, source_id and file_path * @return bool */ public function processZipFile($file_data) { ini_set('memory_limit','4000M'); set_time_limit(1800); //hardcoded temporarily for testing $file_path = 'https://qimple.s3.amazonaws.com/NBData_Temp/' . $file_data['name'] . '.csv'; //$file_path = $file_data['file_path']; //$new_name = str_replace("\\","/",$file_path); $initial_count = $this->db->count_all("`" . $file_data['name'] . "`"); //get header for column names $handle = fopen($file_data['file_path'], 'r'); $header = fgetcsv($handle); $head_data = ""; foreach($header as $value) { $value = preg_replace('/\s+/', '_', $value); $head_data .= '`' . $value . '`,'; } $columns = rtrim(trim($head_data),','); //import from temp csv file into database $sql = ( 'LOAD DATA LOCAL INFILE "'. $file_path . '" IGNORE INTO TABLE `' . $file_data['name'] .'` CHARACTER SET \'utf8\' FIELDS TERMINATED by \',\' ENCLOSED BY \'"\' LINES TERMINATED BY \'\n\' IGNORE 1 LINES (' . $columns .')' ); $query = $this->db->query( $sql ); $final_count = $this->db->count_all("`" . $file_data['name'] . "`"); $count = $final_count - $initial_count; $insert_data = array ( 'last_modified' => $file_data['last_modified'], 'source_id' => $file_data['source_id'], ); $update_data = array ( 'last_modified' => $file_data['last_modified'], 'source_id' => $file_data['source_id'], 'table' => $file_data['name'] ); $this->updateCsvVersion($update_data); $this->saveLastProcessed($insert_data); return $count; } public function getEmploymentRate($data) { $this->db->select("geography, value, CASE geography WHEN 'Canada' THEN 1 WHEN 'Newfoundland and Labrador' THEN 2 WHEN 'Prince Edward Island' THEN 3 WHEN 'Nova Scotia' THEN 4 WHEN 'New Brunswick' THEN 5 WHEN 'Quebec' THEN 6 WHEN 'Ontario' THEN 7 WHEN 'Manitoba' THEN 8 WHEN 'Saskatchewan' THEN 9 WHEN 'Alberta' THEN 10 WHEN 'British Columbia' THEN 11 END AS order_prov", FALSE) ->from("`" . '02820087' . "`") ->where('ref_date =', $data['startdate']) ->where('`characteristics` = ', $data['characteristics']) // ->where_in('geography', array('Canada', 'Newfoundland and Labrador', 'Prince Edward Island', 'Nova Scotia', // 'New Brunswick', 'Quebec', 'Ontario', 'Manitoba', 'Saskatchewan', 'Alberta', 'British Columbia')) ->where('`agegroup` = ', $data['agegroup']) ->where('`sex` = ', $data['sex']) ->where('`statistics` =', $data['statistics'] ) ->where('`datatype` = ', $data['datatype']) ->order_by('order_prov', 'ASC'); $start = $this->db->get()->result(); $query = $this->db->last_query(); $this->db->select("geography, value, CASE geography WHEN 'Canada' THEN 1 WHEN 'Newfoundland and Labrador' THEN 2 WHEN 'Prince Edward Island' THEN 3 WHEN 'Nova Scotia' THEN 4 WHEN 'New Brunswick' THEN 5 WHEN 'Quebec' THEN 6 WHEN 'Ontario' THEN 7 WHEN 'Manitoba' THEN 8 WHEN 'Saskatchewan' THEN 9 WHEN 'Alberta' THEN 10 WHEN 'British Columbia' THEN 11 END AS order_prov", FALSE) ->from("`" . '02820087' . "`") ->where('ref_date =', $data['enddate']) ->where('`characteristics` =', $data['characteristics']) // ->where_in('geo', array('Canada', 'Newfoundland and Labrador', 'Prince Edward Island', 'Nova Scotia', // 'New Brunswick', 'Quebec', 'Ontario', 'Manitoba', 'Saskatchewan', 'Alberta', 'British Columbia')) ->where('`agegroup` = ', $data['agegroup']) ->where('`sex` = ', $data['sex']) ->where('`statistics` = ', $data['statistics']) ->where('`datatype` = ', $data['datatype']) ->order_by('order_prov', 'ASC'); $end = $this->db->get()->result(); $result = array(); foreach($start as $key => $value) { $name = $value->geography; $val = $value->value; foreach($end as $innerKey => $innerValue) { if($innerValue->geography == $name) { $diff = $val - $innerValue->value; $percent = sprintf('%.01f', ($diff / $innerValue->value) * 100); $shortName = $this->_provinceNames($name); $temp = array( 'geography' => $shortName, 'value' => $percent ); array_push($result, $temp); } } } $table = array(); $table['cols'] = array( array('label' => 'Region', 'type' => 'string', ), array('label' => 'Percentage', 'type' => 'number'), array('role' => 'annotation', 'type' => 'string'), array('role' => 'annotation', 'type' => 'string'), array('role' => 'style', 'type' => 'string') ); $rows = array(); foreach($result as $key => $value) { $temp = array(); // the following line will be used to slice the Pie chart $temp[] = array('v' => $value['geography']); $temp[] = array('v' => $value['value']); $temp[] = array('v' => (string)$value['value'] . '%'); $temp[] = array('v' => $value['geography']); if($value['geography'] == 'NB') { $temp[] = array('v' => '#FF5F18'); } else { $temp[] = array('v' => '#8A62A0'); } $rows[] = array('c' => $temp); } $table['rows'] = $rows; $jsonTable = json_encode($table); return $jsonTable; } /** * Query returns data based on the selected characteristics and date. * @param $data * @return string */ public function getBarChart($data) { $date = $data['date']; $characteristics = $data['characteristics']; $this->db->select("geography, value, CASE geography WHEN 'Canada' THEN 1 WHEN 'Newfoundland and Labrador' THEN 2 WHEN 'Prince Edward Island' THEN 3 WHEN 'Nova Scotia' THEN 4 WHEN 'New Brunswick' THEN 5 WHEN 'Quebec' THEN 6 WHEN 'Ontario' THEN 7 WHEN 'Manitoba' THEN 8 WHEN 'Saskatchewan' THEN 9 WHEN 'Alberta' THEN 10 WHEN 'British Columbia' THEN 11 END AS order_prov", FALSE) ->from("`" . '02820087' . "`") ->where('ref_date =', $date) ->where('`characteristics` =', $characteristics) ->where('`agegroup` = "15 years and over"') ->where('`sex` = "Both sexes"') ->where('`statistics` = "Estimate"') ->where('`datatype` = "Seasonally adjusted"') ->order_by('order_prov', 'ASC'); $query = $this->db->get(); $table = array(); $table['cols'] = array( array('label' => 'Region', 'type' => 'string'), array('label' => 'Percentage', 'type' => 'number'), array('role' => 'annotation', 'type' => 'string'), array('role' => 'annotation', 'type' => 'string'), array('role' => 'style', 'type' => 'string') ); $rows = array(); foreach($query->result() as $key => $value) { $temp = array(); $shortName = $this->_provinceNames($value->geography); // the following line will be used to slice the Pie chart $temp[] = array('v' => $shortName); $temp[] = array('v' => floatval($value->value) ); $temp[] = array('v' => (string)$value->value . '%'); $temp[] = array('v' => $shortName); if($shortName == 'NB') { $temp[] = array('v' => '#FF5F18'); } else { $temp[] = array('v' => '#8A62A0'); } $rows[] = array('c' => $temp); }; $table['rows'] = $rows; $jsonTable = json_encode($table); return $jsonTable; } /** * Data includes start date, end date, and characteristic definition, allow comparison between the results of * two queries * @param $data * @return string */ public function getComparisonBarChart($data) { $this->db->select("geography, value, CASE geography WHEN 'Canada' THEN 1 WHEN 'Newfoundland and Labrador' THEN 2 WHEN 'Prince Edward Island' THEN 3 WHEN 'Nova Scotia' THEN 4 WHEN 'New Brunswick' THEN 5 WHEN 'Quebec' THEN 6 WHEN 'Ontario' THEN 7 WHEN 'Manitoba' THEN 8 WHEN 'Saskatchewan' THEN 9 WHEN 'Alberta' THEN 10 WHEN 'British Columbia' THEN 11 END AS order_prov", FALSE) ->from("`" . '02820087' . "`") ->where('ref_date =', $data['startdate']) ->where('`characteristics` =', $data['characteristics']) ->where('`agegroup` = ', $data['agegroup']) ->where('`sex` = ', $data['sex']) ->where('`statistics` = "Estimate"') ->where('`datatype` = ', $data['datatype']) ->order_by('order_prov', 'ASC'); $start = $this->db->get()->result(); $this->db->select("geography, value, CASE geography WHEN 'Canada' THEN 1 WHEN 'Newfoundland and Labrador' THEN 2 WHEN 'Prince Edward Island' THEN 3 WHEN 'Nova Scotia' THEN 4 WHEN 'New Brunswick' THEN 5 WHEN 'Quebec' THEN 6 WHEN 'Ontario' THEN 7 WHEN 'Manitoba' THEN 8 WHEN 'Saskatchewan' THEN 9 WHEN 'Alberta' THEN 10 WHEN 'British Columbia' THEN 11 END AS order_prov", FALSE) ->from("`" . '02820087' . "`") ->where('ref_date =', $data['enddate']) ->where('`characteristics` =', $data['characteristics']) ->where('`agegroup` = "15 years and over"') ->where('`sex` = "Both sexes"') ->where('`statistics` = "Estimate"') ->where('`datatype` = ', $data['datatype']) ->order_by('order_prov', 'ASC'); $end = $this->db->get()->result(); $result = array(); foreach($start as $key => $value) { $name = $value->geography; $val = $value->value; foreach($end as $innerKey => $innerValue) { if($innerValue->geography == $name) { $diff = $innerValue->value - $val; $shortName = $this->_provinceNames($name); $temp = array( 'geography' => $shortName, 'value' => $diff ); array_push($result, $temp); } } } $table = array(); $table['cols'] = array( array('label' => 'Region', 'type' => 'string', ), array('label' => 'Percentage', 'type' => 'number'), array('role' => 'annotation', 'type' => 'string'), array('role' => 'annotation', 'type' => 'string'), array('role' => 'style', 'type' => 'string') ); $rows = array(); foreach($result as $key => $value) { $temp = array(); // the following line will be used to slice the Pie chart $temp[] = array('v' => $value['geography']); $temp[] = array('v' => $value['value']); $temp[] = array('v' => (string)$value['value'] . '(pp)'); $temp[] = array('v' => $value['geography']); if($value['geography'] == 'NB') { $temp[] = array('v' => '#FF5F18'); } else { $temp[] = array('v' => '#8A62A0'); } $rows[] = array('c' => $temp); } $table['rows'] = $rows; $jsonTable = json_encode($table); return $jsonTable; } public function getLabourForceData($data) { $where_in = $data['where_in']; $characteristics = $data['characteristics']; $this->db->select('value, ref_date, characteristics') ->from("`" . '02820087' . "`") ->where_in('ref_date', $where_in) ->where('`agegroup` = "15 years and over"') ->where('`sex` = "Both sexes"') ->where('`statistics` = "Estimate"') ->where('`datatype` = "Seasonally adjusted"') ->where('`characteristics` =', $characteristics) ->where('`geography` = "New Brunswick"'); $result = $this->db->get()->result(); //$query = $this->db->last_query(); $table = array(); $table['cols'] = array( array('id' =>'','label' => 'Date', 'type' => 'date' ), array('id' =>'', 'label' => 'Value', 'type' => 'number') ); $rows = array(); foreach($result as $key => $value) { $temp = array(); $dates = explode('/', $value->ref_date); $temp[] = array('v' => 'Date(' . $dates['0'] . ',' . ($dates['1'] - 1) . ',01' .')'); if($value->characteristics == 'Employment (x 1,000)' || $value->characteristics == 'Labour force (x 1,000)') { $temp[] = array('v' => ((int)$value->value) * 1000); } else { $temp[] = array('v' => ($value->value)); } $rows[] = array('c' => $temp); } $table['rows'] = $rows; $jsonTable = json_encode($table); return $jsonTable; } public function getLabourForceStatistics($data) { $startyear = $data['startyear']; $prevyear = $data['prevyear']; $prevmonth = $data['prevmonth']; $where_in = $data['characteristics']; $math_array = $data['math_array']; $this->db->select("value, ref_date, characteristics, CASE `characteristics` WHEN 'Population (x 1,000)' THEN 1 WHEN 'Labour force (x 1,000)' THEN 2 WHEN 'Employment (x 1,000)' THEN 3 WHEN 'Employment full-time (x 1,000)' THEN 4 WHEN 'Employment part-time (x 1,000)' THEN 5 WHEN 'Unemployment (x 1,000)' THEN 6 WHEN 'Participation rate (percent)' THEN 7 WHEN 'Employment rate (percent)' THEN 8 WHEN 'Unemployment rate (percent)' THEN 9 END AS ord_results") ->from("`" . '02820087' . "`") ->where('`ref_date` =' , $startyear) ->where_in('characteristics', $where_in) ->where('`agegroup` = "15 years and over"') ->where('`sex` = "Both sexes"') ->where('`statistics` = "Estimate"') ->where('`datatype` = "Seasonally adjusted"') ->where('`geography` = "New Brunswick"') ->order_by('ord_results', 'ASC'); $start_result = $this->db->get()->result(); $this->db->select("value, ref_date, characteristics, CASE `characteristics` WHEN 'Population (x 1,000)' THEN 1 WHEN 'Labour force (x 1,000)' THEN 2 WHEN 'Employment (x 1,000)' THEN 3 WHEN 'Employment full-time (x 1,000)' THEN 4 WHEN 'Employment part-time (x 1,000)' THEN 5 WHEN 'Unemployment (x 1,000)' THEN 6 WHEN 'Participation rate (percent)' THEN 7 WHEN 'Employment rate (percent)' THEN 8 WHEN 'Unemployment rate (percent)' THEN 9 END AS ord_results") ->from("`" . '02820087' . "`") ->where('`ref_date` =' , $prevyear) ->where_in('characteristics', $where_in) ->where('`agegroup` = "15 years and over"') ->where('`sex` = "Both sexes"') ->where('`statistics` = "Estimate"') ->where('`datatype` = "Seasonally adjusted"') ->where('`geography` = "New Brunswick"') ->order_by('ord_results', 'ASC'); $prev_result = $this->db->get()->result(); $this->db->select("value, ref_date, characteristics, CASE `characteristics` WHEN 'Population (x 1,000)' THEN 1 WHEN 'Labour force (x 1,000)' THEN 2 WHEN 'Employment (x 1,000)' THEN 3 WHEN 'Employment full-time (x 1,000)' THEN 4 WHEN 'Employment part-time (x 1,000)' THEN 5 WHEN 'Unemployment (x 1,000)' THEN 6 WHEN 'Participation rate (percent)' THEN 7 WHEN 'Employment rate (percent)' THEN 8 WHEN 'Unemployment rate (percent)' THEN 9 END AS ord_results") ->from("`" . '02820087' . "`") ->where('`ref_date` =' , $prevmonth) ->where_in('characteristics', $where_in) ->where('`agegroup` = "15 years and over"') ->where('`sex` = "Both sexes"') ->where('`statistics` = "Estimate"') ->where('`datatype` = "Seasonally adjusted"') ->where('`geography` = "New Brunswick"') ->order_by('ord_results', 'ASC'); $prev_month_result = $this->db->get()->result(); //getting comparisons for year over year and month to last month $result[] = array(); $temp = array(); foreach($start_result as $key => $value) { $characteristic = $value->characteristics; $ref_date = $value->ref_date; $val = $value->value; foreach($prev_result as $innerKey => $innerValue) { if($innerValue->characteristics == $characteristic) { $inVal = $innerValue->value; $diff = $val - $inVal; $temp['characteristics'] = $value->characteristics; $temp['curr_year'] = $ref_date; $temp['prev_year'] = $innerValue->ref_date; if(in_array($innerValue->characteristics, $math_array)) { $perc_diff = sprintf('%.01f', (($diff / $val) * 100)); $temp['perc_diff'] = $perc_diff; $temp['curr_yr_val'] = $value->value * 1000; $temp['prev_yr_val'] = $innerValue->value * 1000; $temp['yr_diff'] = $diff * 1000; } else { $temp['curr_yr_val'] = $value->value; $temp['prev_yr_val'] = $innerValue->value; $temp['yr_diff'] = $diff; $temp['perc_diff'] = ""; } } } foreach($prev_month_result as $prevMonth => $preVal) { if($preVal->characteristics == $characteristic) { $lastMoVal = $preVal->value; $modiff = $val - $lastMoVal; $temp['prev_month'] = $preVal->ref_date; if(in_array($preVal->characteristics, $math_array)) { $month_perc_diff = sprintf('%.01f', (($modiff / $val) * 100)); $temp['mo_per_diff'] = $month_perc_diff; $temp['prev_mo_val'] = $lastMoVal * 1000; $temp['mo_diff'] = $modiff * 1000; } else { $temp['prev_mo_val'] = $lastMoVal; $temp['mo_diff'] = $modiff; $temp['mo_per_diff'] = ""; } } } array_push($result, $temp); } $result1 = array_filter($result); foreach($result1 as $key => $value) { $table = array(); $table['cols'] = array( array('label' => 'Characteristics', 'type' => 'string', ), array('label' => $value['prev_year'], 'type' => 'number'), array('label' => $value['prev_month'], 'type' => 'number'), array('label' => $value['curr_year'], 'type' => 'number'), array('label' => 'M-M Change', 'type' => 'number'), array('label' =>'', 'type' => 'number'), array('label' => 'Y-Y Change', 'type' => 'number'), array('label' => '', 'type' => 'number') ); } $rows = array(); foreach($result1 as $key => $value) { if(is_numeric($value['mo_per_diff'])) { $mo_diff = $value['mo_per_diff']; } else { $mo_diff = null; } if(is_numeric($value['perc_diff'])) { $yr_diff = $value['perc_diff']; } else { $yr_diff = null; } $temp = array(); // the following line will be used to slice the Pie chart $temp[] = array('v' => $this->_fieldNames($value['characteristics'])); $temp[] = array('v' => $value['prev_yr_val']); $temp[] = array('v' => $value['prev_mo_val']); $temp[] = array('v' => $value['curr_yr_val']); $temp[] = array('v' => $value['mo_diff']); $temp[] = array('v' => $mo_diff); $temp[] = array('v' => $value['yr_diff']); $temp[] = array('v' => $yr_diff); $rows[] = array('c' => $temp); } $table['rows'] = $rows; $jsonTable = json_encode($table); return $jsonTable; } private function _provinceNames($name) { switch ($name) { case 'Ontario': $returnName = 'ON'; break; case 'Quebec': $returnName = 'QC'; break; case 'New Brunswick': $returnName = 'NB'; break; case 'Nova Scotia': $returnName = 'NS'; break; case 'Prince Edward Island': $returnName = 'PE'; break; case 'Manitoba': $returnName = 'MB'; break; case 'Alberta': $returnName = 'AB'; break; case 'British Columbia': $returnName = 'BC'; break; case 'Saskatchewan': $returnName = 'SK'; break; case 'Newfoundland and Labrador': $returnName = 'NL'; break; case 'Canada': $returnName = 'Canada'; break; default: $returnName = $name; } return $returnName; } private function _fieldNames($name) { switch ($name) { case 'Population (x 1,000)': $returnName = 'Population'; break; case 'Labour force (x 1,000)': $returnName = 'Labour Force'; break; case 'Employment (x 1,000)': $returnName = 'Employment'; break; case 'Employment full-time (x 1,000)': $returnName = 'FT Employment'; break; case 'Employment part-time (x 1,000)': $returnName = 'PT Employment'; break; case 'Unemployment (x 1,000)': $returnName = 'Unemployment'; break; case 'Participation rate (percent)': $returnName = 'Participation rate (%)'; break; case 'Employment rate (percent)': $returnName = 'Employment rate (%)'; break; case 'Unemployment rate (percent)': $returnName = 'Unemployment rate (%)'; break; default: $returnName = $name; } return $returnName; } } <file_sep>CREATE TABLE `geography_prov` ( `id` int(11) NOT NULL AUTO_INCREMENT, `name` varchar(255) DEFAULT NULL, `lang` varchar(10) DEFAULT NULL, PRIMARY KEY (`id`), KEY `id` (`id`), KEY `name` (`name`), KEY `language` (`lang`) ) ENGINE=InnoDB AUTO_INCREMENT=23 DEFAULT CHARSET=utf8; INSERT INTO `geography_prov` (`id`, `name`, `lang`) VALUES (1, 'Newfoundland and Labrador', 'EN'), (2, 'Nova Scotia', 'EN'), (3, 'Prince Edward Island', 'EN'), (4, 'New Brunswick', 'EN'), (5, 'Quebec', 'EN'), (6, 'Ontario', 'EN'), (7, 'Manitoba', 'EN'), (8, 'Saskatchewan', 'EN'), (9, 'Alberta', 'EN'), (10, 'British Columbia', 'EN'), (11, 'Canada', 'EN'), (12, 'Terre-Neuve-et-Labrador', 'FR'), (13, 'Nouvelle-Écosse', 'FR'), (14, 'Île-du-Prince-Édouard', 'FR'), (15, 'Nouveau-Brunswick ', 'FR'), (16, 'Québec', 'FR'), (17, 'Ontario ', 'FR'), (18, 'Manitoba', 'FR'), (19, 'Saskatchewan', 'FR'), (20, 'Alberta', 'FR'), (21, 'Colombie-Britannique', 'FR'), (22, 'Canada', 'FR'); CREATE TABLE `characteristics` ( `id` int(11) NOT NULL AUTO_INCREMENT, `characteristic` varchar(255) DEFAULT NULL, `characteristic_fr` varchar(255) DEFAULT NULL, PRIMARY KEY (`id`), KEY `id` (`id`), KEY `Characteristic` (`characteristic`), KEY `Characteristic French` (`characteristic_fr`) ) ENGINE=InnoDB AUTO_INCREMENT=10 DEFAULT CHARSET=utf8; CREATE TABLE `tables` ( `id` int(11) NOT NULL AUTO_INCREMENT, `table` VARCHAR(255), KEY `id` (`id`) ); CREATE TABLE `table_characteristics` ( `table_id` int(11) NOT NULL, `characteristic_id` int(11) NOT NULL, KEY `table_id` (`table_id`), KEY `characteristic_id` (`characteristic_id`) ); <file_sep><?php defined('BASEPATH') OR exit('No direct script access allowed'); ?><!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <title>Welcome to Datamining</title> <style type="text/css"> ::selection { background-color: #E13300; color: white; } ::-moz-selection { background-color: #E13300; color: white; } body { background-color: #fff; margin: 40px; font: 13px/20px normal Helvetica, Arial, sans-serif; color: #4F5155; } a { color: #003399; background-color: transparent; font-weight: normal; } h1 { color: #444; background-color: transparent; border-bottom: 1px solid #D0D0D0; font-size: 19px; font-weight: normal; margin: 0 0 14px 0; padding: 14px 15px 10px 15px; } code { font-family: Consolas, Monaco, Courier New, Courier, monospace; font-size: 12px; background-color: #f9f9f9; border: 1px solid #D0D0D0; color: #002166; display: block; margin: 14px 0 14px 0; padding: 12px 10px 12px 10px; } #body { margin: 0 15px 0 15px; } p.footer { text-align: right; font-size: 11px; border-top: 1px solid #D0D0D0; line-height: 32px; padding: 0 10px 0 10px; margin: 20px 0 0 0; } #container { margin: 10px; border: 1px solid #D0D0D0; box-shadow: 0 0 8px #D0D0D0; } </style> </head> <body> <div id="container"> <h1>Charts</h1> <div id="body"> <!-- --><?php //echo form_open('Charts/participation') ;?> <!-- <p>Click to get Charts</p>--> <!-- <label for="date">Enter date in Year/Month format (eg. 2017/01)</label>--> <!-- <input id="date" name="date" type="text" size="15">--> <!----> <!-- --><?php //echo form_submit('Charts', 'Get Participation Chart!');?> <!-- --><?php //echo form_close();?> <!----> <!-- <br><br>--> <!-- --><?php //echo form_open('Charts/participationMM') ;?> <!-- <p>Get Participation M-M Chart</p>--> <!-- <label for="startdate">Enter Start date in Year/Month format (eg. 2017/01)</label>--> <!-- <input id="startdate" name="startdate" type="text" size="15"><br>--> <!-- <label for="enddate">Enter End date in Year/Month format (eg. 2017/01)</label>--> <!-- <input id="enddate" name="enddate" type="text" size="15"><br>--> <!----> <!-- --><?php //echo form_submit('Charts', 'Get Participation Chart!');?> <!-- --><?php //echo form_close();?> <!----> <!-- <br><br>--> <!-- --><?php //echo form_open('Charts/participationYY') ;?> <!-- <p>Get Participation Y-Y Chart</p>--> <!-- <label for="startyear">Enter the start year (eg. 2016)</label>--> <!-- <input id="startyear" name="startyear" type="text" size="15"><br>--> <!-- <label for="startmonth">Enter the start month in numberic format (eg. 12 for December)</label>--> <!-- <input id="startmonth" name="startmonth" type="text" size="15"><br>--> <!----> <!-- --><?php //echo form_submit('Charts', 'Get Participation Chart!');?> <!-- --><?php //echo form_close();?> <br> <?php echo form_open('Charts/getAllParticipationCharts') ;?> <p>Get All Participation Charts</p> <label for="startyear">Enter the year for reports (eg. 2016)</label> <input id="startyear" name="startyear" type="text" size="15"><br> <label for="startmonth">Enter the month in numberic format for reports (eg. 12 for December)</label> <input id="startmonth" name="startmonth" type="text" size="15"><br> <?php echo form_submit('Charts', 'Get Participation Charts!');?> <?php echo form_close();?> <br><br> <?php echo form_open('Charts/getLabourForceCharts') ;?> <p>Get All Participation Charts</p> <label for="startyear">Enter the year for reports (eg. 2016)</label> <input id="startyear" name="startyear" type="text" size="15"><br> <label for="startmonth">Enter the month in numberic format for reports (eg. 12 for December)</label> <input id="startmonth" name="startmonth" type="text" size="15"><br> <?php echo form_submit('Charts', 'Get Labour Force Charts!');?> <?php echo form_close();?> </div> <p class="footer">Page rendered in <strong>{elapsed_time}</strong> seconds. <?php echo (ENVIRONMENT === 'development') ? 'CodeIgniter Version <strong>' . CI_VERSION . '</strong>' : '' ?></p> </div> </body> </html><file_sep><html> <head> <script src="https://code.jquery.com/jquery-3.2.1.min.js" integrity="<KEY> crossorigin="anonymous"></script> <!-- Latest compiled and minified CSS --> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="<KEY>" crossorigin="anonymous"> <!-- Optional theme --> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap-theme.min.css" integrity="<KEY>" crossorigin="anonymous"> <!-- Latest compiled and minified JavaScript --> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js" integrity="<KEY>" crossorigin="anonymous"></script> <!--Load the AJAX API--> <script type="text/javascript" src="https://www.google.com/jsapi"></script> <script type="text/javascript" src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script> <script type="text/javascript"> // Load the Visualization API and the piechart package. google.load('visualization', '1', {'packages':['corechart']}); // Set a callback to run when the Google Visualization API is loaded. google.setOnLoadCallback(drawChart); function drawChart() { var data = new google.visualization.DataTable(<?= $participation ;?>); var options = { title: "Participation Rate", height: 400, bar: {groupWidth: 25}, legend: { position: "none" }, vAxis: { viewWindowMode:'explicit', viewWindow: { max:100, min:50 } }, annotations: { textStyle: { color: 'black', fontSize: 10 }, alwaysOutside: true } }; // Instantiate and draw our chart, passing in some options. var chart = new google.visualization.ColumnChart(document.getElementById('chart_divP')); google.visualization.events.addListener(chart, 'ready', function () { document.getElementById('get_chart_divP').innerHTML = '<a href="' + chart.getImageURI() + '">Get Image</a>'; }); chart.draw(data, options); } </script> <script type="text/javascript"> // Load the Visualization API and the piechart package. google.load('visualization', '1', {'packages':['corechart']}); // Set a callback to run when the Google Visualization API is loaded. google.setOnLoadCallback(drawChart); function drawChart() { var data = new google.visualization.DataTable(<?= $participation_mm ;?>); var options = { title: "Participation Rate M-M", height: 400, vAxis: { format: 'short' }, bar: {groupWidth: 25}, legend: { position: "none" }, annotations: { textStyle: { color: 'black', fontSize: 10 }, alwaysOutside: true } }; // Instantiate and draw our chart, passing in some options. var chart = new google.visualization.ColumnChart(document.getElementById('chart_divMM')); google.visualization.events.addListener(chart, 'ready', function () { document.getElementById('get_chart_divMM').innerHTML = '<a href="' + chart.getImageURI() + '">Get Image</a>'; }); chart.draw(data, options); } </script> <script type="text/javascript"> // Load the Visualization API and the piechart package. google.load('visualization', '1', {'packages':['corechart']}); // Set a callback to run when the Google Visualization API is loaded. google.setOnLoadCallback(drawChart); function drawChart() { var data = new google.visualization.DataTable(<?= $participation_yy ;?>); var options = { title: "Participation Rate Y-Y", height: 400, vAxis: { format: 'short' }, bar: {groupWidth: 25}, legend: { position: "none" }, annotations: { textStyle: { color: 'black', fontSize: 10 }, alwaysOutside: true } }; // Instantiate and draw our chart, passing in some options. var chart = new google.visualization.ColumnChart(document.getElementById('chart_divYY')); google.visualization.events.addListener(chart, 'ready', function () { document.getElementById('get_chart_divYY').innerHTML = '<a href="' + chart.getImageURI() + '">Get Image</a>'; }); chart.draw(data, options); } </script> <script type="text/javascript"> // Load the Visualization API and the piechart package. google.load('visualization', '1', {'packages':['corechart']}); // Set a callback to run when the Google Visualization API is loaded. google.setOnLoadCallback(drawChart); function drawChart() { var data = new google.visualization.DataTable(<?= $employment_mm ;?>); var options = { title: "Employment Rate M-M", height: 400, vAxis: { format: 'short' }, bar: {groupWidth: 25}, legend: { position: "none" }, vAxis: { textPosition: 'none', viewWindowMode:'explicit', viewWindow: { max:2 } }, annotations: { textStyle: { color: 'black', fontSize: 10 }, alwaysOutside: true } }; // Instantiate and draw our chart, passing in some options. var chart = new google.visualization.ColumnChart(document.getElementById('chart_divERMM')); google.visualization.events.addListener(chart, 'ready', function () { document.getElementById('get_chart_divERMM').innerHTML = '<a href="' + chart.getImageURI() + '">Get Image</a>'; }); chart.draw(data, options); } </script> <script type="text/javascript"> // Load the Visualization API and the piechart package. google.load('visualization', '1', {'packages':['corechart']}); // Set a callback to run when the Google Visualization API is loaded. google.setOnLoadCallback(drawChart); function drawChart() { var data = new google.visualization.DataTable(<?= $employment_yy ;?>); var options = { title: "Employment Rate Y-Y", height: 400, vAxis: { format: 'short' }, bar: {groupWidth: 25}, legend: { position: "none" }, annotations: { textStyle: { color: 'black', fontSize: 10 }, alwaysOutside: true } }; // Instantiate and draw our chart, passing in some options. var chart = new google.visualization.ColumnChart(document.getElementById('chart_divERYY')); google.visualization.events.addListener(chart, 'ready', function () { document.getElementById('get_chart_divERYY').innerHTML = '<a href="' + chart.getImageURI() + '">Get Image</a>'; }); chart.draw(data, options); } </script> <script type="text/javascript"> // Load the Visualization API and the piechart package. google.load('visualization', '1', {'packages':['corechart']}); // Set a callback to run when the Google Visualization API is loaded. google.setOnLoadCallback(drawChart); function drawChart() { var data = new google.visualization.DataTable(<?= $employment_ur ;?>); var options = { title: "Unemployment Rate", height: 400, vAxis: { format: 'short' }, bar: {groupWidth: 25}, legend: { position: "none" }, annotations: { textStyle: { color: 'black', fontSize: 10 }, alwaysOutside: true } }; // Instantiate and draw our chart, passing in some options. var chart = new google.visualization.ColumnChart(document.getElementById('chart_divUR')); google.visualization.events.addListener(chart, 'ready', function () { document.getElementById('get_chart_divUR').innerHTML = '<a href="' + chart.getImageURI() + '">Get Image</a>'; }); chart.draw(data, options); } </script> <script type="text/javascript"> // Load the Visualization API and the piechart package. google.load('visualization', '1', {'packages':['corechart']}); // Set a callback to run when the Google Visualization API is loaded. google.setOnLoadCallback(drawChart); function drawChart() { var data = new google.visualization.DataTable(<?= $employment_urMM ;?>); var options = { title: "Unemployment Rate M-M", height: 400, vAxis: { format: 'short' }, bar: {groupWidth: 25}, legend: { position: "none" }, annotations: { textStyle: { color: 'black', fontSize: 10 }, alwaysOutside: true } }; // Instantiate and draw our chart, passing in some options. var chart = new google.visualization.ColumnChart(document.getElementById('chart_divUR_MM')); google.visualization.events.addListener(chart, 'ready', function () { document.getElementById('get_chart_divUR_MM').innerHTML = '<a href="' + chart.getImageURI() + '">Get Image</a>'; }); chart.draw(data, options); } </script> <script type="text/javascript"> // Load the Visualization API and the piechart package. google.load('visualization', '1', {'packages':['corechart']}); // Set a callback to run when the Google Visualization API is loaded. google.setOnLoadCallback(drawChart); function drawChart() { var data = new google.visualization.DataTable(<?= $employment_urYY ;?>); var options = { title: "Unemployment Rate Y-Y", height: 400, vAxis: { format: 'short' }, bar: {groupWidth: 25}, legend: { position: "none" }, annotations: { textStyle: { color: 'black', fontSize: 10 }, alwaysOutside: true } }; // Instantiate and draw our chart, passing in some options. var chart = new google.visualization.ColumnChart(document.getElementById('chart_divUR_YY')); google.visualization.events.addListener(chart, 'ready', function () { document.getElementById('get_chart_divUR_YY').innerHTML = '<a href="' + chart.getImageURI() + '">Get Image</a>'; }); chart.draw(data, options); } </script> <script type="text/javascript"> // Load the Visualization API and the piechart package. google.load('visualization', '1', {'packages':['corechart']}); // Set a callback to run when the Google Visualization API is loaded. google.setOnLoadCallback(drawChart); function drawChart() { var data = new google.visualization.DataTable(<?= $growth_10yr ;?>); var options = { title: "Employment growth over the last ten years", height: 400, vAxis: { format: 'short' }, bar: {groupWidth: 25}, legend: { position: "none" }, annotations: { textStyle: { color: 'black', fontSize: 10 }, alwaysOutside: true } }; // Instantiate and draw our chart, passing in some options. var chart = new google.visualization.ColumnChart(document.getElementById('chart_divGrowth_10')); google.visualization.events.addListener(chart, 'ready', function () { document.getElementById('get_chart_divGrowth_10').innerHTML = '<a href="' + chart.getImageURI() + '">Get Image</a>'; }); chart.draw(data, options); } </script> </head> <body> <!--Div that will hold the chart--> <div id="chart_divP" style="width: 90%"></div> <div style="margin-left: 100px"><button id="get_chart_divP"></button></div> <br> <br> <div id="chart_divMM" style="width: 90%"></div> <div style="margin-left: 100px"><button id="get_chart_divMM"></button></div> <br> <br> <div id="chart_divYY" style="width: 90%"></div> <div style="margin-left: 100px"><button id="get_chart_divYY"></button></div> <br> <br> <div style="width: 100%; background-color: #1f1d1d; height: 5px"></div> <br> <br> <div id="chart_divERMM" style="width: 90%"></div> <div style="margin-left: 100px"><button id="get_chart_divERMM"></button></div> <br> <br> <div id="chart_divERYY" style="width: 90%"></div> <div style="margin-left: 100px"><button id="get_chart_divERYY"></button></div> <br> <br> <div style="width: 100%; background-color: #1f1d1d; height: 5px"></div> <br> <br> <div id="chart_divUR" style="width: 90%"></div> <div style="margin-left: 100px"><button id="get_chart_divUR"></button></div> <br> <br> <div id="chart_divUR_MM" style="width: 90%"></div> <div style="margin-left: 100px"><button id="get_chart_divUR_MM"></button></div> <br> <br> <div id="chart_divUR_YY" style="width: 90%"></div> <div style="margin-left: 100px"><button id="get_chart_divUR_YY"></button></div> <br> <br> <div style="width: 100%; background-color: #1f1d1d; height: 5px"></div> <br> <br> <div id="chart_divGrowth_10" style="width: 90%"></div> <div style="margin-left: 100px"><button id="get_chart_divGrowth_10"></button></div> </body> </html><file_sep><!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1"> <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable = no"> <meta name="apple-mobile-web-app-capable" content="yes" /> <title> <?php if ($custom_title){ echo $custom_title; } else { $domain = str_replace("www.","",$_SERVER['SERVER_NAME']); echo ucfirst($domain) . " - " . $title; } ?> </title> <script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js" type="text/javascript"></script> <?php if ($head) :?> <?= $head;?> <?php endif;?> <body> <?php print $content ?> </body> </html><file_sep><html> <head> <script src="https://code.jquery.com/jquery-3.2.1.min.js" integrity="<KEY> crossorigin="anonymous"></script> <!-- Latest compiled and minified CSS --> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="<KEY>" crossorigin="anonymous"> <!-- Optional theme --> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap-theme.min.css" integrity="<KEY>" crossorigin="anonymous"> <!-- Latest compiled and minified JavaScript --> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js" integrity="<KEY>" crossorigin="anonymous"></script> <!--Load the AJAX API--> <script type="text/javascript" src="https://www.google.com/jsapi"></script> <script type="text/javascript" src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script> <script type="text/javascript"> // Load the Visualization API and the piechart package. google.load('visualization', '1', {'packages':['table']}); // Set a callback to run when the Google Visualization API is loaded. google.setOnLoadCallback(drawTable); function drawTable() { var data = new google.visualization.DataTable(<?= $labour_force_statistics['data'] ;?>); var options = { title: "Labour Force Statistics: " + "<?= $labour_force_statistics['date'] ;?>", height: 400, width: 1200, interpolateNulls: false }; // Instantiate and draw our chart, passing in some options. var table = new google.visualization.Table(document.getElementById('table_divLF_main')); var formatter = new google.visualization.ArrowFormat(); formatter.format(data, 4); formatter.format(data, 5); formatter.format(data, 6); formatter.format(data, 7); var row7 = data.getRowProperties(6); var row8 = data.getRowProperties(7); var row9 = data.getRowProperties(8); table.draw(data, options); } </script> <script type="text/javascript"> // Load the Visualization API and the piechart package. google.load('visualization', '1', {'packages':['corechart']}); // Set a callback to run when the Google Visualization API is loaded. google.setOnLoadCallback(drawChart); function drawChart() { var data = new google.visualization.DataTable(<?= $labour_force_mm ;?>); var options = { title: "Labour Force M-M Trends", height: 400, width: 600, hAxis: { title: 'Month', showTextEvery: 1, slantedText: 'true', slantedTextAngle: 45, gridlines: {count: 12} }, vAxis: { title: 'Labour Force'}, legend:"none", trendlines: { 0: {} } }; // Instantiate and draw our chart, passing in some options. var chart = new google.visualization.LineChart(document.getElementById('chart_divLF_MM')); google.visualization.events.addListener(chart, 'ready', function () { document.getElementById('get_chart_LF_MM').innerHTML = '<a href="' + chart.getImageURI() + '">Get Image</a>'; }); chart.draw(data, options); } </script> <script type="text/javascript"> // Load the Visualization API and the piechart package. google.load('visualization', '1', {'packages':['corechart']}); // Set a callback to run when the Google Visualization API is loaded. google.setOnLoadCallback(drawChart); function drawChart() { var data = new google.visualization.DataTable(<?= $labour_force_yy ;?>); var options = { title: "Labour Force Y-Y Trends", height: 400, width: 600, hAxis: { title: 'Month', showTextEvery: 1, slantedText: 'true', slantedTextAngle: 45, gridlines: {count: 12} }, vAxis: { title: 'Labour Force'}, legend:"none", trendlines: { 0: {} } }; // Instantiate and draw our chart, passing in some options. var chart = new google.visualization.LineChart(document.getElementById('chart_divLF_YY')); google.visualization.events.addListener(chart, 'ready', function () { document.getElementById('get_chart_LF_YY').innerHTML = '<a href="' + chart.getImageURI() + '">Get Image</a>'; }); chart.draw(data, options); } </script> <script type="text/javascript"> // Load the Visualization API and the piechart package. google.load('visualization', '1', {'packages':['corechart']}); // Set a callback to run when the Google Visualization API is loaded. google.setOnLoadCallback(drawChart); function drawChart() { var data = new google.visualization.DataTable(<?= $employment_mm ;?>); var options = { title: "Employment M-M Trends", height: 400, width: 600, hAxis: { title: 'Month', showTextEvery: 1, slantedText: 'true', slantedTextAngle: 45, gridlines: {count: 12} }, vAxis: { title: 'Labour Force'}, legend:"none", trendlines: { 0: {} } }; // Instantiate and draw our chart, passing in some options. var chart = new google.visualization.LineChart(document.getElementById('chart_divEM_MM')); google.visualization.events.addListener(chart, 'ready', function () { document.getElementById('get_chartEM_MM').innerHTML = '<a href="' + chart.getImageURI() + '">Get Image</a>'; }); chart.draw(data, options); } </script> <script type="text/javascript"> // Load the Visualization API and the piechart package. google.load('visualization', '1', {'packages':['corechart']}); // Set a callback to run when the Google Visualization API is loaded. google.setOnLoadCallback(drawChart); function drawChart() { var data = new google.visualization.DataTable(<?= $employment_yy ;?>); var options = { title: "Employment Y-Y Trends", height: 400, width: 600, hAxis: { title: 'Month', showTextEvery: 1, slantedText: 'true', slantedTextAngle: 45, gridlines: {count: 12} }, vAxis: { title: 'Labour Force'}, legend:"none", trendlines: { 0: {} } }; // Instantiate and draw our chart, passing in some options. var chart = new google.visualization.LineChart(document.getElementById('chart_divEM_YY')); google.visualization.events.addListener(chart, 'ready', function () { document.getElementById('get_chartEM_YY').innerHTML = '<a href="' + chart.getImageURI() + '">Get Image</a>'; }); chart.draw(data, options); } </script> <script type="text/javascript"> // Load the Visualization API and the piechart package. google.load('visualization', '1', {'packages':['corechart']}); // Set a callback to run when the Google Visualization API is loaded. google.setOnLoadCallback(drawChart); function drawChart() { var data = new google.visualization.DataTable(<?= $unemployment_mm ;?>); var options = { title: "Unemployment M-M Trends", height: 400, width: 600, hAxis: { title: 'Month', showTextEvery: 1, slantedText: 'true', slantedTextAngle: 45, gridlines: {count: 12} }, vAxis: { title: 'Labour Force'}, legend:"none", trendlines: { 0: {} } }; // Instantiate and draw our chart, passing in some options. var chart = new google.visualization.LineChart(document.getElementById('chart_divUM_MM')); google.visualization.events.addListener(chart, 'ready', function () { document.getElementById('get_chartUM_MM').innerHTML = '<a href="' + chart.getImageURI() + '">Get Image</a>'; }); chart.draw(data, options); } </script> <script type="text/javascript"> // Load the Visualization API and the piechart package. google.load('visualization', '1', {'packages':['corechart']}); // Set a callback to run when the Google Visualization API is loaded. google.setOnLoadCallback(drawChart); function drawChart() { var data = new google.visualization.DataTable(<?= $unemployment_yy ;?>); var options = { title: "Unemployment Y-Y Trends", height: 400, width: 600, hAxis: { title: 'Month', showTextEvery: 1, slantedText: 'true', slantedTextAngle: 45, gridlines: {count: 12} }, vAxis: { title: 'Labour Force'}, legend:"none", trendlines: { 0: {} } }; // Instantiate and draw our chart, passing in some options. var chart = new google.visualization.LineChart(document.getElementById('chart_divUM_YY')); google.visualization.events.addListener(chart, 'ready', function () { document.getElementById('get_chartUM_YY').innerHTML = '<a href="' + chart.getImageURI() + '">Get Image</a>'; }); chart.draw(data, options); } </script> </head> <body> <br> <br> <div class="col-md-12" style="width: 100%"> <div id="table_divLF_main" style="width: 100%"></div> </div> <div class="col-md-12"> <div class="col-md-6"> <div id="chart_divLF_MM" style="width: 100%"></div> <div style="margin-left: 50px"><button id="get_chart_LF_MM"></button></div> </div> <div class="col-md-6"> <div id="chart_divLF_YY" style="width: 100%"></div> <div style="margin-left: 50px"><button id="get_chart_LF_YY"></button></div> </div> </div> <div class="col-md-12"> <div class="col-md-6"> <div id="chart_divEM_MM" style="width: 100%"></div> <div style="margin-left: 50px"><button id="get_chartEM_MM"></button></div> </div> <div class="col-md-6"> <div id="chart_divEM_YY" style="width: 100%"></div> <div style="margin-left: 50px"><button id="get_chartEM_YY"></button></div> </div> </div> <div class="col-md-12"> <div class="col-md-6"> <div id="chart_divUM_MM" style="width: 100%"></div> <div style="margin-left: 50px"><button id="get_chartUM_MM"></button></div> </div> <div class="col-md-6"> <div id="chart_divUM_YY" style="width: 100%"></div> <div style="margin-left: 50px"><button id="get_chartUM_YY"></button></div> </div> </div> </body> </html>
ac66baaba7c8624a494964e833effbdfcbe638a9
[ "SQL", "PHP" ]
9
PHP
pbrooker/nbtest
ea54e3d534fa58e5fc90d7639059a67921f9bc9f
582eb604d9a9ef22200c41c2a00b3640263dfc7b
refs/heads/master
<repo_name>helfertiago/BHSportEstabelecimento<file_sep>/app/src/main/java/com/example/tiago/bhsportestabelecimento/Classes/DataRegister.java package com.example.tiago.bhsportestabelecimento.Classes; import android.os.Parcel; import android.os.Parcelable; /** * Created by tiago on 24/01/17. */ public class DataRegister implements Parcelable { public String NomeFantasia; public String RazaoSocial; public String CNPJ; public String Responsavel; public String Email; public String Fone; public String Contato; public String Cep; public String Cidade; public String Endereco; public String Numero; public String Complemento; public String Bairro; public DataRegister( String NomeFantasia, String RazaoSocial, String CNPJ, String Responsavel, String Email, String Fone, String Contato, String Cep, String Cidade, String Endereco, String Numero, String Complemento, String Bairro ) { this.NomeFantasia = NomeFantasia; this.RazaoSocial = RazaoSocial; this.CNPJ = CNPJ; this.Responsavel = Responsavel; this.Email = Email; this.Fone = Fone; this.Contato = Contato; this.Cep = Cep; this.Cidade = Cidade; this.Endereco = Endereco; this.Numero = Numero; this.Complemento = Complemento; this.Bairro = Bairro; } private DataRegister(Parcel from){ NomeFantasia = from.readString(); RazaoSocial = from.readString(); CNPJ = from.readString(); Responsavel = from.readString(); Email = from.readString(); Fone = from.readString(); Contato = from.readString(); Cep = from.readString(); Cidade = from.readString(); Endereco = from.readString(); Numero = from.readString(); Complemento = from.readString(); Bairro = from.readString(); } public static final Parcelable.Creator<DataRegister> CREATOR = new Parcelable.Creator<DataRegister>(){ @Override public DataRegister createFromParcel(Parcel in) { return new DataRegister(in); } @Override public DataRegister[] newArray(int size) { return new DataRegister[size]; } }; public int describeContents() { return this.hashCode(); } @Override public void writeToParcel(Parcel dest, int flags) { dest.writeString(NomeFantasia); dest.writeString(RazaoSocial); dest.writeString(CNPJ); dest.writeString(Responsavel); dest.writeString(Email); dest.writeString(Fone); dest.writeString(Contato); dest.writeString(Cep); dest.writeString(Cidade); dest.writeString(Endereco); dest.writeString(Numero); dest.writeString(Complemento); dest.writeString(Bairro); } }
82a1d2ee58425b6b5562ed49d9860e8214cea929
[ "Java" ]
1
Java
helfertiago/BHSportEstabelecimento
cc55fc5b32a6f7e90a3e2a094f54c3f3afb95450
b8dc2c4f595d559b3d4b3e7157568145bd2207ca
refs/heads/master
<repo_name>m10118003/test<file_sep>/code.js Hello, World ! You:Who Am I ? I am SpiderMan ! HaHa ~~ YourFriend:Not Funny~ You:yooooooooooo~ function(){ for(var i=0; i<10; i++) { console.log(i) <file_sep>/ReadeMe.md # Hello, World ? ---------------- Here for test ! ----------------
12b312ae19ec8874d35379c257801c73aa358618
[ "JavaScript", "Markdown" ]
2
JavaScript
m10118003/test
334921760a5fd9d9b5a31194d2f77ba484e0f810
83b808db4a40872db90c1acfd727b82580809119
refs/heads/master
<file_sep># Drugi projekt z BOiL Program rozwiązuje problem doboru optymalnego asortymentu # How to start ``` $ git clone https://github.com/jszandula/BOiL_project_2.git $ cd BOiL_project_2 $ pip install -r requirements.txt $ python ./maain.py ``` <file_sep>from PyQt5.QtWidgets import QWidget, QPushButton, QLabel, QGridLayout, QHBoxLayout, QVBoxLayout, QMessageBox, QLineEdit, \ QFormLayout, QTableWidget from PyQt5.QtGui import QCursor, QPixmap, QFont, QIntValidator from PyQt5 import QtCore from settings import * from Data import * import pprint class UIDataInput(QWidget): def __init__(self, parent=None): super(UIDataInput, self).__init__(parent) self.data = Data.get_instance() self.initUI() def initUI(self): self.layout = QGridLayout() self.createTable() self.createTable2() buttonHBox = QHBoxLayout() self.zapisz_dane = QPushButton("Zapisz dane") self.zapisz_dane.clicked.connect(self.zapisz_dane_onclick) self.submit_btn = QPushButton("Dalej") buttonHBox.addWidget(self.zapisz_dane) buttonHBox.addWidget(self.submit_btn) self.layout.addLayout(buttonHBox, 2, 0) self.setLayout(self.layout) def createTable(self): vbox = QVBoxLayout() # produkty sa dawane na koncu bo mozna by bylo ich dodawac w nieskonczonosc # a kilka rzeczy zawszze musi byc w tej tabeli jak np cena # pomimo tego ze najlepsza cena to gratis :) self.columns = ['zyski_jednostkowe', 'max_produkt', 'min_produkt'] self.table = QTableWidget() self.table.setRowCount(self.data.produkty_no) self.table.setColumnCount(len(self.columns)) self.table.setHorizontalHeaderLabels(self.columns) vbox.addWidget(self.table) self.layout.addLayout(vbox, 0, 0) def createTable2(self): vbox = QVBoxLayout() self.columns2 = ['max_fabryka'] prod_str = FAB_PROD for i in range(self.data.produkty_no): new_str = prod_str + str(i) self.columns2.append(new_str) self.table2 = QTableWidget() self.table2.setRowCount(self.data.srodki_produkcji_no) self.table2.setColumnCount(len(self.columns2)) self.table2.setHorizontalHeaderLabels(self.columns2) vbox.addWidget(self.table2) self.layout.addLayout(vbox, 1, 0) def zapisz_dane_onclick(self): columns = [] for i in self.columns: columns.append(i) for i in self.columns2: columns.append(i) for i in columns: self.data.wstawione_dane[i] = [] for i in range(self.data.produkty_no): for j in range(len(self.columns)): self.data.wstawione_dane[self.columns[j]].append(float(self.table.item(i, j).text())) for i in range(self.data.srodki_produkcji_no): for j in range(len(self.columns2)): self.data.wstawione_dane[self.columns2[j]].append(float(self.table2.item(i, j).text())) pprint.pprint(self.data.wstawione_dane) <file_sep>from pulp import LpMaximize, LpProblem, LpStatus, lpSum, LpVariable import pandas as pd import numpy as np from Data import * import pprint class Optimize: def __init__(self): self.data = Data.get_instance() def optimize(self): pprint.pprint(self.data.wstawione_dane) problem = LpProblem("Dobor optymalnego asortymentu", LpMaximize) naklady = [self.data.wstawione_dane["produkt"+str(i)] for i in range(self.data.produkty_no)] print(naklady) zyski = self.data.wstawione_dane["zyski_jednostkowe"] gorne_ograniczenie_produktu = self.data.wstawione_dane["max_produkt"] dolne_ograniczenie_produktu = self.data.wstawione_dane["min_produkt"] gorne_ograniczenie_fabryki = self.data.wstawione_dane["max_fabryka"] nums = [i for i in range(self.data.produkty_no)] nazwy = ["P"+str(num) for num in nums] vars = [LpVariable(name, None, cat="Integer") for name in nazwy] problem += lpSum(float(zyski[i]) * vars[i] for i in range(0, self.data.produkty_no)) for i in range(self.data.srodki_produkcji_no): problem += lpSum([float(naklady[j][i]) * vars[j] for j in range(len(vars))]) <= gorne_ograniczenie_fabryki[i] for i in range(self.data.produkty_no): problem += lpSum([vars[i]]) <= gorne_ograniczenie_produktu[i] for i in range(self.data.produkty_no): problem += lpSum([vars[i]]) >= dolne_ograniczenie_produktu[i] print(problem) problem.solve() zoptymalizowane = [] for v in problem.variables(): zoptymalizowane.append(v.varValue) for i in range(self.data.produkty_no): self.data.produkty_ilosc[i] = zoptymalizowane[i] self.data.wartosc_funkcji_celu = problem.objective.value()<file_sep>from PyQt5.QtWidgets import QWidget, QPushButton, QLabel, QGridLayout, QHBoxLayout, QVBoxLayout, QMessageBox, QLineEdit, QFormLayout from PyQt5.QtGui import QCursor, QPixmap, QFont, QIntValidator from PyQt5 import QtCore from settings import * from Data import * class UIgetInfo(QWidget): def __init__(self, parent=None): super(UIgetInfo, self).__init__(parent) self.data = Data.get_instance() self.initUI() def initUI(self): self.layout = QFormLayout() '''COMPONENTS''' self.produkty = QLabel("Liczba produktow: ") self.produkty_no = QLineEdit() self.produkty_no.setValidator(QIntValidator()) self.srodki_produkcji = QLabel("Srodki produkcji: ") self.srodki_produkcji_no = QLineEdit() self.srodki_produkcji_no.setValidator(QIntValidator()) self.submit_btn = QPushButton("Dalej") '''LAYOUT''' self.layout.addWidget(self.produkty) self.layout.addWidget(self.produkty_no) self.layout.addWidget(self.srodki_produkcji) self.layout.addWidget(self.srodki_produkcji_no) self.layout.addWidget(self.submit_btn) self.setLayout(self.layout) # OBSOLETE FUNC def get_data(self): self.data.produkty_no = float(self.produkty_no.text()) self.data.srodki_produkcji_no = float(self.srodki_produkcji_no.text()) print(f"prod: {self.data.produkty_no}, srodki_produkcji_no: {self.data.srodki_produkcji_no}") <file_sep>from PyQt5.QtGui import QPainter, QPixmap from PyQt5.QtWidgets import QApplication, QMainWindow, QPushButton, QWidget from settings import * from gui.UIgetInfo import UIgetInfo from gui.UIDataInput import UIDataInput from gui.UIResult import UIResult from Data import Data from Optimization import Optimize class MainWindow(QMainWindow): def __init__(self, parent=None): super(MainWindow, self).__init__(parent) self.data = Data.get_instance() self.welcoming_screen() def welcoming_screen(self): self.setMinimumWidth(SCR_SIZE[0]) self.setMinimumHeight(SCR_SIZE[1]) self.UIgetInfo = UIgetInfo(self) self.UIgetInfo.submit_btn.clicked.connect(lambda: self.data_input()) self.setCentralWidget(self.UIgetInfo) self.show() def data_input(self): self.data.produkty_no = int(self.UIgetInfo.produkty_no.text()) self.data.srodki_produkcji_no = int(self.UIgetInfo.srodki_produkcji_no.text()) self.setMinimumWidth(SCR_SIZE[0]) self.setMinimumHeight(SCR_SIZE[1]) self.UIDataInput = UIDataInput(self) self.UIDataInput.submit_btn.clicked.connect(lambda: self.results()) self.setCentralWidget(self.UIDataInput) self.show() def results(self): self.optimize = Optimize() self.optimize.optimize() self.setMinimumWidth(SCR_SIZE[0]) self.setMinimumHeight(SCR_SIZE[1]) self.UIResult = UIResult(self) self.setCentralWidget(self.UIResult) self.show() <file_sep>from pulp import LpMaximize, LpProblem, LpStatus, lpSum, LpVariable import pandas as pd problem = LpProblem("Some metale shiet", LpMaximize) producers_num = int(input("\nEnter number of the producers: ")) products_num = int(input("\nEnter number of the products: ")) # gain = [0] * products_num # constraints = [0] * producers_num # for i in range(0, products_num): # gain[i] = int(input("\nEnter the gain for {:d} product: ".format(i+1))) # for i in range(0, producers_num): # for j in range(0, products_num): # constraints[i] = int(input("\nEnter the constraint for {:d} producer {:d} product".format(i+1, j+1))) df = pd.read_excel("test.xlsx", nrows=products_num) items = list(df['Produkt']) pret = dict(zip(items,df['Pret'])) tasma = dict(zip(items,df['Tasma'])) gain = dict(zip(items,df['Cena'])) products_constraint = list(df['Max_produkt']) producers_constraint = list(df['Max_fabryka']) vars = LpVariable.dicts("Produkt", items, lowBound=0, cat='Continuous') problem += lpSum([gain[i]*vars[i] for i in items]) problem += lpSum([pret[f] * vars[f] for f in items]) <= producers_constraint[0] problem += lpSum([tasma[f] * vars[f] for f in items]) <= producers_constraint[1] problem += vars[items[0]] <= products_constraint[0] problem += vars[items[1]] <= products_constraint[1] print(problem) problem.solve() for v in problem.variables(): if v.varValue>0: print(v.name, "=", v.varValue) print("Total profit: ", problem.objective.value())<file_sep>SCR_SIZE = (WIDTH, HEIGHT) = (600, 400) FAB_PROD = 'produkt'<file_sep>numpy==1.19.2 pandas==1.1.3 PuLP==2.4 PyQt5==5.15.4 <file_sep>from PyQt5.QtWidgets import QWidget, QPushButton, QLabel, QGridLayout, QHBoxLayout, QVBoxLayout, QMessageBox, QLineEdit, QFormLayout, QTableWidget from PyQt5.QtGui import QCursor, QPixmap, QFont, QIntValidator from PyQt5 import QtCore from settings import * from Data import * class UIResult(QWidget): def __init__(self, parent=None): super(UIResult, self).__init__(parent) self.data = Data.get_instance() self.initUI() def initUI(self): self.layout = QVBoxLayout() self.f_v_bl = QLabel(f"Wartość funkcji celu: {self.data.wartosc_funkcji_celu}") for i in range(self.data.produkty_no): self.layout.addWidget(self.create_prod_lbl(i)) self.layout.addWidget(self.f_v_bl) self.setLayout(self.layout) def create_prod_lbl(self, number): lbl = QLabel(f"{FAB_PROD} {number}: {self.data.produkty_ilosc[number]}") return lbl<file_sep>from settings import * class Data: _instance = None @staticmethod def get_instance(): if Data._instance == None: Data() return Data._instance def __init__(self): if Data._instance != None: raise Exception("To je singleton tego nie wywolasz 2 razy :)") else: Data._instance = self self.srodki_produkcji_no = -1 self.produkty_no = -1 self.wstawione_dane = {} # data from table self.wartosc_funkcji_celu = 0 self.produkty_ilosc = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0] # ilosc produktow jaka zostala obliczna
15b9ae30907c8f57900bcd4cda125cbb99a54c24
[ "Markdown", "Python", "Text" ]
10
Markdown
MatWich/BOiL_project_2
2bcefc6d6b881d96a19ab4aef4400327486b268d
7b6b0b86146316eba775d09984ed88d4fb64921c
refs/heads/master
<repo_name>craigbaird/Prime-Prework-Week-3-Assignment<file_sep>/booleanConditions.js function isCartonFull( eggsInCarton, cartonCapacity ){ // write an if statement checks if the carton is at cartonCapacity // this function should return true if so, false if not if (eggsInCarton >= cartonCapacity){ return true; //console.log("true"); } else { return false; //console.log("false"); } } // end checkIfCartonIsFull isCartonFull(11,10); <file_sep>/arrayIndexConsiderations.js // remember! array indices start at 0 var colors = ['red', 'blue', 'yellow']; // using array indices, write an expression that will evaluate to the color described by these variable names // for example var theColorBlue = colors[1]; // uncomment the next two lines and replace ____ with the appropriate code var theColorRed = colors[0]; var theColorBlue = colors[1]; var theColorYellow = colors[2]; // what happens if we access an index that has no element? // uncomment the following line and replace ____ with the appropriate code // var fortyThirdColor = color[43]; // Answer >> Uncaught ReferenceError: color is not defined // at arrayIndexConsiderations.js:17. This apperars in the console because // the element that is being called on does not exist. function lastItem( array ) { // this function accepts an array as an argument // have it return the last item in the array return colors[2]; //console.log(colors[2]); } lastItem(colors); <file_sep>/loopsAndConditions.js var myArray = [1,2,3,4,5,6,7,8,9,10]; var myEvensArray = []; function onlyEvens(array) { // complete this function so that given an array full of // numbers, it returns a new array containing only the even ones // for example `onlyEvens([1,2,3,4]) === [2,4]` for (var i = 0; i<= myArray.length; i++) { if (myArray[i] % 2 === 0){ myEvensArray.push(myArray[i]); } } return (myEvensArray); //console.log(myEvensArray); } onlyEvens(myArray); <file_sep>/forLoop.js function shoesOnTheBus( kidsOnTheBus ){ // this function accepts the number of kids on the bus // assume each kid on the bus is wearing 2 shoes // write a for loop that counts how many shoes are on the bus // this function should return the number of shoes on the bus var shoes = 0; for (var kids = 1; kids <= kidsOnTheBus; kids++) { shoes = shoes + 2; } return shoes; //console.log(shoes); } shoesOnTheBus(50); <file_sep>/switchDefault.js function checkDay( today ){ // use a switch check if 'today' is the weekend ('saturday' or 'sunday') // DAYS MUST BE IN ALL lowercase LETTERS AND FULL NAMES // ex: 'wednesday', not 'Wednesday' or 'wed' // return true if it is the weekend, false if not switch(today) { case 'monday': return false; case 'tuesday': return false; case 'wednesday': return false; case 'thursday': return false; case 'friday': return false; case 'saturday': return true; case 'sunday': return true; } } // end checkDay checkDay("tuesday");
198961f740c2060d3070e0c20d74fb514138d0c1
[ "JavaScript" ]
5
JavaScript
craigbaird/Prime-Prework-Week-3-Assignment
6ba49cc220888daf29f58e25e6741a8beb50a186
659ba848007679e8777840f4017534f3d90b8f8e
refs/heads/master
<file_sep>// Creating a new model, that consequently will // create a table on database with the fields and configs below module.exports = (sequelize) => { const Revenue = sequelize.define('Revenue', { title: { type: sequelize.Sequelize.STRING, allowNull: false }, value: { type: sequelize.Sequelize.DECIMAL(12, 6), allowNull: false }, date: { type: sequelize.Sequelize.DATE, allowNull: false } }, { tableName: 'revenue', timestamps: true, paranoid: false, associate: function (models) { Revenue.belongsTo(models.Category); Revenue.belongsTo(models.FinancialResource); } }); return Revenue; };<file_sep>const database = require('../config/sequelize'); exports.getRevenues = async (req, res) => { try { const query = { include: [{ model: database.models.Category, required: false, attributes: ['title'], }, { model: database.models.FinancialResource, required: false, attributes: ['title'], } ], order: [ ['id', 'ASC'] ], where: {} }; if (req.query.title && req.query.title != 'null') { query.where.title = { $like: "%" + req.query.title + "%" } } if (req.query.date && req.query.date != 'null') { query.where.date = { $eq: new Date(req.query.date) } } if (req.query.CategoryId && req.query.CategoryId != 'null') { query.where.CategoryId = req.query.CategoryId; } if (req.query.FinancialResourceId && req.query.FinancialResourceId != 'null') { query.where.FinancialResourceId = req.query.FinancialResourceId; } const revenues = await database.models.Revenue.findAll(query); return res.status(200).send(revenues); } catch (error) { console.error('ERROR', error); return res.sendStatus(500); } }; exports.getRevenue = async (req, res) => { try { if (!req.params.hasOwnProperty('id')) { return res.sendStatus(400); } const revenue = await database.models.Revenue.findByPk(req.params.id); return res.status(200).send(revenue); } catch (error) { console.error('ERROR', error); return res.sendStatus(500); } }; exports.save = async (req, res) => { try { let revenue; // If register does not have an id, is saving a new register if (!req.body.id) { revenue = await database.models.Revenue.create(req.body); // If there is an id, is an update } else { const updated = await database.models.Revenue.update(req.body, { where: { id: req.body.id } }); if (!updated) { return res.sendStatus(500); } revenue = await database.models.Revenue.findByPk(req.body.id); } return res.status(200).json(revenue); } catch (error) { console.error('ERROR', error); return res.sendStatus(500); } }; exports.delete = async (req, res) => { try { if (!req.params.hasOwnProperty('id')) { return res.sendStatus(400); } const rowsDeleted = await database.models.Revenue.destroy({ where: { id: req.params.id } }); if (rowsDeleted > 0) { return res.status(200).json({ deleted: true }); } return res.sendStatus(500); } catch (error) { console.error('ERROR', error); return res.sendStatus(500); } };<file_sep>[![Build Status](https://travis-ci.org/TiagoValdrich/financial-system-backend.svg?branch=master)](https://travis-ci.org/TiagoValdrich/financial-system-backend) # Financial System - *Back-end* This project, is a simple system for college, that has as purpose make easy to people management their cash flow. > This is only the back-end of the application, to access the Front-end, [click here](https://github.com/TiagoValdrich/financial-system). ## Requirements to run the application - NodeJS ## Installation If you already have NodeJS installed in your computer, you need to install the project dependencies. In project root, run: ``` npm install ``` ## How to run the server After installed all the dependencies, just run the following command to start the server: ``` npm start ``` And that's, if you access `http://localhost:3000` you'll receive a message from the server showing that the server is running. After this, you'll be able to run application front-end. <file_sep>const database = require('../config/sequelize'); exports.getCategories = async (req, res) => { try { const categories = await database.models.Category.findAll(); return res.status(200).send(categories); } catch (error) { console.error('ERROR', error); return res.sendStatus(500); } }; exports.getCategory = async (req, res) => { try { if (!req.params.hasOwnProperty('id')) { return res.sendStatus(400); } const category = await database.models.Category.findByPk(req.params.id); return res.status(200).send(category); } catch (error) { console.error('ERROR', error); return res.sendStatus(500); } }; exports.save = async (req, res) => { try { let category; // If register does not have an id, is saving a new register if (!req.body.id) { category = await database.models.Category.create(req.body); // If there is an id, is an update } else { const updated = await database.models.Category.update(req.body, { where: { id: req.body.id } }); if (!updated) { return res.sendStatus(500); } category = await database.models.Category.findByPk(req.body.id); } return res.status(200).json(category); } catch (error) { console.error('ERROR', error); return res.sendStatus(500); } }; exports.delete = async (req, res) => { try { if (!req.params.hasOwnProperty('id')) { return res.sendStatus(400); } const rowsDeleted = await database.models.Category.destroy({ where: { id: req.params.id } }); if (rowsDeleted > 0) { return res.status(200).json({ deleted: true }); } return res.sendStatus(500); } catch (error) { console.error('ERROR', error); return res.sendStatus(500); } };<file_sep>const Database = require('../config/sequelize').Database; const axios = require('axios').default; const express = require('express'); const http = require('http'); const cors = require('cors'); const bodyParser = require('body-parser'); const env = require('../config/env').env; const assert = require('chai').assert; describe('Testing Revenue Controller', () => { let database; let server; before(async () => { const db = new Database({ doSync: false }); database = db.sequelize; await database.query('SET FOREIGN_KEY_CHECKS = 0', null, null); const forceDb = process.env.NODE_ENV == 'devtest' ? true : false; await database.sync({ force: forceDb, logging: console.log }); await db._loadAssociations(database); await database.sync({ force: false, logging: console.log }); await db._doMigration(database); server = await createServer(); }); it('should return a status 200 if it saved', async () => { // Xunxo for fix database returning resolve without being complete setTimeout(async () => { try { const revenue = { title: 'Teste', value: -50, date: new Date() }; const revenueResponse = await axios.put(`${env.api.url}/api/revenue`, revenue); if (revenueResponse.status == 200) { return assert.ok(true); } else { return assert.fail(true); } } catch (err) { return assert.fail(true); } }, 30000); }); it('should return a status 200 if it updated successfully', async () => { // Xunxo for fix database returning resolve without being complete setTimeout(async () => { try { const revenueResponse = await axios.get(`${env.api.url}/api/revenue/1`); const newRevenue = revenueResponse.data; newRevenue.title = 'New Revenue Title'; newRevenue.value = -150; const updated = await axios.put(`${env.api.url}/api/revenue`, newRevenue); if (updated.status == 200) { return assert.ok(true); } else { return assert.fail(true); } } catch (err) { return assert.fail(err); } }, 30000); }); it('should return an array of revenues', async () => { // Xunxo for fix database returning resolve without being complete setTimeout(async () => { try { const revenues = await axios.get(`${env.api.url}/api/revenue`); if (revenues.data && Array.isArray(revenues.data)) { if (revenues.data[0].id && revenues.data[0].title && revenues.data[0].value) { return assert.ok(true); } } return assert.fail(ok); } catch (err) { return assert.fail(err); } }, 30000); }); it('should return an revenue', async () => { // Xunxo for fix database returning resolve without being complete setTimeout(async () => { try { const revenue = await axios.get(`${env.api.url}/api/revenue/1`); if (revenue.data) { return assert.ok(true); } else { return assert.fail(true); } } catch (err) { return assert.fail(err); } }, 30000); }); after(async () => { await closeConn(server); }); }); function createServer() { return new Promise((resolve, reject) => { try { const app = express(); app.use(cors()); app.use(bodyParser.json()); app.use(bodyParser.urlencoded({ extended: true })); app.use(require('../routes/revenue.routes')); const server = http.Server(app); server.listen('3000', () => { console.log('Server is running.'); resolve(server); }); } catch (err) { return reject(err); } }); } function closeConn(server) { return new Promise((resolve, reject) => { try { server.close(() => { resolve(); }); } catch (err) { reject(err); } }); }<file_sep>// Creating a new model, that consequently will // create a table on database with the fields and configs below module.exports = (sequelize) => { const FinancialResource = sequelize.define('FinancialResource', { title: { type: sequelize.Sequelize.STRING, allowNull: false } }, { tableName: 'financial_resource', timestamps: true, paranoid: true }); return FinancialResource; };<file_sep>module.exports = async (db) => { const revenue = await db.queryInterface.describeTable('revenue'); if (!revenue.CategoryId) { await db.queryInterface.addColumn('revenue', 'CategoryId', { type: db.Sequelize.INTEGER, allowNull: true, defaultValue: null }); await db.queryInterface.addConstraint('revenue', ['CategoryId'], { type: 'foreign key', references: { table: 'category', field: 'id' } }); } };<file_sep>let env; if (process.env.NODE_ENV === 'development') { env = require('../environments/development'); } else if (process.env.NODE_ENV === 'test') { env = require('../environments/tests'); } else if (process.env.NODE_ENV === 'devtest') { env = require('../environments/devtests'); } else { throw new Error('Invalid environment. NODE_ENV is not defined.'); } module.exports.env = env;<file_sep>const express = require('express'); const router = express.Router(); const financialResourceController = require('../controllers/financial-resource.controller'); router.get('/api/financial-resource', financialResourceController.getFinancialResources); router.get('/api/financial-resource/:id', financialResourceController.getFinancialResource); router.put('/api/financial-resource', financialResourceController.save); router.delete('/api/financial-resource/:id', financialResourceController.delete); module.exports = router;<file_sep>const Sequelize = require('sequelize'); const path = require('path'); const fs = require('fs'); const config = require('./env').env.database; const Op = Sequelize.Op; const operatorsAliases = { $eq: Op.eq, $ne: Op.ne, $gte: Op.gte, $gt: Op.gt, $lte: Op.lte, $lt: Op.lt, $not: Op.not, $in: Op.in, $notIn: Op.notIn, $is: Op.is, $like: Op.like, $notLike: Op.notLike, $iLike: Op.iLike, $notILike: Op.notILike, $regexp: Op.regexp, $notRegexp: Op.notRegexp, $iRegexp: Op.iRegexp, $notIRegexp: Op.notIRegexp, $between: Op.between, $notBetween: Op.notBetween, $overlap: Op.overlap, $contains: Op.contains, $contained: Op.contained, $adjacent: Op.adjacent, $strictLeft: Op.strictLeft, $strictRight: Op.strictRight, $noExtendRight: Op.noExtendRight, $noExtendLeft: Op.noExtendLeft, $and: Op.and, $or: Op.or, $any: Op.any, $all: Op.all, $values: Op.values, $col: Op.col }; class Database { constructor(options) { this.doSync = options.doSync ? options.doSync : true; this.sequelize = this.createSequelizeInstance(); this.models; } createSequelizeInstance() { // Create the database instance const sequelize = new Sequelize(config.name, config.username, config.password, { host: config.host, dialect: 'mysql', operatorsAliases }); /** @todo refactor this to async and await pls */ this._loadModels(sequelize).then(() => { if (process.env.NODE_ENV != 'devtest' && process.env.NODE_ENV != 'test') { sequelize.sync().then(() => { this._loadAssociations(sequelize).then(() => { if (this.doSync) { sequelize.sync().then(() => this._doMigration(sequelize)).catch(err => console.log('Fail', err)); } }).catch(err => console.log('Fail to sync associations', err)); }).catch(err => console.log('Fail to sync', err)); } }).catch(err => console.log('Fail to sync.', err)); return sequelize; } _loadModels(instance) { return new Promise((resolve, reject) => { try { // Read the filenames on the paste models const filenames = fs.readdirSync(path.join('.', 'src', 'models')); // Every model should be placed here! filenames.forEach((model, index) => { //const modelName = model.replace(".js", ""); /*const dbModel = */ require(path.join('..', 'models', model))(instance); //this.models[modelName] = new dbModel(); if (index == (filenames.length - 1)) { resolve(); } }); } catch (err) { reject(err); } }); } _loadAssociations(instance) { return new Promise((resolve, reject) => { try { Object.keys(instance.models).forEach((model, index) => { const dbModel = new instance.models[model](); if (dbModel._modelOptions && dbModel._modelOptions.associate) { dbModel._modelOptions.associate(instance.models); } if (index == (Object.keys(instance.models).length - 1)) { resolve(); } }); } catch (err) { reject(err); } }); } _doMigration(instance) { return new Promise((resolve, reject) => { try { require('../migrations/AddCategoryToExpense')(instance); require('../migrations/AddCategoryToRevenue')(instance); require('../migrations/AddFinancialResourceIdToExpense')(instance); require('../migrations/AddFinancialResourceIdToRevenue')(instance); resolve(); } catch (err) { reject(err); } }); } } const database = new Database({ doSync: true }); module.exports = database.sequelize; module.exports.Database = Database;<file_sep>const Database = require('../config/sequelize').Database; const axios = require('axios').default; const express = require('express'); const http = require('http'); const cors = require('cors'); const bodyParser = require('body-parser'); const env = require('../config/env').env; const assert = require('chai').assert; describe('Testing Expense Controller', () => { let database; let server; before(async () => { const db = new Database({ doSync: false }); database = db.sequelize; await database.query('SET FOREIGN_KEY_CHECKS = 0', null, null); const forceDb = process.env.NODE_ENV == 'devtest' ? true : false; await database.sync({ force: forceDb, logging: console.log }); await db._loadAssociations(database); await database.sync({ force: false, logging: console.log }); await db._doMigration(database); server = await createServer(); }); it('should return a status 200 if it saved', async () => { // Xunxo for fix database returning resolve without being complete setTimeout(async () => { try { const expense = { title: 'Teste', value: -50, date: new Date() }; const expenseResponse = await axios.put(`${env.api.url}/api/expense`, expense); if (expenseResponse.status == 200) { return assert.ok(true); } else { return assert.fail(true); } } catch (err) { return assert.fail(true); } }, 30000); }); it('should return a status 200 if it updated successfully', async () => { // Xunxo for fix database returning resolve without being complete setTimeout(async () => { try { const expenseResponse = await axios.get(`${env.api.url}/api/expense/1`); const newExpense = expenseResponse.data; newExpense.title = 'New Expense Title'; newExpense.value = -150; const updated = await axios.put(`${env.api.url}/api/expense`, newExpense); if (updated.status == 200) { return assert.ok(true); } else { return assert.fail(true); } } catch (err) { return assert.fail(err); } }, 30000); }); it('should return an array of expenses', async () => { // Xunxo for fix database returning resolve without being complete setTimeout(async () => { try { const expenses = await axios.get(`${env.api.url}/api/expense`); if (expenses.data && Array.isArray(expenses.data)) { if (expenses.data[0].id && expenses.data[0].title && expenses.data[0].value) { return assert.ok(true); } } return assert.fail(ok); } catch (err) { return assert.fail(err); } }, 30000); }); it('should return an expense', async () => { // Xunxo for fix database returning resolve without being complete setTimeout(async () => { try { const expense = await axios.get(`${env.api.url}/api/expense/1`); if (expense.data) { return assert.ok(true); } else { return assert.fail(true); } } catch (err) { return assert.fail(err); } }, 30000); }); after(async () => { await closeConn(server); }); }); function createServer() { return new Promise((resolve, reject) => { try { const app = express(); app.use(cors()); app.use(bodyParser.json()); app.use(bodyParser.urlencoded({ extended: true })); app.use(require('../routes/expense.routes')); const server = http.Server(app); server.listen('3000', () => { console.log('Server is running.'); resolve(server); }); } catch (err) { console.log('erro desgraçado', err); return reject(err); } }); } function closeConn(server) { return new Promise((resolve, reject) => { try { server.close(() => { resolve(); }); } catch (err) { console.log('error', err); reject(err); } }); }<file_sep>const database = require('../config/sequelize'); exports.getFinancialResources = async (req, res) => { try { const financialResources = await database.models.FinancialResource.findAll(); return res.status(200).send(financialResources); } catch (error) { console.error('ERROR', error); return res.sendStatus(500); } }; exports.getFinancialResource = async (req, res) => { try { if (!req.params.hasOwnProperty('id')) { return res.sendStatus(400); } const financialResource = await database.models.FinancialResource.findByPk(req.params.id); return res.status(200).send(financialResource); } catch (error) { console.error('ERROR', error); return res.sendStatus(500); } }; exports.save = async (req, res) => { try { let financialResource; // If register does not have an id, is saving a new register if (!req.body.id) { financialResource = await database.models.FinancialResource.create(req.body); // If there is an id, is an update } else { const updated = await database.models.FinancialResource.update(req.body, { where: { id: req.body.id } }); if (!updated) { return res.sendStatus(500); } financialResource = await database.models.FinancialResource.findByPk(req.body.id); } return res.status(200).json(financialResource); } catch (error) { console.error('ERROR', error); return res.sendStatus(500); } }; exports.delete = async (req, res) => { try { if (!req.params.hasOwnProperty('id')) { return res.sendStatus(400); } const rowsDeleted = await database.models.FinancialResource.destroy({ where: { id: req.params.id } }); if (rowsDeleted > 0) { return res.status(200).json({ deleted: true }); } return res.sendStatus(500); } catch (error) { console.error('ERROR', error); return res.sendStatus(500); } };
9cbfa51a9415bf27532a2c495c281e0ad058d507
[ "JavaScript", "Markdown" ]
12
JavaScript
TiagoValdrich/financial-system-backend
1809ab36a8cbb70e8d3021b12337d9555da68538
917d9247ec5b469e6f0698c48b626273e07d44f5
refs/heads/master
<file_sep># A-Simple-Keras-Deep-Learning-Script-To-Sum-Five-Binary-Numbers A simple Deep Learning script made with the API Keras to sum five "binary" (0 or 1) numbers. <file_sep>import numpy as np from random import randint #GENERATE TENSORS IN THE FORM [a, b, c, d, e] = [n] #DEFINE THE QUANTITY OF DATA number_of_points = 1000 #CREATE THE TENSORS WITH JUST 'ZEROS': #Train data: train_samples = np.zeros((number_of_points, 5)) train_labels = np.zeros((number_of_points)) #Test data test_samples = np.zeros((number_of_points, 5)) test_labels = np.zeros((number_of_points)) #FILL THE SAMPLES WITH 0's AND 1's: for i in range(number_of_points): #For the training: train_samples[i,0]=randint(0,1) train_samples[i,1]=randint(0,1) train_samples[i,2]=randint(0,1) train_samples[i,3]=randint(0,1) train_samples[i,4]=randint(0,1) #For the test: test_samples[i,0]=randint(0,1) test_samples[i,1]=randint(0,1) test_samples[i,2]=randint(0,1) test_samples[i,3]=randint(0,1) test_samples[i,4]=randint(0,1) #FILL THE LABELS WITH THE SUM OF THE RESPECTIVE SAMPLE: for i in range(number_of_points): #For the training: train_labels[i]=sum(train_samples[i]) #For the test: test_labels[i]=sum(test_samples[i]) #SAVE THE DATA SO WE CAN IMPORT IT TO TRAIN THE NEURAL NETWORK np.save("train_samples", train_samples, allow_pickle=True, fix_imports=True) np.save("train_labels", train_labels, allow_pickle=True, fix_imports=True) np.save("test_samples", train_samples, allow_pickle=True, fix_imports=True) np.save("test_labels", train_labels, allow_pickle=True, fix_imports=True)
e0c9c28a7cb76c5cc4364903009d9ac49cb1ea06
[ "Markdown", "Python" ]
2
Markdown
adsmendesdaniel/A-Simple-Keras-Deep-Learning-Script-To-Sum-Five-Binary-Numbers
6b93d71a24a8a9b72987d874a3205a06a8785a85
b87ace50a9947c8e1e0ac5a3d1d095aefee31f72
refs/heads/main
<file_sep>/*/ +---------------------------------------------------------------------------+ + Funcao | FATA010 | Autor | <NAME> | Data | 11/01/00 | +-----------+----------+-------+-----------------------+------+-------------+ | Descricao | Cadastro de Processo de Vendas | +-----------+---------------------------------------------------------------+ | Sintaxe | FATA010() | +-----------+---------------------------------------------------------------+ | Uso | Generico | +---------------------------------------------------------------------------+ | ATUALIZACOES SOFRIDAS DESDE A CONSTRUCAO NICIAL | +-----------+--------+------+-----------------------------------------------+ |Programador| Data | BOPS | Motivo da Alteracao | +-----------+--------+------+-----------------------------------------------+ | | | | | +-----------+--------+------+-----------------------------------------------+ /*/ #INCLUDE "FATA010.CH" #INCLUDE "FIVEWIN.CH" #DEFINE APOS { 15, 1, 70, 315 } Function Fata010() /*/ +----------------------------------------------------------------+ | Define Array contendo as Rotinas a executar do programa + | ----------- Elementos contidos por dimensao ------------ + | 1. Nome a aparecer no cabecalho + | 2. Nome da Rotina associada + | 3. Usado pela rotina + | 4. Tipo de Transacao a ser efetuada + | 1 - Pesquisa e Posiciona em um Banco de Dados + | 2 - Simplesmente Mostra os Campos + | 3 - Inclui registros no Bancos de Dados + | 4 - Altera o registro corrente + | 5 - Remove o registro corrente do Banco de Dados + +----------------------------------------------------------------+ /*/ PRIVATE cCadastro := OemToAnsi(STR0001) //"Processo de Venda" PRIVATE aRotina := { { OemToAnsi(STR0002),"AxPesqui" ,0,1},; //"Pesquisar" { OemToAnsi(STR0003),"Ft010Visua",0,2},; //"Visual" { OemToAnsi(STR0004),"Ft010Inclu",0,3},; //"Incluir" { OemToAnsi(STR0005),"Ft010Alter",0,4},; //"Alterar" { OemToAnsi(STR0006),"Ft010Exclu",0,5} } //"Exclusao" If !Empty( Select( "AC9" ) ) AAdd( aRotina, { STR0013,"MsDocument",0,4} ) EndIf mBrowse( 6, 1,22,75,"AC1") Return(.T.) /*/ +------------+----------+-------+-----------------------+------+----------+ | Funcao |Ft010Visua| Autor |<NAME> | Data |13.01.2000| |------------+----------+-------+-----------------------+------+----------+ | Descricao |Funcao de Tratamento da Visualizacao | +------------+------------------------------------------------------------+ | Sintaxe | Ft010Visua(ExpC1,ExpN2,ExpN3) | +------------+------------------------------------------------------------+ | Parametros | ExpC1: Alias do arquivo | | | ExpN2: Registro do Arquivo | | | ExpN3: Opcao da MBrowse | +------------+------------------------------------------------------------+ | Retorno | Nenhum | +------------+------------------------------------------------------------+ | Uso | FATA010 | +------------+------------------------------------------------------------+ /*/ Function Ft010Visua(cAlias,nReg,nOpcx) Local aArea := GetArea() Local oGetDad Local oDlg Local nUsado := 0 Local nCntFor := 0 Local nOpcA := 0 Local lContinua := .T. Local lQuery := .F. Local cCadastro := OemToAnsi(STR0001) //"Processo de Venda" Local cQuery := "" Local cTrab := "AC2" Local bWhile := {|| .T. } Local aObjects := {} Local aPosObj := {} Local aSizeAut := MsAdvSize() PRIVATE aHEADER := {} PRIVATE aCOLS := {} PRIVATE aGETS := {} PRIVATE aTELA := {} +----------------------------------------------------------------+ | Montagem de Variaveis de Memoria | +----------------------------------------------------------------+ dbSelectArea("AC1") dbSetOrder(1) For nCntFor := 1 To FCount() M->&(FieldName(nCntFor)) := FieldGet(nCntFor) Next nCntFor +----------------------------------------------------------------+ | Montagem do aHeader | +----------------------------------------------------------------+ dbSelectArea("SX3") dbSetOrder(1) dbSeek("AC2") While ( !Eof() .And. SX3->X3_ARQUIVO == "AC2" ) If ( X3USO(SX3->X3_USADO) .And. cNivel >= SX3->X3_NIVEL ) nUsado++ Aadd(aHeader,{ TRIM(X3Titulo()),; TRIM(SX3->X3_CAMPO),; SX3->X3_PICTURE,; SX3->X3_TAMANHO,; SX3->X3_DECIMAL,; SX3->X3_VALID,; SX3->X3_USADO,; SX3->X3_TIPO,; SX3->X3_ARQUIVO,; SX3->X3_CONTEXT } ) EndIf dbSelectArea("SX3") dbSkip() EndDo +----------------------------------------------------------------+ | Montagem do aCols | +----------------------------------------------------------------+ dbSelectArea("AC2") dbSetOrder(1) #IFDEF TOP If ( TcSrvType()!="AS/400" ) lQuery := .T. cQuery := "SELECT *,R_E_C_N_O_ AC2RECNO " cQuery += "FROM "+RetSqlName("AC2")+" AC2 " cQuery += "WHERE AC2.AC2_FILIAL='"+xFilial("AC2")+"' AND " cQuery += "AC2.AC2_PROVEN='"+AC1->AC1_PROVEN+"' AND " cQuery += "AC2.D_E_L_E_T_<>'*' " cQuery += "ORDER BY "+SqlOrder(AC2->(IndexKey())) cQuery := ChangeQuery(cQuery) cTrab := "FT010VIS" dbUseArea(.T.,"TOPCONN",TcGenQry(,,cQuery),cTrab,.T.,.T.) For nCntFor := 1 To Len(aHeader) TcSetField(cTrab,AllTrim(aHeader[nCntFor][2]),aHeader[nCntFor,8],aHeader[nCnt For,4],aHeader[nCntFor,5]) Next nCntFor Else #ENDIF AC2->(dbSeek(xFilial("AC2")+AC1->AC1_PROVEN)) bWhile := {|| xFilial("AC2") == AC2->AC2_FILIAL .And.; AC1->AC1_PROVEN == AC2->AC2_PROVEN } #IFDEF TOP EndIf #ENDIF While ( !Eof() .And. Eval(bWhile) ) aadd(aCOLS,Array(nUsado+1)) For nCntFor := 1 To nUsado If ( aHeader[nCntFor][10] != "V" ) aCols[Len(aCols)][nCntFor] := FieldGet(FieldPos(aHeader[nCntFor][2])) Else If ( lQuery ) AC2->(dbGoto((cTrab)->AC2RECNO)) EndIf aCols[Len(aCols)][nCntFor] := CriaVar(aHeader[nCntFor][2]) EndIf Next nCntFor aCOLS[Len(aCols)][Len(aHeader)+1] := .F. dbSelectArea(cTrab) dbSkip() EndDo If ( lQuery ) dbSelectArea(cTrab) dbCloseArea() dbSelectArea(cAlias) EndIf aObjects := {} AAdd( aObjects, { 315, 50, .T., .T. } ) AAdd( aObjects, { 100, 100, .T., .T. } ) aInfo := { aSizeAut[ 1 ], aSizeAut[ 2 ], aSizeAut[ 3 ], aSizeAut[ 4 ], 3, 3 } aPosObj := MsObjSize( aInfo, aObjects, .T. ) DEFINE MSDIALOG oDlg TITLE cCadastro From aSizeAut[7],00 To aSizeAut[6],aSizeAut[5] OF oMainWnd PIXEL EnChoice( cAlias ,nReg, nOpcx, , , , , aPosObj[1], , 3 ) oGetDad := MSGetDados():New (aPosObj[2,1], aPosObj[2,2], aPosObj[2,3], aPosObj[2,4], nOpcx, "Ft010LinOk" ,"AllwaysTrue","",.F.) ACTIVATE MSDIALOG oDlg ON INIT EnchoiceBar(oDlg,{||oDlg:End()},{||oDlg:End()}) RestArea(aArea) Return(.T.) /*/ +------------+----------+-------+-----------------------+------+----------+ | Funcao |Ft010Inclu|Autor |<NAME> | Data |13.01.2000| |------------+----------+-------+-----------------------+------+----------+ | Descricao |Funcao de Tratamento da Inclusao | +------------+------------------------------------------------------------+ | Sintaxe | Ft010Inclu(ExpC1,ExpN2,ExpN3) | +------------+------------------------------------------------------------+ | Parametros | ExpC1: Alias do arquivo | | | ExpN2: Registro do Arquivo | | | ExpN3: Opcao da MBrowse | +------------+------------------------------------------------------------+ | Retorno | Nenhum | +------------+------------------------------------------------------------+ | Uso | FATA010 | +------------+------------------------------------------------------------+ /*/ Function Ft010Inclu(cAlias,nReg,nOpcx) Local aArea := GetArea() Local cCadastro := OemToAnsi(STR0001) //"Processo de Venda" Local oGetDad Local oDlg Local nUsado := 0 Local nCntFor := 0 Local nOpcA := 0 Local aObjects := {} Local aPosObj := {} Local aSizeAut := MsAdvSize() PRIVATE aHEADER := {} PRIVATE aCOLS := {} PRIVATE aGETS := {} PRIVATE aTELA := {} +----------------------------------------------------------------+ | Montagem das Variaveis de Memoria | +----------------------------------------------------------------+ dbSelectArea("AC1") dbSetOrder(1) For nCntFor := 1 To FCount() M->&(FieldName(nCntFor)) := CriaVar(FieldName(nCntFor)) Next nCntFor +----------------------------------------------------------------+ | Montagem da aHeader | +----------------------------------------------------------------+ dbSelectArea("SX3") dbSetOrder(1) dbSeek("AC2") While ( !Eof() .And. SX3->X3_ARQUIVO == "AC2" ) If ( X3USO(SX3->X3_USADO) .And. cNivel >= SX3->X3_NIVEL ) nUsado++ Aadd(aHeader,{ TRIM(X3Titulo()),; TRIM(SX3->X3_CAMPO),; SX3->X3_PICTURE,; SX3->X3_TAMANHO,; SX3->X3_DECIMAL,; SX3->X3_VALID,; SX3->X3_USADO,; SX3->X3_TIPO,; SX3->X3_ARQUIVO,; SX3->X3_CONTEXT } ) EndIf dbSelectArea("SX3") dbSkip() EndDo +----------------------------------------------------------------+ | Montagem da Acols | +----------------------------------------------------------------+ aadd(aCOLS,Array(nUsado+1)) For nCntFor := 1 To nUsado aCols[1][nCntFor] := CriaVar(aHeader[nCntFor][2]) Next nCntFor aCOLS[1][Len(aHeader)+1] := .F. aObjects := {} AAdd( aObjects, { 315, 50, .T., .T. } ) AAdd( aObjects, { 100, 100, .T., .T. } ) aInfo := { aSizeAut[ 1 ], aSizeAut[ 2 ], aSizeAut[ 3 ], aSizeAut[ 4 ], 3, 3 } aPosObj := MsObjSize( aInfo, aObjects, .T. ) DEFINE MSDIALOG oDlg TITLE cCadastro From aSizeAut[7],00 To aSizeAut[6],aSizeAut[5] OF oMainWnd PIXEL EnChoice( cAlias ,nReg, nOpcx, , , , , aPosObj[1], , 3 ) oGetDad := MSGetDados():New(aPosObj[2,1], aPosObj[2,2], aPosObj[2,3], aPosObj[2,4], nOpcx, "Ft010LinOk", "Ft010TudOk","",.T.) ACTIVATE MSDIALOG oDlg ; ON INIT EnchoiceBar(oDlg, {||nOpcA:=If(oGetDad:TudoOk() .And. Obrigatorio(aGets,aTela), 1,0),If(nOpcA==1,oDlg:End(),Nil)},{||oDlg:End()}) If ( nOpcA == 1 ) Begin Transaction Ft010Grv(1) If ( __lSX8 ) ConfirmSX8() EndIf EvalTrigger() End Transaction Else If ( __lSX8 ) RollBackSX8() EndIf EndIf RestArea(aArea) Return(.T.) /*/ +------------+----------+-------+-----------------------+------+----------+ | Funcao |Ft010Alter| Autor |<NAME> | Data |13.01.2000| |------------+----------+-------+-----------------------+------+----------+ | Descricao |Funcao de Tratamento da Alteracao | +------------+------------------------------------------------------------+ | Sintaxe | Ft010Alter(ExpC1,ExpN2,ExpN3) | +------------+------------------------------------------------------------+ | Parametros | ExpC1: Alias do arquivo | | | ExpN2: Registro do Arquivo | | | ExpN3: Opcao da MBrowse | +------------+------------------------------------------------------------+ | Retorno | Nenhum | +------------+------------------------------------------------------------+ | Uso | FATA010 | +------------+------------------------------------------------------------+ /*/ Function Ft010Alter(cAlias,nReg,nOpcx) Local aArea := GetArea() Local cCadastro := OemToAnsi(STR0001) //"Processo de Venda" Local oGetDad Local oDlg Local nUsado := 0 Local nCntFor := 0 Local nOpcA := 0 Local lContinua := .T. Local cQuery := "" Local cTrab := "AC2" Local bWhile := {|| .T. } Local aObjects := {} Local aPosObj := {} Local aSizeAut := MsAdvSize() PRIVATE aHEADER := {} PRIVATE aCOLS := {} PRIVATE aGETS := {} PRIVATE aTELA := {} +----------------------------------------------------------------+ | Montagem das Variaveis de Memoria | +----------------------------------------------------------------+ dbSelectArea("AC1") dbSetOrder(1) lContinua := SoftLock("AC1") If ( lContinua ) For nCntFor := 1 To FCount() M->&(FieldName(nCntFor)) := FieldGet(nCntFor) Next nCntFor +----------------------------------------------------------------+ | Montagem da aHeader | +----------------------------------------------------------------+ dbSelectArea("SX3") dbSetOrder(1) dbSeek("AC2") While ( !Eof() .And. SX3->X3_ARQUIVO == "AC2" ) If ( X3USO(SX3->X3_USADO) .And. cNivel >= SX3->X3_NIVEL ) nUsado++ Aadd(aHeader,{ TRIM(X3Titulo()),; TRIM(SX3->X3_CAMPO),; SX3->X3_PICTURE,; SX3->X3_TAMANHO,; SX3->X3_DECIMAL,; SX3->X3_VALID,; SX3->X3_USADO,; SX3->X3_TIPO,; SX3->X3_ARQUIVO,; SX3->X3_CONTEXT } ) EndIf dbSelectArea("SX3") dbSkip() EndDo +----------------------------------------------------------------+ | Montagem da aCols | +----------------------------------------------------------------+ dbSelectArea("AC2") dbSetOrder(1) #IFDEF TOP If ( TcSrvType()!="AS/400" ) lQuery := .T. cQuery := "SELECT *,R_E_C_N_O_ AC2RECNO " cQuery += "FROM "+RetSqlName("AC2")+" AC2 " cQuery += "WHERE AC2.AC2_FILIAL='"+xFilial("AC2")+"' AND " cQuery += "AC2.AC2_PROVEN='"+AC1->AC1_PROVEN+"' AND " cQuery += "AC2.D_E_L_E_T_<>'*' " cQuery += "ORDER BY "+SqlOrder(AC2->(IndexKey())) cQuery := ChangeQuery(cQuery) cTrab := "FT010VIS" dbUseArea(.T.,"TOPCONN",TcGenQry(,,cQuery),cTrab,.T.,.T.) For nCntFor := 1 To Len(aHeader) TcSetField(cTrab,AllTrim(aHeader[nCntFor][2]),aHeader[nCntFor,8],; Header[nCntFor,4],aHeader[nCntFor,5]) Next nCntFor Else #ENDIF AC2->(dbSeek(xFilial("AC2")+AC1->AC1_PROVEN)) bWhile := {|| xFilial("AC2") == AC2->AC2_FILIAL .And.; AC1->AC1_PROVEN == AC2->AC2_PROVEN } #IFDEF TOP EndIf #ENDIF While ( !Eof() .And. Eval(bWhile) ) aadd(aCOLS,Array(nUsado+1)) For nCntFor := 1 To nUsado If ( aHeader[nCntFor][10] != "V" ) aCols[Len(aCols)][nCntFor] := FieldGet(FieldPos(aHeader[nCntFor][2])) Else If ( lQuery ) AC2->(dbGoto((cTrab)->AC2RECNO)) EndIf aCols[Len(aCols)][nCntFor] := CriaVar(aHeader[nCntFor][2]) EndIf Next nCntFor aCOLS[Len(aCols)][Len(aHeader)+1] := .F. dbSelectArea(cTrab) dbSkip() EndDo If ( lQuery ) dbSelectArea(cTrab) dbCloseArea() dbSelectArea(cAlias) EndIf EndIf If ( lContinua ) aObjects := {} AAdd( aObjects, { 315, 50, .T., .T. } ) AAdd( aObjects, { 100, 100, .T., .T. } ) aInfo := { aSizeAut[ 1 ], aSizeAut[ 2 ], aSizeAut[ 3 ], aSizeAut[ 4 ], 3, 3 } aPosObj := MsObjSize( aInfo, aObjects, .T. ) DEFINE MSDIALOG oDlg TITLE cCadastro From aSizeAut[7],00 To aSizeAut[6],aSizeAut[5] ; OF MainWnd PIXEL EnChoice( cAlias ,nReg, nOpcx, , , , , aPosObj[1], , 3 ) oGetDad := MSGetDados():New(aPosObj[2,1],aPosObj[2,2],aPosObj[2,3],aPosObj[2,4],nOpcx,; "Ft010LinOk","Ft010TudOk","",.T.) ACTIVATE MSDIALOG oDlg ; ON INIT EnchoiceBar(oDlg,{||nOpca:=If(oGetDad:TudoOk().And.Obrigatorio(aGets,aTela),1,0),; If(nOpcA==1,oDlg:End(),Nil)},{||oDlg:End()}) If ( nOpcA == 1 ) Begin Transaction Ft010Grv(2) If ( __lSX8 ) ConfirmSX8() EndIf EvalTrigger() End Transaction Else If ( __lSX8 ) RollBackSX8() EndIf EndIf EndIf Endif RestArea(aArea) Return(.T.) /*/ +------------+----------+-------+-----------------------+------+----------+ | Funcao |Ft010Exclu| Autor |<NAME> | Data |13.01.2000| |------------+----------+-------+-----------------------+------+----------+ | Descricao |Funcao de Tratamento da Exclusao | +------------+------------------------------------------------------------+ | Sintaxe | Ft010Exclu(ExpC1,ExpN2,ExpN3) | +------------+------------------------------------------------------------+ | Parametros | ExpC1: Alias do arquivo | | | ExpN2: Registro do Arquivo | | | ExpN3: Opcao da MBrowse | +------------+------------------------------------------------------------+ | Retorno | Nenhum | +------------+------------------------------------------------------------+ | Uso | FATA010 | +------------+------------------------------------------------------------+ /*/ Function Ft010Exclu(cAlias,nReg,nOpcx) Local aArea := GetArea() Local cCadastro := OemToAnsi(STR0001) //"Processo de Venda" Local oGetDad Local oDlg Local nUsado := 0 Local nCntFor := 0 Local nOpcA := 0 Local lContinua := .T. Local cQuery := "" Local cTrab := "AC2" Local bWhile := {|| .T. } Local aObjects := {} Local aPosObj := {} Local aSizeAut := MsAdvSize() PRIVATE aHEADER := {} PRIVATE aCOLS := {} PRIVATE aGETS := {} PRIVATE aTELA := {} +----------------------------------------------------------------+ | Montagem das Variaveis de Memoria | +----------------------------------------------------------------+ dbSelectArea("AC1") dbSetOrder(1) lContinua := SoftLock("AC1") If ( lContinua ) For nCntFor := 1 To FCount() M->&(FieldName(nCntFor)) := FieldGet(nCntFor) Next nCntFor +----------------------------------------------------------------+ | Montagem da aHeader | +----------------------------------------------------------------+ dbSelectArea("SX3") dbSetOrder(1) dbSeek("AC2") While ( !Eof() .And. SX3->X3_ARQUIVO == "AC2" ) If ( X3USO(SX3->X3_USADO) .And. cNivel >= SX3->X3_NIVEL ) nUsado++ Aadd(aHeader,{ TRIM(X3Titulo()),; TRIM(SX3->X3_CAMPO),; SX3->X3_PICTURE,; SX3->X3_TAMANHO,; SX3->X3_DECIMAL,; SX3->X3_VALID,; SX3->X3_USADO,; SX3->X3_TIPO,; SX3->X3_ARQUIVO,; SX3->X3_CONTEXT } ) EndIf dbSelectArea("SX3") dbSkip() EndDo +----------------------------------------------------------------+ | Montagek da aCols | +----------------------------------------------------------------+ dbSelectArea("AC2") dbSetOrder(1) #IFDEF TOP If ( TcSrvType()!="AS/400" ) lQuery := .T. cQuery := "SELECT *,R_E_C_N_O_ AC2RECNO " cQuery += "FROM "+RetSqlName("AC2")+" AC2 " cQuery += "WHERE AC2.AC2_FILIAL='"+xFilial("AC2")+"' AND " cQuery += "AC2.AC2_PROVEN='"+AC1->AC1_PROVEN+"' AND " cQuery += "AC2.D_E_L_E_T_<>'*' " cQuery += "ORDER BY "+SqlOrder(AC2->(IndexKey())) cQuery := ChangeQuery(cQuery) cTrab := "FT010VIS" dbUseArea(.T.,"TOPCONN",TcGenQry(,,cQuery),cTrab,.T.,.T.) For nCntFor := 1 To Len(aHeader) TcSetField(cTrab,AllTrim(aHeader[nCntFor][2]),aHeader[nCntFor,8],; aHeader[nCntFor,4],aHeader[nCntFor,5]) Next nCntFor Else #ENDIF AC2->(dbSeek(xFilial("AC2")+AC1->AC1_PROVEN)) bWhile := {|| xFilial("AC2") == AC2->AC2_FILIAL .And.; AC1->AC1_PROVEN == AC2->AC2_PROVEN } #IFDEF TOP EndIf #ENDIF While ( !Eof() .And. Eval(bWhile) ) aadd(aCOLS,Array(nUsado+1)) For nCntFor := 1 To nUsado If ( aHeader[nCntFor][10] != "V" ) aCols[Len(aCols)][nCntFor] := FieldGet(FieldPos(aHeader[nCntFor][2])) Else If ( lQuery ) AC2->(dbGoto((cTrab)->AC2RECNO)) EndIf aCols[Len(aCols)][nCntFor] := CriaVar(aHeader[nCntFor][2]) EndIf Next nCntFor aCOLS[Len(aCols)][Len(aHeader)+1] := .F. dbSelectArea(cTrab) dbSkip() EndDo If ( lQuery ) dbSelectArea(cTrab) dbCloseArea() dbSelectArea(cAlias) EndIf EndIf If ( lContinua ) aObjects := {} AAdd( aObjects, { 315, 50, .T., .T. } ) AAdd( aObjects, { 100, 100, .T., .T. } ) aInfo := { aSizeAut[ 1 ], aSizeAut[ 2 ], aSizeAut[ 3 ], aSizeAut[ 4 ], 3, 3 } aPosObj := MsObjSize( aInfo, aObjects, .T. ) DEFINE MSDIALOG oDlg TITLE cCadastro From aSizeAut[7],00 To ; aSizeAut[6],aSizeAut[5] OF oMainWnd PIXEL EnChoice( cAlias ,nReg, nOpcx, , , , , aPosObj[1], , 3 ) oGetDad := MSGetDados():New(aPosObj[2,1],aPosObj[2,2],aPosObj[2,3],aPosObj[2,4],nOpcx,; "Ft010LinOk","Ft010TudOk","",.F.) ACTIVATE MSDIALOG oDlg ; ON INIT EnchoiceBar(oDlg,{||nOpca:=If(oGetDad:TudoOk(),1,0),If(nOpcA==1,oDlg:End(),Nil)},; {||oDlg:End()}) If ( nOpcA == 1 ) Begin Transaction If Ft010DelOk() Ft010Grv(3) EvalTrigger() EndIf End Transaction EndIf EndIf RestArea(aArea) Return(.T.) /*/ +------------+----------+-------+-----------------------+------+----------+ | Funcao |Ft010LinOK| Autor |<NAME> | Data |13.01.2000| |------------+----------+-------+-----------------------+------+----------+ | Descricao |Funcao de Validacao da linha OK | +------------+------------------------------------------------------------+ | Sintaxe | Ft010LinOk() +------------+------------------------------------------------------------+ | Parametros | Nennhum | +------------+------------------------------------------------------------+ | Retorno | Nenhum | +------------+------------------------------------------------------------+ | Uso | FATA010 | +------------+------------------------------------------------------------+ /*/ Function Ft010LinOk() Local lRetorno:= .T. Local nPStage := aScan(aHeader,{|x| AllTrim(x[2])=="AC2_STAGE"}) Local nPDescri:= aScan(aHeader,{|x| AllTrim(x[2])=="AC2_DESCRI"}) Local nCntFor := 0 Local nUsado := Len(aHeader) If ( !aCols[n][nUsado+1] ) +----------------------------------------------------------------+ | Verifica os campos obrigatorios | +----------------------------------------------------------------+ If ( nPStage == 0 .Or. nPDescri == 0 ) Help(" ",1,"OBRIGAT") lRetorno := .F. EndIf If ( lRetorno .And. (Empty(aCols[n][nPStage]) .Or. Empty(aCols[n][nPDescri]))) Help(" ",1,"OBRIGAT") lRetorno := .F. EndIf +----------------------------------------------------------------+ | Verifica se não há estagios repetidos | +----------------------------------------------------------------+ If ( nPStage != 0 .And. lRetorno ) For nCntFor := 1 To Len(aCols) If ( nCntFor != n .And. !aCols[nCntFor][nUsado+1]) If ( aCols[n][nPStage] == aCols[nCntFor][nPStage] ) Help(" ",1,"FT010LOK01") lRetorno := .F. EndIf EndIf Next nCntFor EndIf EndIf Return(lRetorno) /*/ +------------+----------+-------+-----------------------+------+----------+ | Funcao |Ft010Grv | Autor |<NAME> | Data |13.01.2000| |------------+----------+-------+-----------------------+------+----------+ | Descricao |Funcao de Gravacao do Processe de Venda | +------------+------------------------------------------------------------+ | Sintaxe | Ft010Grv(ExpN1) | +------------+------------------------------------------------------------+ | Parametros | ExpN1: Opcao do Menu (Inclusao / Alteracao / Exclusao) | +------------+------------------------------------------------------------+ | Retorno | .T. | +------------+------------------------------------------------------------+ | Uso | FATA010 | +------------+------------------------------------------------------------+ /*/ Static Function Ft010Grv(nOpc) Local aArea := GetArea() Local aUsrMemo := If( ExistBlock( "FT010MEM" ), ExecBlock( "FT010MEM", .F.,.F. ), {} ) Local aMemoAC1 := {} Local aMemoAC2 := {} Local aRegistro := {} Local cQuery := "" Local lGravou := .F. Local nCntFor := 0 Local nCntFor2 := 0 Local nUsado := Len(aHeader) Local nPStage := aScan(aHeader,{|x| AllTrim(x[2])=="AC2_STAGE"}) Local nPMEMO := aScan(aHeader,{|x| AllTrim(x[2])=="AC2_MEMO"}) If ValType( aUsrMemo ) == "A" .And. Len( aUsrMemo ) > 0 For nLoop := 1 to Len( aUsrMemo ) If aUsrMemo[ nLoop, 1 ] == "AC1" AAdd( aMemoAC1, { aUsrMemo[ nLoop, 2 ], aUsrMemo[ nLoop, 3 ] } ) ElseIf aUsrMemo[ nLoop, 1 ] == "AC2" AAdd( aMemoAC2, { aUsrMemo[ nLoop, 2 ], aUsrMemo[ nLoop, 3 ] } ) EndIf Next nLoop EndIf +----------------------------------------------------------------+ | Guarda os registros em um array para atualizacao | +----------------------------------------------------------------+ dbSelectArea("AC2") dbSetOrder(1) #IFDEF TOP If ( TcSrvType()!="AS/400" ) cQuery := "SELECT AC2.R_E_C_N_O_ AC2RECNO " cQuery += "FROM "+RetSqlName("AC2")+" AC2 " cQuery += "WHERE AC2.AC2_FILIAL='"+xFilial("AC2")+"' AND " cQuery += "AC2.AC2_PROVEN='"+M->AC1_PROVEN+"' AND " cQuery += "AC2.D_E_L_E_T_<>'*' " cQuery += "ORDER BY "+SqlOrder(AC2->(IndexKey())) cQuery := ChangeQuery(cQuery) dbUseArea(.T.,"TOPCONN",TcGenQry(,,cQuery),"FT010GRV",.T.,.T.) dbSelectArea("FT010GRV") While ( !Eof() ) aadd(aRegistro,AC2RECNO) dbSelectArea("FT010GRV") dbSkip() EndDo dbSelectArea("FT010GRV") dbCloseArea() dbSelectArea("AC2") Else #ENDIF dbSeek(xFilial("AC2")+M->AC1_PROVEN) While ( !Eof() .And. xFilial("AC2") == AC2->AC2_FILIAL .And.; M->AC1_PROVEN == AC2->AC2_PROVEN ) aadd(aRegistro,AC2->(RecNo())) dbSelectArea("AC2") dbSkip() EndDo #IFDEF TOP EndIf #ENDIF Do Case +----------------------------------------------------------------+ | Inclusao / Alteracao | +----------------------------------------------------------------+ Case nOpc != 3 For nCntFor := 1 To Len(aCols) If ( nCntFor > Len(aRegistro) ) If ( !aCols[nCntFor][nUsado+1] ) RecLock("AC2",.T.) EndIf Else AC2->(dbGoto(aRegistro[nCntFor])) RecLock("AC2") EndIf If ( !aCols[nCntFor][nUsado+1] ) lGravou := .T. For nCntFor2 := 1 To nUsado If ( aHeader[nCntFor2][10] != "V" ) FieldPut(FieldPos(aHeader[nCntFor2][2]),aCols[nCntFor][nCn tFor2]) EndIf Next nCntFor2 +----------------------------------------------------------------+ | Grava os campos obrigatórios +----------------------------------------------------------------+ AC2->AC2_FILIAL := xFilial("AC2") AC2->AC2_PROVEN := M->AC1_PROVEN If ( nPMemo != 0 .And. !Empty(aCols[nCntFor][nPMemo])) MSMM(AC2- >AC2_CODMEM,,,aCols[nCntFor][nPMemo],1,,,"AC2","AC2_CODMEM") EndIf +----------------------------------------------------------------+ | Grava os campos memo de usuario | +----------------------------------------------------------------+ For nLoop := 1 To Len( aMemoAC2 ) MSMM(AC2->(FieldGet(aMemoAC2[nLoop,1])),,, ; DFieldGet( aMemoAC2[nLoop,2], nCntFor ),1,,,"AC2",aMemoAC2[nLoop,1]) Next nLoop Else If ( nCntFor <= Len(aRegistro) ) dbDelete() MSMM(AC2->AC2_CODMEM,,,,2) +---------------------------------------------------------------- + | Exclui os campos memo de usuario | +---------------------------------------------------------------- + For nLoop := 1 To Len( aMemoAC2 ) MSMM(aMemoAC2[nLoop,1],,,,2) Next nLoop EndIf EndIf MsUnLock() Next nCntFor +----------------------------------------------------------------+ | Exclusao | +----------------------------------------------------------------+ OtherWise For nCntFor := 1 To Len(aRegistro) AC2->(dbGoto(aRegistro[nCntFor])) RecLock("AC2") dbDelete() MsUnLock() MSMM(AC2->AC2_CODMEM,,,,2) Next nCntFor If !Empty( Select( "AC9" ) ) +----------------------------------------------------------------+ | Exclui a amarracao de conhecimento | +----------------------------------------------------------------+ MsDocument( "AC1", AC1->( Recno() ), 2, , 3 ) EndIf EndCase +----------------------------------------------------------------+ | Atualizacao do cabecalho | +----------------------------------------------------------------+ dbSelectArea("AC1") dbSetOrder(1) If ( MsSeek(xFilial("AC1")+M->AC1_PROVEN) ) RecLock("AC1") Else If ( lGravou ) RecLock("AC1",.T.) EndIf EndIf If ( !lGravou ) dbDelete() MSMM(AC1->AC1_CODMEM,,,,2) +----------------------------------------------------------------+ | Exclui os campos memo de usuario | +----------------------------------------------------------------+ For nLoop := 1 To Len( aMemoAC1 ) MSMM( AC1->( FieldGet( aMemoAC1[ nLoop, 1 ] ) ),,,,2) Next nLoop Else For nCntFor := 1 To AC1->(FCount()) If ( FieldName(nCntFor)!="AC1_FILIAL" ) FieldPut(nCntFor,M->&(FieldName(nCntFor))) Else AC1->AC1_FILIAL := xFilial("AC1") EndIf Next nCntFor MSMM(AC1->AC1_CODMEM,,,M->AC1_MEMO,1,,,"AC1","AC1_CODMEM") +----------------------------------------------------------------+ | Grava os campos memo de usuario | +----------------------------------------------------------------+ For nLoop := 1 To Len( aMemoAC1 ) MSMM( AC1->( FieldGet( aMemoAC1[nLoop,1] ) ),,,; M->&( aMemoAC1[nLoop,2] ),1,,,"AC1",aMemoAC1[nLoop,1]) Next nLoop EndIf MsUnLock() +----------------------------------------------------------------+ | Restaura integridade da rotina | +----------------------------------------------------------------+ RestArea(aArea) Return( .T. ) /*/ +------------+----------+-------+-----------------------+------+----------+ | Funcao |Ft010TudOK| Autor |<NAME> | Data |13.01.2000| |------------+----------+-------+-----------------------+------+----------+ | Descricao |Funcao TudoOK | +------------+------------------------------------------------------------+ | Sintaxe | Ft010TudOK() | +------------+------------------------------------------------------------+ | Parametros | Nenhum | +------------+------------------------------------------------------------+ | Retorno | .T./.F. | +------------+------------------------------------------------------------+ | Uso | FATA010 | +------------+------------------------------------------------------------+ /*/ Function Ft010TudOk() Local lRet := .T. Local nPosRelev := GDFieldPos( "AC2_RELEVA" ) Local nPosStage := GDFieldPos( "AC2_STAGE" ) Local nLoop := 0 Local nTotal := 0 Local nPosDel := Len( aHeader ) + 1 If !Empty( AScan( aCols, { |x| x[nPosRelev] > 0 } ) ) For nLoop := 1 To Len( aCols ) If !aCols[ nLoop, nPosDel ] nTotal += aCols[ nLoop, nPosRelev ] Else +----------------------------------------------------------------+ | Permite excluir apenas se não estiver em uso por oportunidade | +----------------------------------------------------------------+ AD1->( dbSetOrder( 5 ) ) If AD1->( dbSeek( xFilial( "AD1" ) + M->AC1_PROVEN + aCols[nLoop,nPosStage] ) ) Aviso( STR0007, STR0011 + AllTrim( aCols[nLoop,nPosStage] ) + ; STR0012, { STR0009 }, 2 ) ; // Atencao // "A etapa " // " nao pode ser excluida pois esta em uso por uma ou mais // oportunidades !" lRet := .F. Exit EndIf EndIf Next nLoop If lRet If nTotal <> 100 Aviso( STR0007, STR0008, ; { STR0009 }, 2 ) //"Atencao !"###"A soma dos valores de relevancia deve ser igual a 100% //!"###"Fechar" lRet := .F. EndIf EndIf EndIf Return( lRet ) /*/ +------------+----------+-------+-----------------------+------+----------+ | Funcao |Ft010DelOk| Autor |<NAME> | Data |18.01.2001| |------------+----------+-------+-----------------------+------+----------+ | Descricao |Validacao da Exclusao | +------------+------------------------------------------------------------+ | Sintaxe | Ft010DelOk() | +------------+------------------------------------------------------------+ | Parametros | Nenhum | +------------+------------------------------------------------------------+ | Retorno | .T./.F. | +------------+------------------------------------------------------------+ | Uso | FATA010 | +------------+------------------------------------------------------------+ /*/ Static Function Ft010DelOk() LOCAL lRet := .T. AD1->( dbSetOrder( 5 ) ) If AD1->( dbSeek( xFilial( "AD1" ) + M->AC1_PROVEN ) ) lRet := .F. Aviso( STR0007, STR0010, { STR0009 }, 2 ) // "Atencao" // "Este processo de venda nao pode ser excluido pois esta sendo utilizado em uma ou mais // oportunidades !", "Fechar" EndIf Return( lRet ) <file_sep>/*/ +---------------------------------------------------------------------------+ + Funcao | CTBA120 | Autor | <NAME> | Data | 24/07/00 | +-----------+----------+-------+-----------------------+------+-------------+ | Descricao | Cadastro de Criterios de Rateio Externo | +-----------+---------------------------------------------------------------+ | Sintaxe | CTBA120() | +-----------+---------------------------------------------------------------+ | Uso | Generico | +---------------------------------------------------------------------------+ | ATUALIZACOES SOFRIDAS DESDE A CONSTRUCAO NICIAL | +-----------+--------+------+-----------------------------------------------+ |Programador| Data | BOPS | Motivo da Alteracao | +-----------+--------+------+-----------------------------------------------+ | | | | | +-----------+--------+------+-----------------------------------------------+ /*/ #INCLUDE "CTBA120.CH" #INCLUDE "PROTHEUS.CH" #INCLUDE "FONT.CH" FUNCTION CTBA120() /*/ +----------------------------------------------------------------+ | Define Array contendo as Rotinas a executar do programa + | ----------- Elementos contidos por dimensao ------------ + | 1. Nome a aparecer no cabecalho + | 2. Nome da Rotina associada + | 3. Usado pela rotina + | 4. Tipo de Transacao a ser efetuada + | 1 - Pesquisa e Posiciona em um Banco de Dados + | 2 - Simplesmente Mostra os Campos + | 3 - Inclui registros no Bancos de Dados + | 4 - Altera o registro corrente + | 5 - Remove o registro corrente do Banco de Dados + +----------------------------------------------------------------+ /*/ PRIVATE aRotina := { { OemToAnsi(STR0001),"AxPesqui", 0 , 1},; //"Pesquisar" { OemToAnsi(STR0002),"Ctb120Cad", 0 , 2},; //"Visualizar" { OemToAnsi(STR0003),"Ctb120Cad", 0 , 3},; //"Incluir" { OemToAnsi(STR0004),"Ctb120Cad", 0 , 4},; //"Alterar" { OemToAnsi(STR0005),"Ctb120Cad", 0 , 5} } //"Excluir" +----------------------------------------------------------------+ | Define o cabecalho da tela de atualizacoes | +----------------------------------------------------------------+ Private cCadastro := OemToAnsi(STR0006) //"Criterios de Rateio +----------------------------------------------------------------+ | Endereca funcao Mbrowse | +----------------------------------------------------------------+ mBrowse( 6, 1,22,75,"CTJ" ) Return /*/ +------------+---------+-------+-----------------------+------+----------+ | Funcao |CTB120CAD| Autor | <NAME> | Data | 24/07/00 | +------------+---------+-------+-----------------------+------+----------+ | Descricao | Cadastro de Rateio Externo | +------------+-----------------------------------------------------------+ | Sintaxe | Ctb120Cad(ExpC1,ExpN1,ExpN2) | +------------+-----------------------------------------------------------+ | Parametros | ExpC1 = Alias do arquivo | | | ExpN1 = Numero do registro | | | ExpN2 = Numero da opcao selecionada | +------------+-----------------------------------------------------------+ | Uso | CTBA120 | +------------+-----------------------------------------------------------+ /*/ Function Ctb120Cad(cAlias,nReg,nOpc) Local aSaveArea := GetArea() Local aCampos := {} Local aAltera := {} Local aTpSald := CTBCBOX("CTJ_TPSALD") Local cArq Local cRateio Local cDescRat lOCAL cMoedaLc Local cTpSald Local nOpca := 0 Local oGetDb Local oDlg Local oFnt Local oTpSald Private aTela := {} Private aGets := {} Private aHeader := {} Private nTotalD := 0 Private nTotalC := 0 +----------------------------------------------------------------+ | Monta aHeader para uso com MSGETDB | +----------------------------------------------------------------+ aCampos := Ctb120Head(@aAltera) +----------------------------------------------------------------+ | Cria arquivo Temporario para uso com MSGETDB | +----------------------------------------------------------------+ Ctb120Cri(aCampos,@cArq) +----------------------------------------------------------------+ | Carrega dados para MSGETDB | +----------------------------------------------------------------+ Ctb120Carr(nOpc) If nOpc == 3 // Inclusao cRateio := CriaVar("CTJ_RATEIO") // Numero do Rateio cDescRat := CriaVar("CTJ_DESC") // Descricao do Rateio cMoedaLC := CriaVar("CTJ_MOEDLC") // Moeda do Lancamento cTpSald := CriaVar("CTJ_TPSALD") // Tipo do Saldo Else // Visualizacao / Alteracao / Exclusao cRateio := CTJ->CTJ_RATEIO cDescRat := CTJ->CTJ_DESC cMoedaLC := CTJ->CTJ_MOEDLC cTpSald := CTJ->CTJ_TPSALD EndIf +----------------------------------------------------------------+ | Monta Tela Modelo 2 | +----------------------------------------------------------------+ DEFINE MSDIALOG oDlg TITLE OemToAnsi(STR0006) From 9,0 To 32,80 OF oMainWnd //"Rateios Externos" DEFINE FONT oFnt NAME "Arial" Size 10,15 @ 18, 007 SAY OemToAnsi(STR0007) PIXEL //"Rateio: " @ 18, 037 MSGET cRateio Picture "9999" SIZE 020,08 When (nOpc == 3); Valid Ctb120Rat(cRateio) OF oDlg PIXEL @ 18, 090 Say OemToAnsi(STR0008) PIXEL //"Descricao: " @ 18, 120 MSGET cDescRat Picture "@!" SIZE 140,08 When (nOpc == 3 .Or. ; nOpc == 4) Valid !Empty(cDescRat) OF oDlg PIXEL @ 33, 007 Say OemToAnsi(STR0009) PIXEL // "Moeda:" @ 32, 037 MSGET cMoedaLc Picture "@!" F3 "CTO" SIZE 020,08 When (nOpc == 3 .Or.; nOpc == 4) Valid Ct120Moed(cMoedaLC) Of oDlg PIXEL @ 33, 090 SAY OemToAnsi(STR0010) PIXEL // "Saldo:" @ 32, 120 MSCOMBOBOX oTpSald VAR cTpSald ITEMS aTpSald When (nOpc == 3 .Or. ; nOpc == 4) SIZE 45,08 OF oDlg PIXEL Valid (!Empty(cTpSald) .And.; CtbTpSald(@cTpSald,aTpSald)) +----------------------------------------------------------------+ | Chamada da MSGETDB | +----------------------------------------------------------------+ oGetDB := MSGetDB():New(044, 005, 120, 315, Iif(nOpc==3,4,nOpc),"CTB120LOK",; "CTB120TOk", "+CTJ_SEQUEN",.t.,aAltera,,.t.,,"TMP") +----------------------------------------------------------------+ | Validacao da janela | +----------------------------------------------------------------+ ACTIVATE MSDIALOG oDlg ON INIT EnchoiceBar(oDlg,; {||nOpca:=1,if(Ctb120TOK(),oDlg:End(),nOpca := 0)},; {||nOpca:=2,oDlg:End()}) VALID nOpca != 0 IF nOpcA == 1 // Aceita operacao e grava dados Begin Transaction Ctb120Gra(cRateio,cDescRat,nOpc,cMoedaLC,cTpSald) End Transaction ENDIF dbSelectArea(cAlias) +----------------------------------------------------------------+ | Apaga arquivo temporario gerado para MSGETDB | +----------------------------------------------------------------+ DbSelectArea( "TMP" ) DbCloseArea() If Select("cArq") = 0 FErase(cArq+GetDBExtension()) EndIf dbSelectArea("CTJ") dbSetOrder(1) Return nOpca /*/ +------------+---------+-------+-----------------------+------+----------+ | Funcao |CTB120RAT| Autor | <NAME> | Data | 24/07/00 | +------------+---------+-------+-----------------------+------+----------+ | Descricao | Verifica existencia do Rateio | +------------+-----------------------------------------------------------+ | Sintaxe | Ctb120Rat(ExpC1) | +------------+-----------------------------------------------------------+ | Parametros | ExpC1 = Numero do Rateio | +------------+-----------------------------------------------------------+ | Retorno | .T./.F. | +------------+-----------------------------------------------------------+ | Uso | CTBA120 | +------------+-----------------------------------------------------------+ /*/ Function Ctb120Rat(cRateio) Local aSaveArea:= GetArea() Local lRet := .T. Local nReg If Empty(cRateio) lRet := .F. Else dbSelectArea("CTJ") dbSetOrder(1) nReg := Recno() If dbSeek(xFilial()+cRateio) Help(" ",1,"CTJNRATEIO") lRet := .F. EndIf dbGoto(nReg) EndIf RestArea(aSaveArea) Return lRet /*/ +------------+---------+-------+-----------------------+------+----------+ | Funcao |CTB120GRA| Autor | <NAME> | Data | 24/07/00 | +------------+---------+-------+-----------------------+------+----------+ | Descricao | Grava resgistro digitados | +------------+-----------------------------------------------------------+ | Sintaxe | Ctb120Gra(ExpC1,ExpC2,ExpN1,cExpC3,cExpC4) | +------------+-----------------------------------------------------------+ | Parametros | ExpC1 = Numero do Rateio | | | ExpC2 = Descricao do Rateio | | | ExpN1 = Opcao do Menu (Inclusao / Alteracao etc) | | | ExpC3 = Moeda do Rateio | | | ExpC4 = Tipo de Saldo | +------------+-----------------------------------------------------------+ | Retorno | Nenhum | +------------+-----------------------------------------------------------+ | Uso | CTBA120 | +------------+-----------------------------------------------------------+ Function Ctb120Gra(cRateio,cDescRat,nOpc,cMoedaLC,cTpSald) Local aSaveArea := GetArea() dbSelectArea("TMP") dbgotop() While !Eof() If !TMP->CTJ_FLAG // Item nao deletado na MSGETDB If nOpc == 3 .Or. nOpc == 4 dbSelectArea("CTJ") dbSetOrder(1) If !(dbSeek(xFilial()+cRateio+TMP->CTJ_SEQUEN)) RecLock( "CTJ", .t. ) CTJ->CTJ_FILIAL := xFilial() CTJ->CTJ_RATEIO := cRateio CTJ->CTJ_DESC := cDescRat CTJ->CTJ_MOEDLC := cMoedaLC CTJ->CTJ_TPSALD := cTpSald Else RecLock( "CTJ", .f. ) CTJ->CTJ_DESC := cDescRat CTJ->CTJ_MOEDLC := cMoedaLC CTJ->CTJ_TPSALD := cTpSald Endif For nCont := 1 To Len(aHeader) If (aHeader[nCont][10] != "V" ) FieldPut(FieldPos(aHeader[nCont][2]),; TMP->(FieldGet(FieldPos(aHeader[nCont][2])))) EndIf Next nCont MsUnLock() Elseif nOpc == 5 // Se for exclusao dbSelectArea("CTJ") dbSetOrder(1) If dbSeek(xFilial()+cRateio+TMP->CTJ_SEQUEN) RecLock("CTJ",.F.,.T.) dbDelete() MsUnlOCK() EndIf EndIf Else // Item deletado na MSGETDB dbSelectArea("CTJ") dbSetOrder(1) If dbSeek(xFilial()+cRateio+TMP->CTJ_SEQUEN) RecLock( "CTJ", .f., .t. ) DbDelete() MsUnlock() Endif EndIf dbSelectArea("TMP") dbSkip() Enddo RestArea(aSaveArea) Return /*/ +------------+---------+-------+-----------------------+------+----------+ | Funcao |CTB120TOK| Autor | <NAME> | Data | 24/07/00 | +------------+---------+-------+-----------------------+------+----------+ | Descricao | Valida MSGETDB -> Tudo OK | +------------+-----------------------------------------------------------+ | Sintaxe | Ctb120TOK(ExpC1) | +------------+-----------------------------------------------------------+ | Parametros | Nenhum | +------------+-----------------------------------------------------------+ | Retorno | Nenhum | +------------+-----------------------------------------------------------+ | Uso | CTBA120 | +------------+-----------------------------------------------------------+ /*/ Function Ctb120TOk() Local aSaveArea := GetArea() Local lRet := .T. Local nTotalD := 0 Local nTotalC := 0 dbSelectArea("TMP") dbGotop() While !Eof() If !TMP->CTJ_FLAG If !Ctb120LOK() lRet := .F. Exit EndiF If !Empty(TMP->CTJ_DEBITO) nTotalD += TMP->CTJ_PERCEN EndIf If !Empty(TMP->CTJ_CREDITO) nTotalC += TMP->CTJ_PERCEN EndIf EndIf dbSkip() EndDo nTotalD := Round(nTotalD,2) nTotalC := Round(nTotalC,2) If lRet IF (nTotalD > 0 .And. nTotalD != 100 ).Or. (nTotalC > 0 .And. nTotalC != 100) Help(" ",1,"CTJ100%") lRet := .F. EndIF EndIf RestArea(aSaveArea) Return lRet /*/ +------------+---------+-------+-----------------------+------+----------+ | Funcao |CTB120LOK| Autor | <NAME> | Data | 24/07/00 | +------------+---------+-------+-----------------------+------+----------+ | Descricao | Valida MSGETDB -> LinhaOK | +------------+-----------------------------------------------------------+ | Sintaxe | Ctb120LOK(ExpC1) | +------------+-----------------------------------------------------------+ | Parametros | Nenhum | +------------+-----------------------------------------------------------+ | Retorno | Nenhum | +------------+-----------------------------------------------------------+ | Uso | CTBA120 | +------------+-----------------------------------------------------------+ /*/ Function CTB120LOK() Local lRet := .T. Local nCont If !TMP->CTJ_FLAG If Empty(TMP->CTJ_PERCEN) Help(" ",1,"CTJVLZERO") lRet := .F. EndIf If lRet ValidaConta(TMP->CTJ_DEBITO,"1",,,.t.) EndIf If lRet ValidaConta(TMP->CTJ_CREDITO,"2",,,.T.) EndIf EndIf Return lRet /*/ +------------+---------+-------+-----------------------+------+----------+ | Funcao |CTB120Cri| Autor | <NAME> | Data | 24/07/00 | +------------+---------+-------+-----------------------+------+----------+ | Descricao | Cria Arquivo Temporario para MSGETDB | +------------+-----------------------------------------------------------+ | Sintaxe | Ctb120Cri(ExpA1,ExpC1) | +------------+-----------------------------------------------------------+ | Parametros | ExpA1 = Matriz com campos a serem criados | | | ExpC1 = Nome do arquivo temporario | +------------+-----------------------------------------------------------+ | Retorno | Nenhum | +------------+-----------------------------------------------------------+ | Uso | CTBA120 | +------------+-----------------------------------------------------------+ /*/ Function Ctb120Cria(aCampos,cArq) Local cChave Local aSaveArea := GetArea() cChave := "CTJ_SEQUEN" cArq := CriaTrab(aCampos,.t.) dbUseArea(.t.,,cArq,"TMP",.f.,.f.) RestArea(aSaveArea) Return /*/ +------------+----------+-------+-----------------------+------+----------+ | Funcao |CTB120Head| Autor | <NAME> | Data | 24/07/00 | +------------+----------+-------+-----------------------+------+----------+ | Descricao | Montar aHeader para arquivo temporario da MSGETDB | +------------+------------------------------------------------------------+ | Sintaxe | Ctb120Head(ExpA1) | +------------+------------------------------------------------------------+ | Parametros | ExpA1 = Matriz com campos que podem ser alterados | +------------+------------------------------------------------------------+ | Retorno | ExpA1 = Matriz com campos a serem criados no arq temporario| +------------+------------------------------------------------------------+ | Uso | CTBA120 | +------------+------------------------------------------------------------+ /*/ Function Ctb120Head(aAltera) Local aSaveArea:= GetArea() Local aFora := {"CTJ_RATEIO","CTJ_DESC","CTJ_MOEDLC","CTJ_TPSALD","CTJ_VALOR"} Local aCampos := {} Local nCriter := 0 PRIVATE nUsado := 0 // Montagem da matriz aHeader dbSelectArea("SX3") dbSetOrder(1) dbSeek("CTJ") While !EOF() .And. (x3_arquivo == "CTJ") If Alltrim(x3_campo) == "CTJ_SEQUEN" .Or. ; x3Uso(x3_usado) .and. cNivel >= x3_nivel If Ascan(aFora,Trim(X3_CAMPO)) <= 0 nUsado++ AADD(aHeader,{ TRIM(X3Titulo()), x3_campo, x3_picture,; x3_tamanho, x3_decimal, x3_valid,; x3_usado, x3_tipo, "TMP", x3_context } ) If Alltrim(x3_campo) <> "CTJ_SEQUEN" Aadd(aAltera,Trim(X3_CAMPO)) EndIf EndIF EndIF aAdd( aCampos, { SX3->X3_CAMPO, SX3->X3_TIPO, SX3->X3_TAMANHO,; SX3->X3_DECIMAL } ) dbSkip() EndDO Aadd(aCampos,{"CTJ_FLAG","L",1,0}) RestArea(aSaveArea) Return aCampos /*/ +------------+----------+-------+-----------------------+------+----------+ | Funcao |CTB120Carr| Autor | <NAME> | Data | 24/07/00 | +------------+----------+-------+-----------------------+------+----------+ | Descricao | Carrega dados para MSGETDB | +------------+------------------------------------------------------------+ | Sintaxe | Ctb120Carr(ExpN1) | +------------+------------------------------------------------------------+ | Parametros | ExpN1 = Opcao do Menu -> Inclusao / Alteracao etc | +------------+------------------------------------------------------------+ | Retorno | Nenhum | +------------+------------------------------------------------------------+ | Uso | CTBA120 | +------------+------------------------------------------------------------+ /*/ Function CTB120Carr(nOpc) Local aSaveArea:= GetArea() Local cAlias := "CTJ" Local nPos If nOpc != 3 // Visualizacao / Alteracao / Exclusao cRateio := CTJ->CTJ_RATEIO dbSelectArea("CTJ") dbSetOrder(1) If dbSeek(xFilial()+cRateio) While !Eof() .And. CTJ->CTJ_FILIAL == xFilial() .And.; CTJ->CTJ_RATEIO == cRateio dbSelectArea("TMP") dbAppend() For nCont := 1 To Len(aHeader) nPos := FieldPos(aHeader[nCont][2]) If (aHeader[nCont][08] <> "M" .And. aHeader[nCont][10] <> "V" ) FieldPut(nPos,(cAlias)- >(FieldGet(FieldPos(aHeader[nCont][2])))) EndIf Next nCont TMP->CTJ_FLAG := .F. dbSelectArea("CTJ") dbSkip() EndDo EndIf Else dbSelectArea("TMP") dbAppend() For nCont := 1 To Len(aHeader) If (aHeader[nCont][08] <> "M" .And. aHeader[nCont][10] <> "V" ) nPos := FieldPos(aHeader[nCont][2]) FieldPut(nPos,CriaVar(aHeader[nCont][2],.T.)) EndIf Next nCont TMP->CTJ_FLAG := .F. TMP->CTJ_SEQUEN:= "001" EndIf dbSelectArea("TMP") dbGoTop() RestArea(aSaveArea) Return /*/ +------------+---------+-------+-----------------------+------+----------+ | Funcao |CT120Moed| Autor | <NAME> | Data | 24/07/00 | +------------+---------+-------+-----------------------+------+----------+ | Descricao | Valida Moeda do Lancamento | +------------+-----------------------------------------------------------+ | Sintaxe | Ctb120Moed(ExpC1) | +------------+-----------------------------------------------------------+ | Parametros | ExpC1 = Moeda a ser validada | +------------+-----------------------------------------------------------+ | Retorno | .T./.F. | +------------+-----------------------------------------------------------+ | Uso | CTBA120 | +------------+-----------------------------------------------------------+ /*/ Function Ct120MoedLC(cMoeda) Local aCtbMoeda:= {} Local lRet := .T. aCtbMoeda := CtbMoeda(cMoeda) If Empty(aCtbMoeda[1]) Help(" ",1,"NOMOEDA") lRet := .F. Endif Return lRet
06db4e6bceb426db928b7fd77eaa50936b5d4b2f
[ "Kotlin" ]
2
Kotlin
cardosk/Teste
86a063c65c94483aafdae9995c93c0bb30cb6c92
3cac2068af56daeeb527990da2dcd9a00ec542c3
refs/heads/master
<file_sep>var express = require('express'); var app = express(); var http = require('http').Server(app); var io = require('socket.io')(http); var watson = require('watson-developer-cloud'); var conversation = watson.conversation({ username: 'af3d8481-bced-40df-9643-087d68b9fb39', password: '<PASSWORD>', version: 'v1', version_date: '2016-07-11' }); app.set('port', (process.env.PORT || 5000)); app.use(express.static(__dirname + '/public')); // views is directory for all template files app.set('views', __dirname + '/views'); app.set('view engine', 'ejs'); app.get('/', function(request, response) { response.render('pages/index'); }); app.post('/', function(request, response) { response.render('pages/index'); }); io.on('connection', function(socket){ var context = {}; conversation.message({ workspace_id: '3c360d9b-06a8-4175-9d05-1c11c50aa672', input: {'text': 'start'}, context: context }, function(err, response) { context = response.context; if (err){ io.emit('error', err); }else{ var text = response.output.text[0]; var data = {user: "Italu", msg: text} io.emit('chat message', data); } }); socket.on('chat message', function(msg){ var data = {user: "Usuário", msg: msg} io.emit('chat message', data); conversation.message({ workspace_id: '3c360d9b-06a8-4175-9d05-1c11c50aa672', input: {'text': msg}, context: context }, function(err, response) { context = response.context; if (err){ io.emit('error', err); }else{ var text = response.output.text[0]; var data = {user: "Italu", msg: text} io.emit('chat message', data); } }); }); socket.on('disconnect', function(){ console.log('user disconnected'); }); }); http.listen(app.get('port'), function() { console.log('Express server listening on port ' + app.get('port')); }); <file_sep>var socket = io(); $('.chat-footer form').submit(function() { socket.emit('chat message', $('.chat-footer input').val()); $('.chat-footer input').val(''); return false; }); socket.on('chat message', function(data){ if (data.user=="Italu") { $('.chat-body ul').append($('<li>').html("<h2>Italu</h2><p>"+data.msg+"</p>")); }else{ $('.chat-body ul').append($('<li class="user">').html("<h2>"+data.user+"</h2><p>"+data.msg+"</p>")); } $('html, body').animate({ scrollTop: $(document).height()-$(window).height()}, 0 ); }); socket.on('error', function(msg){ console.log(msg); });
cd7d845c81ec82a24bc8404b068c8d630f3cf6a2
[ "JavaScript" ]
2
JavaScript
jcmidia/italu-chat
7ca69bbd4458a5b9e3514eef84c57bbc7cedc401
4b914330bd4916f7a1420ece7d09baac862ce9c9
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 GUIApplication; /** * * @author Philip */ public class GUIWord extends javax.swing.JFrame { private GUIWordController wc; public GUIWord(GUIWordController controller){ wc = controller; initComponents(); showStartScreen(); jTextField1.setText(""); jTextField1.setColumns(10); jLabel2.setText(""); jButton2.setText("RESTART PRACTISE"); jButton2.setVisible(false); jLabel3.setVisible(false); } public void showStartScreen(){ jButton3.setVisible(true); jButton4.setVisible(true); jButton5.setVisible(true); jLabel3.setVisible(false); jLabel4.setVisible(false); jLabel5.setVisible(false); jLabel1.setVisible(false); jLabel2.setVisible(false); jTextField1.setVisible(false); jButton1.setVisible(false); jButton2.setVisible(false); jButton6.setVisible(false); } public void showLanguageSelectionScreen(){ LanguageSelectionScreen lss = new LanguageSelectionScreen(wc); lss.setVisible(true); } public void showPractiseScreen(){ jButton3.setVisible(false); jButton4.setVisible(false); jButton5.setVisible(false); jButton6.setVisible(true); jLabel4.setVisible(true); jLabel1.setVisible(true); jLabel2.setVisible(true); jLabel5.setVisible(true); jTextField1.setVisible(true); jButton1.setVisible(true); jButton2.setVisible(true); } public void enableResults(int numberOfCorrects, int totalNumberOfWords){ jLabel3.setText("You got " + String.valueOf(numberOfCorrects) + " out of " + String.valueOf(totalNumberOfWords) + " correct! Well done!"); jLabel3.setVisible(true); jButton2.setVisible(true); } public void setNativeWord(String word){ jLabel1.setText(word); } public String getNativeWord(){ return jLabel1.getText(); } @SuppressWarnings("unchecked") // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents private void initComponents() { jLabel1 = new javax.swing.JLabel(); jTextField1 = new javax.swing.JTextField(); jLabel2 = new javax.swing.JLabel(); jButton1 = new javax.swing.JButton(); jLabel3 = new javax.swing.JLabel(); jButton2 = new javax.swing.JButton(); jLabel4 = new javax.swing.JLabel(); jLabel5 = new javax.swing.JLabel(); jButton3 = new javax.swing.JButton(); jButton4 = new javax.swing.JButton(); jButton5 = new javax.swing.JButton(); jButton6 = new javax.swing.JButton(); setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE); jLabel1.setText("jLabel1"); jTextField1.setText("jTextField1"); jTextField1.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jTextField1ActionPerformed(evt); } }); jTextField1.addKeyListener(new java.awt.event.KeyAdapter() { public void keyPressed(java.awt.event.KeyEvent evt) { jTextField1KeyPressed(evt); } }); jLabel2.setFont(new java.awt.Font("Tahoma", 0, 24)); // NOI18N jLabel2.setText("jLabel2"); jButton1.setText("ADD NEW WORD"); jButton1.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jButton1ActionPerformed(evt); } }); jLabel3.setText("RIGHTS"); jButton2.setText("jButton2"); jButton2.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jButton2ActionPerformed(evt); } }); jLabel4.setText("Translate the following word"); jLabel5.setText("Translation: "); jButton3.setText("START PRACTISE"); jButton3.setToolTipText(""); jButton3.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jButton3ActionPerformed(evt); } }); jButton4.setText("ADD NEW WORDS"); jButton4.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jButton4ActionPerformed(evt); } }); jButton5.setText("HELP"); jButton6.setText("Return to start screen"); jButton6.setAutoscrolls(true); jButton6.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jButton6ActionPerformed(evt); } }); javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane()); getContentPane().setLayout(layout); layout.setHorizontalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addGap(263, 263, 263) .addComponent(jLabel5) .addGap(48, 48, 48) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addComponent(jLabel1) .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) .addGroup(layout.createSequentialGroup() .addComponent(jTextField1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 108, Short.MAX_VALUE) .addComponent(jButton1) .addGap(140, 140, 140)))) .addGroup(layout.createSequentialGroup() .addGap(52, 52, 52) .addComponent(jLabel3, javax.swing.GroupLayout.PREFERRED_SIZE, 180, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(61, 61, 61) .addComponent(jButton2) .addGap(0, 0, Short.MAX_VALUE)) .addGroup(layout.createSequentialGroup() .addGap(230, 230, 230) .addComponent(jLabel2, javax.swing.GroupLayout.PREFERRED_SIZE, 360, javax.swing.GroupLayout.PREFERRED_SIZE) .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup() .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup() .addComponent(jLabel4, javax.swing.GroupLayout.PREFERRED_SIZE, 315, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(232, 232, 232)) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup() .addComponent(jButton6) .addGap(117, 117, 117)))) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addGap(267, 267, 267) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jButton5, javax.swing.GroupLayout.PREFERRED_SIZE, 296, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jButton3, javax.swing.GroupLayout.PREFERRED_SIZE, 296, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jButton4, javax.swing.GroupLayout.PREFERRED_SIZE, 296, javax.swing.GroupLayout.PREFERRED_SIZE)) .addContainerGap(267, Short.MAX_VALUE))) ); layout.setVerticalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addGap(61, 61, 61) .addComponent(jLabel2, javax.swing.GroupLayout.PREFERRED_SIZE, 30, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(36, 36, 36) .addComponent(jLabel4, javax.swing.GroupLayout.PREFERRED_SIZE, 39, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(26, 26, 26) .addComponent(jLabel1) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jTextField1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jLabel5))) .addGroup(layout.createSequentialGroup() .addGap(21, 21, 21) .addComponent(jButton1))) .addGap(86, 86, 86) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jButton2) .addComponent(jLabel3, javax.swing.GroupLayout.PREFERRED_SIZE, 87, javax.swing.GroupLayout.PREFERRED_SIZE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 50, Short.MAX_VALUE) .addComponent(jButton6) .addGap(59, 59, 59)) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addGap(135, 135, 135) .addComponent(jButton3, javax.swing.GroupLayout.PREFERRED_SIZE, 92, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jButton4, javax.swing.GroupLayout.PREFERRED_SIZE, 92, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jButton5, javax.swing.GroupLayout.PREFERRED_SIZE, 92, javax.swing.GroupLayout.PREFERRED_SIZE) .addContainerGap(136, Short.MAX_VALUE))) ); pack(); }// </editor-fold>//GEN-END:initComponents private void jTextField1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jTextField1ActionPerformed // TODO add your handling code here: }//GEN-LAST:event_jTextField1ActionPerformed private void jTextField1KeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_jTextField1KeyPressed int keyPressed = evt.getKeyCode(); if(keyPressed == java.awt.event.KeyEvent.VK_ENTER){ String correctWord = getNativeWord(); String userWord = jTextField1.getText(); boolean isCorrect = wc.isCorrect(correctWord, userWord); if(isCorrect){ jLabel2.setText("CORRECT!"); } else { jLabel2.setText("INCORRECT!"); } jTextField1.setText(""); wc.showWord(); } }//GEN-LAST:event_jTextField1KeyPressed private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed java.awt.EventQueue.invokeLater(new Runnable() { public void run() { AddWordGUI awGUI = new AddWordGUI(new WordHandler(wc.getCurrentFilename())); awGUI.setVisible(true); awGUI.setDefaultCloseOperation(javax.swing.JFrame.HIDE_ON_CLOSE); } }); }//GEN-LAST:event_jButton1ActionPerformed private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton2ActionPerformed jLabel3.setVisible(false); jButton2.setVisible(false); wc.startAgain(wc.getCurrentFilename());// TODO add your handling code here: }//GEN-LAST:event_jButton2ActionPerformed private void jButton3ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton3ActionPerformed showLanguageSelectionScreen(); }//GEN-LAST:event_jButton3ActionPerformed private void jButton4ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton4ActionPerformed AddWordGUI gui = new AddWordGUI(new WordHandler(wc.getCurrentFilename())); gui.setVisible(true); gui.setDefaultCloseOperation(javax.swing.JFrame.HIDE_ON_CLOSE); }//GEN-LAST:event_jButton4ActionPerformed private void jButton6ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton6ActionPerformed showStartScreen(); }//GEN-LAST:event_jButton6ActionPerformed /** * @param args the command line arguments */ // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JButton jButton1; private javax.swing.JButton jButton2; private javax.swing.JButton jButton3; private javax.swing.JButton jButton4; private javax.swing.JButton jButton5; private javax.swing.JButton jButton6; private javax.swing.JLabel jLabel1; private javax.swing.JLabel jLabel2; private javax.swing.JLabel jLabel3; private javax.swing.JLabel jLabel4; private javax.swing.JLabel jLabel5; private javax.swing.JTextField jTextField1; // End of variables declaration//GEN-END:variables } <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 GUIApplication; import java.util.Scanner; /** * * @author Philip */ public class GUIWordController { private WordHandler wh; private Scanner inputScanner; private GUIWord GUI; private int numberOfCorrects; private int totalNumberOfWords; private String filename; public GUIWordController(){ inputScanner = new Scanner(System.in); setupGUI(); } public void setupGUI(){ GUI = new GUIWord(this); GUI.setVisible(true); } public void startAgain(String filename){ this.filename = filename; GUI.showPractiseScreen(); numberOfCorrects = 0; wh = new WordHandler(filename); totalNumberOfWords = wh.getNumberOfWordsRemaining(); startApplication(); } public String getCurrentFilename(){ return filename; } public boolean isCorrect(String nativeWord, String userWord){ String correctWord = wh.getWordByKey(nativeWord); boolean isCorrect = correctWord.toUpperCase().equals(userWord.toUpperCase()); if(isCorrect){ numberOfCorrects += 1; } return isCorrect; } public String showWord(){ if(!wh.isWordsRemaining()){ GUI.enableResults(numberOfCorrects, totalNumberOfWords); return ""; } else { String wordToShow = wh.getWord(); String correctWord = wh.getWordByKey(wordToShow); GUI.setNativeWord(wordToShow); return correctWord; } } public void addWord(String nativeWord, String foreignWord){ wh.addWord(nativeWord, foreignWord); } public void startApplication(){ showWord(); } }
9ee8294df63e4b157bdece3f2f6bd01300f2014f
[ "Java" ]
2
Java
phiandre/Language
2f2861a54cf723062340c1655057ce1d56c7c409
8ac8ebad18af2dfac71dbf91e08d3e78590806ce