text
stringlengths
184
4.48M
import { Request, Response } from 'express'; import { AppDataSource } from '../data-source'; import { RoomsEntity } from '../entities/rooms'; import { catchError } from './../utils/rout-catch-error'; class RoomsController { public async Get(req: Request, res: Response): Promise<void> { res.json( await AppDataSource.getRepository(RoomsEntity).find({ relations: ['orders', 'orders.users', 'filial'], order: { id: 'ASC' }, }) ); } public async GetEmpty(req: Request, res: Response): Promise<void> { await catchError(res, async () => { const data = await AppDataSource.getRepository(RoomsEntity).find({ relations: ['orders', 'orders.users', 'filial'], where: { status: 'empty' }, order: { id: 'ASC' }, }); return { status: 200, message: 'ok', data, }; }); } public async GetId(req: Request, res: Response): Promise<void> { await catchError(res, async () => { const { id } = req.params; const data = await AppDataSource.getRepository(RoomsEntity).find({ relations: ['orders', 'orders.users', 'filial'], where: { id: +id }, }); return { status: 200, message: 'ok', data, }; }); } public async Post(req: Request, res: Response) { const { rooms, count, type, definition, status, filial } = req.body; const room = await AppDataSource.getRepository(RoomsEntity) .createQueryBuilder() .insert() .into(RoomsEntity) .values({ rooms, count, type, definition, status, filial }) .returning('*') .execute(); res.json({ status: 201, message: 'rooms created', data: room.raw[0], }); } public async Put(req: Request, res: Response) { await catchError(res, async () => { const { rooms, type, count, status, filial } = req.body; const { id } = req.params; const room = await AppDataSource.getRepository(RoomsEntity) .createQueryBuilder() .update(RoomsEntity) .set({ rooms, type, count, status, filial }) .where({ id }) .returning('*') .execute(); return { status: 200, message: 'Rooms updated', data: room.raw[0], }; }); } public async Delete(req: Request, res: Response) { try { const { id } = req.params; const room = await AppDataSource.getRepository(RoomsEntity) .createQueryBuilder() .delete() .from(RoomsEntity) .where({ id }) .returning('*') .execute(); res.json({ status: 200, message: 'rooms deleted', data: room.raw[0], }); } catch (error) { console.log(error); } } } export default new RoomsController();
import 'package:admin/helper/my_logger_helper.dart'; import 'package:admin/instances/firebase_instances.dart'; import 'package:admin/models/user_admin_office_model.dart'; import 'package:admin/models/user_cashier_model.dart'; import 'package:admin/models/user_library_model.dart'; import 'package:admin/models/user_registrar_model.dart'; import 'package:admin/models/user_security_office_model.dart'; import 'package:cloud_firestore/cloud_firestore.dart'; class UserRepository { static const queryLimit = 15; static const String _userData = 'user'; static const String _dateCreated = 'created_at'; static const String _version = 'version'; static const String _answered = 'answered'; static Future<List<UserSecurityOfficeModel>> getUsersSecurityOffice( {DocumentSnapshot? lastDocumentSnapshot, String? office, required int version}) async { MyLogger.printInfo('COLLECTION NAME: $office, VERSION: $version'); try { Query query = firestore .collection(office!) .where(_version, isEqualTo: version) .orderBy(_dateCreated, descending: true) .limit(queryLimit); if (lastDocumentSnapshot != null) { query = query.startAfterDocument(lastDocumentSnapshot); } else { query = query; } final result = await query.get(); return result.docs.map(UserSecurityOfficeModel.fromDocument).toList(); } catch (_) { rethrow; } } static Future<List<UserRegistrarModel>> getUsersRegistrar( {DocumentSnapshot? lastDocumentSnapshot, String? office, required int version}) async { MyLogger.printInfo('COLLECTION NAME: $office, VERSION: $version'); try { Query query = firestore .collection(office!) .where(_version, isEqualTo: version) .orderBy(_dateCreated, descending: true) .limit(queryLimit); if (lastDocumentSnapshot != null) { query = query.startAfterDocument(lastDocumentSnapshot); } else { query = query; } final result = await query.get(); return result.docs.map(UserRegistrarModel.fromDocument).toList(); } catch (_) { rethrow; } } static Future<List<UserCashierModel>> getUsersCashier( {DocumentSnapshot? lastDocumentSnapshot, String? office, required int version}) async { MyLogger.printInfo('COLLECTION NAME: $office, VERSION: $version'); try { Query query = firestore .collection(office!) .where(_version, isEqualTo: version) .orderBy(_dateCreated, descending: true) .limit(queryLimit); if (lastDocumentSnapshot != null) { query = query.startAfterDocument(lastDocumentSnapshot); } else { query = query; } final result = await query.get(); return result.docs.map(UserCashierModel.fromDocument).toList(); } catch (_) { rethrow; } } static Future<DocumentSnapshot<Map<String, dynamic>>> getUsersDocumentSnapshot( String office, String userId, ) async { print('userId $userId'); print('office $office'); try { final docRef = firestore.collection(office).doc(userId); final itemData = await docRef.get(); return itemData; } catch (_) { rethrow; } } static Future<List<UserAdminOfficeModel>> getUsersAdminOffice( {DocumentSnapshot? lastDocumentSnapshot, String? office, required int version}) async { MyLogger.printInfo('COLLECTION NAME: $office, VERSION: $version'); try { Query query = firestore .collection(office!) .where(_version, isEqualTo: version) .orderBy(_dateCreated, descending: true) .limit(queryLimit); if (lastDocumentSnapshot != null) { query = query.startAfterDocument(lastDocumentSnapshot); } else { query = query; } final result = await query.get(); return result.docs.map(UserAdminOfficeModel.fromDocument).toList(); } catch (_) { rethrow; } } static Future<List<UserLibraryModel>> getUsersLibrary( {DocumentSnapshot? lastDocumentSnapshot, String? office, required int version}) async { MyLogger.printInfo('COLLECTION NAME: $office, VERSION: $version'); try { Query query = firestore .collection(office!) .where(_version, isEqualTo: version) .orderBy(_dateCreated, descending: true) .limit(queryLimit); if (lastDocumentSnapshot != null) { query = query.startAfterDocument(lastDocumentSnapshot); } else { query = query; } final result = await query.get(); return result.docs.map(UserLibraryModel.fromDocument).toList(); } catch (_) { rethrow; } } static Future<List<UserLibraryModel>> getUsersLibraryAnswered( {String? office, required int version}) async { MyLogger.printInfo('COLLECTION NAME: $office, VERSION: $version'); try { Query query = firestore .collection(office!) .where(_version, isEqualTo: version) .where(_answered, isEqualTo: true) .orderBy(_dateCreated, descending: true); final result = await query.get(); return result.docs.map(UserLibraryModel.fromDocument).toList(); } catch (_) { rethrow; } } static Future<List<UserLibraryModel>> getUsersLibraryAnsweredFilter({ String? office, required int version, required DateTime start, required DateTime end, }) async { MyLogger.printInfo('COLLECTION NAME: $office, VERSION: $version'); try { var dateStart = Timestamp.fromDate(start); var dateEnd = Timestamp.fromDate(end); Query query = firestore .collection(office!) .where(_version, isEqualTo: version) .where(_answered, isEqualTo: true) .where('created_at', isGreaterThanOrEqualTo: dateStart) .where('created_at', isLessThanOrEqualTo: dateEnd) .orderBy(_dateCreated, descending: true); final result = await query.get(); return result.docs.map(UserLibraryModel.fromDocument).toList(); } catch (_) { rethrow; } } static Future<List<UserAdminOfficeModel>> getUsersAdminOfficeAnswered( {String? office, required int version}) async { MyLogger.printInfo('COLLECTION NAME: $office, VERSION: $version'); try { Query query = firestore .collection(office!) .where(_version, isEqualTo: version) .where(_answered, isEqualTo: true) .orderBy(_dateCreated, descending: true); final result = await query.get(); return result.docs.map(UserAdminOfficeModel.fromDocument).toList(); } catch (_) { rethrow; } } static Future<List<UserAdminOfficeModel>> getUsersAdminOfficeAnsweredFilter({ String? office, required int version, required DateTime start, required DateTime end, }) async { var dateStart = Timestamp.fromDate(start); var dateEnd = Timestamp.fromDate(end); MyLogger.printInfo('COLLECTION NAME: $office, VERSION: $version'); try { Query query = firestore .collection(office!) .where(_version, isEqualTo: version) .where(_answered, isEqualTo: true) .where('created_at', isGreaterThanOrEqualTo: dateStart) .where('created_at', isLessThanOrEqualTo: dateEnd) .orderBy(_dateCreated, descending: true); final result = await query.get(); return result.docs.map(UserAdminOfficeModel.fromDocument).toList(); } catch (_) { rethrow; } } static Future<List<UserCashierModel>> getUsersCashierOfficeAnswered( {String? office, required int version}) async { MyLogger.printInfo('COLLECTION NAME: $office, VERSION: $version'); try { Query query = firestore .collection(office!) .where(_version, isEqualTo: version) .where(_answered, isEqualTo: true) .orderBy(_dateCreated, descending: true); final result = await query.get(); return result.docs.map(UserCashierModel.fromDocument).toList(); } catch (_) { rethrow; } } static Future<List<UserCashierModel>> getUsersCashierOfficeAnsweredFilter({ String? office, required int version, required DateTime start, required DateTime end, }) async { MyLogger.printInfo('COLLECTION NAME: $office, VERSION: $version'); try { var dateStart = Timestamp.fromDate(start); var dateEnd = Timestamp.fromDate(end); Query query = firestore .collection(office!) .where(_version, isEqualTo: version) .where(_answered, isEqualTo: true) .where('created_at', isGreaterThanOrEqualTo: dateStart) .where('created_at', isLessThanOrEqualTo: dateEnd) .orderBy(_dateCreated, descending: true); final result = await query.get(); return result.docs.map(UserCashierModel.fromDocument).toList(); } catch (_) { rethrow; } } static Future<List<UserRegistrarModel>> getUsersRegistrarOfficeAnswered( {String? office, required int version}) async { MyLogger.printInfo('COLLECTION NAME: $office, VERSION: $version'); try { Query query = firestore .collection(office!) .where(_version, isEqualTo: version) .where(_answered, isEqualTo: true) .orderBy(_dateCreated, descending: true); final result = await query.get(); return result.docs.map(UserRegistrarModel.fromDocument).toList(); } catch (_) { rethrow; } } static Future<List<UserRegistrarModel>> getUsersRegistrarOfficeAnsweredFilter({ String? office, required int version, required DateTime start, required DateTime end, }) async { MyLogger.printInfo('COLLECTION NAME: $office, VERSION: $version'); try { var dateStart = Timestamp.fromDate(start); var dateEnd = Timestamp.fromDate(end); Query query = firestore .collection(office!) .where(_version, isEqualTo: version) .where(_answered, isEqualTo: true) .where('created_at', isGreaterThanOrEqualTo: dateStart) .where('created_at', isLessThanOrEqualTo: dateEnd) .orderBy(_dateCreated, descending: true); final result = await query.get(); return result.docs.map(UserRegistrarModel.fromDocument).toList(); } catch (_) { rethrow; } } static Future<List<UserSecurityOfficeModel>> getUsersSecurityOfficeAnswered( {String? office, required int version}) async { MyLogger.printInfo('COLLECTION NAME: $office, VERSION: $version'); try { Query query = firestore .collection(office!) .where(_version, isEqualTo: version) .where(_answered, isEqualTo: true) .orderBy(_dateCreated, descending: true); final result = await query.get(); return result.docs.map(UserSecurityOfficeModel.fromDocument).toList(); } catch (_) { rethrow; } } static Future<List<UserSecurityOfficeModel>> getUsersSecurityOfficeAnsweredFilter({ String? office, required int version, required DateTime start, required DateTime end, }) async { MyLogger.printInfo('COLLECTION NAME: $office, VERSION: $version'); try { var dateStart = Timestamp.fromDate(start); var dateEnd = Timestamp.fromDate(end); Query query = firestore .collection(office!) .where(_version, isEqualTo: version) .where(_answered, isEqualTo: true) .where('created_at', isGreaterThanOrEqualTo: dateStart) .where('created_at', isLessThanOrEqualTo: dateEnd) .orderBy(_dateCreated, descending: true); final result = await query.get(); return result.docs.map(UserSecurityOfficeModel.fromDocument).toList(); } catch (_) { rethrow; } } static Future<DocumentSnapshot<Map<String, dynamic>>> getUserDocumentSnapshot( String userId, ) async { try { final docRef = firestore.collection(_userData).doc(userId); final itemData = await docRef.get(); return itemData; } catch (_) { rethrow; } } static Future<void> updateUserViaVersion( String officeName, int version) async { MyLogger.printInfo('Office : $officeName, version : $version'); var collection = firestore.collection(officeName); try { QuerySnapshot querySnapshot = await collection.where(_version, isEqualTo: version).get(); for (QueryDocumentSnapshot documentSnapshot in querySnapshot.docs) { await collection.doc(documentSnapshot.id).delete(); } } catch (e) { MyLogger.printError("updateUserViaVersion ERROR: $e"); return; } } }
import React from 'react'; import GoogleMapReact from 'google-map-react'; import { Typography, Paper, useMediaQuery } from '@material-ui/core'; import LocationOnOutlinedIcon from '@material-ui/icons/LocationOnOutlined'; import Rating from '@material-ui/lab/Rating'; import useStyles from './styles'; import mapStyles from './mapStyles'; export default function Map({ setCoordinates, setBounds,coordinates, places, setChildClicked }) { const classes = useStyles(); const isDesktop = useMediaQuery('(min-width:600px)'); return ( <div className={classes.mapContainer}> <GoogleMapReact bootstrapURLKeys={{key: process.env.REACT_APP_GOOGLE_MAPS_API_KEY}} defaultCenter={coordinates} center={coordinates} defaultZoom={14} margin={[50,50,50,50]} options={{disableDefaultUI:true, zoomControl:true, styles:mapStyles}} onChange={(e) => { setCoordinates({lat: e.center.lat, lng: e.center.lng}); setBounds({ne: e.marginBounds.ne, sw:e.marginBounds.sw}); }} onChildClick={ (child) => setChildClicked(child) } > { places?.map((place,i)=>( <div className={classes.markerContainer} lat = {Number(place.latitude)} lng = {Number(place.longitude)} key = {i}> { !isDesktop? ( < LocationOnOutlinedIcon color="primary" fontSize='large' /> ):( <Paper elevation={3} className={classes.paper}> <Typography className={classes.typography} variant='subtitle2' gutterBottom>{place.name}</Typography> <img className={classes.pointer} src={place.photo ? place.photo.images.large.url:'https://t3.ftcdn.net/jpg/02/21/40/16/240_F_221401603_6urJw6Di9KjlgcPgLfkdVLHtc5Q21aCx.jpg'} alt={place.name} /> <Rating size='small' value={Number(place.rating)}readOnly /> </Paper> ) } </div> )) } </GoogleMapReact> </div> ) }
LR = 0.01 import os import time import numpy as np import tensorflow as tf from tf_agents.networks import q_network from tf_agents.agents.dqn import dqn_agent from snake import Game import keras from multiprocessing import Process, freeze_support def CreateModel(input_shape, num_actions): model = keras.models.Sequential() model.add(keras.layers.Dense(128, input_shape=input_shape, activation='relu')) model.add(keras.layers.Dense(128, activation='relu')) model.add(keras.layers.Dense(num_actions, activation='linear')) model.compile(optimizer='adam', loss='mse') return model def sigmoid_exploration(snake_length, move_count, k=0.01, C=20): # Calculate sigmoid value based on snake length and move count x = snake_length y = move_count sigmoid_value = 1 / (1 + np.exp(k * (x + y - C))) # Notice the positive k return sigmoid_value def train(model, episodes, gamma, epsilon, snakeSize=3, silent=True): # Accumulators for batch training state_batch = [] target_f_batch = [] for episode in range(episodes): game = Game(5, snakeSize) state = game.GetState() state = np.array(state).reshape(1, 14) done = False averageReward = 0 while not done: if(game.GetScore(snakeSize) <= -250): break possible_moves = game.GetMoves() if np.random.rand() < epsilon: action = np.random.randint(0, len(possible_moves)) else: action = np.argmax(model.predict(state)) if action >= len(possible_moves): action = np.random.randint(0, len(possible_moves)) move = possible_moves[action] next_state, reward, done = game.Play(move[0], move[1], defaultSnakeSize=snakeSize) next_state = np.array(next_state).reshape(1, 14) # Calculate target for the Q value target = reward + gamma * np.max(model.predict(next_state)) target_f = model.predict(state).copy() target_f[0][action] = target # Store experience in the batch state_batch.append(state[0]) target_f_batch.append(target_f[0]) state = next_state if (reward < -1000): print("Bad game", episode, reward, game.GetScore(snakeSize)) averageReward += reward if episode % 5 == 0 and not silent: game.ShowBoard() if episode % 20 == 0 and silent: game.ShowBoard() if episode % 10 == 0: print(f"Episode: {episode}, Reward: {averageReward/10}, Epsilon: {epsilon}") averageReward = 0 epsilon = epsilon * (1 - LR) if epsilon > 0.01 else 0.01 # Train the model with the accumulated batch # Model learns after a game is finished model.fit(np.array(state_batch), np.array(target_f_batch), epochs=1, verbose=0) state_batch, target_f_batch = [], [] # Clear the batch return model def PlayWithTraining(model): game = Game(5, 3) state = game.GetState() state = np.array(state).reshape(1, 14) done = False while not done: # if(game.GetScore() <= -250): # break game.ShowBoard() possible_moves = game.GetMoves() action = np.argmax(model.predict(state)) if(action >= len(possible_moves)): action = np.random.randint(0, len(possible_moves)) move = possible_moves[action] next_state, reward, done = game.Play(move[0], move[1], defaultSnakeSize=3) next_state = np.array(next_state).reshape(1, 14) state = next_state time.sleep(0.1) print(f"Score: {game.GetScore(3)} Length: {len(game.snake.body)}") def PlayWithTrainingEnsemble(ensemble, models): game = Game(5, 3) state = game.GetState() state = np.array(state).reshape(1, 14) done = False while not done: if(game.GetScore(3) <= -250): break game.ShowBoard() possible_moves = game.GetMoves() model_outputs = [np.argmax(model.predict(state)) for model in models] game_descriptors = np.array([game.moveCount, len(game.snake.body)]) ensemble_input = np.concatenate([model_outputs, game_descriptors], axis=-1) ensemble_input = ensemble_input.reshape(1, 5) action = np.argmax(ensemble.predict(ensemble_input)) if(action >= len(possible_moves)): action = np.random.randint(0, len(possible_moves)) move = possible_moves[action] next_state, reward, done = game.Play(move[0], move[1], defaultSnakeSize=3) next_state = np.array(next_state).reshape(1, 14) state = next_state time.sleep(0.1) print(f"Score: {game.GetScore(3)} Length: {len(game.snake.body)}") def MakeModel(stringSnakeSize, snakeSize=3): model = CreateModel((14,), 4) model = train(model, 500, 0.9, 1, snakeSize=snakeSize) model.save(f"./submodels/{stringSnakeSize}/{len(os.listdir(f'./submodels/{stringSnakeSize}'))}.h5") return model def MakeEnsembleModel(models): ensemble = CreateModel((5,), 4) ensemble = TrainEnsembleModel(ensemble, models) return ensemble # We take in models for snake sizes of x y z and we average the output of the models to get the final output # Lets train the ensemble model def TrainEnsembleModel(ensemble, models: list[keras.Model], episodes=250, epsilon = 1.0, gamma = 0.9): for episode in range(episodes): game = Game(5, 3) state = game.GetState() state = np.array(state).reshape(1, 14) done = False while not done: if game.GetScore(3) <= -250: break # Make predictions for each model and concatenate them model_outputs = [np.argmax(model.predict(state)) for model in models] # Include game state descriptors game_descriptors = np.array([game.moveCount, len(game.snake.body)]) ensemble_input = np.concatenate([model_outputs, game_descriptors], axis=-1) ensemble_input = ensemble_input.reshape(1, 5) # Use ensemble to predict and select action action_probs = ensemble.predict(ensemble_input) action = np.argmax(action_probs) # Check if action is valid or if random action should be taken possible_moves = game.GetMoves() if action >= len(possible_moves) or np.random.rand() < epsilon: action = np.random.randint(0, len(possible_moves)) # Execute chosen action move = possible_moves[action] next_state, reward, done = game.Play(move[0], move[1], defaultSnakeSize=3) next_state = np.array(next_state).reshape(1, 14) # Prepare for next iteration and model training model_outputs = [np.argmax(model.predict(next_state)) for model in models] game_descriptors = np.array([game.moveCount, len(game.snake.body)]) ensemble_input = np.concatenate([model_outputs, game_descriptors], axis=-1) ensemble_input = ensemble_input.reshape(1, 5) # Update target and train target = reward + 0.9 * np.max(ensemble.predict(ensemble_input)) target_f = action_probs.copy() target_f[0][action] = target ensemble.fit(ensemble_input, target_f, epochs=1, verbose=0) state = next_state epsilon = epsilon * (1 - LR) if epsilon > 0.01 else 0.01 if episode % 5 == 0: game.ShowBoard() if episode % 10 == 0: print(f"Episode: {episode}, Reward: {game.GetScore(3)}") return ensemble
# Week 4 - Challenge 2 ## Formulario React & TypeScript Crea con React un formulario de tres pasos. - En cada paso habrá un grupo de campos, y sólo se debe ver un paso a la vez. - Pon en cada paso un botón para navegar al siguiente y otro para navegar al anterior (en el primer paso no debe verse el botón de anterior). - En el tercer paso debe haber un botón "Acceder". - En cada paso, el botón para continuar al siguiente paso debe estar deshabilitado hasta que se rellenen todos los campos del paso. ### Paso 1: Personal data - Name - Last name - BirthDate (cuando el usuario introduzca la fecha, al lado de este campo debe aparecer su edad en años) - Gender (male/female/other/prefer not to mention) --> Radio button - Email - Desea recibir información de nuestra newsletter? --> Checkbox ### Paso 2: Access data - Username - Password - Repeat password - Account type (personal/pro/business) --> Tiene que ser un select ### Paso 3: Confirmación - El usuario debe de ver todos los datos introducidos y confirmar que es correcto. Botón para confirmar. ### Paso 4: Login - Username - Password Si los datos son incorrectos, se debe de mostrar un mensaje de error. Si son correctos, se le debe mostrar una pantalla con todos los datos introducidos en el formulario (sería como un cuarto paso). Contraer
// Logika do zapisywania charakterystyk import { useState } from 'react'; import { FormStatus } from '../screens/types'; import { API_URL } from '../lib/const'; import { useUserContext } from '../providers/user-provider/UserProvider'; import { CharacteristicsType } from '../providers/user-provider/types'; export default function useSaveCharacteristics() { const [status, setStatus] = useState<FormStatus>('default'); const [message, setMessage] = useState<string>(''); const { state: { token }, } = useUserContext(); const saveCharacteristics = async (data: CharacteristicsType) => { setStatus('loading'); try { const response = await fetch(API_URL + 'saveUserAllCharacteristics', { method: 'POST', headers: { 'Content-Type': 'application/json', Authorization: `Bearer ${token}`, }, body: JSON.stringify(data), }); if (response.ok) { setStatus('success'); setMessage('Dane zostały zapisane pomyślnie'); } else { setMessage('Wystąpił błąd'); setStatus('error'); } } catch (e) { setMessage('Wystąpił błąd'); setStatus('error'); } }; return { status, saveCharacteristics, setStatus, message, }; }
#include <iostream> using namespace std; class Employee { protected: string name; string company; int age; public: virtual void fun() = 0; // this is a pure virtual function // a pure virtual function makes a class an abstract class void setName(string name) { this->name = name; } void setCompany(string company) { this->company = company; } void setAge(int age) { this->age = age; } string getName() { return name; } string getCompany() { return company; } int getAge() { return age; } void introduction() { cout << "Hello! Iam " << name << " from " << company << " and Iam " << age << " years old.\n"; } Employee(string name, string company, int age) { this->name = name; this->company = company; this->age = age; } virtual void work() // this is just a virtual function { cout << "Employee works.\n"; } }; class developer : public Employee { public: string language; developer(string name, string company, int age, string language) : Employee(name, company, age) { this->language = language; } void devIntroduction() { cout << "Hello! Iam " << name << " from " << company << ", Iam " << age << " years old and I love " << language << endl; // protected accessible } void work() { cout << "Employee codes.\n"; } void fun() { cout << "Have fun developer.\n"; } }; class teacher : public Employee { public: string language; teacher(string name, string company, int age, string language) : Employee(name, company, age) { this->language = language; } void tecIntroduction() { cout << "Hello! Iam " << name << " from " << company << ", Iam " << age << " years old and I teach " << language << endl; // protected accessible } void work() { cout << "Employee teaches.\n"; } void fun() { cout << "Have fun teacher.\n"; } }; int main() { developer dev("Sidharth", "Google", 20, "C++"); teacher tec("Saldina", "udemy", 25, "C++"); dev.devIntroduction(); tec.tecIntroduction(); Employee *emp1 = &dev; Employee *emp2 = &tec; Employee *emp3 = new developer("Mohit", "Ramesh pvt. ltd.", 20, "Java"); Employee *emp4 = new teacher("Rohit", "Kamlesh pvt. ltd.", 20, "Python"); emp2->work(); emp2->introduction(); emp3->fun(); emp4->fun(); cout << emp4->getName(); tec.work(); // see tec doesnt have a work(), still this works...why? }
# Copyright 2023 Huawei Technologies Co., Ltd # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """generate MoE token distribution charts script""" import argparse import os import numpy as np import mindspore as ms import matplotlib.pyplot as plt def append_all_npy_path(path): """ Append all npy files path to path_list Args: path(string): The path where the npy files are stored. Returns: path_list(list): A list of npy files path """ path_list_temp = [] for root, _, files in os.walk(path): for each in files: real_path = (os.path.join(root, each)) path_list_temp.append(real_path) return path_list_temp def merge_npy_files(str_layer, path_npy_list): """ Merge the npy files of each MOE layer into a complete file Args: str_layer(string): Layer number (for example layer-0、layer-1) path_npy_list(list): A list of npy files path Returns: data(list): Token distribution data of a moe layer """ sub_path_list = [] for npy_list in path_npy_list: if str_layer in npy_list: sub_path_list.append(npy_list) if not sub_path_list: raise Exception(f"error: {str_layer} is not exist") sub_path_list.sort(key=lambda x: int(x.split(str_layer)[1].split('.')[0])) temp = [] for path in sub_path_list: real_data = np.load(path, allow_pickle=True) temp.append(real_data) return temp def pyplot_show(str_layer, layer_capital, layer_data, save_path_prefix): """ Generate the picture shows the distribution of hot and cold experts Args: str_layer(string): Layer number (for example layer-0、layer-1) layer_capital(string): Capitalize first letter of str_layer (for example Layer-0、Layer-1) data(list): Token distribution data of a MoE layer save_path_prefix(string): The save path prefix for saving the picture Returns: """ if not data: raise Exception(f"{str_layer} data is empty") layer_data = ms.Tensor(layer_data, dtype=ms.float16) layer_data = ms.ops.transpose(layer_data, (1, 0)) expert_num = layer_data.shape[0] step_num = layer_data.shape[1] # Horizontal coordinate of the point x = np.arange(step_num).reshape(-1,) layer_data_list = [] str_expert_list = [] for i in range(expert_num): # Vertical coordinate of the point ki = layer_data[i].asnumpy() layer_data_list.append(ki) str_expert = 'expert-' + str(i) str_expert_list.append(str_expert) layer_data_list = tuple(layer_data_list) fig = plt.figure(figsize=(10, 4), dpi=500) ax = fig.add_subplot(1, 1, 1) plt.stackplot(x, layer_data_list, labels=str_expert_list) # Horizontal coordinate name plt.xlabel("num of step") # Vertical coordinate name plt.ylabel("num of token") # The title plt.title(layer_capital + '_Token_Distribution', fontsize='large', fontweight='bold') handles, labels = ax.get_legend_handles_labels() # Legend ax.legend(handles[::-1], labels[::-1], fontsize='small', loc=7, borderaxespad=-7) plt.show() save_path = save_path_prefix + str_layer + '_token_distribution.jpg' plt.savefig(save_path) if __name__ == '__main__': parser = argparse.ArgumentParser(description='Load and merge npy files') parser.add_argument( '--num_layers', type=int, default=6, help='The number of layers of the model to be converted.') parser.add_argument( '--hot_expert_num', type=int, default=2, help='The number of hot expert for one MoE layer') parser.add_argument( '--npy_files_load_path', type=str, default='../summary_dir/summary_baseline/export/tensor', help='The path where the npy files are stored') parser.add_argument( '--save_path_prefix', type=str, default='./token_distribution/', help='The path prefix after merging npy files') opt = parser.parse_args() if not os.path.exists(opt.save_path_prefix): os.makedirs(opt.save_path_prefix) path_list = append_all_npy_path(opt.npy_files_load_path) list_all = [] for layer_num in range(opt.num_layers): str_layer_split = 'layer-' + str(layer_num) + '_' str_layer_name = 'layer-' + str(layer_num) str_layer_capital = 'Layer-' + str(layer_num) data = merge_npy_files(str_layer_split, path_list) last_step_data = ms.Tensor(data[-1], dtype=ms.float16) _, hot_expert_index = ms.ops.TopK(sorted=True)(last_step_data, opt.hot_expert_num) pyplot_show(str_layer_name, str_layer_capital, data, opt.save_path_prefix) print(f"{str_layer_name} token_distribution generate successful") hot_expert_index_list = [] for j in range(opt.hot_expert_num): hot_expert_index_list.append(int(str(hot_expert_index[j]))) list_all.append(hot_expert_index_list) if layer_num == opt.num_layers-1: print("All layers token_distribution generate successful") print("hot_expert_index: ", list_all)
/** * @example isNumber(123) * @example isNumber('abc') * @description Checks that the value is a valid number. * @returns true if the value is a valid number, false otherwise. */ function isNumber(value: unknown): boolean { if (value === null || value === undefined || typeof value === 'boolean') { return false; } if (typeof value === 'string') { return !Number.isNaN(parseFloat(value)) && Number.isFinite(parseFloat(value)); } if (typeof value === 'number') { return Number.isFinite(value); } return false; } export default isNumber;
<?php class CreatePdfThumbnailsJob extends Job { /** * Flags for thumbnail jobs */ const BIG_THUMB = 1; const SMALL_THUMB = 2; /** * Construct a thumbnail job * * @param $title Title Title object * @param $params array Associative array of options: * page: page number for which the thumbnail will be created * jobtype: CreatePDFThumbnailsJob::BIG_THUMB or CreatePDFThumbnailsJob::SMALL_THUMB * BIG_THUMB will create a thumbnail visible for full thumbnail view, * SMALL_THUMB will create a thumbnail shown in "previous page"/"next page" boxes * */ public function __construct( $title, $params ) { parent::__construct( 'createPdfThumbnailsJob', $title, $params ); } /** * Run a thumbnail job on a given PDF file. * @return bool true */ public function run() { if ( !isset( $this->params['page'] ) ) { wfDebugLog('thumbnails', 'A page for thumbnails job of ' . $this->title->getText() . ' was not specified! That should never happen!'); return true; // no page set? that should never happen } $file = wfLocalFile( $this->title ); // we just want a local file if ( !$file ) { return true; // Just silently fail, perhaps the file was already deleted, don't bother } switch ($this->params['jobtype']) { case self::BIG_THUMB: global $wgImageLimits; // Ignore user preferences, do default thumbnails // everything here shamelessy copied and reused from includes/ImagePage.php $sizeSel = User::getDefaultOption( 'imagesize' ); // The user offset might still be incorrect, specially if // $wgImageLimits got changed (see bug #8858). if ( !isset( $wgImageLimits[$sizeSel] ) ) { // Default to the first offset in $wgImageLimits $sizeSel = 0; } $max = $wgImageLimits[$sizeSel]; $maxWidth = $max[0]; $maxHeight = $max[1]; $width_orig = $file->getWidth( $this->params['page'] ); $width = $width_orig; $height_orig = $file->getHeight( $this->params['page'] ); $height = $height_orig; if ( $width > $maxWidth || $height > $maxHeight ) { # Calculate the thumbnail size. # First case, the limiting factor is the width, not the height. if ( $width / $height >= $maxWidth / $maxHeight ) { //$height = round( $height * $maxWidth / $width ); $width = $maxWidth; # Note that $height <= $maxHeight now. } else { $newwidth = floor( $width * $maxHeight / $height ); //$height = round( $height * $newwidth / $width ); $width = $newwidth; # Note that $height <= $maxHeight now, but might not be identical # because of rounding. } $transformParams = array( 'page' => $this->params['page'], 'width' => $width ); $file->transform( $transformParams ); } break; case self::SMALL_THUMB: Linker::makeThumbLinkObj( $this->title, $file, '', '', 'none', array( 'page' => $this->params['page'] ) ); break; } return true; } /** * @param $upload UploadBase * @param $mime * @param $error * @return bool */ public static function insertJobs( $upload, $mime, &$error ) { global $wgPdfCreateThumbnailsInJobQueue; if ( !$wgPdfCreateThumbnailsInJobQueue ) { return true; } if (!MimeMagic::singleton()->isMatchingExtension('pdf', $mime)) { return true; // not a PDF, abort } $title = $upload->getTitle(); $uploadFile = $upload->getLocalFile(); if ( is_null( $uploadFile ) ) { wfDebugLog('thumbnails', '$uploadFile seems to be null, should never happen...'); return true; // should never happen, but it's better to be secure } $metadata = $uploadFile->getMetadata(); $unserialized = unserialize( $metadata ); $pages = intval( $unserialized['Pages'] ); $jobs = array(); for ( $i = 1; $i <= $pages; $i++ ) { $jobs[] = new CreatePdfThumbnailsJob( $title, array( 'page' => $i, 'jobtype' => self::BIG_THUMB ) ); $jobs[] = new CreatePdfThumbnailsJob( $title, array( 'page' => $i, 'jobtype' => self::SMALL_THUMB ) ); } Job::batchInsert( $jobs ); return true; } }
from flask import Flask, render_template, request import httpretty import json import mysql.connector import requests import time app = Flask(__name__) @app.route('/') def index(): return render_template('index.html', title='トップページ') @app.route('/analyze', methods=['POST']) def analyze(): # APIのmock-upを有効化 enable_mock(is_success=True) # APIリクエスト URL = "http://example.com/" image_path = request.form.get("image_path") data = {"image_path": image_path} request_timestamp = int(time.time()) response = requests.post(URL, data=data) response_timestamp = int(time.time()) image_info = response.json() # APIのmock-upを無効化 if httpretty.is_enabled(): httpretty.disable() httpretty.reset() # MySQL接続 cnx = mysql.connector.connect( host="mysqldb", user="root", database="invox", password="p@ssw0rd1" ) cursor = cnx.cursor() # データ挿入 query = get_query() insert_value = get_insert_value( image_path, image_info, request_timestamp, response_timestamp) cursor.execute(query, insert_value) cnx.commit() # MySQL接続を閉じる cursor.close() cnx.close() return render_template('result.html', title='結果ページ') def enable_mock(is_success, enabled=True): if not enabled: # mock-upを有効化しない return httpretty.enable(verbose=True, allow_net_connect=True) if is_success: # リクエスト成功時のデータ dummy = { "success": "true", "message": "success", "estimated_data": {"class": 3, "confidence": 0.8683}, } else: # リクエスト失敗時のデータ dummy = { "success": "false", "message": "Error:E50012", "estimated_data": {}, } httpretty.register_uri( httpretty.POST, "http://example.com/", body=json.dumps(dummy)) def get_query(): query = \ 'INSERT INTO ai_analysis_log ('\ 'image_path, '\ 'success, '\ 'message, '\ 'class, '\ 'confidence, '\ 'request_timestamp, '\ 'response_timestamp) '\ 'VALUES ('\ '%(image_path)s, '\ '%(success)s, '\ '%(message)s, '\ '%(class)s, '\ '%(confidence)s, '\ '%(request_timestamp)s, '\ '%(response_timestamp)s)' return query def get_insert_value(image_path, image_info, request_timestamp, response_timestamp): success = image_info.get("success") message = image_info.get("message") estimated_data = image_info.get("estimated_data") if estimated_data: class_ = estimated_data.get("class") confidence = estimated_data.get("confidence") else: class_ = None confidence = None insert_value = { "image_path": image_path, "success": success, "message": message, "class": class_, "confidence": confidence, "request_timestamp": request_timestamp, "response_timestamp": response_timestamp, } return insert_value
% !TeX root = ./0_Manuscript.tex \section{Introduction \ddc} \label{chap:1;sect:intro} %BEGIN LanguageTool In our time, almost every business sector and every part of our surroundings, directly or indirectly, uses integrated electronics circuits. It ranges from smart-cards to supercomputers, through military devices, cell-phones, Cyber-Physical Systems (\cps) and Internet-of-Things (\iot) objects to name but a few. Traditionally, integrated circuits design mainly focused on performance upgrades over the generations. Performance was measured thanks to two factors: computation speed and silicon surface. Within this context, power consumption was not a design constraint; therefore, integrated circuits became more and more energy-consuming. However, with the advent of portable devices, power consumption became a predominant design factor over speed and space, and it got included into the former design flows. Nevertheless, less space and more speed does not physically equate with less energy. Alongside, new systems have emerged and have massively grown these past decades: some fall in the field of \cps, while others lies in the field of \iot. On the one hand, CPS are often systems where hardware and software are interlaced and thought together, and can be drastically different from one application to another. On the other hand, IoT systems have often less coordination between hardware and software, but are commonly more flexible. Whatsoever, both of these systems have something strong in common: their security is fundamental. %In this context, the word security has several meanings: %\begin{itemize} % \setlength\itemsep{-0.1em} % \item Provide data confidentiality; % \item Ensure data integrity; % \item Guarantee data availability. %\end{itemize} Therefore, in this context, as it has been proposed in \cite{securityInIcs}, and because security had been adopted as a countermeasure after the design flow, it had to enter as a fourth design rule when creating integrated circuits. This is required because a secure system has to ensure that every data going in and out of it is subject to the following criteria: \begin{itemize} \setlength\itemsep{-0.1em} \item Authenticity: the data received has to come from the sender; \item Integrity: the data cannot be altered in any way; \item Confidentiality: the data cannot be accessed (read or written) by third-parties. \end{itemize} %every data going in and out of it must stays undiminished and integral, as well as being protected. Consequently, it is imperative to study and comprehend the strategies for enhancing IC security to develop future integrated circuits that are designed with security in mind from the initial stages of development to its completion. Currently, electronic devices implement security in two distinct ways, namely from a software or hardware standpoint. To ensure security, encryption algorithms have been integrated in integrated circuits. It is possible to distinguish two distinct categories of encryption algorithms, namely symmetric and asymmetric algorithms. In short, symmetric cryptographic techniques use a unique key for encrypting and decrypting messages. The most popular algorithms are the \aes (Advanced Encryption Standard) \cite{aesRijndaelProp}, \des (Data Encryption Standard) \cite{desOrigin}, IDEA (International Data Encryption Algorithm) \cite{ideaOrigin}, RC5 (Rivest Cipher 5), and TDES (Triple DES) \cite{tripleDes}, not to cite them all. The key must be kept confidential and only shared among parties to maintain a confidential connection between them. The requirement for a single key is the main drawback of symmetric encryption methods. As a result, every possible step must be taken to safeguard key secrecy, such as avoiding key exchanges on public networks. However, symmetric encryption has a clear advantage over asymmetric encryption. As a result of utilizing a single key, symmetric algorithms are typically simpler than asymmetric algorithms, resulting in a reduction in computing power required for encryption and decryption. It is therefore possible to encrypt a large amount of data in a short amount of time. In contrast, when it comes to symmetric cryptographic techniques, commonly referred to as public key cryptography techniques, a pair of keys is employed. The keys are usually referred to as public-key and private-key. The public key is used to encrypt a message, and anyone can use it. The private-key is, however, kept confidential to ensure that only authorized parties can decrypt a message that has been encrypted with the public-key. The primary motivation behind having two keys is that it is impracticable to reconstruct the public-key from the private-key. The most commonly employed asymmetric algorithms include the RSA (Rivest–Shamir–Adleman) \cite{RSAorigin} algorithm, the ElGamal encryption system \cite{elgamal1985public}, the ECC (Elliptic-curve cryptography) \cite{kapoor2008elliptic}, and the Cramer-Shoup system \cite{cramer2000signature}, to name a few. The main drawback of symmetrical algorithms is that they involve large mathematical calculations, which implies a higher time complexity. Hence, these techniques are capable of encrypting a limited quantity of data. Therefore, to achieve this objective, in the majority of systems, a hybrid approach is employed, involving both encryption methods, thereby ensuring optimal security and brief ciphering times. On the one hand, if all the previously mentioned algorithms are mathematically reliable, their reliability decreases when they are implemented on actual integrated circuits. Indeed, when an IC operates, it alters the behavior of some physical quantities according to the data being processed. Thus, it inevitably and unintentionally communicates information to the surrounding environment through these quantities. Among them, one can identify the electric current, and therefore the resulting electromagnetic field. In a normal context, where the data is not secret, it is not a problem. However, as soon as the data security is a major concern, the IC communicates to its surrounding data information through the various physical quantities. This is called leakage. An adversary can therefore measure these leakages to retrieve confidential data thanks to mathematical and statistical tools. These methods are called \textbf{“side-channel attack” (\sca)}. %Indeed, every integrated circuit uses electrical energy to function. %Therefore, when an electric current appears in a conductor, there is inevitably an electromagnetic field associated with this current. %Moreover, every measurable physical quantity concerning the IC operation could be a point of information leakage. %This is particularly true when considering the fact that these quantities will exhibit varying variations based on the calculations performed by the IC. %When evaluating these quantities, it is possible to retrieve confidential information. %I described what is called a \textbf{"side-channel attack" (\sca)} when considering cybersecurity. On the other hand, physical quantity measurement is not the only flaw in actual algorithm implementations. In fact, every physical IC has specifications under which it can operate properly. It includes temperature, clock frequency, power supply voltage, and the electromagnetic environment. When pushed beyond its specifications, any integrated circuit exhibits unpredictable behavior. However, it is still possible to control the behavior of an IC outside its specifications with a certain degree of success. By doing so, it is possible to run the calculations incorrectly by finely controlling how much time and by which amount the IC is outside its specifications, thus enabling, with specific mathematical algorithms, to retrieve hidden data manipulated by the IC, like secret encryption keys or sensitive data. This process is commonly referred to as a \textbf{“fault injection attack”}. I have identified two potential hardware threats on robust algorithms that have been implemented into actual integrated circuits. However, it is customary to categorize cyberattacks into three distinct categories based on their execution methods. Despite being technically advanced, noninvasive attacks are the most materially trivial. \sca are included in this set, which do not require any hardware modification to the targeted ICs. %, even if there is no physical contact. It is a delicate task to detect them; hence, they are deemed to be highly dangerous and are commonly considered in the initial stages of designing integrated circuits. Then, it is possible to distinguish semi-invasive attacks. Systematically, they are accompanied by device physical preparation, which was entirely devoid of noninvasive attacks, but they are not accompanied by device physical modification. ICs integrity is therefore fully preserved. A typical IC modification involves the removal of the chip package. It enables access to either the front or back side of the integrated circuit, thereby facilitating micro-probing, laser injection, or substrate pulse injection. Furthermore, substrate thinning is also commonly considered and used, as it facilitates the fine-tuning of certain fault injection techniques, such as laser fault injection (\lfi). These attacks necessitate specialized hardware, tools, and expertise and are frequently challenging to establish and execute. Eventually, there are invasive attacks. They imply further physical modifications to integrated circuits. For instance, it is common to eliminate the layers of a chip, thereby enabling the photographing of the various layers and the reverse engineering of the target. A focused ion beam (FIB) can also be used to change the IC target internally by creating electric connections that did not exist before, or destroy existing ones. %Contrary to semi-invasive attacks, invasive attacks frequently involve the definitive destruction of the target, primarily due to the absence of physical integrity during the process. Invasive attacks often involve the definitive destruction of the target, primarily because physical integrity is not preserved during the process. My doctoral thesis is dedicated to the study of a specific fault injection method: Body Biasing Injection. In this particular context, I examine in the next paragraphs the current state of the art in relation to side-channel attacks and fault injection techniques, as outlined in the literature. This allows me to explain the interests of the current work regarding hardware security. In the first place, I briefly discuss side-channel attacks. Then, I examine the various fault injection platforms commonly described. Eventually, I ponder the interests of BBI in this context.
<div class="droppable-root h-100 grid-container" [attr.data-folder-id]="'root'"> <mat-grid-list [cols]="numberOfItemsPerRow" rowHeight="250px" gutterSize="15px" class="grid-container"> <ng-container *ngFor="let document of documents; let i = index; trackBy: trackByFn"> <div (contextmenu)="onOpenContextMenu($event, document)" [ngClass]="{ 'selected': selectedDocument?.id === document.id && !multiFiles.includes(document)}" (click)="onClick(document, i, $event)" (dblclick)="onOpenPreviewAttachment(document)" appDragGhost [content]="document.name" [type]="document.iconType" [countFiles]="multiFiles.length" [draggable]="document.type !== DocumentType.FOLDER" (dragstart)="onDragStartFile($event, document)" (dragend)="onDragEnd()"> <mat-grid-tile fxLayout="column" class="grid-item clickable" fxLayoutAlign="none center" [attr.data-folder-id]="document?.id" [ngClass]="{ 'droppable': document.type === DocumentType.FOLDER, 'file-dragged': filesDragging && filesDragging.includes(document), 'select-many': multiFiles.includes(document), 'selected': selectedDocument?.id === document.id }"> <div class="thumbnail w-100 h-100"> </div> <mat-grid-tile-footer fxLayout="row" fxLayoutGap="8px" fxLayoutAlign="start center"> <img draggable="false" src="assets/icon-files-types/{{document.iconType}}.svg" alt="" width="20" height="20"> <h3 class="label-truncate">{{document.name}}</h3> </mat-grid-tile-footer> </mat-grid-tile> </div> </ng-container> </mat-grid-list> </div> <div class="context-menu" [style.left]="contextMenuPosition.x" [style.top]="contextMenuPosition.y" [matMenuTriggerFor]="contextMenu"> </div> <mat-menu #contextMenu="matMenu" [overlapTrigger]="false" (closed)="onCloseContextMenu()" hasBackdrop="false"> <ng-template matMenuContent> <ng-container> <button mat-menu-item> <mat-icon>open_with</mat-icon> Open with </button> <mat-divider></mat-divider> </ng-container> <ng-container> <button mat-menu-item> <mat-icon>person_add_alt</mat-icon> Share </button> <button mat-menu-item> <mat-icon>link</mat-icon> Get link </button> <button mat-menu-item> <mat-icon>folder_outline</mat-icon> Show folder location </button> <button mat-menu-item> <mat-icon>add_to_drive</mat-icon> Add shortcut to Drive </button> <button mat-menu-item> <mat-icon>drive_file_move_outline</mat-icon> Move to </button> <button mat-menu-item> <mat-icon>star_outline</mat-icon> Add to Starred </button> <button mat-menu-item> <mat-icon>drive_file_rename_outline</mat-icon> Rename </button> <button mat-menu-item> <mat-icon>palette_outline</mat-icon> Change color </button> <button mat-menu-item> <mat-icon>search</mat-icon> Search within ... </button> <mat-divider></mat-divider> </ng-container> <ng-container> <button mat-menu-item> <mat-icon>info_outline</mat-icon> View detail </button> <button mat-menu-item> <mat-icon>download</mat-icon> Download </button> <mat-divider></mat-divider> </ng-container> <ng-container> <button mat-menu-item> <mat-icon>delete_outline</mat-icon> Remove </button> </ng-container> </ng-template> </mat-menu>
#include <stdio.h> #include <stdlib.h> #include <math.h> int mod_inverse(int a, int m) { int m0 = m, t, q; int x0 = 0, x1 = 1; if (m == 1) return 0; while (a > 1) { q = a / m; t = m; m = a % m; a = t; t = x0; x0 = x1 - q * x0; x1 = t; } if (x1 < 0) x1 += m0; return x1; } int main() { int p, q, n, phi_n, e, d; printf("Enter the first prime number (p): "); scanf("%d", &p); printf("Enter the second prime number (q): "); scanf("%d", &q); n = p * q; phi_n = (p - 1) * (q - 1); printf("Enter an integer e such that 1 < e < %d and gcd(e, f(n)) = 1: ", phi_n); for(int i=2;i<phi_n;i++) { int length= phi_n%i; if(!length==0) { e=i; break; } } d = mod_inverse(e, phi_n); printf("Public Key: (n = %d, e = %d)\n", n, e); printf("Private Key: (n = %d, d = %d)\n", n, d); int m; printf("Enter the message to be encrypted: "); scanf("%d", &m); int c = (int)pow(m, e) % n; printf("Original Message: %d\n", m); printf("Encrypted Message: %d\n", c); int decrypted_message = (int)pow(c, d) % n; printf("Decrypted Message: %d\n", decrypted_message); return 0; }
import { Button, Flex, Heading, Stack, useColorModeValue, } from "@chakra-ui/react"; import { Form, Formik } from "formik"; import { NextPage } from "next"; import { useRouter } from "next/router"; import React from "react"; import authService from "../../../services/authService"; import { toErrorMap } from "../../../utils/toErrorMap"; import InputField from "../../components/inputs/InputField"; import Navbar from "../../components/shared/Navbar"; const ResetPassword: NextPage = () => { const router = useRouter(); return ( <> <Navbar /> <Flex minH={"100vh"} align={"center"} justify={"center"} bg={useColorModeValue("gray.50", "gray.800")} > <Formik initialValues={{ password: "" }} onSubmit={async (values, { setErrors }) => { try { await authService.resetPassword({ ...values, token: router.query.token, }); router.push("/"); } catch (error) { if (error.response?.status === 404) { setErrors({ password: error.response.data.message, }); } else { const errors = error.response?.data?.errors; if (errors) { setErrors(toErrorMap(errors)); } } } }} > {({ isSubmitting }) => ( <Form> <Stack spacing={4} w={"full"} maxW={"md"} bg={useColorModeValue("white", "gray.700")} rounded={"xl"} boxShadow={"lg"} p={6} my={12} > <Heading lineHeight={1.1} fontSize={{ base: "2xl", md: "3xl" }}> Enter new password </Heading> <InputField name="password" placeholder="Password" label="Password" type="password" /> <Stack spacing={6}> <Button type="submit" isLoading={isSubmitting}> Change Password </Button> </Stack> </Stack> </Form> )} </Formik> </Flex> </> ); }; export default ResetPassword;
import React, { useState, useEffect } from "react"; import "./App.css"; import endSound from "./end-sound.mp3"; // Importing end sound files. import originalWords from "./words.json"; // Import original word sequences. // Functions for shuffling arrays(Fisher-Yates shuffle algorithm) function shuffleArray(array) { const shuffledArray = array.slice(); // Copy array for (let i = shuffledArray.length - 1; i > 0; i--) { const j = Math.floor(Math.random() * (i + 1)); [shuffledArray[i], shuffledArray[j]] = [shuffledArray[j], shuffledArray[i]]; } return shuffledArray; } function App() { const TIMER_SECONDS = 300; const [words, setWords] = useState(shuffleArray(originalWords)); // Shuffled word sequence const [currentWordIndex, setCurrentWordIndex] = useState(0); const [timer, setTimer] = useState(TIMER_SECONDS); const [isRunning, setIsRunning] = useState(false); const [isEnded, setIsEnded] = useState(false); const [isAllWordsShown, setIsAllWordsShown] = useState(false); useEffect(() => { let countdown; if (isRunning && timer > 0) { // start the timer countdown = setInterval(() => { setTimer((prevTimer) => prevTimer - 1); }, 1000); } else if (timer === 0) { // Stops when the timer is zero. setIsRunning(false); setIsEnded(true); new Audio(endSound).play(); } // コンポーネントのアンマウント時にタイマーをクリア return () => clearInterval(countdown); }, [timer, isRunning]); useEffect(() => { // Enterキーでタイマーをスタート/ストップまたはワードを切り替えるイベントリスナーを追加 const handleKeyDown = (event) => { // Spaceキーでタイマーをスタート/ストップ if (event.key === "s") { setIsRunning((prevIsRunning) => !prevIsRunning); } if (event.key === " ") { if (!isRunning && !isEnded) { setIsRunning(true); setTimer(TIMER_SECONDS); // タイマーをリセット } else if (isRunning) { if (currentWordIndex < words.length - 1 && !isAllWordsShown) { setCurrentWordIndex(currentWordIndex + 1); } else { setIsAllWordsShown(true); } } } }; window.addEventListener("keydown", handleKeyDown); // イベントリスナーをクリーンアップ return () => { window.removeEventListener("keydown", handleKeyDown); }; }, [isRunning, isEnded, currentWordIndex, words.length, isAllWordsShown]); // タイマーを分:秒の形式に変換 const formatTime = () => { const minutes = Math.floor(timer / 60); const seconds = timer % 60; return `${minutes}:${seconds < 10 ? "0" : ""}${seconds}`; }; return ( <div className="App"> <header className="App-header"> {isEnded ? ( <div> <h2>Time is up!</h2> </div> ) : ( <div> {isRunning && !isAllWordsShown && <h1>{words[currentWordIndex]}</h1>} <p>{!isRunning && startComponent}</p> <h3>{formatTime()}</h3> {isAllWordsShown && <p>* All words are displayed...</p>} </div> )} </header> </div> ); } const startComponent = ( <span> Press 'SPACE' to change words. <br /> Press 'S' to start/pause the timer. </span> ); export default App;
package com.example.listfirebase.predefinedlook import androidx.compose.foundation.background import androidx.compose.foundation.clickable import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.padding import androidx.compose.foundation.shape.RoundedCornerShape import androidx.compose.material.icons.Icons import androidx.compose.material.icons.filled.MoreVert import androidx.compose.material.Card import androidx.compose.material3.Icon import androidx.compose.material3.MaterialTheme import androidx.compose.material3.Text import androidx.compose.runtime.Composable import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.graphics.Color import androidx.compose.ui.unit.dp import com.example.listfirebase.data.firebasedata.listfirebase.ListEntity @Composable fun ListItems( list: ListEntity = ListEntity(listName = "aaaaaaaaaaaaaaa"), modifier: Modifier = Modifier, onTextClick: () -> Unit = {}, onDeleteClick: () -> Unit = {}, onDotsClick: () -> Unit = {}, ) { Card( modifier .fillMaxWidth() .background(Color.White) .clickable { } .padding(8.dp), elevation = 8.dp, shape = RoundedCornerShape(16.dp) ) { Row( modifier = Modifier .fillMaxWidth() .padding(16.dp), verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.SpaceBetween ) { Box( modifier = Modifier .weight(1f) .padding(end = 8.dp) .clickable { onTextClick() }, contentAlignment = Alignment.CenterStart ) { Text( text = list.listName, color = Color.Black, style = MaterialTheme.typography.bodyMedium, ) } Icon( imageVector = Icons.Default.MoreVert, contentDescription = "More options", // Add a description tint = Color.Black, modifier = Modifier.clickable { onDotsClick() }) } } }
/* Copyright 2021, Milkdown by Mirone. */ import { defaultValueCtx, Editor, rootCtx } from "@milkdown/core"; import { slash } from "@milkdown/plugin-slash"; import { commonmarkNodes, // commonmarkPlugins, commonmark, // image, } from "@milkdown/preset-commonmark"; import { nord } from "@milkdown/theme-nord"; import { EditorRef, useEditor, VueEditor } from "@milkdown/vue"; import { DefineComponent, defineComponent, ref } from "vue"; // import ImageCat from "./CatImage.vue" import ImageDrawComponent from "./ImageDrawComponent.vue"; // plugins import { history } from "@milkdown/plugin-history"; import { cursor } from "@milkdown/plugin-cursor"; // import { table } from "@milkdown/plugin-table"; import { math } from "@milkdown/plugin-math"; import { tooltip } from "@milkdown/plugin-tooltip"; import { indent } from "@milkdown/plugin-indent"; // https://www.npmjs.com/package/@milkdown/plugin-menu import { menu } from "@milkdown/plugin-menu"; import { upload } from "@milkdown/plugin-upload"; import { prism } from "@milkdown/plugin-prism"; // import { diagram } from "../milkdown_plugins/plugin-diagram/src"; import { drawing } from "../milkdown_plugins/plugin-drawing/src"; import "katex/dist/katex.min.css"; // https://www.npmjs.com/package/material-icons import "material-icons/iconfont/material-icons.css"; const ImageDraw: DefineComponent = defineComponent({ name: "image-draw", setup() { return () => <ImageDrawComponent />; }, components: { ImageDrawComponent, }, }); // import { createNode } from '@milkdown/utils'; import { listener, listenerCtx } from "@milkdown/plugin-listener"; // let output = ''; // import { image } from "../milkdown_plugins/plugin-image-draw/image"; const MyEditor = defineComponent<{ markdown: string }>({ name: "my-editor", setup: (props) => { const editorRef = ref<EditorRef>({ get: () => undefined, dom: () => null }); const editor = useEditor((root, renderVue) => { // const nodes = commonmarkNodes.configure(image, { // view: renderVue(ImageDraw), // }); return ( Editor.make() .config((ctx) => { ctx.set(rootCtx, root); ctx.set(defaultValueCtx, props.markdown); ctx .get(listenerCtx) .markdownUpdated((ctx, markdown, prevMarkdown) => { // @ts-ignore let output = markdown; console.log(output); }); }) .use(nord) // .use(nodes) .use(commonmark) .use(slash) .use(listener) .use(history) .use(cursor) .use(math) .use(tooltip) .use(indent) .use(menu()) .use(upload) .use(prism) .use(drawing) ); }); // @ts-ignore return () => <VueEditor editorRef={editorRef} editor={editor} />; }, }); MyEditor.props = ["markdown"]; export { MyEditor };
package ca.nait.dmit.batch; import jakarta.batch.api.BatchProperty; import jakarta.batch.api.chunk.AbstractItemReader; import jakarta.batch.runtime.context.JobContext; import jakarta.inject.Inject; import jakarta.inject.Named; import java.io.BufferedReader; import java.io.FileReader; import java.io.Serializable; import java.nio.file.Paths; @Named public class EnforcementZoneCentreItemReader extends AbstractItemReader { @Inject private JobContext _jobContext; private BufferedReader _reader; @Inject @BatchProperty(name = "input_file") private String inputFile; @Override public void open(Serializable checkpoint) throws Exception { super.open(checkpoint); _reader = new BufferedReader(new FileReader(Paths.get(inputFile).toFile())); // Read the first line to skip the header row _reader.readLine(); } @Override public Object readItem() throws Exception { try { String line = _reader.readLine(); return line; } catch (Exception ex) { ex.printStackTrace(); } return null; } }
import { createSlice } from '@reduxjs/toolkit'; const initialState = { value: 0, state: 'idle' } const counterSlice = createSlice({ initialState, name: 'counter', reducers: { increment: (state) => { state.value += 1; }, decrement: (state) => { state.value -= 1; }, incrementByAmount: (state, action) => { state.value += action.payload; } } }) // actions export const { increment, decrement, incrementByAmount } = counterSlice.actions; export const selectCount = (state) => state.counter.value; export default counterSlice.reducer;
/*! * * * \brief Calculates the hypervolume covered by a front of non-dominated points. * * * * \author T.Voss * \date 2010 * * * \par Copyright 1995-2017 Shark Development Team * * <BR><HR> * This file is part of Shark. * <http://shark-ml.org/> * * Shark is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published * by the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * Shark 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 Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with Shark. If not, see <http://www.gnu.org/licenses/>. * */ #ifndef SHARK_ALGORITHMS_DIRECTSEARCH_INDICATORS_HYPERVOLUMEINDICATOR_H #define SHARK_ALGORITHMS_DIRECTSEARCH_INDICATORS_HYPERVOLUMEINDICATOR_H #include <shark/Core/Exception.h> #include <shark/Core/OpenMP.h> #include <shark/Algorithms/DirectSearch/Operators/Hypervolume/HypervolumeContribution.h> #include <algorithm> #include <vector> #include <numeric> namespace shark { /// \brief Calculates the hypervolume covered by a front of non-dominated points. /// /// If given, the Indicator uses a provided reference value that can be set via setReference. /// Otherwise, it is computed from the data by using the maximum value in the set. As this usually /// gives 0 contribution to the extremum points (i.e. the ones with best function value), those /// points are skipped when computing the contribution (i.e. extremum points are never selected). /// Note, that for boundary points that are not extrema, this does not hold and they are selected. /// /// for problems with many objectives, an approximative algorithm can be used. struct HypervolumeIndicator { /// \brief Determines the point contributing the least hypervolume to the overall front of points. /// /// \param [in] front pareto front of points template<typename ParetoFrontType, typename ParetoArchive> std::size_t leastContributor( ParetoFrontType const& front, ParetoArchive const& /*archive*/)const{ HypervolumeContribution algorithm; if(m_reference.size() != 0) return m_algorithm.smallest(front,1,m_reference)[0].value; else return m_algorithm.smallest(front,1)[0].value; } template<typename ParetoFrontType, typename ParetoArchive> std::vector<std::size_t> leastContributors( ParetoFrontType const& front, ParetoArchive const& archive, std::size_t K)const{ std::vector<std::size_t> indices; std::vector<RealVector> points(front.begin(),front.end()); std::vector<std::size_t> activeIndices(points.size()); std::iota(activeIndices.begin(),activeIndices.end(),0); for(std::size_t k=0; k != K; ++k){ std::size_t index = leastContributor(points,archive); points.erase(points.begin()+index); indices.push_back(activeIndices[index]); activeIndices.erase(activeIndices.begin()+index); } return indices; } template<class random> void init(std::size_t /*numOfObjectives*/, std::size_t /*mu*/, random& /*rng*/){} /// \brief Sets the reference point. /// /// If no point is set, it is estimated from the current front and the extremum points are never selected. void setReference(RealVector const& newReference){ m_reference = newReference; } /// \brief Whether the approximtive algorithm should be used on large problems void useApproximation(bool useApproximation){ m_algorithm.useApproximation(useApproximation); } ///\brief Error bound for the approximative algorithm double approximationEpsilon()const{ return m_algorithm.approximationEpsilon(); } ///\brief Error bound for the approximative algorithm double& approximationEpsilon(){ return m_algorithm.approximationEpsilon(); } ///\brief Error probability for the approximative algorithm double approximationDelta()const{ return m_algorithm.approximationDelta(); } ///\brief Error probability for the approximative algorithm double& approximationDelta(){ return m_algorithm.approximationDelta(); } template<typename Archive> void serialize( Archive & archive, const unsigned int version ) { archive & BOOST_SERIALIZATION_NVP( m_reference ); archive & BOOST_SERIALIZATION_NVP( m_algorithm ); } private: RealVector m_reference; HypervolumeContribution m_algorithm; }; } #endif
import { styled } from '@mui/material/styles'; import Typography from '@mui/material/Typography'; import { Box, Container } from '@mui/system'; import clsx from 'clsx'; import { ipcRenderer } from 'electron'; import { FC, ReactNode } from 'react'; import NavDrawer from './NavDrawer'; import TitleBar from './TitleBar'; type Props = { title: string; children: ReactNode; disablePadding?: boolean; contentFillPage?: boolean; }; const Root = styled('div')(() => ({ height: '100%', width: '100%', display: 'flex', flexDirection: 'column', '& .page-wrapper': { display: 'flex', flexGrow: 1, maxHeight: 'calc(100vh - 28px)', }, '& .content-wrapper': { width: '100%', maxHeight: 'calc(100vh - 28px)', paddingTop: '20px', '&.no-padding': { padding: 0, '& main': { margin: 0, padding: 0 } }, }, '& .scroll-enabled': { overflow: 'auto', '&::-webkit-scrollbar': { width: '16px', }, '&::-webkit-scrollbar-thumb': { backgroundColor: '#ccc', borderRadius: '12px', border: '4px solid transparent', backgroundClip: 'content-box', minWidth: '16px', minHeigh: '16px', }, '&::-webkit-scrollbar-track': { backgroundColor: 'transparent', }, }, '& main': { height: '100%', maxHeight: '100%', '&.fill-page': { maxWidth: 'unset' }, }, })); const Layout: FC<Props> = ({ title, children, disablePadding, contentFillPage, }) => { return ( <Root> <TitleBar title={title} /> <div className="page-wrapper"> <NavDrawer /> <Box className={clsx({ 'content-wrapper': true, 'scroll-enabled': true, 'no-padding': disablePadding, })} > <Container component="main" className={clsx({ 'fill-page': contentFillPage })} > {children} </Container> </Box> </div> </Root> ); }; Layout.defaultProps = { disablePadding: false, contentFillPage: false, }; export default Layout;
# AGameState > INFO > > With 4.14, the GameState Class got split into AGameStateBase and AGameState. GameStateBase has fewer features because some games might not need the full feature list of the old GameState Class. The class AGameState is probably the most important class for shared information between the server and the clients. The GameState is used to keep track of the current state of the game/match. This includes, for multiplayer important, a list of connected players (APlayerState). Additionally, it is replicated for all clients, so everyone can access it. This makes the GameState one of the most central classes for multiplayer Games in terms of information. While the GameMode would tell how many kills are needed to win, the GameState would keep track of the current amount of kills of each player and/or team! What information you store here is completely up to you. It could be an array of scores or an array of a custom struct that you use to keep track of groups and guilds. ## Examples and Usage In multiplayer, the AGameState class is used to keep track of the current state of the game, which also includes the players and their PlayerStates. The GameMode makes sure that the MatchState functions of the GameState are called and the GameState itself allows you to use them on clients as well. Compared to the GameMode the GameState doesn't give us much to work with, but this still allows us to create our logic, which should mostly try to spread information to clients. ### Blueprint Examples #### Variables ![GameState Variables](../images/g_image-8.png) We get a few variables from the base AGameState Class that we can utilize. The PlayerArray, as well as the MatchState and the ElapsedTime are replicated, so clients can also access them. This does not count for the AuthorityGameMode. Only the server can access it since the GameMode only exists on the server. The PlayerArray is not directly replicated, however, every PlayerState is replicated and they add themselves to the PlayerArray on construction. Additionally, they are collected by the GameState, just to ensure no race-condition causes problems. A quick insert to show how the PlayerStates are collected into the PlayerArray in C++. ``` cpp // Inside of the PlayerState Class itself -------------------------------------------------------------------------------- void APlayerState::PostInitializeComponents() { // […] UWorld* World = GetWorld(); // Register this PlayerState with the Game's ReplicationInfo if (World->GameState != NULL) { World->GameState->AddPlayerState(this); } // […] } ``` ``` cpp // And in the GameState -------------------------------------------------------------------------------- void AGameState::PostInitializeComponents() { // […] for (TActorIterator<APlayerState> It(World); It; ++It) { AddPlayerState(*It); } } void AGameState::AddPlayerState(APlayerState* PlayerState) { if (!PlayerState->bIsInactive) { PlayerArray.AddUnique(PlayerState); } } ``` All of this happens on the server and the client instances of Player- and GameState! #### Functions​ A small function example I could provide you with would be keeping track of the score of two teams 'A' and 'B'. Let's say we have a CustomEvent which is called when a team scores. It passes a boolean so we know which team scored. We could also pass in a PlayerState, Team, or whatever you utilize to identify who scored. Later in the "Replication" chapter, you will read about the rule that only the server can (and should) replicate variables, so we make sure only he can call this event. The event is called from another class (for example a weapon that killed someone) and this should happen on the Server (always!), so we don't need an RPC here. ![Event that increments the score of Team A or Team B based on a boolean input.](../images/g_image-9.png) Since these variables and the GameState are replicated you can use these two variables and get them in any other class you need them. For example, to display them in a scoreboard widget. #### UE++ Examples​ To recreate this small example we need a bit more code, but despite the function itself the code needed to set up the replication is only needed once per class. ``` cpp // Header file of our AGameState class inside of the class declaration -------------------------------------------------------------------------------- // You need this included to get the replication working. #include "UnrealNetwork.h" // Replicated specifier used to mark this variable to replicate UPROPERTY(Replicated) int32 TeamAScore; UPROPERTY(Replicated) int32 TeamBScore; // Function to increase the score of a team void AddScore(bool bTeamAScored); ``` You will read more about this function in the Replication part! ``` cpp // CPP file of our AGameState child class -------------------------------------------------------------------------------- // This function is required through the replicated specifier in the UPROPERTY macro and is declared by it void ATestGameState::GetLifetimeReplicatedProps(TArray<FLifetimeProperty>& OutLifetimeProps) const { Super::GetLifetimeReplicatedProps(OutLifetimeProps); DOREPLIFETIME(ATestGameState, TeamAScore); DOREPLIFETIME(ATestGameState, TeamBScore); } ``` ``` cpp // CPP file of our AGameState child class -------------------------------------------------------------------------------- void ATestGameState::AddScore(bool bTeamAScored) { if (bTeamAScored) { TeamAScore++; } else { TeamBScore++; } } ```
from abc import abstractmethod import datetime from typing import Any, Iterable import uuid from enum import IntEnum from pydantic import BaseModel, ConfigDict from sqlalchemy import ( BigInteger, Column, DateTime, func, Integer, TypeDecorator, Select, select, ) from sqlalchemy.ext.declarative import as_declarative from sqlalchemy.orm import declared_attr, Mapped, mapped_column from summary_bot.utils.common import FilterType, camel_to_snake class_registry: dict = {} MIN_DATE_SQL_LABEL = "x_min_date" MAX_DATE_SQL_LABEL = "x_max_date" @as_declarative(class_registry=class_registry) class Base: @classmethod def table_prefix(cls) -> str: return "mats" @classmethod def get_table_name(cls, model_name: str): return f"{cls.table_prefix()}_{camel_to_snake(model_name)}" @classmethod def __generate_table_snake_name(cls): """StupidCAMelCase to stupid_ca_mel_case""" return camel_to_snake(cls.__name__) @declared_attr def __tablename__(cls) -> str: """this is a class method""" return cls.get_table_name(cls.__name__) @classmethod def filter_fields(cls) -> list[str]: return [] @classmethod def custom_field_comparison(cls) -> dict[str, type]: return {} @classmethod def order_fields(cls) -> list[str]: raise NotImplementedError @classmethod def default_order_fields(cls) -> list[str]: raise NotImplementedError def as_dict(self, *exclude_fields: str) -> dict[str, Any]: exclude_fields = list(exclude_fields) exclude_fields.append("_sa_instance_state") return { name: value for name, value in self.__dict__.items() if name not in exclude_fields } def as_tuple(self, *exclude_fields: str) -> tuple: return tuple(self.as_dict(*exclude_fields).values()) @classmethod def all_fields(cls): return {c.name for c in cls.__table__.columns} @classmethod def from_dict(cls, values: dict[str, any]): """Danger method! Values should be validated with model before call.""" fields = cls.all_fields() instance = cls() for field, value in values.items(): if field in fields: setattr(instance, field, value) return instance class BigIDMixin: """Provides id""" # no required index=True cause primary_key make index automatically # is Identity() required? id: Mapped[int] = mapped_column(BigInteger, primary_key=True) @classmethod def order_fields(cls) -> list[str]: return ["id"] @classmethod def default_order_fields(cls) -> list[str]: return ["desc_id"] class IDMMixin(BigIDMixin): id: Mapped[int] = mapped_column(Integer, primary_key=True) class UUIDMixin: id: Mapped[uuid.UUID] = mapped_column(primary_key=True, default=uuid.uuid4) class DateCreatedMixin: created_at: Mapped[datetime.datetime] = mapped_column( server_default=func.now() ) @classmethod def order_fields(cls) -> list[str]: return ["created_at"] @classmethod def default_order_fields(cls) -> list[str]: return ["desc_created_at"] class DateMixin(DateCreatedMixin): last_modified: Mapped[datetime.datetime] = mapped_column( server_default=func.now(), onupdate=func.now() ) @classmethod def order_fields(cls) -> list[str]: return ["created_at", "last_modified"] class BigIdCreatedDateBaseMixin(BigIDMixin, DateCreatedMixin): @classmethod def order_fields(cls) -> list[str]: return BigIDMixin.order_fields() + DateCreatedMixin.order_fields() @classmethod def default_order_fields(cls) -> list[str]: return ["desc_id"] class BigIdDateBaseMixin(BigIDMixin, DateMixin): @classmethod def order_fields(cls) -> list[str]: return BigIDMixin.order_fields() + DateMixin.order_fields() @classmethod def default_order_fields(cls) -> list[str]: return ["desc_id"] class IdDateCreatedBaseMixin(DateCreatedMixin, IDMMixin): @classmethod def order_fields(cls) -> list[str]: return DateCreatedMixin.order_fields() + IDMMixin.order_fields() class IdDateBaseMixin(DateMixin, IDMMixin): @classmethod def order_fields(cls) -> list[str]: return DateMixin.order_fields() + IDMMixin.order_fields() class UUIDDateCreatedMixin(UUIDMixin, DateCreatedMixin): pass class UUIDDateBaseMixin(UUIDMixin, DateMixin): pass class BoundDbModel: __abstract__ = True @classmethod @abstractmethod def bound_date_column(cls) -> Column: raise NotImplementedError() @classmethod def date_bounds( cls, eq_filters: FilterType | list[bool], **kwargs ) -> "Select": date_column = cls.bound_date_column() return select( func.min(date_column).label(MIN_DATE_SQL_LABEL), func.max(date_column).label(MAX_DATE_SQL_LABEL), ).filter( *eq_filters if isinstance(eq_filters, Iterable) else eq_filters ) def id_column(model_name_id: str) -> str: """jus a simple function that converts ModelName to model_name and join the result with a column name after dot in model_name_id""" model_name, *id_columns = model_name_id.split(".") if not id_columns or len(id_columns) > 1: raise ValueError( 'Incorrect model_name_id value, required "ModelName.id"' ) return ".".join([Base.get_table_name(model_name)] + id_columns) # custom column types class IntEnumDecorator(type): @staticmethod def process_bind_param(obj, value: IntEnum, dialect): if value is not None: return value.value @staticmethod def process_result_value(obj, value: Integer, dialect, enumcls): if value is not None: return enumcls(value) def __new__(cls, clsname, superclasses, attributedict, enumcls): clsname = clsname.replace("Enum", "") process_result_value = ( lambda obj, value, dialect: cls.process_result_value( obj, value, dialect, enumcls ) ) superclasses = (*superclasses, TypeDecorator) attributedict.update( impl=Integer, enumcls=enumcls, process_bind_param=cls.process_bind_param, process_result_value=process_result_value, ) return type.__new__(cls, clsname, superclasses, attributedict) class TMP(BaseModel): model_config = ConfigDict(from_attributes=True) t: datetime.datetime class UnixTimestamp(TypeDecorator): impl = Integer def process_bind_param(self, value: datetime.datetime, dialect): match value: case datetime.datetime(): return value.timestamp() case str(): return int(TMP(t=value).t.timestamp()) case _: return value @property def python_type(self): return datetime.datetime # TODO: Mb change to small int class MyDateTime(TypeDecorator): impl = DateTime def process_bind_param(self, value, dialect): match value: case datetime.datetime(): return value.replace(tzinfo=None) case str(): return TMP(t=value).t case _: return value # TODO: CHANGE @property def python_type(self): return datetime.datetime
package com.phonecommerce.phonestore.controller; import com.phonecommerce.phonestore.dto.PhoneDTO; import com.phonecommerce.phonestore.service.PhoneService; import io.swagger.annotations.Api; import io.swagger.annotations.ApiOperation; import io.swagger.annotations.ApiParam; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.*; import java.util.List; @RestController @RequestMapping("/api/phones") @Api(tags = "Phone Management") public class PhoneController { private final PhoneService phoneService; @Autowired public PhoneController(PhoneService phoneService) { this.phoneService = phoneService; } @GetMapping @ApiOperation(value = "Get all phones", notes = "Retrieve a list of all phones") public ResponseEntity<List<PhoneDTO>> getAllPhones() { List<PhoneDTO> phones = phoneService.getAllPhones(); return new ResponseEntity<>(phones, HttpStatus.OK); } @GetMapping("/{id}") @ApiOperation(value = "Get phone by ID", notes = "Retrieve a phone by its ID") public ResponseEntity<PhoneDTO> getPhoneById( @ApiParam(value = "Phone ID", required = true) @PathVariable Long id) { PhoneDTO phone = phoneService.getPhoneById(id); return new ResponseEntity<>(phone, HttpStatus.OK); } @PostMapping @ApiOperation(value = "Create a new phone", notes = "Add a new phone to the system") public ResponseEntity<PhoneDTO> createPhone( @ApiParam(value = "Phone data", required = true) @RequestBody PhoneDTO phoneDTO) { PhoneDTO createdPhone = phoneService.createPhone(phoneDTO); return new ResponseEntity<>(createdPhone, HttpStatus.CREATED); } @PutMapping("/{id}") @ApiOperation(value = "Update a phone", notes = "Modify an existing phone's information") public ResponseEntity<PhoneDTO> updatePhone( @ApiParam(value = "Phone ID", required = true) @PathVariable Long id, @ApiParam(value = "Updated phone data", required = true) @RequestBody PhoneDTO phoneDTO) { PhoneDTO updatedPhone = phoneService.updatePhone(id, phoneDTO); return new ResponseEntity<>(updatedPhone, HttpStatus.OK); } @DeleteMapping("/{id}") @ApiOperation(value = "Delete a phone", notes = "Remove a phone from the system") public ResponseEntity<Void> deletePhone( @ApiParam(value = "Phone ID", required = true) @PathVariable Long id) { phoneService.deletePhone(id); return new ResponseEntity<>(HttpStatus.NO_CONTENT); } }
/** Programacion orientada a objetos - seccion 10 * Luis Francisco Padilla Juárez - 23663 * Ejercicio 1, Overloading * 13-08-2023 */ import java.util.ArrayList; import java.util.Scanner; public class MU { public static void main(String[] args){ //Intancia de sedes Sede sede1, sede2, sede3; sede1 = new Sede("Sede Norte"); sede2 = new Sede("Sede Sur"); sede3 = new Sede("Sede Central"); //creacion de array list de sedes Scanner scanner = new Scanner(System.in); ArrayList<Sede> Sedelist = new ArrayList<Sede>(); // agregar sedes al array list Sedelist.add(sede1); Sedelist.add(sede2); Sedelist.add(sede3); //Datos de prueba del programa (sede2.getExamList()).add(new Exam("Matematicas", new Estudiante("Billy", "Joel", 231433241, 6, 4, 1964, "[email protected]", "Norte"))); (sede2.getExamList()).add(new Exam("Ingles", new Estudiante("John", "Diaz", 534653456, 7, 4, 1964, "[email protected]", "Norte"))); (sede2.getExamList()).add(new Exam("Lengauje", new Estudiante("Gabriel", "Bran", 974747455, 6, 4, 1964, "[email protected]", "Norte"))); (sede1.getExamList()).add(new Exam("Quimica", new Estudiante("Iris", "Ayala", 958498758, 6, 4, 1964, "[email protected]", "Norte"))); (sede1.getExamList()).add(new Exam("Matematicas", new Estudiante("Anggie", "Quezada", 98937434, 6, 4, 1964, "[email protected]", "Norte"))); (sede1.getExamList()).add(new Exam("Biologia", new Estudiante("David", "Dom", 7547389, 6, 4, 1964, "[email protected]", "Norte"))); // variables de control boolean run = true; String inputString = ""; int inputOption = 0; // inicio del ciclo while (run == true){ //menu System.out.println("===== Monsters University ====="); System.out.println("1. Ingresar nuevo estudiante"); System.out.println("2. Ingresar por csv (opcion en desarrollo)"); System.out.println("3. Ingresar notas"); System.out.println("4. Mostrar estadísticas"); System.out.println("5. Agregar nueva sede"); System.out.println("6. Salir"); inputOption = scanner.nextInt(); //catcher del enter String catcher = scanner.nextLine(); if (inputOption == 1) { System.out.println(catcher); //recorrer array de sede para mostrar opciones for (int count = 0; count<Sedelist.size(); count++) { System.out.println((count+1) + ". Sede " + Sedelist.get(count).getNameSede()); } // Indicar cual es la sede en la que se realiza el examen System.out.println("Ingrese el numero de sede donde realiza el examen: "); inputOption = scanner.nextInt(); //no hay progra defensiva :( // atributos de un objeto estudiante System.out.println("Ingrese el tipo de examen: "); inputString = scanner.nextLine(); System.out.println("Ingrese su Nombre: "); String nombre = scanner.nextLine(); System.out.println("Ingrese su Apellido: "); String Apellido = scanner.nextLine(); System.out.println("Ingrese su CUI: "); long CUI = scanner.nextLong(); System.out.println("Ingrese su Mes de Nacimiento: "); int mes = scanner.nextInt(); System.out.println("Ingrese su Dia de Nacimiento: "); int dia = scanner.nextInt(); System.out.println("Ingrese su Año de Nacimiento: "); int año = scanner.nextInt(); System.out.println("Ingrese su Correo electronico: "); String correo = scanner.nextLine(); System.out.println("Ingrese el campus en el que se inscribira: "); String campus = scanner.nextLine(); Sedelist.get(inputOption-1).getExamList().add(new Exam(inputString, new Estudiante(nombre, Apellido, CUI, mes, dia, año, correo, campus))); } else if (inputOption == 2) { //segun las instrucciones no se debe de elaborar pero deje la opcion en el menu System.out.println("Feature in development, come back soon ;)"); } else if (inputOption == 3) { System.out.println(catcher); //print ctacher, para insertar un enter for (int i = 0; i < Sedelist.size(); i++){ //recorrido de sedes System.out.println("Estudiantes Sede: " + Sedelist.get(i).getNameSede()); Sede sede = Sedelist.get(i); ArrayList<Exam> exlist = sede.getExamList(); for (int j = 0; j < exlist.size(); j++){ //recorrido de examenes/estudiantes por cada sede Exam ex = exlist.get(j); Estudiante stud = ex.getUsuario(); System.out.println(stud.getNombre()); System.out.println("Examen de: " + ex.getTipo()); System.out.println("Ingresar nota: "); int nota = scanner.nextInt(); ex.setNota(nota); } } } else if (inputOption == 4) { for (int i = 0; i < Sedelist.size(); i++){ //recorrido de sedes para calculos estadisticos por sede Sede sede = Sedelist.get(i); System.out.println("Media: " + sede.mean()); System.out.println("Mediana: " + sede.median()); System.out.println("Moda: "+sede.mode()); System.out.println("Desviacion estandar: " + sede.estDesv()); System.out.println("Numero de estudiantes: " + sede.Registstudents()); System.out.println("Nota mas baja: " + sede.LowestByExamn()); System.out.println("Nota mas alta: " + sede.HighestByExamn()); } } else if (inputOption == 5) { //agregar una nueva sede al array list System.out.println(catcher); System.out.println("Ingrese el nombre de la Sede: "); inputString = scanner.nextLine(); Sedelist.add(new Sede(inputString)); } else if (inputOption == 6) { //salir run = false; } else{ System.out.println("Igrese una opcion valida"); } } scanner.close(); } }
<template> <v-container> <v-row class=""> <v-col cols="12" sm="12" md="12"> <v-form v-model="valid"> <v-container> <v-row> <v-col cols="12" md="3" > <v-text-field v-model="firstname" :rules="nameRules" :counter="10" label="Nombre" required ></v-text-field> </v-col> <v-col cols="12" md="3" > <v-text-field v-model="lastName1" :rules="nameRules" :counter="10" label="Primer Apellido" required ></v-text-field> </v-col> <v-col cols="12" md="3" > <v-text-field v-model="lastName2" :counter="10" label="Segundo Apellido" required ></v-text-field> </v-col> <v-col cols="12" md="3" > <v-menu ref="menu" v-model="menu" :close-on-content-click="false" :return-value.sync="date" transition="scale-transition" offset-y min-width="290px" > <template v-slot:activator="{ on }"> <v-text-field v-model="date" label="Fecha de Nacimiento" prepend-icon="event" readonly v-on="on" ></v-text-field> </template> <v-date-picker v-model="date" no-title scrollable> <v-spacer></v-spacer> <v-btn text color="primary" @click="menu = false">Cancel</v-btn> <v-btn text color="primary" @click="$refs.menu.save(date)">OK</v-btn> </v-date-picker> </v-menu> </v-col> </v-row> </v-container> </v-form> <div class="my-2"> <v-btn small color="primary" @click="numeroMaestro" :disabled="!valid">Buscar Número Mestro</v-btn> </div> <div v-if="resultadoNumeroMaestro.length"> <v-divider/> <v-chip class="ma-2" color="green" text-color="white" v-for="(numero, index) in resultadoNumeros" :key="index" > <v-avatar left class="green darken-4" > {{numero.VALOR}} </v-avatar> {{numero.TITULO}} </v-chip> <h1>Lectura numerológica del nombre</h1> <h2>NUMERO {{numero_nombre}}</h2> <p v-html="resultadoNumeroNombre[0].DESCRIPCION"></p> <h1>Lectura número Hereditario</h1> <h2>NUMERO {{numero_hereditario}}</h2> <p v-html="resultadoNumeroHereditario[0].DESCRIPCION"></p> <h1>Número Maestro</h1> <h2>NUMERO {{resultadoNumeroMaestro[0].VALOR}} - {{resultadoNumeroMaestro[0].TITULO}}</h2></v-expansion-panel-header> <h3>INTRODUCCION</h3> <p v-html="resultadoNumeroMaestro[0].DESCRIPCION.INTRODUCCION"></p> <h3>POSITIVO</h3> <p v-html="resultadoNumeroMaestro[0].DESCRIPCION.POSITIVO"></p> <h3>NEGATIVO</h3> <p v-html="resultadoNumeroMaestro[0].DESCRIPCION.NEGATIVO"></p> <h1>Número de Alma</h1> <h2>NÚMERO {{numero_alma}}</h2> <p v-html="resultadoNumeroAlma[0].DESCRIPCION"></p> <h1>Número de Personalidad</h1> <h2>NÚMERO {{numero_personalidad}}</h2> <p v-html="resultadoNumeroPersonalidad[0].DESCRIPCION"></p> </div> </v-col> </v-row> </v-container> </template> <script> import VueTrix from "vue-trix"; export default { name: 'Inicio', components: { VueTrix }, data: () => ({ disabled: true, valid: false, firstname: '', lastname: '', nameRules: [ v => !!v || 'Name is required', v => v.length <= 10 || 'Name must be less than 10 characters', ], email: '', emailRules: [ v => !!v || 'E-mail is required', v => /.+@.+/.test(v) || 'E-mail must be valid', ], editorContent: '', date: new Date().toISOString().substr(0, 10), name: '', lastName1: '', lastName2: '', menu: false, modal: false, menu2: false, resultadoNumeros: [], resultadoNumeroNombre: [], resultadoNumeroHereditario: [], resultadoNumeroMaestro: [], resultadoNumeroExpresion: [], resultadoNumeroAlma: [], resultadoNumeroPersonalidad: [], resultadoMisionCosmica: [], resultadoNumeroPotencial: [], resultadoNumeroIniciacionEspitirual: [], numero_nombre: 0, numero_hereditario: 0, numero_fuerza: 0, numero_maestro: 0, numero_expresion: 0, numero_alma: 0, numero_personalidad: 0, numero_cosmico: 0, numeroMestroNoR: 0, numeroAlmaNoR: 0, numeroPersonalidadNoR: 0, numeroExpresionNoR: 0 }), computed: { }, methods: { numerologiaNombre(){ let nombre = this.firstname.toUpperCase().replace(/\s+/g, ''); let aCalcular = 0; let num = ''; for(let char in nombre){ aCalcular += this.$store.state.descripciones.CHAR_MATRIX.find( x=> { return x.CHARS.find(y => y === nombre[char] ) }).VALOR } aCalcular = this.reduccion(aCalcular) this.numero_nombre = aCalcular this.resultadoNumeroNombre.push(this.$store.state.descripciones.NUMERO_NOMBRE.find(x => x.VALOR == this.numero_nombre)); this.resultadoNumeros.push({ 'VALOR': this.numero_nombre, "TITULO": 'Numerología Nombre'}); }, numeroMaestro(){ let dateFormat = this.$moment(this.date).format('YYYYMMDD'); let calcFuerza = this.$moment(this.date).format('MMDD'); let num = ''; this.numero_fuerza = this.reduccion(calcFuerza) for(let element in dateFormat){ this.numero_maestro += parseInt(dateFormat[element]) } this.numeroMestroNoR = this.numero_maestro if(this.numero_maestro >= 10 ){ let num = this.numero_maestro.toString() this.numero_maestro = parseInt(num[0]) + parseInt(num[1]) } this.numeroExpresion(); this.numerologiaNombre(); this.resultadoNumeroMaestro.push(this.$store.state.descripciones.NUMERO_MAESTRO.find(x => x.VALOR == this.numero_maestro)); this.resultadoNumeros.push({ 'VALOR': this.numero_maestro, "TITULO": 'Número Maestro'}); }, numeroExpresion(){ let nombre = this.firstname.concat(this.lastName1).concat(this.lastName2).toUpperCase().replace(/\s+/g, ''); let aCalcular = 0; let num = ''; for(let char in nombre){ aCalcular += this.$store.state.descripciones.CHAR_MATRIX.find( x=> { return x.CHARS.find(y => y === nombre[char] ) }).VALOR } this.numeroExpresionNoR = aCalcular aCalcular = this.reduccion(aCalcular) this.numero_expresion = aCalcular this.resultadoNumeros.push({ 'VALOR': this.numero_expresion, "TITULO": 'Número Expresión'}); this.numeroAlma() }, numeroAlma(){ let nombre = this.firstname.toUpperCase().replace(/\s+/g, ''); let aCalcular = 0; let num = ''; for(let char in nombre){ let busca = ['A','E','I','O','U'].find(x => x === nombre[char]) if(busca){ aCalcular += this.$store.state.descripciones.CHAR_MATRIX.find( y=> { return y.CHARS.find(z => z === busca ) }).VALOR } } this.numeroAlmaNoR = aCalcular aCalcular = this.reduccion(aCalcular) this.numero_alma = aCalcular this.resultadoNumeroAlma.push(this.$store.state.descripciones.NUMERO_ALMA.find(x => x.VALOR === this.numero_alma)) this.numeroPersonalidad() this.resultadoNumeros.push({ 'VALOR': this.numero_alma, "TITULO": 'Número Alma'}); }, numeroPersonalidad(){ let nombre = this.firstname.toUpperCase().replace(/\s+/g, ''); let aCalcular = 0; let num = ''; for(let char in nombre){ let busca = ['A','E','I','O','U'].find(x => x === nombre[char]) if(!busca){ aCalcular += this.$store.state.descripciones.CHAR_MATRIX.find( y=> { return y.CHARS.find(z => z === nombre[char] ) }).VALOR } } this.numeroPersonalidadNoR = aCalcular aCalcular = this.reduccion(aCalcular) this.numero_personalidad = aCalcular this.resultadoNumeroPersonalidad.push(this.$store.state.descripciones.NUMERO_PERSONALIDAD.find(x => x.VALOR === this.numero_personalidad)) this.numeroMisionCosmica() this.resultadoNumeros.push({ 'VALOR': this.numero_personalidad, "TITULO": 'Número Personalidad'}); }, numeroMisionCosmica(){ let aCalcular = this.numeroAlmaNoR + this.numeroExpresionNoR; let num = ''; aCalcular = this.reduccion(aCalcular) this.numero_cosmico = aCalcular this.numeroPotencial() this.resultadoNumeros.push({ 'VALOR': this.numero_cosmico, "TITULO": 'Misión Cósmica'}); }, numeroPotencial(){ console.log(`Número Potencial: ${this.numero_maestro+this.numero_expresion}`) this.numeroIniciacionEspiritual() }, numeroIniciacionEspiritual(){ let day = this.$moment(this.date).format('DD'); let aCalcular = this.numero_alma+this.numero_expresion+this.numero_maestro+day; let num = ''; aCalcular = this.reduccion(aCalcular) this.numeroHereditario() }, numeroHereditario(){ let nombre = this.lastName1.concat(this.lastName2).toUpperCase().replace(/\s+/g, ''); let aCalcular = 0; let num = ''; for(let char in nombre){ aCalcular += this.$store.state.descripciones.CHAR_MATRIX.find( x=> { return x.CHARS.find(y => y === nombre[char] ) }).VALOR } aCalcular = this.reduccion(aCalcular) this.numero_hereditario = aCalcular this.resultadoNumeroHereditario.push(this.$store.state.descripciones.NUMERO_HEREDITARIO.find(x => x.VALOR === this.numero_hereditario)) this.resultadoNumeros.push({ 'VALOR': this.numero_hereditario, "TITULO": 'NúmeroHereditario'}); }, reduccion(aCalcular){ let num =''; while(aCalcular>=10){ num = aCalcular.toString() if(aCalcular > 100 ){ aCalcular = parseInt(num[0]) + parseInt(num[1]) + parseInt(num[1]) }else if(aCalcular >= 10){ aCalcular = parseInt(num[0]) + parseInt(num[1]) }else if(aCalcular <= 10){ aCalcular = parseInt(num[0]) + parseInt(num[1]) } } return aCalcular } } } </script>
# 拯救世界的 5 种 Rails 迁移模式 > 原文:<https://dev.to/jasterix/5-rails-migrations-to-save-the-day-kpe> 提前道歉,因为这篇文章的格式有点古怪。最初的目标是有一个编号的列表,但是没有成功。 然而,每个迁移都建立在前面的基础上,所以我希望它能帮助您理解设置 Rails 迁移的流程。 创建新的模型用户 * rails g 模型用户:姓名:城市 ``` class CreateUsers < ActiveRecord::Migration[5.2] def change create_table :users do |t| t.string :name t.string :city t.timestamps end end end ``` Enter fullscreen mode Exit fullscreen mode 将用户表重命名为帐户 * rails g 迁移重命名用户帐户 ``` class RenameAccountsToTwitterAccounts < ActiveRecord::Migration[5.2] def change rename_table :users, :accounts end end ``` Enter fullscreen mode Exit fullscreen mode 向帐户表中添加新列 * rails g 迁移 AddEmailToAccounts 电子邮件:string ``` class ChangeAccountsTable < ActiveRecord::Migration[5.0] def change add_column :accounts, :email, :string end end ``` Enter fullscreen mode Exit fullscreen mode 从数据库中删除帐户表 * rails g 迁移卸载 ``` class DropAccounts < ActiveRecord::Migration[5.2] def change drop_table :accounts end end ``` Enter fullscreen mode Exit fullscreen mode 撤消您最近的更改 * rails db:回滚
- day: Mon 16/01 contents: Introduction to the course; administrative details; algorithms for integer multiplication - what constitutes a good algorithm? slides: https://drive.google.com/file/d/1F21tBuUGVUf62bTXjWu6lp8M2T9ye65P/view?usp=share_link notes: references: - Section 0.2 - Erickson misc: <a href="https://drive.google.com/file/d/1znDMqRm3Xka-TBif1dNpt6NIrZwudtNd/view?usp=share_link">PS0</a> released - day: Tue 17/01 contents: Stable marriage problem; Gale-Shapley algorithm and examples slides: https://drive.google.com/file/d/1F21tBuUGVUf62bTXjWu6lp8M2T9ye65P/view?usp=share_link notes: references: - Section 1.1 - [KT] misc: - day: Wed 18/01 contents: Gale-Shapley algorithm - proof of correctness; properties of the solution and proof of optimality slides: https://drive.google.com/file/d/1F21tBuUGVUf62bTXjWu6lp8M2T9ye65P/view?usp=share_link notes: references: - Section 1.1 - [KT] misc: - day: "Fri 20/01" tutorial: "Based on Problem set 0" contents: slides: notes: references: misc: - day: Mon 23/01 contents: Recall of asymptotic analysis; Divide-and-conquer - Karatsuba's algorithm, recurrence relations, recurrence trees, master theorem slides: https://drive.google.com/file/d/1XD8684cRD8UmHnfDsMClkFV2he4Mv6LS/view?usp=share_link notes: references: - Section 1.9 - Erickson - Section 2.1, 2.2 - [DPV] - Chapter 3 - [CLRS] (asymptotic notation) - Section 4.6 - [CLRS] (for a proof of the master theorem) misc: - <a href="https://drive.google.com/file/d/1JFAQMWRS4YHyZLUPQlZHIraohbeFLNWZ/view?usp=share_link">PS1</a> released - day: Tue 24/01 contents: Order statistics - finding the \(k^{th}\) smallest element; median-of-medians - recursive solution, analyzing the recurrence using recursion trees slides: https://drive.google.com/file/d/1XD8684cRD8UmHnfDsMClkFV2he4Mv6LS/view?usp=share_link notes: references: - Section 1.8 - Erickson misc: - day: Wed 25/01 contents: Convolution of vectors; equivalence with polynomial multiplication; evaluating polynomials on mulitple points; FFT algorithm slides: https://drive.google.com/file/d/1XD8684cRD8UmHnfDsMClkFV2he4Mv6LS/view?usp=share_link notes: references: - Section 2.6 - [DPV] - <a href="http://jeffe.cs.illinois.edu/teaching/algorithms/notes/A-fft.pdf">FFT notes</a> - Erickson misc: - day: Mon 30/01 contents: FFT algorithm (contd.); Closest pair of points in 2D slides: https://drive.google.com/file/d/1XD8684cRD8UmHnfDsMClkFV2he4Mv6LS/view?usp=share_link notes: references: - Section 2.6 - [DPV] - <a href="http://jeffe.cs.illinois.edu/teaching/algorithms/notes/A-fft.pdf">FFT notes</a> - Erickson - Section 5.4 - [KT] misc: - <a href="https://drive.google.com/file/d/1W0KItGCZgYIrff1yNkLzR-MXyp3FLWPs/view?usp=share_link">PS2</a> released - day: Tue 31/01 contents: Basic graph algorithms; adjacency matrices and lists; graph traversals - DFS slides: https://drive.google.com/file/d/11qcqp4d1mp421IzMoWrJLGe_9fFy1J_0/view?usp=share_link notes: references: - Sections 3.1, 3.2 - [DPV] - Chapter 5 - Erickson misc: - day: "Wed 01/02" tutorial: "Discussion of Problem Sets 1 and 2" contents: slides: notes: references: misc: - day: Fri 03/02 miniquiz: Based on material covered in Problem sets 0, 1, 2 contents: slides: notes: references: misc: - day: Mon 06/02 contents: BFS; finding connected components in graphs; digraphs - classification of edges slides: https://drive.google.com/file/d/11qcqp4d1mp421IzMoWrJLGe_9fFy1J_0/view?usp=share_link notes: references: - Sections 3.2, 3.3 - [DPV] - Sections 6.1, 6.2 - Erickson misc: <a href="https://drive.google.com/file/d/1TD_HcZRNBKeX0ZoaRnV6jmdh0VC87jk1/view?usp=share_link">PS3</a> released - day: Tue 07/02 contents: DFS with clocks - classification of edges; Topological ordering of DAGs slides: https://drive.google.com/file/d/11qcqp4d1mp421IzMoWrJLGe_9fFy1J_0/view?usp=share_link notes: references: - Section 3.3 - [DPV] - Section 6.3 - Erickson misc: - day: Wed 08/02 contents: Digraphs and their strongly connected components; Finding and labelling the strongly connected components of a digraph slides: https://drive.google.com/file/d/11qcqp4d1mp421IzMoWrJLGe_9fFy1J_0/view?usp=share_link notes: references: - Section 3.4 - [DPV] - Sections 6.5, 6.6 - Erickson misc: - day: Fri 10/02 tutorial: Discussion of Problem set 3 contents: slides: notes: references: misc: - day: Mon 13/02 contents: Finding and labelling strongly connected components - Kosaraju-Sharir algorithm; Shortest paths in graphs - BFS slides: https://drive.google.com/file/d/11qcqp4d1mp421IzMoWrJLGe_9fFy1J_0/view?usp=share_link notes: references: - Sections 3.4,4.2 - [DPV] - Sections 6.6,8.4 - Erickson misc: <a href="https://drive.google.com/file/d/1OCOD_QA-Q1G8etqOqVk8d8erqgkXF4lZ/view?usp=share_link">PS4</a> released - day: Tue 14/02 contents: Shortest path in unweighed graphs - BFS (contd); Shortest paths in DAGs slides: https://drive.google.com/file/d/11qcqp4d1mp421IzMoWrJLGe_9fFy1J_0/view?usp=share_link notes: references: - Sections 4.2,4.7 - [DPV] - Sections 8.4,8.5 - Erickson misc: - day: Wed 15/02 contents: Shortest path in graphs - Dijkstra's algorithm slides: https://drive.google.com/file/d/11qcqp4d1mp421IzMoWrJLGe_9fFy1J_0/view?usp=share_link notes: references: - Section 4.4 - [KT] - Section 4.4 - [DPV] - Section 8.6 - Erickson misc: - day: Fri 17/02 tutorial: Discussion of Problem set 4 contents: slides: notes: references: misc: - day: Mon 20/02 contents: Shortest path in graphs - Dijkstra's algorithm (contd), Bellman-Ford algorithm slides: https://drive.google.com/file/d/11qcqp4d1mp421IzMoWrJLGe_9fFy1J_0/view?usp=share_link notes: references: - Section 4.4 - [KT] - Section 4.4 - [DPV] - Sections 8.6,8.7 - Erickson misc: - day: Tue 21/02 quiz: Based on material covered till Mon Feb 13 contents: slides: notes: references: misc: - day: Wed 22/02 contents: Bellman-Ford algorithm (contd) slides: notes: https://drive.google.com/file/d/1GijCXkdgW9yaUpDxyZRUamYrBXRw-c9h/view?usp=share_link references: - Section 8.7 - Erickson misc: - day: Fri 24/02 contents: Greedy algorithms - interval scheduling slides: notes: https://drive.google.com/file/d/1R_JkHFORZd8pC-kamwWCGrJE-nC6zfNr/view?usp=share_link references: - Section 4.1 - [KT] misc: - day: Mon 27/02 contents: Greedy algorithms - scheduling jobs to minimize delays; exchange arguments slides: notes: references: - Section 4.2 - [KT] misc: <a href="https://drive.google.com/file/d/1kv1oyNQYgl4QGbUDaRdR3pwQcSQKFtC4/view?usp=share_link">PS5</a> released - day: Tue 28/02 contents: Greedy algorithms - scheduling jobs to minimize delays; exchange arguments; greedy vertex cover slides: notes: https://drive.google.com/file/d/1xwPrzIwwzLPCK-ZsbeKch2cC1sTXiAM7/view?usp=share_link references: - Section 4.2 - [KT] misc: - day: Wed 01/03 contents: Huffman coding - optimal prefix codes and binary trees slides: notes: https://drive.google.com/file/d/17rszgMvEOe3DTxtTrg_jhfmP63l722wn/view?usp=share_link references: - Section 4.8 - [KT] misc: - day: Fri 03/03 tutorial: Discussion of Problem set 5 contents: slides: notes: references: misc: - day: Mon 06/03 contents: Huffman coding - algorithm and proof of correctness slides: notes: https://drive.google.com/file/d/19Xp5YVZl7d724ZWLBUKi2dCiKy56PzBQ/view?usp=share_link references: - Section 4.8 - [KT] misc: <a href="https://drive.google.com/file/d/1BiKZ8NIKwbXI6sO5MSf_NFB8qNvPRY2V/view?usp=share_link">PS6</a> released - day: Tue 07/03 contents: Huffman coding - implementation details; Minimum spanning trees - cut property slides: notes: https://drive.google.com/file/d/1g212yMOZCNVeY8ouKM-WSsPUY-BxzjbH/view?usp=share_link references: - Sections 4.5, 4.8 - [KT] - Section 7.1 - Erickson misc: - day: Fri 10/03 miniquiz: Based on Problem sets 5 and 6 contents: slides: notes: references: misc: - day: Mon 13/03 contents: Minimum spanning trees - proof of the cut property; Boruvka's algorithm slides: notes: https://drive.google.com/file/d/1cZ0WzWV0eMOWZrmvpLFdog7Kf3dA6M2u/view?usp=share_link references: - Sections 7.2, 7.3 - Erickson misc: <a href="https://drive.google.com/file/d/1MvF2LhwqBJXjh2xrsU495Fz0gX3A9PI0/view?usp=share_link">PS7</a> released - day: Tue 14/03 contents: Prim's and Kruskal's algorithms - examples, implementation details, running time slides: notes: https://drive.google.com/file/d/1e1MdTBYlGwIWpaMq6aLKaqYLH-FKsm28/view?usp=share_link references: - Sections 7.4, 7.5 - Erickson misc: - day: Wed 15/03 contents: Kruskal's algorithm - amortized analysis; data structures for disjoint sets slides: notes: https://drive.google.com/file/d/1WLlWJuwj4YrcmSIuOhu1HDBcwV_3NzLH/view?usp=share_link references: - Section 7.5 - Erickson misc: - day: Fri 17/03 tutorial: Discussion of Problem set 7 contents: slides: notes: references: misc: - day: Tue 21/03 quiz: Based on material covered through Problems sets 5,6,7 contents: slides: notes: references: misc: - day: Fri 24/03 contents: Union-by-rank with path compression; Amortized analysis - accounting method slides: notes: https://drive.google.com/file/d/18Qi6M1bnAuRMxjx7GjxlT7zn6sabrhE7/view?usp=share_link references: - Section 5.1.4 - [DPV] misc: - day: Mon 27/03 contents: Union-by-rank with path compression - amortized analysis slides: notes: https://drive.google.com/file/d/1y-xnA6s5EkwdUEumzU1nS0gURQakKZiB/view?usp=share_link references: - Section 5.1.4 - [DPV] misc: - day: Tue 28/03 contents: Dynamic programming - text segmentation slides: notes: https://drive.google.com/file/d/1sn9aEyTr-BZMX2unUJrZicM5vx9AA4UL/view?usp=share_link references: - Sections 3.3, 3.4 - Erickson misc: - day: Wed 29/03 contents: Dynamic programming - text justification, edit distance slides: notes: https://drive.google.com/file/d/1GVh3DovQ_Mj6itUeAFl9WX1Z9W56oSzy/view?usp=share_link references: - class notes misc: <a href="https://drive.google.com/file/d/1vjvbEnHDtTyrgBfAZiAHUCr7_24Ik3pP/view?usp=share_link">PS8</a> released - day: Fri 31/03 tutorial: Discussion of Problem set 8 contents: slides: notes: references: misc: - day: Mon 03/04 contents: Dynamic programming - edit distance; saving space using divide-and-conquer slides: notes: https://drive.google.com/file/d/1E7gQo2f3DljzUSqvCoyksS_Vt19Dgd0Q/view?usp=share_link references: - Section 3.7 - Erickson - Sections 6.6, 6.7 - [KT] misc: - day: Wed 05/04 contents: Dynamic programming - edit distane (contd.); 0-1 Knapsack - pseudopolynomial-time algorithm slides: notes: https://drive.google.com/file/d/19snuWfstHntULkblCml8blP-scKElZ8h/view?usp=share_link references: - Sections 6.6, 6.7 - [KT] misc: Online lecture - video link on Zulip - day: Mon 10/04 contents: 0-1 Knapsack - pseudopolynomial-time algorithm (contd.); Dynamic programming on trees - independent sets slides: notes: https://drive.google.com/file/d/1AnCzEWsCKWIZZyI8jMgq0DR0ju2t-1iQ/view?usp=share_link references: - Section 3.10 - Erickson misc: - day: Tue 11/04 contents: All Pairs Shortest Paths (APSP) - Johnson's algorithm; Dynamic programming based algorithms slides: notes: https://drive.google.com/file/d/1ER-SBl5RJs2_Unf0jfSnfev3_m3-BLys/view?usp=share_link references: - Sections 9.4, 9.5, 9.6 - Erickson misc: - day: Wed 12/04 contents: Floyd-Warshall algorithm; APSP and matrix multiplication slides: notes: https://drive.google.com/file/d/1o8h2mZIZjyNYHKJo3cT2uHPDDl6pS5ur/view?usp=share_link references: - Sections 9.7, 9.8 - Erickson misc: - day: Mon 17/04 contents: APSP and matrix multiplication - Seidel's algorithm; Introduction to computational intractability slides: notes: https://drive.google.com/file/d/1whGubSYMS_dfLYTrjvFpscvy4klXQ7h-/view?usp=share_link references: - Section 4.4 - Anupam Gupta's <a href="https://drive.google.com/file/d/1qEJNzfoujYR3mwS9MiOz-dmZ99zvCos7/view?usp=share_link">lecture notes</a> - Seidel's <a href="https://drive.google.com/file/d/1PCLoJ_XXNeIo6smDab8rOn2yuCVREqMA/view?usp=share_link">paper</a> misc: <a href="https://drive.google.com/file/d/10Q6JH3qDt-a9s1RFM0Bj1kezwjEW7xfR/view?usp=share_link">PS9</a> released - day: Tue 18/04 contents: Introduction to intractability - P and NP; poly-time solving versus poly-time verification slides: notes: https://drive.google.com/file/d/1q-tGHOUH1-lqIlmTTSGxuqixj-oQj2xN/view?usp=share_link references: - Sections 34.1, 34.2 - [CLRS] - Sections 12.1, 12.2 - Erickson misc: - day: Wed 19/04 contents: Polynomial-time reductions - NP completeness, examples of reductions slides: notes: https://drive.google.com/file/d/1iQ4IL2PXEgHeAY2BxGxXzFq_TTuH_2B4/view?usp=share_link references: - Chapter 12 - Erickson misc: - day: Fri 21/04 miniquiz: Based on Problem set 8 contents: slides: notes: references: misc: - day: Mon 24/04 contents: NP-completeness - examples of reductions slides: notes: https://drive.google.com/file/d/1TQr5lM9eRAQby7oSuN6PFYtMfM71O8_I/view?usp=share_link references: - Chapter 12 - Erickson misc: <a href="https://drive.google.com/file/d/1MJyaz_w3VI5g3Qyk3n5XkGCtA89gu1hz/view?usp=share_link">PS10</a> released - day: Tue 25/04 contents: Beyond NP-completeness - brief overview; Wrap-up of the course slides: notes: references: misc: - day: Wed 26/04 miniquiz: Based on Problem set 9 contents: slides: notes: references: misc: # - day: Wed 04/08 # contents: Verifying polynomial identities; verifying matrix multiplication # slides: # notes: # references: # - MU - Chapter 2 # misc: # # - day: Thu 05/08 # tutorial: Prev week # contents: # slides: # notes: # references: # misc: # # - day: Fri 06/08 # contents: Concentration inequalities - Markov, Chebyshev and Chernoff # references: MU - Chapter 4 # # - day: Mon 09/08 # miniquiz: Based on Tutorial 1 # # - day: Wed 08/08 # contents: Balls and bins; Birthday problems # references: # - MU - Chapter 5 # # - day: Thur 09/08 # quiz: Material till concentration bounds # # - day: Fri 10/08 # contents: Hashing with chaining - analysis # references: # - MU - Chapter 5
import React from "react"; import "./InterviewerListItem"; import InterviewerListItem from "./InterviewerListItem"; import PropTypes from 'prop-types'; export default function InterviewerList(props){ return( <section className="interviewers"> <h4 className="interviewers__header text--light">Interviewer</h4> <ul className="interviewers__list"> {props.interviewers && props.interviewers.map(interviewer=> <InterviewerListItem key={interviewer.id} name={interviewer.name} avatar={interviewer.avatar} selected={interviewer.id===props.value} //setInterviewer={props.setInterviewer} setInterviewer={()=> props.onChange(interviewer.id)} /> )} </ul> </section> ) } InterviewerList.propTypes = { interviewers: PropTypes.array.isRequired };
final int screenWidth = 720, screenHeight = 480; PImage imgBg; int originX, originY; Crewmate crew1, crew2; void setup() { size(720, 480); originX = screenWidth / 2; originY = screenHeight / 2; imgBg = loadImage("bg.jpg"); PImage imgCyanCrew = loadImage("cyan_crew.png"), imgPurpleCrew = loadImage("purple_crew.png"); imageMode(CENTER); crew1 = new Crewmate(-50, 0, 50, 5, imgCyanCrew); crew2 = new Crewmate(50, 0, 50, 7, imgPurpleCrew); crew1.setLimits(originX, originY); crew2.setLimits(originX, originY); } void draw() { translate(originX, originY); background(0); image(imgBg, 0, 0, screenWidth, screenHeight); crew1.move(); crew2.move(); crew1.render(); crew2.render(); } void keyPressed() { if (key == CODED) { // special key if (keyCode == UP) { crew1.directions[0] = true; } else if (keyCode == DOWN) { crew1.directions[1] = true; } else if (keyCode == LEFT) { crew1.directions[2] = true; } if (keyCode == RIGHT) { crew1.directions[3] = true; } } else { // non-special key if (key == 'w') { // up crew2.directions[0] = true; } else if (key == 's') { // down crew2.directions[1] = true; } else if (key == 'a') { // left crew2.directions[2] = true; } else if (key == 'd') { // right crew2.directions[3] = true; } } } void keyReleased() { if (key == CODED) { // special key if (keyCode == UP) { crew1.directions[0] = false; } else if (keyCode == DOWN) { crew1.directions[1] = false; } else if (keyCode == LEFT) { crew1.directions[2] = false; } if (keyCode == RIGHT) { crew1.directions[3] = false; } } else { // non-special key if (key == 'w') { // up crew2.directions[0] = false; } else if (key == 's') { // down crew2.directions[1] = false; } else if (key == 'a') { // left crew2.directions[2] = false; } else if (key == 'd') { // right crew2.directions[3] = false; } } }
char data= 0; int ledPin = 9; // choose the pin for the LED int inputPin3 = 3; int inputPin2 = 2; // choose the input pin (for PIR sensor) int pirState = LOW; // we start, assuming no motion detected int val = 0; int val2 = 0; // variable for reading the pin status int Lightsensor=0; void setup() { pinMode(ledPin, OUTPUT); pinMode(inputPin2, INPUT); // declare sensor as input pinMode(inputPin3, INPUT); Serial.begin(9600); pinMode(9, OUTPUT); } void loop(){ BluetoothCode();// Bluetooth Phone code PirSensor();// Pir Sensor Code lightSensorcode(); //Calls Light Sensor function // MotionSensor(); } void lightSensorcode () { Lightsensor=analogRead(A5); //connect grayscale sensor to Analog 0 Serial.println(Lightsensor,DEC);//print the value to serial delay(1000); } void PirSensor() { val = digitalRead(inputPin2); // read input value if (val == HIGH) { // check if the input is HIGH digitalWrite(ledPin, HIGH); // turn LED ON if (pirState == LOW) { // we have just turned on Serial.println("Motion detected!"); // We only want to print on the output change, not state pirState = HIGH; } } else { digitalWrite(ledPin, LOW); // turn LED OFF if (pirState == HIGH){ // we have just turned of Serial.println("Motion ended!"); pirState = LOW; } } } /* void MotionSensor() { val = digitalRead(inputPin3); // read input value if (val == HIGH) { // check if the input is HIGH digitalWrite(ledPin, HIGH); // turn LED ON if (pirState == LOW) { // we have just turned on Serial.println("Motion detected!"); // We only want to print on the output change, not state pirState = HIGH; } } else { digitalWrite(ledPin, LOW); // turn LED OFF if (pirState == HIGH){ // we have just turned of Serial.println("Motion ended!"); // We only want to print on the output change, not state pirState = LOW; } } } */ void BluetoothCode() { if(Serial.available() > 0) // Send data only when you receive data: { data = Serial.read(); //Read the incoming data and store it into variable data Serial.println(data); //Print Value inside data in Serial monitor if(data == '1') //Checks whether value of data is equal to 1 digitalWrite(ledPin, HIGH); //If value is 1 then LED turns ON else if(data == '0') //Checks whether value of data is equal to 0 digitalWrite(ledPin, LOW); //If value is 0 then LED turns OFF } }
--- title: "Percentage Children suffering exactly two deprivation" output: html execute: echo: false warning: false message: false --- #### Khaman Singh - 22266466 - Assignment 2 - MT5000 ![Logo](logo.JPG){fig-align="right"} ![Child](child.JPG) ```{r} library(tidyverse) unicef_indicator_1<- read_csv("/cloud/project/unicef_indicator_1.csv") ``` ## World Map of Percentage Children suffering exactly two deprivation. Sub saharan African countries are most prone to children suffering from deprivation. ```{r} map_world <- map_data("world") map_Unicef1 <- full_join(map_world, unicef_indicator_1, by = c("region" = "country")) ggplot(data = map_Unicef1) + aes(x = long, y = lat, group = group, fill = obs_value) + geom_polygon() ``` ### Poverty in Children 1. Children suffering from two deprivation are likely to suffer from **physical** and **psychological** health problems. 2. They may experience difficulty in acquiring **adequate nutrition**, **shelter**, **education**, and access to **health** care services. 3. They are more likely to experience **social exclusion**, which can have a negative impact on their self-esteem and **emotional wellbeing**. 4. They may also have **poor academic** performance, increased risk of substance abuse, and increased risk of **criminal behavior**. ```{r} #| label: setup #| include: false library(tidyverse) unicef_indicator_1<- read_csv("/cloud/project/unicef_indicator_1.csv") ``` ## Bar Chart of Percentage Children suffering exactly two deprivation in Unicef Indicator 1. Year 2014 saw the highest observed values of sum of percentage of children suffering exactly two deprivation ```{r} unicef_by_year_new <- unicef_indicator_1 %>% group_by(time_period) %>% summarise(Sum = sum(obs_value)) ggplot(data = unicef_by_year_new) + aes(x = time_period, y = Sum, fill = Sum) + geom_col() + theme_linedraw() + theme_dark() + theme(text = element_text(size = 12)) + labs( x = "Time Period", y = "Sum of Obs Values", title = "Bar Graph" ) ``` ```{r} library(tidyverse) unicef_indicator_1<- read_csv("/cloud/project/unicef_indicator_1.csv") unicef_metadata<- read_csv("/cloud/project/unicef_metadata.csv") ``` # Scatter Plot of Children Suffering exactly two deprications Scatterplot Figure. ```{r} Unicef_filter1 <- filter(unicef_indicator_1, sex == "Total") Unicef_select1 <- Unicef_filter1 %>% select(country, time_period, obs_value, sex) Unicef_Metadata1 <- unicef_metadata %>% select(country, time_period = year, `GNI (current US$)`, `Life expectancy at birth, total (years)`, `Population, total`) table_manualfull_joined <- full_join(Unicef_select1, Unicef_Metadata1, by = c("time_period", "country")) ggplot(data = table_manualfull_joined) + aes(x = time_period, y = `Life expectancy at birth, total (years)`, colour = country) + geom_point() + geom_smooth(method = "lm") + theme(legend.position="none") ``` ## Focus on Uganda ![Uganda](uganda.JPG) ```{r} library(tidyverse) unicef_metadata<- read_csv("/cloud/project/unicef_metadata.csv") ``` # Line Graph Line Graph of children suffering from poverty ```{r} ggplot(data = unicef_metadata) + aes(x = year, y = `Life expectancy at birth, total (years)`, color = country) + geom_line() + labs( x = "Year ", y = "Life Expectancy", title = "Evolution of life expectancy" ) + guides(color ="none") ``` How Children suffering from Deprivation can be saved: - Provide Access to Education: Education is one of the most important ways to empower children and break the cycle of poverty and deprivation. Invest in educational infrastructure and initiatives that provide access to education for all children in the area. - Improve Nutrition and Health Care: Make sure children have access to nutritious food and health care services. Implement programs that provide free or subsidized meals, as well as promote health and nutrition education. - Provide Basic Needs: Ensure that children have access to basic needs such as clean water, sanitation, and shelter. Invest in resources that give children and families access to these basic needs. - Combat Exploitation: Ensure that children are not exploited by providing resources and services that protect them from exploitation and abuse. - Strengthen Families and Communities: Strengthen families and communities by investing in initiatives that provide access to resources, job opportunities, and community development. These initiatives can help break the cycle of poverty and deprivation. ## "Donate Now to Give Children a Brighter Future!" ![Donate](donate.JPG)
package com.craft.apps.countdowns.ui.util import android.content.Context import com.craft.apps.countdowns.core.model.Countdown import com.craft.apps.countdowns.core.ui.R import com.craft.apps.countdowns.util.daysUntilNow import com.craft.apps.countdowns.util.hoursUntilNow import com.craft.apps.countdowns.util.isAfterNow import com.craft.apps.countdowns.util.minutesUntilNow import com.craft.apps.countdowns.util.secondsUntilNow import kotlinx.datetime.Instant import kotlinx.datetime.LocalDateTime import kotlinx.datetime.TimeZone import kotlinx.datetime.toJavaLocalDateTime import kotlinx.datetime.toLocalDateTime import java.time.format.DateTimeFormatter import java.time.format.FormatStyle enum class CountdownDisplayStyle { /** * Change depending on the most significant duration * * e.g. 2 days, 11 hours, 3 minutes */ DYNAMIC, /** * Comically big. * * e.g. 468,000 seconds */ LEAST_SIGNIFICANT, /** * Display a duration only up to hours and minutes. */ SHORT_TERM, } /** * @param short If true, omit the label after the units (e.g. only "12 days" instead of "12 days until now") */ fun Countdown.getFormattedTimeLeft( context: Context, style: CountdownDisplayStyle, short: Boolean = false, ): String { // TODO: Finish me val instant = this.expiration val daysLeft = instant.daysUntilNow() if (daysLeft < 1) { val hoursLeft = instant.hoursUntilNow() if (hoursLeft < 1) { val minutesLeft = instant.minutesUntilNow() if (short) { context.getString(R.string.minutes_until_now_short, minutesLeft) } else { context.getString(R.string.minutes_until_now_long, minutesLeft) } } } val secondsLeft = instant.secondsUntilNow() return "" } fun Instant.toJavaLocal() = toLocalDateTime(TimeZone.currentSystemDefault()).toJavaLocalDateTime() fun Instant.formattedLongDate(): String = this.toJavaLocal().toLocalDate().format(DateTimeFormatter.ofLocalizedDate(FormatStyle.LONG)) fun Instant.formattedShortDate(): String = this.toJavaLocal().toLocalDate().format(DateTimeFormatter.ofLocalizedDate(FormatStyle.SHORT)) fun Instant.formattedShortTime(): String = this.toJavaLocal().toLocalTime().format(DateTimeFormatter.ofLocalizedTime(FormatStyle.SHORT)) fun LocalDateTime.formattedShortTime(): String = this.toJavaLocalDateTime().format(DateTimeFormatter.ofLocalizedTime(FormatStyle.SHORT)) // TODO: Remove year if the countdown is in the current year val Countdown.formattedExpirationDate: String get() = expiration.formattedLongDate() val Countdown.formattedExpirationTime: String get() = expiration.formattedShortTime() val Countdown.isExpired: Boolean get() = expiration.isAfterNow()
import React, { useEffect, useState } from 'react' import { DataContextProvider, type IDataContext } from './contexts/DataContext' import { BuildContextProvider, DEFAULT_BUILD_CONTEXT, type IBuildContext } from './contexts/BuildContext' import { SnackArea } from './components/SnackArea'; import { Link } from 'react-router-dom' import { BlockDescriptor } from './components/BlockDescriptor'; import { ControllerSelect } from './components/Controller'; import { WorldSelect } from './components/World'; import { ObservationSelector } from './components/Observation'; import { RewardEditor } from './components/RewardEditor'; import { StartSimulation } from './components/StartSimulation/StartSimulation'; const App: React.FC = () => { const [data, setData] = useState<IDataContext>({ worlds: [], controllers: []}); const [build, setBuild] = useState(DEFAULT_BUILD_CONTEXT); const newContextUpdate = (newContext: Partial<Omit<IBuildContext, 'updateContext'>>): IBuildContext => { const newValue = { ...build, ...newContext }; setBuild(newValue); return newValue; }; useEffect(() => { fetch('/api/baseInfo', { method: 'GET' }) .then(async (response) => await response.json() as IDataContext) .then((data) => { setData(data); }) .catch((error) => { console.error(error); }); }, []); return ( <main className='pt-16 mb-10 max-w-[1500px] w-full mx-auto px-4 md:px-8'> <DataContextProvider value={data}> <BuildContextProvider value={{ ...build, updateContext: newContextUpdate }}> <SnackArea /> <h1 className='text-3xl sm:text-5xl md:text-6xl lg:text-8xl uppercase font-[900] leading-tight'> &#47;&#47; Štart simulácie </h1> <p className='text-md md:text-xl text-white text-justify mt-6 sm:mt-12'> Vitaj v našom futbalovom neurónovom zážitku! Tu si môžeš odskúšať aký je to pocit trénovať neurónky na futbalovom ihrisku v jednoduchom a zábavno-prehľadnom prostredí. Len si vyber typ ovládača, jeden z našich pripravených futbalových svetov, pozorovania a metriky. Ak by ti nejaký pojem ušiel, ako lopta pri zlej prihrávke, stačí prejsť myšou nad daný element a nápoveda ti ho vysvetlí ako dobrý tréner. Viac informácií o tom, ako to celé funguje, nájdeš v <a href="WeBots-summary.pdf" target='_blank' className='text-webotsGreen'>tomto PDF</a>. </p> <Link to={'/rebricek'} className='text-lg font-[700] bg-[#032d53] px-12 py-3 uppercase mt-10 inline-block rounded-full'> Pozri si výsledky iných vytvorených agentov </Link> <BlockDescriptor title='Výber ovládača' description={` Tvoj vytvorený ovládač bude odoslaný na naše servery, kde sa začne trénovať, ako by mal hrať priamo na Camp Nou. Po natrénovaní budeš ohodnotený a zobrazíš sa v rebríčku, kde môžeš porovnať svoje taktické schopnosti s inými virtuálnymi trénermi futbalových géniov. Týmto spôsobom môžeš otestovať, či si tvoj ovládač zaslúžil zlatú loptu, alebo skôr výprask od kapitána.` } > <ControllerSelect /> </BlockDescriptor> <BlockDescriptor className='mt-10' title='Výber sveta' description={` Teraz prichádza zábavná časť - vyber si svet, v ktorom sa tvoji roboti pustia do divokého futbalového turnaja. Každý svet má svoj vlastný rebríček, takže sa môžeš pokúsiť o nastavenie simulácie viackrát a získať titul najväčšieho robotického futbalového majstra vo viacerých svetoch!` } > <WorldSelect /> </BlockDescriptor> <BlockDescriptor className='mt-20' title='Výber pozorovaní' description={` Pozorovania sú ako robotov denník plný dobrodružstiev na ihrisku. Predstavte si, že váš robot vraví: "Dnes som videl takú loptu! A ešte väčšiu bránku!" Na základe týchto zážitkov sa PPO agent bude učiť ako školák a s nadšením vyberať svoje ďalšie kroky, takže si vyberajte múdro - predsa len, kto by nechcel mať robota s pútavým denníkom?` } > <ObservationSelector /> </BlockDescriptor> <BlockDescriptor className='mt-20' title='Editovanie odmeňovacieho vzorca' description={` Kedže sa už pohybuješ v svete virtuálneho trénera futbalových robotov a dosahuješ úspechy na ihrisku, nemáš chuť ešte viac robotom vytrhovať drôty z hlavy? Výborná voľba! Ale pozor, bez správneho odmeňovania sa v tom stratíš rýchlejšie ako gól v záverečnej minúte. Prečo je odmeňovanie také dôležité? Pretože týmto spôsobom tvoj robot bude vedieť, kedy si zaslúži odmenu za strelené góly, kedy si získať bonusy za skvelú obranu a kedy si spraviť selfie so skupinkou roztleskávačiek, aby sa následne mohol pýšiť. Napíšeš si ho sice sám, ale neboj sa, nejde o kvantovú fyziku, je to iba Python. Tak sa pusti do toho a ukáž svetu, akým virtuálnym trénerom futbalových génií si! `} > <RewardEditor /> </BlockDescriptor> <StartSimulation /> </BuildContextProvider> </DataContextProvider> </main> ) } export default App
'use strict' const assert = require('assert') const Buffer = require('buffer').Buffer const realZlib = require('zlib') const constants = exports.constants = require('./constants.js') const Minipass = require('minipass') const OriginalBufferConcat = Buffer.concat const _superWrite = Symbol('_superWrite') class ZlibError extends Error { constructor (err) { super('zlib: ' + err.message) this.code = err.code this.errno = err.errno /* istanbul ignore if */ if (!this.code) this.code = 'ZLIB_ERROR' this.message = 'zlib: ' + err.message Error.captureStackTrace(this, this.constructor) } get name () { return 'ZlibError' } } // the Zlib class they all inherit from // This thing manages the queue of requests, and returns // true or false if there is anything in the queue when // you call the .write() method. const _opts = Symbol('opts') const _flushFlag = Symbol('flushFlag') const _finishFlushFlag = Symbol('finishFlushFlag') const _fullFlushFlag = Symbol('fullFlushFlag') const _handle = Symbol('handle') const _onError = Symbol('onError') const _sawError = Symbol('sawError') const _level = Symbol('level') const _strategy = Symbol('strategy') const _ended = Symbol('ended') const _defaultFullFlush = Symbol('_defaultFullFlush') class ZlibBase extends Minipass { constructor (opts, mode) { if (!opts || typeof opts !== 'object') throw new TypeError('invalid options for ZlibBase constructor') super(opts) this[_ended] = false this[_opts] = opts this[_flushFlag] = opts.flush this[_finishFlushFlag] = opts.finishFlush // this will throw if any options are invalid for the class selected try { this[_handle] = new realZlib[mode](opts) } catch (er) { // make sure that all errors get decorated properly throw new ZlibError(er) } this[_onError] = (err) => { this[_sawError] = true // there is no way to cleanly recover. // continuing only obscures problems. this.close() this.emit('error', err) } this[_handle].on('error', er => this[_onError](new ZlibError(er))) this.once('end', () => this.close) } close () { if (this[_handle]) { this[_handle].close() this[_handle] = null this.emit('close') } } reset () { if (!this[_sawError]) { assert(this[_handle], 'zlib binding closed') return this[_handle].reset() } } flush (flushFlag) { if (this.ended) return if (typeof flushFlag !== 'number') flushFlag = this[_fullFlushFlag] this.write(Object.assign(Buffer.alloc(0), { [_flushFlag]: flushFlag })) } end (chunk, encoding, cb) { if (chunk) this.write(chunk, encoding) this.flush(this[_finishFlushFlag]) this[_ended] = true return super.end(null, null, cb) } get ended () { return this[_ended] } write (chunk, encoding, cb) { // process the chunk using the sync process // then super.write() all the outputted chunks if (typeof encoding === 'function') cb = encoding, encoding = 'utf8' if (typeof chunk === 'string') chunk = Buffer.from(chunk, encoding) if (this[_sawError]) return assert(this[_handle], 'zlib binding closed') // _processChunk tries to .close() the native handle after it's done, so we // intercept that by temporarily making it a no-op. const nativeHandle = this[_handle]._handle const originalNativeClose = nativeHandle.close nativeHandle.close = () => {} const originalClose = this[_handle].close this[_handle].close = () => {} // It also calls `Buffer.concat()` at the end, which may be convenient // for some, but which we are not interested in as it slows us down. Buffer.concat = (args) => args let result try { const flushFlag = typeof chunk[_flushFlag] === 'number' ? chunk[_flushFlag] : this[_flushFlag] result = this[_handle]._processChunk(chunk, flushFlag) // if we don't throw, reset it back how it was Buffer.concat = OriginalBufferConcat } catch (err) { // or if we do, put Buffer.concat() back before we emit error // Error events call into user code, which may call Buffer.concat() Buffer.concat = OriginalBufferConcat this[_onError](new ZlibError(err)) } finally { if (this[_handle]) { // Core zlib resets `_handle` to null after attempting to close the // native handle. Our no-op handler prevented actual closure, but we // need to restore the `._handle` property. this[_handle]._handle = nativeHandle nativeHandle.close = originalNativeClose this[_handle].close = originalClose // `_processChunk()` adds an 'error' listener. If we don't remove it // after each call, these handlers start piling up. this[_handle].removeAllListeners('error') } } let writeReturn if (result) { if (Array.isArray(result) && result.length > 0) { // The first buffer is always `handle._outBuffer`, which would be // re-used for later invocations; so, we always have to copy that one. writeReturn = this[_superWrite](Buffer.from(result[0])) for (let i = 1; i < result.length; i++) { writeReturn = this[_superWrite](result[i]) } } else { writeReturn = this[_superWrite](Buffer.from(result)) } } if (cb) cb() return writeReturn } [_superWrite] (data) { return super.write(data) } } class Zlib extends ZlibBase { constructor (opts, mode) { opts = opts || {} opts.flush = opts.flush || constants.Z_NO_FLUSH opts.finishFlush = opts.finishFlush || constants.Z_FINISH super(opts, mode) this[_fullFlushFlag] = constants.Z_FULL_FLUSH this[_level] = opts.level this[_strategy] = opts.strategy } params (level, strategy) { if (this[_sawError]) return if (!this[_handle]) throw new Error('cannot switch params when binding is closed') // no way to test this without also not supporting params at all /* istanbul ignore if */ if (!this[_handle].params) throw new Error('not supported in this implementation') if (this[_level] !== level || this[_strategy] !== strategy) { this.flush(constants.Z_SYNC_FLUSH) assert(this[_handle], 'zlib binding closed') // .params() calls .flush(), but the latter is always async in the // core zlib. We override .flush() temporarily to intercept that and // flush synchronously. const origFlush = this[_handle].flush this[_handle].flush = (flushFlag, cb) => { this.flush(flushFlag) cb() } try { this[_handle].params(level, strategy) } finally { this[_handle].flush = origFlush } /* istanbul ignore else */ if (this[_handle]) { this[_level] = level this[_strategy] = strategy } } } } // minimal 2-byte header class Deflate extends Zlib { constructor (opts) { super(opts, 'Deflate') } } class Inflate extends Zlib { constructor (opts) { super(opts, 'Inflate') } } // gzip - bigger header, same deflate compression const _portable = Symbol('_portable') class Gzip extends Zlib { constructor (opts) { super(opts, 'Gzip') this[_portable] = opts && !!opts.portable } [_superWrite] (data) { if (!this[_portable]) return super[_superWrite](data) // we'll always get the header emitted in one first chunk // overwrite the OS indicator byte with 0xFF this[_portable] = false data[9] = 255 return super[_superWrite](data) } } class Gunzip extends Zlib { constructor (opts) { super(opts, 'Gunzip') } } // raw - no header class DeflateRaw extends Zlib { constructor (opts) { super(opts, 'DeflateRaw') } } class InflateRaw extends Zlib { constructor (opts) { super(opts, 'InflateRaw') } } // auto-detect header. class Unzip extends Zlib { constructor (opts) { super(opts, 'Unzip') } } class Brotli extends ZlibBase { constructor (opts, mode) { opts = opts || {} opts.flush = opts.flush || constants.BROTLI_OPERATION_PROCESS opts.finishFlush = opts.finishFlush || constants.BROTLI_OPERATION_FINISH super(opts, mode) this[_fullFlushFlag] = constants.BROTLI_OPERATION_FLUSH } } class BrotliCompress extends Brotli { constructor (opts) { super(opts, 'BrotliCompress') } } class BrotliDecompress extends Brotli { constructor (opts) { super(opts, 'BrotliDecompress') } } exports.Deflate = Deflate exports.Inflate = Inflate exports.Gzip = Gzip exports.Gunzip = Gunzip exports.DeflateRaw = DeflateRaw exports.InflateRaw = InflateRaw exports.Unzip = Unzip /* istanbul ignore else */ if (typeof realZlib.BrotliCompress === 'function') { exports.BrotliCompress = BrotliCompress exports.BrotliDecompress = BrotliDecompress } else { exports.BrotliCompress = exports.BrotliDecompress = class { constructor () { throw new Error('Brotli is not supported in this version of Node.js') } } }
-- Enable CLI headers .headers on .mode box .separator ROW "\n" .nullvalue NULL CREATE TABLE IF NOT EXISTS node ( path TEXT PRIMARY KEY, content TEXT, -- virtual columns from JSON extractions -- alt_urls TEXT GENERATED ALWAYS AS (json_extract(content, '$.altUrls')), -- id TEXT GENERATED ALWAYS AS (json_extract(content, '$.id')) NOT NULL UNIQUE, -- createdAt TEXT GENERATED ALWAYS AS (json_extract(content, '$.createdAt')), -- modifiedAt TEXT GENERATED ALWAYS AS (json_extract(content, '$.modifiedAt')), -- searchText TEXT GENERATED ALWAYS AS (json_remove(content, '$.modifiedAt')) -- note TEXT GENERATED ALWAYS AS (json_extract(content, '$.note')), tags TEXT GENERATED ALWAYS AS (json_extract(content, '$.tags')), links TEXT GENERATED ALWAYS AS (json_extract(content, '$.links')), title TEXT GENERATED ALWAYS AS (json_extract(content, '$.title')), url TEXT GENERATED ALWAYS AS (json_extract(content, '$.url')) ); CREATE VIRTUAL TABLE IF NOT EXISTS node_fts USING fts5(path, title, tagList, targetUrlList, anyText); -- CREATE VIRTUAL TABLE IF NOT EXISTS node_fts USING fts5(path, anyText, title, tagList, content=''); CREATE TRIGGER IF NOT EXISTS tgr_node_fts_ai AFTER INSERT ON node BEGIN INSERT INTO node_fts(rowid, path, title, tagList, targetUrlList, anyText) VALUES ( new.rowid, new.path, new.title, (SELECT group_concat(value) FROM json_each(new.tags)), (SELECT group_concat(value) FROM json_tree(new.links) WHERE key = 'url'), (SELECT group_concat(value) FROM json_tree(new.content) WHERE atom iS NOT NULL) ); END; CREATE TRIGGER IF NOT EXISTS tgr_node_fts_ad AFTER DELETE ON node BEGIN INSERT INTO node_fts(node_fts, rowid, path, title, tagList, targetUrlList, anyText) VALUES( 'delete', old.rowid, old.path, old.title, (SELECT group_concat(value) FROM json_each(old.tags)), (SELECT group_concat(value) FROM json_tree(old.links) WHERE key = 'url'), (SELECT group_concat(value) FROM json_tree(old.content) WHERE atom iS NOT NULL) ); END; CREATE TRIGGER IF NOT EXISTS trg_node_fts_au AFTER UPDATE ON node BEGIN INSERT INTO node_fts(node_fts, rowid, path, title, tagList, targetUrlList, anyText) VALUES( 'delete', old.rowid, old.path, old.title, (SELECT group_concat(value) FROM json_each(old.tags)), (SELECT group_concat(value) FROM json_tree(old.links) WHERE key = 'url'), (SELECT group_concat(value) FROM json_tree(old.content) WHERE atom iS NOT NULL) ); INSERT INTO node_fts(rowid, path, title, tagList, targetUrlList, anyText) VALUES ( new.rowid, new.path, new.title, (SELECT group_concat(value) FROM json_each(new.tags)), (SELECT group_concat(value) FROM json_tree(new.links) WHERE key = 'url'), (SELECT group_concat(value) FROM json_tree(new.content) WHERE atom iS NOT NULL) ); END; INSERT INTO node(path, content) VALUES ('0001.json', '{"title": "Title 1", "tags": ["book", "todo"]}'), ('0002.json', '{"title": "Title 2", "links": [{"title": "Link 1", "url": "https://example.com/1"}, {"title": "Link 2", "url": "https://example.com/2"}]}'), ('0003.json', '{"title": "Title 3", "Description": "Once upon a time, there is a boy."}'); UPDATE node SET content='{"title": "Title 3 modified"}' WHERE path = '0003.json'; -- SELECT * FROM node_fts WHERE node_fts MATCH '"modified"'; -- SELECT rowid FROM node_fts; -- SELECT * FROM node_fts; SELECT * FROM node WHERE rowid IN ( SELECT rowid FROM node_fts -- SELECT rowid FROM node_fts WHERE node_fts MATCH '"modified"' ); -- SELECT * FROM node_fts; -- SELECT * FROM node; -- UPDATE node SET content='{"title": "Title 3 modified"}' WHERE path = '0003.json'; SELECT * FROM node where PATH = '0003.json';
# -*- coding: utf-8 -*- # # # Mozilla Public License Version 2.0 # Copyright (c) 2023, Flepis from . import haisettings from .haisettings import INVISIBLE, READ_ONLY, READ_WRITE from .HaiErrors import * import numbers import math import typing import os import sys import time def MAIN_VEC_TYPE_CHECKING(fuc): """ 检查必要运算语句(只在haisettings.HAI_MAIN_DEBUG==True时有效)\n """ if haisettings.HAI_MAIN_DEBUG: def checker(self: "HaiVector", other: "HaiVector"): if fuc.__name__ == '__mul__': if not isinstance(other, numbers.Number): raise TypeError return fuc(self, other) if type(self) is not HaiVector or type(other) is not HaiVector: raise TypeError if self.vectorLen != other.vectorLen: raise TypeError else: return fuc(self, other) return checker if not haisettings.HAI_MAIN_DEBUG: return fuc def get_opposite_vector(vector: "HaiVector") -> "HaiVector": """ 求一个向量的相反向量,返回一个相反向量 :param vector: :return: :rtype: HaiVector """ alist = [] for coordinate_tuple in vector: alist.append(-coordinate_tuple[1]) return HaiVector(alist) def get_hai_module(vector: "HaiVector") -> float: """ 求向量的模 :rtype: float :param vector: :return: """ alist = [] for sport_tuple in vector: alist.append(math.pow(sport_tuple[1], 2)) return math.pow(sum(alist), 0.5) class HaiVisitLimiter: """ 一个描述器,限制访问特定属性 默认为只读 """ def __init__(self, name, mode=READ_ONLY): self.__mode = mode self.__name = name def __get__(self, instance, owner=None): raise NameError # if self.__mode == READ_ONLY or READ_WRITE: # return instance.__dict__[self.__name] # # if self.__mode == INVISIBLE: # raise # # else: # raise def __set__(self, instance, value): if self.__mode == READ_WRITE: return instance.__dict__[self.__name] if self.__mode == INVISIBLE or READ_ONLY: raise else: raise def __delete__(self, instance): if self.__mode == INVISIBLE or READ_ONLY: raise if self.__mode == READ_WRITE: del instance.__dict__[self.__name] class HaiVector(object): """ MainGame中的向量类 是一个可迭代对象 遍历返回tuple(坐标列表中的位置,坐标) 例如:\n f = Hai_Vector([1,2,3])\n for i in f: print(i)\n 输出:\n (0,1);(1,2);(2,3)\n 支持向量加法,减法和点乘\n :+ -:向量线性加,减法;\n :* @:向量数量积,点乘;\n 支持一些增强赋值,如+=,-=,*= """ # noinspection PyUnusedLocal def __init__(self, coordinate: list, *args: any) -> None: self.__coordinate = coordinate self.__index = 0 self.vectorLen = len(self) self.module = get_hai_module(self) self.coordinate = self.__coordinate self.__slots__ = ['vectorLen', 'module', 'coordinate'] def __iter__(self): return self def __next__(self) -> tuple[int, any]: if self.__index < self.vectorLen: self.__index += 1 return self.__index - 1, self.__coordinate[self.__index - 1] if self.__index == self.vectorLen: self.__index = 0 raise StopIteration def __len__(self): return len(self.__coordinate) @MAIN_VEC_TYPE_CHECKING def __add__(self, other: "HaiVector") -> "HaiVector": for __coordinate in other: self.__coordinate[__coordinate[0]] += __coordinate[1] return HaiVector(self.__coordinate) @MAIN_VEC_TYPE_CHECKING def __sub__(self, other: "HaiVector") -> "HaiVector": return self + get_opposite_vector(other) @MAIN_VEC_TYPE_CHECKING def __matmul__(self, other: "HaiVector") -> float: alist = [] for __index in range(self.vectorLen): alist.append(self.__coordinate[__index] * other.coordinate[__index]) return float(sum(alist)) @MAIN_VEC_TYPE_CHECKING def __iadd__(self, other: "HaiVector") -> "HaiVector": _self = self _self = self + other return _self @MAIN_VEC_TYPE_CHECKING def __isub__(self, other: "HaiVector") -> "HaiVector": _self = self _self = self - other return _self @MAIN_VEC_TYPE_CHECKING def __eq__(self, other: "HaiVector") -> bool: if self.coordinate == other.coordinate: return True @MAIN_VEC_TYPE_CHECKING def __mul__(self, other: numbers.Number) -> "HaiVector": alist = [] for __index in range(self.vectorLen): alist.append(self.__coordinate[__index] * other) return HaiVector(alist) def __imul__(self, other: numbers.Number) -> "HaiVector": _self = self _self = self * other return _self def __repr__(self) -> str: return f"<A Vector object in {hex(id(self))},\nThe" \ f" coordinate list is {str(self.__coordinate)},\n" \ f"From \n{__file__} {type(self)}>" def __hash__(self) -> int: return hash(str(self)) def __abs__(self) -> float: return self.module class HaiLogs(object): """ 日志功能的实现 """ logs = HaiVisitLimiter(name="_HaiLogs__logs") def __init__(self, input_type: any = None, judgment_fuc: typing.Callable = None, stream_head_chooser_kwargs: dict = {}, type_chooser_kwargs: dict = {}, **kwargs): self.__input_type = input_type self.__stream_head = self.stream_head_chooser(input_type=input_type, judgment_fuc=judgment_fuc, **stream_head_chooser_kwargs) self.__type = self.type_chooser(input_type=input_type, judgment_fuc=judgment_fuc, **type_chooser_kwargs) self.__format = "[{}][{}][{}][{}]" self.__logs = "" def hai_log(self, log_text: str = '') -> None: """ 打印日志 """ __log = "[{}][{}][{}][{}]".format(time.strftime("%Y %B %d %H:%M:%S"), self.__stream_head, self.thread_name(), self.__type) + log_text self.__logs += (__log + log_text + "\n") @staticmethod def stream_head_chooser(input_type: any = None, judgment_fuc: typing.Callable = None, **kwargs) -> str: """ judgment_fuc为可调用类型,且应该返回对输入类型判断结果\n 返回值应该为一段有意义的字符串\n 如果未提供judgment_fuc,默认返回"HaiMain"\n 安全警告:judgment_fuc永远不应该执行钩子类型,以防止意外的执行或注入代码 """ if judgment_fuc: return judgment_fuc(input_type, **kwargs) else: return "HaiMain" @staticmethod def type_chooser(input_type: any = None, judgment_fuc: typing.Callable = None, **kwargs) -> str: """ judgment_fuc为可调用类型,且应该返回对输入类型判断结果\n 返回值应该为一段有意义的字符串,默认为INFO,WARN,ERROR\n 如果未提供judgment_fuc,默认返回"INFO"\n 安全警告:judgment_fuc永远不应该执行钩子类型,以防止意外的执行或注入代码 """ if judgment_fuc: return judgment_fuc(input_type, **kwargs) else: return "INFO" @staticmethod def thread_name() -> str: """ 获得当前进程的名称(未完工) """ return __name__ def log_out(self, log_text: str = '') -> None: """ 打印日志 """ __log = "[{}][{}][{}][{}]".format(time.strftime("%Y %B %d %H:%M:%S"), self.__stream_head, self.thread_name(), self.__type) + log_text print(__log) # self.__logs += (__log + log_text + "\n") def logs_writer(self, path: str) -> None: """ 写入日志文件 """ with open(path, "a+") as file: file.write(self.__logs) # class HaiThread()
type TDataType = keyof any | object; interface GeneralResData { code: number | string; data: { [key: string]: TDataType } | TDataType | TDataType[]; msg?: string; status?: number; } interface LoginResData { retcode: number; retmsg?: string; result: Partial<{ command: string; data: { [key: string]: TDataType } | TDataType | TDataType[]; message: string; }>; }; type Env = 'dev' | 'test' | 'pre' | 'online'; interface IUserdata { acctId: string; acctName: string; acctToken: string | null; deviceType: string; displayName: string; loginId: string; new: boolean; pid: null | string; portraitUrl: string; refreshToken: string } interface Window { sensors: { track(eventName: string, options: object); login(loginId: string): void; }; loginTokerData: Partial<{ retcode: number; retmsg: string; result: { command: string; message: string; data: IUserdata } }>; passport: { pop: { init(config: object): { show(): void; hide(): void; } } }; } declare namespace sensors { interface Options extends Record<string, unknown> { title?: string; } type EventType = 'click' | 'pv'; type Logger = { (eventName: string): void; (eventName: string, eventType: EventType): void; (eventName: string, eventType: EventType, options: Options): void; (eventName: string, eventType: Options): void; } } type TPage = { currPage: number; pageSize: number; totalCount?: number; }
""" The parser is the most important and complex part of the project and, so I thought it necessary to divide it into multiple files - Pre Declaration covers everything that happens before a class declaration such as imports - Class Declarations covers things like method lists and parameters - Statements Semicolons are statements that don't need a semicolon or "already have" a semi-colon like while loops - Statements No Semicolons covers statements that don't already a colon like return statements - Expressions is self-explanatory - Misc is everything else """ import sys # tokens must be imported from src.lexer import tokens # Parser imports from src.core_parser.pre_declaration import * from src.core_parser.class_declaration import * from src.core_parser.statements_semicolon import * from src.core_parser.statements_no_semicolon import * from src.core_parser.expressions import * from src.core_parser.misc import * from src.core_transpiler.main_transpiler import Transpiler from src.util import components as comp # Im not sure precedence even does anything since this is a transpiler # and is not an interpreter precedence = ( ('left', '+', '-'), # Level 1 ('left', '*', '/'), # Level 2 ) # Start is necessary since the grammar is broken up start = "program" def p_program(p): """ program : class_declaration_with_comments """ # - Program acts as the entry point for the parser # - This function creates and calls Transpiler.traverse() # - Though Transpiler.traverse() is a recursive method (thus, the # method takes in at least one argument), its argument defaults to # None which allows this function to call traverse() without any input # given to traverse() transpiler = Transpiler(p[1]) p[0] = transpiler.traverse() def p_class_declaration_with_comments(p): """ class_declaration_with_comments : package_statement_or_empty pre_class_declaration_list class_declaration comment_list_or_empty """ # This little line below will make this rule more readable class_declaration: comp.ClassDeclaration = p[3] # Package statement has to be seperate because there could be multiple class_declaration.package_statement = p[1] class_declaration.pre_class_declaration_list = p[2] class_declaration.comments_after = p[4] # Finally, pass ClassDeclaration through p[0] = p[3] def p_error(p): print("Syntax Errror!") print(f"VALUE: {p.value}") print(f"TYPE: {p.type}") print(f"P: {p}")
import React, {useEffect, useState} from 'react'; export const UseEffectReset = () => { const [text, setText] = useState('') const handler = (e: KeyboardEvent) => { setText((state) => state + e.key) console.log(e.key) } useEffect(() => { window.addEventListener('keypress', handler) return (() => { window.removeEventListener('keypress', handler) }) }, []) return ( <div> Text: {text} </div> ); };
import { Component, signal } from '@angular/core'; import { CommonModule } from '@angular/common'; import { Task } from './models/task.model'; import { FormControl, ReactiveFormsModule, Validators } from '@angular/forms'; @Component({ selector: 'app-home', standalone: true, imports: [CommonModule, ReactiveFormsModule], templateUrl: './home.component.html', styleUrl: './home.component.css' }) export class HomeComponent { tasks = signal<Task[]>([ { id: Date.now(), title: 'crear proyecto', completed: false, }, { id: Date.now(), title: 'crear components', completed: false, }, ]); newtaskCtrl = new FormControl('', { nonNullable: true, validators: [ Validators.required, ] }); changeHandler() { if (this.newtaskCtrl.valid) { const value = this.newtaskCtrl.value.trim(); if (value !== '') { this.addTask(value); this.newtaskCtrl.setValue(''); } } //patrones de manejo del estado no muta lo actualiza } addTask(title: string) { const newTask = { id: Date.now(), title, completed: false, } this.tasks.update((tasks) => [...tasks, newTask]) } deleteTask(index: number) { this.tasks.update((tasks) => tasks.filter((task, position) => position !== index)); } updateTask(index: number) { this.tasks.update((tasks) => { return tasks.map((task, position) => { if (position === index) { return { ...task, completed: !task.completed } } return task; }) }) } }
import React, { useContext, useState } from "react"; import chat from "../../assets/chat.svg"; import arrowUp from "../../assets/arrow-up.svg"; import arrowUpBlue from "../../assets/arrow-up-blue.svg"; import arrowDown from "../../assets/arrow-down.svg"; import arrowDownRed from "../../assets/arrow-down-red.svg"; import "../PostCards/postCards.sass"; import { useNavigate } from "react-router-dom"; import { GlobalContext } from "../../contexts/GlobalContext"; import { BASE_URL } from "../../constants/url"; import axios from "axios"; import { goToCommentPage } from "../../routes/coordinator"; const PostCards = (props) => { const { post } = props; const [likes, setLikes] = useState(false); const [dislikes, setDislikes] = useState(false); const navigate = useNavigate(); const context = useContext(GlobalContext); const { fetchPosts } = context; const like = async () => { try { const body = { like: true, }; await axios.put(BASE_URL + `/posts/${post.id}/like`, body, { headers: { Authorization: window.localStorage.getItem("labeddit-token"), }, }); fetchPosts(); setLikes(true); setDislikes(false); } catch (error) { console.error(error); } }; const dislike = async () => { try { const body = { like: false, }; await axios.put(BASE_URL + `/posts/${post.id}/like`, body, { headers: { Authorization: window.localStorage.getItem("labeddit-token"), }, }); fetchPosts(); setDislikes(true); setLikes(false); } catch (error) { console.error(error); } }; return ( <div className="container" id="card"> <p id="username">Enviador por: {post.creator.name}</p> <p id="post-text">{post.content}</p> <div className="row"> {likes ? ( <img src={arrowUpBlue} alt="" className="icon" onClick={like} /> ) : ( <img src={arrowUp} alt="" className="icon" onClick={like} /> )} <p className="numbers-post">{post.likes}</p> {dislikes ? ( <img src={arrowDownRed} alt="" className="icon" onClick={dislike} /> ) : ( <img src={arrowDown} alt="" className="icon" onClick={dislike} /> )} <img src={chat} alt="" className="icon" onClick={() => goToCommentPage(navigate, post.id)} /> <p className="numbers-post" id="margin-left"> {post.comments} </p> </div> </div> ); }; export default PostCards;
import { FormControl, FormLabel, Input, Textarea, Text, Heading, Switch, NumberInput, NumberInputField, NumberInputStepper, NumberIncrementStepper, NumberDecrementStepper, HStack, Tooltip, Flex, FormErrorMessage, } from "@chakra-ui/react"; import { useField } from "formik"; import React from "react"; import ReactMarkdown from "react-markdown"; import infoOutline from "@iconify/icons-eva/info-outline"; import { getIcon } from "./SidebarConfig"; import remarkGfm from "remark-gfm"; import ChakraUIRenderer from "chakra-ui-markdown-renderer"; import { markdownTheme } from "../theme"; type InputFieldProps = React.InputHTMLAttributes<HTMLInputElement> & { label: string; name: string; renderMarkdown?: boolean; type?: "text" | "textarea" | "switch" | "number"; hint?: string; }; export const InputField: React.FC<InputFieldProps> = ({ label, size: _, color: _1, type = "text", hint, renderMarkdown = false, ...props }) => { const [field, { error }] = useField(props); return ( <FormControl isInvalid={!!error}> <Flex> <FormLabel htmlFor={field.name}>{label}</FormLabel> {hint && <Tooltip label={hint}>{getIcon(infoOutline)}</Tooltip>} </Flex> {type === "text" && ( <Input {...field} {...props} id={field.name} placeholder={props.placeholder} ></Input> )} {type === "textarea" && ( <> {/* // @ts-ignore */} <Textarea {...field} {...props} id={field.name} placeholder={props.placeholder} h={40} mb={4} /> <Heading size="sm" mb={2}> {label} Rendered </Heading> {renderMarkdown && ( <ReactMarkdown components={ChakraUIRenderer(markdownTheme)} linkTarget="_self" remarkPlugins={[remarkGfm]} > {field.value} </ReactMarkdown> )} </> )} {type === "switch" && ( <> {/* // @ts-ignore */} <Switch {...field} {...props} isChecked={field.value} id={field.name} /> </> )} {type === "number" && ( <NumberInput> <NumberInputField {...field} {...props} id={field.name} placeholder={props.placeholder} /> <NumberInputStepper> <NumberIncrementStepper /> <NumberDecrementStepper /> </NumberInputStepper> </NumberInput> )} {error && <FormErrorMessage>{error}</FormErrorMessage>} </FormControl> ); };
<?php get_header(); ?> <?php if ( have_posts() ) : while ( have_posts() ) : the_post(); // start the loop ?> <article id="post-excerpt-<?php the_ID(); ?>" class="post-excerpt"> <h2> <a href="<?php the_permalink(); // link to the posting ?>"><?php the_title(); // the posting title ?></a> </h2> <small>Posted on <?php the_time('F j, Y'); // get the time ?> by <?php the_author(); // the author name ?> in <?php the_category(', '); // the category ?></small> <a href="<?php the_permalink(); // link to the posting ?>"> <?php echo the_post_thumbnail( 'thumbnail' ); // the featured image ?> </a> <?php the_excerpt(); // the posting's excerpt ?> <?php the_excerpt();?> <p class="read-more"> <a href="<?php the_permalink();?>">Read More &raquo;</a> </p> </article> <?php endwhile; endif; // end the loop ?> <small>index.php</small> <!-- End Content --> <?php get_sidebar(); ?> <?php get_footer(); ?>
import express, { Request, Response, NextFunction } from "express"; import multer from "multer"; import { AddFood, GetFoods, GetVendorProfile, updateVendorCoverImage, UpdateVendorProfile, UpdateVendorService, VendorLogin, } from "../controllers"; import { Authenticate } from "../middlewares/CommonAuth"; const router = express.Router(); //image storage initialization const imageStorage = multer.diskStorage({ destination: function (req, file, cb) { cb(null, "images"); }, filename: function (req, file, cb) { cb(null, new Date().toISOString + "_" + file.originalname); }, }); const images = multer({ storage: imageStorage }).array("images", 10); // Authentication router.post("/login", VendorLogin); //General Apis router.use(Authenticate); router.get("/profile", GetVendorProfile); router.patch("/profile", UpdateVendorProfile); router.patch("/coverimage", images, updateVendorCoverImage); router.patch("/service", UpdateVendorService); //Foods router.post("/food", images, AddFood); router.get("/foods", GetFoods); export { router as VendorRoute };
'use strict'; const btn = document.querySelector('.btn-country'); const countriesContainer = document.querySelector('.countries'); /* const getContryData = function(country){ const request = new XMLHttpRequest(); request.open('GET',`https://restcountries.com/v3.1/name/${country}`); request.send(); // console.log(request.responseText); request.addEventListener('load',function(){ const [data] = JSON.parse(this.responseText); console.log(data); const html = ` <article class="country"> <img class="country__img" src="${data.flags.png}" /> <div class="country__data"> <h3 class="country__name">${data.name.common}</h3> <h4 class="country__region">${data.region}</h4> <p class="country__row"><span>👫</span>${+(data.population / 1000000).toFixed(1)}M People</p> <p class="country__row"><span>🗣️</span>${Object.values(data.languages)[0]}</p> <p class="country__row"><span>💰</span>${Object.values(data.currencies)[0].name}</p> </div> </article> `; countriesContainer.insertAdjacentHTML('beforeend',html); countriesContainer.style.opacity = '1' }) }; getContryData('india'); getContryData('usa'); getContryData('sweden'); getContryData('russia'); */ /* // Callback hell const renderCountry = function(data, className=""){ const html = ` <article class="country ${className}"> <img class="country__img" src="${data.flags.png}" /> <div class="country__data"> <h3 class="country__name">${data.name.common}</h3> <h4 class="country__region">${data.region}</h4> <p class="country__row"><span>👫</span>${+(data.population / 1000000).toFixed(1)}M People</p> <p class="country__row"><span>🗣️</span>${Object.values(data.languages)[0]}</p> <p class="country__row"><span>💰</span>${Object.values(data.currencies)[0].name}</p> </div> </article> `; countriesContainer.insertAdjacentHTML('beforeend',html); // countriesContainer.style.opacity = '1' } */ /* const getContryAndNeighbour = function(country){ //AJAX call country 1 const request = new XMLHttpRequest(); request.open('GET',`https://restcountries.com/v3.1/name/${country}`); request.send(); // console.log(request.responseText); request.addEventListener('load',function(){ const [data] = JSON.parse(this.responseText); console.log(data); //render country renderCountry(data); // Get neighbour country const [neighbour] = data.borders; if(!neighbour) return; //AJAX call country 2 const request2 = new XMLHttpRequest(); request2.open('GET',`https://restcountries.com/v3.1/alpha/${neighbour}`); request2.send(); request2.addEventListener('load',function(){ const [data2] = JSON.parse(this.responseText); console.log(data2); renderCountry(data2,'neighbour'); }) }) }; getContryAndNeighbour('usa'); */ // Promises // const request = new XMLHttpRequest(); // request.open('GET',`https://restcountries.com/v3.1/name/${country}`); // request.send(); // const request = fetch('https://restcountries.com/v3.1/name/india'); // console.log(request); // cosuming promise // const getCountryData = function(country){ // fetch(`https://restcountries.com/v3.1/name/${country}`).then(function(response){ // console.log(response); // return response.json(); // }).then(function(data){ // console.log(data); // renderCountry(data[0]); // }) // }; /* const renderErr = function(msg){ countriesContainer.insertAdjacentText('beforeend',msg); // countriesContainer.style.opacity = 1; } const getJSON = function(url,errMsg = "Something went wrong!"){ return fetch(url).then(response => { if(!response.ok) throw new Error(`${errMsg} (${response.status})`); return response.json(); }); }; */ // const getCountryData = function(country){ // //Country 1 // fetch(`https://restcountries.com/v3.1/name/${country}`) // .then(response => { // if(!response.ok){ // throw new Error(`Country not found (${response.status})`) // } // return response.json()/*,*/ // // err => alert(err) // }) // .then(data =>{ // renderCountry(data[0]); // const neighbour = data[0].borders[0]; // if(!neighbour) return; // //Country 2 // return fetch(`https://restcountries.com/v3.1/alpha/${neighbour}`); // }) // .then(response => response.json()) // .then(data => renderCountry(data[0],'neighbour')) // .catch(err => { // console.error(`${err} 💥💥💥`); // renderErr(`Something went wrong 💥💥 ${err.message}. Try again!`) // }) // .finally(() => { // countriesContainer.style.opacity = '1'; // }) // }; /* const getCountryData = function(country){ //Country 1 getJSON(`https://restcountries.com/v3.1/name/${country}`,'Country not found') .then(data =>{ renderCountry(data[0]); const neighbour = data[0].borders[0]; // const neighbour = 'dfjadfja'; if(!neighbour) throw new Error('No neighbour found!'); //Country 2 return getJSON(`https://restcountries.com/v3.1/alpha/${neighbour}`,'Country not found'); }) .then(data => renderCountry(data[0],'neighbour')) .catch(err => { // console.error(`${err} 💥💥💥`); renderErr(`Something went wrong 💥💥 ${err.message}. Try again!`) }) .finally(() => { countriesContainer.style.opacity = '1'; }) }; btn.addEventListener('click',function(){ getCountryData('Bharat'); }); */ /* console.log('Test start'); setTimeout(() => console.log('0 sec timer'),0); Promise.resolve('Resolve promise 1') .then(res => console.log(res)) Promise.resolve('Resolve promise 2') .then(res =>{ for(let i = 0; i < 1000000000; i++){} console.log(res) }) console.log('Test end'); /////////Building NEW PROMISE const lotteryPromise = new Promise(function(resolve,reject){ console.log('Lottery draw is happening! 🔮'); setTimeout(function(){ if(Math.random() >= .5){ resolve('you WIN 💰'); }else{ reject(new Error('you lost your money 💩')); } },2000); }); lotteryPromise.then(res => console.log(res)).catch(err => console.error(err) ); // Promisifying setTimeout const wait = function(seconds){ return new Promise(function(resolve){ setTimeout(resolve, seconds*1000); }); }; // escaping callback hell wait(1).then(() =>{ console.log('1 second passed!'); return wait(1); }) .then(() => { console.log('2 seconds passed!'); return wait(1); }) .then(() => { console.log('3 seconds passed!'); return wait(1); }) .then(() => console.log('4 seconds passed!')) /////////PROMISIFYING GEOLOCATION API // navigator.geolocation.getCurrentPosition( // position => console.log(position), // err => console.log(err) // ) // console.log('geolocation api started'); const getPostion = function(){ return new Promise(function(resolve,reject){ // navigator.geolocation.getCurrentPosition( // position => resolve(position), // err => reject(err) // ) navigator.geolocation.getCurrentPosition(resolve,reject); }); }; getPostion().then(res => console.log(res)); /////////ASYNC AWAIT // just syntactic sugar over .then method const whereAmI = async function(country){ // fetch(`https://restcountries.com/v3.1/name/${country}`) // .then(res => console.log(res)); try{const res = await fetch(`https://restcountries.com/v3.1/name/${country}`); const [data] = await res.json(); console.log(data);} catch(err){ console.error(err); } } whereAmI('Bharat'); console.log('First'); //////////TRY AND CATCH try{ let x = 1; const y = 2; x = 3; } catch(err){ alert(err.message); } */ /////////PARALLEL PROMISES (MANY AT SAME TIME) const getJSON = function(url,errMsg = "Something went wrong!"){ return fetch(url).then(response => { if(!response.ok) throw new Error(`${errMsg} (${response.status})`); return response.json(); }); }; const get3Countries = async function(c1,c2,c3){ try{ const data = await Promise.all( [ getJSON(`https://restcountries.com/v3.1/name/${c1}`), getJSON(`https://restcountries.com/v3.1/name/${c2}`), getJSON(`https://restcountries.com/v3.1/name/${c3}`) ] ); // console.log(data.map(d => d[0].capital[0])); } catch(err){ console.log(err); } }; get3Countries('Bharat','canada','tanzania'); (async function(){ const res = await Promise.race([ getJSON(`https://restcountries.com/v3.1/name/Bharat`), getJSON(`https://restcountries.com/v3.1/name/Italy`), getJSON(`https://restcountries.com/v3.1/name/Egypt`) ]); console.log(res[0]); })(); const timeout = function(s){ return new Promise((_ ,reject) => { setTimeout(() => { reject(new Error("Request took too long!")); }, s * 1000); }); }; Promise.race([ getJSON(`https://restcountries.com/v3.1/name/Bharat`), timeout(.1), ]).then(res => console.log(res[0])) .catch(error => console.log(error)); ///////Promise.allSettled Promise.allSettled([ Promise.resolve('Success'), Promise.reject('Failed'), Promise.resolve('Success Again'), ]) .then(res => console.log(res)); //Promise.allSettled vs Promise.all Promise.all([ Promise.resolve('Success'), Promise.reject('Failed Bruh'), Promise.resolve('Success Again'), ]) .then(res => console.log(res)) .catch(err => console.log(err)); ///Promise.any() Promise.any([ Promise.reject('Failed Bruh'), Promise.reject('Success'), Promise.resolve('Success Again'), ]).then(res => console.log(res));
<nav class="sb-topnav navbar navbar-expand navbar-dark bg-dark"> <!-- Navbar Brand--> <a class="navbar-brand ps-3" >Start Bootstrap</a> <!-- Sidebar Toggle--> <button (click)="bukaTutup()" class="btn btn-link btn-sm order-1 order-lg-0 me-4 me-lg-0" id="sidebarToggle" href="#!"><i class="fas fa-bars"></i></button> <!-- Navbar Search--> <a class="list-item text-white ms-5" routerLink="/apps/home" >Home</a> <a class="list-item text-white ms-3" routerLink="/apps/mahasiswa">Mahasiswa</a> <a class="list-item text-white ms-3" routerLink="/apps/produk" >Produk</a> <a class="list-item text-white ms-3" routerLink="/apps/produkkategori" >Kategori</a> <form class="d-none d-md-inline-block form-inline ms-auto me-0 me-md-3 my-2 my-md-0"> <div class="input-group"> <input class="form-control" type="text" placeholder="Search for..." aria-label="Search for..." aria-describedby="btnNavbarSearch" /> <button class="btn btn-primary" id="btnNavbarSearch" type="button"><i class="fas fa-search"></i></button> </div> </form> <!-- Navbar--> <ul class="navbar-nav ms-auto ms-md-0 me-3 me-lg-4"> <li class="nav-item dropdown"> <a (click)="dropdown()" class="nav-link dropdown-toggle" id="navbarDropdown" role="button" data-bs-toggle="dropdown" aria-expanded="false"><i class="fas fa-user fa-fw"></i></a> <ul [style]="tampilHilang" class="dropdown-menu dropdown-menu-end" aria-labelledby="navbarDropdown"> <li><a class="dropdown-item" href="#!">Settings</a></li> <li><a class="dropdown-item" href="#!">Activity Log</a></li> <li><hr class="dropdown-divider" /></li> <li><button class="btn btn-primary ms-3" type="button" *ngIf="!isLogin" (click)="login()">Login</button> <button class="btn btn-secondary ms-3" type="button" *ngIf="isLogin" (click)="logout()">Logout</button></li> </ul> </li> </ul> </nav> <div id="layoutSidenav"> <div id="layoutSidenav_nav"> <nav class="sb-sidenav accordion sb-sidenav-light" id="sidenavAccordion"> <div class="sb-sidenav-menu"> <div class="nav"> <div class="sb-sidenav-menu-heading">Core</div> <a class="nav-link" href="index.html"> <div class="sb-nav-link-icon"><i class="fas fa-tachometer-alt"></i></div> Dashboard </a> <div class="sb-sidenav-menu-heading">Interface</div> <a class="nav-link collapsed" (click)="collapse('collapseLayouts')" data-bs-toggle="collapse" data-bs-target="#collapseLayouts" aria-expanded="false" aria-controls="collapseLayouts"> <div class="sb-nav-link-icon"><i class="fas fa-columns"></i></div> Layouts <div class="sb-sidenav-collapse-arrow"><i class="fas fa-angle-down"></i></div> </a> <div class="collapse" id="collapseLayouts" aria-labelledby="headingOne" data-bs-parent="#sidenavAccordion"> <nav class="sb-sidenav-menu-nested nav"> <a class="nav-link" href="layout-static.html">Static Navigation</a> <a class="nav-link" href="layout-sidenav-light.html">Light Sidenav</a> </nav> </div> <a class="nav-link collapsed" (click)="collapse('collapsePages')" data-bs-toggle="collapse" data-bs-target="#collapsePages" aria-expanded="false" aria-controls="collapsePages"> <div class="sb-nav-link-icon"><i class="fas fa-book-open"></i></div> Pages <div class="sb-sidenav-collapse-arrow"><i class="fas fa-angle-down"></i></div> </a> <div class="collapse" id="collapsePages" aria-labelledby="headingTwo" data-bs-parent="#sidenavAccordion"> <nav class="sb-sidenav-menu-nested nav accordion" id="sidenavAccordionPages"> <a (click)="collapse('pagesCollapseAuth')" class="nav-link collapsed" data-bs-toggle="collapse" data-bs-target="#pagesCollapseAuth" aria-expanded="false" aria-controls="pagesCollapseAuth"> Authentication <div class="sb-sidenav-collapse-arrow"><i class="fas fa-angle-down"></i></div> </a> <div class="collapse" id="pagesCollapseAuth" aria-labelledby="headingOne" data-bs-parent="#sidenavAccordionPages"> <nav class="sb-sidenav-menu-nested nav"> <a class="nav-link" href="login.html">Login</a> <a class="nav-link" href="register.html">Register</a> <a class="nav-link" href="password.html">Forgot Password</a> </nav> </div> <a (click)="collapse('pagesCollapseError')" class="nav-link collapsed" data-bs-toggle="collapse" data-bs-target="#pagesCollapseError" aria-expanded="false" aria-controls="pagesCollapseError"> Error <div class="sb-sidenav-collapse-arrow"><i class="fas fa-angle-down"></i></div> </a> <div class="collapse" id="pagesCollapseError" aria-labelledby="headingOne" data-bs-parent="#sidenavAccordionPages"> <nav class="sb-sidenav-menu-nested nav"> <a class="nav-link" href="401.html">401 Page</a> <a class="nav-link" href="404.html">404 Page</a> <a class="nav-link" href="500.html">500 Page</a> </nav> </div> </nav> </div> <div class="sb-sidenav-menu-heading">Addons</div> <a class="nav-link" href="charts.html"> <div class="sb-nav-link-icon"><i class="fas fa-chart-area"></i></div> Charts </a> <a class="nav-link" href="tables.html"> <div class="sb-nav-link-icon"><i class="fas fa-table"></i></div> Tables </a> </div> </div> <div class="sb-sidenav-footer"> <div class="small">Logged in as:</div> Start Bootstrap </div> </nav> </div> <div id="layoutSidenav_content"> <main> <router-outlet></router-outlet> </main> <footer class="py-4 bg-light mt-auto"> <div class="container-fluid px-4"> <div class="d-flex align-items-center justify-content-between small"> <div class="text-muted">Copyright &copy; Your Website 2022</div> <div> <a href="#">Privacy Policy</a> &middot; <a href="#">Terms &amp; Conditions</a> </div> </div> </div> </footer> </div> </div> <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.bundle.min.js" crossorigin="anonymous"></script> <script src="js/scripts.js"></script>
package christmas.domain; import christmas.constant.Event; import java.time.DayOfWeek; import java.time.LocalDate; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Optional; public class Calendar { private static Calendar instance; public static final int YEAR = 2023; public static final int MONTH = 12; public static final int START_DATE = 1; public static final int END_DATE = 31; public static final int CHRISTMAS = 25; private final Map<Integer, List<Event>> calendar; public Calendar() { this.calendar = createCalendar(); } public static Calendar getInstance() { if (instance == null) { instance = new Calendar(); } return instance; } public Map<Integer, List<Event>> getCalendar() { return calendar; } public List<Event> getEventsByDate(int date) { return calendar.get(date); } private Map<Integer, List<Event>> createCalendar() { Map<Integer, List<Event>> map = new HashMap<>(); for (int date = START_DATE; date < END_DATE; date++) { List<Event> events = getEventsOnDate(date); if (events.size() > 0) { map.put(date, events); } } return map; } private List<Event> getEventsOnDate(int date) { List<Event> events = new ArrayList<>(); DayOfWeek dayOfWeek = getDayOfWeekByDate(date); getChristmasEvent(date).ifPresent(events::add); getPresentEvent(date).ifPresent(events::add); getWeekendEvent(dayOfWeek, date).ifPresent(events::add); getWeekdayEvent(dayOfWeek, date).ifPresent(events::add); getSpecialEvent(dayOfWeek, date).ifPresent(events::add); return events; } private DayOfWeek getDayOfWeekByDate(int date) { LocalDate localDate = LocalDate.of(YEAR, MONTH, date); return localDate.getDayOfWeek(); } private Optional<Event> getChristmasEvent(int date) { if (isChristmasEvent(date)) { return Optional.of(Event.크리스마스_디데이); } return Optional.empty(); } private Optional<Event> getPresentEvent(int date) { if (isPresentEvent(date)) { return Optional.of(Event.증정_이벤트); } return Optional.empty(); } private Optional<Event> getWeekendEvent(DayOfWeek dayOfWeek, int date) { if (isWeekendEvent(dayOfWeek, date)) { return Optional.of(Event.주말_할인); } return Optional.empty(); } private Optional<Event> getWeekdayEvent(DayOfWeek dayOfWeek, int date) { if (isWeekdayEvent(dayOfWeek, date)) { return Optional.of(Event.평일_할인); } return Optional.empty(); } private Optional<Event> getSpecialEvent(DayOfWeek dayOfWeek, int date) { if (isSpecialEvent(dayOfWeek, date)) { return Optional.of(Event.특별_할인); } return Optional.empty(); } private boolean isChristmasEvent(int date) { if (!Event.크리스마스_디데이.isValid(date)) { return false; } return true; } private boolean isPresentEvent(int date) { if (Event.증정_이벤트.isValid(date)) { return true; } return false; } private boolean isWeekendEvent(DayOfWeek dayOfWeek, int date) { if (Event.주말_할인.isValid(date) && isWeekend(dayOfWeek)) { return true; } return false; } private boolean isWeekdayEvent(DayOfWeek dayOfWeek, int date) { if (Event.평일_할인.isValid(date) && !isWeekend(dayOfWeek)) { return true; } return false; } private boolean isWeekend(DayOfWeek dayOfWeek) { if (dayOfWeek.equals(DayOfWeek.FRIDAY) || dayOfWeek.equals(DayOfWeek.SATURDAY)) { return true; } return false; } private boolean isSpecialEvent(DayOfWeek dayOfWeek, int date) { if (Event.특별_할인.isValid(date) && (dayOfWeek.equals(DayOfWeek.SUNDAY) || date == CHRISTMAS)) { return true; } return false; } }
#include "SpriteBatch.hpp" #include "Log.h" namespace DroidBlaster { SpriteBatch::SpriteBatch(TimeManager &pTimeManager, Graphics::Manager &pGraphicsManager) : m_timeManager(pTimeManager), m_graphicsManager(pGraphicsManager), m_sprites(), m_spriteCount(0), m_vertices(), m_vertexCount(0), m_indexes(), m_indexCount(0), m_shaderProgram(0), aPosition(-1), aTexture(-1), uProjection(-1), uTexture(-1) { m_graphicsManager.registerComponent(this); } SpriteBatch::~SpriteBatch() { for (auto sprite: m_sprites) { delete sprite; } } Sprite * SpriteBatch::registerSprite(Resource &pTextureResource, int32_t pWidth, int32_t pHeight) { int32_t spriteCount = m_spriteCount; int32_t index = spriteCount * 4; // Первая вершина // Пересчитать содержимое индексного буфера m_indexes[m_indexCount++] = index + 0; m_indexes[m_indexCount++] = index + 1; m_indexes[m_indexCount++] = index + 2; m_indexes[m_indexCount++] = index + 2; m_indexes[m_indexCount++] = index + 1; m_indexes[m_indexCount++] = index + 3; // Добавить новый спрайт в массив m_sprites[m_spriteCount] = new Sprite(m_graphicsManager, pTextureResource, pWidth, pHeight); return m_sprites[m_spriteCount++]; } static const char *VERTEX_SHADER = "attribute vec4 aPosition;\n" "attribute vec2 aTexture;\n" "varying vec2 vTexture;\n" "uniform mat4 uProjection;\n" "void main() {\n" " vTexture = aTexture;\n" " gl_Position = uProjection * aPosition;\n" "}"; static const char *FRAGMENT_SHADER = "precision mediump float;\n" "varying vec2 vTexture;\n" "uniform sampler2D u_texture;\n" "void main() {\n" " gl_FragColor = texture2D(u_texture, vTexture);\n" "}"; status SpriteBatch::load() { m_shaderProgram = m_graphicsManager.loadShader(VERTEX_SHADER, FRAGMENT_SHADER); if (m_shaderProgram == 0) return STATUS_KO; aPosition = glGetAttribLocation(m_shaderProgram, "aPosition"); aTexture = glGetAttribLocation(m_shaderProgram, "aTexture"); uProjection = glGetUniformLocation(m_shaderProgram, "uProjection"); uTexture = glGetUniformLocation(m_shaderProgram, "u_texture"); // Загрузить спрайты for (int32_t i = 0; i != m_spriteCount; ++i) { if (m_sprites[i]->load(m_graphicsManager) != STATUS_OK) goto ERROR; } return STATUS_OK; ERROR: Log::error("Error loading sprite batch"); return STATUS_KO; } void SpriteBatch::draw() { glUseProgram(m_shaderProgram); glUniformMatrix4fv(uProjection, 1, GL_FALSE, m_graphicsManager.getProjectionMatrix()); glUniform1i(uTexture, 0); glEnableVertexAttribArray(aPosition); glVertexAttribPointer( aPosition, // индекс аттрибута 2, // размер в байтах (x и y) GL_FLOAT, // тип данных GL_FALSE, // признак нормализованности sizeof(Sprite::Vertex), // шаг &(m_vertices[0].x) // место ); glEnableVertexAttribArray(aTexture); glVertexAttribPointer( aTexture, // индекс аттрибута 2, // размер в байтах (u и v) GL_FLOAT, // тип данных GL_FALSE, // признак нормализованности sizeof(Sprite::Vertex), // шаг &(m_vertices[0].u) // место ); glEnable(GL_BLEND); glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); const int32_t vertexPerSprite = 4; const int32_t indexPerSprite = 6; float timeStep = m_timeManager.elapsed(); int32_t spriteCount = m_spriteCount; int32_t currentSprite = 0, firstSprite = 0; while (bool canDraw = (currentSprite < spriteCount)) { // Выбрать текстуру Sprite *sprite = m_sprites[currentSprite]; GLuint currentTexture = sprite->m_texture; glActiveTexture(GL_TEXTURE0); glBindTexture(GL_TEXTURE_2D, sprite->m_texture); // Сгенерировать вершины спрайтов с текущей текстурой do { sprite = m_sprites[currentSprite]; if (sprite->m_texture == currentTexture) { Sprite::Vertex *vertices = (&m_vertices[currentSprite * 4]); sprite->draw(vertices, timeStep); } else { break; } } while (canDraw = (++currentSprite < spriteCount)); glDrawElements( GL_TRIANGLES, (currentSprite - firstSprite) * indexPerSprite, // число индексов GL_UNSIGNED_SHORT, // тип данных в индексном буфере &m_indexes[firstSprite * indexPerSprite] // первый индекс ); firstSprite = currentSprite; } glUseProgram(0); glDisableVertexAttribArray(aPosition); glDisableVertexAttribArray(aTexture); glDisable(GL_BLEND); } }
// // NIBCalculatorStack.h // NIBCalculator // // Created by Lieu Vu on 9/27/17. // Copyright © 2017 LV. All rights reserved. // #import <Foundation/Foundation.h> NS_ASSUME_NONNULL_BEGIN /** `NIBCalculatorStack` acts as the stack data structure. */ @interface NIBCalculatorStack<ObjectType> : NSObject <NSCopying> /// ----------------- /// @name Utitilities /// ----------------- /** Push object to stack. @param object The object to push to the stack. */ - (void)push:(ObjectType)object; /** Pop object to stack. @return Returns the object at the top of the stack. */ - (ObjectType _Nullable)pop; /** Peek object of stack. It is used to look at the top of the stack without removing it from the stack. @return Returns the object at the top of the stack. */ - (ObjectType _Nullable)peek; /** Clear the stack. */ - (void)clear; @end NS_ASSUME_NONNULL_END
import React, { useState } from "react"; import "./Login.css"; import { Link, useNavigate } from "react-router-dom"; import { auth } from "./firebase"; function Login() { const [email, setEmail] = useState(""); const [password, setPassword] = useState(""); const navigate = useNavigate(); const signIn = (e) => { e.preventDefault(); auth.signInWithEmailAndPassword(email, password).then((auth) => { navigate("/"); }); }; const register = (e) => { e.preventDefault(); // Firebase register auth .createUserWithEmailAndPassword(email, password) .then((auth) => { console.log(auth); if (auth) { navigate("/"); } }) .catch((error) => alert(error.message)); }; return ( <div className="login"> <Link to="/"> <img className="login__logo" src="https://upload.wikimedia.org/wikipedia/commons/thumb/a/a9/Amazon_logo.svg/1024px-Amazon_logo.svg.png" alt="" /> </Link> <div className="login__container"> <h1>Sign-in</h1> <form> <h5>Email</h5> <input type="text" value={email} onChange={(e) => setEmail(e.target.value)} /> <h5>Password</h5> <input type="password" value={password} onChange={(e) => setPassword(e.target.value)} /> <button type="submit" className="login__signInButton" onClick={signIn} > Sign In </button> </form> <p> By singing-in you agree to the AMAZON CLONE Conditions of Use & Sale. Please see our Privacy Noice, our Cookies Noice and our Interest-Based Ads Notice. </p> <button className="login__registerButton" onClick={register}> Create your Amazon Account </button> </div> </div> ); } export default Login;
/** Angular Imports */ import { Component } from '@angular/core'; import { ActivatedRoute, Router } from '@angular/router'; import { MatDialog } from '@angular/material/dialog'; /** Custom Services */ import { LoansService } from 'app/loans/loans.service'; import { SettingsService } from 'app/settings/settings.service'; /** Custom Dialogs */ import { FormDialogComponent } from 'app/shared/form-dialog/form-dialog.component'; import { DeleteDialogComponent } from 'app/shared/delete-dialog/delete-dialog.component'; import { ConfirmationDialogComponent } from 'app/shared/confirmation-dialog/confirmation-dialog.component'; /** Custom Models */ import { FormfieldBase } from 'app/shared/form-dialog/formfield/model/formfield-base'; import { InputBase } from 'app/shared/form-dialog/formfield/model/input-base'; import { DatepickerBase } from 'app/shared/form-dialog/formfield/model/datepicker-base'; import { Dates } from 'app/core/utils/dates'; import { TranslateService } from '@ngx-translate/core'; /** * View Charge Component. */ @Component({ selector: 'mifosx-view-charge', templateUrl: './view-charge.component.html', styleUrls: ['./view-charge.component.scss'] }) export class ViewChargeComponent { /** Charge data. */ chargeData: any; /** Loans Account Data */ loansAccountData: any; allowPayCharge = true; allowWaive = true; /** * Retrieves the Charge data from `resolve`. * @param {LoansService} loansService Loans Service * @param {ActivatedRoute} route Activated Route. * @param {Router} router Router for navigation. * @param {MatDialog} dialog Dialog reference. * @param {Dates} dateUtils Date Utils. * @param {SettingsService} settingsService Settings Service */ constructor(private loansService: LoansService, private route: ActivatedRoute, private dateUtils: Dates, private router: Router, private translateService: TranslateService, public dialog: MatDialog, private settingsService: SettingsService) { this.route.data.subscribe((data: { loansAccountCharge: any, loanDetailsData: any }) => { this.chargeData = data.loansAccountCharge; this.allowPayCharge = (this.chargeData.chargePayable && !this.chargeData.paid); this.allowWaive = !this.chargeData.chargeTimeType.waived; this.loansAccountData = data.loanDetailsData; }); } /** * Pays the charge. */ payCharge() { const formfields: FormfieldBase[] = [ new DatepickerBase({ controlName: 'transactionDate', label: 'Payment Date', value: '', type: 'date', required: true }) ]; const data = { title: `Pay Charge ${this.chargeData.id}`, layout: { addButtonText: 'Confirm' }, formfields: formfields }; const payChargeDialogRef = this.dialog.open(FormDialogComponent, { data }); payChargeDialogRef.afterClosed().subscribe((response: any) => { if (response.data) { const locale = this.settingsService.language.code; const dateFormat = this.settingsService.dateFormat; const prevTransactionDate: Date = response.data.value.transactionDate; const dataObject = { transactionDate: this.dateUtils.formatDate(prevTransactionDate, dateFormat), dateFormat, locale }; this.loansService.executeLoansAccountChargesCommand(this.chargeData.loanId, 'pay', dataObject, this.chargeData.id) .subscribe(() => { this.reload(); }); } }); } /** * Waive's the charge */ waiveCharge() { const waiveChargeDialogRef = this.dialog.open(ConfirmationDialogComponent, { data: { heading: this.translateService.instant('labels.heading.Waive Charge'), dialogContext: this.translateService.instant('labels.dialogContext.Are you sure you want to waive charge with id:')` ${this.chargeData.id}`, type: 'Basic' } }); waiveChargeDialogRef.afterClosed().subscribe((response: any) => { if (response.confirm) { this.loansService.executeLoansAccountChargesCommand(this.chargeData.loanId, 'waive', {}, this.chargeData.id) .subscribe(() => { this.reload(); }); } }); } /** * Edits the charge */ editCharge() { const formfields: FormfieldBase[] = [ new InputBase({ controlName: 'amount', label: 'Amount', value: this.chargeData.amount || this.chargeData.amountOrPercentage, type: 'number', required: true }), new DatepickerBase({ controlName: 'dueDate', label: 'Due Date', value: new Date(this.chargeData.dueDate), type: 'date', maxDate: this.settingsService.maxAllowedDate, required: true }) ]; const data = { title: 'Edit Charge', layout: { addButtonText: 'Confirm' }, formfields: formfields }; const editChargeDialogRef = this.dialog.open(FormDialogComponent, { data }); editChargeDialogRef.afterClosed().subscribe((response: any) => { if (response.data) { const locale = this.settingsService.language.code; const dateFormat = this.settingsService.dateFormat; const dueDate = this.dateUtils.formatDate(response.data.value.dueDate, dateFormat); const amount = response.data.value.amount; const dataObject = { amount, dueDate, dateFormat, locale }; this.loansService.editLoansAccountCharge(this.loansAccountData.id, dataObject, this.chargeData.id) .subscribe(() => { this.reload(); }); } }); } /** * Deletes the charge */ deleteCharge() { const deleteChargeDialogRef = this.dialog.open(DeleteDialogComponent, { data: { deleteContext: `charge id:${this.chargeData.id}` } }); deleteChargeDialogRef.afterClosed().subscribe((response: any) => { if (response.delete) { this.loansService.deleteLoansAccountCharge(this.loansAccountData.id, this.chargeData.id) .subscribe(() => { this.reload(); }); } }); } loanChargeColor(): string { return this.chargeData.paid ? 'paid' : 'not-paid'; } adjustmentCharge(): void { this.router.navigate(['adjustment'], { relativeTo: this.route }); } /** * Refetches data fot the component * TODO: Replace by a custom reload component instead of hard-coded back-routing. */ private reload() { const clientId = this.loansAccountData.clientId; const url: string = this.router.url; this.router.navigateByUrl(`/clients/${clientId}/loans-accounts`, { skipLocationChange: true }) .then(() => this.router.navigate([url])); } }
import React, { useEffect, useState } from 'react'; import axios from 'axios'; import { toast } from 'react-toastify'; import SearchMap from '../Maps/SearchMap' import sunny from '../../resources/image/sunny.png' import cloudy from '../../resources/image/cloudy.png' import lightRain from '../../resources/image/lightrain.png' import heavyRain from '../../resources/image/heavyrain.png' declare global { interface Window { google: any; initMap: () => void; } } function MapOverlay() { const [weatherData, setWeatherData] = useState<any>(); const [rainData, setRainData] = useState<any>(); const [isForecastLoading, setIsForecastLoading] = useState<boolean>(true) const [isRainLoading, setIsRainLoading] = useState<boolean>(true) const [toggleView, setToggleView] = useState<boolean>(false) useEffect(() => { //async function to fetch 2 hr forecast data const fetchForecastData = async() => { try { const apiUrl = 'https://api.data.gov.sg/v1/environment/2-hour-weather-forecast'; await axios .get(apiUrl) .then((response) => { setWeatherData(response.data); setIsForecastLoading(false) }) .catch((error) => { console.error('Error:', error); }); } catch(error){ toast.error('Error: ' + error) } } fetchForecastData() //async function to fetch actual rainfall data const fetchActualData = async() => { try { const apiUrl = 'https://api.data.gov.sg/v1/environment/rainfall'; await axios .get(apiUrl) .then((response) => { setRainData(response.data); setIsRainLoading(false) }) .catch((error) => { console.error('Error:', error); }); } catch(error){ toast.error('Error: ' + error) } } fetchActualData() }, []); //ensure that the data is loaded before generating the google map if(isRainLoading === false && isForecastLoading === false){ const google = window.google; const script = window.document.createElement('script'); script.src = `https://maps.googleapis.com/maps/api/js?key=AIzaSyBVYfFNABDUezksK4S-2ceg8APDpbVIT8o&callback=initMap`; script.defer = true; script.async = true; window.document.head.appendChild(script); window.initMap = async () => { try{ //weather feature const mapOptions: google.maps.MapOptions = { center: { lat: 1.3521, lng: 103.8198 }, //starting position zoom: 10, }; const map = new google.maps.Map(document.getElementById('map') as HTMLElement, mapOptions); if(toggleView === true){ //marker and info window generation for 2 hour forecast data for(let i=0; i<weatherData.area_metadata.length; i++){ var weatherIcon = '' const weatherString: string = JSON.stringify(weatherData.items[0].forecasts[i].forecast) if(weatherString.includes('sun')){ weatherIcon = sunny } else if(weatherString.includes('Cloudy')){ weatherIcon = cloudy } else if(weatherString.includes('Showers')){ weatherIcon = lightRain } else{ weatherIcon = heavyRain } const marker = new google.maps.Marker( { position: new google.maps.LatLng(weatherData.area_metadata[i].label_location.latitude, weatherData.area_metadata[i].label_location.longitude), icon: weatherIcon, map: map, } ); const contentString = '<div>' + '<h1>' + weatherData.area_metadata[i].name + '</h1>' + '<h2> 2 hour forecast: ' + weatherData.items[0].forecasts[i].forecast + '</h2>' + '</div>' const infowindow = new google.maps.InfoWindow({ content: contentString }); marker.addListener('click', () => { infowindow.open(map, marker); }); } } else if(toggleView === false){ //marker and info window generation for actual rainfall data for(let i=0; i<rainData.metadata.stations.length; i++){ var weatherIcon = '' if(rainData.items[0].readings[i].value === 0){ weatherIcon = sunny } else if(rainData.items[0].readings[i].value < 1){ weatherIcon = cloudy } else if(rainData.items[0].readings[i].value < 10){ weatherIcon = lightRain } else{ weatherIcon = heavyRain } const marker = new google.maps.Marker( { position: new google.maps.LatLng(rainData.metadata.stations[i].location.latitude, rainData.metadata.stations[i].location.longitude), icon: weatherIcon, map: map, } ); } } //search bar const input = document.getElementById('pac-input') as HTMLInputElement; const searchBox = new google.maps.places.SearchBox(input); map.controls[google.maps.ControlPosition.TOP_LEFT].push(input); map.addListener('bounds_changed', function () { searchBox.setBounds(map.getBounds() as google.maps.LatLngBounds); }); let markers: google.maps.Marker[] = []; searchBox.addListener('places_changed', function () { const places = searchBox.getPlaces(); if (places.length === 0) { return; } markers.forEach(function (marker) { marker.setMap(null); }); markers = []; const bounds = new google.maps.LatLngBounds(); places.forEach(function (place: { geometry: { location: any; viewport: any; }; name: any; }) { if (!place.geometry) { console.log("Returned place contains no geometry"); return; } markers.push(new google.maps.Marker({ map: map, title: place.name, position: place.geometry.location })); if (place.geometry.viewport) { bounds.union(place.geometry.viewport); } else { bounds.extend(place.geometry.location); } }); map.fitBounds(bounds); }); } catch (error){ console.error('Error in initMap: ', error) } }; } const swapView = () => { if(toggleView === true){ setToggleView(false) } else if(toggleView === false){ setToggleView(true) } } return( <> <div id="map" style={{ width: '100%', height: '500px' }} /> <button onClick={swapView} style={{padding: '1rem', margin: '1rem'}}> {toggleView? ( 'Realtime Rainfall' ) : ( '2 Hour Forecast' )} </button> </> ) } export default MapOverlay;
import React, { useEffect, useState } from "react"; import { BsFillPauseFill, BsFillPlayFill } from "react-icons/bs"; import { useDispatch } from "react-redux"; import { useNavigate, useParams } from "react-router-dom"; import { getPlaylist } from "../../apis/playlist/getPlaylist"; import FavoriteButton from "../../components/buttons/FavoriteButton"; import Follow from "../../components/buttons/FollowButton"; import Comment from "../../components/comment/Comment"; import SideBar from "../../components/side-bar/SideBar"; import Waveform from "../../components/waveform/Waveform"; const PlaylistPage = ({ playlist }) => { const { playlistId } = useParams(); const [track, setTrack] = useState(""); const [comments, setComments] = useState(""); const [isPlaying, setIsPlaying] = useState(false); const dispatch = useDispatch(); const navigate = useNavigate(); const toggleAudio = () => { dispatch({ type: "PLAY_TRACK", track: track, }); dispatch({ type: "APPEND_HISTORY", track: track, }); dispatch({ type: "SET_QUEUE", track: track, }); }; // useEffect(() => { // if (!currentSong || currentSong.audioUrl != track.audioUrl) { // setIsPlaying(false); // } else { // setIsPlaying(currentSong.isPlaying); // } // }, [currentSong]); useEffect(() => { const getTrackOnInitial = async () => { try { const response = await getPlaylist(playlistId); if (response.status == 404) { navigate("/not-found"); return; } const track = await response.json(); setTrack(track); setComments(track.comments); } catch (e) { console.error(e); } }; getTrackOnInitial(); }, []); return ( <> {track ? ( <div> <div className="w-full bg-gradient-to-tl from-[#A19793] to-[#827A60] p-5 flex flex-row justify-between items-center"> <div className="w-full h-full flex flex-col justify-start"> <div className="flex flex-row mb-[150px]"> {/* play button */} <button className="rounded-full bg-[#f30] h-[60px] w-[60px] flex justify-center items-center mr-5" onClick={toggleAudio} > {/* play btn */} {!isPlaying ? ( <BsFillPlayFill className="text-white" size={40} /> ) : ( <BsFillPauseFill className="text-white" size={40} /> )} {/* <FaPlay className="text-white" /> */} </button> <div> <p className="text-white text-xl bg-black p-2 w-fit mb-2"> {track.name} </p> <p className="username text-gray-300 text-sm bg-black p-3 w-fit mb-2"> {track.user.username} </p> </div> </div> <Waveform audioUrl={track.audioUrl} /> </div> {/* track cover */} <img src={track.coverUrl} className="w-[340px] h-[340px] ml-5" /> </div> <div className="flex pl-8 pr-8"> <div className="w-[72%] border-r-[1px] border-solid pt-3 pr-8"> {/* interact button */} <FavoriteButton haveBorder={true} haveText={true} /> {/* comments and artist summary */} <div className="flex flex-row justify-between mt-2"> {/* artist summary */} <div className="mr-5 min-w-fit"> <img src={track.user.avatarUrl} className="w-[120px] h-[120px] rounded-full" /> <h3 className="text-sm mb-2 mt-2">{track.user.username}</h3> {/* follow button */} <Follow user={track.user} /> </div> <div className="w-full"> <div className="border-b w-full"> <p>{Object.keys(track.comments).length} comments</p> </div> {comments.map((comment, index) => ( <Comment comment={comment} key={index} /> ))} </div> </div> </div> <div className="w-[28%] pl-8 pt-8 text-[#999] text-[14px]"> <SideBar /> </div> </div> </div> ) : ( <img src="../../assets/images/loading-gif.gif" /> )} </> ); }; export default PlaylistPage;
- What is SSMS? SQL Server Management Studio (SSMS) is an integrated environment for managing any SQL infrastructure. Use SSMS to access, configure, manage, administer, and develop all components of SQL Server, Azure SQL Database , Azure SQL Managed Instance, SQL Server on Azure VM, and Azure Synapse Analytics. SSMS provides a single comprehensive utility that combines a broad group of graphical tools with many rich script editors to provide access to SQL Server for developers and database administrators of all skill levels. - SQL Server Management Studio components * Use Object Explorer to view and manage all of the objects in one or more instances of SQL Server. * Use Template Explorer to build and manage files of boilerplate text that you use to speed the development of queries and scripts. * Use the deprecated Solution Explorer to build projects used to manage administration items such as scripts and queries. * Use the visual design tools included in Management Studio to build queries, tables, and diagram databases. * Use the Management Studio language editors to interactively build and debug queries and scripts with Query and Text Editors - Logging on to Database (On-Primises) You must provide the correct credentials to access your database * Server Name: . -- Note: Which means 'on this pc' * Authentication: Windows Authentication -> This means your authenticating from your computers login -- Note: There are many kinds of authentication types. Depending on the database your connected to you may have to use the one of the other types, but they will require a User Name & Password to access. ******* EB After this section you'll fill this out. Use the structure i have in all these documents. Remember be detailed ****** - Create a Database What are the rules and naming conventions? In creating a database we have to be precise in naming the whole database. Being short and precise will make it easy for us to diffrentiate one databse from the other. The name can contain letters a-z,all characters like underscore(_),brackets(),parenthesis{},etc... The first letter of the database(DB) should in a upper case and the rest will be in lower case. After naming the Data Base we shall end it with DB, with no space in between. Example :- ReservationDB AkluBakeryDB CrewsDB What are the steps? In creating a DB we follow the following steps STEP 1) Open our SQL SERVER MANAGEMENT STUDIO (SSMS) STEP 2) we connect to our server which is on premise. STEP 3) we go to our Object Explorer (which is on the left side of our screen) and right click the (+) button on the Databases folder to show existing databases if any. STEP 4) after right clicking the database folder we will get a dialogue box with options of New Database..., we click on that option. STEP 5) A new page will appear on the screen with the cursour on the Databse Name. STEP 6) After the database is given a name in the "Owner" textbox underneith you make the owner sa. This ensures full access to the database. "sa" stands for Server Administrator. STEP 7) After naming our database short and precisely we click on the OK button on the right bottom of our new opened up screen. - Creating a Table What are the rules and naming conventions? In naming tables we have to be extra carefull ,because when we quiery to find results the tables are the main source of data. We can use alphabets A-Z,characters like (_),() and etc... We can use both singular and plurar conventions. I prefer to use plurar names and nounes in naming my tables. Example- Ratings, Expenses,Restaurants ,Products etc... If there is a need to use more than 1 word to describe what is in the table, DO IT. Example In the 'RestaurantCuisines' table we cant only use 'Restauant' because we already have a table named Restaurant in our DB, the same goes for cuisines. Naming it either of the two wouldnt clearly describe what is in the table.'RestasurantCuisines' is the right and correct way for naming this table. What are the steps? In creating TABLES we use the following steps STEP 1) We first go to our explorer and click on our databse which was created as xxxxxDB and click on the plus(+) sign. STEP 2) After we clicked the plus sign there will be a drop down of Database Diagrams,Tables,views,External Resources etc..,we go to the tables folder and Right Click on the plus (+) sign. STEP 3) After the right click we will get an options of New, Filter etc..., we go to New --then click on New Table... STEP 4) After we wait for the loading to stop we get a new screen next to our explorer with Coloumn Name, Data Type AND Allow Nulls. STEP 5) NOW we fill our datas as we want with the apporpraite naming conventions and data types. What is a Primary Key (PK), How do you set it, And what is it used for. Primary Keys uniquely identfies each record in a table. Primary Keys must contain unique values and cannot contain Null VALUES. A table can have only 1 primary key. A DB must have a primary key for options to INSERT,UPDATE,DELETE,JOIN etc.. SEETING UP PRIMARY KEY Setting up primary key is preety much easy what we have to do is we go to our coloumns in our already created table and choose the data we want to set as primary key and go to the right side of the field and RIGHT CLICK on it. we will then get option of SET PRIMARY KEY, we click on it and where done. After seeting up our primary key we will find a key sign before the field selected as Primary key. What are the primary data types and give examples of what data type is used for what type of data: Example: -> nvarchar(50) : This is used with data that is text. The parentheses denotes the maximum number of charaters this column can have. -> int : This is used with data that is numbers. examples are XxxxID, Age, Weight etc... -> money : This is used with data that is price. Price of any product Example cars,bread,beer anything that has price uses this data type. -> text : This is used with letters. Anything Thats letters from a-z. Example Name, Last Name etc... -> bit : This is used with a YES OR NO answers. bit is only true or false. Examples are Is Active, Stock Availability. If you allow nulls, then that's three values. true (1), false (0), null. What does null indicate with a column being called InActive. They either are or not. Just like a order. Is it IsComplete? thats a yes or no. You can't have a null order Shortcut to local database ** Note: if you add a '.' to server name when connecting to the server, ssms will instantly connect to your local database Importing & Exporting Data ** Note: The newer version of SSMS Import Data wizard errors out with 64bit systems. You have to make sure you have installed the 64bit version on your PC. This is usually by adding Visual Studio IDE and selecting the SQL Database options in the download options. If you want to use the import wizard that's defaulted you have to uninstall Office 64bit version and install Office 32bit version. If not you'll have to use the following steps below to use the 64bit import wizard. Creating a custom shortcut to SSMS - In this example we will create an shortcut to the 64bit version of the Import Data wizard. Step 1: In your Windows Operating systems search bar, search for "Import". This should show you the "SQL Server 20xx Import & Export Data (64bit)" Application. Step 2: Right click application and select "Open File location" option. This will take you to the shortcut "SQL Server 20xx Import and Export Data (64bit). Right click the short cut and select "Open File Location" again. This will take you to the Microsoft SQL Server sub-folder (Binn) that has the Import Executible "DTSWizard.exe". Copy this folder path. You will need it to create the custom shortcut Step 3: Open up SQL Server Management Studios (SSMS), select "Tools" from top menu and select "External Tools" option. Give the link a Title (ex: Import and Export Data) and in the Command section paste the folder path from Step 2 and hit the '...' button. This will open up the folder and select the DTSWizard.exe, hit open. Step 4: Hit Apply and OK. Go to "Tool" menu again and you will see the new link to the 64bit version of the Wizard that will work with SSMS.
import React, { lazy, Suspense } from "react"; import { BrowserRouter as Router, Routes, Route, useNavigate, } from "react-router-dom"; import "./App.css"; import { Toaster } from "react-hot-toast"; import { useParams } from "react-router-dom"; import Navbar from "./components/Navbar/Navbar"; import Chat from "./components/Chat/Chat"; import Loader from "./components/Loader/Loader"; import Footer from "./components/Footer/Footer"; import HomePage from "./pages/HomePage/HomePage"; // import Home from "./pages/Home/Home"; // import About from "./pages/About/About"; // import Blog from "./pages/Blog/Blog"; // import BlogDetail from "./pages/BlogDetails/BlogDetail"; // import Contact from "./pages/Contact/Contact"; // import Brokers from "./pages/Brokers/Brokers"; // import Mesh from "./pages/Mesh/Mesh"; // import Write from "./pages/Write/Write"; // import Register from "./pages/Authentication/Register"; // import Login from "./pages/Authentication/Login"; // Use lazy to import components dynamically // const HomePage = lazy(() => import("./pages/HomePage/HomePage")); // const Home = lazy(() => import("./pages/Home/Home")); const About = lazy(() => import("./pages/About/About")); const Blog = lazy(() => import("./pages/Blog/Blog")); const BlogDetail = lazy(() => import("./pages/BlogDetails/BlogDetail")); const Contact = lazy(() => import("./pages/Contact/Contact")); const Brokers = lazy(() => import("./pages/Brokers/Brokers")); const Mesh = lazy(() => import("./pages/Mesh/Mesh")); const Write = lazy(() => import("./pages/Write/Write")); const Register = lazy(() => import("./pages/Authentication/Register")); const Login = lazy(() => import("./pages/Authentication/Login")); function App() { const BlogDetailWrapper = () => { const { id } = useParams(); // Extract the postId from the route parameters return <BlogDetail postId={id} />; }; return ( <section className="App"> <Router> <Navbar /> <div className="content"> <Suspense fallback={<Loader />}> <Routes> <Route path="/" element={<HomePage />}></Route> {/* <Route path="/home" element={<Home />}></Route> */} <Route path="/about" element={<About />}></Route> <Route path="/blog" element={<Blog />}></Route> {/* <Route path="/blog/:id" element={<BlogDetail />}></Route> */} <Route path="/blog/:id" element={<BlogDetailWrapper />} /> <Route path="/contact" element={<Contact />}></Route> <Route path="/brokers" element={<Brokers />}></Route> <Route path="/mesh" element={<Mesh />}></Route> {/* <Route path="/write" element={<Write />}></Route> */} {/* <Route path="/write/:postId?" element={<Write />} /> */} <Route path="/write/:postId?" element={<Write postId={useParams().postId || undefined} />} // Pass the postId as a prop /> <Route path="/register" element={<Register />}></Route> <Route path="/login" element={<Login />}></Route> </Routes> <Chat /> <Footer /> </Suspense> </div> <Toaster /> </Router> </section> ); } export default App;
import store from "../../../store"; import { fallbackArray } from "../../utils/array"; import { buildNum } from "../../utils/format"; import { getSequence } from "../../utils/math"; const requirementStat = 'farm_seedBox'; const requirementBase = () => store.state.upgrade.item[requirementStat].highestLevel; export default { seedBox: {cap: 19, hideCap: true, price(lvl) { return [ {farm_vegetable: 70}, {farm_fruit: 150}, {farm_grain: 260}, {farm_flower: 800, farm_gold: 1}, {farm_vegetable: 4600}, {farm_fruit: buildNum(50, 'K')}, {farm_grain: buildNum(335, 'K')}, {farm_flower: buildNum(2, 'M')}, {farm_vegetable: buildNum(17.5, 'M')}, {farm_fruit: buildNum(120, 'M')}, {farm_grain: buildNum(900, 'M')}, {farm_flower: buildNum(7.2, 'B')}, {farm_vegetable: buildNum(54, 'B')}, {farm_fruit: buildNum(370, 'B')}, {farm_grain: buildNum(2.2, 'T')}, {farm_flower: buildNum(35, 'T')}, {farm_vegetable: buildNum(875, 'T')}, {farm_fruit: buildNum(3.1, 'Qa')}, {farm_grain: buildNum(130, 'Qa')} ][lvl]; }, effect: [ {name: 'blueberry', type: 'farmSeed', value: lvl => lvl >= 1}, {name: 'wheat', type: 'farmSeed', value: lvl => lvl >= 2}, {name: 'tulip', type: 'farmSeed', value: lvl => lvl >= 3}, {name: 'potato', type: 'farmSeed', value: lvl => lvl >= 4}, {name: 'raspberry', type: 'farmSeed', value: lvl => lvl >= 5}, {name: 'barley', type: 'farmSeed', value: lvl => lvl >= 6}, {name: 'dandelion', type: 'farmSeed', value: lvl => lvl >= 7}, {name: 'corn', type: 'farmSeed', value: lvl => lvl >= 8}, {name: 'watermelon', type: 'farmSeed', value: lvl => lvl >= 9}, {name: 'rice', type: 'farmSeed', value: lvl => lvl >= 10}, {name: 'rose', type: 'farmSeed', value: lvl => lvl >= 11}, {name: 'leek', type: 'farmSeed', value: lvl => lvl >= 12}, {name: 'honeymelon', type: 'farmSeed', value: lvl => lvl >= 13}, {name: 'rye', type: 'farmSeed', value: lvl => lvl >= 14}, {name: 'daisy', type: 'farmSeed', value: lvl => lvl >= 15}, {name: 'cucumber', type: 'farmSeed', value: lvl => lvl >= 16}, {name: 'grapes', type: 'farmSeed', value: lvl => lvl >= 17}, {name: 'hops', type: 'farmSeed', value: lvl => lvl >= 18}, {name: 'violet', type: 'farmSeed', value: lvl => lvl >= 19} ]}, fertility: {requirementBase, requirementStat, requirementValue: 1, price(lvl) { return {farm_vegetable: 50 * Math.pow(lvl * 0.005 + 1.3, lvl), farm_fruit: 50 * Math.pow(lvl * 0.005 + 1.3, lvl)}; }, effect: [ {name: 'farmCropGain', type: 'mult', value: lvl => Math.pow(1.1, lvl)} ]}, overgrowth: {cap: 9, requirementBase, requirementStat, requirementValue: 1, price(lvl) { return fallbackArray([ {farm_fruit: 200}, {farm_grain: 850, farm_flower: 1300}, ], {farm_flower: 240 * Math.pow(5 + lvl, lvl)}, lvl); }, effect: [ {name: 'farmOvergrow', type: 'base', value: lvl => lvl >= 1 ? (lvl * 0.05 + 0.05) : null} ]}, expansion: {cap: 45, requirementBase, requirementStat, requirementValue: 2, price(lvl) { return {farm_grain: 300 * Math.pow(lvl * 0.05 + 2, lvl)}; }, effect: [ {name: 'farmTiles', type: 'farmTile', value: lvl => lvl} ]}, gardenGnome: {cap: 5, hasDescription: true, requirementBase, requirementStat, requirementValue: 3, price(lvl) { return {farm_vegetable: 500 * Math.pow(96, lvl), farm_fruit: 500 * Math.pow(96, lvl), farm_flower: 1000 * Math.pow(128, lvl)}; }, effect: [ {name: 'gardenGnome', type: 'farmBuilding', value: lvl => lvl}, {name: 'farmDisableEarlyGame', type: 'unlock', value: lvl => lvl >= 1} ]}, learning: {cap: 1, hasDescription: true, requirementBase, requirementStat, requirementValue: 4, price() { return {farm_gold: 1}; }, effect: [ {name: 'farmCropExp', type: 'unlock', value: lvl => lvl >= 1} ]}, manure: {cap: 1, requirement() { return store.state.upgrade.item.farm_learning.level >= 1; }, price() { return {farm_gold: 5}; }, effect: [ {name: 'farmFertilizer', type: 'unlock', value: lvl => lvl >= 1} ]}, groundSeeds: {requirementBase, requirementStat, requirementValue: 5, price(lvl) { return {farm_flower: 6000 * Math.pow(1.75, lvl), farm_seedHull: Math.round(4 * lvl * Math.pow(1.1, Math.max(0, lvl - 10)) + 10)}; }, effect: [ {name: 'currencyFarmGrainGain', type: 'mult', value: lvl => lvl * 0.15 + 1}, {name: 'farmOvergrow', type: 'base', value: lvl => lvl * 0.01} ]}, roastedSeeds: {cap: 5, requirementBase, requirementStat, requirementValue: 5, price(lvl) { return {farm_seedHull: Math.round(Math.pow(1.8, lvl) * 4)}; }, effect: [ {name: 'farmExperience', type: 'base', value: lvl => lvl * 0.1} ]}, hayBales: {requirementBase, requirementStat, requirementValue: 5, price(lvl) { return {farm_grass: lvl * 125 + 75}; }, effect: [ {name: 'currencyFarmGrassCap', type: 'base', value: lvl => lvl * 100} ]}, smallCrate: {cap: 7, capMult: true, requirementBase, requirementStat, requirementValue: 6, price(lvl) { return {farm_fruit: buildNum(24.5, 'K') * Math.pow(1.9, lvl)}; }, effect: [ {name: 'currencyFarmSeedHullCap', type: 'base', value: lvl => lvl * 10} ]}, sprinkler: {cap: 2, hasDescription: true, note: 'farm_8', requirementBase, requirementStat, requirementValue: 6, price(lvl) { return {farm_vegetable: buildNum(120, 'K') * Math.pow(buildNum(4, 'M'), lvl), farm_seedHull: 50 * Math.pow(10, lvl)}; }, effect: [ {name: 'sprinkler', type: 'farmBuilding', value: lvl => lvl} ]}, magnifyingGlass: {cap: 20, requirementBase, requirementStat, requirementValue: 7, price(lvl) { return {farm_grain: buildNum(54, 'K') * Math.pow(lvl * 0.1 + 2, lvl), farm_flower: buildNum(33, 'K') * Math.pow(lvl * 0.1 + 2, lvl)}; }, effect: [ {name: 'farmExperience', type: 'mult', value: lvl => lvl * 0.1 + 1} ]}, scarecrow: {cap: 10, capMult: true, requirementBase, requirementStat, requirementValue: 7, price(lvl) { return {farm_grain: buildNum(110, 'K') * Math.pow(1.8, lvl), farm_petal: Math.round(Math.pow(1.4, lvl) * 3), farm_gold: 6 + lvl}; }, effect: [ {name: 'farmCropGain', type: 'mult', value: lvl => lvl * 0.1 + 1}, {name: 'currencyFarmPetalCap', type: 'base', value: lvl => lvl * 3} ]}, bugPowder: {requirementBase, requirementStat, requirementValue: 8, price(lvl) { return {farm_grain: buildNum(675, 'K') * Math.pow(1.75, lvl), farm_bug: Math.round(5 * lvl * Math.pow(1.1, Math.max(0, lvl - 10)) + 10)}; }, effect: [ {name: 'currencyFarmVegetableGain', type: 'mult', value: lvl => lvl * 0.15 + 1} ]}, shed: {cap: 10, capMult: true, requirementBase, requirementStat, requirementValue: 8, price(lvl) { return {farm_seedHull: 5 * getSequence(3, lvl) + 35, farm_bug: 5 * getSequence(3, lvl) + 35, farm_petal: 4 * getSequence(1, lvl) + 10}; }, effect: [ {name: 'currencyFarmSeedHullCap', type: 'base', value: lvl => lvl * 20}, {name: 'currencyFarmBugCap', type: 'base', value: lvl => lvl * 20}, {name: 'currencyFarmPetalCap', type: 'base', value: lvl => lvl * 10} ]}, lectern: {cap: 2, hasDescription: true, note: 'farm_12', requirementBase, requirementStat, requirementValue: 9, price(lvl) { return {farm_flower: buildNum(3.5, 'M') * Math.pow(buildNum(3, 'M'), lvl), farm_petal: 75 * Math.pow(5, lvl)}; }, effect: [ {name: 'lectern', type: 'farmBuilding', value: lvl => lvl} ]}, perfume: {cap: 25, note: 'farm_13', requirementBase, requirementStat, requirementValue: 9, price(lvl) { return {farm_bug: Math.round(5 * lvl * Math.pow(1.1, Math.max(0, lvl - 10)) + 10), farm_butterfly: Math.round(lvl * Math.pow(1.1, Math.max(0, lvl - 10)) + 2)}; }, effect: [ {name: 'currencyFarmFruitGain', type: 'mult', value: lvl => lvl * 0.15 + 1}, {name: 'farmRareDropChance', type: 'base', value: lvl => lvl * 0.002} ]}, mediumCrate: {cap: 8, capMult: true, requirementBase, requirementStat, requirementValue: 10, price(lvl) { return {farm_vegetable: buildNum(90, 'M') * Math.pow(1.75, lvl), farm_grain: buildNum(54, 'M') * Math.pow(2.1, lvl)}; }, effect: [ {name: 'currencyFarmSeedHullCap', type: 'base', value: lvl => lvl * 25}, {name: 'currencyFarmGrassCap', type: 'base', value: lvl => lvl * 40} ]}, stompedSeeds: {requirementBase, requirementStat, requirementValue: 10, price(lvl) { return {farm_seedHull: Math.round(Math.pow(1.15, lvl) * 150)}; }, effect: [ {name: 'farmCropGain', type: 'mult', value: lvl => Math.pow(1.12, lvl)} ]}, insectParadise: {cap: 6, capMult: true, requirementBase, requirementStat, requirementValue: 11, price(lvl) { return {farm_fruit: buildNum(750, 'M') * Math.pow(2.4, lvl), farm_petal: Math.round(Math.pow(1.75, lvl) * 11)}; }, effect: [ {name: 'currencyFarmBugCap', type: 'base', value: lvl => lvl * 40}, {name: 'currencyFarmButterflyCap', type: 'base', value: lvl => lvl * 5}, {name: 'currencyFarmLadybugCap', type: 'base', value: lvl => lvl * 30} ]}, goldenTools: {requirementBase, requirementStat, requirementValue: 11, price(lvl) { return {farm_gold: Math.round(Math.pow(1.25, lvl) * 350)}; }, effect: [ {name: 'farmCropGain', type: 'mult', value: lvl => lvl * 0.1 + 1} ]}, butterflyWings: {cap: 6, requirementBase, requirementStat, requirementValue: 12, price(lvl) { return {farm_butterfly: Math.round(Math.pow(1.35, lvl) * 14)}; }, effect: [ {name: 'currencyFarmPetalCap', type: 'base', value: lvl => lvl * 15} ]}, fertileGround: {requirementBase, requirementStat, requirementValue: 12, price(lvl) { return {farm_fruit: buildNum(4, 'B') * Math.pow(2.25, lvl), farm_flower: buildNum(3.3, 'B') * Math.pow(2.25, lvl)}; }, effect: [ {name: 'currencyFarmVegetableGain', type: 'mult', value: lvl => lvl * 0.1 + 1} ]}, pinwheel: {cap: 1, hasDescription: true, note: 'farm_17', requirementBase, requirementStat, requirementValue: 13, price() { return {farm_flower: buildNum(250, 'B'), farm_petal: 150, farm_ladybug: 50}; }, effect: [ {name: 'pinwheel', type: 'farmBuilding', value: lvl => lvl} ]}, mysticGround: {requirementBase, requirementStat, requirementValue: 13, price(lvl) { return {farm_vegetable: buildNum(37.5, 'B') * Math.pow(2.25, lvl), farm_ladybug: Math.round(Math.pow(1.12, lvl) * 10)}; }, effect: [ {name: 'currencyFarmGrainGain', type: 'mult', value: lvl => lvl * 0.1 + 1}, {name: 'currencyFarmLadybugCap', type: 'base', value: lvl => lvl * 20} ]}, fertilizerBag: {cap: 1, requirementBase, requirementStat, requirementValue: 14, price() { return {farm_gold: 700}; }, effect: [ {name: 'farm_weedKiller', type: 'findConsumable', value: lvl => lvl >= 1}, {name: 'farm_turboGrow', type: 'findConsumable', value: lvl => lvl >= 1}, {name: 'farm_premium', type: 'findConsumable', value: lvl => lvl >= 1} ]}, bigCrate: {cap: 10, capMult: true, requirementBase, requirementStat, requirementValue: 14, price(lvl) { return {farm_fruit: buildNum(190, 'B') * Math.pow(1.85, lvl), farm_grain: buildNum(240, 'B') * Math.pow(1.85, lvl)}; }, effect: [ {name: 'currencyFarmSeedHullCap', type: 'base', value: lvl => lvl * 60}, {name: 'currencyFarmGrassCap', type: 'base', value: lvl => lvl * 80}, {name: 'currencyFarmPetalCap', type: 'base', value: lvl => lvl * 25} ]}, artificialWebs: {cap: 3, requirementBase, requirementStat, requirementValue: 15, price(lvl) { return {farm_flower: buildNum(1, 'T') * Math.pow(9, lvl), farm_ladybug: Math.round(Math.pow(1.5, lvl) * 100)}; }, effect: [ {name: 'currencyFarmSpiderCap', type: 'base', value: lvl => lvl * 4} ]}, studyInsects: {cap: 10, requirementBase, requirementStat, requirementValue: 15, price(lvl) { return {farm_fruit: buildNum(1.35, 'T') * Math.pow(2.65, lvl), farm_butterfly: Math.round(Math.pow(1.25, lvl) * 28)}; }, effect: [ {name: 'farmExperience', type: 'mult', value: lvl => lvl * 0.1 + 1} ]}, beehive: {cap: 20, requirementBase, requirementStat, requirementValue: 16, price(lvl) { return {farm_flower: buildNum(22.5, 'T') * Math.pow(1.4, lvl), farm_seedHull: Math.round(Math.pow(1.14, lvl) * 280), farm_bug: Math.round(Math.pow(1.16, lvl) * 160)}; }, effect: [ {name: 'currencyFarmSpiderCap', type: 'base', value: lvl => lvl}, {name: 'currencyFarmBeeCap', type: 'base', value: lvl => lvl * 200} ]}, flag: {cap: 1, hasDescription: true, note: 'farm_20', requirementBase, requirementStat, requirementValue: 18, price() { return {farm_spider: 50, farm_bee: 2500, farm_goldenPetal: 10}; }, effect: [ {name: 'flag', type: 'farmBuilding', value: lvl => lvl} ]}, }
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Tugas 4a Internet dan Teknologi Web - Latihan Box Model</title> <link rel="stylesheet" href="T4b233040075.css"> </head> <body> <nav class="navbar"> <div class="content-navbar"> <h1 class="judul">My Article</h1> <ul> <li><a href="#intro">Pendahuluan</a></li> <li><a href="#what">Apa itu JavaScript?</a></li> <li><a href="#history">Sejarah JavaScript</a></li> <li><a href="#why">Kenapa harus JavaScript?</a></li> </ul> </div> </nav> <div class="container"> <div class="hero"></div> <div class="content"> <h2 id="intro">JavaScript</h2> <p class="penulis">ditulis oleh <a href="https://www.dicoding.com/blog/apa-itu-bahasa-pemrograman-javascript/">Dicoding Indonesia</a>. pada 24 April 2021</p> <p>JavaScript adalah bahasa pemrograman tingkat tinggi yang pada awalnya dikembangkan untuk membuat website menjadi lebih “hidup”. Bersama dengan HTML dan CSS, JavaScript menjadi bahasa pemrograman paling populer untuk mengembangkan aplikasi berbasis web. Bahasa ini mampu memberikan logic ke dalam website, sehingga website tersebut memiliki fungsionalitas tambahan dan lebih interaktif. Pada artikel kali ini, kita akan bahas mengenai “Apa itu bahasa pemrograman JavaScript?”, serta sejarah dan alasan untuk mempelajarinya.</p> <p>JavaScript adalah bahasa pemrograman tingkat tinggi yang pada awalnya dikembangkan untuk membuat website menjadi lebih “hidup”. Bersama dengan HTML dan CSS, JavaScript menjadi bahasa pemrograman paling populer untuk mengembangkan aplikasi berbasis web. Bahasa ini mampu memberikan logic ke dalam website, sehingga website tersebut memiliki fungsionalitas tambahan dan lebih interaktif. Pada artikel kali ini, kita akan bahas mengenai “Apa itu bahasa pemrograman JavaScript?”, serta sejarah dan alasan untuk mempelajarinya.</p> <h2 id="what">Apa itu bahasa pemrograman JavaScript?</h2> <p>JavaScript termasuk ke dalam kategori scripting language. Apa maksudnya? Salah satu ciri-ciri utama dari bahasa scripting adalah kode tidak perlu dikompilasi agar bisa dijalankan. Scripting language menggunakan interpreter untuk menerjemahkan kode atau perintah yang kita tulis supaya dimengerti oleh mesin.</p> <p>Itulah kenapa bahasa scripting tidak membutuhkan banyak kode yang perlu ditulis agar sebuah program bisa dijalankan. Hanya dengan satu baris kode berikut Anda sudah bisa membuat program yang menampilkan teks “Hello, World!” ke layar</p> <h2 id="history">Sejarah JavaScript?</h2> <p>JavaScript dibuat pada tahun 1995 oleh Brendan Eich, programmer dari Netscape. Bahasa ini awalnya dinamai “Mocha” kemudian berubah menjadi “LiveScript”. Pada saat itu bahasa Java merupakan bahasa pemrograman yang paling populer. Untuk memanfaatkan kepopulerannya, nama LiveScript pun diubah menjadi “JavaScript”. Jadi, meskipun namanya mirip, JavaScript tidak ada hubungannya dengan bahasa pemrograman Java.</p> <p>Setelah diadopsi di luar Netscape, JavaScript distandarisasi oleh European Computer Manufacturers Association (ECMA). Sejak saat itu JavaScript juga dikenal dengan ECMAScript. Meskipun begitu, masih banyak yang menyebutnya dengan JavaScript hingga saat ini.</p> <p>Terdapat beberapa versi JavaScript yang sudah distandarisasi oleh ECMAScript. Pada tahun 2000 hingga 2010, ECMAScript 3 merupakan versi yang banyak digunakan ketika JavaScript sedang mendominasi. Selama waktu tersebut, ECMAScript 4 sedang dalam proses pengembangan dengan harapan akan memberikan improvisasi yang cukup signifikan. Namun, ambisi tersebut tidak berjalan mulus sehingga pada tahun 2008 pengembangan ECMAScript dihentikan.</p> <p>Terdapat beberapa versi JavaScript yang sudah distandarisasi oleh ECMAScript. Pada tahun 2000 hingga 2010, ECMAScript 3 merupakan versi yang banyak digunakan ketika JavaScript sedang mendominasi. Selama waktu tersebut, ECMAScript 4 sedang dalam proses pengembangan dengan harapan akan memberikan improvisasi yang cukup signifikan. Namun, ambisi tersebut tidak berjalan mulus sehingga pada tahun 2008 pengembangan ECMAScript dihentikan.</p> <p>Lalu, pada tahun 2015 ECMAScript 6 rilis dengan membawa perubahan yang cukup besar termasuk ide-ide yang sudah direncanakan untuk versi 4. Sejak saat itu, tiap tahun JavaScript melakukan update bersifat minor</p> <img class="image" src="./img/1_LyZcwuLWv2FArOumCxobpA.png" alt="1_LyZcwuLWv2FArOumCxobpA.png"> <h2 id="why">Kenapa JavaScript?</h2> <p>Jadi, kenapa kita perlu mempelajari JavaScript? <br> Alasan utamanya karena JavaScript merupakan bahasa yang penting untuk Anda kuasai jika ingin menjadi web developer, baik itu front-end maupun back-end. <br> Berikut ini adalah beberapa kelebihan dari JavaScript yang dapat Anda pertimbangkan sebelum mulai mempelajari JavaScript: <ol> <li><b>JavaScript bahasa yang versatile</b> <p class="paragraph-list">JavaScript bisa berjalan di lingkungan browser, server, bahkan desktop. Artinya, jika Anda bisa menguasai bahasa ini, maka skill Anda bisa digunakan di mana pun.</p></li> <li><b>Mudah dipelajari oleh pemula</b> <p class="paragraph-list">JavaScript termasuk salah satu bahasa pemrograman yang ramah bagi pemula. Anda tidak perlu menginstal software dan lingkungan pengembangan lain yang rumit untuk memulai membuat program dengan JavaScript. Cukup dengan browser Anda sudah bisa menulis kode JavaScript dan menjalankannya sekaligus.</p> <p class="paragraph-list">Selain itu, sebagai salah satu bahasa pemrograman paling populer, JavaScript memiliki komunitas yang besar pada situs seperti <a href="https://stasckoverflow.com">StackOverflow</a> yang siap membantu Anda jika memiliki pertanyaan atau kesulitan dalam JavaScript.</p> </li> <li><b>Potensi karir yang meyakinkan</b> <p class="paragraph-list">Mengikuti perkembangan teknologi dan banyaknya bisnis yang mulai merambah ke ranah digital, JavaScript menjadi salah satu skill yang paling banyak dicari di industri. Jika Anda mencari kata kunci “JavaScript” pada laman pencarian kerja seperti JobStreet, akan muncul hampir 1.500 lowongan pekerjaan di Indonesia yang bisa Anda lamar (data Maret 2021).</p> <p class="paragraph-list">Bukan hanya ramai peminat, pekerjaan yang berkaitan dengan JavaScript juga dihargai cukup tinggi. Menurut data yang diambil dari situs id.neuvoo.com rata-rata gaji seorang Front End Developer adalah Rp 7.500.000 per bulan (data Maret 2021) dan untuk Back End Developer adalah Rp 8.500.000 per bulan (data Maret 2021).</p> </li> </ol> </p> </div> <div class="footer" id="footer"> <p class="copy">Copyright 2023. Arsyad Rianda Putra</p> </div> </div> </body> </html>
#pragma once #if ENABLE_BARCODE #include <view/view.h> #include <string> #include <zint.h> struct zint_symbol *symbol; namespace cdroid{ class BarcodeView:public View{ public: enum BorderType{NO_BORDER=0, TOP=1 , BIND=2, BOX=4}; enum AspectRatioMode{IgnoreAspectRatio=0, KeepAspectRatio=1, CenterBarCode=2}; class ZintSeg { public: std::string mText;//`seg->source` and `seg->length` int mECI; //`seg->eci` ZintSeg(); ZintSeg(const std::string& text, const int ECIIndex = 0); // `ECIIndex` is comboBox index (not ECI value) }; enum Symbologies{ Code11 = BARCODE_CODE11, /*1 Code 11 */ C25Standard=BARCODE_C25STANDARD,/*2 2 of 5 Standard (Matrix) */ C25Matrix= BARCODE_C25MATRIX, /*2 Legacy */ C25Inter = BARCODE_C25INTER, /*3 2 of 5 Interleaved */ C25Data = BARCODE_C25IATA, /*4 2 of 5 IATA */ C25Logic = BARCODE_C25LOGIC, /*6 2 of 5 Data Logic */ C25Ind = BARCODE_C25IND, /*7 2 of 5 Industrial */ Code39 = BARCODE_CODE39, /*8 Code 39 */ ExCode39 = BARCODE_EXCODE39, /*9 Extended Code 39 */ Eanx = BARCODE_EANX, /*13 EAN (European Article Number) */ EanxChk = BARCODE_EANX_CHK, /*14 EAN + Check Digit */ GS1128 = BARCODE_GS1_128, /*16 GS1-128 */ Ean128 = BARCODE_EAN128, /*16 Legacy */ CodaBar = BARCODE_CODABAR, /*18 Codabar */ Code128 = BARCODE_CODE128, /*20 Code 128 */ DPLeit = BARCODE_DPLEIT, /*21 Deutsche Post Leitcode */ DPIdent = BARCODE_DPIDENT, /*22 Deutsche Post Identcode */ Code16K = BARCODE_CODE16K, /*23 Code 16k */ Code49 = BARCODE_CODE49, /*24 Code 49 */ Code93 = BARCODE_CODE93, /*25 Code 93 */ Flat = BARCODE_FLAT , /*28 Flattermarken */ DBAR_OMN = BARCODE_DBAR_OMN, /*29 GS1 DataBar Omnidirectional */ RSS14 = BARCODE_RSS14, /*29 Legacy */ DBAR_LTD = BARCODE_DBAR_LTD, /*30 GS1 DataBar Limited */ RSS_LTD = BARCODE_RSS_LTD, /*30 Legacy */ DBAR_EXP = BARCODE_DBAR_EXP, /*31 GS1 DataBar Expanded */ RSSEXP = BARCODE_RSS_EXP, /*31 Legacy */ Telepen = BARCODE_TELEPEN, /*32 Telepen Alpha */ UPCA = BARCODE_UPCA, /*34 UPC-A */ UPCACHK = BARCODE_UPCA_CHK, /*35 UPC-A + Check Digit */ UPCE = BARCODE_UPCE, /*37 UPC-E */ UPCECHK = BARCODE_UPCE_CHK, /*38 UPC-E + Check Digit */ PostNet = BARCODE_POSTNET, /* 40 USPS (U.S. Postal Service) POSTNET */ MsiPlessey=BARCODE_MSI_PLESSEY, /*47 MSI Plessey */ FIM = BARCODE_FIM , /*49 Facing Identification Mark */ LOGMARS = BARCODE_LOGMARS, /*50 LOGMARS */ PHARMA = BARCODE_PHARMA, /*51 Pharmacode One-Track */ PZN = BARCODE_PZN , /*52 Pharmazentralnummer */ PharmaTwo= BARCODE_PHARMA_TWO, /*53 Pharmacode Two-Track */ CEPNet = BARCODE_CEPNET , /*54 razilian CEPNet Postal Code */ PDF417 = BARCODE_PDF417 , /*55 PDF417 */ PDF417Comp=BARCODE_PDF417COMP, /*56 Compact PDF417 (Truncated PDF417) */ PDF417Trunc=BARCODE_PDF417TRUNC,/*56 Legacy */ MaxiCode = BARCODE_MAXICODE , /*57 MaxiCode */ QRCode = BARCODE_QRCODE , /*58 QR Code */ Code128AB= BARCODE_CODE128AB, /*60 Code 128 (Suppress subset C) */ Code128B = BARCODE_CODE128B, /*60 Legacy */ AusPost = BARCODE_AUSPOST , /*63 Australia Post Standard Customer */ AusReply = BARCODE_AUSREPLY, /*66 Australia Post Reply Paid */ AusRoute = BARCODE_AUSROUTE, /*67 Australia Post Routing */ AusRedirect=BARCODE_AUSREDIRECT,/*68 Australia Post Redirection */ ISBNX = BARCODE_ISBNX , /*69 ISBN */ RM4SCC = BARCODE_RM4SCC , /*70 Royal Mail 4-State Customer Code */ DataMatrix=BARCODE_DATAMATRIX, /*71 Data Matrix (ECC200) */ EAN14 = BARCODE_EAN14 , /*72 EAN-14 */ VIN = BARCODE_VIN , /*73 Vehicle Identification Number */ CodaBlockF=BARCODE_CODABLOCKF, /*74 Codablock-F */ NVE18 = BARCODE_NVE18 , /*75 NVE-18 (SSCC-18) */ JapanPost= BARCODE_JAPANPOST , /*76 Japanese Postal Code */ KoreaPost= BARCODE_KOREAPOST , /*77 Korea Post */ DBAR_STK = BARCODE_DBAR_STK , /*79 GS1 DataBar Stacked */ RSS14STACK=BARCODE_RSS14STACK, /*79 Legacy */ DBAR_OMNSTK=BARCODE_DBAR_OMNSTK,/*80 GS1 DataBar Stacked Omnidirectional */ RSS14StackOmni=BARCODE_RSS14STACK_OMNI, /*80 Legacy */ DBAR_EXPSTK= BARCODE_DBAR_EXPSTK, /*81 GS1 DataBar Expanded Stacked */ RssExpStack= BARCODE_RSS_EXPSTACK,/*81 Legacy */ PLANET = BARCODE_PLANET , /*82 USPS PLANET */ MicroPDF417=BARCODE_MICROPDF417, /*84 MicroPDF417 */ USPS_IMail= BARCODE_USPS_IMAIL, /*85 USPS Intelligent Mail (OneCode) */ OneCode = BARCODE_ONECODE, /*85 Legacy */ Plessy = BARCODE_PLESSEY, /*86 UK Plessey */ /*barcode 8 codes */ TelepenNum= BARCODE_TELEPEN_NUM, /*87 Telepen Numeric */ ITF14 = BARCODE_ITF14, /*89 ITF-14 */ KIX = BARCODE_KIX , /*90 Dutch Post KIX Code */ Axtec = BARCODE_AZTEC, /*92 Aztec Code */ DAFT = BARCODE_DAFT, /*93 DAFT Code */ DPD = BARCODE_DPD , /*96 DPD Code */ MicroQR = BARCODE_MICROQR, /*97 Micro QR Code */ /*barcode 9 codes */ HIBC128 = BARCODE_HIBC_128, /*98 HIBC (Health Industry Barcode) Code 128 */ HIBC39 = BARCODE_HIBC_39, /*99 HIBC Code 39 */ HIBCDM = BARCODE_HIBC_DM, /*102 HIBC Data Matrix */ HIBCQR = BARCODE_HIBC_QR, /*104 HIBC QR Code */ HIBCPDF = BARCODE_HIBC_PDF, /*106 HIBC PDF417 */ HIBCMicroPDF=BARCODE_HIBC_MICPDF, /*108 HIBC MicroPDF417 */ HIBCBlockF=BARCODE_HIBC_BLOCKF, /*110 HIBC Codablock-F */ HIBCAztec= BARCODE_HIBC_AZTEC, /*112 HIBC Aztec Code */ /*barcode 10 codes */ DotCode = BARCODE_DOTCODE, /*115 DotCode */ HanXin = BARCODE_HANXIN, /*116 Han Xin (Chinese Sensible) Code */ /*barcode 11 codes */ MailMark2D= BARCODE_MAILMARK_2D, /*119 Royal Mail 2D Mailmark (CMDM) (Data Matrix) */ UPU_S10 = BARCODE_UPU_S10, /*120 Universal Postal Union S10 */ MailMark4S=BARCODE_MAILMARK_4S, /*121 Royal Mail 4-State Mailmark */ MailMark = BARCODE_MAILMARK, /*121 Legacy */ /*int specific */ AZRune = BARCODE_AZRUNE , /*128 Aztec Runes */ Code32 = BARCODE_CODE32 , /*129 Code 32 */ EAN_CC = BARCODE_EANX_CC, /*130 EAN Composite */ GS1_128_CC = BARCODE_GS1_128_CC , /*131 GS1-128 Composite */ EAN128_CC = BARCODE_EAN128_CC , /*131 Legacy */ DBAR_OMN_CC = BARCODE_DBAR_OMN_CC, /*132 GS1 DataBar Omnidirectional Composite */ RSS14_CC = BARCODE_RSS14_CC , /*132 Legacy */ DBAR_LTD_CC = BARCODE_DBAR_LTD_CC, /*133 GS1 DataBar Limited Composite */ DBAR_EXP_CC = BARCODE_DBAR_EXP_CC, /*134 GS1 DataBar Expanded Composite */ RSS_EXP_CC = BARCODE_RSS_EXP_CC, /*134 Legacy */ UPCA_CC = BARCODE_UPCA_CC, /*135 UPC-A Composite */ UPCE_CC = BARCODE_UPCE_CC, /*136 UPC-E Composite */ DBAR_STK_CC = BARCODE_DBAR_STK_CC, /*137 GS1 DataBar Stacked Composite */ RSS14STACK_CC= BARCODE_RSS14STACK_CC, /*137 Legacy */ OMNSTK_CC = BARCODE_DBAR_OMNSTK_CC, /*138 GS1 DataBar Stacked Omnidirectional Composite */ RSS14_OMNI_CC= BARCODE_RSS14_OMNI_CC, /*138 Legacy */ EXPSTK_CC = BARCODE_DBAR_EXPSTK_CC, /*139 GS1 DataBar Expanded Stacked Composite */ RSS_EXPSTACK_CC=BARCODE_RSS_EXPSTACK_CC, /*139 Legacy */ Channel= BARCODE_CHANNEL , /*140 Channel Code */ CodeOne= BARCODE_CODEONE , /*141 Code One */ GridMatrix = BARCODE_GRIDMATRIX, /*142 Grid Matrix */ UPNQR = BARCODE_UPNQR, /*143 UPNQR (Univerzalnega Plačilnega Naloga QR) */ ULTRA = BARCODE_ULTRA, /*144 Ultracode */ RMQR = BARCODE_RMQR , /*145 Rectangular Micro QR Code (rMQR) */ BC412 = BARCODE_BC412, /*146 IBM BC412 (SEMI T1-95) */ LAST = BARCODE_LAST /*146Max barcode number marker, not barcode */ }; private: int mErrorNo; int mRotateAngle; int mFgColor; int mSymbology; bool mDotty; bool mShowHRT; bool mCmyk; bool mGssep; bool mQuietZones; bool mNoQuietZones; bool mCompliantHeight; bool mReaderInit; bool mDebug; bool mGS1Parens; bool mGS1NoCheck; int mBorderType; int mOption1; int mOption2; int mOption3; int mDotSize; int mBorderWidth; int mWhiteSpace; int mVWhiteSpace; int mWarnLevel; int mECI; int mInputMode; int mEncodedRows; int mEncodedWidth; int mEncodedHeight; int mChanged; float mZoom; float mDpmm; float mGuardDescent; float mVectorWidth; float mVectorHeight; std::string mErrorStr; std::string mPrimaryMessage; std::vector<ZintSeg>mSegs; void initView(); int convertSegs(struct zint_seg* zsegs, std::vector<std::string>& bstrs); bool resetSymbol(); protected: struct zint_symbol *mSymbol; std::string mText; void encode(); /*Test capabilities*/ bool hasHRT()const; bool isStackable()const; bool isExtendable()const; bool isComposite()const; bool supportsECI()const; bool supportsGS1()const; bool isDotty()const; bool hasDefaultQuietZones()const; bool isFixedRatio()const; bool supportsReaderInit()const; bool supportsFullMultibyte()const; bool hasMask()const; bool supportsStructApp()const; bool hasCompliantHeight()const; bool getWidthHeightXdim(float x_dim, float &width_x_dim, float &height_x_dim) const; void onMeasure(int widthMeasureSpec, int heightMeasureSpec)override; public: BarcodeView(int w,int h); BarcodeView(Context*ctx,const AttributeSet&attrs); ~BarcodeView()override; void setText(const std::string&text); std::vector<ZintSeg> getSegs()const; void setSegs(const std::vector<ZintSeg>& segs); void setBarcodeColor(int color); int getBarcodeColor()const; int getSymbology()const; void setBorderType(int borderTypeIndex/*enum BorderType*/); int getBorderType()const; void setSymbology(int ); std::string getBarcodeName()const; void setZoom(float); float getZoom()const; void setSHRT(bool hrt); bool getSHRT()const; void setRotateAngle(int angle); int getRotateAngle()const; void onDraw(Canvas&canvas)override; public: }; }/*endof namespace*/ #endif/*ENABLE_BARCODE*/
import React, { useState, useEffect } from 'react'; import { useNavigate } from 'react-router-dom'; import axios from 'axios'; import DeleteUser from './DeleteAccount'; import "../styles/UpdateUser.css" export default function UpdateUser({ userId }) { const navigate = useNavigate(); // eslint-disable-next-line const [user, setUser] = useState({}); const [username, setUsername] = useState(''); const [password, setPassword] = useState(''); const [email, setEmail] = useState(''); useEffect(() => { const fetchUser = async () => { try { const response = await axios.get(`https://responsible-knowledgeable-restaurant.glitch.me/auth/users/${userId}`); setUser(response.data); setUsername(response.data.username); setPassword(response.data.password); setEmail(response.data.email); } catch (error) { console.error(error); } }; fetchUser(); }, [userId]); const handleUpdate = async (event) => { event.preventDefault(); try { const response = await axios.put(`https://zcgapi.glitch.me/auth/users/${userId}`, { username, password, email }); console.log(response.data); } catch (error) { console.error(error); navigate("/home") } }; return ( <div className="update-form"> <h2 className='text-center mb-5'>UPDATE INFO</h2> <form onSubmit={handleUpdate}> <div> <label htmlFor="username">USERNAME:</label> <input type="text" id="username" value={username} onChange={(event) => setUsername(event.target.value)} /> </div> <div> <label htmlFor="password">PASSWORD:</label> <input type="password" id="password" value={password} onChange={(event) => setPassword(event.target.value)} /> </div> <div> <label htmlFor="email">EMAIL:</label> <input type="email" id="email" value={email} onChange={(event) => setEmail(event.target.value)} /> </div> <button className='btn btn-warning update-btn' type="submit">Update User</button> </form> <h4>DELETE ACCOUNT?</h4> <DeleteUser/> </div> ); };
#pragma once #include "Lamp/Utility/PlatformUtility.h" #include "Lamp/AssetSystem/Asset.h" #include "ImGuiExtension.h" #include <imgui.h> #include <imgui_internal.h> #include <imgui_stdlib.h> #include <glm/glm.hpp> #include <glm/gtc/type_ptr.hpp> #include <string> #include <vector> namespace Lamp { class Texture2D; class Image2D; } namespace UI { static uint32_t s_contextId = 0; static uint32_t s_stackId = 0; class ScopedColor { public: ScopedColor(ImGuiCol_ color, const glm::vec4& newColor) : m_Color(color) { auto& colors = ImGui::GetStyle().Colors; m_OldColor = colors[color]; colors[color] = ImVec4{ newColor.x, newColor.y, newColor.z, newColor.w }; } ~ScopedColor() { auto& colors = ImGui::GetStyle().Colors; colors[m_Color] = m_OldColor; } private: ImVec4 m_OldColor; ImGuiCol_ m_Color; }; class ScopedStyleFloat { public: ScopedStyleFloat(ImGuiStyleVar_ var, float value) { ImGui::PushStyleVar(var, value); } ~ScopedStyleFloat() { ImGui::PopStyleVar(); } }; class ScopedStyleFloat2 { public: ScopedStyleFloat2(ImGuiStyleVar_ var, const glm::vec2& value) { ImGui::PushStyleVar(var, { value.x, value.y }); } ~ScopedStyleFloat2() { ImGui::PopStyleVar(); } }; ImTextureID GetTextureID(Ref<Lamp::Texture2D> texture); ImTextureID GetTextureID(Ref<Lamp::Image2D> texture); ImTextureID GetTextureID(Lamp::Texture2D* texture); static uint64_t BytesToMBs(uint64_t input) { return (input / (1024 * 1024)); } static void ImageText(Ref<Lamp::Texture2D> texture, const std::string& text) { ImVec2 size = ImGui::CalcTextSize(text.c_str()); ImGui::Image(GetTextureID(texture), { size.y, size.y }); ImGui::SameLine(); ImGui::Text(text.c_str()); } static bool ImageSelectable(Ref<Lamp::Texture2D> texture, const std::string& text, bool selected) { ImVec2 size = ImGui::CalcTextSize(text.c_str()); ImGui::Image(GetTextureID(texture), { size.y, size.y }, { 0, 1 }, { 1, 0 }); ImGui::SameLine(); return ImGui::Selectable(text.c_str(), selected, ImGuiSelectableFlags_SpanAvailWidth); } static bool TreeNode(const std::string& text, ImGuiTreeNodeFlags flags = 0) { ScopedStyleFloat2 frame{ ImGuiStyleVar_FramePadding, { 0.f, 0.f } }; ScopedStyleFloat2 spacing{ ImGuiStyleVar_ItemSpacing, { 0.f, 0.f } }; return ImGui::TreeNodeEx(text.c_str(), flags); } static bool TreeNodeImage(Ref<Lamp::Texture2D> texture, const std::string& text, ImGuiTreeNodeFlags flags) { ScopedStyleFloat2 frame{ ImGuiStyleVar_FramePadding, { 0.f, 0.f } }; ScopedStyleFloat2 spacing{ ImGuiStyleVar_ItemSpacing, { 0.f, 0.f } }; ImVec2 size = ImGui::CalcTextSize(text.c_str()); ImGui::Image(GetTextureID(texture), { size.y, size.y }, { 0, 1 }, { 1, 0 }); ImGui::SameLine(); return ImGui::TreeNodeEx(text.c_str(), flags); } static bool TreeNodeFramed(const std::string& text, bool alwaysOpen = false, bool useOther = false, float rounding = 0.f, const glm::vec2& padding = { 0.f, 0.f }) { ImGuiTreeNodeFlags nodeFlags = ImGuiTreeNodeFlags_Framed | ImGuiTreeNodeFlags_AllowItemOverlap | ImGuiTreeNodeFlags_SpanAvailWidth | ImGuiTreeNodeFlags_FramePadding; if (alwaysOpen) { nodeFlags |= ImGuiTreeNodeFlags_DefaultOpen; } if (!useOther) { return ImGui::TreeNodeEx(text.c_str(), nodeFlags); } UI::ScopedStyleFloat frameRound(ImGuiStyleVar_FrameRounding, rounding); return ImGui::TreeNodeEx(text.c_str(), nodeFlags); } static bool TreeNodeFramed(const std::string& text, float width, bool useOther = false, float rounding = 0.f, const glm::vec2& padding = { 0.f, 0.f }) { const ImGuiTreeNodeFlags nodeFlags = ImGuiTreeNodeFlags_Framed | ImGuiTreeNodeFlags_AllowItemOverlap | ImGuiTreeNodeFlags_SpanAvailWidth | ImGuiTreeNodeFlags_FramePadding; if (!useOther) { return ImGui::TreeNodeWidthEx(text.c_str(), width, nodeFlags); } UI::ScopedStyleFloat frameRound(ImGuiStyleVar_FrameRounding, rounding); return ImGui::TreeNodeWidthEx(text.c_str(), width, nodeFlags); } static void TreeNodePop() { ImGui::TreePop(); } static bool InputText(const std::string& id, std::string& text, ImGuiInputTextFlags_ flags = ImGuiInputTextFlags_None) { return ImGui::InputTextString(id.c_str(), &text, flags); } static bool InputTextOnSameline(std::string& string, const std::string& id) { ImGui::SameLine(); return InputText(id, string); } static void Separator(ImGuiSeparatorFlags customFlags = 0) { ImGuiContext& g = *GImGui; ImGuiWindow* window = g.CurrentWindow; if (window->SkipItems) return; // Those flags should eventually be overridable by the user ImGuiSeparatorFlags flags = (window->DC.LayoutType == ImGuiLayoutType_Horizontal) ? ImGuiSeparatorFlags_Vertical : ImGuiSeparatorFlags_Horizontal; flags |= customFlags; ImGui::SeparatorEx(flags); } static void PushId() { int id = s_contextId++; ImGui::PushID(id); s_stackId = 0; } static void PopId() { ImGui::PopID(); s_contextId--; } static bool BeginPopup(const std::string& id = "") { if (id.empty()) { return ImGui::BeginPopupContextItem(); } return ImGui::BeginPopupContextItem(id.c_str()); } static void EndPopup() { ImGui::EndPopup(); } static void SameLine(float offsetX = 0.f, float spacing = -1.f) { ImGui::SameLine(offsetX, spacing); } static bool BeginProperties(const std::string& name = "", bool pushId = true) { if (pushId) { PushId(); } return ImGui::BeginTable(name.c_str(), 2, ImGuiTableFlags_BordersInnerV | ImGuiTableFlags_SizingStretchProp | ImGuiTableFlags_Resizable); } static void EndProperties(bool popId = true) { ImGui::EndTable(); if (popId) { PopId(); } } static void ShiftCursor(float x, float y) { ImVec2 pos = { ImGui::GetCursorPosX() + x, ImGui::GetCursorPosY() + y }; ImGui::SetCursorPos(pos); } //Inputs static bool PropertyAxisColor(const std::string& text, glm::vec3& value, float resetValue = 0.f) { ScopedStyleFloat2 cellPad(ImGuiStyleVar_CellPadding, { 4.f, 0.f }); bool changed = false; ImGui::TableNextColumn(); ImGui::Text(text.c_str()); ImGui::TableNextColumn(); ImGui::PushMultiItemsWidths(3, ImGui::CalcItemWidth()); ImGui::PushStyleVar(ImGuiStyleVar_ItemSpacing, ImVec2{ 0.f, 0.f }); float lineHeight = GImGui->Font->FontSize + GImGui->Style.FramePadding.y * 2.f; ImVec2 buttonSize = { lineHeight + 3.f, lineHeight }; { ScopedColor color{ ImGuiCol_Button, { 0.8f, 0.1f, 0.15f, 1.f } }; ScopedColor colorh{ ImGuiCol_ButtonHovered, { 0.9f, 0.2f, 0.2f, 1.f } }; ScopedColor colora{ ImGuiCol_ButtonActive, { 0.8f, 0.1f, 0.15f, 1.f } }; std::string butId = "X##" + std::to_string(s_stackId++); if (ImGui::Button(butId.c_str(), buttonSize)) { value.x = resetValue; changed = true; } } ImGui::SameLine(); std::string id = "##" + std::to_string(s_stackId++); changed = true; if (ImGui::DragFloat(id.c_str(), &value.x, 0.1f)) changed = true; ImGui::PopItemWidth(); ImGui::SameLine(); { ScopedColor color{ ImGuiCol_Button, { 0.2f, 0.7f, 0.2f, 1.f } }; ScopedColor colorh{ ImGuiCol_ButtonHovered, { 0.3f, 0.8f, 0.3f, 1.f } }; ScopedColor colora{ ImGuiCol_ButtonActive, { 0.2f, 0.7f, 0.2f, 1.f } }; std::string butId = "Y##" + std::to_string(s_stackId++); if (ImGui::Button(butId.c_str(), buttonSize)) { value.y = resetValue; changed = true; } } ImGui::SameLine(); id = "##" + std::to_string(s_stackId++); if (ImGui::DragFloat(id.c_str(), &value.y, 0.1f)) changed = true; ImGui::PopItemWidth(); ImGui::SameLine(); { ScopedColor color{ ImGuiCol_Button, { 0.1f, 0.25f, 0.8f, 1.f } }; ScopedColor colorh{ ImGuiCol_ButtonHovered, { 0.2f, 0.35f, 0.9f, 1.f } }; ScopedColor colora{ ImGuiCol_ButtonActive, { 0.1f, 0.25f, 0.8f, 1.f } }; std::string butId = "Z##" + std::to_string(s_stackId++); if (ImGui::Button(butId.c_str(), buttonSize)) { value.z = resetValue; changed = true; } } ImGui::SameLine(); id = "##" + std::to_string(s_stackId++); if (ImGui::DragFloat(id.c_str(), &value.z, 0.1f)) changed = true; ImGui::PopItemWidth(); ImGui::PopStyleVar(); return true; } static bool Combo(const std::string& text, int& currentItem, const std::vector<const char*>& items, float width = 0.f) { bool changed = false; ImGui::TableNextColumn(); ImGui::TextUnformatted(text.c_str()); ImGui::TableNextColumn(); if (width == 0.f) { ImGui::PushItemWidth(ImGui::GetColumnWidth()); } else { ImGui::PushItemWidth(width); } std::string id = "##" + std::to_string(s_stackId++); if (ImGui::Combo(id.c_str(), &currentItem, items.data(), (int)items.size())) { changed = true; } ImGui::PopItemWidth(); return changed; } static void* DragDropTarget(const std::string& type) { void* data = nullptr; if (ImGui::BeginDragDropTarget()) { if (const ImGuiPayload* pPayload = ImGui::AcceptDragDropPayload(type.c_str())) { data = pPayload->Data; } ImGui::EndDragDropTarget(); } return data; } static void* DragDropTarget(std::initializer_list<std::string> types) { void* data = nullptr; for (const auto& type : types) { if (ImGui::BeginDragDropTarget()) { if (const ImGuiPayload* pPayload = ImGui::AcceptDragDropPayload(type.c_str())) { data = pPayload->Data; } ImGui::EndDragDropTarget(); } } return data; } static bool ImageButton(const std::string& id, ImTextureID textureId, const ImVec2& size, const ImVec2& uv0 = ImVec2(0, 1), const ImVec2& uv1 = ImVec2(1, 0), int frame_padding = -1, const ImVec4& bg_col = ImVec4(0, 0, 0, 0), const ImVec4& tint_col = ImVec4(1, 1, 1, 1)) { ImGuiContext& g = *GImGui; ImGuiWindow* window = g.CurrentWindow; if (window->SkipItems) return false; const ImGuiID imId = window->GetID(id.c_str()); // Default to using texture ID as ID. User can still push string/integer prefixes. const ImVec2 padding = (frame_padding >= 0) ? ImVec2((float)frame_padding, (float)frame_padding) : g.Style.FramePadding; return ImGui::ImageButtonEx(imId, textureId, size, uv0, uv1, padding, bg_col, tint_col); } static bool ImageButtonState(const std::string& id, bool state, ImTextureID textureId, const ImVec2& size, const ImVec2& uv0 = ImVec2(0, 1), const ImVec2& uv1 = ImVec2(1, 0)) { if (state) { return ImageButton(id, textureId, size, uv0, uv1, -1, { 0.18f, 0.18f, 0.18f, 1.f }); } else { return ImageButton(id, textureId, size, uv0, uv1); } } static bool Property(const std::string& text, int& value, bool useMinMax = false, int min = 0, int max = 0) { bool changed = false; ScopedStyleFloat2 cellPad{ ImGuiStyleVar_CellPadding, { 4.f, 0.f } }; ImGui::TableNextColumn(); ImGui::TextUnformatted(text.c_str()); ImGui::TableNextColumn(); std::string id = "##" + std::to_string(s_stackId++); ImGui::PushItemWidth(ImGui::GetColumnWidth()); if (ImGui::DragInt(id.c_str(), &value, 1.f, min, max)) { if (value > max && useMinMax) { value = max; } if (value < min && useMinMax) { value = min; } changed = true; } ImGui::PopItemWidth(); return changed; } static bool Property(const std::string& text, uint32_t& value, bool useMinMax = false, int min = 0, int max = 0) { bool changed = false; ScopedStyleFloat2 cellPad{ ImGuiStyleVar_CellPadding, { 4.f, 0.f } }; ImGui::TableNextColumn(); ImGui::TextUnformatted(text.c_str()); ImGui::TableNextColumn(); std::string id = "##" + std::to_string(s_stackId++); ImGui::PushItemWidth(ImGui::GetColumnWidth()); if (ImGui::DragScalar(id.c_str(), ImGuiDataType_U32, &value, 1.f, &min, &max)) { if (value > (uint32_t)max && useMinMax) { value = (uint32_t)max; } if (value < (uint32_t)min && useMinMax) { value = (uint32_t)min; } changed = true; } ImGui::PopItemWidth(); return changed; } static void PropertyText(const std::string& text) { ImGui::TableNextColumn(); ImGui::TextUnformatted(text.c_str()); ImGui::TableNextColumn(); } static bool Property(const std::string& text, bool& value) { bool changed = false; ImGui::TableNextColumn(); ImGui::TextUnformatted(text.c_str()); ImGui::TableNextColumn(); std::string id = "##" + std::to_string(s_stackId++); if (ImGui::Checkbox(id.c_str(), &value)) { changed = true; } return changed; } static bool Property(const std::string& text, float& value, bool useMinMax = false, float min = 0.f, float max = 0.f) { bool changed = false; ImGui::TableNextColumn(); ImGui::TextUnformatted(text.c_str()); ImGui::TableNextColumn(); std::string id = "##" + std::to_string(s_stackId++); ImGui::PushItemWidth(ImGui::GetColumnWidth()); if (ImGui::DragFloat(id.c_str(), &value, 1.f, min, max)) { if (value < min && useMinMax) { value = min; } if (value > max && useMinMax) { value = max; } changed = true; } ImGui::PopItemWidth(); return changed; } static bool Property(const std::string& text, glm::vec2& value, float min = 0.f, float max = 0.f) { bool changed = false; ImGui::TableNextColumn(); ImGui::TextUnformatted(text.c_str()); ImGui::TableNextColumn(); std::string id = "##" + std::to_string(s_stackId++); ImGui::PushItemWidth(ImGui::GetColumnWidth()); if (ImGui::DragFloat2(id.c_str(), glm::value_ptr(value), 1.f, min, max)) { changed = true; } ImGui::PopItemWidth(); return changed; } static bool Property(const std::string& text, glm::vec3& value, float min = 0.f, float max = 0.f) { bool changed = false; ImGui::TableNextColumn(); ImGui::TextUnformatted(text.c_str()); ImGui::TableNextColumn(); std::string id = "##" + std::to_string(s_stackId++); ImGui::PushItemWidth(ImGui::GetColumnWidth()); if (ImGui::DragFloat3(id.c_str(), glm::value_ptr(value), 1.f, min, max)) { changed = true; } ImGui::PopItemWidth(); return changed; } static bool Property(const std::string& text, glm::vec4& value, float min = 0.f, float max = 0.f) { bool changed = false; ImGui::TableNextColumn(); ImGui::TextUnformatted(text.c_str()); ImGui::TableNextColumn(); std::string id = "##" + std::to_string(s_stackId++); ImGui::PushItemWidth(ImGui::GetColumnWidth()); if (ImGui::DragFloat4(id.c_str(), glm::value_ptr(value), 1.f, min, max)) { changed = true; } ImGui::PopItemWidth(); return changed; } static bool Property(const std::string& text, const std::string& value) { bool changed = false; ImGui::TableNextColumn(); ImGui::TextUnformatted(text.c_str()); ImGui::TableNextColumn(); std::string id = "##" + std::to_string(s_stackId++); ImGui::PushItemWidth(ImGui::GetColumnWidth()); if (InputText(id, const_cast<std::string&>(value))) { changed = true; } ImGui::PopItemWidth(); return changed; } static bool Property(const std::string& text, std::string& value) { bool changed = false; ImGui::TableNextColumn(); ImGui::TextUnformatted(text.c_str()); ImGui::TableNextColumn(); std::string id = "##" + std::to_string(s_stackId++); ImGui::PushItemWidth(ImGui::GetColumnWidth()); if (InputText(id, value)) { changed = true; } return changed; } static bool PropertyColor(const std::string& text, glm::vec4& value) { ImGui::TableNextColumn(); ImGui::TextUnformatted(text.c_str()); ImGui::TableNextColumn(); std::string id = "##" + std::to_string(s_stackId++); ImGui::PushItemWidth(ImGui::GetColumnWidth()); if (ImGui::ColorEdit4(id.c_str(), glm::value_ptr(value))) { return true; } return false; } static bool PropertyColor(const std::string& text, glm::vec3& value) { ImGui::TableNextColumn(); ImGui::TextUnformatted(text.c_str()); ImGui::TableNextColumn(); std::string id = "##" + std::to_string(s_stackId++); ImGui::PushItemWidth(ImGui::GetColumnWidth()); if (ImGui::ColorEdit3(id.c_str(), glm::value_ptr(value))) { return true; } return false; } static bool Property(const std::string& text, std::filesystem::path& path) { bool changed = false; ImGui::TableNextColumn(); ImGui::TextUnformatted(text.c_str()); ImGui::TableNextColumn(); std::string sPath = path.string(); ImGui::PushItemWidth(ImGui::GetColumnWidth() - ImGui::CalcTextSize("Open...").x - 20.f); std::string id = "##" + std::to_string(s_stackId++); if (InputText(id, sPath)) { path = std::filesystem::path(sPath); changed = true; } ImGui::PopItemWidth(); ImGui::SameLine(); if (ImGui::Button("Open...", { ImGui::GetContentRegionAvail().x, 25.f })) { auto newPath = Lamp::FileDialogs::OpenFile("All (*.*)\0*.*\0"); path = newPath; changed = true; } if (auto ptr = UI::DragDropTarget("CONTENT_BROWSER_ITEM")) { const wchar_t* inPath = (const wchar_t*)ptr; std::filesystem::path newPath = std::filesystem::path("assets") / inPath; path = newPath; changed = true; } return changed; } static bool Property(const std::string& text, Ref<Lamp::Asset>& asset) { bool changed = false; ImGui::TableNextColumn(); ImGui::TextUnformatted(text.c_str()); ImGui::TableNextColumn(); ImGui::PushItemWidth(ImGui::GetColumnWidth() - 20.f); ImGui::Text("Asset: %s", asset->Path.filename().string().c_str()); ImGui::PopItemWidth(); ImGui::SameLine(); std::string buttonId = "Open##" + std::to_string(s_stackId++); if (ImGui::Button(buttonId.c_str(), { ImGui::GetContentRegionAvail().x, 25.f })) { } if (BeginPopup()) { ImGui::Text("Test"); EndPopup(); } if (auto ptr = UI::DragDropTarget("CONTENT_BROWSER_ITEM")) { const wchar_t* inPath = (const wchar_t*)ptr; std::filesystem::path newPath = std::filesystem::path("assets") / inPath; changed = true; } return changed; } };
function tnt_ftprocess_tla_wrapper(whichStages) % tnt_ftprocess_tla_wrapper(whichStages) % % To run on dream, at the command line type: distmsub tnt_ftprocess_tla_wrapper.m % % To run on a local computer, type the command in MATLAB % % There is only one stage: % stage1 = call wrapper that calls create_ft_struct (which calls seg2ft, % which calls ft_timelockanalysis) and saves one file per subject % % Input: % whichStages: the stage number(s) to run (default = 1) % % Output: % timelocked ERP data % % check/handle arguments error(nargchk(0,1,nargin)) STAGES = 1; if nargin == 1 STAGES = whichStages; end % initialize the analysis structs exper = struct; files = struct; dirs = struct; ana = struct; %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %% MODIFY THIS STUFF %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %% Experiment-specific setup exper.name = 'TNT'; exper.sampleRate = 250; % pre- and post-stimulus times to read, in seconds (pre is negative) exper.prepost = [-1.0 1.7]; % equate the number of trials across event values? exper.equateTrials = 1; % type of NS file for FieldTrip to read; raw or sbin must be put in % dirs.dataroot/ns_raw; egis must be put in dirs.dataroot/ns_egis exper.eegFileExt = 'egis'; %exper.eegFileExt = 'raw'; % types of events to find in the NS file; these must be the same as the % events in the NS files exper.eventValues = sort({'B1of2','B2of2','NT1of2For','NT1of2Rec','NT2of2For','NT2of2Rec','T1of2For','T1of2Rec','T2of2For','T2of2Rec'}); %exper.eventValues = sort({'NT1of2For','NT1of2Rec','NT2of2For','NT2of2Rec','T1of2For','T1of2Rec','T2of2For','T2of2Rec'}); %exper.eventValues = sort({'NT1of2Rec','T1of2Rec'}); % combine some events into higher-level categories exper.eventValuesExtra.toCombine = {... {'B1of2','B2of2'},... {'NT1of2For','NT2of2For','NT1of2Rec','NT2of2Rec'},... {'T1of2For','T2of2For','T1of2Rec','T2of2Rec'}... % {'NT1of2For','NT1of2Rec'},{'NT2of2For','NT2of2Rec'}... % {'T1of2For','T1of2Rec'},{'T2of2For','T2of2Rec'}... % {'NT1of2For','NT2of2For'},{'NT1of2Rec','NT2of2Rec'}... % {'T1of2For','T2of2For'},{'T1of2Rec','T2of2Rec'}... }; exper.eventValuesExtra.newValue = {... {'B'},... {'NT'},... {'TH'}... % {'NT1'},{'NT2'}... % {'TH1'},{'TH2'}... % {'NTF'},{'NTR'}... % {'THF'},{'THR'}... }; % keep only the combined (extra) events and throw out the original events? exper.eventValuesExtra.onlyKeepExtras = 1; exper.subjects = { 'TNT 06'; 'TNT 07'; % 'TNT 08'; % 'TNT 09'; % 'TNT 11'; % 'TNT 13'; % 'TNT 14'; % 'TNT 15'; % 'TNT 17'; % 'TNT 19'; % 'TNT 20'; % 'TNT 21'; % 'TNT 22'; % 'TNT 23'; % 'TNT 25'; % 'TNT 26'; % 'TNT 27'; % 'TNT 28'; % 'TNT 30'; % 'TNT 32'; % 'TNT 33'; % 'TNT 35'; % 'TNT 39'; % 'TNT 41'; % 'TNT 42'; % 'TNT 44'; % 'TNT 45'; % 'TNT 46'; % 'TNT 47'; % 'TNT 48'; % 'TNT 49'; % 'TNT 50'; % 'TNT 51'; % 'TNT 52'; % 'TNT 53'; % 'TNT 54'; }; % The sessions that each subject ran; the strings in this cell are the % directories in dirs.dataDir (set below) containing the ns_egis/ns_raw % directory and, if applicable, the ns_bci directory. They are not % necessarily the session directory names where the FieldTrip data is saved % for each subject because of the option to combine sessions. See 'help % create_ft_struct' for more information. exper.sessions = {'session_0'}; %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %% POSSIBLY MODIFY THIS STUFF %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %% set up file and directory handling parameters % directory where the data to read is located dirs.dataDir = fullfile('TNT_matt','eeg',sprintf('%d_%d',exper.prepost(1)*1000,exper.prepost(2)*1000)); % Possible locations of the data files (dataroot) dirs.serverDir = fullfile('/Volumes','curranlab','Data'); dirs.serverLocalDir = fullfile('/Volumes','RAID','curranlab','Data'); dirs.dreamDir = fullfile('/data','projects','curranlab'); dirs.localDir = fullfile(getenv('HOME'),'data'); % pick the right dirs.dataroot if exist(dirs.serverDir,'dir') dirs.dataroot = dirs.serverDir; runLocally = 1; elseif exist(dirs.serverLocalDir,'dir') dirs.dataroot = dirs.serverLocalDir; runLocally = 1; elseif exist(dirs.localDir,'dir') dirs.dataroot = dirs.localDir; runLocally = 1; elseif exist(dirs.dreamDir,'dir') dirs.dataroot = dirs.dreamDir; runLocally = 0; else error('Data directory not found.'); end % Use the FT chan locs file files.elecfile = 'GSN-HydroCel-129.sfp'; files.locsFormat = 'besa_sfp'; ana.elec = ft_read_sens(files.elecfile,'fileformat',files.locsFormat); %% set up analysis parameters ana.segFxn = 'seg2ft'; ana.ftFxn = 'ft_timelockanalysis'; ana.ftype = 'tla'; % any preprocessing? cfg_pp = []; % single precision to save space cfg_pp.precision = 'single'; cfg_proc = []; cfg_proc.keeptrials = 'no'; % set the save directories [dirs,files] = mm_ft_setSaveDirs(exper,ana,cfg_proc,dirs,files,ana.ftype); %% set up for running stages and specifics for Dream % name(s) of the functions for different stages of processing stageFun = {@stage1}; timeOut = {2}; % in HOURS if runLocally == 0 % need to export DISPLAY to an offscreen buffer for MATLAB DCS graphics sched = findResource(); if strcmp(sched.Type, 'generic') setenv('DISPLAY', 'dream:99'); end end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %% ANALYSIS %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %capture diary and time statistics thisRun = [exper.name,'_overview_',datestr(now,'ddmmmyyyy-HHMMSS')]; diary(fullfile(dirs.saveDirProc,[thisRun '.log'])); tStart = tic; fprintf('START TIME: %s\n',datestr(now,13)); for i = STAGES tS = tic; fprintf('STAGE%d START TIME: %s\n',i, datestr(now,13)); % execute the processing stage stageFun{i}(ana,cfg_pp,cfg_proc,exper,dirs,files,runLocally,timeOut{i}); fprintf('STAGE%d END TIME: %s\n',i, datestr(now,13)); fprintf('%.3f -- elapsed time STAGE%d (seconds)\n', toc(tS), i); end time = toc(tStart); fprintf('%.3f -- elapsed time OVERALL (seconds)\n', time); fprintf('END TIME: %s\n',datestr(now,13)); diary off %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %% FUNCTIONS %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function stage1(ana,cfg_pp,cfg_proc,exper,dirs,files,runLocally,timeOut) % stage1: process the input files with FieldTrip based on the analysis % parameters %% Process the data if runLocally == 0 %% Dream: create one task for each subject (i.e., submit one to each node) % start a new job job = newJob(dirs); % save the original subjects array so we can set exper to have single % subjects, one for each task created allSubjects = exper.subjects; for i = 1:length(allSubjects) fprintf('Processing %s...\n',allSubjects{i}); % Dream: create one task for each subject exper.subjects = allSubjects(i); inArg = {ana,cfg_pp,cfg_proc,exper,dirs,files}; % save the exper struct (output 1) so we can use it later createTask(job,@create_ft_struct,1,inArg); end runJob(job,timeOut,fullfile(dirs.saveDirProc,[exper.name,'_stage1_',datestr(now,'ddmmmyyyy-HHMMSS'),'.log'])); % get the trial counts together across subjects, sessions, and events [exper] = mm_ft_concatTrialCounts_cluster(job,exper,allSubjects); % save the analysis details; overwrite if it already exists saveFile = fullfile(dirs.saveDirProc,sprintf('analysisDetails.mat')); %if ~exist(saveFile,'file') fprintf('Saving %s...',saveFile); save(saveFile,'exper','ana','dirs','files','cfg_proc','cfg_pp'); fprintf('Done.\n'); %else % error('Not saving! %s already exists.\n',saveFile); %end % final step: destroy the job because this doesn't happen in runJob destroy(job); else %% run the function locally % create a log of the command window output thisRun = [exper.name,'_stage1_',datestr(now,'ddmmmyyyy-HHMMSS')]; % turn the diary on diary(fullfile(dirs.saveDirProc,[thisRun,'.log'])); % use the peer toolbox %ana.usePeer = 1; ana.usePeer = 0; % Local: run all the subjects [exper] = create_ft_struct(ana,cfg_pp,cfg_proc,exper,dirs,files); % save the analysis details; overwrite if it already exists saveFile = fullfile(dirs.saveDirProc,sprintf('analysisDetails.mat')); %if ~exist(saveFile,'file') fprintf('Saving %s...',saveFile); save(saveFile,'exper','ana','dirs','files','cfg_proc','cfg_pp'); fprintf('Done.\n'); %else % error('Not saving! %s already exists.\n',saveFile); %end % turn the diary off diary off end function job = newJob(dirs) % newJob Creates a new PCT job and sets job's dependencies % % dirs -- data structure with necessary fields like data locations % Set up scheduler, job sched = findResource(); job = createJob(sched); % define the directories to add to worker sessions' matlab path homeDir = getenv('HOME'); myMatlabDir = fullfile(homeDir,'Documents','MATLAB'); p = path(); set(job, 'PathDependencies', {homeDir, myMatlabDir, pwd(), p, dirs.dataroot}); function runJob( job, timeOut, logFile ) % runJob Submits and waits on job to finish or timeout % runJob will submit the supplied job to the scheduler and will % wait for the job to finish or until the timeout has been reached. % If the job finishes, then the command window outputs of all tasks % are appended to the log file and the job is destroyed. % If the timeout is reached, an error is reported but the job is not % destroyed. % % job -- the job object to submit % timeOut -- the timeout value in hours % logFile -- full file name of the log file to append output to % % Example: % runJob( job, 5, 'thisrun.log'); % check/handle arguments error(nargchk(1,3,nargin)) TIMEOUT=3600*5; % default to 5 hours if nargin > 1 TIMEOUT=timeOut*3600; end LOGFILE=[job.Name '.log']; if nargin > 2 LOGFILE = logFile; end % Capture command window output from all tasks alltasks = get(job, 'Tasks'); set(alltasks, 'CaptureCommandWindowOutput', true); % Submit Job/Tasks and wait for completion (or timeout) submit(job) finished = waitForState(job, 'finished', TIMEOUT); if finished errors = logOutput(alltasks, LOGFILE); if errors error([mfilename ':logOutput'],'%s had %d errors',job.Name, errors) %elseif ~errors % destroy(job); end else error([mfilename ':JobTimeout'],'%s: Timed out waiting for job...NAME: %s',... datestr(now, 13), job.Name, job.ID, job.StartTime) end function numErrors=logOutput( tasks, logFile ) % logOutput - concatenates tasks' output into a logfile % tasks -- the tasks to capture output from % logFile -- the file to log the output to % numErrors -- number of tasks which failed % check for argument(s) error(nargchk(2,2,nargin)) numErrors=0; try fid=fopen(logFile, 'a+'); for i=1:length(tasks) fprintf(fid,'\n***** START TASK %d *****\n',i); fprintf(fid,'%s\n', tasks(i).CommandWindowOutput); if ~isempty(tasks(i).Error.stack) numErrors = numErrors +1; % write to log file fprintf( fid, 'ERROR: %s\n', tasks(i).Error.message ); fprintf( fid, '%s\n', tasks(i).Error.getReport ); % write to standard error fprintf( 2, 'ERROR: %s\n', tasks(i).Error.message ); fprintf( 2, '%s\n', tasks(i).Error.getReport ); end fprintf(fid,'\n***** END TASK %d *****\n',i); end fclose(fid); catch ME disp(ME) warning([mfilename ':FailOpenLogFile'],... 'Unable to write log file with task output...'); end
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <title>E-COMMERCE PAGE</title> <link href="https://stackpath.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet"> <link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" rel="stylesheet"> <link rel="stylesheet" href="style.css"> <style> * { margin: 0; padding: 0; box-sizing: border-box; } #container { display: flex; flex-wrap: wrap; width: 95%; /* Adjust the width as needed */ margin: 20px auto; /* Center the container horizontally */ gap: 20px; } #container div { box-shadow: 0px 0px 2px grey; padding: 20px; margin: auto; width: 20%; } #container div img { width: 100%; aspect-ratio: 8/5; display: block; margin: auto; } .btn{ border: none; background-color: rgb(0, 102, 255); color: white; } .btn:hover{ background-color:rgb(61, 59, 59) ; color: white; } /* Media queries for responsiveness */ @media screen and (max-width: 768px) { #container div { width: 40%; /* Each div occupies 40% of the container width on screens up to 768px wide */ } } @media screen and (max-width: 480px) { #container div { width: 100%; /* Each div occupies 100% of the container width on screens up to 480px wide */ } } </style> </head> <body> <div class="main-navbar shadow-sm sticky-top"> <div class="top-navbar"> <div class="container-fluid"> <div class="row"> <div class="col-md-2 my-auto d-none d-sm-none d-md-block d-lg-block"> <h5 class="brand-name">Funda Ecom</h5> </div> <div class="col-md-5 my-auto"> <form role="search"> <div class="input-group"> <input type="search" placeholder="Search your product" class="form-control" /> <button class="btn bg-white" type="submit"> <i class="fa fa-search"></i> </button> </div> </form> </div> <div class="col-md-5 my-auto"> <ul class="nav justify-content-end"> <li class="nav-item"> <a class="nav-link" id="cartpage" href="#"> <i class="fa fa-shopping-cart"></i> Cart <span id="cart">0</span> </a> </li> <li class="nav-item"> <a class="nav-link" href="#"> <i class="fa fa-heart"></i> Wishlist (0) </a> </li> <li class="nav-item dropdown"> <a class="nav-link dropdown-toggle" href="#" id="navbarDropdown" role="button" data-bs-toggle="dropdown" aria-expanded="false"> <i class="fa fa-user"></i> Username </a> <ul class="dropdown-menu" aria-labelledby="navbarDropdown"> <li><a class="dropdown-item" href="#"><i class="fa fa-user"></i> Profile</a></li> <li><a class="dropdown-item" href="#"><i class="fa fa-list"></i> My Orders</a></li> <li><a class="dropdown-item" href="#"><i class="fa fa-heart"></i> My Wishlist</a></li> <li><a class="dropdown-item" href="#"><i class="fa fa-shopping-cart"></i> My Cart</a></li> <li><a class="dropdown-item" href="#"><i class="fa fa-sign-out"></i> Logout</a></li> </ul> </li> </ul> </div> </div> </div> </div> <nav class="navbar navbar-expand-lg"> <div class="container-fluid"> <a class="navbar-brand d-block d-sm-block d-md-none d-lg-none" href="#"> Funda Ecom </a> <button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#navbarSupportedContent" aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation"> <span class="navbar-toggler-icon"></span> </button> <div class="collapse navbar-collapse" id="navbarSupportedContent"> <ul class="navbar-nav me-auto mb-2 mb-lg-0"> <li class="nav-item"> <a class="nav-link" href="#">Home</a> </li> <li class="nav-item"> <a class="nav-link" href="#">All Categories</a> </li> <li class="nav-item"> <a class="nav-link" href="#">New Arrivals</a> </li> <li class="nav-item"> <a class="nav-link" href="#">Featured Products</a> </li> <li class="nav-item"> <a class="nav-link" href="#">Electronics</a> </li> <li class="nav-item"> <a class="nav-link" href="#">Fashions</a> </li> <li class="nav-item"> <a class="nav-link" href="#">Accessories</a> </li> <li class="nav-item"> <a class="nav-link" href="#">Home</a> </li> <li class="nav-item"> <a class="nav-link" href="#">Appliances</a> </li> </ul> </div> </div> </nav> </div> <div id="container"></div> <section> <div class="footer"> <div class="footer-links"> <ul> <li><a href="#">About Us</a></li> <li><a href="#">Contact Us</a></li> <li><a href="#">FAQs</a></li> <li><a href="#">Terms of Service</a></li> <li><a href="#">Privacy Policy</a></li> </ul> </div> <div class="social-links"> <a href="#"><i class="fa fa-facebook"></i></a> <a href="#"><i class="fa fa-twitter"></i></a> <a href="#"><i class="fa fa-instagram"></i></a> <a href="#"><i class="fa fa-linkedin"></i></a> </div> <p style="font-size: 18px;">&copy; 2024 E-Commerce Store. All rights reserved.</p> </div> </section> <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.bundle.min.js"></script> <script> let arr = JSON.parse(localStorage.getItem("eshopCart")) || []; async function getData() { try { let res = await fetch("https://dummyjson.com/products"); let responce = await res.json(); arr = responce; console.log(arr.products); displayData(arr.products); } catch (error) { console.log("error"); } } getData(); let container = document.getElementById("container"); function displayData(data) { data.map((item) => { let div = document.createElement("div"); let brand = document.createElement("h5"); brand.innerText = item.brand; let category = document.createElement("h5"); category.innerText = item.category; let discount = document.createElement("h5"); discount.innerText = item.discountPercentage; let description = document.createElement("h4"); description.innerText = item.description.split(" ").slice(0, 2).join(" ") + " ............"; let price = document.createElement("h6"); price.innerText = item.price; let title = document.createElement("h6"); title.innerText = item.title; let img = document.createElement("img"); img.src = item.images[0]; let btn = document.createElement("button") btn.innerText = "Add to cart" btn.classList.add("btn") btn.addEventListener("click",()=>{ addToCart(item) updatedCartQuantity() }) div.append(brand,img,description,category,discount,price,title,btn); container.append(div); }); } function addToCart(data){ let value = JSON.parse(localStorage.getItem("eshopCart")) || []; value.push(data) localStorage.setItem("eshopCart",JSON.stringify(value)); alert("Add To Cart Success!") } function updatedCartQuantity(){ let cart = document.getElementById("cart"); let value = JSON.parse(localStorage.getItem("eshopCart")) || []; let data = value.length; cart.innerText = data; } updatedCartQuantity() let cartpage = document.getElementById("cartpage"); cartpage.addEventListener("click",()=>{ window.location.href = "./cart.html"; }) </script> </body> </html>
/* * PwnChat -- A Bukkit/Spigot plugin for multi-channel cross-server (via bungeecord) chat. * Copyright (c) 2013 Pwn9.com. Sage905 <[email protected]> * * 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. */ package com.pwn9.pwnchat.utils; import java.io.File; import java.io.IOException; import java.util.logging.FileHandler; import java.util.logging.Level; import java.util.logging.Logger; import java.util.logging.SimpleFormatter; /** * Unified Logging interface for PwnChat-related messages * User: ptoal * Date: 13-10-02 * Time: 4:50 PM */ public class LogManager { // Logging variables public static DebugModes debugMode = DebugModes.off; public static Logger logger; private static File logFolder; private FileHandler logfileHandler; private static LogManager _instance; private LogManager() { } public void setDebugMode(DebugModes dm) { debugMode = dm; } public void debugLow(String message) { if (debugMode.compareTo(DebugModes.low) >= 0) { logger.finer(message); } } public void debugMedium(String message) { if (debugMode.compareTo(DebugModes.medium) >= 0) { logger.finer(message); } } public void debugHigh(String message) { if (debugMode.compareTo(DebugModes.high) >= 0) { logger.finer(message); } } public static LogManager getInstance(Logger l, File f) { if (_instance == null) { _instance = new LogManager(); logger = l; logFolder = f; } return _instance; } public static LogManager getInstance() { if (_instance == null) { throw new IllegalStateException("LogManager not yet initialized!"); } else { return _instance; } } public void stop() { if (logfileHandler != null) { logfileHandler.close(); LogManager.logger.removeHandler(logfileHandler); logfileHandler = null; } } public enum DebugModes { off, // Off low, // Some debugging medium, // More debugging high, // You're crazy. :) } public void start(String fileName ) { if (logfileHandler == null) { try { // For now, one logfile, like the old way. String file = new File(logFolder, fileName).toString(); logfileHandler = new FileHandler(file, true); SimpleFormatter f = new LogFormatter(); logfileHandler.setFormatter(f); logfileHandler.setLevel(Level.FINEST); // Catch all log messages LogManager.logger.addHandler(logfileHandler); LogManager.logger.info("Now logging to " + file ); } catch (IOException e) { LogManager.logger.warning("Unable to open logfile."); } catch (SecurityException e) { LogManager.logger.warning("Security Exception while trying to add file Handler"); } } } }
<template> <div> <EmptyState v-if="workbench.currentInteractions?.length === 0" title="Nothing here yet." description="Add your first option by clicking on the button below." /> <Container v-else lock-axis="y" drag-handle-selector="button.handle" orientation="vertical" @drop="onDrop" > <Draggable v-for="(item, index) in workbench.currentInteractions" :key="item.id" > <ConsentInteraction v-bind="{ item, index }" :key="`${item.id}-${index}`" :ref="bindTemplateRefsForTraversables.bind(index)" /> </Draggable> </Container> <div class="mt-8"> <D9Button label="Add new policy" icon="plus" icon-position="left" color="dark" :isLoading="isCreatingInteraction" @click="createConsentPolicy" /> </div> </div> </template> <script setup lang="ts"> import { useWorkbench } from "@/stores"; import { D9Button } from "@deck9/ui"; import { ref, nextTick } from "vue"; import ConsentInteraction from "./Interactions/ConsentInteraction.vue"; import { Container, Draggable } from "vue3-smooth-dnd"; import EmptyState from "@/components/EmptyState.vue"; import { useKeyboardNavigation } from "@/components/Factory/utils/useKeyboardNavigation"; import { storeToRefs } from "pinia"; const workbench = useWorkbench(); const { currentInteractions } = storeToRefs(workbench); const isCreatingInteraction = ref(false); const onDrop = ({ removedIndex, addedIndex }: any): void => { if (removedIndex === null || addedIndex === null) { return; } workbench.changeInteractionSequence(removedIndex, addedIndex); }; const createConsentPolicy = async () => { isCreatingInteraction.value = true; try { await workbench.createInteraction("consent"); nextTick(() => { focusLastItem(); }); return Promise.resolve(); } catch (error) { return Promise.reject(error); } finally { isCreatingInteraction.value = false; } }; const { bindTemplateRefsForTraversables, focusLastItem } = useKeyboardNavigation(currentInteractions, () => { return; }); </script>
SELECT /* [NAME] - HANA_Security_SecureStore [DESCRIPTION] - SAP HANA secure store overview [SOURCE] - SAP Note 1969700 [DETAILS AND RESTRICTIONS] [VALID FOR] - Revisions: all - Statistics server type: all [SQL COMMAND VERSION] - 2018/11/12: 1.0 (initial version) [INVOLVED TABLES] - M_SECURESTORE [INPUT PARAMETERS] - KEY_TYPE Secure store type 'PERSISTENCE' --> Display secure store information related to PERSISTENCE - IS_CONSISTENT Consistency of secure store 'FALSE' --> Only display inconsistent secure stores '%' --> No restriction related to secure store consistency - IS_CURRENT Information if secure store is current or not 'TRUE' --> Only display current secure stores '%' --> Display current and non-current secure stores [OUTPUT PARAMETERS] - KEY_TYPE: Secure store key type - IS_CONSISTENT: Consistency of secure store (TRUE -> consistent, FALSE -> not consistent) - RESET_COUNT: Number of secure store resets - VERSION: Secure store version - IS_CURRENT: Information if secure store is current (TRUE) or not (FALSE) [EXAMPLE OUTPUT] ---------------------------------------------------------- |KEY_TYPE |IS_CONSISTENT|RESET_COUNT|VERSION|IS_CURRENT| ---------------------------------------------------------- |DPAPI |TRUE | 0| 0|TRUE | |PERSISTENCE|TRUE | 0| 0|TRUE | ---------------------------------------------------------- */ S.KEY_TYPE, S.IS_CONSISTENT, LPAD(S.RESET_COUNT, 11) RESET_COUNT, LPAD(S.VERSION, 7) VERSION, S.IS_CURRENT FROM ( SELECT /* Modification section */ '%' KEY_TYPE, '%' IS_CONSISTENT, '%' IS_CURRENT FROM DUMMY ) BI, M_SECURESTORE S WHERE S.KEY_TYPE LIKE BI.KEY_TYPE AND S.IS_CONSISTENT LIKE BI.IS_CONSISTENT AND S.IS_CURRENT LIKE BI.IS_CURRENT ORDER BY KEY_TYPE
/// <reference types="cypress" /> describe('Intermediate typescript v1 course page', () => { beforeEach(() => { cy.visit( 'http://localhost:8000/course/intermediate-v1', ).waitForRouteChange(); }); it('course sections appear', () => { cy.get('.course-article__title').should( 'have.length.above', 4, ); }); it('title is present', () => { cy.get('h1').should( 'have.text', 'Intermediate TypeScript v1', ); }); it('summary is present', () => { cy.contains('Leverage TypeScript').should('exist'); }); it('logo is present', () => { cy.get('main > header > img') .should('exist') .should('have.attr', 'src', '/intermediate-ts.png'); }); it('clicking on a section works', () => { cy.get('.course-article__title') .contains('Intro') .click(); cy.waitForRouteChange(); cy.location('href').should( 'include', 'course/intermediate-v1/01', ); cy.get('h2').should('have.length.above', 4); }); });
# Getting Started with Create React App This project was bootstrapped with [Create React App](https://github.com/facebook/create-react-app). ## License This project is licensed under the following licenses: - MIT License - Apache License 2.0 - Creative Commons Zero v1.0 Universal - BSD 3-Clause License - ISC License ### MIT License The MIT License is a permissive license that allows you to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the software, subject to certain conditions. ### Apache License 2.0 The Apache License 2.0 is a permissive license that allows you to use, copy, modify, distribute, and/or sell copies of the software, subject to certain conditions. ### Creative Commons Zero v1.0 Universal The Creative Commons Zero v1.0 Universal license allows you to waive all rights to your work worldwide and dedicate it to the public domain. ### BSD 3-Clause License The BSD 3-Clause License is a permissive license that allows you to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the software, subject to certain conditions. ### ISC License The ISC License is a permissive license that allows you to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the software, subject to certain conditions. Of course, you can customize this section to suit your project's specific needs and include any other relevant details or information that you feel would be helpful for users. Additionally, be sure to include the appropriate license file(s) in your project's root directory, so that users can easily access and review the terms of each license. ## Available Scripts In the project directory, you can run: ### `npm start` Runs the app in the development mode.\ Open [http://localhost:3000](http://localhost:3000) to view it in your browser. The page will reload when you make changes.\ You may also see any lint errors in the console. ### `npm test` Launches the test runner in the interactive watch mode.\ See the section about [running tests](https://facebook.github.io/create-react-app/docs/running-tests) for more information. ### `npm run build` Builds the app for production to the `build` folder.\ It correctly bundles React in production mode and optimizes the build for the best performance. The build is minified and the filenames include the hashes.\ Your app is ready to be deployed! See the section about [deployment](https://facebook.github.io/create-react-app/docs/deployment) for more information. ### `npm run eject` **Note: this is a one-way operation. Once you `eject`, you can't go back!** If you aren't satisfied with the build tool and configuration choices, you can `eject` at any time. This command will remove the single build dependency from your project. Instead, it will copy all the configuration files and the transitive dependencies (webpack, Babel, ESLint, etc) right into your project so you have full control over them. All of the commands except `eject` will still work, but they will point to the copied scripts so you can tweak them. At this point you're on your own. You don't have to ever use `eject`. The curated feature set is suitable for small and middle deployments, and you shouldn't feel obligated to use this feature. However we understand that this tool wouldn't be useful if you couldn't customize it when you are ready for it. ## Learn More You can learn more in the [Create React App documentation](https://facebook.github.io/create-react-app/docs/getting-started). To learn React, check out the [React documentation](https://reactjs.org/). ### Code Splitting This section has moved here: [https://facebook.github.io/create-react-app/docs/code-splitting](https://facebook.github.io/create-react-app/docs/code-splitting) ### Analyzing the Bundle Size This section has moved here: [https://facebook.github.io/create-react-app/docs/analyzing-the-bundle-size](https://facebook.github.io/create-react-app/docs/analyzing-the-bundle-size) ### Making a Progressive Web App This section has moved here: [https://facebook.github.io/create-react-app/docs/making-a-progressive-web-app](https://facebook.github.io/create-react-app/docs/making-a-progressive-web-app) ### Advanced Configuration This section has moved here: [https://facebook.github.io/create-react-app/docs/advanced-configuration](https://facebook.github.io/create-react-app/docs/advanced-configuration) ### Deployment This section has moved here: [https://facebook.github.io/create-react-app/docs/deployment](https://facebook.github.io/create-react-app/docs/deployment) ### `npm run build` fails to minify This section has moved here: [https://facebook.github.io/create-react-app/docs/troubleshooting#npm-run-build-fails-to-minify](https://facebook.github.io/create-react-app/docs/troubleshooting#npm-run-build-fails-to-minify)
import React, { useContext, useState } from "react"; import { AiFillEye, AiFillEyeInvisible } from "react-icons/ai"; import * as S from "../styles/styleLogin"; import { Context } from "../context/AuthContext"; import { useNavigate } from "react-router-dom"; function LoginPage() { const navigate = useNavigate(); const { handleLogin } = useContext(Context);// eslint-disable-line no-unused-vars const [email, setEmail] = useState(""); const [password, setPassword] = useState(""); const [showPassword, setShowPassword] = React.useState(false) const handleSubmit = async (e) => { e.preventDefault(); const data = await handleLogin(email, password) if (data) { navigate('/dash') } }; return ( <S.bgAuth> <S.container> <S.boxForm className="login"> <S.titleForm> Faça login para continuar </S.titleForm> <S.Form onSubmit={handleSubmit}> <S.labelForm className="margin-bot"> <S.titleInput> Email </S.titleInput> <S.input type="text" value={email} onChange={(e) => { setEmail(e.target.value) }} /> </S.labelForm> <S.labelForm> <S.titleInput> Senha </S.titleInput> <S.input type="password" value={password} onChange={(e) => { setPassword(e.target.value) }} /> </S.labelForm> <S.buttonForm type="submit" value="Login" /> </S.Form> <S.linkBox>Ainda não possue conta? <S.link href="/auth/register">Registra-se</S.link></S.linkBox> </S.boxForm> </S.container> </S.bgAuth> ); } export default LoginPage;
import React from 'react' import { useTranslation } from 'react-i18next' import { StyleSheet } from 'react-native' import colors from 'libs/ui/colors' import { Box, Button, Link, Modal, ModalProps, Text } from 'libs/ui' type Props = ModalProps & { closeModal: () => void onPress: () => void categoryName?: string } export const DeleteWarnModal = ({ isVisible, closeModal, onPress, categoryName }: Props) => { const { t } = useTranslation() return ( <Modal isVisible={isVisible} animationIn={'fadeIn'} animationOut={'fadeOut'}> <Box backgroundColor={colors.white} padding={24} borderRadius={16} justifyContent="center"> <Text textAlign="center" fontSize={16} lineHeight={24} marginBottom={16} bold> {t('categories_screen.modal_title', { category: categoryName })} </Text> <Text textAlign="center" marginBottom={32} color={colors.mono80}> {t('categories_screen.modal_content')} </Text> <Button onPress={onPress} label={t('categories_screen.delete')} style={styles.logout_btn} labelStyle={styles.white_text} /> <Box padding={12} marginTop={8} alignItems="center"> <Link label={t('categories_screen.cancel')} onPress={closeModal} /> </Box> </Box> </Modal> ) } const styles = StyleSheet.create({ logout_btn: { backgroundColor: colors.destructive }, white_text: { color: colors.white } })
// @ts-check import React from "react" import { formatAmount } from "medusa-react" import translations from "../../translations/success.json" const TotalPrice = ({ cart, locale }) => { return ( <section className="mt-4 mb-2 py-4 border-y border-y-lightGrey"> <div className="flex justify-between text-xs"> <p className="text-darkGrey">{translations[locale].sub_total}</p> <p> {formatAmount({ amount: cart.subtotal, region: cart.region, locale })} </p> </div> <div className="flex justify-between my-2 text-xs"> <p className="text-darkGrey">{translations[locale].shipping}</p> <p> {formatAmount({ amount: cart.shipping_total, region: cart.region, locale, })} </p> </div> <div className="flex justify-between text-xs"> <p className="text-darkGrey">{translations[locale].total}</p> <p> {formatAmount({ amount: cart.total, region: cart.region, locale })} </p> </div> </section> ) } export default TotalPrice
package com.accolite.app.entity; import com.fasterxml.jackson.annotation.JsonIgnore; import lombok.*; import jakarta.persistence.*; @Getter @Setter @NoArgsConstructor @AllArgsConstructor @Entity public class TestCaseOutput { @Id @GeneratedValue(strategy = GenerationType.SEQUENCE) private Long id; @Column(columnDefinition = "LONGTEXT") private String actualOutput; @Column(columnDefinition = "LONGTEXT") private String expectedOutput; private Boolean exitValue; @ManyToOne(fetch = FetchType.LAZY) @JoinColumn(name = "test_submission_id", nullable = false) @JsonIgnore private TestSubmission testSubmission; public TestCaseOutput(String actualOutput, String expectedOutput, Boolean exitValue) { this.actualOutput = actualOutput; this.expectedOutput = expectedOutput; this.exitValue = exitValue; } }
--- title: 在 Office 365 進階電子文件探索中檢視分析結果 f1.keywords: - NOCSH ms.author: chrfox author: chrfox manager: laurawi titleSuffix: Office 365 ms.date: 9/14/2017 audience: Admin ms.topic: article ms.service: O365-seccomp localization_priority: Normal search.appverid: - MOE150 - MET150 ms.assetid: 5974f3c2-89fe-4c5f-ac7b-57f214437f7e description: '了解要檢視 Office 365 進階電子文件探索,包括顯示的工作選項的定義中的分析處理的結果。 ' ms.openlocfilehash: adee00d2b7826827cc14f4ca945952f4892511a1 ms.sourcegitcommit: e741930c41abcde61add22d4b773dbf171ed72ac ms.translationtype: MT ms.contentlocale: zh-TW ms.lasthandoff: 03/07/2020 ms.locfileid: "42557621" --- # <a name="view-analyze-results-in-advanced-ediscovery-classic"></a>在進階電子文件 (傳統) 中檢視分析結果 > [!NOTE] > 進階電子文件探索需要具有進階合規性附加元件的 Office 365 E3,或適用於您組織的 E5 訂閱。如果您沒有該方案,且想要嘗試進階電子文件探索,您可以[註冊 Office 365 企業版 E5 試用版](https://go.microsoft.com/fwlink/p/?LinkID=698279)。 在 [進階電子文件,進度和分析處理程序的結果可以檢視中顯示各種如下所示。 ## <a name="view-analyze-task-status"></a>檢視分析工作狀態 在 [**準備\>分析\>結果\>任務狀態**、 期間和之後分析處理程序執行,會顯示狀態。 ![分析工作狀態](../media/d0372978-ce08-4f4e-a1fc-aa918ae44364.png) 顯示的工作會視所選取的選項而異。 - **ND/ET: 安裝程式**: 準備來執行,例如,設定執行與案例的參數。 - **ND/ET: ND 計算**: 程序近似重複分析的檔案。 - **ND/ET: ET 計算**: 執行電子郵件執行緒分析對整個電子郵件設定。 - **ND/ET: 樞紐分析表和相似之處**: 執行樞紐分析表和檔案相似性處理。 - **ND/ET: 中繼資料更新**: 完成在資料庫中的檔案上收集到的新資料。 - **佈景主題: 佈景主題計算**: 執行佈景主題分析。 (顯示唯有在選取了)。 - **工作狀態**: 這一行顯示在工作完成之後。 執行工作時,會顯示執行的持續時間。 > [!NOTE] > 近似重複項目和電子郵件執行緒 (ND 和 ED) 的分析結果套用至可進行處理的文件數目。 它不包含完全重複的檔案。 ## <a name="view-near-duplicates-and-email-threads-status"></a>檢視接近重複項目和電子郵件執行緒狀態 **目標**母體結果會顯示目標母體中的文件、 電子郵件、 附件及錯誤數目。 **文件**結果顯示樞紐分析表、 唯一近似重複項目,並完全重複的檔案的數目。 **電子郵件**結果會顯示數目 (含),內含減唯一內含的副本,以及電子郵件的其餘部分。 不同類型的電子郵件的結果是: - **Inclusive**: (含) 的電子郵件是在電子郵件執行緒中的終止節點,且包含該執行緒的所有舊的歷程記錄。 因此,檢閱者可以放心地專注於 (含) 的電子郵件,而不需要讀取在執行緒中舊的郵件。 - **減 Inclusive**: (含) 的電子郵件會被指定為內含減號如果沒有父項 (含) 的郵件相關聯的一個或多個不同的附件。 在這個內容、 向上位於電子郵件執行緒或交談的郵件都使用父系字詞包含在該特定 (含) 的電子郵件。 檢閱者可以使用內含減為訊號的指示,雖然不可能需要檢閱 (含) 的電子郵件家長的內容,可能很有用來檢閱 (含) 的路徑家長相關聯的附件。 - **內含的複本**: (含) 的電子郵件指定作為內含複製如果它是另一個郵件副本標示為 (含) 或減號 (含)。 換句話說,此訊息有相同的主體和主體為另一個 (含) 的郵件,因此共同位於相同的節點。 內含複製郵件包含相同的內容,因為他們可以通常會略過檢閱程序。 - **其餘**: 這表示不包含任何唯一的內容,因此不屬於任何先前的三種類別的電子郵件。 這些電子郵件訊息不需要檢閱。 如果郵件包含不在稍後內含電子郵件的附件,可能需要檢閱的附件。 這被指定的電子郵件執行緒內減去 (含) 存在。 **附件**結果會顯示附件,根據這類為唯一的類型和重複項目數目。 ![近似重複項目和電子郵件執行緒](../media/54491303-0ee3-4739-b42e-d1ee486842fd.png) ## <a name="see-also"></a>請參閱 [進階電子文件 (傳統)](office-365-advanced-ediscovery.md) [了解文件相似性](understand-document-similarity-in-advanced-ediscovery.md) [設定分析選項](set-analyze-options-in-advanced-ediscovery.md) [設定忽略文字](set-ignore-text-in-advanced-ediscovery.md) [設定分析進階設定](view-analyze-results-in-advanced-ediscovery.md)
import { forwardRef, MiddlewareConsumer, Module, NestModule, RequestMethod, } from '@nestjs/common'; import { ACCOUNT_TFA, GOOGLE_ACCOUNT_TFA, LOCAL_ACCOUNT_TFA, MANAGE_DATA_SERVICE, TFA_ROUTE, } from 'src/lib/constants'; import { TypeOrmModule } from '@nestjs/typeorm'; import { TwoFactorAuth } from './entities/two-factor-auth.entity'; import { AccountsModule } from 'src/resources/accounts/accounts.module'; import { LocalAccountTFAController } from './controllers/local-account-tfa.controller'; import { TwoFactorAuthService } from './services/two-factor-auth.service'; import { NotificationsModule } from 'src/notifications/notifications.module'; import { TwoFactorAuthManager } from './services/two-factor-auth-manager.service'; import { validateBodyDto } from 'src/lib/middlewares/validate-body-dto'; import { VerificationCodeDto } from 'src/resources/verification_codes/dto/verification-code.dto'; import { TFARoutes } from './enums/tfa-routes'; import { PasswordDto } from 'src/resources/accounts/request-dto/password.dto'; import { validateParamDto } from 'src/lib/middlewares/validate-param.dto'; import { VerificationTokenDto } from 'src/resources/verification_codes/dto/verification-token.dto'; import { VerificationCodesModule } from 'src/resources/verification_codes/verification-codes.module'; import { GoogleAccountTFAController } from './controllers/google-account-tfa.controller'; import { AccountTFAController } from './controllers/account-tfa.controller'; @Module({ imports: [ TypeOrmModule.forFeature([TwoFactorAuth]), NotificationsModule, VerificationCodesModule, forwardRef(() => AccountsModule), ], controllers: [ AccountTFAController, LocalAccountTFAController, GoogleAccountTFAController, ], providers: [ TwoFactorAuthService, TwoFactorAuthManager, { provide: MANAGE_DATA_SERVICE, useClass: TwoFactorAuthService }, ], exports: [TwoFactorAuthService], }) export class TwoFactorAuthModule implements NestModule { configure(consumer: MiddlewareConsumer) { consumer.apply(validateBodyDto(PasswordDto)).forRoutes( { method: RequestMethod.POST, path: LOCAL_ACCOUNT_TFA + TFARoutes.ENABLE_WITH_EMAIL_FACTOR, }, { method: RequestMethod.POST, path: LOCAL_ACCOUNT_TFA + TFARoutes.ENABLE_WITH_MOBILE_PHONE, }, { method: RequestMethod.POST, path: GOOGLE_ACCOUNT_TFA + TFARoutes.ENABLE_WITH_MOBILE_PHONE, }, ); consumer .apply( validateParamDto(VerificationTokenDto), validateBodyDto(VerificationCodeDto), ) .forRoutes( { method: RequestMethod.POST, path: LOCAL_ACCOUNT_TFA + TFARoutes.CREATE + ':token', }, { method: RequestMethod.POST, path: GOOGLE_ACCOUNT_TFA + TFARoutes.CREATE + ':token', }, { method: RequestMethod.POST, path: ACCOUNT_TFA + TFARoutes.DELETE + ':token', }, ); } }
(numericals.common:compiler-in-package numericals.common:*compiler-package*) (define-polymorphic-function rand:gaussian (&key (loc 0) (scale 1) size shape (mean 0) (std 1) out type) :documentation "Returns a scalar or an array of shape SHAPE (or SIZE) filled with random numbers drawn from a gaussian/normal distribution centered at LOC (or MEAN) and standard deviation SCALE (or STD). If SHAPE (or SIZE) is NIL (default) and OUT is NIL, then only a scalar is returned. The following are analogous pairs of arguments. Supply only one of these. - LOC and MEAN - SCALE and STD - SIZE and SHAPE For more information and examples, see: https://numpy.org/doc/stable/reference/random/generated/numpy.random.normal.html") (defpolymorph rand:gaussian (&key ((size null)) ((shape null)) (mean 0.0d0 meanp) (loc 0.0d0 locp) (std 1.0d0 stdp) (scale 1.0d0 scalep) (type nu:*default-float-format*) ((out null))) number (declare (ignore size shape out) (ignorable meanp locp scalep stdp)) (policy-cond:with-expectations (= safety 0) ((assertion (not (and meanp locp)) () "Only one of MEAN or LOC should be supplied") (assertion (not (and stdp scalep)) () "Only one of STD or SCALE should be supplied")) (imlet ((mean (coerce (if meanp mean loc) 'double-float)) (std (coerce (if stdp std scale) 'double-float))) ;; If there were a way to stack allocate a foreign value (portably), ;; then we could have used the CEIGEN-LITE function. (coerce (+ mean (cffi:foreign-funcall "gsl_ran_gaussian" :pointer +gsl-rng+ :double std :double)) type)))) (defpolymorph rand:gaussian (&key ((size list) nil sizep) ((shape list) nil shapep) (mean 0.0d0 meanp) (loc 0.0d0 locp) (std 1.0d0 stdp) (scale 1.0d0 scalep) (type nu:*default-float-format*) ((out null))) simple-array (declare (ignorable out sizep shapep meanp locp stdp scalep)) (policy-cond:with-expectations (= safety 0) ((assertion (not (and shapep sizep)) () "Only one of SHAPE or SIZE should be supplied") (assertion (not (and meanp locp)) () "Only one of MEAN or LOC should be supplied") (assertion (not (and stdp scalep)) () "Only one of STD or SCALE should be supplied")) (let* ((mean (coerce (if meanp mean loc) type)) (std (coerce (if stdp std scale) type)) (shape (if shapep shape size)) (out (nu:empty shape :type type)) (c-name (c-name type 'rand:gaussian)) (sv (array-storage out)) (len (nu:array-total-size out))) (declare (ignorable mean std)) (with-pointers-to-vectors-data ((ptr sv)) (inline-or-funcall c-name len ptr mean std)) out))) (defpolymorph rand:gaussian (&key ((size list) nil sizep) ((shape list) nil shapep) (mean 0.0d0 meanp) (loc 0.0d0 locp) (std 1.0d0 stdp) (scale 1.0d0 scalep) (type nu:*default-float-format* typep) ((out (simple-array <type>)))) (simple-array <type>) (declare (ignorable sizep shapep meanp locp stdp scalep typep type shape size)) (policy-cond:with-expectations (= safety 0) ((assertion (not (and shapep sizep)) () "Only one of SHAPE or SIZE should be supplied") (assertion (not (and meanp locp)) () "Only one of MEAN or LOC should be supplied") (assertion (not (and stdp scalep)) () "Only one of STD or SCALE should be supplied") (assertion (if typep (type= type <type>) t) () "OUT was expected to be a simple array with element type ~S" type) (assertion (if (or shapep sizep) (let ((shape (if shapep shape size))) (equal (narray-dimensions out) shape)) t) () "OUT was expected to be a simple array with shape ~S" (if shapep shape size))) (let* ((mean (coerce (if meanp mean loc) <type>)) (std (coerce (if stdp std scale) <type>)) (c-name (c-name <type> 'rand:gaussian)) (sv (array-storage out)) (len (nu:array-total-size out))) (declare (ignorable mean std)) (with-pointers-to-vectors-data ((ptr sv)) (inline-or-funcall c-name len ptr mean std)) out)))
package miu.mdp.assignment7.animal.ui.addspecies import android.os.Bundle import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import androidx.fragment.app.FragmentManager import miu.mdp.assignment7.animal.model.Species import miu.mdp.assignment7.databinding.DialogAddSpeciesBinding import miu.mdp.core.BaseDialogFragment import miu.mdp.core.showToast class AddSpeciesDialogFragment : BaseDialogFragment<DialogAddSpeciesBinding>() { private lateinit var callback: (Species) -> Unit override fun initializeBinding( inflater: LayoutInflater, container: ViewGroup? ) = DialogAddSpeciesBinding.inflate(inflater, container, false) override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) binding.addBtn.setOnClickListener { val name = binding.name.text.toString() val description = binding.description.text.toString() if (validateInput(name = name, description = description)) { callback(Species(name = name, description = description)) dismissAllowingStateLoss() } else { activity?.showToast("Please input valid data") } } binding.cancelBtn.setOnClickListener { dismissAllowingStateLoss() } } private fun validateInput(name: String, description: String): Boolean { return !(name.isBlank() || description.isBlank()) } companion object { fun show(fragmentManager: FragmentManager, callback: (Species) -> Unit = {}) { val dialogFragment = AddSpeciesDialogFragment() dialogFragment.callback = callback dialogFragment.show(fragmentManager, AddSpeciesDialogFragment::class.java.simpleName) } } }
from rest_framework import serializers from post.models import Post from subreddits.models import Subreddit from post.models import UpVote , DownVote from comments.models import Comment from comments.serializers import ListCommentSerializer class ListPostSerializer(serializers.ModelSerializer): upvote = serializers.SerializerMethodField() downvote = serializers.SerializerMethodField() comment = serializers.SerializerMethodField() class Meta: model = Post fields = '__all__' def get_upvote(self , post): return UpVote.objects.filter(post = post.id).count() def get_downvote(self , post): return DownVote.objects.filter(post = post.id).count() def get_comment(self , post): return ListCommentSerializer( Comment.objects.filter(post=post.id).order_by('-created_at') , many = True).data class PostSerializer(serializers.ModelSerializer): class Meta: model = Post fields = ('title' , 'interest' ) def validate(self , new_post): subreddit_id = new_post.get('subreddit' , None) # * `subreddit_id` is None post upload for user indivitualy if subreddit_id is None: return new_post else: # * `subreddit_id` is exist the post upload for subreddit community subreddit = Subreddit.objects.get(id = subreddit_id) # * check if community exists are not if subreddit is None: return serializers.ValidationError("Given Subreddit is not exist") return new_post
import { DatePipe } from '@angular/common'; import { Component, OnInit } from '@angular/core'; import { AbstractControl, FormControl, FormGroup, ValidatorFn, Validators } from '@angular/forms'; import { Router } from '@angular/router'; import { MenuItem, MessageService } from 'primeng/api'; import { Meeting } from 'src/app/models/meeting/meeting'; import { User } from 'src/app/models/user/user'; import { Workshop } from 'src/app/models/workshop/workshop'; import { MeetingService } from 'src/app/services/meeting/meeting.service'; import { UserService } from 'src/app/services/users/user.service'; import { WorkshopService } from 'src/app/services/workshop/workshop.service'; @Component({ selector: 'app-add-workshop', templateUrl: './add-workshop.component.html', styleUrls: ['./add-workshop.component.scss'] }) export class AddWorkshopComponent implements OnInit { breadcrumbItems!: MenuItem[]; generatedMeeting!:Meeting; // loggedInUser!:User; workshop: Workshop = { workshop_id: "", title: "", description: "", capacity: 0, start_date: new Date(), end_date: new Date(), location: "", link: "", // static untill user token is set userId: "", feedbacks: [], joinedUsers: [], meetingId: '' }; addWorkshopForm!: FormGroup; presenceType: string = 'InPerson'; dateValidity!: boolean; loggedInUser!: User; constructor( private sw:WorkshopService, private meetingServie:MeetingService, private datePipe: DatePipe, private messageService:MessageService, private router:Router, private userService:UserService ) { } //options for workshop stateOptions: any[] = [ { label: 'In-Person', value: 'inPerson' }, { label: 'Online', value: 'online' } ]; //getters for from get title() { return this.addWorkshopForm.get('title') }; get description() { return this.addWorkshopForm.get('description') }; get capacity() { return this.addWorkshopForm.get('capacity') }; get start_date() { return this.addWorkshopForm.get('start_date') }; get end_date() { return this.addWorkshopForm.get('end_date') }; get location() { return this.addWorkshopForm.get('location') }; get link() { return this.addWorkshopForm.get('link') }; //custom date range validity validator endDateValidator() { const start_date = new Date(this.addWorkshopForm.value.start_date); const end_date = new Date(this.addWorkshopForm.value.end_date); return this.dateValidity = end_date >= start_date }; //format date formatDate(date: Date): Date { const formattedDate = this.datePipe.transform(date, 'yyyy-MM-dd'); return formattedDate ? new Date(formattedDate) : new Date(); } //add workshop addWorkshop() { if (this.addWorkshopForm.valid) { const formData={ ...this.addWorkshopForm.value, start_date: this.formatDate(this.addWorkshopForm.value.start_date), end_date: this.formatDate(this.addWorkshopForm.value.end_date), meetingId:this.generatedMeeting.meeting_id, userId:this.loggedInUser.id }; console.log(formData); this.sw.addWorkshop(formData).subscribe( res=>{ //show popup message this.messageService.add({severity:'success', summary:'Success', detail:'Workshop updated successfully'}); // wait 8s then route to show workshops setTimeout(() => { this.router.navigateByUrl("/workshopBack/show") }, 800); }, err=>{ // show error popup this.messageService.add({severity:'error', summary:'Error', detail:'Failed to update workshop'}); } ); } } ngOnInit(): void { this.breadcrumbItems = [ { label: 'dashboard', routerLink: '/dashboard' }, { label: 'workshops', routerLink: '/workshopBack/show' }, { label: 'add' } ]; //fetch local storage var email= window.localStorage.getItem("email"); console.log(email); if (email ) { this.userService.findUserByEmail(email).subscribe( res=>{ this.loggedInUser=res as User; console.log(this.loggedInUser); }, err=>{ console.log(err); } ); } //add workshop form this.addWorkshopForm = new FormGroup({ title: new FormControl(this.workshop.title, Validators.required), description: new FormControl(this.workshop.description, Validators.required), capacity: new FormControl(this.workshop.capacity, [Validators.required, Validators.pattern('^[1-9][0-9]*$')]), start_date: new FormControl(this.workshop.start_date, Validators.required), end_date: new FormControl(this.workshop.end_date, [Validators.required]), location: new FormControl(this.workshop.location), // link: new FormControl(this.workshop.link), // userId: new FormControl(this.workshop.userId), }) } // creating meeting createMeeting() { this.meetingServie.addMeeting().subscribe( res=>{ this.generatedMeeting=res as Meeting; }, err=>{ console.log(err); } ); } }
#include <iostream> #include <stdio.h> #include <algorithm> using namespace std; //endl 쓰면 느리다. -> 한번 호출될때마다 출력버퍼 밀어 초기화됨. //아래 3문장 또는 scanf와 printf를 추천한다. void hanoi(int N, int num1, int num2, int num3) { if (N == 1) { //cout << num1 << " " << num3 << endl; printf("%d %d\n", num1, num3); return; } else { hanoi(N-1, num1, num3, num2); //cout << num1 << " " << num3 << endl; printf("%d %d\n", num1, num3); hanoi(N-1, num2, num1, num3); return; } } int count(int N) { if (N == 1) return 2; return 2 * count(N - 1); } int main() { //ios::sync_with_stdio(false); //cin.tie(0); //cout.tie(0); int N; //cin >> N; //여기서는 scanf_s 지만, 백준에서는 scanf 쓴다. scanf_s("%d", &N); //오래 걸리는 pow 함수 //cout << count(N)-1 << endl; printf("%d\n", count(N) - 1); if(N<=20) hanoi(N, 1, 2, 3); return 0; }
<?php namespace App\Console\Commands; use Illuminate\Console\Command; use Illuminate\Filesystem\Filesystem; abstract class Crud extends Command { protected static function checkIfFileExists(string $file_path): bool { return !empty(glob($file_path)); } protected static function getSourceFile(string $stub_path, array $stub_variables) { return self::_getStubContents($stub_path, $stub_variables); } private static function _getStubContents($stub , $stub_variables = []) { $contents = file_get_contents($stub); foreach($stub_variables as $search => $replace) { $contents = str_replace('{{ '.$search.' }}' , $replace, $contents); } return $contents; } protected static function saveFile(string $destination, string $content, string $create_path_if_not_exist = null) { $filesystem = new Filesystem; if($create_path_if_not_exist && !$filesystem->isDirectory($create_path_if_not_exist)) { $filesystem->makeDirectory($create_path_if_not_exist, 0777, true, true); } $filesystem->put($destination, $content); } protected function getNameFileStub(string $name_file, bool $with_account) { if($with_account) { $name_file .= '-with-account'; } return $name_file; } }
<html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>v-if条件渲染</title> <script src="./vue.js"></script> </head> <body> <div id = 'app'> <!-- 条件渲染——VUE会操作DOM,但为false时 删除此dom --> <div v-if="show"> {{message}} </div> <!-- else or if else必须紧跟在 if之后, --> <div v-else >esle</div> <!-- show渲染机制是 样式的隐藏 --> <div v-show="show"> bye wolrd </div> </div> <script> var vm = new Vue({ el:'#app', data() { return { message:'hello world', show:false } }, }) </script> </body> </html>
#!/usr/bin/perl -w use strict; use FS::UID qw(adminsuidsetup); use FS::Record qw(qsearch); use FS::cust_svc; use FS::svc_acct; &untaint_argv; #what it sounds like (eww) my($user, $action, $groupname, $svcpart) = @ARGV; adminsuidsetup $user; my @svc_acct = map { $_->svc_x } qsearch('cust_svc', { svcpart => $svcpart } ); if ( lc($action) eq 'add' ) { foreach my $svc_acct ( @svc_acct ) { my @groups = $svc_acct->radius_groups; next if grep { $_ eq $groupname } @groups; push @groups, $groupname; my %hash = $svc_acct->hash; $hash{usergroup} = \@groups; my $new = new FS::svc_acct \%hash; my $error = $new->replace($svc_acct); die $error if $error; } } else { die &usage; } # subroutines sub untaint_argv { foreach $_ ( $[ .. $#ARGV ) { #untaint @ARGV $ARGV[$_] =~ /^(.*)$/ || die "Illegal arguement \"$ARGV[$_]\""; $ARGV[$_]=$1; } } sub usage { die "Usage:\n\n freeside-radgroup user action groupname svcpart\n"; } =head1 NAME freeside-radgroup - Command line utility to manipulate radius groups =head1 SYNOPSIS freeside-addgroup user action groupname svcpart =head1 DESCRIPTION B<user> is a freeside user as added with freeside-adduser. B<command> is the action to take. Available actions are: I<add> B<groupname> is the group to add (or remove, etc.) B<svcpart> specifies which accounts will be updated. =head1 EXAMPLES freeside-radgroup freesideuser add groupname 3 Adds I<groupname> to all accounts with service definition 3. =head1 BUGS =head1 SEE ALSO L<freeside-adduser>, L<FS::svc_acct>, L<FS::part_svc> =cut
using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Hosting; using Microsoft.AspNetCore.HttpsPolicy; using Microsoft.AspNetCore.ResponseCompression; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Hosting; using System.Linq; using NBG.Visitor_Registration.Server.ModelContexts; using NBG.Visitor_Registration.Server.Repositories; using Microsoft.EntityFrameworkCore; using NBG.Visitor_Registration.Server.Data; using System; namespace NBG.Visitor_Registration.Server { public class Startup { public Startup(IConfiguration configuration) { Configuration = configuration; } public IConfiguration Configuration { get; } // This method gets called by the runtime. Use this method to add services to the container. // For more information on how to configure your application, visit https://go.microsoft.com/fwlink/?LinkID=398940 public void ConfigureServices(IServiceCollection services) { services.AddControllersWithViews(); services.AddRazorPages(); //13.09.2021 services.AddDbContext<VisitorContext>( options => options.UseNpgsql( Configuration.GetConnectionString("LocalConnection") //appsettings.json ) ); services.AddScoped<IVisitorContext>(provider => provider.GetService<VisitorContext>()); // services.AddScoped<IVisitorRepository, VisitorRepository>(); services.AddAutoMapper(AppDomain.CurrentDomain.GetAssemblies()); } // This method gets called by the runtime. Use this method to configure the HTTP request pipeline. public void Configure(IApplicationBuilder app, IWebHostEnvironment env) { if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); app.UseWebAssemblyDebugging(); } else { app.UseExceptionHandler("/Error"); // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts. app.UseHsts(); } app.UseHttpsRedirection(); app.UseBlazorFrameworkFiles(); app.UseStaticFiles(); app.UseRouting(); app.UseEndpoints(endpoints => { endpoints.MapRazorPages(); endpoints.MapControllers(); endpoints.MapFallbackToFile("index.html"); }); // //PrepareDb.PreparePopulation(app); } } }
package vn.ztech.software.ecomSeller.ui.order.order import android.util.Log import androidx.lifecycle.MutableLiveData import androidx.lifecycle.ViewModel import androidx.lifecycle.viewModelScope import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.flow.collect import kotlinx.coroutines.flow.flowOn import kotlinx.coroutines.launch import vn.ztech.software.ecomSeller.api.request.CreateOrderRequest import vn.ztech.software.ecomSeller.api.request.GetShippingOptionsReq import vn.ztech.software.ecomSeller.api.response.CartProductResponse import vn.ztech.software.ecomSeller.api.response.ShippingOption import vn.ztech.software.ecomSeller.common.LoadState import vn.ztech.software.ecomSeller.common.extension.toLoadState import vn.ztech.software.ecomSeller.model.* import vn.ztech.software.ecomSeller.ui.order.IOrderUserCase import vn.ztech.software.ecomSeller.util.CustomError import vn.ztech.software.ecomSeller.util.errorMessage import vn.ztech.software.ecomSeller.util.extension.toCartItems private const val TAG = "OrderViewModel" class OrderViewModel(private val shippingUseCase: IShippingUserCase, val orderUseCase: IOrderUserCase): ViewModel() { val loading = MutableLiveData<Boolean>() val error = MutableLiveData<CustomError>() val products = MutableLiveData<MutableList<CartProductResponse>>() val currentSelectedAddress = MutableLiveData<AddressItem>() val shippingOptions = MutableLiveData<List<ShippingOption>>() val currentSelectedShippingOption = MutableLiveData<ShippingOption>() val loadingShipping = MutableLiveData<Boolean>() val orderCost = MutableLiveData<OrderCost>() val createdOrder = MutableLiveData<OrderDetails>() fun getShippingOptions(getShippingOptionReq: GetShippingOptionsReq, isLoadingEnabled: Boolean = true){ viewModelScope.launch { shippingUseCase.getShippingOptions(getShippingOptionReq).flowOn(Dispatchers.IO).toLoadState().collect { when(it){ LoadState.Loading -> { if(isLoadingEnabled) loadingShipping.value = true } is LoadState.Loaded -> { loadingShipping.value = false shippingOptions.value = it.data Log.d("getShippingOptions", shippingOptions.value.toString()) } is LoadState.Error -> { loadingShipping.value = false error.value = errorMessage(it.e) Log.d("getShippingOptions: error", it.e.message.toString()) } } } } } fun checkIfCanGetShippingOptions(): Boolean { Log.d(TAG, "${!products.value.isNullOrEmpty()} && ${currentSelectedAddress.value != null}") return !products.value.isNullOrEmpty() && currentSelectedAddress.value != null } fun calculateCost(){ val productsCost = products.value?.sumOf { it.price*it.quantity }?:-1 val shippingFee = currentSelectedShippingOption.value?.fee?.total?:-1 orderCost.value = OrderCost(productsCost, shippingFee, productsCost+shippingFee) } fun createOrder(products: MutableList<CartProductResponse>?, addressItem: AddressItem?, shippingOption: ShippingOption?) { if (products.isNullOrEmpty() || addressItem == null || shippingOption == null){ if(addressItem==null){ error.value = errorMessage(CustomError(customMessage = "Please choose an address")) }else if(shippingOption == null){ error.value = errorMessage(CustomError(customMessage = "Please choose a shipping option")) }else{ error.value = errorMessage(CustomError(customMessage = "Products is empty, go shopping please")) } }else{ val createOrderRequest = CreateOrderRequest( addressItemId = addressItem._id, orderItems = products.toCartItems(), shippingServiceId = shippingOption.service_id, note = "" //todo: implement ui for Note ) viewModelScope.launch { orderUseCase.createOrder(createOrderRequest).flowOn(Dispatchers.IO).toLoadState().collect{ when(it){ LoadState.Loading -> { loading.value = true } is LoadState.Loaded -> { loading.value = false createdOrder.value = it.data Log.d("createOrder", createdOrder.value.toString()) } is LoadState.Error -> { loading.value = false error.value = errorMessage(it.e) Log.d("createOrder: error", it.e.message.toString()) } } } } } } data class OrderCost( var productsCost: Int = -1, var shippingFee: Int = -1, var totalCost: Int = -1, ) fun clearErrors() { error.value = null } }
#' First clear the environment of variables rm(list=ls(all=TRUE)) # get root director of project root.dir <- getwd() # setwd(dir = "/Group/react2_study5/report_phases_combined/projects/omicron_symptom_profiling/") outpath <- paste0(root.dir,"/output/") figpath <- paste0(root.dir,"/plots/") source("E:/Group/functions/load_packages.R", local = T) source("E:/Group/functions/full_join_multiple_datasets.R", local = T) source("E:/Group/functions/wrangle_cleaner_functions.R", local = T) source("E:/Group/functions/cats_and_covs.R", local = T) source("E:/Group/react2_study5/report_phases_combined/projects/function_scripts/create_subfolder.R", local = T) source("E:/Group/react2_study5/report_phases_combined/projects/function_scripts/forest_plot.R", local = T) source("E:/Group/react2_study5/report_phases_combined/projects/function_scripts/save_styled_table.R", local = T) source("E:/Group/react2_study5/report_phases_combined/projects/function_scripts/stability_selection.R", local = T) #' Pull in packages needed package.list <- c("prevalence","mgcv","knitr","MASS","kableExtra","table1","dplyr", "tidyr", "pheatmap","OverReact", "ggplot2","ggsci", "RColorBrewer", "tidyverse", "lubridate", "readr","ggthemes", "questionr", "foreach", "doParallel","withr", "patchwork","randomcoloR" ) load_packages(package.list) # Import REACT-1 data ----------------------------------------------------- source("E:/Group/react2_study5/report_phases_combined/projects/omicron_symptom_profiling/code/00_bits_and_pieces.R", local = T) source("E:/Group/react2_study5/report_phases_combined/projects/omicron_symptom_profiling/code/00_data_prep.R", local = T) # create subfolder createMySubfolder(subfolderName = "pooled_analysis") # Run analysis ------------------------------------------------------------ symp=sympnames_type_df$symptom_code[[1]] dfRes$variant_inferred %>% class() dfRes$vax_status_number %>% table(dfRes$round, exclude="none") dfRes <- dfRes %>% mutate(vax_count_imputed=case_when(round %in% 1:8 ~ 0, T ~ vax_status_number), variant_inferred_new=factor(case_when(round==17 ~ "Round 17 (Omicron BA.1)", round==19 ~ "Round 19 (Omicron BA.2)", T ~ as.character(variant_inferred)), levels= c("Rounds 2-7 (Wild type)", "Rounds 8-10 (Alpha)", "Rounds 12-15 (Delta)", "Round 17 (Omicron BA.1)", "Round 19 (Omicron BA.2)"))) dfRes$variant_inferred_new %>% table(dfRes$round) runFunctions <- function(symp){ ### Define formula interaction=paste(c(symp,"variant_inferred_new"),collapse = ":") f=paste0("estbinres ~ ",paste(c("age_group_named", "sex", "vax_count_imputed", "variant_inferred_new", symp),collapse = "+"),"+", interaction ) f # Run models mymod_wild_alpha=glm(formula = f,family = "binomial",data = dfRes %>% filter(round%in%c(2:10))) mymod_alpha_delta=glm(formula = f,family = "binomial",data = dfRes %>% filter(round%in%c(8:15))) print("Halfway!") mymod_delta_BA1=glm(formula = f,family = "binomial",data = dfRes %>% filter(round%in%c(12:15,17))) mymod_BA1_BA2=glm(formula = f,family = "binomial",data = dfRes %>% filter(round%in%c(17,19))) ### get model summaries summ_wild_alpha=jtools::summ(mymod_wild_alpha,exp=T)[[1]] %>% as.data.frame() summ_alpha_delta=jtools::summ(mymod_alpha_delta,exp=T)[[1]] %>% as.data.frame() summ_delta_ba1=jtools::summ(mymod_delta_BA1,exp=T)[[1]] %>% as.data.frame() summ_ba1_ba2=jtools::summ(mymod_BA1_BA2,exp=T)[[1]] %>% as.data.frame() ### add interaction column description summ_wild_alpha$variant_interact="Wild-type:Alpha" summ_alpha_delta$variant_interact="Alpha:Delta" summ_delta_ba1$variant_interact="Delta:BA.1" summ_ba1_ba2$variant_interact="BA.1:BA.2" summ_wild_alpha$variable=rownames(summ_wild_alpha) summ_alpha_delta$variable=rownames(summ_alpha_delta) summ_delta_ba1$variable=rownames(summ_delta_ba1) summ_ba1_ba2$variable=rownames(summ_ba1_ba2) res=rbind(summ_wild_alpha,summ_alpha_delta,summ_delta_ba1,summ_ba1_ba2) res$symptom = sympnames_type_df$symptom[sympnames_type_df$symptom_code==symp] res <- res %>% select(symptom,variable, everything()) return(res) } ### Run over all symptoms myresults_list=list() for(symp in sympnames_type_df$symptom_code){ print(symp) myresults_list[[symp]] <- runFunctions(symp) } names(myresults_df) myresults_df=bind_rows(myresults_list) myresults_df <- myresults_df %>% filter(grepl("variant_inferred_new",variable)) myresults_df <- myresults_df %>% filter(grepl(":",variable)) myresults_df <- myresults_df %>% janitor::clean_names() myresults_df <- myresults_df %>% left_join(sympnames_type_df) # sympnames_type_df$symptom_type # # dodge_mult=0.8 # dodger <- position_dodge2(width = dodge_mult,reverse = F) # # myresults_df %>% # ggplot(aes(x=symptom,y = exp_est, # col=variant_interact, fill=variant_interact)) + # geom_point(position = dodger) + # geom_errorbar(aes(ymin=x2_5_percent,ymax=x97_5_percent),position = dodger) + # OverReact::theme_react() + # ggforce::facet_col(.~symptom_type,scales = "free_x") # # # Plot layout grid -------------------------------------------------------- ### Get summary df to fix column widths summ <- myresults_df %>% group_by(symptom_type) %>% summarise(n=n()) # dodge # dodger <- ggstance::position_dodge2v(height = dodge_mult,preserve = "single",reverse = F) dodge_mult=0.9 dodger <- position_dodge2(width = dodge_mult,reverse = F) # join sympnames_type_df <- sympnames_type_df %>% left_join(summ) # set col width sympnames_type_df$col_width=dodge_mult*sympnames_type_df$n/max(sympnames_type_df$n) # # # dodge # # dodger <- ggstance::position_dodge2v(height = dodge_mult,preserve = "single",reverse = F) dodge_mult=0.5 dodger <- position_dodge2(width = dodge_mult,reverse = F) symptype="Smell/taste" plots=list() x=1 for(symptype in c("Overall","Smell/taste","Respiratory/cardiac", "Coryzal (cold-like)", "Gastrointestinal","Fatigue", "Other","Influenza-like")){ # PLot p_prevs=myresults_df %>% mutate( variant_interact = factor(variant_interact, levels = c("Wild-type:Alpha","Alpha:Delta","Delta:BA.1","BA.1:BA.2")), symptom_type = factor(symptom_type, levels = c("Overall", "Smell/taste","Respiratory/cardiac", "Coryzal (cold-like)", "Gastrointestinal","Fatigue", "Other","Influenza-like"))) %>% filter(symptom_type==symptype) %>% ggplot(aes(group=variant_interact)) + geom_hline(yintercept = 1, size=0.3, linetype="dashed", col ="grey30") + geom_hline(yintercept = 4, size=0.2, linetype="dashed", col ="grey50") + geom_hline(yintercept = 16, size=0.2, linetype="dashed", col ="grey50") + # geom_hline(yintercept = 64, size=0.2, linetype="dashed", col ="grey50") + geom_point(aes(x=reorder(symptom,exp_est), y= exp_est, col = variant_interact,width=col_width), size=1.3,position = dodger, shape = 15) + geom_errorbar(aes(x=reorder(symptom,exp_est),y=exp_est,ymin= x2_5_percent, ymax=x97_5_percent,col = variant_interact), size=0.6,position = dodger, width=0.5) + scale_x_discrete(labels = function(x) str_wrap(x, width =17)) + scale_y_continuous(trans = "log2", #breaks = x_seq, labels =function(x) MASS::fractions(x), limits = c(min(myresults_df$x2_5_percent), max(myresults_df$x97_5_percent)))+ # OverReact::scale_fill_imperial(palette = "default") + # OverReact::scale_color_imperial(palette = "default") + scale_color_manual(values = as.character(OverReact::imperial_palettes$default[c(2:5)])) + scale_fill_manual(values = as.character(OverReact::imperial_palettes$default[c(2:5)])) + theme_react(strip_text_size = 10) + # coord_flip() + # facet_grid(scales = "free",rows = "symptom_type",space = "fixed",shrink = T) + ggforce::facet_col(facets = "symptom_type",scales = "free",space = "free") + labs(x="", y="Odds ratio", fill = "", col ="", fill = "") + theme(legend.position = "bottom", panel.spacing = unit(1, "cm"), panel.grid.minor.x = element_blank(), panel.grid.major.x = element_blank()) p_prevs if(!x%in%c(1,2,4)){ p_prevs <- p_prevs+theme(axis.text.y = element_blank(), axis.title.y = element_blank()) } plots[[x]]=p_prevs x=x+1 } # Create design layout=" AAAACCCCCCCCCCCCCCHHHHHHHHHHHHHH DDDDDDDDDDDDDDDDDDDDDFFFFFFFFFFF BBBBBBBEEEEEEEEEEEEEEGGGGGGGGGGG " p_comb <- patchwork::wrap_plots(plots,guides = "collect", design = layout ) & theme(legend.position = "bottom") p_comb # save OverReact::saveREACTplot(p = p_comb,figpath = figpath, filename = paste0("pooled_analysis_interaction_effects"), width = 11,height = 6.5)
package io.ebean.migration.runner; import io.avaje.applog.AppLog; import io.ebean.migration.MigrationConfig; import io.ebean.migration.MigrationException; import io.ebean.migration.MigrationResource; import java.sql.Connection; import java.sql.SQLException; import java.util.List; import static java.lang.System.Logger.Level.*; import static java.lang.System.Logger.Level.WARNING; import static java.util.Collections.emptyList; /** * Actually runs the migrations. */ public class MigrationEngine { static final System.Logger log = AppLog.getLogger("io.ebean.migration"); private final MigrationConfig migrationConfig; private final boolean checkStateOnly; private final boolean fastMode; /** * Create with the MigrationConfig. */ public MigrationEngine(MigrationConfig migrationConfig, boolean checkStateOnly) { this.migrationConfig = migrationConfig; this.checkStateOnly = checkStateOnly; this.fastMode = !checkStateOnly && migrationConfig.isFastMode(); } /** * Run the migrations if there are any that need running. */ public List<MigrationResource> run(Connection connection) { try { long startMs = System.currentTimeMillis(); LocalMigrationResources resources = new LocalMigrationResources(migrationConfig); if (!resources.readResources() && !resources.readInitResources()) { log.log(DEBUG, "no migrations to check"); return emptyList(); } long splitMs = System.currentTimeMillis() - startMs; final var platform = derivePlatform(migrationConfig, connection); final var firstCheck = new FirstCheck(migrationConfig, connection, platform); if (fastMode && firstCheck.fastModeCheck(resources.versions())) { long checkMs = System.currentTimeMillis() - startMs; log.log(INFO, "DB migrations completed in {0}ms - totalMigrations:{1} readResources:{2}ms", checkMs, firstCheck.count(), splitMs); return emptyList(); } // ensure running with autoCommit false setAutoCommitFalse(connection); final MigrationTable table = initialiseMigrationTable(firstCheck, connection); try { List<MigrationResource> result = runMigrations(table, resources.versions()); connection.commit(); if (!checkStateOnly) { long commitMs = System.currentTimeMillis(); log.log(INFO, "DB migrations completed in {0}ms - executed:{1} totalMigrations:{2} mode:{3}", (commitMs - startMs), table.count(), table.size(), table.mode()); int countNonTransactional = table.runNonTransactional(); if (countNonTransactional > 0) { log.log(INFO, "Non-transactional DB migrations completed in {0}ms - executed:{1}", (System.currentTimeMillis() - commitMs), countNonTransactional); } } return result; } catch (MigrationException e) { rollback(connection); throw e; } catch (Throwable e) { log.log(ERROR, "Perform rollback due to DB migration error", e); rollback(connection); throw new MigrationException("Error running DB migrations", e); } finally { table.unlockMigrationTable(); } } finally { close(connection); } } private static void setAutoCommitFalse(Connection connection) { try { connection.setAutoCommit(false); } catch (SQLException e) { throw new MigrationException("Error running DB migrations", e); } } private MigrationTable initialiseMigrationTable(FirstCheck firstCheck, Connection connection) { try { final MigrationTable table = firstCheck.initTable(checkStateOnly); table.createIfNeededAndLock(); return table; } catch (Throwable e) { rollback(connection); throw new MigrationException("Error initialising db migrations table", e); } } /** * Run all the migrations as needed. */ private List<MigrationResource> runMigrations(MigrationTable table, List<LocalMigrationResource> localVersions) throws SQLException { // get the migrations in version order if (table.isEmpty()) { LocalMigrationResource initVersion = lastInitVersion(); if (initVersion != null) { // run using a dbinit script log.log(INFO, "dbinit migration version:{0} local migrations:{1} checkState:{2}", initVersion, localVersions.size(), checkStateOnly); return table.runInit(initVersion, localVersions); } } return table.runAll(localVersions); } /** * Return the last init migration. */ private LocalMigrationResource lastInitVersion() { LocalMigrationResources initResources = new LocalMigrationResources(migrationConfig); if (initResources.readInitResources()) { List<LocalMigrationResource> initVersions = initResources.versions(); if (!initVersions.isEmpty()) { return initVersions.get(initVersions.size() - 1); } } return null; } /** * Return the platform deriving from connection if required. */ private MigrationPlatform derivePlatform(MigrationConfig migrationConfig, Connection connection) { final String platform = migrationConfig.getPlatform(); if (platform != null) { return DbNameUtil.platform(platform); } // determine the platform from the db connection String derivedPlatformName = DbNameUtil.normalise(connection); migrationConfig.setPlatform(derivedPlatformName); return DbNameUtil.platform(derivedPlatformName); } /** * Close the connection logging if an error occurs. */ private void close(Connection connection) { try { if (connection != null) { connection.close(); } } catch (SQLException e) { log.log(WARNING, "Error closing connection", e); } } /** * Rollback the connection logging if an error occurs. */ static void rollback(Connection connection) { try { if (connection != null) { connection.rollback(); } } catch (SQLException e) { log.log(WARNING, "Error on connection rollback", e); } } }
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <meta http-equiv="X-UA-Compatible" content="IE=edge" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <title>Dženis</title> <link rel="stylesheet" href="styles.css" /> <link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.14.0/css/all.css" integrity="sha384-HzLeBuhoNPvSl5KYnjx0BT+WB0QEEqLprO+NBkkk5gbc67FTaL7XIGa2w1L0Xbgc" crossorigin="anonymous" /> <script src="app.js" defer></script> </head> <body> <!-- Navbar Section --> <nav class="navbar"> <div class="navbar-container"> <a href="#home" id="navbar-logo">Dženis</a> <div class="navbar-toggle" id="mobile-menu"> <span class="bar"></span> <span class="bar"></span> <span class="bar"></span> </div> <ul class="navbar-menu"> <li class="navbar-item"> <a href="#home" class="navbar-links" id="home-page">Početna</a> </li> <li class="navbar-item"> <a href="#about" class="navbar-links" id="about-page">O nama</a> </li> <li class="navbar-item"> <a href="#services" class="navbar-links" id="services-page">Usluge</a > </li> <li class="navbar-item"> <a href="#team" class="navbar-links" id="team-page" >Naš tim</a > </li> <li class="navbar-btn"> <a href="#sing-up" class="button" id="sign-up">Kontakt</a> </li> </ul> </div> </nav> <!-- Heading Section --> <div class="heading-section" id="home"> <h1 class="heading-title">SERVIS <span>MOTORKI I KOSILICA</span></h1> <!--image slider start--> <div class="slider"> <div class="slides"> <!--radio buttons start--> <input type="radio" name="radio-btn" id="radio1"> <input type="radio" name="radio-btn" id="radio2"> <input type="radio" name="radio-btn" id="radio3"> <input type="radio" name="radio-btn" id="radio4"> <!--radio buttons end--> <!--slide images start--> <div class="slide first"> <img src="./kosilica.jpg"> </div> <div class="slide"> <img src="./OIP.jpg"> </div> <div class="slide"> <img src="./repair.png"> </div> <div class="slide"> <img src="./kosilica.jpg"> </div> <!--slide images end--> <!--automatic navigation start--> <div class="navigation-auto"> <div class="auto-btn1"></div> <div class="auto-btn2"></div> <div class="auto-btn3"></div> <div class="auto-btn4"></div> </div> <!--automatic navigation end--> </div> <!--manual navigation start--> <div class="navigation-manual"> <label for="radio1" class="manual-btn"></label> <label for="radio2" class="manual-btn"></label> <label for="radio3" class="manual-btn"></label> <label for="radio4" class="manual-btn"></label> </div> <!--manual navigation end--> </div> <!--image slider end--> </div> <!-- About Section --> <div class="main" id="about"> <div class="main-container"> <div class="main-content"> <h1>Šta Vam nudimo?</h1> <h2>Mi vršimo popravku vaših kosilica i motornih pila</h2> <p>Odgovaramo na sva vaša pitanja u vezi kosilica i motornih pila</p> <button class="main-btn"><a href="#">Nazovite nas</a></button> </div> </div> </div> <!-- Services Section --> <div class="services" id="services"> <h1>Naše usluge</h1> <div class="services-wrapper"> <div class="services-card"> <h2>Dijagnostika kosilice</h2> <div class="services-btn"> <button>O</button> </div> </div> <div class="services-card"> <h2>Popravka kosilice</h2> <div class="services-btn"> <button>O</button> </div> </div> <div class="services-card"> <h2>Dijagnostika motorne pile</h2> <div class="services-btn"> <button>O</button> </div> </div> <div class="services-card"> <h2>Popravak motorne pile</h2> <div class="services-btn"><button>O</button></div> </div> </div> </div> <!-- Team Section --> <div class="main" id="team"> <div class="main-container"> <div class="main-content"> <h1>Naš tim</h1> <h2>Najbolji majstori u REGIJI SBK</h2> </div> <div class="main-img__container"> <div class="main-img__card" id="card-2"> <i class="fas fa-user"></i> <span>DŽENIS</span> </div> <div class="main-img__card" id="card-2"> <i class="fas fa-user"></i> <span>SUAD</span> </div> <div class="main-img__card" id="card-2"> <i class="fas fa-user"></i> <span>ELMIR</span> </div> </div> </div> </div> <!-- Footer Section --> <div class="footer-container"> <div class="footer-links"> <div class="footer-link__wrapper"> <div class="footer-link__items"> <h2>O nama</h2> <p>SZR Dženis je specijalizirana radionica za zamjenu dijelova ili popravke na kosilicama i motornim pilama. Vaše kosilice ili pile nam možete dostaviti direktno ili se javiti nama da preuzmemo sa vaše adrese</p> </div> <div class="footer-link__items"> <h2>Kontakt</h2> <span class="fa fa-phone"><a style="margin-left: 1rem;">+387-62-xxx-xxx</a></span> <span class="fa fa-map-marker"><a style="margin-left: 1rem;">Gromile IV</a></span> <span class="fa fa-envelope"><a style="margin-left: 1rem;">[email protected]</a></span> </div> </div> </div> <section class="social-media"> <div class="social-media__wrap"> <a id="footer-logo">Društvene mreže</a> </div> <div class="social-icons"> <a href="/" class="social-icon__link" target="_blank"><i class="fab fa-facebook"></i></a> <a href="/" class="social-icon__link"><i class="fab fa-instagram"></i></a> <a href="/" class="social-icon__link"><i class="fab fa-youtube"></i></a> </div> </section> </div> </div> </body> </html>
''' Creates the theme to be used in our bar chart. ''' import plotly.graph_objects as go import plotly.io as pio THEME = { 'bar_colors': [ '#861388', '#d4a0a7', '#dbd053', '#1b998b', '#A0CED9', '#3e6680' ], 'background_color': '#ebf2fa', 'font_family': 'Montserrat', 'font_color': '#898989', 'label_font_size': 16, 'label_background_color': '#ffffff' } def create_template(): ''' Adds a new layout template to pio's templates. The template sets the font color and font to the values defined above in the THEME dictionary. The plot background and paper background are the background color defined above in the THEME dictionary. Also, sets the hover label to have a background color and font size as defined for the label in the THEME dictionary. The hover label's font color is the same as the theme's overall font color. The hover mode is set to 'closest'. Also sets the colors for the bars in the bar chart to those defined in the THEME dictionary. ''' pio.templates['my_theme'] = go.layout.Template( layout=go.Layout( font=dict( family=THEME['font_family'], color=THEME['font_color'] ), plot_bgcolor=THEME['background_color'], paper_bgcolor=THEME['background_color'], hoverlabel=dict( bgcolor=THEME['label_background_color'], font=dict( size=THEME['label_font_size'], color=THEME['font_color'] ) ), hovermode='closest' ), data_bar=[go.Bar(marker_color=x) for x in THEME['bar_colors']] )
// Copyright (c) AlphaSierraPapa for the SharpDevelop Team (for details please see \doc\copyright.txt) // This code is distributed under the GNU LGPL (for details please see \doc\license.txt) using System; using ICSharpCode.NRefactory; using ICSharpCode.PythonBinding; using NUnit.Framework; namespace PythonBinding.Tests.Converter { /// <summary> /// Tests the C# to Python converter does not add an /// assignment for a variable declaration that has no /// initial value assigned. /// </summary> [TestFixture] public class FieldDeclarationWithNoInitializerTestFixture { string csharp = "class Foo\r\n" + "{\r\n" + "\tprivate int i;\r\n" + "\tpublic Foo()\r\n" + "\t{\r\n" + "\t\tint j = 0;\r\n" + "\t}\r\n" + "}"; [Test] public void ConvertedPythonCode() { NRefactoryToPythonConverter converter = new NRefactoryToPythonConverter(SupportedLanguage.CSharp); string python = converter.Convert(csharp); string expectedPython = "class Foo(object):\r\n" + "\tdef __init__(self):\r\n" + "\t\tj = 0"; Assert.AreEqual(expectedPython, python); } } }
package com.medvedomg.a20220803_vadymzhdanov_nycschools.domain import kotlinx.coroutines.Dispatchers import org.koin.core.qualifier.named import org.koin.dsl.module object DispatchersName { const val IO = "DispatcherIO" const val Main = "DispatcherMain" const val Immediate = "DispatcherImmediate" } internal val domainModule = module { single(named(DispatchersName.IO)) { Dispatchers.IO } single(named(DispatchersName.Main)) { Dispatchers.Main } single(named(DispatchersName.Immediate)) { Dispatchers.Main.immediate } factory { GetSatScoreListUseCase( coroutineDispatcher = get(qualifier = named(DispatchersName.IO)), schoolListRepository = get() ) } factory { GetSchoolListUseCase( coroutineDispatcher = get(qualifier = named(DispatchersName.IO)), schoolListRepository = get() ) } factory { SchoolListInteractor( getSchoolListUseCase = get(), getSatScoreListUseCase = get() ) } }
class Particle { constructor(x, y) { this.pos = createVector(x, y); this.vel = createVector(random(19, 20), 0); this.vel.rotate((TAU / 360) * random(0, 360)); // this.vel.mult(3); this.acc = createVector(0, 0); this.mass = 10; this.rad = 10; this.lifespan = 60; // this.color = color(h, s, v); } applyForce(force) { // const calcedAcc = p5.Vector.div(force, this.mass); // const calcedAcc = force.div(this.mass); this.acc.add(force); } update() { this.vel.add(this.acc); this.vel.mult(magnitude); // this.vel.limit(5); this.pos.add(this.vel); // this.acc.set(0, 0); // this.acc.setMag(0); this.acc.mult(0); this.lifespan--; } display() { // colorMode(HSB, 100); // fill(200, this.lifeSpan * 3); // ellipse(this.pos.x, this.pos.y, this.rad * 2); // stroke(0, this.lifeSpan * 3); // colorMode(RGB); noStroke(); let alpha = map(this.lifespan, 0, 60, 0, 100); fill(0, 50, 255, alpha); ellipse(this.pos.x, this.pos.y, this.rad); } isDead() { return ( this.lifeSpan < 0 || this.pos.x < 0 || this.pos.x > width || this.pos.y < 0 || this.pos.y > height ); } }
import React, { FormEvent, useState } from 'react' import { useSession } from 'next-auth/react' import Image from 'next/image' import Link from 'next/link' import moment from 'moment' import { MdModeEditOutline } from 'react-icons/md' import { BsFillTrashFill } from 'react-icons/bs' import { IoMdSend } from 'react-icons/io' import { AiFillLike } from 'react-icons/ai' import { BiCommentDetail } from 'react-icons/bi' import api from '../lib/axios' import { useRouter } from 'next/router' import { toast } from 'react-toastify' export default function Post({ id, text, date, ownerId, ownerName, ownerImage, ownerEmail, comments, likesCount, likesData, }: any) { const { data: session }: any = useSession() const postDate = moment(date).format('MMMM Do YYYY, h:mm a') const [postText, setPostText] = useState('') const [commentTextState, setCommentTextState] = useState('') const [isEditingPost, setIsEditingPost] = useState(false) const [isCommenting, setIsCommenting] = useState(false) const router = useRouter() const refreshData = () => { router.replace(router.asPath) } const notify = (notif: string) => toast.success(notif) const notifyError = (notif: string) => toast.error(notif) async function handleEditPost(event: FormEvent) { event.preventDefault() try { postText !== '' ? await api.post('/api/posts/edit', { text: postText, id: id, }) : notifyError("Post can't be empty.") } catch (e) { console.error(e) } finally { setIsEditingPost(false) postText !== '' ? notify('Post edited successfully.') : null refreshData() } } async function handleDeletePost() { try { await api.post('/api/posts/delete', { id: id, }) setIsEditingPost(false) } catch (e) { console.error(e) } finally { notify('Post deleted successfully.') refreshData() } } async function handleCreateComment(event: FormEvent) { event.preventDefault() try { commentTextState !== '' ? await api.post('/api/comments/create', { postsId: id, text: commentTextState, email: session?.user?.email, }) : notifyError("Comment can't be empty.") } catch (e) { console.error(e) } finally { setCommentTextState('') setIsCommenting(false) commentTextState !== '' ? notify('Comment posted successfully.') : null refreshData() } } async function handleCreateLike() { try { session ? await api.post('/api/likes/create', { postsId: id, userId: session?.user?.email, }) : null } catch (e) { console.error(e) } finally { refreshData() } } async function handleDeletePostLike(event: any, id: any) { const code = id.map((i: any) => i.id) try { await api.post('/api/likes/postDelete', { id: code[0], }) } catch (e) { console.error(e) } finally { refreshData() } } return ( <div className='flex px-4'> <div className='mx-auto my-4 h-auto w-80 rounded-md bg-white p-5 shadow-md dark:bg-gray-700'> <div className='justify-between'> <div className='flex'> <Image src={ownerImage} width={48} height={48} className='cursor-pointer rounded-full' alt={ownerName + 'profile picture'} onClick={() => router.push('accounts/' + ownerId)} /> <div> <Link href={'accounts/' + ownerId}> <h2 className='ml-3 font-medium text-black dark:text-white'> {ownerName.length > 16 ? ownerName.substring(0, 16) + '...' : ownerName} </h2> </Link> <p className='ml-3 whitespace-nowrap text-sm text-gray-500 dark:text-gray-200'> {postDate} </p> </div> {ownerEmail === session?.user?.email ? ( <div className='-ml-6 flex'> <MdModeEditOutline className='duration-250 cursor-pointer text-gray-400 transition-all ease-in hover:text-gray-500' onClick={() => setIsEditingPost(true)} /> <BsFillTrashFill className='duration-250 ml-2 mr-2 cursor-pointer text-gray-400 transition-all ease-in hover:text-gray-500' onClick={handleDeletePost} /> </div> ) : session?.user?.isAdmin === true ? ( <div className='-ml-6 flex'> <MdModeEditOutline className='duration-250 cursor-pointer text-gray-400 transition-all ease-in hover:text-gray-500' onClick={() => setIsEditingPost(true)} /> <BsFillTrashFill className='duration-250 ml-2 mr-2 cursor-pointer text-gray-400 transition-all ease-in hover:text-gray-500' onClick={handleDeletePost} /> </div> ) : null} </div> </div> {isEditingPost === false ? ( <h1 className='my-5 text-black dark:text-white'> {text.length > 750 ? text.substring(0, 750) + '...' : text} </h1> ) : ( <form onSubmit={handleEditPost} className='mx-auto' > <input type='text' value={postText} onChange={(e: any) => setPostText(e.target.value)} className='rounded-md border bg-white pb-10 pl-4 pr-36 pt-4 outline-0 focus:border-gray-400 xl:pr-44' placeholder='Write something...' defaultValue={text} /> <div className='flex'> <button type='submit' className='duration-250 my-2 block rounded-md bg-blue-700 px-5 py-2 text-white transition-all ease-in hover:bg-blue-800 active:bg-blue-900' > Edit </button> <button onClick={() => setIsEditingPost(false)} className='duration-250 my-2 ml-2 block rounded-md bg-red-700 px-5 py-2 text-white transition-all ease-in hover:bg-red-800 active:bg-red-900' > Cancel </button> </div> </form> )} <div className='flex justify-around gap-5'> {likesData .map((i: any) => i.userId) .includes(session?.user?.email) ? ( <div onClick={(event) => handleDeletePostLike(event, likesData)} className='duration-250 flex w-full cursor-pointer rounded-md bg-blue-500 px-3 py-2 transition-all ease-in hover:bg-blue-600' > <AiFillLike className='text-white' /> {likesCount >= 2 ? ( <div className='flex'> <p className='duration-250 -mt-1 ml-1 font-medium text-white transition-all ease-in hover:text-gray-300'> {likesCount} </p> <p className='duration-250 -mt-1 ml-1 font-medium text-white transition-all ease-in hover:text-gray-300'> Likes </p> </div> ) : likesCount === 1 ? ( <div className='flex'> <p className='duration-250 -mt-1 ml-1 font-medium text-white transition-all ease-in hover:text-gray-300'> {likesCount} </p> <p className='duration-250 -mt-1 ml-1 font-medium text-white transition-all ease-in hover:text-gray-300'> Like </p> </div> ) : ( <div className='flex'> <p className='duration-250 -mt-1 ml-1 font-medium text-white transition-all ease-in hover:text-gray-300'> Like </p> </div> )} </div> ) : ( <div onClick={handleCreateLike} className='duration-250 flex w-full cursor-pointer rounded-md bg-gray-200 px-3 py-2 transition-all ease-in hover:bg-gray-300 dark:bg-gray-500 dark:hover:bg-gray-600' > <AiFillLike className='text-black dark:text-white' /> {likesCount >= 2 ? ( <div className='flex'> <p className='duration-250 -mt-1 ml-1 font-medium text-black transition-all ease-in hover:text-gray-300 dark:text-white'> {likesCount} </p> <p className='duration-250 -mt-1 ml-1 font-medium text-black transition-all ease-in hover:text-gray-300 dark:text-white'> Likes </p> </div> ) : likesCount === 1 ? ( <div className='flex'> <p className='-mt-1 ml-1 font-medium dark:text-white'> {likesCount} </p> <p className='-mt-1 ml-1 font-medium dark:text-white'>Like</p> </div> ) : ( <div className='flex'> <p className='-mt-1 ml-1 font-medium dark:text-white'>Like</p> </div> )} </div> )} {isCommenting === false && session ? ( <div onClick={() => setIsCommenting(true)} className='duration-250 flex w-full cursor-pointer rounded-md bg-gray-200 px-3 py-2 transition-all ease-in hover:bg-gray-300 dark:bg-gray-500 dark:hover:bg-gray-600' > <BiCommentDetail className='text-black dark:text-white' /> <p className='-mt-1 ml-1 font-medium text-black dark:text-white'> Comment </p> </div> ) : ( <div onClick={() => setIsCommenting(false)} className='duration-250 flex w-full cursor-pointer rounded-md bg-gray-200 px-3 py-2 transition-all ease-in hover:bg-gray-300 dark:bg-gray-500 dark:hover:bg-gray-600' > <BiCommentDetail className='text-black dark:text-white' /> <p className='-mt-1 ml-1 font-medium text-black dark:text-white'> Comment </p> </div> )} </div> {isCommenting === true ? ( <form onSubmit={handleCreateComment} className='mx-auto mt-5 flex' > <input type='text' value={commentTextState} onChange={(e: any) => setCommentTextState(e.target.value)} className='w-full rounded-md border bg-gray-200 pl-4 outline-none focus:border-gray-400 dark:border-none dark:bg-gray-600 dark:text-white' placeholder='Comment something...' /> <button type='submit' className='duration-250 ml-2 rounded-md bg-blue-700 px-5 py-3 text-white transition-all ease-in hover:bg-blue-800 active:bg-blue-900' > <IoMdSend className='duration-250 text-white transition-all ease-in hover:text-gray-200' /> </button> </form> ) : null} <div> {comments.map((comment: any) => { async function handleDeleteComment() { await api.post('/api/comments/delete', { id: comment.id, }) notify('Comment deleted successfully.') setIsEditingPost(false) } return ( <div key={comment.id} className='my-6' > <div className='flex'> <div className='flex justify-between'> <Image src={comment?.User?.image} width={40} height={40} className='h-[40px] w-[40px] cursor-pointer rounded-full' alt={comment?.User?.name + 'profile picture'} onClick={() => router.push('accounts/' + comment?.User?.id) } /> <div> <h4 className='ml-3 w-56 cursor-pointer font-medium text-black dark:text-white' onClick={() => router.push('accounts/' + comment?.User?.id) } > {comment?.User?.name.length > 16 ? comment?.User?.name.substring(0, 16) + '...' : comment?.User?.name} </h4> <p className='ml-3 whitespace-nowrap text-sm text-gray-500 dark:text-gray-200'> {moment(comment?.createdAt?.toString()).format( 'MMMM Do YYYY, h:mm a' )} </p> </div> {comment.email === session?.user?.email ? ( <div className='flex'> <BsFillTrashFill className='duration-250 -ml-3 cursor-pointer text-gray-400 transition-all ease-in hover:text-gray-500' onClick={handleDeleteComment} /> </div> ) : session?.user?.isAdmin === true ? ( <div className='flex'> <BsFillTrashFill className='duration-250 -ml-3 cursor-pointer text-gray-400 transition-all ease-in hover:text-gray-500' onClick={handleDeleteComment} /> </div> ) : null} </div> </div> <h3 className='text-black dark:text-white'> {comment.text.length > 750 ? comment.text.substring(0, 750) + '...' : comment.text} </h3> </div> ) })} </div> </div> </div> ) }
<!DOCTYPE html> <html> <head> <link rel="apple-touch-icon" sizes="180x180" href="/apple-touch-icon.png"> <link rel="icon" type="image/png" sizes="32x32" href="/favicon-32x32.png"> <link rel="icon" type="image/png" sizes="16x16" href="/favicon-16x16.png"> <link rel="manifest" href="/site.webmanifest"> <link rel="mask-icon" href="/safari-pinned-tab.svg" color="#5bbad5"> <meta name="msapplication-TileColor" content="#da532c"> <meta name="theme-color" content="#ffffff"> <meta charset="UTF-8"> <title>{% block title %}Welcome!{% endblock %}</title> {% block stylesheets %} <link rel="stylesheet" href="{{ asset('css/main_layout.css') }}"> <link rel="stylesheet" href="{{ asset('css/main_design.css') }}"> {% endblock %} </head> <body> <header> <div id="logo"> <img src="{{ asset('img/images.png') }}" height="80px" width="80px"> </div> <nav> {% if is_granted("IS_AUTHENTICATED_FULLY") %} <a href="{{ path('user_index') }}">Users</a> <a href="{{ path('profile_index') }}">Profiles</a> <a class="login" href="{{ path('logout') }}">Logout</a> {% else %} <a class="login" href="{{ path('login') }}">Login</a> <i id="navSep">|</i> <a class="login" href="{{ path('user_registration') }}">Register</a> {% endif %} </nav> </header> {% block body %} {% endblock %} {% block footer %} {% endblock %} {% block javascripts %}{% endblock %} </body> </html>
import React, { useEffect } from 'react' import { Meteor } from 'meteor/meteor' import { Accounts } from 'meteor/accounts-base' import Avatar from '@material-ui/core/Avatar' import LockOutlinedIcon from '@material-ui/icons/LockOutlined' import Typography from '@material-ui/core/Typography' import { makeStyles } from '@material-ui/core/styles' import { useHistory, useParams, Link as RouterLink } from 'react-router-dom' import Container from '@material-ui/core/Container' import { useSelector, useDispatch } from 'react-redux' import Box from '@material-ui/core/Box' import Button from '@material-ui/core/Button' import CircularProgress from '@material-ui/core/CircularProgress' import Grid from '@material-ui/core/Grid' import Link from '@material-ui/core/Link' import { Messages } from '../../api/common/models' import CONSTANTS from '../../api/common/constants' const useStyles = makeStyles((theme) => ({ paper: { marginTop: theme.spacing(8), display: 'flex', flexDirection: 'column', alignItems: 'center', }, avatar: { margin: theme.spacing(1), backgroundColor: theme.palette.secondary.main, }, form: { width: '100%', // Fix IE 11 issue. height: '250px', marginTop: theme.spacing(1), }, submit: { margin: theme.spacing(3, 0, 2), }, register: { margin: theme.spacing(3, 0, 2), }, })) export default function VerifyEmail() { const classes = useStyles() const history = useHistory() const dispatch = useDispatch() const [verified, setVerified] = React.useState(false) const warning = useSelector((state) => state.globalMessage) || { visible: false, } // dispatch({ type: "canvas", noDrawer: true }); if (Meteor.user()) { history.push('/') } const { token } = useParams() function dashboard() { // dispatch({ type: "canvas", noDrawer: false }); setVerified(true) } useEffect(() => { Accounts.verifyEmail(token, (err) => { if (Meteor.user() && Meteor.user().emails[0].verified) { dashboard() Messages.insert({ timestamp: new Date().valueOf(), userId: Meteor.userId(), title: 'Email Verified', text: `Hooray, you've verified your email!`, read: false, type: CONSTANTS.messageTypes.system, priority: 10, }) } else if (err) { dispatch({ type: 'canvas', globalMessage: { visible: true, text: `Oh Snap. There was a problem verifying your email. (Error: ${err.reason})`, severity: 'error', autoHide: 60000, }, }) } else { dashboard() } }) }, []) const retry = () => { dispatch({ type: 'registration', registrationOpen: true, registrationTitle: `Retry Email Verification`, registrationMessage: `Please try verifying your email again.`, }) } return ( <Container component="main" maxWidth="xs"> <div className={classes.paper}> <Avatar className={classes.avatar}> <LockOutlinedIcon /> </Avatar> {!verified && ( <> <Typography component="h1" variant="h5" style={{ color: '#fff' }}> {warning.visible ? ( <>Unable to Verify Email</> ) : ( <>Verifying Email...</> )} </Typography> <Grid container alignItems="center" justify="center" className={classes.form} > {warning.visible ? ( <Button variant="outlined" color="secondary" onClick={retry}> Try Verifying Again </Button> ) : ( <CircularProgress color="secondary" /> )} </Grid> </> )} {verified && ( <Grid container alignItems="center" justify="center" className={classes.form} spacing={10} > <Grid item xs={12}> <Box m="auto"> <Typography component="h1" variant="h5" style={{ color: '#fff' }} > Woohoo! Email Verified. </Typography> </Box> </Grid> <Grid item xs={12}> <Box m="auto"> <Typography component="div" variant="subtitle1" style={{ color: '#fff', margin: 'auto' }} > Congrats, you&apos;re verified! You can close this window and go back to building your slate, or just{' '} <Link component={RouterLink} style={{ color: '#fff' }} to="/"> go to your dashboard </Link>{' '} and continue here. </Typography> </Box> </Grid> </Grid> )} </div> </Container> ) }
'use client'; import React from 'react'; import SliderComponent from "@/components/SliderComponent"; import SliderPopulares from "@/components/SliderPopulares"; import '../globals.css'; import { register } from "swiper/element/bundle"; import MovieSearch from '@/components/MovieSearch'; import { useRouter } from 'next/navigation'; import Header from '@/components/Header'; register(); export default function Home() { const router = useRouter(); return ( <div className="flex flex-col w-full h-full" > <Header/> <div className="flex flex-col gap-[4em] text-white" > <MovieSearch /> <div className='flex flex-col gap-2 h-auto px-8 ' > <h1 className="titulo">Nuevos & Populares</h1> <SliderPopulares /> </div> <div className='flex flex-col gap-2 h-auto px-8 '> <h1 onClick={()=>router.push(`generos/${878}`)} className="titulo max-w-fit" style={{ cursor: 'pointer' }}>Ciencia Ficción</h1> <SliderComponent genre={878} /> </div> <div className='flex flex-col gap-2 h-auto px-8'> <h1 onClick={()=>router.push(`generos/${16}`)} className="titulo max-w-fit" style={{ cursor: 'pointer' }}>Animadas</h1> <SliderComponent genre={16}/> </div> <div className='flex flex-col gap-2 h-auto px-8'> <h1 onClick={()=>router.push(`generos/${12}`)} className="titulo max-w-fit" style={{ cursor: 'pointer' }}>Aventura</h1> <SliderComponent genre={12}/> </div> <div className='flex flex-col gap-2 h-auto px-8'> <h1 onClick={()=>router.push(`generos/${35}`)} className="titulo max-w-fit" style={{ cursor: 'pointer' }}>Comedia</h1> <SliderComponent genre={35}/> </div> <div className='flex flex-col gap-2 h-auto px-8'> <h1 onClick={()=>router.push(`generos/${27}`)} className="titulo max-w-fit" style={{ cursor: 'pointer' }}>Terror</h1> <SliderComponent genre={27} /> </div> <div className='flex flex-col gap-2 h-auto px-8'> <h1 onClick={()=>router.push(`generos/${53}`)} className="titulo max-w-fit" style={{ cursor: 'pointer' }}>Suspenso</h1> <SliderComponent genre={53} /> </div> <div className='flex flex-col gap-2 h-auto px-8'> <h1 onClick={()=>router.push(`generos/${18}`)} className="titulo max-w-fit" style={{ cursor: 'pointer' }}>Drama</h1> <SliderComponent genre={18} /> </div> <div className='flex flex-col gap-2 h-auto px-8'> <h1 onClick={()=>router.push(`generos/${99}`)} className="titulo max-w-fit" style={{ cursor: 'pointer' }}>Documentales</h1> <SliderComponent genre={99} /> </div> <div className='flex flex-col gap-2 h-auto px-8'> <h1 onClick={()=>router.push(`generos/${36}`)} className="titulo max-w-fit" style={{ cursor: 'pointer' }}>Historia</h1> <SliderComponent genre={36} /> </div> <div className='flex flex-col gap-2 h-auto px-8'> <h1 onClick={()=>router.push(`generos/${10402}`)} className="titulo max-w-fit" style={{ cursor: 'pointer' }}>Musicales</h1> <SliderComponent genre={10402} /> </div> <div className='flex flex-col gap-2 h-auto px-8'> <h1 onClick={()=>router.push(`generos/${37}`)} className="titulo max-w-fit" style={{ cursor: 'pointer' }}>Cowboys</h1> <SliderComponent genre={37} /> </div> <div className='flex flex-col gap-2 h-auto px-8'> <h1 onClick={()=>router.push(`generos/${14}`)} className="titulo max-w-fit" style={{ cursor: 'pointer' }}>Fantasía</h1> <SliderComponent genre={14} /> </div> <div className='flex flex-col gap-2 h-auto px-8'> <h1 onClick={()=>router.push(`generos/${10752}`)} className="titulo max-w-fit" style={{ cursor: 'pointer' }}>Guerra</h1> <SliderComponent genre={10752} /> </div> <div className='flex flex-col gap-2 h-auto px-8'> <h1 onClick={()=>router.push(`generos/${80}`)} className="titulo max-w-fit" style={{ cursor: 'pointer' }}>Crimen</h1> <SliderComponent genre={80} /> </div> <div className='flex flex-col gap-2 h-auto px-8'> <h1 onClick={()=>router.push(`generos/${10749}`)} className="titulo max-w-fit" style={{ cursor: 'pointer' }}>Romance</h1> <SliderComponent genre={10749}/> </div> </div> <footer className="bg-neutral-200 text-center dark:bg-neutral-700 lg:text-left mt-20"> <div className="p-3 text-center text-neutral-700 dark:text-neutral-200"> © 2024 Copyright: <a className="text-neutral-800 dark:text-neutral-400" href="https://tw-elements.com/" > Esto Es Cine Argentina</a> </div> </footer> </div> ); }
package Hackerthon; import java.util.Scanner; import java.util.regex.Pattern; import java.util.regex.PatternSyntaxException; public class Patterns { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); int t = scanner.nextInt(); // Number of test cases scanner.nextLine(); // Consume the newline after reading the integer for (int i = 0; i < t; i++) { String pattern = scanner.nextLine(); // Read the pattern if (isValidRegex(pattern)) { System.out.println("Valid"); } else { System.out.println("Invalid"); } } scanner.close(); } public static boolean isValidRegex(String pattern) { try { Pattern.compile(pattern); return true; } catch (PatternSyntaxException e) { return false; } } } // Using Regex, we can easily match or search for patterns in a text. Before searching for a pattern, we have to specify one using some well-defined syntax. // // In this problem, you are given a pattern. You have to check whether the syntax of the given pattern is valid. // // Note: In this problem, a regex is only valid if you can compile it using the Pattern.compile method. // // Input Format // // The first line of input contains an integer // , denoting the number of test cases. The next // // lines contain a string of any printable characters representing the pattern of a regex. // // Output Format // // For each test case, print Valid if the syntax of the given pattern is correct. Otherwise, print Invalid. Do not print the quotes. // // Sample Input // // 3 // ([A-Z])(.+) // [AZ[a-z](a-z) // batcatpat(nat // // Sample Output // // Valid // Invalid // Invalid
# tx_simulation The `tx_simulation` tool facilitates transaction simulation using `aiken tx simulate` in conjunction with Koios. The simulation script assumes the contracts are implemented using PlutusV2, relies on reference script UTxOs, and operates under the assumption that within a transaction, only the scripts themselves contain datums. It's important to note that specific edge cases may need to be considered when transitioning to a production environment. Additionally, the simulation script currently supports both the mainnet and pre-production environments but does not provide support for preview environments at this time. The tx simulation script was tested with `Python 3.10.12`, `Aiken v1.0.19-alpha`, and `Ubuntu 22.04.2 LTS`. ## Requirements It is highly suggested that Aiken is installed and on path. [Install Aiken](https://aiken-lang.org/installation-instructions) A precompile version of Aiken may be used with the `from_file` or `from_cbor` functions. ## Development It is highly suggested to work on `tx_simulation` inside a virtual environment. ```bash # Create a Python virtual environment python3 -m venv venv # Activate the virtual environment source venv/bin/activate # On Windows, use: venv\Scripts\activate # Install required Python packages pip install -r requirements.txt ``` ## Use The `tx_simulation` script can simulate a transaction from a draft file or from pure cbor. ```bash import tx_simulation # can be used on a tx.draft file required_units = tx_simulation.from_file('tx.draft') # can be used directory on the tx cbor required_units = tx_simulation.from_cbor(tx_cbor) ``` It will either return a list of dictionaries of the units or a list with an empty dict if it fails. An output example is shown below. ```json [{ "mem": 443656, "cpu": 171399581 }] ``` ## Test Data Inside the `test_data` folder are some example tx drafts. The script can be tested by running the command below. ```bash python tx_simulation.py ``` ## Known Issues Any scripts involving fee logic always error resulting in an empty dictionary being returned.
import Form from '@/components/modules/Form'; import moment from 'moment' import { useEffect, useRef, useState } from 'react'; import axios from '@/services/axiosConfig'; import { useRouter } from 'next/router'; const EditCustomerPage = ({ data, customerId }) => { const date = data.date ? moment(data.date).utc().format('YYYY-MM-DD') : ''; const [form, setForm] = useState({ name: data.name || '', lastName: data.lastName || '', email: data.email || '', phone: data.phone || '', address: data.address || '', postalCode: data.postalCode || '', products: data.products || '', date: date, }); const router = useRouter(); const handleEdit = async () => { const data = await axios.patch(`/edit/${customerId}`, { data: { form }, }); if (data.status === 201) router.push('/'); }; const handleCancel = () => { router.push('/') } return ( <div className='max-w-[950px] mx-auto mt-8 px-4'> <h4 className='text-white text-xl font-bold'>Edit customer</h4> <Form form={form} setForm={setForm} /> <div className='mt-4 flex justify-between'> <button onClick={handleCancel} className='border border-red-500 px-5 py-2 rounded text-red-400 transition hover:text-red-300 hover:border-red-400' > Cancel </button> <button onClick={handleEdit} className='border border-green-500 px-5 py-2 rounded text-green-400 transition hover:text-green-300 hover:border-green-400' > Edit </button> </div> </div> ); }; export default EditCustomerPage;
import { UsersService } from './users.service'; import { UpdateUserDto } from './dto/update-user.dto'; import { Body, Post, Controller, Get, Param, Patch, /* Post, */ UseGuards, UseFilters, } from '@nestjs/common/decorators'; import { User } from './entities/user.entity'; import { AuthUser } from 'src/common/decorators/user.decorator'; import { FindOneOptions } from 'typeorm'; import { JWTAuthGuard } from 'src/auth/guard/jwt-auth.guard'; import { WishesService } from 'src/wishes/wishes.service'; import { Wish } from 'src/wishes/entities/wish.entity'; import { FindUsersDto } from './dto/query-user.dto'; import { UserProfileResponseDto } from './dto/profile-respons-user.dto'; import { UserWishesDto } from './dto/wishes-user.dto'; import { UserPublicProfileResponseDto } from './dto/public-profile-response-user.dto'; import { HttpExceptionFilter } from 'src/filters/HttpException.filter'; import { HttpException } from '@nestjs/common'; @UseGuards(JWTAuthGuard) @Controller('users') @UseFilters(HttpExceptionFilter) export class UsersController { constructor( private readonly usersService: UsersService, private readonly wishesService: WishesService, ) {} @Get('me') async findOwn(@AuthUser() user: User): Promise<UserProfileResponseDto> { const query: FindOneOptions<User> = { where: { id: user.id }, select: { email: true, username: true, id: true, avatar: true, createdAt: true, updatedAt: true, about: true, }, }; return this.usersService.findOne(query); } @Patch('me') async update( @AuthUser() user: User, @Body() updateUserDto: UpdateUserDto, ): Promise<UserProfileResponseDto> { const updateUser = await this.usersService.update(user, updateUserDto); if (updateUser) return updateUser; else { throw new HttpException('Пользователя не существует', 400); } } @Get('me/wishes') async findMyWishes(@AuthUser() user: User): Promise<Wish[]> { return await this.wishesService.findWishById(user.id); } //надо написать запрос по этому маршруту /* @Post('find') */ @Get(':username') async findUser(@Param() param: { username: string }): Promise<User> { const { username } = param; return await this.usersService.findUserName(username); } @Get(':username/wishes') async findUserWishes( @Param() param: { username: string }, ): Promise<UserWishesDto[]> { const { username } = param; return await this.usersService.findUserWishes(username); } @Post('find') async findByQuery( @Body() body: FindUsersDto, ): Promise<UserPublicProfileResponseDto[]> { return await this.usersService.findByQuery(body.query); } }