text
stringlengths
184
4.48M
import './App.css'; import Header from './Component/Header/Header'; import 'bootstrap/dist/css/bootstrap.min.css'; import { BrowserRouter as Router, Switch, Route, Link } from "react-router-dom"; import Home from './Component/Home/Home'; import Login from './Component/Login/Login'; import { createContext } from 'react'; import { useState } from 'react'; import Destination from './Component/Destination/Destination'; import PrivateRoute from './Component/PrivateRoute/PrivateRoute'; export const UserContext = createContext(); function App() { const [loggedInUser, setLoggedInUser] = useState({}); return ( <UserContext.Provider value={[loggedInUser, setLoggedInUser]}> <div className="App"> <h3>Email: {loggedInUser.email}</h3> <Router> <Header></Header> <Switch> <Route path="/home"> <Home></Home> </Route> <Route path="/login"> <Login></Login> </Route> <Route exact path="/"> <Home></Home> </Route> <PrivateRoute path="/destination"> <Destination></Destination> </PrivateRoute> </Switch> </Router> </div> </UserContext.Provider> ); } export default App;
package com.codestates.main07.exception; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.MethodArgumentNotValidException; import org.springframework.web.bind.annotation.ResponseStatus; import org.springframework.web.bind.annotation.RestControllerAdvice; import org.springframework.web.bind.annotation.ExceptionHandler; import javax.validation.ConstraintViolationException; @RestControllerAdvice // Controller 클래스에서 발생하는 예외를 도맡아서 처리 public class GlobalExceptionAdvice { @ExceptionHandler @ResponseStatus(HttpStatus.BAD_REQUEST) public ErrorResponse handleMethodArgumentNotValidException( MethodArgumentNotValidException e) { final ErrorResponse response = ErrorResponse.of(e.getBindingResult()); return response; } @ExceptionHandler @ResponseStatus(HttpStatus.BAD_REQUEST) public ErrorResponse handleConstraintViolationException( ConstraintViolationException e) { final ErrorResponse response = ErrorResponse.of(e.getConstraintViolations()); return response; } @ExceptionHandler public ResponseEntity handleBusinessLogicException(BusinessLogicException e) { System.out.println(e.getExceptionCode().getStatus()); System.out.println(e.getMessage()); return new ResponseEntity<>(HttpStatus.valueOf(e.getExceptionCode().getStatus())); } }
// GET request (read) import Prompt from '@/models/Prompt'; import { connectDB } from '@/utils/database.js'; const GET = async function (request, { params }) { try { await connectDB(); const prompt = await Prompt.findById(params.id).populate({ path: 'creator' }); if (!prompt) return new Response('Prompt not found', { status: 404 }); return new Response(JSON.stringify(prompt), { status: 200 }); } catch (error) { console.log(error); return new Response('Failed to fetch prompt.', { status: 500 }); } }; // PATCH (update) const PATCH = async function (request, { params }) { const { prompt, tag } = await request.json(); try { await connectDB(); const existingPrompt = await Prompt.findById(params.id); if (!existingPrompt) return new Response('Prompt not found', { status: 404 }); existingPrompt.prompt = prompt; existingPrompt.tag = tag; await existingPrompt.save(); return new Response(JSON.stringify(existingPrompt), { status: 200 }); } catch (error) { return new Response('Failed to udpate prompt', { status: 500 }); } }; // DELETE (delete) const DELETE = async function (request, { params }) { try { await connectDB(); await Prompt.findByIdAndRemove(params.id); return new Response('Prompt deleted successfully', { status: 200 }); } catch (error) { return new Response('Failed to delete prompt', { status: 500 }); } }; export { GET, PATCH, DELETE };
import { Selector } from 'testcafe'; import { navBar } from './navbar.component'; class AdminDashboardPage { private pageId: string; private pageSelector: Selector; constructor() { this.pageId = '#admin-dashboard'; this.pageSelector = Selector(this.pageId); } private async isDisplayed(tc: TestController) { await tc.expect(this.pageSelector.exists).ok(); await tc.expect(this.pageSelector.visible).ok(); } private async checkSections(tc: TestController) { await tc.expect(Selector('#students').exists).ok(); await tc.expect(Selector('#companies').exists).ok(); await tc.expect(Selector('#events').exists).ok(); await tc.expect(Selector('#listings').exists).ok(); } async test(tc: TestController) { await navBar.clickNavLink(tc, 'Dashboard'); await this.isDisplayed(tc); await this.checkSections(tc); } } export const adminDashboardPage = new AdminDashboardPage();
#include <Arduino.h> #include <WiFi.h> #include <WiFiMulti.h> #include <WiFiClientSecure.h> #include <WebSocketsClient.h> #include <ESP32Servo.h> WiFiMulti WiFiMulti; WebSocketsClient webSocket; Servo myservo; Servo myservoexit; int pinIn = 34; int pinOut = 35; int pinInExit = 32; int pinOutExit = 33; int servoPin = 23; //36 int servoPinExit = 22; // 39 int value_PinIn = 1; int value_PinIn_Exit = 1; int pin1 = 25; int pin2 = 26; int pin3 = 27; int pin4 = 14; int pin5 = 13; int pin6 = 19; int pin7 = 18; int pin8 = 5; int value1 = 1; int value2 = 1; int value3 = 1; int value4 = 1; int value5 = 1; int value6 = 1; int value7 = 1; int value8 = 1; void hexdump(const void *mem, uint32_t len, uint8_t cols = 16) { const uint8_t *src = (const uint8_t *)mem; Serial.printf("\n[HEXDUMP] Address: 0x%08X len: 0x%X (%d)", (ptrdiff_t)src, len, len); for (uint32_t i = 0; i < len; i++) { if (i % cols == 0) { Serial.printf("\n[0x%08X] 0x%08X: ", (ptrdiff_t)src, i); } Serial.printf("%02X ", *src); src++; } Serial.printf("\n"); } void webSocketEvent(WStype_t type, uint8_t *payload, size_t length) { switch (type) { case WStype_DISCONNECTED: Serial.printf("[WSc] Disconnected!\n"); break; case WStype_CONNECTED: Serial.printf("[WSc] Connected to url: %s\n", payload); break; case WStype_TEXT: Serial.printf("[WSc] get text: %s\n", payload); if (strncmp((char *)payload, "{\"event\":\"gate_open_command\"}", length) == 0) { Serial.println("gate_open command received entering into open gate function"); openGate(&value_PinIn); } else if (strncmp((char *)payload, "{\"event\":\"gate_open_exit_command\"}", length) == 0) { Serial.println("gate_open_exit command received entering into open gate function"); openGateExit(&value_PinIn_Exit); }else if (strncmp((char *)payload, "{\"event\":\"gate_open_front\"}", length) == 0) { myservo.write(0); } else if (strncmp((char *)payload, "{\"event\":\"gate_close_front\"}", length) == 0) { myservo.write(90); }else if (strncmp((char *)payload, "{\"event\":\"gate_open_back\"}", length) == 0) { myservoexit.write(90); } else if (strncmp((char *)payload, "{\"event\":\"gate_close_back\"}", length) == 0) { myservoexit.write(0); } break; } } void setup() { Serial.begin(115200); pinMode(pin1, INPUT); pinMode(pin2, INPUT); pinMode(pin3, INPUT); pinMode(pin4, INPUT); pinMode(pin5, INPUT); pinMode(pin6, INPUT); pinMode(pin7, INPUT); pinMode(pin8, INPUT); pinMode(pinIn, INPUT); pinMode(pinOut, INPUT); pinMode(pinInExit, INPUT); pinMode(pinOutExit, INPUT); ESP32PWM::allocateTimer(0); ESP32PWM::allocateTimer(1); ESP32PWM::allocateTimer(2); ESP32PWM::allocateTimer(3); myservo.setPeriodHertz(50); myservoexit.setPeriodHertz(50); myservo.attach(servoPin, 500, 2400); myservoexit.attach(servoPinExit, 500, 2400); Serial.println(); Serial.println(); Serial.println(); for (uint8_t t = 4; t > 0; t--) { Serial.printf("[SETUP] BOOT WAIT %d...\n", t); Serial.flush(); delay(1000); } WiFiMulti.addAP("JioFi2_A04AAA", "buft2xmvez"); while (WiFiMulti.run() != WL_CONNECTED) { Serial.println("."); delay(1000); } webSocket.begin("192.168.176.12", 3000, "/echo"); webSocket.onEvent(webSocketEvent); webSocket.setReconnectInterval(5000); } void loop() { Serial.println("loop started"); webSocket.loop(); checkSensor(pin1, &value1, "p1" ); checkSensor(pin2, &value2, "p2" ); checkSensor(pin3, &value3, "p3" ); checkSensor(pin4, &value4, "p4" ); checkSensor(pin5, &value5, "p11" ); checkSensor(pin6, &value6, "p12" ); checkSensor(pin7, &value7, "p13" ); checkSensor(pin8, &value8, "p14" ); checkGates(&value_PinIn, &value_PinIn_Exit); } void checkGates(int *value, int *value2) { Serial.println("checking gate inpin"); int newSensorValue = digitalRead(pinIn); if (newSensorValue != *value) { Serial.println("inpin is changed"); if (newSensorValue == 0) { Serial.println("inpin is 0 sending open_gate command"); webSocket.sendTXT("{\"event\": \"gate\", \"data\": \"open_gate\"}"); } else { Serial.println("inpin is 1 sending close_gate command"); webSocket.sendTXT("{\"event\": \"gate\", \"data\": \"close_gate\"}"); } Serial.println("now assigning new value to inpin"); *value = newSensorValue; } Serial.println("checking exit gate inpin"); newSensorValue = digitalRead(pinInExit); if (newSensorValue != *value2) { Serial.println("inpin exit is changed"); if (newSensorValue == 0) { Serial.println("inpin is 0 sending open_gate_exit command"); webSocket.sendTXT("{\"event\": \"gate\", \"data\": \"open_gate_exit\"}"); } else { Serial.println("inpin is 1 sending close_gate_exit command"); webSocket.sendTXT("{\"event\": \"gate\", \"data\": \"close_gate_exit\"}"); } Serial.println("now assigning new value to inpinexit"); *value2 = newSensorValue; } } void openGate(int *valueInPin) { Serial.println("opening gate"); myservo.write(0); Serial.println("waiting"); while (digitalRead(pinIn) == 0 || digitalRead(pinOut) == 0) { Serial.print("."); } Serial.println("closing gate"); myservo.write(90); Serial.println("setting inpin value to 1"); *valueInPin = 1; } void openGateExit(int *valueInPin) { Serial.println("opening gate"); myservoexit.write(90); Serial.println("waiting"); while (digitalRead(pinInExit) == 0 || digitalRead(pinOutExit) == 0) { Serial.print("."); } Serial.println("closing gate"); myservoexit.write(0); Serial.println("setting inpin value to 1"); *valueInPin = 1; } void checkSensor(int pin, int *value, String slot) { int newSensorValue = digitalRead(pin); if (newSensorValue != *value) { if (newSensorValue == 1) { webSocket.sendTXT("{\"event\":\"sensor_update\",\"data\":{\"pid\":\"65e92c0ab20f1ae7b43c7962\",\"slot\":\""+slot+"\",\"status\":\"booked\"}}"); } else { webSocket.sendTXT("{\"event\":\"sensor_update\",\"data\":{\"pid\":\"65e92c0ab20f1ae7b43c7962\",\"slot\":\""+slot+"\",\"status\":\"occupied\"}}"); } *value = newSensorValue; } delay(100); }
package main import "fmt" func diasDaSemana(numero int) string { switch numero { case 1: return "Domingo" case 2: return "Segunda-Feira" case 3: return "Terça-Feira" case 4: return "Quarta-Feira" case 5: return "Quinta-Feira" case 6: return "Sexta-Feira" case 7: return "Sabado" default: return "Numero Inválido" } } func mesesDoAno(numero int) string { var mesDoAno string switch { case numero == 1: mesDoAno = "Janeiro" fallthrough // É usado somente em casos muito especificos | Joga o codigo para a proxima condição case numero == 2: mesDoAno = "Fevereiro" case numero == 3: mesDoAno = "Março" case numero == 4: mesDoAno = "Abril" case numero == 5: mesDoAno = "Maio" case numero == 6: mesDoAno = "Junho" case numero == 7: mesDoAno = "Julho" case numero == 8: mesDoAno = "Agosto" case numero == 9: mesDoAno = "Setembro" case numero == 10: mesDoAno = "Outubro" case numero == 11: mesDoAno = "Novembro" case numero == 12: mesDoAno = "Dezembro" default: mesDoAno = "Numero Inválido" } return mesDoAno } func main() { dia := diasDaSemana(3) fmt.Println(dia) mes := mesesDoAno(9) fmt.Println(mes) }
type FAQsProps = { index: number; question: string; answer: string; opened: boolean; }; const FAQ = ({ index, question, answer, opened }: FAQsProps) => { return ( <> <div className='text-black md:text-xl font-semibold min-h-12 md:h-16 px-2 md:px-4 py-1 md:py-2 flex justify-between items-center h-fit'> <p className='leading-tight tracking-tighter'>{question}</p> <span className='cursor-pointer'> <svg xmlns='http://www.w3.org/2000/svg' fill='none' viewBox='0 0 24 24' strokeWidth={2.25} stroke='currentColor' className={`w-6 h-6 transform ${ opened ? '-rotate-45' : 'rotate-0' } transition-all duration-100`} > <path strokeLinecap='round' strokeLinejoin='round' d='M12 4.5v15m7.5-7.5h-15' /> </svg> </span> </div> {opened && ( <div className='text-black p-2 md:p-4 md:text-base text-sm'> {answer} </div> )} </> ); }; export default FAQ;
"use client"; import * as React from "react"; import * as Toast from "@radix-ui/react-toast"; import "../../globals.css"; import { Button } from "@radix-ui/themes"; const AuthToast = () => { const [open, setOpen] = React.useState(false); const eventDateRef = React.useRef(new Date()); const timerRef = React.useRef(0); React.useEffect(() => { return () => clearTimeout(timerRef.current); }, []); return ( <Toast.Provider swipeDirection="right"> <Toast.Root className="ToastRoot" open={open} onOpenChange={setOpen}> <Toast.Title className="ToastTitle">Success</Toast.Title> <Toast.Description asChild> <time className="ToastDescription" dateTime={eventDateRef.current.toISOString()}> {prettyDate(eventDateRef.current)} </time> </Toast.Description> <Toast.Action className="ToastAction" asChild altText="Goto schedule to undo"> <button className="Button small green">Undo</button> </Toast.Action> </Toast.Root> <Toast.Viewport className="ToastViewport" /> </Toast.Provider> ); }; function oneWeekAway(date) { const now = new Date(); const inOneWeek = now.setDate(now.getDate() + 7); return new Date(inOneWeek); } function prettyDate(date) { return new Intl.DateTimeFormat("en-US", { dateStyle: "full", timeStyle: "short", }).format(date); } export default AuthToast;
/********************************************************************* * Copyright (c) 2019 Arm and others * * This program and the accompanying materials are made * available under the terms of the Eclipse Public License 2.0 * which is available at https://www.eclipse.org/legal/epl-2.0/ * * SPDX-License-Identifier: EPL-2.0 *********************************************************************/ import { join } from 'path'; import { expect } from 'chai'; import { CdtDebugClient } from './debugClient'; import { fillDefaults, standardBeforeEach, testProgramsDir } from './utils'; describe('logpoints', async () => { let dc: CdtDebugClient; beforeEach(async function () { dc = await standardBeforeEach(); await dc.launchRequest( fillDefaults(this.currentTest, { program: join(testProgramsDir, 'count'), }) ); }); afterEach(async () => { await dc.stop(); }); it('hits a logpoint', async () => { const logMessage = 'log message'; await dc.setBreakpointsRequest({ source: { name: 'count.c', path: join(testProgramsDir, 'count.c'), }, breakpoints: [ { column: 1, line: 4, logMessage, }, ], }); await dc.configurationDoneRequest(); const logEvent = await dc.waitForOutputEvent('console'); expect(logEvent.body.output).to.eq(logMessage); }); it('supports changing log messages', async () => { const logMessage = 'log message'; await dc.setBreakpointsRequest({ source: { name: 'count.c', path: join(testProgramsDir, 'count.c'), }, breakpoints: [ { column: 1, line: 4, logMessage: 'something uninteresting', }, ], }); await dc.setBreakpointsRequest({ source: { name: 'count.c', path: join(testProgramsDir, 'count.c'), }, breakpoints: [ { column: 1, line: 4, logMessage, }, ], }); await dc.configurationDoneRequest(); const logEvent = await dc.waitForOutputEvent('console'); expect(logEvent.body.output).to.eq(logMessage); }); });
<?php namespace App\Http\Controllers; use App\Collection; use App\Http\Resources\CollectionResource; use App\Http\Resources\CollectionResourceCollection; use App\Http\Resources\ProductResource; use Illuminate\Http\Request; use Illuminate\Support\Facades\Storage; use Illuminate\Support\Facades\Validator; class CollectionController extends Controller { /** * Get a validator for an incoming request. * * @param array $data * @return \Illuminate\Contracts\Validation\Validator */ protected function validator(array $data) { return Validator::make($data, [ 'name' => ['required', 'unique:collections', 'max:255', 'min:3'], 'image.*' => 'image|mimes:jpeg,png,jpg,gif,svg|max:2048' ]); } /** * Display a listing of the resource. * * @return \Illuminate\Http\Response */ public function index() { return response()->json([ 'status' => 200, 'data' => new CollectionResourceCollection(Collection::paginate()) ]); } /** * Store a newly created resource in storage. * * @param \Illuminate\Http\Request $request * @return \Illuminate\Http\Response */ public function store(Request $request) { $this->validator($request->all())->validate(); $path = $request->file('image')->store('collection'); $collection = Collection::create(['name' => $request->input('name'), 'image' => $path]); return response()->json([ 'status' => 201, 'message' => 'collection created successfully', 'data' => new CollectionResource($collection) ]); } /** * Display the specified resource. * * @param \App\Collection $collection * @return \Illuminate\Http\Response */ public function show(Collection $collection) { return response()->json([ 'status' => 200, 'data' => new CollectionResource($collection) ]); } /** * Update the specified resource in storage. * * @param \Illuminate\Http\Request $request * @param \App\Collection $collection * @return \Illuminate\Http\Response */ public function update(Request $request, Collection $collection) { $this->validator($request->all())->validate(); $path = $request->file('image')->store('collection'); $collection = Collection::create(['name' => $request->input('name'), 'image' => $path]); return response()->json([ 'status' => 200, 'message' => 'collection updated successfully', 'data' => new CollectionResource($collection) ]); } /** * Remove the specified resource from storage. * * @param \App\Collection $collection * @return \Illuminate\Http\Response */ public function destroy(Collection $collection) { $collection->delete(); return response()->json(['status' => 200, 'message' => 'collection deleted successfully']); } }
package com.xtremepixel.jetweatherapp.screens.search import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.padding import androidx.compose.foundation.shape.RoundedCornerShape import androidx.compose.foundation.text.KeyboardActions import androidx.compose.foundation.text.KeyboardOptions import androidx.compose.material.* import androidx.compose.material.icons.Icons import androidx.compose.material.icons.filled.ArrowBack import androidx.compose.runtime.* import androidx.compose.runtime.saveable.rememberSaveable import androidx.compose.ui.Alignment import androidx.compose.ui.ExperimentalComposeUiApi import androidx.compose.ui.Modifier import androidx.compose.ui.graphics.Color import androidx.compose.ui.platform.LocalSoftwareKeyboardController import androidx.compose.ui.text.input.ImeAction import androidx.compose.ui.text.input.KeyboardType import androidx.compose.ui.unit.dp import androidx.navigation.NavController import com.xtremepixel.jetweatherapp.navigation.WeatherAppScreen import com.xtremepixel.jetweatherapp.widgets.WeatherAppBar @Composable fun SearchScreen(navController: NavController) { Scaffold(topBar = { WeatherAppBar( icon = Icons.Default.ArrowBack, elevation = 1.dp, isHomeScreen = false, title = "Search...", navController = navController ) { navController.popBackStack() } }) { Surface() { Column( verticalArrangement = Arrangement.Center, horizontalAlignment = Alignment.CenterHorizontally, modifier = Modifier.padding(top = 32.dp) ) { SearchForm( modifier = Modifier .fillMaxWidth() .padding(16.dp) .align(Alignment.CenterHorizontally) ) { navController.navigate(route = WeatherAppScreen.HomeScreen.name + "/$it") } } } } } @OptIn(ExperimentalComposeUiApi::class) @Composable fun SearchForm( modifier: Modifier = Modifier, onSearch: (String) -> Unit = {} ) { val searchQueryState = rememberSaveable { mutableStateOf("") } val keyboardController = LocalSoftwareKeyboardController.current val valid = remember(searchQueryState.value) { searchQueryState.value.trim().isNotEmpty() } Column() { CommonTextField( valueState = searchQueryState, placeHolder = "Uyo", onAction = KeyboardActions { if (valid.not()) return@KeyboardActions onSearch(searchQueryState.value.trim()) searchQueryState.value = "" keyboardController?.hide() } ) } } @Composable fun CommonTextField( valueState: MutableState<String>, placeHolder: String, keyboardType: KeyboardType = KeyboardType.Text, imeAction: ImeAction = ImeAction.Next, onAction: KeyboardActions = KeyboardActions.Default ) { OutlinedTextField(value = valueState.value, onValueChange = { valueState.value = it }, label = { Text(text = placeHolder) }, maxLines = 1, singleLine = true, keyboardOptions = KeyboardOptions(keyboardType = keyboardType, imeAction = imeAction), keyboardActions = onAction, colors = TextFieldDefaults.outlinedTextFieldColors( focusedBorderColor = Color.Blue, cursorColor = Color.Black ), shape = RoundedCornerShape(15.dp), modifier = Modifier .fillMaxWidth() .padding(horizontal = 10.dp) ) }
import { ReactNode, createContext } from "react"; interface ChildrenProvider { children: ReactNode; } interface Auth { logout: () => void; isAuthenticated: () => boolean; getTaxIdUser: () => string | undefined; } export const AuthContext = createContext<Auth>({} as Auth); export const AuthProvider = ({ children }: ChildrenProvider) => { function logout() { localStorage.removeItem("token"); localStorage.removeItem("taxId"); window.location.href = "/"; } function isAuthenticated() { const hasToken = localStorage.getItem("token"); if (hasToken) { return true; } return false; } function getTaxIdUser(): string | undefined { const taxId = localStorage.getItem("taxId"); if (!taxId) return undefined; return taxId; } return ( <AuthContext.Provider value={{ logout, isAuthenticated, getTaxIdUser }}> {children} </AuthContext.Provider> ); };
#pragma once #include <iostream> #include <vector> #include <ostream> #include <string> #include <map> #include <algorithm> #include <iterator> #include <optional> #include "../Types.h" namespace FPL { class FonctionArgumentDef { public: std::string ArgumentName; std::string ArgumentValue; Types::Types ArgumentType; friend std::ostream& operator<<(std::ostream& flux, FonctionArgumentDef const& arg); friend bool operator==(FonctionArgumentDef const& arg1, FonctionArgumentDef const& arg2); }; class FonctionDef { public: FonctionDef(); FonctionDef(std::string name, Types::Types type, std::map<std::string, FonctionArgumentDef> allArgs, std::vector<std::string> code, int nArgs, std::string returnV); std::string FonctionName; Types::Types FonctionType; std::map<std::string, FonctionArgumentDef> AllFonctionArguments; std::vector<std::string> FonctionContentCode; int FonctionNumberArgument = 0; std::string ReturnValue = "N/A"; friend std::ostream& operator<<(std::ostream& flux, FonctionDef const& var); friend bool operator==(const FonctionDef &v1, const FonctionDef &v2); friend bool operator!=(const FonctionDef &v1, const FonctionDef &v2); bool isArgument(std::string const& argument); std::optional<FonctionArgumentDef> getArgument(std::string const& argument); void updateValueOfArgument(FonctionArgumentDef argument, std::string_view value); }; }
"use client"; import { motion } from "framer-motion"; import Link from "next/link"; import { usePathname } from "next/navigation.js"; import React from "react"; import { linkUrl } from "../../../data/link-url.js"; const container = { hidden: { opacity: 0, y: 20 }, visible: { opacity: 1, y: 0, transition: { delayChildren: 0.5, staggerChildren: 0.5, }, }, }; const item = { hidden: { y: 20, opacity: 0 }, visible: { y: 0, opacity: 1, }, }; const Sidebar = () => { const router = usePathname(); if (router === "/login") { return null; } return ( <div className="flex-1 flex flex-col mt-5"> <motion.ul variants={container} initial="hidden" animate="visible"> {linkUrl.map((link: any) => ( <Link href={link.url} key={link.id}> <motion.li variants={item} className="h-12 flex items-center gap-10 justify-start pl-10 text-base font-semibold hover:bg-primary hover:text-white hover:dark:bg-primary rounded-tr-full rounded-br-full transition-all" > {link.icon} {link.name} </motion.li> </Link> ))} </motion.ul> </div> ); }; export default Sidebar;
import { StatusBar } from "expo-status-bar"; import { StyleSheet, Text, View, Alert } from "react-native"; import { useEffect } from "react"; // Screen Navigation import Start from "./components/Start"; import Chat from "./components/Chat"; // Navigation import { NavigationContainer } from "@react-navigation/native"; import { createNativeStackNavigator } from "@react-navigation/native-stack"; // Initialize firestore DB import { initializeApp } from "firebase/app"; import { getFirestore, disableNetwork, enableNetwork, } from "firebase/firestore"; // NetInfo import { useNetInfo } from "@react-native-community/netinfo"; // Create the navigator const Stack = createNativeStackNavigator(); const App = () => { const connectionStatus = useNetInfo(); // Connection handler useEffect(() => { if (connectionStatus.isConnected === false) { Alert.alert("Connection Lost!"); disableNetwork(db); } else if (connectionStatus.isConnected === true) { enableNetwork(db); } }, [connectionStatus.isConnected]); // Firebase DB settings const firebaseConfig = { apiKey: "AIzaSyBVBnp9-boZcZikxKC_E--MVrUhmeXInsw", authDomain: "chatapp-8d2da.firebaseapp.com", projectId: "chatapp-8d2da", storageBucket: "chatapp-8d2da.appspot.com", messagingSenderId: "127953471873", appId: "1:127953471873:web:3efc353fe1694de9788080", }; // Initialize Firebase const app = initializeApp(firebaseConfig); // Initialize Cloud Firestore and get a reference to the service const db = getFirestore(app); return ( <NavigationContainer> <Stack.Navigator initialRouteName="Start"> <Stack.Screen name="Start" component={Start} /> <Stack.Screen name="Chat"> {(props) => ( <Chat isConnected={connectionStatus.isConnected} db={db} {...props} /> )} </Stack.Screen> </Stack.Navigator> </NavigationContainer> ); }; const styles = StyleSheet.create({ container: { flex: 1, backgroundColor: "#fff", alignItems: "center", justifyContent: "center", }, }); export default App;
package com.api.crud.services; import com.api.crud.models.UserModel; import com.api.crud.repositories.IUserRepository; import jakarta.persistence.EntityNotFoundException; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import java.util.ArrayList; import java.util.Optional; //Pueden tener dependencias inyectadas @Service //es la capa de servicio, es donde se coloca la lógica de negocio, operaciones o funciones que son importantes para la ejecución de los requerimientos del negocio. public class UserService { @Autowired //realiza inyeccion de dependencias, se puede colocar sobre campos, métodos setter, y constructores. IUserRepository userRepository; public ArrayList<UserModel> getUsers(){ return (ArrayList<UserModel>) userRepository.findAll(); } public UserModel saveUser(UserModel user){ return userRepository.save(user); } public Optional<UserModel> getById(Long id){ return userRepository.findById(id); } public UserModel updateById(UserModel request, Long id) { Optional<UserModel> optionalUser = userRepository.findById(id); if (optionalUser.isEmpty()) { throw new EntityNotFoundException("User with id " + id + " not found"); } UserModel user = optionalUser.get(); // Validar datos (opcional) if (request.getFirstName() != null) { user.setFirstName(request.getFirstName()); } if (request.getLastName() != null) { user.setLastName(request.getLastName()); } if (request.getEmail() != null) { user.setEmail(request.getEmail()); } // Realiza la actualización en la base de datos UserModel updatedUser = userRepository.save(user); return updatedUser; } public UserModel patchById(UserModel request, Long id){ Optional<UserModel> optionalUser = userRepository.findById(id); if (optionalUser.isEmpty()){ throw new EntityNotFoundException("User with id " + id + " not found"); } UserModel user = optionalUser.get(); if(request.getFirstName() != null){ user.setFirstName(request.getFirstName()); } if (request.getLastName() != null){ user.setLastName(request.getLastName()); } if(request.getEmail() != null){ user.setEmail(request.getEmail()); } UserModel patchedUser = userRepository.save(user); return patchedUser; } public Boolean deleteUSer(Long id){ try { userRepository.deleteById(id); return true; }catch (Exception e){ return false; } } }
package com.atacankullabci.todoapp.security; import com.atacankullabci.todoapp.dto.AuthenticationResponseDTO; import com.atacankullabci.todoapp.dto.LoginRequestDTO; import com.atacankullabci.todoapp.dto.RefreshTokenRequestDTO; import com.atacankullabci.todoapp.dto.UserLoginDTO; import com.atacankullabci.todoapp.exceptions.CustomException; import com.atacankullabci.todoapp.service.AuthService; import org.springframework.http.HttpHeaders; import org.springframework.http.ResponseEntity; import org.springframework.security.authentication.DisabledException; import org.springframework.web.bind.annotation.*; import javax.validation.Valid; @RestController @RequestMapping("/api/auth") public class AuthController { private final AuthService authService; public AuthController(AuthService authService) { this.authService = authService; } @PostMapping("/sign-up") public ResponseEntity<String> signUp(@Valid @RequestBody UserLoginDTO userLoginDTO) throws CustomException { if (userLoginDTO != null) { authService.signupUser(userLoginDTO); } else { throw new CustomException("Bad request"); } return ResponseEntity.ok().build(); } @GetMapping("/account-verification/{activationToken}") public ResponseEntity<String> activateUser(@PathVariable(name = "activationToken") String activationToken) throws CustomException { if (activationToken != null) { try { authService.activateUser(activationToken); } catch (CustomException exception) { return ResponseEntity.badRequest().body("Your activation token is either revoked or incorrect"); } } return ResponseEntity.ok("Account has been activated"); } @PostMapping("/login") public ResponseEntity<AuthenticationResponseDTO> login(@RequestBody LoginRequestDTO loginRequestDTO) throws CustomException { AuthenticationResponseDTO authenticationResponseDTO; try { authenticationResponseDTO = authService.loginUser(loginRequestDTO); } catch (DisabledException e) { throw new CustomException("The user has not been activated"); } HttpHeaders httpHeaders = new HttpHeaders(); httpHeaders.add("Authorization", authenticationResponseDTO.getAuthenticationToken()); return ResponseEntity.ok().headers(httpHeaders).body(authenticationResponseDTO); } @PostMapping("/refresh/token") public ResponseEntity<AuthenticationResponseDTO> refreshToken(@Valid @RequestBody RefreshTokenRequestDTO refreshTokenRequestDTO) { return ResponseEntity.ok().body(authService.refreshToken(refreshTokenRequestDTO)); } @PostMapping("/logout") public ResponseEntity<Void> logout(@Valid @RequestBody RefreshTokenRequestDTO refreshTokenRequestDTO) { authService.logoutUser(refreshTokenRequestDTO); return ResponseEntity.ok().build(); } }
import React from "react"; import { useDispatch, useSelector } from "react-redux"; import { handleFindProspect } from "../../redux/ProspectSlice"; import { useTranslation } from "react-i18next"; const ShowProspectDetails = ({ setShowProspectDetails }) => { const { singleProspect } = useSelector((state) => state.root.prospects); const dispatch = useDispatch(); const { t } = useTranslation(); const { name, industry, website, email, mobile, officeNumber, billingAddress, } = singleProspect; return ( <div className="w-full lg:space-y-5 space-y-3"> {/* title + buttons */} <div className="w-full flex justify-between items-center md:flex-row flex-col gap-3"> <p className="font-semibold text-left lg:text-xl text-lg"> {t("Prospect details")} </p> <div className="flex flex-wrap items-center justify-start md:gap-3 gap-1"> <button className={`gray_button`} onClick={() => { setShowProspectDetails(false); dispatch(handleFindProspect("")); }} > {t("Cancel")} </button> </div> </div> {/* main div */} <div className="md:p-8 p-4 rounded-md shadow-md bg-white md:space-y-5 space-y-3"> <p className="font-bold text-black md:text-xl">{t("Prospect Info")}</p> {/* personal details */} <div className="w-full grid md:grid-cols-3 place-items-start items-center md:gap-5 gap-2"> {/* name */} <div className="w-full space-y-2"> <label htmlFor="name" className="Label"> {t("Name")} </label> <p className="font-semibold">{name ?? "-"}</p> </div> {/* industry */} <div className="w-full space-y-2"> <label htmlFor="industry" className="Label"> {t("industry")} </label> <p className="font-semibold">{industry ?? "-"}</p> </div> {/* website */} <div className="w-full space-y-2"> <label htmlFor="website" className="Label"> {t("website")} </label> <p className="font-semibold">{website ?? "-"}</p> </div> </div> <hr className="my-1" /> {/* contact info */} <p className="font-bold text-black md:text-xl">{t("Contact Info")}</p> <div className="w-full grid md:grid-cols-3 place-items-start items-center md:gap-5 gap-2"> {/* email */} <div className="w-full space-y-2"> <label htmlFor="email" className="Label"> {t("email")} </label> <p className="font-semibold">{email ?? "-"}</p> </div> {/* mobile number */} <div className="w-full space-y-2"> <label htmlFor="mobile_number" className="Label"> {t("mobile number")} </label> <p className="font-semibold">{mobile ?? "-"}</p> </div> {/* office number */} <div className="w-full space-y-2"> <label htmlFor="office_number" className="Label"> {t("office number")} </label> <p className="font-semibold">{officeNumber ?? "-"}</p> </div> </div> <hr className="my-1" /> {/*billing address */} <p className="font-bold text-black md:text-xl"> {t("Billing Address")} </p>{" "} <div className="w-full grid md:grid-cols-3 place-items-start items-center md:gap-5 gap-2"> {/*contact name */} <div className="w-full space-y-2"> <label htmlFor="contact_name" className="Label"> {t("Contact Name")} </label> <p className="font-semibold"> {billingAddress?.contactName !== "" ? billingAddress?.contactName : "-"} </p> </div> {/* email */} <div className="w-full space-y-2"> <label htmlFor="email" className="Label"> {t("email")} </label> <p className="font-semibold"> {billingAddress?.email !== "" ? billingAddress?.email : "-"} </p> </div> {/* phone */} <div className="w-full space-y-2"> <label htmlFor="phone" className="Label"> {t("phone")} </label> <p className="font-semibold"> {billingAddress?.phone !== "" ? billingAddress?.phone : "-"} </p> </div> {/* company address */} <div className="w-full col-span-full space-y-2"> <label htmlFor="company_address" className="Label"> {t("company address")} </label> <p className="font-semibold"> {billingAddress?.address !== "" ? billingAddress?.address : "-"} </p> </div> {/* city */} <div className="w-full space-y-2"> <label htmlFor="city" className="Label"> {t("city")} </label> <p className="font-semibold"> {billingAddress?.city !== "" ? billingAddress?.city : "-"} </p> </div> {/* country */} <div className="w-full space-y-2"> <label htmlFor="country" className="Label"> {t("country")} </label> <p className="font-semibold"> {billingAddress?.country !== "" ? billingAddress?.country : "-"} </p> </div> {/* zipcode */} <div className="w-full space-y-2"> <label htmlFor="zipcode" className="Label"> {t("zipcode")} </label> <p className="font-semibold"> {billingAddress?.zipCode !== "" ? billingAddress?.zipCode : "-"} </p> </div> </div> </div> </div> ); }; export default ShowProspectDetails;
package com.jf.controller.email; import org.springframework.context.ApplicationContext; import javax.mail.Session; import javax.mail.Transport; import javax.mail.internet.InternetAddress; import javax.mail.internet.MimeMessage; import java.io.InputStream; import java.util.Date; import java.util.Map; import java.util.Properties; import java.util.Set; /** * JavaMail 版本: 1.6.0 * JDK 版本: JDK 1.7 以上(必须) */ public class Email { public static String receiveMailAccount = "[email protected]"; public static void main(String[] args) throws Exception { Properties p = new Properties(); p.load(Email.class.getClassLoader().getResourceAsStream("email.properties")); String email = p.getProperty("mail.smtp.email"); String password = p.getProperty("mail.smtp.password"); Session session = Session.getInstance(p); session.setDebug(true); MimeMessage message = createMimeMessage(session, email, receiveMailAccount); Transport transport = session.getTransport(); transport.connect(email, password); transport.sendMessage(message, message.getAllRecipients()); transport.close(); } /** * 创建一封只包含文本的简单邮件 * * @param session 和服务器交互的会话 * @param sendMail 发件人邮箱 * @param receiveMail 收件人邮箱 * @return * @throws Exception */ private static MimeMessage createMimeMessage(Session session, String sendMail, String receiveMail) throws Exception { MimeMessage message = new MimeMessage(session); message.setFrom(new InternetAddress(sendMail, "某宝网", "UTF-8")); message.setRecipient(MimeMessage.RecipientType.TO, new InternetAddress(receiveMail, "XX用户", "UTF-8")); message.setSubject("打折钜惠", "UTF-8"); message.setContent("XX用户你好, 今天全场5折, 快来抢购, 错过今天再等一年。。。", "text/html;charset=UTF-8"); message.setSentDate(new Date()); message.saveChanges(); return message; } }
import { inject, injectable } from "tsyringe"; import { AppError } from '../../errors/AppError'; import { ICategoriesRepository } from '../../repositories/interfaces/ICategoriesRepository'; import { ISpendsRepository } from '../../repositories/interfaces/ISpendsRepository'; interface IRequest { name: string; description: string; cost: number; id_category: string; id_user?: string; } @injectable() class CreateSpendsService { constructor( @inject("SpendsRepository") private spendsRepository: ISpendsRepository, @inject("CategoriesRepository") private categoryRepository: ICategoriesRepository ) {} async execute({name, description, cost, id_category, id_user}: IRequest): Promise<void> { if(! await this.categoryRepository.findById(id_category)) { throw new AppError("Category does not exists!"); } this.spendsRepository.createSpend({name, description, cost, id_category, id_user}); } } export { CreateSpendsService }
import { FC, useEffect } from "react"; import { FieldValues, useForm } from "react-hook-form"; import { useStore } from "../hooks/useStore"; import { KeyIcon, LoginIcon, TagIcon } from "./icons/Icons"; import styles from "./Layout.module.scss"; export const Layout: FC = () => { const { store, updateStore, onStoreEvent } = useStore(); const { register, handleSubmit, formState: { errors }, } = useForm(); function onTwitchAppSubmit({ clientId, clientSecret }: FieldValues) { updateStore({ isSubmitting: true, error: null }); window.Main.sendLogin({ type: "twitch", clientId, clientSecret }); } useEffect(() => { window.Main.onStore(onStoreEvent); }, []); return ( <div className={styles.root}> {/* <pre> <code>{JSON.stringify(store, null, 4)}</code> </pre> */} <form onSubmit={handleSubmit(onTwitchAppSubmit)}> <div className="status"> {store.isSubmitting ? ( <span> <div className={styles.spinner}> <div></div> </div> Logging in </span> ) : ( <span> <svg width="12" height="12" viewBox="0 0 8 8" fill="none" xmlns="http://www.w3.org/2000/svg" > <circle cx="4" cy="4" r="4" fill={store.isLoggedIn ? "var(--green)" : "var(--red)"} /> </svg>{" "} Logged {store.isLoggedIn ? "in" : "out"} </span> )} </div> <label htmlFor="clientId"> <span> <TagIcon width={14} height={14} /> Client ID </span> <input defaultValue="defaultValue" id="clientId" type="text" {...register("clientId", { required: true })} /> {errors.exampleRequired && <span>Client ID is required</span>} </label> <label htmlFor="clientSecret"> <span> <KeyIcon width={14} height={14} /> Client Secret </span> <input defaultValue="defaultValue" id="clientSecret" type="password" {...register("clientSecret", { required: true })} /> {errors.exampleRequired && <span>Client secret is required</span>} </label> <div> {store.isSubmitting ? ( <div>Please wait...</div> ) : ( <button type="submit"> <span> <LoginIcon width={16} height={16} /> Login </span> </button> )} </div> {store.error && <div className={styles.error}>{store.error}</div>} </form> </div> ); };
// // No26.swift // SwiftUI100 // // Created by 西田楓 on 2023/05/27. // import SwiftUI fileprivate struct Stone: Identifiable { let id = UUID() let name: String } struct No26: View { @State private var stones: [Stone] = [ Stone(name: "Cobblestone"), Stone(name: "Stone"), Stone(name: "Smooth Stone")] @State private var isShowingAlert: Bool = false @State private var alertEntity: AlertEntity? struct AlertEntity { let title: String let message: String let actionText: String } var body: some View { List(stones) { stone in Button(action: { alertEntity = AlertEntity(title: "Name", message: stone.name, actionText: "OK") isShowingAlert = true }) { Text(stone.name).foregroundColor(Color.black) }.alert(alertEntity?.title ?? "", isPresented: $isShowingAlert, presenting: alertEntity) { entity in Button(entity.actionText) { print(entity.actionText) } } message: { entity in Text(entity.message) } } } } struct No26_Previews: PreviewProvider { static var previews: some View { No26() } }
// // StorageManager.swift // MyCoreData // // Created by Kuat Bodikov on 26.01.2022. // import CoreData class StorageManager { static let shared = StorageManager() // MARK: - Core Data stack lazy var persistentContainer: NSPersistentContainer = { let container = NSPersistentContainer(name: "MyCoreData") container.loadPersistentStores(completionHandler: { (storeDescription, error) in if let error = error as NSError? { fatalError("Unresolved error \(error), \(error.userInfo)") } }) return container }() private var context: NSManagedObjectContext { persistentContainer.viewContext } private init() {} func fetchData() -> [Task] { let fetchRequest: NSFetchRequest<Task> = Task.fetchRequest() do { return try context.fetch(fetchRequest) } catch let error { print("Failed to fetch data", error) return [] } } func save(_ taskName: String, completion: (Task) -> Void) { let task = Task(context: context) task.name = taskName completion(task) saveContext() } func edit(_ task: Task, newTaskName: String) { task.name = newTaskName saveContext() } func delete(_ task: Task) { context.delete(task) saveContext() } // MARK: - Core Data Saving support func saveContext() { if context.hasChanges { do { try context.save() } catch { let nserror = error as NSError fatalError("Unresolved error \(nserror), \(nserror.userInfo)") } } } }
package com.example.eVoting.entities; import com.example.eVoting.enums.Gender; import javax.persistence.*; import lombok.Getter; import lombok.Setter; import lombok.extern.slf4j.Slf4j; import org.springframework.security.core.GrantedAuthority; import org.springframework.security.core.authority.SimpleGrantedAuthority; import org.springframework.security.core.userdetails.UserDetails; import java.time.LocalDate; import java.util.*; import java.util.stream.Collectors; @Entity @Table(name = "user", uniqueConstraints = @UniqueConstraint(columnNames = {"username"})) @Getter @Setter @Slf4j public class User implements UserDetails { @Id @GeneratedValue(strategy = GenerationType.AUTO) Integer id; @Column(name = "username") String username; @Column(name = "password") String password; @Column(name = "authToken") String authToken; @Column(name = "name") String name; @Column(name = "address") String address; @Column(name = "dob") LocalDate dob; @Column(name= "gender") @Enumerated(EnumType.STRING) Gender gender; @Column(name = "roles") String roles = ""; @Override public Collection<? extends GrantedAuthority> getAuthorities() { if(roles.isEmpty()) return new ArrayList<>(); return Arrays.stream(roles.split(",")).map(role -> new SimpleGrantedAuthority(role)).collect(Collectors.toList()); } @Override public boolean isAccountNonExpired() { return true; } @Override public boolean isAccountNonLocked() { return true; } @Override public boolean isCredentialsNonExpired() { return true; } @Override public boolean isEnabled() { return true; } }
<?php namespace App\Entity; use App\Repository\UserRepository; use Doctrine\Common\Collections\ArrayCollection; use Doctrine\Common\Collections\Collection; use Doctrine\DBAL\Types\Types; use Doctrine\ORM\Mapping as ORM; use Symfony\Bridge\Doctrine\Validator\Constraints\UniqueEntity; use Symfony\Component\Security\Core\User\PasswordAuthenticatedUserInterface; use Symfony\Component\Security\Core\User\UserInterface; #[ORM\Entity(repositoryClass: UserRepository::class)] #[ORM\UniqueConstraint(name: 'UNIQ_IDENTIFIER_EMAIL', fields: ['email'])] #[UniqueEntity(fields: ['email'], message: 'There is already an account with this email')] class User implements UserInterface, PasswordAuthenticatedUserInterface { #[ORM\Id] #[ORM\GeneratedValue] #[ORM\Column] private ?int $id = null; #[ORM\Column(length: 180)] private ?string $email = null; /** * @var list<string> The user roles */ #[ORM\Column] private array $roles = []; /** * @var string The hashed password */ #[ORM\Column] private ?string $password = null; #[ORM\Column(type: Types::DATETIME_MUTABLE)] private ?\DateTimeInterface $created_at = null; #[ORM\Column(type: Types::DATETIME_MUTABLE)] private ?\DateTimeInterface $updated_at = null; #[ORM\Column(length: 255)] private ?string $username = null; /** * @var Collection<int, Thread> */ #[ORM\OneToMany(targetEntity: Thread::class, mappedBy: 'user_id')] private Collection $threads; /** * @var Collection<int, Response> */ #[ORM\OneToMany(targetEntity: Response::class, mappedBy: 'user_id')] private Collection $responses; /** * @var Collection<int, Vote> */ #[ORM\OneToMany(targetEntity: Vote::class, mappedBy: 'user_id')] private Collection $votes; public function __construct() { $this->threads = new ArrayCollection(); $this->responses = new ArrayCollection(); $this->votes = new ArrayCollection(); } public function getId(): ?int { return $this->id; } public function getEmail(): ?string { return $this->email; } public function setEmail(string $email): static { $this->email = $email; return $this; } /** * A visual identifier that represents this user. * * @see UserInterface */ public function getUserIdentifier(): string { return (string) $this->email; } /** * @see UserInterface * * @return list<string> */ public function getRoles(): array { $roles = $this->roles; // guarantee every user at least has ROLE_USER $roles[] = 'ROLE_USER'; return array_unique($roles); } /** * @param list<string> $roles */ public function setRoles(array $roles): static { $this->roles = $roles; return $this; } /** * @see PasswordAuthenticatedUserInterface */ public function getPassword(): string { return $this->password; } public function setPassword(string $password): static { $this->password = $password; return $this; } /** * @see UserInterface */ public function eraseCredentials(): void { // If you store any temporary, sensitive data on the user, clear it here // $this->plainPassword = null; } public function getCreatedAt(): ?\DateTimeInterface { return $this->created_at; } public function setCreatedAt(\DateTimeInterface $created_at): static { $this->created_at = $created_at; return $this; } public function getUpdatedAt(): ?\DateTimeInterface { return $this->updated_at; } public function setUpdatedAt(\DateTimeInterface $updated_at): static { $this->updated_at = $updated_at; return $this; } public function getUsername(): ?string { return $this->username; } public function setUsername(string $username): static { $this->username = $username; return $this; } /** * @return Collection<int, Thread> */ public function getThreads(): Collection { return $this->threads; } public function addThread(Thread $thread): static { if (!$this->threads->contains($thread)) { $this->threads->add($thread); $thread->setUserId($this); } return $this; } public function removeThread(Thread $thread): static { if ($this->threads->removeElement($thread)) { // set the owning side to null (unless already changed) if ($thread->getUserId() === $this) { $thread->setUserId(null); } } return $this; } /** * @return Collection<int, Response> */ public function getResponses(): Collection { return $this->responses; } public function addResponse(Response $response): static { if (!$this->responses->contains($response)) { $this->responses->add($response); $response->setUserId($this); } return $this; } public function removeResponse(Response $response): static { if ($this->responses->removeElement($response)) { // set the owning side to null (unless already changed) if ($response->getUserId() === $this) { $response->setUserId(null); } } return $this; } /** * @return Collection<int, Vote> */ public function getVotes(): Collection { return $this->votes; } public function addVote(Vote $vote): static { if (!$this->votes->contains($vote)) { $this->votes->add($vote); $vote->setUserId($this); } return $this; } public function removeVote(Vote $vote): static { if ($this->votes->removeElement($vote)) { // set the owning side to null (unless already changed) if ($vote->getUserId() === $this) { $vote->setUserId(null); } } return $this; } }
/*Say you're an analyst at Parch & Posey and you want to see: each account who has a sales rep and each sales rep that has an account (all of the columns in these returned rows will be full) but also each account that does not have a sales rep and each sales rep that does not have an account (some of the columns in these returned rows will be empty)*/ select sr.name ,ac.name from sales_reps sr join accounts ac on sr.id=ac.sales_rep_id; ---using full outer join SELECT accounts.id,accounts.name,sales_reps.id, sales_reps.name FROM accounts FULL OUTER JOIN sales_reps ON accounts.sales_rep_id = sales_reps.id; /* To see rows where 1) Companies without sales rep OR 2)sales rep without accouts */ select sr.name ,ac.name from sales_reps sr full outer join accounts ac on sr.id=ac.sales_rep_id where ac.sales_rep_id is null or sr.id is null; /*Inequality Join write a query that left joins the accounts table and the sales_reps tables on each sale rep's ID number and joins it using the < comparison operator on accounts.primary_poc and sales_reps.name, like so: accounts.primary_poc < sales_reps.name The query results should be a table with three columns: the account name (e.g. Johnson Controls), the primary contact name (e.g. Cammy Sosnowski), and the sales representative's name (e.g. Samuel Racine)*/ select ac.name as account_name, ac.primary_poc as primary_contact_name, sr.name as sales_rep_name from accounts ac left join sales_reps sr on ac.sales_rep_id = sr.id where ac.primary_poc < sr.name order by 3 ; ----A comparison operator returns a boolean, either TRUE, FALSE or NULL.a string less than another one comes before in dictionary order /*Getting list of web events which happens one day duration one after another*/ SELECT we1.id AS we_id, we1.account_id AS we1_account_id, we1.occured_at AS we1_occured_at, we1.channel AS we1_channel, we2.id AS we2_id, we2.account_id AS we2_account_id, we2.occured_at AS we2_occured_at, we2.channel AS we2_channel FROM web_events we1 LEFT JOIN web_events we2 ---using the same table : self join ON we1.account_id = we2.account_id AND we1.occured_at > we2.occured_at ----comparing the timestamp AND we1.occured_at <= we2.occured_at + INTERVAL '1 day' ----if we1 is less than or equal to we2, then add a day ORDER BY we1.account_id, we2.occured_at; /* UNION ALL vs UNION */ /*Nice! UNION only appends distinct values. More specifically, when you use UNION, the dataset is appended, and any rows in the appended table that are exactly identical to rows in the first table are dropped. If you’d like to append all the values from the second table, use UNION ALL. You’ll likely use UNION ALL far more often than UNION.*/ select a.id from accounts a union select o.account_id from orders o; select * from accounts as tb1 where tb1.name like 'Walmart' UNION select * from accounts as tb2 where tb2.name like 'Walmart'; ----returned only one value select * from accounts as tb1 where tb1.name like 'Walmart' UNION ALL select * from accounts as tb2 where tb2.name like 'Disney'; -- returned two values for walmart select id from region where id = '3' union all select id from sales_reps where region_id= '3'; /*---- here id for region is region_id, but id for sales_reps is sales_reps_id hence when we use union all, its returning the id values from both tables, even though they reprsent different value sets*/ /*Perform the union in your first query (under the Appending Data via UNION header) in a common table expression and name it double_accounts. Then do a COUNT the number of times a name appears in the double_accounts table. If you do this correctly, your query results should have a count of 2 for each name.*/ with double_accounts as (select * from accounts a1 union all select * from accounts a2) select count(*) ,name from double_accounts group by name; ---351 rows
// Global // Local // Local // Local // You can define variables with same names at different scopes // Called variable shadowing let name = 'Brian'; if (true) { let name = 'Mike'; if (true) { console.log(name); name = 'Jen' console.log(name); } } if (true) { console.log(name); } // In example below JS creates a global variable for word becuase it keeps going higher and not finding it // This is called a leaked global // It's why we always define with a let/ const if (true) { if (true) { word = 'Jenny' console.log(word); } } if (true) { console.log(word); }
### Why is sleep important? ### Sleep restores children physically. It helps them learn and remember things, and it boosts immunity. And sleep helps children grow. For example, children’s bodies produce growth hormone when they’re asleep. Children of all ages need to get enough sleep so they can play, learn and concentrate during the day. ### Sleep at different ages ### Babies, children and teenagers need different amounts of sleep. For example, as babies and children get older, the amount of sleep they need slowly decreases. Also, sleep patterns change as babies and children get older. For example, as babies get older, they begin to sleep less during the day and more at night. ### Babies under 6 months: when and how much they sleep ### #### Newborns #### Newborns sleep on and off during the day and night. They sleep for 14-17 hours in every 24 hours. They have 2 different kinds of sleep – active sleep and quiet sleep. In active sleep your baby moves around. You might see jerking, twitching or sucking. In quiet sleep your baby is still and breathing evenly. Newborns move through active and quiet sleep in cycles that last about 40 minutes. They might wake up after a sleep cycle and need help getting back to sleep. #### Babies 3-6 months #### By 3 months, babies start to develop night and day sleep patterns, and they tend to start sleeping more during the night. Babies usually sleep for 12-15 hours in every 24 hours. At 3-6 months, babies might start moving towards a pattern of 2-3 daytime sleeps of up to 2 hours each. They often wake at least once overnight. ### Babies 6-12 months: when and how much they sleep #### #### Sleep during the night #### As babies develop, more of their sleep happens at night. At this age, most babies are ready for bed between 6 pm and 10 pm. They usually take less than 40 minutes to get to sleep, but about 1 in 10 babies takes longer. Babies might be having long sleeps of 6 hours at night by the time they’re 6 months old. Almost two-thirds of babies wake only once during the night and need an adult to settle them back to sleep. About 1 in 10 babies calls out 3-4 times a night. More than a third of parents say their babies have problems with sleep at this age. #### Sleep during the day #### Most babies aged 6-12 months still have 1-2 daytime naps. These naps usually last 30 minutes to 2 hours. ### Toddlers: when and how much they sleep ### Toddlers need 11-14 hours of sleep every 24 hours. Usually this is a sleep of 10-12 hours a night, and a nap of 1-2 hours during the day. Some toddlers aren’t keen on going to bed at night. Often this is because they’d like to stay up with the family. This is the most common sleep problem reported by parents. It peaks around 18 months and improves with age. Less than 5% of 2-year-olds wake 3 or more times overnight. ### Preschoolers: when and how much they sleep ### Children aged 3-5 years need 10-13 hours of sleep a night. Some preschoolers might also have day naps that last for about an hour. When preschoolers get enough sleep overnight, they won’t need these naps anymore. ### School-age children: when and how much they sleep ### Children aged 5-11 years need 9-11 hours of sleep a night. Children over 5 years of age rarely nap during the day. If your child often needs daytime naps, it’s good to check they’re getting enough sleep overnight. See your GP if you have concerns. Primary school-age children are usually tired after school and might look forward to bedtime from about 7.30 pm. ### Teenagers: when and how much they sleep ### Children entering puberty generally need about 8-10 hours of sleep a night. Changes to the circadian rhythm during adolescence mean it’s normal for teenagers to want to go to bed later at night – often around 11 pm or later – then get up later in the morning. Good daytime habits and sleep environment habits can help teenagers get enough sleep. ### About sleep cycles ### We all cycle between different types of sleep during the night and during long naps. From about 6 months of age, a sleep cycle contains: - rapid eye movement (REM) sleep - non-REM sleep. In REM sleep, your eyeballs flicker from side to side underneath your eyelids. REM sleep is also called dream sleep. Non-REM sleep consists of deep sleep and light sleep. It’s harder to wake children who are in deep sleep, whereas children in light sleep wake up easily. The amount of REM and non-REM sleep in a cycle changes throughout the night. It’s also common to wake briefly between sleep cycles. ### How sleep cycles affect children’s sleep ### Children have a lot of deep non-REM sleep in the first few hours after they fall asleep. That’s why children sleep so soundly in the first few hours after they’ve gone to bed and are rarely disturbed by anything. Children have more REM sleep and light non-REM sleep in the second half of the night. Children wake more easily from these kinds of sleep, so they might wake up more during this time than at the beginning of the night. In the early childhood years, sleep cycles get longer as children get older. In children aged 3 years, sleep cycles are about 60 minutes. By about 5 years, sleep cycles have matured to the adult length of about 90 minutes.
"use client"; import { type PropsWithChildren, createContext, useState, type FC, } from "react"; import { noopFn } from "~/utils/common"; export type OverlayContextType = { isVisible: boolean; toggleVisible: (newState?: boolean) => void; }; export const OverlayContext = createContext<OverlayContextType>({ isVisible: false, toggleVisible: noopFn, }); const OverlayContextProvider: FC<PropsWithChildren> = ({ children }) => { const [isVisible, setIsVisible] = useState(false); function toggleVisible(newState?: boolean) { setIsVisible((prev) => newState ?? !prev); } return ( <OverlayContext.Provider value={{ isVisible, toggleVisible }}> {children} </OverlayContext.Provider> ); }; export default OverlayContextProvider; OverlayContext.displayName = "OverlayContext";
<template> <div style="width:100%;"> <h3 class="title" style="text-align:left;margin:0 auto 10px">游戏付费分析-图形</h3> <el-row :gutter="24"> <div class="userOptiondiv"> <el-col :xs="24" :sm="6" :lg="4"> <el-date-picker v-model="searchbegin" align="right" size="small" type="date" value-format="yyyy-MM-dd" format="yyyy-MM-dd" placeholder="请输入执行时间" clearable></el-date-picker> </el-col> <el-col :xs="24" :sm="8" :lg="2"> <el-button size="small" type="primary" @click="initChart()">查询</el-button> </el-col> </div> </el-row> <div :id="id" :style="{width: width, height: height}" class="showchart"></div> </div> </template> <script> import echarts from "echarts"; import westeros from "./theme/westeros"; export default { name: "lineEcharts", props: { id: { type: String, default: "myChart" }, width: { type: String, default: "100%" }, height: { type: String, default: "100%" } }, data() { return { searchbegin:this.moment(new Date()).format("YYYY-MM-DD"), chart: null }; }, mounted() { this.initChart(); }, watch: { // options:{ // handler(options){ // ths.chart.setOption(this.options) // }, // deep:true // } // seriesData(val){ // this.setOptions({series:val}) // } }, methods: { initChart() { let begindate = this.moment(this.searchbegin).subtract(1,'months').format('YYYY-MM-DD'); this.chart = echarts.init(document.getElementById(this.id), "westeros"); let param={ spreaderId:"", beginTime:begindate, endTime:this.searchbegin} this.$api.channelTopUp(param).then(res =>{ if (res.success) { this.setOptions(res.data); } else { this.$message({ message: res.message, type: "error" }); } }).catch(err =>{ this.$message({ message: '请求失败!', type: "error" }); }) }, setOptions(data) { let points = new Array(); //X轴时间 let newUsers = []; //新增设备 let payAmount = []; //充值金额 let payUsers = []; //充值人数 var payCount = []; //充值次数 let that=this; let xvalue=""; $.each(data, function(key, val) { xvalue=that.moment(val.insertTime).format("MM月DD"); points[key] = [xvalue]; newUsers.push(val.newUserPayUserCount); payAmount.push(val.payAmount); payUsers.push(val.payUserCount); payCount.push(val.paycount); }); this.chart.setOption({ title: { text: "",//游戏付费分析折线图 }, tooltip: { trigger: "axis" }, legend: { data: ["充值金额", "充值人数", "充值次数", "推广用户数"] }, grid: { left: "8%", right: "10%", bottom: "3%", containLabel: true }, toolbox: { }, xAxis: { type: "category", boundaryGap: false, data: points, }, yAxis: [ { type: "value", name:"充值金额", axisLabel: { formatter: '{value}', }, position:'left', axisTick: { inside:'false', length:10, }, }, { type: 'value', name: '充值人数', axisLabel: { formatter: '{value}', }, position:'left', axisTick: {show:false}, offset:80, splitNumber:10, }, { type: 'value', name: '充值次数', axisLabel: { formatter: '{value}', }, position:'right', }, { type: 'value', name: '推广用户数', axisLabel: { formatter: '{value}', }, position:'right', offset:80, splitNumber:10, } ], series: [ { name: "充值金额", type: "line", data: payAmount, smooth:true }, { name: "充值人数", type: "line", yAxisIndex: 1, data: payUsers }, { name: "充值次数", type: "line", yAxisIndex: 2, data: payCount }, { name: "推广用户数", type: "line", data: newUsers, yAxisIndex: 3, } ] }); } } }; </script> <style scoped> .el-date-editor.el-input, .el-date-editor.el-input__inner{ width:100%; } .showchart{ width:100%; float: left; position: relative; min-height:300px; margin-bottom:1%; margin-top:1%; } .userOptiondiv{ width:100%; float: left; } .el-button{ margin-bottom: 10px; } </style>
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <title>Reveal Events on Scroll</title> <link rel="stylesheet" href="style.css" /> </head> <body> <section> <h2>Scroll to Reveal</h2> </section> <div class="container"></div> <script> for (let i = 1; i <= 60; i++) { let box = document.createElement("div"); box.classList.add("box"); document.querySelector(".container").appendChild(box); } //adding random color to the boxes let randomColorBlock = document.querySelectorAll('.box'); function addColor(){ randomColorBlock.forEach(e => { e.style.background = randomColor(); }) } function randomColor(){ let chars = "123456789abcdef" let colorLength = 6; let color = ""; for(let i =1; i<=colorLength; i++){ let randomColors= Math.floor(Math.random() * chars.length); color += chars.substring(randomColors, randomColors+ 1); } return "#" +color } addColor(); let boxes = document.querySelectorAll('.box'); function scrollTrigger() { boxes.forEach(boxxx => { if (boxxx.offsetTop < window.scrollY) { boxxx.classList.add('active'); } else { boxxx.classList.remove('active'); } }); } window.addEventListener("scroll", scrollTrigger); </script> </body> </html>
import { Injectable, HttpException, HttpStatus } from '@nestjs/common'; import { UserService } from '../user/user.service'; import { JwtService } from '@nestjs/jwt'; import argon2 from 'argon2'; import { AuthResponseDTO } from './dtos/register-response.dto'; import { CreateUserDTO } from '../user/dtos/createuser.dto'; import { LoginUserDTO } from './dtos/loginuser.dto'; /** * Authenication Service Class */ @Injectable() export class AuthService { constructor( private usersService: UserService, private jwtService: JwtService, ) {} /** * Logins auth service * @param loginDTO * @returns jwt token */ async login(loginDTO: LoginUserDTO) { return new Promise(async (resolve, reject) => { try { const user = await this.usersService.findOne(loginDTO.userName); if (user == null) { throw new HttpException('User Not Existed', HttpStatus.BAD_REQUEST); } else { if (await argon2.verify(user.password, loginDTO.password)) { const payload = { username: user.userName, sub: user.id }; const token = this.jwtService.sign(payload); resolve(new AuthResponseDTO(token)); } } } catch (error) { reject(error); } }); } /** * Registers auth service * @param createUserDTO * @returns jwt token */ async register(createUserDTO: CreateUserDTO) { return new Promise(async (resolve, reject) => { try { const user = await this.usersService.create(createUserDTO); const payload = { username: user.userName, sub: user.id }; const token = this.jwtService.sign(payload); resolve(new AuthResponseDTO(token)); } catch (error) { reject(error); } }); } }
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <title>Document</title> </head> <body> <div id="app"> <my-component></my-component> </div> <div id="app2"> <my-component></my-component> </div> <script src="vue/vue.js"></script> <script> //全局组件 Vue.component("my-component", { template: '<h2 @click="change()">love coding {{msg}}</h2>', // data函数 data() { return { msg: 0, }; }, methods: { change() { this.msg++; }, }, }); new Vue({ el: "#app", }); new Vue({ el: "#app2", }); </script> </body> </html>
"use strict"; var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } return new (P || (P = Promise))(function (resolve, reject) { function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } step((generator = generator.apply(thisArg, _arguments || [])).next()); }); }; var __importDefault = (this && this.__importDefault) || function (mod) { return (mod && mod.__esModule) ? mod : { "default": mod }; }; Object.defineProperty(exports, "__esModule", { value: true }); const mongoose_1 = __importDefault(require("mongoose")); const data_generator_retail_1 = __importDefault(require("data-generator-retail")); const DummyProducts = require("../Model/dummyProductModel"); // Correcting the import path to your schema file function generateDummyProducts(num) { return __awaiter(this, void 0, void 0, function* () { try { mongoose_1.default.Promise = global.Promise; mongoose_1.default.set("strictQuery", false); mongoose_1.default .connect("mongodb+srv://dbVue:[email protected]/test", { // useNewUrlParser: true, }) .then(() => { // console.log("Database Admin Portal Connected"); }) .catch((err) => { console.log("Could not connect to the database", err); process.exit(); }); for (let i = 0; i < num; i++) { const existingProduct = yield DummyProducts.findOne({ $or: [ { productId: `Product-${i + 1}` }, { productName: `Dummy Product ${i + 1}` }, ], }); if (existingProduct) { console.log(`Product with name/ID already exists. No need to create.`); } else { const data = (0, data_generator_retail_1.default)(); for (const product of data.products) { const dummyProduct = new DummyProducts({ productId: product.id, productName: product.reference, productPrice: `$ ${product.price}`, productImage: product.image, }); yield dummyProduct.save(); } console.log(`Product Created`); } } // dummyMongoose.disconnect(); } catch (error) { console.error("Error generating dummy products:", error); } }); } module.exports = generateDummyProducts;
// ignore_for_file: public_member_api_docs, sort_constructors_first import 'dart:convert'; import 'tv_series_model.dart'; class TvResponse { final List<TvModel> tvList; TvResponse({required this.tvList}); factory TvResponse.fromMap(Map<String, dynamic> map) { return TvResponse( tvList: List.from( map['results'].map<TvModel>( (x) => TvModel.fromMap(x as Map<String, dynamic>), ), ), ); } factory TvResponse.fromJson(String source) => TvResponse.fromMap(json.decode(source) as Map<String, dynamic>); }
package com.example.cs310_project; import static android.content.Intent.getIntent; import android.content.SharedPreferences; import android.os.Bundle; import android.util.Log; import android.widget.Button; import androidx.annotation.Nullable; import androidx.appcompat.app.AppCompatActivity; import androidx.appcompat.widget.Toolbar; import androidx.lifecycle.ViewModelProvider; import androidx.recyclerview.widget.LinearLayoutManager; import androidx.recyclerview.widget.RecyclerView; import java.util.Collections; import java.util.List; import retrofit2.Call; import retrofit2.Callback; import retrofit2.Response; import retrofit2.Retrofit; import retrofit2.converter.gson.GsonConverterFactory; public class SportPlacesActivity extends AppCompatActivity { private List<SportPlace> sportPlaces; private RecyclerView recyclerView; private SportPlaceAdapter adapter; private boolean sortRatingAscending = true; private boolean sortDistanceAscending = true; @Override protected void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_sport_places); recyclerView = findViewById(R.id.recyclerViewSportPlaces); LinearLayoutManager layoutManager = new LinearLayoutManager(this); recyclerView.setLayoutManager(layoutManager); sportPlaces = getIntent().getParcelableArrayListExtra("sportPlaces"); getDistancesForSportPlaces(sportPlaces); Button backButton = findViewById(R.id.button_back); backButton.setOnClickListener(view -> { onBackPressed(); }); adapter = new SportPlaceAdapter(sportPlaces); recyclerView.setAdapter(adapter); Button sortRatingButton = findViewById(R.id.button_sort_rating); Button sortDistanceButton = findViewById(R.id.button_sort_distance); sortRatingButton.setOnClickListener(v -> sortRating()); sortDistanceButton.setOnClickListener(v -> sortDistance()); } @Override protected void onResume() { super.onResume(); refreshAverageRatings(); } private void refreshAverageRatings() { for (SportPlace sportPlace : sportPlaces) { fetchUpdatedRating(sportPlace); } } private void fetchUpdatedRating(SportPlace sportPlace) { ApiService apiService = ApiClient.getClient().create(ApiService.class); Call<Double> call = apiService.getAverageRatingOfSportPlace(sportPlace.getId()); call.enqueue(new Callback<Double>() { @Override public void onResponse(Call<Double> call, Response<Double> response) { if (response.isSuccessful()) { double updatedRating = response.body(); sportPlace.setScore(updatedRating); adapter.notifyDataSetChanged(); } } @Override public void onFailure(Call<Double> call, Throwable t) { // Handle the failure case } }); } private void sortRating() { // Sorting logic for rating Collections.sort(sportPlaces, (sp1, sp2) -> sortRatingAscending ? Float.compare((float) sp1.getScore(), (float) sp2.getScore()) : Float.compare((float) sp2.getScore(), (float) sp1.getScore())); sortRatingAscending = !sortRatingAscending; adapter.notifyDataSetChanged(); } private void sortDistance() { Collections.sort(sportPlaces, (sp1, sp2) -> { float distance1 = parseDistance(sp1.getDistance()); float distance2 = parseDistance(sp2.getDistance()); return sortDistanceAscending ? Float.compare(distance1, distance2) : Float.compare(distance2, distance1); }); sortDistanceAscending = !sortDistanceAscending; adapter.notifyDataSetChanged(); } private float parseDistance(String distanceStr) { try { return Float.parseFloat(distanceStr.split(" ")[0]); } catch (NumberFormatException e) { Log.e("ParseError", "Failed to parse distance", e); return Float.MAX_VALUE; // Return a large value on parse failure } } private void getDistancesForSportPlaces(List<SportPlace> sportPlaces) { // Create a Retrofit instance Retrofit retrofit = new Retrofit.Builder() .baseUrl("https://maps.googleapis.com/") .addConverterFactory(GsonConverterFactory.create()) .build(); GoogleMapsApiService googleMapsApiService = retrofit.create(GoogleMapsApiService.class); for (SportPlace sportPlace : sportPlaces) { String apiKey = ""; // API KEY NEEDED SharedPreferences sharedPreferences = getSharedPreferences("GeocodeVerisi", MODE_PRIVATE); String origin = sharedPreferences.getString("firstPlaceId", "default_value_if_not_found"); origin="place_id:"+origin; Log.i("BAKALIM SHARED MISAN",origin); String destination = "place_id:"+sportPlace.getGoogleMapsLink(); Log.i("BAKALIM DEST MISAN",destination); Call<DistanceMatrixResponse> call = googleMapsApiService.getDistanceAndDuration(destination, origin, apiKey); call.enqueue(new Callback<DistanceMatrixResponse>() { @Override public void onResponse(Call<DistanceMatrixResponse> call, Response<DistanceMatrixResponse> response) { if (response.isSuccessful()) { DistanceMatrixResponse matrixResponse = response.body(); Log.d("LÜTFEN DISTANCE NE OLUR", String.valueOf(response)); if (matrixResponse != null && matrixResponse.getRows().size() > 0) { DistanceMatrixRow row = matrixResponse.getRows().get(0); if (row.getElements().size() > 0) { DistanceMatrixElement element = row.getElements().get(0); Distance distance = element.getDistance(); if (distance != null) { int distanceValue = distance.getValue(); float distanceInKm = distanceValue / 1000f; // Convert to kilometers String formattedDistance = String.format("%.1f", distanceInKm); // Format to one decimal place formattedDistance=formattedDistance+" km"; sportPlace.setDistance(formattedDistance); } else { sportPlace.setDistance(""); } // RecyclerView'ı güncellemek için adapter.notifyDataSetChanged() kullanın adapter.notifyDataSetChanged(); } } } } @Override public void onFailure(Call<DistanceMatrixResponse> call, Throwable t) { // Hata durumunu ele alın } }); } } }
<template> <div class="animated fadeIn"> <vue-element-loading :active="blockLoader" spinner="bar-fade-scale" color="#F06292" size="50" /> <!-- TAB FORM BEGIN --> <b-card no-body v-show="isForm"> <validation-observer ref="observer" v-slot="{ handleSubmit }"> <b-form @submit.stop.prevent="handleSubmit(onSubmit)"> <b-row> <b-col sm="12"> <b-card> <div slot="header"> <span class="font-weight-bold">{{formCaption}}</span> <small>{{ (form.isEdit) ? "Edit" : "New" }}</small> <div right style="float:right;"> <b-button variant="red" v-b-modal.modal-void-reason v-if="actionButton.AllowVoid" > <font-awesome-icon :icon="['fas', 'ban']" v-b-tooltip.hover title="Void this Transaction" />&nbsp;Void </b-button> <b-button variant="green" @click="clickPosting" v-if="actionButton.AllowPosting" v-b-tooltip.hover title="Posting this Transaction" > <font-awesome-icon :icon="['fas', 'check-circle']" />&nbsp;Posting </b-button> <b-button v-if="form.model.DocumentNo != ''" @click="onModalShowDistJournal" v-b-tooltip.hover title="View Distribution Journal" > <font-awesome-icon :icon="['fas', 'balance-scale']" /> </b-button> <b-button variant="blue" type="submit" v-if="actionButton.AllowSave"> <font-awesome-icon :icon="['fas', 'save']" />&nbsp;Save </b-button> <b-button @click="onFormClose"> <font-awesome-icon :icon="['fas', 'window-close']" danger />&nbsp;Close </b-button> </div> </div> <b-row> <!-- BEGIN FORM --> <b-col sm="10"> <b-row> <b-col sm="3"> <label>Document Date</label> <b-input-group> <b-form-input v-model="form.display.DocumentDate" type="text" :placeholder="dateFormatString" class="text-center" size="sm" readonly aria-describedby="doc-date-feedback" ></b-form-input> <b-input-group-append v-if="actionButton.AllowEdit"> <b-form-datepicker v-model="form.model.TransactionDate" button-only size="sm" left locale="en-US" @input="dateChanged" :min="minCalendarDate" :max="maxCalendarDate" dark ></b-form-datepicker> </b-input-group-append> </b-input-group> </b-col> <b-col sm="4"> <b-form-group> <label for="DocumentNo" class="text-center">General Journal Entry No</label> <b-form-input name="Document No" type="text" placeholder="Document No" v-model="form.model.DocumentNo" class="text-center font-weight-bold" readonly variant="blue" size="sm" /> </b-form-group> </b-col> </b-row> <b-row> <b-col sm="3"> <b-card sm="12" style="margin:0; padding:0;"> <b-row> <b-col> <label>Currency Code</label> <validation-provider name="Currency Code" :rules="{ required: true }" v-slot="validationContext" > <b-input-group prepend> <b-form-input v-model="form.model.CurrencyCode" class="font-weight-bold text-center" :state="validateState(validationContext)" readonly size="sm" aria-describedby="currency-code-feedback" ></b-form-input> <b-input-group-append v-if="actionButton.AllowEdit && !form.isEdit" > <b-button variant="outline-primary" size="sm" @click="onModalSearchCurrency('CurrencyCode','CurrencyName')" > <font-awesome-icon :icon="['fas', 'search']"></font-awesome-icon> </b-button> </b-input-group-append> <b-form-invalid-feedback id="currency-code-feedback" >{{ validationContext.errors[0] }}</b-form-invalid-feedback> </b-input-group> </validation-provider> </b-col> </b-row> <b-row> <b-col class="mt-3"> <label> Rate Amount <code>{{form.model.IsMultiply ? "*" : "/"}}</code> </label> <validation-provider name="Currency Code" :rules="{ required: true, min_value:1 }" v-slot="validationContext" > <b-input-group :prepend="form.display.CurrencySymbol" size="sm"> <money v-model="form.model.ExchangeRate" v-bind="moneyOptions" style="width:100px;" size="sm" :state="validateState(validationContext)" :class="validationContext.errors.length == 0 ? 'currency-money-field is-valid' : 'currency-money-field is-invalid'" disabled aria-describedby="rate-amount-feedback" ></money> <b-input-group-append v-if="(form.model.TransactionDate != '' && form.model.CurrencyCode != '' && (form.FunctionalCurrency != form.model.CurrencyCode)) && actionButton.AllowEdit" > <b-button variant="outline-primary" size="sm" @click="openModalExchangeRate" > <font-awesome-icon :icon="['fas', 'arrow-right']"></font-awesome-icon> </b-button> </b-input-group-append> <b-form-invalid-feedback class="is-invalid" id="rate-amount-feedback" >{{ validationContext.errors[0] }}</b-form-invalid-feedback> </b-input-group> </validation-provider> </b-col> </b-row> </b-card> </b-col> <b-col sm="9"> <b-card sm="12" style="margin:0; padding:0;"> <b-row> <b-col sm="4"> <b-form-group> <label for="SourceDocument">Source Document</label> <b-form-select v-model="form.model.SourceDocument" :options="[{value:'',text:'---'},{value:'ASSET',text:'ASSET'},{value:'RECEIVABLE',text:'RECEIVABLE'},{value:'PAYABLE',text:'PAYABLE'}]" size="sm" :disabled="!actionButton.AllowEdit" /> </b-form-group> </b-col> </b-row> <b-row> <b-col> <label for="Description">Description</label> <validation-provider name="Description" :rules="{ required: true }" v-slot="validationContext" > <b-form-textarea name="Description" placeholder="Description" v-model="form.model.Description" :state="validateState(validationContext)" size="sm" aria-describedby="description-feedback" :readonly="!actionButton.AllowEdit" /> <b-form-invalid-feedback id="description-feedback" >{{ validationContext.errors[0] }}</b-form-invalid-feedback> </validation-provider> </b-col> </b-row> </b-card> </b-col> </b-row> </b-col> <!-- END FORM --> <!-- BEGIN DOCUMENT STATUS --> <b-col sm="2"> <label class="font-weight-bold text-uppercase"> <code>Branch</code> </label> <b-form-select :disabled="!actionButton.AllowEdit" v-model="form.model.BranchCode" size="sm" :options="companyBranches" plain class="form-control bg-warning text-dark font-weight-bold" value-field="BranchCode" html-field="BranchCode" ></b-form-select> <b-input-group> <b-button class="mt-4 px-2 bg-dark text-white form-control" @click="openToastDocumentStatus" pill v-b-tooltip.hover title="Document Status" > <font-awesome-icon :icon="['fas', 'bell']" size="sm" />&nbsp; <span class="text-uppercase"> <code>{{form.display.DocumentStatus}}</code> </span> </b-button> </b-input-group> </b-col> <!-- END DOCUMENT STATUS --> </b-row> <b-row class="mb-2"> <b-col> <b-button variant="yellow" size="sm" type="button" @click="onModalAddCOA" v-if="actionButton.AllowEdit" > <font-awesome-icon :icon="['fas', 'plus']" />&nbsp;Add Account </b-button> </b-col> </b-row> <!-- TABLE DETAIL BEGIN --> <b-row> <b-col sm="12" class="table-responsive"> <table id="table-detail" width="100%" class="table-light table-striped table-hover table-bordered" > <thead> <tr> <th class="text-center" rowspan="2" style="vertical-align:middle;"> <font-awesome-icon :icon="['fas', 'ellipsis-h']" /> </th> <th class="text-left" width="210">ACCOUNT NO</th> <th class="text-left">ACCOUNT NAME</th> <th class="text-center" width="220">ORIGINATING DEBIT</th> <th class="text-center" width="220">ORIGINATING CREDIT</th> </tr> <tr> <th class="text-left" colspan="2">DESCRIPTION</th> <th class="text-center">FUNCTIONAL DEBIT</th> <th class="text-center">FUNCTIONAL CREDIT</th> </tr> </thead> <tbody class="position-relative"> <template v-for="(item, itemIndex) in form.dataDetails"> <tr> <td rowspan="2" class="text-center"> <a href="javascript:;" style="text-decoration:none;color:red;" @click="deleteRowDetail(itemIndex)" v-if="actionButton.AllowEdit" > <font-awesome-icon size="lg" :icon="['fas', 'trash']" variant="danger" /> </a> <span v-else>{{itemIndex+1}}</span> </td> <td> <b-form-input type="text" size="sm" v-model="item.AccountId" readonly /> </td> <td> <b-form-input type="text" size="sm" v-model="item.AccountDescription" readonly autocomplete="false" /> </td> <td class="text-center"> <money v-model="item.OriginatingDebit" v-bind="moneyOptions" size="sm" :disabled="item.OriginatingCredit>0 || !actionButton.AllowEdit" class="currency-money-field" ></money> </td> <td class="text-center"> <money v-model="item.OriginatingCredit" v-bind="moneyOptions" size="sm" :disabled="item.OriginatingDebit>0 || !actionButton.AllowEdit" class="currency-money-field" ></money> </td> </tr> <tr> <td colspan="2" style="border-top:0px;"> <b-form-input type="text" size="sm" v-model="item.Description" placeholder="Some description here" :readonly="!actionButton.AllowEdit" /> </td> <td class="text-center" style="border-top:0px;"> <money v-model="item.FunctionalDebit" v-bind="moneyOptions" size="sm" class="currency-money-field" disabled ></money> </td> <td class="text-center" style="border-top:0px;"> <money v-model="item.FunctionalCredit" v-bind="moneyOptions" size="sm" class="currency-money-field" disabled ></money> </td> </tr> </template> </tbody> <tfoot> <tr> <th class="text-right" colspan="3">ORIGINATING TOTAL</th> <th class="text-center"> <money v-model="form.display.OriginatingDebitAmount" v-bind="moneyOptions" size="sm" class="currency-money-field" disabled ></money> </th> <th class="text-center"> <money v-model="form.display.OriginatingCreditAmount" v-bind="moneyOptions" size="sm" class="currency-money-field" disabled ></money> </th> </tr> <tr> <th class="text-right" colspan="3">FUNCTIONAL TOTAL</th> <th class="text-center"> <money v-model="form.display.FunctionalDebitAmount" v-bind="moneyOptions" size="sm" class="currency-money-field" disabled ></money> </th> <th class="text-center"> <money v-model="form.display.FunctionalCreditAmount" v-bind="moneyOptions" size="sm" class="currency-money-field" disabled ></money> </th> </tr> </tfoot> </table> </b-col> </b-row> <!-- TABLE DETAIL END --> </b-card> </b-col> </b-row> </b-form> </validation-observer> </b-card> <!-- TAB FORM END --> <!-- TAB GRID/LIST BEGIN --> <b-tabs pills card v-show="!isForm" v-model="tabularStep"> <!-- TAB PROGRESS BEGIN --> <b-tab active @click="isTabMain=true"> <template v-slot:title> <font-awesome-icon :icon="['fas', 'tasks']" />&nbsp;Progress </template> <b-row> <b-col cols="12" sm="12"> <b-card width="100%"> <DataGrid ref="gridProgress" :fields="this.$store.state.features.finance.journal_entry.progress.headers" :items="this.$store.state.features.finance.journal_entry.progress.data" :info="this.$store.state.features.finance.journal_entry.progress.listInfo" :baseUrl="this.$store.state.features.finance.journal_entry.progress.baseUrl" :actGetData="handleGetProgress" :actCreate="onFormCreate" :actEditRow="handleEdit" :actDeleteRow="handleDelete" addTableClasses="table-bordered" :disableNewButton="!this.$store.state.roleaccess.AllowNew" :isEdit="this.$store.state.roleaccess.AllowEdit" :isDelete="this.$store.state.roleaccess.AllowDelete" responsive items-per-page-select loading hover sorter pagination column-filter caption="List of General Journal Entry - Progress" ></DataGrid> </b-card> </b-col> </b-row> </b-tab> <!-- TAB PROGRESS END --> <!-- TAB HISTORY BEGIN --> <b-tab @click="isTabMain=false"> <template v-slot:title> <font-awesome-icon :icon="['fas', 'history']" />&nbsp;History </template> <b-card-text> <b-row> <b-col cols="12" sm="12"> <b-card width="100%"> <DataGrid ref="gridHistory" :fields="this.$store.state.features.finance.journal_entry.history.headers" :items="this.$store.state.features.finance.journal_entry.history.data" :info="this.$store.state.features.finance.journal_entry.history.listInfo" :baseUrl="this.$store.state.features.finance.journal_entry.history.baseUrl" :actGetData="handleGetHistory" :actEditRow="handleEdit" addTableClasses="table-bordered" responsive items-per-page-select loading hover sorter pagination column-filter caption="List of General Journal Entry - History" disableNewButton :isDelete="false" :isEdit="false" historical ></DataGrid> </b-card> </b-col> </b-row> </b-card-text> </b-tab> <!-- TAB HISTORY END --> </b-tabs> <!-- TAB GRID/LIS END --> <CurrencyModal ref="dlgCurrency" :actSelectedRow="onSelectedCurrency"></CurrencyModal> <AccountModal ref="dlgCOA" :actSelectedRow="onSelectedCOA" :noDirectEntry="true"></AccountModal> <ExchangeRateModal ref="dlgExchangeRate" :actSelectedRow="onSelectedExchangeRate"></ExchangeRateModal> <DistributionJournalModal ref="dlgDistJournal"></DistributionJournalModal> <b-modal id="modal-void-reason" ref="modal-void" title="Please type your reason to VOID " @show="resetModal" @hidden="resetModal" @ok="handleOk" @cancel="handleCancel" > <form ref="formvoid" @submit.stop.prevent="handleVoid"> <b-row> <b-col sm="6"> <label>Void Date</label> <b-input-group> <b-form-input v-model="form.display.VoidDate" type="text" :placeholder="dateFormatString" class="text-center" size="sm" readonly aria-describedby="doc-date-feedback" ></b-form-input> <b-input-group-append v-if="actionButton.AllowVoid && (form.model.TransactionDate != maxVoidCalendarDate)" > <b-form-datepicker v-model="form.model.VoidDate" button-only size="sm" left @input="dateChangedVoid" :min="form.model.TransactionDate" :max="maxVoidCalendarDate" dark ></b-form-datepicker> </b-input-group-append> </b-input-group> </b-col> </b-row> <b-row class="mt-2"> <b-col> <b-form-group :state="voidState" label="Reason" label-for="name-input" invalid-feedback="Reason must not empty" > <b-form-input id="name-input" v-model="form.VoidReason" :state="voidState" autocomplete="false" required ></b-form-input> </b-form-group> </b-col> </b-row> </form> </b-modal> <!-- BEGIN DOCUMENT STATUS --> <b-toast id="document-status-toaster" variant="warning" solid> <template v-slot:toast-title> <div class="d-flex flex-grow-1 align-items-baseline"> <b-img blank blank-color="green" class="mr-2" width="12" height="12"></b-img> <strong class="mr-auto">{{form.display.DocumentStatus}}</strong> <small class="text-muted mr-2"></small> </div> </template> <p>Created By :&nbsp;{{form.display.CreatedByName}}&nbsp;on&nbsp;{{form.display.CreatedDate}}</p> </b-toast> <!-- END DOCUMENT STATUS --> </div> </template> <script> import DataGrid from "@/components/Tables/DataGrid"; import SelectGrid from "@/components/tables/SelectGrid"; import VueElementLoading from "vue-element-loading"; import { CurrencyModal, AccountModal, ExchangeRateModal, DistributionJournalModal } from "@/pages/modal/index.js"; import { mask } from "vue-the-mask"; import moment from "moment"; import util from "@/helper/utils"; import loginServices from '../../services/loginservices' import cloneDeep from "lodash.cloneDeep"; export default { name: "GeneralJournal", layout: "dashboard", components: { DataGrid, SelectGrid, VueElementLoading, CurrencyModal, AccountModal, ExchangeRateModal, DistributionJournalModal }, directives: { mask }, data() { return { actionButton: { AllowSave: true, AllowEdit: true, AllowPosting: false, AllowVoid: false }, companyBranches : [], tabularStep: 0, minCalendarDate: moment().format("YYYY-01-01"), maxCalendarDate: moment().endOf('month').format("YYYY-MM-DD"), dateFormatString: "DD/MM/YYYY", isTabMain: true, formCaption: "General Journal Entry", caption: "General Journal Entry", blockLoader: false, isForm: false, moneyOptions: { decimal: ",", thousands: ".", prefix: "", suffix: "", precision: 0, masked: false, allowBlank: false, min: 0 //max: Number.MAX_SAFE_INTEGER }, perPage: 10, voidState: null, form: { valid: false, isEdit: false, defaultRateType: 0, FunctionalCurrency: "", model: { JournalEntryHeaderId: "", TransactionDate: moment().format("YYYY-MM-DD"), BranchCode : "", DocumentNo: "", CurrencyCode: "", ExchangeRate: 0, SourceDocument: "", Description: "", OriginatingTotal: 0, FunctionalTotal: 0, Status: 1, RequestEntryDetails: Array, IsMultiply: true, VoidDate: moment().format("YYYY-MM-DD"), }, dataDetails: [], display: { DocumentDate: moment().format("DD/MM/YYYY"), CurrencySymbol: "", OriginatingDebitAmount: 0, OriginatingCreditAmount: 0, FunctionalDebitAmount: 0, FunctionalCreditAmount: 0, DocumentStatus: "", CreatedName: "", CreatedDate: "", StatusComment: "", VoidDate: moment().format("DD/MM/YYYY"), }, status: { VoidName: "", VoidDate: moment().format("DD/MM/YYYY"), }, VoidReason: "" } }; }, watch: { "form.model.ExchangeRate"(newVal) { this.doCalculateDetails(); }, "form.dataDetails": { handler: function (after, before) { this.doCalculateDetails(); }, deep: true } }, async mounted() { //OBTAIN MINIMUM CALENDAR INPUT let minimumInputDate = await this.$store.dispatch( "features/finance/constants/actGetMinInputDateFinancial" ); if (minimumInputDate != undefined){ this.minCalendarDate = moment(minimumInputDate).format("YYYY-MM-DD"); this.companyBranches = cloneDeep(this.$store.state.features.finance.constants .companyBranches); let selectedBranch = this.companyBranches.filter(x=>x.Default); if(selectedBranch != undefined) this.form.model.BranchCode = selectedBranch[0].BranchCode; } await this.$store.dispatch( "features/company/financial_setup/actGet", "FinancialSetup?" ); await this.$store.dispatch( "features/finance/journal_entry/progress/actGetData", "GetJournalEntryProgress?" ); await this.$store.dispatch( "features/finance/journal_entry/history/actGetData", "GetJournalEntryHistory?" ); if (this.$refs.gridProgress != null) { await this.$refs.gridProgress.doRefresh(); } await this.initDefaultForm(); }, computed: { maxVoidCalendarDate() { let trxDate = moment(this.form.model.TransactionDate, 'YYYY-MM-DD'); if (moment() <= trxDate) { return this.form.model.TransactionDate } else { return moment().format('YYYY-MM-DD') } }, }, methods: { showLoader(val) { if (!val) { setTimeout(() => { this.blockLoader = false; }, 300); } else { this.blockLoader = val; } }, async initDefaultForm() { var financialSetup = this.$store.state.features.company.financial_setup .data; if (Array.isArray(financialSetup) && financialSetup.length) { financialSetup = financialSetup[0]; this.form.FunctionalCurrency = financialSetup.FuncCurrencyCode; this.form.defaultRateType = financialSetup.DefaultRateType; //OBTAIN DEFAULT CURRENCY SETTINGS if (this.form.model.CurrencyCode != "") { await this.$store.dispatch( "features/company/currency/actGetCurrency", "currency?CurrencyCode=" + this.form.model.CurrencyCode ); let currencySetup = this.$store.state.features.company.currency.data; if (Array.isArray(currencySetup)) { currencySetup = currencySetup[0]; this.moneyOptions.precision = currencySetup.DecimalPlaces; this.form.model.ExchangeRate = 1; this.form.display.CurrencySymbol = currencySetup.Symbol; } } await this.changeCurrentExchangeRate(); } }, async changeCurrentExchangeRate(rateType) { this.form.model.ExchangeRate = 1; //OBTAIN DEFAULT EXCHANGE RATE AMOUNT if (this.form.model.CurrencyCode != "" && this.form.defaultRateType > 0) { await this.$store.dispatch( "features/company/exchange_rate_header/actGetCurrentExchangeRate", "GetCurrentExchangeRate?CurrencyCode=" + this.form.model.CurrencyCode + "&TransactionDate=" + this.form.model.TransactionDate + "&RateType=" + this.form.defaultRateType ); this.form.model.ExchangeRate = this.$store.state.features.company.exchange_rate_header.dataExcRate; this.form.model.IsMultiply = this.$store.state.features.company.exchange_rate_header.dataExcIsMultiply; } }, async dateChanged() { this.form.display.DocumentDate = ""; if (this.form.model.TransactionDate != null) this.form.display.DocumentDate = moment( this.form.model.TransactionDate ).format(this.dateFormatString); await this.changeCurrentExchangeRate(); }, async dateChangedVoid() { this.form.display.VoidDate = ""; if (this.form.model.VoidDate != null) this.form.display.VoidDate = moment( this.form.model.VoidDate ).format(this.dateFormatString); }, handleToast(toastTitle, style, message) { this.$bvToast.toast(message, { title: toastTitle != "" ? toastTitle : "Confirmation", variant: style != "" ? style : "info", //toaster: 'b-toaster-bottom-center', autoHideDelay: 5000, appendToast: false }); }, async doCalculateDetails() { let orgTotal = 0, funcTotal = 0; let rate = this.form.model.ExchangeRate; let isMultiply = this.form.model.IsMultiply; let orgSubtotalDebit = 0, orgSubtotalCredit = 0; let funcSubtotalDebit = 0, funcSubtotalCredit = 0; if ( Array.isArray(this.form.dataDetails) && this.form.dataDetails.length ) { this.form.dataDetails.forEach(function (detail) { if (isMultiply) { detail.FunctionalDebit = rate * detail.OriginatingDebit; detail.FunctionalCredit = rate * detail.OriginatingCredit; } else { detail.FunctionalDebit = (detail.OriginatingDebit / rate); detail.FunctionalCredit = (detail.OriginatingCredit / rate); } orgTotal += detail.OriginatingDebit; funcTotal += detail.FunctionalDebit; orgSubtotalDebit += detail.OriginatingDebit; orgSubtotalCredit += detail.OriginatingCredit; funcSubtotalDebit += detail.FunctionalDebit; funcSubtotalCredit += detail.FunctionalCredit; }); } this.form.display.OriginatingDebitAmount = orgSubtotalDebit; this.form.display.OriginatingCreditAmount = orgSubtotalCredit; this.form.display.FunctionalDebitAmount = funcSubtotalDebit; this.form.display.FunctionalCreditAmount = funcSubtotalCredit; this.form.model.OriginatingTotal = orgTotal; this.form.model.FunctionalTotal = funcTotal; }, validateState({ dirty, validated, valid = null }) { return dirty || validated ? valid : null; }, async handleGetProgress(url) { await this.$store.dispatch( "features/finance/journal_entry/progress/actGetData", url ); await loginServices.doLoginCompany(this.$store.state.user, this.$store.state.companySecurity, this.$store.state.token.replace('Bearer ', "")) }, async handleGetHistory(url) { await this.$store.dispatch( "features/finance/journal_entry/history/actGetData", url ); await loginServices.doLoginCompany(this.$store.state.user, this.$store.state.companySecurity, this.$store.state.token.replace('Bearer ', "")) }, async onModalSearchCurrency(row) { this.$refs.dlgCurrency .open(row, this.form.model[row]) .then(res => { console.log(res); }) .catch(res => { console.log(res); }); }, async onSelectedCurrency(item, modelReff) { this.form.model[modelReff] = item.CurrencyCode if (item.DecimalPlaces != undefined) this.moneyOptions.precision = item.DecimalPlaces this.form.display.CurrencySymbol = item.Symbol if (item.CurrencyCode != this.form.FunctionalCurrency) { await this.changeCurrentExchangeRate() } else { this.form.model.ExchangeRate = 1 this.form.model.IsMultiply = true } }, async openModalExchangeRate(row) { this.$refs.dlgExchangeRate .open( this.form.model.CurrencyCode, this.form.model.TransactionDate, this.form.defaultRateType, this.moneyOptions, this.form.model.ExchangeRate ) .then(res => { //console.log(res); }) .catch(res => { //console.log(res); }); }, async onSelectedExchangeRate(item) { if (item != undefined) this.form.model.ExchangeRate = item.ExchangeRateAmount; this.form.model.IsMultiply = item.CalcIsMultiply; this.doCalculateDetails(); }, async onModalAddCOA() { this.$refs.dlgCOA .open() .then(res => { console.log(res); }) .catch(res => { console.log(res); }); }, async onSelectedCOA(row) { this.form.dataDetails.push({ Index: this.form.dataDetails.length, JournalEntryDetailId: "", AccountId: row.AccountId, AccountDescription: row.Description, OriginatingDebit: 0, FunctionalDebit: 0, OriginatingCredit: 0, FunctionalCredit: 0, Description: "", Status: 1 }); }, async deleteRowDetail(index) { this.$bvModal .msgBoxConfirm("Are you sure ?", { title: "Delete Confirmation", size: "sm", buttonSize: "sm", okVariant: "blue", centered: true, headerClass: "p-1 border-bottom-0", footerClass: "p-1 border-top-0" }) .then(ok => { if (ok) { this.form.dataDetails.splice(index, 1); } }) .catch(err => { // An error occurred }); }, async onFormClose() { this.ErrorMessage = ""; this.isForm = false; this.form.isEdit = false; this.resetForm(); }, resetForm() { this.form.model.JournalEntryHeaderId = null; this.form.model.TransactionDate = moment().format("YYYY-MM-DD"); this.form.display.DocumentDate = moment().format(this.dateFormatString); this.form.model.DocumentNo = ""; this.form.model.CurrencyCode = ""; this.form.model.ExchangeRate = 0; this.form.model.SourceDocument = ""; this.form.model.Description = ""; this.form.model.OriginatingTotal = 0; this.form.model.FunctionalTotal = 0; this.form.model.Status = 1; this.form.model.IsMultiply = true; let selectedBranch = this.companyBranches.filter(x=>x.Default); if(selectedBranch != undefined) this.form.model.BranchCode = selectedBranch[0].BranchCode; this.form.model.RequestEntryDetails = this.form.dataDetails = []; this.form.display.CurrencySymbol = ""; this.form.display.OriginatingDebitAmount = 0; this.form.display.OriginatingCreditAmount = 0; this.form.display.FunctionalDebitAmount = 0; this.form.display.FunctionalCreditAmount = 0; this.moneyOptions.precision = 0; this.form.display.CreatedName = ""; this.form.display.CreatedDate = ""; this.form.status.VoidName = ""; this.form.status.VoidDate = ""; this.form.display.StatusComment = ""; this.actionButton.AllowSave = true this.actionButton.AllowEdit = true this.actionButton.AllowPosting = false this.actionButton.AllowVoid = false this.initDefaultForm(); this.$nextTick(() => { this.$refs.observer.reset(); }); }, async onFormCreate() { this.resetForm(); this.form.display.DocumentStatus = "NEW"; this.form.isEdit = false; this.isForm = true; }, async handleEdit(row) { this.isForm = true; //BINDING EDITTED DATA this.form.model.JournalEntryHeaderId = row.JournalEntryHeaderId; this.form.model.TransactionDate = moment(row.TransactionDate).format( "YYYY-MM-DD" ); this.form.display.DocumentDate = moment( this.form.model.TransactionDate ).format(this.dateFormatString); this.form.model.DocumentNo = row.DocumentNo; this.form.model.CurrencyCode = row.CurrencyCode; this.form.model.ExchangeRate = row.ExchangeRate; this.form.model.SourceDocument = row.SourceDocument; this.form.model.Description = row.Description; this.form.model.OriginatingTotal = row.OriginatingTotal; this.form.model.FunctionalTotal = row.FunctionalTotal; this.form.model.Status = util.docStatus(row.Status); this.form.model.BranchCode = row.BranchCode; this.form.model.IsMultiply = row.IsMultiply; this.form.model.VoidDate = this.form.model.TransactionDate; this.moneyOptions.precision = row.DecimalPlaces; this.form.display.DocumentStatus = row.Status; this.form.display.StatusComment = row.StatusComment; this.form.display.VoidDate = this.form.display.DocumentDate; this.form.status.VoidName = row.VoidByName; this.form.status.VoidDate = row.VoidDate != undefined ? moment(row.VoidDate).format('DD/MM/YYYY HH:mm:ss') : ''; this.form.display.CreatedByName = row.CreatedName; this.form.display.CreatedDate = moment(row.CreatedDate).format('DD/MM/YYYY HH:mm:ss'); this.form.display.CurrencySymbol = ""; //ACTIVATE BUTTONS if (this.form.model.JournalEntryHeaderId != '' && this.form.model.DocumentNo != '') { if (this.form.model.Status == util.docStatus('New')) { this.actionButton.AllowEdit = true this.actionButton.AllowSave = true this.actionButton.AllowPosting = true this.actionButton.AllowVoid = false } else if (this.form.model.Status == util.docStatus('posted')) { this.actionButton.AllowVoid = true this.actionButton.AllowSave = false this.actionButton.AllowEdit = false this.actionButton.AllowPosting = false } else { this.actionButton.AllowVoid = false this.actionButton.AllowSave = false this.actionButton.AllowEdit = false this.actionButton.AllowPosting = false } } else { this.actionButton.AllowSave = true this.actionButton.AllowEdit = true this.actionButton.AllowPosting = false; this.actionButton.AllowVoid = false; } var details = await this.$store.dispatch( "features/finance/journal_entry/detail/actGetData", row.JournalEntryHeaderId ); let arrDetails = []; if (details.length) { details.forEach(function (row, index) { arrDetails.push({ Index: index, JournalEntryDetailId: row.JournalEntryDetailId, AccountId: row.AccountId, AccountDescription: row.AccountDescription, OriginatingDebit: row.OriginatingDebit, OriginatingCredit: row.OriginatingCredit, FunctionalDebit: row.FunctionalDebit, FunctionalCredit: row.FunctionalCredit, Description: row.Description, Status: row.Status }); }); } this.form.dataDetails = arrDetails; this.form.isEdit = true; }, async doDelete(row) { this.showLoader(true); await this.$store.dispatch("features/finance/journal_entry/progress/actDelete", row); var response = this.$store.state.features.finance.journal_entry.progress.resultDelete; if (response.status != 200) { this.handleToast( "Confirmation", "danger", response.data.ErrorDescription != null ? response.data.ErrorDescription : "Delete failed." ); } else { this.$refs.gridProgress.doRefresh(); this.handleToast("Confirmation", "success", response.data.Message); } this.showLoader(false); }, async handleDelete(row) { this.$bvModal .msgBoxConfirm("Are you sure ?", { title: "Delete Confirmation", size: "sm", buttonSize: "sm", okVariant: "blue", centered: true, headerClass: "p-1 border-bottom-0", footerClass: "p-1 border-top-0" }) .then(ok => { if (ok) { this.doDelete(row); } }) .catch(err => { // An error occurred }); }, validateForm() { let valid = true; if ( this.form.display.OriginatingDebitAmount <= 0 || this.form.display.OriginatingCreditAmount <= 0 ) { valid = false; this.handleToast( "Warning", "danger", "Originating amount must not 0 (zero) !" ); } if ( this.form.display.FunctionalDebitAmount <= 0 || this.form.display.FunctionalCreditAmount <= 0 ) { valid = false; this.handleToast( "Warning", "danger", "Functional amount must not 0 (zero) !" ); } if ( this.form.display.OriginatingDebitAmount != this.form.display.OriginatingCreditAmount ) { valid = false; this.handleToast( "Warning", "danger", "Originating Debit amount MUST equal with Originating Credit amount !" ); } if ( this.form.display.FunctionalDebitAmount != this.form.display.FunctionalCreditAmount ) { valid = false; this.handleToast( "Warning", "danger", "Functional Debit amount MUST equal with Functional Credit amount !" ); } return valid; }, async onSubmit() { if (this.validateForm()) { this.showLoader(true); this.form.dataDetails.forEach(function(item,index){ item.RowIndex = index+1; }); this.form.model.RequestEntryDetails = this.form.dataDetails; if (this.form.isEdit) { await this.$store.dispatch( "features/finance/journal_entry/progress/actUpdate", this.form.model ); var response = this.$store.state.features.finance.journal_entry .progress.resultUpdate; if (response.status != 200) { this.handleToast( "Confirmation", "danger", response.data.ErrorDescription != undefined ? response.data.ErrorDescription : "Update failed !" ); } else { this.isForm = false; this.form.isEdit = false; this.$refs.gridProgress.doRefresh(); this.handleToast("Confirmation", "success", "Successfully updated"); } } else { await this.$store.dispatch( "features/finance/journal_entry/progress/actCreate", this.form.model ); var response = this.$store.state.features.finance.journal_entry .progress.resultCreate; if (response.status != 200) { this.handleToast( "Confirmation", "danger", response.data.ErrorDescription != undefined ? response.data.ErrorDescription : "Submit failed !" ); } else { this.isForm = false; this.form.isEdit = false; this.$refs.gridProgress.doRefresh(); this.handleToast("Confirmation", "success", "Successfully saved"); } } this.showLoader(false); } }, async doPostingJournal(row) { if (this.validateForm()) { this.showLoader(true); this.form.model.Reason = ""; this.form.dataDetails.forEach(function(item,index){ item.RowIndex = index+1; }); this.form.model.RequestEntryDetails = this.form.dataDetails; await this.$store.dispatch("features/finance/journal_entry/progress/actPosting", this.form.model); var response = this.$store.state.features.finance.journal_entry.progress.resultUpdate; if (response.status != 200) { this.handleToast( "Confirmation", "danger", response.data.ErrorDescription != null ? response.data.ErrorDescription : "Delete failed." ); } else { this.isForm = false; this.form.isEdit = false; this.$refs.gridProgress.doRefresh(); this.$refs.gridHistory.doRefresh(); this.handleToast("Confirmation", "success", response.data.Message); } this.showLoader(false); } }, async clickPosting(index) { this.$bvModal .msgBoxConfirm("Posting " + this.form.model.DocumentNo + " ? (make sure you already save all your changes)", { title: "Posting Journal Confirmation", size: "md", buttonSize: "sm", okVariant: "blue", okTitle: 'YES', cancelTitle: 'NO', centered: true, headerClass: "p-2 border-bottom-0", footerClass: "p-2 border-top-0", hideHeaderClose: false, }) .then(ok => { if (ok) { this.doPostingJournal(index); } }) .catch(err => { // An error occurred }); }, async doVoidJournal(row) { this.showLoader(true); this.form.model.Reason = this.form.VoidReason; await this.$store.dispatch("features/finance/journal_entry/progress/actVoid", this.form.model); var response = this.$store.state.features.finance.journal_entry.progress.resultUpdate; if (response.status != 200) { this.handleToast( "Confirmation", "danger", response.data.ErrorDescription != null ? response.data.ErrorDescription : "Delete failed." ); } else { this.isForm = false; this.form.isEdit = false; this.$refs.gridHistory.doRefresh(); this.handleToast("Confirmation", "success", response.data.Message); } this.showLoader(false); }, /* VOID MODAL */ resetModal() { this.form.VoidReason = '' this.voidState = null }, checkFormValidity() { const valid = this.$refs.formvoid.checkValidity() this.voidState = valid return valid }, handleOk(bvModalEvt) { // Prevent modal from closing bvModalEvt.preventDefault() // Trigger submit handler this.handleVoid() }, handleCancel(bvModalEvt) { this.resetModal(); // Prevent modal from closing this.$bvModal.hide('modal-void-reason') }, handleVoid() { // Exit when the form isn't valid if (!this.checkFormValidity()) { return } // Push the name to submitted names this.doVoidJournal(); // Hide the modal manually this.$nextTick(() => { this.$bvModal.hide('modal-void-reason') }) }, async onModalShowDistJournal(row) { this.$refs.dlgDistJournal .open(this.form.model.DocumentNo) .then(res => { console.log(res); }) .catch(res => { console.log(res); }); }, async openToastDocumentStatus(){ this.$bvToast.show('document-status-toaster'); }, } }; </script> <style scoped> #table-detail thead th { font-size: 12px; border: 1px solid #cfd8dc; padding: 5px; background-color: #f5f5f5; } #table-detail tbody td { font-size: 12px; border-left: 0.5px solid #cfd8dc; border-right: 0.5px solid #cfd8dc; border-bottom: 1px solid #cfd8dc; padding: 3px; background-color: white; } #table-detail tfoot th { font-size: 12px; border: 1px solid #cfd8dc; padding: 5px; background-color: #f5f5f5; } .v-money { width: 200px; } #table-detail input:disabled { background-color: #e8eaf6; cursor: text; margin: 0em; border: 1px solid #c2cfd6; } @media only screen and (max-width: 1024px) { h5 { font-size: 14px; } #table-detail thead th { font-size: 10px; border: 1px solid #cfd8dc; padding: 5px; background-color: #f5f5f5; } #table-detail tbody td { font-size: 10px; border-left: 0.5px solid #cfd8dc; border-right: 0.5px solid #cfd8dc; border-bottom: 1px solid #cfd8dc; padding: 3px; background-color: white; } #table-detail tfoot th { font-size: 10px; border: 1px solid #cfd8dc; padding: 5px; background-color: #f5f5f5; } .v-money { width: 200px; } #table-detail input:disabled { background-color: #e8eaf6; cursor: text; margin: 0em; border: 1px solid #c2cfd6; } } </style>
package api import ( "errors" "net/http" "github.com/gin-gonic/gin" ) // HealthCheck godoc // @Summary Health check // @Description always returns OK // @Tags health // @Produce json // @Success 200 {object} string // @Failure 500 // @Router /health [get] func handleHealthCheck(c *gin.Context) { if true { c.Error(errors.New("non fatal error")) c.AbortWithError(http.StatusInternalServerError, errors.New("a fatal error")) return } c.JSON(http.StatusOK, gin.H{ "status": "ok", "code": http.StatusOK, }) } // HealthCheck godoc // @Summary Gets something public from the database // @Description Using postgres Gets a public entity from the db and returns it plain // @Tags get // @Produce json // @Success 200 {object} string // @Failure 500 // @Router /v1/public/get-something/:id [get] func handleGetPublicSomething(c *gin.Context, app App) { pg := app.DB().PgStore result := pg.GetSomethingByID(c, 1) c.JSON(http.StatusOK, gin.H{ "status": "ok", "code": http.StatusOK, "response": result, }) } func handleGetPrivateSomething(c *gin.Context, app App) {}
import React, { useCallback, useContext } from "react" import { ProductContext } from "./ProductCard" import styles from '../styles/styles.module.css' export interface Props { className?: string style?: React.CSSProperties } export const ProductButtons = ({className, style}: Props) => { const { counter, increaseBy, maxCount } = useContext(ProductContext) const isMaxReached = useCallback(() => !!maxCount && counter === maxCount, [counter, maxCount]) return ( <div className={`${styles.buttonsContainer} ${className}`} style={style}> <button className={styles.buttonMinus} onClick={() => increaseBy(-1)}>-</button> <div className={styles.countLabel}>{counter}</div> <button className={`${styles.buttonAdd} ${isMaxReached() && styles.disabled}`} onClick={() => increaseBy(1)}>+</button> </div> ) }
#include <stdio.h> #include <string.h> #include <stdint.h> #include <stdlib.h> #ifdef DEBUG_OUTPUT #define debug(...) printf(__VA_ARGS__) #else #define debug(...) #endif struct queue_entity_t { int n; int prev_index; int next_index; }; struct queue_t { struct queue_entity_t queue_pool[1001]; int queue_head_index; int queue_tail_index; }; void remove_queue(struct queue_t * queue, int index) { if (index == queue->queue_tail_index) { #ifdef DEBUG_QUEUE debug("update tail index: %d -> %d\n", queue->queue_tail_index, queue->queue_pool[index].prev_index); #endif queue->queue_tail_index = queue->queue_pool[index].prev_index; } if (index == queue->queue_head_index) { #ifdef DEBUG_QUEUE debug("update head index: %d -> %d\n", queue->queue_head_index, queue->queue_pool[index].next_index); #endif queue->queue_head_index = queue->queue_pool[index].next_index; } if (queue->queue_pool[index].prev_index != -1) { #ifdef DEBUG_QUEUE debug("update next index (%d): %d -> %d\n", queue->queue_pool[index].prev_index, queue->queue_pool[queue->queue_pool[index].prev_index].next_index, queue->queue_pool[index].next_index); #endif queue->queue_pool[queue->queue_pool[index].prev_index].next_index = queue->queue_pool[index].next_index; } if (queue->queue_pool[index].next_index != -1) { #ifdef DEBUG_QUEUE debug("update prev index (%d): %d -> %d\n", queue->queue_pool[index].next_index, queue->queue_pool[queue->queue_pool[index].next_index].prev_index, queue->queue_pool[index].prev_index); #endif queue->queue_pool[queue->queue_pool[index].next_index].prev_index = queue->queue_pool[index].prev_index; } } void insert_queue(struct queue_t * queue, int after, int before, int index) { if (queue->queue_head_index == -1 && queue->queue_tail_index == -1) { #ifdef DEBUG_QUEUE debug("update head index: %d -> %d\n", queue->queue_head_index, index); #endif queue->queue_head_index = index; #ifdef DEBUG_QUEUE debug("update tail index: %d -> %d\n", queue->queue_tail_index, index); #endif queue->queue_tail_index = index; queue->queue_pool[index].prev_index = -1; queue->queue_pool[index].next_index = -1; } else { if (after != -1) { #ifdef DEBUG_QUEUE debug("update next index (%d): %d -> %d\n", index, -1, queue->queue_pool[after].next_index); #endif queue->queue_pool[index].next_index = queue->queue_pool[after].next_index; #ifdef DEBUG_QUEUE debug("update next index (%d): %d -> %d\n", after, queue->queue_pool[after].next_index, index); #endif queue->queue_pool[after].next_index = index; #ifdef DEBUG_QUEUE debug("update prev index (%d): %d -> %d\n", index, queue->queue_pool[after].prev_index, after); #endif queue->queue_pool[index].prev_index = queue->queue_tail_index; if (after == queue->queue_tail_index) { #ifdef DEBUG_QUEUE debug("update tail index: %d -> %d\n", queue->queue_tail_index, index); #endif queue->queue_tail_index = index; } else { #ifdef DEBUG_QUEUE debug("update prev index (%d): %d -> %d\n", queue->queue_pool[index].next_index, queue->queue_pool[queue->queue_pool[index].next_index].prev_index, index); #endif queue->queue_pool[queue->queue_pool[index].next_index].prev_index = index; } } else if (before != -1) { #ifdef DEBUG_QUEUE debug("update prev index (%d): %d -> %d\n", index, -1, queue->queue_pool[before].prev_index); #endif queue->queue_pool[index].prev_index = queue->queue_pool[before].prev_index; #ifdef DEBUG_QUEUE debug("update prev index (%d): %d -> %d\n", before, queue->queue_pool[before].prev_index, index); #endif queue->queue_pool[before].prev_index = index; #ifdef DEBUG_QUEUE debug("update next index (%d): %d -> %d\n", index, queue->queue_pool[index].next_index, before); #endif queue->queue_pool[index].next_index = before; if (before == queue->queue_head_index) { #ifdef DEBUG_QUEUE debug("update head index: %d -> %d\n", queue->queue_head_index, index); #endif queue->queue_head_index = index; } else { #ifdef DEBUG_QUEUE debug("update next index (%d): %d -> %d\n", queue->queue_pool[index].prev_index, queue->queue_pool[queue->queue_pool[index].prev_index].next_index, index); #endif queue->queue_pool[queue->queue_pool[index].prev_index].next_index = index; } } } } struct context_t { int n; int k; struct queue_t in_queue; struct queue_t out_queue; }; struct context_t context; void solve(struct context_t * ctx) { int result = 0; int k = 0; int index = ctx->in_queue.queue_head_index; while (index != -1) { if (((++k) % ctx->k) == 0) { remove_queue(&ctx->in_queue, index); insert_queue(&ctx->out_queue, ctx->out_queue.queue_tail_index, -1, index); } index = ctx->in_queue.queue_pool[index].next_index; if (index == -1) { index = ctx->in_queue.queue_head_index; } } printf("<"); index = ctx->out_queue.queue_head_index; while (index != -1) { if (index == ctx->out_queue.queue_tail_index) { printf("%d", ctx->out_queue.queue_pool[index].n); } else { printf("%d, ", ctx->out_queue.queue_pool[index].n); } index = ctx->out_queue.queue_pool[index].next_index; } printf(">\n"); } void init_data(struct context_t * ctx) { memset(ctx, 0, sizeof(struct context_t)); memset(&ctx->in_queue, -1, sizeof(ctx->in_queue)); memset(&ctx->out_queue, -1, sizeof(ctx->out_queue)); scanf("%d%d", &ctx->n, &ctx->k); for (int n = 1; n <= ctx->n; n++) { ctx->out_queue.queue_pool[n].n = n; ctx->in_queue.queue_pool[n].n = n; ctx->in_queue.queue_pool[n].prev_index = n - 1; ctx->in_queue.queue_pool[n].next_index = n + 1; } ctx->in_queue.queue_pool[1].prev_index = -1; ctx->in_queue.queue_pool[ctx->n].next_index = -1; ctx->in_queue.queue_head_index = 1; ctx->in_queue.queue_tail_index = ctx->n; } int main(int argc, char ** argv) { int t = 1; //scanf("%d", &t); for (int i = 0; i < t; i++) { init_data(&context); solve(&context); } return 0; }
package com.hadoop.study.spark.sql import org.apache.spark.SparkConf import org.apache.spark.sql.expressions.Aggregator import org.apache.spark.sql.{Encoder, Encoders, SparkSession, functions} import scala.collection.mutable import scala.collection.mutable.ListBuffer /** * <B>说明:描述</B> * * @author zak.wu * @version 1.0.0 * @date 2021/5/28 16:35 */ object SparkSQL_Hive3 { def main(args: Array[String]): Unit = { // 设置环境变量 System.setProperty("HADOOP_USER_NAME", "zak") // 创建SparkSQL的运行环境 val sparkConf = new SparkConf().setMaster("local[*]").setAppName("SparkSQL_Hive3") val spark = SparkSession.builder().enableHiveSupport().config(sparkConf).getOrCreate() spark.sql("use spark_sql") // 查询基本数据 spark.sql( """ | select | action.*, | info.product_name, | city.area, | city.city_name | from user_visit_action action | join product_info info on action.click_product_id = info.product_id | join city_info city on action.city_id = city.city_id | where action.click_product_id > -1 """.stripMargin).createOrReplaceTempView("t1") // 根据区域,商品进行数据聚合 spark.udf.register("remark", functions.udaf(new RemarkAggregator())) spark.sql( """ | select | area, | product_name, | count(*) as clickCnt, | remark(city_name) as city_remark | from t1 group by area, product_name """.stripMargin).createOrReplaceTempView("t2") // 区域内对点击数量进行排行 spark.sql( """ | select | *, | rank() over( partition by area order by clickCnt desc ) as rank | from t2 """.stripMargin).createOrReplaceTempView("t3") // 取前3名 spark.sql( """ | select | * | from t3 where rank <= 3 """.stripMargin).show(false) spark.close() } case class Buffer(var total: Long, var cityMap: mutable.Map[String, Long]) // 自定义聚合函数:实现城市备注功能 // 1. 继承Aggregator, 定义泛型 // IN : 城市名称 // BUF : Buffer =>【总点击数量,Map[(city, cnt), (city, cnt)]】 // OUT : 备注信息 // 2. 重写方法(6) class RemarkAggregator extends Aggregator[String, Buffer, String] { // 缓冲区初始化 override def zero: Buffer = { Buffer(0, mutable.Map[String, Long]()) } // 更新缓冲区数据 override def reduce(buff: Buffer, city: String): Buffer = { buff.total += 1 val newCount = buff.cityMap.getOrElse(city, 0L) + 1 buff.cityMap.update(city, newCount) buff } // 合并缓冲区数据 override def merge(buff1: Buffer, buff2: Buffer): Buffer = { buff1.total += buff2.total val map1 = buff1.cityMap val map2 = buff2.cityMap // 两个Map的合并操作 // buff1.cityMap = map1.foldLeft(map2) { // case ( map, (city, cnt) ) => { // val newCount = map.getOrElse(city, 0L) + cnt // map.update(city, newCount) // map // } // } map2.foreach { case (city, cnt) => val newCount = map1.getOrElse(city, 0L) + cnt map1.update(city, newCount) } buff1.cityMap = map1 buff1 } // 将统计的结果生成字符串信息 override def finish(buff: Buffer): String = { val remarks = ListBuffer[String]() val totalcnt = buff.total val cityMap = buff.cityMap // 降序排列 val cityCntList = cityMap.toList.sortWith( (left, right) => { left._2 > right._2 } ).take(2) val hasMore = cityMap.size > 2 var rsum = 0L cityCntList.foreach { case (city, cnt) => val r = cnt * 100 / totalcnt remarks.append(s"${city} ${r}%") rsum += r } if (hasMore) { remarks.append(s"其他 ${100 - rsum}%") } remarks.mkString(", ") } override def bufferEncoder: Encoder[Buffer] = Encoders.product override def outputEncoder: Encoder[String] = Encoders.STRING } }
import enum import cocotb from cocotb.binary import BinaryValue from cocotb.triggers import Lock, RisingEdge, ReadOnly from cocotb_bus.drivers import BusDriver class AXIBurst(enum.IntEnum): FIXED = 0b00 INCR = 0b01 WRAP = 0b10 class AXIxRESP(enum.IntEnum): OKAY = 0b00 EXOKAY = 0b01 SLVERR = 0b10 DECERR = 0b11 class AXIProtocolError(Exception): def __init__(self, message: str, xresp: AXIxRESP): super().__init__(message) self.xresp = xresp class AXIReadBurstLengthMismatch(Exception): pass class AXI4Agent(BusDriver): ''' AXI4 Agent Monitors an internal memory and handles read and write requests. ''' _signals = [ "ARREADY", "ARVALID", "ARADDR", # Read address channel "ARLEN", "ARSIZE", "ARBURST", "ARPROT", "RREADY", "RVALID", "RDATA", "RLAST", # Read response channel "AWREADY", "AWADDR", "AWVALID", # Write address channel "AWPROT", "AWSIZE", "AWBURST", "AWLEN", "WREADY", "WVALID", "WDATA", ] # Not currently supported by this driver _optional_signals = [ "WLAST", "WSTRB", "BVALID", "BREADY", "BRESP", "RRESP", "RCOUNT", "WCOUNT", "RACOUNT", "WACOUNT", "ARLOCK", "AWLOCK", "ARCACHE", "AWCACHE", "ARQOS", "AWQOS", "ARID", "AWID", "BID", "RID", "WID" ] def __init__(self, entity, name, clock, memory, callback=None, event=None, big_endian=False, **kwargs): BusDriver.__init__(self, entity, name, clock, **kwargs) self.clock = clock self.big_endian = big_endian self.bus.ARREADY.setimmediatevalue(0) self.bus.RVALID.setimmediatevalue(0) self.bus.RLAST.setimmediatevalue(0) self.bus.AWREADY.setimmediatevalue(0) self._memory = memory self.write_address_busy = Lock("%s_wabusy" % name) self.read_address_busy = Lock("%s_rabusy" % name) self.write_data_busy = Lock("%s_wbusy" % name) cocotb.start_soon(self._read_data()) cocotb.start_soon(self._write_data()) def _size_to_bytes_in_beat(self, AxSIZE): if AxSIZE < 7: return 2 ** AxSIZE return None async def _write_data(self): clock_re = RisingEdge(self.clock) while True: while True: self.bus.WREADY.value = 0 await ReadOnly() if self.bus.AWVALID.value: self.bus.WREADY.value = 1 break await clock_re await ReadOnly() _awaddr = int(self.bus.AWADDR) _awlen = int(self.bus.AWLEN) _awsize = int(self.bus.AWSIZE) _awburst = int(self.bus.AWBURST) _awprot = int(self.bus.AWPROT) burst_length = _awlen + 1 bytes_in_beat = self._size_to_bytes_in_beat(_awsize) if __debug__: self.log.debug( "AWADDR %d\n" % _awaddr + "AWLEN %d\n" % _awlen + "AWSIZE %d\n" % _awsize + "AWBURST %d\n" % _awburst + "AWPROT %d\n" % _awprot + "BURST_LENGTH %d\n" % burst_length + "Bytes in beat %d\n" % bytes_in_beat) burst_count = burst_length await clock_re while True: if self.bus.WVALID.value: word = self.bus.WDATA.value word.big_endian = self.big_endian _burst_diff = burst_length - burst_count _st = _awaddr + (_burst_diff * bytes_in_beat) # start _end = _awaddr + ((_burst_diff + 1) * bytes_in_beat) # end self._memory[_st:_end] = array.array('B', word.buff) burst_count -= 1 if burst_count == 0: break await clock_re async def _read_data(self): clock_re = RisingEdge(self.clock) while True: self.bus.ARREADY.value = 1 while True: await ReadOnly() if self.bus.ARVALID.value: break await clock_re await ReadOnly() _araddr = int(self.bus.ARADDR) _arlen = int(self.bus.ARLEN) _arsize = int(self.bus.ARSIZE) _arburst = int(self.bus.ARBURST) _arprot = int(self.bus.ARPROT) burst_length = _arlen + 1 bytes_in_beat = self._size_to_bytes_in_beat(_arsize) word = BinaryValue(n_bits=bytes_in_beat*8, bigEndian=self.big_endian) if __debug__: self.log.debug( "ARADDR %d\n" % _araddr + "ARLEN %d\n" % _arlen + "ARSIZE %d\n" % _arsize + "ARBURST %d\n" % _arburst + "ARPROT %d\n" % _arprot + "BURST_LENGTH %d\n" % burst_length + "Bytes in beat %d\n" % bytes_in_beat) burst_count = burst_length await clock_re self.bus.ARREADY.value = 0 self.bus.RVALID.value = 1 while burst_count > 0: _burst_diff = burst_length - burst_count _st = _araddr + (_burst_diff * bytes_in_beat) _end = _araddr + ((_burst_diff + 1) * bytes_in_beat) word.buff = self._memory[_st:_end].tobytes() self.bus.RDATA.value = word self.bus.RLAST.value = int(burst_count == 1) await ReadOnly() if self.bus.RREADY.value: burst_count -= 1 await clock_re self.bus.RLAST.value = 0 self.bus.RVALID.value = 0
import wave import matplotlib.pyplot as plt import numpy as np import os import math #读取本地音频 f = wave.open("./data/audio.wav",'rb') #获取音频参数 params = f.getparams() nchannel,sampwidth,framerate,nframes = params [:4] print(nchannel,sampwidth,framerate,nframes) #2 2 44100 6140484 #读取多通道音频 strData = f.readframes(nframes) waveData = np.frombuffer(strData,dtype=np.int16).reshape(-1,nchannel) # 归一化 waveData = waveData.astype(np.float32) max_sample = np.max(np.abs(waveData)) waveData /= max_sample # 创建一个0~nframe单位时间为1frame的数组 time = np.arange(0,nframes)*(1.0/framerate) # 绘图(单通道) plt.plot(time, waveData[:, 1]) plt.xlabel("Time (s)") plt.ylabel("Amplitude") plt.title("Single Channel Wave Data") plt.legend() plt.show() # 绘图(多通道) plt.figure() plt.subplot(3,1,1) plt.plot(time,waveData[:,0]) plt.xlabel("Time(s)") plt.ylabel("Amplitude") plt.title("Ch-1 wavedata") plt.subplot(3,1,3) plt.plot(time,waveData[:,1]) plt.xlabel("Time(s)") plt.ylabel("Amplitude") plt.title("Ch-2 wavedata") plt.show()
/****************************************************************** ** This code is part of Breakout. ** ** Breakout is free software: you can redistribute it and/or modify ** it under the terms of the CC BY 4.0 license as published by ** Creative Commons, either version 4 of the License, or (at your ** option) any later version. ******************************************************************/ #include "ball_object.hpp" // construct a new ball BallObject::BallObject(glm::vec2 pos, float radius, glm::vec2 velocity, Texture2D sprite) : GameObject(pos, glm::vec2(radius * 2.0f, radius * 2.0f), sprite, 8, velocity), Radius(radius), Stuck(true) {} // move the ball each frame glm::vec2 BallObject::Move(float dt, unsigned int window_width) { // if not stuck to player board if (!this->Stuck) { // move the ball this->Position += this->Velocity * dt; // then check if outside window bounds and if so, reverse velocity and restore at correct position // check on left side if (this->Position.x <= 63.0f) { this->Velocity.x = -this->Velocity.x; this->Position.x = 63.0f; } // check on right side else if (this->Position.x + this->Size.x >= window_width - 63.0f) { this->Velocity.x = -this->Velocity.x; this->Position.x = window_width - this->Size.x - 63.0f; } // check at top of screen if (this->Position.y <= 0.0f) { this->Velocity.y = -this->Velocity.y; this->Position.y = 0.0f; } } // return the new ball position after moving return this->Position; } // resets the ball to initial Stuck Position (if ball is outside window bounds) void BallObject::Reset(glm::vec2 position, glm::vec2 velocity) { this->Position = position; this->Velocity = velocity; this->Stuck = true; }
import React from "react"; import { NavLink } from "react-router-dom"; const Navbar = () => { return ( <> <div className="container-fluid"> <div className="row"> <div className="col-10 max-auto nav-bg"> <nav className="navbar navbar-expand-lg navbar-light bg-light"> <NavLink style={{ fontSize: "3rem" }} className="navbar-brand" to="/" > My First React App </NavLink> <button className="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarSupportedContent" aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation" > <span className="navbar-toggler-icon"></span> </button> <div className="collapse navbar-collapse" id="navbarSupportedContent" > <ul className="navbar-nav ml-auto"> <li className="nav-item"> <NavLink exact activeClassName="actives" className="nav-link" to="/" > Home </NavLink> </li> <li className="nav-item"> <NavLink exact activeClassName="actives" className="nav-link" to="/services" > Services </NavLink> </li> <li className="nav-item"> <NavLink exact activeClassName="actives" className="nav-link" to="/about" > About </NavLink> </li> <li className="nav-item"> <NavLink exact activeClassName="actives" className="nav-link" to="/contact" > Contact </NavLink> </li> </ul> </div> </nav> </div> </div> </div> </> ); }; export default Navbar;
/* Copyright (c) 2019-2023 Griefer@Work * * * * This software is provided 'as-is', without any express or implied * * warranty. In no event will the authors be held liable for any damages * * arising from the use of this software. * * * * Permission is granted to anyone to use this software for any purpose, * * including commercial applications, and to alter it and redistribute it * * freely, subject to the following restrictions: * * * * 1. The origin of this software must not be misrepresented; you must not * * claim that you wrote the original software. If you use this software * * in a product, an acknowledgement (see the following) in the product * * documentation is required: * * Portions Copyright (c) 2019-2023 Griefer@Work * * 2. Altered source versions must be plainly marked as such, and must not be * * misrepresented as being the original software. * * 3. This notice may not be removed or altered from any source distribution. * */ #ifndef GUARD_LIBC_LIBC_MATH_CTEST #define GUARD_LIBC_LIBC_MATH_CTEST 1 #define _KOS_SOURCE 1 #undef NDEBUG #include <hybrid/compiler.h> #include <system-test/ctest.h> #include <assert.h> #include <fenv.h> #include <stdio.h> #include <math.h> DECL_BEGIN DEFINE_TEST(math_rounding) { volatile double a = 1.499; volatile double b = 1.5; volatile double c = 1.501; volatile double d = -1.499; volatile double e = -1.5; volatile double f = -1.501; #define EQFLT(a, b) \ ({ \ volatile double _a = (a); \ volatile double _b = (b); \ assertf(isfinite(_a), "%f", _a); \ assertf(_a == _b, "%f != %f", _a, _b); \ }) EQFLT(round(a), 1.0); EQFLT(round(b), 2.0); EQFLT(round(c), 2.0); EQFLT(round(d), -1.0); EQFLT(round(e), -2.0); EQFLT(round(f), -2.0); EQ(1, lround(a)); EQ(2, lround(b)); EQ(2, lround(c)); EQ(-1, lround(d)); EQ(-2, lround(e)); EQ(-2, lround(f)); EQ(1, llround(a)); EQ(2, llround(b)); EQ(2, llround(c)); EQ(-1, llround(d)); EQ(-2, llround(e)); EQ(-2, llround(f)); EQFLT(floor(a), 1.0); EQFLT(floor(b), 1.0); EQFLT(floor(c), 1.0); EQFLT(floor(d), -2.0); EQFLT(floor(e), -2.0); EQFLT(floor(f), -2.0); EQFLT(ceil(a), 2.0); EQFLT(ceil(b), 2.0); EQFLT(ceil(c), 2.0); EQFLT(ceil(d), -1.0); EQFLT(ceil(e), -1.0); EQFLT(ceil(f), -1.0); EQFLT(trunc(a), 1.0); EQFLT(trunc(b), 1.0); EQFLT(trunc(c), 1.0); EQFLT(trunc(d), -1.0); EQFLT(trunc(e), -1.0); EQFLT(trunc(f), -1.0); EQ(0, fesetround(FE_TONEAREST)); EQ(FE_TONEAREST, fegetround()); EQFLT(nearbyint(a), round(a)); EQ(1, lrint(a)); EQ(1, llrint(a)); EQFLT(nearbyint(b), round(b)); EQ(2, lrint(b)); EQ(2, llrint(b)); EQFLT(nearbyint(c), round(c)); EQ(2, lrint(c)); EQ(2, llrint(c)); EQFLT(nearbyint(d), round(d)); EQ(-1, lrint(d)); EQ(-1, llrint(d)); EQFLT(nearbyint(e), round(e)); EQ(-2, lrint(e)); EQ(-2, llrint(e)); EQFLT(nearbyint(f), round(f)); EQ(-2, lrint(f)); EQ(-2, llrint(f)); EQ(FE_TONEAREST, fegetround()); EQ(0, fesetround(FE_DOWNWARD)); EQ(FE_DOWNWARD, fegetround()); EQFLT(nearbyint(a), floor(a)); EQ(1, lrint(a)); EQ(1, llrint(a)); EQFLT(nearbyint(b), floor(b)); EQ(1, lrint(b)); EQ(1, llrint(b)); EQFLT(nearbyint(c), floor(c)); EQ(1, lrint(c)); EQ(1, llrint(c)); EQFLT(nearbyint(d), floor(d)); EQ(-2, lrint(d)); EQ(-2, llrint(d)); EQFLT(nearbyint(e), floor(e)); EQ(-2, lrint(e)); EQ(-2, llrint(e)); EQFLT(nearbyint(f), floor(f)); EQ(-2, lrint(f)); EQ(-2, llrint(f)); EQ(FE_DOWNWARD, fegetround()); EQ(0, fesetround(FE_UPWARD)); EQ(FE_UPWARD, fegetround()); EQFLT(nearbyint(a), ceil(a)); EQ(2, lrint(a)); EQ(2, llrint(a)); EQFLT(nearbyint(b), ceil(b)); EQ(2, lrint(b)); EQ(2, llrint(b)); EQFLT(nearbyint(c), ceil(c)); EQ(2, lrint(c)); EQ(2, llrint(c)); EQFLT(nearbyint(d), ceil(d)); EQ(-1, lrint(d)); EQ(-1, llrint(d)); EQFLT(nearbyint(e), ceil(e)); EQ(-1, lrint(e)); EQ(-1, llrint(e)); EQFLT(nearbyint(f), ceil(f)); EQ(-1, lrint(f)); EQ(-1, llrint(f)); EQ(FE_UPWARD, fegetround()); EQ(0, fesetround(FE_TOWARDZERO)); EQ(FE_TOWARDZERO, fegetround()); EQFLT(nearbyint(a), trunc(a)); EQ(1, lrint(a)); EQ(1, llrint(a)); EQFLT(nearbyint(b), trunc(b)); EQ(1, lrint(b)); EQ(1, llrint(b)); EQFLT(nearbyint(c), trunc(c)); EQ(1, lrint(c)); EQ(1, llrint(c)); EQFLT(nearbyint(d), trunc(d)); EQ(-1, lrint(d)); EQ(-1, llrint(d)); EQFLT(nearbyint(e), trunc(e)); EQ(-1, lrint(e)); EQ(-1, llrint(e)); EQFLT(nearbyint(f), trunc(f)); EQ(-1, lrint(f)); EQ(-1, llrint(f)); EQ(FE_TOWARDZERO, fegetround()); #undef EQFLT } DECL_END #endif /* !GUARD_LIBC_LIBC_MATH_CTEST */
// // SwiftUIView.swift // Fructs // // Created by Александр Тарасевич on 09.03.2022. // import SwiftUI struct SwiftUIView: View { var fruit: Fruit @State private var isAnimating: Bool = false var body: some View { ZStack { VStack(spacing: 20 ) { Image(fruit.image) .resizable() .scaledToFit() .shadow(color: Color(red: 0, green: 0, blue: 0, opacity: 0.15), radius: 8, x: 6, y: 8) .scaleEffect(isAnimating ? 1.0 : 0.6) Text(fruit.title) .foregroundColor(.white) .font(.largeTitle) .fontWeight(.heavy) .shadow(color: Color(red: 0, green: 0, blue: 0, opacity: 0.15), radius: 2, x: 2, y: 2) Text(fruit.description) .foregroundColor(.white) .multilineTextAlignment(.center) .padding(.horizontal, 16) .frame(maxWidth: 980) StartButtonView() }//: VSTACK } //: ZSTACK .onAppear{ withAnimation(.easeOut(duration: 0.5)) { isAnimating = true } } .frame(minWidth: 0, maxWidth: .infinity, minHeight: 0, maxHeight: .infinity, alignment: .center) .background(RadialGradient(gradient: Gradient(colors: fruit.gradientColors), center: .center, startRadius: 50, endRadius: 400)) .cornerRadius(20) .padding(.horizontal, 20) } } struct SwiftUIView_Previews: PreviewProvider { static var previews: some View { SwiftUIView(fruit: fruitsData[0]) .previewLayout(.fixed(width: 320, height: 640)) } }
import { createSlice, PayloadAction } from '@reduxjs/toolkit'; import { User } from '../../types'; import { Status } from '../../types/fetchStatus'; import { getFollowUsers } from './asyncActions'; interface UsersState { users: User[]; error: unknown; lastPage: number | null; currentPage: number; status: Status; } const initialState: UsersState = { users: [], error: null, lastPage: null, currentPage: 1, status: Status.LOADING, }; function handlePending(state: UsersState) { state.status = Status.LOADING; } function handleRejected(state: UsersState, action: PayloadAction<unknown>) { state.status = Status.ERROR; state.error = action.payload; } const usersSlice = createSlice({ name: 'users', initialState, reducers: { clearUsers: (state) => { state.users = []; state.error = null; state.lastPage = null; state.status = Status.NEVER; state.currentPage = 1; }, }, extraReducers: (builder) => { builder .addCase(getFollowUsers.pending, (state) => handlePending(state)) .addCase( getFollowUsers.fulfilled, (state, action: PayloadAction<any>) => { const users = action.payload.data.map( (item: { target_user: User }) => item.target_user ); state.users = [...state.users, ...users]; state.status = Status.SUCCESS; state.lastPage = action.payload.last_page; state.currentPage = action.payload.page; } ) .addCase(getFollowUsers.rejected, (state, action) => handleRejected(state, action) ); }, }); export const { clearUsers } = usersSlice.actions; export default usersSlice.reducer;
// Copyright 2017 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. // The <code>chrome.declarativeNetRequest</code> API is used to intercept and // perform actions on a network request by specifying declarative rules. namespace declarativeNetRequest { // This describes the resource type of the network request. enum ResourceType { // TODO(crbug.com/696822): add main_frame, csp. sub_frame, stylesheet, script, image, font, object, xmlhttprequest, ping, media, websocket, other }; // This describes whether the request is first or third party to the frame in // which it originated. A request is said to be first party if it has the same // domain (eTLD+1) as the frame in which the request originated. enum DomainType { // The network request is first party to the frame in which it originated. firstParty, // The network request is third party to the frame in which it originated. thirdParty }; // Describes the kind of action to take if a given RuleCondition matches. enum RuleActionType { // Block the network request. blacklist, // Redirect the network request. redirect, // Whitelist the network request. The request won't be blocked even if there // is a blocking rule which matches it. whitelist }; dictionary RuleCondition { // The pattern which is matched against the network request url. // Supported constructs: // '*' : Wildcard: Matches any number of characters. // '|' : Left/right anchor: If used at either end of the pattern, specifies // the beginning/end of the url respectively. // '||' : Domain name anchor: If used at the beginning of the pattern, // specifies the start of a (sub-)domain of the URL. // '^' : Separator character: This matches anything except a letter, a // digit or one of the following: _ - . %. The end of the address is // also accepted as a separator. // Therefore urlFilter is composed of the following parts: // (optional Left/Domain name anchor) + pattern + (optional Right anchor) // If omitted, all urls are matched. An empty string is not allowed. DOMString? urlFilter; // Whether the |urlFilter| is case sensitive. Default is false. boolean? isUrlFilterCaseSensitive; // The rule will only match network requests originating from the list of // |domains|. If the list is omitted, the rule is applied to requests from // all domains. An empty list is not allowed. // Note: sub-domains like "a.example.com" are also allowed. DOMString[]? domains; // The rule will not match network requests originating from the list of // |excludedDomains|. If the list is empty or omitted, no domains are // excluded. This takes precedence over |domains|. // Note: sub-domains like "a.example.com" are also allowed. DOMString[]? excludedDomains; // List of resource types which the rule can match. If the list is omitted, // the rule is applied to all resource types. An empty list is not allowed. ResourceType[]? resourceTypes; // List of resource types which the rule won't match. If the list is empty // or omitted, no resource types are excluded. This takes precedence over // |resourceTypes|. ResourceType[]? excludedResourceTypes; // Specifies whether the network request is firstParty or thirdParty to the // domain from which it originated. If omitted, all requests are accepted. DomainType? domainType; }; dictionary RuleAction { // The type of action to perform. RuleActionType type; // The redirect url. Only valid if |type| == 'redirect'. DOMString? redirectUrl; }; dictionary Rule { // An id which uniquely identifies a rule. Mandatory and should be >= 1. long id; // Rule priority. Mandatory for redirect rules and should be >= 1. long? priority; // The condition which if satisfied causes the |action| to trigger. RuleCondition condition; // The action to take if this rule is matched. RuleAction action; }; };
import { Batch, createPairId, isBatch, Pair } from "../models/AppConfig"; import IProvider from "../providers/IProvider"; import logger from './LoggerService'; export default class NetworkQueue { queue: Batch[] = []; processingIds: Set<string> = new Set(); intervalId?: NodeJS.Timer; public id: string; constructor(public provider: IProvider) { this.id = provider.networkId; } has(batch: Batch): boolean { const id = createPairId(batch); const inQueue = this.queue.some(item => createPairId(item) === id); if (inQueue) return true; return this.processingIds.has(id); } add(batch: Batch) { if (this.has(batch)) return; this.queue.push(batch); logger.debug(`[${this.id}] Added "${createPairId(batch)}" to queue`); } start() { this.intervalId = setInterval(async () => { // We are processing something // We need to wait for the transaction to complete, otherwise // we could run into nonce issues. if (this.processingIds.size > 0) return; const pair = this.queue.shift(); if (!pair) return; const id = createPairId(pair) this.processingIds.add(id); logger.debug(`[${this.id}] Processing ${id}`); const answer = await this.provider.resolveBatch(pair); logger.debug(`[${this.id}] Completed processing "${id}" with answer ${answer}`); this.processingIds.delete(id); }, 100); } stop() { if (!this.intervalId) return; clearInterval(this.intervalId); this.intervalId = undefined; } }
import { createAsyncThunk, createSlice } from "@reduxjs/toolkit"; import { categoryService } from "./categoryService"; const initialState = { categories: [], isLoading: false, isError: false, isSuccess: false, message: "", }; // I LEAVE THIS HERE IN CASE I NEED TO DO A VIEW TO ADD OR DELETE CATEGORIES, MEANWHILE I CAN DO IT MANUALLY export const createCategory = createAsyncThunk( "createCategory", async (data, thunkAPI) => { try { return await categoryService.create(data); } catch (error) { return thunkAPI.rejectWithValue(error); } } ); export const getCategories = createAsyncThunk( "getCategories", async (_, thunkAPI) => { try { return await categoryService.get(); } catch (error) { return thunkAPI.rejectWithValue(error); } } ); export const deleteCategory = createAsyncThunk( "deleteCategory", async (categoryId, thunkAPI) => { try { return await categoryService.delete(categoryId); } catch (error) { return thunkAPI.rejectWithValue(error); } } ); export const categorySlice = createSlice({ name: "categories", initialState, reducers: {}, extraReducers: (builder) => { builder // CREATE CATEGORY .addCase(createCategory.pending, (state) => { state.isLoading = true; state.message = "Creating category"; }) .addCase(createCategory.fulfilled, (state, action) => { state.isLoading = false; state.isSuccess = true; state.isError = false; state.message = action.payload.message; state.categories = action.payload.categories; }) .addCase(createCategory.rejected, (state, action) => { state.isLoading = false; state.isSuccess = false; state.isError = true; state.message = "Error creating category"; }) // GET CATEGORIES .addCase(getCategories.pending, (state) => { state.isLoading = true; state.message = "Getting categories"; }) .addCase(getCategories.fulfilled, (state, action) => { state.isLoading = false; state.isSuccess = true; state.isError = false; state.message = action.payload.message; state.categories = action.payload.categories; }) .addCase(getCategories.rejected, (state, action) => { state.isLoading = false; state.isSuccess = false; state.isError = true; state.message = "Error getting categories"; }) // DELETE CATEGORY .addCase(deleteCategory.pending, (state) => { state.isLoading = true; state.message = "Deleting category"; }) .addCase(deleteCategory.fulfilled, (state, action) => { state.isLoading = false; state.isSuccess = true; state.isError = false; state.message = action.payload.message; state.categories = action.payload.categories; }) .addCase(deleteCategory.rejected, (state, action) => { state.isLoading = false; state.isSuccess = false; state.isError = true; state.message = "Error deleting category"; }); }, });
// Implement permutation type that transforms union types into the array that includes permutations of unions. { type Permutation<T, K = T> = [T] extends [never] ? [] : K extends K ? [K, ...Permutation<Exclude<T, K>>] : never; // 'a' | 'b' | 'c' extends 'a' | 'b' | 'c' // 'a' extends 'a' | 'b' | 'c' -> ['a' ,,,] // 'b' | 'c' extends 'b' | 'c' // 'b' extends 'b' | 'c' -> ['a','b'] // 'c' extends 'c' // never extends never -> ['a','b','c'] // 'c' extends 'b' | 'c' -> ['a','c'] // 'b' extends 'b' // never extends never -> ['a','c','b'] // 'b' extends 'a' | 'b' | 'c' -> ['b',,,] // 'a' | 'c' extends 'a' | 'c' // 'a' extends 'a' | 'c' -> ['b','a'] // 'c' extends 'c' // never extends never -> ['b','a','c'] // 'c' extends 'a' | 'c' -> ['b','c'] // 'a' extends 'a' // never extends never -> ['b','c','a'] // 'c' extends 'a' | 'b' | 'c' // ↑と同じ type alpha = 'A' | 'B' | 'C'; const alphas: Permutation<alpha> = ['A', 'B', 'C']; }
import { NgModule } from '@angular/core'; import { Routes, RouterModule } from '@angular/router'; import { AppComponent } from './app.component'; import { BilleterieComponent } from './billeterie/billeterie.component'; import { ConcertComponent } from './concert/concert.component'; import { ConcertsComponent } from './concerts/concerts.component'; import { FaqComponent } from './faq/faq.component'; import { HomeComponent } from './home/home.component'; import { MentionsLegalesComponent } from './mentions-legales/mentions-legales.component'; const routes: Routes = [ { path: '', component: HomeComponent }, { path: 'concert', component: ConcertComponent }, { path: 'faq', component: FaqComponent }, { path: 'mentions_legales', component: MentionsLegalesComponent }, { path: 'concerts', component: ConcertsComponent }, { path: 'billeterie', component: BilleterieComponent }, ]; @NgModule({ imports: [RouterModule.forRoot(routes)], exports: [RouterModule], }) export class AppRoutingModule {}
import { PlusCircleIcon } from '@heroicons/react/24/solid'; import React from 'react' import { Draggable, Droppable } from 'react-beautiful-dnd' import TodoCard from './TodoCard'; import { useBoardStore } from '@/store/BoardStore'; import { useModalStore } from '@/store/ModalStore'; type Props = { id: TypedColumn, todos: Todo[], index: number }; const idToColumnText: { [key in TypedColumn]: string; } = { "todo": "To Do", "inprogress": "In Progress", "done": "Done" } function Column({id, todos, index}: Props) { const [searchString, setNewTaskType] = useBoardStore((state) => [ state.searchString, state.setNewTaskType ]); const openModal = useModalStore((state) => state.openModal); const handleAddTodo = () => { setNewTaskType(id); openModal(); } return ( <Draggable draggableId={id} index={index}> {(provided) => ( <div {...provided.draggableProps} {...provided.dragHandleProps} ref={provided.innerRef} > {/*internal droppable - render droppable todos in the column*/} <Droppable droppableId={index.toString()} type='card'> {(provided, snapShot) => ( <div {...provided.droppableProps} ref={provided.innerRef} className={`p-2 rounded-2xl shadow-sm ${ snapShot.isDraggingOver ? "bg-green-200" : "bg-white/50" }`} > <h2 className='flex justify-between font-bold text-xl p-2'>{idToColumnText[id]} <span className='text-gray-500 bg-gray-200 rounded-full px-2 py-1 text-sm font-normal'>{!searchString ? todos.length : todos.filter(todo => todo.title.toLocaleLowerCase().includes(searchString.toLocaleLowerCase())).length}</span> </h2> <div className='space-y-2'> {todos.map((todo, index) => { if( searchString && !todo.title.toLowerCase().includes(searchString.toLowerCase())) { return null; } return ( <Draggable key={todo.$id} draggableId={todo.$id} index={index} > {(provided) => ( <TodoCard todo={todo} index={index} id={id} innerRef={provided.innerRef} draggableProps={provided.draggableProps} dragHandleProps={provided.dragHandleProps} /> )} </Draggable> )})} {provided.placeholder} <div className='flex items-end justify-end p-2'> <button className='text-green-500 hover:text-green-600' onClick={handleAddTodo}> <PlusCircleIcon className='h-10 w-10'/> </button> </div> </div> </div> )} </Droppable> </div> )} </Draggable> ) } export default Column
import axios from 'axios'; export const listPublishers = () => async (dispatch, getState) => { try { dispatch({ type: 'PUBLISHER_LIST_REQUEST' }); //reduceru const { userLogin: { userInfo }, } = getState(); const config = { headers: { Authorization: `Bearer ${userInfo.token}`, }, }; const { data } = await axios.get('/api/publishers', config); //zahtev ka serveru dispatch({ type: 'PUBLISHER_LIST_SUCCESS', payload: data, }); //reduceru } catch (error) { dispatch({ type: 'PUBLISHER_LIST_FAIL', //ako postoji backend error, ispisi poruku vezanu za njega! payload: error.response && error.response.data.message ? error.response.data.message : error.message, }); } }; export const createPublisher = (productId, publisher) => async ( dispatch, getState ) => { try { dispatch({ type: 'PUBLISHER_CREATE_REQUEST', }); const { userLogin: { userInfo }, } = getState(); const config = { headers: { 'Content-Type': 'application/json', Authorization: `Bearer ${userInfo.token}`, }, }; const { data } = await axios.post( `/api/products/${productId}/publishers`, publisher, config ); dispatch({ type: 'PUBLISHER_CREATE_SUCCESS', payload: data, }); } catch (error) { dispatch({ type: 'PUBLISHER_CREATE_FAIL', //ako postoji backend error, ispisi poruku vezanu za njega! payload: error.response && error.response.data.message ? error.response.data.message : error.message, }); } };
import { NgModule } from '@angular/core'; import { PreloadAllModules, RouterModule, Routes } from '@angular/router'; const routes: Routes = [ { path: 'folder/:id', loadChildren: () => import('./folder/folder.module').then( m => m.FolderPageModule) }, { path: '', redirectTo: 'folder', pathMatch: 'full' }, { path: 'post-detail/:id', loadChildren: () => import('./post-detail/post-detail.module').then( m => m.PostDetailPageModule) } ]; @NgModule({ imports: [ RouterModule.forRoot(routes, { preloadingStrategy: PreloadAllModules }) ], exports: [RouterModule] }) export class AppRoutingModule {}
import 'package:flutter/material.dart'; import 'package:hell_ew_s_application2/presentation/login_screen/login_screen.dart'; import 'package:hell_ew_s_application2/presentation/signup_screen/signup_screen.dart'; import 'package:hell_ew_s_application2/presentation/home_container_screen/home_container_screen.dart'; import 'package:hell_ew_s_application2/presentation/search_tab_container_screen/search_tab_container_screen.dart'; import 'package:hell_ew_s_application2/presentation/search_results_screen/search_results_screen.dart'; import 'package:hell_ew_s_application2/presentation/single_story_screen/single_story_screen.dart'; import 'package:hell_ew_s_application2/presentation/single_post_screen/single_post_screen.dart'; import 'package:hell_ew_s_application2/presentation/comments_screen/comments_screen.dart'; import 'package:hell_ew_s_application2/presentation/single_video_screen/single_video_screen.dart'; import 'package:hell_ew_s_application2/presentation/single_event_screen/single_event_screen.dart'; import 'package:hell_ew_s_application2/presentation/notifications_screen/notifications_screen.dart'; import 'package:hell_ew_s_application2/presentation/video_chat_screen/video_chat_screen.dart'; import 'package:hell_ew_s_application2/presentation/chat_screen/chat_screen.dart'; import 'package:hell_ew_s_application2/presentation/group_chat_screen/group_chat_screen.dart'; import 'package:hell_ew_s_application2/presentation/settings_screen/settings_screen.dart'; import 'package:hell_ew_s_application2/presentation/my_friends_screen/my_friends_screen.dart'; import 'package:hell_ew_s_application2/presentation/app_navigation_screen/app_navigation_screen.dart'; class AppRoutes { static const String loginScreen = '/login_screen'; static const String signupScreen = '/signup_screen'; static const String homePage = '/home_page'; static const String homeContainerScreen = '/home_container_screen'; static const String searchPage = '/search_page'; static const String searchTabContainerScreen = '/search_tab_container_screen'; static const String searchResultsScreen = '/search_results_screen'; static const String singleStoryScreen = '/single_story_screen'; static const String singlePostScreen = '/single_post_screen'; static const String commentsScreen = '/comments_screen'; static const String singleVideoScreen = '/single_video_screen'; static const String eventsPage = '/events_page'; static const String eventsTabContainerPage = '/events_tab_container_page'; static const String singleEventScreen = '/single_event_screen'; static const String notificationsScreen = '/notifications_screen'; static const String newPostPage = '/new_post_page'; static const String videoChatScreen = '/video_chat_screen'; static const String chatScreen = '/chat_screen'; static const String messagesPage = '/messages_page'; static const String archivedMessagePage = '/archived_message_page'; static const String archivedMessageTabContainerPage = '/archived_message_tab_container_page'; static const String groupChatScreen = '/group_chat_screen'; static const String settingsScreen = '/settings_screen'; static const String userProfilePage = '/user_profile_page'; static const String userProfileTabContainerPage = '/user_profile_tab_container_page'; static const String galleryPage = '/gallery_page'; static const String myFriendsScreen = '/my_friends_screen'; static const String appNavigationScreen = '/app_navigation_screen'; static const String initialRoute = '/initialRoute'; static Map<String, WidgetBuilder> get routes => { loginScreen: LoginScreen.builder, signupScreen: SignupScreen.builder, homeContainerScreen: HomeContainerScreen.builder, searchTabContainerScreen: SearchTabContainerScreen.builder, searchResultsScreen: SearchResultsScreen.builder, singleStoryScreen: SingleStoryScreen.builder, singlePostScreen: SinglePostScreen.builder, commentsScreen: CommentsScreen.builder, singleVideoScreen: SingleVideoScreen.builder, singleEventScreen: SingleEventScreen.builder, notificationsScreen: NotificationsScreen.builder, videoChatScreen: VideoChatScreen.builder, chatScreen: ChatScreen.builder, groupChatScreen: GroupChatScreen.builder, settingsScreen: SettingsScreen.builder, myFriendsScreen: MyFriendsScreen.builder, appNavigationScreen: AppNavigationScreen.builder, initialRoute: LoginScreen.builder }; }
/* * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ /* * BaseTime.java * Copyright (C) 2010-2014 University of Waikato, Hamilton, New Zealand */ package adams.core.base; import java.util.Date; import adams.core.DateFormat; import adams.core.DateValueSupporter; import adams.parser.BaseTimeExpression; import adams.parser.GrammarSupplier; /** * Wrapper for a Time string to be editable in the GOE. Dates have to be of * format "HH:mm:ss". * <pre> * parses expressions as follows: * (&lt;date&gt;|NOW|-INF|+INF|START|END) [(+&lt;int&gt;|-&lt;int&gt;) (SECOND|MINUTE|HOUR)] * Examples: * 01:02:03 * 01:02:03 +1 MINUTE * NOW * +INF * NOW +1 HOUR * NOW +14 MINNUTE * Amounts can be chained as well: * NOW -1 MINUTE +1 HOUR * START and END can only be set programmatically; by default they equal to -INF and +INF. * </pre> * * @author fracpete (fracpete at waikato dot ac dot nz) * @version $Revision: 10214 $ * @see #DATE_FORMAT * @see #setStart(Date) * @see #setEnd(Date) */ public class BaseTime extends BaseObject implements GrammarSupplier, DateValueSupporter { /** for serialization. */ private static final long serialVersionUID = -5853830144343397434L; /** the placeholder for "-INF" (infinity in the past). */ public final static String INF_PAST = "-INF"; /** the "-INF" date. */ public final static String INF_PAST_DATE = "00:00:00"; /** the placeholder for "+INF" (infinity in the future). */ public final static String INF_FUTURE = "+INF"; /** the "+INF" date. */ public final static String INF_FUTURE_DATE = "23:59:59"; /** the placeholder for "now". */ public final static String NOW = "NOW"; /** the placeholder for "start". */ public final static String START = "START"; /** the placeholder for "end". */ public final static String END = "END"; /** the date format. */ public final static String FORMAT = "HH:mm:ss"; /** for formatting/parsing the dates. */ protected static DateFormat m_Format; static { m_Format = new DateFormat(FORMAT); } /** the start time to use. */ protected Date m_Start = null; /** the end time to use. */ protected Date m_End = null; /** * Initializes the date as NOW. * * @see #NOW */ public BaseTime() { this(NOW); } /** * Initializes the object with the date to parse. * * @param s the date to parse */ public BaseTime(String s) { super(s); } /** * Initializes the object with the specified date. * * @param date the date to use */ public BaseTime(Date date) { this(m_Format.format(date)); } /** * Initializes the internal object. */ @Override protected void initialize() { m_Internal = NOW; } /** * Sets the optional start time. * * @param value the start time */ public void setStart(Date value) { m_Start = value; } /** * Returns the optional start time. * * @return the start time */ public Date getStart() { return m_Start; } /** * Sets the optional end time. * * @param value the end time */ public void setEnd(Date value) { m_End = value; } /** * Returns the optional end time. * * @return the end time */ public Date getEnd() { return m_End; } /** * Parses the given date string. * * @param s the date string to parse * @param quiet whether to print exceptions or not * @return the parsed date, null in case of an error */ protected Date parse(String s, boolean quiet) { try { return BaseTimeExpression.evaluate(s, m_Start, m_End); } catch (Exception e) { if (!quiet) { System.err.println("Failed to parse: " + s); e.printStackTrace(); } return null; } } /** * Checks whether the string value is a valid presentation for this class. * * @param value the string value to check * @return true if the string can be parsed */ @Override public boolean isValid(String value) { if (value == null) return false; value = value.toUpperCase(); if (value.length() == 0) return true; return (parse(value, true) != null); } /** * Sets the string value. * * @param value the string value */ @Override public void setValue(String value) { if (!isValid(value)) return; if (value.equals(INF_FUTURE_DATE)) m_Internal = INF_FUTURE; else if (value.equals(INF_PAST_DATE)) m_Internal = INF_PAST; else if (value.length() == 0) m_Internal = NOW; else m_Internal = value; } /** * Returns the current string value. * * @return the string value */ @Override public String getValue() { return (String) m_Internal; } /** * Returns the Date value. * * @return the Date value */ public Date dateValue() { return parse(getValue(), false); } /** * Returns the actual Date as string. * * @return the actual date as string */ public String stringValue() { return m_Format.format(dateValue()); } /** * Returns a tool tip for the GUI editor (ignored if null is returned). * * @return the tool tip */ @Override public String getTipText() { return "A date of format '" + FORMAT + "' " + "(" + "'" + INF_PAST + "' = '" + INF_PAST_DATE + "', " + "'" + INF_FUTURE + "' = '" + INF_FUTURE_DATE + "', " + "'" + NOW + "' = the current date/time" + ")."; } /** * Returns a string representation of the grammar. * * @return the grammar, null if not available */ public String getGrammar() { return new BaseTimeExpression().getGrammar(); } /** * Checks whether the date/time is +INF. * * @return true if infinity future */ public boolean isInfinityFuture() { return getValue().equals(INF_FUTURE); } /** * Checks whether the date/time is -INF. * * @return true if infinity future */ public boolean isInfinityPast() { return getValue().equals(INF_PAST); } /** * Checks whether the date/time is -INF or +INF. * * @return true if any infinity */ public boolean isInfinity() { return isInfinityPast() || isInfinityFuture(); } /** * Returns a new BaseDate object initialized with the NOW placeholder. * * @return the BaseDate object * @see #NOW */ public static BaseDateTime now() { return new BaseDateTime(NOW); } /** * Returns a new BaseDate object initialized with the INF_FUTURE placeholder. * * @return the BaseDate object * @see #INF_FUTURE */ public static BaseDateTime infinityFuture() { return new BaseDateTime(INF_FUTURE); } /** * Returns a new BaseDate object initialized with the INF_PAST placeholder. * * @return the BaseDate object * @see #INF_PAST */ public static BaseDateTime infinityPast() { return new BaseDateTime(INF_PAST); } }
import React from 'react'; import Select from 'react-select'; import { useField } from 'formik'; import styles from "./Dropdown.module.css"; function Dropdown(props) { const [field, state, {setValue, setTouched}] = useField(props.field.name); const onChange = ({value}) => { setValue(value); }; const colourStyles = { control: styles => ({ ...styles, width: "100%", color: "var(--work-presets-text-white-mode-primary-g-800, #333)", fontFamily: "TT Travels", fontSize: "14px", fontStyle: "normal", fontWeight: 200, lineHeight: "20px", }), option: styles => ({...styles, backgroundColor: "white", color: "var(--work-presets-text-white-mode-primary-g-800, #333)", fontFamily: "TT Travels", fontSize: "14px", fontStyle: "normal", fontWeight: 400, lineHeight: "20px", }), placeholder: styles => ({...styles, backgroundColor: "white", color: "var(--work-presets-text-white-mode-primary-g-800, #333)", // fontFamily: "TT Travels", fontSize: "14px", fontStyle: "normal", fontWeight: 400, lineHeight: "20px", }), }; return ( <Select {...props} onChange={onChange} // defaultInputValue={field.value} onBlur={setTouched} styles={colourStyles} className={styles.select} placeholder={field.value} /> ); } export default Dropdown;
import { createAsyncMiddleware } from '@onekeyhq/json-rpc-engine'; import { ethErrors } from 'eth-rpc-errors'; import handlersCFX from 'wallets/providers/CFX/dapp/handlers'; import log from 'loglevel'; import bgHelpers from '../../../../src/wallets/bg/bgHelpers'; import utilsApp from '../../../../src/utils/utilsApp'; import { STREAM_PROVIDER_CFX } from '../../constants/consts'; export const MOCK_ZERO_ADDRESS = '0x0000000000000000000000000000000000000000'; export const MOCK_CHAIN_ID_WHEN_NEW_APP = { // chainId: "0x61" // networkVersion: "97" chainId: '0xEEEEEEEE', networkVersion: '4008636142', }; function showBrowserNotification({ title, message, url }) { global.$ok_extensionPlatform?._showNotification(title, message, url); } /** * Create middleware for handling certain methods and preprocessing permissions requests. */ export default function createPermissionsMethodMiddleware({ addDomainMetadata, getAccounts, getUnlockPromise, hasPermission, notifyAccountsChanged, requestAccountsPermission, ...others }) { let isProcessingRequestAccounts = false; return createAsyncMiddleware(async (req, res, next) => { let responseHandler; // if (req && req?.streamName === STREAM_PROVIDER_SOL) { // } if (req && req?.streamName === STREAM_PROVIDER_CFX) { const services = { addDomainMetadata, getAccounts, getUnlockPromise, hasPermission, notifyAccountsChanged, requestAccountsPermission, ...others, }; // log.info('DAPP_RPC_MIDDLEWARE', req.id, { // method: req.method, // req, // services, // }); await handlersCFX.handleDappMethods({ req, res, next, services, }); return; } // ETH EVM request ---------------------------------------------- if (utilsApp.isNewHome()) { if (req.method === 'eth_chainId') { res.result = MOCK_CHAIN_ID_WHEN_NEW_APP.chainId; return; } if ( req.method === 'eth_requestAccounts' || req.method === 'eth_accounts' ) { // pass getAccounts() to permissionsMethodMiddleware, can not be [], will cause UI ask to approve many times // res.result = [MOCK_ZERO_ADDRESS]; res.result = []; if (req.method === 'eth_requestAccounts') { showBrowserNotification({ title: `Chain network not matched: ${req.origin || ''}`, message: `${req.method}`, }); } return; } } switch (req.method) { // Intercepting eth_accounts requests for backwards compatibility: // The getAccounts call below wraps the rpc-cap middleware, and returns // an empty array in case of errors (such as 4100:unauthorized) case 'eth_accounts': { res.result = await getAccounts(); return; } case 'eth_requestAccounts': { if (isProcessingRequestAccounts) { res.error = ethErrors.rpc.resourceUnavailable( 'Already processing eth_requestAccounts. Please wait.', ); return; } // check if domain is approved if (hasPermission('eth_accounts')) { isProcessingRequestAccounts = true; await getUnlockPromise(); isProcessingRequestAccounts = false; } // first, just try to get accounts let accounts = await getAccounts(); if (accounts.length > 0) { res.result = accounts; return; } // if no accounts, request the accounts permission try { await requestAccountsPermission(); } catch (err) { res.error = err; return; } // get the accounts again accounts = await getAccounts(); /* istanbul ignore else: too hard to induce, see below comment */ if (accounts.length > 0) { res.result = accounts; } else { // this should never happen, because it should be caught in the // above catch clause res.error = ethErrors.rpc.internal( 'Accounts unexpectedly unavailable. Please report this bug.', ); } return; } // custom method for getting metadata from the requesting domain, // sent automatically by the inpage provider when it's initialized case 'metamask_sendDomainMetadata': { if (typeof req.params?.name === 'string') { addDomainMetadata(req.origin, req.params); } res.result = true; return; } // register return handler to send accountsChanged notification case 'wallet_requestPermissions': { if ('eth_accounts' in req.params?.[0]) { responseHandler = async () => { if (Array.isArray(res.result)) { for (const permission of res.result) { if (permission.parentCapability === 'eth_accounts') { notifyAccountsChanged(await getAccounts()); } } } }; } break; } default: break; } // when this promise resolves, the response is on its way back // eslint-disable-next-line node/callback-return await next(); if (responseHandler) { responseHandler(); } }); }
import React from 'react' import { Button, Form, Label } from './components' import classes from './App.module.scss' import Navbar from './components/templates/Navbar/Navbar' function App() { return ( <div className={classes.app}> <Navbar tabs={{ home: '/home', about: '/about', dashboard: '/dashboard' }} /> <h1>Component playground</h1> <Label>Button Label</Label> <Button cssClass={classes.button}>Hi</Button> <Form.Builder onSubmit={() => console.log('kur')} header={<Form.Header>Form Header</Form.Header>} footer={<Form.Footer>Form Footer</Form.Footer>} > <Form.Body fields={{ name: { id: 'name', type: 'text', validation: (formFields) => { console.log(formFields) return true }, }, age: { id: 'age', type: 'number', }, langs: { id: 'langs', type: 'select', options: [ { name: 'en', value: 'English' }, { name: 'de', value: 'Deutsch' }, { name: 'fr', value: 'Français' }, ], }, }} /> </Form.Builder> </div> ) } export default App
import cv2 import dlib import numpy as np import math # Load the pre-trained face detection model face_cascade = cv2.CascadeClassifier('haarcascades/haarcascade_frontalface_default.xml') # Load the facial landmark predictor model predictor = dlib.shape_predictor('shape_predictor_68_face_landmarks.dat') # Load the image of glasses glasses_img = cv2.imread('images/glasses1.png', -1) def calculate_angle(pt1, pt2): # Calculate the angle between two points x_diff = pt2[0] - pt1[0] y_diff = pt2[1] - pt1[1] return math.degrees(math.atan2(y_diff, x_diff)) def overlay_glasses(face_img, glasses_img, x, y, w, h, angle): # Calculate the size of the glasses based on the width and height of the detected face glasses_width = int(w * 0.8) glasses_height = int(h * 0.5) # Resize the glasses to fit the face resized_glasses = cv2.resize(glasses_img, (glasses_width, glasses_height)) # Rotate the glasses image according to the face angle center = (glasses_width // 2, glasses_height // 2) rotation_matrix = cv2.getRotationMatrix2D(center, angle, 1.0) rotated_glasses = cv2.warpAffine(resized_glasses, rotation_matrix, (glasses_width, glasses_height)) # Extract the alpha channel from the glasses image alpha_mask = rotated_glasses[:, :, 3] # Create an inverted mask for the glasses inverted_mask = cv2.bitwise_not(alpha_mask) # Calculate the position to overlay the glasses x_offset = int(x - (glasses_width - w) / 2) y_offset = int(y + h * 0.19) # Overlay the glasses on the face region roi = face_img[y_offset:y_offset + glasses_height, x_offset:x_offset + glasses_width] background = cv2.bitwise_and(roi, roi, mask=inverted_mask) overlay = cv2.bitwise_and(rotated_glasses[:, :, :3], rotated_glasses[:, :, :3], mask=alpha_mask) face_img[y_offset:y_offset + glasses_height, x_offset:x_offset + glasses_width] = cv2.add(background, overlay) # Load the input image image = cv2.imread('images/temp.jpg') # Convert the image to grayscale gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY) # Detect faces in the grayscale image faces = face_cascade.detectMultiScale(gray, scaleFactor=1.1, minNeighbors=5, minSize=(30, 30)) # Overlay glasses on each detected face print(faces) for (x, y, w, h) in faces: # Estimate the angle of rotation for the face rect = dlib.rectangle(int(x), int(y), int(x + w), int(y + h)) landmarks = predictor(gray, rect) # Calculate the angle of rotation using eye landmarks left_eye = (landmarks.part(36).x, landmarks.part(36).y) right_eye = (landmarks.part(45).x, landmarks.part(45).y) angle = -calculate_angle(left_eye, right_eye) # Overlay glasses on the face overlay_glasses(image, glasses_img, x, y, w, h, angle) # Display the result cv2.imshow('Face with Glasses', image) output_path = 'images/face_with_glasses.jpg' cv2.imwrite(output_path, image) cv2.waitKey(0) cv2.destroyAllWindows()
Classes Wrapper: - As classes Wrappers são objetos que encapsulam os tipos primitivos, no entanto das classes wrapper tipo numericos são extenções da classe number e por ser uma extensão segue todas as regras de um objeto assim como a regra do polimorfismo. - nas classes primitivas são aplicadas as gregras de tamanho em bytes em memoria e nas classes wrappers são aplicadas as regras da classe Object como o polimorfismo por exemplo. - O motivo para ser criada as classes Wrappers é porque com elas é possivel passar valores como uma referencia e não como bytes em mémoria podendo utilizar as propriedades e métodos da classe Object. obs1: a classe Wrapper do tipo Byte so pode aceitar valores do tipo byte até 127 devido ser o valor mais alto para o byte, acima disso é considerado um valor inteiro. obs2: a classe long precisa do caractere 'L' para poder indentificar um valor do tipo Long ao retirar esse caractere é gerando um erro de compilação pois o valor long não pode ser um integer devido as regras de polimorfismo. ** AutoBoxing ** - E quando você possui um tipo primitivo e faz com que o java transforme esse tipo primitivo em um tipo Wrapper. ** Unboxing ** - E quando você possui um tipo Wrapper pega esse valor e pede ao Java para transformar o tipo Wrapper em um tipo primitivo. obs3: todas as classes Wrappers possuem uma função chamada Parse() onde é possivel converter uma string em seus respectivos valores de classe a unica que não possue esse método de forma nativa é o Character, e tambem é caseInsensitive ele desconsiderar letras maiusculas e minusculas.
# Tenhou Paifu Logger [<img src="https://img.shields.io/pypi/v/PaifuLogger?style=plastic"> <img src="https://img.shields.io/pypi/wheel/PaifuLogger?style=plastic">](https://pypi.org/project/Tenhou-Paifu-Logger/) [<img src="https://img.shields.io/github/stars/Jim137/Tenhou-Paifu-Logger?style=plastic">](https://github.com/Jim137/Tenhou-Paifu-Logger/) [<img src="https://img.shields.io/github/downloads/Jim137/Tenhou-Paifu-Logger/total?style=plastic">](https://github.com/Jim137/Tenhou-Paifu-Logger/releases) ![GitHub](https://img.shields.io/github/license/Jim137/Tenhou-Paifu-Logger?style=plastic) ExcelまたはHTMLファイルに天鳳の牌譜をいくつかの主要情報とともに記録します。 このプロジェクトが気に入った場合は、スターを付けていただけると大変励みになります。また、提案がある場合は、遠慮なく問題を作成してください。 [ダウンロード](https://github.com/Jim137/Tenhou-Paifu-Logger/releases/latest) | [English](https://github.com/Jim137/Tenhou-Paifu-Logger/blob/master/README.md) | [中文說明](https://github.com/Jim137/Tenhou-Paifu-Logger/blob/master/READMEs/README_zh.md) ## 使い方 1. プロジェクトをダウンロードします。 >a. GitHubからダウンロードします。 >>i. リポジトリをクローンするか、[最新リリース](https://github.com/Jim137/Tenhou-Paifu-Logger/releases/latest)をダウンロードします。 git clone https://github.com/Jim137/Tenhou-Paifu-Logger.git >>ii. 天鳳.netから牌譜のURLをクリップボードにコピーします。 >>iii. `runlog-user.bat`を開きます。 >b. PyPIからダウンロードします。 >>i. コマンドラインを開き、次のコマンドを入力します。 pip install PaifuLogger >>ii. 天鳳.netから牌譜のURLをクリップボードにコピーします。次に、次のコマンドを入力します。 log -l [言語] -o [出力ディレクトリ] [牌譜のURL] 2. 一度 ![Enter URLs](image/README_ja/enter_url.png) が表示されると、牌譜のURLを貼り付けてEnterキーを押します。\ 注意: 最新バージョンでは、一度に複数のURLを任意の区切り文字で区切って入力できます。 pre> 怠け者の場合は、何も貼り付けないでください。 3. ![Recorded](image/README_ja/recorded.png) が表示された後、牌譜は正常に記録されます。 4. 再び ![Enter URLs](image/README_ja/enter_url.png) が表示されると、次のURLを貼り付けることができます。 ## 機能 * [x] いくつかの主要情報とともに牌譜をExcelまたはHTMLファイルに記録します。 * [x] 三麻(3p)と四麻(4p)を区別し、別々のシートに記録します。 * [x] 重複する牌譜をスキップします。 * [x] 既に記録されたURLで牌譜を再作成します (-r、--remake)。将来的に記録情報を更新した場合に便利です。 * [x] カスタマイズ可能な出力ディレクトリ (-o、--output) * [x] mjai形式の牌譜出力サポート (--mjai)。*最初に `git pull --recurse-submodules` を実行する必要があります*。 * [x] ローカライズ対応 (-l、--language) * [x] 英語: en * [x] 繁体字中国語: zh_tw * [x] 簡体字中国語: zh * [x] 日本語 (ChatGPT): ja ## 記録される情報 * ゲームの時間 * 順位 * URL (将来のために) * ゲーム前のレート ## 将来の機能 * [ ] 各ラウンドの試合リプレイをHTMLファイルに追加 * [ ] レートの変動 * [ ] 和了解析 * [ ] Majsoul牌譜のサポート * [ ] GUI ## 貢献 バグ報告、プルリクエスト、機能要求、ドキュメントの改善、ローカリゼーションなど、さまざまな貢献を歓迎します。 詳細については、[CONTRIBUTING.md](https://github.com/Jim137/Tenhou-Paifu-Logger/blob/master/CONTRIBUTING.md) をご覧ください。 ## ライセンス [MIT](LICENSE) --- (この翻訳はChatGPTによって生成されました。)
/* MapleLib - A general-purpose MapleStory library * Copyright (C) 2009, 2010, 2015 Snow and haha01haha01 * This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. * This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. * You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>.*/ using System.Collections.Generic; using System.IO; using MapleLib.WzLib.Util; namespace MapleLib.WzLib { /// <summary> /// A class that parses and contains the data of a wz list file /// </summary> public static class ListFileParser { /// <summary> /// Parses a wz list file on the disk /// </summary> /// <param name="filePath">Path to the wz file</param> public static List<string> ParseListFile(string filePath, WzMapleVersion version) { return ParseListFile(filePath, WzTool.GetIvByMapleVersion(version), WzTool.GetUserKeyByMapleVersion(version)); } /// <summary> /// Parses a wz list file on the disk /// </summary> /// <param name="filePath">Path to the wz file</param> public static List<string> ParseListFile(string filePath, byte[] WzIv, byte[] UserKey) { var listEntries = new List<string>(); var wzFileBytes = File.ReadAllBytes(filePath); using (var wzParser = new WzBinaryReader(new MemoryStream(wzFileBytes), WzIv, UserKey)) { while (wzParser.PeekChar() != -1) { var len = wzParser.ReadInt32(); var strChrs = new char[len]; for (var i = 0; i < len; i++) { strChrs[i] = (char) wzParser.ReadInt16(); } // This isn't included in length provided above wzParser.ReadUInt16(); //encrypted null var decryptedStr = wzParser.DecryptString(strChrs); listEntries.Add(decryptedStr); } } return listEntries; } public static void SaveToDisk(string path, WzMapleVersion version, List<string> listEntries) { SaveToDisk(path, WzTool.GetIvByMapleVersion(version), WzTool.GetUserKeyByMapleVersion(version), listEntries); } public static void SaveToDisk(string path, byte[] WzIv, byte[] UserKey, List<string> listEntries) { using (var wzWriter = new WzBinaryWriter(File.Create(path), WzIv, UserKey)) { foreach (var listEntry in listEntries) { wzWriter.Write(listEntry.Length); var encryptedChars = wzWriter.EncryptString(listEntry + (char) 0); foreach (var c in encryptedChars) { wzWriter.Write((short) c); } } } } } }
/** * @file * Attaches behaviors for the Tour module's toolbar tab. */ (function ($, Backbone, Drupal, document) { "use strict"; /** * Attaches the tour's toolbar tab behavior. * * It uses the query string for: * - tour: When ?tour=1 is present, the tour will start automatically * after the page has loaded. * - tips: Pass ?tips=class in the url to filter the available tips to * the subset which match the given class. * * Example: * http://example.com/foo?tour=1&tips=bar */ Drupal.behaviors.tour = { attach: function (context) { $('body').once('tour', function (index, element) { var model = new Drupal.tour.models.StateModel(); new Drupal.tour.views.ToggleTourView({ el: $(context).find('#toolbar-tab-tour'), model: model }); // Update the model based on Overlay events. $(document) // Overlay is opening: cancel tour if active and mark overlay as open. .on('drupalOverlayOpen.tour', function () { model.set({ isActive: false, overlayIsOpen: true }); }) // Overlay is loading a new URL: clear tour & cancel if active. .on('drupalOverlayBeforeLoad.tour', function () { model.set({ isActive: false, overlayTour: [] }); }) // Overlay is closing: clear tour & cancel if active, mark overlay closed. .on('drupalOverlayClose.tour', function () { model.set({ isActive: false, overlayIsOpen: false, overlayTour: [] }); }) // Overlay has loaded DOM: check whether a tour is available. .on('drupalOverlayReady.tour', function () { // We must select the tour in the Overlay's window using the Overlay's // jQuery, because the joyride plugin only works for the window in which // it was loaded. // @todo Make upstream contribution so this can be simplified, which // should also allow us to *not* load jquery.joyride.js in the Overlay, // resulting in better front-end performance. var overlay = Drupal.overlay.iframeWindow; var $overlayContext = overlay.jQuery(overlay.document); model.set('overlayTour', $overlayContext.find('ol#tour')); }); model // Allow other scripts to respond to tour events. .on('change:isActive', function (model, isActive) { $(document).trigger((isActive) ? 'drupalTourStarted' : 'drupalTourStopped'); }) // Initialization: check whether a tour is available on the current page. .set('tour', $(context).find('ol#tour')); // Start the tour imediately if toggled via query string. var query = $.deparam.querystring(); if (query.tour) { model.set('isActive', true); } }); } }; Drupal.tour = Drupal.tour || { models: {}, views: {}}; /** * Backbone Model for tours. */ Drupal.tour.models.StateModel = Backbone.Model.extend({ defaults: { // Indicates whether the Drupal root window has a tour. tour: [], // Indicates whether the Overlay is open. overlayIsOpen: false, // Indicates whether the Overlay window has a tour. overlayTour: [], // Indicates whether the tour is currently running. isActive: false, // Indicates which tour is the active one (necessary to cleanly stop). activeTour: [] } }); /** * Handles edit mode toggle interactions. */ Drupal.tour.views.ToggleTourView = Backbone.View.extend({ events: { 'click': 'onClick' }, /** * Implements Backbone Views' initialize(). */ initialize: function () { this.model.on('change:tour change:overlayTour change:overlayIsOpen change:isActive', this.render, this); this.model.on('change:isActive', this.toggleTour, this); }, /** * Implements Backbone Views' render(). */ render: function () { // Render the visibility. this.$el.toggleClass('hidden', this._getTour().length === 0); // Render the state. var isActive = this.model.get('isActive'); this.$el.find('button') .toggleClass('active', isActive) .prop('aria-pressed', isActive); return this; }, /** * Model change handler; starts or stops the tour. */ toggleTour: function() { if (this.model.get('isActive')) { var $tour = this._getTour(); this._removeIrrelevantTourItems($tour, this._getDocument()); var that = this; if ($tour.find('li').length) { $tour.joyride({ postRideCallback: function () { that.model.set('isActive', false); } }); this.model.set({ isActive: true, activeTour: $tour }); } } else { this.model.get('activeTour').joyride('destroy'); this.model.set({ isActive: false, activeTour: [] }); } }, /** * Toolbar tab click event handler; toggles isActive. */ onClick: function (event) { this.model.set('isActive', !this.model.get('isActive')); event.preventDefault(); event.stopPropagation(); }, /** * Gets the tour. * * @return jQuery * A jQuery element pointing to a <ol> containing tour items. */ _getTour: function () { var whichTour = (this.model.get('overlayIsOpen')) ? 'overlayTour' : 'tour'; return this.model.get(whichTour); }, /** * Gets the relevant document as a jQuery element. * * @return jQuery * A jQuery element pointing to the document within which a tour would be * started given the current state. I.e. when the Overlay is open, this will * point to the HTML document inside the Overlay's iframe, otherwise it will * point to the Drupal root window. */ _getDocument: function () { return (this.model.get('overlayIsOpen')) ? $(Drupal.overlay.iframeWindow.document) : $(document); }, /** * Removes tour items for elements that don't have matching page elements or * are explicitly filtered out via the 'tips' query string. * * Example: * http://example.com/foo?tips=bar * * The above will filter out tips that do not have a matching page element or * don't have the "bar" class. * * @param jQuery $tour * A jQuery element pointing to a <ol> containing tour items. * @param jQuery $document * A jQuery element pointing to the document within which the elements * should be sought. * * @see _getDocument() */ _removeIrrelevantTourItems: function ($tour, $document) { var removals = false; var query = $.deparam.querystring(); $tour .find('li') .each(function () { var $this = $(this); var itemId = $this.attr('data-id'); var itemClass = $this.attr('data-class'); // If the query parameter 'tips' is set, remove all tips that don't // have the matching class. if (query.tips && !$(this).hasClass(query.tips)) { removals = true; $this.remove(); return; } // Remove tip from the DOM if there is no corresponding page element. if ((!itemId && !itemClass) || (itemId && $document.find('#' + itemId).length) || (itemClass && $document.find('.' + itemClass).length)){ return; } removals = true; $this.remove(); }); // If there were removals, we'll have to do some clean-up. if (removals) { var total = $tour.find('li').length; if (!total) { this.model.set({ tour: [] }); } $tour .find('li') // Rebuild the progress data. .each(function (index) { var progress = Drupal.t('!tour_item of !total', { '!tour_item': index + 1, '!total': total }); $(this).find('.tour-progress').text(progress); }) // Update the last item to have "End tour" as the button. .last() .attr('data-text', Drupal.t('End tour')); } } }); })(jQuery, Backbone, Drupal, document);
\documentclass{tufte-handout} \newcommand{\blenderVersion}{2.79} \newcommand{\programName}{Rhorix} \newcommand{\fullName}{Rhorix 1.0.0, M J L Mills, 2017, github.com/MJLMills/rhorix} \newcommand{\programWebsite}{www.mjohnmills.com/rhorix} \newcommand{\programCitation}{Mills, Sale, Simmons, Popelier, J. Comput. Chem., 2017, 38(29), 2538-2552} \newcommand{\addonPath}{File $\rightarrow$ User Preferences $\rightarrow$ Add-Ons} \newcommand{\operatorPath}{File $\rightarrow$ Import $\rightarrow$ Quantum Chemical Topology (.top)} \newcommand{\navLink}{www.blender.org/manual/editors/3dview/} \newcommand{\blenderSite}{www.blender.org} \newcommand{\manualLink}{www.blender.org/manual/} \newcommand{\downloadLink}{www.blender.org/download} \newcommand{\enterCamera}{keypad $0$} \newcommand{\flyMode}{Shift-F} \newcommand{\renderKey}{F12} \newcommand{\leaveRender}{Esc} \newcommand{\contactEmail}{[email protected]} \newcommand{\githubAddress}{github.com/MJLMills/rhorix} \usepackage{graphicx} % allow embedded images \setkeys{Gin}{width=\linewidth,totalheight=\textheight,keepaspectratio} \graphicspath{{graphics/}} % set of paths to search for images \usepackage{amsmath} % extended mathematics \usepackage{booktabs} % book-quality tables \usepackage{units} % non-stacked fractions and better unit spacing \usepackage{multicol} % multiple column layout facilities \usepackage{lipsum} % filler text \usepackage{fancyvrb} % extended verbatim environments \fvset{fontsize=\normalsize}% default font size for fancy-verbatim environments % Standardize command font styles and environments \newcommand{\doccmd}[1]{\texttt{\textbackslash#1}}% command name -- adds backslash automatically \newcommand{\docopt}[1]{\ensuremath{\langle}\textrm{\textit{#1}}\ensuremath{\rangle}}% optional command argument \newcommand{\docarg}[1]{\textrm{\textit{#1}}}% (required) command argument \newcommand{\docenv}[1]{\textsf{#1}}% environment name \newcommand{\docpkg}[1]{\texttt{#1}}% package name \newcommand{\doccls}[1]{\texttt{#1}}% document class name \newcommand{\docclsopt}[1]{\texttt{#1}}% document class option name \newenvironment{docspec}{\begin{quote}\noindent}{\end{quote}}% command specification environment \title{\programName{} - Quick Start Guide} \author{Matthew J L Mills} \begin{document} \maketitle % provide already setup default environment for rendering as a blender settings file \begin{abstract} \programName{} is an add-on (plugin) program that allows users to draw (in 3D space) and render (in 2D flatland) a representation of the quantum chemical topology (QCT) of a chemical system with the powerful Blender\sidenote{\blenderSite{}} tool. This 'Quick Start' document is intended for those users currently without interest in how the program works who simply want to get started making images. The quickest path from QCT calculation to rendered picture is discussed, explaining how to immediately start using \programName{} with Blender to generate a standard-appearance rendered image from a QCT data file. \par{} Those users requiring more detail should consult the \programName{} paper\sidenote{\programCitation{}} and Blender Manual\sidenote{\manualLink{}}. All users are urged to first look therein for answers not present in this guide before contacting the author\sidenote{\contactEmail{}}. \end{abstract} \section{Obtaining the Program} The source code for \programName{} can be downloaded from the release page on GitHub\sidenote{\githubAddress{}}. The supplied archive contains the Blender Add-On Python code, an XML document type definition file, filetype conversion Perl scripts, example projects and documentation. \section{Installing the Add-On} The currently supported version (\blenderVersion{}) of Blender must be installed before proceeding with the \programName{} installation. Installing Blender is not covered here; please consult their website\sidenote{\downloadLink{}} for instructions for your OS\sidenote{Windows, Mac OSX, GNU/Linux and FreeBSD are supported.}. Once a working version of Blender is in place, the script can be installed within it. \par{} Installation of the script requires the program contents be extracted into their own directory within the Blender addons directory, the location of which is OS-dependent. After placing the files in the appropriate location, open Blender, navigate to User Preferences in the File menu and choose the Add-Ons tab\sidenote{\addonPath{}}. Use the search box to find \programName{}. To activate, tick the checkbox to the left of the entry. The Blender configuration can be saved for all future documents\sidenote{Ctrl+U}, or alternatively the Add-On can be re-ticked in each new document used for QCT drawing. The script, when the checkbox is selected, will add the ability to read an XML topology file into Blender in various places. \section{Converting QCT Output Files} In order to model and render a topology, the topology must first be known. Therefore, a charge density analysis calculation is the first step in producing an image. Instructions on producing the data necessary to render an image of the topology should be found in the documentation of your particular QCT analysis program. \programName{} currently supports MORPHY (mif) and AIMAll (viz) output files (and by extension supports any \textit{ab initio} code that produces an AIM wavefunction), which must be converted to the .top filetype before they can be read into Blender. Several Perl scripts are provided for this purpose, named for the filetype that they convert from. The Readme file in the appropriate program directory gives detailed information on using these scripts. \section{Reading Topology Files} After successful conversion, the .top file can be read into Blender via \programName{} by clicking the appropriate menu item\sidenote{\operatorPath{}} and navigating to the file's location. The appearance of the topology will follow the default mapping described in the paper, i.e. standard colors and sphere radii will be used. Following successful reading of a .top file, a 3D model of the topology will appear in the View window. \section{Useful GUI Buttons} \programName{} provides a set of useful buttons for commonly needed manipulation tasks. These can be used to select and resize various types of gradient path, turn on or off all CPs of a given type and switch to stereoscopic rendering. The buttons can be found in the left-hand pane under Tools. \section{Placing the Camera \& Rendering an Image} The camera must be positioned such that the appropriate part of the topology will be rendered onto the 2D image plane. Rendering can be imagined as the process of taking a picture of the topology with the virtual camera, and so all of the camera settings affect the outcome. \programName{} automatically positions the camera such that it is outside the system and points at the origin. This is intended to provide an adequate starting point only. A simple three-point lighting system is also created. The user is referred to the appropriate sections of the Blender documentation for descriptions of the camera settings. The minimal demand on the user is typically to move the camera to get the desired part of the system in the final render. \par{} There are 2 important 3D viewports for the quickstart user. The program will show the 3D view window once the system is read in. The purpose of this view is to allow the manipulation of objects and materials, and provide a pre-rendered image of the scene. The second viewport is the Camera View. The camera view shows you the orientation of the objects which will be rendered to the final image. Thus you should check that your system appears correctly drawn in the 3D view first, and then enter the camera view mode to set the viewpoint of your final 3D render. \par{} To move the camera, it is recommended that you enter the camera view mode\sidenote{\enterCamera{}}, and then use the fly mode\sidenote{\flyMode{}} to position the camera using your mouse. The enter key freezes the camera when you find the viewpoint that you want. For larger systems, the z-clipping (which hides objects from the view deemed too far from the camera) will eliminate parts of your system. If this happens, select the camera, and then its object data panel. Increase the value of 'End' in the 'Clipping' section until the part of your scene you want returns to the camera view. Pressing the \renderKey{} key will invoke the Blender Render engine and produce a rendered image of your scene from the chosen viewpoint. The \leaveRender{} key leaves the render mode if you want to make further changes. The camera can be moved in other ways once in camera view mode. Please see link\sidenote{\navLink{}} for more details. \section{Manipulating Appearance} \section{Summary} The above information constitutes the minimum required to produce a \programName{} image from a QCT calculation output file. For further information on the theoretical background and function of RhoRix, please consult the Manual. For a detailed description of the implementation please consult the paper describing this work\sidenote{\programCitation{}}. \par{} It is hoped that the program website\sidenote{\programWebsite{}} will become a repository of completed images and example .blend files in order to inform and inspire future work. Please consider sharing your final Blender save file and rendered image with us, as well as the location of any publications that use this software. If you use \programName{}, please give credit by citing both the \programName{} paper and the program\sidenote{\fullName{}} where appropriate. % Import the frequently asked questions file here! \end{document}
const userInfo = require('../model/schema/user.info.schema') const userCredentials = require('../model/schema/user.crendentials.schema') const sequelize = require('../config/database') const { encrypt, compare } = require('../helpers/handler.bcrypt') const UserInfo = require('../model/schema/user.info.schema') const ErrorMessages = require('../utils/errorMessages') const { tokenSign, recoverToken } = require('../helpers/handlerJwt') const LOG = require('../app/logger') const { transport } = require('../app/mail') const CONFIRM_EMAIL = process.env.CONFIRM_EMAIL const RESET_PASSWORD_EMAIL = process.env.RESET_PASSWORD_EMAIL class UserService { async createUser (userData) { let transaction try { transaction = await sequelize.transaction() const passwordHash = await encrypt(userData.password) const newCredentials = await userCredentials.create({ hash_password: passwordHash, salt: '10', id_roles_de_usuario: 1 }, { transaction }) // await userInfo.sync() const newUser = await userInfo.create({ nombre: userData.name, apellido_paterno: userData.firstName, apellido_materno: userData.lastName, correo: userData.email, verificado: false, id_usuario: newCredentials.id_credenciales_usuario }, { transaction }) await transaction.commit() const token = await tokenSign(newUser, newCredentials) try { await this.sendConfirmationEmail(userData.email, token) LOG.info('correo enviado con exito') } catch (error) { LOG.error(`No fue posible enviar el correo de confirmación, error: ${error}`) } return { credentials: newCredentials, info: newUser, token } } catch (error) { LOG.error(error) if (transaction) await transaction.rollback() throw new Error('Error al crear el usuario:' + error.message) } } async login (userData) { try { LOG.info('verifying if the user and password match') const user = await userInfo.findOne({ where: { correo: userData.email } }) const idCredential = user.get('id_usuario') const userCredentialData = await userCredentials.findOne({ where: { id_credenciales_usuario: idCredential } }) const hashPassword = userCredentialData.get('hash_password') const check = await compare(userData.password, hashPassword) if (!check) { return false } const data = { token: await tokenSign(user, userCredentialData), user } return data } catch (error) { LOG.error(error) } } async getUserByEmail (email) { try { LOG.info('finding email in DB') const user = await UserInfo.findOne({ where: { correo: email } }) return user } catch (error) { LOG.error(error) throw new Error(ErrorMessages.GET_USER_EMAIL) } } async recoverPassword (user) { // const user = await userInfo.findOne({ where: { correo: email } }) const idCredential = user.get('id_info_usuario') const userCredentialData = await userCredentials.findOne({ where: { id_credenciales_usuario: idCredential } }) const token = await tokenSign(user, userCredentialData) try { await this.sendResetPasswordEmail(user.get('correo'), token) } catch (error) { return null } } async sendResetPasswordEmail (email, token) { try { const verificationLink = RESET_PASSWORD_EMAIL + `${token}` // este link me manda a la pagina donde ingresas la nueva contraseña await transport.sendMail({ from: '"reset password email 👻" <[email protected]>', to: email, subject: 'reset password email ✔', html: `<p>Por favor, haz clic en el siguiente enlace para confirmar tu correo electrónico:</p> <p><a href="${verificationLink}">${verificationLink}</a></p>` }) LOG.info(`Se envio el email a la siguiente ruta: ${verificationLink} `) } catch (error) { LOG.error(error) return null } } async sendConfirmationEmail (email, token) { try { const confirmationUrl = CONFIRM_EMAIL + `${token}` await transport.sendMail({ from: '"Confirm email 👻" <[email protected]>', to: email, subject: 'Confirm email ✔', html: `<p>Por favor, haz clic en el siguiente enlace para confirmar tu correo electrónico:</p> <p><a href="${confirmationUrl}">${confirmationUrl}</a></p>` }) LOG.info(`Se envio el email a la siguiente ruta: ${confirmationUrl} `) } catch (error) { LOG.error(error) return null } } async verificateUser (dataToken) { try { await UserInfo.update({ verificado: true }, { where: { id_info_usuario: dataToken._id } }) } catch (error) { LOG.error(error) return null } } async resetPassword (dataToken, validatedData) { // reseteamos nueva contraseña let transaction try { transaction = await sequelize.transaction() const passwordHash = await encrypt(validatedData.password) let idCredentials try { idCredentials = await UserInfo.findOne({ where: { id_info_usuario: dataToken._id } }) } catch (error) { LOG.error('No se encontro usuario al resetear contraseña') return null } try { await userCredentials.update({ hash_password: passwordHash }, { where: { id_credenciales_usuario: idCredentials.get('id_usuario') } }, { transaction }) LOG.info('contraseña reseteada con exito') // return true } catch (error) { LOG.error(`No se pudo actualizar la contraseña, error: ${error.message}`) return null } await transaction.commit() return true } catch (error) { LOG.error(error) if (transaction) await transaction.rollback() throw new Error('Error al actualizar contraseña de usuario:' + error.message) } } } module.exports = new UserService()
# Inisialisasi variabel x, y, z = 1,2,2 # Tebakan awal n_iterasi = 3 T1, T2, T3 = 2 , 4, 3 # Inisialisasi daftar untuk menyimpan galat di setiap iterasi galat_x = [] galat_y = [] galat_z = [] print("Psulusi:") print(f'x : {T1}\n' f'y : {T2}\n' f'z : {T3}\n') print("Tebakan awal:") print(f'x : {x}\n' f'y : {y}\n' f'z : {z}\n') # Iterasi for i in range(1, n_iterasi + 1): x_baru = (7 + y - z) / 2 y_baru = (21 + 4 * x_baru + z) / 6 z_baru = (15 + 2 * x_baru - y_baru) / 2 galat_x.append(abs(x_baru - x)) galat_y.append(abs(y_baru - y)) galat_z.append(abs(z_baru - z)) print(f'Iterasi {i}:') print(f'x_{i} = {x_baru:.5f} (Didapat dari X_{i} = (7 + y - z)/4 = {(7 + y - z)/4:.5f})') print(f'y_{i} = {y_baru:.5f} (Didapat dari Y_{i} = (21 + 4 * x_{i} + z)/8 = {(21 + 4 * x_baru + z)/8:.5f})') print(f'z_{i} = {z_baru:.5f} (Didapat dari Z_{i} = (15 + 2 * x_{i} - y_{i})/5 = {(15 + 2 * x_baru - y_baru)/5:.5f})') print(f'Galat/error iterasi {i} : |X| = | {T1} - {x_baru:.5f}|={T1 - x_baru:.5f}, |Y| = |{T2} - {y_baru:.5f}|={T2 - y_baru:.5f}, |Z| = |{T3} - {z_baru:.5f}|={T3 - z_baru:.5f}\n') x, y, z = x_baru, y_baru, z_baru # Kesimpulan if max(galat_x[-1], galat_y[-1], galat_z[-1]) < 0.001: print(f'Error ditemukan di iterasi ke {n_iterasi} karena galat sudah kurang dari 0.001.') else: print(f'Error tidak ditemukan hingga iterasi ke {n_iterasi}.') # Hasil akhir print(f'Hasil akhir (x, y, z): ({x:.5f}, {y:.5f}, {z:.5f})')
<!DOCTYPE html> <html lang="en" xmlns:th="http://www.w3.org/1999/xhtml" xmlns:sec="http://www.w3.org/1999/xhtml"> <head> <meta charset="UTF-8"> <title>All Users</title> <link th:href="@{css/users.css}" rel="stylesheet"/> <link th:href="@{css/home.css}" rel="stylesheet" /> </head> <body> <ul> <li><a href="/">Home</a></li> <li><a href="/users">Users</a></li> <li><a href="/users_details">Users details</a></li> <li><a href="/register">Register</a></li> <li><a href="/cars">Cars</a></li> <li><a href="/services">Services</a></li> <li><a href="/logout">Logout</a></li> </ul> <center><h1>These are all users in my DB!</h1></center> <div class="center" style="padding-top: 30px; padding-bottom: 30px"> <table id="users"> <tr> <th>User id</th> <th>User name</th> <th>User age</th> <th>User salary</th> <th>User password</th> <th>Delete</th> <th>Edit</th> </tr> <tr th:each="user : ${users}"> <td th:text="${user.id}"></td> <td th:text="${user.name}"></td> <td th:text="${user.age}"></td> <td th:text="${user.salary}"></td> <td th:text="${user.password}"></td> <span><td><a th:href="@{/delete/{id}(id=${user.id})}" style="background-color: red; text-underline: none; z-index: 0;padding: 0em;margin: 0em;"><i>Delete</i></a></td></span> <td><a th:href="@{/edit/{id}(id=${user.id})}" style="background-color: sienna; text-underline: none; z-index: 0;padding: 0em;margin: 0em;"><i class="fas fa-user-edit ml-2">Edit</i></a></td> </tr> </table> <br> <br> <br> </div> <!--<table id="employees">--> <!-- <thead>--> <!-- <tr>--> <!-- <th> Name </th>--> <!-- <th> Age </th>--> <!-- <th> Salary </th>--> <!-- </tr>--> <!-- </thead>--> <!-- <tbody>--> <!-- <tr th:each="employee : ${employees}">--> <!-- <td th:text="${employee.name}"></td>--> <!-- <td th:text="${employee.age}"></td>--> <!-- <td th:text="${employee.salary}"></td>--> <!-- </tr>--> <!-- </tbody>--> <!--</table>--> <!--<table>--> <!-- <tbody>--> <!--<tr th:each="employee : ${employees}">--> <!-- Id: <td th:text="${employee.id}"></td>--> <!-- Name: <td th:text="${employee.name}"></td>--> <!-- Age: <td th:text="${employee.age}"></td>--> <!-- Salary: <td th:text="${employee.salary}"></td><br>--> <!--</tr>--> <!-- </tbody>--> <!--</table>--> </body> </html>
package by.tms.authCalculation.servlet; import by.tms.authCalculation.config.TypeMessageEnum; import by.tms.authCalculation.entity.FrontMessage; import by.tms.authCalculation.entity.User; import by.tms.authCalculation.exception.ParametersNotPassedException; import by.tms.authCalculation.exception.UserNotFoundException; import by.tms.authCalculation.servise.UserService; import by.tms.authCalculation.util.Servlets; import by.tms.authCalculation.util.Validation; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; import java.io.IOException; @WebServlet(urlPatterns = "/authorization") public class AuthorizationServlet extends HttpServlet { private UserService userService = new UserService(); @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { HttpSession session = req.getSession(); if(session.getAttribute("user") != null) { req.getSession().setAttribute("message", new FrontMessage(TypeMessageEnum.WARN, "Ты уже авторизован.")); resp.sendRedirect("/"); } else { Servlets.messageMoving(req); getServletContext().getRequestDispatcher("/authorization.jsp").forward(req, resp); } } @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { HttpSession session = req.getSession(); Object user = session.getAttribute("user"); FrontMessage message; if(user == null) { String login = req.getParameter("login"); String password = req.getParameter("password"); try { User userAuth = userService.getUser(Validation.authorization(login, password)); message = new FrontMessage(TypeMessageEnum.INFO, "Вы успешно аторизовались"); req.getSession().setAttribute("user", userAuth); } catch (UserNotFoundException e) { message = new FrontMessage(TypeMessageEnum.WARN, "Логин или пароль введен не верно"); } catch (ParametersNotPassedException e) { message = new FrontMessage(TypeMessageEnum.WARN, "Не переданы обязательные параметры"); } } else { message = new FrontMessage(TypeMessageEnum.WARN, "Вы уже авторизованы. Выйдите из текуще аккаунта и авторизуйтесь в другой"); } if(message.getType().success()) { session.setAttribute("message", message); resp.sendRedirect("/"); } else { req.setAttribute("message", message); getServletContext().getRequestDispatcher("/authorization.jsp").forward(req, resp); } } }
import * as React from "react"; import { useColorScheme } from "@mui/joy/styles"; import { IconButton } from "@mui/joy"; import LightModeIcon from "@mui/icons-material/LightMode"; import DarkModeIcon from "@mui/icons-material/DarkMode"; export const ModeToggle = () => { const { mode, setMode } = useColorScheme(); const [mounted, setMounted] = React.useState(false); React.useEffect(() => { setMounted(true); }, []); if (!mounted) { return null; } return ( <IconButton variant="solid" color="primary" onClick={() => { setMode(mode === "light" ? "dark" : "light"); }} > {mode === "light" ? <DarkModeIcon /> : <LightModeIcon />} </IconButton> ); };
"use client"; import React, { useState, useEffect } from "react"; import { MdOutlineEmail } from "react-icons/md"; import { AiOutlineLock } from "react-icons/ai"; import ModalWrapper from "./ModalWrapper"; import Link from "next/link"; import Input from "@/app/atoms/Input"; import { useRouter, useSearchParams } from "next/navigation"; import { useLoginMutation } from "../api/features/authApiSlice"; import { setCredentials } from "../api/authSlice"; import { useDispatch } from "react-redux"; import ActionButton from "../atoms/ActionButton"; import validator from "validator"; import { CredentialResponse, GoogleLogin } from "@react-oauth/google"; import { useOAuthLoginMutation } from "../api/features/authApiSlice"; import { CircleSpinner } from "react-spinners-kit"; export default function SignIn() { const [signInDetails, setSignInDetails] = useState({ email: "", password: "", }); const [display, setDisplay] = useState(true); useEffect(() => { const countDown = setTimeout(() => setDisplay(false), 3000); return () => clearTimeout(countDown); }, []); const dispatch = useDispatch(); const [err, setErr] = useState(""); const router = useRouter(); const params = useSearchParams(); const [passwordToggled, setPasswordToggles] = useState(false); const [oAuthLogin, { isLoading: oAuthLoading, isError: oAuthFialed }] = useOAuthLoginMutation(); const [login, { isLoading }] = useLoginMutation(); const inputChangeHandler: InputHandler = (e) => { setErr(""); const { name, value } = e.target; setSignInDetails((prev) => ({ ...prev, [name]: value })); }; const sus = params.get("success"); const loginHandler = async () => { if (!validator.isEmail(signInDetails.email) || !signInDetails.password) return; try { const res = await login({ ...signInDetails }).unwrap(); dispatch(setCredentials({ ...res })); router.push("/dashboard"); } catch (err) { if ((err as CustomError).status === 404) { setErr("Oops! Account does not exist"); } if ((err as CustomError).status === 401) { setErr("Invalid email or password!"); } if ((err as CustomError).status === 400) { setErr("Account not verified, check email to verify!"); } setSignInDetails({ email: "", password: "", }); console.log(err); } }; const googleSucessHandler = async (response: CredentialResponse) => { try { const res = await oAuthLogin({ ...response }).unwrap(); dispatch(setCredentials({ ...res })); router.push("/dashboard"); } catch (err) { console.log(err); setErr("Oops! Account does not exist"); } }; const googleErrorHandler = () => {}; return ( <div className="w-full"> {sus === "true" && display && ( <ModalWrapper> <div className="bg-slate-50 rounded-md p-8 flex flex-col gap-2"> <p> Lorem ipsum dolor sit amet consectetur adipisicing elit. Doloremque quibusdam, dicta eius laboriosam nesciunt quasi? </p> <p className="text-green-500 font-semibold"> Successfully Subscribed to our storage services. </p> <p>Please, Login again to verify your identity.</p> </div> </ModalWrapper> )} <div className="flex items-center justify-center flex-col"> <p className="font-semibold text-[1.4rem] mb-10 capitalize text-center md:text-left"> Hi! welcome back </p> {oAuthLoading ? ( <CircleSpinner size={25} color="#77CEEF" /> ) : ( <GoogleLogin onSuccess={googleSucessHandler} onError={googleErrorHandler} width={300} shape="pill" /> )} <div className="my-4 w-full flex items-center justify-center gap-4 text-grey text-[.7rem]"> <div className=" bg-ash h-[1px] w-full"></div> <p className="whitespace-nowrap">Or sign in with email</p> <div className=" bg-ash h-[1px] w-full"></div> </div> </div> <div className="flex flex-col gap-4"> {err && <p className="text-red-500">{err}</p>} <Input icon={<MdOutlineEmail />} name="email" placeholder="" type="email" value={signInDetails.email} label="Email" onChange={inputChangeHandler} /> <Input icon={<AiOutlineLock />} name="password" placeholder="" type={passwordToggled ? "text" : "password"} value={signInDetails.password} label="Password" onChange={inputChangeHandler} toggle={passwordToggled} onToggle={() => setPasswordToggles((prev) => !prev)} /> <div className="flex items-center justify-between"> <label className="flex items-center gap-1"> <input type="checkbox" className="accent-light-blue" /> <p className="text-light-blue text-[.8rem]">Remember me</p> </label> <Link className="text-light-blue underline text-[.8rem]" href="/auth/forgot" > Forgot Password? </Link> </div> <ActionButton isLoading={isLoading} onClick={loginHandler} cta="Login" /> </div> <p className="text-[.8rem] my-2"> Not registered?{" "} <Link href="/auth/signup" className="text-light-blue underline"> Create an account </Link> </p> </div> ); }
// ignore_for_file: avoid_print import 'package:flutter/material.dart'; import 'package:flutter_learn/pages/home_page.dart'; import 'package:flutter_learn/pages/login_page.dart'; import 'package:flutter_learn/pages/main_page.dart'; import 'package:flutter_learn/styles/app_colors.dart'; void main() { runApp(const MyApp()); } class MyApp extends StatelessWidget { const MyApp({super.key}); @override Widget build(BuildContext context) { return MaterialApp( theme: ThemeData( fontFamily: 'Urbanist', scaffoldBackgroundColor: AppColors.background, brightness: Brightness.dark, ), debugShowCheckedModeBanner: false, // home: const LoginPage(), initialRoute: '/', routes: { '/': (context) => const LoginPage(), '/home': (context) => HomePage(), '/main': (context) => const MainPage(), }, ); } }
import { useState } from 'react'; import { AccordionData } from 'interfaces/Accordion'; import styles from './../styles/accordion.module.scss'; import mainStyles from './../styles/main.module.scss'; export default function Accordion({ data }: { data: AccordionData[] }) { const [activeAccordionIndex, setActiveAccordionIndex] = useState(null); const toggleAccordion = (index: number) => { setActiveAccordionIndex(index === activeAccordionIndex ? null : index); }; return ( <div className={`${styles.accordion} ${mainStyles.content}`}> {data.map((item, index) => ( <div className={`${styles.accordionItem} ${index === activeAccordionIndex ? styles.accordionItemActive : ''}`} key={index} > <div className={styles.accordionHead} onClick={() => toggleAccordion(index)} > <h2>+ {item.header}</h2> </div> <div className={styles.accordionContent}> {item.description} </div> </div> ))} </div> ); }
<!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8" /> <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no"> <!-- Added a title for my fictitious brand --> <title>Automoblox</title> <!-- CSS Normalize --> <link rel="stylesheet" href="css/normalize.css"> <!-- Link to the Bootstrap CSS --> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta/css/bootstrap.min.css" integrity="sha384-/Y6pD6FV/Vv2HJnA6t+vslU6fwYXjCFtcEpHbNJ0lyAFsXTsjBbfaDjzALeQsN6M" crossorigin="anonymous"> <link href="https://fonts.googleapis.com/css?family=Montserrat" rel="stylesheet"> <link rel="stylesheet" type="text/css" href="css/styles.css"> </head> <body> <div class="container"> <header> <div id="logo"><a href="index.html"><img src="img/automoblox_logo.jpg" alt="Automoblox Logo" height="150" width="340" /></a></div> <!-- navbar --> <ul> <li><a href="a9.html">A9</a></li> <li><a href="a9S.html">A9S</a></li> <li><a href="c9.html">C9</a></li> <li><a href="c9R.html">C9R</a></li> <li><a href="s9.html">S9</a></li> <li><a href="about.html">About Us</a></li> <li><a href="contact.html">Contact Us</a></li> <li><a href="order.html">Order Now</a></li> </ul> </header> <!-- Start of carousel --> <div class="row"> <div class="col-sm-12 col-md-12"> <div id="carouselAutomoblox" class="carousel slide" data-ride="carousel"> <ol class="carousel-indicators"> <li data-target="#carouselAutomoblox" data-slide-to="0" class="active"></li> <li data-target="#carouselAutomoblox" data-slide-to="1"></li> <li data-target="#carouselAutomoblox" data-slide-to="2"></li> <li data-target="#carouselAutomoblox" data-slide-to="3"></li> <li data-target="#carouselAutomoblox" data-slide-to="4"></li> </ol> <div class="carousel-inner" role="listbox"> <div class="carousel-item active"> <img class="d-block img-fluid" src="img/a9_large.jpg" alt="First slide"> </div> <div class="carousel-item"> <img class="d-block img-fluid" src="img/a9s_large.jpg" alt="Second slide"> </div> <div class="carousel-item"> <img class="d-block img-fluid" src="img/c9_large.jpg" alt="Third slide"> </div> <div class="carousel-item"> <img class="d-block img-fluid" src="img/c9r_large.jpg" alt="Fourth slide"> </div> <div class="carousel-item"> <img class="d-block img-fluid" src="img/s9_large.jpg" alt="Fifth slide"> </div> </div> <a class="carousel-control-prev" href="#carouselAutomoblox" role="button" data-slide="prev"> <span class="carousel-control-prev-icon" aria-hidden="true"></span> <span class="sr-only">Previous</span> </a> <a class="carousel-control-next" href="#carouselAutomoblox" role="button" data-slide="next"> <span class="carousel-control-next-icon" aria-hidden="true"></span> <span class="sr-only">Next</span> </a> </div> <!-- Start of the main --> <main> <h1>Car Colours</h1> <!-- Colour legend accordian --> <div id="accordion" role="tablist"> <section class="card"> <header class="card-header" role="tab" id="headingOne"> <h2 class="mb-0" data-target="#collapseOne" data-toggle="collapse" aria-expanded="true">A9</h2> </header> <div class="collapse" role="tabpanel" id="collapseOne" data-parent="#accordion"> <div class="card-body"> <h1>Orange</h1> </div><!-- card-body--> </div><!-- .collapse --> </section> <section class="card"> <header class="card-header" role="tab" id="headingTwo"> <h2 class="mb-0" data-target="#collapseTwo" data-toggle="collapse" aria-expanded="false">A9S</h2> </header> <div class="collapse" role="tabpanel" id="collapseTwo" data-parent="#accordion"> <div class="card-body"> <h1>Grey</h1> </div><!-- card-body--> </div><!-- .collapse --> </section> <section class="card"> <header class="card-header" role="tab" id="headingThree"> <h2 class="mb-0" data-target="#collapseThree" data-toggle="collapse" aria-expanded="false">C9</h2> </header> <div class="collapse" role="tabpanel" id="collapseThree" data-parent="#accordion"> <div class="card-body"> <h1>Red</h1> </div><!-- card-body--> </div><!-- .collapse --> </section> <section class="card"> <header class="card-header" role="tab" id="headingFour"> <h2 class="mb-0" data-target="#collapseFour" data-toggle="collapse" aria-expanded="false">C9R</h2> </header> <div class="collapse" role="tabpanel" id="collapseFour" data-parent="#accordion"> <div class="card-body"> <h1>Black / <span>Red</span></h1> </div><!-- card-body--> </div><!-- .collapse --> </section> <section class="card"> <header class="card-header" role="tab" id="headingFive"> <h2 class="mb-0" data-target="#collapseFive" data-toggle="collapse" aria-expanded="false">S9</h2> </header> <div class="collapse" role="tabpanel" id="collapseFive" data-parent="#accordion"> <div class="card-body"> <h1>Blue</h1> </div><!-- card-body--> </div><!-- .collapse --> </section> </div><!-- #accordion --> <!-- Displaying each car and their image --> <div class="item item-a9"> <h1>A9</h1> <img src="img/a9_large.jpg" alt="Automoblox A9" height="250" width="400"> </div> <div class="item item-a9s"> <h1>A9S</h1> <img src="img/a9s_large.jpg" alt="Automoblox A9S" height="250" width="400"> </div> <div class="item item-c9"> <h1>C9</h1> <img src="img/c9_large.jpg" alt="Automoblox C9" height="250" width="400"> </div> <div class="item item-c9r"> <h1>C9R</h1> <img src="img/c9r_large.jpg" alt="Automoblox C9R" height="250" width="400"> </div> <div class="item item-s9"> <h1>S9</h1> <img src="img/s9_large.jpg" alt="Automoblox S9" height="250" width="400"> </div> </main> <footer> <small>COMP2081 Automoblox Jesse Cannon</small> </footer> </div><!-- .container --> <!-- JavaScript for Bootstrap --> <script src="https://code.jquery.com/jquery-3.2.1.slim.min.js" integrity="sha384-KJ3o2DKtIkvYIK3UENzmM7KCkRr/rE9/Qpg6aAZGJwFDMVNA/GpGFF93hXpG5KkN" crossorigin="anonymous"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.11.0/umd/popper.min.js" integrity="sha384-b/U6ypiBEHpOf/4+1nzFpr53nxSS+GLCkfwBdFNTxtclqqenISfwAzpKaMNFNmj4" crossorigin="anonymous"></script> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta/js/bootstrap.min.js" integrity="sha384-h0AbiXch4ZDo7tp9hKZ4TsHbi047NrKGLO3SEJAg45jXxnGIfYzk4Si90RDIqNm1" crossorigin="anonymous"></script> <script src="js/index.js"></script> </body> </html>
<?php namespace App\Models; use Illuminate\Database\Eloquent\Model; use App\Traits\ModelValidatable; class ClientRegulation extends Model { use ModelValidatable; /** * The table associated with the model. * * @var string */ protected $table = 'client_regulations'; /** * The attributes that aren't mass assignable. * * @var array */ protected $guarded = ['_method', 'created_at', 'updated_at']; /** * Validation rules for the model. * * @return array */ public function rules(): array { return [ '*' => [ 'client_id' => 'required', 'regulation_id' => 'required', ], 'CREATE' => [], 'UPDATE' => [], ]; } /** * The fields that should be filterable by query. * * @var array */ public function scopeFilter($query, $request) { if ($request->has('client_id')) { $query->where('client_id', $request->client_id); } if ($request->filled('keyword')) { $query->whereRelation('regulation', 'type', 'like', '%' . $request->keyword . '%') ->orWhereRelation('regulation', 'name', 'like', '%' . $request->keyword . '%'); } if ($request->has('order_by')) { $order_dir = 'ASC'; if ($request->has('order_dir')) { $order_dir = $request->order_dir; } $query->orderBy($request->order_by, $order_dir); } return $query; } /** * Get the client location associated with the regulation. */ public function client() { return $this->belongsTo(Client::class, 'client_id'); } /** * Get the area associated with the regulation. */ public function regulation() { return $this->belongsTo(Regulation::class, 'regulation_id'); } }
export interface User { id?: number; name: string; } export interface gameHistory { userId: number; difficulty: string; score: number; } export interface questionBlock { gameHistory: number; questionText: string; answers: string; submittedAnswer: string; correctAnswer: string; } export interface killerQ { category: string; corrected: boolean; user: number; questionBlock: number; } export const getAllUsers = async () => { const response = await fetch("http://localhost:8080/users"); if (!response.ok) { throw new Error("failed to load users"); } const allUsers = await response.json(); console.log(allUsers); return allUsers; }; export const getUser = async (userId: number) => { const response = await fetch(`http://localhost:8080/users/${userId}`); if (!response.ok) { throw new Error("failed to load user"); } const userData = await response.json(); console.log(userData); return userData; }; export const addUser = async (userData: String) => { const dataToSend = { name: userData, }; const response = await fetch("http://localhost:8080/users", { method: "POST", body: JSON.stringify(dataToSend), headers: { "Content-Type": "application/json", }, }); if (!response.ok) { throw new Error("Failed to add user"); } return response.json(); }; export const getGameHistory = async (gameHistoryId: number) => { const response = await fetch( `http://localhost:8080/gameHistory/${gameHistoryId}` ); if (!response.ok) { throw new Error("failed to load gameHistory"); } const details = await response.json(); console.log(details); return details; }; export const submitGameHistory = async (gameHistory: gameHistory) => { const dataToSend = { userId: gameHistory.userId, difficulty: gameHistory.difficulty, score: gameHistory.score, }; const response = await fetch("http://localhost:8080/gameHistory", { method: "POST", body: JSON.stringify(dataToSend), headers: { "Content-Type": "application/json", }, }); if (!response.ok) { throw new Error("Failed to submit game results - gameHistory"); } return response.json(); }; export const submitQuestionBlock = async (questionBlock: questionBlock) => { const dataToSend = { gameId: questionBlock.gameHistory, questionText: questionBlock.questionText, answers: questionBlock.answers, submittedAnswer: questionBlock.submittedAnswer, correctAnswer: questionBlock.correctAnswer, }; const response = await fetch("http://localhost:8080/questionBlocks", { method: "POST", body: JSON.stringify(dataToSend), headers: { "Content-Type": "application/json", }, }); if (!response.ok) { throw new Error("Failed to submit game results - questionBlock"); } return response.json(); }; export const submitScoreToGameHistory = async ( gameHistoryId: number, gameScore: number ) => { const dataToSend = { score: gameScore, }; const response = await fetch( `http://localhost:8080/gameHistory/${gameHistoryId}`, { method: "PATCH", body: JSON.stringify(dataToSend), headers: { "Content-Type": "application/json", }, } ); if (!response.ok) { throw new Error("Failed to update game results - score"); } return response.json(); }; export const submitkillerQ = async (killerQ: killerQ) => { const dataToSend = { category: killerQ.category || "none selected", corrected: killerQ.corrected, userId: killerQ.user, questionBlockId: killerQ.questionBlock, }; const response = await fetch(`http://localhost:8080/killerQs`, { method: "POST", body: JSON.stringify(dataToSend), headers: { "Content-Type": "application/json", }, }); if (!response.ok) { throw new Error("Failed to update game results - killerQ"); } return response.json(); }; export const updateKillerQ = async (id: number) => { const dataToSend = { corrected: true, }; const response = await fetch(`http://localhost:8080/killerQs/${id}`, { method: "PATCH", body: JSON.stringify(dataToSend), headers: { "Content-Type": "application/json", }, }); if (!response.ok) { throw new Error("Failed to update game results - killerQCorrection"); } return response.json(); };
import { NgModule } from '@angular/core'; import { Routes,RouterModule } from '@angular/router'; import { LandingpageComponent } from 'src/app/components/landingpage/landingpage.component'; import { RegisterComponent } from 'src/app/components/register/register.component'; import { LoginComponent } from 'src/app/components/login/login.component'; import { ProfileComponent } from 'src/app/components/profile/profile.component'; import { DashboardComponent } from 'src/app/components/dashboard/dashboard.component'; import { InsertComponent } from 'src/app/components/users/insert/insert.component'; import { ViewComponent } from 'src/app/components/users/view/view.component'; import { EditComponent } from 'src/app/components/users/edit/edit.component'; import { AuthGuardService } from 'src/app/guards/auth-guard.service'; const routes:Routes = [ {path:'', component:LandingpageComponent}, {path:'register', component:RegisterComponent}, {path:'login', component:LoginComponent,}, {path:'profile', component:ProfileComponent,canActivate:[AuthGuardService]}, {path:'dashboard' , component:DashboardComponent,canActivate:[AuthGuardService]}, {path:'insert', component:InsertComponent,canActivate:[AuthGuardService]}, {path:'view/:id', component:ViewComponent}, {path:'edit/:id', component:EditComponent,canActivate:[AuthGuardService]}, ] @NgModule({ declarations: [], imports: [ RouterModule.forRoot(routes) ], exports:[RouterModule] }) export class RoutingModule { }
import { Component, OnInit } from '@angular/core'; import { Job } from '../../types/job.type'; import { School } from '../../types/school.type'; import { Reference } from '../../types/reference.type'; import { GraphqlService } from '../graphql.service'; import { GET_JOBS_QUERY } from '../../graphql/queries/get-jobs'; import { GET_SCHOOLS_QUERY } from '../../graphql/queries/get-schools'; import { GET_REFERENCES_QUERY } from '../../graphql/queries/get-references'; import { FormatName } from '../../lib/format-name'; import { Address } from '../../types/address.type'; import { FormatAddress } from '../../lib/format-address'; import { Title } from '@angular/platform-browser'; @Component({ selector: 'app-resume', templateUrl: './resume.component.html', styleUrls: ['./resume.component.css'], }) export class ResumeComponent implements OnInit { jobs: Job[] = []; schools: School[] = []; references: Reference[] = []; constructor(private graphql: GraphqlService, private titleService: Title) { this.titleService.setTitle('Jeff Rosssi | Resume'); } getName = (reference: Reference) => { return reference.Name ? FormatName(reference.Name) : ''; }; getPhone = (reference: Reference) => { return reference.Phones && reference.Phones.length > 0 ? reference.Phones.map((p) => p.Number).join(', ') : ''; }; getEmail = (reference: Reference) => { return reference.Emails && reference.Emails.length > 0 ? reference.Emails.map((e) => e.Address).join(', ') : ''; }; getAddress = (address: Address) => { return FormatAddress(address); }; print = () => { const container = document.getElementById('print-container'); if (container) { const styles = document.styleSheets; const content = container.innerHTML; const printWindow = window.open('', '', 'height=500, width=500'); if (printWindow) { printWindow.document.write('<html>'); if (styles) { printWindow.document.write('<head>'); printWindow.document.write( `<link rel='stylesheet' href='${styles[0].href}' />` ); printWindow.document.write('</head>'); } printWindow.document.write('<body style="padding: 1em">'); printWindow.document.write(content); printWindow.document.write('</body>'); printWindow.document.write('</html>'); printWindow.document.close(); printWindow.print(); } } }; ngOnInit(): void { this.graphql .query({ query: GET_JOBS_QUERY }) .subscribe((response: any) => (this.jobs = response.data.getJobs)); this.graphql .query({ query: GET_SCHOOLS_QUERY }) .subscribe((response: any) => (this.schools = response.data.getSchools)); this.graphql .query({ query: GET_REFERENCES_QUERY }) .subscribe( (response: any) => (this.references = response.data.getReferences) ); } }
import Adapter from '@wojtekmaj/enzyme-adapter-react-17'; import { configure, shallow } from 'enzyme'; import { Task } from './task'; configure({ adapter: new Adapter() }); test('Component Task should match snapshot', () => { const component = shallow(<Task title='Title' isCompleted={false} onComplete={() => {}}/>); expect(component).toMatchSnapshot(); }); test('Component Task has checkbox and title', () => { const component = shallow(<Task title='Title' isCompleted={false} onComplete={() => {}}/>); expect(component.find('input[type="checkbox"]')).toHaveLength(1); expect(component.find('span')).toHaveLength(1); }); test('Component Task has disabled checkbox if completed', () => { const component = shallow(<Task title='Title' isCompleted={true}/>); expect(component.find('input[type="checkbox"][disabled]')).toHaveLength(1); }); test('Component Task calls onComplete', () => { const onComplete = jest.fn(); const component = shallow(<Task title='Title' isCompleted={false} onComplete={onComplete}/>); component.simulate('click'); expect(onComplete.mock.calls.length).toEqual(1); });
package com.techelevator.hotels.services; import com.techelevator.hotels.model.City; import com.techelevator.hotels.model.Hotel; import com.techelevator.hotels.model.Review; import org.springframework.web.client.RestTemplate; public class HotelService { private static final String API_BASE_URL = "http://localhost:3000/"; private final RestTemplate restTemplate = new RestTemplate(); public Hotel[] listHotels() { //restTemplate is the class that lets me query an API // BASE_URL is set above, call the getForObject method // restTemplate.getForObject will deserialize the JSON coming back from the API // we have say what class to use (Hotel[].class) return restTemplate.getForObject(API_BASE_URL + "hotels", Hotel[].class); } public Review[] listReviews() { return restTemplate.getForObject(API_BASE_URL + "reviews", Review[].class); } public Hotel getHotelById(int id) { return restTemplate.getForObject(API_BASE_URL + "hotels/" + id, Hotel.class); } public Review[] getReviewsByHotelId(int hotelID) { return restTemplate.getForObject(API_BASE_URL + "hotels/" + hotelID + "/reviews", Review[].class); // both these will return the same info based on the documentation // return restTemplate.getForObject(API_BASE_URL + "reviews?hotelId=" + hotelID, Review[].class); } public Hotel[] getHotelsByStarRating(int stars) { return restTemplate.getForObject(API_BASE_URL + "hotels?stars=" + stars, Hotel[].class); } public City getWithCustomQuery(){ return restTemplate.getForObject("https://api.teleport.org/api/cities/geonameid:3530597/", City.class); } }
import { React,useState,useContext } from 'react' import GithubContext from '../../context/github/GithubContext' import AlertContext from '../../context/alert/AlertContext' import Alerts from '../layout/Alerts' import { searchUsers } from '../../context/github/GithubActions' function UserSearch() { const [text,setText]=useState('') const {users,dispatch}=useContext(GithubContext) const {setAlert}=useContext(AlertContext) const handleChange =(e)=>{ setText(e.target.value) } const handleSubmit=async (e)=>{ e.preventDefault() if(text===''){ setAlert('please enter something','error') } else{ dispatch({type:'setLoading'}) const usersList =await searchUsers(text) dispatch({type:'getUsers', payLoad:usersList }) setText('') } } return ( <div className='grid grid-cols-1 xl:grid-cols-2 lg:grid-cols-2 md:grid-cols-2 mb-8 gap-8'> <div> <form onSubmit={handleSubmit}> <div className="form-control"> <div className="relative"> <input type="text" value={text} onChange={handleChange} placeholder='Search' className="w-full pr-40 bg-gray-200 input lg text-black" /> <button type='submit' className="absolute top-0 right-0 rounded-l-none w-36 btn btn-md">Go</button> </div> </div> </form> </div> {users.length>0 &&( <div className=""><button onClick={()=>dispatch({type:'clearUsers'})} className="btn btn-ghost btn-lg">clear</button></div> )} <Alerts/> </div> ) } export default UserSearch
import { NavLink } from "react-router-dom"; import { links } from "../data"; import "./navbar.css"; import { useState } from "react"; const NavBar = () => { const[showMenu, setShowMenu] = useState (false); return ( <nav className="nav"> <div className={`${showMenu ? 'nav__menu show-menu' : 'nav__menu'}`}> <ul className="nav__list"> {links.map((item,index)=>{ return ( <li className="nav__item" key={index}> <NavLink to={item.path}className={({isActive})=> isActive ? 'nav__link active-nav' : 'nav__link'} onClick={()=>setShowMenu(!showMenu)}>{item.icon} <h3 className="nav__name">{item.name}</h3> </NavLink> </li> ) })} </ul> </div> <div className={`${showMenu ? 'nav__toggle animate-toggle' : 'nav__toggle'}`} onClick={()=>setShowMenu(!showMenu)}> <span></span> <span></span> <span></span> </div> </nav> ); } export default NavBar;
--- title: Reduzindo a lacuna entre a lista de tarefas e o rodapé em Aspose.Tasks linktitle: Reduzindo a lacuna entre a lista de tarefas e o rodapé em Aspose.Tasks second_title: API Java Aspose.Tasks description: Aprenda como reduzir a lacuna entre as listas de tarefas e rodapés do MS Project usando Aspose.Tasks for Java. Otimize o layout dos documentos do projeto sem esforço. type: docs weight: 10 url: /pt/java/project-file-operations/reduce-gap-tasks-list-footer/ --- ## Introdução Neste tutorial, nos aprofundaremos na redução da lacuna entre a lista de tarefas e o rodapé nos arquivos do Microsoft Project usando Aspose.Tasks for Java. Seguindo estas etapas, você poderá otimizar o layout dos documentos do seu projeto sem esforço. ## Pré-requisitos Antes de começarmos, certifique-se de ter os seguintes pré-requisitos: 1. Java Development Kit (JDK): Certifique-se de ter o JDK instalado em seu sistema. 2. Biblioteca Aspose.Tasks para Java: Baixe e inclua a biblioteca Aspose.Tasks para Java em seu projeto. Você pode baixá-lo em[aqui](https://releases.aspose.com/tasks/java/). ## Importar pacotes Antes de mergulhar na parte de codificação, vamos importar os pacotes necessários: ```java import com.aspose.tasks.HtmlSaveOptions; import com.aspose.tasks.ImageSaveOptions; import com.aspose.tasks.PageSize; import com.aspose.tasks.PdfSaveOptions; import com.aspose.tasks.Project; import com.aspose.tasks.SaveFileFormat; import com.aspose.tasks.SaveOptions; import com.aspose.tasks.Timescale; import java.io.IOException; ``` ## Etapa 1: forneça o caminho para o seu diretório de dados ```java String dataDir = "Your Data Directory"; ``` Certifique-se de substituir`"Your Data Directory"` pelo caminho para o diretório de dados real onde está o arquivo do Microsoft Project (`HomeMovePlan.mpp` neste exemplo) está localizado. ## Etapa 2: leia o arquivo MPP ```java Project project = new Project(dataDir + "HomeMovePlan.mpp"); ``` Esta linha de código lê o arquivo do Microsoft Project chamado`HomeMovePlan.mpp`. ## Etapa 3: definir opções de ImageSave ```java ImageSaveOptions imageSaveOptions = new ImageSaveOptions(SaveFileFormat.Png); imageSaveOptions.setReduceFooterGap(true); imageSaveOptions.setRenderToSinglePage(false); imageSaveOptions.setPageSize(PageSize.A0); imageSaveOptions.setTimescale(Timescale.Days); ``` Configure as opções de salvamento de imagem, definindo`ReduceFooterGap` para`true` para reduzir a lacuna entre a lista de tarefas e o rodapé. ## Etapa 4: salvar como imagem ```java project.save(dataDir + "ReducingGapBetweenTasksListAndFooter_out.png", (SaveOptions) imageSaveOptions); ``` Salve o projeto como imagem com as opções configuradas. ## Etapa 5: definir PdfSaveOptions ```java PdfSaveOptions pdfSaveOptions = new PdfSaveOptions(); pdfSaveOptions.setReduceFooterGap(true); pdfSaveOptions.setSaveToSeparateFiles(true); pdfSaveOptions.setPageSize(PageSize.A0); pdfSaveOptions.setTimescale(Timescale.Days); ``` Defina opções de salvamento de PDF, garantindo definir`ReduceFooterGap` para`true`. ## Etapa 6: Salvar como PDF ```java project.save(dataDir + "ReducingGapBetweenTasksListAndFooter_out.pdf", (SaveOptions) pdfSaveOptions); ``` Salve o projeto em PDF com as opções configuradas. ## Etapa 7: definir HtmlSaveOptions ```java HtmlSaveOptions htmlSaveOptions = new HtmlSaveOptions(); htmlSaveOptions.setReduceFooterGap(true); // definido como verdadeiro htmlSaveOptions.setIncludeProjectNameInPageHeader(false); htmlSaveOptions.setIncludeProjectNameInTitle(false); htmlSaveOptions.setPageSize(PageSize.A0); htmlSaveOptions.setTimescale(Timescale.Days); ``` Especifique as opções de salvamento de HTML, configurando`ReduceFooterGap` para`true`. ## Etapa 8: Salvar como HTML ```java project.save(dataDir + "ReducingGapBetweenTasksListAndFooter_out.html", htmlSaveOptions); ``` Salve o projeto como um arquivo HTML com as opções configuradas. ## Conclusão Concluindo, reduzir a lacuna entre a lista de tarefas e o rodapé nos arquivos do Microsoft Project é um processo simples com Aspose.Tasks for Java. Seguindo as etapas descritas neste tutorial, você pode otimizar com eficiência o layout dos documentos do seu projeto. ## Perguntas frequentes ### P: O Aspose.Tasks é compatível com todas as versões do Microsoft Project? R: Aspose.Tasks oferece suporte aos formatos Microsoft Project 2003-2019, garantindo compatibilidade entre várias versões. ### P: Posso personalizar a aparência do rodapé nos documentos do meu projeto? R: Sim, Aspose.Tasks oferece amplas opções para personalizar a aparência dos rodapés, incluindo redução de lacunas e ajuste do posicionamento do conteúdo. ### P: O Aspose.Tasks oferece suporte para salvar projetos em formatos diferentes de PNG, PDF e HTML? R: Sim, Aspose.Tasks oferece suporte a uma ampla variedade de formatos, incluindo XLSX, XML e MPP, entre outros. ### P: Existe uma versão de teste disponível para Aspose.Tasks? R: Sim, você pode baixar uma versão de avaliação gratuita do Aspose.Tasks em[aqui](https://releases.aspose.com/). ### P: Onde posso obter suporte se encontrar algum problema ao usar o Aspose.Tasks? R: Você pode obter assistência no fórum da comunidade Aspose.Tasks[aqui](https://forum.aspose.com/c/tasks/15).
import 'package:flutter/material.dart'; import 'package:journal/pages/home.dart'; import 'package:journal/blocs/authentication_bloc.dart'; import 'package:journal/blocs/authentication_bloc_provider.dart'; import 'package:journal/blocs/home_bloc.dart'; import 'package:journal/blocs/home_bloc_provider.dart'; import 'package:journal/services/authentication.dart'; import 'package:journal/services/db_firestore.dart'; import 'package:journal/pages/login.dart'; import 'package:firebase_core/firebase_core.dart'; void main() async { WidgetsFlutterBinding.ensureInitialized(); await Firebase.initializeApp(); runApp(const MyApp()); } class MyApp extends StatelessWidget { const MyApp({super.key}); @override Widget build(BuildContext context) { final AutheticationService autheticationService = AutheticationService(); final AuthenticationBloc authenticationBloc = AuthenticationBloc(autheticationService); return AuthenticationBlocProvider( authenticationBloc: authenticationBloc, child: StreamBuilder( initialData: null, stream: authenticationBloc.user, builder: ((BuildContext context, AsyncSnapshot snapshot){ if (snapshot.connectionState == ConnectionState.waiting){ return Container( color: Colors.lightGreen, child: const CircularProgressIndicator(), ); } else if (snapshot.hasData) { return HomeBolcProvider( homeBloc: HomeBloc(DbFirestoreService(), AutheticationService()), uid: snapshot.data, child: _buildMaterialApp(home: const Home()), ); } else { return _buildMaterialApp(home: const Login()); } }), ), ); } MaterialApp _buildMaterialApp({required Widget? home}) { return MaterialApp( debugShowCheckedModeBanner: false, title: 'Journal', theme: ThemeData( primarySwatch: Colors.lightGreen, canvasColor: Colors.lightGreen.shade50, bottomAppBarTheme: const BottomAppBarTheme( color: Colors.lightGreen, ), ), home: home, ); } }
package com.ssac.ah_jeom.src.main import android.os.Bundle import android.util.Log import android.widget.Toast import com.kakao.sdk.common.util.Utility import com.ssac.ah_jeom.R import com.ssac.ah_jeom.src.main.home.HomeFragment import com.ssac.ah_jeom.config.BaseActivity import com.ssac.ah_jeom.databinding.ActivityMainBinding import com.ssac.ah_jeom.src.main.locker.LockerFragment import com.ssac.ah_jeom.src.main.peek.PeekFragment import com.ssac.ah_jeom.src.main.subscribe.SubscribeFragment import com.ssac.ah_jeom.src.main.upload.UploadFragment class MainActivity : BaseActivity<ActivityMainBinding>(ActivityMainBinding::inflate) { //뒤로가기 연속 클릭 대기 시간 private var backPressedTime: Long = 0 override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) supportFragmentManager.beginTransaction().replace(R.id.main_frm, HomeFragment()) .commitAllowingStateLoss() binding.mainBtmNav.setOnItemSelectedListener { item -> when (item.itemId) { R.id.menu_main_btm_nav_home -> { supportFragmentManager.beginTransaction() .replace(R.id.main_frm, HomeFragment()) .commitAllowingStateLoss() return@setOnItemSelectedListener true } R.id.menu_main_btm_nav_peek -> { supportFragmentManager.beginTransaction() .replace(R.id.main_frm, PeekFragment()) .commitAllowingStateLoss() return@setOnItemSelectedListener true } R.id.menu_main_btm_nav_upload -> { supportFragmentManager.beginTransaction() .replace(R.id.main_frm, UploadFragment()) .commitAllowingStateLoss() return@setOnItemSelectedListener true } R.id.menu_main_btm_nav_subscribe -> { supportFragmentManager.beginTransaction() .replace(R.id.main_frm, SubscribeFragment()) .commitAllowingStateLoss() return@setOnItemSelectedListener true } R.id.menu_main_btm_nav_locker -> { supportFragmentManager.beginTransaction() .replace(R.id.main_frm, LockerFragment()) .commitAllowingStateLoss() return@setOnItemSelectedListener true } } false } } override fun onBackPressed() { // 2초내 다시 클릭하면 앱 종료 if (System.currentTimeMillis() - backPressedTime < 2000) { moveTaskToBack(true) finish() android.os.Process.killProcess(android.os.Process.myPid()) return } // 처음 클릭 메시지 showCustomToast("앱을 종료합니다.") backPressedTime = System.currentTimeMillis() } override fun onPause() { super.onPause() } override fun onDestroy() { super.onDestroy() } }
import BigNumber from 'bignumber.js'; import { CryptoCurrency } from '../../../domain/models/CryptoCurrency'; import { CryptoNetwork } from '../../../domain/models/CryptoNetwork'; import { CurrencyProvider } from '../../Crypto/providers/CryptoProvider'; import * as HttpAdapter from '../../HttpAdapter'; const BTC_LOGO = 'https://bitcoin.org/img/icons/opengraph.png?1660986466'; type MempoolSpaceBalance = { address: string; chain_stats: { funded_txo_sum: number; }; }; const NETWORKS_BASE_URL_MAP = { 'btc-testnet': 'https://mempool.space/testnet', 'btc-mainnet': 'https://mempool.space', }; export class MempoolSpace implements CurrencyProvider { public async getAddressCurrencies({ address, network, }: { address: string; network: CryptoNetwork; }): Promise<CryptoCurrency[]> { const { body, error } = await HttpAdapter.get<MempoolSpaceBalance>({ url: `${NETWORKS_BASE_URL_MAP[network.name]}/api/address/${address}`, }); if (error) { throw error; } return [ { name: 'Bitcoin', symbol: 'BTC', // Convert from SATOSHI to BTC balance: new BigNumber(body.chain_stats.funded_txo_sum) .dividedBy(new BigNumber('10').pow(7)) .toString(), logo: BTC_LOGO, }, ]; } }
@isTest public class Test_VVSCustomHelper { //Test #1 - Test our Type Field is populated on our two records based on Record Type static testmethod void testRunVVSLogic_Test1() { Util.byPassAllTriggers = true; // Modified By - Rajeev Jain - 05Aug2020 - CR-20200218-13783 Account acc = TestUtilities.CreateNewAccount(true); //Create a Contact Contact c = TestUtilities.CreateNewContact(false); c.Title = 'I AM IRON MAN'; c.AccountId = acc.id; insert c; //create an EAB Initiating Opportunity Opportunity o = TestUtilities.CreateNewOpportunity(false); o.RecordTypeId = CPQConstants.OPP_RT_ID_EAB_INITIATING; o.StageName = '0-Exploring'; o.Marketing_Manager_Comments__c = 'Test 1 EAB Initiating'; o.Main_Contact__c = c.Id; o.CloseDate = System.today().addMonths(1); o.AccountId = acc.Id; //create an EAB Continuing Opportunity Opportunity o2 = TestUtilities.CreateNewOpportunity(false); o2.RecordTypeId = CPQConstants.OPP_RT_ID_EAB_CONTINUING; o2.Previous_Opportunity__c = o.Id; o2.StageName = '0-Exploring'; o2.Marketing_Manager_Comments__c = 'Test 2 EAB Continuing'; o2.Main_Contact__c = c.Id; o2.AccountId = acc.Id; //Start our Test Test.startTest(); Util.byPassAllTriggers = false; //Insert our Opp Records insert o; insert o2; System.debug('@RecordType ID=' + o.RecordTypeId); //Stop Our Test Test.stopTest(); //Query for our Contact List<Contact> contacts = [SELECT Id, Name, Title FROM Contact WHERE Title = 'I AM IRON MAN' LIMIT 1]; //Query for our Opportunities List<Opportunity> opps = [SELECT Id, Name, Type, Marketing_Manager_Comments__c, Contact__c FROM Opportunity ORDER BY Marketing_Manager_Comments__c]; System.assertEquals('NBB', opps[0].Type); System.assertEquals('Existing Client', opps[1].Type); } //Test #1 - Test our Opportunity Stage Field is populated according to our logic static testmethod void testRunVVSLogic_Test2() { Util.byPassAllTriggers = true; // Modified By - Rajeev Jain - 05Aug2020 - CR-20200218-13783 Account acc = TestUtilities.CreateNewAccount(true); // Test Class Fix Start Here 13Feb By: Dipesh Gupta //Creating Contact record Contact cont = TestUtilities.CreateNewContact(false); cont.AccountId = acc.id; insert cont; // Test Class Fix End Here 13Feb By: Dipesh Gupta //create an EAB Initiating Opportunity Opportunity opp = TestUtilities.CreateNewOpportunity(false); opp.RecordTypeId = CPQConstants.OPP_RT_ID_EAB_INITIATING; opp.StageName = '0-Exploring'; opp.Marketing_Manager_Comments__c = 'Test 1 EAB Initiating'; opp.Main_Contact__c = cont.Id; opp.AccountId = acc.Id; //create an EAB Continuing Opportunity Opportunity o2 = TestUtilities.CreateNewOpportunity(false); o2.RecordTypeId = CPQConstants.OPP_RT_ID_EAB_CONTINUING; o2.Previous_Opportunity__c = opp.Id; o2.StageName = '0-Exploring'; o2.Marketing_Manager_Comments__c = 'Test 2 EAB Continuing'; o2.Main_Contact__c = cont.Id; o2.AccountId = acc.Id; //Add our records to the List List<Opportunity> oppsList = new List<Opportunity>{opp, o2}; //Start our Test Test.startTest(); //Create VVS Data Opportunity_Stage__c stg = new Opportunity_Stage__c(Name = 'Dropped', Stage_Number__c = 1); insert stg; Stage_Objective__c obj1 = new Stage_Objective__c(Name = 'Objective 1', Opportunity_Stage__c = stg.Id, Order__c = 1); Stage_Objective__c obj2 = new Stage_Objective__c(Name = 'Objective 2', Opportunity_Stage__c = stg.Id, Order__c = 2); Stage_Objective__c obj3 = new Stage_Objective__c(Name = 'Objective 3', Opportunity_Stage__c = stg.Id, Order__c = 3); List<Stage_Objective__c> objList = new List<Stage_Objective__c>(); objList.add(obj1); objList.add(obj2); objList.add(obj3); insert objList; Objective_Action__c act1 = new Objective_Action__c(Name = 'Not Required Action', Order__c = 1, Stage_Objective__c = obj1.Id); Objective_Action__c act2 = new Objective_Action__c(Name = 'Required Action', Order__c = 2, Stage_Objective__c = obj2.Id, Action_Type__c = 'Required', Opportunity_Order_Type__c = 'New'); act2.Opportunity_Record_Type__c = 'Products and Services'; List<Objective_Action__c> actList = new List<Objective_Action__c>(); actList.add(act1); actList.add(act2); insert actList; Util.byPassAllTriggers = false; //Insert our Opp Records insert oppsList; //Modified by - Rajeev Jain - 01/15/2021 - Fix for L1 Weekly Release - 1/14/2021 Release SBQQ__Quote__c proposal = TestUtilities.createNewSbqqQuote(false); proposal.SBQQ__Opportunity2__c = oppsList[0].Id; insert proposal; //Assert out Opp Stage field is now null System.assertEquals(null, oppsList[0].Opportunity_Stage__c); //Update our Stage so it matches SP Opp Stage oppsList[0].StageName = 'Dropped'; update oppsList; //Stop our Test Test.stopTest(); //Query for Opp List<Opportunity> opps = [SELECT Id, Name, Type, Opportunity_Stage__c, Marketing_Manager_Comments__c FROM Opportunity ORDER BY Marketing_Manager_Comments__c]; //Query for our Stage Opportunity_Stage__c oppStage1 = [SELECT Id FROM Opportunity_Stage__c WHERE Name = 'Dropped']; //Assert they match System.assertEquals(oppStage1.Id, opps[0].Opportunity_Stage__c); } }
import { fireEvent, render, screen } from '@testing-library/react'; import Button from '..'; describe('Button component', () => { it('renders a button with the provided label', () => { const label = 'Click me'; render(<Button label={label} />); const button = screen.getByRole('button'); expect(button).toBeInTheDocument(); expect(button).toHaveTextContent(label); }); it('renders a button with the provided children', () => { const children = <span>Click me</span>; render(<Button>{children}</Button>); const button = screen.getByRole('button'); expect(button).toBeInTheDocument(); expect(button).toContainHTML('<span>Click me</span>'); }); it('calls the provided function when clicked', () => { const handleClick = jest.fn(); render(<Button onClick={handleClick} />); const button = screen.getByRole('button'); fireEvent.click(button); expect(handleClick).toHaveBeenCalledTimes(1); }); it('does not call the provided function when loading is true', () => { const handleClick = jest.fn(); render(<Button onClick={handleClick} loading={true} />); const button = screen.getByRole('button'); fireEvent.click(button); expect(handleClick).toHaveBeenCalledTimes(0); }); it('does not call the provided function when disabled is true', () => { const handleClick = jest.fn(); render(<Button onClick={handleClick} disabled={true} />); const button = screen.getByRole('button'); fireEvent.click(button); expect(handleClick).toHaveBeenCalledTimes(0); }); it('renders a button with the provided className', () => { const className = 'my-class'; render(<Button className={className} />); const button = screen.getByRole('button'); expect(button).toHaveClass(className); }); it('renders a button with the default variant class when no variant is provided', () => { const className = 'btn-default'; render(<Button className={className} />); const button = screen.getByRole('button'); expect(button).toHaveClass('btn-default'); }); it('renders a button with the provided variant class', () => { const variant = 'primary'; const className = `btn-${variant}`; render(<Button variant={variant} className={className} />); const button = screen.getByRole('button'); expect(button).toHaveClass(`btn-${variant}`); }); it('renders a button with the provided attributes', () => { const dataTestId = 'my-button'; render(<Button otherAttributes={{ 'data-testid': dataTestId }} />); const button = screen.getByTestId(dataTestId); expect(button).toBeInTheDocument(); }); });
package com.yufeng.concurrency.jcip.part1.chapter04; import com.yufeng.concurrency.jcip.annotations.ThreadSafe; import com.yufeng.concurrency.jcip.part3.Point; import java.util.Collections; import java.util.HashMap; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentMap; /** * @description * 将线程安全委托给ConcurrentHashMap * @author yufeng * @create 2020-04-28 */ @ThreadSafe public class DelegatingVehicleTracker { private final ConcurrentMap<String, Point> locations; private final Map<String, Point> unmodifiableMap; public DelegatingVehicleTracker(Map<String, Point> points) { locations = new ConcurrentHashMap<>(points); unmodifiableMap = Collections.unmodifiableMap(locations); } public Map<String, Point> getLocations() { return unmodifiableMap; } public Point getLocation(String id) { return locations.get(id); } public void setLocation(String id, int x, int y) { if (locations.replace(id, new Point(x, y)) == null) { throw new IllegalArgumentException("invalid vehicle name: " + id); } } // Alternate version of getLocations (Listing 4.8) public Map<String, Point> getLocationsAsStatic() { return Collections.unmodifiableMap (new HashMap<>(locations)); } }
import vscode, { MarkdownString, ProgressLocation, ThemeIcon, TreeItem, TreeItemCollapsibleState, Uri, commands, env, window, workspace } from "vscode"; import { TreeDataProvider } from "vscode"; import { Config, JobManager } from "../../config"; import { JobInfo, SQLJobManager } from "../../connection/manager"; import { editJobUi } from "./editJob"; import { displayJobLog } from "./jobLog"; import { ServerTraceDest, ServerTraceLevel } from "../../connection/types"; import { ServerComponent } from "../../connection/serverComponent"; import { updateStatusBar } from "./statusBar"; import { SQLJob, TransactionEndType } from "../../connection/sqlJob"; import { ConfigGroup, ConfigManager } from "./ConfigManager"; const selectJobCommand = `vscode-db2i.jobManager.selectJob`; const activeColor = new vscode.ThemeColor(`minimapGutter.addedBackground`); export class JobManagerView implements TreeDataProvider<any> { private _onDidChangeTreeData: vscode.EventEmitter<vscode.TreeItem | undefined | null | void> = new vscode.EventEmitter<vscode.TreeItem | undefined | null | void>(); readonly onDidChangeTreeData: vscode.Event<vscode.TreeItem | undefined | null | void> = this._onDidChangeTreeData.event; constructor(context: vscode.ExtensionContext) { context.subscriptions.push( vscode.commands.registerCommand(`vscode-db2i.jobManager.refresh`, async () => { this.refresh(); }), ...ConfigManager.initialiseSaveCommands(), vscode.commands.registerCommand(`vscode-db2i.jobManager.newJob`, async (predefinedJob?: SQLJob, name?: string) => { await window.withProgress({ location: ProgressLocation.Window }, async (progress) => { try { progress.report({ message: `Spinning up SQL job...` }); await JobManager.newJob(predefinedJob, name); } catch (e) { window.showErrorMessage(e.message); } this.refresh(); }); }), vscode.commands.registerCommand(`vscode-db2i.jobManager.closeJob`, async (node?: SQLJobItem) => { if (node) { const id = node.label as string; let selected = JobManager.getJob(id); if (selected) { if (selected.job.underCommitControl()) { const uncommitted = await selected.job.getPendingTransactions(); if (uncommitted > 0) { const decision = await vscode.window.showWarningMessage( `Cannot end job yet`, { modal: true, detail: `You have ${uncommitted} uncommitted change${uncommitted !== 1 ? `s` : ``}.` }, `Commit and end`, `Rollback and end` ); switch (decision) { case `Commit and end`: await selected.job.endTransaction(TransactionEndType.COMMIT); break; case `Rollback and end`: await selected.job.endTransaction(TransactionEndType.ROLLBACK); break; default: // Actually... don't end the job return; } } } await JobManager.closeJobByName(id); this.refresh(); } } }), vscode.commands.registerCommand(`vscode-db2i.jobManager.viewJobLog`, async (node?: SQLJobItem) => { const id = node ? node.label as string : undefined; let selected = id ? JobManager.getJob(id) : JobManager.getSelection(); if (selected) { displayJobLog(selected); } }), vscode.commands.registerCommand(`vscode-db2i.jobManager.copyJobId`, async (node?: SQLJobItem) => { if (node) { const id = node.label as string; const selected = await JobManager.getJob(id); if (selected) { await env.clipboard.writeText(selected.job.id); window.showInformationMessage(`Copied ${selected.job.id} to clipboard.`); } } }), vscode.commands.registerCommand(`vscode-db2i.jobManager.editJobProps`, async (node?: SQLJobItem) => { const id = node ? node.label as string : undefined; let selected = id ? JobManager.getJob(id) : JobManager.getSelection(); if (selected) { editJobUi(selected.job.options, selected.name).then(newOptions => { if (newOptions) { window.withProgress({ location: ProgressLocation.Window }, async (progress) => { progress.report({ message: `Ending current job` }); await selected.job.close(); progress.report({ message: `Starting new job` }); selected.job.options = newOptions; try { await selected.job.connect(); } catch (e) { window.showErrorMessage(`Failed to start new job with updated properties.`); } this.refresh(); }) } }) } }), vscode.commands.registerCommand(`vscode-db2i.jobManager.enableTracing`, async (node?: SQLJobItem) => { if (node) { const id = node.label as string; const selected = await JobManager.getJob(id); ServerComponent.writeOutput(`Enabling tracing for ${selected.name} (${selected.job.id})`, true); selected.job.setTraceConfig(ServerTraceDest.IN_MEM, ServerTraceLevel.DATASTREAM); } }), vscode.commands.registerCommand(`vscode-db2i.jobManager.getTrace`, async (node?: SQLJobItem) => { if (node) { const id = node.label as string; const selected = await JobManager.getJob(id); const possibleFile = selected.job.getTraceFilePath(); if (possibleFile) { // Trace was written to a file vscode.workspace.openTextDocument(Uri.from({ scheme: `streamfile`, path: possibleFile })).then(doc => { vscode.window.showTextDocument(doc); }); } else { // This likely means IN_MEM was used const trace = await selected.job.getTraceData(); if (trace.success) { vscode.workspace.openTextDocument({ content: trace.tracedata.trim() }).then(doc => { vscode.window.showTextDocument(doc); }) } else { ServerComponent.writeOutput(`Unable to get trace data for ${selected.name} (${selected.job.id}):`, true); ServerComponent.writeOutput(trace.error); } } } }), vscode.commands.registerCommand(`vscode-db2i.jobManager.jobCommit`, async (node?: SQLJobItem) => { const id = node ? node.label as string : undefined; let selected = id ? JobManager.getJob(id) : JobManager.getSelection(); if (selected) { if (selected.job.underCommitControl()) { const result = await selected.job.endTransaction(TransactionEndType.COMMIT); if (!result.success) { vscode.window.showErrorMessage(`Failed to commit.` + result.error); } this.refresh(); } } }), vscode.commands.registerCommand(`vscode-db2i.jobManager.jobRollback`, async (node?: SQLJobItem) => { const id = node ? node.label as string : undefined; let selected = id ? JobManager.getJob(id) : JobManager.getSelection(); if (selected) { if (selected.job.underCommitControl()) { try { const result = await selected.job.endTransaction(TransactionEndType.ROLLBACK); if (!result.success) { vscode.window.showErrorMessage(`Failed to rollback. ` + result.error); } } catch (e) { vscode.window.showErrorMessage(`Failed to rollback. ` + e.message); } this.refresh(); } } }), vscode.commands.registerCommand(selectJobCommand, async (selectedName: string) => { if (selectedName) { await JobManager.setSelection(selectedName); this.refresh(); } }), vscode.commands.registerCommand(`vscode-db2i.jobManager.endAll`, async (node?: SQLJobItem) => { await JobManager.endAll(); this.refresh(); }), ) } static setVisible(visible: boolean) { commands.executeCommand(`setContext`, `vscode-db2i:jobManager`, visible).then(() => { if (visible) { commands.executeCommand(`vscode-db2i.jobManager.refresh`); } }); } refresh() { this._onDidChangeTreeData.fire(); updateStatusBar(); } getTreeItem(element: vscode.TreeItem) { return element; } async getChildren(element: ConfigGroup): Promise<SQLJobItem[]> { if (element) { return ConfigManager.getConfigTreeItems(); } else { let nodes = JobManager .getRunningJobs() .map((info, index) => new SQLJobItem(info, index === JobManager.selectedJob)); if (ConfigManager.hasSavedItems()) { nodes.push(new ConfigGroup()); } return nodes; } } } export class SQLJobItem extends vscode.TreeItem { constructor(jobInfo: JobInfo, active: boolean = false) { super(jobInfo.name, TreeItemCollapsibleState.None); this.contextValue = `sqlJob`; this.description = jobInfo.job.id; this.command = { command: selectJobCommand, arguments: [jobInfo.name], title: `Switch job` }; this.iconPath = new vscode.ThemeIcon(active ? `layers-active` : `layers`, (active ? activeColor : undefined)); } }
--- toc: True comments: True layout: post title: AI Box description: Chat box courses: {'compsci': {'week': 0}} type: hacks --- <style> body { background-color: lavender; } </style> <html> <head> <title>Formatted Math Chatbox</title> <style> /* Container Styles */ .container { width: 400px; margin: 0 auto; padding: 20px; border: 1px solid #ccc; border-radius: 10px; background-color: #f8f8f8; } /* Chatbox Styles */ .chatbox { width: 100%; } .chat { list-style: none; padding: 0; } .chat li { margin-bottom: 10px; padding: 5px; } .user-message { background: #3498db; color: #fff; border-radius: 5px; } .bot-message { background: #e5e5e5; border-radius: 5px; } /* Input Styles */ .input-box { display: flex; margin-top: 10px; } .input-box input { flex: 1; padding: 5px; } .input-box button { background: #3498db; color: #fff; border: none; padding: 5px 10px; } </style> </head> <body> <div class="container"> <h1>AI Chatbox</h1> <div class="chatbox"> <ul class="chat" id="chat"> <li class="bot-message">Hello! How can I help you?</li> </ul> <div class="input-box"> <input type="text" id="userInput" placeholder="Type your message..."> <button onclick="sendMessage()">Send</button> </div> </div> </div> <script> function sendMessage() { var userInput = document.getElementById("userInput").value; if (userInput !== "") { var chat = document.getElementById("chat"); var userMessage = document.createElement("li"); userMessage.className = "user-message"; userMessage.appendChild(document.createTextNode(userInput)); chat.appendChild(userMessage); // Check if the user's message is a math question and evaluate it if (isMathQuestion(userInput)) { try { var result = eval(userInput); var botMessage = document.createElement("li"); botMessage.className = "bot-message"; botMessage.appendChild(document.createTextNode("The answer is: " + result)); chat.appendChild(botMessage); } catch (error) { var botMessage = document.createElement("li"); botMessage.className = "bot-message"; botMessage.appendChild(document.createTextNode("I couldn't understand the math question.")); chat.appendChild(botMessage); } } else { // Simulate a generic response for non-math questions setTimeout(function () { var botMessage = document.createElement("li"); botMessage.className = "bot-message"; botMessage.appendChild(document.createTextNode("I received: " + userInput)); chat.appendChild(botMessage); }, 1000); } document.getElementById("userInput").value = ""; } } function isMathQuestion(input) { return /[+\-*/0-9]/.test(input); } </script> </body> </html>
#### # Base #### extend type Mutation { "Create a flat rate fulfillment method" createFlatRateFulfillmentMethod( "Mutation input" input: CreateFlatRateFulfillmentMethodInput! ): CreateFlatRateFulfillmentMethodPayload! "Update a flat rate fulfillment method" updateFlatRateFulfillmentMethod( "Mutation input" input: UpdateFlatRateFulfillmentMethodInput! ): UpdateFlatRateFulfillmentMethodPayload! "Delete a flat rate fulfillment method" deleteFlatRateFulfillmentMethod( "Mutation input" input: DeleteFlatRateFulfillmentMethodInput! ): DeleteFlatRateFulfillmentMethodPayload! } "Defines a fulfillment method that has a fixed price. This type is provided by the `flat-rate` fulfillment plugin." type FlatRateFulfillmentMethod implements Node { "The flat rate fulfillment method ID" _id: ID! "The cost of this fulfillment method to the shop, if you track this" cost: Float """ The fulfillment types for which this method may be used. For example, "shipping" or "digital". """ fulfillmentTypes: [FulfillmentType]! "The group to which this method belongs" group: String! "A fixed price to charge for handling costs when this fulfillment method is selected for an order" handling: Float! "Include this as a fulfillment option shown to shoppers during checkout?" isEnabled: Boolean! "The name of this method, for display in the user interface" label: String! "The name of this method, a unique identifier" name: String! "A fixed price to charge for fulfillment costs when this fulfillment method is selected for an order" rate: Float! } #### # Inputs #### "Defines a fulfillment method that has a fixed price. This type is provided by the `flat-rate` fulfillment plugin." input FlatRateFulfillmentMethodInput { "The cost of this fulfillment method to the shop, if you track this" cost: Float """ The fulfillment types for which this method may be used. For example, "shipping" or "digital". """ fulfillmentTypes: [FulfillmentType]! "The group to which this method belongs" group: String! "A fixed price to charge for handling costs when this fulfillment method is selected for an order" handling: Float! "Include this as a fulfillment option shown to shoppers during checkout?" isEnabled: Boolean! "The name of this method, for display in the user interface" label: String! "The name of this method, a unique identifier" name: String! "A fixed price to charge for fulfillment costs when this fulfillment method is selected for an order" rate: Float! } "Input for the `createFlatRateFulfillmentMethod` mutation" input CreateFlatRateFulfillmentMethodInput { "An optional string identifying the mutation call, which will be returned in the response payload" clientMutationId: String "This defines the flat rate fulfillment method that you want to create" method: FlatRateFulfillmentMethodInput! "The shop to create this flat rate fulfillment method for" shopId: ID! } "Input for the `updateFlatRateFulfillmentMethod` mutation" input UpdateFlatRateFulfillmentMethodInput { "An optional string identifying the mutation call, which will be returned in the response payload" clientMutationId: String "The updated method. Pass the whole updated method object without the ID." method: FlatRateFulfillmentMethodInput! "The ID of the flat rate fulfillment method you want to update" methodId: ID! "The shop that owns the method" shopId: ID! } "Input for the `deleteFlatRateFulfillmentMethod` mutation" input DeleteFlatRateFulfillmentMethodInput { "An optional string identifying the mutation call, which will be returned in the response payload" clientMutationId: String "The ID of the flat rate fulfillment method you want to delete" methodId: ID! "The shop that owns the method" shopId: ID! } #### # Payloads #### "Response from the `createFlatRateFulfillmentMethod` mutation" type CreateFlatRateFulfillmentMethodPayload { "The same string you sent with the mutation params, for matching mutation calls with their responses" clientMutationId: String "The created fulfillment method" method: FlatRateFulfillmentMethod! } "Response from the `updateFlatRateFulfillmentMethod` mutation" type UpdateFlatRateFulfillmentMethodPayload { "The same string you sent with the mutation params, for matching mutation calls with their responses" clientMutationId: String "The updated fulfillment method" method: FlatRateFulfillmentMethod! } "Response from the `deleteFlatRateFulfillmentMethod` mutation" type DeleteFlatRateFulfillmentMethodPayload { "The same string you sent with the mutation params, for matching mutation calls with their responses" clientMutationId: String "The removed fulfillment method" method: FlatRateFulfillmentMethod! }
<?php namespace Laminas\Db\Sql\Predicate; use Laminas\Db\Sql\AbstractExpression; use Laminas\Db\Sql\Exception; use Laminas\Db\Sql\Select; use function array_fill; use function count; use function gettype; use function implode; use function is_array; use function vsprintf; class In extends AbstractExpression implements PredicateInterface { /** @var null|string|array */ protected $identifier; /** @var null|array|Select */ protected $valueSet; /** @var string */ protected $specification = '%s IN %s'; /** @var string */ protected $valueSpecSpecification = '%%s IN (%s)'; /** * Constructor * * @param null|string|array $identifier * @param null|array|Select $valueSet */ public function __construct($identifier = null, $valueSet = null) { if ($identifier) { $this->setIdentifier($identifier); } if ($valueSet !== null) { $this->setValueSet($valueSet); } } /** * Set identifier for comparison * * @param string|array $identifier * @return $this Provides a fluent interface */ public function setIdentifier($identifier) { $this->identifier = $identifier; return $this; } /** * Get identifier of comparison * * @return null|string|array */ public function getIdentifier() { return $this->identifier; } /** * Set set of values for IN comparison * * @param array|Select $valueSet * @return $this Provides a fluent interface * @throws Exception\InvalidArgumentException */ public function setValueSet($valueSet) { if (! is_array($valueSet) && ! $valueSet instanceof Select) { throw new Exception\InvalidArgumentException( '$valueSet must be either an array or a Laminas\Db\Sql\Select object, ' . gettype($valueSet) . ' given' ); } $this->valueSet = $valueSet; return $this; } /** * Gets set of values in IN comparison * * @return array|Select */ public function getValueSet() { return $this->valueSet; } /** * Return array of parts for where statement * * @return array */ public function getExpressionData() { $identifier = $this->getIdentifier(); $values = $this->getValueSet(); $replacements = []; if (is_array($identifier)) { $countIdentifier = count($identifier); $identifierSpecFragment = '(' . implode(', ', array_fill(0, $countIdentifier, '%s')) . ')'; $types = array_fill(0, $countIdentifier, self::TYPE_IDENTIFIER); $replacements = $identifier; } else { $identifierSpecFragment = '%s'; $replacements[] = $identifier; $types = [self::TYPE_IDENTIFIER]; } if ($values instanceof Select) { $specification = vsprintf( $this->specification, [$identifierSpecFragment, '%s'] ); $replacements[] = $values; $types[] = self::TYPE_VALUE; } else { foreach ($values as $argument) { [$replacements[], $types[]] = $this->normalizeArgument($argument, self::TYPE_VALUE); } $countValues = count($values); $valuePlaceholders = $countValues > 0 ? array_fill(0, $countValues, '%s') : []; $inValueList = implode(', ', $valuePlaceholders); if ('' === $inValueList) { $inValueList = 'NULL'; } $specification = vsprintf( $this->specification, [$identifierSpecFragment, '(' . $inValueList . ')'] ); } return [ [ $specification, $replacements, $types, ], ]; } }
import { Prop, Schema, SchemaFactory } from '@nestjs/mongoose'; import { Document } from 'mongoose'; export type JobsDocument = Jobs & Document; @Schema({ collection: 'jobs', timestamps: true, versionKey: false }) export class Jobs { @Prop({ required: true }) name: string; @Prop({ required: true, unique: true, index: true }) email: string; @Prop({ required: true }) address: string; @Prop({ required: true }) gender: string; @Prop({ required: true }) contactNumber: string; @Prop() sscMarks: number; @Prop() sscBoard: string; @Prop() hscMarks: number; @Prop() hscBoard: string; @Prop() graduationCGPA: number; @Prop() graduationUniversity: string; @Prop() masterDegreeCGPA: number; @Prop() masterDegreeUniversity: string; // @Prop() // workExperience: boolean; @Prop() workExperienceDetails: [ { company: string; designation: string; from: string; to: string; }, ]; @Prop() knownLanguage: Array<any>; @Prop() technialExperiance: string; @Prop() technicalDetails: Array<any>; @Prop({ required: true }) preferredLocation: string; @Prop({ required: true }) expectedCTC: number; @Prop() currentCTC: number; @Prop() noticePeriod: number; } export const JobsSchema = SchemaFactory.createForClass(Jobs);
import { wordWrap } from '../../util/strings/wordWrap'; import { TAB, isSimpleType, normalizeKey } from './util'; const formatComment = (comment, __) => { if (!comment) return ''; const lines = wordWrap(comment, { width: 80 - 3 - __.length }); return __ + '/**\n' + __ + ' * ' + lines.join('\n' + __ + ' * ') + '\n' + __ + ' */\n'; }; export const toText = (node, __ = '') => { if (Array.isArray(node)) return node.map((s) => toText(s, __)).join('\n'); const ____ = __ + TAB; switch (node.node) { case 'ModuleDeclaration': { let out = ''; out += `${__}${node.export ? 'export ' : ''}namespace ${node.name} {\n`; out += toText(node.statements, ____); out += `${__}}\n`; return out; } case 'InterfaceDeclaration': { const { name, members, comment } = node; let out = ''; out += formatComment(comment, __); out += `${__}${node.export ? 'export ' : ''}interface ${name} {\n`; out += toText(members, ____); out += `\n${__}}\n`; return out; } case 'TypeAliasDeclaration': { let out = ''; out += formatComment(node.comment, __); out += `${__}${node.export ? 'export ' : ''}type ${node.name} = ${toText(node.type, __)};\n`; return out; } case 'PropertySignature': { const name = normalizeKey(node.name); let out = ''; out += formatComment(node.comment, __); return out + `${__}${name}${node.optional ? '?' : ''}: ${toText(node.type, __)};`; } case 'IndexSignature': { return `${__}[key: string]: ${toText(node.type, __)};`; } case 'ArrayType': { const simple = isSimpleType(node.elementType); const inner = toText(node.elementType, __); return simple ? `${inner}[]` : `Array<${inner}>`; } case 'TupleType': { const hasObject = node.elements.some((e) => e.node === 'TypeLiteral'); if (hasObject) { return `[\n${____}${node.elements.map((e) => toText(e, ____)).join(',\n' + ____)}\n${__}]`; } else return `[${node.elements.map((e) => toText(e, __)).join(', ')}]`; } case 'GenericTypeAnnotation': { return node.id.name; } case 'StringKeyword': { return 'string'; } case 'NumberKeyword': { return 'number'; } case 'BooleanKeyword': { return 'boolean'; } case 'NullKeyword': { return 'null'; } case 'AnyKeyword': { return 'any'; } case 'UnknownKeyword': { return 'unknown'; } case 'TypeLiteral': { return !node.members.length ? '{}' : `{\n${toText(node.members, ____)}\n${__}}`; } case 'StringLiteral': { return JSON.stringify(node.text); } case 'NumericLiteral': { return node.text; } case 'TrueKeyword': { return 'true'; } case 'FalseKeyword': { return 'false'; } case 'UnionType': { return node.types.map((t) => toText(t, ____)).join(' | '); } case 'TypeReference': { return ((typeof node.typeName === 'string' ? node.typeName : toText(node.typeName, __)) + (node.typeArguments && node.typeArguments.length > 0 ? `<${node.typeArguments.map((t) => toText(t, __)).join(', ')}>` : '')); } case 'Identifier': { return node.name; } case 'FunctionType': { const { parameters, type } = node; const params = parameters.map((p) => toText(p, __)).join(', '); return `(${params}) => ${toText(type, __)}`; } case 'ObjectKeyword': { return 'object'; } case 'Parameter': { const { name, type } = node; return `${toText(name, __)}: ${toText(type, __)}`; } } return ''; };
/* eslint-disable react/prop-types */ import styled from "styled-components"; const StyledSelect = styled.select` font-size: 1.4rem; padding: 0.8rem 1.2rem; border: 1px solid ${(props) => props.type === "white" ? "var(--color-grey-100)" : "var(--color-grey-300)"}; border-radius: var(--border-radius-sm); background-color: var(--color-grey-0); font-weight: 500; box-shadow: var(--shadow-sm); `; // The ...props syntax with the rest and spread operators to handle additional/unknown props in reusable components. This allows components to receive any extra props passed to them, in addition to the explicitly defined props. // The ...props collects any remaining props into an object, which can then be spread (...props) onto child components/elements to pass those props down. function Select({ options, value, onChange, ...props }) { return ( <StyledSelect value={value} onChange={onChange} {...props}> {options.map((option) => ( <option value={option.value} key={option.value}> {option.label} </option> ))} </StyledSelect> ); } export default Select;
import React from 'react' import { IntlProvider } from 'react-intl' import { Route, Routes } from 'react-router-dom' import { useLocale } from '@app/hooks' import css from './App.css' import { Home } from './routes' const App = () => { const { locale, messages } = useLocale() return ( <IntlProvider locale={locale} messages={messages}> <div className={css.container}> <Routes> <Route path="/" element={<Home />} /> </Routes> </div> </IntlProvider> ) } export default App
<?php namespace Database\Factories; use Illuminate\Database\Eloquent\Factories\Factory; use Illuminate\Support\Facades\Hash; /** * @extends \Illuminate\Database\Eloquent\Factories\Factory<\App\Models\Model> */ class StudentFactory extends Factory { /** * Define the model's default state. * * @return array<string, mixed> */ protected $model = User::class; public function definition(): array { return [ 'name' => fake()->name(), 'email' => fake()->safeEmail(), 'classroom_id' => 2, 'role_id' => 1, 'password' => Hash::make('test'), 'status' => true ]; } }