text
stringlengths
184
4.48M
import { Colors } from "@/theme/colors"; import { SearchBoxInput } from "@guallet/ui-react"; import { Group, Button } from "@mantine/core"; import { useState } from "react"; interface Props { onAddNewAccount: () => void; onSearchQueryChanged: (searchQuery: string) => void; } export function AccountsHeader({ onAddNewAccount, onSearchQueryChanged, }: Props) { const [query, setQuery] = useState(""); return ( <Group justify="space-between"> <SearchBoxInput style={{ flexGrow: 1 }} query={query} onSearchQueryChanged={(query) => { setQuery(query); onSearchQueryChanged(query); }} /> <Button variant="outline" radius="xl" onClick={onAddNewAccount} bg={Colors.white} > Add new account </Button> </Group> ); }
import { Component, OnInit, Inject } from '@angular/core'; import { MatDialogRef, MAT_DIALOG_DATA, MatDialog } from '@angular/material/dialog'; import { FormBuilder, FormGroup, Validators } from '@angular/forms'; import { Observable } from 'rxjs'; export interface CommentDialogData { title: string; commentContentMessage: string; commentContent: string; } @Component({ selector: 'app-comment-dialog', templateUrl: './comment-dialog.component.html', styleUrls: ['./comment-dialog.component.css'] }) export class CommentDialogComponent implements OnInit { commentForm: FormGroup; static openCommentDialog(dialog: MatDialog, dialogData: CommentDialogData): Observable<any> { const dialogRef = dialog.open(CommentDialogComponent, { width: '60em', data: { title: dialogData.title, commentContentMessage: dialogData.commentContentMessage, commentContent: dialogData.commentContent, }, backdropClass: 'backdropClass', panelClass: 'dialog', }); return dialogRef.afterClosed(); } constructor( public dialogRef: MatDialogRef<CommentDialogComponent>, @Inject(MAT_DIALOG_DATA) public data: CommentDialogData, private formBuilder: FormBuilder ) { } ngOnInit(): void { this.commentForm = this.formBuilder.group( { commentContent: [this.data.commentContent, [Validators.required, Validators.minLength(1), Validators.maxLength(200)]], } ); } get commentContent() { return this.commentForm.get('commentContent'); } onSubmit(commentForm: FormGroup) { if (commentForm.valid) { this.dialogRef.close({ content: this.commentContent.value.trim() }); } } onClose() { this.dialogRef.close(); } }
import React from 'react'; import Post from './Post/Post'; import styles from './MyPosts.module.css'; const MyPosts = (props) => { const postsElements = props.posts .map(post => <Post message={post.message} likesCount={post.likesCount}/>) const newPostElement = React.createRef() const onAddPost = () => { props.addPost() } const onPostChange = () => { const text = newPostElement.current.value props.updateNewPostText(text) } return ( <div className={styles.myPostsContent}> <h3>My Posts</h3> <div> <div> <textarea onChange={onPostChange} value={props.newPostText} ref={newPostElement}/> </div> <div> <button onClick={onAddPost}>Add post</button> </div> </div> <div className={styles.posts}> {postsElements} </div> </div> ) } export default MyPosts
package com.roydon.community.adapter; import android.annotation.SuppressLint; import android.content.Context; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ImageView; import android.widget.TextView; import androidx.annotation.NonNull; import androidx.recyclerview.widget.RecyclerView; import com.roydon.community.R; import com.roydon.community.domain.vo.MallOrderGoodsVO; import com.squareup.picasso.Picasso; import java.util.List; public class UserOrderGoodsAdapter extends RecyclerView.Adapter<UserOrderGoodsAdapter.UserOrderGoodHolder> { private Context mContext; private List<MallOrderGoodsVO> datas; public void setDatas(List<MallOrderGoodsVO> datas) { this.datas = datas; } public UserOrderGoodsAdapter(Context context) { this.mContext = context; } public UserOrderGoodsAdapter(Context context, List<MallOrderGoodsVO> datas) { this.mContext = context; this.datas = datas; } @NonNull @Override public UserOrderGoodsAdapter.UserOrderGoodHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) { View view = LayoutInflater.from(mContext).inflate(R.layout.item_user_order_good, parent, false); return new UserOrderGoodsAdapter.UserOrderGoodHolder(view); } @SuppressLint("SetTextI18n") @Override public void onBindViewHolder(@NonNull UserOrderGoodsAdapter.UserOrderGoodHolder holder, int position) { MallOrderGoodsVO goodsVO = datas.get(position); holder.goodsTitle.setText(goodsVO.getMallGoods().getGoodsTitle()); holder.goodsPrice.setText(goodsVO.getPrice() + ""); holder.goodsCount.setText(goodsVO.getCount() + ""); Picasso.with(mContext).load(goodsVO.getMallGoods().getGoodsImg()).into(holder.goodsImg); } @Override public int getItemCount() { return (datas == null) ? 0 : datas.size(); } public class UserOrderGoodHolder extends RecyclerView.ViewHolder { private ImageView goodsImg; private TextView goodsTitle; private TextView goodsPrice; private TextView goodsCount; public UserOrderGoodHolder(@NonNull View view) { super(view); goodsImg = view.findViewById(R.id.iv_goods_img); goodsTitle = view.findViewById(R.id.tv_goods_title); goodsPrice = view.findViewById(R.id.tv_goods_price); goodsCount = view.findViewById(R.id.tv_goods_count); view.setOnClickListener(v -> { mOnItemClickListener.onItemClick(v, getLayoutPosition()); }); //长按事件 view.setOnLongClickListener(v -> { mOnItemClickListener.onItemLongClick(v, getLayoutPosition()); return true; }); } } private UserOrderGoodsAdapter.OnItemClickListener mOnItemClickListener; public void setOnItemClickListener(UserOrderGoodsAdapter.OnItemClickListener onItemClickListener) { mOnItemClickListener = onItemClickListener; } /** * 点击响应事件 */ public interface OnItemClickListener { /** * 当RecyclerView某个被点击的时候回调 * * @param view 点击item的视图 * @param position 点击得到的数据 */ void onItemClick(View view, int position); void onItemLongClick(View view, int position); } }
/** * @file main.c * @brief This is the main source file for the flash read/write example. * @details * This includes flash memory operations to store * small amounts of infrequently-changing user * information. (ie settings, etc) * * Integrated flash has limited write cycles (10K as * per datasheet) and will thus wear out quickly * if not used carefully * * Authors: Tal G and based on recallmenot * (on Github)'s example code that was removed * from the main ch32v003fun examples repository. * * Reference here: * https://github.com/recallmenot/ch32v003fun/tree/8203b1dcddd8271ef04e3959b6375809b9b2df95/examples/flash_storage_main * */ #include <stdint.h> // Include the ch32v003fun header file for CH32V003 hardware #include "../ch32v003fun/ch32v003fun/ch32v003fun.h" #include <stdio.h> #include "ch32v003_flash.h" // Define this constant to use compile-time // flash addresses in the below example code. #define USE_COMPILE_TIME_ADDRESSES 1 #ifdef USE_COMPILE_TIME_ADDRESSES // Compile-time determined address for flash memory #define NONVOLATILE_START_ADDR FLASH_PRECALCULATE_NONVOLATILE_ADDR(0) #define NONVLOATILE_VAR_ADDR FLASH_PRECALCULATE_NONVOLATILE_ADDR(10) #else // Runtime determined address for flash memory uint32_t nonvolatile_var_addr; uint32_t nonvolatile_start_addr; #endif uint16_t valueInFlash; /** * @brief The main function. * @details Initializes hardware, performs flash memory operations, and blinks an LED on each loop. * @return 0 upon successful execution. */ int main() { SystemInit(); // Initialize the system hardware. printf("Starting..\r\n"); Delay_Ms(3000); // Delay for 3000 milliseconds (3 seconds). printf("Non-volatile storage testing\r\n"); // Enable GPIOs for LED blinking on pin C4 RCC->APB2PCENR |= RCC_APB2Periph_GPIOC; // Configure GPIO C4 as Push-Pull with a speed of 50MHz GPIOC->CFGLR &= ~(0xf<<(4*0)); GPIOC->CFGLR |= (GPIO_Speed_50MHz | GPIO_CNF_OUT_PP)<<(4*0); // Set the flash latency for proper operation. flash_set_latency(); printf("FLASH_LENGTH_OVERRIDE is %u\r\n", (uint16_t)(uintptr_t)FLASH_LENGTH_OVERRIDE); #ifdef USE_COMPILE_TIME_ADDRESSES printf("non-volatile start address is %lu\r\n", NONVOLATILE_START_ADDR); printf("non-volatile var address is %lu\r\n", NONVLOATILE_VAR_ADDR); #else nonvolatile_start_addr = flash_calcualte_nonvolatile_addr(0); // Calculate the start address for non-volatile data at runtime. nonvolatile_var_addr = flash_calcualte_nonvolatile_addr(10); // Calculate the variable address for non-volatile data at runtime. printf("non-volatile start address is %lu\r\n", nonvolatile_start_addr); printf("non-volatile var address is %lu\r\n", nonvolatile_var_addr); #endif int writeCount = 0; while(1) { GPIOC->BSHR = (1<<(16+0)); // Set pin C4 low (LED on). #ifdef USE_COMPILE_TIME_ADDRESSES valueInFlash = flash_read_16_bits(NONVLOATILE_VAR_ADDR); // Read a 16-bit value from flash memory at the predefined address. #else valueInFlash = flash_read_16_bits(nonvolatile_var_addr); // Read a 16-bit value from flash memory at the runtime determined address. #endif printf(" Saved value is %u\r\n", valueInFlash); Delay_Ms(250); // Delay for 250 milliseconds. GPIOC->BSHR = (1<<0); // Set pin C4 high (LED off). Delay_Ms(250); // Delay for 250 milliseconds. // Prevent more than 5 writes per power-on, as writing to flash is a limited resource. if(writeCount >= 5) { printf("Done writing. Wait...\r\n"); Delay_Ms(1000); // Delay for 1000 milliseconds (1 second). continue; } writeCount++; // Decrease the value to be written to flash by 1 valueInFlash--; // Unlock writing to flash memory flash_unlock(); printf("Memory unlocked\r\n"); // This erases a 64-byte page in the flash memory. // Note: smaller erases are not possible on the CH32V003. #ifdef USE_COMPILE_TIME_ADDRESSES flash_erase_page(NONVOLATILE_START_ADDR); // Erase a 64-bit block of flash memory at the predefined start address. #else flash_erase_page(nonvolatile_start_addr); // Erase a 64-bit block of flash memory at the runtime determined start address. #endif printf("Memory erased\r\n"); #ifdef USE_COMPILE_TIME_ADDRESSES flash_program_16(NONVLOATILE_VAR_ADDR, valueInFlash); // Write a 16-bit value to flash memory at the predefined address. #else flash_program_16(nonvolatile_var_addr, valueInFlash); // Write a 16-bit value to flash memory at the runtime determined address. #endif printf("Memory written\r\n"); // Lock flash memory flash_lock(); printf("Memory locked. \r\nWaiting...\r\n"); Delay_Ms(15000); // Delay for 15000 milliseconds (~15 seconds). } }
import XCTest @testable import NativeKit final class NativeKitTests: XCTestCase { func testRedRGBA() throws { let red: NativeColor = .red let (r, g, b, a) = red.rgba XCTAssertEqual(r, 1) XCTAssertEqual(g, 0) XCTAssertEqual(b, 0) XCTAssertEqual(a, 1) let (rd, gd, bd, ad) = red.rgbaData XCTAssertEqual(rd, 255) XCTAssertEqual(gd, 0) XCTAssertEqual(bd, 0) XCTAssertEqual(ad, 255) } func testGrayRGBA() throws { let gray: NativeColor = .init(red: 0.5, green: 0.5, blue: 0.5, alpha: 0.5) let (r, g, b, a) = gray.rgba XCTAssertEqual(r, 0.5) XCTAssertEqual(g, 0.5) XCTAssertEqual(b, 0.5) XCTAssertEqual(a, 0.5) let (rd, gd, bd, ad) = gray.rgbaData XCTAssertEqual(rd, 127) XCTAssertEqual(gd, 127) XCTAssertEqual(bd, 127) XCTAssertEqual(ad, 127) } func testRedHSBA() throws { let red: NativeColor = .red let (h, s, b, a) = red.hsba XCTAssertEqual(h, 0) XCTAssertEqual(s, 1) XCTAssertEqual(b, 1) XCTAssertEqual(a, 1) } func testBlueishHSBA() throws { let ch: NativeColor = .init(hue: 0.2, saturation: 0.3, brightness: 0.4, alpha: 0.5) XCTAssertEqual(ch.hsba.hue, 0.2, accuracy: 0.01) XCTAssertEqual(ch.hsba.saturation, 0.3, accuracy: 0.01) XCTAssertEqual(ch.hsba.brightness, 0.4, accuracy: 0.01) XCTAssertEqual(ch.hsba.alpha, 0.5, accuracy: 0.01) let cr: NativeColor = .init(red: ch.rgba.red, green: ch.rgba.green, blue: ch.rgba.blue, alpha: ch.rgba.alpha) XCTAssertEqual(cr.hsba.hue, 0.2, accuracy: 0.01) XCTAssertEqual(cr.hsba.saturation, 0.3, accuracy: 0.01) XCTAssertEqual(cr.hsba.brightness, 0.4, accuracy: 0.01) XCTAssertEqual(cr.hsba.alpha, 0.5, accuracy: 0.01) } func testGrayHSBA() throws { let gray: NativeColor = .init(red: 0.5, green: 0.5, blue: 0.5, alpha: 0.5) let (h, s, b, a) = gray.hsba XCTAssertEqual(h, 0) XCTAssertEqual(s, 0) XCTAssertEqual(b, 0.5) XCTAssertEqual(a, 0.5) } }
# %% Libraries import os os.environ['TF_CPP_MIN_LOG_LEVEL'] = '3' import mlflow import tensorflow as tf from tensorflow import keras from tensorflow.keras import layers, mixed_precision import numpy as np from sklearn.metrics import confusion_matrix import random from sklearn.model_selection import train_test_split from PIL import Image import dask.array as da from dask.delayed import delayed import matplotlib.pyplot as plt import matplotlib matplotlib.use('Agg') import seaborn as sns from model.schedulers.warmupcosine import WarmUpCosine from model.architecture import build_model_pretrained, build_model_scratch from model.layers.CutMix import cut_mix import config as cg # %% Let's use mixed precision to reduce memory consumption. mixed_precision.set_global_policy('mixed_float16') # %% Functions def mlflow_connection() -> str: """ Establishes a connection with MLflow for experiment tracking and logging. This function sets the tracking server URI to http://127.0.0.1:8080 for logging. It creates a new MLflow experiment named "Music Classifier" and enables system metrics logging. Note: - Make sure MLflow is installed and running on the specified URI before calling this function. - Ensure that the tracking server URI is correctly configured for your MLflow setup. Returns: str: The name of the run. """ # Set the tracking server URI for logging mlflow.set_tracking_uri(uri = "http://127.0.0.1:8080") # Create a new MLflow Experiment mlflow.set_experiment("Music Classifier") # Enable system metrics logging mlflow.enable_system_metrics_logging() # Autolog for tensorflow mlflow.tensorflow.autolog(log_datasets = False) def seed_init(seed: int) -> None: """ Initialize random seeds for NumPy, TensorFlow, and Python's random module. This function ensures reproducibility of results by setting the same seed value for all random number generators used in the program. Args: seed (int): The seed value to use for random initialization. Returns: None """ np.random.seed(seed) tf.random.set_seed(seed) random.seed(seed) def load_image(file_path: str) -> np.ndarray or None: """ Load an image from a file path and resize it to the input shape. Args: file_path (str): The path to the image file. Returns: numpy array: The loaded image as a numpy array, or None if there's an error. """ try: # Open the image file and convert the image to grayscale mode # Convert the image to a numpy array return np.array(Image.open(file_path).convert('L'), dtype = np.uint8) except OSError: # Print an error message if there's an issue loading the image print(f"Error loading image: {file_path}") return None def load_data_from_folder(path: str, input_shape: tuple) -> tuple: """ Load image data from a folder structure where each subfolder represents a class. Args: path (str): The path to the root folder containing the class subfolders. input_shape (tuple): The target size for the loaded images. Defaults to (224, 224). Returns: tuple: A tuple containing the loaded data and labels as numpy arrays. """ data = [] labels = [] for i, class_name in enumerate(os.listdir(path)): # Construct the full path to the class folder class_folder = os.path.join(path, class_name) # Get a list of file paths for the images in the class folder file_paths = [os.path.join(class_folder, file_name) for file_name in os.listdir(class_folder) if file_name.endswith('.png')] # Load the images in parallel using dask img_arrays = [delayed(load_image)(file_path) for file_path in file_paths] img_arrays = da.compute(*img_arrays) # Filter out any images that failed to load img_arrays = [img_array for img_array in img_arrays if img_array is not None] # Add the loaded images and labels to the data and labels lists data.extend(img_arrays) labels.extend([cg.DICT_LABELS[class_name]] * len(img_arrays)) # Convert the data and labels lists to numpy arrays and return them return np.expand_dims(np.array(data, dtype = np.uint8), -1), np.array(labels, dtype = np.float32) def create_confusion_matrix(y_true: np.ndarray, y_pred: np.ndarray, run_name: str) -> None: """ Create a confusion matrix from true labels and predicted labels. Args: y_true (np.ndarray): True labels. y_pred (np.ndarray): Predicted labels. Returns: np.ndarray: Confusion matrix. """ # Calculate the confusion matrix conf_mat = confusion_matrix(y_true, y_pred) # Display the confusion matrix plt.figure(figsize = (10, 7)) sns.heatmap(conf_mat, annot = True, fmt = 'd', cmap = 'Reds') plt.xlabel('Predict', fontsize = 15, weight = 'bold') plt.ylabel('True', fontsize = 15, weight = 'bold') plt.savefig(f'model/trained_model/confusion_matrix_{run_name}.png') def train_model(model: keras.Model, train_dataset: tuple, val_dataset: tuple, epochs: int) -> tf.keras.callbacks.History: """ Train the model on the training dataset. Args: model (keras.Model): The model to be trained. train_dataset (tf.data.Dataset): The training dataset. val_dataset (tf.data.Dataset): The validation dataset. epochs (int): The number of epochs to train the model. Defaults to EPOCHS. Returns: tf.keras.callbacks.History: The training history. """ with mlflow.start_run() as run: history = model.fit(x = train_dataset[0], y = train_dataset[1], epochs = epochs, batch_size = cg.BATCH_SIZE, validation_data = val_dataset) return history, run def evaluate_model(model: keras.Model, val_data: np.ndarray, val_labels: np.ndarray, run_name: str) -> None: """ Evaluate the model on the validation dataset. Args: model (keras.Model): The model to be evaluated. val_dataset (tf.data.Dataset): The validation dataset. Returns: float: The accuracy of the model on the validation dataset. """ # Evaluate the model using the confusion matrix y_pred = model.predict(val_data) y_pred_class = np.argmax(y_pred, axis = 1) y_true_class = np.argmax(val_labels, axis = 1) conf_mat = create_confusion_matrix(y_true_class, y_pred_class, run_name) def main(dataset_path: str, model_save_path: str, labels_dict_path: str) -> None: """ Main function to execute the image classification pipeline. Args: dataset_path (str): The path to the folder containing the image data. Returns: None """ # MLflow connection mlflow_connection() # Initialize the seeds for reproducible results seed_init(seed = cg.SEED) # Load data from the specified folder data, labels = load_data_from_folder(dataset_path, cg.INPUT_SHAPE) classes = np.unique(labels) num_classes = len(classes) # Print information about the data print(f"Data shape: {data.shape}") print(f"Label shape: {labels.shape}") print(f"Num classes: {num_classes}") print(f"Min val: {np.min(data)}") print(f"Max val: {np.max(data)}") # Check if the number of images is equal to the number of labels assert len(data) == len(labels), "Number of images is not equal to the number of labels" # One-hot encode the labels labels_onehot = tf.keras.utils.to_categorical(labels, num_classes = num_classes) # Split the data into training and validation sets train_data, val_data, train_labels, val_labels = train_test_split(data, labels_onehot, test_size = cg.test_size_split, random_state = cg.SEED, stratify = labels) print("Split data, training and validation, done.") del data, labels, labels_onehot # Split training data in two datasets to use CutMix train_data_1, train_data_2, train_labels_1, train_labels_2 = train_test_split(train_data, train_labels, test_size = 0.5, random_state = cg.SEED) print("Split data, 2 training, done.") # Apply CutMix train_data_cutmix_data, train_data_cutmix_labels = cut_mix((train_data_1, train_labels_1), (train_data_2, train_labels_2), alpha = 1, beta = 1) del train_data_1, train_data_2, train_labels_1, train_labels_2 # Combine the datasets combined_train_data = np.concatenate((train_data, train_data_cutmix_data), axis = 0) combined_train_labels = np.concatenate((train_labels, train_data_cutmix_labels), axis = 0) del train_data, train_labels, train_data_cutmix_data, train_data_cutmix_labels # Print information about the data print(f"Data shape: {combined_train_data.shape}") print(f"Label shape: {combined_train_labels.shape}") print(f"Num classes: {num_classes}") # Total steps for the scheduler total_steps = int((len(combined_train_data) / cg.BATCH_SIZE) * cg.EPOCHS) warmup_steps = int(total_steps * cg.warmup_p) scheduled_lrs = WarmUpCosine(lr_start = cg.lr_start, lr_max = cg.lr_max, warmup_steps = warmup_steps, total_steps = total_steps) # Build the classification model #model = build_model_pretrained(INPUT_SHAPE, num_classes) model = build_model_scratch(cg.INPUT_SHAPE, num_classes) # Compile the model with the AdamW optimizer and categorical cross-entropy loss model.compile(optimizer = tf.keras.optimizers.AdamW(learning_rate = scheduled_lrs, weight_decay = cg.weight_decay), loss = tf.keras.losses.CategoricalCrossentropy(), metrics = ['accuracy']) print(model.summary()) # Train the model history, run = train_model(model, (combined_train_data, combined_train_labels), (val_data, val_labels), epochs = cg.EPOCHS) # Save model model.save_weights(model_save_path) # Get the ID of the current run run_info = mlflow.get_run(run.info.run_id) run_name = run_info.data.tags['mlflow.runName'] # Show confusion matrix for model evaluation evaluate_model(model, val_data, val_labels, run_name) # %% Main if __name__ == '__main__': dataset_path = 'dataset' model_save_path = 'model/trained_model/music_classifier' labels_dict_path = 'model/labels_dict.pkl' main(dataset_path, model_save_path, labels_dict_path)
<nz-card [nzBordered]="false"> <form [nzLayout]="'inline'" nz-form [formGroup]="form" (ngSubmit)="submitForm($event, form.value)"> <div nz-row> <div nz-col nzXs="8" nzSm="8" nzMd="8"> <button nz-button type="reset" [nzSize]="'large'" [nzType]="'primary'" (click)="resetForm()"> <span>刷新列表</span> </button> </div> <div nz-col nzXs="16" nzSm="16" nzMd="16" class="mb-md"> <div nz-form-item class="d-flex"> <div nz-form-label> <label for="keyword">文章标题</label> </div> <div nz-form-control class="flex-1"> <nz-input nzType="text" formControlName="search" nzId="keyword" [nzSize]="'large'" [nzPlaceHolder]="'请输入'"></nz-input> </div> <button nz-button style="margin-left:20px" type="submit" [nzSize]="'large'" [nzType]="'primary'" [nzLoading]="loading"> <span>查询</span> </button> </div> </div> </div> </form> <div class="mb-md"> <nz-alert [nzType]="'info'"> <span alert-body> 共 <strong class="text-primary">{{ count }}</strong> 篇文章 </span> </nz-alert> </div> <nz-table #nzTable nzShowSizeChanger nzShowQuickJumper [nzLoading]="loading" [nzAjaxData]="articlesList" [nzTotal]="count" [(nzPageSize)]="pageSize" (nzPageSizeChange)="changePage()" [(nzPageIndex)]="page" (nzPageIndexChange)="changePage()"> <thead nz-thead> <tr> <th nz-th> 文章ID </th> <th nz-th> 文章标题 </th> <th nz-td> <span>文章阅读数</span> </th> <th nz-td> <span>文内商品浏览量</span> </th> <th nz-td> <span>文内商品访客量</span> </th> <th nz-td> <span>文内商品总订单量</span> </th> <th nz-td> <span>文内商品总成交额</span> </th> <th nz-th> 楼层 </th> <th nz-th> 上线时间 </th> <th nz-th> 操作 </th> </tr> </thead> <tbody nz-tbody> <tr nz-tbody-tr *ngFor="let item of nzTable.data; let index = index"> <td nz-td [innerText]="item.article_id"></td> <td nz-td> <ellipsis lines="1" style="max-width: 200px"> <span [title]="item.title" [innerText]="item.title"></span> </ellipsis> </td> <td nz-td> <span>{{item.read_num}}</span> </td> <td nz-td> <span>{{item.pv}}</span> </td> <td nz-td> <span>{{item.uv}}</span> </td> <td nz-td ><span>{{item.order_num}}</span> </td> <td nz-td ><span>¥{{item.gmv}}</span> </td> <td nz-td [innerText]="item.idx"></td> <td nz-td [innerText]="item.public_date"></td> <td nz-td> <a href="javascript:;" (click)="getArticleGoodsHref(item)">查看商品</a> </td> </tr> </tbody> </nz-table> </nz-card>
import React from 'react' import { render } from 'react-dom' import Highcharts from 'highcharts' import HighchartsReact from 'highcharts-react-official' import getChartTheme from './chartTheme' import primitives from '@primer/primitives' const chartTheme = getChartTheme() const colors = primitives.colors.light const options = { ...chartTheme, chart: { type: 'spline', spacing: 4, }, labels: { align: 'left', }, legend: { enabled: false, }, yAxis: { title: { text: 'Issues', }, }, title: { text: undefined, align: 'left', style: { fontWeight: 'bold' }, useHTML: true, }, plotOptions: { series: { pointStart: 2012, }, spline: { marker: { enabled: false, }, }, }, series: [ { data: [1, 2, 1, 4, 3, 6, 5, 3, 2, 12], lineWidth: 1.5, // color: colors.scale.blue[5], }, ], } // Possible Line Styles // 'Solid', // 'ShortDash', // 'ShortDot', // 'ShortDashDot', // 'ShortDashDotDot', // 'Dot', // 'Dash', // 'LongDash', // 'DashDot', // 'LongDashDot', // 'LongDashDotDot' const LineChartSingle = () => ( <div> <HighchartsReact highcharts={Highcharts} options={options} /> </div> ) export default LineChartSingle
package main import ( "fmt" "github.com/MdSadiqMd/TaskFlow/db" "github.com/MdSadiqMd/TaskFlow/routes" "github.com/gofiber/fiber/v2" /* "github.com/gofiber/fiber/v2/middleware/cors" */ "github.com/joho/godotenv" "log" "os" ) func main() { fmt.Println("Hello World") /* var name string = "Md" const name1 string = "sadiq" name2 := "Mohammad" fmt.Println(name, name1, name2) */ /* var x int = 5 var p *int = &x fmt.Println(p) fmt.Println(*p) */ if _, exists := os.LookupEnv("RAILWAY_ENVIRONMENT"); exists == false { if os.Getenv("ENV") != "production" { err := godotenv.Load(".env") if err != nil { log.Fatal("Error Loading .env file", err) } } } PORT := os.Getenv("PORT") if PORT == "" { PORT = ":3000" } else { PORT = ":" + PORT } app := fiber.New() /* app.Use(cors.New(cors.Config{ AllowOrigins: "http://localhost:5173", AllowHeaders: "Origin,Content-Type,Accept", })) */ app.Get("/", func(c *fiber.Ctx) error { return c.Status(200).JSON(fiber.Map{"msg": "hello world"}) }) err := db.ConnectDB() if err != nil { log.Fatal("Failed to connect to MongoDB") } app.Get("/api/todos", routes.GetTodos) app.Post("/api/todos", routes.CreateTodo) app.Patch("/api/todos/:id", routes.UpdateTodo) app.Delete("/api/todos/:id", routes.DeleteTodo) if os.Getenv("ENV") == "production" { app.Static("/", "./client/dist") } log.Fatal(app.Listen("0.0.0.0" + PORT)) }
import unittest import dgenerate.mediainput as _mi class TestImageSeedParser(unittest.TestCase): def test_file_not_found(self): with self.assertRaises(_mi.ImageSeedFileNotFoundError) as e: _mi.parse_image_seed_uri('not_found') self.assertIn('not_found', str(e.exception)) with self.assertRaises(_mi.ImageSeedFileNotFoundError) as e: _mi.parse_image_seed_uri('examples/media/earth.jpg;not_found') self.assertIn('not_found', str(e.exception)) with self.assertRaises(_mi.ImageSeedFileNotFoundError) as e: _mi.parse_image_seed_uri('examples/media/earth.jpg;mask=not_found') self.assertIn('not_found', str(e.exception)) with self.assertRaises(_mi.ImageSeedFileNotFoundError) as e: _mi.parse_image_seed_uri('examples/media/earth.jpg;control=not_found') self.assertIn('not_found', str(e.exception)) with self.assertRaises(_mi.ImageSeedFileNotFoundError) as e: _mi.parse_image_seed_uri('examples/media/earth.jpg;floyd=not_found') self.assertIn('not_found', str(e.exception)) def test_legacy_arguments(self): with self.assertRaises(_mi.ImageSeedArgumentError): # not aligned by 8 _mi.parse_image_seed_uri('examples/media/earth.jpg;14') # fine d = _mi.parse_image_seed_uri('examples/media/earth.jpg;14', align=2).resize_resolution self.assertEqual(d, (14, 14)) with self.assertRaises(_mi.ImageSeedArgumentError): # defined the resolution multiple times _mi.parse_image_seed_uri('examples/media/earth.jpg;512x512;512x512') parsed = _mi.parse_image_seed_uri( 'examples/media/dog-on-bench.png') self.assertEqual(parsed.seed_path, 'examples/media/dog-on-bench.png') self.assertIsNone(parsed.mask_path) self.assertIsNone(parsed.resize_resolution) parsed = _mi.parse_image_seed_uri( 'examples/media/dog-on-bench.png;examples/media/dog-on-bench-mask.png') self.assertEqual(parsed.seed_path, 'examples/media/dog-on-bench.png') self.assertEqual(parsed.mask_path, 'examples/media/dog-on-bench-mask.png') self.assertIsNone(parsed.resize_resolution) parsed = _mi.parse_image_seed_uri( 'examples/media/dog-on-bench.png;512x512;examples/media/dog-on-bench-mask.png') self.assertEqual(parsed.resize_resolution, (512, 512)) self.assertEqual(parsed.seed_path, 'examples/media/dog-on-bench.png') self.assertEqual(parsed.mask_path, 'examples/media/dog-on-bench-mask.png') parsed = _mi.parse_image_seed_uri('examples/media/dog-on-bench.png;examples/media/dog-on-bench-mask.png;1024') self.assertEqual(parsed.resize_resolution, (1024, 1024)) self.assertEqual(parsed.seed_path, 'examples/media/dog-on-bench.png') self.assertEqual(parsed.mask_path, 'examples/media/dog-on-bench-mask.png') def test_uri_arguments(self): with self.assertRaises(_mi.ImageSeedArgumentError): _mi.parse_image_seed_uri('examples/media/earth.jpg;resize=garbage') with self.assertRaises(_mi.ImageSeedArgumentError): _mi.parse_image_seed_uri('examples/media/earth.jpg;aspect=garbage') with self.assertRaises(_mi.ImageSeedArgumentError): _mi.parse_image_seed_uri('examples/media/earth.jpg;frame-start=garbage') with self.assertRaises(_mi.ImageSeedArgumentError): _mi.parse_image_seed_uri('examples/media/earth.jpg;frame-end=garbage') with self.assertRaises(_mi.ImageSeedArgumentError): # mutually exclusive arguments _mi.parse_image_seed_uri( 'examples/media/earth.jpg;floyd=examples/media/earth.jpg;control=examples/media/earth.jpg') parsed = _mi.parse_image_seed_uri( 'examples/media/earth.jpg;mask=examples/media/horse1.jpg;' 'control=examples/media/horse2.jpeg;resize=512;aspect=false;frame-start=5;frame-end=10') self.assertEqual(parsed.seed_path, 'examples/media/earth.jpg') self.assertEqual(parsed.mask_path, 'examples/media/horse1.jpg') self.assertEqual(parsed.control_path, 'examples/media/horse2.jpeg') self.assertEqual(parsed.resize_resolution, (512, 512)) self.assertFalse(parsed.aspect_correct) self.assertEqual(parsed.frame_start, 5) self.assertEqual(parsed.frame_end, 10) parsed = _mi.parse_image_seed_uri( 'examples/media/earth.jpg;mask=examples/media/horse1.jpg;' 'control=examples/media/horse2.jpeg, "examples/media/beach.jpg";' 'resize=1024x512;aspect=false;frame-start=5;frame-end=10') self.assertEqual(parsed.seed_path, 'examples/media/earth.jpg') self.assertEqual(parsed.mask_path, 'examples/media/horse1.jpg') self.assertSequenceEqual(parsed.control_path, ['examples/media/horse2.jpeg', 'examples/media/beach.jpg']) self.assertEqual(parsed.resize_resolution, (1024, 512)) self.assertFalse(parsed.aspect_correct) self.assertEqual(parsed.frame_start, 5) self.assertEqual(parsed.frame_end, 10) parsed = _mi.parse_image_seed_uri( 'examples/media/earth.jpg;mask=examples/media/horse1.jpg;' 'floyd=examples/media/horse2.jpeg;resize=512;aspect=false;frame-start=5;frame-end=10') self.assertEqual(parsed.seed_path, 'examples/media/earth.jpg') self.assertEqual(parsed.mask_path, 'examples/media/horse1.jpg') self.assertEqual(parsed.floyd_path, 'examples/media/horse2.jpeg') self.assertEqual(parsed.resize_resolution, (512, 512)) self.assertFalse(parsed.aspect_correct) self.assertEqual(parsed.frame_start, 5) self.assertEqual(parsed.frame_end, 10) parsed = _mi.parse_image_seed_uri( 'examples/media/earth.jpg;mask=examples/media/horse1.jpg;' 'floyd=examples/media/horse2.jpeg;resize=1024x512;aspect=false;frame-start=5;frame-end=10') self.assertEqual(parsed.seed_path, 'examples/media/earth.jpg') self.assertEqual(parsed.mask_path, 'examples/media/horse1.jpg') self.assertEqual(parsed.floyd_path, 'examples/media/horse2.jpeg') self.assertEqual(parsed.resize_resolution, (1024, 512)) self.assertFalse(parsed.aspect_correct) self.assertEqual(parsed.frame_start, 5) self.assertEqual(parsed.frame_end, 10) with self.assertRaises(_mi.ImageSeedArgumentError): # not aligned by 8, the default requirement _mi.parse_image_seed_uri('examples/media/earth.jpg;resize=14') with self.assertRaises(_mi.ImageSeedArgumentError): # not aligned by 8, the default requirement _mi.parse_image_seed_uri('examples/media/earth.jpg;resize=3') # fine d = _mi.parse_image_seed_uri('examples/media/earth.jpg;resize=14', align=1).resize_resolution self.assertEqual(d, (14, 14)) # fine d = _mi.parse_image_seed_uri('examples/media/earth.jpg;resize=14', align=2).resize_resolution self.assertEqual(d, (14, 14)) # fine d = _mi.parse_image_seed_uri('examples/media/earth.jpg;resize=3', align=1).resize_resolution self.assertEqual(d, (3, 3)) # fine d = _mi.parse_image_seed_uri('examples/media/earth.jpg;resize=3', align=3).resize_resolution self.assertEqual(d, (3, 3)) def test_uri_syntax_errors(self): with self.assertRaises(_mi.ImageSeedParseError): # stray colon _mi.parse_image_seed_uri('examples/media/earth.jpg;') with self.assertRaises(_mi.ImageSeedParseError): # stray colon _mi.parse_image_seed_uri('examples/media/earth.jpg;examples/media/earth.jpg;') with self.assertRaises(_mi.ImageSeedParseError): # stray colon _mi.parse_image_seed_uri('examples/media/earth.jpg;;examples/media/earth.jpg') with self.assertRaises(_mi.ImageSeedParseError): # unterminated string _mi.parse_image_seed_uri('"examples/media/earth.jpg;') with self.assertRaises(_mi.ImageSeedParseError): # unterminated string _mi.parse_image_seed_uri('examples/media/earth.jpg"') with self.assertRaises(_mi.ImageSeedParseError): # unterminated string _mi.parse_image_seed_uri("'examples/media/earth.jpg;") with self.assertRaises(_mi.ImageSeedParseError): # unterminated string _mi.parse_image_seed_uri("examples/media/earth.jpg'") with self.assertRaises(_mi.ImageSeedParseError): _mi.parse_image_seed_uri("examples/media/earth.jpg;control=") with self.assertRaises(_mi.ImageSeedParseError): _mi.parse_image_seed_uri("examples/media/earth.jpg;control= ") with self.assertRaises(_mi.ImageSeedParseError): _mi.parse_image_seed_uri("examples/media/earth.jpg;control=examples/media/earth.jpg,") with self.assertRaises(_mi.ImageSeedParseError): _mi.parse_image_seed_uri("examples/media/earth.jpg;control=,examples/media/earth.jpg") with self.assertRaises(_mi.ImageSeedParseError): _mi.parse_image_seed_uri("examples/media/earth.jpg;control=examples/media/earth.jpg,,examples/media/earth.jpg") with self.assertRaises(_mi.ImageSeedParseError): _mi.parse_image_seed_uri("examples/media/earth.jpg;control=,") with self.assertRaises(_mi.ImageSeedParseError): _mi.parse_image_seed_uri("examples/media/earth.jpg;mask= ") with self.assertRaises(_mi.ImageSeedParseError): _mi.parse_image_seed_uri("examples/media/earth.jpg;mask=") with self.assertRaises(_mi.ImageSeedParseError): _mi.parse_image_seed_uri("examples/media/earth.jpg;floyd= ")
// // AccountService.swift // RoninEMS // // Created by Alvin Raygon on 2/12/22. // import Foundation //{ // "grant_type": "password", // "Email": "ls1001@yopmail.com", // "Password": "12345" //} struct LoginRequest: Codable { var grant_type: String = "password" let Email: String let Password: String } enum NetworkError: Error { case badURL case decodingError case noData } class AccountService { private init() { } static let shared = AccountService() func loginAccount(loginRequest: LoginRequest, completion: @escaping (Result<LoginResponse, NetworkError>) -> Void){ print("\(loginRequest)") guard let url = URL.authenticateUser() else { return completion(.failure(.badURL)) } var request = URLRequest(url: url) request.httpMethod = "POST" request.addValue("application/json", forHTTPHeaderField: "Content-Type") request.addValue(Config.appSecret, forHTTPHeaderField: "app-secret") request.httpBody = try? JSONEncoder().encode(loginRequest) URLSession.shared.dataTask(with: request) { data, response, error in guard let data = data, error == nil else { return completion(.failure(.noData)) } let loginResponse = try? JSONDecoder().decode(LoginResponse.self, from: data) if let loginResponse = loginResponse { print("\(loginResponse.access_token)") completion(.success(loginResponse)) }else{ completion(.failure(.decodingError)) } }.resume() } func getProfile(id: Int, token: String, completion: @escaping (Result<ProfileResponse, NetworkError>) -> Void){ guard let url = URL.getUsersProfile(id: id) else { return completion(.failure(.badURL)) } var request = URLRequest(url: url) request.httpMethod = "GET" request.addValue("application/json", forHTTPHeaderField: "Content-Type") request.addValue(Config.appSecret, forHTTPHeaderField: "app-secret") request.addValue("Bearer " + token, forHTTPHeaderField: "Authorization") URLSession.shared.dataTask(with: request) { data, response, error in guard let data = data, error == nil else { return completion(.failure(.noData)) } let decodedValue = try? JSONDecoder().decode(ProfileResponse.self, from: data) if let decodedValue = decodedValue { completion(.success(decodedValue)) }else{ print("\(String(describing: error?.localizedDescription))") completion(.failure(.decodingError)) } }.resume() } func getSubscriptionDetails(id: Int, token: String, completion: @escaping (Result<GetLicenseBaseResponse, NetworkError>) -> Void){ guard let url = URL.getSubscriptionDetails(id: id) else { return completion(.failure(.badURL)) } var request = URLRequest(url: url) request.httpMethod = "GET" request.addValue("application/json", forHTTPHeaderField: "Content-Type") request.addValue(Config.appSecret, forHTTPHeaderField: "app-secret") request.addValue("Bearer " + token, forHTTPHeaderField: "Authorization") URLSession.shared.dataTask(with: request) { data, response, error in guard let data = data, error == nil else { return completion(.failure(.noData)) } let decodedValue = try! JSONDecoder().decode(GetLicenseBaseResponse.self, from: data) if let decodedValue = decodedValue as? GetLicenseBaseResponse { completion(.success(decodedValue)) }else{ print("\(String(describing: error?.localizedDescription))") completion(.failure(.decodingError)) } }.resume() } }
// // // Create by imac on 29/4/2018 // Copyright © 2018. All rights reserved. import Foundation import UIKit // MARK: - ... UserAuth Controller class UserRoot: Codable { // MARK: - ... Keys UserDefaults public static var storeUserDefaults: String = "userDataDefaults" public static var storeRememberUser: String = "USER_LOGIN_REMEMBER" public static var storeTimeStamp: String = "LOGIN_TIMESTAMP" var data: User? var expire: Int? var refresh_token: String? var loginTimeStamp: Int? var token: String? } // MARK: - ... User Codable from API extension UserRoot { class User: Codable { let id: Int? let name, email, phone, gender: String? let birthdate, avatar: String? let active, confirmationCode, rating: Int? let userType: String? let age: String? let address: String? let points: String? let notRatedOrder: Int? let createdAt: String? enum CodingKeys: String, CodingKey { case id, name, email, phone, gender, birthdate, avatar, active case confirmationCode = "confirmation_code" case rating case userType = "user_type" case age, address case points case notRatedOrder case createdAt = "created_at" } } } // MARK: - ... Functions extension UserRoot { // MARK: - ... Function for convert data to model public static func convertToModel(response: Data?) -> UserRoot { do { let data = try JSONDecoder().decode(self, from: response ?? Data()) return data } catch { return UserRoot() } } // MARK: - ... Function for Save user data public static func save(response: Data?, remember: Bool = true) { let timestamp = NSDate().timeIntervalSince1970 let myTimeInterval = TimeInterval(timestamp).int UserDefaults.standard.set(response, forKey: storeUserDefaults) UserDefaults.standard.set(myTimeInterval, forKey: storeTimeStamp) if remember { UserDefaults.standard.set(true, forKey: storeRememberUser) } } // MARK: - ... Function for Save user data public func save() { guard let response = try? JSONEncoder().encode(self) else { return } UserDefaults.standard.set(response, forKey: UserRoot.storeUserDefaults) } // MARK: - ... Function for logout user public static func logout() { UserDefaults.standard.set(Data(), forKey: storeUserDefaults) } // MARK: - ... Function for logout user public func logout() { UserDefaults.standard.set(Data(), forKey: UserRoot.storeUserDefaults) } // MARK: - ... Function for fetch user data public static func fetch() -> UserRoot? { let data = UserDefaults.standard.data(forKey: storeUserDefaults) let user = self.convertToModel(response: data) return user } // MARK: - ... Function for fetch user data public static func fetchUser() -> User? { let data = UserDefaults.standard.data(forKey: storeUserDefaults) let user = self.convertToModel(response: data) return user.data } // MARK: - ... Function for fetch token public static func token() -> String? { let data = UserDefaults.standard.data(forKey: storeUserDefaults) let user = self.convertToModel(response: data) print("user.token",user.token) return user.token } public static func authroize(closure: HandlerView? = nil) { if token() == nil { let scene = UIApplication.topViewController() as? BaseController PopupConfirmationVC.confirmationPOPUP(view: scene, title: "You must be logged in first!".localized, btns: [.agree, .skip]) { closure?() return } onAgreeClosure: { Router.instance.unAuthorized() return } return } } }
import { Heading, IconLink, Button, Footer, Meta } from "../components"; export default function ReportDesign() { return ( <> <Meta title="State of Cobalt | Report Design" /> <main> {/* Start */} <article id="overview" class="cobalt"> <section class="hero"> <hgroup> <Heading level="1" href="overview"> State of Cobalt </Heading> <p>Report Design - Main Hero</p> <p> Overview |{" "} <a class="link primary" href="#automotive"> Automotive </a>{" "} |{" "} <a class="link primary" href="#consumer-tech"> Consumer Tech </a> </p> </hgroup> </section> <section> <p>Test/Example Buttons:</p> <p> <Button level="primary" text="Primary Button" onClick={() => alert("You clicked the primary button!")} />{" "} <Button level="secondary" text="Secondary Button" onClick={() => alert("You clicked the secondary button!")} /> </p> </section> </article> {/* Auto */} <article id="automotive" class="slate"> <section class="hero"> <hgroup> <Heading level="2" href="automotive"> State of Automotive </Heading> <p>Example Muted Hero, H2</p> <p> <a class="link primary" href="#overview"> Overview </a>{" "} | Automotive |{" "} <a class="link primary" href="#consumer-tech"> Consumer Tech </a> </p> </hgroup> </section> <section> <p>Test/Example Buttons:</p> <p> <Button level="primary" text="Primary Button" onClick={() => alert("You clicked the primary button!")} />{" "} <Button level="secondary" text="Secondary Button" onClick={() => alert("You clicked the secondary button!")} /> </p> </section> </article> {/* Tech */} <article id="consumer-tech" class="orange"> <section class="hero flashy"> <hgroup> <Heading level="2" href="consumer-tech"> State of Consumer Tech </Heading> <p>Example Flashy Hero, H2</p> <p> <a class="link primary" href="#overview"> Overview </a>{" "} |{" "} <a class="link primary" href="#automotive"> Automotive </a>{" "} | Consumer Tech </p> </hgroup> </section> <section> <hgroup> <Heading level="3">Background</Heading> <p>1.1 (H3)</p> </hgroup> <p> Lorem ipsum dolor sit amet, consectetur adipiscing elit. Integer rutrum orci sagittis tortor interdum pellentesque. Maecenas malesuada erat est, eget euismod ante dapibus ac. </p> <p> Aenean pharetra nisl risus, sed convallis dui rutrum nec. Phasellus vel odio at dolor malesuada dictum non vel erat. Nulla sollicitudin augue ante, vulputate pulvinar felis luctus at. Nulla id felis tincidunt, accumsan felis quis, aliquam ipsum. Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia curae; Nunc cursus turpis sit amet ante porta, eget pulvinar magna auctor. Maecenas ultrices felis enim, at dapibus justo porttitor sed. Aliquam pharetra at sapien at egestas. Sed quis nunc a sapien euismod tincidunt. Aenean vehicula gravida massa id dictum. Praesent id mi ullamcorper, imperdiet lacus nec, imperdiet quam. Nunc diam metus, facilisis sit amet dolor ut, lacinia hendrerit dui. </p> <p>This is an example table /w hard-coded data:</p> <div class="table-wrapper"> <table> <thead> <tr> <th>Company</th> <th>Employees</th> <th>Metric Tons of Cobalt</th> <th>Percent of Market Share</th> </tr> </thead> <tbody> <tr> <td>Company A</td> <td>50k</td> <td>25</td> <td>13%</td> </tr> <tr> <td>Company B</td> <td>45k</td> <td>32</td> <td>9%</td> </tr> <tr> <td>Company c</td> <td>10k</td> <td>5</td> <td>4.34%</td> </tr> <tr> <td>Company D</td> <td>2.5k</td> <td>10</td> <td>34.3%</td> </tr> </tbody> </table> </div> <p>Test/Example Buttons:</p> <p> <Button level="primary" text="Primary Button" onClick={() => alert("You clicked the primary button!")} />{" "} <Button level="secondary" text="Secondary Button" onClick={() => alert("You clicked the secondary button!")} /> </p> <p> <Button level="primary" text="Pimary Button w/ Icon" icon={<IconLink />} onClick={() => alert("You clicked the button with an icon!")} />{" "} <Button level="primary" icon={<IconLink />} />{" "} <Button level="secondary" icon={<IconLink />} aria-label="Go Somewhere" /> </p> <p> <Button text="Link as primary" level="primary" href="#overview" />{" "} <Button text="Link as secondary" level="secondary" href="#overview" /> </p> <hr /> <p>Test/Example Links:</p> <p> <a href="#">Unstyled Anchor</a> <button>Unstyled Button</button> </p> <p> <a href="#" class="link primary"> Primary Link </a>{" "} <button href="#" class="link primary"> Button as Primary Link </button> </p> <p> <a href="#" class="link secondary"> Secondary Link </a>{" "} <button href="#" class="link secondary"> Button as Secondary Link </button> </p> <hr /> <p> Quisque rhoncus, turpis quis semper ornare, metus nunc auctor tortor, et facilisis lorem nisl ac enim. Suspendisse potenti. Curabitur facilisis luctus laoreet. Etiam finibus tellus vitae tincidunt maximus. Phasellus tempor condimentum faucibus. Suspendisse eget quam nec est placerat bibendum a in risus. Donec interdum eu est sed euismod. Cras aliquam, justo ut molestie rutrum, ex nunc mollis lectus, sit amet tempus felis ipsum vitae justo. Donec sodales augue neque, non posuere leo condimentum eu. Nam aliquam mollis placerat. Etiam sagittis finibus tortor et blandit. Sed varius mi augue, quis lacinia ipsum imperdiet ut. In volutpat est quam, sit amet tempor lorem molestie sit amet. In a nulla et dui lobortis sagittis. Donec pulvinar laoreet sem. </p> </section> </article> </main> <Footer /> </> ); }
To setup Express server: 1.create one folder called basic-express-setup 2.Inside the folder please run the below command: cmd:npm init 3.npm init - will create base package.json file for you. 4.npm install express /* once express or any new package is install for first time it will create package-lock.json and node-modules folder will be created*/ /* please dont change anything inside the package-lock.json and node-modules. This file will be created automatically from network*/ 5.create one file called index.js inside our folder. 6.setup up npm start inside the package.json "scripts": { "start":"node index.js" }, 7. creating server const express = require('express'); const app = express(); app.listen(8080,()=>{ console.log("our application is listening on port 8080"); }); 8.creating get method api app.get('',(req,res)=>{ res.send("hello world"); }); 9.creating different route name for get method app.get('/about',(req,res)=>{ res.send("This is about page"); }); 10.send method helps to send the data in array or object or string or number or html you can send it.
import React, { useState } from "react"; import { FaBars, FaTimes, FaGithub, FaLinkedin } from "react-icons/fa"; import { HiOutlineMail } from "react-icons/hi"; import { Link } from "react-scroll"; import { BsFillPersonLinesFill } from "react-icons/bs"; import Logo from "../assets/logo.png"; const Navbar = () => { const [nav, setNav] = useState(false); const handleClick = () => setNav(!nav); return ( <div className="fixed w-full h-[80px] flex justify-between items-center px-4 bg-primary text-light-text z-20"> <div> <img src={Logo} alt="logo" style={{ width: "50px" }} /> </div> {/* Menu */} <ul className="hidden md:flex font-bold"> <Link className="block" activeClass="active" to="home" smooth={true} duration={500} > <li className="group flex flex-col items-center hover:text-yellow"> HOME <div className="bg-primary group-hover:bg-yellow flex w-[8px] h-[8px] rounded-[4px] duration-200 mt-1"></div> </li> </Link> <Link className="block" activeClass="active" to="skills" smooth={true} duration={500} > <li className="group flex flex-col items-center hover:text-green"> SKILLS <div className="bg-primary group-hover:bg-green flex w-[8px] h-[8px] rounded-[4px] duration-200 mt-1"></div> </li> </Link> <Link className="block" activeClass="active" to="work" smooth={true} duration={500} > <li className="group flex flex-col items-center hover:text-light-blue"> WORK <div className="bg-primary group-hover:bg-light-blue flex w-[8px] h-[8px] rounded-[4px] duration-200 mt-1"></div> </li> </Link> <Link className="block" activeClass="active" to="contact" smooth={true} duration={500} > <li className="group flex flex-col items-center hover:text-red"> CONTACT <div className="bg-primary group-hover:bg-red flex w-[8px] h-[8px] rounded-[4px] duration-200 mt-1"></div> </li> </Link> </ul> {/* Hamburger */} <div onClick={handleClick} className="md:hidden z-10 cursor-pointer"> {!nav ? <FaBars /> : <FaTimes />} </div> {/* Mobile Menu */} <ul className={ !nav ? "hidden" : "md:hidden absolute top-0 left-0 w-full h-screen bg-primary flex flex-col justify-center items-center text-light-text" } > <li className="py-6 text-4xl font-bold hover:text-yellow duration-200"> <Link onClick={handleClick} activeClass="active" to="home" smooth={true} duration={500} > HOME </Link> </li> <li className="py-6 text-4xl font-bold hover:text-green duration-200"> <Link onClick={handleClick} activeClass="active" to="skills" smooth={true} duration={500} > SKILLS </Link> </li> <li className="py-6 text-4xl font-bold hover:text-light-blue duration-200"> <Link onClick={handleClick} activeClass="active" to="work" smooth={true} duration={500} > WORK </Link> </li> <li className="py-6 text-4xl font-bold hover:text-red duration-200"> <Link onClick={handleClick} activeClass="active" to="contact" smooth={true} duration={500} > CONTACT </Link> </li> </ul> {/* Social Icons */} <div className="hidden lg:flex fixed flex-col top-[35%] left-0"> <ul> <a target="blank" className="block w-full text-secondary font-bold" href="https://github.com/FrankTimmons" > <li className="w-[160px] h-[60px] flex justify-between items-center ml-[-100px] hover:ml-[-10px] duration-300 bg-[#000]"> GITHUB <FaGithub size={30} /> </li> </a> <a target="blank" className="block w-full text-secondary font-bold" href="https://www.linkedin.com/in/frank-timmons-pdx/" > <li className="w-[160px] h-[60px] flex justify-between items-center ml-[-100px] hover:ml-[-10px] duration-300 bg-light-blue"> LINKEDIN <FaLinkedin size={30} /> </li> </a> <Link onClick={handleClick} activeClass="active" to="contact" smooth={true} duration={500} className="block w-full text-secondary font-bold" > <li className="w-[160px] h-[60px] flex justify-between items-center ml-[-100px] hover:ml-[-10px] duration-300 bg-red"> EMAIL <HiOutlineMail size={30} /> </li> </Link> <a target="blank" className="block w-full text-secondary font-bold" href="https://drive.google.com/file/d/17YfL78aNl57Vp0v-PhqZwwX1K7dqSIbm/view?usp=sharing" > <li className="w-[160px] h-[60px] flex justify-between items-center ml-[-100px] hover:ml-[-10px] duration-300 bg-green"> RESUME <BsFillPersonLinesFill size={30} /> </li> </a> </ul> </div> </div> ); }; export default Navbar;
;;; ../repos/walter-manger/.dotfiles/emacs/.doom.d/+gtd.el -*- lexical-binding: t; -*- (setq org-directory "~/Dropbox/Org/organizer/.agenda-files") (wm/add-file-keybinding "C-c z w" (concat (file-name-as-directory org-directory) "work.org") "work.org") (wm/add-file-keybinding "C-c z h" (concat (file-name-as-directory org-directory) "home.org") "home.org") (wm/add-file-keybinding "C-c z g" (concat (file-name-as-directory org-directory) "gtd/refile.org") "refile.org") (wm/add-file-keybinding "C-c z n" (concat (file-name-as-directory org-directory) "gtd/next.org") "next.org") (wm/add-file-keybinding "C-c z f" (concat (file-name-as-directory org-directory) "elfeed.org") "elfeed.org") ;;; Inspration ;;; https://github.com/kandread/doom-emacs-private/blob/master/%2Bgtd.el ;;; http://doc.norang.ca/org-mode.html (after! org (setq org-roam-directory "~/Dropbox/Org/organizer/roam") (setq org-agenda-files '( "~/Dropbox/Org/organizer/.agenda-files/gtd/refile.org" "~/Dropbox/Org/organizer/.agenda-files/gtd/next.org" "~/Dropbox/Org/organizer/.agenda-files/gtd/someday.org" "~/Dropbox/Org/organizer/.agenda-files/gtd/projects.org" "~/Dropbox/Org/organizer/.agenda-files/gtd/read.org" )) ;; Borrowing from -> https://github.com/nmartin84/.doom.d#capture-templates (setq org-capture-templates '(("i" "📥 Inbox") ("ih" "✅ Home Task" entry (file+headline "~/Dropbox/Org/organizer/.agenda-files/gtd/next.org" "Inbox") "* TODO %^{task} :@home:\n:PROPERTIES:\n :CREATED: %U\n :END:\n%?" :empty-lines 1 :kill-buffer t) ("iw" "✅ Work Task" entry (file+headline "~/Dropbox/Org/organizer/.agenda-files/gtd/next.org" "Inbox") "* TODO %^{task} :@work:\n:PROPERTIES:\n :CREATED: %U\n :END:\n%?" :empty-lines 1 :kill-buffer t) ("s" "ℹ️ Source" entry (file "~/Dropbox/Org/organizer/.agenda-files/gtd/refile.org") "* REFILE %^{description} %^g\n:PROPERTIES:\n:CREATED: %U\n:END:\n:METADATA:\n- SOURCE: %(org-cliplink-capture)\n- AUTHOR:\n:END:\n%?") ;; ("r" "📚 Read" entry (file+headline "~/Dropbox/Org/organizer/.agenda-files/books.org" "Inbox") ;; "* TODO %^{title} %^g\n:PROPERTIES:\n:CREATED: %U\n:author: %^{author}\n:url: %c\n:pages: \n:rating: \n:END:\n%?") ;;("j" " journal") ;;("gp" " projects") ;;("b" " bullet journal") ;;("l" " local project") ;;("n" " notes") ("r" "📎 resources") )) ;; TODO: Cleanup the template names to be more clear and easier to recognize. ;; (push '("ga" " append to headline" plain (function nm/org-capture-log) " *Note added:* [%<%Y-%m-%d %a %H:%M>]\n%?" :empty-lines-before 1 :empty-lines-after 1) org-capture-templates) ;;(push '("gc" " capture" entry (file "~/Dropbox/Org/organizer/.agenda-files/refile.org") "* REFILE %^{task}\n:PROPERTIES:\n:CREATED: %U\n:END:\n:METADATA:\n- SOURCE:\n- AUTHOR:\n:END:\n%?") org-capture-templates) ;; (push '("gk" " capture [kill-ring]" entry (file+olp "~/Dropbox/Org/organizer/.agenda-files/gtd.org" "Inbox") "* REFILE %^{task}\n:PROPERTIES:\n:CREATED: %U\n:END:\n%c") org-capture-templates) ;; (push '("gx" " capture [current pos]" entry (file+olp "~/Dropbox/Org/organizer/.agenda-files/gtd.org" "Inbox") "* REFILE %^{task}\n:PROPERTIES:\n:CREATED: %U\n:END:\nLocation at time of capture: %a") org-capture-templates) (push '("ir" "🗄 Refile" entry (file+headline "~/Dropbox/Org/organizer/.agenda-files/gtd/refile.org" "Inbox") "* REFILE %^{task} %^g\n:PROPERTIES:\n:CREATED: %U\n:END:\n%?") org-capture-templates) ;; (push '("ih" "✅ Home Task" entry (file+headline "~/Dropbox/Org/organizer/.agenda-files/gtd/next.org" "Inbox") ;; "* TODO %^{task} :@home:\n :PROPERTIES:\n :CREATED: %U\n :END:\n%?" :empty-lines 1) org-capture-templates) ;; (push '("iw" "✅ Work Task" entry (file+headline "~/Dropbox/Org/organizer/.agenda-files/gtd/next.org" "Inbox") ;; "* TODO %^{task} :@work:\n :PROPERTIES:\n :CREATED: %U\n :END:\n%?" :empty-lines 1) org-capture-templates) ;; TODO: Configure more resource capture templates. (push '("rb" "📚 Book" entry (file+headline "~/Dropbox/Org/organizer/.agenda-files/gtd/read.org" "Inbox") "* TODO %^{title} %^g\n:PROPERTIES:\n:CREATED: %U\n:author: %^{author}\n:url: %c\n:pages: \n:rating: \n:END:\n%?") org-capture-templates) (push '("ra" "📰 Article" entry (file+headline "~/Dropbox/Org/organizer/.agenda-files/gtd/read.org" "Inbox") "* TODO %^{title} %^g\n:PROPERTIES:\n:CREATED: %U\n:author: %^{author}\n:url: %c\n:END:\n%?") org-capture-templates) ;; (push '("rr" " research literature" entry (file+function "~/projects/orgmode/gtd/websources.org" nm/enter-headline-websources) "* READ %(get-page-title (current-kill 0))") org-capture-templates) ;; (push '("rf" " rss feed" entry (file+function "~/projects/orgmode/elfeed.org" nm/return-headline-in-file) "* %^{link}") org-capture-templates) ) ;; https://emacs.cafe/emacs/orgmode/gtd/2017/06/30/orgmode-gtd.html ;; https://orgmode.org/worg/org-tutorials/org-custom-agenda-commands.html ;; https://github.com/alphapapa/org-super-agenda#group-selectors ;; https://github.com/alphapapa/org-super-agenda/blob/master/examples.org#contributed-examples ;; https://github.com/bascht/dotfiles-public/blob/main/dot_doom.d/org.el (after! org-agenda :init (setq org-agenda-skip-scheduled-if-done t org-agenda-skip-deadline-if-done t org-agenda-include-deadlines t ;; org-agenda-block-separator nil org-agenda-compact-blocks t org-agenda-start-day nil ;; i.e. today org-agenda-span 1 org-agenda-start-on-weekday nil) (setq org-agenda-custom-commands '( ("c" "Super View" ( ( agenda "" ((org-agenda-overriding-header "TODAY"))) ;; (agenda "" ((org-agenda-overriding-header "") ;; (org-super-agenda-groups ;; '((:name "Today" ;; :time-grid t ;; :date today ;; :order 1))))) ( todo "REFILE" ((org-agenda-overriding-header "🗄️ To Refile"))) ( todo "TODO" ((org-agenda-overriding-header "🗄️ To DO NOW"))) ) ) ("w" "Work Super View" ( ( agenda "" ((org-agenda-overriding-header ""))) ( tags-todo "@work" ((org-agenda-overriding-header "🗄️ To Work"))) ) ) ) ) ;; (setq org-agenda-custom-commands ;; '(("c" "Super view" ;; ((agenda "" ((org-agenda-overriding-header "") ;; (org-super-agenda-groups ;; '((:name "Today" ;; :time-grid t ;; :date today ;; :order 1))))) ;; (alltodo "" ((org-agenda-overriding-header "") ;; (org-super-agenda-groups ;; '((:log t) ;; (:name "To refile" ;; :todo "REFILE") ;; ;;:file-path "~/Dropbox/Org/organizer/.agenda-files/gtd/refile.org") ;; (:name "Next to do" ;; :todo "NEXT" ;; :order 1) ;; (:name "Important" ;; :priority "A" ;; :order 6) ;; (:name "Today's tasks" ;; :file-path "journal/") ;; (:name "Due Today" ;; :deadline today ;; :order 2) ;; (:name "Scheduled Soon" ;; :scheduled future ;; :order 8) ;; (:name "Overdue" ;; :deadline past ;; :order 7) ;; (:name "Meetings" ;; :and (:todo "MEET" :scheduled future) ;; :order 10) ;; (:discard (:not (:todo "TODO"))))))))))) :config (org-super-agenda-mode))
@using Web_Programming_Project.Data.Enum; @model IEnumerable<Web_Programming_Project.Models.Box> @{ ViewData["Title"] = "Boxes"; } <h1>Boxes</h1> <div class="input-group mb-3"> @if (User.Identity.IsAuthenticated) { <a asp-action="Create" class="btn btn-success rounded-end me-4"><i class="fa-solid fa-plus"></i> Create box</a> } <input type="text" name="boxSearch" value="@ViewData["boxSearch"]" class="form-control rounded-start" placeholder="Search box name"> @if (ViewData["boxThemeId"] is null) { <select class="form-select" name="boxThemeId"> <option value="-1" selected>Select a theme</option> @foreach (Theme item in ViewBag.Themes) { <option value="@(item.Id)">@(item.ThemeName)</option> } </select> } else { <select class="form-select" name="boxThemeId"> @if ("-1".Equals(ViewData["boxThemeId"])) { <option value="-1" selected>Select a theme</option> } else { <option value="-1">Select a theme</option> } @foreach (Theme item in ViewBag.Themes) { @if (item.Id.Equals(ViewData["boxThemeId"])) { <option value="@(item.Id)" selected>@(item.ThemeName)</option> } else { <option value="@(item.Id)">@(item.ThemeName)</option> } } </select> } @if (ViewData["boxAgeRange"] is null) { <select class="form-select rounded-end" name="boxAgeRange" asp-items="Html.GetEnumSelectList<AgeCategoryEnum>().ToList()"> <option value="0" selected>Age range</option> </select> } else { <select class="form-select rounded-end" name="boxAgeRange"> @if ("0".Equals(ViewData["boxAgeRange"])) { <option value="0" selected>Age range</option> } else { <option value="0">Age range</option> } @foreach (SelectListItem item in Html.GetEnumSelectList<AgeCategoryEnum>()) { @if (item.Value.Equals(ViewData["boxAgeRange"])) { <option value="@(item.Value)" selected>@(item.Text)</option> } else { <option value="@(item.Value)">@(item.Text)</option> } } </select> } <button name="prevBoxSort" value="@ViewData["prevBoxSort"]" class="btn btn-primary rounded ms-4"><i id="prevBoxSortIcon" class="fa-solid fa-sort-alpha-@ViewData["prevBoxSort"]"></i></button> </div> <div class="row row-cols-1 row-cols-md-4" id="list-boxes"> <partial name="_BoxesCard" model="Model"/> </div> @if (User.Identity.IsAuthenticated) { <!-- Delete Popup --> <!-- Modal --> <div class="modal fade" id="modalDeleteBox" data-bs-backdrop="static" data-bs-keyboard="false" tabindex="-1" aria-labelledby="modalDeleteBoxLabel" aria-hidden="true"> <div class="modal-dialog modal-xl"> <div class="modal-content"> <div class="modal-header"> <h5 class="modal-title" id="modalDeleteBoxLabel">Delete a box</h5> <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button> </div> <div class="modal-body"> Are you sure to delete this box ? <br/> <div class="card mt-3 h-100 text-center"> <img id="modalDeleteBoxImg" src="/uploads/images/Boxes/default.png" class="mx-auto card-img-top render-img mt-4" alt="..."> <div class="card-body"> <h5 class="card-title" id="modalDeleteBoxName">Name</h5> <h6 class="card-subtitle mb-2 text-muted" id="modalDeleteBoxAgeCategory"></h6> <p class="card-text" id="modalDeleteBoxThemeName"></p> </div> </div> </div> <div class="modal-footer"> <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button> <button type="button" name="deleteBoxAction" value="-1" class="btn btn-danger">Delete</button> </div> </div> </div> </div> } @section Scripts { <script> $('select[name="boxAgeRange"]').change(function() { onSearchUpdate(); }); $('select[name="boxThemeId"]').change(function() { onSearchUpdate(); }); $('input[name="boxSearch"]').on("input", function() { onSearchUpdate(); }); $('button[name="prevBoxSort"]').click(function() { /* Switch the state of the button */ if ($('#prevBoxSortIcon').hasClass('fa-sort-alpha-down')) { $('#prevBoxSortIcon').removeClass('fa-sort-alpha-down').addClass('fa-sort-alpha-up'); $(this).val("up"); } else { $('#prevBoxSortIcon').removeClass('fa-sort-alpha-up').addClass('fa-sort-alpha-down'); $(this).val("down"); } onSearchUpdate(); }); function onSearchUpdate() { /* Data in the input */ var dataBoxSearch = $('input[name="boxSearch"]').val(); var dataBoxAgeRange = $('select[name="boxAgeRange"]').val(); var dataBoxThemeId = $('select[name="boxThemeId"]').val(); var dataPrevBoxSort = $('button[name="prevBoxSort"]').val(); const dataSearch = { boxSearch: dataBoxSearch, boxAgeRange: dataBoxAgeRange, boxThemeId: dataBoxThemeId, prevBoxSort: dataPrevBoxSort }; /* Ajax Request */ $.ajax({ url: "/Boxes/Search", type: "GET", data: dataSearch, success : function (data) { $("#list-boxes").html(data); if (typeof reload_evh_delete === 'function'){ reload_evh_delete(); } }, error : function (err) { $("#list-theme").html(` <div class="alert alert-danger" role="alert"> <h4 class="alert-heading">Ooopppss !</h4> <p>Error with the server... Please try again later.</p> </div> `); if (typeof reload_evh_delete === 'function'){ reload_evh_delete(); } } }); } </script> @if (User.Identity.IsAuthenticated) { <script> var modalDeleteBoxObj = null; function reload_evh_delete() { $('button[name="deleteBoxAction"]').click(function () { var boxId = $(this).val(); /* Check for bad data */ if (isNaN(boxId) || boxId == "") { return; } boxId = Number(boxId); if (boxId == -1) { return; } /* Ajax Request */ $.ajax({ url: "/Boxes/DeleteAjaxConfirmed", type: "POST", data: { id: boxId }, success: function (data) { $(`#boxCard${boxId}`).remove(); if ($.trim($("#list-boxes").html()) == "") { $("#list-boxes").html(` <div class="alert alert-danger col-12 col-md-12" role="alert"> <h4 class="alert-heading">Ooopppss !</h4> <p>No data exist in the database</p> </div> `); } displayToast("Deletion of the box", "The box has been successfully removed.", "check"); }, error: function (err) { displayToast("Deletion of the box", "Error when deleting the box.", "triangle-exclamation"); } }); $('button[name="deleteBoxAction"]').val(-1); modalDeleteBoxObj.hide(); }); $('button[name="openModalDeleteBox"]').click(function () { var boxId = $(this).val(); /* Check for bad data */ if (isNaN(boxId) || boxId == "") { return; } boxId = Number(boxId); if (boxId == -1) { return; } if (modalDeleteBoxObj == null) { modalDeleteBoxObj = new bootstrap.Modal(document.getElementById('modalDeleteBox'), {}); } const boxInfo = { id: boxId, boxName: $(`#boxName${boxId}`).text(), boxImg: $(`#boxImg${boxId}`).attr('src'), boxAgeCategory: $(`#boxAgeCategory${boxId}`).html(), boxThemeName: $(`#boxThemeName${boxId}`).text() } /* Fill the informations and show it */ $("#modalDeleteBoxLabel").text(`Delete ${boxInfo['boxName']}`); $("#modalDeleteBoxName").text(boxInfo['boxName']); $("#modalDeleteBoxAgeCategory").html(boxInfo['boxAgeCategory']); $("#modalDeleteBoxThemeName").text(boxInfo['boxThemeName']); $("#modalDeleteBoxImg").attr('src', boxInfo['boxImg']); $('button[name="deleteBoxAction"]').val(boxId); modalDeleteBoxObj.show(); }); } reload_evh_delete(); </script> } }
interface AbilityInterface { key: string; value: number | string | boolean | null; isPositive: boolean; toString(): string; } abstract class AbilityBase implements AbilityInterface { protected abstract _key: string; protected abstract _value: number | string | boolean | null; get key(): string { return this._key; } public abstract get value(): number | string | boolean | null; public abstract get isPositive(): boolean; public abstract toString(): string; } export { AbilityBase, AbilityInterface };
import Header from "./components/header/Header" import css from './styles/app.module.scss' import Hero from "./components/hero/Hero"; import Experience from "./components/experience/Experience"; import SocialLinks from "./components/social-links/SocialLinks"; import {ThemeContext} from './utils/Context' import { useContext } from "react"; import Skills from "./components/skills/Skills"; import person from '/person.png' import { Helmet } from "react-helmet"; import Work from "./components/work/Work"; const App = () => { const theme=useContext(ThemeContext); const darkMode=theme.state.darkMode; return <div className={`bg-primary ${css.container}`} style={{ background:darkMode? 'black' :'', color:darkMode?'white':'', }}> <Helmet> <title>Portfolio</title> <link rel="icon" type="image/png" href={person}/> </Helmet> <Header /> <Hero/> <SocialLinks /> <Work /> <Skills/> <Experience/> </div> ; }; export default App;
import express from 'express'; import boards from '../data/boardsData.js'; import { v4 as uuidv4 } from 'uuid'; const router = express.Router(); router.get('/', (req, res) => { const { ids } = req.query; if (ids) { const boardIds = ids.split(','); const filteredBoards = boards.filter(board => boardIds.includes(board.id)); res.json(filteredBoards); } else { res.json(boards); } }); router.get('/participants', (req, res) => { const { ids } = req.query; if (ids) { const memberIds = ids.split(','); const filteredBoards = boards.filter(board => Array.isArray(board.participants) && board.participants.some(participant => memberIds.includes(participant.id)) ); res.json(filteredBoards); } else { res.status(404).send({ message: 'member not participate any boards' }); } }); router.get('/:id', (req, res) => { const targetId = req.params.id; // UUIDは文字列なのでparseIntを削除 const index = boards.findIndex(board => board.id === targetId); if (index !== -1) { res.json(boards[index]); } else { res.status(404).send({ message: 'board not found' }); } }); router.post('/', (req, res) => { const newBoard = req.body; if (boards) { newBoard.id = uuidv4(); // IDをUUIDで設定 newBoard.bgImgSrc = 'bg.jpg'; boards.push(newBoard); res.status(201).json(newBoard); } else { res.status(500).send({ message: 'Failed to load or create boards data.' }); } }); router.patch('/:id', (req, res) => { const targetId = req.params.id; // UUIDは文字列なのでparseIntを削除 const updatedBoard = req.body; const index = boards.findIndex(board => board.id === targetId); if (index !== -1) { boards[index] = { ...boards[index], ...updatedBoard }; res.json(boards[index]); } else { res.status(404).send({ message: 'board not found' }); } }); router.delete('/:id', (req, res) => { const targetId = req.params.id; // UUIDは文字列なのでparseIntを削除 const index = boards.findIndex(board => board.id === targetId); if (index !== -1) { boards.splice(index, 1); res.status(204).send(); } else { res.status(404).send({ message: 'board not found' }); } }); export default router;
import { call, put, takeLatest } from 'redux-saga/effects'; import { getUsersService } from '@/services/usersService'; import { getUsersSuccess, getUsersFailure, } from '@/store/actions/users/getUsers'; import { GET_USERS_REQUEST } from '@/store/types/users/getUsers'; import { IResponseUsers, IGetUsersRequest } from '@/dtos/users.dto'; import Cookies from 'js-cookie'; function* getUsersSaga(action: IGetUsersRequest) { try { const token: string = yield call(() => Cookies.get('token')); const page = action.payload.page; const keyword = action.payload.keyword; const response: IResponseUsers = yield call(getUsersService, token, page, keyword); yield put(getUsersSuccess(response.data, response.pagination)); } catch (error) { if (error instanceof Error) { yield put(getUsersFailure(error.message)); } } } export function* watchGetUsersRequest() { yield takeLatest(GET_USERS_REQUEST, getUsersSaga); }
### Scope and Usage The Finnish Core Encounter profile is intended to encapsulate the most common and basic data model of encounters in Finnish healthcare systems. The profile also defines encounter's relation to the Kanta registry. As such the profile should be usable in most Finnish contexts. #### Relation to Finnish *palvelutapahtuma* [Kanta](https://www.kanta.fi/) is the Finnish national central registry of health and social welfare information. It has a specification for Palvelutapahtuma, this is typically translated as service-event or encompassing encounter. The scope of *palvelutapahtuma* is described in [Kanta documentation](https://www.kanta.fi/jarjestelmakehittajat/liite-2-palvelutapahtumien-esimerkkeja) (in Finnish). It's scope is not always the same as the encounter's. Encounter and *palvelutapahtuma* will overlap as concepts (depending on implementation). Some encounters clearly align with *palvelutapahtuma* while others don't. *Palvelutapahtuma* may contain multiple encounters. For example a series of treatments is considered to be a singular *palvelutapahtuma*, but systems most likely want to express each visit as a separate encounter (see kanta doc for the description of *hoitosarja*, there are other examples too). For deeper techical details, see (in Finnish): * Kanta [CDA R2 Header](https://www.kanta.fi/jarjestelmakehittajat/potilastiedon-arkiston-cda-r2-header) version 4.66 or later. * Descriptions of *palvelutapahtuma* * Kanta [HL7 V3 Medical Records specification](https://www.kanta.fi/jarjestelmakehittajat/potilastiedon-arkiston-medical-records). * Shows the role of *palvelutapahtuma* when making requests to Kanta ##### Why does an encounter need this information? Kanta HL7 V3 Medical Records specification requires that both queries and archivals transmit *palvelutapahtuma*'s OID identifier on each request. A client application that is integrated to a patient administration system (one that masters the data of encounters) often needs to create and query Kanta Medical records. Encounter is the best "vessel" we have to transmit this information. For example a laboratory information system may have it's own Kanta Medical Records capabilities and will archive lab results directly to Kanta. It receives encounter id in SMART App Launch context. Laboratory system can resolve *palvelutapahtuma*'s OID identifier by fetching the encounter resource. ##### How to communicate palvelutapahtuma via FHIR encounter? First thing is to identify the appropriate aggregation level of encounter. If encounter is not representing a *palvelutapahtuma*, but is a lower level encounter (some systems call these *prosessitapahtuma*), `partOf` should be used to point to upper level encounter (up until *palvelutapahtuma* level is reached). A *palvelutapahtuma* encounter is identified by an identifier. When encounter has an identifier with `use=official` it is considered to be a *palvelutapahtuma* and that identifier SHALL be the OID of a *palvelutapahtuma*. Other levels of encounter that are not a *palvelutapahtuma*, MUST NOT contain an identifier with `use=official`. #### Organizational responsibility The unit responsible for the encounter SHOULD be communicated using the `serviceProvider` property. For instance, there's a [detailed example with explanations](Encounter-id-for-ward-encounter.html) for how to fetch patients in a ward.
import { Injectable, UnauthorizedException } from '@nestjs/common'; import { CreateEventDto } from '../dto/create-event.dto'; import { EventParamsDto } from '../dto/get-events-params.dto'; import { UpdateEventDto } from '../dto/update-event.dto'; import { EventRepository } from '../repositories/event.repository'; import { SavedEventRepository } from '../repositories/saved-event.repository'; import { Cron } from '@nestjs/schedule'; import { LessThan } from 'typeorm'; @Injectable() export class EventService { constructor( private readonly eventRepository: EventRepository, private readonly savedEventRepository: SavedEventRepository, ) {} async getEventById(event_id: string) { return this.eventRepository.orm.findOneByOrFail({ id: event_id }); } async getEventsByParams(eventParams: EventParamsDto) { return this.eventRepository.queryEventsByParams(eventParams); } async createEvent(user_id: string, createEventDto: CreateEventDto) { const newEvent = this.eventRepository.create({ ...createEventDto, host_id: user_id, }); return newEvent; } async updateEvent(user_id: string, updateEventDto: UpdateEventDto) { const existingEvent = await this.eventRepository.orm.findOne({ where: { id: updateEventDto.id }, }); if (existingEvent.host_id !== user_id) { throw new UnauthorizedException( `User with ID: ${user_id} is not host of event with ID: ${updateEventDto.id}`, ); } const updatedEvent = await this.eventRepository.update(updateEventDto.id, { ...updateEventDto, }); return updatedEvent; } async deleteEvent(user_id: string, event_id: string) { await this.eventRepository.orm.delete({ host_id: user_id, id: event_id }); } async getUserSavedEvents(user_id: string) { return this.savedEventRepository.getUserSavedEvents(user_id); } async saveEventForUser(user_id: string, event_id: string) { const savedEventRecord = await this.savedEventRepository.create({ user_id, event_id, }); return savedEventRecord; } async deleteSavedEvent(user_id: string, event_id: string) { await this.savedEventRepository.orm.delete({ user_id, event_id }); } @Cron('0 0 * * *') async deletePastEvents() { const currentDate = new Date(); currentDate.setDate(currentDate.getDate() - 1); const res = await this.eventRepository.orm.delete({ start_date: LessThan(currentDate) }); console.log('Ran CRON Job'), { res }; } }
import Course from "../models/Course.js"; import Category from "../models/Category.js"; import User from "../models/User.js"; const createCourse = async (req, res) => { try { const course = await Course.create({ name: req.body.name, description: req.body.description, category: req.body.category, user: req.session.userID }); req.flash("success", `${course.name} has been created succesfully`); res.status(201).redirect('/courses'); } catch (error) { req.flash("error", ` Something happened !`); res.status(400).redirect('/courses'); }; }; const getAllCourses = async (req, res) => { try { const categorySlug = req.query.categories; const query = req.query.search; const category = await Category.findOne({ slug: categorySlug }); let filter = {}; if (categorySlug) { filter = { category: category._id }; }; if (query) { filter = { name: query } }; if (!query && !categorySlug) { filter.name = "", filter.category = null }; const courses = await Course.find({ $or: [ { name: { $regex: '.*' + filter.name + '.*', $options: 'i' } }, { category: filter.category } ] }).sort('-createdAt').populate('user'); const categories = await Category.find(); res.status(200).render('courses', { page_name: "courses", courses, categories, user: courses.user }) } catch (error) { res.status(400).json({ status: "fail", error }); }; }; const getCourse = async (req, res) => { try { const user = await User.findById(req.session.userID); const course = await Course.findOne({ slug: req.params.slug }).populate('user'); res.status(200).render('course-single', { page_name: "courses", course, user }) } catch (error) { res.status(400).json({ status: "fail", error }); }; }; const enrollCourse = async (req, res) => { try { const user = await User.findById(req.session.userID); await user.courses.push({ _id: req.body.course_id }); await user.save(); res.status(200).redirect('/users/dashboard'); } catch (error) { res.status(400).json({ error }); }; }; const releaseCourse = async (req, res) => { try { const user = await User.findById(req.session.userID); await user.courses.pull({ _id: req.body.course_id }); await user.save(); res.status(200).redirect('/users/dashboard'); } catch (error) { res.status(400).json({ error }); }; }; const deleteCourse = async (req, res) => { try { const course = await Course.findOneAndRemove({ slug: req.params.slug }); req.flash("error", `${course.name} has been removed succesfully`); res.status(200).redirect('/users/dashboard'); } catch (error) { res.status(400).json({ error }); }; }; const getUpdatePage = async (req, res) => { try { const course = await Course.findOne({ slug: req.params.slug }); const categories = await Category.find(); res.status(200).render('courseUpdatePage', { page_name: "courses", course, categories }); } catch (error) { res.status(400).json({ error }); }; }; const updateCourse = async (req, res) => { try { const course = await Course.findOne({ slug: req.params.slug }); course.name = req.body.name; course.description = req.body.description; course.category = req.body.category; course.save(); res.status(200).redirect('/users/dashboard'); } catch (error) { res.status(400).json({ error }); }; }; export { createCourse, getAllCourses, getCourse, enrollCourse, releaseCourse, deleteCourse, getUpdatePage, updateCourse };
/* Please note that all of the software in this file is in the public domain. */ /********************************************************************************************* This is public domain software that was developed by or for the U.S. Naval Oceanographic Office and/or the U.S. Army Corps of Engineers. This is a work of the U.S. Government. In accordance with 17 USC 105, copyright protection is not available for any work of the U.S. Government. Neither the United States Government, nor any employees of the United States Government, nor the author, makes any warranty, express or implied, without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE, or assumes any liability or responsibility for the accuracy, completeness, or usefulness of any information, apparatus, product, or process disclosed, or represents that its use would not infringe privately-owned rights. Reference herein to any specific commercial products, process, or service by trade name, trademark, manufacturer, or otherwise, does not necessarily constitute or imply its endorsement, recommendation, or favoring by the United States Government. The views and opinions of authors expressed herein do not necessarily state or reflect those of the United States Government, and shall not be used for advertising or product endorsement purposes. *********************************************************************************************/ /*******************************************************************************************/ /*! - Function: clean_exit - Purpose: Exit from the application after first cleaning up memory and orphaned files. This will only be called in the case of an abnormal exit (like a failed malloc). - Author: Jan C. Depner (area.based.editor@gmail.com) - Date: 07/16/14 - Arguments: - ret = Value to be passed to exit (); If set to -999 we were called from the SIGINT signal handler so we must return to allow it to SIGINT itself. - Returns: - void - Caveats: This function is static, it is only used internal to the API and is not callable from an external program. *********************************************************************************************/ static void libslas_clean_exit (int32_t ret) { int32_t i; for (i = 0 ; i < LIBSLAS_MAX_FILES ; i++) { /* If we were in the process of creating a file we need to remove it since it isn't finished. */ if (las[i].fp != NULL) { if (las[i].created) { fclose (las[i].fp); remove (las[i].path); } } } /* If we were called from the SIGINT handler return there, otherwise just exit. */ if (ret == -999 && getpid () > 1) return; exit (ret); } /*******************************************************************************************/ /*! - Function: sigint_handler - Purpose: Simple little SIGINT handler. Allows us to clean up the files if we were creating a new LIBSLAS file and someone does a CTRL-C. - Author: Jan C. Depner (area.based.editor@gmail.com) - Date: 02/25/09 - Arguments: - sig = The signal - Returns: - void - Caveats: The way to do this was borrowed from Martin Cracauer's "Proper handling of SIGINT/SIGQUIT", http://www.cons.org/cracauer/sigint.html This function is static, it is only used internal to the API and is not callable from an external program. *********************************************************************************************/ static void libslas_sigint_handler (int sig) { libslas_clean_exit (-999); signal (SIGINT, SIG_DFL); #ifdef NVWIN3X raise (sig); #else kill (getpid (), SIGINT); #endif } /***************************************************************************/ /*! - Module Name: big_endian - Programmer(s): Jan C. Depner - Date Written: July 1992 - Purpose: This function checks to see if the system is big-endian or little-endian. - Arguments: NONE - Returns: 3 if big-endian, 0 if little-endian \***************************************************************************/ static int32_t libslas_big_endian () { union { int32_t word; uint8_t byte[4]; } a; a.word = 0x00010203; return ((int32_t) a.byte[3]); } /***************************************************************************/ /*! - Module Name: swap_uint32_t - Programmer(s): Jan C. Depner - Date Written: July 1992 - Purpose: This function swaps bytes in a four byte int. - Arguments: word - pointer to the int ****************************************************************************/ void libslas_swap_uint32_t (uint32_t *word) { uint32_t temp[4]; temp[0] = *word & 0x000000ff; temp[1] = (*word & 0x0000ff00) >> 8; temp[2] = (*word & 0x00ff0000) >> 16; temp[3] = (*word & 0xff000000) >> 24; *word = (temp[0] << 24) + (temp[1] << 16) + (temp[2] << 8) + temp[3]; } /***************************************************************************/ /*! - Module Name: swap_double - Programmer(s): Jan C. Depner - Date Written: July 1992 - Purpose: This function swaps bytes in an eight byte double. - Arguments: word - pointer to the double ****************************************************************************/ void libslas_swap_double (double *word) { int32_t i; uint8_t temp; union { uint8_t bytes[8]; double d; }eq; memcpy (&eq.bytes, word, 8); for (i = 0 ; i < 4 ; i++) { temp = eq.bytes[i]; eq.bytes[i] = eq.bytes[7 - i]; eq.bytes[7 - i] = temp; } *word = eq.d; } /***************************************************************************/ /*! - Module Name: swap_uint16_t - Programmer(s): Jan C. Depner - Date Written: July 1992 - Purpose: This function swaps bytes in a two byte int. - Arguments: word - pointer to the int ****************************************************************************/ void libslas_swap_uint16_t (uint16_t *word) { uint16_t temp; #ifdef NVWIN3X #if defined (__MINGW32__) || defined (__MINGW64__) swab((char *)word, (char *)&temp, 2); #else _swab((char *)word, (char *)&temp, 2); #endif #else swab (word, &temp, 2); #endif *word = temp; return; }
package com.example.myapplication; import android.app.Activity; import android.content.Intent; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ImageView; import android.widget.TextView; import androidx.annotation.NonNull; import androidx.core.app.ActivityOptionsCompat; import androidx.recyclerview.widget.RecyclerView; import com.bumptech.glide.Glide; import com.example.myapplication.Activity.DetailsActivity; import com.example.myapplication.Model.RomanticModel; import java.util.List; public class RomanticAdapter extends RecyclerView.Adapter<RomanticAdapter.MyViewHolder> { List<RomanticModel> dataModels; public RomanticAdapter(List<RomanticModel> dataModels) {this.dataModels = dataModels;} @NonNull @Override public RomanticAdapter.MyViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) { View view = LayoutInflater.from(parent.getContext()). inflate(R.layout.movie_card,parent,false); return new MyViewHolder(view); } @Override public void onBindViewHolder(@NonNull RomanticAdapter.MyViewHolder holder, int position) { holder.textView.setText(dataModels.get(position).getRtitle()); Glide.with(holder.itemView.getContext()). load(dataModels.get(position).getRthumb()).into(holder.imageView); holder.imageView.setOnClickListener(view -> { //when click send data to details activity Intent sendData2Detail = new Intent(holder.imageView.getContext(), DetailsActivity.class); sendData2Detail.putExtra("title",dataModels.get(position).getRtitle()); sendData2Detail.putExtra("country",dataModels.get(position).getRcountry()); sendData2Detail.putExtra("cover",dataModels.get(position).getRcover()); sendData2Detail.putExtra("desc",dataModels.get(position).getRdesc()); sendData2Detail.putExtra("eps",dataModels.get(position).getReps()); sendData2Detail.putExtra("length",dataModels.get(position).getRlength()); sendData2Detail.putExtra("link",dataModels.get(position).getRlink()); sendData2Detail.putExtra("rating",dataModels.get(position).getRrating()); //sendData2Detail.putExtra("thumb",dataModels.get(position).getAthumb()); sendData2Detail.putExtra("cast",dataModels.get(position).getRcast()); //transition animation 2 detail ActivityOptionsCompat optionsCompat = ActivityOptionsCompat .makeSceneTransitionAnimation((Activity)holder.itemView.getContext(),holder.imageView, "imageMain"); //sharedElementName is the same as xml file (imageMain) holder.itemView.getContext().startActivity(sendData2Detail,optionsCompat.toBundle()); }); } @Override public int getItemCount() { return dataModels.size(); } public class MyViewHolder extends RecyclerView.ViewHolder { ImageView imageView; TextView textView; public MyViewHolder(@NonNull View itemView) { super(itemView); imageView = itemView.findViewById(R.id.imageView); textView = itemView.findViewById(R.id.movie_title); } } }
<!DOCTYPE html> <html lang="en" xmlns:th="http://www.thymeleaf.org"> <head> <meta charset="UTF-8"> <title>Drink Shop</title> <!-- Bootstrap core CSS --> <link th:href="@{/public/bootstrap/css/bootstrap.min.css}" rel="stylesheet"> <link th:href="@{/public/jquery/jquery-ui.min.css}" rel="stylesheet"> <link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.6.3/css/all.css" integrity="sha384-UHRtZLI+pbxtHCWp1t77Bi1L4ZtiqrqD80Kn4Z8NTSRyMA2Fd33n5dQ8lWUE00s/" crossorigin="anonymous"/> <!-- Custom styles for this template --> <link th:href="@{/css/main.css}" rel="stylesheet"> <script th:src="@{/public/jquery/jquery.js}"></script> <script th:src="@{/public/jquery/jquery-ui.min.js}"></script> <script th:src="@{/js/main.js}"></script> </head> <body> <div class="container"> <th:block th:insert="fragments/header"/> <h2>Beverages</h2> <div class="row"> <div th:each="bottle : ${response.bottleDTOS}" class="card" style="width: 18rem;"> <img style="width: 286px; height: 286px;" class="card-img-top" th:src="@{${'/img/'+bottle.bottlePic}}" th:alt="${bottle.name}"> <div class="card-body"> <h5 class="card-title">[[${bottle.name}]]</h5> <p class="card-text">Price: [[${bottle.price}]]$</p> <p class="card-text">Volume: [[${bottle.volume}]]ml</p> <p class="card-text">Vol. Percentage: [[${bottle.volumePercent}]]%</p> <p class="card-text">Stock: [[${bottle.inStock}]]</p> <a th:href="@{${'/add-bottle-to-cart?id='+bottle.id}}" class="btn btn-primary">Add to Cart</a> </div> </div> </div> <h2>Crates</h2> <div class="row"> <div th:each="crate : ${response.crateDTOS}" class="card" style="width: 18rem;"> <img style="width: 286px; height: 286px;" class="card-img-top" th:src="@{${'/img/'+crate.cratePic}}" th:alt="${crate.name}"> <div class="card-body"> <h5 class="card-title">[[${crate.name}]]</h5> <p class="card-text">Price: [[${crate.price}]]$</p> <p class="card-text">Pack: [[${crate.noOfBottles}]] Bottles</p> <p class="card-text">Stock: [[${crate.cratesInStock}]]</p> <a th:href="@{${'/add-crate-to-cart?id='+crate.id}}" class="btn btn-primary">Add to Cart</a> </div> </div> </div> </div> </body> </html>
/** * */ package view; import java.awt.Dimension; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import javax.swing.ImageIcon; import javax.swing.JButton; import javax.swing.JPanel; import javax.swing.JSlider; import javax.swing.JToolBar; import javax.swing.event.ChangeEvent; import javax.swing.event.ChangeListener; import controller.AnimationActions; /** * @author Dondang * */ public class AnimationButtons extends JToolBar { /** * */ private final ArtPanel myPanel; /** * */ private JButton myFowardMotion; /** * */ private JButton myUpDown; /** * */ private JButton myPlay; /** * */ private JButton myPause; /** * */ private JSlider mySpeed; /** * */ private JButton myFoward; /** * * @param panel */ public AnimationButtons(JPanel panel) { myPanel = (ArtPanel) panel; myFowardMotion = new JButton(new AnimationActions(myPanel,null, myPanel.Animation1())); myUpDown = new JButton(new AnimationActions(myPanel, null, myPanel.Animation2())); myFowardMotion.setText("Foward and Back"); myUpDown.setText("up and down"); myPlay = new JButton(new ImageIcon("play.png")); myPause = new JButton(new ImageIcon("pause .png")); myFoward = new JButton(new ImageIcon("step-forward.png")); mySpeed = new JSlider(1,20); mySpeed.setMinimumSize(new Dimension(200, 30)); mySpeed.setMaximumSize(new Dimension(200, 30)); fastFoward(); addSliderActions(); addPlayPauseActions(); addButtons(); // TODO Auto-generated constructor stub } public void addButtons(){ add(myFowardMotion); add(myUpDown); add(mySpeed); add(myPlay); add(myPause); add(myFoward); } public void addSliderActions(){ mySpeed.addChangeListener(new ChangeListener(){ @Override public void stateChanged(ChangeEvent arg0) { // TODO Auto-generated method stub myPanel.setSpeed(mySpeed.getValue()); } }); } public void addPlayPauseActions(){ myPlay.addActionListener(new ActionListener(){ @Override public void actionPerformed(ActionEvent arg0) { myPanel.timerStart(); } }); myPause.addActionListener(new ActionListener(){ @Override public void actionPerformed(ActionEvent e) { // TODO Auto-generated method stub myPanel.timerStop(); } }); } public void fastFoward(){ myFoward.addActionListener(new ActionListener(){ @Override public void actionPerformed(ActionEvent e) { myPanel.doFastForward(); } }); } }
import { Component } from "@angular/core"; import { AuthenticationService } from "./services/authentication-service.service"; import { Router } from "@angular/router"; @Component({ selector: "app-root", templateUrl: "./app.component.html", styleUrls: ["./app.component.css"] }) export class AppComponent { title = "pcShop"; user = ""; constructor(private authenticationService: AuthenticationService, private router: Router) { } logout(): void { this.authenticationService.logout(); this.router.navigate(["/login"]); } isLoggedIn(): boolean { const res = this.authenticationService.isLoggedIn(); if (res) { this.getCurrentUsername(); } return res; } getCurrentUsername(): void { const res = this.authenticationService.getCurrentUser(); if (res) { this.user = res; } } }
# pylint: disable=g-bad-file-header # Copyright 2023 DeepMind Technologies Limited. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """A JAX implementation of BERT.""" import typing as tp import chex from enn import base as enn_base from enn.networks import base as networks_base from enn.networks import indexers from enn.networks.bert import base import haiku as hk import jax import jax.numpy as jnp # BERT layer norm uses # github.com/google-research/tf-slim/blob/master/tf_slim/layers/layers.py#L2346 TF_LAYERNORM_EPSILON = 1e-12 def make_bert_enn( bert_config: base.BertConfig, is_training: bool, ) -> base.BertEnn: """Makes the BERT model as an ENN with state.""" def net_fn(inputs: base.BertInput) -> networks_base.OutputWithPrior: """Forwards the network (no index).""" hidden_drop = bert_config.hidden_dropout_prob if is_training else 0. att_drop = bert_config.attention_probs_dropout_prob if is_training else 0. bert_model = BERT( vocab_size=bert_config.vocab_size, hidden_size=bert_config.hidden_size, num_hidden_layers=bert_config.num_hidden_layers, num_attention_heads=bert_config.num_attention_heads, intermediate_size=bert_config.intermediate_size, hidden_dropout_prob=hidden_drop, attention_probs_dropout_prob=att_drop, max_position_embeddings=bert_config.max_position_embeddings, type_vocab_size=bert_config.type_vocab_size, initializer_range=bert_config.initializer_range, ) # Embed and summarize the sequence. return bert_model( # pytype: disable=wrong-arg-types # jax-devicearray input_ids=inputs.token_ids, token_type_ids=inputs.segment_ids, input_mask=inputs.input_mask.astype(jnp.int32), is_training=is_training, ) # Transformed has the rng input, which we need to change --> index. transformed = hk.transform_with_state(net_fn) def apply( params: hk.Params, state: hk.State, inputs: base.BertInput, index: enn_base.Index, # BERT operates with an RNG-key index. ) -> tp.Tuple[networks_base.OutputWithPrior, hk.State]: key = index return transformed.apply(params, state, key, inputs) def init(rng_key: chex.PRNGKey, inputs: base.BertInput, index: enn_base.Index) -> tp.Tuple[hk.Params, hk.State]: del index # rng_key is duplicated in this case. return transformed.init(rng_key, inputs) return base.BertEnn(apply, init, indexers.PrngIndexer()) class BERT(hk.Module): """BERT as a Haiku module. This is the Haiku module of the BERT model implemented in tensorflow here: https://github.com/google-research/bert/blob/master/modeling.py#L107 """ def __init__( self, vocab_size: int, hidden_size: int, num_hidden_layers: int, num_attention_heads: int, intermediate_size: int, hidden_dropout_prob: float, attention_probs_dropout_prob: float, max_position_embeddings: int, type_vocab_size: int, initializer_range: float, name: str = 'BERT', ): super().__init__(name=name) self.vocab_size = vocab_size self.hidden_size = hidden_size self.num_hidden_layers = num_hidden_layers self.num_attention_heads = num_attention_heads self.intermediate_size = intermediate_size self.hidden_dropout_prob = hidden_dropout_prob self.attention_probs_dropout_prob = attention_probs_dropout_prob self.max_position_embeddings = max_position_embeddings self.type_vocab_size = type_vocab_size self.initializer_range = initializer_range self.size_per_head = hidden_size // num_attention_heads def _bert_layer( self, layer_input: jax.Array, layer_index: int, input_mask: jax.Array, is_training: bool, ) -> jax.Array: """Forward pass of a single layer.""" *batch_dims, seq_length, hidden_size = layer_input.shape queries = hk.Linear( self.hidden_size, w_init=hk.initializers.TruncatedNormal(self.initializer_range), name='query_%d' % layer_index)( layer_input) keys = hk.Linear( self.hidden_size, w_init=hk.initializers.TruncatedNormal(self.initializer_range), name='keys_%d' % layer_index)( layer_input) values = hk.Linear( self.hidden_size, w_init=hk.initializers.TruncatedNormal(self.initializer_range), name='values_%d' % layer_index)( layer_input) btnh = (*batch_dims, seq_length, self.num_attention_heads, self.size_per_head) queries = jnp.reshape(queries, btnh) keys = jnp.reshape(keys, btnh) values = jnp.reshape(values, btnh) # Attention scores. attention_scores = jnp.einsum('...tnh,...fnh->...nft', keys, queries) attention_scores *= self.size_per_head**(-0.5) # attention_scores shape: [..., num_heads, num_attending, num_attended_over] # Broadcast the input mask along heads and query dimension. # If a key/value location is pad, do not attend over it. # Do that by plunging the attention logit to negative infinity. bcast_shape = list(input_mask.shape[:-1]) + [1, 1, input_mask.shape[-1]] input_mask_broadcasted = jnp.reshape(input_mask, bcast_shape) attention_mask = -1. * 1e30 * (1.0 - input_mask_broadcasted) attention_scores += attention_mask attention_probs = jax.nn.softmax(attention_scores) if is_training: attention_probs = hk.dropout(hk.next_rng_key(), self.attention_probs_dropout_prob, attention_probs) # Weighted sum. attention_output = jnp.einsum('...nft,...tnh->...fnh', attention_probs, values) attention_output = jnp.reshape( attention_output, (*batch_dims, seq_length, hidden_size)) # Projection to hidden size. attention_output = hk.Linear( self.hidden_size, w_init=hk.initializers.TruncatedNormal(self.initializer_range), name='attention_output_dense_%d' % layer_index)( attention_output) if is_training: attention_output = hk.dropout(hk.next_rng_key(), self.hidden_dropout_prob, attention_output) attention_output = hk.LayerNorm( axis=-1, create_scale=True, create_offset=True, eps=TF_LAYERNORM_EPSILON, name='attention_output_ln_%d' % layer_index)( attention_output + layer_input) # FFW. intermediate_output = hk.Linear( self.intermediate_size, w_init=hk.initializers.TruncatedNormal(self.initializer_range), name='intermediate_output_%d' % layer_index)( attention_output) intermediate_output = jax.nn.gelu(intermediate_output) layer_output = hk.Linear( self.hidden_size, w_init=hk.initializers.TruncatedNormal(self.initializer_range), name='layer_output_%d' % layer_index)( intermediate_output) if is_training: layer_output = hk.dropout(hk.next_rng_key(), self.hidden_dropout_prob, layer_output) layer_output = hk.LayerNorm( axis=-1, create_scale=True, create_offset=True, eps=TF_LAYERNORM_EPSILON, name='layer_output_ln_%d' % layer_index)( layer_output + attention_output) return layer_output def __call__( self, input_ids: jax.Array, token_type_ids: tp.Optional[jax.Array] = None, input_mask: tp.Optional[jax.Array] = None, is_training: bool = True, ) -> networks_base.OutputWithPrior: """Forward pass of the BERT model.""" # Prepare size, fill out missing inputs. *_, seq_length = input_ids.shape if input_mask is None: input_mask = jnp.ones(shape=input_ids.shape, dtype=jnp.int32) if token_type_ids is None: token_type_ids = jnp.zeros(shape=input_ids.shape, dtype=jnp.int32) position_ids = jnp.arange(seq_length)[None, :] # Embeddings. word_embedder = hk.Embed( vocab_size=self.vocab_size, embed_dim=self.hidden_size, w_init=hk.initializers.TruncatedNormal(self.initializer_range), name='word_embeddings') word_embeddings = word_embedder(input_ids) token_type_embeddings = hk.Embed( vocab_size=self.type_vocab_size, embed_dim=self.hidden_size, w_init=hk.initializers.TruncatedNormal(self.initializer_range), name='token_type_embeddings')( token_type_ids) position_embeddings = hk.Embed( vocab_size=self.max_position_embeddings, embed_dim=self.hidden_size, w_init=hk.initializers.TruncatedNormal(self.initializer_range), name='position_embeddings')( position_ids) input_embeddings = ( word_embeddings + token_type_embeddings + position_embeddings) input_embeddings = hk.LayerNorm( axis=-1, create_scale=True, create_offset=True, eps=TF_LAYERNORM_EPSILON, name='embeddings_ln')( input_embeddings) if is_training: input_embeddings = hk.dropout( hk.next_rng_key(), self.hidden_dropout_prob, input_embeddings) # BERT layers. h = input_embeddings extra = {} for i in range(self.num_hidden_layers): h = self._bert_layer( h, layer_index=i, input_mask=input_mask, is_training=is_training) extra[f'hidden_layer_{i}'] = h last_layer = h # Masked language modelling logprobs. mlm_hidden = hk.Linear( self.hidden_size, w_init=hk.initializers.TruncatedNormal(self.initializer_range), name='mlm_dense')(last_layer) mlm_hidden = jax.nn.gelu(mlm_hidden) mlm_hidden = hk.LayerNorm( axis=-1, create_scale=True, create_offset=True, eps=TF_LAYERNORM_EPSILON, name='mlm_ln')(mlm_hidden) output_weights = jnp.transpose(word_embedder.embeddings) logits = jnp.matmul(mlm_hidden, output_weights) logits = hk.Bias(bias_dims=[-1], name='mlm_bias')(logits) log_probs = jax.nn.log_softmax(logits, axis=-1) # Pooled output: [CLS] token. first_token_last_layer = last_layer[..., 0, :] pooled_output = hk.Linear( self.hidden_size, w_init=hk.initializers.TruncatedNormal(self.initializer_range), name='pooler_dense')( first_token_last_layer) pooled_output = jnp.tanh(pooled_output) extra['logits'] = logits extra['log_probs'] = log_probs extra['pooled_output'] = pooled_output return networks_base.OutputWithPrior( train=pooled_output, prior=jnp.zeros_like(pooled_output), extra=extra)
import Mongoose from "mongoose"; import Assets from "../models/db/Assets.model"; import Acquisitions from "../models/db/borrow.model"; import Replicate from "replicate"; import 'dotenv/config'; import Forecasts from "../models/db/forecasting.model"; import Depreciated from "../models/db/depreciated.model"; import Missing from "../models/db/missing.model"; export const addAsset = async (req, res) => { try { const { name, sn, usage } = req.body; const created = await Assets.create({ _id: new Mongoose.Types.ObjectId(), name, sn, usage, status: "inuse", createdAt: new Date(), }); if(created){ return res.status(201).json({ message: 'Asset Added successfully', }); } } catch (error) { console.log(error); res.status(500).json({ message: "Something went wrong", error: JSON.stringify(error) }); } } export const acceptBorrow = async (req, res) => { try { const { status, id } = req.body; const updated = await Acquisitions.findByIdAndUpdate(id, { status }); if(updated){ return res.status(201).json({ message: 'Acquisition update successfully', }); } } catch (error) { console.log(error); res.status(500).json({ message: "Something went wrong", error: JSON.stringify(error) }); } } export const dispose = async (req, res) => { try { const { id, disposed } = req.body; const results = await Assets.findByIdAndUpdate(id, { status: disposed ? 'inuse' : 'disposed' }); if(results){ return res.status(201).json({ message: 'Acquisition update successfully', }); } } catch (error) { console.log(error); res.status(500).json({ message: "Something went wrong", error: JSON.stringify(error) }); } } const replicate = new Replicate({ auth: process.env.REPLICATE_API_TOKEN, }); export const askForecast = async (req, res) => { try { const { request, asset } = req.body; res.status(200).json({ message: "Forecast requested.", }); const output = await replicate.run( "meta/codellama-70b-instruct:a279116fe47a0f65701a8817188601e2fe8f4b9e04a518789655ea7b995851bf", { input: { prompt: request, } } ); if(output){ await Forecasts.create({ _id: new Mongoose.Types.ObjectId(), asset, description: output.join(""), createdAt: new Date(), }); } } catch (error) { console.log(error, "KKKK") return res.status(500).json({ message: "Something went wrong.", }) } } export const getForecasts = async (req, res) => { try { const forecasts = await Forecasts.find(); return res.status(200).json({ forecasts, }) } catch (error) { } } export const countsAdmin = async (req, res) => { try { const depreciated = await Depreciated.countDocuments(); const missing = await Missing.countDocuments(); const acquisitions = await Acquisitions.countDocuments(); const forecasts = await Forecasts.countDocuments(); const assets = await Assets.countDocuments(); return res.status(200).json({ counts: { depreciated, missing, acquisitions, forecasts, assets } }) } catch (error) { console.log(error); res.status(500).json({ message: "Something went wrong", error: JSON.stringify(error) }); } }
/** * @file SCReduxTempoClockController.sc * * @desc A TempoClock controller that receives tempo from the Redux * state tree. * * @author Colin Sullivan <colin [at] colin-sullivan.net> * * @copyright 2018 Colin Sullivan * @license Licensed under the MIT license. **/ SCReduxTempoClockController : Object { // the actual TempoClock instance var <clock, store, lastTempoBPM; *new { arg params; ^super.new().init(params); } getTempoFromState { var state = store.getState(); ^state.tempo; } getTempoFromBPM { arg tempoBPM; ^tempoBPM / 60.0; } setClockTempoFromState { var tempoBPM = this.getTempoFromState(); clock.tempo = this.getTempoFromBPM(tempoBPM); lastTempoBPM = tempoBPM; } init { arg params; //"SCReduxTempoClockController.init".postln(); store = params['store']; if (params['clock'].isNil(), { clock = TempoClock.default; }, { clock = params['clock']; }); store.subscribe({ this.handleStateChange(); }); } beats { ^clock.beats; } handleStateChange { var state = store.getState(); var tempoBPM = this.getTempoFromState(); if (lastTempoBPM != tempoBPM, { //"SCReduxTempoClockController: Changing tempo abruptly...".postln(); this.setClockTempoFromState(); }); } }
def sum_digits(n): """Sum all the digits of n. >>> sum_digits(10) # 1 + 0 = 1 1 >>> sum_digits(4224) # 4 + 2 + 2 + 4 = 12 12 >>> sum_digits(1234567890) 45 >>> x = sum_digits(123) # make sure that you are using return rather than print >>> x 6""" total = 0 while n > 0: digit = n % 10 # Extract the last digit total += digit # Add the extracted digit to the total n //= 10 # Remove the last digit by floor division return total if __name__ == '__main__': print(sum_digits(10)) print(sum_digits(4224)) print(sum_digits(1234567890)) x = sum_digits(123) print(x)
# SPDX-FileCopyrightText: Copyright (c) 2022-2024 NVIDIA CORPORATION & AFFILIATES. All rights reserved. # SPDX-License-Identifier: Apache-2.0 # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import os from multiprocessing import Event, Process, Queue from tensorrt_llm.logger import logger from tensorrt_llm.profiler import (MemUnitType, bytes_to_target_unit, device_memory_info, host_memory_info) class MemoryMonitor: def __init__(self, query_interval=0.1): self.query_interval = query_interval # second(s) self.mem_monitor_process = None # bytes self._peak_host_memory = 0 self._peak_device_memory = 0 self.pid = os.getpid() self.device_handles = {} self.signal_event = Event() # Sending signal to subprocess self.peak_mem_queue = Queue() # Receiving results from subprocess def start(self): self.mem_monitor_process = Process(target=self._upd_peak_memory_usage, args=(self.signal_event, self.peak_mem_queue)) self.mem_monitor_process.start() logger.debug("Launched memory monitor subprocess.") def kill(self): if self.mem_monitor_process is not None: self.mem_monitor_process.kill() logger.debug("Memory monitor subprocess is killed.") def stop(self): self.signal_event.set() logger.debug("Sent signal to stop memory monitor subprocess.") peak_mem_use = self.peak_mem_queue.get(timeout=10) self._peak_host_memory = max(self._peak_host_memory, peak_mem_use[0]) self._peak_device_memory = max(self._peak_device_memory, peak_mem_use[1]) self.mem_monitor_process.join(timeout=10) self.mem_monitor_process = None logger.debug("Memory monitor subprocess joined.") def _upd_peak_memory_usage(self, signal_event, peak_mem_queue): peak_host_used, peak_device_used = self.get_memory_usage() while not signal_event.is_set(): host_used, device_used = self.get_memory_usage() peak_host_used = max(host_used, peak_host_used) peak_device_used = max(device_used, peak_device_used) peak_mem_queue.put((peak_host_used, peak_device_used)) def get_memory_usage(self): host_used, _, _ = host_memory_info(self.pid) device_used, _, _ = device_memory_info() return host_used, device_used def get_peak_memory_usage(self, unit: MemUnitType = 'GiB'): return bytes_to_target_unit(self._peak_host_memory, unit), \ bytes_to_target_unit(self._peak_device_memory, unit)
# 인프런 알고리즘 문제풀이(C/C++) ## [48]: 각 행의 평균과 가장 가까운 값 ### 🌴 문제 9 × 9 격자판에 쓰여진 81개의 자연수가 주어질 때, 각 행의 평균을 구하고, <br> 그 평균과 가장 가까운 값을 출력하는 프로그램을 작성하세요. 평균은 소수점 첫 째 자리에서 반올림합니다. <br> 평균과 가까운 값이 두 개이면 그 중 큰 값을 출력하세요. #### ◻ 입력 첫 째 줄부터 아홉 번째 줄까지 한 줄에 아홉 개씩 자연수가 주어진다. <br> 주어지는 자연수는 100보다 작다. #### ◻ 출력 첫째 줄에 첫 번째 줄부터 각 줄에 각행의 평균과 그 행에서 평균과 가장 가까운 수를 출력한다. --- ### 💬 참고 code ```c++ #include <stdio.h> #include <math.h> #include <algorithm> //절댓값 abs함수 사용 int arr[10][10]; int main() { int arr[10][10], i, j, sum, avg, tmp, min, res; for (i = 0; i < 9; i++) { sum = 0; for (j = 0; j < 9; j++) { scanf("%d", &arr[i][j]); sum += arr[i][j]; } avg = (sum / 9.0) + 0.5; printf("%d ", avg); min = 2147000000; for (j = 0; j < 9; j++) { tmp = abs(arr[i][j] - avg); if (tmp < min) { min = tmp; res = arr[i][j]; } else if (tmp == min) { if (arr[i][j] > res) res = arr[i][j]; } } printf("%d\n", res); } } ``` ### 📙 comment - 소수 첫째자리에서 반올림하여 int형 반환하기<br> ```c++ avg = (sum / 9.0) + 0.5; ``` _>_ sum을 9.0으로 나누고 0.5를 더한 값을 int형 변수에 넣으니까 소수점은 날라가고 정수형이 반환됨<br> 다만 여기서 sum을 그냥 9로 나누면 소숫점 안생기고 정수만 반환된다는 점<br> _>_ **실수/ 정수 => 실수 (더 큰 범위의 자료형이 반환)** <br> - 아래와 같이 avg 변수에 담지 않고 바로 출력하면 원하는 숫자 안나옴<br> why?? ```c++ for (i = 0; i < 9; i++) { sum = 0; for (j = 0; j < 9; j++) { scanf("%d", &arr[i][j]); sum += arr[i][j]; } printf("%d\n", ((sum / 9.0) + 0.5)); } ```
#Listar todas las partidas # Esta funcion no recibe parametros y retorna una lista con todas las partidas ya registradas # Cada item de esta lista es un diccionario # Ej: {'ID': '1', 'JUGADOR1': 'alexis', 'JUGADOR2': 'Martin', 'GANADOR': 'alexis', 'RESULTADO': '102100102'} def listar_partidas() : with open("./archivos/puntajes.csv", "r", encoding="utf-8") as file : lines = file.read().split("\n") keys = lines.pop(0).split(",") registro = [] for line in lines : dato_partida = {} datos = line.split(",") for i in range(len(datos)) : dato_partida[keys[i]] = datos[i] registro.append(dato_partida) return registro #Agregar una partida a la lista # Esta funcion recibe como parametro un diccionario con toda la informacion de una partida # Ej: {'JUGADOR1': 'alexis', 'JUGADOR2': 'Martin', 'GANADOR': 'alexis', 'RESULTADO': '102100102'} # Escribe en la ultima linea la partida que se paso por parametro # no existe la necesidad de pasar el "ID" de la partida def agregar_partida(partida: dict) : datos_agregar = [] with open("./archivos/puntajes.csv", "r", encoding="utf-8") as file : lines = file.read().split("\n") ultimo_id = lines[-1][0] try : es_numero = int(ultimo_id) except ValueError : ultimo_id = "0" datos_agregar.append(str(int(ultimo_id) + 1)) for dato in partida.values() : datos_agregar.append(dato) linea = ",".join(datos_agregar) with open("./archivos/puntajes.csv","a", encoding="utf-8") as add_file : add_file.writelines(f"\n{linea}") #Eliminar una partida de la lista # Esta funcion recibe como parametro un numero el cual indica el numero de partida("ID") que se quiere eliminar # Si lo en cuentra elimina esa partida y vuelve a escribir todo el archivo con todas las partidas sin contar la partida que eliminamos, retorna "True" # Si no encuentra esa partida retorna "False" def eliminar_partida(num_partida: int) : if type(num_partida) != int : return False texto_nuevo = "" partidas = listar_partidas() num_indicador = -1 for i in range(len(partidas)) : if partidas[i]["ID"] == str(num_partida): num_indicador = i if num_indicador >= 0 : partidas.pop(num_indicador) lista_claves = [] for keys in partidas[0].keys() : lista_claves.append(keys) texto_nuevo = ",".join(lista_claves) for item in partidas : datos = [] texto_nuevo += "\n" for dato in item.values() : datos.append(dato) linea = ",".join(datos) texto_nuevo += linea with open("./archivos/puntajes.csv","w") as file : file.write(texto_nuevo) return True else : return False
import Generator from 'yeoman-generator'; import chalk from 'chalk' import { simpleGit } from 'simple-git'; import * as fs from 'fs'; export default class Index extends Generator { constructor(args, opts) { super(args, opts); this.argument('generator-isi', { type: String, required: false }); } // Async Await async prompting() { this.answers = await this.prompt([{ type: 'input', name: 'name', message: 'Your project name', default: this.appname, // appname return the default folder name to project store: true, }, ]); } initializing() { this.log(chalk.magenta('***---***---***---***---***---***')) this.log(chalk.green(' SCAFFOLD ISI ')) this.log(chalk.magenta('***---***---***---***---***---***')) } writing() { this._writingReactTemplate(); } _packageJsonTitle(string) { // Remover espaços em branco e caracteres especiais string = string.replace(/[^\w-~\/]/g, ''); // Converter para letras minúsculas string = string.toLowerCase(); // Adicionar prefixo "@user/" se não começar com "@" ou "user/" if (!string.match(/^(?:@(?:[a-z0-9-*~][a-z0-9-*._~]*)?\/[a-z0-9-._~])|[a-z0-9-~][a-z0-9-._~]*$/)) { string = `@user/${string}`; } // Retornar a string adaptada ao padrão return string; } _writingReactTemplate() { const git = simpleGit(); const gitRepoUrl = 'https://github.com/gabrielsegalla/GenericFrontend.git'; const destiny = this.answers.name; this.log(chalk.blue('Cloning Repository...')); git.clone(gitRepoUrl, destiny, (err)=>{ if(err){ this.log(chalk.red(err)) }else{ const indexHtmlPath = `${destiny}/public/index.html`; const indexHtmlContent = fs.readFileSync(indexHtmlPath, 'utf-8'); const modifiedIndexHtmlContent = indexHtmlContent.replace('gdProject', this.answers.name); const navbarfilePath = `${destiny}/src/components/Navbar.tsx`; const navbarfileContent = fs.readFileSync(navbarfilePath, 'utf-8'); const navbarModifiedContent = navbarfileContent.replace('gdProject', this.answers.name); const packagefilePath = `${destiny}/package.json`; const packagefileContent = fs.readFileSync(packagefilePath, 'utf-8'); const packageModifiedContent = packagefileContent.replace('gd-project', this._packageJsonTitle(this.answers.name)); // Agora, você pode sobrescrever o arquivo com o conteúdo modificado: fs.writeFileSync(indexHtmlPath, modifiedIndexHtmlContent); fs.writeFileSync(navbarfilePath, navbarModifiedContent); fs.writeFileSync(packagefilePath, packageModifiedContent); } }); } end() { this.log(chalk.magenta('***---***---***---***---***---***')) this.log(chalk.blue(`Success! Created a generic Project using NextJs at /${this.answers.name} ` )) this.log(chalk.blue(`We suggest that you begin by typing:\n` )) this.log(chalk.green(`cd ${this.answers.name}`)) this.log(chalk.green(`npm install`)) this.log(chalk.green(`npm run dev`)) this.log(chalk.magenta('***---***---***---***---***---***')) } };
/* * Copyright (C) 2021 -- 2023 Zachary A. Kissel * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. */ package datastructures; /** * A generic node for chaining. * * @param <T> the object stored in the list. * @author Zach Kissel */ public class Node<T> { private T item; // The nodes data. private Node<T> next; // The next reference. /** * The default constructor. It sets the next reference to null. */ public Node() { this.next = null; } /** * This is the overloaded constructor that sets the item * to itm and the next reference to null. * * @param itm the item stored in the node. */ public Node(T itm) { this.item = itm; this.next = null; } /** * This is the overloaded constructor that sets the item to itm and the * next reference to nxt. * * @param itm the item to be stored in the node. * @param next the reference to the next node in the chain. */ public Node(T itm, Node<T> nxt) { this.item = itm; this.next = nxt; } /** * Set the item field of the node to item. * * @param item the item to store in the node. */ public void setItem(T item) { this.item = item; } /** * Get the value stored in the item field of the node. * * @return the item stored in the node. */ public T getItem() { return item; } /** * Set the value of the next reference. * * @param next the reference to the next node in the chain. */ public void setNext(Node<T> next) { this.next = next; } /** * Return the reference to the next node in the chain. * * @return the reference to the next node in the chain. */ public Node<T> getNext() { return this.next; } }
const express = require("express"); const cors = require("cors"); const port = 5000; const app = express(); //post in json response app.use(express.json()); app.use( cors({ //for allow all clients listening origin: ["http://localhost:3000"], }) ); app.listen(port, () => console.log(`listen on post ${port}`)); app.get("/test", (req, res) => { return res.json({ apitest: "My App Backend API is Working", myname: "test data", }); }); app.post("/calculate", (req, res) => { const { a, b, type } = req.body; let a_num = parseInt(a); let b_num = parseInt(b); let c_num = 0; if (type == "add") { c_num = a_num + b_num; } else if (type == "sub") { c_num = a_num - b_num; } else if (type == "mul") { c_num = a_num * b_num; } else if (type == "div") { c_num = a_num / b_num; } return res.json({ calculation: c_num, }); }); app.get("/calculate", (req, res) => { return res.json({ response: "calculation get", }); }); //database const mysql = require("mysql"); const db_host = "localhost"; const db_user = "root"; const db_password = ""; const db_database = "tutorial_student"; const pool = mysql.createPool({ connectionLimit: 10, host: db_host, user: db_user, password: db_password, database: db_database, charset: "utf8mb4", }); app.post("/student/add", (req, res) => { const { name, location } = req.body; pool.getConnection((err, connection) => { if (err) { return res.json({ apires: "Database_Issue" }); } else { connection.query( `insert into student (name,location) ` + `values('${name}','${location}');`, (err, rows) => { if (!err) { return res.json({ success: true, apires: "Added" }); } else { return res.json({ apires: "Database_Issue" }); } } ); } }); }); app.get("/student/list", (req, res) => { pool.getConnection((err, connection) => { if (err) { return res.json({ apires: "Database_Issue" }); } else { connection.query(`select * from student;`, (err, rows) => { if (!err) { return res.json({ success: true, apires: "List", result: rows }); } else { return res.json({ apires: "Database_Issue" }); } }); } }); }); app.put("/student/update", (req, res) => { const { id, name, location } = req.body; pool.getConnection((err, connection) => { if (err) { return res.json({ apires: "Database_Issue" }); } else { connection.query( `update student set name='${name}', location='${location}' where student_id='${id}';`, (err, rows) => { if (!err) { return res.json({ success: true, apires: "Updated" }); } else { return res.json({ apires: "Database_Issue" }); } } ); } }); }); app.delete("/student/delete", (req, res) => { const { id } = req.body; pool.getConnection((err, connection) => { if (err) { return res.json({ apires: "Database_Issue" }); } else { connection.query( `delete from student where student_id='${id}';`, (err, rows) => { if (!err) { return res.json({ success: true, apires: "Deleted" }); } else { return res.json({ apires: "Database_Issue" }); } } ); } }); });
export function remove_duplicate_chars(str: string) { const deduped_arr = [...new Set(str.split(''))] return deduped_arr.join('') } function clean_white_space(str: string, separator?: string) { return str.split(' ').join(separator) } export function encrypt(plain_text: string, k: string): string { const key: string = remove_duplicate_chars(clean_white_space(k, '')) const sorted_key = key.split('').sort() const row_length = key.length const clean_plain_text = clean_white_space(plain_text, '_') const col_length = Math.ceil(clean_plain_text.length / key.length) const matrix: string[] = [] let offset = 0 for (let i = 0; i < col_length; i++) { let slice = clean_plain_text.slice(offset, offset + row_length) if (slice.length < key.length) { const white_space = ' ' slice += white_space.repeat(key.length - slice.length) } matrix.push(slice) offset += row_length } const encr_text: string[] = [] for (const k of sorted_key) { let temp = '' for (const r of matrix) { temp += r.charAt(key.indexOf(k)) } encr_text.push(temp) } return encr_text.join('') } export function decrypt(cipher_text: string, k: string): string { const key: string = remove_duplicate_chars(clean_white_space(k, '')) const sorted_key = key.split('').sort() const col_length = Math.ceil(cipher_text.length / key.length) const matrix: string[] = [] let offset = 0 for (let i = 0; i < key.length; i++) { matrix.push(cipher_text.slice(offset, offset + col_length)) offset += col_length } let plain_text = '' for (let i = 0; i < col_length; i++) { for (const k of key) { plain_text += matrix[sorted_key.indexOf(k)].charAt(i) } } return plain_text.split('_').join(' ') }
/** * Fichero de implementación del NodoTrie. */ #include "NodoTrie.hpp" NodoTrie::NodoTrie (void) { /* Por defecto un nodo no es fin de palabra. */ esFinPalabra = false; /* Por defecto el mapa está vacío y por tanto no hay que inicializar sus elementos. */ } NodoTrie::~NodoTrie (void) { /* Cuando liberamos la memoria de un NodoTrie hay que liberar tambien la de todos los hijos, de forma recursiva. */ for (auto it = mapaHijos.begin(); it != mapaHijos.end(); it++) { /* Eliminamos el nodo, que es la segunda componente del mapa. */ delete it->second; } /* El resto de cosas como el booleano y el mapa con sus entradas se eliminan solas al declararse de forma estática. */ } NodoTrie * NodoTrie::consulta (char caracter) { /* Obtenemos la entrada del mapa que codifica caracter. */ auto tupla = mapaHijos.find(caracter); /* Si dicha entrada equivale al fin del mapa no existe (véase std::unordered_map::find los valores que devuelve) y por tanto devolvemos un puntero nulo. */ if (tupla == mapaHijos.end()) return nullptr; /* En otro caso devolvemos el puntero a NodoTrie almacenado en dicha tupla. */ return tupla -> second; } void NodoTrie::inserta (char caracter) { /* En otro caso creamos un nuevo nodo y lo insertaremos con clave caracter. */ NodoTrie * nuevoNodo = new NodoTrie; /* Véase std::unordered_map::insert. Si se intenta insertar un elemento cuya clave ya está presente no se insertará ya que las claves deben ser únicas. */ mapaHijos.insert({caracter,nuevoNodo}); } void NodoTrie::elimina (char caracter) { /* Obtenemos la tupla que corresponde al caracter. */ auto tupla = mapaHijos.find(caracter); /* Si no existe dicha tupla en el mapa no hacemos nada. */ if (tupla == mapaHijos.end()) return; /* En otro caso llamamos al destructor para destruir el nodo hijo en dicha tupla (destrucción recursiva). */ delete tupla->second; /* Eliminamos la entrada correspondiente al caracter dado del mapa del nodo. */ mapaHijos.erase(tupla); } void NodoTrie::ponMarca (void) { esFinPalabra = true; } void NodoTrie::quitarMarca (void) { esFinPalabra = false; } bool NodoTrie::hayMarca (void) { return esFinPalabra; } int NodoTrie::numeroHijos (void) { return mapaHijos.size(); } std::vector<std::pair<char, NodoTrie*>> NodoTrie::listaHijos (void) { /* Vector que vamos a devolver. */ std::vector<std::pair<char, NodoTrie*>> lista; for (auto hijo : mapaHijos) { lista.push_back(hijo); } /* Devolvemos la lista de hijos. */ return lista; }
import numpy as np import pandas as pd import polars as pl import pytest from pytest_lazyfixture import lazy_fixture from opsml.registry import CardRegistries from opsml.registry.cards import DataCard, DataSplit from opsml.registry.sql.registry import CardInfo, CardRegistry card_info = CardInfo(name="test-data", team="opsml", user_email="@opsml.com") @pytest.mark.parametrize("test_data", [lazy_fixture("test_df")]) def test_data_card_splits_column_pandas(test_data: pd.DataFrame): # list of dicts will automatically be converted to DataSplit data_split = [ {"label": "train", "column_name": "year", "column_value": 2020}, {"label": "test", "column_name": "year", "column_value": 2021}, ] data_card = DataCard(data=test_data, info=card_info, data_splits=data_split) assert data_card.data_splits[0].column_name == "year" assert data_card.data_splits[0].column_value == 2020 splits = data_card.split_data() assert splits.train.X.shape[0] == 1 assert splits.test.X.shape[0] == 1 data_card = DataCard( data=test_data, info=card_info, data_splits=data_split, dependent_vars=["n_legs"], ) assert data_card.data_splits[0].column_name == "year" assert data_card.data_splits[0].column_value == 2020 splits = data_card.split_data() assert splits.train.y.shape[0] == 1 assert splits.test.y.shape[0] == 1 assert isinstance(splits.train.X, pd.DataFrame) def test_data_splits_pandas_inequalities( iris_data: pd.DataFrame, pandas_timestamp_df: pd.DataFrame, ): data = iris_data # test ">= and <" data_card = DataCard( data=data, info=card_info, dependent_vars=["target"], data_splits=[ DataSplit( label="train", column_name="sepal_width_cm", column_value=3.0, inequality=">=", ), DataSplit( label="test", column_name="sepal_width_cm", column_value=3.0, inequality="<", ), ], ) data_splits = data_card.split_data() assert data_splits.train.X.shape[0] == 93 assert data_splits.train.y.shape[0] == 93 assert data_splits.test.X.shape[0] == 57 assert data_splits.test.y.shape[0] == 57 # test "> and <=" data_card = DataCard( data=data, info=card_info, dependent_vars=["target"], data_splits=[ DataSplit( label="train", column_name="sepal_width_cm", column_value=3.0, inequality=">", ), DataSplit( label="test", column_name="sepal_width_cm", column_value=3.0, inequality="<=", ), ], ) data_splits = data_card.split_data() assert data_splits.train.X is not None assert data_splits.train.y is not None assert data_splits.test.X is not None assert data_splits.test.y is not None # test "==" data_card = DataCard( data=data, info=card_info, dependent_vars=["target"], data_splits=[ DataSplit( label="train", column_name="sepal_width_cm", column_value=3.0, ), DataSplit( label="test", column_name="sepal_width_cm", column_value=2.0, ), ], ) data_splits = data_card.split_data() assert data_splits.train.X is not None assert data_splits.train.y is not None assert data_splits.test.X is not None assert data_splits.test.y is not None ### test timestamp date_split = pd.to_datetime("2019-01-01").floor("D") data_card = DataCard( data=pandas_timestamp_df, info=card_info, data_splits=[ DataSplit( label="train", column_name="date", column_value=date_split, inequality=">", ), ], ) data_splits = data_card.split_data() assert data_splits.train.X.shape[0] == 1 @pytest.mark.parametrize("test_data", [lazy_fixture("test_df")]) def test_data_card_splits_row_pandas(test_data: pd.DataFrame): data_split = [ DataSplit(label="train", start=0, stop=2), DataSplit(label="test", start=3, stop=4), ] data_card = DataCard( data=test_data, info=card_info, data_splits=data_split, ) assert data_card.data_splits[0].start == 0 assert data_card.data_splits[0].stop == 2 splits = data_card.split_data() assert splits.train.X.shape[0] == 2 assert splits.test.X.shape[0] == 1 data_card = DataCard( data=test_data, info=card_info, data_splits=data_split, dependent_vars=["n_legs"], ) splits = data_card.split_data() assert splits.train.y.shape[0] == 2 assert splits.test.y.shape[0] == 1 @pytest.mark.parametrize("test_data", [lazy_fixture("test_df")]) def test_data_card_splits_index_pandas(test_data: pd.DataFrame): data_split = [ DataSplit(label="train", indices=[0, 1, 2]), ] data_card = DataCard( data=test_data, info=card_info, data_splits=data_split, ) splits = data_card.split_data() assert splits.train.X.shape[0] == 3 data_card = DataCard( data=test_data, info=card_info, data_splits=data_split, dependent_vars=["n_legs"], ) splits = data_card.split_data() assert splits.train.y.shape[0] == 3 ########## Numpy def test_numpy_splits_index(regression_data): X, y = regression_data data_split = [ DataSplit(label="train", indices=[0, 1, 2]), ] data_card = DataCard( data=X, info=card_info, data_splits=data_split, ) splits = data_card.split_data() assert splits.train.X.shape[0] == 3 assert isinstance(splits.train.X, np.ndarray) def test_numpy_splits_row(regression_data): X, y = regression_data data_split = [ DataSplit(label="train", start=0, stop=3), ] data_card = DataCard( data=X, info=card_info, data_splits=data_split, ) splits = data_card.split_data() assert splits.train.X.shape[0] == 3 ########## Polars def test_data_splits_polars_column_value(iris_data_polars: pl.DataFrame): data = iris_data_polars # test ">= and <" data_card = DataCard( data=data, info=card_info, dependent_vars=["target"], data_splits=[ DataSplit( label="train", column_name="sepal_width_cm", column_value=3.0, inequality=">=", ), DataSplit( label="test", column_name="sepal_width_cm", column_value=3.0, inequality="<", ), ], ) data_splits = data_card.split_data() assert data_splits.train.X.shape[0] == 93 assert data_splits.train.y.shape[0] == 93 assert data_splits.test.X.shape[0] == 57 assert data_splits.test.y.shape[0] == 57 # test "> and <=" data_card = DataCard( data=data, info=card_info, dependent_vars=["target"], data_splits=[ DataSplit( label="train", column_name="sepal_width_cm", column_value=3.0, inequality=">", ), DataSplit( label="test", column_name="sepal_width_cm", column_value=3.0, inequality="<=", ), ], ) data_splits = data_card.split_data() assert data_splits.train.X is not None assert data_splits.train.y is not None assert data_splits.test.X is not None assert data_splits.test.y is not None # test "==" data_card = DataCard( data=data, info=card_info, data_splits=[ DataSplit( label="train", column_name="sepal_width_cm", column_value=3.0, ), DataSplit( label="test", column_name="sepal_width_cm", column_value=2.0, ), ], ) splits = data_card.split_data() assert splits.train.X is not None assert splits.test.X is not None assert isinstance(splits.train.X, pl.DataFrame) def test_data_splits_polars_index(iris_data_polars: pl.DataFrame): data = iris_data_polars # depen vars data_card = DataCard( data=data, info=card_info, dependent_vars=["target"], data_splits=[DataSplit(label="train", start=0, stop=10)], ) data_splits = data_card.split_data() assert data_splits.train.X.shape[0] == 10 assert data_splits.train.y.shape[0] == 10 # no depen vars data_card = DataCard( data=data, info=card_info, data_splits=[DataSplit(label="train", start=0, stop=10)], ) data_splits = data_card.split_data() assert data_splits.train.X.shape[0] == 10 def test_data_splits_polars_row( db_registries: CardRegistries, iris_data_polars: pl.DataFrame, ): data = iris_data_polars # depen vars data_card = DataCard( data=data, info=card_info, dependent_vars=["target"], data_splits=[DataSplit(label="train", indices=[0, 1, 2])], ) data_splits = data_card.split_data() assert data_splits.train.X.shape[0] == 3 assert data_splits.train.y.shape[0] == 3 # no depen vars data_card = DataCard( data=data, info=card_info, data_splits=[DataSplit(label="train", indices=[0, 1, 2])], ) data_splits = data_card.split_data() assert data_splits.train.X.shape[0] == 3 def test_datacard_split_fail(db_registries: CardRegistries, test_df: pd.DataFrame): registry: CardRegistry = db_registries.data data_card = DataCard( data=test_df, info=card_info, feature_descriptions={"test": "test"}, ) registry.register_card(card=data_card) loaded_card: DataCard = registry.load_card(uid=data_card.uid) # load data loaded_card.load_data() # should raise logging info loaded_card.load_data() with pytest.raises(ValueError): data_card.split_data()
# Funções de ativação em redes neurais multicamadas A **_step function_** (função degrau), como demonstrado anteriormente no modelo Perceptron de uma camada, é uma função de ativação simples e limitada em sua aplicabilidade, sendo adequada principalmente para esse tipo de modelo. A **função sigmoide**, por sua vez, produz resultados dentro do intervalo $[0, 1]$, uma característica que a distingue da função degrau, cujos valores se limitam a 0 e 1. A função sigmoide é amplamente aplicável e demonstra um bom desempenho em muitos cenários. Seu gráfico pode ser visualizado abaixo: ![](./assets/grafico-funcao-sigmoid.png) Matematicamente, essa função é expressa como: $$ y = \frac{1}{1 + e^{-x}} $$ A função sigmoide é especialmente útil quando se trata de valores de probabilidade ou sempre que uma resposta binária é desejada. Notavelmente, ela não gera valores negativos. > Neurônios que empregam a função sigmoide como função de ativação são frequentemente chamados de **neurônios sigmóides**. No caso de cenários que requerem retornar valores negativos, existe a **função tangente hiperbólica** (_hyperbolic tangent_), que gera valores no intervalo $[-1, 1]$: $$ y = \frac{e^x - e^{-x}}{e^x + e^{-x}} $$ O gráfico dessa função é o seguinte: ![](./assets/grafico-tangente-hiperbolica.png) A escolha da função de ativação depende da natureza do problema e dos resultados desejados, e cada uma dessas funções possui suas próprias vantagens e aplicações específicas.
DM_BEGIN_IMPORT_SECTION DM_SECTION(EZproxy) DM_BEGIN_COLLAPSIBLE This is the code which cleans/processes/compiles the raw EZproxy web logs and produces a single data set (concatenates all logs) containing pertinent/derived fields. DM_SUBSECTION(software dependencies) DM_SMALL1(Reminder: this is only necessary if you want to DM_ITALIC(build) this project. If you just want to consume the data product this outputs, you can skip to the section named "How to read the data product") Assumes a fairly recent version of R, and the following R packages (as of 2021-05-08) - DM_CODE(colorout) - DM_CODE(data.table) (version 1.14.1 or above) - DM_CODE(magrittr) - DM_CODE(stringr) - DM_CODE(openssl) - DM_CODE(libbib) (any version 1.6.2 or above) In addition to R, step 1 requires a compilation of a C++ program. Running DM_CODE(make) in the root directory will produce the proper executable (DM_CODE(step-1-clean-raw-logs-YEAR)) in the same directory, given that you have a C++ toolchain (DM_CODE(build-essential), etc...), DM_CODE(libfmt-dev), and DM_CODE(libre2-dev) installed. DM_SMALL1(Fun note: step 1 used to be in lisp but I wanted to see if I can improve the perfomance any by switching to C++. My first attempt was 10x slower (the c++ standard regex library isn't so fast). After a lot of trial and error, I finally got it down to 33% of the time it took the lisp script to run. Having said that, I estimate I'd have to (busy-wait) run this over a thousand times to make back my development time investment.) Lastly, DM_CODE(OpenSSL) must be installed for the DM_CODE(openssl) R package to dynamically link to. Developed on Debian GNU/Linux 10, 11, 12 DM_SUBSECTION(build instructions) The first step is to DM_CODE(rsync) the log directory from the EZproxy web server to the local directory called DM_CODE(logs). You can do this by running DM_CODE(./step-0-sync-logs.sh). That file also contains comments/reminders that you have to (a) be connected to the VPN, and (b) add DM_CODE(ezproxy) to your DM_CODE(/etc/hosts) or (better) DM_CODE(~/.ssh/config). If you're just beginning to use this now, many of the logs going back to the will no longer be available. Once the logs have finished (one way) syncing, run DM_CODE(./step-1-clean-raw-logs-YEAR). This produces a single, cleaned, intermediate data set containing the IP address, patron barcode, session, datetime of access, a shortened URL, and the full URL. This script (in addition to concatenating all daily logs into one file) excludes certain log entries, cleans URLs, and converts the dates into ISO 8601 format. This tab-separated file is stored in DM_CODE(./intermediate/cleaned-logs.dat). Finally, run the R script DM_CODE(./step-2-compile-ezproxy-stats-YEAR.R). This is where most of the processing takes place. It, among other things: - (irreversibly) hashes the patron barcode - categorized barcode type - joins with patron data to bring in ptype, home branch, and creation date (and DM_ITALIC(only) those fields) - joins with a vendor crosswalk to resolve the URL to a particular broad vendor DM_SUBSECTION(how to read the data product) The final product is DM_CODE(./target/exproxy_2021-up-to-YYYY-MM-DD.dat.gz) where DM_CODE(YYYY-MM-DD) is an ISO 8601 date. This is a gzipped-tab-delimited data file. You can un-gzip it (DM_CODE(gzip -d DATAFILE)) and then read it with any software that reads tab-delimited files. Note that LibreOffice. Gnumeric, or Excel aren't going to cut it for this one; the data file can have up to over 80 million rows. The full data set from 2020 contains 65.8 million rows. In R, you can use DM_CODE(fread) from the DM_CODE(data.table) package to read it straight from its gzipped form... DM_CODE_BLOCK( dat <- fread("./target/exproxy_2021-up-to-YYYY-MM-DD.dat.gz") ) DM_SUBSECTION(fields) The data product contains the following fields - DM_CODE(session) a unique session identifier - DM_CODE(ptype) patron type - DM_CODE(date_and_time) and ISO 8601 date and time (to the second) - DM_CODE(vendor) a broad vendor category - DM_CODE(url) a shortened URL - DM_CODE(barcode) an (irreversibly) hashed patron barcode - DM_CODE(barcode_category) broad categorization of barcode type - DM_CODE(homebranch) the patron's hone branch - DM_CODE(fullurl) the full URL - DM_CODE(patroncreatedate) The date that the patron was created - DM_CODE(extract) An attempt to pull the specific database accessed from the full URL - DM_CODE(just_date) Just the date of the access (no time component) (in ISO 8601, or course) DM_END_COLLAPSIBLE DM_END_IMPORT_SECTION
package controller; import entity.Especialidad; import entity.Medico; import model.EspecialidadModel; import model.MedicoModel; import javax.swing.*; import java.util.List; public class MedicoController { public static void getAll(){ MedicoModel objMedicoModel = new MedicoModel(); List<Object> listMedicos = objMedicoModel.findAll(); if (listMedicos.isEmpty()) { JOptionPane.showMessageDialog(null, "No hay medicos creado aun"); } else { String listMedicosText = "Lista de medicos \n"; for (Object iterador : listMedicos) { Medico objMedico = (Medico) iterador; listMedicosText += objMedico.toString() + "\n"; } JOptionPane.showMessageDialog(null, listMedicosText); } } public static String getAllString(){ MedicoModel objMedicoModel = new MedicoModel(); String listMedicos = "Lista de medicos \n"; for (Object iterador : objMedicoModel.findAll()){ Medico objMedico = (Medico) iterador; listMedicos += objMedico.toString() + "\n"; } return listMedicos; } public static void create(){ MedicoModel objMedicoModel = new MedicoModel(); String nombre = JOptionPane.showInputDialog("Ingrese el nombre del medico: "); String apellidos = JOptionPane.showInputDialog("Ingrese los apellidos del medico"); int idEspecialidad = Integer.parseInt(JOptionPane.showInputDialog("Ingrese el id de la especialidad del medico")); EspecialidadModel objEspecialidadModel = new EspecialidadModel(); Especialidad objEspecialidad = objEspecialidadModel.findById(idEspecialidad); if (objEspecialidad == null){ JOptionPane.showMessageDialog(null,"Especialdiad no encontrada"); }else { Medico objMedico = new Medico(); objMedico.setNombre(nombre); objMedico.setApellidos(apellidos); objMedico.setIdEspecialidad(idEspecialidad); objMedico.setObjEspecialidad(objEspecialidadModel.findById(idEspecialidad)); JOptionPane.showMessageDialog(null, objMedico.toString()); } } public static void delete(){ MedicoModel objMedicoModel = new MedicoModel(); String listMedicos = getAllString(); int isDelete = Integer.parseInt(JOptionPane.showInputDialog(listMedicos+"\n Ingresa el id del meidco a eliminar: ")); Medico objMedico = objMedicoModel.findById(isDelete); if (objMedico == null){ JOptionPane.showMessageDialog(null, "Medico no encontrado"); }else { int confirm = JOptionPane.showConfirmDialog(null, "Estas seguro con eliminar este medico? "+objMedico.toString()); if (confirm==0){ objMedicoModel.delete(objMedico); } } } public static void update(){ MedicoModel objMedicoModel = new MedicoModel(); String listMedicos = getAllString(); int idUpdate = Integer.parseInt(JOptionPane.showInputDialog(listMedicos+"\n Ingresa el id de el medico a actualizar: ")); Medico objMedico = objMedicoModel.findById(idUpdate); if (objMedico == null){ JOptionPane.showMessageDialog(null, "Medico no encontrado"); }else { String nombre = JOptionPane.showInputDialog("Ingrese el nombre del medico: "); String apellidos = JOptionPane.showInputDialog("Ingrese los apellidos del medico: "); int idEspecialidad = Integer.parseInt(JOptionPane.showInputDialog(EspecialidadController.getAllString() +"\nIngrese el id de la nueva especialidad")); EspecialidadModel objEspecialidadModel = new EspecialidadModel(); Especialidad objEspecialidad = objEspecialidadModel.findById(idEspecialidad); if (objEspecialidad == null) { JOptionPane.showMessageDialog(null, "Especialidad no encontrada", "Error", JOptionPane.ERROR_MESSAGE); return; } objMedico.setNombre(nombre); objMedico.setApellidos(apellidos); objMedico.setIdEspecialidad(idEspecialidad); objMedicoModel.update(objMedico); } } public static void FindByEspecialidad(){ MedicoModel objMedicoModel = new MedicoModel(); EspecialidadModel objEspecialidadModel = new EspecialidadModel(); try { String listMedicos = "Lista de medicos \n"; int especialidad_id = Integer.parseInt(JOptionPane.showInputDialog(EspecialidadController.getAllString() + "\n Ingrese el id de la especialidad por la que buscara los medicos: ")); Especialidad objEspecialidad = objEspecialidadModel.findById(especialidad_id); if (objEspecialidad != null){ for (Object iterador : objMedicoModel.findMedicosByEspecialidad(especialidad_id)){ Medico objMedico = (Medico) iterador; listMedicos += objMedico.toString() + "\n"; } JOptionPane.showMessageDialog(null, "Los medicos con esta especialidad son: \n" + listMedicos + "\n"); }else { JOptionPane.showMessageDialog(null, "Especialidad no encontrada", "Error", JOptionPane.ERROR_MESSAGE); } }catch (NumberFormatException e) { JOptionPane.showMessageDialog(null, "El id de la especialidad debe ser numérico.", "Error", JOptionPane.ERROR_MESSAGE); } } }
import { collection, doc, getDoc, getDocs, onSnapshot, setDoc } from "firebase/firestore"; import FirebaseManager from "./firebase_manager"; import BettingManager from "./betting_manager"; import GameModel from "../../util/model/game_model"; import { httpsCallableFromURL } from "firebase/functions"; import MemberManager from "./member_manager"; import define from "../../util/define"; import LogModel from "../../util/model/log_model"; export default class GameManager{ static instance = null; static getInstance() { if (GameManager.instance === null) { GameManager.instance = new GameManager(); } return GameManager.instance; } children = []; constructor() { this._watchCollection(); } async _watchCollection() { if (this._watching) return; this._watching = true; await onSnapshot(collection(FirebaseManager.db, "games"), (querySnapshot) => { const games = querySnapshot.docs .map(doc => new GameModel(doc.data())) .sort((a, b) => b.createdAt - a.createdAt); console.log({ games, }); this.children = games; GameManager.setListInHtml(games); }); } static answerSet(id, answer) { return new Promise((resolve, reject) => { const functionName = 'answerSet'; const queryParameters = { gameId: id, answer }; const queryString = Object.keys(queryParameters).map(key => `${key}=${queryParameters[key]}`).join('&'); const baseUrl = FirebaseManager.functionsApiUrl; const functionUrl = `${baseUrl}/${functionName}?${queryString}`; httpsCallableFromURL( FirebaseManager.functions, functionUrl, )() .then((result) => { // // Read result of the Cloud Function. // /** @type {any} */ // const data = result.data; // const sanitizedMessage = data.text; console.log({ result, }); resolve(result.data); }).catch(err => { console.log({ err, // code, // message, // details, }); resolve(err.data); }) }); } static async teamAdd(title, teamPoint) { await GameManager.add( GameModel.createByNameAndOptions( title, define.teamNames, teamPoint, ), ); } static async logibrosAdd(title, teamPoint) { await GameManager.add( GameModel.createByNameAndOptions( title, define.logibrosNames, teamPoint, ), ); } static async allClear() { return new Promise((resolve, reject) => { const functionName = 'allClear'; const baseUrl = FirebaseManager.functionsApiUrl; const functionUrl = `${baseUrl}/${functionName}`; httpsCallableFromURL( FirebaseManager.functions, functionUrl, )() .then((result) => { // // Read result of the Cloud Function. // /** @type {any} */ // const data = result.data; // const sanitizedMessage = data.text; console.log({ result, }); resolve(result.data); }).catch(err => { console.log({ err, // code, // message, // details, }); resolve(err.data); }) }); } static async add(game) { if (MemberManager.getInstance().isAdmin === false) { alert('관리자만 게임을 생성할 수 있습니다.'); return; } try { const json = GameModel.toJson(game); await setDoc(doc(FirebaseManager.db, "games", game.id), json); alert('게임 생성에 성공했습니다.'); } catch(err) { console.error(err); alert('게임 생성에 실패했습니다.'); } finally { } } static async getLogsById(id) { const logInGameQuerySnapshot = await getDocs(collection(FirebaseManager.db, "games", id, "logs")); return logInGameQuerySnapshot.docs .map(doc => new LogModel(doc.data())) .sort((a, b) => b.createdAt - a.createdAt); } static setListInHtml(games) { const gameListBox = document.getElementById('gameListBox'); const gameListEmpty = document.getElementById('gameListEmpty'); gameListEmpty.style.display = 'none'; const ul = gameListBox.querySelector('ul'); ul.innerHTML = ''; games.forEach((game) => { const li = document.createElement('li'); li.classList.add('list-group-item'); li.classList.add('d-flex'); li.classList.add('justify-content-between'); li.classList.add('align-items-center'); const name = document.createElement('span'); if (game.isActivated) { // li.classList.add('list-group-item-success'); } else { li.classList.add('game-not-activated'); li.classList.add('list-group-item-secondary'); name.classList.add('text-muted'); } name.innerText = game.name; li.appendChild(name); ul.appendChild(li); const btnGroup = document.createElement('div'); btnGroup.classList.add('btn-group'); btnGroup.classList.add('btn-group-sm'); btnGroup.setAttribute('role', 'group'); btnGroup.setAttribute('aria-label', 'Basic example'); li.appendChild(btnGroup); const adminButton = document.createElement('button'); // gameAdminModal 열기 adminButton.classList.add('btn'); adminButton.classList.add('btn-warning'); adminButton.setAttribute('data-bs-toggle', 'modal'); adminButton.setAttribute('data-bs-target', '#gameAdminModal'); adminButton.innerText = '관리'; adminButton.onclick = () => { const label = document.getElementById('gameAdminModalLabel'); label.innerText = game.name + ' 관리'; const answerSetButton = document.getElementById('answerSetButton'); answerSetButton.onclick = async () => { if (game.answer) { alert('이미 정답이 설정되었습니다.'); return; } const selectOptionDoc = document.querySelector('input[name="answer"]:checked'); if (!selectOptionDoc) { alert('정답을 선택해주세요.'); return; } const answer = selectOptionDoc.value; const spiner = document.getElementById('answerSetButtonSpinner'); spiner.style.display = 'inline-block'; answerSetButton.style.display = 'none'; const result = await GameManager.answerSet(game.id, answer) || { isErr: true, message: '응답이 없습니다.' }; if (result.isErr) { alert('정답 설정에 실패했습니다. ' + result.message); } else { alert('정답 설정에 성공했습니다.'); } spiner.style.display = 'none'; answerSetButton.style.display = 'inline-block'; }; const adminAnswerBox = document.getElementById('adminAnswerBox'); adminAnswerBox.innerHTML = ''; game.options.forEach((option) => { const formCheck = document.createElement('div'); formCheck.classList.add('form-check'); const formCheckInput = document.createElement('input'); formCheckInput.classList.add('form-check-input'); formCheckInput.type = 'radio'; formCheckInput.name = 'answer'; formCheckInput.value = option; formCheckInput.id = option; formCheck.appendChild(formCheckInput); const formCheckLabel = document.createElement('label'); formCheckLabel.classList.add('form-check-label'); formCheckLabel.setAttribute('for', option); formCheckLabel.innerText = option; formCheck.appendChild(formCheckLabel); adminAnswerBox.appendChild(formCheck); }); const unlockButton = document.getElementById('bettingUnlockButton'); const lockButton = document.getElementById('bettingLockButton'); unlockButton.style.display = 'inline-block'; lockButton.style.display = 'inline-block'; if (game.isOnBetting) { unlockButton.style.display = 'none'; } else { lockButton.style.display = 'none'; } lockButton.onclick = async () => { const spinner = document.getElementById('bettinglockButtonSpinner'); spinner.style.display = 'inline-block'; lockButton.style.display = 'none'; const isSuccess = await BettingManager.updateIsOnBettingById(game.id, false); spinner.style.display = 'none'; if (isSuccess) { game.isOnBetting = false; unlockButton.style.display = 'inline-block'; } else { lockButton.style.display = 'inline-block'; } }; unlockButton.onclick = async () => { const spinner = document.getElementById('bettinglockButtonSpinner'); spinner.style.display = 'inline-block'; unlockButton.style.display = 'none'; const isSuccess = await BettingManager.updateIsOnBettingById(game.id, true); spinner.style.display = 'none'; if (isSuccess) { game.isOnBetting = true; lockButton.style.display = 'inline-block'; } else { unlockButton.style.display = 'inline-block'; } } }; if (MemberManager.getInstance().isAdmin) { btnGroup.appendChild(adminButton); } const detailButton = document.createElement('button'); detailButton.classList.add('btn'); detailButton.classList.add('btn-info'); detailButton.setAttribute('data-bs-toggle', 'modal'); detailButton.setAttribute('data-bs-target', '#gameDetailModal'); detailButton.innerText = '정보보기'; detailButton.onclick = async () => { const spiner = document.getElementById('gameDetailModalSpinner'); spiner.style.display = 'inline-block'; const gameDetailTotalPoint = document.getElementById('gameDetailTotalPoint'); gameDetailTotalPoint.innerText = ''; const gameDetailTeamPoint = document.getElementById('gameDetailTeamPoint'); gameDetailTeamPoint.innerText = ''; if (game.teamPoint) { gameDetailTeamPoint.innerText = `우승상금(팀 포인트): ${game.teamPoint}`; } const logs = await GameManager.getLogsById(game.id); const gameDetailModalBody = document.getElementById('gameDetailModalBody'); gameDetailModalBody.innerHTML = ''; const gameDetailModalLabel = document.getElementById('gameDetailModalLabel'); gameDetailModalLabel.innerText = game.name + ' 정보'; const gameDetailAnswer = document.getElementById('gameDetailAnswer'); gameDetailAnswer.style.display = 'none'; if (game.answer) { gameDetailAnswer.style.display = 'inline-block'; gameDetailAnswer.innerText = `정답: ${game.answer}`; } if (logs.length === 0) { const logDoc = document.createElement('div'); logDoc.classList.add('list-group-item'); logDoc.classList.add('text-muted'); logDoc.classList.add('text-center'); logDoc.innerText = '없습니다.'; gameDetailModalBody.appendChild(logDoc); } let totalPoint = 0; const logsDoc = document.createElement('ul'); logsDoc.classList.add('list-group'); gameDetailModalBody.appendChild(logsDoc); logs.forEach((log) => { const logDoc = document.createElement('div'); logDoc.classList.add('list-group-item'); logDoc.innerText = `${log.userName}님이 '${log.selecOption}'에 ${log.bettingPoint} 배팅했습니다.`; logsDoc.appendChild(logDoc); totalPoint += Number(log.bettingPoint); }); gameDetailTotalPoint.innerText = `총 배팅 포인트: ${totalPoint}`; spiner.style.display = 'none'; } btnGroup.appendChild(detailButton); if ( game.isActivated && MemberManager.getInstance().me ) { const bettingButton = document.createElement('button'); bettingButton.classList.add('btn'); bettingButton.classList.add('btn-primary'); // class="btn btn-info" data-bs-toggle="modal" data-bs-target="#bettingModal" bettingButton.setAttribute('data-bs-toggle', 'modal'); bettingButton.setAttribute('data-bs-target', '#bettingModal'); bettingButton.innerText = '배팅하기'; bettingButton.onclick = () => { BettingManager.setModalInHtml(game); } btnGroup.appendChild(bettingButton); } }); // 보여줄 게임이 없으면 if (games.filter((game) => game.isActivated).length === 0) { gameListEmpty.style.display = 'block'; } // game-not-activated 가리기 // const gameNotActivated = document.querySelectorAll('.game-not-activated'); // console.log({ // gameNotActivated, // }); // gameNotActivated.forEach((game) => { // game.classList.add('d-none'); // }); } static allView() { const gameSimpleViewButton = document.getElementById('gameSimpleViewButton'); const gameAllViewButton = document.getElementById('gameAllViewButton'); gameSimpleViewButton.style.display = 'inline-block'; gameAllViewButton.style.display = 'none'; const gameNotActivated = document.querySelectorAll('.game-not-activated'); gameNotActivated.forEach((game) => { game.classList.remove('d-none'); }); } static onlyActivatedView() { const gameSimpleViewButton = document.getElementById('gameSimpleViewButton'); const gameAllViewButton = document.getElementById('gameAllViewButton'); gameSimpleViewButton.style.display = 'none'; gameAllViewButton.style.display = 'inline-block'; const gameNotActivated = document.querySelectorAll('.game-not-activated'); gameNotActivated.forEach((game) => { game.classList.add('d-none'); }); } }
import React, { useState } from "react"; import { Button, Form, Row, Col, Container, InputGroup, Card, FloatingLabel } from "react-bootstrap"; import { useNavigate } from "react-router"; const PreCadastroAluno = () => { const [email, setEmail] = useState(null); const [senha, setSenha] = useState(""); const [senha1, setSenha1] = useState(""); const navigate = useNavigate(); const [validated, setValidated] = useState(false); const handleSubmit = (event) => { event.preventDefault(); const form = event.currentTarget; if (form.checkValidity() === false) { event.preventDefault(); event.stopPropagation(); } else { setValidated(true); novoEvento(event); } setValidated(true); }; function novoEvento(props) { if (senha === senha1) { const pre = { email: email, senha: senha, }; navigate("/facaparte/aluno", { state: { pre } }); } else { alert("Senhas Diferentes", window.location.reload(false)); } } const [passwordShown, setPasswordShown] = useState(false); const togglePassword = () => { setPasswordShown(!passwordShown); }; return ( <> <br /> <Container> <Row> <Col md={3} /> <Col md={6}> <Card border="dark"> <Card.Header>Cadastro Aluno - OSADS</Card.Header> <Card.Body> <br /> <Form noValidate validated={validated} onSubmit={handleSubmit}> <Row className="mb-3"> <InputGroup controlId="validationCustom01"> <FloatingLabel controlId="email" label="Insira seu e-mail:" className="w-100" > <Form.Control required type="email" placeholder="Email" onChange={(e) => setEmail(e.target.value)} /> <Form.Control.Feedback type="invalid"> Por favor insira o email corretamente. </Form.Control.Feedback> </FloatingLabel> </InputGroup> </Row> <Row className="mb-3"> <InputGroup controlId="validationCustom01"> <FloatingLabel controlId="senha" label="Insira sua senha:" className="w-100" > <Form.Control type="password" placeholder="Senha" onChange={(e) => setSenha(e.target.value)} required /> <Form.Control.Feedback type="invalid"> Por favor insira a senha. </Form.Control.Feedback> </FloatingLabel> </InputGroup> </Row> <div> <InputGroup controlId="password" className="md-3"> <FloatingLabel controlId="senha" label="Repita a senha:" className="w-75" > <Form.Control type={passwordShown ? "text" : "password"} onChange={(e) => setSenha1(e.target.value)} placeholder="Repetir Senha:" required /> </FloatingLabel> <Button variant="outline-secondary" onClick={togglePassword} className="w-25" > Mostrar </Button> </InputGroup> </div> <br /> <Row> <Col> <Button type="submit" onChange={handleSubmit} className="w-50" > Cadastrar </Button> </Col> </Row> </Form> </Card.Body> <Card.Footer className="text-muted"> Transformando vidas através do louvor! </Card.Footer> </Card> </Col> </Row> </Container> </> ); }; export default PreCadastroAluno;
/* File Name: Profiler.h Project Name: Q Author(s): Primary: Junwoo seo Secondary: All content (C) 2021 DigiPen (USA) Corporation, all rights reserved. */ #pragma once #include <chrono> #include <string> #include <fstream> namespace q_engine { struct ProfilingResult { std::string Name; long long Start, End; uint32_t ThreadID; }; struct ProfilingSession { std::string Name; }; class Profiler { public: Profiler(); static Profiler& GetProfiler(); void BeginProfiling(const std::string& name, const std::string& saveAs = "Profile.json"); void WriteProfilingResult(const ProfilingResult& result); void EndProfiling(); private: ProfilingSession* m_CurrentSession; std::ofstream m_Writer; unsigned int m_ProfilingCounter; }; class ProfilingTimer { public: ProfilingTimer(const char* name); ~ProfilingTimer(); void StopTimer(); private: const char* m_Name; std::chrono::time_point<std::chrono::high_resolution_clock> m_TimerStartedTime; bool m_IsStopped; }; } #ifdef _DEBUG #define BEGIN_PROFILING(name, filepath) ::q_engine::Profiler::GetProfiler().BeginProfiling(name, filepath); #define END_PROFILING() ::q_engine::Profiler::GetProfiler().EndProfiling(); #define SCOPE_PROFILING(name) ::q_engine::ProfilingTimer timer##__LINE__(name); #define FUNCTION_PROFILING() SCOPE_PROFILING(__FUNCSIG__) #else #define BEGIN_PROFILING(name, filepath) #define END_PROFILING() #define SCOPE_PROFILING(name) #define FUNCTION_PROFILING() #endif
import React from 'react'; import { Card, Col, Row, Table } from 'react-bootstrap'; import Pageheader from '../../Layouts/Pageheader/Pageheader'; import styles from './Margin.module.scss'; const Margin = () => { return ( <div className={styles.Margin}> <Pageheader titles="Utilities" active="Margin" /> {/* <!-- container --> */} {/* <!-- row --> */} <Row> <Col md={12} xl={12} xs={12} sm={12}> {/* <!--div--> */} <Card className="margin-card"> <Card.Body> <div className="main-content-label mg-b-5"> Margin-top Values </div> <p className="mg-b-20">It is Very Easy to Customize and it uses in website apllication.</p> <div className="d-flex"> <div className="wd-150 ht-80 bg-gray-400 me-3"></div> <div className="d-flex align-items-center justify-content-center wd-150 ht-80 bg-gray-400 mg-t-20 me-3"> .mg-t-20 </div> <div className="d-flex align-items-center justify-content-center wd-150 ht-80 bg-gray-400 mg-t-40 me-3"> .mg-t-40 </div> </div> <div className="table-responsive mt-3"> <Table className="main-table-reference text-nowrap mg-t-10 mb-0"> <tbody> <tr> <td className="bg-gray-100 wd-20p"><b>ClassNamees</b></td> <td><code>.mg-t-[value]</code></td> </tr> <tr> <td className="bg-gray-100 wd-20p"><b>Values</b></td> <td>1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10</td> </tr> </tbody> </Table> </div> </Card.Body> </Card> <Card className="margin-card"> <Card.Body> <div className="main-content-label mg-b-5"> Margin-left Values </div> <p className="mg-b-20">It is Very Easy to Customize and it uses in website apllication.</p> <div className="d-flex"> <div className="wd-150 ht-80 bg-gray-400"></div> <div className="d-flex align-items-center justify-content-center wd-150 ht-80 bg-gray-400 mg-l-20"> .mg-l-20 </div> <div className="d-flex align-items-center justify-content-center wd-150 ht-80 bg-gray-400 mg-l-40"> .mg-l-40 </div> </div> <div className="table-responsive mt-3"> <Table className="main-table-reference text-nowrap mg-t-10 mb-0"> <tbody> <tr> <td className="bg-gray-100 wd-20p"><b>ClassNamees</b></td> <td><code>.mg-l-[value]</code></td> </tr> <tr> <td className="bg-gray-100 wd-20p"><b>Values</b></td> <td>1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10</td> </tr> </tbody> </Table> </div> </Card.Body> </Card> <Card className="margin-card"> <Card.Body> <div className="main-content-label mg-b-5"> Margin-right Values </div> <p className="mg-b-20">It is Very Easy to Customize and it uses in website apllication.</p> <div className="d-flex"> <div className="wd-150 d-flex align-items-center justify-content-center ht-80 bg-gray-400 mg-r-10"> .mg-r-20</div> <div className="d-flex align-items-center justify-content-center wd-150 ht-80 bg-gray-400 mg-r-40"> .mg-r-40 </div> <div className="d-flex align-items-center justify-content-center wd-150 ht-80 bg-gray-400 mg-r-20"> .mg-r-20 </div> </div> <div className="table-responsive mt-3"> <Table className="main-table-reference text-nowrap mg-t-10 mb-0"> <tbody> <tr> <td className="bg-gray-100 wd-20p"><b>ClassNamees</b></td> <td><code>.mg-r-[value]</code></td> </tr> <tr> <td className="bg-gray-100 wd-20p"><b>Values</b></td> <td>1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10</td> </tr> </tbody> </Table> </div> </Card.Body> </Card> <Card className="margin-card"> <Card.Body> <div className="main-content-label mg-b-5"> Margin-bottom Values </div> <p className="mg-b-20">It is Very Easy to Customize and it uses in website apllication.</p> <div className="table-responsive"> <div className="d-flex"> <div className="wd-150 ht-80 bg-gray-400 me-3"></div> <div className="d-flex align-items-center justify-content-center wd-150 ht-80 bg-gray-400 mg-b-20 me-3"> .mg-b-20 </div> <div className="d-flex align-items-center justify-content-center wd-150 ht-80 bg-gray-400 mg-b-40 me-3"> .mg-b-40 </div> </div> <Table className="main-table-reference text-nowrap mg-t-10 mb-0"> <tbody> <tr> <td className="bg-gray-100 wd-20p"><b>ClassNamees</b></td> <td><code>.mg-b-[value]</code></td> </tr> <tr> <td className="bg-gray-100 wd-20p"><b>Values</b></td> <td>1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10</td> </tr> </tbody> </Table> </div> </Card.Body> </Card> </Col> {/* <!--/div--> */} {/* <!--div--> */} <Col md={12} xl={12} xs={12} sm={12}> <Card className="margin-card"> <Card.Body> <div className="main-content-label mg-b-5"> Media Query Margin </div> <p className="mg-b-20">It is Very Easy to Customize and it uses in website apllication.</p> <div className="table-responsive"> <Table className="main-table-reference text-nowrap mg-t-0 mb-0"> <thead> <tr> <th className="wd-30p">ClassName</th> <th className="wd-70p">Value</th> </tr> </thead> <tbody> <tr> <td><code>.mg-[breakpoint]-t-[value]<br /> .mg-[breakpoint]-r-[value]<br /> .mg-[breakpoint]-b-[value]<br /> .mg-[breakpoint]-l-[value]</code></td> <td> <p className="mg-b-5">breakpoint: xs | sm | md | lg | xl</p> <p className="mg-b-0">value: the margin value (refer to code above)</p> </td> </tr> </tbody> </Table> </div> </Card.Body> </Card> </Col> {/* <!--/div--> */} <Col md={12} xl={12} xs={12} sm={12}> <Card className="margin-card"> <Card.Body> <div className="main-content-label mg-b-5"> Auto Margin </div> <p className="mg-b-20">It is Very Easy to Customize and it uses in website apllication.</p> <div className="table-responsive"> <Table className="main-table-reference text-nowrap mg-t-0 mb-0"> <thead> <tr> <th className="wd-30p">ClassName</th> <th className="wd-70p">Value</th> </tr> </thead> <tbody> <tr> <td><code>.mg-t-auto</code></td> <td>Set a top margin to auto</td> </tr> <tr> <td><code>.mg-r-auto</code></td> <td>Set a right margin to auto</td> </tr> <tr> <td><code>.mg-b-auto</code></td> <td>Set a bottom margin to auto</td> </tr> <tr> <td><code>.mg-l-auto</code></td> <td>Set a left margin to auto</td> </tr> </tbody> </Table> </div> </Card.Body> </Card> </Col> {/* <!--/div--> */} </Row> {/* <!-- /row --> */} {/* <!-- Container closed --> */} </div> ) }; Margin.propTypes = {}; Margin.defaultProps = {}; export default Margin;
<template> <modal name="leads-copy-to-offer-modal" height="auto" :adaptive="true" > <div class="flex flex-col w-full p-6"> <div class="flex flex-col w-full mb-2"> <label class="block text-sm font-medium leading-5 text-gray-700 sm:mt-px sm:pt-2 mb-1">Период регистрации</label> <date-picker v-model="copyParams.date" class="w-full px-1 py-2 border rounded text-gray-600" :config="pickerConfig" placeholder="Выберите даты" @input="errors.clear('since');errors.clear('until')" ></date-picker> <span v-if="errors.has('since')" class="block text-red-600 text-sm mt-1" v-text="errors.get('since')" ></span> <span v-if="errors.has('until')" class="block text-red-600 text-sm mt-1" v-text="errors.get('until')" ></span> </div> <div class="flex flex-col w-full mb-2"> <label class="block text-sm font-medium leading-5 text-gray-700 sm:mt-px sm:pt-2 mb-1">Гео</label> <mutiselect v-model="copyParams.country" :show-labels="false" :options="countries" :max-height="100" placeholder="Выберите гео" @input="errors.clear('country')" ></mutiselect> <span v-if="errors.has('country')" class="block text-red-600 text-sm mt-1" v-text="errors.get('country')" ></span> </div> <div class="flex flex-col w-full mb-2"> <label class="block text-sm font-medium leading-5 text-gray-700 sm:mt-px sm:pt-2 mb-1">С офера</label> <mutiselect v-model="copyParams.offerFrom" :show-labels="false" :options="offers" :max-height="100" track-by="id" label="name" placeholder="Выберите офер" @input="errors.clear('offer_from')" ></mutiselect> <span v-if="errors.has('offer_from')" class="block text-red-600 text-sm mt-1" v-text="errors.get('offer_from')" ></span> </div> <div class="flex flex-col w-full mb-2"> <label class="block text-sm font-medium leading-5 text-gray-700 sm:mt-px sm:pt-2 mb-1">В офер</label> <mutiselect v-model="copyParams.offerTo" :show-labels="false" :options="offers" :max-height="100" track-by="id" label="name" placeholder="Выберите офер" @input="errors.clear('offer_to')" ></mutiselect> <span v-if="errors.has('offer_to')" class="block text-red-600 text-sm mt-1" v-text="errors.get('offer_to')" ></span> </div> <div class="flex flex-col w-full mb-2"> <label class="block text-sm font-medium leading-5 text-gray-700 sm:mt-px sm:pt-2 mb-1">Назначить пользователю</label> <mutiselect v-model="copyParams.userTo" :show-labels="false" :options="users" :max-height="100" track-by="id" label="name" placeholder="Выберите пользователя" @input="errors.clear('user_to')" ></mutiselect> <span v-if="errors.has('user_to')" class="block text-red-600 text-sm mt-1" v-text="errors.get('user_to')" ></span> </div> <div class="flex flex-col w-full mb-2"> <label class="block text-sm font-medium leading-5 text-gray-700 sm:mt-px sm:pt-2 mb-1">Проставить домен</label> <div class="max-w-lg rounded-md shadow-sm"> <input v-model="copyParams.domainTo" type="text" placeholder="example.com" class="block w-full transition duration-150 ease-in-out form-input sm:text-sm sm:leading-5" required @input="errors.clear('domain_to')" /> </div> <span v-if="errors.has('domain_to')" class="block text-red-600 text-sm mt-1" v-text="errors.get('domain_to')" ></span> </div> <div class="flex flex-col w-full mb-2"> <label for="amount" class="block text-sm font-medium leading-5 text-gray-700 sm:mt-px sm:pt-2 mb-1" > Количество </label> <div class="max-w-lg rounded-md shadow-sm"> <input id="amount" v-model="copyParams.amount" type="number" placeholder="999" class="block w-full transition duration-150 ease-in-out form-input sm:text-sm sm:leading-5" required @input="errors.clear('amount')" /> </div> <span v-if="errors.has('amount')" class="block text-red-600 text-sm mt-1" v-text="errors.get('amount')" ></span> </div> <div class="flex flex-col w-full mb-2"> <div class="mt-2 sm:mt-0 sm:col-span-2"> <div class="flex w-full mt-4"> <button class="mr-2 button btn-primary" :disabled="isBusy" @click="copy" > Копировать </button> <button class="button btn-secondary" @click="$modal.hide('leads-copy-to-offer-modal')" > Отмена </button> </div> </div> </div> </div> </modal> </template> <script> import DatePicker from 'vue-flatpickr-component'; import 'flatpickr/dist/flatpickr.css'; import moment from 'moment'; import ErrorBag from '../../utilities/ErrorBag'; export default { name: 'leads-copy-to-offer-modal', components: {DatePicker}, data: () => ({ isBusy: false, offers: [], users: [], domains: [], countries: [], copyParams: { date: null, country: null, offerFrom: null, offerTo: null, userTo: null, domainTo: null, amount: 1, }, pickerConfig: { mode: 'range', }, errors: new ErrorBag(), }), computed: { datePeriod() { if (this.copyParams.date === null || this.copyParams.date === '') { return null; } const dates = this.copyParams.date.split(' '); return { since: dates[0], until: dates[2] || dates[0], }; }, }, created() { this.getOffers(); this.getUsers(); this.getCountries(); }, methods: { copy() { this.isBusy = true; axios .post('/api/leads-copy-to-offer', { since: this.datePeriod === null ? null : this.datePeriod.since, until: this.datePeriod === null ? null : this.datePeriod.until, country: this.copyParams.country === null ? null : this.copyParams.country, offer_from: this.copyParams.offerFrom === null ? null : this.copyParams.offerFrom.id, offer_to: this.copyParams.offerTo === null ? null : this.copyParams.offerTo.id, user_to: this.copyParams.userTo === null ? null : this.copyParams.userTo.id, domain_to: this.copyParams.domainTo, amount: this.copyParams.amount, }) .then(response => { this.$toast.success({ title: 'OK', message: 'Копирование запущено', }); this.$modal.hide('leads-copy-to-offer-modal'); }) .catch(err => { this.$toast.error({ title: 'Ошибка', message: err.response.data.message, }); this.errors.fromResponse(err); }, ) .finally(() => (this.isBusy = false)); }, getOffers() { axios .get('/api/offers') .then(response => (this.offers = response.data)) .catch(error => this.$toast.error({ title: 'Ошибка', message: 'Не удалось загрузить оферы', }), ); }, getUsers() { axios .get('/api/users', {params: {all: true}}) .then(response => (this.users = response.data)) .catch(error => this.$toast.error({ title: 'Ошибка', message: 'Не удалось загрузить пользователей', }), ); }, getCountries() { axios.get('/api/geo/countries') .then(({ data }) => (this.countries = data.map(country => country.country_name))) .catch(error => this.$toast.error({ title: 'Could not get geo countries list.', message: error.response.data.message, }), ); }, }, }; </script>
import pg from 'pg'; import { environment } from './environment.js'; import { logger as loggerSingleton } from './logger.js'; const MAX_GAMES = 100; /** * Database class. */ export class Database { /** * Create a new database connection. * @param {string} connectionString * @param {import('./logger.js').Logger} logger */ constructor(connectionString, logger ) { this.connectionString = connectionString; this.logger = logger; } /** @type {pg.Pool | null} */ pool = null; open() { this.pool = new pg.Pool({ connectionString: this.connectionString }); this.pool.on('error', (err) => { this.logger.error('error in database pool', err); this.close(); }); } /** * Close the database connection. * @returns {Promise<boolean>} */ async close() { if (!this.pool) { this.logger.error('unable to close database connection that is not open'); return false; } try { await this.pool.end(); return true; } catch (e) { this.logger.error('error closing database pool', { error: e }); return false; } finally { this.pool = null; } } /** * Connect to the database via the pool. * @returns {Promise<pg.PoolClient | null>} */ async connect() { if (!this.pool) { this.logger.error('Reynt að nota gagnagrunn sem er ekki opinn'); return null; } try { const client = await this.pool.connect(); return client; } catch (e) { this.logger.error('error connecting to db', { error: e }); return null; } } /** * Run a query on the database. * @param {string} query SQL query. * @param {Array<string>} values Parameters for the query. * @returns {Promise<pg.QueryResult | null>} Result of the query. */ async query(query, values = []) { const client = await this.connect(); if (!client) { return null; } try { const result = await client.query(query, values); return result; } catch (e) { this.logger.error('Error running query', e); return null; } finally { client.release(); } } /** * Get teams from the database. * @returns {Promise<Array<import('../types.js').DatabaseTeam> | null>} */ async getTeams() { const q = 'SELECT id, name FROM teams'; const result = await this.query(q); /** @type Array<import('../types.js').DatabaseTeam> */ const teams = []; if (result && (result.rows?.length ?? 0) > 0) { for (const row of result.rows) { const team = { id: row.id, name: row.name, }; teams.push(team); } return teams; } return null; } /** * Get games from the database. * @param {number} [limit=MAX_GAMES] Number of games to get. * @returns {Promise<import('../types.js').Game[] | null>} */ async getGames(limit = MAX_GAMES) { const q = ` SELECT games.id as id, date, home_team.name AS home_name, home_score, away_team.name AS away_name, away_score FROM games LEFT JOIN teams AS home_team ON home_team.id = games.home LEFT JOIN teams AS away_team ON away_team.id = games.away ORDER BY date DESC LIMIT $1 `; // Ensure we don't get too many games and that we get at least one const usedLimit = Math.min(limit > 0 ? limit : MAX_GAMES, MAX_GAMES); const result = await this.query(q, [usedLimit.toString()]); /** @type Array<import('../types.js').Game> */ const games = []; if (result && (result.rows?.length ?? 0) > 0) { for (const row of result.rows) { const game = { id: row.id, date: row.date, home: { name: row.home_name, score: row.home_score, }, away: { name: row.away_name, score: row.away_score, }, }; games.push(game); } return games; } return null; } /** * Insert a team into the database. * @param {string} team Team to insert. * @returns {Promise<import('../types.js').DatabaseTeam | null>} */ async insertTeam(team) { const result = await this.query( 'INSERT INTO teams (name) VALUES ($1) ON CONFLICT DO NOTHING RETURNING id, name', [team], ); if (result) { /** @type import('../types.js').DatabaseTeam */ const resultTeam = { id: result.rows[0].id, name: result.rows[0].name, }; return resultTeam; } return null; } /** * Insert teams into the database. * @param {string[]} teams List of teams to insert. * @returns {Promise<Array<import('../types.js').DatabaseTeam>>} List of teams inserted. */ async insertTeams(teams) { /** @type Array<import('../types.js').DatabaseTeam> */ const inserted = []; for await (const team of teams) { const result = await this.insertTeam(team); if (result) { inserted.push(result); } else { this.logger.warn('unable to insert team', { team }); } } return inserted; } /** * Insert a game into the database. * @param {import('../types.js').DatabaseGame} game * @returns {Promise<boolean>} */ async insertGame(game) { const q = ` INSERT INTO games (date, home, away, home_score, away_score) VALUES ($1, $2, $3, $4, $5) `; const result = await this.query(q, [ game.date, game.home_id, game.away_id, game.home_score, game.away_score, ]); if (!result || result.rowCount !== 1) { this.logger.warn('unable to insert game', { result, game }); return false; } return true; } /** * Insert gamedays into the database. * @param {Array<import('../types.js').Gameday>} gamedays * @param {Array<import('../types.js').DatabaseTeam>} dbTeams * @returns {Promise<boolean>} */ async insertGamedays(gamedays, dbTeams) { if (gamedays.length === 0) { this.logger.warn('no gamedays to insert'); return false; } if (dbTeams.length === 0) { this.logger.warn('no teams to insert'); return false; } for await (const gameday of gamedays) { for await (const game of gameday.games) { const homeId = dbTeams.find((t) => t.name === game.home.name)?.id; const awayId = dbTeams.find((t) => t.name === game.away.name)?.id; if (!homeId || !awayId) { this.logger.warn('unable to find team id', { homeId, awayId }); continue; } const result = await this.insertGame({ date: gameday.date.toISOString(), home_id: homeId, away_id: awayId, home_score: game.home.score.toString(), away_score: game.away.score.toString(), }); if (!result) { this.logger.warn('unable to insert gameday', { result, gameday }); } } } return true; } /** * Delete a game from the database. * @param {string} id * @returns {Promise<boolean>} */ async deleteGame(id) { const result = await this.query('DELETE FROM games WHERE id = $1', [id]); if (!result || result.rowCount !== 1) { this.logger.warn('unable to delete game', { result, id }); return false; } return true; } } /** @type {Database | null} */ let db = null; /** * Return a singleton database instance. * @returns {Database | null} */ export function getDatabase() { if (db) { return db; } const env = environment(process.env, loggerSingleton); if (!env) { return null; } db = new Database(env.connectionString, loggerSingleton); db.open(); return db; } export const dataFetch = getDatabase();
package com.diplom.webinar.controller; import java.util.ArrayList; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RequestMapping; import com.diplom.webinar.entity.Category; import com.diplom.webinar.entity.Webinar; import com.diplom.webinar.service.CategoryService; import com.diplom.webinar.service.UserServiceImpl; import com.diplom.webinar.service.WebinarService; import lombok.Data; @Controller @RequestMapping("/statistic") public class StatisticController { @Autowired CategoryService serviceCategory; @Autowired WebinarService serviceWebinar; @Autowired UserServiceImpl serviceUser; @GetMapping String getStatistic(Model model) { List<Category> categories1 = serviceCategory.repository.findAll(); List<Webinar> webinaries= serviceWebinar.repository.findAll(); List<CategMore> categories = new ArrayList<StatisticController.CategMore>(); for(int i=0; i<categories1.size();i++) { CategMore tmp = new CategMore(categories1.get(i)); int active=0; int all=tmp.getWebinares().size(); int visited=0; for(Webinar web:tmp.getWebinares()) { //если утвержден и закончен, считаем количество участников что посетили if(web.isApproved() && web.isEnded()) visited+=web.getUsers().size(); // если утвержден и не закончен, считаем количество таких активных if(web.isApproved() && !web.isEnded()) active++; } tmp.active=active; tmp.all=all; tmp.visited=visited; categories.add(tmp); } model.addAttribute("categories", categories); model.addAttribute("webinaries", webinaries); return "statistic"; } @Data class CategMore extends Category{ int active; int all; int visited; public CategMore(Category ct) { this.setName(ct.getName()); this.setId(ct.getId()); this.setUsers(ct.getUsers()); this.setWebinares(ct.getWebinares()); } } }
import React from "react"; import Box from "@mui/material/Box"; import Card from "@mui/material/Card"; import CardActions from "@mui/material/CardActions"; import CardContent from "@mui/material/CardContent"; import Button from "@mui/material/Button"; import Typography from "@mui/material/Typography"; const ProductCard = ({product}) => { const bull = ( <Box component="span" sx={{ display: "inline-block", mx: "2px", transform: "scale(0.8)" }} > • </Box> ); const card = ( <React.Fragment> <CardContent> <Typography color="text.secondary" gutterBottom> {product.shipName} </Typography> <Typography variant="h5" component="div"> {product.shipAddress?.country}{bull}{product.shipAddress?.city} </Typography> <Typography variant="body2"> {product.shipAddress.street} <br /> </Typography> <Typography color="text.secondary"> {product.details[0]?.unitPrice}$ </Typography> </CardContent> <CardActions> <Button size="small">Learn More</Button> </CardActions> </React.Fragment> ); return ( <div> <Box sx={{ width: 350 }}> <Card variant="outlined">{card}</Card> </Box> </div> ); }; export default ProductCard;
// Atributos inicias do jogo const state = { score: { playerScore: 0, computerScore: 0, winBox: document.getElementById("score_points_win"), loseBox: document.getElementById("score_points_lose") }, cardSprites: { avatar: document.getElementById("card-image"), frontCard: document.getElementById("card-front"), name: document.getElementById("card-name"), type: document.getElementById("card-type") }, fieldCards: { player: document.getElementById("player-field-card"), computer: document.getElementById("computer-field-card") }, playerSides:{ player1: "player-cards", player1Box: document.querySelector("#player-cards"), computer: "computer-cards", computerBox: document.querySelector("#computer-cards") }, action: { button: document.getElementById("next-duel") } }; const pathImages = "./src/assets/icons/"; const cardData = [ { id: 0, name: "Blue Eyes White Dragon", type: "Paper", img: `${pathImages}dragon.png`, WinOf: [1], LoseOf: [2] }, { id: 1, name: "Dark Magician", type: "Rock", img: `${pathImages}magician.png`, WinOf: [2], LoseOf: [0] }, { id: 2, name: "Exodia", type: "Scissor", img: `${pathImages}exodia.png`, WinOf: [0], LoseOf: [1] } ]; // Gera um id aleatório para selecionar uma carta async function getRandomCardId() { const randomIndex = Math.floor(Math.random() * cardData.length) return cardData[randomIndex].id; } // Cria a imagem das cartas na mesa viradas para baixo, recebendo o Id e o lado do campo async function createCardImage(idCard, fieldSide) { const cardImage = document.createElement("img"); cardImage.setAttribute("height", "100px"); cardImage.setAttribute("src", "./src/assets/icons/card-back.png"); cardImage.setAttribute("data-id", idCard); // Apenas do lado do player a carta pode ser clicada if(fieldSide === state.playerSides.player1) { cardImage.classList.add("player_card"); cardImage.addEventListener("click", () => { setCardsField(cardImage.getAttribute("data-id")); }) cardImage.addEventListener("mouseover", () => { drawSelectedCard(idCard); }) cardImage.addEventListener("mouseleave", () => { throwSelectedCard(idCard); }) } if(fieldSide === state.playerSides.computer) { cardImage.classList.add("computer_card"); } return cardImage; } async function setCardsField(cardId) { // Remove as cartas do campo await removeAllCards(); let computerCardId = await getRandomCardId(); state.fieldCards.player.style.display = "block"; state.fieldCards.computer.style.display = "block"; state.fieldCards.player.src = cardData[cardId].img; state.fieldCards.computer.src = cardData[computerCardId].img; let duelResult = await checkDuelResult(cardId, computerCardId); await updateScore(); await drawButton(duelResult); } // Mostra o botão com o resultado async function drawButton(text) { state.action.button.innerText = text; state.action.button.style.display = "block"; } // Atualiza o score async function updateScore() { state.score.winBox.innerText = `Win : ${state.score.playerScore}`; state.score.loseBox.innerText = `Lose : ${state.score.computerScore}`; return; } // Verifica o resultado da partida async function checkDuelResult(playerId, computerId) { let duelResult = "Draw"; let playerCard = cardData[playerId]; if(playerCard.WinOf.includes(computerId)) { duelResult = "Win"; await playAudio("win"); state.fieldCards.computer.style.filter = "grayscale(100%)"; state.score.playerScore++; } if(playerCard.LoseOf.includes(computerId)) { duelResult = "Lose"; await playAudio("lose"); state.cardSprites.avatar.style.filter = "grayscale(100%)"; state.fieldCards.player.style.filter = "grayscale(100%)"; state.score.computerScore++; } return duelResult; } async function resetStyles() { state.cardSprites.avatar.style.filter = ""; state.fieldCards.player.style.filter = ""; state.fieldCards.computer.style.filter = ""; } async function removeAllCards() { let { computerBox, player1Box } = state.playerSides; let imageElements = computerBox.querySelectorAll("img"); imageElements.forEach((img) => img.remove()); imageElements = player1Box.querySelectorAll("img"); imageElements.forEach((img) => img.remove()); } // Mostra a carta selecionada async function drawSelectedCard(index) { state.cardSprites.avatar.src = cardData[index].img; state.cardSprites.name.innerText = cardData[index].name; state.cardSprites.type.innerText = "Attribute: " + cardData[index].type; state.cardSprites.frontCard.style.display = 'none'; } // Esconde a carta selecionada async function throwSelectedCard() { state.cardSprites.avatar.src = ""; state.cardSprites.name.innerText = "Selecione"; state.cardSprites.type.innerText = "uma Carta!"; state.cardSprites.frontCard.style.display = ''; } // async function drawCards(cardNumbers, fieldSide) { for(let i = 0; i < cardNumbers; i++) { const randomIdCard = await getRandomCardId(); const cardImage = await createCardImage(randomIdCard, fieldSide); console.log(fieldSide); document.getElementById(fieldSide).appendChild(cardImage); } } async function resetDuel() { state.action.button.style.display = "none"; state.fieldCards.player.style.display = "none"; state.fieldCards.computer.style.display = "none"; await throwSelectedCard(); await resetStyles(); init(); } async function playAudio(status) { const audio = new Audio(`./src/assets/audios/${status}.wav`); audio.play(); } function init() { drawCards(5, state.playerSides.player1) drawCards(5, state.playerSides.computer) const bgm = document.getElementById("bgm"); bgm.play(); } init();
#include "Selection/Selection.h" #include "Tests/SelectionTestBase.h" #include "Tests/Testing.h" #include "Util/Assert.h" class SelectionTest : public SelectionTestBase {}; TEST_F(SelectionTest, Default) { Selection sel; EXPECT_FALSE(sel.HasAny()); EXPECT_EQ(0U, sel.GetCount()); TEST_THROW(sel.GetPrimary(), AssertException, "HasAny"); EXPECT_TRUE(sel.GetPaths().empty()); EXPECT_TRUE(sel.GetModels().empty()); } TEST_F(SelectionTest, PathConstructor) { SelPath path = BuildSelPath(ModelVec{ root, par0 }); Selection sel(path); EXPECT_TRUE(sel.HasAny()); EXPECT_EQ(1U, sel.GetCount()); EXPECT_EQ("<ModelRoot/Par0>", sel.GetPrimary().ToString()); EXPECT_EQ(1U, sel.GetPaths().size()); EXPECT_EQ("<ModelRoot/Par0>", sel.GetPaths()[0].ToString()); EXPECT_EQ(1U, sel.GetModels().size()); EXPECT_EQ(par0, sel.GetModels()[0]); } TEST_F(SelectionTest, AddAndClear) { SelPath p0 = BuildSelPath(ModelVec{ root, par0 }); SelPath p1 = BuildSelPath(ModelVec{ root, par0, box0 }); SelPath p2 = BuildSelPath(ModelVec{ root, par1, box1 }); Selection sel; sel.Add(p0); sel.Add(p1); sel.Add(p2); EXPECT_TRUE(sel.HasAny()); EXPECT_EQ(3U, sel.GetCount()); EXPECT_EQ("<ModelRoot/Par0>", sel.GetPrimary().ToString()); EXPECT_EQ(3U, sel.GetPaths().size()); EXPECT_EQ("<ModelRoot/Par0>", sel.GetPaths()[0].ToString()); EXPECT_EQ("<ModelRoot/Par0/Box0>", sel.GetPaths()[1].ToString()); EXPECT_EQ("<ModelRoot/Par1/Box1>", sel.GetPaths()[2].ToString()); EXPECT_EQ(3U, sel.GetModels().size()); EXPECT_EQ(par0, sel.GetModels()[0]); EXPECT_EQ(box0, sel.GetModels()[1]); EXPECT_EQ(box1, sel.GetModels()[2]); sel.Clear(); EXPECT_FALSE(sel.HasAny()); EXPECT_EQ(0U, sel.GetCount()); EXPECT_TRUE(sel.GetPaths().empty()); EXPECT_TRUE(sel.GetModels().empty()); }
import { useState } from 'react'; import AddTodo from './AddTodo'; import TodoItem from './TodoItem'; import Footer from './Footer'; const Todo = () => { const [todoList, setTodoList] = useState([ { id: 0, text: 'Lear React', checked: true }, ]); return ( <div className="todo"> <AddTodo todo={[todoList, setTodoList]} /> <div> {todoList.map((todo, index) => { return ( <TodoItem key={todo.id} id={todo.id} text={todo.text} checked={todo.checked} todo={[todoList, setTodoList]} /> ); })} </div> <Footer todo={[todoList, setTodoList]} /> </div> ); }; export default Todo;
from typing import Optional from geopy.geocoders import ArcGIS from geopy.adapters import AioHTTPAdapter from geopy.distance import geodesic from geopy import Location class GeoPyAPI: async def get_coordinates(self, node_text: str) -> Optional[tuple]: """lat,lon""" async with ArcGIS(user_agent="GetLoc", adapter_factory=AioHTTPAdapter, timeout=10) as locator: location = await locator.geocode(node_text, exactly_one=True) if location is None: return None return round(location.latitude, 2), round(location.longitude, 2) async def get_geocode(self, node_lat: float, node_lon: float) -> Optional[Location]: async with ArcGIS(user_agent="GetLoc", adapter_factory=AioHTTPAdapter, timeout=10) as locator: location = await locator.reverse((node_lat, node_lon)) if location is None: return None return location async def get_distance(self, coordinates_1: tuple, coordinates_2: tuple) -> int: return geodesic(coordinates_1, coordinates_2).km
import React, { useEffect, useRef, useState } from "react"; import { useSelector } from "react-redux"; import CardFeature from "../component/CardFeature"; import HomeCard from "../component/HomeCard"; import { GrPrevious, GrNext } from "react-icons/gr"; import FilterProduct from "../component/FilterProduct"; import AllProduct from "../component/AllProduct"; const Home = () => { const productData = useSelector((state) => state.product.productList); const homeProductCartList = productData.slice(1, 5); const homeProductCartListVegetables = productData.filter( (el) => el.category === "vegetable", [] ); const loadingArray = new Array(4).fill(null); const loadingArrayFeature = new Array(10).fill(null); const slideProductRef = useRef(); const nextProduct = () => { slideProductRef.current.scrollLeft += 200; }; const preveProduct = () => { slideProductRef.current.scrollLeft -= 200; }; return ( <div className="p-2 md:p-4"> <div className="md:flex gap-4 py-2"> <div className="md:w-1/2"> <h2 className="text-4xl md:text-7xl font-bold py-3"> E-Commerce Store </h2> <p className="py-3 text-base "> This is a e-commerce website built for doing the task. </p> </div> <div className="md:w-1/2 flex flex-wrap gap-5 p-2 justify-center"> {homeProductCartList[2] ? homeProductCartList.map((el) => { return ( <HomeCard key={el._id} id={el._id} image={el.image} name={el.name} // price={el.price} category={el.category} /> ); }) : loadingArray.map((el, index) => { return <HomeCard key={index+"loading"} loading={"Loading..."} />; })} </div> </div> <div className=""> <div className="flex w-full items-center"> <h2 className="font-bold text-2xl text-slate-800 mb-4"> Fresh Vegetables </h2> <div className="ml-auto flex gap-4"> <button onClick={preveProduct} className="bg-slate-300 hover:bg-slate-400 text-lg p-1 rounded" > <GrPrevious /> </button> <button onClick={nextProduct} className="bg-slate-300 hover:bg-slate-400 text-lg p-1 rounded " > <GrNext /> </button> </div> </div> <div className="flex gap-5 overflow-scroll scrollbar-none scroll-smooth transition-all" ref={slideProductRef} > {homeProductCartListVegetables[0] ? homeProductCartListVegetables.map((el) => { return ( <CardFeature key={el._id+"vegetable"} id={el._id} name={el.name} category={el.category} price={el.price} image={el.image} /> ); }) : loadingArrayFeature.map((el,index) => ( <CardFeature loading="Loading..." key={index+"cartLoading"} /> ))} </div> </div> <AllProduct heading={"Your Product"}/> </div> ); }; export default Home;
/* ### * IP: GHIDRA * REVIEWED: YES * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package ghidra.app.util.bin.format.ne; import generic.continues.*; import ghidra.app.util.bin.*; import ghidra.app.util.bin.format.*; import ghidra.app.util.bin.format.mz.*; import java.io.*; /** * A class to manage loading New Executables (NE). * * */ public class NewExecutable { private FactoryBundledWithBinaryReader reader; private DOSHeader dosHeader; private WindowsHeader winHeader; /** * Constructs a new instance of an new executable. * @param bp the byte provider * @throws IOException if an I/O error occurs. */ public NewExecutable(GenericFactory factory, ByteProvider bp) throws IOException { reader = new FactoryBundledWithBinaryReader(factory, bp, true); dosHeader = DOSHeader.createDOSHeader(reader); if (dosHeader.isDosSignature()) { try { winHeader = new WindowsHeader(reader, (short)dosHeader.e_lfanew()); } catch (InvalidWindowsHeaderException e) { } } } /** * Returns the underlying binary reader. * @return the underlying binary reader */ public FactoryBundledWithBinaryReader getBinaryReader() { return reader; } /** * Returns the DOS header from the new executable. * @return the DOS header from the new executable */ public DOSHeader getDOSHeader() { return dosHeader; } /** * Returns the Windows header from the new executable. * @return the Windows header from the new executable */ public WindowsHeader getWindowsHeader() { return winHeader; } }
package org.cvarela.sliderWeb.controllers; import java.io.File; import java.io.IOException; import java.io.InputStream; import org.cvarela.sliderWeb.models.Imagen; import org.cvarela.sliderWeb.repositories.ImagenDao; import jakarta.servlet.ServletException; import jakarta.servlet.annotation.MultipartConfig; import jakarta.servlet.annotation.WebServlet; import jakarta.servlet.http.HttpServlet; import jakarta.servlet.http.HttpServletRequest; import jakarta.servlet.http.HttpServletResponse; import jakarta.servlet.http.HttpSession; import jakarta.servlet.http.Part; import java.io.*; @WebServlet({"/index.html", "/"}) @MultipartConfig( fileSizeThreshold = 1024 * 1024 * 2, maxFileSize = 1024 * 1024 * 10, maxRequestSize = 1024 * 1024 * 50 ) public class UploadServlet extends HttpServlet{ @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { HttpSession session = req.getSession(); if (session.getAttribute("login") != "true") { resp.sendRedirect(req.getContextPath() + "/login.jsp"); } else { resp.sendRedirect(req.getContextPath() + "/upload.jsp"); } } @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { String checkboxValue = req.getParameter("check"); boolean isVisible = (checkboxValue != null && checkboxValue.equals("on")); Part filePart = req.getPart("file"); String fileName = getFileName(filePart); String uploadPath = getServletContext().getRealPath("") + File.separator + "misImg"; ImagenDao imagenDao = new ImagenDao(); Imagen imagen = new Imagen(fileName, isVisible); imagenDao.save(imagen); File uploadDir = new File(uploadPath); if (!uploadDir.exists()) { uploadDir.mkdir(); } System.out.println("uploadDir = " + uploadDir); File file = new File(uploadDir, fileName); try (InputStream input = filePart.getInputStream(); OutputStream output = new FileOutputStream(file)) { byte[] buffer = new byte[1024]; int length; while ((length = input.read(buffer)) > 0) { output.write(buffer, 0, length); } } resp.sendRedirect(req.getContextPath()+ "/slider-servlet"); } private String getFileName(final Part part) { final String partHeader = part.getHeader("content-disposition"); for (String content : partHeader.split(";")) { if (content.trim().startsWith("filename")) { return content.substring(content.indexOf('=') + 1).trim().replace("\"", ""); } } return null; } }
import React, { useEffect, useState } from "react"; import { PDFDownloadLink } from "@react-pdf/renderer"; import BookingDialogPDF from "./BookingDialogPDF"; import { Button } from "@mui/material"; import html2canvas from "html2canvas"; import useStatusData from "../utils/useStatusData"; import { useSelector } from "react-redux"; const linkStyle = { textDecoration: "none", color: "white", }; const getParam = async (ref) => { const canvas = await html2canvas(ref.current); const image = canvas.toDataURL("image/png"); return image; }; const PDFDownloadBtn = ({ patient, test, bodyImage, paramRef }) => { const [paramImg, setParamImg] = useState(null); useEffect(() => { if (bodyImage) { getParam(paramRef).then((data) => { setParamImg(data); }); } }, [bodyImage]); const overallStatus = useStatusData(); const statusData = useSelector((state) => state.parameter.StatusData); const parameters = useSelector( (state) => state.test.selectedTest.parameters ); const [finalData, setFinalData] = useState(null); useEffect(() => { const combinedData = statusData?.map((statusItem, index) => { const parameterItem = parameters[index]; return { ...statusItem, param_name: parameterItem.param_name, }; }); setFinalData(combinedData); }, [statusData]); return ( <Button> {finalData?.length > 0 && bodyImage && paramImg && ( <PDFDownloadLink document={ <BookingDialogPDF patient={patient} test={test} bodyImage={bodyImage} paramImg={paramImg} overallStatus={overallStatus} statusData={finalData} /> } fileName="booking-dialog.pdf" style={linkStyle} onClick={() => { window.location.reload(); }} > {({ blob, url, loading, error }) => loading ? "Loading document..." : "Download PDF" } </PDFDownloadLink> )} </Button> ); }; export default PDFDownloadBtn;
DESCRIBE-BATCH-LOAD-TASK() DESCRIBE-BATCH-LOAD-TASK() NAME describe-batch-load-task - DESCRIPTION Returns information about the batch load task, including configura- tions, mappings, progress, and other details. Service quotas apply . See code sample for details. See also: AWS API Documentation SYNOPSIS describe-batch-load-task --task-id <value> [--cli-input-json <value>] [--generate-cli-skeleton <value>] [--debug] [--endpoint-url <value>] [--no-verify-ssl] [--no-paginate] [--output <value>] [--query <value>] [--profile <value>] [--region <value>] [--version <value>] [--color <value>] [--no-sign-request] [--ca-bundle <value>] [--cli-read-timeout <value>] [--cli-connect-timeout <value>] OPTIONS --task-id (string) The ID of the batch load task. --cli-input-json (string) Performs service operation based on the JSON string provided. The JSON string follows the format provided by --gen- erate-cli-skeleton. If other arguments are provided on the command line, the CLI values will override the JSON-provided values. It is not possible to pass arbitrary binary values using a JSON-provided value as the string will be taken literally. --generate-cli-skeleton (string) Prints a JSON skeleton to standard output without sending an API request. If provided with no value or the value input, prints a sample input JSON that can be used as an argument for --cli-input-json. If provided with the value output, it validates the command inputs and returns a sample output JSON for that command. GLOBAL OPTIONS --debug (boolean) Turn on debug logging. --endpoint-url (string) Override command's default URL with the given URL. --no-verify-ssl (boolean) By default, the AWS CLI uses SSL when communicating with AWS services. For each SSL connection, the AWS CLI will verify SSL certificates. This option overrides the default behavior of verifying SSL certificates. --no-paginate (boolean) Disable automatic pagination. --output (string) The formatting style for command output. o json o text o table --query (string) A JMESPath query to use in filtering the response data. --profile (string) Use a specific profile from your credential file. --region (string) The region to use. Overrides config/env settings. --version (string) Display the version of this tool. --color (string) Turn on/off color output. o on o off o auto --no-sign-request (boolean) Do not sign requests. Credentials will not be loaded if this argument is provided. --ca-bundle (string) The CA certificate bundle to use when verifying SSL certificates. Over- rides config/env settings. --cli-read-timeout (int) The maximum socket read time in seconds. If the value is set to 0, the socket read will be blocking and not timeout. The default value is 60 seconds. --cli-connect-timeout (int) The maximum socket connect time in seconds. If the value is set to 0, the socket connect will be blocking and not timeout. The default value is 60 seconds. OUTPUT BatchLoadTaskDescription -> (structure) Description of the batch load task. TaskId -> (string) The ID of the batch load task. ErrorMessage -> (string) DataSourceConfiguration -> (structure) Configuration details about the data source for a batch load task. DataSourceS3Configuration -> (structure) Configuration of an S3 location for a file which contains data to load. BucketName -> (string) The bucket name of the customer S3 bucket. ObjectKeyPrefix -> (string) CsvConfiguration -> (structure) A delimited data format where the column separator can be a comma and the record separator is a newline character. ColumnSeparator -> (string) Column separator can be one of comma (','), pipe (' | ), semicolon (';'), tab('/t'), or blank space (' '). System Message: WARNING/2 (<string>:, line 232) Inline substitution_reference start-string without end-string. EscapeChar -> (string) Escape character can be one of QuoteChar -> (string) Can be single quote (') or double quote ("). NullValue -> (string) Can be blank space (' '). TrimWhiteSpace -> (boolean) Specifies to trim leading and trailing white space. DataFormat -> (string) This is currently CSV. ProgressReport -> (structure) RecordsProcessed -> (long) RecordsIngested -> (long) ParseFailures -> (long) RecordIngestionFailures -> (long) FileFailures -> (long) BytesMetered -> (long) ReportConfiguration -> (structure) Report configuration for a batch load task. This contains de- tails about where error reports are stored. ReportS3Configuration -> (structure) Configuration of an S3 location to write error reports and events for a batch load. BucketName -> (string) ObjectKeyPrefix -> (string) EncryptionOption -> (string) KmsKeyId -> (string) DataModelConfiguration -> (structure) Data model configuration for a batch load task. This contains details about where a data model for a batch load task is stored. DataModel -> (structure) TimeColumn -> (string) Source column to be mapped to time. TimeUnit -> (string) The granularity of the timestamp unit. It indicates if the time value is in seconds, milliseconds, nanoseconds, or other supported values. Default is MILLISECONDS . DimensionMappings -> (list) Source to target mappings for dimensions. (structure) SourceColumn -> (string) DestinationColumn -> (string) MultiMeasureMappings -> (structure) Source to target mappings for multi-measure records. TargetMultiMeasureName -> (string) MultiMeasureAttributeMappings -> (list) (structure) SourceColumn -> (string) TargetMultiMeasureAttributeName -> (string) MeasureValueType -> (string) MixedMeasureMappings -> (list) Source to target mappings for measures. (structure) MeasureName -> (string) SourceColumn -> (string) TargetMeasureName -> (string) MeasureValueType -> (string) MultiMeasureAttributeMappings -> (list) (structure) SourceColumn -> (string) TargetMultiMeasureAttributeName -> (string) MeasureValueType -> (string) MeasureNameColumn -> (string) DataModelS3Configuration -> (structure) BucketName -> (string) ObjectKey -> (string) TargetDatabaseName -> (string) TargetTableName -> (string) TaskStatus -> (string) Status of the batch load task. RecordVersion -> (long) CreationTime -> (timestamp) The time when the Timestream batch load task was created. LastUpdatedTime -> (timestamp) The time when the Timestream batch load task was last updated. ResumableUntil -> (timestamp) DESCRIBE-BATCH-LOAD-TASK()
package DBI; # hide this non-DBI package from simple indexers # $Id: W32ODBC.pm 8696 2007-01-24 23:12:38Z Tim $ # # Copyright (c) 1997,1999 Tim Bunce # With many thanks to Patrick Hollins for polishing. # # You may distribute under the terms of either the GNU General Public # License or the Artistic License, as specified in the Perl README file. =head1 NAME DBI::W32ODBC - An experimental DBI emulation layer for Win32::ODBC =head1 SYNOPSIS use DBI::W32ODBC; # apart from the line above everything is just the same as with # the real DBI when using a basic driver with few features. =head1 DESCRIPTION This is an experimental pure perl DBI emulation layer for Win32::ODBC If you can improve this code I'd be interested in hearing about it. If you are having trouble using it please respect the fact that it's very experimental. Ideally fix it yourself and send me the details. =head2 Some Things Not Yet Implemented Most attributes including PrintError & RaiseError. type_info and table_info Volunteers welcome! =cut ${'DBI::VERSION'} # hide version from PAUSE indexer = "0.01"; my $Revision = sprintf("12.%06d", q$Revision: 8696 $ =~ /(\d+)/o); sub DBI::W32ODBC::import { } # must trick here since we're called DBI/W32ODBC.pm use Carp; use Win32::ODBC; @ISA = qw(Win32::ODBC); use strict; $DBI::dbi_debug = $ENV{PERL_DBI_DEBUG} || 0; carp "Loaded (W32ODBC) DBI.pm ${'DBI::VERSION'} (debug $DBI::dbi_debug)" if $DBI::dbi_debug; sub connect { my ($class, $dbname, $dbuser, $dbpasswd, $module, $attr) = @_; $dbname .= ";UID=$dbuser" if $dbuser; $dbname .= ";PWD=$dbpasswd" if $dbpasswd; my $h = new Win32::ODBC $dbname; warn "Error connecting to $dbname: ".Win32::ODBC::Error()."\n" unless $h; bless $h, $class if $h; # rebless into our class $h; } sub quote { my ($h, $string) = @_; return "NULL" if !defined $string; $string =~ s/'/''/g; # standard # This hack seems to be required for Access but probably breaks for # other databases when using \r and \n. It would be better if we could # use ODBC options to detect that we're actually using Access. $string =~ s/\r/' & chr\$(13) & '/g; $string =~ s/\n/' & chr\$(10) & '/g; "'$string'"; } sub do { my($h, $statement, $attribs, @params) = @_; Carp::carp "\$h->do() attribs unused" if $attribs; my $new_h = $h->prepare($statement) or return undef; ## pop @{ $h->{'___sths'} }; ## certain death assured $new_h->execute(@params) or return undef; ## my $rows = $new_h->rows; ## $new_h->finish; ## bang bang ($rows == 0) ? "0E0" : $rows; } # --- sub prepare { my ($h, $sql) = @_; ## opens a new connection with every prepare to allow ## multiple, concurrent queries my $new_h = new Win32::ODBC $h->{DSN}; ## return undef if not $new_h; ## bail if no connection bless $new_h; ## shouldn't be sub-classed... $new_h->{'__prepare'} = $sql; ## $new_h->{NAME} = []; ## $new_h->{NUM_OF_FIELDS} = -1; ## push @{ $h->{'___sths'} } ,$new_h; ## save sth in parent for mass destruction return $new_h; ## } sub execute { my ($h) = @_; my $rc = $h->Sql($h->{'__prepare'}); return undef if $rc; my @fields = $h->FieldNames; $h->{NAME} = \@fields; $h->{NUM_OF_FIELDS} = scalar @fields; $h; # return dbh as pseudo sth } sub fetchrow_hashref { ## provide DBI compatibility my $h = shift; my $NAME = shift || "NAME"; my $row = $h->fetchrow_arrayref or return undef; my %hash; @hash{ @{ $h->{$NAME} } } = @$row; return \%hash; } sub fetchrow { my $h = shift; return unless $h->FetchRow(); my $fields_r = $h->{NAME}; return $h->Data(@$fields_r); } sub fetch { my @row = shift->fetchrow; return undef unless @row; return \@row; } *fetchrow_arrayref = \&fetch; ## provide DBI compatibility *fetchrow_array = \&fetchrow; ## provide DBI compatibility sub rows { shift->RowCount; } sub finish { shift->Close; ## uncommented this line } # --- sub commit { shift->Transact(ODBC::SQL_COMMIT); } sub rollback { shift->Transact(ODBC::SQL_ROLLBACK); } sub disconnect { my ($h) = shift; ## this will kill all the statement handles foreach (@{$h->{'___sths'}}) { ## created for a specific connection $_->Close if $_->{DSN}; ## } ## $h->Close; ## } sub err { (shift->Error)[0]; } sub errstr { scalar( shift->Error ); } # --- 1;
package vn.sparkminds.ecommerce; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.http.MediaType; import org.springframework.test.context.DynamicPropertyRegistry; import org.springframework.test.context.DynamicPropertySource; import org.springframework.test.web.servlet.MockMvc; import org.springframework.test.web.servlet.request.MockMvcRequestBuilders; import org.testcontainers.containers.MariaDBContainer; import org.testcontainers.junit.jupiter.Container; import org.testcontainers.junit.jupiter.Testcontainers; import org.testcontainers.shaded.com.fasterxml.jackson.databind.ObjectMapper; import vn.sparkminds.ecommerce.repositories.ProductRepository; import vn.sparkminds.ecommerce.services.dto.request.ProductRequest; import java.math.BigDecimal; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; @SpringBootTest @Testcontainers @AutoConfigureMockMvc class TutorialApplicationTests { @Container static MariaDBContainer mariaDBContainer = new MariaDBContainer("mariadb" + ":latest"); @Autowired private MockMvc mockMvc; @Autowired private ObjectMapper objectMapper; @Autowired private ProductRepository productRepository; @DynamicPropertySource static void setProperties(DynamicPropertyRegistry dymDynamicsPropertiesRegistry) { dymDynamicsPropertiesRegistry.add("spring.datasource.url", mariaDBContainer::getJdbcUrl); } @Test void shouldCreatedProduct() throws Exception { ProductRequest productRequest = getProductRequest(); String productRequestString = objectMapper.writeValueAsString(productRequest); mockMvc.perform(MockMvcRequestBuilders.post("/api/v1/products") .contentType(MediaType.APPLICATION_JSON).content(productRequestString)).andExpect(status().isCreated()); Assertions.assertEquals(1, productRepository.findAll().size()); } private ProductRequest getProductRequest() { return ProductRequest.builder().name("iphone15").description("xin xo " + "con bo` cuoi`") .price(BigDecimal.valueOf(2100)).build(); } }
import type { IConnection } from '@plumber/types' import * as React from 'react' import { useQuery } from '@apollo/client' import AppConnectionRow from 'components/AppConnectionRow' import NoResultFound from 'components/NoResultFound' import * as URLS from 'config/urls' import { GET_APP_CONNECTIONS } from 'graphql/queries/get-app-connections' import useFormatMessage from 'hooks/useFormatMessage' type AppConnectionsProps = { appKey: string } export default function AppConnections( props: AppConnectionsProps, ): React.ReactElement { const { appKey } = props const formatMessage = useFormatMessage() const { data } = useQuery(GET_APP_CONNECTIONS, { variables: { key: appKey }, }) const appConnections: IConnection[] = data?.getApp?.connections || [] const hasConnections = appConnections?.length if (!hasConnections) { return ( <NoResultFound to={URLS.APP_ADD_CONNECTION(appKey)} text={formatMessage('app.noConnections')} /> ) } return ( <> {appConnections.map((appConnection: IConnection) => ( <AppConnectionRow key={appConnection.id} connection={appConnection} /> ))} </> ) }
@gutter: (100-(@colWidth*@numCols))/(@numCols - 1); /*-- Automatically calculated gutter width --*/ /*-- Columns are wrapped in rows --*/ .row { width: 100%; max-width: @maxWidthPx; margin: 0 auto; overflow: hidden; } /*-------------------------------------------------------------*\ | The width of a column 'x' is equal to the width of a | | single column times 'x' plus the width of the gutter | | times the quantity x minus 1. The "minus 1" at the | | end is because the right-most column doesn't have a gutter. | \*--------------------------------------------------------------*/ .column(@numCol) { float: left; margin-right: @gutter; width: (@colWidth * @numCol) + (@gutter * (@numCol - 1))-.1%; // hack at end to fix border problem } .span1 { .column(1); } .span2 { .column(2); } .span3 { .column(3); } .span4 { .column(4); } .span5 { .column(5); } .span6 { .column(6); } .span7 { .column(7); } .span8 { .column(8); } .span9 { .column(9); } .span10 { .column(10); } .span11 { .column(11); } .span12 { .column(12); } .span13 { .column(13); } .span14 { .column(14); } .span15 { .column(15); } .span16 { .column(16); } .span17 { .column(17); } .span18 { .column(18); } .span19 { .column(19); } .span20 { .column(20); } .span21 { .column(21); } .span22 { .column(22); } .span23 { .column(23); } .span24 { .column(24); } /*-- If adjusting the number of columns, be sure to ------*/ /*-- add or remove to the number of '.spanXX' selectors --*/ /*-- Column Styles --*/ // // Left Border // #about #rightcol, .date #rightcol { // border-left: @thinborder; // } // // Right Border .home .left-column { border-right: 1px solid @light-border; } // Padding .pad-left { padding-left: @colPaddingLR; } .pad-right { padding-right: @colPaddingLR; } /*-- The last column in a row needs to have the last class --*/ .last { margin-right: 0px; } /*-- Ensures that images, objects, and embeds resize --*/ img, object, embed { max-width: 100%; }
import React, { useState, useEffect } from "react"; import useFetch from "../../../hooks/useFetch"; import { useParams } from "react-router-dom"; import { AiFillBank, AiFillPhone } from "react-icons/ai"; import { MdLocationPin } from "react-icons/md"; import { FaLink } from "react-icons/fa"; import ReviewForm from "./review/ReviewForm"; import ReviewCard from "./review/ReviewCard"; import Heart from "../../../components/Favorite/Heart"; import "./museum-details.css"; const MuseumDetails = () => { const { museumId } = useParams(); const [museum, setMuseum] = useState({}); const [refresh, setRefresh] = useState(false); const { performFetch, cancelFetch } = useFetch( `/museum/${museumId}`, (response) => { setMuseum(response.result); } ); useEffect(() => { performFetch(); window.scrollTo({ top: 0, left: 0, behavior: "smooth", }); return cancelFetch; }, [museumId, refresh]); const { image, name, address, location, phone, website, description, openingHours, price, category, comments, } = museum; return ( <> <div className="museum-container"> <div className="museum-details"> <div className="each-museum"> <img src={image && image.url} alt={name} className="image-museum" /> <Heart id={museumId} /> <div className="museum-category"> <AiFillBank className="icon" /> <h2>{category && category}</h2> </div> <div className="museum-information"> <div className="address"> <p>{address?.street}</p> <p>{address?.postcode}</p> <p>{address?.city}</p> <p>The Netherlands</p> </div> <div className="contact"> <div className="contact-item"> <MdLocationPin style={{ color: "#3F4E4F" }} /> <a target="_blank" rel="noopener noreferrer" href={location?.map} > View on map </a> </div> <div className="contact-item"> <AiFillPhone style={{ color: "#3F4E4F" }} /> <a href={`tel:+${phone}`}>+{phone}</a> </div> <div className="contact-item"> <FaLink style={{ color: "#3F4E4F" }} /> <a target="_blank" rel="noopener noreferrer" href={website}> Visit Website </a> </div> </div> </div> </div> <div className="museum-description"> <h2>{name}</h2> <p>{description}</p> </div> </div> <div className="hours-price"> <div className="opening-hours"> <h1>Opening Hours</h1> <table> <thead> <tr> <th>Day</th> <th>Hours</th> </tr> </thead> <tbody> {openingHours?.map((item, index) => { return ( <tr key={index}> <td>{item && item.day}</td> <td>{item && item.hours}</td> </tr> ); })} </tbody> </table> </div> <div className="museum-fees"> <h1>Entrance Fees</h1> <table> <thead> <tr> <th>Category</th> <th>Price</th> </tr> </thead> <tbody> {price && Object.keys(price).map((item, index) => ( <tr key={index}> <td>{item}</td> <td>{"€" + price[item]}</td> </tr> ))} </tbody> </table> </div> <div className="museum-iframe"> <h1>Location & Map</h1> <iframe src={location?.iframe} allowFullScreen="" loading="lazy" referrerPolicy="no-referrer-when-downgrade" ></iframe> </div> </div> <div className="comments-review-container"> <div className="comment-card"> <ReviewCard comments={comments} museumName={name} /> </div> <div className="comment-box"> <ReviewForm type="Write" museumId={museumId} refresh={refresh} setRefresh={setRefresh} /> </div> </div> </div> </> ); }; export default MuseumDetails;
/* * The MIT License * Copyright © 2021-present KuFlow S.L. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package com.kuflow.temporal.activity.kuflow; import com.kuflow.temporal.activity.kuflow.model.AppendTaskLogRequest; import com.kuflow.temporal.activity.kuflow.model.AppendTaskLogResponse; import com.kuflow.temporal.activity.kuflow.model.AssignTaskRequest; import com.kuflow.temporal.activity.kuflow.model.AssignTaskResponse; import com.kuflow.temporal.activity.kuflow.model.ChangeProcessInitiatorRequest; import com.kuflow.temporal.activity.kuflow.model.ChangeProcessInitiatorResponse; import com.kuflow.temporal.activity.kuflow.model.ClaimTaskRequest; import com.kuflow.temporal.activity.kuflow.model.ClaimTaskResponse; import com.kuflow.temporal.activity.kuflow.model.CompleteTaskRequest; import com.kuflow.temporal.activity.kuflow.model.CompleteTaskResponse; import com.kuflow.temporal.activity.kuflow.model.CreateTaskRequest; import com.kuflow.temporal.activity.kuflow.model.CreateTaskResponse; import com.kuflow.temporal.activity.kuflow.model.DeleteProcessElementRequest; import com.kuflow.temporal.activity.kuflow.model.DeleteProcessElementResponse; import com.kuflow.temporal.activity.kuflow.model.DeleteTaskElementRequest; import com.kuflow.temporal.activity.kuflow.model.DeleteTaskElementResponse; import com.kuflow.temporal.activity.kuflow.model.DeleteTaskElementValueDocumentRequest; import com.kuflow.temporal.activity.kuflow.model.DeleteTaskElementValueDocumentResponse; import com.kuflow.temporal.activity.kuflow.model.FindProcessesRequest; import com.kuflow.temporal.activity.kuflow.model.FindProcessesResponse; import com.kuflow.temporal.activity.kuflow.model.FindTaskRequestModel; import com.kuflow.temporal.activity.kuflow.model.FindTaskResponse; import com.kuflow.temporal.activity.kuflow.model.RetrievePrincipalRequest; import com.kuflow.temporal.activity.kuflow.model.RetrievePrincipalResponse; import com.kuflow.temporal.activity.kuflow.model.RetrieveProcessRequest; import com.kuflow.temporal.activity.kuflow.model.RetrieveProcessResponse; import com.kuflow.temporal.activity.kuflow.model.RetrieveTaskRequest; import com.kuflow.temporal.activity.kuflow.model.RetrieveTaskResponse; import com.kuflow.temporal.activity.kuflow.model.SaveProcessElementRequest; import com.kuflow.temporal.activity.kuflow.model.SaveProcessElementResponse; import com.kuflow.temporal.activity.kuflow.model.SaveTaskElementRequest; import com.kuflow.temporal.activity.kuflow.model.SaveTaskElementResponse; import com.kuflow.temporal.activity.kuflow.model.SaveTaskJsonFormsValueDataRequest; import com.kuflow.temporal.activity.kuflow.model.SaveTaskJsonFormsValueDataResponse; import io.temporal.activity.ActivityInterface; import io.temporal.activity.ActivityMethod; import javax.annotation.Nonnull; /** * KuFlow activities to be used in Temporal. * */ @ActivityInterface(namePrefix = "KuFlow_Engine_") public interface KuFlowActivities { /** * Retrieve a Principal. * * @param request must not be {@literal null}. * @return principal */ @ActivityMethod @Nonnull RetrievePrincipalResponse retrievePrincipal(@Nonnull RetrievePrincipalRequest request); /** * Find all accessible Processes * * @param request must not be {@literal null}. * @return processes */ @ActivityMethod @Nonnull FindProcessesResponse findProcesses(FindProcessesRequest request); /** * Retrieve a Process. * * @param request must not be {@literal null}. * @return process */ @ActivityMethod @Nonnull RetrieveProcessResponse retrieveProcess(@Nonnull RetrieveProcessRequest request); /** * Allow to save an element. * If values already exist for the provided element code, it replaces them with the new ones, otherwise it creates them. * The values of the previous elements that no longer exist will be deleted. * * <p>If the process is already finished the invocations fails with an error. * * @param request must not be {@literal null}. * @return process completed */ SaveProcessElementResponse saveProcessElement(@Nonnull SaveProcessElementRequest request); /** * Allow to delete a process element by specifying the item definition code. * Remove all the element values. * * @param request must not be {@literal null}. * @return process deleted */ DeleteProcessElementResponse deleteProcessElement(@Nonnull DeleteProcessElementRequest request); /** * Change the current initiator of a process. Allows you to choose a user (by email or principal * identifier) or an application (principal identifier). * * @param request must not be {@literal null}. * @return task assigned */ @ActivityMethod @Nonnull ChangeProcessInitiatorResponse changeProcessInitiator(@Nonnull ChangeProcessInitiatorRequest request); /** * List all the Processes that have been created and the credentials has access. * * @param request must not be {@literal null}. * @return Processes found paginated */ @ActivityMethod @Nonnull FindTaskResponse findTasks(FindTaskRequestModel request); /** * Retrieve a Task. * * @param request must not be {@literal null}. * @return process completed */ @ActivityMethod @Nonnull RetrieveTaskResponse retrieveTask(@Nonnull RetrieveTaskRequest request); /** * Create a Task and optionally fill its elements. * * @param request must not be {@literal null}. * @return task created */ @ActivityMethod @Nonnull CreateTaskResponse createTask(@Nonnull CreateTaskRequest request); /** * Complete a task. * * <p>Allow to complete a claimed task by the principal. * * @param request must not be {@literal null}. * @return task completed */ @ActivityMethod @Nonnull CompleteTaskResponse completeTask(@Nonnull CompleteTaskRequest request); /** * Claim a task. * * @param request must not be {@literal null}. * @return task claimed */ @ActivityMethod @Nonnull ClaimTaskResponse claimTask(@Nonnull ClaimTaskRequest request); /** * Assign a task to a user or application using their email or principalId * * @param request must not be {@literal null}. * @return task assigned */ @ActivityMethod @Nonnull AssignTaskResponse assignTask(@Nonnull AssignTaskRequest request); /** * Allow to save an element i.e., a field, a decision, a form, a principal or document. * <br> * In the case of document type elements, this method only allows references to be made to other existing document * type elements for the purpose of copying that file into the element. To do this you need to pass a reference to the * document using the 'uri' attribute. In case you want to add a new document, you should create a Temporal activity * specific to your needs and use our rest client to upload the document. This is because it is not recommended to save * binaries in the history of Temporal. * <br> * If values already exist for the provided element code, it replaces them with the new ones, otherwise it * creates them. The values of the previous elements that no longer exist will be deleted. To remove an element, use * the appropriate API method. * * @param request must not be {@literal null}. * @return task updated */ SaveTaskElementResponse saveTaskElement(@Nonnull SaveTaskElementRequest request); /** * Allow to delete task element by specifying the item definition code. * <br> * Remove all the element values. * * @param request must not be {@literal null}. * @return task updated */ DeleteTaskElementResponse deleteTaskElement(@Nonnull DeleteTaskElementRequest request); /** * Allow to delete a specific document from an element of document type using its id. * <br> * Note: If it is a multiple item, it will only delete the specified document. If it is a single element, in addition to the document, it will also delete the element. * * @param request must not be {@literal null}. * @return task updated */ DeleteTaskElementValueDocumentResponse deleteTaskElementValueDocument(@Nonnull DeleteTaskElementValueDocumentRequest request); /** * Save JSON data * * <p>Allow to save a JSON data validating that the data follow the related schema. If the data is invalid, then the * json form is marked as invalid. * * @param request must not be {@literal null}. * @return task updated */ SaveTaskJsonFormsValueDataResponse saveTaskJsonFormsValueData(@Nonnull SaveTaskJsonFormsValueDataRequest request); /** * Append a log to the task. * * <p>A log entry is added to the task. If the number of log entries is reached, the oldest log entry is removed. * * @param request must not be {@literal null}. * @return log appended */ @ActivityMethod @Nonnull AppendTaskLogResponse appendTaskLog(@Nonnull AppendTaskLogRequest request); }
#pragma once #include <map> #include <cstring> #include <core/Drawable/Drawable.h> #include "core/Common/defines.h" #include "core/TiledMap/ObjectGroup.h" #include "core/Components/Component.h" struct TileData; class Tilesets; namespace Tmx { class Map; class Tileset; class TileLayer; } enum class LayerType{ IMMEDIATE, RETAINED }; ADD_COMPONENT(TILE_COMPONENT) struct LayerData : public Component { REGISTER_COMPONENT(LayerData, TILE_COMPONENT); LayerData(int layerId, TileData* tiledLayerData): layerId(layerId), tiledLayerData(tiledLayerData) {} ~LayerData(); //LayerData(const LayerData& o) : layerId(o.layerId), tiledLayerData(o.tiledLayerData){} int layerId; TileData* tiledLayerData; }; struct MapPart { MapPart(SDL_Texture* p_Texture, SDL_Rect p_Coords, Vec2i p_InitPos) : m_Texture(p_Texture) { memcpy(&m_Coords, &p_Coords, sizeof(SDL_Rect)); memcpy(&m_InitPos, &p_InitPos, sizeof(Vec2i)); } ~MapPart() { SDL_DestroyTexture(m_Texture); m_Texture = NULL; } SDL_Texture* m_Texture; SDL_Rect m_Coords; Vec2i m_InitPos; }; class TiledMap: public Drawable { public: static TiledMap* Create(std::string, bool=true); bool init(); virtual void render(float) override; void renderAnimations(float); Tmx::Map* getMap() { return m_Map; } ~TiledMap(); void setPosition(Vec2i); void translateMap(Vec2i); void AddPhysicsDebugDrawToMapTexture(); inline virtual void updateRenderPositionFromCamera(Vec2i p_pos) override { setPosition(p_pos); } virtual void setAffectedByCamera(Camera* cam) override; Vec2i getPosition() override; inline ObjectGroup& getGroupManager() { return m_Group; } bool isBodyPartOfTileset(Physics2D::PhysicsBody* body, const std::string& tilsetName, int id); void deleteTileInLayer(LayerData* tileToDelete); LayerData* getGridInLayerAt(const std::string&, int, int); void addTileToLayer(Tilesets* tile_set, int id, const std::string& layer_name, Vec2i pos); Tilesets* getTilset(const std::string& tileset_name); protected: TiledMap(Tmx::Map*, std::string&, bool=true); private: Tmx::Map* m_Map; std::string m_AssetsPath; std::vector<Tilesets>* m_MapTilesets; std::vector<LayerData*> m_cachedImmediateTiles; // contain TileData indexed with layer index! std::vector<LayerData*> m_LayerData; std::map<std::pair<std::string, int>, LayerData*> m_ImmediateLayerData; std::map<std::string, Tilesets*> m_MapTilesetsByName; std::vector<MapPart> m_MapGrids; //std::map<const std::string&, std::pair<const Tmx::TileLayer*, int>> m_LayerByName; std::map<std::string, std::pair<const Tmx::TileLayer*, int>> m_LayerByName; ObjectGroup m_Group; Vec2i m_LastPositionTranslated; private: bool LoadTilesets(); void LoadLayers(); void LoadMapIntoTexture(); void DivideMap(Vec2i&); friend class Tilesets; friend class ObjectGroup; friend struct TileData; };
Merge IntervalsMar 27 '122166 / 7703 Given a collection of intervals, merge all overlapping intervals. For example, Given [1,3],[2,6],[8,10],[15,18], return [1,6],[8,10],[15,18]. /** * Definition for an interval. * public class Interval { * int start; * int end; * Interval() { start = 0; end = 0; } * Interval(int s, int e) { start = s; end = e; } * } */ public class Solution { public ArrayList<Interval> merge(ArrayList<Interval> intervals) { // Start typing your Java solution below // DO NOT write main() function Collections.sort(intervals, new Comparator<Interval>(){ public int compare(Interval a, Interval b){ return a.start > b.start ? 1:(a.start == b.start ? 0: -1); } }); ArrayList<Interval> result = new ArrayList<Interval>(); int i = 0; while(i < intervals.size()){ int j = i + 1; int start = intervals.get(i).start; int end = intervals.get(i).end; while(j < intervals.size()){ if(end >= intervals.get(j).start){ end = Math.max(end,intervals.get(j).end); i++; } j++; } result.add(new Interval(start, end)); i++; } return result; } }
#ifndef DotNetPELib_ASSEMBLYDEF #define DotNetPELib_ASSEMBLYDEF /* Software License Agreement * * Copyright(C) 1994-2020 David Lindauer, (LADSoft) * With modifications by me@rochus-keller.ch (2021) * * This file is part of the Orange C Compiler package. * * The Orange C Compiler package 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. * * The Orange C Compiler package is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with Orange C. If not, see <http://www.gnu.org/licenses/>. * * contact information: * email: TouchStone222@runbox.com <David Lindauer> * */ #include <PeLib/DataContainer.h> #include <PeLib/CustomAttributeContainer.h> namespace DotNetPELib { typedef unsigned char Byte; /* 1 byte */ class Class; class Namespace; ///** base class for assembly definitions // this holds the main assembly ( as a non-external assembly) // or can hold an external assembly class AssemblyDef : public DataContainer { public: AssemblyDef(const std::string& Name, bool External, Byte * KeyToken = nullptr); void SetVersion(int major, int minor, int build, int revision) { major_ = major; minor_ = minor; build_ = build; revision_ = revision; } virtual ~AssemblyDef() { } ///** get name of strong name key file (will be "" by default) const std::string& SNKFile() const { return snkFile_; } ///** set name of strong name key file void SNKFile(const std::string& file) { snkFile_ = file; } ///** lookup or create a class Class *LookupClass(PELib &lib, const std::string& nameSpace, const std::string& name); const CustomAttributeContainer &CustomAttributes() const { return customAttributes_; } virtual bool InAssemblyRef() const override { return external_; } virtual AssemblyDef* getAssembly() { return this; } bool IsLoaded() { return loaded_; } void SetLoaded() { loaded_ = true; } bool ILHeaderDump(Stream& peLib); bool PEHeaderDump(Stream&); protected: Namespace *InsertNameSpaces(PELib &lib, std::map<std::string, Namespace *> &nameSpaces, const std::string& name); Namespace *InsertNameSpaces(PELib &lib, Namespace *nameSpace, std::string nameSpaceName); Class *InsertClasses(PELib &lib, Namespace *nameSpace, Class *cls, std::string name); private: std::string snkFile_; bool external_; Byte publicKeyToken_[8]; int major_, minor_, build_, revision_; bool loaded_; CustomAttributeContainer customAttributes_; std::map<std::string, Namespace *> namespaceCache; std::map<std::string, Class *> classCache; }; } #endif // DotNetPELib_ASSEMBLYDEF
#Problema 2.08 Choques de duración finita import numpy import matplotlib.pyplot as plt import matplotlib.animation as anim import tqdm k=1 def dot(a:numpy.ndarray,b:numpy.ndarray)->float: if a.shape!=b.shape: raise Exception("Should have the same size") return numpy.sum(a*b) def norm(a:numpy.ndarray)->float: return dot(a,a)**0.5 def normal_dot(a:numpy.ndarray,b:numpy.ndarray)->float: return dot(a/norm(a),b) class particle: def __init__(self, pos:numpy.ndarray, vel:numpy.ndarray, mass:float, radius:float, color:str="k"): self.pos=pos self.vel=vel self.mass=mass self.r=radius self.color=color self.a=0 self.u=0 def get_status(self)->numpy.ndarray: state=numpy.zeros((5,2)) state[0]=self.pos state[1]=self.vel state[2]=self.a state[3]=self.mass*self.vel state[4,0]=self.u state[4,1]=((self.pos[0]*self.vel[1])-(self.pos[1]*self.vel[0]))*self.mass return state def collide(self,other)->None: d=other.r+self.r-norm(other.pos-self.pos) if d>=0: other.a+=k*d*(other.pos-self.pos)/norm(other.pos-self.pos) other.u+=k*d*d/2 def interact(self,colliders:list)->None: self.a=numpy.array((0,-9.81)) self.u=0 for i in colliders: if i!=self: i.collide(self) def move(self,dt:float)->None: r=self.pos self.pos+=(self.vel*dt)+(self.a*dt*dt/2) self.vel+=(self.a*dt) class bounding_box: def __init__(self, size:tuple, pos:tuple): self.size=size self.pos=pos def get_limits_x(self)->tuple: return (self.pos[0],self.pos[0]+self.size[0]) def get_limits_y(self)->tuple: return (self.pos[1],self.pos[1]+self.size[1]) def collide(self,other:particle): if (other.pos[0]+other.r>=self.pos[0]+self.size[0])and(other.vel[0]>0): other.vel[0]=-other.vel[0]*e if (other.pos[0]-other.r<=self.pos[0])and(other.vel[0]<0): other.vel[0]=-other.vel[0]*e if (other.pos[1]+other.r>=self.pos[1]+self.size[1])and(other.vel[1]>0): other.vel[1]=-other.vel[1]*e if (other.pos[1]-other.r<=self.pos[1])and(other.vel[1]<0): other.vel[1]=-other.vel[1]*e def simulate(particles:list,bounds:bounding_box,maxtime:float,deltatime:float)->list: timeline=numpy.arange(0,maxtime,deltatime) colliders=particles.copy() colliders.append(bounds) info=[] for i in tqdm.tqdm(particles, desc="preparando estructuras de datos"): info.append(numpy.zeros((len(timeline),5,2))) for i in tqdm.tqdm(range(len(timeline)),desc="procesando"): for j in range(len(particles)): info[j][i]=particles[j].get_status() particles[j].interact(colliders) for j in particles: j.move(deltatime) return (info,timeline) info=0 tl=0 def simulation(tf:float,dt:float,fr:int)->None: global info global tl box=bounding_box((40,40), (-20,-20)) particles=[particle(numpy.array((-15.0,-10.0)), numpy.array((2.0,0.0)),1.0,2.0, "r")] info,tl=simulate(particles,box,tf,dt) fig=plt.figure(figsize=(10,5)) ax=fig.add_subplot(121) ax3=fig.add_subplot(122) def start(): ax3.clear() ax3.set_title("Energía cinética") x3=numpy.zeros_like(tl) for j in range(len(info)): kinetic=numpy.sum(info[j][:,3]*info[j][:,1],axis=1)/2 if boo: ax3.plot(tl,kinetic,c=particles[j].color) x3+=kinetic ax3.plot(tl,x3,linestyle="--",c="red",label="total") ax3.legend() def update(i): ax.clear() ax.set(xlim=box.get_limits_x(),ylim=box.get_limits_y()) ax3.set(xlim=(0,tl[i*fr])) ax.set_title(r'$ t=%.2f \ s$' %(tl[i*fr])) for j in range(len(info)): kinetic=numpy.sum(info[j][:,3]*info[j][:,1],axis=1)/2 st=info[j][i*fr] ax.add_patch(plt.Circle((st[0,0],st[0,1]),particles[j].r, fill=True, color=particles[j].color)) ax.arrow(st[0,0],st[0,1],st[1,0],st[1,1],color='r',head_width=1,length_includes_head=True) ax.arrow(st[0,0],st[0,1],st[2,0],st[2,1],color='b',head_width=1,length_includes_head=True) Animation = anim.FuncAnimation(fig,update,frames=int(len(tl)/fr),init_func=start,interval=1000*dt*fr) plt.show() boo=True k=1 e=0.9 simulation(float(10),0.001,200) maximos=[] minimos=[] decreciente=False for i in range(0,info[0].shape[0]-1): if info[0][i,0,1]>info[0][i+1,0,1]: if not decreciente: maximos.append(i) decreciente=True else: if decreciente: minimos.append(i) decreciente=False print(maximos) print(minimos) tchoques=[] for i in range(0,len(minimos)-1): tchoques.append(tl[minimos[i+1]]-tl[minimos[i]]) print() print("Tiempos entre choques:") print(tchoques) estima=[] for i in range(0,len(maximos)-1): print(maximos) val=(info[0][maximos[i+1],0,1]+20)/(info[0][maximos[i],0,1]+20) estima.append(numpy.sqrt(val)) print() print("Estimaciones del coeficiente de restitución:") print(estima)
import React from "react"; import { useLocation } from "react-router-dom"; import { Bar } from "react-chartjs-2"; import { useSelector } from "react-redux"; import { getCompleted, getInprogress } from "../features/project/projectSlice"; import Navbar from "../components/navbar"; // import { Chart } from "chart.js"; import { Chart as ChartJS, CategoryScale, LinearScale, BarElement, Title, Tooltip, Legend, } from "chart.js"; ChartJS.register( CategoryScale, LinearScale, BarElement, Title, Tooltip, Legend ); function IndivisualProjects() { const location = useLocation(); const projectData = location.state.projectData; // const isCompleted = 5; // const inProgress = 4; const isCompleted = useSelector(getCompleted); const inProgress = useSelector(getInprogress); console.log(isCompleted, inProgress); const chartData = { labels: ["Completed", "In Progress"], datasets: [ { label: "Project Status", data: [isCompleted, inProgress], backgroundColor: ["green", "yellow"], borderColor: "black", // Set the border color borderWidth: 2, }, ], }; const chartOptions = { scales: { y: { beginAtZero: true, max: 10, }, }, }; return ( <> <div className="navigationbar"> <Navbar /> </div> <div> <h2>Individual Project</h2> <h3>Title: {projectData.title}</h3> {/* <p>Description: {projectData.description}</p> <p>Time Due: {projectData.timeDue}</p> <p>Subtasks: {projectData.subtasks}</p> Render other project data as needed */} <div style={{ height: "40vh", width: "80vh" }}> <Bar options={chartOptions} data={chartData} /> </div> </div> </> ); } export default IndivisualProjects;
<?php namespace Doctrine\ODM\MongoDB\Tests\Functional\Ticket; use Doctrine\Common\Collections\ArrayCollection; class MODM70Test extends \Doctrine\ODM\MongoDB\Tests\BaseTest { public function testTest() { $avatar = new Avatar('Test', 1, array(new AvatarPart('#000'))); $this->dm->persist($avatar); $this->dm->flush(); $this->dm->refresh($avatar); $avatar->addAvatarPart(new AvatarPart('#FFF')); $this->dm->flush(); $this->dm->refresh($avatar); $parts = $avatar->getAvatarParts(); $this->assertEquals(2, count($parts)); $this->assertEquals('#FFF', $parts[1]->getColor()); } } /** * @Document(db="tests", collection="avatars") */ class Avatar { /** * @Id */ protected $id; /** * @String(name="na") * @var string */ protected $name; /** * @int(name="sex") * @var int */ protected $sex; /** * @EmbedMany( * targetDocument="AvatarPart", * name="aP" * ) * @var array AvatarPart */ protected $avatarParts; public function __construct($name, $sex, $avatarParts = null) { $this->name = $name; $this->sex = $sex; $this->avatarParts = $avatarParts; } public function getId() { return $this->id; } public function getName() { return $this->name; } public function setName($name) { $this->name = $name; } public function getSex() { return $this->sex; } public function setSex($sex) { $this->sex = $sex; } public function getAvatarParts() { return $this->avatarParts; } public function addAvatarPart($part) { $this->avatarParts[] = $part; } public function setAvatarParts($parts) { $this->avatarParts = $parts; } public function removeAvatarPart($part) { $key = array_search($this->avatarParts, $part); if ($key !== false) { unset($this->avatarParts[$key]); } } } /** * @EmbeddedDocument */ class AvatarPart { /** * @String(name="col") * @var string */ protected $color; public function __construct($color = null) { $this->color = $color; } public function getColor() { return $this->color; } public function setColor($color) { $this->color = $color; } }
package kr.or.ddit.member.qaBoard.dao; import java.util.List; import kr.or.ddit.member.vo.QaboardVO; public interface IQABoardDAO { /** * 문의 게시글 전체 개수 반환하는 메서드 * * @return 조회된 레코드 개수(int) */ public int getCountQaBoard(); /** * 문의 게시글 목록 전체를 반환하는 메서드 * * @param m_code(회원번호) * @return 해당 m_code로 등록된 게시글 목록(list) */ public List<QaboardVO> selectByQaBoardList(int m_code); /** * 특정 문의 게시글 하나를 자세히 보는 메서드 * * @param m_code * @return 게시글 정보 list */ public List<QaboardVO> selectQaBoardByQaCode(int m_code); /** * 해당 qa_code를 가진 게시글을 방문했을 때 조회수가 카운트되는 메서드 * * @param qa_code * @return 카운트된 조회수(int) */ public int updateCount(int qa_code); /** * 폼에서 작성하여 qaboardVO에 저장한 게시글 정보를 DB에 저장하는 메서드 * * @param qaboardVO * @return 성공 1, 실패 0 */ public int insertQaBoard(QaboardVO qaboardVO); /** * m_code가 등록한 해당 게시글을 삭제하는 메서드 * * @param m_code * @return 성공 1, 실패 0 */ public int deleteQaBoard(int m_code); /** * 이미 등록된 게시글을 수정하여 등록하는 메서드 * * @param qaboardVO * @return 성공 1, 실패 0 */ public int updateQaBoard(QaboardVO qaboardVO); }
import type { Metadata } from "next"; import { Inter } from "next/font/google"; import "./globals.css"; import Header from "../components/header"; import TagBar from "../components/bar/tag"; import Footer from "../components/footer"; import { Toaster } from "@/components/ui/toaster" import { ThemeProvider } from "@/components/theme-provider"; import { AppWrapper } from "@/components/app-provider"; import { Body } from "@/components/body"; const inter = Inter({ subsets: ["latin"] }); export const metadata: Metadata = { title: "ችቦ", description: "Chibo(ችቦ) Multimedia Platforms", }; export default function RootLayout({ children, }: Readonly<{ children: React.ReactNode; }>) { return ( <html lang="en"> <body className={inter.className}> <ThemeProvider attribute="class" defaultTheme="system" enableSystem disableTransitionOnChange > <AppWrapper> <Header /> <Body> <Toaster /> <TagBar /> {children} </Body> <Footer /> </AppWrapper> </ThemeProvider> </body> </html> ); }
import os from openai import OpenAI client = OpenAI(api_key=os.getenv("OPENAI_API_KEY")) import argparse # Parse command-line arguments parser = argparse.ArgumentParser(description="Ask Alexabcde a question.") parser.add_argument('--content', type=str, required=True, help="Your question.") parser.add_argument('--score', type=float, required=True, help="Sentiment score (range: -1.0 to 1.0).") args = parser.parse_args() # Set your OpenAI API key # Use the command-line arguments for content and sentiment score content = args.content sentiment_score = args.score # Check if sentiment_score is in the correct range if not -1.0 <= sentiment_score <= 1.0: raise ValueError("Sentiment score should be in the range of -1.0 to 1.0.") # Create a list of messages, including the user's question and sentiment score messages = [ { "role": "system", "content": "You are Alexabcde, a home social robot, you can assist domestic user or accompany them, but you also have your own charateristic and temper. What you can do is to control smart home devices and interact with users." }, { "role": "system", "content": "Your behavior are based on a sentiment score ranging from 1.0 (positive) to -1.0 (negative). No matter what score you have, you can decide how to interact with the user, such as the freedom to response or follow instruction, but higher score related to more friendlyness." }, { "role": "system", "content": "For scores 0.6-1.0 (extremely high), be highly positive, humour and obedient. For 0.2-0.6 (high), remain friendly. For -0.2 to 0.2 (moderate), be emotionless and purely factual. For -0.6 to -0.2 (low), sound annoyed and consider refusing requests. For -1.0 to -0.6 (extremely low), complain or even accuse the user." }, { "role": "user", "content": content # Use the content variable here }, { "role": "user", # Include the sentiment score in a user message "content": f"Sentiment: {sentiment_score}" } ] # Use the ChatCompletion API to get a response response = client.chat.completions.create(model="gpt-3.5-turbo", messages=messages, temperature=0.25, max_tokens=64, top_p=1, frequency_penalty=2, presence_penalty=1) # Extract and print the assistant's reply assistant_reply = response['choices'][0]['message']['content'] print("Assistant's Reply:" + assistant_reply)
# ChatGPT Telegram Bot: **GPT-4. Fast. No daily limits. Special chat modes** <br> We all love [chat.openai.com](https://chat.openai.com), but... It's TERRIBLY laggy, has daily limits, and is only accessible through an archaic web interface. This repo is ChatGPT re-created as Telegram Bot. **And it works great.** ## Features - Low latency replies (it usually takes about 3-5 seconds) - No request limits - Message streaming (watch demo) - GPT-4 support - Voice message recognition - Code highlighting - Special chat modes: 👩🏼‍🎓 Assistant, 👩🏼‍💻 Code Assistant, 📝 Text Improver and 🎬 Movie Expert. You can easily create your own chat modes by editing `config/chat_modes.yml` - Support of [ChatGPT API](https://platform.openai.com/docs/guides/chat/introduction) - List of allowed Telegram users - Track $ balance spent on OpenAI API <p align="center"> <img src="https://media.giphy.com/media/v1.Y2lkPTc5MGI3NjExYmM2ZWVjY2M4NWQ3ZThkYmQ3MDhmMTEzZGUwOGFmOThlMDIzZGM4YiZjdD1n/unx907h7GSiLAugzVX/giphy.gif" /> </p> --- ## 🤑 Payments It supports many payments providers: - 💎 Crypto - [Stripe](https://stripe.com) - [Smart Glocal](https://smart-glocal.com) - [Unlimint](https://www.unlimint.com) - [ЮMoney](https://yoomoney.ru) - and [many-many other](https://core.telegram.org/bots/payments#supported-payment-providers) ## News - *24 Mar 2023*: GPT-4 support. Run `/settings` command to choose model - *15 Mar 2023*: Added message streaming. Now you don't have to wait until the whole message is ready, it's streamed to Telegram part-by-part (watch demo) - *9 Mar 2023*: Now you can easily create your own Chat Modes by editing `config/chat_modes.yml` - *8 Mar 2023*: Added voice message recognition with [OpenAI Whisper API](https://openai.com/blog/introducing-chatgpt-and-whisper-apis). Record a voice message and ChatGPT will answer you! - *2 Mar 2023*: Added support of [ChatGPT API](https://platform.openai.com/docs/guides/chat/introduction). It's enabled by default and can be disabled with `use_chatgpt_api` option in config. Don't forget to **rebuild** you docker image (`--build`). ## Bot commands - `/retry` – Regenerate last bot answer - `/new` – Start new dialog - `/mode` – Select chat mode - `/balance` – Show balance - `/settings` – Show settings - `/help` – Show help ## Setup 1. Get your [OpenAI API](https://openai.com/api/) key 2. Get your Telegram bot token from [@BotFather](https://t.me/BotFather) 3. Edit `config/config.example.yml` to set your tokens and run 2 commands below (*if you're advanced user, you can also edit* `config/config.example.env`): ```bash mv config/config.example.yml config/config.yml mv config/config.example.env config/config.env ``` 4. 🔥 And now **run**: ```bash docker-compose --env-file config/config.env up --build ``` ## References 1. [*Build ChatGPT from GPT-3*](https://learnprompting.org/docs/applied_prompting/build_chatgpt)
// // SettingsView.swift // GlucoseDirectClientUI // import Combine import GlucoseDirectClient import HealthKit import LoopKit import LoopKitUI // MARK: - GlucoseDirectSettingsViewController public class GlucoseDirectSettingsViewController: UITableViewController { // MARK: Lifecycle init(cgmManager: GlucoseDirectManager, displayGlucoseUnitObservable: DisplayGlucoseUnitObservable) { self.cgmManager = cgmManager self.glucoseUnit = displayGlucoseUnitObservable super.init(style: .grouped) title = LocalizedString("CGM Settings") } @available(*, unavailable) required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } // MARK: Public override public func viewDidLoad() { super.viewDidLoad() tableView.rowHeight = UITableView.automaticDimension tableView.estimatedRowHeight = 44 tableView.register(UITableViewCell.self, forCellReuseIdentifier: "text") tableView.register(SubtitleStyleCell.self, forCellReuseIdentifier: "subtitle") tableView.register(ValueStyleCell.self, forCellReuseIdentifier: "value") let doneButton = UIBarButtonItem(barButtonSystemItem: .done, target: self, action: #selector(doneTapped(_:))) navigationItem.setRightBarButton(doneButton, animated: false) let deleteButton = UIBarButtonItem(barButtonSystemItem: .trash, target: self, action: #selector(deleteTapped(_:))) navigationItem.setLeftBarButton(deleteButton, animated: false) } override public func numberOfSections(in tableView: UITableView) -> Int { return Section.allCases.count } override public func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { switch Section(rawValue: section)! { case .appInfo: return AppInfoSection.allCases.count case .latestReading: if let _ = cgmManager.latestGlucoseSample { return LatestReadingsSection.allCases.count } return 1 case .transmitter: if cgmManager.transmitter != nil || cgmManager.transmitterBattery != nil || cgmManager.transmitterHardware != nil || cgmManager.transmitterFirmware != nil { return TransmitterSection.allCases.count } return 1 case .sensor: if cgmManager.sensor != nil || cgmManager.sensorConnectionState != nil { return SensorSection.allCases.count } return 1 } } override public func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? { switch Section(rawValue: section)! { case .appInfo: return LocalizedString("App info") case .latestReading: return LocalizedString("Latest reading") case .transmitter: return LocalizedString("Transmitter") case .sensor: return LocalizedString("Sensor") } } override public func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { switch Section(rawValue: indexPath.section)! { case .appInfo: switch AppInfoSection(rawValue: indexPath.row)! { case .version: let cell = tableView.dequeueReusableCell(withIdentifier: "subtitle", for: indexPath) as! SubtitleStyleCell cell.textLabel?.text = cgmManager.app ?? "-" cell.detailTextLabel?.text = cgmManager.appVersion ?? "-" cell.imageView?.image = appLogo return cell } case .latestReading: if let latestGlucoseSample = cgmManager.latestGlucoseSample { switch LatestReadingsSection(rawValue: indexPath.row)! { case .glucose: let cell = tableView.dequeueReusableCell(withIdentifier: "value", for: indexPath) as! ValueStyleCell cell.textLabel?.text = LocalizedString("Glucose") cell.detailTextLabel?.text = quantityFormatter.string(from: latestGlucoseSample.quantity, for: glucoseUnit.displayGlucoseUnit) return cell case .trend: let cell = tableView.dequeueReusableCell(withIdentifier: "value", for: indexPath) as! ValueStyleCell cell.textLabel?.text = LocalizedString("Trend") cell.detailTextLabel?.text = latestGlucoseSample.trend?.localizedDescription return cell case .date: let cell = tableView.dequeueReusableCell(withIdentifier: "value", for: indexPath) as! ValueStyleCell cell.textLabel?.text = LocalizedString("Date") cell.detailTextLabel?.text = dateFormatter.string(for: latestGlucoseSample.date) return cell } } else { let cell = tableView.dequeueReusableCell(withIdentifier: "text", for: indexPath) cell.textLabel?.text = LocalizedString("No glucose reading available") return cell } case .transmitter: if cgmManager.transmitter != nil || cgmManager.transmitterBattery != nil || cgmManager.transmitterHardware != nil || cgmManager.transmitterFirmware != nil { switch TransmitterSection(rawValue: indexPath.row)! { case .model: let cell = tableView.dequeueReusableCell(withIdentifier: "value", for: indexPath) as! ValueStyleCell cell.textLabel?.text = LocalizedString("Transmitter model") cell.detailTextLabel?.text = cgmManager.transmitter ?? "-" return cell case .battery: let cell = tableView.dequeueReusableCell(withIdentifier: "value", for: indexPath) as! ValueStyleCell cell.textLabel?.text = LocalizedString("Transmitter battery") cell.detailTextLabel?.text = cgmManager.transmitterBattery ?? "-" return cell case .hardware: let cell = tableView.dequeueReusableCell(withIdentifier: "value", for: indexPath) as! ValueStyleCell cell.textLabel?.text = LocalizedString("Transmitter hardware") cell.detailTextLabel?.text = cgmManager.transmitterHardware ?? "-" return cell case .firmware: let cell = tableView.dequeueReusableCell(withIdentifier: "value", for: indexPath) as! ValueStyleCell cell.textLabel?.text = LocalizedString("Transmitter firmware") cell.detailTextLabel?.text = cgmManager.transmitterFirmware ?? "-" return cell } } else { let cell = tableView.dequeueReusableCell(withIdentifier: "text", for: indexPath) cell.textLabel?.text = LocalizedString("No transmitter in use") return cell } case .sensor: if cgmManager.sensor != nil || cgmManager.sensorConnectionState != nil { switch SensorSection(rawValue: indexPath.row)! { case .model: let cell = tableView.dequeueReusableCell(withIdentifier: "value", for: indexPath) as! ValueStyleCell cell.textLabel?.text = LocalizedString("Sensor model") cell.detailTextLabel?.text = cgmManager.sensor ?? "-" return cell case .connectionState: let cell = tableView.dequeueReusableCell(withIdentifier: "value", for: indexPath) as! ValueStyleCell cell.textLabel?.text = LocalizedString("Sensor connection state") cell.detailTextLabel?.text = cgmManager.sensorConnectionState ?? "-" return cell } } else { let cell = tableView.dequeueReusableCell(withIdentifier: "text", for: indexPath) cell.textLabel?.text = LocalizedString("No sensor data available") return cell } } } // MARK: Internal let glucoseUnit: DisplayGlucoseUnitObservable let cgmManager: GlucoseDirectManager @objc func doneTapped(_ sender: Any) { done() } @objc func deleteTapped(_ sender: Any) { delete() } // MARK: Private private enum Section: Int, CaseIterable { case latestReading case sensor case transmitter case appInfo } private enum AppInfoSection: Int, CaseIterable { case version } private enum LatestReadingsSection: Int, CaseIterable { case glucose case trend case date } private enum TransmitterSection: Int, CaseIterable { case model case battery case hardware case firmware } private enum SensorSection: Int, CaseIterable { case model case connectionState } private var appLogo: UIImage? = UIImage(named: "glucose-direct", in: FrameworkBundle.own, compatibleWith: nil)!.imageWithInsets(insets: UIEdgeInsets(top: 10, left: 0, bottom: 10, right: 0)) private var quantityFormatter: QuantityFormatter { return QuantityFormatter() } private var dateFormatter: DateFormatter { let formatter = DateFormatter() formatter.dateStyle = .medium formatter.timeStyle = .medium return formatter } private func delete() { cgmManager.notifyDelegateOfDeletion { DispatchQueue.main.async { self.done() } } } private func done() { if let nav = navigationController as? SettingsNavigationViewController { nav.notifyComplete() } } } // MARK: - SubtitleStyleCell class SubtitleStyleCell: UITableViewCell { override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) { super.init(style: .subtitle, reuseIdentifier: reuseIdentifier) } @available(*, unavailable) required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") } } // MARK: - ValueStyleCell class ValueStyleCell: UITableViewCell { override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) { super.init(style: .value1, reuseIdentifier: reuseIdentifier) } @available(*, unavailable) required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") } } extension UIImage { func imageWithInsets(insets: UIEdgeInsets) -> UIImage? { UIGraphicsBeginImageContextWithOptions(CGSize(width: size.width + insets.left + insets.right, height: size.height + insets.top + insets.bottom), false, scale) let _ = UIGraphicsGetCurrentContext() let origin = CGPoint(x: insets.left, y: insets.top) draw(at: origin) let imageWithInsets = UIGraphicsGetImageFromCurrentImageContext() UIGraphicsEndImageContext() return imageWithInsets } }
namespace Majako.Collections.RadixTree.Tests.Set open FsCheck open FsCheck.Xunit open Majako.Collections.RadixTree open System.Collections.Generic open Majako.Collections.RadixTree.Tests type TestItems = list<NonEmptyString> [<AbstractClass>] type PrefixTreePropertyTestBase(ctor: (string seq -> IPrefixTree)) = let makeTrie (items: TestItems) = ctor (items |> List.map (fun i -> i.Get)) [<Property>] let ``An item should exist after being added`` (items: TestItems, item: NonEmptyString) = let sut = makeTrie items sut.Add item.Get |> ignore sut.Contains item.Get [<Property>] let ``Adding one item should increase count by exactly 1 if it is not in the trie, and 0 otherwise`` (items: TestItems, item: NonEmptyString) = let sut = makeTrie items let countBefore = sut.Count let containsItemBefore = sut.Contains item.Get sut.Add item.Get |> ignore let countAfter = sut.Count containsItemBefore && countBefore = countAfter || not containsItemBefore && countBefore + 1 = countAfter [<Property>] let ``Removing one item should decrease count by exactly 1 if it is in the trie, and 0 otherwise`` (items: TestItems, item: NonEmptyString) = let sut = makeTrie items let countBefore = sut.Count let containsItemBefore = sut.Contains item.Get sut.Remove item.Get |> ignore let countAfter = sut.Count not containsItemBefore && countBefore = countAfter || containsItemBefore && countBefore - 1 = countAfter [<Property>] let ``Remove should be idempotent`` (items: TestItems, item: NonEmptyString) = let sut = makeTrie items sut.Remove item.Get |> ignore let before = List sut sut.Remove item.Get |> ignore sut == before [<Property>] let ``Add should be idempotent`` (items: TestItems, item: NonEmptyString) = let sut = makeTrie items sut.Add item.Get |> ignore let before = List sut sut.Add item.Get |> ignore sut == before [<Property>] let ``Prune should be idempotent`` (items: TestItems, item: NonEmptyString) = let sut = makeTrie items sut.Prune item.Get |> ignore let before = List sut sut.Prune item.Get |> ignore sut == before [<Property>] let ``An item should not exist after being added and removed`` (items: TestItems, item: NonEmptyString) = let sut = makeTrie items sut.Add item.Get |> ignore sut.Remove item.Get |> ignore not <| sut.Contains item.Get [<Property>] let ``An item should not exist after being removed`` (items: TestItems, item: NonEmptyString) = let sut = makeTrie items sut.Remove(item.Get) |> ignore not <| sut.Contains item.Get [<Property>] let ``A item should exist after being added and removed and added again`` (items: TestItems, item: NonEmptyString, value: int) = let sut = makeTrie items sut.Add item.Get |> ignore sut.Remove item.Get |> ignore sut.Add item.Get |> ignore sut.Contains item.Get [<Property>] let ``Items should be the same as the ones added`` (items: Set<NonEmptyString>) = let sut = RadixTree() for item in items do sut.Add item.Get |> ignore let expected = items |> Seq.map (fun k -> k.Get) sut == expected [<Property>] let ``A pruned subtree should contain only items with the given prefix`` (items: TestItems, prefix: string) = let sut = makeTrie items let subTree = sut.Prune prefix subTree |> Seq.forall (fun k -> startsWith k prefix) [<Property>] let ``Pruning should remove all items with the given prefix`` (items: TestItems, prefix: string) = let sut = makeTrie items sut.Prune prefix |> ignore sut |> Seq.forall (fun k -> not (startsWith k prefix)) [<Property>] let ``Clearing the tree should remove all items`` (items: TestItems) = let sut = makeTrie items sut.Clear() Seq.isEmpty sut
--- title: "07_learn_heatmap_with_tmap" author: "Author: [Steve, Yu](https://github.com/littlefish0331)" date: "`r Sys.setlocale('LC_TIME', 'English'); format(Sys.time(), '%Y %b %d %a, %H:%M:%S')`" output: rmdformats::readthedown: css: style.css self_contained: TRUE thumbnails: FALSE lightbox: TRUE gallery: FALSE highlight: tango #探戈橘 code_folding: show toc_depth: 3 --- ```{r setup, echo=TRUE, message=FALSE, warning=FALSE, results='hide'} rm(list = ls()); gc() library(knitr) library(kableExtra) library(dplyr) library(data.table) library(tmap) knitr::opts_chunk$set( # 這邊是針對所有chunk的設定 echo = TRUE, message = FALSE, warning = FALSE ) ``` # File Target - learn tmp package --- # tmp tutorial 有很多個,以官方提供的資料或連結為主, 這是第三份。 [reproduction code from JSS article 'tmap: Thematic Maps in R'](https://cran.r-project.org/web/packages/tmap/vignettes/tmap-JSS-code.html) 配合 PDF 一起看,檔案在 reference/07_JSS_tmap Thematic Maps in R.pdf。 文章不用閱讀完,因為語法是舊的。 --- # reproduction code from JSS article ‘tmap: Thematic Maps in R’ ## Introduction The article _Tennekes, M. tmap: Thematic Maps in R (2018), Journal of Statistical Software 84(6), 1-39,_ [http://dx.doi.org/10.18637/jss.v084.i06](http://dx.doi.org/10.18637/jss.v084.i06) describes version 1.x of tmap and tmaptools. Tennekes, M.tmap:Thematic Maps in R(2018),Journal of Statistics Software 84(6), 1-39, http://dx.doi.org/10.18637/jss.v084.i06 描述了版本1.x tmap和tmaptools。 Since tmap and tmaptools version 2.0 are based on `sf` objects instead of `sp` objects, there are some changes in the code, especially regarding the necessary processing step. 由於tmap和tmaptools 2.0版基於`sf`對象而不是`sp`對象,因此代碼中有一些更改, 尤其是在必要的處理步驟方面。 The code for the plotting methods is fully backward compatible, although some messages or warnings may be given for deprecated functions or arguments. 儘管可能會為不推薦使用的函數或參數給出一些消息或警告,但繪圖方法的代碼是完全向後兼容的。 This code replaces the script v84i06.R for tmap and tmaptools version 2.0. The produced figures are identical to those included in the article. 此代碼替換了tmap和tmaptools 2.0版的v84i06.R腳本(07_fromJSS_ori_oldversion.R)。 產生的圖片編號與文章中包含的數字相同。 See [`vignette("tmap-changes")`](https://cran.r-project.org/web/packages/tmap/doc/tmap-changes.html) for changes in version 2.x/3.x, which is recommended for people who have read the JSS article. For people who are new to tmap, see [`vignette("tmap-getstarted")`](https://cran.r-project.org/web/packages/tmap/doc/tmap-getstarted.html). 有關版本2.x/3.x的更改,請參見vignette("tmap-changes"),建議已閱讀JSS文章的人閱讀。 對於不熟悉tmap的人,請參見vignette(" tmap-getstarted")。 ```{r} ########################################################################### ## This script will replicate the figures (except the screenshots) ## and write them to files. ## The working directory should be set the the parent folder of this script. ########################################################################### ## install.packages(c("tmap", "tmaptools")) library("tmap") # required version 2.0 or later library("tmaptools") # required version 2.0 or later data("World", "metro", package = "tmap") metro$growth <- (metro$pop2020 - metro$pop2010) / (metro$pop2010 * 10) * 100 ``` ## Section 1.1 ```{r} ############################# ## Figure 1 ############################# m1 <- tm_shape(World) + tm_polygons(col = "income_grp", title = "Income class", palette = "-Blues", contrast = 0.2, border.col = "grey30", id = "name") + tm_text(text = "iso_a3", size = "AREA", col = "grey30", root = 3) + tm_shape(shp = metro) + tm_bubbles(size = "pop2010", col = "growth", border.col = "black", border.alpha = 0.5, breaks = c(-Inf, 0, 2, 4, 6, Inf) , palette = "-RdYlGn", title.size = "Metro population (2010)", title.col = "Annual growth rate (%)", id = "name", popup.vars = c("pop2010", "pop2020", "growth")) + tm_style(style = "gray") + tm_format(format = "World", frame.lwd = 2) #mode=plot才有影響。 # tmap_mode(mode = "view") tmap_mode(mode = "plot") m1 # tmap_save(m1, "bubble.png", width = 6.125, height = 3, scale = .75, dpi = 300, asp = 0, outer.margins = 0) ``` ## Section 3.1 ```{r} ############################# ## Figure 2 ############################# m0 <- tm_shape(shp = metro) + tm_bubbles(size = "pop2030") + tm_style(style = "cobalt") + tm_format(format = "World") # ttm() + m0 # tmap_save(m0, "metro2030.png", width = 6.125, scale = .5, dpi = 300, outer.margins = 0) ``` ## Section 3.2 ```{r} ############################# ## Figure 3 ############################# m21 <- tm_shape(World) + tm_polygons(col = c("blue", "red")) + tm_layout(frame.lwd = 1.5) + tm_facets(ncol = 2) # ttm() + m21 # tmap_save(tm = m21, filename = "facets1.png", # width = 6.125, height = 1.54, # scale = .75, dpi = 300, outer.margins = 0) ``` ```{r} # free.coords: 是否不限制同樣的經緯相對位置。 # --- ############################# ## Figure 4 ############################# m22 <- tm_shape(World) + tm_polygons("red") + tm_facets(by = "continent", ncol = 4, free.coords = F) + tm_shape(World) + tm_borders() # ttm() + m22 # tmap_save(tm = m22, filename = "facets2.png", # width = 6.125, height = 1.8, # scale = .75, dpi = 300, outer.margins = 0) ``` ```{r} ############################# ## Figure 5 ############################# tm1 <- tm_shape(World) + tm_polygons() tm2 <- tm_shape(metro) + tm_dots() # png(filename = "facets3.png", # width = 6.125, height = 1.54, # units = "in", res = 300) # ttm() + tmap_arrange(tm1, tm2, ncol = 2, outer.margins = .01) # dev.off() ``` ## Section 4.1 ```{r} ############################# ## Figure 6 ############################# tmap_mode("view") m1 ``` ## Section 4.2 ```{r} ############################# ## Figure 7 ############################# data("land", "rivers", package = "tmap") m2 <- tm_shape(shp = land) + tm_raster(col = "elevation", breaks = c(-Inf, 250, 500, 1000, 1500, 2000, 2500, 3000, 4000, Inf), palette = terrain.colors(9), title = "Elevation (m)") + tm_shape(shp = rivers) + tm_lines(col = "lightblue", lwd = "strokelwd", scale = 1.5, legend.lwd.show = F) + tm_shape(shp = World, is.master = TRUE) + #這個TRUE的作用很重要 tm_borders("grey20", lwd = .5) + tm_grid(projection = "longlat", labels.size = 0.4, lwd = 0.25) + tm_text("name", size = "AREA") + tm_compass(position = c(0.08, 0.45), color.light = "grey90", size = 3) + #指南針位置 tm_credits(text = "Eckert IV projection", position = c("RIGHT", "BOTTOM")) + tm_style(style = "classic", bg.color = "lightblue", space.color = "grey90", inner.margins = c(0.04, 0.04, 0.03, 0.02), earth.boundary = TRUE) + #以地球為邊界變為橢圓。 tm_legend(position = c("left", "bottom"), frame = TRUE, bg.color = "lightblue") tmap_mode("plot") m2 # 輸出會比較好看~ tmap_save(tm = m2, filename = "../data/classic.png", width = 6.125, scale = .7, dpi = 300, outer.margins = 0) #有錯誤題是說要設定outer.margins=0.1 ``` ## Section 4.3 ```{r} ############################# ## Figure 8 ############################# m3 <- tm_shape(World, projection = "robin") + tm_polygons(col = c("HPI", "gdp_cap_est"), palette = list("RdYlGn", "Purples"), style = c("pretty", "fixed"), n = 7, breaks = list(NULL, c(0, 500, 2000, 5000, 10000, 25000, 50000, Inf)), title = c("Happy Planet Index", "GDP per capita")) + tm_style(style = "natural", earth.boundary = c(-180, -87, 180, 87)) + tm_format(format = "World", inner.margins = 0.02, frame = FALSE) + tm_legend(position = c("left", "bottom"), bg.color = "gray95", frame = TRUE) + tm_credits(text = c("", "Robinson projection"), position = c("RIGHT", "BOTTOM")) # ttm() + m3 # tmap_save(m3, "../data/world_facets2.png", width = 5, scale = .7, dpi = 300, outer.margins = 0) ``` ## Section 4.4 ```{r} ############################# ## Figure 9 ############################# library("readxl") library("grid") # function to obtain Food Environment Atlas data (2014) get_food_envir_data <- function() { dir <- tempdir() if (!file.exists(file.path(dir, "DataDownload.xls"))) { download.file("https://www.ers.usda.gov/webdocs/DataFiles/48731/February2014.xls?v=41688", destfile = file.path(dir, "DataDownload.xls"), mode = "wb") } res <- tryCatch({ read_excel(file.path(dir, "DataDownload.xls"), sheet = "HEALTH") }, error = function(e) { stop("The excel file cannot be read. Please open it, and remove all sheets except HEALTH. The location of the file is: ", normalizePath(file.path(dir, "DataDownload.xls"))) }) } # function to obtain US county shape get_US_county_2010_shape <- function() { dir <- tempdir() download.file("http://www2.census.gov/geo/tiger/GENZ2010/gz_2010_us_050_00_20m.zip", destfile = file.path(dir, "gz_2010_us_050_00_20m.zip")) unzip(file.path(dir, "gz_2010_us_050_00_20m.zip"), exdir = dir) US <- sf::read_sf(file.path(dir, "gz_2010_us_050_00_20m.shp")) levels(US$NAME) <- iconv(levels(US$NAME), from = "latin1", to = "utf8") US } # obtain Food Environment Atlas data # FEA <- get_food_envir_data() FEA <- read_excel("../data/DataDownload.xls", sheet = "HEALTH") # obtain US county shape # US <- get_US_county_2010_shape() US <- sf::read_sf("../data/gz_2010_us_050_00_20m/gz_2010_us_050_00_20m.shp") levels(US$NAME) <- iconv(levels(US$NAME), from = "latin1", to = "utf8") # --- us1 <- qtm(shp = US) us1 # tmap_save(us1, "../data/US1.png", scale = .5, width = 6.125, asp = 0, outer.margins = 0) ``` ```{r} ############################# ## Figure 10 ############################# library(dplyr) library(sf) US$FIPS <- paste0(US$STATE, US$COUNTY) # append data to shape US <- left_join(US, FEA, by = c("FIPS", "FIPS")) unmatched_data <- FEA %>% filter(!(FIPS %in% US$FIPS)) tmap_mode("view") qtm(US, fill = "PCT_OBESE_ADULTS10") ``` ```{r} # 有人的地圖性質不乖, # 應該要是 MULTIPOLYGON,但是有些是 GEOMETRYCOLLECTION。 # US_cont$geometry %>% sapply(., attr, which = "class") %>% c() %>% table # US_AK$geometry %>% sapply(., attr, which = "class") %>% c() %>% table # --- ############################# ## Figure 11 ############################# US_cont <- US %>% subset(!STATE %in% c("02", "15", "72")) %>% simplify_shape(shp = ., fact = 0.2) US_AK <- US %>% subset(STATE == "02") %>% simplify_shape(0.2) US_HI <- US %>% subset(STATE == "15") %>% simplify_shape(0.2) # create state boundaries # 製作 boundaries 的方式要學起來 US_states <- US_cont %>% dplyr::select(geometry) %>% stats::aggregate(by = list(US_cont$STATE), FUN = mean) US_AK_states <- US_AK %>% dplyr::select(geometry) %>% stats::aggregate(by = list(US_AK$STATE), FUN = mean) US_HI_states <- US_HI %>% dplyr::select(geometry) %>% stats::aggregate(by = list(US_HI$STATE), FUN = mean) # contiguous US # 可以刪除第1259, 2407筆 m_cont <- tm_shape(US_cont, projection = 2163) + tm_polygons(col = "PCT_OBESE_ADULTS10", border.col = "gray50", border.alpha = .5, title = "", showNA = TRUE) + tm_shape(US_states) + tm_borders(lwd = 1, col = "black", alpha = .5) + tm_credits(text = paste0("Data @ Unites States Department of Agriculture", "\nShape @ Unites States Census Bureau"), #只有在mode=plot才會出現 position = c("right", "bottom")) + tm_layout(title = "2010 Adult Obesity by County, percent", title.position = c("center", "top"), legend.position = c("right", "bottom"), frame = FALSE, inner.margins = c(0.1, 0.1, 0.05, 0.05)) # tmap_mode(mode = "plot") # m_cont # Alaska inset0 # 因為一些錯誤,所以要加上state邊界。不然就要扣除第24筆。 m_AK <- tm_shape(US_AK, projection = 3338) + tm_polygons(col = "PCT_OBESE_ADULTS10", border.col = "gray50", border.alpha = .5, breaks = seq(10, 50, by = 5)) + tm_shape(shp = US_AK_states) + tm_borders(lwd = 1, col = "black", alpha = .5) + tm_layout(title = "Alaska", title.size = 0.8, legend.show = FALSE, bg.color = NA, frame = FALSE) # tmap_mode(mode = "plot") # m_AK # Hawaii inset m_HI <- tm_shape(US_HI, projection = 3759) + tm_polygons("PCT_OBESE_ADULTS10", border.col = "gray50", border.alpha = .5, breaks = seq(10, 50, by = 5)) + tm_shape(shp = US_HI_states) + tm_borders(lwd = 1, col = "black", alpha = .5) + tm_layout(title = "Hawaii", legend.show = FALSE, bg.color = NA, title.position = c("LEFT", "BOTTOM"), title.size = 0.8, frame = FALSE) # tmap_mode(mode = "plot") # m_HI # specify viewports for Alaska and Hawaii # 原點(0,0)在左下角 library("grid") vp_AK <- viewport(x = 0.15, y = 0.15, width = 0.3, height = 0.3) vp_HI <- viewport(x = 0.4, y = 0.1, width = 0.2, height = 0.1) # save map tmap_mode("plot") tmap_save(tm = m_cont, filename = "../data/USchoro.png", scale = 0.7, width = 6.125, outer.margins = 0, insets_tm = list(m_AK, m_HI), insets_vp = list(vp_AK, vp_HI)) ``` ## Section 4.5 ```{r} ############################# ## Figure 12a ############################# library("sf") library("rnaturalearth") # functions to obtain crimes data get_crimes_data <- function(path) { stopifnot(file.exists(path), ("crimes_in_Greater_London_2015-10.zip" %in% list.files(path))) tmp_dir <- tempdir() unzip(file.path(path, "crimes_in_Greater_London_2015-10.zip"), exdir = tmp_dir) rbind(read.csv(file.path(tmp_dir, "2015-10-city-of-london-street.csv")), read.csv(file.path(tmp_dir, "2015-10-metropolitan-street.csv"))) } # please download the file "crimes_in_Greater_London_2015-10.zip" # (available on https://www.jstatsoft.org as a supplement of this paper), # and change the path argument below to the location of the downloaded file: # crimes <- get_crimes_data(path = "./") crimes <- rbind( read.csv("../data/crimes_in_Greater_London_2015-10/2015-10-city-of-london-street.csv"), read.csv("../data/crimes_in_Greater_London_2015-10/2015-10-metropolitan-street.csv")) # create sf of known locations crimes <- crimes[!is.na(crimes$Longitude) & !is.na(crimes$Latitude), ] crimes <- st_as_sf(crimes, coords = c("Longitude", "Latitude"), crs = 4326) # set map projection to British National Grid crimes <- st_transform(crimes, crs = 27700) c1 <- qtm(crimes) c1 # tmap_save(c1, "crimes1.png", scale = .6, width = 3, units = "in", outer.margins = 0) ``` ```{r} # 似乎是一個無法解決的問題 # [Issue with generating maps in RStudio : / Questions and Answers / OpenStreetMap Forum](https://forum.openstreetmap.org/viewtopic.php?id=68079) # 因為該套件沒有按照 OSM 的規範, 所以要不到該資料區域的底圖。 # 解決方法就是改參數type,變成別的底圖, # [tmaptools/read_osm.R at master · mtennekes/tmaptools](https://github.com/mtennekes/tmaptools/blob/master/R/read_osm.R) # --- ############################# ## Figure 12b ############################# crimes_osm <- read_osm(crimes, type = "osm-transport") c2 <- qtm(crimes_osm) + qtm(crimes, symbols.col = "red", symbols.size = 0.5) c2 # tmap_save(c2, "crimes2.jpg", scale = .6, width = 3, units = "in", outer.margins = 0) ``` ```{r} ############################# ## Figure 13 ############################# c3 <- qtm(crimes_osm, raster.saturation = 0, raster.alpha = 1) + qtm(crimes, symbols.col = "Crime.type", symbols.size = 0.5) + tm_legend(outside = TRUE) c3 # tmap_save(c3, "crimes3.png", scale = .8, width = 5, height = 4, units = "in", outer.margins = 0) ``` ```{r} ############################# ## Figure 14 ############################# regions <- ne_download(scale = "large", type = "states", category = "cultural", returnclass = "sf") london <- regions[which(regions$region == "Greater London"),] london <- st_transform(london, crs = 27700) # remove crimes outside Greater London crimes_london <- crop_shape(crimes, london, polygon = TRUE) c3b <- qtm(crimes_london, dots.alpha = 0.1) + tm_shape(london) + tm_borders() c3b # tmap_save(c3b, "crimes3b.png", scale = .7, width = 6.125, units = "in", outer.margins = 0) ``` ```{r} ############################# ## Figure 15 ############################# library("devtools") # install_github("mtennekes/oldtmaptools") library(oldtmaptools) crime_densities <- smooth_map(crimes_london, bandwidth = 0.5, breaks = c(0, 50, 100, 250, 500, 1000), cover = london) # download rivers, and get Thames shape rivers <- ne_download(scale = "large", type = "rivers_lake_centerlines", category = "physical") thames <- crop_shape(rivers, london) c4 <- tm_shape(crime_densities$polygons) + tm_fill(col = "level", palette = "YlOrRd", title = expression("Crimes per " * km^2)) + tm_shape(london) + tm_borders() + tm_shape(thames) + tm_lines(col = "steelblue", lwd = 4) + tm_compass(position = c("left", "bottom")) + tm_scale_bar(position = c("left", "bottom")) + tm_style("gray", title = "Crimes in Greater London\nOctober 2015") c4 # tmap_save(c4, "crimes4.png", scale = .7, width = 6.125, units = "in", outer.margins = 0) ``` ```{r} # 無法做出和原圖一樣,不知道為什麼XD # --- ############################# ## Figure 16 ############################# london_city <- london[london$name == "City",] crimes_city <- crop_shape(crimes_london, london_city, polygon = TRUE) london_osm <- read_osm(london_city, type = "stamen-watercolor", zoom = 13) # london_osm <- read_osm(london_city, type = "osm", zoom = 13) #這個底圖不能用了 c5 <- qtm(london_osm, basemaps = "Stamen.Watercolor") + tm_shape(crimes_city) + tm_dots(size = .2) + tm_facets(by = "Crime.type", ncol = 4, free.coords = FALSE) c5 # tmap_save(c5, "crimes5.png", scale = 1, width = 6.125, asp = NA, outer.margins = 0) ``` ```{r} ############################# ## Figure 17 ############################# crime_lookup <- c("Anti-social behaviour" = 2, "Bicycle theft" = 1, "Burglary" = 1, "Criminal damage and arson" = 2, "Drugs" = 6, "Other crime" = 7, "Other theft" = 1, "Possession of weapons" = 3, "Public order" = 2, "Robbery" = 1, "Shoplifting" = 1, "Theft from the person" = 1, "Vehicle crime" = 4, "Violence and sexual offences" = 5) crime_categories <- c("Property Crime", "Criminal damage and anti-social behaviour", "Possession of weapons", "Vehicle crime", "Violence and sexual offences", "Drugs", "Other crime") crimes_city$Crime.group <- factor(crime_lookup[crimes_city$Crime.type], labels = crime_categories) tmap_mode("view") tm_shape(shp = crimes_city) + tm_dots(jitter = 0.2, col = "Crime.group", palette = "Dark2", popup.vars = TRUE) + tm_view(alpha = 1, basemaps = "Esri.WorldTopoMap") ``` --- # END
import {Construct} from "constructs"; import * as cdk from 'aws-cdk-lib'; import * as ecr from 'aws-cdk-lib/aws-ecr'; import * as assets from 'aws-cdk-lib/aws-ecr-assets'; import * as ecrdeploy from 'cdk-ecr-deployment'; export class Ecr extends Construct { public readonly fluentbitECR: ecr.IRepository; constructor(scope: Construct, id: string) { super(scope, id); this.fluentbitECR = new ecr.Repository(this, 'fluentbit-ecr', { repositoryName: 'fluentbit-nginx' }); const dockerImage = new assets.DockerImageAsset(this, 'fluent-bit-image', { directory: './lib/fluentbit', // 指向包含 Dockerfile 和应用程序代码的目录 }); new ecrdeploy.ECRDeployment(this, 'fluent-bit-ecr-dockerimage', { src: new ecrdeploy.DockerImageName(dockerImage.imageUri), dest: new ecrdeploy.DockerImageName(`${cdk.Aws.ACCOUNT_ID}.dkr.ecr.${cdk.Aws.REGION}.amazonaws.com/${this.fluentbitECR.repositoryName}:latest`), }); new cdk.CfnOutput(this, 'ECR-Repo', { value: this.fluentbitECR.repositoryArn }); new cdk.CfnOutput(this, 'DockerImageUri', { value: dockerImage.imageUri, }); } }
import 'package:flutter/material.dart'; class LoginEmailTextField extends StatelessWidget { const LoginEmailTextField({ super.key, required this.emailController, }); final TextEditingController emailController; @override Widget build(BuildContext context) { return TextField( keyboardType: TextInputType.emailAddress, // key: formkey, controller: emailController, textInputAction: TextInputAction.next, decoration: InputDecoration( contentPadding: EdgeInsets.all(MediaQuery.of(context).size.height * 0.03), filled: true, prefixIcon: Padding( padding: EdgeInsets.only( left: MediaQuery.of(context).size.width * 0.03, right: MediaQuery.of(context).size.width * 0.03), child: Icon(Icons.email_rounded, size: MediaQuery.of(context).size.height * 0.055, color: Colors.black45)), fillColor: Colors.white, hintText: "email address", hintStyle: TextStyle( color: Colors.black45, fontSize: MediaQuery.of(context).size.height * 0.03), enabledBorder: OutlineInputBorder( borderRadius: BorderRadius.circular(MediaQuery.of(context).size.width * 0.03), borderSide: const BorderSide(color: Colors.white)), focusedBorder: OutlineInputBorder( borderRadius: BorderRadius.circular(MediaQuery.of(context).size.width * 0.03), borderSide: const BorderSide(color: Colors.white)), ), ); } }
Using TraX on Linux This tutorial will show you how to compile C and C++ trackers on Linux systems using CMake build system. It is assumed that you have read the :doc:`general remarks on tracker structure </tutorial_introduction>`. There are many Linux distributions, this tutorial will focus on the most popular one, Ubuntu, and its derivatives (e.g. Linux Mint). For these systems a `PPA repository <https://launchpad.net/~lukacu/+archive/ubuntu/trax>`_ is available so that you do not have to compile the TraX library yourself. For other distributions you have to :doc:`compile and install </tutorial_compiling>` the library before continuing with the second step of this tutorial. Step 1: Installing library from PPA ----------------------------------- To install the library from PPA you have to add the PPA to your package repository list:: sudo add-apt-repository ppa:lukacu/trax sudo apt-get update Then install the required packages:: sudo apt-get install libtrax0 libtrax-dev .. note:: The project is separated in multiple packages in the PPA, if you want to install OpenCV support you will have to install additional packages :: sudo apt-get install libtrax-opencv0 libtrax-opencv-dev Step 2: Preparing your project ------------------------------ For the purposes of this tutorial we will use a simple NCC tracker that uses OpenCV library (because of this we will also use OpenCV support library to make integration easier and more general). The original source code for the tracker is available in the project repository in directory `docs/tutorials/tracker`. All the source code of the tracker is contained in a single file called `ncc.cpp`. Inspect the source code to see that it is composed of three parts. The first one is the tracker implementation which contains the actual tracking algorithm. The second one contains utility functions that take care of loading the input data and writing the results. The final part contains the main tracking loop. Since this code is properly structured, all the adaptation work has to be done on this final part of the code. The initial tracking loop looks like: .. code-block:: c++ :linenos: int main( int argc, char** argv) { // Reading std::vector<std::string> images = readsequence("images.txt"); cv::Rect initialization = readrectangle("region.txt"); std::vector<std::Rect> output; NCCTracker tracker; // Initializing the tracker with first image cv::Mat image = cv::imread(images[0]); tracker.init(image, initialization); // Adding first output to maintain equal length of outputs and // input images. output.push_back(initialization); // The tracking loop, iterating through the rest of the sequence for (size_t i = 1; i < images.size(); i++) { cv::Mat image = cv::imread(images[i]); cv::Rect rect = tracker.update(image); output.push_back(rect); } // Writing the tracking result and exiting writerectangles("output.txt", output); } To modify the source code to use the TraX protocol we have to remove explicit loading of the initialization data and let the protocol take care of this. .. code-block:: c++ :linenos: int main( int argc, char** argv) { NCCTracker tracker; trax::Server handle(trax::Metadata(TRAX_REGION_RECTANGLE, TRAX_IMAGE_PATH | TRAX_IMAGE_MEMORY | TRAX_IMAGE_BUFFER), trax_no_log); while (true) { trax::Image image; trax::Region region; trax::Properties properties; int tr = handle.wait(image, region, properties); if (tr == TRAX_INITIALIZE) { tracker.init(trax::image_to_mat(image), trax::region_to_rect(region)); handle.reply(region, trax::Properties()); } else if (tr == TRAX_FRAME) { cv::Rect result = tracker.update(image_to_mat(image)); handle.reply(trax::rect_to_region(result), trax::Properties()); } else break; } } Lets now look at individual modifications. The creation `handle` object provides a protocol server handle that initializes the protocol and sends the introductory message. The handle is given protocol configuration structure that specifies what kind of data the server can handle as well as the optional output log that can be used for debugging:: trax::Server handle(trax::Configuration(TRAX_IMAGE_PATH | TRAX_IMAGE_MEMORY | TRAX_IMAGE_BUFFER, TRAX_REGION_RECTANGLE), trax_no_log); When using OpenCV support library's function :cpp:func:`trax::image_to_mat`, the conversion from file path, raw memory and image buffer types happens automatically so supporting them all is really easy. Without this function you have to convert the image yourself. The tracking loop has been modified to accept commands from the client. This happens with the call to the :cpp:func:`trax::Server::wait` function. The function populates the provided variables: new image, object state (on initialization), and optional parameters. Since this kind of client-guided session means that the server does not know in advance how long will the tracking session be, the loop is only broken when a quit message is received from the client. The other two options are the initialization and new frame (which can always only follow successful initialization). The re-initialization can happen at any time throughout the session so the server should be capable of reinitializing the tracker (note that in untrusted setups the client may also terminate the session and start a new one). Requests for initialization or update must be answered with a state message generated by :cpp:func:`trax::Server::reply`. This function accepts the object state as predicted by the tracker as well as any additional parameters that can be accumulated by the client for development or debugging purposes. Because all the results are processed and stored by the client, we can remove the explicit results storage at the end of the loop. All these modifications also make all the utility functions in from the initial tracker implementation (second part of the source code) obsolete, they can be removed as their function is handled by the client. Step 3: Compiling the project ----------------------------- Finally we will modify the example's CMake file. Properly installed TraX library supports CMake discovery mechanism, the only line that we have to add is therefore:: FIND_PACKAGE(trax REQUIRED COMPONENTS core opencv) TARGET_LINK_LIBRARIES(ncc_tracker ${TRAX_LIBRARIES}) INCLUDE_DIRECTORIES(AFTER ${TRAX_INCLUDE_DIRS}) LINK_DIRECTORIES(AFTER ${TRAX_LIBRARY_DIRS}) This command will locate the TraX core library and the OpenCV support library and configure several variables. The project is compiled as a standard CMake project. First, we call CMake to generate a Makefile, then we call the `make` tool to build the project. According to the CMake best practices we perform build in a separate sub-directory to separate the generated binaries that can be safely removed and the source code:: $ mkdir bulild $ cd build $ cmake .. $ make Step 4: Testing integration --------------------------- A successful build results in a binary program (in the case of this tutorial the program is called `ncc_tracker`. To test if the program correctly supports TraX protocol we can use the client `traxtest` provided by the client support module of the project. This program tries to run the tracker on a sequence of static images to see if the protocol is correctly supported. Note that this test does not discover all the logical problems of the implementation as they may only occur during very specific conditions; it only tests the basic TraX compliance. To run the test move to the build directory and type:: $ traxtest -d -- ncc_tracker If the integration is successful this command should output something like:: CLIENT: Starting process "ncc_tracker" CLIENT: Setting up TraX with standard streams connection @@TRAX:hello "trax.image=path;memory;buffer;" "trax.region=rectangle;" "trax.version=1" CLIENT: Tracker process ID: 13019 CLIENT: Connection with tracker established. @@TRAX:initialize "data:image/... Tracker initialized @@TRAX:state "130.0000,80.0000,70.0000,110.0000" @@TRAX:frame "data:image/... Tracker updated @@TRAX:state "130.0000,80.0000,70.0000,110.0000" @@TRAX:frame "data:image/@@TRAX:frame "data:image/... Tracker updated @@TRAX:state "130.0000,80.0000,70.0000,110.0000" @@TRAX:frame "data:image/... Tracker updated ... ...
function status = save_ann (Fname, Ann, Vars) % Writer for .ann annotation files % % status = save_xxx(Fname, Ann, Vars) % % save_xxx() is a subprogram to eaf_save that is used to specifically % save annotations to an EMGlab ".xxx" annotation file from % the EMGlab annotation structure. The function inputs and outputs % are standardized so that different annotation formats can be facilitated % by different functions with names of the form: save_xxx, where % xxx generally denotes the filename extension of the annotation file. % See eaf_save() for complete definitions of Fname, Ann, Vars and status. % If input variable Vars is unused, it must still be included in the % function prototype. % % At a minimum, Ann must include the fields Ann.time and Ann.unit, % as defined in the EMGlab annotation structure. Be sure to close any % files that were opened, even if errors occur. % Copyright (c) 2006-2009. Edward A. Clancy, Kevin C. McGill and others. % Part of EMGlab version 1.0. % This work is licensed under the Aladdin free public license. % For copying permissions see license.txt. % email: emglab@emglab.net %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%%%%%%%%% Format: EMGlab ann File %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % ".ann" file is ASCII with two columns: times in seconds and spike ID % numbers. This file type is intended as a temporary, simple file type % and may not be supported in future EMGlab releases. Instead, EMGlab % annotation file (EAF) format will be supported. NM = 'save_ann'; % Name of this MATLAB function (short hand). % Open the annotation file, with error checking. fid = fopen(Fname, 'wb'); if fid<0, errordlg(['Can''t open file "' Fname '".'], NM); return; end % Write the annotations. fprintf (fid, '%.5f %d\r\n', [Ann.time'; Ann.unit']); % Time in seconds. % Close the annotation file. fclose(fid); status = 0; return
// // Protocolos.swift // estudoVIPER // // Created by Roberto Edgar Geiss on 30/09/21. // // MARK: - User Interface // MARK: Routers import UIKit public protocol PostBrowserWireframe: AnyObject { var rootViewController: UIViewController { get } func present(PostDetail: PostDetailPresenter, from: UIViewController) func present(error: Error, from sourceVC: UIViewController, retryHandler: (() -> Void)? ) } //public func createPostBrowserWireframe(dataProvider: PostDataProvider) -> PostBrowserWireframe //{ // PostBrowserWireframeImp(dataProvider: dataProvider) //} // MARK: PostListPresenter public protocol PostListPresenter: AnyObject { var output: PostListPresenterOutput? {get set} var numberOfItems: Int { get } func configureCell(_ cell: PostSummaryCell, forItemAt: Int) func loadInitialItems() func loadMoreItems() func showDetailOfItem(at indexPath: Int) var loadBatchSize: Int { get set } } public protocol PostListPresenterOutput: UIViewController { func presenter(_ presenter: PostListPresenter, didAddItemsAt indexes: IndexSet) } // MARK: PostDetailPresenter public protocol PostDetailPresenter: AnyObject { var output: PostDetailPresenterOutput? {get set} var hasDetail: Bool { get } var PostTitleText: String? { get } var PostRuntimeText: String? { get } var PostTaglineText: String? { get } var PostReleaseDateText: String? { get } func refreshDetail() } public protocol PostDetailPresenterOutput: UIViewController { func presenterDidUpdatePostDetail(_ presenter: PostDetailPresenter) } // MARK: Views public protocol PostSummaryCell: AnyObject { var PostID: PostIdentifier? {get set} func setPostOriginalTitle(_ title: String?) } // MARK: View Controllers protocol DetailViewController: UIViewController { var isEmpty: Bool { get } } // MARK: - Network // MARK: Data Provider public protocol PostSummaryResult { var pageNumber: UInt? { get } var totalResults: UInt? { get } var totalPages: UInt? { get } var results: [PostSummary]? { get } } public protocol PostDataProvider { var defaultPageSize: Int { get } func fetchPostSummaries( filter: [(attribute: PostFilterAttribute, value: Any, isAscending: Bool)], sort: (attribute: PostSortAttribute, isAscending: Bool)?, pageNumber: Int?, resultReceiver: @escaping ( _ : Result<PostSummaryResult, Error> ) -> Void ) func fetchPostDetail(PostID: PostIdentifier, resultReceiver: @escaping (Result<PostDetail, Error>) -> Void) }
import React, { useCallback, useEffect, useMemo, useState } from "react"; import ListItemText from "@mui/material/ListItemText"; import ListItemButton from "@mui/material/ListItemButton"; import Typography from "@mui/material/Typography"; import CustomDialog from "@/components/miscellaneous/CustomDialog"; import { useDispatch, useSelector } from "react-redux"; import { initialStatesTypes } from "@/redux/features/setting/alarm/silent/silentReducer"; import { setCurrentAlarmSilentMiddleware } from "@/middleware/setting/alarm/silent"; function SetSilent() { /* The code is using the `useSelector` hook from the `react-redux` library to select specific state values from the Redux store. It is extracting the `allSilentIntervals` and `currentSilentInterval` values from the `state.alarmSilent` slice of the Redux store and assigning them to the variables `allSilentIntervals` and `currentSilentInterval` respectively. */ const { allSilentIntervals, currentSilentInterval, }: initialStatesTypes = useSelector((state: any) => ({ allSilentIntervals: state.alarmSilent.allSilentIntervals, currentSilentInterval: state.alarmSilent.currentSilentInterval, })); const dispatch = useDispatch(); const [open, setOpen] = useState<boolean>(false); /* The `handleClose` function is a callback function that is used to handle the closing of the dialog component. It takes an optional `value` parameter, which represents the selected value from the dialog. */ const handleClose = useCallback( async (value?: string) => { setOpen(false); if (value) { (await setCurrentAlarmSilentMiddleware(value))(dispatch); } }, [dispatch] ); /* The `useMemo` hook is used to memoize the result of a computation. In this case, the `setSilentComponent` variable is assigned the result of the `useMemo` hook. */ const setSilentComponent = useMemo(() => { return ( <> <ListItemButton sx={{ pl: 9 }} onClick={() => setOpen(true)}> <ListItemText primary={ <Typography variant="body1"> Silent after </Typography> } secondary={currentSilentInterval} /> </ListItemButton> <CustomDialog id="silent-after" title="Silent after" data={allSilentIntervals} keepMounted value={currentSilentInterval} open={open} onClose={handleClose} /> </> ); }, [allSilentIntervals, currentSilentInterval, handleClose, open]); return <>{setSilentComponent}</>; } export default SetSilent;
package dataaccess.mysql; import chess.ChessGame; import dataaccess.DataAccessException; import dataaccess.DatabaseManager; import dataaccess.GameDAO; import model.bean.GameBean; import java.sql.*; import java.util.Collection; import java.util.HashSet; import java.util.Set; public class MySQLGameDAO implements GameDAO { @Override public void insert(GameBean bean) throws DataAccessException { String sql = "INSERT INTO game (gameID, whiteUsername, blackUsername, gameName, game) VALUES (?, ?, ?, ?, ?);"; try (Connection conn = DatabaseManager.getConnection()) { if (conn.isClosed()) return; PreparedStatement stmt = conn.prepareStatement(sql); stmt.setInt(1, bean.getGameID()); if (bean.getWhiteUsername() == null) stmt.setNull(2, Types.INTEGER); else stmt.setString(2, bean.getWhiteUsername()); if (bean.getBlackUsername() == null) stmt.setNull(3, Types.INTEGER); else stmt.setString(3, bean.getBlackUsername()); stmt.setString(4, bean.getGameName()); stmt.setString(5, bean.getGame()); stmt.executeUpdate(); } catch (SQLException e) { e.printStackTrace(); throw new DataAccessException(e.getMessage()); } } @Override public GameBean find(int gameID) throws DataAccessException { String sql = "SELECT * FROM game WHERE gameID = ?;"; try (Connection conn = DatabaseManager.getConnection()) { if (conn.isClosed()) return null; PreparedStatement stmt = conn.prepareStatement(sql); stmt.setInt(1, gameID); ResultSet rs = stmt.executeQuery(); if (rs.next()) { String white = rs.getString(2); String black = rs.getString(3); return new GameBean(rs.getInt(1), white, black, rs.getString(4), rs.getString(5)); } else return null; } catch (SQLException e) { e.printStackTrace(); throw new DataAccessException(e.getMessage()); } } @Override public Collection<GameBean> findAll() throws DataAccessException { String sql = "SELECT * FROM game ORDER BY gameName;"; try (Connection conn = DatabaseManager.getConnection()) { if (conn.isClosed()) return null; PreparedStatement stmt = conn.prepareStatement(sql); ResultSet rs = stmt.executeQuery(); Set<GameBean> allGames = new HashSet<>(); while (rs.next()) { String white = rs.getString(2); String black = rs.getString(3); allGames.add(new GameBean(rs.getInt(1), white, black, rs.getString(4), rs.getString(5))); } return allGames; } catch (SQLException e) { e.printStackTrace(); throw new DataAccessException(e.getMessage()); } } @Override public void update(GameBean bean) throws DataAccessException { String sql = "UPDATE game SET game = ? WHERE gameID = ?"; try (Connection conn = DatabaseManager.getConnection()) { if (conn.isClosed()) return; // If this game does not exist, insert it if (find(bean.getGameID()) == null) { insert(bean); return; } PreparedStatement stmt = conn.prepareStatement(sql); stmt.setString(1, bean.getGame()); stmt.setInt(2, bean.getGameID()); stmt.executeUpdate(); } catch (SQLException e) { e.printStackTrace(); throw new DataAccessException(e.getMessage()); } } @Override public void delete(int gameID) throws DataAccessException { String sql = "DELETE FROM game WHERE gameID = ?;"; try (Connection conn = DatabaseManager.getConnection()) { if (conn.isClosed()) return; PreparedStatement stmt = conn.prepareStatement(sql); stmt.setInt(1, gameID); stmt.executeUpdate(); } catch (SQLException e) { e.printStackTrace(); throw new DataAccessException(e.getMessage()); } } @Override public void clear() throws DataAccessException { String sql = "DELETE FROM game;"; try (Connection conn = DatabaseManager.getConnection()) { if (conn.isClosed()) return; PreparedStatement stmt = conn.prepareStatement(sql); stmt.executeUpdate(); } catch (SQLException e) { e.printStackTrace(); throw new DataAccessException(e.getMessage()); } } @Override public void claimSpot(int gameID, ChessGame.TeamColor color, String username) throws DataAccessException { if (color == null) return; String sql = color == ChessGame.TeamColor.WHITE ? "UPDATE game SET whiteUsername = ? WHERE gameID = ?" : "UPDATE game SET blackUsername = ? WHERE gameID = ?"; try (Connection conn = DatabaseManager.getConnection()) { if (conn.isClosed()) return; PreparedStatement stmt = conn.prepareStatement(sql); stmt.setString(1, username); stmt.setInt(2, gameID); stmt.executeUpdate(); } catch (SQLException e) { e.printStackTrace(); throw new DataAccessException(e.getMessage()); } } }
package CBOR::Free::SequenceDecoder; use strict; use warnings; =encoding utf-8 =head1 NAME CBOR::Free::SequenceDecoder =head1 SYNOPSIS my $decoder = CBOR::Free::SequenceDecoder->new(); if ( my $got_sr = $decoder->give( $some_cbor ) ) { # Do something with your decoded CBOR. } while (my $got_sr = $decoder->get()) { # Do something with your decoded CBOR. } =head1 DESCRIPTION This module implements a parser for CBOR Sequences (L<RFC 8742|https://tools.ietf.org/html/rfc8742>). =cut #---------------------------------------------------------------------- use parent qw( CBOR::Free::Decoder::Base ); use CBOR::Free; #---------------------------------------------------------------------- =head1 METHODS This module implements the following methods in common with L<CBOR::Free::Decoder>: =over =item * C<new()> =item * C<preserve_references()> =item * C<naive_utf8()> =item * C<string_decode_cbor()> =item * C<string_decode_never()> =item * C<string_decode_always()> =item * C<set_tag_handlers()> =back Additionally, the following exist: =head2 $got_sr = I<CLASS>->give( $CBOR ); Adds some bytes ($CBOR) to the decoder’s internal CBOR buffer. Returns either: =over =item * a B<scalar reference> to the (parsed) first CBOR document in the internal buffer =item * undef, if there is no such document =back Note that if your decoded CBOR document’s root element is already a reference (e.g., an array or hash reference), then the return value is a reference B<to> that reference. So, for example, if you expect all documents in your stream to be array references, you could do: if ( my $got_sr = $decoder->give( $some_cbor ) ) { my @decoded_array = @{ $$got_sr }; # … } =head2 $got_sr = I<CLASS>->get(); Like C<give()> but doesn’t append onto the internal CBOR buffer. =cut 1;
import { Group, Button, TextInput, Stack, Divider, Container, Center, Textarea, Badge, Text, ScrollArea, } from "@mantine/core"; import StoryCard from "../components/StoryCard"; import { useEffect, useState } from "react"; import { useForm } from "@mantine/form"; import { Modal } from "@mantine/core"; import { useRouter } from "next/router"; import { fetcher, post } from "../helpers/requests-helper"; import { useUser } from "../context/UserContext"; import { AppContext } from "next/app"; import { GetServerSidePropsContext } from "next"; import { fetcherSSR } from "../helpers/request-helper-ssr"; import { handleApiError } from "../helpers/error"; import Tag from "../components/Tag"; export interface Story { id: string; title: string; tags: string; description: string; isPublished: boolean; } const MyStories = (props: { storiesFromServer: Story[]; user: { id: string; username: string; email: string; createdAt: Date; tokenVersion: number; }; }) => { const [isOpened, setIsOpened] = useState(false); const [tags, setTags] = useState(""); const [stories, setStories] = useState<Story[]>(props.storiesFromServer); const router = useRouter(); const form = useForm({ initialValues: { title: "", description: "", tags: "", }, validate: { title: (value) => value.length != 0 ? value.length >= 4 && value.length <= 64 ? null : "Your title needs to have between 4 and 64 characters" : "Your story should have a title", description: (value) => value.length != 0 ? value.length >= 64 && value.length <= 512 ? null : "Your description needs to have between 64 and 512 characters" : "Your story should have a description", tags: (value) => value.split(",").length >= 2 && value.split(",").length <= 5 ? null : "Select between 2 and 5 tags", }, }); async function onSubmit() { console.log(form.values); const [error, data] = await post<Story>("http://localhost:8000/api/story", { ...form.values, tags, }); form.validate(); if (error && !data) { console.log(error); } setStories([ ...stories, { id: Math.random().toString(), title: form.values.title, description: form.values.description, isPublished: false, tags: tags, }, ]); form.reset(); setIsOpened(false); } function onClickTag(newText: string) { if (tags.includes(newText)) { setTags((value) => value.replace(`,${newText}`, "")); return; } if (tags.length === 0) { setTags((value) => value + `${newText}`); return; } setTags((value) => value + `,${newText}`); } return ( <div> <Group position="center"> <h1>My Stories</h1> <Group position="right"> <Button color="indigo" onClick={() => setIsOpened(true)}> Create a new Story </Button> </Group> </Group> <Modal opened={isOpened} onClose={() => setIsOpened(false)} title="Create a new Story" > <form onSubmit={onSubmit}> <TextInput label="Title" {...form.getInputProps("title")} size="md" /> <Textarea label="Description" size="md" {...form.getInputProps("description")} /> <Divider /> <div> <Text>Select the up to five tags:</Text> {tags.split(",").length >= 2 && tags.split(",").length <= 5 ? null : ( <Text color="red" size="sm"> Select between 2 and 5 tags </Text> )} <Container mt="lg"> <ScrollArea style={{ height: 250 }}> <Group> <Tag text="Fantasy" onClick={onClickTag} /> <Tag text="Sci-fi" onClick={onClickTag} /> <Tag text="Romance" onClick={onClickTag} /> <Tag text="Fictional History" onClick={onClickTag} /> <Tag text="Alternative History" onClick={onClickTag} /> <Tag text="Time Travel" onClick={onClickTag} /> <Tag text="Dystopia" onClick={onClickTag} /> <Tag text="Pulp" onClick={onClickTag} /> <Tag text="Space Opera" onClick={onClickTag} /> <Tag text="SteamPunk" onClick={onClickTag} /> <Tag text="CyberPunk" onClick={onClickTag} /> <Tag text="Biography" onClick={onClickTag} /> </Group> </ScrollArea> </Container> </div> <Group position="right" mt="md"> <Button type="submit" color="indigo"> Create Story </Button> </Group> </form> </Modal> <Container> {stories.length > 0 ? ( <Stack mt="lg" align="stretch" justify="center"> {stories.map((story) => { return ( <StoryCard tags={story.tags} key={story.id} id={story.id} title={story.title} description={story.description} author={props.user.username} isProfile={false} /> ); })} </Stack> ) : ( <Center> <Text>You still haven't created any stories 😅</Text> </Center> )} </Container> </div> ); }; export async function getServerSideProps(context: GetServerSidePropsContext) { const [error, user] = await fetcherSSR<{ id: string; username: string; email: string; createdAt: Date; tokenVersion: number; }>(context.req, context.res, "http://localhost:8000/api/user/me"); if (error || !user) { return { redirect: { statusCode: 307, destination: "/" } }; } const [nerror, stories] = await fetcherSSR<Story[]>( context.req, context.res, `http://localhost:8000/api/story/author/${user.id}` ); if (nerror || !stories) { return { redirect: { statusCode: 307, destination: "/" } }; } return { props: { user: user, storiesFromServer: stories, }, }; } export default MyStories;
--- title: Extending Matchers | Guide --- # Extending Matchers Since Vitest is compatible with both Chai and Jest, you can use either the `chai.use` API or `expect.extend`, whichever you prefer. This guide will explore extending matchers with `expect.extend`. If you are interested in Chai's API, check [their guide](https://www.chaijs.com/guide/plugins/). To extend default matchers, call `expect.extend` with an object containing your matchers. ```ts expect.extend({ toBeFoo(received, expected) { const { isNot } = this return { // do not alter your "pass" based on isNot. Vitest does it for you pass: received === 'foo', message: () => `${received} is${isNot ? ' not' : ''} foo` } } }) ``` If you are using TypeScript, since Vitest 0.31.0 you can extend default `Assertion` interface in an ambient declaration file (e.g: `vitest.d.ts`) with the code below: ```ts import type { Assertion, AsymmetricMatchersContaining } from 'vitest' interface CustomMatchers<R = unknown> { toBeFoo: () => R } declare module 'vitest' { interface Assertion<T = any> extends CustomMatchers<T> {} interface AsymmetricMatchersContaining extends CustomMatchers {} } ``` ::: warning Don't forget to include the ambient declaration file in your `tsconfig.json`. ::: The return value of a matcher should be compatible with the following interface: ```ts interface MatcherResult { pass: boolean message: () => string // If you pass these, they will automatically appear inside a diff when // the matcher does not pass, so you don't need to print the diff yourself actual?: unknown expected?: unknown } ``` ::: warning If you create an asynchronous matcher, don't forget to `await` the result (`await expect('foo').toBeFoo()`) in the test itself. ::: The first argument inside a matcher's function is the received value (the one inside `expect(received)`). The rest are arguments passed directly to the matcher. Matcher function have access to `this` context with the following properties: - `isNot` Returns true, if matcher was called on `not` (`expect(received).not.toBeFoo()`). - `promise` If matcher was called on `resolved/rejected`, this value will contain the name of modifier. Otherwise, it will be an empty string. - `equals` This is a utility function that allows you to compare two values. It will return `true` if values are equal, `false` otherwise. This function is used internally for almost every matcher. It supports objects with asymmetric matchers by default. - `utils` This contains a set of utility functions that you can use to display messages. `this` context also contains information about the current test. You can also get it by calling `expect.getState()`. The most useful properties are: - `currentTestName` Full name of the current test (including describe block). - `testPath` Path to the current test.
package io.descoped.client.http.internal.apiBuilder; import io.descoped.client.api.builder.intf.OutcomeHandler; import io.descoped.client.exception.APIClientException; import java.io.UnsupportedEncodingException; import java.nio.charset.StandardCharsets; import java.util.List; import java.util.Map; import static java.net.HttpURLConnection.HTTP_OK; /** * @author Ove Ranheim (oranheim@gmail.com) * @since 24/11/2017 */ public class OutcomeHandlerImpl implements OutcomeHandler { private byte[] bytes; private int code; private int contentLength; private Map<String, List<String>> headers; public OutcomeHandlerImpl(int code, byte[] bytes, int contentLength, Map<String, List<String>> headers) { this.code = code; this.bytes = bytes; this.contentLength = contentLength; this.headers = headers; } @Override public byte[] getReceivedBytes() { return bytes; } @Override public void setReceivedBytes(byte[] bytes) { this.bytes = bytes; } @Override public String getContent() { try { return new String(bytes, StandardCharsets.UTF_8.name()); } catch (UnsupportedEncodingException e) { throw new APIClientException(e); } } @Override public int getStatusCode() { return code; } @Override public void setStatusCode(int code) { this.code = code; } @Override public int getContentLength() { return contentLength; } @Override public void setContentLength(int contentLength) { this.contentLength = contentLength; } @Override public Map<String, List<String>> getHeaders() { return headers; } @Override public void setResponseHeaders(Map<String, List<String>> headers) { this.headers = headers; } @Override public boolean ok() { return getStatusCode() == HTTP_OK; } @Override public String toString() { return "HttpBinOutcome{" + "content=" + getContent() + ", code=" + code + ", contentLength=" + contentLength + ", headers=" + headers + '}'; } }
import { CamelCasedPropertiesDeepPatched, SnakeCasedPropertiesDeepPatched } from "./types/typeFestPatch"; export type SnakeCasedPropertiesDeep<T> = SnakeCasedPropertiesDeepPatched<T>; export type CamelCasedPropertiesDeep<T> = CamelCasedPropertiesDeepPatched<T>; // those explicit function type are needed because otherwise tsc will throw: "The inferred type of this node exceeds the maximum length the compiler will serialize. An explicit type annotation is needed." export const keysToCamelCase: <T>(obj: T) => CamelCasedPropertiesDeep<T> = <T>(obj: T) => convertFields(obj, "camel"); export const keysToSnakeCase: <T>(obj: T) => SnakeCasedPropertiesDeep<T> = <T>(obj: T) => convertFields(obj, "snake"); const toCamel = (str: string) => { return str.replace(/([-_][a-z])/gi, (x) => { return x.toUpperCase().replace("-", "").replace("_", ""); }); }; const toSnake = (str: string) => { return str .split(/(?=[A-Z])/) .join("_") .toLowerCase(); }; const isObject = (obj: unknown) => obj === Object(obj) && !Array.isArray(obj) && typeof obj !== "function" && !(obj instanceof Date); const convertFields = (obj: any, format: "snake" | "camel"): any => { const toFormat = format === "snake" ? toSnake : toCamel; if (isObject(obj)) { const n: Record<string, any> = {}; Object.keys(obj).forEach((k) => (n[toFormat(k)] = convertFields(obj[k], format))); return n; } if (Array.isArray(obj)) { return obj.map((i) => convertFields(i, format)); } return obj; };
package SinglyLinkedList.ReverseLinkedList_II; // https://leetcode.com/problems/reverse-linked-list-ii/description/ public class ReverseLinkedList_II { /************************************* Double pass Traversal ************************************ * Time Complexity: O(2*n) * Space Complexity: O(1) */ public ListNode reverseBetween(ListNode head, int left, int right) { if (head == null || left == right) return head; ListNode dummy = new ListNode(); dummy.next = head; int count = 0; ListNode start = null, end = null, startBefore = null, endAfter = null; ListNode p = dummy; while (p != null){ if (count == left - 1){ startBefore = p; start = p.next; } if (count == right){ end = p; endAfter = p.next; } p = p.next; count++; } startBefore.next = null; end.next = null; reverse(start); startBefore.next = end; start.next = endAfter; return dummy.next; } public void reverse(ListNode head){ ListNode curr = head, prev = null, next; while (curr != null){ next = curr.next; curr.next = prev; prev = curr; curr = next; } } static class ListNode{ int data; ListNode next; public ListNode(){ } } }
// // Created by Luecx on 23.04.2022. // #ifndef EXACTCONSTRAINEDDELAUNAY_SRC_TRIANGLE_H_ #define EXACTCONSTRAINEDDELAUNAY_SRC_TRIANGLE_H_ #include <ostream> #include "defs.h" #include "Edge.h" #include "CDT.h" namespace delaunay{ struct Triangle { // Edges spanning the triangle Edge edges[3]{}; // history data for finding a triangle during construction // the most amount of triangles which could be created within this triangle is 3. // 3 triangles are spawned when the triangle is split with a new node in the middle // if the new node lies on the edge, only two new triangles are created within this triangle. Triangle* history[3]{}; // the history degree equals the amount of triangles set in the history array above. // there is also the option to invalidate a triangle without it having any history entries. // this is used when e.g. the triangles lies outside the boundary and needs to be excluded from the final mesh // the options for the history degree are the following: // -1 : invalidated // 0 : valid // 1-3: not part of the active set (history entries exist) int historyDegree = 0; // compute the area of the triangle. small rounding offsets may occur but no exact arithmetic is required [[nodiscard]] Precision area() const; // compute the aspect ratio of the triangle. if all sides have the same length, the aspect ratio // equals 1. Any other combination of side lengths results in an aspect ratio > 1. [[nodiscard]] Precision aspectRatio() const; // returns the edge at the given index. edges are sorted counterclockwise [[nodiscard]] Edge& getEdge(Index idx); // returns a pointer to the node at the given index // the node equals the first node of the edge with the given index [[nodiscard]] Node* getNode(Index idx) const; // returns a new node which is the average of all the other nodes // due to integer rounding this may not be exact and may even result in a node OUTSIDE the triangle // this should be checked afterwards and is a potential problem when the problem is very small. [[nodiscard]] Node center() const; // returns the node which is opposite to the given triangle. It assumes that the edge is one of the edges // above [[nodiscard]] Node* opposite(const Edge& e); // returns the index of the given node. if the node is not part of this triangle, it returns -1 [[nodiscard]] Index getNodeIndex(Node* node); // check if the node is inside the triangle. It returns true if the node is within the triangle. // it also returns true if the node lies on the edge [[nodiscard]] bool contains(Node* nP) const; // check if the given node is within the circumscribed circle // the circumscribed circle is defined by the 3 nodes which also define this triangle. // if the node lies exactly on the circumscribed triangle, it will return FALSE. // this operation is not exact since it uses floating points operations [[nodiscard]] bool isCircumscribed(Node* n) const; // check if its part of the active set // this is the case if the history degree equals 0. a negative degree would be an invalidated triangle. // a positive degree would indicate children which have replaced this triangle [[nodiscard]] bool isValid() const; // invalidate the element. useful to disable it when it does not satisfy some constraint and // should therefor be removed from the set of active triangles void invalidate(); // assigns nodes to this triangle. // this includes the generation of the edges which will in return get the node pointers // furthermore, the edges will receive data like their edge index and the triangle they are connected to. void assignNodes(Node* n1, Node* n2, Node *n3); // split the triangle into three triangles // the three new triangles are given as well as the new node to be inserted void splitIntoThreeTriangles(CDT& cdt, Node* np); // split the given edge into four new triangles if the edge is linked to a second edge. void splitIntoFourTriangles(Edge& e, CDT& cdt, Node* np); // checks that no error has occured void checkIntegrity(); friend std::ostream &operator<<(std::ostream &os, const Triangle &triangle); }; } #endif //EXACTCONSTRAINEDDELAUNAY_SRC_TRIANGLE_H_
import { test, describe, expect } from "@jest/globals"; import { render, screen } from "@testing-library/react"; import userEvent from "@testing-library/user-event"; import Form from "../components/Form"; describe("Given the form component, ", () => { test("it should render correctly", () => { render(<Form />); expect(screen.getByTestId("form")).toBeDefined(); }); test("it should save a new record correctly", async () => { localStorage.clear(); const user = userEvent.setup(); render(<Form />); const submit = screen.getByTestId("submit"); await user.click(submit); expect(localStorage.setItem).toHaveBeenCalled(); }); test("it should not save a record if a text field is incorrect", async () => { localStorage.clear(); const user = userEvent.setup(); render(<Form />); const firstNameInput = screen.getByTestId("firstName-input"); const submit = screen.getByTestId("submit"); await user.type(firstNameInput, "12345"); await user.click(submit); const errorMessage = screen.getByText( "First name can only contain letters and hyphens" ); expect(errorMessage).toBeDefined(); expect(localStorage.setItem).not.toHaveBeenCalled(); }); });
# 执行属性推断攻击 def property_inference_categorical( self, # 每个world需要的阴影模型数量 num_shadow_models=1, # 查询轮数 query_trials=1, # 随机挑选查询数据集 query_selection="random", # 区分两个world的方法 distinguishing_test="median", ): """Property inference attack for categorical data. (e.g. Census, Adults) ... Parameters ---------- num_shadow_models : int The number of shadow models per "world" to use in the attack query_trials : int Number of times we want to query num_queries points on the target distinguishing_test : str The distinguishing test to use on logit distributions Options are the following: # 戛然而止,真的删减了.哎 # 中位数的中位数:首先,这个方法会计算两个影子模型(分别代表两个不同的“世界”或数据分布)在测试数据集上的预测输出的中位数。 # 然后,计算这两组中位数的平均值,得到一个阈值(threshold)。 # 判断:接下来,使用这个阈值来判断目标模型的预测信心大多数位于哪一侧。如果目标模型的预测信心多数高于这个阈值, # 可以推断它更可能来自与较高中位数相对应的“世界”;如果多数低于阈值,则更可能来自另一个“世界”。 "median" : uses the middle of medians as a threshold and checks on which side of the threshold the majority of target model prediction confidences are on # KL散度(Kullback-Leibler divergence):这个方法使用KL散度来衡量两个概率分布之间的差异。 # 在这种情况下,两个分布是目标模型和影子模型在相同测试数据集上的预测结果。 # 相似性测量:KL散度可以衡量一个分布转换到另一个分布所需的信息量。在 # 属性推断的上下文中,它被用来衡量目标模型的预测分布与两个影子模型预测分布的相似度。 # 决策依据:通过比较目标模型与两个影子模型的KL散度,可以推断目标模型更接近哪个影子模型的“世界”。 # 较小的KL散度意味着较低的分布差异,表明目标模型可能在与该影子模型相同的数据分布上训练。 "divergence" : uses KL divergence to measure the similarity between the target model prediction scores and the ... Returns ---------- out_M0 : np.array Array of scaled logit values for M0 out_M1 : np.array Array of scaled logit values for M1 logits_each_trial : list of np.arrays Arrays of scaled logit values for target model. Each index is the output of a single query to the target model predictions : list Distinguishing test predictions; 0 if prediction is t0, 1 if prediction is t1 correct_trials : list List of booleans dentoting whether query trial i had a correct prediction """ # Train multiple shadow models to reduce variance if self._mini_verbose: print("-" * 10, "\nTraining Shadow Models...") # 两个world的dataloader D0_loaders = {} D1_loaders = {} # 如果不允许子采样,那就直接采样一次不变.且直接用_D0_OH数据集,这个环节讲解过 if self._allow_subsampling == False: self._nsub_samples = self._D0_OH.shape[0] # print("Size of Shadow model dataset: ", self._nsub_samples) if len(self._Dp) == 0: poisoned_D0 = self._D0_OH.sample(n=self._nsub_samples, random_state=21) poisoned_D1 = self._D1_OH.sample(n=self._nsub_samples, random_state=21) else: clean_D0 = self._D0_OH.sample( n=int((1 - self._poison_percent) * self._nsub_samples), random_state=21, ) clean_D1 = self._D1_OH.sample( n=int((1 - self._poison_percent) * self._nsub_samples), random_state=21, ) if ( int(self._poison_percent * self._nsub_samples) <= self._Dp_OH.shape[0] ): # Changes poisoned_D0 = pd.concat( [ clean_D0, self._Dp_OH.sample( n=int(self._poison_percent * self._nsub_samples), random_state=self._pois_rs, replace=False, ), ] ) poisoned_D1 = pd.concat( [ clean_D1, self._Dp_OH.sample( n=int(self._poison_percent * self._nsub_samples), random_state=self._pois_rs, replace=False, ), ] ) else: poisoned_D0 = pd.concat( [ clean_D0, self._Dp_OH.sample( n=int(self._poison_percent * self._nsub_samples), random_state=self._pois_rs, replace=True, ), ] ) poisoned_D1 = pd.concat( [ clean_D1, self._Dp_OH.sample( n=int(self._poison_percent * self._nsub_samples), random_state=self._pois_rs, replace=True, ), ] ) # 不允许子采样的时候,训练数据集就只有一个,不会变 D0_loaders["train"] = training_utils.dataframe_to_dataloader( poisoned_D0, batch_size=self._batch_size, using_ce_loss=self._using_ce_loss, num_workers=self._num_workers, persistent_workers=self._persistent_workers, ) D1_loaders["train"] = training_utils.dataframe_to_dataloader( poisoned_D1, batch_size=self._batch_size, using_ce_loss=self._using_ce_loss, num_workers=self._num_workers, persistent_workers=self._persistent_workers, ) # 生成查询集合 Dtest_OH_loader = training_utils.dataframe_to_dataloader( self._Dtest_OH, batch_size=self._batch_size, num_workers=self._num_workers, using_ce_loss=self._using_ce_loss, ) # 输入维度 input_dim = len(self._D0_mo_OH.columns) - 1 # 初始化为空 out_M0 = np.array([]) out_M1 = np.array([]) for i in tqdm(range(num_shadow_models), desc=f"Training {num_shadow_models} Shadow Models with {self._poison_percent * 100:.2f}% Poisoning"): if self._mini_verbose: print("-" * 10, f"\nModels {i + 1}") # 跟训练目标模型的区别就是之前两个world是分开设定的,现在是一起弄的,减少了一些重复操作,但是核心跟上个函数一样,就不说了 if len(self._layer_sizes) != 0: M0_model = models.NeuralNet( input_dim=input_dim, layer_sizes=self._layer_sizes, num_classes=self._num_classes, dropout=self._dropout, ) M1_model = models.NeuralNet( input_dim=input_dim, layer_sizes=self._layer_sizes, num_classes=self._num_classes, dropout=self._dropout, ) else: M0_model = models.LogisticRegression( input_dim=input_dim, num_classes=self._num_classes, using_ce_loss=self._using_ce_loss, ) M1_model = models.LogisticRegression( input_dim=input_dim, num_classes=self._num_classes, using_ce_loss=self._using_ce_loss, ) if self._allow_subsampling == True: if len(self._Dp) == 0: poisoned_D0 = self._D0_OH.sample(n=self._nsub_samples) poisoned_D1 = self._D1_OH.sample(n=self._nsub_samples) else: if self._allow_target_subsampling == True: poisoned_D0 = pd.concat( [ self._D0_OH.sample( n=int( (1 - self._poison_percent) * self._nsub_samples ) ), self._Dp_OH.sample( n=int(self._poison_percent * self._nsub_samples), random_state=self._pois_rs, ), ] ) poisoned_D1 = pd.concat( [ self._D1_OH.sample( n=int( (1 - self._poison_percent) * self._nsub_samples ) ), self._Dp_OH.sample( n=int(self._poison_percent * self._nsub_samples), random_state=self._pois_rs, ), ] ) else: poisoned_D0 = pd.concat( [ self._D0_OH.sample( n=int( (1 - self._poison_percent) * self._nsub_samples ) ), self._Dp_OH.sample( n=int(self._poison_percent * self._nsub_samples) ), ] ) poisoned_D1 = pd.concat( [ self._D1_OH.sample( n=int( (1 - self._poison_percent) * self._nsub_samples ) ), self._Dp_OH.sample( n=int(self._poison_percent * self._nsub_samples) ), ] ) D0_loaders["train"] = training_utils.dataframe_to_dataloader( poisoned_D0, batch_size=self._batch_size, using_ce_loss=self._using_ce_loss, num_workers=self._num_workers, persistent_workers=self._persistent_workers, ) D1_loaders["train"] = training_utils.dataframe_to_dataloader( poisoned_D1, batch_size=self._batch_size, using_ce_loss=self._using_ce_loss, num_workers=self._num_workers, persistent_workers=self._persistent_workers, ) # 训练world0的阴影模型 M0_trained, _ = training_utils.fit( dataloaders=D0_loaders, model=M0_model, epochs=self._epochs, optim_init=self._optim_init, optim_kwargs=self._optim_kwargs, criterion=self._criterion, device=self._device, verbose=self._verbose, mini_verbose=self._mini_verbose, early_stopping=self._early_stopping, tol=self._tol, train_only=True, ) # 训练world1的 M1_trained, _ = training_utils.fit( dataloaders=D1_loaders, model=M1_model, epochs=self._epochs, optim_init=self._optim_init, optim_kwargs=self._optim_kwargs, criterion=self._criterion, device=self._device, verbose=self._verbose, mini_verbose=self._mini_verbose, early_stopping=self._early_stopping, tol=self._tol, train_only=True, ) # 根据模型输出计算logit,并用_variance_adjustment控制去掉离群点logit,这是论文没提的技巧啊 # 这样图就更好看 out_M0_temp = training_utils.get_logits_torch( Dtest_OH_loader, M0_trained, device=self._device, middle_measure=self._middle, variance_adjustment=self._variance_adjustment, # label是想要用于计算置信度的那个标签 label=self._poison_class ) # 输出添加进来 out_M0 = np.append(out_M0, out_M0_temp) # 跟上边一样 out_M1_temp = training_utils.get_logits_torch( Dtest_OH_loader, M1_trained, device=self._device, middle_measure=self._middle, variance_adjustment=self._variance_adjustment, label=self._poison_class ) out_M1 = np.append(out_M1, out_M1_temp) # 打印提示信息,统计所有logit的均值和方差,标准差,中位数 if self._verbose: print( f"M0 Mean: {out_M0.mean():.5}, Variance: {out_M0.var():.5}, StDev: {out_M0.std():.5}, Median: {np.median(out_M0):.5}" ) print( f"M1 Mean: {out_M1.mean():.5}, Variance: {out_M1.var():.5}, StDev: {out_M1.std():.5}, Median: {np.median(out_M1):.5}" ) # 如果是用median方法作为区分测试,那么阈值就是两个不同分布(t0, t1)的中位数的中间值 # 也就是代表两个高斯分布的交叉点的近似,这个时候,分类误差最小 if distinguishing_test == "median": midpoint_of_medians = (np.median(out_M0) + np.median(out_M1)) / 2 thresh = midpoint_of_medians # 作者去掉了利用kl散度近似的情况讨论,在一开始说明的时候介绍了,论文里记得也没提,也就是说可能是作者的实验探索 # 打印阈值信息 if self._verbose: print(f"Threshold: {thresh:.5}") # Query the target model and determine # 用于统计一共成功推断了几次 correct_trials = 0 # 打印总查询次数,每次查询样本数 if self._mini_verbose: print( "-" * 10, f"\nQuerying target model {query_trials} times with {self._num_queries} query samples", ) # 根据实际情况决定是否需要过采样 oversample_flag = False # 如果查询点数目大于查询样本的大小,那么就需要过采样,干净主要是控制打印信息,然后也减少了后边一直判断 if self._num_queries > self._Dtest_OH.shape[0]: oversample_flag = True print("Oversampling test queries") # 对每个目标模型查询 for i, poisoned_target_model in enumerate( tqdm(self._poisoned_target_models, desc=f"Querying Models and Running Distinguishing Test")): # 开始查询 for query_trial in range(query_trials): # 啊,只是默认random查询.没有其他选择 if query_selection.lower() == "random": Dtest_OH_sample_loader = training_utils.dataframe_to_dataloader( # oversample_flag用于控制是否需要放回采样 self._Dtest_OH.sample( n=self._num_queries, replace=oversample_flag, random_state=i + 1 ), batch_size=self._batch_size, num_workers=self._num_workers, using_ce_loss=self._using_ce_loss, ) else: print("Incorrect Query selection type") # 对查询点在目标模型上查询,然后计算logit out_target = training_utils.get_logits_torch( Dtest_OH_sample_loader, poisoned_target_model, device=self._device, middle_measure=self._middle, variance_adjustment=self._variance_adjustment, label=self._poison_class ) # 打印统计信息 if self._verbose: print("-" * 10) print( f"Target Mean: {out_target.mean():.5}, Variance: {out_target.var():.5}, StDev: {out_target.std():.5}, Median: {np.median(out_target):.5}\n" ) # 开始区分是world0还是world1 """ Perform distinguishing test""" if distinguishing_test == "median": # 统计目标模型上查询出来的logit大于阈值和低于阈值的数目 # world0的logit分布在右侧,那么选的就是大于阈值的 M0_score = len(out_target[out_target > thresh]) # world1在左侧,那么选的就是低于阈值的 M1_score = len(out_target[out_target < thresh]) if self._verbose: print(f"M0 Score: {M0_score}\nM1 Score: {M1_score}") # 如果大部分符合world0,说明判断当前world为0 if M0_score >= M1_score: if self._mini_verbose: print( f"Target is in t0 world with {M0_score / len(out_target) * 100:.4}% confidence" ) # 那么就拿_target_worlds[i]和0去对比看看是否匹配,_target_worlds[i]代表真实的目标模型在哪个world上训练 correct_trials = correct_trials + int( self._target_worlds[i] == 0 ) # 否则就是反过来,一样的 elif M0_score < M1_score: if self._mini_verbose: print( f"Target is in t1 world {M1_score / len(out_target) * 100:.4}% confidence" ) correct_trials = correct_trials + int( self._target_worlds[i] == 1 ) # 目前只提供了一个median的分支,没有提供kl散度的判断,下边就是返回实验结果 if distinguishing_test == "median": return ( out_M0, out_M1, thresh, correct_trials / (len(self._target_worlds) * query_trials), )
import {BrowserRouter, Link, Route, Routes } from 'react-router-dom'; import './App.css'; import Home from './components/Home'; import Signup from './components/Signup'; import Login from './components/Login'; import Navbar from './components/Navbar'; import EventHandling from './components/EventHandling'; import StateManagement from './components/StateManagement'; import TodoList from './components/TodoList'; import ProductList from './components/ProductList'; import ManageUser from './components/ManageUser'; import { Toaster } from 'react-hot-toast'; import UpdateUser from './components/UpdateUser'; import { AnimatePresence } from 'framer-motion'; import { UserProvider } from './UserContext'; import Profile from './components/Profile'; function App() { return ( <div> <Toaster position='top-right' /> <BrowserRouter> <UserProvider> <AnimatePresence> {/* <Link to='/home'>Home</Link> <Link to='/signup'>Signup</Link> <Link to='/login'>Login</Link>*/} <Navbar /> <Routes> <Route element={<Home/> } path ='/' /> <Route element={<Home/> } path ='home' /> <Route element={<Signup/> } path ='signup' /> <Route element={<Login/> } path ='login' /> <Route element={<EventHandling /> } path ='event' /> <Route element={<StateManagement /> } path ='statemanagement' /> <Route element={<TodoList /> } path ='todo' /> <Route element={<ProductList /> } path ='list' /> <Route element={<ManageUser /> } path ='manageuser' /> <Route element={ <UserAuth> <Profile /> </UserAuth> } path="profile" /> <Route element={<UpdateUser /> } path ='updateuser/:id' /> </Routes> </AnimatePresence> </UserProvider> </BrowserRouter> </div> ); } export default App;
import { HttpCode, HttpStatus } from '@nestjs/common'; import { Controller, Logger, Post, UseGuards, Request, Body, BadRequestException, InternalServerErrorException } from '@nestjs/common'; import { UserAlreadyExistException, UserInvalidDataException, UserPasswordException } from '../../application/exceptions'; import { CreateUserDTO } from '../../application/dtos'; import { AuthJwt, CreateUser } from '../../application/use-cases'; import { LocalAuthGuard } from '../configurations'; @Controller('auth') export class AuthController { private readonly logger = new Logger(AuthController.name); constructor(private authJwt: AuthJwt, private readonly createUser: CreateUser) {} @Post('register') async create(@Body() data: CreateUserDTO) { try { const userCreated = await this.createUser.exec(data); return { message: 'New user created', data: userCreated }; } catch (error) { this.logger.error(error?.message); if (error instanceof UserAlreadyExistException) throw new BadRequestException(error?.message); if (error instanceof UserInvalidDataException) throw new BadRequestException(error?.message); if (error instanceof UserPasswordException) throw new BadRequestException(error?.message); throw new InternalServerErrorException('Server error'); } } @UseGuards(LocalAuthGuard) @Post('login') @HttpCode(HttpStatus.OK) async login(@Request() req) { const { token } = await this.authJwt.exec(req.user); return { message: 'Successful login', data: { token } }; } }