text
stringlengths
184
4.48M
Animation ========= ![](http://docwiki.hq.unity3d.com/uploads/Main/AnimationInspector35.png) _The Animation <span class=keyword>Inspector</span>_ Properties ---------- |**_Property:_** |**_Function:_** | |:---|:---| |<span class=component>Animation</span> |The default animation that will be played when Play Automatically is enabled. | |<span class=component>Animations</span> |A list of animations that can be accessed from scripts. | |<span class=component>Play Automatically</span> |Should the animation be played automatically when starting the game? | |<span class=component>Animate Physics</span> |Should the animation interact with physics. | |<span class=component>Culling Type</span>|Determines when the animation will not be played.| |>>><span class=component>Always Animate</span>|Always animate.| |>>><span class=component>Based on Renderers</span>|Cull based on the default animation pose.| |>>><span class=component>Based on Clip Bounds</span>|Cull based on clip bounds (calculated during import), if the clip bounds are out of view, the animation will not be played.| |>>><span class=component>Based on User Bounds</span>|Cull based on bounds defined by the user, if the user-defined bounds are out of view, the animation will not be played.| See the [Animation View Guide](AnimationEditorGuide.md) for more information on how to create animations inside Unity.%% See the [Animation Import](Animations.md) page on how to import animated characters, or the [Animation Scripting](AnimationScripting.md) page on how to create animated behaviors for your game.
// SPDX-License-Identifier: MIT pragma solidity ^0.8.7; import "@openzeppelin/contracts/utils/Counters.sol"; interface OldTwitter { function getTweet( uint _id ) external view returns (string memory, string memory, address); } /** * # Features * - store the tweets in a mapping of address => Tweet * - handle the logic for when we don't receive a pic url * - Tweet consist of author, message, imageUrl */ contract Twitter { Counters.Counter public tweetsCounter; address public immutable owner; // address 123 post new tweet => addressToTweets[123][addressToCounter[123]] = Tweet => addressToCounter[123]++ mapping(address => mapping(uint => Tweet)) public addressToTweets; using Counters for Counters.Counter; mapping(address => Counters.Counter) addressToTweetId; struct Tweet { string message; string imageUrl; } event TweetCreated( address indexed tweeter, string tweetMsg, string tweetImg ); constructor() { owner = msg.sender; } // only text function postTextTweet(string memory _message) external { uint currIndex = addressToTweetId[msg.sender].current(); addressToTweetId[msg.sender].increment(); addressToTweets[msg.sender][currIndex] = Tweet({ message: _message, imageUrl: "" }); emit TweetCreated({ tweeter: msg.sender, tweetMsg: _message, tweetImg: "no-img" }); } // only image function postImageTweet(string memory _imageUrl) external { uint currIndex = addressToTweetId[msg.sender].current(); addressToTweetId[msg.sender].increment(); addressToTweets[msg.sender][currIndex] = Tweet({ message: "", imageUrl: _imageUrl }); emit TweetCreated({ tweeter: msg.sender, tweetMsg: "no-msg", tweetImg: _imageUrl }); } // text & image function postHybridTweet( string memory _message, string memory _imageUrl ) external { uint currIndex = addressToTweetId[msg.sender].current(); addressToTweetId[msg.sender].increment(); addressToTweets[msg.sender][currIndex] = Tweet({ message: _message, imageUrl: _imageUrl }); emit TweetCreated({ tweeter: msg.sender, tweetMsg: _message, tweetImg: _imageUrl }); } // * Modifers modifier OnlyOwner() { require(msg.sender == owner, "You are not the owner!"); _; } // * Contract migration of data available in https://mumbai.polygonscan.com/address/0x4B0a24db3a6e5F5247a7868C02230f8F1ba0c9D1 function migrateData(address oldTwitterAdx) external OnlyOwner { // I personally know there's only 2 tweets, so... OldTwitter oldTwitterInstance = OldTwitter(oldTwitterAdx); for (uint8 i = 0; i < 2; i++) { // get tweet data ( string memory twitMsg, string memory tweetImg, address sender ) = oldTwitterInstance.getTweet(i); // create a new one in this contract uint tweetId = addressToTweetId[sender].current(); addressToTweetId[sender].increment(); addressToTweets[sender][tweetId] = Tweet({ message: twitMsg, imageUrl: tweetImg }); emit TweetCreated({ tweeter: sender, tweetMsg: twitMsg, tweetImg: tweetImg }); } } }
import OtherUsers from '../components/other-users'; import { getUserById } from '../services/get-user-by-id'; import { getUsers } from '../services/get-users'; export async function generateStaticParams() { const users = await getUsers(); const usersIds = users.map((user) => ({ userId: user.id.toString() })); return usersIds; } export default async function UserDetailsPage({ params, }: { params: { userId: string }; }) { const user = await getUserById(params.userId); return ( <> <h2> Usuário: {user.first_name} {user.last_name} </h2> <span>{user.email}</span> <hr /> {user.body} <hr /> <h2>Outros Usuários</h2> <OtherUsers currentUserId={params.userId} /> </> ); }
import { requester } from './NuQue.requester'; import { Options, Response } from './NuQue.types'; export class NuQue { constructor(public defaults: Options = {}) { // 어떤 props도 없다면 withCredentials 설정 if (Object.keys(this.defaults).length < 1) { this.defaults.withCredentials = true; } // 어떤 header도 없다면 Request 방식 설정 if (!this.defaults.headers) { this.defaults.headers = { 'X-Requested-With': 'XMLHttpRequest', }; } } /** * 커스텀 config 옵션으로 NuQue 객체를 재생성합니다. * * @param {Options} customOptions * @return {{new(defaults:Options): NuQue}} */ public create = (customOptions?: Options) => { return new NuQue(customOptions); }; /** * default Config 수정하기 * * @desc 만약 프로퍼티를 추가하는 게 아니라 삭제하고 싶다면 '@@DEL@@' 문자열을 키에 추가해주세요. * @example * newProps = { * '@@DEL@@headers': {}, * 'headers': { * // ... * } * } * @param {Record<string, string | Record<string, string>>} newProps * @return void */ public setConfig = (newProps: Record<string, string | Record<string, string>>) => { for (const key in newProps) { if (key.includes('@@DEL@@')) { // @ts-ignore delete this.defaults[key]; continue; } // @ts-ignore this.defaults[key] = newProps[key]; } }; /** * 데이터를 가져오기 위해 특정 서버 리소스를 요청합니다. * * @template T * @param url * @param config * @return {Promise<Response<T>>} */ public get = <T>(url: string, config?: Options): Promise<Response<T>> => { return requester<T>(url, config || {}, 'get', undefined, this.defaults); }; /** * 특정 서버 리소스를 삭제합니다. * * @template T * @param url * @param config * @return {Promise<Response<T>>} */ public delete = <T>(url: string, config?: Options): Promise<Response<T>> => { return requester<T>(url, config || {}, 'delete', undefined, this.defaults); }; /** * 서버 리소스의 헤더를 요청합니다. * * @template T * @param url * @param config * @return {Promise<Response<T>>} */ public head = <T>(url: string, config?: Options): Promise<Response<T>> => { return requester<T>(url, config || {}, 'head', undefined, this.defaults); }; /** * 서버 리소스와의 통신 옵션을 설정합니다. * * @template T * @param url * @param config * @return {Promise<Response<T>>} */ public options = <T>(url: string, config?: Options): Promise<Response<T>> => { return requester<T>(url, config || {}, 'options', undefined, this.defaults); }; /** * 특정 서버 리소스를 수정합니다. 서버의 상태를 변경하거나 사이드 이펙트를 발생시킬 수 있습니다. * * @template T * @param url * @param body * @param config * @return {Promise<Response<T>>} */ public post = <T = unknown>( url: string, body?: BodyInit, config?: Options, ): Promise<Response<T>> => { return requester<T>(url, config || {}, 'post', body, this.defaults); }; /** * 서버 리소스의 모든 부분을 요청한 payload로 변경합니다. * * @template T * @param url * @param body * @param config * @return {Promise<Response<T>>} */ public put = <T = unknown>( url: string, body?: BodyInit, config?: Options, ): Promise<Response<T>> => { return requester<T>(url, config || {}, 'put', body, this.defaults); }; /** * 서버 리소스의 일부분을 수정합니다. * * @template T * @param url * @param body * @param config * @return {Promise<Response<T>>} */ public patch = <T = unknown>( url: string, body?: BodyInit, config?: Options, ): Promise<Response<T>> => { return requester<T>(url, config || {}, 'patch', body, this.defaults); }; /** * 반환된 결과값에 대한 배열 객체를 전개합니다. * * @template Args * @template R * @param fn * @return {(...args2: Args[]) => R} */ public static spread = <Args, R>(fn: (...args: Args[]) => R): ((...args2: Args[]) => R) => { // @ts-ignore return fn.apply.bind(fn, fn); }; /** * 모든 요청을 대기합니다. * * @example * import nuque from '@nextunicorn-inc/neque'; * * const result = await nuque.all([Promise.resolve('hello'), Promise.resolve('world')]).then( * nuque.spread((item1, item2) => { * return `${item1} ${item2}`; * }) * ); */ public static all = Promise.all.bind(Promise); /** * 요청에 대한 대기 시간을 제한합니다. * * @example * import nuque from '@nextunicorn-inc/neque'; * * const result = nuque.post(url, query, { * ...config, * signal: nuque.abortSignal(2000) * }); * * @see https://blog.logrocket.com/complete-guide-abortcontroller-node-js/ * @param timeoutMs * @todo aborted message 를 외부에서 입력할 수 있게 변경 */ public abortSignal = (timeoutMs = 3000) => { const abortController = new AbortController(); setTimeout(() => abortController.abort(), timeoutMs); return abortController.signal; }; } export const nuq = new NuQue();
<!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> </head> <body> <script> class Person { constructor() { this.names = ['jiabin', 'zhangiqng', 'bingbing', 'doubao']; this.age = 31; } /* 类定义语法也支持定义生成器 */ *createNameItrator() { //在原型中定义生成器 yield* ['jiabin', 'zhangiqng', 'ddoubao']; yield 'bingbing'; } static *createJobItrator() { //在类本身定义生成器 yield 'teacher'; yield 'software engineer'; yield 'student'; } /* 可以通过添加一个默认的迭代器,把实例变成是可迭代的 */ [Symbol.iterator]() { return this.names.entries(); // values()是获取值迭代器、keys()获取键的迭代器、entries()获取键/值对的迭代器 } } let p1 = new Person(); let nameIter = p1.createNameItrator(); for (const x of nameIter) { console.log(x); } let jobIter = Person.createJobItrator(); console.log(jobIter.next()); // 显式调用next()没啥意义,一般都是迭代 console.log(...p1); // 从此,对象改变了不能迭代的历史 console.log(p1[Symbol.iterator]); //对象也有了迭代接口 </script> </body> </html>
from __future__ import annotations import time from pathlib import Path from typing import List from icecream import ic def read_input(input_file: Path) -> List[str]: with input_file.open("r") as f: lines = f.readlines() return [l.strip() for l in lines] def transpose_lines(lines: List[str] | List[List[str]]) -> List[str]: new_lines = [] for row in range(len(lines[0])): new_row = "" for col in range(len(lines)): new_row += lines[col][row] new_lines.append(new_row) return new_lines def roll_rocks_by_col(row: str) -> str: if "#" in row: cube_rocks = row.count("#") row_splices = row.split("#") if row_splices[-1] == "": el = row_splices.pop() rolled_row = "" count_cubes = 0 for row_splice in row_splices: rolled_row = rolled_row + get_rolled(row_splice) if count_cubes < cube_rocks: rolled_row = rolled_row + "#" count_cubes += 1 else: rolled_row = get_rolled(row) return rolled_row def get_rolled(row_splice: str) -> str: rolled = "" round_rocks = len([n for n in row_splice if n != "."]) rolled = ("0" * round_rocks) + ("." * (len(row_splice) - round_rocks)) # ic(rolled) return rolled def get_load(rolled_rocks_lines: List[str]) -> int: load = 0 for i, row in enumerate(rolled_rocks_lines): count_round = len([r for r in row if ((r != ".") and (r != "#"))]) load += count_round * (len(rolled_rocks_lines) - i) return load if __name__ == "__main__": start_time = time.time() # lines = read_input(Path("inputs/test_input_yields_136.txt")) lines = read_input(Path("inputs/input.txt")) transposed_lines = transpose_lines(lines) rolled_rocks_lines = [] round_rocks = 0 for row in transposed_lines: rolled_row = roll_rocks_by_col(row) rolled_rocks_lines.append(rolled_row) lengths = [len(row) for row in rolled_rocks_lines] rocks_rolled_north = transpose_lines(rolled_rocks_lines) load = get_load(rocks_rolled_north) ic(load) """ Correct answer for Part 1: 105623 """ print("--- %s seconds ---" % round((time.time() - start_time), 2))
import { Component, importProvidersFrom } from '@angular/core'; import { CheckProjectFormService } from '../check-project-form.service'; import { ProjectService } from '../project.service'; import { ClientService } from '../client.service'; import { Router } from '@angular/router'; import { ClientListComponent } from '../client_list/client_list.component' import { HttpClient } from '@angular/common/http'; import { tap } from 'rxjs' @Component({ selector: 'app-project_add', templateUrl: './project_add.component.html', styleUrls: ['./project_add.component.scss'] }) export class ProjectAddComponent { name: String = ''; description: String = ''; clients: any = []; type: String = ''; experience: Number | String = '' constructor(private checkForm: CheckProjectFormService, private router: Router, private projectserv: ProjectService, private http: HttpClient) {} ngOnInit() { this.getClient() //console.log(this.clients) } /*getClient() { this.http.get<any[]>('http://localhost:8080/client/records') .subscribe(clients => this.clients = clients); }*/ getClient() { this.http.get<any[]>('http://localhost:8080/client/records') .subscribe(clients => { this.clients = clients; console.log(this.clients); }); } createProject(): any { const project = { name: this.name, description: this.description, type: this.type, experience: this.experience, } console.log(this.clients); if(!this.checkForm.checkName(project.name)) { alert("The field of name must be specified!") return false; } else if(!this.checkForm.checkDescription(project.description)) { alert("The field of number of description must be specified!") return false; } else if(!this.checkForm.checkClient(project.type)) { alert("The field of experience must be specified!") return false; }else if(!this.checkForm.checkExperience(project.experience)) { alert("The field of experience must be specified!") return false; } console.log(project) this.projectserv.addProject(project) this.router.navigate(['/project_list']); } } /*import { Component } from '@angular/core'; import { CheckProjectFormService } from '../check-project-form.service'; import { ProjectService } from '../project.service'; import { Router } from '@angular/router'; import { HttpClient } from '@angular/common/http'; import { tap } from 'rxjs' @Component({ selector: 'app-project_add', templateUrl: './project_add.component.html', styleUrls: ['./project_add.component.scss'] }) export class ProjectAddComponent { name: string = ''; description: string = ''; clients: any[] = []; experience: number | string = ''; selectedClientId: number | string = ''; constructor(private checkForm: CheckProjectFormService, private router: Router, private projectserv: ProjectService, private http: HttpClient) {} ngOnInit() { this.http.get<any[]>('http://localhost:8080/client/records') .subscribe(clients => this.clients = clients); } createProject(): any { const project = { name: this.name, description: this.description, clientId: this.selectedClientId, experience: this.experience } if(!this.checkForm.checkName(project.name)) { alert("The field of name must be specified!") return false; } else if(!this.checkForm.checkDescription(project.description)) { alert("The field of number of description must be specified!") return false; } else if(!this.checkForm.checkClient(project.clientId)) { alert("The field of experience must be specified!") return false; }else if(!this.checkForm.checkExperience(project.experience)) { alert("The field of experience must be specified!") return false; } console.log(project) this.projectserv.addProject(project) this.router.navigate(['/project_list']); } }*/ /*import { Component } from '@angular/core'; import { CheckProjectFormService } from '../check-project-form.service'; import { ProjectService } from '../project.service'; import { Router } from '@angular/router'; //import { Client } from '../client.model'; import { HttpClient } from '@angular/common/http'; import { tap } from 'rxjs/operators' @Component({ selector: 'app-project_add', templateUrl: './project_add.component.html', styleUrls: ['./project_add.component.scss'] }) export class ProjectAddComponent { name: string = ''; description: string = ''; clients: any[] = []; selectedClient:any= {}; experience: number | string = ''; constructor( private checkForm: CheckProjectFormService, private router: Router, private projectService: ProjectService, private http: HttpClient) {} async ngOnInit() { this.getClients(); } async getClients() { this.http.get<any[]>('http://localhost:8080/client/records').toPromise(); } createProject(): any { const project = { name: this.name, description: this.description, clientId: this.selectedClient.id, client: this.selectedClient, experience: this.experience } if(!this.checkForm.checkName(project.name)) { alert("The field of name must be specified!") return false; } else if(!this.checkForm.checkDescription(project.description)) { alert("The field of number of description must be specified!") return false; } else if(!this.checkForm.checkClient(project.clientId)) { alert("The field of experience must be specified!") return false; }else if(!this.checkForm.checkExperience(project.experience)) { alert("The field of experience must be specified!") return false; } console.log(project) this.projectService.addProject(project) this.router.navigate(['/project_list']); } } */
document.addEventListener("DOMContentLoaded", function () { // Create countdown element const countdownElement = document.createElement("div"); countdownElement.id = "countdown-element"; countdownElement.style.position = "absolute"; countdownElement.style.zIndex = "5"; countdownElement.style.backgroundColor = "rgba(0, 0, 0, 0.3)"; countdownElement.style.fontSize = "16px"; countdownElement.style.top = "0px"; countdownElement.style.left = "50%"; countdownElement.style.width = "20em"; countdownElement.style.marginLeft = "-10em"; countdownElement.style.padding = "10px"; countdownElement.style.borderRadius = "0px 0px 10px 10px"; countdownElement.style.textAlign = "center"; countdownElement.style.zIndex = "1000"; countdownElement.style.color = "rgb(255, 255, 255)"; countdownElement.style.boxShadow = "rgba(0, 0, 0, 0.15) 0px 10px 35px, rgba(0, 0, 0, 0.12) 0px 5px 10px"; countdownElement.style.pointerEvents = "none"; countdownElement.innerHTML = ` This demo will reset in:<br> <span id="countdown-timer"></span> `; // Append countdown element to the body document.body.appendChild(countdownElement); function updateCountdown() { const now = new Date(); const nextReset = new Date(now); nextReset.setHours(nextReset.getHours() + 1, 0, 0, 0); const timeUntilReset = nextReset - now; const hours = Math.floor(timeUntilReset / 3600000); const minutes = Math.floor((timeUntilReset % 3600000) / 60000); const seconds = Math.floor((timeUntilReset % 60000) / 1000); const timerElement = document.getElementById("countdown-timer"); timerElement.textContent = `${hours}h ${minutes}m ${seconds}s`; // When timer reaches 0, redirect to logout and clear credentials if (hours === 0 && minutes === 0 && seconds === 0) { const origin = window.location.origin; window.location.href = `${origin}/logout`; // Logout the user // Clear cached credentials if (window.localStorage) { window.localStorage.clear(); // Clear local storage } if (window.sessionStorage) { window.sessionStorage.clear(); // Clear session storage } } else { setTimeout(updateCountdown, 1000); // Update every second } } updateCountdown(); // Initial call to start the timer });
<!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"> <link rel="stylesheet" href="scss/normalize.css"> <link rel="stylesheet" href="scss/main.css"> <link rel="preconnect" href="https://fonts.googleapis.com"> <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin> <link href="https://fonts.googleapis.com/css2?family=Roboto:ital,wght@0,100;0,300;0,700;1,100&family=Shrikhand&display=swap" rel="stylesheet"> <script src="https://kit.fontawesome.com/d21300426d.js" crossorigin="anonymous"></script> <title>Le Gourmand</title> </head> <body id="animation-menu"> <!--Logo + Home button--> <header> <a href="index.html"><i class="fas fa-arrow-left"></i></a> <a href="le-gourmand.html"><img src="dist/images/logo/ohmyfood@2x.svg" alt="ohmyfood logo"></a> </header> <!--Menu section--> <section class="menu"> <img src="dist/images/restaurants/louis-hansel-shotsoflouis-qNBGVyOCY8Q-unsplash.jpg" alt="Le Gourmand restaurant"> <div class="menu-block"> <div class="menu-block__title"> <h1>Le Gourmand</h1> <i class="far fa-heart"></i> </div> <div class="menu-section"> <h2><u>ENTR</u>EES</h2> <div class="main-menu-block" id="entrees-animation"> <a class="menu-section__block"> <div class="menu-description"> <h3>Tuna Carpaccio</h3> <div class="text-block"> <span>Seasoned with yuzu</span> <b>25€</b> </div> </div> <div class="check-icon"> <i class="fas fa-check-circle"></i> </div> </a> <a class="menu-section__block"> <div class="menu-description"> <h3>Crunchy Lobster Croquets</h3> <div class="text-block"> <span>With seasonal vegetables</span> <b>35€</b> </div> </div> <div class="check-icon"> <i class="fas fa-check-circle"></i> </div> </a> <a class="menu-section__block"> <div class="menu-description"> <h3>Mushroom soup</h3> <div class="text-block"> <span>With truffles</span> <b>20€</b> </div> </div> <div class="check-icon"> <i class="fas fa-check-circle"></i> </div> </a> </div> <h2><u>MAIN</u>DISH</h2> <div class="main-menu-block" id="main-dish-animation"> <a class="menu-section__block"> <div class="menu-description"> <h3>Roas Chicken with Provincal Herbs</h3> <div class="text-block"> <span>With truffle cream</span> <b>40€</b> </div> </div> <div class="check-icon"> <i class="fas fa-check-circle"></i> </div> </a> <a class="menu-section__block"> <div class="menu-description"> <h3>Roasted Lobster</h3> <div class="text-block"> <span>With seasonal vegetables</span> <b>35€</b> </div> </div> <div class="check-icon"> <i class="fas fa-check-circle"></i> </div> </a> <a class="menu-section__block"> <div class="menu-description"> <h3>Angust Beef Ribs</h3> <div class="text-block"> <span>With mashed parsnips</span> <b>44€</b> </div> </div> <div class="check-icon"> <i class="fas fa-check-circle"></i> </div> </a> </div> <h2><u>DESS</u>ERTS</h2> <div class="main-menu-block" id="desserts-animation"> <a class="menu-section__block"> <div class="menu-description"> <h3>Assorted Dessert Plate</h3> <div class="text-block"> <span>Chef's choice</span> <b>18€</b> </div> </div> <div class="check-icon"> <i class="fas fa-check-circle"></i> </div> </a> <a class="menu-section__block"> <div class="menu-description"> <h3>Crème Brulée</h3> <div class="text-block"> <span>Revisted</span> <b>22€</b> </div> </div> <div class="check-icon"> <i class="fas fa-check-circle"></i> </div> </a> <a class="menu-section__block"> <div class="menu-description"> <h3>Tiramisu</h3> <div class="text-block"> <span>With hazelnuts</span> <b>23€</b> </div> </div> <div class="check-icon"> <i class="fas fa-check-circle"></i> </div> </a> </div> </div> <button id="order-button" type="button">Order</button> </div> </section> <!--Footer--> <footer> <div class="footer-block"> <h1>ohmyfood</h1> <ul> <li><a href="#"><i class="fas fa-utensils"></i>Suggest a restaurant</a></li> <li><a href="#"><i class="fas fa-hands-helping"></i>Become a partner</a></li> <li><a href="#">Legal</a></li> <li><a href="mailto:placeholderemail@placeholder.com">Contact</a></li> </ul> </div> </footer> </body> </html>
package br.erbatista.brpackstest; import br.erbatista.brpackstest.entity.ModEntityRegister; import br.erbatista.brpackstest.item.ModItems; import br.erbatista.brpackstest.render.ColheitadeiraRender; import net.minecraft.block.Blocks; import net.minecraftforge.api.distmarker.Dist; import net.minecraftforge.api.distmarker.OnlyIn; import net.minecraftforge.common.MinecraftForge; import net.minecraftforge.eventbus.api.IEventBus; import net.minecraftforge.eventbus.api.SubscribeEvent; import net.minecraftforge.fml.client.registry.RenderingRegistry; import net.minecraftforge.fml.common.Mod; import net.minecraftforge.fml.event.lifecycle.FMLClientSetupEvent; import net.minecraftforge.fml.event.lifecycle.FMLCommonSetupEvent; import net.minecraftforge.fml.javafmlmod.FMLJavaModLoadingContext; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import software.bernie.geckolib3.GeckoLib; // The value here should match an entry in the META-INF/mods.toml file @Mod(BrPacksTest.MOD_ID) public class BrPacksTest { // Directly reference a log4j logger. private static final Logger LOGGER = LogManager.getLogger(); public static final String MOD_ID = "brpackstest"; public BrPacksTest() { GeckoLib.initialize(); // Register the setup method for modloading IEventBus modEventBus = FMLJavaModLoadingContext.get().getModEventBus(); ModEntityRegister.register(modEventBus); ModItems.register(modEventBus); modEventBus.addListener(this::setup); // Register the doClientStuff method for modloading modEventBus.addListener(this::doClientStuff); // Register ourselves for server and other game events we are interested in MinecraftForge.EVENT_BUS.register(this); } private void setup(final FMLCommonSetupEvent event) { // some preinit code LOGGER.info("HELLO FROM PREINIT"); LOGGER.info("DIRT BLOCK >> {}", Blocks.DIRT.getRegistryName()); } private void doClientStuff(final FMLClientSetupEvent event) { // do something that can only be done on the client LOGGER.info("Got game settings {}", event.getMinecraftSupplier().get().options); registerRenderers(event); } @OnlyIn(Dist.CLIENT) @SubscribeEvent public void registerRenderers(final FMLClientSetupEvent event) { RenderingRegistry.registerEntityRenderingHandler(ModEntityRegister.COLHEITADEIRA.get(), manager -> new ColheitadeiraRender(manager)); } }
<template> <AppModal v-slot="{ close }" :title="$t('errors.logs')" no-padding header-border > <ol> <li v-for="(log, index) in $errors.logs" :key="index" class="flex justify-between max-w-prose border-b px-4 py-2 mb-2 last:border-b-0 last:mb-0" > <div> <h3 class="font-medium"> {{ log.report.title }} </h3> <time :datetime="log.date.toISOString()" class="text-xs text-gray-700"> {{ renderDate(log.date) }} </time> <CoreMarkdown v-if="log.report.description" :text="log.report.description" /> </div> <CoreButton clear :aria-label="$t('errors.viewDetails')" :title="$t('errors.viewDetails')" @click="$ui.openModal(ErrorReportModal, { reports: [log.report] }), close()" > <i-zondicons-view-show class="w-4 h-4" aria-hidden="true" /> </CoreButton> </li> </ol> </AppModal> </template> <script setup lang="ts"> import { onMounted } from 'vue'; import { translate } from '@/framework/utils/translate'; import ErrorReportModal from '@/components/modals/ErrorReportModal.vue'; import Errors from '@/framework/core/facades/Errors'; const now = Date.now(); function renderDate(date: Date): string { const seconds = Math.round((now - date.getTime()) / 1000); if (seconds > 60) { return translate('time.minutesAgo', { minutes: Math.round(seconds / 60) }); } return translate('time.secondsAgo', { seconds }); } onMounted(() => Errors.seeAll()); </script>
### ---------------------------------------------- ### ### -------- Compute distance matrices ----------- ### ### ---------------------------------------------- ### # ____________________________ # date created: 29.04.22 # date last modified: 03.05.22 # Project: Evaluating European Broad River Types for Macroinvertebrates # Purpose: Compute distance tables #___________________________ # setup ----------------------------------------------------------------------------- library(pacman) p_load( parallelDist, data.table, tidyr, dplyr, rstudioapi ) x<-getActiveDocumentContext() sink(file = paste0("R/02_combined_data/log_files/005","_", Sys.Date(), "_", "log.txt")) Sys.Date() x$path sessionInfo() sink(file = NULL) rm(x) # load data ------------------------------------------------------------------------- data.all <- readRDS("data/02_combined_data/03_2022-05-04_core_taxa_data_aggregated.rds") sites <- lapply(data.all, function(x) unique(x, by = "gr_sample_id")) rbindlist(sites) # prepare data ---------------------------------------------------------------------- #- extract seasons into indivudal objects from list "data.all" data.spring <- setDT(data.all[[1]]) data.summer <- setDT(data.all[[2]]) data.autumn <- setDT(data.all[[3]]) data.spring <- data.spring[, c("brt12", "bgr", "ife", "gr_sample_id", "family", "abundance2", "least.impacted")] data.summer <- data.summer[, c("brt12", "bgr", "ife", "gr_sample_id", "family", "abundance2", "least.impacted")] data.autumn <- data.autumn[, c("brt12", "bgr", "ife", "gr_sample_id", "family", "abundance2", "least.impacted")] data.spring <- unique(data.spring, by = c("gr_sample_id", "family")) data.summer <- unique(data.summer, by = c("gr_sample_id", "family")) data.autumn <- unique(data.autumn, by = c("gr_sample_id", "family")) sites.spring <- unique(data.spring, by = "gr_sample_id") sites.summer <- unique(data.summer, by = "gr_sample_id") sites.autumn <- unique(data.autumn, by = "gr_sample_id") data.spring2 <- pivot_wider(data.spring, id_cols = "gr_sample_id", names_from = "family", values_from = "abundance2", values_fill = 0) data.summer2 <- pivot_wider(data.summer, id_cols = "gr_sample_id", names_from = "family", values_from = "abundance2", values_fill = 0) data.autumn2 <- pivot_wider(data.autumn, id_cols = "gr_sample_id", names_from = "family", values_from = "abundance2", values_fill = 0) id1 <- data.spring2 |> select("gr_sample_id") |> left_join(sites.spring) |> select(brt12, bgr, ife) |> rename(brt = brt12) id2 <- data.summer2 |> select("gr_sample_id") |> left_join(sites.summer) |> select(brt12, bgr, ife) |> rename(brt = brt12) id3 <- data.autumn2 |> select("gr_sample_id") |> left_join(sites.autumn) |> select(brt12, bgr, ife) |> rename(brt = brt12) ids <- list(sp.i = id1, su.i = id2, au.i = id3 ) # compute distance matrices --------------------------------------------------------- spring.dist <- parallelDist(as.matrix(data.spring2[,-1]), method = "binary", threads = 8) summer.dist <- parallelDist(as.matrix(data.summer2[,-1]), method = "binary", threads = 8) autumn.dist <- parallelDist(as.matrix(data.autumn2[,-1]), method = "binary", threads = 8) # save to file ---------------------------------------------------------------------- #- community data saveRDS(data.spring2, paste0("data/02_combined_data/04_",Sys.Date(), "_community_data_spring.rds")) saveRDS(data.summer2, paste0("data/02_combined_data/04_",Sys.Date(), "_community_data_summer.rds")) saveRDS(data.autumn2, paste0("data/02_combined_data/04_",Sys.Date(), "_community_data_autumn.rds")) #- distance matrices saveRDS(spring.dist, paste0("data/02_combined_data/04_", Sys.Date(), "_distance_spring.rds")) saveRDS(summer.dist, paste0("data/02_combined_data/04_", Sys.Date(), "_distance_summer.rds")) saveRDS(autumn.dist, paste0("data/02_combined_data/04_", Sys.Date(), "_distance_autumn.rds")) #- ids saveRDS(ids, paste0("data/02_combined_data/04_",Sys.Date(),"_distance_ids.rds"))
import { useState } from 'react'; import "./App.scss"; import classNames from 'classnames'; const options = { 'htmlcss': 40000, 'javascript': 50000, 'react': 60000, 'node': 65000 } export default function App() { const [users, setUsers] = useState([]); const [currentUserID, setcurrentUserID] = useState(null) const handleSubmit = (e) => { e.preventDefault(); const { username, password, teacher, language } = e.target; const user = { id: Date.now(), username: username.value, password: password.value, teacher: teacher.value, language: language.value, } setUsers([...users, user]) } const handleClick = (userId) => { if (userId === currentUserID) { setcurrentUserID(null) } else { setcurrentUserID(userId) } } const total = () => { return users.reduce((acc, cv) => acc + options[cv.language], 0) } return ( <div className='container'> <form onSubmit={handleSubmit}> <div className='form-group'> <label htmlFor="username">username</label> <input type="text" id='username' name='username' /> </div> <div className='form-group'> <label htmlFor="password">password</label> <input type="password" id='password' name='password' /> </div> <div className='form-group'> <label htmlFor="teacher">select your teacher</label> <select name="teacher" id="teacher" defaultValue={"Emil"}> <option value="Hayk">Hayk</option> <option value="Zmruxt">Zmruxt</option> <option value="Emil">Emil</option> <option value="Edgar">Edgar</option> </select> </div> <div className='form-group form-group_check'> <label htmlFor="Html&css"> <input type="radio" name='language' value="htmlcss" id='Html&css' /> <span>Html&css</span> </label> <label htmlFor="js"> <input type="radio" name='language' value="javascript" id='js' /> <span>Javascript</span> </label> <label htmlFor="React"> <input type="radio" name='language' value="react" id='React' /> <span>React.js</span> </label> <label htmlFor="Node"> <input type="radio" name='language' value="node" id='Node' /> <span>Node.js</span> </label> </div> <div className="form-group"> <input type="submit" value="add user" /> </div> </form> <div className="users"> <table> <thead> <tr> <th>id</th> <th>username</th> <th>password</th> <th>teacher</th> <th>language</th> </tr> </thead> <tbody> {users.map(elem => { return ( <tr key={elem.id} className={classNames({ [`color-${elem.language}`]: true })}> <td>{elem.id % 1e4}</td> <td>{elem.username}</td> <td className='pass'> {currentUserID === elem.id ? elem.password : "*".repeat(10)} <i className={classNames("fa-solid", { 'fa-eye': currentUserID !== elem.id, 'fa-eye-slash': currentUserID === elem.id })} onClick={() => handleClick(elem.id)}></i> </td> <td>{elem.teacher}</td> <td>{elem.language}</td> </tr> ) })} </tbody> <tfoot> {users.length > 0 && <tr> <td colSpan={5}> {total()} դրամ </td> </tr> } </tfoot> </table> </div> </div> ) }
import 'dart:convert'; class Product { Product({ this.id, required this.available, required this.name, this.picture, required this.price, }); String? id; bool available; String name; String? picture; double price; factory Product.fromJson(String str) => Product.fromMap(json.decode(str)); String toJson() => json.encode(toMap()); factory Product.fromMap(Map<String, dynamic> json) => Product( available : json["available"], name : json["name"], picture : json["picture"], price : json["price"].toDouble(), ); Map<String, dynamic> toMap() => { "available": available, "name": name, "picture": picture, "price": price, }; Product copy() => Product( available : available, picture : picture, price : price, name : name, id : id, ); }
import React, { useEffect, useState } from 'react' import { Container, ContainerItems,ContainerTotal } from './style' import Button from '../Button' import formatCurrency from '../../utils/formatCurrency' import { useCard } from '../../hooks/CardContext' import api from '../../services/api' import { toast } from 'react-toastify'; import { useNavigate } from 'react-router-dom' function CartResume() { const [finalPrice , setFinalPrice] = useState(0) const [deliveryTax, setDeliveryTax] = useState(5) const navigate= useNavigate() const {CardData} = useCard() useEffect(() => { const sumAllItems = CardData.reduce((acc, current) => { return current.price * current.quantity + acc }, 0) setFinalPrice(sumAllItems) },[CardData, deliveryTax]) const submitOrder = async () => { try { const order = CardData.map(product => { return {id: product.id , quantity: product.quantity} }) await api.post('orders', {products: order}) toast.success('Pedido Finalizado com sucesso', { position: "top-right", autoClose: 1380, hideProgressBar: false, closeOnClick: true, pauseOnHover: true, draggable: true, progress: undefined, theme: "colored", }); setTimeout(() => { navigate('/') },2000) } catch (error) { toast.error('Deu algum erro com seu Pedido', { position: "top-right", autoClose: 1380, hideProgressBar: false, closeOnClick: true, pauseOnHover: true, draggable: true, progress: undefined, theme: "colored", }); } } return ( <div> <Container> <ContainerItems> <h2 className='title'>Resumo do pedido</h2> <p className='items'>Items</p> <p className='itemsPrice'>{formatCurrency(finalPrice)}</p> <p className='taxe'>Taxa de entrega</p> <p className='taxePrice'>{formatCurrency(deliveryTax)}</p> </ContainerItems> <ContainerTotal> <p>Total</p> <p>{formatCurrency(finalPrice + deliveryTax)}</p> </ContainerTotal> </Container> <Button style={{width: "100%", marginTop: "30"}} onClick={submitOrder}>Finalizar Pedido</Button> </div> ) } export default CartResume
/******************************************************************************* * Copyright (c) 2016 Cisco and/or its affiliates * @author Matt Day * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. *******************************************************************************/ package com.cisco.matday.ucsd.hp3par.tasks.cpg; import com.cisco.matday.ucsd.hp3par.account.HP3ParCredentials; import com.cisco.matday.ucsd.hp3par.constants.HP3ParConstants; import com.cisco.matday.ucsd.hp3par.exceptions.HP3ParCpgException; import com.cisco.matday.ucsd.hp3par.rest.json.HP3ParRequestStatus; import com.cloupia.service.cIM.inframgr.AbstractTask; import com.cloupia.service.cIM.inframgr.TaskConfigIf; import com.cloupia.service.cIM.inframgr.TaskOutputDefinition; import com.cloupia.service.cIM.inframgr.customactions.CustomActionLogger; import com.cloupia.service.cIM.inframgr.customactions.CustomActionTriggerContext; /** * Create cpg implementation task * * @author Matt Day * */ public class CreateCpgTask extends AbstractTask { @Override public void executeCustomAction(CustomActionTriggerContext context, CustomActionLogger ucsdLogger) throws Exception { CreateCpgConfig config = (CreateCpgConfig) context.loadConfigObject(); HP3ParCredentials c = new HP3ParCredentials(config.getAccount()); // HP3ParRequestStatus s = HP3ParCopyExecute.copy(c, config); HP3ParRequestStatus s = HP3ParCpgExecute.create(c, config); if (!s.isSuccess()) { ucsdLogger.addError("Failed to create CPG: " + s.getError()); throw new HP3ParCpgException("Failed to create CPG: " + s.getError()); } ucsdLogger.addInfo("Created cpg"); context.getChangeTracker().undoableResourceAdded("assetType", "idString", "CPG created", "Undo creation of cpg: " + config.getCpgName(), DeleteCpgConfig.DISPLAY_LABEL, new DeleteCpgConfig(config)); // Construct Cpg name in the format: // id@Account@Volume // Don't know the volume so just use 0 as a workaround String cpgName = "0@" + config.getAccount() + "@" + config.getCpgName(); context.saveOutputValue(HP3ParConstants.CPG_LIST_FORM_LABEL, cpgName); } @Override public TaskConfigIf getTaskConfigImplementation() { return new CreateCpgConfig(); } @Override public String getTaskName() { return CreateCpgConfig.DISPLAY_LABEL; } @Override public TaskOutputDefinition[] getTaskOutputDefinitions() { TaskOutputDefinition[] ops = { // Register output type for the volume created new TaskOutputDefinition(HP3ParConstants.CPG_LIST_FORM_LABEL, HP3ParConstants.CPG_LIST_FORM_TABLE_NAME, HP3ParConstants.CPG_LIST_FORM_LABEL), }; return ops; } }
<template> <el-dialog class="user-settings-popup" title="Settings" v-model="isShowing"> <el-form v-model="settings"> <el-form-item label="Auto save"> <el-switch v-model="settings.autoSave"/> </el-form-item> <el-form-item label="Theme"> <el-radio-group v-model="settings.theme"> <el-radio label="dark"> <el-icon> <Moon/> </el-icon> </el-radio> <el-radio label="light"> <el-icon> <Sunny/> </el-icon> </el-radio> </el-radio-group> </el-form-item> <el-form-item label="Build Index"> <el-button @click="rebuildIndex"><el-icon><Refresh/></el-icon></el-button> </el-form-item> <el-form-item label="Download Backup"> <el-button @click="downloadBackup"><arrow-down></arrow-down></el-button> </el-form-item> </el-form> <template #footer> PixlWiki Version <span @click="showVersionsPopup">{{ version }}</span> | <span @click="logout">Logout</span> </template> </el-dialog> </template> <script lang="ts"> import {defineComponent, h, watch} from "vue"; import {useDialogStore} from "@/src/stores/dialog"; import {useUserSettings} from "@/src/stores/user-settings"; import {useMainStore} from "@/src/stores/main"; import {Sunny, Moon, Refresh, ArrowDown} from "@element-plus/icons-vue"; import {ElMessageBox, ElNotification} from "element-plus"; import {useAuthStore} from "@/src/stores/auth"; import {useWikiStore} from "@/src/stores/wiki"; const route = '/settings'; export default defineComponent({ components: { Moon, Sunny, Refresh, ArrowDown, }, data() { return { dialogStore: useDialogStore(), userSettings: useUserSettings(), settings: useUserSettings().getSettings, } }, created() { watch(this.settings, (value) => { this.userSettings.updateSettings(value); this.setTheme(value.theme); }); }, computed: { version() { return useMainStore().meta.frontendVersion; }, isShowing: { get() { return route === this.dialogStore.getShowingDialog; }, set() { this.dialogStore.clearShowingDialog(); } }, }, methods: { downloadBackup() { this.userSettings.downloadBackup(); }, rebuildIndex() { useWikiStore().rebuildIndex().then(response => { ElNotification({ title: 'Rebuild Index', message: 'Built in ' + Math.round(response.data.indexTime * 1000) + "ms", }); }) }, logout() { useAuthStore().logout(); useWikiStore().loadNav(); }, setTheme(theme: string) { document.documentElement.classList.remove('light'); document.documentElement.classList.remove('dark'); document.documentElement.classList.add(theme); }, showVersionsPopup() { ElMessageBox({ title: 'Version Information', message: h('ul', null, [ h('li', null, 'Plugin Version: '+ useMainStore().meta.pluginVersion), h('li', null, 'CMS Version: '+ useMainStore().meta.cmsVersion), h('li', null, 'Frontend Version: '+ useMainStore().meta.frontendVersion), ]), }) }, }, }) </script> <style lang="scss"> .user-settings-popup footer { width: 100%; text-align: center; color: grey; font-style: italic; font-size: 0.8rem; } </style>
package com.nur.command.commend.get; import builder.CommendDTOBuilder; import builder.CommendPersonDTOBuilder; import com.nur.dtos.CommendDTO; import com.nur.dtos.CommendPersonDTO; import com.nur.model.Commend; import com.nur.model.CommendPerson; import com.nur.repositories.ICommendPersonRepository; import com.nur.repositories.ICommendRepository; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.mockito.Mock; import org.mockito.MockitoAnnotations; import java.util.UUID; import static org.junit.jupiter.api.Assertions.*; import static org.mockito.Matchers.any; import static org.mockito.Mockito.when; class GetCommendPersonHandlerTest { @Mock private ICommendPersonRepository commendRepository; @BeforeEach void setUp() { MockitoAnnotations.initMocks(this); } @Test void testCreateHandler() { assertDoesNotThrow(() -> { CommendPersonDTO commendJpa = new CommendPersonDTOBuilder().build(); CommendPerson commendDomain = new CommendPerson(UUID.randomUUID(), "Bueno", "Lo que sea", "Cristhian", 3); GetCommendPersonQuery query = new GetCommendPersonQuery(String.valueOf(UUID.randomUUID())); when(commendRepository.getById(any())).thenReturn(commendDomain); GetCommendPersonHandler handler = new GetCommendPersonHandler(commendRepository); CommendPersonDTO response = handler.handle(query); assertNotNull(response); assertEquals(commendJpa.getValoration(), response.getValoration()); assertEquals(commendJpa.getDescription(), response.getDescription()); assertEquals(commendJpa.getPerson(), response.getPerson()); assertEquals(commendJpa.getPoints(), response.getPoints()); assertNotNull(response.getUserId()); }); } }
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* philo.h :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: omer/baha <oolkay/acepni@gtu.xv6> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2023/10/04 15:16:11 by omer/baha #+# #+# */ /* Updated: 2023/10/07 12:16:08 by omer/baha ### ########.fr */ /* */ /* ************************************************************************** */ #ifndef PHILO_H # define PHILO_H # define EAT "\033[1;93mis eating 🍝\033[0;39m\n" # define SLEEP "\033[1;95mis sleeping 🌙\033[0;39m\n" # define THINK "\033[1;90mis thinking 💭\033[0;39m\n" # define TAKE_FORK "\033[1;94mhas taken a fork 🍴\033[0;39m\n" # define DIE "\033[1;91mdied 💀\033[0;39m\n" # include <pthread.h> typedef struct s_philo t_philo; typedef struct s_table { int nb_philo; int time_to_die; int time_to_eat; int time_to_sleep; long start_time; int nb_eat; int dead; pthread_mutex_t *fork_mutex; pthread_mutex_t print_mutex; pthread_mutex_t dead_mutex; pthread_mutex_t nb_eat_mutex; pthread_mutex_t last_eat_mutex; pthread_t monitor; t_philo *philo; } t_table; struct s_philo { int id; int nb_eat; long last_eat; t_table *table; pthread_t thread; }; void *routine(void *arg); int ft_init_philo(t_table *table); int ft_check_dead_philo(t_table *table); int ft_init_table(t_table *table, int argc, char **argv); int ft_print(t_philo *philo, char *str); long philo_get_time(void); int ft_atoi(const char *str); void *monitor(t_table *table); int ft_eat_goal(t_table *table); void my_sleep(long long time); #endif
<!-- GrantCard --> <template> <figure class="group cursor-pointer" @click=" pushRoute({ name: 'dgrants-id', params: { id: id.toString() }, query: roundAddress && roundName ? { roundAddress: roundAddress, roundName: roundName } : {}, }) " > <!--img--> <div class="relative"> <!--img--> <div class="aspect-w-16 aspect-h-9 shadow-light"> <LogoPtrImage :logoPtr="logoPtr" class="w-full h-full object-center object-cover group-hover:opacity-90" placeholder="/placeholder_grant.svg" /> </div> <!--cart button--> <div class="absolute bottom-0 right-0"> <template v-if="idList && idList.includes(id)"> <button class="btn opacity-100 md:opacity-0 group-hover:opacity-100" :class="{ 'in-cart': isInCart(id) }" @click.stop="isInCart(id) ? removeFromCart(id) : addToCart(id)" > <CartIcon /> </button> </template> </div> </div> <figcaption class="mt-4"> <div class="truncate">{{ name }}</div> <div> <span class="text-grey-400" >by <a class="link ml-1" :href="getEtherscanUrl(ownerAddress, 'address')" target="_blank" rel="noopener noreferrer" >{{ formatAddress(ownerAddress) }} </a> </span> </div> <div> <span class="text-grey-400">Raised:</span><span class="ml-1">{{ raised }}</span> </div> </figcaption> </figure> </template> <script lang="ts"> import { computed, defineComponent, PropType, ref } from 'vue'; import { MetaPtr } from '@dgrants/types'; // --- Components --- import LogoPtrImage from 'src/components/LogoPtrImage.vue'; // --- Store --- import useCartStore from 'src/store/cart'; import useDataStore from 'src/store/data'; // --- Methods and Data --- import { filterContributionsByGrantId } from 'src/utils/data/contributions'; import { formatNumber, formatAddress, getEtherscanUrl, pushRoute } from 'src/utils/utils'; // --- Icons --- import { Cart2Icon as CartIcon } from '@fusion-icons/vue/interface'; function getTotalRaised(grantId: number) { const { grantRounds, grantContributions } = useDataStore(); const contributions = filterContributionsByGrantId(grantId, grantContributions.value); const raised = `${formatNumber( contributions.reduce((total, contribution) => contribution?.amount + total, 0), 2 )} ${grantRounds.value && grantRounds.value[0] && grantRounds.value[0].donationToken.symbol}`; return raised; } export default defineComponent({ name: 'GrantCard', props: { id: { type: Number, required: true }, name: { type: String, required: true }, logoPtr: { type: Object as PropType<MetaPtr>, required: false }, ownerAddress: { type: String, required: true }, roundAddress: { type: String, default: '' }, roundName: { type: String, default: '' }, }, components: { CartIcon, LogoPtrImage }, setup(props) { const grantId = ref<number>(props.id); const raised = computed(() => getTotalRaised(grantId.value)); const { addToCart, isInCart, removeFromCart } = useCartStore(); const { approvedGrantsPk: idList } = useDataStore(); return { addToCart, removeFromCart, isInCart, formatAddress, getEtherscanUrl, pushRoute, raised, idList, }; }, }); </script>
import { ComponentFixture, TestBed } from '@angular/core/testing'; import { FontAwesomeModule } from '@fortawesome/angular-fontawesome'; import { NavBarComponent } from "./nav-bar.component"; describe(NavBarComponent.name, () => { let fixture!: ComponentFixture<NavBarComponent>; let component!: NavBarComponent; beforeEach(async () => { await TestBed.configureTestingModule({ declarations: [NavBarComponent], imports: [FontAwesomeModule] }).compileComponents(); fixture = TestBed.createComponent(NavBarComponent); component = fixture.componentInstance; }); it('Should create', () => { expect(component).toBeTruthy(); }); it('Should init (@Input navBar) with undefined', () => { const navBar = component.navBar; expect(navBar).toBeUndefined(); }); it('(D) Should init role property value with menubar', () => { const nav: HTMLElement = fixture.nativeElement.querySelector('nav'); expect(nav.role).toBe('menubar'); }); });
const fs = require("fs"); const knex_mariaDB = require("../DB/config/mariaDB"); const knex_sqliteDB = require("../DB/config/sqliteDB"); class Contenedor { constructor(nombre, posicion, DB) { this._DB = DB; if (this._DB !== "JSON") { this.tablename = nombre; } else { this.pathname = `./public/data/${nombre}.json`; this.posicion = posicion; // recupera los datos del txt y lo convierte en un array de objetos try { this.json = JSON.parse(fs.readFileSync(this.pathname, "utf-8")); } catch (error) { this.json = null; } } } async save(obj) { obj.timestamp = Date.now(); obj.feccarga = new Date() .toISOString() .replace(/T/, " ") .replace(/\..+/, "") .replace(/-/g, "/"); if (this._DB !== "JSON") { if (this._DB=== "SqliteDB") { return await knex_sqliteDB(this.tablename).insert(obj); } return await knex_mariaDB(this.tablename).insert(obj); } obj.id = Date.now(); // lee el archivo, si existe recupera un array con objetos y le agrega el nuevo. if (this.json) { if (this.posicion === "ultimo") { this.json.unshift(obj); } else { this.json.push(obj); } this.escribirArchivo(this.json); return obj.id; } // si no existe el json u no tiene datos crea un nuevo array de objetos this.escribirArchivo([obj]); return obj.id; } async getById(id) { if (this._DB !== "JSON") { if (this._DB=== "SqliteDB") { return await knex_sqliteDB(this.tablename) .select("*") .where({ id: id }); } return await knex_mariaDB(this.tablename).select("*").where({ id: id }); } if (this.json) { const obj = this.json.find((e) => e.id === id); if (obj) return obj; } return null; } async getAll() { if (this._DB !== "JSON") { if (this._DB=== "SqliteDB") { return await knex_sqliteDB(this.tablename).select("*"); } return await knex_mariaDB(this.tablename).select("*"); } return this.json ? this.json : []; } async deleteById(id) { if (this._DB !== "JSON") { if (this._DB=== "SqliteDB") { return await knex_sqliteDB(this.tablename).where({ id: id }).del(); } return await knex_mariaDB(this.tablename).where({ id: id }).del(); } if (this.json) { this.json = this.json.filter((e) => e.id !== id); this.escribirArchivo(this.json); } return "No hay datos en el archivo"; } deleteAll() { this.escribirArchivo(""); } escribirArchivo(dato) { dato = dato ? JSON.stringify(dato) : ""; try { fs.writeFileSync(this.pathname, `${dato}`); } catch (error) { return `Error al escribir el archivo: ${error}`; } } // Funciones exclusivas de manejo de productos en el carro async saveProds_xcarro(idcarro, prod) { const list_carros = await this.getAll(); const indexCarro = list_carros.findIndex((e) => e.id === idcarro); list_carros[indexCarro].productos.push(prod); this.escribirArchivo(list_carros); } async getProds_xcarro(idcarro) { const list_carros = await this.getAll(); let obj_carro = { productos: [], }; if (list_carros.length > 0) { obj_carro = list_carros.find((e) => e.id === +idcarro); } return obj_carro ? obj_carro.productos : []; } async deleteProd_xcarro(idcarro, id_prod) { const list_carros = await this.getAll(); const obj_carro = list_carros.find((e) => e.id === idcarro); obj_carro.productos = obj_carro?.productos.filter((e) => e.id !== id_prod); this.escribirArchivo(list_carros); } } module.exports = Contenedor;
function Weight = calculate_baselineEmptyWeight(ACFT) % Function: % calculate_baselineEmptyWeight(ACFT) % % Description: % Calculates the empty weight of the aircraft without propulsion and fuel % system % Also calculates the fuelTankSystem weight for the baseline, parallel % and series hybrids % % Input: % ACFT - In particular need EW, engine specific power, % power and fuel quantity % Output: % Weight - Baseline Empty Weight in kg % Copy the weight structure Weight = ACFT.Weight; % Unwrap the structure ACFT EW_kg = ACFT.Weight.EW_kg; icePistonSpecificPower_kWkg = ACFT.Weight.icePistonSpecificPower_kWkg; maxPower_kW = ACFT.Propulsion.maxPower_kW; maxFuelVolume_m3 = ACFT.EnergyStorage.Baseline.maxFuelVolume_m3; engineNum = ACFT.engineNum; % Calculate the engine and tank weight engineWeight_kg = maxPower_kW/icePistonSpecificPower_kWkg; fuelTankSystem_kg= calculate_fuelTankWeight(maxFuelVolume_m3,engineNum); % Calculate the BEW baselineEmpty_kg = EW_kg - engineWeight_kg - fuelTankSystem_kg; Weight.baselineEmpty_kg = baselineEmpty_kg; Weight.fuelTankSystem_kg = fuelTankSystem_kg; end
package ru.mirea.shchukin.serviceapp; import android.Manifest; import android.content.Intent; import android.content.pm.PackageManager; import android.os.Bundle; import android.util.Log; import android.view.View; import androidx.appcompat.app.AppCompatActivity; import androidx.core.app.ActivityCompat; import androidx.core.content.ContextCompat; import ru.mirea.shchukin.serviceapp.databinding.ActivityMainBinding; public class MainActivity extends AppCompatActivity { ActivityMainBinding binding; private int PermissionCode = 200; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); binding = ActivityMainBinding.inflate(getLayoutInflater()); View view = binding.getRoot(); setContentView(view); if (ContextCompat.checkSelfPermission(this, Manifest.permission.POST_NOTIFICATIONS) == PackageManager.PERMISSION_GRANTED) { Log.d(MainActivity.class.getSimpleName(), "Разрешения получены"); } else { Log.d(MainActivity.class.getSimpleName(), "Нет разрешений"); ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.POST_NOTIFICATIONS, Manifest.permission.FOREGROUND_SERVICE}, PermissionCode); } binding.playButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent serviceIntent = new Intent(MainActivity.this, PlayerService.class); ContextCompat.startForegroundService(MainActivity.this, serviceIntent); } }); binding.pauseButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { stopService(new Intent(MainActivity.this, PlayerService.class)); } }); } }
package ant_colony import graph.Node import kotlin.math.pow /** * Класс для описания муравья * @property id Уникальное строковое значение для каждого муравья */ data class Ant(val id: String) { /** * Функция для создания пути движения муравья * @param graph Граф, по рёбрам которого перемещается муравей * @param startNode Начальная и конечная вершина движеняи муравья * @param proximityCoefficient Коэффициент близости вершин * @param alpha Коэффициент, показывающий насколько сильно муравьи при переходе будут обращать внимание на кол-во феромона * @param beta Коэффициент, показывающий насколько сильно муравьи при переходе будут обращать внимание на длину ребра * @return Список рёбер, по которым прошёл муравей */ fun getPath( graph: PheromoneGraph<Double>, startNode: Node, proximityCoefficient: Double, alpha: Double, beta: Double ): MutableList<PheromoneEdge<Double>> { // Набор посещённых рёбер val visitedEdgeIds = mutableSetOf<String>() /** * Получение ребра, по которому муравей пройдёт дальше * @param currentNode Вершина, в которой сейчас находится муравей * @return Ребро, по которому муравью следует продолжить движение */ fun getNextEdge(currentNode: Node): PheromoneEdge<Double> { // получение списка всех возможных рёбер var suitableEdges = graph.getEdgesFrom(currentNode) val notVisitedSuitableEdges = suitableEdges.filter { !visitedEdgeIds.contains(it.id) } if (notVisitedSuitableEdges.isNotEmpty()) { suitableEdges = notVisitedSuitableEdges } // общее желание муравья val totalDesire = suitableEdges.sumOf { it.pheromoneCount.pow(alpha) * (proximityCoefficient / it.weight).pow(beta) } // случайное значение из промежутка от 0 до 1 val randomValue = Math.random() var sum = 0.0 for (edge in suitableEdges) { // вычисляем желание муравья пройти по данной ветке sum += (edge.pheromoneCount.pow(alpha) * (proximityCoefficient / edge.weight).pow(beta)) / totalDesire // проверяем не было ли выбрано это ребро: если да, то возвращаем его if (randomValue < sum) { visitedEdgeIds.add(edge.id) return edge } } // если из вершины не исходит ни одно ребро, то бросаем исключение throw IllegalStateException("Suitable edges were not found (Node: ${currentNode.id}, ${currentNode.label})") } // путь муравья val path = mutableListOf<PheromoneEdge<Double>>() // муравей начинает своё движение из стартовой вершины var currentNode = startNode // пока каждое из рёбер графа не будет посещено хотя бы один раз и муравей не вернётся в стартовую вершину while (!(visitedEdgeIds.size >= graph.edges.size && currentNode.id == startNode.id)) { // получаем следующее ребро val nextEdge = getNextEdge(currentNode) // добавляем его в набор посещённых рёбер visitedEdgeIds.add(nextEdge.id) // добавляем это ребро в путь path.add(nextEdge) // обновляем текущую вершину муравья: записываем в неё вершину, до которой муравей может добраться, пройдя по выбранному ребру currentNode = if (nextEdge.destination.id == currentNode.id) nextEdge.source else nextEdge.destination } // возвращаем готовый путь return path } }
<script> import toastr from "toastr"; toastr.options = { timeOut: "1000", progressBar: true, positionClass: "toast-bottom-right", }; import { db } from "./firebase"; let task = { name: "", description: "", }; let tasks = []; let editStatus = false; let currentId = ""; db.collection("tasks").onSnapshot((querySnap) => { let docs = []; querySnap.forEach((doc) => { docs.push({ ...doc.data(), id: doc.id }); }); tasks = [...docs]; }); const addTask = async () => { await db .collection("tasks") .doc() .set({ ...task, createdAt: Date.now(), }); toastr.success("new task created"); }; const handleSubmit = () => { if (!editStatus) { addTask(); } else { updateTask(); } task = { name: "", description: "" }; }; const updateTask = async () => { await db.collection("tasks").doc(currentId).update(task); toastr["success"]("Task updated"); }; const deleteTask = async (id) => { await db.collection("tasks").doc(id).delete(); toastr["warning"]("Task deleted"); }; const editTask = (currentTask) => { editStatus = true; task.name = currentTask.name; task.description = currentTask.description; currentId = currentTask.id; }; const onCancel = () => { editStatus = false; task = { name: "", description: "" }; }; </script> <style> </style> <form on:submit|preventDefault={handleSubmit} class="card card-body"> <div class="form-group"> <input bind:value={task.name} type="text" placeholder="write a new task" class="form-control" /> </div> <div class="form-group"> <textarea class="form-control" bind:value={task.description} rows="3" placeholder="write a task description" /> </div> <button class="btn btn-primary">{#if !editStatus} Save {:else}Update{/if}</button> {#if editStatus} <button class="btn btn-info" on:click={onCancel}>Cancel</button> {/if} </form> {#each tasks as task} <div class="card card-body mt-2"> <div class="d-flex justify-content-between"> <h5>{task.name}</h5> <i class="material-icons" style="vertical-align:middle;" on:click={editTask(task)}>edit</i> </div> <p>{task.description}</p> <button class="btn btn-danger" on:click={deleteTask(task.id)}> <i class="material-icons" style="vertical-align:middle;">delete_forever</i> </button> </div> {/each}
<template> <div class="pagination"> <button :disabled="pageNo === 1" @click="$emit('getPageNo', pageNo - 1)">上一页</button> <button v-if="startNumAndEndNum.start > 1" @click="$emit('getPageNo', 1)" :class="{ active: pageNo === 1 }">1</button> <button v-if="startNumAndEndNum.start > 2">···</button> <!-- 中间部分 --> <button v-for="(page, index) in startNumAndEndNum.end" :key="index" v-if="page >= startNumAndEndNum.start" @click="$emit('getPageNo', page)" :class="{ active: pageNo === page }">{{ page }}</button> <button v-if="startNumAndEndNum.end < totalPage - 1">···</button> <button v-if="startNumAndEndNum.end < totalPage" @click="$emit('getPageNo', totalPage)" :class="{ active: pageNo === totalPage }">{{ totalPage }}</button> <button :disabled="pageNo === totalPage" @click="$emit('getPageNo', pageNo + 1)">下一页</button> <button style="margin-left: 30px">共 {{ total }} 条</button> </div> </template> <script> export default { name: 'ShopPagination', props: ['pageNo', 'pageSize', 'total', 'continues'], computed: { // 总页数 totalPage() { // 向上取整 return Math.ceil(this.total / this.pageSize) }, // 计算出连续的页码的起始数字和结束数字(连续页码的数字一般是5或者7) startNumAndEndNum() { const { pageNo, totalPage, continues } = this let start = 0, end = 0 // 总页数没有连续页码(至少是5)多 if (continues > totalPage) { start = 1 end = totalPage } else { start = pageNo - parseInt(continues / 2) end = pageNo + parseInt(continues / 2) // 纠正start出现负数和0的情况 if (start < 1) { start = 1 end = continues } // 纠正end大于总页数的情况 if (end > totalPage) { end = totalPage start = totalPage - continues + 1 } } return { start, end } } } } </script> <style lang="less" scoped> .pagination { text-align: center; button { margin: 0 5px; background-color: #f4f4f5; color: #606266; outline: none; border-radius: 2px; padding: 0 4px; vertical-align: top; display: inline-block; font-size: 13px; min-width: 35.5px; height: 28px; line-height: 28px; cursor: pointer; box-sizing: border-box; text-align: center; border: 0; &[disabled] { color: #c0c4cc; cursor: not-allowed; } &.active { cursor: not-allowed; background-color: #e1251b; color: #fff; } } } </style>
import 'package:cartoonizer/common/importFile.dart'; import 'package:cartoonizer/controller/effect_data_controller.dart'; import 'package:cartoonizer/config.dart'; import 'package:cartoonizer/files.dart'; import 'package:common_utils/common_utils.dart'; extension StringEx on String { avatar() { if (TextUtil.isEmpty(this.trim())) { return this; } if (!this.startsWith('http')) { return 'https://s3-us-west-2.amazonaws.com/superboostaa/$this'; } return this; } get cartoonizeApi { if (this == Config.instance.host) { return '$this/api/tool/image/cartoon'; } else { return '$this/api/image/cartoonize'; } } bool get isGoogleAccount { if (TextUtil.isEmpty(this.trim())) { return false; } return this.contains('googleusercontent.com'); } String get toUpperCaseFirst { if (TextUtil.isEmpty(this)) { return this; } var s = this[0]; return s.toUpperCase() + this.substring(1); } String get appendHash { EffectDataController effectDataController = Get.find(); if (effectDataController.data?.hash == null) { return this; } if (this.contains('hash=')) { return this; } if (this.contains("?")) { return '${this}&hash=${effectDataController.data?.hash}'; } else { return '${this}?hash=${effectDataController.data?.hash}'; } } String get intl { if (Get.context == null) { return this; } return _intlMap[this.toLowerCase()]?.call() ?? this; } String get fileImageType { var lowerCase = this.toLowerCase(); if (lowerCase == 'png' || lowerCase == 'jpg' || lowerCase == 'jpeg' || lowerCase == 'webp' || lowerCase == 'gif' || lowerCase == 'bmp') { return this; } else { return 'png'; } } bool get isVideoFile => isVideo(this); bool get isImageFile => isImage(this); DateTime? get timezoneCur { DateTime? result; var date = DateUtil.getDateTime(this, isUtc: true); if (date != null) { var timeZoneOffset = DateTime.now().timeZoneOffset; result = date.add(timeZoneOffset); } return result; } } typedef StringRender = String Function(); Map<String, StringRender> _intlMap = { 'no network': () => S.of(Get.context!).no_network, 'not_found': () => S.of(Get.context!).not_found, 'invalid password': () => S.of(Get.context!).invalid_password, 'oops failed': () => S.of(Get.context!).commonFailedToast, 'recent': () => S.of(Get.context!).recent, 'get inspired': () => S.of(Get.context!).get_inspired, 'facetoon': () => S.of(Get.context!).face_toon, 'effects': () => S.of(Get.context!).effects, 'january': () => S.of(Get.context!).january, 'february': () => S.of(Get.context!).february, 'march': () => S.of(Get.context!).march, 'april': () => S.of(Get.context!).april, 'may': () => S.of(Get.context!).may, 'june': () => S.of(Get.context!).june, 'july': () => S.of(Get.context!).july, 'august': () => S.of(Get.context!).august, 'september': () => S.of(Get.context!).september, 'october': () => S.of(Get.context!).october, 'november': () => S.of(Get.context!).november, 'december': () => S.of(Get.context!).december, 'monday': () => S.of(Get.context!).monday, 'tuesday': () => S.of(Get.context!).tuesday, 'wednesday': () => S.of(Get.context!).wednesday, 'thursday': () => S.of(Get.context!).thursday, 'friday': () => S.of(Get.context!).friday, 'saturday': () => S.of(Get.context!).saturday, 'sunday': () => S.of(Get.context!).sunday, 'man': () => S.of(Get.context!).man, 'woman': () => S.of(Get.context!).woman, 'cat': () => S.of(Get.context!).cat, 'dog': () => S.of(Get.context!).dog, 'size': () => S.of(Get.context!).size, 'model': () => S.of(Get.context!).model, 'quantity': () => S.of(Get.context!).quantity, 'color': () => S.of(Get.context!).color, 'colors': () => S.of(Get.context!).colors, 'template': () => S.of(Get.context!).template, 'album': () => S.of(Get.context!).album, };
#pragma once #include<iostream> #include<vector> #include<list> #include <utility> #include"BaseObject.h" #include"Sprite2D.h" #include"MapObject.h" #include"Mob.h" #include"CMath.h" #include"Define.h" enum class MapMode { MAP_INVALID = 0, MAP_VALLILA, MAP_MAZE }; enum class MTerrain { MTERRAIN_INVALID = 0, MTERRAIN_PLAIN, MTERRAIN_RIVER }; class GridPoint : Sprite2D{ public: int gridNumber; MTerrain terrain; //terrain type std::shared_ptr<TextureManager> texture = ResourceManagers::GetInstance()->GetTexture("Forest_Turf_Texture.png"); GridPoint(); GridPoint(std::shared_ptr<TextureManager> texture); void Draw(SDL_Renderer* renderer) override; }; class MapChunk : Sprite2D { public: int mobCount = 0; std::shared_ptr<GridPoint> plainTerrain; std::shared_ptr<GridPoint> riverTerrain; std::shared_ptr<MapObject> mObject; std::vector<std::shared_ptr<GridPoint>> grids; //list the map grid std::vector< std::shared_ptr<MapObject>> objects; //list the objects that are here std::list < std::shared_ptr<Mob>> mobs; // list the mobs MapChunk(MapMode mode); //MapChunk(char* data); void Draw(SDL_Renderer* renderer) override; }; class Map { private: std::pair<Vector2, Vector2> checkPoint; public: int h, v; //size of the map in chunk unit std::vector<std::shared_ptr<MapChunk>> chunks; std::map <std::shared_ptr<MapObject>, Vector2*> objectHitboxs; std::vector<std::pair<Vector2, Vector2>> collieBoxs; Map(MapMode mode); void Init(MapMode mode); //Map(char* data); void Draw(SDL_Renderer* renderer); void DisplayHitboxs(SDL_Renderer* renderer); void UpdateCollies(); bool isOnTheCheckPoint(Vector2 playerPos); };
package viewservice import "net" import "net/rpc" import "log" import "time" import "sync" import "fmt" import "os" import "sync/atomic" type ViewServer struct { mu sync.Mutex l net.Listener dead int32 // for testing rpccount int32 // for testing me string // Your declarations here. curView View views map[string]time.Time Ack bool } // // server Ping RPC handler. // func (vs *ViewServer) Ping(args *PingArgs, reply *PingReply) error { // Your code here. vs.mu.Lock() defer vs.mu.Unlock() // used defer to defer the unlocking of the lock until the function //surrounding it unlocks. if vs.curView.Primary == args.Me && vs.curView.Viewnum == args.Viewnum { vs.Ack = true } vs.views[args.Me] = time.Now() if args.Viewnum == 0 { if vs.curView.Primary == "" && vs.curView.Backup == "" { vs.curView.Primary = args.Me vs.curView.Viewnum = 1 } else if vs.curView.Primary == args.Me { vs.views[args.Me] = time.Time{} } else if vs.curView.Backup == args.Me { vs.views[args.Me] = time.Time{} } } reply.View = vs.curView return nil } // // server Get() RPC handler. // func (vs *ViewServer) Get(args *GetArgs, reply *GetReply) error { // Your code here. vs.mu.Lock() defer vs.mu.Unlock() reply.View = vs.curView return nil } // // tick() is called once per PingInterval; it should notice // if servers have died or recovered, and change the view // accordingly. // func (vs *ViewServer) tick() { // Your code here. vs.mu.Lock() defer vs.mu.Unlock() for server, i := range vs.views { if time.Now().Sub(i) > DeadPings*PingInterval { delete(vs.views, server) if vs.Ack { if server == vs.curView.Primary { vs.curView.Primary = "" } if server == vs.curView.Backup { vs.curView.Backup = "" } } } } if vs.Ack { flag := false if vs.curView.Primary == "" && vs.curView.Backup != "" { vs.curView.Primary = vs.curView.Backup vs.curView.Backup = "" flag = true } if vs.curView.Backup == "" { for server, _ := range vs.views { if server != vs.curView.Primary { vs.curView.Backup = server flag = true break } } } if flag { vs.curView.Viewnum++ vs.Ack = false } } } // // tell the server to shut itself down. // for testing. // please don't change these two functions. // func (vs *ViewServer) Kill() { atomic.StoreInt32(&vs.dead, 1) vs.l.Close() } // // has this server been asked to shut down? // func (vs *ViewServer) isdead() bool { return atomic.LoadInt32(&vs.dead) != 0 } // please don't change this function. func (vs *ViewServer) GetRPCCount() int32 { return atomic.LoadInt32(&vs.rpccount) } func StartServer(me string) *ViewServer { vs := new(ViewServer) vs.me = me // Your vs.* initializations here. vs.curView = View{0, "", ""} vs.Ack = false vs.views = make(map[string]time.Time) // tell net/rpc about our RPC server and handlers. rpcs := rpc.NewServer() rpcs.Register(vs) // prepare to receive connections from clients. // change "unix" to "tcp" to use over a network. os.Remove(vs.me) // only needed for "unix" l, e := net.Listen("unix", vs.me) if e != nil { log.Fatal("listen error: ", e) } vs.l = l // please don't change any of the following code, // or do anything to subvert it. // create a thread to accept RPC connections from clients. go func() { for vs.isdead() == false { conn, err := vs.l.Accept() //block utill Dail if err == nil && vs.isdead() == false { atomic.AddInt32(&vs.rpccount, 1) go rpcs.ServeConn(conn) //block utill rpc call } else if err == nil { conn.Close() } if err != nil && vs.isdead() == false { fmt.Printf("ViewServer(%v) accept: %v\n", me, err.Error()) vs.Kill() } } }() // create a thread to call tick() periodically. go func() { for vs.isdead() == false { vs.tick() time.Sleep(PingInterval) } }() return vs }
import { AutoValidator, IsDateAfterThan } from '@zro/common'; import { Retry, RetryEntity, RetryRepository } from '@zro/utils/domain'; import { IsDate, IsDefined, IsInt, IsString, IsUUID } from 'class-validator'; import { Logger } from 'winston'; import { DeleteRetryUseCase as UseCase } from '@zro/utils/application'; type TDeleteRetryRequest = Retry; export class DeleteRetryRequest extends AutoValidator implements TDeleteRetryRequest { @IsUUID(4) id: string; @IsInt() counter: number; @IsString() retryQueue: string; @IsString() failQueue: string; @IsDate() retryAt: Date; @IsDateAfterThan('retryAt', false) abortAt: Date; @IsDefined() data: unknown; constructor(props: TDeleteRetryRequest) { super(props); } } export class DeleteRetryController { private usecase: UseCase; constructor( private logger: Logger, private retryRepository: RetryRepository, ) { this.logger = logger.child({ context: DeleteRetryController.name }); this.usecase = new UseCase(this.logger, this.retryRepository); } async execute(request: TDeleteRetryRequest): Promise<void> { const { id, counter, retryQueue, failQueue, retryAt, abortAt, data } = request; const retry = new RetryEntity({ id, counter, retryQueue, failQueue, retryAt, abortAt, data, }); this.logger.debug('Deleteing a retry.', { retry }); await this.usecase.execute(retry); } }
import { fireEvent, render, screen } from '@testing-library/react'; import { App } from '../App'; describe('App', () => { it('renders a Mars Rover screen', () => { render(<App />); const gridElement = screen.getByTestId('mars-rover-grid'); expect(gridElement).toBeInTheDocument(); const moveButton = screen.getByText('Move'); expect(moveButton).toBeInTheDocument(); }); it ('should command rover to move and display the updated location in a label', () => { render(<App />); const moveButton = screen.getByText('Move'); fireEvent.click(moveButton); const locationLabel = screen.getByText('0:1:North'); expect(locationLabel).toBeInTheDocument(); }); it.each( [ [1, 'East', '>'], [2, 'South', 'V'], [3, 'West', '<'], [4, 'North', '^'] ] )('should command rover to turn and display updated position in a label', (timesToTurn, compass, roverDisplay) => { render(<App />); const turnRightButton = screen.getByText('R'); for(let i = 0; i < timesToTurn; i++){ fireEvent.click(turnRightButton); } const locationLabel = screen.getByText(`0:0:${compass}`); expect(locationLabel).toBeInTheDocument(); const rover = screen.getByText(roverDisplay); expect(rover).toBeInTheDocument(); }); });
//* This file is part of the MOOSE framework //* https://www.mooseframework.org //* //* All rights reserved, see COPYRIGHT for full restrictions //* https://github.com/idaholab/moose/blob/master/COPYRIGHT //* //* Licensed under LGPL 2.1, please see LICENSE for details //* https://www.gnu.org/licenses/lgpl-2.1.html #pragma once #include "Material.h" #include "RankFourTensorForward.h" #include "RankTwoTensorForward.h" #include "StabilizationUtils.h" #include "GradientOperator.h" /// Calculate strains to use the MOOSE materials with the Lagrangian kernels /// /// This class calculates strain measures used by ComputeLagrangianStress /// derived materials and used with /// UpdatedLagrangianStressDivergence and TotalLagrangianStressDivergence /// kernels /// /// It has two basic jobs /// 1) Calculate the deformation gradient at time steps n+1 and n /// (the MOOSE material system doesn't bother for the SmallStrain case) /// This includes including F_bar stabilization, if requested /// 2) Calculate the kinematic quantities needed by the kernels: /// a) The incremental inverse deformation gradient /// b) The inverse deformation gradient /// c) The determinant of the current deformation gradient /// /// If required by the stabilize_strain flag it averages the pressure parts /// of the deformation gradient. /// /// This object cooperates with the homogenization constraint system by /// adding in the scalar field representing the macroscale displacement /// gradient before calculating strains. /// template <class G> class ComputeLagrangianStrainBase : public Material, public G { public: static InputParameters baseParams(); static InputParameters validParams(); ComputeLagrangianStrainBase(const InputParameters & parameters); virtual void initialSetup() override; protected: virtual void initQpStatefulProperties() override; virtual void computeProperties() override; virtual void computeQpProperties() override; /// Calculate the strains based on the spatial velocity gradient virtual void computeQpIncrementalStrains(const RankTwoTensor & dL); /// Subtract the eigenstrain increment to subtract from the total strain virtual void subtractQpEigenstrainIncrement(RankTwoTensor & strain); /// Calculate the unstabilized deformation gradient at the quadrature point virtual void computeQpUnstabilizedDeformationGradient(); /// Calculate the unstabilized and optionally the stabilized deformation gradients virtual void computeDeformationGradient(); // Displacements and displacement gradients const unsigned int _ndisp; std::vector<const VariableValue *> _disp; std::vector<const VariableGradient *> _grad_disp; /// Material system base name const std::string _base_name; /// If true the equilibrium conditions is calculated with large deformations const bool _large_kinematics; /// If true stabilize the strains with F_bar const bool _stabilize_strain; // The eigenstrains std::vector<MaterialPropertyName> _eigenstrain_names; std::vector<const MaterialProperty<RankTwoTensor> *> _eigenstrains; std::vector<const MaterialProperty<RankTwoTensor> *> _eigenstrains_old; // The total strains MaterialProperty<RankTwoTensor> & _total_strain; const MaterialProperty<RankTwoTensor> & _total_strain_old; MaterialProperty<RankTwoTensor> & _mechanical_strain; const MaterialProperty<RankTwoTensor> & _mechanical_strain_old; /// Strain increment MaterialProperty<RankTwoTensor> & _strain_increment; /// Vorticity increment MaterialProperty<RankTwoTensor> & _vorticity_increment; /// The unstabilized deformation gradient MaterialProperty<RankTwoTensor> & _F_ust; // The average deformation gradient over the element for F-bar stabilization. Note that the // average deformation gradient is undefined if stabilization is not active. MaterialProperty<RankTwoTensor> & _F_avg; // The deformation gradient. If stabilization is active, this will be the stabilized deformation // gradient. Otherwise this will be equal to the unstabilized deformation gradient. MaterialProperty<RankTwoTensor> & _F; /// Old deformation gradient const MaterialProperty<RankTwoTensor> & _F_old; /// Inverse deformation gradient MaterialProperty<RankTwoTensor> & _F_inv; /// Inverse incremental deformation gradient MaterialProperty<RankTwoTensor> & _f_inv; /// Names of any extra homogenization gradients std::vector<MaterialPropertyName> _homogenization_gradient_names; /// Actual homogenization contributions std::vector<const MaterialProperty<RankTwoTensor> *> _homogenization_contributions; /// Rotation increment for "old" materials inheriting from ComputeStressBase MaterialProperty<RankTwoTensor> & _rotation_increment; };
# [ Soriting Iterables ] # - sorted() 함수의 argument 는Seqeunce Type 이 아닌 Iterable 이면 지원 # - Iterable 객체 구현 후 sorted() Test import random class RandomInts: def __init__(self, length, *, seed=0, lower=0, upper=10): self.length = length self.seed = seed self.lower = lower self.upper = upper def __len__(self): return self.length def __iter__(self): return self.RandomIterator(self.length, seed=self.seed, lower=self.lower, upper=self.upper) # Iterator 객체 class RandomIterator: def __init__(self, length, *, seed=0, lower=0, upper=10): self.length = length self.seed = seed self.lower = lower self.upper = upper self.num_request = 0 random.seed(seed) def __iter__(self): return self def __next__(self): if self.num_request >= self.length: raise StopIteration else: result = random.randint(self.lower, self.upper) # Lazy ? self.num_request += 1 return result # 활용 random_ints = RandomInts(10, seed=0, lower=0, upper=20) # 출력 for v in random_ints: print(v) # sorted 사용 print("Before Sorted -> ", list(random_ints)) print("After Sorted -> ", sorted(random_ints))
package com.tecno.udemy.fernando.cityworld.adapters; import android.content.Context; import android.net.Uri; import android.support.annotation.NonNull; import android.support.v7.widget.RecyclerView; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.BaseAdapter; import android.widget.Button; import android.widget.ImageView; import android.widget.TextView; import com.squareup.picasso.Picasso; import com.tecno.udemy.fernando.cityworld.R; import com.tecno.udemy.fernando.cityworld.model.City; import org.w3c.dom.Text; import java.util.List; public class CityAdapter extends RecyclerView.Adapter<CityAdapter.ViewHolder> { private OnButtonClickListener buttonListener; private OnClickListener clickListener; private List<City> cities; private Context context; private int layout; public CityAdapter(List cities, Context context, int layout, OnButtonClickListener buttonListener, OnClickListener clickListener) { this.buttonListener = buttonListener; this.clickListener = clickListener; this.cities = cities; this.context = context; this.layout = layout; } @NonNull @Override public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int position) { View view = LayoutInflater.from(context).inflate(layout, parent, false); ViewHolder holder = new ViewHolder(view); return holder; } @Override public void onBindViewHolder(@NonNull ViewHolder viewHolder, int position) { viewHolder.bind(cities.get(position), clickListener, buttonListener); } @Override public int getItemCount() { return cities.size(); } public class ViewHolder extends RecyclerView.ViewHolder{ ImageView cityImage; TextView textViewName; TextView textViewDescription; TextView textViewStars; Button btnDelete; public ViewHolder(View view){ super(view); cityImage = view.findViewById(R.id.imageViewCity); textViewName = view.findViewById(R.id.textViewName); textViewDescription = view.findViewById(R.id.textViewDescription); textViewStars = view.findViewById(R.id.textViewStars); btnDelete = view.findViewById(R.id.btnDelete); } public void bind(final City city, final OnClickListener clickListener, final OnButtonClickListener buttonListener){ Picasso.get().load(city.getLinkBackground()).fit().into(cityImage); textViewName.setText(city.getName()); textViewDescription.setText(city.getDescription()); textViewStars.setText(city.getNumStarts()+""); itemView.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { clickListener.onClickListener(city, getAdapterPosition()); } }); btnDelete.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { buttonListener.onButtonClick(city, getAdapterPosition()); } }); } } public interface OnButtonClickListener{ void onButtonClick(City city, int position); } public interface OnClickListener{ void onClickListener(City city, int position); } }
import React, { useContext } from 'react'; import { MenuListItemType } from '../ContextMenu'; import DropdownWithIcon from '../Dropdown/WithIcon'; import { LocaleContext } from '../../context/localeContext'; const LanguageSelector = () => { const { locale, setLocale } = useContext(LocaleContext); return ( <DropdownWithIcon items={[ { text: 'English', icon: <span>🇬🇧</span>, type: MenuListItemType.DEFAULT, onClick: () => { setLocale('en'); }, }, { text: '日本', icon: <span>🇯🇵</span>, type: MenuListItemType.DEFAULT, onClick: () => { setLocale('ja'); }, }, ]} icon={ <div className="flex items-center gap-2"> <span> {locale === 'ja' ? '🇯🇵' : '🇬🇧'}</span> <span>{locale === 'ja' ? '日本' : 'English'}</span> </div> } noChevron dropdownBtnClassName="" btnSize="small" btnVariant="tertiary" size="small" appendTo={document.body} /> ); }; export default LanguageSelector;
# Rustls development roadmap ## Future priorities In rough order of priority: * **FIPS Certification for Default Cryptographic Library**. Change the default cryptographic library to something with FIPS certification. rustls/rustls#1540 * **Add No-Allocation / Write-Through API**. Would make handshakes faster and give the caller more control over allocations. RFC: rustls/rustls#1420 * **Support no_std**. Enables use of rustls in more memory-constrained environments. RFC: rustls/rustls#1399 * **OpenSSL API Compatibility Layer**. Add an OpenSSL C API compatibility layer for adoption purposes. * **Support Encrypted Client Hello (Client Side)**. Encrypted Client Hello is an upcoming standard from the TLS WG providing better protection for some of the data sent by a client in the initial Client Hello message. rustls/rustls#1718 * **Additional Performance Optimization**. Additional performance optimization including CPU usage, latency, and memory usage. The goal is to outperform OpenSSL across the board if we are not already. * **Support RFC 8879 Certificate Compression**. Support for a TLS extension that substantially shrinks certificates (one of the largest parts of the TLS handshake), improving handshake latency by decreasing bandwidth used. rustls/rustls#534 * **Enforce Confidentiality / Integrity Limits**. The QUIC use of TLS mandates limited usage of AEAD keys. While TLS 1.3 and 1.2 do not require this, the same kinds of issues can apply here, and we should consider implementing limits for TLS over TCP as well. rustls/rustls#755 * **Support Post-Quantum Hybrid Key Exchange**. Experimental, optional support for the `X25519Kyber768Draft00` key exchange. This should track [the draft](https://datatracker.ietf.org/doc/draft-tls-westerbaan-xyber768d00/). rustls/rustls#1687 ## Past priorities Delivered in [rustls-platform-verifier](https://github.com/rustls/rustls-platform-verifier) 0.1.0: * **Improve OS Trust Verifier Support**. While we currently have a way to trust certificates stored in the platform trust store, platform trust stores can have other ways of restricting how/when roots that they expose are trusted. In order to rely on these (on Windows, Android, and Apple platforms) we should rely on the platform verifier directly. Delivered in 0.22: * **Enable Pluggable Cryptographic Back-ends**. Allow plugging in different cryptographic back-ends. rustls/rustls#1184 * **Comprehensive Performance Benchmarking**. Performance should be a headline feature of Rustls. We need to develop a more comprehensive benchmarking system so that we can assess and improve performance from multiple angles, including CPU usage, latency, and memory usage. Delivered in 0.21: * **Support IP Address Certificates**. There are some popular use cases where applications want TLS certificates for services that don’t have their own host name, relying on the IP address directly instead. This is common in Kubernetes deployments and service meshes. rustls/rustls#184 * **Implement RFC 8446 Appendix C.4 in session cache**. TLS clients should use session tickets at most once for resumption. Without this, TLS clients may be tracked across connections through reuse of session tickets. Requires changes of the internal APIs to the session caching infrastructure. rustls/rustls#466 * **Improve Client Certificate Authentication Support**. Rustls and webpki currently do not provide access to client information supplied as part of the certificate, and there’s no infrastructure to deal with revocation checks. rustls/rustls-ffi#87 Delivered in 0.20: * **Add/extend support for TLS 1.3 Early Data**. Early data allows clients to submit data before the TLS handshake is complete in some cases (idempotent requests, data where replay is not a risk), improving latency in the cases of, for example, HTTP requests by submitting the request in parallel with the TLS handshake.
//this for Notes Model to manage notes and rounting const express = require('express'); const router = express.Router(); const fetchuser = require('../middleware/fetchuser'); const Notes = require('../models/Notes'); const { body, validationResult } = require('express-validator'); //Route 1:- get all the notes using : GET "/api/auth/fetchallnotes". Login required; router.get('/fetchallnotes', fetchuser, async (req, res) => { try { const notes = await Notes.find({ user: req.user.id }); res.json(notes); } catch (error) { res.status(500).send("Internal server error"); } }) //-------------------------------------------------------------------------end---------------------------------------------------------------------------------- //Route 2 Add a new Note using POST: '/api/auth/addnote' router.post('/addnote', fetchuser, [ body('title', 'Enter valid title').isLength({ min: 3 }), body('description', 'Description must be atleast 5 character').isLength({ min: 5 })], async (req, res) => { try { const { title, description, tag } = req.body; //coming from frontend NoteState addnote. //if there are error, return Bad request and the errors const errors = validationResult(req); if (!errors.isEmpty()) { return res.status(404).json({ errors: errors.array() }) } //Below :- when we are creating a note to store in mongo title , description , tag is coming from frontend using req.body but... but... but.. when we are storing this note in db we will also store user_id of that user who are adding this note which we will get from user model of mongo using middleware . **req.user.id** getting it from middleware. //for NoteAdda:- we will add subject_id in the notes model so that we can fetch all the note corresponding to that subject; const note = new Notes({ title, description, tag, user: req.user.id }) const savedNote = await note.save(); //save function is saving notes res.json(savedNote); } catch (error) { console.log(error.message); res.status(500).send("Internal Server Error") } }) //-------------------------------------------------------------------------end---------------------------------------------------------------------------------- //route 2 Updation an existing Notes :Post "/api/auth/updatenotes".Login required router.put('/updatenote/:id' ,fetchuser,async(req, res)=>{ const{title,description,tag}=req.body; //create a newnote object const newNote={}; if(title){newNote.title=title} if(description){newNote.description=description} if(tag){newNote.tag=tag} //find the note to be updated and update it; let note=await Notes.findById(req.params.id); if(!note){return res.status(404).send("Not Found")} //below: yadi ye uhi user nhi hai to not allowed //I think unnecessary but not tested yet. if(note.user.toString() !==req.user.id){ //ye uhhi fetchuser bala hai and note.user is coming from Notes schema; return res.status(401).send("Not Allowed"); } note=await Notes.findByIdAndUpdate(req.params.id,{$set:newNote},{new:true}) res.json(note); //after updation of notes send it to the frontend }) //-------------------------------------------------------------------------end---------------------------------------------------------------------------------- // Route 4:- Delete an existing Noet using:DELETE "/api/notes/deletenote" .Login required router.delete('/deletenote/:id',fetchuser,async(req,res)=>{ try{ //Find the note to be delete and delete it let note=await Notes.findById(req.params.id); if(!note){return res.status(404).send("Not Found")} //Allow deletions only to be delete and delete it if(note.user.toString()!==req.user.id){ return res.status(401).send("Not Allowed"); } note=await Notes.findByIdAndDelete(req.params.id); res.json({"Success":"Note has been deleted",note:note}); }catch(error){ console.error(error.massage); res.status(500).send("Iternal server error"); } }) module.exports = router
import React from 'react'; import PropTypes from 'prop-types'; import ImageGalleryItem from 'components/ImageGalleryItem/ImageGalleryItem'; import { ImagesList } from './ImageGallery.styled'; export function ImageGallery({ images }) { return ( <ImagesList> {images.map(image => ( <ImageGalleryItem key={image.id} {...image} /> ))} </ImagesList> ); } ImageGallery.propTypes = { images: PropTypes.arrayOf( PropTypes.shape({ id: PropTypes.number.isRequired, largeImageURL: PropTypes.string.isRequired, webformatURL: PropTypes.string.isRequired, tags: PropTypes.string.isRequired, }).isRequired ).isRequired, }; export default ImageGallery;
// SPDX-License-Identifier: MIT pragma solidity 0.8.9; import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol"; import "./interfaces/IAstranoVestingWallet.sol"; /** * @title AstranoVestingWallet * @dev Handles the vesting of ERC20 token fees for Astrano * @custom:security-contact marcel.miro@astrano.io */ contract AstranoVestingWallet is IAstranoVestingWallet { address private _beneficiary; uint256 private immutable _startIn; uint256 private immutable _duration; mapping(address => Vest) private _vestings; struct Vest { uint256 start; uint256 released; } event Deposit(address indexed token, uint256 amount); event Released(address indexed token, uint256 amount); constructor( address beneficiary_, uint256 startIn_, uint256 duration_ ) { require(beneficiary_ != address(0), "beneficiary is the zero address"); require(duration_ > 0, "duration is 0"); _beneficiary = beneficiary_; _startIn = startIn_; _duration = duration_; } /** * @return address to release tokens to */ function beneficiary() external view returns (address) { return _beneficiary; } /** * @param beneficiary_ address to release tokens to */ function setBeneficiary(address beneficiary_) external { require(_beneficiary == msg.sender, "caller not beneficiary"); require(beneficiary_ != address(0), "beneficiary is the zero address"); _beneficiary = beneficiary_; } /** * @return duration until vesting starts in unix seconds */ function startIn() external view returns (uint256) { return _startIn; } /** * @return vesting duration in unix seconds */ function duration() external view returns (uint256) { return _duration; } /** * @param token ERC20 address * @return vesting start timestamp for `token` in unix seconds */ function start(address token) external view returns (uint256) { return _vestings[token].start; } /** * @param token ERC20 address * @return amount of released tokens for `token` */ function released(address token) external view returns (uint256) { return _vestings[token].released; } /** * @param token ERC20 address * @return amount_ amount of releasable tokens for `token` * @return finished_ has vesting ended */ function releasable(address token) public view returns (uint256 amount_, bool finished_) { // solhint-disable-next-line not-rely-on-time uint256 timestamp = block.timestamp; Vest memory vest = _vestings[token]; if (vest.start == 0 || timestamp <= vest.start) { return (0, false); } uint256 balance = IERC20(token).balanceOf(address(this)); if (timestamp >= vest.start + _duration) { return (balance, true); } uint256 unreleased = (((balance + vest.released) * (timestamp - vest.start)) / _duration) - vest.released; return (unreleased, false); } /** * @dev Deposit tokens. Caller must have `amount` as the allowance of this contract (spender) for `token` * @param token ERC20 address * @param amount amount to deposit */ function deposit(address token, uint256 amount) external { require(amount > 0, "amount is 0"); SafeERC20.safeTransferFrom(IERC20(token), msg.sender, address(this), amount); Vest storage vest = _vestings[token]; //solhint-disable-next-line not-rely-on-time if (vest.start == 0) vest.start = block.timestamp + _startIn; emit Deposit(token, amount); } /** * @dev Transfer releasable tokens for `token` to beneficiary * @param token ERC20 address */ function release(address token) external { (uint256 unreleased, bool finished) = releasable(token); require(unreleased > 0, "no tokens due"); _vestings[token].released += unreleased; SafeERC20.safeTransfer(IERC20(token), _beneficiary, unreleased); emit Released(token, unreleased); if (finished) delete _vestings[token]; } }
import 'package:firebase_prac/screens/user_input.dart'; import 'package:flutter/material.dart'; import 'package:fluttertoast/fluttertoast.dart'; import 'package:modal_progress_hud_nsn/modal_progress_hud_nsn.dart'; import '../components/rounded_button.dart'; import '../constants.dart'; import 'package:firebase_auth/firebase_auth.dart'; import 'basic_screen.dart'; class RegistrationScreen extends StatefulWidget { static String id = 'registration_screen'; @override _RegistrationScreenState createState() => _RegistrationScreenState(); } class _RegistrationScreenState extends State<RegistrationScreen> { final _auth = FirebaseAuth.instance; String email=''; String password=''; bool showSpinner = false; @override Widget build(BuildContext context) { return Scaffold( backgroundColor: Colors.white, body: ModalProgressHUD( inAsyncCall: showSpinner, child: Padding( padding: EdgeInsets.symmetric(horizontal: 24.0), child: Column( mainAxisAlignment: MainAxisAlignment.center, crossAxisAlignment: CrossAxisAlignment.stretch, children: <Widget>[ Flexible( child: Hero( tag: 'logo', child: Container( height: 200.0, child: Padding( padding: const EdgeInsets.symmetric(horizontal: 12.0), child: Icon( Icons.swap_horizontal_circle_outlined, size: 170.0, ), ), ), ), ), SizedBox( height: 48.0, ), TextField( textAlign: TextAlign.center, keyboardType: TextInputType.emailAddress, onChanged: (value) { //Do something with the user input. email = value; }, decoration: kTextFieldDecoration.copyWith(hintText: 'Enter your email'), ), SizedBox( height: 8.0, ), TextField( textAlign: TextAlign.center, obscureText: true, onChanged: (value) { //Do something with the user input. password = value; }, decoration: kTextFieldDecoration.copyWith(hintText: 'Enter your password'), ), SizedBox( height: 24.0, ), RoundedButton( title: 'Register', colour: Colors.blueAccent, onPressed: () async{ // print(email); // print(password); setState(() { showSpinner = true; }); try { final newUser = await _auth.createUserWithEmailAndPassword(email: email, password: password); if(newUser != null){ Navigator.pushNamed(context, UserInputForm.id); } setState(() { showSpinner = false; }); } catch (e) { print(e); Fluttertoast.showToast( msg: 'Error', ); setState(() { showSpinner = false; }); } }, ), ], ), ), ), ); } }
import { screen, render } from 'utils/testUtils' import GameDetails from '.' import mock from './mock' const props = mock describe('<GameDetails />', () => { it('should render the blocks', () => { render(<GameDetails {...props} />) expect( screen.getByRole('heading', { name: /developer/i }) ).toBeInTheDocument() expect( screen.getByRole('heading', { name: /release date/i }) ).toBeInTheDocument() expect( screen.getByRole('heading', { name: /platforms/i }) ).toBeInTheDocument() expect( screen.getByRole('heading', { name: /publisher/i }) ).toBeInTheDocument() expect(screen.getByRole('heading', { name: /rating/i })).toBeInTheDocument() expect(screen.getByRole('heading', { name: /genres/i })).toBeInTheDocument() }) it('should render the platform icons', () => { render(<GameDetails {...props} />) expect(screen.getByRole('img', { name: /windows/i })).toBeInTheDocument() expect(screen.getByRole('img', { name: /linux/i })).toBeInTheDocument() expect(screen.getByRole('img', { name: /mac/i })).toBeInTheDocument() }) it('should render the publisher', () => { render(<GameDetails {...props} />) expect(screen.getByText('Walkabout')).toBeInTheDocument() }) it('should render the developer', () => { render(<GameDetails {...props} />) expect(screen.getByText('Different Tales')).toBeInTheDocument() }) it('should render the formatted date', () => { render(<GameDetails {...props} />) expect(screen.getByText('Nov 21, 2020')).toBeInTheDocument() }) it('should render free when rating is BR0', () => { render(<GameDetails {...props} rating="BR0" />) expect(screen.getByText(/free/i)).toBeInTheDocument() }) it('should render 16+ when rating is BR16', () => { render(<GameDetails {...props} rating="BR16" />) expect(screen.getByText('16+')).toBeInTheDocument() }) it('should render the genres list', () => { render(<GameDetails {...props} />) expect(screen.getByText('Role-playing / Action')).toBeInTheDocument() }) })
import React, { useState, useEffect } from 'react'; import { useParams } from 'react-router'; import Page from '../components/Page'; import Text from '../components/Text'; import NavButton from '../components/NavButton'; import { FontAwesomeIcon } from '@fortawesome/react-fontawesome'; import { faGenderless, faCircleNotch, faAdjust, } from '@fortawesome/free-solid-svg-icons'; import { getFesterfontClasses, getFesterfontClass } from '../utils/festerfonts'; export default function FesterfontClassPage() { const { festerfontClassName } = useParams(); const [isLoaded, setIsLoaded] = useState(false); const [festerfontClass, setFesterfontClass] = useState( getFesterfontClasses()[0] ); useEffect(() => { setIsLoaded(true); }); useEffect(() => { if (isLoaded) { setFesterfontClass(getFesterfontClass(festerfontClassName)); } }, [isLoaded]); const getIcon = () => { switch (festerfontClassName) { case 'Clarion': return faGenderless; case 'Umbra': return faCircleNotch; default: return faAdjust; } }; return ( <Page> <div className='back-button-flex'> <NavButton pageString='/festerfonts?Classes' /> <NavButton pageString='/festerfonts?General' label='Festerfonts' /> </div> <div className='festerfont-class-page-container page-container'> <div className='festerfont-class-page-name-container'> <FontAwesomeIcon size='2x' icon={getIcon()} /> <h1 className='page-title festerfont-class-name'> {festerfontClass.name} </h1> <FontAwesomeIcon size='2x' icon={getIcon()} /> </div> <Text paragraphs={festerfontClass.description} classes='text' /> <div> <h1 className='header'>Blightsource Patterns</h1> <div className='festerfont-class-blightsources'> {festerfontClass.blightsources.map((blightsource, i) => { return ( <h1 key={i} className='subheader festerfont-class-blightsource'> {blightsource} </h1> ); })} </div> </div> <div> <h1 className='header'>Biome Patterns</h1> <div className='festerfont-class-biomes'> {festerfontClass.biomes.map((biome, i) => { return ( <h1 key={i} className='subheader festerfont-class-biome'> {biome} </h1> ); })} </div> </div> <div> <h1 className='header'>Blightsource Patterns</h1> <div className='festerfont-class-blightsources'> {festerfontClass.blightsources.map((blightsource, i) => { return ( <h1 key={i} className='subheader festerfont-class-blightsource'> {blightsource} </h1> ); })} </div> </div> </div> </Page> ); }
import streamlit as st import os import time import pandas as pd from datetime import datetime import plotly.express as px import PIL.Image from docx2pdf import convert import platform #os.chdir(r'E:\projects\smartscan2_1') import utilities st.set_page_config(layout="wide") system = platform.system() import os def list_files_and_directories(path="."): # List all files and directories in the specified path for entry in os.listdir(path): # Join the path with the entry name to get the full path full_path = os.path.join(path, entry) if os.path.isdir(full_path): print("Directory:", full_path) # Recursively list files and directories within the directory list_files_and_directories(full_path) else: print("File:", full_path) #input_image_path = 'uploaded_image.jpg' # State management ----------------------------------------------------------- state = st.session_state def init_state(key, value): if key not in state: state[key] = value # generic callback to set state def _set_state_cb(**kwargs): for state_key, widget_key in kwargs.items(): val = state.get(widget_key, None) if val is not None or val == "": setattr(state, state_key, state[widget_key]) def _set_login_cb(username, password): state.login_successful, state.role = utilities.login(username, password) def _reset_login_cb(): state.login_successful = False state.username = "" state.password = "" init_state('login_successful', False) init_state('username', '') init_state('password', '') def main(): st.title("SmartScan") # Get session state if "login_successful" not in st.session_state: st.session_state.login_successful = False if "username" not in st.session_state: st.session_state.username = "" if "password" not in st.session_state: st.session_state.password = "" # If login is successful if state.login_successful: if state.role == 'diagnostics': if 'patients_df' or 'credentials_df' not in st.session_state: st.session_state.patients_df = pd.read_excel('patients_info.xlsx') st.session_state.credentials_df = pd.read_excel('credentials.xlsx') if st.button("Refresh Reports"): st.session_state.patients_df = pd.read_excel('patients_info.xlsx') st.session_state.credentials_df = pd.read_excel('credentials.xlsx') #... Read existing data ... patients_df = st.session_state.patients_df # pd.read_excel('patients_info.xlsx') credentials_df = st.session_state.credentials_df # pd.read_excel('credentials.xlsx') curr_diag_combination = st.session_state.username + '__' + st.session_state.password curr_diag_credits = list( credentials_df.loc[credentials_df['combination'] == curr_diag_combination, 'credits' ] )[0] st.write( 'Available Credits : ', int( curr_diag_credits ) ) st.subheader( 'Upload Image', divider='orange' ) # Input fields col1, col2, col3, col4 = st.columns([2, 1, 1, 2]) with col1: patient_name = st.text_input("Patient Name", key = 'patient_name', max_chars = 100 ) with col2: patient_age = st.number_input("Age", min_value=0, step=1, value = None ) with col3: patient_gender = st.selectbox("Gender", ['Male', 'Female', 'Other'], key = 'gender', index = None ) with col4: doctor_name = st.text_input("Doctor's Name", key = 'doctor_name', max_chars = 100 ) col5, col5_1, col5_2 = st.columns([2, 2, 2]) with col5: uploaded_image = st.file_uploader("Upload image 1") with col5_1: uploaded_image_2 = st.file_uploader("Upload image 2") with col5_2: uploaded_image_3 = st.file_uploader("Upload image 3") # Check if all mandatory inputs are provided mandatory_fields_filled = patient_name and patient_age is not None and patient_gender and doctor_name and uploaded_image is not None if st.button("Submit"): if curr_diag_credits == 0: st.markdown("<p style='color: red;'>Please Top Up Credits to generate reports.</p>", unsafe_allow_html=True) else: # Highlight mandatory fields if not filled if not mandatory_fields_filled: st.markdown("<p style='color: red;'>Please provide all inputs.</p>", unsafe_allow_html=True) else: #... Updating credits .... curr_diag_credits = max( 0, curr_diag_credits - 1 ) credentials_df.loc[credentials_df['combination'] == curr_diag_combination, 'credits'] = curr_diag_credits credentials_df.to_excel( 'credentials.xlsx', index = False) #.... Patient info submission patient_id = 'p' + str( int( 1000*time.time() ) ) patient_image_filename = 'submitted_images/img_' + patient_id col6, col6_2, col6_3 = st.columns([1,1,1]) print( list_files_and_directories('.') ) # Display the uploaded images with col6: st.subheader( 'Submitted Image 1', divider='orange' ) st.image(uploaded_image, caption="Uploaded Image", use_column_width=True) with open(patient_image_filename + '_1' + '.jpg', "wb") as f: f.write(uploaded_image.read()) with col6_2: st.subheader( 'Submitted Image 2', divider='orange' ) st.image(uploaded_image_2, caption="Uploaded Image", use_column_width=True) with open(patient_image_filename + '_2' + '.jpg', "wb") as f: f.write(uploaded_image_2.read()) with col6_3: st.subheader( 'Submitted Image 3', divider='orange' ) st.image(uploaded_image_3, caption="Uploaded Image", use_column_width=True) with open(patient_image_filename + '_3' + '.jpg', "wb") as f: f.write(uploaded_image_3.read()) data = { 'ID': patient_id, 'Name': [patient_name], 'Age': [patient_age], 'Gender': [patient_gender], "Doctor_name": [doctor_name], 'diagnostics_combination': curr_diag_combination, 'Submission_time': datetime.now().strftime("%dth %b %Y %H:%M:%S") } # Create a DataFrame submitted_patient_df = pd.DataFrame(data) # Convert 'Submission_time' to datetime submitted_patient_df['Submission_time'] = pd.to_datetime(submitted_patient_df['Submission_time'], format="%dth %b %Y %H:%M:%S") # Extract date submitted_patient_df['Date'] = submitted_patient_df['Submission_time'].dt.date report_creation_flag = utilities.analysis_docx( uploaded_image, patient_id, patient_image_filename+ '_1' + '.jpg' ) if report_creation_flag == 'Success': submitted_patient_df['Report_Status'] = 'Not Ready' else: submitted_patient_df['Report_Status'] = 'Report generation failed. Upload better image.' updated_patients_df = pd.concat([submitted_patient_df, patients_df ], ignore_index=True) updated_patients_df.to_excel('patients_info.xlsx', index = False) #... Filtering for current diagonstics combination curr_diag_patients_df = updated_patients_df.loc[updated_patients_df['diagnostics_combination'] == curr_diag_combination, ] display_patients_df = curr_diag_patients_df[ ['ID', 'Name', 'Age', 'Gender', 'Doctor_name', 'Submission_time', 'Report_Status'] ] #with col7: st.subheader( 'Patient Information', divider='orange' ) st.table( display_patients_df ) #.... Download report logic .... st.subheader( 'Download Report', divider='orange' ) report_ready_df = patients_df.loc[patients_df['Report_Status'] == 'Report Ready', ].reset_index(drop=True) if len( report_ready_df ) > 0: # Convert 'Submission_time' to datetime report_ready_df['Submission_time'] = pd.to_datetime(report_ready_df['Submission_time'], format='%dth %b %Y %H:%M:%S') # Extract date from datetime report_ready_df['Date'] = report_ready_df['Submission_time'].dt.date report_ready_df_to_show = report_ready_df[['ID', 'Name', 'Age', 'Gender', 'Doctor_name', 'Submission_time', 'Report_Status']] st.table( report_ready_df_to_show ) col6, col7, col8 = st.columns([1, 1, 4]) with col6: report_dl_date = st.selectbox("Image Submission Date", list(dict.fromkeys(report_ready_df['Date'] )), key = 'report_dl_date' ) report_ready_df_datewise = report_ready_df.loc[report_ready_df['Date'] == report_dl_date, ] with col7: report_dl_id = st.selectbox("Patient ID", list( report_ready_df_datewise['ID'] ), key = 'report_dl_id' ) report_ready_filename_path = 'generated_reports/report_' + report_dl_id + '_report.pdf' report_patient_dl_df = report_ready_df_datewise.loc[report_ready_df_datewise['ID'] == report_dl_id, ] report_filename = 'Report_' + report_patient_dl_df['Name'].iloc[0] + '_' + report_patient_dl_df['ID'].iloc[0] + '.pdf' with col8: utilities.download_pdf( report_ready_filename_path, report_filename ) utilities.display_pdf(report_ready_filename_path) else: st.info( 'No Reports to download !' ) elif state.role == 'radiologist': logged_in_radiologist = st.session_state.username + '__' + st.session_state.password if 'patients_df' or 'credentials_df' not in st.session_state: st.session_state.patients_df = pd.read_excel('patients_info.xlsx') st.session_state.credentials_df = pd.read_excel('credentials.xlsx') if st.button("Refresh Radiologist"): st.session_state.patients_df = pd.read_excel('patients_info.xlsx') st.session_state.credentials_df = pd.read_excel('credentials.xlsx') #... Read existing data ... patients_df = st.session_state.patients_df # pd.read_excel('patients_info.xlsx') credentials_df = st.session_state.credentials_df # pd.read_excel('credentials.xlsx') assigned_diagnostics = str( list( credentials_df.loc[credentials_df['combination'] == logged_in_radiologist, 'diagnostics_to_radiologist'] )[0] ) assigned_diagnostics_list = [] if assigned_diagnostics == 'nan' else assigned_diagnostics.split(',') if len( assigned_diagnostics_list ) == 0: report_not_ready_df_sorted = pd.DataFrame() else: assigned_patients_df = patients_df[patients_df['diagnostics_combination'].isin( assigned_diagnostics_list )] report_not_ready_df = assigned_patients_df.loc[patients_df['Report_Status'] == 'Not Ready', ] report_not_ready_df_sorted = report_not_ready_df.sort_values(by='ID', ascending=True).reset_index(drop=True) #... Arranging to keep older reports on top if len(report_not_ready_df_sorted) > 0: st.table( report_not_ready_df_sorted.drop('diagnostics_combination', axis=1) ) patient_selected_id = st.selectbox("Patient ID", list(report_not_ready_df_sorted.ID), key = 'gender' ) curr_patient_report_filename = 'generated_reports/report_' + patient_selected_id curr_patient_report_filename_docx = curr_patient_report_filename + '.docx' curr_patient_report_filename_docx_report = curr_patient_report_filename + '_report.docx' curr_patient_report_filename_pdf = curr_patient_report_filename + '.pdf' original_content = utilities.read_docx(curr_patient_report_filename_docx) curr_patient_image_filepath = 'submitted_images/img_' + patient_selected_id curr_patient_image_1 = PIL.Image.open(curr_patient_image_filepath + '_1' + '.jpg') st.image(curr_patient_image_1, caption="", use_column_width=True) curr_patient_image_2 = PIL.Image.open(curr_patient_image_filepath + '_2' + '.jpg') st.image(curr_patient_image_2, caption="", use_column_width=True) curr_patient_image_3 = PIL.Image.open(curr_patient_image_filepath + '_3' + '.jpg') st.image(curr_patient_image_3, caption="", use_column_width=True) edited_content = st.text_area("Report", value=original_content, height=400) if st.button("Approve Report"): curr_patient_info_df = patients_df.loc[patients_df['ID'] == patient_selected_id, ['ID', 'Name', 'Age', 'Gender', 'Doctor_name', 'Submission_time'] ] curr_patient_info_df['Modality'] = 'XR' #.... Save edited docx report #utilities.write_docx(curr_patient_report_filename_docx, edited_content ) curr_patient_report_filename_pdf = curr_patient_report_filename + '_report.pdf' curr_patient_image_path = 'submitted_images/img_' + patient_selected_id + '.jpg' sign_path = 'radiologist_sign/' + logged_in_radiologist + '_sign.jpg' logged_in_radiologist_details_df = credentials_df.loc[credentials_df['combination'] == logged_in_radiologist] utilities.write_docx(edited_content, curr_patient_image_path, curr_patient_info_df, curr_patient_report_filename_docx_report, sign_path, logged_in_radiologist_details_df ) if system == 'Windows': import pythoncom # Manually initialize COM pythoncom.CoInitialize() convert( curr_patient_report_filename_docx_report, curr_patient_report_filename_pdf ) else: utilities.convert_docx_to_pdf( curr_patient_report_filename_docx_report, 'generated_reports' ) #st.write( utilities.list_files( 'generated_reports' ) ) #st.write( utilities.list_directories( 'generated_reports' ) ) #utilities.save_as_docx_markdown2(edited_content, curr_patient_image_path, curr_patient_info_df, curr_patient_report_filename_docx_report, sign_path, logged_in_radiologist_details_df ) # utilities.save_as_pdf_markdown(edited_content, curr_patient_image_path, curr_patient_info_df, curr_patient_report_filename_pdf, sign_path, logged_in_radiologist_details_df ) #json_data = json.loads(edited_content) #headings = ['Findings', 'Impressions', 'Recommendations', 'ICD-10'] # list(json_data.keys()) #markdown_content = edited_content # utilities.json_to_markdown(edited_content) #utilities.save_as_pdf(markdown_content, curr_patient_report_filename_pdf, headings, curr_patient_info_df) st.success( 'Report saved successfully.' ) utilities.display_pdf(curr_patient_report_filename_pdf) patients_df.loc[patients_df['ID'] == patient_selected_id, 'Report_Status'] = 'Report Ready' patients_df.loc[patients_df['ID'] == patient_selected_id, 'approved_by'] = logged_in_radiologist patients_df.to_excel( 'patients_info.xlsx', index=False ) else: st.success('All reports verified. No new report to be verified as of now.') #.... Logic for how many reports radiologist approved .... # Convert 'Submission_time' to datetime patients_df['Submission_time'] = pd.to_datetime(patients_df['Submission_time'], format='%dth %b %Y %H:%M:%S') # Extract date from datetime patients_df['Date'] = patients_df['Submission_time'].dt.date curr_radiologist_approval_df = patients_df[patients_df['approved_by'] == logged_in_radiologist ] if len( curr_radiologist_approval_df ) == 0: #.... If there are no reports approved st.success("No approved reports !") else: reports_approved_summary = curr_radiologist_approval_df.groupby([ 'Date']).size().reset_index(name='num_reports_approved') st.subheader( 'Reports Approved Summary', divider='orange' ) st.table( reports_approved_summary ) elif state.role == 'admin': if 'patients_df' or 'credentials_df' not in st.session_state: st.session_state.patients_df = pd.read_excel('patients_info.xlsx') st.session_state.credentials_df = pd.read_excel('credentials.xlsx') if st.button("Refresh Admin"): st.session_state.patients_df = pd.read_excel('patients_info.xlsx') st.session_state.credentials_df = pd.read_excel('credentials.xlsx') #... Read existing data ... patients_df = st.session_state.patients_df # pd.read_excel('patients_info.xlsx') credentials_df = st.session_state.credentials_df # pd.read_excel('credentials.xlsx') # Convert 'Submission_time' to datetime patients_df['Submission_time'] = pd.to_datetime(patients_df['Submission_time'], format='%dth %b %Y %H:%M:%S') # Extract date from datetime patients_df['Date'] = patients_df['Submission_time'].dt.date # Count the number of entries on each date entries_per_date = patients_df['Date'].value_counts().reset_index() entries_per_date.columns = ['Date', 'Number of Entries'] # Sort the DataFrame by Date entries_per_date = entries_per_date.sort_values(by='Date') fig = px.line(entries_per_date, x='Date', y='Number of Entries', markers=True, text='Number of Entries', labels={'Number of Entries': 'Reports'}) fig.update_xaxes(type='category') fig.update_layout(title='Number of Reports Over Time') st.subheader('Metrics', divider='orange') col100, col101, col102, col103, col104, col105, col105_1 = st.columns(7) with col100: st.metric(label="Total Reports", value = len( patients_df ) ) with col101: st.metric(label="Pending Verification", value = len( patients_df[patients_df['Report_Status'] == 'Not Ready']) ) with col102: st.metric(label="Report Ready", value = len( patients_df[patients_df['Report_Status'] == 'Report Ready']) ) with col103: st.metric(label="Report Generation Failed", value = len( patients_df[patients_df['Report_Status'] == 'Report generation failed. Upload better image.']) ) with col104: st.metric(label="Total Diagnostics", value = len( credentials_df[credentials_df['role'] == 'diagnostics']) ) with col105: st.metric(label="Total Radiologists", value = len( credentials_df[credentials_df['role'] == 'radiologist']) ) with col105_1: st.metric(label="Total Referrals", value = len( credentials_df[credentials_df['role'] == 'referral']) ) st.plotly_chart(fig) #.... User creation ..... st.subheader('User Creation', divider='orange') col120, col121, col122, col123, col123_1 = st.columns([2, 2, 2, 1, 1]) with col120: new_name = st.text_input("Name", key = 'new_name', max_chars = 100 ) with col121: new_username = st.text_input("Username", key = 'new_username', max_chars = 100 ) with col122: new_password = st.text_input("Password", key = 'new_password', max_chars = 100 ) with col123: new_role = st.selectbox("Role", ['diagnostics', 'radiologist', 'referral'], key = 'new_role', index = None ) with col123_1: if st.button("Create New User"): if not ( new_name and new_username and new_password and new_role ): st.markdown("<p style='color: red;'>Please provide all inputs.</p>", unsafe_allow_html=True) else: data_new_user = { 'name': [new_name], 'username': [new_username], 'password': [new_password], 'role': [new_role], 'credits': 20 } # Create a DataFrame new_user_df = pd.DataFrame(data_new_user) new_user_combination = new_user_df.username + '__' + new_user_df.password new_user_df['combination'] = new_user_combination if any( credentials_df['combination'].isin([new_user_combination[0]]) ): st.error('This username and password combination already exists.') else: updated_credentials_df = pd.concat([new_user_df, credentials_df ], ignore_index=True) updated_credentials_df.to_excel( 'credentials.xlsx', index=False ) st.success( 'New user created successfully !' ) #.... Radiologist Details ..... st.subheader('Radiologist Onboarding', divider='orange') col123_2, col123_3, col123_4, col123_5, col123_6, col123_7 = st.columns([1, 2, 1, 2, 2, 1]) with col123_2: radiologist_combination = st.selectbox("Radiologist", list( credentials_df[credentials_df['role'] == 'radiologist']['combination'] ), key = 'radiologist_combination', index = None ) with col123_3: radiologist_designation = st.text_input("Designation", key = 'radiologist_designation', max_chars = 100 ) with col123_4: radiologist_degree = st.text_input("Degree", key = 'radiologist_degree', max_chars = 100 ) with col123_5: radiologist_registration_num = st.text_input("Registration Number", key = 'radiologist_registration_num', max_chars = 100 ) with col123_6: radiologist_sign = st.file_uploader("Signature") with col123_7: if st.button('Onboard'): if not ( radiologist_combination and radiologist_designation and radiologist_degree and radiologist_registration_num and radiologist_sign ): st.markdown("<p style='color: red;'>Please provide all inputs.</p>", unsafe_allow_html=True) else: radiologist_sign_filepath = 'radiologist_sign/' + radiologist_combination + '_sign.jpg' radiologist_details = { 'combination': [radiologist_combination], 'radiologist_designation': [radiologist_designation], 'radiologist_degree': [radiologist_degree], 'radiologist_registration_num': [radiologist_registration_num], 'radiologist_sign_filepath': [radiologist_sign_filepath] } with open(radiologist_sign_filepath, "wb") as f: f.write(radiologist_sign.read()) # Create a DataFrame radiologist_details_df = pd.DataFrame(radiologist_details) selected_columns_credentials = [ col for col in credentials_df.columns if col not in ['radiologist_designation', 'radiologist_degree', 'radiologist_registration_num', 'radiologist_sign_filepath' ] ] credentials_df = pd.merge( credentials_df[ selected_columns_credentials ], radiologist_details_df, on='combination', how='left' ) credentials_df.to_excel('credentials.xlsx', index=False) st.success('Radiologist onboard successful!') #... Assign credits to diagnostics centre ... # credentials_df = pd.read_excel('credentials.xlsx') st.subheader('Assign credits to diagnostics centre', divider='orange') col124, col125, col125_1 = st.columns([2,2,1]) with col124: assign_credits_user = st.selectbox("User", list( credentials_df[credentials_df['role'] == 'diagnostics']['combination'] ), key = 'assign_credits_user', index = None ) with col125: num_credits_given = st.number_input("Number of Credits", min_value=1, step=1, value = None ) with col125_1: if st.button('Assign Credits'): if not ( assign_credits_user and num_credits_given is not None ): st.markdown("<p style='color: red;'>Please provide all inputs.</p>", unsafe_allow_html=True) else: credentials_df.loc[credentials_df['combination'] == assign_credits_user, 'credits'] = list( credentials_df.loc[credentials_df['combination'] == assign_credits_user, 'credits'] )[0] + num_credits_given #.... adding new credits to previous credits credentials_df.to_excel( 'credentials.xlsx', index = False) #... Assign diagnostics centres to referral ... st.subheader('Assign diagnostics centres to referral', divider='orange') col126, col127, col128 = st.columns([2,2,1]) with col126: referral_user = st.selectbox("Referral", list( credentials_df[credentials_df['role'] == 'referral']['combination'] ), key = 'referral_user', index = None ) with col127: assigned_diagnostics_centre = st.selectbox("Diagnostics Centre", list( credentials_df[credentials_df['role'] == 'diagnostics']['combination'] ), key = 'assigned_diagnostics_centre', index = None ) with col128: if st.button('Assign Diagnostics Centre to Referral'): if not ( referral_user and assigned_diagnostics_centre is not None ): st.markdown("<p style='color: red;'>Please provide all inputs.</p>", unsafe_allow_html=True) else: curr_diagnostics = str( list( credentials_df.loc[credentials_df['combination'] == referral_user, 'referred_diagnostics'] )[0] ).split(',') if assigned_diagnostics_centre not in curr_diagnostics: #... if already assigned to referral don't reassign updated_diagnostics_list = ( [] if curr_diagnostics == 'nan' else curr_diagnostics ) + [ assigned_diagnostics_centre ] credentials_df.loc[credentials_df['combination'] == referral_user, 'referred_diagnostics'] = ",".join( updated_diagnostics_list ) credentials_df.to_excel( 'credentials.xlsx', index=False ) #... Assign diagnostics centres to radiologists ... st.subheader('Assign diagnostics centres to radiologists', divider='orange') col129, col130, col131 = st.columns([2,2,1]) with col129: radiologist_user = st.selectbox("Radiologist", list( credentials_df[credentials_df['role'] == 'radiologist']['combination'] ), key = 'radiologist_user', index = None ) with col130: assigned_diagnostics_centre_rad = st.selectbox("Diagnostics Centre", list( credentials_df[credentials_df['role'] == 'diagnostics']['combination'] ), key = 'assigned_diagnostics_centre_rad', index = None ) with col131: if st.button('Assign Diagnostics to Radiologist'): if not ( radiologist_user and assigned_diagnostics_centre_rad is not None ): st.markdown("<p style='color: red;'>Please provide all inputs.</p>", unsafe_allow_html=True) else: curr_diagnostics_rad = str( list( credentials_df.loc[credentials_df['combination'] == radiologist_user, 'diagnostics_to_radiologist'] )[0] ).split(',') if assigned_diagnostics_centre_rad not in curr_diagnostics_rad: #... if already assigned to radiologist don't reassign updated_diagnostics_list_rad = ( [] if curr_diagnostics_rad == 'nan' else curr_diagnostics_rad ) + [ assigned_diagnostics_centre_rad ] credentials_df.loc[credentials_df['combination'] == radiologist_user, 'diagnostics_to_radiologist'] = ",".join( updated_diagnostics_list_rad ) credentials_df.to_excel( 'credentials.xlsx', index=False ) st.table( credentials_df ) elif state.role == 'referral': if 'patients_df' or 'credentials_df' not in st.session_state: st.session_state.patients_df = pd.read_excel('patients_info.xlsx') st.session_state.credentials_df = pd.read_excel('credentials.xlsx') if st.button("Refresh Referral"): st.session_state.patients_df = pd.read_excel('patients_info.xlsx') st.session_state.credentials_df = pd.read_excel('credentials.xlsx') #... Read existing data ... patients_df = st.session_state.patients_df # pd.read_excel('patients_info.xlsx') credentials_df = st.session_state.credentials_df # pd.read_excel('credentials.xlsx') # Convert 'Submission_time' to datetime patients_df['Submission_time'] = pd.to_datetime(patients_df['Submission_time'], format='%dth %b %Y %H:%M:%S') # Extract date from datetime patients_df['Date'] = patients_df['Submission_time'].dt.date curr_referral_combination = st.session_state.username + '__' + st.session_state.password referred_diagnostics = str( list( credentials_df.loc[credentials_df['combination'] == curr_referral_combination, 'referred_diagnostics'] )[0] ) referred_diagnostics_list = [] if referred_diagnostics == 'nan' else referred_diagnostics.split(',') if len( referred_diagnostics_list ) == 0: #.... If there are no referrals to show st.success("No referrals to show !") else: referred_diag_stats_df = patients_df[patients_df['diagnostics_combination'].isin( referred_diagnostics_list )] referred_diag_stats_df_with_name = pd.merge(referred_diag_stats_df, credentials_df[['name', 'combination']] , left_on='diagnostics_combination', right_on='combination', how='left') diag_stats_summary = referred_diag_stats_df_with_name.groupby(['Name', 'Date']).size().reset_index(name='num_reports_uploaded') st.subheader( 'Diagnostics Centre Stats', divider='orange' ) st.table( diag_stats_summary ) else: st.subheader("Login") # Display login form st.text_input( "Username:", value=state.username, key='username_input', on_change=_set_state_cb, kwargs={'username': 'username_input'} ) st.text_input( "Password:", type="password", value=state.password, key='password_input', on_change=_set_state_cb, kwargs={'password': 'password_input'} ) # Check login credentials if not state.login_successful and st.button("Login", on_click=_set_login_cb, args=(state.username, state.password)): st.warning("Wrong username or password.") if __name__ == "__main__": main()
// $Id: UserRealm.java,v 1.16 2006/02/28 12:45:01 gregwilkins Exp $ // Copyright 1996-2004 Mort Bay Consulting Pty. Ltd. // ------------------------------------------------------------------------ // 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.browsermob.proxy.jetty.http; import java.security.Principal; // TODO: Auto-generated Javadoc /* ------------------------------------------------------------ */ /** * User Realm. * * This interface should be specialized to provide specific user lookup and * authentication using arbitrary methods. * * For SSO implementation sof UserRealm should also implement SSORealm. * * @see SSORealm * @version $Id: UserRealm.java,v 1.16 2006/02/28 12:45:01 gregwilkins Exp $ * @author Greg Wilkins (gregw) */ public interface UserRealm { /* ------------------------------------------------------------ */ /** * Gets the name. * * @return the name */ public String getName(); /* ------------------------------------------------------------ */ /** * Get the principal for a username. This method is not guaranteed to return * a Principal for non-authenticated users. * * @param username * the username * @return the principal */ public Principal getPrincipal(String username); /* ------------------------------------------------------------ */ /** * Authenticate a users credentials. Implementations of this method may * adorn the calling context to assoicate it with the authenticated * principal (eg ThreadLocals). If such context associations are made, they * should be considered valid until a * UserRealm.deAuthenticate(UserPrincipal) call is made for this * UserPrincipal. * * @param username * The username. * @param credentials * The user credentials, normally a String password. * @param request * The request to be authenticated. Additional parameters may be * extracted or set on this request as needed for the * authentication mechanism (none required for BASIC and FORM * authentication). * @return The authenticated UserPrincipal. */ public Principal authenticate(String username, Object credentials, HttpRequest request); /* ------------------------------------------------------------ */ /** * Re Authenticate a Principal. Authenicate a principal that has previously * been return from the authenticate method. * * Implementations of this method may adorn the calling context to assoicate * it with the authenticated principal (eg ThreadLocals). If such context * associations are made, they should be considered valid until a * UserRealm.deAuthenticate(UserPrincipal) call is made for this * UserPrincipal. * * @param user * the user * @return True if this user is still authenticated. */ public boolean reauthenticate(Principal user); /* ------------------------------------------------------------ */ /** * Check if the user is in a role. * * @param user * the user * @param role * A role name. * @return True if the user can act in that role. */ public boolean isUserInRole(Principal user, String role); /* ------------------------------------------------------------ */ /** * Dissassociate the calling context with a Principal. This method is called * when the calling context is not longer associated with the Principal. It * should be used by an implementation to remove context associations such * as ThreadLocals. The UserPrincipal object remains authenticated, as it * may be associated with other contexts. * * @param user * A UserPrincipal allocated from this realm. */ public void disassociate(Principal user); /* ------------------------------------------------------------ */ /** * Push role onto a Principal. This method is used to add a role to an * existing principal. * * @param user * An existing UserPrincipal or null for an anonymous user. * @param role * The role to add. * @return A new UserPrincipal object that wraps the passed user, but with * the added role. */ public Principal pushRole(Principal user, String role); /* ------------------------------------------------------------ */ /** * Pop role from a Principal. * * @param user * A UserPrincipal previously returned from pushRole * @return The principal without the role. Most often this will be the * original UserPrincipal passed. */ public Principal popRole(Principal user); /* ------------------------------------------------------------ */ /** * logout a user Principal. Called by authentication mechanisms (eg FORM) * that can detect logout. * * @param user * A Principal previously returned from this realm */ public void logout(Principal user); }
import './bootstrap'; import Alpine from 'alpinejs'; import jQuery from 'jquery'; import 'jquery-validation'; import persist from '@alpinejs/persist'; import 'flowbite'; import { setupAjax, objectifyForm, closeModel, openModel, addHTMLForPut, checkCategoryValidation, handleSelectedCategory, requiredAndTrimmed } from './main'; window.$ = jQuery; Alpine.plugin(persist) window.Alpine = Alpine; window.setupAjax = setupAjax; window.objectifyForm = objectifyForm; window.openModel = openModel; window.closeModel = closeModel; window.checkCategoryValidation = checkCategoryValidation; window.handleSelectedCategory = handleSelectedCategory; window.requiredAndTrimmed = requiredAndTrimmed; window.addHTMLForPut = addHTMLForPut; Alpine.start(); // jQuery Validation Rules const supportedFilesExtensions = ['image/jpeg', 'image/png']; //custom rules $.validator.addMethod("checkEmail", function (value) { return /^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/.test(value); }); $.validator.addMethod("checkPassword", function (value) { return /^(?=.*\d)(?=.*[A-Z])(?=.*[a-z])(?=.*[^\w\d\s:])([^\s]){8,16}$/.test(value); }); $.validator.addMethod('fileExtension', function (value, element) { if (value) { return supportedFilesExtensions.includes(element.files[0].type); } return true; }); $.validator.addMethod('pinCode', function (value) { return /^[1-9]{1}\d{2}\s?\d{3}$/.test(value); }); jQuery.extend(jQuery.validator.messages, { required: "This field is required.", remote: "Please fix this field.", email: "Please enter a valid email address.", checkEmail: "Please enter a valid email address.", checkPassword: "Please enter a valid password.", url: "Please enter a valid URL.", date: "Please enter a valid date.", dateISO: "Please enter a valid date (ISO).", number: "Please enter a valid number.", digits: "Please enter only digits.", equalTo: "Please enter the same value again.", accept: "Please enter a value with a valid extension.", range: jQuery.validator.format("Please enter a value between {0} and {1}."), max: jQuery.validator.format("Please enter a value less than or equal to {0}."), min: jQuery.validator.format("Please enter a value greater than or equal to {0}."), fileExtension: "Please upload file in these format only (jpg, jpeg, png).", pinCode: "Please enter a valid pincode." }); $("#registrationForm").validate({ rules: { name: requiredAndTrimmed(), email: { required: true, checkEmail: { depends: function (element) { return true; } }, normalizer: function (value) { return $.trim(value); } }, role_id: { required: true, }, password: { required: true, minlength: { param: 8, }, checkPassword: { depends: function (element) { return true; } }, normalizer: function (value) { return $.trim(value); } }, password_confirmation: { required: true, equalTo: "#password" }, }, errorElement: 'span', errorPlacement: function (error, element) { error.addClass('invalid-feedback'); element.closest('.form-group').append(error); }, highlight: function (element, errorClass, validClass) { $(element).addClass('is-invalid'); }, unhighlight: function (element, errorClass, validClass) { $(element).removeClass('is-invalid'); } }); $("#loginForm").validate({ rules: { email: { required: true, checkEmail: { depends: function (element) { return true; } }, normalizer: function (value) { return $.trim(value); } }, password: { required: true, minlength: { param: 8, }, checkPassword: { depends: function (element) { return true; } }, normalizer: function (value) { return $.trim(value); } }, }, errorElement: 'span', errorPlacement: function (error, element) { error.addClass('invalid-feedback'); element.closest('.form-group').append(error); }, highlight: function (element, errorClass, validClass) { $(element).addClass('is-invalid'); }, unhighlight: function (element, errorClass, validClass) { $(element).removeClass('is-invalid'); } }); // jQuery Validation Rules End setTimeout(function () { $('#toast-success').fadeOut('fast'); $('#toast-danger').fadeOut('fast'); $('#toast-warning').fadeOut('fast'); }, 5000);
package br.com.azindustria.azsim.mbean; import br.com.azindustria.azsim.core.lazy.CustomLazyDataModel; import br.com.azindustria.azsim.entity.*; import br.com.azindustria.azsim.repository.ClienteRepository; import br.com.azindustria.azsim.service.ClienteService; import br.com.azindustria.azsim.type.NaturezaEnum; import lombok.Data; import lombok.extern.slf4j.Slf4j; import org.primefaces.PrimeFaces; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; import javax.annotation.PostConstruct; import javax.faces.application.FacesMessage; import javax.faces.context.FacesContext; import javax.faces.view.ViewScoped; import java.io.Serializable; import java.util.ArrayList; import java.util.List; import static java.util.Objects.isNull; import static java.util.Objects.nonNull; @Slf4j @Data @Component(value = "clienteMB") @ViewScoped public class ClienteMB implements Serializable { @Autowired private ClienteService clienteService; @Autowired private CustomLazyDataModel<Cliente, Long, ClienteRepository> clienteLazyDataModel; private Cliente cliente; private String documentoMask = "999999999-99"; private Setor selectedSetor; private Contato selectedContato; private Viagem selectedViagem; private List<Contato> selectedContatos; private List<Setor> selectedSetores; private List<Viagem> selectedViagens; private boolean viewOnly; @PostConstruct public void init() { log.info("Chamado método Construtor"); if (isNull(cliente)) { novo(); } } public void novo() { cliente = new Cliente(); cliente.setUf("RS"); cliente.setCentral(new Central()); cliente.getCentral().setCodificador(new Codificador()); viewOnly = false; } public void salvar() { cliente = clienteService.salvar(cliente); } public void changeMask() { if (nonNull(cliente.getNatureza()) && cliente.getNatureza().equals(NaturezaEnum.FISICA)) { documentoMask = "999999999-99"; } else { documentoMask = "99.999.999/9999-99"; } } // ------------------------------------------------------ // CONTATOS // ------------------------------------------------------ public void adicionarNovoContato() { if (isNull(cliente.getContatos())) { cliente.setContatos(new ArrayList<>()); } selectedContato = new Contato(); } public void salvarContato() { cliente.getContatos().add(selectedContato); PrimeFaces.current().executeScript("PF('cadastrarContatoDialog').hide()"); } public String getDeleteContatoButtonMessage() { if (hasSelectedContatos()) { int size = this.selectedContatos.size(); return size > 1 ? size + " contatos selecionados" : "1 contato selecionado"; } return "Excluir"; } public boolean hasSelectedContatos() { return this.selectedContatos != null && !this.selectedContatos.isEmpty(); } public void deleteSelectedContatos() { cliente.getContatos().removeAll(this.selectedContatos); this.selectedContatos = null; FacesContext.getCurrentInstance().addMessage(null, new FacesMessage("Contato excluído com sucesso")); } // ------------------------------------------------------ // SETORES // ------------------------------------------------------ public void adicionarNovoSetor() { if (isNull(cliente.getCentral().getSetores())) { cliente.getCentral().setSetores(new ArrayList<>()); } selectedSetor = new Setor(); } public void salvarSetor() { cliente.getCentral().getSetores().add(selectedSetor); PrimeFaces.current().executeScript("PF('cadastrarSetorDialog').hide()"); } public String getDeleteSetorButtonMessage() { if (hasSelectedSetores()) { int size = this.selectedSetores.size(); return size > 1 ? size + " setores selecionados" : "1 setor selecionado"; } return "Excluir"; } public boolean hasSelectedSetores() { return this.selectedSetores != null && !this.selectedSetores.isEmpty(); } public void deleteSelectedSetores() { cliente.getCentral().getSetores().removeAll(this.selectedSetores); this.selectedSetores = null; FacesContext.getCurrentInstance().addMessage(null, new FacesMessage("Setor excluído com sucesso")); } // ------------------------------------------------------ // VIAGENS // ------------------------------------------------------ public void adicionarNovaViagem() { if (isNull(cliente.getViagens())) { cliente.setViagens(new ArrayList<>()); } selectedViagem = new Viagem(); } public void salvarViagem() { cliente.getViagens().add(selectedViagem); PrimeFaces.current().executeScript("PF('cadastrarViagemDialog').hide()"); } public String getDeleteViagemButtonMessage() { if (hasSelectedViagens()) { int size = this.selectedViagens.size(); return size > 1 ? size + " viagens selecionadas" : "1 viagem selecionada"; } return "Excluir"; } public boolean hasSelectedViagens() { return this.selectedViagens != null && !this.selectedViagens.isEmpty(); } public void deleteSelectedViagens() { cliente.getViagens().removeAll(this.selectedViagens); this.selectedViagens = null; FacesContext.getCurrentInstance().addMessage(null, new FacesMessage("Viagem excluída com sucesso")); } }
```python import pyqtgraph as pg from pyqtgraph.GraphItems import GraphItem from pyqtgraph.Qt import QtCore, QtGui class CustomGraphItem(GraphItem): def __init__(self, nodes, edges, **kwargs): super().__init__(**kwargs) self.nodes = nodes self.edges = edges self.data = {} self.setData(self.nodes, self.edges) def setData(self, nodes, edges): self.nodes = nodes self.edges = edges self.data = {} for node in nodes: self.data[node] = [] for edge in edges: self.data[edge[0]].append(edge[1]) self.updateGraph() def updateGraph(self): self.clear() for node, edges in self.data.items(): self.plot(x=node[0], y=node[1], symbol='o', symbolBrush=(node[2],), pen=None, name=f'Node {node}') for edge in edges: self.plot(x=[node[0], edge[0]], y=[node[1], edge[1]], symbol='', symbolBrush=None, pen='r', name=f'Edge {node}-{edge}') def mouseDragEvent(self, ev): if ev.button() == QtCore.Qt.LeftButton: item = self.scene().itemAt(ev.pos()) if item is not None and isinstance(item, pg.GraphicsObject): node = item.name().split()[1] self.nodes[int(node)] = (ev.pos().x(), ev.pos().y()) self.setData(self.nodes, self.edges) def mouseClickEvent(self, ev): if ev.button() == QtCore.Qt.LeftButton: item = self.scene().itemAt(ev.pos()) if item is not None and isinstance(item, pg.GraphicsObject): node = item.name().split()[1] print(f'Node {node} clicked.') if __name__ == '__main__': app = QtGui.QApplication([]) view = pg.GraphicsView() layout = pg.GraphicsLayoutWidget() view.setCentralItem(layout) graph = CustomGraphItem(nodes=[(100, 100, 'r'), (300, 300, 'g'), (500, 100, 'b')], edges=[(0, 1), (1, 2)]) layout.addItem(graph) view.show() app.exec_() ```
import { useContext } from "react" import { SocketContext } from "../../../context/Socket" import Highcharts from "highcharts" import HighchartsReact from "highcharts-react-official" import "../style.css" export default function AverageDuration() { const { dataAvgDuration } = useContext(SocketContext) const cardContent = (value = null, name = '', icon = '', background = '', color = '') => { return ( <div className="item pt-1"> <div className="d-flex pr-2"> <div className="d-flex flex-column justify-content-between w-100"> <div className='d-flex flex-row mt-2 align-items-center justify-content-between'> <div className='d-flex align-items-center'> <div className="card-content-icon d-flex justify-content-center align-items-center" style={{ background: background }}> <i className={icon} style={{ color: color }}></i> </div> <div className="card-content--color h-100 px-2">{name} </div> </div> <span className="card-content__value_duration g-bdr-round px-2">{value || 0}</span> </div> </div> </div> </div> ) } const doubleCharts = () => { const options = { chart: { backgroundColor: "transparent", type: "pie", height: 85, width: 90, style: { marginRight: '10px' } }, title: { style: { display: 'none' } }, plotOptions: { pie: { allowPointSelect: true, cursor: 'pointer', showInLegend: true, size: '165%', style: { marginRight: '10px' } }, }, xAxis: { labels: { style: { color: '#525252' } } }, exporting: { enabled: false }, legend: { enabled: false, align: 'center', verticalAlign: 'bottom', layout: 'horizontal', itemStyle: { color: '#525252' }, itemHoverStyle: { color: '#525252' }, }, tooltip: { enabled: false, pointFormat: '{series.name}: <b>{point.percentage:.1f}%</b>' }, credits: { enabled: false }, series: [ { name: 'Total', borderWidth: 0, innerSize: '90%', data: [ { name: "Answered", y: dataAvgDuration.answer_rate, color: '#2f72c3', dataLabels: { enabled: false, format: '{point.percentage:.0f}%', distance: -50, backgroundColor: 'none', borderWidth: 0, style: { fontSize: "20px", color: '#525252' } } }, { name: "Abandoned", y: dataAvgDuration.answer_rate ? dataAvgDuration.abandone_rate : 1, color: '#d5e0ff', dataLabels: { enabled: false }, } ] } ] }; const options2 = { chart: { backgroundColor: "transparent", type: "pie", height: 85, width: 90, }, title: { style: { display: 'none' } }, plotOptions: { pie: { allowPointSelect: true, cursor: 'pointer', showInLegend: true, size: '165%' }, }, xAxis: { labels: { style: { color: '#525252' } } }, exporting: { enabled: false }, legend: { enabled: false, align: 'center', verticalAlign: 'bottom', layout: 'horizontal', itemStyle: { color: '#525252' }, itemHoverStyle: { color: '#525252' }, }, tooltip: { enabled: false, pointFormat: '{series.name}: <b>{point.percentage:.1f}%</b>' }, credits: { enabled: false }, series: [ { name: 'Total', borderWidth: 0, innerSize: '90%', data: [ { name: "Abandoned", y: dataAvgDuration.abandone_rate, color: '#ea5455', dataLabels: { enabled: false, format: '{point.percentage:.0f}%', distance: -70, backgroundColor: 'none', borderWidth: 0, style: { fontSize: "20px", color: '#525252' } } }, { name: "Answered", y: dataAvgDuration.abandone_rate ? dataAvgDuration.answer_rate : 100, color: '#ea54542a', dataLabels: { enabled: false, format: '{point.percentage:.0f}%', }, } ] } ] }; return ( <div className='d-flex flex-column justify-content-start'> <div> <HighchartsReact highcharts={Highcharts} options={options} /> <div className="chart-icon--phone"> <i className="chart-icon__phone bx bxs-phone bx-rotate-270" style={{color: '#2f72c3'}}></i> </div> </div> <div> <HighchartsReact highcharts={Highcharts} options={options2} /> <div className="chart-icon"> <i className="chart-icon__x bx bx-x"></i> </div> </div> </div> ) } return ( <div className='card-content pt-3 g-bdr-round d-flex justify-content-center px-2 flex-column'> <h5 className='title-chart px-3'>Average Duration</h5> <div className="g-bdr-round d-flex flex-row"> <div className='px-3 pl-0' style={{ width: '48%' }}> <ul className='pl-0 d-flex flex-column g-list-none mt-2'> <li> {cardContent(dataAvgDuration.avg_asa, 'ASA', 'bx bx-hourglass', '#d5e0ff', '#2f72c3')}</li> <li> {cardContent(dataAvgDuration.avg_acd, 'ACD', 'bx bx-timer', '#ea545536', '#ea5455')}</li> <li> {cardContent(dataAvgDuration.avg_acw, 'ACW', 'bx bx-spreadsheet', '#28c76f40', '#28c76f')}</li> <li> {cardContent(dataAvgDuration.avg_aht, 'AHT', 'bx bx-window', '#ff9f4342', '#ff9f43')}</li> </ul> </div> <div className='d-flex align-items-center' style={{ width: '49.5%' }}> <div className=" d-flex justify-content-center"> <h6 className="title-chart pl-4" style={{ position: 'absolute', marginTop: '-25px' }}>Call Percentage</h6> {doubleCharts()} <div className="call-percentage d-flex flex-column align-items-end"> <div className="call-percentage__info"> <h5 className="call-percentage__info-value">{dataAvgDuration.answer_rate ? `${dataAvgDuration.answer_rate}%` : '-'}</h5> <span className="call-percentage__info-title">Answered</span> </div> <div className="call-percentage__info"> <h5 className="call-percentage__info-value">{dataAvgDuration.abandone_rate ? `${dataAvgDuration.abandone_rate}%` : '-'}</h5> <span className="call-percentage__info-title">Abandoned</span> </div> </div> </div> </div> </div> </div> ) }
import { Box, Stack, Card, CardContent, Typography } from "@mui/material"; type CardTextType = [string, string]; type CardsTextType = { expeditor: CardTextType[]; deliverer: CardTextType[]; }; type BottomCardsProps = { youAre: keyof CardsTextType; }; const cardsTxt: CardsTextType = { expeditor: [ [ "Déposez une annonce", "Dites ce que vous voulez envoyer. Détaillez votre annonce avec l'adresse, les dimensions, le poids et le détail de livraison.", ], [ "Recevez des propositions", "Les voyageurs vous contactent par texto ou mail. Mettez-vous d'accord sur les détails de livraison (prix, date d'enlèvement et de livraison).", ], [ "Validez votre réservation", "Réglez en ligne pour bénéficier d'une assurance et suivre votre colis. Votre paiement ne sera versé au voyageur qu'une fois le colis livré.", ], ], deliverer: [ [ "Enregistrez vos trajets", "Renseignez le ou les trajets sur lesquels vous souhaitez assurer le transport d’objets ou de colis. Bring4you vous adressera des propositions de collecte que vous pouvez accepter ou non.", ], [ "Contactez les expéditeurs", "Vous pouvez aussi choisir vous-même les demandes de collecte qui vous intéressent, puis vous mettre d’accord avec l’expéditeur sur les détails de la livraison (participation à vos frais de voyage, date d’enlèvement, de collecte…).", ], [ "Recevez le paiement", "Une fois la livraison réalisée par vous-même, vous recevrez de Bring4you le paiement de la participation à vos frais de transport directement sur votre compte.", ], ], }; export const BottomCards = ({ youAre }: BottomCardsProps) => { return ( <Stack spacing={{ xs: 1, sm: 2, md: 4 }} direction={{ xs: "column", sm: "row" }} justifyContent="space-evenly" mx={4} my={2} > {cardsTxt[youAre].map((card, i) => ( <Card key={`${card}-${i}`} sx={{ width: { sm: "30%" } }}> <CardContent> <Box> {card.map((txt, i) => ( <Typography key={`${txt}-${i}`} component={"p"} marginBottom={1} fontSize={i === 0 ? 18 : 12} > {txt} </Typography> ))} </Box> </CardContent> </Card> ))} </Stack> ); };
const express = require('express') const exphbs = require("express-handlebars") const conn = require('./db/conn') const User = require('./models/User') const Address = require('./models/Address') const app = express() app.use(express.urlencoded({extended:true})) app.use(express.json()) app.engine('handlebars', exphbs.engine()) app.set('view engine', 'handlebars') app.use(express.static('public')) app.get('/users/create', (req,res)=>{ res.render('adduser') }) app.post('/users/create', async (req,res)=>{ const name = req.body.name const occupation = req.body.occupation let newsletter = req.body.newsletter if (newsletter === 'on') { newsletter = true } else{ newsletter = false } console.log(req.body); await User.create({name,occupation,newsletter}) res.redirect('/') }) app.get('/users/:id', async (req,res) => { const id = req.params.id const user = await User.findOne({raw:true, where:{id:id}}) res.render('userview', {user}) }) app.post('/users/delete/:id', async (req,res)=>{ const id = req.params.id await User.destroy({where:{id:id}}) res.redirect('/') }) app.get('/users/edit/:id', async (req,res)=>{ const id = req.params.id try{ const user = await User.findOne({include : Address ,where:{id:id}}) res.render('useredit',{user: user.get({plain:true})}) } catch (error){ console.log(error) } }) app.post('/users/update', async (req,res)=>{ const id = req.body.id const name = req.body.name const occupation = req.body.occupation let newsletter = req.body.newsletter if (newsletter === 'on') { newsletter = true } else { newsletter = false } const userData = { id, name, occupation, newsletter } await User.update(userData, {where:{id:id}}) res.redirect('/') }) app.get('/', async (req,res)=>{ const users = await User.findAll({raw: true}) console.log(users); res.render('home',{users}) }) app.post('/address/create', async (req,res)=>{ const UserId = req.body.UserId const street = req.body.street const number = req.body.number const city = req.body.city const address = { UserId, street, number, city } await Address.create(address) res.redirect(`/users/edit/${UserId}`) }) app.post('/address/delete', async (req,res)=>{ const UserId = req.body.UserId const id = req.body.id await Address.destroy({ where: {id:id} }) res.redirect(`/users/edit/${UserId}`) }) conn // .sync({force:false}) .sync() .then(()=>{ app.listen(3000) }).catch(err=>console.log(err))
import styled from "styled-components"; import { Announcement } from "../components/Announcement"; import { Footer } from "../components/Footer"; import Header from "../components/Header"; import { FontAwesomeIcon } from "@fortawesome/react-fontawesome"; import { faMinus, faPlus } from "@fortawesome/free-solid-svg-icons"; import { useSelector, useDispatch } from "react-redux"; import store from "../redux/store"; import { changeAmount, removeFromCart } from "../redux/cartRedux"; import { useEffect } from "react"; import { mobile, tablet } from "../responsive"; export const Cart = () => { const cart = useSelector((state) => state.cart); const dispatch = useDispatch(); const productsElements = cart.products.map((product, index) => { return ( <Product> <ProductDetail> <Image src={product.img} /> <Details> <ProductName> {product.title} </ProductName> <ProductId> <b>ID: </b> {product._id} </ProductId> <ProductColor color={product.color} /> <ProductSize> <b>Size: </b> {product.size} </ProductSize> </Details> </ProductDetail> <PriceDetail> <ProductAmountContainer> <FontAwesomeIcon icon={faPlus} onClick={() => { dispatch(changeAmount({ index, operation: "inc", productPrice: product.price })); }} /> <ProductAmount>{product.quantity}</ProductAmount> <FontAwesomeIcon icon={faMinus} onClick={() => { dispatch(changeAmount({ index, operation: "dec", productPrice: product.price, quantity:cart.quantity })); }} /> </ProductAmountContainer> <ProductPrice>${(product.price * product.quantity).toFixed(2)}</ProductPrice> </PriceDetail> </Product> ); }) return ( <Container> <Announcement /> <Header /> <Wrapper> <Title>Your Cart</Title> <Top> <TopButton>Continue Shopping</TopButton> <TopTexts> </TopTexts> <TopButton type="filled">Checkout</TopButton> </Top> <Bottom> <Info> {console.log(cart)} {productsElements.length === 0 ? <p>No products in cart</p> : productsElements} </Info> <Summary> <SummaryTitle>Order Summary</SummaryTitle> <SummaryItem> <SummaryItemText>Subtotal</SummaryItemText> <SummaryItemPrice>$ {cart.total.toFixed(2)}</SummaryItemPrice> </SummaryItem> <SummaryItem> <SummaryItemText>Estimated Shipping</SummaryItemText> <SummaryItemPrice>$ 0.00</SummaryItemPrice> </SummaryItem> <SummaryItem> <SummaryItemText>Shipping Discount</SummaryItemText> <SummaryItemPrice>$ -0.00</SummaryItemPrice> </SummaryItem> <SummaryItem> <SummaryItemText type="total">Total</SummaryItemText> <SummaryItemPrice>$ {cart.total.toFixed(2)}</SummaryItemPrice> </SummaryItem> <SummaryButton>Checkout Now</SummaryButton> </Summary> </Bottom> </Wrapper> <Footer /> </Container> ); }; const Container = styled.div``; const Wrapper = styled.div` padding: 20px; width: 80%; margin: 0 auto; padding-bottom: 150px; ${mobile({ width: "95%", padding: '0' })} `; const Title = styled.h1` font-weight: 300; text-align: center; margin-bottom: 20px; `; const Top = styled.div` display: flex; align-items: center; justify-content: space-between; `; const TopButton = styled.button` padding: 10px; font-weight: 600; cursor: pointer; border: ${(prop) => (prop.type === "filled" ? "none" : "2px solid black")}; background-color: ${(prop) => (prop.type === "filled" ? "black" : "transparent")}; color: ${(prop) => (prop.type === "filled" ? "white" : "black")}; transition: 0.3s; &:hover { transition: 0.3s; background-color: teal; color: #fff; } `; const TopTexts = styled.div``; const TopText = styled.span` text-decoration: underline; cursor: pointer; margin: 0 10px; `; const Bottom = styled.div` display: flex; justify-content: space-between; ${tablet({ flexDirection: "column" })} `; const Info = styled.div` flex: 3; margin-top: 50px; `; const Product = styled.div` display: flex; justify-content: space-between; border-bottom: 1px solid #eee; padding: 30px 20px; /* margin: 10px 0; */ border-right: 1px solid #eee; &:last-of-type { border-bottom: none; } `; const ProductDetail = styled.div` flex: 2; display: flex; `; const Image = styled.img` /* width: 200px; */ height: 200px; align-self: center; ${tablet({ height: "150px", })} `; const Details = styled.div` padding: 20px; display: flex; flex-direction: column; justify-content: space-between; & > * { margin-top: 10px; } `; const ProductName = styled.h1` ${mobile({ fontSize: "18px" })}`; const ProductId = styled.span` ${tablet({ display: "none" })} `; const ProductColor = styled.div` width: 20px; height: 20px; border-radius: 50%; background-color: ${(props) => props.color}; border: 1px solid black; `; const ProductSize = styled.span``; const PriceDetail = styled.div` flex: 1; display: flex; flex-direction: column; align-items: center; justify-content: center; `; const ProductAmountContainer = styled.div` display: flex; align-items: center; margin-bottom: 20px; svg { cursor: pointer; } `; const ProductAmount = styled.span` font-size: 24px; margin: 5px; `; const ProductPrice = styled.span` font-size: 30px; font-weight: 200; `; const Summary = styled.div` flex: 1; border: 0.5px solid lightgray; border-left: 0px; border-radius: 10px; border-top-left-radius: 0; border-bottom-left-radius: 0; padding: 30px 30px 50px 30px; height: max-content; position: sticky; top: 239px; `; const SummaryTitle = styled.h1` font-weight: 500; `; const SummaryItemPrice = styled.span``; const SummaryItemText = styled.span``; const SummaryItem = styled.div` margin: 30px 0; display: flex; justify-content: space-between; &:last-of-type ${SummaryItemPrice}, &:last-of-type ${SummaryItemText} { font-weight: 500; font-size: 24px; } `; const SummaryButton = styled.button` width: 100%; padding: 10px; background-color: #000; color: #fff; font-weight: 600; border: none; border: 2px solid black; transition: 0.3s; cursor: pointer; &:hover { transition: 0.3s; background-color: #fff; color: #000; } `;
/* * Copyright © 2020 EUSTYLE LABORATORY - ALL RIGHTS RESERVED. * UNAUTHORIZED COPYING OF THIS FILE, VIA ANY MEDIUM IS STRICTLY PROHIBITED PROPRIETARY AND CONFIDENTIAL. */ import { Wrapper } from '@vue/test-utils' import Vue from 'vue' import { HttpStatusCode } from '~/models/http-status-code' import PasswordResetsCommitPage from '~/pages/password-resets/_token.vue' import { PasswordResetsApi } from '~/services/api/password-resets-api' import { ValidationObserverInstance } from '~/support/validation/types' import { createAxiosError } from '~~/test/helpers/create-axios-error' import { createMockedApi } from '~~/test/helpers/create-mocked-api' import { createMockedRoute } from '~~/test/helpers/create-mocked-route' import { createMockedRouter } from '~~/test/helpers/create-mocked-router' import { getValidationObserver } from '~~/test/helpers/get-validation-observer' import { setData } from '~~/test/helpers/set-data' import { setupComponentTest } from '~~/test/helpers/setup-component-test' import { submit } from '~~/test/helpers/trigger' describe('pages/password-resets/_token.vue', () => { const { mount } = setupComponentTest() const token = 'x'.repeat(60) const params = { token } const $api = createMockedApi('passwordResets') const $route = createMockedRoute({ params }) const $router = createMockedRouter() const mocks = { $api, $route, $router } let wrapper: Wrapper<Vue & any> async function mountComponent () { wrapper = mount(PasswordResetsCommitPage, { mocks }) await wrapper.vm.$nextTick() } function unmountComponent () { wrapper.destroy() } beforeEach(() => { jest.spyOn($api.passwordResets, 'verify').mockResolvedValue(undefined) }) afterEach(() => { jest.clearAllMocks() }) it('should display message when token verified', async () => { await mountComponent() expect(wrapper).toMatchSnapshot() unmountComponent() }) it('should display message when server responses 403 Forbidden', async () => { jest.spyOn($api.passwordResets, 'verify').mockRejectedValueOnce(createAxiosError(HttpStatusCode.Forbidden)) await mountComponent() expect(wrapper).toMatchSnapshot() unmountComponent() }) describe('validate', () => { const context: { params: Dictionary } = { params: { ...params } } beforeAll(async () => { await mountComponent() }) afterAll(() => { unmountComponent() }) it('should return true when valid token given', () => { const result = wrapper.vm.$options.validate!(context) expect(result).toBeTrue() }) it('should return false when valid token not given', () => { context.params.token = 'x'.repeat(59) expect(wrapper.vm.$options.validate!(context)).toBeFalse() context.params.token = 'x'.repeat(61) expect(wrapper.vm.$options.validate!(context)).toBeFalse() context.params.token = '-'.repeat(60) expect(wrapper.vm.$options.validate!(context)).toBeFalse() context.params = {} expect(wrapper.vm.$options.validate!(context)).toBeFalse() }) }) describe('validation', () => { const formValues: PasswordResetsApi.CommitForm = { password: 'PaSSWoRD' } async function validate (values: Partial<PasswordResetsApi.CommitForm> = {}): Promise<ValidationObserverInstance> { const form = { ...formValues, ...values } await setData(wrapper, { form, verified: true }) const observer = getValidationObserver(wrapper) await observer.validate() jest.runOnlyPendingTimers() return observer } beforeAll(async () => { await mountComponent() jest.spyOn($api.passwordResets, 'verify').mockResolvedValueOnce() }) afterAll(() => { unmountComponent() }) it('should pass when input correctly', async () => { const observer = await validate() expect(observer).toBePassed() }) it('should fail when password is empty', async () => { const observer = await validate({ password: '' }) expect(observer).not.toBePassed() }) it('should fail when password.length < 8', async () => { let observer: ValidationObserverInstance observer = await validate({ password: 'x'.repeat(7) }) expect(observer).not.toBePassed() observer = await validate({ password: 'x'.repeat(8) }) expect(observer).toBePassed() }) }) describe('submit', () => { const form = { password: 'PaSSWoRD' } beforeEach(async () => { await mountComponent() jest.spyOn($api.passwordResets, 'commit').mockResolvedValue(undefined) }) afterEach(() => { unmountComponent() }) it('should run validation', async () => { await submit(() => wrapper.find('[data-form]')) expect(wrapper).toMatchSnapshot() }) it('should not call api when validation failed', async () => { await submit(() => wrapper.find('[data-form]')) expect($api.passwordResets.commit).not.toHaveBeenCalled() }) it('should call $api.passwordResets.commit when validation succeeded', async () => { await setData(wrapper, { form }) await submit(() => wrapper.find('[data-form]')) expect($api.passwordResets.commit).toHaveBeenCalledTimes(1) expect($api.passwordResets.commit).toHaveBeenCalledWith({ form, token }) }) it('should display message when api responses 2xx', async () => { await setData(wrapper, { form }) await submit(() => wrapper.find('[data-form]')) expect(wrapper).toMatchSnapshot() }) it('should display errors when api responses bad request', async () => { jest.spyOn($api.passwordResets, 'commit').mockRejectedValue(createAxiosError(HttpStatusCode.BadRequest, { errors: { password: ['パスワードを入力してください。'] } })) await setData(wrapper, { form }) await submit(() => wrapper.find('[data-form]')) expect(wrapper.vm.committed).toBeFalse() expect(wrapper).toMatchSnapshot() }) }) })
import React from "react"; import { useNavigate } from "react-router-dom"; function ProfileCardOneday({ onedayId, onedayTitle, onedayContent, onedayTag, onedayGroupSize, onedayLocation, imageUrlList, onedayAttendantsNum, thumbnailUrl }) { const navigate = useNavigate(); console.log('onedayTag',onedayTag); return ( <> <div onClick={() => navigate(`/oneday/${onedayId}`)} className="cursor-pointer rounded-[18px] flex w-[360px] border border-[#E8E8E8] rounded-xl h-[175px] items-center mb-[16px] bg-white " > <div className="flex items-center rounded-xl "> <img className="rounded-[15px] w-[130px] h-[130px] border-[1px] ml-5 aspect-square object-cover" src={imageUrlList.length > 0 ? imageUrlList[0] : `${process.env.PUBLIC_URL}/images/favicon.png`} alt="clubThumbnail" /> </div> <div className="w-[172px] h-[130px] ml-[20px] flex justify-start flex-col"> <div className="flex justify-between"> <div className="text-[12px] text-orange-400 mb-[12px] w-[240px] flex "> {onedayTag && onedayTag.map((tag) => { return ( <div key={tag} className="rounded-[50px] mb-[15px] mr-1 b-1 border-1 px-2 bg-orange-400 text-white flex justify-start align-center"> {tag} </div> ); })} </div> </div> <div className="w-[160px] h-[60px] truncate hover:text-clip text-[20px] font-bold"> {onedayTitle} </div> <div className="flex justify-between"> <div className="text-[14px] flex items-center text-[#747474] truncate hover:text-clip"> <img className="w-[21px] h-[21px] mr-[2px]" src={`${process.env.PUBLIC_URL}/images/location.svg`} alt="location" /> {onedayLocation} </div> <div className="text-[14px] flex items-center text-[#747474]"> <img className="w-[14px] h-[14px] mr-[5px]" src={`${process.env.PUBLIC_URL}/images/count.svg`} alt="count" /> {onedayAttendantsNum}/{onedayGroupSize} </div> </div> </div> </div> </> ); } export default ProfileCardOneday;
package com.example.newsapp.News.Adapter import android.os.Build import android.view.LayoutInflater import android.view.ViewGroup import androidx.navigation.NavController import androidx.recyclerview.widget.AsyncListDiffer import androidx.recyclerview.widget.DiffUtil import androidx.recyclerview.widget.RecyclerView import com.bumptech.glide.Glide import com.example.newsapp.News.Models.Article import com.example.newsapp.News.UI.Fragment.BreakingNewsFragmentDirections import com.example.newsapp.News.UI.Fragment.SaveNewsFragmentDirections import com.example.newsapp.News.Utils.Converter import com.example.newsapp.R import com.example.newsapp.databinding.ItemArticleBinding class NewsAdapter(private val navController: NavController, private val nameFragment: String = "Breaking") : RecyclerView.Adapter<NewsAdapter.ArticleViewHolder>() { inner class ArticleViewHolder(val binding: ItemArticleBinding) : RecyclerView.ViewHolder(binding.root) private val differCallBack = object : DiffUtil.ItemCallback<Article>() { override fun areItemsTheSame(oldItem: Article, newItem: Article): Boolean { // Because Article From API don't have ID return oldItem.url == newItem.url } override fun areContentsTheSame(oldItem: Article, newItem: Article): Boolean { return oldItem == newItem } } val differ = AsyncListDiffer(this, differCallBack) override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ArticleViewHolder { return ArticleViewHolder( ItemArticleBinding.inflate(LayoutInflater.from(parent.context), parent, false) ) } override fun getItemCount(): Int { return differ.currentList.size } override fun onBindViewHolder(holder: ArticleViewHolder, position: Int) { val article = differ.currentList[position] holder.binding.apply { if (article.urlToImage == "") { ivArticleImage.setImageResource(R.drawable.baseline_news_24) } else Glide.with(this.root).load(article.urlToImage).into(ivArticleImage) tvSource.text = article.source?.name tvTitle.text = article.title if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { tvPublishedAt.text = article.publishedAt?.let { Converter.FormatFullDate(it) } } else tvPublishedAt.text = article.publishedAt articleItem.setOnClickListener { //onItemClickListener?.let { it(article) } if (article != null) { if (nameFragment == "Breaking") { val action = BreakingNewsFragmentDirections.actionBreakingNewsFragmentToArticleFragment( article ) navController.navigate(action) } else { val action = SaveNewsFragmentDirections.actionSaveNewsFragmentToArticleFragment(article) navController.navigate(action) } } } } } private var onItemClickListener: ((Article) -> Unit)? = null fun setOnItemClickListener(onItemClickListener: ((Article) -> Unit)?) { this.onItemClickListener = onItemClickListener } }
package vn.codegym.config; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder; import org.springframework.security.config.annotation.web.builders.HttpSecurity; import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; import org.springframework.security.web.authentication.rememberme.InMemoryTokenRepositoryImpl; import org.springframework.security.web.authentication.rememberme.PersistentTokenRepository; import vn.codegym.service.impl.MyUserDetailServiceImpl; @Configuration @EnableWebSecurity public class WebSecurityConfig extends WebSecurityConfigurerAdapter { @Autowired private MyUserDetailServiceImpl userDetailService; @Bean public BCryptPasswordEncoder passwordEncoder() { return new BCryptPasswordEncoder(); } @Override protected void configure(AuthenticationManagerBuilder auth) throws Exception { auth.userDetailsService(userDetailService).passwordEncoder(passwordEncoder()); } @Override protected void configure(HttpSecurity http) throws Exception { http.csrf().disable() .formLogin() .defaultSuccessUrl("/home").permitAll() .loginPage("/login") .and() .authorizeRequests() .antMatchers("/login").permitAll() .anyRequest().authenticated(); http.authorizeRequests().and().rememberMe() .tokenRepository(persistentTokenRepository()) .tokenValiditySeconds(30*24*60*60); } @Bean public PersistentTokenRepository persistentTokenRepository(){ InMemoryTokenRepositoryImpl inMemoryTokenRepository = new InMemoryTokenRepositoryImpl(); return inMemoryTokenRepository; } }
// this page defines basic structure for the page that allows input of data for new product // imports for react and basic layout structure const React = require('react') const Layout = require('./Layouts/layout') class New extends React.Component { render() { return ( <Layout title="Add New Map" > <header id='header'> {/*title header for page */} <h1>Add a Map</h1> </header> <br /> <form action="/products" method="POST"> {/* input box new product country data*/} <label htmlFor="country">Country: </label> <input type="text" id="country" name="country" /> <br /> {/* input box new product city data*/} <label htmlFor="city">City: </label> <input type="text" id="city" name="city" /> <br /> {/* input box new product vintage*/} <label htmlFor="year">Year: </label> <input type="text" id="year" name="year" /> <br /> {/* input box new product image link*/} <label htmlFor="path">Path: </label> <input type="text" id="path" name="path" /> <br /> {/* input box for name of the illustrator */} <label htmlFor="illustrator">Illustrator: </label> <input type="text" id="illustrator" name="illustrator" /> <br /> {/* input box for in stock quantity */} <label htmlFor="quantity">Quantity: </label> <input type="number" id="quantity" name="quantity" /> <br /> {/* input box for the products price */} <label htmlFor="price">Price: </label> <input type="number" id="price" name="price" /> <br /> {/* submit toggle for the data */} <input type="submit" value="Create Product"/> </form> <nav> {/* navigates back to index page */} <a href="/products">Back to the Map Index</a> </nav> </Layout> ) } } module.exports = New
Konvektive Koordinaten Konvektive Koordinaten sind krummlinige Koordinatensysteme auf dem euklidischen Raum formula_1, die an einen Träger gebunden sind und von allen Transformationen, die der Träger erfährt, mitgeführt werden, daher die Bezeichnung konvektiv. In der Kontinuumsmechanik ergeben sich konvektive Koordinaten auf natürliche Weise, wenn die Koordinatenlinien materielle Linien sind, die dann von allen Bewegungen und Deformationen des materiellen Körpers mittransponiert werden. Bildlich kann man sich ein Koordinatennetz auf eine Gummihaut aufgemalt denken, die dann gedehnt wird und das Koordinatennetz mitnimmt, siehe Abbildung rechts. Praktische Bedeutung haben konvektive Koordinatensysteme in der Kinematik schlanker Strukturen (Stäbe, Balken) und dünnwandiger Strukturen (Schalen und Membranen), wo die Spannungen und Dehnungen parallel zu den Vorzugsrichtungen der Struktur interessieren. Außerdem können materielle Vorzugsrichtungen nicht isotroper Materialien, wie z. B. von Holz, in konvektiven Koordinaten beschrieben werden. In der Kinematik deformierbarer Körper bekommen die in der Kontinuumsmechanik benutzten Tensoren in konvektiven Koordinaten ausgedrückt besonders einfache Darstellungen. Die Methode der konvektiven Koordinaten ist ein Spezialfall adaptiver Finite-Elemente-Methoden und wird wie diese in der numerischen Lösung von Advektions-Diffusions-Problemen verwendet (z. B. Schadstoffausbreitung in der Atmosphäre oder im Grundwasser). Betrachtet wird ein deformierbarer Körper wie im Bild, der mittels Konfigurationen in einen euklidischen Vektorraum formula_2 abgebildet wird. Die konvektiven Koordinaten eines materiellen Punktes formula_3 werden durch die Referenzkonfiguration formula_4 zugewiesen. Für jedes Partikel formula_3 eines Körpers formula_6 sind seine konvektiven Koordinaten gegeben durch: Diese Zuordnung ist vom gewählten Bezugssystem des Beobachters, von der Zeit und vom physikalischen Raum unserer Anschauung unabhängig. Für den viereckigen Körper im Bild eignet sich z. B. das Einheitsquadrat formula_8 als Bildbereich. formula_9 ist ein-eindeutig (bijektiv), so dass formula_10 auch der Benennung des Partikels formula_3 dienen kann. Weil die Koordinaten formula_10 an das Partikel gebunden sind, werden sie von jeder Bewegung des Partikels mitgenommen. Die Bewegungsfunktion formula_13 beschreibt die Bewegung des Partikels formula_10 durch den Raum unserer Anschauung und liefert uns ein Objekt unserer Anschauung, weil diese Positionen vom Körper einmal eingenommen wurden. Die Bewegung startet zu einem bestimmten Zeitpunkt formula_15, in dem sich der Körper in der Ausgangskonfiguration befindet. Die Funktion ordnet den Koordinaten formula_10 ein-eindeutig (bijektiv) einen Punkt formula_18 im Raum zu, den das Partikel zum Zeitpunkt formula_15 eingenommen hat. Der Vektor formula_18 hat materielle Koordinaten formula_21 bezüglich der Standardbasis formula_22. Wegen der Bijektivität kann geschrieben werden. Variiert im Vektor formula_10 nur eine Koordinate formula_25, dann fährt formula_26 eine materielle Koordinatenlinie ab, die im allgemeinen Fall eine Kurve im Raum ist, siehe obere Abbildung rechts. Die Tangentenvektoren an diese Kurven werden "kovariante" Basisvektoren des krummlinigen Koordinatensystems genannt. Die Richtung, in der sich die Koordinate formula_25 am stärksten ändert, sind die Gradienten die die Basisvektoren formula_30 in einem materiellen Punkt darstellen. Wegen sind die ko- und kontravarianten Basisvektoren dual zueinander und die kontravarianten Basisvektoren können aus berechnet werden. Darin wurde das dyadische Produkt "formula_33" benutzt. In der Jacobi-Matrix formula_34 sind die kovarianten Basisvektoren formula_35 spaltenweise eingetragen und die kontravarianten Basisvektoren formula_30 finden sich in den Zeilen der Inversen formula_37. Die ko- und kontravarianten Basisvektoren werden nur lokal (in den Tangentialräumen) im Punkt formula_18 als Basissystem für Vektor- und Tensorfelder, nicht aber für Ortsvektoren, benutzt: Die kovarianten Basisvektoren formula_35 bilden eine Basis des Tangentialraumes formula_40 und die kontravarianten Basisvektoren formula_30 bilden eine Basis des Kotangentialraumes formula_42 im Punkt formula_18, siehe untere Abbildung rechts. Im Zuge der Bewegung entsteht in jedem Punkt und zu jedem Zeitpunkt formula_44 einen Satz kovarianter Basisvektoren formula_45 und kontravarianter Basisvektoren formula_46, die die Tangenten bzw. Gradienten der materiellen Koordinatenlinien im deformierten Körper zur Zeit formula_47 sind. Sie sind mithin Basen der Tangentialräume formula_48 bzw. formula_49. Die Differentialoperatoren Gradient (grad), Divergenz (div) und Rotation (rot) aus der Vektoranalysis können mit dem Nabla-Operator formula_50 definiert werden. In konvektiven Koordinaten hat der Nabla-Operator in der Lagrange’schen Fassung die Form: Die Gradienten von Skalar- und Vektorfeldern werden mit ihm wie folgt dargestellt: Die Divergenzen werden aus dem Skalarprodukt mit formula_52 erhalten: Die Rotation eines Vektorfeldes entsteht mit dem Kreuzprodukt: Entsprechende Operatoren formula_54, formula_55 und formula_56 für Felder in der Euler’schen Fassung liefert der Nabla-Operator Der Einheitstensor formula_58 bildet jeden Vektor auf sich selbst ab. Bezüglich der ko- und kontravarianten Basisvektoren lauten seine Darstellungen: Die Skalarprodukte der kovarianten Basisvektoren heißen "kovariante Metrikkoeffizienten" (des Tangentialraumes formula_40). Entsprechend sind die Skalarprodukte der kontravarianten Basisvektoren "kontravariante Metrikkoeffizienten" (des Kotangentialraumes formula_42). In der Euler’schen Betrachtungsweise ist entsprechend mit den ko- und kontravarianten Metrikkoeffizienten formula_65 bzw. formula_66 (des Tangentialraumes formula_48 bzw. Kotangentialraumes formula_49). In konvektiven Koordinaten ausgedrückt bekommt der Deformationsgradient formula_69 eine besonders einfache Form. Der Deformationsgradient bildet gemäß seiner Definition die Tangentenvektoren an materielle Linien in der Ausgangskonfiguration auf die in der Momentankonfiguration ab und diese Tangentenvektoren sind gerade die kovarianten Basisvektoren formula_35 bzw. formula_45. Also ist Das ergibt sich auch aus der Ableitung der Bewegungsfunktion formula_73 : In dieser Darstellung lässt sich auch sofort mit die Inverse des Deformationsgradienten angeben. Der transponiert inverse Deformationensgradient bildet die kontravarianten Basisvektoren aufeinander ab: Die materielle Zeitableitung des Deformationsgradienten ist der "materielle Geschwindigkeitsgradient" denn die Ausgangskonfiguration hängt nicht von der Zeit ab und das gilt dann auch für die Basisvektoren formula_35 und formula_30. Der "räumliche Geschwindigkeitsgradient" formula_80 bekommt in konvektiven Koordinaten die einfache Form worin formula_82 die Geschwindigkeit eines Partikels am Ort formula_83 zur Zeit formula_47 ist. Der räumliche Geschwindigkeitsgradient transformiert die Basisvektoren in ihre Raten: Die folgenden Tensoren treten in der Kontinuumsmechanik auf. Ihre Darstellung in konvektiven Koordinaten ist in der Tabelle zusammengestellt. Weil der rechte Cauchy-Green Tensor formula_86, der Green-Lagrange-Verzerrungstensor formula_87 und der Euler-Almansi-Tensor formula_88 in ihrer (hier angegebenen) natürlichen Form mit den kovarianten Komponenten formula_89 bzw. formula_90 gebildet werden, werden diese Tensoren üblicher Weise als "kovariante Tensoren" bezeichnet. Die Spannungstensoren formula_91 und formula_92 sind entsprechend "kontravariante Tensoren". Objektive Größen sind solche, die von bewegten Beobachtern in gleicher Weise wahrgenommen werden. Die Zeitableitung von Tensoren ist im allgemeinen nicht objektiv. Die konvektiven ko- bzw. kontravarianten Oldroyd-Ableitungen objektiver Tensoren sind jedoch objektiv. Sie sind definiert über Kovariante Oldroyd-Ableitung, z. B. von formula_93: Kontravariante Oldroyd-Ableitung, z. B. von formula_95: Daraus leiten sich auch die Bezeichnungen "konvektiv kovariant" bzw. "konvektiv kontravariant" der Oldroyd-Ableitungen ab. Bemerkenswert sind die übereinstimmenden Transformationseigenschaften der kovarianten Tensoren sowie der kontravarianten Tensoren Siehe auch den Abschnitt Objektive Zeitableitungen im Artikel zum Geschwindigkeitsgradient. Ein Parallelogramm mit Grundseite und Höhe formula_101 und Neigungswinkel formula_102 wird zu einem flächengleichen Quadrat verformt, siehe Bild. Als Referenzkonfiguration eignet sich das Einheitsquadrat In der Ausgangskonfiguration haben die Punkte des Parallelogramms die Koordinaten: Die kovarianten Basisvektoren sind Sie stehen spaltenweise in der Jacobimatrix formula_34 und die kontravarianten Basisvektoren entspringen den Zeilen der Inversen der Jacobimatrix: In der Momentankonfiguration ist formula_109: und die konvektiven ko- und kontravarianten Basisvektoren bilden die Standardbasis Der Deformationsgradient ist ortsunabhängig und hat die Determinante eins, was die Erhaltung des Flächeninhalts differentialgeometrisch nachweist. Die kovarianten Metrikkoeffizienten lauten Damit lautet der Green-Lagrange-Verzerrungstensor: Kontinuumsmechanik: Mathematik:
<template> <PostSkeleton v-if="loading"/> <div v-if="item" v-resize="onResize"> <v-card v-if="!loading" class="elevation-1 pa-2"> <v-btn v-if="item.image" icon="mdi-keyboard-backspace" color="orange-darken-4" @click="$router.push('/')" class="back-button" > </v-btn> <v-img v-show="item.image" :src="item.image" lazy-src="/logo/shadai-main.jpeg" height="300" cover class="custom-image" ></v-img> <div class="elevation-0 mt-1"> <div> <div class="text-h3 ma-2"> {{ item.name }} </div> </div> <div class="d-flex align-center"> <v-rating :model-value="item.rating.review" readonly color="amber" ></v-rating> <p class="text-grey" :class="fontInfoText"> {{ item.rating.review }} {{ translate("home.stars") }} | ({{ commentsLenght }} {{ translate("home.comments") }}) | {{ formatDate(item.created_at) }} </p> </div> <v-divider></v-divider> <div class="my-2 mx-0 px-0"> <quill-editor v-model:content="item.description" contentType="html" :readOnly="true" theme="bubble" ></quill-editor> </div> <v-divider></v-divider> <Actions :model_reactions="item.reactions"/> <v-divider></v-divider> <Comments :model_id="item.id" /> <v-divider></v-divider> <Create :model_id="item.id"/> </div> </v-card> </div> </template> <script> import ResponsivePost from '../components/Common/Responsives/post.vue'; import PostService from '@/services/PostService.js' import Table from '../components/Common/Table.vue'; import Comments from '../components/Comment/Comments.vue'; import Actions from '../components/Post/Actions.vue'; import Create from '../components/Comment/Create.vue'; import { initials, formatDate } from '../utils/helpers'; import PostSkeleton from '../components/Common/Skeletons/PostSkeleton.vue'; export default { extends: ResponsivePost, mixins: [initials, formatDate, Table], components: { Comments, Create, Actions, PostSkeleton }, data() { return { loading: false, apiService: PostService, postId: null, item: null, preventSnackbar: true, comments: [], commentsLenght: 0 } }, methods: { getCommentLength() { setTimeout(() => { this.commentsLenght = this.item.comments.length }, 500); }, addCommentLenght () { this.commentsLenght++ }, reduceCommentLenght() { setTimeout(() => { this.commentsLenght = this.commentsLenght - 1 }, 1000) }, updatePost(resp) { this.item.rating = resp.rating if (this.item.reactions.length <= 0) { this.item.reactions[0] = resp return } let reactionsUpdated = this.item.reactions.map(function (reaction) { if (reaction.id === resp.id) { return resp } return reaction }) this.item.reactions = reactionsUpdated } }, computed: { progress () { return Math.min(100, this.comment.length * 10) }, }, mounted() { this.itemId = this.$route.params.id if (!this.itemId) return this.$router.push('/') this.getItem() this.getCommentLength() this.listenEvent("add-new-comment-length", this.addCommentLenght) this.listenEvent("remove-comment-lenght", this.reduceCommentLenght) this.listenEvent("update-reaction-rating", this.updatePost) }, beforeDestroy() { this.unlistenEvent("add-new-comment-length", this.addCommentLenght) this.unlistenEvent("remove-comment-lenght", this.reduceCommentLenght) this.unlistenEvent("update-reaction-rating", this.updatePost) }, } </script> <style> .back-button { position: absolute; z-index: 1; } .custom-image { z-index: 0; } .post-custom-title { z-index: 1; opacity: 0.8; } </style>
import {sessionActions} from "components/entities/session"; import orderFixture from '../fixtures/post-order.json' const test = it describe('Test burger-constructor', () => { beforeEach(() => { cy.clearCookies() cy.clearLocalStorage() cy.intercept("GET", 'https://norma.nomoreparties.space/api/ingredients', {fixture: 'products'}).as("getIngredients") cy.intercept("POST", 'https://norma.nomoreparties.space/api/orders', {fixture: 'post-order'}).as("postOrder") cy.initApp() cy.wait('@getIngredients') //User is required authed cy.AppDispatch(sessionActions.login({ accessToken: "Mock accessToken", refreshToken: "Mock refreshToken", user: {email: "mock@mock.mock", name: "Mock"}} )) }) test('series of steps to do the order', ()=>{ /* 1. перетаскивание ингредиента в конструктор 2. открытие модального окна с данными о заказе при клике по кнопке «Оформить заказ» 3. закрытие модальных окон при клике на кнопку закрытия. */ //#1 const dropPlace = cy.get('[data-testid=drop_card-product_from_burger-ingredients]').first() const ingredients = orderFixture.order.ingredients ingredients.forEach((ingredient)=>{ cy.get('[data-testid=card-product]').filter(`:contains("${ingredient.name}")`).trigger('dragstart') dropPlace.trigger('drop') }) ingredients.forEach((ingredient)=>{ dropPlace.filter(`:contains("${ingredient.name}")`) .should('exist') }) //#2 cy.get('[data-testid=button-post-order]').click() cy.wait('@postOrder') cy.get('[data-testid=order-details_number-order]').should("have.text", orderFixture.order.number) //#3 cy.get('[data-testid=modal_close]').first().click() cy.get('[data-testid=modal_showed]').should('not.exist') }) }) export {}
import React from "react"; import {Redirect} from "react-router"; import {connect} from "react-redux"; let mapStateToProps = (state) => { return { isAuth: state.auth.isAuth } }; const withAuthRedirect = ( Component ) => { class RedirectComponent extends React.Component { render() { if (!this.props.isAuth) return <Redirect to={"/login"}/>; return <Component {...this.props}/>; } } let ConnectedAuthRedirect = connect(mapStateToProps)(RedirectComponent); return ConnectedAuthRedirect }; export default withAuthRedirect;
import 'dart:math'; import 'package:someonetoview/models/available_times.dart'; import 'package:someonetoview/models/furniture_listing.dart'; import 'package:someonetoview/models/location.dart'; import 'package:someonetoview/models/property_listing.dart'; import 'package:someonetoview/models/vehicle_listing.dart'; import 'package:uuid/uuid.dart'; class Generator { static List<PropertyListing> generatePropertyListings() { // Sample data for location Location location = Location( longitude: -118.264854, latitude: 34.077164, streetAddress: '123 Main St', city: 'Los Angeles', stateCode: 'CA', stateName: 'California', zipCode: 90057, ); // Sample data for image URLs List<String> imageUrls = [ 'https://picsum.photos/id/10/300/300', 'https://picsum.photos/id/11/300/300', 'https://picsum.photos/id/12/300/300', 'https://picsum.photos/id/13/300/300', 'https://picsum.photos/id/14/300/300', ]; // Generate random sample data for VehicleListing List<PropertyListing> listings = []; String description = 'Lorem ipsum dolor sit amet, consectetur adipiscing elit.'; String finalDesc = ''; TimeSlot timeSlot1 = TimeSlot(start: '8:00 AM', end: '12:00 PM'); TimeSlot timeSlot2 = TimeSlot(start: '3:00 PM', end: '5:00 PM'); for (int i = 0; i < 4; i++) { finalDesc += ' $description'; } for (int i = 0; i < 12; i++) { int imageIndex = Random().nextInt(15); PropertyListing listing = PropertyListing( id: const Uuid().v4(), username: 'Fake User', userEmail: 'fakeUser@gmail.com', dateCreated: DateTime.now().subtract(const Duration(days: 4)), lastUpdated: DateTime.now().subtract(const Duration(hours: 36)), mainImageUrl: 'https://picsum.photos/id/$imageIndex/300', title: 'Property Listing Here ${i + 1}', price: Random().nextInt(4000) + 500, location: location, description: finalDesc, bedroomCount: Random().nextInt(2) + 1, bathroomCount: Random().nextInt(1) + 1, imageUrls: ['https://picsum.photos/id/$imageIndex/300', ...imageUrls], availableTimes: AvailableTimes( sunday: [timeSlot1, timeSlot2], monday: 'none', tuesday: [timeSlot1], wednesday: [timeSlot2], thursday: 'none', friday: [timeSlot1, timeSlot2], saturday: 'none', ), ); listings.add(listing); } return listings; } static List<FurnitureListing> generateFurnitureListings() { // Sample data for location Location location = Location( longitude: -118.264854, latitude: 34.077164, streetAddress: '123 Main St', city: 'Los Angeles', stateCode: 'CA', stateName: 'California', zipCode: 90057, ); // Sample data for image URLs List<String> imageUrls = [ 'https://picsum.photos/id/10/300/300', 'https://picsum.photos/id/11/300/300', 'https://picsum.photos/id/12/300/300', 'https://picsum.photos/id/13/300/300', 'https://picsum.photos/id/14/300/300', ]; // Generate random sample data for VehicleListing List<FurnitureListing> listings = []; String description = 'Lorem ipsum dolor sit amet, consectetur adipiscing elit.'; String finalDesc = 'Lorem ipsum dolor sit amet, consectetur adipiscing elit.'; for (int i = 0; i < 3; i++) { finalDesc += ' $description'; } // Sample data for TimeSlots TimeSlot timeSlot1 = TimeSlot(start: '9:00 AM', end: '12:00 PM'); TimeSlot timeSlot2 = TimeSlot(start: '1:00 PM', end: '5:00 PM'); for (int i = 0; i < 12; i++) { int imageIndex = Random().nextInt(15); FurnitureListing listing = FurnitureListing( id: const Uuid().v4(), username: 'Fake User', userEmail: 'fakeUser@gamil.com', dateCreated: DateTime.now().subtract(const Duration(days: 4)), lastUpdated: DateTime.now().subtract(const Duration(hours: 36)), mainImageUrl: 'https://picsum.photos/id/$imageIndex/300', title: 'Furniture Listing ${i + 1}', price: Random().nextInt(500) + 10, location: location, description: finalDesc, condition: 'Used', imageUrls: ['https://picsum.photos/id/$imageIndex/300', ...imageUrls], availableTimes: AvailableTimes( sunday: [timeSlot1, timeSlot2], monday: 'none', tuesday: [timeSlot1], wednesday: [timeSlot2], thursday: 'none', friday: [timeSlot1, timeSlot2], saturday: 'none', ), ); listings.add(listing); } return listings; } static List<VehicleListing> generateVehicleListings() { // Sample data for location Location location = Location( longitude: -118.264854, latitude: 34.077164, streetAddress: '123 Main St', city: 'Los Angeles', stateCode: 'CA', stateName: 'California', zipCode: 90057, ); // Sample data for image URLs List<String> imageUrls = [ 'https://picsum.photos/id/10/300/300', 'https://picsum.photos/id/11/300/300', 'https://picsum.photos/id/12/300/300', 'https://picsum.photos/id/13/300/300', 'https://picsum.photos/id/14/300/300', ]; // Generate random sample data for VehicleListing List<VehicleListing> listings = []; String description = 'Lorem ipsum dolor sit amet, consectetur adipiscing elit.'; String finalDesc = ''; for (int i = 0; i < 4; i++) { finalDesc += ' $description'; } TimeSlot timeSlot1 = TimeSlot(start: '6:00 AM', end: '11:00 AM'); TimeSlot timeSlot2 = TimeSlot(start: '1:00 PM', end: '5:30 PM'); for (int i = 0; i < 12; i++) { int imageIndex = Random().nextInt(15); VehicleListing listing = VehicleListing( id: const Uuid().v4(), username: 'Fake User', userEmail: 'fakeUser@gamil.com', dateCreated: DateTime.now().subtract(const Duration(days: 4)), lastUpdated: DateTime.now().subtract(const Duration(hours: 36)), mainImageUrl: 'https://picsum.photos/id/$imageIndex/300', title: 'Vehicle Listing ${i + 1}', price: Random().nextInt(30000) + 1000, location: location, description: finalDesc, mileage: Random().nextInt(200000) + 100000, imageUrls: ['https://picsum.photos/id/$imageIndex/300', ...imageUrls], availableTimes: AvailableTimes( sunday: [timeSlot1, timeSlot2], monday: 'none', tuesday: [timeSlot1], wednesday: [timeSlot2], thursday: 'none', friday: [timeSlot1, timeSlot2], saturday: 'none', ), ); listings.add(listing); } return listings; } }
package controllers import ( "errors" "regexp" "testing" "github.com/DATA-DOG/go-sqlmock" constants "github.com/Prashansa-K/serviceCatalog/internal" api "github.com/Prashansa-K/serviceCatalog/internal/api/structs" "github.com/stretchr/testify/assert" "gorm.io/driver/postgres" "gorm.io/gorm" "gorm.io/gorm/logger" ) var gormMockDB *gorm.DB var mock sqlmock.Sqlmock func initMockDB() error { db, sqlmocker, err := sqlmock.New() if err != nil { return err } mock = sqlmocker gormMockDB, err = gorm.Open(postgres.New(postgres.Config{ Conn: db, }), &gorm.Config{ Logger: logger.Default.LogMode(logger.Info), }) if err != nil { return err } return nil } func TestGetServiceByNameWithPaginatedVersions_Success(t *testing.T) { if (gormMockDB == nil) || (mock == nil) { // Setup the mock DB err := initMockDB() assert.NoError(t, err) } mock.ExpectQuery(regexp.QuoteMeta(`SELECT count(*) FROM "versions" JOIN services ON versions.service_id = services.id WHERE services.name = $1 AND "versions"."deleted_at" IS NULL`)). WithArgs("test-service"). WillReturnRows(sqlmock.NewRows([]string{"count"}). AddRow(2)) mock.ExpectQuery(regexp.QuoteMeta(`SELECT * FROM "services" WHERE name = $1 AND "services"."deleted_at" IS NULL ORDER BY "services"."id" LIMIT $2`)). WithArgs("test-service", 1). WillReturnRows(sqlmock.NewRows([]string{"id", "name", "description", "version_count"}). AddRow("123", "test-service", "Test service", constants.PAGE_SIZE)) mock.ExpectQuery(regexp.QuoteMeta(`SELECT * FROM "versions" WHERE "versions"."service_id" = $1 AND "versions"."deleted_at" IS NULL LIMIT $2`)). WithArgs(int64(123), constants.PAGE_SIZE). WillReturnRows(sqlmock.NewRows([]string{"id", "name", "service_id", "description"}). AddRow("1", "v1", "123", "Version 1"). AddRow("2", "v2", "123", "Version 2")) // Create the controller and call the method totalVersions, service, err := GetServiceByNameWithPaginatedVersions(gormMockDB, 1, "test-service") // Assert the results assert.NoError(t, err) assert.Equal(t, int64(2), totalVersions) assert.Equal(t, "test-service", service.Name) assert.Equal(t, "Test service", service.Description) assert.Len(t, service.Versions, 2) assert.Equal(t, "v1", service.Versions[0].Name) assert.Equal(t, "v2", service.Versions[1].Name) // Ensure all expectations were met assert.NoError(t, mock.ExpectationsWereMet()) } func TestGetPaginatedServicesByFilters_NoFilters_Success(t *testing.T) { if (gormMockDB == nil) || (mock == nil) { // Setup the mock DB err := initMockDB() assert.NoError(t, err) } // Expect the query to be executed mock.ExpectQuery(regexp.QuoteMeta(`SELECT count(*) FROM "services" WHERE "services"."deleted_at" IS NULL`)). WillReturnRows(sqlmock.NewRows([]string{"count"}). AddRow(2)) mock.ExpectQuery(regexp.QuoteMeta(`SELECT * FROM "services" WHERE "services"."deleted_at" IS NULL ORDER BY name ASC LIMIT $1`)). WillReturnRows(sqlmock.NewRows([]string{"id", "name", "description", "version_count"}). AddRow(123, "test-service-1", "Test check 1", 2). AddRow(456, "test-service-2", "Test check 2", 1)) // Create the controller and call the method totalServices, services, err := GetPaginatedServicesByFilters(gormMockDB, 1, constants.ASC, "", "") // Assert the results assert.NoError(t, err) assert.Equal(t, int64(2), totalServices) assert.Len(t, services, 2) assert.Equal(t, uint(123), services[0].ID) assert.Equal(t, "test-service-1", services[0].Name) assert.Equal(t, "Test check 1", services[0].Description) assert.Equal(t, uint(456), services[1].ID) assert.Equal(t, "test-service-2", services[1].Name) assert.Equal(t, "Test check 2", services[1].Description) // Ensure all expectations were met assert.NoError(t, mock.ExpectationsWereMet()) } func TestGetPaginatedServicesByFilters_NameFilters_Success(t *testing.T) { if (gormMockDB == nil) || (mock == nil) { // Setup the mock DB err := initMockDB() assert.NoError(t, err) } // Expect the query to be executed mock.ExpectQuery(regexp.QuoteMeta(`SELECT count(*) FROM "services" WHERE LOWER(name) LIKE $1 AND "services"."deleted_at" IS NULL`)). WithArgs(`%test%`). WillReturnRows(sqlmock.NewRows([]string{"count"}). AddRow(2)) mock.ExpectQuery(regexp.QuoteMeta(`SELECT * FROM "services" WHERE LOWER(name) LIKE $1 AND "services"."deleted_at" IS NULL ORDER BY name ASC LIMIT $2`)). WithArgs(`%test%`, constants.PAGE_SIZE). WillReturnRows(sqlmock.NewRows([]string{"id", "name", "description", "version_count"}). AddRow(123, "test-service-1", "Test check 1", 2). AddRow(456, "test-service-2", "Test check 2", 1)) // Create the controller and call the method totalServices, services, err := GetPaginatedServicesByFilters(gormMockDB, 1, constants.ASC, "test", "") // Assert the results assert.NoError(t, err) assert.Equal(t, int64(2), totalServices) assert.Len(t, services, 2) assert.Equal(t, uint(123), services[0].ID) assert.Equal(t, "test-service-1", services[0].Name) assert.Equal(t, "Test check 1", services[0].Description) assert.Equal(t, uint(456), services[1].ID) assert.Equal(t, "test-service-2", services[1].Name) assert.Equal(t, "Test check 2", services[1].Description) // Ensure all expectations were met assert.NoError(t, mock.ExpectationsWereMet()) } func TestGetPaginatedServicesByFilters_DescriptionFilters_Success(t *testing.T) { if (gormMockDB == nil) || (mock == nil) { // Setup the mock DB err := initMockDB() assert.NoError(t, err) } // Expect the query to be executed mock.ExpectQuery(regexp.QuoteMeta(`SELECT count(*) FROM "services" WHERE LOWER(description) LIKE $1 AND "services"."deleted_at" IS NULL`)). WithArgs(`%check%`). WillReturnRows(sqlmock.NewRows([]string{"count"}). AddRow(2)) mock.ExpectQuery(regexp.QuoteMeta(`SELECT * FROM "services" WHERE LOWER(description) LIKE $1 AND "services"."deleted_at" IS NULL ORDER BY name ASC LIMIT $2`)). WithArgs(`%check%`, constants.PAGE_SIZE). WillReturnRows(sqlmock.NewRows([]string{"id", "name", "description", "version_count"}). AddRow(123, "test-service-1", "Test check 1", 2). AddRow(456, "test-service-2", "Test check 2", 1)) // Create the controller and call the method totalServices, services, err := GetPaginatedServicesByFilters(gormMockDB, 1, constants.ASC, "", "check") // Assert the results assert.NoError(t, err) assert.Equal(t, int64(2), totalServices) assert.Len(t, services, 2) assert.Equal(t, uint(123), services[0].ID) assert.Equal(t, "test-service-1", services[0].Name) assert.Equal(t, "Test check 1", services[0].Description) assert.Equal(t, uint(456), services[1].ID) assert.Equal(t, "test-service-2", services[1].Name) assert.Equal(t, "Test check 2", services[1].Description) // Ensure all expectations were met assert.NoError(t, mock.ExpectationsWereMet()) } func TestGetPaginatedServicesByFilters_AllFilters_Success(t *testing.T) { if (gormMockDB == nil) || (mock == nil) { // Setup the mock DB err := initMockDB() assert.NoError(t, err) } // Expect the query to be executed mock.ExpectQuery(regexp.QuoteMeta(`SELECT count(*) FROM "services" WHERE LOWER(name) LIKE $1 AND LOWER(description) LIKE $2 AND "services"."deleted_at" IS NULL`)). WithArgs(`%test%`, `%check%`). WillReturnRows(sqlmock.NewRows([]string{"count"}). AddRow(2)) mock.ExpectQuery(regexp.QuoteMeta(`SELECT * FROM "services" WHERE LOWER(name) LIKE $1 AND LOWER(description) LIKE $2 AND "services"."deleted_at" IS NULL ORDER BY name ASC LIMIT $3`)). WithArgs(`%test%`, `%check%`, constants.PAGE_SIZE). WillReturnRows(sqlmock.NewRows([]string{"id", "name", "description", "version_count"}). AddRow(123, "test-service-1", "Test check 1", 2). AddRow(456, "test-service-2", "Test check 2", 1)) // Create the controller and call the method totalServices, services, err := GetPaginatedServicesByFilters(gormMockDB, 1, constants.ASC, "test", "check") // Assert the results assert.NoError(t, err) assert.Equal(t, int64(2), totalServices) assert.Len(t, services, 2) assert.Equal(t, uint(123), services[0].ID) assert.Equal(t, "test-service-1", services[0].Name) assert.Equal(t, "Test check 1", services[0].Description) assert.Equal(t, uint(456), services[1].ID) assert.Equal(t, "test-service-2", services[1].Name) assert.Equal(t, "Test check 2", services[1].Description) // Ensure all expectations were met assert.NoError(t, mock.ExpectationsWereMet()) } func TestCreateService_Success(t *testing.T) { if (gormMockDB == nil) || (mock == nil) { // Setup the mock DB err := initMockDB() assert.NoError(t, err) } // Expect the query to be executed mock.ExpectBegin() mock.ExpectQuery(regexp.QuoteMeta(`INSERT INTO "services" ("name","description","created_at","version_count") VALUES ($1,$2,$3,$4) RETURNING "deleted_at","id"`)). WithArgs("test-service", "Test service", sqlmock.AnyArg(), 0). WillReturnRows(sqlmock.NewRows([]string{"id"}). AddRow("123")) mock.ExpectCommit() serviceRequest := api.ServiceRequest{ Name: "test-service", Description: "Test service", } err := CreateService(gormMockDB, serviceRequest) // Assert the results assert.NoError(t, err) // Ensure all expectations were met assert.NoError(t, mock.ExpectationsWereMet()) } func TestCreateVersion_Success(t *testing.T) { if (gormMockDB == nil) || (mock == nil) { // Setup the mock DB err := initMockDB() assert.NoError(t, err) } mock.ExpectQuery(regexp.QuoteMeta(`SELECT * FROM "services" WHERE name = $1 AND "services"."deleted_at" IS NULL ORDER BY "services"."id" LIMIT $2`)). WithArgs("test-service", 1). WillReturnRows(sqlmock.NewRows([]string{"id", "name", "description", "version_count"}). AddRow("123", "test-service", "Test service", 1)) // Expect the query to be executed mock.ExpectBegin() mock.ExpectQuery(regexp.QuoteMeta(`INSERT INTO "versions" ("service_id","name","created_at","description") VALUES ($1,$2,$3,$4) RETURNING "deleted_at","description","id"`)). WithArgs(123, "v1", sqlmock.AnyArg(), "Version 1"). WillReturnRows(sqlmock.NewRows([]string{"id"}). AddRow(1)) mock.ExpectCommit() mock.ExpectBegin() mock.ExpectExec(regexp.QuoteMeta(`UPDATE "services" SET "name"=$1,"description"=$2,"created_at"=$3,"deleted_at"=$4,"version_count"=$5 WHERE "services"."deleted_at" IS NULL AND "id" = $6`)). WithArgs("test-service", "Test service", sqlmock.AnyArg(), nil, 2, 123). WillReturnResult(sqlmock.NewResult(0, 1)) mock.ExpectCommit() versionRequest := api.ServiceVersionRequest{ Name: "v1", ServiceName: "test-service", Description: "Version 1", } err := CreateVersion(gormMockDB, versionRequest) // Assert the results assert.NoError(t, err) // Ensure all expectations were met assert.NoError(t, mock.ExpectationsWereMet()) } func TestCreateVersion_ServiceNotFound(t *testing.T) { if (gormMockDB == nil) || (mock == nil) { // Setup the mock DB err := initMockDB() assert.NoError(t, err) } mock.ExpectQuery(regexp.QuoteMeta(`SELECT * FROM "services" WHERE name = $1 AND "services"."deleted_at" IS NULL ORDER BY "services"."id" LIMIT $2`)). WithArgs("test-non-existing-service", 1). WillReturnError(gorm.ErrRecordNotFound) versionRequest := api.ServiceVersionRequest{ Name: "v1", ServiceName: "test-non-existing-service", Description: "Version 1", } err := CreateVersion(gormMockDB, versionRequest) // Assert the results assert.Error(t, err) assert.Equal(t, "service not found", err.Error()) // Ensure all expectations were met assert.NoError(t, mock.ExpectationsWereMet()) } func TestCreateVersion_DuplicateVersions(t *testing.T) { if (gormMockDB == nil) || (mock == nil) { // Setup the mock DB err := initMockDB() assert.NoError(t, err) } mock.ExpectQuery(regexp.QuoteMeta(`SELECT * FROM "services" WHERE name = $1 AND "services"."deleted_at" IS NULL ORDER BY "services"."id" LIMIT $2`)). WithArgs("test-service", 1). WillReturnRows(sqlmock.NewRows([]string{"id", "name", "description", "version_count"}). AddRow("123", "test-service", "Test service", 1)) mock.ExpectBegin() mock.ExpectQuery(regexp.QuoteMeta(`INSERT INTO "versions" ("service_id","name","created_at","description") VALUES ($1,$2,$3,$4) RETURNING "deleted_at","description","id"`)). WithArgs(123, "v1", sqlmock.AnyArg(), "Version 1"). WillReturnError(errors.New("duplicate key value violates unique constraint \"versions_service_id_name_key\"")) versionRequest := api.ServiceVersionRequest{ Name: "v1", ServiceName: "test-service", Description: "Version 1", } err := CreateVersion(gormMockDB, versionRequest) // Assert the results assert.Error(t, err) assert.Equal(t, "version with the same name already exists for this service", err.Error()) // Ensure all expectations were met assert.NoError(t, mock.ExpectationsWereMet()) } func TestCreateVersion_ErrorInVersionCreation(t *testing.T) { if (gormMockDB == nil) || (mock == nil) { // Setup the mock DB err := initMockDB() assert.NoError(t, err) } mock.ExpectQuery(regexp.QuoteMeta(`SELECT * FROM "services" WHERE name = $1 AND "services"."deleted_at" IS NULL ORDER BY "services"."id" LIMIT $2`)). WithArgs("test-service", 1). WillReturnRows(sqlmock.NewRows([]string{"id", "name", "description", "version_count"}). AddRow("123", "test-service", "Test service", 1)) mock.ExpectBegin() mock.ExpectQuery(regexp.QuoteMeta(`INSERT INTO "versions" ("service_id","name","created_at","description") VALUES ($1,$2,$3,$4) RETURNING "deleted_at","description","id"`)). WithArgs(123, "v1", sqlmock.AnyArg(), "Version 1"). WillReturnError(errors.New("some other error")) versionRequest := api.ServiceVersionRequest{ Name: "v1", ServiceName: "test-service", Description: "Version 1", } err := CreateVersion(gormMockDB, versionRequest) // Assert the results assert.Error(t, err) assert.Regexp(t, "some other error", err.Error()) // Ensure all expectations were met assert.NoError(t, mock.ExpectationsWereMet()) } func TestDeleteService_Success(t *testing.T) { if (gormMockDB == nil) || (mock == nil) { // Setup the mock DB err := initMockDB() assert.NoError(t, err) } mock.ExpectQuery(regexp.QuoteMeta(`SELECT * FROM "services" WHERE name = $1 AND "services"."deleted_at" IS NULL ORDER BY "services"."id" LIMIT $2`)). WithArgs("test-service", 1). WillReturnRows(sqlmock.NewRows([]string{"id", "name", "description", "version_count"}). AddRow("123", "test-service", "Test service", 1)) // Expect the query to be executed mock.ExpectBegin() mock.ExpectExec(regexp.QuoteMeta(`UPDATE "versions" SET "deleted_at"=$1 WHERE service_id = $2 AND "versions"."deleted_at" IS NULL`)). WithArgs(sqlmock.AnyArg(), 123). WillReturnResult(sqlmock.NewResult(0, 1)) mock.ExpectCommit() mock.ExpectBegin() mock.ExpectExec(regexp.QuoteMeta(`UPDATE "services" SET "deleted_at"=$1 WHERE "services"."id" = $2 AND "services"."deleted_at" IS NULL`)). WithArgs(sqlmock.AnyArg(), 123). WillReturnResult(sqlmock.NewResult(0, 1)) mock.ExpectCommit() // Create the controller and call the method err := DeleteService(gormMockDB, "test-service") // Assert the results assert.NoError(t, err) // Ensure all expectations were met assert.NoError(t, mock.ExpectationsWereMet()) } func TestDeleteVersionInDB_Success(t *testing.T) { if (gormMockDB == nil) || (mock == nil) { // Setup the mock DB err := initMockDB() assert.NoError(t, err) } mock.ExpectQuery(regexp.QuoteMeta(`SELECT * FROM "services" WHERE name = $1 AND "services"."deleted_at" IS NULL ORDER BY "services"."id" LIMIT $2`)). WithArgs("test-service", 1). WillReturnRows(sqlmock.NewRows([]string{"id", "name", "description", "version_count"}). AddRow("123", "test-service", "Test service", 1)) mock.ExpectQuery(regexp.QuoteMeta(`SELECT * FROM "versions" WHERE (service_id = $1 AND name = $2) AND "versions"."deleted_at" IS NULL ORDER BY "versions"."id" LIMIT $3`)). WithArgs(123, "v1", 1). WillReturnRows(sqlmock.NewRows([]string{"id", "name", "description", "version_count"}). AddRow("123", "test-service", "Test service", 1)) // Expect the query to be executed mock.ExpectBegin() mock.ExpectExec(regexp.QuoteMeta(`UPDATE "versions" SET "deleted_at"=$1 WHERE "versions"."id" = $2 AND "versions"."deleted_at" IS NULL`)). WithArgs(sqlmock.AnyArg(), 123). WillReturnResult(sqlmock.NewResult(0, 1)) mock.ExpectCommit() mock.ExpectBegin() mock.ExpectExec(regexp.QuoteMeta(`UPDATE "services" SET "name"=$1,"description"=$2,"created_at"=$3,"deleted_at"=$4,"version_count"=$5 WHERE "services"."deleted_at" IS NULL AND "id" = $6`)). WithArgs("test-service", "Test service", sqlmock.AnyArg(), nil, 0, 123). WillReturnResult(sqlmock.NewResult(0, 1)) mock.ExpectCommit() // Create the controller and call the method err := DeleteVersion(gormMockDB, "test-service", "v1") // Assert the results assert.NoError(t, err) // Ensure all expectations were met assert.NoError(t, mock.ExpectationsWereMet()) } func TestUpdateService_Success(t *testing.T) { if (gormMockDB == nil) || (mock == nil) { // Setup the mock DB err := initMockDB() assert.NoError(t, err) } mock.ExpectQuery(regexp.QuoteMeta(`SELECT * FROM "services" WHERE id = $1 AND "services"."deleted_at" IS NULL ORDER BY "services"."id" LIMIT $2`)). WithArgs(123, 1). WillReturnRows(sqlmock.NewRows([]string{"id", "name", "description", "version_count"}). AddRow("123", "test-service", "Test service", 1)) // Expect the query to be executed mock.ExpectBegin() mock.ExpectExec(regexp.QuoteMeta(`UPDATE "services" SET "id"=$1,"name"=$2,"description"=$3,"created_at"=$4,"deleted_at"=$5,"version_count"=$6 WHERE "services"."deleted_at" IS NULL AND "id" = $7`)). WithArgs(123, "test-service-2", "Test service 2", sqlmock.AnyArg(), nil, 1, 123). WillReturnResult(sqlmock.NewResult(0, 1)) mock.ExpectCommit() serviceRequest := api.ServiceRequest{ ID: 123, Name: "test-service-2", Description: "Test service 2", } err := UpdateService(gormMockDB, serviceRequest) // Assert the results assert.NoError(t, err) // Ensure all expectations were met assert.NoError(t, mock.ExpectationsWereMet()) }
import CheckIcon from "@mui/icons-material/Check"; import CloseIcon from "@mui/icons-material/Close"; import { Box, Grid, Typography } from "@mui/material"; import Button from "@mui/material/Button"; import Dialog from "@mui/material/Dialog"; import DialogContent from "@mui/material/DialogContent"; import DialogTitle from "@mui/material/DialogTitle"; import TextField from "@mui/material/TextField"; import * as React from "react"; import { useState } from "react"; import employeeService from "../services/employeeService"; export default function AddEmployee(props) { const [formData, setFormData] = useState({ id: "", name: "", age: "", position: "", email: "", phone: "", address: "", department: "", salary: "", skills: "", }); const handleChange = (e) => { const { name, value } = e.target; setFormData({ ...formData, [name]: e.target.value }); }; const handleSubmit = async (event) => { event.preventDefault(); try { const res = await employeeService.addEmployee(formData); if(!res.isError) { alert("Information Successfully Inserted") props.handleClose() } else { alert("Please try again") } } catch (e) { alert(e.message) } setFormData({ id: "", name: "", age: "", position: "", email: "", phone: "", address: "", department: "", salary: "", skills: "", }); }; return ( <React.Fragment> <Dialog open={props.open} onClose={props.handleClose}> <DialogTitle> <Typography gutterBottom variant="h5" component="div" sx={{ padding: "20px", fontWeight: "bold", color: "darkcyan", fontFamily: "revert-layer", }} > Add Employee Information </Typography> </DialogTitle> <DialogContent> <Box component="form" Validate //onSubmit={handleSubmit} sx={{ mt: 3 }} > <Grid container spacing={2}> <Grid item xs={12} sm={3}> <TextField autoComplete="id" name="id" required fullWidth id="id" label="ID" autoFocus onChange={handleChange} /> </Grid> <Grid item xs={12} sm={9}> <TextField required fullWidth id="name" label="Name" name="name" autoComplete="given-name" onChange={handleChange} /> </Grid> <Grid item xs={12}> <TextField required fullWidth id="age" label="Age" name="age" autoComplete="age" onChange={handleChange} /> </Grid> <Grid item xs={12}> <TextField required fullWidth name="position" label="Position" id="position" autoComplete="position" onChange={handleChange} /> </Grid> <Grid item xs={12}> <TextField required fullWidth name="email" label="Email" id="email" autoComplete="email" onChange={handleChange} /> </Grid> <Grid item xs={12}> <TextField required fullWidth name="phone" label="Phone" id="phone" autoComplete="phone" onChange={handleChange} /> </Grid> <Grid item xs={12}> <TextField required fullWidth name="address" label="Address" id="address" autoComplete="address" onChange={handleChange} /> </Grid> <Grid item xs={12}> <TextField required fullWidth name="department" label="Department" id="department" autoComplete="department" onChange={handleChange} /> </Grid> <Grid item xs={12}> <TextField required fullWidth name="salary" label="Salary" id="salary" autoComplete="salary" onChange={handleChange} /> </Grid> <Grid item xs={12}> <TextField required fullWidth name="skills" label="Skills" id="skills" autoComplete="skills" onChange={handleChange} /> </Grid> </Grid> <Grid> <Button type="submit" variant="contained" onClick={handleSubmit} startIcon={<CheckIcon />} sx={{ mt: 3, mb: 2, mr: 2 }} > Submit </Button> <Button type="submit" variant="contained" color="error" startIcon={<CloseIcon />} onClick={props.handleClose} sx={{ mt: 3, mb: 2 }} > Cancel </Button> </Grid> </Box> </DialogContent> {/* <DialogActions> <Button onClick={props.handleClose}>Cancel</Button> <Button onClick={props.handleClose}>Subscribe</Button> </DialogActions> */} </Dialog> </React.Fragment> ); }
/* * Copyright (c) Meta Platforms, Inc. and affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ package com.facebook.react.uimanager import android.view.View import com.facebook.react.uimanager.annotations.ReactProp import com.facebook.react.uimanager.annotations.ReactPropGroup import com.facebook.testutils.shadows.ShadowSoLoader import com.facebook.testutils.shadows.ShadowYogaConfigProvider import com.facebook.testutils.shadows.ShadowYogaNodeFactory import org.junit.Test import org.junit.runner.RunWith import org.robolectric.RobolectricTestRunner import org.robolectric.annotation.Config /** * Test that verifies that spec of methods annotated with @ReactProp in {@link ReactShadowNode} is * correct */ @RunWith(RobolectricTestRunner::class) @Config( shadows = [ShadowYogaConfigProvider::class, ShadowSoLoader::class, ShadowYogaNodeFactory::class]) class ReactPropForShadowNodeSpecTest { @Test(expected = RuntimeException::class) fun testMethodWithWrongNumberOfParams() { BaseViewManager( object : ReactShadowNodeImpl() { @Suppress("UNUSED_PARAMETER") @ReactProp(name = "prop") fun setterWithIncorrectNumberOfArgs(value: Boolean, anotherValue: Int) = Unit } .javaClass) .nativeProps } @Test(expected = RuntimeException::class) fun testMethodWithTooFewParams() { BaseViewManager( object : ReactShadowNodeImpl() { @ReactProp(name = "prop") fun setterWithNoArgs() = Unit } .javaClass) .nativeProps } @Test(expected = RuntimeException::class) fun testUnsupportedValueType() { BaseViewManager( object : ReactShadowNodeImpl() { @Suppress("UNUSED_PARAMETER") @ReactProp(name = "prop") fun setterWithMap(value: Map<*, *>) = Unit } .javaClass) .nativeProps } @Test(expected = RuntimeException::class) fun testGroupInvalidNumberOfParams() { BaseViewManager( object : ReactShadowNodeImpl() { @Suppress("UNUSED_PARAMETER") @ReactPropGroup(names = ["prop1", "prop2"]) fun setterWithTooManyParams(index: Int, value: Float, boolean: Boolean) = Unit } .javaClass) .nativeProps } @Test(expected = RuntimeException::class) fun testGroupTooFewParams() { BaseViewManager( object : ReactShadowNodeImpl() { @Suppress("UNUSED_PARAMETER") @ReactPropGroup(names = ["props1", "prop2"]) fun setterWithTooFewParams(index: Int) = Unit } .javaClass) .nativeProps } @Test(expected = RuntimeException::class) fun testGroupNoIndexParam() { BaseViewManager( object : ReactShadowNodeImpl() { @Suppress("UNUSED_PARAMETER") @ReactPropGroup(names = ["prop1", "prop2"]) fun setterWithNoIndexParam(value: Float, boolean: Boolean) = Unit } .javaClass) .nativeProps } companion object { private class BaseViewManager( private val shadowNodeClass: Class<out ReactShadowNode<ReactShadowNodeImpl>> ) : ViewManager<View, ReactShadowNode<*>>() { override fun getName(): String = "IgnoredName" override fun createShadowNodeInstance(): ReactShadowNode<*>? = null override fun getShadowNodeClass(): Class<out ReactShadowNode<ReactShadowNodeImpl>> = shadowNodeClass override fun createViewInstance(reactContext: ThemedReactContext): View = View(null) override fun updateExtraData(root: View, extraData: Any?) = Unit } } }
<?php session_start(); require_once 'db_connection.php'; $course_id = ""; $course_title = ""; $course_description = ""; $course_credits = ""; $instructor_ids = array(); $language_ids = array(); $errorMessage = ""; $successMessage = ""; // Check if the course ID is provided in the URL if (isset($_GET['id'])) { $editCourseID = $_GET['id']; // Fetch course details from the database $fetchCourseQuery = "SELECT * FROM Courses WHERE course_id = '$editCourseID'"; $fetchCourseResult = mysqli_query($conn, $fetchCourseQuery); if ($fetchCourseResult && mysqli_num_rows($fetchCourseResult) > 0) { $courseData = mysqli_fetch_assoc($fetchCourseResult); // Assign fetched data to variables $course_id = $courseData['course_id']; $course_title = $courseData['course_title']; $course_description = $courseData['course_description']; $course_credits = $courseData['course_credits']; // Fetch associated instructors $fetchCourseInstructorsQuery = "SELECT ci.instructor_id, ci.language_id, u.username, l.language_name FROM course_instructors ci INNER JOIN users u ON ci.instructor_id = u.user_id INNER JOIN languages l ON ci.language_id = l.language_id WHERE ci.course_id = '$editCourseID'"; $fetchCourseInstructorsResult = mysqli_query($conn, $fetchCourseInstructorsQuery); if ($fetchCourseInstructorsResult) { while ($row = mysqli_fetch_assoc($fetchCourseInstructorsResult)) { $instructor_ids[] = $row['instructor_id']; $language_ids[] = $row['language_id']; $instructor_names[] = $row['username']; $language_names[] = $row['language_name']; } } } else { $errorMessage = "Course not found with ID: $editCourseID"; } } else { $errorMessage = "Course ID not provided in the URL."; } // Handle form submission if ($_SERVER['REQUEST_METHOD'] === 'POST') { // Retrieve form data $course_id = $_POST['course_id']; $course_title = $_POST['course_title']; $course_description = $_POST['course_description']; $course_credits = $_POST['course_credits']; // Check if the instructor and language arrays are provided if (isset($_POST['instructor_id']) && isset($_POST['language_id'])) { $instructor_ids = $_POST['instructor_id']; $language_ids = $_POST['language_id']; // Check for required fields if ( empty($course_id) || empty($course_title) || empty($course_description) || empty($course_credits) || empty($instructor_ids) || empty($language_ids) ) { $errorMessage = "All the fields are required."; } else { // Check if there are valid instructors $validInstructorIDs = array(); foreach ($instructor_ids as $instructorID) { $checkInstructorQuery = "SELECT user_id FROM users WHERE user_id = $instructorID AND role = 'teacher'"; $checkInstructorResult = mysqli_query($conn, $checkInstructorQuery); if (mysqli_num_rows($checkInstructorResult) == 1) { $validInstructorIDs[] = $instructorID; } else { $errorMessage = "Invalid instructor provided or some instructors are not teachers."; break; // Exit the loop if any invalid instructor is found } } if (empty($validInstructorIDs)) { $errorMessage = "No valid instructors were provided or some instructors are not teachers."; } else { // Update Courses table $updateCourseQuery = "UPDATE Courses SET course_title = '$course_title', course_description = '$course_description', course_credits = '$course_credits' WHERE course_id = '$editCourseID'"; $updateCourseResult = mysqli_query($conn, $updateCourseQuery); // Update course_instructors table if ($updateCourseResult) { // Delete existing instructors for the course $deleteInstructorsQuery = "DELETE FROM course_instructors WHERE course_id = '$editCourseID'"; mysqli_query($conn, $deleteInstructorsQuery); // Check if the arrays are set before trying to use them $newInstructorIDs = isset($_POST['instructor_id']) ? $_POST['instructor_id'] : []; $newLanguageIDs = isset($_POST['language_id']) ? $_POST['language_id'] : []; // Insert new instructors if arrays are not empty if (!empty($newInstructorIDs) && !empty($newLanguageIDs)) { foreach ($newInstructorIDs as $key => $instructorID) { // Check if the instructor is already associated with the course $checkInstructorQuery = "SELECT * FROM course_instructors WHERE course_id = '$editCourseID' AND instructor_id = '$instructorID'"; $checkInstructorResult = mysqli_query($conn, $checkInstructorQuery); if (mysqli_num_rows($checkInstructorResult) == 0) { $languageID = $newLanguageIDs[$key]; $insertInstructorQuery = "INSERT INTO course_instructors (course_id, instructor_id, language_id) VALUES ('$editCourseID', '$instructorID', '$languageID')"; mysqli_query($conn, $insertInstructorQuery); } } } $successMessage = "Course details updated successfully."; } else { $errorMessage = "Error updating course details: " . mysqli_error($conn); } } } } } ?> <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Edit Course</title> <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/css/bootstrap.min.css"> </head> <body> <div class="container my-5"> <h2>Edit Course</h2> <?php if(!empty($errorMessage)){ echo" <div class='alert alert-warning alert-dismissible fade show' role='alert'> <strong>$errorMessage</strong> <button type='button' class'btn-close' data-bs-dismiss='alert' area-label='close'></button> </div> "; } if(!empty($successMessage)){ echo" <div class='alert alert-success alert-dismissible fade show' role='alert'> <strong>$successMessage</strong> <button type='button' class'btn-close' data-bs-dismiss='alert' area-label='close'></button> </div> "; } ?> <!-- Your form, corrected --> <form method="POST"> <!-- Hidden input to pass course ID --> <input type="hidden" name="id" value="<?php echo $course_id; ?>"> <div class="row mb-3"> <label class="col-sm-3 col-form-label">Course ID</label> <div class="col-sm-6"> <input type="text" class="form-control" name="course_id" value="<?php echo $course_id; ?>" readonly> </div> </div> <div class="row mb-3"> <label class="col-sm-3 col-form-label">Course Title</label> <div class="col-sm-6"> <input type="text" class="form-control" name="course_title" value="<?php echo $course_title; ?>"> </div> </div> <div class="row mb-3"> <label class="col-sm-3 col-form-label">Course Description</label> <div class="col-sm-6"> <input type="text" class="form-control" name="course_description" value="<?php echo $course_description; ?>"> </div> </div> <div class="row mb-3"> <label class="col-sm-3 col-form-label">Course Credits</label> <div class="col-sm-6"> <input type="text" class="form-control" name="course_credits" value="<?php echo $course_credits; ?>"> </div> </div> <div class="instructor-inputs"> <?php // Populate existing instructors if (!empty($instructor_ids)) { foreach ($instructor_ids as $key => $instructor_id) { $language_id = isset($language_ids[$key]) ? $language_ids[$key] : ''; // Check if the key exists $language_name = isset($language_names[$key]) ? $language_names[$key] : ''; // Check if the key exists echo ' <div class="row mb-3"> <div class="col-sm-3"> <input type="text" class="form-control" name="instructor_id[]" value="' . $instructor_id . '" placeholder="Instructor ID" required readonly> </div> <div class="col-sm-3"> <select name="language_id[]" required> <option value="' . $language_id . '">' . $language_name . '</option> <!-- Add other language options as needed --> </select> </div> <div class="col-sm-1"> <button type="button" class="btn btn-danger btn-remove-instructor">X</button> </div> </div>'; } } ?> </div> <button type="button" id="add-instructor">Add Instructor</button> <div class="row mb-3"> <div class="offset-sm-3 col-sm-3 d-grid"> <button type="submit" class="btn btn-primary">Submit</button> </div> <div class="col-sm-3 d-grid"> <a class="btn btn-outline-primary" href="/website/admin.php" role="button">Cancel</a> </div> </div> </form> <script> document.getElementById('add-instructor').addEventListener('click', function () { var instructorInput = document.createElement('div'); instructorInput.classList.add('instructor-input'); instructorInput.innerHTML = ` <div class="row mb-3"> <div class="col-sm-3"> <input type="text" class="form-control" name="instructor_id[]" value="" placeholder="Instructor ID" required> </div> <div class="col-sm-3"> <select name="language_id[]" required> <option value="1">Arabic</option> <option value="2">English</option> <option value="3">French</option> </select> </div> <div class="col-sm-1"> <button type="button" class="btn btn-danger btn-remove-instructor">X</button> </div> </div> `; document.querySelector('.instructor-inputs').appendChild(instructorInput); }); // Event delegation for dynamically added close buttons document.querySelector('.instructor-inputs').addEventListener('click', function (event) { if (event.target.classList.contains('btn-remove-instructor')) { // Remove the parent row when the close button is clicked event.target.closest('.row').remove(); } }); </script> </div> </body> </html>
use anyhow::Context; use roxmltree::{Document, Node}; use serde::Serialize; use std::io::{BufReader, Read, Seek}; use zip::ZipArchive; #[derive(Serialize)] pub struct Nuspec { /// The unique package identifier. pub id: String, /// The version of the package, following the major.minor.patch pattern. pub version: String, /// A description of the package for UI display. pub description: String, /// A comma-separated list of packages authors, matching the profile names on nuget.org. pub authors: String, /// A URL for the package's home page, often shown in UI displays as well as nuget.org. pub project_url: Option<String>, /// An SPDX license expression or path to a license file within the package. pub license: Option<String>, /// A URL for a 128x128 image with transparency background to use as the icon for the package in UI display. pub icon_url: Option<String>, /// It is a path to an image file within the package, often shown in UIs like nuget.org as the package icon. pub icon: Option<String>, /// The path to the package's readme file. pub readme: Option<String>, /// A human-friendly title of the package which may be used in some UI displays. pub title: Option<String>, } impl Nuspec { /// Creates a [Nuspec] from the given [ZipArchive]. pub fn from_archive<R: Read + Seek>(zip: &mut ZipArchive<R>) -> anyhow::Result<Self> { for i in 0..zip.len() { let file = zip.by_index(i); let file = file.context("Failed to extract NuGet package entry")?; let file_name = file.name(); if file_name.ends_with(".nuspec") { let mut contents = String::with_capacity(file.size() as _); let mut file = BufReader::new(file); file.read_to_string(&mut contents)?; return Self::parse(&contents); } } anyhow::bail!("Failed to find nuspec file in NuGet package"); } /// Parse the `xxx.nuspec` file contents. fn parse(nuspec: &str) -> anyhow::Result<Self> { let xml = Document::parse(nuspec).context("Failed to parse nuspec file")?; let meta = xml .descendants() .find(|n| n.has_tag_name("metadata")) .context("Failed to find metadata node")?; Ok(Self { id: get_el_text(meta, "id").context("Missing `id` node")?, version: get_el_text(meta, "version").context("Missing `version` node")?, description: get_el_text(meta, "description").context("Missing `description` node")?, authors: get_el_text(meta, "authors").context("Missing `authors` node")?, project_url: get_el_text(meta, "projectUrl"), license: get_el_text(meta, "license"), icon_url: get_el_text(meta, "iconUrl"), icon: get_el_text(meta, "icon"), readme: get_el_text(meta, "readme"), title: get_el_text(meta, "title"), }) } } fn get_el_text(node: Node, name: &str) -> Option<String> { node .children() .find(|n| n.has_tag_name(name)) .and_then(|n| n.text()) .map(|t| t.to_string()) }
import createHttpError from 'http-errors'; import httpStatus from 'http-status'; import { z } from 'zod'; import { validateReqBody } from '../../../middlewares/validateRequest.js'; import asyncHandler from '../../../utils/asyncHandler.js'; import controllerFactory from '../../../utils/controllerFactory.js'; import { HttpMethod } from '../../../utils/enum/index.js'; import { success } from '../../../utils/response.js'; import { addItemToCart } from '../cart.services.js'; import { findProductById } from '../../product/product.services.js'; const reqBodySchema = z.object({ productId: z.string(), productName: z.string(), type: z.string(), quantity: z.number(), price: z.number(), ownerId: z.string().optional() }); async function handler(req, res) { const product = await findProductById(req.body.productId); if (!product) { throw createHttpError.BadRequest('Product not found'); } await addItemToCart(req.user.userId, req.body); return success({ status: httpStatus.OK, message: 'Item has been added to your cart!' }).send(res); } const addItem = controllerFactory() .method(HttpMethod.POST) .path('/') .handler(asyncHandler(handler)) .middlewares([validateReqBody(reqBodySchema)]); export default addItem;
import { AfterViewInit, Component, HostListener, Input, OnDestroy, OnInit, QueryList, ViewChildren } from '@angular/core'; import { Router } from '@angular/router'; import { NbDialogService, NbIconConfig, NbPopoverDirective, NbToastrService } from '@nebular/theme'; import { KeyboardModes, KeyboardNavigationService } from 'src/app/services/keyboard-navigation.service'; import { StatusService } from 'src/app/services/status.service'; import { Constants } from 'src/assets/util/Constants'; import { Actions, DefaultKeySettings, KeyBindings } from 'src/assets/util/KeyBindings'; import { environment } from 'src/environments/environment'; import * as $ from 'jquery'; import { BaseNavigatableComponentComponent } from '../../shared/base-navigatable-component/base-navigatable-component.component'; import { ConfirmationDialogComponent } from '../../shared/simple-dialogs/confirmation-dialog/confirmation-dialog.component'; import { LoginDialogComponent } from '../../auth/login-dialog/login-dialog.component'; import { LoginDialogResponse } from '../../auth/models/LoginDialogResponse'; import { TokenStorageService } from '../../auth/services/token-storage.service'; import { AuthService } from '../../auth/services/auth.service'; import { SubMappingNavigatable } from 'src/assets/model/navigation/Nav'; import { BbxToastrService } from 'src/app/services/bbx-toastr-service.service'; import { KeyboardHelperService } from 'src/app/services/keyboard-helper.service'; import { HelperFunctions } from 'src/assets/util/HelperFunctions'; import { CommonService } from 'src/app/services/common.service'; import { LoggerService } from 'src/app/services/logger.service'; @Component({ selector: 'app-header', templateUrl: './header.component.html', styleUrls: ['./header.component.scss'] }) export class HeaderComponent extends BaseNavigatableComponentComponent implements OnInit, AfterViewInit, OnDestroy { @ViewChildren(NbPopoverDirective) popover?: QueryList<NbPopoverDirective>; @Input() title: string = ""; settingsIconConfig: NbIconConfig = { icon: 'settings-2-outline', pack: 'eva' }; isElectron: boolean = false; isLoading: boolean = false; get isLoggedIn(): boolean { return this.tokenService.isLoggedIn; }; get InProgress(): boolean { return this.statusService.InProgress || this.isLoading; } get keyboardMode(): string { var mode = this.keyboardService.currentKeyboardMode; switch (mode) { case KeyboardModes.NAVIGATION: return "Mód: Navigáció"; break; case KeyboardModes.EDIT: return "Mód: Szerkesztés"; break; case KeyboardModes.NAVIGATION_EDIT: return "Mód: Javítás"; break; default: return "Mód: Ismeretlen"; break; } } get keyboardModeStatus(): string { var mode = this.keyboardService.currentKeyboardMode; switch (mode) { case KeyboardModes.NAVIGATION: return "primary"; break; case KeyboardModes.EDIT: return "warning"; break; case KeyboardModes.NAVIGATION_EDIT: default: return "danger"; break; } } get wareHouseInfo(): string { const wareHouse = this.tokenService.wareHouse; if (wareHouse) { return `${wareHouse.warehouseCode} ${wareHouse.warehouseDescription}` } else { return 'nincs kiválasztva' } } constructor( private readonly dialogService: NbDialogService, private readonly keyboardService: KeyboardNavigationService, private readonly router: Router, private readonly statusService: StatusService, private readonly authService: AuthService, private readonly tokenService: TokenStorageService, private readonly bbxToastrService: BbxToastrService, private readonly simpleToastrService: NbToastrService, private readonly status: StatusService, private readonly keyboardHelperService: KeyboardHelperService, private readonly commonService: CommonService, private readonly loggerService: LoggerService) { super(); this.OuterJump = true; } override ngOnInit(): void { this.isElectron = environment.electron; } ngAfterViewInit(): void { this.GenerateAndSetNavMatrices(); this.keyboardService.SelectFirstTile(); if (!this.isLoggedIn) { this.login(undefined); } this.commonService.CloseAllHeaderMenuTrigger.subscribe({ next: data => { if (data) { this.popover?.forEach(x => x?.hide()); } } }) } ngOnDestroy(): void { this.commonService.CloseAllHeaderMenuTrigger.unsubscribe() } public override GenerateAndSetNavMatrices(attach: boolean = true): void { // Get menus const headerMenusRaw = $(".cl-header-menu"); // Prepare matrix and submenu mappings this.Matrix = [[]]; this.SubMapping = {}; // Getting ids for menus for (let i = 0; i < headerMenusRaw.length; i++) { // Id of menu for navigation const nextId = headerMenusRaw[i].id; this.Matrix[0].push(nextId); // Get list of submenu ids from the data-sub attribute const subItems = headerMenusRaw[i].getAttribute('data-sub')?.split(','); if (!!subItems) { for (let o = 0; o < subItems.length; o++) { // Next submenu id to add const nextSubId = subItems[o]; // If no available mapping for the menu, initialize it if (!!!this.SubMapping[nextId]) { this.SubMapping[nextId] = new SubMappingNavigatable(); } // Adding submenu id to the mapping of the current menu this.SubMapping[nextId].Matrix.push([nextSubId]); } } } this.loggerService.info(`[HeaderComponent] Generated header matrix: '${JSON.stringify(this.Matrix)}' \nSubmapping: '${JSON.stringify(this.SubMapping)}'`); this.keyboardService.SetRoot(this); } /** * Checkboxok esetében readonly mellett is át tudom őket kattintani, így ilyen esetekre itt blokkolok minden readonly elemre szóló kattintást. * @param event */ @HostListener('window:click', ['$event']) onClick(event: MouseEvent) { if (event.target && (event as any).target.readOnly) { event.stopPropagation(); event.preventDefault(); } } /** * Billentyűsnavigálás tekintetében az event érzékelés felsőbb rétege. Iniciálisan itt történik meg a * 4 irányba történő navigálásra vonatkozó parancs meghívása, eventek továbbfolyásának tiltása. * @param event * @returns */ @HostListener('window:keydown', ['$event']) onKeyDown(event: KeyboardEvent) { if (event.ctrlKey && event.key === KeyBindings.F5) { this.loggerService.info("[onKeyDown] Ctrl+F5 pressed, navigating to home...") event.preventDefault() event.stopImmediatePropagation() event.stopPropagation() this.goTo('/') this.keyboardService.ClickCurrentElement() this.keyboardService.setEditMode(KeyboardModes.NAVIGATION) return } if (this.bbxToastrService.IsToastrOpened) { event.preventDefault(); event.stopImmediatePropagation(); event.stopPropagation(); this.bbxToastrService.close(); return } if (this.keyboardService.IsLocked() || this.status.InProgress || this.keyboardHelperService.IsKeyboardBlocked) { this.loggerService.info("[onKeyDown] Movement is locked!"); event.preventDefault(); event.stopImmediatePropagation(); event.stopPropagation(); return } switch (event.key) { case DefaultKeySettings[Actions.Help].KeyCode: { event.preventDefault(); event.stopImmediatePropagation(); event.stopPropagation(); this.goToUserManuals() break; } case KeyBindings.up: { if (!this.keyboardService.isEditModeActivated) { event.preventDefault(); this.keyboardService.MoveUp(true, event.altKey); } break; } case KeyBindings.down: { if (!this.keyboardService.isEditModeActivated) { event.preventDefault(); this.keyboardService.MoveDown(true, event.altKey); } break; } case KeyBindings.left: { if (!this.keyboardService.isEditModeActivated) { event.preventDefault(); this.keyboardService.MoveLeft(true, event.altKey); } break; } case KeyBindings.right: { if (!this.keyboardService.isEditModeActivated) { event.preventDefault(); this.keyboardService.MoveRight(true, event.altKey); } break; } case KeyBindings.exitIE: case KeyBindings.exit: { if (!this.keyboardHelperService.IsDialogOpened) { this.keyboardService.setEditMode(KeyboardModes.NAVIGATION); } break; } default: { } } } handleEscape(): void { this.keyboardService.setEditMode(KeyboardModes.NAVIGATION); } goTo(link: string): void { this.popover?.forEach(x => x?.hide()) this.keyboardService.RemoveWidgetNavigatable() if (link === "home") { this.router.navigate([link]) } else { this.router.navigate(["home"]) setTimeout(() => { this.router.navigate([link]) }, 50) } } goToUserManuals(event?: any): void { if (event) event.preventDefault() window.open(environment.userManualsLink, "_blank") } quit(event: any): void { event.preventDefault(); if (!this.isElectron) { return; } const dialogRef = this.dialogService.open(ConfirmationDialogComponent, { context: { msg: Constants.MSG_CONFIRMATION_QUIT } }); dialogRef.onClose.subscribe(res => { if (res) { window.close(); } }); } login(event: any): void { event?.preventDefault(); const dialogRef = this.dialogService.open(LoginDialogComponent, { context: {}, closeOnEsc: false }); this.isLoading = true; dialogRef.onClose.subscribe(this.onLoginDialogClose.bind(this)); } private async onLoginDialogClose(res: LoginDialogResponse): Promise<void> { if (!!res && res.answer && res.wareHouse) { try { this.statusService.pushProcessStatus(Constants.LoggingInStatus) const response = await this.authService.login(res.name, res.pswd) if (response.succeeded && !HelperFunctions.isEmptyOrSpaces(response?.data?.token) && response?.data?.user) { this.tokenService.token = response?.data?.token; this.tokenService.user = response?.data?.user; this.tokenService.wareHouse = res.wareHouse this.simpleToastrService.show( Constants.MSG_LOGIN_SUCCESFUL, Constants.TITLE_INFO, Constants.TOASTR_SUCCESS_5_SEC ); setTimeout(() => { this.GenerateAndSetNavMatrices(); this.keyboardService.SelectFirstTile(); this.isLoading = false; this.keyboardService.setEditMode(KeyboardModes.NAVIGATION); }, 200); } else { this.bbxToastrService.show(Constants.MSG_LOGIN_FAILED, Constants.TITLE_ERROR, Constants.TOASTR_ERROR); this.isLoading = false; this.keyboardService.setEditMode(KeyboardModes.NAVIGATION); } } catch (error) { this.bbxToastrService.show(Constants.MSG_LOGIN_FAILED, Constants.TITLE_ERROR, Constants.TOASTR_ERROR); this.isLoading = false; this.keyboardService.setEditMode(KeyboardModes.NAVIGATION); } finally { this.statusService.pushProcessStatus(Constants.BlankProcessStatus) } } else { setTimeout(() => { this.keyboardService.SelectFirstTile(); this.isLoading = false; this.keyboardService.setEditMode(KeyboardModes.NAVIGATION); }, 200); } } logout(event: any): void { event?.preventDefault(); HelperFunctions.confirm(this.dialogService, Constants.MSG_LOGOUT_CONFIGM, () => { this.statusService.pushProcessStatus(Constants.LogoutSavingStatuses[Constants.LogoutSavingPhases.LOGGING_OUT]); this.authService.logout().subscribe({ next: res => { this.simpleToastrService.show( Constants.MSG_LOGOUT_SUCCESFUL, Constants.TITLE_INFO, Constants.TOASTR_SUCCESS_5_SEC ); this.tokenService.signOut(); this.router.navigate(['/home']); setTimeout(() => { this.GenerateAndSetNavMatrices(); this.keyboardService.SelectFirstTile(); }, 200); }, error: err => { this.bbxToastrService.show(Constants.MSG_LOGOUT_FAILED, Constants.TITLE_ERROR, Constants.TOASTR_ERROR); }, complete: () => { this.statusService.pushProcessStatus(Constants.BlankProcessStatus); } }); }); } }
import os from flask import Flask, request from flask_smorest import Api import uuid from resources.shop import blueprint as ShopBluePrint from resources.product import blueprint as ProductBluePrint from db import db import models app = Flask(__name__) app.config["PROPAGATE_EXCEPTIONS"] = True app.config["API_TITLE"] = "Shops REST API" app.config["API_VERSION"] = "v1" app.config["OPENAPI_VERSION"] = "3.0.3" app.config["OPENAPI_URL_PREFIX"] = "/" app.config["OPENAPI_SWAGGER_UI_PATH"] = "/swagger-ui" app.config["OPENAPI_SWAGGER_UI_URL"] = "https://cdn.jsdelivr.net/npm/swagger-ui-dist/" app.config["SQLALCHEMY_DATABASE_URI"] = os.getenv("DATABASE_URL", "sqlite:///shop.db") app.config["SQLALCHEMY_TRACK_MODIFICATIONS"] = False db.init_app(app) api = Api(app) with app.app_context(): db.create_all() api.register_blueprint(ShopBluePrint) api.register_blueprint(ProductBluePrint)
#ifndef _MAIN_H_ #define _MAIN_H_ /** * binary_to_uint - function that converts a binary number to an unsigned int * @b: pointer to a string of 0 and 1 chars * * Return: the binary representation or * 0 if b == NULL, or b contains a char not 0 or 1 */ unsigned int binary_to_uint(const char *b); /** * print_binary - function that prints the binary representation of a number * @n: number to convert to binary * */ void print_binary(unsigned long int n); /** * get_bit - function that returns the value of a bit at a given index * @n: integer to be searched * @index: index of the bit required * * Return: value of the bit at index or -1(ERROR) */ int get_bit(unsigned long int n, unsigned int index); /** * set_bit - function that sets the value of a bit to 1 at a given index * @n: pointer to integer to have bit set to 1 * @index: index of bit to be set to 1 * * Return: 1(SUCCESS), OR -1(ERROR) */ int set_bit(unsigned long int *n, unsigned int index); /** * clear_bit - function that sets the value of a bit to 0 at a given index * @n: pointer to integer to have bit set to 0 * @index: index of bit to be set to 0 * * Return: 1(SUCCESS), OR -1(ERROR) */ int clear_bit(unsigned long int *n, unsigned int index); /** * flip_bits - function that returns the number of bits you would need to flip * to get from one number to another * @n: initial number * @m: number to convert to * * Return: number of bits to flip */ unsigned int flip_bits(unsigned long int n, unsigned long int m); /** * _putchar - writes the character c to stdout * @c: The character to print * * Return: On success 1. * On error, -1 is returned, and errno is set appropriately. */ int _putchar(char c); #endif /* #ifndef _MAIN_H_ */
@file:Suppress("DEPRECATION") package io.esper.lenovolauncher.fragment import android.annotation.SuppressLint import android.content.Context import android.content.Intent import android.graphics.Bitmap import android.graphics.BitmapFactory import android.os.Build import android.os.Bundle import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.webkit.PermissionRequest import android.webkit.WebChromeClient import android.webkit.WebSettings import android.webkit.WebViewClient import android.widget.FrameLayout import android.widget.LinearLayout import android.widget.TextView import androidx.fragment.app.Fragment import androidx.fragment.app.FragmentActivity import im.delight.android.webview.AdvancedWebView import io.esper.lenovolauncher.R import io.esper.lenovolauncher.constants.Constants import io.esper.lenovolauncher.constants.Constants.sharedPrefManaged import org.greenrobot.eventbus.EventBus import org.greenrobot.eventbus.Subscribe import org.greenrobot.eventbus.ThreadMode class VideoVisitFragment : Fragment(), AdvancedWebView.Listener { private lateinit var ctx: Context private lateinit var mWebView: AdvancedWebView private lateinit var featureNotAvailable: TextView private lateinit var loading: LinearLayout @SuppressLint("SetJavaScriptEnabled") override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?, ): View { val rootView: View = inflater.inflate(R.layout.fragment_video_visit, container, false) mWebView = rootView.findViewById<View>(R.id.webview_video_visit) as AdvancedWebView featureNotAvailable = rootView.findViewById<View>(R.id.feature_not_available_video_visit) as TextView loading = rootView.findViewById<View>(R.id.feature_loading_video_visit) as LinearLayout mWebView.setDesktopMode(true) mWebView.settings.builtInZoomControls = true mWebView.settings.displayZoomControls = false mWebView.settings.setAppCacheMaxSize(5 * 1024 * 1024) mWebView.settings.setAppCachePath(requireContext().applicationContext.cacheDir.absolutePath) mWebView.settings.allowFileAccess = true mWebView.settings.setAppCacheEnabled(true) mWebView.settings.cacheMode = WebSettings.LOAD_DEFAULT mWebView.setMixedContentAllowed(true) mWebView.setListener(activity, this) mWebView.webViewClient = WebViewClient() mWebView.webChromeClient = MyChrome(activity) val webSettings = mWebView.settings webSettings.javaScriptEnabled = true webSettings.allowFileAccess = true webSettings.setAppCacheEnabled(true) checkForFeatureAvailability() return rootView } @SuppressLint("NewApi") override fun onResume() { super.onResume() mWebView.onResume() } @SuppressLint("NewApi") override fun onPause() { mWebView.onPause() super.onPause() } override fun onDestroy() { mWebView.onDestroy() super.onDestroy() } override fun onActivityResult(requestCode: Int, resultCode: Int, intent: Intent?) { super.onActivityResult(requestCode, resultCode, intent) mWebView.onActivityResult(requestCode, resultCode, intent) } override fun onAttach(context: Context) { super.onAttach(context) ctx = context } override fun onPageStarted(url: String?, favicon: Bitmap?) { } override fun onPageFinished(url: String?) { loading.visibility = View.GONE } override fun onPageError(errorCode: Int, description: String, failingUrl: String) {} override fun onDownloadRequested( url: String, suggestedFilename: String, mimeType: String, contentLength: Long, contentDisposition: String, userAgent: String, ) { } override fun onExternalPageRequest(url: String) {} private class MyChrome(private var activity: FragmentActivity?) : WebChromeClient() { private var mCustomView: View? = null private var mCustomViewCallback: CustomViewCallback? = null // protected var mFullscreenContainer: FrameLayout? = null // private var mOriginalOrientation = 0 private var mOriginalSystemUiVisibility = 0 override fun getDefaultVideoPoster(): Bitmap? { return if (mCustomView == null) { null } else BitmapFactory.decodeResource(activity!!.applicationContext.resources, 2130837573) } override fun onHideCustomView() { (activity!!.window.decorView as FrameLayout).removeView(mCustomView) mCustomView = null activity!!.window.decorView.systemUiVisibility = mOriginalSystemUiVisibility mCustomViewCallback!!.onCustomViewHidden() mCustomViewCallback = null } override fun onShowCustomView( paramView: View, paramCustomViewCallback: CustomViewCallback, ) { if (mCustomView != null) { onHideCustomView() return } mCustomView = paramView mOriginalSystemUiVisibility = activity!!.window.decorView.systemUiVisibility mCustomViewCallback = paramCustomViewCallback (activity!!.window.decorView as FrameLayout).addView( mCustomView, FrameLayout.LayoutParams(-1, -1) ) activity!!.window.decorView.systemUiVisibility = 3846 or View.SYSTEM_UI_FLAG_LAYOUT_STABLE } override fun onPermissionRequest(request: PermissionRequest) { val resources = request.resources when (resources[0]) { PermissionRequest.RESOURCE_AUDIO_CAPTURE -> { // Toast.makeText(activity, "Audio Permission", Toast.LENGTH_SHORT).show() request.grant(arrayOf(PermissionRequest.RESOURCE_AUDIO_CAPTURE)) } PermissionRequest.RESOURCE_MIDI_SYSEX -> { // Toast.makeText(activity, "MIDI Permission", Toast.LENGTH_SHORT).show() if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) { request.grant(arrayOf(PermissionRequest.RESOURCE_MIDI_SYSEX)) } } PermissionRequest.RESOURCE_PROTECTED_MEDIA_ID -> { // Toast.makeText(activity, "Encrypted media permission", Toast.LENGTH_SHORT).show() request.grant(arrayOf(PermissionRequest.RESOURCE_PROTECTED_MEDIA_ID)) } PermissionRequest.RESOURCE_VIDEO_CAPTURE -> { // Toast.makeText(activity, "Video Permission", Toast.LENGTH_SHORT).show() request.grant(arrayOf(PermissionRequest.RESOURCE_VIDEO_CAPTURE)) } } } } class RefreshNeededInFragment @Subscribe(threadMode = ThreadMode.MAIN) fun onMessageEvent(event: RefreshNeededInFragment) { checkForFeatureAvailability() } private fun checkForFeatureAvailability() { if (sharedPrefManaged == null) { sharedPrefManaged = ctx.getSharedPreferences(Constants.SHARED_MANAGED_CONFIG_VALUES, Context.MODE_PRIVATE) } if (sharedPrefManaged!!.getString(Constants.SHARED_MANAGED_CONFIG_PATIENT_ID, null) != null && sharedPrefManaged!!.getString(Constants.SHARED_MANAGED_CONFIG_PATIENT_NAME, null) != null ) { mWebView.visibility = View.VISIBLE featureNotAvailable.visibility = View.GONE loading.visibility = View.VISIBLE mWebView.loadUrl( "https://meet.jit.si/" + sharedPrefManaged!!.getString( Constants.SHARED_MANAGED_CONFIG_PATIENT_ID, null ) ) } else { mWebView.visibility = View.GONE loading.visibility = View.GONE featureNotAvailable.visibility = View.VISIBLE } } override fun onStart() { super.onStart() EventBus.getDefault().register(this) } override fun onStop() { EventBus.getDefault().unregister(this) super.onStop() } }
module BinomialSets export BinomialSet, order, binomials, reduction_tree, is_support_reducible, fourti2_form, sbinomial, minimal_basis!, reduced_basis!, auto_reduce_once!, is_minimization, change_ordering!, is_groebner_basis, is_truncated_groebner_basis using MIPMatrixTools.IPInstances using IPGBs.FastBitSets using IPGBs.Orders using IPGBs.GBElements using IPGBs.SupportTrees using IPGBs.Binomials """ Represents a set of binomials (e.g. a partial or complete Gröbner Basis), including structures for efficient reduction of elements. In order to allow 4ti2-form bases, we allow elements to be Vector{Int}, in addition to GBElements. """ struct BinomialSet{T <: AbstractVector{Int}, S <: GBOrder} <: AbstractVector{T} basis :: Vector{T} order :: S reduction_tree :: SupportTree{T} minimization_form :: Bool #TODO: maybe this should be part of the order? function BinomialSet{T, S}(basis :: Vector{T}, order :: S, min :: Bool) where {T, S} tree = SupportTree{T}(basis, fullfilter=is_implicit(T)) GBElements.compute_supports.(basis) GBElements.compute_binaries.(basis) new{T, S}(basis, order, tree, min) end end function BinomialSet( basis :: Vector{T}, order :: S ) where {T <: AbstractVector{Int}, S <: GBOrder} return BinomialSet{T, S}(basis, order, !is_implicit(T)) end function BinomialSet( basis :: Vector{T}, C :: Array{S}, A :: Matrix{Int}, b :: Vector{Int}, unbounded :: Union{Vector{Bool}, Nothing} = nothing, R :: DataType = T ) where {T <: AbstractVector{Int}, S <: Real} is_minimization = !is_implicit(T) if !(S <: Float64) C = Float64.(C) end if isnothing(unbounded) unbounded = fill(false, size(A, 2)) end order = MonomialOrder(C, A, b, unbounded, is_minimization) oriented_basis = T[] for g in basis oriented_g = copy(g) orientate!(oriented_g, order) push!(oriented_basis, oriented_g) end if R == Binomial new_oriented = [to_gbelement(v, order, R, false) for v in oriented_basis] return BinomialSet{R, MonomialOrder}(new_oriented, order, is_minimization) end return BinomialSet{T, MonomialOrder}(oriented_basis, order, is_minimization) end function BinomialSet( basis :: Vector{T}, ip :: IPInstance, S :: DataType = T ) where {T <: AbstractVector{Int}} return BinomialSet(basis, ip.C, ip.A, ip.b, unbounded_variables(ip), S) end """ Changes the ordering of `bs` to a monomial order given by the matrix `new_order`. """ function change_ordering!( bs :: BinomialSet{T, S}, new_order :: Array{Float64, 2}, A :: Array{Int, 2}, b :: Vector{Int} ) where {T <: AbstractVector{Int}, S <: GBOrder} Orders.change_ordering!(bs.order, new_order, A, b) #TODO: I probably should also reorientate all elements of bs end function binomials(fourti2_basis :: Matrix{Int}) return [ fourti2_basis[i, :] for i in 1:size(fourti2_basis, 1) ] end has_order(:: BinomialSet) = true has_order(:: AbstractVector) = false # # Accessors # binomials(bs :: BinomialSet) = bs.basis order(bs :: BinomialSet) = bs.order reduction_tree(bs :: BinomialSet) = bs.reduction_tree is_minimization(bs :: BinomialSet) = bs.minimization_form # # Implementing the AbstractVector interface # function Base.size( bs :: BinomialSet{T, S} ) :: Tuple where {T <: AbstractVector{Int}, S <: GBOrder} return size(bs.basis) end function Base.getindex( bs :: BinomialSet{T, S}, i :: Int ) :: T where {T <: AbstractVector{Int}, S <: GBOrder} return bs.basis[i] end function Base.length( bs :: BinomialSet{T, S} ) :: Int where {T <: AbstractVector{Int}, S <: GBOrder} return length(bs.basis) end function Base.push!( bs :: BinomialSet{T, S}, g :: T ) where {T <: AbstractVector{Int}, S <: GBOrder} push!(bs.basis, g) add_binomial!(bs.reduction_tree, bs[length(bs)]) GBElements.compute_supports(g) GBElements.compute_binaries(g) end function Base.insert!( bs :: BinomialSet{T, S}, i :: Int, g :: T ) where {T <: AbstractVector{Int}, S <: GBOrder} insert!(bs.basis, i, g) add_binomial!(bs.reduction_tree, g) GBElements.compute_supports(g) GBElements.compute_binaries(g) end function Base.deleteat!( bs :: BinomialSet{T, S}, i :: Int ) where {T <: AbstractVector{Int}, S <: GBOrder} deleted_elem = bs[i] remove_binomial!(reduction_tree(bs), deleted_elem) deleteat!(bs.basis, i) end # # Additional functions defined on a BinomialSet # """ Reduces `g` by `bs` efficiently using a Support Tree. Returns a pair of booleans (r, c) where r == true iff `g` reduced to zero, and c == true iff `g` was changed in this reduction. """ function reduce!( g :: T, bs :: BinomialSet{T, S}; skipbinomial :: Union{T, Nothing} = nothing, is_monomial_reduction :: Bool = is_monomial(g) ) :: Tuple{Bool, Bool} where {T <: AbstractVector{Int}, S <: GBOrder} return reduce!( g, bs, reduction_tree(bs), skipbinomial=skipbinomial, is_monomial_reduction=is_monomial_reduction ) end """ reduce!( g :: T, bs :: Vector{T} ) :: Tuple{Bool, Bool} where {T <: AbstractVector{Int}} Reduce `g` by `bs` inefficiently by linearly searching for a reducer. This is useful for very small examples and debugging. For anything else, consider making a BinomialSet and reducing using a SupportTree. Return a tuple (r, c) where r == true iff `g` reduced to zero, and c == true iff `g` was changed in this reduction. """ function reduce!( g :: T, bs :: Vector{T} ) :: Tuple{Bool, Bool} where {T <: AbstractVector{Int}} function linear_reducer_search(g, bs) found_reducer = false reducer = copy(g) for r in bs if GBElements.reduces(r, g) found_reducer = true reducer = r break end end return reducer, found_reducer end reducer, found_reducer = linear_reducer_search(g, bs) changed = false reduced_to_zero = false while found_reducer changed = true GBElements.reduce!(g, reducer) if is_zero(g) reduced_to_zero = true break end reducer, found_reducer = linear_reducer_search(g, bs) end return reduced_to_zero, changed end """ Fully reduce `binomial` by `gb` in-place, finding its normal form. Uses `tree` to speed up the search for reducers. Returns a pair of booleans (r, c) where r == true iff `g` reduced to zero, and c == true iff `g` was changed in this reduction. `binomial` can also be a monomial. If `reduction_count` is given, the number of times each reducer was used in this reduction process is added to reduction_count. This greatly slows down execution, and is only meant for experimental purposes. The parameter should be set to `nothing` in practical runs. """ function reduce!( g :: T, gb :: S, tree :: ReductionTree{T}; reduction_count :: Union{Vector{Int}, Nothing} = nothing, skipbinomial :: Union{T, Nothing} = nothing, is_monomial_reduction :: Bool = false ) :: Tuple{Bool, Bool} where {T <: AbstractVector{Int}, S <: AbstractVector{T}} changed = false #Reduce both the leading and trailing terms, leading first for negative in (false, true) if negative && !is_minimization(gb) #In implicit form, the reduction already reduces both leading and #trailing term. In this case, there's nothing to do here. return false, changed end while true reducer, found_reducer = find_reducer( g, gb, tree, skipbinomial=skipbinomial, negative=negative ) #g has a singular signature, so it reduces to zero #We can ignore the reducer and just say `g` reduces to zero #if haskey(params, "is_singular") && params["is_singular"] #if is_singular[] # return true, changed #end #No reducer found, terminate search if !found_reducer if negative return false, changed end break end #Found some reducer, add it to histogram if one is available if !isnothing(reduction_count) for i in 1:length(gb) if gb[i] === reducer reduction_count[i] += 1 break end end end if !GBElements.is_negative_disjoint(g, reducer, negative=negative) #@debug( # "Found reducer but it is not negative disjoint", # g, reducer, negative #) return true, changed end #Now apply the reduction and check if it is a zero reduction #@debug( # "Reducing g by reducer", g, reducer, negative #) changed = true if has_order(gb) && !is_monomial_reduction reduced_to_zero = GBElements.reduce!( g, reducer, order(gb), negative=negative ) else reduced_to_zero = GBElements.reduce!( g, reducer, negative=negative ) end #@debug("Reduced g", result=g, reduced_to_zero) if reduced_to_zero return true, changed end end end @assert false #We should never reach this return false, false end """ Creates a concrete S-binomial from `pair`. In practice, this should only be called after we were unable to eliminate `pair`. """ function sbinomial( mem :: Vector{Int}, pair :: CriticalPair, bs :: BinomialSet{T, S} ) :: T where {T <: AbstractVector{Int}, S <: GBOrder} v = bs[GBElements.first(pair)] w = bs[GBElements.second(pair)] r = build(mem, v, w, pair) orientate!(r, order(bs)) return r end """ Returns true if (i, j) should be discarded. This is an implementation of Criteria 1 and 2 from Malkin's thesis. Criterion 1 is simply the classical Buchberger GCD criterion. If the positive supports are disjoint (= GCD of the leading terms is 1) then the pair may be discarded. Criterion 2 is specific to homogeneous ideals (or just ideals coming from lattices?) Either way, if the negative supports are not disjoint (= GCD of trailing terms is not 1) then the pair may be discarded. This applies specifically to the bounded components (= variables) of the problem. I also added new criteria for binary variables. In this case, a pair (i, j) may be discarded if the positive binaries of i are disjoint from the negative binaries of j, and vice-versa. This is because in these cases the pair will generate some binomial with 2 or -2 in some coordinate. These are never necessary in a Gröbner basis. """ function is_support_reducible( i :: Int, j :: Int, bs :: BinomialSet{T, S}; use_binary_truncation :: Bool = true ) :: Bool where {T <: AbstractVector{Int}, S <: GBOrder} #if is_minimization(bs) eliminate_by_criteria = !disjoint(negative_support(bs[i]), negative_support(bs[j])) || disjoint(positive_support(bs[i]), positive_support(bs[j])) eliminate_by_truncation = use_binary_truncation && ( !disjoint(positive_binaries(bs[i]), negative_binaries(bs[j])) || !disjoint(negative_binaries(bs[i]), positive_binaries(bs[j]))) return eliminate_by_criteria || eliminate_by_truncation #end #Maximization problem #return disjoint(negative_support(bs[i]), negative_support(bs[j])) || # !disjoint(positive_support(bs[i]), positive_support(bs[j])) end """ Returns true iff `bs` is a Gröbner Basis. This is checked by applying Buchberger's theorem and generating all S-binomials, thus may be slow. Note that this verifies if `bs` is a Gröbner Basis, but not a truncated Gröbner Basis. To check the latter case, use is_truncated_groebner_basis. Useful for debugging and automatic tests. """ function is_groebner_basis( bs :: BinomialSet{T, S} ) :: Bool where {T <: AbstractVector{Int}, S <: GBOrder} mem = Vector{Int}(undef, length(bs[1])) for i in 1:length(bs) for j in 1:(i-1) s = BinomialPair(i, j) binomial = sbinomial(mem, s, bs) reduced_to_zero, _ = reduce!(binomial, bs) if !reduced_to_zero return false end end end return true end """ is_truncated_groebner_basis( bs :: BinomialSet{T, S}, truncate :: Function ) :: Bool where {T <: AbstractVector{Int}, S <: GBOrder} Returns true if and only if `bs` is a truncated Gröbner Basis with truncation done using the `truncate` function. """ function is_truncated_groebner_basis( bs :: BinomialSet{T, S}, truncate :: Function ) :: Bool where {T <: AbstractVector{Int}, S <: GBOrder} if isempty(bs) return true end mem = Vector{Int}(undef, length(bs[1])) for i in 1:length(bs) for j in 1:(i-1) s = BinomialPair(i, j) binomial = sbinomial(mem, s, bs) reduced_to_zero, _ = reduce!(binomial, bs) if !reduced_to_zero && !truncate(binomial) @info("Missing binomial in truncated GB", binomial, bs[i], bs[j], i, j) #Note we check truncation after reduction. This is often #quicker, because then we skip the check for zero reductions return false end end end return true end """ Returns the binomials of `bs` as integer vectors in minimization form. """ function fourti2_form( bs :: BinomialSet{T, S} ) :: Vector{Vector{Int}} where {T <: AbstractVector{Int}, S <: GBOrder} sign = is_minimization(bs) ? 1 : -1 return [ sign * fullform(g) for g in bs ] end function auto_reduce_once!( gb :: BinomialSet{T, S}; current_index :: Int = 0 ) :: Tuple{Int, Int} where {T <: AbstractVector{Int}, S <: GBOrder} removed = 0 removed_before_index = 0 i = length(gb) while i >= 1 g = copy(gb[i]) #We reduce a copy of the element, otherwise, if it #is changed by reduction, it will stay in the reduction tree later reduced_to_zero, changed = reduce!(g, gb, skipbinomial=gb[i]) if reduced_to_zero || changed if i < current_index removed_before_index += 1 current_index -= 1 end @debug("Autorreduced binomial", original=gb[i], result=(reduced_to_zero ? 0 : g), reduced_to_zero, changed ) deleteat!(gb, i) end if reduced_to_zero removed += 1 elseif changed #Elements have to be readded so that their S-pairs are #recomputed. Otherwise, the cancellation criterion may #break things. push!(gb, g) end i -= 1 end return removed, removed_before_index end """ Updates gb to a minimal Gröbner Basis. For more info on minimal GBs, see Lemma 3 from Cox, Little, O'Shea Chapter 2.7. In summary, it shows that one can remove from a GB any g such that LT(g) is a multiple of LT(h), for h distinct from g in the GB. """ function minimal_basis!( gb :: BinomialSet{T, S} ) where {T <: AbstractVector{Int}, S <: GBOrder} for i in length(gb):-1:1 g = gb[i] _, found_reducer = find_reducer(g, gb, reduction_tree(gb), skipbinomial=g) if found_reducer deleteat!(gb, i) end end end """ Updates gb to a reduced Gröbner Basis. """ function reduced_basis!( gb :: BinomialSet{T, S} ) where {T <: AbstractVector{Int}, S <: GBOrder} #Currently, this implementation doesn't support signatures #TODO: Fix this later if has_signature(T) return end minimal_basis!(gb) if !is_minimization(gb) #Doesn't compute reduced basis for implicit representation #TODO: fix this in some later version! return end for i in length(gb):-1:1 g = gb[i] reducing = true while reducing h, found_reducer = find_reducer( g, gb, reduction_tree(gb), negative=true, skipbinomial=g ) if found_reducer #The binomial has to be removed from the tree first, otherwise #its filter will already have been changed and it won't be #found in the tree. SupportTrees.remove_binomial!(gb.reduction_tree, g) GBElements.reduce!(g, h, order(gb), negative=true) SupportTrees.add_binomial!(gb.reduction_tree, g) else reducing = false end end end end end
package view; import controller.GameController; import model.Chessboard; import model.PlayerColor; import javax.swing.*; import java.awt.*; import java.io.IOException; import java.io.InputStream; import java.net.ServerSocket; import java.net.Socket; public class BeginFrame extends JFrame { private final int WIDTH; private final int HEIGTH; private JLabel background; private final int ONE_CHESS_SIZE; public BeginFrame(int width,int height){ setTitle("欢迎来玩斗兽棋"); this.WIDTH = width; this.HEIGTH = height; this.ONE_CHESS_SIZE = (HEIGTH * 4 / 5) / 9; setSize(WIDTH, HEIGTH); setLocationRelativeTo(null); // Center the window. setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE); //设置程序关闭按键,如果点击右上方的叉就游戏全部关闭了 setLayout(null); addBeginButton(); addAIButton(); addNetButton(); addEasyAIButton(); addBackground(); } private void addBeginButton() { //以此为模板编写一个重新开始的按钮 JButton button = new JButton("Begin"); button.addActionListener(e -> { System.out.println("Click begin"); ChessGameFrame mainFrame = new ChessGameFrame(1100, 810,1, PlayerColor.BLUE); GameController gameController = new GameController(mainFrame.getChessboardComponent(), new Chessboard(),1,PlayerColor.BLUE); mainFrame.setVisible(true);}); button.setLocation(WIDTH/3+20,HEIGTH/3); button.setSize(200, 60); button.setFont(new Font("Rockwell", Font.BOLD, 20)); add(button); } private void addAIButton() { //以此为模板编写一个重新开始的按钮 JButton button = new JButton("AI"); button.addActionListener(e -> { System.out.println("Click AI"); ChessGameFrame mainFrame = new ChessGameFrame(1100, 810,1, PlayerColor.BLUE); GameController gameController = new GameController(mainFrame.getChessboardComponent(), new Chessboard(),1,PlayerColor.BLUE); gameController.setAI(true); mainFrame.setVisible(true);}); button.setLocation(WIDTH/3+20,HEIGTH/3+120); button.setSize(200, 60); button.setFont(new Font("Rockwell", Font.BOLD, 20)); add(button); } private void addEasyAIButton() { //以此为模板编写一个重新开始的按钮 JButton button = new JButton("easyAI"); button.addActionListener(e -> { System.out.println("Click easyAI"); ChessGameFrame mainFrame = new ChessGameFrame(1100, 810,1, PlayerColor.BLUE); GameController gameController = new GameController(mainFrame.getChessboardComponent(), new Chessboard(),1,PlayerColor.BLUE); gameController.setEasyAI(true); mainFrame.setVisible(true);}); button.setLocation(WIDTH/3+20,HEIGTH/3+240); button.setSize(200, 60); button.setFont(new Font("Rockwell", Font.BOLD, 20)); add(button); } private void addNetButton() { //以此为模板编写一个重新开始的按钮 JButton button = new JButton("Net"); button.addActionListener(e -> { System.out.println("Click Net"); Object[]colors={"BLUE","RED"}; int op = JOptionPane.showOptionDialog(null, "选择颜色", "“标题”",JOptionPane.YES_NO_CANCEL_OPTION,JOptionPane.QUESTION_MESSAGE,null, colors, colors[0]); String yoursIP = JOptionPane.showInputDialog(this,"Input IP(yours) here"); int yoursPort = Integer.parseInt(JOptionPane.showInputDialog(this,"Input port(yours) here")); String IP = JOptionPane.showInputDialog(this,"Input IP(other) here"); int port = Integer.parseInt(JOptionPane.showInputDialog(this,"Input port(other) here")); ChessGameFrame mainFrame = new ChessGameFrame(1100, 810,1, PlayerColor.BLUE); GameController gameController = new GameController(mainFrame.getChessboardComponent(), new Chessboard(),1,PlayerColor.BLUE); gameController.setYourIP(yoursIP);gameController.setIP(IP);gameController.setPort(port);gameController.setYourPort(yoursPort); mainFrame.setVisible(true); gameController.getView().paintImmediately(-gameController.getView().getGameFrame().getHeight()/5,-gameController.getView().getGameFrame().getHeight()/10,gameController.getView().getGameFrame().getWidth(),gameController.getView().getGameFrame().getHeight()); if (op==0){ try { gameController.setServer(new ServerSocket(yoursPort)); } catch (IOException ex) { throw new RuntimeException(ex); } }else { try { gameController.setYourSocket(new Socket(IP,port)); Socket socket = gameController.getYourSocket(); InputStream inputStream=socket.getInputStream(); byte[] bytes = new byte[1024]; int len; StringBuilder sb = new StringBuilder(); while ((len = inputStream.read(bytes)) != -1) { sb.append(new String(bytes, 0, len, "UTF-8")); } gameController.doAction(gameController.translateAction(sb)); inputStream.close(); gameController.setYourSocket(new Socket(IP,port)); gameController.setMove(false); } catch (IOException ex) { throw new RuntimeException(ex); } } }); button.setLocation(WIDTH/3+20,HEIGTH/3+360); button.setSize(200, 60); button.setFont(new Font("Rockwell", Font.BOLD, 20)); add(button); } private void addBackground(){ Image img = new ImageIcon("resource/gameBg4.png").getImage(); img=img.getScaledInstance(WIDTH,HEIGTH,Image.SCALE_DEFAULT); ImageIcon imageIcon=new ImageIcon(img); this.background = new JLabel(imageIcon); background.setSize(WIDTH,HEIGTH); background.setLocation(0,0); add(background); } }
import "./login.css"; import { faUser, faLock, faEye, faEyeSlash, } from "@fortawesome/free-solid-svg-icons"; import { FontAwesomeIcon } from "@fortawesome/react-fontawesome"; import React,{ useState } from "react"; import NotificationService from "../../services/notification_service/notification_service"; import AuthService from "../../services/authentication_services/auth_service"; import LoadingSpinner from "../../components/LoadingSpinner/LoadingSpinner"; const {user,lock} = [<FontAwesomeIcon icon={faUser}></FontAwesomeIcon>, <FontAwesomeIcon icon={faLock}></FontAwesomeIcon>]; const eye = <FontAwesomeIcon icon={faEye}></FontAwesomeIcon>; const eyeSlash = <FontAwesomeIcon icon={faEyeSlash}></FontAwesomeIcon>; const Login = () => { const notificationService = new NotificationService(); const authService = new AuthService(); // const formData = { // email: "", // password: "", // }; // states const [formData, setFormData] = useState({email: '', password: ''}); const [isVisible, setVisibility] = useState(false); const [isLoading, setLoading] = useState(false); const showPassword = () => { const password = document.getElementById("password"); if (!isVisible) { password.setAttribute("type", "text"); } else { password.setAttribute("type", "password"); } }; const onEmailInputChange = (event) => { setFormData({...formData, email: event.target.value}); }; const onPasswordInputChange = (event) => { setFormData({...formData, password : event.target.value}); }; const validateEmail = (email) => { var regExp = /^(([^<>()[\]\\.,;:\s@"]+(\.[^<>()[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/; if ( email && String(email) .toLowerCase() .match(regExp) ) { return true; } else { notificationService.showError("Fields Cannot Be Empty"); return false; } }; const validatePassword = (password) => { if (password.length < 4) { notificationService.showError("Invalid Password"); return false; } else { return true; } }; const onFormSubmit = async (e) => { e.preventDefault(); // console.log(formData) if (validateEmail(formData.email) && validatePassword(formData.password)) { setLoading(true); console.log(isLoading); const data = await authService.login(formData); if (typeof data === "undefined") { setLoading(false); } } else { return; } }; return ( <> <div className="main-container"> <div className="background-dark-overlay"> <div className="login-container"> <form onSubmit={onFormSubmit}> <h3>Login</h3> <div className="input-fields"> <div className="input-wrapper email"> <span className="icon">{user}</span> <input type="email" name="email" id="email" placeholder="Email" value={formData.email} onChange={onEmailInputChange} /> </div> <div className="input-wrapper password"> <span className="icon">{lock}</span> <div className="password-container"> <input type="password" name="password" id="password" placeholder="Password" value={formData.password} onChange={onPasswordInputChange} /> <span className="view-password" onClick={() => { setVisibility(!isVisible); showPassword(); }} > {isVisible ? eyeSlash : eye} </span> </div> </div> </div> {isLoading ? <LoadingSpinner/>: <input type="submit" disabled={isLoading} value="Sign in" />} </form> </div> </div> </div> </> ); }; export default Login;
// Copyright (c) Mysten Labs, Inc. // SPDX-License-Identifier: Apache-2.0 import type { WalletWithFeatures, WalletWithRequiredFeatures } from '@mysten/wallet-standard'; import type { ReactNode } from 'react'; import { useRef } from 'react'; import type { StateStorage } from 'zustand/middleware'; import { DEFAULT_PREFERRED_WALLETS, DEFAULT_REQUIRED_FEATURES, DEFAULT_STORAGE, DEFAULT_STORAGE_KEY, } from '../constants/walletDefaults.js'; import { WalletContext } from '../contexts/walletContext.js'; import { useAutoConnectWallet } from '../hooks/wallet/useAutoConnectWallet.js'; import { useUnsafeBurnerWallet } from '../hooks/wallet/useUnsafeBurnerWallet.js'; import { useWalletPropertiesChanged } from '../hooks/wallet/useWalletPropertiesChanged.js'; import { useWalletsChanged } from '../hooks/wallet/useWalletsChanged.js'; import type { ZkSendWalletConfig } from '../hooks/wallet/useZkSendWallet.js'; import { useZkSendWallet } from '../hooks/wallet/useZkSendWallet.js'; import { lightTheme } from '../themes/lightTheme.js'; import type { Theme } from '../themes/themeContract.js'; import { createInMemoryStore } from '../utils/stateStorage.js'; import { getRegisteredWallets } from '../utils/walletUtils.js'; import { createWalletStore } from '../walletStore.js'; import { InjectedThemeStyles } from './styling/InjectedThemeStyles.js'; export type WalletProviderProps = { /** A list of wallets that are sorted to the top of the wallet list, if they are available to connect to. By default, wallets are sorted by the order they are loaded in. */ preferredWallets?: string[]; /** A list of features that are required for the dApp to function. This filters the list of wallets presented to users when selecting a wallet to connect from, ensuring that only wallets that meet the dApps requirements can connect. */ requiredFeatures?: (keyof WalletWithRequiredFeatures['features'])[]; /** Enables the development-only unsafe burner wallet, which can be useful for testing. */ enableUnsafeBurner?: boolean; /** Enables automatically reconnecting to the most recently used wallet account upon mounting. */ autoConnect?: boolean; /** Enables the zkSend wallet */ zkSend?: ZkSendWalletConfig; /** Configures how the most recently connected to wallet account is stored. Set to `null` to disable persisting state entirely. Defaults to using localStorage if it is available. */ storage?: StateStorage | null; /** The key to use to store the most recently connected wallet account. */ storageKey?: string; /** The theme to use for styling UI components. Defaults to using the light theme. */ theme?: Theme | null; children: ReactNode; }; export type { WalletWithFeatures }; export function WalletProvider({ preferredWallets = DEFAULT_PREFERRED_WALLETS, requiredFeatures = DEFAULT_REQUIRED_FEATURES, storage = DEFAULT_STORAGE, storageKey = DEFAULT_STORAGE_KEY, enableUnsafeBurner = false, autoConnect = false, zkSend, theme = lightTheme, children, }: WalletProviderProps) { const storeRef = useRef( createWalletStore({ autoConnectEnabled: autoConnect, wallets: getRegisteredWallets(preferredWallets, requiredFeatures), storage: storage || createInMemoryStore(), storageKey, }), ); return ( <WalletContext.Provider value={storeRef.current}> <WalletConnectionManager preferredWallets={preferredWallets} requiredFeatures={requiredFeatures} enableUnsafeBurner={enableUnsafeBurner} zkSend={zkSend} > {/* TODO: We ideally don't want to inject styles if people aren't using the UI components */} {theme ? <InjectedThemeStyles theme={theme} /> : null} {children} </WalletConnectionManager> </WalletContext.Provider> ); } type WalletConnectionManagerProps = Pick< WalletProviderProps, 'preferredWallets' | 'requiredFeatures' | 'enableUnsafeBurner' | 'zkSend' | 'children' >; function WalletConnectionManager({ preferredWallets = DEFAULT_PREFERRED_WALLETS, requiredFeatures = DEFAULT_REQUIRED_FEATURES, enableUnsafeBurner = false, zkSend, children, }: WalletConnectionManagerProps) { useWalletsChanged(preferredWallets, requiredFeatures); useWalletPropertiesChanged(); useZkSendWallet(zkSend); useUnsafeBurnerWallet(enableUnsafeBurner); useAutoConnectWallet(); return children; }
/** * */ package auctionhouse; import java.util.ArrayList; import java.util.List; import java.util.HashMap; import java.util.SortedSet; import java.util.TreeSet; import java.util.Comparator; import java.util.logging.Logger; /** * @author pbj * */ public class AuctionHouseImp implements AuctionHouse { private static Logger logger = Logger.getLogger("auctionhouse"); private static final String LS = System.lineSeparator(); public List<Buyer> buyers = new ArrayList<Buyer>(); public List<Seller> sellers = new ArrayList<Seller>(); public List<Auctioneer> auctioneers = new ArrayList<Auctioneer>(); public SortedSet<Lot> lots = new TreeSet<>(Comparator.comparing(Lot::getLotNumber)); public HashMap<Integer, List<String>> interestedBuyers = new HashMap<>(); public List<Auction> auctionList = new ArrayList<Auction>(); public Parameters parameters; private String startBanner(String messageName) { return LS + "-------------------------------------------------------------" + LS + "MESSAGE IN: " + messageName + LS + "-------------------------------------------------------------"; } public AuctionHouseImp(Parameters parameters) { this.parameters = parameters; } public Status registerBuyer(String name, String address, String bankAccount, String bankAuthCode) { logger.fine(startBanner("registerBuyer " + name)); Buyer buyer = new Buyer(name, bankAccount, bankAuthCode, address); for (Buyer b : buyers) { if (b.name.equals(name)) { logger.fine(startBanner("registerBuyer " + name + ": FAILED")); return Status.error("The name provided is already in the system"); } } buyers.add(buyer); logger.finer(startBanner(name + ": buyer is registered now")); return Status.OK(); } public Status registerSeller(String name, String address, String bankAccount) { logger.fine(startBanner("registerSeller " + name)); Seller seller = new Seller(name, bankAccount, address); for (Seller s : sellers) { if (s.name.equals(name)) { logger.fine(startBanner("registerSeller " + name + ": FAILED")); return Status.error("The name provided is already in the system"); } } sellers.add(seller); logger.finer(startBanner(name + ": seller is registered now")); return Status.OK(); } public Status addLot(String sellerName, int number, String description, Money reservePrice) { logger.fine(startBanner("addLot " + sellerName + " " + number)); if (getUser(sellerName, "seller") == null) { logger.fine(startBanner("Add lot : FAILED")); return Status.error("The name provided is already in the system"); } if (getLot(number) != null) { logger.fine(startBanner("Adding lot: FAILED")); return Status.error("The Lot Number assigned already exist in the system"); } Lot lot = new Lot(sellerName, number, description, LotStatus.UNSOLD, reservePrice); lots.add(lot); logger.finer(startBanner(number + ": lot is added in the system now")); return Status.OK(); } private User getUser(String user, String type) { switch (type) { case "seller": for (Seller s : sellers) { if (s.name.equals(user)) { return s; } } break; case "buyer": for (Buyer b : buyers) { if (b.name.equals(user)) { return b; } } break; case "auctioneer": for (Auctioneer a : auctioneers) { if (a.name.equals(user)) { return a; } } break; default: return null; } return null; } private Lot getLot(int lotNumber) { for (Lot l : lots) { if (l.getLotNumber() == lotNumber) { return l; } } return null; } public List<CatalogueEntry> viewCatalogue() { logger.fine(startBanner("viewCatalog")); List<CatalogueEntry> catalogue = new ArrayList<CatalogueEntry>(); logger.fine("Catalogue: " + catalogue.toString()); for (Lot l : lots) { catalogue.add(l); } return catalogue; } public Status noteInterest(String buyerName, int lotNumber) { logger.fine(startBanner("noteInterest " + buyerName + " " + lotNumber)); List<String> temp = new ArrayList<>(); if (interestedBuyers.containsKey(lotNumber)) { temp = interestedBuyers.get(lotNumber); temp.add(buyerName); interestedBuyers.put(lotNumber, temp); } else { temp.add(buyerName); interestedBuyers.put(lotNumber, temp); } return Status.OK(); } public Status openAuction(String auctioneerName, String auctioneerAddress, int lotNumber) { logger.fine(startBanner("openAuction " + auctioneerName + " " + lotNumber)); Lot lot = getLot(lotNumber); if (lot == null) { logger.fine(startBanner("Opening Auction: FAILED")); return Status.error("The Lot Doesn't exist in the system"); } Auctioneer auctioneer = new Auctioneer(auctioneerName, auctioneerAddress); auctioneers.add(auctioneer); if (lot.status == LotStatus.UNSOLD) { lot.status = LotStatus.IN_AUCTION; Auction auction = new Auction(lot, "0"); auction.setAuctioneer(auctioneerName); auctionList.add(auction); for (String buyerName : interestedBuyers.get(lotNumber)) { this.parameters.messagingService.auctionOpened(getUser(buyerName, "buyer").getAddress(), lotNumber); } this.parameters.messagingService.auctionOpened(getUser(lot.getSellerName(), "seller").getAddress(), lotNumber); logger.finest(startBanner("openAuction " + auctioneerName + " " + lotNumber +": Success")); return Status.OK(); // SUCCESS } else { logger.fine(startBanner("openAuction " + auctioneerName + " " + lotNumber +": Failed, The lot should be unsold to open Action")); return Status.error("The lot should be unsold to open Action"); } } public Status makeBid(String buyerName, int lotNumber, Money bid) { List<String> temp = new ArrayList<>(); logger.fine(startBanner("makeBid " + buyerName + " " + lotNumber + " " + bid)); Lot lot = getLot(lotNumber); if (lot == null) { logger.fine(startBanner("Make Bid: FAILED")); return Status.error("The Lot Doesn't exist in the system"); } if (lot.status != LotStatus.IN_AUCTION) { return Status.error("Lot is not in Auction"); } if (getUser(buyerName, "buyer") == null) { logger.fine(startBanner("Add lot : FAILED")); return Status.error("The buyer name provided is already in the system"); } for (Auction a : auctionList) { if (a.getLot().getLotNumber() == lotNumber) { if (!bid.lessEqual(a.highestBid.add(this.parameters.increment))) { for (String buyername : interestedBuyers.get(lotNumber)) { if (buyerName.equals(buyername)) continue; this.parameters.messagingService.bidAccepted(getUser(buyername, "buyer").getAddress(), lotNumber, bid); } this.parameters.messagingService .bidAccepted(getUser(a.getLot().getSellerName(), "seller").getAddress(), lotNumber, bid); this.parameters.messagingService.bidAccepted(getUser(a.getAuctioneer(), "auctioneer").getAddress(), lotNumber, bid); if (interestedBuyers.containsKey(lotNumber)) { temp = interestedBuyers.get(lotNumber); temp.add(buyerName); interestedBuyers.put(lotNumber, temp); } else { temp.add(buyerName); interestedBuyers.put(lotNumber, temp); } a.bidderAndBid.put(buyerName, bid); a.highestBid = bid; a.highestBidder = (Buyer) getUser(buyerName, "buyer"); logger.finest(startBanner("Success creating the bid")); return Status.OK(); } else { return Status.error("Bid is lower than highest bid"); } } } return Status.error("Lot doesn't exist"); } public Status closeAuction(String auctioneerName, int lotNumber) { Lot lot = getLot(lotNumber); if (lot.status != LotStatus.IN_AUCTION) { return Status.error("Lot is not in Auction"); } for (Auction a : auctionList) { if (a.getLot().getLotNumber() == lotNumber) { a.setHammerPrice(); // taking the highest bid and make it hammer price Money reservePrice = a.getLot().getReservePrice(); if (reservePrice.lessEqual(a.getHammerPrice())) { Buyer sender = a.getHighestBidder(); Seller receiver = (Seller) getUser(a.getLot().getSellerName(), "seller"); Money hammerWithPremium = a.getHighestBid().addPercent(this.parameters.buyerPremium); // first transfer money to AuctionHouse Bank Account if (this.parameters.bankingService.transfer(sender.getAccount(), sender.getBankAuthCode(), this.parameters.houseBankAccount, hammerWithPremium).kind == Status.Kind.OK) { logger.finest(startBanner("Success taking money off the buyer's account")); for (String buyername : interestedBuyers.get(lotNumber)) { String buyerAddress =getUser(buyername, "buyer").getAddress(); this.parameters.messagingService.lotSold(buyerAddress,lotNumber); } String sellerAddress = getUser(getLot(lotNumber).getSellerName(), "seller").getAddress(); this.parameters.messagingService .lotSold(sellerAddress, lotNumber); //Transferring Money to seller Account from Auction House bank Account Money sellerGain = a.getHighestBid().addPercent(-this.parameters.commission); if (this.parameters.bankingService.transfer(this.parameters.houseBankAccount, this.parameters.houseBankAuthCode, receiver.getAccount(), sellerGain).kind == Status.Kind.OK) { lot.status = LotStatus.SOLD; logger.finest(startBanner("Success sending money to the seller")); return new Status(Status.Kind.SALE); } else { logger.fine(startBanner("Error while taking money from from seller's account")); lot.status = LotStatus.SOLD_PENDING_PAYMENT; return new Status(Status.Kind.SALE_PENDING_PAYMENT); } } else { logger.fine(startBanner("Errow while taking money from buyer's account")); lot.status = LotStatus.SOLD_PENDING_PAYMENT; return new Status(Status.Kind.SALE_PENDING_PAYMENT); } } else { lot.status = LotStatus.UNSOLD; for (String buyername : interestedBuyers.get(lotNumber)) { this.parameters.messagingService.lotUnsold(getUser(buyername, "buyer").getAddress(), lotNumber); } this.parameters.messagingService .lotSold(getUser(getLot(lotNumber).getSellerName(), "seller").getAddress(), lotNumber); return new Status(Status.Kind.NO_SALE); } } } logger.fine(startBanner("closeAuction " + auctioneerName + " " + lotNumber)); return Status.OK(); } }
import Vue from 'vue' import Router from 'vue-router' import Layout from '@/layout' Vue.use(Router) /** * constantRoutes * a base page that does not have permission requirements * all roles can be accessed */ export const constantRoutes = [ { path: '/redirect', component: Layout, hidden: true, children: [ { path: '/redirect/:path(.*)', component: () => import('@/views/redirect/index') } ] }, { path: '/login', component: () => import('@/views/login/index'), hidden: true }, { path: '/auth-redirect', component: () => import('@/views/login/auth-redirect'), hidden: true }, { path: '/404', component: () => import('@/views/error-page/404'), hidden: true }, { path: '/401', component: () => import('@/views/error-page/401'), hidden: true }, { path: '/', component: Layout, redirect: '/dashboard', children: [ { path: 'dashboard', component: () => import('@/views/dashboard/index'), name: 'Dashboard', meta: { title: 'Dashboard', icon: 'dashboard', affix: true } } ] } ] /** * asyncRoutes * the routes that need to be dynamically loaded based on user roles */ export const asyncRoutes = [ { path: '/HR', component: Layout, redirect: '/HR/list', meta: { title: 'HR Management', icon: 'documentation' }, children: [ { path: '/HR/create', component: () => import('@/views/HR/components/create'), name: 'Upload Excel', meta: { title: 'Upload Excel', icon: 'edit' } }, { path: '/HR/edit', component: () => import('@/views/HR/components/edit'), name: 'Data Edit', hidden: true, meta: { title: 'Data Edit', icon: 'edit', activeMenu: '/HR/list' } }, { path: '/HR/list', component: () => import('@/views/HR/components/list'), name: 'Data List', meta: { title: 'Data List', icon: 'list' } } ] }, // 404 page must be placed at the end !!! { path: '*', redirect: '/404', hidden: true } ] const createRouter = () => new Router({ // mode: 'history', // require service support scrollBehavior: () => ({ y: 0 }), routes: constantRoutes }) const router = createRouter() // Detail see: https://github.com/vuejs/vue-router/issues/1234#issuecomment-357941465 export function resetRouter() { const newRouter = createRouter() router.matcher = newRouter.matcher // reset router } export default router
import React, { useState, useEffect } from 'react' import { Link } from 'react-router-dom' import { styles } from "../style" import { navLinks } from '../constants' import { menu, close } from "../assets" const Navbar = () => { const [active, setActive] = useState("") const [toggle, setToggle] = useState(false) return ( <nav className={`${styles.paddingX} w-full flex items-center py-5 fixed top-0 z-20 bg-primary`}> <div className='w-full flex items-center justify-between max-w-7xl mz-auto'> <Link to ="/" className='flex items-center gap-2' onClick={() =>{setActive(""); window.scrollTo(0, 0) }}> <img src="/logo.svg" alt='logo' className='w-9 h-9 object-contain'/> <p className='text-white text-[18px] font-bold cursor-pointer flex'>MAAZ &nbsp; <span className='sm:block hidden'>| React Developer</span></p> </Link> <ul className='list-none hidden sm:flex flex-row gap-10'> {navLinks.map((link) => ( <li key={link.id} className={`${active === link.id ? "text-white" : "text-secondary"} hover:text-white text-[18px] font-medium cursor-pointer`} onClick={() =>{setActive(link.title)}}> <a href={`#${link.id}`}>{link.title}</a> </li> ))} </ul> <div className='sm:hidden flex flex-1 justify-end items-center'> <img src={toggle ? close : menu} alt='menu' className='w-[28px] h-[28px] object-contain cursor-pointer' onClick={() =>setToggle(!toggle) }/> <div className={`${!toggle ? 'hidden' : 'flex'} p-6 black-gradient absolute top-20 right-0 mx-4 my-2 min-w-[140px] z-10 rounded-xl`}> <ul className='list-none flex justify-end items-end flex-col gap-4'> {navLinks.map((link) => ( <li key={link.id} className={`${active === link.id ? "text-white" : "text-secondary"} font-poppins font-medium cursor-pointer text-[16px]`} onClick={() =>{ setToggle(!toggle); setActive(link.title)}}> <a href={`#${link.id}`}>{link.title}</a> </li> ))} </ul> </div> </div> </div> </nav> ) } export default Navbar
# kingdom # ## Definition: ## A kingdom is a group of people ruled by a king. It also refers to the realm or political regions over which a king or other ruler has control and authority. * A kingdom can be of any geographical size. A king might govern a nation or country or only one city. * The term "kingdom" can also refer to a spiritual reign or authority, as in the term "kingdom of God." * God is the ruler of all creation, but the term "kingdom of God" especially refers to his reign and authority over the people who have believed in Jesus and who have submitted to his authority. * The Bible also talks about Satan having a "kingdom" in which he temporarily rules over many things on this earth. His kingdom is evil and is referred to as "darkness." ## Translation Suggestions: ## * When referring to a physical region that is ruled over by a king, the term "kingdom" could be translated as "country (ruled by a king)" or "king's territory" or "region ruled by a king." * In a spiritual sense, "kingdom" could be translated as "ruling" or "reigning" or "controlling" or "governing." * One way to translate "kingdom of priests" might be "spiritual priests who are ruled by God." * The phrase "kingdom of light" could be translated as "God's reign that is good like light" or "when God, who is light, rules people" or "the light and goodness of God's kingdom." It is best to keep the word "light" in this expression since that is a very important term in the Bible. * Note that the term "kingdom" is different from an empire, in which an emperor rules over several countries. (See also: [authority](../kt/authority.md), [king](../other/king.md), [kingdom of God](../kt/kingdomofgod.md), [kingdom of Israel](../other/kingdomofisrael.md), [Judah](../other/judah.md), [Judah](../other/kingdomofjudah.md), [priest](../kt/priest.md)) ## Bible References: ## * [1 Thessalonians 02:10-12](en/tn/1th/help/02/10) * [2 Timothy 04:17-18](en/tn/2ti/help/04/17) * [Colossians 01:13-14](en/tn/col/help/01/13) * [John 18:36-37](en/tn/jhn/help/18/36) * [Mark 03:23-25](en/tn/mrk/help/03/23) * [Matthew 04:7-9](en/tn/mat/help/04/07) * [Matthew 13:18-19](en/tn/mat/help/13/18) * [Matthew 16:27-28](en/tn/mat/help/16/27) * [Revelation 01:9-11](en/tn/rev/help/01/09) ## Examples from the Bible stories: ## * __[13:02](en/tn/obs/help/13/02)__ God said to Moses and the people of Israel, "If you will obey me and keep my covenant, you will be my prized possession, a __kingdom__ of priests, and a holy nation." * __[18:04](en/tn/obs/help/18/04)__ God was angry with Solomon and, as a punishment for Solomon's unfaithfulness, he promised to divide the nation of Israel in two __kingdoms__ after Solomon's death. * __[18:07](en/tn/obs/help/18/07)__ Ten of the tribes of the nation of Israel rebelled against Rehoboam. Only two tribes remained faithful to him. These two tribes became the __kingdom__ of Judah. * __[18:08](en/tn/obs/help/18/08)__ The other ten tribes of the nation of Israel that rebelled against Rehoboam appointed a man named Jeroboam to be their king. They set up their __kingdom__ in the northern part of the land and were called the __kingdom__ of Israel. * __[21:08](en/tn/obs/help/21/08)__ A king is someone who rules over a __kingdom__ and judges the people.
import java.util.Scanner; public class AbrindoContas { public static void main(String[] args) { // Lendo os dados de Entrada: Scanner scanner = new Scanner(System.in); int numeroConta = scanner.nextInt(); scanner.nextLine(); // Consome a quebra de linha após a entrada do número da conta String nomeTitular = scanner.nextLine(); double saldo = scanner.nextDouble(); //TODO: Criar uma instância de "ContaBancaria" com os valores de Entrada. ContaBancaria contaBancaria = new ContaBancaria(numeroConta, nomeTitular, saldo); System.out.println("Informacoes:"); //TODO: Imprimir as informações da conta usando o objeto criado no TODO acima. System.out.println("Conta: " + contaBancaria.numero); System.out.println("Titular: " + contaBancaria.titular); System.out.println("Saldo: R$ " + contaBancaria.saldo); } } class ContaBancaria { int numero; String titular; double saldo; public ContaBancaria(int numero, String titular, double saldo) { this.numero = numero; this.titular = titular; this.saldo = saldo; } }
// Pegando dados do JSON: /* Usando o fetch: fetch('pessoas.json') .then(resposta => resposta.json()) .then(json => carregaElementosNaPagina(json)); */ // Usando o axios: axios('pessoas.json') .then(resposta => carregaElementosNaPagina(resposta.data)); function carregaElementosNaPagina(json) { const table = document.createElement('table'); for (let pessoa of json) { const tr = document.createElement('tr'); let td = document.createElement('td'); td.innerHTML = pessoa.nome; tr.appendChild(td); td = document.createElement('td'); td.innerHTML = pessoa.idade; tr.appendChild(td); td = document.createElement('td'); td.innerHTML = pessoa.salario.toFixed(2); tr.appendChild(td); table.appendChild(tr); } const resultado = document.querySelector('.resultado'); resultado.appendChild(table); }
import React from 'react'; import { Line, ComposedChart, XAxis, YAxis, Tooltip, ResponsiveContainer, Bar, Area, } from 'recharts'; import Formatters from '../../data/modifiers/formatters'; import { WidgetDefinition } from '../../domain/widget'; const COLORS = ['var(--blue-500)', 'var(--green-300)', 'var(--yellow-500)']; type Props = { data: any[]; config: WidgetDefinition['chart']; }; function Chart(props: Props) { try { const { data = [], config } = props; const { xAxis, yAxis, lines = [], areas = [], bars = [] } = config!; const xAxisFormatter = xAxis.format ? (input: any) => Formatters[xAxis.format as keyof typeof Formatters](input) : null; const yAxisFormatter = yAxis?.format ? (input: any) => Formatters[yAxis?.format as keyof typeof Formatters](input) : null; const dataKeys = [...lines, ...areas, ...bars].map((c) => c.dataKey); let maxData = 0; for (const datum of data) { for (const dataKey of dataKeys) { const value = Number(datum[dataKey]); if (value > maxData) { maxData = value; } } } return ( <ResponsiveContainer> <ComposedChart data={data}> <XAxis dataKey={xAxis.dataKey} {...(xAxisFormatter && { tickFormatter: xAxisFormatter })} reversed={xAxis.reversed} /> <YAxis {...(yAxisFormatter && { tickFormatter: yAxisFormatter })} type='number' domain={[0, maxData * 1.1]} /> <Tooltip labelFormatter={xAxisFormatter || Formatters['camelCaseToTitle']} {...(yAxisFormatter && { formatter: yAxisFormatter })} /> {areas.map((area, i) => ( <Area key={area.dataKey} name={area.label || area.dataKey} type='monotone' dataKey={area.dataKey} fill={COLORS[i]} legendType='none' /> ))} {lines.map((line, i) => ( <Line key={line.dataKey} name={line.label || line.dataKey} type='monotone' strokeLinecap='round' strokeWidth={2} dataKey={line.dataKey} stroke={COLORS[i]} dot={false} legendType='none' /> ))} {bars.map((bar, i) => ( <Bar key={bar.dataKey} name={bar.label || bar.dataKey} type='monotone' dataKey={bar.dataKey} legendType='none' fill={COLORS[i]} /> ))} </ComposedChart> </ResponsiveContainer> ); } catch (error) { return <div>{(error as Error).message}</div>; } } export default React.memo(Chart);
package api; import java.io.BufferedReader; import java.io.InputStreamReader; import java.net.HttpURLConnection; import java.net.URL; import java.net.URLEncoder; import java.util.ArrayList; import java.util.List; import org.json.JSONArray; import org.json.JSONObject; public class ApiMain_review { public static void main(String[] args) { try { // API주소 완성 String apiURL = "http://apis.data.go.kr/B552061/AccidentDeath/getRestTrafficAccidentDeath"; apiURL += "?serviceKey=" + URLEncoder.encode("lIiaVHQPSbv8hKaGqyz4QW8vgsxqagt/amPC9Uu4aYvSl4ANX7/2/q1ag1cDx+Oj7dZO0ntuLfO3Fk39fmtfCg==", "UTF-8"); apiURL += "&searchYear=" + URLEncoder.encode("2021", "UTF-8"); apiURL += "&siDo=" + URLEncoder.encode("1100", "UTF-8"); apiURL += "&guGun=" + URLEncoder.encode("1125", "UTF-8"); apiURL += "&type=" + URLEncoder.encode("json", "UTF-8"); apiURL += "&numOfRows=" + URLEncoder.encode("10", "UTF-8"); apiURL += "&pageNo=" + URLEncoder.encode("1", "UTF-8"); // URL 객체 생성(API주소의 형식 검증) URL url = new URL(apiURL); // API주소로 접속 HttpURLConnection con = (HttpURLConnection) url.openConnection(); // GET 방식의 요청임을 처리 con.setRequestMethod("GET"); // GET방식 : 주소창에 파라미터 주렁주렁 매달아 요청하는 방식 // 응답 데이터는 "json" 임을 처리 // 웹 상에서 주고 받는 데이터의 타입 : Content-Type con.setRequestProperty("Content-Type", "application/json; charset=UTF-8"); //[; charset=UTF-8] 생략 가능 // 접속된 API로부터 데이터를 읽어 들일 입력 스트림 생성 // 1. 정상 스트림과 에러 스트림으로 구분해서 생성 // 2. API 입력 스트림은 오직 바이트 입력 스트림만 지원하므로 문자 입력 스트림으로 바꾸는 작업이 필요하다. // 3. 속도 향상을 위해서 Buffer가 내장된 스트림을 생성 BufferedReader reader = null; if(con.getResponseCode() == 200) { reader = new BufferedReader(new InputStreamReader(con.getInputStream())); } else { reader = new BufferedReader(new InputStreamReader(con.getErrorStream())); } // BufferedReader는 readLine 메소드를 지원한다. String line = null; StringBuilder sb = new StringBuilder(); while((line = reader.readLine()) != null) { sb.append(line); } // 이제 API의 응답 데이터는 sb에 저장되어 있다. // System.out.println(sb.toString()); // API의 응답 데이터를 분석하기 위해서 JSONObject로 변환한다. // json 라이브러리 사용을 위해서 Build Path 작업을 수행한다. // JSONObject obj = new JSONObject(sb.toString()); // JSONObject items = obj.getJSONObject("items"); // JSONArray itemList = items.getJSONArray("items"); JSONArray itemList = new JSONObject(sb.toString()) .getJSONObject("items") .getJSONArray("item"); List<Accident_review> list = new ArrayList<Accident_review>(); // accident 9개를 한번에 저장하기 위해 arraylist 사용 for(int i = 0; i<itemList.length(); i++) { // 응답 데이터에서 필요한 데이터를 분석(파싱)한다. JSONObject item = itemList.getJSONObject(i); String occrrncDt = item.getString("occrrnc_dt"); // 4개의 정보가 하나의 데이터가 되기 위해서 Bean이나 Map으로 만들어야 함 String occrrncDayCd = item.getString("occrrnc_day_cd"); // Accident 클래스를 만들어서 4개의 데이터를 저장시켜라 int dthDnvCnt = item.getInt("dth_dnv_cnt"); int injpsnCnt = item.getInt("injpsn_cnt"); // 응답 데이터에서 추출한 데이터를 하나의 객체(Bean)으로 만든다. Accident_review accident = new Accident_review(); accident.setOccrrncDt(occrrncDt); accident.setOccrrncDayCd(occrrncDayCd); accident.setDthDnvCnt(dthDnvCnt); accident.setInjpsnCnt(injpsnCnt); // 객체를 ArrayList엣 저장한다. list.add(accident); // System.out.println("발생월일시 : " + occrrncDt); // System.out.println("발생요일코드 : " + occrrncDayCd); // System.out.println("사망자수 : " + dthDnvCnt); // System.out.println("부상자수 : " + injpsnCnt); // System.out.println("----------"); } } catch(Exception e) { e.printStackTrace(); } } }
import { useContext, useEffect, useRef } from 'react' import { CourseContext } from '../../contexts/Courses/CourseContext' import { AuthContext } from '../../contexts/Users/AuthContext' import toastrNotificationsService from "../../services/toastrNotificationsService" import { ServicesHome } from './ServicesHome' import { ServicesWelcome } from './ServicesWelcome' import { CourseDetails } from './coursesComponents/CourseDetails' import {CoursesTimetableBackgroundImage} from './coursesComponents/CoursesTimetableBackgroundImage' import { CoursesTimetable } from './coursesComponents/CoursesTimetable' import { ServicesDiscount } from './ServicesDiscount' import '../../assets/styles/bootstrap-4.1.2/bootstrap.min.css' import '../../assets/plugins/font-awesome-4.7.0/css/font-awesome.min.css' import '../../assets/plugins/OwlCarousel2-2.2.1/owl.carousel.css' import '../../assets/plugins/OwlCarousel2-2.2.1/owl.theme.default.css' import '../../assets/plugins/OwlCarousel2-2.2.1/animate.css' import '../../assets/plugins/colorbox/colorbox.css' import '../../assets/styles/services.css' import '../../assets/styles/services_responsive.css' export const Services = ({setFocus}) => { const {courses} = useContext(CourseContext); const myDivRef = useRef(null); useEffect(()=> { if (setFocus) { myDivRef.current.scrollIntoView({ behavior: 'smooth' }); myDivRef.current.focus(); } }, [setFocus]); const { auth } = useContext(AuthContext); const isAuthenticated = !!auth.username; return ( <div className="super_container"> {/* Home */} <ServicesHome /> {/* Services */} <div className="services" > <div className="container"> <ServicesWelcome myDivRef = {myDivRef}/> <div className="row services_row_details" > {Object.values(courses) .map((course) => ( <CourseDetails key={course._id} {...course} /> ))} </div> </div> </div> {/* Timetable */} <div className="timetable"> <CoursesTimetableBackgroundImage /> <div className="tt_overlay" /> <div className="container"> <div className="row" > {Object.values(courses).length > 0 && <CoursesTimetable />} </div> </div> </div> {/* Discount */} {!isAuthenticated && <ServicesDiscount />} </div> ); }
''' 338. Counting Bits Easy Given an integer n, return an array ans of length n + 1 such that for each i (0 <= i <= n), ans[i] is the number of 1's in the binary representation of i. Example 1: Input: n = 2 Output: [0,1,1] Explanation: 0 --> 0 1 --> 1 2 --> 10 Example 2: Input: n = 5 Output: [0,1,1,2,1,2] Explanation: 0 --> 0 1 --> 1 2 --> 10 3 --> 11 4 --> 100 5 --> 101 Constraints: 0 <= n <= 105 Follow up: It is very easy to come up with a solution with a runtime of O(n log n). Can you do it in linear time O(n) and possibly in a single pass? Can you do it without using any built-in function (i.e., like __builtin_popcount in C++)? ''' from typing import List import unittest class Solution: ''' space: O(n) time: O(n) ''' def countBits(self, n: int) -> List[int]: result = [0] * (n + 1) for i in range(1, n + 1): result[i] = result[i >> 1] + (i & 1) return result class TestCountBits(unittest.TestCase): def setUp(self): self.sut = Solution() def tearDown(self): pass def test_number(self): test_cases = { 0: [0], 1: [0, 1], 5: [0, 1, 1, 2, 1, 2], } for n in test_cases.keys(): # action actual = self.sut.countBits(n) # asserts self.assertListEqual(actual, test_cases[n]) self.assertEqual(len(actual), n + 1)
import { APIGatewayProxyEvent, APIGatewayProxyResult } from 'aws-lambda' import 'source-map-support/register' import * as AWS from 'aws-sdk' import * as middy from 'middy' import { cors } from 'middy/middlewares' const docClient = new AWS.DynamoDB.DocumentClient() const groupsTable = process.env.GROUPS_TABLE || 'Groups' const imagesTable = process.env.IMAGES_TABLE || 'Images' export const handler = middy(async (event: APIGatewayProxyEvent): Promise<APIGatewayProxyResult> => { console.log('Caller event', event) if (!!event.pathParameters && !!event.pathParameters.groupId) { const groupId = event.pathParameters.groupId const validGroupId = await groupExists(groupId) if (!validGroupId) { return { statusCode: 404, body: JSON.stringify({ error: 'Group does not exist' }) } } const images = await getImagesPerGroup(groupId) return { statusCode: 201, body: JSON.stringify({ items: images }) } } return { statusCode: 404, body: JSON.stringify({ error: 'Unknown error occurred' }) } }) async function groupExists(groupId: string) { const result = await docClient .get({ TableName: groupsTable, Key: { id: groupId } }) .promise() console.log('Get group: ', result) return !!result.Item } async function getImagesPerGroup(groupId: string) { const result = await docClient.query({ TableName: imagesTable, KeyConditionExpression: 'groupId = :groupId', ExpressionAttributeValues: { ':groupId': groupId }, ScanIndexForward: false }).promise() return result.Items } handler.use( cors({ credentials: true }) )
# Map, Filter, Reduce ```js const array = [1,2,3,4,5,6] let newArrayWithMaP = array.map((value, index, array)=>{ return value + 1 }) console.log(newArrayWithMaP) // map makes a new array by performing a certain function on the array and can take 3 argument number index and array ``` ```js let newArrayWithFilter = array.filter((value, index, array)=>{ return value > 1 }) console.log(newArrayWithFilter) // filter makes a new array by performing a filtering the array and can't be done with loops and also can take 3 argument number index and array ``` ```js let newArrayWithReduce = array.reduce((total, currentValue, currentIndex, arr)=>{ return total - currentValue },initialValue) console.log(newArrayWithReduce); // Reduce makes a new array by take 2 value which is the first and the second index values and then perform a calculation on it like in this case substrate and then continue it on the new ones ``` # Memory in Js ```js // Stack (Primitive), Heap (Non-Primitive) // stack have copy // heap have reference ``` # Execution context - ## global execution context - ## functional execution context - ## eval execution context ```js ``` # Lexical scoping ```js // Is that outer function variables are accesable to the inner function but not vice versa // And the sibling inner functions also can't use the other sibling variable ``` # Closure ```js function makeFunc() { const name = "Mozilla"; function displayName() { console.log(name); } return displayName; } I const myFunc = makeFunc(); myFunc(); // It is about if we return a reference of a function in a function so it won't just gona give the executional contex of the returned fuction but the lexical scope of the function which means all the variable which it uses from its parent function ``` # Object Oriented Programming - ## Constructor Function ```js // new keyword use ``` - ## Classes ```js class User { constructor(username, email, password){ this.username = username; this.email = email; this.password = password; } encryptPassword(){ return `${this.password} abc` } } const chai = new User("prince", "princerawatemail","password123") ``` - ## - ## # IIFE ```js (()=>{ })(); semicolen is necessary other vice it will give error ``` # Good to know - ## how return works in functions ```js // if you use {} in forEach or map , filter, reduce or in any function then you have to use return keyword but if you are not using {} then it will automatically return ``` - ## chained functions ```js // you can also do array1.map().map().filter() // this is called function channing which passes the new value to the next function till the last one and then return the final value and stores it ``` - ## implesit scope ```js // its nothing but the scope created when you are doing something without {} ```
//requiring the modules const express = require('express'); const cookieSession = require('cookie-session'); const passport = require('passport'); const authRoutes = require('./routes/auth-routes'); const profileRoutes=require('./routes/profile-routes'); const passportSetup = require('./config/passport-setup'); const mongoose = require('mongoose'); const keys = require('./config/keys'); const app = express(); // set view engine app.set('view engine', 'ejs'); // set up session cookies app.use(cookieSession({ maxAge: 24 * 60 * 60 * 1000, keys: [keys.cookie.encrypt] })); // initialize passport app.use(passport.initialize()); app.use(passport.session()); //using the middlewares app.use(express.static('assets')); app.use(express.static('uploads')); // connect to mongodb mongoose.connect(keys.mongodb.dbURI, () => { console.log('connected to mongodb'); }); // set up routes app.use('/auth', authRoutes); app.use('/profile', profileRoutes); // create home route app.get('/', (req, res) => { res.render('home'); }); app.listen(4000, () => { console.log('app now listening for requests on port 4000'); });
const { body, validationResult } = require("express-validator"); const Item = require("../models/item"); const Category = require("../models/category"); const asyncHandler = require("express-async-handler"); //index exports.index = asyncHandler(async (req, res, next) => { const [ numItems, numCategories ] = await Promise.all([ Item.countDocuments({}).exec(), Category.countDocuments({}).exec(), ]); res.render("index", { title: "Inventory Application", item_count: numItems, category_count: numCategories }); }); //display item_list on GET exports.item_list = asyncHandler(async (req, res, next) => { const allItems = await Item.find().exec(); res.render("item_list", { title: "Item List", item_list: allItems }) }) //create new item with GET exports.item_create_get = asyncHandler(async(req, res, next) => { const allCategories = await Category.find().exec(); res.render("item_form", { title: 'Create Item', categories: allCategories }) }) //create new item on POST exports.item_create_post = [ //Convert the categories to an array: [0] (req, res, next) => { if(!Array.isArray(req.body.category)){ req.body.category = typeof req.body.category === "undefined" ? [] : [req.body.category]; } next(); }, //Validate and sanitize the fields: [1] body("name", "Name must not be empty") .trim() .isLength({min: 1}) .escape(), body("description", "Description must not be empty") .trim() .isLength({min: 1}) .escape(), body("price", "Price must not be empty") .trim() .isLength({min: 1}) .escape(), body("number_in_stock", "Please provide the number of items in stock") .trim() .isLength({min: 1}) .escape(), body("category.*").escape(), //Process request after validation and sanitization: [2] asyncHandler(async(req, res, next) => { //extract the validation errors from a request. const errors = validationResult(req); //Create a item object with escaped and trimmed data const item = new Item( { name: req.body.name, description: req.body.description, price: req.body.price, number_in_stock: req.body.number_in_stock, category: req.body.category } ); if(!errors.isEmpty()){ //There are errors. Render form again with sanitized values/error messages. const allCategories = await Category.find().exec(); // Mark our selected genres as checked. for (const category of allCategories) { if (item.category.includes(category._id)) { category.checked = "true"; } } res.render("item_form", { title: 'Create Item', categories: allCategories }) } else{ //Data from form is valid. Save item. await item.save(); res.redirect(item.url); } }) ] //Display detail for a specific item. exports.item_detail = asyncHandler(async (req, res, next) => { const item = await Item.findById(req.params.id).populate("category").exec(); if(item == null){ //No results const err = new Error("Item not fouond"); err.status = 404; return next(err); } res.render("item_detail", { item: item, title: item.name, genre: item.genre }) })
from sqlalchemy import Column, String, Integer, create_engine from sqlalchemy.orm import relationship from sqlalchemy import ForeignKey from sqlalchemy.orm import registry password = input("Enter you MYSQL password:") engine = create_engine(f'mysql+mysqlconnector://root:{password}@localhost:3306/Projects',echo=True) mapper_registry = registry() #mapper_registry.metadata base = mapper_registry.generate_base() class Project(base): __tablename__ = 'Projects' project_id = Column(Integer, primary_key = True) title = Column(String(length=50)) description = Column(String(length=50)) def __repr__(self): return "<Project (title={0}, description={1})>".format(self.title, self.description) class Task(base): __tablename__ = 'tasks' task_id = Column(Integer, primary_key=True) project_id = Column(Integer, ForeignKey('projects.project_id')) description = Column(String(length=50)) project = relationship("Project") def __repr__(self): return "<Task(description='{0}')>".format(self.description) base.metadata.create_all(engine)
# Импортируем необходимые модули import random import string from colorama import Fore # Модуль для окрашивания вывода в консоль # Например, вывода ошибок красного цвета или паролей зелёного цвета def generate_letters_password(length, quantity): """Функция для генерации паролей вида "Только буквы разного регистра\"""" answer = [] for i in range(quantity): letters = string.ascii_letters # Вписываем необходимые символы для генерации пароля result = ''.join(random.choice(letters) for _ in range(length)) # Генерируем символ answer.append(result) # Добавляем в список сгенерированный символ return answer def generate_alphanumeric_password(length, quantity): """Функция для генерации паролей вида "Буквы разного регистра и цифры\"""" answer = [] for i in range(quantity): letters = string.ascii_letters + string.digits # Вписываем необходимые символы для генерации пароля result = ''.join(random.choice(letters) for _ in range(length)) # Генерируем символ answer.append(result) # Добавляем в список сгенерированный символ return answer def generate_complex_password(length, quantity): """Функция для генерации паролей вида "Буквы, цифры и спецсимволы\"""" answer = [] for i in range(quantity): letters = string.ascii_letters + string.digits + string.punctuation # Вписываем необходимые символы для # генерации пароля result = ''.join(random.choice(letters) for _ in range(length)) # Генерируем символ answer.append(result) # Добавляем в список сгенерированный символ return answer def router_password_generate(length, pass_type, quantity): """Функция определяющая какой тип пароля выбрал пользователь""" if pass_type == "1": # Тип "Только буквы разного регистра" return generate_letters_password(length, quantity) elif pass_type == "2": # Тип "Буквы разного регистра и цифры" return generate_alphanumeric_password(length, quantity) elif pass_type == "3": # Тип "Буквы, цифры и спецсимволы" return generate_complex_password(length, quantity) else: # Вывод ошибки return Fore.RED + 'Произошла ошибка!' def main(): """Главная функция выполняющая роль соединителя кода в одно целое""" try: # Если код работает без ошибок, то код переходит в блок "try" print("Добро пожаловать в Генератор Сложных Паролей!") print("У нас есть несколько типов паролей, которые мы можем создать:") possible_commands = { # Словарь необходимый для вывода возможных команд "1": "Только буквы разного регистра", "2": "Буквы разного регистра и цифры", "3": "Буквы, цифры и спецсимволы" } for key, value in possible_commands.items(): print(f'{key}: {value}') # Вывод словаря с командами user_choice = input('Введите тип пароля (1-3): ') # Ввод типа пароля if user_choice in possible_commands: # Проверка на корректность ввода long = int(input("Введите длину пароля (от 4 до 30 символов): ")) # Ввод длины пароля quantity = int(input("Введите количество генераций паролей (не больше 40): ")) # Ввод количества # генерация пароля if 4 <= long <= 30 and 1 <= quantity <= 40: # Проверка на корректность ввода password = router_password_generate(long, user_choice, quantity) print("Сгенерированные пароли:") for i in password: print(Fore.GREEN + i) # Вывод сгенерированный паролей else: # Выбор типа ошибки if not 4 <= long <= 30: print(Fore.RED + "Длина не подходит под нужные параметры!") if not 1 <= quantity <= 40: print(Fore.RED + "Количество генераций задано неправильно!") else: # Вывод ошибки print(Fore.RED + 'Такой команды нет в списке!') except KeyboardInterrupt: """Блок "except" запускается когда пользователь досрочно закрывает программу. Тип ошибки KeyboardInterrupt""" print(Fore.RED + 'Преждевременный выход из программы') # Вывод сообщения заменяющего ошибку досрочного # закрытия программы if __name__ == '__main__': # Этот блок кода выполняет функцию точки входа в программу """Конструкция "if name == 'main':" используется, чтобы определить, выполняется ли файл напрямую как основной скрипт, или же он импортируется как модуль, и в зависимости от этого выполнить соответствующий код или действия.""" main() # Запускаем главную функцию "main"
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you 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.apache.flink.table.store.file.utils; import org.apache.flink.connector.file.src.FileSourceSplit; import org.apache.flink.connector.file.src.reader.BulkFormat; import org.apache.flink.table.data.RowData; import org.apache.flink.table.store.file.KeyValue; import org.apache.flink.table.store.file.predicate.Predicate; import org.apache.flink.table.store.file.schema.DataField; import org.apache.flink.table.store.file.schema.KeyValueFieldsExtractor; import org.apache.flink.table.store.file.schema.RowDataType; import org.apache.flink.table.store.file.schema.SchemaEvolutionUtil; import org.apache.flink.table.store.file.schema.TableSchema; import org.apache.flink.table.store.format.FileFormat; import org.apache.flink.table.store.utils.Projection; import org.apache.flink.table.types.logical.RowType; import javax.annotation.Nullable; import java.util.List; /** Class with index mapping and bulk format. */ public class BulkFormatMapping { @Nullable private final int[] indexMapping; private final BulkFormat<RowData, FileSourceSplit> bulkFormat; public BulkFormatMapping(int[] indexMapping, BulkFormat<RowData, FileSourceSplit> bulkFormat) { this.indexMapping = indexMapping; this.bulkFormat = bulkFormat; } @Nullable public int[] getIndexMapping() { return indexMapping; } public BulkFormat<RowData, FileSourceSplit> getReaderFactory() { return bulkFormat; } public static BulkFormatMappingBuilder newBuilder( FileFormat fileFormat, KeyValueFieldsExtractor extractor, int[][] keyProjection, int[][] valueProjection, @Nullable List<Predicate> filters) { return new BulkFormatMappingBuilder( fileFormat, extractor, keyProjection, valueProjection, filters); } /** Builder to build {@link BulkFormatMapping}. */ public static class BulkFormatMappingBuilder { private final FileFormat fileFormat; private final KeyValueFieldsExtractor extractor; private final int[][] keyProjection; private final int[][] valueProjection; @Nullable private final List<Predicate> filters; private BulkFormatMappingBuilder( FileFormat fileFormat, KeyValueFieldsExtractor extractor, int[][] keyProjection, int[][] valueProjection, @Nullable List<Predicate> filters) { this.fileFormat = fileFormat; this.extractor = extractor; this.keyProjection = keyProjection; this.valueProjection = valueProjection; this.filters = filters; } public BulkFormatMapping build(TableSchema tableSchema, TableSchema dataSchema) { List<DataField> tableKeyFields = extractor.keyFields(tableSchema); List<DataField> tableValueFields = extractor.valueFields(tableSchema); int[][] tableProjection = KeyValue.project(keyProjection, valueProjection, tableKeyFields.size()); List<DataField> dataKeyFields = extractor.keyFields(dataSchema); List<DataField> dataValueFields = extractor.valueFields(dataSchema); RowType keyType = RowDataType.toRowType(false, dataKeyFields); RowType valueType = RowDataType.toRowType(false, dataValueFields); RowType dataRecordType = KeyValue.schema(keyType, valueType); int[][] dataKeyProjection = SchemaEvolutionUtil.createDataProjection( tableKeyFields, dataKeyFields, keyProjection); int[][] dataValueProjection = SchemaEvolutionUtil.createDataProjection( tableValueFields, dataValueFields, valueProjection); int[][] dataProjection = KeyValue.project(dataKeyProjection, dataValueProjection, dataKeyFields.size()); /** * We need to create index mapping on projection instead of key and value separately * here, for example * * <ul> * <li>the table key fields: 1->d, 3->a, 4->b, 5->c * <li>the data key fields: 1->a, 2->b, 3->c * </ul> * * The value fields of table and data are 0->value_count, the key and value projections * are as follows * * <ul> * <li>table key projection: [0, 1, 2, 3], value projection: [0], data projection: [0, * 1, 2, 3, 4, 5, 6] which 4/5 is seq/kind and 6 is value * <li>data key projection: [0, 1, 2], value projection: [0], data projection: [0, 1, * 2, 3, 4, 5] where 3/4 is seq/kind and 5 is value * </ul> * * We will get value index mapping null fro above and we can't create projection index * mapping based on key and value index mapping any more. */ int[] indexMapping = SchemaEvolutionUtil.createIndexMapping( Projection.of(tableProjection).toTopLevelIndexes(), tableKeyFields, tableValueFields, Projection.of(dataProjection).toTopLevelIndexes(), dataKeyFields, dataValueFields); List<Predicate> dataFilters = tableSchema.id() == dataSchema.id() ? filters : SchemaEvolutionUtil.createDataFilters( tableSchema.fields(), dataSchema.fields(), filters); return new BulkFormatMapping( indexMapping, fileFormat.createReaderFactory(dataRecordType, dataProjection, dataFilters)); } } }
#Hoppe Functions # DA ---------------------------------------------------------------------- # ACTUALS dp_close_actuals <- function(tw){ # cost_centers_data. ccdata <- openxlsx::read.xlsx("datacc_da.xlsx", "hist_raw") %>% as_tibble() %>% janitor::clean_names() samort <- openxlsx::read.xlsx("datacc_da.xlsx", "samort") %>% as_tibble() %>% janitor::clean_names() %>% mutate(period = as.Date(period, origin = "1899-12-30")) %>% mutate(value = abs(value)) %>% mutate(period = as.yearmon(period)) %>% select(-cost_center) %>% mutate(s_description = case_when(str_detect(description,"Tool Connect")~"Tool Connect", str_detect(description,"Connected Product Integration")~"Connected Product Integration", str_detect(description,"Dewalt Connector")~"Dewalt Connector", str_detect(description,"HTAS Enhancements")~"HTAS Enhancements", str_detect(description,"LDMs")~"Laser Distance Measures", str_detect(description,"PTE Enhancements")~"PTE Enhancements", str_detect(description,"Rotary")~"Rotary Laser", str_detect(description,"All Purpose Light")~"All Purpose Light", str_detect(description,"Universal Serial")~"Universal Serial Number", TRUE ~ as.character("Other projects"))) %>% mutate(category = "Soft.Amort") %>% unite("category", c(category, s_description), sep = "/") %>% relocate(.before = period, value) %>% group_by(category, period) %>% summarise(value = sum(value),.groups = "drop") %>% filter(period <= tw) # mutate(period = lubridate::month(period))%>% # pivot_wider(names_from = period, values_from = value, values_fn = sum) # fix_assets clearing <- ccdata %>% filter(grepl("C.I.P.", name_of_offsetting_account)) %>% select(cost_element, cost_element_name, period,val_in_rep_cur) %>% rename(clearing_account = val_in_rep_cur) # tidy_actuals. actuals <- ccdata %>% filter(!cost_element %in% c("1817400","1919350","5672215")) %>% mutate(cost_element_name = ifelse(cost_element_name == "UTILITY TELEPHONE" & val_in_rep_cur > 5000, name_of_offsetting_account, cost_element_name)) %>% group_by(cost_element, cost_element_name, period) %>% summarise(val_in_rep_cur = sum(val_in_rep_cur), .groups = "drop") %>% left_join(clearing, by = c("cost_element", "cost_element_name", "period")) %>% ungroup() %>% replace_na(list(val_in_rep_cur = 0, clearing_account = 0)) %>% mutate(period = as.numeric(period)) %>% mutate(date = make_date(year = year(today()), month = period, day = 1L)) %>% mutate(period = as.yearmon(date)) %>% select(-date) %>% rename(actual = val_in_rep_cur) %>% mutate(gross = actual - clearing_account) %>% mutate(category =case_when(str_detect(cost_element_name,"EMP BEN")~"C&B", str_detect(cost_element_name,"PR TAXES")~"C&B", str_detect(cost_element_name,"WAGE")~"C&B", # str_detect(cost_element_name,"DEMO")~"Demo Tools - FG Stock", str_detect(cost_element_name,"DEMO")~"Demo Tools", str_detect(cost_element_name,"OS FEE LABOR")~"Professional Fees - Globant LLC", str_detect(cost_element_name,"OS FEE GENERAL")~"Services Fees - Cambridge Sharpe", # str_detect(cost_element_name,"PROMO SPECIAL P")~"Promo Services", str_detect(cost_element_name,"OS FEE RECRUIT")~"Recruiting", str_detect(cost_element_name,"RENT BUILD")~"Rent", str_detect(cost_element_name,"AMORTIZ SOFTW")~"Software Amortization", str_detect(cost_element_name,"MATL PROTO")~"Supplies", str_detect(cost_element_name,"OS FEE LEGAL GEN")~"Supplies", str_detect(cost_element_name,"OTH EXP MISC")~"Supplies", str_detect(cost_element_name,"SUPPLIES")~"Supplies", str_detect(cost_element_name,"T&E")~"T&E", str_detect(cost_element_name,"UTILITY TELEP")~"Telephone", str_detect(cost_element_name,"EMP DEV SHOW EXHIBIT")~"Supplies", str_detect(cost_element_name,"HAMILTON MANU")~"Gyro Development - Didio Design", TRUE ~ as.character("Others"))) %>% relocate(.before = cost_element, category ) # summarized actuals by category. resumen_actuals <- actuals %>% group_by(category, period) %>% summarise(gross = sum(gross),.groups="drop") %>% rename(value = gross) %>% filter(!grepl("Software Amort",category)) %>% bind_rows(samort) # summarized capitalization. resumen_capitalized <- actuals %>% group_by(category, period) %>% mutate(category = "Capitalized") %>% summarise(clearing_account = sum(clearing_account),.groups="drop") %>% rename(value = clearing_account) detailed <- resumen_actuals %>% bind_rows(resumen_capitalized) %>% mutate(period = as.Date(period, origin = "1899-12-30")) %>% mutate(period = as.yearmon(period)) %>% mutate(quarter = quarter(period)) %>% mutate(quarter = paste0("Q",quarter)) %>% mutate(type = "actuals") %>% filter(period <= all_of(tw)) monthly <- detailed %>% select(-quarter) %>% pivot_wider(names_from = period, values_from = value, values_fn = sum) %>% mutate_if(~ any(is.na(.)),~ if_else(is.na(.),0,.)) quarterly <- detailed %>% select(-period, -type) %>% pivot_wider(names_from = quarter, values_from = value, values_fn = sum) %>% mutate_if(~ any(is.na(.)),~ if_else(is.na(.),0,.)) overview = monthly %>% left_join(quarterly, by = "category") %>% mutate_if(~ any(is.na(.)),~ if_else(is.na(.),0,.)) return(list(raw_cc = ccdata, fixed_assets = clearing, actuals = actuals, detailed = detailed, # monthly = monthly, # quarterly = quarterly, overview = overview)) } # OPlan dp_op_plan <- function(tw){ # detailed detailed <- openxlsx::read.xlsx("datacc_da.xlsx", "OP") %>% as_tibble() %>% janitor::clean_names() %>% mutate(period = as.Date(period, origin = "1899-12-30")) %>% mutate(period = as.yearmon(period)) %>% mutate(quarter = quarter(period)) %>% mutate(quarter = paste0("Q",quarter)) %>% mutate(type = "op") %>% filter(period <= all_of(tw)) # monthly monthly <- detailed %>% select(-quarter) %>% pivot_wider(names_from = period, values_from = value) # quarterly quarterly <- detailed %>% select(-period, -type) %>% pivot_wider(names_from = quarter, values_from = value, values_fn = sum) # mutate(full_year = rowSums(select(., -category))) overview = monthly %>% left_join(quarterly, by = "category") return(list( detailed = detailed, overview = overview)) } # Forecast dp_fcast <- function(tw){ # detailed detailed <- openxlsx::read.xlsx("datacc_da.xlsx", "F7") %>% as_tibble() %>% janitor::clean_names() %>% mutate(period = as.Date(period, origin = "1899-12-30")) %>% mutate(period = as.yearmon(period)) %>% mutate(quarter = quarter(period)) %>% mutate(quarter = paste0("Q",quarter)) %>% mutate(type = "fcast") %>% filter(period <= all_of(tw)) # monthly monthly <- detailed %>% select(-quarter) %>% pivot_wider(names_from = period, values_from = value) # quarterly quarterly <- detailed %>% select(-period, -type) %>% pivot_wider(names_from = quarter, values_from = value, values_fn = sum) # mutate(full_year = rowSums(select(., -category))) overview = monthly %>% left_join(quarterly, by = "category") return(list( detailed = detailed, overview = overview)) } # IoT --------------------------------------------------------------------- # ACTUALS iot_close_actuals <- function(tw){ # cost_centers_data. ccdata <- openxlsx::read.xlsx("datacc_iot.xlsx", "hist_raw") %>% as_tibble() %>% janitor::clean_names() %>% filter(cost_element != 5363840) # tidy_actuals. actuals <- ccdata %>% mutate(cost_element_name = ifelse(cost_element_name == "UTILITY TELEPHONE" & val_in_rep_cur > 5000, name_of_offsetting_account, cost_element_name)) %>% mutate(cost_element_name = ifelse(cost_element_name == "UTILITY TELEPHONE" & val_in_rep_cur < -5000, name_of_offsetting_account, cost_element_name)) %>% group_by(cost_element, cost_element_name, period) %>% summarise(val_in_rep_cur = sum(val_in_rep_cur), .groups = "drop") %>% ungroup() %>% replace_na(list(val_in_rep_cur = 0)) %>% mutate(period = as.numeric(period)) %>% mutate(date = make_date(year = year(today()), month = period, day = 1L)) %>% mutate(period = as.yearmon(date)) %>% select(-date) %>% rename(actual = val_in_rep_cur) %>% mutate(category =case_when(str_detect(cost_element_name,"EMP BEN")~"C&B", str_detect(cost_element_name,"PR TAXE")~"C&B", str_detect(cost_element_name,"WAGE")~"C&B", # str_detect(cost_element_name,"DEMO")~"Demo Tools - FG Stock", str_detect(cost_element_name,"DEMO")~"Demo Tools", str_detect(cost_element_name,"OS FEE RECRUIT")~"Recruiting", str_detect(cost_element_name,"RENT BUILD")~"Rent", str_detect(cost_element_name,"AMORTIZ SOFTW")~"Software Amortization", str_detect(cost_element_name,"MATL PROTO")~"Cloud Usage and Support - Amazon Web Services", str_detect(cost_element_name,"OS FEE LEGAL GEN")~"Supplies", str_detect(cost_element_name,"SUPPLIES")~"Supplies", str_detect(cost_element_name,"T&E")~"T&E", str_detect(cost_element_name,"UTILITY TELEP")~"Telephone", str_detect(cost_element_name,"OS FEE GENERAL")~"IoT Cloud Service - Software AG", str_detect(cost_element_name,"ZIGATTA")~"ConsumerApp - Zigatta", # ON RAW - KSB1 inputted --- check uot reference file + Accruels Sharepoint : str_detect(cost_element_name,"Software Engineering - Infotech Prism")~"Software Engineering - Infotech Prism", str_detect(cost_element_name,"IoT Cloud Service - Software AG")~"IoT Cloud Service - Software AG", str_detect(cost_element_name,"Cloud Usage and Support - AWS")~"Cloud Usage and Support - Amazon Web Services", str_detect(cost_element_name,"ConsumerApp - Zigatta")~"ConsumerApp - Zigatta", TRUE ~ as.character("Others"))) %>% relocate(.before = cost_element, category ) # summarized actuals by category. resumen_actuals <- actuals %>% group_by(category, period) %>% summarise(actual = sum(actual),.groups="drop") %>% rename(value = actual) detailed <- resumen_actuals %>% mutate(period = as.Date(period, origin = "1899-12-30")) %>% mutate(period = as.yearmon(period)) %>% mutate(quarter = quarter(period)) %>% mutate(quarter = paste0("Q",quarter)) %>% mutate(type = "actuals") %>% filter(period <= all_of(tw)) monthly <- detailed %>% select(-quarter) %>% pivot_wider(names_from = period, values_from = value, values_fn = sum) %>% mutate_if(~ any(is.na(.)),~ if_else(is.na(.),0,.)) quarterly <- detailed %>% select(-period, -type) %>% pivot_wider(names_from = quarter, values_from = value, values_fn = sum) %>% mutate_if(~ any(is.na(.)),~ if_else(is.na(.),0,.)) overview = monthly %>% left_join(quarterly, by = "category") %>% mutate_if(~ any(is.na(.)),~ if_else(is.na(.),0,.)) return(list(raw_cc = ccdata, actuals = actuals, detailed = detailed, overview = overview)) } # OPlan iot_op_plan <- function(tw){ # detailed detailed <- openxlsx::read.xlsx("datacc_iot.xlsx", "OP") %>% as_tibble() %>% janitor::clean_names() %>% mutate(period = as.Date(period, origin = "1899-12-30")) %>% mutate(period = as.yearmon(period)) %>% mutate(quarter = quarter(period)) %>% mutate(quarter = paste0("Q",quarter)) %>% mutate(type = "op") %>% filter(period <= all_of(tw)) # monthly monthly <- detailed %>% select(-quarter) %>% pivot_wider(names_from = period, values_from = value) # quarterly quarterly <- detailed %>% select(-period, -type) %>% pivot_wider(names_from = quarter, values_from = value, values_fn = sum) # mutate(full_year = rowSums(select(., -category))) overview = monthly %>% left_join(quarterly, by = "category") return(list( detailed = detailed, # monthly = monthly, # quarterly = quarterly, overview = overview)) } # Forecast iot_fcast <- function(tw){ # detailed detailed <- openxlsx::read.xlsx("datacc_iot.xlsx", "F7") %>% as_tibble() %>% janitor::clean_names() %>% mutate(period = as.Date(period, origin = "1899-12-30")) %>% mutate(category = ifelse(str_detect(category,"PSD"), "Product Service Technology Upgrade", category)) %>% group_by(category, period) %>% summarise(value = sum(value), .groups = "drop") %>% mutate(period = as.yearmon(period)) %>% mutate(quarter = quarter(period)) %>% mutate(quarter = paste0("Q",quarter)) %>% mutate(type = "fcast") %>% filter(period <= all_of(tw)) # monthly monthly <- detailed %>% select(-quarter) %>% pivot_wider(names_from = period, values_from = value) # quarterly quarterly <- detailed %>% select(-period, -type) %>% pivot_wider(names_from = quarter, values_from = value, values_fn = sum) # mutate(full_year = rowSums(select(., -category))) overview = monthly %>% left_join(quarterly, by = "category") return(list( detailed = detailed, # monthly = monthly, # quarterly = quarterly, overview = overview)) } # Time Windows ------------------------------------------------------------ # MTD mtd_output_da <- function(tw){ MTD= dp_fcast(tw)$detailed %>% bind_rows(dp_close_actuals(tw)$detailed) %>% bind_rows(dp_op_plan(tw)$detailed) %>% filter(period == tw) %>% select(category,type,value) %>% pivot_wider(names_from = type, values_from = value, values_fn = sum) %>% rename(MTD_forecast = fcast, MTD_actuals = actuals, MTD_OP =op) %>% select(category, MTD_actuals,MTD_forecast,MTD_OP) %>% mutate_if(~ any(is.na(.)),~ if_else(is.na(.),0,.)) %>% mutate(MTD_actuals = MTD_actuals/1, MTD_forecast = MTD_forecast/1, MTD_OP = MTD_OP/1) %>% mutate(MTD_VF = MTD_actuals-MTD_forecast, MTD_VOP = MTD_actuals-MTD_OP) return(MTD) } # QTD qtd_output_da <- function(tw, q){ QTD = dp_fcast(tw)$detailed %>% bind_rows(dp_close_actuals(tw)$detailed) %>% bind_rows(dp_op_plan(tw)$detailed) %>% filter(period <= tw) %>% filter(quarter == q) %>% select(category,type,value) %>% pivot_wider(names_from = type, values_from = value, values_fn = sum) %>% rename(QTD_forecast = fcast, QTD_actuals = actuals, QTD_OP =op) %>% select(category, QTD_actuals,QTD_forecast,QTD_OP) %>% mutate_if(~ any(is.na(.)),~ if_else(is.na(.),0,.)) %>% mutate(QTD_actuals = QTD_actuals/1, QTD_forecast = QTD_forecast/1, QTD_OP = QTD_OP/1) %>% mutate(QTD_VF = QTD_actuals-QTD_forecast, QTD_VOP = QTD_actuals-QTD_OP) return(QTD) } # YTD ytd_output_da <- function(tw){ YTD = dp_fcast(tw)$detailed %>% bind_rows(dp_close_actuals(tw)$detailed) %>% bind_rows(dp_op_plan(tw)$detailed) %>% filter(period <= tw) %>% select(category,type,value) %>% pivot_wider(names_from = type, values_from = value, values_fn = sum) %>% rename(YTD_forecast = fcast, YTD_actuals = actuals, YTD_OP =op) %>% select(category, YTD_actuals,YTD_forecast,YTD_OP) %>% mutate_if(~ any(is.na(.)),~ if_else(is.na(.),0,.)) %>% mutate(YTD_actuals = YTD_actuals/1, YTD_forecast = YTD_forecast/1, YTD_OP = YTD_OP/1) %>% mutate(YTD_VF = YTD_actuals-YTD_forecast, YTD_VOP = YTD_actuals-YTD_OP) return(YTD) } # MTD mtd_output_iot <- function(tw){ MTD= iot_fcast(tw)$detailed %>% bind_rows(iot_close_actuals(tw)$detailed) %>% bind_rows(iot_op_plan(tw)$detailed) %>% filter(period == tw) %>% select(category,type,value) %>% pivot_wider(names_from = type, values_from = value, values_fn = sum) %>% rename(MTD_forecast = fcast, MTD_actuals = actuals, MTD_OP =op) %>% select(category, MTD_actuals,MTD_forecast,MTD_OP) %>% mutate_if(~ any(is.na(.)),~ if_else(is.na(.),0,.)) %>% mutate(MTD_actuals = MTD_actuals/1, MTD_forecast = MTD_forecast/1, MTD_OP = MTD_OP/1) %>% mutate(MTD_VF = MTD_actuals-MTD_forecast, MTD_VOP = MTD_actuals-MTD_OP) return(MTD) } # QTD qtd_output_iot <- function(tw, q){ QTD = iot_fcast(tw)$detailed %>% bind_rows(iot_close_actuals(tw)$detailed) %>% bind_rows(iot_op_plan(tw)$detailed) %>% filter(period <= tw) %>% filter(quarter == q) %>% select(category,type,value) %>% pivot_wider(names_from = type, values_from = value, values_fn = sum) %>% rename(QTD_forecast = fcast, QTD_actuals = actuals, QTD_OP =op) %>% select(category, QTD_actuals,QTD_forecast,QTD_OP) %>% mutate_if(~ any(is.na(.)),~ if_else(is.na(.),0,.)) %>% mutate(QTD_actuals = QTD_actuals/1, QTD_forecast = QTD_forecast/1, QTD_OP = QTD_OP/1) %>% mutate(QTD_VF = QTD_actuals-QTD_forecast, QTD_VOP = QTD_actuals-QTD_OP) return(QTD) } # YTD ytd_output_iot <- function(tw){ YTD = iot_fcast(tw)$detailed %>% bind_rows(iot_close_actuals(tw)$detailed) %>% bind_rows(iot_op_plan(tw)$detailed) %>% filter(period <= tw) %>% select(category,type,value) %>% pivot_wider(names_from = type, values_from = value, values_fn = sum) %>% rename(YTD_forecast = fcast, YTD_actuals = actuals, YTD_OP =op) %>% select(category, YTD_actuals,YTD_forecast,YTD_OP) %>% mutate_if(~ any(is.na(.)),~ if_else(is.na(.),0,.)) %>% mutate(YTD_actuals = YTD_actuals/1, YTD_forecast = YTD_forecast/1, YTD_OP = YTD_OP/1) %>% mutate(YTD_VF = YTD_actuals-YTD_forecast, YTD_VOP = YTD_actuals-YTD_OP) return(YTD) }
import { forwardRef } from 'react'; import { getClassName } from '~utils/helpers'; import s from './Button.module.css'; interface ButtonProps extends React.ComponentProps<'button'> { variant: 'filled' | 'filledTonal' size: 'small' | 'large' active?: boolean } export const Button = forwardRef<HTMLButtonElement, ButtonProps>( ({ variant, size, active = false, children, ...otherProps }, ref) => ( <button {...otherProps} ref={ref} className={getClassName( s.button, s[size], s[variant], { [s.active]: active, }, )} > {children} </button> ), );
--- title: "Precall and Postcall" authors: ["Chengyu Song"] date: "2009-06-14" tags: - "qebek" - "sebek" - "qemu" - "windows" --- When using hooking technology to intercept system calls, there are two different places to collect information: before the original function is called (precall) and after the original function returns (postcall). For example, in Sebek Win32 client, when callback function OnZwReadFile is called, it first calls the original function s\_fnZwReadFile, after the original function returns, it checks whether the original call succeeds,  if does, it then calls the data collection function LogIfStdHandle: ``` status = s\_fnZwReadFile(FileHandle, Event, ApcRoutine, ApcContext, IoStatusBlock, Buffer, Length, ByteOffset, Key); if(status == STATUS\_SUCCESS) LogIfStdHandle(FileHandle, Buffer, Length); ``` If the hook is done under Windows, or any other operating systems, breaking at precall and postcall is equally difficult, because the callback function is directly insert into the calling chain. In QEMU, supporting precall is easy and such mechanism has already been added to Qebek.  However, since the callback function is executed outside the VM, a ret instruction won't naturally be trapped into the postcall procedure. As a result, I need to find another way.  Because Qebek will check the target EIP every time EIP is about to change, the simplest way to support postcall is to add the return address to the check list. This idea has been used in Ether\[1\] and proved to be feasible. The following code is a demo on hooking NtReadFile in Qebek (the full version can be found in the public [svn](https://projects.honeynet.org/sebek/browser/virtualization/qebek/trunk) ) ``` // NtReadFile pre call if(eip == NtReadFile) { // get file handle, buffer & buffer size from stack qebek\_read\_ulong(env, env->regs\[R\_ESP\] + 4, &ReadHandle); qebek\_read\_ulong(env, env->regs\[R\_ESP\] + 4 \* 6, &ReadBuffer); qebek\_read\_ulong(env, env->regs\[R\_ESP\] + 4 \* 7, &ReadSize); // set return address, so the VM will break when returne <script src="/modules/tinymce/tinymce/jscripts/tiny_mce/themes/advanced/langs/en.js" type="text/javascript"><!--mce:0--></script> d qebek\_read\_ulong(env, env->regs\[R\_ESP\], &NtReadFilePost); } // NtReadFile post call else if(eip == NtReadFilePost) { qemu\_printf("ReadPost\\n"); // if succeed if(env->regs\[R\_EAX\] == 0) OnNtReadWriteFile(env, ReadHandle, ReadBuffer, ReadSize); NtReadFilePost = 0; //clear the break point } ``` This code works well as a demo, but has obviously drawbacks: 1) when the system calls required to be hooked increases, the performance penalty of if-else structure will be unacceptable; 2) if the system call is reenterable, the postcall break point will mess up; 3) if there is context swith during the system call, which is true according to the test, the collected informaiton will mess up. So next week I'll mainly focus on improving the hook infrastucture. \[1\] Dinaburg, A., Royal, P., Sharif, M., Lee, W.: Ether: malware analysis via hardware virtualization extensions. In: CCS '08: Proceedings of the 15th ACM Conference on Computer and Communications Security, New York, NY, USA, ACM (2008) 51-62.
import { Injectable } from '@angular/core'; import { InMemoryDbService } from 'angular-in-memory-web-api'; import { chardetailInter } from './character-detail/chardetailInterface'; import { gadgetdetailinter } from './gadget-detail/gadgetdetailinter'; import { galleryInter } from './gallery/galleryInter'; @Injectable({ providedIn: 'root', }) export class InmemorycharacterService implements InMemoryDbService { createDb() { const characters = [ { name: 'Nobita', id: 1, height: 4.3, weight: 40 }, { name: 'Sunio', id: 2, height: 3.4, weight: 30 }, { name: 'Shizhuka', id: 3, height: 4.2, weight: 35 }, { name: 'Jeean', id: 4, height: 5, weight: 500 }, ]; const gadgets = [ { id: 1, name: 'Bamboocopter', color: 'Red', }, { id: 2, name: 'Time Machine', color: 'Red', }, { id: 3, name: 'Anywhere Door', color: 'Red', }, { id: 4, name: 'Big Light', color: 'Red', }, ]; const gallery = [ { imageUrl: 'https://wallpapers.com/images/high/flying-and-winking-doraemon-iphone-omiax63ve36g8ls3.webp', id: 1, }, { imageUrl: 'https://wallpapers.com/images/high/cute-nobita-watching-tv-with-doraemon-cby61fad07nqlt0t.webp', id: 2, }, { imageUrl: 'https://wallpapers.com/images/high/room-doraemon-4k-v1yj0ac84uiv8j5d.webp', id: 3, }, { imageUrl: 'https://wallpapers.com/images/high/doraemon-anime-series-jyi51qfzj7w2aq1e.webp', id: 4, }, { imageUrl: 'https://wallpapers.com/images/high/crazy-cartoon-8zlj1r5h52u8pvge.webp', id: 5, }, { imageUrl: 'https://wallpapers.com/images/high/doraemon-in-outer-space-ylg89xqr55bpg3lt.webp', id: 6, }, ]; return { characters, gadgets, gallery }; } genId<T extends chardetailInter | gadgetdetailinter | galleryInter>( myTable: T[] ): number { return Number( myTable.length > 0 ? Math.max(...myTable.map((t) => t.id)) + 1 : 1 ); } }
package com.project.sbs.api.controllers.auth; import com.project.sbs.api.requests.LoginRequest; import com.project.sbs.api.requests.RegisterRequest; import com.project.sbs.api.requests.VerifyEmailRequest; import com.project.sbs.api.responses.ErrorResponse; import com.project.sbs.api.responses.LoginSuccessfulResponse; import com.project.sbs.api.responses.SimpleResponse; import com.project.sbs.api.responses.SuccessBooleanResponse; import com.project.sbs.api.services.auth.AuthService; import com.project.sbs.api.services.auth.EmailService; import com.project.sbs.api.services.auth.JwtService; import com.project.sbs.config.response_components.UserData; import com.project.sbs.database.entities.User; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpStatus; import org.springframework.http.HttpStatusCode; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.*; @RestController @CrossOrigin public class AuthController { AuthService authService; JwtService jwtService; EmailService emailService; @Autowired public AuthController(AuthService authService, JwtService jwtService, EmailService emailService) { this.authService = authService; this.jwtService = jwtService; this.emailService = emailService; } @GetMapping("/hello") public String getHello() { return "Hello Sukhad"; } @GetMapping("/") public ResponseEntity<String> getRootMessage() { return new ResponseEntity<>("the message", HttpStatus.OK); } @PostMapping("/register") public ResponseEntity<SimpleResponse> registerUser( @RequestBody RegisterRequest userDetails ) { String user_fullname = userDetails.getUser_fullname(); String user_email = userDetails.getUser_email(); String user_password = userDetails.getUser_password(); String user_otp = userDetails.getUser_otp(); if (user_fullname==null || user_email==null || user_password==null || user_otp==null) { return ResponseEntity.status(HttpStatus.BAD_REQUEST) .body(new ErrorResponse("Something went wrong (null)")); } user_fullname = user_fullname.trim(); user_email = user_email.trim(); user_otp = user_otp.trim(); if (user_fullname.isEmpty() || user_email.isEmpty() || user_password.isEmpty() || user_otp.isEmpty()) { return ResponseEntity.status(HttpStatus.BAD_REQUEST) .body(new ErrorResponse("Empty fields are not allowed")); } if (!emailService.isValidEmail(user_email)) { return ResponseEntity.status(HttpStatus.BAD_REQUEST) .body(new ErrorResponse("Invalid email")); } if (authService.userAlreadyExists(user_email)) { return ResponseEntity.status(HttpStatus.BAD_REQUEST) .body(new ErrorResponse("Email already registered")); } if (!user_otp.equals(String.valueOf(emailService.generateOTP()))) { return ResponseEntity.status(HttpStatus.UNAUTHORIZED) .body(new ErrorResponse("Wrong OTP")); } User newUser = authService.registerNewUser(user_fullname, user_email, user_password); if (newUser != null) { return ResponseEntity.ok(new LoginSuccessfulResponse( new UserData(newUser), jwtService.generateToken(newUser.getUserId()), true )); } else { return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR) .body(new ErrorResponse("Some error occurred")); } } @PostMapping("/verify-email") public ResponseEntity<SimpleResponse> verifyEmail( @RequestBody VerifyEmailRequest emailRequest ) { String email = emailRequest.getEmail(); if (email == null || !emailService.isValidEmail(email)) { return new ResponseEntity<>(new ErrorResponse("Invalid email"), HttpStatus.BAD_REQUEST); } int OTP = emailService.generateOTP(); emailService.sendEmail(email, OTP); return new ResponseEntity<>(new SuccessBooleanResponse(true), HttpStatus.OK); } @PostMapping("/login") public ResponseEntity<SimpleResponse> login( @RequestBody LoginRequest loginRequest ) { String user_email = loginRequest.getUser_email(); String user_password = loginRequest.getUser_password(); if (user_email == null || user_password == null) { return ResponseEntity.status(HttpStatus.BAD_REQUEST) .body(new ErrorResponse("Something went wrong (null)")); } user_email = user_email.trim(); if (user_password.isEmpty() || user_email.isEmpty()) { return ResponseEntity.status(HttpStatus.BAD_REQUEST) .body(new ErrorResponse("Empty fields are not allowed")); } if (!emailService.isValidEmail(user_email)) { return ResponseEntity.status(HttpStatus.BAD_REQUEST) .body(new ErrorResponse("Invalid email")); } User loggedInUser = authService.loginUser(user_email, user_password); if (loggedInUser != null) { return ResponseEntity.ok(new LoginSuccessfulResponse( new UserData(loggedInUser), jwtService.generateToken(loggedInUser.getUserId()), true )); } else { return ResponseEntity.status(HttpStatus.UNAUTHORIZED) .body(new ErrorResponse("Invalid credentials")); } } @PostMapping("/autologin") public ResponseEntity<SimpleResponse> autoLogin(@RequestHeader("Authorization") String token) { if (jwtService.isTokenValid(token)) { User loggedInUser = authService.autoLoginUser(token); if (loggedInUser == null) { return ResponseEntity.status(HttpStatus.UNAUTHORIZED) .body(new ErrorResponse("Login expired, please log in again")); } return ResponseEntity.ok(new LoginSuccessfulResponse( new UserData(loggedInUser), token, true )); } else { return ResponseEntity.status(HttpStatus.UNAUTHORIZED) .body(new ErrorResponse("Login expired, please log in again")); } } }
import { expect } from 'chai'; import sinon from 'sinon'; import { Kinesis } from '@aws-sdk/client-kinesis'; import logger from '../../services/external/Logger.service'; import { IKinesisService, KinesisService } from '../../services/external/Kinesis.service'; describe('KinesisService', () => { let kinesisService: IKinesisService; let putRecordStub: sinon.SinonStub; // let getShardIteratorStub: sinon.SinonStub; // let getRecordsStub: sinon.SinonStub; let sandbox: sinon.SinonSandbox; before(() => { sandbox = sinon.createSandbox(); }); beforeEach(() => { // Stubbing Kinesis client methods putRecordStub = sandbox.stub(Kinesis.prototype, 'putRecord').resolves(); // getShardIteratorStub = sandbox // .stub(Kinesis.prototype, 'getShardIterator') // .callsArgWith(1, null, { ShardIterator: 'dummyShardIterator' }); // getRecordsStub = sandbox // .stub(Kinesis.prototype, 'getRecords') // .callsArgWith(1, null, { Records: [], NextShardIterator: 'dummyNextShardIterator' }); kinesisService = new KinesisService(); }); afterEach(() => { sandbox.restore(); }); describe('publish', async () => { it('should publish record to the stream', async () => { await kinesisService.publish('testStream', { message: 'Test message' }); expect(putRecordStub.calledOnce).to.be.true; expect(putRecordStub.firstCall.args[0]).to.deep.equal({ StreamName: 'testStream', Data: Uint8Array.from([ 123, 34, 109, 101, 115, 115, 97, 103, 101, 34, 58, 34, 84, 101, 115, 116, 32, 109, 101, 115, 115, 97, 103, 101, 34, 125, ]), PartitionKey: '1', }); }); it('should log success message when record is published', async () => { const loggerInfoStub = sandbox.stub(logger, 'info'); await kinesisService.publish('testStream', { message: 'Test message' }); expect(loggerInfoStub.calledOnce).to.be.true; expect(loggerInfoStub.firstCall.args[0]).to.equal('Record published'); }); it('should log error message when record publishing fails', async () => { putRecordStub.rejects(new Error('Failed to publish record')); const loggerErrorStub = sandbox.stub(logger, 'error'); await kinesisService.publish('testStream', { message: 'Test message' }); expect(loggerErrorStub.calledOnce).to.be.true; expect(loggerErrorStub.firstCall.args[0]).to.equal('Failed to publish record'); }); }); });
module decode #(parameter DWIDTH = 32) ( input [DWIDTH-1:0] instr, // Input instruction. output reg [2 : 0] jump_type, output reg [DWIDTH-7:0] jump_addr, output reg we_regfile, output reg we_dmem, re_dmem, output reg [3 : 0] op, // Operation code for the ALU. output reg ssel, // Select the signal for either the immediate value or rs2. output reg [DWIDTH-1:0] imm, // The immediate value (if used). output reg [4 : 0] rs1_id, // register ID for rs. output reg [4 : 0] rs2_id, // register ID for rt (if used). output reg [4 : 0] rdst_id // register ID for rd or rt (if used). ); import common::*; /*************************************************************************************** --------------------------------------------------------------------------------- | R_type | | opcode | rs | rt | rd | shamt | funct | --------------------------------------------------------------------------------- | I_type | | opcode | rs | rt | immediate | --------------------------------------------------------------------------------- | J_type | | opcode | address | --------------------------------------------------------------------------------- 31 26 25 21 20 16 15 11 10 6 5 0 ***************************************************************************************/ // FIXME: when DWIDTH != 32 wire [5:0] opcode, funct; wire [4:0] rs, rt, rd, shamt; wire [15:0] immediate; wire [25:0] address; assign { opcode, address } = instr; assign { rs, rt, immediate } = address; assign { rd, shamt, funct } = immediate; // assign { opcode, rs, rt, rd, shamt, funct } = instr; // assign immediate = ssel ? 0 : instr[15:0]; // assign address = instr[25:0]; assign jump_addr = address; assign rs1_id = rs; assign rs2_id = rt; reg zero_imm; always @ (*) begin casez (opcode) OPCODE_JAL: zero_imm = 1; default: zero_imm = 0; endcase end always @ (*) begin casez (opcode) OPCODE_REGS: ssel = 1; default: ssel = 0; endcase end assign imm = (ssel || zero_imm) ? 0 : { {16{ immediate[15] }}, immediate }; always @ (*) begin casez (opcode) OPCODE_REGS: casez (funct) REGS_ADD: op = OP_ADD; REGS_SUB: op = OP_SUB; REGS_AND: op = OP_AND; REGS_OR: op = OP_OR; REGS_NOR: op = OP_NOR; REGS_SLT: op = OP_SLT; REGS_JR: op = OP_NOT_DEFINED; default: op = OP_NOT_DEFINED; endcase OPCODE_ADDI: op = OP_ADD; OPCODE_SLTI: op = OP_SLT; OPCODE_LW, OPCODE_SW: op = OP_ADD; OPCODE_J, OPCODE_JAL, OPCODE_BEQ: op = OP_OR; default: op = OP_NOT_DEFINED; endcase end always @ (*) begin casez (opcode) OPCODE_REGS : casez (funct) REGS_JR: rdst_id = 0; default: rdst_id = rd; endcase OPCODE_ADDI, OPCODE_SLTI, OPCODE_LW : rdst_id = rt; OPCODE_JAL : rdst_id = 5'd31; default: rdst_id = rd; endcase end always @ (*) begin casez (opcode) OPCODE_SW , OPCODE_BEQ, OPCODE_J : we_regfile = 0; default: we_regfile = 1; endcase end always @ (*) begin casez (opcode) OPCODE_SW : we_dmem = 1; default: we_dmem = 0; endcase end always @ (*) begin casez (opcode) OPCODE_LW: re_dmem = 1; default: re_dmem = 0; endcase end always @ (*) begin casez (opcode) OPCODE_REGS: casez (funct) REGS_JR: jump_type = J_TYPE_JR; default: jump_type = J_TYPE_NOP; endcase OPCODE_J: jump_type = J_TYPE_J; OPCODE_JAL: jump_type = J_TYPE_JAL; OPCODE_BEQ: jump_type = J_TYPE_BEQ; default: jump_type = J_TYPE_NOP; endcase end endmodule