text
stringlengths
184
4.48M
<script lang="ts"> import {defineComponent} from 'vue' import VFontAwesomeBtn from "@/components/Buttons/VFontAwesomeBtn.vue"; import FontAwesomeBtn from "@/components/Buttons/FontAwesomeBtn.vue"; import {LeaveTypes} from "@/globals.ts"; import {useGameStore} from "@/store"; export default defineComponent({ name: "SaveGameDialog", computed: { LeaveTypes() { return LeaveTypes } }, components: {FontAwesomeBtn, VFontAwesomeBtn}, setup() { const colorStore = useColorStore(); return {colorStore} }, emits:{ closeMe(){return true}, }, props: { visible: { type: Boolean, default: false } }, methods: { getColor(color: string = 'lighten1'){ return this.colorStore.currentColor[color] }, leaveGame(leaveType: LeaveTypes) { const gameStore = useGameStore(); gameStore.exit(leaveType); } } }) </script> <template> <v-dialog v-model="visible" width="500" :persistent="true" > <v-card class="ml-save-dialog" > <v-card-title> <v-row> <v-col cols="11" > {{ $t('exit_dialog.title')}} </v-col> <v-col> <font-awesome-btn :icon="['fas', 'fa-close']" @click="$emit('closeMe')" /> </v-col> </v-row> </v-card-title> <v-card-text class="ml-save-dialog-text" > {{ $t('exit_dialog.description') }} </v-card-text> <v-card-actions class="ml-dialog-actions evenly" > <v-font-awesome-btn :btn-color="getColor()" btn-variant="outlined" @click="leaveGame(LeaveTypes.saveLocal)" :icon="['fas', 'fa-download']" iconSize="lg" :text="$t('exit_dialog.save')" icon-text-spacing="me-2" :tooltip-text="$t('exit_dialog.tooltips.save_local')" tooltip-location="bottom" /> <v-font-awesome-btn :btn-color="getColor()" btn-variant="elevated" @click="leaveGame(LeaveTypes.saveRemote)" :icon="['fas', 'fa-cloud-upload-alt']" iconSize="lg" :text="$t('exit_dialog.save')" icon-text-spacing="me-2" :tooltip-text="$t('exit_dialog.tooltips.save_remote')" tooltip-location="bottom" /> <v-font-awesome-btn :btn-color="getColor()" btn-variant="plain" @click="leaveGame(LeaveTypes.exit)" :icon="['fas', 'fa-sign-out-alt']" iconSize="lg" :text="$t('exit_dialog.exit')" icon-text-spacing="me-2" :tooltip-text="$t('exit_dialog.tooltips.exit')" tooltip-location="bottom" /> </v-card-actions> </v-card> </v-dialog> </template> <style scoped lang="scss"> @import "@/scss/ml-dialog"; </style>
/** * Copyright 2012 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.broadleafcommerce.inventory.domain; import java.io.Serializable; import java.util.Date; import java.util.List; import org.broadleafcommerce.core.catalog.domain.Sku; import com.ssbusy.core.invoicing.domain.Invoicing; public interface Inventory extends Serializable { /** * Retrieves the unique identifier of the Inventory * * @return id */ public Long getId(); /** * Sets the unique identifier of the Inventory * * @param id */ public void setId(Long id); /** * Retrieves the fulfillment location information related to this inventory * * @return FulfillmentLocation */ public FulfillmentLocation getFulfillmentLocation(); /** * Sets the fulfillment location information related to this inventory * * @param fulfillmentLocation */ public void setFulfillmentLocation(FulfillmentLocation fulfillmentLocation); /** * Retrieves the sku for this Inventory * * @return sku */ public Sku getSku(); /** * Sets the sku for this Inventory * * @param sku */ public void setSku(Sku sku); /** * Retrieves the actual inventory in possession of the business * * @return quantity */ public Integer getQuantityOnHand(); /** * Sets the actual inventory in possession of the business * * @param quantity */ public void setQuantityOnHand(Integer quantity); /** * Retrieves the inventory available for sale. This is typically the * difference of quantity on hand reduced by the inventory allocated for * existing orders. * * @return quantityAvailable */ public Integer getQuantityAvailable(); /** * Sets the inventory available for sale. * * @param quantity */ public void setQuantityAvailable(Integer quantity); /** * @return 库存警戒线,低于该数则必须补货 */ public Integer getQuantitySafe(); /** * @param 库存警戒线 */ public void setQuantitySafe(Integer quantity); public Integer getQuantitySafeDiff(); public void setQuantitySafeDiff(Integer diff); /** * Retrieves the expected availability date * * @return Date */ public Date getExpectedAvailabilityDate(); /** * Sets the expected availability date * * @param expectedAvailabilityDate */ public void setExpectedAvailabilityDate(Date expectedAvailabilityDate); /** * Retrieves the version set by Hibernate. Version has a getter only. * * @return */ public Long getVersion(); public List<Invoicing> getInvoicings(); public void setInvoicings(List<Invoicing> invoicings); }
import { UserRepository } from "./@UserRepository.Service"; import { AccessRepository } from "../Access/@AccessRepository.Service"; import { UseCase } from "../../.shared/UseCase"; import { Message } from "../../.shared/Interfaces" import { hash } from "bcryptjs" type CreateUserProps = { name: string; email: string; password: string; accessName: string; } class CreateUserService implements UseCase<CreateUserProps, Array<Object> | Message> { constructor( private readonly repository: UserRepository, private readonly accessRepository: AccessRepository ) {} async execute(request: CreateUserProps): Promise< Array<Object> | Message> { const { name, email, password, accessName } = request; const passwordHash = await hash(password, 8) { const userExists = await this.repository.isUniqueEmail(email); if(userExists) { const message: Message = { text: `Error - User already exists` } return message } } { const accessExists = await this.accessRepository.findUniqueAccess(accessName) if(!accessExists) { const message: Message = { text: `Error - This Nivel of access does not exist` } return message } } const message: Message = { text: `User created successfully` } const userCreate = await this.repository.create({ name, email, password: passwordHash, accessName }); return [ userCreate, message ]; } } export { CreateUserService };
// Collapsible var coll = document.getElementsByClassName("collapsible"); for (let i = 0; i < coll.length; i++) { coll[i].addEventListener("click", function () { this.classList.toggle("active"); var content = this.nextElementSibling; if (content.style.maxHeight) { content.style.maxHeight = null; } else { content.style.maxHeight = content.scrollHeight + "px"; } }); } function getTime() { let today = new Date(); hours = today.getHours(); minutes = today.getMinutes(); if (hours < 10) { hours = "0" + hours; } if (minutes < 10) { minutes = "0" + minutes; } return hours + ":" + minutes; } function wrapChatText(message, type) { return '<p class="' + type + '"><span>' + message + '</span></p>' } function wrapUserMessage(message) { return wrapChatText(message, 'userText') } function wrapBotMessage(message) { return wrapChatText(message, 'botText') } // Gets the first message function firstBotMessage() { let firstMessage = "Здравствуйте! Меня зовут Светлана. Я — нейросетевой ассистент по услугам МТС. Буду рада помочь вам разобраться в услуге \"Мобильные сотрудники\"" document.getElementById("botStarterMessage").innerHTML = wrapBotMessage(firstMessage); let time = getTime(); $("#chat-timestamp").append(time); document.getElementById("userInput").scrollIntoView(false); } firstBotMessage(); // Retrieves the response function handleBotResponse(botResponse) { $("#chatbox").append(wrapBotMessage(botResponse)); document.getElementById("chat-bar-bottom").scrollIntoView(true); } //Gets the text from the input box and processes it function proceedUserMessage() { let userText = $("#textInput").val(); if (userText === "") { return } let userHtml = wrapUserMessage(userText); $("#textInput").val(""); $("#chatbox").append(userHtml); document.getElementById("chat-bar-bottom").scrollIntoView(true); setTimeout(() => { getBotResponse(userText); }, 1000) } function sendButton() { proceedUserMessage(); } // Press enter to send a message $("#textInput").keypress(function (e) { if (e.which == 13) { proceedUserMessage(); } });
import javax.swing.*; import javax.swing.table.DefaultTableModel; import java.awt.*; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.net.URL; import java.sql.*; // 学生添加对话框类 public class StudentAddDialog extends JFrame { private Connection connection; private JFrame frame = new JFrame("Formulaire étudiant"); private static DefaultTableModel tableModel; public StudentAddDialog(Connection connection, JFrame frame, DefaultTableModel tableModel) { this.connection = connection; this.frame = frame; this.tableModel = tableModel; setTitle("Ajouter Étudiant"); setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE); setSize(new Dimension(400, 200)); JPanel mainPanel = new JPanel(new GridLayout(5, 2)); JTextField studentNameField = new JTextField(10); JTextField studentFirstNameField = new JTextField(10); JComboBox<String> formationComboBox = new JComboBox<>(getFormationOptions()); JComboBox<String> promotionComboBox = new JComboBox<>(getPromotionOptions()); mainPanel.add(new JLabel("Nom :")); mainPanel.add(studentNameField); mainPanel.add(new JLabel("Prénom :")); mainPanel.add(studentFirstNameField); mainPanel.add(new JLabel("Formation :")); mainPanel.add(formationComboBox); mainPanel.add(new JLabel("Promotion :")); mainPanel.add(promotionComboBox); JButton validerButton = new JButton("Valider"); JButton effacerButton = new JButton("Effacer"); mainPanel.add(validerButton); mainPanel.add(effacerButton); add(mainPanel); ImageIcon icon = new ImageIcon(getClass().getResource("/Picture/logo_D.jpg")); setIconImage(icon.getImage()); validerButton.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { String nom = studentNameField.getText(); String prenom = studentFirstNameField.getText(); String formation = (String) formationComboBox.getSelectedItem(); String promotion = (String) promotionComboBox.getSelectedItem(); int formationNumero = -1; nom = capitalizeFirstLetter(nom); prenom = capitalizeFirstLetter(prenom); if (nom.isEmpty() || prenom.isEmpty()) { JOptionPane.showMessageDialog(frame, "Les champs 'Nom' et 'Prénom' ne peuvent pas être vides.", "Erreur", JOptionPane.ERROR_MESSAGE); } else { switch (formation.toLowerCase() + promotion.toLowerCase()) { case "idinitial": formationNumero = 1; break; case "idalternance": formationNumero = 2; break; case "idcontinue": formationNumero = 3; break; case "sitninitial": formationNumero = 4; break; case "sitnalternance": formationNumero = 5; break; case "sitncontinue": formationNumero = 6; break; case "ifinitial": formationNumero = 7; break; case "ifalternance": formationNumero = 8; break; case "ifcontinue": formationNumero = 9; break; default: JOptionPane.showMessageDialog(frame, "Formation ou promotion non valides", "Erreur", JOptionPane.ERROR_MESSAGE); break; } if (formationNumero != -1) { try { String sql = "INSERT INTO Etudiants (nom, prenom, formation_id) VALUES (?, ?, ?)"; PreparedStatement preparedStatement = connection.prepareStatement(sql); preparedStatement.setString(1, nom); preparedStatement.setString(2, prenom); preparedStatement.setInt(3, formationNumero); preparedStatement.executeUpdate(); tableModel.addRow(new Object[]{getLastInsertedStudentId(), nom, prenom, formation, promotion}); studentNameField.setText(""); studentFirstNameField.setText(""); formationComboBox.setSelectedIndex(0); promotionComboBox.setSelectedIndex(0); JOptionPane.showMessageDialog(frame, "Étudiant ajouté avec succès", "Confirmation", JOptionPane.INFORMATION_MESSAGE); } catch (SQLException ex) { ex.printStackTrace(); } } } } }); effacerButton.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { studentNameField.setText(""); studentFirstNameField.setText(""); formationComboBox.setSelectedIndex(0); promotionComboBox.setSelectedIndex(0); } }); setLocationRelativeTo(null); setVisible(true); } private DefaultComboBoxModel<String> getFormationOptions() { DefaultComboBoxModel<String> model = new DefaultComboBoxModel<>(); try { String query = "SELECT DISTINCT nom FROM Formations"; PreparedStatement preparedStatement = connection.prepareStatement(query); ResultSet resultSet = preparedStatement.executeQuery(); while (resultSet.next()) { String formation = resultSet.getString("nom"); model.addElement(formation); } } catch (SQLException ex) { ex.printStackTrace(); } return model; } private DefaultComboBoxModel<String> getPromotionOptions() { DefaultComboBoxModel<String> model = new DefaultComboBoxModel<>(); try { String query = "SELECT DISTINCT promotion FROM Formations"; PreparedStatement preparedStatement = connection.prepareStatement(query); ResultSet resultSet = preparedStatement.executeQuery(); while (resultSet.next()) { String promotion = resultSet.getString("promotion"); model.addElement(promotion); } } catch (SQLException ex) { ex.printStackTrace(); } return model; } private String capitalizeFirstLetter(String input) { if (input == null || input.isEmpty()) { return input; } return input.substring(0, 1).toUpperCase() + input.substring(1); } private int getLastInsertedStudentId() { int lastInsertedId = -1; try { Statement statement = connection.createStatement(); ResultSet resultSet = statement.executeQuery("SELECT LAST_INSERT_ID() as last_id"); if (resultSet.next()) { lastInsertedId = resultSet.getInt("last_id"); } } catch (SQLException ex) { ex.printStackTrace(); } return lastInsertedId; } }
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <!-- fonts --> <link rel="preconnect" href="https://fonts.googleapis.com" /> <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin /> <link href="https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600;700;800;900&family=Quicksand:wght@400;500;600;700&display=swap" rel="stylesheet" /> <!-- icons --> <link href="https://unpkg.com/[email protected]/css/boxicons.min.css" rel="stylesheet" /> <!-- styles --> <link rel="stylesheet" href="./reset.css" /> <link rel="stylesheet" href="./normalize.css" /> <link rel="stylesheet" href="./style.css" /> <title>Samar Karam</title> </head> <body> <!-- site header --> <header class="header"> <!-- media logo --> <div class="header__wrapper container"> <a class="header__logo" href="./index.html"> <img class="header__img" src="./images/logo.svg" alt="site logo" width="300" height="90" /> </a> <nav class="header__nav nav"> <ul class="nav__list" role="list"> <li class="nav__item"> <a class="nav__link" href="./index.html">home</a> </li> <li class="nav__item"> <a class="nav__link" href="#">cultural hub</a> </li> <li class="nav__item"> <a class="nav__link" href="./index.html"> <img class="nav__img" src="./images/logo.svg" alt="site logo" width="300" height="90" /> </a> </li> <li class="nav__item"> <a class="nav__link" href="./resources.html">resources</a> </li> <li class="nav__item"> <a class="nav__link active" href="./contact.html">contact me</a> </li> </ul> </nav> <button class="header__toggler"> <i class="header__icon bx bx-menu-alt-right"></i> </button> <ul class="nav__list-mob" role="list"> <li class="nav__item-mob"> <a class="nav__link-mob" href="./index.html">home</a> </li> <li class="nav__item-mob"> <a class="nav__link-mob" href="#">cultural hub</a> </li> <li class="nav__item-mob"> <a class="nav__link-mob" href="./resources.html">resources</a> </li> <li class="nav__item-mob"> <a class="nav__link-mob active" href="./contact.html">contact me</a> </li> </ul> </div> </header> <!-- site main --> <main class="main"> <section class="contact"> <h2 class="contact__title site-title">contact me</h2> <div class="contact__container container"> <div class="contact__box contact-box"> <form id="contactForm" class="contact-box__form" action="https://formspree.io/your-email" method="POST" > <input id="fullName" class="contact-box__input" type="text" name="Full Name" placeholder="Full Name" required /> <input id="email" class="contact-box__input" type="email" name="_replyto" placeholder="Your Email" required /> <textarea id="message" class="contact-box__input contact-box__textarea" name="Message" placeholder="Your Message" required ></textarea> <button id="submitButton" class="contact-box__btn" type="submit"> Submit </button> </form> </div> </div> </section> </main> <!-- site footer --> <footer class="footer"> <div class="footer__container container"> <ul class="footer__list" role="list"> <li class="footer__item"> <a class="footer__link" href="./index.html">home</a> </li> <li class="footer__item"> <a class="footer__link" href="./cultural_hub.html">cultural hub</a> </li> <li class="footer__item"> <a class="footer__link" href="@[email protected]">resources</a> </li> <li class="footer__item"> <a class="footer__link active" href="+971509066491">contact me</a> </li> </ul> <ul class="footer__social social" role="list"> <li class="social__item"> <a class="social__link" href="#"> <i class="social__img bx bxl-instagram-alt"></i> </a> </li> <li class="social__item"> <a class="social__link" href="#"> <i class="social__img bx bxl-facebook"></i> </a> </li> <li class="social__item"> <a class="social__link" href="#"> <i class="social__img bx bxl-linkedin-square"></i> </a> </li> <li class="social__item"> <a class="social__link" href="#"> <i class="social__img bx bxl-youtube"></i> </a> </li> <li class="social__item"> <a class="social__link" href="#"> <i class="social__img bx bxl-twitter"></i> </a> </li> <li class="social__item"> <a class="social__link" href="#"> <i class="social__img bx bxl-tiktok"></i> </a> </li> </ul> <span class="footer_copy">Copyright © 2023 Samar Karam</span> </div> </footer> <script src="./main.js"></script> </body> </html>
/* *Copyright (c) 2022, kaydxh * *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. */ package opentelemetry import ( "time" "github.com/kaydxh/golang/pkg/monitor/opentelemetry/metric" "github.com/kaydxh/golang/pkg/monitor/opentelemetry/tracer" ) func WithMeterPushExporter(pushExporterBuilder metric.PushExporterBuilder) OpenTelemetryOption { return OpenTelemetryOptionFunc(func(o *OpenTelemetry) { o.opts.meterOptions = append(o.opts.meterOptions, metric.WithPushExporter(pushExporterBuilder)) }) } func WithMeterPullExporter(pullExporterBuilder metric.PullExporterBuilder) OpenTelemetryOption { return OpenTelemetryOptionFunc(func(o *OpenTelemetry) { o.opts.meterOptions = append(o.opts.meterOptions, metric.WithPullExporter(pullExporterBuilder)) }) } func WithMetricCollectDuration(period time.Duration) OpenTelemetryOption { return OpenTelemetryOptionFunc(func(o *OpenTelemetry) { o.opts.meterOptions = append(o.opts.meterOptions, metric.WithCollectPeriod(period)) }) } func WithTracerExporter(exporterBuilder tracer.TracerExporterBuilder) OpenTelemetryOption { return OpenTelemetryOptionFunc(func(o *OpenTelemetry) { o.opts.tracerOptions = append(o.opts.tracerOptions, tracer.WithExporterBuilder(exporterBuilder)) }) }
// // GChild.swift // Gululu // // Created by Baker on 17/3/10. // Copyright © 2017年 Ray Xu. All rights reserved. // import UIKit enum ChildPetBottle: Int{ case none = 0 case pet case both } var activeChildID: String = "" class GChild: NSObject { static let share = GChild() var drinkWaterDayArray = [Int]() var drinkWaterHourArray = [Int]() var lastDrinkUpdate : Date = Date() let defaultRecommendValue : Float = 960 func getActiveChildID() -> String { if isValidString(activeChildID){ return activeChildID } if isValidString(GUser.share.activeChild?.childID){ return (GUser.share.activeChild?.childID)! }else{ let childid = GUser.share.readActiveChildID() if isValidString(childid){ return childid! }else{ return "0" } } } func updateChild() { let child:Children? = createObject(Children.self, objectID: activeChildID) guard child?.childID != nil else { return } child!.update(.fetch, uiCallback: { _ in }) } func deleteChildFromNet(_ cloudCallback:@escaping (Bool) -> Void) { let children : Children? = createObject(Children.self, objectID: activeChildID) guard children != nil else { cloudCallback(false) return } children?.remove(uiCallback: { result in cloudCallback(result.boolValue) }) } func readChildListFromDB() -> [Children]? { let childListFromData:[Children]? = createObjects(Children.self) as? [Children] guard childListFromData != nil else { return [Children]() } return childListFromData! } func isHaveChild() -> Bool { let childListFromData:[Children]? = readChildListFromDB() let child = childListFromData?.first guard child?.childID != nil else { return false } return true } func syncChild(_ dic : NSDictionary,handleObject : NSObject) { let childListFromData:[Children]? = readChildListFromDB() guard childListFromData?.count != 0 else { return } if cloudObj().getOperationFromObject(handleObject) == .fetchAll{ for i in 0...(childListFromData?.count)!-1 { let child = childListFromData?[i] backgroundMoc?.delete(child!) } }else{ for i in 0...(childListFromData?.count)!-1 { let child = childListFromData?[i] if child?.childID == nil { backgroundMoc?.delete(child!) } } } saveContext() } func childIsHaveCup() -> Bool { let child : Children? = createObject(Children.self, objectID: activeChildID) guard child?.childID != nil else { return false } if child?.hasCup == 1 { return true }else{ return false } } func childIsHaveCupFromChild(_ child : Children) -> Bool { guard child.childID != nil else { return false } if child.hasCup == 1 { return true }else{ return false } } func deleteAllChildIfSame(childID:String?) { if childID == ""{ return }else{ let childListFromData:[Children]? = readChildListFromDB() for i in 0...(childListFromData?.count)!-1 { let child = childListFromData?[i] if child?.childID == childID { backgroundMoc?.delete(child!) } } saveContext() } } func checkHabitResult(result : Int) -> Int { var str : Int = 0 if result > 100{ str = 100 } if result < 60 { str = 60 } str = result saveHabitIndex(str) return str } //saveHabitex func saveHabitIndex(_ habitScore : Int) { let key = habitIndexKey.appending(activeChildID) UserDefaults.standard.set(habitScore, forKey: key) } func readHabitIndex() -> Int { let key = habitIndexKey.appending(activeChildID) let myHabitx = UserDefaults.standard.object(forKey: key) as! Int? if myHabitx == nil{ return 60 } if myHabitx > 100{ return 100 } if myHabitx < 60 { return 60 } return myHabitx! } func handleWaterPer(_ per:Float?) -> Float { var perStr = per if perStr <= 0.05 { perStr = 0.05 }else if perStr >= 0.98 { perStr = 0.98 } return perStr! } func handleHourDayToPer(_ daydrinkAllWater:Int?) -> Float{ guard GUser.share.activeChild?.unit != nil else { return 0 } let allper = getActiveChildRecommentWater(GUser.share.activeChild?.unit) let day_drink_true_water = changeRecommendWater(daydrinkAllWater, unitStr: GUser.share.activeChild?.unit) var perInData : Float = Float(day_drink_true_water) / Float(allper) if perInData >= 1{ perInData = 1 } return perInData } func saveDrinkHourData(_ daydrinkAllWater:Int?) { let key1 = activeChildID + drinkHourAllDataKey let key2 = activeChildID + drinkHourDataArrayKey UserDefaults.standard.set(daydrinkAllWater!, forKey: key1) UserDefaults.standard.set(drinkWaterHourArray, forKey: key2) UserDefaults.standard.synchronize() } func saveDrinkDayData() { let key3 = activeChildID + drinkDayDataArrayKey UserDefaults.standard.set(drinkWaterDayArray, forKey: key3) UserDefaults.standard.synchronize() } func readDrinkHourData() -> Int { let key1 = activeChildID + drinkHourAllDataKey let key2 = activeChildID + drinkHourDataArrayKey let hourData : [Int]? = UserDefaults.standard.object(forKey: key2) as! [Int]? if hourData?.count == 0 || hourData == nil{ drinkWaterDayArray = [0,0,0,0,0,0,0] }else{ drinkWaterDayArray = hourData! } var allDrinkDayData : Int? = UserDefaults.standard.object(forKey: key1) as! Int? if allDrinkDayData == nil{ allDrinkDayData = 0 return 0 }else{ return allDrinkDayData! } } func readChildDrinkHourData(_ child : Children) -> Int { guard child.childID != nil else { return 0 } let key = child.childID! + drinkHourAllDataKey let allDrinkDayData : Int? = UserDefaults.standard.object(forKey: key) as! Int? if allDrinkDayData == nil{ return 0 }else{ return allDrinkDayData! } } func readDrinkDayData(){ let key3 = activeChildID + drinkDayDataArrayKey let dayData : [Int]? = UserDefaults.standard.object(forKey: key3) as! [Int]? if dayData?.count == 0 || dayData == nil{ drinkWaterDayArray = [0,0,0,0,0,0,0] }else{ drinkWaterDayArray = dayData! } } func check_current_child_have_cup() -> Bool { guard GUser.share.activeChild?.childID != nil else { return false } if GUser.share.activeChild!.hasCup == 1{ return true } return false } func checkPetAndBottleWithChild(_ child: Children?) -> ChildPetBottle{ guard child?.childID != nil else { return .none } if child!.hasPet == 1{ if child!.hasCup == 1{ return .both }else{ return .pet } } return .none } func getMainViewUnitStr(_ daydrinkAllWater:Int ) -> String{ let per = handleHourDayToPer(daydrinkAllWater) if per == 1.00 { return Localizaed("Wow! Goal achieved!") }else{ if !isValidString(GUser.share.activeChild?.unit){ GUser.share.activeChild?.unit = "kg" } let recommendValue = getActiveChildRecommentWater(GUser.share.activeChild?.unit) let day_drink_true_water = changeRecommendWater(daydrinkAllWater, unitStr: GUser.share.activeChild?.unit) return String(format: Localizaed("%d of %d %@"),day_drink_true_water,recommendValue,getChildUnitStr()) } } func getDayDrinkWater() -> String { if GUser.share.activeChild == nil || GUser.share.activeChild?.recommendWater == nil{ return "10\rml" } let recommednVallue = getActiveChildRecommentWater(GUser.share.activeChild?.unit) let unitStrValue = getChildUnitStr() if GUser.share.activeChild?.unit == "lbs"{ return "\(getDayDrinkHourWater_lbs(recommednVallue))\r\(unitStrValue)" } return "\(getDayDrinkHourWater_ml(recommednVallue))\r\(unitStrValue)" } func getDayDrinkHourWater_ml(_ recommendValue : Int?) -> Int { if recommendValue == 0 || recommendValue == nil{ return 0 } return (Int(Float((recommendValue)!)/7+5))/10*10 } func getDayDrinkHourWater_lbs(_ recommendValue : Int?) -> Int { return recommendValue!/7 } func waterUnitMlTrunOz(_ ozVlaue : Int) -> Int { return Int(Double(ozVlaue)*0.033814) } func getWeekDrinkWater() -> String { let unit = getChildUnitStr() let recommentValue = getActiveChildRecommentWater(GUser.share.activeChild!.unit) return String(format:"%d\r%@",recommentValue, unit) } func getActiveChildName() -> String { guard GUser.share.activeChild?.childName != nil else { return Localizaed("Child's Name") } return (GUser.share.activeChild?.childName)! } func getActiveChildRecommentWater(_ unit : String?) -> Int { var unitStr = unit var intWaterRate : Float? var recommendValue : Float? if !isValidString(unit){ unitStr = "kg" } if !isValidString(GUser.share.activeChild?.recommendWater?.stringValue) || GUser.share.activeChild?.recommendWater?.intValue == 0{ recommendValue = 0 }else{ recommendValue = GUser.share.activeChild?.recommendWater?.floatValue } if GUser.share.activeChild?.water_rate == nil || GUser.share.activeChild?.water_rate?.floatValue == 0{ intWaterRate = 100000 }else{ intWaterRate = (GUser.share.activeChild?.water_rate?.floatValue)! * 100000 } recommendValue = recommendValue! * intWaterRate! return changeRecommendWater(Int(recommendValue!/100000), unitStr: unitStr) } func getActiveChildBaseRecommentWater() -> Int { if !isValidString(GUser.share.activeChild?.recommendWater?.stringValue){ return Int(defaultRecommendValue) } return GUser.share.activeChild?.recommendWater as! Int } func changeRecommendWater(_ recommendValue : Int?, unitStr : String?) -> Int { if recommendValue == nil || recommendValue == 0{ return kgTurnKg(Int(0)) } if !isValidString(unitStr){ return kgTurnKg(recommendValue) } if unitStr == "kg"{ return kgTurnKg(recommendValue) }else{ return kgTurnLbs(recommendValue) } } func kgTurnKg(_ recommedIntValue:Int?) -> Int { if recommedIntValue != nil{ return (recommedIntValue!+5)/10*10 } return Int(0) } func kgTurnLbs(_ recommedIntValue:Int?) -> Int { if recommedIntValue != nil{ return waterUnitMlTrunOz(recommedIntValue!) } return waterUnitMlTrunOz(Int(0)) } func getChildUnitStr() -> String { if getChildWightUnitStr() == "lbs" { return Localizaed("oz") } return Localizaed("ml") } func getChildWeight() -> Int { if GUser.share.activeChild?.weight?.doubleValue == 0 || GUser.share.activeChild?.weight == nil{ return 25 } if getChildWightUnitStr() == "kg"{ return GUser.share.activeChild?.weight as! Int } return GUser.share.activeChild?.weightLbs as! Int } func getChildWightUnitStr() -> String { if !isValidString(GUser.share.activeChild?.unit){ return "kg" } return (GUser.share.activeChild?.unit)! } func getChildUnitDayStr() -> String { if GUser.share.activeChild?.unit == "lbs" { return Localizaed("oz/day") } return Localizaed("ml/day") } }
import React, { useState } from "react"; type FormProps = { onSubmit: (value: string) => void; onCancel: () => void; } const Form: React.FC<FormProps> = ({ onSubmit, onCancel }) => { const [name, setName] = useState(''); return ( <form onSubmit={() => onSubmit(name)} onReset={onCancel}> <input type="text" value={name} onChange={(event) => setName(event.target.value)} /> <button type="submit">Create</button> <button type="reset">Cancel</button> </form> ) }; export default Form
package br.com.delogic.leitoor.util; import br.com.delogic.jfunk.Has; /** * Representa um resultado de execução de um método. Pode ser definido como * sucesso ou falha, contendo uma mensagem e valor de retorno. * * @author [email protected] * * @since 25/05/2014 * @param <E> */ public class Result<E> { public enum Status { SUCCESS, FAILURE } private final String message; private final Status status; private final E value; private final Violation violation; private Result(String message, E value) { this.message = message; this.status = Status.SUCCESS; this.value = value; this.violation = null; } private Result(Violation violation, E value) { this.message = violation.getMessage(); this.status = Status.FAILURE; this.value = value; this.violation = violation; } public static final <E> Result<E> success(String message) { return new Result<E>(message, null); } public static final <E> Result<E> success(String message, E value) { return new Result<E>(message, value); } public static final <E> Result<E> failure(Violation violation) { return new Result<E>(violation, null); } public static final <E> Result<E> failure(Violation violation, E value) { return new Result<E>(violation, value); } public String getMessage() { return message; } public boolean isSuccess() { return status == Status.SUCCESS; } public boolean isFailure() { return status == Status.FAILURE; } public boolean hasValue() { return Has.content(value); } public E getValue() { return value; } public Violation getViolation() { return violation; } public Status getStatus() { return status; } public boolean failsAt(Violation violation, Violation... violations) { if (this.violation == null || this.status == Status.SUCCESS) { return false; } if (this.violation == violation || violation.equals(this.violation)) { return true; } if (violations != null && violations.length > 0) { for (Violation v : violations) { if (this.violation == v || this.violation.equals(v)) { return true; } } } return false; } }
// // SignUpVC.swift // TravioProject // // Created by Damla Erişmiş on 25.10.2023. // import UIKit import SnapKit class SignUpVC: UICustomViewController { private var viewModel = SignUpViewModel() private var isFormComplete: Bool = false private lazy var txtUsername:UICustomTextField = { let txt = UICustomTextField(labeltext: "Username", placeholderText: "bilge_adam") txt.textField.addTarget(self, action: #selector(textFieldDidChange), for: .editingChanged) txt.textField.autocapitalizationType = .none return txt }() private lazy var txtEmail:UICustomTextField = { let txt = UICustomTextField(labeltext: "Email", placeholderText: "[email protected]") txt.textField.addTarget(self, action: #selector(textFieldDidChange), for: .editingChanged) txt.textField.autocapitalizationType = .none return txt }() private lazy var txtPassword:UICustomTextField = { let txt = UICustomTextField(labeltext: "Password", placeholderText: "********", isStatusImageViewVisible: true) txt.textField.isSecureTextEntry = true txt.textField.addTarget(self, action: #selector(textFieldDidChange), for: .editingChanged) txt.statusImageView.image = UIImage(systemName: "eye.slash.fill") let longPressGesture = UILongPressGestureRecognizer(target: self, action: #selector(handlePasswordLongPress(_:))) txt.addGestureRecognizer(longPressGesture) return txt }() private lazy var txtPasswordConfirm:UICustomTextField = { let txt = UICustomTextField(labeltext: "Password Confirm", placeholderText: "********", isStatusImageViewVisible: true) txt.textField.addTarget(self, action: #selector(textFieldDidChange), for: .editingChanged) txt.textField.autocapitalizationType = .none txt.textField.isSecureTextEntry = true return txt }() private lazy var stackView:UIStackView = { let sv = UIStackView() sv.axis = .vertical sv.spacing = 24 sv.distribution = .fillProportionally return sv }() private lazy var buttonSignup:UIButton = { let btn = UIButton() btn.setTitle("Sign Up", for: .normal) btn.titleLabel?.font = FontStatus.poppinsSemiBold16.defineFont btn.setTitleColor(.white, for: .normal) btn.backgroundColor = .lightGray btn.layer.cornerRadius = 12 btn.addTarget(self, action: #selector(btnSignUpTapped), for: .touchUpInside) return btn }() func initVM(){ viewModel.updateLoadingStatus = { [weak self] (staus) in DispatchQueue.main.async { if staus { self?.activityIndicator.startAnimating() } else { self?.activityIndicator.stopAnimating() } } } viewModel.showAlertClosure = { [weak self] () in DispatchQueue.main.async { if let message = self?.viewModel.alertMessage { self?.showAlert(title: "Sign Up Failed ", message: message) } } } } override func viewDidLoad() { super.viewDidLoad() navigationController?.navigationBar.isHidden = true configureView() setupViews() initVM() } @objc func handlePasswordLongPress(_ gesture: UILongPressGestureRecognizer) { if gesture.state == .began { txtPassword.statusImageView.image = UIImage(systemName: "eye.fill") txtPassword.textField.isSecureTextEntry = false } else if gesture.state == .ended { txtPassword.statusImageView.image = UIImage(systemName: "eye.slash.fill") txtPassword.textField.isSecureTextEntry = true } } @objc func backButtonTapped(){ self.navigationController?.popViewController(animated: true) } @objc func textFieldDidChange(_ textField: UITextField) { if textField == txtPassword.textField || textField == txtPasswordConfirm.textField { let usernameText = txtUsername.textField.text ?? "" let emailText = txtEmail.textField.text ?? "" let passwordText = txtPassword.textField.text ?? "" let passwordConfirmText = txtPasswordConfirm.textField.text ?? "" if textField == txtPasswordConfirm.textField{ let passwordsMatch = passwordText == passwordConfirmText && passwordConfirmText.count >= 6 txtPasswordConfirm.showPasswordMatched(passwordsMatch) } let passwordsMatch = passwordText == passwordConfirmText isFormComplete = !usernameText.isEmpty && !emailText.isEmpty && !passwordText.isEmpty && !passwordConfirmText.isEmpty && passwordsMatch buttonSignup.isEnabled = isFormComplete buttonSignup.backgroundColor = isFormComplete ?.mainColor : .lightGray } } @objc func btnSignUpTapped(){ guard let textUsername = txtUsername.textField.text else{return} guard let textEmail = txtEmail.textField.text else{return} guard let textPassword = txtPassword.textField.text else{return} viewModel.postSignUpData(userName: textUsername, email: textEmail, password: textPassword) viewModel.showAlertClosure = { [weak self] in if let message = self?.viewModel.alertMessage { self?.showAlert(title: "Success!", message: message) } } } private func configureView(){ labelTitle.text = "Sign Up" self.viewMain.backgroundColor = .viewColor buttonBack.addTarget(self, action: #selector(backButtonTapped), for: .touchUpInside) } private func setupViews() { self.view.backgroundColor = .mainColor viewMain.addSubviews(stackView, buttonSignup) stackView.addArrangedSubviews(txtUsername, txtEmail, txtPassword, txtPasswordConfirm) setupLayouts() } private func setupLayouts() { stackView.snp.makeConstraints({ sv in sv.top.equalToSuperview().offset(65) sv.leading.equalToSuperview().offset(25) sv.trailing.equalToSuperview().offset(-25) }) buttonSignup.snp.makeConstraints({ btn in btn.centerX.equalToSuperview() btn.height.equalTo(54) btn.width.equalTo(342) btn.bottom.equalToSuperview().offset(-30) }) } }
[![codecov](https://codecov.io/github/casantosmu/metal-tracker/graph/badge.svg?token=D2EKM1OD1N)](https://codecov.io/github/casantosmu/metal-tracker) # Metal Tracker Metal Tracker is a script that fetches and sends email notifications for new concerts, reviews, and news related to the metal music from various sources of interest. ## Prerequisites Before running the script, ensure you have the following prerequisites set up: 1. **AWS Account**: You must have an AWS account to use the AWS services required for sending email notifications. 2. **AWS Credentials**: [Configure your AWS credentials](https://docs.aws.amazon.com/sdk-for-javascript/v3/developer-guide/setting-credentials-node.html). 3. **Amazon SNS Topic**: Create an SNS topic in your AWS account with the list of email addresses to which you want to send notifications. ## Getting Started To execute the Metal Tracker script, follow these steps: 1. Pull the Docker image from the GitHub Container Registry: ```bash docker pull ghcr.io/casantosmu/metal-tracker:main ``` 2. Run the Docker container with the required environment variables: ```bash docker run --rm --name metal-tracker \ -v metal-tracker-db:/app/sqlite \ -e AWS_ACCESS_KEY_ID=YOUR_ACCESS_KEY_ID \ -e AWS_SECRET_ACCESS_KEY=YOUR_SECRET_ACCESS_KEY \ -e AWS_REGION=us-east-1 \ -e SNS_TOPIC_ARN=YOUR_SNS_TOPIC_ARN \ ghcr.io/casantosmu/metal-tracker:main ``` Replace the placeholders with your actual AWS credentials, AWS region, and SNS topic ARN. ## How It Works Metal Tracker automates the following tasks: - **Data Collection**: It fetches data from various sources related to metal music, such as concert listings and music news. - **Data Storage**: The script saves this data in a database to keep track of previously fetched information. - **Notification**: When new data is available, Metal Tracker sends email notifications via Amazon SNS to the specified Amazon SNS topic.
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* ft_strlcpy.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: msmiesko <[email protected]> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2023/09/12 15:32:23 by msmiesko #+# #+# */ /* Updated: 2023/09/22 10:06:37 by msmiesko ### ########.fr */ /* */ /* ************************************************************************** */ #include <unistd.h> unsigned int ft_strlcpy(char *dest, char *src, unsigned int size) { unsigned int index; unsigned int lenght; index = 0; lenght = 0; while (src[lenght]) { lenght++; } if (size <= 0 || dest == NULL) { return (lenght); } while (src[index] && index < size - 1) { dest[index] = src[index]; ++index; } dest[index] = '\0'; return (lenght); } /* #include <stdio.h> int main() { char old[] = "Hello, World!"; char new[20]; printf("Copied String: %s\n", new); printf("Length of Copied String: %u\n", ft_strlcpy(new, old, 2)); return 0; } */
import 'package:care_compass/theme/colors.dart'; import 'package:flutter/material.dart'; class ProfilePage extends StatelessWidget { @override Widget build(BuildContext context) { return Scaffold( backgroundColor: black, appBar: AppBar( backgroundColor: primary, title: Text( 'Profile', style: TextStyle(color: black), ), ), body: Padding( padding: const EdgeInsets.all(16.0), child: Column( crossAxisAlignment: CrossAxisAlignment.center, mainAxisAlignment: MainAxisAlignment.center, children: [ CircleAvatar( radius: 50, backgroundColor: primary, // You can add an image here for the profile picture ), SizedBox(height: 16), Text( 'John Doe', style: TextStyle( fontSize: 24, fontWeight: FontWeight.bold, color: primary), ), SizedBox(height: 8), Text( 'Software Developer', style: TextStyle(fontSize: 16, color: thirdColor), ), SizedBox(height: 16), _buildInfoCard( icon: Icons.email, label: 'Email', value: '[email protected]', ), _buildInfoCard( icon: Icons.phone, label: 'Phone', value: '+1 123-456-7890', ), ], ), ), ); } Widget _buildInfoCard( {required IconData icon, required String label, required String value}) { return Card( elevation: 3, shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(12)), margin: EdgeInsets.symmetric(vertical: 8), child: ListTile( leading: Icon(icon, color: primary), title: Text(label, style: TextStyle(color: primary)), subtitle: Text(value), ), ); } }
import { Button, Tooltip, Zoom } from "@mui/material"; import { ipcRenderer } from "electron"; import React, { useEffect, useState } from "react"; import PauseCircleOutlineOutlinedIcon from "@mui/icons-material/PauseCircleOutlineOutlined"; import PlayCircleFilledWhiteOutlinedIcon from "@mui/icons-material/PlayCircleFilledWhiteOutlined"; import { useParseContext } from "../../context/ParseContext"; import { PARSE_EVENTS, PROCESS_STATUS } from "../../../main/model"; const ProcessButton = () => { const { state: { status, channels }, } = useParseContext(); const [isProcess, setIsProcess] = useState<boolean>(false); useEffect(() => { if (status === PROCESS_STATUS.FINISHED) { setIsProcess(false); } }, [status]); const handleStartParsing = () => { ipcRenderer.send(PARSE_EVENTS.START, channels); setIsProcess(true); }; const parseAbort = () => { ipcRenderer.send(PARSE_EVENTS.ABORT, true); }; return ( <> <Tooltip title={channels.length ? "" : "Add channels first"} placement="bottom" arrow disableInteractive TransitionComponent={Zoom} > <span> <Button variant="contained" color={isProcess ? "error" : "primary"} size="small" disabled={channels.length === 0} sx={{ fontSize: 13, }} onClick={isProcess ? parseAbort : handleStartParsing} endIcon={ isProcess ? ( <PauseCircleOutlineOutlinedIcon /> ) : ( <PlayCircleFilledWhiteOutlinedIcon /> ) } > {isProcess ? "Stop Parse" : "Start Parse"} </Button> </span> </Tooltip> </> ); }; export default ProcessButton;
extends CharacterBody2D const GRAVITY = 800 const MOVE_SPEED = 120 const JUMP_FORCE = 200 enum {WALK, ATTACK, JUMP, FALL, IDLE, SLIDE} var current_state = IDLE var enter_state = true @onready var animated_sprite = $AnimatedSprite2D func _physics_process(delta): match current_state: WALK: _walk_state(delta) ATTACK: _attack_state(delta) JUMP: _jump_state(delta) FALL: _fall_state(delta) IDLE: _idle_state(delta) SLIDE: _slide_state(delta) # state functions func _jump_state(_delta): if enter_state: animated_sprite.play("jump") velocity.y = -JUMP_FORCE enter_state = false _apply_gravity(_delta) _move() _apply_move_and_slide() _set_state(_check_jump_state()) func _fall_state(_delta): animated_sprite.play("fall") _apply_gravity(_delta) _move() _apply_move_and_slide() _set_state(_check_fall_state()) func _walk_state(_delta): animated_sprite.play("walk") _move() _apply_gravity(_delta) _apply_move_and_slide() _set_state(_check_walk_state()) func _attack_state(_delta): if enter_state: animated_sprite.play("attack") enter_state = false velocity.x = 0 _apply_gravity(_delta) _apply_move_and_slide() func _idle_state(_delta): animated_sprite.play("idle") velocity.x = 0 _apply_gravity(_delta) _apply_move_and_slide() _set_state(_check_idle_state()) func _slide_state(_delta): animated_sprite.play("slide") velocity.x = lerp(velocity.x, 0.0, 0.05) _apply_gravity(_delta) _apply_move_and_slide() _set_state(_check_slide_state()) # check functions func _check_idle_state(): var new_state = IDLE if Input.is_action_pressed("ui_right") or Input.is_action_pressed("ui_left"): new_state = WALK elif Input.is_action_pressed("ui_attack"): new_state = ATTACK elif Input.is_action_pressed("ui_jump"): new_state = JUMP elif not is_on_floor(): new_state = FALL return new_state func _check_walk_state(): var new_state = WALK if Input.get_axis("ui_left", "ui_right") == 0: new_state = IDLE elif Input.is_action_pressed("ui_attack"): new_state = ATTACK elif Input.is_action_pressed("ui_jump"): new_state = JUMP elif Input.is_action_pressed("ui_down"): new_state = SLIDE elif not is_on_floor(): new_state = FALL return new_state func _check_jump_state(): var new_state = JUMP if velocity.y >= 0: new_state = FALL elif Input.is_action_pressed("ui_attack"): new_state = ATTACK return new_state func _check_fall_state(): var new_state = FALL if is_on_floor(): new_state = IDLE elif Input.is_action_pressed("ui_attack"): new_state = ATTACK return new_state func _check_slide_state(): var new_state = SLIDE if abs(round(velocity.x)) <= 20: new_state = IDLE elif not is_on_floor(): new_state = FALL return new_state # helpers functions func _apply_gravity(_delta): velocity.y += GRAVITY * _delta func _apply_move_and_slide(): move_and_slide() func _move(): if Input.is_action_pressed("ui_right"): velocity.x = MOVE_SPEED animated_sprite.flip_h = false elif Input.is_action_pressed("ui_left"): velocity.x = -MOVE_SPEED animated_sprite.flip_h = true func _set_state(new_state): if new_state != current_state: enter_state = true current_state = new_state func _on_animated_sprite_2d_animation_finished(): var anim_name = animated_sprite.animation if anim_name == "attack": _set_state(IDLE)
package external import ( "context" "encoding/json" "github.com/opentracing/opentracing-go" "github.com/opentracing/opentracing-go/ext" "github.com/wagslane/go-rabbitmq" "github.kolesa-team.org/backend/go-example/app/common/usecase/post/create" "golang.org/x/exp/slog" ) type req struct { Title string `json:"title"` Content string `json:"content"` } type Handler struct { logger *slog.Logger usecase create.PostCreateExecutor tracer opentracing.Tracer } func NewHandler( logger *slog.Logger, usecase create.PostCreateExecutor, tracer opentracing.Tracer, ) Handler { return Handler{ logger: logger, usecase: usecase, tracer: tracer, } } func (h Handler) Handle( ctx context.Context, delivery rabbitmq.Delivery, ) rabbitmq.Action { span := h.tracer.StartSpan( "app::external::handler", opentracing.ChildOf( opentracing.SpanFromContext(ctx).Context(), ), ) defer span.Finish() h.logger.Info( "обработка сообщения из очереди", "body", string(delivery.Body), ) var r req if err := json.Unmarshal(delivery.Body, &r); err != nil { ext.LogError(span, err) h.logger.Error( "не удалось распарсить тело сообщения", "error", err, "body", string(delivery.Body), ) return rabbitmq.NackDiscard } post, err := h.usecase.Execute( ctx, r.Title, r.Content, ) if err != nil { ext.LogError(span, err) h.logger.Error( "не удалось создать пост", "error", err, "request", r, ) return rabbitmq.NackRequeue } h.logger.Info( "пост успешно создан через external worker", "post", *post, ) return rabbitmq.Ack }
"""Collection of various functions for the GUI.""" from __future__ import annotations import time from typing import TYPE_CHECKING from napari.qt import get_stylesheet from napari.settings import get_settings from qtpy.QtCore import Qt, QTimer from qtpy.QtGui import QValidator from qtpy.QtWidgets import ( QCheckBox, QFileDialog, QGridLayout, QLabel, QSizePolicy, QSpacerItem, QWidget, ) if TYPE_CHECKING: import napari.viewer from qtpy import QtWidgets from superqt import QRangeSlider class ThrottledCallback: def __init__(self, callback, max_interval): self.callback = callback self.max_interval = max_interval self.last_call_time = 0 self.timer = QTimer() self.timer.setSingleShot(True) self.args, self.kwargs = None, None def __call__(self, *args, **kwargs): current_time = time.time() self.args, self.kwargs = args, kwargs # store the latest args and kwargs if current_time - self.last_call_time > self.max_interval: self.last_call_time = current_time self.callback(*self.args, **self.kwargs) else: self.timer.stop() self.timer.timeout.connect(self._timeout_callback) self.timer.start(int(self.max_interval * 1000)) def _timeout_callback(self): self.last_call_time = time.time() self.callback(*self.args, **self.kwargs) self.timer.timeout.disconnect(self._timeout_callback) class OutputOrderValidator(QValidator): def __init__(self, vColsCore, parent=None): super().__init__(parent) self.vColsCore = vColsCore self.required_chars = ["t", "x", "y"] self.allowed_chars = ["t", "x", "y", "z"] self.max_length = 4 def validate(self, string, pos): if len(string) > self.max_length: return QValidator.Invalid, string, pos for char in string: if char not in self.allowed_chars: return QValidator.Invalid, string, pos if len(set(string)) != len(string): return QValidator.Invalid, string, pos if len(string) < len(self.vColsCore): return QValidator.Intermediate, string, pos for char in self.required_chars: if char not in string: return QValidator.Intermediate, string, pos return QValidator.Acceptable, string, pos class SelectionDialog(QFileDialog): def __init__(self, selection_values, *args, **kwargs): super().__init__(*args, **kwargs) # Use non-native file dialog to allow customizations self.setOption(QFileDialog.DontUseNativeDialog, True) # Create a new grid layout for your widgets layout = QGridLayout() self.selection_title = QLabel("Select:") # Create and add a label to the first row layout.addWidget(self.selection_title, 0, 0, 1, 4) # Create and add "Select All" checkbox above the selection_values checkboxes self.selectAllCheckbox = QCheckBox("Select All") self.selectAllCheckbox.setTristate(False) self.selectAllCheckbox.setChecked(True) layout.addWidget(self.selectAllCheckbox, 1, 0, 1, 4) self.checkboxes = {} for index, value in enumerate(selection_values): self.checkboxes[value] = QCheckBox(value.replace("_", " ").title()) self.checkboxes[value].setChecked(True) row = 2 + index // 5 # Compute the row, starting from the 3rd row col = index % 5 # Compute the column, up to 4 columns layout.addWidget(self.checkboxes[value], row, col) # Add expanding spacers to the right of your widgets layout.addItem( QSpacerItem(0, 0, QSizePolicy.Expanding, QSizePolicy.Minimum), 0, len(selection_values), ) layout.addItem( QSpacerItem(0, 0, QSizePolicy.Expanding, QSizePolicy.Minimum), 1, len(selection_values), ) # Get the existing layout and add your layout to it self.layout().addWidget(QWidget(), 3, 0) # Add a spacer widget self.layout().addLayout( layout, 4, 0, 1, 4 ) # Adjust row and column indices as needed # Connect "Select All" checkbox to selectAll function self.selectAllCheckbox.stateChanged.connect(self.selectAll) # Connect each individual checkbox to updateSelectAllState function for checkbox in self.checkboxes.values(): checkbox.stateChanged.connect(self.updateSelectAllState) # Set stylesheet style_sheet = get_stylesheet(get_settings().appearance.theme) self.setStyleSheet(style_sheet) # Override mousePressEvent for selectAllCheckbox def new_mousePressEvent( event, original_method=self.selectAllCheckbox.mousePressEvent ): if self.selectAllCheckbox.checkState() == Qt.Unchecked: self.selectAllCheckbox.setCheckState(Qt.Checked) else: original_method(event) self.selectAllCheckbox.mousePressEvent = new_mousePressEvent def selectAll(self, state): if state == Qt.PartiallyChecked: return # Ignore partially checked state isChecked = state == Qt.Checked # Block signals from individual checkboxes to prevent recursion for checkbox in self.checkboxes.values(): checkbox.blockSignals(True) checkbox.setChecked(isChecked) checkbox.blockSignals(False) # Now, update the "Select All" checkbox without triggering its signal self.selectAllCheckbox.blockSignals(True) self.selectAllCheckbox.setCheckState(Qt.Checked if isChecked else Qt.Unchecked) self.selectAllCheckbox.blockSignals(False) def updateSelectAllState(self): checkedCount = sum( 1 for checkbox in self.checkboxes.values() if checkbox.isChecked() ) # Update the state of selectAllCheckbox without triggering its signal self.selectAllCheckbox.blockSignals(True) if checkedCount == 0: self.selectAllCheckbox.setCheckState(Qt.Unchecked) elif checkedCount == len(self.checkboxes): self.selectAllCheckbox.setCheckState(Qt.Checked) else: self.selectAllCheckbox.setCheckState(Qt.PartiallyChecked) self.selectAllCheckbox.blockSignals(False) def get_selected_options(self): """Returns a list of selected checkboxes' values excluding the 'Select All' checkbox.""" return [ value for value, checkbox in self.checkboxes.items() if checkbox.isChecked() and value != "Select All" ] class BatchFileDialog(SelectionDialog): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.setFileMode(QFileDialog.Directory) self.setOption(QFileDialog.ShowDirsOnly, True) self.setWindowTitle("Select Folder to Batch Process") self.selection_title.setText("Select what to export:") class ParameterFileDialog(SelectionDialog): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.setFileMode(QFileDialog.ExistingFile) self.setOption(QFileDialog.ShowDirsOnly, False) # filter for .yaml files self.setNameFilter("*.yaml") self.setWindowTitle("Select Parameter File") self.selection_title.setText("Select what to import:") def remove_layers_after_columnpicker(viewer: napari.viewer.Viewer, arcos_layers: list): """Remove existing arcos layers before loading new data""" layer_list = get_layer_list(viewer) for layer in arcos_layers: if layer in layer_list: viewer.layers.remove(layer) def get_layer_list(viewer: napari.viewer.Viewer): """Get list of open layers.""" layer_list = [layer.name for layer in viewer.layers] return layer_list def set_track_lenths( track_lenths_minmax: tuple, tracklenght_slider: QRangeSlider, min_tracklength_spinbox: QtWidgets.QDoubleSpinBox, max_tracklength_spinbox: QtWidgets.QDoubleSpinBox, ): """Set track length slider and spinboxes to min and max values of track lengths. Parameters ---------- track_lenths_minmax : tuple Tuple of min and max track length. tracklenght_slider : QRangeSlider tracklenght_slider : QRangeSlider min_tracklength_spinbox : QtWidgets.QDoubleSpinBox max_tracklength_spinbox : QtWidgets.QDoubleSpinBox """ if track_lenths_minmax[1] - track_lenths_minmax[0] > 1: tracklenght_slider.setMinimum(track_lenths_minmax[0]) tracklenght_slider.setMaximum(track_lenths_minmax[1]) min_tracklength_spinbox.setMinimum(track_lenths_minmax[0]) max_tracklength_spinbox.setMinimum(track_lenths_minmax[0]) min_tracklength_spinbox.setMaximum(track_lenths_minmax[1]) max_tracklength_spinbox.setMaximum(track_lenths_minmax[1]) min_tracklength_spinbox.setValue(track_lenths_minmax[0]) max_tracklength_spinbox.setValue(track_lenths_minmax[1])
import * as bcrypt from 'bcrypt'; import { Request } from 'express'; import httpStatus from 'http-status'; import { Secret } from "jsonwebtoken"; import config from "../../../config"; import { jwtHelpers } from "../../../helpars/jwtHelpers"; import prisma from "../../../shared/prisma"; import ApiError from '../../errors/ApiError'; const loginUser = async (payload: { email: string, password: string }) => { const userData = await prisma.user.findUniqueOrThrow({ where: { email: payload.email } }); const isCorrectPassword: boolean = await bcrypt.compare(payload.password, userData.password); if (!isCorrectPassword) { throw new Error("Password incorrect!") } const accessToken = jwtHelpers.generateToken({ email: userData.email, userId: userData.id }, config.jwt.jwt_secret as Secret, config.jwt.expires_in as string ); const refreshToken = jwtHelpers.generateToken({ email: userData.email, userId: userData.id }, config.jwt.refresh_token_secret as Secret, config.jwt.refresh_token_expires_in as string ); return { accessToken, refreshToken, userData:{ id: userData.id, name: userData.name, email: userData.email, } }; }; const createUserIntoDB = async (req: Request) => { // /find already user exit or not const findUser = await prisma.user.findUnique({ where: { email: req.body.email } }); if(findUser?.email){ throw new ApiError(httpStatus.BAD_REQUEST, "you have already register with this email!") } const hashedPassword: string = await bcrypt.hash(req.body.password, 12) const userData = { "name": req.body.name, "email": req.body.email, "password": hashedPassword, "bloodType":req.body.bloodType, "location": req.body.location, availability: req.body.availability } const profileData={ "age":req.body.age, "bio": req.body.bio, "lastDonationDate": req.body.lastDonationDate } const result = await prisma.$transaction(async (transactionClient) => { const createdUserData= await transactionClient.user.create({ data: userData }); const created = await transactionClient.userProfile.create({ data: {...profileData,userId:createdUserData.id as string} }); const {password,...restData}=createdUserData; return {...restData,userProfile:created}; }); return result; }; export const AuthServices = { loginUser,createUserIntoDB }
import React from "react"; import { useSelector } from "react-redux"; import { Link } from "react-router-dom"; const Navbar = () => { const count = useSelector((state) => state.counter.count); const cartItems = useSelector((state) => state.cart.cartItems); return ( <nav className="navbar navbar-expand-lg bg-body-tertiary mb-5"> <div className="container-fluid"> <Link className="navbar-brand" to={"/"}> Redux Demo </Link> <button className="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#navbarNavAltMarkup" aria-controls="navbarNavAltMarkup" aria-expanded="false" aria-label="Toggle navigation" > <span className="navbar-toggler-icon" /> </button> <div className="collapse navbar-collapse" id="navbarNavAltMarkup"> <div className="navbar-nav"> <Link className="nav-link" to={"/"}> Home </Link> <Link className="nav-link" to={"/counter"}> Counter </Link> <Link className="nav-link" to={"/shop"}> shop </Link> </div> <div className="navbar-nav ms-auto"> <Link className="nav-link " to={"/cart"}> <i className="fa-solid fa-cart-shopping me-2 position-relative"> <span class="position-absolute top-0 start-100 badge rounded-pill bg-danger"> {cartItems.length} <span class="visually-hidden">unread messages</span> </span> </i> Cart </Link> </div> </div> </div> </nav> ); }; export default Navbar;
package Arrays.Easy; import java.util.List; import java.util.ArrayList; // https://leetcode.com/problems/find-all-numbers-disappeared-in-an-array/ // Runtime 5 ms Beats 96.69% // Memory 50.8 MB Beats 84.67% public class DissapearedNumsInArr { public List<Integer> findDisappearedNumbers(int[] nums) { // December 15, 2022 // Negate each number while traversing // Run again and find the index that is not negated. List<Integer> ans=new ArrayList<>(); for(int i=0;i<nums.length;i++){ int correctIdx=Math.abs(nums[i])-1; if(nums[correctIdx]>0){ nums[correctIdx]*=-1; } } for(int i=0;i<nums.length;i++){ if(nums[i]>0){ ans.add(i+1); } } return ans; // Runtime: 6 ms, faster than 92.01% of Java online submissions for Find All Numbers Disappeared in an Array. // Memory Usage: 50.3 MB, less than 96.51% of Java online submissions for Find All Numbers Disappeared in an Array. // int i=0; // while(i<nums.length){ // int correctIdx=nums[i]-1; // if(nums[i]<=nums.length && nums[i]!=nums[correctIdx]){ // int temp=nums[i]; // nums[i]=nums[correctIdx]; // nums[correctIdx]=temp; // }else{ // i++; // } // } // List<Integer> ans=new ArrayList<>(); // for(i=0;i<nums.length;i++){ // if(nums[i]!=i+1){ // ans.add(i+1); // } // } // return ans; } }
import { NextFunction, Response, Request } from "express"; import { Logger } from "./logger"; // Custum error export class HttpError extends Error{ httpStatusCode: number UImsg: string constructor(status: number = 500, message: string = "Internal Server Error", UImsg: string = "Something went wrong! Try again later" ) { super(message) Object.setPrototypeOf(this, new.target.prototype); this.httpStatusCode = status; this.UImsg = UImsg Error.captureStackTrace(this); } } // Error Handler export const errorHandler = async (error: HttpError, _request: Request, response: Response, next: NextFunction) => { Logger.error(`Error : ${error}`) return response.status(error.httpStatusCode || 500).json({ error }) } // Error 404 not found route or resource export const error404Route = async (request: Request, response: Response) => { const resource = request.originalUrl.split("/v1").pop(); Logger.error(`Error : Can't find ${resource}`) return response.status(404).json({ message: `Resource: [ ${resource} ] not found` }) } export const checkRequest = async(request: Request, response: Response, next: NextFunction) => { const ALLOWED = [ "OPTIONS", "HEAD", "CONNECT", "GET", "POST", "PUT", "DELETE", "PATCH" ]; if( !ALLOWED.includes( request.method) ) { Logger.error(`Error : HTTP Method -> ${request.method} not allowed`) return response.send(405).json({ message: `${request.method} not allowed!`}); } next(); }
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta name="author" content="Kateryna Glazkova"> <meta name="description" content="WDD 230 - Web Frontend Development Lesson02 - Kateryna Glazkova"> <meta property="og:title" content="Lesson02 - WDD230 Assignment"> <meta property="og:type" content="website"> <meta property="og:url" content="https://mvedmanpro.github.io/wdd230/"> <link rel="canonical" href="https://mvedmanpro.github.io/wdd230/"> <link rel="stylesheet" href="styles/normalize.css"> <link rel="stylesheet" href="styles/base.css"> <link rel="preconnect" href="https://fonts.googleapis.com"> <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin> <link href="https://fonts.googleapis.com/css2?family=Fira+Sans&display=swap" rel="stylesheet"> <title>WDD-230 Lesson02 Design Principles Document </title> <link rel="preconnect" href="https://fonts.googleapis.com"> </head> <body> <header> <h1>Design Principles Document</h1> <h2>Kateryna Glazkova</h2> </header> <main> <section class="card"> <h3>Rule of Thirds</h3> <p>Rockstroh Drums</p> <a href="https://www.rockstrohdrums.com">Visit ROCKSTROHDRUMS.COM</a> <hr> <img id="mobile-screenshot1" src="images/drums-300px.jpg" alt="Rule of Thirds (mobile view screenshot example of use)"> <hr> <p>Brief description of how the design is exemplified:<br>The Rule of Thirds is used in visual arts. It is a compositional principle that suggests an image should be imagined as divided into nine equal parts. Important compositional elements should be placed along these equal lines or their intersections to create more tension and energy to the content. In the example of ROCKSTROH DRUMS website the designer has effectively used this principle to create a visually appealing and balanced layout. By placing important information in the left third of the banner, which is said to have more impact on the viewer's eye, and filling the right third with an image that represents the main idea of the website (in this case, drums), the designer has created a composition that is both engaging and informative.</p> </section> <section class="card"> <h3>PARC: Alignment</h3> <p>Cloud Software Group</p> <a href="https://www.cloud.com/trust-center/privacy">Visit CLOUD.COM</a> <hr> <img id="mobile-screenshot2" src="images/cloud-300px.jpg" alt="PARC: Alignment (mobile view screenshot example of use)"> <hr> <p>Brief description of how the design is exemplified:<br> Alignment in web design is arrangement and positioning of all elements on the Webpage. It is an essential part of the appealing look and clarity of the website. All elements must be aligned, otherwise the it would look messy and chaotic. In this example of CLOUD SOFTWARE GROUP Webpage it is clearly seen that left alignment is effectively used for the text elements. This kind of alignment provides clarity and contributes to a well-structured layout. </section> <section class="card"> <h3>Hick's Law</h3> <p>Amazon</p> <a href="https://www.amazon.com/">Visit AMAZON.COM</a> <hr> <img id="mobile-screenshot3" src="images/amazon-300px-betterquality.jpg" alt="Hick's Law(mobile view screenshot example of use)"> <hr> <p>Brief description of how the design is exemplified: <br> Hick's Law suggests that if there is less choices then the decision time too choose is faster, as fewer choices reduces cognitive load of the user, but otherwise the decision can even not be made at all, as it becomes overwhelming to choose. In the example shown above we see categories of AMAZON services/products which makes it easier to find needed option for the user. Amazon used this as a tip to not make its users to find product or service through search bar, which saves a lot of time and reduces the risk of user leaving the website in frustration that there wasn't a chance to find needed option, this way the Amazon benefits in terms of users purchases increasing sales and improving user experience.</p> </section> </main> <footer> <p id="copyright">&copy; Kateryna Glazkova | Completed Assignment </footer> </body> </html>
import {useEffect, useState} from 'react'; import {Fade, Form} from 'react-bootstrap'; import {myFetch} from '../../../../../module/myFetch'; import BaseFormGroup from '../form-parts/BaseFormGroup'; import FormButton from '../form-parts/FormButton'; const LoginForm = ({isLoading, setIsLoading}) => { const [username, setUsername] = useState(); const [password, setPassword] = useState(); const [error, setError] = useState(); useEffect(() => setError(null), [username, password]); const login = async e => { e.preventDefault(); setIsLoading(true); const res = await myFetch('/login', { method: 'POST', body: {username, password} }); if (res.error) { setError(res.error); setIsLoading(false); } else { setIsLoading(false); window.location.href = '/'; } }; return ( <Form onSubmit={login}> <BaseFormGroup type="username"> <Form.Control type="text" disabled={isLoading} isInvalid={error} onChange={e => setUsername(e.target.value)}/> </BaseFormGroup> <BaseFormGroup type="password"> <Form.Control type="password" disabled={isLoading} isInvalid={error} onChange={e => setPassword(e.target.value)}/> </BaseFormGroup> <Fade in={error}> <p id="Login-Feedback" className="mb-4 text-center text-nowrap"> ユーザーネームかパスワードが間違っています </p> </Fade> <FormButton {...{username, password, isLoading}}> Log in </FormButton> </Form> ); }; export default LoginForm;
#include <stdio.h> #include <stdlib.h> #include <string.h> struct Products { char code[5]; int unit; char name[100]; float cost; float sell; }; void bin2csv() { const char *binFileName = "Database.bin"; const char *csvFileName = "Database.csv"; FILE *binFile = fopen(binFileName, "rb"); if (binFile == NULL) { printf("Error opening binary file.\n"); return; } // Create CSV file FILE *csvFile = fopen(csvFileName, "w"); if (csvFile == NULL) { printf("Error creating CSV file.\n"); fclose(binFile); return; } struct Products product_csv; fprintf(csvFile, "Code,Unit,Name,Cost(฿),Sell(฿)\n"); // Write to CSV while (fread(&product_csv, sizeof(struct Products), 1, binFile) == 1) { fprintf(csvFile, "%s,%d,%s,%.2f,%.2f\n", product_csv.code, product_csv.unit, product_csv.name, product_csv.cost, product_csv.sell); } fclose(binFile); fclose(csvFile); printf("Binary to CSV conversion completed. CSV file: %s\n", csvFileName); // Delete the binary file remove(binFileName); } void csv2bin() { const char *csvFileName = "Database.csv"; const char *binFileName = "Database.bin"; FILE *csvFile = fopen(csvFileName, "r"); if (csvFile == NULL) { printf("Error opening CSV file.\n"); return; } FILE *binFile = fopen(binFileName, "wb"); if (binFile == NULL) { printf("Error creating binary file.\n"); fclose(csvFile); return; } struct Products product_bin; fscanf(csvFile, "%*[^\n]\n"); while (fscanf(csvFile, "%[^,],%d,%[^,],%f,%f\n", product_bin.code, &product_bin.unit, product_bin.name, &product_bin.cost, &product_bin.sell) == 5) { fwrite(&product_bin, sizeof(struct Products), 1, binFile); } fclose(csvFile); fclose(binFile); printf("CSV to Binary conversion completed. Binary file: %s\n", binFileName); // Delete the CSV file remove(csvFileName); } int main() { int choice; printf("1. Convert binary to CSV\n"); printf("2. Convert CSV to binary\n"); printf("Enter your choice: "); scanf("%d", &choice); switch (choice) { case 1: bin2csv(); break; case 2: csv2bin(); break; default: printf("Invalid choice.\n"); break; } return 0; }
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <!-- jsp에서 jdbc의 객체를 사용하기 위해 java.sql 패키지를 import한다. --> <%@ page import = "java.sql.*" %> <% Connection conn = null; PreparedStatement pstmt = null; ResultSet rs = null; try { String url = "jdbc:mysql://localhost:3306/bookshopdb"; String user = "bookmaster"; String pwd = "1111"; //데이터베이스와 연동하기 위해 DriverManager에 등록한다. Class.forName("com.mysql.jdbc.Driver"); //DriverManager객체로부터 Connection객체를 얻어온다. conn = DriverManager.getConnection(url, user, pwd); //sql 쿼리 작성 String sql = "SELECT * FROM member"; //prepareStatement에서 해당 sql을 미리 컴파일한다. pstmt = conn.prepareStatement(sql); //쿼리를 실행하고 결과를 ResultSet객체에 넣는다. rs = pstmt.executeQuery(); %> <table class="table table-bordered table-striped table-hover"> <tr> <td width="100" align="center">아이디</td> <td width="100" align="center">비밀번호</td> <td width="100" align="center">이름</td> <td width="100" align="center">가입일자</td> <td width="100" align="center">전화번호</td> <td width="400" align="center">주소</td> </tr> <% while(rs.next()) { String id = rs.getString("id"); String passwd = rs.getString("passwd"); String name = rs.getString("name"); String reg_date = rs.getString("reg_date"); String tel = rs.getString("tel"); String address = rs.getString("address"); %> <tr> <td width="100" align="center"><%=id%></td> <td width="100" align="center"><%=passwd%></td> <td width="100" align="center"><%=name%></td> <td width="100" align="center"><%=reg_date%></td> <td width="100" align="center"><%=tel%></td> <td width="400" align="center"><%=address%></td> </tr> <% } %> </table> <% } catch(Exception e) { e.printStackTrace(); e.getMessage(); out.println("회원정보를 가져오는데 실패했습니다."); out.println(e.getMessage()); } finally { if(rs != null) try { rs.close(); } catch(SQLException sqle) {} if(pstmt != null) try { pstmt.close(); } catch(SQLException sqle) {} if(conn != null) try { conn.close(); } catch(SQLException sqle) {} } %>
Aslet Eleccentric Vehicles Final Project By: Steven Kravitz Section 1: The Main Menu Interface At the main menu, there are 5 options for the user to choose from by entering 1, 2, 3, 4, or 5. They are as follows: Option 1: Log in This menu is for customers who have existing accounts to log in. They enter their first and last name and the user logs them into their account where they can access the Customer Main Menu. Option 2: Create Account This option is for customers who do not already have accounts. It walks them through the steps that allow them to add a row for them in the databases Customer entity, address entity (for their home), and payment entity (for their credit card info). After they create their account, they are logged in and sent to the customer main menu. Option 3: Employee Access This option is for Employees to access. This tab takes them the employee main menu. Unlike in a real database system, there is no security measures to stop anyone from accessing this menu. The focus of this project is not on security. Option 4: Browse Showroom This tab allows users to select a service location and browse the vehicles in its showroom. Users can access this feature without needing an account or to access an employee tab. Option 5: Exit This option closes the program. Section 2: The Customer Main Menu Interface At the customer main menu, there are 5 options which can be accessed in a similar fashion to the main menu. They are as follows: Option 1: Browse Showroom This option allows the customers to browse the showroom. The functionality is the exact same as from the main menu. The reason this option is here is such that customers do not need to log out to the main menu to see the showrooms. Option 2: Select Vehicle This option allows users to buy vehicles. They get to choose which specifications they want including the model, whether or not the vehicle is used or new, and capacity. The user is presented with the vehicles on hand which meet their specifications. The user see all the information about the vehicle including the VIN, color, model, year, capacity, base price, miles, and service center. If the vehicle is used, the customer can see if the vehicle has any upgrades or an upgrade package or neither. If the vehicle is new, the user is shown all the available upgrades and upgrade packages and is prompted to choose if they want to include any. Afterwards, a transaction is made and the ownership is transferred to the customer. Option 3: View Account Information This option takes the user to an interface that allows them to see their account information. This is described in Section 3. Option 4: This option allows the user to get their vehicle serviced. The number of miles is increased by a random amount to simulate how much the odometer would have increased since the customers last visit. The customer pays a relatively small amount and the maintence entity gets a new row for this new maintenance appointment. Option 5: Exit This option logs the user out by returning to the main menu. Section 3: Customer Account Interface At the customer account menu, the customer is given options to see information about them stored in the database. They have 4 options. Option 1: View Customer Info This option prints out the customer ID, name, phone, and email. Option 2: View Address This option prints out the user's address ID, Planet/Celestial body, environment, and street address. Option 3: View Payment This option prints out the users payment ID, credit card number, expiration date, security code, and company. Option 4: Exit This option exits this interface and returns to the customer main menu. Section 4: Employee Menu Interface At this menu, the employee schedule repairs and issue recalls. The options are listed below. Option 1: Browse the Showrooms The employee can browse the showrooms without needing to return to the main menu. Option 2: The employee can see which customers have over 950,000,000,000 miles on their vehicle and contact them to schedule repairs. Option 3: The employee can select a specific year and model of vehicle to be recalled. They are then given the contact information of customers who own such vehicles. Option 4: Exit This option returns to the main menu. Section 5: Data Generation Most of the data used in the making of this project was generated in Mockaroo. There were some errors noticed after the data was already implemented so there are SQL files to fix those errors. Section 6: ER diagram. There were a couple of small changes made to the ER diagram. A couple relationships were changed from one-to-one to one-to-many. Additonally, a relationship was added between Customer and payment. Finally a few variables names were altered in the transaction entity.
import { EditOutlined } from "@ant-design/icons"; import { Button, Col, Form, Input, Modal, Row, Tooltip, notification, } from "antd"; import { useTranslation } from "react-i18next"; import { useRecoilValue } from "recoil"; import { ERROR_TIMEOUT } from "@/constant/config"; import { queryClient } from "@/lib/react-query"; import { CACHE_ACTION, useCreateAction, useGetActionById, useUpdateAction, } from "@/loader/action.loader"; import { getFunctionIdSelector } from "@/modules/authorization/store/state"; import { RULES_FORM } from "@/modules/authorization/utils/validator"; import { UserState } from "@/store/auth/atom"; import { useDisclosure } from "@/utils/modal"; import styles from "../../../../scss/styles.module.scss"; interface Props { isCreate: boolean; id?: string; } export function ActionModal({ isCreate, id }: Props): JSX.Element { const [form] = Form.useForm(); const { isOpen, close, open } = useDisclosure(); const function_id = useRecoilValue(getFunctionIdSelector); const userRecoil = useRecoilValue(UserState); const { t } = useTranslation(); const { remove: removeAction, refetch } = useGetActionById({ id: id!, config: { enabled: isOpen && !!id, onSuccess: (data) => { if (data.message === ERROR_TIMEOUT) { refetch(); } else { form.setFieldsValue(data); } }, }, }); const createAction = useCreateAction({ config: { onSuccess: () => { notification.success({ message: t("messages.create_success"), }); close(); queryClient.invalidateQueries([CACHE_ACTION.SEARCH]); form.resetFields(); }, onError: () => { notification.error({ message: t("messages.create_failure"), }); }, }, }); const updateAction = useUpdateAction({ config: { onSuccess: () => { notification.success({ message: t("messages.update_success"), }); close(); queryClient.invalidateQueries([CACHE_ACTION.SEARCH]); form.resetFields(); }, onError: () => { notification.error({ message: t("messages.update_failure"), }); }, }, }); const handleOpen = () => { open(); }; const handleCancel = () => { close(); removeAction(); form.resetFields(); }; const handleOk = () => { form .validateFields() .then((values) => { const dataPost = { ...values, function_id, lu_user_id: userRecoil.user_id, created_by_user_id: userRecoil.user_id, }; isCreate ? createAction.mutate(dataPost) : updateAction.mutate(dataPost); }) .catch(() => { notification.warning({ message: "Cần điền đầy đủ thông tin", }); }); }; return ( <> {isCreate ? ( <Button type="primary" className={`${styles.button} ${styles.btn_add}`} onClick={handleOpen} disabled={!function_id} > {t("all.btn_add")} </Button> ) : ( <Tooltip title={t("authorization.tooltip.btn_update")}> <Button type="default" size="small" onClick={handleOpen} className={styles.center} > <EditOutlined style={{ color: "#faad14", cursor: "pointer", }} /> </Button> </Tooltip> )} <Modal style={{ top: 110 }} open={isOpen} width={"40%"} title={ isCreate ? t("authorization.actions.modal.title_create") : t("authorization.actions.modal.title_update") } okText={t("all.btn_save")} cancelText={t("all.btn_cancel")} onOk={handleOk} maskClosable={false} destroyOnClose onCancel={handleCancel} confirmLoading={ isCreate ? createAction.isLoading : updateAction.isLoading } > <div className="modal-body"> <Form form={form} layout="vertical"> <Row gutter={32}> <Col span={12}> <Form.Item label={t("authorization.actions.table.action_code")} name={"action_code"} rules={[...RULES_FORM.required]} > <Input placeholder={ t("authorization.actions.table.action_code") || "" } disabled={!isCreate} /> </Form.Item> </Col> <Col span={12}> <Form.Item name="action_name" label={t("authorization.actions.table.action_name")} rules={[...RULES_FORM.required]} > <Input placeholder={ t("authorization.actions.table.action_name") || "" } /> </Form.Item> </Col> <Col span={24}> <Form.Item name="description" label={t("authorization.actions.table.description")} > <Input.TextArea placeholder={ t("authorization.actions.table.description") || "" } /> </Form.Item> </Col> </Row> </Form> </div> </Modal> </> ); }
library(dplyr) library(textclean) library(stringr) library(httr) # L1: Compare old and new csv files to obtain table with rows that need to be cleaned and added==== load_all_new_data <- function () { all_csv_files <- c("fracfocuscsv/FracFocusRegistry_1.csv", "fracfocuscsv/FracFocusRegistry_2.csv", "fracfocuscsv/FracFocusRegistry_3.csv", "fracfocuscsv/FracFocusRegistry_4.csv", "fracfocuscsv/FracFocusRegistry_5.csv", "fracfocuscsv/FracFocusRegistry_6.csv", "fracfocuscsv/FracFocusRegistry_7.csv", "fracfocuscsv/FracFocusRegistry_8.csv", "fracfocuscsv/FracFocusRegistry_9.csv", "fracfocuscsv/FracFocusRegistry_10.csv", "fracfocuscsv/FracFocusRegistry_11.csv", "fracfocuscsv/FracFocusRegistry_12.csv", "fracfocuscsv/FracFocusRegistry_13.csv", "fracfocuscsv/FracFocusRegistry_14.csv", "fracfocuscsv/FracFocusRegistry_15.csv", "fracfocuscsv/FracFocusRegistry_16.csv", "fracfocuscsv/FracFocusRegistry_17.csv") list <- lapply(all_csv_files, function(fname) { read.csv(paste0("8 Update Data/", fname), stringsAsFactors = FALSE, colClasses = c("APINumber"="character")) }) master_table <- do.call(rbind.data.frame, list) return (tbl_df(master_table)) } new_master_table <- load_all_new_data() old_L5 <- tbl_df(read.csv("2 Cleaning/L5 Cleaning/L5 master table.csv", stringsAsFactors = FALSE, colClasses = c("APINumber"="character"))) %>% select(-X) old_upload_keys <- unique(old_L5$UploadKey) uncleaned_master <- new_master_table %>% filter( !(UploadKey %in% old_upload_keys) ) # L2 ===== # Search for non-ASCII characters column_classes <- sapply(uncleaned_master, class) char_type_indices <- unname(which(column_classes == "character")) # records all indices of char columns replaced_indices <- data.frame(column = c(), row = c()) replaced_strings <- c() for (i in char_type_indices) { print(paste("beginning column", i)) v <- pull(uncleaned_master, i) nonascii <- which(replace_non_ascii(str_replace_all(v, " ", "")) != str_replace_all(v, " ", "")) for (rowentry in nonascii) { replaced_indices <- rbind(replaced_indices, data.frame(column=i, row=rowentry)) replaced_strings <- c(replaced_strings, v[rowentry]) } } # Results: 1023 entries with non-ascii characters w <- str_replace_all(replaced_strings, "\n", "") w <- str_replace_all(w, "\t", "") which_replaced_strings <- which(replace_non_ascii(str_replace_all(w, " ", "")) != str_replace_all(w, " ", "")) # all non-ascii characters taken care of L2_updated <- uncleaned_master for (r in 1:nrow(replaced_indices)) { col <- replaced_indices$column[r] row <- replaced_indices$row[r] entry <- L2_updated[row, col] print(paste0(r, "/1023 replacing entry: ", entry)) entry <- str_replace_all(entry, "\n", "") entry <- str_replace_all(entry, "\t", "") L2_updated[row, col] <- entry } write.csv(L2_updated, file="8 Update Data/L2 updated.csv") # L3 ===== # Exclude all 88,184 entries made to Frac Focus 1.0 L3_updated <- L2_updated %>% filter(FFVersion != 1) # Quality assurance check 1: unique combination of fracture date and API number QA_table_1 <- L3_updated %>% select(UploadKey, JobStartDate, JobEndDate, APINumber) %>% distinct() # Results: 18,921 unique UploadKeys; each have unique JobStartDate, JobEndDate, APINumber combination distinct_uploadkeys <- QA_table_1 %>% distinct(JobStartDate, JobEndDate, APINumber, .keep_all = TRUE) %>% pull(UploadKey) # Results: 18,570 unique JobStartDate/JobEndDate/APINumber combinations; 351 duplicate UploadKeys L3_updated <- L3_updated %>% filter(UploadKey %in% distinct_uploadkeys) # Results: Excluded 12,312 rows # Quality assurance check 2: fracture date after January 1, 2011 L3_updated <- L3_updated %>% filter(grepl("201[12345678]", JobStartDate)) # Results: Filtered out 2,434 submissions from before 2011; last JobStartDate was 12/31/2018 # State verification: ensure Latitude/Longitude match StateName # (which is calculated from StateNumber, calculated from APINumber) projection_summary <- L3_updated %>% group_by(Projection) %>% summarize(NumSubmissions = n(), NumJobs = n_distinct(UploadKey), NumWells = n_distinct(APINumber)) # Results: NAD27: 414887 submissions, 10386 jobs # NAD83: 262752 submissions, 7723 jobs # WGS84: 16285 submissions, 397 jobs # Convert NAD27 to NAD83 NAD27_points_to_convert <- L3_updated %>% filter(Projection == "NAD27") %>% select(UploadKey, Latitude, Longitude) %>% rename(lat = Latitude, lon = Longitude) %>% distinct(UploadKey, .keep_all=TRUE) %>% mutate(eht="N/A", inDatum="NAD27", outDatum="NAD83(2011)", spcZone="auto", utmZone="auto") # Make manual corrections for latitudes out of range [25, 50] and longitudes outside range [-130, -65] for (i in which(NAD27_points_to_convert$UploadKey %in% c( # switch lat and lon for these UploadKeys "84115b41-f470-4ae8-a9a7-9721006e3711", "10993081-6739-4d9e-9056-b314b07d7fb5" ))) { lat <- NAD27_points_to_convert[i, 3] NAD27_points_to_convert[i, 3] <- NAD27_points_to_convert[i, 2] NAD27_points_to_convert[i, 2] <- lat } for (i in which(NAD27_points_to_convert$UploadKey %in% c( # negative longitude for these UploadKeys "4267797c-63d3-448c-97af-edec3d9934f9", "d2eaf41d-bf01-407e-8e7f-13d9de224a9a", "72fd733e-2ab2-430d-910b-37f97bdcc248", "5d286e91-4a59-46f4-bd35-4e6e0e4286c5", "f838249d-7308-4de4-a4b2-7e234f896256", "879a6b42-a30f-4d15-8924-eeb6c00f9ea3" ))) { NAD27_points_to_convert[i, 3] <- -NAD27_points_to_convert[i, 3] } # These 3 have unsalvageable errors: # d4358031-8937-4cd4-9227-801045baf5c0 # d82618d9-ea80-4ea0-ae9a-134df8d45ae7 # b71f0646-2c79-43b1-ace8-c71846839a6c # Now write them to separate files writeNAD <- function (startnum, endnum) { write.csv(NAD27_points_to_convert[startnum:endnum,], file=paste0("8 Update Data/NAD27 points to convert/", startnum, "_", endnum, ".csv"), quote=FALSE, row.names=FALSE) } writeNAD(1, 1000) writeNAD(1001, 4000) writeNAD(4001, 8000) writeNAD(8001, nrow(NAD27_points_to_convert)) # MANUAL USE OF CONVERTER HERE TO GET OUTPUT FILES allcsvs <- list.files(path = "8 Update Data/NAD83 converted points/", pattern = "[0-9]+\\_[0-9]+\\.csv") list <- lapply(allcsvs, function(fname) { read.csv(paste0("8 Update Data/NAD83 converted points/", fname), na.strings="N/A", stringsAsFactors=FALSE) }) NAD83_converted_points <- tbl_df(do.call(rbind.data.frame, list)) %>% distinct() # weird doubles # Add LatitudeClean and LongitudeClean to hold NAD83, converted or original, or WGS84 coordinates get_lat_clean <- function (projection, uploadkey, srcLat) { if (projection == "NAD27") { return (NAD83_converted_points$destLat[which(NAD83_converted_points$ID == uploadkey)]) } return (srcLat) } get_lon_clean <- function (projection, uploadkey, srcLon) { if (projection == "NAD27") { return (NAD83_converted_points$destLon[which(NAD83_converted_points$ID == uploadkey)]) } return (srcLon) } L3_updated <- L3_updated %>% # (note: takes a while) mutate(LatitudeClean = mapply(get_lat_clean, Projection, UploadKey, Latitude)) %>% mutate(LongitudeClean = mapply(get_lon_clean, Projection, UploadKey, Longitude)) # Get area of each UploadKey from coordinates using FCC Area API area_from_coords <- L3_updated %>% distinct(UploadKey, .keep_all = TRUE) %>% select(UploadKey, LatitudeClean, LongitudeClean) %>% mutate(StateNameFromCoords = "", StateAbbFromCoords = "", StateNumberFromCoords = 0, CountyNameFromCoords = "", CountyCodeFromCoords = 0) invalid_keys <- c() for (i in 1:nrow(area_from_coords)) { print(paste0("Querying ", i, "/", nrow(area_from_coords))) FCC_resp <- GET(paste0("https://geo.fcc.gov/api/census/area?lat=", area_from_coords$LatitudeClean[i], "&lon=", area_from_coords$LongitudeClean[i], "&format=json")) if (status_code(FCC_resp) == 200 && length(content(FCC_resp)$results) > 0) { FCC_resp <- content(FCC_resp)$results[[1]] area_from_coords$StateNameFromCoords[i] <- FCC_resp$state_name area_from_coords$StateAbbFromCoords[i] <- FCC_resp$state_code area_from_coords$StateNumberFromCoords[i] <- as.integer(FCC_resp$state_fips) area_from_coords$CountyNameFromCoords[i] <- FCC_resp$county_name area_from_coords$CountyCodeFromCoords[i] <- as.integer(FCC_resp$county_fips) } else { invalid_keys <- c(invalid_keys, area_from_coords$UploadKey[i]) area_from_coords$StateNameFromCoords[i] <- NA area_from_coords$StateAbbFromCoords[i] <- NA area_from_coords$StateNumberFromCoords[i] <- NA area_from_coords$CountyNameFromCoords[i] <- NA area_from_coords$CountyCodeFromCoords[i] <- NA } } # Match to master table L3_updated <- left_join(L3_updated, (area_from_coords %>% select(-LatitudeClean, -LongitudeClean)), by="UploadKey") # Add StateOK and CountyOK fields L3_updated <- L3_updated %>% mutate(StateOK = (!is.na(StateNameFromCoords) & StateName == StateNameFromCoords)) %>% mutate(CountyOK = (!is.na(CountyNameFromCoords) & CountyName == CountyNameFromCoords)) # Fix all misspellings of Supplier in new SupplierClean field # Read supplier aliases.csv as data frame and convert to list of vectors, getting rid of "\t" and "\n" supplier_aliases_df <- read.csv("2 Cleaning/L3 Cleaning/supplier aliases.csv", header=FALSE, na.strings="", stringsAsFactors=FALSE) supplier_aliases_list <- apply(supplier_aliases_df, 1, function (row) { return (unique(str_replace_all(str_replace_all(row[which(!is.na(row))], "\n", ""), "\t", ""))) }) # Add SupplierClean column containing first possible spelling of each company L3_updated <- L3_updated %>% mutate(SupplierClean = as.character(lapply(Supplier, function (supplierdirty) { lst_idx <- match(TRUE, lapply(supplier_aliases_list, function (v) {supplierdirty %in% v})) if (is.na(lst_idx)) { return (NA) } return (supplier_aliases_list[[lst_idx]][1]) }))) # Remove spaces from CASNumber field L3_updated <- L3_updated %>% mutate(CASNumber = str_replace_all(CASNumber, " ", "")) write.csv(L3_updated, file="8 Update Data/L3 updated.csv") # L4: L4_updated <- L3_updated # CASLabel generation: Valid, Invalid, Confidential, Proprietary, Trade Secret, or Not Available confidentials <- c("Confidential", "CBI", "Confidnetial", "confidential", "CONFIDENTIAL", "ConfidentialInfo", "ConfidentialBusines", "Confidenial", "Confidentail", "ConfBusInfo", "Confid.Bus.Info", "Confidental", "BusinessConfidental", "Conf", "Confidentia1", "Confinential", "CONFIDENTIALBUSINES", "Confindential", "COnfidential", "Condidential", "Confdential", "Coinfidential") proprietaries <- c("PROPRIETARY", "Proprietary", "proprietary", "Proprietatry", "3rdPartyProprietar", "Proprietar", "ProprietaryBlend", "Prop", "7732-18-5proprietary", "PROP", "7732-18-5/propr", "Propritary", "PROPRITARY", "propietary", "propriety", "3rdpartyproprietar", "Propietary", "proprietry", "Proprietart", "Priprietary", "Proprietery", "Properitary", "Propreitary", "Propriatary", "Prop.", "Proprietarty", "PROPRIERTARY", "PROPRIERARY", "PRIOPRIETARY", "prop", "Propriety", "proprietarty", "PRORIETARY", "Proprietaryl", "PROPRIETARY0.10", "Proptietary", "Proprietory", "Propreitory", "Proprieatary", "propriatary", "proprietory", "Porprietary") tradesecrets <- c("TradeSecret", "TRADESECRET", "tradesecret", "TradeSecret,disc.", "Tradesecret", "TRADESECRETS", "TS", "ts", "tradeseccret", "TradeSeceret", "tracesecret", "TradeName", "TradSecret", "TRADESECERET", "tradeSecret", "TradeSecrer", "TradeSecrte", "TradeSecert", "Tradesecret.", "Trade") notavailables <- c("NOTPROVIDED", "N/A", "na", "NA", "NotAvailable", "N.A.", "None", "none", "NOTAVAILABLE", "NONE", "n/a", "unknown", "Unavailable", "Notavailable", "Notavailable.", "\"N/A\"", "NOTASSIGNED", "undisclosed", "NotApplicable", "notlisted", "Undisclosed", "notassigned", "Notapplicable.", "UNK", "N/D", "N\\A", "NULL", "unk", "Notlisted", "NotEstablished", "non", "n/A", "Unknown", "NotAssigned", "NA?", "N/a", "Na", "(N/A#)", "BA", "Blank", "CASNotAssigned", "NoneListed", "UNKNOWN", "Notassigned", "NotListed", "CASnotassigned") L4_updated$CASNumber[which(is.na(L4_updated$CASNumber))] <- "NA" getCASLabel <- function (CAS) { if (grepl("^[0-9]+\\-[0-9][0-9]\\-[0-9]$", CAS)) { # It is a properly formatted number: check through digit verification digits <- as.numeric(strsplit(str_replace_all(CAS, "-", ""), "")[[1]]) checksum <- 0 for (i in 1:(length(digits)-1)) { checksum <- checksum + digits[i] * (length(digits) - i) } if (checksum %% 10 == digits[length(digits)]) { return ("Valid") } else { return ("Invalid") } } else if (CAS %in% confidentials) { return ("Confidential") } else if (CAS %in% proprietaries) { return ("Proprietary") } else if (CAS %in% tradesecrets) { return ("Trade Secret") } else if (CAS %in% notavailables) { return ("Not Available") } return ("Invalid") } L4_updated <- L4_updated %>% mutate(CASLabel = as.character(lapply(CASNumber, getCASLabel))) # Check for leading zeros in valid CASNumbers L4_updated %>% select(CASNumber, CASLabel) %>% filter(CASLabel == "Valid") %>% filter(substring(CASNumber, 1, 1) == "0") # Results: 8,323 mathematically valid CASNumbers with leading zeros cut_leading_zeros_CAS <- function (CASNumber, CASLabel) { if (CASLabel != "Valid") { return (NA) } if (substring(CASNumber, 1, 1) != "0") { return (CASNumber) } return (cut_leading_zeros_CAS(substring(CASNumber, 2), CASLabel)) } L4_updated <- L4_updated %>% mutate(CASNumberClean = mapply(cut_leading_zeros_CAS, CASNumber, CASLabel)) names(L4_updated$CASNumberClean) <- NULL # First check all existing CASNumberClean in previously cleaned data raw_nums2vnames <- tibble(CASNumberClean = unique(L4_updated$CASNumberClean)) cas2name <- tbl_df(read.csv("2 Cleaning/L5 Cleaning/L5 master table.csv", stringsAsFactors=F)) %>% select(CASNumberClean, IngredientNameClean) %>% filter(!is.na(CASNumberClean)) %>% distinct(CASNumberClean, .keep_all = TRUE) raw_nums2vnames <- left_join(raw_nums2vnames, cas2name, "CASNumberClean") raw_nums2vnames <- raw_nums2vnames %>% mutate(verified_names = ifelse(is.na(IngredientNameClean), "NOT FOUND", IngredientNameClean)) %>% filter(!is.na(CASNumberClean)) # Check against chemical database raw_nums <- raw_nums2vnames$CASNumberClean verified_names <- raw_nums2vnames$verified_names # Check NIH database for (i in 1:length(raw_nums)) { if (verified_names[i] == "NOT FOUND") { raw_num <- raw_nums[i] r <- GET(paste0("https://chem.nlm.nih.gov/chemidplus/rn/startswith/", raw_num)) ct <- content(r, "text") match <- regexpr("Substance Name\\:\\&nbsp\\;.+?<", ct) if (match != -1) { vname <- substring(ct, match[1]+21, attr(match, "match.length")[1]+match[1]-2) verified_names[i] <- vname } print(paste0("i=", i, "/", length(raw_nums), "; CAS=", raw_nums[i], "; vname: ", verified_names[i])) Sys.sleep(3.1) # has a max 1 search per 3 seconds } } # Through www.chemnet.com for (i in 1:length(raw_nums)) { if (verified_names[i] == "NOT FOUND") { r <- GET(paste0("http://www.chemnet.com/Products/supplier.cgi?f=plist;terms=", raw_nums[i], ";submit=search")) ct <- content(r, "text") match <- str_match(ct, "Found <b> (\\d+) </b> products for <h1>(?:.|\\r|\\n)*?<p>(?:.|\\r|\\n)*?<a href=.*?>(.*?)(?:<| \\[)") if (match[1,2] != "0" && !is.na(match[1,3])) { verified_names[i] <- match[1,3] } print(paste0("Raw_num=", raw_nums[i], " vname=", verified_names[i])) } } # Through webbook.nist.gov for (i in 1:length(raw_nums)) { if (verified_names[i] == "NOT FOUND") { r <- GET(paste0("https://webbook.nist.gov/cgi/cbook.cgi?ID=", raw_nums[i], "&Units=SI")) ct <- content(r, "text") vname <- str_match(ct, "<title>(.*?)</title>")[1,2] if (vname != "Registry Number Not Found") { verified_names[i] <- vname } print(paste0("raw_num=", raw_nums[i], " vname=", verified_names[i])) } } # Through http://www.sigmaaldrich.com/catalog/AdvancedSearchPage.do for (i in 1:length(raw_nums)) { if (verified_names[i] == "NOT FOUND") { r <- GET(paste0("https://www.sigmaaldrich.com/catalog/search?interface=CAS%20No.&term=", raw_nums[i], "&N=0&lang=en&region=US&focus=product&mode=mode+matchall")) ct <- content(r, "text") vname <- str_match(ct, "<h2 class=\"name\".*?>(.*?)</h2>")[1,2] if (!is.na(vname)) { verified_names[i] <- vname } print(paste0("raw_num=", raw_nums[i], " vname=", verified_names[i])) } } # Manual verification through scifinder.cas.org raw_nums[which(verified_names == "NOT FOUND")] # prints out CAS numbers to manually search set_vname <- function (casnum, vname) { new_verified_names <- verified_names new_verified_names[which(raw_nums == casnum)] <- vname eval.parent(substitute(verified_names <- new_verified_names)) } set_vname("5789-27-5", "4-Imidazolidinone, 5-methylene-3-phenyl-2-thioxo-") set_vname("6474-02-8", "Acetamide, N-[4-[[[(4-methylphenyl)sulfonyl](2-methyl-2H-tetrazol-5-yl)amino]sulfonyl]phenyl]-") set_vname("32685-03-3", "Phosphonic acid, P,P'-[[[2-[(2-hydroxyethyl)(phosphonomethyl)amino]ethyl]imino]bis(methylene)]bis-") set_vname("424-85-1", "Pregn-4-ene-3,11,20-trione, 9-fluoro-21-hydroxy- (7CI,8CI,9CI)") set_vname("6742-94-5", "Ethanone, 1-[(5alpha,17beta)-17-(acetyloxy)-3-[(difluoroboryl)oxy]androst-2-en-2-yl]- (9CI)") set_vname("1310-62-9", "DNA (mouse strain C57BL/6J clone K330328H03 EST (expressed sequence tag)) (9CI)") set_vname("253222-68-3", "GenBank AW300807 (9CI)") # Set all that aren't found to invalid invalids <- raw_nums[which(verified_names == "NOT FOUND")] for (inv_cas in invalids) { i <- which(L4_updated$CASNumberClean == inv_cas) L4_updated$CASLabel[i] = "Invalid" L4_updated$CASNumberClean[i] <- NA } raw_nums <- raw_nums[! raw_nums %in% invalids] verified_names <- verified_names[verified_names != "NOT FOUND"] # Add IngredientNameClean field to master table cas2vname <- tbl_df(data.frame(CASNumberClean = raw_nums, IngredientNameClean = verified_names, stringsAsFactors=FALSE)) L4_updated <- left_join(L4_updated, cas2vname, by = "CASNumberClean") # Many entries for water (base fluid) do not include a CAS number, so identify these as valid disclosures water_identifiers <- c( "Water (Including Mix Water Supplied by Client)*", "Water", "Carrier / Base Fluid - Water", "2% KCL Water", "Fresh Water", "Water (Including Mix Water Supplied by Client)", "Water, other", "Recycled Water ", "4% KCL Water", "Brine Water", "Lease Water", "NFIDB:2% KCL Water", "3% KCL Water", "Field Salt Water", "Produced Brine Water", "Tulare Water", "NFIDB:Lease Water", "water", "Water ", "KCl Water", "Produced Water", "1% KCL Water", "NFIDB:4% KCL Water", "NFIDB:Brine Water", "Recycled Water", "4% Salt Water", "10% Salt Water", "2% KCl Water", "NFIDB:3% KCL Water", "Water Moisture", "6% KCL Water", "fresh water", "NFIDB:3% NaCl Water", "NFIDB:6% KCL Water", "NFIDB:7% KCL Water", "18% Salt Water", "3% NaCl Water", "3% NACL Water", "4% NaCl Water", "5% KCl Water", "5% KCL Water", "7% KCL Water", "water, other", "2% KCl Lokern Water", "Brackish Water", "Brackish Water ", "NaCl Water", "NFIDB:15% Salt Water", "15% Salt Water", "3% Salt Water", "Fresh water", "KCL Water", "Lease Salt Water", "lease water", "NFIDB:5% KCL Water", "NFIDB:Water", "Produced Water ", "Production Water", "Salt Water", "Water (including mix water supplied by client)*", "Water, Other", " Water ", "1.5% KCL Water", "10% KCL Water", "3% KCl Water", "4% KCl Water", "4% NaCl Water ", "6% Salt Water ?", "Field Water", "NFIDB - 4 percent KCL Water", "NFIDB:1% KCL Water", "NFIDB:10% KCL Water", "NFIDB:10% Salt Water", "NFIDB:Sea Water", "produced Water", "Seawater", "Tulare Water", "Water (Including Mix Water Supplied by Client).", "Water (including mix water supplied by Client)*", "Water (including Mix Water supplied by Client)*", "Water (major)", "Water, Including MIx water supplied by client", "Water,other", "water(including mix water supplied by client)*", "Water/Salt" ) rows_to_change <- which((L4_updated$IngredientName %in% water_identifiers) & (L4_updated$CASLabel %in% c("Invalid", "Not Available"))) for (r in rows_to_change) { L4_updated$CASLabel[r] <- "Valid" L4_updated$CASNumberClean[r] <- "7732-18-5" L4_updated$IngredientNameClean[r] <- "Water" print(r) } # Identify System Disclosures L4_updated <- L4_updated %>% select(-SystemApproach) %>% mutate(SystemApproachFlag = !is.na(CASNumber) & !is.na(IngredientName) & (CASNumber == "Listed" | CASNumber == "ListedBelow" | CASNumber == "SystemDisclosure" | grepl("listed below", IngredientName, ignore.case=TRUE) | IngredientName == "Listed with chemicals" | IngredientName == "Listed with Ingredients" | IngredientName == "Listed with Other Chemicals" | IngredientName == "Listed with Other ingredients" | IngredientName == "Listed with Chemicals" | IngredientName == "Listed with Chemical Ingredients")) L4_updated$CASLabel[L4_updated$SystemApproachFlag] <- "Systems Approach" # Add WithheldFlag field: TRUE if CASLabel == Valid or Systems Approach; FALSE otherwise caslabel2withheld <- tbl_df(data.frame( CASLabel = c("Valid", "Systems Approach", "Invalid", "Proprietary", "Confidential", "Trade Secret", "Not Available"), WithheldFlag = c(FALSE, FALSE, TRUE, TRUE, TRUE, TRUE, TRUE), stringsAsFactors = FALSE)) L4_updated <- left_join(L4_updated, caslabel2withheld, by = "CASLabel") # Add Systems Approach Form flag (TRUE if the Form has any ingredients that used SA) L4_updated <- L4_updated %>% group_by(UploadKey) %>% mutate(FormUsedSystemApproach = sum(SystemApproachFlag) > 0) %>% ungroup() # RESULTS: 9,905 / 18,506 forms used Systems Approach write.csv(L4_updated, file="8 Update Data/L4 updated.csv") # L5 cleanup: this download already includes FF3 SA forms in entirety, so just assign relevant attributes L5_updated <- L4_updated %>% mutate( SubmissionsAvailable = TRUE, FromPDF = FALSE ) write.csv(L5_updated, "8 Update Data/L5 updated.csv") # Combine original and updated data sets ===== L5_original <- tbl_df(read.csv("2 Cleaning/L5 Cleaning/L5 master table.csv", stringsAsFactors = FALSE, colClasses = c("APINumber"="character"))) %>% select(-X) L5_original <- L5_original %>% mutate(DownloadDate = "2018-01-26") L5_updated <- L5_updated %>% mutate(DownloadDate = "2019-01-19") L5_updated_master_table <- bind_rows(L5_original, L5_updated) write.csv(L5_updated_master_table, "8 Update Data/L5_updated_master_table.csv") # Other data sets ==== essentials <- L5_updated_master_table %>% select(UploadKey, JobStartDate, JobEndDate, APINumber, FFVersion, StateName, StateAbbFromCoords, SupplierClean, CASLabel, CASNumberClean, IngredientNameClean, SystemApproachFlag, WithheldFlag, FormUsedSystemApproach, SubmissionsAvailable, FromPDF, DownloadDate) write.csv(essentials, file="8 Update Data/updated ESSENTIALS.csv") forms_data <- L5_updated_master_table %>% group_by(UploadKey) %>% mutate(WithholdingForm = sum(WithheldFlag) >= 1) %>% ungroup() %>% distinct(UploadKey, .keep_all=TRUE) %>% select(UploadKey, JobStartDate, JobEndDate, APINumber, StateNumber, CountyNumber, OperatorName, WellName, Latitude, Longitude, Projection, StateName, CountyName, FFVersion, LatitudeClean, LongitudeClean, StateNameFromCoords, StateAbbFromCoords, StateNumberFromCoords, CountyNameFromCoords, CountyCodeFromCoords, StateOK, CountyOK, FormUsedSystemApproach, SubmissionsAvailable, WithholdingForm, DownloadDate) write.csv(forms_data, file="8 Update Data/updated forms data.csv")
package Singleton.implementation; /** * * @author FA20-BSE-037 */ public class GameConfig { private static GameConfig instance; private int graphicsQuality; private int soundVolume; private String controlScheme; private GameConfig() { graphicsQuality = 30; soundVolume = 70; controlScheme = "Touchpad"; } public static synchronized GameConfig getInstance() { if (instance == null) { instance = new GameConfig(); } return instance; } public int getGraphicsQuality() { return graphicsQuality; } public void setGraphicsQuality(int quality) { graphicsQuality = quality; } public int getSoundVolume() { return soundVolume; } public void setSoundVolume(int volume) { soundVolume = volume; } public String getControlScheme() { return controlScheme; } public void setControlScheme(String scheme) { controlScheme = scheme; } public void displayConfig() { System.out.println("Graphics Quality: " + graphicsQuality); System.out.println("Sound Volume: " + soundVolume); System.out.println("Control Scheme: " + controlScheme); } }
using System; using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Hosting; using Microsoft.AspNetCore.Mvc; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using Monaco.Core.Infrastructure.Extensions; using Monaco.Data.Core.Infrastructure.Extensions; namespace Monaco.WebAPI { public class Startup { public Startup(IConfiguration configuration) { Configuration = configuration; } public IConfiguration Configuration { get; } // This method gets called by the runtime. Use this method to add services to the container. public IServiceProvider ConfigureServices(IServiceCollection services) { // Initialize Configurations services.InitializeConfigurations(Configuration); // Register HttpContext Accessor services.AddHttpContextAccessor(); // Register AutoMapper services.AddMonacoMapper(); // Register DataBase Context services.AddMonacoDbContext(); // Register MVC services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2); // Register Autofac var serviceProvider = services.AddMonacoAutoFac(); return serviceProvider; } // This method gets called by the runtime. Use this method to configure the HTTP request pipeline. public void Configure(IApplicationBuilder app, IHostingEnvironment env) { if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); } else { // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts. app.UseHsts(); } app.UseHttpsRedirection(); app.UseMvc(); } } }
import { useState } from 'react'; import Col from 'react-bootstrap/Col'; import Form from 'react-bootstrap/Form'; import Row from 'react-bootstrap/Row'; const ScoopOption = ({ name, imagePath, updateItemCount }) => { const [isValid, setIsValid] = useState(); const handleChange = (event) => { const currentValue = event.target.value; const currentValueFloat = parseFloat(currentValue); const valueIsValid = 0 <= currentValueFloat && currentValueFloat <= 10 && Math.floor(currentValueFloat) === currentValueFloat; setIsValid(valueIsValid); if (valueIsValid) updateItemCount(name, currentValue); }; return ( <Col xs={12} sm={6} md={4} lg={3} style={{ textAlign: 'center' }}> <img style={{ width: '75%' }} src={`http://localhost:3030/${imagePath}`} alt={`${name} scoop`} /> <Form.Group controlId={`${name}-count`} as={Row} style={{ marginTop: '10px' }}> <Form.Label column xs="6" style={{ textAlign: "right" }}>{name}</Form.Label> <Col xs="5" style={{ textAlign: "left" }}> <Form.Control isInvalid={!isValid} type="number" defaultValue={0} onChange={handleChange} /> </Col> </Form.Group> </Col> ); } export default ScoopOption;
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>jQuery Template</title> <script src="//code.jquery.com/jquery-1.12.0.min.js"></script> <script> $(function() { //code goes here, cant run without being wrapped in function //can use conditionals $('#generate').click(function() { //everything will happen once the generate button is clicked var backgroundURL = $("#userChoice").val(); //grabs value of background choice var name = $("#name").val(); //grabs value of the name var motto = $("#motto").val(); //grabs value of the motto $('#motto2').html(motto); //changes the motto from nothing to there choice $('#motto').fadeIn(2000); //will have it fade in when the button is clicked $('#name2').html(name);//change name to their name // $('#name').css("position", "absolute"); // <-- something i tried $('#name').fadeIn(2000); //will have it fade in when the button is clicked $("#banner").css("background-image", "url(" + backgroundURL + ")", "position", "relative;"); //will display the background of their choice $("#banner").fadeIn(2000); //banner will show $('#reset').click(function() { //will reset page when button is clicked location.reload(); }); //If the background chosen is colorful.jpg then change the font color to black if (backgroundURL == 'colorful.jpg') { $('#name2').css("color", "black"); $('#motto2').css("color", "black"); } //else keep the color of the font white else { $('#name2').css("color", "white"); $("#motto2").css("color", "white"); } }); }); </script> <style> #banner { height: 500px; width: 500px; display: none; margin: 0 auto; /*line-height:200px;*/ } #name2, #motto2 { /*Font on the banner*/ font-size: 50px; font-family: Courier; } /* Gives style to the questions for the user */ body { background-color: #66CCFF; text-align: center; text-shadow: 2px 1.5px orange; } /*Gives style to the buttons*/ button{ color:Black; font-family:Courier; border-radius: 12px; box-shadow: 0 2px 5px 0 black; } </style> </head> <body> <em><button type='reset' id='reset'>Reset</button></em> <h1> Name:<input type='text' id='name'></h1> <h1> Motto:<input type= 'text' id='motto'></h1> <h1 id='background'>What kind of background would you like?</h1> <select id="userChoice"> <option>---</option> <!--Picture URL is set to the Value is set to the userChoice--> <option value="beautiful_2.jpg">Beautiful</option> <option value='colorful.jpg'>Colorful</option> <option value='wonderful.jpg'>Cool</option> </select> <br> <br> <button id='generate'>Generate</button> <!--Allows everything to take place--> <div id='banner'> <h1 id='name2' style="color:black"></h1> <h1 id='motto2' style="color:black"></h1> </div> </body>
// Distance on 2D plane /* Input Format: The first line contains an integer M, indicating how many points you should read. For the next M lines, each line has two integers, indicating the point's location x and y. The next line contains an integer N, indicating the number of the pairs of chosen two points. And the next N lines, each line contains two integers, which are two indices representing two specific points needed to be calculated for Euclidean distance. (Notice that the first point is indexed 0, and the second point is indexed 1, and so on...) */ /* Output Format: Ouput has N lines. Each line contains a floating number, indicating the Euclidan distance of two specific points. */ #include <stdio.h> #include <stdlib.h> #include <math.h> typedef struct { int x; int y; } Point; Point * ones_vec_1(int length); float compute_distance(Point * a, int first_id, int second_id); int main(void) { Point * point_array; int i, length, N; float ans; scanf("%d", &length); // Give point_array memory and get first element address point_array = ones_vec_1(length); scanf("%d", &N); for (i = 0; i < N; i++) { int first, second; scanf("%d %d", &first, &second); // Compute distance of two points ans = compute_distance(point_array, first, second); printf("%.3f\n", ans); } return 0; } Point * ones_vec_1(int length) { Point * ptr = (Point *) malloc(length * sizeof(Point)); for (int i = 0; i < length; i++) { scanf("%d%d", &ptr[i].x, &ptr[i].y); } return ptr; } float compute_distance(Point * a, int first_id, int second_id) { float ans; Point first_p, second_p; first_p = a[first_id]; second_p = a[second_id]; ans = (float) sqrt(pow(first_p.x - second_p.x, 2) + pow(first_p.y - second_p.y, 2)); return ans; }
<template> <div> <br/> <Row style="margin-left: 20px;"> <Button type="success" @click="menuAdd" :disabled="add_button" :loading="add_loading"> <Icon type="md-add"/> 新建 </Button> <Button type="info" @click="menuChange" :disabled="change_button" :loading="change_loading"> <Icon type="ios-paper-outline"/> 编辑 </Button> <Button type="error" @click="menuDelete" :disabled="delete_button" :loading="delete_loading"> <Icon type="md-close"/> 删除 </Button> </Row> <br> <Row :gutter="16" style="margin-left: 20px;"> <Col span="20"> <Card :style="{height:Height+'px',overflow:'scroll'}"> <Tree :data="menu" :render="renderContent" @on-select-change="onClickMenu"></Tree> </Card> </Col> </Row> <Modal v-model="edit_menu" :mask-closable="false" :closable="true" :footer-hide="true" width="600" :styles="{top: '70px'}"> <NewMenu v-bind:is_edit="is_edit" v-bind:menu_info="menu_info" @toCancel="toCancel"></NewMenu> </Modal> </div> </template> <script> import { mapGetters, mapActions } from 'vuex' import NewMenu from '@/components/News/NewMenu.vue' import {system_get_editable_tree_menu, system_delete_menu} from '@/api/staffRole' export default { components: { NewMenu }, data() { return { menu: [], edit_menu: false, is_edit: false, add_loading: false, change_loading: false, delete_loading: false, add_button: true, change_button: true, delete_button: true, loading: false, menu_info: { id: null, parent_id: null, order: 1, code: '', name: '', url: '', button_type: 0 }, selected_menu: null } }, methods: { menuAdd() { if (!this.selected_menu) { return } this.menu_info = { id: null, parent_id: this.selected_menu.id, order: 1, code: '', name: '', url: '', button_type: 0 } this.is_edit = false this.edit_menu = true }, menuChange() { if (!this.selected_menu) { return } this.menu_info = { id: this.selected_menu.id, parent_id: this.selected_menu.parent_id, order: this.selected_menu.order, code: this.selected_menu.code, name: this.selected_menu.name, url: this.selected_menu.url, button_type: this.selected_menu.button_type, } this.is_edit = true this.edit_menu = true }, menuDelete() { if (!this.selected_menu) { return } let params = { id: this.selected_menu.id }; let that = this this.$Modal.confirm({ title: '削除', content: '削除しますか?', okText: "はい", cancelText: "いいえ", onOk: () => { system_delete_menu(params).then(res => { if (res.data.status == 'success') { this.$Message.success('正常に削除されました'); location.reload(); } else { this.$Message.error('削除に失敗しました'); } }) }, onCancel: () => { }, }) }, onClickMenu(node, item) { if (item.selected) { this.selected_menu = item this.add_button = false this.change_button = false this.delete_button = false } else { this.selected_menu = null this.add_button = true this.change_button = true this.delete_button = true } }, getMenu() { this.loading = true system_get_editable_tree_menu().then(res => { this.loading = false; if (res.data.status == "success") { this.menu = [{ id: 0, expand: true, name: "菜单树", button_type: -1, children: res.data.result }] } }).catch((error) => {this.loading = false}) }, renderContent(h, {root, node, data}) { let that = this if (data.children) { return h('span', { style: { display: 'inline-block', width: '100%' } }, [ h('span', [ h('Icon', { props: { type: 'ios-folder-outline' }, style: { marginRight: '8px' }, on: { click: () => { that.$set(data, 'expand', !data.expanded) } } }), h('span', { style: { cursor: 'pointer', fontSize: '15px' }, on: { click: () => { //console.log(data) } } }, data.name) ]) ]) } else { return h('span', { style: { display: 'inline-block', width: '100%' } }, [ h('span', [ h('Icon', { props: { type: 'ios-paper-outline' }, style: { marginRight: '8px' } }), h('span', { style: { cursor: 'pointer', fontSize: '15px' }, on: { click: () => { //console.log(data) } } }, data.name) ]), ] ) } }, toCancel(is_refesh) { if (is_refesh) { location.reload(); } this.edit_menu = false }, }, mounted() { this.getMenu() }, computed: { ...mapGetters(["screenHeight"]), Height() { return parseInt(this.screenHeight - 200) } } } </script>
import React, { useState, useEffect } from "react"; import { Box, Button, Flex, Text, Heading, useToast, Modal, ModalOverlay, ModalContent, ModalHeader, ModalFooter, ModalBody, ModalCloseButton, useDisclosure, } from "@chakra-ui/react"; import Header from "../../Components/Header"; import Footer from "../../Components/Footer"; import { BASE_URL } from "../../Redux/actionItems"; import { useSelector } from "react-redux"; import { Navigate } from "react-router-dom"; const Resultlist = () => { const [researchResults, setResearchResults] = useState([]); const [selectedResult, setSelectedResult] = useState(null); const [userDetails, setUserDetails] = useState({}); const { isOpen, onOpen, onClose } = useDisclosure(); const toast = useToast(); const state = useSelector((state) => state.authentication); useEffect(() => { const fetchResearchResults = async () => { try { const response = await fetch(`${BASE_URL}/api/ResearchResult`); if (response.ok) { const data = await response.json(); setResearchResults(data); } else { throw new Error("Failed to fetch research results."); } } catch (error) { toast({ title: "Error", description: error.message || "An error occurred while fetching research results.", status: "error", duration: 5000, isClosable: true, }); } }; fetchResearchResults(); }, [toast]); const fetchUserDetails = async (userId) => { try { const response = await fetch(`${BASE_URL}/api/User/${userId}`); if (response.ok) { const data = await response.json(); setUserDetails(data); } else { throw new Error("Failed to fetch user details."); } } catch (error) { toast({ title: "Error", description: error.message || "An error occurred while fetching user details.", status: "error", duration: 5000, isClosable: true, }); } }; const handleView = async (result) => { setSelectedResult(result); await fetchUserDetails(result.userId); onOpen(); }; if (!state.isAuth) { return <Navigate to="/login" />; } return ( <Box bgColor="lightblue"> <Header /> <Flex justify="center"> <Box w="80%" px={4}> <Box mt={10}> <Heading as="h2" textAlign="center" mb={8} fontSize="3xl">Research Results</Heading> {researchResults.map((result, index) => ( <Box key={result.id} p={4} borderWidth="1px" borderRadius="lg" mb={4} boxShadow="md" display="flex" alignItems="center" justifyContent="space-between" bgColor={index % 2 === 0 ? "teal.100" : "green.100"} onClick={() => handleView(result)} cursor="pointer" > <Text flex="20%"> {userDetails.firstName} {userDetails.lastName} </Text> <Text fontSize="lg" flex="80%"> Topic: {result.topic} </Text> </Box> ))} </Box> </Box> </Flex> <Modal isOpen={isOpen} onClose={onClose} size="full"> <ModalOverlay /> <ModalContent> <ModalHeader bg="teal.500" color="white"> Research Result Details </ModalHeader> <ModalCloseButton color="white" /> <ModalBody bg="gray.100" color="black" p={8}> {selectedResult && ( <> <Text fontSize="4xl" fontWeight="bold" textAlign="center" mb={4}> {selectedResult.topic} </Text> <Text fontWeight="bold" mb={2}>Introduction:</Text> <Text mb={4}>{selectedResult.introduction}</Text> <Text fontWeight="bold" mb={2}>Abstract:</Text> <Text mb={4}>{selectedResult.abstract}</Text> <Text fontWeight="bold" mb={2}>Methodology:</Text> <Text mb={4}>{selectedResult.methodology}</Text> <Text fontWeight="bold" mb={2}>Description:</Text> <Text mb={4}>{selectedResult.description}</Text> <Text fontWeight="bold" mb={2}>Result:</Text> <Text mb={4}>{selectedResult.result}</Text> <Text fontWeight="bold" mb={2}>Conclusion:</Text> <Text mb={4}>{selectedResult.conclusion}</Text> {userDetails && ( <> <Text fontWeight="bold" mt={4}>Researcher: {userDetails.firstName} {userDetails.lastName}</Text> <Text>Email: {userDetails.email}</Text> <Text>Department: {userDetails.department}</Text> </> )} </> )} </ModalBody> <ModalFooter bg="teal.500"> <Button colorScheme="whiteAlpha" mr={3} onClick={onClose}> Close </Button> </ModalFooter> </ModalContent> </Modal> <Footer /> </Box> ); }; export default Resultlist;
/* ooooo ooooo oooo `888' `888' `888 888 888 .ooooo. 888 oo.ooooo. .ooooo. oooo d8b .oooo.o 888ooooo888 d88' `88b 888 888' `88b d88' `88b `888""8P d88( "8 888 888 888ooo888 888 888 888 888ooo888 888 `"Y88b. 888 888 888 .o 888 888 888 888 .o 888 o. )88b o888o o888o `Y8bod8P' o888o 888bod8P' `Y8bod8P' d888b 8""888P' 888 o888o */ /** * Check if current browser is Internet Explorer * * @return {Boolean} */ function isIE() { var ua = window.navigator.userAgent; var msie = ua.indexOf("MSIE ") > 0; var trident = ua.indexOf("Trident/") > 0; var edge = ua.indexOf("Edge/") > 0; return (msie || trident || edge); } /** * Smooth scroll to an element on the page * * @param {HTMLElement} element HTML element to scroll to. * @param {Number} duration Animation duration in ms. Default 1500 * @param {Boolean} centerElement Center element on page. Default true */ function scrollToElement(element, duration = 1500, centerElement = true) { if (!element) return console.error( "HTML element missing" ); var headerHeight = document.querySelector(".site-header").offsetHeight; var vacantSpace = window.innerHeight - element.offsetHeight; var elementTop = getOffset(element).top; var offset = centerElement ? elementTop - Math.max(vacantSpace / 2, headerHeight) : elementTop - headerHeight; // Stop ongoing animations if (jQuery("html, body").is(':animated')) jQuery("html, body").stop(); jQuery("html, body").animate({ scrollTop: offset, }, duration); } /** * Get an elements offset position on page * * @param {HTMLElement} el HTML element to get position of * * @return {Object} Object containing top and left position of element */ function getOffset(el) { var _x = 0; var _y = 0; while( el && !isNaN( el.offsetLeft ) && !isNaN( el.offsetTop ) ) { _x += el.offsetLeft - el.scrollLeft; _y += el.offsetTop - el.scrollTop; el = el.offsetParent; } return { top: _y, left: _x }; } /** * Serialize form data * * @param {HTMLElement} Form element * * @return {String} Data string */ function serializeForm(form) { var data = []; if ( (typeof form === "object") && (form.nodeName === "FORM") ) { var multiples = {}; for (var elem in form.elements) { if ( !form.elements.hasOwnProperty(elem) ) continue; var field = form.elements[elem]; if ( field.name && (!field.disabled) && (field.type !== "file") && (field.type !== "reset") && (field.type !== "submit") && (field.type !== "button") ) { if ( field.type === "select-multiple" ) { // TODO: Create this function } else if ( ((field.type !== "checkbox") && (field.type !== "radio")) || field.checked ) { if ( field.name in multiples ) { if (multiples[field.name].indexOf(field.value) == -1) multiples[field.name].push(field.value); } else { multiples[field.name] = [field.value]; } } } } for (var i = 0; i < Object.keys(multiples).length; i++) { var values = multiples[Object.keys(multiples)[i]].join(","); data.push(encodeURIComponent(Object.keys(multiples)[i]) + "=" + encodeURIComponent(values)); } } return data.join("&").replace(/%20/g, "+"); } /** * Load or reload Google reCaptcha v3 */ function loadRecaptcha(callback = null, args = null) { const CAPTCHA_SITE_KEY = "6LcJSiUoAAAAAEgeaFT3TmET3--IIrHeNzCfFHjK"; grecaptcha.ready(function() { grecaptcha.execute(CAPTCHA_SITE_KEY, {action: 'submit'}).then(function(token) { let captchaResponses = document.querySelectorAll("#g-recaptcha-response"); if (captchaResponses) for (let i = 0; i < captchaResponses.length; i++) captchaResponses[i].value = token; if (callback) callback(args); }); }); window.recaptchaLoaded = true; } /** * Checks if an element is the child of another element * * @param {HTMLElement} element Child element * @param {HTMLElement} parent Suspected parent element * * @return {Boolean} Returns true if the element is a child of the parent */ function childOf(element, parent) { if (!element) return false; if (element == parent) return true; return childOf(element.parentElement, parent); }; /** * Get closest parent of specified tag name * * @param {HTMLElement} element Child element * @param {String} tag Tag name * * @return {HTMLElement} The closest element parent of specified tag name */ function getClosestByTag(element, tag) { if (!element) return false; if (element.tagName.toUpperCase() == tag.toUpperCase()) return element; return getClosestByTag(element.parentElement, tag); } /** * Get closest parent by class name * * @param {HTMLElement} element Child element * @param {String} className Class name * * @return {HTMLElement} The closest element parent by class name */ function getClosestByClass(element, className) { if (!element) return false; if (element.classList.contains(className)) return element; return getClosestByClass(element.parentElement, className); }
"use client"; import { Paginating } from "@/components/paginating"; import { useGetLocations } from "@/api/queries/getLocations"; import { Location, getLocationsResponse } from "@/utils/types"; import { ApolloError } from "@apollo/client"; import { useState } from "react"; import { SingleLocation } from "./components/single-location"; import { LocationModal } from "./components/location-modal"; export const LocationsPage = () => { const [page, setPage] = useState(1); const [selectedLocation, setSelectedLocation] = useState<null | Location>( null ); const handleLocationClick = (location: Location) => { setSelectedLocation(location); }; const handleCloseModal = () => { setSelectedLocation(null); }; const { data, loading, error, }: { data: getLocationsResponse; loading: boolean; error?: ApolloError } = useGetLocations(page); if (loading) return ( <div className="w-full px-[20%] mob:px-[5%] flex flex-row grow justify-center items-center"> <p className="text-center self-center text-[24px] font-bold "> {"Loading..."} </p> </div> ); if (error) return ( <div className="w-full px-[20%] mob:px-[5%] flex flex-row grow justify-center items-center"> <p className="text-center text-[24px] font-bold ">{error.message}</p> </div> ); const maxPages = data.locations.info.pages; const locations = data.locations.results; return ( <div className="px-[20%] mob:px-[5%]"> {selectedLocation && ( <LocationModal location={selectedLocation} closeModalEvent={handleCloseModal} /> )} <div className={`h-fit py-5 grid grid-cols-4 gap-4 mob:grid-cols-2`}> {locations.map((location) => ( <SingleLocation location={location} key={location.id} locationClickEvent={handleLocationClick} /> ))} </div> {maxPages > 1 && ( <Paginating currentPage={page} pagesQty={maxPages} setPageEvent={setPage} /> )} </div> ); };
import { useEffect, useState } from "react"; export const Message = () => { const [ coords, setCoords] = useState({x:0, y:0}); useEffect(() => { //creo una función a parte para que es la que se ejecutará cuando se monte el componente //debe ser a parte para que sea el mismo espacio en memoria al montar y desmontar el componenete const onMouseMove = ({x, y})=>{ // capturo las cordenadas del mouse desde el evento(event.x, event.y) y desestructuro setCoords({x, y}); } //se crea el listener y llamo a la función window.addEventListener('mousemove', onMouseMove) //se desmonta el componente y la función return () => { window.removeEventListener('mousemove', onMouseMove) } }, []) return ( <> <h3>Usuario ya existe</h3> {JSON.stringify(coords)} </> ) }
import ReactQueryProvider from "@/components/ReactQuery/ReactQueryProvider"; import {ToastContainer} from 'react-toastify'; import 'react-toastify/dist/ReactToastify.css'; import {BrowserRouter as Router} from 'react-router-dom'; // import {Inter} from "next/font/google"; // import {Roboto} from 'next/font/google' import {Poppins} from 'next/font/google' import "./globals.css"; import {AppRouterCacheProvider} from '@mui/material-nextjs/v13-appRouter'; import theme from "@/utils/theme"; import {ThemeProvider} from "@mui/material/styles"; // const roboto = Roboto({ // subsets: ["latin"], // weight: ['100', '300', '400', '500', '700', '900'], // display: 'swap', // }); const poppins = Poppins({ subsets: ['latin'], weight: ['400', '500', '600', '700', '800', '900'] }); export const metadata = { title: "Yalmar Management System", description: "The smart system for managing staff and client operations.", }; export default function RootLayout({children}) { return ( <html lang="en"> <body className={poppins.className}> <ReactQueryProvider> <AppRouterCacheProvider> <ThemeProvider theme={theme}> {children} </ThemeProvider> </AppRouterCacheProvider> </ReactQueryProvider> <ToastContainer position="top-center" autoClose={2500} hideProgressBar={false} newestOnTop={false} closeOnClick pauseOnFocusLoss={false} draggable pauseOnHover={false} theme="dark" style={{ color: "#fff", width: 600 }} /> </body> </html> ); }
import { create } from 'zustand' import { persist } from 'zustand/middleware' interface User { username: string, password: string } interface UserStore { user: User | null, setUser: (newUser: User) => void clearUser: () => void } export const useUserStore = create<UserStore>()( persist( (set) => ({ user: null, setUser: (newUser) => set(() => ({ user: newUser })), clearUser: () => set(() => ({ user: null })) }), { name: 'UserStorage' } ) )
// PROJECT CHRONO - http://projectchrono.org // // Copyright (c) 2014 projectchrono.org // All rights reserved. // // Use of this source code is governed by a BSD-style license that can be found // in the LICENSE file at the top level of the distribution and at // http://projectchrono.org/license-chrono.txt. // // Authors: Alessandro Tasora, Radu Serban #include "chrono/core/ChGlobal.h" #include "chrono/physics/ChBody.h" #include "chrono/physics/ChForce.h" namespace chrono { // Register into the object factory, to enable run-time dynamic creation and persistence CH_FACTORY_REGISTER(ChForce) ChForce::ChForce() : Body(nullptr), mode(FORCE), frame(BODY), align(BODY_DIR), vpoint(VNULL), vrelpoint(VNULL), restpos(VNULL), mforce(0), vdir(VECT_X), vreldir(VECT_X), force(VNULL), relforce(VNULL) { modula = chrono_types::make_shared<ChFunctionConst>(1); move_x = chrono_types::make_shared<ChFunctionConst>(0); move_y = chrono_types::make_shared<ChFunctionConst>(0); move_z = chrono_types::make_shared<ChFunctionConst>(0); f_x = chrono_types::make_shared<ChFunctionConst>(0); f_y = chrono_types::make_shared<ChFunctionConst>(0); f_z = chrono_types::make_shared<ChFunctionConst>(0); } ChForce::ChForce(const ChForce& other) : ChObj(other) { Body = other.Body; mforce = other.mforce; force = other.force; relforce = other.relforce; vdir = other.vdir; vreldir = other.vreldir; vpoint = other.vpoint; vrelpoint = other.vrelpoint; restpos = other.restpos; align = other.align; frame = other.frame; mode = other.mode; ChTime = other.ChTime; Qf = other.Qf; modula = std::shared_ptr<ChFunction>(other.modula->Clone()); move_x = std::shared_ptr<ChFunction>(other.move_x->Clone()); move_y = std::shared_ptr<ChFunction>(other.move_y->Clone()); move_z = std::shared_ptr<ChFunction>(other.move_z->Clone()); f_x = std::shared_ptr<ChFunction>(other.f_x->Clone()); f_y = std::shared_ptr<ChFunction>(other.f_y->Clone()); f_z = std::shared_ptr<ChFunction>(other.f_z->Clone()); } // Impose absolute or relative positions, also setting the correct "rest position". void ChForce::SetVpoint(ChVector3d mypoint) { // abs pos vpoint = mypoint; // rel pos vrelpoint = GetBody()->TransformPointParentToLocal(vpoint); // computes initial rest position. ChVector3d displace = VNULL; if (move_x) displace.x() = move_x->GetVal(ChTime); if (move_y) displace.y() = move_y->GetVal(ChTime); if (move_z) displace.z() = move_z->GetVal(ChTime); switch (frame) { case WORLD: restpos = Vsub(vpoint, displace); break; case BODY: restpos = Vsub(vrelpoint, displace); break; } } void ChForce::SetVrelpoint(ChVector3d myrelpoint) { // rel pos vrelpoint = myrelpoint; // abs pos vpoint = GetBody()->TransformPointLocalToParent(vrelpoint); // computes initial rest position. ChVector3d displace = VNULL; if (move_x) displace.x() = move_x->GetVal(ChTime); if (move_y) displace.y() = move_y->GetVal(ChTime); if (move_z) displace.z() = move_z->GetVal(ChTime); switch (frame) { case WORLD: restpos = Vsub(vpoint, displace); break; case BODY: restpos = Vsub(vrelpoint, displace); break; } } // Impose absolute force directions void ChForce::SetDir(ChVector3d newf) { vdir = Vnorm(newf); vreldir = GetBody()->TransformDirectionParentToLocal(vdir); UpdateState(); // update also F } // Impose relative force directions void ChForce::SetRelDir(ChVector3d newf) { vreldir = Vnorm(newf); vdir = GetBody()->TransformDirectionLocalToParent(vreldir); UpdateState(); // update also F } // Impose module void ChForce::SetMforce(double newf) { mforce = newf; UpdateState(); // update also F } // Force as applied to body void ChForce::GetBodyForceTorque(ChVector3d& body_force, ChVector3d& body_torque) const { switch (mode) { case FORCE: { body_force = force; // Fb = F.w ChStarMatrix33<> Xpos(vrelpoint); body_torque = -(Xpos.transpose() * relforce); // Mb = - [u]'[A]'F,w = - [u]'F,l break; } case TORQUE: body_force = VNULL; // Fb = 0; body_torque = relforce; // Mb = [A]'F,w = F,l break; default: break; } } // Updating void ChForce::UpdateTime(double mytime) { ChTime = mytime; //... put time-dependent stuff here.. } void ChForce::UpdateState() { ChBody* my_body; double modforce; ChVector3d vectforce; ChVector3d vmotion; ChVector3d xyzforce; my_body = GetBody(); // ====== Update the position of point of application vmotion = VNULL; if (move_x) vmotion.x() = move_x->GetVal(ChTime); if (move_y) vmotion.y() = move_y->GetVal(ChTime); if (move_z) vmotion.z() = move_z->GetVal(ChTime); switch (frame) { case WORLD: vpoint = Vadd(restpos, vmotion); // Uw vrelpoint = my_body->TransformPointParentToLocal(vpoint); // Uo1 = [A]'(Uw-Xo1) break; case BODY: vrelpoint = Vadd(restpos, vmotion); // Uo1 vpoint = my_body->TransformPointLocalToParent(vrelpoint); // Uw = Xo1+[A]Uo1 break; } // ====== Update the fm force vector and add fv modforce = mforce * modula->GetVal(ChTime); vectforce = VNULL; xyzforce = VNULL; if (f_x) xyzforce.x() = f_x->GetVal(ChTime); if (f_y) xyzforce.y() = f_y->GetVal(ChTime); if (f_z) xyzforce.z() = f_z->GetVal(ChTime); switch (align) { case WORLD_DIR: vreldir = my_body->TransformDirectionParentToLocal(vdir); vectforce = Vmul(vdir, modforce); vectforce = Vadd(vectforce, xyzforce); break; case BODY_DIR: vdir = my_body->TransformDirectionLocalToParent(vreldir); vectforce = Vmul(vdir, modforce); xyzforce = my_body->TransformDirectionLocalToParent(xyzforce); vectforce = Vadd(vectforce, xyzforce); break; } force = vectforce; // Fw relforce = my_body->TransformDirectionParentToLocal(force); // Fo1 = [A]'Fw // ====== Update the Qc lagrangian! switch (mode) { case FORCE: { Qf(0) = force.x(); // pos.lagrangian Qfx Qf(1) = force.y(); Qf(2) = force.z(); // Qfrot= (-[A][u][G])'f ChStarMatrix33<> Xpos(vrelpoint); ChVector3d VQtemp = Xpos.transpose() * relforce; // = [u]'[A]'F,w ChGlMatrix34<> mGl(my_body->GetCoordsys().rot); ChVectorN<double, 4> Qfrot = -mGl.transpose() * VQtemp.eigen(); // Q = - [Gl]'[u]'[A]'F,w Qf.segment(3, 4) = Qfrot; break; } case TORQUE: Qf(0) = 0; // pos.lagrangian Qfx Qf(1) = 0; Qf(2) = 0; // rot.lagangian ChGlMatrix34<> mGl(my_body->GetCoordsys().rot); ChVectorN<double, 4> Qfrot = mGl.transpose() * relforce.eigen(); Qf.segment(3, 4) = Qfrot; break; } } void ChForce::Update(double mytime) { UpdateTime(mytime); UpdateState(); } // File I/O void ChForce::ArchiveOut(ChArchiveOut& archive_out) { // class version number archive_out.VersionWrite<ChForce>(); // serialize parent class too ChObj::ArchiveOut(archive_out); // stream out all member data ForceType_mapper ftypemapper; archive_out << CHNVP(ftypemapper(mode), "force_type"); ReferenceFrame_mapper refmapper; archive_out << CHNVP(refmapper(frame), "reference_frame_type"); AlignmentFrame_mapper alignmapper; archive_out << CHNVP(alignmapper(align), "alignment_frame_type"); archive_out << CHNVP(vrelpoint); archive_out << CHNVP(vpoint); archive_out << CHNVP(move_x); archive_out << CHNVP(move_y); archive_out << CHNVP(move_z); archive_out << CHNVP(restpos); archive_out << CHNVP(f_x); archive_out << CHNVP(f_y); archive_out << CHNVP(f_z); archive_out << CHNVP(mforce); archive_out << CHNVP(modula, "f_time"); archive_out << CHNVP(vreldir); archive_out << CHNVP(vdir); } void ChForce::ArchiveIn(ChArchiveIn& archive_in) { // class version number /*int version =*/archive_in.VersionRead<ChForce>(); // deserialize parent class too ChObj::ArchiveIn(archive_in); // stream in all member data ForceType_mapper ftypemapper; archive_in >> CHNVP(ftypemapper(mode), "force_type"); ReferenceFrame_mapper refmapper; archive_in >> CHNVP(refmapper(frame), "reference_frame_type"); AlignmentFrame_mapper alignmapper; archive_in >> CHNVP(alignmapper(align), "alignment_frame_type"); archive_in >> CHNVP(vrelpoint); archive_in >> CHNVP(vpoint); archive_in >> CHNVP(move_x); archive_in >> CHNVP(move_y); archive_in >> CHNVP(move_z); archive_in >> CHNVP(restpos); archive_in >> CHNVP(f_x); archive_in >> CHNVP(f_y); archive_in >> CHNVP(f_z); archive_in >> CHNVP(mforce); archive_in >> CHNVP(modula, "f_time"); archive_in >> CHNVP(vreldir); archive_in >> CHNVP(vdir); } } // end namespace chrono
//controllers/authController.js import User from "../models/userModel.js"; import bcrypt from "bcryptjs"; import { generateToken } from "../utils/jwtUtils.js"; export const handleSignup = async (req,res)=>{ try { const {username,password}=req.body; //check if username is already exist const existingUser = await User.findOne({username}); if(existingUser){ return res.status(400).json({ message: "Username already exists" }); } // hash the password const hashedPassword = await bcrypt.hash(password,10); // create new user const newUser = new User({ username, password: hashedPassword }) await newUser.save(); // generate token const token = generateToken(newUser._id, newUser.username) console.log(token) res.status(201).json({token}) } catch (error) { res.status(500).json({ message: error.message }); } } export const handleLogin = async (req, res) => { try { // Implementation for user login const { username, password } = req.body; // Find user by username const user = await User.findOne({ username }); if (!user) { return res.status(401).json({ message: "Invalid username or password" }); } // Check password const isPasswordValid = await bcrypt.compare(password, user.password); if (!isPasswordValid) { return res.status(401).json({ message: "Invalid username or password" }); } // Generate token const token = generateToken(user._id, user.username); res.status(200).json({ token }); } catch (error) { res.status(500).json({ message: error.message }); } }; export const handleLogout = async (req, res) => { try { // No need to do anything special for logout with JWT res.status(200).json({ message: "Logout successful" }); } catch (error) { res.status(500).json({ message: error.message }); } };
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <meta http-equiv="X-UA-Compatible" content="IE=edge" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <!-- Theme Color --> <meta name="theme-color" content="#6d9886" /> <!-- Fav Icon --> <!-- <link rel="icon" type="image/png" href="./images/logo.png" /> --> <!-- Css --> <!-- <link rel="stylesheet" href="../css/layout.css" /> --> <!-- Page style --> <link rel="stylesheet" href="../css/signup.css" /> <!-- Fonts --> <link rel="preconnect" href="https://fonts.googleapis.com" /> <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin /> <link href="https://fonts.googleapis.com/css2?family=Raleway:wght@700&family=Source+Code+Pro:wght@400;600&display=swap" rel="stylesheet" /> <title>Ostory | Signup</title> </head> <body> <div class="main"> <input type="checkbox" id="chk" aria-hidden="true" /> <!-- ........Signup form.......... --> <div class="signup"> <form id="signup-form" action=""> <label for="chk" aria-hidden="true">Sign up</label> <input id="userName" type="text" name="txt" placeholder="User name" required="" pattern="^[a-z]{8,}" /> <h5> Minimum eight characters,Usernames only smoll letter and no space </h5> <!-- ......................................................................................................... --> <input type="email" id="email" name="email" placeholder="Email" required="" pattern="^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$" /> <h5> The required Email may not include any special charaxters other than'@'sign </h5> <!-- ......................................................................................................... --> <input type="password" onChange="onChange(this.id,'confirm')" name="pswd" id="password" placeholder="Password" required="" pattern="^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)[a-zA-Z\d]{8,}$" /> <h5> Minimum eight characters, at least one uppercase letter, one lowercase letter and one number </h5> <!-- ......................................................................................................... --> <input name="confirm" type="password" onChange="onChange('password',this.id)" placeholder="confirm password" id="confirm" pattern="^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)[a-zA-Z\d]{8,}$" /> <!-- <button id="sign-up-button">Sign up</button> --> <div class="show" style="color: rgb(28, 23, 23)"> <input type="checkbox" onclick="Show1()" style="width: 20px; margin: 0" />show password </div> <input type="submit" id="sign-up-button" value="Submit" /> </form> </div> <!-- ..............login form................. --> <div class="login"> <form id="login-form" action=""> <label for="chk" aria-hidden="true" id="log">Login</label> <input id="login-email" type="email" name="email" placeholder="Email" required="" /> <input id="login-password" type="password" name="pswd" placeholder="Password" required="" /> <div class="show"> <input type="checkbox" onclick="Show2()" style="width: 20px; margin: 0" />show password </div> <input type="submit" id="login-button" value="Submit" /> </form> </div> </div> <script src="../js/login.js"></script> <script src="../js/signup.js"></script> <script> // Event Listener For Button sign up. document .getElementById("signup-form") .addEventListener("submit", function (event) { event.preventDefault(); const userName = document.getElementById("userName").value; const password = document.getElementById("password").value; const email = document.getElementById("email").value; const log = document.getElementById("log"); const id = new Date().valueOf(); signup({ userName, password, email, id }); document.getElementById("signup-form").reset(); log.click(); }); // Event Listener For Button login. /*-------------------- login ----------------------------------*/ document .getElementById("login-form") .addEventListener("submit", function (event) { event.preventDefault(); const email = document.getElementById("login-email").value; const password = document.getElementById("login-password").value; const id = new Date().valueOf(); login({ email, password, id }); document.getElementById("login-form").reset(); }); </script> </body> </html>
--[[ Name: Tokenizer.lua Author: ByteXenon [Luna Gilbert] Approximate date of creation: 2023/06/XX --]] --* Dependencies *-- local ModuleManager = require("ModuleManager/ModuleManager"):newFile("Interpreter/Synthax/Tokenizer/Tokenizer") local Helpers = ModuleManager:loadModule("Helpers/Helpers") local ParserBuilder = ModuleManager:loadModule("Interpreter/ParserBuilder/ParserBuilder") --* Export library functions *-- local StringToTable = Helpers.StringToTable local Class = Helpers.NewClass local Find = Helpers.TableFind local Insert = table.insert local Concat = table.concat --* Tokenizer *-- local Tokenizer = Class{ __init__ = function(self, String) self.CurPos = 1 self.CharStream = StringToTable(String) self.CurChar = self.CharStream[self.CurPos] end; Peek = function(self) self.CurPos = self.CurPos + 1 self.CurChar = self.CharStream[self.CurPos] return self.CurChar end; Check = function(self) return self.CharStream[self.CurPos + 1] end; SkipOptionalWhitespaces = function(self) if self:IsBlank(self.CurChar) then self:ReadBlank(); self:Peek() end end; IsKeyword = function(self, Character) return Character and Character:match("[%w_]") end; IsBlank = function(self, Character) return Character == "\t" or Character == "\n" or Character == " " end; IsCodeBlock = function(self, Character) return Character == "{" or Character == "(" end; IsComment = function(self, Character) return Character == "#" end; IsArrow = function(self, Character) return Character == "-" and self:Check() == ">" end; IsString = function(self, Character) return Character == "'" or Character == '"' end; IsMacro = function(self, Character) return Character == "@" end; IsToken = function(self, Character) return Character == "<" end; ReadKeyword = function(self) -- Use table.concat instead of multiple string -- concatinations to make it faster. local Keyword = {} repeat Insert(Keyword, self.CurChar) until not (self:IsKeyword(self:Check()) and self:Peek()) return Concat(Keyword) end; ReadBlank = function(self) repeat -- Nothing until not (self:IsBlank(self:Check()) and self:Peek()) end; ReadComment = function(self) repeat -- Nothing until not (self:Check() ~= "\n" and self:Peek()) end; ReadArrow = function(self) self:Peek(); self:Peek() self:SkipOptionalWhitespaces() return self:ReadKeyword() end; ReadString = function(self) local OpeningQuote = self.CurChar local String = {} while self:Peek() ~= OpeningQuote and self.CurChar do Insert(String, self.CurChar) end; assert(self.CurChar, "Invalid string") return Concat(String) end; ReadMacro = function(self) self:Peek() local Name = self:ReadKeyword() self:Peek() self:SkipOptionalWhitespaces() local Value = {} if self:IsCodeBlock(self.CurChar) then self:Peek() local My_StopChars = {(self.CurChar == "(" and ")" or "}")} Value = {{ TYPE = "CodeBlock", Value = self:ReadCodeBlock(My_StopChars) }} elseif self:IsKeyword(self.CurChar) then local NewKeyword = self:ReadKeyword() Value = {{ TYPE = "Keyword", Value = NewKeyword }} elseif self:IsString(self.CurChar) then local NewString = self:ReadString() Value = {{ TYPE = "Keyword", Value = NewString }} else repeat Insert(Value, self.CurChar) until not (self:Check() ~= "\n" and self:Peek()) Value = {{ TYPE = "Keyword", Value = Concat(Value) }} end return Name, Value end; ReadToken = function(self) self:Peek() local Params = {} local GetNextParam; function GetNextParam() if self:IsBlank(self.CurChar) then self:ReadBlank(); self:Peek() end local CurrentParam; if self:IsKeyword(self.CurChar) then CurrentParam = self:ReadKeyword() elseif self.CurChar == "%" then self:Peek() CurrentParam = "%" .. self:ReadKeyword() elseif self.CurChar == ">" then return Params end self:Peek() Insert(Params, CurrentParam) return GetNextParam() end return GetNextParam() end; ReadCodeBlock = function(self, StopChars) local AST = {} repeat if StopChars and Find(StopChars, self.CurChar) then return AST elseif self:IsBlank(self.CurChar) then self:ReadBlank() elseif self:IsComment(self.CurChar) then self:ReadComment() elseif self:IsToken(self.CurChar) then Insert(AST, { TYPE = "Token", Value = self:ReadToken() }) elseif self:IsKeyword(self.CurChar) then if self.CurChar == "_" then Insert(AST, { TYPE = "Token", Value = { "Blank" } }) else Insert(AST, { TYPE = "Keyword", Value = self:ReadKeyword() }) end elseif self:IsMacro(self.CurChar) then local Name, Value = self:ReadMacro() Insert(AST, { TYPE = "Macro", Name = Name, Value = Value }) elseif self:IsCodeBlock(self.CurChar) then local My_StopChars = {(self.CurChar == "(" and ")" or "}")} self:Peek() Insert(AST, { TYPE = "CodeBlock", Value = self:ReadCodeBlock(My_StopChars) }) elseif self:IsString(self.CurChar) then Insert(AST, { TYPE = "String", Value = self:ReadString() }) elseif self:IsArrow(self.CurChar) then Insert(AST, { TYPE = "Arrow", Value = self:ReadArrow() }) elseif self.CurChar == "}" or self.CurChar == ")" then return error("Unexpected end of code block") else Insert(AST, { TYPE = "Character", Value = self.CurChar }) end until not (self:Peek()) return AST end; Tokenize = function(self) return self:ReadCodeBlock() end } return Tokenizer
class Student1(object): def __init__(self, name, score=19): self.name = name self.score = score def print_score(self): print('%s: %s' % (self.name, self.score)) def get_grade(self): if self.score >= 90: return 'A' if self.score >= 60: return 'B' if self.score: return 'C' a = Student1('a', 98) print(a.score) a.score = 89 print(a.score) # 此处内部属性可以被外部改变 class Student2(object): def __init__(self, name, score=19): self.__name = name # 在属性名称前加 __ ,则实例变量变为私有变量,在类外部无法直接访问 self.__score = score def print_score(self): print('%s: %s' % (self.__name, self.__score)) def get_name(self): # 以下四个类的方法用于获取属性和修改属性 return self.__name def get_score(self): return self.__score def set_name(self, name): self.__name = name def set_score(self, score): self.__score = score b = Student2('b', 100) print() print(b.get_name()) print(b.get_score()) b.set_score(99) b.set_name('B') print() print(b.get_name()) print(b.get_score())
import { useState } from "react"; import AllotmentCard from "../Cards/AllotmentCard"; interface DragAndDropProps { allCourses: any[]; setAllCourses: any; widgets: any[]; setWidgets: any; } export default function DragAndDrop({ allCourses, setAllCourses, widgets, setWidgets, }: DragAndDropProps) { const [draggedItem, setDraggedItem] = useState<any>(null); function handleOnDragStart(event: React.DragEvent, widgetType: any, index: number) { event.dataTransfer.setData('widget', JSON.stringify(widgetType)); event.dataTransfer.setData('source', 'allCourses'); setDraggedItem({ widgetType, index }); } function handleWidgetDragStart(event: React.DragEvent, widget: any, index: number) { event.dataTransfer.setData('widget', JSON.stringify(widget)); event.dataTransfer.setData('source', 'widgets'); setDraggedItem({ widget, index }); } function handleOnDrop(event: React.DragEvent) { event.preventDefault(); const source = event.dataTransfer.getData('source'); const widget = JSON.parse(event.dataTransfer.getData('widget')); if (source === 'allCourses') { setWidgets([...widgets, widget]); const newAllCourses = allCourses.filter((course) => course.name !== widget.name); setAllCourses(newAllCourses); } else if (source === 'widgets') { const updatedWidgets = [...widgets]; updatedWidgets.splice(draggedItem.index, 1); setWidgets(updatedWidgets); setAllCourses([...allCourses, widget]); } setDraggedItem(null); } function handleWidgetDrop(event: React.DragEvent, targetIndex: number) { event.preventDefault(); const source = event.dataTransfer.getData('source'); const draggedWidget = JSON.parse(event.dataTransfer.getData('widget')); if (source === 'widgets') { const updatedWidgets = [...widgets]; updatedWidgets.splice(draggedItem.index, 1); updatedWidgets.splice(targetIndex, 0, draggedWidget); setWidgets(updatedWidgets); } setDraggedItem(null); } function handleCourseDrop(event: React.DragEvent) { event.preventDefault(); const source = event.dataTransfer.getData('source'); const widget = JSON.parse(event.dataTransfer.getData('widget')); if (source === 'widgets') { // setAllCourses([...allCourses, widget]); allCourses.push(widget); const sortedAllCourses = allCourses.sort((a, b) => a.id - b.id); setAllCourses(sortedAllCourses); console.log("Dropped course", widget.name); const updatedWidgets = widgets.filter((course) => course.name !== widget.name); setWidgets(updatedWidgets); } setDraggedItem(null); } function handleDragOver(event: React.DragEvent) { event.preventDefault(); } return ( <div className={`dark:bg-[#1A202C] p-4 flex-col lg:flex-row md:flex-row xl:flex-row 2xl:flex-row flex justify-center gap-10 min-h-[35rem] h-full w-full lg:w-[55rem] xl:w-w-[55rem] md:w-[55rem] 2xl:w-[55rem]`}> <div className="w-full min-h-96 h-full" onDrop={handleOnDrop} onDragOver={handleDragOver} > <div className="flex flex-col dark:bg-gray-800 bg-[#A4B8FF] h-96 overflow-y-auto shadow-xl"> {widgets.length > 0 ? ( widgets.map((widget: any, index: any) => ( <div className="py-2" key={index} draggable onDragStart={(e) => handleWidgetDragStart(e, widget, index)} onDrop={(e) => handleWidgetDrop(e, index)} onDragOver={(e) => e.preventDefault()} > <AllotmentCard course={widget} showRightIcon={true} showLeftIcon={false} onRightIconClick={() => { allCourses.push(widget); const newAllCourses = allCourses.sort((a, b) => a.id - b.id); setAllCourses(newAllCourses); const updatedWidgets = widgets.filter((course) => course.name !== widget.name); setWidgets(updatedWidgets); }} /> </div> )) ) : ( <div className="flex justify-center items-center h-full"> <p className="dark:text-[#808080] text-white text-center italic align-middle"> Drop your courses here </p> </div> )} </div> { widgets.length > 0 && ( <div className="flex justify-center items-center my-5"> <button className="dark:bg-[#1F2937] bg-[#A4B8FF] text-white px-4 py-1 rounded-md" onClick={() => { setWidgets([]); setAllCourses([...allCourses, ...widgets]); }} > Reset </button> </div> ) } </div> <div className="w-full min-h-96 h-full mb-20" onDrop={handleCourseDrop} onDragOver={handleDragOver} > <div className="flex flex-col dark:bg-gray-800 bg-[#A4B8FF] h-96 overflow-y-auto shadow-xl"> {allCourses.map((widget: any, index: any) => ( <div key={index} className="dark:bg-[#1F2937] bg-[#A4B8FF] px-2 py-2 text-white cursor-pointer" draggable onDragStart={(e) => handleOnDragStart(e, widget, index)} > <AllotmentCard course={widget} showRightIcon={false} showLeftIcon={true} onLeftIconClick={() => { setWidgets([...widgets, widget]); const newAllCourses = allCourses.filter((course) => course.name !== widget.name); setAllCourses(newAllCourses); }} /> </div> ))} {allCourses.length === 0 && ( <div className="flex justify-center items-center h-full"> <p className="dark:text-[#808080] text-white text-center italic align-middle"> No courses left </p> </div> )} </div> </div> </div> ); }
<!DOCTYPE html> <html> <head> <link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-T3c6CoIi6uLrA9TneNEoa7RxnatzjcDSCmG1MXxSR1GAsXEV/Dwwykc2MPK8M2HN" crossorigin="anonymous"> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.2/css/all.min.css"> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css"> </head> <title>Navigation Bar with Search Field</title> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.15.4/css/all.min.css"> <style> ul { list-style-type: none; margin: 0; padding: 0; overflow: hidden; background-color: #13817b; } li { float: left; } li a { display: block; color: white; text-align: center; padding: 14px 16px; text-decoration: none; } li a:hover { background-color: #111; } .div-flex { display: flex; flex-direction: row; justify-content: space-around; } .div-flex-col { display: flex; flex-direction: column; justify-content: space-around; } .blue-txt { color: rgb(80, 186, 179); display: flex; justify-content: center; font-size: x-large; } .search-field { display: flex; align-items: center; justify-content: center; margin-top: 20px; } .search-field input[type="text"] { padding: 5px; border: none; border-radius: 4px; } .search-field button { background-color: #555; color: white; border: none; padding: 5px 10px; border-radius: 4px; margin-left: 5px; cursor: pointer; } .search-field button:hover { background-color: #333; } .div-backgroundcolor{ background-color: #69c9c4; display: flex; flex-direction: row; justify-content: space-around; width: 100%; height: 60vh; } .square { display: flex; flex-direction: row; justify-content: space-around; background-color: #5ebcb7; margin-top: 3rem; width: 22vw; height: 40vh; border-radius: 20px; } .div-square-content{ display: flex; flex-direction: column; justify-content: space-around; align-items: center; } .img-size{ height: 8rem; width: 4rem; margin-top: 1rem; } .img-size1{ height: 8rem; width: 8rem; margin-top: 1rem; } </style> </head> <body> <ul class="div-flex"> <li><a href="#"><i class="fas fa-desktop navbar-icon"></i></a></li> <li><a>Home</a></li> </ul> <div class="div-flex-col"> <p class="blue-txt">Is your website design friendly?</p> <div class="search-field"> <!-- <input type="text" placeholder="Enter link"> --> <input type="text" id="url-input" placeholder="Enter any website link"> </div> </div> <div class="div-backgroundcolor"> <div class="square"> <div class="div-square-content"> <img class="img-size" src="https://m-cdn.phonearena.com/images/phones/74103-940/Apple-iPhone-X.jpg" alt=""> <h5>IphonX</h5> <P>375 * 812</P> <!-- <button>Choose</button> --> <!-- <button onclick="openWin()">Open Window</button> --> <button id="open-button">Choose</button> </div> </div> <div class="square"> <div class="div-square-content"> <img class="img-size" src="https://m.media-amazon.com/images/I/61U7w60CzrL.__AC_SY300_SX300_QL70_ML2_.jpg" alt=""> <h5>Galaxy Note 10</h5> <P>412 * 869</P> <button id="open-button-2">Choose</button> </div> </div> <div class="square"> <div class="div-square-content"> <img class="img-size" src="https://m.media-amazon.com/images/I/61ToKShnQvL.__AC_SY445_SX342_QL70_ML2_.jpg" alt=""> <h5>Ipad Pro</h5> <P>1024 * 1366</P> <button id="open-button-3">Choose</button> </div> </div> <div class="square"> <div class="div-square-content"> <img class="img-size1" src="https://m.media-amazon.com/images/I/71KR2i6-WaL.__AC_SX300_SY300_QL70_ML2_.jpg" alt=""> <h5>Mac OSX</h5> <P>1920 * 1080</P> <button id="open-button-4">Choose</button> </div> </div> </div> <script> document.addEventListener('DOMContentLoaded', function() { var button = document.getElementById('open-button'); button.addEventListener('click', openWin); var button2 = document.getElementById('open-button-2'); button2.addEventListener('click', openWin2); var button3 = document.getElementById('open-button-3'); button3.addEventListener('click', openWin3); var button4 = document.getElementById('open-button-4'); button4.addEventListener('click', openWin4); }); function openWin() { var url = document.getElementById('url-input').value; window.open(url, "_blank", "width=375,height=812"); } function openWin2() { var url = document.getElementById('url-input').value; window.open(url, "_blank", "width=412,height=869"); } function openWin3() { var url = document.getElementById('url-input').value; window.open(url, "_blank", "width=1024,height=1366"); } function openWin4() { var url = document.getElementById('url-input').value; window.open(url, "_blank", "width=1920,height=1080"); } </script> </body> </html>
import { Client } from '@notionhq/client' import fs from 'fs' import 'dotenv/config' const NOTION_INTEGRATION_SECRET = process.env .NOTION_INTEGRATION_SECRET as string const NOTION_DATABASE_ID = process.env.NOTION_DATABASE_ID as string const notion = new Client({ auth: NOTION_INTEGRATION_SECRET }) // 1. Recursion on nested blocks // 2. Recursion on block size const fetchPageBlocks = async (id: string) => { const blockListObj = await notion.blocks.children.list({ block_id: id, page_size: 50, }) const hydratedBlocks = Promise.all( blockListObj.results.map(async (block) => ({ ...block, children: block['has_children'] ? await fetchPageBlocks(block.id) : [], })) ) return hydratedBlocks } const serializeRead = async (doc: any) => { return fs.promises.writeFile( 'database.json', JSON.stringify(doc, undefined, 2) ) } ;(async () => { const databaseData = await notion.databases.query({ database_id: NOTION_DATABASE_ID, }) const databaseBlocks = await Promise.all( databaseData.results.map((page) => fetchPageBlocks(page.id)) ) // This completes reading await serializeRead({ database: databaseData, blocks: databaseBlocks.flat(), }) })()
import React, { useState, useEffect } from 'react'; import './ReportListPage.css'; import Navbar from '../Navbar'; import axios from 'axios'; const ReportListPage = () => { const [reports, setReportsData] = useState([]); const [searchTerm, setSearchTerm] = useState(''); useEffect(() => { axios.get('http://192.168.68.43:8000/api/v1/allreports') .then(response => { console.log('API response:', response.data); setReportsData(response.data); }) .catch(error => { console.error('Failed to fetch report data:', error); }); }, []); const filteredReports = reports.filter(report => { const lowerCaseSearchTerm = searchTerm.toLowerCase(); return ( report.date.toLowerCase().includes(lowerCaseSearchTerm) || report.project.toLowerCase().includes(lowerCaseSearchTerm) ); }); return ( <> <Navbar /> <div className="report-list"> <h2>Report List</h2> <input type="text" placeholder="Search by Date or Project Name" value={searchTerm} onChange={(e) => setSearchTerm(e.target.value)} /> <table> <thead> <tr> <th>id</th> <th>Name</th> <th>Project Name</th> <th>Date</th> <th>Hours Worked</th> <th>Comments</th> </tr> </thead> <tbody> {filteredReports.map((report, index) => ( <tr key={report.id || index}> <td>{report._id}</td> <td>{report.name}</td> <td>{report.project}</td> <td>{report.date}</td> <td>{report.time}</td> <td>{report.discription}</td> </tr> ))} </tbody> </table> </div> </> ); }; export default ReportListPage; // import React, { useState, useEffect } from 'react'; // import './ReportListPage.css'; // import Navbar from '../Navbar'; // const ReportListPage = (props) => { // const data = props.ds; // console.warn(data); // const [reportsData, setReportsData] = useState([]); // const [currentPage, setCurrentPage] = useState(1); // const [reportsPerPage] = useState(10); // const [searchTerm, setSearchTerm] = useState(''); // const [filteredReports, setFilteredReports] = useState([]); // const [currentReports, setCurrentReports] = useState([]); // useEffect(() => { // if (reportsData) { // const filtered = reportsData.filter( // (report) => // report.date.includes(searchTerm) || report.projectName.includes(searchTerm) // ); // setFilteredReports(filtered); // const indexOfLastReport = currentPage * reportsPerPage; // const indexOfFirstReport = indexOfLastReport - reportsPerPage; // setCurrentReports(filtered.slice(indexOfFirstReport, indexOfLastReport)); // } // }, [searchTerm, reportsData, currentPage, reportsPerPage]); // const paginate = (pageNumber) => { // setCurrentPage(pageNumber); // }; // return ( // <> // <Navbar /> // <div className="report-list"> // <h2>Report List</h2> // <input // type="text" // placeholder="Search by Date or Project Name" // value={searchTerm} // onChange={(e) => setSearchTerm(e.target.value)} // /> // <table> // <thead> // <tr> // <th>Date</th> // <th>Name</th> // <th>Project Name</th> // <th>Hours Worked</th> // <th>Comments</th> // </tr> // </thead> // <tbody> // {currentReports.map((info, index) => ( // <tr key={index}> // <td>{info.date}</td> // <td>{info.name}</td> // <td>{info.projectName}</td> // <td>{info.hoursWorked}</td> // <td>{info.comments}</td> // </tr> // ))} // </tbody> // </table> // <div className="pagination"> // {Array.from({ length: Math.ceil(filteredReports.length / reportsPerPage) }).map( // (_, index) => ( // <button key={index} onClick={() => paginate(index + 1)}> // {index + 1} // </button> // ) // )} // </div> // </div> // </> // ); // }; // export default ReportListPage;
/** ****************************************************************************** * @file main.c * @author Ac6 * @version V1.0 * @date 01-December-2013 * @brief Default main function. ****************************************************************************** */ #include "stm32f4xx.h" #include "stm32f4xx.h" #include <stdio.h> #include <stdlib.h> #include <stdint.h> #include <string.h> #include "task.h" #include <FreeRTOS.h> #define TRUE 1 #define FALSE 0 #define NOT_PRESSED FALSE #define PRESSED TRUE uint8_t button_status_flag = NOT_PRESSED,switch_prio; static void prvSetupHardware(void); static void pvrSetupUart(void); void printmsg(char *msg); char usr_msg[250]; void vTask1_handler(void *params); void vTask2_handler(void *params); void rtos_delay(uint32_t delay_in_ms); TaskHandle_t xTaskHandle1= NULL; TaskHandle_t xTaskHandle2= NULL; int main(void) { //1. Reset the RCC clock configuration to the default reset state. //HSI ON, PLL OFF, HSE OFF, system clock = 16MHz, cpu_clock = 16MHz RCC_DeInit(); //DWT->CTRL |= (1<<0);// Enable CYCCNT in DWT_CTRL //2. Update the SystemCoreClock variable SystemCoreClockUpdate(); prvSetupHardware(); //Start Recording //SEGGER_SYSVIEW_Conf(); //SEGGER_SYSVIEW_Start(); //lets create led_task xTaskCreate(vTask1_handler,"TASK-1",500,NULL,2,&xTaskHandle1); xTaskCreate(vTask2_handler,"TASK-1",500,NULL,3,&xTaskHandle2); //lets start the scheduler vTaskStartScheduler(); for(;;); } void vTask1_handler(void *params) { UBaseType_t p1,p2; sprintf(usr_msg,"Task-1 is running\r\n"); printmsg(usr_msg); sprintf(usr_msg,"Task-1 Priority %ld\r\n",uxTaskPriorityGet(xTaskHandle1)); printmsg(usr_msg); sprintf(usr_msg,"Task-2 Priority %ld\r\n",uxTaskPriorityGet(xTaskHandle2)); printmsg(usr_msg); while(1) { sprintf(usr_msg,"Task-1 is running\r\n"); printmsg(usr_msg); if(switch_prio) { sprintf(usr_msg,"Cambiando Prioridad\r\n"); printmsg(usr_msg); switch_prio=FALSE; p1= uxTaskPriorityGet(xTaskHandle1); p2= uxTaskPriorityGet(xTaskHandle2); vTaskPrioritySet(xTaskHandle1,p2); vTaskPrioritySet(xTaskHandle2,p1); }else { GPIO_ToggleBits(GPIOA,GPIO_Pin_5); rtos_delay(1000); } } } void vTask2_handler(void *params) { UBaseType_t p1,p2; sprintf(usr_msg,"Task-2 is running\r\n"); printmsg(usr_msg); sprintf(usr_msg,"Task-1 Priority %ld\r\n",uxTaskPriorityGet(xTaskHandle1)); printmsg(usr_msg); sprintf(usr_msg,"Task-2 Priority %ld\r\n",uxTaskPriorityGet(xTaskHandle2)); printmsg(usr_msg); while(1) { sprintf(usr_msg,"Task-2 is running\r\n"); printmsg(usr_msg); if(switch_prio) { sprintf(usr_msg,"Cambiando Prioridad\r\n"); printmsg(usr_msg); switch_prio=FALSE; p1= uxTaskPriorityGet(xTaskHandle1); p2= uxTaskPriorityGet(xTaskHandle2); vTaskPrioritySet(xTaskHandle1,p2); vTaskPrioritySet(xTaskHandle2,p1); }else { GPIO_ToggleBits(GPIOA,GPIO_Pin_5); rtos_delay(1000); } } } void button_handler(void *params) { button_status_flag ^=1;//XOR } static void pvrSetupUart(void) { GPIO_InitTypeDef gpio_uart_pins; USART_InitTypeDef uart2_init; //1. Enable the UART and GPIOA Peripheral clock RCC_APB1PeriphClockCmd(RCC_APB1Periph_USART2,ENABLE); RCC_AHB1PeriphClockCmd(RCC_AHB1Periph_GPIOA,ENABLE); //PA2 is UART2_TX, PA3 is UART2_RX //2. Alternate fnction configurations of MCU pins to behave as UART2 TX and RX //zeroing each and every member element of the structure memset(&gpio_uart_pins,0,sizeof(gpio_uart_pins)); gpio_uart_pins.GPIO_Pin = GPIO_Pin_2 | GPIO_Pin_3; gpio_uart_pins.GPIO_Mode = GPIO_Mode_AF; gpio_uart_pins.GPIO_PuPd = GPIO_PuPd_UP; GPIO_Init(GPIOA, &gpio_uart_pins); //3. AF mode settings for the pins GPIO_PinAFConfig(GPIOA,GPIO_PinSource2,GPIO_AF_USART2);//PA2 GPIO_PinAFConfig(GPIOA,GPIO_PinSource3,GPIO_AF_USART2);//PA3 //4. UART parameter initializations1 memset(&uart2_init,0,sizeof(uart2_init)); uart2_init.USART_BaudRate = 115200; uart2_init.USART_HardwareFlowControl = USART_HardwareFlowControl_None; uart2_init.USART_Mode = USART_Mode_Tx | USART_Mode_Rx; uart2_init.USART_Parity = USART_Parity_No; uart2_init.USART_StopBits = USART_StopBits_1; uart2_init.USART_WordLength = USART_WordLength_8b; USART_Init(USART2, &uart2_init); //5. Enable the UART2 peripheral USART_Cmd(USART2,ENABLE); } void prvSetupGpio(void) { RCC_AHB1PeriphClockCmd(RCC_AHB1Periph_GPIOA,ENABLE); RCC_AHB1PeriphClockCmd(RCC_AHB1Periph_GPIOC,ENABLE); RCC_APB2PeriphClockCmd(RCC_APB2Periph_SYSCFG,ENABLE); GPIO_InitTypeDef led_init,button_init; led_init.GPIO_Mode = GPIO_Mode_OUT; led_init.GPIO_OType = GPIO_OType_PP; led_init.GPIO_Pin = GPIO_Pin_5; led_init.GPIO_Speed = GPIO_Low_Speed; led_init.GPIO_PuPd = GPIO_PuPd_NOPULL; GPIO_Init(GPIOA,&led_init); button_init.GPIO_Mode = GPIO_Mode_IN; button_init.GPIO_OType = GPIO_OType_PP; button_init.GPIO_Pin = GPIO_Pin_13; button_init.GPIO_Speed = GPIO_Low_Speed; button_init.GPIO_PuPd = GPIO_PuPd_NOPULL; GPIO_Init(GPIOC,&button_init); //interrupt configuration for the button(pc13) //1. system configuration for exti line (SYSCFG settings) SYSCFG_EXTILineConfig(EXTI_PortSourceGPIOC,EXTI_PinSource13); //2. EXTI line configuration 13, fallin edge, interrup mode EXTI_InitTypeDef exti_init; exti_init.EXTI_Line = EXTI_Line13; exti_init.EXTI_Mode = EXTI_Mode_Interrupt; exti_init.EXTI_Trigger = EXTI_Trigger_Falling; exti_init.EXTI_LineCmd = ENABLE; EXTI_Init(&exti_init); //3. NVIC settings (IRQ settings for the selected EXTI line(13)) NVIC_SetPriority(EXTI15_10_IRQn,5); NVIC_EnableIRQ(EXTI15_10_IRQn); } static void prvSetupHardware() { //Setup Button and LED prvSetupGpio(); //setup UART2 pvrSetupUart(); } void printmsg(char *msg) { for(uint32_t i =0;i < strlen(msg);i++) { while(USART_GetFlagStatus(USART2,USART_FLAG_TXE)!= SET); USART_SendData(USART2,msg[i]); } } void EXTI15_10_IRQHandler(void) { //traceISR_ENTER(); //1. clear the interrupt pending bit of the EXTI line (13) EXTI_ClearITPendingBit(EXTI_Line13); switch_prio=TRUE; //traceISR_EXIT(); } void rtos_delay(uint32_t delay_in_ms) { uint32_t current_tick_count = xTaskGetTickCount(); uint32_t delay_in_ticks= (delay_in_ms*configTICK_RATE_HZ)/1000; while(xTaskGetTickCount() < (current_tick_count + delay_in_ticks)); }
const { DataTypes, Model } = require('sequelize') const sequelize = require('@database/dbConnection') class ViewSettings extends Model {} ViewSettings.init( { id: { type: DataTypes.UUID, allowNull: false, primaryKey: true, defaultValue: DataTypes.UUIDV4, }, name: { type: DataTypes.STRING(250), allowNull: false, index: true, }, description: { type: DataTypes.TEXT, }, template: { type: DataTypes.TEXT, defaultValue: '', }, module: { type: DataTypes.TEXT, defaultValue: '', }, style: { type: DataTypes.TEXT, defaultValue: '', }, markedToDelete: { type: DataTypes.BOOLEAN, allowNull: false, defaultValue: false, }, }, { sequelize, modelName: 'ViewSettings', tableName: 'view_settings', } ) module.exports = ViewSettings
/* * The Alluxio Open Foundation licenses this work under the Apache License, version 2.0 * (the "License"). You may not use this work except in compliance with the License, which is * available at www.apache.org/licenses/LICENSE-2.0 * * This software is distributed on an "AS IS" basis, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, * either express or implied, as more fully set forth in the License. * * See the NOTICE file distributed with this work for information regarding copyright ownership. */ package alluxio.underfs.obs; import com.obs.services.ObsClient; import com.obs.services.exception.ObsException; import com.obs.services.model.GetObjectRequest; import com.obs.services.model.ObsObject; import org.junit.Assert; import org.junit.Before; import org.junit.Test; import org.mockito.ArgumentMatchers; import org.mockito.Mockito; import java.io.IOException; import java.io.InputStream; public class OBSPositionReaderTest { /** * The OBS Position Reader. */ private OBSPositionReader mOBSPositionReader; /** * The OBS Client. */ private ObsClient mClient; /** * The Bucket Name. */ private final String mBucketName = "bucket"; /** * The Path (or the Key). */ private final String mPath = "path"; /** * The File Length. */ private final long mFileLength = 100L; @Before public void before() throws Exception { mClient = Mockito.mock(ObsClient.class); mOBSPositionReader = new OBSPositionReader(mClient, mBucketName, mPath, mFileLength); } /** * Test case for {@link OBSPositionReader#openObjectInputStream(long, int)}. */ @Test public void openObjectInputStream() throws Exception { ObsObject object = Mockito.mock(ObsObject.class); InputStream inputStream = Mockito.mock(InputStream.class); Mockito.when(mClient.getObject(ArgumentMatchers.any( GetObjectRequest.class))).thenReturn(object); Mockito.when(object.getObjectContent()).thenReturn(inputStream); // test successful open object input stream long position = 0L; int bytesToRead = 10; Object objectInputStream = mOBSPositionReader.openObjectInputStream(position, bytesToRead); Assert.assertTrue(objectInputStream instanceof InputStream); // test open object input stream with exception Mockito.when(mClient.getObject(ArgumentMatchers.any(GetObjectRequest.class))) .thenThrow(ObsException.class); try { mOBSPositionReader.openObjectInputStream(position, bytesToRead); } catch (Exception e) { Assert.assertTrue(e instanceof IOException); String errorMessage = String .format("Failed to get object: %s bucket: %s", mPath, mBucketName); Assert.assertEquals(errorMessage, e.getMessage()); } } }
const userModel = require("../models/user-model"); const argon2 = require("argon2"); const isStrongPw = require("validator/lib/isStrongPassword"); const isEmail = require("validator/lib/isEmail"); const createUser = async (req, res) => { const data = req.body; if (!isEmail(data.email)) return res.json({ type: "error", message: "Invalid Email Address", }); if (!isStrongPw) { return res.json({ type: "error", message: "Strong password is required", }); } const checkUser = await userModel.findOne( { $or: [{ email: data.email }, { name: data.name }], }, "-password" ); if (!!checkUser) return res.json({ type: "error", message: "Account already existed" }); const hashPw = argon2.hash(data.password); await userModel.create({ email: data.email, name: data.name, password: hashPw, }); return res.json({ type: "success", message: "Successfully created", }); }; const listUsers = async (req, res) => { const allUsers = await userModel.find(); return res.json({ type: "success", message: allUsers, }); }; const fetchUser = async (req, res) => { const userId = req.params.userId; const checkUser = await userModel.findById(userId, "-password"); if (!checkUser) return res.json({ type: "error", message: "Found no user.", }); return res.json({ type: "success", message: checkUser, }); }; const updateUser = async (req, res) => { const userId = req.params.userId; const data = req.body; // from client, user must use payload{ // name: string; // email: string; // updated: Date;} await userModel .findByIdAndUpdate(userId, { $set: { email: data.email, name: data.name, updated: new Date(Date.now()), }, }) .catch(() => { return res.json({ type: "error", message: "Found no user.", }); }); return res.json({ type: "success", message: "Updated a user.", }); }; const deleteUser = async (req, res) => { const userId = req.params.userId; await userModel.findOneAndDelete(userId).catch(() => { return res.json({ type: "error", message: "Found no user.", }); }); return res.json({ type: "success", message: "Deleted a user.", }); }; const signIn = async (req, res) => { const data = req.body; if (!isEmail(data.email)) return res.json({ type: "error", message: "Invalid Email Address", }); if (!isStrongPw) { return res.json({ type: "error", message: "Strong password is required", }); } const checkUser = await userModel.findOne({ email: data.email }); if (!checkUser) return res.json({ type: "error", message: "Create an account first to log in.", }); if (!(await argon2.verify(checkUser.password, data.password))) return res.json({ type: "error", message: "Incorrect password", }); return res.json({ type: "success", message: "Successfully login", }); }; const signOut = async (req, res) => { // delete token from client... return res.json({ type: "success", message: "Successfully logout", }); }; module.exports = { createUser, listUsers, fetchUser, updateUser, deleteUser, signIn, signOut, };
# BEGIN GPL LICENSE BLOCK # # This program 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. # # This program 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 this program. If not, see <https://www.gnu.org/licenses/>. # # END GPL LICENSE BLOCK """ File with the class Plane, class in charge of rendering a plane on the scene. """ import OpenGL.GL as GL import numpy as np from src.engine.scene.model.model import Model from src.utils import get_logger log = get_logger(module="PLANE") class Plane(Model): """ Class in charge of the modeling and drawing lines in the engine. """ def __init__(self, scene): """ Constructor of the class """ super().__init__(scene) self.draw_mode = GL.GL_TRIANGLES self.update_uniform_values = True self.__vertex_shader_file = './src/engine/shaders/plane_vertex.glsl' self.__fragment_shader_file = './src/engine/shaders/plane_fragment.glsl' self.__vertices_list = np.array([]) self.__indices_list = np.array([]) self.__plane_color = (1, 0, 0, 0.3) self.set_shaders(self.__vertex_shader_file, self.__fragment_shader_file) def set_plane_color(self, new_color: tuple) -> None: """ Change the color of the plane. Args: new_color: New color to use in the plane. (R,G,B,A) Returns: None """ self.__plane_color = new_color def _update_uniforms(self) -> None: """ Update the uniforms values for the model. Returns: None """ # update values for the polygon shader # ------------------------------------ projection_location = GL.glGetUniformLocation(self.shader_program, "projection") plane_color_location = GL.glGetUniformLocation(self.shader_program, "plane_color") # set the color and projection matrix to use # ------------------------------------------ GL.glUniform4f(plane_color_location, self.__plane_color[0], self.__plane_color[1], self.__plane_color[2], self.__plane_color[3]) GL.glUniformMatrix4fv(projection_location, 1, GL.GL_TRUE, self.scene.get_projection_matrix_2D()) def set_triangles(self, vertices: np.ndarray) -> None: """ Set the triangles to be drawn in the plane. Args: vertices: Vertices to be draw on the model. Returns: None """ self.__vertices_list = vertices num_vertices = int(len(self.__vertices_list) / 3) self.__indices_list = np.array(range(0, num_vertices)) # reset the buffers self.set_vertices(self.__vertices_list.astype(dtype=np.float32)) self.set_indices(self.__indices_list.astype(dtype=np.uint32)) def draw(self) -> None: """ Draw the model on the scene. Returns: None """ super().draw()
import 'package:flutter_clean_architecture_demo/ui/pages/carrousel_page.dart'; import 'package:flutter_clean_architecture_demo/ui/pages/home_page.dart'; import 'package:flutter_clean_architecture_demo/ui/pages/movie_page.dart'; import 'package:go_router/go_router.dart'; //* Clase para gestionar las diferentes rutas del proyecto a la hora de navegar entre pantallas final appRouter = GoRouter( initialLocation: '/carrousel', routes: [ GoRoute( path: '/carrousel', name: CarrouselPage.name, builder: (_, __) => const CarrouselPage(), ), GoRoute( path: '/home/:page', name: HomePage.name, builder: (_, state) => HomePage(pageIndex: int.parse(state.pathParameters['page'] ?? '0')), routes: [ GoRoute( path: 'movie/:id', name: MoviePage.name, builder: (_, state) => MoviePage(movieId: state.pathParameters['id'] ?? 'no-id'), ), ] ), GoRoute( path: '/', redirect: ( _ , __ ) => '/home/0', ), ] );
<!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8" /> <meta content="width=device-width, initial-scale=1.0" name="viewport" /> <title>Portfolio</title> <meta content="" name="description" /> <meta content="" name="keywords" /> <!-- Favicons --> <link href="assets/img/favicon.png" rel="icon" /> <link href="assets/img/apple-touch-icon.png" rel="apple-touch-icon" /> <!-- Google Fonts --> <link href="https://fonts.googleapis.com/css?family=Open+Sans:300,300i,400,400i,600,600i,700,700i|Raleway:300,300i,400,400i,500,500i,600,600i,700,700i|Poppins:300,300i,400,400i,500,500i,600,600i,700,700i" rel="stylesheet" /> <!-- Vendor CSS Files --> <link href="assets/vendor/aos/aos.css" rel="stylesheet" /> <link href="assets/vendor/bootstrap/css/bootstrap.min.css" rel="stylesheet" /> <link href="assets/vendor/bootstrap-icons/bootstrap-icons.css" rel="stylesheet" /> <link href="assets/vendor/boxicons/css/boxicons.min.css" rel="stylesheet" /> <link href="assets/vendor/glightbox/css/glightbox.min.css" rel="stylesheet" /> <link href="assets/vendor/swiper/swiper-bundle.min.css" rel="stylesheet" /> <!-- Template Main CSS File --> <link href="assets/css/style.css" rel="stylesheet" /> * Template Name: iPortfolio * Updated: Nov 17 2023 with Bootstrap v5.3.2 * Template URL: https://bootstrapmade.com/iportfolio-bootstrap-portfolio-websites-template/ * Author: BootstrapMade.com * License: https://bootstrapmade.com/license/ </head> <body> <!-- ======= Mobile nav toggle button ======= --> <i class="bi bi-list mobile-nav-toggle d-xl-none"></i> <!-- ======= Header ======= --> <header id="header"> <div class="d-flex flex-column"> <div class="profile"> <img src="assets/img/JEREENA D30489 B.jpg" alt="" class="portfolio-item" /> <h1 class="text-light"><a href="index.html">JEREENA JOHN</a></h1> <div class="social-links mt-3 text-center"> <!-- <a href="#" class="twitter"><i class="bx bxl-twitter"></i></a> <a href="#" class="facebook"><i class="bx bxl-facebook"></i></a> <a href="#" class="instagram"><i class="bx bxl-instagram"></i></a> <a href="#" class="google-plus"><i class="bx bxl-skype"></i></a> --> <!-- <label style="color: white">LinkedIn</label> --> <a href="https://www.linkedin.com/in/jereena-john-8a7888277/" class="linkedin" ><i class="bx bxl-linkedin"></i ></a> <a href="https://github.com/jereenajohn" class="github" ><i class="bx bxl-github"></i ></a> </div> </div> <nav id="navbar" class="nav-menu navbar"> <ul> <li> <a href="#hero" class="nav-link scrollto active" ><i class="bx bx-home"></i> <span>Home</span></a > </li> <li> <a href="#about" class="nav-link scrollto" ><i class="bx bx-user"></i> <span>About</span></a > </li> <!-- <li> <a href="#resume" class="nav-link scrollto" ><i class="bx bx-file-blank"></i> <span>Resume</span></a > </li> --> <li> <a href="#skills" class="nav-link scrollto" ><i class="bx bx-code"></i> <span>Languages & Skills</span></a > </li> <li> <a href="#experience" class="nav-link scrollto" ><i class="bx-link"></i> <span>Experience</span></a > </li> <li> <a href="#education" class="nav-link scrollto" ><i class="bx bx-book-content"></i> <span>Education</span></a > </li> <li> <a href="#projects" class="nav-link scrollto" ><i class="bx bx-server"></i> <span>Projects</span></a > </li> <li> <a href="Jereena's Resume (10).pdf" download="Jereena's Resume (10).pdf" class="nav-link scrollto" > <i class="bx bx-download"></i> <span>Resume</span> </a> </li> <!-- <li> <a href="#portfolio" class="nav-link scrollto" ><i class="bx bx-book-content"></i> <span>Portfolio</span></a > </li> --> <!-- <li> <a href="#education" class="nav-link scrollto" ><i class="bx bx-book-content"></i> <span>Portfolio</span></a > </li> --> <!-- <li> <a href="#services" class="nav-link scrollto" ><i class="bx bx-server"></i> <span>Services</span></a > </li> --> <li> <a href="#contact" class="nav-link scrollto" ><i class="bx bx-envelope"></i> <span>Contact</span></a > </li> </ul> </nav> <!-- .nav-menu --> </div> </header> <!-- End Header --> <!-- ======= Hero Section ======= --> <section id="hero" class="d-flex flex-column justify-content-center align-items-center" > <div class="hero-container" data-aos="fade-in"> <h1>Jereena John</h1> <p> I'm a <span class="typed" data-typed-items="Passionate Developer, Knowledge Seeker, Problem Solver" ></span> </p> </div> </section> <!-- End Hero --> <main id="main"> <!-- ======= About Section ======= --> <section id="about" class="about"> <div class="container"> <div class="section-title"> <h2>About</h2> <p style="text-align: justify"> <h6 style="font-family: 'Times New Roman', Times, serif;"> 👋I'm a passionate Flutter developer dedicated to building beautiful and performant mobile applications.</h6> <h6 style="font-family: 'Times New Roman', Times, serif;"> 🚀 With a strong focus on clean architecture and intuitive design, I create apps that offer seamless user experiences.</h6> <h6 style="font-family: 'Times New Roman', Times, serif;"> 💡 I'm always exploring the latest in Flutter and Dart, constantly learning and improving my skills.</h6> <h6 style="font-family: 'Times New Roman', Times, serif;"> 🌟 My projects showcase a blend of creativity and technical expertise, solving real-world problems with innovative solutions.</h6> <h6 style="font-family: 'Times New Roman', Times, serif;"> 🔧 I'm proficient in integrating APIs, managing state, and optimizing performance to deliver robust applications.</h6> <!-- I am a highly motivated IT fresher with a strong passion for technology and a desire to kick-start my career in the industry with a solid educational foundation in computer science. I am eager to apply my knowledge and gain hands-on experience in a dynamic professional setting. I am driven by curiosity, a strong work ethic, and a commitment to continuous learning. --> </p> </div> <div class="row"> <div class="col-lg-4" data-aos="fade-right"> <img src="assets/img/jereenajohn.jpg" class="img-fluid" alt="" /> </div> <div class="col-lg-8 pt-4 pt-lg-0 content" data-aos="fade-left"> <h3>Personal Details</h3> <!-- <p class="fst-italic"> Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. </p> --> <div class="row"> <div class="col-lg-6"> <ul> <li> <i class="bi bi-chevron-right"></i> <strong>Birthday:</strong> <span>9 July 1999</span> </li> <li> <i class="bi bi-chevron-right"></i> <strong>linkedin:</strong> <span ><a href="https://www.linkedin.com/in/jereena-john-8a7888277/" target="_blank" >LinkedIn Profile</a ></span > </li> <li> <i class="bi bi-chevron-right"></i> <strong>Phone:</strong> <span>+91 8157845851</span> </li> </ul> </div> <div class="col-lg-6"> <ul> <!-- <li> <i class="bi bi-chevron-right"></i> <strong>Age:</strong> <span>24</span> </li> --> <li> <i class="bi bi-chevron-right"></i> <strong>Degree:</strong> <span>Master's (MCA)</span> </li> <li> <i class="bi bi-chevron-right"></i> <strong>Email:</strong> <span>[email protected]</span> </li> <li> <i class="bi bi-chevron-right"></i> <strong>Place:</strong> <span>Thodupuzha, Idukki,Kerala</span> </li> <!-- <li> <i class="bi bi-chevron-right"></i> <strong>Freelance:</strong> <span>Available</span> </li> --> </ul> </div> </div> <h3>Achievements</h3> <div class="row"> <div class="col-lg-6"> <ul> <li> <i class="bi bi-chevron-right"></i> NPTEL Online Certification On Database Management System. <span></span> </li> <li> <i class="bi bi-chevron-right"></i> NPTEL Online Certification On Software Engineering. </li> <!-- <li> <i class="bi bi-chevron-right"></i> <strong>Phone:</strong> <span>+91 8157845851</span> </li> --> </ul> </div> <div class="col-lg-6"> <ul> <!-- <li> <i class="bi bi-chevron-right"></i> <strong>Age:</strong> <span>24</span> </li> --> <li> <i class="bi bi-chevron-right"></i> Published a Research Paper in IJARSCT International Conference on the topic Artificial Intelligence In Surveillance Camera. <!-- <li> <i class="bi bi-chevron-right"></i> <strong>Email:</strong> <span>[email protected]</span> </li> --> <!-- <li> <i class="bi bi-chevron-right"></i> <strong>Place:</strong> <span>Thodupuzha, Idukki,Kerala</span> </li> --> <!-- <li> <i class="bi bi-chevron-right"></i> <strong>Freelance:</strong> <span>Available</span> </li> --> </li> </ul> </div> </div> <!-- <p> Officiis eligendi itaque labore et dolorum mollitia officiis optio vero. Quisquam sunt adipisci omnis et ut. Nulla accusantium dolor incidunt officia tempore. Et eius omnis. Cupiditate ut dicta maxime officiis quidem quia. Sed et consectetur qui quia repellendus itaque neque. Aliquid amet quidem ut quaerat cupiditate. Ab et eum qui repellendus omnis culpa magni laudantium dolores. </p> --> </div> </div> </div> </section> <!-- End About Section --> <!-- ======= Facts Section ======= --> <!-- <section id="facts" class="facts"> <div class="container"> <div class="section-title"> <h2>Facts</h2> <p> Magnam dolores commodi suscipit. Necessitatibus eius consequatur ex aliquid fuga eum quidem. Sit sint consectetur velit. Quisquam quos quisquam cupiditate. Et nemo qui impedit suscipit alias ea. Quia fugiat sit in iste officiis commodi quidem hic quas. </p> </div> <div class="row no-gutters"> <div class="col-lg-3 col-md-6 d-md-flex align-items-md-stretch" data-aos="fade-up" > <div class="count-box"> <i class="bi bi-emoji-smile"></i> <span data-purecounter-start="0" data-purecounter-end="232" data-purecounter-duration="1" class="purecounter" ></span> <p><strong>Happy Clients</strong> consequuntur quae</p> </div> </div> <div class="col-lg-3 col-md-6 d-md-flex align-items-md-stretch" data-aos="fade-up" data-aos-delay="100" > <div class="count-box"> <i class="bi bi-journal-richtext"></i> <span data-purecounter-start="0" data-purecounter-end="521" data-purecounter-duration="1" class="purecounter" ></span> <p><strong>Projects</strong> adipisci atque cum quia aut</p> </div> </div> <div class="col-lg-3 col-md-6 d-md-flex align-items-md-stretch" data-aos="fade-up" data-aos-delay="200" > <div class="count-box"> <i class="bi bi-headset"></i> <span data-purecounter-start="0" data-purecounter-end="1453" data-purecounter-duration="1" class="purecounter" ></span> <p><strong>Hours Of Support</strong> aut commodi quaerat</p> </div> </div> <div class="col-lg-3 col-md-6 d-md-flex align-items-md-stretch" data-aos="fade-up" data-aos-delay="300" > <div class="count-box"> <i class="bi bi-people"></i> <span data-purecounter-start="0" data-purecounter-end="32" data-purecounter-duration="1" class="purecounter" ></span> <p><strong>Hard Workers</strong> rerum asperiores dolor</p> </div> </div> </div> </div> </section> --> <!-- End Facts Section --> <!-- ======= Skills Section ======= --> <section id="skills" class="skills section-bg"> <div class="container"> <div class="section-title"> <h2>Languages &amp; Skills</h2> <!-- <p> Magnam dolores commodi suscipit. Necessitatibus eius consequatur ex aliquid fuga eum quidem. Sit sint consectetur velit. Quisquam quos quisquam cupiditate. Et nemo qui impedit suscipit alias ea. Quia fugiat sit in iste officiis commodi quidem hic quas. </p> --> </div> <div class="row skills-content"> <div class="col-lg-6" data-aos="fade-up"> <div class="progress"> <span class="skill">Flutter <i class="val">95%</i></span> <div class="progress-bar-wrap"> <div class="progress-bar" role="progressbar" aria-valuenow="85" aria-valuemin="0" aria-valuemax="100" ></div> </div> </div> <div class="progress"> <span class="skill">Figma<i class="val">90%</i></span> <div class="progress-bar-wrap"> <div class="progress-bar" role="progressbar" aria-valuenow="100" aria-valuemin="0" aria-valuemax="100" ></div> </div> </div> <div class="progress"> <span class="skill">HTML <i class="val">100%</i></span> <div class="progress-bar-wrap"> <div class="progress-bar" role="progressbar" aria-valuenow="100" aria-valuemin="0" aria-valuemax="100" ></div> </div> </div> <div class="progress"> <span class="skill">CSS <i class="val">90%</i></span> <div class="progress-bar-wrap"> <div class="progress-bar" role="progressbar" aria-valuenow="90" aria-valuemin="0" aria-valuemax="100" ></div> </div> </div> <div class="progress"> <span class="skill">SQL <i class="val">95%</i></span> <div class="progress-bar-wrap"> <div class="progress-bar" role="progressbar" aria-valuenow="95" aria-valuemin="0" aria-valuemax="100" ></div> </div> </div> <div class="progress"> <span class="skill">Php <i class="val">85%</i></span> <div class="progress-bar-wrap"> <div class="progress-bar" role="progressbar" aria-valuenow="85" aria-valuemin="0" aria-valuemax="100" ></div> </div> </div> </div> <div class="col-lg-6" data-aos="fade-up" data-aos-delay="100"> <div class="progress"> <span class="skill">Firebase <i class="val">85%</i></span> <div class="progress-bar-wrap"> <div class="progress-bar" role="progressbar" aria-valuenow="85" aria-valuemin="0" aria-valuemax="100" ></div> </div> </div> <div class="progress"> <span class="skill">Python <i class="val">90%</i></span> <div class="progress-bar-wrap"> <div class="progress-bar" role="progressbar" aria-valuenow="90" aria-valuemin="0" aria-valuemax="100" ></div> </div> </div> <div class="progress"> <span class="skill">Java <i class="val">80%</i></span> <div class="progress-bar-wrap"> <div class="progress-bar" role="progressbar" aria-valuenow="80" aria-valuemin="0" aria-valuemax="100" ></div> </div> </div> <div class="progress"> <span class="skill">AngularJS <i class="val">70%</i></span> <div class="progress-bar-wrap"> <div class="progress-bar" role="progressbar" aria-valuenow="70" aria-valuemin="0" aria-valuemax="100" ></div> </div> </div> <div class="progress"> <span class="skill">Node Js <i class="val">70%</i></span> <div class="progress-bar-wrap"> <div class="progress-bar" role="progressbar" aria-valuenow="70" aria-valuemin="0" aria-valuemax="100" ></div> </div> </div> </div> </div> </div> </section> <!-- End Skills Section --> <!-- ======= Resume Section ======= --> <section id="experience" class="resume"> <div class="container"> <div class="section-title"> <h2>WORK EXPERIENCE</h2> <!-- <ul> <li> <a href="Jereena's Resume (4).pdf" download="Jereena's Resume (4).pdf" class="nav-link scrollto"> <i class="bx bx-download"></i> <span>Resume</span> </a> </li> </ul> <strong>DOWNLOAD YOUR RESUME HERE</strong> --> <!-- <p style="text-align: justify;"> I am a highly motivated IT fresher with a strong passion for technology and a desire to kick-start my career in the industry with a solid educational foundation in computer science. I am eager to apply my knowledge and gain hands-on experience in a dynamic professional setting. I am driven by curiosity, a strong work ethic, and a commitment to continuous learning. </p> --> </div> <div class="row"> <div class="col-lg-6" data-aos="fade-up"> <!-- <h3 class="resume-title">Sumary</h3> --> <!-- <div class="resume-item pb-0"> <h4>Alex Smith</h4> <p> <em style="text-align: justify;">I am a highly motivated IT fresher with a strong passion for technology and a desire to kick-start my career in the industry with a solid educational foundation in computer science. I am eager to apply my knowledge and gain hands-on experience in a dynamic professional setting. I am driven by curiosity, a strong work ethic, and a commitment to continuous learning.</em> </p> <ul> <li>Portland par 127,Orlando, FL</li> <li>(123) 456-7891</li> <li>[email protected]</li> </ul> </div> --> <!-- <h3 class="resume-title">Education</h3> --> <div class="resume-item"> <h4>FLUTTER DEVELOPER</h4> <h5>2024</h5> <h6 style="text-align: justify; font-family: 'Times New Roman', Times, serif;">Bepositive Racing Pvt Ltd</h6> <h6 style="text-align: justify; font-family: 'Times New Roman', Times, serif;">Currently Im working As a Flutter Developer at BePositive, I am responsible for designing and building sophisticated and highly scalable mobile applications for both Android and iOS platforms using the Flutter framework. </h6> <!-- <p> Qui deserunt veniam. Et sed aliquam labore tempore sed quisquam iusto autem sit. Ea vero voluptatum qui ut dignissimos deleniti nerada porti sand markend </p> --> </div> <div class="resume-item"> <h4>Flutter Intership</h4> <h5>2023</h5> <h6 style="text-align: justify; font-family: 'Times New Roman', Times, serif;">SmecLabs Kochi</h6> <h6 style="text-align: justify; font-family: 'Times New Roman', Times, serif;">During my internship at SMECLabs in Kochi, I gained hands-on experience in Flutter development, working on real-world projects that honed my skills in building cross-platform mobile applications. This internship provided me with valuable insights into the full software development lifecycle, from ideation to deployment, and reinforced my passion for creating innovative mobile solutions.</h6> <!-- <p> Quia nobis sequi est occaecati aut. Repudiandae et iusto quae reiciendis et quis Eius vel ratione eius unde vitae rerum voluptates asperiores voluptatem Earum molestiae consequatur neque etlon sader mart dila </p> --> </div> </div> <div class="col-lg-6" data-aos="fade-up" data-aos-delay="100"> <!-- <h3 class="resume-title">Education</h3> --> <div class="resume-item"> <h4>Jr.Python Developer</h4> <h5>2023</h5> <h6 style="text-align: justify; font-family: 'Times New Roman', Times, serif;">Tenzotech Kochi</h6> <h6 style="text-align: justify; font-family: 'Times New Roman', Times, serif;">At Tenzotech, my Python internship allowed me to immerse myself in diverse projects, enhancing my proficiency in this versatile programming language. I worked alongside a talented team, where I contributed to tasks ranging from data analysis and automation to web development.</div> <!-- <p> Quia nobis sequi est occaecati aut. Repudiandae et iusto quae reiciendis et quis Eius vel ratione eius unde vitae rerum voluptates asperiores voluptatem Earum molestiae consequatur neque etlon sader mart dila </p> --> </div> <!-- <div class="resume-item"> <h4>Senior graphic design specialist</h4> <h5>2019 - Present</h5> <p><em>Experion, New York, NY </em></p> <ul> <li> Lead in the design, development, and implementation of the graphic, layout, and production communication materials </li> <li> Delegate tasks to the 7 members of the design team and provide counsel on all aspects of the project. </li> <li> Supervise the assessment of all graphic materials in order to ensure quality and accuracy of the design </li> <li> Oversee the efficient use of production project budgets ranging from $2,000 - $25,000 </li> </ul> </div> --> <!-- <div class="resume-item"> <h4>Graphic design specialist</h4> <h5>2017 - 2018</h5> <p><em>Stepping Stone Advertising, New York, NY</em></p> <ul> <li> Developed numerous marketing programs (logos, brochures,infographics, presentations, and advertisements). </li> <li> Managed up to 5 projects or tasks at a given time while under pressure </li> <li> Recommended and consulted with clients on the most appropriate graphic design </li> <li> Created 4+ design presentations and proposals a month for clients and account managers </li> </ul> </div> --> </div> </div> </div> </section> <!-- ======= Resume Section ======= --> <section id="education" class="resume"> <div class="container"> <div class="section-title"> <h2>EDUCATION</h2> <!-- <ul> <li> <a href="Jereena's Resume (4).pdf" download="Jereena's Resume (4).pdf" class="nav-link scrollto"> <i class="bx bx-download"></i> <span>Resume</span> </a> </li> </ul> <strong>DOWNLOAD YOUR RESUME HERE</strong> --> <!-- <p style="text-align: justify;"> I am a highly motivated IT fresher with a strong passion for technology and a desire to kick-start my career in the industry with a solid educational foundation in computer science. I am eager to apply my knowledge and gain hands-on experience in a dynamic professional setting. I am driven by curiosity, a strong work ethic, and a commitment to continuous learning. </p> --> </div> <div class="row"> <div class="col-lg-6" data-aos="fade-up"> <!-- <h3 class="resume-title">Sumary</h3> --> <!-- <div class="resume-item pb-0"> <h4>Alex Smith</h4> <p> <em style="text-align: justify;">I am a highly motivated IT fresher with a strong passion for technology and a desire to kick-start my career in the industry with a solid educational foundation in computer science. I am eager to apply my knowledge and gain hands-on experience in a dynamic professional setting. I am driven by curiosity, a strong work ethic, and a commitment to continuous learning.</em> </p> <ul> <li>Portland par 127,Orlando, FL</li> <li>(123) 456-7891</li> <li>[email protected]</li> </ul> </div> --> <!-- <h3 class="resume-title">Education</h3> --> <div class="resume-item"> <h4>Master of Computer Application</h4> <h5>2021 - 2023</h5> <h6>82 %</h6> <p> <em >Santhigiri College Of Computer Sciences,Vazhithala,Idukki</em > </p> <!-- <p> Qui deserunt veniam. Et sed aliquam labore tempore sed quisquam iusto autem sit. Ea vero voluptatum qui ut dignissimos deleniti nerada porti sand markend </p> --> </div> <div class="resume-item"> <h4>Bachelor Computer Application</h4> <h5>2017 - 2020</h5> <h6>67 %</h6> <p> <em >Santhigiri College Of Computer Sciences,Vazhithala,Idukki</em > </p> <!-- <p> Quia nobis sequi est occaecati aut. Repudiandae et iusto quae reiciendis et quis Eius vel ratione eius unde vitae rerum voluptates asperiores voluptatem Earum molestiae consequatur neque etlon sader mart dila </p> --> </div> </div> <div class="col-lg-6" data-aos="fade-up" data-aos-delay="100"> <!-- <h3 class="resume-title">Education</h3> --> <div class="resume-item"> <h4>Higher Secondary Education</h4> <h5>2015 - 2017</h5> <h6>77 %</h6> <p> <em >ST.Joseph's Higher Secondary School,Karimannoor,Idukki</em > </p> <!-- <p> Quia nobis sequi est occaecati aut. Repudiandae et iusto quae reiciendis et quis Eius vel ratione eius unde vitae rerum voluptates asperiores voluptatem Earum molestiae consequatur neque etlon sader mart dila </p> --> </div> <div class="resume-item"> <h4>High School</h4> <h5>2015</h5> <h6>84 %</h6> <p><em>Vimala Public School,Thodupuzha,Idukki</em></p> <!-- <p> Quia nobis sequi est occaecati aut. Repudiandae et iusto quae reiciendis et quis Eius vel ratione eius unde vitae rerum voluptates asperiores voluptatem Earum molestiae consequatur neque etlon sader mart dila </p> --> </div> <!-- <div class="resume-item"> <h4>Senior graphic design specialist</h4> <h5>2019 - Present</h5> <p><em>Experion, New York, NY </em></p> <ul> <li> Lead in the design, development, and implementation of the graphic, layout, and production communication materials </li> <li> Delegate tasks to the 7 members of the design team and provide counsel on all aspects of the project. </li> <li> Supervise the assessment of all graphic materials in order to ensure quality and accuracy of the design </li> <li> Oversee the efficient use of production project budgets ranging from $2,000 - $25,000 </li> </ul> </div> --> <!-- <div class="resume-item"> <h4>Graphic design specialist</h4> <h5>2017 - 2018</h5> <p><em>Stepping Stone Advertising, New York, NY</em></p> <ul> <li> Developed numerous marketing programs (logos, brochures,infographics, presentations, and advertisements). </li> <li> Managed up to 5 projects or tasks at a given time while under pressure </li> <li> Recommended and consulted with clients on the most appropriate graphic design </li> <li> Created 4+ design presentations and proposals a month for clients and account managers </li> </ul> </div> --> </div> </div> </div> </section> <!-- End Resume Section --> <!-- ======= Portfolio Section ======= --> <!-- <section id="portfolio" class="portfolio section-bg"> <div class="container"> <div class="section-title"> <h2>Portfolio</h2> <p> Magnam dolores commodi suscipit. Necessitatibus eius consequatur ex aliquid fuga eum quidem. Sit sint consectetur velit. Quisquam quos quisquam cupiditate. Et nemo qui impedit suscipit alias ea. Quia fugiat sit in iste officiis commodi quidem hic quas. </p> </div> <div class="row" data-aos="fade-up"> <div class="col-lg-12 d-flex justify-content-center"> <ul id="portfolio-flters"> <li data-filter="*" class="filter-active">All</li> <li data-filter=".filter-app">App</li> <li data-filter=".filter-card">Card</li> <li data-filter=".filter-web">Web</li> </ul> </div> </div> <div class="row portfolio-container" data-aos="fade-up" data-aos-delay="100" > <div class="col-lg-4 col-md-6 portfolio-item filter-app"> <div class="portfolio-wrap"> <img src="assets/img/portfolio/portfolio-1.jpg" class="img-fluid" alt="" /> <div class="portfolio-links"> <a href="assets/img/portfolio/portfolio-1.jpg" data-gallery="portfolioGallery" class="portfolio-lightbox" title="App 1" ><i class="bx bx-plus"></i ></a> <a href="portfolio-details.html" title="More Details" ><i class="bx bx-link"></i ></a> </div> </div> </div> <div class="col-lg-4 col-md-6 portfolio-item filter-web"> <div class="portfolio-wrap"> <img src="assets/img/portfolio/portfolio-2.jpg" class="img-fluid" alt="" /> <div class="portfolio-links"> <a href="assets/img/portfolio/portfolio-2.jpg" data-gallery="portfolioGallery" class="portfolio-lightbox" title="Web 3" ><i class="bx bx-plus"></i ></a> <a href="portfolio-details.html" title="More Details" ><i class="bx bx-link"></i ></a> </div> </div> </div> <div class="col-lg-4 col-md-6 portfolio-item filter-app"> <div class="portfolio-wrap"> <img src="assets/img/portfolio/portfolio-3.jpg" class="img-fluid" alt="" /> <div class="portfolio-links"> <a href="assets/img/portfolio/portfolio-3.jpg" data-gallery="portfolioGallery" class="portfolio-lightbox" title="App 2" ><i class="bx bx-plus"></i ></a> <a href="portfolio-details.html" title="More Details" ><i class="bx bx-link"></i ></a> </div> </div> </div> <div class="col-lg-4 col-md-6 portfolio-item filter-card"> <div class="portfolio-wrap"> <img src="assets/img/portfolio/portfolio-4.jpg" class="img-fluid" alt="" /> <div class="portfolio-links"> <a href="assets/img/portfolio/portfolio-4.jpg" data-gallery="portfolioGallery" class="portfolio-lightbox" title="Card 2" ><i class="bx bx-plus"></i ></a> <a href="portfolio-details.html" title="More Details" ><i class="bx bx-link"></i ></a> </div> </div> </div> <div class="col-lg-4 col-md-6 portfolio-item filter-web"> <div class="portfolio-wrap"> <img src="assets/img/portfolio/portfolio-5.jpg" class="img-fluid" alt="" /> <div class="portfolio-links"> <a href="assets/img/portfolio/portfolio-5.jpg" data-gallery="portfolioGallery" class="portfolio-lightbox" title="Web 2" ><i class="bx bx-plus"></i ></a> <a href="portfolio-details.html" title="More Details" ><i class="bx bx-link"></i ></a> </div> </div> </div> <div class="col-lg-4 col-md-6 portfolio-item filter-app"> <div class="portfolio-wrap"> <img src="assets/img/portfolio/portfolio-6.jpg" class="img-fluid" alt="" /> <div class="portfolio-links"> <a href="assets/img/portfolio/portfolio-6.jpg" data-gallery="portfolioGallery" class="portfolio-lightbox" title="App 3" ><i class="bx bx-plus"></i ></a> <a href="portfolio-details.html" title="More Details" ><i class="bx bx-link"></i ></a> </div> </div> </div> <div class="col-lg-4 col-md-6 portfolio-item filter-card"> <div class="portfolio-wrap"> <img src="assets/img/portfolio/portfolio-7.jpg" class="img-fluid" alt="" /> <div class="portfolio-links"> <a href="assets/img/portfolio/portfolio-7.jpg" data-gallery="portfolioGallery" class="portfolio-lightbox" title="Card 1" ><i class="bx bx-plus"></i ></a> <a href="portfolio-details.html" title="More Details" ><i class="bx bx-link"></i ></a> </div> </div> </div> <div class="col-lg-4 col-md-6 portfolio-item filter-card"> <div class="portfolio-wrap"> <img src="assets/img/portfolio/portfolio-8.jpg" class="img-fluid" alt="" /> <div class="portfolio-links"> <a href="assets/img/portfolio/portfolio-8.jpg" data-gallery="portfolioGallery" class="portfolio-lightbox" title="Card 3" ><i class="bx bx-plus"></i ></a> <a href="portfolio-details.html" title="More Details" ><i class="bx bx-link"></i ></a> </div> </div> </div> <div class="col-lg-4 col-md-6 portfolio-item filter-web"> <div class="portfolio-wrap"> <img src="assets/img/portfolio/portfolio-9.jpg" class="img-fluid" alt="" /> <div class="portfolio-links"> <a href="assets/img/portfolio/portfolio-9.jpg" data-gallery="portfolioGallery" class="portfolio-lightbox" title="Web 3" ><i class="bx bx-plus"></i ></a> <a href="portfolio-details.html" title="More Details" ><i class="bx bx-link"></i ></a> </div> </div> </div> </div> </div> </section> --> <!-- End Portfolio Section --> <!-- ======= Services Section ======= --> <section id="projects" class="services"> <div class="container"> <div class="section-title"> <h2>PROJECTS</h2> <!-- <p> Magnam dolores commodi suscipit. Necessitatibus eius consequatur ex aliquid fuga eum quidem. Sit sint consectetur velit. Quisquam quos quisquam cupiditate. Et nemo qui impedit suscipit alias ea. Quia fugiat sit in iste officiis commodi quidem hic quas. </p> --> </div> <div class="row"> <div class="col-lg-6 col-md-6 icon-box" data-aos="fade-up"> <div class="icon"><i class="bi bi-emoji-smile"></i></div> <h4 class="title"><a href="">Bepocart</a></h4> <p style="text-align: justify" class="description"> Bepocart is a an Android/Ios App developed for Buying Best Cycling Accessories & Apparel india online from Bepocart with Best offers you can get on Cycling Helmets, Cycling Jerseys etc.<strong >Technologies used to develop are Flutter,API Integration.</strong > </p> </div> <div class="col-lg-6 col-md-6 icon-box" data-aos="fade-up" data-aos-delay="100" > <div class="icon"><i class="bi bi-card-checklist"></i></div> <h4 class="title"><a href="">Studyspot Discover</a></h4> <p class="description" style="text-align: justify"> Study Spot Discover is an Android Application for helping students to find there desired courses in the best Institute.<strong >Technologies used to develop this project includes Flutter and Firebase.</strong > </p> </div> <div class="col-lg-6 col-md-6 icon-box" data-aos="fade-up" data-aos-delay="200" > <div class="icon"><i class="bi bi-calendar4-week"></i></div> <h4 class="title"><a href="">Smart Light</a></h4> <p class="description" style="text-align: justify"> Smart Light is an IOT based Android Application used for controlling Lights.<b >Technologies used to develop this project are Flutter and Firebase.</b > </p> </div> <div class="col-lg-6 col-md-6 icon-box" data-aos="fade-up"> <div class="icon"><i class="bi bi-emoji-smile"></i></div> <h4 class="title"><a href="">Design Your Dream</a></h4> <p style="text-align: justify" class="description"> Design Your Dream is a an Android App developed for customizing designing materials based on customers interest and purchase those items.<strong >Technologies used to develop are HTML, CSS, PYTHON, MYSQL.</strong > </p> </div> <div class="col-lg-6 col-md-6 icon-box" data-aos="fade-up" data-aos-delay="100" > <div class="icon"><i class="bi bi-card-checklist"></i></div> <h4 class="title"><a href="">Leave Management System</a></h4> <p class="description" style="text-align: justify"> Leave Management System is web application developed for employees for applying leaves online.<strong >Technologies used to develop this project includes HTML, CSS, ANGULAR, NODEJS, MYSQL.</strong > </p> </div> <!-- <div class="col-lg-4 col-md-6 icon-box" data-aos="fade-up" data-aos-delay="400" > <div class="icon"><i class="bi bi-brightness-high"></i></div> <h4 class="title"><a href="">Nemo Enim</a></h4> <p class="description"> At vero eos et accusamus et iusto odio dignissimos ducimus qui blanditiis praesentium voluptatum deleniti atque </p> </div> --> <!-- <div class="col-lg-4 col-md-6 icon-box" data-aos="fade-up" data-aos-delay="500" > <div class="icon"><i class="bi bi-calendar4-week"></i></div> <h4 class="title"><a href="">Eiusmod Tempor</a></h4> <p class="description"> Et harum quidem rerum facilis est et expedita distinctio. Nam libero tempore, cum soluta nobis est eligendi </p> </div> --> </div> </div> </section> <!-- End Services Section --> <!-- ======= Testimonials Section ======= --> <!-- <section id="testimonials" class="testimonials section-bg"> <div class="container"> <div class="section-title"> <h2>Testimonials</h2> <p> Magnam dolores commodi suscipit. Necessitatibus eius consequatur ex aliquid fuga eum quidem. Sit sint consectetur velit. Quisquam quos quisquam cupiditate. Et nemo qui impedit suscipit alias ea. Quia fugiat sit in iste officiis commodi quidem hic quas. </p> </div> <div class="testimonials-slider swiper" data-aos="fade-up" data-aos-delay="100" > <div class="swiper-wrapper"> <div class="swiper-slide"> <div class="testimonial-item" data-aos="fade-up"> <p> <i class="bx bxs-quote-alt-left quote-icon-left"></i> Proin iaculis purus consequat sem cure digni ssim donec porttitora entum suscipit rhoncus. Accusantium quam, ultricies eget id, aliquam eget nibh et. Maecen aliquam, risus at semper. <i class="bx bxs-quote-alt-right quote-icon-right"></i> </p> <img src="assets/img/testimonials/testimonials-1.jpg" class="testimonial-img" alt="" /> <h3>Saul Goodman</h3> <h4>Ceo &amp; Founder</h4> </div> </div> <!-- End testimonial item --> <!-- <div class="swiper-slide"> <div class="testimonial-item" data-aos="fade-up" data-aos-delay="100" > <p> <i class="bx bxs-quote-alt-left quote-icon-left"></i> Export tempor illum tamen malis malis eram quae irure esse labore quem cillum quid cillum eram malis quorum velit fore eram velit sunt aliqua noster fugiat irure amet legam anim culpa. <i class="bx bxs-quote-alt-right quote-icon-right"></i> </p> <img src="assets/img/testimonials/testimonials-2.jpg" class="testimonial-img" alt="" /> <h3>Sara Wilsson</h3> <h4>Designer</h4> </div> </div> --> <!-- End testimonial item --> <!-- <div class="swiper-slide"> <div class="testimonial-item" data-aos="fade-up" data-aos-delay="200" > <p> <i class="bx bxs-quote-alt-left quote-icon-left"></i> Enim nisi quem export duis labore cillum quae magna enim sint quorum nulla quem veniam duis minim tempor labore quem eram duis noster aute amet eram fore quis sint minim. <i class="bx bxs-quote-alt-right quote-icon-right"></i> </p> <img src="assets/img/testimonials/testimonials-3.jpg" class="testimonial-img" alt="" /> <h3>Jena Karlis</h3> <h4>Store Owner</h4> </div> </div> --> <!-- End testimonial item --> <!-- <div class="swiper-slide"> <div class="testimonial-item" data-aos="fade-up" data-aos-delay="300" > <p> <i class="bx bxs-quote-alt-left quote-icon-left"></i> Fugiat enim eram quae cillum dolore dolor amet nulla culpa multos export minim fugiat minim velit minim dolor enim duis veniam ipsum anim magna sunt elit fore quem dolore labore illum veniam. <i class="bx bxs-quote-alt-right quote-icon-right"></i> </p> <img src="assets/img/testimonials/testimonials-4.jpg" class="testimonial-img" alt="" /> <h3>Matt Brandon</h3> <h4>Freelancer</h4> </div> </div> --> <!-- End testimonial item --> <!-- <div class="swiper-slide"> <div class="testimonial-item" data-aos="fade-up" data-aos-delay="400" > <p> <i class="bx bxs-quote-alt-left quote-icon-left"></i> Quis quorum aliqua sint quem legam fore sunt eram irure aliqua veniam tempor noster veniam enim culpa labore duis sunt culpa nulla illum cillum fugiat legam esse veniam culpa fore nisi cillum quid. <i class="bx bxs-quote-alt-right quote-icon-right"></i> </p> <img src="assets/img/testimonials/testimonials-5.jpg" class="testimonial-img" alt="" /> <h3>John Larson</h3> <h4>Entrepreneur</h4> </div> </div> --> <!-- End testimonial item --> <!-- </div> <div class="swiper-pagination"></div> </div> </div> </section> --> <!-- End Testimonials Section --> <!-- ======= Contact Section ======= --> <section id="contact" class="contact"> <div class="container"> <div class="section-title"> <h2>Contact</h2> <p></p> </div> <div class="row" data-aos="fade-in"> <div class="col-lg-12 d-flex align-items-stretch"> <div class="info"> <div class="address"> <i class="bi bi-geo-alt"></i> <h4>Location:</h4> <p>Karimannoor,Thodupuzha,Idukki</p> </div> <div class="email" > <i class="bi bi-envelope"></i> <h4>Email:</h4> <p>[email protected]</p> </div> <div class="phone"> <i class="bi bi-phone"></i> <h4>Call:</h4> <p>+91 8157845851</p> </div> <!-- <iframe src="https://www.google.com/maps/embed?pb=!1m18!1m12!1m3!1d125773.62416972195!2d76.57313122176646!3d9.898453128849255!2m3!1f0!2f0!3f0!3m2!1i1024!2i768!4f13.1!3m3!1m2!1s0x3b07c40a315b6705%3A0x4a8f3d2b78b03d27!2sThodupuzha%2C%20Kerala!5e0!3m2!1sen!2sin!4v1700907243389!5m2!1sen!2sin" width="840" height="250" style="border: 0" allowfullscreen="" loading="lazy" referrerpolicy="no-referrer-when-downgrade" ></iframe> --> </div> </div> <!-- <div class="col-lg-7 mt-5 mt-lg-0 d-flex align-items-stretch"> <form action="forms/contact.php" method="post" role="form" class="php-email-form" > <div class="row"> <div class="form-group col-md-6"> <label for="name">Your Name</label> <input type="text" name="name" class="form-control" id="name" required /> </div> <div class="form-group col-md-6"> <label for="name">Your Email</label> <input type="email" class="form-control" name="email" id="email" required /> </div> </div> <div class="form-group"> <label for="name">Subject</label> <input type="text" class="form-control" name="subject" id="subject" required /> </div> <div class="form-group"> <label for="name">Message</label> <textarea class="form-control" name="message" rows="10" required ></textarea> </div> <div class="my-3"> <div class="loading">Loading</div> <div class="error-message"></div> <div class="sent-message"> Your message has been sent. Thank you! </div> </div> <div class="text-center"> <button type="submit">Send Message</button> </div> </form> </div> --> </div> </div> </section> <!-- End Contact Section --> </main> <!-- End #main --> <!-- ======= Footer ======= --> <!-- <footer id="footer"> <div class="container"> <div class="copyright"> &copy; Copyright <strong><span>iPortfolio</span></strong> </div> <div class="credits"> --> <!-- All the links in the footer should remain intact. --> <!-- You can delete the links only if you purchased the pro version. --> <!-- Licensing information: https://bootstrapmade.com/license/ --> <!-- Purchase the pro version with working PHP/AJAX contact form: https://bootstrapmade.com/iportfolio-bootstrap-portfolio-websites-template/ --> <!-- Designed by <a href="https://bootstrapmade.com/">BootstrapMade</a> </div> </div> </footer> --> <!-- End Footer --> <a href="#" class="back-to-top d-flex align-items-center justify-content-center" ><i class="bi bi-arrow-up-short"></i ></a> <!-- Vendor JS Files --> <script src="assets/vendor/purecounter/purecounter_vanilla.js"></script> <script src="assets/vendor/aos/aos.js"></script> <script src="assets/vendor/bootstrap/js/bootstrap.bundle.min.js"></script> <script src="assets/vendor/glightbox/js/glightbox.min.js"></script> <script src="assets/vendor/isotope-layout/isotope.pkgd.min.js"></script> <script src="assets/vendor/swiper/swiper-bundle.min.js"></script> <script src="assets/vendor/typed.js/typed.umd.js"></script> <script src="assets/vendor/waypoints/noframework.waypoints.js"></script> <script src="assets/vendor/php-email-form/validate.js"></script> <!-- Template Main JS File --> <script src="assets/js/main.js"></script> </body> </html>
import os import re import time from random import randint from src.custom_types import Action from selenium import webdriver from selenium.webdriver.chrome.options import Options from selenium.webdriver.remote.webelement import WebElement from selenium.webdriver.support.ui import WebDriverWait from selenium.common.exceptions import TimeoutException, ElementNotInteractableException, NoSuchElementException from selenium.webdriver.support import expected_conditions as EC from src.services.actions import Actions from selenium.webdriver.common.keys import Keys from selenium.webdriver.common.by import By from webdriver_manager.chrome import ChromeDriverManager from selenium.webdriver.support.select import Select from src.utils import Utils from string import Template import time import logging class Chrome: driver = "" element = "" action_chains = "" url_list = [] last_key = "" variables = {} errors = [] skip_conditions = [] def __init__(self, variables: dict): logging.basicConfig( level=logging.INFO, format="%(asctime)s | [%(name)s - %(levelname)s] | %(message)s", datefmt="%Y-%m-%d %H:%M:%S", ) self.logger = logging.getLogger("Chrome") chrome_options = Options() # chrome_options.binary_location = os.environ.get("GOOGLE_CHROME_BIN") chrome_options.add_argument("--no-sandbox") #bypass OS security model chrome_options.add_argument("--disable-gpu") chrome_options.add_argument("--disable-dev-shm-usage") #overcome limited resource problems chrome_options.add_experimental_option("detach", True) chrome_options.add_argument("--disable-extensions") chrome_options.add_argument("disable-infobars") chrome_options.add_argument("--disable-plugins-discovery") chrome_options.add_argument("--disable-blink-features=AutomationControlled") chrome_options.add_argument("--start-maximized") chrome_options.add_argument('window-size=1920x1480') chrome_options.add_experimental_option("excludeSwitches", ["enable-automation"]) chrome_options.add_experimental_option("useAutomationExtension", False) user_agent = "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/60.0.3112.50 Safari/537.36" chrome_options.add_argument(f"user-agent={user_agent}") # chrome_options.add_argument("headless") self.driver = webdriver.Chrome(ChromeDriverManager().install(), options=chrome_options) self.logger.info("Selenium initialized") self.driver.maximize_window() self.variables = variables def is_open(self, website): try: url = self.get_current_url() website = website.replace("https://", "") website = website.replace("http://", "") website = website.replace("www.", "") return website in url except: return False def open(self, website): if isinstance(self.driver, webdriver.Chrome): if not self.is_open(website): self.logger.info('Opening website: {}'.format(website)) self.driver.get(website) else: self.logger.error("Driver instance not defined or misstyped") def get_element_and_add_actions(self, key_type: str, key: str, action: Action, step: str): try: if "$" in key: # variable_key = re.findall(r"\$\w+", "//button[@aria-label='$size' i]")[0].replace("$", "") variable_key = re.findall(r"\$\w+", key)[0].replace("$", "") variable_value = self.variables.get(variable_key) key = Utils.replace_variable_in_sentence( sentence=key, variable_key=variable_key, variable_value=variable_value ) if key_type == 'SCREENSHOT': # save screenshot with today`s date and time as in a clients folder client_name = self.variables.get('name') or 'unknown' self.driver.save_screenshot(f"{client_name.split(' ')[0]}-{time.strftime('%Y-%m-%d')}-{time.strftime('%H-%M-%S')}-{key}.png") return elif not self.element or self.last_key != key: self.logger.info(f"Searching for element with {key_type}={key}...") self.element: WebElement = WebDriverWait(self.driver, 10).until( EC.presence_of_element_located(locator=(key_type.lower(), key)) ) self.logger.info(f"Element found: {self.element.tag_name}") self.action_chains = Actions(self.driver) self.last_key = key if(self.element): self.append_action(action) else: self.errors.append(step) except NotImplementedError as error: self.logger.error(f"Fatal error in get_element_and_act: {error}") self.errors.append(step) except TimeoutException: if step == 'verificando se existe endereço cadastrado': return self.logger.error(f"Cannot find element with {key_type}={key}") if not action.get('type') == 'conditional': self.errors.append(step) except Exception as error: self.logger.error(f"Fatal error in get_element_and_act: {error}") self.errors.append(step) def has_error_in_step(self, step: str): return step in self.errors def append_action(self, action: Action): action_type = action.get("type") action_params = action.get("params") action_value = action_params.get("value") self.driver.implicitly_wait(10) # seconds try: if action_value and "$" in action_value: variable_key = action_value.replace("$", "") variable_value = self.variables.get(variable_key) action_value = Utils.replace_variable_in_sentence( sentence=action_value, variable_key=variable_key, variable_value=variable_value ) if action_params.get('register_skip_condition'): self.skip_conditions.append(action_params.get('register_skip_condition')) if action_type == "click": self.action_chains.move_to_element(self.element) self.action_chains.click(on_element=self.element) time.sleep(2) elif action_type == "select": select_object = Select(self.element) if action_params.get('by') != None and action_params.get('by') == "visible_text": select_object.select_by_visible_text(action_value) else: select_object.select_by_value(action_value) elif action_type == "send_keys": self.logger.info(f"Sending keys: {action_value}") self.action_chains.move_to_element(self.element) self.action_chains.click(on_element=self.element) if action_value != self.element.text and action_params.get('override') != 'bypass': self.action_chains.send_keys(action_value) elif action_type == "keyboard": action = Utils.get_function_from(Keys, action_params.get("value")) self.action_chains.move_to_element(self.element) self.action_chains.send_keys(action) elif action_type == "hover": self.action_chains.move_to_element(self.element) elif action_type == "continue": self.logger.info(f"Continuing with next step") except ElementNotInteractableException as not_interactable_err: self.driver.execute_script("arguments[0].scrollIntoView(true);", self.element); self.action_chains.click(on_element=self.element) except Exception as error: self.logger.exception(f"Fatal error in append_action: {error}") self.end_connection() def perform_actions(self): if type(self.action_chains) is Actions: self.action_chains.perform() def end_connection(self): self.skip_conditions = [] self.errors = [] self.driver.close() self.driver.quit() def get_current_url(self): time.sleep(1) return self.driver.current_url def get_current_page_title(self): time.sleep(1) return self.driver.title
/// <reference types="cypress" /> // Pages Import import LoginPage from "../../support/pages/loginPage" import RecruitmentPage from "../../support/pages/recruitmentPage" // Test-data Import import credentials from '../../fixtures/credentials.json' describe('TSR-001 : Smoke Test Recruitment Page', () => { beforeEach(() => { cy.session('AdminLogin', () => { cy.visit('/auth/login') LoginPage.typeUsername(credentials.allowedUser.username) LoginPage.typePassword(credentials.allowedUser.password) LoginPage.clickLoginButton() }) }) it('TCR-001 : Number of candidates retrieved by the api are displayed in the table', () => { let numberOfRecordsRetrieved cy.intercept('GET', (Cypress.env('backend_url')+'/recruitment/candidates?*')).as('getCandidates') cy.visit('/recruitment/viewCandidates') cy.wait('@getCandidates') .then(res => { expect(res.response.statusCode).to.be.eq(200) numberOfRecordsRetrieved = res.response.body.meta.total RecruitmentPage.areRecordsFound(numberOfRecordsRetrieved) }) }) it('TCR-002 : The "+ Add" button redirects the user to the Add Candidate form', () => { cy.visit('/recruitment/viewCandidates') RecruitmentPage.clickAddCandidateButton() cy.isLocatedAt('/recruitment/addCandidate') }) it('TCR-003 : The user clicks on the eye action icon and is redirected to the candidate detail page', () => { cy.visit('/recruitment/viewCandidates') RecruitmentPage.clickEyeActionButton() cy.isLocatedAtDinamic('/recruitment/addCandidate/') }) it('TCR-004 : The user clicks on the delete action icon and a pop-up is displayed', () => { cy.visit('/recruitment/viewCandidates') RecruitmentPage.clickDeleteActionButton() RecruitmentPage.isDeletePopUpBody('The selected record will be permanently deleted. Are you sure you want to continue?') RecruitmentPage.isDeletePopUpCancelButtonDisplayed() RecruitmentPage.isDeletePopUpDeleteButtonDisplayed() }) it('TCR-005 : The user deletes a candidate and a DELETE request is sent', () => { cy.visit('/recruitment/viewCandidates') RecruitmentPage.clickDeleteActionButton() cy.intercept('DELETE', (Cypress.env('backend_url')+'/recruitment/candidates')).as('deleteCandidate') RecruitmentPage.clickDeletePopUpDeleteButton() cy.wait('@deleteCandidate') .then(res => { expect(res.request.body.ids).to.be.not.undefined expect(res.response.statusCode).to.be.eq(200) }) }) it('TCR-006 : The user clicks on the download action icon and a .PDF file is downloaded', () => { cy.intercept('GET', (Cypress.env('backend_url')+'/recruitment/candidates?*')).as('getCandidates') cy.visit('/recruitment/viewCandidates') //RecruitmentPage.clickDownloadActionButton() // Workaround to download file because the button cy.wait('@getCandidates') .then(res => { for(let i = 0 ; i < res.response.body.meta.total ; i++){ if(res.response.body.data[i].hasAttachment === 'True'){ cy.request('GET', (Cypress.env('backend_url')+'/recruitment/viewCandidateAttachment/candidateId/'+res.response.body.data[i].id)) } } }) // Workaround to download file because the button RecruitmentPage.wasTheResumeDownloaded() }) it('TCR-007 : The user filters candidates by status', () => { cy.intercept('GET', (Cypress.env('backend_url')+'/recruitment/candidates?*')).as('getCandidates') cy.visit('/recruitment/viewCandidates') cy.wait('@getCandidates') RecruitmentPage.clickStatusDropdown() RecruitmentPage.clickStatusDropdownItem('Interview Passed') cy.intercept('GET', (Cypress.env('backend_url')+'/recruitment/candidates?*')).as('getCandidates') RecruitmentPage.clickSearchButton() cy.wait('@getCandidates') .then(res => { // status 5 = Interview Passed expect(res.request.url).contain('status=5') }) }) it('TCR-008 : The user navigates to the "Vacancies" tab, and the vacancies are retrieved with the data to complete the table', () => { cy.visit('/recruitment/viewCandidates') cy.intercept('GET', (Cypress.env('backend_url')+'/recruitment/vacancies?limit*')).as('getVacancies') RecruitmentPage.clickVacanciesTab() cy.wait('@getVacancies') .then(res => { expect(res.response.statusCode).to.be.eq(200) expect(res.response.body.data[0].id).to.be.not.undefined expect(res.response.body.data[0].name).to.be.not.undefined expect(res.response.body.data[0].status).to.be.not.undefined expect(res.response.body.data[0].jobTitle.title).to.be.not.undefined expect(res.response.body.data[0].hiringManager).to.be.not.undefined }) }) })
import { BrowserModule } from '@angular/platform-browser'; import { NgModule } from '@angular/core'; import { HttpModule } from '@angular/http'; import { FormsModule} from '@angular/forms'; // import { FontAwesomeModule } from '@fortawesome/fontawesome-free'; import { UsersService } from './services/users.service'; // Usamos para entrar con Facebook y Gmail // import { // SocialLoginModule, // AuthServiceConfig, // GoogleLoginProvider, // FacebookLoginProvider, // } from "angular5-social-login"; import { AppComponent } from './app.component'; import { UsersComponent } from './componentes/users/users.component'; import { HomeComponent } from './pagina/home/home.component'; import { LoginComponent } from './pagina/login/login.component'; import { AppRoutingModule } from './/app-routing.module'; import { LoginHomeComponent } from './pagina/login/login-home.component'; // export function getAuthServiceConfigs() { // let config = new AuthServiceConfig( // [ // { // id: FacebookLoginProvider.PROVIDER_ID, // provider: new FacebookLoginProvider("Your-Facebook-app-id") // }, // { // id: GoogleLoginProvider.PROVIDER_ID, // provider: new GoogleLoginProvider("Your-Google-Client-Id") // } // ] // ) // return config; // } @NgModule({ declarations: [ AppComponent, UsersComponent, HomeComponent, LoginComponent, LoginHomeComponent ], imports: [ BrowserModule, HttpModule, FormsModule, AppRoutingModule, // SocialLoginModule // FontAwesomeModule ], providers: [ UsersService // { // provide: AuthServiceConfig, // useFactory: getAuthServiceConfigs // } ], bootstrap: [AppComponent] }) export class AppModule { }
#include <stdio.h> #include "lib.h" #include "m.h" #include "symtable.h" void symtable_test_0(void) { struct symtable *symtable = symtable_new(); assert_neq(symtable, NULL); symtable_free(symtable); } void symtable_test_1(void) { struct symtable *symtable = symtable_new(); symtable_insert(symtable, "a"); symtable_insert(symtable, "b"); int level; assert_neq(symtable_lookup(symtable, "a", &level), NULL); assert_eq(level, 0); assert_neq(symtable_lookup(symtable, "b", &level), NULL); assert_eq(level, 0); symtable_enter_scope(symtable); symtable_insert(symtable, "c"); symtable_insert(symtable, "d"); assert_neq(symtable_lookup(symtable, "a", &level), NULL); assert_eq(level, 0); assert_neq(symtable_lookup(symtable, "b", &level), NULL); assert_eq(level, 0); assert_neq(symtable_lookup(symtable, "c", &level), NULL); assert_eq(level, 1); assert_neq(symtable_lookup(symtable, "d", &level), NULL); assert_eq(level, 1); symtable_leave_scope(symtable); symtable_insert(symtable, "e"); symtable_insert(symtable, "f"); assert_neq(symtable_lookup(symtable, "a", &level), NULL); assert_eq(level, 0); assert_neq(symtable_lookup(symtable, "b", &level), NULL); assert_eq(level, 0); assert_neq(symtable_lookup(symtable, "e", &level), NULL); assert_eq(level, 0); assert_neq(symtable_lookup(symtable, "f", &level), NULL); assert_eq(level, 0); assert_eq(symtable_lookup(symtable, "c", &level), NULL); assert_eq(symtable_lookup(symtable, "d", &level), NULL); symtable_free(symtable); } void symtable_test_2(void) { struct symtable *symtable = symtable_new(); struct symnode *node_a = symtable_insert(symtable, "a"); node_a->node_type = val_node; node_a->var_type = inttype; node_a->mem_addr_type = global; node_a->var_addr = 0; symtable_enter_scope(symtable); struct symnode *node_b = symtable_insert(symtable, "b"); node_b->node_type = val_node; node_b->var_type = inttype; node_b->mem_addr_type = off_fp; node_b->var_addr = 0; symtable_display(symtable); // to check if we have valid read/write assert_eq(symtable_lookup(symtable, "a", NULL), node_a); assert_eq(symtable_lookup(symtable, "b", NULL), node_b); symtable_leave_scope(symtable); assert_eq(symtable_lookup(symtable, "a", NULL), node_a); assert_eq(symtable_lookup(symtable, "b", NULL), NULL); symtable_free(symtable); } void symtable_test(void) { test_case(symtable_test_0); test_case(symtable_test_1); test_case(symtable_test_2); }
import React, { useContext } from 'react'; import { MainContext } from '../../Context/Main'; import axios from 'axios'; import { useNavigate } from "react-router-dom"; const Login = () => { const { BASEURL, ADMIN_BASEURL, notify, admin, setAdmin, token, setToken } = useContext(MainContext); const navigate = useNavigate(); if (admin != null) { navigate("/admin"); } const loginHandler = (event) => { event.preventDefault(); const data = { email: event.target.email.value, password: event.target.password.value, } axios.post(BASEURL + ADMIN_BASEURL + "/login", data) .then( (success) => { if (success.data.status == 1) { setToken(success.data.token) const adminData = { name: success.data.admin.name, id: success.data.admin._id }; setAdmin(adminData) localStorage.setItem("admin", JSON.stringify(adminData)); localStorage.setItem("token", JSON.stringify(success.data.token)); navigate("/admin"); } else { } } ).catch( (error) => { console.log(error) } ) } return ( <section className="bg-gray-50 dark:bg-gray-900"> <div className="flex flex-col items-center justify-center px-6 py-8 mx-auto md:h-screen lg:py-0"> <div className="w-full rounded-lg shadow dark:border md:mt-0 sm:max-w-md xl:p-0 dark:bg-gray-800 dark:border-gray-700"> <div className="p-6 space-y-4 md:space-y-6 sm:p-8"> <h1 className="text-xl font-bold leading-tight tracking-tight text-gray-900 md:text-2xl "> Sign in to your account </h1> <form className="space-y-4 md:space-y-6" onSubmit={loginHandler}> <div> <label htmlFor="email" className="block mb-2 text-sm font-medium text-gray-900 ">Your email</label> <input type="email" name="email" id="email" className="bg-gray-50 border border-gray-300 text-gray-900 sm:text-sm rounded-lg focus:ring-primary-600 focus:border-primary-600 block w-full p-2.5 dark:bg-gray-700 dark:border-gray-600 dark:placeholder-gray-400 dark:focus:ring-blue-500 dark:focus:border-blue-500" placeholder="[email protected]" required="" /> </div> <div> <label htmlFor="password" className="block mb-2 text-sm font-medium text-gray-900 ">Password</label> <input type="text" name="password" id="password" placeholder="••••••••" className="bg-gray-50 border border-gray-300 text-gray-900 sm:text-sm rounded-lg focus:ring-primary-600 focus:border-primary-600 block w-full p-2.5 dark:bg-gray-700 dark:border-gray-600 dark:placeholder-gray-400 dark:focus:ring-blue-500 dark:focus:border-blue-500" required="" /> </div> <div className="flex items-center justify-between"> <div className="flex items-start"> <div className="flex items-center h-5"> <input id="remember" aria-describedby="remember" type="checkbox" className="w-4 h-4 border border-gray-300 rounded bg-gray-50 focus:ring-3 focus:ring-primary-300 dark:bg-gray-700 dark:border-gray-600 dark:focus:ring-primary-600 dark:ring-offset-gray-800" required="" /> </div> <div className="ml-3 text-sm"> <label htmlFor="remember" className="text-gray-500 dark:text-gray-300">Remember me</label> </div> </div> <a href="#" className="text-sm font-medium text-primary-600 hover:underline dark:text-primary-500">Forgot password?</a> </div> <button type="submit" className="w-full bg-primary-600 hover:bg-primary-700 focus:ring-4 focus:outline-none focus:ring-primary-300 font-medium rounded-lg text-sm px-5 py-2.5 text-center dark:bg-primary-600 dark:hover:bg-primary-700 dark:focus:ring-primary-800 bg-blue-500 text-white">Sign in</button> <p className="text-sm font-light text-gray-500 dark:text-gray-400"> Don’t have an account yet? <a href="#" className="font-medium text-primary-600 hover:underline dark:text-primary-500">Sign up</a> </p> </form> </div> </div> </div> </section> ); } export default Login;
# include "merge.h" #include<stdio.h> void merge(struct WordFrequency arr[], int l, int m, int r) { int n1 = m - l + 1; int n2 = r - m; // Create temporary arrays struct WordFrequency L[n1], R[n2]; // Copy data to temporary arrays L[] and R[] for (int i = 0; i < n1; i++) L[i] = arr[l + i]; for (int j = 0; j < n2; j++) R[j] = arr[m + 1 + j]; // Merge the temporary arrays back into arr[l..r] int i = 0, j = 0, k = l; while (i < n1 && j < n2) { if (L[i].frequency > R[j].frequency) { arr[k++] = L[i++]; } else { arr[k++] = R[j++]; } } // Copy the remaining elements of L[], if there are any while (i < n1) { arr[k++] = L[i++]; } // Copy the remaining elements of R[], if there are any while (j < n2) { arr[k++] = R[j++]; } } // Merge sort function void mergeSort(struct WordFrequency arr[], int l, int r) { if (l < r) { int m = l + (r - l) / 2; // Sort first and second halves mergeSort(arr, l, m); mergeSort(arr, m + 1, r); // Merge the sorted halves merge(arr, l, m, r); } }
import { inject } from 'tsyringe'; import { Body, Files, GetMapping, PostMapping, PutMapping, Query, RestController, Session, } from '../decoratos/api/rest.api.decorator'; import { MovieService } from '../services/movie.service'; import { AllMoviesRequestDto } from '../dtos/req/movie/movie.all.req.dto'; import { PipeDto } from '../decoratos/api/pipe.decorator'; import { AppBaseResponseDto } from '../dtos/res/app.api.base.res.dto'; import { StatusEnum } from '../enum/status.enum'; import session from 'express-session'; import { UserRole } from '../enum/user.enum'; import { Category } from '../entities/category.entity'; import { MultiPart, MultiParts } from '../decoratos/api/multipart.decorator'; import { CSRFProtection } from '../decoratos/api/guards/guard.csrf.decorator'; import { ImageFilesGuard } from '../decoratos/api/guards/guard.image.file.decorator'; import { AdminAuth } from '../decoratos/api/guards/guard.admin.auth.decorator'; import { MovieSaveRequestDto, MovieUpdateRequestDto, } from '../dtos/req/movie/movie.save.req.dto'; @RestController('/api/movie') export class MovieRestController { constructor( @inject(MovieService) private readonly movieService: MovieService, ) {} @GetMapping('/') public async getAllMoviesWithPagination( @Query(null, PipeDto(AllMoviesRequestDto)) allMoviesRequestDto: AllMoviesRequestDto, @Session() session: session.Session & Partial<session.SessionData>, ) { const adminRequest = session?.['user']?.role == UserRole.ADMIN ? true : false; const pagination = await this.movieService.getMoivesWithPagination( allMoviesRequestDto.page, allMoviesRequestDto.name, allMoviesRequestDto.categoryIds, allMoviesRequestDto.age, adminRequest, ); if (session?.['user']?.role == UserRole.ADMIN) { return { message: 'OK', status: StatusEnum.OK, data: pagination ? { ...pagination, items: pagination.items.map((item) => { const { createdAt, updatedAt, ...rest } = item; rest.categories = rest.categories.map((category) => { const { createdAt, updatedAt, ...categoryRest } = category; return categoryRest as Category; }); return rest; }), } : null, } as AppBaseResponseDto; } return { message: 'OK', status: StatusEnum.OK, data: pagination ? { ...pagination, items: pagination.items.map((item) => { return { id: item.id, name: item.name, smallImgurl: item.smallImgurl, shortDescription: item.shortDescription, }; }), } : null, } as AppBaseResponseDto; } @AdminAuth() @MultiParts({ fields: [ { name: 'largeImgurl', maxCount: 1 }, { name: 'smallImgurl', maxCount: 1 }, ], }) @CSRFProtection() @ImageFilesGuard() @PostMapping('/') public async create( @Body(null, PipeDto(MovieSaveRequestDto)) movieSaveRequestDto: MovieSaveRequestDto, @Files('largeImgurl') largeImgurl: Express.Multer.File, @Files('smallImgurl') smallImgurl: Express.Multer.File, ) { return this.movieService.save( movieSaveRequestDto, largeImgurl?.[0], smallImgurl?.[0], ); } @AdminAuth() @MultiParts({ fields: [ { name: 'largeImgurl', maxCount: 1 }, { name: 'smallImgurl', maxCount: 1 }, ], }) @CSRFProtection() @ImageFilesGuard() @PutMapping('/') public async update( @Body(null, PipeDto(MovieUpdateRequestDto)) movieUpdateRequestDto: MovieUpdateRequestDto, @Files('largeImgurl') largeImgurl: Express.Multer.File, @Files('smallImgurl') smallImgurl: Express.Multer.File, ) { return this.movieService.save( movieUpdateRequestDto, largeImgurl?.[0], smallImgurl?.[0], ); } }
{{unreferenced|time=2015-05-14T02:40:58+00:00}} '''流速''',是[[流体|流体]]的流动[[速度|速度]]。当流速很小时,流体分层流动,互不混合,称为[[层流|层流]],或称为片流;逐渐增加流速,流体的流线开始出现波浪状的摆动,摆动的频率及振幅随流速的增加而增加,此种流况称为[[过渡流|过渡流]];当流速增加到很大时,流线不再清楚可辨,流场中有许多小漩涡,称为[[湍流|湍流]],又称为乱流、扰流或紊流。 这种变化可以用[[雷诺数|雷诺数]]来量化。雷诺数较小时,黏滞力对流场的影响大于惯性力,流场中流速的扰动会因黏滞力而衰减,流体流动稳定,为层流;反之,若雷诺数较大时,惯性力对流场的影响大于黏滞力,流体流动较不稳定,流速的微小变化容易发展、增强,形成紊乱、不规则的湍流流场。 ==流速测定== 根据不同情况和要求,可以采用不同的方法和仪器进行量测,常用的方法和仪器如下。 * [[皮托管|皮托管]]:1732年由法国工程师H.皮托首创,至今仍是实验室内测量时均点流速的常用仪器。 * 旋桨(杯)式流速仪:有多种形式,可用于现场及实验室,都有一组可旋转的叶片,受水流冲击后的叶片转数与流速有一固定关系,可通过率定求得。采用适当装置将转数化为电讯号予以记录显示。 * 激光测速仪:最大优点是对所测流场无干扰。 * 热丝(膜)流速仪:可测瞬时流速、脉动流速及紊流流速的随机变化过程。 * 摄影法:根据曝光时间及亮点迹线长度推算流速。  [[Category:流体力学|Category:流体力学]] [[Category:速度|Category:速度]]
using System; using System.Collections.Generic; using System.Linq; using Autodesk.Revit.DB; using dosymep.Bim4Everyone; using dosymep.Bim4Everyone.SystemParams; using dosymep.Revit; using dosymep.Revit.Geometry; using RevitClashDetective.Models.Extensions; using RevitOpeningPlacement.Models; using RevitOpeningPlacement.Models.Extensions; using RevitOpeningPlacement.Models.Interfaces; using RevitOpeningPlacement.OpeningModels.Enums; namespace RevitOpeningPlacement.OpeningModels { /// <summary> /// Класс, обозначающий экземпляры семейств заданий на отверстия из связанного файла-задания на отверстия, /// подгруженного в текущий документ получателя /// </summary> internal class OpeningMepTaskIncoming : IOpeningTaskIncoming, IEquatable<OpeningMepTaskIncoming>, IFamilyInstanceProvider { /// <summary> /// Экземпляр семейства задания на отверстие из связанного файла /// </summary> private readonly FamilyInstance _familyInstance; /// <summary> /// Репозиторий текущего документа, в который подгружен связанный документ с заданиями на отверстия /// </summary> private readonly RevitRepository _revitRepository; /// <summary> /// Экземпляр семейства задания на отверстие, расположенного в связанном файле задания на отверстия /// /// <para>Примечание: конструктор не обновляет свойства <see cref="Status"/>, <see cref="HostName"/> и <see cref="Host"/>. Для обновления этих свойств надо вызвать <see cref="UpdateStatusAndHostName"/></para> /// </summary> /// <param name="openingTaskIncoming">Экземпляр семейства задания на отверстие из связанного файла</param> /// <param name="revitRepository">Репозиторий текущего документа, в который подгружен документ с заданиями на отверстия</param> /// <param name="transform">Трансформация связанного файла, в котором создано задание на отверстие</param> public OpeningMepTaskIncoming(FamilyInstance openingTaskIncoming, RevitRepository revitRepository, Transform transform) { if(openingTaskIncoming is null) { throw new ArgumentNullException(nameof(openingTaskIncoming)); } _familyInstance = openingTaskIncoming; _revitRepository = revitRepository; Id = _familyInstance.Id; Transform = transform; Location = Transform.OfPoint((_familyInstance.Location as LocationPoint).Point); // https://forums.autodesk.com/t5/revit-api-forum/get-angle-from-transform-basisx-basisy-and-basisz/td-p/5326059 Rotation = (_familyInstance.Location as LocationPoint).Rotation + Transform.BasisX.AngleOnPlaneTo(Transform.OfVector(Transform.BasisX), Transform.BasisZ); FileName = _familyInstance.Document.PathName; OpeningType = RevitRepository.GetOpeningType(openingTaskIncoming.Symbol.Family.Name); Date = GetFamilyInstanceStringParamValueOrEmpty(RevitRepository.OpeningDate); MepSystem = GetFamilyInstanceStringParamValueOrEmpty(RevitRepository.OpeningMepSystem); Description = GetFamilyInstanceStringParamValueOrEmpty(RevitRepository.OpeningDescription); CenterOffset = GetFamilyInstanceStringParamValueOrEmpty(RevitRepository.OpeningOffsetCenter); BottomOffset = GetFamilyInstanceStringParamValueOrEmpty(RevitRepository.OpeningOffsetBottom); DisplayDiameter = GetFamilyInstanceStringParamValueOrEmpty(RevitRepository.OpeningDiameter); DisplayHeight = GetFamilyInstanceStringParamValueOrEmpty(RevitRepository.OpeningHeight); DisplayWidth = GetFamilyInstanceStringParamValueOrEmpty(RevitRepository.OpeningWidth); DisplayThickness = GetFamilyInstanceStringParamValueOrEmpty(RevitRepository.OpeningThickness); Comment = _familyInstance.GetParamValueStringOrDefault( SystemParamsConfig.Instance.CreateRevitParam( _familyInstance.Document, BuiltInParameter.ALL_MODEL_INSTANCE_COMMENTS), string.Empty); Username = GetFamilyInstanceStringParamValueOrEmpty(RevitRepository.OpeningAuthor); Diameter = GetFamilyInstanceDoubleParamValueOrZero(RevitRepository.OpeningDiameter); Height = GetFamilyInstanceDoubleParamValueOrZero(RevitRepository.OpeningHeight); Width = GetFamilyInstanceDoubleParamValueOrZero(RevitRepository.OpeningWidth); Thickness = GetFamilyInstanceDoubleParamValueOrZero(RevitRepository.OpeningThickness); string[] famNameParts = _familyInstance.Symbol.FamilyName.Split('_'); if(famNameParts.Length > 0) { FamilyShortName = famNameParts.Last(); } } public string FileName { get; } /// <summary> /// Id экземпляра семейства задания на отверстие /// </summary> public ElementId Id { get; } /// <summary> /// Точка расположения экземпляра семейства входящего задания на отверстие в координатах активного документа - получателя заданий /// </summary> public XYZ Location { get; } public string Date { get; } = string.Empty; public string MepSystem { get; } = string.Empty; public string Description { get; } = string.Empty; public string CenterOffset { get; } = string.Empty; public string BottomOffset { get; } = string.Empty; /// <summary> /// Значение диаметра в мм. Если диаметра у отверстия нет, будет пустая строка. /// </summary> public string DisplayDiameter { get; } = string.Empty; /// <summary> /// Значение ширины в мм. Если ширины у отверстия нет, будет пустая строка. /// </summary> public string DisplayWidth { get; } = string.Empty; /// <summary> /// Значение высоты в мм. Если высоты у отверстия нет, будет пустая строка. /// </summary> public string DisplayHeight { get; } = string.Empty; /// <summary> /// Значение толщины в мм. Если толщины у отверстия нет, будет пустая строка. /// </summary> public string DisplayThickness { get; } = string.Empty; /// <summary> /// Диаметр в единицах ревита или 0, если диаметра нет /// </summary> public double Diameter { get; } = 0; /// <summary> /// Ширина в единицах ревита или 0, если ширины нет /// </summary> public double Width { get; } = 0; /// <summary> /// Высота в единицах ревита или 0, если высоты нет /// </summary> public double Height { get; } = 0; /// <summary> /// Толщина в единицах ревита или 0, если толщины нет /// </summary> public double Thickness { get; } = 0; /// <summary> /// Трансформация связанного файла с заданием на отверстие относительно активного документа - получателя заданий /// </summary> public Transform Transform { get; } = Transform.Identity; /// <summary> /// Короткое обозначение семейства задания на отверстие /// </summary> public string FamilyShortName { get; } = string.Empty; /// <summary> /// Название элемента, в котором расположено задание на отверстие. Предназначено для дальнейшей сортировки входящих заданий в навигаторе по типам стен: штукатурка/монолит/кладка и т.п. /// <para>Для обновления использовать <see cref="UpdateStatusAndHostName"/></para> /// </summary> public string HostName { get; private set; } = string.Empty; /// <summary> /// Элемент из активного документа, в котором расположено задание на отверстие из связи. /// <para>Для обновления использовать <see cref="UpdateStatusAndHostName"/></para> /// </summary> public Element Host { get; private set; } = default; /// <summary> /// Комментарий экземпляра семейства задания на отверстие /// </summary> public string Comment { get; } = string.Empty; /// <summary> /// Имя пользователя, создавшего задание на отверстие /// </summary> public string Username { get; } = string.Empty; /// <summary> /// Статус отработки задания на отверстие /// <para>Для обновления использовать <see cref="UpdateStatusAndHostName"/></para> /// </summary> public OpeningTaskIncomingStatus Status { get; private set; } = OpeningTaskIncomingStatus.New; /// <summary> /// Тип проема /// </summary> public OpeningType OpeningType { get; } = OpeningType.WallRectangle; /// <summary> /// Угол поворота задания на отверстие в радианах в координатах активного файла, в который подгружена связь с заданием на отверстие /// </summary> public double Rotation { get; } = 0; public override bool Equals(object obj) { return (obj is OpeningMepTaskIncoming opening) && Equals(opening); } public override int GetHashCode() { return (int) Id.GetIdValue() + FileName.GetHashCode(); } public bool Equals(OpeningMepTaskIncoming other) { return (other != null) && (Id == other.Id) && FileName.Equals(other.FileName); } public FamilyInstance GetFamilyInstance() { return _familyInstance; } /// <summary> /// Возвращает солид входящего задания на отверстие в координатах активного файла - получателя заданий на отверстия /// </summary> /// <returns></returns> /// <exception cref="ArgumentException"></exception> public Solid GetSolid() { Solid famInstSolid = _familyInstance.GetSolid(); if(famInstSolid?.Volume > 0) { return SolidUtils.CreateTransformed(_familyInstance.GetSolid(), Transform); } else { throw new ArgumentException($"Не удалось обработать задание на отверстие с ID {Id} из файла \'{FileName}\'"); } } /// <summary> /// Возвращает BBox в координатах активного документа-получателя заданий на отверстия, в который подгружены связи с заданиями /// </summary> /// <returns></returns> public BoundingBoxXYZ GetTransformedBBoxXYZ() { // _familyInstance.GetBoundingBox().TransformBoundingBox(Transform); // при получении бокса сразу из экземпляра семейства // сначала строится бокс в координатах экземпляра семейства, // а потом строится описанный бокс в координатах проекта. // B = b*cos(a) + b*sin(a), где // (a) - угол поворота // (B) - сторона описанного бокса в координатах проекта // (b) - сторона вписанного бокса в координатах экземпляра семейства // Если семейство - вертикальный цилиндр, то это приведет к значительной погрешности. return GetSolid().GetTransformedBoundingBox(); } /// <summary> /// Обновляет <see cref="Status"/> и <see cref="HostName"/> входящего задания на отверстие /// </summary> /// <param name="realOpenings">Коллекция чистовых отверстий, размещенных в активном документе-получателе заданий на отверстия</param> /// <param name="constructureElementsIds">Коллекция элементов конструкций в активном документе-получателе заданий на отверстия</param> /// <exception cref="ArgumentException"></exception> public void UpdateStatusAndHostName(ICollection<IOpeningReal> realOpenings, ICollection<ElementId> constructureElementsIds) { var thisOpeningSolid = GetSolid(); var thisOpeningBBox = GetTransformedBBoxXYZ(); var intersectingStructureElements = GetIntersectingStructureElementsIds(thisOpeningSolid, constructureElementsIds); var intersectingOpenings = GetIntersectingOpeningsIds(realOpenings, thisOpeningSolid, thisOpeningBBox); var hostId = GetOpeningTaskHostId(thisOpeningSolid, intersectingStructureElements, intersectingOpenings); SetOpeningTaskHost(hostId); if((intersectingStructureElements.Count == 0) && (intersectingOpenings.Count == 0)) { Status = OpeningTaskIncomingStatus.NoIntersection; } else if((intersectingStructureElements.Count > 0) && (intersectingOpenings.Count == 0)) { Status = OpeningTaskIncomingStatus.New; } else if((intersectingStructureElements.Count > 0) && (intersectingOpenings.Count > 0)) { Status = OpeningTaskIncomingStatus.NotMatch; } else if((intersectingStructureElements.Count == 0) && (intersectingOpenings.Count > 0)) { Status = OpeningTaskIncomingStatus.Completed; } } /// <summary> /// Возвращает значение double параметра экземпляра семейства задания на отверстие в единицах ревита, или 0, если параметр отсутствует /// </summary> /// <param name="paramName">Название параметра</param> /// <returns></returns> private double GetFamilyInstanceDoubleParamValueOrZero(string paramName) { if(_familyInstance.GetParameters(paramName).FirstOrDefault(item => item.IsShared) != null) { return _familyInstance.GetSharedParamValue<double>(paramName); } else { return 0; } } /// <summary> /// Возвращает значение параметра, или пустую строку, если параметра у семейства нет. Значения параметров с типом данных "длина" конвертируются в мм и округляются до 1 мм. /// </summary> /// <param name="paramName"></param> /// <returns></returns> /// <exception cref="ArgumentNullException"></exception> private string GetFamilyInstanceStringParamValueOrEmpty(string paramName) { if(_familyInstance is null) { throw new ArgumentNullException(nameof(_familyInstance)); } string value = string.Empty; //if(_familyInstance.IsExistsSharedParam(paramName)) { if(_familyInstance.GetParameters(paramName).FirstOrDefault(item => item.IsShared) != null) { #if REVIT_2022_OR_GREATER if(_familyInstance.GetSharedParam(paramName).Definition.GetDataType() == SpecTypeId.Length) { return Math.Round(UnitUtils.ConvertFromInternalUnits(GetFamilyInstanceDoubleParamValueOrZero(paramName), UnitTypeId.Millimeters)).ToString(); } #elif REVIT_2021 if(_familyInstance.GetSharedParam(paramName).Definition.ParameterType == ParameterType.Length) { return Math.Round(UnitUtils.ConvertFromInternalUnits(GetFamilyInstanceDoubleParamValueOrZero(paramName), UnitTypeId.Millimeters)).ToString(); } #else if(_familyInstance.GetSharedParam(paramName).Definition.UnitType == UnitType.UT_Length) { return Math.Round(UnitUtils.ConvertFromInternalUnits(GetFamilyInstanceDoubleParamValueOrZero(paramName), DisplayUnitType.DUT_MILLIMETERS)).ToString(); } #endif object paramValue = _familyInstance.GetParamValue(paramName); if(!(paramValue is null)) { if(paramValue is double doubleValue) { value = Math.Round(doubleValue).ToString(); } else { value = paramValue.ToString(); } } } return value; } /// <summary> /// Возвращает коллекцию элементов конструкций, с которыми пересекается текущее задание на отверстие /// </summary> /// <param name="thisOpeningSolid">Солид текущего задания на отверстие в координатах активного файла - получателя заданий</param> /// <param name="constructureElementsIds">Коллекция id элементов конструкций из активного документа ревита, для которых были сделаны задания на отверстия</param> /// <returns></returns> private ICollection<ElementId> GetIntersectingStructureElementsIds(Solid thisOpeningSolid, ICollection<ElementId> constructureElementsIds) { if((thisOpeningSolid is null) || (thisOpeningSolid.Volume <= 0) || (!constructureElementsIds.Any())) { return Array.Empty<ElementId>(); } else { return new FilteredElementCollector(_revitRepository.Doc, constructureElementsIds) .WherePasses(new BoundingBoxIntersectsFilter(thisOpeningSolid.GetOutline())) .WherePasses(new ElementIntersectsSolidFilter(thisOpeningSolid)) .ToElementIds(); } } /// <summary> /// Возвращает коллекцию Id проемов из активного документа, которые пересекаются с текущим заданием на отверстие из связи /// </summary> /// <param name="realOpenings">Коллекция чистовых отверстий из активного документа ревита</param> /// <param name="thisOpeningSolid">Солид текущего задания на отверстие в координатах активного файла - получателя заданий</param> /// <param name="thisOpeningBBox">Бокс текущего задания на отверстие в координатах активного файла - получателя заданий</param> /// <returns></returns> private ICollection<ElementId> GetIntersectingOpeningsIds(ICollection<IOpeningReal> realOpenings, Solid thisOpeningSolid, BoundingBoxXYZ thisOpeningBBox) { if((thisOpeningSolid is null) || (thisOpeningSolid.Volume <= 0)) { return Array.Empty<ElementId>(); } else { // для ускорения поиск первого пересечения var opening = realOpenings.FirstOrDefault(realOpening => realOpening.IntersectsSolid(thisOpeningSolid, thisOpeningBBox)); if(opening != null) { return new ElementId[] { opening.Id }; } else { return Array.Empty<ElementId>(); } } } /// <summary> /// Возвращает Id элемента конструкции, который наиболее похож на хост для задания на отверстие. /// <para>Под наиболее подходящим понимается элемент конструкции, с которым пересечение наибольшего объема, либо хост чистового отверстия, с которым пересекается задание на отверстие.</para> /// </summary> /// <param name="thisOpeningSolid">Солид текущего задания на отверстие в координатах активного файла-получателя заданий</param> /// <param name="intersectingStructureElementsIds">Коллекция Id элементов конструкций из активного документа, с которыми пересекается задание на отверстие</param> /// <param name="intersectingOpeningsIds">Коллекция Id чистовых отверстий из активного документа, с которыми пересекается задание на отверсите</param> /// <returns></returns> private ElementId GetOpeningTaskHostId(Solid thisOpeningSolid, ICollection<ElementId> intersectingStructureElementsIds, ICollection<ElementId> intersectingOpeningsIds) { if((intersectingOpeningsIds != null) && intersectingOpeningsIds.Any()) { return (_revitRepository.GetElement(intersectingOpeningsIds.First()) as FamilyInstance)?.Host?.Id ?? ElementId.InvalidElementId; } else if((thisOpeningSolid != null) && (thisOpeningSolid.Volume > 0) && (intersectingStructureElementsIds != null) && intersectingStructureElementsIds.Any()) { // поиск элемента конструкции, с которым пересечение задания на отверстие имеет наибольший объем double halfOpeningVolume = thisOpeningSolid.Volume / 2; double intersectingVolumePrevious = 0; ElementId hostId = intersectingStructureElementsIds.First(); foreach(var structureElementId in intersectingStructureElementsIds) { var structureSolid = _revitRepository.GetElement(structureElementId)?.GetSolid(); if((structureSolid != null) && (structureSolid.Volume > 0)) { try { double intersectingVolumeCurrent = BooleanOperationsUtils.ExecuteBooleanOperation(thisOpeningSolid, structureSolid, BooleanOperationsType.Intersect)?.Volume ?? 0; if(intersectingVolumeCurrent >= halfOpeningVolume) { return structureElementId; } if(intersectingVolumeCurrent > intersectingVolumePrevious) { intersectingVolumePrevious = intersectingVolumeCurrent; hostId = structureElementId; } } catch(Autodesk.Revit.Exceptions.InvalidOperationException) { continue; } } } return hostId; } else { return ElementId.InvalidElementId; } } /// <summary> /// Записывает элемент и название хоста задания на отверстие соответственно в свойства <see cref="Host"/> и <see cref="HostName"/> /// </summary> /// <param name="hostId">Id хоста задания на отверстие из активного документа (стены/перекрытия)</param> private void SetOpeningTaskHost(ElementId hostId) { if(hostId != null) { Host = _revitRepository.GetElement(hostId); var name = Host?.Name; if(!string.IsNullOrWhiteSpace(name)) { HostName = name; } } } } }
#!/usr/bin/python3 """define the imported modules""" import models from uuid import uuid4 from datetime import datetime class BaseModel: """this is the base class""" def __init__(self, *args, **kwargs): """initializing function""" format = "%Y-%m-%dT%H:%M:%S.%f" self.id = str(uuid4()) self.created_at = datetime.today() self.updated_at = datetime.today() if len(kwargs) != 0: for key, value in kwargs.items(): if key == 'created_at' or key == 'updated_at': self.__dict__[key] = datetime.strptime(value, format) else: self.__dict__[key] = value else: models.storage.new(self) def __str__(self) -> str: """prints [<class name>] (<self.id>) <self.__dict__>""" return ("[{}] ({}) {}".format(self.__class__.__name__, self.id, self.__dict__)) def save(self): """ updates the public instance attribute updated_at with the current datetime """ self.updated_at = datetime.today() models.storage.save() def to_dict(self): """ returns a dictionary containing all keys/values of __dict__ of the instance """ dict = self.__dict__.copy() dict['created_at'] = self.created_at.isoformat() dict['updated_at'] = self.updated_at.isoformat() dict['__class__'] = self.__class__.__name__ return dict
### 解题思路 以每个bus_id为例 其能载客的总数等于所有小于该车始发时间的乘客总数 - 上一班载客总数 具体思路: 1. 先用左连接 得到每班bus及其之前bus的载客总数 2. 然后用IFNULL + lag 减去前行数(也就是上一班车搭载总人数) ### 代码 * mysql ```mysql # Write your MySQL query statement below SELECT bus_id, passenger_cnt_total - IFNULL(lag(passenger_cnt_total) over (order by arrival_time), 0) AS passengers_cnt FROM (SELECT bus_id, a.arrival_time, IFNULL(COUNT(DISTINCT passenger_id), 0) AS passenger_cnt_total FROM Buses a LEFT JOIN Passengers b ON b.arrival_time <= a.arrival_time GROUP BY bus_id ORDER BY a.arrival_time) c ORDER BY bus_id ```
# Warped::Controllers::Pageable The `Pageable` concern provides a method to paginate the records in a controller's action. The method `paginate` is used to paginate the records. It will use the query parameters `page` and `per_page` to paginate the records. ```ruby class UsersController < ApplicationController include Warped::Controllers::Pageable def index users = paginate(User.all) render json: users, meta: pagination end end ``` Request examples: ``` GET /users?page=1&per_page=10 # returns the first page of users with 10 records per page GET /users?per_page=25 # returns the first page of users with 25 records per page GET /users?page=2&per_page=25 # returns the second page of users with 25 records per page ``` ## Accessing the pagination information The `pagination` method can be used to access the pagination information. ```ruby class UsersController < ApplicationController include Warped::Controllers::Pageable def index users = paginate(User.all) render json: users, meta: pagination end end ``` `pagination` returns a hash with - `page` - the current page - `per_page` - the number of records per page - `total_pages` - the total number of pages - `total_count` - the number of records in the scope - `next-page` - the next page number - `prev-page` - the previous page number ## Customizing the pagination behavior By default, the `paginate` method will paginate the scope in pages of size 10, and will return the first page if the `page` query parameter is not provided. Additionally, there's a limit of `100` records per page. So, if the `per_page` query parameter is greater than `100`, the pagination will use `100` as the page size. You can customize the default page size and the default page number by overriding the `default_per_page` value in the controller. ```ruby class UsersController < ApplicationController include Warped::Controllers::Pageable # This will set the default page size to 25 when the `per_page` query parameter is not provided self.default_per_page = 25 def index users = paginate(User.all) render json: users, meta: pagination end end ```
//! Timing attack simulation for a device implementing some form of group operation //! not in constant time. //! //! For example, given a message `m` and a secret `d`, it can simulate: //! - m^d mod n using "square and multiply" //! - d·m mod n using "double and add" //! //! The secret is recovered using the //! [variance difference strategy](https://datawok.net/posts/timing-attack). //! //! It is a probabilistic attack in nature, so you may not be successfull on the //! first run. //! //! The execution times of group operations are not fixed but vary with the value //! of `m`. If `m` is chosen randomly, these times follow a Gaussian distribution //! with a configurable mean μ and standard deviation σ (with default μ = 1000 //! and σ = 50). use num_bigint::{BigUint, RandBigInt}; use rand::{Rng, SeedableRng}; use rand_chacha::ChaCha20Rng; use rand_distr::{Distribution, Normal}; use std::io::{self, Write}; use std::str::FromStr; fn get_modulus(keylen: u64) -> BigUint { match keylen { 8 => BigUint::from(61_u8), 16 => BigUint::from(53759_u16), 32 => BigUint::from(2675797811_u32), 64 => BigUint::from(8642890157798231327_u64), 128 => BigUint::from(249018405283997733407297959207515566297_u128), 256 => BigUint::from_str( "44836394558820158783687605622545866580915032641323282158738215690847176590297", ) .unwrap(), _ => panic!("Not supported keylen"), } } fn square_and_multiply(m: &BigUint, d: &BigUint, p: &BigUint) -> f64 { let mut res = BigUint::from(1u64); let mut delay = 0.0; let seed = m.iter_u64_digits().next().unwrap(); let mut rng = ChaCha20Rng::seed_from_u64(seed); let normal = Normal::new(1000.0, 50.0).unwrap(); let mut nbits = d.bits(); if nbits == 0 { nbits = 1 } for i in 1..=nbits { res = (res.pow(2)) % p; delay += normal.sample(&mut rng); if d.bit(nbits - i) { res = (res * m) % p; let seed = res.iter_u64_digits().next().unwrap(); let mut rng = ChaCha20Rng::seed_from_u64(seed); delay += normal.sample(&mut rng); } } delay } struct VictimDevice { modulus: BigUint, secret: BigUint, } impl VictimDevice { pub fn new(seed: u64, keylen: u64) -> Self { let mut rng = ChaCha20Rng::seed_from_u64(seed); let mut secret = rng.gen_biguint(keylen); secret.set_bit(keylen - 1, true); VictimDevice { modulus: get_modulus(keylen), secret, } } pub fn sign(&self, m: &BigUint) -> f64 { square_and_multiply(&m, &self.secret, &self.modulus) } } struct AttackerDevice { modulus: BigUint, } impl AttackerDevice { pub fn new(keylen: u64) -> Self { AttackerDevice { modulus: get_modulus(keylen), } } pub fn sign(&self, m: &BigUint, d: &BigUint) -> f64 { square_and_multiply(&m, d, &self.modulus) } } fn main() { let mut rng = rand::rngs::OsRng; // Key length in bits let keylen = 64; // The more bit is keylen the more bit this value should be... // E.g. 64 -> 1000, 128 -> 4000, 256 -> 10000 let variance_iters_count = 1000; let victim = VictimDevice::new(rng.gen(), keylen); let attacker = AttackerDevice::new(keylen); println!("secret : {:064b}", victim.secret); print!("recovered : "); // Recovered secret let mut recovered = BigUint::from(0_u64); for _ in 0..keylen { let mut sum0 = 0.0; let mut sum0_square = 0.0; let mut sum1 = 0.0; let mut sum1_square = 0.0; recovered <<= 1; for _ in 0..variance_iters_count { let m = rng.gen_biguint(keylen); let t_vic = victim.sign(&m); // Attempt with i-th bit = 0 recovered.set_bit(0, false); let t_att0 = attacker.sign(&m, &recovered); let delta0 = t_vic - t_att0; sum0 += delta0; sum0_square += delta0 * delta0; // Attempt with i-th bit = 1 recovered.set_bit(0, true); let t_att1 = attacker.sign(&m, &recovered); let delta1 = t_vic - t_att1; sum1 += delta1; sum1_square += delta1 * delta1; } let exp0 = sum0 / variance_iters_count as f64; let var0 = (sum0_square / variance_iters_count as f64) - exp0 * exp0; let exp1 = sum1 / variance_iters_count as f64; let var1 = (sum1_square / variance_iters_count as f64) - exp1 * exp1; if var0 < var1 { recovered.set_bit(0, false); print!("0") } else { recovered.set_bit(0, true); print!("1") } io::stdout().flush().unwrap(); } }
import Box from '@mui/material/Box'; import Grid from '@mui/material/Grid'; import SectionTitle from '../SectionTitle/SectionTitle'; import SkillCard from '../SkillCard/SkillCard'; const techIcons = [ { title: "JavaScript", img: require('../../assets/icons/icons8-javascript-96.png') }, { title: "TypeScript", img: require('../../assets/icons/icons8-typescript-48.png') }, { title: "React", img: require('../../assets/icons/icons8-react-a-javascript-library-for-building-user-interfaces-96.png') }, { title: "HTML", img: require('../../assets/icons/icons8-html-96.png') }, { title: "CSS", img: require('../../assets/icons/icons8-css-96.png') }, { title: "Sass", img: require('../../assets/icons/icons8-sass-96.png') }, { title: "MUI", img: require('../../assets/icons/icons8-material-ui-48.png') }, { title: "Node.js", img: require('../../assets/icons/icons8-node-js-96.png') }, { title: "MongoDB", img: require('../../assets/icons/output-onlinepngtools (2).png') }, { title: "Kafka", img: require('../../assets/icons/kafka - White on Transparent.png') }, { title: "Docker", img: require('../../assets/icons/01-symbol_blue-docker-logo.png') }, { title: "git", img: require('../../assets/icons/Git-Icon-1788C.png') }, { title: "GitHub", img: require('../../assets/icons/github-mark-white.png') }, { title: "WordPress", img: require('../../assets/icons/icons8-wordpress-100.png') } ] const containerStyles = (theme:any) => ({ display:'flex', flexDirection: "column", justifyContent: 'center', alignItems: 'center', padding: "2rem 4rem", paddingBottom: "100px", background: 'linear-gradient(90deg, rgba(5,8,16,1) 0%, rgba(0,0,0,1) 50%)', [theme.breakpoints.down('sm')]: { padding: "25px", }, }) const skillsGridStyles = (theme:any) => ({ gridTemplateColumns: 'repeat(4, 150px)', display:'flex', justifyContent: 'center', alignItems: 'center', paddingTop: "1.5rem", [theme.breakpoints.up('md')]: { width: "85%", }, [theme.breakpoints.up('lg')]: { width: "1000px", }, }) const SkillsContainer = () => ( <Box sx={containerStyles}> <SectionTitle section="Skills"/> <Grid container gap={3} sx={skillsGridStyles}> {techIcons.map(techIcon => { const { title, img } = techIcon return ( <Grid item lg={2.5} key={title} padding={0}> <SkillCard skill={title} image={img} /> </Grid> ) })} </Grid> </Box> ) export default SkillsContainer;
import React, { useState } from 'react'; import { useSelector, useDispatch } from 'react-redux'; import Avatar from '@material-ui/core/Avatar'; import Button from '@material-ui/core/Button'; import TextField from '@material-ui/core/TextField'; import Grid from '@material-ui/core/Grid'; import LockOutlinedIcon from '@material-ui/icons/LockOutlined'; import Typography from '@material-ui/core/Typography'; import { makeStyles } from '@material-ui/core/styles'; import Container from '@material-ui/core/Container'; const useStyles = makeStyles((theme) => ({ mainContainer: { border: 1, borderRadius: 3, boxShadow: '0 3px 5px 2px rgba(255, 105, 135, .3)', }, closeButton: { display: 'flex', justifyContent: 'flex-end', }, paper: { display: 'flex', flexDirection: 'column', alignItems: 'center', }, avatar: { margin: theme.spacing(1), backgroundColor: theme.palette.secondary.main, }, form: { width: '100%', marginTop: theme.spacing(3), }, submit: { margin: theme.spacing(3, 0, 2), }, })); export default function SignUpModal(props) { const classes = useStyles(); const [email, setEmail] = useState(); const [username, setUserName] = useState(); const [password, setPassword] = useState(); const dispatch = useDispatch(); const showModal = useSelector((state) => state.utilsReducer.isModalSignUpShown); const handleCloseSignUp = () => { dispatch({ type: 'SHOW_MODAL_SIGN_UP', payload: false }); }; const handleSignup = () => { const payload = { username, email, password, }; dispatch({ type: 'SIGNUP_USER', payload }); }; return ( <> {showModal && ( <Container className={classes.mainContainer} component="main" maxWidth="xs"> <div className={classes.closeButton}> <Button onClick={handleCloseSignUp} variant="contained" color="secondary"> Close </Button> </div> <div className={classes.paper}> <Avatar className={classes.avatar}> <LockOutlinedIcon /> </Avatar> <Typography component="h1" variant="h5"> Sign up </Typography> <form className={classes.form} noValidate> <Grid container spacing={2}> <Grid item xs={12}> <TextField autoComplete="uname" name="userName" variant="outlined" required fullWidth id="userName" label="User Name" value={username} onChange={(e) => setUserName(e.target.value)} autoFocus /> </Grid> <Grid item xs={12}> <TextField variant="outlined" required fullWidth id="email" label="Email Address" name="email" value={email} onChange={(e) => setEmail(e.target.value)} autoComplete="email" /> </Grid> <Grid item xs={12}> <TextField variant="outlined" required fullWidth name="password" label="Password" type="password" id="password" value={password} onChange={(e) => setPassword(e.target.value)} autoComplete="current-password" /> </Grid> </Grid> <Button onClick={handleSignup} type="button" fullWidth variant="contained" color="primary" className={classes.submit} > Sign Up </Button> </form> </div> </Container> ) } </> ); }
import { ComponentFixture, fakeAsync, inject, TestBed, tick } from '@angular/core/testing'; import { Router } from '@angular/router'; import { HttpClientTestingModule } from '@angular/common/http/testing'; import { RouterTestingModule } from '@angular/router/testing'; import { TranslateTestingModule } from 'ngx-translate-testing'; import { AuthenticationPopupComponent } from './authentication-popup.component'; import { TranslateService } from '@ngx-translate/core'; import { LocaleService } from '@fedex/caas'; import { of } from 'rxjs'; import { SendOtpService } from 'src/app/services/send-otp/send-otp.service'; import { delay } from 'rxjs/operators'; import { ConfigurationService } from 'src/app/services/configuration/configuration.service'; import { APIResponse } from 'src/app/shared/models/Response'; import {HttpErrorResponse} from '@angular/common/http'; export class MockFactorsService { sendVerificationCode = (): any => of({}); } describe('AuthenticationPopupComponent', () => { let component: AuthenticationPopupComponent; let fixture: ComponentFixture<AuthenticationPopupComponent>; let localeService: LocaleService; let configService: ConfigurationService; let router: Router; const ENGLISH_TRANSLATIONS = require('src/assets/i18n/en.json'); let sendOtpService: SendOtpService; beforeAll(() => { configService = new ConfigurationService(null); configService.appConfig = { ...require('../../../../assets/configs/config.json'), ...require('../../../../assets/configs/level.json') }; }); beforeEach(() => { TestBed.configureTestingModule({ declarations: [AuthenticationPopupComponent], imports: [RouterTestingModule, HttpClientTestingModule, TranslateTestingModule.withTranslations({ en: ENGLISH_TRANSLATIONS })], providers: [LocaleService, { provide: ConfigurationService, useValue: configService }, { provide: SendOtpService, useClass: MockFactorsService }] }) .compileComponents(); }); beforeEach(() => { fixture = TestBed.createComponent(AuthenticationPopupComponent); component = fixture.componentInstance; router = TestBed.inject(Router); fixture.detectChanges(); localeService = TestBed.inject(LocaleService); sendOtpService = TestBed.inject(SendOtpService); }); it('should create', () => { expect(component).toBeTruthy(); }); // Test case to check selectDeliveryMethod it('should call selectDeliveryMethod', () => { const method = 'phone'; component.selectDeliveryMethod(method); fixture.detectChanges(); expect(component.selectedMethod).toBe('phone'); }); // Test case to check sendVerificationCode method for success case it('should call sendVerificationCode method for success case', fakeAsync(() => { const response = { output: { 'maxLimit': true } }; component.response = { output: { uuidCookie: '7zqesGMub0', sessionId: 'KKKDFJ332kdfkj' } }; spyOn(sendOtpService, 'sendVerificationCode').and.returnValue(of(response).pipe(delay(1))); component.confirm(); fixture.detectChanges(); expect(sendOtpService.sendVerificationCode).toHaveBeenCalled(); tick(1000); })); // Test case to check Choose a verification method on screen it('should display Choose a verification method-title', inject([TranslateService], (translateService: TranslateService) => { translateService.setDefaultLang('en'); fixture.detectChanges(); const element = fixture.debugElement.nativeElement; expect(element.querySelector('#verifyMethodTitle').textContent.trim()).toBe(ENGLISH_TRANSLATIONS.chooseVerifyMethod.verifyMethodTitle); })); // Test case to check if 'subtitle' is available' it('should display subtitle', inject([TranslateService], (translateService: TranslateService) => { translateService.setDefaultLang('en'); fixture.detectChanges(); const element = fixture.debugElement.nativeElement; expect(element.querySelector('#verifyMethodSubtitle').textContent.trim()).toBe(ENGLISH_TRANSLATIONS.chooseVerifyMethod.verifyMethodSubtitle); })); // Test case to check if 'confirm' button is available it('should display confirm button', inject([TranslateService], (translateService: TranslateService) => { translateService.setDefaultLang('en'); fixture.detectChanges(); const element = fixture.debugElement.nativeElement; expect(element.querySelector('#confirm-btn').textContent.trim()).toBe(ENGLISH_TRANSLATIONS.chooseVerifyMethod.confirmButton); })); // Test case to check if 'cancel' text is available' it('should display cancel button', inject([TranslateService], (translateService: TranslateService) => { translateService.setDefaultLang('en'); fixture.detectChanges(); const element = fixture.debugElement.nativeElement; expect(element.querySelector('#cancelBtn').textContent.trim()).toBe(ENGLISH_TRANSLATIONS.chooseVerifyMethod.cancelButton); })); // Test case to check close popup method it('should check close popup', () => { spyOn(component.hidePopup, 'emit'); fixture.detectChanges(); component.closePopup(); expect(component.hidePopup.emit).toHaveBeenCalled(); }); // Test case for verified response method it('should check errorHandler success case', () => { const err = new HttpErrorResponse({ error: { status: '400', errors: [{ code: 'ATTEMPT.EXCEEDED' }] } }); /*component.response = { output: { uuidCookie: '7zqesGMub0', sessionId: 'KKKDFJ332kdfkj', verificationMethods: [{ deliveryMethod: 'EMAIL' }] } };*/ const spyNavigate = spyOn(router, 'navigate'); spyOn(sendOtpService, 'sendVerificationCode').and.throwError(err); component.errorHandler(err); fixture.detectChanges(); expect(spyNavigate).toHaveBeenCalledWith(['/fail']); }); it('should call sendVerificationCode method for success case', () => { const response: APIResponse = { status: '200', output: {} }; component.response = { output: { uuidCookie: '7zqesGMub0', sessionId: 'KKKDFJ332kdfkj', verificationMethods: [{ deliveryMethod: 'EMAIL' }] } }; spyOn(sendOtpService, 'sendVerificationCode').and.returnValue(of(response).pipe(delay(1))); spyOn(component, 'errorHandler').and.callThrough(); component.confirm(); fixture.detectChanges(); expect(sendOtpService.sendVerificationCode).toHaveBeenCalled(); }); // Test case to check status 400 Exceeded it('On click of login button should get error status 400 Exceeded', () => { const err = new HttpErrorResponse({ error: { transactionId: '624deea6-b709-470c-8c39-4b5511281492', errors: [{ code: 'LOGIN.UNSUCCESSFUL.EXCEEDED', parameterList: [], message: 'Internal server error' }] } }); component.errorHandler(err); fixture.detectChanges(); }); });
# Automated Evaluation Framework for Graph Database Query Generation ## Overview This project "An Automated Evaluation Framework for Graph Database Query Generation Leveraging Large Language Models," is designed to streamline the process of evaluating graph database query generation using large language models. By automating various aspects of query generation and evaluation, this framework aims to enhance the efficiency and accuracy of graph database query development. ## Components ### 1. chatgpt_client.py This file provides the necessary login information for accessing the ChatGPT API. ChatGPT is utilized within the framework to generate natural language queries based on given parameters and templates. ### 2. neo4j_client.py neo4j_client.py contains the login information required to connect to a Neo4j graph database. Neo4j is a popular choice for graph databases due to its powerful querying capabilities and scalability. ### 3. design_template.json design_template.json serves as the raw data template for query generation. This file contains the structure and specifications required for generating queries. Users can customize this template according to their specific graph database schema and requirements. ### 4. data_preparation.py The data_preparation.py script is responsible for preparing the data required for query generation. It processes the raw data template (design_template.json) and transforms it into a format suitable for input into the query generation process. ### 5. query_generation.py query_generation.py is the main script of the framework. It utilizes the processed data from data_preparation.py and leverages the ChatGPT model to generate natural language queries. These queries are then executed against the Neo4j database, and the results are evaluated based on predefined metrics. ## Getting Started To utilize this framework, follow these steps: 1. Ensure you have [conda](https://conda.io/projects/conda/en/latest/user-guide/install/index.html) installed on your system. 2. Create a new Python 3.11 environment using conda by running the following command in your terminal: ```bash conda create -n graph_query_env python=3.11 ``` 3. Activate the newly created environment: ```bash conda activate graph_query_env ``` 4. Install the required dependencies listed in requirements.txt by running: ```bash pip install -r requirements.txt ``` 5. Provide the necessary login credentials in chatgpt_client.py and neo4j_client.py. 6. Customize the design_template.json file according to your graph database schema. 7. Run data_preparation.py to prepare the data for query generation. 8. Execute query_generation.py to generate and evaluate queries against your Neo4j database.
#-------------SETUP------------------- # Load (and possibly install) packages required. library(plyr) library(tidyverse) library(readr) library(broom) library(modelr) library(socviz) library(ggforce) library(colorBlindness) # Import raw dataset. # I converted the Excel page needed into csv format first. Raw_Data <- read_csv("Data-Raw/rawdata.csv") # Remove unsatisfactory flags. Flags_Removed <- Raw_Data[!grepl('CurveFitFail|MultipleMeltPeak|NoAmplification', Raw_Data$Flags),] # Remove flags column, as it's no longer needed. Flags_Removed$Flags = NULL # ------------WRANGLE--------------------------- # Add individual sample locations for removing "solo" results. # "Solo" results are when out of the three repeats, there was only amplification in one sample. Flags_Removed$ID = NA Flags_Removed$Replicate = NA # Fill in replicate IDs. Flags_Removed <- mutate(Flags_Removed, Replicate = case_when( str_detect(Sample, "rep1") ~ "1", str_detect(Sample, "rep2") ~ "2", str_detect(Sample, "rep3") ~ "3" )) # Fill in sample IDs. # I swapped ASP Distribution to be Sample 1 as it's the earliest stage. Flags_Removed <- mutate(Flags_Removed, ID = case_when( str_detect(Sample, "1A") ~ "A", str_detect(Sample, "2A") ~ "B", str_detect(Sample, "3A") ~ "C" , str_detect(Sample, "4A") ~ "D", str_detect(Sample, "5A") ~ "E", str_detect(Sample, "6A") ~ "F", str_detect(Sample, "7A") ~ "ASP", str_detect(Sample, "8A") ~ "G")) # Remove "solo" results. Solo_Removed <- ddply(Flags_Removed, c("Assay", "ID"), function(d) {if (nrow(d) > 1) d else NULL}) # Remove Tm and Efficiency columns as we're focusing on cycle threshold. Solo_Removed$Tm = NULL Solo_Removed$Efficiency = NULL # We now have to remove entries with no amplification at the ASP location. # ASP is the first location during the treatment process we have data for. # Make a list of unique genes that have data for the ASP location, then filter by that. list. List_AssayID <- unique(Solo_Removed[grepl("ASP",Solo_Removed$ID),]$Assay) Only_ASP <- dplyr::filter(Solo_Removed, Assay %in% List_AssayID) # Mutate the sample column to not begin with a number, for easier coding and recognition. Only_ASP$SampleID = NA Mutated_SampleID <- mutate(Only_ASP, SampleID = case_when( str_detect(Sample, "1A-rep1") ~ "A_rep1", str_detect(Sample, "1A-rep2") ~ "A_rep2", str_detect(Sample, "1A-rep3") ~ "A_rep3", str_detect(Sample, "2A-rep1") ~ "B_rep1", str_detect(Sample, "2A-rep2") ~ "B_rep2", str_detect(Sample, "2A-rep3") ~ "B_rep3", str_detect(Sample, "3A-rep1") ~ "C_rep1" , str_detect(Sample, "3A-rep2") ~ "C_rep2" , str_detect(Sample, "3A-rep3") ~ "C_rep3" , str_detect(Sample, "4A-rep1") ~ "D_rep1", str_detect(Sample, "4A-rep2") ~ "D_rep2", str_detect(Sample, "4A-rep3") ~ "D_rep3", str_detect(Sample, "5A-rep1") ~ "E_rep1", str_detect(Sample, "5A-rep2") ~ "E_rep2", str_detect(Sample, "5A-rep3") ~ "E_rep3", str_detect(Sample, "6A-rep1") ~ "F_rep1", str_detect(Sample, "6A-rep2") ~ "F_rep2", str_detect(Sample, "6A-rep3") ~ "F_rep3", str_detect(Sample, "7A-rep1") ~ "ASP_rep1", str_detect(Sample, "7A-rep2") ~ "ASP_rep2", str_detect(Sample, "7A-rep3") ~ "ASP_rep3", str_detect(Sample, "8A-rep1") ~ "G_rep1", str_detect(Sample, "8A-rep2") ~ "G_rep2", str_detect(Sample, "8A-rep3") ~ "G_rep3")) # Remove the original Sample ID column, as it has been replaced. Mutated_SampleID$Sample = NULL # Pivot the table wider. Mutated_Wide <- Mutated_SampleID %>% pivot_wider(names_from = Assay, values_from = Ct) # Remove extra unneeded columns Mutated_Wide$ID = NULL Mutated_Wide$Replicate = NULL # Create sample ID list. SampleID <- Mutated_Wide$SampleID # Pivot the table back to longer. Mutated_Long <- Mutated_Wide %>% pivot_longer( cols = AY1:AY96, names_to = "Assay", values_to = "Ct") # Pivot the table again, so Sample ID is across the top, rather than Assay. Mutated_Wide_2 <- Mutated_Long %>% pivot_wider( names_from = SampleID, values_from = Ct) # Transpose the table. Transposed_Ct <- t(Mutated_Wide_2[2:25]) # Make sure the top row is the Assay codes, by first extracting as a list. Assay_Names <- t(Mutated_Wide_2[1]) colnames(Transposed_Ct) <- as.character(Assay_Names[1,]) # Calculate Delta Ct and make sure the output is as a data frame. as.data.frame(Transposed_Ct) Delta_Ct <- Transposed_Ct[ , 2:137] - Transposed_Ct[ , "AY1"] DF_Delta_Ct <- as.data.frame(Delta_Ct) # Start with ASP values on their own. Delta_Ct_ASP <- head(DF_Delta_Ct, 3) # Turn the rownames into the first column to preserve them. Delta_Ct_ASP_Rownames <- rownames_to_column(Delta_Ct_ASP, "SampleID") # Calculate the sum of each column. Delta_Ct_ASP_Sum <- as.data.frame(colSums(Delta_Ct_ASP_Rownames[ , -1], na.rm = TRUE)) # Rename the resulting sum column. Delta_Ct_ASP_Sum_Rownames <- rownames_to_column(Delta_Ct_ASP_Sum, "Assay") names(Delta_Ct_ASP_Sum_Rownames)[2] <- "Sum_Delta_Ct" # Pivot wider ready for mean calculation. Delta_Ct_ASP_Sum_Wide <- pivot_wider(Delta_Ct_ASP_Sum_Rownames, names_from = "Assay", values_from = "Sum_Delta_Ct") # Pivot longer for counting data entries. Delta_Ct_ASP_Long <- pivot_longer(Delta_Ct_ASP_Sum_Wide, cols = AY10:AY96, names_to = "Assay", values_to = "Delta_Ct", values_drop_na = TRUE) # Count the frequency for each gene. Delta_Ct_ASP_Count <- as.data.frame(table(Delta_Ct_ASP_Long$Assay)) # Pivot wider again. Delta_Ct_ASP_Count_Wide <- as.data.frame(pivot_wider(Delta_Ct_ASP_Count, names_from = "Var1", values_from = "Freq")) # Calculate ASP means for Delta Delta Ct calculation. Delta_Ct_ASP_Mean <- as.data.frame(Delta_Ct_ASP_Sum_Wide * Delta_Ct_ASP_Count_Wide) # Calculate Delta Delta Ct. Delta_Delta_Ct <- DF_Delta_Ct - as.list(Delta_Ct_ASP_Mean) # Remove ASP values from main table. Delta_Delta_Ct_No_ASP <- tail(Delta_Delta_Ct, -3) # Calculate 2^DDC, or is it better to log2 later? DDCt_Power <- 2^-(Delta_Delta_Ct_No_ASP) # Convert row names to a column of their own to protect them. DDCt_Power_Loc <- rownames_to_column(DDCt_Power, "SampleID") # ------------ANALYSIS---------------- # Add replicate and ID columns. DDCt_P <- DDCt_Power_Loc DDCt_P$Replicate = NA DDCt_P$Treatment_Stage = NA # Rearrange the columns to make it easier. Rearranged_DDCt_P <- subset(DDCt_P, select = c( SampleID, Treatment_Stage, Replicate, AY10:AY96)) Rearranged_DDCt_P <- mutate(Rearranged_DDCt_P, Replicate = case_when( str_detect(SampleID, "rep1") ~ "rep1", str_detect(SampleID, "rep2") ~ "rep2", str_detect(SampleID, "rep3") ~ "rep3" )) # Add sample IDs in their column. Rearranged_DDCt_P <- mutate(Rearranged_DDCt_P, Treatment_Stage = case_when( str_detect(SampleID, "A") ~ "A", str_detect(SampleID, "B") ~ "B", str_detect(SampleID, "C") ~ "C", str_detect(SampleID, "D") ~ "D", str_detect(SampleID, "E") ~ "E", str_detect(SampleID, "F") ~ "F", str_detect(SampleID, "G") ~ "G")) # Remove the joined sample ID column, as it has been split. Rearranged_DDCt_P$SampleID = NULL # Pivot longer. DDCt_P_Long <- pivot_longer(Rearranged_DDCt_P, cols = AY10:AY96, names_to = "Assay", values_to = "DDCtTwoP", values_drop_na = TRUE) DDCt_ASP_Power <- 2^-(Delta_Ct_ASP_Mean) DDCt_ASP_Mean_Long <- pivot_longer(DDCt_ASP_Power, cols = AY10:AY96, names_to = "Assay", values_to = "ASP_DCt") # Join the ASP and long table together. DDCtP_With_ASP <- full_join(DDCt_P_Long, DDCt_ASP_Mean_Long, by = c("Assay" = "Assay")) # ------------ANNOTATONS------- # Import assay information. Assay_Information <- read_csv("Data-Raw/assayinformation.csv") # Remove the columns not needed. Assay_Information$`Forward Primer` = NULL Assay_Information$`Reverse Primer` = NULL # Change column names for easier code. colnames(Assay_Information) = c("Assay", "Gene", "Target_Antibiotic") # Remove Taxonomic genes for now, focus on resistance genes. Assay_Information <- Assay_Information[!grepl('Taxanomic', Assay_Information$Target_Antibiotic),] # Join the main table with the assay information. Annotated_DDCtP <- full_join(DDCtP_With_ASP, Assay_Information, by = c("Assay" = "Assay")) # Remove any NAs Annotated_DDCtP <- Annotated_DDCtP %>% drop_na() # Rearrange columns. Annotated_DDCtP <- subset(Annotated_DDCtP, select = c( Assay, Treatment_Stage, Gene, DDCtTwoP, ASP_DCt, Target_Antibiotic, Replicate)) # Calculate the standard errors. DDCtP_Summary <- Annotated_DDCtP %>% group_by(Gene, Treatment_Stage) %>% summarise(mean = mean(DDCtTwoP), std = sd(DDCtTwoP), n = length(DDCtTwoP), se = std/sqrt(n)) Summary_DDCtP <- Annotated_DDCtP Summary_DDCtP$Assay = NULL # Potentially create a wide format table with the summary information. DDCtP_Wide <- pivot_wider(Annotated_DDCtP, names_from = Gene, values_from = DDCtTwoP) # ------------MODEL------- # Produce initial plot. ggplot(data = Annotated_DDCtP, mapping = aes(Treatment_Stage, DDCtTwoP)) + geom_violin() + facet_wrap_paginate(facets = vars(Target_Antibiotic), ncol = 4, scales = "free_x") # Split based on Treatment Stage. Split <- split(Annotated_DDCtP, Annotated_DDCtP$Treatment_Stage) A <- Split$A B <- Split$B C <- Split$C D <- Split$D E <- Split$E F <- Split$F G <- Split$G # Rename dataset for model. DDCtP_LM <- DDCtP_Wide DDCtP_LM <- na.omit(DDCtP_LM) str(DDCtP_LM) # Create model. # How does DDCtTwoP change across each location for each gene? A_lm <- lm(DDCtTwoP ~ Gene, data = A) # Use tidy to neaten table and add confidence intervals. A_out_conf <- tidy(A_lm, conf.int = TRUE) # Needed to strip term names. # Strip out prefix in term column. A_out_conf$nicelabs <- prefix_strip(A_out_conf$term, "Gene") # Augment generates Cook's distance, residual values and fitted values. A_out_aug <- augment(A_lm) # Create new column to show location. A_out_aug$Treatment_Stage = "A" # Summary model values. glance(A_lm) # repeat for B. B_lm <- lm(DDCtTwoP ~ Gene, data = B) B_out_conf <- tidy(B_lm, conf.int = TRUE) B_out_conf$nicelabs <- prefix_strip(B_out_conf$term, "Gene") B_out_aug <- augment(B_lm) B_out_aug$Treatment_Stage = "B" glance(B_lm) # repeat for C. C_lm <- lm(DDCtTwoP ~ Gene, data = C) C_out_conf <- tidy(C_lm, conf.int = TRUE) C_out_conf$nicelabs <- prefix_strip(C_out_conf$term, "Gene") C_out_aug <- augment(C_lm) C_out_aug$Treatment_Stage = "C" glance(C_lm) # repeat for D. D_lm <- lm(DDCtTwoP ~ Gene, data = D) D_out_conf <- tidy(D_lm, conf.int = TRUE) D_out_conf$nicelabs <- prefix_strip(D_out_conf$term, "Gene") D_out_aug <- augment(D_lm) D_out_aug$Treatment_Stage = "D" glance(D_lm) # repeat for E. E_lm <- lm(DDCtTwoP ~ Gene, data = E) E_out_conf <- tidy(E_lm, conf.int = TRUE) E_out_conf$nicelabs <- prefix_strip(E_out_conf$term, "Gene") E_out_aug <- augment(E_lm) E_out_aug$Treatment_Stage = "E" glance(E_lm) # repeat for F. F_lm <- lm(DDCtTwoP ~ Gene, data = F) F_out_conf <- tidy(F_lm, conf.int = TRUE) F_out_conf$nicelabs <- prefix_strip(F_out_conf$term, "Gene") F_out_aug <- augment(F_lm) F_out_aug$Treatment_Stage = "F" glance(F_lm) # repeat for G. G_lm <- lm(DDCtTwoP ~ Gene, data = G) G_out_conf <- tidy(G_lm, conf.int = TRUE) G_out_conf$nicelabs <- prefix_strip(G_out_conf$term, "Gene") G_out_aug <- augment(G_lm) G_out_aug$Treatment_Stage = "G" glance(G_lm) # Join all tables together. Full_lm_out <- rbind.data.frame(A_out_aug, B_out_aug, C_out_aug, D_out_aug, E_out_aug, F_out_aug, G_out_aug) # Join with the assay information. Annotated_Full_Model <- full_join(Full_lm_out, Assay_Information, by = c("Gene" = "Gene")) Annotated_Full_Model <- Annotated_Full_Model %>% drop_na() Annotated_Full_Model$Assay = NULL # Re-do summary table. Annotated_Full_Summary <- Annotated_Full_Model %>% group_by(Gene, Treatment_Stage) %>% summarise(mean = mean(DDCtTwoP), std = sd(DDCtTwoP), n = length(DDCtTwoP), se = std/sqrt(n)) # Join summary and model table. All_Data <- full_join(Annotated_Full_Summary, Annotated_Full_Model, by = c("Gene" = "Gene", "Treatment_Stage" = "Treatment_Stage")) # create a table for tidy data write.csv(All_Data, "AllData.csv", row.names = FALSE) # remove all samples except biosolids Biosolids <- All_Data[grepl("^[EF]+$", All_Data$Treatment_Stage), ] # Filter the data Filtered_Biosolid <- Biosolids %>% group_by(Gene) %>% filter(n_distinct(Treatment_Stage) == 2) %>% ungroup() Biosolid_Renamed <- mutate(Filtered_Biosolid, Treatment_Stage = case_when( str_detect(Treatment_Stage, "E") ~ "newdry", str_detect(Treatment_Stage, "F") ~ "Aged Biosolid")) Biosolid_Renamed <- Biosolid_Renamed %>% group_by(Gene, Treatment_Stage, mean) %>% filter(row_number() == 1) # remove all samples except biosolids for target_antibiotic grouping Biosolids_Target <- Annotated_Full_Model[grepl("^[EF]+$", Annotated_Full_Model$Treatment_Stage), ] # Re-do summary table. Annotated_Full_Summary2 <- Biosolids_Target %>% group_by(Target_Antibiotic, Treatment_Stage) %>% summarise(mean = mean(DDCtTwoP), std = sd(DDCtTwoP), n = length(DDCtTwoP), se = std/sqrt(n)) Annotated_Full_Summary2 <- mutate(Annotated_Full_Summary2, Treatment_Stage = case_when( str_detect(Treatment_Stage, "E") ~ "newdry", str_detect(Treatment_Stage, "F") ~ "olddry")) # ------------GRAPHS------------------ ggplot(data = Annotated_Full_Summary2, mapping = aes(x = Treatment_Stage, y = log(mean), group = Target_Antibiotic, color = as.factor(Target_Antibiotic))) + geom_point(size = 2, aes(color = Target_Antibiotic)) + geom_line(aes(color = Target_Antibiotic)) + labs(x = "Treatment Stage", y = "Log Gene Expression", colour = "Class") + theme_bw(base_size = 10) + theme(panel.grid.major = element_line(colour = "gray80"), panel.grid.minor = element_line(colour = "gray80"), axis.text.x = element_text(angle = 90), legend.text = element_text(family = "serif", size = 10), axis.text = element_text(family = "serif", size = 10), axis.title = element_text(family = "serif", size = 10, face = "bold", colour = "gray20"), legend.title = element_text(size = 10, family = "serif"), plot.background = element_rect(colour = NA, linetype = "solid"), legend.key = element_rect(colour = NA)) ggsave("Figure/line-target.png", width = 7, height = 5) Annotated_Full_Summary2 %>% group_by(Target_Antibiotic) %>% ggplot(aes(x = Treatment_Stage, y = mean, colour = Target_Antibiotic, shape = Treatment_Stage, size = 1.5)) + geom_point() + geom_line() + scale_x_discrete(limits = rev) + labs(x = "Treatment Stage", y = "Mean Gene Expression", colour = "Class") + theme_bw(base_size = 10) + guides(shape = "none", size = "none") + theme(panel.grid.major = element_line(colour = "gray80"), panel.grid.minor = element_line(colour = "gray80"), axis.text.x = element_text(angle = 90), legend.text = element_text(family = "serif", size = 10), axis.text = element_text(family = "serif", size = 10), axis.title = element_text(family = "serif", size = 10, face = "bold", colour = "gray20"), legend.title = element_text(size = 10, family = "serif"), plot.background = element_rect(colour = NA, linetype = "solid"), legend.key = element_rect(colour = NA)) ggsave("Figure/jitter_target.png", width = 7, height = 5) #split table based on target antibiotic?? Split2 <- split(Biosolid_Renamed, Biosolid_Renamed$Target_Antibiotic) Aminoglycoside <- Split2$Aminoglycoside Beta_Lactam <- Split2$`Beta Lactam` Integrons <- Split2$Integrons MDR <- Split2$MDR MGE <- Split2$MGE MLSB <- Split2$MLSB Other <- Split2$Other Phenicol <- Split2$Phenicol Quinolone <- Split2$Quinolone Sulfonamide <- Split2$Sulfonamide Tetracycline <- Split2$Tetracycline Trimethoprim <- Split2$Trimethoprim Vancomycin <- Split2$Vancomycin Aminoglycoside %>% group_by(Gene) %>% ggplot(aes(x = Treatment_Stage, y = mean, colour = Gene, shape = Treatment_Stage, size = 1.5)) + geom_jitter(width = 0.3) + labs(x = "Treatment Stage", y = "Normalised Gene Expression") + theme_bw(base_size = 10) + guides(shape = "none", size = "none") + theme(panel.grid.major = element_line(colour = "gray80"), panel.grid.minor = element_line(colour = "gray80"), axis.text.x = element_text(angle = 90), legend.text = element_text(family = "serif", size = 10), axis.text = element_text(family = "serif", size = 10), axis.title = element_text(family = "serif", size = 10, face = "bold", colour = "gray20"), legend.title = element_text(size = 10, family = "serif"), plot.background = element_rect(colour = NA, linetype = "solid"), legend.key = element_rect(colour = NA)) ggsave("Figure/line-biosolid-aminoglycoside.png", width = 7, height = 5) Beta_Lactam %>% group_by(Gene) %>% ggplot(aes(x = Treatment_Stage, y = mean, colour = Gene, shape = Treatment_Stage, size = 1.5)) + geom_jitter(width = 0.3) + labs(x = "Treatment Stage", y = "Normalised Gene Expression") + theme_bw(base_size = 10) + guides(shape = "none", size = "none") + theme(panel.grid.major = element_line(colour = "gray80"), panel.grid.minor = element_line(colour = "gray80"), axis.text.x = element_text(angle = 90), legend.text = element_text(family = "serif", size = 10), axis.text = element_text(family = "serif", size = 10), axis.title = element_text(family = "serif", size = 10, face = "bold", colour = "gray20"), legend.title = element_text(size = 10, family = "serif"), plot.background = element_rect(colour = NA, linetype = "solid"), legend.key = element_rect(colour = NA)) ggsave("Figure/line-biosolid-beta-lactam.png", width = 4, height = 4) Integrons %>% group_by(Gene) %>% ggplot(aes(x = Treatment_Stage, y = mean, colour = Gene, shape = Treatment_Stage, size = 1.5)) + geom_jitter(width = 0.3) + labs(x = "Treatment Stage", y = "Normalised Gene Expression") + theme_bw(base_size = 10) + guides(shape = "none", size = "none") + theme(panel.grid.major = element_line(colour = "gray80"), panel.grid.minor = element_line(colour = "gray80"), axis.text.x = element_text(angle = 90), legend.text = element_text(family = "serif", size = 10), axis.text = element_text(family = "serif", size = 10), axis.title = element_text(family = "serif", size = 10, face = "bold", colour = "gray20"), legend.title = element_text(size = 10, family = "serif"), plot.background = element_rect(colour = NA, linetype = "solid"), legend.key = element_rect(colour = NA)) ggsave("Figure/line-biosolid-integron.png", width = 4, height = 4) MDR %>% group_by(Gene) %>% ggplot(aes(x = Treatment_Stage, y = mean, colour = Gene, shape = Treatment_Stage, size = 1.5)) + geom_jitter(width = 0.3) + labs(x = "Treatment Stage", y = "Normalised Gene Expression") + theme_bw(base_size = 10) + guides(shape = "none", size = "none") + theme(panel.grid.major = element_line(colour = "gray80"), panel.grid.minor = element_line(colour = "gray80"), axis.text.x = element_text(angle = 90), legend.text = element_text(family = "serif", size = 10), axis.text = element_text(family = "serif", size = 10), axis.title = element_text(family = "serif", size = 10, face = "bold", colour = "gray20"), legend.title = element_text(size = 10, family = "serif"), plot.background = element_rect(colour = NA, linetype = "solid"), legend.key = element_rect(colour = NA)) ggsave("Figure/line-biosolid-mdr.png", width = 4, height = 4) MGE %>% group_by(Gene) %>% ggplot(aes(x = Treatment_Stage, y = mean, colour = Gene, shape = Treatment_Stage, size = 1.5)) + geom_jitter(width = 0.3) + labs(x = "Treatment Stage", y = "Normalised Gene Expression") + theme_bw(base_size = 10) + guides(shape = "none", size = "none") + theme(panel.grid.major = element_line(colour = "gray80"), panel.grid.minor = element_line(colour = "gray80"), axis.text.x = element_text(angle = 90), legend.text = element_text(family = "serif", size = 10), axis.text = element_text(family = "serif", size = 10), axis.title = element_text(family = "serif", size = 10, face = "bold", colour = "gray20"), legend.title = element_text(size = 10, family = "serif"), plot.background = element_rect(colour = NA, linetype = "solid"), legend.key = element_rect(colour = NA)) ggsave("Figure/line-biosolid-mge.png", width = 10, height = 8) MLSB %>% group_by(Gene) %>% ggplot(aes(x = Treatment_Stage, y = mean, colour = Gene, shape = Treatment_Stage, size = 1.5)) + geom_jitter(width = 0.3) + labs(x = "Treatment Stage", y = "Normalised Gene Expression") + theme_bw(base_size = 10) + guides(shape = "none", size = "none") + theme(panel.grid.major = element_line(colour = "gray80"), panel.grid.minor = element_line(colour = "gray80"), axis.text.x = element_text(angle = 90), legend.text = element_text(family = "serif", size = 10), axis.text = element_text(family = "serif", size = 10), axis.title = element_text(family = "serif", size = 10, face = "bold", colour = "gray20"), legend.title = element_text(size = 10, family = "serif"), plot.background = element_rect(colour = NA, linetype = "solid"), legend.key = element_rect(colour = NA)) ggsave("Figure/line-biosolid-mlsb.png", width = 4, height = 4) Other %>% group_by(Gene) %>% ggplot(aes(x = Treatment_Stage, y = mean, colour = Gene, shape = Treatment_Stage, size = 1.5)) + geom_jitter(width = 0.3) + labs(x = "Treatment Stage", y = "Normalised Gene Expression") + theme_bw(base_size = 10) + guides(shape = "none", size = "none") + theme(panel.grid.major = element_line(colour = "gray80"), panel.grid.minor = element_line(colour = "gray80"), axis.text.x = element_text(angle = 90), legend.text = element_text(family = "serif", size = 10), axis.text = element_text(family = "serif", size = 10), axis.title = element_text(family = "serif", size = 10, face = "bold", colour = "gray20"), legend.title = element_text(size = 10, family = "serif"), plot.background = element_rect(colour = NA, linetype = "solid"), legend.key = element_rect(colour = NA)) ggsave("Figure/line-biosolid-other.png", width = 4, height = 4) Phenicol %>% group_by(Gene) %>% ggplot(aes(x = Treatment_Stage, y = mean, colour = Gene, shape = Treatment_Stage, size = 1.5)) + geom_jitter(width = 0.3) + labs(x = "Treatment Stage", y = "Normalised Gene Expression") + theme_bw(base_size = 10) + guides(shape = "none", size = "none") + theme(panel.grid.major = element_line(colour = "gray80"), panel.grid.minor = element_line(colour = "gray80"), axis.text.x = element_text(angle = 90), legend.text = element_text(family = "serif", size = 10), axis.text = element_text(family = "serif", size = 10), axis.title = element_text(family = "serif", size = 10, face = "bold", colour = "gray20"), legend.title = element_text(size = 10, family = "serif"), plot.background = element_rect(colour = NA, linetype = "solid"), legend.key = element_rect(colour = NA)) ggsave("Figure/line-biosolid-phenicol.png", width = 4, height = 3) Quinolone %>% group_by(Gene) %>% ggplot(aes(x = Treatment_Stage, y = mean, colour = Gene, shape = Treatment_Stage, size = 1.5)) + geom_jitter(width = 0.3) + labs(x = "Treatment Stage", y = "Normalised Gene Expression") + theme_bw(base_size = 10) + guides(shape = "none", size = "none") + theme(panel.grid.major = element_line(colour = "gray80"), panel.grid.minor = element_line(colour = "gray80"), axis.text.x = element_text(angle = 90), legend.text = element_text(family = "serif", size = 10), axis.text = element_text(family = "serif", size = 10), axis.title = element_text(family = "serif", size = 10, face = "bold", colour = "gray20"), legend.title = element_text(size = 10, family = "serif"), plot.background = element_rect(colour = NA, linetype = "solid"), legend.key = element_rect(colour = NA)) ggsave("Figure/line-biosolid-quinolone.png", width = 4, height = 4) Sulfonamide %>% group_by(Gene) %>% ggplot(aes(x = Treatment_Stage, y = mean, colour = Gene, shape = Treatment_Stage, size = 1.5)) + geom_jitter(width = 0.3) + labs(x = "Treatment Stage", y = "Normalised Gene Expression") + theme_bw(base_size = 10) + guides(shape = "none", size = "none") + theme(panel.grid.major = element_line(colour = "gray80"), panel.grid.minor = element_line(colour = "gray80"), axis.text.x = element_text(angle = 90), legend.text = element_text(family = "serif", size = 10), axis.text = element_text(family = "serif", size = 10), axis.title = element_text(family = "serif", size = 10, face = "bold", colour = "gray20"), legend.title = element_text(size = 10, family = "serif"), plot.background = element_rect(colour = NA, linetype = "solid"), legend.key = element_rect(colour = NA)) ggsave("Figure/line-biosolid-sulfonamide.png", width = 4, height = 4) Tetracycline %>% group_by(Gene) %>% ggplot(aes(x = Treatment_Stage, y = mean, colour = Gene, shape = Treatment_Stage, size = 1.5)) + geom_jitter(width = 0.3) + labs(x = "Treatment Stage", y = "Normalised Gene Expression") + theme_bw(base_size = 10) + guides(shape = "none", size = "none") + theme(panel.grid.major = element_line(colour = "gray80"), panel.grid.minor = element_line(colour = "gray80"), axis.text.x = element_text(angle = 90), legend.text = element_text(family = "serif", size = 10), axis.text = element_text(family = "serif", size = 10), axis.title = element_text(family = "serif", size = 10, face = "bold", colour = "gray20"), legend.title = element_text(size = 10, family = "serif"), plot.background = element_rect(colour = NA, linetype = "solid"), legend.key = element_rect(colour = NA)) ggsave("Figure/line-biosolid-tetracycline.png", width = 8, height = 6) Trimethoprim %>% group_by(Gene) %>% ggplot(aes(x = Treatment_Stage, y = mean, colour = Gene, shape = Treatment_Stage, size = 1.5)) + geom_jitter(width = 0.3) + labs(x = "Treatment Stage", y = "Normalised Gene Expression") + theme_bw(base_size = 10) + guides(shape = "none", size = "none") + theme(panel.grid.major = element_line(colour = "gray80"), panel.grid.minor = element_line(colour = "gray80"), axis.text.x = element_text(angle = 90), legend.text = element_text(family = "serif", size = 10), axis.text = element_text(family = "serif", size = 10), axis.title = element_text(family = "serif", size = 10, face = "bold", colour = "gray20"), legend.title = element_text(size = 10, family = "serif"), plot.background = element_rect(colour = NA, linetype = "solid"), legend.key = element_rect(colour = NA)) ggsave("Figure/line-biosolid-trimethoprim.png", width = 4, height = 4) Vancomycin %>% group_by(Gene) %>% ggplot(aes(x = Treatment_Stage, y = mean, colour = Gene, shape = Treatment_Stage, size = 1.5)) + geom_jitter(width = 0.3) + labs(x = "Treatment Stage", y = "Normalised Gene Expression") + theme_bw(base_size = 10) + guides(shape = "none", size = "none") + theme(panel.grid.major = element_line(colour = "gray80"), panel.grid.minor = element_line(colour = "gray80"), axis.text.x = element_text(angle = 90), legend.text = element_text(family = "serif", size = 10), axis.text = element_text(family = "serif", size = 10), axis.title = element_text(family = "serif", size = 10, face = "bold", colour = "gray20"), legend.title = element_text(size = 10, family = "serif"), plot.background = element_rect(colour = NA, linetype = "solid"), legend.key = element_rect(colour = NA)) ggsave("Figure/line-biosolid-vancomycin.png", width = 4, height = 4) # Create a list of target antibiotics. target_antibiotics <- unique(Biosolid_Renamed$Target_Antibiotic) # Create a loop for each target antibiotic. for (target_antibiotic in target_antibiotics) { # Create a subset of the data for the current target antibiotic. data <- Biosolid_Renamed[Biosolid_Renamed$Target_Antibiotic == target_antibiotic, ] # Create a heatmap of the data. ggplot(data, aes(x = Treatment_Stage, y = Gene, fill = mean)) + geom_tile() + scale_y_discrete(limits = rev) + scale_fill_gradient2(low = "turquoise3", high = "orange", mid = "yellow", midpoint = 5e+12) + labs(x = "Sample", y = "Gene", colour = "Prevalence") + theme_bw(base_size = 10) + theme(panel.grid.major = element_line(colour = "gray80"), panel.grid.minor = element_line(colour = "gray80"), axis.text.x = element_text(angle = 90), legend.text = element_text(family = "serif", size = 10), axis.text = element_text(family = "serif", size = 10), axis.title = element_text(family = "serif", size = 10, face = "bold", colour = "gray20"), legend.title = element_text(size = 10, family = "serif"), plot.background = element_rect(colour = NA, linetype = "solid"), legend.key = element_rect(fill = NA)) + labs(fill = "Intensity") # Save the heatmap to a file. ggsave(paste0("Figure/heatmap-", target_antibiotic, ".png"), width = 5, height = 7) } # seperate heatmaps? Aminoglycoside %>% group_by(Target_Antibiotic) %>% ggplot() + geom_tile(aes(y = Gene, x = Treatment_Stage, fill = mean)) + scale_y_discrete(limits = rev) + scale_fill_gradient2(low = "turquoise3", high = "orange", mid = "yellow", midpoint = 4e+09) + labs(x = "Sample", y = "Gene Name", colour = "Prevalence") + theme_bw(base_size = 10) + theme(panel.grid.major = element_line(colour = "gray80"), panel.grid.minor = element_line(colour = "gray80"), axis.text.x = element_text(angle = 90), legend.text = element_text(family = "serif", size = 10), axis.text = element_text(family = "serif", size = 10), axis.title = element_text(family = "serif", size = 10, face = "bold", colour = "gray20"), legend.title = element_text(size = 10, family = "serif"), plot.background = element_rect(colour = NA, linetype = "solid"), legend.key = element_rect(fill = NA)) + labs(fill = "Intensity") ggsave("Figure/heatmap-biosolid-aminoglycoside.png", width = 4, height = 6) Beta_Lactam %>% group_by(Target_Antibiotic) %>% ggplot() + geom_tile(aes(y = Gene, x = Treatment_Stage, fill = mean)) + scale_y_discrete(limits = rev) + scale_fill_gradient2(low = "turquoise3", high = "orange", mid = "yellow", midpoint = 2e+12) + labs(x = "Sample", y = "Gene Name", colour = "Prevalence") + theme_bw(base_size = 10) + theme(panel.grid.major = element_line(colour = "gray80"), panel.grid.minor = element_line(colour = "gray80"), axis.text.x = element_text(angle = 90), legend.text = element_text(family = "serif", size = 10), axis.text = element_text(family = "serif", size = 10), axis.title = element_text(family = "serif", size = 10, face = "bold", colour = "gray20"), legend.title = element_text(size = 10, family = "serif"), plot.background = element_rect(colour = NA, linetype = "solid"), legend.key = element_rect(fill = NA)) + labs(fill = "Intensity") ggsave("Figure/heatmap-biosolid-beta-lactam.png", width = 4, height = 3) Integrons %>% group_by(Target_Antibiotic) %>% ggplot() + geom_tile(aes(y = Gene, x = Treatment_Stage, fill = mean)) + scale_y_discrete(limits = rev) + scale_fill_gradient2(low = "turquoise3", high = "orange", mid = "yellow", midpoint = 1.5e+07) + labs(x = "Sample", y = "Gene Name", colour = "Prevalence") + theme_bw(base_size = 10) + theme(panel.grid.major = element_line(colour = "gray80"), panel.grid.minor = element_line(colour = "gray80"), axis.text.x = element_text(angle = 90), legend.text = element_text(family = "serif", size = 10), axis.text = element_text(family = "serif", size = 10), axis.title = element_text(family = "serif", size = 10, face = "bold", colour = "gray20"), legend.title = element_text(size = 10, family = "serif"), plot.background = element_rect(colour = NA, linetype = "solid"), legend.key = element_rect(fill = NA)) + labs(fill = "Intensity") ggsave("Figure/heatmap-biosolid-integron.png", width = 4, height = 2.5) MGE %>% group_by(Target_Antibiotic) %>% ggplot() + geom_tile(aes(y = Gene, x = Treatment_Stage, fill = mean)) + scale_y_discrete(limits = rev) + scale_fill_gradient2(low = "turquoise3", high = "orange", mid = "yellow", midpoint = 2.5e+09) + labs(x = "Sample", y = "Gene Name", colour = "Prevalence") + theme_bw(base_size = 10) + theme(panel.grid.major = element_line(colour = "gray80"), panel.grid.minor = element_line(colour = "gray80"), axis.text.x = element_text(angle = 90), legend.text = element_text(family = "serif", size = 10), axis.text = element_text(family = "serif", size = 10), axis.title = element_text(family = "serif", size = 10, face = "bold", colour = "gray20"), legend.title = element_text(size = 10, family = "serif"), plot.background = element_rect(colour = NA, linetype = "solid"), legend.key = element_rect(fill = NA)) + labs(fill = "Intensity") ggsave("Figure/heatmap-biosolid-mge.png", width = 4, height = 6) MDR %>% group_by(Target_Antibiotic) %>% ggplot() + geom_tile(aes(y = Gene, x = Treatment_Stage, fill = mean)) + scale_y_discrete(limits = rev) + scale_fill_gradient2(low = "turquoise3", high = "orange", mid = "yellow", midpoint = 5e+12) + labs(x = "Sample", y = "Gene Name", colour = "Prevalence") + theme_bw(base_size = 10) + theme(panel.grid.major = element_line(colour = "gray80"), panel.grid.minor = element_line(colour = "gray80"), axis.text.x = element_text(angle = 90), legend.text = element_text(family = "serif", size = 10), axis.text = element_text(family = "serif", size = 10), axis.title = element_text(family = "serif", size = 10, face = "bold", colour = "gray20"), legend.title = element_text(size = 10, family = "serif"), plot.background = element_rect(colour = NA, linetype = "solid"), legend.key = element_rect(fill = NA)) + labs(fill = "Intensity") ggsave("Figure/heatmap-biosolid-mdr.png", width = 4, height = 4) MLSB %>% group_by(Target_Antibiotic) %>% ggplot() + geom_tile(aes(y = Gene, x = Treatment_Stage, fill = mean)) + scale_y_discrete(limits = rev) + scale_fill_gradient2(low = "turquoise3", high = "orange", mid = "yellow", midpoint = 6e+08) + labs(x = "Sample", y = "Gene Name", colour = "Prevalence") + theme_bw(base_size = 10) + theme(panel.grid.major = element_line(colour = "gray80"), panel.grid.minor = element_line(colour = "gray80"), axis.text.x = element_text(angle = 90), legend.text = element_text(family = "serif", size = 10), axis.text = element_text(family = "serif", size = 10), axis.title = element_text(family = "serif", size = 10, face = "bold", colour = "gray20"), legend.title = element_text(size = 10, family = "serif"), plot.background = element_rect(colour = NA, linetype = "solid"), legend.key = element_rect(fill = NA)) + labs(fill = "Intensity") ggsave("Figure/heatmap-biosolid-mlsb.png", width = 4, height = 5) Other %>% group_by(Target_Antibiotic) %>% ggplot() + geom_tile(aes(y = Gene, x = Treatment_Stage, fill = mean)) + scale_y_discrete(limits = rev) + scale_fill_gradient2(low = "turquoise3", high = "orange", mid = "yellow", midpoint = 1000000) + labs(x = "Sample", y = "Gene Name", colour = "Prevalence") + theme_bw(base_size = 10) + theme(panel.grid.major = element_line(colour = "gray80"), panel.grid.minor = element_line(colour = "gray80"), axis.text.x = element_text(angle = 90), legend.text = element_text(family = "serif", size = 10), axis.text = element_text(family = "serif", size = 10), axis.title = element_text(family = "serif", size = 10, face = "bold", colour = "gray20"), legend.title = element_text(size = 10, family = "serif"), plot.background = element_rect(colour = NA, linetype = "solid"), legend.key = element_rect(fill = NA)) + labs(fill = "Intensity") ggsave("Figure/heatmap-biosolid-other.png", width = 4, height = 3) Phenicol %>% group_by(Target_Antibiotic) %>% ggplot() + geom_tile(aes(y = Gene, x = Treatment_Stage, fill = mean)) + scale_y_discrete(limits = rev) + scale_fill_gradient2(low = "turquoise3", high = "orange", mid = "yellow", midpoint = 4e+05) + labs(x = "Sample", y = "Gene Name", colour = "Prevalence") + theme_bw(base_size = 10) + theme(panel.grid.major = element_line(colour = "gray80"), panel.grid.minor = element_line(colour = "gray80"), axis.text.x = element_text(angle = 90), legend.text = element_text(family = "serif", size = 10), axis.text = element_text(family = "serif", size = 10), axis.title = element_text(family = "serif", size = 10, face = "bold", colour = "gray20"), legend.title = element_text(size = 10, family = "serif"), plot.background = element_rect(colour = NA, linetype = "solid"), legend.key = element_rect(fill = NA)) + labs(fill = "Intensity") ggsave("Figure/heatmap-biosolid-phenicol.png", width = 4, height = 2) Quinolone %>% group_by(Target_Antibiotic) %>% ggplot() + geom_tile(aes(y = Gene, x = Treatment_Stage, fill = mean)) + scale_y_discrete(limits = rev) + scale_fill_gradient2(low = "turquoise3", high = "orange", mid = "yellow", midpoint = 1e+10) + labs(x = "Sample", y = "Gene Name", colour = "Prevalence") + theme_bw(base_size = 10) + theme(panel.grid.major = element_line(colour = "gray80"), panel.grid.minor = element_line(colour = "gray80"), axis.text.x = element_text(angle = 90), legend.text = element_text(family = "serif", size = 10), axis.text = element_text(family = "serif", size = 10), axis.title = element_text(family = "serif", size = 10, face = "bold", colour = "gray20"), legend.title = element_text(size = 10, family = "serif"), plot.background = element_rect(colour = NA, linetype = "solid"), legend.key = element_rect(fill = NA)) + labs(fill = "Intensity") ggsave("Figure/heatmap-biosolid-quinolone.png", width = 4, height = 2.5) Sulfonamide %>% group_by(Target_Antibiotic) %>% ggplot() + geom_tile(aes(y = Gene, x = Treatment_Stage, fill = mean)) + scale_y_discrete(limits = rev) + scale_fill_gradient2(low = "turquoise3", high = "orange", mid = "yellow", midpoint = 1e+11) + labs(x = "Sample", y = "Gene Name", colour = "Prevalence") + theme_bw(base_size = 10) + theme(panel.grid.major = element_line(colour = "gray80"), panel.grid.minor = element_line(colour = "gray80"), axis.text.x = element_text(angle = 90), legend.text = element_text(family = "serif", size = 10), axis.text = element_text(family = "serif", size = 10), axis.title = element_text(family = "serif", size = 10, face = "bold", colour = "gray20"), legend.title = element_text(size = 10, family = "serif"), plot.background = element_rect(colour = NA, linetype = "solid"), legend.key = element_rect(fill = NA)) + labs(fill = "Intensity") ggsave("Figure/heatmap-biosolid-sulfonamide.png", width = 4, height = 2.5) Tetracycline %>% group_by(Target_Antibiotic) %>% ggplot() + geom_tile(aes(y = Gene, x = Treatment_Stage, fill = mean)) + scale_y_discrete(limits = rev) + scale_fill_gradient2(low = "turquoise3", high = "orange", mid = "yellow", midpoint = 7e+09) + labs(x = "Sample", y = "Gene Name", colour = "Prevalence") + theme_bw(base_size = 10) + theme(panel.grid.major = element_line(colour = "gray80"), panel.grid.minor = element_line(colour = "gray80"), axis.text.x = element_text(angle = 90), legend.text = element_text(family = "serif", size = 10), axis.text = element_text(family = "serif", size = 10), axis.title = element_text(family = "serif", size = 10, face = "bold", colour = "gray20"), legend.title = element_text(size = 10, family = "serif"), plot.background = element_rect(colour = NA, linetype = "solid"), legend.key = element_rect(fill = NA)) + labs(fill = "Intensity") ggsave("Figure/heatmap-biosolid-tetracycline.png", width = 4, height = 5) Trimethoprim %>% group_by(Target_Antibiotic) %>% ggplot() + geom_tile(aes(y = Gene, x = Treatment_Stage, fill = mean)) + scale_y_discrete(limits = rev) + scale_fill_gradient2(low = "turquoise3", high = "orange", mid = "yellow", midpoint = 7500000) + labs(x = "Sample", y = "Gene Name", colour = "Prevalence") + theme_bw(base_size = 10) + theme(panel.grid.major = element_line(colour = "gray80"), panel.grid.minor = element_line(colour = "gray80"), axis.text.x = element_text(angle = 90), legend.text = element_text(family = "serif", size = 10), axis.text = element_text(family = "serif", size = 10), axis.title = element_text(family = "serif", size = 10, face = "bold", colour = "gray20"), legend.title = element_text(size = 10, family = "serif"), plot.background = element_rect(colour = NA, linetype = "solid"), legend.key = element_rect(fill = NA)) + labs(fill = "Intensity") ggsave("Figure/heatmap-biosolid-trimethoprim.png", width = 4, height = 1) Vancomycin %>% group_by(Target_Antibiotic) %>% ggplot() + geom_tile(aes(y = Gene, x = Treatment_Stage, fill = mean)) + scale_y_discrete(limits = rev) + scale_fill_gradient2(low = "turquoise3", high = "orange", mid = "yellow", midpoint = 2e+08) + labs(x = "Sample", y = "Gene Name", colour = "Prevalence") + theme_bw(base_size = 10) + theme(panel.grid.major = element_line(colour = "gray80"), panel.grid.minor = element_line(colour = "gray80"), axis.text.x = element_text(angle = 90), legend.text = element_text(family = "serif", size = 10), axis.text = element_text(family = "serif", size = 10), axis.title = element_text(family = "serif", size = 10, face = "bold", colour = "gray20"), legend.title = element_text(size = 10, family = "serif"), plot.background = element_rect(colour = NA, linetype = "solid"), legend.key = element_rect(fill = NA)) + labs(fill = "Intensity") ggsave("Figure/heatmap-biosolid-vancomycin.png", width = 4, height = 2)
package main import ( "bufio" "flag" "fmt" "os" "strings" ) /* === Утилита cut === Принимает STDIN, разбивает по разделителю (TAB) на колонки, выводит запрошенные Поддержать флаги: -f - "fields" - выбрать поля (колонки) -d - "delimiter" - использовать другой разделитель -s - "separated" - только строки с разделителем Программа должна проходить все тесты. Код должен проходить проверки go vet и golint. */ type config struct { fields int delimiter string hideWrongLines bool } func parseFlags() config { cfg := config{} flag.IntVar(&cfg.fields, "f", 0, "выбрать поля (колонки)") flag.StringVar(&cfg.delimiter, "d", "\t", "использовать другой разделитель") flag.BoolVar(&cfg.hideWrongLines, "s", true, "только строки с разделителем") flag.Parse() return cfg } func cut(sc *bufio.Scanner, cfg config) { for sc.Scan() { line := sc.Text() if !cfg.hideWrongLines && !strings.Contains(line, cfg.delimiter) { continue } columns := strings.Split(line, cfg.delimiter) if cfg.fields == 0 { fmt.Println(strings.Join(columns, " ")) } else { if len(columns) >= cfg.fields { fmt.Println(columns[cfg.fields-1]) } } } } func main() { cfg := parseFlags() sc := bufio.NewScanner(os.Stdin) cut(sc, cfg) }
// Hunter Game by Gamer Guru. #include "Character/BaseCharacter.h" #include "EnhancedInputSubsystems.h" #include "Components/InputComponent.h" #include "EnhancedInputComponent.h" #include "InputAction.h" #include "Actor/WeaponAmmo/WeaponAmmo.h" #include "Camera/CameraComponent.h" #include "Component/CombatComponent.h" #include "Component/FinanceComponent.h" #include "Component/InteractionComponent.h" #include "Component/InventoryComponent.h" #include "Component/PhysicalAnimation_C_Component.h" #include "Component/StatsComponent.h" #include "Components/CapsuleComponent.h" #include "GameFramework/CharacterMovementComponent.h" #include "GameFramework/SpringArmComponent.h" #include "Kismet/KismetMathLibrary.h" #include "Net/UnrealNetwork.h" #include "PlayerController/HunterPlayerController.h" #include "Weapon/Weapon.h" ABaseCharacter::ABaseCharacter() { PrimaryActorTick.bCanEverTick = true; bReplicates = true; NetUpdateFrequency = 66.f; // How many times variables are replicated from server to client per sec. MinNetUpdateFrequency = 33.f; // The min net update frequency to be if the variables are not changing frequently. Tags.AddUnique(FName("Character")); Tags.AddUnique(FName("Human")); Tags.AddUnique(FName("BaseCharacter")); Tags.AddUnique(FName("PlayerTeam")); GetCapsuleComponent()->SetCollisionResponseToChannel(ECollisionChannel::ECC_Camera, ECollisionResponse::ECR_Ignore); GetMesh()->SetCollisionResponseToChannel(ECollisionChannel::ECC_Camera, ECollisionResponse::ECR_Ignore); CameraBoom = CreateDefaultSubobject<USpringArmComponent>(TEXT("Camera Boom")); CameraBoom->SetupAttachment(GetMesh()); CameraBoom->TargetArmLength = CAMERA_BOOM_TP_TARGET_ARM_LENGTH; TP_ViewCamera = CreateDefaultSubobject<UCameraComponent>(TEXT("Third Person View Camera")); TP_ViewCamera->SetupAttachment(CameraBoom); FP_ViewCamera = CreateDefaultSubobject<UCameraComponent>(TEXT("First Person Camera")); FP_ViewCamera->SetupAttachment(GetMesh()), FName("head"); FP_ViewCamera->bUsePawnControlRotation = true; FP_ViewCamera->SetAutoActivate(false); bUseControllerRotationPitch = true; bUseControllerRotationYaw = true; bUseControllerRotationRoll = false; GetCharacterMovement()->bOrientRotationToMovement = true; GetCharacterMovement()->RotationRate = FRotator(0.f, 285.f, 0.f); GetCharacterMovement()->NavAgentProps.bCanCrouch = true; GetCharacterMovement()->MaxWalkSpeed = RunSpeed; CharacterMovementState = ECharacterMovementState::ECMS_Running; CombatComponent = CreateDefaultSubobject<UCombatComponent>(TEXT("Combat Component")); InteractionComponent = CreateDefaultSubobject<UInteractionComponent>(TEXT("Interaction Component")); InventoryComponent = CreateDefaultSubobject<UInventoryComponent>(TEXT("Inventory Component")); FinanceComponent = CreateDefaultSubobject<UFinanceComponent>(TEXT("Finance Component")); StatsComponent = CreateDefaultSubobject<UStatsComponent>(TEXT("Stats Component")); PhysicalAnimationComponent = CreateDefaultSubobject<UPhysicalAnimation_C_Component>(TEXT("Physical Animation Component")); } void ABaseCharacter::BeginPlay() { Super::BeginPlay(); if (const APlayerController* PlayerController = Cast<APlayerController>(GetController())) { if (UEnhancedInputLocalPlayerSubsystem* EnhancedInputLocalPlayerSubsystem = ULocalPlayer::GetSubsystem<UEnhancedInputLocalPlayerSubsystem>(PlayerController->GetLocalPlayer())) { EnhancedInputLocalPlayerSubsystem->AddMappingContext(BaseInputMappingContext, 1); } } HunterPlayerController = HunterPlayerController == nullptr ? Cast<AHunterPlayerController>(GetController()) : HunterPlayerController; UpdateHUDHealth(); if (HasAuthority()) // Bind Receive Damage to OnTakeAnyDamage only on the server { OnTakeAnyDamage.AddDynamic(this, &ABaseCharacter::ReceiveDamage); } } void ABaseCharacter::Tick(float DeltaTime) { Super::Tick(DeltaTime); if (CombatComponent && CombatComponent->WeaponInHand) { AimOffset(DeltaTime); } } void ABaseCharacter::GetLifetimeReplicatedProps(TArray<FLifetimeProperty>& OutLifetimeProps) const { Super::GetLifetimeReplicatedProps(OutLifetimeProps); DOREPLIFETIME(ABaseCharacter, bOrientRotationToMovement_WhenInCombat); } void ABaseCharacter::PostInitializeComponents() { Super::PostInitializeComponents(); if (InteractionComponent) {InteractionComponent->PlayerCharacter = this;} if (CombatComponent) {CombatComponent->HunterCharacter = this;} if (InventoryComponent) { InventoryComponent->InitInventory(); InventoryComponent->OnInventoryUpdated.AddDynamic(this, &ABaseCharacter::OnInventoryUpdated); } if (StatsComponent) { StatsComponent->OwnerHuman = this; StatsComponent->Init_Attributes(); } if (PhysicalAnimationComponent) { PhysicalAnimationComponent->SetOwnerCharacter(this); } } void ABaseCharacter::SetupPlayerInputComponent(UInputComponent* PlayerInputComponent) { Super::SetupPlayerInputComponent(PlayerInputComponent); if (UEnhancedInputComponent* EnhancedInputComponent = Cast<UEnhancedInputComponent>(PlayerInputComponent)) { EnhancedInputComponent->BindAction(MoveAction, ETriggerEvent::Triggered,this, &ABaseCharacter::Move); EnhancedInputComponent->BindAction(LookAction, ETriggerEvent::Triggered, this, &ABaseCharacter::Look); EnhancedInputComponent->BindAction(JumpAction, ETriggerEvent::Started, this, &ABaseCharacter::Jump); EnhancedInputComponent->BindAction(CrouchAction, ETriggerEvent::Started, this, &ABaseCharacter::CrouchButtonPressed); EnhancedInputComponent->BindAction(InteractAction, ETriggerEvent::Started, this,&ABaseCharacter::InteractButtonPressed); EnhancedInputComponent->BindAction(AimAction, ETriggerEvent::Started, this, &ABaseCharacter::AimButtonPressed); EnhancedInputComponent->BindAction(AimAction, ETriggerEvent::Completed, this, &ABaseCharacter::AimButtonReleased); EnhancedInputComponent->BindAction(ShootAction, ETriggerEvent::Started, this, &ABaseCharacter::ShootButtonPressed); EnhancedInputComponent->BindAction(ShootAction, ETriggerEvent::Completed, this, &ABaseCharacter::ShootButtonReleased); EnhancedInputComponent->BindAction(ChangeCameraModeAction, ETriggerEvent::Started, this, &ABaseCharacter::ChangeCameraMode); EnhancedInputComponent->BindAction(TogglePrimaryWeaponAction, ETriggerEvent::Started, this, &ABaseCharacter::TogglePrimaryWeaponButtonPressed); EnhancedInputComponent->BindAction(ToggleSecondaryWeaponAction, ETriggerEvent::Started, this, &ABaseCharacter::ToggleSecondaryWeaponButtonPressed); EnhancedInputComponent->BindAction(ReloadAction, ETriggerEvent::Started, this, &ABaseCharacter::ReloadButtonPressed); EnhancedInputComponent->BindAction(ToggleInventoryAction, ETriggerEvent::Started, this, &ABaseCharacter::ToggleInventoryButtonPressed); EnhancedInputComponent->BindAction(RunAction, ETriggerEvent::Started, this, &ABaseCharacter::SprintButtonPressed); EnhancedInputComponent->BindAction(RunAction, ETriggerEvent::Completed, this, &ABaseCharacter::SprintButtonReleased); EnhancedInputComponent->BindAction(WalkAction, ETriggerEvent::Started, this, &ABaseCharacter::WalkButtonPressed); } } /** Interface **/ void ABaseCharacter::GetHit(FName HitBoneName, FVector HitBoneLocation) { GEngine->AddOnScreenDebugMessage(-1, 20.f, FColor::Cyan, HitBoneName.ToString()); //if (GEngine) {GEngine->AddOnScreenDebugMessage(-1, 5.f, FColor::Green, FString("Hit"));} } USkinnedMeshComponent* ABaseCharacter::GetCharacterMesh() { return GetMesh(); } void ABaseCharacter::UpdateUIHealth() { UpdateHUDHealth(); } /** Interface **/ /** Generic **/ void ABaseCharacter::PlayAnimationMontage(UAnimMontage* Montage, FName SectionName, bool bJumpToSection) { if (Montage == nullptr) return; if (UAnimInstance* AnimInstance = GetMesh()->GetAnimInstance()) { AnimInstance->Montage_Play(Montage); if (bJumpToSection) { AnimInstance->Montage_JumpToSection(SectionName); } } } /** Generic **/ /** Input CallBacks **/ void ABaseCharacter::Move(const FInputActionValue& Value) { if (!Controller || GetCharacterMovement()->IsFalling()) return; const FVector2d InputValue = Value.Get<FVector2d>(); const FRotator YawRotation = FRotator(0.f, GetControlRotation().Yaw, 0.f); if (InputValue.Y != 0.f) { const FVector ForwardDirection = FRotationMatrix(YawRotation).GetUnitAxis(EAxis::X); AddMovementInput(ForwardDirection, InputValue.Y); } if (InputValue.X != 0.f) { const FVector RightDirection = FRotationMatrix(YawRotation).GetUnitAxis(EAxis::Y); AddMovementInput(RightDirection, InputValue.X); } } void ABaseCharacter::Look(const FInputActionValue& Value) { if (!Controller) return; const FVector2d InputValue = Value.Get<FVector2d>() * HunterPlayerController->GetLookSensitivity(); if (InputValue.X != 0.f) {AddControllerYawInput(InputValue.X);} if (InputValue.Y != 0.f) {AddControllerPitchInput(InputValue.Y);} } void ABaseCharacter::Jump() { if (!Controller) return; ACharacter::Jump(); } void ABaseCharacter::CrouchButtonPressed() { if (!Controller || GetCharacterMovement()->IsFalling()) return; if (!bIsCrouched) {ACharacter::Crouch();} if (bIsCrouched) {ACharacter::UnCrouch();} } void ABaseCharacter::InteractButtonPressed() { if (!InteractionComponent) return; InteractionComponent->Interact(); } void ABaseCharacter::AimButtonPressed() { if (CombatComponent == nullptr || CombatComponent->GetWeaponInHand() == nullptr) return; CombatComponent->SetAiming(true); } void ABaseCharacter::AimButtonReleased() { if (!CombatComponent || CombatComponent->GetWeaponInHand() == nullptr) return; CombatComponent->SetAiming(false); } void ABaseCharacter::ShootButtonPressed() { if (GetCharacterMovement()->IsFalling()) return; if (CombatComponent) { CombatComponent->ShootButtonPressed(true); } } void ABaseCharacter::ShootButtonReleased() { if (CombatComponent) { CombatComponent->ShootButtonPressed(false); } } void ABaseCharacter::ChangeCameraMode() { if (CurrentCameraMode == ECameraMode::ECM_ThirdPerson) { bOrientRotationToMovement_WhenInCombat = false; CurrentCameraMode = ECameraMode::ECM_SemiFirstPerson; CameraBoom->TargetArmLength = CAMERA_BOOM_SFP_TARGET_ARM_LENGTH; CameraBoom->SocketOffset = CameraBoomSocketOffset_SFP; TP_ViewCamera->SetActive(true); FP_ViewCamera->SetActive(false); } else if (CurrentCameraMode == ECameraMode::ECM_SemiFirstPerson) { bOrientRotationToMovement_WhenInCombat = false; CurrentCameraMode = ECameraMode::ECM_FirstPerson; FP_ViewCamera->SetActive(true); TP_ViewCamera->SetActive(false); } else if (CurrentCameraMode == ECameraMode::ECM_FirstPerson) { bOrientRotationToMovement_WhenInCombat = true; CurrentCameraMode = ECameraMode::ECM_ThirdPerson; CameraBoom->TargetArmLength = CAMERA_BOOM_TP_TARGET_ARM_LENGTH; CameraBoom->SocketOffset = CameraBoomSocketOffset_TP; TP_ViewCamera->SetActive(true); FP_ViewCamera->SetActive(false); } } void ABaseCharacter::TogglePrimaryWeaponButtonPressed() { if (!CombatComponent) return; CombatComponent->OnTogglePrimaryWeaponButtonPressed(); } void ABaseCharacter::ToggleSecondaryWeaponButtonPressed() { if (!CombatComponent) return; CombatComponent->OnToggleSecondaryWeaponButtonPressed(); } void ABaseCharacter::ReloadButtonPressed() { if (!CombatComponent) return; CombatComponent->Reload(); } void ABaseCharacter::ToggleInventoryButtonPressed() { if (HunterPlayerController == nullptr) return; HunterPlayerController->ToggleInventory(); } void ABaseCharacter::SprintButtonPressed() { if (CombatComponent == nullptr || GetCharacterMovement() == nullptr) return; if (CombatComponent->bIsAiming) return; GetCharacterMovement()->MaxWalkSpeed = IsCombatEnabled() && GetEquippedWeapon() != nullptr ? InCombatSprintSpeed : SprintSpeed; GetCharacterMovement()->RotationRate = FRotator(0.f, 180.f, 0.f); CharacterMovementState = ECharacterMovementState::ECMS_Sprinting; } void ABaseCharacter::SprintButtonReleased() { if (CombatComponent == nullptr || GetCharacterMovement() == nullptr) return; if (CombatComponent->bIsAiming) return; GetCharacterMovement()->MaxWalkSpeed = RunSpeed; GetCharacterMovement()->RotationRate = FRotator(0.f, 285.f, 0.f); CharacterMovementState = ECharacterMovementState::ECMS_Running; } void ABaseCharacter::WalkButtonPressed() { if (CharacterMovementState != ECharacterMovementState::ECMS_Walking) { GetCharacterMovement()->MaxWalkSpeed = WalkSpeed; GetCharacterMovement()->RotationRate = FRotator(0.f, 300.f, 0.f); CharacterMovementState = ECharacterMovementState::ECMS_Walking; } else { GetCharacterMovement()->MaxWalkSpeed = RunSpeed; GetCharacterMovement()->RotationRate = FRotator(0.f, 285.f, 0.f); CharacterMovementState = ECharacterMovementState::ECMS_Running; } } /** Input CallBacks **/ /** Event Trigger CallBacks **/ void ABaseCharacter::OnInventoryUpdated() { if (CombatComponent) {CombatComponent->OnInventoryUpdated();} } /** Event Trigger CallBacks **/ /** Stats **/ void ABaseCharacter::UpdateHUDHealth() { if (HunterPlayerController) { HunterPlayerController->SetHUDHealth(StatsComponent->Health_Data.CurrentValue, StatsComponent->MaxHealth_Data.CurrentValue); } } /** Stats **/ /** Combat **/ void ABaseCharacter::ReceiveDamage(AActor* DamagedActor, float Damage, const UDamageType* DamageType, AController* InstigatorController, AActor* DamageCauser) { if (StatsComponent) { StatsComponent->Health_Data.CurrentValue = FMath::Clamp( StatsComponent->Health_Data.CurrentValue - Damage, 0.f, StatsComponent->MaxHealth_Data.CurrentValue); UpdateUIHealth(); if (StatsComponent->Health_Data.CurrentValue <= 0) { //Death(); } } } void ABaseCharacter::AimOffset(float DeltaTime) { if (CombatComponent == nullptr || CombatComponent->GetWeaponInHand() == nullptr) return; if (bOrientRotationToMovement_WhenInCombat == true && CombatComponent->bIsAiming == false) return; FVector Velocity = GetVelocity(); Velocity.Z = 0.f; const float Speed = Velocity.Size(); const bool bIsInAir = GetCharacterMovement()->IsFalling(); // Aim Offset Yaw if (Speed == 0.f && !bIsInAir) // Standing still, not Jumping { const FRotator CurrentAimRotation = FRotator(0.f, GetBaseAimRotation().Yaw, 0.f); const FRotator DeltaAimRotation = UKismetMathLibrary::NormalizedDeltaRotator(CurrentAimRotation, StartingAimRotation); AO_Yaw = DeltaAimRotation.Yaw; if (TurningInPlace == ETurningInPlace::ETIP_NotTurning) { InterpAO_Yaw = AO_Yaw; } bUseControllerRotationYaw = true; TurnInPlace(DeltaTime); // Checking turn in place if standing still and not jumping } if (Speed > 0.f || bIsInAir) // Running or Jumping { StartingAimRotation = FRotator(0.f, GetBaseAimRotation().Yaw, 0.f); AO_Yaw = 0.f; bUseControllerRotationYaw = true; TurningInPlace = ETurningInPlace::ETIP_NotTurning; // Should not turn in place if running or jumping. } // Aim Offset Pitch AO_Pitch = GetBaseAimRotation().Pitch; if (AO_Pitch > 90.f && !IsLocallyControlled()) { // Map Pitch from [270, 360) to [-90, 0) const FVector2d InRange(270.f, 360.f); const FVector2d OutRange(-90.f, 0.f); AO_Pitch = FMath::GetMappedRangeValueClamped(InRange, OutRange, AO_Pitch); } } void ABaseCharacter::TurnInPlace(float DeltaTime) { // Turn in place based on the aim offset yaw value. if (AO_Yaw > 90.f) { TurningInPlace = ETurningInPlace::ETIP_Right; } else if (AO_Yaw < -90.f) { TurningInPlace = ETurningInPlace::ETIP_Left; } if (AO_Yaw > 45.f) { if (!CombatComponent) return; if (CombatComponent->bIsAiming) {TurningInPlace = ETurningInPlace::ETIP_Right;} } else if (AO_Yaw < -45.f) { if (!CombatComponent) return; if (CombatComponent->bIsAiming) {TurningInPlace = ETurningInPlace::ETIP_Left;} } if (TurningInPlace != ETurningInPlace::ETIP_NotTurning) { InterpAO_Yaw = FMath::FInterpTo(InterpAO_Yaw, 0.f, DeltaTime, 4.f); AO_Yaw = InterpAO_Yaw; if (FMath::Abs(AO_Yaw) < 15.f) { TurningInPlace = ETurningInPlace::ETIP_NotTurning; StartingAimRotation = FRotator(0.f, GetBaseAimRotation().Yaw, 0.f); } } } int32 ABaseCharacter::GetAmmoInInventory() const { if (CombatComponent == nullptr || CombatComponent->bIsCombatEnabled == false) return 0; if (CombatComponent->GetWeaponInHand() == nullptr) return 0; if (InventoryComponent == nullptr) return 0; int32 Local_InInventoryAmmo = 0; for (FSlotData Slot : InventoryComponent->GetContent()) { if (CombatComponent->GetWeaponInHand()->GetWeaponAmmoClass() == Slot.ItemData.ItemClass) { Local_InInventoryAmmo = Local_InInventoryAmmo + Slot.Quantity; } } return Local_InInventoryAmmo; } bool ABaseCharacter::RemoveAmmoFromInventory(int32 AmountOfAmmoToRemove) { if (CombatComponent == nullptr || InventoryComponent == nullptr) return false; int Local_Index = 0; for (FSlotData Slot : InventoryComponent->GetContent()) { if (CombatComponent->GetWeaponInHand()->GetWeaponAmmoClass() == Slot.ItemData.ItemClass) { int32 ElementsRemoved = InventoryComponent->RemoveItemFromSlot(Local_Index, AmountOfAmmoToRemove); if (AmountOfAmmoToRemove > ElementsRemoved) { // TODO: Resolve Issue -> Calling RemoveAmmoFromInventory creates a infinite loop (Creates a infinite loop only if inventory is full) //RemoveAmmoFromInventory(AmountOfAmmoToRemove - ElementsRemoved); } return true; // Return so it doesn't remove ammo from every stack of ammo in the inventory } Local_Index++; } return false; } void ABaseCharacter::OnReloadEnd_AnimNotifyCallBack() { if (!CombatComponent) return;; CombatComponent->OnReloadEnd(); } void ABaseCharacter::TogglePrimaryWeapon_AnimNotifyCallBack() { if (!CombatComponent) return; CombatComponent->TogglePrimaryWeaponAttachment(); } void ABaseCharacter::ToggleSecondaryWeapon_AnimNotifyCallBack() { if (!CombatComponent) return; CombatComponent->ToggleSecondaryWeaponAttachment(); } /** Combat **/ void ABaseCharacter::Death() { PlayAnimationMontage(DeathMontage, FName(), false); HunterPlayerController->OnDeath(); } /** Interaction **/ int32 ABaseCharacter::AddItemToInventory(FItemData ItemData) { if (!InventoryComponent) return -1; int32 Local_Remaining = InventoryComponent->AddItemToInventory(ItemData); return Local_Remaining; } void ABaseCharacter::OnPlayerInteractWithAnimal(UAnimMontage* PlayerInteractAnimMontage) { if (InteractionComponent) { InteractionComponent->OnPlayerInteractWithAnimal(PlayerInteractAnimMontage);; } } /** Interaction **/ /** UI **/ void ABaseCharacter::HideCharacterOverlayUI() { if (HunterPlayerController == nullptr) return; HunterPlayerController->HideCharacterOverlayUI(); } void ABaseCharacter::ShowCharacterOverlayUI() { if (HunterPlayerController == nullptr) return; HunterPlayerController->ShowCharacterOverlayUI(); } /** UI **/ /** Animation **/ void ABaseCharacter::PlayShootMontage(bool bAiming) { if (CombatComponent == nullptr || CombatComponent->GetWeaponInHand() == nullptr || GetEquippedWeapon() == nullptr) return; UAnimInstance* AnimInstance = GetMesh()->GetAnimInstance(); if (AnimInstance && GetEquippedWeapon()->WeaponShootMontage) { AnimInstance->Montage_Play(GetEquippedWeapon()->WeaponShootMontage); FName SectionName = bAiming ? FName("Aim") : FName("Hip"); // Choose section name based on bAiming; AnimInstance->Montage_JumpToSection(SectionName, GetEquippedWeapon()->WeaponShootMontage); //PlayAnimationMontage(GetEquippedWeapon()->WeaponShootMontage, SectionName, true); } } /** Animation **/ /** Getter / Setter **/ AWeapon* ABaseCharacter::GetEquippedWeapon() const { if (!CombatComponent) return nullptr; return CombatComponent->GetWeaponInHand(); } bool ABaseCharacter::IsCombatEnabled() const { return CombatComponent && CombatComponent->bIsCombatEnabled; } bool ABaseCharacter::IsAiming() const { return CombatComponent && CombatComponent->bIsAiming; } FVector ABaseCharacter::GetHitTarget() const { if (!CombatComponent) return FVector(); return CombatComponent->HitTarget; } ECombatState ABaseCharacter::GetCombatState() const { if (!CombatComponent) return ECombatState::ECS_Max; return CombatComponent->CombatState; } AActor* ABaseCharacter::GetInteractionTargetActor() const { if (InteractionComponent) { return InteractionComponent->GetInteractionTargetActor(); } return nullptr; } bool ABaseCharacter::CanBuyItem(FItemData ItemData) const { if (!InventoryComponent || !FinanceComponent) return false; return FinanceComponent->CanBuyItem(ItemData.Cost) && InventoryComponent->SpaceAvailable(ItemData); } void ABaseCharacter::SetOverlappingActor(AActor* InOverlappingActor) { if (!InteractionComponent) return; InteractionComponent->SetOverlappingActor(InOverlappingActor); } void ABaseCharacter::SetInteractionTargetActor(AActor* InTargetActor) { if (InteractionComponent) { InteractionComponent->SetInteractionTargetActor(InTargetActor); } } /** Getter / Setter **/
<!DOCTYPE html> <html> <head> <!-- This title is used for tabs and bookmarks --> <title>Lab 3 - File Structure and Files</title> <!-- Use UTF character set, a good idea with any webpage --> <meta charset="UTF-8" /> <!-- Set viewport so page remains consistently scaled w narrow devices --> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <!-- Include a sitewide CSS file for consistent styling across the site --> <link rel="stylesheet" type="text/css" href="../css/site.css"> <!-- Lab-specifc CSS file for any special styling of this particular page --> <link rel="stylesheet" type="text/css" href="css/lab.css"> <!-- load jQuery library to make javascript easier (must be above our lab js)--> <script src="https://code.jquery.com/jquery-3.6.4.min.js"></script> <!-- Link to javascript file - DEFER waits until all elements are rendered --> <script type="text/javascript" src="./js/lab.js" DEFER></script> </head> <body> <!-- Style this page by changing the CSS in ../css/site.css or css/lab.css --> <main id="content"> <section> <h1>Lab 3 - File Structure and Files</h1> <p>Navigate among files, and create links within the file structure.</p> <div class="minor-section"> <h2>Challenge</h2> <p>As someone with a background in CS, nothing stood out as super challenging, but I remember that the first time I attempted this, it was definitely difficult to follow all the implicit coding 'rules' like "no spaces", "make sure you're telling the computer exactly what it needs to do", that would pull up so many frustrating errors. I took all of this into account when I was helping my partner with the assignment.</p> </div> <div class="minor-section"> <h2>Problems</h2> <p>Some problems that arose were getting the right filepath and getting images to fit in boxes. </p> </div> <div class="minor-section"> <h2>Reflection</h2> <p>I've found that the best way to learn HTML and CSS is to try things willy-nilly and learn all the possible interactions by trial-and-error. This will often serve helpful later, when one thing I accidentally found turns out to actually have been useful. </p> </div> <div class="minor-section"> <h2>Results</h2> <div id="output"></div> <img class="screenshot" src="img/list_source_code.png" alt="this is a screenshot of source code showing html of the list"> <p>this is a screenshot of source code showing html of the list</p> <img class="screenshot" src="img/page_source_code.png" alt="this is a screenshot of source code showing html of the website lab3"> <p>this is a screenshot of source code showing html of the website lab3</p> <img class="screenshot" src="img/page_site.png" alt="this is a screenshot of source code showing resulting website of lab3"> <p>this is a screenshot of source code showing resulting website of lab3</p> </div> </section> <nav id="links"> <ul> <li><a href="../index.html">Home</a></li> <li><a href="../lab2/index.html">Lab 2</a></li> <li><a href="../lab4/index.html">Lab 4</a></li> <li><a href="../lab5/index.html">Lab 5</a></li> <li><a href="../lab6/index.html">Lab 6</a></li> </ul> </nav> </main> </body> </html>
package deb import ( "io" "strings" "testing" "github.com/stretchr/testify/assert" ) const packages = ` Package: zip Priority: optional Section: utils Installed-Size: 100 Package: unzip Priority: optional Section: utils Installed-Size: 100 ` const contents = ` bin/afio utils/afio bin/bash shells/bash bin/bash-static shells/bash-static bin/brltty admin/brltty bin/bsd-csh shells/csh bin/btrfs admin/btrfs-progs bin/btrfs-convert admin/btrfs-progs bin/btrfs-find-root admin/btrfs-progs bin/btrfs-image admin/btrfs-progs bin/btrfs-map-logical admin/btrfs-progs ` func TestPackageReader(t *testing.T) { r := strings.NewReader(packages) reader := NewPackageReader(r) var packages []Package for { pack, err := reader.Next() if err == io.EOF { break } if err != nil { assert.Fail(t, err.Error()) } packages = append(packages, pack) } assert.Equal(t, "zip", packages[0].Name) assert.Equal(t, "unzip", packages[1].Name) } func TestContentsReader(t *testing.T) { r := strings.NewReader(contents) reader := NewContentsReader(r) var contents []Contents for { entry, err := reader.Next() if err == io.EOF { break } if err != nil { assert.Fail(t, err.Error()) } contents = append(contents, entry) } assert.Equal(t, "bin/afio", contents[0].File) assert.Equal(t, "bin/bash", contents[1].File) assert.Equal(t, []string{"utils/afio"}, contents[0].Packages) assert.Equal(t, []string{"shells/bash"}, contents[1].Packages) }
#pragma once #include <unordered_map> #include <string> #include <memory> template<typename T> class AssetCache { public: ~AssetCache() { m_assets.clear(); } void add(const std::string& name, const std::shared_ptr<T>& asset) { m_assets.emplace(std::make_pair(name, asset)); } std::weak_ptr<T> get(const std::string& name) { return m_assets[name]; } void remove(const std::string& name) { if (exists(name)) { m_assets.erase(m_assets.find(name)); } } bool exists(const std::string& name) { return m_assets.find(name) != m_assets.end(); } void flush() { m_assets.clear(); } std::unordered_map<std::string, std::shared_ptr<T>>& get_internal_list() { return m_assets; } private: std::unordered_map<std::string, std::shared_ptr<T>> m_assets; }; class Texture; class Shader; class AudioBuffer; class Material; class Scene; class AssetManager { public: static AssetManager* get_instance() { static AssetManager manager; return &manager; } void flush(); void load_asset_folder(const std::string& path); AssetCache<Material>& get_material_cache() { return m_materials; } AssetCache<Scene>& get_scene_cache() { return m_scenes; } std::weak_ptr<Texture> get_texture(const std::string& path); std::weak_ptr<Shader> get_shader(const std::string& path); std::weak_ptr<AudioBuffer> get_audio_buffer(const std::string& path); std::weak_ptr<Material> get_material(const std::string& name); std::weak_ptr<Scene> get_scene(const std::string& name); std::weak_ptr<Material> create_material(const std::string& name); std::weak_ptr<Scene> create_scene(const std::string& name); private: AssetCache<Texture> m_textures; AssetCache<Shader> m_shaders; AssetCache<AudioBuffer> m_audio_buffers; AssetCache<Material> m_materials; AssetCache<Scene> m_scenes; };
@page @model IndexModel @{ ViewData["Title"] = "Profile"; ViewData["ActivePage"] = ManageNavPages.Index; } <h4>@ViewData["Title"]</h4> <partial name="_StatusMessage" model="Model.StatusMessage" /> <div class="row"> <div class="col-md-6"> <form enctype="multipart/form-data" id="profile-form" method="post"> <div asp-validation-summary="ModelOnly" class="text-danger"></div> <div class="form-group"> <img src="data:image/png;base64,@Model.OldProfilePicture" alt="Red dot" class="rounded-circle" height="150" width="150" /> </div> <div class="form-group"> <label>Change Profile Picture</label> <input type="file" asp-for="Input.NewProfilePicture" class="form-control"> </div> <div class="form-group"> <label asp-for="Username"></label> <input asp-for="Username" class="form-control" disabled /> </div> <div class="form-group"> <label asp-for="Input.FirstName"></label> <input asp-for="Input.FirstName" class="form-control" /> <span asp-validation-for="Input.FirstName" class="text-danger"></span> </div> <div class="form-group"> <label asp-for="Input.LastName"></label> <input asp-for="Input.LastName" class="form-control" /> <span asp-validation-for="Input.LastName" class="text-danger"></span> </div> <div class="form-group"> <label asp-for="Input.DateOfBirth"></label> <input type="date" asp-for="Input.DateOfBirth" class="form-control" /> <span asp-validation-for="Input.DateOfBirth" class="text-danger"></span> </div> <div class="form-group"> <label asp-for="Input.PhoneNumber"></label> <input asp-for="Input.PhoneNumber" class="form-control" /> <span asp-validation-for="Input.PhoneNumber" class="text-danger"></span> </div> <div class="form-group"> <label asp-for="Input.Address"></label> <input asp-for="Input.Address" class="form-control" /> <span asp-validation-for="Input.Address" class="text-danger"></span> </div> <div class="form-group"> <div class="checkbox" > <label asp-for="Input.GenderMale"> <input asp-for="Input.GenderMale" /> @Html.DisplayNameFor(m => m.Input.GenderMale) </label> </div> </div> <div class="form-group"> <div class="checkbox"> <label asp-for="Input.GenderFemale"> <input asp-for="Input.GenderFemale" /> @Html.DisplayNameFor(m => m.Input.GenderFemale) </label> </div> </div> <button id="update-profile-button" type="submit" class="btn btn-primary">Save</button> </form> </div> </div> @section Scripts { <partial name="_ValidationScriptsPartial" /> }
package com.tanchengjin.oauth2.gateway.conf; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.core.io.buffer.DataBuffer; import org.springframework.core.io.buffer.DataBufferUtils; import org.springframework.http.HttpHeaders; import org.springframework.http.HttpStatus; import org.springframework.http.MediaType; import org.springframework.security.core.AuthenticationException; import org.springframework.security.web.server.ServerAuthenticationEntryPoint; import org.springframework.stereotype.Component; import org.springframework.web.server.ServerWebExchange; import reactor.core.publisher.Mono; import java.nio.charset.StandardCharsets; /** * Token认证失败、超时等错误相应处理 * * @Author TanChengjin * @Email [email protected] * @Since V1.0.0 **/ @Component public class AccessAuthenticationEntryPoint implements ServerAuthenticationEntryPoint { private final static Logger logger = LoggerFactory.getLogger(AccessAuthenticationEntryPoint.class); @Override public Mono<Void> commence(ServerWebExchange serverWebExchange, AuthenticationException e) { return Mono.defer(() -> Mono.just(serverWebExchange.getResponse())) .flatMap(response -> { logger.error(e.getMessage()); response.getHeaders().set(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE); response.getHeaders().set("Access-Control-Allow-Origin","*"); response.getHeaders().set("Cache-Control","no-cache"); response.setStatusCode(HttpStatus.UNAUTHORIZED); String body = "{\"code\":401,\"msg\":\"token不合法或过期\"}"; DataBuffer buffer = response.bufferFactory().wrap(body.getBytes(StandardCharsets.UTF_8)); return response.writeWith(Mono.just(buffer)) .doOnError(error -> DataBufferUtils.release(buffer)); }); } }
using TorchSharp; using static TorchSharp.torch; namespace BayesianNetwork.Inference.Naive; public class NetworkWithMultipleParents_NoneObserved { private Node _Q1, _Q2, _Y; private NaiveInferenceMachine _sut; [SetUp] public void Setup() { torch.set_default_dtype(torch.float64); _Q1 = new Node(cpt: Helpers.GenerateRandomProbabilityMatrix([2]), name: "Q1"); _Q2 = new Node(cpt: Helpers.GenerateRandomProbabilityMatrix([2, 2]), parents: [_Q1], name: "Q2"); _Y = new Node(cpt: Helpers.GenerateRandomProbabilityMatrix([2, 2, 2]), parents: [_Q1, _Q2], name: "Y"); BayesianNetwork bayesianNetwork = new(nodes: [_Q1, _Q2, _Y]); _sut = new NaiveInferenceMachine(bayesianNetwork); } [Test] public void InferSingleNode_NoObservations_CorrectInference() { // Assign Tensor pQ1_expected = torch.einsum("i->i", _Q1.Cpt); Tensor pQ2_expected = torch.einsum("i, ij->j", _Q1.Cpt, _Q2.Cpt); Tensor pY_expected = torch.einsum("i, ij, ijk->k", _Q1.Cpt, _Q2.Cpt, _Y.Cpt); // Act Tensor pQ1_actual = _sut.Infer(_Q1); Tensor pQ2_actual = _sut.Infer(_Q2); Tensor pY_actual = _sut.Infer(_Y); // Assert Assert.Multiple(() => { Helpers.AssertTensorEqual(pQ1_expected, pQ1_actual); Helpers.AssertTensorEqual(pQ2_expected, pQ2_actual); Helpers.AssertTensorEqual(pY_expected, pY_actual); }); } [Test] public void InferSingleNodeWithParents_NoObservations_CorrectInference() { // Assign Tensor pQ1xQ2_expected = torch.einsum("i, ij->ij", _Q1.Cpt, _Q2.Cpt); Tensor pQ1xQ2xY_expected = torch.einsum("i, ij, ijk->ijk", _Q1.Cpt, _Q2.Cpt, _Y.Cpt); // Act Tensor pQ1xQ2_actual = _sut.Infer(_Q2, includeParents: true); Tensor pQ1xQ2xY_actual = _sut.Infer(_Y, includeParents: true); // Assert Assert.Multiple(() => { Helpers.AssertTensorEqual(pQ1xQ2_expected, pQ1xQ2_actual); Helpers.AssertTensorEqual(pQ1xQ2xY_expected, pQ1xQ2xY_actual); }); } }
# Web Spider ## Overview This PHP-based web spider is designed to systematically crawl websites, extract information, and perform content searches. The project includes a simple user interface for entering seed URLs and adheres to ethical crawling guidelines. Optional features such as depth control, concurrency, and advanced search capabilities are provided for enhanced functionality. ## Features - **URL Queue:** Maintain a queue of URLs to be crawled, starting with a seed URL. - **Crawling:** Send HTTP requests to URLs, retrieve HTML content, and save it. - **HTML Parsing:** Extract relevant information from crawled pages using PHP's DOMDocument. - **URL Extraction:** Extract hyperlinks from crawled HTML and add them to the URL queue. - **Depth Limit:** Set a depth limit to control spider's crawling depth. - **Output:** Display/log extracted information like title, meta description, etc. - **Content Search Module:** Search for a specified string within crawled content. - **Robots.txt Compliance:** Respect rules specified in the robots.txt file of the website. - **Error Handling:** Implement error handling for fetching, parsing, and other issues. - **Bonus (Attempted):** - **Concurrency:** Explore and implement concurrency for improved performance. - **Filtering:** Exclude certain URLs from crawling based on specific criteria. - **Persistent Storage:** Store crawled data persistently, e.g., in a local database. - **Advanced Search Features:** Extend search module with advanced features. ## Usage 1. Clone the repository: `git clone https://github.com/Me-AU/web-crawler.git` 2. Navigate to the project directory: `cd web-crawler` 3. Open `index.html` in a web browser and enter the seed URL. 4. Click "Start Crawling" to initiate the spider. ## Technologies Used - PHP - HTML - JavaScript (AJAX) - DOMDocument - cURL (intended for advanced HTTP requests) ## Notes - Ensure responsible crawling: respect website rules and policies, avoid overloading servers. - Test thoroughly before deploying on any website. - Feel free to customize and extend the code based on your requirements. ## Contributors - [Ahsan Ullah](https://github.com/Me-AU) ## License This project is licensed under the [MIT License](LICENSE).
/* * Click nbfs://nbhost/SystemFileSystem/Templates/Licenses/license-default.txt to change this license * Click nbfs://nbhost/SystemFileSystem/Templates/Classes/Class.java to edit this template */ package com.example.demo.service.Impl; /** * * @author lossa */ import com.example.demo.domain.Proveedores; import com.example.demo.DAo.ProveedorDao; import com.example.demo.service.ProveedorService; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; @Service public class ProveedoresServiceImpl implements ProveedorService { @Autowired private ProveedorDao proveedorDao; @Transactional(readOnly = true) @Override public List<Proveedores>getProveedores(){ return proveedorDao.findAll(); } @Override @Transactional(readOnly = true) public Proveedores getProvedor(Long id){ return proveedorDao.findById(id).orElse(null); } @Override @Transactional public void SaveProveedor(Proveedores proveedores){ proveedorDao.save(proveedores); } @Override @Transactional public void DeleteProveedor(Long id){ proveedorDao.deleteById(id); } @Override @Transactional public void UpdateProveedor(Proveedores proveedores){ proveedorDao.save(proveedores); } }
#!/usr/bin/env python3 import asyncio import re import discord import msgspec import model config = model.parse_config('./resources/config.yml') MAX_USERS = config.get('max_limit', 99999) DISCORD_TOKEN = config.get('token', None) CONVERSATION_PATH = config.get('conv_folder', './resources/conversation/') intents = discord.Intents.default() intents.message_content = True client = discord.Client(intents=intents) in_session = [] @client.event async def on_ready(): print(f'The discord client ({client.user}) is now ready...') @client.event async def on_message(message): authorID = str(message.author.id) if message.content.startswith(client.user.mention) and authorID != str(client.user.id): if authorID in in_session: await message.reply('Please wait as I\'m still responding to your previous question...') else: if MAX_USERS >= len(in_session): client_mention = re.escape(client.user.mention) pattern = rf"{client_mention}\s*|\s+" content = re.sub(pattern, ' ', message.content).strip() in_session.append(authorID) async with message.channel.typing(): try: with open(f"{CONVERSATION_PATH}{authorID}.json", "rb") as memory_file: memory = msgspec.json.decode(memory_file.read()) if len(memory) == 0: memory = {} except FileNotFoundError: memory = {} # Use asyncio.sleep() to keep typing until the bot finishes generating the answer await asyncio.sleep(2.5) # Adjust the sleep duration as needed response = await client.loop.run_in_executor(None, model.generation, content, memory, authorID) await message.reply(response) in_session.remove(authorID) async def change_client_status(): await client.wait_until_ready() while not client.is_closed(): await client.change_presence(activity=discord.Activity(type=discord.ActivityType.listening, name=f'{len(in_session)} messages!')) await asyncio.sleep(25) client.loop.create_task(change_client_status()) if __name__ == '__main__': client.run(DISCORD_TOKEN)
<nz-layout class="app-layout"> <nz-sider nzCollapsible class="app-sider" nzWidth="200px" nzBreakpoint="md" [nzCollapsedWidth]="48" [(nzCollapsed)]="isCollapsed" [nzTrigger]="null"> <div class="sidebar-logo"> <a href="/" target="_blank"> <img src="assets/images/logo.png" alt="logo"> <h1>{{(options$ | async)?.['site_name']}}</h1> </a> </div> <ul nz-menu nzTheme="dark" nzMode="inline"> <ng-template #menuItemTpl let-menu> <i *ngIf="menu.icon" nz-icon [nzType]="menu.icon"></i> <span *ngIf="!menu.url">{{ menu.title }}</span> <a *ngIf="menu.url" [routerLink]="menu.url">{{ menu.title }}</a> </ng-template> <ng-container *ngFor="let menu of menus"> <li nz-submenu *ngIf="menu.children" [nzTitle]="menu.title" [nzIcon]="menu.icon || ''" [nzPaddingLeft]="isCollapsed ? 16 : menu.level * 24" [(nzOpen)]="openMap[menu.key]" (nzOpenChange)="onMenuOpen(menu.key)"> <ul> <li nz-menu-item *ngFor="let subMenu of menu.children" [nzPaddingLeft]="isCollapsed ? 16 : subMenu.level * 24" [nzSelected]="selectedMap[subMenu.key]"> <ng-container *ngTemplateOutlet="menuItemTpl; context: { $implicit: subMenu }"></ng-container> </li> </ul> </li> <li nz-menu-item *ngIf="!menu.children" [nzPaddingLeft]="isCollapsed ? 16 : menu.level * 24" [nzSelected]="selectedMap[menu.key]"> <ng-container *ngTemplateOutlet="menuItemTpl; context: { $implicit: menu }"></ng-container> </li> </ng-container> </ul> </nz-sider> <nz-layout> <nz-header> <div class="app-header"> <span class="header-trigger" (click)="onCollapsedChange()"> <i nz-icon class="trigger" [nzType]="isCollapsed ? 'menu-unfold' : 'menu-fold'"></i> </span> <span class="header-user" *ngIf="isLoggedIn">欢迎,{{loginUser?.userName}}</span> </div> </nz-header> <nz-content> <div class="app-content"> <i-breadcrumb></i-breadcrumb> <router-outlet></router-outlet> </div> </nz-content> </nz-layout> </nz-layout>
type _StripLeadingZeros<S extends string> = S extends '0' ? S // don't convert zero itself into the empty string -- we only want to strip _leading_ zeros : S extends `0${infer T}` ? _StripLeadingZeros<T> : S /** * strips leading zeros from number string `S` * * @since 0.0.2 */ export type StripLeadingZeros<S extends string> = S extends `-${infer T}` ? `-${_StripLeadingZeros<T>}` : _StripLeadingZeros<S>
import { Response } from "express"; import { Octokit } from "@octokit/core"; import { createOAuthUserAuth } from "@octokit/auth-oauth-user"; import { startSession } from "../session"; import { addCookies } from "../utils/cookies"; import fail from "../utils/fail"; import { updateOrCreateGitHubUser } from "./queries"; import { getRepoCollaborators } from "./api_wrappers"; import Config from "../config"; /** api handlers for performing a github authentication flow */ export function handle_GET_github_init( req: { p: { dest: string; owner: string } }, res: { redirect: (arg0: string) => void }, ) { let dest = req.p.dest; const clientId = process.env.GH_APP_CLIENT_ID; const redirectUri = `${Config.getServerUrl()}/api/v3/github_oauth_callback?dest=${dest}`; const githubAuthorizeUrl = `https://github.com/login/oauth/authorize?scope=user:email&client_id=${clientId}&redirect_uri=${encodeURIComponent( redirectUri, )}`; res.redirect(githubAuthorizeUrl); } export function handle_GET_github_oauth_callback( req: { p: { uid?: any; code: any; dest?: any } }, res: any, // { redirect: (arg0: any) => void } ) { handleGithubOauthCallback(req, res).catch((err) => { fail(res, 500, err.message); }); } async function handleGithubOauthCallback( req: { p: { uid?: any; code: string; dest?: any } }, res: Response, ) { const octokit = new Octokit({ authStrategy: createOAuthUserAuth, auth: { clientId: process.env.GH_APP_CLIENT_ID, clientSecret: process.env.GH_APP_CLIENT_SECRET, code: req.p.code, }, }); // get the github username that is associated with the token const { data: { login: githubUsername, id: githubUserId, email: githubUserEmail }, } = await octokit.request("GET /user"); if (!githubUsername) { throw Error("invalid github access token"); } // the user is now authenticated // check if the user is a proposals repo collaborator or the owner of the repo let isRepoCollaborator = githubUsername === process.env.FIP_REPO_OWNER; const collaborators = await getRepoCollaborators(); for (const collaborator of collaborators) { if (collaborator.id === githubUserId) { isRepoCollaborator = true; } } const { uid } = await updateOrCreateGitHubUser({ username: githubUsername, id: githubUserId, email: githubUserEmail, isRepoCollaborator, }); const token = await startSession(uid); try { await addCookies(req as any, res, token, uid); } catch (err) { return fail(res, 500, "polis_err_adding_cookies", err); } const dest = req.p.dest; res.redirect(dest); }
# Annotations 📜✍️ ## Chapter 1 - Fundamentals of Data Architecture ### 1.1 - Why cloud? The main difference between on-premises architecture and cloud architecture is the cost model. - On-premises: Using on-premises we have to buy resources based on predictions and in a good prediction case, a lot of resources will be less useful for some time, in a bad prediction case the resources won’t be enough to attend to the demand. - Cloud architecture (pay-as-you-go): In a cloud architecture case is possible to buy just the resources that are needed for each situation, in a simple and small project that uses few resources you will pay only for those few resources, if this project became a big one, you don’t need to wait to buy and implement new resources, the cloud elasticity allows to expand the project in a dynamic way. - IaaS x PaaS x SaaS: IaaS is Virtual Machine; PaaS is SQL Database; SaaS is Gmail; ### 1.2 - Well-Architected Framework Well-Architected Framework is a framework created by AWS that defines the five pillars to design a cloud architecture, theses pillars are: - Operational Excellence - Security - Reliability - Performance Efficiency - Costs Optimization <p align="center"> <img width="400" src="https://user-images.githubusercontent.com/48625700/196230940-6f090e42-1c63-4aa3-ac7c-94f7eb1f549c.png"> </p> ### 1.3 - Operational Excellence The main topics of operational excellence are change management and automatization, fast and efficient response for infrastructure events, and guidelines definitions for daily operations. Those topics are related to IaC (infrastructure as code), small + frequent + reversible changes, frequent operational procedures refinements, failure and event predictions, and documentation production. ### 1.4 - Security The main topics of security are to protect information and active systems and besides that create value for business through risk evaluations and mitigation strategies. Those topics are related to identifying and managing the profiles on each environment (authorizations, authentications, and user tracking), applying security for all layers, protecting data in traffic and in rest, preparing the system for security events, and guaranteeing data integrity and confidentiality. ### 1.5 - Reliability The main topics of reliability are avoiding and recovering from failures to attend to business demands. Those topics are related to automating recovery procedures, frequent recovery procedure tests, horizontal scalability of resources to increase availability, and change management in automated processes. ### 1.6 - Performance Efficiency The main topics of performance efficiency are to keep attending to the business demand in an efficient way while the project is growing, and the tools are renewing themselves. Those topics are related to spreading advanced technologies into the team, the uses of serverless architecture and resources, and the exploration and experiments of new technologies in a periodic way. ### 1.7 - Costs Optimization The main idea here is to choose the resources with minor prices that create value for the business. This idea is related to the cloud model consumption (ex: CapEx or OpEx), cost measuring and cost tracking of the development environments, mitigation (or elimination) of operational expenses with data centers and hardware, and cost segmentation. ## Chapter 2 - Data Architecture Models on Cloud ### 2.1 - DaaS Database as a Service (Relational) - AWS resources - RDS (Relational Database Service): It is compatible with Oracle, Microsoft SQL Server, MySQL, PostgreSQL, MariaDB, and the AWS serverless option Amazon Aurora. - DW solutions: Amazon Redshift and Amazon Redshift Spectrum. - Azure resources - Relational solutions: Azure SQL Database, Azure SQL Server, SQL Server in VM, Azure Database for PostgreSQL Azure Database for MySQL, Azure Database for MariaDB. - DW solutions: Azure SQL Data Warehouse and Azure Synapse Analytics. - GCP resources - Relational solutions: Bare Mental Solution, Cloud SQL (it is compatible with MySQL, PostgreSQL, and Microsoft SQL Server), Cloud Spanner (it is compatible with Oracle and DynamoDB). - DW solutions: BigQuery. ### 2.2 - DaaS Database as a Service (Non-relational) - AWS resources - DynamoDB (key-value) - DocumentDB (it is compatible with MongoDB) - Amazon Neptune (graph) - Amazon Elasticache (database in memory, it is compatible with Memcached and Redis) - Amazon ElasticSearch Service - Azure resources - Azure Cosmos DB: it is compatible with key-value, document-oriented, and graph database types - Azure Cache for Redis (database in memory, it is compatible with Redis) - Elastic in Azure (Elastic Search) - GCP resources - Cloud BigTable (key-value) - Firestore (document-oriented) - Firebase Realtime Database (document-oriented) - Memorystore (database in memory, it is compatible with Redis and Memcached) - Integration with partners: MongoDB Atlas, Datastax, Redis Labs, Neo4j, and ElasticSearch. ### 2.3 - Data Lake (Architecture Design) - Lambda Architecture: what defines this architecture is the existence of two layers, the batch layer, and the speed layer. Both layers work in parallel, the batch layer works with data batches and the speed layer works in real-time or near-real-time. It is important to cite the serving layer too, it is the layer of data consumption that receives that from the batch layer. - Advantages: it is helpful for attending requirements that have these two necessities (historical data and real-time data) - Disadvantages: The simultaneous processing usually requires a lot of data storage and sometimes causes duplicates <p align="center"> <img width="600" src="https://user-images.githubusercontent.com/48625700/196685326-f02ae667-e64e-4bb1-bfd1-5caa3d57cafe.png"> </p> - Kappa Architecture: this architecture has only one layer, that calls Data Processing Layer. This unique layer is a kind of speed layer, that works in real-time or near-real-time, but also works with batches. So, it solves the problem of duplicates that the Lambda architecture has. - Advantages: it avoids duplicates and reduces the data storage space (when we compare it with Lambda architecture) - Disadvantages: the architecture is hard to be implemented especially for the data reprocessing of streaming <p align="center"> <img width="650" src="https://user-images.githubusercontent.com/48625700/196685419-d314b93e-fb68-441a-8bd2-c662d232cc1d.png"> </p> - Unifield Architecture: it is very similar to Lambda architecture, the novelty here is that the machine learning layer is combined with the speed layer. - Advantages: the possibility to create real-time machine learning can offer a lot of insights for the users - Disadvantages: it is more complex to be implemented <p align="center"> <img width="600" src="https://user-images.githubusercontent.com/48625700/196685477-739ac305-b72e-4389-a3d6-afab97b290fc.jpeg"> </p> - Lakehouse Architecture: it is a modern structure that allows flexibility, cost optimization, and scalability for the Data Lake, besides that it also brings ACID operations that are common in relational databases. Data Lakehouse is the mix between Data Lake and Data Warehouse, it gets the best from these two architectures to create a new one. - Main tools: delta lake + query engines <p align="center"> <img width="600" src="https://user-images.githubusercontent.com/48625700/197502558-044519b0-dec1-45b2-ad21-465b5a0913cd.png"> </p> ### 2.4 - Data Lake (Storage - Amazon S3) Amazon S3 (Simple Storage Service) is the main storage solution in AWS. The main features are: - Volume limit: limitless. There is just a limit for each object, and each one has to have up to 5 TB. - Durability: 11 nines (99,999999999%) - Replication: it does automatic replication for all objects in all disponibility zones of the region. We only need to choose the region. - Costs: it has the pay-as-you-go model. - Pay: 1. GBs per month; 2. Data traffic for other regions or out of AWS; 3. Queries PUT, COPY, POST, LIST, and GET; - Non-pay: 1. Data traffic to put data into S3; 2. Data traffic for AWS services at the same region; ### 2.5 - Data Lake (Data Ingestion) - Batch ingestion: Spark; Python; Apache Nifi; - Real-time: Kafka (near real-time); - Managed Services: - AWS: DMS (Database Migration Service); Amazon Kinesis; - GCP: Google PubSub; - Azure: Azure EventHub; ### 2.6 - Data Lake (Big Data Processing) - Open source tools: - Apache Spark (Batch and Real-time) - ksqlDB (Kafka - Real-time) - Managed tools: - AWS: - EMR: it is a PaaS service that is compatible with Hadoop, Spark, Hive, and others; - Glue Job: it is a SaaS service that uses mainly spark; - Kinesis Data Analytics: a resource for data streaming solution (it seems Kafka); - Azure: - HD Insight: batch and real-time processing; - Azure Stream Analytics: data streaming solution (it seems Kafka); - Google Cloud: - Dataproc; - Pub/Sub; - BigQuery - Databricks ### 2.7 - Data Lake (Data Consumption - DW & Engines) - Managed engines: - AWS: - Amazon Athena (it is combined with Glue Data Catalog); - Azure: - Azure Data Lake Analytics; - Google Cloud: - BigQuery is a DW service, but it is the nearest resource that GCP has - Non-managed engines: - Presto; - Trino; - Apache Drill; - Dremio; ## Chapter 4 - IaC Infrastructure as Code ### 4.1 - IaC Tools - Why IaC? - Automation; - Cycle time: velocity to implement; - Easy replication for other environments (dev, prod, etc); - Reliability: easy and fast to rebuild in a disaster recovery situation; - Open-source tools: - Terraform; - Pulimi; - Chef infra; - Puppet; - Cloud-based: - AWS CloudFormation; - Azure Resource Manager; - Google Cloud Deployment Manager;
import React, { useState } from 'react'; import { useParams } from 'react-router-dom'; import { useDispatch } from 'react-redux'; import WebsiteCreation from 'pages/dashboard/WebsiteCreation'; import { LinearProgress } from '@mui/material'; import { webCreationSliceActions } from 'store/web-creation'; import { productTypeSliceActions } from 'store/product-type'; import { useWebsiteCreation } from 'hooks/websiteCreation'; import { useQuery } from 'react-query'; import ApiService from 'helpers/api'; import { useAlert } from 'hooks/alert'; function WebsiteCreationPre() { const params = useParams(); const { bookId } = params; const { addAlert } = useAlert(); const [isLoading, setIsLoading] = useState(true); const [salesData, setSalesData] = useState(''); const [hasSalesPage, setHasSalesPage] = useState(false); const [mockupData, setMockupData] = useState({}); const [pageImages, setPageImages] = useState([]); const [websiteMainData, setWebsiteMainData] = useState({}); const [deliveryMainData, setDeliveryMainData] = useState({}); const dispatch = useDispatch(); const { defaultWebsiteValues } = useWebsiteCreation(); const onBooksSuccess = async (data) => { setMockupData({ mockupId: data.mockup.id, mockupImage: data.mockup.file, coverImage: data.cover_image_preview }); try { const webData = await defaultWebsiteValues(bookId, !!data.sales_page); if (!data.sale_page) { setWebsiteMainData(webData.website); setDeliveryMainData(webData.delivery); } } catch { addAlert('Something went wrong. Please try again', 'error'); } setIsLoading(false); setPageImages(data.pages.map((x) => x.image_preview)); if (data.sale_page) { dispatch(webCreationSliceActions.setHasSalesPageId(data.sale_page)); } else { dispatch(webCreationSliceActions.setSubDomain('your-domain')); } if (data.book_file) { dispatch(webCreationSliceActions.setDownloadUrl(data.book_file.file)); } else { addAlert('Please Publish your Book First...', 'warning'); } }; const onBooksMediaSuccess = (data) => { if (data.length > 0) { dispatch(productTypeSliceActions.setBookMediaImage(data[0].file)); } }; const onSalesPageSuccess = (data) => { setSalesData(data); setHasSalesPage(true); setWebsiteMainData(data.page_data); setDeliveryMainData(data.delivery_page_data); dispatch(webCreationSliceActions.setSalesType(data.type)); dispatch(webCreationSliceActions.setSubDomain(data.sub_domain)); dispatch(webCreationSliceActions.setHasSalesPage()); dispatch(webCreationSliceActions.setHasSalesPageData(data)); }; const onSalesMediaSuccess = (data) => { if (data.length > 0) { dispatch(productTypeSliceActions.addAboutImage(data[0].file)); dispatch(productTypeSliceActions.addNewAboutImage(data[0].file)); } }; const { isLoading: isBooksLoading, data: booksData } = useQuery( `books-${bookId}`, () => ApiService.get(`/book-generator/books/${bookId}/`), { onSuccess: (response) => onBooksSuccess(response.data), refetchOnWindowFocus: false } ); const { isLoading: isSalesPageLoading } = useQuery( `sales-page-${bookId}`, () => ApiService.get(`/sales/sales-page/${booksData.data.sale_page}`), { enabled: !isBooksLoading && Boolean(booksData.data.sale_page), onSuccess: (response) => onSalesPageSuccess(response.data), refetchOnWindowFocus: false } ); const { isLoading: isMediaLoading } = useQuery( `sales-media-${bookId}`, () => ApiService.get(`/sales/sales-page/${booksData.data.sale_page}/media`), { enabled: !isBooksLoading && Boolean(booksData.data.sale_page), onSuccess: (response) => onSalesMediaSuccess(response.data), refetchOnWindowFocus: false } ); const { isLoading: isBooksMediaLoading } = useQuery( `booksMedia-${bookId}`, () => ApiService.get(`/book-generator/books/${bookId}/book_media/`), { onSuccess: (response) => onBooksMediaSuccess(response.data), refetchOnWindowFocus: false } ); if (isBooksLoading || isSalesPageLoading || isMediaLoading || isBooksMediaLoading || isLoading) { return <LinearProgress color="inherit" />; } return ( <WebsiteCreation websiteMainData={websiteMainData} setWebsiteMainData={setWebsiteMainData} deliveryMainData={deliveryMainData} setDeliveryMainData={setDeliveryMainData} mockupData={mockupData} pageImages={pageImages} hasSalesPage={hasSalesPage} salesData={salesData} /> ); } export default WebsiteCreationPre;
<template> <FormLIne ref="queryRef" @query-strategy="queryStrategy" ></FormLIne> <DialogMenuDetail :button-info="addButtonInfo" :strategy-info="strategyInfo"></DialogMenuDetail> <el-table :data="tableData" border highlight-current-row style="width: 100%"> <el-table-column type="index" width="50"/> <el-table-column label="id" width="190"> <template #default="scope"> <span>{{ scope.row.id }}</span> </template> </el-table-column> <el-table-column label="code" width="150"> <template #default="scope"> <span>{{ scope.row.code }}</span> </template> </el-table-column> <el-table-column label="名称" width="200"> <template #default="scope"> <span>{{ scope.row.name }}</span> </template> </el-table-column> <el-table-column label="开始时间" width="200"> <template #default="scope"> <span>{{ scope.row.beginDate }}</span> </template> </el-table-column> <el-table-column label="结束时间" width="200" > <template #default="scope"> <span>{{ scope.row.endDate }}</span> </template> </el-table-column> <el-table-column fixed="right" label="操作" width="300"> <template #default="scope"> <DialogMenuDetail :button-info="editInfo" :strategy-info="scope.row">{{ buttonInfo.buttonName }} </DialogMenuDetail> <el-button type="text" @click="deleteInfo(scope.row)">删除</el-button> </template> </el-table-column> </el-table> </template> <script setup> import axios from 'axios'; import AxiosUrl from '/src/constant/AxiosUrl' import {onMounted, reactive} from 'vue' import FormLIne from './FormLIne' import DialogMenuDetail from './DialogMenuDetail' import {ref} from "vue"; import Button from "@/constant/Button"; const tableData = reactive([]) const strategyInfo=ref({}) const editInfo = ref({ buttonName: '查看详情', buttonUrl: AxiosUrl.river.stockTemplate.add, buttonType: 'text' }) const queryRef = ref({}) function queryStrategy(){ getAllStockInfo(queryRef.value.queryParam); } onMounted(() => { getAllStockInfo(queryRef.value.queryParam); }) function deleteInfo(row){ axios.post(AxiosUrl.river.stockTemplate.delete,{ id:row.id, }).then(()=>{ getAllStockInfo(queryRef.value.queryParam); } ) } function getAllStockInfo(queryParam) { tableData.length=0; axios.post(AxiosUrl.stock.stockAnomalousBehavior.getAbStatic,{ plateList: queryParam == null ? null : queryParam.plateIdArr, }).then((res) => { res.forEach(v => { tableData.push(v); }) // tableData.data=res; }); } </script>
public class Lutador { // atributos private String nome; private String nacionalidade; private int idade; private double altura; private double peso; private String categoria; private int vitorias; private int derrotas; private int empates; // Metodos Publicos public void apresentar() { System.out.println("--------------------------------------------------------------"); System.out.println("APRESENTANDO O LUTADOR " + this.getNome()); System.out.println("--------------------------------------------------------------"); System.out.println("Diretamente de " + this.getNacionalidade()); System.out.println("Com " + this.getIdade() + " de idade" + " e " + this.getAltura() + " de altura"); System.out.println("Pesando " + this.getPeso() + "Kg"); System.out.println("Vitorias " + this.getVitorias()); System.out.println("Derrotas " + this.getDerrotas()); System.out.println("Empates " + this.getEmpates()); System.out.println("--------------------------------------------------------------"); } public void status() { System.out.println("---------------------------------------------------------------"); System.out.println("STATUS ATUAL"); System.out.println("---------------------------------------------------------------"); System.out.println("Lutador " + this.getNome() + " é categoria " + this.getCategoria()); System.out.println("Ganhou " + this.getVitorias() + " vezes"); System.out.println("Perdeu " + this.getDerrotas() + " vezes"); System.out.println("Empatou " + this.getEmpates() + " vezes"); System.out.println("---------------------------------------------------------------"); } public void ganharLuta() { this.setVitorias(this.getVitorias() + 1); } public void perderLuta() { this.setDerrotas(this.getDerrotas() + 1); } public void empatarLuta() { this.setEmpates(this.getEmpates() + 1); } // metodos especiais public Lutador(String no, String na, int id, double al, double pe, int vi, int de, int em) { this.nome = no; this.nacionalidade = na; this.idade = id; this.altura = al; this.setPeso(pe); this.vitorias = vi; this.derrotas = de; this.empates = em; } public String getNome() { return this.nome; } public void setNome(String no) { this.nome = no; } public String getNacionalidade() { return this.nacionalidade; } public void setNacionalidade(String na) { this.nacionalidade = na; } public int getIdade() { return this.idade; } public void setIdade(int id) { this.idade = id; } public double getAltura() { return this.altura; } public void setAltura(float al) { this.altura = al; } public double getPeso() { return this.peso; } public void setPeso(double pe) { this.peso = pe; this.setCategoria(); } public String getCategoria() { return this.categoria; } private void setCategoria() // metodo interno por isso private { if (this.peso < 52.2) { this.categoria = "Invalido"; } else if (this.peso <= 70.3) { this.categoria = "Leve"; } else if (this.peso <= 83.9) { this.categoria = "Medio"; } else if (this.peso <= 120.2) { this.categoria = "Pesado"; } else { this.categoria = "Invalido"; } } public int getVitorias() { return this.vitorias; } public void setVitorias(int vi) { this.vitorias = vi; } public int getDerrotas() { return this.derrotas; } public void setDerrotas(int de) { this.derrotas = de; } public int getEmpates() { return this.empates; } public void setEmpates(int em) { this.empates = em; } }
/* * module2.js - Part of "Lanczos resampling" JavaScript experiment. * * * Copyright 2012-2013 Valera Rozuvan * http://javascript-experiments.net/ * * * This file is part of javascript-experiments. * * javascript-experiments 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. * * javascript-experiments 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 Foobar. If not, see <http://www.gnu.org/licenses/>. */ define( [ 'pipeline', 'MathJaxLoader', 'jquery', 'jquery_ui', 'flot', 'showdown', 'text!../md/module2_text.md' ], function (pipeline, MathJaxLoader, $, jui, flot, Showdown, module2Text) { return function () { var out, converter; out = this.moduleDiv.out; converter = new Showdown.converter(); out(converter.makeHtml(module2Text)); this.moduleDiv.publish(); pipeline.a = 2; $('#a_slider_value').css('left', (pipeline.a * 60 + 80) + 'px'); $('#a_slider_value').html(pipeline.a.toFixed(1)); $('#a_slider').slider({ 'min': 0, 'max': 5, 'value': 2, 'step': 0.1, 'slide': function(event, ui) { pipeline.a = ui.value; $('#a_slider_value').css( 'left', (pipeline.a * 60 + 80) + 'px' ); $('#a_slider_value').html(pipeline.a.toFixed(1)); plot(); } }); plot(); MathJaxLoader.typeset(this.el); }; // End-of: return function () function plot() { var i, d1, d2; d1 = []; for (i = -5; i <= 5; i += 0.05) { if (Math.abs(i) < 1e-16) { d1.push([i, 1]); } else { d1.push([i, Math.sin(Math.PI * i) / (Math.PI * i)]); } } d1.push([5, Math.sin(Math.PI * 5) / (Math.PI * 5)]); d2 = []; if (pipeline.a !== 0) { d2.push([ -pipeline.a, // Math.sin(Math.PI * (-pipeline.a / pipeline.a)) / (Math.PI * (-pipeline.a / pipeline.a)) Math.sin(-Math.PI) / (-Math.PI) ]); } else { d2.push([0, 1]); } for (i = -5; i <= 5; i += 0.05) { if ((i < -pipeline.a) || (i > pipeline.a)) { continue; } if (Math.abs(i * pipeline.a) < 1e-16) { d2.push([i, 1]); } else { d2.push([ i, Math.sin(Math.PI * (i / pipeline.a)) / (Math.PI * (i / pipeline.a)) ]); } } if (pipeline.a !== 0) { d2.push([ pipeline.a, // Math.sin(Math.PI * (pipeline.a / pipeline.a)) / (Math.PI * (pipeline.a / pipeline.a)) Math.sin(Math.PI) / Math.PI ]); } flot( $('#placeholder1'), [ { 'data': d1, 'label': 'sinc' }, { 'data': d2, 'label': 'Lanczos window' } ], { 'legend': { 'show': true, 'backgroundOpacity': 0 }, 'grid': { 'markings': [ { 'color': '#000', 'lineWidth': 1, 'xaxis': { 'from': -pipeline.a, 'to': -pipeline.a } }, { 'color': '#000', 'lineWidth': 1, 'xaxis': { 'from': pipeline.a, 'to': pipeline.a } } ] }, 'xaxis': { 'min': -5, 'max': 5 }, 'yaxis': { 'min': -0.4, 'max': 1.2 } } ); // End-of: flot( } // End-of: function plot() });
<template> <b-container class="team-section"> <h2 class="gordita-medium">Team Section Content</h2> <form> <b-row class="mt-4" v-for="(teamRow, index) in splitTeam" :key="`teamRow-${index}`" > <b-col md="4" v-for="(teamMember, i) in teamRow" :key="`teamMember-${index}-${i}`" > <div class="form-section"> <label>Team Member {{ 3 * index + (i + 1) }} Picture</label> <ImageUpload @invalid-image-type="showErrorAlert" @image-changed="imageChanged" :index="3 * index + i" :alt=" sectionData.team[3 * index + i].name ? sectionData.team[3 * index + i].name : '' " :preview=" sectionData.team[3 * index + i].image ? sectionData.team[3 * index + i].image : '' " /> <label>Team Member {{ 3 * index + (i + 1) }} Name</label> <input v-model="sectionData.team[3 * index + i].name" /> </div> <div class="form-section mt-3"> <label>Team Member {{ 3 * index + (i + 1) }} Roles</label> <div v-for="(role, j) in sectionData.team[3 * index + i].roles" :key="`team-role-${i}-${j}-${index}`" > <input class="mt-3" v-model="sectionData.team[3 * index + i].roles[j].text" /> </div> <button @click.prevent="addContent(3 * index + i)" class="small-btn mt-3" v-if="sectionData.team[3 * index + i].roles.length < 2" > <fai icon="plus" /> Add Role </button> </div> </b-col> </b-row> <b-row> <button class="mt-5" @click.prevent="addTeamMember"> <fai icon="plus" /> Add New Team Member </button> <button @click.prevent="updateSection(false)" class="mt-5 ml-1"> <fai icon="upload" /> Update Team Section's Content </button> <button @click.prevent="updateSection(true)" class="mt-5 ml-1"> <fai icon="magic" /> Preview Changes to Team Section </button> </b-row> </form> <EmailAlert v-if="showAlert" :type="type" :content="content" /> </b-container> </template> <script> import mixin from "@/views/cms/mixins/network_update_content"; import EmailAlert from "@/views/home/components/EmailAlert"; import ImageUpload from "@/views/cms/components/ImageUpload"; import axios from "axios"; export default { name: "TeamSection", mixins: [mixin], components: { ImageUpload, EmailAlert }, data: () => ({ showAlert: false, type: "success", content: "", sectionData: { team: [{ name: "", roles: [{ text: "" }], image: "" }] } }), mounted() { Object.keys(this.sectionData).forEach(key => { this.sectionData[key] = this.websiteData.fourthSection[key]; }); }, methods: { addContent: function(index) { this.sectionData.team[index].roles.push({ text: "" }); }, addTeamMember: function() { this.sectionData.team.push({ name: "", roles: [{ text: "" }] }); }, validRoles: function(roles) { if (!roles.length) return false; else { let valid = false; for (let role of roles) { if (role.text !== "") { valid = true; break; } } return valid; } }, updateSection: async function(update = false) { let currentData = await this.getWebsiteData(this.websiteData, update); let team = this.sectionData.team.filter( teamMember => teamMember.name !== "" && this.validRoles(teamMember.roles) ); team = await Promise.all( team.map(async teamMember => { teamMember.roles = teamMember.roles.filter(role => role.text !== ""); if (teamMember.updatedImage) { let data = new FormData(); data.append( "upload_preset", process.env.VUE_APP_CLOUDINARY_UNSIGNED_PRESET ); data.append("file", teamMember.updatedImage); let res = await axios.post( process.env.VUE_APP_CLOUDINARY_URL, data, { headers: { "Content-Type": "multipart/form-data" } } ); let { secure_url } = res.data; teamMember.image = secure_url; delete teamMember.updatedImage; } else { if (!teamMember.image) teamMember.image = "https://res.cloudinary.com/hotel-finder/image/upload/v1604964056/avatar_temara.png"; } return teamMember; }) ); currentData.homePage.fourthSection.team = team; if (update) this.previewContent(currentData, "Your changes will be previewed"); else this.updateContent( currentData, "Team Section Content Updated Successfully", () => (this.sectionData.team = team) ); }, showErrorAlert: function() { this.content = "Please upload either jpeg, jpg or png. Other file types are not allowed"; this.type = "error"; this.showAlert = true; setTimeout(() => (this.showAlert = false), 3000); }, imageChanged: function(data) { this.sectionData.team[data.index].updatedImage = data.file; } }, computed: { splitTeam: function() { let threes = []; let intermediate = []; this.sectionData.team.forEach(teamMember => { intermediate.push(teamMember); if (intermediate.length === 3) { threes.push(intermediate); intermediate = []; } }); if (intermediate.length) threes.push(intermediate); return threes; } }, props: { websiteData: Object } }; </script> <style lang="sass" scoped></style>
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title> 쿠키활용 </title> </head> <body> <button id="create"> 첫 방문 쿠키 생성 </button> <button id="create1"> 서브페이지 쿠키 생성 </button> <button id="check"> 쿠키 확인 </button> <button id="delete"> 쿠키 삭제 </button> <script> // 쿠키 생성(첫 방문 쿠키 생성, 서브페이지 쿠키 생성) function setCookie (name, value, day) { let date = new Date(); date.setDate(date.getDate() + day); // 7일 이후 지정 let exdate = date.toUTCString(); // UTC 변환 let setCookie = ''; setCookie += `${name}=${value};`; setCookie += `Expires=${exdate};`; console.log(setCookie); // 쿠키 지정 함수 /* document.cookie = "값1(name)=값2(value); Expires=날짜"; */ document.cookie = setCookie; } document.querySelector('#create').addEventListener('click', () => { setCookie ('ABC', '방문', 7) }); document.querySelector('#create1').addEventListener('click', () => { setCookie ('DEF', '방문', 7) }); // 쿠키 확인 function checkCookie (name) { let cookieArr = document.cookie.split(';'); for(let cookie of cookieArr) { if(cookie.search(name) > -1) { alert(cookie); } } } // 1. str = "hello.world" // str.split('.'); str 문자열을 구분자 .으로 나누어 배열로 반환 // 2. array.search("a"); 배열 array에 서치의 괄호안 "a"라는 문자가 있을 경우 참 1을 반환하고 아니면 거짓 -1을 반환 document.querySelector('#check').addEventListener('click', () => { checkCookie ('ABC'); }); // 쿠키 삭제 function delCookie (name) { let date = new Date(); date.setDate(date.getDate() + -1); // 1일 이전 let exdate = date.toUTCString(); // UTC 변환 let setCookie = ''; setCookie += `${name}=값;`; setCookie += `Expires=${exdate}`; // 쿠키 지정 함수 /* document.cookie = "Name=값; Expires=날짜"; */ document.cookie = setCookie; alert(name + '의 쿠키가 삭제되었습니다.'); } document.querySelector('#delete').addEventListener('click', () => { delCookie ('ABC'); }); /* console.log(document.cookie.split(';')); */ </script> </body> </html>
# Copyright 2020 ros2_control Development Team # # 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 from launch import LaunchDescription from launch.actions import ExecuteProcess, IncludeLaunchDescription, RegisterEventHandler, DeclareLaunchArgument from launch.event_handlers import OnProcessExit from launch.substitutions import Command, FindExecutable, PathJoinSubstitution, LaunchConfiguration from launch_ros.actions import Node from launch_ros.substitutions import FindPackageShare from launch.launch_description_sources import PythonLaunchDescriptionSource from ament_index_python.packages import get_package_share_directory def generate_launch_description(): # Get URDF via xacro gazebo = IncludeLaunchDescription( PythonLaunchDescriptionSource([os.path.join( get_package_share_directory('gazebo_ros'), 'launch'), '/gazebo.launch.py']), ) gzserver = IncludeLaunchDescription( PythonLaunchDescriptionSource([os.path.join( get_package_share_directory('gazebo_ros'), 'launch'), '/gzserver.launch.py']), ) use_gazebo_parameter_name = 'use_gazebo' use_fake_hardware_parameter_name = 'use_fake_hardware' use_gazebo = LaunchConfiguration(use_gazebo_parameter_name) use_fake_hardware = LaunchConfiguration(use_fake_hardware_parameter_name) capstone_xacro_file = os.path.join(get_package_share_directory('diffdrive_arduino'), 'urdf', 'capstone.urdf.xacro') robot_description_content = Command( [FindExecutable(name='xacro'), ' ', capstone_xacro_file, ' use_gazebo:=', use_gazebo, ' use_fake_hardware:=', use_fake_hardware]) robot_description = {"robot_description": robot_description_content} robot_controllers = PathJoinSubstitution( [ FindPackageShare("diffdrive_arduino"), "config", "capstone_controllers.yaml", ] ) # SPAWN ROBOT TO GAZEBO: spawn_entity = Node(package='gazebo_ros', executable='spawn_entity.py', arguments=['-topic', 'robot_description', '-entity', 'capstone'], output='screen') control_node = Node( package="controller_manager", executable="ros2_control_node", parameters=[robot_description, robot_controllers], output="both", ) robot_state_pub_node = Node( package="robot_state_publisher", executable="robot_state_publisher", output="both", parameters=[robot_description], remappings=[ ("/capstone_controller/cmd_vel_unstamped", "/cmd_vel"), ], ) rviz_node = Node( package="rviz2", executable="rviz2", name="rviz2", output="log", ) joint_state_broadcaster_spawner = Node( package="controller_manager", executable="spawner", arguments=["joint_state_broadcaster"], output='screen', ) robot_controller_spawner = Node( package="controller_manager", executable="spawner", arguments=["velocity_controller"], output='screen', ) # Delay rviz start after `joint_state_broadcaster` # delay_rviz_after_joint_state_broadcaster_spawner = RegisterEventHandler( # event_handler=OnProcessExit( # target_action=joint_state_broadcaster_spawner, # on_exit=[rviz_node], # ) # ) # # Delay start of robot_controller after `joint_state_broadcaster` # delay_robot_controller_spawner_after_joint_state_broadcaster_spawner = RegisterEventHandler( # event_handler=OnProcessExit( # target_action=joint_state_broadcaster_spawner, # on_exit=[robot_controller_spawner], # ) # ) nodes = [ DeclareLaunchArgument( 'use_gazebo', default_value="true" , description="use gazebo simulation"), ############################################## DeclareLaunchArgument( 'use_fake_hardware', default_value="true", description="use fake hardware interface. default is false for safety"), gazebo, robot_state_pub_node, control_node, spawn_entity, # delay_rviz_after_joint_state_broadcaster_spawner, # delay_robot_controller_spawner_after_joint_state_broadcaster_spawner, robot_controller_spawner, joint_state_broadcaster_spawner, ] return LaunchDescription(nodes)
/* * Copyright (c) 2021 Mark A. Hunter (ACT Health) * * 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. */ package net.fhirfactory.pegacorn.internals.directories.api; import net.fhirfactory.pegacorn.internals.directories.api.beans.PatientServiceHandler; import net.fhirfactory.pegacorn.internals.directories.api.common.ResourceDirectoryAPI; import net.fhirfactory.pegacorn.core.model.ui.resources.simple.PatientESR; import net.fhirfactory.pegacorn.core.model.ui.resources.simple.PractitionerRoleESR; import net.fhirfactory.pegacorn.core.model.ui.resources.simple.datatypes.FavouriteListESDT; import net.fhirfactory.pegacorn.core.model.ui.resources.simple.datatypes.PractitionerRoleListESDT; import org.apache.camel.Exchange; import org.apache.camel.LoggingLevel; import org.apache.camel.model.rest.RestParamType; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import javax.enterprise.context.ApplicationScoped; import javax.inject.Inject; @ApplicationScoped public class PatientESRAPI extends ResourceDirectoryAPI { private static final Logger LOG = LoggerFactory.getLogger(PatientESRAPI.class); @Inject private PatientServiceHandler patientServiceHandler; @Override protected String specifyESRName() { return ("Patient"); } @Override protected Class specifyESRClass() { return (PatientESR.class); } @Override protected Logger getLogger(){return(LOG);} @Override public void configure() throws Exception { // // Camel REST Configuration // getRestConfigurationDefinition(); // // The PatientDirectory Resource Handler (Exceptions) // getResourceNotFoundException(); getResourceUpdateException(); getGeneralException(); // // The PatientESR Resource Handler // getRestGetDefinition() .get("/search?urn={urn}&displayName={displayName}" + "&pageSize={pageSize}&page={page}&sortBy={sortBy}&sortOrder={sortOrder}") .param().name("urn").type(RestParamType.query).required(false).endParam() .param().name("displayName").type(RestParamType.query).required(false).endParam() .param().name("pageSize").type(RestParamType.query).required(false).endParam() .param().name("page").type(RestParamType.query).required(false).endParam() .param().name("sortBy").type(RestParamType.query).required(false).endParam() .param().name("sortOrder").type(RestParamType.query).required(false).endParam() .to("direct:"+getESRName()+"SearchGET") .get("/{simplifiedID}/PractitionerRoles").outType(PractitionerRoleListESDT.class) .to("direct:" + getESRName() + "PractitionerRolesGET") .get("/{simplifiedID}/PractitionerRoleFavourites").outType(FavouriteListESDT.class) .to("direct:" + getESRName() + "PractitionerRoleFavouritesGET") .get("/{simplifiedID}/ServiceFavourites").outType(FavouriteListESDT.class) .to("direct:" + getESRName() + "ServiceFavouritesGET") .get("/{simplifiedID}/PractitionerFavourites").outType(FavouriteListESDT.class) .to("direct:" + getESRName() + "PractitionerFavouritesGET") .post().type(PractitionerRoleESR.class) .to("direct:"+getESRName()+"POST") .put("/").type(PractitionerRoleESR.class) .to("direct:"+getESRName()+"PUT"); from("direct:"+getESRName()+"GET") .bean(patientServiceHandler, "getResource") .log(LoggingLevel.DEBUG, "GET Request --> ${body}"); from("direct:"+getESRName()+"ListGET") .bean(patientServiceHandler, "defaultGetResourceList") .log(LoggingLevel.DEBUG, "GET Request --> ${body}"); from("direct:"+getESRName()+"SearchGET") .bean(patientServiceHandler, "defaultSearch") .log(LoggingLevel.DEBUG, "GET (Search) Request --> ${body}"); from("direct:"+getESRName()+"POST") .log(LoggingLevel.DEBUG, "POST Request --> ${body}") .setHeader(Exchange.HTTP_RESPONSE_CODE, constant(501)) .setBody(simple("Action not support for this Directory Entry")); from("direct:"+getESRName()+"PUT") .bean(patientServiceHandler, "updatePractitioner") .log(LoggingLevel.DEBUG, "PUT Request --> ${body}"); from("direct:"+getESRName()+"DELETE") .log(LoggingLevel.DEBUG, "DELETE Request --> ${body}") .setHeader(Exchange.HTTP_RESPONSE_CODE, constant(501)) .setBody(simple("Action not support for this Directory Entry")); } }
//------------- Imports ---------------------------- import { renderPost } from "./src/components/renderPost/renderPost"; import { createPostApi } from "./src/helper/createPostApi"; import { deletePostApi } from "./src/helper/deletePostApi"; import { getPostApi } from "./src/helper/getPostApi"; import { updatePostApi } from "./src/helper/updatePostApi"; const URL = `${import.meta.env.VITE_URL}/posts`; //------------- Varibles Grobales -------------------- const postList = document.querySelector(".posts-list"); const addPostForm = document.querySelector(".add-post-form"); const titlePost = document.querySelector("#title-post"); const contentPost = document.querySelector("#content-post"); //------------- Funciones --------------------------- function init() { // Traerme todos los post de mi api. getPostApi(URL, (data) => { renderPost(postList, data); }); } addPostForm.addEventListener("submit", (e) => { // esoty escuchando el evento submit del formulario. e.preventDefault(); // const target = e.target; const button = addPostForm.querySelector(".btn"); // compruebo que los campos tenga campos if (!(titlePost.value && contentPost.value)) { alert("Los campos deben de estar con informacion"); return; } if(button.classList.contains("btn-secondary")){ // estoy editando const idEdit = button.dataset.id; const escape = addPostForm.querySelector(".escape"); escape.addEventListener("click", (e) => { e.preventDefault(); return false; }) //Accedo a la Api y actualizo el campo de dicho id const updateData = { id: idEdit, title: titlePost.value, post: contentPost.value, }; updatePostApi(URL, updateData, (post) => { //modifico el dom const cardDataId = postList.querySelector(`[data-id="${post.id}"]`) const cardTitle = cardDataId.querySelector(".card-title"); cardTitle.textContent = post.title; const cardText = cardDataId.querySelector(".card-text"); cardText.textContent = post.post; button.classList.remove("btn-secondary") button.textContent = "Añadir post" button.dataset.id = ""; cardDataId.parentElement.classList.remove("selected") escape.style.display = "none"; addPostForm.reset(); }) return ; } // ---------------------- añadiendo ----------------- const postData = { id: null, title: titlePost.value, post: contentPost.value, }; createPostApi(URL, postData,(data) => { renderPost(postList,[data]); }); e.target.reset(); }); postList.addEventListener("click", (e) => { e.preventDefault(); let editBtnPress = e.target.id == "edit-post"; let deleteBtnPress = e.target.id == "delete-post"; const postId = e.target.parentElement.dataset.id; const card = e.target.closest(".card"); // Eliminar card if (deleteBtnPress) { deletePostApi(URL, postId, () => { // ahora busco en el dom el elemento con ID --> postId y lo remove() card.remove(); }); return; } // Editar card if (editBtnPress) { const button = addPostForm.querySelector(".btn"); const escape = addPostForm.querySelector(".escape"); button.classList.add("btn-secondary"); button.textContent = "Editar Post"; card.classList.add("selected"); escape.style.display = "block"; button.dataset.id = postId; const titleCardEdit = card.querySelector(".card-title"); const textCardEdit = card.querySelector(".card-text"); titlePost.value = titleCardEdit.textContent.trim(); contentPost.value = textCardEdit.textContent.trim(); } }); //---------------- Inicializar --------------- document.addEventListener("DOMContentLoaded", init);
// // SearchViewController.swift // DanTang // // import UIKit let searchCollectionCellID = "searchCollectionCellID" class SearchViewController: BaseViewController, UISearchBarDelegate, UICollectionViewDelegate, UICollectionViewDataSource, UICollectionViewDelegateFlowLayout, CollectionViewCellDelegate, SortTableViewDelegate { /// 搜索结果列表 var results = [SearchResult]() weak var collectionView: UICollectionView? override func viewDidAppear(_ animated: Bool) { super.viewDidAppear(animated) searchBar.becomeFirstResponder() } override func viewWillDisappear(_ animated: Bool) { super.viewWillDisappear(animated) searchBar.resignFirstResponder() } override func viewDidLoad() { super.viewDidLoad() // 设置导航栏 setupNav() view.addSubview(searchRecordView) } // 设置导航栏 func setupNav() { navigationItem.titleView = searchBar searchBar.delegate = self navigationItem.leftBarButtonItem = UIBarButtonItem(customView: UIView()) navigationItem.rightBarButtonItem = UIBarButtonItem(title: "取消", style: .plain, target: self, action: #selector(navigationBackClick)) } /// 设置collectionView private func setupCollectionView() { let collectionView = UICollectionView(frame: view.bounds, collectionViewLayout: UICollectionViewFlowLayout()) collectionView.delegate = self collectionView.contentInset = UIEdgeInsetsMake(64, 0, 0, 0) collectionView.backgroundColor = view.backgroundColor collectionView.dataSource = self let nib = UINib(nibName: String(describing: CollectionViewCell.self), bundle: nil) collectionView.register(nib, forCellWithReuseIdentifier: searchCollectionCellID) view.addSubview(collectionView) self.collectionView = collectionView } /// 搜索条件点击 @objc func sortButtonClick() { popView.show() } private lazy var popView: SortTableView = { let popView = SortTableView() popView.delegate = self return popView }() /// 返回按钮、取消按钮点击 @objc func navigationBackClick() { navigationController?.popViewController(animated: true) } private lazy var searchBar: UISearchBar = { let searchBar = UISearchBar() searchBar.placeholder = "搜索商品、专题" return searchBar }() private lazy var searchRecordView: SearchRecordView = { let searchRecordView = SearchRecordView() searchRecordView.backgroundColor = GlobalColor() searchRecordView.frame = CGRect(x: 0, y: 64, width: SCREENW, height: SCREENH - 64) return searchRecordView }() private func searchBarShouldEndEditing(searchBar: UISearchBar) -> Bool { /// 设置collectionView setupCollectionView() return true } /// 搜索按钮点击 private func searchBarSearchButtonClicked(searchBar: UISearchBar) { searchBar.resignFirstResponder() navigationItem.leftBarButtonItem = UIBarButtonItem(image: UIImage(named: "checkUserType_backward_9x15_"), style: .plain, target: self, action: #selector(navigationBackClick)) navigationItem.rightBarButtonItem = UIBarButtonItem(image: UIImage(named: "icon_sort_21x21_"), style: .plain, target: self, action: #selector(sortButtonClick)) /// 根据搜索条件进行搜索 let keyword = searchBar.text weak var weakSelf = self NetworkTool.shareNetworkTool.loadSearchResult(keyword: keyword!, sort: "") { (results) in weakSelf!.results = results weakSelf!.collectionView!.reloadData() } } // MARK: - UICollectionViewDataSource func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return results.count } func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { let cell = collectionView.dequeueReusableCell(withReuseIdentifier: searchCollectionCellID, for: indexPath as IndexPath) as! CollectionViewCell cell.result = results[indexPath.item] cell.delegate = self return cell } // MARK: - UICollectionViewDelegate func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) { // let productDetailVC = ProductDetailViewController() // productDetailVC.title = "商品详情" // productDetailVC.type = String(describing: self) // productDetailVC.result = results[indexPath.item] // navigationController?.pushViewController(productDetailVC, animated: true) } // MARK: - UICollectionViewDelegateFlowLayout func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize { let width: CGFloat = (UIScreen.main.bounds.width - 20) / 2 let height: CGFloat = 245 return CGSize(width: width, height: height) } func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, insetForSectionAt section: Int) -> UIEdgeInsets { return UIEdgeInsetsMake(5, 5, 5, 5) } // MARK: - CollectionViewCellDelegate func collectionViewCellDidClickedLikeButton(button: UIButton) { // if !UserDefaults.standard.bool(forKey: isLogin) { // let loginVC = YMLoginViewController() // loginVC.title = "登录" // let nav = YMNavigationController(rootViewController: loginVC) // present(nav, animated: true, completion: nil) // } else { // // } } // MARK: - SortTableViewDelegate func sortView(sortView: SortTableView, didSelectSortAtIndexPath sort: String) { /// 根据搜索条件进行搜索 let keyword = searchBar.text weak var weakSelf = self NetworkTool.shareNetworkTool.loadSearchResult(keyword: keyword!, sort: sort) { (results) in sortView.dismiss() weakSelf!.results = results weakSelf!.collectionView!.reloadData() } } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } }