text
stringlengths
184
4.48M
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <!-- displays site properly based on user's device --> <link rel="icon" type="image/png" sizes="32x32" href="./images/favicon-32x32.png" /> <link rel="stylesheet" href="style.css" /> <title>Frontend Mentor | Social proof section</title> <!-- Google Fonts Spartan --> <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=Spartan:wght@400;500;700&display=swap" rel="stylesheet" /> </head> <body> <head> <h1></h1> </head> <main> <div class="container"> <div class="top"> <div class="top__text"> <div class="top__text-title"> 10,000+ of our users love our products. </div> <div class="top__text-desc"> We only provide great products combined with excellent customer service. See what our satisfied customers are saying about our services. </div> </div> <div class="top__rate"> <div class="top__rate-review"> <div class="top__rate-review-star"> <img src="images/icon-star.svg" alt="" /> <img src="images/icon-star.svg" alt="" /> <img src="images/icon-star.svg" alt="" /> <img src="images/icon-star.svg" alt="" /> <img src="images/icon-star.svg" alt="" /> </div> <div class="top__rate-review-text">Rated 5 Stars in Reviews</div> </div> <div class="top__rate-review"> <div class="top__rate-review-star"> <img src="images/icon-star.svg" alt="" /> <img src="images/icon-star.svg" alt="" /> <img src="images/icon-star.svg" alt="" /> <img src="images/icon-star.svg" alt="" /> <img src="images/icon-star.svg" alt="" /> </div> <div class="top__rate-review-text"> Rated 5 Stars in Report Guru </div> </div> <div class="top__rate-review"> <div class="top__rate-review-star"> <img src="images/icon-star.svg" alt="" /> <img src="images/icon-star.svg" alt="" /> <img src="images/icon-star.svg" alt="" /> <img src="images/icon-star.svg" alt="" /> <img src="images/icon-star.svg" alt="" /> </div> <div class="top__rate-review-text">Rated 5 Stars in BestTech</div> </div> </div> </div> <div class="bottom"> <div class="bottom__card"> <div class="bottom__card__profile"> <div class="bottom__card__profile-image"> <img src="images/image-colton.jpg" alt="profile-colton" /> </div> <div class="bottom__card__profile-info"> <div class="bottom__card__profile__info-name">Colton Smith</div> <div class="bottom__card__profile__info-major"> Verified Buyer </div> </div> </div> <div class="bottom__card__story"> <span >"We needed the same printed design as the one we had ordered a week prior. Not only did they find the original order, but we also received it in time. Excellent!"</span > </div> </div> <div class="bottom__card"> <div class="bottom__card__profile"> <div class="bottom__card__profile-image"> <img src="images/image-irene.jpg" alt="profile-irene" /> </div> <div class="bottom__card__profile-info"> <div class="bottom__card__profile__info-name"> Irene Roberts </div> <div class="bottom__card__profile__info-major"> Verified Buyer </div> </div> </div> <div class="bottom__card__story"> <span >"Customer service is always excellent and very quick turn around. Completely delighted with the simplicity of the purchase and the speed of delivery."</span > </div> </div> <div class="bottom__card"> <div class="bottom__card__profile"> <div class="bottom__card__profile-image"> <img src="images/image-anne.jpg" alt="profile-colton" /> </div> <div class="bottom__card__profile-info"> <div class="bottom__card__profile__info-name">Anne Wallace</div> <div class="bottom__card__profile__info-major"> Verified Buyer </div> </div> </div> <div class="bottom__card__story"> <span >"Put an order with this company and can only praise them for the very high standard. Will definitely use them again and recommend them to everyone!"</span > </div> </div> </div> </div> </main> <!-- Irene Roberts Verified Buyer Anne Wallace Verified Buyer --> <div class="attribution"> Challenge by <a href="https://www.frontendmentor.io?ref=challenge" target="_blank" >Frontend Mentor</a >. Coded by <a href="#">Dongwoo-Kim(@iamIET)</a>. </div> </body> </html>
package oop.b4_1; public class Circle { private double radius = 1.0; private String color = "red"; public Circle() { } public Circle(double radius) { if(radius <= 0){ throw new RuntimeException("Error"); } this.radius = radius; } public Circle(double radius, String color) { if(radius <= 0){ throw new RuntimeException("Error"); } this.radius = radius; this.color = color; } public double getRadius() { return radius; } public void setRadius(double radius) { if(radius <= 0){ throw new RuntimeException("Error"); } this.radius = radius; } public String getColor() { return color; } public void setColor(String color) { this.color = color; } public double getArea(){ return Math.PI * radius * radius; } @Override public String toString() { return "Circle[" + "radius=" + radius + ",color='" + color + '\'' + ']'; } }
package com.example.myapp.data.datasource; import android.app.Application; import androidx.lifecycle.LiveData; import androidx.lifecycle.MutableLiveData; import com.example.myapp.R; import com.example.myapp.data.ItemsDao; import com.example.myapp.data.MyDatabase; import com.example.myapp.data.model.Item; import java.util.ArrayList; import java.util.List; public class FirstDataSource { public static MutableLiveData<List<Item>> getItems(Application app) { MutableLiveData<List<Item>> usersLiveData = new MutableLiveData<>(); ItemsDao dao = MyDatabase.getDataBase(app).dao(); MyDatabase.databaseWriterExecutor.execute(() -> { List<Item> items = dao.getAllItems(); if (items.isEmpty()) { for (int i = 0; i < 200; i++) { dao.insert(new Item( i, "description of simple item" + (i + 1), "subtitle of simple item" + (i + 1), "title of simple item" + (i + 1), R.drawable.ic_android_black_24dp )); } } usersLiveData.postValue(dao.getAllItems()); }); return usersLiveData; } }
#include <zephyr/kernel.h> #include <zephyr/logging/log.h> #include <zephyr/drivers/gpio.h> #include <zephyr/bluetooth/bluetooth.h> #include <zephyr/bluetooth/conn.h> #include <zephyr/bluetooth/gatt.h> #include <zephyr/bluetooth/uuid.h> #include <zephyr/drivers/pwm.h> LOG_MODULE_REGISTER(ble_test); volatile bool ble_ready = false; static bool led_state = 0; #define LED DT_ALIAS(led0) #define BT_UUID_MY_CUSTOM_SERV_VAL BT_UUID_128_ENCODE(0x347F1281,0x56EE,0x488B,0xA55A,0x4AFBF234FA8C) #define BT_UUID_MY_CUSTOM_SERVICE BT_UUID_DECLARE_128(BT_UUID_MY_CUSTOM_SERV_VAL) #define BT_UUID_LED_STATE_CHRC_VAL BT_UUID_128_ENCODE(0x347F1281,0x56EE,0x488B,0xA55A,0x4AFBF234FA8D) #define BT_UUID_LED_STATE_CHRC BT_UUID_DECLARE_128(BT_UUID_LED_STATE_CHRC_VAL) static const struct pwm_dt_spec pwm_led0 = PWM_DT_SPEC_GET(DT_ALIAS(pwm_led0)); static const struct gpio_dt_spec led = GPIO_DT_SPEC_GET(LED, gpios); static const struct bt_data ad[] = { BT_DATA_BYTES(BT_DATA_FLAGS, (BT_LE_AD_GENERAL | BT_LE_AD_NO_BREDR)), BT_DATA_BYTES(BT_DATA_UUID128_ALL, BT_UUID_MY_CUSTOM_SERV_VAL) }; static ssize_t read_led_state(struct bt_conn *conn, const struct bt_gatt_attr * attr, void *buf, uint16_t len, uint16_t offset); static ssize_t write_led_state(struct bt_conn *conn, const struct bt_gatt_attr * attr, void *buf, uint16_t len, uint16_t offset, uint8_t flags); BT_GATT_SERVICE_DEFINE(custom_srv, BT_GATT_PRIMARY_SERVICE(BT_UUID_MY_CUSTOM_SERVICE), BT_GATT_CHARACTERISTIC(BT_UUID_LED_STATE_CHRC, (BT_GATT_CHRC_READ | BT_GATT_CHRC_WRITE), (BT_GATT_PERM_READ | BT_GATT_PERM_WRITE), read_led_state, write_led_state, &led_state), ); static ssize_t read_led_state(struct bt_conn *conn, const struct bt_gatt_attr * attr, void *buf, uint16_t len, uint16_t offset) { return bt_gatt_attr_read(conn, attr, buf, len, offset, &led_state, sizeof(led_state)); } static ssize_t write_led_state(struct bt_conn *conn, const struct bt_gatt_attr * attr, void *buf, uint16_t len, uint16_t offset, uint8_t flags) { memcpy(&led_state, buf, sizeof(led_state)); if (len != sizeof(led_state)) { return BT_GATT_ERR(BT_ATT_ERR_INVALID_ATTRIBUTE_LEN); } if (led_state) { gpio_pin_set_dt(&led, 1); pwm_set_pulse_dt(&pwm_led0, 4000000); } else { gpio_pin_set_dt(&led, 0); pwm_set_pulse_dt(&pwm_led0, 1000000); } return len; } void bt_ready(int err) { if (err) { LOG_ERR("bt enable return %d", err); } LOG_INF("bt ready!"); ble_ready = true; } int init_ble(void) { LOG_INF("Init BLE"); int err; err = bt_enable(bt_ready); if (err) { LOG_ERR("bt_enable failed (err %d)", err); return err; } } void main(void) { init_ble(); while(!ble_ready) { LOG_INF("BLE stack not ready yet"); k_msleep(100); } LOG_INF("BLE stack ready"); int err; err = bt_le_adv_start(BT_LE_ADV_CONN_NAME, ad, ARRAY_SIZE(ad), NULL, 0); if (err) { printk("Advertising failed to start (err %d)\n", err); } err = gpio_pin_configure_dt(&led, GPIO_OUTPUT_ACTIVE); if (err < 0) { LOG_INF("LED not configures"); } while(1) { //k_msleep(2000); } }
import React, { useEffect } from 'react'; import { showFormattedDate } from '../utils'; import NotesCard from './NotesCardComponents/NotesCard'; const NotesList = ({ dataSets, deleteFunction, archiveFunction, archivedData }) => { // SET NEW ARRAY OBJECT FORMATTED DATE const newDatas = dataSets.map((data) => ({ ...data, createdAt: showFormattedDate(data.createdAt), })); useEffect(() => { console.log(newDatas); }, [newDatas]); return ( <> <div className="mt-16"> <p className="text-xl font-semibold text-center">Catatan</p> <hr className="w-1/6 mx-auto mb-10" /> <div className="mx-auto flex flex-wrap justify-center"> {newDatas.length === 0 ? ( <p>- Tidak Ada Catatan -</p> ) : newDatas.filter((data) => !data.archived).length === 0 ? ( <p>- Tidak Ada Catatan -</p> ) : ( newDatas.map((data) => !data.archived && <NotesCard key={data.id} deleteFunction={deleteFunction} archiveFunction={archiveFunction} {...data} />) )} </div> <p className="text-xl font-semibold text-center mt-16">Arsip</p> <hr className="w-1/6 mx-auto mb-10" /> <div className="mx-auto flex flex-wrap justify-center"> {archivedData.length === 0 || dataSets.length === 0 ? ( <p className="mb-10">- Arsip Kosong -</p> ) : newDatas.filter((data) => data.archived).length === 0 ? ( <p className="mb-10">- Arsip Tidak Ditemukan -</p> ) : ( newDatas.map((data) => data.archived && <NotesCard key={data.id} deleteFunction={deleteFunction} archiveFunction={archiveFunction} {...data} />) )} </div> </div> </> ); }; export default NotesList;
import time from random import randrange import names from selenium.webdriver.common.by import By from selenium.webdriver.support.ui import Select from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.support import expected_conditions as ec from selenium.common.exceptions import NoSuchElementException, TimeoutException from api.APIClient import APIClient from .Bot import Bot from configs.logger import get_logger from models.Source import Source from models.tokens import outlook_token class OutlookBot(Bot): def __init__(self, client: APIClient, token: dict = outlook_token, proxy: str | None = None): super().__init__(client, token, proxy) self.login_link = '' self.registration_link = 'https://signup.live.com/' self.source = Source.Outlook self.logger = get_logger(__name__) def _register(self, email: str | None = None) -> bool: try: self.driver.get(self.registration_link) self.logger.info( F"Start registration to LinkedIn account with email: {email} and proxy: {self.proxy}") self.driver.maximize_window() except Exception as e: self.logger.exception(f"Failed to open the link with Exception: {str(e)}") self.wait.until(ec.element_to_be_clickable((By.ID, "MemberName"))).send_keys(email) self.wait.until(ec.element_to_be_clickable((By.ID, "iSignupAction"))).click() self.wait.until(ec.element_to_be_clickable((By.ID, "PasswordInput"))).send_keys("strongPASS") self.wait.until(ec.element_to_be_clickable((By.ID, "iSignupAction"))).click() self.wait.until(ec.element_to_be_clickable((By.ID, "FirstName"))).send_keys(names.get_first_name()) self.wait.until(ec.element_to_be_clickable((By.ID, "LastName"))).send_keys(names.get_last_name()) self.wait.until(ec.element_to_be_clickable((By.ID, "iSignupAction"))).click() month_select_element = self.wait.until( ec.element_to_be_clickable((By.ID, "BirthMonth"))) month_select = Select(month_select_element) month_select.select_by_value(str(randrange(1, 12))) day_select_element = self.wait.until( ec.element_to_be_clickable((By.ID, "BirthDay"))) day_select = Select(day_select_element) day_select.select_by_value(str(randrange(1, 28))) self.wait.until(ec.element_to_be_clickable((By.ID, "BirthYear"))).send_keys(str(randrange(1990, 2000))) self.wait.until(ec.element_to_be_clickable((By.ID, "iSignupAction"))).click() verification_code_input = self.wait.until(ec.element_to_be_clickable((By.ID, "VerificationCode"))) time.sleep(40) onesecmail_params = { 'action': 'getMessages', 'login': email.split('@')[0], 'domain': '1secmail.com', } verification_code = self.client.get_verification_code(onesecmail_params, Source.Outlook, True) verification_code_input.send_keys(verification_code) self.wait.until(ec.element_to_be_clickable((By.ID, "iSignupAction"))).click() self.wait.until(ec.presence_of_element_located((By.ID, "StickyFooter"))).find_element(By.ID, "id__0").click() self.wait.until(ec.element_to_be_clickable((By.ID, "idSIButton9"))).click() try: self.wait.until(ec.presence_of_element_located((By.ID, "main-content-landing-react"))) self.logger.info("Successful registration!") return True except TimeoutException: self.logger.exception("Failed to register!") return False def create_new_token(self, email: str | None = None) -> None: if not self._register(email): self.logger.info("Failed to register!") return # try: # response = self.client.create_token(self.token) # self.logger.info(f"Token successfully created! {response.content}") # self._close_driver() # except Exception as e: # self.logger.exception(f"Failed to create a new token: {str(e)}") # self._close_driver()
// // EPPainterView.m // EPainter // // Created by Hannibal Yang on 12/21/14. // Copyright (c) 2014 Frankenstein Yang. All rights reserved. // #import "EPPainterView.h" #import "EPDrawPath.h" @interface EPPainterView() @property (assign, nonatomic) CGMutablePathRef path; // 保存所有路径 @property (strong, nonatomic) NSMutableArray *pathArray; // 路径被释放的标记 @property (assign, nonatomic) BOOL pathReleased; @end @implementation EPPainterView - (id)initWithFrame:(CGRect)frame { self = [super initWithFrame:frame]; if (self) { self.backgroundColor = [UIColor whiteColor]; // 实例化路径数组 self.pathArray = [NSMutableArray array]; // 初始化默认属性 self.color = [UIColor blackColor]; self.lineWidth = 8.0f; // 设置手势监听 // 手势识别,监听两个手指的点按事件 // 通过代理通知视图控制器,由视图控制器显示/隐藏工具视图 UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tap:)]; [tap setNumberOfTouchesRequired:2]; [self addGestureRecognizer:tap]; } return self; } /* 在重绘视图内容时,会清空原有所有内容,全部重新绘制 */ - (void)drawRect:(CGRect)rect { CGContextRef context = UIGraphicsGetCurrentContext(); [self drawViewWithContext:context]; } #pragma mark - 重绘视图 - (void)drawViewWithContext:(CGContextRef)context { for (EPDrawPath *drawPath in self.pathArray) { // 数组中可能存在(setImage:)图像,判断绘制图像还是路径 if (drawPath.img != nil) { [drawPath.img drawAtPoint:CGPointMake(100, 100)]; } else { // 用.CGPath进行类型转换 CGContextAddPath(context, drawPath.path.CGPath); [drawPath.color set]; CGContextSetLineWidth(context, drawPath.lineWidth); CGContextSetLineCap(context, kCGLineCapRound); // 绘制路径 CGContextDrawPath(context, kCGPathStroke); } } if (!self.pathReleased) { // 将路径添加到上下文 CGContextAddPath(context, self.path); // 设置上下文属性 [self.color set]; /* CGContextSetLineCap 设置线条顶点(起点、终点)的样式 CGContextSetLineJoin 设置连接点样式 */ CGContextSetLineWidth(context, self.lineWidth); CGContextSetLineCap(context, kCGLineCapRound); // CGContextSetLineJoin(context, kCGLineJoinBevel); /* C 语言 绘制虚线的参数: 1. 上下文 2. 相位:虚线开始的位置,通常设置为0 3. 虚线段的长度数组 4. 虚线段数组的个数 */ // CGFloat length[] = {10.0, 20.0f}; // CGContextSetLineDash(context, 0, length, 2); // 绘制路径 CGContextDrawPath(context, kCGPathStroke); } } - (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event { // 取出手势 UITouch *touch = [touches anyObject]; // 取出点 CGPoint location = [touch locationInView:self]; CGPathAddLineToPoint(self.path, NULL, location.x, location.y); // self.previousPoint = [touch previousLocationInView:self]; // // 使用成员变量记录手指点 // self.point = location; // 重绘视图 [self setNeedsDisplay]; } - (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event { // 实例化路径 self.path = CGPathCreateMutable(); // 新路径开始 self.pathReleased = NO; CGPoint location = [[touches anyObject] locationInView:self]; CGPathMoveToPoint(self.path, NULL, location.x, location.y); } - (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event { // 将路径添加到数组 // 在OC中提供了一个UIBezierPath对象,是对CGPath的封装 // UIBezierPath *path = [UIBezierPath bezierPathWithCGPath:self.path]; EPDrawPath *path = [EPDrawPath drawPathWith:self.path color:self.color lineWidth:self.lineWidth]; [self.pathArray addObject:path]; // 释放路径 CGPathRelease(self.path); // 新路径结束 self.pathReleased = YES; } #pragma mark - 手势监听方法 - (void)tap:(UITapGestureRecognizer *)recognizer { [_delegate painterViewBeTapped]; } #pragma mark - 成员方法 撤销 - (void)undo { // 撤销:删除数组中的最后一项 [self.pathArray removeLastObject]; // 重新绘制 [self setNeedsDisplay]; } - (void)clear { [self.pathArray removeAllObjects]; [self setNeedsDisplay]; } #pragma mark Image的Setter - (void)setImage:(UIImage *)image { // 使用image建立一个EPDrawPath对象 EPDrawPath *path = [[EPDrawPath alloc] init]; path.img = image; // 把EPDrawPath对象添加到数组 [self.pathArray addObject:path]; // 重绘视图 [self setNeedsDisplay]; } #pragma mark - 生成图像(使用绘制路径) - (UIImage *)createImage { // 打开图像上下文 UIGraphicsBeginImageContext(self.bounds.size); // 获取上下文 CGContextRef context = UIGraphicsGetCurrentContext(); for (EPDrawPath *drawPath in self.pathArray) { // 数组中可能存在(setImage:)图像,判断绘制图像还是路径 if (drawPath.img != nil) { [drawPath.img drawAtPoint:CGPointMake(100, 100)]; } else { // 用.CGPath进行类型转换 CGContextAddPath(context, drawPath.path.CGPath); [drawPath.color set]; CGContextSetLineWidth(context, drawPath.lineWidth); CGContextSetLineCap(context, kCGLineCapRound); // 绘制路径 CGContextDrawPath(context, kCGPathStroke); } } // 获取图像 UIImage *image = UIGraphicsGetImageFromCurrentImageContext(); // 关闭上下文 UIGraphicsEndImageContext(); // 返回图像 return image; } #pragma mark - 保存照片到相册 - (void)savePhoto { // 生成image,使用图像上下文重新绘制 UIImage *img = [self createImage]; // 保存到相册 UIImageWriteToSavedPhotosAlbum(img, self, @selector(image:didFinishSavingWithError:contextInfo:), nil); } #pragma mark - 照片保存完成 - (void)image:(UIImage *)image didFinishSavingWithError:(NSError *)error contextInfo:(void *)contextInfo { UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"提示" message:@"保存成功!" delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil, nil]; [alert show]; } @end
package blockchain import ( "bytes" "crypto/sha256" "encoding/binary" "fmt" "log" "math" "math/big" "time" ) type ProofOfWork struct { Block *Block Target *big.Int } // NewProof creates a new ProofOfWork structure func NewProof(b *Block) *ProofOfWork { target := big.NewInt(1) target.Lsh(target, uint(256)) target.Div(target, big.NewInt(int64(b.Difficulty))) pow := &ProofOfWork{b, target} return pow } // Run executes proof of work to find the nonce that makes block hash has NumZeros leading zeros func (pow *ProofOfWork) Run() { for pow.Block.Nonce < math.MaxUint32 { if pow.Next(false) { break } } } func (pow *ProofOfWork) Next(delayed bool) (success bool) { var hash [32]byte var intHash big.Int data := pow.BlockToBytes(pow.Block.Nonce) hash = sha256.Sum256(data) intHash.SetBytes(hash[:]) if intHash.Cmp(pow.Target) == -1 { // find the nonce success = true pow.Block.Hash = hash[:] } else { success = false pow.Block.Hash = hash[:] pow.Block.Nonce++ } if delayed { time.Sleep(50 * time.Millisecond) } return } // Validate checks whether the nonce is correct func (pow *ProofOfWork) Validate() bool { var intHash big.Int data := pow.BlockToBytes(pow.Block.Nonce) hash := sha256.Sum256(data) intHash.SetBytes(hash[:]) return intHash.Cmp(pow.Target) == -1 } // --------------------------- func (pow *ProofOfWork) BlockToBytes(nonce uint32) []byte { data := bytes.Join( [][]byte{ pow.Block.PrevHash, NumToBytes(uint32(pow.Block.BlockNum)), NumToBytes(pow.Block.Timestamp), []byte(pow.Block.MinerID), NumToBytes(nonce), pow.HashTxns(), }, []byte{}, ) return data } //NumToBytes Converts a number to bytes. Note that the number must have fixed size, i.e. int64 instead of int. func NumToBytes(num interface{}) []byte { buff := new(bytes.Buffer) err := binary.Write(buff, binary.BigEndian, num) if err != nil { log.Println("[WARN] error when converting number to bytes.", err) } return buff.Bytes() } func (pow *ProofOfWork) HashTxns() []byte { var txBytes [][]byte var txHash [32]byte for _, tx := range pow.Block.Txns { txBytes = append(txBytes, EncodeTxn(tx)) } txHash = sha256.Sum256(bytes.Join(txBytes, []byte{})) return txHash[:] } func EncodeTxn(tx *Transaction) []byte { str := fmt.Sprintf("%v", tx.Data) // TODO: sanity check data := bytes.Join( [][]byte{ []byte(str), tx.ID, tx.Signature, tx.PublicKey, }, []byte{}, ) return data }
import {FaMapMarkerAlt} from 'react-icons/fa' import { MdGroup, MdDateRange, MdDone, MdCheckCircle, MdPerson, MdSportsCricket, } from 'react-icons/md' import './index.css' const LatestMatch = ({latestMatchDetailsObj}) => ( <div className="latestMatchDetailsContainer"> <div className="leftContainer"> <div> <MdGroup size={30} /> <p>{latestMatchDetailsObj.competingTeam}</p> </div> <div> <MdDateRange size={30} /> <p>{latestMatchDetailsObj.date}</p> </div> <div> <FaMapMarkerAlt size={30} /> <p>{latestMatchDetailsObj.venue}</p> </div> <div> <MdCheckCircle size={30} /> <p>{latestMatchDetailsObj.result}</p> </div> </div> <img src={latestMatchDetailsObj.competingTeamLogo} className="latestMatchImageUrl" alt="opponentImage" /> <div className="rightContainer"> <div> <MdSportsCricket size={30} /> <p>First Innings</p> </div> <p>{latestMatchDetailsObj.firstInnings}</p> <div> <MdSportsCricket size={30} /> <p>Second Innings</p> </div> <p>{latestMatchDetailsObj.secondInnings}</p> <div> <MdPerson size={30} /> <p>Man of the Match</p> </div> <p>{latestMatchDetailsObj.manOfTheMatch}</p> <div> <MdPerson size={30} /> <p>Umpires</p> </div> <p>{latestMatchDetailsObj.umpires}</p> </div> </div> ) export default LatestMatch
import { Component, OnInit, Inject, ViewChild } from '@angular/core'; import { Worker } from "../../models/worker.model"; import { WorkerService } from "../../services/worker.service"; import { Subscription } from 'rxjs'; import { Reservation } from "../../models/reservation.model"; import { ReservationService } from "../../services/reservation.service"; import { AuthService } from "../../services/auth.service"; import { User } from 'src/app/models/user.model'; import { NgForm } from '@angular/forms'; declare var $: any; @Component({ selector: 'app-reservation-add', templateUrl: './reservation-add.component.html', styleUrls: ['./reservation-add.component.scss'] }) export class ReservationAddComponent implements OnInit { myString: string = ""; private workerSubscription: Subscription; worker: Worker = { id: -1, firstName: "", lastName: "", companyId: -1, companyName: '', serviceName: "", }; // status: -1 reservation: Reservation = { id: 4, bookedBy: "", // is user id workerId: -9, date: new Date(), status: true }; private user: User = { id: "", username: "", password: "", userType: "", phoneNumber: "" }; /** * * @param as Checks for logged in user * @param ws gets the worker assigned * @param rs sets reservation status * @param datePipe sets date format */ constructor( private as: AuthService, private ws: WorkerService, private rs: ReservationService) { } /** * sets user value and selected worker to pass values to backend */ ngOnInit(): void { this.as.loggedUser.subscribe(result => { this.user = result; }) this.workerSubscription = this.ws.getWorker().subscribe((worker: Worker) => { this.worker = worker; }); } /** * Deselects worker */ ngOnDestroy() { this.workerSubscription.unsubscribe(); } /** * * @param form gets form values to set variables */ onSubmit(form: NgForm) { if (form.value.invalid) { return; } this.reservation.id = 99; this.reservation.bookedBy = this.user.id; this.reservation.workerId = this.worker.id; this.reservation.status = true; // this.rs.register(this.reservation).toPromise().then(res => { // form.resetForm(); // }).catch(err => console.log(err)); this.rs.register(this.reservation).subscribe(res => { if (res) form.resetForm(); }); } }
import React, { useState, useEffect } from "react"; import MoviesCardList from "../MoviesCardList/MoviesCardList"; import Footer from "../../Footer/Footer"; import SearchForm from "../../Movies/SearchForm/SearchForm"; import Header from "../../Header/Header"; import { filterMovies, filterDurationMovies, } from "../../../utils/configFunctions"; function SavedMovies({ loggedIn, onDeleteCard, savedMovies }) { const [searchQuery, setSearchQuery] = useState(""); const [filteredMovies, setFilteredMovies] = useState(savedMovies); const [isShortMovies, setisShortMovies] = useState(false); const [isNotFound, setIsNotFound] = useState(false); useEffect(() => { const moviesFilmList = filterMovies(savedMovies, searchQuery); setFilteredMovies( isShortMovies ? filterDurationMovies(moviesFilmList) : moviesFilmList ); }, [savedMovies, isShortMovies, searchQuery]); useEffect(() => { if (filteredMovies.length === 0) { setIsNotFound(true); } else { setIsNotFound(false); } }, [filteredMovies]); function handleToggleShortMovies() { setisShortMovies(!isShortMovies); } function setSearchQueryValue(query) { setSearchQuery(query); } return ( <section className="movies"> <Header loggedIn={loggedIn} /> <SearchForm onFilterMovies={handleToggleShortMovies} setSearchQueryValue={setSearchQueryValue} /> <MoviesCardList cards={filteredMovies} savedMovies={savedMovies} isSavedFilms={true} onDeleteCard={onDeleteCard} isNotFound={isNotFound} /> <Footer /> </section> ); } export default SavedMovies;
import React from 'react' import { Grid } from "@mui/material"; import { TextField, Typography } from "@mui/material"; import { useState } from "react"; import AdapterDateFns from '@mui/lab/AdapterDateFns'; import LocalizationProvider from '@mui/lab/LocalizationProvider'; import DatePicker from '@mui/lab/DatePicker'; export default function Publication() { const [value, setValue] = React.useState(null); const [values, setValues] = useState({ title: "", publisher: "", URL:"", description:"", }); const handleChange = (event) => { setValues({ ...values, [event.target.name]: event.target.value, }); }; return ( <Grid container spacing={3} justifyContent="center"> <Grid item md={12}> <TextField id="outlined-basic" label="Title" name="title" placeholder="Ex: Giving and receving feedback" variant="outlined" size="small" onChange={handleChange} value={values.title} fullWidth /> </Grid> <Grid item md={12}> <TextField id="outlined-basic" label="Publication/Publisher" name="publisher" placeholder="Ex: Hardvard Business Review" variant="outlined" size="small" onChange={handleChange} value={values.publisher} fullWidth /> </Grid> <Grid item md={12}> <LocalizationProvider dateAdapter={AdapterDateFns}> <DatePicker label="Publication date" value={value} onChange={(newValue) => { setValue(newValue); }} renderInput={(params) => <TextField {...params} fullWidth size='small'/>} /> </LocalizationProvider> </Grid> <Grid item md={12}> <TextField id="outlined-basic" label="Publication URL" name="URL" variant="outlined" size="small" onChange={handleChange} value={values.URL} fullWidth /> </Grid> <Grid item md={12}> <TextField id="outlined-basic" label="Description" variant="outlined" placeholder='Write Something' multiline fullWidth minRows={3} size="small" name="description" onChange={handleChange} value={values.description} /> </Grid> </Grid> ) }
import java.util.*; class GenrePlayItem { String genre; int totalPlays; PriorityQueue<int[]> playQueue; public GenrePlayItem(String genre){ this.genre = genre; totalPlays = 0; playQueue = new PriorityQueue<int[]>((o1,o2) -> { return o2[1] - o1[1]; }); } public void addItem(int[] item){ this.totalPlays += item[1]; playQueue.add(item); } } class Solution { public int[] solution(String[] genres, int[] plays) { Map<String,GenrePlayItem> genrePlayMap = new HashMap<>(); int size = genres.length; for(int i = 0; i < size; i++){ if(genrePlayMap.containsKey(genres[i])){ genrePlayMap.get(genres[i]).addItem(new int[]{i,plays[i]}); } else{ genrePlayMap.put(genres[i], new GenrePlayItem(genres[i])); genrePlayMap.get(genres[i]).addItem(new int[]{i,plays[i]}); } } PriorityQueue<GenrePlayItem> genreOrderQueue = new PriorityQueue<GenrePlayItem>((o1,o2) -> { return o2.totalPlays - o1.totalPlays; }); for(Map.Entry<String,GenrePlayItem> item : genrePlayMap.entrySet()){ genreOrderQueue.add(item.getValue()); } List<Integer> answerList = new ArrayList<>(); while(!genreOrderQueue.isEmpty()){ PriorityQueue<int[]> playQueue = genreOrderQueue.poll().playQueue;; int count = 0; while(!playQueue.isEmpty() && count < 2){ answerList.add(playQueue.poll()[0]); count++; } } int[] answer = new int[answerList.size()]; for(int i = 0; i < answerList.size(); i++){ answer[i] = answerList.get(i); } return answer; } }
'use client'; import { useRef } from 'react'; import { WineInfo } from './model/WineInfo'; import { postWine } from './api/postWine'; import { postProduct } from './api/postProduct'; import { useWineKindList } from './hooks/useWineKindList'; import WineInfoByCategory from './components/WineInfoByCategory'; import { addWine } from './utils/addWine'; import { addProduct } from './utils/addProduct'; import withAuth from '@/common/hocs/withAuth'; function AddWinePage() { const wineList = useWineKindList(); const formRef = useRef<HTMLFormElement | null>(null); const onSubmitWineInfo = async () => { const winePostProps = addWine(formRef, wineList); if (winePostProps) { await postWine(winePostProps) .then(async ({ _id }) => { const productPostProps = addProduct(formRef, _id); await postProduct(productPostProps) .then(() => { window.alert('와인이 등록되었습니다!'); }) .catch(() => { window.alert( `product 등록에 실패했습니다. ${_id} 와인에 대해 문의 바랍니다.` ); }); }) .catch(() => { window.alert('wine 등록에 실패했습니다.'); }); } }; return ( <div className="h-screen overflow-y-scroll"> <div className="text-3xl font-bold pl-5">와인 추가</div> <form ref={formRef} className="flex flex-col w-full gap-5 px-5 py-5" onSubmit={(e) => { e.preventDefault(); onSubmitWineInfo(); }} > {WineInfo.map((info) => { return <WineInfoByCategory wineCategory={info} />; })} <button type="submit" className="self-end w-24 h-12 rounded-xl text-xl text-white bg-blue-500" > 저장 </button> </form> </div> ); } export default withAuth(AddWinePage);
import 'package:flutter/material.dart'; import 'package:org_template/components/inventory_components/inventory_list.dart'; class InventoryPage extends StatefulWidget { const InventoryPage({super.key}); @override State<InventoryPage> createState() => _InventoryPageState(); } class _InventoryPageState extends State<InventoryPage> { @override Widget build(BuildContext context) { return Container( color: Theme.of(context).colorScheme.background, child: Center( child: Row( children: <Widget>[ // First Column - Buttons Expanded( flex: 1, child: Column( children: <Widget>[ // Add your buttons here ElevatedButton( onPressed: () {}, child: const Text('Button 1'), ), ElevatedButton( onPressed: () {}, child: const Text('Button 2'), ), // Add more buttons as needed ], ), ), // Second Column - Container with Search and List Expanded( flex: 4, child: Column( children: <Widget>[ // Title const Text( 'Inventory', style: TextStyle( fontSize: 24, fontWeight: FontWeight.bold, ), ), Expanded( child: Padding( padding: const EdgeInsets.all(8.0), child: Card( elevation: 0, color: Theme.of(context).canvasColor, child: Column( children: [ /* SEARCH BOX */ Padding( padding: const EdgeInsets.all(8.0), child: SizedBox( width: 600, child: TextField( decoration: InputDecoration( filled: true, fillColor: Theme.of(context).brightness == Brightness.light ? Colors.white : Theme.of(context).canvasColor, labelText: 'Search', border: const OutlineInputBorder(), ), ), ), ), // ROW with titles for the inventory list like: Item, Quantity, Price, etc. IntrinsicHeight( child: Card( elevation: 0, color: Theme.of(context).primaryColor, child: const Row( mainAxisAlignment: MainAxisAlignment.spaceAround, children: [ Expanded( flex: 2, child: Text( 'Item Name', textAlign: TextAlign.center, style: TextStyle( fontWeight: FontWeight.bold, height: 3, ), ), ), VerticalDivider( color: Colors.grey, thickness: 1, ), Expanded( flex: 1, child: Text( 'Quantity', textAlign: TextAlign.center, style: TextStyle( fontWeight: FontWeight.bold, height: 3, ), ), ), VerticalDivider( color: Colors.grey, thickness: 1, ), Expanded( child: Text( 'Price', textAlign: TextAlign.center, style: TextStyle( fontWeight: FontWeight.bold, height: 3), ), ), VerticalDivider( color: Colors.grey, thickness: 1, ), Expanded( child: Text( 'Total', textAlign: TextAlign.center, style: TextStyle( fontWeight: FontWeight.bold, height: 3, ), ), ), VerticalDivider( color: Colors.grey, thickness: 1, indent: 10, endIndent: 10, ), // empty space for the edit and delete buttons Expanded( child: SizedBox(), ), ], ), ), ), const ItemListView(), // LIST ], ), ), ), ), ], ), ), ], ), ), ); } }
rm(list=ls()) library(readxl) Bonds <- read_excel("~/Desktop/UofT/2021-22/WINTER 2022/APM466/Assignment 1/Data/Bonds.xlsx") ## Creating variables that measure the time to maturity of bonds for each day we collected data Bonds$ttm10 <- as.numeric(as.Date(Bonds$Maturity) - as.Date(as.character("2022/01/10"), format="%Y/%m/%d"))/365.25 Bonds$ttm11 <- as.numeric(as.Date(Bonds$Maturity) - as.Date(as.character("2022/01/11"), format="%Y/%m/%d"))/365.25 Bonds$ttm12 <- as.numeric(as.Date(Bonds$Maturity) - as.Date(as.character("2022/01/12"), format="%Y/%m/%d"))/365.25 Bonds$ttm13 <- as.numeric(as.Date(Bonds$Maturity) - as.Date(as.character("2022/01/13"), format="%Y/%m/%d"))/365.25 Bonds$ttm14 <- as.numeric(as.Date(Bonds$Maturity) - as.Date(as.character("2022/01/14"), format="%Y/%m/%d"))/365.25 Bonds$ttm17 <- as.numeric(as.Date(Bonds$Maturity) - as.Date(as.character("2022/01/17"), format="%Y/%m/%d"))/365.25 Bonds$ttm18 <- as.numeric(as.Date(Bonds$Maturity) - as.Date(as.character("2022/01/18"), format="%Y/%m/%d"))/365.25 Bonds$ttm19 <- as.numeric(as.Date(Bonds$Maturity) - as.Date(as.character("2022/01/19"), format="%Y/%m/%d"))/365.25 Bonds$ttm20 <- as.numeric(as.Date(Bonds$Maturity) - as.Date(as.character("2022/01/20"), format="%Y/%m/%d"))/365.25 Bonds$ttm21 <- as.numeric(as.Date(Bonds$Maturity) - as.Date(as.character("2022/01/21"), format="%Y/%m/%d"))/365.25 ## 4a ## empty matrix to store ytm data ytmdata <- data.frame(matrix(, nrow = 11, ncol = 10)) ## Using Newton's method to compute ytm of each bond each day for(i in 7:16){ ytmdata[1, i-6] <- -log(Bonds[1,i]/(100+100*Bonds$Coupon[1]))/Bonds[1, i+10] for(j in 2:11){ p_i <- Bonds$Coupon[j]*100 f <- function(r){ sum1 <- 0 for(k in 1:(j-1)){ sum1 <- sum1 - exp(-r*Bonds[k, i+10]) } z = Bonds[j,i] + p_i*sum1 - (100+p_i)*exp(-r*Bonds[j, i+10]) } df <- function(r){ sum2 <- 0 for(k in 1:(j-1)){ sum2 <- sum2 + Bonds[k,i+10]*exp(-r*Bonds[k,i+10]) } z = p_i*sum2 + (100+p_i)*Bonds[j,i+10]*exp(-r*Bonds[j,i+10]) } x1 <- 0.1 n <- 1 while(n<10){ n <- n+1 y1 <- f(x1) y2 <- df(x1) x2 <- x1 - y1/y2 x1 <- x2 } ytmdata[j, i-6] <- x1 } } colors = c("black", "blue", "red", "green", "yellow", "purple", "grey", "brown", "cornsilk", "cyan") ## Plotting the Yield Curves xaxis <- seq(0, 5, by = 0.5) plot(xaxis, ytmdata$X1, type = "l", ylim = c(0,0.06), xlab="Maturity (in Years)", ylab="Yield To Maturity", col=colors[1], main="Yield Curve") for(i in 2:10){ lines(xaxis, ytmdata[1:11, i], col=colors[i]) } legend(4, 0.025, cex=0.38, legend=c("10-Jan", "11-Jan", "12-Jan", "13-Jan", "14-Jan", "17-Jan", "18-Jan", "19-Jan", "20-Jan", "21-Jan"), col=colors, lty=1:1) ## 4b ## Computing the spot rate for the first bond with no coupons remaining for(i in 7:16){ Bonds[1 , i+20] <- -log(Bonds[1 , i]/(100+100*Bonds[1,2]))/Bonds[1, i+10] } ## Using bootstrapping to compute the spot rates for(j in 2:11){ for(i in 7:16){ p_i <- Bonds$Coupon[j]*100 sum <- 0 for(k in 1:(j-1)){ sum <- sum - exp(-Bonds[k, i+20]*Bonds[k, i+10]) } Bonds[j, i+20] <- -log((Bonds[j, i] + p_i*sum)/(100+p_i))/Bonds[j, i+10] } } ## empty matrix to store spot rates yields <- data.frame(matrix(, nrow = 11, ncol = 10)) ## filling up the matrix with spot rates for(i in 1:11){ for(j in 1:10){ yields[i,j] <- Bonds[i, j+26] } } ## Plotting the spot curve plot(xaxis, yields[1:11, 1], ylim = c(0,0.06), type ="l", xlab = "Maturity (in Years)", ylab="Spot Rate", col=colors[1], main="Spot Curve") for(i in 2:10){ lines(xaxis, yields[1:11, i], col=colors[i]) } legend(4, 0.025, cex=0.38, legend=c("10-Jan", "11-Jan", "12-Jan", "13-Jan", "14-Jan", "17-Jan", "18-Jan", "19-Jan", "20-Jan", "21-Jan"), col=colors, lty=1:1) ## 4c ## empty matrix to store forward rates forward <- data.frame(matrix(, nrow = 9, ncol = 11)) ## computing forward rates using spot rates for(j in 1:9){ for(i in 1:10){ forward[j,i] <- (yields[j+2,i]*Bonds[j+2,i+16] - yields[j,i]*Bonds[j,i+16])/(Bonds[j+2,i+16]-Bonds[j,i+16]) } } ## Plotting forward rates plot(xaxis[2:10], forward$X1, ylim = c(0,0.08), type="l", xlab="Maturity (in Years)", ylab="1 Year Forward Rate", col=colors[1], main="Forward Curve") for(i in 2:9){ lines(xaxis[2:10], forward[1:9,i], col=colors[i]) } legend(4, 0.028, cex=0.38, legend=c("10-Jan", "11-Jan", "12-Jan", "13-Jan", "14-Jan", "17-Jan", "18-Jan", "19-Jan", "20-Jan", "21-Jan"), col=colors, lty=1:1) ## 5 ## empty matrix to store log-return of yield logyield <- data.frame(matrix(, nrow = 5, ncol = 9)) ## computing log-return of yield for(i in 1:5){ for(j in 1:9){ logyield[i,j] <- log(ytmdata[((2*i)+1),j+1]/ytmdata[((2*i)+1),j]) } } ## covariance matrix of the transpose of log-return of yield ly_cov <- cov(t(logyield)) ## empty matrix to store log-return of forward rates logforward <- data.frame(matrix(, nrow = 5, ncol = 9)) ## computing log-return of forward rates for(i in 1:5){ for(j in 1:9){ logforward[i,j] <- log(forward[2*i-1,j+1]/forward[2*i-1,j]) } } ## covariance matrix of the transpose of log-return of forward rates lf_cov <- cov(t(logforward)) ## 6 ## eigenvalues and eigenvectors of both covariance matrices eigen(ly_cov) eigen(lf_cov)
import importlib import subprocess # List of package names to check and install packages_to_check = ['requests', 'pandas'] for package in packages_to_check: try: importlib.import_module(package) print(f"{package} is installed.") except ImportError: print(f"{package} is not installed. Installing...") subprocess.check_call(['pip', 'install', package]) print(f"{package} has been installed.") import requests from bs4 import BeautifulSoup import pandas as pd cookies = { '_cfuvid': 'jrpN8a3IqRfE4A3ALIquXSLKg_Cdm2UMxkfpXSdJPjI-1697354870445-0-604800000', '_pk_ref.2.1556': '%5B%22%22%2C%22%22%2C1697354871%2C%22https%3A%2F%2Fwww.google.com%2F%22%5D', '_pk_id.2.1556': '807466cabd7b6df9.1697354871.', '_pk_ses.2.1556': '1', 'ref': 'zerodha', } headers = { 'authority': 'zerodha.com', 'accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.7', 'accept-language': 'en-US,en;q=0.9', # 'cookie': '_cfuvid=jrpN8a3IqRfE4A3ALIquXSLKg_Cdm2UMxkfpXSdJPjI-1697354870445-0-604800000; _pk_ref.2.1556=%5B%22%22%2C%22%22%2C1697354871%2C%22https%3A%2F%2Fwww.google.com%2F%22%5D; _pk_id.2.1556=807466cabd7b6df9.1697354871.; _pk_ses.2.1556=1; ref=zerodha', 'referer': 'https://zerodha.com/', 'sec-ch-ua': '"Chromium";v="118", "Google Chrome";v="118", "Not=A?Brand";v="99"', 'sec-ch-ua-mobile': '?0', 'sec-ch-ua-platform': '"Windows"', 'sec-fetch-dest': 'document', 'sec-fetch-mode': 'navigate', 'sec-fetch-site': 'same-origin', 'sec-fetch-user': '?1', 'upgrade-insecure-requests': '1', 'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/118.0.0.0 Safari/537.36', } response = requests.get('https://zerodha.com/margin-calculator/Futures/', cookies=cookies, headers=headers) soup = BeautifulSoup(response.text, 'html.parser') rows = soup.find_all('tr') headers = [header.text.strip() for header in rows[0].find_all('th')] data = [] for row in rows[1:]: row_data = [cell.text.strip() for cell in row.find_all('td')] data.append(row_data) def func(cell): if cell is not None: return pd.Series(cell.split('\n')[:2] if cell is not None else ['','']) df = pd.DataFrame(data,columns= headers) df.dropna(axis = 0,inplace=True) df[["Contract","Date"]] = df["Contract"].apply(func) df.to_csv('Final_Result.csv',index = False)
import logging from functools import partial from multiprocessing import Pool, cpu_count import numpy as np from tqdm import tqdm from example_freature import MRCFeatures, is_whitespace, is_chinese_char import torch from torch.utils.data import TensorDataset logger = logging.getLogger(__name__) def eliminate_whitespace_in_chinese(text): new_text = "" for i, char in enumerate(text): if char == " ": if is_chinese_char(text[max(0,i-1)]) or is_chinese_char(text[min(i+1,len(text)-1)]): continue new_text += char else: new_text += char return new_text def _improve_answer_span(doc_tokens, input_start, input_end, tokenizer, orig_answer_text): """Returns tokenized answer spans that better match the annotated answer.""" tok_answer_text = " ".join(tokenizer.tokenize(orig_answer_text)) for new_start in range(input_start, input_end + 1): for new_end in range(input_end, new_start - 1, -1): text_span = " ".join(doc_tokens[new_start: (new_end + 1)]) if text_span == tok_answer_text: return (new_start, new_end) # logger.info("answer not improved origin=%s \t answer=%s \t old=%s", orig_answer_text, tok_answer_text, " ".join(doc_tokens[input_start: (input_end + 1)])) return (input_start, input_end) def _check_is_max_context(doc_spans, cur_span_index, position): """Check if this is the 'max context' doc span for the token.""" # if len(doc_spans) == 1: # return True best_score = None best_span_index = None for (span_index, doc_span) in enumerate(doc_spans): end = doc_span["start"] + doc_span["length"] - 1 if position < doc_span["start"]: continue if position > end: continue num_left_context = position - doc_span["start"] num_right_context = end - position score = min(num_left_context, num_right_context) + 0.01 * doc_span["length"] if best_score is None or score > best_score: best_score = score best_span_index = span_index return cur_span_index == best_span_index def whitespace_tokenize(text): """Runs basic whitespace cleaning and splitting on a piece of text.""" text = text.strip() if not text: return [] tokens = text.split() return tokens def mrc_convert_example_to_features(example, tokenizer, max_seq_length, doc_stride, max_query_length, is_training): features = [] labels = None if is_training: labels = example.labels if is_training and not example.is_impossible: # Get start and end position start_position = example.start_position end_position = example.end_position # If the answer cannot be found in the text, then skip this example. actual_text = "".join(example.doc_tokens[start_position: (end_position + 1)])#.replace(" ","") cleaned_answer_text = "".join(example.answer_text.strip().split()) if actual_text.find(cleaned_answer_text) == -1: print(example.doc_tokens[start_position-2 : (end_position + 1)]) logger.warning("Could not find answer: '%s' vs. '%s'", actual_text, cleaned_answer_text) return [] tok_to_orig_index = [] orig_to_tok_index = [] all_doc_tokens = [] for (i, token) in enumerate(example.doc_tokens): orig_to_tok_index.append(len(all_doc_tokens)) sub_tokens = tokenizer.tokenize(token) for sub_token in sub_tokens: tok_to_orig_index.append(i) all_doc_tokens.append(sub_token) # print(all_doc_tokens) if is_training and not example.is_impossible: tok_start_position = orig_to_tok_index[example.start_position] if example.end_position < len(example.doc_tokens) - 1: tok_end_position = orig_to_tok_index[example.end_position + 1] - 1 else: tok_end_position = len(all_doc_tokens) - 1 (tok_start_position, tok_end_position) = _improve_answer_span( all_doc_tokens, tok_start_position, tok_end_position, tokenizer, example.answer_text ) # if tok_start_position != old_start or tok_end_position != old_end: # print("haha") # print(old_start, old_end, tok_start_position, tok_end_position) # print(example.answer_text) # print(all_doc_tokens[old_start:old_end+1]) # print(all_doc_tokens[tok_start_position:tok_end_position+1]) # print() # span_answer = "".join(all_doc_tokens[tok_start_position:tok_end_position+1]).replace("##","") # if example.answer_text.lower() != span_answer: # print(example.answer_text.lower()) # print(span_answer) # print() spans = [] truncated_query = tokenizer.encode(example.question_text, add_special_tokens=False, max_length=max_query_length, truncation=True) sequence_added_tokens = ( tokenizer.model_max_length - tokenizer.max_len_single_sentence + 1 if "roberta" in str(type(tokenizer)) else tokenizer.model_max_length - tokenizer.max_len_single_sentence ) # print("sequence_added_tokens",sequence_added_tokens) sequence_pair_added_tokens = tokenizer.model_max_length - tokenizer.max_len_sentences_pair # print("sequence_pair_added_tokens",sequence_pair_added_tokens) # span_doc_tokens = all_doc_tokens token_spans = [] rest_length = max_seq_length - len(truncated_query) - sequence_pair_added_tokens for i in range(0, len(all_doc_tokens), doc_stride): token_spans.append(all_doc_tokens[i:i+rest_length]) if i+rest_length >= len(all_doc_tokens): break # while len(spans) * doc_stride < len(all_doc_tokens): for span_doc_tokens in token_spans: # print(len(spans), doc_stride, len(all_doc_tokens)) # print(truncated_query, span_doc_tokens) if len(span_doc_tokens) == 0: break encoded_dict = tokenizer.encode_plus( truncated_query if tokenizer.padding_side == "right" else span_doc_tokens, span_doc_tokens if tokenizer.padding_side == "right" else truncated_query, max_length=max_seq_length, return_overflowing_tokens=True, padding='max_length', # stride=max_seq_length - doc_stride - len(truncated_query) - sequence_pair_added_tokens, # stride=doc_stride, # truncation_strategy= truncation="only_second" if tokenizer.padding_side == "right" else "only_first", ) paragraph_len = min( len(all_doc_tokens) - len(spans) * doc_stride, max_seq_length - len(truncated_query) - sequence_pair_added_tokens, ) # print(encoded_dict["input_ids"]) if tokenizer.pad_token_id in encoded_dict["input_ids"]: # print("haha") if tokenizer.padding_side == "right": non_padded_ids = encoded_dict["input_ids"][: encoded_dict["input_ids"].index(tokenizer.pad_token_id)] else: last_padding_id_position = ( len(encoded_dict["input_ids"]) - 1 - encoded_dict["input_ids"][::-1].index(tokenizer.pad_token_id) ) non_padded_ids = encoded_dict["input_ids"][last_padding_id_position + 1 :] else: non_padded_ids = encoded_dict["input_ids"] tokens = tokenizer.convert_ids_to_tokens(non_padded_ids) token_to_orig_map = {} for i in range(paragraph_len): index = len(truncated_query) + sequence_added_tokens + i if tokenizer.padding_side == "right" else i token_to_orig_map[index] = tok_to_orig_index[len(spans) * doc_stride + i] encoded_dict["paragraph_len"] = paragraph_len encoded_dict["tokens"] = tokens encoded_dict["token_to_orig_map"] = token_to_orig_map encoded_dict["truncated_query_with_special_tokens_length"] = len(truncated_query) + sequence_added_tokens encoded_dict["token_is_max_context"] = {} encoded_dict["start"] = len(spans) * doc_stride encoded_dict["length"] = paragraph_len spans.append(encoded_dict) if "overflowing_tokens" not in encoded_dict: break # print() # print(span_doc_tokens) # print(len(span_doc_tokens)) # span_doc_tokens = encoded_dict["overflowing_tokens"] # print(span_doc_tokens) # print() for doc_span_index in range(len(spans)): for j in range(spans[doc_span_index]["paragraph_len"]): is_max_context = _check_is_max_context(spans, doc_span_index, doc_span_index * doc_stride + j) index = ( j if tokenizer.padding_side == "left" else spans[doc_span_index]["truncated_query_with_special_tokens_length"] + j ) spans[doc_span_index]["token_is_max_context"][index] = is_max_context for span in spans: # Identify the position of the CLS token cls_index = span["input_ids"].index(tokenizer.cls_token_id) # p_mask: mask with 1 for token than cannot be in the answer (0 for token which can be in an answer) # Original TF implem also keep the classification token (set to 0) (not sure why...) p_mask = np.array(span["token_type_ids"]) p_mask = np.minimum(p_mask, 1) if tokenizer.padding_side == "right": # Limit positive values to one p_mask = 1 - p_mask p_mask[np.where(np.array(span["input_ids"]) == tokenizer.sep_token_id)[0]] = 1 # Set the CLS index to '0' p_mask[cls_index] = 0 span_is_impossible = example.is_impossible start_position = 0 end_position = 0 if is_training and not span_is_impossible: # For training, if our document chunk does not contain an annotation # we throw it out, since there is nothing to predict. doc_start = span["start"] doc_end = span["start"] + span["length"] - 1 out_of_span = False # print(doc_start, doc_end) if not (tok_start_position >= doc_start and tok_end_position <= doc_end): out_of_span = True if out_of_span: start_position = cls_index end_position = cls_index span_is_impossible = True else: if tokenizer.padding_side == "left": doc_offset = 0 else: doc_offset = len(truncated_query) + sequence_added_tokens start_position = tok_start_position - doc_start + doc_offset end_position = tok_end_position - doc_start + doc_offset assert span["tokens"][doc_offset-1] == '[SEP]' # print(tok_start_position, start_position, doc_start, doc_offset) # if all_doc_tokens[tok_start_position] != span["tokens"][start_position]: # print(all_doc_tokens[tok_start_position]) # print(span["tokens"][start_position]) # print(span["tokens"][start_position-20:start_position+20]) # if is_training and start_position != 0: # actual_text = example.answer_text.replace(" ", "") # actual_text22 = "".join(all_doc_tokens[tok_start_position: (tok_end_position + 1)]).lower() # span_answer = span["tokens"][start_position:end_position+1] # span_answer = "".join(span_answer).replace("##", "") # if actual_text.lower() != span_answer: # print(actual_text) # print(actual_text22) # print(span_answer) # print() features.append( MRCFeatures( span["input_ids"], span["attention_mask"], span["token_type_ids"], cls_index, p_mask.tolist(), example_index=0, # Can not set unique_id and example_index here. They will be set after multiple processing. unique_id=0, paragraph_len=span["paragraph_len"], token_is_max_context=span["token_is_max_context"], tokens=span["tokens"], token_to_orig_map=span["token_to_orig_map"], start_position=start_position, end_position=end_position, is_impossible=span_is_impossible, labels=labels, ) ) return features def mrc_convert_example_to_features_init(tokenizer_for_convert): global tokenizer tokenizer = tokenizer_for_convert def convert_features(features, is_training): new_features = [] unique_id = 1000000000 example_index = 0 for example_features in features: if not example_features: continue for example_feature in example_features: example_feature.example_index = example_index example_feature.unique_id = unique_id new_features.append(example_feature) unique_id += 1 example_index += 1 features = new_features del new_features # Convert to Tensors and build dataset all_input_ids = torch.tensor([f.input_ids for f in features], dtype=torch.long) all_attention_masks = torch.tensor([f.attention_mask for f in features], dtype=torch.long) all_token_type_ids = torch.tensor([f.token_type_ids for f in features], dtype=torch.long) all_cls_index = torch.tensor([f.cls_index for f in features], dtype=torch.long) all_p_mask = torch.tensor([f.p_mask for f in features], dtype=torch.float) all_is_impossible = torch.tensor([f.is_impossible for f in features], dtype=torch.float) if not is_training: all_example_index = torch.arange(all_input_ids.size(0), dtype=torch.long) dataset = TensorDataset( all_input_ids, all_attention_masks, all_token_type_ids, all_example_index, all_cls_index, all_p_mask ) else: all_start_positions = torch.tensor([f.start_position for f in features], dtype=torch.long) all_end_positions = torch.tensor([f.end_position for f in features], dtype=torch.long) all_labels = torch.tensor([f.labels for f in features], dtype=torch.long) dataset = TensorDataset( all_input_ids, all_attention_masks, all_token_type_ids, all_start_positions, all_end_positions, all_cls_index, all_p_mask, all_is_impossible, all_labels ) return features, dataset def mrc_convert_examples_to_features_multiprocessing(examples, tokenizer, max_seq_length, doc_stride, max_query_length, is_training, threads=1): # Defining helper methods features = [] threads = min(threads, cpu_count()) with Pool(threads, initializer=mrc_convert_example_to_features_init, initargs=(tokenizer,)) as p: annotate_ = partial( mrc_convert_example_to_features, tokenizer=tokenizer, max_seq_length=max_seq_length, doc_stride=doc_stride, max_query_length=max_query_length, is_training=is_training, ) features = list( tqdm( p.imap(annotate_, examples, chunksize=32), total=len(examples), desc="Convert Features", ) ) features, dataset = convert_features(features, is_training) return features, dataset def mrc_convert_examples_to_features(examples, tokenizer, max_seq_length, doc_stride, max_query_length, is_training, threads=1): """ Converts a list of examples into a list of features that can be directly given as input to a model. It is model-dependant and takes advantage of many of the tokenizer's features to create the model's inputs. Args: examples: list of :class:`~mrcExample` tokenizer: an instance of a child of :class:`~transformers.PreTrainedTokenizer` max_seq_length: The maximum sequence length of the inputs. doc_stride: The stride used when the context is too large and is split across several features. max_query_length: The maximum length of the query. is_training: whether to create features for model evaluation or model training. threads: multiple processing threadsa-smi Returns: list of :class:`mrcFeatures` """ if threads > 1: return mrc_convert_examples_to_features_multiprocessing(examples, tokenizer, max_seq_length, doc_stride, max_query_length, is_training, threads) features = [] for example in tqdm(examples, desc="Convert Features"): feature = mrc_convert_example_to_features(example, tokenizer, max_seq_length, doc_stride, max_query_length, is_training) features.append(feature) features, dataset = convert_features(features, is_training) return features, dataset
using DotLiquid.Tags; using DotLiquid.Util; using LibraryManagement.Application.Interfaces; using LibraryManagement.Data.EF; using LibraryManagement.Data.Enums; using LibraryManagement.DTO.Blog; using LibraryManagement.DTO.BookRequest; using MailKit.Net.Smtp; using MailKit.Security; using Microsoft.EntityFrameworkCore; using Microsoft.Extensions.Configuration; using MimeKit; using static LibraryManagement.Data.Enums.StatusBlogEnums; using static LibraryManagement.Data.Enums.StatusEnums; namespace LibraryManagement.Application.Services { public class EmailService : IEmailService { private readonly IConfiguration _configuration; private readonly LibraryManagementDbContext _context; public EmailService(IConfiguration configuration, LibraryManagementDbContext context) { _configuration = configuration; _context = context; } public async Task SendEmailAsync(string bookRequestId) { var bookRequest = await _context.BookRequests .Include(r => r.BookDetail) .Include(r => r.UserAccount).ThenInclude(r => r.User) .Where(r => r.IsDeleted == false && r.Id == bookRequestId) .Select(r => new GetBookRequestByIdResponse() { Id = r.Id, Code = r.Code, UserAccountId = r.UserAccountId.ToString(), UserAvatar = r.UserAccount.Avatar, UserName = r.UserAccount.User.Name, UserEmail = r.UserAccount.UserName, UserCode = r.UserAccount.User.UserCode, UserAddress = r.UserAccount.User.Address, UserPhone = r.UserAccount.User.PhoneNumber, PublishedBookId = r.BookDetail.PublishedBookId, PublishedBookName = r.BookDetail.PublishedBook.Book.Name, PublishedBookImage = r.BookDetail.PublishedBook.Image, BookDetailCode = r.BookDetail.Code, BookCheckoutId = null, BookDetailId = r.BookDetailId, BookTaked = null, Status = StatusEnums.GetDisplayName((Status)r.Status), CreatedTime = r.CreatedTime, RejectedTime = r.RejectedTime, ApprovedTime = r.ApprovedTime, ReceivedTime = r.ReceivedTime, BorrowedTime = r.BorrowedTime, DueTime = r.DueTime, ReturnedTime = r.ReturnedTime, CanceledTime = r.CanceledTime, }).FirstOrDefaultAsync(); var email = new MimeMessage(); var builder = new BodyBuilder(); email.From.Add(new MailboxAddress("MinsCars Library", _configuration["EmailSettings:AdminEmailAddress"])); if(bookRequest.Status == "Pending") { email.To.Add(MailboxAddress.Parse("khakhongkhung@gmail.com")); }else { email.To.Add(MailboxAddress.Parse(bookRequest.UserEmail)); } switch (bookRequest.Status) { case "Pending": builder.HtmlBody = GetPendingEmailContent(bookRequest); email.Subject = "[MinsCars Library] Hệ thống có yêu cầu mới"; break; case "Approve": builder.HtmlBody = GetApproveEmailContent(bookRequest); email.Subject = "[MinsCars Library] Thông báo đã duyệt yêu cầu mượn sách"; break; case "Borrowing": builder.HtmlBody = GetBorrowingEmailContent(bookRequest); email.Subject = "[MinsCars Library] Xác nhận thông tin mượn sách"; break; case "Rejected": builder.HtmlBody = GetRejectedEmailContent(bookRequest); email.Subject = "[MinsCars Library] Thông báo từ chối yêu cầu mượn sách"; break; case "Extend": builder.HtmlBody = GetExtendEmailContent(bookRequest); email.Subject = "[MinsCars Library] Xác nhận thông tin gia hạn thời gian mượn sách"; break; } email.Body = builder.ToMessageBody(); SmtpClient smtpClient = new SmtpClient(); await smtpClient.ConnectAsync(_configuration["EmailSettings:EmailHost"], 587, SecureSocketOptions.StartTls); await smtpClient.AuthenticateAsync(_configuration["EmailSettings:AdminEmailAddress"], _configuration["EmailSettings:AdminEmailPassword"]); await smtpClient.SendAsync(email); await smtpClient.DisconnectAsync(true); } public async Task SendEmailExtendAsync(string bookRequestId) { var bookRequest = await _context.BookRequests .Include(r => r.BookDetail) .Include(r => r.UserAccount).ThenInclude(r => r.User) .Where(r => r.IsDeleted == false && r.Id == bookRequestId) .Select(r => new GetBookRequestByIdResponse() { Id = r.Id, Code = r.Code, UserAccountId = r.UserAccountId.ToString(), UserAvatar = r.UserAccount.Avatar, UserName = r.UserAccount.User.Name, UserEmail = r.UserAccount.UserName, UserCode = r.UserAccount.User.UserCode, UserAddress = r.UserAccount.User.Address, UserPhone = r.UserAccount.User.PhoneNumber, PublishedBookId = r.BookDetail.PublishedBookId, PublishedBookName = r.BookDetail.PublishedBook.Book.Name, PublishedBookImage = r.BookDetail.PublishedBook.Image, BookDetailCode = r.BookDetail.Code, BookCheckoutId = null, BookDetailId = r.BookDetailId, BookTaked = null, Status = StatusEnums.GetDisplayName((Status)r.Status), CreatedTime = r.CreatedTime, RejectedTime = r.RejectedTime, ApprovedTime = r.ApprovedTime, ReceivedTime = r.ReceivedTime, BorrowedTime = r.BorrowedTime, DueTime = r.DueTime, ExtendedTime = r.ExtendedTime, ReturnedTime = r.ReturnedTime, CanceledTime = r.CanceledTime, }).FirstOrDefaultAsync(); var email = new MimeMessage(); var builder = new BodyBuilder(); email.From.Add(new MailboxAddress("MinsCars Library", _configuration["EmailSettings:AdminEmailAddress"])); email.To.Add(MailboxAddress.Parse(bookRequest.UserEmail)); builder.HtmlBody = GetExtendEmailContent(bookRequest); email.Subject = "[MinsCars Library] Xác nhận thông tin gia hạn thời gian mượn sách"; email.Body = builder.ToMessageBody(); SmtpClient smtpClient = new SmtpClient(); await smtpClient.ConnectAsync(_configuration["EmailSettings:EmailHost"], 587, SecureSocketOptions.StartTls); await smtpClient.AuthenticateAsync(_configuration["EmailSettings:AdminEmailAddress"], _configuration["EmailSettings:AdminEmailPassword"]); await smtpClient.SendAsync(email); await smtpClient.DisconnectAsync(true); } public async Task SendEmailExtendAdminAsync(string bookRequestId) { var bookRequest = await _context.BookRequests .Include(r => r.BookDetail) .Include(r => r.UserAccount).ThenInclude(r => r.User) .Where(r => r.IsDeleted == false && r.Id == bookRequestId) .Select(r => new GetBookRequestByIdResponse() { Id = r.Id, Code = r.Code, UserAccountId = r.UserAccountId.ToString(), UserAvatar = r.UserAccount.Avatar, UserName = r.UserAccount.User.Name, UserEmail = r.UserAccount.UserName, UserCode = r.UserAccount.User.UserCode, UserAddress = r.UserAccount.User.Address, UserPhone = r.UserAccount.User.PhoneNumber, PublishedBookId = r.BookDetail.PublishedBookId, PublishedBookName = r.BookDetail.PublishedBook.Book.Name, PublishedBookImage = r.BookDetail.PublishedBook.Image, BookDetailCode = r.BookDetail.Code, BookCheckoutId = null, BookDetailId = r.BookDetailId, BookTaked = null, Status = StatusEnums.GetDisplayName((Status)r.Status), CreatedTime = r.CreatedTime, RejectedTime = r.RejectedTime, ApprovedTime = r.ApprovedTime, ReceivedTime = r.ReceivedTime, BorrowedTime = r.BorrowedTime, DueTime = r.DueTime, ExtendedTime = r.ExtendedTime, ReturnedTime = r.ReturnedTime, CanceledTime = r.CanceledTime, }).FirstOrDefaultAsync(); var email = new MimeMessage(); var builder = new BodyBuilder(); email.From.Add(new MailboxAddress("MinsCars Library", _configuration["EmailSettings:AdminEmailAddress"])); email.To.Add(MailboxAddress.Parse("khakhongkhung@gmail.com")); builder.HtmlBody = GetExtendEmailAdminContent(bookRequest); email.Subject = "[MinsCars Library] Xác nhận thông tin gia hạn thời gian mượn sách"; email.Body = builder.ToMessageBody(); SmtpClient smtpClient = new SmtpClient(); await smtpClient.ConnectAsync(_configuration["EmailSettings:EmailHost"], 587, SecureSocketOptions.StartTls); await smtpClient.AuthenticateAsync(_configuration["EmailSettings:AdminEmailAddress"], _configuration["EmailSettings:AdminEmailPassword"]); await smtpClient.SendAsync(email); await smtpClient.DisconnectAsync(true); } public async Task SendMailBlogAsync(string blogId) { var blog = await _context.Blogs .Include(p => p.UserAccount).ThenInclude(p => p.User) .Where(p => p.IsDeleted == false && p.Id == blogId) .OrderByDescending(p => p.CreatedDate) .Select(p => new GetBlogByIdResponse() { Id = p.Id, UserAccountId = p.UserAccountId, Avatar = p.UserAccount.Avatar, UserName = p.UserAccount.User.Name, UserCode = p.UserAccount.User.UserCode, Address = p.UserAccount.User.Address, PhoneNumber = p.UserAccount.User.PhoneNumber, Email = p.UserAccount.UserName, Title = p.Title, Image = p.Image, Content = p.Content, Status = StatusBlogEnums.GetDisplayName((StatusBlog)p.Status), CreatedDate = p.CreatedDate, IsDeleted = p.IsDeleted, PostedDate = p.PostedDate, }).FirstOrDefaultAsync(); var email = new MimeMessage(); var builder = new BodyBuilder(); email.From.Add(new MailboxAddress("MinsCars Library", _configuration["EmailSettings:AdminEmailAddress"])); if(blog.Status == "Pending") { email.To.Add(MailboxAddress.Parse("khakhongkhung@gmail.com")); builder.HtmlBody = GetNewBlogContent(blog); email.Subject = "[MinsCars Library] Hệ thống vừa nhận được yêu cầu đăng bài blog mới"; }else if(blog.Status == "Posted") { email.To.Add(MailboxAddress.Parse(blog.Email)); builder.HtmlBody = GetApproveBlogEmailContent(blog); email.Subject = "[MinsCars Library] Thông báo đã duyệt yêu cầu đăng bài blog"; } else { email.To.Add(MailboxAddress.Parse(blog.Email)); builder.HtmlBody = GetRejectedBlogEmailContent(blog); email.Subject = "[MinsCars Library] Thông báo từ chối yêu cầu đăng bài blog"; } email.Body = builder.ToMessageBody(); SmtpClient smtpClient = new SmtpClient(); await smtpClient.ConnectAsync(_configuration["EmailSettings:EmailHost"], 587, SecureSocketOptions.StartTls); await smtpClient.AuthenticateAsync(_configuration["EmailSettings:AdminEmailAddress"], _configuration["EmailSettings:AdminEmailPassword"]); await smtpClient.SendAsync(email); await smtpClient.DisconnectAsync(true); } private string GetApproveEmailContent(GetBookRequestByIdResponse bookRequest) { var content = $"<p>Mến chào bạn đọc!</p>"; content += $"<p>Ban quản lý MinsCars Library xin được thông báo với bạn đọc thông tin yêu cầu mượn sách như sau:</p>"; content += $"<ul>" + $"<li>Mã yêu cầu: <b>{bookRequest.Code}</b>" + $"<li>Tên sách: {bookRequest.PublishedBookName}" + $"<li>Mã sách: {bookRequest.BookDetailCode}" + $"<li>Yêu cầu mượn sách <b>đã được duyệt</b> vào ngày lúc: <b>{bookRequest.ApprovedTime.Value.ToString("dd/MM/yyyy HH:mm")}</b></li>" + $"</ul>"; content += $"<p> Bạn đọc vui lòng đến thư viện vào ngày <b>{bookRequest.DueTime.Value.ToString("dd/MM/yyyy")}</b> để lấy sách! " + $"Bạn nhớ lấy đúng quyển sách có mã <b>{bookRequest.BookDetailCode}</b> và gặp Thủ thư xác nhận!" + $"Sau thời gian trên, bạn đọc không đến lấy sách thì yêu cầu mượn sách sẽ tự động hủy!</p>"; content += $"<p> Bạn đọc vui lòng kiểm tra lại thông tin và liên hệ ngay với thu thư nếu có sai sót!</p>"; content += $"<p>Mọi chi tiết vui lòng liên hệ: </p>"; content += $"<ul>" + $"<li>Email: minscarslibrary@gmail.com</li>" + $"<li>Số điện thoại: 0398 897 634 (gặp cô Thủ thư xinh đẹp)</li>" + $"</ul>"; return content; } private string GetBorrowingEmailContent(GetBookRequestByIdResponse bookRequest) { var content = $"<p>Mến chào bạn đọc!</p>"; content += $"<p>Ban quản lý MinsCars Library xin được thông báo với bạn đọc thông tin yêu cầu mượn sách như sau:</p>"; content += $"<ul>" + $"<li>Mã yêu cầu: <b>{bookRequest.Code}</b>" + $"<li>Tên sách: <b>{bookRequest.PublishedBookName}</b>" + $"<li>Mã sách: <b>{bookRequest.BookDetailCode}</b>" + $"<li>Ngày nhận sách: <b>{bookRequest.BorrowedTime.Value.ToString("dd/MM/yyyy HH:mm")}</b></li>" + $"<li>Ngày trả sách: <b>{bookRequest.DueTime.Value.ToString("dd/MM/yyyy")}</b></li>" + $"</ul>"; content += $"<p> Bạn đọc có thể <b>gia hạn tài liệu</b> tại mục <b>Yêu cầu</b> trong hệ thống!</p>"; content += $"<p> Bạn đọc vui lòng kiểm tra lại thông tin và liên hệ ngay với thu thư nếu có sai sót và bạn nhớ trả sách đúng hạn nhé!</p>"; content += $"<p>Mọi chi tiết vui lòng liên hệ: </p>"; content += $"<ul>" + $"<li>Email: minscarslibrary@gmail.com</li>" + $"<li>Số điện thoại: 0398 897 634 (gặp cô Thủ thư xinh đẹp)</li>" + $"</ul>"; return content; } private string GetRejectedEmailContent(GetBookRequestByIdResponse bookRequest) { var content = $"<p>Mến chào bạn đọc!</p>"; content += $"<p>Ban quản lý MinsCars Library xin được thông báo với bạn đọc yêu cầu mượn sách của bạn đã bị hủy với thông tin cụ thể như sau:</p>"; content += $"<ul>" + $"<li>Mã yêu cầu: <b>{bookRequest.Code}</b>" + $"<li>Tên sách: <b>{bookRequest.PublishedBookName}</b>" + $"<li>Mã sách: <b>{bookRequest.BookDetailCode}</b>" + $"<li>Ngày tạo yêu cầu: <b>{bookRequest.CreatedTime.Value.ToString("dd/MM/yyyy HH:mm")}</b></li>" + $"<li>Ngày dự kiến nhận sách: <b>{bookRequest.DueTime.Value.ToString("dd/MM/yyyy")}</b></li>" + $"<li>Trạng thái yêu cầu: <b>Đã bị hủy</b></li>" + $"<li>Lý do: <b>Không đến lấy sách đúng hạn.</b></li>" + $"</ul>"; content += $"<p>Cảm ơn bạn đã sử dụng dịch vụ của chúng tôi! Bạn có thể tạo yêu cầu mượn sách mới tại hệ thống thư viện nhé! </p>"; content += $"<p>Mọi chi tiết vui lòng liên hệ: </p>"; content += $"<ul>" + $"<li>Email: minscarslibrary@gmail.com</li>" + $"<li>Số điện thoại: 0398 897 634 (gặp cô Thủ thư xinh đẹp)</li>" + $"</ul>"; return content; } private string GetPendingEmailContent(GetBookRequestByIdResponse bookRequest) { var content = $"<p>Chào John!</p>"; content += $"<p>Hệ thống vừa nhận được một yêu cầu mượn sách mới, thông tin yêu cầu như sau:</p>"; content += $"<ul>" + $"<li>Mã yêu cầu: <b>{bookRequest.Code}</b>" + $"<li>Tên sách: <b>{bookRequest.PublishedBookName}</b>" + $"<li>Mã sách: <b>{bookRequest.BookDetailCode}</b>" + $"<li>Ngày tạo yêu cầu: <b>{bookRequest.CreatedTime.Value.ToString("dd/MM/yyyy HH:mm")}</b></li>" + $"<li>Trạng thái yêu cầu: <b>{bookRequest.Status}</b></li>" + $"</ul>"; content += $"<p>Bạn vào hệ thống để xem cụ thể nhé! </p>"; return content; } private string GetExtendEmailContent(GetBookRequestByIdResponse bookRequest) { var content = $"<p>Mến chào bạn đọc!</p>"; content += $"<p>Ban quản lý MinsCars Library xin được thông báo với bạn đọc thông tin yêu cầu gian hạn thời gian sách như sau:</p>"; content += $"<ul>" + $"<li>Mã yêu cầu: <b>{bookRequest.Code}</b>" + $"<li>Tên sách: <b>{bookRequest.PublishedBookName}</b>" + $"<li>Mã sách: <b>{bookRequest.BookDetailCode}</b>" + $"<li>Ngày nhận sách: <b>{bookRequest.BorrowedTime.Value.ToString("dd/MM/yyyy HH:mm")}</b></li>"; content += $"<li>Thời gian gia hạn: <b>{bookRequest.ExtendedTime.Value.ToString("dd/MM/yyyy HH:mm")}</b></li>"; content+= $"<li>Ngày trả sách: <b>{bookRequest.DueTime.Value.ToString("dd/MM/yyyy")}</b></li>" + $"</ul>"; content += $"<p> <b>Lưu ý:</b> Bạn đọc chỉ <b>gia hạn mượn tài liệu được 01 lần</b>!</p>"; content += $"<p> Bạn đọc vui lòng kiểm tra lại thông tin và liên hệ ngay với thu thư nếu có sai sót và bạn nhớ trả sách đúng hạn nhé!</p>"; content += $"<p>Mọi chi tiết vui lòng liên hệ: </p>"; content += $"<ul>" + $"<li>Email: minscarslibrary@gmail.com</li>" + $"<li>Số điện thoại: 0398 897 634 (gặp cô Thủ thư xinh đẹp)</li>" + $"</ul>"; return content; } private string GetExtendEmailAdminContent(GetBookRequestByIdResponse bookRequest) { var content = $"<p>Chào John!</p>"; content += $"<p>Độc giả <b>{bookRequest.UserName}</b> vừa gian hạn thời gian mượn tài liệu, thông tin yêu cầu như sau:</p>"; content += $"<ul>" + $"<li>Mã yêu cầu: <b>{bookRequest.Code}</b>" + $"<li>Tên sách: <b>{bookRequest.PublishedBookName}</b>" + $"<li>Mã sách: <b>{bookRequest.BookDetailCode}</b>" + $"<li>Ngày tạo yêu cầu: <b>{bookRequest.CreatedTime.Value.ToString("dd/MM/yyyy HH:mm")}</b></li>" + $"<li>Ngày nhận sách: <b>{bookRequest.BorrowedTime.Value.ToString("dd/MM/yyyy HH:mm")}</b></li>" + $"<li>Thời gian gia hạn: <b>{bookRequest.ExtendedTime.Value.ToString("dd/MM/yyyy HH:mm")}</b></li>" + $"<li>Ngày trả sách: <b>{bookRequest.DueTime.Value.ToString("dd/MM/yyyy")}</b></li>" + $"<li>Trạng thái yêu cầu: <b>{bookRequest.Status}</b></li>" + $"</ul>"; content += $"<p>Bạn vào hệ thống để xem cụ thể nhé! </p>"; return content; } private string GetNewBlogContent(GetBlogByIdResponse blog) { var content = $"<p>Chào John!</p>"; content += $"<p>Hệ thống vừa nhận được một yêu cầu đăng bài blog mới, thông tin yêu cầu như sau:</p>"; content += $"<ul>" + $"<li>Tiêu đề: <b>{blog.Title}</b>" + $"<li>Độc giả: <b>{blog.UserName}</b>" + $"<li>Ngày tạo yêu cầu: <b>{blog.CreatedDate.Value.ToString("dd/MM/yyyy HH:mm")}</b></li>" + $"<li>Trạng thái yêu cầu: <b>{blog.Status}</b></li>" + $"</ul>"; content += $"<p>Bạn vào hệ thống để xem cụ thể nhé! </p>"; return content; } private string GetApproveBlogEmailContent(GetBlogByIdResponse blog) { var content = $"<p>Mến chào bạn đọc <b>{blog.UserName}</b>!</p>"; content += $"<p>Ban quản lý MinsCars Library xin được thông báo với bạn đọc yêu cầu đăng bài blog của bạn <b>đã được duyệt</b>!</p>"; content += $"<p> Bạn đọc vui lòng kiểm tra lại thông tin và liên hệ ngay với thu thư nếu có sai sót!</p>"; content += $"<p>Mọi chi tiết vui lòng liên hệ: </p>"; content += $"<ul>" + $"<li>Email: minscarslibrary@gmail.com</li>" + $"<li>Số điện thoại: 0398 897 634 (gặp cô Thủ thư xinh đẹp)</li>" + $"</ul>"; return content; } private string GetRejectedBlogEmailContent(GetBlogByIdResponse blog) { var content = $"<p>Mến chào bạn đọc <b>{blog.UserName}</b>!</p>"; content += $"<p>Ban quản lý MinsCars Library xin được thông báo với bạn đọc yêu cầu đăng bài blog của bạn <b>đã bị từ chối<b/> vì lý do vi phạm thuần phong mỹ tục!</p>"; content += $"<p> Bạn đọc vui lòng kiểm tra lại thông tin và liên hệ ngay với thu thư nếu có sai sót!</p>"; content += $"<p>Mọi chi tiết vui lòng liên hệ: </p>"; content += $"<ul>" + $"<li>Email: minscarslibrary@gmail.com</li>" + $"<li>Số điện thoại: 0398 897 634 (gặp cô Thủ thư xinh đẹp)</li>" + $"</ul>"; return content; } } }
import { Component, ViewChild, OnInit, AfterViewInit } from '@angular/core'; import { MatDialog } from '@angular/material/dialog'; import { PlanRepas } from 'src/interfaces/planrepas'; import { AddDialogComponent } from '../add-dialog/add-dialog.component'; import { DialogComponent } from '../components/dialog/dialog.component'; import { ClientControllerService } from '../services/client-controller.service'; import { MatSort, Sort } from '@angular/material/sort'; import { MatTableDataSource } from '@angular/material/table'; import { LiveAnnouncer } from '@angular/cdk/a11y'; import { UpdateDialogComponent } from '../update-dialog/update-dialog.component'; const DELETE_CONFIRMATION_MESSAGE = 'Est ce que vous êtes sure de supprimer le plan repas '; @Component({ selector: 'app-plan-repas-table', templateUrl: './plan-repas-table.component.html', styleUrls: ['./plan-repas-table.component.css'] }) export class PlanRepasTableComponent implements OnInit, AfterViewInit { constructor(private readonly controller: ClientControllerService, public dialog: MatDialog, private _liveAnnouncer: LiveAnnouncer) { } displayedColumns: string[] = ['numeroplan', 'categorie', 'frequence', 'nbrcalories', 'nbrpersonnes', 'numerofournisseur', 'prix', 'action']; allPlanRepas: PlanRepas[] = []; dataSource: MatTableDataSource<PlanRepas> = new MatTableDataSource(this.allPlanRepas); dialogOpen: boolean = false; @ViewChild(MatSort) set matSort(sort: MatSort) { this.dataSource.sort = sort; } ngOnInit(): void { this.dialogOpen = false; try { this.controller.getAllPlanRepas().subscribe((allPlanRepas) => { this.allPlanRepas = allPlanRepas; this.dataSource.data = allPlanRepas; }); } catch { } } ngAfterViewInit() { this.dataSource.data = this.allPlanRepas; } add() { if (this.dialogOpen) return; this.dialogOpen = true; try { let addDialog = this.dialog.open(AddDialogComponent, { width: '420px', }); addDialog.afterClosed().subscribe(() => { this.ngOnInit() }); } catch { this.dialogOpen = false; } } update(numeroplan: string) { if (this.dialogOpen) return; this.dialogOpen = true; try { this.dialogOpen = true; let updateDialog = this.dialog.open(UpdateDialogComponent, { width: '420px', data: { numeroplan: numeroplan }, }); updateDialog.afterClosed().subscribe(() => { this.ngOnInit(); this.dialogOpen = false; }); } catch { this.dialogOpen = false; } } delete(numeroplan: string) { if (this.dialogOpen) return; this.dialogOpen = true; try { const deleteDialog = this.dialog.open(DialogComponent, { data: { numeroplan: numeroplan, message: DELETE_CONFIRMATION_MESSAGE + numeroplan + ' ?', buttonText: { ok: ' Oui', cancel: 'Non' } }, width: '420px' }); deleteDialog.afterClosed().subscribe((confirmed: boolean) => { if (confirmed) { this.controller.deletePlanrepas(numeroplan); this.ngOnInit(); this.dialogOpen = false; } }); } catch { } } announceSortChange(sortState: Sort) { if (sortState.direction) { this._liveAnnouncer.announce(`Sorted ${sortState.direction}ending`); } else { this._liveAnnouncer.announce('Sorting cleared'); } } goToGithub() { window.open("https://github.com/rachadchazbek/INF3710_TP4", '_blank'); } }
import SwiftUI public struct Placeholder<T: View>: ViewModifier { private let placeholder: T private let needShow: Bool public init( placeholder: T, needShow: Bool ) { self.placeholder = placeholder self.needShow = needShow } public func body(content: Content) -> some View { ZStack(alignment: .leading) { if needShow { placeholder } content } } } public extension View { func placeholder<T: View>(_ holder: T, needShow: Bool) -> some View { modifier(Placeholder(placeholder: holder, needShow: needShow)) } }
import '/auth/firebase_auth/auth_util.dart'; import '/backend/backend.dart'; import '/flutter_flow/flutter_flow_choice_chips.dart'; import '/flutter_flow/flutter_flow_icon_button.dart'; import '/flutter_flow/flutter_flow_theme.dart'; import '/flutter_flow/flutter_flow_util.dart'; import '/flutter_flow/flutter_flow_widgets.dart'; import '/flutter_flow/form_field_controller.dart'; import 'package:flutter/material.dart'; import 'package:google_fonts/google_fonts.dart'; import 'package:lottie/lottie.dart'; import 'package:provider/provider.dart'; import 'interests_model.dart'; export 'interests_model.dart'; class InterestsWidget extends StatefulWidget { const InterestsWidget({super.key}); @override State<InterestsWidget> createState() => _InterestsWidgetState(); } class _InterestsWidgetState extends State<InterestsWidget> { late InterestsModel _model; final scaffoldKey = GlobalKey<ScaffoldState>(); @override void initState() { super.initState(); _model = createModel(context, () => InterestsModel()); WidgetsBinding.instance.addPostFrameCallback((_) => setState(() {})); } @override void dispose() { _model.dispose(); super.dispose(); } @override Widget build(BuildContext context) { context.watch<FFAppState>(); return GestureDetector( onTap: () => _model.unfocusNode.canRequestFocus ? FocusScope.of(context).requestFocus(_model.unfocusNode) : FocusScope.of(context).unfocus(), child: Scaffold( key: scaffoldKey, backgroundColor: FlutterFlowTheme.of(context).secondaryBackground, appBar: AppBar( backgroundColor: FlutterFlowTheme.of(context).secondaryBackground, automaticallyImplyLeading: false, leading: FlutterFlowIconButton( borderColor: Colors.transparent, borderRadius: 30.0, borderWidth: 1.0, buttonSize: 60.0, icon: Icon( Icons.arrow_back_rounded, color: FlutterFlowTheme.of(context).primary, size: 30.0, ), onPressed: () async { context.pop(); }, ), actions: const [], centerTitle: true, elevation: 0.0, ), body: SafeArea( top: true, child: Padding( padding: const EdgeInsetsDirectional.fromSTEB(15.0, 0.0, 15.0, 10.0), child: Column( mainAxisSize: MainAxisSize.max, mainAxisAlignment: MainAxisAlignment.spaceBetween, crossAxisAlignment: CrossAxisAlignment.start, children: [ Column( mainAxisSize: MainAxisSize.max, mainAxisAlignment: MainAxisAlignment.start, children: [ Padding( padding: const EdgeInsets.all(15.0), child: Column( mainAxisSize: MainAxisSize.max, crossAxisAlignment: CrossAxisAlignment.start, children: [ Text( 'What are you interested in?', style: FlutterFlowTheme.of(context) .bodyMedium .override( fontFamily: FlutterFlowTheme.of(context) .bodyMediumFamily, fontSize: 26.0, letterSpacing: 0.0, fontWeight: FontWeight.w800, useGoogleFonts: GoogleFonts.asMap() .containsKey(FlutterFlowTheme.of(context) .bodyMediumFamily), ), ), Text( 'Interests are used to personalize your experience and will be visible on your profile...', style: FlutterFlowTheme.of(context) .bodyMedium .override( fontFamily: FlutterFlowTheme.of(context) .bodyMediumFamily, color: FlutterFlowTheme.of(context).tertiary, fontSize: 16.0, letterSpacing: 0.0, fontWeight: FontWeight.bold, useGoogleFonts: GoogleFonts.asMap() .containsKey(FlutterFlowTheme.of(context) .bodyMediumFamily), ), ), Text( 'Select atleast one to continue', style: FlutterFlowTheme.of(context) .bodyMedium .override( fontFamily: FlutterFlowTheme.of(context) .bodyMediumFamily, color: FlutterFlowTheme.of(context).secondary, fontSize: 18.0, letterSpacing: 0.0, fontWeight: FontWeight.bold, useGoogleFonts: GoogleFonts.asMap() .containsKey(FlutterFlowTheme.of(context) .bodyMediumFamily), ), ), ].divide(const SizedBox(height: 10.0)), ), ), Padding( padding: const EdgeInsetsDirectional.fromSTEB( 15.0, 30.0, 15.0, 10.0), child: Column( mainAxisSize: MainAxisSize.max, crossAxisAlignment: CrossAxisAlignment.stretch, children: [ FlutterFlowChoiceChips( options: FFAppState() .Interests .map((label) => ChipData(label)) .toList(), onChanged: (val) => setState(() => _model.choiceChipsValues = val), selectedChipStyle: ChipStyle( backgroundColor: FlutterFlowTheme.of(context).primary, textStyle: FlutterFlowTheme.of(context) .bodyMedium .override( fontFamily: FlutterFlowTheme.of(context) .bodyMediumFamily, color: FlutterFlowTheme.of(context) .primaryBackground, letterSpacing: 0.0, useGoogleFonts: GoogleFonts.asMap() .containsKey( FlutterFlowTheme.of(context) .bodyMediumFamily), ), iconColor: FlutterFlowTheme.of(context).primary, iconSize: 18.0, elevation: 4.0, borderRadius: BorderRadius.circular(16.0), ), unselectedChipStyle: ChipStyle( backgroundColor: FlutterFlowTheme.of(context).alternate, textStyle: FlutterFlowTheme.of(context) .bodyMedium .override( fontFamily: FlutterFlowTheme.of(context) .bodyMediumFamily, color: FlutterFlowTheme.of(context) .secondaryText, letterSpacing: 0.0, useGoogleFonts: GoogleFonts.asMap() .containsKey( FlutterFlowTheme.of(context) .bodyMediumFamily), ), iconColor: FlutterFlowTheme.of(context).alternate, iconSize: 18.0, elevation: 0.0, borderRadius: BorderRadius.circular(16.0), ), chipSpacing: 12.0, rowSpacing: 12.0, multiselect: true, initialized: _model.choiceChipsValues != null, alignment: WrapAlignment.start, controller: _model.choiceChipsValueController ??= FormFieldController<List<String>>( [], ), wrapped: true, ), ], ), ), ], ), Lottie.asset( 'assets/lottie_animations/eH2JrNQExY_(1).json', width: 200.0, height: 350.0, fit: BoxFit.cover, animate: true, ), Align( alignment: const AlignmentDirectional(1.0, 1.0), child: FFButtonWidget( onPressed: ((_model.choiceChipsValues != null && (_model.choiceChipsValues)!.isNotEmpty) == false) ? null : () async { await currentUserReference!.update({ ...mapToFirestore( { 'interests': _model.choiceChipsValues, }, ), }); }, text: 'Continue', options: FFButtonOptions( width: 150.0, height: 50.0, padding: const EdgeInsetsDirectional.fromSTEB(24.0, 0.0, 24.0, 0.0), iconPadding: const EdgeInsetsDirectional.fromSTEB(0.0, 0.0, 0.0, 0.0), color: FlutterFlowTheme.of(context).primary, textStyle: FlutterFlowTheme.of(context) .titleSmall .override( fontFamily: FlutterFlowTheme.of(context).titleSmallFamily, color: FlutterFlowTheme.of(context) .secondaryBackground, fontSize: 18.0, letterSpacing: 0.0, useGoogleFonts: GoogleFonts.asMap().containsKey( FlutterFlowTheme.of(context).titleSmallFamily), ), elevation: 3.0, borderSide: const BorderSide( color: Colors.transparent, width: 1.0, ), borderRadius: BorderRadius.circular(8.0), ), ), ), ], ), ), ), ), ); } }
# Conclusion of part 2 Congratulations, we are done going down the reproducibility iceberg. Our project should now be entirely reproducible. I showed you how to reuse the same R version and the same package library as the one that was used to develop the pipeline originally. If in addition you've used the software engineering best practices from part 1, your project is also well tested and documented. This part of the book focused on the operating system your pipeline runs on. It's a bit trickier to "freeze" an operating system, like we froze the R version and the packages library. Strictly speaking, we should develop and deploy our pipeline on the same operating system. If you're using Ubuntu as your daily driver, that is not an issue, but if you're a Windows or a macOS user, then this *could* potentially be a problem. After all, Docker images are based on Ubuntu (or other Linux distributions), so the best we can do is either start developing with the end in mind from the beginning; which means that we develop our project from inside a Docker environment, or we must ensure that running the pipeline inside Docker returns the same results as on your operating system of choice. This should most of the time not be an issue, but as already mentioned in this book, running the same code on Linux or Windows does sometimes return different results (this is rarer, at least in my experience, when comparing Linux to macOS). But there is yet another, potential, issue. Let's assume the best case scenario: the pipeline returns the same result inside Docker as on your development machine (which should be the case most of the time anyways). Is using Docker truly the best we can do? Is the pipeline truly reproducible? Well, *strictly* speaking, not quite. Indeed, the base operating system inside Docker also gets updated. So if you build an image based on Ubuntu 22.04 today, and then again in 6 months, the operating system is not the same anymore, because the software it ships got updated. So even if the R package library and R version remain fixed, the operating system does not. Now, I realize that this is really pushing it, but I want to be as thorough as possible. So there are two ways around this, if you really, absolutely, need also Ubuntu to remain frozen. The first solution is the simplest and is explained in the [reproducibility page](https://rocker-project.org/use/reproducibility.html)^[https://is.gd/YKL0T4] of the Rocker project. The idea is to use a digest, which is the equivalent of a commit hash on Github but for Docker images instead. As the example in the linked page above shows, instead of this: ``` FROM rocker/r-ver:4.2.0 ``` which would base your Docker image on the latest Ubuntu 22.04 shipping R version 4.2.0, you would use this: ``` FROM rocker/r-ver@sha256:b343df137d83b0701e0... ``` which is the digest of the latest rebuild of that image. You can find digests on the Docker Hub page: ::: {.content-hidden when-format="pdf"} <figure> <img src="images/digest.png" alt="You can find Docker image digests on Docker Hub."></img> <figcaption>You can find Docker image digests on Docker Hub.</figcaption> </figure> ::: ::: {.content-visible when-format="pdf"} ```{r, echo = F, out.height="300px"} #| fig-cap: "You can find Docker image digests on Docker Hub." knitr::include_graphics("images/digest.png") ``` ::: If you use a digest instead of a tag, it doesn't matter when the image gets built, you'll be using the exact same Ubuntu version under the hood that was current *at that time*. The second way around this is to use a functional package manager like Guix or Nix. As I stated in the reproducibility iceberg, this is outside the scope of this book, but the idea of these package managers is that they allow users to reproduce the entirety of a project (so including the operating system libraries) to the exact same byte. If you want to know more, take a look at @vallet2022 ([open access article](https://www.nature.com/articles/s41597-022-01720-9#Abs1)^[https://www.nature.com/articles/s41597-022-01720-9#Abs1]) which shows how Guix works by reproducing the results from another paper.
<head> <meta charset="utf-8"> <title>LibrosJ.K</title> <!-- CSS only --> <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-1BmE4kWBq78iYhFldvKuhfTAU6auU8tT94WrHftjDbrCEXSU1oBoqyl2QvZ6jIW3" crossorigin="anonymous"> <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.bundle.min.js" integrity="sha384-ka7Sk0Gln4gmtz2MlQnikT1wXgYsOg+OMhuP+IlRH9sENBO0LRn5q+8nbTov4+1p" crossorigin="anonymous"></script> <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=Noto+Sans:ital,wght@0,100;0,200;0,300;0,400;0,500;0,600;0,700;0,800;0,900;1,100;1,200;1,300;1,400;1,500;1,600;1,700;1,800;1,900&display=swap" rel="stylesheet"> <script defer src="https://use.fontawesome.com/releases/v5.0.7/js/all.js"></script> <link rel="stylesheet" href="body.css"> </head> <body> <section id="titulo"> <div class="container-fluid"> <nav class="navbar navbar-expand-lg navbar-light"> <div class="container-fluid"> <a class="navbar-brand" href="#">LibrosJ.K</a> <button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#navbarNavAltMarkup" aria-controls="navbarNavAltMarkup" aria-expanded="false" aria-label="Toggle navigation"> <span class="navbar-toggler-icon"></span> </button> <div class="collapse navbar-collapse" id="navbarNavAltMarkup"> <div class="navbar-nav"> <a class="nav-link active" aria-current="page" href="#caracteristicas">Características</a> <a class="nav-link" href="#recomendaciones">Recomendaciones</a> <a class="nav-link" href="#cta">Descargar</a> </div> </div> </div> </nav> <!--termina la barra de navegacion--> <div class="container-fluid"> <div class="row"> <div class="col-lg-6"> <h1>Los cuentos de hadas ya no son como antes.</h1> <button type="button" class="btn btn-dark btn-lg download-button"><i class=""></i>Libro Digital</button> <button type="button" class="btn btn-dark btn-lg download-button"><i class=""></i>Libro Fisico</button> <h1>El ickabog</h1> <h3>El ickabog es un cuento de hadas de la escritora J. K. Rowling. Rowling publica gratuitamente el relato en línea por entregas, comenzando en mayo de 2020 y culminando en julio. El mes de noviembre de 2020, la obra íntegra se publicó como libro.​</h3> </div> <div class="col-lg-6"> <img class="title-image" src="imagenes/portada.jpg" alt="iphone-mockup"> </div> </div> </div> </section> <section id="caracteristicas"> <div class="caja-caracteristica"> <div class="row"> <div class="caja-caracteristica col-lg-4"> <h3>Bibliografia.</h3> <br /> <i class="fas fa-address-book fa-4x icon"></i> <p>Todo sobre tus autores favoritos.</p> </div> <div class="caja-caracteristica col-lg-4"> <h3>Mejores Libros.</h3> <br /> <i class="fas fa-book fa-4x icon"></i> <p>Tenemos a todos los cachorros, los mejores cachorros</p> </div> <div class="caja-caracteristica col-lg-4"> <h3>Chat Grupal.</h3> <br /> <i class="fas fa-comment fa-4x icon"></i> <p>Conectate con lectores de todo el mundo.</p> </div> </div> </section> <section id="recomendaciones"> <div id="carousel-recomendaciones" class="carousel slide" data-ride="carousel"> <div class="carousel-inner"> <div class="carousel-item active"> <h2>Desde lo mas profundo del bosque, en esa parte donde ni los más valientes se atreven a entrar</h2> <img class="img-recomendaciones" src="imagenes/ika.jfif" alt="editorial-profile"> <em>El ickabog</em> </div> <div class="carousel-item"> <h2>Es un libro para toda la familia, es el favorito de mis hijos</h2> <img class="img-recomendaciones" src="imagenes/chica.jpg" alt="chica-profile"> <em>Laura, Planeta Tierra</em> </div> </div> <button class="carousel-control-prev" type="button" data-bs-target="#carousel-recomendaciones" data-bs-slide="prev"> <span class="carousel-control-prev-icon" aria-hidden="true"></span> <span class="visually-hidden">Previous</span> </button> <button class="carousel-control-next" type="button" data-bs-target="#carousel-recomendaciones" data-bs-slide="next"> <span class="carousel-control-next-icon" aria-hidden="true"></span> <span class="visually-hidden">Next</span> </button> </div> <section id="cta"> <h3>Encuentranos en:</h3> <button type="button" class="btn btn-dark btn-lg download-button"><i class="fab fa-apple"></i>Descargar</button> <button type="button" class="btn btn-outline-light btn-lg download-button"><i class="fab fa-google-play"></i>Descargar</button> </section> <footer id="footer"> <p>© Copyright 2022 TinPup</p> </footer>
import React, { useEffect, useMemo, useState } from 'react' import { useParams, useNavigate } from 'react-router-dom' import { Grid, Button, TextField, Text, Link, Select, dialog } from '@stage-ui/core' import { ArrowLeft, Plus, Save } from '@stage-ui/icons' import { useForm, Controller } from 'react-hook-form' import { yupResolver } from '@hookform/resolvers/yup' import * as yup from 'yup' import { useMasterContext } from '..' import { Page } from '~/components/Page' import { useTitle } from '~/hooks/useTitle' import { AddCategoryModal } from '~/modals/AddCategoryModal' import { AddServiceModal } from '~/modals/AddServiceModal' import { EnititiesActions } from '~/data/enitities' import { selectCategoriesWithParent, selectCategoriesWithFreeChild, } from '~/data/enitities/select' import { useSelector } from '~/hooks/useSelector' import { HintError } from '~/components/HintError' type EditFormType = { category?: number | null service: number duration: number price: number } const schema = yup.object({ service: yup.number().required('Пожалуйста, укажите услугу'), duration: yup .number() .typeError('Пожалуйста, введите число') .positive('Пожалуйста, укажите положительную длительность') .integer('Пожалуйста, целое число') .required('Пожалуйста, укажите корректную длительность'), price: yup .number() .typeError('Пожалуйста, введите число') .positive('Пожалуйста, укажите положительную стоимость') .integer('Пожалуйста, целое число') .required('Пожалуйста, укажите корректную стоимость'), }) export const MasterServicesEdit = () => { const navigate = useNavigate() const [category, setCategory] = useState<EditFormType['category']>() const { setMenu } = useMasterContext() const { id } = useParams<{ id: string }>() const title = id ? 'Редактирование услуги' : 'Добавление услуги' useTitle(title) useEffect(() => { setMenu('services') EnititiesActions.categoriesFetch() }, []) const { handleSubmit, control, watch, setValue, formState: { isValid }, } = useForm<EditFormType>({ defaultValues: { duration: 0, price: 0 }, mode: 'onChange', resolver: yupResolver(schema), }) const categories = useSelector(selectCategoriesWithParent) const services = useSelector(selectCategoriesWithFreeChild) const loading = useSelector((state) => state.schedule.mutationPending) const categoryOptions = useMemo( () => categories.map((c) => ({ text: c.name, value: c.id })), [categories.length], ) const serviceOptions = useMemo(() => { return services .filter((s) => s.parentId === (category || null)) .map((s) => ({ text: s.name, value: s.id })) }, [services.length, category]) useEffect(() => { const subscription = watch((value, { name }) => { if (name === 'category') setCategory(value.category) }) return () => subscription.unsubscribe() }, [watch]) const handleSave = () => navigate('../services') const fetchService = async () => { if (!id) return const service = await EnititiesActions.serviceFetch(+id) if (!service) { return handleSave() } setValue('duration', service.duration) setValue('price', service.price) setValue('category', service.category.parentId) setValue('service', service.category.id) } useEffect(() => { fetchService() }, [id]) const handleSubmitForm = (data: EditFormType) => { if (!id) { EnititiesActions.serviceCreate( { categoryId: data.service, duration: data.duration, price: data.price, }, handleSave, ) } else { EnititiesActions.serviceUpdate( { serviceId: +id, duration: data.duration, price: data.price, }, handleSave, ) } } const handleClickAddCategory = (e: React.MouseEvent<HTMLDivElement>) => { e.stopPropagation() dialog({ title: 'Новая категория', render: (close) => <AddCategoryModal onClose={close} />, }) } const handleClickAddService = (e: React.MouseEvent<HTMLDivElement>) => { e.stopPropagation() dialog({ title: 'Новая услуга', render: (close) => <AddServiceModal onClose={close} />, }) } return ( <Page title={title} titleLeftChild={ <Button color="onPrimary" borderColor="onSecondary" borderStyle="solid" borderWidth="0.0625rem" onClick={() => navigate('../services')} > <ArrowLeft color="onBackground" /> </Button> } > <form onSubmit={handleSubmit(handleSubmitForm)}> <Grid gap="0.25rem"> <Controller name="category" control={control} render={({ field: { value, onChange }, fieldState: { error } }) => ( <Select clearable label="Категория" placeholder="Выберите категорию" values={categoryOptions.filter((c) => c.value === value)} options={categoryOptions} onChange={(_, option) => { onChange(option?.value as number) }} rightChild={ !id && ( <Link mx="s" onClick={handleClickAddCategory}> Добавить </Link> ) } hint={<HintError error={error?.message} />} disabled={!!id} /> )} /> <Controller name="service" control={control} render={({ field: { value, onChange }, fieldState: { error } }) => ( <Select clearable label="Услуга" placeholder="Выберите услугу" values={serviceOptions.filter((s) => s.value === value)} options={serviceOptions} onChange={(_, option) => { onChange(option?.value as number) }} hint={<HintError error={error?.message} />} rightChild={ !id && ( <Link mx="s" onClick={handleClickAddService}> Добавить </Link> ) } disabled={!!id} /> )} /> <Controller name="duration" control={control} render={({ field: { value, onChange }, fieldState: { error } }) => { return ( <TextField value={value} onChange={(e) => onChange(e.target.value.trim())} label="Длительность" rightChild={<Text>мин</Text>} hint={<HintError error={error?.message} />} /> ) }} /> <Controller name="price" control={control} render={({ field: { value, onChange }, fieldState: { error } }) => ( <TextField value={value} onChange={onChange} label="Стоимость" rightChild={<Text>₽</Text>} hint={<HintError error={error?.message} />} /> )} /> <Button textColor="surface" type="submit" disabled={!isValid || loading}> {id ? <Save /> : <Plus />} <Text pl="s">{id ? 'Сохранить' : 'Добавить'}</Text> </Button> </Grid> </form> </Page> ) } export default MasterServicesEdit
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> <style type="text/css"> .demo{ background: red; width: 300px; height: 400px; border-radius: 10px; } </style> <script src="jquery-1.11.1.js"></script> <script> $(function(){ $("#buttonId").click(function(){ /* * 1:样式的名称, * 2:样式的值.. * 我们一次只能修改一个样式.. * * */ /* $("div").css("font-size","200px"); $("div").css("background","red");*/ /* * * 我们可以把css 的内容封装到一个对象里面去.. * * */ /* var obj={ "background":"red", "font-size":"99px" };*/ /* $("div").css(obj);*/ /* * * 我们开发写代码,我们要解耦.. * * css 代码,应该写在css 的文件里面去. * * js 代码就放在js 文件. * */ /* $("div").addClass("demo")*/ /* setAttribute("","") * * * */ }) /* * * 移除样式. * */ /* $("#removebuttonId").click(function(){ $("div").removeClass("demo"); /!*setAttrite("class","")*!/ }); */ $("#togglebuttonId").click(function(){ /* * 如果class 有值,则把class 的值移除 * 如果class 没有值,再次调用,把原来的值还原... * */ /* $("div").toggleClass();*/ /* * * 为当前元素切换一个样式.. * 如果当前元素有该样式,则移除。 * 如果当前元素没有该样式,则添加... * */ /* $("div").toggleClass("demo");*/ }); $("#hasbuttonId").click(function(){ /* * 判断某个样式是否存在.. * */ var flag=$("div").hasClass("demo"); alert(flag); }) }); </script> </head> <body> <input type="button" value="css 样式操作" id="buttonId"> <input type="button" value="css 移除样式" id="removebuttonId"> <input type="button" value="css 切换样式" id="togglebuttonId"> <input type="button" value="css 判断样式是否存在" id="hasbuttonId"> <div class="demo" > what are you 弄撒勒! </div> </body> </html>
// Copyright Mia srl // SPDX-License-Identifier: Apache-2.0 // // 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 kustomizehelper import ( "errors" "fmt" "os" "path/filepath" "sort" "github.com/mia-platform/vab/internal/utils" "github.com/mia-platform/vab/pkg/apis/vab.mia-platform.eu/v1alpha1" "gopkg.in/yaml.v3" "sigs.k8s.io/kustomize/api/konfig" kustomize "sigs.k8s.io/kustomize/api/types" ) // SyncKustomization read the kustomization file ath path and sync its resources and components properties with // the content of modules and addOns func SyncAllClusterKustomization(basePath string, modules, addOns map[string]v1alpha1.Package) error { allGroupsPath := filepath.Join(basePath, utils.AllGroupsDirPath, utils.BasesDir) kustomization, err := ReadKustomization(allGroupsPath) if err != nil { return fmt.Errorf("failed to read kustomization at path %s: %w", allGroupsPath, err) } resources, err := sortedPackagesPathList(modules, allGroupsPath, filepath.Join(basePath, utils.VendorsModulesPath)) if err != nil { return fmt.Errorf("failed to create a sorted list for modules: %w", err) } components, err := sortedPackagesPathList(addOns, allGroupsPath, filepath.Join(basePath, utils.VendorsAddOnsPath)) if err != nil { return fmt.Errorf("failed to create a sorted list for addons: %w", err) } kustomization.Resources = resources kustomization.Components = components if err := utils.WriteKustomization(*kustomization, allGroupsPath); err != nil { return fmt.Errorf("failed to write kustomization at path %s: %w", allGroupsPath, err) } return nil } // SyncKustomization read the kustomization file ath path and sync its resources and components properties with // the content of modules and addOns specifically for clusters func SyncClusterKustomization(basePath, clusterPath string, modules, addOns map[string]v1alpha1.Package) error { kustomization, err := ReadKustomization(clusterPath) if err != nil { return fmt.Errorf("failed to read kustomization at path %s: %w", clusterPath, err) } var resources, components []string allGroupsDirPath := filepath.Join(basePath, utils.AllGroupsDirPath) if len(modules) == 0 && len(addOns) == 0 { allGroupsPath, err := filepath.Rel(clusterPath, allGroupsDirPath) if err != nil { return fmt.Errorf("failed to create link to all groups bases: %w", err) } resources = []string{allGroupsPath} } else { resources, err = sortedPackagesPathList(modules, clusterPath, filepath.Join(basePath, utils.VendorsModulesPath)) if err != nil { return fmt.Errorf("failed to create a sorted list for modules: %w", err) } components, err = sortedPackagesPathList(addOns, clusterPath, filepath.Join(basePath, utils.VendorsAddOnsPath)) if err != nil { return fmt.Errorf("failed to create a sorted list for addons: %w", err) } customResourcePath := filepath.Join(allGroupsDirPath, utils.CustomResourcesDir) customResourceseRelativePath, err := filepath.Rel(clusterPath, customResourcePath) if err != nil { return fmt.Errorf("failed to create link to all custom resources: %w", err) } components = append(components, customResourceseRelativePath) } kustomization.Resources = resources kustomization.Components = components if err := utils.WriteKustomization(*kustomization, clusterPath); err != nil { return fmt.Errorf("failed to write kustomization at path %s: %w", clusterPath, err) } return nil } // sortedPackagesPathList return a sorted array of path for the given packages map with paths relative to basePath func sortedPackagesPathList(packages map[string]v1alpha1.Package, basePath, targetPath string) ([]string, error) { sortedList := make([]string, 0) for _, pkg := range packages { if !pkg.Disable { var pkgPath string versionedPath := pkg.GetName() + "-" + pkg.Version if pkg.IsModule() { pkgPath = filepath.Join(versionedPath, pkg.GetFlavorName()) } else { pkgPath = versionedPath } modulePath, err := filepath.Rel(basePath, filepath.Join(targetPath, pkgPath)) if err != nil { return nil, err } sortedList = append(sortedList, modulePath) } } sort.SliceStable(sortedList, func(i, j int) bool { return sortedList[i] < sortedList[j] }) return sortedList, nil } // ReadKustomization reads a kustomization file given its path func ReadKustomization(targetPath string) (*kustomize.Kustomization, error) { // create the path to the kustomization file if it does not exist // useful when creating clusters' sub-directories if err := utils.ValidatePath(targetPath); err != nil { return nil, err } // create the kustomization file if it does not exist kustomizationPath, err := getKustomizationFilePath(targetPath) if err != nil { return nil, fmt.Errorf("error getting kustomization file path for %s: %w", targetPath, err) } kustomization, err := os.ReadFile(kustomizationPath) if err != nil { return nil, fmt.Errorf("error reading kustomization file %s: %w", kustomizationPath, err) } output := &kustomize.Kustomization{} err = yaml.Unmarshal(kustomization, output) if err != nil { return nil, fmt.Errorf("error unmarshaling kustomization file %s: %w", targetPath, err) } return output, nil } // getKustomizationFilePath checks if a kustomization file exists and creates it if missing, // initializing the TypeMeta fields func getKustomizationFilePath(targetPath string) (string, error) { for _, validFileName := range konfig.RecognizedKustomizationFileNames() { kustomizationPath := filepath.Join(targetPath, validFileName) _, err := os.Stat(kustomizationPath) switch { case err == nil: return kustomizationPath, nil // if there is a match, return the valid path to the kustomization file case errors.Is(err, os.ErrNotExist): continue default: return "", fmt.Errorf("error while checking kustomization path %s: %w", kustomizationPath, err) } } // If the execution gets here, it means that no kustomization file with a valid name // was found. A new kustomization file is created (with initialized TypeMeta) kustomizationPath := filepath.Join(targetPath, konfig.DefaultKustomizationFileName()) newKustomization := utils.EmptyKustomization() newKustomization.TypeMeta = kustomize.TypeMeta{ Kind: kustomize.KustomizationKind, APIVersion: kustomize.KustomizationVersion, } if err := utils.WriteKustomization(newKustomization, kustomizationPath); err != nil { return "", fmt.Errorf("error writing kustomization file %s: %w", targetPath, err) } return kustomizationPath, nil } // PackagesMapForPaths return the package map with key the disk path for kustomize func PackagesMapForPaths(packages map[string]v1alpha1.Package) map[string]v1alpha1.Package { pathsMap := make(map[string]v1alpha1.Package, len(packages)) for _, pkg := range packages { newKey := pkg.GetName() + "-" + pkg.Version pathsMap[newKey] = pkg } return pathsMap }
Novo Nordisk Microsoft Entra ID Training - Code Kata #1 This training exercise is a **beginner-level** course on [Microsoft Entra ID](https://learn.microsoft.com/en-us/entra/identity/) at Novo Nordisk and serves as a starting point for developers looking to onboard [Heimdall](https://medium.com/@ZaradarTR/wtf-is-heimdall-646843ec18d0). ## Getting started These instructions will help you prepare for the kata and ensure that your training machine has the tools installed you will need to complete the assignment(s). If you find yourself in a situation where one or more tools might not be available for your training environment please reach out to your instructor for assistance on how to proceed, post an [issue in our repository](https://github.com/NovoNordisk-OpenSource/dojo/issues) or fix it yourself and update the kata via a [pull request](https://github.com/NovoNordisk-OpenSource/dojo/pulls). ### Prerequisites * [Azure](https://portal.azure.com/) * [Azure CLI](https://learn.microsoft.com/en-us/cli/azure/install-azure-cli#install) * [Git](https://git-scm.com/book/en/v2/Getting-Started-Installing-Git) ## Exercise This instructional exercise is meticulously designed to serve as a comprehensive guide, taking you step-by-step through the landscape of [Microsoft Entra ID](https://learn.microsoft.com/en-us/entra/identity/) application registrations. Its purpose is not solely limited to getting you started on the [IAM](https://www.microsoft.com/en-gb/security/business/security-101/what-is-identity-access-management-iam) training; it also aims to provide a detailed walkthrough that acquaints you with the nuanced functionalities of application manifests to ensure we have a broad shared understanding of the taxonomy associated with this particulare subject. ### 1. Login to Azure portal To get started we need to login to Azure to ensure we have permissions to interact with our [Microsoft Entra ID](https://learn.microsoft.com/en-us/entra/identity/) tenant: ```bash az login -u johndoe@contoso.com -p VerySecret ``` ***Note*** <br/> By default, this command logs in with a user account and will pick up on the active windows user if no values are supplied. [Azure CLI](https://learn.microsoft.com/en-us/cli/azure) will try to launch a web browser to log in interactively. If a web browser is not available, CLI will fall back to device code login. To login with a service principal, specify `--service-principal`. ### 2. Create a kata directory Once we have our access permissions sorted we can setup a directory for our exercise files. It's pretty straight forward: ```bash mkdir kata1 cd kata1 ``` ### 3. Create application manifest Next we can proceed to creating a `manifest.json` file in our `kata1` directory that contains the desired state of the application registration we want to provisiong with our Microsoft Entra ID tenant: ```json { "id": "f7f9acfc-ae0c-4d6c-b489-0a81dc1652dd", # Unique identifier for the app in the directory. This ID is not used to identify the app in any protocol transaction. It's used for referencing the object in directory queries. "acceptMappedClaims": false, # Do not set acceptMappedClaims property to true for multi-tenant apps. This can allow malicious actors to create claims-mapping policies for your app. "accessTokenAcceptedVersion": 2, # Possible values for accesstokenAcceptedVersion are 1, 2, or null. If the value is null, this parameter defaults to 1, which corresponds to the v1.0 endpoint. "allowPublicClient": false, # If this value is set to true the fallback application type is public client. The default value is false which means the fallback application type is confidential client. "appRoles": ["MyAppRole"], # Specifies the collection of roles that an app may declare. These roles can be assigned to users, groups, or service principals. "groupMembershipClaims": "None", # Configures the groups claim issued in a user or OAuth 2.0 access token that the app expects. Valid values are: None, SecurityGroup , ApplicationGroup, DirectoryRole, All "optionalClaims": { # The optional claims returned in tokens issued by the security token service for this specific app registration. "idToken": [ { "name": "auth_time", "essential": false } ], "accessToken": [ { "name": "ipaddr", "essential": false } ], "saml2Token": [ { "name": "upn", "essential": false }, { "name": "extension_ab603c56068041afb2f6832e2a17e237_skypeId", "source": "user", "essential": false } ] }, "identifierUris": ["api://f7f9acfc-ae0c-4d6c-b489-0a81dc1652dd"], # User-defined URI(s) that uniquely identify a web app within its Microsoft Entra tenant or verified customer owned domain. "knownClientApplications": ["f7f9acfc-ae0c-4d6c-b489-0a81dc1652dd"], # Used for bundling consent if you have a solution that contains multiple application registrations "oauth2AllowImplicitFlow": false, # Never allow implicit flow. Its dead @ https://developer.okta.com/blog/2019/05/01/is-the-oauth-implicit-flow-dead "oauth2Permissions": [ # Specifies the collection of OAuth 2.0 permission scopes that the web API (resource) app exposes to client apps. { "adminConsentDescription": "Allow the app to access resources on behalf of the signed-in user.", "adminConsentDisplayName": "Access resource1", "id": "<guid>", "isEnabled": true, "type": "User", "userConsentDescription": "Allow the app to access resource1 on your behalf.", "userConsentDisplayName": "Access resources", "value": "user_impersonation" } ], "oauth2RequirePostResponse": false, # Specifies whether, as part of OAuth 2.0 token requests, Microsoft Entra ID will allow POST requests, as opposed to GET requests. "replyUrlsWithType": [ # Registered redirect_uri values that Microsoft Entra ID will accept as destinations when returning tokens. For more info: https://learn.microsoft.com/en-us/entra/identity-platform/reply-url { "url": "https://localhost:4400/services/office365/redirectTarget.html", "type": "InstalledClient" }, { "url": "https://someconfidentialclient/someauthhandler", "type": "Web" }, { "url": "https://somepublicclient/someauthhandler", "type": "Spa" } ], "requiredResourceAccess": [ # Specifies that your application requires access to the resource application (identified by RESOURCE_APP_ID) and requests the specified appRole (identified by GUID_OF_APP_ROLE) defined in that resource application { "resourceAppId": "RESOURCE_APP_ID", "resourceAccess": [ { "id": "GUID_OF_APP_ROLE", "type": "Role" } ] } ], } ``` ***Note*** <br/> Its worth noting that due to limitations in the `AZ CLI` we are only allowed to infer certain values from our application manifest file, however for the sake of completness we have opted to present a more verbose version to ensure that people understand all the key settings that are required for them to succesfully setup an application registration that is compatible with our Heimdall platform. Furthermore the application manifest schema is quiet extensive and our working example only covers the essentials, thus it is worth taking time to [investigate the various configuration options at our disposal](https://learn.microsoft.com/en-us/entra/identity-platform/reference-app-manifest). ### 4. Create application registration With the manifest in hand we can now use the `AZ CLI` to create a new application registration: ```bash # Replace <display-name> with the display name of your Azure App Registration display_name="<display-name>" # Create app registration with desired display name az ad app create --display-name $display_name # Get the ID of the Azure App Registration app_id=$(az ad app list --display-name "$display_name" --query '[].{AppId: appId}' --output tsv) # Update the settings of our new app registration based on our manifest.json az ad app update --id $app_id --app-roles ./manifest.json --optional-claims ./manifest.json --required-resource-accesses ./manifest.json ``` ***Note*** <br/> We cannot directly create an application registration from a `manifest.json` file using the `az ad app create` command. The `az ad app create` command creates a new Azure AD application registration with the specified parameters, but it doesn't accept a manifest file as input. To create an application registration with specific configurations defined in a `manifest.json` file, you would typically create the application first using `az ad app create`, and then update its properties using the `az ad app update` command as shown above. Alternatively you can create the application registration by hand via the Azure portal and paste in the full `manifest.json`. ## Want to help make our training material better? * Want to **log an issue** or **request a new kata**? Feel free to visit our [GitHub site](https://github.com/NovoNordisk-OpenSource/dojo/issues).
import { PropsWithChildren, useRef } from 'react' import dynamic from 'next/dynamic' import Head from 'next/head' import { useRouter } from 'next/router' import { SUPPORTED_CHAINS } from 'config/chains' import { isBsc } from 'utils/isBsc' import { isEthereum } from 'utils/isEthereum' import { useChain, useMediaQuery } from 'hooks' import { StyledLayout, StyledMain } from './styled' import Favicon from 'components/Favicon' import RootFavicon from 'components/RootFavicon' import Suspense from 'components/Suspense' import RootGnb from './Gnb/Root' import MainGnb from './Gnb/Main' const Alerts = dynamic(() => import('./Alerts'), { ssr: false, }) const BalancerPool = dynamic(() => import('components/BalancerPool'), { ssr: false, }) const Modals = dynamic(() => import('components/Modals'), { ssr: false, }) const PancakeSwapPool = dynamic(() => import('components/PancakeSwapPool'), { ssr: false, }) function Layout({ children }: PropsWithChildren) { const mainRef = useRef<HTMLDivElement>(null) const { chainId } = useChain() const { route, pathname, query } = useRouter() useMediaQuery() const isRootPage = pathname === '/' if (isRootPage) { return ( <> <Head> <RootFavicon /> </Head> <StyledLayout layoutRoot $root> <RootGnb /> <StyledMain ref={mainRef} layout> {children} </StyledMain> </StyledLayout> </> ) } const isErrorPage = ['/404', '/500'].includes(route) || (query.chainId && !SUPPORTED_CHAINS.includes(Number(query.chainId) as ChainId)) if (isErrorPage) { return ( <StyledLayout layoutRoot> <Head> <Favicon /> </Head> {children} </StyledLayout> ) } return ( <> <Head> <Favicon /> </Head> <StyledLayout layoutRoot> <Suspense> <Alerts /> </Suspense> <MainGnb /> <StyledMain ref={mainRef} layout> {children} </StyledMain> </StyledLayout> <Modals /> <Suspense> {isEthereum(chainId) && ( <Suspense> <BalancerPool /> </Suspense> )} {isBsc(chainId) && <PancakeSwapPool />} </Suspense> </> ) } export default Layout
document.addEventListener("DOMContentLoaded", function () { const sendButton = document.getElementById("send-button"); const messageInput = document.getElementById("message-input"); const nameInput = document.getElementById("name-input"); const chatIdInput = document.getElementById("chat-id-input"); const startChatBtn = document.getElementById("start-chat-btn"); const logoBtn = document.getElementById("logo-btn"); const chatBox = document.getElementById("chat-box"); const nameInputContainer = document.getElementById("name-input-container"); const chatIdInputContainer = document.getElementById("chat-id-input-container"); logoBtn.style.display = "none"; chatBox.style.display = "none"; messageInput.style.display = "none"; sendButton.style.display = "none"; sendButton.addEventListener("click", handleSendButtonClick); messageInput.addEventListener("keypress", handleKeyPress); nameInput.addEventListener("keypress", handleKeyPress); chatIdInput.addEventListener("keypress", handleKeyPress); startChatBtn.addEventListener("click", startChat); function handleSendButtonClick() { sendMessage(messageInput.value.trim()); } let ws; function sendMessage(message) { if (ws.readyState === WebSocket.OPEN) { ws.send(JSON.stringify({ name: nameInput.value.trim(), chatId: chatIdInput.value.trim(), message: message })); messageInput.value = ""; } } function handleKeyPress(event) { if (event.key === "Enter") { if (event.target === messageInput) { sendMessage(messageInput.value.trim()); } else { startChat(); } } } async function startChat() { const name = nameInput.value.trim(); const chatId = chatIdInput.value.trim(); if (name !== "" && chatId !== "") { nameInputContainer.style.display = "none"; chatIdInputContainer.style.display = "none"; startChatBtn.style.display = "none"; logoBtn.style.display = "block"; chatBox.style.display = "block"; messageInput.style.display = "block"; sendButton.style.display = "block"; ws = new WebSocket(`ws://localhost:8880/chat/${chatId}`); // Change to your server address ws.onmessage = function (event) { const data = JSON.parse(event.data); const messageElement = document.createElement("div"); const nameElement = document.createElement("span"); const messageContent = document.createElement("span"); nameElement.textContent = `${data.name}: `; nameElement.style.fontWeight = "bold"; messageContent.textContent = data.message; messageElement.appendChild(nameElement); messageElement.appendChild(messageContent); chatBox.appendChild(messageElement); chatBox.scrollTop = chatBox.scrollHeight; } } else { alert("Please enter your name."); } } });
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* complex_literals.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: akharrou <akharrou@student.42.us.org> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2019/11/11 08:22:04 by akharrou #+# #+# */ /* Updated: 2019/11/11 08:22:18 by akharrou ### ########.fr */ /* */ /* ************************************************************************** */ /* ** (C) Example: ** Complex literals. */ #include <stdio.h> /* Standard Library of Input and Output */ #include <complex.h> /* Standard's Complex Header */ int main(void) { /* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */ ( 7.3if ); // complex literal of value: ( 0.0 + 7.3if ) ( 7.3i ); // complex literal of value: ( 0.0 + 7.3i ) ( 7.3il ); // complex literal of value: ( 0.0 + 7.3il ) ( 6.32f + 7.3if ); // literal of type: _Complex float ( 6.32 + 7.3i ); // literal of type: _Complex double ( 6.32L + 7.3il ); // literal of type: _Complex long double /* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */ printf("Real: %.2f ; Imag: %.2f\n", creal( 6.32f + 7.3if ) , cimag( 6.32f + 7.3if ) ); printf("Real: %.2f ; Imag: %.2f\n", creal( 6.32 + 7.3i ) , cimag( 6.32 + 7.3i ) ); printf("Real: %.2f ; Imag: %.2f\n", creal( 6.32L + 7.3il ) , cimag( 6.32L + 7.3il ) ); /* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */ return (0); } /* Output: Real: 6.32 ; Imag: 7.30 Real: 6.32 ; Imag: 7.30 Real: 6.32 ; Imag: 7.30 */ /* * Compiled with: clang -std=c11 -w * * Compiler: * Apple LLVM version 9.1.0 (clang-902.0.39.1) * Target: x86_64-apple-darwin17.4.0 * Thread model: posix * */
package co.flowers.usecases; import co.flowers.domain.collection.Flower; import co.flowers.domain.dto.FlowerDTO; import co.flowers.publisher.FlowerPublisher; import co.flowers.repository.IFlowerRepository; import com.fasterxml.jackson.core.JsonProcessingException; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.Mock; import org.mockito.Mockito; import org.mockito.junit.jupiter.MockitoExtension; import org.modelmapper.ModelMapper; import org.springframework.http.HttpStatus; import reactor.core.publisher.Mono; import reactor.test.StepVerifier; import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.never; import static org.mockito.Mockito.times; @ExtendWith(MockitoExtension.class) class ReturnFlowerUseCaseTest { @Mock IFlowerRepository repository; ModelMapper mapper; @Mock FlowerPublisher flowerPublisher; ReturnFlowerUseCase returnFlowerUseCase; @BeforeEach void setUp() { mapper = new ModelMapper(); returnFlowerUseCase = new ReturnFlowerUseCase(repository, mapper, flowerPublisher); } @Test @DisplayName("returnFlower_successfully") void returnFlower() { // flower Flower flower = new Flower("sunflower", "Asteraceae", "yellow", "sunflower", "Mexico"); flower.setId("1"); flower.setInStock(false); var monoFlower = Mono.just(flower); Mockito.when(repository.findById(any(String.class))).thenReturn(monoFlower); //flower updated Flower flowerUpdated = new Flower("sunflower", "Asteraceae", "yellow", "sunflower", "Mexico"); flowerUpdated.setId("1"); flowerUpdated.setInStock(true); Mockito.when(repository.save(any(Flower.class))).thenReturn(Mono.just(flowerUpdated)); var result = returnFlowerUseCase.returnFlower("1", "customerId"); StepVerifier.create(result) .expectNext(mapper.map(flowerUpdated, FlowerDTO.class)) .expectComplete() .verify(); Mockito.verify(repository, times(1)).findById("1"); Mockito.verify(repository, times(1)).save(flowerUpdated); try{ Mockito.verify(flowerPublisher, times(1)).publishReturn(any(FlowerDTO.class), any(String.class)); } catch (JsonProcessingException e){ System.out.println(e.getMessage()); } } @Test @DisplayName("returnFlower_Failed") void returnFlower_Failed(){ Flower flower = new Flower("sunflower", "Asteraceae", "yellow", "sunflower", "Mexico"); flower.setId("1"); Mockito.when(repository.findById(any(String.class))) .thenReturn(Mono.error(new Throwable(HttpStatus.BAD_REQUEST.toString()))); var result = returnFlowerUseCase.returnFlower("1", "customerId"); StepVerifier.create(result) .expectErrorMatches(throwable -> throwable != null && throwable.getMessage().equals(HttpStatus.BAD_REQUEST.toString())) .verify(); Mockito.verify(repository, times(1)).findById("1"); Mockito.verify(repository, never()).save(Mockito.any(Flower.class)); try{ Mockito.verify(flowerPublisher, never()).publishReturn(any(FlowerDTO.class), any(String.class)); } catch (JsonProcessingException e){ System.out.println(e.getMessage()); } } }
import React, { Component } from "react"; import PropTypes from "prop-types"; import { TouchableOpacity, Text, StyleSheet } from "react-native"; class MainHistoryButton extends Component { render() { const { text, onPress } = this.props; return ( <TouchableOpacity style={styles.buttonStyle} onPress={() => onPress()}> <Text style={styles.textStyle}>{text}</Text> </TouchableOpacity> ); } } MainHistoryButton.propTypes = { text: PropTypes.string.isRequired, onPress: PropTypes.func.isRequired }; const styles = StyleSheet.create({ textStyle: { fontSize: 24, color: "black", textAlign: "center", opacity: 1, fontFamily: "Chomsky" }, buttonStyle: { padding: 10, backgroundColor: "red", borderRadius: 25, width: "80%", alignSelf: "center", opacity: 0.6, marginTop: 10 } }); export default MainHistoryButton;
<div class="container"> <form [formGroup]="form"> <div class="row mb-2" formArrayName="searchFilters"> <div *ngFor="let param of searchFilters.controls; let i=index" class="col-md-12 form-input"> <div [formGroupName]="i"> <select formControlName="bool"> <option *ngFor="let b of bool" [value] = b> {{boolMap[b]}} </option> </select> <select #element formControlName="filter"> <option value='' selected>-- Select filter --</option> <option *ngFor="let filterKey of filterKeys.sort()" [value] = filterKey> {{filtersMap[filterKey]}} </option> </select> <ng-container [ngSwitch]="element.value"> <ng-container *ngSwitchCase="'population'"> <select formControlName="populationId"> <option *ngFor="let pos of (populations$ | async)" [value] = pos.populationId> {{pos.populationName}} </option>value </select> <button (click)="addFilter()" class="btn btn-info btn-sm">Add filter</button> <button (click)="removeFilter(i)" class="btn btn-info btn-sm" *ngIf="i > 0">Remove filter</button> </ng-container> <ng-container *ngSwitchCase="'tissue'"> <select formControlName="tissueId"> <option *ngFor="let pos of (tissues$ | async)" [value] = pos.tissueId> {{pos.tissueName}} </option> </select> <button (click)="addFilter()" class="btn btn-info btn-sm">Add filter</button> <button (click)="removeFilter(i)" class="btn btn-info btn-sm" *ngIf="i > 0">Remove filter</button> </ng-container> <ng-container *ngSwitchCase="'duplication'"> <select formControlName="duplicationId"> <option *ngFor="let pos of (duplications$ | async)" [value] = pos.duplicationId> {{pos.duplicationName}} </option> </select> <button (click)="addFilter()" class="btn btn-info btn-sm">Add filter</button> <button (click)="removeFilter(i)" class="btn btn-info btn-sm" *ngIf="i > 0">Remove filter</button> </ng-container> <ng-container *ngSwitchCase="'location'"> <select formControlName="locationId"> <option *ngFor="let pos of (locations$ | async)" [value] = pos.locationId> {{pos.locationName}} </option> </select> <button (click)="addFilter()" class="btn btn-info btn-sm">Add filter</button> <button (click)="removeFilter(i)" class="btn btn-info btn-sm" *ngIf="i > 0">Remove filter</button> </ng-container> <ng-container *ngSwitchCase="'shelfPosition'"> <select formControlName="shelfPositionId"> <option *ngFor="let pos of (shelfPositions$ | async)" [value] = pos.shelfPositionId> {{pos.shelfPositionName}} </option> </select> <button (click)="addFilter()" class="btn btn-info btn-sm">Add filter</button> <button (click)="removeFilter(i)" class="btn btn-info btn-sm" *ngIf="i > 0">Remove filter</button> </ng-container> <ng-container *ngSwitchCase="'containerType'"> <select formControlName="containerTypeId"> <option *ngFor="let pos of (containerType$ | async)" [value] = pos.containerTypeId> {{pos.containerTypeName}} </option> </select> <button (click)="addFilter()" class="btn btn-info btn-sm">Add filter</button> <button (click)="removeFilter(i)" class="btn btn-info btn-sm" *ngIf="i > 0">Remove filter</button> </ng-container> </ng-container> </div> </div> <button (click)="searchPlantSamples()" class="btn btn-info btn-sm action-button">Search</button> <button (click)="clearSearchResults()" class="btn btn-warning btn-sm action-button">Clear</button> </div> <button (click)="openFilterDialog()" class="btn btn-warning btn-sm">Filter columns</button> <div class="row mb-2" formArrayName="searchResults"> <input type="text" *ngIf="searchResults.controls.length > 0" placeholder="Range filter" style="margin-left: 15px;" #rangesToMark> <button class="btn btn-info btn-sm" *ngIf="searchResults.controls.length > 0" (click)="mark(rangesToMark.nativeElement.value)">Mark</button> <button class="btn btn-info btn-sm" *ngIf="searchResults.controls.length > 0" (click)="unmark()">Unmark</button> <button class="btn btn-warning btn-sm" *ngIf="searchResults.controls.length > 0" (click)="openAddPrepDialog()" [disabled]="getSelectedRows().length === 0">Add prep</button> <div *ngFor="let result of searchResults.controls; let i=index" class="col-md-12 form-input"> <div [formGroupName]="i"> <label [for]="'checkbox-' + i">{{i}}</label> <input [id]="'checkbox-' + i" type="checkbox" formControlName="edit" (change)="onEditChange(i)"> <input type="text" formControlName="sampleName" [hidden]="columnShowFilters.controls.showSampleName.value === false" (change)="onEdit('sampleName', sampleName.value)" #sampleName> <input type="date" formControlName="collectionDate" [hidden]="columnShowFilters.controls.showCollectionDate.value === false" (change)="onEdit('collectionDate', collectionDate.value)" #collectionDate> <select id="populationId" formControlName="populationId" [hidden]="columnShowFilters.controls.showPopulation.value === false" (change)="onEdit('populationId', populationId.value)" #populationId> <option *ngFor="let pos of (populations$ | async)" [value] = pos.populationId> {{pos.populationName}} </option> </select> <select id="tissueId" formControlName="tissueId" [hidden]="columnShowFilters.controls.showTissue.value === false" (change)="onEdit('tissueId', tissueId.value)" #tissueId> <option *ngFor="let pos of (tissues$ | async)" [value] = pos.tissueId> {{pos.tissueName}} </option> </select> <select id="duplicationId" formControlName="duplicationId" [hidden]="columnShowFilters.controls.showDuplication.value === false" (change)="onEdit('duplicationId', duplicationId.value)" #duplicationId> <option *ngFor="let pos of (duplications$ | async)" [value] = pos.duplicationId> {{pos.duplicationName}} </option> </select> <input type="text" placeholder="Sample weight" formControlName="sampleWeight" [hidden]="columnShowFilters.controls.showSampleWeight.value === false" (change)="onEdit('sampleWeight', sampleWeight.value)" #sampleWeight> <select id="locationId" formControlName="locationId" [hidden]="columnShowFilters.controls.showLocation.value === false" (change)="onEdit('locationId', locationId.value)" #locationId> <option *ngFor="let pos of (locations$ | async)" [value] = pos.locationId> {{pos.locationName}} </option> </select> <select id="shelfPositionId" formControlName="shelfPositionId" [hidden]="columnShowFilters.controls.showShelfPosition.value === false" (change)="onEdit('shelfPositionId', shelfPositionId.value)" #shelfPositionId> <option *ngFor="let pos of (shelfPositions$ | async)" [value] = pos.shelfPositionId> {{pos.shelfPositionName}} </option> </select> <select id="containerTypeId" formControlName="containerTypeId" [hidden]="columnShowFilters.controls.showContainerType.value === false" (change)="onEdit('containerTypeId', containerTypeId.value)" #containerTypeId> <option *ngFor="let pos of (containerType$ | async)" [value] = pos.containerTypeId> {{pos.containerTypeName}} </option> </select> <app-prep-label *ngFor="let prep of result.get('prepsLocation').value" [hidden]="columnShowFilters.controls.showPreps.value === false" [prepData]="prep" [matTooltip]="prepTooltipMessageFactory(prep)" matTooltipClass="prep-tooltip">{{prep}}</app-prep-label> </div> </div> <button *ngIf="searchResults.controls.length > 0" (click)="save()" class="btn btn-warning btn-sm action-button" [disabled]="editRowCounter === 0">Save</button> </div> <!--<div class="row mb-2"> <div class="col-md-12 form-input"> <input type="text" placeholder="Sample name ranges" [class.is-invalid]="form.controls.sampleNameRanges.invalid && (form.controls.sampleNameRanges.touched || submitted)" formControlName="sampleNameRanges"> </div> </div> <div class="col-md-12 form-input"> <label for="speciesId">Species: </label> <select id="speciesId" (change)="onSpeciesSelectionChange($event)"> <option value='' selected></option> <option *ngFor="let pos of (species$ | async)" [value] = pos.speciesId> {{pos.speciesName}} </option> </select> </div> <div class="col-md-12 form-input"> <label for="populationId">Population: </label> <select id="populationId" formControlName="populationId"> <option *ngFor="let pos of (populations$ | async)" [value] = pos.populationId> {{pos.populationName}} </option> </select> </div> <div class="col-md-12 form-input"> <label for="tissueId">Tissue: </label> <select id="tissueId" formControlName="tissueId"> <option *ngFor="let pos of (tissues$ | async)" [value] = pos.tissueId> {{pos.tissueName}} </option> </select> </div> <div class="row mb-2"> <div class="col-md-12 form-input"> <input type="text" placeholder="Sample weight" formControlName="sampleWeight"> </div> </div> <div class="col-md-12 form-input"> <label for="duplicationId">Duplication: </label> <select id="duplicationId" formControlName="duplicationId"> <option *ngFor="let pos of (duplications$ | async)" [value] = pos.duplicationId> {{pos.duplicationName}} </option> </select> </div> <div class="col-md-12 form-input"> <label for="locationId">Location: </label> <select id="locationId" formControlName="locationId"> <option *ngFor="let pos of (locations$ | async)" [value] = pos.locationId> {{pos.locationName}} </option> </select> </div> <div class="col-md-12 form-input"> <label for="shelfPositionId">Shelf position: </label> <select id="shelfPositionId" formControlName="shelfPositionId"> <option *ngFor="let pos of (shelfPositions$ | async)" [value] = pos.shelfPositionId> {{pos.shelfPositionName}} </option> </select> </div> <div class="col-md-12 form-input"> <label for="containerTypeId">Container type: </label> <select id="containerTypeId" formControlName="containerTypeId"> <option *ngFor="let pos of (containerType$ | async)" [value] = pos.containerTypeId> {{pos.containerTypeName}} </option> </select> </div> <div class="col-md-12 form-input"> <label for="collectionDate">Collection date: </label> <input type="date" id="collectionDate" formControlName="collectionDate"> </div> <div class="row mb-2"> <div class="col-md-12"> <button (click)="addPlantSamples()" class="btn btn-info">Generate samples set</button> </div> </div> <div class="row mb-2" formArrayName="plantSamples"> <div *ngIf="plantSamples.length > 0"> <div *ngFor="let plantSample of plantSamples.controls; let i=index" class="col-md-12 form-input"> <div [formGroupName]="i"> <input type="text" placeholder="Sample name ranges" [class.is-invalid]="plantSampleValid(i, 'sampleName')" formControlName="sampleName"> <input type="text" placeholder="Sample weight" formControlName="sampleWeight"> <select formControlName="locationId"> <option *ngFor="let pos of (locations$ | async)" [value] = pos.locationId> {{pos.locationName}} </option> </select> <select formControlName="shelfPositionId"> <option *ngFor="let pos of (shelfPositions$ | async)" [value] = pos.shelfPositionId> {{pos.shelfPositionName}} </option> </select> <select formControlName="containerTypeId"> <option *ngFor="let pos of (containerType$ | async)" [value] = pos.containerTypeId> {{pos.containerTypeName}} </option> </select> </div> </div> <button (click)="submit()" style="margin-left: 15px; margin-top: 10px;" [disabled]="submitButtonDisable" class="btn btn-info">Submit</button> </div> </div>--> </form> </div>
#include <iostream> class Complex { double real; double imaginary; public: Complex(double real = 0.0, double imaginary = 0.0) : real(real), imaginary(imaginary) {} friend std::ostream& operator<<(std::ostream& out, const Complex& c); friend std::istream& operator>>(std::istream& in, Complex& c); }; std::ostream& operator<<(std::ostream& out, const Complex& c) { out << c.real; if (c.imaginary >= 0) out << "+"; out << c.imaginary << "i"; return out; } std::istream& operator>>(std::istream& in, Complex& c) { std::cout << "Enter real part: "; in >> c.real; std::cout << "Enter imaginary part: "; in >> c.imaginary; return in; } int main() { Complex c1, c2; std::cout << "Enter complex number 1:" << std::endl; std::cin >> c1; std::cout << "Enter complex number 2:" << std::endl; std::cin >> c2; std::cout << "Complex number 1: " << c1 << std::endl; std::cout << "Complex number 2: " << c2 << std::endl; system("pause"); return 0; }
import React from "react"; import "./Login.css"; import Button from '@mui/material/Button'; import Logo from "./whatsapp-logo.jpg"; import { useStateValue } from "./StateProvider"; import { actionTypes } from "./Reducer"; import { auth } from "./firebase"; import { provider } from "./firebase"; import db from "./firebase"; function Login() { const [{}, dispatch] = useStateValue(); const signIn = () => { auth .signInWithPopup(provider) .then((result) => { dispatch({ type: actionTypes.SET_USER, user: result.user, }); console.log(result.user.email); var docRef = db.collection("users").doc(result.user.email); docRef .get() .then((doc) => { if (doc.exists) { } else { db.collection("users").doc(result.user.email).set({ name: result.user.displayName, email: result.user.email, photoURL: result.user?.photoURL, }); console.log("No such document!"); } }) .catch((error) => { console.log("Error getting document:", error); }); }) .catch((error) => alert(error.message)); }; return ( <div className="login"> <div className="login__container"> <img src={Logo} alt="" /> <div className="login__text"> <h1>Sign in to WhatsApp</h1> </div> <Button type= "submit" onClick={signIn}>Sign In With Google</Button> </div> </div> ); } export default Login;
//#7.4. Factoria d'objectes //Afegeix els setters setFruit i setSpecies a l'objecte tree. function plantTree(species, fruit) { if (typeof species !== 'string' || typeof fruit !== 'string') { return('Els arguments han de ser cadenes de text.'); } //Aquestes variables no són accessibles des de fora de la funció let _species = species; // Propietat privada per emmagatzemar especie let _fruit = fruit; return { // Propietat privada per emmagatzemar fruit set species(species) { _species = species; }, set fruit(fruit) { _fruit = fruit; }, get species() { return _species; }, get fruit() { return _fruit; } } }; module.exports = { plantTree };
package dynakube import ( "context" "errors" "testing" "github.com/Dynatrace/dynatrace-operator/pkg/api/scheme/fake" dynatracev1beta1 "github.com/Dynatrace/dynatrace-operator/pkg/api/v1beta1/dynakube" dtclient "github.com/Dynatrace/dynatrace-operator/pkg/clients/dynatrace" "github.com/Dynatrace/dynatrace-operator/pkg/controllers/dynakube/apimonitoring" controllermock "github.com/Dynatrace/dynatrace-operator/test/mocks/pkg/controllers" "github.com/stretchr/testify/mock" "github.com/stretchr/testify/require" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" ) func TestReconcileActiveGate(t *testing.T) { ctx := context.Background() dynakubeBase := &dynatracev1beta1.DynaKube{ ObjectMeta: metav1.ObjectMeta{ Name: "this-is-a-name", Namespace: "dynatrace", }, Spec: dynatracev1beta1.DynaKubeSpec{ ActiveGate: dynatracev1beta1.ActiveGateSpec{Capabilities: []dynatracev1beta1.CapabilityDisplayName{dynatracev1beta1.KubeMonCapability.DisplayName}}, }, } t.Run("no active-gate configured => nothing happens (only call active-gate reconciler)", func(t *testing.T) { dynakube := dynakubeBase.DeepCopy() dynakube.Spec.ActiveGate = dynatracev1beta1.ActiveGateSpec{} fakeClient := fake.NewClientWithIndex(dynakube) mockActiveGateReconciler := controllermock.NewReconciler(t) mockActiveGateReconciler.On("Reconcile", mock.Anything, mock.Anything).Return(nil) controller := &Controller{ client: fakeClient, apiReader: fakeClient, activeGateReconcilerBuilder: createActivegateReconcilerBuilder(mockActiveGateReconciler), } err := controller.reconcileActiveGate(ctx, dynakube, nil, nil) require.NoError(t, err) }) t.Run("no active-gate configured => active-gate reconcile returns error => returns error", func(t *testing.T) { dynakube := dynakubeBase.DeepCopy() dynakube.Spec.ActiveGate = dynatracev1beta1.ActiveGateSpec{} fakeClient := fake.NewClientWithIndex(dynakube) mockActiveGateReconciler := controllermock.NewReconciler(t) mockActiveGateReconciler.On("Reconcile", mock.Anything, mock.Anything).Return(errors.New("BOOM")) controller := &Controller{ client: fakeClient, apiReader: fakeClient, activeGateReconcilerBuilder: createActivegateReconcilerBuilder(mockActiveGateReconciler), } err := controller.reconcileActiveGate(ctx, dynakube, nil, nil) require.Error(t, err) require.Equal(t, "failed to reconcile ActiveGate: BOOM", err.Error()) }) t.Run(`reconcile automatic kubernetes api monitoring`, func(t *testing.T) { instance := &dynatracev1beta1.DynaKube{ ObjectMeta: metav1.ObjectMeta{ Name: testName, Namespace: testNamespace, Annotations: map[string]string{ dynatracev1beta1.AnnotationFeatureAutomaticK8sApiMonitoring: "true", }, }, Spec: dynatracev1beta1.DynaKubeSpec{ APIURL: testApiUrl, ActiveGate: dynatracev1beta1.ActiveGateSpec{ Capabilities: []dynatracev1beta1.CapabilityDisplayName{ dynatracev1beta1.KubeMonCapability.DisplayName, }, }, }, Status: dynatracev1beta1.DynaKubeStatus{ KubeSystemUUID: testUID, }, } fakeClient := fake.NewClientWithIndex(instance) mockClient := createDTMockClient(t, dtclient.TokenScopes{}, dtclient.TokenScopes{}) mockActiveGateReconciler := controllermock.NewReconciler(t) mockActiveGateReconciler.On("Reconcile", mock.Anything, mock.Anything).Return(nil) controller := &Controller{ client: fakeClient, apiReader: fakeClient, activeGateReconcilerBuilder: createActivegateReconcilerBuilder(mockActiveGateReconciler), apiMonitoringReconcilerBuilder: apimonitoring.NewReconciler, // TODO: actually mock it } err := controller.reconcileActiveGate(ctx, instance, mockClient, nil) require.NoError(t, err) mockClient.AssertCalled(t, "CreateOrUpdateKubernetesSetting", mock.AnythingOfType("context.backgroundCtx"), testName, testUID, mock.AnythingOfType("string")) require.NoError(t, err) }) t.Run(`reconcile automatic kubernetes api monitoring with custom cluster name`, func(t *testing.T) { const clusterLabel = "..blabla..;.🙃" instance := &dynatracev1beta1.DynaKube{ ObjectMeta: metav1.ObjectMeta{ Name: testName, Namespace: testNamespace, Annotations: map[string]string{ dynatracev1beta1.AnnotationFeatureAutomaticK8sApiMonitoring: "true", dynatracev1beta1.AnnotationFeatureAutomaticK8sApiMonitoringClusterName: clusterLabel, }, }, Spec: dynatracev1beta1.DynaKubeSpec{ APIURL: testApiUrl, ActiveGate: dynatracev1beta1.ActiveGateSpec{ Capabilities: []dynatracev1beta1.CapabilityDisplayName{ dynatracev1beta1.KubeMonCapability.DisplayName, }, }, }, Status: dynatracev1beta1.DynaKubeStatus{ KubeSystemUUID: testUID, }, } fakeClient := fake.NewClientWithIndex(instance) mockClient := createDTMockClient(t, dtclient.TokenScopes{}, dtclient.TokenScopes{}) mockClient.On("CreateOrUpdateKubernetesSetting", mock.AnythingOfType("context.backgroundCtx"), mock.AnythingOfType("string"), mock.AnythingOfType("string"), mock.AnythingOfType("string")).Return(testUID, nil) mockActiveGateReconciler := controllermock.NewReconciler(t) mockActiveGateReconciler.On("Reconcile", mock.Anything, mock.Anything).Return(nil) controller := &Controller{ client: fakeClient, apiReader: fakeClient, activeGateReconcilerBuilder: createActivegateReconcilerBuilder(mockActiveGateReconciler), apiMonitoringReconcilerBuilder: apimonitoring.NewReconciler, // TODO: actually mock it } err := controller.reconcileActiveGate(ctx, instance, mockClient, nil) require.NoError(t, err) mockClient.AssertCalled(t, "CreateOrUpdateKubernetesSetting", mock.AnythingOfType("context.backgroundCtx"), clusterLabel, testUID, mock.AnythingOfType("string")) require.NoError(t, err) }) }
package Alchole_free.Cockpybara.controller.cocktailrecipe.recipe_detail; import Alchole_free.Cockpybara.controller.cocktailrecipe.recipe_detail.ingredient.IngredientDTO; import Alchole_free.Cockpybara.domain.cocktail_recipe.AlcoholicType; import Alchole_free.Cockpybara.domain.cocktail_recipe.Category; import Alchole_free.Cockpybara.domain.cocktail_recipe.CocktailRecipe; import Alchole_free.Cockpybara.domain.cocktail_recipe.Glass; import Alchole_free.Cockpybara.domain.cocktail_recipe.taste.RecipeTaste; import Alchole_free.Cockpybara.domain.cocktail_recipe.taste.Taste; import Alchole_free.Cockpybara.domain.ingredient.Unit; import lombok.Builder; import lombok.Getter; import java.time.LocalDateTime; import java.util.List; import java.util.stream.Collectors; @Getter @Builder public class CocktailRecipeDetailDTO { private Long id; private String name; private AlcoholicType alcoholicType; private Category category; private String drinkImgPath; private Glass glass; private String instruction; private Boolean isMemberRecipe; private LocalDateTime createdAt; private List<Taste> tastes; private List<IngredientDTO> ingredients; public static CocktailRecipeDetailDTO from(CocktailRecipe cocktailRecipe) { List<Taste> tastes = cocktailRecipe.getTastes() .stream().map(RecipeTaste::getTaste) .collect(Collectors.toList()); List<IngredientDTO> ingredients = cocktailRecipe.getIngredients() .stream().map(recipeIngredient -> { String name = recipeIngredient.getIngredient().getName(); Double quantity = recipeIngredient.getQuantity(); Unit unit = recipeIngredient.getUnit(); return new IngredientDTO(name, quantity, unit); }).collect(Collectors.toList()); return CocktailRecipeDetailDTO.builder() .id(cocktailRecipe.getId()) .name(cocktailRecipe.getName()) .alcoholicType(cocktailRecipe.getAlcoholicType()) .category(cocktailRecipe.getCategory()) .drinkImgPath(cocktailRecipe.getDrinkImgPath()) .glass(cocktailRecipe.getGlass()) .instruction(cocktailRecipe.getInstruction()) .isMemberRecipe(cocktailRecipe.getIsMemberRecipe()) .createdAt(cocktailRecipe.getCreatedAt()) .tastes(tastes) .ingredients(ingredients) .build(); } }
# # Pedro Díaz | 23-05-2023 # Test unitarios para controlador BTCars # import os TEST_INIT_VALUE= os.getenv('TEST_INIT_VALUE') TEST_END_VALUE= os.getenv('TEST_END_VALUE') TEST_TIMESTAMP= os.getenv('TEST_TIMESTAMP') TEST_PAGE_VALUE= os.getenv('TEST_PAGE_VALUE') # # Pruebas unitarias para la obtención de precio bitcoin # # resultado exitoso: 200 def test_btcars_GET_BTCars_success(app, client): response = client.get(f'/btcars/{TEST_TIMESTAMP}') assert response.status_code == 200 json_data = response.get_json() assert json_data['message'] == 'Documento encontrado en MongoDB' assert 'element' in json_data # no se encuentra documento: 404 def test_btcars_GET_BTCars_not_found(app, client): response = client.get('/btcars/1234567890') assert response.status_code == 404 json_data = response.get_json() assert json_data['message'] == 'Documento no encontrado en MongoDB' assert json_data['element'] == {} # timestamp inválido: 404 def test_btcars_GET_BTCars_invalid_timestamp(app, client): response = client.get('/btcars/invalid') assert response.status_code == 404 # # Pruebas unitarias para el cálculo de promedio # # cálculo de promedio exitoso: 200 def test_btcars_promedio_success(app, client): response = client.get(f'/btcars/promedio?init={TEST_INIT_VALUE}&end={TEST_END_VALUE}') assert response.status_code == 200 json_data = response.get_json() assert json_data['message'] == 'Promedio obtenido exitosamente.' assert 'prom' in json_data # No se encuentran documentos: 404 def test_btcars_promedio_no_docs(app, client): response = client.get('/btcars/promedio?init=1116519438&end=1126522306') assert response.status_code == 404 json_data = response.get_json() assert json_data['message'] == 'No existen documentos para el rango solicitado.' assert json_data['prom'] is None # rango inválido de cálculo de promedio: 400 def test_btcars_promedio_invalid_range(app, client): response = client.get(f'/btcars/promedio?init={TEST_END_VALUE}&end={TEST_INIT_VALUE}') assert response.status_code == 400 json_data = response.get_json() assert json_data['message'] == 'Búsqueda mal formada. end debe ser mayor que init.' assert json_data['prom'] is None # inexistencia de parmámetros: 400 def test_btcars_promedio_missing_params(app, client): response = client.get('/btcars/promedio') assert response.status_code == 400 json_data = response.get_json() assert json_data['message'] == 'Consulta mal formada. Se requieren parametros init Y end' assert json_data['prom'] is None # # Pruebas unitarias para función de paginación # # éxito en paginación con filtro: 200 def test_btcars_pagination_with_timestamps_success(app, client): response = client.get(f'/btcars?page={TEST_PAGE_VALUE}&init={TEST_INIT_VALUE}&end={TEST_END_VALUE}') assert response.status_code == 200 json_data = response.get_json() assert json_data['message'] == 'Documentos obtenidos con filtro de timestamp.' assert 'elements' in json_data # éxito de paginación sin filtro: 200 def test_btcars_pagination_without_timestamps_success(app, client): response = client.get(f'/btcars?page={TEST_PAGE_VALUE}') assert response.status_code == 200 json_data = response.get_json() assert json_data['message'] == 'Documentos obtenidos sin filtro de timestamp.' assert 'elements' in json_data # rango inválido de paginación con filtro: 400 def test_btcars_pagination_invalid_page(app, client): response = client.get('/btcars?page=-1&init=1716519438&end=1716522306') assert response.status_code == 400 json_data = response.get_json() assert json_data['message'] == 'La página no puede ser menor que 1' assert json_data['elements'] is None
import java.io.FileReader; import java.io.IOException; import java.util.Arrays; import java.util.HashSet; import java.util.Scanner; import java.util.Set; public class Parser { Scanner scanner; Command command; Set<String> arithmeticCommands; Set<String> segments; public Parser(String path) throws IOException { this.scanner = new Scanner(new FileReader(path)); arithmeticCommands = new HashSet<>(Arrays. asList("add", "sub", "neg", "eq", "gt", "lt", "and", "or", "not")); segments = new HashSet<>(Arrays. asList("argument", "local", "static", "constant", "this", "that", "pointer", "temp")); } public boolean hasMoreCommands() throws IOException { return scanner.hasNextLine(); } public void advance() throws IOException, VMSyntaxException { if (hasMoreCommands()) { String line = scanner.nextLine(); line = line.replaceAll("//.*", "").trim(); if (line.isBlank()) { advance(); } else { command = parseLine(line); } } } public CommandType commandType() { return command.type; } // Method to close the reader when done public void close() throws IOException { scanner.close(); } private Command parseLine(String line) throws VMSyntaxException { return generateCommand(line); } private Command generateCommand(String line) throws VMSyntaxException { if (isArithmetic(line)) { return new Command(line, CommandType.C_ARITHMETIC, "", 0); } String[] parts = line.split(" "); if (parts.length != 3 || !isPopPush(parts[0]) || !isSegments(parts[1]) || !isInteger(parts[2])) { throw new VMSyntaxException("Assembler.Command " + line + " is illegal"); } if ("push".equals(parts[0])) { return new Command(line, CommandType.C_PUSH, parts[1], Integer.parseInt(parts[2])); } else if ("pop".equals(parts[0])) { return new Command(line, CommandType.C_POP, parts[1], Integer.parseInt(parts[2])); } else { throw new VMSyntaxException(""); } } public String arg1() { return command.arg1; } public int arg2() { return command.arg2; } private boolean isArithmetic(String line) { return arithmeticCommands.contains(line); } private boolean isSegments(String segment) { return segments.contains(segment); } private boolean isInteger(String index) { try { Integer.parseInt(index); return true; } catch (NumberFormatException e) { return false; } } private boolean isPopPush(String s) { return "push".equals(s) || "pop".equals(s); } }
<?php use App\Enums\ApprovalStatus; use App\Models\User; use Illuminate\Database\Migrations\Migration; use Illuminate\Database\Schema\Blueprint; use Illuminate\Support\Facades\Schema; return new class extends Migration { /** * Run the migrations. */ public function up(): void { Schema::create('advanced_leave_requests', function (Blueprint $table) { $table->id(); $table->foreignIdFor(User::class); // $table->foreignId('timeoff_period_regulation_id')->constrained(); // $table->string('month', 2); $table->text('data')->nullable(); // isinya array dari timeoff regulation month new dan old $table->unsignedFloat('amount')->default(0); $table->string('approval_status')->default(ApprovalStatus::PENDING); $table->foreignId('approved_by')->nullable(); $table->timestamp('approved_at')->nullable(); $table->timestamps(); }); } /** * Reverse the migrations. */ public function down(): void { Schema::dropIfExists('advanced_leave_requests'); } };
import os import h5py import torch import torch.nn as nn import torch.nn.functional as F import torch.optim as optim from torch.utils.data import Dataset, DataLoader, random_split import numpy as np import pandas as pd import matplotlib.pyplot as plt from pathlib import Path import gc from torch.utils.tensorboard import SummaryWriter import tqdm as tqdm from sklearn import metrics from sklearn.manifold import TSNE import ray from ray.tune.schedulers import ASHAScheduler from functools import partial import data_setup, utils, tuning #model_interpreter.run = False """ This script is for all the main running parts: training, incl. contrastive loss function and early stopping create_writer, for saving the training details for comparison testing, incl. saving output embeddings and predictions """ "########################################## TRAINING ###########################################" ##### ------------- Step 3: Define training function ------------ # Define the Contrastive Loss Function class ContrastiveLoss(nn.Module): """ Contrastive loss function used to push similar images to a lower distance D and dissimilar images to a higher distance. Inputs: prediction: cosine_similarity of the two input images, i.e. the distance between the embedded outputs (final fully-connected layer) truth: cosine_similarity of the metadata of the two input images, i.e. the true value of similarity. Transformed in this function to the target value from [0,1] where truth=1 -> target=1, truth=-1 -> target=0 data_setup.distance_function: if == "cosine": Transforms prediction to a distance value from [-1,1]->[0,1] with distance = 0.5 * (1 - prediction), such that prediction=1 -> distance=0 and prediction=(-1) -> distance=1 & Transforms truth to a target value from [-1,1]->[0,1] with target = 0.5 * (truth + 1), such that prediction=1 -> distance=0 and prediction=(-1) -> distance=1 Drives similar images (truth~1, target~1) towards a smaller distance (higher predictions) and dissimilar images (truth~-1, target~0) towards a larger distance (lower predictions), but maximum distance=1 (pred=-1) NOTE: The outputs are unused here since it just uses the predictions from the model and the target true value. """ def __init__(self, margin: float): super(ContrastiveLoss, self).__init__() self.margin = margin def forward(self, output1, output2, prediction, truth): if data_setup.distance_function == "cosine": distance = 0.5 * (1 - prediction) # pred=1 -> dist=0, pred=-1 -> dist=1 target = 0.5 * (truth + 1) # truth=1 -> target=1, truth=-1 -> target=0 first_part = 0.5 * (target) * torch.pow(distance, 2) second_part = 0.5 * (1 - target) * torch.pow(torch.clamp(self.margin - distance, min=0.0), 2) loss_contrastive = first_part + second_part if data_setup.distance_function == "euclid": distance = prediction loss_contrastive = torch.mean((1 - target) * torch.pow(distance, 2) + (target) * torch.pow(torch.clamp(self.margin - distance, min=0.0), 2)) return loss_contrastive, first_part, second_part class EarlyStopping: def __init__(self, patience: int, min_delta: float): self.patience = patience self.min_delta = min_delta self.counter = 0 self.best_loss = float('inf') self.early_stop = False def __call__(self, val_loss): if val_loss < self.best_loss - self.min_delta: self.best_loss = val_loss self.counter = 0 else: self.counter += 1 if self.counter >= self.patience: self.early_stop = True if val_loss < 0: self.early_stop = True def training(model: nn.Module, train_dataloader: DataLoader, validation_dataloader: DataLoader, output_dir: str, model_name: str, loss_fn: nn.Module, optimizer: optim.Optimizer, num_epochs: int, device: torch.device, writer: SummaryWriter, patience: int, min_delta: float): print("[INFO] Training started") model_eval_metric = "val_loss" early_stopping = EarlyStopping(patience=patience, min_delta=min_delta) scaler = torch.cuda.amp.GradScaler() # https://pytorch.org/docs/stable/amp.html#gradient-scaling scheduler = torch.optim.lr_scheduler.ReduceLROnPlateau(optimizer, factor=0.1, patience=5, verbose=True ) # ------TRAINING------ training_losses = [] first_train_losses = [] second_train_losses = [] train_mses = [] validation_losses = [] first_val_losses = [] second_val_losses = [] val_mses = [] epochs = [] best_validation_loss = 1e9 try: model_parameter_df = pd.DataFrame(columns=[name for name, _ in model.named_parameters() if _.grad is not None]) except Exception as e: print("There was an error initializing the gradient dataframe. Returning None.") model_parameter_df = None print("Error:", e) for epoch in range(num_epochs): model.train() training_loss_output = [] train_first_output = [] train_second_output = [] train_truths = [] train_predictions = [] for i, batch in enumerate(train_dataloader): #print("bshape", batch) img1, img2 = batch[0], batch[1] # OBS: Model takes as input image sets when working with batches img1 = img1.to(device).float() img2 = img2.to(device).float() if batch[2].dtype != torch.float: sim_score = batch[2].to(device, dtype=torch.float) else: sim_score = batch[2].to(device).float() if np.isnan(sim_score.detach().cpu().numpy()).any(): print("sim score index with nan", i) optimizer.zero_grad() # zero the gradients so they dont accumulate over epochs with torch.autocast(device_type="cuda", dtype=torch.float16): # run in mixed precision to improve perfomance while maintaining accuracy # See more: https://pytorch.org/docs/stable/amp.html#autocasting # Forward pass output1, output2, prediction = model(img1, img2) if np.isnan(prediction.detach().cpu().numpy()).any(): print("There was a NaN value in the batch predictions at index", i) print(prediction) print("Setting NaN-value to zero") prediction = torch.nan_to_num(prediction, nan=0.1) print(prediction) assert output1.dtype is torch.float16 assert output2.dtype is torch.float16 # Calculate loss training_loss, train_first, train_second = loss_fn(output1, output2, prediction, sim_score) assert training_loss.dtype is torch.float32 assert train_first.dtype is torch.float32 assert train_second.dtype is torch.float32 output1.detach() # No need to calculate gradients of these items output2.detach() train_first.detach() train_second.detach() #torch.cuda.empty_cache() # empty after each batch? # Perform backpropagation scaler.scale(torch.mean(training_loss)).backward(retain_graph=True) # Take a gradient descent step by the optimizer and update scaler scaler.step(optimizer) scaler.update() # Save values training_loss_output.append(torch.mean(training_loss).item()) train_first_output.append(torch.mean(train_first).item()) train_second_output.append(torch.mean(train_second).item()) train_truths.append(sim_score.detach().cpu().numpy()) train_predictions.append(prediction.detach().cpu().numpy()) training_loss = np.mean(training_loss_output) # Getting the mean loss for the batch first_training_loss = np.mean(train_first_output) second_training_loss = np.mean(train_second_output) try: train_mse = metrics.mean_squared_error(np.concatenate(train_truths), np.concatenate(train_predictions)) train_mses.append(train_mse) except Exception as e: print(f"There was an error in MSE calculation: {e}") train_mses.append(1.0) scheduler.step(training_loss) # Updates learning rate training_losses.append(training_loss) first_train_losses.append(first_training_loss) second_train_losses.append(second_training_loss) if writer: # Add results to SummaryWriter writer.add_scalar(tag="Training loss", scalar_value=training_loss, global_step=epoch ) writer.add_graph(model=model, input_to_model = (img1, img2) ) writer.close() #torch.cuda.empty_cache() # empty before evaluation? #gc.collect() model.eval() # Set the model to evaluation mode validation_loss_output = [] val_first_output = [] val_second_output = [] val_truths = [] val_predictions = [] for batch in validation_dataloader: val_img1, val_img2 = batch[0], batch[1] val_img1 = val_img1.to(device).float() val_img2 = val_img2.to(device).float() val_sim_score = batch[2].to(device).float() optimizer.zero_grad() with torch.autocast(device_type="cuda", dtype=torch.float16): val_output1, val_output2, val_prediction = model(val_img1, val_img2) assert val_output1.dtype is torch.float16 assert val_output2.dtype is torch.float16 validation_loss, val_first, val_second = loss_fn(val_output1, val_output2, val_prediction, val_sim_score) assert validation_loss.dtype is torch.float32 val_output1.detach() val_output2.detach() val_first.detach() val_second.detach() validation_loss_output.append(torch.mean(validation_loss).item()) val_first_output.append(torch.mean(val_first).item()) val_second_output.append(torch.mean(val_second).item()) val_truths.append(val_sim_score.detach().cpu().numpy()) val_predictions.append(val_prediction.detach().cpu().numpy()) validation_loss = np.mean(validation_loss_output) first_val_loss = np.mean(val_first_output) second_val_loss = np.mean(val_second_output) try: val_mse = metrics.mean_squared_error(np.concatenate(val_truths), np.concatenate(val_predictions)) val_mses.append(val_mse) except Exception as e: print(f"There was an error in validation MSE calculation: {e}") print("Val truths:", np.concatenate(val_truths)) print("NaN at index:", np.where(np.isnan(val_truths))) print("Val predictions", np.concatenate(val_predictions)) print("NaN at index:", np.where(np.isnan(val_predictions))) val_mses.append(1.0) validation_losses.append(validation_loss) first_val_losses.append(first_val_loss) second_val_losses.append(second_val_loss) # Save improved model, if metric has improved if model_eval_metric == "val_loss": if validation_loss < best_validation_loss: best_validation_loss = validation_loss utils.save_model(model, output_dir, model_name, structure_df=None) epochs.append(epoch+1) print(f'Epoch:{epoch+1}, Training Loss: {training_loss:.6f}, Validation Loss: {validation_loss:.6f}') epoch_gradients = {} for name, param in model.named_parameters(): if param.grad is not None: epoch_gradients[name] = param.grad.norm().item() try: model_parameter_df = pd.concat([model_parameter_df, pd.DataFrame(epoch_gradients, index=[0])], ignore_index=True) except: print("There was an error in concatenating the gradient dataframe. Returning None") model_parameter_df = None print("Error:", e) h5_filename = os.path.join(output_dir, model_name, "training_stats.h5") os.makedirs(os.path.dirname(h5_filename), exist_ok=True) with h5py.File(h5_filename, "w") as hf: batch_id = "all_batches" train_val_params = {"epoch": epochs, "training_loss": training_losses, "first_train_loss": first_train_losses, "second_train_loss": second_train_losses, "train_mse": train_mses, "validation_loss": validation_losses, "first_val_loss": first_val_losses, "second_val_loss": second_val_losses, "validation_mse": val_mses, } utils.save_batch_data_hdf5(hf, train_val_params, batch_id) if writer: writer.add_scalar(tag="Validation Loss", scalar_value=np.mean(validation_loss_output), global_step=epoch) early_stopping(validation_loss) if writer: writer.close() if early_stopping.early_stop: print("Early stopping triggered. Training stopped.") break # Calculate memory usage after each epoch current_memory = torch.cuda.memory_allocated(0) print(f"Total memory usage {current_memory / (1024**2):.2f} MB") torch.cuda.empty_cache() #gc.collect() print("[INFO] Training done") return model_parameter_df def pre_tuning(config, num_samples, max_num_epochs, gpus_per_trial, cpus, dataloader_dir, output_dir, model_name): checkpoint_dir = "/lustre/astro/antonmol/learning_stuff/siamese_networks/checkpoints" scheduler = ASHAScheduler( metric="val_mse", mode="min", max_t=max_num_epochs, grace_period=1, reduction_factor=2, ) print("RUNNING") result = ray.tune.run( partial(tuning.train_func, data_dir=dataloader_dir), resources_per_trial={"cpu": cpus, "gpu": gpus_per_trial}, config=config, num_samples=num_samples, scheduler=scheduler, local_dir=checkpoint_dir, ) print("RUNNING2") top_trials = result.trials top_trials.sort(key=lambda trial: trial.last_result.get("val_mse", float("inf"))) n_saves = len(top_trials) # Print the configurations and validation losses of the top three trials for i, trial in enumerate(top_trials[:n_saves]): print(f"Top {i + 1} trial config: {trial.config}") print(f"Top {i + 1} trial final validation loss: {trial.last_result['val_loss']}") print(f"Top {i + 1} trial final mean squared error: {trial.last_result['val_mse']}") print("\n") # Save the output to a text file file_path = os.path.join(output_dir, model_name) if not os.path.exists(file_path): os.makedirs(file_path) # Saving as csv file with pandas params = [trial.config for trial in top_trials[:n_saves]] df = pd.DataFrame(params) df['Validation Loss'] = [trial.last_result['val_loss'] for trial in top_trials[:n_saves]] df['Mean squared error'] = [trial.last_result['val_mse'] for trial in top_trials[:n_saves]] csv_file = os.path.join(file_path, f"tuning_nsamp{num_samples}.csv") df.to_csv(csv_file, sep="\t", index=False) return top_trials def create_writer(experiment_name: str, model_name: str, timestamp: str, extra: str=None) -> torch.utils.tensorboard.writer.SummaryWriter(): """ Creates a torch.utils.tensorboard.writer.SummaryWriter() instance saving to a specific log_dir. Args: experiment_name (str): Name of experiment. model_name (str): Name of model. extra (str, optional): Anything extra to add to the directory. Defaults to None. Returns: torch.utils.tensorboard.writer.SummaryWriter(): Instance of a writer saving to log_dir. Example usage: # Create a writer saving to "runs/2022-06-04/data_10_percent/effnetb2/5_epochs/" writer = create_writer(experiment_name="data_10_percent", model_name="effnetb2", extra="5_epochs") """ from datetime import datetime import os # Get timestamp of current date (all experiments on certain day live in same folder) if extra: # Create log directory path log_dir = os.path.join("runs", timestamp, experiment_name, model_name, extra) else: log_dir = os.path.join("runs", timestamp, experiment_name, model_name) print(f"[INFO] Created SummaryWriter, saving to: {log_dir}...") return SummaryWriter(log_dir=log_dir) "########################################## TESTING ###########################################" ##### --------------- Visualisations ------------------- def visualize_embeddings(h5_filename, output_dir, model_name): out1, out2 = utils.get_batch_data_hdf5(h5_filename, ["out1", "out2"]) tsne = TSNE(n_components=2, random_state=42) embed = np.vstack((out1, out2)).T embeddings_2d = tsne.fit_transform(embed) save_dir = os.path.join(output_dir, model_name, "images") save_path = os.path.join(save_dir, "embedding.png") plt.figure(figsize=(10, 8)) plt.scatter(embeddings_2d[:, 0], embeddings_2d[:, 1]) #plt.colorbar() plt.title("t-SNE Visualization of Embeddings") plt.savefig(save_path) plt.close() print("Embeddings saved!") # ------------------- TEST -------------------- def testing(model: nn.Module, test_dataloader: DataLoader, device: torch.device, output_dir: str, model_name: str, ): print("\n[INFO] Model test started.") print("\nLoading trained model...") checkpoint = torch.load(f"{output_dir}/{model_name}/{model_name}.pth") model_state_dict = model.state_dict() model.eval() model.load_state_dict(checkpoint) print(f"Testing on {len(test_dataloader)} test batches...") # Create an HDF5 file to store images, truths, and predictions h5_filename = os.path.join(output_dir, model_name, "batch_data.h5") h5_images = os.path.join(output_dir, model_name, "batch_images.h5") os.makedirs(os.path.dirname(h5_filename), exist_ok=True) with h5py.File(h5_filename, "w") as hf: with h5py.File(h5_images, "w") as hf2: with torch.no_grad(): for batch_id, batch in enumerate(test_dataloader): img1_batch, img2_batch = batch[0], batch[1] out1_batch, out2_batch, predictions_batch = model(img1_batch.to(device).float(), img2_batch.to(device).float()) truths_batch = batch[2] metadata1 = batch[3] metadata2 = batch[4] metadata1_raw = batch[5] metadata2_raw = batch[6] test_params = { "out1": out1_batch, "out2": out2_batch, "truths": truths_batch, "predictions": predictions_batch, "metadata1": metadata1, "metadata2": metadata2, "metadata1_raw": metadata1_raw, "metadata2_raw": metadata2_raw, } input_images = { "img1": img1_batch, "img2": img2_batch, } utils.save_batch_data_hdf5(hf, test_params, batch_id) utils.save_batch_data_hdf5(hf2, input_images, batch_id) del test_params, input_images #torch.cuda.empty_cache() #gc.collect() print("[INFO] Test done.") # Calculate memory usage after each epoch current_memory = torch.cuda.memory_allocated(0) print(f"Total memory usage {current_memory / (1024**2):.2f} MB") torch.cuda.empty_cache() gc.collect() # Run functions mse = utils.calculate_mse_from_hdf5(h5_filename, ) print(f"Mean Squared Error: {mse}") utils.create_clustering_plot(h5_filename, output_dir, model_name, batch_id) acc_means, acc_sums = utils.plot_accuracy(h5_filename, output_dir, model_name, lower_limit=0.9, upper_limit=1.0, bins=10, plot=True) #visualize_embeddings(h5_filename, output_dir, model_name) return
/* * Copyright 2021 Steinar Bang * * 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 no.priv.bang.handlereg.services; import no.priv.bang.beans.immutable.Immutable; public class NyFavoritt extends Immutable { private String brukernavn; private Butikk butikk; private NyFavoritt() {} public String getBrukernavn() { return brukernavn; } public Butikk getButikk() { return butikk; } @Override public String toString() { return "NyFavoritt [brukernavn=" + brukernavn + ", butikk=" + butikk + "]"; } public static NyFavorittBuilder with() { return new NyFavorittBuilder(); } public static class NyFavorittBuilder { private String brukernavn; private Butikk butikk; private NyFavorittBuilder() {} public NyFavoritt build() { NyFavoritt favorittOgBrukernavn = new NyFavoritt(); favorittOgBrukernavn.brukernavn = this.brukernavn; favorittOgBrukernavn.butikk = this.butikk; return favorittOgBrukernavn; } public NyFavorittBuilder brukernavn(String brukernavn) { this.brukernavn = brukernavn; return this; } public NyFavorittBuilder butikk(Butikk favoritt) { this.butikk = favoritt; return this; } } }
import { LoadingButton } from "@mui/lab"; import { Box, TextField, Typography } from "@mui/material"; import React, { useState } from "react"; import { useAppDispatch } from "../../../redux/hooks"; import { settingsActions } from "../../../actions/settingActions"; import { EmailPortType } from "../../../utils/api/settingApi"; import { NotificationToast } from "../../../utils/handlers/NotificationToast"; const EmailForm = (emailSendPort: { email: string; password: string }) => { const [loading, setLoading] = useState(false); const dispatch = useAppDispatch(); const handleSubmit = async (e: React.FormEvent<HTMLFormElement>) => { e.preventDefault(); setLoading(true); const formData = new FormData(e.currentTarget); const data: EmailPortType = { email: formData.get("email") as string, password: formData.get("password") as string, }; await dispatch(settingsActions.emailPortAction(data)) .unwrap() .then(() => NotificationToast({ message: "Email created successfully", type: "success", }) ) .finally(() => { setLoading(false); }); }; return ( <Box onSubmit={handleSubmit} component={"form"} sx={{ display: "flex", flexDirection: "column", m: 5, gap: 2 }} > <Typography textAlign={"center"} fontSize={23} fontWeight={600}> Email to send port </Typography> <TextField name="email" label="Email" defaultValue={emailSendPort.email} /> <TextField name="password" label="Password" defaultValue={emailSendPort.password} /> <LoadingButton loading={loading} type="submit" fullWidth variant="contained" > Submit </LoadingButton> </Box> ); }; export default EmailForm;
/** * Created by zhouwanli on 13/05/2017. */ 'use strict'; const log = require('log4js').getLogger('Oauth2 Authenticate controller'); const webConf = require('../../webConf'); const userDao = require('../../dao/userDao'); const cache = require('../../domain/cache/lruCache')(); const authenticateTokenDao = require('../../dao/authenticateTokenDao'); const AuthUser = require('../../messages/user'); const weiboAuthService = require('../../services/weiboAuthService'); const qqAuthService = require('../../services/qqAuthService'); const githubAuthService = require('../../services/githubAuthService'); const facebookAuthService = require('../../services/facebookAuthService'); var deleteAuthCookie = function(cookies, cookieName){ cookies.set(cookieName, 'deleted', { path: '/', httpOnly: true, expires: new Date(0) }); }; var getNeedUpdateUserField = (user, oauth2AuthResponse) =>{ var needUpdate = {}; var hadUpdatedField = false; if(user.email !== oauth2AuthResponse.email){ needUpdate.email = oauth2AuthResponse.email; hadUpdatedField = true; } if(user.image !== oauth2AuthResponse.image){ needUpdate.image = oauth2AuthResponse.image; hadUpdatedField = true; } if(user.name !== oauth2AuthResponse.name){ needUpdate.name = oauth2AuthResponse.name; hadUpdatedField = true; } if(user.role !== oauth2AuthResponse.role){ needUpdate.role = oauth2AuthResponse.role; hadUpdatedField = true; } if(hadUpdatedField){ needUpdate.updatedAt = new Date(); return needUpdate; } return null; }; var oauth2AuthenticateFromWeibo = async (ctx, next) => { var authProvider = ctx.params.provider; var code = ctx.query.code; var fromUrl = ctx.cookies.get(webConf.cookie.LOGIN_FROM_URL); if(!authProvider){ ctx.response.redirect(fromUrl || '/'); return; } log.info(`Try to Authenticate from ${authProvider}, code: ${code}, fromUrl: ${fromUrl}`); try{ var oauth2AuthResponse; switch (authProvider){ case webConf.oauth2Provider.WEI_BO: oauth2AuthResponse = await weiboAuthService.oauth2Authenticate(code); break; case webConf.oauth2Provider.QQ: oauth2AuthResponse = await qqAuthService.oauth2Authenticate(code); break; case webConf.oauth2Provider.GITHUB: oauth2AuthResponse = await githubAuthService.oauth2Authenticate(code); break; case webConf.oauth2Provider.FACEBOOK: oauth2AuthResponse = await facebookAuthService.oauth2Authenticate(code); break; } if(!oauth2AuthResponse){ ctx.response.redirect(fromUrl || '/'); return; } var user = await userDao.findUserByEmail(oauth2AuthResponse.email); if(user == null){//如果第一次登录,那么要创建user, 否则更新user log.debug(`User: ${oauth2AuthResponse.email} First Login, Create it.`); user = await userDao.createUser(oauth2AuthResponse); }else{ var updateUserFields = getNeedUpdateUserField(user, oauth2AuthResponse); await userDao.updateUser(updateUserFields, user.id); //删除之前的token var delToken = await authenticateTokenDao.deleteAllAuthUserFromDbAndCache(user.id); log.debug(`Delete from authen_token table : count: ${delToken}, userId: ${user.id}`); } //保存最新的token var authUser = await authenticateTokenDao.createAuthUser(oauth2AuthResponse, user.id); var cacheUser = new AuthUser(user.id, user.name, user.email, authUser.localToken, user.role, user.image, authUser.expiresAt, authUser.oauth2AuthId, authUser.oauth2AuthToken, authUser.oauthProvider); log.info(`Save to cache: ${JSON.stringify(cacheUser)}`); cache.set(oauth2AuthResponse.localToken, cacheUser); ctx.cookies.set(webConf.cookie.AUTH_COOKIE_NAME, oauth2AuthResponse.localToken, { path: '/', httpOnly: true, expires: new Date(oauth2AuthResponse.expiresAt) }); ctx.request.authUser = authUser; ctx.response.redirect(fromUrl || '/'); deleteAuthCookie(ctx.cookies, webConf.cookie.LOGIN_FROM_URL); next(); }catch(e){ log.error(e); ctx.response.redirect(fromUrl || '/authenticate/login.html'); next(); } }; var logout = async (ctx, next)=>{ if(!ctx.request.authUser){ return ; } var authUser = ctx.request.authUser; cache.del(authUser.localToken); await authenticateTokenDao.deleteAllAuthUserFromDbAndCache(authUser.id); deleteAuthCookie(ctx.cookies, webConf.cookie.AUTH_COOKIE_NAME); deleteAuthCookie(ctx.cookies, webConf.cookie.LOGIN_FROM_URL); var forwardUrl = ctx.cookies.get(webConf.cookie.LOGIN_FROM_URL); ctx.response.redirect(forwardUrl || '/'); next(); }; var login = async (ctx, next) =>{ var forwardPage = ctx.query.forward || '/'; log.debug(`Login From Page : ${forwardPage}`); if(ctx.request.authUser){//如果已经登录,那么不允许在访问这个url ctx.response.redirect(forwardPage || '/'); return; } var expiredDate = new Date(); expiredDate.setTime(expiredDate.getTime() + webConf.cookie.TTL) ctx.cookies.set(webConf.cookie.LOGIN_FROM_URL, forwardPage, { path: '/', httpOnly: true, expires: expiredDate }); ctx.render('authenticate/login.html', { weiboClientId: process.env.weibo_clientId, weiboRedirectUri: process.env.weibo_redirectUri, githubClientId: process.env.github_clientId, githubRedirectUri: process.env.github_redirectUri, qqClientId: process.env.qq_clientId, qqRedirectUri: process.env.qq_redirectUri, facebookClientId: process.env.facebook_clientId, facebookRedirectUri: process.env.facebook_redirectUri }); next(); }; var profile = async (ctx, next) =>{ if(!ctx.request.authUser){ ctx.response.redirect('/site/authenticate/login'); next(); return; } ctx.render('authenticate/profile.html'); next(); }; module.exports = { 'GET /authenticate/callback/:provider' : oauth2AuthenticateFromWeibo, 'GET /authenticate/logout': logout, 'GET /authenticate/login': login, 'GET /authenticate/profile': profile }
/* * Copyright 2023 The original 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.rschwietzke.devoxxpl24; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Paths; import java.util.HashMap; import java.util.Map; import java.util.TreeMap; import org.rschwietzke.Benchmark; /** * Split costs a lot, try the most naive next best things first * * @author Rene Schwietzke */ public class BRC05_ReplaceSplitST extends Benchmark { /** * Holds our temperature data without the station, because the * map already knows that */ private static class Temperatures { private final double min; private final double max; private final double total; private final long count; public Temperatures(final double value) { this.min = value; this.max = value; this.total = value; this.count = 1; } private Temperatures(double min, double max, double total, long count) { this.min = min; this.max = max; this.total = total; this.count = count; } /** * Combine two temperatures * * @param other the other city temperature * @return a new combined state */ public Temperatures merge(final Temperatures other) { return new Temperatures(Math.min(min, other.min), Math.max(max, other.max), total + other.total, count + other.count); } /** * 1BRC wants to have one decimal digits * @param value the value to transform * @return the rounded value */ private double round(double value) { return Math.round(value * 10.0) / 10.0; } /** * Our final printing format */ public String toString() { return round(min) + "," + round(total / count) + "," + round(max); } } @Override public String run(final String fileName) throws IOException { // our cities with temperatures final Map<String, Temperatures> cities = new HashMap<>(); try (var reader = Files.newBufferedReader(Paths.get(fileName))) { String line; while ((line = reader.readLine()) != null) { // split the line final int pos = line.indexOf(';'); // get us the city final String city = line.substring(0, pos); final String temperatureAsString = line.substring(pos + 1); // parse our temperature final double temperature = Double.parseDouble(temperatureAsString); // merge the data into the captured data cities.merge(city, new Temperatures(temperature), (t1, t2) -> t1.merge(t2)); } } // ok, we got everything, now we need to order it and print it return new TreeMap<String, Temperatures>(cities).toString(); } public static void main(String[] args) throws NoSuchMethodException, SecurityException { Benchmark.run(BRC05_ReplaceSplitST.class, args); } }
package atelier.modelo.entidades; import java.util.Date; import java.util.List; import javax.persistence.CascadeType; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.FetchType; import javax.persistence.GeneratedValue; import javax.persistence.Id; import javax.persistence.JoinColumn; import javax.persistence.ManyToOne; import javax.persistence.OneToMany; import javax.persistence.OneToOne; import javax.persistence.Temporal; import javax.persistence.TemporalType; import org.hibernate.annotations.ColumnDefault; import org.hibernate.annotations.GenericGenerator; @Entity public class Recetario { @Id @GeneratedValue(generator = "increment") @GenericGenerator(name = "increment", strategy = "increment") private int id; @Temporal(TemporalType.TIMESTAMP) private Date fechaRegistro = new Date(); @ColumnDefault("true") @Column(nullable = false) private boolean estado = true; @ManyToOne @JoinColumn(nullable = true) private Funcionario funcionarioQueRegistra; @Column(nullable = false) private String observacion; @Temporal(TemporalType.DATE) @Column(nullable = false) private Date fechaReceta = new Date(); @OneToMany(mappedBy = "recetario", cascade = CascadeType.ALL, orphanRemoval = true, fetch = FetchType.LAZY) private List<RecetarioDetalle> detalle; @ManyToOne @JoinColumn(nullable = false) private Paciente paciente; @OneToOne(mappedBy = "receta", cascade = CascadeType.ALL, orphanRemoval = true, fetch = FetchType.LAZY) private Reposo reposo; public int getId() { return id; } public void setId(int id) { this.id = id; } public Date getFechaRegistro() { return fechaRegistro; } public void setFechaRegistro(Date fechaRegistro) { this.fechaRegistro = fechaRegistro; } public boolean isEstado() { return estado; } public void setEstado(boolean estado) { this.estado = estado; } public Funcionario getFuncionarioQueRegistra() { return funcionarioQueRegistra; } public void setFuncionarioQueRegistra(Funcionario funcionarioQueRegistra) { this.funcionarioQueRegistra = funcionarioQueRegistra; } public String getObservacion() { return observacion; } public void setObservacion(String observacion) { this.observacion = observacion; } public Date getFechaReceta() { return fechaReceta; } public void setFechaReceta(Date fechaReceta) { this.fechaReceta = fechaReceta; } public List<RecetarioDetalle> getDetalle() { return detalle; } public void setDetalle(List<RecetarioDetalle> detalle) { this.detalle = detalle; } public Paciente getPaciente() { return paciente; } public void setPaciente(Paciente paciente) { this.paciente = paciente; } public Reposo getReposo() { return reposo; } public void setReposo(Reposo reposo) { this.reposo = reposo; } @Override public String toString() { return "Recetario [id=" + id + ", fechaRegistro=" + fechaRegistro + ", estado=" + estado + ", funcionarioQueRegistra=" + funcionarioQueRegistra + ", observacion=" + observacion + ", fechaReceta=" + fechaReceta + ", detalle=" + detalle + ", paciente=" + paciente + ", reposo=" + reposo + "]"; } }
public class ParkingSpot implements Bookable{ private String spotId; private String location; // e.g., fab-lab, admin car park, hostel car parks... private boolean isOccupied; private String type; // e.g., disabled, general, staff... // Constructor ParkingSpot(String spotId, String location, boolean isOccupied, String type) { this.spotId = spotId; this.location = location; this.isOccupied = isOccupied; this.type = type; } // Getters public String getSpotId() { return spotId; } public String getLocation() { return location; } public boolean getIsOccupied() { return isOccupied; } public String getType() { return type; } // Setters public void setspotId(String spotId) { this.spotId = spotId; } public void setLocation(String location) { this.location = location; } public void setIsOccupied(boolean isOccupied) { this.isOccupied = isOccupied; } public void setType(String type) { this.type = type; } // Bookable interface implementation // method allows user to book a car park spot if it's not already occupied, @Override public boolean book() { if (!this.isOccupied) { this.isOccupied = true; return true; } else { return false; } } // implemented methods to release the car from a parking spot @Override public void release() { isOccupied = false; } } //FUNCTION TO DISPLAY THE PROPERTIES OF THE PARKING SPOT I.E. LOCATION, SPOT ID ETC. public static String displaySpotDetails{}
import React, { useState, useEffect } from 'react'; import { View, Text, Button, Image, ImageBackground, StyleSheet, TextInput, ScrollView, FlatList } from 'react-native'; import axios from 'axios'; // Caminho para a imagem de fundo no seu projeto const backgroundImage = require('./assets/Champions3.jpg'); const TelaSimples = () => { const [info, setInfo] = useState('Clique no botão para pesquisar'); const [teamName, setTeamName] = useState(''); // Para entrada do nome do time const [leagueData, setLeagueData] = useState([]); // Para armazenar todos os dados da liga const [teamDetails, setTeamDetails] = useState(null); // Para armazenar detalhes do time pesquisado const fetchLeagueData = async () => { try { const response = await axios.get( 'https://apiv3.apifootball.com/?action=get_teams&league_id=99&APIkey=73dfd9fe47fea905a22286fb8e3b45b2fcc9c30686927ff8463083e4dbb36f3c' ); if (response.data && response.data.length > 0) { setLeagueData(response.data); // Armazena todos os dados da liga setInfo('Dados da liga carregados com sucesso'); } else { setInfo('Nenhum dado encontrado'); } } catch (error) { console.error(error); setInfo('Erro ao buscar dados da liga'); } }; const searchTeam = () => { // Pesquisa por um time específico no leagueData const team = leagueData.find(t => t.team_name.toLowerCase() === teamName.toLowerCase()); if (team) { setTeamDetails({ teamName: team.team_name, teamLogo: team.team_badge, teamCountry: team.team_country, players: team.players, // Armazena a lista de jogadores }); setInfo(`Detalhes do time: ${teamName}`); } else { setTeamDetails(null); setInfo(`Time ${teamName} não encontrado`); } }; return ( <ImageBackground source={backgroundImage} style={styles.background}> <ScrollView contentContainerStyle={styles.scrollViewContent}> <View style={styles.container}> <TextInput style={styles.input} placeholder="Digite o nome do time" value={teamName} onChangeText={setTeamName} /> <View style={styles.buttonContainer}> <View style={styles.buttonWrapper}> <Button title="Carregar Dados da Liga" onPress={fetchLeagueData} /> </View> <View style={styles.buttonWrapper}> <Button title="Pesquisar Time" onPress={searchTeam} /> </View> <View style={styles.buttonWrapper}> <Button title="Limpar" onPress={() => { setTeamName(''); setTeamDetails(null); setInfo('Clique para pesquisar um time'); }} /> </View> </View> {teamDetails ? ( <View style={styles.teamDetails}> <Image source={{ uri: teamDetails.teamLogo }} style={styles.teamLogo} /> <Text>Nome: {teamDetails.teamName}</Text> <Text>País: {teamDetails.teamCountry}</Text> <Text style={styles.title}>Jogadores</Text> <FlatList data={teamDetails.players} // Lista de jogadores keyExtractor={(item) => item.player_key.toString()} renderItem={({ item }) => ( <View style={styles.playerItem}> <Image source={{ uri: item.player_image }} style={styles.playerImage} /> <Text>{item.player_name}</Text> <Text> {item.player_number}</Text> </View> )} /> </View> ) : ( <Text style={styles.label}>{info}</Text> )} </View> </ScrollView> </ImageBackground> ); }; const styles = StyleSheet.create({ background: { flex: 1, justifyContent: 'flex-start', alignItems: 'center', paddingTop: 60, }, scrollViewContent: { flexGrow: 1, justifyContent: 'center', alignItems: 'center', }, container: { backgroundColor: 'rgba(255, 255, 255, 0.7)', padding: 20, borderRadius: 20, width: 350, }, input: { height: 40, borderColor: 'gray', borderWidth: 1, paddingHorizontal: 10, marginBottom: 20, // Espaço entre o input e os botões }, buttonContainer: { justifyContent: 'space-between', // Para separar os botões marginBottom: 20, // Espaço entre os botões e os detalhes do time }, buttonWrapper: { marginBottom: 10, // Margem entre os botões }, teamDetails: { alignItems: 'center', // Centraliza os detalhes do time }, teamLogo: { width: 150, height: 150, marginVertical: 10, }, playerItem: { flexDirection: 'row', alignItems: 'center', padding: 10, borderBottomWidth: 1, borderBottomColor: '#ccc', }, playerImage: { width: 40, height: 40, borderRadius: 20, marginRight: 10, }, label: { fontSize: 18, color: '#333', marginTop: 10, }, title: { fontSize: 18, fontWeight: 'bold', marginTop: 16, marginBottom: 10, }, }); export default TelaSimples;
import { useState } from "react"; // Next import Link from "next/link"; // Tauri import { invoke } from "@tauri-apps/api/tauri"; // React Syntax Highlighter import { Prism as SyntaxHighlighter } from "react-syntax-highlighter"; import { darcula } from "react-syntax-highlighter/dist/cjs/styles/prism"; // Sweet Alert import Swal from "sweetalert2"; type OAIResponseType = { result: ResponseResultType; prompt: string; max_tokens: number; }; type ResponseChoicesType = { text: string; index: number; finish_reason: string; }; type ResponseResultType = { Ok: { choices: ResponseChoicesType[]; id: string; object: string; created: number; model: string; }; }; export default function Home() { const [isLoading, setIsLoading] = useState(false); const [userText, setUserText] = useState(""); const [query, setQuery] = useState<any>(null); const handleSubmit = async (e: React.FormEvent<HTMLFormElement>) => { e.preventDefault(); setQuery(null); setIsLoading(true); try { const res: any = await invoke("generate_query", { userText }); setQuery(JSON.parse(res?.result?.Ok)); } catch (err: any) { console.log(err); Swal.fire({ icon: "error", title: "Oops...", text: err || "Something went wrong!", }); } setIsLoading(false); }; return ( <section className="w-full h-full font-poppins flex justify-center items-center flex-col"> <div className="absolute top-1/2 -mt-32 pb-14 wax-w-xl w-full"> <h1 className="text-gray-300 font-bold text-center text-3xl -mt-4 mb-10 tracking-wider"> SQL Query Generator </h1> <article className="w-full flex items-center justify-center"> <form className="flex flex-col max-w-xl w-full gap-4" onSubmit={handleSubmit} > <textarea placeholder="Search SQL Query.." className="rounded-md p-3 w-full border-none outline-none disabled:cursor-wait disabled:opacity-70" required onChange={(e) => setUserText(e.target.value)} value={userText} disabled={isLoading} /> <button className="bg-slate-900 text-white w-full p-3 rounded-md outline-none hover:bg-slate-950 transition-all ease-in-out duration-500 disabled:cursor-not-allowed disabled:opacity-80 flex items-center justify-center gap-1" disabled={isLoading} > {isLoading ? ( <> Searching <img src="/images/loader.gif" className="w-7" /> </> ) : ( "Search" )} </button> </form> </article> <article className="my-10 flex flex-col items-center w-full"> {isLoading && ( <div className="w-40"> <img src="/images/cat.gif" /> </div> )} {query && ( <div className="bg-gray-400 p-3 rounded-md w-full max-w-xl"> {query?.choices?.map((item: ResponseChoicesType) => ( <SyntaxHighlighter language="sql" key={item?.index} style={darcula} > {item?.text} </SyntaxHighlighter> ))} </div> )} <p></p> </article> </div> <div className="fixed bottom-0 py-3 left-1/2 -translate-x-1/2 bg-slate-900 w-full flex items-center justify-center"> <h4 className="text-gray-300 text-lg tracking-wide"> Made with ❤️ by{" "} <Link href="https://github.com/hadihaider055" className="underline"> Hadi Haider </Link> </h4> </div> </section> ); } ``;
<template> <div class="col-span-1"> <div class="bg-white rounded border border-gray-200 relative flex flex-col"> <div class="px-6 pt-6 pb-5 font-bold border-b border-gray-200"> <span class="card-title">Upload</span> <i class="fas fa-upload float-right text-teal-600 text-2xl"></i> </div> <div class="p-6"> <!-- Upload Dropbox --> <div :class="{ 'bg-teal-600 border-teal-600 border-dashed': is_dragover }" class="w-full px-10 py-20 rounded text-center cursor-pointer border border-dashed border-gray-400 text-gray-400 transition duration-500 hover:text-white hover:bg-teal-600 hover:bg-teal-600 hover:border-solid" @drag.prevent.stop="" @dragstart.prevent.stop="" @drop.prevent.stop="upload($event)" @dragover.prevent.stop="is_dragover = true" @dragenter.prevent.stop="is_dragover = true" @dragleave.prevent.stop="is_dragover = false" @dragend.prevent.stop="is_dragover = false" > <h5>Drop your files here</h5> </div> <hr class="my-6" /> <!-- Progess Bar --> <div class="mb-4" v-for="upload in uploads" :key="upload.name"> <!-- File Name --> <div class="font-bold text-sm" :class="upload.text_class"> <i :class="upload.icon"></i>{{ upload.name }} </div> <div class="flex h-4 overflow-hidden bg-gray-200 rounded"> <!-- Inner Progress Bar --> <div class="transition-all progress-bar" :class="upload.variant" :style="{ width: upload.current_progress + '%' }" ></div> </div> </div> </div> </div> </div> </template> <script lang="ts"> import { defineComponent } from "vue"; import { storage, songsCollection } from "@/includes/firebase"; import UploadSong from "@/interfaces/upload-song.interface"; import Track from "@/interfaces/song.interface"; export default defineComponent({ name: "RafUpload", data() { return { is_dragover: false, uploads: [] as UploadSong[], }; }, methods: { upload(ev: DragEvent) { // capture files and check type const dropFiles = ev?.dataTransfer?.files; if (dropFiles) { Object.values(dropFiles).forEach((file) => { if (file.type !== "audio/mpeg") { return; } // db ref const storageRef = storage.ref(); // directory ref const songsRef = storageRef.child(`songs/${file.name}`); // init task const task = songsRef.put(file); // push new upload on and find index const uploadIndex = this.uploads.push({ task, current_progress: 0, name: file.name, variant: "bg-teal-700", icon: "fas fa-spinner fa-spin", text_class: "", }) - 1; const currentUpload = this.uploads[uploadIndex]; // listen to task execution task.on( "state_changed", (snapshot) => { currentUpload.current_progress = (snapshot.bytesTransferred / snapshot.totalBytes) * 100; }, (error) => { currentUpload.variant = "bg-red-400"; currentUpload.icon = "fas fa-times"; currentUpload.text_class = "text-red-400"; }, async () => { // create new track for db const song: Track = { userDisplayName: "Artie", originalName: task.snapshot.ref.name, modifiedName: task.snapshot.ref.name, comment_count: 0, genre: "", uid: "123456", url: "", }; song.url = await task.snapshot.ref.getDownloadURL(); await songsCollection.add(song); // toggle css for completion currentUpload.variant = "bg-zinc-600"; currentUpload.icon = "fas fa-check"; currentUpload.text_class = "text-teal-600"; } ); }); } // reset drop box style this.is_dragover = false; }, }, beforeUnmount() { this.uploads.forEach((upload, i) => { upload.task.cancel(); if (i === this.uploads.length - 1) { console.log( "%c Uploads canceled - Please Retry", "color: red; font-size: 14px" ); } }); }, }); </script>
import { TableHead, TableRow, TableCell, Checkbox, TableSortLabel } from '@mui/material'; import { ChangeEvent } from 'react'; import { image, headCells } from './constants'; export type Order = 'asc' | 'desc'; interface EnhancedTableHeadProps { onRequestSort: (property: string) => void; onSelectAllClick: (event: ChangeEvent<HTMLInputElement>) => void; order: Order; orderBy: string; } export const EnhancedTableHead = ({ order, orderBy, onRequestSort, onSelectAllClick, }: EnhancedTableHeadProps): JSX.Element => { const createSortHandler = (property: string) => onRequestSort(property); const generateHeadCells = () => { return headCells.map(headCell => { if (headCell.id === image) { return <TableCell key={headCell.id}>{headCell.label}</TableCell>; } return ( <TableCell key={headCell.id} sortDirection={orderBy === headCell.id ? order : false} > <TableSortLabel active={orderBy === headCell.id} direction={orderBy === headCell.id ? order : 'asc'} onClick={() => createSortHandler(headCell.id)} > {headCell.label} </TableSortLabel> </TableCell> ); }); }; return ( <TableHead> <TableRow> <TableCell padding="checkbox"> <Checkbox color="primary" onChange={onSelectAllClick} /> </TableCell> {generateHeadCells()} <TableCell></TableCell> </TableRow> </TableHead> ); };
define(function (require) { // base angular components/directives we expect to be loaded require('angular-bootstrap'); require('angular-cookies'); require('services/private'); require('components/config/config'); require('components/courier/courier'); require('components/filter_bar/filter_bar'); require('components/notify/notify'); require('components/persisted_log/persisted_log'); require('components/state_management/app_state'); require('components/storage/storage'); require('components/url/url'); require('components/doc_title/doc_title'); require('components/tooltip/tooltip'); require('components/style_compile/style_compile'); require('components/watch_multi'); require('components/bind'); require('components/listen'); require('components/fancy_forms/fancy_forms'); require('components/stringify/register'); require('directives/click_focus'); require('directives/info'); require('directives/spinner'); require('directives/paginate'); require('directives/pretty_duration'); require('directives/rows'); // @lu: authorization require('plugins/auth/services/auth'); var Notifier = require('components/notify/_notifier'); // ensure that the kibana module requires ui.bootstrap require('modules') .get('kibana', ['ui.bootstrap', 'ngCookies']) .config(function ($tooltipProvider, $httpProvider, configFile) { $tooltipProvider.setTriggers({ 'mouseenter': 'mouseleave click' }); $httpProvider.interceptors.push(function () { return { request: function (opts) { var kbnXsrfToken = configFile.xsrf_token; if (kbnXsrfToken) { var headers = opts.headers || (opts.headers = {}); headers['kbn-xsrf-token'] = kbnXsrfToken; } return opts; } }; }); }) .constant('AUTH_EVENTS', { loginSuccess: 'auth-login-success', loginFailed: 'auth-login-failed', logoutSuccess: 'auth-logout-success', sessionTimeout: 'auth-session-timeout', notAuthenticated: 'auth-not-authenticated', notAuthorized: 'auth-not-authorized' }) .constant('USER_ROLES', { all: '*', admin: 'admin', editor: 'editor', guest: 'guest' }) .directive('kibana', function (Private, $rootScope, $injector, Promise, config, kbnSetup, USER_ROLES, AuthService) { return { template: require('text!plugins/kibana/kibana.html'), controllerAs: 'kibana', controller: function ($scope) { var _ = require('lodash'); var self = $rootScope.kibana = this; var notify = new Notifier({ location: 'Kibana' }); // this is the only way to handle uncaught route.resolve errors $rootScope.$on('$routeChangeError', function (event, next, prev, err) { notify.fatal(err); }); // run init functions before loading the mixins, so that we can ensure that // the environment is ready for them to get and use their dependencies self.ready = Promise.all([ kbnSetup(), config.init() ]) .then(function () { // load some "mixins" var mixinLocals = { $scope: $scope, notify: notify }; $injector.invoke(require('plugins/kibana/_init'), self, mixinLocals); $injector.invoke(require('plugins/kibana/_apps'), self, mixinLocals); $injector.invoke(require('plugins/kibana/_timepicker'), self, mixinLocals); $scope.setupComplete = true; }); // @lu: auth $scope.currentUser = null; $scope.userRoles = USER_ROLES; $scope.isAuthorized = AuthService.isAuthorized; $scope.setCurrentUser = function (user) { $scope.currentUser = user; }; $scope.logout = function() { AuthService.logout(); } } }; }); });
using AutoMapper; using Backend.DB.Models; using Backend.DTO.Course; using Backend.DTO.CourseDetails; using Backend.Repository.CourseDetailsRepository; using Microsoft.EntityFrameworkCore; namespace Backend.Services.CourseDetails { public class CourseDetailsService : ICourseDetailsService { private readonly ICourseDetailsRepository _courseDetailsRepository; private readonly IMapper _mapper; public CourseDetailsService(ICourseDetailsRepository courseDetailsRepository, IMapper mapper) { _courseDetailsRepository = courseDetailsRepository; _mapper = mapper; } public ICollection<CourseDetailsDTO>? GetAllCourseDetails() { try { var courseDetails = _courseDetailsRepository.GetAll(). Include(c => c.Course).ToList(); ; return courseDetails is null ? null : _mapper.Map<ICollection<CourseDetailsDTO>>(courseDetails); } catch (Exception e) { Console.WriteLine(e); throw; } } public async Task<ServiceResult<int>> CreateCourseDetails (ICollection<CourseDetailsCreateDTO> courseDetailsCreateDto) { var result = new ServiceResult<int>(); int i = 0; var courseDetail = courseDetailsCreateDto.ElementAt(0); var m = courseDetail.CourseTimeEnd; try { foreach (var c in courseDetailsCreateDto) { if (c.CourseTimeEnd < c.CourseTimeStart) { result.IsError = true; result.Payload = 0; result.ErrorMessage = "Ngày kết thúc phải lớn hơn ngày bắt đầu"; return result; } if (i != 0) { if (c.CourseTimeStart < m) { result.IsError = true; result.Payload = -1; result.ErrorMessage = "Ngày bắt đầu phải lớn hơn ngày kết thúc của kỳ trước"; return result; } var courseDetaill = _mapper.Map<DB.Models.CourseDetail>(c); courseDetaill.Status = true; await _courseDetailsRepository.CreateAsync(courseDetaill); m = courseDetail.CourseTimeEnd; } else { var courseDetaill = _mapper.Map<DB.Models.CourseDetail>(c); courseDetaill.Status = true; await _courseDetailsRepository.CreateAsync(courseDetaill); } i++; } } catch (Exception e) { result.IsError = true; result.Payload = 0; result.ErrorMessage = e.Message; } return result; } public async Task<ServiceResult<ICollection<CourseDetailsDTO>>> GetCourseDetailsByCourse(string courseId) { var result = new ServiceResult<ICollection<CourseDetailsDTO>>(); try { var courseDetails = await _courseDetailsRepository.GetAll() .Include(c => c.Course) .Where(p => p.CourseId == courseId).ToListAsync(); if (!courseDetails.Any()) { result.IsError = true; result.ErrorMessage = "Không tìm thấy nội dung khóa học"; return result; } result.Payload = _mapper.Map<ICollection<CourseDetailsDTO>>(courseDetails); } catch (Exception e) { result.IsError = true; result.ErrorMessage = e.Message; } return result; } public async Task<ServiceResult<int>> UpdateCourseDetails (ICollection<CourseDetailsCreateDTO> courseDetailsCreateDto) { var result = new ServiceResult<int>(); int i = 0; var courseDetail = courseDetailsCreateDto.ElementAt(0); var m = courseDetail.CourseTimeEnd; try { foreach (var c in courseDetailsCreateDto) { if (c.CourseTimeEnd < c.CourseTimeStart) { result.IsError = true; result.Payload = 0; result.ErrorMessage = "Ngày kết thúc phải lớn hơn ngày bắt đầu"; return result; } if (i != 0) { if (c.CourseTimeStart < m) { result.IsError = true; result.Payload = -1; result.ErrorMessage = "Ngày bắt đầu phải lớn hơn ngày kết thúc của kỳ trước"; return result; } var courseDetaill = _mapper.Map<DB.Models.CourseDetail>(c); courseDetaill.Status = true; await _courseDetailsRepository.UpdateAsync(courseDetaill); m = courseDetail.CourseTimeEnd; } else { var courseDetaill = _mapper.Map<DB.Models.CourseDetail>(c); courseDetaill.Status = true; await _courseDetailsRepository.CreateAsync(courseDetaill); } i++; } } catch (Exception e) { result.IsError = true; result.Payload = 0; result.ErrorMessage = e.Message; } return result; } } }
import React, { useRef, useState, useEffect } from 'react'; import { SafeAreaView, ScrollView, StyleSheet, Text, View, TouchableOpacity, } from 'react-native'; import { PermissionsAndroid, Platform } from 'react-native'; import { ClientRoleType, createAgoraRtcEngine, IRtcEngine, ChannelProfileType, } from 'react-native-agora'; const appId = 'enter-your-appid'; const channelName = 'dhruvicalling'; const token = 'enter-your-tokenid'; const uid = 0; const App = () => { const agoraEngineRef = useRef<IRtcEngine>(); // Agora engine instance const [isJoined, setIsJoined] = useState(false); // Indicates if the local user has joined the channel const [remoteUid, setRemoteUid] = useState(0); // Uid of the remote user const [message, setMessage] = useState(''); // Message to the user useEffect(() => { // Initialize Agora engine when the app starts setupVoiceSDKEngine(); }, []); const join = async () => { if (isJoined) { return; } try { agoraEngineRef.current?.setChannelProfile( ChannelProfileType.ChannelProfileCommunication, ); agoraEngineRef.current?.joinChannel(token, channelName, uid, { clientRoleType: ClientRoleType.ClientRoleBroadcaster, }); } catch (e) { console.log(e); } }; const setupVoiceSDKEngine = async () => { try { // use the helper function to get permissions if (Platform.OS === 'android') { await getPermission(); } agoraEngineRef.current = createAgoraRtcEngine(); const agoraEngine = agoraEngineRef.current; agoraEngine.registerEventHandler({ onJoinChannelSuccess: () => { showMessage('Successfully joined the channel ' + channelName); setIsJoined(true); }, onUserJoined: (_connection, Uid) => { showMessage('Remote user joined with uid ' + Uid); setRemoteUid(Uid); }, onUserOffline: (_connection, Uid) => { showMessage('Remote user left the channel. uid: ' + Uid); setRemoteUid(0); }, }); agoraEngine.initialize({ appId: appId, }); } catch (e) { console.log(e); } }; const leave = () => { try { agoraEngineRef.current?.leaveChannel(); setRemoteUid(0); setIsJoined(false); showMessage('You left the channel'); } catch (e) { console.log(e); } }; function showMessage(msg: string) { setMessage(msg); } return ( <SafeAreaView style={styles.container}> <Text style={styles.header}>Calling App</Text> <View style={styles.buttonContainer}> <TouchableOpacity onPress={join} style={styles.joinButton}> <Text style={styles.buttonText}>Join</Text> </TouchableOpacity> <TouchableOpacity onPress={leave} style={styles.leaveButton}> <Text style={styles.buttonText}>Leave</Text> </TouchableOpacity> </View> <ScrollView style={styles.scroll} contentContainerStyle={styles.scrollContainer}> {isJoined ? ( <Text style={styles.infoText}>Local user uid: {uid}</Text> ) : ( <Text style={styles.infoText}>Join a channel</Text> )} {isJoined && remoteUid !== 0 ? ( <Text style={styles.infoText}>Remote user uid: {remoteUid}</Text> ) : ( <Text style={styles.infoText}>Waiting for a remote user to join</Text> )} <Text style={styles.messageText}>{message}</Text> </ScrollView> </SafeAreaView> ); }; const styles = StyleSheet.create({ container: { flex: 1, alignItems: 'center', backgroundColor: '#f0f0f0', }, header: { fontSize: 24, fontWeight: 'bold', marginVertical: 20, }, buttonContainer: { flexDirection: 'row', justifyContent: 'center', marginBottom: 20, }, joinButton: { paddingHorizontal: 25, paddingVertical: 10, borderRadius: 8, backgroundColor: '#4CAF50', margin: 5, }, leaveButton: { paddingHorizontal: 25, paddingVertical: 10, borderRadius: 8, backgroundColor: '#E57373', margin: 5, }, buttonText: { color: '#ffffff', fontWeight: 'bold', fontSize: 16, }, scroll: { flex: 1, backgroundColor: '#ffffff', width: '90%', padding: 10, borderRadius: 8, }, scrollContainer: { alignItems: 'center', }, infoText: { fontSize: 18, marginVertical: 10, }, messageText: { fontSize: 16, fontStyle: 'italic', color: '#555555', }, }); const getPermission = async () => { if (Platform.OS === 'android') { await PermissionsAndroid.requestMultiple([ PermissionsAndroid.PERMISSIONS.RECORD_AUDIO, ]); } }; export default App;
package com.example.demo.gql; import com.example.demo.repository.AuthorNotFoundException; import com.example.demo.repository.PostNotFoundException; import graphql.ErrorClassification; import graphql.GraphQLError; import graphql.GraphqlErrorBuilder; import graphql.execution.DataFetcherExceptionHandler; import graphql.execution.DataFetcherExceptionHandlerParameters; import graphql.execution.DataFetcherExceptionHandlerResult; import graphql.execution.SimpleDataFetcherExceptionHandler; import lombok.extern.slf4j.Slf4j; @Slf4j public class CustomDataFetchingExceptionHandler implements DataFetcherExceptionHandler { private final SimpleDataFetcherExceptionHandler defaultHandler = new SimpleDataFetcherExceptionHandler(); @Override public DataFetcherExceptionHandlerResult onException(DataFetcherExceptionHandlerParameters handlerParameters) { Throwable exception = handlerParameters.getException(); if (exception instanceof AuthorNotFoundException || exception instanceof PostNotFoundException) { log.debug("caught exception: {}", exception); enum TypedError implements ErrorClassification { NOT_FOUND } GraphQLError graphqlError = GraphqlErrorBuilder.newError() .message(exception.getMessage()) .errorType(TypedError.NOT_FOUND) .path(handlerParameters.getPath()) .build(); return DataFetcherExceptionHandlerResult.newResult() .error(graphqlError) .build(); } else { return defaultHandler.onException(handlerParameters); } } }
import * as React from 'react'; import { getPvcs } from '../../../../../api'; import { PersistentVolumeClaimKind } from '../../../../../k8sTypes'; const useProjectPvcs = ( namespace?: string, ): [ pvcs: PersistentVolumeClaimKind[], loaded: boolean, loadError: Error | undefined, forceRefresh: () => void, ] => { const [pvcs, setPvcs] = React.useState<PersistentVolumeClaimKind[]>([]); const [loaded, setLoaded] = React.useState(false); const [loadError, setLoadError] = React.useState<Error | undefined>(undefined); const getProjectPvcs = React.useCallback(() => { if (namespace) { getPvcs(namespace) .then((newPvcs) => { setPvcs(newPvcs); setLoaded(true); }) .catch((e) => { setLoadError(e); setLoaded(true); }); } else { setPvcs([]); setLoaded(true); setLoadError(undefined); } }, [namespace]); const forceRefresh = React.useCallback(() => { getProjectPvcs(); }, [getProjectPvcs]); React.useEffect(() => { getProjectPvcs(); }, [getProjectPvcs]); return [pvcs, loaded, loadError, forceRefresh]; }; export default useProjectPvcs;
'use client'; import React from 'react'; import Login from '../Login/Login'; import Image from 'next/image'; import timeboxLogo from '../../assets/evocal-2.png'; import Link from 'next/link'; import styles from './Navbar.module.css'; import { useSession } from 'next-auth/react'; import { Avatar, AvatarFallback, AvatarImage } from '@/components/ui/avatar'; import Logout from '../Logout/Logout'; import SignUp from '../Signup/Signup'; import Feedback from '../../app/feedback'; import { CiCalendar } from 'react-icons/ci'; import { MdOutlineFeedback } from 'react-icons/md'; import { Separator } from '@/components/ui/separator'; import { DropdownMenu, DropdownMenuContent, DropdownMenuItem, DropdownMenuLabel, DropdownMenuSeparator, DropdownMenuTrigger, } from '@/components/ui/dropdown-menu'; import ModeToggle from '../ModeToggle/ModeToggle'; import { usePathname } from 'next/navigation'; export default function Navbar() { const session = useSession(); const pathName = usePathname(); return ( <> <nav className={`${styles.navbar} fixed left-1/2 translate-x-[-50%] top-0 rounded-3xl ${pathName == '/' ? 'dark:bg-black/30 bg-neutral-200/30' : 'dark:bg-neutral-900'} px-6 py-2 my-4 z-40 backdrop-blur-md`} > <div className="nav__log"> <Link href="/" className="flex items-center"> <Image src={timeboxLogo} width={50} height={50} alt="Timebox logo" className="dark:invert rounded-3xl" ></Image> <h1 className="font-bold poppins dark:text-neutral-50 text-neutral-800 ml-4"> Evo<span className="text-neutral-500">Cal</span> </h1> </Link> </div> <div className={`${styles.nav__links} flex items-center justify-center`} > {session?.data?.user ? ( <></> ) : ( <> <Login /> <SignUp /> <div className="flex items-center justify-center mx-2"> <ModeToggle /> </div> </> )} <div> {session?.data?.user && ( <> <div className=" flex items-center justify-center"> <DropdownMenu> <DropdownMenuTrigger> <Avatar className="mx-3"> <AvatarImage src={ session?.data?.user ?.image || '' } alt="User image" width={30} height={30} /> <AvatarFallback> {session?.data?.user?.email ?.charAt(0) .toUpperCase()} </AvatarFallback> </Avatar> </DropdownMenuTrigger> <DropdownMenuContent> <DropdownMenuLabel> {session.data.user.name ? session.data.user.name : session?.data?.user.email} </DropdownMenuLabel> <DropdownMenuSeparator /> <DropdownMenuItem> <Link href="/calendar" className="flex items-center justify-center" > {' '} <CiCalendar className="mr-2" /> Go to Calendar </Link> </DropdownMenuItem> <DropdownMenuItem> <div className="flex items-center justify-center"> <MdOutlineFeedback className="mr-2" /> <Feedback /> </div> </DropdownMenuItem> <Separator className="my-2"></Separator> <DropdownMenuItem> <Logout /> </DropdownMenuItem> </DropdownMenuContent> </DropdownMenu> <ModeToggle /> </div> </> )} </div> </div> </nav> </> ); }
# This is a sample Python script that runs the chest x-ray scanning app import streamlit as st from PIL import Image, ImageOps from keras.models import load_model from loguru import logger import numpy as np def load_ml_model(): keras_model = load_model('./ml_model/keras_model.h5') return keras_model st.title("Pneumonia X-Ray scanning app") st.text("This app used a ML model trained on thousands on chest x-rays for identifying " "pneumonia, it has a reasonable accuracy north of 90%. ") uploaded_file = st.file_uploader("Choose an image...", type=["jpg", "jpeg", "png"]) keras_model = load_ml_model() if uploaded_file is not None: image = Image.open(uploaded_file).convert('RGB') st.image(image, caption='Uploaded Image.', use_column_width=True) with st.form(key='classification form'): submit_button = st.form_submit_button(label='submit') if submit_button: st.write("Classifying...") if keras_model is not None: keras_model = load_ml_model() data = np.ndarray(shape=(1, 224, 224, 3), dtype=np.float32) # Replace this with the path to your image # resize the image to a 224x224 with the same strategy as in TM2: # resizing the image to be at least 224x224 and then cropping from the center size = (224, 224) image = ImageOps.fit(image, size, Image.ANTIALIAS) # turn the image into a numpy array image_array = np.asarray(image) # Normalize the image normalized_image_array = (image_array.astype(np.float32) / 127.0) - 1 # Load the image into the array data[0] = normalized_image_array prediction = keras_model.predict(data) logger.info('prediction -> {}'.format(prediction)) label_dict = {'0': 'Normal', '1': 'Pneumonia'} logger.info(label_dict) normal_prob = round(prediction[0][0],4) pneumonia_prob = round(prediction[0][1],4) final_label = 'Normal' if normal_prob > pneumonia_prob else 'Pneumonia' final_proba = normal_prob if normal_prob > pneumonia_prob else pneumonia_prob st.write('{} with {:.2f}% confidence'.format(final_label, final_proba*100))
# https://github.com/PdxCodeGuild/class_salmon/blob/main/2%20Flask%20%2B%20HTML%20%2B%20CSS/mob/jsondb.py import json class JsonDB: def __init__(self, path='database.json'): self.path = path self.data = None def __str__(self) -> str: return str(self.data) def load(self): with open(self.path, 'r') as file: self.data = json.loads(file.read()) def save(self): with open(self.path, 'w') as file: file.write(json.dumps(self.data, indent=4, sort_keys=True)) def __getitem__(self, key): return self.data[key] def __setitem__(self, key, value): self.data[key] = value def __delitem__(self, key): del self.data[key] def get(self, key, default=None): return self.data.get(key, default) def set(self, key, value): self.data[key] = value def clear(self, key=None): if key is not None: del self.data[key] else: self.data = {}
<script setup> import RatingScore from './RatingScore.vue' import MovieImage from './MovieImage.vue' import BookmarkActionsNav from './BookmarkActionsNav.vue' defineProps({ type: String, movie: Object }) </script> <template> <div class="movie movie-simple"> <div class="movie-poster"> <RouterLink class="s" :to="{ name: 'movie', params: { id: movie.id } }" > <MovieImage :path="movie.poster_path" :title="movie.title" /> </RouterLink> <BookmarkActionsNav :movie="movie" :type="type" /> </div> <div class="movie-details"> <div class="movie-title"> <h2 class="movie-title-text"> <RouterLink class="s" :to="{ name: 'movie', params: { id: movie.id } }" > {{ movie.title }} </RouterLink> </h2> <div class="movie-title-rating"> <RatingScore :score="movie.vote_average" /> </div> </div> </div> </div> </template>
/** @format */ import paletteCreator from "../components/style/PaletteCreator"; import { Card } from "../types/Types"; export async function changePage( filters, currentPage, index, maxPages, cardsPerPage ) { let newPage = currentPage + index; newPage = newPage >= maxPages ? maxPages : newPage < 0 ? 0 : newPage; const params = { subject: filters.subjects, activity: filters.activities, deadline: filters.deadline, checked: filters.checked, _start: newPage * cardsPerPage, _limit: cardsPerPage, }; const currentCards = await fetchCards(params); return { newPage, currentCards }; } export const getXP = async () => { let XP = 0; const res = await fetch( `${process.env.REACT_APP_FAKE_SERVER}/cards?checked=true` ); const cards: Card[] = await res.json(); cards.map((card) => (XP += Number(card.xp))); return XP; }; export const fetchGameLevels = async (level = "") => { const params = level ? paramBuilder(level) : ""; const res = await fetch( `${process.env.REACT_APP_FAKE_SERVER}/levels/${params}` ); return await res.json(); }; export const updateGameLevels = (userData, gameLevels) => {}; export async function fetchActivities() { const response = await fetch( `${process.env.REACT_APP_FAKE_SERVER}/activities`, { headers: { "Content-Type": "json" }, } ); return await response.json(); } export const fetchCards = async (params, getXTotalCount = false) => { const queryParams = paramBuilder(params); const response = await fetch( `${process.env.REACT_APP_FAKE_SERVER}/cards?${queryParams}`, { headers: { "Content-Type": "text/html" }, } ); const data = await response.json(); const xTotalCount = Number(response.headers.get("X-total-count")); return getXTotalCount ? [data, xTotalCount] : data; }; export async function createSubjectPalette() { const subjects = await fetchSubjects(); const subjectPalette = paletteCreator(subjects, "#c491ff", "#b56576"); return subjectPalette; } export async function createActivityPalette() { const activities = await fetchActivities(); const activityPalette = paletteCreator(activities, "#ff6f08", "#ff6f08"); return activityPalette; } export const fetchSubjects = async () => { const response = await fetch( `${process.env.REACT_APP_FAKE_SERVER}/subjects`, { headers: { "Content-Type": "json" }, } ); const data = await response.json(); return data; }; export function setPagesParameters(cardHeight, windowHeight, totalCards) { const cardsPerPage = Math.floor((windowHeight * 0.85) / (cardHeight + 16)); const maxPages = Math.floor(totalCards / cardsPerPage); const PageParameters = { cardsPerPage: cardsPerPage, maxPages: maxPages }; return PageParameters; } export const paramBuilder = (queryParams) => { const params = {}; const keys = [ "subject", "type", "deadline", "checked", "_start", "_limit", "level", ]; const values = Object.values(queryParams); values.map((value, index) => { return value || value === false ? (params[keys[index]] = value) : ""; }); return new URLSearchParams(params); }; export const handlePageChange = async ( index: number, filters, page, maxPages, cardsPerPage, dispatch ) => { const payload = await changePage( filters, page, index, maxPages, cardsPerPage ); dispatch({ type: "CHANGE_PAGE", payload: payload }); }; export const filterCards = async ( filters, windowHeight, dispatch, page, cardsPerPage ) => { const { subjects, activities, deadline, checked } = filters; const params = { subjects: subjects, activites: activities, deadline: deadline, checked: checked, _start: page, _limit: cardsPerPage, }; const payload = await fetchCards(params); //Workaround to get number of filtered cards const params2 = { subjects: subjects, activites: activities, deadline: deadline, checked: checked, }; const payload2 = await fetchCards(params2); dispatch({ type: "LOAD_TOTAL_CARDS", payload: payload2.length, }); const filteredPagesParameters = await setPagesParameters( 100, windowHeight, payload2.length ); dispatch({ type: "SET_PAGES_PARAMETERS", payload: filteredPagesParameters, }); dispatch({ type: "RENDER_CARDS", payload: payload }); }; export const setUserLevel = (userXP, gameLevels) => { let userLevel = "0"; for (let level = 0; userXP > Number(gameLevels[level]); level++) { userLevel = level.toString(); } return userLevel; }; export const fetchUserData = async (id = "") => { const res = await fetch(`${process.env.REACT_APP_FAKE_SERVER}/user`); const userData = await res.json(); const userXP = await getXP(); const gameLevels = await fetchGameLevels(); const userLevel = setUserLevel(userXP, gameLevels); return { ...userData, xp: userXP, level: userLevel }; }; export const init = async (cardHeight, dispatch, windowHeight) => { dispatch({ type: "LOGIN_SUCCESS" }); const firstCardParams = { subject: "", activity: "", deadline: "", checked: "", _start: 0, _limit: 1, }; dispatch({ type: "SET_LOADING", payload: true }); const [firstCard, xTotalCount] = await fetchCards(firstCardParams, true); dispatch({ type: "LOAD_TOTAL_CARDS", payload: xTotalCount }); const subjects = await fetchSubjects(); const subjectPalette = await createSubjectPalette(); const activities = await fetchActivities(); const activityPalette = await createActivityPalette(); const gameLevels = await fetchGameLevels(); const userData = await fetchUserData(); dispatch({ type: "LOAD_SUBJECTS", payload: subjects }); dispatch({ type: "FETCH_ACTIVITIES", payload: activities }); dispatch({ type: "CREATE_PALETTES", payload: { subjectPalette, activityPalette }, }); dispatch({ type: "SET_GAME_LEVELS", payload: gameLevels }); dispatch({ type: "SET_USER_DATA", payload: userData }); const pageParameters = setPagesParameters( cardHeight, windowHeight, xTotalCount ); dispatch({ type: "SET_PAGES_PARAMETERS", payload: pageParameters }); const { cardsPerPage } = pageParameters; const firstLoadParams = { subject: "", activity: "", deadline: "", checked: "", _start: 0, _limit: cardsPerPage, }; dispatch({ type: "CLEAR_CARDS" }); const cards = await fetchCards(firstLoadParams); dispatch({ type: "RENDER_CARDS", payload: cards }); dispatch({ type: "INIT_SUCCESS" }); setTimeout(() => dispatch({ type: "SET_LOADING", payload: false }), 1000); }; /** Puts the current state of the task in the database. * * @param id - Card id. * @eventProperty */ export const addDone: any = async (item, id) => { item.checked = !item.checked; await fetch(`${process.env.REACT_APP_FAKE_SERVER}/cards/${id}`, { method: "PUT", headers: { "Content-Type": "application/json" }, body: JSON.stringify(item), }); }; /** handles what happens when the user clicks on the checkbox item, by calling the 'addDone' * function and flipping the 'completed' state. * * @params id - Card id * @params item - the card. * @params xp - current user XP. * @params completed, setCompleted - useState function to update the checkmark. * @params dispatch - dispatch function that comes from {@link AppReducer.} * @eventProperty */ export const setLastLevel = (gameLevels) => { const levelIndexes = Object.keys(gameLevels); const lastLevel = levelIndexes[levelIndexes.length - 1]; return lastLevel; };
package com.abhi41.jetweatherforcast.repository import com.abhi41.jetweatherforcast.data.WeatherDao import com.abhi41.jetweatherforcast.model.DbModel.Favorite import com.abhi41.jetweatherforcast.model.DbModel.Unit import kotlinx.coroutines.flow.Flow import javax.inject.Inject class WeatherDbRepository @Inject constructor(private val weatherDao: WeatherDao) { fun getFavorites(): Flow<List<Favorite>> = weatherDao.getFevorites() suspend fun insertFavorite(favorite: Favorite) = weatherDao.insertFavourite(favorite) suspend fun updateFavorite(favorite: Favorite) = weatherDao.updateFavourite(favorite) suspend fun deleteFavorite(favorite: Favorite) = weatherDao.deleteFavorites(favorite) suspend fun deleteAllFavorites() = weatherDao.deleteAllFavourites() suspend fun getFavById(city: String): Favorite = weatherDao.getFavById(city) //---------------------Unit-------------------------- fun getUnits(): Flow<List<Unit>> = weatherDao.getUnits() suspend fun insertUnit(unit: Unit) = weatherDao.insertUnit(unit) suspend fun updateUnit(unit: Unit) = weatherDao.updateUnit(unit) suspend fun deleteAllUnit() = weatherDao.deleteAllUnits() suspend fun deleteUnit(unit: Unit) = weatherDao.deleteUnit(unit) }
import Foundation @objc class Spaceship: NSObject { @objc let name: String @objc let shipDescription: String? @objc let cost: Int init(name: String, description: String? = nil, cost: Int) { self.name = name self.shipDescription = description self.cost = cost } } extension Spaceship { static let deathStar = Spaceship(name: "Death Star", cost: .max) static let tardis = Spaceship( name: "Tardis", description: "Time And Relative Dimension In Space", cost: 100 ) } let predicate = NSPredicate(format: "shipDescription LIKE %@", "T") print([Spaceship.deathStar, .tardis].filter(predicate.evaluate(with:)).map(\.name))
<script lang="ts"> import { onMount } from 'svelte'; import Card from '../Card/Card.svelte'; import Flex from '../FlexAndGrid/Flex.svelte'; import { cubeCss } from '../../../utils/cubeCss/cubeCss'; import Item from './Item.svelte'; import Button from '../../Interactibles/Button/Button.svelte'; import { homeStore } from '../../../stores/homeStore'; function addAllItems() { categoryItems.forEach(item => homeStore.addItem(item)); } export let categoryName: string; export let categoryItems: string[]; export let canAddAll = false; let showItems = false; </script> <Card> <header class="category__header"> <Flex align="center" justify="space-between"> <h2 class="fw-500"> {categoryName} <span class="fs-400 clr-neutral-800">[{categoryItems.length}]</span> </h2> <Flex align='center' gap={2}> <Button on:click={() => (showItems = !showItems)} variant={showItems ? 'error' : 'muted'} attachments={['hologram', 'mix']} > {#if showItems} Close {:else} Open {/if} </Button> {#if canAddAll} <Button on:click={addAllItems} attachments={['hologram', 'mix', 'tiny-pad', 'capsule']} > Add all </Button> {/if} </Flex> </Flex> </header> {#if showItems} <Flex cls={cubeCss('', '', 'width-100 margin-block-start-1')} useColumn={true}> {#each categoryItems as item} <Card cls={cubeCss('', '', 'width-100')} variant="muted-light"> <Item {item} /> </Card> {/each} </Flex> {/if} </Card>
This is an example showing the "memory logging" feature in which the pre-HLS and post-HLS memory logs are used to debug a problem in the design involving the incorrect usage of the "ignore_memory_precedences" Catapult directive. See ../../doc/memory_logging_and_debug.pdf for a detailed description of the memory logging and debug methodology and of this particular example. Note that this example uses a locally patched version of mc_transactors.h to enable monitoring of the memory in the post-HLS model. This approach to memory monitoring is not the most general approach, and it is not a currently supported feature of Catapult. The most general way to generate memory logs for memories in RTL models is to write a monitor in Verilog or VHDL. The monitor "snoops" the ports to the memory of interest, converts the pin wiggles to read/write operations, and generates the logs in the same format demonstrated here. If the memory is internal to the DUT, the Verilog "dotted name" syntax (e.g. dut1.blk1.my_mem.raddr ) can be used to gain access to memories within the DUT. Steps: 1. Build the SystemC simulation executable by typing: make build 2. Run the SC simulation by typing: ./sim_sc 3. View the waveforms generated from the SC simulation: make view_wave 4. Run Catapult HLS to generate Verilog RTL for DUT: catapult -f go_hls.tcl 5. Launch SCVerify / QuestaSim with generated RTL by typing in Catapult command line: dofile scverify.tcl 6. Run RTL Sim by typing in QuestaSim command line: run -all wave zoom full 7. View the RTL simulation waveforms and compare to SC waveforms before HLS synthesis 8. Delete all generated files make clean
import { FlyRocketPowered } from "./FlyRocketPowered"; import { MallardDuck } from "./MallardDuck"; import { ModelDuck } from "./ModelDuck"; export const miniDuckSimulator = () => { const mallard = new MallardDuck(); mallard.performQuack(); mallard.performFly(); const model = new ModelDuck(); model.performFly(); model.setFlyBehavior(new FlyRocketPowered()); model.performFly(); }; miniDuckSimulator();
import React, { useEffect, useState } from 'react' import { Api } from '../API/Api' import { endPoints } from '../API/Endpoint' import Slider from 'react-slick' import ProductCard from './ProductCard' const CozyAtHomeSlider = ({ data }) => { const [CozyAtHomeSliderData, SetCozyAtHomeSliderData] = useState() useEffect(() => { const requestpayload = { block_name: data.block_name, id: data.id } Api.post(endPoints.GET_HOME_PAGE_DATA, requestpayload).then((res) => SetCozyAtHomeSliderData(res.data.data)) .catch((err) => console.log(err)) }, [data]) const settings = { dots: false, infinite: false, speed: 500, slidesToShow: 6, slidesToScroll: 1 }; return (<> <div className="arrival-costumes"> <div className="arrival-caption"> <h2>Cozy at home</h2><a className="shop-now" href="/product-listing-page/block?block_name=subcategory-product&amp;id=609d1142a227e8400ce5ff0d">View All</a> </div> <div className="popular-costumes"> <Slider {...settings}> {CozyAtHomeSliderData ? CozyAtHomeSliderData.map((item, id) => { return ( <ProductCard data={item} key={id} /> ) }) : null} </Slider> </div> </div> </>) } export default CozyAtHomeSlider
namespace PoolBox.PoolBox { @Serenity.Decorators.registerClass() @Serenity.Decorators.responsive() export class FileImportDialog extends Serenity.PropertyDialog<any, any> { protected form = new PoolBox.FileImportForm(this.idPrefix); protected fileFormatHandler: fileFormatHandler; protected fileFormatResponseHandler: fileFormatAndResponseHandler; constructor(fileFormatAndCheckHandler: fileFormatHandler, formatAndCheckResponseHandler: fileFormatAndResponseHandler) { super(); this.fileFormatHandler = fileFormatAndCheckHandler; this.fileFormatResponseHandler = formatAndCheckResponseHandler; } protected getDialogTitle(): string { return "File Import"; } protected getDialogButtons() { return [ { text: 'Import', click: () => { if (!this.validateBeforeSave()) return; console.info("uploadfileName" + this.form.FileName.value); if (this.form.FileName.value == null || Q.isEmptyOrNull(this.form.FileName.value.Filename)) { Q.notifyError("Please select a file"); return; } this.fileFormatHandler( { FileName: this.form.FileName.value.Filename, } , this.fileFormatResponseHandler , { async: true, onError: (response: Serenity.ServiceResponse) => Q.notifyError(response.Error.Message, response.Error.Code, { timeOut: 0, extendedTimeOut: 0, tapToDismiss: true }) } ); Q.blockUndo(); this.dialogClose(); }, }, { text: 'Cancel', click: () => this.dialogClose() } ]; } } interface fileFormatHandler { (request: Requests.FileImportRequest, onSuccess?: fileFormatAndResponseHandler, opt?: Q.ServiceOptions<any>): Responses.FileImportResponse; } interface fileFormatAndResponseHandler { (response: Responses.FileImportResponse): void; } }
<!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>CSS Website Layout</title> <style> * { box-sizing: border-box; } body { margin: 0; } /* Style the header */ .header { background-color: #f1f1f1; padding: 20px; text-align: center; } /* Style the top navigation bar */ .topnav { overflow: hidden; background-color: #333; } /* Style the topnav links */ .topnav a { float: left; display: block; color: #f2f2f2; text-align: center; padding: 14px 16px; text-decoration: none; } /* Change color on hover */ .topnav a:hover { background-color: #ddd; color: black; } </style> </head> <body> <div class="header"> <h1>Tutorial Web</h1> <p>Mempelajari Dasar Pembuatan Website</p> </div> <div class="topnav"> <a href="#">Home</a> <a href="#">JavaScript</a> <a href="#">PHP</a> <a href="buku_tamu.php">Buku Tamu</a> </div> <div class="row"> <div class="column"> <h2>&nbspHome</h2> <p>&nbspSelamat Datang di website tutorial belajar Website.</p> </div> </div> </body> </html>
import java.util.Random; class Drop { private String message; private boolean empty = true; public synchronized String take() { while (empty) { try { wait(); } catch (InterruptedException e) {} } empty = true; notifyAll(); return message; } public synchronized void put (String message) { while (!empty) { try { wait(); } catch (InterruptedException e) {} } this.message = message; this.empty = false; notifyAll(); } } class Producer implements Runnable { private Drop drop; public Producer (Drop drop) { this.drop = drop; } @Override public void run() { String[] importantInfos = { "Message One", "Message Two", "Message three", "Message Four", "Message Five", "DONE" }; Random random = new Random(); for (String importantInfo: importantInfos) { try { Thread.sleep (random.nextInt (4000)); } catch (InterruptedException e) { e.printStackTrace(); } drop.put (importantInfo); } } } class Consumer implements Runnable { private Drop drop; Consumer (Drop drop) { this.drop = drop; } @Override public void run() { Random random = new Random(); for (String message = drop.take(); !message.equals("DONE"); message = drop.take()) { System.out.printf ("MESSAGE RECEIVED: %s\n", message); try { Thread.sleep (random.nextInt(3000)); } catch (InterruptedException e) {} } } } public class ProducerConsumerExample { public static void main(String[] args) { Drop drop = new Drop(); new Thread(new Producer(drop)).start(); new Thread(new Consumer(drop)).start(); } }
package eu.zderadicka.mbs3; import static io.restassured.RestAssured.given; import static org.hamcrest.Matchers.allOf; import static org.hamcrest.Matchers.anyOf; import static org.hamcrest.Matchers.greaterThanOrEqualTo; import static org.hamcrest.Matchers.is; import static org.hamcrest.Matchers.lessThan; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertNotNull; import static org.junit.jupiter.api.Assertions.assertTrue; import static eu.zderadicka.mbs3.Utils.*; import java.util.List; import org.junit.jupiter.api.MethodOrderer; import org.junit.jupiter.api.Order; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.TestMethodOrder; import eu.zderadicka.mbs3.data.entity.Author; import eu.zderadicka.mbs3.data.entity.Ebook; import eu.zderadicka.mbs3.data.value.Genre; import eu.zderadicka.mbs3.data.value.Language; import eu.zderadicka.mbs3.rest.EbookResource; import io.quarkus.logging.Log; import io.quarkus.test.common.http.TestHTTPEndpoint; import io.quarkus.test.junit.QuarkusTest; import io.restassured.common.mapper.TypeRef; import jakarta.ws.rs.core.MediaType; import jakarta.ws.rs.core.Response; @QuarkusTest @TestHTTPEndpoint(EbookResource.class) @TestMethodOrder(MethodOrderer.OrderAnnotation.class) public class EBookResourceTest { private static Long ebookId; @Order(10) @Test public void testInitialEmptyList() { var result = given() .when() .get() .then() .statusCode(isSuccessNoRedirect()) .extract().body().as(List.class); assertEquals(0, result.size()); } @Order(20) @Test public void testCreateEbook() { Language language = new Language(); language.code = "cs"; language.name = "Czech"; language.id = 1L; language.version = 1; Ebook ebook = new Ebook(); ebook.setTitle("Testovaci kniha"); ebook.setBaseDir("Testovaci kniha"); ebook.setLanguage(language); var genre1 = new Genre(); genre1.id = 9L; var genre2 = new Genre(); genre2.id = 25L; var author = new Author(); author.setId(2L); ebook.addGenre(genre1, genre2); ebook.addAuthor(author); var response = given() .body(ebook) .and() .header("Content-Type", "application/json") .when() .post() .then(); final int EXPECTED_CODE = Response.Status.CREATED.getStatusCode(); if (response.extract().statusCode() != EXPECTED_CODE) { Log.warn("Response body: " + response.extract().body().asPrettyString()); } response.statusCode(is(EXPECTED_CODE)); Ebook createdEbook = response.extract().body().as(Ebook.class); assertNotNull(createdEbook); assertNotNull(createdEbook.getId()); ebookId = createdEbook.getId(); } @Order(25) @Test public void testModification() { Ebook ebook = given().when().get("/{id}", ebookId) .then().statusCode(is(200)).extract().body().as(Ebook.class); assertEquals(ebookId, ebook.getId()); var author = new Author(); author.setId(3L); ebook.addAuthor(author); ebook.setTitle(ebook.getTitle() + " 2"); given().body(ebook).and().header("Content-Type", MediaType.APPLICATION_JSON) .when().put("/{id}", ebookId) .then().statusCode(anyOf(is(200), is(204))); } @Order(30) @Test public void testExists() { List<Ebook> result = given() .when() .get() .then() .extract().body().as(new TypeRef<List<Ebook>>() { }); assertEquals(1, result.size(), "One ebook should exists"); var first = result.get(0); assertEquals("Testovaci kniha 2", first.getTitle()); assertEquals("Czech", first.getLanguage().name); assertEquals(2, first.getGenres().size()); assertEquals(2, first.getAuthors().size()); assertTrue(first.getModified().compareTo(first.getCreated()) > 0, "Modified timestamp is bigger then Created"); for (var genre : first.getGenres()) { if (genre.id == 9L) { assertEquals("Fantasy", genre.name); } else if (genre.id == 25L) { assertEquals("Science Fiction", genre.name); } } // Nefunguje v testech - asi diky transakcim // assertEquals(2, first.getVersion(), "After update version should increase"); } }
from django.db import models from .base_model import BaseModel from django.apps import apps class Language(BaseModel): name = models.CharField(max_length=255, unique=True) def __str__(self): return self.name def provider_count(self): # The provider_set is added dynamically, due to the # relation between the two. It's a Django thing and here # it prevents us from needing to make a circular import by # not needing to `from .provider import Provider` return self.provider_set.filter(is_public=True).count() class Meta: verbose_name = "Sprog" verbose_name_plural = "Sprog"
from dotenv import load_dotenv load_dotenv() ##loading all environment variables import streamlit as st import os import google.generativeai as genai from PIL import Image genai.configure(api_key=os.getenv("GOOGLE_API_KEY")) ##function to load Gemini Pro VISION Model and get reponses model=genai.GenerativeModel("gemini-pro-vision") def get_gemini_response(input,image): if input!="": response=model.generate_content([input,image]) else: response=model.generate_content(image) return response.text ##initialize stremlit app st.set_page_config(page_title="Gemini Image Demo") st.header("Gemini LLM Application") input=st.text_input("Input Promp:",key="input") uploaded_file=st.file_uploader("Choose an image....",type=["jpg","jpeg","png"]) image="" if uploaded_file is not None: image=Image.open(uploaded_file) st.image(image,caption="Uploaded Image.",use_column_width=True) submit=st.button("Tell me about the Image") ## if submit is clicked if submit: response=get_gemini_response(input,image) st.subheader("The Response is") st.write(response)
<template> <v-data-table :headers="headers" :items="tags" :items-per-page="-1" :search="search" :sort-by="[{ key: 'id', order: 'desc' }]" fixed-header height="90vh"> <template v-slot:top> <v-toolbar color="indigo-darken-2"> <v-toolbar-title color="indigo-darken-2">Tags</v-toolbar-title> <v-divider class="mx-4" inset vertical></v-divider> <v-text-field prepend-inner-icon="mdi-magnify" density="compact" label="Buscar tags..." variant="outlined" hide-details v-model="search" style="margin-right: 20px; max-width: 300px;"/> <v-dialog v-model="dialog" max-width="500px"> <template v-slot:activator="{ props }"> <v-btn prepend-icon="mdi-plus-circle-multiple" variant="tonal" elevation="10" color="white" v-bind="props"> Nuevo Tag </v-btn> </template> <v-card width="120%" style="transform: translateX(-20px);"> <v-card-title> <v-icon class="text-h5 margin" style="margin-top: -5px; margin-right: 8px;">{{ this.editedIndex === -1 ? "mdi-plus-circle-multiple" : "mdi-pencil-circle"}} </v-icon> <span class="text-h5 font-weight-bold"> {{ this.editedIndex === -1 ? "Nuevo Tag" : "Editar Tag" }} </span> </v-card-title> <v-card-text> <v-container> <v-row> <v-col cols="12"> <v-text-field v-model="editedItem.nombre" label="Nombre" prepend-inner-icon="mdi-rename-box" /> </v-col> <v-col cols="12"> <v-select :item-props="this.activoProps" v-model="this.activosSelected" clearable label="Activos" :items="this.activos" chips multiple prepend-inner-icon="mdi-package-variant-closed-plus" /> </v-col> </v-row> </v-container> </v-card-text> <v-card-actions> <v-spacer /> <v-btn color="indigo-darken-2" variant="text" @click="close">Cancelar</v-btn> <v-btn color="indigo-darken-2" variant="tonal" @click="save">Guardar</v-btn> </v-card-actions> </v-card> </v-dialog> <v-dialog v-model="dialogDelete" max-width="350px"> <v-card> <v-card-title> <div class="text-h5 font-weight-bold" style="white-space: pre-wrap; text-align: center;">¿Quieres eliminar este tag? </div> </v-card-title> <v-card-actions> <v-spacer /> <v-btn color="blue-darken-1" variant="text" @click="closeDelete">Cancelar</v-btn> <v-btn color="deep-orange-accent-4" variant="tonal" @click="deleteItemConfirm">ELIMINAR</v-btn> <v-spacer /> </v-card-actions> </v-card> </v-dialog> </v-toolbar> </template> <template v-slot:item.actions="{ item }"> <v-icon class="mr-3" size="small" @click="editItem(item)"> mdi-pencil </v-icon> <v-icon class="mr-3" size="small" @click="showActivosDialog(item)"> mdi-package </v-icon> <v-icon class="mr-3" size="small" @click="deleteItem(item)"> mdi-delete </v-icon> </template> </v-data-table> <template> <v-dialog v-model="imageDialog" style="width: 75%"> <v-card> <v-card-title>Imagen</v-card-title> <v-col cols="12"> <v-card-text> <v-img :src="imagePreview" /> </v-card-text> </v-col> <v-btn text="Ok" @click="this.imageDialog = false; this.imagePreview = null" /> </v-card> </v-dialog> </template> <template> <v-dialog v-model="activosDialog" width="100%"> <v-card> <v-card-title>Activos</v-card-title> <v-data-table :items="this.activosSelected" :headers="activosHeaders" :sort-by="[{ key: 'id', order: 'desc' }]"> <template v-slot:item.actions="{ item }"> <v-icon size="small" @click="showImageDialog(item)"> mdi-image </v-icon> </template> </v-data-table> <v-btn text="Ok" @click="this.activosDialog = false" /> </v-card> </v-dialog> </template> <v-template> <v-dialog v-model="this.errorDialog" max-width="300px"> <v-card color="red"> <v-card-title style="color: white;" class="text-wrap text-center">{{ errorMessage }}</v-card-title> <v-btn variant="tonal" @click="errorDialog = false; error = ''" style="color: white;">OK</v-btn> </v-card> </v-dialog> </v-template> </template> <script> import axios from "axios" import { store } from '../store' export default { data: () => ({ store: store(), dialog: false, dialogDelete: false, imageDialog: false, activosDialog: false, imagePreview: null, activosSelected: [], errorDialog: false, errorMessage: "", search: "", activos: [], tags: [], headers: [ { title: "Id", key: "id", sortable: true }, { title: 'Nombre', key: 'nombre' }, { title: 'Acciones', key: 'actions', sortable: false } ], activosHeaders: [ { title: 'Id', key: 'id', sortable: true }, { title: 'Serie', key: 'numSerie', sortable: false }, { title: 'Inventario', key: 'numInventario', sortable: false }, { title: 'Descripción', key: 'descripcion', sortable: false }, { title: 'Responsable', key: 'responsableId', sortable: true }, { title: 'Ubicación', key: 'ubicacionId', sortable: true }, { title: 'Imagen', key: 'actions' } ], activos: [], editedIndex: -1, editedItem: { id: null, nombre: null }, defaultItem: { id: null, nombre: null }, }), watch: { async dialog(val) { if (!val) { this.close() this.activosSelected = [] } }, dialogDelete(val) { val || this.closeDelete() }, }, beforeMount() { this.fetchTags() this.fetchActivos() }, methods: { async fetchTags() { try { const response = await axios.get("https://localhost:4000/tag", this.store.headers) this.tags = response.data } catch (error) { this.errorMessage = error.response.data || "Error de conexión." this.errorDialog = true } }, async fetchActivos() { try { const response = await axios.get("https://localhost:4000/activo/", this.store.headers) this.activos = response.data } catch (error) { this.errorMessage = error.response.data || "Error de conexión." this.errorDialog = true } }, async createTag() { try { const response = await axios.post("https://localhost:4000/tag/", this.editedItem, this.store.headers) this.tags.push(response.data.tag) this.activosSelected.forEach(async (activo) => await axios.post(`https://localhost:4000/tag/${response.data.tag.id}/activo/${activo.id}`, {}, this.store.headers)) } catch (error) { this.errorMessage = error.response.data || "Error de conexión." this.errorDialog = true } }, async editTag() { try { const response = await axios.put(`https://localhost:4000/tag/${this.editedItem.id}`, this.editedItem, this.store.headers) await Object.assign(this.tags[this.editedIndex], await response.data.tag) await axios.delete(`https://localhost:4000/tag/${response.data.tag.id}/activos`, this.store.headers) this.activosSelected.forEach(async (activo) => await axios.post(`https://localhost:4000/tag/${response.data.tag.id}/activo/${activo.id}`, {}, this.store.headers)) } catch (error) { this.errorMessage = error.response.data || "Error de conexión." this.errorDialog = true } }, async editItem(item) { try { this.editedIndex = this.tags.indexOf(item) this.editedItem = Object.assign({}, item) this.activosSelected = [] const activos = (await axios.get(`https://localhost:4000/tag/${item.id}/activos`, this.store.headers)).data activos.forEach((a) => this.activosSelected.push(this.activos.find((a2) => a.id == a2.id))) this.dialog = true } catch (error) { this.errorMessage = error.response.data || "Error de conexión." this.errorDialog = true } }, deleteItem(item) { this.editedIndex = this.tags.indexOf(item) this.editedItem = Object.assign({}, item) this.dialogDelete = true }, async deleteItemConfirm() { try { const response = await axios.delete(`https://localhost:4000/tag/${this.editedItem.id}`, this.store.headers) if (response.status == 200) this.tags.splice(this.editedIndex, 1) } catch (error) { this.errorMessage = error.response.data || "Error de conexión." this.errorDialog = true } this.closeDelete() }, close() { this.dialog = false this.$nextTick(() => { this.editedItem = Object.assign({}, this.defaultItem) this.editedIndex = -1 }) this.imagePreview = null }, closeDelete() { this.dialogDelete = false this.$nextTick(() => { this.editedItem = Object.assign({}, this.defaultItem) this.editedIndex = -1 }) }, async save() { if (this.editedIndex > -1) { await this.editTag() } else { await this.createTag() } this.close() }, async showImageDialog(item) { if (item.imagen) { console.log(new Blob([new Uint8Array(await item.imagen.data)], { type: "image/png" })) this.imagePreview = URL.createObjectURL(new Blob([new Uint8Array(await item.imagen.data)], { type: "image/png" })) } this.imageDialog = true }, async showActivosDialog(item) { try { this.activosSelected = (await axios.get(`https://localhost:4000/tag/${item.id}/activos`, this.store.headers)).data this.activosDialog = true } catch (error) { this.errorMessage = error.response.data || "Error de conexión." this.errorDialog = true } }, activoProps(item) { return { title: item.id, subtitle: `${item.numSerie} - ${item.descripcion}` } } }, } </script>
clear n=5; [m, b] = spare_matrix(n); x = transpose(repelem(0,n)); [new_x, steps] = jacobi(m,b,x); disp(new_x) disp(steps) % jacobi method for solving systems function [x, steps] = jacobi(a,b,x) absVal = inf; steps = 0; while absVal > 1e-6 for i = 1:length(a) selc = [a(i,1:i-1), a(i,i+1:length(a))]; x_selc = vertcat(x(1:i-1,1), x(i+1:length(x),1)); val = selc*x_selc; x(i,1) = (b(i,1) - val)/a(i,i); end steps = steps + 1; absVal = max(abs(b - x)); end end % Sparse matrix setup function [m,b] = spare_matrix(size) m = eye(size) * 3; for i = 1:size-1 m(i,i+1) = -1; m(i+1,i) = -1; end b = transpose(repelem(1,size)); for x = 1:size if mod(x,2) == 0 b(x, 1) = 1; else b(x, 1) = 2; end end end
--- permalink: nfs-admin/ldap-fast-bind-nsswitch-authentication-task.html sidebar: sidebar keywords: use, ldap, fast, bind, authentication, configure summary: 'A partire da ONTAP 9.11.1, è possibile sfruttare la funzionalità LDAP _fast bind_ (nota anche come _Concurrent BIND_) per richieste di autenticazione client più semplici e veloci. Per utilizzare questa funzionalità, il server LDAP deve supportare la funzionalità di associazione rapida' --- = Utilizza il binding rapido LDAP per l'autenticazione nsswitch :allow-uri-read: :icons: font :imagesdir: ../media/ [role="lead"] A partire da ONTAP 9.11.1, è possibile sfruttare la funzionalità LDAP _fast bind_ (nota anche come _Concurrent BIND_) per richieste di autenticazione client più semplici e veloci. Per utilizzare questa funzionalità, il server LDAP deve supportare la funzionalità di associazione rapida. .A proposito di questa attività Senza il binding rapido, ONTAP utilizza il binding semplice LDAP per autenticare gli utenti amministratori con il server LDAP. Con questo metodo di autenticazione, ONTAP invia un nome utente o di gruppo al server LDAP, riceve la password hash memorizzata e confronta il codice hash del server con il codice hash generato localmente dalla password utente. Se sono identici, ONTAP concede l'autorizzazione di accesso. Grazie alla funzionalità di associazione rapida, ONTAP invia solo le credenziali utente (nome utente e password) al server LDAP tramite una connessione sicura. Il server LDAP convalida quindi queste credenziali e richiede a ONTAP di concedere le autorizzazioni di accesso. Uno dei vantaggi di fast bind è che non è necessario che ONTAP supporti ogni nuovo algoritmo di hashing supportato dai server LDAP, perché l'hashing delle password viene eseguito dal server LDAP. link:https://docs.microsoft.com/en-us/openspecs/windows_protocols/ms-adts/dc4eb502-fb94-470c-9ab8-ad09fa720ea6["Scopri come utilizzare fast bind."^] È possibile utilizzare le configurazioni client LDAP esistenti per l'associazione rapida LDAP. Tuttavia, si consiglia vivamente di configurare il client LDAP per TLS o LDAPS; in caso contrario, la password viene inviata via cavo in testo normale. Per abilitare il binding rapido LDAP in un ambiente ONTAP, è necessario soddisfare i seguenti requisiti: * Gli utenti admin di ONTAP devono essere configurati su un server LDAP che supporti il fast bind. * ONTAP SVM deve essere configurato per LDAP nel database name Services switch (nsswitch). * Gli account di gruppo e utente amministratore di ONTAP devono essere configurati per l'autenticazione nsswitch utilizzando il collegamento rapido. .Fasi . Verificare con l'amministratore LDAP che il collegamento rapido LDAP sia supportato sul server LDAP. . Assicurarsi che le credenziali dell'utente amministratore di ONTAP siano configurate sul server LDAP. . Verificare che l'amministratore o l'SVM dei dati sia configurato correttamente per il binding rapido LDAP. + .. Per confermare che il server fast bind LDAP è elencato nella configurazione del client LDAP, immettere: + `vserver services name-service ldap client show` + link:https://docs.netapp.com/us-en/ontap/nfs-config/create-ldap-client-config-task.html["Informazioni sulla configurazione del client LDAP."] .. Per confermare `ldap` è una delle sorgenti configurate per nsswitch `passwd` database, inserire: + `vserver services name-service ns-switch show` + link:https://docs.netapp.com/us-en/ontap/nfs-config/configure-name-service-switch-table-task.html["Scopri di più sulla configurazione di nsswitch."] . Assicurarsi che gli utenti admin stiano autenticando con nsswitch e che l'autenticazione LDAP fast bind sia attivata nei propri account. + ** Per gli utenti esistenti, immettere `security login modify` e verificare le seguenti impostazioni dei parametri: + `-authentication-method nsswitch` + `-is-ldap-fastbind true` ** Per i nuovi utenti admin, vedere link:https://docs.netapp.com/us-en/ontap/authentication/grant-access-nis-ldap-user-accounts-task.html["Abilitare l'accesso all'account LDAP o NIS."]
"use client"; import { useEffect, useRef } from 'react'; import * as THREE from 'three'; const ThreeDAdaptiveModel = () => { const mountRef = useRef<HTMLDivElement | null>(null); useEffect(() => { const currentMountRef = mountRef.current; if (!currentMountRef) return; const scene = new THREE.Scene(); const camera = new THREE.PerspectiveCamera(75, window.innerWidth / window.innerHeight, 0.1, 1000); const renderer = new THREE.WebGLRenderer({ antialias: true, alpha: true }); // Set alpha to true for transparency renderer.setSize(window.innerWidth * 0.73, window.innerHeight); renderer.setClearColor(0x000000, 0); // Set clear color to transparent currentMountRef.appendChild(renderer.domElement); const geometry = new THREE.TorusKnotGeometry(10, 3, 100, 16); const material = new THREE.MeshBasicMaterial({ color: 0x0000ff, wireframe: true }); // Change color to blue const torusKnot = new THREE.Mesh(geometry, material); scene.add(torusKnot); camera.position.z = 50; const animate = () => { requestAnimationFrame(animate); torusKnot.rotation.x += 0.01; torusKnot.rotation.y += 0.01; renderer.render(scene, camera); }; animate(); return () => { if (currentMountRef) { currentMountRef.removeChild(renderer.domElement); } }; }, []); return <div ref={mountRef} style={{ width: '100%', height: '100vh' }}></div>; }; export default ThreeDAdaptiveModel;
package com.snakeGame; import java.awt.*; import java.awt.event.*; import java.util.*; import javax.swing.*; import javax.swing.Timer; public class GamePanel extends JPanel implements ActionListener{ private static final long serialVersionUID = 1L; static final int WIDTH =600; static final int HEIGHT =600; static final int UNIT_SIZE= 15; static final int GAME_UNITS = (WIDTH*HEIGHT)/UNIT_SIZE*UNIT_SIZE; // static final int DELAY = 100; final int x[] = new int[GAME_UNITS]; final int y[] = new int[GAME_UNITS]; int bodyParts = 5; int applesEaten; int appleX; int appleY; char direction= 'D'; boolean running = false; Timer timer; Random random; GamePanel() { random = new Random(); this.setPreferredSize(new Dimension(WIDTH, HEIGHT)); this.setBackground(Color.black); this.setFocusable(true); this.addKeyListener(new MyKeyAdapter()); startGame(); } public void startGame(){ newApple(); running = true; timer= new Timer(100,this); timer.start(); } @Override public void paintComponent(Graphics g){ super.paintComponent(g); draw(g); } public void move(){ for(int i = bodyParts; i > 0; i--){ x[i]=x[i-1]; y[i]=y[i-1]; } // switch(direction){ // case 'U': // y[0]=y[0]-UNIT_SIZE; // break; // case 'D': // y[0]=y[0]+UNIT_SIZE; // break; // case 'L': // x[0]=x[0]-UNIT_SIZE; // break; // case 'R': // x[0]=x[0]+UNIT_SIZE; // break; // } if (direction == 'L') { x[0] = x[0] - UNIT_SIZE; } else if (direction == 'R') { x[0] = x[0] + UNIT_SIZE; } else if (direction == 'U') { y[0] = y[0] - UNIT_SIZE; } else { y[0] = y[0] + UNIT_SIZE; } } public void checkApple(){ if(x[0] == appleX && y[0] == appleY){ bodyParts++; applesEaten++; newApple(); } } public void draw(Graphics g){ if(running){ // for(int i=0; i<HEIGHT/UNIT_SIZE; i++){ // this for loop is for to view grid of frame // g.drawLine(i*UNIT_SIZE, 0, i*UNIT_SIZE, HEIGHT); // g.drawLine(0, i*UNIT_SIZE, WIDTH, i*UNIT_SIZE); // } g.setColor(Color.MAGENTA); // this line is for apple g.fillOval(appleX, appleY, UNIT_SIZE, UNIT_SIZE); for(int i = 0; i < bodyParts; i++){ //this for loop is for snake if(i==0){ g.setColor(Color.lightGray); g.fillRoundRect(x[i], y[i], UNIT_SIZE, UNIT_SIZE, UNIT_SIZE, UNIT_SIZE); // this line is for head of snake } else{ g.setColor(Color.CYAN); g.fillRoundRect(x[i], y[i], UNIT_SIZE, UNIT_SIZE, UNIT_SIZE, UNIT_SIZE); // this line is for tail of snake } g.setColor(Color.white); g.setFont(new Font("Sans serif" , Font.ROMAN_BASELINE, 25)); FontMetrics metrics = getFontMetrics(g.getFont()); g.drawString("Score: " + applesEaten, (WIDTH - metrics.stringWidth("Score: " + applesEaten)) / 2, g.getFont().getSize()); } } else{ gameOver(g); } } public void newApple(){ appleX= random.nextInt((int)(WIDTH/UNIT_SIZE))*UNIT_SIZE; appleY= random.nextInt((int)(HEIGHT/UNIT_SIZE))*UNIT_SIZE; } public void checkCollisions(){ for(int i=bodyParts; i>0;i--){ //check if head touches body if(x[0] == x[i] && y[0]==y[i]){ running = false; } } // if(x[0]<0){ //check if head touches the left border // running = false; // } // // if(x[0]> SCREEN_WIDTH){ //check if head touches the right border // running = false; // } // // if(y[0]<0){ //check if head touches the top border // running = false; // } // if(y[0]> SCREEN_HEIGHT){ //check if head touches the bottom border // running = false; // } // if(x[0]<0 || x[0]> WIDTH || y[0] <0 || y[0]> HEIGHT ){ running = false; } if(!running){ timer.stop(); } } public void gameOver(Graphics g){ g.setColor(Color.red); g.setFont(new Font("Sans serif", Font.ROMAN_BASELINE, 25)); FontMetrics metrics = getFontMetrics(g.getFont()); g.drawString("Game Over", (WIDTH - metrics.stringWidth("Game Over")) / 2, HEIGHT/2); g.setColor(Color.white); g.setFont(new Font("Sans serif", Font.ROMAN_BASELINE, 25)); metrics = getFontMetrics(g.getFont()); g.drawString("Score: " + applesEaten, (WIDTH - metrics.stringWidth("Score: " + applesEaten)) / 2, g.getFont().getSize()); } @Override public void actionPerformed(ActionEvent arg0) { // TODO Auto-generated method stub if(running){ move(); checkApple(); checkCollisions(); } repaint(); } public class MyKeyAdapter extends KeyAdapter{ @Override public void keyPressed(KeyEvent e){ switch(e.getKeyCode()) { case KeyEvent.VK_LEFT: if (direction != 'R') { direction = 'L'; } break; case KeyEvent.VK_RIGHT: if (direction != 'L') { direction = 'R'; } break; case KeyEvent.VK_UP: if (direction != 'D') { direction = 'U'; } break; case KeyEvent.VK_DOWN: if (direction != 'U') { direction = 'D'; } break; } } } }
// ALU module lab3ALU(A, B, Function, ALUout, register); input [3:0] A, B; input [2:0] Function; input [7:0] register; output reg [7:0]ALUout; wire [3:0] w1; wire w2; RIPPLE_ADDER adder(.A(A), .B(B), .Cin(1'b0), .S(w1[3:0]), .Co(w2)); always @(*) begin case(Function[2:0]) // 0: A+B with adder 3'b000: begin ALUout[3:0]=w1[3:0]; ALUout[4] = w2; ALUout[7:5] = 1'b0; end // 1: A+B using "+" 3'b001: ALUout = A+B; // 2: Sign Extension 3'b010: ALUout[7:0] = { {4{B[3]}}, B[3:0] }; // 3: Output if... 3'b011: begin ALUout[7:1] = 1'b0; ALUout[0] = |{A, B}; end // 4: Output if... 3'b100: begin ALUout[7:1] = 1'b0; ALUout[0] = &{A, B}; end // 5: Left shift B by A bits 3'b101: ALUout = B * (2**A); // 6: AXB using "*" 3'b110: ALUout = A*B; // 7: Hold current value in the Register 3'b111: ALUout = register; default: ALUout[7:0]=1'b0; endcase end endmodule // Register module register (D, Reset_b, Clock, q); input [7:0] D; input Reset_b, Clock; output reg [7:0] q; always @(posedge Clock) // triggered every time clock rises begin if (Reset_b == 1'b0) // when reset_b is 0 q <= 0; // q set to 0 else // when not 0 q <= D; // value of d passes through to output q end endmodule // 7 Bit Hex Display Setup module hex_decoder(c, display); input [3:0] c; output [6:0] display; assign display[0] = ~((c[3]&~c[2]&~c[1]) | (~c[3] & c[2] & c[0]) | (c[3] & ~c[0]) | (~c[3] & c[1]) | (c[2] & c[1]) | (~c[2] & ~c[0])); assign display[1] = ~((~c[3] & ~c[1] & ~c[0]) | (~c[3] & c[1] & c[0]) | (c[3] & ~c[1] & c[0]) | (~c[2] & ~c[1]) | (~c[2] & ~c[0])); assign display[2] = ~((~c[3] & ~c[1]) | (~c[3] & c[0]) | (~c[1] & c[0]) | (~c[3] & c[2]) | (c[3] & ~c[2])); assign display[3] = ~((~c[3] & ~c[2] & ~c[0]) | (~c[2] & c[1] & c[0]) | (c[2] & ~c[1] & c[0]) | (c[2] & c[1] & ~c[0]) | (c[3] & ~c[1])); assign display[4] = ~((~c[2] & ~c[0]) | (c[1] & ~c[0]) | (c[3] & c[1]) | (c[3] & c[2])); assign display[5] = ~((~c[3] & c[2] & ~c[1]) | (~c[1] & ~c[0]) | (c[2] & ~c[0]) | (c[3] & ~c[2]) | (c[3] & c[1])); assign display[6] = ~((~c[3] & c[2] & ~c[1]) | (~c[2] & c[1]) | (c[1] & ~c[0]) | (c[3] & ~c[2]) | (c[3] & c[0])); endmodule // Full adder module full_adder(A, B, Ci, S, Co); input A, B, Ci; output S, Co; wire w1,w2,w3; xor H1(w1, A, B); xor H2(S, w1, Ci); and H3(w2, w1, Ci); and H4(w3, A, B); or H5(Co, w2, w3); endmodule // Ripple Adder module RIPPLE_ADDER(A, B,Cin, S, Co); input [3:0] A, B; input Cin; output [3:0] S; output Co; wire w1, w2, w3; full_adder u1(A[0], B[0], Cin,S[0], w1); full_adder u2(A[1], B[1], w1, S[1], w2); full_adder u3(A[2], B[2], w2, S[2], w3); full_adder u4(A[3], B[3], w3, S[3], Co); endmodule
// Copyright (c) 2017 Intel Corporation // // 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. #include "medium_test.hpp" #include "rdt/rdt_utils.hpp" #include "gtest/gtest.h" int main(int argc, char **argv) { testing::InitGoogleTest(&argc, argv); return RUN_ALL_TESTS(); } namespace rdt { using ::testing::_; using ::testing::Return; using ::testing::DoAll; using ::testing::SetArgumentPointee; using ::testing::SaveArgPointee; using ::testing::Invoke; #define CMT_METRICS_PER_CORE 2 #define MBM_LOCAL_METRICS_PER_CORE 1 #define MBM_REMOTE_METRICS_PER_CORE 2 #define CAP_METRICS 7 bool is_prefix(std::string const &prefix, std::string const &str); std::string extract_ns(const Plugin::Metric &metric); pqos_cap *mock_caps(std::vector<pqos_mon_event> events); pqos_cpuinfo *mock_cpu(unsigned num_cores); void mock_mon_poll(struct pqos_mon_data **groups, const unsigned num_groups); std::vector<Plugin::Metric> fixture_metrics(unsigned cpu_cores); void test_get_metric_types(PQOSMock *p_mock, pqos_cap *p_cap, unsigned num_cores, int expected_count); void test_collected_metrics_content(PQOSMock *p_mock, pqos_cap *p_cap, unsigned num_cores); void test_collect_no_cmt_cap(PQOSMock *p_mock, pqos_cap *p_cap, unsigned num_cores); void test_collect_err(PQOSMock *p_mock, pqos_cap *p_cap, unsigned num_cores, std::string const &expected_err); void emplace_per_core_metrics(rdt_metric_map *expected_values, double llc_size, int cpu_id); // Test PQOS init failure on collector construct TEST(CollectorContructor, TestPQOSInitFailure) { PQOSMock p_mock; // Checking PQOS init failure EXPECT_CALL(p_mock, pqos_init(_)).WillOnce(Return(PQOS_RETVAL_ERROR)); EXPECT_CALL(p_mock, pqos_cap_get(_, _)).Times(0); EXPECT_CALL(p_mock, pqos_fini()).Times(0); EXPECT_THROW({ auto rdt = new rdt::Collector(&p_mock); delete rdt; }, Plugin::PluginException); } // Test get PQOS capabilities failure on collector construct TEST(CollectorContructor, TestPQOSCapGetFailure) { PQOSMock p_mock; // Checking PQOS init failure EXPECT_CALL(p_mock, pqos_init(_)).WillOnce(Return(PQOS_RETVAL_OK)); EXPECT_CALL(p_mock, pqos_cap_get(_, _)).WillOnce(Return(PQOS_RETVAL_ERROR)); EXPECT_CALL(p_mock, pqos_fini()).Times(0); EXPECT_THROW({ auto rdt = new rdt::Collector(&p_mock); delete rdt; }, Plugin::PluginException); } // Test successfull collector construct TEST(CollectorContructor, TestConstructorSuccess) { PQOSMock p_mock; pqos_cap *p_cap = mock_caps(std::vector<pqos_mon_event>{}); pqos_cpuinfo *p_cpu = mock_cpu(1); // Checking PQOS init failure EXPECT_CALL(p_mock, pqos_init(_)).WillOnce(Return(PQOS_RETVAL_OK)); EXPECT_CALL(p_mock, pqos_cap_get(_, _)).WillOnce(DoAll(SetArgumentPointee<0>(p_cap), SetArgumentPointee<1>(p_cpu), Return(PQOS_RETVAL_OK))); EXPECT_CALL(p_mock, pqos_fini()).Times(1); EXPECT_NO_THROW({ auto rdt = new rdt::Collector(&p_mock); delete (rdt); }); delete (p_cpu); delete (p_cap); } // Test get metric types with CMT capability available TEST(GetMetricTypesTest, TestMetricCountMultiCpu) { PQOSMock p_mock; pqos_cap *p_cap; pqos_cpuinfo *p_cpu; p_cap = mock_caps(std::vector<pqos_mon_event>{PQOS_MON_EVENT_L3_OCCUP, PQOS_MON_EVENT_LMEM_BW, PQOS_MON_EVENT_RMEM_BW}); EXPECT_TRUE(rdt::has_cmt_capability(p_cap)); EXPECT_CALL(p_mock, pqos_init(_)).WillRepeatedly(Return(PQOS_RETVAL_OK)); int mts_per_core = CMT_METRICS_PER_CORE + MBM_LOCAL_METRICS_PER_CORE + MBM_REMOTE_METRICS_PER_CORE; test_get_metric_types(&p_mock, p_cap, 1, CAP_METRICS + 1 * mts_per_core); test_get_metric_types(&p_mock, p_cap, 2, CAP_METRICS + 2 * mts_per_core); test_get_metric_types(&p_mock, p_cap, 3, CAP_METRICS + 3 * mts_per_core); test_get_metric_types(&p_mock, p_cap, 4, CAP_METRICS + 4 * mts_per_core); delete (p_cap); } // test_get_metric_types takes capabilities and checks if expected_count of metrics is returned for provided num_cores void test_get_metric_types(PQOSMock *p_mock, pqos_cap *p_cap, unsigned num_cores, int expected_count) { auto p_cpu = mock_cpu(num_cores); EXPECT_CALL(*p_mock, pqos_cap_get(_, _)).WillOnce(DoAll(SetArgumentPointee<0>(p_cap), SetArgumentPointee<1>(p_cpu), Return(PQOS_RETVAL_OK))); rdt::Collector *rdt = new rdt::Collector(p_mock); rpc::ConfigMap map; Plugin::Config config(map); auto metric_types = rdt->get_metric_types(config); EXPECT_EQ(metric_types.size(), expected_count); EXPECT_CALL(*p_mock, pqos_fini()).Times(1); delete (rdt); delete (p_cpu); } // Test get metric types without CMT capability available TEST(GetMetricTypesTest, TestMetricCountMultiCpuNoCmtCap) { PQOSMock p_mock; pqos_cap *p_cap; pqos_cpuinfo *p_cpu; p_cap = mock_caps(std::vector<pqos_mon_event>{PQOS_MON_EVENT_LMEM_BW, PQOS_MON_EVENT_RMEM_BW}); EXPECT_FALSE(rdt::has_cmt_capability(p_cap)); EXPECT_CALL(p_mock, pqos_init(_)).WillRepeatedly(Return(PQOS_RETVAL_OK)); int mts_per_core = MBM_LOCAL_METRICS_PER_CORE + MBM_REMOTE_METRICS_PER_CORE; test_get_metric_types(&p_mock, p_cap, 1, CAP_METRICS + 1 * mts_per_core); test_get_metric_types(&p_mock, p_cap, 2, CAP_METRICS + 2 * mts_per_core); test_get_metric_types(&p_mock, p_cap, 3, CAP_METRICS + 3 * mts_per_core); test_get_metric_types(&p_mock, p_cap, 4, CAP_METRICS + 4 * mts_per_core); delete (p_cap); } // Test get metric types without any RDT capability available TEST(GetMetricTypesTest, TestMetricCountMultiCpuNoCaps) { PQOSMock p_mock; pqos_cap *p_cap; pqos_cpuinfo *p_cpu; p_cap = mock_caps(std::vector<pqos_mon_event>{}); EXPECT_FALSE(rdt::has_cmt_capability(p_cap)); EXPECT_CALL(p_mock, pqos_init(_)).WillRepeatedly(Return(PQOS_RETVAL_OK)); test_get_metric_types(&p_mock, p_cap, 1, CAP_METRICS); test_get_metric_types(&p_mock, p_cap, 2, CAP_METRICS); test_get_metric_types(&p_mock, p_cap, 3, CAP_METRICS); test_get_metric_types(&p_mock, p_cap, 4, CAP_METRICS); delete (p_cap); } // Test collecting metrics without CMT capability TEST(CollectMetricsTest, TestCollectNoCmtCap) { PQOSMock p_mock; pqos_cap *p_cap; p_cap = mock_caps(std::vector<pqos_mon_event>{}); EXPECT_FALSE(rdt::has_cmt_capability(p_cap)); EXPECT_FALSE(rdt::has_local_mbm_capability(p_cap)); EXPECT_FALSE(rdt::has_remote_mbm_capability(p_cap)); EXPECT_CALL(p_mock, pqos_init(_)).WillRepeatedly(Return(PQOS_RETVAL_OK)); EXPECT_CALL(p_mock, pqos_mon_reset()).WillRepeatedly(Return(PQOS_RETVAL_OK)); EXPECT_CALL(p_mock, pqos_mon_start(_, _, _, _, _)).WillRepeatedly(Return(PQOS_RETVAL_OK)); EXPECT_CALL(p_mock, pqos_mon_stop(_)).WillRepeatedly(Return(PQOS_RETVAL_OK)); EXPECT_CALL(p_mock, pqos_mon_poll(_, _)).WillRepeatedly(Return(PQOS_RETVAL_OK)); test_collect_no_cmt_cap(&p_mock, p_cap, 1); test_collect_no_cmt_cap(&p_mock, p_cap, 2); test_collect_no_cmt_cap(&p_mock, p_cap, 3); test_collect_no_cmt_cap(&p_mock, p_cap, 4); delete (p_cap); } // test_collect_no_cmt_cap takes capabilities and checks if expected_count of metrics is collected for provided num_cores // This test expects that CMT capabilities are not available void test_collect_no_cmt_cap(PQOSMock *p_mock, pqos_cap *p_cap, unsigned num_cores) { auto p_cpu = mock_cpu(num_cores); EXPECT_CALL(*p_mock, pqos_cap_get(_, _)).WillRepeatedly(DoAll(SetArgumentPointee<0>(p_cap), SetArgumentPointee<1>(p_cpu), Return(PQOS_RETVAL_OK))); rdt::Collector *rdt = new rdt::Collector(p_mock); auto metrics = fixture_metrics(num_cores); EXPECT_NO_THROW(rdt->collect_metrics(metrics)); EXPECT_EQ(metrics.size(), CAP_METRICS); EXPECT_CALL(*p_mock, pqos_fini()).Times(1); delete (rdt); delete (p_cpu); } // Test collecting metrics with pqos_mon_start failure TEST(CollectMetricsTest, TestCollectMonStartErr) { PQOSMock p_mock; pqos_cap *p_cap; p_cap = mock_caps(std::vector<pqos_mon_event>{PQOS_MON_EVENT_L3_OCCUP}); EXPECT_TRUE(rdt::has_cmt_capability(p_cap)); EXPECT_CALL(p_mock, pqos_init(_)).WillRepeatedly(Return(PQOS_RETVAL_OK)); EXPECT_CALL(p_mock, pqos_mon_reset()).WillRepeatedly(Return(PQOS_RETVAL_OK)); EXPECT_CALL(p_mock, pqos_mon_poll(_, _)).WillRepeatedly(DoAll(Invoke(mock_mon_poll), Return(PQOS_RETVAL_OK))); EXPECT_CALL(p_mock, pqos_mon_start(_, _, _, _, _)).WillOnce(Return(PQOS_RETVAL_ERROR)); test_collect_err(&p_mock, p_cap, 1, "Could not start PQoS monitoring"); EXPECT_CALL(p_mock, pqos_mon_start(_, _, _, _, _)).WillOnce(Return(PQOS_RETVAL_ERROR)); test_collect_err(&p_mock, p_cap, 2, "Could not start PQoS monitoring"); EXPECT_CALL(p_mock, pqos_mon_start(_, _, _, _, _)).WillOnce(Return(PQOS_RETVAL_ERROR)); test_collect_err(&p_mock, p_cap, 3, "Could not start PQoS monitoring"); EXPECT_CALL(p_mock, pqos_mon_start(_, _, _, _, _)).WillOnce(Return(PQOS_RETVAL_ERROR)); test_collect_err(&p_mock, p_cap, 4, "Could not start PQoS monitoring"); delete (p_cap); } // Test collecting metrics with pqos_mon_reset failure TEST(CollectMetricsTest, TestCollectMonResetErr) { PQOSMock p_mock; pqos_cap *p_cap; p_cap = mock_caps(std::vector<pqos_mon_event>{PQOS_MON_EVENT_L3_OCCUP}); EXPECT_TRUE(rdt::has_cmt_capability(p_cap)); EXPECT_CALL(p_mock, pqos_init(_)).WillRepeatedly(Return(PQOS_RETVAL_OK)); EXPECT_CALL(p_mock, pqos_mon_reset()).WillOnce(Return(PQOS_RETVAL_ERROR)); test_collect_err(&p_mock, p_cap, 1, "Could not reset PQoS RMIDs"); EXPECT_CALL(p_mock, pqos_mon_reset()).WillOnce(Return(PQOS_RETVAL_ERROR)); test_collect_err(&p_mock, p_cap, 2, "Could not reset PQoS RMIDs"); EXPECT_CALL(p_mock, pqos_mon_reset()).WillOnce(Return(PQOS_RETVAL_ERROR)); test_collect_err(&p_mock, p_cap, 3, "Could not reset PQoS RMIDs"); EXPECT_CALL(p_mock, pqos_mon_reset()).WillOnce(Return(PQOS_RETVAL_ERROR)); test_collect_err(&p_mock, p_cap, 4, "Could not reset PQoS RMIDs"); delete (p_cap); } // test_collect_no_cmt_cap takes capabilities and num_cores and checks if expected error message was raised void test_collect_err(PQOSMock *p_mock, pqos_cap *p_cap, unsigned num_cores, std::string const &expected_err) { auto p_cpu = mock_cpu(num_cores); EXPECT_CALL(*p_mock, pqos_cap_get(_, _)).WillRepeatedly(DoAll(SetArgumentPointee<0>(p_cap), SetArgumentPointee<1>(p_cpu), Return(PQOS_RETVAL_OK))); rdt::Collector *rdt = new rdt::Collector(p_mock); auto metrics = fixture_metrics(num_cores); EXPECT_THROW(rdt->collect_metrics(metrics), Plugin::PluginException); EXPECT_CALL(*p_mock, pqos_fini()).Times(1); delete (rdt); delete (p_cpu); } // Test collecting metrics successfull TEST(CollectMetricsTest, TestCollectSuccess) { PQOSMock p_mock; pqos_cap *p_cap; pqos_cpuinfo *p_cpu; p_cap = mock_caps(std::vector<pqos_mon_event>{PQOS_MON_EVENT_L3_OCCUP, PQOS_MON_EVENT_RMEM_BW, PQOS_MON_EVENT_LMEM_BW}); EXPECT_TRUE(rdt::has_cmt_capability(p_cap)); EXPECT_CALL(p_mock, pqos_init(_)).WillRepeatedly(Return(PQOS_RETVAL_OK)); EXPECT_CALL(p_mock, pqos_mon_reset()).WillRepeatedly(Return(PQOS_RETVAL_OK)); EXPECT_CALL(p_mock, pqos_mon_start(_, _, _, _, _)).WillRepeatedly(Return(PQOS_RETVAL_OK)); test_collected_metrics_content(&p_mock, p_cap, 1); test_collected_metrics_content(&p_mock, p_cap, 2); test_collected_metrics_content(&p_mock, p_cap, 3); test_collected_metrics_content(&p_mock, p_cap, 4); delete (p_cap); } // test_collected_metrics_content comapres collected data with expected values void test_collected_metrics_content(PQOSMock *p_mock, pqos_cap *p_cap, unsigned num_cores) { rdt_metric_map expected_values; // Expected capabilities values const double cache_way_size = 200 * num_cores; const double cache_ways_count = 201 * num_cores; const double llc_size = 202 * num_cores; // Global metrics independent from CPU core number expected_values.emplace("/intel/rdt/capabilities/cmt_capability", rdt_metric_data{expected_value : 1, is_float: false}); expected_values.emplace("/intel/rdt/capabilities/mbm_local_monitoring", rdt_metric_data{expected_value : 1, is_float: false}); expected_values.emplace("/intel/rdt/capabilities/mbm_remote_monitoring", rdt_metric_data{expected_value : 1, is_float: false}); expected_values.emplace("/intel/rdt/capabilities/cache_allocation", rdt_metric_data{expected_value : 0, is_float: false}); expected_values.emplace("/intel/rdt/capabilities/llc_size", rdt_metric_data{expected_value : llc_size, is_float: false}); expected_values.emplace("/intel/rdt/capabilities/cache_ways_count", rdt_metric_data{expected_value : cache_ways_count, is_float: false}); expected_values.emplace("/intel/rdt/capabilities/cache_way_size", rdt_metric_data{expected_value : cache_way_size, is_float: false}); // Mocks auto p_cpu = mock_cpu(num_cores); EXPECT_CALL(*p_mock, pqos_cap_get(_, _)).WillRepeatedly(DoAll(SetArgumentPointee<0>(p_cap), SetArgumentPointee<1>(p_cpu), Return(PQOS_RETVAL_OK))); EXPECT_CALL(*p_mock, pqos_mon_poll(_, _)).WillOnce(DoAll(Invoke(mock_mon_poll), Return(PQOS_RETVAL_OK))); // Start collecting all metrics rdt::Collector *rdt = new rdt::Collector(p_mock); auto metrics = fixture_metrics(num_cores); EXPECT_NO_THROW(rdt->collect_metrics(metrics)); // Fill expected values map with per-core metric values for (int cpu_id = 0; cpu_id < num_cores; cpu_id++) { emplace_per_core_metrics(&expected_values, llc_size, cpu_id); } // Checking if collected metrics values equal expected ones for (int i = 0; i < metrics.size(); i++) { auto metric_ns = extract_ns(metrics[i]); auto tested_ns = expected_values.find(metric_ns) != expected_values.end(); EXPECT_TRUE(tested_ns); if (tested_ns) { if (expected_values[metric_ns].is_float) EXPECT_EQ(expected_values[metric_ns].expected_value, metrics[i].get_float64_data()); else EXPECT_EQ(expected_values[metric_ns].expected_value, metrics[i].get_int_data()); } } EXPECT_CALL(*p_mock, pqos_mon_stop(_)).Times(num_cores); EXPECT_CALL(*p_mock, pqos_fini()).Times(1); delete (rdt); delete (p_cpu); } // emplace_per_core_metrics fills expected metric value map with per-core metrics void emplace_per_core_metrics(rdt_metric_map *expected_values, double llc_size, int cpu_id) { // Expected per-core values const double cmt_data = (100 * (cpu_id + 1)); const double mbm_data_local = (101 * (cpu_id + 1)); const double mbm_data_remote = (102 * (cpu_id + 1)); const double mbm_data_total = (103 * (cpu_id + 1)); const double llc_percentage = (cmt_data / llc_size) * 100; // List of per-core metrics and expected values auto cpu_id_entry = std::to_string(cpu_id); expected_values->emplace("/intel/rdt/llc_occupancy/" + cpu_id_entry + "/bytes", rdt_metric_data{expected_value : cmt_data, is_float: true}); expected_values->emplace("/intel/rdt/llc_occupancy/" + cpu_id_entry + "/percentage", rdt_metric_data{expected_value : llc_percentage, is_float: true}); expected_values->emplace("/intel/rdt/memory_bandwidth/local/" + cpu_id_entry + "/bytes", rdt_metric_data{expected_value : mbm_data_local, is_float: true}); expected_values->emplace("/intel/rdt/memory_bandwidth/remote/" + cpu_id_entry + "/bytes", rdt_metric_data{expected_value : mbm_data_remote, is_float: true}); expected_values->emplace("/intel/rdt/memory_bandwidth/total/" + cpu_id_entry + "/bytes", rdt_metric_data{expected_value : mbm_data_total, is_float: true}); } bool is_prefix(std::string const &prefix, std::string const &str) { auto res = std::mismatch(prefix.begin(), prefix.end(), str.begin()); return res.first == prefix.end(); } // Extract ns entries and return as single string value std::string extract_ns(const Plugin::Metric &metric) { std::string ns_str; for (auto const &elem : metric.ns()) { ns_str += "/" + elem.value; } return ns_str; } // Mock capabilities object pqos_cap *mock_caps(std::vector<pqos_mon_event> events) { // Mock capability list auto pqosCapMock = new pqos_capability; pqosCapMock->type = PQOS_CAP_TYPE_MON; pqosCapMock->u.mon = (pqos_cap_mon *)malloc(sizeof(pqos_cap_mon) + sizeof(pqos_monitor) * events.size()); pqosCapMock->u.mon->num_events = events.size(); for (int i = 0; i < pqosCapMock->u.mon->num_events; i++) pqosCapMock->u.mon->events[i] = {events[i]}; // Assign capability list to capabilities object auto result = (pqos_cap *)malloc(sizeof(pqos_cap) + sizeof(pqos_capability)); result->num_cap = 1; result->capabilities[0] = *pqosCapMock; delete pqosCapMock; return result; } // Mock CPU object pqos_cpuinfo *mock_cpu(unsigned num_cores) { auto mockCpuInfo = new pqos_cpuinfo; mockCpuInfo->num_cores = num_cores; mockCpuInfo->l3.way_size = 200 * num_cores; mockCpuInfo->l3.num_ways = 201 * num_cores; mockCpuInfo->l3.total_size = 202 * num_cores; return mockCpuInfo; } // Mock monitor group data void mock_mon_poll(struct pqos_mon_data **groups, const unsigned num_groups) { for (unsigned i = 0; i < num_groups; i++) { groups[i]->cores = new unsigned(i); groups[i]->poll_ctx = new pqos_mon_poll_ctx; groups[i]->values.llc = 100 * (i + 1); groups[i]->values.mbm_local_delta = 101 * (i + 1); groups[i]->values.mbm_remote_delta = 102 * (i + 1); groups[i]->values.mbm_total_delta = 103 * (i + 1); } } // Mock metrics to collect_metrics std::vector<Plugin::Metric> fixture_metrics(unsigned cpu_cores) { auto metrics = std::vector<Plugin::Metric>{ Plugin::Metric(rdt::cmt_capability_ns, "bool", "This CPU supports LLC Cache Monitoring."), Plugin::Metric(rdt::mbm_local_monitoring_ns, "bool", "This CPU supports Local Memory Bandwidth Monitoring."), Plugin::Metric(rdt::llc_size_ns, "bytes", "LLC Size."), Plugin::Metric(rdt::cache_ways_count_ns, "bytes", "Number of cache ways in Last Level Cache."), Plugin::Metric(rdt::cache_way_size_ns, "bytes", "Size of cache way in Last Level Cache.")}; for (unsigned i = 0; i < cpu_cores; i++) { Plugin::Metric::NamespaceElement dynamicCoreIdElement; dynamicCoreIdElement.value = "*"; dynamicCoreIdElement.name = "core_id"; dynamicCoreIdElement.description = "Cache occupancy for core_id"; std::string core_id = std::to_string(i); Plugin::Metric llc_occupancy_bytes( {{"intel"}, {"rdt"}, {"llc_occupancy"}, dynamicCoreIdElement, {"bytes"}}, "bytes", "Total LLC Occupancy of CPU " + core_id + " in bytes."); Plugin::Metric llc_occupancy_percentage( {{"intel"}, {"rdt"}, {"llc_occupancy"}, dynamicCoreIdElement, {"percentage"}}, "percentage", "Total LLC Occupancy of CPU " + core_id + " in bytes."); Plugin::Metric local_membw_usage_bytes( {{"intel"}, {"rdt"}, {"memory_bandwidth"}, {"local"}, dynamicCoreIdElement, {"bytes"}}, "bytes", "Local memory bandwidth usage for CPU " + core_id + " in bytes."); Plugin::Metric remote_membw_usage_bytes( {{"intel"}, {"rdt"}, {"memory_bandwidth"}, {"remote"}, dynamicCoreIdElement, {"bytes"}}, "bytes", "Remote memory bandwidth usage for CPU " + core_id + " in bytes."); Plugin::Metric total_membw_usage_bytes( {{"intel"}, {"rdt"}, {"memory_bandwidth"}, {"total"}, dynamicCoreIdElement, {"bytes"}}, "bytes", "Total memory bandwidth usage for CPU " + core_id + " in bytes."); metrics.push_back(llc_occupancy_bytes); metrics.push_back(llc_occupancy_percentage); metrics.push_back(local_membw_usage_bytes); metrics.push_back(remote_membw_usage_bytes); metrics.push_back(total_membw_usage_bytes); } return metrics; } } // namespace rdt
import 'dart:async'; import 'dart:io'; import 'package:langchain/langchain.dart'; final class FileRetrieverTool extends Tool { FileRetrieverTool() : super( name: 'file_retriever', description: 'Useful for getting the file. ' 'The input to this tool should be a valid file path.', ); @override Future<String> runInternalString(final String toolInput) async { try { final file = File(toolInput); if (await file.exists()) { final contents = await file.readAsString(); return "File contents:\n$contents"; } else { return "File does not exist."; } } catch (e) { return "An error occurred: ${e.toString()}"; } } }
<script setup> import axios from 'axios'; import {onMounted, reactive, ref} from 'vue'; import { useToastr } from '@/toastr.js'; //import { useToastr } from '../../toastr.js'; import { useAuthUserStore } from '../../stores/AuthUserStore.js'; const authUserStore = useAuthUserStore(); const toastr = useToastr(); /*const form = ref({ name: '', email: '', role: '', role_name: '', avatar: '', }); const getUser = () => { axios.get('/api/profile') .then((response) => { form.value = response.data; }) };*/ const errors = ref(); const updateProfile = () => { //axios.put('/api/profile', form.value) axios.put('/api/profile', { name: authUserStore.user.name, email: authUserStore.user.email, role: authUserStore.user.role, }) .then((response) => { toastr.success('Profile updated successfully.') }) .catch((error) => { if (error.response && error.response.status === 422) { errors.value = error.response.data.errors; } }); }; const changePasswordForm = reactive({ currentPassword: '', password: '', passwordConfirmation: '', }); const handleChangePassword = () => { errors.value = ''; axios.post('/api/change-user-password', changePasswordForm) .then((response) => { toastr.success(response.data.message); for (const field in changePasswordForm) { changePasswordForm[field] = ''; } }) .catch((error) => { if (error.response && error.response.status === 422) { errors.value = error.response.data.errors; } }); }; const fileInput = ref(null); const openFileInput = () => { fileInput.value.click(); }; //const profilePictureUrl = ref(null); const handleFileChange = (event) => { const file = event.target.files[0]; //profilePictureUrl.value = URL.createObjectURL(file); authUserStore.user.avatar = URL.createObjectURL(file); //console.log(profilePictureUrl.value, file, typeof file); const formData = new FormData(); formData.append('profile_picture', file); //console.log(formData); axios.post('/api/upload-profile-image', formData) .then((response) => { toastr.success('Image uploaded successfully.'); }); }; /*onMounted(() => { getUser(); });*/ </script> <template> <div class="content-header"> <div class="container-fluid"> <div class="row mb-2"> <div class="col-sm-6"> <h1 class="m-0">Profile</h1> </div> <div class="col-sm-6"> <ol class="breadcrumb float-sm-right"> <li class="breadcrumb-item"><a href="#">Home</a></li> <li class="breadcrumb-item active">Profile</li> </ol> </div> </div> </div> </div> <div class="content"> <div class="container-fluid"> <div class="row"> <div class="col-md-3"> <div class="card card-primary card-outline"> <div class="card-body box-profile"> <div class="text-center"> <input @change="handleFileChange" ref="fileInput" type="file" class="d-none"> <!-- :src="profilePictureUrl ? profilePictureUrl : authUserStore.user.avatar" alt="User profile pic" --> <img @click="openFileInput" class="profile-user-img img-circle" :src="authUserStore.user.avatar" alt="User profile pic" > </div> <h3 class="profile-username text-center">{{ authUserStore.user.name }}</h3> <!--<p class="text-muted text-center">{{ form.role }}</p>--> <!--<p class="text-muted text-center">{{ form.role_name }}</p>--> <p class="text-muted text-center">{{ authUserStore.user.role }}</p> </div> </div> </div> <div class="col-md-9"> <div class="card"> <div class="card-header p-2"> <ul class="nav nav-pills"> <li class="nav-item"><a class="nav-link active" href="#profile" data-toggle="tab"><i class="fa fa-user mr-1"></i> Edit Profile</a></li> <li class="nav-item"><a class="nav-link" href="#changePassword" data-toggle="tab"><i class="fa fa-key mr-1"></i> Change Password</a></li> </ul> </div> <div class="card-body"> <div class="tab-content"> <div class="tab-pane active" id="profile"> <form @submit.prevent="updateProfile()" class="form-horizontal"> <div class="form-group row"> <label for="inputName" class="col-sm-2 col-form-label">Name</label> <div class="col-sm-10"> <input v-model="authUserStore.user.name" type="text" class="form-control" id="inputName" placeholder="Name"> <span class="text-danger text-sm" v-if="errors && errors.name">{{ errors.name[0]}}</span> </div> </div> <div class="form-group row"> <label for="inputEmail" class="col-sm-2 col-form-label">Email</label> <div class="col-sm-10"> <input v-model="authUserStore.user.email" type="email" class="form-control " id="inputEmail" placeholder="Email"> <span class="text-danger text-sm" v-if="errors && errors.email">{{ errors.email[0]}}</span> </div> </div> <div class="form-group row"> <div class="offset-sm-2 col-sm-10"> <button type="submit" class="btn btn-success"><i class="fa fa-save mr-1"></i> Save Changes</button> </div> </div> </form> </div> <div class="tab-pane" id="changePassword"> <form @submit.prevent="handleChangePassword" class="form-horizontal"> <div class="form-group row"> <label for="currentPassword" class="col-sm-3 col-form-label">Current Password</label> <div class="col-sm-9"> <input v-model="changePasswordForm.currentPassword" type="password" class="form-control " id="currentPassword" placeholder="Current Password"> <span class="text-danger text-sm" v-if="errors && errors.current_password">{{ errors.current_password[0]}}</span> </div> </div> <div class="form-group row"> <label for="newPassword" class="col-sm-3 col-form-label">New Password</label> <div class="col-sm-9"> <input v-model="changePasswordForm.password" type="password" class="form-control " id="newPassword" placeholder="New Password"> <span class="text-danger text-sm" v-if="errors && errors.password">{{ errors.password[0]}}</span> </div> </div> <div class="form-group row"> <label for="passwordConfirmation" class="col-sm-3 col-form-label">Confirm New Password</label> <div class="col-sm-9"> <input v-model="changePasswordForm.passwordConfirmation" type="password" class="form-control " id="passwordConfirmation" placeholder="Confirm New Password"> </div> </div> <div class="form-group row"> <div class="offset-sm-3 col-sm-9"> <button type="submit" class="btn btn-success"><i class="fa fa-save mr-1"></i> Save Changes</button> </div> </div> </form> </div> </div> </div> </div> </div> </div> </div> </div> </template> <style scoped> .profile-user-img:hover { background-color: #0c84ff; cursor: pointer; } </style>
import { ReactNode, createContext, useReducer } from "react"; import { TopMovieState, topMovieReducer } from "../reducers/TopMovieReducer"; import axios from "axios"; import { TopMovieActionType } from "../reducers/types"; import topMoviesInfo from "../api/getTopMovies"; const { GET_TOP_MOVIES, TOGGLE_TOP_MOVIE_WATCHED } = TopMovieActionType; interface TopMovieContextProps { children: ReactNode; } interface TopMovieContextDefault { topMovies: TopMovieState; getTopMovies: () => Promise<void>; // or: () => void toggleWatched: (id: string) => void; } const topMoviesDefault: TopMovieState = []; export const TopMovieContext = createContext<TopMovieContextDefault>({ topMovies: topMoviesDefault, getTopMovies: () => Promise.resolve(void 0), // then here it can be () => null or () => {} toggleWatched: (id: string) => {}, }); const TopMovieContextProvider = ({ children }: TopMovieContextProps) => { const [topMovies, dispatch] = useReducer(topMovieReducer, topMoviesDefault); // get top movies from api const getTopMovies = async () => { const topMovies = await Promise.all(topMoviesInfo); dispatch({ type: GET_TOP_MOVIES, payload: topMovies.map((topMovie) => ({ ...topMovie.data, Watched: false, })), }); }; //toggle watch const toggleWatched = (imdbID: string) => dispatch({ type: TOGGLE_TOP_MOVIE_WATCHED, payload: imdbID }); const topMovieContextData = { topMovies, getTopMovies, toggleWatched, }; return ( <TopMovieContext.Provider value={topMovieContextData}> {children} </TopMovieContext.Provider> ); }; export default TopMovieContextProvider;
//SPDX-License-Identifier: MIT pragma solidity >=0.8.11 <0.9.0; /** * @title Allows accounts to delegate collateral to a pool. * @dev Delegation updates the account's position in the vault that corresponds to the associated pool and collateral type pair. * @dev A pool contains one vault for each collateral type it supports, and vaults are not shared between pools. */ interface IVaultModule { /** * @notice Thrown when attempting to delegate collateral to a vault with a leverage amount that is not supported by the system. */ error InvalidLeverage(uint256 leverage); /** * @notice Thrown when attempting to delegate collateral to a market whose capacity is locked. */ error CapacityLocked(uint256 marketId); /** * @notice Thrown when the specified new collateral amount to delegate to the vault equals the current existing amount. */ error InvalidCollateralAmount(); /** * @notice Emitted when {sender} updates the delegation of collateral in the specified liquidity position. * @param accountId The id of the account whose position was updated. * @param poolId The id of the pool in which the position was updated. * @param collateralType The address of the collateral associated to the position. * @param amount The new amount of the position, denominated with 18 decimals of precision. * @param leverage The new leverage value of the position, denominated with 18 decimals of precision. * @param sender The address that triggered the update of the position. */ event DelegationUpdated( uint128 indexed accountId, uint128 indexed poolId, address collateralType, uint256 amount, uint256 leverage, address indexed sender ); /** * @notice Updates an account's delegated collateral amount for the specified pool and collateral type pair. * @param accountId The id of the account associated with the position that will be updated. * @param poolId The id of the pool associated with the position. * @param collateralType The address of the collateral used in the position. * @param amount The new amount of collateral delegated in the position, denominated with 18 decimals of precision. * @param leverage The new leverage amount used in the position, denominated with 18 decimals of precision. * * Requirements: * * - `msg.sender` must be the owner of the account, have the `ADMIN` permission, or have the `DELEGATE` permission. * - If increasing the amount delegated, it must not exceed the available collateral (`getAccountAvailableCollateral`) associated with the account. * - If decreasing the amount delegated, the liquidity position must have a collateralization ratio greater than the target collateralization ratio for the corresponding collateral type. * * Emits a {DelegationUpdated} event. */ function delegateCollateral( uint128 accountId, uint128 poolId, address collateralType, uint256 amount, uint256 leverage ) external; /** * @notice Returns the collateralization ratio of the specified liquidity position. If debt is negative, this function will return 0. * @dev Call this function using `callStatic` to treat it as a view function. * @dev The return value is a percentage with 18 decimals places. * @param accountId The id of the account whose collateralization ratio is being queried. * @param poolId The id of the pool in which the account's position is held. * @param collateralType The address of the collateral used in the queried position. * @return ratioD18 The collateralization ratio of the position (collateral / debt), denominated with 18 decimals of precision. */ function getPositionCollateralRatio( uint128 accountId, uint128 poolId, address collateralType ) external returns (uint256 ratioD18); /** * @notice Returns the debt of the specified liquidity position. Credit is expressed as negative debt. * @dev This is not a view function, and actually updates the entire debt distribution chain. * @dev Call this function using `callStatic` to treat it as a view function. * @param accountId The id of the account being queried. * @param poolId The id of the pool in which the account's position is held. * @param collateralType The address of the collateral used in the queried position. * @return debtD18 The amount of debt held by the position, denominated with 18 decimals of precision. */ function getPositionDebt( uint128 accountId, uint128 poolId, address collateralType ) external returns (int256 debtD18); /** * @notice Returns the amount and value of the collateral associated with the specified liquidity position. * @dev Call this function using `callStatic` to treat it as a view function. * @dev collateralAmount is represented as an integer with 18 decimals. * @dev collateralValue is represented as an integer with the number of decimals specified by the collateralType. * @param accountId The id of the account being queried. * @param poolId The id of the pool in which the account's position is held. * @param collateralType The address of the collateral used in the queried position. * @return collateralAmountD18 The amount of collateral used in the position, denominated with 18 decimals of precision. * @return collateralValueD18 The value of collateral used in the position, denominated with 18 decimals of precision. */ function getPositionCollateral( uint128 accountId, uint128 poolId, address collateralType ) external view returns (uint256 collateralAmountD18, uint256 collateralValueD18); /** * @notice Returns all information pertaining to a specified liquidity position in the vault module. * @param accountId The id of the account being queried. * @param poolId The id of the pool in which the account's position is held. * @param collateralType The address of the collateral used in the queried position. * @return collateralAmountD18 The amount of collateral used in the position, denominated with 18 decimals of precision. * @return collateralValueD18 The value of the collateral used in the position, denominated with 18 decimals of precision. * @return debtD18 The amount of debt held in the position, denominated with 18 decimals of precision. * @return collateralizationRatioD18 The collateralization ratio of the position (collateral / debt), denominated with 18 decimals of precision. **/ function getPosition( uint128 accountId, uint128 poolId, address collateralType ) external returns ( uint256 collateralAmountD18, uint256 collateralValueD18, int256 debtD18, uint256 collateralizationRatioD18 ); /** * @notice Returns the total debt (or credit) that the vault is responsible for. Credit is expressed as negative debt. * @dev This is not a view function, and actually updates the entire debt distribution chain. * @dev Call this function using `callStatic` to treat it as a view function. * @param poolId The id of the pool that owns the vault whose debt is being queried. * @param collateralType The address of the collateral of the associated vault. * @return debtD18 The overall debt of the vault, denominated with 18 decimals of precision. **/ function getVaultDebt(uint128 poolId, address collateralType) external returns (int256 debtD18); /** * @notice Returns the amount and value of the collateral held by the vault. * @dev Call this function using `callStatic` to treat it as a view function. * @dev collateralAmount is represented as an integer with 18 decimals. * @dev collateralValue is represented as an integer with the number of decimals specified by the collateralType. * @param poolId The id of the pool that owns the vault whose collateral is being queried. * @param collateralType The address of the collateral of the associated vault. * @return collateralAmountD18 The collateral amount of the vault, denominated with 18 decimals of precision. * @return collateralValueD18 The collateral value of the vault, denominated with 18 decimals of precision. */ function getVaultCollateral( uint128 poolId, address collateralType ) external returns (uint256 collateralAmountD18, uint256 collateralValueD18); /** * @notice Returns the collateralization ratio of the vault. If debt is negative, this function will return 0. * @dev Call this function using `callStatic` to treat it as a view function. * @dev The return value is a percentage with 18 decimals places. * @param poolId The id of the pool that owns the vault whose collateralization ratio is being queried. * @param collateralType The address of the collateral of the associated vault. * @return ratioD18 The collateralization ratio of the vault, denominated with 18 decimals of precision. */ function getVaultCollateralRatio( uint128 poolId, address collateralType ) external returns (uint256 ratioD18); }
#include "qgraphicsitemcomposite.h" #include "qexception.h" #include <cmath> QGraphicsItemComposite::QGraphicsItemComposite(QGraphicsItem *parent) : QGraphicsItem(parent) { setFlag(QGraphicsItem::ItemIsMovable, true); } QGraphicsItemComposite::Composite QGraphicsItemComposite::release() { Composite result = children; qreal x = this->x(); qreal y = this->y(); for (QGraphicsItem* child : children) { if (x < 0) { child->setX(child->x() - std::abs(x)); } else { child->setX(child->x() + std::abs(x)); } if (y < 0) { child->setY(child->y() - std::abs(y)); } else { child->setY(child->y() + std::abs(y)); } child->setParentItem(0); child->setFlag(QGraphicsItem::ItemIsMovable, true); dynamic_cast<ColorSetter*>(child)->setColor(Qt::black); } children.clear(); return result; } void QGraphicsItemComposite::add(QGraphicsItem *component) { // check argument if (!component) { throw QArgumentNullException(); } if (component->parentItem()) { dynamic_cast<QGraphicsItemComposite*>(component->parentItem())->remove(component); } dynamic_cast<ColorSetter*>(component)->setColor(Qt::green); component->setParentItem(this); component->setFlag(QGraphicsItem::ItemIsMovable, false); children.append(component); } void QGraphicsItemComposite::remove(QGraphicsItem *component) { // check argument if (!component) { throw QArgumentNullException(); } // variables int index = children.indexOf(component); // remove if (index < 0) { return; } dynamic_cast<ColorSetter*>(children.at(index))->setColor(Qt::black); children.at(index)->setParentItem(0); component->setFlag(QGraphicsItem::ItemIsMovable, true); children.removeAt(index); } QGraphicsItem* QGraphicsItemComposite::getChild(int index) { // check argument if (index < 0) { throw QArgumentOutOfRangeException(); } else if (index >= children.length()) { throw QArgumentOutOfRangeException(); } return children.at(index); } const QGraphicsItem* QGraphicsItemComposite::getChild(int index) const { // check argument if (index < 0) { throw QArgumentOutOfRangeException(); } else if (index >= children.length()) { throw QArgumentOutOfRangeException(); } return children.at(index); } bool QGraphicsItemComposite::contains(QGraphicsItem *item) const { return children.contains(item); } void QGraphicsItemComposite::adjustPosition() { qreal xmin, xmax, ymin, ymax; computeSize(xmin, xmax, ymin, ymax); setPos(xmin, ymin); for (QGraphicsItem* child : children) { if (xmin < 0) { child->setX(child->x() + std::abs(xmin)); } else { child->setX(child->x() - std::abs(xmin)); } if (ymin < 0) { child->setY(child->y() + std::abs(ymin)); } else { child->setY(child->y() - std::abs(ymin)); } } } QRectF QGraphicsItemComposite::boundingRect() const { // variables qreal xmin, xmax, ymin, ymax; computeSize(xmin, xmax, ymin, ymax); return QRectF(QPointF(), QRectF(QPointF(xmin, ymin), QPointF(xmax, ymax)).size()); } void QGraphicsItemComposite::paint(QPainter *, const QStyleOptionGraphicsItem *, QWidget *) { } void QGraphicsItemComposite::setColor(QColor color) { if (color == Qt::black) { for (QGraphicsItem* child : children) { dynamic_cast<ColorSetter*>(child)->setColor(Qt::green); } } else { for (QGraphicsItem* child : children) { dynamic_cast<ColorSetter*>(child)->setColor(color); } } } void QGraphicsItemComposite::computeSize(qreal &xmin, qreal &xmax, qreal &ymin, qreal &ymax) const { if (children.empty()) { xmin = xmax = ymin = ymax = 0; return; } xmin = xmax = children.first()->x(); ymin = ymax = children.first()->y(); xmax += children.first()->boundingRect().width(); ymax += children.first()->boundingRect().height(); for (int i = 1; i < children.length(); i++) { QGraphicsItem* child = children.at(i); if (xmin > child->x()) { xmin = child->x(); } if (xmax < child->x() + child->boundingRect().width()) { xmax = child->x() + child->boundingRect().width(); } if (ymin > child->y()) { ymin = child->y(); } if (ymax < child->y() + child->boundingRect().height()) { ymax = child->y() + child->boundingRect().height(); } } }
module PostCategoriesHelper # Generates hierarchical category options for dropdowns def category_options(exclude_category = nil) category_list = [] build_category_list(PostCategory.where(parent_category_id: nil), category_list, exclude_category) category_list end private # Recursive method to build category list def build_category_list(categories, category_list, exclude_category, prefix = '') categories.each do |category| next if category == exclude_category category_list << [prefix + category.name, category.id] build_category_list(category.child_categories, category_list, exclude_category, prefix + '-- ') end end end
# Copyright 2021 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Sampling component definition.""" from typing import List, Optional from tfx import types from tfx.dsl.components.base import base_beam_component, executor_spec from tfx.types import channel_utils, standard_artifacts from tfx.utils import json_utils from tfx_addons.sampling.executor import Executor from tfx_addons.sampling.spec import SamplerSpec, SamplingStrategy class Sampler(base_beam_component.BaseBeamComponent): """A TFX component to sample examples. The sampling component wraps an Apache Beam pipeline to process data in an TFX pipeline. This component loads in tf.Record files from an earlier example artifact, processes the 'train' split by default, samples the split by a given label's classes, and stores the new set of sampled examples into its own example artifact in tf.Record format. The sampling is probabilistic estimation. Note that in small datasets this may result in worse datasets or such. This module is meant to approximate sampling using probability. By default, the component will ignore all examples with a null value (more precisely, a value that evaluates to False) for the given label, although more values can be added in as necessary. Additionally, it will copy all non-'train' splits, through this behavior can be changed as well. The component will save the examples in a user-specified number of files, and it can be given a name as well. ## Example ``` import tfx_addons as tfxa under = tfxa.sampling.Sampler( examples=example_gen.outputs['examples'], sampling_strategy=tfxa.sampling.SamplingStrategy.UNDERSAMPLE ) ``` Component `outputs` contains: - `sampled_examples`: Channel of type `standard_artifacts.Examples` for materialized sampled examples, based on the input splits, which includes copied splits unless otherwise specified by copy_others. """ SPEC_CLASS = SamplerSpec EXECUTOR_SPEC = executor_spec.BeamExecutorSpec(Executor) def __init__( self, label: str, input_data: types.Channel = None, splits: Optional[List[str]] = None, copy_others: bool = True, shards: Optional[int] = 0, null_classes: Optional[List[str]] = None, sampling_strategy: SamplingStrategy = SamplingStrategy.UNDERSAMPLE): """Construct a SamplerComponent. Args: input_data: A Channel of type `standard_artifacts.Examples`. label: The name of the column containing class names to sample by. splits: A list containing splits to sample. copy_others: Determines whether we copy over the splits that aren't sampled, or just exclude them from the output artifact. shards: The number of files that each sampled split should contain. Default 0 is Beam's tfrecordio function's default. null_classes: A list determining which classes that we should not sample. sampling_strategy: Wether to undersample or Oversample """ output_data = channel_utils.as_channel([standard_artifacts.Examples()]) spec = SamplerSpec( input_data=input_data, output_data=output_data, label=label, splits=json_utils.dumps(splits), copy_others=int(copy_others), shards=shards, null_classes=json_utils.dumps(null_classes), sampling_strategy=sampling_strategy, ) super().__init__(spec=spec)
package io.github.madmaximuus.persian.menus import androidx.compose.foundation.background import androidx.compose.foundation.interaction.MutableInteractionSource import androidx.compose.foundation.interaction.PressInteraction import androidx.compose.foundation.layout.Box import androidx.compose.material3.DropdownMenu import androidx.compose.material3.MaterialTheme import androidx.compose.runtime.Composable import androidx.compose.runtime.LaunchedEffect import androidx.compose.runtime.MutableState import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember import androidx.compose.ui.Modifier import androidx.compose.ui.unit.DpOffset import androidx.compose.ui.window.PopupProperties import kotlinx.coroutines.flow.filter @Composable fun PersianDropdownMenu( anchor: @Composable () -> Unit, modifier: Modifier = Modifier, expanded: MutableState<Boolean> = remember { mutableStateOf(false) }, interactionSource: MutableInteractionSource = remember { MutableInteractionSource() }, onDismissRequest: () -> Unit = {}, colors: MenuColors = PersianMenuDefaults.colors(), offset: DpOffset = DpOffset.Zero, children: @Composable () -> Unit ) { LaunchedEffect(interactionSource) { interactionSource.interactions .filter { it is PressInteraction.Press } .collect { expanded.value = !expanded.value } } Box { anchor() MaterialTheme(shapes = MaterialTheme.shapes.copy(extraSmall = MaterialTheme.shapes.large)) { DropdownMenu( modifier = modifier .background(colors.backgroundColor, MaterialTheme.shapes.large), expanded = expanded.value, offset = offset, onDismissRequest = { onDismissRequest() expanded.value = false }, properties = PopupProperties(clippingEnabled = false), content = { children() } ) } } }
const express = require('express'); const router = express.Router(); const passport = require('passport'); const jwt = require('jsonwebtoken'); const config = require('../config/database'); const User = require('../models/user'); const Article = require('../models/article'); const Episode = require('../models/episode'); const Show = require('../models/show'); const multer = require('multer'); const Jimp = require('jimp'); const Promise = require('bluebird'); const fileType = require('file-type'); //create show router.post('/create', passport.authenticate('jwt', {session: false}), (req, res, next) => { var Djs = req.body.djs let newShow = new Show({ name: req.body.name, djs: Djs, description: req.body.description, startDate: req.body.startDate, endDate: req.body.endDate, startDays: req.body.startDays, startHour: req.body.startHour, startMinute: req.body.startMinute, endDays: req.body.endDays, endHour: req.body.endHour, endMinute: req.body.endMinute, genre: req.body.genre, timeString: req.body.timeString, type: req.body.type, duration: req.body.duration, tags: req.body.tags, thumbnailPath: req.body.thumbnailPath, bannerPath: req.body.bannerPath, placeholder: req.body.placeholder }); newShow.save((err, show) => { if(err) { res.json({success: false, msg: "Failed to create show"}) console.log(err) } else { res.json({success: true, msg: "Show created successfully"}) } }); }); //edit a show in the database router.put('/edit/:id', passport.authenticate('jwt', {session: false}), (req, res, next) => { var Djs = req.body.djs; var tags = req.body.tags; Show.findByIdAndUpdate({_id: req.params.id}, {$set: { 'name': req.body.name, 'djs': Djs, 'description': req.body.description, 'startDate': req.body.startDate, 'endDate': req.body.endDate, 'timeString': req.body.timeString, 'type': req.body.type, 'duration': req.body.duration, 'tags': tags, 'thumbnailPath': req.body.thumbnailPath, 'bannerPath': req.body.bannerPath, 'placeholder': req.body.placeholder, 'startDays': req.body.startDays, 'startHour': req.body.startHour, 'startMinute': req.body.startMinute, 'endDays': req.body.endDays, 'endHour': req.body.endHour, 'endMinute': req.body.endMinute, 'genre': req.body.genre }}) .then((show, err) => { if(err) { console.log(err); res.json({success:false, msg: 'failed to edit show'}) } else { console.log(req.body.genre) res.json({success: true, msg: 'Show successfully edited'}) } }) }); //multer disk storage for images var storage = multer.diskStorage({ // destination folder destination: function (req, file, cb) { cb(null, './public/show-banner/') }, // rename file to originalname filename: function (req, file, cb) { cb(null, file.originalname + Date.now()); } }); //returns list of all shows router.get('/showlist', (req, res, next) => { Show.find({}) .then((shows) => { res.send(shows); }) .catch(next); }); //returns the episodes for a show router.get('/episodes/:id', (req, res, next) => { Episode.find({show: req.params.id, endDate: {$lt: Date.now()}}) .then((episodes, err) => { if(err){ console.log(err) res.json({success: false, msg: 'Something went wrong'}) } else if (episodes === null){ res.json({success: false, msg: 'There were no episodes'}) } else { res.send(episodes) } }) }) //returns all shows that are listed as on air router.get('/get-on-air', (req, res, next) => { Show.find({onAir: true}) .then(shows => { res.send(shows) }); }); //returns all shows that are listed as archived router.get('/get-archive', (req, res, next) => { Show.find({archive: true}) .then(shows => { res.send(shows) }); }); //change the archive status of a show router.put('/change-archive', passport.authenticate('jwt', {session: false}), (req, res, next) => { Show.findByIdAndUpdate({_id: req.body.id}, {$set: {archive: req.body.status}}) .then((show, err) => { if(err) { res.json({success: false, msg: 'Something went wrong'}); return false } else { res.json({success: true, msg: 'Status updated!'}); return true } }) }) //change the on air status of a show router.put('/change-status', passport.authenticate('jwt', {session: false}), (req, res, next) => { Show.findByIdAndUpdate({_id: req.body.id}, {$set: {onAir: req.body.status}}) .then((show, err) => { if(err) { res.json({success: false, msg: 'Something went wrong'}); return false } else { res.json({success: true, msg: 'Status updated!'}); return true } }) }) //memory storage to allow processing of image var thumbnailStorage = multer.memoryStorage(); var bannerStorage = multer.memoryStorage(); var upload = multer({storage: bannerStorage}); var thumbnailUpload = multer({storage: thumbnailStorage}); //post show banner image router.post('/images/show-banner', upload.single('file'), passport.authenticate('jwt', {session: false}), (req, res, next) => { var rand = Math.floor(Math.random() * 200000).toString() Jimp.read(req.file.buffer, (err, image) => { image.resize(300, 300); image.write('./public/show-banners/' + rand + req.file.originalname); }); if(req.body.showId){ let id = req.body.showId; Show.findOneAndUpdate({_id: id}, {$set: {"bannerPath": 'public/show-banners/' + rand + req.file.originalname}}) .then((article, err) => { if (err) { res.json({success: false, msg: 'failed to upload image'}) } else { res.json({success: true, msg: 'Image uploaded!', path: 'public/show-banners/' + rand + req.file.originalname}) } }) } else { res.json({path: 'public/show-banners/' + rand + req.file.originalname}) } }) //post show thumbnail router.post('/images/thumbnail', thumbnailUpload.single('file'), passport.authenticate('jwt', {session:false}), (req, res, next) => { var rand = Math.floor(Math.random() * 200000).toString() Jimp.read(req.file.buffer, (err, image) => { image.resize(100, 100); image.write('./public/show-thumbnails/' + rand + req.file.originalname) }); if(req.body.showId){ let id = req.body.showId; Show.findOneAndUpdate({_id: id}, {$set: {"thumbnailPath": 'public/show-thumbnails/' + rand + req.file.originalname}}) .then( (article, err ) => { if (err) { res.json({success: false, msg: 'failed to upload image'}) } else { res.json({success: true, msg: 'Image Uploaded!', path: 'public/show-thumbnails/' + rand + req.file.originalname}) } }); } else { res.json({path: 'public/show-thumbnails/' + rand + req.file.originalname}) } }); //delete show router.delete('/delete/:id', passport.authenticate('jwt', {session:false}), (req, res, next) => { Show.findByIdAndRemove({_id:req.params.id}) .then((show) => { res.send(show); }); }); //get show by id router.get('/get/:id', (req, res, next) => { Show.findOne({_id: req.params.id}) .then(show => { res.send(show) }); }); router.get('/get-by-user/:id', passport.authenticate('jwt', {session: false}), (req, res, next) => { Show.find({djs: req.params.id}) .then(shows => { res.send(shows) }); }); //find shows that occur on a given day and are on the air router.post('/get-by-day', (req, res, next) => { Show.find({startDays: req.body.day, onAir: true}) .then(shows => { res.send(shows) }); }); //get placeholder show router.get('/get-placeholder', (req, res, next) => { Show.findOne({placeholder: true}) .then(show => { res.send(show) }); }); //get active and archived shows router.get('/get-for-playlist', (req, res, next) => { Show.find({ $or: [{onAir: true}, {archive: true}]}, (err, shows) => { if(err){ console.log(err); res.json({success: false, msg: "Could not retrieve shows"}) } else { res.send(shows); } }); }); //get unique tags from the database router.get('/get-tags', (req, res, next) => { Show.find().distinct('tags', (err, tags) => { if(err){ console.log(err); res.json({success: false, msg: 'Could not retrieve tags'}); } else { res.send(tags); } }) }) module.exports = router;
<!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>Document</title> <script src="js/jquery-1.12.4.js"></script> <style> .one { font-size: 3em; color: orange; } .two { font-style: italic; text-decoration: underline; } </style> </head> <body> <h1>jQuery + CSS</h1> <input type="button" value="버튼1" id="btn1"> <hr> <div id="box">상자</div> <script> $('#btn1').click(function() { //CSS 조작 //- css(속성) > 읽기 //- css(속성, 값) > 쓰기 //alert(document.getElementById('box').style.color); > 기본값이라서 이 방법으로는 얻어올 수 없다. // alert(getComputedStyle(document.getElementById('box')).getPropertyValue('color')); // alert($('#box').css('color')); //바로 위의 방식과 같다. // $('#box') // .css('color', 'blue') // .css('background-color', 'gold') // .css('width', 300) // .css('height', 100); //------------------------------------------------------------------------------------------------- // $('#box').css({ // color: 'blue', // backgroundColor: 'gold', // width: 300, // height: 100 // }) //box.classList.add('one') //box.classList.remove('one') // $('#box').addClass('one'); // $('#box').addClass('two'); // $('#box').removeClass('one'); $('#box').toggleClass('one'); }); </script> </body> </html>
import { tvDetailsPage as Page } from "@/integration/page-objects"; describe("TV Details Buttons", () => { beforeEach(() => { cy.login(); }); it("Fully Available Request", () => { cy.intercept("GET", "**/v2/search/Tv/1399", (req) => { req.reply((res) => { const body = res.body; body.fullyAvailable = true; body.partlyAvailable = false; res.send(body); }); }).as("detailsResponse"); Page.visit("1399"); cy.wait('@detailsResponse'); Page.availableButton.should('be.visible'); Page.requestButton.should('not.exist'); Page.requestFabButton.fab.should('not.exist'); }); it("Partially Available Request", () => { cy.intercept("GET", "**/v2/search/Tv/1399", (req) => { req.reply((res) => { const body = res.body; body.fullyAvailable = false; body.partlyAvailable = true; res.send(body); }); }).as("detailsResponse"); Page.visit("1399"); cy.wait('@detailsResponse'); Page.availableButton.should('not.exist'); Page.requestButton.should('be.visible'); Page.requestFabButton.fab.should('be.visible'); Page.partiallyAvailableButton.should('be.visible'); }); it("Not Available Request", () => { cy.intercept("GET", "**/v2/search/Tv/1399", (req) => { req.reply((res) => { const body = res.body; body.fullyAvailable = false; body.partlyAvailable = false; res.send(body); }); }).as("detailsResponse"); Page.visit("1399"); cy.wait('@detailsResponse'); Page.availableButton.should('not.exist'); Page.requestButton.should('be.visible'); Page.requestFabButton.fab.should('be.visible'); Page.partiallyAvailableButton.should('not.exist'); }); it("Issues Enabled", () => { cy.intercept("GET", "**/Settings/issuesenabled", 'true').as('issuesEnabled'); cy.visit("/details/tv/1399"); cy.wait('@issuesEnabled'); Page.reportIssueButton.should('be.visible'); }); it("Issues Disabled", () => { cy.intercept("GET", "**/Settings/issuesenabled", 'false'); Page.visit("1399"); Page.reportIssueButton.should('not.exist'); }); });
local ViewportPosition = Vector3.new(-82.61264038085938, 4.956138610839844, -2.969184398651123) local VieportModelPos = Vector3.new(-78.3, 3, -0.8) local RunService = game:GetService("RunService") local UserInputService = game:GetService("UserInputService") local ReplicatedStorage = game:GetService("ReplicatedStorage") local Players = game:GetService("Players") local Towers = ReplicatedStorage:WaitForChild("Towers") local camera = workspace.CurrentCamera local player = Players.LocalPlayer local TOWER_ROTATION_INCREMENT = 45 local hoverColor = Color3.fromRGB(33, 33, 33) local hoverOutlineColor = Color3.fromRGB(62, 62, 62) local hoverOutlineTransparency = 0.2 local selectedColor = Color3.fromRGB(180, 180, 180) local selectedOutlineColor = Color3.fromRGB(167, 167, 167) local selectedOutlineTransparency = 0.6 local selectedTowerName = "" local SELECT_MODE_NONE = 0 local SELECT_MODE_HOVER = 1 local SELECT_MODE_SELECTED = 2 local neonGreen = Color3.fromRGB(21, 111, 21) local neonRed = Color3.fromRGB(165, 0, 3) function highlightAreas(folder: Folder?, towerType: string) -- set all of them to be not visible for _, part in pairs(folder:GetDescendants()) do if part:IsA("Part") or part:IsA("UnionOperation") then part.Transparency = 1 end end if towerType then -- set the one we want to highlight to be visible for _, part: Part | UnionOperation in pairs(folder[towerType]:GetChildren()) do part.Color = neonGreen part.Transparency = 0.9 end -- make all the others red for _, planefolder in pairs(folder:GetChildren()) do if planefolder ~= folder[towerType] then for _, part: Part | UnionOperation in pairs(planefolder:GetChildren()) do part.Color = neonRed part.Transparency = 0.75 end end end end end local numDefaultSize = UDim2.new(0.34, 0, 0.34, 0) local numSelectSize = UDim2.new(0.4, 0, 0.4, 0) -- this function just changes a frames look based on if its selected or not function selectFrameHighlight(frame: Frame, mode: number) -- disable others for _, tFrame in pairs(script.Parent:GetChildren()) do if tFrame:IsA("Frame") then tFrame.SlotNum.Size = numDefaultSize tFrame.SlotNum.BackgroundColor3 = Color3.fromRGB(26, 26, 26) end end if frame then local highlight: Frame = frame.SlotNum if mode == SELECT_MODE_NONE then highlight.BackgroundColor3 = Color3.fromRGB(26, 26, 26) highlight.Size = numDefaultSize end if mode == SELECT_MODE_HOVER then highlight.BackgroundColor3 = Color3.fromRGB(44, 44, 44) end if mode == SELECT_MODE_SELECTED then highlight.Size = numSelectSize highlight.BackgroundColor3 = selectedColor end end end -- setup viewports and gui for _, frame in pairs(script.Parent:GetChildren()) do if frame:IsA("Frame") then local towername: string = frame.TowerInternalName.Value if towername ~= "" then local cost = ReplicatedStorage.getTowerData:InvokeServer(towername, "Cost") local replicatedTemplate: Model = ReplicatedStorage.getTowerData:InvokeServer(towername, "Template") frame.Money.Text = "$"..cost frame.TowerName.Text = towername local viewportFrame: ViewportFrame = frame.ViewportFrame local newModel = replicatedTemplate:Clone() newModel.Parent = viewportFrame newModel:ScaleTo(1) newModel:PivotTo(CFrame.new(VieportModelPos) * CFrame.Angles(0, math.rad(90), 0)) local tool = newModel:FindFirstChildOfClass("Tool") if tool then pcall(function() tool.Handle.CFrame = newModel.HumanoidRootPart.RightGripAttachment.WorldCFrame end) end local newCam = Instance.new("Camera", frame) newCam.CFrame = CFrame.new(ViewportPosition, newModel.PrimaryPart.Position + Vector3.new(0, newModel.PrimaryPart.Size.Y / 4 - 0.5, 0)) viewportFrame.CurrentCamera = newCam else frame.Money.Text = "$0" frame.TowerName.Text = "None" frame.ViewportFrame.Visible = false end local selectButton: TextButton = frame.Select selectButton.MouseEnter:Connect(function() if selectedTowerName == "" then selectFrameHighlight(frame, SELECT_MODE_HOVER) end end) selectButton.MouseLeave:Connect(function() if selectedTowerName == "" then selectFrameHighlight(nil, SELECT_MODE_NONE) end end) end end UserInputService.InputBegan:Connect(function(input: InputObject, gameProcessedEvent: boolean) if input.UserInputType == Enum.UserInputType.Keyboard then if input.KeyCode == Enum.KeyCode.One then for _, frame in pairs(script.Parent:GetChildren()) do if frame:IsA("Frame") then local num: TextLabel = frame.SlotNum.Num if num.Text == "1" then local twrname = frame.TowerInternalName.Value if selectedTowerName ~= twrname then selectFrameHighlight(frame, SELECT_MODE_SELECTED) selectedTowerName = twrname beginTowerPlacement() end end end end end end end) -- make the buttons do something local latestRay = nil function MouseRaycast(params: RaycastParams): RaycastResult | nil local mousePos = UserInputService:GetMouseLocation() local mouseRay = camera:ViewportPointToRay(mousePos.X, mousePos.Y) latestRay = mouseRay local enemyRayResult = workspace:Raycast(mouseRay.Origin, mouseRay.Direction * 50, params) return enemyRayResult end function endTowerPlacement(towerPlaceholder: Model, towerRay: Ray, towerCFrame: CFrame) towerPlaceholder:Destroy() ReplicatedStorage.towerPlaceEvent:FireServer(towerRay.Origin, towerRay.Direction, towerCFrame, selectedTowerName) selectedTowerName = "" selectFrameHighlight(nil, SELECT_MODE_NONE) highlightAreas(workspace.TowerPlaceholderAreas, nil) end local towerRayParams = RaycastParams.new() towerRayParams.FilterType = Enum.RaycastFilterType.Exclude local towerRotation = 0 function beginTowerPlacement() local templateTower = Towers:FindFirstChild(selectedTowerName) if templateTower then local towerToSpawn: Model = templateTower:Clone() towerToSpawn.Name = "PlaceholderTower" towerToSpawn.Parent = workspace for _, v in pairs(towerToSpawn:GetDescendants()) do if v:IsA("BasePart") or v:IsA("MeshPart") then if v.Transparency < 1 then v.Transparency = 0.5 v.CastShadow = false end v.CollisionGroup = "Towers" end end local towerRoot: Part = towerToSpawn:FindFirstChild("HumanoidRootPart") local towerHuman: Humanoid = towerToSpawn:FindFirstChild("Humanoid") local towerHighlight: Highlight = Instance.new("Highlight", towerToSpawn) towerHighlight.FillTransparency = 0.5 towerHighlight.OutlineTransparency = 0.1 towerRayParams.FilterDescendantsInstances = {towerToSpawn, player.Character, workspace.MapAI, workspace.Towers, workspace.TowerPlaceholderAreas} local towerCanPlace = false local cframe = nil local towerType = ReplicatedStorage.getTowerData:InvokeServer(selectedTowerName, "TowerType") highlightAreas(workspace.TowerPlaceholderAreas, towerType) local runEvent = RunService.RenderStepped:Connect(function() local result = MouseRaycast(towerRayParams) if result and result.Instance then if not result.Instance:HasTag("GroundUnit") then -- make it red towerHighlight.FillColor = Color3.fromRGB(200, 0, 0) towerHighlight.OutlineColor= Color3.fromRGB(200, 0, 0) towerCanPlace = false else -- make it green towerHighlight.FillColor = Color3.fromRGB(0, 154, 0) towerHighlight.OutlineColor = Color3.fromRGB(0, 200, 0) towerCanPlace = true end local x = result.Position.X local y = result.Position.Y + towerHuman.HipHeight + (towerRoot.Size.Y / 2) local z = result.Position.Z cframe = CFrame.new(x, y, z) * CFrame.Angles(0, math.rad(towerRotation), 0) towerToSpawn:PivotTo(cframe) end end) local clickEvent clickEvent = UserInputService.InputBegan:Connect(function(input: InputObject, gameProcessedEvent: boolean) if not gameProcessedEvent then if input.UserInputType == Enum.UserInputType.MouseButton1 then if towerCanPlace then -- finish the thing and disconnect events endTowerPlacement(towerToSpawn, latestRay, cframe) runEvent:Disconnect() clickEvent:Disconnect() end end if input.UserInputType == Enum.UserInputType.Keyboard then if input.KeyCode == Enum.KeyCode.Q then towerRotation = towerRotation + TOWER_ROTATION_INCREMENT end if input.KeyCode == Enum.KeyCode.E then towerRotation = towerRotation - TOWER_ROTATION_INCREMENT end -- X to cancel place logic if input.KeyCode == Enum.KeyCode.X then towerToSpawn:Destroy() selectedTowerName = "" selectFrameHighlight(nil, SELECT_MODE_NONE) highlightAreas(workspace.TowerPlaceholderAreas, nil) runEvent:Disconnect() clickEvent:Disconnect() end end end end) else warn("No tower with the name "..selectedTowerName.." exists") end end for _, towerFrame in pairs(script.Parent:GetChildren()) do if towerFrame:IsA("Frame") then local selectButton: TextButton = towerFrame:FindFirstChild("Select") selectButton.Activated:Connect(function() local towerName = towerFrame.TowerInternalName.Value if selectedTowerName ~= towerName and towerName ~= "" then -- set it and start the placing function selectFrameHighlight(towerFrame, SELECT_MODE_SELECTED) selectedTowerName = towerName beginTowerPlacement() end end) end end
/* ***** BEGIN LICENSE BLOCK ***** * This file is part of Natron <https://natrongithub.github.io/>, * (C) 2018-2023 The Natron developers * (C) 2013-2018 INRIA and Alexandre Gauthier-Foichat * * Natron 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 2 of the License, or * (at your option) any later version. * * Natron 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 Natron. If not, see <http://www.gnu.org/licenses/gpl-2.0.html> * ***** END LICENSE BLOCK ***** */ #ifndef Engine_CacheSerialization_h #define Engine_CacheSerialization_h // ***** BEGIN PYTHON BLOCK ***** // from <https://docs.python.org/3/c-api/intro.html#include-files>: // "Since Python may define some pre-processor definitions which affect the standard headers on some systems, you must include Python.h before any standard headers are included." #include <Python.h> // ***** END PYTHON BLOCK ***** #include "Global/Macros.h" #include <list> #include <set> #include <cstddef> #include <stdexcept> #if !defined(Q_MOC_RUN) && !defined(SBK_RUN) GCC_DIAG_UNUSED_LOCAL_TYPEDEFS_OFF // clang-format off GCC_DIAG_OFF(unused-parameter) // /opt/local/include/boost/serialization/smart_cast.hpp:254:25: warning: unused parameter 'u' [-Wunused-parameter] #include <boost/archive/binary_iarchive.hpp> #include <boost/archive/binary_oarchive.hpp> #include <boost/serialization/utility.hpp> #include <boost/serialization/list.hpp> // /usr/local/include/boost/serialization/shared_ptr.hpp:112:5: warning: unused typedef 'boost_static_assert_typedef_112' [-Wunused-local-typedef] #include <boost/serialization/shared_ptr.hpp> #include <boost/serialization/export.hpp> #include <boost/serialization/split_member.hpp> GCC_DIAG_UNUSED_LOCAL_TYPEDEFS_ON GCC_DIAG_ON(unused-parameter) // clang-format on #endif #include "Engine/Cache.h" #include "Engine/ImageSerialization.h" #include "Engine/ImageParamsSerialization.h" #include "Engine/FrameEntrySerialization.h" #include "Engine/FrameParamsSerialization.h" #include "Engine/EngineFwd.h" // Note: these classes are used for cache serialization and do not have to maintain backward compatibility #define SERIALIZED_ENTRY_INTRODUCES_SIZE 2 #define SERIALIZED_ENTRY_VERSION SERIALIZED_ENTRY_INTRODUCES_SIZE //Beyond that percentage of occupation, the cache will start evicting LRU entries #define NATRON_CACHE_LIMIT_PERCENT 0.9 ///When defined, number of opened files, memory size and disk size of the cache are printed whenever there's activity. //#define NATRON_DEBUG_CACHE NATRON_NAMESPACE_ENTER /*Saves cache to disk as a settings file. */ template<typename EntryType> void Cache<EntryType>::save(CacheTOC* tableOfContents) { clearInMemoryPortion(false); { QMutexLocker l(&_lock); // must be locked for (ConstCacheIterator it = _diskCache.begin(); it != _diskCache.end(); ++it) { const std::list<EntryTypePtr> & listOfValues = getValueFromIterator(it); for (typename std::list<EntryTypePtr>::const_iterator it2 = listOfValues.begin(); it2 != listOfValues.end(); ++it2) { if ( (*it2)->isStoredOnDisk() ) { SerializedEntry serialization; serialization.hash = (*it2)->getHashKey(); serialization.params = (*it2)->getParams(); serialization.key = (*it2)->getKey(); serialization.size = (*it2)->dataSize(); serialization.filePath = (*it2)->getFilePath(); serialization.dataOffsetInFile = (*it2)->getOffsetInFile(); (*it2)->syncBackingFile(); tableOfContents->push_back(serialization); #ifdef DEBUG if ( !_isTiled && !CacheAPI::checkFileNameMatchesHash(serialization.filePath, serialization.hash) ) { qDebug() << "WARNING: Cache entry filename is not the same as the serialized hash key"; } #endif } } } } } /*Restores the cache from disk.*/ template<typename EntryType> void Cache<EntryType>::restore(const CacheTOC & tableOfContents) { ///Make sure the shared_ptrs live in this list and are destroyed not while under the lock ///so that the memory freeing (which might be expensive for large images) doesn't happen while under the lock std::list<EntryTypePtr> entriesToBeDeleted; std::set<QString> usedFilePaths; for (typename CacheTOC::const_iterator it = tableOfContents.begin(); it != tableOfContents.end(); ++it) { if ( it->hash != it->key.getHash() ) { /* * If this warning is printed this means that the value computed by it->key() * is different than the value stored prior to serialiazing this entry. In other words there're * 2 possibilities: * 1) The key has changed since it has been added to the cache: maybe you forgot to serialize some * members of the key or you didn't save them correctly. * 2) The hash key computation is unreliable and is depending upon changing or non-deterministic * parameters which is wrong. */ qDebug() << "WARNING: serialized hash key different than the restored one"; } #ifdef DEBUG if ( !_isTiled && !checkFileNameMatchesHash(it->filePath, it->hash) ) { qDebug() << "WARNING: Cache entry filename is not the same as the serialized hash key"; } #endif EntryType* value = NULL; try { value = new EntryType(it->key, it->params, this); if (it->size != getTileSizeBytes()) { delete value; continue; } ///This will not put the entry back into RAM, instead we just insert back the entry into the disk cache value->restoreMetadataFromFile(it->size, it->filePath, it->dataOffsetInFile); } catch (const std::exception & e) { qDebug() << e.what(); delete value; continue; } const std::string& filePath = value->getFilePath(); usedFilePaths.insert(QString::fromUtf8(filePath.c_str())); { QMutexLocker locker(&_lock); sealEntry(EntryTypePtr(value), false /*inMemory*/); } } // Remove from the cache all files that are not referenced by the table of contents QString cachePath = getCachePath(); if (isTileCache()) { QDir cacheFolder(cachePath); QString absolutePath = cacheFolder.absolutePath(); QStringList etr = cacheFolder.entryList(QDir::NoDotAndDotDot); for (QStringList::iterator it = etr.begin(); it!=etr.end(); ++it) { QString entryFilePath = absolutePath + QLatin1Char('/') + *it; std::set<QString>::iterator foundUsed = usedFilePaths.find(entryFilePath); if (foundUsed == usedFilePaths.end()) { cacheFolder.remove(*it); } } } else { for (U32 i = 0x00; i <= 0xF; ++i) { for (U32 j = 0x00; j <= 0xF; ++j) { char str[3] = { '0', '0', 0 }; str[0] += i; str[1] += j; QDir cacheFolder(cachePath + QLatin1Char('/') + QString::fromUtf8(str)); QString absolutePath = cacheFolder.absolutePath(); QStringList etr = cacheFolder.entryList(QDir::NoDotAndDotDot); for (QStringList::iterator it = etr.begin(); it!=etr.end(); ++it) { QString entryFilePath = absolutePath + QLatin1Char('/') + *it; std::set<QString>::iterator foundUsed = usedFilePaths.find(entryFilePath); if (foundUsed == usedFilePaths.end()) { cacheFolder.remove(*it); } } } } } } template<typename EntryType> struct Cache<EntryType>::SerializedEntry { hash_type hash; typename EntryType::key_type key; ParamsTypePtr params; std::size_t size; //< the data size in bytes std::string filePath; //< we need to serialize it as several entries can have the same hash, hence we index them std::size_t dataOffsetInFile; SerializedEntry() : hash(0) , key() , params() , size(0) , filePath() , dataOffsetInFile(0) { } template<class Archive> void serialize(Archive & ar, const unsigned int /*version*/) { ar & ::boost::serialization::make_nvp("Hash", hash); ar & ::boost::serialization::make_nvp("Key", key); ar & ::boost::serialization::make_nvp("Params", params); ar & ::boost::serialization::make_nvp("Size", size); ar & ::boost::serialization::make_nvp("Filename", filePath); ar & ::boost::serialization::make_nvp("Offset", dataOffsetInFile); } }; NATRON_NAMESPACE_EXIT #endif // Engine_CacheSerialization_h
--- date: "2023-09-14T18:43:19+01:00" draft: false title: Modules - overview --- Compilation of a large C++ project can be terribly slow when the project is not structured correctly - structured in a way in fact mimicking modules. Unfortunately this requires deep understanding of linkage and compilation process. These are not most popular and essential parts of the language and as a result are quite often ignored and forgotten. Consequently, projects have tendencies to diverge from optimal structure in terms of compilation speed. The default and the easiest option should be the most efficient, but it's opposite. ### How modules affect linkage? Modules introduce new term: **module linkage** along with existing external and internal linkages: "The name can be referred to only from the scopes in the same module unit or in the other translation units of the same named module." - en.cppreference.com. A translation unit is a subset of module unit - multiple translation unit can form one module unit. Translation unit used to be self-contained. All symbols required for compilation had to be declared through included header files. Modules aim to eliminated separate files for providing symbols. How compiler can validate presence of the **Module linkage function** (see picture below) in the **Module unit 1**? During compilation of **Translation unit B** (client to module linkage function contained in **Translation unit A**) it is required to validate if used symbol exists and makes sense. ![Modules](modules.svg) What's more - a function defined in **Translation unit A** happens to have the same signature as function defined in **Translation unit C**. Which function should linker pick when resolving unresolved symbol encountered in **Translation unit B**? GCC would use first symbol encountered, and it might be ODR violation. Modules however introduce **module linkage** and the same can be referenced to only from the scopes in the same module unit. We defined following implementation challenges so far: 1) Symbols from other modules should be accessible during compilation phase 2) There should be no collisions for the same functions define in different module (with module linkage) Standard does not impose any implementation way so let's examine GCC only. They introduced separate artifacts when compiled named module interfaces, partitions or header units that are read when importing. At moment of writing this article there are no tools available for inspecting content of such artifacts and documentation is lack of details. This is however logical place to put all metadata required to solve **problem 1**. Linker does not change on each cpp standard update - it barely knows about c++ standard. Linker knows about executable format at specific platform. It knows what are sections and segments and how to update references in compiled assembly to other assembly in other translation unit. Modules are not implemented in linker - the different is how linker sees function with the same signature defined in different translation units. ![Modules](modulesLinking.svg) Symbol `_ZW11moduleUnit13foov` from module 1 is different from symbol `_ZW11moduleUnit23foov` in module 2, even through function signature is the same. This ensures that it is not possible to link against symbol defined in other module, but it is perfectly fine to link against such symbol defined in the same module but in other translation unit (module partitions). ### Macros and defines are separated Preprocessor does not only textually copy-paste a code but also decides which section of text should be skipped based on combination of `#defines` and `#ifdefs`. It does not know C++ syntax - is unaware about classes and variables. Everything from its perspective is just a text. Heavy reliance on macros is highly discouraged but the fact is that still large codebases are highly depended on them. Sometimes using preprocessor is the only elegant way to solve a problem (serializing and deserializing libraries without reflection). Sometimes programmers are used to solve problems in certain ways and don't update knowledge about best practices. There are many reasons why preprocessor usage is not and will not be deprecated soon. At this point modules aim to limit macros related challenges by separation. According to proposal: "macros and preprocessor directives in a module unit should have no effect on the translation units that import it.". It basically eliminates possibility of sneaky errors as result of `#include` ordering. ![Modules](modulesDefines.svg) ### Templates Templates in standard inclusion model by default result with duplication of definitions across translation units. Every time a file template defined in an include file is copy-pasted into a translation unit following chunk of code is copy-pasted into resulting object file. Modules does not change that behaviour but give more clear semantic way of expressing implicit instantiation of a template. For C++11 the only way to avoid copy-pasting template code into multiple translation unit was to implicitly defined then in one translation unit and extern that definition in header file: ```c++ template<class Type> void execute() {} extern template void execute<int>(); ``` then the template is explicitly instantiate in corresponding cpp file: ```c++ template void execute<int>(); ``` it results with having a translation unit with assembly code that other translation units can refer to. The reference is resolved during the linkage. ![Modules](templates.svg) Executor.hpp defines template body and provides a symbol for a specialised version of the template. Corresponding cpp file contains specialization definition and as a result translation unit will contain assembly code for `execute<int>()` function. If any other translation unit refer to this version of template it will not contain its own version of assembly code because inclusion of executor.hpp file will tell compiler that this symbol is declared here and defined somewhere else (extern). Reference to the symbol will be updated during linkage. Modules provide similar functionality, but in my opinion with much nicer syntax: ```c++ export { template<class Type> void execute() {} template void execute<int>(); } ``` The syntax above provides a way to tell other modules what is available to them: 1) There is a template that can be specialised in any importing translation unit. In such case importing unit will have its own copy of assembly code. 2) There is exported function `execute<int>()` that is defined in module unit and resulting translation unit. Importing translation units will not have their own copy of assembly code. ### Reachability vs visibility Modules give a programmer correct and efficient way of defining public interface by default. It means you would have to work hard in order to mimic inefficiency of header files. Let's consider following example of a library animal: ```cpp module; #include <string> export module animal; export std::string makeSound() { return "Sound"; } ``` Client code does not have to be aware of all symbols in std::string in order to fully use the code. There is a notion of 'reachability' vs 'visibility'. In this case std::string is not visible by client code but is reachable. ```cpp import animal; int main() { auto s = makeSound(); printf("%s", s.c_str()); // .c_str() of std::string is reachable but not visible // std::string text; // will not compile unless #include <string> is added return 0; } ``` The example above shows IMHO the most important aspect of modules - efficiency by default. Only exported symbols are visible to a client module. By no means am I saying that it's good practice to provide a library that is not self-sufficient - requiring doing more than just 'import' to fully use their API. But this has to be done consciously by explicitly exporting what is needed. It helps to avoid accidental `#include` bloat!
package leetcode.editor.cn; import java.util.ArrayList; import java.util.Arrays; import java.util.List; //47、全排列 II class PermutationsIi { public static void main(String[] args) { Solution solution = new PermutationsIi().new Solution(); int[] nums = {1, 1, 2}; List<List<Integer>> lists = solution.permuteUnique(nums); System.out.println(lists); } //leetcode submit region begin(Prohibit modification and deletion) class Solution { public List<List<Integer>> permuteUnique(int[] nums) { List<List<Integer>> lists = new ArrayList<>(); ArrayList<Integer> list = new ArrayList<>(); Arrays.sort(nums); boolean[] booleans = new boolean[nums.length]; dfs(nums, 0, lists, list,booleans); return lists; } //nums:数组,n:list中的个数,lists:结果集,list:当前结果集合 private void dfs(int[] nums, int n, List<List<Integer>> lists, ArrayList<Integer> list,boolean[] visit) { if (n == nums.length) { lists.add(new ArrayList<>(list)); } else { for (int i = 0; i < nums.length; i++) { //如果i位置标记过(已加到list中) 或者 当i重复时,且i-1未标记时跳过循环(也就是两个相同的数,只有前一个访问过,才去访问后一个,确保之访问这一次) //for循环保证了从数组中从前往后一个一个取值,再用if判断条件。所以nums[i - 1]一定比nums[i]先被取值和判断。 // 如果nums[i - 1]被取值了,那vis[i - 1]会被置1,只有当递归再回退到这一层时再将它置0。 // 每递归一层都是在寻找数组对应于递归深度位置的值,每一层里用for循环来寻找。 // 所以当vis[i - 1] == 1时(回溯前进dfs)说明nums[i - 1]和nums[i]分别属于两层递归中, // 也就是我们要用这两个数分别放在数组的两个位置,这时不需要去重。 // 但是当vis[i - 1] == 0时(回溯完)说明nums[i - 1]和nums[i]属于同一层递归中(只是for循环进入下一层循环), // 也就是我们要用这两个数放在数组中的同一个位置上,这就是我们要去重的情况。 if(visit[i] || (i>0 && nums[i] == nums[i-1] && !visit[i-1])){ continue; } list.add(nums[i]); visit[i] = true; //list中加的值,则访问数组标记 dfs(nums, n + 1, lists, list,visit); //递归 list.remove(list.size() - 1); //回溯 visit[i] = false; //回溯后,值抹去,标记清除 } } } } //leetcode submit region end(Prohibit modification and deletion) }
import 'package:dominick/core/utils/sizes/responsive.dart'; import 'package:flutter/material.dart'; import '../../../../data/experience_data.dart'; import '../../../../models/formation_model.dart'; import '../widgets/icon_and_title_widet.dart'; import '../widgets/my_parcours_widget.dart'; class MyParcoursPart extends StatelessWidget { const MyParcoursPart({ super.key, }); @override Widget build(BuildContext context) { return Container( margin: EdgeInsets.symmetric( horizontal: ResponsiveSize.number( context: context, mobile: 10, tablet: 0, desktop: 0, mobileLarge: 0), vertical: 20, ), height: ResponsiveSize.number( context: context, mobile: 450, tablet: MediaQuery.sizeOf(context).height * .55, mobileLarge: MediaQuery.sizeOf(context).height * .7, desktop: 650, ), width: MediaQuery.sizeOf(context).width, child: Column( mainAxisAlignment: MainAxisAlignment.start, children: [ const BigTitileWidget( title: 'Experiences pro', svgIcon: 'mouse_icon', ), Expanded( child: ListView.builder( scrollDirection: Axis.vertical, itemBuilder: (context, index) { FormationModel formation = experienceList[index]; return MyPalmaresWidget( isSelected: false, formation: formation, // isSelected: index == selectedIndex, size: MediaQuery.sizeOf(context), ); }, itemCount: experienceList.length, ), ), ], ), ); } }
package com.example.githubuser.main import com.example.githubuser.detail.DetailUserActivity import android.app.SearchManager import android.content.Context import android.content.Intent import androidx.appcompat.app.AppCompatActivity import android.os.Bundle import android.view.Menu import android.view.MenuItem import android.view.View import android.widget.Toast import androidx.appcompat.app.AppCompatDelegate import androidx.appcompat.widget.SearchView import androidx.datastore.core.DataStore import androidx.datastore.preferences.core.Preferences import androidx.datastore.preferences.preferencesDataStore import androidx.lifecycle.ViewModelProvider import androidx.recyclerview.widget.LinearLayoutManager import com.example.githubuser.Favorite.FavoriteActivity import com.example.githubuser.model.ItemsItem import com.example.githubuser.R import com.example.githubuser.databinding.ActivityMainBinding import com.example.githubuser.setting.SettingActivity import com.example.githubuser.setting.SettingPreferences import com.example.githubuser.setting.SettingViewModel import com.example.githubuser.setting.ViewModelFactory private val Context.datastore: DataStore<Preferences> by preferencesDataStore(name = "settings") class MainActivity : AppCompatActivity() { private lateinit var binding : ActivityMainBinding private lateinit var viewModel: MainViewModel private lateinit var adapter: UserAdapter override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) binding = ActivityMainBinding.inflate(layoutInflater) setContentView(binding.root) val pref = SettingPreferences.getInstance(datastore) val mainViewModel = ViewModelProvider(this,ViewModelFactory(pref)).get( SettingViewModel::class.java ) mainViewModel.getThemeSettings().observe(this){ if (it){ AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_YES) }else{ AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_NO) } } adapter = UserAdapter() binding.apply { rvUser.layoutManager = LinearLayoutManager(this@MainActivity) rvUser.hasFixedSize() rvUser.adapter = adapter } showLoading(true) adapter.setOnItemClickCallback(object : UserAdapter.OnItemClickCallback { override fun onItemClicked(data: ItemsItem) { Intent(this@MainActivity, DetailUserActivity::class.java).also { it.putExtra(DetailUserActivity.TAG_USERNAME,data.login) it.putExtra(DetailUserActivity.TAG_ID,data.id) it.putExtra(DetailUserActivity.TAG_URL,data.avatarUrl) startActivity(it) } } }) viewModel = ViewModelProvider(this, ViewModelProvider.NewInstanceFactory()).get( MainViewModel::class.java) binding.apply { if (adapter.itemCount == 0){ viewModel.setSearch("elroi") }else{ adapter.notifyDataSetChanged() } } viewModel.getSearchUssers().observe(this,{ if(it!= null){ showLoading(false) adapter.setList(it) } }) } override fun onCreateOptionsMenu(menu: Menu): Boolean { val inflater = menuInflater inflater.inflate(R.menu.option_menu, menu) val searchManager = getSystemService(Context.SEARCH_SERVICE) as SearchManager val searchView = menu.findItem(R.id.search).actionView as SearchView searchView.setSearchableInfo(searchManager.getSearchableInfo(componentName)) searchView.queryHint = resources.getString(R.string.search_hint) searchView.setOnQueryTextListener(object : SearchView.OnQueryTextListener { override fun onQueryTextSubmit(query: String): Boolean { showLoading(true) if (query == null){ Toast.makeText(this@MainActivity, "Masukan Username", Toast.LENGTH_SHORT).show() showLoading(false) searchView.clearFocus() }else{ showLoading(true) viewModel.setSearch(query) searchView.clearFocus() } return true } override fun onQueryTextChange(newText: String): Boolean { return false } }) return true } override fun onOptionsItemSelected(item: MenuItem): Boolean { when(item.itemId){ R.id.favorite_menu ->{ Intent(this,FavoriteActivity::class.java).also { startActivity(it) } } R.id.setting_activity->{ Intent(this,SettingActivity::class.java).also{ startActivity(it) } } } return super.onOptionsItemSelected(item) } private fun showLoading(isLoading: Boolean) { if (isLoading) { binding.progressBar.visibility = View.VISIBLE binding.rvUser.visibility = View.INVISIBLE } else { binding.progressBar.visibility = View.INVISIBLE binding.rvUser.visibility = View.VISIBLE } } }
import React from 'react' import { IconButton,Menu,MenuItem } from '@mui/material'; import { AccountCircle } from '@mui/icons-material'; import { selectUser } from '../../store/userSlice'; import { useSelector } from 'react-redux'; import { Link, useNavigate } from 'react-router-dom'; const NavBar = () => { const navigate = useNavigate() const user = useSelector(selectUser) const [anchorEl, setAnchorEl] = React.useState(null); const handleMenu = (event) => { setAnchorEl(event.currentTarget); }; const handleClose = () => { setAnchorEl(null); }; return ( <div className='navbar'> <p className='navbarText'>Welcome {user?.user?.name}</p> <div className='account'> <IconButton size="large" aria-label="account of current user" aria-controls="menu-appbar" aria-haspopup="true" onClick={handleMenu} color="inherit" > <AccountCircle /> </IconButton> <Menu id="menu-appbar" anchorEl={anchorEl} anchorOrigin={{ vertical: 'top', horizontal: 'right', }} keepMounted transformOrigin={{ vertical: 'top', horizontal: 'right', }} open={Boolean(anchorEl)} onClose={handleClose} > <MenuItem onClick={handleClose}><Link style={{textDecoration: "none",color: "black"}} to="/profile">Profile</Link></MenuItem> <MenuItem onClick={()=>{ handleClose() sessionStorage.removeItem("login") return navigate("/login") }}>Logout</MenuItem> </Menu> </div> </div> ) } export default NavBar