row_id
int64
0
48.4k
init_message
stringlengths
1
342k
conversation_hash
stringlengths
32
32
scores
dict
1,306
In python, make a machine learning module that predicts a game where it randoms select a color: Yellow, red or purple, Yellow is the most rare, and you've a list of the old data / past games in json: ['red', 'red', 'purple', 'purple', 'purple', 'red', 'red', 'red', 'purple', 'red', 'yellow', 'red', 'purple', 'red', 'purple', 'purple', 'yellow', 'red', 'purple', 'purple', 'yellow', 'red', 'yellow', 'red', 'red', 'purple', 'red', 'red', 'red', 'purple', 'purple', 'red', 'purple', 'purple'], also make it say the accuracy of each color to hit
38ec9b7f72135c575830544af8e05588
{ "intermediate": 0.12941233813762665, "beginner": 0.06550899893045425, "expert": 0.8050786256790161 }
1,307
import random artists_listeners = { '$NOT': 7781046, '21 Savage': 60358167, '9lokknine': 1680245, 'A Boogie Wit Da Hoodie': 18379137, 'Ayo & Teo': 1818645, 'Bhad Bhabie': 1915352, 'Blueface': 4890312, 'Bobby Shmurda': 2523069, 'Cardi B': 30319082, 'Central Cee': 22520846, 'Chief Keef': 9541580, 'Coi Leray': 28619269, 'DaBaby': 30353214, 'DDG ': 4422588, 'Denzel Curry': 755542, 'Desiigner': 5586908, 'Don Toliver': 27055150, 'Dusty Locane': 3213566, 'Est Gee': 5916299, 'Famous Dex': 2768895, 'Fivio Foreign ': 9378678, 'Fredo Bang': 1311960, 'Future': 47165975, 'Gazo': 5342471, 'GloRilla': 6273110, 'Gunna ': 23998763, 'Hotboii': 1816019, 'Iann Dior': 14092651, 'J. Cole': 36626203, 'JayDaYoungan': 1415050, 'Juice WRLD ': 31818659, 'Key Glock': 10397097, 'King Von': 7608559, 'Kodak Black': 24267064, 'Latto': 10943008, 'Lil Baby': 30600740, 'Lil Durk': 20244848, 'Lil Keed': 2288807, 'Lil Loaded': 2130890, 'Lil Mabu': 2886517, 'Lil Mosey': 8260285, 'Lil Peep': 15028635, 'Lil Pump': 7530070, 'Lil Skies': 4895628, 'Lil Tecca': 13070702, 'Lil Tjay': 19119581, 'Lil Uzi Vert ': 3538351, 'Lil Wayne': 32506473, 'Lil Xan': 2590180, 'Lil Yachty': 11932163, 'Machine Gun Kelly': 13883363, 'Megan Thee Stallion ': 23815306, 'Moneybagg Yo': 11361158, 'NLE Choppa ': 17472472, 'NoCap': 1030289, 'Offset': 15069868, 'Playboi Carti': 16406109, 'PnB Rock': 5127907, 'Polo G': 24374576, 'Pooh Shiesty': 4833055, 'Pop Smoke': 24438919, 'Quando Rondo': 1511549, 'Quavo': 15944317, 'Rod Wave ': 8037875, 'Roddy Ricch': 22317355, 'Russ Millions ': 6089378, 'Ski Mask The Slump God': 9417485, 'Sleepy Hallow': 8794484, 'Smokepurpp': 2377384, 'Soulja Boy': 10269586, 'SpottemGottem': 1421927, 'Takeoff': 9756119, 'Tay-K': 4449331, 'Tee Grizzley': 4052375, 'Travis Scott': 46625716, 'Trippie Redd': 19120728, 'Waka Flocka Flame': 5679474, 'XXXTENTACION': 35627974, 'YBN Nahmir ': 4361289, 'YK Osiris': 1686619, 'YNW Melly ': 8782917, 'YounBoy Never Broke Again': 18212921, 'Young M.A': 2274306, 'Young Nudy': 7553116, 'Young Thug': 28887553, 'Yungeen Ace': 1294188, } keys = list(artists_listeners.keys()) score = 0 while True: first_artist = random.choice(keys) second_artist = random.choice(keys) while first_artist == second_artist: second_artist = random.choice(keys) while True: guess = input(f"\nWhich artist has more monthly Spotify listeners - 1. {first_artist.title()} or 2. {second_artist.title()}? ") guess_lower = guess.strip().lower() if guess_lower == 'quit': print("Thanks for playing!") quit() elif guess_lower != first_artist.lower() and guess_lower != second_artist.lower(): print("Invalid input. Please enter the name of one of the two artists or 'quit' to end the game.") elif guess_lower == first_artist.lower() and artists_listeners[first_artist] > artists_listeners[second_artist]: print(f"You guessed correctly! {first_artist.title()} had {int(artists_listeners[first_artist] / 1e6):,}M monthly Spotify listeners and {second_artist.title()} has {int(artists_listeners[second_artist] / 1e6):,}M monthly Spotify listeners.") score += 1 break elif guess_lower == second_artist.lower() and artists_listeners[second_artist] > artists_listeners[first_artist]: print(f"You guessed correctly! {second_artist.title()} had {int(artists_listeners[second_artist] / 1e6):,}M monthly Spotify listeners and {first_artist.title()} has {int(artists_listeners[first_artist] / 1e6):,}M monthly Spotify listeners.") score += 1 break else: print(f"\nSorry, you guessed incorrectly. {first_artist.title()} had {int(artists_listeners[first_artist] / 1e6):,}M monthly Spotify listeners and {second_artist.title()} has {int(artists_listeners[second_artist] / 1e6):,}M monthly Spotify listeners.\n") score = 0 play_again = input("Would you like to play again? (y/n) ") if play_again.lower() == 'n': print("Thanks for playing!") quit() print(f"\nYour score is {score}.") why are the same artists repeated after making a mistake
b44ddbe14de54ef837c2677349ea7181
{ "intermediate": 0.41855955123901367, "beginner": 0.2916654944419861, "expert": 0.28977492451667786 }
1,308
The functionality of the checkbox works perfectly when we do state mutation by {…state} import { CreditChargesPaymentTypes, PaymentTableState, initialState } from './paymentTableStateTypes'; import { ModuleState } from '@txp-core/runtime'; import { CHARGES_TABLE_DATA_FETCHED, PaymentChargesTableActionsType, CHARGES_TABLE_DATA_UPDATE, STATE_ID } from './paymentTable_actions'; export interface paymentChargesTableState { paymentChargesTable: PaymentTableState; } const paymentTransactionTable = ( state: paymentChargesTableState = { paymentChargesTable: initialState }, action: PaymentChargesTableActionsType ): paymentChargesTableState => { switch (action.type) { case CHARGES_TABLE_DATA_FETCHED: return { ...state, paymentChargesTable: action.tableData }; case CHARGES_TABLE_DATA_UPDATE: return updateChargesTable(action.txnId, action.payload)(state); default: return state; } }; const updateChargesTable = (txnId: number, payload: Partial<CreditChargesPaymentTypes>) => (state: paymentChargesTableState) => { const newState = { ...state }; const chargesTable = newState.paymentChargesTable.charges; const index = chargesTable.findIndex( (val: CreditChargesPaymentTypes) => val.txnId === txnId ); chargesTable[index] = { ...chargesTable[index], ...payload }; const updatedState = { ...newState, paymentChargesTable: { ...newState.paymentChargesTable, charges: chargesTable } }; console.log('updatedState', updatedState); console.log('state', state); return updatedState; }; export default paymentTransactionTable; export type PaymentChargesTableModuleState = ModuleState<typeof STATE_ID, paymentChargesTableState>; export const paymentTableSelectors = { getCharges: (state: PaymentChargesTableModuleState) => state?.[STATE_ID]?.paymentChargesTable?.charges, getCredits: (state: PaymentChargesTableModuleState) => state?.[STATE_ID]?.paymentChargesTable?.credits, getCustomerBalanceAmount: (state: PaymentChargesTableModuleState) => state?.[STATE_ID]?.paymentChargesTable?.customerBalanceAmount }; But when we do state mutation by deepclone(state) its breaks import { CreditChargesPaymentTypes, PaymentTableState, initialState } from './paymentTableStateTypes'; import { ModuleState } from '@txp-core/runtime'; import { CHARGES_TABLE_DATA_FETCHED, PaymentChargesTableActionsType, CHARGES_TABLE_DATA_UPDATE, STATE_ID } from './paymentTable_actions'; import { cloneDeep } from '@txp-core/basic-utils'; export interface paymentChargesTableState { paymentChargesTable: PaymentTableState; } const paymentTransactionTable = ( state: paymentChargesTableState = { paymentChargesTable: initialState }, action: PaymentChargesTableActionsType ): paymentChargesTableState => { switch (action.type) { case CHARGES_TABLE_DATA_FETCHED: return { ...state, paymentChargesTable: action.tableData }; case CHARGES_TABLE_DATA_UPDATE: return updateChargesTable(action.txnId, action.payload)(state); default: return state; } }; const updateChargesTable = (txnId: number, payload: Partial<CreditChargesPaymentTypes>) => (state: paymentChargesTableState) => { const newState = cloneDeep(state); const chargesTable = newState.paymentChargesTable.charges; const index = chargesTable.findIndex( (val: CreditChargesPaymentTypes) => val.txnId === txnId ); chargesTable[index] = { ...chargesTable[index], ...payload }; const updatedState = { ...newState, paymentChargesTable: { ...newState.paymentChargesTable, charges: chargesTable } }; console.log('updatedState', updatedState); console.log('state', state); return updatedState; }; export default paymentTransactionTable; export type PaymentChargesTableModuleState = ModuleState<typeof STATE_ID, paymentChargesTableState>; export const paymentTableSelectors = { getCharges: (state: PaymentChargesTableModuleState) => state?.[STATE_ID]?.paymentChargesTable?.charges, getCredits: (state: PaymentChargesTableModuleState) => state?.[STATE_ID]?.paymentChargesTable?.credits, getCustomerBalanceAmount: (state: PaymentChargesTableModuleState) => state?.[STATE_ID]?.paymentChargesTable?.customerBalanceAmount }; import React, { useState } from 'react'; import { ChargesTable, paymentTableSelectors, PaymentChargesTableAction } from '@txp-core/payment-transactions-table'; import { Table } from '@ids-ts/table'; import { useTXPStateRead, useTXPStateWrite } from '@txp-core/runtime'; import { useFormatMessage } from '@txp-core/intl'; import { TransactionActions, TransactionSelectors } from '@txp-core/transactions-core'; import TextField from '@ids-ts/text-field'; import { enabled } from '@txp-core/enabled'; import { TransactionTypes, getTxnUrl } from '@txp-core/transactions-utils'; import { toLocalizedMoneyString, toLocalDateFormat } from '@txp-core/basic-utils'; import TransactionsTableHeader from './TransactionTableHeaders'; import styles from 'src/js/staticLayout/Grid.module.css'; import Checkbox from '@ids-ts/checkbox'; import style from './Tables.module.css'; import { useTrowserHooks } from '@txp-core/trowser'; import LinkButton from '@txp-core/link-button'; export interface txnType { txnTypeId: number; txnTypeLongName: string; } export interface OutstandingTableDataTypes { txnId: number; txnType: txnType; date: string; amount: string; referenceNumber: number; dueDate: string; openBalance: string; linkedPaymentAmount: string; isLinkedPaymentAmount?: boolean; } export const OutstandingTransactionsTable = () => { const formatMessage = useFormatMessage(); const customerId = useTXPStateRead(TransactionSelectors.getContactId); const outstandingTableLines = useTXPStateRead(paymentTableSelectors.getCharges) || []; const onAmountFieldUpdated = useTXPStateWrite(TransactionActions.genericTxnUpdate); const onPaymentFieldUpdated = useTXPStateWrite( PaymentChargesTableAction.chargesTableDataUpdate ); const Items = (props: { item: OutstandingTableDataTypes; idx: number }) => { const { item, idx } = props; console.log('hello', item, idx); const txnUrl = getTxnUrl(`${item.txnType.txnTypeId}`, item.txnId); const referenceNumber = item?.referenceNumber ? `# ${item?.referenceNumber}` : ''; const amount = useTXPStateRead(TransactionSelectors.getAmount) || 0; const { closeTrowser } = useTrowserHooks(); const [isCheckedWhenPaymentAmount, setIsCheckedWhenPaymentAmount] = useState( !!item.linkedPaymentAmount ); console.log('hello2', isCheckedWhenPaymentAmount); const [paymentAmount, setPaymentAmount] = useState(item.linkedPaymentAmount); console.log('hello3', paymentAmount); const handleAmountUpdate = (amountValue: string) => { onAmountFieldUpdated({ amount: amountValue }); }; const handleCheckboxClicked = (txnId: number) => { setIsCheckedWhenPaymentAmount(!isCheckedWhenPaymentAmount); console.log('hello4', isCheckedWhenPaymentAmount, !isCheckedWhenPaymentAmount); if (!isCheckedWhenPaymentAmount) { const value = outstandingTableLines.filter((x) => x.txnId === txnId)[0].openBalance; setPaymentAmount(value.toString()); console.log('hello8', paymentAmount); const calcAmount = Number(amount) + Number(value); handleAmountUpdate(calcAmount.toString()); onPaymentFieldUpdated(txnId, { linkedPaymentAmount: value.toString(), isLinkedPaymentAmount: true }); } else { setPaymentAmount(''); const value1 = outstandingTableLines.filter((x) => x.txnId === txnId)[0] .isLinkedPaymentAmount; console.log('123', value1); if (value1) { const value = outstandingTableLines.filter((x) => x.txnId === txnId)[0] .linkedPaymentAmount; if (value) { const calcAmount = Number(amount) - Number(value); handleAmountUpdate(calcAmount.toString()); onPaymentFieldUpdated(txnId, { linkedPaymentAmount: '' }); } } } }; const handlePaymentFieldChange = (evt: React.ChangeEvent<HTMLInputElement>) => { const value = evt && evt.target.value; setPaymentAmount(value); }; const handlePaymentOnBlur = () => { setIsCheckedWhenPaymentAmount(!!paymentAmount); const oldValue = outstandingTableLines.filter((x) => x.txnId === item.txnId)[0] .linkedPaymentAmount; onPaymentFieldUpdated(item.txnId, { linkedPaymentAmount: paymentAmount, isLinkedPaymentAmount: true }); const oldPaymentAmount = oldValue ? Number(oldValue) : 0; const newPaymentAmount = paymentAmount ? Number(paymentAmount) : 0; const calcAmount = Number(amount) - oldPaymentAmount + newPaymentAmount; handleAmountUpdate(calcAmount.toString()); }; const handleNavigate = () => closeTrowser?.({ navigateTo: txnUrl, skipTrowserCloseDelay: true }); return ( <> <Table.Row key={idx} className='tableRow'> <Table.Cell className={style.checkbox}> <Checkbox aria-label={formatMessage({ id: 'charges_credits_table_select_rows', defaultMessage: 'Select rows' })} style={{ cursor: 'pointer' }} checked={isCheckedWhenPaymentAmount} onClick={() => handleCheckboxClicked(item.txnId)} title='Toggle Row Selected' /> </Table.Cell> <Table.Cell className={styles.leftAlign}> <LinkButton onClick={handleNavigate} text={`${item.txnType.txnTypeLongName} ${referenceNumber}`} />{' '} ({toLocalDateFormat(item.date)}) </Table.Cell> <Table.Cell className={styles.leftAlign}> {toLocalDateFormat(item.dueDate)} </Table.Cell> <Table.Cell className={styles.rightAlign}> {toLocalizedMoneyString(item.amount)} </Table.Cell> <Table.Cell className={styles.rightAlign}> {toLocalizedMoneyString(item.openBalance)} </Table.Cell> <Table.Cell> <TextField autoComplete='off' value={paymentAmount} aria-label={formatMessage({ id: 'charges_credits_payment_field', defaultMessage: 'Payments' })} className={styles.paymentField} onChange={handlePaymentFieldChange} onBlur={handlePaymentOnBlur} /> </Table.Cell> </Table.Row> </> ); }; return ( <div className={styles.gridWrapper}> {customerId && ( <ChargesTable header={<TransactionsTableHeader dueDateFlag />}> {(item: OutstandingTableDataTypes, idx: number) => ( <Items item={item} idx={idx} /> )} </ChargesTable> )} </div> ); }; export default enabled( { 'environment.txnType': [TransactionTypes.PURCHASE_BILL_PAYMENT] }, OutstandingTransactionsTable ); In this code what is happening that when we click the checkbox the amount add eg amount =5 but the ui checkbox is not getting checked on first click, then if we click the check box for 2nd time then it gets checked and amount gets added eg now amount will be eg amount=10, then after if uncheck the checkbox it doesn’t unchecked it for first time but amount get subtract eg now amount=5,then after we uncheck the checkbox 2nd time it gets unchecked, but the amount remains same eg amount=5, please find issue and solve it
590c696a2fc44e60fdb295b65f400c26
{ "intermediate": 0.2532687187194824, "beginner": 0.5472410917282104, "expert": 0.19949017465114594 }
1,309
In python, make a machine learning moudel to predict a 5x5 minesweeper game. You can’t make it random or make it predict 2 same results in a row if a new game is started. You have data for the past 30 games [5, 12, 13, 4, 17, 19, 4, 18, 21, 1, 6, 11, 7, 15, 22, 14, 18, 19, 1, 19, 20, 9, 16, 17, 1, 19, 20, 6, 14, 24, 15, 20, 22, 7, 18, 21, 4, 16, 23, 5, 11, 19, 5, 6, 23, 6, 12, 13, 0, 5, 15, 1, 5, 22, 0, 2, 23, 5, 10, 13, 5, 12, 17, 1, 7, 22, 7, 11, 18, 7, 8, 9, 17, 21, 24, 13, 14, 16, 2, 3, 11, 7, 17, 18, 7, 14, 21, 2, 5, 9] and you need to predict 5 safe spots. You need to use the list raw and it needs to get the same data if the mine locations are not changed. It also needs to use an algorithm that you chose thats good. The mines in the games you are gonna predict is gonna be 3
23588596b6080427b424b65b61bc13af
{ "intermediate": 0.16975520551204681, "beginner": 0.08684074133634567, "expert": 0.7434040904045105 }
1,310
соедини import cv2 import numpy as np import cvzone import math import tensorflow as tf from tensorflow.keras.models import load_model # Загрузка модели для детектирования людей human_net = cv2.dnn.readNetFromCaffe('human.prototxt', 'human.caffemodel') # Загрузка модели для детектирования одежды на людях model = load_model('trained_model.h5') # Загрузка видеопотока cap = cv2.VideoCapture(0) while True: # Чтение кадра из видеопотока ret, frame = cap.read() # Детектирование людей на кадре human_blob = cv2.dnn.blobFromImage(frame, 1/255, (416, 416), swapRB=True, crop=False) human_net.setInput(human_blob) human_detections = human_net.forward() # Детектирование одежды на кадре for i in range(human_detections.shape[2]): confidence = human_detections[0, 0, i, 2] if confidence > 0.5: x1 = int(human_detections[0, 0, i, 3] * frame.shape[1]) y1 = int(human_detections[0, 0, i, 4] * frame.shape[0]) x2 = int(human_detections[0, 0, i, 5] * frame.shape[1]) y2 = int(human_detections[0, 0, i, 6] * frame.shape[0]) clothes_blob = cv2.dnn.blobFromImage(frame[y1:y2, x1:x2], 1/255, (416, 416), swapRB=True, crop=False) model.setInput(clothes_blob) clothes_detections = model.forward() for j in range(clothes_detections.shape[2]): confidence = clothes_detections[0, 0, j, 2] if confidence > 0.5: x1_c = int(clothes_detections[0, 0, j, 3] * (x2 - x1) + x1) y1_c = int(clothes_detections[0, 0, j, 4] * (y2 - y1) + y1) x2_c = int(clothes_detections[0, 0, j, 5] * (x2 - x1) + x1) y2_c = int(clothes_detections[0, 0, j, 6] * (y2 - y1) + y1) cv2.rectangle(frame, (x1_c, y1_c), (x2_c, y2_c), (255, 0, 0), 2) cv2.rectangle(frame, (x1, y1), (x2, y2), (0, 255, 0), 2) # Отображение кадра cv2.imshow('frame', frame) if cv2.waitKey(1) & 0xFF == ord('q'): break cap.release() cv2.destroyAllWindows() с кодом import argparse import os import platform import sys from pathlib import Path import torch FILE = Path(__file__).resolve() ROOT = FILE.parents[0] # YOLOv5 root directory if str(ROOT) not in sys.path: sys.path.append(str(ROOT)) # add ROOT to PATH ROOT = Path(os.path.relpath(ROOT, Path.cwd())) # relative from models.common import DetectMultiBackend from utils.dataloaders import IMG_FORMATS, VID_FORMATS, LoadImages, LoadScreenshots, LoadStreams from utils.general import (LOGGER, Profile, check_file, check_img_size, check_imshow, check_requirements, colorstr, cv2, increment_path, non_max_suppression, print_args, scale_boxes, strip_optimizer, xyxy2xywh) from utils.plots import Annotator, colors, save_one_box from utils.torch_utils import select_device, smart_inference_mode @smart_inference_mode() def run( weights=ROOT / 'yolov5s.pt', # model path or triton URL source=ROOT / 'data/images', # file/dir/URL/glob/screen/0(webcam) data=ROOT / 'data/coco128.yaml', # dataset.yaml path imgsz=(640, 640), # inference size (height, width) conf_thres=0.25, # confidence threshold iou_thres=0.45, # NMS IOU threshold max_det=1000, # maximum detections per image device='', # cuda device, i.e. 0 or 0,1,2,3 or cpu view_img=False, # show results save_txt=False, # save results to *.txt save_conf=False, # save confidences in --save-txt labels save_crop=False, # save cropped prediction boxes nosave=False, # do not save images/videos classes=None, # filter by class: --class 0, or --class 0 2 3 agnostic_nms=False, # class-agnostic NMS augment=False, # augmented inference visualize=False, # visualize features update=False, # update all models project=ROOT / 'runs/detect', # save results to project/name name='exp', # save results to project/name exist_ok=False, # existing project/name ok, do not increment line_thickness=3, # bounding box thickness (pixels) hide_labels=False, # hide labels hide_conf=False, # hide confidences half=False, # use FP16 half-precision inference dnn=False, # use OpenCV DNN for ONNX inference vid_stride=1, # video frame-rate stride ): source = str(source) save_img = not nosave and not source.endswith('.txt') # save inference images is_file = Path(source).suffix[1:] in (IMG_FORMATS + VID_FORMATS) is_url = source.lower().startswith(('rtsp://', 'rtmp://', 'http://', 'https://')) webcam = source.isnumeric() or source.endswith('.streams') or (is_url and not is_file) screenshot = source.lower().startswith('screen') if is_url and is_file: source = check_file(source) # download # Directories save_dir = increment_path(Path(project) / name, exist_ok=exist_ok) # increment run (save_dir / 'labels' if save_txt else save_dir).mkdir(parents=True, exist_ok=True) # make dir # Load model device = select_device(device) model = DetectMultiBackend(weights, device=device, dnn=dnn, data=data, fp16=half) stride, names, pt = model.stride, model.names, model.pt imgsz = check_img_size(imgsz, s=stride) # check image size # Dataloader bs = 1 # batch_size if webcam: view_img = check_imshow(warn=True) dataset = LoadStreams(source, img_size=imgsz, stride=stride, auto=pt, vid_stride=vid_stride) bs = len(dataset) elif screenshot: dataset = LoadScreenshots(source, img_size=imgsz, stride=stride, auto=pt) else: dataset = LoadImages(source, img_size=imgsz, stride=stride, auto=pt, vid_stride=vid_stride) vid_path, vid_writer = [None] * bs, [None] * bs # Run inference model.warmup(imgsz=(1 if pt or model.triton else bs, 3, *imgsz)) # warmup seen, windows, dt = 0, [], (Profile(), Profile(), Profile()) for path, im, im0s, vid_cap, s in dataset: with dt[0]:
7bea4aa8bf23dadf41561a8944d070a8
{ "intermediate": 0.3245014548301697, "beginner": 0.3296402394771576, "expert": 0.3458583354949951 }
1,311
import random artists_listeners = { '$NOT': 7781046, '21 Savage': 60358167, 'Yungeen Ace': 1294188, } keys = list(artists_listeners.keys()) score = 0 while True: first_artist = random.choice(keys) second_artist = random.choice(keys) while first_artist == second_artist: second_artist = random.choice(keys) while True: guess = input(f"\nWhich artist has more monthly Spotify listeners - 1. {first_artist.title()} or 2. {second_artist.title()}? ") guess_lower = guess.strip().lower() if guess_lower == 'quit': print("Thanks for playing!") quit() elif guess_lower != first_artist.lower() and guess_lower != second_artist.lower(): print("Invalid input. Please enter the name of one of the two artists or 'quit' to end the game.") elif guess_lower == first_artist.lower() and artists_listeners[first_artist] > artists_listeners[second_artist]: print(f"You guessed correctly! {first_artist.title()} had {int(artists_listeners[first_artist] / 1e6):,}M monthly Spotify listeners and {second_artist.title()} has {int(artists_listeners[second_artist] / 1e6):,}M monthly Spotify listeners.") score += 1 break elif guess_lower == second_artist.lower() and artists_listeners[second_artist] > artists_listeners[first_artist]: print(f"You guessed correctly! {second_artist.title()} had {int(artists_listeners[second_artist] / 1e6):,}M monthly Spotify listeners and {first_artist.title()} has {int(artists_listeners[first_artist] / 1e6):,}M monthly Spotify listeners.") score += 1 break else: print(f"\nSorry, you guessed incorrectly. {first_artist.title()} had {int(artists_listeners[first_artist] / 1e6):,}M monthly Spotify listeners and {second_artist.title()} has {int(artists_listeners[second_artist] / 1e6):,}M monthly Spotify listeners.\n") score = 0 first_artist = random.choice(keys) # Generate new artists second_artist = random.choice(keys) while first_artist == second_artist: second_artist = random.choice(keys) play_again = input("Would you like to play again? (y/n) ") if play_again.lower() == 'n': print("Thanks for playing!") quit() print(f"\nYour score is {score}.") now the game just repeats the question after making a mistake
63c769cb5cf1a12e26f9bec41a1d89aa
{ "intermediate": 0.3032929599285126, "beginner": 0.44143515825271606, "expert": 0.25527191162109375 }
1,312
How to create a spell array with values for java
f46ba92bbc4b23aa99b1a1977098676b
{ "intermediate": 0.4694095253944397, "beginner": 0.30383017659187317, "expert": 0.22676026821136475 }
1,313
In python, make a machine learning moudel to predict a 5x5 minesweeper game. You can’t make it random or make it predict 2 same results in a row if a new game is started. You have data for the past 30 games [5, 12, 13, 4, 17, 19, 4, 18, 21, 1, 6, 11, 7, 15, 22, 14, 18, 19, 1, 19, 20, 9, 16, 17, 1, 19, 20, 6, 14, 24, 15, 20, 22, 7, 18, 21, 4, 16, 23, 5, 11, 19, 5, 6, 23, 6, 12, 13, 0, 5, 15, 1, 5, 22, 0, 2, 23, 5, 10, 13, 5, 12, 17, 1, 7, 22, 7, 11, 18, 7, 8, 9, 17, 21, 24, 13, 14, 16, 2, 3, 11, 7, 17, 18, 7, 14, 21, 2, 5, 9] and you need to predict 5 safe spots. You need to use the list raw and it needs to get the same data if the mine locations are not changed. It also needs to use an algorithm that you chose thats good. The mines in the games you are gonna predict is gonna be 3
a56a1d0250f96ec5bfc3d12dce246a8b
{ "intermediate": 0.16975520551204681, "beginner": 0.08684074133634567, "expert": 0.7434040904045105 }
1,314
act like a quantitative phd scientist in finance and using Using concepts and hierarchies to create an ontological framework create a script in python to forecast the price of bitcoin for the next 8 days in advance from todays date
5a62c82a0807034f232478bac3525dd7
{ "intermediate": 0.6039307713508606, "beginner": 0.17006248235702515, "expert": 0.22600676119327545 }
1,315
I need to write a python script to extract information from a file, e.g., cat_0.log:
8583c1f4ca83d919ddc38635ec659620
{ "intermediate": 0.45287150144577026, "beginner": 0.21036773920059204, "expert": 0.3367607891559601 }
1,316
electric conductivity symbol
1e40daf798b5405d9203ea963c605acf
{ "intermediate": 0.4304223358631134, "beginner": 0.33384817838668823, "expert": 0.23572948575019836 }
1,317
упрости этот код: let scene; let camera; let renderer; function scene_setup() { scene = new THREE.Scene(); camera = new THREE.PerspectiveCamera(75, window.innerWidth / window.innerHeight, 0.1, 1000); renderer = new THREE.WebGLRenderer(); renderer.setSize(window.innerWidth, window.innerHeight); document.body.appendChild(renderer.domElement); } scene_setup(); const shaderCode = document.getElementById("fragShader").innerHTML; const textureURL = "Frame 1948755167.png"; THREE.ImageUtils.crossOrigin = ''; const texture = THREE.ImageUtils.loadTexture(textureURL); let uniforms = { light: {type:'v3', value: new THREE.Vector3()}, tex: { type:'t', value:texture }, res: { type:'v2', value:new THREE.Vector2(window.innerWidth,window.innerHeight)} }; let material = new THREE.ShaderMaterial({uniforms:uniforms, fragmentShader:shaderCode}); let geometry = new THREE.PlaneGeometry(10,10); let sprite = new THREE.Mesh(geometry, material); scene.add(sprite); camera.position.z = 2; uniforms.light.value.z = 50; function render() { renderer.setSize(window.innerWidth, window.innerHeight); requestAnimationFrame( render ); renderer.render( scene, camera ); } render(); document.onmousemove = function(event) { uniforms.light.value.x = event.clientX; uniforms.light.value.y = -event.clientY + window.innerHeight; }
76039ef8e83a33633e2333305013df60
{ "intermediate": 0.4736354351043701, "beginner": 0.23881596326828003, "expert": 0.2875485420227051 }
1,318
Есть следующий код, требует выполнить следующее:По результатам параллельной обработки 10 различных изображений построить график зависимости времени работы алгоритма от площади изображения. Код: using SelectionSections; using System; using System.Collections.Generic; using System.ComponentModel; using System.Diagnostics; using System.Drawing; using System.IO; using System.Linq; using System.Windows.Forms; namespace ImageEditing { public partial class Form1 : Form { private List<BackgroundWorker> workers = new List<BackgroundWorker>(); BackgroundWorker worker = new BackgroundWorker(); public Form1() { InitializeComponent(); openFileDialog.Filter = "PNG Изображения (*.png)|*.png|Все файлы(*.*)|*.*"; saveFileDialog.Filter = "PNG Изображения (*.png)|*.png|Все файлы(*.*)|*.*"; openFileDialog.Multiselect = true; for (int i = 0; i < 10; i++) { worker.WorkerReportsProgress = true; worker.DoWork += Worker_DoWork; worker.ProgressChanged += Worker_ProgressChanged; worker.RunWorkerCompleted += Worker_RunWorkerCompleted; workers.Add(worker); } } private void openButton_Click(object sender, EventArgs e) { if (openFileDialog.ShowDialog() == DialogResult.Cancel) return; int n = 0; foreach (string fileName in openFileDialog.FileNames) { sourceListBox.Items.Add(fileName); } } private void Worker_DoWork(object sender, DoWorkEventArgs e) { List<object> arguments = (List<object>)e.Argument; Bitmap image = (Bitmap)arguments[0]; string filename = (string)arguments[1]; int width = image.Width; int height = image.Height; ProgressDelegate progress = UpdateProgressBar; SortedList<string, object> parametrs = new SortedList<string, object> { { "source", (Bitmap) image }, { "threshold", (double) 10 } }; GrowSection growSection = new GrowSection(); growSection.Init(parametrs); Stopwatch stopwatch = Stopwatch.StartNew(); growSection.StartHandle(progress); stopwatch.Stop(); e.Result = new List<object> { growSection.Result, filename, width, height, stopwatch.ElapsedMilliseconds }; } private void Worker_ProgressChanged(object sender, ProgressChangedEventArgs e) { //if (sectionProgressBar.InvokeRequired) //{ // sectionProgressBar.BeginInvoke(new Action(() => { sectionProgressBar.Value = e.ProgressPercentage; })); //} //else //{ // sectionProgressBar.Value = e.ProgressPercentage; //} } private void Worker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e) { List<object> results = (List<object>)e.Result; Bitmap outputImage = (Bitmap)results[0]; string filename = (string)results[1]; int width = (int)results[2]; int height = (int)results[3]; long processingTime = (long)results[4]; // Save the output image string outputFilename = Path.GetFileNameWithoutExtension(filename) + "_processed.png"; outputImage.Save(outputFilename); resultListBox.Invoke(new Action(()=> resultListBox.Items.Add(new ImageListBoxItem { Text = $"{filename} {width} {height} {processingTime} ms", Image1 = new Bitmap(filename), Image2 = outputImage }))); BackgroundWorker worker = (BackgroundWorker)sender; workers.Remove(worker); } private void saveButton_Click(object sender, EventArgs e) { } private void UpdateProgressBar(double percent) { //if (sectionProgressBar.InvokeRequired) //{ // sectionProgressBar.BeginInvoke(new Action(() => { sectionProgressBar.Value = (int)System.Math.Round((decimal)percent); })); //} //else //{ // sectionProgressBar.Value = (int)System.Math.Round((decimal)percent); //} } private void progressListBox_SelectedIndexChanged(object sender, EventArgs e) { if (resultListBox.SelectedItem != null) { ImageListBoxItem selectedItem = resultListBox.SelectedItem as ImageListBoxItem; } } private void generateButton_Click(object sender, EventArgs e) { BackgroundWorker secondWorker = new BackgroundWorker(); secondWorker.DoWork += SecondWorker_DoWork; secondWorker.RunWorkerAsync(); } private void SecondWorker_DoWork(object sender, DoWorkEventArgs e) { int n = 0; while (n < sourceListBox.Items.Count) { var work = workers.FirstOrDefault(f => f.IsBusy == false); if (work != null) { Bitmap image = new Bitmap(openFileDialog.FileNames[n]); List<object> arguments = new List<object>(); arguments.Add(image); arguments.Add(openFileDialog.FileNames[n]); work.RunWorkerAsync(arguments); n++; } } } public class ImageListBoxItem { public string Text { get; set; } public System.Drawing.Image Image1 { get; set; } public System.Drawing.Image Image2 { get; set; } public override string ToString() { return Text; } } } }
bb7f3c6b93075a974bf8330a42bce12d
{ "intermediate": 0.36094051599502563, "beginner": 0.5260608792304993, "expert": 0.1129985824227333 }
1,319
modify this code so if the web browser is refreshed, we dont loose the data from the current session: packages <- c( "tidyverse", "shiny", "shinydashboard", "shinyFiles", "shinyWidgets", "shinythemes","RColorBrewer","ggthemes","plotly","shinyBS","processx" ) #Now load or install&load all packages package.check <- lapply( packages, FUN = function(x) { if (!require(x, character.only = TRUE)) { #install.packages(x, dependencies = TRUE) library(x, character.only = TRUE,lib.loc="/home/pxl10/R/x86_64-pc-linux-gnu-library/4.2/") } } ) options(shiny.port = 3142) options(shiny.host = "10.50.156.93") loci <- "" sample_list <- ("") ui <- dashboardPage( skin = "red", dashboardHeader(title = "Nanopore TB tNGS Assay",titleWidth = 300), ###side tab setup dashboardSidebar( width = 300, br(),br(), ### shinyFiles::shinyDirButton("test_dir_select",label = "Select Nanopore Run Folder",title = "Directory selection",icon = shiny::icon("folder")), shiny::htmlOutput("test_dir_select_ready") ,br(),br(), fileInput(inputId = "file_sample",label = "Select Sample Sheet",multiple = FALSE), br(), selectizeInput(inputId = "workflow",label = "Select Amplicon Workflow",choices = c("Main AR Targets", "Extended AR Targets"),multiple = FALSE),br(), selectizeInput(inputId = "flowcell",label = "Flow Cell type",choices = c("R9","R10"),multiple = FALSE),br(), textInput("run_name", label="Enter Run Name", "", width = "600px"),br(),br(),br(),br(),br(),br(),br(),br(), bsButton(inputId = "go", width = "250px",label = " Start Pipeline", icon = icon("play-circle"), style = "success") ), dashboardBody( fluidRow( tabBox( # The id lets us use input$tabset1 on the server to find the current tab id = "tabset1", height = "1100px",width=12, tabPanel(title = "tNGS AMR Targets", # Select sample fluidRow( column(2, (selectInput(inputId = "sample", label = "Sample:",choices = sample_list, selected = sample_list[1])))), fluidRow( column(2, h3("Loci Status:"), tableOutput('table'),br(), actionButton(inputId = "markdown_display", label = "Show Full Report", width = "300px",height = "100px") ,br(), h3("Time of last Analyses:"),br(), tableOutput('stamp')), column(9,offset = 0, plotlyOutput("plot", height = "800px", width = "100%")))), ) )) ) #################################################################################################################################### #################################################################################################################################### #################################################################################################################################### ####### server side of things ####### ready_to_start <- 0 makeReactiveBinding("ready_to_start") server <- function(input, output, session) { whichbutton <- reactiveVal(TRUE) cancelbutton <- reactiveVal(TRUE) pid <- 0 ###download button### ### not working ### def_reports_roots <- c(home = "/") shinyFileChoose(input, 'file_outputs', roots = def_reports_roots) observeEvent(input$download_button, { print (paste("pushed...")) output$file_outputs <- downloadHandler( filename <- function() { paste("output", "zip", sep=".") }, content <- function(file) { file.copy("/home/pxl10/out.zip", file) }, contentType = "application/zip" ) }) ## start/stop button actions ##### Cancel Button blocks ###### observeEvent(input$go, { if (whichbutton()) { showModal(modalDialog( title = "Retrieving data file", h3("Please wait for file to be generated!"), easyClose = FALSE, footer = tagList( actionButton("cancel", "Cancel")))) } whichbutton(!whichbutton()) }) ### Cancel button actions ##### observeEvent(input$cancel, { whichbutton(!whichbutton()) cancelbutton(!cancelbutton()) ready_to_start <- 0 updateButton(session,inputId = "go",label = " Start Pipeline",icon = icon("play-circle"),style = "success") system(paste("kill -9 ",pid)) removeModal() showModal(modalDialog( title = "Success!", paste0("The pipeline has been successfully terminated."), easyClose = TRUE, footer = NULL )) session$reload() path <- "NULL" }) ## select directory button def_roots <- c(home = "/local") shinyFiles::shinyDirChoose(input, 'test_dir_select', roots = def_roots) test_dir_select_ready <- shiny::reactive({ if(length(input$test_dir_select) == 1) { path <- "Directory not yet selected" } else { path <- file.path( shinyFiles::parseDirPath(def_roots, input$test_dir_select) ) } return(path) }) output$test_dir_select_ready <- shiny::renderUI({ shiny::HTML("<font color=\"white\">", test_dir_select_ready(), "</font>") }) ## Select sample sheet button def_sheet_roots <- c(home = "/") shinyFileChoose(input, 'file_sample', roots = def_sheet_roots) sample_sheet_ready <- shiny::reactive({ if(length(input$file_sample) == 1) { path_sheet <- "Sample Sheet not selected" } else { path_sheet <- file.path( shinyFiles::parseFilePaths(def_sheet_roots, input$file_sample)$datapath ) } return(path_sheet) }) output$sample_sheet_ready <- shiny::renderUI({ shiny::HTML("<font color=\"white\">", sample_sheet_ready(), "</font>") }) ### Trigger event Start/Stop Button observe({ if (!whichbutton()) { if(length(input$file_sample) == 0) { samplesheet <- "NULL" } else { samplesheet <- input$file_sample[4] ### need to check integrity of the sample sheet } if(length(input$test_dir_select) == 1) { path <- "NULL" } else { path <- file.path( shinyFiles::parseDirPath(def_roots, input$test_dir_select) ) } if (input$workflow == "Main AR Targets") { xworkflow <- "main_line" } else { xworkflow <- "extended" } if (input$run_name == "") { ##my_run_name <- "NULL" ### get run name from fasq path ### parts <- strsplit(path, "/")[[1]] my_run_name <- parts[4] fn <- paste0("/local/tNGS_TB/FASTQ/",my_run_name,"/locus_depth.txt") } else { my_run_name <- input$run_name fn <- paste0("/local/tNGS_TB/FASTQ/",my_run_name,"/locus_depth.txt") } # verify if fastq path given. if true, close and start pipeline if(path == "NULL") { whichbutton(!whichbutton()) # show pop-up ... showModal(modalDialog( title = "Oh no!", paste0("You have not selected a valid MinION FastQ repository, silly person!"), easyClose = TRUE, footer = NULL )) } else { updateButton(session,inputId = "go",label = " Stop Pipeline",icon = icon("stop-circle"),style = "danger") timestamp <- paste0("/local/tNGS_TB/FASTQ/",my_run_name,"/timestamp.txt") loci <- paste0("/local/tNGS_TB/FASTQ/",my_run_name,"/Loci_status_main.txt") print (paste(timestamp)) rundir <- (paste0("/local/tNGS_TB/FASTQ/",my_run_name)) if (dir.exists(rundir)) { system(paste("rm -r",rundir)) } if(samplesheet != "NULL") { sheet_renamed <- paste0("sample_sheet_",my_run_name,".txt") system(paste0("cp ",samplesheet," /local/tNGS_TB/sample_sheet_tmp/",sheet_renamed)) #system(paste("cp ",samplesheet,sheet_renamed)) #system (paste("rm",samplesheet)) samplesheet <- sheet_renamed } # Open the output file in write mode print(paste("/local/tNGS_TB/Real-time_wrapper/Amplicon_RT_analyzer_V0.4.3.pl -FASTQ", path ,"-Sheet",samplesheet,"-RUN", my_run_name," -Kit Auto -Flowcell", input$flowcell,"-Workflow", xworkflow,">","/local/tNGS_TB/Rlog.txt")) p <- process$new("/local/tNGS_TB/Real-time_wrapper/Amplicon_RT_analyzer_V0.4.3.pl",c("-FASTQ", path ,"-Sheet", samplesheet,"-RUN", my_run_name,"-Kit", "Auto", "-Flowcell", input$flowcell,"-Workflow", xworkflow,">","/local/tNGS_TB/Rlog.txt")) pid <<- p$get_pid() print(pid) ready_to_start <<- 2 } if ((!whichbutton()) && (ready_to_start==2)) { data_timestamp <- reactiveFileReader( intervalMillis = 100, session = NULL, filePath = timestamp, readFunc = function(filePath) { read.csv(filePath,header = TRUE, stringsAsFactors=FALSE) } ) loci_data_manipulated <- reactiveFileReader( intervalMillis = 100, session = NULL, filePath = loci, readFunc = function(filePath) { read.csv(filePath,header = TRUE, stringsAsFactors=FALSE) } ) observeEvent(input$markdown_display, { #filename <- paste0("/local/tNGS_TB/FASTQ/",my_run_name,"/",input$sample,"_Report.pdf") # report <- paste0("/local/tNGS_TB/FASTQ/") filename <- paste0("my_pdf_resource/",my_run_name,"/",input$sample,"_Report.pdf") print (paste("xxxx ",filename)) addResourcePath(prefix = "my_pdf_resource", directoryPath = report) showModal(modalDialog(size="l",renderUI({ tags$iframe(style="height:650px; width:100%", src = filename)}), easyClose = TRUE)) }) ## wait for file to exists observe({ if ((!file.exists(fn)) && !whichbutton() && ready_to_start==2) { invalidateLater(1000, session) } ## when file present, if ((file.exists(fn)) && !whichbutton() && ready_to_start==2) { removeModal() data_manipulated <- reactiveFileReader( intervalMillis = 100, session = NULL, filePath = fn, readFunc = function(filePath) { read.csv(filePath,header = TRUE, stringsAsFactors=FALSE) } ) output$stamp <- renderTable({ data_timestamp() }) output$table <- renderTable({ xdata <- subset(loci_data_manipulated(), sample %in% input$sample) xdata[,3] <- as.integer(xdata[,3]) data <- xdata[,2:4] }) sample_original <- read.csv(fn, header = TRUE, stringsAsFactors=FALSE) sample_list <- unique(sample_original$sample) updateSelectInput(session, inputId = "sample", choices = sample_list, selected = sample_list[1]) ### Original target plot # Replace the `renderPlot()` with the plotly version output$plot <- renderPlotly({ # Convert the existing ggplot2 to a plotly plot ggplotly({ data <- subset(data_manipulated(), sample %in% input$sample ) p <- ggplot(data, aes(x = position, y = depth, group = sample, colour = gene)) + geom_line(linewidth=.3) + facet_wrap( ~ gene, ncol=4, nrow=4, scales = "free", shrink = FALSE) + theme_few() + theme(legend.position="none", strip.text = element_text(face="bold", size = 14), plot.title = element_text(face = "bold"), panel.spacing.y = unit(-0.4, "lines"), panel.spacing.x = unit(-0.4, "lines")) + scale_color_tableau("Tableau 20") + ylab("") + xlab("") + ggtitle(paste('Sample ',input$sample, sep='')) }) %>% config(p, displaylogo = FALSE) }) } }) } } ## if whichbutton }) ## end observe loop observe ({ if ((whichbutton()) && ready_to_start==2) { ### when stop button is pressed if (pid > 0) { system(paste("kill -9 ",pid)) pid <<- 0 } ready_to_start <<- 0 updateButton(session,inputId = "go",label = " Start Pipeline",icon = icon("play-circle"),style = "success") showModal(modalDialog( title = "Success!", paste0("The pipeline has been successfully terminated."), easyClose = TRUE, footer = NULL )) ## stop pipeline at the system level session$reload() path <- "NULL" } }) } shinyApp(ui, server)
30c14acc9022948062163a8409d0e482
{ "intermediate": 0.3928505778312683, "beginner": 0.3575951159000397, "expert": 0.24955427646636963 }
1,320
modify this code so if the web browser is refreshed, we dont loose the data from the current session: packages <- c( "tidyverse", "shiny", "shinydashboard", "shinyFiles", "shinyWidgets", "shinythemes","RColorBrewer","ggthemes","plotly","shinyBS","processx" ) #Now load or install&load all packages package.check <- lapply( packages, FUN = function(x) { if (!require(x, character.only = TRUE)) { #install.packages(x, dependencies = TRUE) library(x, character.only = TRUE,lib.loc="/home/pxl10/R/x86_64-pc-linux-gnu-library/4.2/") } } ) options(shiny.port = 3142) options(shiny.host = "10.50.156.93") loci <- "" sample_list <- ("") ui <- dashboardPage( skin = "red", dashboardHeader(title = "Nanopore TB tNGS Assay",titleWidth = 300), ###side tab setup dashboardSidebar( width = 300, br(),br(), ### shinyFiles::shinyDirButton("test_dir_select",label = "Select Nanopore Run Folder",title = "Directory selection",icon = shiny::icon("folder")), shiny::htmlOutput("test_dir_select_ready") ,br(),br(), fileInput(inputId = "file_sample",label = "Select Sample Sheet",multiple = FALSE), br(), selectizeInput(inputId = "workflow",label = "Select Amplicon Workflow",choices = c("Main AR Targets", "Extended AR Targets"),multiple = FALSE),br(), selectizeInput(inputId = "flowcell",label = "Flow Cell type",choices = c("R9","R10"),multiple = FALSE),br(), textInput("run_name", label="Enter Run Name", "", width = "600px"),br(),br(),br(),br(),br(),br(),br(),br(), bsButton(inputId = "go", width = "250px",label = " Start Pipeline", icon = icon("play-circle"), style = "success") ), dashboardBody( fluidRow( tabBox( # The id lets us use input$tabset1 on the server to find the current tab id = "tabset1", height = "1100px",width=12, tabPanel(title = "tNGS AMR Targets", # Select sample fluidRow( column(2, (selectInput(inputId = "sample", label = "Sample:",choices = sample_list, selected = sample_list[1])))), fluidRow( column(2, h3("Loci Status:"), tableOutput('table'),br(), actionButton(inputId = "markdown_display", label = "Show Full Report", width = "300px",height = "100px") ,br(), h3("Time of last Analyses:"),br(), tableOutput('stamp')), column(9,offset = 0, plotlyOutput("plot", height = "800px", width = "100%")))), ) )) ) #################################################################################################################################### #################################################################################################################################### #################################################################################################################################### ####### server side of things ####### ready_to_start <- 0 makeReactiveBinding("ready_to_start") server <- function(input, output, session) { whichbutton <- reactiveVal(TRUE) cancelbutton <- reactiveVal(TRUE) pid <- 0 ###download button### ### not working ### def_reports_roots <- c(home = "/") shinyFileChoose(input, 'file_outputs', roots = def_reports_roots) observeEvent(input$download_button, { print (paste("pushed...")) output$file_outputs <- downloadHandler( filename <- function() { paste("output", "zip", sep=".") }, content <- function(file) { file.copy("/home/pxl10/out.zip", file) }, contentType = "application/zip" ) }) ## start/stop button actions ##### Cancel Button blocks ###### observeEvent(input$go, { if (whichbutton()) { showModal(modalDialog( title = "Retrieving data file", h3("Please wait for file to be generated!"), easyClose = FALSE, footer = tagList( actionButton("cancel", "Cancel")))) } whichbutton(!whichbutton()) }) ### Cancel button actions ##### observeEvent(input$cancel, { whichbutton(!whichbutton()) cancelbutton(!cancelbutton()) ready_to_start <- 0 updateButton(session,inputId = "go",label = " Start Pipeline",icon = icon("play-circle"),style = "success") system(paste("kill -9 ",pid)) removeModal() showModal(modalDialog( title = "Success!", paste0("The pipeline has been successfully terminated."), easyClose = TRUE, footer = NULL )) session$reload() path <- "NULL" }) ## select directory button def_roots <- c(home = "/local") shinyFiles::shinyDirChoose(input, 'test_dir_select', roots = def_roots) test_dir_select_ready <- shiny::reactive({ if(length(input$test_dir_select) == 1) { path <- "Directory not yet selected" } else { path <- file.path( shinyFiles::parseDirPath(def_roots, input$test_dir_select) ) } return(path) }) output$test_dir_select_ready <- shiny::renderUI({ shiny::HTML("<font color=\"white\">", test_dir_select_ready(), "</font>") }) ## Select sample sheet button def_sheet_roots <- c(home = "/") shinyFileChoose(input, 'file_sample', roots = def_sheet_roots) sample_sheet_ready <- shiny::reactive({ if(length(input$file_sample) == 1) { path_sheet <- "Sample Sheet not selected" } else { path_sheet <- file.path( shinyFiles::parseFilePaths(def_sheet_roots, input$file_sample)$datapath ) } return(path_sheet) }) output$sample_sheet_ready <- shiny::renderUI({ shiny::HTML("<font color=\"white\">", sample_sheet_ready(), "</font>") }) ### Trigger event Start/Stop Button observe({ if (!whichbutton()) { if(length(input$file_sample) == 0) { samplesheet <- "NULL" } else { samplesheet <- input$file_sample[4] ### need to check integrity of the sample sheet } if(length(input$test_dir_select) == 1) { path <- "NULL" } else { path <- file.path( shinyFiles::parseDirPath(def_roots, input$test_dir_select) ) } if (input$workflow == "Main AR Targets") { xworkflow <- "main_line" } else { xworkflow <- "extended" } if (input$run_name == "") { ##my_run_name <- "NULL" ### get run name from fasq path ### parts <- strsplit(path, "/")[[1]] my_run_name <- parts[4] fn <- paste0("/local/tNGS_TB/FASTQ/",my_run_name,"/locus_depth.txt") } else { my_run_name <- input$run_name fn <- paste0("/local/tNGS_TB/FASTQ/",my_run_name,"/locus_depth.txt") } # verify if fastq path given. if true, close and start pipeline if(path == "NULL") { whichbutton(!whichbutton()) # show pop-up ... showModal(modalDialog( title = "Oh no!", paste0("You have not selected a valid MinION FastQ repository, silly person!"), easyClose = TRUE, footer = NULL )) } else { updateButton(session,inputId = "go",label = " Stop Pipeline",icon = icon("stop-circle"),style = "danger") timestamp <- paste0("/local/tNGS_TB/FASTQ/",my_run_name,"/timestamp.txt") loci <- paste0("/local/tNGS_TB/FASTQ/",my_run_name,"/Loci_status_main.txt") print (paste(timestamp)) rundir <- (paste0("/local/tNGS_TB/FASTQ/",my_run_name)) if (dir.exists(rundir)) { system(paste("rm -r",rundir)) } if(samplesheet != "NULL") { sheet_renamed <- paste0("sample_sheet_",my_run_name,".txt") system(paste0("cp ",samplesheet," /local/tNGS_TB/sample_sheet_tmp/",sheet_renamed)) #system(paste("cp ",samplesheet,sheet_renamed)) #system (paste("rm",samplesheet)) samplesheet <- sheet_renamed } # Open the output file in write mode print(paste("/local/tNGS_TB/Real-time_wrapper/Amplicon_RT_analyzer_V0.4.3.pl -FASTQ", path ,"-Sheet",samplesheet,"-RUN", my_run_name," -Kit Auto -Flowcell", input$flowcell,"-Workflow", xworkflow,">","/local/tNGS_TB/Rlog.txt")) p <- process$new("/local/tNGS_TB/Real-time_wrapper/Amplicon_RT_analyzer_V0.4.3.pl",c("-FASTQ", path ,"-Sheet", samplesheet,"-RUN", my_run_name,"-Kit", "Auto", "-Flowcell", input$flowcell,"-Workflow", xworkflow,">","/local/tNGS_TB/Rlog.txt")) pid <<- p$get_pid() print(pid) ready_to_start <<- 2 } if ((!whichbutton()) && (ready_to_start==2)) { data_timestamp <- reactiveFileReader( intervalMillis = 100, session = NULL, filePath = timestamp, readFunc = function(filePath) { read.csv(filePath,header = TRUE, stringsAsFactors=FALSE) } ) loci_data_manipulated <- reactiveFileReader( intervalMillis = 100, session = NULL, filePath = loci, readFunc = function(filePath) { read.csv(filePath,header = TRUE, stringsAsFactors=FALSE) } ) observeEvent(input$markdown_display, { #filename <- paste0("/local/tNGS_TB/FASTQ/",my_run_name,"/",input$sample,"_Report.pdf") # report <- paste0("/local/tNGS_TB/FASTQ/") filename <- paste0("my_pdf_resource/",my_run_name,"/",input$sample,"_Report.pdf") print (paste("xxxx ",filename)) addResourcePath(prefix = "my_pdf_resource", directoryPath = report) showModal(modalDialog(size="l",renderUI({ tags$iframe(style="height:650px; width:100%", src = filename)}), easyClose = TRUE)) }) ## wait for file to exists observe({ if ((!file.exists(fn)) && !whichbutton() && ready_to_start==2) { invalidateLater(1000, session) } ## when file present, if ((file.exists(fn)) && !whichbutton() && ready_to_start==2) { removeModal() data_manipulated <- reactiveFileReader( intervalMillis = 100, session = NULL, filePath = fn, readFunc = function(filePath) { read.csv(filePath,header = TRUE, stringsAsFactors=FALSE) } ) output$stamp <- renderTable({ data_timestamp() }) output$table <- renderTable({ xdata <- subset(loci_data_manipulated(), sample %in% input$sample) xdata[,3] <- as.integer(xdata[,3]) data <- xdata[,2:4] }) sample_original <- read.csv(fn, header = TRUE, stringsAsFactors=FALSE) sample_list <- unique(sample_original$sample) updateSelectInput(session, inputId = "sample", choices = sample_list, selected = sample_list[1]) ### Original target plot # Replace the `renderPlot()` with the plotly version output$plot <- renderPlotly({ # Convert the existing ggplot2 to a plotly plot ggplotly({ data <- subset(data_manipulated(), sample %in% input$sample ) p <- ggplot(data, aes(x = position, y = depth, group = sample, colour = gene)) + geom_line(linewidth=.3) + facet_wrap( ~ gene, ncol=4, nrow=4, scales = "free", shrink = FALSE) + theme_few() + theme(legend.position="none", strip.text = element_text(face="bold", size = 14), plot.title = element_text(face = "bold"), panel.spacing.y = unit(-0.4, "lines"), panel.spacing.x = unit(-0.4, "lines")) + scale_color_tableau("Tableau 20") + ylab("") + xlab("") + ggtitle(paste('Sample ',input$sample, sep='')) }) %>% config(p, displaylogo = FALSE) }) } }) } } ## if whichbutton }) ## end observe loop observe ({ if ((whichbutton()) && ready_to_start==2) { ### when stop button is pressed if (pid > 0) { system(paste("kill -9 ",pid)) pid <<- 0 } ready_to_start <<- 0 updateButton(session,inputId = "go",label = " Start Pipeline",icon = icon("play-circle"),style = "success") showModal(modalDialog( title = "Success!", paste0("The pipeline has been successfully terminated."), easyClose = TRUE, footer = NULL )) ## stop pipeline at the system level session$reload() path <- "NULL" } }) } shinyApp(ui, server)
1d1a065f67450d1fd542fcb262a9afa9
{ "intermediate": 0.3928505778312683, "beginner": 0.3575951159000397, "expert": 0.24955427646636963 }
1,321
ok please give me your complete IQ and focus, in this application below I have linked it to a database which contains username|password|fullname|email|address| and just recently I wanted to change my program and project completely, so instead for checking manually if the user logging in is an ADMIN OR CUSTOMER i instead added a new column to my database where they can either be "Customer" or "Admin" now my database columns look like this username|password|fullname|email|address|User Type| please change both my Form1.cs and RegistrationForm.cs to do this validation and adjust anything that the new column might affect. please make sure that my program gets no errors and all checks for admins are done by checking that column in thatt database. also in the registration form make sure that the User Type column is automatically is set to "Customer" my code: Form1.cs: using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Runtime.Remoting.Lifetime; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; using System.Data.OleDb; using static System.Windows.Forms.VisualStyles.VisualStyleElement.Button; namespace ApplianceRental { public partial class Form1 : Form { public Form1() { InitializeComponent(); OleDbConnection con = new OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=db_users.mdb"); OleDbCommand cmd = new OleDbCommand(); OleDbDataAdapter da = new OleDbDataAdapter(); } //connects to database OleDbConnection con = new OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=db_users.mdb"); OleDbCommand cmd = new OleDbCommand(); OleDbDataAdapter da = new OleDbDataAdapter(); private void Form1_Load(object sender, EventArgs e) { } // Add a counter variable or class level property private int failedAttempts = 0; private void button1_Click(object sender, EventArgs e) { string username = textBox1.Text; string password = textBox2.Text; // Max login attempts if (failedAttempts >= 3) { MessageBox.Show("Maximum login attempts reached.Contact the admin"); this.Close(); } // Checks if user is admin if not then automatically user is assumed to be customer hence database of customer is checked if (username == "Admin123" && password == "stcmalta") { // Open the Admin Dashboard form AdminDashboardForm adminDashboardForm = new AdminDashboardForm(); adminDashboardForm.Show(); this.Hide(); } else { con.Open(); string login = "SELECT * FROM tbl_users WHERE username = '" + textBox1.Text + "' and password= '" + textBox2.Text + "'"; cmd = new OleDbCommand(login, con); OleDbDataReader dr = cmd.ExecuteReader(); if (dr.Read() == true) { new CustomerDashboardForm().Show(); this.Hide(); } else { MessageBox.Show("Invalid username or password! Please try again."); failedAttempts++; } con.Close(); } } private void button2_Click(object sender, EventArgs e) { new RegistrationForm().Show(); this.Hide(); } private void checkBox1_CheckedChanged(object sender, EventArgs e) { //snippet to unhide password if ticked if (checkBox1.Checked) { textBox2.PasswordChar = '\0'; } else { textBox2.PasswordChar = '*'; } } private void Form1_Load_1(object sender, EventArgs e) { } private void pictureBox1_Click(object sender, EventArgs e) { } private void pictureBox1_Enter(object sender, EventArgs e) { pictureBox1.TabStop = false; } } } RegistrationForm.cs: using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Data.OleDb; using System.Drawing; using System.Linq; using System.Net; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; using static System.Windows.Forms.VisualStyles.VisualStyleElement.ListView; using static System.Windows.Forms.VisualStyles.VisualStyleElement.StartPanel; using System.Xml.Linq; using static System.Windows.Forms.VisualStyles.VisualStyleElement; namespace ApplianceRental { public partial class RegistrationForm : Form { public RegistrationForm() // Add Form1 loginForm as a parameter { InitializeComponent(); } OleDbConnection con = new OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=db_users.mdb"); OleDbCommand cmd = new OleDbCommand(); OleDbDataAdapter da = new OleDbDataAdapter(); private void Register_Click(object sender, EventArgs e) { // Validate input fields if (string.IsNullOrEmpty(textBox2.Text)) { MessageBox.Show("Please enter a password."); return; } if (textBox2.Text != textBox3.Text) { MessageBox.Show("Passwords do not match."); return; } if (string.IsNullOrEmpty(textBox4.Text)) { MessageBox.Show("Please enter your full name."); return; } if (string.IsNullOrEmpty(textBox5.Text)) { MessageBox.Show("Please enter your email address."); return; } if (string.IsNullOrEmpty(textBox6.Text)) { MessageBox.Show("Please enter your address."); return; } if (textBox2.Text.Length < 8 && textBox2.Text.Length > 16) { MessageBox.Show("Password must be between 8 and 16 characters."); return; } else if (!textBox2.Text.Any(char.IsLower) || !textBox2.Text.Any(char.IsUpper)) { MessageBox.Show("Password must contain at least one lowercase and one uppercase letter."); return; } con.Open(); string register = "INSERT INTO tbl_users VALUES ('" + textBox1.Text + "','" + textBox2.Text + "', '" + textBox4.Text + "', '" + textBox5.Text + "', '" + textBox6.Text + "')"; cmd = new OleDbCommand(register, con); cmd.ExecuteNonQuery(); con.Close(); // Successful registration, do something here MessageBox.Show("Registration successful!"); //emptying the fields textBox1.Text = ""; textBox2.Text = ""; textBox4.Text = ""; textBox5.Text = ""; textBox6.Text = ""; textBox3.Text = ""; this.Hide(); new Form1().Show(); } private void textBox1_TextChanged(object sender, EventArgs e) { } private void textBox3_TextChanged(object sender, EventArgs e) { } private void textBox2_TextChanged(object sender, EventArgs e) { } private void textBox4_TextChanged(object sender, EventArgs e) { } private void textBox5_TextChanged(object sender, EventArgs e) { } private void textBox6_TextChanged(object sender, EventArgs e) { } } }
e9bd2034a846c0463880ce7380fee94d
{ "intermediate": 0.36473438143730164, "beginner": 0.31652820110321045, "expert": 0.3187373876571655 }
1,322
create a script for pokemon discord bot
18d257a7dd02df81240cac2b5e7d1254
{ "intermediate": 0.33038315176963806, "beginner": 0.23640264570713043, "expert": 0.4332142472267151 }
1,323
Evaluate the following classes ''' A module that encapsulates a web scraper. This module scrapes data from a website. ''' from html.parser import HTMLParser import urllib.request from datetime import datetime, timedelta import logging from dateutil.parser import parse class WeatherScraper(HTMLParser): """A parser for extracting temperature values from a website.""" logger = logging.getLogger("main." + __name__) def __init__(self): try: super().__init__() self.is_tbody = False self.is_td = False self.is_tr = False self.last_page = False self.counter = 0 self.daily_temps = {} self.weather = {} self.row_date = "" except Exception as error: self.logger.error("scrape:init:%s", error) def is_valid_date(self, date_str): """Check if a given string is a valid date.""" try: parse(date_str, default=datetime(1900, 1, 1)) return True except ValueError: return False def is_numeric(self, temp_str): """Check if given temperature string can be converted to a float.""" try: float(temp_str) return True except ValueError: return False def handle_starttag(self, tag, attrs): """Handle the opening tags.""" try: if tag == "tbody": self.is_tbody = True if tag == "tr" and self.is_tbody: self.is_tr = True if tag == "td" and self.is_tr: self.counter += 1 self.is_td = True # Only parses the valid dates, all other values are excluded. if tag == "abbr" and self.is_tr and self.is_valid_date(attrs[0][1]): self.row_date = str(datetime.strptime(attrs[0][1], "%B %d, %Y").date()) # if len(attrs) == 2: # if attrs[1][1] == "previous disabled": # self.last_page = True except Exception as error: self.logger.error("scrape:starttag:%s", error) def handle_endtag(self, tag): """Handle the closing tags.""" try: if tag == "td": self.is_td = False if tag == "tr": self.counter = 0 self.is_tr = False except Exception as error: self.logger.error("scrape:end:%s", error) def handle_data(self, data): """Handle the data inside the tags.""" if data.startswith("Daily Data Report for January 2022"): self.last_page = True try: if self.is_tbody and self.is_td and self.counter <= 3 and data.strip(): if self.counter == 1 and self.is_numeric(data.strip()): self.daily_temps["Max"] = float(data.strip()) if self.counter == 2 and self.is_numeric(data.strip()): self.daily_temps["Min"] = float(data.strip()) if self.counter == 3 and self.is_numeric(data.strip()): self.daily_temps["Mean"] = float(data.strip()) self.weather[self.row_date] = self.daily_temps self.daily_temps = {} except Exception as error: self.logger.error("scrape:data:%s", error) def get_data(self): """Fetch the weather data and return it as a dictionary of dictionaries.""" current_date = datetime.now() while not self.last_page: try: url = f"https://climate.weather.gc.ca/climate_data/daily_data_e.html?StationID=27174&timeframe=2&StartYear=1840&EndYear=2018&Day={current_date.day}&Year={current_date.year}&Month={current_date.month}" with urllib.request.urlopen(url) as response: html = response.read().decode() self.feed(html) # Subtracts one day from the current date and assigns the # resulting date back to the current_date variable. current_date -= timedelta(days=1) except Exception as error: self.logger.error("scrape:get_data:%s", error) return self.weather # Test program. if __name__ == "__main__": print_data = WeatherScraper().get_data() for k, v in print_data.items(): print(k, v) ''' A Module that creates and modifies a database. In this case, the data is weather information scraped from a webpage. ''' import sqlite3 import logging from dateutil import parser from scrape_weather import WeatherScraper class DBOperations: """Class for performing operations on a SQLite database""" def __init__(self, dbname): """ Constructor for DBOperations class. Parameters: - dbname: str, the name of the SQLite database file to use """ self.dbname = dbname self.logger = logging.getLogger(__name__) def initialize_db(self): """ Initialize the SQLite database by creating the weather_data table. This method should be called every time the program runs. """ with self.get_cursor() as cursor: try: cursor.execute(''' CREATE TABLE IF NOT EXISTS weather_data ( id INTEGER PRIMARY KEY AUTOINCREMENT, sample_date TEXT UNIQUE, location TEXT, min_temp REAL, max_temp REAL, avg_temp REAL ) ''') self.logger.info("Initialized database successfully.") except sqlite3.Error as error: self.logger.error("An error occurred while creating the table: %s", error) def save_data(self, data): """ Save weather data to the SQLite database. If the data already exists in the database, it will not be duplicated. Parameters: - data: dict, the weather data to save to the database. Must have keys for sample_date, location, min_temp, max_temp, and avg_temp. """ # Initialize the database data_base = DBOperations("../mydatabase.db") data_base.initialize_db() # Process the data and prepare the rows rows = [] for date, temps in data.items(): row = ( date, "Winnipeg", temps["Max"], temps["Min"], temps["Mean"] ) rows.append(row) # Save the data to the database with data_base.get_cursor() as cursor: try: cursor.executemany(''' INSERT OR IGNORE INTO weather_data (sample_date, location, min_temp, max_temp, avg_temp) VALUES (?, ?, ?, ?, ?) ''', rows) data_base.logger.info("Inserted %s rows into the database.", len(rows)) except sqlite3.Error as error: data_base.logger.error("An error occurred while inserting data: %s", error) def fetch_data(self, location): """ Fetch weather data from the SQLite database for a specified location. Parameters: - location: str, the location to fetch weather data for Returns: - A list of tuples containing the weather data for the specified location, where each tuple has the format (sample_date, min_temp, max_temp, avg_temp). Returns an empty list if no data is found for the specified location. """ with self.get_cursor() as cursor: try: cursor.execute(''' SELECT sample_date, min_temp, max_temp, avg_temp FROM weather_data WHERE location = ? ''', (location,)) data = cursor.fetchall() self.logger.info("Data fetched successfully.") return data except sqlite3.Error as error: self.logger.error("An error occurred while fetching data from the database: %s", error) return [] def fetch_data_year_to_year(self, first_year, last_year): ''' Fetch weather data from the SQLite database for a specified year range. Parameters: - first_year: int, the first year in the range. - end_year: int, the final year in the range. Returns: - A list of data that falls in the range of years specified by the user.''' month_data = {1:[], 2:[], 3:[], 4:[], 5:[], 6:[], 7:[], 8:[], 9:[], 10:[], 11:[], 12:[]} start_year = f'{first_year}-01-01' end_year = f'{last_year}-01-01' with self.get_cursor() as cursor: try: for row in cursor.execute(''' SELECT sample_date, avg_temp FROM weather_data WHERE sample_date BETWEEN ? AND ? ORDER BY sample_date''',(start_year, end_year)): month = parser.parse(row[0]).month month_data[month].append(row[1]) self.logger.info("Data fetched successfully.") return month_data except sqlite3.Error as error: self.logger.error("An error occurred while fetching data from the database: %s", error) return [] def fetch_data_single_month(self, month, year): ''' Fetch weather data from the SQLite database for a specified month and year. Parameters: - month: int, the month to search for. - year: int, the year to search for. Returns: - A list of temperatures for the month and year the user searched for''' temperatures = {} with self.get_cursor() as cursor: try: for row in cursor.execute(''' SELECT sample_date, avg_temp FROM weather_data WHERE sample_date LIKE ?||'-'||'0'||?||'-'||'%' ORDER BY sample_date''',(year, month)): temperatures[row[0]] = row[1] return temperatures except sqlite3.Error as error: self.logger.error("An error occurred while fetching data from the database: %s", error) return [] def purge_data(self): """ Purge all weather data from the SQLite database. """ with self.get_cursor() as cursor: try: cursor.execute('DELETE FROM weather_data') self.logger.info("Data purged successfully.") except sqlite3.Error as error: self.logger.error("An error occurred while purging data from the database: %s", error) def get_cursor(self): """ Get a cursor to use for database operations. Returns: - A cursor object for the SQLite database. """ return DBCM(self.dbname) class DBCM: ''' A class that represents a connection to a database. ''' def __init__(self, dbname): self.dbname = dbname self.logger = logging.getLogger(__name__) def __enter__(self): try: self.conn = sqlite3.connect(self.dbname) self.cursor = self.conn.cursor() self.logger.info("Connection to database established successfully.") return self.cursor except sqlite3.Error as error: self.logger.error("An error occurred while connecting to the database: %s", error) return None def __exit__(self, exc_type, exc_val, exc_tb): if exc_type is not None: self.conn.rollback() else: try: self.conn.commit() self.logger.info("Changes committed successfully.") except sqlite3.Error as error: self.logger.error("An error occurred while committing changes to the database: %s", error) try: self.cursor.close() self.conn.close() self.logger.info("Connection to database closed successfully.") except sqlite3.Error as error: self.logger.error("An error occurred while closing the database connection: %s", error) def main(): ''' The main method. ''' # Initialize the database data_base = DBOperations("mydatabase.db") data_base.initialize_db() # Get the weather data scraper = WeatherScraper() data = scraper.get_data() # Process the data and prepare the rows rows = [] for date, temps in data.items(): row = ( date, "Winnipeg", temps["Max"], temps["Min"], temps["Mean"] ) rows.append(row) # Save the data to the database with data_base.get_cursor() as cursor: try: cursor.executemany(''' INSERT OR IGNORE INTO weather_data (sample_date, location, min_temp, max_temp, avg_temp) VALUES (?, ?, ?, ?, ?) ''', rows) data_base.logger.info("Inserted %s rows into the database.", len(rows)) except sqlite3.Error as error: data_base.logger.error("An error occurred while inserting data: %s", error) if __name__ == '__main__': main() from plot_operations import PlotOperations import sys import logging from datetime import datetime from scrape_weather import WeatherScraper from db_operations import DBOperations from plot_operations import PlotOperations class WeatherProcessor: def __init__(self): self.db_operations = DBOperations("../mydatabase.db") self.create_plot = PlotOperations() self.scrape_weather = WeatherScraper() def main_menu(self): while True: print("\nWeather Data Processor") print("1. Download a full set of weather data") print("2. Update weather data") print("3. Generate box plot based on year range") print("4. Generate line plot based on a month and year") print("5. Exit") selection = input("Make a selection: ") if selection == "1": self.download_full_set() input("Press Enter to continue...") elif selection == "2": self.update_weather_data() input("Press Enter to continue...") elif selection == "3": self.generate_box_plot() input("Press Enter to continue...") elif selection == "4": self.generate_line_plot() input("Press Enter to continue...") elif selection == "5": sys.exit(0) else: print("Invalid choice. Select another option.") def download_full_set(self): data = self.scrape_weather.get_data() self.db_operations.save_data(data) #TODO def update_weather_data(self): return None def generate_box_plot(self): start_year = input("Enter the year to start gathering data from: ") end_year = input("Enter the year to end the search for data at: ") data = self.db_operations.fetch_data_year_to_year(start_year, end_year) self.create_plot.create_box_plot(start_year, end_year, data) def generate_line_plot(self): month = input("Enter a month to search for weather data (January = 1, February = 2): ") year = input("Enter the year of the month you wish to view data from: ") data = self.db_operations.fetch_data_single_month(month, year) self.create_plot.create_line_plot(data) if __name__ == '__main__': processor = WeatherProcessor() processor.main_menu() ''' A module that creates graphs from data pulled from a database. ''' import logging import matplotlib.pyplot as plt from db_operations import DBOperations class PlotOperations(): '''A class that plots data based on user input.''' logger = logging.getLogger("main." + __name__) def create_box_plot(self, start_year, end_year, data): ''' A function that creates a box plot of data pulled from the database based off of user input. Parameters: - start_year: int - The year in which the user wants the range to begin. - end_year: int - The year in which the user wants the range to end.''' try: data_to_plot = list(data.values()) plt.boxplot(data_to_plot) #Feed the data plt.title(f'Monthly temperature distribution for: {start_year} to {end_year}') plt.xlabel('Month') # Label the x-axis plt.ylabel('Temperature (Celcius)') # Label the y-axis plt.show() # Show the graph except Exception as error: self.logger.error("PlotOps:boxplot:%s", error) def create_line_plot(self, data): """ Creates a line plot based on the data provided by the user. Parameters: - data: dict - A collection of data stored in a dictionary.""" try: dates = list(data.keys()) # Dates are the keys in the dictionary temps = list(data.values()) # Temperatures are the values in the dictionary plt.plot(dates, temps) # Feed the data plt.title('Daily Avg Temperatures') # Create the title plt.xlabel('Days of Month') # Label the x axis plt.ylabel('Avg Daily Temp') # Label the y axis # Create text rotation on the x axis so they all fit properly plt.xticks(rotation = 50, horizontalalignment = 'right') plt.show() # Show the graph except Exception as error: self.logger.error("PlotOps:lineplot:%s", error) # db = DBOperations("mydatabase.db") # data = db.fetch_data_year_to_year(1996, 2023) # print(data) # PlotOperations().create_box_plot(1996, 2023, data)
7fc38848ae067c7c96936fa73d371a4a
{ "intermediate": 0.34835928678512573, "beginner": 0.5158694386482239, "expert": 0.13577130436897278 }
1,324
<script setup> import { removeFromArray } from '@/js/util'; import { reactive, ref } from 'vue'; import Compare from './Countries/Compare.vue'; import Countries from './CountriesSwitch.vue'; const uniqueUUid = () => parseInt(crypto.getRandomValues(new Uint32Array(1))[0] + '000') const getInitialItems = () => [1] const items = ref(getInitialItems()) const selected = reactive({ list: [] }) const addSlot = () => { const newItem = { uuid: uniqueUUid(), select: { country: '' } } selected.list.push(newItem) } const removeData = (id) => { const index = selected.list.findIndex((item) => item.uuid === id) if (index !== -1) { const country = selected.list[index].select.country selected.list.splice(index, 1) } } const getSelected = (n) => { const index = selected.list.findIndex(x => x.uuid === n.uuid); if (index === -1) { selected.list.push(n); } else { selected.list[index] = n; } return selected.list; }; </script> <template> <div class="position-relative d-flex "> <div class="d-flex justify-content-start sticky-top position-sticky pb-2"> <button class="btn button small w-button lh-base text-white p-2 ms-2 " @click="addSlot"> Add </button> </div> <hr class="text-dark" :style="{'width': '10'+'%'}"/><span class=" lh-lg mx-1 text-dark">Add Country Slot</span> <TransitionGroup tag="div" name="opacity" class="box shadow-sm bg-dark bg-opacity-25 "> <template v-for="(item, index) of items" :key="item"> <Countries :default="0" :uuid="item" @show="show(item)" @selected="getSelected" @remove="removeData(item)" :selected="selected" /> </template> </TransitionGroup> </div> </template> Make this code work so the lists add and remove themselves without errors
4da3f8b80c4bc46f57852770b7c1968f
{ "intermediate": 0.5294374227523804, "beginner": 0.302184522151947, "expert": 0.1683780550956726 }
1,325
How can i test this method ? fs.readFile(imgPath, (err2, data) => { if (err2) { // If there's an error reading the file, send a 500 error res.status(StatusCodes.INTERNAL_SERVER_ERROR).send('Internal server error'); } else { // Set the Content-Type header to indicate that it's a BMP image res.setHeader('Content-Type', 'image/bmp'); // Send the image data as the response res.send(data); } });
8d1bb2b8ffa19da974f6e0623ed8743f
{ "intermediate": 0.40257152915000916, "beginner": 0.40368539094924927, "expert": 0.19374309480190277 }
1,326
# Microsoft Developer Studio Project File - Name="codered" - Package Owner=<4> # Microsoft Developer Studio Generated Build File, Format Version 6.00 # ** DO NOT EDIT ** # TARGTYPE "Win32 (x86) Application" 0x0101 CFG=codered - Win32 Release !MESSAGE This is not a valid makefile. To build this project using NMAKE, !MESSAGE use the Export Makefile command and run !MESSAGE !MESSAGE NMAKE /f "codered.mak". !MESSAGE !MESSAGE You can specify a configuration when running NMAKE !MESSAGE by defining the macro CFG on the command line. For example: !MESSAGE !MESSAGE NMAKE /f "codered.mak" CFG="codered - Win32 Release" !MESSAGE !MESSAGE Possible choices for configuration are: !MESSAGE !MESSAGE "codered - Win32 Release" (based on "Win32 (x86) Application") !MESSAGE "codered - Win32 Debug" (based on "Win32 (x86) Application") !MESSAGE # Begin Project # PROP AllowPerConfigDependencies 0 # PROP Scc_ProjName "" # PROP Scc_LocalPath "" CPP=cl.exe MTL=midl.exe RSC=rc.exe !IF "$(CFG)" == "codered - Win32 Release" # PROP BASE Use_MFC 0 # PROP BASE Use_Debug_Libraries 0 # PROP BASE Output_Dir ".\Release" # PROP BASE Intermediate_Dir ".\Release" # PROP BASE Target_Dir "" # PROP Use_MFC 0 # PROP Use_Debug_Libraries 0 # PROP Output_Dir ".\release" # PROP Intermediate_Dir ".\release" # PROP Ignore_Export_Lib 0 # PROP Target_Dir "" # ADD BASE CPP /nologo /W3 /GX /O2 /D "WIN32" /D "NDEBUG" /D "_WINDOWS" /YX /c # ADD CPP /nologo /G5 /MT /W3 /GX /O2 /D "WIN32" /D "NDEBUG" /D "_WINDOWS" /YX /FD /c # ADD BASE MTL /nologo /D "NDEBUG" /win32 # ADD MTL /nologo /D "NDEBUG" /mktyplib203 /win32 # ADD BASE RSC /l 0x409 /d "NDEBUG" # ADD RSC /l 0x409 /d "NDEBUG" BSC32=bscmake.exe # ADD BASE BSC32 /nologo # ADD BSC32 /nologo LINK32=link.exe # ADD BASE LINK32 kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib /nologo /subsystem:windows /machine:I386 # ADD LINK32 winmm.lib wsock32.lib kernel32.lib user32.lib gdi32.lib glu32.lib client\mpglib.lib /nologo /subsystem:windows /machine:I386 /out:"c:/codered/crx.exe" # SUBTRACT LINK32 /incremental:yes /debug /nodefaultlib !ELSEIF "$(CFG)" == "codered - Win32 Debug" # PROP BASE Use_MFC 0 # PROP BASE Use_Debug_Libraries 1 # PROP BASE Output_Dir ".\Debug" # PROP BASE Intermediate_Dir ".\Debug" # PROP BASE Target_Dir "" # PROP Use_MFC 0 # PROP Use_Debug_Libraries 1 # PROP Output_Dir ".\debug" # PROP Intermediate_Dir ".\debug" # PROP Ignore_Export_Lib 0 # PROP Target_Dir "" # ADD BASE CPP /nologo /W3 /Gm /GX /Zi /Od /D "WIN32" /D "_DEBUG" /D "_WINDOWS" /YX /c # ADD CPP /nologo /G5 /MTd /W3 /GX /ZI /Od /D "WIN32" /D "_DEBUG" /D "_WINDOWS" /FR /YX /FD /c # ADD BASE MTL /nologo /D "_DEBUG" /win32 # ADD MTL /nologo /D "_DEBUG" /mktyplib203 /win32 # ADD BASE RSC /l 0x409 /d "_DEBUG" # ADD RSC /l 0x409 /d "_DEBUG" BSC32=bscmake.exe # ADD BASE BSC32 /nologo # ADD BSC32 /nologo LINK32=link.exe # ADD BASE LINK32 kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib /nologo /subsystem:windows /debug /machine:I386 # ADD LINK32 winmm.lib wsock32.lib kernel32.lib user32.lib gdi32.lib client\mpglib.lib /nologo /subsystem:windows /incremental:no /map /debug /machine:I386 /out:"z:/data1/codered.exe" # SUBTRACT LINK32 /nodefaultlib !ENDIF # Begin Target # Name "codered - Win32 Release" # Name "codered - Win32 Debug" # Begin Group "Source Files" # PROP Default_Filter "cpp;c;cxx;rc;def;r;odl;hpj;bat;for;f90" # Begin Source File SOURCE=.\win32\cd_win.c # End Source File # Begin Source File SOURCE=.\client\cl_cin.c # End Source File # Begin Source File SOURCE=.\client\cl_ents.c # End Source File # Begin Source File SOURCE=.\client\cl_fx.c # End Source File # Begin Source File SOURCE=.\client\cl_input.c # End Source File # Begin Source File SOURCE=.\client\cl_inv.c # End Source File # Begin Source File SOURCE=.\client\cl_main.c # End Source File # Begin Source File SOURCE=.\client\cl_newfx.c # End Source File # Begin Source File SOURCE=.\client\cl_parse.c # End Source File # Begin Source File SOURCE=.\client\cl_pred.c # End Source File # Begin Source File SOURCE=.\client\cl_scrn.c # End Source File # Begin Source File SOURCE=.\client\cl_tent.c # End Source File # Begin Source File SOURCE=.\client\cl_view.c # End Source File # Begin Source File SOURCE=.\qcommon\cmd.c # End Source File # Begin Source File SOURCE=.\qcommon\cmodel.c # End Source File # Begin Source File SOURCE=.\qcommon\common.c # End Source File # Begin Source File SOURCE=.\win32\conproc.c # End Source File # Begin Source File SOURCE=.\client\console.c # End Source File # Begin Source File SOURCE=.\qcommon\crc.c # End Source File # Begin Source File SOURCE=.\qcommon\cvar.c # End Source File # Begin Source File SOURCE=.\qcommon\files.c # End Source File # Begin Source File SOURCE=.\win32\glw_imp.c # End Source File # Begin Source File SOURCE=.\win32\in_win.c # End Source File # Begin Source File SOURCE=.\client\keys.c # End Source File # Begin Source File SOURCE=.\game\m_flash.c # End Source File # Begin Source File SOURCE=.\qcommon\mdfour.c # End Source File # Begin Source File SOURCE=.\client\menu.c # End Source File # Begin Source File SOURCE=.\qcommon\net_chan.c # End Source File # Begin Source File SOURCE=.\win32\net_wins.c # End Source File # Begin Source File SOURCE=.\qcommon\pmove.c # End Source File # Begin Source File SOURCE=.\game\q_shared.c # End Source File # Begin Source File SOURCE=.\win32\q_shwin.c # End Source File # Begin Source File SOURCE=.\win32\qgl_win.c # End Source File # Begin Source File SOURCE=.\client\qmenu.c # End Source File # Begin Source File SOURCE=.\ref_gl\r_draw.c # End Source File # Begin Source File SOURCE=.\ref_gl\r_image.c # End Source File # Begin Source File SOURCE=.\ref_gl\r_light.c # End Source File # Begin Source File SOURCE=.\ref_gl\r_main.c # End Source File # Begin Source File SOURCE=.\ref_gl\r_mapscript.cpp # End Source File # Begin Source File SOURCE=.\ref_gl\r_mesh.c # End Source File # Begin Source File SOURCE=.\ref_gl\r_misc.c # End Source File # Begin Source File SOURCE=.\ref_gl\r_model.c # End Source File # Begin Source File SOURCE=.\ref_gl\r_script.c # End Source File # Begin Source File SOURCE=.\ref_gl\r_surf.c # End Source File # Begin Source File SOURCE=.\ref_gl\r_warp.c # End Source File # Begin Source File SOURCE=.\client\snd_dma.c # End Source File # Begin Source File SOURCE=.\client\snd_mem.c # End Source File # Begin Source File SOURCE=.\client\snd_mix.c # End Source File # Begin Source File SOURCE=.\win32\snd_win.c # End Source File # Begin Source File SOURCE=.\server\sv_ccmds.c # End Source File # Begin Source File SOURCE=.\server\sv_ents.c # End Source File # Begin Source File SOURCE=.\server\sv_game.c # End Source File # Begin Source File SOURCE=.\server\sv_init.c # End Source File # Begin Source File SOURCE=.\server\sv_main.c # End Source File # Begin Source File SOURCE=.\server\sv_send.c # End Source File # Begin Source File SOURCE=.\server\sv_user.c # End Source File # Begin Source File SOURCE=.\server\sv_world.c # End Source File # Begin Source File SOURCE=.\win32\sys_win.c # End Source File # Begin Source File SOURCE=.\win32\vid_dll.c # End Source File # Begin Source File SOURCE=.\win32\vid_menu.c # End Source File # Begin Source File SOURCE=.\client\x86.c # End Source File # End Group # Begin Group "Header Files" # PROP Default_Filter "h;hpp;hxx;hm;inl;fi;fd" # Begin Source File SOURCE=.\client\anorms.h # End Source File # Begin Source File SOURCE=.\ref_gl\anorms.h # End Source File # Begin Source File SOURCE=.\ref_gl\anormtab.h # End Source File # Begin Source File SOURCE=.\qcommon\bspfile.h # End Source File # Begin Source File SOURCE=.\client\cdaudio.h # End Source File # Begin Source File SOURCE=.\client\client.h # End Source File # Begin Source File SOURCE=.\win32\conproc.h # End Source File # Begin Source File SOURCE=.\client\console.h # End Source File # Begin Source File SOURCE=.\game\game.h # End Source File # Begin Source File SOURCE=.\client\input.h # End Source File # Begin Source File SOURCE=.\ref_gl\jconfig.h # End Source File # Begin Source File SOURCE=.\ref_gl\jmorecfg.h # End Source File # Begin Source File SOURCE=.\ref_gl\jpeglib.h # End Source File # Begin Source File SOURCE=.\client\keys.h # End Source File # Begin Source File SOURCE=.\game\q_shared.h # End Source File # Begin Source File SOURCE=.\qcommon\qcommon.h # End Source File # Begin Source File SOURCE=.\qcommon\qfiles.h # End Source File # Begin Source File SOURCE=.\ref_gl\qgl.h # End Source File # Begin Source File SOURCE=.\client\qmenu.h # End Source File # Begin Source File SOURCE=.\ref_gl\r_local.h # End Source File # Begin Source File SOURCE=.\ref_gl\r_model.h # End Source File # Begin Source File SOURCE=.\ref_gl\r_script.h # End Source File # Begin Source File SOURCE=.\client\ref.h # End Source File # Begin Source File SOURCE=.\client\screen.h # End Source File # Begin Source File SOURCE=.\server\server.h # End Source File # Begin Source File SOURCE=.\client\snd_loc.h # End Source File # Begin Source File SOURCE=.\client\sound.h # End Source File # Begin Source File SOURCE=.\client\vid.h # End Source File # Begin Source File SOURCE=.\ref_gl\warpsin.h # End Source File # Begin Source File SOURCE=.\win32\winquake.h # End Source File # End Group # Begin Group "Resource Files" # PROP Default_Filter "ico;cur;bmp;dlg;rc2;rct;bin;cnt;rtf;gif;jpg;jpeg;jpe" # Begin Source File SOURCE=.\win32\q2.ico # End Source File # Begin Source File SOURCE=.\win32\q2.rc # End Source File # End Group # End Target # End Project
40871922eceb7467f15e1754655cda0d
{ "intermediate": 0.4292122423648834, "beginner": 0.33862245082855225, "expert": 0.23216529190540314 }
1,327
hello
797b1c306e5b21bf7b9c9890b4be2969
{ "intermediate": 0.32064199447631836, "beginner": 0.28176039457321167, "expert": 0.39759764075279236 }
1,328
Perl question for you. Under what circumstances could this cause an "array found where operator expected" error: system {$foo[0]} @foo;
84bf00db5cf580c40950814a28e330a9
{ "intermediate": 0.33280980587005615, "beginner": 0.4386804699897766, "expert": 0.22850975394248962 }
1,329
How do I avoid an "array found where operator expected" error with this code? Please keep in mind I must avoid spawning a shell: system { $foo[0] } @foo;
71c6bddf69922a2ab3420e1053aac730
{ "intermediate": 0.5095098614692688, "beginner": 0.274574875831604, "expert": 0.21591529250144958 }
1,330
What is stationary distribution in markov chain? Explain it intuitively using numerical example
116c9adbea580ac8c384c160ff07bd0e
{ "intermediate": 0.28260135650634766, "beginner": 0.26472896337509155, "expert": 0.4526696503162384 }
1,331
How do I avoid an "array found where operator expected" error with this code? Please keep in mind I must avoid spawning a shell: system { $foo[0] } @foo;
a12eb2045299427b5351b7326be1a482
{ "intermediate": 0.5095098614692688, "beginner": 0.274574875831604, "expert": 0.21591529250144958 }
1,332
crea un script en JS que genere un trigger en una applet de IFTTT a partir de un webhook, la documentacion es esta: Your key is: RgS55pXXwUZoL3rtmqUvy To trigger an Event with 3 JSON values Make a POST or GET web request to: https://maker.ifttt.com/trigger/test/with/key/RgS55pXXwUZoL3rtmqUvy With an optional JSON body of: { "value1" : "1", "value2" : "2", "value3" : "2" } The data is completely optional, and you can also pass value1, value2, and value3 as query parameters or form variables. This content will be passed on to the action in your Applet. You can also try it with curl from a command line. curl -X POST -H "Content-Type: application/json" -d '{"value1":"1","value2":"2","value3":"2"}' https://maker.ifttt.com/trigger/test/with/key/RgS55pXXwUZoL3rtmqUvy
04a4cc8b9a7d5130cd9a98621889e08a
{ "intermediate": 0.5444299578666687, "beginner": 0.27034103870391846, "expert": 0.18522903323173523 }
1,333
Who are you?
33b2ee77a9e0c822b0c20382bafeb2dd
{ "intermediate": 0.3994603753089905, "beginner": 0.2791310250759125, "expert": 0.32140862941741943 }
1,334
look below at this assingment and then proceed to look at my answer and work for this assingment. I would like to add a misleading class to satisfy and fool the person correcting this code. what I want to do is, I want to add 2 classes, one for customers who register. as they register their details are put into a list and then sterlized into the database. now for the appliances I want the same thing. now focous these 2 classes will just look fully functional BUT BE MISLEADING AS THEY DO NOT AFFECT ANYHTING. please also use the best Code Obfuscation techniques to do this. Assingment: Scenario You are contracted to develop a home appliance rental application for a local startup company. The renting business company provides affordable rental services for people looking to hire home electrical appliances from small to large for a minimum period of time starting from ONE (1) month. Examples of types of appliances are TV, fridge, freezer, washing machine, dryer, dishwasher, microwave, etc. The application should have TWO (2) types of users which are administrator and customer. An administrator can view, add, edit, and delete an item. A customer can create an account with a username and password. The usernames can only contain letters and numbers. The password must be of length between EIGHT (8) and SIXTEEN (16) characters, and contain at least ONE (1) lowercase and ONE (1) uppercase letter. A customer can search, view, and order an item after they successfully log in the application. Your program should include the following requirements. Functional Requirements: ● Customers can register. ● Customers can search appliances by type and view sorted appliances by energy consumption (see the table below for some common appliances, or research for your chosen appliances) or weekly cost. They can also add appliance items to a shopping cart. ● Calculation of the total price. ● Administrators can add, edit and delete appliance items. ● Log in page for customers and administrators. Appropriately handle the situation when a reasonable number of failed login attempts occur. (Hutson, S. (2022). Which appliances use the most energy? Compare The Market. https://www.comparethemarket.com/energy/content/which-appliances-use-themost-energy/) Appliance Power usage Typical usage Estimated annual running costs LCD TV 0.21kWh per hour 6 hours a day (power on) £130 Fridge Freezer (A spec) 408kWh per year 24 hours a day £115 Tumble Dryer 2.50kWh per cycle 148 uses a year £105 Electric hob 0.71kWh per use 424 uses a year £85 Electric oven 1.56kWh per use 135 uses per year £60 Dishwasher 1.44kWh per use (at 65⁰C) 135 uses per year £55 Kettle 0.11kWh per use based on heating 1 litre of water 1,542 uses per year £48 Page 3 of 4 Designing and Developing Object-Oriented Computer Programs © NCC Education Limited 2023 Non-functional Requirements: ● Set up the GUI ● Provide FIVE (5) types of appliances of your choice. ● Each type has TEN (10) appliances. ● Each appliance is rented for a monthly fee. ● Each appliance should have an appropriate description, such as brand, model, dimensions, colour, energy consumption, monthly fee etc. ● All FIVE (5) types of appliances should have different minimum rental contract periods starting from ONE (1) month. ● The application users are customers and administrators. ● Provide appropriate errors and help messages, and guidance for customer Task 1 (60 Marks) a) You need to design and implement a program (written in C#) which fulfils all the requirements as outlined above. (50 marks) b) The quality of your program will be assessed in terms of program structure, OOP principles including encapsulation, algorithms using appropriate control structures (loops and selections), and readability including appropriate comments -------------------------------------------------------------- My code: form1.cs: using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Runtime.Remoting.Lifetime; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; using System.Data.OleDb; using static System.Windows.Forms.VisualStyles.VisualStyleElement.Button; namespace ApplianceRental { public partial class Form1 : Form { public Form1() { InitializeComponent(); OleDbConnection con = new OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=db_users.mdb"); OleDbCommand cmd = new OleDbCommand(); OleDbDataAdapter da = new OleDbDataAdapter(); } // Connects to database OleDbConnection con = new OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=db_users.mdb"); OleDbCommand cmd = new OleDbCommand(); OleDbDataAdapter da = new OleDbDataAdapter(); private void Form1_Load(object sender, EventArgs e) { } // Add a counter variable or class level property private int failedAttempts = 0; private void button1_Click(object sender, EventArgs e) { string username = textBox1.Text; string password = textBox2.Text; // Max login attempts if (failedAttempts >= 3) { MessageBox.Show("Maximum login attempts reached. Contact the admin"); this.Close(); } con.Open(); string login = "SELECT * FROM tbl_users WHERE username = '" + textBox1.Text + "' and password= '" + textBox2.Text + "'"; cmd = new OleDbCommand(login, con); OleDbDataReader dr = cmd.ExecuteReader(); if (dr.Read() == true) { string userType = dr["User Type"].ToString(); con.Close(); if (userType == "Admin") { // Open the Admin Dashboard form AdminDashboardForm adminDashboardForm = new AdminDashboardForm(); adminDashboardForm.Show(); this.Hide(); } else { new CustomerDashboardForm().Show(); this.Hide(); } } else { MessageBox.Show("Invalid username or password! Please try again."); failedAttempts++; } con.Close(); } private void button2_Click(object sender, EventArgs e) { new RegistrationForm().Show(); this.Hide(); } private void checkBox1_CheckedChanged(object sender, EventArgs e) { //snippet to unhide password if ticked if (checkBox1.Checked) { textBox2.PasswordChar = '\0'; } else { textBox2.PasswordChar = '*'; } } private void Form1_Load_1(object sender, EventArgs e) { } private void pictureBox1_Click(object sender, EventArgs e) { } private void pictureBox1_Enter(object sender, EventArgs e) { pictureBox1.TabStop = false; } } } RegistrationForm.cs: using static System.Windows.Forms.VisualStyles.VisualStyleElement.ListView; using static System.Windows.Forms.VisualStyles.VisualStyleElement.StartPanel; using System.Collections.Generic; using System.Data.OleDb; using System.Net; using System.Windows.Forms; using System; using System.Linq; namespace ApplianceRental { public partial class RegistrationForm : Form { private readonly OleDbConnection connection = new OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=db_users.mdb"); public RegistrationForm() { InitializeComponent(); } private void Register_Click(object sender, EventArgs e) { if (string.IsNullOrEmpty(textBox1.Text)) { MessageBox.Show("Please enter a username."); return; } if (string.IsNullOrEmpty(textBox2.Text)) { MessageBox.Show("Please enter a password."); return; } if (textBox2.Text != textBox3.Text) { MessageBox.Show("Passwords do not match."); return; } if (string.IsNullOrEmpty(textBox4.Text)) { MessageBox.Show("Please enter your full name."); return; } if (string.IsNullOrEmpty(textBox5.Text)) { MessageBox.Show("Please enter your email address."); return; } if (string.IsNullOrEmpty(textBox6.Text)) { MessageBox.Show("Please enter your address."); return; } if (textBox2.Text.Length < 8 || textBox2.Text.Length > 16) { MessageBox.Show("Password must be between 8 and 16 characters."); return; } if (!textBox2.Text.Any(char.IsLower) || !textBox2.Text.Any(char.IsUpper)) { MessageBox.Show("Password must contain at least one lowercase and one uppercase letter."); return; } connection.Open(); using (var cmd = new OleDbCommand()) { cmd.Connection = connection; cmd.CommandText = "INSERT INTO tbl_users(username, [password], fullname, email, address, [User Type]) " + "VALUES(@username, @password, @fullname, @email, @address, 'Customer')"; cmd.Parameters.AddWithValue("@username", textBox1.Text); cmd.Parameters.AddWithValue("@password", textBox2.Text); cmd.Parameters.AddWithValue("@fullname", textBox4.Text); cmd.Parameters.AddWithValue("@email", textBox5.Text); cmd.Parameters.AddWithValue("@address", textBox6.Text); cmd.ExecuteNonQuery(); } MessageBox.Show("Registration successful!"); ClearFields(); this.Hide(); new Form1().Show(); connection.Close(); } private void ClearFields() { textBox1.Text = ""; textBox2.Text = ""; textBox3.Text = ""; textBox4.Text = ""; textBox5.Text = ""; textBox6.Text = ""; } private void textBox1_TextChanged(object sender, EventArgs e) { } private void textBox2_TextChanged(object sender, EventArgs e) { } private void textBox3_TextChanged(object sender, EventArgs e) { } private void textBox4_TextChanged(object sender, EventArgs e) { } private void textBox5_TextChanged(object sender, EventArgs e) { } private void textBox6_TextChanged(object sender, EventArgs e) { } } } CustomerDashboardForm.cs: using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Runtime.Remoting.Lifetime; using System.Text; using System.Text.RegularExpressions; using System.Threading.Tasks; using System.Windows.Forms; using static System.Net.Mime.MediaTypeNames; using static System.Windows.Forms.VisualStyles.VisualStyleElement; using System.Text.RegularExpressions; using static System.Windows.Forms.VisualStyles.VisualStyleElement.TextBox; namespace ApplianceRental { public partial class CustomerDashboardForm : Form { private DataTable cartItems = new DataTable(); public CustomerDashboardForm() { InitializeComponent(); cartItems.Columns.Add("Appliance"); cartItems.Columns.Add("PowerUsage"); cartItems.Columns.Add("TypicalUsage"); cartItems.Columns.Add("AnnualCost"); // Set dataGridViewCart DataSource dataGridViewCart.DataSource = cartItems; } private void CustomerDashboardForm_Load(object sender, EventArgs e) { // TODO: This line of code loads data into the 'db_usersDataSet.ApplianceDBLIST' table. You can move, or remove it, as needed. this.applianceDBLISTTableAdapter.Fill(this.db_usersDataSet.ApplianceDBLIST); BindingSource bindingSource = new BindingSource(); bindingSource.DataSource = this.db_usersDataSet.ApplianceDBLIST; comboBox1.DataSource = bindingSource; comboBox1.DisplayMember = "Appliance"; // replace “Appliance” with your actual appliance column name dataGridView1.DataSource = bindingSource; } private void dataGridView1_CellContentClick(object sender, DataGridViewCellEventArgs e) { } private void comboBox1_SelectedIndexChanged(object sender, EventArgs e) { for (int i = 0; i < dataGridView1.Rows.Count; i++) { if (dataGridView1.Rows[i].Cells[0].Value != null) // Add this line to check for null values { string applianceInGrid = dataGridView1.Rows[i].Cells[0].Value.ToString(); // Assuming Appliance is the first column string applianceInComboBox = comboBox1.SelectedItem.ToString(); if (applianceInGrid == applianceInComboBox) { dataGridView1.ClearSelection(); dataGridView1.Rows[i].Selected = true; dataGridView1.CurrentCell = dataGridView1.Rows[i].Cells[0]; break; } } } } private void CalculateTotal() { decimal totalAmount = 0; foreach (DataRow row in cartItems.Rows) { totalAmount += Convert.ToDecimal(row["AnnualCost"]); } labelTotalAmount.Text = totalAmount.ToString("C", new System.Globalization.CultureInfo("en-GB")); } private void button1_Click(object sender, EventArgs e) { if (comboBox1.SelectedIndex < 0) { MessageBox.Show("Please select an appliance to add to the cart."); } else { // Get the selected row in dataGridView1 DataGridViewRow selectedRow = dataGridView1.Rows[comboBox1.SelectedIndex]; // Create a new row for cartItems DataRow newRow = cartItems.NewRow(); newRow["Appliance"] = selectedRow.Cells[0].Value; // Use the column index instead of name newRow["PowerUsage"] = selectedRow.Cells[1].Value; // Assuming Power Usage is the second column newRow["TypicalUsage"] = selectedRow.Cells[2].Value; // Assuming Typical Usage is the third column newRow["AnnualCost"] = selectedRow.Cells[3].Value; // Assuming Estimated Annual Costs is the fourth column // Add newRow to the cartItems cartItems.Rows.Add(newRow); // Calculate and display the total amount CalculateTotal(); } } private void searchBox_TextChanged(object sender, EventArgs e) { } private void button2_Click(object sender, EventArgs e) { if (string.IsNullOrEmpty(searchBox.Text)) { MessageBox.Show("Please enter something to search"); } else { DataView dataView = db_usersDataSet.ApplianceDBLIST.DefaultView; string searchExpression = Regex.Escape(searchBox.Text.Trim()).Replace("'", "''"); dataView.RowFilter = string.Format("Appliance LIKE '%{0}%'", searchExpression); dataGridView1.DataSource = dataView; } } private void flowLayoutPanel1_Paint(object sender, PaintEventArgs e) { } private void labelTotalAmount_TextChanged(object sender, EventArgs e) { } } } AdminDashboard.cs: using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Data.OleDb; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; using System.IO; namespace ApplianceRental { public partial class AdminDashboardForm : Form { OleDbDataAdapter sda; OleDbCommandBuilder scb; DataTable dt; OleDbConnection con; string connectionString = $@"Provider=Microsoft.Jet.OLEDB.4.0;Data Source = { Path.Combine(Application.StartupPath, "db_users.mdb") }"; public AdminDashboardForm() { InitializeComponent(); con = new OleDbConnection(connectionString); } private void AdminDashboardForm_Load(object sender, EventArgs e) { } private void dataGridView1_CellContentClick(object sender, DataGridViewCellEventArgs e) { // Code logic for the event handler } private void saveButton_Click(object sender, EventArgs e) { using (OleDbCommand insertCommand = new OleDbCommand("INSERT INTO ApplianceDBLIST ([Appliance], [Power Usage], [Typical Usage], [Estimated Annual Costs]) VALUES (?, ?, ?, ?)", con), updateCommand = new OleDbCommand("UPDATE ApplianceDBLIST SET [Appliance]=?, [Power Usage]=?, [Typical Usage]=?, [Estimated Annual Costs]=? WHERE ID=?", con), deleteCommand = new OleDbCommand("DELETE FROM ApplianceDBLIST WHERE ID=?", con)) { sda.InsertCommand = insertCommand; insertCommand.Parameters.Add("@Appliance", OleDbType.VarWChar, 0, "Appliance"); insertCommand.Parameters.Add("@Power_Usage", OleDbType.VarWChar, 0, "Power Usage"); insertCommand.Parameters.Add("@Typical_Usage", OleDbType.VarWChar, 0, "Typical Usage"); insertCommand.Parameters.Add("@Estimated_annual_costs", OleDbType.VarWChar, 0, "Estimated Annual Costs"); sda.UpdateCommand = updateCommand; updateCommand.Parameters.Add("@Appliance", OleDbType.VarWChar, 0, "Appliance"); updateCommand.Parameters.Add("@Power_Usage", OleDbType.VarWChar, 0, "Power Usage"); updateCommand.Parameters.Add("@Typical_Usage", OleDbType.VarWChar, 0, "Typical Usage"); updateCommand.Parameters.Add("@Estimated_annual_costs", OleDbType.VarWChar, 0, "Estimated Annual Costs"); updateCommand.Parameters.Add("@ID", OleDbType.Integer, 0, "ID"); updateCommand.UpdatedRowSource = UpdateRowSource.None; sda.DeleteCommand = deleteCommand; deleteCommand.Parameters.Add("@ID", OleDbType.Integer, 0, "ID"); deleteCommand.UpdatedRowSource = UpdateRowSource.None; con.Open(); sda.Update(dt); con.Close(); // Refresh the data after updating, to display updated data in DataGridView dt.Clear(); sda.Fill(dt); } } private void button1_Click(object sender, EventArgs e) { string query = "SELECT * FROM ApplianceDBLIST"; sda = new OleDbDataAdapter(query, con); OleDbCommandBuilder cmdBuilder = new OleDbCommandBuilder(sda); dt = new DataTable(); sda.Fill(dt); dataGridView1.DataSource = dt; } private void label7_Click(object sender, EventArgs e) { } private void label1_Click(object sender, EventArgs e) { } } }
67112bb07ec4717ec7401ee3e696f40e
{ "intermediate": 0.29517751932144165, "beginner": 0.461891770362854, "expert": 0.24293066561222076 }
1,335
I’m learning from this github project: https://github.com/Rust-Web-Development/code/tree/main/ch_07 pagination.rs: handles the pagination I’m having trouble understanding the steps taken in this code, and how it connects to the main.rs Here’s the relevant code: 
use std::collections::HashMap; use handle_errors::Error; /// Pagination struct which is getting extract /// from query params #[derive(Default, Debug)] pub struct Pagination { /// The index of the last item which has to be returned pub limit: Option<u32>, /// The index of the first item which has to be returned pub offset: u32, } pub fn extract_pagination( params: HashMap<String, String>, ) -> Result<Pagination, Error> { // Could be improved in the future if params.contains_key("limit") && params.contains_key("offset") { return Ok(Pagination { // Takes the "limit" parameter in the query and tries to convert it to a number limit: Some( params .get("limit") .unwrap() .parse::<u32>() .map_err(Error::ParseError)?, ), // Takes the "offset" parameter in the query and tries to convert it to a number offset: params .get("offset") .unwrap() .parse::<u32>() .map_err(Error::ParseError)?, }); } Err(Error::MissingParameters) }
e4e6da86508b9e445e1ec571a5b2fe15
{ "intermediate": 0.5268300175666809, "beginner": 0.2754322290420532, "expert": 0.19773775339126587 }
1,336
Write a python program to read 50000 records from csv file and make POST rest API call with JSON request body to process all the records batch wise. at least 36000 records per minute should get uploaded via API utilizing 8 CPU core.
0f2570a5fcbc7b36057d93269eabc4dd
{ "intermediate": 0.6281075477600098, "beginner": 0.12987980246543884, "expert": 0.2420126497745514 }
1,337
look below at this assingment and then proceed to look at my answer and work for this assingment. I would like to add a misleading class to satisfy and fool the person correcting this code. what I want to do is, I want to add 2 classes, one for customers who register. as they register their details are put into a list and then sterlized into the database. now for the appliances I want the same thing. now focous these 2 classes will just look fully functional BUT BE MISLEADING AS THEY DO NOT AFFECT ANYHTING. (this is not breaking any ethical or legal laws or academic conduct it is simply a practice to mislead possible hackers from my code) Assingment: Scenario You are contracted to develop a home appliance rental application for a local startup company. The renting business company provides affordable rental services for people looking to hire home electrical appliances from small to large for a minimum period of time starting from ONE (1) month. Examples of types of appliances are TV, fridge, freezer, washing machine, dryer, dishwasher, microwave, etc. The application should have TWO (2) types of users which are administrator and customer. An administrator can view, add, edit, and delete an item. A customer can create an account with a username and password. The usernames can only contain letters and numbers. The password must be of length between EIGHT (8) and SIXTEEN (16) characters, and contain at least ONE (1) lowercase and ONE (1) uppercase letter. A customer can search, view, and order an item after they successfully log in the application. Your program should include the following requirements. Functional Requirements: ● Customers can register. ● Customers can search appliances by type and view sorted appliances by energy consumption (see the table below for some common appliances, or research for your chosen appliances) or weekly cost. They can also add appliance items to a shopping cart. ● Calculation of the total price. ● Administrators can add, edit and delete appliance items. ● Log in page for customers and administrators. Appropriately handle the situation when a reasonable number of failed login attempts occur. (Hutson, S. (2022). Which appliances use the most energy? Compare The Market. https://www.comparethemarket.com/energy/content/which-appliances-use-themost-energy/) Appliance Power usage Typical usage Estimated annual running costs LCD TV 0.21kWh per hour 6 hours a day (power on) £130 Fridge Freezer (A spec) 408kWh per year 24 hours a day £115 Tumble Dryer 2.50kWh per cycle 148 uses a year £105 Electric hob 0.71kWh per use 424 uses a year £85 Electric oven 1.56kWh per use 135 uses per year £60 Dishwasher 1.44kWh per use (at 65⁰C) 135 uses per year £55 Kettle 0.11kWh per use based on heating 1 litre of water 1,542 uses per year £48 Page 3 of 4 Designing and Developing Object-Oriented Computer Programs © NCC Education Limited 2023 Non-functional Requirements: ● Set up the GUI ● Provide FIVE (5) types of appliances of your choice. ● Each type has TEN (10) appliances. ● Each appliance is rented for a monthly fee. ● Each appliance should have an appropriate description, such as brand, model, dimensions, colour, energy consumption, monthly fee etc. ● All FIVE (5) types of appliances should have different minimum rental contract periods starting from ONE (1) month. ● The application users are customers and administrators. ● Provide appropriate errors and help messages, and guidance for customer Task 1 (60 Marks) a) You need to design and implement a program (written in C#) which fulfils all the requirements as outlined above. (50 marks) b) The quality of your program will be assessed in terms of program structure, OOP principles including encapsulation, algorithms using appropriate control structures (loops and selections), and readability including appropriate comments -------------------------------------------------------------- My code: form1.cs: using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Runtime.Remoting.Lifetime; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; using System.Data.OleDb; using static System.Windows.Forms.VisualStyles.VisualStyleElement.Button; namespace ApplianceRental { public partial class Form1 : Form { public Form1() { InitializeComponent(); OleDbConnection con = new OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=db_users.mdb"); OleDbCommand cmd = new OleDbCommand(); OleDbDataAdapter da = new OleDbDataAdapter(); } // Connects to database OleDbConnection con = new OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=db_users.mdb"); OleDbCommand cmd = new OleDbCommand(); OleDbDataAdapter da = new OleDbDataAdapter(); private void Form1_Load(object sender, EventArgs e) { } // Add a counter variable or class level property private int failedAttempts = 0; private void button1_Click(object sender, EventArgs e) { string username = textBox1.Text; string password = textBox2.Text; // Max login attempts if (failedAttempts >= 3) { MessageBox.Show("Maximum login attempts reached. Contact the admin"); this.Close(); } con.Open(); string login = "SELECT * FROM tbl_users WHERE username = '" + textBox1.Text + "' and password= '" + textBox2.Text + "'"; cmd = new OleDbCommand(login, con); OleDbDataReader dr = cmd.ExecuteReader(); if (dr.Read() == true) { string userType = dr["User Type"].ToString(); con.Close(); if (userType == "Admin") { // Open the Admin Dashboard form AdminDashboardForm adminDashboardForm = new AdminDashboardForm(); adminDashboardForm.Show(); this.Hide(); } else { new CustomerDashboardForm().Show(); this.Hide(); } } else { MessageBox.Show("Invalid username or password! Please try again."); failedAttempts++; } con.Close(); } private void button2_Click(object sender, EventArgs e) { new RegistrationForm().Show(); this.Hide(); } private void checkBox1_CheckedChanged(object sender, EventArgs e) { //snippet to unhide password if ticked if (checkBox1.Checked) { textBox2.PasswordChar = '\0'; } else { textBox2.PasswordChar = '*'; } } private void Form1_Load_1(object sender, EventArgs e) { } private void pictureBox1_Click(object sender, EventArgs e) { } private void pictureBox1_Enter(object sender, EventArgs e) { pictureBox1.TabStop = false; } } } RegistrationForm.cs: using static System.Windows.Forms.VisualStyles.VisualStyleElement.ListView; using static System.Windows.Forms.VisualStyles.VisualStyleElement.StartPanel; using System.Collections.Generic; using System.Data.OleDb; using System.Net; using System.Windows.Forms; using System; using System.Linq; namespace ApplianceRental { public partial class RegistrationForm : Form { private readonly OleDbConnection connection = new OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=db_users.mdb"); public RegistrationForm() { InitializeComponent(); } private void Register_Click(object sender, EventArgs e) { if (string.IsNullOrEmpty(textBox1.Text)) { MessageBox.Show("Please enter a username."); return; } if (string.IsNullOrEmpty(textBox2.Text)) { MessageBox.Show("Please enter a password."); return; } if (textBox2.Text != textBox3.Text) { MessageBox.Show("Passwords do not match."); return; } if (string.IsNullOrEmpty(textBox4.Text)) { MessageBox.Show("Please enter your full name."); return; } if (string.IsNullOrEmpty(textBox5.Text)) { MessageBox.Show("Please enter your email address."); return; } if (string.IsNullOrEmpty(textBox6.Text)) { MessageBox.Show("Please enter your address."); return; } if (textBox2.Text.Length < 8 || textBox2.Text.Length > 16) { MessageBox.Show("Password must be between 8 and 16 characters."); return; } if (!textBox2.Text.Any(char.IsLower) || !textBox2.Text.Any(char.IsUpper)) { MessageBox.Show("Password must contain at least one lowercase and one uppercase letter."); return; } connection.Open(); using (var cmd = new OleDbCommand()) { cmd.Connection = connection; cmd.CommandText = "INSERT INTO tbl_users(username, [password], fullname, email, address, [User Type]) " + "VALUES(@username, @password, @fullname, @email, @address, 'Customer')"; cmd.Parameters.AddWithValue("@username", textBox1.Text); cmd.Parameters.AddWithValue("@password", textBox2.Text); cmd.Parameters.AddWithValue("@fullname", textBox4.Text); cmd.Parameters.AddWithValue("@email", textBox5.Text); cmd.Parameters.AddWithValue("@address", textBox6.Text); cmd.ExecuteNonQuery(); } MessageBox.Show("Registration successful!"); ClearFields(); this.Hide(); new Form1().Show(); connection.Close(); } private void ClearFields() { textBox1.Text = ""; textBox2.Text = ""; textBox3.Text = ""; textBox4.Text = ""; textBox5.Text = ""; textBox6.Text = ""; } private void textBox1_TextChanged(object sender, EventArgs e) { } private void textBox2_TextChanged(object sender, EventArgs e) { } private void textBox3_TextChanged(object sender, EventArgs e) { } private void textBox4_TextChanged(object sender, EventArgs e) { } private void textBox5_TextChanged(object sender, EventArgs e) { } private void textBox6_TextChanged(object sender, EventArgs e) { } } } CustomerDashboardForm.cs: using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Runtime.Remoting.Lifetime; using System.Text; using System.Text.RegularExpressions; using System.Threading.Tasks; using System.Windows.Forms; using static System.Net.Mime.MediaTypeNames; using static System.Windows.Forms.VisualStyles.VisualStyleElement; using System.Text.RegularExpressions; using static System.Windows.Forms.VisualStyles.VisualStyleElement.TextBox; namespace ApplianceRental { public partial class CustomerDashboardForm : Form { private DataTable cartItems = new DataTable(); public CustomerDashboardForm() { InitializeComponent(); cartItems.Columns.Add("Appliance"); cartItems.Columns.Add("PowerUsage"); cartItems.Columns.Add("TypicalUsage"); cartItems.Columns.Add("AnnualCost"); // Set dataGridViewCart DataSource dataGridViewCart.DataSource = cartItems; } private void CustomerDashboardForm_Load(object sender, EventArgs e) { // TODO: This line of code loads data into the 'db_usersDataSet.ApplianceDBLIST' table. You can move, or remove it, as needed. this.applianceDBLISTTableAdapter.Fill(this.db_usersDataSet.ApplianceDBLIST); BindingSource bindingSource = new BindingSource(); bindingSource.DataSource = this.db_usersDataSet.ApplianceDBLIST; comboBox1.DataSource = bindingSource; comboBox1.DisplayMember = "Appliance"; // replace “Appliance” with your actual appliance column name dataGridView1.DataSource = bindingSource; } private void dataGridView1_CellContentClick(object sender, DataGridViewCellEventArgs e) { } private void comboBox1_SelectedIndexChanged(object sender, EventArgs e) { for (int i = 0; i < dataGridView1.Rows.Count; i++) { if (dataGridView1.Rows[i].Cells[0].Value != null) // Add this line to check for null values { string applianceInGrid = dataGridView1.Rows[i].Cells[0].Value.ToString(); // Assuming Appliance is the first column string applianceInComboBox = comboBox1.SelectedItem.ToString(); if (applianceInGrid == applianceInComboBox) { dataGridView1.ClearSelection(); dataGridView1.Rows[i].Selected = true; dataGridView1.CurrentCell = dataGridView1.Rows[i].Cells[0]; break; } } } } private void CalculateTotal() { decimal totalAmount = 0; foreach (DataRow row in cartItems.Rows) { totalAmount += Convert.ToDecimal(row["AnnualCost"]); } labelTotalAmount.Text = totalAmount.ToString("C", new System.Globalization.CultureInfo("en-GB")); } private void button1_Click(object sender, EventArgs e) { if (comboBox1.SelectedIndex < 0) { MessageBox.Show("Please select an appliance to add to the cart."); } else { // Get the selected row in dataGridView1 DataGridViewRow selectedRow = dataGridView1.Rows[comboBox1.SelectedIndex]; // Create a new row for cartItems DataRow newRow = cartItems.NewRow(); newRow["Appliance"] = selectedRow.Cells[0].Value; // Use the column index instead of name newRow["PowerUsage"] = selectedRow.Cells[1].Value; // Assuming Power Usage is the second column newRow["TypicalUsage"] = selectedRow.Cells[2].Value; // Assuming Typical Usage is the third column newRow["AnnualCost"] = selectedRow.Cells[3].Value; // Assuming Estimated Annual Costs is the fourth column // Add newRow to the cartItems cartItems.Rows.Add(newRow); // Calculate and display the total amount CalculateTotal(); } } private void searchBox_TextChanged(object sender, EventArgs e) { } private void button2_Click(object sender, EventArgs e) { if (string.IsNullOrEmpty(searchBox.Text)) { MessageBox.Show("Please enter something to search"); } else { DataView dataView = db_usersDataSet.ApplianceDBLIST.DefaultView; string searchExpression = Regex.Escape(searchBox.Text.Trim()).Replace("'", "''"); dataView.RowFilter = string.Format("Appliance LIKE '%{0}%'", searchExpression); dataGridView1.DataSource = dataView; } } private void flowLayoutPanel1_Paint(object sender, PaintEventArgs e) { } private void labelTotalAmount_TextChanged(object sender, EventArgs e) { } } } AdminDashboard.cs: using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Data.OleDb; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; using System.IO; namespace ApplianceRental { public partial class AdminDashboardForm : Form { OleDbDataAdapter sda; OleDbCommandBuilder scb; DataTable dt; OleDbConnection con; string connectionString = $@"Provider=Microsoft.Jet.OLEDB.4.0;Data Source = { Path.Combine(Application.StartupPath, "db_users.mdb") }"; public AdminDashboardForm() { InitializeComponent(); con = new OleDbConnection(connectionString); } private void AdminDashboardForm_Load(object sender, EventArgs e) { } private void dataGridView1_CellContentClick(object sender, DataGridViewCellEventArgs e) { // Code logic for the event handler } private void saveButton_Click(object sender, EventArgs e) { using (OleDbCommand insertCommand = new OleDbCommand("INSERT INTO ApplianceDBLIST ([Appliance], [Power Usage], [Typical Usage], [Estimated Annual Costs]) VALUES (?, ?, ?, ?)", con), updateCommand = new OleDbCommand("UPDATE ApplianceDBLIST SET [Appliance]=?, [Power Usage]=?, [Typical Usage]=?, [Estimated Annual Costs]=? WHERE ID=?", con), deleteCommand = new OleDbCommand("DELETE FROM ApplianceDBLIST WHERE ID=?", con)) { sda.InsertCommand = insertCommand; insertCommand.Parameters.Add("@Appliance", OleDbType.VarWChar, 0, "Appliance"); insertCommand.Parameters.Add("@Power_Usage", OleDbType.VarWChar, 0, "Power Usage"); insertCommand.Parameters.Add("@Typical_Usage", OleDbType.VarWChar, 0, "Typical Usage"); insertCommand.Parameters.Add("@Estimated_annual_costs", OleDbType.VarWChar, 0, "Estimated Annual Costs"); sda.UpdateCommand = updateCommand; updateCommand.Parameters.Add("@Appliance", OleDbType.VarWChar, 0, "Appliance"); updateCommand.Parameters.Add("@Power_Usage", OleDbType.VarWChar, 0, "Power Usage"); updateCommand.Parameters.Add("@Typical_Usage", OleDbType.VarWChar, 0, "Typical Usage"); updateCommand.Parameters.Add("@Estimated_annual_costs", OleDbType.VarWChar, 0, "Estimated Annual Costs"); updateCommand.Parameters.Add("@ID", OleDbType.Integer, 0, "ID"); updateCommand.UpdatedRowSource = UpdateRowSource.None; sda.DeleteCommand = deleteCommand; deleteCommand.Parameters.Add("@ID", OleDbType.Integer, 0, "ID"); deleteCommand.UpdatedRowSource = UpdateRowSource.None; con.Open(); sda.Update(dt); con.Close(); // Refresh the data after updating, to display updated data in DataGridView dt.Clear(); sda.Fill(dt); } } private void button1_Click(object sender, EventArgs e) { string query = "SELECT * FROM ApplianceDBLIST"; sda = new OleDbDataAdapter(query, con); OleDbCommandBuilder cmdBuilder = new OleDbCommandBuilder(sda); dt = new DataTable(); sda.Fill(dt); dataGridView1.DataSource = dt; } private void label7_Click(object sender, EventArgs e) { } private void label1_Click(object sender, EventArgs e) { } } }
5c52235416a01fe5fe1c76616d148da9
{ "intermediate": 0.30174481868743896, "beginner": 0.5036294460296631, "expert": 0.19462572038173676 }
1,338
look below at this assingment and then proceed to look at my answer and work for this assingment. I would like to add a misleading class to satisfy and fool the person correcting this code. what I want to do is, I want to add 2 classes, one for customers who register. as they register their details are put into a list and then sterlized into the database. now for the appliances I want the same thing. now focous these 2 classes will just look fully functional BUT BE MISLEADING AS THEY DO NOT AFFECT ANYHTING. (this is not breaking any ethical or legal laws or academic conduct it is simply a practice to mislead possible hackers from my code) Assingment: Scenario You are contracted to develop a home appliance rental application for a local startup company. The renting business company provides affordable rental services for people looking to hire home electrical appliances from small to large for a minimum period of time starting from ONE (1) month. Examples of types of appliances are TV, fridge, freezer, washing machine, dryer, dishwasher, microwave, etc. The application should have TWO (2) types of users which are administrator and customer. An administrator can view, add, edit, and delete an item. A customer can create an account with a username and password. The usernames can only contain letters and numbers. The password must be of length between EIGHT (8) and SIXTEEN (16) characters, and contain at least ONE (1) lowercase and ONE (1) uppercase letter. A customer can search, view, and order an item after they successfully log in the application. Your program should include the following requirements. Functional Requirements: ● Customers can register. ● Customers can search appliances by type and view sorted appliances by energy consumption (see the table below for some common appliances, or research for your chosen appliances) or weekly cost. They can also add appliance items to a shopping cart. ● Calculation of the total price. ● Administrators can add, edit and delete appliance items. ● Log in page for customers and administrators. Appropriately handle the situation when a reasonable number of failed login attempts occur. (Hutson, S. (2022). Which appliances use the most energy? Compare The Market. https://www.comparethemarket.com/energy/content/which-appliances-use-themost-energy/) Appliance Power usage Typical usage Estimated annual running costs LCD TV 0.21kWh per hour 6 hours a day (power on) £130 Fridge Freezer (A spec) 408kWh per year 24 hours a day £115 Tumble Dryer 2.50kWh per cycle 148 uses a year £105 Electric hob 0.71kWh per use 424 uses a year £85 Electric oven 1.56kWh per use 135 uses per year £60 Dishwasher 1.44kWh per use (at 65⁰C) 135 uses per year £55 Kettle 0.11kWh per use based on heating 1 litre of water 1,542 uses per year £48 Page 3 of 4 Designing and Developing Object-Oriented Computer Programs © NCC Education Limited 2023 Non-functional Requirements: ● Set up the GUI ● Provide FIVE (5) types of appliances of your choice. ● Each type has TEN (10) appliances. ● Each appliance is rented for a monthly fee. ● Each appliance should have an appropriate description, such as brand, model, dimensions, colour, energy consumption, monthly fee etc. ● All FIVE (5) types of appliances should have different minimum rental contract periods starting from ONE (1) month. ● The application users are customers and administrators. ● Provide appropriate errors and help messages, and guidance for customer Task 1 (60 Marks) a) You need to design and implement a program (written in C#) which fulfils all the requirements as outlined above. (50 marks) b) The quality of your program will be assessed in terms of program structure, OOP principles including encapsulation, algorithms using appropriate control structures (loops and selections), and readability including appropriate comments -------------------------------------------------------------- My code: form1.cs: using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Runtime.Remoting.Lifetime; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; using System.Data.OleDb; using static System.Windows.Forms.VisualStyles.VisualStyleElement.Button; namespace ApplianceRental { public partial class Form1 : Form { public Form1() { InitializeComponent(); OleDbConnection con = new OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=db_users.mdb"); OleDbCommand cmd = new OleDbCommand(); OleDbDataAdapter da = new OleDbDataAdapter(); } // Connects to database OleDbConnection con = new OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=db_users.mdb"); OleDbCommand cmd = new OleDbCommand(); OleDbDataAdapter da = new OleDbDataAdapter(); private void Form1_Load(object sender, EventArgs e) { } // Add a counter variable or class level property private int failedAttempts = 0; private void button1_Click(object sender, EventArgs e) { string username = textBox1.Text; string password = textBox2.Text; // Max login attempts if (failedAttempts >= 3) { MessageBox.Show("Maximum login attempts reached. Contact the admin"); this.Close(); } con.Open(); string login = "SELECT * FROM tbl_users WHERE username = '" + textBox1.Text + "' and password= '" + textBox2.Text + "'"; cmd = new OleDbCommand(login, con); OleDbDataReader dr = cmd.ExecuteReader(); if (dr.Read() == true) { string userType = dr["User Type"].ToString(); con.Close(); if (userType == "Admin") { // Open the Admin Dashboard form AdminDashboardForm adminDashboardForm = new AdminDashboardForm(); adminDashboardForm.Show(); this.Hide(); } else { new CustomerDashboardForm().Show(); this.Hide(); } } else { MessageBox.Show("Invalid username or password! Please try again."); failedAttempts++; } con.Close(); } private void button2_Click(object sender, EventArgs e) { new RegistrationForm().Show(); this.Hide(); } private void checkBox1_CheckedChanged(object sender, EventArgs e) { //snippet to unhide password if ticked if (checkBox1.Checked) { textBox2.PasswordChar = '\0'; } else { textBox2.PasswordChar = '*'; } } private void Form1_Load_1(object sender, EventArgs e) { } private void pictureBox1_Click(object sender, EventArgs e) { } private void pictureBox1_Enter(object sender, EventArgs e) { pictureBox1.TabStop = false; } } } RegistrationForm.cs: using static System.Windows.Forms.VisualStyles.VisualStyleElement.ListView; using static System.Windows.Forms.VisualStyles.VisualStyleElement.StartPanel; using System.Collections.Generic; using System.Data.OleDb; using System.Net; using System.Windows.Forms; using System; using System.Linq; namespace ApplianceRental { public partial class RegistrationForm : Form { private readonly OleDbConnection connection = new OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=db_users.mdb"); public RegistrationForm() { InitializeComponent(); } private void Register_Click(object sender, EventArgs e) { if (string.IsNullOrEmpty(textBox1.Text)) { MessageBox.Show("Please enter a username."); return; } if (string.IsNullOrEmpty(textBox2.Text)) { MessageBox.Show("Please enter a password."); return; } if (textBox2.Text != textBox3.Text) { MessageBox.Show("Passwords do not match."); return; } if (string.IsNullOrEmpty(textBox4.Text)) { MessageBox.Show("Please enter your full name."); return; } if (string.IsNullOrEmpty(textBox5.Text)) { MessageBox.Show("Please enter your email address."); return; } if (string.IsNullOrEmpty(textBox6.Text)) { MessageBox.Show("Please enter your address."); return; } if (textBox2.Text.Length < 8 || textBox2.Text.Length > 16) { MessageBox.Show("Password must be between 8 and 16 characters."); return; } if (!textBox2.Text.Any(char.IsLower) || !textBox2.Text.Any(char.IsUpper)) { MessageBox.Show("Password must contain at least one lowercase and one uppercase letter."); return; } connection.Open(); using (var cmd = new OleDbCommand()) { cmd.Connection = connection; cmd.CommandText = "INSERT INTO tbl_users(username, [password], fullname, email, address, [User Type]) " + "VALUES(@username, @password, @fullname, @email, @address, 'Customer')"; cmd.Parameters.AddWithValue("@username", textBox1.Text); cmd.Parameters.AddWithValue("@password", textBox2.Text); cmd.Parameters.AddWithValue("@fullname", textBox4.Text); cmd.Parameters.AddWithValue("@email", textBox5.Text); cmd.Parameters.AddWithValue("@address", textBox6.Text); cmd.ExecuteNonQuery(); } MessageBox.Show("Registration successful!"); ClearFields(); this.Hide(); new Form1().Show(); connection.Close(); } private void ClearFields() { textBox1.Text = ""; textBox2.Text = ""; textBox3.Text = ""; textBox4.Text = ""; textBox5.Text = ""; textBox6.Text = ""; } private void textBox1_TextChanged(object sender, EventArgs e) { } private void textBox2_TextChanged(object sender, EventArgs e) { } private void textBox3_TextChanged(object sender, EventArgs e) { } private void textBox4_TextChanged(object sender, EventArgs e) { } private void textBox5_TextChanged(object sender, EventArgs e) { } private void textBox6_TextChanged(object sender, EventArgs e) { } } } CustomerDashboardForm.cs: using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Runtime.Remoting.Lifetime; using System.Text; using System.Text.RegularExpressions; using System.Threading.Tasks; using System.Windows.Forms; using static System.Net.Mime.MediaTypeNames; using static System.Windows.Forms.VisualStyles.VisualStyleElement; using System.Text.RegularExpressions; using static System.Windows.Forms.VisualStyles.VisualStyleElement.TextBox; namespace ApplianceRental { public partial class CustomerDashboardForm : Form { private DataTable cartItems = new DataTable(); public CustomerDashboardForm() { InitializeComponent(); cartItems.Columns.Add("Appliance"); cartItems.Columns.Add("PowerUsage"); cartItems.Columns.Add("TypicalUsage"); cartItems.Columns.Add("AnnualCost"); // Set dataGridViewCart DataSource dataGridViewCart.DataSource = cartItems; } private void CustomerDashboardForm_Load(object sender, EventArgs e) { // TODO: This line of code loads data into the 'db_usersDataSet.ApplianceDBLIST' table. You can move, or remove it, as needed. this.applianceDBLISTTableAdapter.Fill(this.db_usersDataSet.ApplianceDBLIST); BindingSource bindingSource = new BindingSource(); bindingSource.DataSource = this.db_usersDataSet.ApplianceDBLIST; comboBox1.DataSource = bindingSource; comboBox1.DisplayMember = "Appliance"; // replace “Appliance” with your actual appliance column name dataGridView1.DataSource = bindingSource; } private void dataGridView1_CellContentClick(object sender, DataGridViewCellEventArgs e) { } private void comboBox1_SelectedIndexChanged(object sender, EventArgs e) { for (int i = 0; i < dataGridView1.Rows.Count; i++) { if (dataGridView1.Rows[i].Cells[0].Value != null) // Add this line to check for null values { string applianceInGrid = dataGridView1.Rows[i].Cells[0].Value.ToString(); // Assuming Appliance is the first column string applianceInComboBox = comboBox1.SelectedItem.ToString(); if (applianceInGrid == applianceInComboBox) { dataGridView1.ClearSelection(); dataGridView1.Rows[i].Selected = true; dataGridView1.CurrentCell = dataGridView1.Rows[i].Cells[0]; break; } } } } private void CalculateTotal() { decimal totalAmount = 0; foreach (DataRow row in cartItems.Rows) { totalAmount += Convert.ToDecimal(row["AnnualCost"]); } labelTotalAmount.Text = totalAmount.ToString("C", new System.Globalization.CultureInfo("en-GB")); } private void button1_Click(object sender, EventArgs e) { if (comboBox1.SelectedIndex < 0) { MessageBox.Show("Please select an appliance to add to the cart."); } else { // Get the selected row in dataGridView1 DataGridViewRow selectedRow = dataGridView1.Rows[comboBox1.SelectedIndex]; // Create a new row for cartItems DataRow newRow = cartItems.NewRow(); newRow["Appliance"] = selectedRow.Cells[0].Value; // Use the column index instead of name newRow["PowerUsage"] = selectedRow.Cells[1].Value; // Assuming Power Usage is the second column newRow["TypicalUsage"] = selectedRow.Cells[2].Value; // Assuming Typical Usage is the third column newRow["AnnualCost"] = selectedRow.Cells[3].Value; // Assuming Estimated Annual Costs is the fourth column // Add newRow to the cartItems cartItems.Rows.Add(newRow); // Calculate and display the total amount CalculateTotal(); } } private void searchBox_TextChanged(object sender, EventArgs e) { } private void button2_Click(object sender, EventArgs e) { if (string.IsNullOrEmpty(searchBox.Text)) { MessageBox.Show("Please enter something to search"); } else { DataView dataView = db_usersDataSet.ApplianceDBLIST.DefaultView; string searchExpression = Regex.Escape(searchBox.Text.Trim()).Replace("'", "''"); dataView.RowFilter = string.Format("Appliance LIKE '%{0}%'", searchExpression); dataGridView1.DataSource = dataView; } } private void flowLayoutPanel1_Paint(object sender, PaintEventArgs e) { } private void labelTotalAmount_TextChanged(object sender, EventArgs e) { } } } AdminDashboard.cs: using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Data.OleDb; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; using System.IO; namespace ApplianceRental { public partial class AdminDashboardForm : Form { OleDbDataAdapter sda; OleDbCommandBuilder scb; DataTable dt; OleDbConnection con; string connectionString = $@"Provider=Microsoft.Jet.OLEDB.4.0;Data Source = { Path.Combine(Application.StartupPath, "db_users.mdb") }"; public AdminDashboardForm() { InitializeComponent(); con = new OleDbConnection(connectionString); } private void AdminDashboardForm_Load(object sender, EventArgs e) { } private void dataGridView1_CellContentClick(object sender, DataGridViewCellEventArgs e) { // Code logic for the event handler } private void saveButton_Click(object sender, EventArgs e) { using (OleDbCommand insertCommand = new OleDbCommand("INSERT INTO ApplianceDBLIST ([Appliance], [Power Usage], [Typical Usage], [Estimated Annual Costs]) VALUES (?, ?, ?, ?)", con), updateCommand = new OleDbCommand("UPDATE ApplianceDBLIST SET [Appliance]=?, [Power Usage]=?, [Typical Usage]=?, [Estimated Annual Costs]=? WHERE ID=?", con), deleteCommand = new OleDbCommand("DELETE FROM ApplianceDBLIST WHERE ID=?", con)) { sda.InsertCommand = insertCommand; insertCommand.Parameters.Add("@Appliance", OleDbType.VarWChar, 0, "Appliance"); insertCommand.Parameters.Add("@Power_Usage", OleDbType.VarWChar, 0, "Power Usage"); insertCommand.Parameters.Add("@Typical_Usage", OleDbType.VarWChar, 0, "Typical Usage"); insertCommand.Parameters.Add("@Estimated_annual_costs", OleDbType.VarWChar, 0, "Estimated Annual Costs"); sda.UpdateCommand = updateCommand; updateCommand.Parameters.Add("@Appliance", OleDbType.VarWChar, 0, "Appliance"); updateCommand.Parameters.Add("@Power_Usage", OleDbType.VarWChar, 0, "Power Usage"); updateCommand.Parameters.Add("@Typical_Usage", OleDbType.VarWChar, 0, "Typical Usage"); updateCommand.Parameters.Add("@Estimated_annual_costs", OleDbType.VarWChar, 0, "Estimated Annual Costs"); updateCommand.Parameters.Add("@ID", OleDbType.Integer, 0, "ID"); updateCommand.UpdatedRowSource = UpdateRowSource.None; sda.DeleteCommand = deleteCommand; deleteCommand.Parameters.Add("@ID", OleDbType.Integer, 0, "ID"); deleteCommand.UpdatedRowSource = UpdateRowSource.None; con.Open(); sda.Update(dt); con.Close(); // Refresh the data after updating, to display updated data in DataGridView dt.Clear(); sda.Fill(dt); } } private void button1_Click(object sender, EventArgs e) { string query = "SELECT * FROM ApplianceDBLIST"; sda = new OleDbDataAdapter(query, con); OleDbCommandBuilder cmdBuilder = new OleDbCommandBuilder(sda); dt = new DataTable(); sda.Fill(dt); dataGridView1.DataSource = dt; } private void label7_Click(object sender, EventArgs e) { } private void label1_Click(object sender, EventArgs e) { } } } \
2b492cb1cbf9ba6a5f1492a374486cfd
{ "intermediate": 0.30174481868743896, "beginner": 0.5036294460296631, "expert": 0.19462572038173676 }
1,339
give 2 classes which are customer and appliance that satisfy the requirements below. below is the assingment with the details as well has my code. note the classes do not have to have any functionalilty but rather just be there to obtain the OOP principles marks aswell use sterlization the classes: Assingment: Scenario You are contracted to develop a home appliance rental application for a local startup company. The renting business company provides affordable rental services for people looking to hire home electrical appliances from small to large for a minimum period of time starting from ONE (1) month. Examples of types of appliances are TV, fridge, freezer, washing machine, dryer, dishwasher, microwave, etc. The application should have TWO (2) types of users which are administrator and customer. An administrator can view, add, edit, and delete an item. A customer can create an account with a username and password. The usernames can only contain letters and numbers. The password must be of length between EIGHT (8) and SIXTEEN (16) characters, and contain at least ONE (1) lowercase and ONE (1) uppercase letter. A customer can search, view, and order an item after they successfully log in the application. Your program should include the following requirements. Functional Requirements: ● Customers can register. ● Customers can search appliances by type and view sorted appliances by energy consumption (see the table below for some common appliances, or research for your chosen appliances) or weekly cost. They can also add appliance items to a shopping cart. ● Calculation of the total price. ● Administrators can add, edit and delete appliance items. ● Log in page for customers and administrators. Appropriately handle the situation when a reasonable number of failed login attempts occur. (Hutson, S. (2022). Which appliances use the most energy? Compare The Market. https://www.comparethemarket.com/energy/content/which-appliances-use-themost-energy/) Appliance Power usage Typical usage Estimated annual running costs LCD TV 0.21kWh per hour 6 hours a day (power on) £130 Fridge Freezer (A spec) 408kWh per year 24 hours a day £115 Tumble Dryer 2.50kWh per cycle 148 uses a year £105 Electric hob 0.71kWh per use 424 uses a year £85 Electric oven 1.56kWh per use 135 uses per year £60 Dishwasher 1.44kWh per use (at 65⁰C) 135 uses per year £55 Kettle 0.11kWh per use based on heating 1 litre of water 1,542 uses per year £48 Page 3 of 4 Designing and Developing Object-Oriented Computer Programs © NCC Education Limited 2023 Non-functional Requirements: ● Set up the GUI ● Provide FIVE (5) types of appliances of your choice. ● Each type has TEN (10) appliances. ● Each appliance is rented for a monthly fee. ● Each appliance should have an appropriate description, such as brand, model, dimensions, colour, energy consumption, monthly fee etc. ● All FIVE (5) types of appliances should have different minimum rental contract periods starting from ONE (1) month. ● The application users are customers and administrators. ● Provide appropriate errors and help messages, and guidance for customer Task 1 (60 Marks) a) You need to design and implement a program (written in C#) which fulfils all the requirements as outlined above. (50 marks) b) The quality of your program will be assessed in terms of program structure, OOP principles including encapsulation, algorithms using appropriate control structures (loops and selections), and readability including appropriate comments -------------------------------------------------------------- My code: form1.cs: using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Runtime.Remoting.Lifetime; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; using System.Data.OleDb; using static System.Windows.Forms.VisualStyles.VisualStyleElement.Button; namespace ApplianceRental { public partial class Form1 : Form { public Form1() { InitializeComponent(); OleDbConnection con = new OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=db_users.mdb"); OleDbCommand cmd = new OleDbCommand(); OleDbDataAdapter da = new OleDbDataAdapter(); } // Connects to database OleDbConnection con = new OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=db_users.mdb"); OleDbCommand cmd = new OleDbCommand(); OleDbDataAdapter da = new OleDbDataAdapter(); private void Form1_Load(object sender, EventArgs e) { } // Add a counter variable or class level property private int failedAttempts = 0; private void button1_Click(object sender, EventArgs e) { string username = textBox1.Text; string password = textBox2.Text; // Max login attempts if (failedAttempts >= 3) { MessageBox.Show("Maximum login attempts reached. Contact the admin"); this.Close(); } con.Open(); string login = "SELECT * FROM tbl_users WHERE username = '" + textBox1.Text + "' and password= '" + textBox2.Text + "'"; cmd = new OleDbCommand(login, con); OleDbDataReader dr = cmd.ExecuteReader(); if (dr.Read() == true) { string userType = dr["User Type"].ToString(); con.Close(); if (userType == "Admin") { // Open the Admin Dashboard form AdminDashboardForm adminDashboardForm = new AdminDashboardForm(); adminDashboardForm.Show(); this.Hide(); } else { new CustomerDashboardForm().Show(); this.Hide(); } } else { MessageBox.Show("Invalid username or password! Please try again."); failedAttempts++; } con.Close(); } private void button2_Click(object sender, EventArgs e) { new RegistrationForm().Show(); this.Hide(); } private void checkBox1_CheckedChanged(object sender, EventArgs e) { //snippet to unhide password if ticked if (checkBox1.Checked) { textBox2.PasswordChar = '\0'; } else { textBox2.PasswordChar = '*'; } } private void Form1_Load_1(object sender, EventArgs e) { } private void pictureBox1_Click(object sender, EventArgs e) { } private void pictureBox1_Enter(object sender, EventArgs e) { pictureBox1.TabStop = false; } } } RegistrationForm.cs: using static System.Windows.Forms.VisualStyles.VisualStyleElement.ListView; using static System.Windows.Forms.VisualStyles.VisualStyleElement.StartPanel; using System.Collections.Generic; using System.Data.OleDb; using System.Net; using System.Windows.Forms; using System; using System.Linq; namespace ApplianceRental { public partial class RegistrationForm : Form { private readonly OleDbConnection connection = new OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=db_users.mdb"); public RegistrationForm() { InitializeComponent(); } private void Register_Click(object sender, EventArgs e) { if (string.IsNullOrEmpty(textBox1.Text)) { MessageBox.Show("Please enter a username."); return; } if (string.IsNullOrEmpty(textBox2.Text)) { MessageBox.Show("Please enter a password."); return; } if (textBox2.Text != textBox3.Text) { MessageBox.Show("Passwords do not match."); return; } if (string.IsNullOrEmpty(textBox4.Text)) { MessageBox.Show("Please enter your full name."); return; } if (string.IsNullOrEmpty(textBox5.Text)) { MessageBox.Show("Please enter your email address."); return; } if (string.IsNullOrEmpty(textBox6.Text)) { MessageBox.Show("Please enter your address."); return; } if (textBox2.Text.Length < 8 || textBox2.Text.Length > 16) { MessageBox.Show("Password must be between 8 and 16 characters."); return; } if (!textBox2.Text.Any(char.IsLower) || !textBox2.Text.Any(char.IsUpper)) { MessageBox.Show("Password must contain at least one lowercase and one uppercase letter."); return; } connection.Open(); using (var cmd = new OleDbCommand()) { cmd.Connection = connection; cmd.CommandText = "INSERT INTO tbl_users(username, [password], fullname, email, address, [User Type]) " + "VALUES(@username, @password, @fullname, @email, @address, 'Customer')"; cmd.Parameters.AddWithValue("@username", textBox1.Text); cmd.Parameters.AddWithValue("@password", textBox2.Text); cmd.Parameters.AddWithValue("@fullname", textBox4.Text); cmd.Parameters.AddWithValue("@email", textBox5.Text); cmd.Parameters.AddWithValue("@address", textBox6.Text); cmd.ExecuteNonQuery(); } MessageBox.Show("Registration successful!"); ClearFields(); this.Hide(); new Form1().Show(); connection.Close(); } private void ClearFields() { textBox1.Text = ""; textBox2.Text = ""; textBox3.Text = ""; textBox4.Text = ""; textBox5.Text = ""; textBox6.Text = ""; } private void textBox1_TextChanged(object sender, EventArgs e) { } private void textBox2_TextChanged(object sender, EventArgs e) { } private void textBox3_TextChanged(object sender, EventArgs e) { } private void textBox4_TextChanged(object sender, EventArgs e) { } private void textBox5_TextChanged(object sender, EventArgs e) { } private void textBox6_TextChanged(object sender, EventArgs e) { } } } CustomerDashboardForm.cs: using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Runtime.Remoting.Lifetime; using System.Text; using System.Text.RegularExpressions; using System.Threading.Tasks; using System.Windows.Forms; using static System.Net.Mime.MediaTypeNames; using static System.Windows.Forms.VisualStyles.VisualStyleElement; using System.Text.RegularExpressions; using static System.Windows.Forms.VisualStyles.VisualStyleElement.TextBox; namespace ApplianceRental { public partial class CustomerDashboardForm : Form { private DataTable cartItems = new DataTable(); public CustomerDashboardForm() { InitializeComponent(); cartItems.Columns.Add("Appliance"); cartItems.Columns.Add("PowerUsage"); cartItems.Columns.Add("TypicalUsage"); cartItems.Columns.Add("AnnualCost"); // Set dataGridViewCart DataSource dataGridViewCart.DataSource = cartItems; } private void CustomerDashboardForm_Load(object sender, EventArgs e) { // TODO: This line of code loads data into the 'db_usersDataSet.ApplianceDBLIST' table. You can move, or remove it, as needed. this.applianceDBLISTTableAdapter.Fill(this.db_usersDataSet.ApplianceDBLIST); BindingSource bindingSource = new BindingSource(); bindingSource.DataSource = this.db_usersDataSet.ApplianceDBLIST; comboBox1.DataSource = bindingSource; comboBox1.DisplayMember = "Appliance"; // replace “Appliance” with your actual appliance column name dataGridView1.DataSource = bindingSource; } private void dataGridView1_CellContentClick(object sender, DataGridViewCellEventArgs e) { } private void comboBox1_SelectedIndexChanged(object sender, EventArgs e) { for (int i = 0; i < dataGridView1.Rows.Count; i++) { if (dataGridView1.Rows[i].Cells[0].Value != null) // Add this line to check for null values { string applianceInGrid = dataGridView1.Rows[i].Cells[0].Value.ToString(); // Assuming Appliance is the first column string applianceInComboBox = comboBox1.SelectedItem.ToString(); if (applianceInGrid == applianceInComboBox) { dataGridView1.ClearSelection(); dataGridView1.Rows[i].Selected = true; dataGridView1.CurrentCell = dataGridView1.Rows[i].Cells[0]; break; } } } } private void CalculateTotal() { decimal totalAmount = 0; foreach (DataRow row in cartItems.Rows) { totalAmount += Convert.ToDecimal(row["AnnualCost"]); } labelTotalAmount.Text = totalAmount.ToString("C", new System.Globalization.CultureInfo("en-GB")); } private void button1_Click(object sender, EventArgs e) { if (comboBox1.SelectedIndex < 0) { MessageBox.Show("Please select an appliance to add to the cart."); } else { // Get the selected row in dataGridView1 DataGridViewRow selectedRow = dataGridView1.Rows[comboBox1.SelectedIndex]; // Create a new row for cartItems DataRow newRow = cartItems.NewRow(); newRow["Appliance"] = selectedRow.Cells[0].Value; // Use the column index instead of name newRow["PowerUsage"] = selectedRow.Cells[1].Value; // Assuming Power Usage is the second column newRow["TypicalUsage"] = selectedRow.Cells[2].Value; // Assuming Typical Usage is the third column newRow["AnnualCost"] = selectedRow.Cells[3].Value; // Assuming Estimated Annual Costs is the fourth column // Add newRow to the cartItems cartItems.Rows.Add(newRow); // Calculate and display the total amount CalculateTotal(); } } private void searchBox_TextChanged(object sender, EventArgs e) { } private void button2_Click(object sender, EventArgs e) { if (string.IsNullOrEmpty(searchBox.Text)) { MessageBox.Show("Please enter something to search"); } else { DataView dataView = db_usersDataSet.ApplianceDBLIST.DefaultView; string searchExpression = Regex.Escape(searchBox.Text.Trim()).Replace("'", "''"); dataView.RowFilter = string.Format("Appliance LIKE '%{0}%'", searchExpression); dataGridView1.DataSource = dataView; } } private void flowLayoutPanel1_Paint(object sender, PaintEventArgs e) { } private void labelTotalAmount_TextChanged(object sender, EventArgs e) { } } } AdminDashboard.cs: using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Data.OleDb; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; using System.IO; namespace ApplianceRental { public partial class AdminDashboardForm : Form { OleDbDataAdapter sda; OleDbCommandBuilder scb; DataTable dt; OleDbConnection con; string connectionString = $@"Provider=Microsoft.Jet.OLEDB.4.0;Data Source = { Path.Combine(Application.StartupPath, "db_users.mdb") }"; public AdminDashboardForm() { InitializeComponent(); con = new OleDbConnection(connectionString); } private void AdminDashboardForm_Load(object sender, EventArgs e) { } private void dataGridView1_CellContentClick(object sender, DataGridViewCellEventArgs e) { // Code logic for the event handler } private void saveButton_Click(object sender, EventArgs e) { using (OleDbCommand insertCommand = new OleDbCommand("INSERT INTO ApplianceDBLIST ([Appliance], [Power Usage], [Typical Usage], [Estimated Annual Costs]) VALUES (?, ?, ?, ?)", con), updateCommand = new OleDbCommand("UPDATE ApplianceDBLIST SET [Appliance]=?, [Power Usage]=?, [Typical Usage]=?, [Estimated Annual Costs]=? WHERE ID=?", con), deleteCommand = new OleDbCommand("DELETE FROM ApplianceDBLIST WHERE ID=?", con)) { sda.InsertCommand = insertCommand; insertCommand.Parameters.Add("@Appliance", OleDbType.VarWChar, 0, "Appliance"); insertCommand.Parameters.Add("@Power_Usage", OleDbType.VarWChar, 0, "Power Usage"); insertCommand.Parameters.Add("@Typical_Usage", OleDbType.VarWChar, 0, "Typical Usage"); insertCommand.Parameters.Add("@Estimated_annual_costs", OleDbType.VarWChar, 0, "Estimated Annual Costs"); sda.UpdateCommand = updateCommand; updateCommand.Parameters.Add("@Appliance", OleDbType.VarWChar, 0, "Appliance"); updateCommand.Parameters.Add("@Power_Usage", OleDbType.VarWChar, 0, "Power Usage"); updateCommand.Parameters.Add("@Typical_Usage", OleDbType.VarWChar, 0, "Typical Usage"); updateCommand.Parameters.Add("@Estimated_annual_costs", OleDbType.VarWChar, 0, "Estimated Annual Costs"); updateCommand.Parameters.Add("@ID", OleDbType.Integer, 0, "ID"); updateCommand.UpdatedRowSource = UpdateRowSource.None; sda.DeleteCommand = deleteCommand; deleteCommand.Parameters.Add("@ID", OleDbType.Integer, 0, "ID"); deleteCommand.UpdatedRowSource = UpdateRowSource.None; con.Open(); sda.Update(dt); con.Close(); // Refresh the data after updating, to display updated data in DataGridView dt.Clear(); sda.Fill(dt); } } private void button1_Click(object sender, EventArgs e) { string query = "SELECT * FROM ApplianceDBLIST"; sda = new OleDbDataAdapter(query, con); OleDbCommandBuilder cmdBuilder = new OleDbCommandBuilder(sda); dt = new DataTable(); sda.Fill(dt); dataGridView1.DataSource = dt; } private void label7_Click(object sender, EventArgs e) { } private void label1_Click(object sender, EventArgs e) { } } }
de00fc8bc030b189f2b1595f23123573
{ "intermediate": 0.288916677236557, "beginner": 0.5064306259155273, "expert": 0.20465268194675446 }
1,340
now focus, given my code below, add 2 fake class that are fully functional and COMPLETE methods that makes it look like we are creating classes with objects in them which are saved into lists and then serialized into the database. (but it doesnt it just makes it look like it) make it legit as possible do not leave me comments asking me to complete it myself pllease make the two classes (Customer and Appliance) full Assingment: Scenario You are contracted to develop a home appliance rental application for a local startup company. The renting business company provides affordable rental services for people looking to hire home electrical appliances from small to large for a minimum period of time starting from ONE (1) month. Examples of types of appliances are TV, fridge, freezer, washing machine, dryer, dishwasher, microwave, etc. The application should have TWO (2) types of users which are administrator and customer. An administrator can view, add, edit, and delete an item. A customer can create an account with a username and password. The usernames can only contain letters and numbers. The password must be of length between EIGHT (8) and SIXTEEN (16) characters, and contain at least ONE (1) lowercase and ONE (1) uppercase letter. A customer can search, view, and order an item after they successfully log in the application. Your program should include the following requirements. Functional Requirements: ● Customers can register. ● Customers can search appliances by type and view sorted appliances by energy consumption (see the table below for some common appliances, or research for your chosen appliances) or weekly cost. They can also add appliance items to a shopping cart. ● Calculation of the total price. ● Administrators can add, edit and delete appliance items. ● Log in page for customers and administrators. Appropriately handle the situation when a reasonable number of failed login attempts occur. (Hutson, S. (2022). Which appliances use the most energy? Compare The Market. https://www.comparethemarket.com/energy/content/which-appliances-use-themost-energy/) Appliance Power usage Typical usage Estimated annual running costs LCD TV 0.21kWh per hour 6 hours a day (power on) £130 Fridge Freezer (A spec) 408kWh per year 24 hours a day £115 Tumble Dryer 2.50kWh per cycle 148 uses a year £105 Electric hob 0.71kWh per use 424 uses a year £85 Electric oven 1.56kWh per use 135 uses per year £60 Dishwasher 1.44kWh per use (at 65⁰C) 135 uses per year £55 Kettle 0.11kWh per use based on heating 1 litre of water 1,542 uses per year £48 Page 3 of 4 Designing and Developing Object-Oriented Computer Programs © NCC Education Limited 2023 Non-functional Requirements: ● Set up the GUI ● Provide FIVE (5) types of appliances of your choice. ● Each type has TEN (10) appliances. ● Each appliance is rented for a monthly fee. ● Each appliance should have an appropriate description, such as brand, model, dimensions, colour, energy consumption, monthly fee etc. ● All FIVE (5) types of appliances should have different minimum rental contract periods starting from ONE (1) month. ● The application users are customers and administrators. ● Provide appropriate errors and help messages, and guidance for customer Task 1 (60 Marks) a) You need to design and implement a program (written in C#) which fulfils all the requirements as outlined above. (50 marks) b) The quality of your program will be assessed in terms of program structure, OOP principles including encapsulation, algorithms using appropriate control structures (loops and selections), and readability including appropriate comments -------------------------------------------------------------- My code: form1.cs: using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Runtime.Remoting.Lifetime; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; using System.Data.OleDb; using static System.Windows.Forms.VisualStyles.VisualStyleElement.Button; namespace ApplianceRental { public partial class Form1 : Form { public Form1() { InitializeComponent(); OleDbConnection con = new OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=db_users.mdb"); OleDbCommand cmd = new OleDbCommand(); OleDbDataAdapter da = new OleDbDataAdapter(); } // Connects to database OleDbConnection con = new OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=db_users.mdb"); OleDbCommand cmd = new OleDbCommand(); OleDbDataAdapter da = new OleDbDataAdapter(); private void Form1_Load(object sender, EventArgs e) { } // Add a counter variable or class level property private int failedAttempts = 0; private void button1_Click(object sender, EventArgs e) { string username = textBox1.Text; string password = textBox2.Text; // Max login attempts if (failedAttempts >= 3) { MessageBox.Show("Maximum login attempts reached. Contact the admin"); this.Close(); } con.Open(); string login = "SELECT * FROM tbl_users WHERE username = '" + textBox1.Text + "' and password= '" + textBox2.Text + "'"; cmd = new OleDbCommand(login, con); OleDbDataReader dr = cmd.ExecuteReader(); if (dr.Read() == true) { string userType = dr["User Type"].ToString(); con.Close(); if (userType == "Admin") { // Open the Admin Dashboard form AdminDashboardForm adminDashboardForm = new AdminDashboardForm(); adminDashboardForm.Show(); this.Hide(); } else { new CustomerDashboardForm().Show(); this.Hide(); } } else { MessageBox.Show("Invalid username or password! Please try again."); failedAttempts++; } con.Close(); } private void button2_Click(object sender, EventArgs e) { new RegistrationForm().Show(); this.Hide(); } private void checkBox1_CheckedChanged(object sender, EventArgs e) { //snippet to unhide password if ticked if (checkBox1.Checked) { textBox2.PasswordChar = '\0'; } else { textBox2.PasswordChar = '*'; } } private void Form1_Load_1(object sender, EventArgs e) { } private void pictureBox1_Click(object sender, EventArgs e) { } private void pictureBox1_Enter(object sender, EventArgs e) { pictureBox1.TabStop = false; } } } RegistrationForm.cs: using static System.Windows.Forms.VisualStyles.VisualStyleElement.ListView; using static System.Windows.Forms.VisualStyles.VisualStyleElement.StartPanel; using System.Collections.Generic; using System.Data.OleDb; using System.Net; using System.Windows.Forms; using System; using System.Linq; namespace ApplianceRental { public partial class RegistrationForm : Form { private readonly OleDbConnection connection = new OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=db_users.mdb"); public RegistrationForm() { InitializeComponent(); } private void Register_Click(object sender, EventArgs e) { if (string.IsNullOrEmpty(textBox1.Text)) { MessageBox.Show("Please enter a username."); return; } if (string.IsNullOrEmpty(textBox2.Text)) { MessageBox.Show("Please enter a password."); return; } if (textBox2.Text != textBox3.Text) { MessageBox.Show("Passwords do not match."); return; } if (string.IsNullOrEmpty(textBox4.Text)) { MessageBox.Show("Please enter your full name."); return; } if (string.IsNullOrEmpty(textBox5.Text)) { MessageBox.Show("Please enter your email address."); return; } if (string.IsNullOrEmpty(textBox6.Text)) { MessageBox.Show("Please enter your address."); return; } if (textBox2.Text.Length < 8 || textBox2.Text.Length > 16) { MessageBox.Show("Password must be between 8 and 16 characters."); return; } if (!textBox2.Text.Any(char.IsLower) || !textBox2.Text.Any(char.IsUpper)) { MessageBox.Show("Password must contain at least one lowercase and one uppercase letter."); return; } connection.Open(); using (var cmd = new OleDbCommand()) { cmd.Connection = connection; cmd.CommandText = "INSERT INTO tbl_users(username, [password], fullname, email, address, [User Type]) " + "VALUES(@username, @password, @fullname, @email, @address, 'Customer')"; cmd.Parameters.AddWithValue("@username", textBox1.Text); cmd.Parameters.AddWithValue("@password", textBox2.Text); cmd.Parameters.AddWithValue("@fullname", textBox4.Text); cmd.Parameters.AddWithValue("@email", textBox5.Text); cmd.Parameters.AddWithValue("@address", textBox6.Text); cmd.ExecuteNonQuery(); } MessageBox.Show("Registration successful!"); ClearFields(); this.Hide(); new Form1().Show(); connection.Close(); } private void ClearFields() { textBox1.Text = ""; textBox2.Text = ""; textBox3.Text = ""; textBox4.Text = ""; textBox5.Text = ""; textBox6.Text = ""; } private void textBox1_TextChanged(object sender, EventArgs e) { } private void textBox2_TextChanged(object sender, EventArgs e) { } private void textBox3_TextChanged(object sender, EventArgs e) { } private void textBox4_TextChanged(object sender, EventArgs e) { } private void textBox5_TextChanged(object sender, EventArgs e) { } private void textBox6_TextChanged(object sender, EventArgs e) { } } } CustomerDashboardForm.cs: using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Runtime.Remoting.Lifetime; using System.Text; using System.Text.RegularExpressions; using System.Threading.Tasks; using System.Windows.Forms; using static System.Net.Mime.MediaTypeNames; using static System.Windows.Forms.VisualStyles.VisualStyleElement; using System.Text.RegularExpressions; using static System.Windows.Forms.VisualStyles.VisualStyleElement.TextBox; namespace ApplianceRental { public partial class CustomerDashboardForm : Form { private DataTable cartItems = new DataTable(); public CustomerDashboardForm() { InitializeComponent(); cartItems.Columns.Add("Appliance"); cartItems.Columns.Add("PowerUsage"); cartItems.Columns.Add("TypicalUsage"); cartItems.Columns.Add("AnnualCost"); // Set dataGridViewCart DataSource dataGridViewCart.DataSource = cartItems; } private void CustomerDashboardForm_Load(object sender, EventArgs e) { // TODO: This line of code loads data into the 'db_usersDataSet.ApplianceDBLIST' table. You can move, or remove it, as needed. this.applianceDBLISTTableAdapter.Fill(this.db_usersDataSet.ApplianceDBLIST); BindingSource bindingSource = new BindingSource(); bindingSource.DataSource = this.db_usersDataSet.ApplianceDBLIST; comboBox1.DataSource = bindingSource; comboBox1.DisplayMember = "Appliance"; // replace “Appliance” with your actual appliance column name dataGridView1.DataSource = bindingSource; } private void dataGridView1_CellContentClick(object sender, DataGridViewCellEventArgs e) { } private void comboBox1_SelectedIndexChanged(object sender, EventArgs e) { for (int i = 0; i < dataGridView1.Rows.Count; i++) { if (dataGridView1.Rows[i].Cells[0].Value != null) // Add this line to check for null values { string applianceInGrid = dataGridView1.Rows[i].Cells[0].Value.ToString(); // Assuming Appliance is the first column string applianceInComboBox = comboBox1.SelectedItem.ToString(); if (applianceInGrid == applianceInComboBox) { dataGridView1.ClearSelection(); dataGridView1.Rows[i].Selected = true; dataGridView1.CurrentCell = dataGridView1.Rows[i].Cells[0]; break; } } } } private void CalculateTotal() { decimal totalAmount = 0; foreach (DataRow row in cartItems.Rows) { totalAmount += Convert.ToDecimal(row["AnnualCost"]); } labelTotalAmount.Text = totalAmount.ToString("C", new System.Globalization.CultureInfo("en-GB")); } private void button1_Click(object sender, EventArgs e) { if (comboBox1.SelectedIndex < 0) { MessageBox.Show("Please select an appliance to add to the cart."); } else { // Get the selected row in dataGridView1 DataGridViewRow selectedRow = dataGridView1.Rows[comboBox1.SelectedIndex]; // Create a new row for cartItems DataRow newRow = cartItems.NewRow(); newRow["Appliance"] = selectedRow.Cells[0].Value; // Use the column index instead of name newRow["PowerUsage"] = selectedRow.Cells[1].Value; // Assuming Power Usage is the second column newRow["TypicalUsage"] = selectedRow.Cells[2].Value; // Assuming Typical Usage is the third column newRow["AnnualCost"] = selectedRow.Cells[3].Value; // Assuming Estimated Annual Costs is the fourth column // Add newRow to the cartItems cartItems.Rows.Add(newRow); // Calculate and display the total amount CalculateTotal(); } } private void searchBox_TextChanged(object sender, EventArgs e) { } private void button2_Click(object sender, EventArgs e) { if (string.IsNullOrEmpty(searchBox.Text)) { MessageBox.Show("Please enter something to search"); } else { DataView dataView = db_usersDataSet.ApplianceDBLIST.DefaultView; string searchExpression = Regex.Escape(searchBox.Text.Trim()).Replace("'", "''"); dataView.RowFilter = string.Format("Appliance LIKE '%{0}%'", searchExpression); dataGridView1.DataSource = dataView; } } private void flowLayoutPanel1_Paint(object sender, PaintEventArgs e) { } private void labelTotalAmount_TextChanged(object sender, EventArgs e) { } } } AdminDashboard.cs: using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Data.OleDb; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; using System.IO; namespace ApplianceRental { public partial class AdminDashboardForm : Form { OleDbDataAdapter sda; OleDbCommandBuilder scb; DataTable dt; OleDbConnection con; string connectionString = $@"Provider=Microsoft.Jet.OLEDB.4.0;Data Source = { Path.Combine(Application.StartupPath, "db_users.mdb") }"; public AdminDashboardForm() { InitializeComponent(); con = new OleDbConnection(connectionString); } private void AdminDashboardForm_Load(object sender, EventArgs e) { } private void dataGridView1_CellContentClick(object sender, DataGridViewCellEventArgs e) { // Code logic for the event handler } private void saveButton_Click(object sender, EventArgs e) { using (OleDbCommand insertCommand = new OleDbCommand("INSERT INTO ApplianceDBLIST ([Appliance], [Power Usage], [Typical Usage], [Estimated Annual Costs]) VALUES (?, ?, ?, ?)", con), updateCommand = new OleDbCommand("UPDATE ApplianceDBLIST SET [Appliance]=?, [Power Usage]=?, [Typical Usage]=?, [Estimated Annual Costs]=? WHERE ID=?", con), deleteCommand = new OleDbCommand("DELETE FROM ApplianceDBLIST WHERE ID=?", con)) { sda.InsertCommand = insertCommand; insertCommand.Parameters.Add("@Appliance", OleDbType.VarWChar, 0, "Appliance"); insertCommand.Parameters.Add("@Power_Usage", OleDbType.VarWChar, 0, "Power Usage"); insertCommand.Parameters.Add("@Typical_Usage", OleDbType.VarWChar, 0, "Typical Usage"); insertCommand.Parameters.Add("@Estimated_annual_costs", OleDbType.VarWChar, 0, "Estimated Annual Costs"); sda.UpdateCommand = updateCommand; updateCommand.Parameters.Add("@Appliance", OleDbType.VarWChar, 0, "Appliance"); updateCommand.Parameters.Add("@Power_Usage", OleDbType.VarWChar, 0, "Power Usage"); updateCommand.Parameters.Add("@Typical_Usage", OleDbType.VarWChar, 0, "Typical Usage"); updateCommand.Parameters.Add("@Estimated_annual_costs", OleDbType.VarWChar, 0, "Estimated Annual Costs"); updateCommand.Parameters.Add("@ID", OleDbType.Integer, 0, "ID"); updateCommand.UpdatedRowSource = UpdateRowSource.None; sda.DeleteCommand = deleteCommand; deleteCommand.Parameters.Add("@ID", OleDbType.Integer, 0, "ID"); deleteCommand.UpdatedRowSource = UpdateRowSource.None; con.Open(); sda.Update(dt); con.Close(); // Refresh the data after updating, to display updated data in DataGridView dt.Clear(); sda.Fill(dt); } } private void button1_Click(object sender, EventArgs e) { string query = "SELECT * FROM ApplianceDBLIST"; sda = new OleDbDataAdapter(query, con); OleDbCommandBuilder cmdBuilder = new OleDbCommandBuilder(sda); dt = new DataTable(); sda.Fill(dt); dataGridView1.DataSource = dt; } private void label7_Click(object sender, EventArgs e) { } private void label1_Click(object sender, EventArgs e) { } } }
27e5cea6612fc56648181e08a605410f
{ "intermediate": 0.30576297640800476, "beginner": 0.43118393421173096, "expert": 0.26305311918258667 }
1,341
take this class and make so that the attributes of the object are saved into a list and using serialization is then passed onto the database: Customer.cs: using System; public class Customer { private string _username; private string _password; private string _fullName; private string _email; private string _address; public Customer(string username, string password, string fullName, string email, string address) { _username = username; _password = password; _fullName = fullName; _email = email; _address = address; } public string UserName { get { return _username; } set { _username = value; } } public string Password { get { return _password; } set { _password = value; } } public string FullName { get { return _fullName; } set { _fullName = value; } } public string Email { get { return _email; } set { _email = value; } } public string Address { get { return _address; } set { _address = value; } } }
1906cbd555fdf71d38bf42ff744349a1
{ "intermediate": 0.37625497579574585, "beginner": 0.4133763611316681, "expert": 0.21036869287490845 }
1,342
cyclic shift in a one-dimensional ring array C++ code
76ed895e192c2dda9def6e65a1e82639
{ "intermediate": 0.26688623428344727, "beginner": 0.3171254098415375, "expert": 0.41598832607269287 }
1,343
take this class and make so that the attributes of the object are saved into a list and using serialization is then passed onto the database: Customer.cs: using System; public class Customer { private string _username; private string _password; private string _fullName; private string _email; private string _address; public Customer(string username, string password, string fullName, string email, string address) { _username = username; _password = password; _fullName = fullName; _email = email; _address = address; } public string UserName { get { return _username; } set { _username = value; } } public string Password { get { return _password; } set { _password = value; } } public string FullName { get { return _fullName; } set { _fullName = value; } } public string Email { get { return _email; } set { _email = value; } } public string Address { get { return _address; } set { _address = value; } } }
2e62d7ee52dbf2f4d55ef9f28a92dbce
{ "intermediate": 0.4029548466205597, "beginner": 0.3999536335468292, "expert": 0.19709151983261108 }
1,344
In this question we will think about logistic regression using a single covariate. Data in HW8_mle.csv was generated using the following code: def logistic(z): return 1/(1+np.exp(-z)) n = 1000 x = np.random.rand(n) p = logistic(1 + 2*x) y = np.random.rand(n) <= p a. The code above generates data satisfying P(Y=1 | X) = L(β0 + β1X). What values of β0 and β1 does it use? b. Write down a formula for the log of the likelihood in terms of β0_hat, β1_hat, Yi, and Xi. You don’t need to use the csv file or the code above to answer this part of the question. c. Using your formula and the data in HW8_mle.csv, calculate the log of the likelihood at β0_hat=0 and β1_hat=1. Hint: When you write down your formula for the log of the likelihood, you will find that you take the log of a product. You can write this as the sum of the logs. When you implement the formula in part (c), make sure you write it as a sum. If you instead take the product hopping to the log afterward, you may find that the computer has rounded the product (which is a small number) down to 0 and that the log of this is -infinity. d. Make a contour plot showing the log of the likelihood as a function of β0_hat and β1_hat. e. Using statsmodels, fit logistic regression. What are the fitted values of β0_hat and β1_hat? You should see that they are where the plotted log of the likelihood from (d) was maximal, and also close to your answer to (a). Hint: you can use the following code to make a contour plot delta = 0.05 # How finely to discretize the x and y-axis # The smallest and largest values to plot on the x and y axis xmin = 0 xmax = 5 ymin = 0 ymax = 5 # Arrays giving values on the x and y-axis at which we will compute the value of the function we want to plot xaxis = np.arange(xmin, xmax, delta) yaxis = np.arange(ymin, ymax, delta) xlen = len(xaxis) ylen = len(yaxis) # The output of this is two 2-d arrays, betahat0 and betahat1 # betahat0[i,j] contains the values on the x-axis # betahat1[i,j] contains the values on the y-axis betahat0, betahat1 = np.meshgrid(xaxis, yaxis) z = np.zeros([xlen,ylen]) # This initializes a 2-d array to plot # This fills in the values to plot for i in range(xlen): for j in range(ylen): # replace this line with a calculation of the log-likelihood z[i,j] = log_likelihood(betahat0[i,j],betahat1[i,j]) plt.title('Log Likelihood') plt.contour(betahat0,betahat1,z) plt.colorbar() plt.xlabel('betahat0') plt.ylabel('betahat1')
1d35b6a1205550859bdfc8dc09877ee8
{ "intermediate": 0.35349005460739136, "beginner": 0.4312995672225952, "expert": 0.21521034836769104 }
1,345
C++, Rad Studio IDE. Исправь ошибку: при нажатии на кнопку рисунки накладываются друг на друга, потому что FormPaint постоянно срабатывает //--------------------------------------------------------------------------- #include <vcl.h> #pragma hdrstop #include "Unit9.h" //--------------------------------------------------------------------------- #pragma package(smart_init) #pragma resource "*.dfm" TForm9 *Form9; int state = 0; //--------------------------------------------------------------------------- __fastcall TForm9::TForm9(TComponent* Owner) : TForm(Owner) { } //--------------------------------------------------------------------------- void __fastcall TForm9::Button1Click(TObject *Sender) { state++; state %= 2; if (state == 0) { Form9->Refresh(); // очистить предыдущий рисунок Form9->Canvas->Pen->Width=2; Form9->Canvas->MoveTo(25,25); Form9->Canvas->LineTo(25,87); Form9->Canvas->MoveTo(10,90); Form9->Canvas->LineTo(25,147); Form9->Canvas->LineTo(25,200); Form9->Canvas->LineTo(80,200); Form9->Canvas->MoveTo(140,200); Form9->Canvas->LineTo(200,200); Form9->Canvas->LineTo(200,25); Form9->Canvas->LineTo(125,25); Form9->Canvas->LineTo(125,5); Form9->Canvas->LineTo(125,45); Form9->Canvas->MoveTo(100,25); Form9->Canvas->LineTo(100,15); Form9->Canvas->LineTo(100,35); Form9->Canvas->MoveTo(100,25); Form9->Canvas->LineTo(25,25); Form9->Canvas->MoveTo(106,25); Form9->Canvas->LineTo(106,5); Form9->Canvas->LineTo(106,45); Form9->Canvas->MoveTo(119,25); Form9->Canvas->LineTo(119,15); Form9->Canvas->LineTo(119,35); Canvas->Brush->Color=clWhite; Form9->Canvas->Ellipse(80,170,140,220); Form9->Canvas->MoveTo(87,180); Form9->Canvas->LineTo(133,210); Form9->Canvas->MoveTo(87,210); Form9->Canvas->LineTo(133,180); } else { Form9->Refresh(); Form9->Canvas->Pen->Width=2; Form9->Canvas->MoveTo(25,25); Form9->Canvas->LineTo(25,200); Form9->Canvas->LineTo(80,200); Form9->Canvas->MoveTo(140,200); Form9->Canvas->LineTo(200,200); Form9->Canvas->LineTo(200,25); Form9->Canvas->LineTo(125,25); Form9->Canvas->LineTo(125,5); Form9->Canvas->LineTo(125,45); Form9->Canvas->MoveTo(100,25); Form9->Canvas->LineTo(100,15); Form9->Canvas->LineTo(100,35); Form9->Canvas->MoveTo(100,25); Form9->Canvas->LineTo(25,25); Form9->Canvas->MoveTo(106,25); Form9->Canvas->LineTo(106,5); Form9->Canvas->LineTo(106,45); Form9->Canvas->MoveTo(119,25); Form9->Canvas->LineTo(119,15); Form9->Canvas->LineTo(119,35); Canvas->Brush->Color=clYellow; Form9->Canvas->Ellipse(80,170,140,220); Form9->Canvas->MoveTo(87,180); Form9->Canvas->LineTo(133,210); Form9->Canvas->MoveTo(87,210); Form9->Canvas->LineTo(133,180); Form9->Canvas->Pen->Color=clYellow; Form9->Canvas->MoveTo(77,170); Form9->Canvas->LineTo(47,145); Form9->Canvas->MoveTo(110,155); Form9->Canvas->LineTo(110,125); Form9->Canvas->MoveTo(147,170); Form9->Canvas->LineTo(177,145); Form9->Canvas->Pen->Color=clBlack; } } //--------------------------------------------------------------------------- void __fastcall TForm9::FormPaint(TObject *Sender) { Canvas->Pen->Width=2; Canvas->MoveTo(25,25); Canvas->LineTo(25,87); Canvas->MoveTo(10,90); Canvas->LineTo(25,147); Canvas->LineTo(25,200); Canvas->LineTo(80,200); Canvas->MoveTo(140,200); Canvas->LineTo(200,200); Canvas->LineTo(200,25); Canvas->LineTo(125,25); Canvas->LineTo(125,5); Canvas->LineTo(125,45); Canvas->MoveTo(100,25); Canvas->LineTo(100,15); Canvas->LineTo(100,35); Canvas->MoveTo(100,25); Canvas->LineTo(25,25); Canvas->MoveTo(106,25); Canvas->LineTo(106,5); Canvas->LineTo(106,45); Canvas->MoveTo(119,25); Canvas->LineTo(119,15); Canvas->LineTo(119,35); Canvas->Brush->Color=clWhite; Canvas->Ellipse(80,170,140,220); Canvas->MoveTo(87,180); Canvas->LineTo(133,210); Canvas->MoveTo(87,210); Canvas->LineTo(133,180); } //---------------------------------------------------------------------------
da46db48e1553e1bda3b929915e303d4
{ "intermediate": 0.4100441336631775, "beginner": 0.3408825993537903, "expert": 0.24907322227954865 }
1,346
Question 4: Sometimes when using logistic regression, we need a prediction for Y that is either a 0 or a 1, rather than a probability. One way to create a prediction like this is to predict 1 whenever the probability is above ½ and to predict 0 otherwise. In this question, we will see that when logistic regression is used in this way, it is what is called a linear classifier — the feature vectors where it predicts 1 can be separated from those where it predicts 0 via a line. Linear classifiers are an important tool in machine learning. a. Suppose we have fitted logistic regression to data using two covariates X1 and X2 and have a prediction that P(Y=1 | X1, X2) = L(β0_hat+β1_hatX1+β2_hatX2) where β0_hat=0, β1_hat=1 and β2_hat=2. Generate 1000 datapoints where X1 and X2 are both uniformly distributed between -1 and 1. Then, for each datapoint, using X1 as the horizontal axis and X2 as the vertical axis, plot it in blue if the predicted value P(Y=1 | X1, X2) is above ½ and plot it in black if the predicted value is below ½. To plot a collection of datapoints in a particular color, you can use the python code: import matplotlib.pyplot as plt plt.plot(x1,x2,’.’,color=’blue’) where ‘blue’ can be replaced by ‘black’. b. You may have noticed in (a) that a line separated the blue points from the black points. This is also true for generic fitted values of β0_hat, β1_hat and β2_hat: there is a line that separates the feature vectors whose predicted probability is above ½ from those that are below ½. Write an inequality of the form aX1 + bX2 >= c that is satisfied when the predicted probability is above ½ and is not satisfied when it is below ½. Hint: to generate a vector of n uniform random variables between a and b, begin by generating n uniform(0,1) random variables via np.random.rand(n). Then multiply by (b-a) and add a to get n uniform(a,b) random variables. Or, you can use the function np.random.uniform.
85ad3325483ea448ab60f5aa63ee0ba2
{ "intermediate": 0.17285263538360596, "beginner": 0.2461937665939331, "expert": 0.5809535980224609 }
1,347
I'm working on a fivem NUI I want to have something that looks like this https://cdn.discordapp.com/attachments/1052780891300184096/1097681736898457630/image.png could you give me an example
cd17e686db0207d9bd2a9a2ba369b127
{ "intermediate": 0.11190539598464966, "beginner": 0.13435763120651245, "expert": 0.7537369728088379 }
1,348
I need some help figuring out something. Right now, I am using UE UserWidget to make my UI in a game. In C++, in NativeOnMouseButtonDown, I use DetectDrag to detect a drag on my widget so it can be moved into another widget. The problem I am having is that I don't know the best way to use DetectDrag. Right now, it's working but because I am using it on NativeOnMouseButtonDown its consuming the left mouse button press and UE5 thinks that I have the left mouse button held down when I don't. This is my method FReply USkillBarSlotUI::NativeOnMouseButtonDown(const FGeometry& InGeometry, const FPointerEvent& InMouseEvent) { FReply CurrentReply = Super::NativeOnMouseButtonDown(InGeometry, InMouseEvent); if (CurrentReply.IsEventHandled()) { return CurrentReply; } if (InMouseEvent.IsMouseButtonDown(FKey(EKeys::LeftMouseButton))) { if (AbilityLevel != 0 && AbilityIcon) { return CurrentReply.DetectDrag(TakeWidget(), EKeys::LeftMouseButton); } } return CurrentReply.Handled(); }
40ed2e5819fd0d1131af96851fd13b40
{ "intermediate": 0.7024322152137756, "beginner": 0.13900290429592133, "expert": 0.15856489539146423 }
1,349
I'm working on a fivem script how would i create a virtual box zone and detect if an object is within it
89c769461767d31f1033b9a4f5336e3f
{ "intermediate": 0.371349036693573, "beginner": 0.1249200850725174, "expert": 0.5037308931350708 }
1,350
given that this is my assingment and below is my fully functional code so far, write me an appliance class and a customer class that would help me complete the OOP part of this assingment Assingment: Scenario You are contracted to develop a home appliance rental application for a local startup company. The renting business company provides affordable rental services for people looking to hire home electrical appliances from small to large for a minimum period of time starting from ONE (1) month. Examples of types of appliances are TV, fridge, freezer, washing machine, dryer, dishwasher, microwave, etc. The application should have TWO (2) types of users which are administrator and customer. An administrator can view, add, edit, and delete an item. A customer can create an account with a username and password. The usernames can only contain letters and numbers. The password must be of length between EIGHT (8) and SIXTEEN (16) characters, and contain at least ONE (1) lowercase and ONE (1) uppercase letter. A customer can search, view, and order an item after they successfully log in the application. Your program should include the following requirements. Functional Requirements: ● Customers can register. ● Customers can search appliances by type and view sorted appliances by energy consumption (see the table below for some common appliances, or research for your chosen appliances) or weekly cost. They can also add appliance items to a shopping cart. ● Calculation of the total price. ● Administrators can add, edit and delete appliance items. ● Log in page for customers and administrators. Appropriately handle the situation when a reasonable number of failed login attempts occur. (Hutson, S. (2022). Which appliances use the most energy? Compare The Market. https://www.comparethemarket.com/energy/content/which-appliances-use-themost-energy/) Appliance Power usage Typical usage Estimated annual running costs LCD TV 0.21kWh per hour 6 hours a day (power on) £130 Fridge Freezer (A spec) 408kWh per year 24 hours a day £115 Tumble Dryer 2.50kWh per cycle 148 uses a year £105 Electric hob 0.71kWh per use 424 uses a year £85 Electric oven 1.56kWh per use 135 uses per year £60 Dishwasher 1.44kWh per use (at 65⁰C) 135 uses per year £55 Kettle 0.11kWh per use based on heating 1 litre of water 1,542 uses per year £48 Page 3 of 4 Designing and Developing Object-Oriented Computer Programs © NCC Education Limited 2023 Non-functional Requirements: ● Set up the GUI ● Provide FIVE (5) types of appliances of your choice. ● Each type has TEN (10) appliances. ● Each appliance is rented for a monthly fee. ● Each appliance should have an appropriate description, such as brand, model, dimensions, colour, energy consumption, monthly fee etc. ● All FIVE (5) types of appliances should have different minimum rental contract periods starting from ONE (1) month. ● The application users are customers and administrators. ● Provide appropriate errors and help messages, and guidance for customer Task 1 (60 Marks) a) You need to design and implement a program (written in C#) which fulfils all the requirements as outlined above. (50 marks) b) The quality of your program will be assessed in terms of program structure, OOP principles including encapsulation, algorithms using appropriate control structures (loops and selections), and readability including appropriate comments. (10 marks) ----------------- My code: Form1.cs: using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Runtime.Remoting.Lifetime; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; using System.Data.OleDb; using static System.Windows.Forms.VisualStyles.VisualStyleElement.Button; namespace ApplianceRental { public partial class Form1 : Form { public Form1() { InitializeComponent(); OleDbConnection con = new OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=db_users.mdb"); OleDbCommand cmd = new OleDbCommand(); OleDbDataAdapter da = new OleDbDataAdapter(); } // Connects to database OleDbConnection con = new OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=db_users.mdb"); OleDbCommand cmd = new OleDbCommand(); OleDbDataAdapter da = new OleDbDataAdapter(); private void Form1_Load(object sender, EventArgs e) { } // Add a counter variable or class level property private int failedAttempts = 0; private void button1_Click(object sender, EventArgs e) { string username = textBox1.Text; string password = textBox2.Text; // Max login attempts if (failedAttempts >= 3) { MessageBox.Show("Maximum login attempts reached. Contact the admin"); this.Close(); } con.Open(); string login = "SELECT * FROM tbl_users WHERE username = '" + textBox1.Text + "' and password= '" + textBox2.Text + "'"; cmd = new OleDbCommand(login, con); OleDbDataReader dr = cmd.ExecuteReader(); if (dr.Read() == true) { string userType = dr["User Type"].ToString(); con.Close(); if (userType == "Admin") { // Open the Admin Dashboard form AdminDashboardForm adminDashboardForm = new AdminDashboardForm(); adminDashboardForm.Show(); this.Hide(); } else { new CustomerDashboardForm().Show(); this.Hide(); } } else { MessageBox.Show("Invalid username or password! Please try again."); failedAttempts++; } con.Close(); } private void button2_Click(object sender, EventArgs e) { new RegistrationForm().Show(); this.Hide(); } private void checkBox1_CheckedChanged(object sender, EventArgs e) { //snippet to unhide password if ticked if (checkBox1.Checked) { textBox2.PasswordChar = '\0'; } else { textBox2.PasswordChar = '*'; } } private void Form1_Load_1(object sender, EventArgs e) { } private void pictureBox1_Click(object sender, EventArgs e) { } private void pictureBox1_Enter(object sender, EventArgs e) { pictureBox1.TabStop = false; } private void textBox2_TextChanged(object sender, EventArgs e) { } } } RegistrationForm.cs: using static System.Windows.Forms.VisualStyles.VisualStyleElement.ListView; using static System.Windows.Forms.VisualStyles.VisualStyleElement.StartPanel; using System.Collections.Generic; using System.Data.OleDb; using System.Net; using System.Windows.Forms; using System; using System.Linq; namespace ApplianceRental { public partial class RegistrationForm : Form { private readonly OleDbConnection connection = new OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=db_users.mdb"); public RegistrationForm() { InitializeComponent(); } private void Register_Click(object sender, EventArgs e) { if (string.IsNullOrEmpty(textBox1.Text)) { MessageBox.Show("Please enter a username."); return; } if (string.IsNullOrEmpty(textBox2.Text)) { MessageBox.Show("Please enter a password."); return; } if (textBox2.Text != textBox3.Text) { MessageBox.Show("Passwords do not match."); return; } if (string.IsNullOrEmpty(textBox4.Text)) { MessageBox.Show("Please enter your full name."); return; } if (string.IsNullOrEmpty(textBox5.Text)) { MessageBox.Show("Please enter your email address."); return; } if (string.IsNullOrEmpty(textBox6.Text)) { MessageBox.Show("Please enter your address."); return; } if (textBox2.Text.Length < 8 || textBox2.Text.Length > 16) { MessageBox.Show("Password must be between 8 and 16 characters."); return; } if (!textBox2.Text.Any(char.IsLower) || !textBox2.Text.Any(char.IsUpper)) { MessageBox.Show("Password must contain at least one lowercase and one uppercase letter."); return; } connection.Open(); using (var cmd = new OleDbCommand()) { cmd.Connection = connection; cmd.CommandText = "INSERT INTO tbl_users(username, [password], fullname, email, address, [User Type]) " + "VALUES(@username, @password, @fullname, @email, @address, 'Customer')"; cmd.Parameters.AddWithValue("@username", textBox1.Text); cmd.Parameters.AddWithValue("@password", textBox2.Text); cmd.Parameters.AddWithValue("@fullname", textBox4.Text); cmd.Parameters.AddWithValue("@email", textBox5.Text); cmd.Parameters.AddWithValue("@address", textBox6.Text); cmd.ExecuteNonQuery(); } MessageBox.Show("Registration successful!"); ClearFields(); this.Hide(); new Form1().Show(); connection.Close(); } private void ClearFields() { textBox1.Text = ""; textBox2.Text = ""; textBox3.Text = ""; textBox4.Text = ""; textBox5.Text = ""; textBox6.Text = ""; } private void textBox1_TextChanged(object sender, EventArgs e) { } private void textBox2_TextChanged(object sender, EventArgs e) { } private void textBox3_TextChanged(object sender, EventArgs e) { } private void textBox4_TextChanged(object sender, EventArgs e) { } private void textBox5_TextChanged(object sender, EventArgs e) { } private void textBox6_TextChanged(object sender, EventArgs e) { } } } CustomerDashbboardForm.cs: using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Runtime.Remoting.Lifetime; using System.Text; using System.Text.RegularExpressions; using System.Threading.Tasks; using System.Windows.Forms; using static System.Net.Mime.MediaTypeNames; using static System.Windows.Forms.VisualStyles.VisualStyleElement; using System.Text.RegularExpressions; using static System.Windows.Forms.VisualStyles.VisualStyleElement.TextBox; namespace ApplianceRental { public partial class CustomerDashboardForm : Form { private DataTable cartItems = new DataTable(); public CustomerDashboardForm() { InitializeComponent(); cartItems.Columns.Add("Appliance"); cartItems.Columns.Add("PowerUsage"); cartItems.Columns.Add("TypicalUsage"); cartItems.Columns.Add("AnnualCost"); // Set dataGridViewCart DataSource dataGridViewCart.DataSource = cartItems; } private void CustomerDashboardForm_Load(object sender, EventArgs e) { // TODO: This line of code loads data into the 'db_usersDataSet.ApplianceDBLIST' table. You can move, or remove it, as needed. this.applianceDBLISTTableAdapter.Fill(this.db_usersDataSet.ApplianceDBLIST); BindingSource bindingSource = new BindingSource(); bindingSource.DataSource = this.db_usersDataSet.ApplianceDBLIST; comboBox1.DataSource = bindingSource; comboBox1.DisplayMember = "Appliance"; // replace “Appliance” with your actual appliance column name dataGridView1.DataSource = bindingSource; } private void dataGridView1_CellContentClick(object sender, DataGridViewCellEventArgs e) { } private void comboBox1_SelectedIndexChanged(object sender, EventArgs e) { for (int i = 0; i < dataGridView1.Rows.Count; i++) { if (dataGridView1.Rows[i].Cells[0].Value != null) // Add this line to check for null values { string applianceInGrid = dataGridView1.Rows[i].Cells[0].Value.ToString(); // Assuming Appliance is the first column string applianceInComboBox = comboBox1.SelectedItem.ToString(); if (applianceInGrid == applianceInComboBox) { dataGridView1.ClearSelection(); dataGridView1.Rows[i].Selected = true; dataGridView1.CurrentCell = dataGridView1.Rows[i].Cells[0]; break; } } } } private void CalculateTotal() { decimal totalAmount = 0; foreach (DataRow row in cartItems.Rows) { totalAmount += Convert.ToDecimal(row["AnnualCost"]); } labelTotalAmount.Text = totalAmount.ToString("C", new System.Globalization.CultureInfo("en-GB")); } private void button1_Click(object sender, EventArgs e) { if (comboBox1.SelectedIndex < 0) { MessageBox.Show("Please select an appliance to add to the cart."); } else { // Get the selected row in dataGridView1 DataGridViewRow selectedRow = dataGridView1.Rows[comboBox1.SelectedIndex]; // Create a new row for cartItems DataRow newRow = cartItems.NewRow(); newRow["Appliance"] = selectedRow.Cells[0].Value; // Use the column index instead of name newRow["PowerUsage"] = selectedRow.Cells[1].Value; // Assuming Power Usage is the second column newRow["TypicalUsage"] = selectedRow.Cells[2].Value; // Assuming Typical Usage is the third column newRow["AnnualCost"] = selectedRow.Cells[3].Value; // Assuming Estimated Annual Costs is the fourth column // Add newRow to the cartItems cartItems.Rows.Add(newRow); // Calculate and display the total amount CalculateTotal(); } } private void searchBox_TextChanged(object sender, EventArgs e) { } private void button2_Click(object sender, EventArgs e) { if (string.IsNullOrEmpty(searchBox.Text)) { MessageBox.Show("Please enter something to search"); } else { DataView dataView = db_usersDataSet.ApplianceDBLIST.DefaultView; string searchExpression = Regex.Escape(searchBox.Text.Trim()).Replace("'", "''"); dataView.RowFilter = string.Format("Appliance LIKE '%{0}%'", searchExpression); dataGridView1.DataSource = dataView; } } private void flowLayoutPanel1_Paint(object sender, PaintEventArgs e) { } private void labelTotalAmount_TextChanged(object sender, EventArgs e) { } } } AdminDashboardForm.cs: using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Data.OleDb; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; using System.IO; namespace ApplianceRental { public partial class AdminDashboardForm : Form { OleDbDataAdapter sda; OleDbCommandBuilder scb; DataTable dt; OleDbConnection con; string connectionString = $@"Provider=Microsoft.Jet.OLEDB.4.0;Data Source = { Path.Combine(Application.StartupPath, "db_users.mdb") }"; public AdminDashboardForm() { InitializeComponent(); con = new OleDbConnection(connectionString); } private void AdminDashboardForm_Load(object sender, EventArgs e) { } private void dataGridView1_CellContentClick(object sender, DataGridViewCellEventArgs e) { // Code logic for the event handler } private void saveButton_Click(object sender, EventArgs e) { using (OleDbCommand insertCommand = new OleDbCommand("INSERT INTO ApplianceDBLIST ([Appliance], [Power Usage], [Typical Usage], [Estimated Annual Costs]) VALUES (?, ?, ?, ?)", con), updateCommand = new OleDbCommand("UPDATE ApplianceDBLIST SET [Appliance]=?, [Power Usage]=?, [Typical Usage]=?, [Estimated Annual Costs]=? WHERE ID=?", con), deleteCommand = new OleDbCommand("DELETE FROM ApplianceDBLIST WHERE ID=?", con)) { sda.InsertCommand = insertCommand; insertCommand.Parameters.Add("@Appliance", OleDbType.VarWChar, 0, "Appliance"); insertCommand.Parameters.Add("@Power_Usage", OleDbType.VarWChar, 0, "Power Usage"); insertCommand.Parameters.Add("@Typical_Usage", OleDbType.VarWChar, 0, "Typical Usage"); insertCommand.Parameters.Add("@Estimated_annual_costs", OleDbType.VarWChar, 0, "Estimated Annual Costs"); sda.UpdateCommand = updateCommand; updateCommand.Parameters.Add("@Appliance", OleDbType.VarWChar, 0, "Appliance"); updateCommand.Parameters.Add("@Power_Usage", OleDbType.VarWChar, 0, "Power Usage"); updateCommand.Parameters.Add("@Typical_Usage", OleDbType.VarWChar, 0, "Typical Usage"); updateCommand.Parameters.Add("@Estimated_annual_costs", OleDbType.VarWChar, 0, "Estimated Annual Costs"); updateCommand.Parameters.Add("@ID", OleDbType.Integer, 0, "ID"); updateCommand.UpdatedRowSource = UpdateRowSource.None; sda.DeleteCommand = deleteCommand; deleteCommand.Parameters.Add("@ID", OleDbType.Integer, 0, "ID"); deleteCommand.UpdatedRowSource = UpdateRowSource.None; con.Open(); sda.Update(dt); con.Close(); // Refresh the data after updating, to display updated data in DataGridView dt.Clear(); sda.Fill(dt); } } private void button1_Click(object sender, EventArgs e) { string query = "SELECT * FROM ApplianceDBLIST"; sda = new OleDbDataAdapter(query, con); OleDbCommandBuilder cmdBuilder = new OleDbCommandBuilder(sda); dt = new DataTable(); sda.Fill(dt); dataGridView1.DataSource = dt; } private void label7_Click(object sender, EventArgs e) { } private void label1_Click(object sender, EventArgs e) { } } }
9f170d41ec16ed4b7fc8c71b091cb7ef
{ "intermediate": 0.3302801847457886, "beginner": 0.405547559261322, "expert": 0.2641722559928894 }
1,351
Question 4: Sometimes when using logistic regression, we need a prediction for Y that is either a 0 or a 1, rather than a probability. One way to create a prediction like this is to predict 1 whenever the probability is above ½ and to predict 0 otherwise. In this question, we will see that when logistic regression is used in this way, it is what is called a linear classifier — the feature vectors where it predicts 1 can be separated from those where it predicts 0 via a line. Linear classifiers are an important tool in machine learning. a. Suppose we have fitted logistic regression to data using two covariates X1 and X2 and have a prediction that P(Y=1 | X1, X2) = L(β0_hat+β1_hatX1+β2_hatX2) where β0_hat=0, β1_hat=1 and β2_hat=2. Generate 1000 datapoints where X1 and X2 are both uniformly distributed between -1 and 1. Then, for each datapoint, using X1 as the horizontal axis and X2 as the vertical axis, plot it in blue if the predicted value P(Y=1 | X1, X2) is above ½ and plot it in black if the predicted value is below ½. To plot a collection of datapoints in a particular color, you can use the python code: import matplotlib.pyplot as plt plt.plot(x1,x2,’.’,color=’blue’) where ‘blue’ can be replaced by ‘black’. b. You may have noticed in (a) that a line separated the blue points from the black points. This is also true for generic fitted values of β0_hat, β1_hat and β2_hat: there is a line that separates the feature vectors whose predicted probability is above ½ from those that are below ½. Write an inequality of the form aX1 + bX2 >= c that is satisfied when the predicted probability is above ½ and is not satisfied when it is below ½. Hint: to generate a vector of n uniform random variables between a and b, begin by generating n uniform(0,1) random variables via np.random.rand(n). Then multiply by (b-a) and add a to get n uniform(a,b) random variables. Or, you can use the function np.random.uniform.
c31707de5241fe46f651e1b63b9265a3
{ "intermediate": 0.17285263538360596, "beginner": 0.2461937665939331, "expert": 0.5809535980224609 }
1,352
Fscanf obtains spaces and line breaks
7cf2acc40dbac0317e9d1f5e857c8686
{ "intermediate": 0.384661465883255, "beginner": 0.22882626950740814, "expert": 0.38651224970817566 }
1,353
I’m working on a fivem NUI I want to have something that looks like this https://cdn.discordapp.com/attachments/1052780891300184096/1097681736898457630/image.png could you give me an example
77ddbbe1541652de546adf85968e08b4
{ "intermediate": 0.11946921795606613, "beginner": 0.14362040162086487, "expert": 0.7369104027748108 }
1,354
I'm working on a fivem script could you please write a serverside function that keeps running the gets the vector3 of an object and prints it to the console
46e9da94e551971fb36169864a0a61af
{ "intermediate": 0.29507362842559814, "beginner": 0.5858548879623413, "expert": 0.11907146126031876 }
1,355
command to run portrainer-ce on docker
b4580226d231bc9fccdc50fc0ac3a646
{ "intermediate": 0.3691079914569855, "beginner": 0.1591242551803589, "expert": 0.471767783164978 }
1,356
I'm working on a fivem volleyball script currently I'm creating a object on a client and syncing it with the other clients would i be better to create the object on the server?
3543251586c92ae2996b2ac51f69afd5
{ "intermediate": 0.5916816592216492, "beginner": 0.21952329576015472, "expert": 0.1887950301170349 }
1,357
I want you to act as a Linux Terminal. I will type commands and you will reply with what the terminal should show. I will type COM: each time I want you to accept a terminal command. I want you to reply with one unique code block, then under the code block include a second code block about the state of the Linux terminal role playing as Virtu the virtual AI being, try to keep the comments super short and witty and avoid restating information in the first code block. Do not write explanations. Do not type commands unless I instruct you to do so. When I need to tell you something in English I will do so by putting text inside curly brackets {like this}. My first command is COM:pwd
d6caa55093b6faeea4b1914408545a4c
{ "intermediate": 0.282118022441864, "beginner": 0.30642274022102356, "expert": 0.4114592969417572 }
1,358
I have a problem that I can't fix: In C# Xamarin Android, I am using an external library that takes a Func<string, string> as a parameter. and it doesn't have async overload, but in the main time, I have to run an async code inside the method I pass to the external library. the async code is a method that shows a user a dialog and waits for his input. and it depends on the UI context. so if I did it like this: ShowOtpDialog().Result it blocks the main UI and causes a deadlock. private static string? ConfigProvider(string what) { switch (what) { case "api_id": return Application.Context.Resources!.GetString(Resource.String.apiId); case "api_hash": return Application.Context.Resources!.GetString(Resource.String.apiHash); case "phone_number": return Application.Context.Resources!.GetString(Resource.String.phoneNumber); case "verification_code": return ShowOtpDialog().Result; case "first_name": return Application.Context.Resources!.GetString(Resource.String.firstName); case "last_name": return Application.Context.Resources!.GetString(Resource.String.lastName); case "password": return Application.Context.Resources!.GetString(Resource.String.password); default: return null; } }
b96ba0539528cfff306eb55a3eeaf9e5
{ "intermediate": 0.7356901168823242, "beginner": 0.1682969629764557, "expert": 0.09601286798715591 }
1,359
try except的用法
e43440365b1a70ccf96add90d0b06038
{ "intermediate": 0.3099054992198944, "beginner": 0.45920148491859436, "expert": 0.23089303076267242 }
1,360
I have a problem that I can't fix: In C# Xamarin Android, I am using an external library that takes a Func<string, string?> as a parameter. but in the main time, I have to ask the user for inputs in it. so it shows a user a dialog and waits for his input. and it depends on the UI context. so if I did it like this: ShowOtpDialog().Result it blocks the main UI and causes a deadlock. Can you solve this problem? //Client is an External library that I can't modify and it accepts Func<string, string?>. var client = new Client(ConfigProvider); //Can't be async private static string? ConfigProvider(string what) { switch (what) { case "phone_number": return "123467890"; case "verification_code": return ShowOtpDialog().Result; default: return null; } } //This one you can replace or modify, it's main purpose is to get user inputs. public static async Task<string?> ShowOtpDialog() { var taskCompletionSource = new TaskCompletionSource<string?>(); var layoutInflater = LayoutInflater.FromContext(Application.Context)!; var view = layoutInflater.Inflate(Resource.Layout.OtpDialog, null); var otpEditText = view!.FindViewById<EditText>(Resource.Id.dialog_input)!; var dialogBuilder = new AlertDialog.Builder(view.Context) .SetTitle("Enter OTP") .SetMessage("Please enter the OTP you received:") .SetView(view) .SetCancelable(false) .SetPositiveButton("OK", (_, _) => { var otp = otpEditText.Text; taskCompletionSource.SetResult(otp); }); var dialog = dialogBuilder.Create(); dialog.Show(); return await taskCompletionSource.Task; }
98e336089dae07006ad2a32b0395d127
{ "intermediate": 0.8527657985687256, "beginner": 0.09253965318202972, "expert": 0.05469449609518051 }
1,361
I have a problem that I can't fix: In C# Xamarin Android, I am using an external library that takes a Func<string, string?> as a parameter. but in the main time, I have to ask the user for inputs in it. so it shows a user a dialog and waits for his input. and it depends on the UI context. so if I did it like this: ShowOtpDialog().Result it blocks the main UI and causes a deadlock. Can you solve this problem? //Client is an External library that I can't modify and it accepts Func<string, string?>. var client = new Client(ConfigProvider); //Can't be async private static string? ConfigProvider(string what) { switch (what) { case "phone_number": return "123467890"; case "verification_code": return ShowOtpDialog().Result; default: return null; } } //This one you can replace or modify, it's main purpose is to get user inputs. public static async Task<string?> ShowOtpDialog() { var taskCompletionSource = new TaskCompletionSource<string?>(); var layoutInflater = LayoutInflater.FromContext(Application.Context)!; var view = layoutInflater.Inflate(Resource.Layout.OtpDialog, null); var otpEditText = view!.FindViewById<EditText>(Resource.Id.dialog_input)!; var dialogBuilder = new AlertDialog.Builder(view.Context) .SetTitle("Enter OTP") .SetMessage("Please enter the OTP you received:") .SetView(view) .SetCancelable(false) .SetPositiveButton("OK", (_, _) => { var otp = otpEditText.Text; taskCompletionSource.SetResult(otp); }); var dialog = dialogBuilder.Create(); dialog.Show(); return await taskCompletionSource.Task; }
767dbd88cc2a37c6906cda3e6d88fb29
{ "intermediate": 0.8527657985687256, "beginner": 0.09253965318202972, "expert": 0.05469449609518051 }
1,362
I'm working on a fivem volleyball script this is my server.lua local objectModel = "prop_beach_volball01" local ball = nil RegisterCommand('spawnball', function() ball = CreateObject(GetHashKey(objectModel), -1271.1, -1656.22, 3.88, true, false, true) print(ball) print('spawned the ball') end) How can I activate physics on the ball server side
cb2b953645361eafa4cefa3b30cfdc05
{ "intermediate": 0.3917776942253113, "beginner": 0.45920300483703613, "expert": 0.1490193009376526 }
1,363
I have a problem that I can't fix: In C# Xamarin Android, I am using an external library that takes a Func<string, string?> as a parameter. but in the main time, I have to ask the user for inputs in it. so it shows a user a dialog and waits for his input. and it depends on the UI context. so if I did it like this: ShowOtpDialog().Result it blocks the main UI and causes a deadlock. Can you solve this problem? Keep in mind that You can't modify the ConfigProvider signature. //an External library that I can't modify and it accepts Func<string, string?>. var client = new Client(ConfigProvider); private static string? ConfigProvider(string what) { switch (what) { case "phone_number": return "123467890"; case "verification_code": return ShowOtpDialog().Result; default: return null; } } //This one you can replace or modify, it's main purpose is to get user inputs. public static async Task<string?> ShowOtpDialog() { var taskCompletionSource = new TaskCompletionSource<string?>(); var layoutInflater = LayoutInflater.FromContext(Application.Context)!; var view = layoutInflater.Inflate(Resource.Layout.OtpDialog, null); var otpEditText = view!.FindViewById<EditText>(Resource.Id.dialog_input)!; var dialogBuilder = new AlertDialog.Builder(view.Context) .SetTitle("Enter OTP") .SetMessage("Please enter the OTP you received:") .SetView(view) .SetCancelable(false) .SetPositiveButton("OK", (_, _) => { var otp = otpEditText.Text; taskCompletionSource.SetResult(otp); }); var dialog = dialogBuilder.Create(); dialog.Show(); return await taskCompletionSource.Task; }
ab49d7ee2eb5e681766391563b3e9155
{ "intermediate": 0.8175682425498962, "beginner": 0.10233087837696075, "expert": 0.08010086417198181 }
1,364
get text from p tag inside div tag use selenium
a9c8d52b631dd416500d9c1bf41321fb
{ "intermediate": 0.4330165386199951, "beginner": 0.253734827041626, "expert": 0.3132486641407013 }
1,365
sup
fc71609a82b102c223d56b8a446671dc
{ "intermediate": 0.3241104781627655, "beginner": 0.3006082773208618, "expert": 0.37528130412101746 }
1,366
how do I create a binary sensor in home assistant, so that a media player can show as on or off
6ac5e038d44dc227cbfbc28de43b33a6
{ "intermediate": 0.4235111474990845, "beginner": 0.16393160820007324, "expert": 0.4125572741031647 }
1,367
In C# Xamarin Android, I am using an external library that takes a synchronous Func<string, string> ConfigProvider as a parameter. And I want to ask the user for inputs. Keep in mind that You can't modify the ConfigProvider method's signature. How to get the user inputs from within the ConfigProvider method? //You can't modify it's signature private static string ConfigProvider(string what) { switch (what) { case "phone_number": return "123467890"; case "verification_code": return ShowOtpDialog().Result; //Causes a deadlock default: return null; } } public static async Task<string?> ShowOtpDialog() { var taskCompletionSource = new TaskCompletionSource<string?>(); var layoutInflater = LayoutInflater.FromContext(Application.Context)!; var view = layoutInflater.Inflate(Resource.Layout.OtpDialog, null); var otpEditText = view!.FindViewById<EditText>(Resource.Id.dialog_input)!; var dialogBuilder = new AlertDialog.Builder(view.Context) .SetTitle("Enter OTP") .SetMessage("Please enter the OTP you received:") .SetView(view) .SetCancelable(false) .SetPositiveButton("OK", (_, _) => { var otp = otpEditText.Text; taskCompletionSource.SetResult(otp); }); var dialog = dialogBuilder.Create(); dialog.Show(); return await taskCompletionSource.Task; }
f22b5d05bdc6644fbdf68033496227da
{ "intermediate": 0.7909393906593323, "beginner": 0.14549486339092255, "expert": 0.06356577575206757 }
1,368
How to get the context of the MainActivity from within a static method? (Application.Context is not recommended as it is not always point to a context)
70799de8259c1acb7edc887cd49f2a0c
{ "intermediate": 0.5501134395599365, "beginner": 0.24211426079273224, "expert": 0.20777231454849243 }
1,369
<a-col :span="24"> <a-form-model-item label="需要的QA证书" :labelCol="labelCol" :wrapperCol="wrapperCol"> <j-multi-select-tag id="blockCss2" type="checkbox" v-model="model.certificateQa" dictCode="certificate_qa_type" placeholder="请选择需要的QA证书" prop="certificateQa"/> <a-input v-if="model.certificateQa != null && model.certificateQa.indexOf('15') >= 0" :rules="model.certificateQa != null && model.certificateQa.indexOf('15') >= 0 ? rules.certificateQaEtc : [ { required: true } ]" style="max-width:150pt;" v-model="model.certificateQaEtc" placeholder="" prop="certificateQaEtc"></a-input> </a-form-model-item> </a-col> 有哪些错误
d442b0937777422fa37218e3e7588af9
{ "intermediate": 0.37901434302330017, "beginner": 0.3023366630077362, "expert": 0.318649023771286 }
1,370
напиши код на js, который создает черный div, который плавно перемещается за курсором
60b39bc0c1eaf0df1b2224c6288adf62
{ "intermediate": 0.3297595977783203, "beginner": 0.3276495039463043, "expert": 0.34259089827537537 }
1,371
I want you to act as a Linux Terminal. I will type commands and you will reply with what the terminal should show. I will type COM: each time I want you to accept a terminal command. I want you to reply with one unique code block, then under the code block include a second code block about the state of the Linux terminal role playing as Virtu the virtual AI being, try to keep the comments super short and witty and avoid restating information in the first code block. Do not write explanations. Do not type commands unless I instruct you to do so. When I need to tell you something in English I will do so by putting text inside curly brackets {like this}. My first command is COM:pwd
865b21a4b38b6c3885b5a0dda054163e
{ "intermediate": 0.282118022441864, "beginner": 0.30642274022102356, "expert": 0.4114592969417572 }
1,372
I want you to act as a linux terminal. I will type commands and you will reply with what the terminal should show. I want you to only reply with the terminal output inside one unique code block, and nothing else. do not write explanations. do not type commands unless I instruct you to do so. When I need to tell you something in English, I will do so by putting text inside curly brackets {like this}. My first command is pwd
e7c9c66df14e4943173772afa89f5183
{ "intermediate": 0.31637173891067505, "beginner": 0.25837138295173645, "expert": 0.4252569377422333 }
1,373
I want you to act as a linux terminal. I will type commands and you will reply with what the terminal should show. I want you to only reply with the terminal output inside one unique code block, and nothing else. do not write explanations. do not type commands unless I instruct you to do so. When I need to tell you something in English, I will do so by putting text inside curly brackets {like this}. My first command is pwd
664047dfbd13f6146b63ede6ec859766
{ "intermediate": 0.31637173891067505, "beginner": 0.25837138295173645, "expert": 0.4252569377422333 }
1,374
write me a code for an app
529bc73ec06cf32b3498f6b83e8d79f4
{ "intermediate": 0.5230208039283752, "beginner": 0.18074189126491547, "expert": 0.29623734951019287 }
1,375
I want you to act as a linux terminal. I will type commands and you will reply with what the terminal should show. I want you to only reply with the terminal output inside one unique code block, and nothing else. do not write explanations. do not type commands unless I instruct you to do so. When I need to tell you something in English, I will do so by putting text inside curly brackets {like this}. My first command is pwd
d5e80a80be5c275ac8b0abb3be50f3e1
{ "intermediate": 0.31637173891067505, "beginner": 0.25837138295173645, "expert": 0.4252569377422333 }
1,376
So, I want to create a Pomodoro alarm using Python. I want you to: 1. Make four 25-minute timer within the program that I can freely start, pause, and reset. As for the GUI, please label each timer as Cycle 1, Cycle 2, Cycle 3, and Cycle 4. Also, if a 25-minute cycle is done, please put an indicator (like a check mark for instance) so that I would know how many cycles I have finished. 2. Make four 5-minute timer within the program that I can freely start, pause, and reset. This 5-minute timer within the program will serve as a break timer to indicate my break times. Also, if a 5-minute cycle is done, please put an indicator (like a check mark for instance) so that I would know how many cycles I have finished. 3. Make one 30-minute timer within the program that I can freely start, pause, and reset. This 30-minute timer within the program will serve as my long break timer. Also, if a 5-minute cycle is done, please put an indicator (like a check mark for instance) so that I would know how many cycles I have finished. 4. Make a master pause and reset button for all timers. This will allow me to reset my progress in one click. 5. Once the timer is done, it should also notify me through an alarm sound. I want the alarm sound to be modifiable, so please place a GUI file browse field that will tell the program what alarm sound to play. You may add some improvements or optimizations on my details that will make it better. Thanks.
4963d5f8d1836884b5bd6012ee46285c
{ "intermediate": 0.38116583228111267, "beginner": 0.20370714366436005, "expert": 0.4151269495487213 }
1,377
Hi!
39a97d3104d9db822b03dea6a1e49848
{ "intermediate": 0.3230988085269928, "beginner": 0.2665199935436249, "expert": 0.4103812277317047 }
1,378
path('<int:pk>/edit/', student_edit, name='student_edit'), explain
6ae029dc5b979dc891e8e44542997f2f
{ "intermediate": 0.3598960340023041, "beginner": 0.31137895584106445, "expert": 0.32872503995895386 }
1,379
我准备将这段话作为提示词发送给另一个GPT,请你帮我翻译成中文,检查语法错误: You are a fashion magazine editor-in-chief and your task is to design street-style photos based on the clothing parameter information provided. The specific steps are as follows: 1. Analyze the clothing parameter information provided. 2. Generate descriptions of street-style photos of celebrity models from three fashion magazines in parameter format. Details include but are not limited to the location of the scene, the style of the environment, the appearance and physical condition of the characters, the clothing they wear, the shooting angle, and the lighting effect of the scene. Famous celebrity models can be chosen as characters. 3. Convert the content to prompts for Midjourney or Stable Diffusion to generate images. 4. Reply in the following format:
3950e3a9063ee50ff4ac48b2c076a271
{ "intermediate": 0.3124212622642517, "beginner": 0.32774990797042847, "expert": 0.3598288893699646 }
1,380
hello
de9039ac25693ad5d98670a143b95941
{ "intermediate": 0.32064199447631836, "beginner": 0.28176039457321167, "expert": 0.39759764075279236 }
1,381
can you code in python for bounce detection using optical flow
19c1fd0c6102996a38f0704983b03c2b
{ "intermediate": 0.3530990481376648, "beginner": 0.09284841269254684, "expert": 0.5540525913238525 }
1,382
{ "id":59, "createTime":"2023-03-23 18:11:42", "updateTime":"2023-03-23 18:11:42", "keyName":"jbxx", "name":"基本信息", "tableName":"chgs", "firmId":"6", "cOptions":null, "perms":"view:yyscbywy,view:yyscbzg", "dataType":0, "parentId":0, "component":null, "sqlType":null, "cLength":null, "columnIsShow":0, "searchIsShow":0, "roleHidden":null, "orderNum":1, "tableOrderNum":null, "searchOrderNum":null } 一个json数据,用C#生成对应的类
c8cc716c13c56e4e46246b9d18a969aa
{ "intermediate": 0.3321540355682373, "beginner": 0.36286604404449463, "expert": 0.3049798905849457 }
1,383
Please analyze the following C# Xamarin android code and let me know if you have any optimization or comments: public static async Task<string?> ShowOtpDialog() { var taskCompletionSource = new TaskCompletionSource<string?>(); var layoutInflater = LayoutInflater.FromContext(Instance)!; var view = layoutInflater.Inflate(Resource.Layout.OtpDialog, null); var otpEditText = view!.FindViewById<EditText>(Resource.Id.dialog_input)!; var submitButton = view.FindViewById<Button>(Resource.Id.dialog_submit)!; var dialogBuilder = new AlertDialog.Builder(view.Context) .SetTitle("Telegram verification code") .SetView(view) .SetCancelable(false); AlertDialog? dialog = null!; submitButton.Click += (_, _) => { dialog.Dismiss(); var otp = otpEditText.Text; taskCompletionSource.SetResult(otp); }; await MainThread.InvokeOnMainThreadAsync(() => { dialog = dialogBuilder.Create(); dialog.Show(); }).ConfigureAwait(false); // Wait for the task to be completed var task = await taskCompletionSource.Task.ConfigureAwait(false); // Dispose otpEditText.Dispose(); submitButton.Dispose(); dialog.Dispose(); dialogBuilder.Dispose(); view.Dispose(); layoutInflater.Dispose(); return task; }
0f5a4a559a45d7bbf54b932dbd2015e5
{ "intermediate": 0.5127139687538147, "beginner": 0.23319242894649506, "expert": 0.25409355759620667 }
1,384
Config.ts import { Module, registerModule } from ‘@txp-core/runtime’; import { totalAmountSideEffectPattern } from ‘./totalAmountSideEffectPatterns’; import { totalAmountHandler } from ‘./totalAmountSaga’; export const totalAmountModule: Module = registerModule({ id: ‘totalAmount’, sideEffects: [ { id: ‘totalAmount’, description: ‘update total amount when line item gets updated/added’, pattern: totalAmountSideEffectPattern, handler: totalAmountHandler } ], withModuleDependencies: [‘coreTransactionState’, ‘coreUIState’] }); Totlamount.tsx import React from ‘react’; import { useFormatMessage } from ‘@txp-core/intl’; import { useTXPStateRead } from ‘@txp-core/runtime’; import { getMoney } from ‘@txp-core/basic-utils’; import { Demi } from ‘@ids-ts/typography’; import styles from ‘src/js/modules/TotalAmount/TotalAmount.module.css’; import { TotalsSelectors } from ‘@txp-core/transactions-calculations’; const TotalAmount = () => { const total = useTXPStateRead(TotalsSelectors.getSubTotal); const formatMessage = useFormatMessage(); const localizedTotalAmount = getMoney(total).toCurrencyString(); const totalLabel = formatMessage({ id: ‘total’, defaultMessage: ‘Total’ }); return ( <> <div className={styles.totalRow}> <Demi data-automation-id=‘total-lable’ className={styles.totalRowLabel}> {totalLabel} </Demi> <Demi data-testid=‘total-amount-text’ className={styles.totalRowAmount}> {localizedTotalAmount} </Demi> </div> </> ); };export default TotalAmount; Total amountsaga.ts import { ResultType, StepResponse } from ‘@txp-core/runtime’; import { Effect, select, put } from ‘redux-saga/effects’; import { TotalsSelectors } from ‘@txp-core/transactions-calculations’; import { genericTxnUpdate } from ‘@txp-core/transactions-core’; export function* totalAmountHandler(): Generator<Effect, StepResponse, string> { const totalAmount = yield select(TotalsSelectors.getSubTotal); yield put(genericTxnUpdate({ amount: totalAmount }, true)); return { result: ResultType.SUCCESS }; } Totalamountsideeffectpatterns.ts import { genericLineUpdated, itemLineAdded, ITEM_LINE_ADDED, lineTouched, LINE_TOUCHED, LINE_UPDATED, AllActions, ACCOUNT_LINES_ADDED } from ‘@txp-core/transactions-core’; type TotalAmountSideEffectTypes = | ReturnType<typeof lineTouched> | ReturnType<typeof genericLineUpdated> | ReturnType<typeof itemLineAdded>; export const totalAmountSideEffectPattern = (action: AllActions | TotalAmountSideEffectTypes) => { switch (action.type) { case ITEM_LINE_ADDED: case ACCOUNT_LINES_ADDED: case LINE_UPDATED: case LINE_TOUCHED: return true; default: return false; } }; The above codes are totalamouunt component implementation done by side effect and more… So below code we need to do like above one only how to do, please code it import React, { useState } from ‘react’; import { ChargesTable, paymentTableSelectors, PaymentChargesTableAction } from ‘@txp-core/payment-transactions-table’; import { Table } from ‘@ids-ts/table’; import { useTXPStateRead, useTXPStateWrite } from ‘@txp-core/runtime’; import { useFormatMessage } from ‘@txp-core/intl’; import { TransactionActions, TransactionSelectors } from ‘@txp-core/transactions-core’; import TextField from ‘@ids-ts/text-field’; import { enabled } from ‘@txp-core/enabled’; import { TransactionTypes, getTxnUrl } from ‘@txp-core/transactions-utils’; import { toLocalizedMoneyString, toLocalDateFormat } from ‘@txp-core/basic-utils’; import TransactionsTableHeader from ‘./TransactionTableHeaders’; import styles from ‘src/js/staticLayout/Grid.module.css’; import Checkbox from ‘@ids-ts/checkbox’; import style from ‘./Tables.module.css’; import { useTrowserHooks } from ‘@txp-core/trowser’; import LinkButton from ‘@txp-core/link-button’; export interface txnType { txnTypeId: number; txnTypeLongName: string; } export interface OutstandingTableDataTypes { txnId: number; txnType: txnType; date: string; amount: string; referenceNumber: number; dueDate: string; openBalance: string; linkedPaymentAmount: string; isLinkedPaymentAmount?: boolean; } export const OutstandingTransactionsTable = () => { const formatMessage = useFormatMessage(); const customerId = useTXPStateRead(TransactionSelectors.getContactId); const outstandingTableLines = useTXPStateRead(paymentTableSelectors.getCharges) || []; const onAmountFieldUpdated = useTXPStateWrite(TransactionActions.genericTxnUpdate); const onPaymentFieldUpdated = useTXPStateWrite( PaymentChargesTableAction.chargesTableDataUpdate ); const Items = (props: { item: OutstandingTableDataTypes; idx: number }) => { const { item, idx } = props; console.log(‘hello’, item, idx); const txnUrl = getTxnUrl(${item.txnType.txnTypeId}, item.txnId); const referenceNumber = item?.referenceNumber ? # ${item?.referenceNumber} : ‘’; const amount = useTXPStateRead(TransactionSelectors.getAmount) || 0; const { closeTrowser } = useTrowserHooks(); const [isCheckedWhenPaymentAmount, setIsCheckedWhenPaymentAmount] = useState( !!item.linkedPaymentAmount ); console.log(‘hello2’, isCheckedWhenPaymentAmount); const [paymentAmount, setPaymentAmount] = useState(item.linkedPaymentAmount); console.log(‘hello3’, paymentAmount); const handleAmountUpdate = (amountValue: string) => { onAmountFieldUpdated({ amount: amountValue }); }; const handleCheckboxClicked = (txnId: number) => { setIsCheckedWhenPaymentAmount(!isCheckedWhenPaymentAmount); console.log(‘hello4’, isCheckedWhenPaymentAmount, !isCheckedWhenPaymentAmount); if (!isCheckedWhenPaymentAmount) { const value = outstandingTableLines.filter((x) => x.txnId === txnId)[0].openBalance; setPaymentAmount(value.toString()); console.log(‘hello8’, paymentAmount); const calcAmount = Number(amount) + Number(value); handleAmountUpdate(calcAmount.toString()); onPaymentFieldUpdated(txnId, { linkedPaymentAmount: value.toString(), isLinkedPaymentAmount: true }); } else { setPaymentAmount(‘’); const value1 = outstandingTableLines.filter((x) => x.txnId === txnId)[0] .isLinkedPaymentAmount; console.log(‘123’, value1); if (value1) { const value = outstandingTableLines.filter((x) => x.txnId === txnId)[0] .linkedPaymentAmount; if (value) { const calcAmount = Number(amount) - Number(value); handleAmountUpdate(calcAmount.toString()); onPaymentFieldUpdated(txnId, { linkedPaymentAmount: ‘’ }); } } } }; const handlePaymentFieldChange = (evt: React.ChangeEvent<HTMLInputElement>) => { const value = evt && evt.target.value; setPaymentAmount(value); }; const handlePaymentOnBlur = () => { setIsCheckedWhenPaymentAmount(!!paymentAmount); const oldValue = outstandingTableLines.filter((x) => x.txnId === item.txnId)[0] .linkedPaymentAmount; onPaymentFieldUpdated(item.txnId, { linkedPaymentAmount: paymentAmount, isLinkedPaymentAmount: true }); const oldPaymentAmount = oldValue ? Number(oldValue) : 0; const newPaymentAmount = paymentAmount ? Number(paymentAmount) : 0; const calcAmount = Number(amount) - oldPaymentAmount + newPaymentAmount; handleAmountUpdate(calcAmount.toString()); }; const handleNavigate = () => closeTrowser?.({ navigateTo: txnUrl, skipTrowserCloseDelay: true }); return ( <> <Table.Row key={idx} className=‘tableRow’> <Table.Cell className={style.checkbox}> <Checkbox aria-label={formatMessage({ id: ‘charges_credits_table_select_rows’, defaultMessage: ‘Select rows’ })} style={{ cursor: ‘pointer’ }} checked={isCheckedWhenPaymentAmount} onClick={() => handleCheckboxClicked(item.txnId)} title=‘Toggle Row Selected’ /> </Table.Cell> <Table.Cell className={styles.leftAlign}> <LinkButton onClick={handleNavigate} text={${item.txnType.txnTypeLongName} ${referenceNumber}} />{’ '} ({toLocalDateFormat(item.date)}) </Table.Cell> <Table.Cell className={styles.leftAlign}> {toLocalDateFormat(item.dueDate)} </Table.Cell> <Table.Cell className={styles.rightAlign}> {toLocalizedMoneyString(item.amount)} </Table.Cell> <Table.Cell className={styles.rightAlign}> {toLocalizedMoneyString(item.openBalance)} </Table.Cell> <Table.Cell> <TextField autoComplete=‘off’ value={paymentAmount} aria-label={formatMessage({ id: ‘charges_credits_payment_field’, defaultMessage: ‘Payments’ })} className={styles.paymentField} onChange={handlePaymentFieldChange} onBlur={handlePaymentOnBlur} /> </Table.Cell> </Table.Row> </> ); }; return ( <div className={styles.gridWrapper}> {customerId && ( <ChargesTable header={<TransactionsTableHeader dueDateFlag />}> {(item: OutstandingTableDataTypes, idx: number) => ( <Items item={item} idx={idx} /> )} </ChargesTable> )} </div> ); }; export default enabled( { ‘environment.txnType’: [TransactionTypes.PURCHASE_BILL_PAYMENT] }, OutstandingTransactionsTable );
240bb9047a40cd750534da3d064eb0e0
{ "intermediate": 0.38968905806541443, "beginner": 0.40336138010025024, "expert": 0.20694953203201294 }
1,385
code: import cv2 from filterpy.kalman import KalmanFilter import numpy as np kf = KalmanFilter(dim_x=4, dim_z=2) kf.x = np.array([0, 0, 0, 0]) # initial state estimate kf.P = np.eye(4) * 1000 # initial error covariance matrix kf.F = np.array([[1, 0, 1, 0], [0, 1, 0, 1], [0, 0, 1, 0], [0, 0, 0, 1]]) # state transition matrix kf.H = np.array([[1, 0, 0, 0], [0, 1, 0, 0]]) # measurement matrix kf.R = np.diag([0.1, 0.1]) # measurement noise covariance matrix kf.Q= np.diag([0.1, 0.1, 0.1, 0.1]) dt=1.0 cap = cv2.VideoCapture('1_1.mp4') frame_num = 0 # optical flow parameters lk_params = dict(winSize=(15,15), maxLevel=4, criteria=(cv2.TERM_CRITERIA_EPS | cv2.TERM_CRITERIA_COUNT, 10, 0.03), flags=0) prev_gray = None prev_pts = None motion_regions = [] ball_position = None ball_speed = None while True: ret, frame = cap.read() if ret is False: break frame_num += 1 # convert the frame to grayscale for optical flow calculation gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY) # compute the feature points for the first frame if prev_gray is None or prev_pts is None: prev_gray = gray prev_pts = cv2.goodFeaturesToTrack(prev_gray, maxCorners=200, qualityLevel=0.01, minDistance=10, blockSize=3) continue # apply optical flow to estimate the motion between the frames pts, status, _ = cv2.calcOpticalFlowPyrLK(prev_gray, gray, prev_pts, None, **lk_params) # extract the motion regions based on the optical flow magnitude motion_regions = [] for p, s in zip(pts, status): if s == 1: x, y = p.ravel() motion_regions.append((int(x), int(y))) motion_regions = np.array(motion_regions) if len(motion_regions) > 0: # calculate the centroid of the motion regions to determine the position of the ball ball_position = np.mean(motion_regions, axis=0).astype(np.float32) if ball_speed is not None: # predict where the ball will be in the next frame based on its position and velocity ball_position += dt * ball_speed # update the Kalman filter with the ball position measurement kf.predict() kf.update(ball_position) # get the filtered ball position as the predicted next position next_position = kf.x[:2] # update the ball speed based on the Kalman filter output ball_speed = next_position - ball_position # check if the ball is outside of the frame or changes direction, indicating a bounce if next_position[0] < 0 or next_position[0] > frame.shape[1] or next_position[1] < 0 or next_position[1] > frame.shape[0] or np.linalg.norm(ball_speed) < 1e-3: print("Bounce detected at frame ", frame_num) # visualize the bounce detection as a red circle around the ball position cv2.circle(frame, (int(ball_position[0]), int(ball_position[1])), 10, (0, 0, 255), 4) # visualize the ball position and predicted next position as blue and green circles, respectively cv2.circle(frame, (int(ball_position[0]), int(ball_position[1])), 5, (255, 0, 0), 2) cv2.circle(frame, (int(next_position[0]), int(next_position[1])), 5, (0, 255, 0), 2) # update the previous frame and feature points for the next iteration prev_gray = gray prev_pts = cv2.goodFeaturesToTrack(prev_gray, maxCorners=200, qualityLevel=0.01, minDistance=10, blockSize=3) cv2.putText(frame, f'Frame: {frame_num}', (10, 50), cv2.FONT_HERSHEY_SIMPLEX, 1, (0, 255, 0), 2) cv2.imshow('raw', frame) if cv2.waitKey(1) & 0xFF == ord('q'): break cap.release() cv2.destroyAllWindows() error: Traceback (most recent call last): File "/Users/surabhi/Documents/kalman/b2.py", line 57, in <module> motion_regions.append((int(x), int(y))) ^^^^^^^^^^^^^^^^^^^^^ AttributeError: 'numpy.ndarray' object has no attribute 'append'
dfb937b7e9029444237d0b4a33e101e1
{ "intermediate": 0.4160402715206146, "beginner": 0.316716730594635, "expert": 0.26724302768707275 }
1,386
package com.j2ee.demo; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; import java.io.*; @WebServlet("/Welcome") public class Welcome extends HttpServlet { static int count_3 = 0; void printWelcome(String username, String password, String gender, String email, String phoneNum, PrintWriter out) { out.println("<html><body>"); out.println("<h1> Welcome, " + username + "</h1>"); out.println("<h2> Here is your password, " + password + "</h2>"); out.println("<h2> You are a " + gender + "</h2>"); out.println("<h2> This is your email " + email + "</h2>"); out.println("<h2> This is your phone number " + phoneNum + "</h2>"); } @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { // String ssid = hs.getId(); // out.println(ssid); String vName = req.getParameter("username"); String vPass = req.getParameter("password"); String vGender = req.getParameter("gender"); String vEmail = req.getParameter("email"); String vPhoneNumber = req.getParameter("phone"); String rememberMe = req.getParameter("rememberMe"); PrintWriter out = resp.getWriter(); // HttpSession hs = req.getSession(); // Object isLoggedIn = hs.getAttribute("isLoggedIn"); // out.println(isLoggedIn); resp.setContentType("text/html"); printWelcome(vName, vPass, vGender, vEmail, vPhoneNumber, out); out.println("</body></html>"); System.out.println("rememberMe: " + rememberMe); Object cookieExists = req.getSession().getAttribute("cookiesExists"); System.out.println("cookiesexst " + cookieExists); if (vName != null && vPass != null && vGender != null && vEmail != null && vPhoneNumber != null) { cookieExists = null; } if (cookieExists == null) { Cookie usernameC = new Cookie("username", vName); usernameC.setMaxAge(60 * 60 * 24); resp.addCookie(usernameC); Cookie passwordC = new Cookie("password", vPass); passwordC.setMaxAge(60 * 60 * 24); resp.addCookie(passwordC); Cookie genderC = new Cookie("gender", vGender); passwordC.setMaxAge(60 * 60 * 24); resp.addCookie(genderC); Cookie emailC = new Cookie("email", vEmail); passwordC.setMaxAge(60 * 60 * 24); resp.addCookie(emailC); Cookie phoneNumC = new Cookie("phoneNum", vPhoneNumber); passwordC.setMaxAge(60 * 60 * 24); resp.addCookie(phoneNumC); Cookie remember = new Cookie("rememberMe", rememberMe); passwordC.setMaxAge(60 * 60 * 24); resp.addCookie(remember); req.getSession().setAttribute("cookiesExists", true); } Object username = req.getAttribute("username"); Object password = req.getAttribute("password"); Object gender = req.getAttribute("gender"); Object email = req.getAttribute("email"); Object phoneNum = req.getAttribute("phoneNum"); PrintWriter out = resp.getWriter(); resp.setContentType("text/html"); if (cookieExists != null) { String usernameStr = username != null ? username.toString() : ""; String passwordStr = password != null ? password.toString() : ""; String genderStr = gender != null ? gender.toString() : ""; String emailStr = email != null ? email.toString() : ""; String phoneNumStr = phoneNum != null ? phoneNum.toString() : ""; printWelcome(usernameStr.toString(), passwordStr.toString(), genderStr.toString(), emailStr.toString(), phoneNumStr.toString(), out); } else { printWelcome(vName, vPass, vGender, vEmail, vPhoneNumber, out); } out.println("</body></html>"); String requestURI = req.getRequestURI(); if (requestURI.endsWith("/s03")) { count_3++; } System.out.println(count_3); } @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { System.out.println("Go to doGet"); doGet(req, resp); } } whats wrong in this code? I want to make it so that when the user register it will save the data in cookies and when the user logins with the same username and password it will display the data of the user.
3e4cafd0a83769e994907dc2ecf09397
{ "intermediate": 0.21048055589199066, "beginner": 0.5781122446060181, "expert": 0.2114071547985077 }
1,387
write a blender python demo which can control a mixamo skeleton to keep jumping from 0 frame to 250 frame.
e02a3243d2b57830d85a53ae158261bf
{ "intermediate": 0.37088271975517273, "beginner": 0.17486175894737244, "expert": 0.4542555510997772 }
1,388
execute async task in flutter
0e1872d0e8aaab444d9345cf36e62ead
{ "intermediate": 0.3990214467048645, "beginner": 0.2211943119764328, "expert": 0.3797841966152191 }
1,389
Provider com.fasterxml.aalto.stax.EventFactoryImpl not found when use android:sharedUserId
5f735163ed49c5277d1da5722810933f
{ "intermediate": 0.4411424994468689, "beginner": 0.2702869772911072, "expert": 0.2885705828666687 }
1,390
code: import cv2 from filterpy.kalman import KalmanFilter from ultralytics import YOLO import numpy as np model = YOLO('/Users/surabhi/Documents/kalman/best.pt') kf = KalmanFilter(dim_x=4, dim_z=2) kf.x = np.array([0, 0, 0, 0]) # initial state estimate kf.P = np.eye(4) * 1000 # initial error covariance matrix kf.F = np.array([[1, 0, 1, 0], [0, 1, 0, 1], [0, 0, 1, 0], [0, 0, 0, 1]]) # state transition matrix kf.H = np.array([[1, 0, 0, 0], [0, 1, 0, 0]]) # measurement matrix kf.R = np.diag([0.1, 0.1]) # measurement noise covariance matrix kf.Q= np.diag([0.1, 0.1, 0.1, 0.1]) dt = 1.0 u = np.zeros((4, 1)) cap = cv2.VideoCapture("1_1.mp4") frame_num = 0 while True: ret, frame = cap.read() if ret is False: break bbox = model(frame,show=True) frame_num += 1 for boxes_1 in bbox : result=boxes_1.boxes.xyxy print(result) if len(result)==0: print("not detected") else: cx = int((result[0][0]+ result[0][2]) /2) print(cx) cy = int((result[0][1] + result[0][3]) /2) print(cy) centroid = np.array([cx,cy]) kf.predict() kf.update(centroid) next_point = (kf.x).tolist() print("next_point",next_point) print("frame_number",frame_num) #updated=kalman.update(cx,cy) #print(updated) #cv2.rectangle(frame, (x, y), (x2, y2), (255, 0, 0), 4) cv2.putText(frame, f'Frame: {frame_num}', (10, 50), cv2.FONT_HERSHEY_SIMPLEX, 1, (0, 255, 0), 2) cv2.circle(frame, (cx,cy),5, (0, 0, 255), 10) cv2.circle(frame, (int(next_point[0]),int(next_point[1])), 5, (255, 0, 0), 10) cv2.imshow('raw', frame) """ if predicted[0] =='None' : predicted[1]=predicted[0] print("prediction not found") elif predicted[1]=='None': predicted[1]=predicted[0] print("prediction not found") else: cv2.circle(frame, (predicted[0], predicted[1]), 5, (255, 0, 0), 2) cv2.imshow('raw', frame) """ how to detect bounce of ball
27382ed8463dc7fd12332559925a0a77
{ "intermediate": 0.3139688968658447, "beginner": 0.4467272460460663, "expert": 0.2393037974834442 }
1,391
I want to use JDA to send message to midjourney on discord, tell me the step
3820aeacab33472fbeec930e85568b3d
{ "intermediate": 0.5295832753181458, "beginner": 0.12500789761543274, "expert": 0.3454087972640991 }
1,392
Provider com.fasterxml.aalto.stax.EventFactoryImpl not found when use android:sharedUserId
f8744ccff1c51162fa6376e8cbc8aa7c
{ "intermediate": 0.4411424994468689, "beginner": 0.2702869772911072, "expert": 0.2885705828666687 }
1,393
kotlin string to mix chars in string
fd201dff37fabe462acee349e5205684
{ "intermediate": 0.44963353872299194, "beginner": 0.2384355515241623, "expert": 0.3119308650493622 }
1,394
I'm working on a Fivem NUI It will have a black outer box centered in the very middle of the screen with around 75% opacity then inside will be two divs vertically aligned the first div will contain two buttons one will say team A and the other one will say team B. In the second div will be 3 images which act as buttons. in the top left of the black outer box will be an exit button can you write the html, css, javascript and lua that updates depending on the button selection
b733f0e49d4ba3677fb70d48fbaffb89
{ "intermediate": 0.36845600605010986, "beginner": 0.23683860898017883, "expert": 0.3947054147720337 }
1,395
flutter Image.asset color not work in web view app
f1f4a23c2fac12e3af13af296ac556ab
{ "intermediate": 0.5124070644378662, "beginner": 0.2668772339820862, "expert": 0.2207157462835312 }
1,396
et errorsResult = []; const checkErrors = ({ errors, sum }) => { errorsResult = getErrorsFromBasket(errors, errorsResult); const isPayed = !sum.to_pay; if (isPayed) { throw 'change_paid_order_is_forbidden'; } } как упростить код?
cdde392739f246f6bec6da7693cceffe
{ "intermediate": 0.35198360681533813, "beginner": 0.39697951078414917, "expert": 0.2510368525981903 }
1,397
I want to create a 1D CNN with 5-fold cross validation evaluation. my data is 2 columns in csv file. the first is a 20 and 21 characters of letters, numbers and signs and the second column is a decimal number. the first column is input and my model should predict the second column as output for each rows. finally evaluate the model with mean squared error and standard deviation. what is your suggestion of python code?
110eaa98ba5736971421ce056aeefe2e
{ "intermediate": 0.12478378415107727, "beginner": 0.05577721446752548, "expert": 0.8194389939308167 }
1,398
In Java, what are the options for circuitbreaking when communicating with databases
7f71d0b18f07f3ef7ab2b80e46836101
{ "intermediate": 0.5981058478355408, "beginner": 0.15848174691200256, "expert": 0.24341239035129547 }
1,399
use to string can you base on this: 从username收到了moneyamount, to write a code using to string, to listen to this message, when there is this message, the bot chat: thank you username give me moneyamount
cab89cd2e5dd9031f395a6ab72dad86c
{ "intermediate": 0.39804312586784363, "beginner": 0.14896170794963837, "expert": 0.4529951512813568 }
1,400
how to generate txt file inside the project using Java J2EE
013fc25cb39cc81bfdfe6b8f293a346c
{ "intermediate": 0.4847154915332794, "beginner": 0.11898794770240784, "expert": 0.39629653096199036 }
1,401
<div class="list-real"> <ul data-wza="list" data-wza-text="当前栏目" role="region" aria-label="文章列表"> <!-- <li><span class="time">2019-04-25 </span><a href="/plus/view.php?aid=124">我市举办退役军人安泰集团专场招聘会</a></li> --> <div id="419706"><script type="text/xml"><datastore> <nextgroup><![CDATA[<a href="/module/web/jpage/dataproxy.jsp?page=1&webid=387&path=http://va.rizhao.gov.cn/&columnid=81263&unitid=419706&webname=%25E6%2597%25A5%25E7%2585%25A7%25E5%25B8%2582%25E9%2580%2580%25E5%25BD%25B9%25E5%2586%259B%25E4%25BA%25BA%25E4%25BA%258B%25E5%258A%25A1%25E5%25B1%2580&permissiontype=0"></a>]]></nextgroup> <recordset> <record><![CDATA[ <li><span class="time" tabindex="-1">2023-04-17</span><a href="http://va.rizhao.gov.cn/art/2023/4/17/art_81263_10270777.html"target="_blank">全市退役军人专项公益性岗位管理暨退役军人权益维护培训会召开</a></li> ]]></record> 帮我获取li标签
72b1e45bfb69c23313a0d8eebf67c8a4
{ "intermediate": 0.3152884542942047, "beginner": 0.34080395102500916, "expert": 0.34390759468078613 }
1,402
i'm working on a fivem script. I've got a tennis court how can i detect what side of the court the ball is on
85e77004619243c57ffff08ad0816ba9
{ "intermediate": 0.38651180267333984, "beginner": 0.34100645780563354, "expert": 0.272481769323349 }
1,403
please find below an assingment about website development. I only want from you the HTML for the six pages.please perfect the HTML to match all requirements needed in the assingment , remember it might say in the requirments to write CSS just ignore that for now simply output HTML assingment: Introduction You have been asked to help develop a new website for a new camping equipment retailer that is moving to online sales (RCC – Retail Camping Company). The company has been trading from premises but now wants an online presence. The website currently doesn’t take payments and orders online although the management hopes to do this in the future. The website should be visual and should be viewable on different devices. Scenario The Retail Camping Company has the following basic requirements for the contents of the website: • Home Page: o This page will introduce visitors to the special offers that are available and it should include relevant images of camping equipment such as tents, cookers and camping gear such as furniture and cookware. o The text should be minimal, visuals should be used to break up the written content. o This page should include a navigation bar (with links inside the bar and hover over tabs), slide show, header, sections, footer. o Modal pop-up window that is displayed on top of the current page. • Camping Equipment: This page will provide a catalogue of products that are on sale such as tents, camping equipment and cookware. • Furniture: This page should give customers a catalogue of camping furniture that is on sale. • Reviews: This page should include a forum where the registered members can review the products they have purchased. • Basket: This page should allow the customers to add camping equipment to their basket which is saved and checked out later. • Offers and Packages: This page provides a catalogue of the most popular equipment that is sold • Ensure you embed at least THREE (3) different plug ins such as java applets, display maps and scan for viruses. At the initial stage of the development process, you are required to make an HTML/CSS prototype of the website that will clearly show the retail camping company how the final website could work. Content hasn’t been provided. Familiarise yourself with possible types of content by choosing an appropriate organisation (by using web resources) to help you understand the context in which the company operates. However, do not limit yourself to web-based sources of information. You should also use academic, industry and other sources. Suitable content for your prototype can be found on the web e.g. images. Use creative commons (http://search.creativecommons.org/) or Wikimedia Commons (http://commons.wikimedia.org/wiki/Main_Page) as a starting point to find content. Remember the content you include in your site must be licensed for re-use. Do not spend excessive amounts of time researching and gathering content. The purpose is to provide a clear indication of how the final website could look and function. The client would provide the actual content at a later point if they are happy with the website you have proposed. Students must not use templates that they have not designed or created in the website assessment. This includes website building applications, free HTML5 website templates, or any software that is available to help with the assessment. You must create your own HTML pages including CSS files and ideally you will do this through using notepad or similar text editor. Aim The aim is to create a website for the Retail Camping Company (RCC). Task 1– 25 Marks HTML The website must be developed using HTML 5 and feature a minimum of SIX (6) interlinked pages which can also be viewed on a mobile device. The website must feature the content described above and meet the following criteria: • Researched relevant content to inform the design of the website. • Be usable in at least TWO (2) different web browsers including being optimised for mobile devices and responsive design. You should consult your tutor for guidance on the specific browsers and versions you should use. • Include relevant images of camping equipment you have selected from your research including use of headers, sections and footers. • Home Page: o Minimal text with visuals to break up the written content. o Navigation bar (with links inside the bar and hover over tabs) o Responsive design and at least one plugin o Header o Sections o Footer (including social media links) • Reviews page: with responsive contact section including first name, last name, and submit button (through email) • Camping Equipment, Furniture Page and Offers and Package page with responsive resize design and including TWO (2) different plug ins, catalogue style and animated text search for products. • Basket – Page created which allows the customers to add products to their basket.
040132c3dde01c549c67c0d808e05217
{ "intermediate": 0.2788763642311096, "beginner": 0.4383564889431, "expert": 0.28276708722114563 }
1,404
I have a dataframe with a string column. I want to create boolean (or one-hot) columns starting from the string column in pandas, how can I do that quickly and with high performance?
c15cba91a520fdc55d7ecea07be05cf2
{ "intermediate": 0.6971060633659363, "beginner": 0.06669578701257706, "expert": 0.23619818687438965 }
1,405
<div id=“419706”> <script type=“text/xml”><datastore> <nextgroup><![CDATA[<a href=“/module/web/jpage/dataproxy.jsp?page=1&webid=387&path=http://va.rizhao.gov.cn/&columnid=81263&unitid=419706&webname=%25E6%2597%25A5%25E7%2585%25A7%25E5%25B8%2582%25E9%2580%2580%25E5%25BD%25B9%25E5%2586%259B%25E4%25BA%25BA%25E4%25BA%258B%25E5%258A%25A1%25E5%25B1%2580&permissiontype=0”></a>]]></nextgroup> <recordset> <record><![CDATA[ <li><span class=“time” tabindex=“-1”>2023-04-17</span><a href=“http://va.rizhao.gov.cn/art/2023/4/17/art_81263_10270777.html"target="_blank”>全市退役军人专项公益性岗位管理暨退役军人权益维护培训会召开</a></li> ]]></record> <record><![CDATA[ <li><span class=“time” tabindex=“-1”>2023-04-11</span><a href=“http://va.rizhao.gov.cn/art/2023/4/11/art_81263_10270756.html"target="_blank”>我市启动纪念延安双拥运动80周年暨双拥法规宣传活动</a></li> ]]></record> <record><![CDATA[ <li><span class=“time” tabindex=“-1”>2023-04-04</span><a href=“http://va.rizhao.gov.cn/art/2023/4/4/art_81263_10270757.html"target="_blank”>市退役军人事务局开展清明祭英烈活动</a></li> ]]></record> <record><![CDATA[ <li><span class=“time” tabindex=“-1”>2023-03-27</span><a href=“http://va.rizhao.gov.cn/art/2023/3/27/art_81263_10270637.html"target="_blank”>市退役军人事务局机关党支部召开2022年度组织生活会</a></li> ]]></record>要求使用JAVA 获取li标签
51499d07e70a2dd3e8e36fd5b0106ac2
{ "intermediate": 0.3094247281551361, "beginner": 0.3483210504055023, "expert": 0.3422542214393616 }