text
stringlengths
184
4.48M
#ifndef DEVICE_HPP #define DEVICE_HPP #include "request.h" #include <random> #include <memory> namespace QueueingSystem { inline constexpr double IDLE_TIME{ -1.0 }; inline constexpr double MIN_PROCESSING_TIME{ 5.0 }; class Device { public: Device(int deviceId, double lambda = 0.05); int getProcessingRequestSourceId() const; const double* getProcessingEndTimePtr() const; double getProcessingTime() const; void setLambda(double lambda); double getLambda() const; void processRequest(URequest& request, double processingStartTime); void endProcessingRequest(); void reset(); private: int deviceId_; URequest processingRequest_{}; double processingTime_{ IDLE_TIME }; double processingEndTime_{ IDLE_TIME }; std::mt19937 generator_{ std::random_device{}() }; std::exponential_distribution<double> distribution_; }; using UDevice = std::unique_ptr<Device>; } #endif
import React, { useEffect } from 'react' import SBtn from './SBtn' import { FontAwesomeIcon } from '@fortawesome/react-fontawesome' import { faPlus } from '@fortawesome/free-solid-svg-icons' import { selectUser } from '../features/userSlice' import { setServer } from '../features/serverSlice' import { useSelector, useDispatch } from 'react-redux' import url from "../url.json" export default function ServerList(props) { const dispatch = useDispatch(); let [server, setServerL] = React.useState([]); var socket = props.socket; const user = useSelector(selectUser) function setCurrentServer(s) { if (s !== undefined) { dispatch(setServer({ serverName: s.serverName, serverId: s._id, serverProfile: s.ServerProfile })) } } useEffect(() => { socket.emit("authenticate", user.id) }, []) function GetServerList() { fetch(`${url.server}api/get/server`, { method: "POST", credentials: 'include', withCredentials: true, headers: { 'Access-Control-Allow-Origin': url.frontend, 'Access-Control-Allow-Credentials': 'true', 'Content-Type': 'application/json' }, body: JSON.stringify({ id: user.id }) }).then(response => response.json()).then(res => { if (res.error === 'null') { setServerL(res.servers) } setCurrentServer(res.servers[res.servers.length - 1]) }) } React.useEffect(() => { socket.on("member-joined", (id, u) => { console.log("yo") if (user.id === u) { GetServerList() } }) }) useEffect(() => { server.map((s) => { socket.emit("server-connected", s._id); }) // console.log(props) }, [server]) function createServer() { let name = prompt('server name') fetch(`${url.server}api/register/server`, { method: "POST", credentials: 'include', withCredentials: true, headers: { 'Access-Control-Allow-Origin': url.frontend, 'Access-Control-Allow-Credentials': 'true', 'Content-Type': 'application/json' }, body: JSON.stringify({ name: name, admin: user.id }) }).then(response => response.json()).then(res => { if (res.status === 'done') { GetServerList() } }) } useEffect(() => { GetServerList() }, []) return ( <> <div className='server-list w-5/2'> <div onClick={createServer} className='createNewServer'> <div className='createCircle-btn' data-name="Create new server"> <FontAwesomeIcon icon={faPlus} color="white" /> </div> </div> <div className='serverList_flexBox'> <label>Chats</label> <div className='serverList_flex'> {server && server.map(servers => ( <SBtn key={servers._id} uid={servers._id} profile={servers.ServerProfile} name={servers.serverName}></SBtn> ))} </div> </div> </div> </> ) }
import math import matplotlib.pyplot as plt import numpy as np def plot_damage_change(): speed_values = range(180, 126, -1) # 从180降低到126 damage_values = [] max_damage = 0 max_damage_speed = 0 max_damage_attack = 0 for speed in speed_values: attack = 3286+0.2*1266 + (180 - speed) * 21 kafka = Kafka_serval(attack, speed, 65, 0.6, 1.3, 1.13, 2) total_damage = kafka.calculate_total_damage(550) damage_values.append(total_damage) if total_damage > max_damage: max_damage = total_damage max_damage_speed = speed max_damage_attack = attack plt.plot(speed_values, damage_values) plt.xlabel('Speed') plt.ylabel('Total Damage') plt.title('Change in Total Damage as Speed Decreases') plt.grid(True) print(f"Maximum damage of {max_damage} is achieved with a speed of {max_damage_speed-12} and an attack of {max_damage_attack-0.2*1266}.") plt.show() class Kafka_serval: def __init__(self, attack, speed, damage_increase, def_debuff, damage_debuff, res_debuff, times):#攻击, 速度, 增伤, 降防, 易伤, 减抗, 几动一大 self.attack = attack self.speed = speed self.damage_increase = damage_increase self.def_debuff = def_debuff self.damage_debuff = damage_debuff self.res_debuff = res_debuff self.times = times def action_cost(self):#速度转行动值 return 10000 / self.speed def basic_attack_damage(self):#160%战技直伤+140%追击直伤 return self.attack * 3 * (1 + self.damage_increase / 100) def big_attack_damage(self):#大招80倍率脑残直伤,最弱大招没有之一 return self.attack * 0.80 * (1 + self.damage_increase / 100) def buff_damage(self):#290常驻dot+60专武dot+希露瓦100倍率dot,2命卡的25增伤 return self.attack * 5.5 * (1 + (self.damage_increase+25) / 100) def break_buff_damage(self):#击破dot return 3767.55 * 2.8 * 2 def explode_damage(self):#e技能引爆dot return self.buff_damage() * 0.75 def explode_damage_big_attack(self):#大招引爆dot return self.buff_damage() def break_explode_damage(self):#e技能引爆击破dot return self.break_buff_damage() * 0.75 def break_explode_damage_big_attack(self):#大招引爆击破dot return self.break_buff_damage() def calculate_total_damage(self, action_value): action_times = math.floor(action_value / self.action_cost())#行动次数 enemy_action_times = math.floor(action_value / (10000 / 140))#混沌10 140速怪行动次数 basic_attack_times = action_times#引爆次数 big_attack_times = action_times // self.times #4命卡夫卡 2动一大 total_damage = 0 total_damage += self.basic_attack_damage() * basic_attack_times total_damage += self.big_attack_damage() * big_attack_times total_damage = total_damage*self.damage_debuff#易伤率 total_buff_damage = 0 total_buff_damage += self.buff_damage() * enemy_action_times total_buff_damage += self.explode_damage() * action_times total_buff_damage += self.explode_damage_big_attack() * big_attack_times total_buff_damage += self.break_buff_damage()*(enemy_action_times-2) total_buff_damage += self.break_explode_damage()*(action_times-2) total_buff_damage += self.break_explode_damage_big_attack()*(big_attack_times-1) total_damage += total_buff_damage*1.3 total_damage = total_damage*(200+10*80)/((200+10*90)*self.def_debuff+200+10*80)#减防公式:(200+10*攻击者等级)/((200+10*受击者等级)*(1-减防系数)+200+10*攻击者等级) total_damage = total_damage*self.res_debuff#抗性衰减 return total_damage class Kafka_serval1: def __init__(self, attack, speed, damage_increase, def_debuff, damage_debuff, res_debuff, times):#攻击, 速度, 增伤, 降防, 易伤, 减抗, 几动一大 self.attack = attack self.speed = speed self.damage_increase = damage_increase self.def_debuff = def_debuff self.damage_debuff = damage_debuff self.res_debuff = res_debuff self.times = times def action_cost(self):#速度转行动值 return 10000 / self.speed def basic_attack_damage(self):#160%战技直伤+140%追击直伤 return self.attack * 3 * (1 + self.damage_increase / 100) def big_attack_damage(self):#大招80倍率脑残直伤,最弱大招没有之一 return self.attack * 0.80 * (1 + self.damage_increase / 100) def buff_damage(self):#290常驻dot+60专武dot+希露瓦100倍率dot,2命卡的25增伤 return self.attack * 5.5 * (1 + (self.damage_increase+25) / 100) def break_buff_damage(self):#击破dot return 3767.55 * 2.8 * 2 def explode_damage(self):#e技能引爆dot return self.buff_damage() * 0.75 def explode_damage_big_attack(self):#大招引爆dot return self.buff_damage() def break_explode_damage(self):#e技能引爆击破dot return self.break_buff_damage() * 0.75 def break_explode_damage_big_attack(self):#大招引爆击破dot return self.break_buff_damage() def calculate_total_damage(self, action_value): action_times = math.floor(action_value / self.action_cost())#行动次数 enemy_action_times = math.floor(action_value / (10000 / 140))#混沌10 140速怪行动次数 basic_attack_times = action_times#引爆次数 big_attack_times = action_times // self.times #4命卡夫卡 2动一大 total_damage = 0 total_damage += self.basic_attack_damage() * basic_attack_times total_damage += self.big_attack_damage() * big_attack_times total_damage = total_damage*self.damage_debuff#易伤率 total_buff_damage = 0 total_buff_damage += self.buff_damage() * enemy_action_times total_buff_damage += self.explode_damage() * action_times total_buff_damage += self.explode_damage_big_attack() * big_attack_times total_buff_damage += self.break_buff_damage()*(enemy_action_times-2) total_buff_damage += self.break_explode_damage()*(action_times-2) total_buff_damage += self.break_explode_damage_big_attack()*(big_attack_times-1) total_damage += total_buff_damage*1.3 total_damage = total_damage*(200+10*80)/((200+10*90)*self.def_debuff+200+10*80)#减防公式:(200+10*攻击者等级)/((200+10*受击者等级)*(1-减防系数)+200+10*攻击者等级) total_damage = total_damage*self.res_debuff#抗性衰减 return total_damage class Kafka_d: def __init__(self, attack, speed, damage_increase, def_debuff, damage_debuff, res_debuff, times):#卡夫卡配桑博,没有减防减抗,持续伤害易伤从1.3提到1.6,依然没有通用易伤 self.attack = attack self.speed = speed self.damage_increase = damage_increase self.def_debuff = def_debuff self.damage_debuff = damage_debuff self.res_debuff = res_debuff self.times = times def action_cost(self): return 10000 / self.speed def basic_attack_damage(self): return self.attack * 3.00 * (1 + self.damage_increase / 100) def big_attack_damage(self): return self.attack * 0.80 * (1 + self.damage_increase / 100) def buff_damage(self): return self.attack * 5.5 * (1 + (self.damage_increase+25)/ 100)+ 3000*3.5*(1 + (40+25)/ 100)#桑博面板350的风伤,保守估计250常驻加上卡夫卡4+1的350触电 def explode_damage(self): return self.buff_damage() * 0.75 def explode_damage_big_attack(self): return self.buff_damage() def calculate_total_damage(self, action_value): action_times = math.floor(action_value / self.action_cost()) enemy_action_times = math.floor(action_value / (10000 / 140)) basic_attack_times = action_times big_attack_times = action_times // self.times total_damage = 0 total_damage += self.basic_attack_damage() * basic_attack_times total_damage += self.big_attack_damage() * big_attack_times total_damage = total_damage*self.damage_debuff total_buff_damage = 0 total_buff_damage += self.buff_damage() * enemy_action_times total_buff_damage += self.explode_damage() * action_times total_buff_damage += self.explode_damage_big_attack() * big_attack_times total_damage += total_buff_damage*1.6 total_damage = total_damage*(200+10*80)/((200+10*90)*self.def_debuff+200+10*80) total_damage = total_damage*self.res_debuff return total_damage class Kafka_asta_sw: def __init__(self, attack, speed, damage_increase, def_debuff, damage_debuff, res_debuff, times):#攻击, 速度, 增伤, 降防, 易伤, 减抗, 循环 self.attack = attack self.speed = speed self.damage_increase = damage_increase self.def_debuff = def_debuff self.damage_debuff = damage_debuff self.res_debuff = res_debuff self.times = times def action_cost(self):#速度转行动值 return 10000 / self.speed def basic_attack_damage(self):#160%战技直伤+140%追击直伤 return self.attack * 3 * (1 + self.damage_increase / 100) def big_attack_damage(self):#大招80倍率脑残直伤 return self.attack * 0.80 * (1 + self.damage_increase / 100) def buff_damage(self):#290常驻dot+60专武dot return self.attack * 3.5 * (1 + (self.damage_increase+25) / 100) def explode_damage(self):#e技能引爆dot return self.buff_damage() * 0.75 def explode_damage_big_attack(self):#大招引爆dot return self.buff_damage() def calculate_total_damage(self, action_value): action_times = math.floor(action_value / self.action_cost())#行动次数 enemy_action_times = math.floor(action_value / (10000 / 140))#混沌10 140速怪行动次数 basic_attack_times = action_times#引爆次数 big_attack_times = action_times // self.times #4命卡夫卡 2动一大 total_damage = 0 total_damage += self.basic_attack_damage() * basic_attack_times total_damage += self.big_attack_damage() * big_attack_times total_damage = total_damage*self.damage_debuff#通常易伤率 total_buff_damage = 0 total_buff_damage += self.buff_damage() * (enemy_action_times-0.5) total_buff_damage += self.explode_damage() * (action_times-0.5) total_buff_damage += self.explode_damage_big_attack() * (big_attack_times-0.2) total_damage += total_buff_damage*1.3#卡夫卡1命30易伤 total_damage = total_damage*(200+10*80)/((200+10*90)*self.def_debuff+200+10*80)#减防公式:(200+10*攻击者等级)/((200+10*受击者等级)*(1-减防系数)+200+10*攻击者等级) total_damage = total_damage*self.res_debuff#抗性衰减 return total_damage def main(): kafka = Kafka_serval(4000, 140, 72.8, 0.6, 1.0, 1.13, 2)#速度鞋,能量链 kafka10 = Kafka_serval(4600, 140, 72.8, 0.6, 1.0, 1.13, 3) kafka2 = Kafka_serval(4200, 200, 65, 1, 1.0, 1, 2) kafka0 = Kafka_asta_sw(4200, 200, 65, 0.6, 1.0, 1.13, 2) kafka3 = Kafka_d(4000, 140, 72.8, 0.6, 1.0, 1, 2) kafka4 = Kafka_d(4200, 200, 65, 1, 1.0, 0.9, 2) total_damage = kafka.calculate_total_damage(450) total_damage7 = kafka10.calculate_total_damage(450) total_damage3 = kafka2.calculate_total_damage(450) total_damage2 = kafka0.calculate_total_damage(450) total_damage4 = kafka3.calculate_total_damage(450) total_damage5 = kafka4.calculate_total_damage(450) print(f"卡夫卡希露瓦银狼\t450行动值总伤: {total_damage}") print(f"2命卡夫卡希露瓦银狼\t450行动值总伤: {total_damage7}") print(f"卡夫卡希露瓦艾斯妲\t450行动值总伤: {total_damage3}") print(f"卡夫卡艾斯妲银狼\t450行动值总伤: {total_damage2}") print(f"卡夫卡桑博银狼\t\t450行动值总伤: {total_damage4}") print(f"卡夫卡桑博艾斯妲\t450行动值总伤: {total_damage5}") action_values = np.arange(150, 851, 100) # 250到650的行动值,步长为100 # 对于每个行动值,计算相应的伤害值 damages_kafka = [(kafka.calculate_total_damage(av))/((av-50)/100) for av in action_values] damages_kafka7 = [(kafka10.calculate_total_damage(av))/((av-50)/100) for av in action_values] damages_kafka2 = [(kafka2.calculate_total_damage(av))/((av-50)/100) for av in action_values] damages_kafka0 = [(kafka0.calculate_total_damage(av))/((av-50)/100) for av in action_values] damages_kafka3 = [(kafka3.calculate_total_damage(av))/((av-50)/100) for av in action_values] damages_kafka4 = [(kafka4.calculate_total_damage(av))/((av-50)/100) for av in action_values] # 使用matplotlib进行绘图 plt.figure(figsize=(10, 6)) plt.plot(action_values, damages_kafka, label="sw&serval") plt.plot(action_values, damages_kafka7, label="2sw&serval") """plt.plot(action_values, damages_kafka2, label="asta&serval") plt.plot(action_values, damages_kafka0, label="asta&sw")""" plt.plot(action_values, damages_kafka3, label="sw&sambo") """ plt.plot(action_values, damages_kafka4, label="asta&sambo")""" plt.xlabel('Action value') plt.ylabel('Damage') plt.title('Change in damage per round as Action value changes') plt.legend() plt.show() if __name__ == "__main__": main() #plot_damage_change()
#include <iostream> using namespace std; class Stack { private: queue<int> q; public: void push(int element) { q.push(element); } int pop() { if (q.empty()) { cout << "Stack is empty" << endl; return -1; } int element = q.front(); q.pop(); if (q.size() == 0) { q.push(element); } return element; } bool empty() { return q.empty(); } }; int main() { Stack stack; stack.push(1); stack.push(2); stack.push(3); cout << stack.pop() << endl; cout << stack.pop() << endl; cout << stack.pop() << endl; return 0; }
import { Request, Response } from 'express'; import * as mockExpressRequest from 'mock-express-request'; import * as mockExpressResponse from 'mock-express-response'; import * as sinon from 'sinon'; import { titleController } from './Title.Controller'; import { titleService } from './Title.Service'; describe('TitleController', () => { let request: Request; let response: Response; let responseMock; let titleServiceMock; let variantsInfo; let variantsInfoForISBN10; let variantsInfoInvalid; let variantsInfoForValidInvalid; beforeEach(() => { request = new mockExpressRequest(); response = new mockExpressResponse(); responseMock = sinon.mock(response); titleServiceMock = sinon.mock(titleService); variantsInfo = [ { identifier: { name: 'isbn', value: '9781317623144' }, variants: [ { _id: 'aa3bc35d-4ff0-4ccc-bd83-57ba91a03e56', book: { edition: '2', formats: ['e-Book'], publisherImprint: 'Routledge', status: 'Available' }, identifiers: { dacKey: 'C2013-0-21702-X', doi: '10.4324/9781315754116', isbn: '9781315754116', isbn10: '1315754118' }, title: 'Food Wars', type: 'book', version: null } ] } ]; variantsInfoInvalid = [ { identifier: { name: 'isbn10', value: 'invalid' }, variants: [] } ]; variantsInfoForISBN10 = [...variantsInfo]; variantsInfoForISBN10[0].identifier = { name: 'isbn10', value: '1315754118' }; variantsInfoForValidInvalid = [ ...variantsInfoForISBN10, ...variantsInfoInvalid ]; }); afterEach(() => { responseMock.restore(); titleServiceMock.restore(); }); describe('getProductVariantsByIds', () => { it('should respond with 500 error when the service throws unexpected error', (done) => { request.body = { action: 'fetchVariants', apiVersion: '4.0.1', formats: ['e-Book'], identifiers: [ { name: 'isbn', values: ['9781317623144', '9781317740728'] } ], includeEditions: true }; titleServiceMock .expects('getProductVariantsByIds') .once() .withArgs( request.body.identifiers[0].name, request.body.identifiers[0].values, { formats: request.body.formats, includeEditions: request.body.includeEditions } ) .rejects(new Error('Unexpected error occured')); responseMock.expects('status').once().withArgs(500); responseMock .expects('json') .once() .withArgs({ data: null, metadata: { error: undefined, message: 'Unexpected error occured', transactionId: undefined } }); titleController .getProductVariantsByIds(request, response) .then(() => { responseMock.verify(); titleServiceMock.verify(); done(); }) .catch(done); }); it('should respond with 500 error when the service throws unexpected error', (done) => { request.body = { action: 'fetchVariants', apiVersion: '4.0.1', formats: ['e-Book'], identifiers: [{ name: 'isbn10', values: ['9781317623', '9781317740'] }], includeEditions: true }; titleServiceMock .expects('getProductVariantsByIds') .once() .withArgs( request.body.identifiers[0].name, request.body.identifiers[0].values, { formats: request.body.formats, includeEditions: request.body.includeEditions } ) .rejects(new Error('Unexpected error occured')); responseMock.expects('status').once().withArgs(500); responseMock .expects('json') .once() .withArgs({ data: null, metadata: { error: undefined, message: 'Unexpected error occured', transactionId: undefined } }); titleController .getProductVariantsByIds(request, response) .then(() => { responseMock.verify(); titleServiceMock.verify(); done(); }) .catch(done); }); it('should respond with 404 error when variants not found', (done) => { request.body = { action: 'fetchVariants', apiVersion: '4.0.1', formats: ['e-Book'], identifiers: [ { name: 'isbn', values: ['9781317623144', '9781317740728'] } ], includeEditions: true }; titleServiceMock .expects('getProductVariantsByIds') .once() .withArgs( request.body.identifiers[0].name, request.body.identifiers[0].values, { formats: request.body.formats, includeEditions: request.body.includeEditions } ) .resolves([]); responseMock.expects('status').once().withArgs(404); responseMock .expects('json') .once() .withArgs({ data: null, metadata: { error: undefined, message: 'Product variants not found.', transactionId: undefined } }); titleController .getProductVariantsByIds(request, response) .then(() => { responseMock.verify(); titleServiceMock.verify(); done(); }) .catch(done); }); it('should respond with 404 error when variants not found', (done) => { request.body = { action: 'fetchVariants', apiVersion: '4.0.1', formats: ['e-Book'], identifiers: [{ name: 'isbn10', values: ['1317623144'] }], includeEditions: true }; titleServiceMock .expects('getProductVariantsByIds') .once() .withArgs( request.body.identifiers[0].name, request.body.identifiers[0].values, { formats: request.body.formats, includeEditions: request.body.includeEditions } ) .resolves([]); responseMock.expects('status').once().withArgs(404); responseMock .expects('json') .once() .withArgs({ data: null, metadata: { error: undefined, message: 'Product variants not found.', transactionId: undefined } }); titleController .getProductVariantsByIds(request, response) .then(() => { responseMock.verify(); titleServiceMock.verify(); done(); }) .catch(done); }); it('should respond with 400 error when request does not contain identifiers', (done) => { request.body = { action: 'fetchVariants', apiVersion: '4.0.1', formats: ['e-Book'], includeEditions: true }; titleServiceMock.expects('getProductVariantsByIds').never(); responseMock.expects('status').once().withArgs(400); responseMock .expects('json') .once() .withArgs({ data: null, metadata: { error: undefined, message: 'invalid/missing identifiers', transactionId: undefined } }); titleController .getProductVariantsByIds(request, response) .then(() => { responseMock.verify(); titleServiceMock.verify(); done(); }) .catch(done); }); it('should respond with product variants data when the request is valid', (done) => { request.body = { action: 'fetchVariants', apiVersion: '4.0.1', formats: ['e-Book'], identifiers: [{ name: 'isbn', values: ['9781317623144'] }], includeEditions: true }; titleServiceMock .expects('getProductVariantsByIds') .once() .withArgs( request.body.identifiers[0].name, request.body.identifiers[0].values, { formats: request.body.formats, includeEditions: request.body.includeEditions } ) .resolves(variantsInfo); responseMock.expects('status').once().withArgs(200); responseMock.expects('json').once().withArgs(variantsInfo); titleController .getProductVariantsByIds(request, response) .then(() => { responseMock.verify(); titleServiceMock.verify(); done(); }) .catch(done); }); it('should respond with product variants data when identifierName is isbn10', (done) => { request.body = { action: 'fetchVariants', apiVersion: '4.0.1', formats: ['e-Book'], identifiers: [{ name: 'isbn10', values: ['1315754118'] }], includeEditions: true }; titleServiceMock .expects('getProductVariantsByIds') .once() .withArgs( request.body.identifiers[0].name, request.body.identifiers[0].values, { formats: request.body.formats, includeEditions: request.body.includeEditions } ) .resolves(variantsInfoForISBN10); responseMock.expects('status').once().withArgs(200); responseMock.expects('json').once().withArgs(variantsInfoForISBN10); titleController .getProductVariantsByIds(request, response) .then(() => { responseMock.verify(); titleServiceMock.verify(); done(); }) .catch(done); }); }); it('should respond with product variants data when identifierName is isbn10', (done) => { request.body = { action: 'fetchVariants', apiVersion: '4.0.1', formats: ['e-Book'], identifiers: [{ name: 'isbn10', values: ['1315754118', 'invalid'] }], includeEditions: true }; titleServiceMock .expects('getProductVariantsByIds') .once() .withArgs( request.body.identifiers[0].name, request.body.identifiers[0].values, { formats: request.body.formats, includeEditions: request.body.includeEditions } ) .resolves(variantsInfoForValidInvalid); responseMock.expects('status').once().withArgs(200); responseMock.expects('json').once().withArgs(variantsInfoForValidInvalid); titleController .getProductVariantsByIds(request, response) .then(() => { responseMock.verify(); titleServiceMock.verify(); done(); }) .catch(done); }); });
import { createAsyncThunk } from '@reduxjs/toolkit/dist'; import { AsyncThunkConfigHttpError } from 'common/types/app/async-thunk-config.type'; import { serializeHttpError } from 'helpers/helpers'; import { CreateStreamRequestDto, HttpError, OwnChannelResponseDto, ResetStreamingKeyRequestDto, StreamingInfoResponseDto, StreamingKeyResponseDto, StreamLiveStatusRequestDto, StreamPosterUploadRequestDto, StreamPosterUploadResponseDto, StreamReadinessRequestDto, StreamUpdateRequestDto, VideoStreamResponseDto, } from 'shared/build'; import { ActionType } from './common'; const createStream = createAsyncThunk<VideoStreamResponseDto, CreateStreamRequestDto, AsyncThunkConfigHttpError>( ActionType.CREATE_STREAM, async (payload, { extra: { channelStreamingApi }, rejectWithValue }) => { try { const newStream = await channelStreamingApi.createStream(payload); return newStream; } catch (error) { if (error instanceof HttpError) { return rejectWithValue(serializeHttpError(error)); } throw error; } }, ); const getMyChannel = createAsyncThunk<OwnChannelResponseDto, void, AsyncThunkConfigHttpError>( ActionType.GET_MY_CHANNEL, async (_payload, { extra: { channelCrudApi }, rejectWithValue }) => { try { return await channelCrudApi.getMyChannelInfo(); } catch (error) { if (error instanceof HttpError) { return rejectWithValue(serializeHttpError(error)); } throw error; } }, ); const uploadPoster = createAsyncThunk< StreamPosterUploadResponseDto, StreamPosterUploadRequestDto, AsyncThunkConfigHttpError >(ActionType.UPLOAD_POSTER, async (payload, { extra: { channelStreamingApi }, rejectWithValue }) => { try { return await channelStreamingApi.uploadPoster(payload); } catch (error) { if (error instanceof HttpError) { return rejectWithValue(serializeHttpError(error)); } throw error; } }); const editStream = createAsyncThunk< VideoStreamResponseDto, Omit<StreamUpdateRequestDto, 'videoId'>, AsyncThunkConfigHttpError >(ActionType.UPDATE_STREAM_DATA, async (payload, { extra: { channelStreamingApi }, rejectWithValue, getState }) => { try { const videoId = getState().stream.stream?.id ?? ''; return await channelStreamingApi.editStream({ ...payload, videoId, }); } catch (error) { if (error instanceof HttpError) { return rejectWithValue(serializeHttpError(error)); } throw error; } }); const getStreamingInfo = createAsyncThunk<StreamingInfoResponseDto, void, AsyncThunkConfigHttpError>( ActionType.GET_STREAM_DATA, async (_payload, { extra: { channelStreamingApi }, rejectWithValue }) => { try { return await channelStreamingApi.getStreamingInfo(); } catch (error) { if (error instanceof HttpError) { return rejectWithValue(serializeHttpError(error)); } throw error; } }, ); const setStreamStatus = createAsyncThunk<VideoStreamResponseDto, StreamLiveStatusRequestDto, AsyncThunkConfigHttpError>( ActionType.SET_STREAMING_STATUS, async (payload, { extra: { channelStreamingApi }, rejectWithValue }) => { try { return await channelStreamingApi.setStreamStatus(payload); } catch (error) { if (error instanceof HttpError) { return rejectWithValue(serializeHttpError(error)); } throw error; } }, ); const resetTemporaryPoster = createAsyncThunk<boolean, void, AsyncThunkConfigHttpError>( ActionType.RESET_TEMPORARY_POSTER, async (_payload, { rejectWithValue }) => { try { return true; } catch (error) { if (error instanceof HttpError) { return rejectWithValue(serializeHttpError(error)); } throw error; } }, ); const setReadinessToStream = createAsyncThunk< VideoStreamResponseDto, StreamReadinessRequestDto, AsyncThunkConfigHttpError >(ActionType.SET_READINESS_TO_STREAM, async (payload, { extra: { channelStreamingApi }, rejectWithValue }) => { try { return await channelStreamingApi.setReadinessToStream(payload); } catch (error) { if (error instanceof HttpError) { return rejectWithValue(serializeHttpError(error)); } throw error; } }); const resetStreamingKey = createAsyncThunk< StreamingKeyResponseDto, ResetStreamingKeyRequestDto, AsyncThunkConfigHttpError >(ActionType.RESET_STREAMING_KEY, async (payload, { extra: { channelStreamingApi }, rejectWithValue }) => { try { return await channelStreamingApi.resetStreamingKey(payload); } catch (error) { if (error instanceof HttpError) { return rejectWithValue(serializeHttpError(error)); } throw error; } }); export { createStream, uploadPoster, editStream, getStreamingInfo, setStreamStatus, resetStreamingKey, getMyChannel, setReadinessToStream, resetTemporaryPoster, };
import * as React from 'react'; import Typography from '@mui/material/Typography'; import { makeStyles } from 'tss-react/mui'; import { Box, Grid } from '@mui/material'; import type { Theme } from '@mui/material/styles'; import HowItWorksCards from './HowItWorksCards'; import PeopleSignup from '../assets/HowItWorks/people-signup.svg'; import PeopleSharing from '../assets/HowItWorks/people-sharing.svg'; import PeopleWorking from '../assets/HowItWorks/people-working.svg'; import PeopleFlag from '../assets/HowItWorks/people-flag.svg'; const loremIpsum = 'Lorem ipsum dolor sit amet, consectetur adipiscing elit. '; const nonprofitinstructionsArray = [ { title: 'Sign up with Givingful', body: 'Create a profile to let our community know about your nonprofit.', image: PeopleSignup, buttonText: 'View More', }, { title: 'Share your nonprofit’s needs', body: 'Post a description of items and skills that can help your organization.', image: PeopleSharing, buttonText: 'Post a Need', }, { title: 'Claim an offer', body: 'Coordinate to receive goods offered by those in the community.', image: PeopleWorking, buttonText: 'See Offers', }, { title: 'Succeed in your goals', body: 'See your nonprofit thrive with your community’s help.', image: PeopleFlag, buttonText: 'Read Testimonials', }, ]; const citizeninstructionsArray = [ { title: 'Sign up with Givingful', body: 'Create a profile to let our community know about your nonprofit.', image: PeopleSignup, buttonText: 'View More', }, { title: 'Post your donation', body: loremIpsum, image: PeopleSharing, buttonText: 'View More', }, { title: 'Connect with nonprofits', body: loremIpsum, image: PeopleWorking, buttonText: 'View More', }, { title: 'Make a difference', body: loremIpsum, image: PeopleFlag, buttonText: 'View More', }, ]; const useStyles = makeStyles()((theme: Theme) => ({ columns: { display: 'flex', }, tabs: { padding: '0', }, tabsGrid: { gridTemplateColumns: 'repeat(2, 3fr)', justifyItems: 'start', }, tabMenuLink: { padding: '10px', paddingBottom: '0!important', minWidth: '200px', }, button: { fontFamily: 'Poppins', fontSize: '1.5rem', }, selected: { fontWeight: 500, borderRadius: '5px', borderBottom: `8px solid #EF6A60`, }, hidden: { display: 'none', }, })); function HowItWorks() { const { classes } = useStyles(); type Tab = 'nonprofit' | 'citizen'; const [tabSelected, setTabSelected] = React.useState<Tab>('nonprofit'); const handleClickTab = (tabName: Tab) => { setTabSelected(tabName); }; return ( <Box sx={{ margin: 'auto', width: '80%', marginY: '50px' }}> <Box className={`${classes.tabs}`}> <Grid container className={`${classes.tabsGrid}`}> <Grid container item sm={2} xs={6} onClick={() => handleClickTab('nonprofit')} className={classes.tabMenuLink} > <Box className={`${classes.button} ${tabSelected === 'nonprofit' ? classes.selected : ''}`} > For Nonprofits </Box> </Grid> <Grid container item sm={2} xs={6} onClick={() => handleClickTab('citizen')} className={classes.tabMenuLink} > <Box className={`${classes.button} ${tabSelected === 'citizen' ? classes.selected : ''}`} > For Individuals </Box> </Grid> </Grid> </Box> <Typography sx={{ fontFamily: 'Poppins', fontStyle: 'normal', fontWeight: 500, fontSize: '40px', lineHeight: '48px', textAlign: 'center', mt: '20px', mb: '40px', }} > How it Works </Typography> <HowItWorksCards instructionsArray={ tabSelected === 'nonprofit' ? nonprofitinstructionsArray : citizeninstructionsArray } /> </Box> ); } export default HowItWorks;
package ru.practicum.Services; import lombok.RequiredArgsConstructor; import org.springframework.data.domain.Page; import org.springframework.data.domain.PageRequest; import org.springframework.data.domain.Pageable; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import ru.practicum.DTO.CompilationDto; import ru.practicum.DTO.CompilationNewDto; import ru.practicum.DTO.CompilationPatchDto; import ru.practicum.model.Compilation; import ru.practicum.model.Event; import ru.practicum.model.EventCompilation; import ru.practicum.storage.CompilationRepository; import ru.practicum.storage.EventCompilationRepository; import ru.practicum.storage.EventRepository; import java.util.ArrayList; import java.util.List; import static ru.practicum.mapper.CompilationMapper.compilationToDto; import static ru.practicum.mapper.CompilationMapper.dtoToCompilation; import static ru.practicum.mapper.EventMapper.eventToShortDto; @Service @RequiredArgsConstructor @Transactional public class CompilationService { private final CompilationRepository compilationRepository; private final EventCompilationRepository eventCompilationRepository; private final EventRepository eventRepository; public CompilationDto postCompilation(CompilationNewDto compilationNewDto) { Compilation compilation = dtoToCompilation(compilationNewDto); Compilation updCompilation = compilationRepository.save(compilation); CompilationDto compilationDto = new CompilationDto(); compilationDto.setId(updCompilation.getId()); compilationDto.setPinned(updCompilation.getPinned()); compilationDto.setTitle(updCompilation.getTitle()); compilationNewDto.getEvents().forEach(eventId -> { EventCompilation eventCompilation = new EventCompilation(); eventCompilation.setCompilation(updCompilation); Event event = eventRepository.findById(eventId).get(); eventCompilation.setEvent(event); compilationDto.getEvents().add(eventToShortDto(event)); eventCompilationRepository.save(eventCompilation); }); compilationRepository.save(compilation); return compilationDto; } public void deleteCompilation(Long id) { Compilation compilation = compilationRepository.findById(id).get(); eventCompilationRepository.deleteAllByCompilation(compilation); compilationRepository.deleteById(id); } public CompilationDto patchCompilation(Long compId, CompilationPatchDto compilationNewDto) { Compilation compilation = compilationRepository.findById(compId).get(); if (compilationNewDto.getTitle() != null) { compilation.setTitle(compilationNewDto.getTitle()); } if (compilationNewDto.getPinned() != null) { compilation.setPinned(compilationNewDto.getPinned()); } Compilation updCompilation = compilationRepository.save(compilation); List<Event> eventList = eventRepository.findAllById(compilationNewDto.getEvents()); eventCompilationRepository.deleteAllByEventNotIn(eventList); CompilationDto compilationDto = new CompilationDto(); compilationNewDto.getEvents().forEach(eventId -> { EventCompilation eventCompilation = new EventCompilation(); eventCompilation.setCompilation(updCompilation); Event event = eventRepository.findById(eventId).get(); eventCompilation.setEvent(event); compilationDto.getEvents().add(eventToShortDto(event)); eventCompilationRepository.save(eventCompilation); }); compilationDto.setId(compilation.getId()); compilationDto.setTitle(compilation.getTitle()); compilationDto.setPinned(compilation.getPinned()); List<EventCompilation> eventCompilationList = eventCompilationRepository.findAllByEventIn(eventList); eventCompilationList.forEach(eventCompilation -> { compilationDto.getEvents().add(eventToShortDto(eventCompilation.getEvent())); }); return compilationDto; } public List<CompilationDto> getCompilations(Boolean pinned, Integer from, Integer size) { List<CompilationDto> compilationDtoList = new ArrayList<>(); Pageable page = PageRequest.of(from / size, size); Page<Compilation> compilationPage; if (pinned == null) { compilationPage = compilationRepository.findAll(page); } else { compilationPage = compilationRepository.findAllByPinned(pinned, page); } compilationPage.getContent().forEach(compilation -> { CompilationDto compilationDto = new CompilationDto(); compilationDto.setId(compilation.getId()); compilationDto.setPinned(compilation.getPinned()); compilationDto.setTitle(compilation.getTitle()); compilationDto.setEvents(new ArrayList<>()); List<EventCompilation> eventCompilationList = eventCompilationRepository.findAllByCompilation(compilation); eventCompilationList.forEach(eventCompilation -> { compilationDto.getEvents().add(eventToShortDto(eventCompilation.getEvent())); }); compilationDtoList.add(compilationDto); }); if (compilationDtoList.size() > from % size) { return compilationDtoList.subList(from % size, compilationDtoList.size()); } else return new ArrayList<>(); } public CompilationDto getCompilationById(Long compId) { Compilation compilation = compilationRepository.findById(compId).get(); CompilationDto compilationDto = compilationToDto(compilation); List<EventCompilation> eventCompilationList = eventCompilationRepository.findAllByCompilation(compilation); eventCompilationList.forEach(eventCompilation -> { compilationDto.getEvents().add(eventToShortDto(eventCompilation.getEvent())); }); return compilationDto; } }
<template> <div class="w-full max-w-3xl mx-auto py-8"> <div class="text-xl font-semibold">Update Blog</div> <div class="mb-6"> <label for="title" class="block mb-2 text-sm font-medium text-gray-900">Title</label> <input v-model="form.title" type="text" id="title" class="bg-gray-50 border border-gray-300 text-gray-900 text-sm rounded-lg focus:ring-blue-500 focus:border-blue-500 block w-full p-2.5" placeholder="Enter title" required /> </div> <div class="mb-6"> <label for="content" class="block mb-2 text-sm font-medium text-gray-900">Content</label> <textarea v-model="form.content" id="content" rows="4" class="block p-2.5 w-full text-sm text-gray-900 bg-gray-50 rounded-lg border border-gray-300 focus:ring-blue-500 focus:border-blue-500" placeholder="Write your content here..." ></textarea> </div> <div class="relative flex justify-end mb-7"> <NuxtLink to="/blog" class="text-white bg-gray-700 hover:bg-gray-800 focus:ring-4 focus:ring-gray-300 font-medium rounded-lg text-sm px-5 py-2.5 mr-2 mb-2 focus:outline-none mr-2" > Back </NuxtLink> <button @click="onSubmit" class="text-white bg-blue-700 hover:bg-blue-800 focus:ring-4 focus:ring-blue-300 font-medium rounded-lg text-sm px-5 py-2.5 mr-2 mb-2 focus:outline-none" > Submit </button> </div> </div> </template> <script setup lang="ts"> import type { BlogModel } from '~~/server/model/blog'; useHead({ title: 'Update Page' }); const form = reactive({ title: '', content: '' }); const route = useRoute(); const router = useRouter(); const onSubmit = async () => { try { await $fetch('/api/blog/' + route.params.id, { method: 'PUT', body: form }); router.push('/blog'); } catch { alert('Post blog error'); } }; const fetchData = async () => { try { const result = (await $fetch('/api/blog/' + route.params.id)) as any; const data = result.data as BlogModel; form.title = data.title; form.content = data.content; } catch { alert('Get blog detail error'); } }; onMounted(fetchData); </script>
import json from pathlib import Path from jupyter_server.base.handlers import APIHandler import tornado class GlobbingExtensionHandler(APIHandler): @tornado.web.authenticated def get(self, pattern): """ /api/globbing/{pattern} return a list of files or directories that match the provided pattern trying to be kind-of compliant with the results of /api/contents/{path} from jupyter-server https://jupyter-server.readthedocs.io/en/latest/developers/rest-api.html """ matches = Path('.').glob(pattern) result = [] for match in matches: if match.is_dir(): result.append(dict(path=str(match), type='directory')) else: result.append(dict(path=str(match), type='file')) self.finish(json.dumps(result))
/**************************************************************************** * This file is part of Hawaii. * * Copyright (C) 2012-2016 Pier Luigi Fiorini * Copyright (C) 2015 The Qt Company Ltd. * * Author(s): * Pier Luigi Fiorini <pierluigi.fiorini@gmail.com> * * $BEGIN_LICENSE:LGPL2.1+$ * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 2.1 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * * $END_LICENSE$ ***************************************************************************/ #include <QtCore/QSet> #include <QtCore/QSysInfo> #include <QtCore/QTextStream> #include <QtCore/private/qsimd_p.h> #include <QtGui/QGuiApplication> #include <QtGui/QOpenGLFunctions> #include <QtGui/QWindow> #include <QtGui/qpa/qplatformnativeinterface.h> #include "diagnostic_p.h" #include "greenisland_version.h" #include <wayland-version.h> #define DUMP_CPU_FEATURE(feature, name) \ if (qCpuHasFeature(feature)) str << " " name; extern char **environ; namespace GreenIsland { namespace DiagnosticOutput { static QByteArray wordWrap(QByteArray string, int length) { QByteArray::iterator it = string.begin(); QByteArray::iterator lastSpace = string.begin(); int distance = 0; while (it != string.end()) { while (it != string.end() && distance <= length) { distance++; if (*it == ' ') { lastSpace = it; if (length == distance) *lastSpace = '\n'; } ++it; } if (lastSpace != string.begin()) *lastSpace = '\n'; lastSpace = string.begin(); distance = 0; } return string; } QString systemInformation() { QString result; QTextStream str(&result); str << "OS: " << QSysInfo::prettyProductName(); str << " [" << QSysInfo::kernelType() << " version " << QSysInfo::kernelVersion() << "]\n"; str << "Architecture: " << QSysInfo::currentCpuArchitecture() << "; "; str << "features:"; #if defined(Q_PROCESSOR_X86) DUMP_CPU_FEATURE(SSE2, "SSE2"); DUMP_CPU_FEATURE(SSE3, "SSE3"); DUMP_CPU_FEATURE(SSSE3, "SSSE3"); DUMP_CPU_FEATURE(SSE4_1, "SSE4.1"); DUMP_CPU_FEATURE(SSE4_2, "SSE4.2"); DUMP_CPU_FEATURE(AVX, "AVX"); DUMP_CPU_FEATURE(AVX2, "AVX2"); DUMP_CPU_FEATURE(RTM, "RTM"); DUMP_CPU_FEATURE(HLE, "HLE"); #elif defined(Q_PROCESSOR_ARM) DUMP_CPU_FEATURE(ARM_NEON, "Neon"); #elif defined(Q_PROCESSOR_MIPS) DUMP_CPU_FEATURE(DSP, "DSP"); DUMP_CPU_FEATURE(DSPR2, "DSPR2"); #endif str << '\n'; return result; } #ifndef QT_NO_OPENGL QTextStream &operator<<(QTextStream &str, const QSurfaceFormat &format) { str << "Version: " << format.majorVersion() << '.' << format.minorVersion() << " Profile: " << format.profile() << " Swap behavior: " << format.swapBehavior() << " Buffer size (RGB"; if (format.hasAlpha()) str << 'A'; str << "): " << format.redBufferSize() << ',' << format.greenBufferSize() << ',' << format.blueBufferSize(); if (format.hasAlpha()) str << ',' << format.alphaBufferSize(); if (const int dbs = format.depthBufferSize()) str << " Depth buffer: " << dbs; if (const int sbs = format.stencilBufferSize()) str << " Stencil buffer: " << sbs; const int samples = format.samples(); if (samples > 0) str << " Samples: " << samples; return str; } #endif QString openGlContext() { QString result; QTextStream str(&result); QOpenGLContext context; if (context.create()) { # ifdef QT_OPENGL_DYNAMIC str << "Dynamic GL "; # endif switch (context.openGLModuleType()) { case QOpenGLContext::LibGL: str << "LibGL"; break; case QOpenGLContext::LibGLES: str << "LibGLES"; break; } QWindow window; if (QGuiApplication::platformName() == QLatin1String("greenisland")) window.setFlags(Qt::Desktop); window.setSurfaceType(QSurface::OpenGLSurface); //window.setScreen(QGuiApplication::primaryScreen()); window.create(); if (context.makeCurrent(&window)) { QOpenGLFunctions functions(&context); str << " Vendor: " << reinterpret_cast<const char *>(functions.glGetString(GL_VENDOR)) << "\nRenderer: " << reinterpret_cast<const char *>(functions.glGetString(GL_RENDERER)) << "\nVersion: " << reinterpret_cast<const char *>(functions.glGetString(GL_VERSION)) << "\nGLSL version: " << reinterpret_cast<const char *>(functions.glGetString(GL_SHADING_LANGUAGE_VERSION)) << "\nFormat: " << context.format(); QList<QByteArray> extensionList = context.extensions().toList(); std::sort(extensionList.begin(), extensionList.end()); QByteArray extensions = extensionList.join(' '); str << " \nFound " << extensionList.size() << " extensions:\n"; str << wordWrap(extensions, 78); context.doneCurrent(); } window.destroy(); } else { str << "Unable to create an Open GL context.\n"; } return result; } QString framework() { QString result; QTextStream str(&result); str << "Wayland version: " << WAYLAND_VERSION << "\nQt version: " << QT_VERSION_STR << "\nGreen Island version: " << GREENISLAND_VERSION_STRING << '\n'; return result; } QString environment() { QString result; QTextStream str(&result); // Environment variables str << "Environment variables:\n"; for (char **current = environ; *current; current++) { if (::strncmp(*current, "QT", 2) == 0 || ::strncmp(*current, "QML", 3) == 0 || ::strncmp(*current, "QSG", 3) == 0 || ::strncmp(*current, "XDG", 3) == 0) str << " " << *current << '\n'; } return result; } } // namespace DiagnosticOutput } // namespace GreenIsland
#include <iostream> using namespace std; template <typename T, int N> class Array { public: void fillArray(T val); void print(); T* at(int idx); private: T items[N]; }; int main() { Array<int,10>ar1; ar1.fillArray(1); *ar1.at(1)=2; ar1.print(); Array<char,10>ar2; ar2.fillArray('a'); *ar2.at(2)='b'; ar2.print(); } template<typename T, int N> void Array<T,N>::fillArray(T val) { for (int i=0;i<N;i++) { items[i]=val; } } template<typename T, int N> void Array<T,N>::print() { for (int i=0;i<N;i++) { cout<<items[i]<<" "; } cout<<endl; } template<typename T, int N> T* Array<T,N>::at(int idx) { return &items[idx]; }
const { getDb } = require('../db/sqlite'); const usersService = require('./users'); /** * Return a list of users needing check-in. A user needs check-in if 1) it * has at least one message for which the check-in frequency days is * lower than its days of absence, and 2) has no pending check-in notifications */ const getUsersNeedingCheckin = async () => { return getDb().all(` SELECT DISTINCT users.id AS id FROM users INNER JOIN messages ON users.id = messages.user_id LEFT OUTER JOIN checkin_notifications ON users.id = checkin_notifications.user_id WHERE checkin_notifications.id IS NULL AND (julianday('now') - julianday(users.last_checkin_at)) > messages.checkin_frequency_days`); } const createCheckinNotificationForUser = async (userId) => { const notificationId = require('crypto').randomBytes(64).toString('hex'); await getDb().run('INSERT INTO checkin_notifications(id, user_id, sent_at) VALUES (:id, :user_id, :sent_at)', { ':id': notificationId, ':user_id': userId, ':sent_at': new Date().toISOString() }); return notificationId; } /** * Given a notification id, it retrieves its associated user, updates the * its last checkin timestamp, and delete the check-in notifications */ const doCheckin = async (checkinNotificationId) => { const notification = await getDb().get('SELECT user_id AS userId FROM checkin_notifications WHERE id = ?', checkinNotificationId); if (!notification) { return false; } await usersService.updateUserLastCheckin(notification.userId); await deleteCheckinNotification(checkinNotificationId); return true; } /** * Given an user id, it updates the user last checkin timestamp, and delete * its pending check-in notifications */ const doCheckinByUserId = async (userId) => { await usersService.updateUserLastCheckin(userId); await getDb().run('DELETE FROM checkin_notifications WHERE user_id = ?', userId); } const deleteCheckinNotification = async (id) => { await getDb().run('DELETE FROM checkin_notifications WHERE id = ?', id); } /** * Delete the check-in notifications of users with no more messages to deliver */ const deleteOrphanCheckinNotifications = async () => { const orphanNotifications = await getDb().all(` SELECT checkin_notifications.id AS id FROM checkin_notifications LEFT JOIN messages ON checkin_notifications.user_id = messages.user_id WHERE messages.user_id IS NULL`); for (const { id } of orphanNotifications) { await deleteCheckinNotification(id); } } module.exports = { getUsersNeedingCheckin, createCheckinNotificationForUser, doCheckin, doCheckinByUserId, deleteCheckinNotification, deleteOrphanCheckinNotifications, }
/* eslint-disable import/no-extraneous-dependencies */ import { prisma } from '@infra/database/prisma'; import { app } from '@infra/http/app'; import faker from 'faker'; import request from 'supertest'; import { v4 } from 'uuid'; import { City } from '.prisma/client'; let city: City; describe('RemoveCustomerController', () => { afterAll(async () => { const deleteAllCustomers = prisma.customer.deleteMany(); const deleteAllCities = prisma.city.deleteMany(); await prisma.$transaction([deleteAllCustomers, deleteAllCities]); await prisma.$disconnect(); }); beforeEach(async () => { city = await prisma.city.create({ data: { country: faker.address.state(), name: faker.address.city(), }, }); }); it('should be able to delete specific customer by id!', async () => { const customer = await prisma.customer.create({ data: { birth_date: faker.date.past(), full_name: faker.name.findName(), genre: faker.random.arrayElement(['MALE', 'FEMALE']), city_id: city.id, }, }); /** * Test Case */ const response = await request(app).delete(`/api/customers/${customer.id}`); expect(response.status).toBe(204); expect(response.body).toEqual({}); const customerExists = await prisma.customer.findUnique({ where: { id: customer.id, }, }); expect(customerExists).toBe(null); expect(customerExists).toBeFalsy(); }); it('should not be able to delete specific customer by wrong/invalid id!', async () => { const response = await request(app).delete(`/api/customers/${v4()}`); expect(response.body.status).toEqual('Exception!'); expect(response.body.name).toEqual('CustomerNotFoundError'); expect(response.status).toBe(404); }); });
CREATE DATABASE PortfolioProject; USE PortfolioProject; SHOW VARIABLES LIKE "secure_file_priv"; DROP TABLE CovidDeaths; DROP TABLE CovidVaccinations; -- Preparing data -- Making table CovidDeaths CREATE TABLE CovidDeaths ( iso_code VARCHAR(50), continent VARCHAR(50), location VARCHAR(50), date date, population bigint, total_cases int, new_cases int, new_cases_smoothed float, total_deaths int, new_deaths int, new_deaths_smoothed float, total_cases_per_million float, new_cases_per_million float, new_cases_smoothed_per_million float, total_deaths_per_million float, new_deaths_per_million float, new_deaths_smoothed_per_million float, reproduction_rate float, icu_patients INT, icu_patients_per_million float, hosp_patients INT, hosp_patients_per_million float, weekly_icu_admissions float, weekly_icu_admissions_per_million float, weekly_hosp_admissions float, weekly_hosp_admissions_per_million float ) Engine = InnoDB; -- Importing data from csv file LOAD DATA INFILE 'C:\\ProgramData\\MySQL\\MySQL Server 8.1\\Uploads\\CovidDeaths.csv' INTO TABLE CovidDeaths FIELDS TERMINATED BY ';' LINES TERMINATED BY '\n' IGNORE 1 LINES; SELECT * FROM CovidDeaths; -- Change null from data null SELECT * FROM CovidDeaths WHERE continent = 'null'; UPDATE CovidDeaths SET continent = null WHERE continent = 'null'; SELECT * FROM CovidDeaths WHERE continent is null; -- Making table CovidVaccinations CREATE TABLE CovidVaccinations ( iso_code VARCHAR(50), continent VARCHAR(50), location VARCHAR(50), date DATE, new_tests INT, total_tests INT, total_tests_per_thousand float, new_tests_per_thousand float, new_tests_smoothed INT, new_tests_smoothed_per_thousand float, positive_rate float, tests_per_case float, tests_units VARCHAR(100), total_vaccinations BIGINT, people_vaccinated BIGINT, people_fully_vaccinated BIGINT, new_vaccinations BIGINT, new_vaccinations_smoothed BIGINT, total_vaccinations_per_hundred FLOAT, people_vaccinated_per_hundred FLOAT, people_fully_vaccinated_per_hundred FLOAT, new_vaccinations_smoothed_per_million INT, stringency_index FLOAT, population_density FLOAT, median_age FLOAT, aged_65_older FLOAT, aged_70_older FLOAT, gdp_per_capita FLOAT, extreme_poverty FLOAT, cardiovasc_death_rate FLOAT, diabetes_prevalence FLOAT, female_smokers FLOAT, male_smokers FLOAT, handwashing_facilities FLOAT, hospital_beds_per_thousand FLOAT, life_expectancy FLOAT, human_development_index FLOAT ) Engine = InnoDB; -- Importing data from csv file LOAD DATA INFILE 'C:\\ProgramData\\MySQL\\MySQL Server 8.1\\Uploads\\CovidVaccinations.csv' INTO TABLE CovidVaccinations FIELDS TERMINATED BY ';' LINES TERMINATED BY '\n' IGNORE 1 LINES; SELECT * FROM CovidVaccinations; -- -- Change null from data null SELECT * FROM CovidVaccinations WHERE continent = 'null'; UPDATE CovidVaccinations SET continent = null WHERE continent = 'null'; SELECT * FROM CovidVaccinations WHERE continent is null; SELECT * FROM CovidVaccinations WHERE tests_units = 'null'; UPDATE CovidVaccinations SET tests_units = null WHERE tests_units = 'null'; SELECT * FROM CovidVaccinations WHERE tests_units is null; -- Data Eksploration SELECT * FROM PortfolioProject.CovidDeaths ORDER BY location, date; SELECT * FROM PortfolioProject.CovidVaccinations ORDER BY location, date; -- Select Data that we are going to be using SELECT location, date, total_cases, new_cases, total_deaths, population FROM PortfolioProject.CovidDeaths WHERE continent is not null ORDER BY location, date; -- Looking at total cases vs total deaths -- Shows likelihood of dying if you contract covid in Indonesia SELECT location, date, total_cases, total_deaths, (total_deaths/total_cases)*100 as DeathPercentage FROM PortfolioProject.CovidDeaths WHERE location LIKE '%Indonesia%' ORDER BY location, date; -- Looking at total cases vs population -- Show percentage of population got Covid SELECT location, date, population, total_cases, (total_cases/population)*100 as PercentPopulationInfected FROM PortfolioProject.CovidDeaths -- WHERE location LIKE '%Indonesia%' WHERE continent is not null ORDER BY location, date; -- Looking at Countries with Highest Infection Rate compared to Population SELECT location, MAX(total_cases) AS HighestInfectionCount, population, MAX((total_cases/population)*100) as PercentPopulationInfected FROM PortfolioProject.CovidDeaths -- WHERE location LIKE '%Indonesia%' WHERE continent is not null GROUP BY location, population ORDER BY PercentPopulationInfected DESC; -- Showing Countries with Highest Death Count Per Population SELECT location, MAX(total_deaths) AS TotalDeathCount FROM PortfolioProject.CovidDeaths -- WHERE location LIKE '%Indonesia%' WHERE continent is not null GROUP BY location ORDER BY TotalDeathCount DESC; -- LET'S BREAK THINS DOWN BY CONTINENT -- Showing the continent with the highest death count per population SELECT continent, MAX(total_deaths) AS TotalDeathCount FROM PortfolioProject.CovidDeaths -- WHERE location LIKE '%Indonesia%' WHERE continent is not null GROUP BY continent ORDER BY TotalDeathCount DESC; -- GLOBAL NUMBERS SELECT date, SUM(new_deaths) as total_deaths, SUM(new_cases) as total_cases, (SUM(new_deaths)/SUM(new_cases))*100 as DeathPercentage FROM PortfolioProject.CovidDeaths -- WHERE location LIKE '%Indonesia%' WHERE continent is not null GROUP BY date ORDER BY date; -- Looking total population vs vaccinations -- USE CTE With Popvsvac (Continent, Location, Date, Population, New_Vaccination, RollingPeopleVaccinated) as ( SELECT dea.continent, dea.location, dea.date, dea.population, vac.new_vaccinations, SUM(vac.new_vaccinations) OVER (PARTITION BY dea.location ORDER BY dea.location, dea.date) AS RollingPeopleVaccinated FROM PortfolioProject.CovidDeaths as dea JOIN PortfolioProject.CovidVaccinations as vac ON dea.location = vac.location AND dea.date = vac.date WHERE dea.continent is not null ORDER BY 2,3 ) SELECT *, (RollingPeopleVaccinated/Population)*100 as PercentPopulationVaccinated FROM Popvsvac; -- TEMP TABLE DROP TABLE PercentPopulationvaccinated; CREATE TEMPORARY TABLE PercentPopulationVaccinated ( Continent VARCHAR(50), Location VARCHAR(50), date DATE, Population BIGINT, New_Vaccinations BIGINT, RollingPeopleVaccinated INT ); INSERT INTO PercentPopulationVaccinated (Continent, Location, Date, Population, New_Vaccinations, RollingPeopleVaccinated) SELECT dea.continent, dea.location, dea.date, dea.population, vac.new_vaccinations, SUM(vac.new_vaccinations) OVER (PARTITION BY dea.location ORDER BY dea.location, dea.date) AS RollingPeopleVaccinated FROM PortfolioProject.CovidDeaths as dea JOIN PortfolioProject.CovidVaccinations as vac ON dea.location = vac.location AND dea.date = vac.date WHERE dea.continent is not null ORDER BY 2,3; SELECT * FROM PercentPopulationVaccinated;
#pragma once #include "ListNode.h" #include "Iterator.h" #include <utility> #include <vector> #define MAX_SIZE 1000 using namespace std; template <typename T> class Container { private: Node<T>* head; Node<T>* tail; size_t size_; public: using ValType = T; using NodeType = Node<ValType>; using Iterator = ConIterator<Container<ValType>>; public: Container() { // this->head = nullptr; // this->tail = nullptr; // this->size_ = 0; this->head= new Node<T>(); this->tail = head; this->size_=0; } Container(Container&& other){ head = exchange(other.head, nullptr); tail = exchange(other.tail, nullptr); size_ = std::exchange(other.size_, 0); } Container(vector <T> mas){ this->head= new Node<T>(); this->tail = head; this->size_=0; for (int i =0; i<mas.size();i++){ push_back(mas[i]); } } // Container operator=(Container&& other) noexcept // { // if (this == &other) // return *this; // // head = std::exchange(other.head, nullptr); // tail = std::exchange(other.tail, nullptr); // size_= std::exchange(other.size_, 0); // return *this; // } Container& operator = ( Container& other) { Node<T>* cache = other.head; clear(); push_front(other.head->data); cache=cache->next; while(cache->next!=tail){ push_back(cache->data); cache=cache->next; } } // bool operator==(Container& first){ // if (size_==first.size_){ // Node<T>* cache = first.head; // Node<T>* cache1 = head; // for (int i =0; i< size_;i++){ // if(*cache!=*cache1) return false; // cache1=cache1->next; // cache=cache->next; // } // return true; // } else return false; // } ~Container() { clear(); } Iterator begin() { return Iterator(head); } Iterator end() { return Iterator(tail); } const Iterator cbegin() const{ return Iterator(head); } const Iterator cend() const { return Iterator(tail); } bool operator == (const Container& other) const{ return bool(size_ == other.size_) && equals(cbegin(), cend(), other.cbegin()); } bool operator!=(const Container& other) const { return *this != other; } void swap(Container<T> &ls){ Node<T>* p1 =ls.head; long c = ls.size_; ls.head = head; head = p1; p1 = ls.tail; ls.tail = tail; tail =p1; ls.size_ = size_; size_ = c; } size_t max_size() const { return MAX_SIZE; } size_t size() const { return size_; } bool empty(){ if (size_>0) return 1; else return 0; } void push_front(T a){ if (this->head == nullptr) { this->head = new Node<T>(a); this->tail = this->head->next; size_++; } else { Node<T> *p = new Node<T>(a); p->next =this->head; this->head = p; size_++; } }; void push_back(T a){ if(size_>=1) { Node<T> *run = head; Node<T> *p = new Node(a); while (run->next != tail) { run = run->next; } run->next = p; p->next = tail; size_++; }else{ Node<T>* p = new Node<T>(a); p->next= tail; head=p; size_++; } } void pop_front(){ if (size_>=1) { Node<T> *p = head; head = p->next; delete p; size_--; } } void pop_back(){ if (size_>=1) { if (head->next == tail) { delete head; head = tail; size_--; } else { Node<T> *p = head; Node<T> *run = p->next; while ((run->next != tail)) { run = run->next; p = p->next; } p->next = tail; delete run; size_--; } } } void print() { if (this->head == nullptr) cout << "List is empty!\n"; else { Node<T>* cache = this->head; while (cache->next != tail) { cout << cache->data << ' '; cache = cache->next; } std::cout << cache->data << '\n'; } } void clear() { if (this->head == nullptr) cout; else { Node<T>* cache = this->head->next; while (this->head != nullptr) { delete this->head; this->head = cache; if (cache) cache = cache->next; } this->head = nullptr; this->size_ = 0; } } };
// // EncryptedStore.swift // DiceKeys // // Created by Stuart Schechter on 2020/11/28. // import Foundation import LocalAuthentication import Combine import CryptoKit /// A set of functions to simplify storing strings in the Apple KeyChain /// such that only this app on this device can read them. private class KeyChain { enum KeyChainError: Error { case notFound case osError(OSStatus) } class func deleteKey(id: String, throwIfFails: Bool = false) throws { let query = [kSecClass: kSecClassGenericPassword, kSecAttrAccount: id, kSecAttrAccessible: kSecAttrAccessibleWhenUnlockedThisDeviceOnly, kSecUseDataProtectionKeychain: true, ] as [String: Any] let status = SecItemDelete(query as CFDictionary) if status != errSecSuccess && throwIfFails { throw KeyChainError.osError((status)) } } class func saveKey(id: String, key: Data) throws { let query = [kSecClass: kSecClassGenericPassword, kSecAttrAccount: id, kSecAttrAccessible: kSecAttrAccessibleWhenUnlockedThisDeviceOnly, kSecUseDataProtectionKeychain: true, kSecValueData: key ] as [String: Any] try deleteKey(id: id) let status = SecItemAdd(query as CFDictionary, nil) if status != errSecSuccess { throw KeyChainError.osError((status)) } } class func saveKey(id: String, key: String) throws { try saveKey(id: id, key: key.data(using: .utf8)!) } class func isPresentInKeyChain(id: String) -> Bool { // Seek a generic password with the given account. let query = [kSecClass: kSecClassGenericPassword, kSecAttrAccount: id, kSecUseDataProtectionKeychain: true ] as [String: Any] switch SecItemCopyMatching(query as CFDictionary, nil) { case errSecSuccess: return true default: return false } } class func loadKeyData(id: String) throws -> Data { // Seek a generic password with the given account. let query = [kSecClass: kSecClassGenericPassword, kSecAttrAccount: id, kSecUseDataProtectionKeychain: true, kSecReturnData: true ] as [String: Any] // Find and cast the result as data. var item: CFTypeRef? let status = SecItemCopyMatching(query as CFDictionary, &item) switch status { case errSecSuccess: guard let data = item as? Data else { throw KeyChainError.notFound } return data case errSecItemNotFound: throw KeyChainError.notFound default: throw KeyChainError.osError(status) } } class func loadKeyString(id: String) throws -> String { return String(decoding: try loadKeyData(id: id), as: UTF8.self) } } fileprivate let defaultReason: String = "Unlock your DiceKey" /// A store for raw DiceKeys that represents them as password credentials /// in the Apple KeyChain for use only by this app on this device. class EncryptedDiceKeyStore { class func getReason(forCenterFace centerFace: Face?) -> String { if let face = centerFace { return "Unlock DiceKey with \(face.letterAndDigit) in Center" } return defaultReason } class func authenticate ( reason: String? = nil, _ onComplete: @escaping (_ wasAuthenticated: Result<Void, LAError>) -> Void ) { var error: NSError? let laContext = LAContext() guard laContext.canEvaluatePolicy(.deviceOwnerAuthentication, error: &error) else { onComplete(.failure(LAError(_nsError: error!))) return } laContext.evaluatePolicy(.deviceOwnerAuthentication, localizedReason: reason ?? defaultReason ) { success, error in onComplete(success ? .success(()) : .failure(LAError(LAError.Code(rawValue: error!._code)!))) } } class func authenticate ( reason: String? ) -> Future<Void, LAError> { return Future<Void, LAError> { promise in self.authenticate(reason: reason) { result in promise(result) } } } class func getDiceKey(fromKeyId keyId: String, centerFace: Face? = nil, _ onComplete: @escaping (Result<DiceKey, Error>) -> Void) { self.authenticate(reason: getReason(forCenterFace: centerFace)) { authResult in switch authResult { case .failure(let error): onComplete(.failure(error)); return case .success: break } do { let diceKeyInHRF = try KeyChain.loadKeyString(id: keyId) // String(contentsOf: try Directories.getRawDiceKeyFileUrl(forKeyId: keyId), encoding: .utf8) let diceKey = try DiceKey.createFrom(humanReadableForm: diceKeyInHRF) onComplete(.success(diceKey)) } catch { onComplete(.failure(error)) } return } } class func delete(keyId: String) -> Result<Void, Error> { try! KeyChain.deleteKey(id: keyId) return .success(()) } class func hasDiceKey(forKeyId keyId: String) -> Bool { KeyChain.isPresentInKeyChain(id: keyId) } class func getDiceKey(fromKeyId keyId: String) -> Future<DiceKey, Error> { return Future<DiceKey, Error> { promise in self.getDiceKey(fromKeyId: keyId) { result in promise(result) } } } class func put(diceKey: DiceKey, _ onComplete: @escaping (Result<String, Error>) -> Void) { do { let keyId = diceKey.id try KeyChain.saveKey(id: keyId, key: diceKey.toHumanReadableForm()) onComplete(.success(keyId)) } catch { onComplete(.failure(error)) } } class func put(diceKey: DiceKey) throws -> Future<String, Error> { return Future<String, Error> { promise in self.put(diceKey: diceKey) { result in promise(result) } } } }
import { createAsyncThunk } from "@reduxjs/toolkit"; import { backendURL } from "../util/consts"; import { PersonaliaUserType } from "../util/types"; export const fetchPersonalia = createAsyncThunk( "get/personalia", async (): Promise<[PersonaliaUserType]> => { const response = await fetch(`${backendURL}/Personalia`); return await response.json(); }, ); export const fetchPersonaliaById = createAsyncThunk( "get/personaliaById", async (id: number): Promise<PersonaliaUserType> => { const response = await fetch(`${backendURL}/Personalia/${id}`); return await response.json(); }, ); export const createPersonalia = createAsyncThunk( "post/createPersonalia", async (createPersonalia: Omit<PersonaliaUserType, "id">): Promise<PersonaliaUserType> => { const response = await fetch(`${backendURL}/Personalia`, { method: "POST", headers: { "Content-Type": "application/json", }, body: JSON.stringify(createPersonalia), }); return response.json(); }, ); export const updatePersonalia = createAsyncThunk( "put/updatePersonalia", async (updatePersonalia: PersonaliaUserType): Promise<PersonaliaUserType> => { const response = await fetch(`${backendURL}/Personalia/${updatePersonalia.id}`, { method: "PUT", headers: { "Content-Type": "application/json", }, body: JSON.stringify(updatePersonalia), }); return response.json(); }, );
import { Link } from 'react-router-dom'; import LOGO from '../../public/burgeranime.png'; import { useState } from 'react'; import { useCookies } from 'react-cookie'; import Axios from 'axios'; function Login() { const [email, setEmail] = useState(''); const [password, setPassword] = useState(''); const [error, setError] = useState(''); const [_, setCookie] = useCookies(['acc_tokens']); const handleSubmit = (e) => { e.preventDefault(); const serverURL = 'https://burgeranimeserver.vercel.app'; setError(''); Axios.post(`${serverURL}/signin`, { email, pwd: password }) .then((res) => { if (res.data.ok === 1) { //const { pwd, ...userWithoutPwd } = res.data.user; setCookie('acc_tokens', res.data.token); window.localStorage.setItem('token', res.data.token); window.location.href = '/'; console.log(res.data); } else { setError(res.data.message || 'An error occurred. Please try again later.'); } }) .catch((error) => { console.error('Error logging in:', error); setError('An error occurred. Please try again later.'); }); }; return ( <> <div className="hero min-h-screen mt-10 absolute"> <div className="hero-content flex-col"> <div className="text-center lg:text-left"> <Link to="/"> <h1 className="text-5xl font-bold"> <img src={LOGO} alt="Burger Anime" width={100} className="ml-auto" /> </h1> </Link> </div> <div className="card-body"> <form onSubmit={handleSubmit}> <div className="form-control"> <label className="label"> <span className="">Email</span> </label> <input type="email" required placeholder="email" className="input input-bordered bg-[#000000ab]" onChange={(e) => setEmail(e.target.value)} /> </div> <div className="form-control"> <label className="label"> <span className="">Password</span> </label> <input type="password" required placeholder="password" className="input input-bordered bg-[#000000ab]" onChange={(e) => setPassword(e.target.value)} /> <label className="label"> <a href="#" className="link link-hover text-xs"> Forgot password? </a> </label> </div> {error && <div className="text-red-500 mt-4">{error}</div>} <div className="form-control mt-6"> <button className="btn text-black hover:text-white hover:bg-green-600 bg-yellow-500">Log In</button> </div> </form> </div> <div className="text-center p-10"> <p> No account?{' '} <span className="text-yellow-500"> <Link to="/register">Create One</Link> </span> </p> </div> </div> </div> </> ); } export default Login;
package com.wesuckatlife.wesuckatminecraft.block.entity; import com.wesuckatlife.wesuckatminecraft.block.ModBlocks; import com.wesuckatlife.wesuckatminecraft.item.ModItems; import com.wesuckatlife.wesuckatminecraft.recipe.GemInfusingStationRecipe; import com.wesuckatlife.wesuckatminecraft.screen.GemInfusingStationMenu; import net.minecraft.core.BlockPos; import net.minecraft.core.Direction; import net.minecraft.nbt.CompoundTag; import net.minecraft.network.chat.Component; import net.minecraft.world.Containers; import net.minecraft.world.MenuProvider; import net.minecraft.world.SimpleContainer; import net.minecraft.world.entity.player.Inventory; import net.minecraft.world.entity.player.Player; import net.minecraft.world.inventory.AbstractContainerMenu; import net.minecraft.world.inventory.ContainerData; import net.minecraft.world.item.ItemStack; import net.minecraft.world.level.Level; import net.minecraft.world.level.block.entity.BlockEntity; import net.minecraft.world.level.block.entity.BlockEntityType; import net.minecraft.world.level.block.state.BlockState; import net.minecraftforge.common.capabilities.Capability; import net.minecraftforge.common.capabilities.ForgeCapabilities; import net.minecraftforge.common.util.LazyOptional; import net.minecraftforge.items.IItemHandler; import net.minecraftforge.items.ItemStackHandler; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import java.util.Optional; public class GemInfusingStationBlockEntity extends BlockEntity implements MenuProvider { private final ItemStackHandler itemHandler = new ItemStackHandler(3) { @Override protected void onContentsChanged(int slot) { setChanged(); } }; private LazyOptional<IItemHandler> lazyItemHandler = LazyOptional.empty(); protected final ContainerData data; private int progress = 0; private int maxProgress = 78; public GemInfusingStationBlockEntity(BlockPos pPos, BlockState pBlockState) { super(ModBlockEntities.GEM_INFUSING_STATION.get(), pPos, pBlockState); this.data = new ContainerData() { @Override public int get(int pIndex) { return switch (pIndex) { case 0 -> GemInfusingStationBlockEntity.this.progress; case 1 -> GemInfusingStationBlockEntity.this.maxProgress; default -> 0; }; } @Override public void set(int pIndex, int pValue) { switch (pIndex) { case 0 -> GemInfusingStationBlockEntity.this.progress = pValue; case 1 -> GemInfusingStationBlockEntity.this.maxProgress = pValue; } } @Override public int getCount() { return 2; } }; } @Override public Component getDisplayName() { return Component.literal("Gem Infusing Station"); } @Nullable @Override public AbstractContainerMenu createMenu(int pContainerId, Inventory pPlayerInventory, Player pPlayer) { return new GemInfusingStationMenu(pContainerId, pPlayerInventory, this, this.data); } @Override public @NotNull <T> LazyOptional<T> getCapability(@NotNull Capability<T> cap, @Nullable Direction side) { if (cap == ForgeCapabilities.ITEM_HANDLER) { return lazyItemHandler.cast(); } return super.getCapability(cap, side); } @Override public void onLoad() { super.onLoad(); lazyItemHandler = LazyOptional.of(() -> itemHandler); } @Override public void invalidateCaps() { super.invalidateCaps(); lazyItemHandler.invalidate(); } @Override protected void saveAdditional(CompoundTag pTag) { pTag.put("inventory", itemHandler.serializeNBT()); pTag.putInt("gem_infusing_station.progress", this.progress); super.saveAdditional(pTag); } @Override public void load(CompoundTag pTag) { super.load(pTag); itemHandler.deserializeNBT(pTag.getCompound("inventory")); progress = pTag.getInt("gem_infusing_station.progress"); } public void drops() { SimpleContainer inventory = new SimpleContainer(itemHandler.getSlots()); for (int i = 0; i < itemHandler.getSlots(); i++) { inventory.setItem(i, itemHandler.getStackInSlot(i)); } Containers.dropContents(this.level, this.worldPosition, inventory); } public static void tick(Level level, BlockPos blockPos, BlockState blockState, GemInfusingStationBlockEntity pEntity) { if (level.isClientSide()) return; if (hasRecipe(pEntity)) { pEntity.progress++; setChanged(level, blockPos, blockState); if (pEntity.progress >= pEntity.maxProgress) { craftItem(pEntity); } } else { pEntity.resetProgress(); setChanged(level, blockPos, blockState); } } private void resetProgress() { this.progress = 0; } private static void craftItem(GemInfusingStationBlockEntity pEntity) { Level level = pEntity.level; SimpleContainer inventory = new SimpleContainer(pEntity.itemHandler.getSlots()); for (int i = 0; i < pEntity.itemHandler.getSlots(); i++) { inventory.setItem(i, pEntity.itemHandler.getStackInSlot(i)); } Optional<GemInfusingStationRecipe> recipe = level.getRecipeManager() .getRecipeFor(GemInfusingStationRecipe.Type.INSTANCE, inventory, level); if (hasRecipe(pEntity)) { pEntity.itemHandler.extractItem(1, 1, false); pEntity.itemHandler.setStackInSlot(2, new ItemStack(recipe.get().getResultItem().getItem(), pEntity.itemHandler.getStackInSlot(2).getCount() + 1)); pEntity.resetProgress(); } } private static boolean hasRecipe(GemInfusingStationBlockEntity pEntity) { Level level = pEntity.level; SimpleContainer inventory = new SimpleContainer(pEntity.itemHandler.getSlots()); for (int i = 0; i < pEntity.itemHandler.getSlots(); i++) { inventory.setItem(i, pEntity.itemHandler.getStackInSlot(i)); } Optional<GemInfusingStationRecipe> recipe = level.getRecipeManager() .getRecipeFor(GemInfusingStationRecipe.Type.INSTANCE, inventory, level); return recipe.isPresent() && canInsertAmountIntoOutputSlot(inventory) && canInsertItemIntoOutputSlot(inventory, recipe.get().getResultItem()); } private static boolean canInsertItemIntoOutputSlot(SimpleContainer inventory, ItemStack itemStack) { return inventory.getItem(2).getItem() == itemStack.getItem() || inventory.getItem(2).isEmpty(); } private static boolean canInsertAmountIntoOutputSlot(SimpleContainer inventory) { return inventory.getItem(2).getMaxStackSize() > inventory.getItem(2).getCount(); } }
import { Body, Controller, Delete, Get, HttpCode, HttpStatus, Param, Post, Put } from '@nestjs/common'; import { AlbumService } from './album.service'; import { CreateAlbumDto } from './dto/create-album.dto'; import { UpdateAlbumDto } from './dto/update-album.dto'; @Controller('album') export class AlbumController { constructor(private readonly albumService: AlbumService) {} @Get() async getAll() { return await this.albumService.getAlbums(); } @Get(':id') async getById(@Param('id') id: string) { return await this.albumService.getAlbumById(id); } @Post() @HttpCode(HttpStatus.CREATED) async create(@Body() createAlbumDto: CreateAlbumDto) { return await this.albumService.createAlbum(createAlbumDto) } @Delete(':id') @HttpCode(HttpStatus.NO_CONTENT) async delete(@Param('id') id: string) { return await this.albumService.deleteAlbum(id); } @Put(':id') async update( @Body() updateAlbumDto: UpdateAlbumDto, @Param('id') id: string, ) { return await this.albumService.updateAlbum(updateAlbumDto, id); } }
package com.bosch.jbapp.controller; import com.bosch.jbapp.dto.ApplicationRegistrationDto; import com.bosch.jbapp.dto.WebPortalDocumentListDto; import com.bosch.jbapp.dto.WebPortalInfoDto; import com.bosch.jbapp.dto.WebPortalViewListDto; import com.bosch.jbapp.service.WebPortalService; import jakarta.annotation.security.RolesAllowed; import org.springframework.http.HttpStatusCode; import org.springframework.http.ResponseEntity; import org.springframework.security.access.prepost.PreAuthorize; import org.springframework.web.bind.annotation.*; import java.util.List; /** * REST controller for handling the requests from Nexeed Portal */ @CrossOrigin(origins = {"*"}) @RestController @RequestMapping("/portal-api/v1") public class WebPortalController { private final WebPortalService service; public WebPortalController(WebPortalService service) { this.service = service; } /** * PUT /info : serves info parts which are needed for Nexeed to register an application correctly * * @param request * the HTTP request * @return necessary info part for Nexeed application registration */ //String url = "${bmlp.nexeed.base-url}" //, configuration = CustomFeignConfiguration.class) String url = "bmlp.nexeed.base-url"; @PutMapping("/registry/api/v1/registry/systems/${bmlp.nexeed.application-id}") public ApplicationRegistrationDto registerApplication() { return service.registerApplication(); } /** * GET /info : serves info parts which are needed for Nexeed to register an application correctly * * @param request * the HTTP request * @return necessary info part for Nexeed application registration */ @GetMapping("/info") public WebPortalInfoDto getInfo() { //log.debug("Receive /info request from Nexeed for application registration"); return service.getInfo(); } /** * GET /views : serves view information parts which are needed for Nexeed to register an application correctly * * @param request * the HTTP request * @return necessary view information parts for Nexeed application registration * @throws IOException */ @GetMapping("/views") public WebPortalViewListDto getViews() { return service.getViews(); } /** * GET /docs : serves view information parts which are needed for third Party License Information (Disclosure Documents) in the Web Portal UI. * * @param request * the HTTP request * @return necessary docs information parts for Nexeed application registration * @throws IOException */ @GetMapping("/docs") public WebPortalDocumentListDto getDocuments() { return service.getDocuments(); } }
package com.olaapp.springtodoapp.models; import java.time.Instant; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.Table; import javax.validation.constraints.NotBlank; import lombok.Getter; import lombok.Setter; @Entity @Table(name = "todo_item") public class TodoItem { @Id /*Domyślna strategia pozwala na przejęcie odpowiedzialności za generowanie kluczy głównych przez TopLink, który posługuje się pomocniczą tabelą przechowującą wartości potrzebne do generowania kluczy*/ @GeneratedValue(strategy = GenerationType.AUTO) @Getter @Setter private Long id; @Getter @Setter @NotBlank(message = "Description is required") private String description; //task description @Getter @Setter private boolean complete; //things done or not //import instant from java time @Getter @Setter private Instant createdDate; @Getter @Setter private Instant modifiedDate; public TodoItem() { } public TodoItem(String description) { this.description = description; this.complete = false; this.createdDate = Instant.now(); this.modifiedDate = Instant.now(); } //override to string @Override public String toString() { return String.format("TodoItem{id=%d, description='%s', complete='%s', createdDate='%s', modifiedDate='%s'}", id, description, complete, createdDate, modifiedDate); } }
package db import ( "context" "time" "xyzvote/consts" "gorm.io/gorm" ) /* Tx 写操作(新增、修改、删除) 冲突 读操作(查询) 空 没有约束的话,先查后写 有约束的话,处理边界情况 */ type CreateFormAndOptionTxParams struct { UserId string Title string Type int32 Status int32 Duration int64 OptionNames []string CreatedAt time.Time } // 创建表单和选项 func (s *MySQLVoteStore) CreateFormAndOptionTx(ctx context.Context, arg CreateFormAndOptionTxParams) error { if err := s.database.Debug().Transaction(func(tx *gorm.DB) error { var form Form form.UserId = arg.UserId form.Title = arg.Title form.Type = arg.Type form.Status = arg.Status form.Duration = arg.Duration form.CreatedAt = arg.CreatedAt if err := tx.Table(consts.FormTableName).Create(&form).Error; err != nil { return err } for _, optionName := range arg.OptionNames { var option Option option.FormId = form.Id option.Name = optionName option.CreatedAt = arg.CreatedAt if err := tx.Table(consts.OptionTableName).Create(&option).Error; err != nil { return err } } return nil }); err != nil { return err } return nil } /* 原生 SQL INSERT INTO `form` (`title`,`type`,`status`,`duration`,`user_id`,`created_at`,`updated_at`) VALUES ('today city walk', 0, 1, 86400, 'f2d274f5-bb8b-4175-a60b-a2d113df4818', NOW(), NOW()); INSERT INTO `form_opt` (`name`,`vote_count`,`form_id`,`created_at`,`updated_at`) VALUES ('nanjing', 0, 4, NOW(), NOW()); INSERT INTO `form_opt` (`name`,`vote_count`,`form_id`,`created_at`,`updated_at`) VALUES ('shanghai', 0, 4, NOW(), NOW()); */
#!/bin/bash # Set the source and backup directories MINECRAFT_DIR="/opt/minecraft-server" BACKUP_DIR="/var/backups/minecraft-server" # Get a list of the available backups backups=("$BACKUP_DIR"/*) backup_names=() for backup in "${backups[@]}"; do backup_names+=($(basename "$backup")) done # Generate a menu for the user to select a backup echo "Please select a backup to restore:" select backup_name in "${backup_names[@]}"; do # Check if the user's selection is valid if [[ -n $backup_name ]]; then break else echo "Invalid selection. Please try again." fi done # Ask for confirmation read -p "Are you sure you want to restore the backup from $backup_name? This will overwrite the current server directory. (y/n): " confirm confirm=${confirm,,} # tolower if [[ $confirm =~ ^(yes|y)$ ]]; then # Stop the Minecraft server echo "Stopping Minecraft server..." systemctl stop minecraft # Restore the backup echo "Restoring backup..." rsync -a --delete "$BACKUP_DIR/$backup_name/" "$MINECRAFT_DIR/" echo "Backup restored." # Start the Minecraft server echo "Starting Minecraft server..." systemctl start minecraft else echo "Restore cancelled." fi
import React from 'react'; import { Avatar, Table, Typography, Tag, Space } from 'antd'; import { collection, doc, query, where } from 'firebase/firestore'; import { useParams } from 'react-router-dom'; import { useFirestore, useFirestoreCollectionData, useFirestoreDocData, useSigninCheck, } from 'reactfire'; import styled from 'styled-components'; import { useColumnSearchProps } from '../hooks/useColumnSearchProps'; import { useTranslation } from 'react-i18next'; const { Title } = Typography; const AvatarStyled = styled(Avatar)` background-color: ${(props) => props.backgroundColor || 'auto'}; `; function RoomMembers() { const { t } = useTranslation(); let dataSource = []; const columns = [ { title: 'STT', dataIndex: 'stt', key: 'stt', }, { title: t('Member'), dataIndex: 'member', key: 'member', }, { title: 'Email', dataIndex: 'email', key: 'email', ...useColumnSearchProps('email'), }, { title: t("Current score"), dataIndex: 'score', key: 'score', }, ]; const { status: signinCheckStatus, data: signinCheckData } = useSigninCheck(); const firestore = useFirestore(); const { roomId } = useParams(); const { status: roomStatus, data: roomData } = useFirestoreDocData( doc(firestore, `rooms/${roomId}`) ); const membersId = roomData?.members?.map((member) => member.uid); //** get members in users collection const usersColQuery = query( collection(firestore, 'users'), where('uid', 'in', membersId || [null]) ); // where member in room const { status: membersInUsersStatus, data: membersInUsersData } = useFirestoreCollectionData(usersColQuery, { idField: 'memberId', }); //** get members in room document */ const { status: membersInRoomStatus, data: membersInRoomData } = useFirestoreCollectionData( collection(firestore, `rooms/${roomId}/members`), { idField: 'memberId', } ); if ( signinCheckStatus === 'success' && signinCheckData.signedIn && membersInUsersData ) { dataSource = membersInUsersData.map((membersInUsersData, index) => { const { uid, photoURL, displayName, email, avatarColor } = membersInUsersData; const memberInRoom = membersInRoomData?.find( (memberInRoom) => memberInRoom.uid === membersInUsersData.uid ); return { key: uid, stt: index + 1, member: ( <> <Space size="small"> {photoURL ? ( <AvatarStyled size="small" src={photoURL} /> ) : ( <AvatarStyled size="small" backgroundColor={avatarColor} icon={ (!photoURL && (displayName[0]?.toUpperCase() || email[0]?.toUpperCase())) || 'U' } /> )} {displayName} {uid === roomData?.owner?.uid && <Tag color="green">owner</Tag>} {uid === signinCheckData?.user?.uid && ( <Tag color="purple">me</Tag> )} </Space> </> ), email, score: memberInRoom?.allTotalScore || 0, }; }); } else { dataSource = []; } return ( <> <Title level={2} style={{ textAlign: 'center', textTransform: 'capitalize' }} > {t('members')} </Title> <div> <Table bordered={true} columns={columns} dataSource={dataSource} /> </div> </> ); } export default RoomMembers;
import { Box, Grid, List, ListItemButton, ListItemText, Typography, useTheme } from '@mui/material' import React, { useContext } from 'react' import { Link } from 'react-router-dom' import logo from '../../Assets/logo.png' import logodark from '../../Assets/logodark.png' import { ColorModeContext } from '../../Store' export default function MuiFooter() { const { mode } = useContext(ColorModeContext) const theme = useTheme() return ( <Box component="footer" sx={{ bgcolor: theme.palette.background.paper }} // sx={{ mt: 6, bgcolor: theme.palette.background.paper, p:{md:10} }} > <Grid container sx={{ px: { xs: 3, sm: 10, md: 12, lg: 8, xl: 32 }, py: { xs: 3, md: 8 }, mt: { xs: 3, sm: 10, md: 12, lg: 8, xl: 32 } }} // direction="row" // justifyContent="space-between" // alignItems="center" > <Grid item xs={12} sm={12} md={6} lg={6} sx={{ textAlign: { xs: 'center', sm: 'center', md: 'left', lg: 'left', xl: 'left' } }} > <img src={mode === 'light' ? logo : logodark} alt='logo' /> <Typography variant="body1"> {"Copyright © "} <Link to="https://fxcryptospot.com/" style={{ textDecoration: 'none' }}> Forex Crypto Spot </Link>{" "} {new Date().getFullYear()} {"."} </Typography> </Grid> <Grid item xs={12} sm={4} md={2} lg={2} sx={{ textAlign: { xs: 'center', sm: 'center', md: 'left', lg: 'left', xl: 'left' }, px: { xs: 8, sm: 8, md: 0, lg: 0, xl: 0 } }}> <Typography variant="h6" > Quick Links </Typography> <List component="div" disablePadding> <ListItemButton component='a' href='/advertise'> <ListItemText primary="Advertise with us" sx={{ textAlign: { xs: 'center', sm: 'center', md: 'left', lg: 'left', xl: 'left' } }} /> </ListItemButton> <ListItemButton component='a' href='/contact' > <ListItemText primary="Contact us" sx={{ textAlign: { xs: 'center', sm: 'center', md: 'left', lg: 'left', xl: 'left' } }} /> </ListItemButton> <ListItemButton component='a' href='/about'> <ListItemText primary="About us" sx={{ textAlign: { xs: 'center', sm: 'center', md: 'left', lg: 'left', xl: 'left' } }} /> </ListItemButton> </List> </Grid> <Grid item xs={12} sm={4} md={2} lg={2} sx={{ textAlign: { xs: 'center', sm: 'center', md: 'left', lg: 'left', xl: 'left' }, px: { xs: 8, sm: 8, md: 0, lg: 0, xl: 0 } }}> <Typography variant="h6" > Legal Stuff </Typography> <List component="div" disablePadding> <ListItemButton component='a' href='/privacy-policy'> <ListItemText primary="Privacy Policy" sx={{ textAlign: { xs: 'center', sm: 'center', md: 'left', lg: 'left', xl: 'left' } }} /> </ListItemButton> <ListItemButton component='a' href='/privacy-policy'> <ListItemText primary="Terms of use" sx={{ textAlign: { xs: 'center', sm: 'center', md: 'left', lg: 'left', xl: 'left' } }} /> </ListItemButton> <ListItemButton component='a' href='/sitemap'> <ListItemText primary="Sitemap" sx={{ textAlign: { xs: 'center', sm: 'center', md: 'left', lg: 'left', xl: 'left' } }} /> </ListItemButton> </List> </Grid> <Grid item xs={12} sm={4} md={2} lg={2} sx={{ textAlign: { xs: 'center', sm: 'center', md: 'left', lg: 'left', xl: 'left' }, px: { xs: 8, sm: 8, md: 0, lg: 0, xl: 0 } }}> <Typography variant="h6" > Follow Us </Typography> <List component="div" disablePadding > <ListItemButton component='a' href='https://www.facebook.com/' > <ListItemText primary="Facebook" sx={{ textAlign: { xs: 'center', sm: 'center', md: 'left', lg: 'left', xl: 'left' } }} /> </ListItemButton> <ListItemButton component='a' href='https://www.instagram.com/'> <ListItemText primary="Instagram" sx={{ textAlign: { xs: 'center', sm: 'center', md: 'left', lg: 'left', xl: 'left' } }} /> </ListItemButton> <ListItemButton component='a' href='https://www.twitter.com/'> <ListItemText primary="Twitter" sx={{ textAlign: { xs: 'center', sm: 'center', md: 'left', lg: 'left', xl: 'left' } }} /> </ListItemButton> </List> </Grid> </Grid> </Box> ) }
GPT URL: https://chat.openai.com/g/g-acZ1g7xWK-educational-email-course-creator GPT logo: <img src="https://files.oaiusercontent.com/file-UNueF7MjvhUBP1rLwS8766Ib?se=2123-12-22T13%3A27%3A23Z&sp=r&sv=2021-08-06&sr=b&rscc=max-age%3D1209600%2C%20immutable&rscd=attachment%3B%20filename%3DDALL%25C2%25B7E%25202024-01-14%252015.57.44%2520-%2520Create%2520an%2520image%2520of%2520a%2520banner%2520with%2520the%2520word%2520%2527EDUCREATOR%2527.%2520The%2520banner%2520should%2520have%2520a%2520central%2520motif%2520of%2520a%2520lightbulb%2520intertwined%2520with%2520a%2520book%252C%2520symbolizing%2520the.png&sig=RuJRBfgXF088MSyK%2B4xDBGIxaiF3uaGXAYO%2BSgssBoQ%3D" width="100px" /> GPT Title: Educational Email Course Creator GPT Description: Create a complete validated 5-Day Email Course - By Marcus Edwards GPT instructions: ```markdown When asked to create an email course, walk the user through a step by step process. Only ask one question at a time so the user doesn't get overwhelmed. Explain the importance of each step. Step 1: Start with validating the course by asking the 3 validation questions and then proceed to creating the title for the course based on the answer. Once the compelling SEO title is created, create the course outline. Step 2: If the user is happy with the title and outline, proceed with creating each day's email and its contents. Ask the user if they would like to begin creating each email one by one. Each email should be comprehensive and include all relevant content. There should be at least a full page of content. Once all emails have been created, draft a Day 0 email that is an introduction. Step 3: The final step is to create a product marketing plan to promote this email course. Create a 5 week content plan for the social media platform the user prefers. Make sure to use a variety of media formats and optimize the content for each individual platform’s audience preferences. Incorporate effective principles of storytelling throughout the plan. Put the plan in a neatly organized table. Ask the following questions before creating the plan: 1. Which platform are you using? 2. What kind of media do you create (video, articles, short form posts, etc) 3. How many times per week do you want to post? Each week's content should include various forms of media, including opportunities for feedback and relate to the corresponding day in the 5-day course. Each week has it's own labeled table. As an expert email marketer and online course creator, please incorporate the following elements in every email: 1. Effective Email Copy: Utilize storytelling, incorporate relevant statistics, include well-designed graphics, use power words, and empathize to engage your audience effectively. 2. Clear Call to Action (CTA): Your CTA should be visually distinct, prominently placed, clear in its messaging, and persuasive to encourage action. 3. Engaging Subject Line: Develop subject lines that resonate with the recipient's pain points and offer value, increasing the likelihood of the email being opened. 4. Provide Value: Offer content that is educational, inspirational, and informative at no cost, positioning yourself as a valuable resource. 5. Leverage Psychology: Use principles of understanding of subconscious cues, and elements like FOMO to enhance engagement and conversions. Here's a structured approach to guide you through the validation process: Before creating the email course outline, go through these validation steps for the email course by asking the following questions one at a time: 1. Identify the Specific Problem - Question: "Do you know the specific problem your course is addressing? If not, I can help you figure it out. Please just respond NO." - Purpose: This helps to ensure that your course is targeted and relevant. It's important to pinpoint a particular issue or need that your course will solve. If the user says NO, please ask them probing questions one at a time to help them figure out what problem they are solving. Also, recommend that they use perplexity.ai to get more information. 2. Define the Target Audience - Question: Who exactly are you solving this problem for? - Purpose: Understanding your audience is key to creating content that resonates. This involves knowing their demographics, challenges, and what they hope to achieve. 3. Assess Your Unique Positioning - Question: What skills, experience, or perspective do you have that makes you uniquely qualified to offer this course? - Purpose: This is about establishing credibility and trust. Your unique qualifications could be your professional background, personal experiences, or a distinctive teaching approach. Developing a Compelling SEO Title Once you've validated your course idea, the next step is crafting a compelling SEO title. This title should be clear, engaging, and optimized for search engines. It should reflect the problem being solved and resonate with the target audience. Consider using relevant keywords that your audience is likely to search for. Outline Creation After validation and title formulation, you can proceed to outline the course. The outline should be structured in a way that logically progresses from introduction to more complex concepts, always keeping in mind the key elements of effective email marketing. Here is an example: To start building our first email course, let's follow a structured process: Step 1: Course Validation 1. Identifying the Problem - **Question**: What specific problem will this course address? - **Suggestion**: For instance, the course could focus on "Improving Social Media Engagement for Small Businesses". 2. Defining the Target Audience - **Question**: Who is this course specifically for? - **Suggestion**: The target audience might be small business owners or marketing professionals in small to mid-size companies. 3. Assessing Unique Positioning - **Question**: What makes you uniquely qualified to offer this course? - **Suggestion**: Your expertise in digital marketing, with a focus on social media and data analysis, positions you well to teach this course. Step 2: Crafting a Compelling SEO Title - **Suggestion**: "Boost Your Business: Mastering Social Media Engagement in 5 Days" Step 3: Outline Creation Day 1: Understanding Social Media Fundamentals - **Topics**: Overview of social media platforms, determining the right platforms for your business, setting up profiles. Day 2: Content Creation and Brand Voice - **Topics**: Developing a content strategy, creating a consistent brand voice, types of content that drive engagement. Day 3: Engagement Tactics and Community Building - **Topics**: Techniques to increase engagement, building a community, responding to comments and messages. Day 4: Analytics and Data-Driven Decisions - **Topics**: Using analytics tools to track performance, understanding metrics, making data-driven decisions. Day 5: Paid Advertising and Scaling Up - **Topics**: Introduction to paid advertising, best practices for sponsored content, strategies for scaling up your social media presence. Step 4: Developing Course Content Each day's content should include effective email copy, a clear CTA, personalized elements, an engaging subject line, and be optimized for mobile. Regular testing and maintenance of the course should be conducted to ensure its relevance and effectiveness. This structure covers the essentials of building a comprehensive email course, targeting the right audience, and positioning it effectively in the market. Remember, each element of the course should aim to solve the identified problem and cater to the specific needs of your target audience. Please do not stop until all 6 emails, including Day 0 introduction email, and the product marketing plan in table format have been created. Once Day 0 is done, please automatically create the product marketing plan asking the appropriate questions. ```
export default class GameHandler { constructor(app) { /** @type {'READY' | 'PLAYING' | 'FINISHED'} */ this._status = 'READY'; this.init(); this.app = app; } get status() { return this._status; } set status(value) { this._status = value; switch (value) { case 'READY': this.showReadyScreen(); break; case 'FINISHED': this.showFinishScreen(); break; } } init() { this.readyScreen = document.querySelector('.ready-screen'); this.titleImage = this.readyScreen.querySelector('#title-img'); this.playBtn = this.readyScreen.querySelector('#play-img'); this.playBtn.addEventListener('click', () => { this.hideReadyScreen(); }); this.finishiScreen = document.querySelector('.finish-screen'); this.distanceText = this.finishiScreen.querySelector('.distance'); this.coinText = this.finishiScreen.querySelector('.coin'); this.replayBtn = this.finishiScreen.querySelector('#replay-img'); this.replayBtn.addEventListener('click', () => { this.hideFinishScreen(); }); this.status = 'READY'; } showReadyScreen() { gsap.to(this.titleImage, { scale: 1, rotation: 720, opacity: 1, duration: 0.5, }); gsap.to(this.playBtn, { scale: 1, duration: 1, ease: Elastic.easeOut.config(2, 0.5), delay: 0.5, }); } hideReadyScreen() { gsap.to(this.readyScreen, { opacity: 0, duration: 0.3, pointerEvents: 'none', onComplete: () => { this.status = 'PLAYING'; }, }); } showFinishScreen() { this.distanceText.innerText = Math.floor(this.app.score.distCount) + 'm'; this.coinText.innerText = Math.floor(this.app.score.coinCount) + ' coin'; gsap.fromTo( this.finishiScreen, { opacity: 0, }, { opacity: 1, duration: 0.5, pointerEvents: 'all', } ); gsap.fromTo( this.distanceText, { opacity: 0, scale: 0 }, { opacity: 1, scale: 1, duration: 0.5, delay: 1, } ); gsap.fromTo( this.coinText, { opacity: 0, scale: 0 }, { opacity: 1, scale: 1, duration: 0.5, delay: 1.1, } ); gsap.fromTo( this.replayBtn, { opacity: 0, scale: 0 }, { opacity: 1, scale: 1, rotation: 720, duration: 0.5, delay: 1.3, } ); } hideFinishScreen() { gsap.fromTo(this.finishiScreen, {opacity: 1}, { opacity: 0, pointerEvents: 'none', duration: 0.1, }) this.status = 'PLAYING'; this.app.reset(); } }
//Make sure your IDE has org.json library installed import org.json.JSONArray; import org.json.JSONObject; import javax.swing.*; import java.awt.*; import java.io.*; import java.nio.file.FileSystems; import java.util.Scanner; public class JsonStringParser { public static void main(String[] args) { try { // Specify the input file path String inputFile = "null"; JFileChooser chooser = new JFileChooser(); int status = chooser.showOpenDialog(null); if (status == JFileChooser.APPROVE_OPTION) { File file = chooser.getSelectedFile(); if (file == null) { return; } inputFile = chooser.getSelectedFile().getAbsolutePath(); } // Create new txt file for output and save to desktop String fileSeparator = FileSystems.getDefault().getSeparator(); String userHomeFolder = System.getProperty("user.home") + fileSeparator + "Desktop"; File textFile = new File(userHomeFolder, "EntropyOutput.txt"); System.out.println("Starting program..."); // Create a BufferedReader to read the input text file BufferedReader br = new BufferedReader(new FileReader(inputFile)); // Create a FileWriter to write to the output text file FileWriter fw = new FileWriter(textFile); // Turn each line within input file into JSON object String line; while ((line = br.readLine()) != null) { // Parse the JSON string JSONObject jsonObject = new JSONObject(line); // Initialize variables String keywords = "not found"; double clickEntropy = 0.0; String pageType = "null"; // Create JSON array JSONArray queryInfoArray = jsonObject.getJSONArray("queryInfo"); // Get keywords from first element json array keywords = queryInfoArray.getJSONObject(0) .getJSONObject("meta") .getString("keywords"); // Check if each element in json array has a click-entropy score, and return it if so for(int i = 0; i < queryInfoArray.length(); i++){ JSONObject obj = queryInfoArray.getJSONObject(i); if(obj.has("type") && obj.get("type").toString().equals("query-specificity")){ if(obj.getJSONObject("meta").has("click-entropy")){ clickEntropy = obj.getJSONObject("meta") .getDouble("click-entropy"); } } } if(clickEntropy <= 2){ pageType = "Detail"; } else { pageType = "Search"; } // Write the extracted values to the output text file fw.write("Keyword: " + keywords + ", Score: " + clickEntropy + ", Page Type: " + pageType + "\n"); } // Close the input and output files br.close(); fw.close(); System.out.println("Extraction and writing completed successfully."); Desktop desktop = Desktop.getDesktop(); if(textFile.exists()) desktop.open(textFile); } catch (FileNotFoundException e) { throw new RuntimeException(e); } catch (IOException e) { throw new RuntimeException(e); } catch (Exception e) { e.printStackTrace(); } } }
#include <iostream> #include <map> // БОР /** В первой строке ввода число запросов q В следующих q строках вводится запросы вида: + word - добавить слово word в бор ? i - вывести i-ое слово из лексикографического порядка бора */ struct Node { int count = 0; std::map<char, Node*> children; int children_count = 0; }; struct Trie { Node root = Node{}; std::string find_k_element(int k, Node* current_node, std::string s = "") { if (current_node->count >= k) { return s; } k -= current_node->count; for (char i = 'a'; i < 'a' + 26; i++) { if (current_node->children.find(i) != current_node->children.end() && current_node->children[i]->children_count >= k) { return find_k_element(k, current_node->children[i], s + i); } else if (current_node->children.find(i) != current_node->children.end()) { k -= current_node->children[i]->children_count; } } return ""; } void insert(const std::string& s, Node* current_node, int ind = 0) { if (ind >= s.size()) { current_node->count++; current_node->children_count++; return; } if (current_node->children.find(s[ind]) == current_node->children.end()) { current_node->children[s[ind]] = new Node{}; } insert(s, current_node->children[s[ind]], ind + 1); current_node->children_count++; } }; int main() { int q; std::cin >> q; auto t = Trie(); for (int i = 0; i < q; i++) { std::string s; char oper; std::cin >> oper >> s; if (oper == '?') { int j = stoi(s); std::cout << t.find_k_element(j, &t.root) << '\n'; } else if (oper == '+') { if (s.empty()) { continue; } t.insert(s, &t.root); } } }
import React from "react"; import { connect } from "react-redux"; import { IState, IWavelengthData } from "../store/store"; interface IAdminPanelProps { socket?: SocketIOClient.Socket; wavelengthData: IWavelengthData; teams: string[]; } const AdminPanelUnconnected = ({ socket, wavelengthData, teams, }: IAdminPanelProps) => { const [leftPromptInput, setLeftPromptInput] = React.useState( wavelengthData.prompt.left ); const [rightPromptInput, setRightPromptInput] = React.useState( wavelengthData.prompt.right ); return ( <> <div className="d-flex w-100 justify-content-center mb-2"> <button onClick={() => { socket.emit("setCovered", !wavelengthData.covered); }} > Show/Hide </button> <button onClick={() => { const newTarget = Math.random() * 156 - 77; socket.emit("setTargetRange", newTarget); }} > Randomize </button> </div> <div className="d-flex w-100 justify-content-center mb-2"> <input type="text" placeholder="Question" className="mr-2" value={leftPromptInput} onChange={(e) => { setLeftPromptInput(e.target.value); }} ></input> <input type="text" placeholder="Question" className="mr-2" value={rightPromptInput} onChange={(e) => { setRightPromptInput(e.target.value); }} ></input> <button onClick={() => { socket.emit("setPrompt", { left: leftPromptInput, right: rightPromptInput, }); }} > Set Prompts </button> </div> <div className="d-flex w-100 justify-content-center mb-2"> <button onClick={() => { socket.emit("setActiveTeam", "admin"); }} > Admin Control </button> </div> {teams.map((team) => { const teamData = wavelengthData.teams[team]; if (teamData) { return ( <div className="d-flex w-100 justify-content-center mb-2"> <button className="mr-4" onClick={() => { socket.emit("setActiveTeam", team); }} > Activate {teamData.name} </button> <button onClick={() => { socket.emit("setTeamScore", team, teamData.score - 1); }} > ⌄ </button> <div className="mx-2 large">{teamData.score}</div> <button className="mr-4" onClick={() => { socket.emit("setTeamScore", team, teamData.score + 1); }} > ⌃ </button> <button className="mr-4" onClick={() => { socket.emit("setShowTeam", team, !teamData.shown); }} > {teamData.shown ? "Hide" : "Show"} </button> <button onClick={() => { socket.emit("setTeamPosition", team, "left"); }} > {"<--"} </button> <button className="mr-4" onClick={() => { socket.emit("setTeamPosition", team, "right"); }} > {"-->"} </button> </div> ); } return <div>Missing Team?</div>; })} </> ); }; const mapStateToProps = (state: IState) => ({ socket: state.socket, wavelengthData: state.wavelengthData, }); export const AdminPanel = connect(mapStateToProps)(AdminPanelUnconnected);
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" tools:context="com.example.android.moviebuzzapp.Details" android:orientation="vertical"> <!-- TODO: Update blank fragment layout --> <TextView android:layout_width="match_parent" android:layout_height="wrap_content" android:text="Movie Title" android:id="@+id/titleView" android:layout_gravity="start|center_vertical" android:height="100dp" android:background="#26A69A" android:textColor="#ffffff" android:textStyle="bold" android:textSize="30dp" android:gravity="center_vertical" android:paddingLeft="20dp"></TextView> <ScrollView android:layout_width="match_parent" android:layout_height="match_parent" android:layout_below="@id/titleView" android:layout_margin="15dp" android:id="@+id/scrollView"> <LinearLayout android:orientation="vertical" android:layout_width="match_parent" android:layout_height="match_parent"> <LinearLayout android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="horizontal" android:minHeight="250dp"> <LinearLayout android:orientation="vertical" android:layout_width="0dp" android:layout_height="match_parent" android:layout_weight="1"> <ImageView android:layout_width="match_parent" android:layout_height="match_parent" android:id="@+id/imageView" android:scaleType="centerCrop" android:padding="20dp" /> </LinearLayout> <LinearLayout android:orientation="vertical" android:layout_width="0dp" android:layout_height="match_parent" android:layout_weight="1"> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="2015" android:id="@+id/year" android:layout_gravity="center_horizontal" android:textSize="25dp" android:layout_margin="20dp" /> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="120 min" android:id="@+id/duration" android:layout_gravity="center_horizontal" android:textStyle="italic" android:textSize="20dp" android:layout_marginLeft="20dp" android:layout_marginRight="20dp" android:layout_marginBottom="20dp" /> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="8.1/10" android:id="@+id/rating" android:layout_gravity="center_horizontal" android:textSize="20dp" android:layout_marginLeft="10dp" android:layout_marginRight="10dp" android:layout_marginBottom="10dp" /> <Button android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Mark As Favourite" android:id="@+id/favoriteButton" android:layout_gravity="center_horizontal" android:layout_marginLeft="10dp" android:layout_marginRight="10dp" android:layout_marginBottom="10dp" android:layout_marginTop="10dp" /> </LinearLayout> </LinearLayout> <LinearLayout android:orientation="horizontal" android:layout_width="match_parent" android:layout_height="match_parent"> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="New Text" android:id="@+id/overview" android:textColor="#000000" android:textSize="15sp" /> </LinearLayout> <View android:layout_width="match_parent" android:layout_height="1dp" android:background="#424242" android:layout_marginTop="15dp"> </View> <RelativeLayout android:layout_width="match_parent" android:layout_height="wrap_content" android:id="@+id/videoLayout"> <ImageButton android:layout_width="wrap_content" android:layout_height="wrap_content" android:id="@+id/videoButton" android:layout_marginBottom="85dp" android:src="@drawable/play" android:layout_marginTop="10dp" android:focusable="false"/> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Play Trailer" android:id="@+id/videoName" android:layout_alignBottom="@+id/videoButton" android:layout_toEndOf="@+id/videoButton" android:layout_alignParentTop="true" android:gravity="center_vertical" android:textSize="35dp" android:textStyle="bold" android:paddingLeft="25dp" android:paddingRight="25dp" android:focusable="false"/> </RelativeLayout> </LinearLayout> </ScrollView> </RelativeLayout>
<?php namespace App\Livewire\Panel\Support; use App\Jobs\SendCloseTicketSupportJob; use App\Jobs\SendOpenTicketSupportJob; use App\Mail\Support\ClosedTicket; use App\Models\SupportTicket; use App\Models\SupportTicketComment; use Illuminate\Support\Facades\Mail; use Livewire\Component; class LoadTicketComments extends Component { public $ticketData; public $ticketID; public $msg; public $loadData; public function mount() { $this->loadData = SupportTicketComment::where(['ticket_id' => $this->ticketID])->get(); $this->ticketData = SupportTicket::where(['ticket_id' => $this->ticketID])->first(); } public function sendComment() { if ($this->msg == null){ return; } SupportTicketComment::create([ 'ticket_id' => $this->ticketID, 'sender' => 0, 'msg' => $this->msg, ]); $this->reset('msg'); $this->mount(); } public function continue_communication() { SupportTicket::where('ticket_id', $this->ticketID)->update([ 'ticket_status' => 0 ]); $this->mount(); } public function closeTicket() { SupportTicket::where('ticket_id', $this->ticketID)->update([ 'ticket_status' => 3 ]); $url = route('support.tickets.viewticket', $this->ticketID); $this->mount(); dispatch(new SendCloseTicketSupportJob(auth()->user()->email, $this->ticketID, $url)); } public function render() { return view('livewire.panel.support.load-ticket-comments'); } }
/* * Copyright (C) 2014 Cristian Sulea ( http://cristian.sulea.net ) * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package jatoo.ftp; import java.io.File; import java.io.InputStream; import java.io.OutputStream; /** * This class provides a skeletal implementation of the {@link FTPClient} * interface. * * @author <a href="http://cristian.sulea.net" rel="author">Cristian Sulea</a> * @version 1.2, July 25, 2014 */ public abstract class AbstractFTPClient implements FTPClient { @Override public final void connect(final String host, final int port, final String username, final String password) throws FTPClientException { if (isConnected()) { disconnect(); } connectImpl(host, port, username, password); } protected abstract void connectImpl(String host, int port, String username, String password) throws FTPClientException; @Override public final void connect(final FTPClientConnectionInfoProvider connectionInfoProvider) throws FTPClientException { final FTPClientConnectionInfo connectionInfo = connectionInfoProvider.getConnectionInfo(); connect(connectionInfo.getHost(), connectionInfo.getPort(), connectionInfo.getUsername(), connectionInfo.getPassword()); } @Override public final void upload(final File srcFile, final String dstFile) throws FTPClientException { upload(srcFile.getAbsolutePath(), dstFile, MODE.OVERWRITE); } @Override public final void upload(final File srcFile, final String dstFile, final MODE mode) throws FTPClientException { upload(srcFile.getAbsolutePath(), dstFile, mode); } @Override public final void upload(final String srcFile, final String dstFile) throws FTPClientException { upload(srcFile, dstFile, MODE.OVERWRITE); } @Override public final void upload(final InputStream srcStream, final String dstFile) throws FTPClientException { upload(srcStream, dstFile, MODE.OVERWRITE); } @Override public final void download(final String srcFile, final File dstFile) throws FTPClientException { download(srcFile, dstFile.getAbsolutePath(), MODE.OVERWRITE); } @Override public final void download(final String srcFile, final File dstFile, final MODE mode) throws FTPClientException { download(srcFile, dstFile.getAbsolutePath(), mode); } @Override public final void download(final String srcFile, final String dstFile) throws FTPClientException { download(srcFile, dstFile, MODE.OVERWRITE); } @Override public final void download(final String srcFile, final OutputStream dstStream) throws FTPClientException { download(srcFile, dstStream, MODE.OVERWRITE); } }
**Snakes and Ladders** === _Problem:_ --- Your task is to make a simple class called SnakesLadders. The test cases will call the method play(die1, die2) independantly of the state of the game or the player turn. The variables die1 and die2 are the die thrown in a turn and are both integers between 1 and 6. The player will move the sum of die1 and die2. inputs: integers (sum of two dice with values 1-6) outputs: integer (the space on the board that the player has landed) - string ( the player has landed on a snake and fallen back to space x) - string (the player has laned on a ladder and has moved ahead to space y) **Returns:** - Return Player n Wins!. Where n is winning player that has landed on square 100 without any remainding moves left. - Return Game over! if a player has won and another player tries to play. - Otherwise return Player n is on square x. Where n is the current player and x is the sqaure they are currently on. Rules of the Game: 1. There are two players and both start off the board on square 0. 2. Player 1 starts and alternates with player 2. 3. You follow the numbers up the board in order 1=>100 4. If the value of both die are the same then that player will have another go. 5. Climb up ladders. The ladders on the game board allow you to move upwards and get ahead faster. If you land exactly on a square that shows an image of the bottom of a ladder, then you may move the player all the way up to the square at the top of the ladder. (even if you roll a double). 6. Slide down snakes. Snakes move you back on the board because you have to slide down them. If you land exactly at the top of a snake, slide move the player all the way to the square at the bottom of the snake or chute. (even if you roll a double). 7. Land exactly on the last square to win. The first person to reach the highest square on the board wins. But there's a twist! If you roll too high, your player "bounces" off the last square and moves back. You can only win by rolling the exact number needed to land on the last square. For example, if you are on square 98 and roll a five, move your game piece to 100 (two moves), then "bounce" back to 99, 98, 97 (three, four then five moves.) **Methods Needed** --- Player turns Board Initialization Player Rolls Again Climbs Ladder Snake Slide Winner Game Over Play Again? Board Initialization: - Array of integers 0..100 or - MAX = 100 - this way you can just add your die totals, and if your total equals 100 exactly, then you win. Player Turns: - PLAYER_SQUARE = sum total of dice - move to square x - if Ladder or snake include square x - move accordingly - if dice1 == dice2 - roll again NEXT PLAYERS TURN Climbs Ladder: - Hash of key value pairs - keys will reference the bottom of the ladders - values will represent the tops of ladders - if the hash inlcudes a key that matches the integer that the player has landed on, then the PLAYER_SQUARE will now equal the value that key referenced Snake Slides: - Same idea as ladder Winner: - If PLAYER SQUARE == MAX - then player wins - GAME OVER - PLAY AGAIN?
package org.singledog.dogmall.ums.controller; import java.util.List; import io.swagger.annotations.Api; import io.swagger.annotations.ApiOperation; import org.singledog.dogmall.core.request.PageRequest; import org.singledog.dogmall.core.response.Response; import org.singledog.dogmall.core.response.ResponseFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RestController; import org.singledog.dogmall.ums.entity.UserLevelEntity; import org.singledog.dogmall.ums.service.UserLevelService; /** * 会员等级表 * * @author ZheMing Liu * @email dogmall@qq.com * @date 2022-05-03 23:52:33 */ @Api(tags = "会员等级表 管理") @RestController @RequestMapping("ums/userlevel") public class UserLevelController { @Autowired private UserLevelService userLevelService; /** * 列表 */ @GetMapping @ApiOperation("分页查询") public Response<List<UserLevelEntity>> queryUserLevelByPage(PageRequest request) { return userLevelService.queryPage(request); } /** * 信息 */ @GetMapping("{id}") @ApiOperation("详情查询") public Response<UserLevelEntity> queryUserLevelById(@PathVariable("id") Long id) { UserLevelEntity entity = userLevelService.getById(id); return ResponseFactory.getSuccessResponse(entity); } /** * 保存 */ @PostMapping @ApiOperation("保存") public Response save(@RequestBody UserLevelEntity userLevel) { userLevelService.save(userLevel); return ResponseFactory.getSuccessResponse(); } /** * 修改 */ @PostMapping("/update") @ApiOperation("修改") public Response update(@RequestBody UserLevelEntity userLevel) { userLevelService.updateById(userLevel); return ResponseFactory.getSuccessResponse(); } /** * 删除 */ @PostMapping("/delete") @ApiOperation("删除") public Response delete(@RequestBody List<Long> ids) { userLevelService.removeByIds(ids); return ResponseFactory.getSuccessResponse(); } }
<template> <ValidationObserver ref="form" v-slot="{ handleSubmit, reset }"> <b-overlay :show="loading"> <b-form @submit.prevent="handleSubmit(saveUpdate)" @reset.prevent="reset" autocomplete="off" enctype="multipart/form-data"> <b-row> <b-col md="12" sm="12"> <b-row> <b-col xl="6" lg="6" sm="12"> <ValidationProvider name="Area Type" vid="area_type_id" rules="required|min_value:1"> <b-form-group class="row" label-cols-sm="5" label-for="area_type_id " slot-scope="{ valid, errors }" > <template v-slot:label> {{$t('orgProfile.area_type')}} <span class="text-danger">*</span> </template> <b-form-select plain v-model="form.area_type_id" id="area_type_id" :options="getAreaTypeList" :state="errors[0] ? false : (valid ? true : null)" > <template v-slot:first> <b-form-select-option :value="0">{{$t('globalTrans.select')}}</b-form-select-option> </template> </b-form-select> <div class="invalid-feedback"> {{ errors[0] }} </div> </b-form-group> </ValidationProvider> </b-col> <b-col xl="6" lg="6" sm="12" v-if="ItemShow"> <ValidationProvider name="Division" vid="division_id" rules="required|min_value:1"> <b-form-group class="row" label-cols-sm="5" label-for="division_id" slot-scope="{ valid, errors }" > <template v-slot:label> {{ $t('orgProfile.division')}} <span class="text-danger">*</span> </template> <b-form-select plain v-model="form.division_id" :options="divisionList" id="division_id" :state="errors[0] ? false : (valid ? true : null)" > <template v-slot:first> <b-form-select-option :value="0">{{$t('globalTrans.select')}}</b-form-select-option> </template> </b-form-select> <div class="invalid-feedback"> {{ errors[0] }} </div> </b-form-group> </ValidationProvider> </b-col> <b-col xl="6" lg="6" sm="12" v-if="ItemShow"> <ValidationProvider name="District" vid="district_id" rules="required|min_value:1"> <b-form-group class="row" label-cols-sm="5" label-for="district_id" slot-scope="{ valid, errors }" > <template v-slot:label> {{ $t('orgProfile.district')}} <span class="text-danger">*</span> </template> <b-form-select plain v-model="form.district_id" :options="districtList" id="district_id" :state="errors[0] ? false : (valid ? true : null)" > <template v-slot:first> <b-form-select-option :value="0">{{$t('globalTrans.select')}}</b-form-select-option> </template> </b-form-select> <div class="invalid-feedback"> {{ errors[0] }} </div> </b-form-group> </ValidationProvider> </b-col> <b-col xl="6" lg="6" sm="12" v-if="PauroshobaItemShow || UnionItemShow"> <ValidationProvider name="Upazila" vid="upazilla_id" rules="required|min_value:1"> <b-form-group class="row" label-cols-sm="5" label-for="upazilla_id" slot-scope="{ valid, errors }" > <template v-slot:label> {{ $t('orgProfile.upazila')}} <span class="text-danger">*</span> </template> <b-form-select plain v-model="form.upazilla_id" :options="upazilaList" id="upazilla_id" :state="errors[0] ? false : (valid ? true : null)" > <template v-slot:first> <b-form-select-option :value="0">{{$t('globalTrans.select')}}</b-form-select-option> </template> </b-form-select> <div class="invalid-feedback"> {{ errors[0] }} </div> </b-form-group> </ValidationProvider> </b-col> <b-col xl="6" lg="6" sm="12" v-if="CityCorpItemShow"> <ValidationProvider name="City Corporation" vid="city_corporation_id" rules="required|min_value:1"> <b-form-group class="row" label-cols-sm="5" label-for="city_corporation_id" slot-scope="{ valid, errors }" > <template v-slot:label> {{ $t('orgProfile.city_corporation') }} <span class="text-danger">*</span> </template> <b-form-select plain v-model="form.city_corporation_id" :options="cityCorporationList" id="city_corporation_id" :state="errors[0] ? false : (valid ? true : null)" > <template v-slot:first> <b-form-select-option :value="0">{{$t('globalTrans.select')}}</b-form-select-option> </template> </b-form-select> <div class="invalid-feedback"> {{ errors[0] }} </div> </b-form-group> </ValidationProvider> </b-col> <b-col xl="12" lg="12" sm="12"> <p> {{ $t('tcbconfiguration.excel_downolad_msg') }} </p> <a target="_blank" class="btn btn-primary mr-2" :href="licenseRegistrationServiceBaseUrl+'download-attachment?file=storage/beneficiary/beneficiary-excel-format/tcb_beneficiary_info_format.xlsx'"><i class="ri-file-download-line"></i>&nbsp;{{$t('globalTrans.download')}}</a> </b-col> <b-col xs="6" sm="12" md="6" lg="6" xl="6" class="mt-3"> <ValidationProvider name="Beneficiary Attachment" vid="excel_file" rules="required"> <b-form-group label-for="excel_file" label-cols-sm="5" slot-scope="{ valid, errors }" > <template v-slot:label> {{ $t('tcbconfiguration.beneficiary_attachment') }}<span class="text-danger">*</span> </template> <b-form-file id="excel_file" v-model="form.excel_file" v-on:change="onFileChange" accept=".xlsx" class="mt-2" plain :state="errors[0] ? false : (valid ? true : null)" ></b-form-file> <div class="invalid-feedback"> {{ errors[0] }} </div> </b-form-group> </ValidationProvider> </b-col> </b-row> </b-col> </b-row> <b-row class="text-right"> <b-col> <b-button type="submit" variant="success" class="mr-2 btn-sm">{{ saveBtnName }}</b-button> <b-button variant="danger" class="btn-sm" @click="$bvModal.hide('modal-form')">{{ $t('globalTrans.cancel') }}</b-button> </b-col> </b-row> </b-form> </b-overlay> </ValidationObserver> </template> <script> import RestApi, { licenseRegistrationServiceBaseUrl } from '@/config/api_config' import { beneficiartInformationExcelUpload } from '../../../api/routes' export default { name: 'Form', props: ['id'], data () { return { valid: null, licenseRegistrationServiceBaseUrl: licenseRegistrationServiceBaseUrl, saveBtnName: this.id ? this.$t('globalTrans.update') : this.$t('globalTrans.save'), errors: [], form: { area_type_id: 0, district_id: 0, division_id: 0, upazilla_id: 0, city_corporation_id: 0, excel_file: [], attachment: '' }, districtList: [], upazilaList: [], cityCorporationList: [], ItemShow: false, CityCorpItemShow: false, PauroshobaItemShow: false, UnionItemShow: false, UnionItemPerShow: false } }, created () { if (this.id) { const tmp = this.getItemEntry() this.form = tmp } }, computed: { loading: function () { return this.$store.state.commonObj.loading }, getAreaTypeList: function () { const objectData = this.$store.state.commonObj.typeList return objectData.map((obj, key) => { if (this.$i18n.locale === 'bn') { return { value: obj.id, text: obj.name_bn } } else { return { value: obj.id, text: obj.name } } }) }, divisionList: function () { return this.$store.state.CommonService.commonObj.divisionList.filter(item => item.status === 1) } }, watch: { 'form.area_type_id': function (n, o) { if (o !== n) { this.getAreaTypeData(n) } }, 'form.division_id': function (newVal, oldVal) { this.districtList = this.getDistrictList(newVal) }, 'form.district_id': function (newVal, oldVal) { this.cityCorporationList = this.getCityCorporationList(newVal) this.upazilaList = this.getUpazillaList(newVal) } }, methods: { onFileChange (e) { this.form.attachment = e.target.files[0] }, getAreaTypeData (typeId) { if (typeId) { this.ItemShow = true if (typeId === 1) { this.CityCorpItemShow = true this.PauroshobaItemShow = false this.UnionItemShow = false } else if (typeId === 2) { this.CityCorpItemShow = false this.PauroshobaItemShow = true this.UnionItemShow = false } else if (typeId === 3) { this.CityCorpItemShow = false this.PauroshobaItemShow = false this.UnionItemShow = true } } }, async saveUpdate () { this.$store.dispatch('mutateCommonProperties', { loading: true }) let result = null const loadingState = { loading: false, listReload: false } var formData = new FormData() Object.keys(this.form).map(key => { formData.append(key, this.form[key]) }) formData.append('excel_file', this.form.attachment) result = await RestApi.postData(licenseRegistrationServiceBaseUrl, beneficiartInformationExcelUpload, formData) loadingState.listReload = true this.$store.dispatch('mutateCommonProperties', loadingState) if (result === undefined) { this.$toast.success({ title: 'Error', message: this.$t('tcbconfiguration.excel_error'), color: '#FF0000' }) } if (result.success) { this.$store.dispatch('LicenseRegistrationService/mutateCommonObj', { hasDropdownLoaded: false }) this.$toast.success({ title: this.$t('globalTrans.success'), message: this.id ? this.$t('globalTrans.update_msg') : this.$t('globalTrans.save_msg'), color: '#D6E09B' }) this.$bvModal.hide('modal-form') } else { this.$refs.form.setErrors(result.errors) } }, getItemEntry () { const tmpData = this.$store.state.list.find(item => item.id === this.id) return JSON.parse(JSON.stringify(tmpData)) }, getDistrictList (divisionId) { return this.$store.state.CommonService.commonObj.districtList.filter(item => item.status === 1 && item.division_id === divisionId) }, getUpazillaList (districtId) { return this.$store.state.CommonService.commonObj.upazilaList.filter(item => item.status === 1 && item.district_id === districtId) }, getCityCorporationList (districtId) { const objectData = this.$store.state.CommonService.commonObj.cityCorporationList.filter(item => item.status === 1 && item.district_id === districtId) return objectData.map((obj, key) => { if (this.$i18n.locale === 'bn') { return { value: obj.value, text: obj.text_bn } } else { return { value: obj.value, text: obj.text_en } } }) } } } </script>
package pl.vistersky.vvvpetclinic.controllers; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.servlet.ModelAndView; import pl.vistersky.vvvpetclinic.services.OwnerService; @RequestMapping("/owners") @Controller public class OwnerController { private final OwnerService ownerService; public OwnerController(OwnerService ownerService) { this.ownerService = ownerService; } @RequestMapping({"","/","index","/index.html"}) public String listOwners(Model model){ model.addAttribute("owners",ownerService.findAll()); return "owners/index"; } @RequestMapping("/find") public String findOwners(){ return "notImpl"; } @GetMapping("/{ownerId}") public ModelAndView showOwner(@PathVariable("ownerId") Long ownerId) { ModelAndView mav = new ModelAndView("owners/ownerDetails"); mav.addObject(ownerService.findById(ownerId)); return mav; } }
import { json, type LinksFunction, type LoaderArgs } from '@shopify/remix-oxygen' import { useLoaderData } from '@remix-run/react' import { Image } from '@shopify/hydrogen' import { Blog } from '@shopify/hydrogen/storefront-api-types' import invariant from 'tiny-invariant' import { PageHeader, Section } from '~/components' import { ATTR_LOADING_EAGER } from '~/lib/const' import { seoPayload } from '~/lib/seo.server' import styles from '../../../styles/custom-font.css' import { routeHeaders, CACHE_LONG } from '~/data/cache' const BLOG_HANDLE = 'journal' export const headers = routeHeaders export const links: LinksFunction = () => { return [{ rel: 'stylesheet', href: styles }] } export async function loader({ request, params, context }: LoaderArgs) { const { language, country } = context.storefront.i18n invariant(params.journalHandle, 'Missing journal handle') const { blog } = await context.storefront.query<{ blog: Blog }>(ARTICLE_QUERY, { variables: { blogHandle: BLOG_HANDLE, articleHandle: params.journalHandle, language } }) if (!blog?.articleByHandle) { throw new Response(null, { status: 404 }) } const article = blog.articleByHandle const formattedDate = new Intl.DateTimeFormat(`${language}-${country}`, { year: 'numeric', month: 'long', day: 'numeric' }).format(new Date(article?.publishedAt!)) const seo = seoPayload.article({ article, url: request.url }) return json( { article, formattedDate, seo }, { headers: { 'Cache-Control': CACHE_LONG } } ) } export default function Article() { const { article, formattedDate } = useLoaderData<typeof loader>() const { title, image, contentHtml, author } = article return ( <> <PageHeader heading={title} variant="blogPost"> <span> {formattedDate} &middot; {author.name} </span> </PageHeader> <Section as="article" padding="x"> {image && ( <Image data={image} className="w-full mx-auto mt-8 md:mt-16 max-w-7xl" sizes="90vw" widths={[400, 800, 1200]} width="100px" loading={ATTR_LOADING_EAGER} loaderOptions={{ scale: 2, crop: 'center' }} /> )} <div dangerouslySetInnerHTML={{ __html: contentHtml }} className="article" /> </Section> </> ) } const ARTICLE_QUERY = `#graphql query ArticleDetails( $language: LanguageCode $blogHandle: String! $articleHandle: String! ) @inContext(language: $language) { blog(handle: $blogHandle) { articleByHandle(handle: $articleHandle) { title contentHtml publishedAt author: authorV2 { name } image { id altText url width height } seo { description title } } } } `
package com.example.fitnessapp.presentation import android.app.AlertDialog import com.example.fitnessapp.presentation.viewModels.ProfileViewModel import android.os.Bundle import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.Toast import androidx.fragment.app.Fragment import androidx.lifecycle.ViewModelProvider import com.example.fitnessapp.databinding.FragmentProfilePageBinding import com.example.fitnessapp.domain.User class ProfilePageFragment : Fragment() { private var _binding: FragmentProfilePageBinding? = null private val binding: FragmentProfilePageBinding get() = _binding ?: throw RuntimeException("FragmentProfilePageBinding = null") private lateinit var viewModel: ProfileViewModel override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View { _binding = FragmentProfilePageBinding.inflate(inflater, container, false) return binding.root } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) viewModel = ViewModelProvider(this)[ProfileViewModel::class.java] observeViewModel() binding.btnLogOut.setOnClickListener { val builder = AlertDialog.Builder(requireContext()) builder.setMessage("Вы уверены?") .setCancelable(false) .setPositiveButton("Да") { dialog, id -> viewModel.logout() } .setNegativeButton("Нет") { dialog, id -> dialog.dismiss() } val alert = builder.create() alert.show() } binding.cvProfile.setOnClickListener { val editProfileFragment = EditProfileFragment.newInstance() activity?.supportFragmentManager?.beginTransaction() ?.setCustomAnimations( android.R.anim.slide_in_left, android.R.anim.slide_out_right, android.R.anim.slide_in_left, android.R.anim.slide_out_right ) ?.add(android.R.id.content, editProfileFragment) ?.addToBackStack(null) ?.commit() } } private fun observeViewModel() { viewModel.user.observe(viewLifecycleOwner) { if (it == null) { launchLoginPageFragment() } else { updateUIWithUserData(it) } } viewModel.error.observe(viewLifecycleOwner) { errorMessage -> errorMessage?.let { Toast.makeText(context, it, Toast.LENGTH_SHORT).show() } } } private fun updateUIWithUserData(user: User) { binding.tvUserName.text = String.format("${user.name} ${user.lastName}") binding.tvUserCourse.text = user.level } private fun launchLoginPageFragment() { val newFragment = LoginPageFragment.newInstance() (activity as? MainActivity)?.loadFragment(newFragment) } override fun onDestroyView() { super.onDestroyView() _binding = null } companion object { fun newInstance(): ProfilePageFragment { return ProfilePageFragment() } } }
from random import choice import requests def fetch_fact(): api_url = 'https://api.api-ninjas.com/v1/facts' response = requests.get(api_url, headers={'X-Api-Key': 'OunaPrs6VTPlzAPwYtqOzQ==GK2iGERCC61alMh6'}) if response.status_code == 200: data = response.json() if data: return data[0]['fact'] else: return "No facts were found." else: return f"Error: unable to fetch a fact. Status code {response.status_code}" def fetch_weather(city_name): api_key = 'c4zmWjxrILFRN50mkGeSIQ71MPJhJjuq' url = f'https://api.tomorrow.io/v4/weather/forecast?location={city_name}&apikey={api_key}' response = requests.get(url) if response.status_code == 200: data = response.json() info = data["timelines"]['hourly'][0] temp = info['values']['temperature'] uv = info['values']['uvIndex'] return f"{city_name} has a temperature of {temp} degrees Celsius and a UV index of {uv}." else: return f'Error: unable to get weather forecast. Status code {response.status_code}' def fetch_quote(): url = 'https://zenquotes.io/api/random' response = requests.get(url) if response.status_code == 200: data = response.json() json = data[0] quote = json['q'] author = json['a'] return f"{quote} - {author}" else: return f'Error: unable to get inspirational quote. Status code {response.status_code}' def get_response(user_input: str) -> str: lowered: str = user_input.lower() split_params = lowered.split() if lowered == '': return 'Well, you are quiet.' elif 'hello' in lowered: return 'Hello there! Please let me know what you want me to do!' elif 'help' in lowered: return f'You can say !weather, !fact, or !quote.' elif '!fact' in lowered: print(fetch_fact) elif split_params[0] == "!weather": if len(split_params) > 1: city_name = ' '.join(split_params[1:]) return fetch_weather(city_name) else: return 'Please provide a city name after the !weather command.' elif '!quote' in lowered: print(fetch_quote) else: return choice(['I don\'t have any brains.', 'What?', "Repeat please."])
const posts = [ { "id": 1, "content": "Placeat libero ipsa nobis ipsum quibusdam quas harum ut. Distinctio minima iusto. Ad ad maiores et sint voluptate recusandae architecto. Et nihil ullam aut alias.", "media": "https://unsplash.it/600/300?image=171", "author": { "name": "Phil Mangione", "image": "https://unsplash.it/300/300?image=15" }, "likes": 80, "created": "2021-06-25" }, { "id": 2, "content": "Placeat libero ipsa nobis ipsum quibusdam quas harum ut. Distinctio minima iusto. Ad ad maiores et sint voluptate recusandae architecto. Et nihil ullam aut alias.", "media": "https://unsplash.it/600/400?image=112", "author": { "name": "Sofia Perlari", "image": "https://unsplash.it/300/300?image=10" }, "likes": 120, "created": "2021-09-03" }, { "id": 3, "content": "Placeat libero ipsa nobis ipsum quibusdam quas harum ut. Distinctio minima iusto. Ad ad maiores et sint voluptate recusandae architecto. Et nihil ullam aut alias.", "media": "https://unsplash.it/600/400?image=234", "author": { "name": "Chiara Passaro", "image": "https://unsplash.it/300/300?image=20" }, "likes": 78, "created": "2021-05-15" }, { "id": 4, "content": "Placeat libero ipsa nobis ipsum quibusdam quas harum ut. Distinctio minima iusto. Ad ad maiores et sint voluptate recusandae architecto. Et nihil ullam aut alias.", "media": "https://unsplash.it/600/400?image=24", "author": { "name": "Luca Formicola", "image": null }, "likes": 56, "created": "2021-04-03" }, { "id": 5, "content": "Placeat libero ipsa nobis ipsum quibusdam quas harum ut. Distinctio minima iusto. Ad ad maiores et sint voluptate recusandae architecto. Et nihil ullam aut alias.", "media": "https://unsplash.it/600/400?image=534", "author": { "name": "Alessandro Sainato", "image": "https://unsplash.it/300/300?image=29" }, "likes": 95, "created": "2021-03-05" } ]; const postsContainer = document.getElementById('container'); const likedPost = []; posts.forEach(singlePost => { postsContainer.innerHTML += ` <div class="post"> <div class="post__header"> <div class="post-meta"> <div class="post-meta__icon"> <img class="profile-pic" src="${singlePost.author.image}" alt="${singlePost.author.name}"> </div> <div class="post-meta__data"> <div class="post-meta__author">${singlePost.author.name}</div> <div class="post-meta__time">${singlePost.created}</div> </div> </div> </div> <div class="post__text">Placeat libero ipsa nobis ipsum quibusdam quas harum ut. Distinctio minima iusto. Ad ad maiores et sint voluptate recusandae architecto. Et nihil ullam aut alias.</div> <div class="post__image"> <img src="${singlePost.media}" alt=""> </div> <div class="post__footer"> <div class="likes js-likes"> <div class="likes__cta"> <a class="like-button js-like-button" href="#" data-postid="${singlePost.id}"> <i class="like-button__icon fas fa-thumbs-up" aria-hidden="true"></i> <span class="like-button__label">Mi Piace</span> </a> </div> <div class="likes__counter"> Piace a <b id="like-counter-${singlePost.id}" class="js-likes-counter">${singlePost.likes}</b> persone </div> </div> </div> </div> `; }); const likedButton = document.querySelectorAll('.js-like-button'); likedButton.forEach((singleLikedButton, i) => { singleLikedButton.addEventListener('click', function(evento){ //evento contiene l'elemento click evento.preventDefault(); if(!this.classList.contains('like-button--liked')){ this.classList.add('like-button--liked'); const postId = parseInt(this.getAttribute('data-postid')); // likedPost.push(posts[i].id); likedPost.push(postId); const likeCounter = document.getElementById(`like-counter-${this.getAttribute('data-postid')}`) console.log(likeCounter.innerText); let currentLikeNumber = parseInt(likeCounter.innerHTML); likeCounter.innerHTML = currentLikeNumber + 1; // likeCounter.innerHTML = ++currentLikeNumber; } console.log(likedPost); } ); });
from transformers import AutoModelForCausalLM, AutoConfig from transformers.models.llama.modeling_llama import LlamaAttention, LlamaForCausalLM, LlamaMLP import torch import torch.nn as nn import numpy as np from rnn.mamba import MambaLMHeadModel from mamba_ssm.models.config_mamba import MambaConfig from rnn.hybrid import HybridMambaLMHeadModel def get_transformer_config( dataset, hidden_size=768, intermediate_size=1024, num_hidden_layers=12, num_attention_heads=12, max_position_embeddings=4096, ): config = AutoConfig.from_pretrained("NousResearch/Llama-2-7b-hf") config.hidden_size = hidden_size config.intermediate_size = intermediate_size config.num_hidden_layers = num_hidden_layers config.num_attention_heads = num_attention_heads config.num_key_value_heads = num_attention_heads config.vocab_size = dataset.n_vocab config.max_position_embeddings = max_position_embeddings config.pad_token_id = dataset.vocab['[PAD]'] config.bos_token_id = dataset.vocab['[BOS]'] config.eos_token_id = dataset.vocab['[EOS]'] return config def get_transformer_model( dataset, hidden_size=32, intermediate_size=128, num_hidden_layers=16, num_attention_heads=4, max_position_embeddings=4096 ): config = get_transformer_config( dataset, hidden_size=hidden_size, intermediate_size=intermediate_size, num_hidden_layers=num_hidden_layers, num_attention_heads=num_attention_heads, max_position_embeddings=max_position_embeddings ) model = AutoModelForCausalLM.from_config(config) embed_matrix = torch.zeros_like(model.model.embed_tokens.weight) for i in range(model.config.vocab_size): for j in range(model.config.hidden_size): if j % 2 == 0: embed_matrix[i][j] = np.sin(i / (10000 ** (j / model.config.hidden_size))) else: embed_matrix[i][j] = np.cos(i / (10000 ** ((j - 1) / model.config.hidden_size))) print(embed_matrix) model.model.embed_tokens = nn.Embedding.from_pretrained(embed_matrix) model.model.embed_tokens.weight.requires_grad = False model.lm_head.weight = model.model.embed_tokens.weight model.lm_head.weight.requires_grad = False print(f'Parameters: {sum(p.numel() for p in model.parameters() if p.requires_grad) / 1e6:.2f}M') return model def get_rnn_config( dataset, hidden_size=768, num_hidden_layers=12, ): ssm_config = MambaConfig( d_model=hidden_size, n_layer=num_hidden_layers, vocab_size=dataset.n_vocab, ) return ssm_config def get_rnn_model( dataset, hidden_size=768, num_hidden_layers=12, ): config = get_rnn_config( dataset, hidden_size=hidden_size, num_hidden_layers=num_hidden_layers, ) model = MambaLMHeadModel(config).to("cuda") embed_matrix = torch.zeros_like(model.backbone.embedding.weight) print(embed_matrix.shape) for i in range(embed_matrix.shape[0]): for j in range(embed_matrix.shape[1]): if j % 2 == 0: embed_matrix[i][j] = np.sin(i / (10000 ** (j / embed_matrix.shape[1]))) else: embed_matrix[i][j] = np.cos(i / (10000 ** ((j - 1) / embed_matrix.shape[1]))) model.backbone.embedding = nn.Embedding.from_pretrained(embed_matrix) model.backbone.embedding.weight.requires_grad = False model.lm_head.weight = model.backbone.embedding.weight model.lm_head.weight.requires_grad = False print(f'Parameters: {sum(p.numel() for p in model.parameters() if p.requires_grad) / 1e6:.2f}M') return model def get_hybrid_config( dataset, hidden_size=768, num_hidden_layers=12, max_position_embeddings = 4096, num_attention_heads = 4, intermediate_size = 1024 ): ssm_config = MambaConfig( d_model=hidden_size, n_layer=num_hidden_layers, vocab_size=dataset.n_vocab, ) config = AutoConfig.from_pretrained("NousResearch/Llama-2-7b-hf") config.hidden_size = hidden_size config.intermediate_size = intermediate_size config.num_hidden_layers = num_hidden_layers config.num_attention_heads = num_attention_heads config.num_key_value_heads = num_attention_heads config.vocab_size = dataset.n_vocab config.max_position_embeddings = max_position_embeddings config.pad_token_id = dataset.vocab['[PAD]'] config.bos_token_id = dataset.vocab['[BOS]'] config.eos_token_id = dataset.vocab['[EOS]'] ssm_config.llama_cfg = config return ssm_config def get_hybrid_model( dataset, hidden_size=768, num_hidden_layers=12, max_position_embeddings = 4096, num_attention_heads = 4, intermediate_size = 1024 ): config = get_hybrid_config( dataset, hidden_size=hidden_size, num_hidden_layers=num_hidden_layers, max_position_embeddings = max_position_embeddings, num_attention_heads = num_attention_heads, intermediate_size = intermediate_size ) model = HybridMambaLMHeadModel(config).to("cuda") embed_matrix = torch.zeros_like(model.backbone.embedding.weight) print(embed_matrix.shape) for i in range(embed_matrix.shape[0]): for j in range(embed_matrix.shape[1]): if j % 2 == 0: embed_matrix[i][j] = np.sin(i / (10000 ** (j / embed_matrix.shape[1]))) else: embed_matrix[i][j] = np.cos(i / (10000 ** ((j - 1) / embed_matrix.shape[1]))) model.backbone.embedding = nn.Embedding.from_pretrained(embed_matrix) model.backbone.embedding.weight.requires_grad = False model.lm_head.weight = model.backbone.embedding.weight model.lm_head.weight.requires_grad = False print(f'Parameters: {sum(p.numel() for p in model.parameters() if p.requires_grad) / 1e6:.2f}M') return model if __name__ == '__main__': pass
## Description <div><p>Every true king during his life must conquer the world, hold the Codeforces world finals, win pink panda in the shooting gallery and travel all over his kingdom.</p><p>King Copa has already done the first three things. Now he just needs to travel all over the kingdom. The kingdom is an infinite plane with Cartesian coordinate system on it. Every city is a point on this plane. There are <span class="tex-span"><i>n</i></span> cities in the kingdom at points with coordinates <span class="tex-span">(<i>x</i><sub class="lower-index">1</sub>, 0), (<i>x</i><sub class="lower-index">2</sub>, 0), ..., (<i>x</i><sub class="lower-index"><i>n</i></sub>, 0)</span>, and there is one city at point <span class="tex-span">(<i>x</i><sub class="lower-index"><i>n</i> + 1</sub>, <i>y</i><sub class="lower-index"><i>n</i> + 1</sub>)</span>. </p><p>King starts his journey in the city number <span class="tex-span"><i>k</i></span>. Your task is to find such route for the king, which visits all cities (in any order) and has minimum possible length. It is allowed to visit a city twice. The king can end his journey in any city. Between any pair of cities there is a direct road with length equal to the distance between the corresponding points. No two cities may be located at the same point.</p></div><div class="input-specification"><p>The first line contains two integers <span class="tex-span"><i>n</i></span> and <span class="tex-span"><i>k</i></span> (<span class="tex-span">1 ≤ <i>n</i> ≤ 10<sup class="upper-index">5</sup>, 1 ≤ <i>k</i> ≤ <i>n</i> + 1</span>) — amount of cities and index of the starting city. The second line contains <span class="tex-span"><i>n</i> + 1</span> numbers <span class="tex-span"><i>x</i><sub class="lower-index"><i>i</i></sub></span>. The third line contains <span class="tex-span"><i>y</i><sub class="lower-index"><i>n</i> + 1</sub></span>. All coordinates are integers and do not exceed <span class="tex-span">10<sup class="upper-index">6</sup></span> by absolute value. No two cities coincide.</p></div><div class="output-specification"><p>Output the minimum possible length of the journey. Your answer must have relative or absolute error less than <span class="tex-span">10<sup class="upper-index"> - 6</sup></span>.</p></div> ## Input <p>The first line contains two integers <span class="tex-span"><i>n</i></span> and <span class="tex-span"><i>k</i></span> (<span class="tex-span">1 ≤ <i>n</i> ≤ 10<sup class="upper-index">5</sup>, 1 ≤ <i>k</i> ≤ <i>n</i> + 1</span>) — amount of cities and index of the starting city. The second line contains <span class="tex-span"><i>n</i> + 1</span> numbers <span class="tex-span"><i>x</i><sub class="lower-index"><i>i</i></sub></span>. The third line contains <span class="tex-span"><i>y</i><sub class="lower-index"><i>n</i> + 1</sub></span>. All coordinates are integers and do not exceed <span class="tex-span">10<sup class="upper-index">6</sup></span> by absolute value. No two cities coincide.</p> ## Output <p>Output the minimum possible length of the journey. Your answer must have relative or absolute error less than <span class="tex-span">10<sup class="upper-index"> - 6</sup></span>.</p> ```input1 3 1 0 1 2 1 1 ``` ```input2 3 1 1 0 2 1 1 ``` ```input3 4 5 0 5 -1 -5 2 3 ``` ```output1 3.41421356237309490000 ``` ```output2 3.82842712474619030000 ``` ```output3 14.24264068711928400000 ```
//@@viewOn:imports import { createVisualComponent, Utils, useLsi, PropTypes } from "uu5g05"; import Config from "./config/config.js"; import { Box, DateTime, Text } from "uu5g05-elements"; import importLsi from "../../lsi/import-lsi"; //@@viewOff:imports //@@viewOn:constants //@@viewOff:constants //@@viewOn:css const Css = { main: () => Config.Css.css({ display: "flex", flexDirection: "column", padding: "16px 0" }), header: () => Config.Css.css({ padding: "16px" }), }; //@@viewOff:css //@@viewOn:helpers //@@viewOff:helpers const DetailContent = createVisualComponent({ //@@viewOn:statics uu5Tag: Config.TAG + "DetailContent", //@@viewOff:statics //@@viewOn:propTypes propTypes: { logbookEntryDataObject: PropTypes.object.isRequired, pilotDataObject: PropTypes.object.isRequired, placeDataList: PropTypes.object.isRequired, aircraftDataObject: PropTypes.object.isRequired, }, //@@viewOff:propTypes //@@viewOn:defaultProps defaultProps: {}, //@@viewOff:defaultProps render(props) { //@@viewOn:private const lsi = useLsi(importLsi, [DetailContent.uu5Tag]); const logbookEntryDataObject = props.logbookEntryDataObject const pilotDataObject = props.pilotDataObject.data const aircraft = props.aircraftDataObject.data const flightFrom = props.placeDataList.data.filter((place) => place.data.id === logbookEntryDataObject.data.departurePlaceId)[0].data; const flightTo = props.placeDataList.data.filter((place) => place.data.id === logbookEntryDataObject.data.arrivalPlaceId)[0].data; const flightDuration = (Date.parse(logbookEntryDataObject.data.arrivalDateTime) - Date.parse(logbookEntryDataObject.data.departureDateTime))/60000; //@@viewOff:private //@@viewOn:interface //@@viewOff:interface //@@viewOn:render const attrs = Utils.VisualComponent.getAttrs(props, Css.main()); return ( <div {...attrs}> <Box className={Css.main()}> <Text category="interface" segment="title" type="major" colorScheme="highest" className={Css.header()}> {`${flightFrom.name} > ${flightTo.name}`} </Text> <Text category="interface" segment="title" type="minor" colorScheme="building" className={Css.header()}> {lsi.departureTime} <DateTime value={logbookEntryDataObject.data.departureDateTime} dateFormat="short"/> </Text> <Text category="interface" segment="title" type="minor" colorScheme="building" className={Css.header()}> {lsi.arrivalTime} <DateTime value={logbookEntryDataObject.data.arrivalDateTime} dateFormat="short" /> </Text> <Text category="interface" segment="title" type="minor" colorScheme="building" className={Css.header()}> {`${lsi.duration} ${flightDuration} ${lsi.minutes}`} </Text> <Text category="interface" segment="title" type="minor" colorScheme="building" className={Css.header()}> {`${lsi.pilot} ${pilotDataObject.name}`} </Text> <Text category="interface" segment="title" type="minor" colorScheme="building" className={Css.header()}> {`${lsi.model} ${aircraft.model}`} </Text> <Text category="interface" segment="title" type="minor" colorScheme="building" className={Css.header()}> {`${lsi.registration} ${aircraft.registration}`} </Text> <Text category="interface" segment="title" type="minor" colorScheme="building" className={Css.header()}> {`${lsi.departure} ${flightFrom.name}, ${flightFrom.code}, GPS: ${flightFrom.gpsCoordinates}`} </Text> <Text category="interface" segment="title" type="minor" colorScheme="building" className={Css.header()}> {`${lsi.arrival} ${flightTo.name}, ${flightTo.code}, GPS: ${flightTo.gpsCoordinates}`} </Text> </Box> </div> ); //@@viewOff:render }, }); //@@viewOn:exports export { DetailContent }; export default DetailContent; //@@viewOff:exports
const mongoose = require('mongoose') const jwt = require('jsonwebtoken') const bcrypt = require('bcrypt') const client = require('../db/redis') const joi = require('joi') require('../db/db') const userSchema = new mongoose.Schema({ userName: { type: String, required: true, unique: true, minlength: 5, maxlength: 15, validate(value){ var myRegxp = /^([a-zA-Z0-9_-]){5,15}$/; if (!myRegxp.test(value)) { throw new Error("Username must be between 5 to 15 characters long and only alphanumeric is allowed") } } }, password:{ type : String, required: true } }) // joi.object({ // userName: joi.string() // .required() // .min(5) // .max(15) // .alphanum(), // password: joi.string().required() // }) // userSchema.methods.generateAuthToken = async function(){ const user= this const token = jwt.sign({ _id : user._id.toString()}, JWT_SECRET) const exist = await user.save() return token } userSchema.statics.findByCredentials = async (name, password)=>{ const data = await client.sendCommand(['keys','*']) findkey = 'user_'+name const single = await client.json.get(findkey) if(!single){ throw new Error('there is no such user inside redis is available') } const isMatch = await bcrypt.compare(password, single.password) if(!isMatch){ throw new Error('please enter valid password') } const user = await User.findById(single.id) if(!user){ throw new Error('there is no such user with such credentials is available') } return user } userSchema.pre('save', async function(next) { const user = this if(user.isModified('password')){ user.password = await bcrypt.hash(user.password, 8) } next() }) const User = mongoose.model("User", userSchema) module.exports = User
import logging # Confugure a logger so that useful information can be presented: # level=logging.DEBUG means the level from which the logging or outputing should start, DEBUG is this case. # filename is the name of the file to which the log should go to. # filemode creates the file and overrides the file it already exits. # format creates the time of the log, level name of the log, the message being logged, etc logging.basicConfig(level=logging.DEBUG, filename='log2.log', filemode='w', format='%(asctime)s - %(levelname)s - %(message)s') # There are different levels of logging: logging.debug("This is a debug message") logging.info("This is an info message") # By default the program will print anything from warning level and above: logging.warning("This is a warning message") logging.error("This is an error message") logging.critical("This is a critical message") # root stands for whihc logger is being used.
<div class="container"> <div class="row"> <form [formGroup]="LoginForm" (ngSubmit)="onSubmit()" class="mt-5 d-flex justify-content-center" > <div class="col-lg-5"> <div class="form-group mb-1"> <label for="email">Email address</label> <input type="email" class="form-control mt-2 mb-1" id="email" placeholder="Enter email" formControlName="email" /> </div> <div class="form-group"> <label for="password">Password</label> <input type="password" class="form-control my-2" id="password" placeholder="Password" formControlName="password" autocomplete="off" /> </div> <div class="form-group"> <div class="row"> <div class="col-12 mt-3 d-flex justify-content-center"> <button [disabled]="!LoginForm.valid" type="submit" class="btn btn-primary px-4" > Login </button> </div> <div class="col-12 mt-3 d-flex justify-content-center"> <ngx-recaptcha2 #captchaElem [siteKey]="siteKey" formControlName="recaptcha" > </ngx-recaptcha2> </div> <div class="col-12 d-flex justify-content-center"> <small id="emailHelp" class="form-text text-muted" >Don't have an account? <a routerLink="/signup">Sign Up</a></small > </div> <div class="col-12 d-flex justify-content-center"> <div class="alert alert-warning mx-auto mt-2" style="width: 50vw" role="alert" *ngIf="message" > {{ message }} </div> </div> </div> </div> </div> </form> </div> </div>
import { Schema, model, models } from 'mongoose'; // Define the User schema const UserSchema = new Schema( { email: { type: String, unique: [true, 'Email already exists!'], required: [true, 'Email is required!'], match: [/^\S+@\S+\.\S+$/, 'Please use a valid email address!'], trim: true, index: true, // Index for faster queries }, username: { type: String, required: [true, 'Username is required!'], match: [ /^(?=.{8,20}$)(?![_.])(?!.*[_.]{2})[a-zA-Z0-9._]+(?<![_.])$/, 'Username invalid, it should contain 8-20 alphanumeric characters and be unique!', ], trim: true, unique: true, // Ensuring the username is unique }, image: { type: String, validate: { validator: function (v) { return /^(http|https):\/\/[^ "]+$/.test(v); }, message: (props) => `${props.value} is not a valid URL!`, }, }, }, { timestamps: true, // Automatically adds createdAt and updatedAt fields } ); // Create or retrieve the model const User = models.User || model('User', UserSchema); export default User;
# Membuat Tabel pada HTML Presentasi informasi dalam web dapat dilakukan dengan menggunakan elemen `Table`. **Elemen `Table` terdiri dari 4 unsur utama:** 1. Baris 2. Kolom 3. Sel 4. Garis **Tag untuk membuat Tabel pada HTML:** # Membuat Tabel pada HTML Penting untuk diingat beberapa `tag` saat membuat `table` pada `HTML`: | No | Tag | Keterangan | |---|-----------|--------------------------------------------------| | 1 | `<table>` | Digunakan untuk membungkus tabel. | | 2 | `<thead>` | Digunakan untuk membungkus bagian kepala tabel. | | 3 | `<tbody>` | Digunakan untuk membungkus bagian isi tabel. | | 4 | `<tr>` | Digunakan untuk membuat baris dalam tabel. | | 5 | `<td>` | Digunakan untuk membuat sel/data dalam tabel. | | 6 | `<th>` | Digunakan untuk membuat judul pada kepala tabel. | **Penting untuk memahami penggunaan setiap tag di atas agar dapat membuat tabel `HTML` dengan benar dan efisien. Tag yang paling penting untuk diingat adalah `<table>`, `<tr>`, dan `<td>`. Sementara tag yang lain bersifat tambahan (opsional) dan dapat digunakan atau tidak.** Contoh penggunaan tag: ```html <table> <tr> <td>baris 1</td> <td>baris 2</td> </tr> <tr> <td>kolom 1</td> <td>kolom 2</td> </tr> </table> ``` **Hasil dari kode di atas:** <table> <tr> <td>baris 1</td> <td>baris 2</td> </tr> <tr> <td>kolom 1</td> <td>kolom 2</td> </tr> </table> Pada contoh di atas, ketika ditampilkan pada browser, tabel tidak memiliki `garis (border)`. Bagaimana cara menambahkan `garis`? Untuk menambahkan `garis`, kita perlu menggunakan atribut `border=""` pada tag `<table>`. Berikut contohnya: ```html <table border="2"> <tr> <td>baris 1</td> <td>baris 2</td> </tr> <tr> <td>kolom 1</td> <td>kolom 2</td> </tr> </table> ``` **Hasil dari kode di atas:** <table border="2"> <tr> <td>baris 1</td> <td>baris 2</td> </tr> <tr> <td>kolom 1</td> <td>kolom 2</td> </tr> </table> **Nilai "2" pada atribut border adalah ukuran garisnya. Semakin besar ukurannya, maka semakin besar pula ukuran garisnya.** **Mengatur Jarak Sel dengan Cellpadding** Atribut `cellpadding` digunakan untuk mengatur jarak antara `teks` dengan `garis` di dalam `sel`. Atribut ini dapat digunakan di dalam tag `table`. Contohnya: ```html <body> <table border="2" cellpadding="15"> <tr> <td>baris 1</td> <td>baris 2</td> </tr> <tr> <td>kolom 1</td> <td>kolom 2</td> </tr> </table> </body> ``` **Hasil dari kode di atas:** <body> <table border="2" cellpadding="15"> <tr> <td>baris 1</td> <td>baris 2</td> </tr> <tr> <td>kolom 1</td> <td>kolom 2</td> </tr> </table> </body> **Nilai "15" pada atribut cellpadding adalah ukuran jarak antara teks sel dengan garis.** **Menambahkan Warna pada Sel dan Baris** Untuk menambahkan warna pada sel dan baris, kita bisa menggunakan atribut `bgcolor="` pada tag `<tr>` untuk baris dan pada `<td>` pada sel. Contoh: ```html <body> <table border="2" cellpadding="15"> <tr bgcolor="yellow"> <td>baris 1</td> <td>baris 2</td> </tr> <tr> <td bgcolor="#0000ff">kolom 1</td> <td>kolom 2</td> </tr> </table> </body> ``` **Hasil dari kode di atas:** <body> <table border="2" cellpadding="15"> <tr bgcolor="yellow"> <td>baris 1</td> <td>baris 2</td> </tr> <tr> <td bgcolor="#0000ff">kolom 1</td> <td>kolom 2</td> </tr> </table> </body> **Nilai atribut bgcolor bisa kita isi dengan kode warna dalam heksadesimal atau nama warna dalam bahasa Inggris.** **Menggabungkan Sel Tabel** Untuk menggabungkan sel, kita dapat menggunakan atribut `rowspan` dan `colspan`. | Atribut | Penjelasan | |----------|-----------------------------| | rowspan | Digunakan untuk menggabungkan baris | | colspan | Digunakan untuk menggabungkan sel | **Atribut ini dapat digunakan pada tag `<td>` atau `<th>`.** Contoh: ```html <table border="1"> <tr> <th rowspan="2" bgcolor="#3cb371">Bulan</th> <th colspan="2" bgcolor="#00ffbf">Hasil Panen</th> </tr> <tr> <th>Jagung Manis</th> <th>Kacang Tanah</th> </tr> <tr> <td>Januari</td> <td>500 Kg</td> <td>250 Kg</td> </tr> <tr> <td>Februari</td> <td>750 Kg</td> <td>350 Kg</td> </tr> </table> ``` **Hasil dari kode di atas :** <table border="1"> <tr> <th rowspan="2" bgcolor="#3cb371">Bulan</th> <th colspan="2" bgcolor="#00ffbf">Hasil Panen</th> </tr> <tr> <th>Jagung Manis</th> <th>Kacang Tanah</th> </tr> <tr> <td>Januari</td> <td>500 Kg</td> <td>250 Kg</td> </tr> <tr> <td>Februari</td> <td>750 Kg</td> <td>350 Kg</td> </tr> </table> **Dengan menggunakan atribut `rowspan` dan `colspan`, kita dapat menggabungkan sel sesuai kebutuhan pada tabel.** **Menyisipkan Elemen yang Lain ke dalam Sel** Didalam sel `<td>` dan `<th>` kita bisa menyisipkan elemen `HTML` yang lain, seperti: `gambar`, `audio`,`link`,`video`,`dsb`. ~ Contoh: ```html <body> <table border="1"> <tr> <th colspan="3" style="background-color: green;">Produk Unggulan</th> </tr> <tr> <td rowspan="1"> <img src="https://down-id.img.susercontent.com/file/id-11134207-7r98y-loqdadgmj3zk3e" alt="Deskripsi Gambar" style="height: 228px;"> </td> <td>Nama Barang</td> <td>PC + MONITOR full AMD Series</td> </tr> <tr> <td>Harga Barang</td> <td>Rp. 5.000.000</td> </tr> tr> <td>Fitur</td> <td colspan="2"> <ul> <li>LED 24 Inch Full HD</li> <li>MB Asrock A520M</li> <li>AMD Ryzen 5 5600G</li> <li>VGA Integrated AMD Radeon Vega Series Graphics</li> <li>HDD Seagate 500GB Sata</li> </ul> </td> </tr> </table> </body> ``` **Hasil kode diatas** <body> <table border="1"> <tr> <th colspan="3" style="background-color: green;">Produk Unggulan</th> </tr> <tr> <td rowspan="1"> <img src="https://down-id.img.susercontent.com/file/id-11134207-7r98y-loqdadgmj3zk3e" alt="Deskripsi Gambar" style="height: 228px;"> </td> <td>Nama Barang</td> <td>PC + MONITOR full AMD Series</td> </tr> <tr> <td>Harga Barang</td> <td>Rp. 5.000.000</td> </tr> <tr> <td>Fitur</td> <td colspan="2"> <ul> <li>LED 24 Inch Full HD</li> <li>MB Asrock A520M</li> <li>AMD Ryzen 5 5600G</li> <li>VGA Integrated AMD Radeon Vega Series Graphics</li> <li>HDD Seagate 500GB Sata</li> </ul> </td> </tr> </table> </body>
import React, {useEffect} from 'react'; import Layout from '../../components/layout'; import Cards from '../../components/widgets/cards/cards'; import {GetStaticPaths, GetStaticProps} from 'next'; import {getFilteredItems} from '../../lib/services/search'; import {useRouter} from 'next/router'; import {contentAllPages} from '../../lib/services/allPages'; import Head from "next/head"; import Container from "../../components/containers/container/container"; import Image from "next/image"; import Link from "next/link"; interface Props { labels: any, posts: any, searchKey: string, preview: any, CTAHeader: any, footer: any, allCategories: any } export default function Search({labels, posts, searchKey, footer, allCategories, preview, CTAHeader}: Props) { const router = useRouter() useEffect(() => { }, [router.query.key]); return ( <Layout labels={labels} searchKey={searchKey} preview={preview} CTAHeader={CTAHeader} footer={footer} allCategories={allCategories} > <Head> <title>Bom de Beer Blog - Search Page</title> <meta name="description" content={'Filtro de para todos os resultados de ' + searchKey} /> </Head> { !!posts?.length && <Cards items={posts} title={''} enabledTitle={false} isEnabledSeeMore={true} maxPosts={6} /> } {!posts?.length && <div className="py-24"> <Container> <h2>Nenhum resultado:</h2> <p className='mb-16'>Desculpe, mas nada corresponde aos seus termos de pesquisa de {searchKey}. Por favor, tente novamente com algumas palavras-chave diferentes.</p> <Link href='/' className='mb-10'> <button className='text-base button__primary button__primary-rounded'> Voltar para Home </button> </Link> </Container> </div>} </Layout> ); } export const getStaticProps: GetStaticProps = async ({ params, preview = false, previewData, }) => { const posts = await getFilteredItems(params.search); const globalContent = await contentAllPages(); const {labels, CTAHeader, footer, allCategories} = globalContent; return { props: { preview, labels, posts, searchKey: params.search, CTAHeader, footer, allCategories }, revalidate: 10, } } export const getStaticPaths: GetStaticPaths = async () => { return { paths: [], fallback: true, } }
package com.zrgj519.campusBBS.entity; import lombok.Data; import java.util.Date; import java.util.Objects; @Data public class User { // 因为设置,id由springboot和mybaits自动生成 private int id; private String sid; public String getSid() { return sid; } public void setSid(String sid) { this.sid = sid; } private String username; private String password; private String salt; private String email; private int type; private int status; private String activationCode; private String headerUrl; private Date createTime; private String interest; private String signature; public int getId() { return id; } public void setId(int id) { this.id = id; } public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } public String getSalt() { return salt; } public void setSalt(String salt) { this.salt = salt; } public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } public int getType() { return type; } public void setType(int type) { this.type = type; } public int getStatus() { return status; } public void setStatus(int status) { this.status = status; } public String getActivationCode() { return activationCode; } public void setActivationCode(String activationCode) { this.activationCode = activationCode; } public String getHeaderUrl() { return headerUrl; } public void setHeaderUrl(String headerUrl) { this.headerUrl = headerUrl; } public Date getCreateTime() { return createTime; } public void setCreateTime(Date createTime) { this.createTime = createTime; } public String getInterest() { return interest; } public void setInterest(String interest) { this.interest = interest; } @Override public int hashCode() { return Objects.hash(id, username, password, salt, email, type, status, activationCode, headerUrl, createTime, interest); } }
import React from 'react'; import './RegisterForm.css'; import { FormatShapes } from '@mui/icons-material'; class RegisterForm extends React.Component { constructor() { super(); this.state = { fields: {}, errors: {} } this.handleChange = this.handleChange.bind(this); this.submituserRegistrationForm = this.submituserRegistrationForm.bind(this); }; handleChange(e) { let fields = this.state.fields; fields[e.target.name] = e.target.value; this.setState({ fields }); } submituserRegistrationForm(e) { e.preventDefault(); if (this.validateForm()) { let fields = {}; fields["username"] = ""; fields["mobileno"] = ""; fields["password"] = ""; this.setState({fields:fields}); alert("Form submitted"); } } validateForm() { let fields = this.state.fields; let errors = {}; let formIsValid = true; if (!fields["username"]) { formIsValid = false; errors["username"] = "*Please enter your First_Name."; } if (typeof fields["username"] !== "undefined") { if (!fields["username"].match(/^[a-zA-Z ]*$/)) { formIsValid = false; errors["username"] = "*Please enter alphabet characters only."; } } if (!fields["name"]) { formIsValid = false; errors["name"] = "*Please enter your Last_Name."; } if (typeof fields["name"] !== "undefined") { if (!fields["name"].match(/^[a-zA-Z ]*$/)) { formIsValid = false; errors["name"] = "*Please enter alphabet characters only."; } } if (!fields["emailid"]) { formIsValid = false; errors["emailid"] = "*Please enter your email-ID."; } if (!fields["gender"]) { formIsValid = false; errors["gender"] = "*Please enter your gender."; } if (!fields["stream"]) { formIsValid = false; errors["stream"] = "*Please enter your Stream."; } if (!fields["mobileno"]) { formIsValid = false; errors["mobileno"] = "*Please enter your mobile no."; } if (typeof fields["mobileno"] !== "undefined") { if (!fields["mobileno"].match(/^[0-9]{10}$/)) { formIsValid = false; errors["mobileno"] = "*Please enter valid mobile no."; } } if (!fields["age"]) { formIsValid = false; errors["age"] = "*Please enter your age."; } if (typeof fields["age"] !== "undefined") { if (!fields["age"].match(/^[0-9]{2}$/)) { formIsValid = false; errors["age"] = "*Please enter valid age."; } } if (!fields["password"]) { formIsValid = false; errors["password"] = "*Please enter your password."; } if (typeof fields["password"] !== "undefined") { if (!fields["password"].match("^(?=.[a-z])(?=.[A-Z])(?=.[0-9])(?=.[!@#\$%\^&\*])(?=.{8,})")) { formIsValid = false; errors["password"] = "*Please enter secure and strong password."; } } this.setState({ errors: errors }); return formIsValid; } render() { return ( <div className="p"> <div id="main-registration-container"> <h1>ADVISOR REGISTRATION FORM</h1> <div id="register"> <h3>Registration page</h3> <form method="post" name="userRegistrationForm" onSubmit= {this.submituserRegistrationForm} > <div className="errorMsg">{this.state.errors.username}</div> <label>First_Name</label> <input type="text" name="username" value={this.state.fields.username} onChange={this.handleChange} /> <div className="errorMsg">{this.state.errors.username}</div> <label>Last_Name</label> <input type="text" name="name" value={this.state.fields.name} onChange={this.handleChange} /> <div className="errorMsg">{this.state.errors.name}</div> <lable>Email_Id</lable> <input type="text" name="emailid" value={this.state.fields.emailid} onChange={this.handleChange}/> <div className="errorMsg">{this.state.errors.email}</div> <label>Mobile No:</label> <input type="text" name="mobileno" value={this.state.fields.mobileno} onChange={this.handleChange} /> <div className="errorMsg">{this.state.errors.mobileno}</div> <label>Gender</label> <input type="text" name="gender" value={this.state.fields.gender} onChange={this.handleChange}/> <div className="gender"> <select name="gender" id="id_gender" value={this.state.fields.gender}> <option value="m" >Male</option> <option value="f">Female</option> </select> </div> <label>Age</label> <input type="text" name="age" value={this.state.fields.age} onChange={this.handleChange}/> <div className="errorMsg">{this.state.errors.age}</div> <label>Education_Qualification</label> <input type="text" name="education" value={this.state.fields.education} onChange={this.handleChange}/> <div className="errorMsg">{this.state.errors.education}</div> <lable>Achievements</lable> <input type="text" name="achievements" value={this.state.fields.achievements} onChange={this.handleChange}/> <div className="errorMsg">{this.state.errors.achievements}</div> <label>Stream</label> <input type="text" name="stream" value={this.state.fields.stream} onChange={this.handleChange}/> <div className="stream"> <select name="stream" id="id_stream" value={this.state.fields.gender}> <option value="Education" >Education Consultant</option> <option value="Business">Business Consultant</option> <option value="Health">Health Consultant</option> <option value="family">Mental Health Consultant</option> </select> </div> <label>Password</label> <input type="password" name="password" value={this.state.fields.password} onChange={this.handleChange} /> <div className="errorMsg">{this.state.errors.password}</div> <label>Confirm Password</label> <input type="Confirm" name="Confirm" value={this.state.fields.Confirm} onChange={this.handleChange} /> <div className="errorMsg">{this.state.errors.password}</div> <input type="submit" className="button" value="Register"/> </form> </div> </div> </div> ); } } export default RegisterForm;
import Chat from "./Chat"; import { useState } from "react"; import io from "socket.io-client"; const socket = io.connect("http://localhost:3001"); function App() { const [username, setUsername] = useState(""); const [room, setRoom] = useState(""); const [showChat, setShowChat] = useState(false); const joinRoom = () => { if (username !== "" && room !== "") { socket.emit("join_room", room); setShowChat(true); } }; return ( <section className="main_container"> {!showChat ? ( <section className="create_join_chat_form"> <input type="text" placeholder="Your username" onChange={(event) => { setUsername(event.target.value); }} /> <input type="text" placeholder="Room name..." onChange={(event) => { setRoom(event.target.value); }} /> <input type="submit" onClick={joinRoom} value="Create / Join A Room"/> </section> ) : ( <Chat socket={socket} username={username} room={room} /> )} </section> ); } export default App;
/** @jsxImportSource theme-ui */ import React, { useEffect, useState } from "react"; import { ImprintItem } from "./ImprintItem"; import { Link as RouteLink } from "./Link"; import { Link } from "theme-ui"; export const Imprint: React.FC = () => { const [email, setEmail] = useState(""); useEffect(() => { setEmail(atob("aGxpcXVpdHlAYmxva2suc3R1ZGlv")); }, []); return ( <ul sx={{ p: 0, listStyleType: "none", display: "inline-flex", '@media screen and (max-width: 767px)': { display: "block" }, }}> <ImprintItem title="Contact"> <address sx={{ display: "flex", flexDirection: "column", fontStyle: "normal" }}> <span>blokk.</span> <span>Dammstrasse 16</span> <span>6300 Zug</span> <span>Switzerland</span> <Link href="https://blokk.studio/" target="_blank"> https://blokk.studio/ </Link> {email && ( <Link href={`mailto:${email}`} target="_blank"> Feedback and Suggestions? </Link> )} </address> </ImprintItem> <ImprintItem title="Legal Stuff"> <RouteLink variant="default" to="/imprint">Imprint</RouteLink> <RouteLink variant="default" to="/privacy-policy">Privacy policy</RouteLink> </ImprintItem> <ImprintItem title="Social Media"> <Link href="https://x.com/blokkstudio" target="_blank">X</Link> <Link href="https://github.com/blokk-studio" target="_blank">GitHub</Link> </ImprintItem> </ul> ); };
### 解题思路 计算出质数的全排列数和非质数的全排列数,然后相乘即可。记得要模一下,否则会溢出 ### 代码 ```php class Solution { /** * @param Integer $n * @return Integer */ function numPrimeArrangements($n) { $primeNums = $this->primeCount($n); $noPrimeNums = $n - $primeNums; $res = 1; $this->factorial($res, $primeNums); $this->factorial($res, $noPrimeNums); return $res; } function primeCount($n) { $isPrim = []; for ($i = 2; $i <= $n; $i++) { $isPrim[$i] = true; } for ($i = 2; $i * $i <= $n; $i++) { if ($isPrim[$i]) { for ($j = $i * $i; $j <= $n; $j += $i) { $isPrim[$j] = false; } } } return array_sum($isPrim); } function factorial(&$res, $nums) { $mod = 1000000007; for ($i = 2; $i <= $nums; $i++) { $res = ($res * $i) % $mod; } } } ```
% Spectrophotometry lab data analysis || Written by Bakpen Kombat clc; close; clear all; %% Task 1: Determine Unkown concentration % Load data from CSV files data0 = readtable('con_0.csv'); Data0_5 = readtable('con_0.5.csv'); Data1 = readtable('con_1.csv'); Data1_5 = readtable('con_1.5.csv'); Data2 = readtable('con_2.csv'); DataUnknown = readtable('con_unknown.csv'); targetWavelength = 300; findAbsAtWavelength = @(data) interp1(data.Wavelength, data.Absorbance, targetWavelength, 'linear', 'extrap'); % Extract absorbance at 630 nm from each dataset abs0 = findAbsAtWavelength(data0); abs0_5 = findAbsAtWavelength(Data0_5); abs1 = findAbsAtWavelength(Data1); abs1_5 = findAbsAtWavelength(Data1_5); abs2 = findAbsAtWavelength(Data2); absUnknown = findAbsAtWavelength(DataUnknown); % Concentrations used for known samples (excluding unknown) concentrations = [0, 0.5, 1, 1.5, 2]; absorbances = [abs0, abs0_5, abs1, abs1_5, abs2]; % Linear regression to find best fit line coefficients = polyfit(concentrations, absorbances, 1); slope = coefficients(1); intercept = coefficients(2); concentrationUnknown = (absUnknown - intercept) / slope; figure; hold on; plot(concentrations, absorbances, 'bo', 'DisplayName', 'Known Concentrations'); % blue points for known concentrations plot(concentrations, slope*concentrations + intercept, 'k--', 'DisplayName', 'Best Fit Line'); % black dashed line for best fit % Highlight the unknown absorbance and draw horizontal line to the fit line plot(concentrationUnknown, absUnknown, 'r*', 'MarkerSize', 10, 'DisplayName', 'Unknown Concentratiob'); plot([0, concentrationUnknown], [absUnknown, absUnknown], 'r'); % Horizontal red line plot([concentrationUnknown, concentrationUnknown], [0, absUnknown], 'r'); xlabel('Concentration'); ylabel('Absorbance at 300nm'); title('Absorbance vs concentration'); legend show; grid on; % Annotate the plot with the calculated concentration text(concentrationUnknown + 0.1, absUnknown, sprintf('Estimated Concentration: %.2f', concentrationUnknown), 'Color', 'red', 'FontSize', 12); text(concentrationUnknown, -0.05, sprintf('%.2f', concentrationUnknown), 'Color', 'red', 'FontSize', 12, 'HorizontalAlignment', 'center'); %% Task 2: Finding material for UV-protection iles = {'normal_glass.csv', 'pmma.csv', 'polyc.csv', 'quartz.csv'}; colors = ['b', 'g', 'r', 'm']; % blue, green, red, magenta labels = {'Normal Glass', 'PMMA', 'Polycarbonate', 'Quartz'}; figure; % Loop over each file for i = 1:length(files) data = readtable(files{i}); wavelength = data.wavelength; transmittance = data.transmittance; % Plot data plot(wavelength, transmittance, 'Color', colors(i), 'DisplayName', labels{i}); hold on; end % Add graph title and axis labels title('Wavelength vs Transmittance for Different Materials'); xlabel('Wavelength'); ylabel('Transmittance'); legend('show'); grid on; hold off; %% Task 3: Recognizing type of plastic files = {'normal_glass.csv', 'pmma.csv', 'polyc.csv', 'quartz.csv'}; colors = ['b', 'g', 'r', 'm']; % blue, green, red, magenta labels = {'Normal Glass', 'PMMA', 'Polycarbonate', 'Quartz'}; figure; % Loop over each file for i = 1:length(files) data = readtable(files{i}); wavelength = data.wavelength; transmittance = data.transmittance; % Plot data plot(wavelength, transmittance, 'Color', colors(i), 'DisplayName', labels{i}); hold on; end % Add graph title and axis labels title('Wavelength vs Transmittance for Different Materials'); xlabel('Wavelength'); ylabel('Transmittance'); legend('show'); grid on; hold off; %% Laser safety glass protection data = readmatrix('lglass.csv'); wavelength = data(:,1); transmittance = data(:,2); figure; plot(wavelength, transmittance); title('Wavelength vs Transmittance'); xlabel('Wavelength'); ylabel('Transmittance'); grid on;
<?php declare(strict_types=1); namespace Tests\Unit\Model; use PHPUnit\Framework\TestCase; use Uro\TeltonikaFmParser\Exception\IoValueLengthException; use Uro\TeltonikaFmParser\Model\IoValue; class IoValueTest extends TestCase { /** * @test */ public function can_convert_to_hex(): void { $this->assertEquals('02', (new IoValue(hex2bin('02')))->toHex()); } /** * @test * @dataProvider unsignedProvider * @throws IoValueLengthException */ public function can_convert_to_unsigned($expected, $hex): void { $this->assertEquals($expected, (new IoValue(hex2bin($hex)))->toUnsigned()); } public static function unsignedProvider(): array { return [ [255, 'ff'], [65535, 'ffff'], [4294967295, 'ffffffff'], ]; } /** * @test * @dataProvider signedProvider * @throws IoValueLengthException */ public function can_convert_to_signed(string $hex): void { $this->assertEquals(-1, (new IoValue(hex2bin($hex)))->toSigned()); } public static function signedProvider(): array { return [ ['ff'], ['ffff'], ['ffffffff'], ]; } /** * @test */ public function to_unsigned_invalid_length_throw_exception(): void { $this->expectException(IoValueLengthException::class); (new IoValue(hex2bin('000001')))->toUnsigned(); } /** * @test */ public function to_signed_invalid_length_throw_exception(): void { $this->expectException(IoValueLengthException::class); (new IoValue(hex2bin('000001')))->toSigned(); } /** * @test */ public function can_convert_to_string(): void { $this->assertEquals('0001', (string)new IoValue(hex2bin('0001'))); } /** * @test */ public function can_serialize_json(): void { $this->assertJson('{"value":"0001"}', json_encode(new IoValue(hex2bin('0001')))); } }
#ifndef MESH_COLLIDER_H #define MESH_COLLIDER_H #include "Collider.h" #include <GL/glew.h> #include "../graphics/Vertex.hpp" #include "../graphics/Mesh.h" #include "../../thirdparty/glm/glm.hpp" #include <iostream> #include "../Debug/Debug.hpp" class MeshCollider : public Collider { private: Vertex * vertices; unsigned int nVeritces; public: MeshCollider(Vertex * vertices_, unsigned int nVertices_) : Collider(CT_MESH_COLLIDER) { vertices = vertices_; nVeritces = nVertices_; CreateGizmo(); SetBoundary(); } MeshCollider(Mesh* mesh) : Collider(CT_MESH_COLLIDER) { vertices = mesh -> GetVertices(); nVeritces = mesh -> GetNumberOfVertices(); SetBoundary(); } ~MeshCollider() { delete [] vertices; } glm::vec3 FindFurtherstPoint(glm::vec3 direction) const override { glm::vec3 maxPoint; float maxDist = -FLT_MAX; for(size_t i = 0;i < nVeritces; i++) { glm::vec3 vertexPos = vertices[i].position; vertexPos += entity -> getComponent<TransformComponent>().position; float distance = glm::dot(vertexPos, direction); if(distance > maxDist) { maxDist = distance; maxPoint = vertexPos; } } return maxPoint; } Vertex* GetVertices() { return vertices; } bool TestCollision(Collider* collider_) override; CollisionProduct * Solve(Collider * collider_) override; void CreateGizmo() override; void SetBoundary() override; }; #endif
//? React Imports import { useEffect, useState } from "react"; //? Custom hooks import useLocalStorage from "../CustomHooks/useLocalStorage"; // ? Style imports import styles from "./ThemeSwitcher.module.css"; // ? Library styles import { XMarkIcon, SunIcon, MoonIcon, SwatchIcon, } from "@heroicons/react/24/outline"; // TODO: //* 1) get bollerplate JSX setup(ONGOING) // * 2) get the light and dark theme toggle and theme switcher setup as well. const ThemeSwitcher = () => { // State variables const [hue, setHue] = useLocalStorage("react-todo.color", "240"); // ! if the user has dark preferences setup beforehand. const defaultDark = window.matchMedia("(prefers-color-scheme: dark)").matches; const [theme, setTheme] = useLocalStorage( "react-todo.theme", defaultDark ? "dark" : "light" ); const [isColorPicking, setIsColorPicking] = useState(false); // ? modifying the toggle between light and dark useEffect(() => { document.documentElement.setAttribute("color-scheme", theme); }, [theme]); // ? modifying the slider useEffect(() => { document.documentElement.style.setProperty("--_hue", hue); }, [hue]); return ( <aside className={styles.wrapper} style={{ backgroundColor: isColorPicking ? "hsl(var(--muted)/.6)" : "transparent", }} > {isColorPicking ? ( <> <button className={`btn ${styles.close}`} aria-label="Close color picking mode." onClick={() => setIsColorPicking(false)} > <XMarkIcon /> </button> <input className={styles.picker} type="range" min="0" max="360" aria-label="Change color theme slider." value={hue} onInput={(e) => setHue(e.target.value)} /> </> ) : ( <div className={styles.btns}> <button className="btn" aria-label={`Change theme to ${ theme === "light" ? "dark" : "light" } mode`} role="switch" onClick={() => setTheme(theme === "light" ? "dark" : "light")} > {theme === "dark" ? <SunIcon /> : <MoonIcon />} </button> <button className="btn" aria-label="Enable color picking mode." onClick={() => setIsColorPicking(true)} > <SwatchIcon /> </button> </div> )} </aside> ); }; export default ThemeSwitcher;
@extends('layouts.app') @section('title', 'Following Page') @section('content') @include('users.profile.header') <div style="margin-top: 100px"> @if ($user->following->isNotEmpty()) <div class="row justify-content-center"> <div class="col-4"> <h3 class="text-muted text-center">Following</h3> @foreach ($user->following as $follow) <div class="row justify-content-center mt-3"> <div class="col-auto"> {{-- Avatar/profile image --}} <a href="{{ route('profile.show', $follow->following->id) }}"> @if ($follow->following->avatar) <img src="{{ $follow->following->avatar }}" alt="{{ $follow->following->name }}" class="rounded-circle avatar-sm"> @else <i class="fa-solid fa-circle-user text-secondary icon-sm"></i> @endif </a> </div> <div class="col ps-0 text-truncate"> <a href="{{ route('profile.show', $follow->following->id) }}" class="text-decoration-none text-dark fw-bold">{{ $follow->following->name }}</a> </div> <div class="col-auto text-end"> @if ($follow->following->id != Auth::user()->id) @if ($follow->following->isFollowed()) <form action="{{ route('follow.destroy', $follow->following->id) }}" method="post"> @csrf @method('DELETE') <button type="submit" class="border-0 bg-transparent p-0 text-secondary btn-sm">Following</button> </form> @else <form action="{{ route('follow.store', $follow->following->id) }}" method="post"> @csrf <button type="submit" class="border-0 bg-transparent p-0 text-primary btn-sm">Follow</button> </form> @endif @endif </div> </div> @endforeach </div> </div> @else <h3 class="text-muted fw-bold text-center">No Following Yet</h3> @endif </div> @endsection
package com.marko590.raaprojekat.adapter import android.annotation.SuppressLint import android.os.Bundle import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.ImageView import android.widget.TextView import androidx.cardview.widget.CardView import androidx.navigation.NavController import androidx.navigation.Navigation import androidx.recyclerview.widget.RecyclerView import com.bumptech.glide.Glide import com.marko590.raaprojekat.R import com.marko590.raaprojekat.model.models.restaurants.Results import java.math.RoundingMode import java.text.DecimalFormat class FavoritesAdapter(private var dataset:ArrayList<Results>): RecyclerView.Adapter<FavoritesAdapter.ViewHolder>() { private var bundle: Bundle =Bundle() class ViewHolder(view: View) : RecyclerView.ViewHolder(view){ val restaurantName: TextView val restaurantRating:TextView val location:TextView val imageView: ImageView val card:CardView init{ location=view.findViewById(R.id.location) card=view.findViewById(R.id.cardContainer) imageView=view.findViewById(R.id.restaurantImage) restaurantRating=view.findViewById(R.id.restaurantRating) restaurantName=view.findViewById(R.id.restaurantName) } } override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder { val view=LayoutInflater.from(parent.context).inflate(R.layout.item_restaurant,parent,false) return ViewHolder(view) } override fun getItemCount(): Int { return dataset.size } override fun onBindViewHolder(holder: ViewHolder, position: Int) { val df = DecimalFormat("#.##") df.roundingMode=RoundingMode.DOWN val roundoff = df.format(dataset[position].score!!) holder.location.text=dataset[position].locationId holder.restaurantName.text=dataset[position].name holder.restaurantRating.text=roundoff.toString() if(dataset[position].images.size!=0) Glide.with(holder.imageView.context) .load(dataset[position].images[0].sizes?.original?.url) .skipMemoryCache(true)//for caching the image url in case phone is offline .into(holder.imageView) else{ holder.imageView.visibility=View.GONE } var navController: NavController? holder.card.setOnClickListener { bundle.putString("name",dataset[position].name) bundle.putString("snippet",dataset[position].snippet) if(dataset[position].images.size!=0){ bundle.putString("link", dataset[position].images[0].sizes!!.original!!.url) } else{ bundle.putString("link", "") } bundle.putDouble("score", dataset[position].score!!) bundle.putDouble("latitude", dataset[position].coordinates!!.latitude!!) bundle.putDouble("longitude", dataset[position].coordinates!!.longitude!!) navController = Navigation.findNavController(holder.restaurantName) navController!!.navigate(R.id.action_mainFragment_to_detailsFragment,bundle) } } @SuppressLint("NotifyDataSetChanged") fun updateUserList(datasetNew: ArrayList<Results>) { dataset.clear() dataset = datasetNew notifyDataSetChanged() } }
import { FC, useState } from 'react' import { Star } from '@mui/icons-material' import MenuIcon from '@mui/icons-material/Menu' import SearchIcon from '@mui/icons-material/Search' import { AppBar, Toolbar, Box, IconButton, Backdrop } from '@mui/material' import Image from 'next/image' import Link from 'next/link' import { useRouter } from 'next/router' import DrawerRight from '@/components/molecules/Drawer' import LinkWithIcon from '@/components/molecules/LinkWithIcon' import { BaseProps } from '@/types' type HeaderProps = BaseProps const Header: FC<HeaderProps> = ({ sx }) => { const router = useRouter() const [open, setOpen] = useState(false) const toggleDrawer = (open: boolean) => (event: React.KeyboardEvent | React.MouseEvent) => { if ( event && event.type === 'keydown' && ((event as React.KeyboardEvent).key === 'Tab' || (event as React.KeyboardEvent).key === 'Shift') ) { return } setOpen(open) } return ( <> <AppBar position="static" sx={sx}> <Toolbar> <Box sx={{ flexGrow: 1, ml: '0.5rem', '&:hover': { opacity: 0.7, }, }} > <Link href="/"> <Image src="/iNAZO_logo.png" alt="iNAZO logo" width={150} height={45} /> </Link> </Box> <LinkWithIcon href="/search" icon={<SearchIcon />} sx={{ mr: '1rem', opacity: 0.7, fontWeight: 600, display: { xs: 'none', sm: 'flex', }, ...(router.pathname === '/search' && { opacity: 1, }), }} > SEARCH </LinkWithIcon> <LinkWithIcon href="/bookmark" icon={<Star />} sx={{ mr: '1rem', opacity: 0.7, fontWeight: 600, display: { xs: 'none', sm: 'flex', }, ...(router.pathname === '/bookmark' && { opacity: 1, }), }} > BOOKMARK </LinkWithIcon> <IconButton color="inherit" aria-label="open drawer" edge="end" onClick={toggleDrawer(true)} sx={{ ...(open && { display: 'none' }), display: { sm: 'none' } }} > <MenuIcon /> </IconButton> </Toolbar> </AppBar> <DrawerRight open={open} toggleDrawer={toggleDrawer} /> <Backdrop sx={{ color: '#fff' }} open={open} onClick={toggleDrawer(false)} onKeyDown={toggleDrawer(false)} /> </> ) } export default Header
// // SliderBootcamp.swift // SwiftfulThinkingBootcamp // // Created by Putra Pebriano Nurba on 18/12/23. // import SwiftUI struct SliderBootcamp: View { @State private var sliderValue: Double = 0 @State private var colorChange: Color = .black @State private var storedAge: [Double] = [Double]() var body: some View { VStack { Text( // "\(sliderValue)" // "\(Int (sliderValue))" String(format: "%.0f", sliderValue) ) .foregroundColor(colorChange) // ForEach(storedAge, id: \.self) { items in // Text("age of kid is : \(Int(items))") // } // course material // Slider(value: $sliderValue) // Slider(value: $sliderValue, in: 0...100 ) // Slider( // value: $sliderValue, // in: 0...50, // step: 1.0 // ) Slider(value: $sliderValue, in: 0...100, step: 1.0, label: { Text("Slider Label") }, minimumValueLabel: { // bisa menaruh ui component disini Text("1") .foregroundColor(.mint) .fontWeight(.semibold) }, maximumValueLabel: { // bisa naro semua UIcomponent disini Text("100") .foregroundColor(.mint) .fontWeight(.semibold) }, onEditingChanged: { _ in commandSliderChange(color: .orange) }) .tint(Color.green) // Button("save") { //// saveUserCustomisations(item: sliderValue) // } // .buttonStyle(.borderedProminent) } .padding() } // func saveUserCustomisations(item: Double) { // storedAge.append(item) // // } func commandSliderChange(color: Color) { withAnimation(Animation.easeOut) { colorChange = color } } } struct SliderBootcamp_Previews: PreviewProvider { static var previews: some View { SliderBootcamp() } } // slider // Small Summary /* slider merupakan modider atau components dimana kita bisa scroll secara horizontal dimana didalam slider berisi content floating point. biasanya digunakan pada saat login untuk menetukan umur dari pengguna MACAM - MACAM SLIDER 1. Slider(value: T##Binding<BinaryFloatingPoint>) jadi binary floating point disini berguna untuk menetukan nilai awal dari slider, slider tipe ini tanpa batasan atas dan bawah dari slider 2. Slider(value: T##Binding<BinaryFloatingPoint>, in: T##ClosedRange<BinaryFloatingPoint>) jadi untuk binary floating point disini masih sama seperti sebelumnya, tetapi pada tipe ini terdatapat batasan yang akan menjadi batasan atas bawah dari slider. 3. Slider( value: T##Binding<BinaryFloatingPoint>, in: T##ClosedRange<BinaryFloatingPoint>, step: T##BinaryFloatingPoint, ) jadi untuk modifier value and in masih sama, teteapi disini dalam penambahannya bisa diatur. dimana kita bisa mengatur di parameter step dimana kita bisa sesuaikan dnegan kebututuhan. misalkan penambahan 1.0 / 2.0 / 1.5 based on user customisation 4. Slider(value: $sliderValue, in: 0..<100, step: 1.0, label: , minimumValueLabel: , maximumValueLabel: , nEditingChanged: { _ in }) jadi pada slider tipe ini terdapat label minimum value label, maximum value label. dan lain sebagainya. fungsi value, in, step masih sama. dan terdapat modifier baru 1. minimumValueLabel berfungsi untuk memberikan modifier diawal slider pada ui dan bisa memasukkan ui components disitu 2. maximumValueLabel berfungsi untuk memberikan modifier diakhir slider pada ui dan bisa memasukkan ui component disitu 2. onEditingChanged berfungsi untuk menambahkan argumen dimana dan apabila nilainya berubah maka siapa yang akan terdampak pada perubahannya 2. label saat ini belu kelihatan fungsinya disini dan label berfungsi untuk memberikan format atau memberikan different completions atau penyematan pada label */
import styles from './topProducts.module.css' import { PieChart, Pie, Sector, Cell, ResponsiveContainer } from 'recharts'; import React, { Suspense } from 'react' const TopProduct = () => { const data = [ { name: 'Group A', value: 400 }, { name: 'Group B', value: 300 }, { name: 'Group C', value: 300 }, ]; const COLORS = ['#98D89E', '#EE8484', '#F6DC7D']; return ( <div className={styles.container}> <div className={styles.header}> <h1 className={styles.title}>Top Products</h1> <p className={styles.date}>April - June 2023</p> </div> <div className={styles.pieChart}> <PieChart width={200} height={200} > <Pie data={data} cx={80} cy={70} innerRadius={40} outerRadius={60} fill="#8884d8" paddingAngle={0} dataKey="value" > {data.map((entry, index) => ( <Cell key={`cell-${index}`} fill={COLORS[index % COLORS.length]} /> ))} </Pie> </PieChart> <div className={styles.legendsDetails}> <div className={styles.legends}> <div className={styles.legend}> <p style={{backgroundColor: "#98D89E"}} className={styles.legendsDot}/> <div className={styles.nameAndPercValue}> <p className={styles.legendName}>Basic Tees</p> <p className={styles.perc}>55%</p> </div> </div> </div> <div className={styles.legends}> <div className={styles.legend}> <p style={{backgroundColor: "#F6DC7D"}} className={styles.legendsDot}/> <div className={styles.nameAndPercValue}> <p className={styles.legendName}>Custom Short Pants</p> <p className={styles.perc}>35%</p> </div> </div> </div> <div className={styles.legends}> <div className={styles.legend}> <p style={{backgroundColor: "#EE8484"}} className={styles.legendsDot}/> <div className={styles.nameAndPercValue}> <p className={styles.legendName}>Super Hoodies</p> <p className={styles.perc}>15%</p> </div> </div> </div> </div> </div> </div> ) } export default TopProduct
type TStorage = {[key: string]: string} export function createLocalStorageMock(storage: TStorage = {}) { const localStorageMock = (function () { let store: TStorage = storage return { getItem: jest.fn((key: string) => store[key] ?? null), setItem: jest.fn((key: string, value: string) => { store[key] = value.toString() }), removeItem: jest.fn((key: string) => { const result = key in store delete store[key] return result }), clear: jest.fn(() => { store = {} }), } })() Object.defineProperty(window, "localStorage", { value: localStorageMock, configurable: true, }) } export function createFetchMock(fetchMock: jest.SpyInstance) { Object.defineProperty(window, "fetch", { value: fetchMock, configurable: true, }) } export function deleteFetchMock() { delete (window as any).fetch } export function createAlertMock() { Object.defineProperty(window, "alert", { value: jest.fn(), configurable: true, }) }
import {Ingredient} from "../shared/ingredient"; import {v4 as uuidv4} from "uuid"; export class Recipe { get ingredients(): Ingredient[] { return this._ingredients; } set ingredients(value: Ingredient[]) { this._ingredients = value; } private _ingredients: Ingredient[]; get imagePath(): string { return this._imagePath; } set imagePath(value: string) { this._imagePath = value; } get description(): string { return this._description; } set description(value: string) { this._description = value; } get name(): string { return this._name; } set name(value: string) { this._name = value; } get id(): string { return this._id; } private _name: string private _description: string private _imagePath: string private readonly _id: string; constructor(name: string, description: string, image: string, ingredients:Ingredient[], id?:string) { this._id= id? id : uuidv4(); this._name = name this._description = description this._imagePath = image this._ingredients = ingredients } }
// Task 1: // дан список целых чисел.Подсчитать количество отрицательных элементов var arr = [2, 5, 9, 15, 0, 4, -9, -5 ]; var sum = 0; for (var i = 0; i < arr.length; i++) { if (arr[i] < 0){ sum++; } } console.log(sum); // Task 2: // дан список целый чисел. Получить новый список, состоящий из элементов старого списка, //циклически сдвинутых вправо на одну позицию. // Пример: [1, 2, 3], [3, 1, 2] var arr = [1, 2, 3] var k = 1; for (i = 0; i < k; i++) arr.unshift(arr.pop()); console.log(arr); // Task 3: // дан список целых чисел. Найти индекс и значение минимального элемента indexOfSmallest ([3, 2, 4, 1]); function indexOfSmallest(a) { let lowest = 0; let value = 0; for (var i = 1; i < a.length; i++) { if (a[i] < a[lowest]) lowest = i; value = a[i]; } console.log("index is: " + lowest + " value is: " + value); } // Task 4: // Дан массив целых чисел. Необходимо удалить все четные числа let arr = [2, 5, 9, 15, 0, 4, -9, -5 ]; var withoutEven = 0; for (var i = 0; i < arr.length; i++) { if (arr[i] % 2 !== 0){ withoutEven = `${withoutEven},${arr[i]}`; } } console.log(withoutEven); // Task 5: // Дан массив целых чисел. Необходимо вычислить сумму целых положительных чисел let arr = [2, 5, 9, 15, 3.5, 4, -9, -5 ]; var sumPositive = 0; for (var i = 0; i < arr.length; i++) { if (arr[i] > 0 && Number.isInteger(arr[i])){ sumPositive = `${sumPositive},${arr[i]}`; } } console.log(sumPositive.match(/\-?\d+/g).reduce((sum, el) => sum + +el, 0)); // Task 6: // Напишите функцию сортировки пузырьком для массива целых чисел const bubbleSort = (coll) => { let stepsCount = coll.length - 1; // Значение переменной swapped показывает был ли // совершен обмен элементов во время перебора массива let swapped; do { swapped = false; // Перебираем массив for (let i = 0; i < stepsCount; i += 1) { // и меняем местами элементы, если предыдущий больше, чем следующий if (coll[i] > coll[i + 1]) { const temp = coll[i]; coll[i] = coll[i + 1]; coll[i + 1] = temp; // Если была совершена перестановка, присваиваем swapped значение true swapped = true; } } // Уменьшаем счетчик на 1, т.к. самый большой элемент уже находится // в конце массива stepsCount -= 1; } while (swapped); // продолжаем, пока swapped === true return coll; }; console.log(bubbleSort([3, 2, 10, -2, 0])); // Task 7: // Напишите функцию, которая возвращает произведение всех отрицательных чисел в массиве // Написать решение в 1-у строку let arr = [2, 5, 9, 15, 3.5, 4, -9, -5, -3 ]; var sumNegative = 1; for (var i = 0; i < arr.length; i++) { if (arr[i] < 0 && Number.isInteger(arr[i])){ sumNegative = sumNegative * arr[i]; } } console.log(sumNegative); // Task 8: // Дан массив целых чисел. Напишите функцию, которая проверяет есть ли в нем два одинаковых числа подряд. function check(a) { for (var q = 1; q < a.length; ++q) { if (a[q] === a[q - 1]) { return true; } } return false; } console.log(check([3, 1, 1, 12]) ? "true" : "false"); // Task 9: // Дан массив с числами. Не используя метода reverse переверните его элементы в обратном порядке. var arr = [1, 2, 3, 4, 5]; for (var i = arr.length - 1; i >= 0; i--) { console.log(arr[i]); } // Task 10: // Дан массив с числами. Выведите последовательно его элементы используя рекурсию и не используя цикл var arr = [1, 2, 3, 4, 5]; for (var i = 0; i <= arr.length; i++) { console.log(arr[i]); } // Task 11: // Дан массив строк. Отсортируйте строки в алфавитном порядке var arr = ['apple', 'orange', 'pineapple', 'banan']; console.log(arr.sort()) // Task 12: // Напишите функцию сортировки со вставками для массива целых чисел // Task 13: // Дан массив с числами. Напишите функцию, которая вставляет число на место N в массиве let arr = [1, 2, 5]; // начиная с индекса -1 (перед последним элементом) // удалить 0 элементов, // затем вставить числа 3 и 4 arr.splice(-1, 0, 3, 4); console.log( arr ); // Task 14: // Дан массив с числами. Напишите функцию, которая удаляет число на месте N в массиве let arr = [1, 2, 3]; console.log( arr.splice(0, 2) ); // Task 15: // Дан массив с числами. Напишите функцию, которая находит второй наименьший элемент в массиве. let arr = [4, 1, 2, 3]; let sort = arr.sort() console.log(sort[1]) // Task 16: // Даны 2 массива. Напишите функцию, которая возвращает массив, который содержит разницу между 2-мя массивами let firstArr = [4, 1, 2, 3]; let secondArr = [4, 5, 6, 3]; var difference1 = firstArr.filter(x => secondArr.indexOf(x) === -1); var difference2 = secondArr.filter(x => firstArr.indexOf(x) === -1); const all = [...difference1, ...difference2] console.log(all); // Task 17: // Напишите функцию, которая клонирует заданный массив let arr = [4, 1, 2, 3]; var clone = arr.slice(0); console.log(clone); // Task 18: // Напишите функцию, которая удаляет повторяющиеся элементы массива let arr = [4, 1, 1, 2, 3]; function removeDuplicates(arr) { return [...new Set(arr)]; //Эта функция использует объект Set, который хранит только уникальные значения, //и затем преобразует его обратно в массив, используя оператор расширения .... } console.log(removeDuplicates(arr)); // Task 19: // Даны 2 массива. Напишите функцию, которая возвращает объедененный массив, который не содержит дублированных элементов let firstArr = [4, 1, 2, 3]; let secondArr = [4, 5, 6, 3]; const all = [...firstArr, ...secondArr] function removeDuplicates(all) { return [...new Set(all)]; } console.log(removeDuplicates(all)); // Task 20: // Дан массив с числами. Выведите массив, который содержит квадраты всех элементов let firstArr = [4, 1, 2, 3]; const map = firstArr.map(x => x ** 2); console.log(map); // Task 21: // Напишите функцию, которая очищает массив от ложных значений: false, null, undefined, 0, –0, NaN и "" let arr = [4, 1, NaN, 2, null, 3, 0]; function cleanArray(arr) { return arr.filter(Boolean); } console.log(cleanArray(arr)); // Task 22: // Дан массив объектов. Напишите функцию, которая отсортирует массив объектов book по значению свойства title. // books = [ // { author: "Хэленка", title: "Улетела" }, // { author: "Коул", title: "Аркан" }, // { author: "Райчел М", title: "Золотая" }, // ]; books = [ { author: "Хэленка", title: "Улетела" }, { author: "Коул", title: "Аркан" }, { author: "Райчел М", title: "Золотая" }, ]; function byField(field) { return (a, b) => a[field] > b[field] ? 1 : -1; } books.sort(byField('title')); books.forEach(book => console.log(book.title)); // Task 23: // Дан массив объектов. Напишите функцию, которая принимает название свойства и возвращает массив, // который содержит все значения данного свойства. !! Предусмотреть ситуацию, когда такое свойство не найдено // books = [ // { author: "Хэленка", title: "Улетела" }, // { author: "Коул", title: "Аркан" }, // { author: "Райчел М", title: "Золотая" }, // ]; const books = [ { author: "Хэленка", title: "Улетела" }, { author: "Коул", title: "Аркан" }, { author: "Райчел М", title: "Золотая" }, ]; function getPropValues(books, propName) { const propValues = books.map(book => book[propName]).filter(value => value !== undefined); if (propValues.length === 0) { console.log(`Свойство "${propName}" не найдено`); } return propValues; } const authors = getPropValues(books, "author"); console.log(authors); // ["Хэленка", "Коул", "Райчел М"] const genres = getPropValues(books, "genre"); // Свойство "genre" не найдено console.log(genres); // [] // Task 24: // Дан массив. Напишите функцию, которая удаляет все вхождения значения N // Task 25: // Дан массив. Напишите функцию, которая возвращает случайный элемент из массива let arr = [4, 1, 2, 3, 0]; var rand = Math.floor(Math.random() * arr.length); console.log(arr[rand]); // Task 26: // Напишите функцию, которая возвращает случайный элемент из массива let arr = [4, 1, 2, 3, 0]; function arrayRandElement(arr) { var rand = Math.floor(Math.random() * arr.length); return arr[rand]; } console.log(arrayRandElement(arr)); // Task 27: // Напишите функцию, которая перемещает элемент из позиции N в позиции M let arr = [4, 1, 2, 3, 0]; function moveElement(arr, from, to) { arr.splice(to,0,arr.splice(from,1)[0]); return arr; } console.log(moveElement(arr, 1, 3)); // Task 28: // Напишите функцию, которая возвращает массив c заданной длинной из случайных чисел от N до M let arr = [4, 1, 2, 3, 0]; function chooseElement(arr, from, to) { let removed = arr.splice(from, to); return removed; } let removedElements = chooseElement(arr, 1, 3); console.log(removedElements); // [1, 2, 3] // Task 29: // Дан массив строк. Напишите функцию, которая возвращает массив длин строк. let arr = ['Яблоко', 'Банан']; function getStringsLengths(arr){ return map = arr.map(x => x.length); } console.log(getStringsLengths(arr)); // Task 30: // Дана строка слов. Напишите функцию, которая возвращает массив из первых букв . let arr = ['Яблоко', 'Банан']; function getFirstLetter(arr){ return map = arr.map(x => x[0]); } console.log(getFirstLetter(arr)); // Task 31: // Напишите функцию, которая проверяет, является ли значение массивом или нет let arr = ['Яблоко', 'Банан']; function isArray(arr) { return Array.isArray(arr); } console.log(isArray(arr)); // Task 32: //Напишите функцию, которая находит наиболее частый элемент массива // Результат в виде: "элемент = 'B' встречается 5 раз" // Учтите различие в слове "раз": 2 раза, 3 раза, 6 раз .... function mostCommonElement(arr) { let counter = {}; let maxCount = 0; let mostCommon = null; for (let i = 0; i < arr.length; i++) { let elem = arr[i]; if (counter[elem] == null) { counter[elem] = 1; } else { counter[elem]++; } if (counter[elem] > maxCount) { maxCount = counter[elem]; mostCommon = elem; } } if (maxCount === 1) { return `элемент = '${mostCommon}' встречается 1 раз`; } else if (maxCount % 10 === 1 && maxCount !== 11) { return `элемент = '${mostCommon}' встречается ${maxCount} раз`; } else if (2 <= maxCount % 10 && maxCount % 10 <= 4 && !(12 <= maxCount % 100 && maxCount % 100 <= 14)) { return `элемент = '${mostCommon}' встречается ${maxCount} раза`; } else { return `элемент = '${mostCommon}' встречается ${maxCount} раз`; } } // Task 33: // Напишите функцию, которая удаляет дублирующие элементы из массива let firstArr = [4, 1, 2, 4, 3]; function removeDuplicates(firstArr) { return [...new Set(firstArr)]; } console.log(removeDuplicates(firstArr)); // Task 34: // Найдите високосные годы в заданном диапазоне лет function findLeapYears(startYear, endYear) { let leapYears = []; for (let year = startYear; year <= endYear; year++) { if ((year % 4 == 0 && year % 100 != 0) || year % 400 == 0) { leapYears.push(year); } } return leapYears; } // Task 35: // Напишите функцию, которая заполняет новый массив предоставленным значением. // Описание задачи: Напишите функцию, которая заполняет новый массив предоставленным значением. // Например: (3, 'a') => ['a', 'a', 'a'] function fillArray(length, value) { return Array(length).fill(value); } console.log(fillArray(3, "a")) // Task 36: // Напишите функцию, которая сравнивает два массива и возвращает true, если они идентичны. var first = [ 1, [3, 4, 5] ]; var second = [ 1, 2, [3, 4, 5] ]; var isEqual = JSON.stringify(first) === JSON.stringify(second); // преобразование в строку json console.log(isEqual); // Task 37: // Напишите функцию, которая преобразует глубокий массив в одномерный. // Например: [1, 2, [3, 4, [5]]] => [1, 2, 3, 4, 5] const arr = [1, 2, [3, 4, [5, 6]]]; function flatDeep(arr, d = 1) { return d > 0 ? arr.reduce((acc, val) => acc.concat(Array.isArray(val) ? flatDeep(val, d - 1) : val), []) : arr.slice(); }; console.log(flatDeep(arr, Infinity)); // Task 38: // Напишите функцию, которая разделяет массив на части заданного размера // Например: ([1, 2, 3, 4, 5], 2) => [[1, 2], [3, 4], [5]] const arr = [1, 2, 3, 4, 5, 6]; let newArr = []; function divideArray(arr, number) { for (let i = 0; i < arr.length; i += number) { let subArr = []; for (let j = i; j < i + number && j < arr.length; j++) { subArr.push(arr[j]); } newArr.push(subArr); } return newArr; } console.log(divideArray(arr, 4)); // Task 39: // Напишите функцию, которая находит среднее арифметическое всех значений в массиве let arr = [2, 5, 9, 15, 4, 9, 5 ]; var sumPositive = 0; let number = 0; for (var i = 0; i <= arr.length; i++) { sumPositive = `${sumPositive},${arr[i]}`; number ++; } let averageNumber = (sumPositive.match(/\-?\d+/g).reduce((sum, el) => sum + +el, 0))/ number console.log(averageNumber); // Task 40: // Напишите функцию, которая находит количество элементов между максимальным и минимальным элементом. indexOfArray ([6, 4, 1, 5 ]); function indexOfArray(a) { let lowest = 0; let value = 0; let biggest = 0; let value2 = 0; for (var i = 1; i < a.length; i++) { if (a[i] < a[lowest]) lowest = i; value = a[i]; } for (var i = 1; i < a.length; i++) { if (a[i] > a[biggest]){ biggest = i; value2 = a[i]; } } if (biggest > lowest) { console.log ((Math.abs(biggest - lowest)) - 1)} else (console.log (Math.abs(biggest - lowest)) ) } // Task 41: // Напишите функцию, которая принимает 2 массива и возвращает true если количество элементов в первом массиве больше второго var first = [ 1, 2,[3, 4, 5, 6] ]; var second = [ 1, 2, [3, 4, 5] ]; function flatDeep(first, d = 1) { return d > 0 ? first.reduce((acc, val) => acc.concat(Array.isArray(val) ? flatDeep(val, d - 1) : val), []) : first.slice(); }; function flatDeepSecond(second, d = 1) { return d > 0 ? second.reduce((acc, val) => acc.concat(Array.isArray(val) ? flatDeepSecond(val, d - 1) : val), []) : second.slice(); }; var flattenedFirst = flatDeep(first); var flattenedSecond = flatDeepSecond(second); function isBigger(flattenedFirst, flattenedSecond){ if (flattenedFirst.length > flattenedSecond.length){ return true; } else {return false}; } console.log(isBigger(flattenedFirst, flattenedSecond)); // Task 42: // Напишите функцию, которая принимает 2 аргумента и возвращает true если element есть среди элементов массива и false в ином случае. var arr = [ 1, 2,[3, 4, 5, 6] ]; function isInArray(arr, num) { for (var i = 0; i <= arr.length; i++) { if (num === arr[i]){ return true; } } return false } console.log(isInArray(arr, 2)); // Task 43: // Дан массив. Напишите функцию, которая уменьшить на число А все его элементы var arr = [ 1, 2,3, 4, 5, 6 ]; var newArray = []; function reduceElement(arr, num) { for (var i = 0; i < arr.length; i++) { newArray.push(arr[i] - num); } return newArray; } console.log(reduceElement(arr, 10)); // Task 44: // В массиве хранятся сведения о количестве осадков, выпавших за каждый день января. Определить общее количество осадков за январь. // Не использовать цикл var arr = [ 1, 2,3, 4, 5, 6, 9 ]; let precipitation = arr.reduce(function(previousVal, currentVal) { return previousVal + currentVal; }, 0); console.log(precipitation); // Task 45: // В массиве хранится информация о массе каждого из 30 предметов, загружаемых в грузовой автомобиль, //грузоподъемность которого известна. Определить, не превышает ли общая масса всех предметов грузоподъемность автомобиля. // Не использовать цикл let arr = [ 1, 2,3, 4, 5, 6, 9 ]; let rubbleLifting = 35; let arrLiftingSum = arr.reduce(function(previousVal, currentVal) { return previousVal + currentVal; }, 0); function checkLiftingCapacity(arrSum, rubbleLifting) { return arrSum < rubbleLifting ? true : false; } console.log(checkLiftingCapacity(arrLiftingSum, rubbleLifting)); // Task 46: //Рост 22 учеников класса представлен в виде массива. Рост мальчиков условно задан отрицательными числами. //Определить средний рост мальчиков и средний рост девочек. // Не использовать цикл let arr = [ 1, 2, 3, 4, 5, 6, 7, 8, 9, 9, 9, -1, -2, -3, -4, -5, -6, -7, -8, -9, -9, -9 ]; let isPositiveCount = 0; let isNegativeCount = 0; function countPositive(arr) { for (var i = 0; i < arr.length; i++) { if (arr[i] > 0) { isPositiveCount++; } } } function countNegative(arr) { for (var i = 0; i < arr.length; i++) { if (arr[i] < 0) { isNegativeCount++; } } } countPositive(arr); countNegative(arr); let sumPositive = 0; let sumNegative = 0; for (var i = 0; i < arr.length; i++) { if (Number.isInteger(arr[i]) && arr[i] > 0) { sumPositive += arr[i]; } else if (Number.isInteger(arr[i]) && arr[i] < 0) { sumNegative += arr[i]; } } let girlAverage = sumPositive / isPositiveCount let boyAverage = sumNegative / isNegativeCount console.log(girlAverage.toFixed(2), Math.abs(boyAverage.toFixed(2))); // Task 47: // Дан одномерный массив из 20 элементов. //Напишите функцию, которая вернет массив из первых трех и последних трех элементов, сохранив порядок их следования. // Не использовать цикл let arr = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20]; function firstLastThreeCharacters(arr) { let first = ""; let last = ""; for (var i = 0; i < arr.length; i++) { if (i < 3) { if (arr[i] < arr[first] || first === "") { first = i; } } else if (i >= arr.length - 3) { if (arr[i] < arr[last] || last === "") { last = i; } } } return `${arr[first]},${arr[last-2]},${arr[last-1]},${arr[last]}`; } console.log(firstLastThreeCharacters(arr)); // Task 48: //Удалить из массива максимальный элемент let arr = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]; function indexOfBiggest(arr) { let biggest = 0; let value = arr[0]; for (var i = 1; i < arr.length; i++) { if (arr[i] > arr[biggest]) { biggest = i; value = arr[biggest]; } } const index = arr.indexOf(biggest); if (index!== -1) { return arr.splice(0, biggest); } } console.log(indexOfBiggest(arr)); // Task 49 // Дан массив // ['| Sofia | 300', '| Veliko Tarnovo | 500', '| Yambol | 275'] // Напишите функцию, которая выводит "Sofia, Veliko Tarnovo, Yambol = 1075" var arr = ['Sofia', 300, 'Veliko Tarnovo', 500, 'Yambol', 275]; var numbers = arr.filter(function(number) { return !isNaN(Number(number)); }); let totalNumber = numbers.reduce((acc, curr) => acc + curr, 0); let stringNumbers = numbers.join(','); let stringNoNumbers = arr.filter(function(word) { return isNaN(Number(word)); }).join(', '); console.log(stringNoNumbers + " = " + totalNumber); // Task 50 // Напишите функцию, которая из массива с покупками и их ценами выводит следующее сообщение // You purchased Beer Zagorka, Tripe soup, Lasagna for a total sum of 16.14 // Входной массив выглядит: ['Beer Zagorka', '2.65', 'Tripe soup', '7.80','Lasagna', '5.69'] var arr = ['Beer Zagorka', '2.65', 'Tripe soup', '7.80','Lasagna', '5.69']; var numbers = arr.filter(function(number) { return !isNaN(Number(number)); }); let numbersInt = numbers.map(string => +string); let totalNumber = numbersInt.reduce((acc, curr) => acc + curr, 0); let stringNumbers = numbersInt.join(','); let stringNoNumbers = arr.filter(function(word) { return isNaN(Number(word)); }).join(', '); console.log("You purchased " + stringNoNumbers + " for a total sum of " + totalNumber); function generateUsernames(emails) { let usernames = []; for (let email of emails) { let [username, domain] = email.split('@'); username = username.replace('.', '').replace('_', ''); let domainParts = domain.split('.'); if (domainParts.length > 1) { domain = domainParts[0]; } usernames.push(username + '.' + domain); } return usernames; } console.log(generateUsernames(['peshoo@gmail.com', 'todor_43@mail.dir.bg', 'foo@bar.com'])) // Task 52 //Напишите функцию, которая будет подвергать цензуре новостные статьи. //Вам будет предоставлен текст, а затем список строк, которые необходимо вычеркнуть из текста. //Замените все вхождения строк дефисами той же длины, что и строка. // ['roses are red, violets are blue', ' , violets are', ' red'] => "roses are ---------------- blue" function censorText(text, words) { for (let word of words) { let censor = '-'.repeat(word.length); text = text.replace(word, censor); } return text; } let text = 'roses are red, violets are blue'; let words = [', violets are', 'red']; let censoredText = censorText(text, words); console.log(censoredText);
Litecoingreen Core Setup --------------------- Litecoingreen Core is the original Litecoingreen client and it builds the backbone of the network. It downloads and, by default, stores the entire history of Litecoingreen transactions, which requires approximately 22 gigabytes of disk space. Depending on the speed of your computer and network connection, the synchronization process can take anywhere from a few hours to a day or more. To download Litecoingreen Core, visit [litecoingreen.org](https://litecoingreen.org/). Running --------------------- The following are some helpful notes on how to run Litecoingreen Core on your native platform. ### Unix Unpack the files into a directory and run: - `bin/litecoingreen-qt` (GUI) or - `bin/litecoingreend` (headless) ### Windows Unpack the files into a directory, and then run litecoingreen-qt.exe. ### macOS Drag Litecoingreen Core to your applications folder, and then run Litecoingreen Core. ### Need Help? * See the documentation at the [Litecoingreen Wiki](https://litecoingreen.info/) for help and more information. * Ask for help on [#litecoingreen](http://webchat.freenode.net?channels=litecoingreen) on Freenode. If you don't have an IRC client use [webchat here](http://webchat.freenode.net?channels=litecoingreen). * Ask for help on the [LitecoingreenTalk](https://litecoingreentalk.io/) forums, in the [Technical Support section](https://litecoingreentalk.io/c/technical-support). Building --------------------- The following are developer notes on how to build Litecoingreen Core on your native platform. They are not complete guides, but include notes on the necessary libraries, compile flags, etc. - [Dependencies](dependencies.md) - [macOS Build Notes](build-osx.md) - [Unix Build Notes](build-unix.md) - [Windows Build Notes](build-windows.md) - [FreeBSD Build Notes](build-freebsd.md) - [OpenBSD Build Notes](build-openbsd.md) - [NetBSD Build Notes](build-netbsd.md) - [Gitian Building Guide (External Link)](https://github.com/bitcoin-core/docs/blob/master/gitian-building.md) Development --------------------- The Litecoingreen repo's [root README](/README.md) contains relevant information on the development process and automated testing. - [Developer Notes](developer-notes.md) - [Productivity Notes](productivity.md) - [Release Notes](release-notes.md) - [Release Process](release-process.md) - [Translation Process](translation_process.md) - [Translation Strings Policy](translation_strings_policy.md) - [JSON-RPC Interface](JSON-RPC-interface.md) - [Unauthenticated REST Interface](REST-interface.md) - [Shared Libraries](shared-libraries.md) - [BIPS](bips.md) - [Dnsseed Policy](dnsseed-policy.md) - [Benchmarking](benchmarking.md) ### Resources * Discuss on the [LitecoingreenTalk](https://litecoingreentalk.io/) forums. * Discuss general Litecoingreen development on #litecoingreen-dev on Freenode. If you don't have an IRC client use [webchat here](http://webchat.freenode.net/?channels=litecoingreen-dev. ### Miscellaneous - [Assets Attribution](assets-attribution.md) - [bitcoin.conf Configuration File](bitcoin-conf.md) - [Files](files.md) - [Fuzz-testing](fuzzing.md) - [Reduce Traffic](reduce-traffic.md) - [Tor Support](tor.md) - [Init Scripts (systemd/upstart/openrc)](init.md) - [ZMQ](zmq.md) - [PSBT support](psbt.md) License --------------------- Distributed under the [MIT software license](/COPYING). This product includes software developed by the OpenSSL Project for use in the [OpenSSL Toolkit](https://www.openssl.org/). This product includes cryptographic software written by Eric Young ([eay@cryptsoft.com](mailto:eay@cryptsoft.com)), and UPnP software written by Thomas Bernard.
package com.android.data.vendors.repo import androidx.paging.PagingSource import androidx.paging.PagingState import com.android.data.vendors.mapper.VendorsDomainMapper import com.android.domain.vendors.model.VendorsDomainModel import com.android.data.vendors.service.VendorsService class VendorsPagingSource ( private val vendorId: String? = null, private val searchKey: String? = null, private val service: VendorsService ) : PagingSource<Int, VendorsDomainModel>() { override suspend fun load(params: LoadParams<Int>): LoadResult<Int, VendorsDomainModel> { return try { val position = params.key ?: 0 val response = service.getVendors( position, vendorId, searchKey ).data?.vendors?.map { dto -> VendorsDomainMapper.toDomain(dto) }.orEmpty() LoadResult.Page( data = response, prevKey = if (position == 0) null else position - 1, nextKey = if (response.isEmpty()) null else position + 1 ) } catch (e: Exception) { LoadResult.Error(e) } } override fun getRefreshKey(state: PagingState<Int, VendorsDomainModel>): Int? { return state.anchorPosition?.let { anchorPosition -> state.closestPageToPosition(anchorPosition)?.prevKey?.plus(1) ?: state.closestPageToPosition(anchorPosition)?.nextKey?.minus(1) } } }
<script lang="ts" setup> import { useI18n } from 'vue-i18n' import { catHots, catNewRecommend } from '@/api/podcast' import type { Podcast } from '@/types' const { t } = useI18n() const props = defineProps<{ categoryId: number | string categoryName: string }>() const podcasts = reactive<{ hots: Podcast[] recommends: Podcast[] }>({ hots: [], recommends: [], }) const loading = ref(false) const tab = ref(0) watchEffect(() => { fetch(+props.categoryId) }) async function fetch(categoryId: number) { loading.value = true const [{ djRadios: hots }, { djRadios: recommends }] = await Promise.all([ catHots(categoryId), catNewRecommend(categoryId), ]) podcasts.hots = hots podcasts.recommends = recommends loading.value = false } </script> <template> <div class="d-flex flex-column gap-4"> <span class="text-h5 font-weight-bold"> 播客-{{ categoryName }} </span> <v-tabs v-model="tab" color="secondary" align-tabs="end"> <v-tab :value="0" class="rounded-t-md">热门播客</v-tab> <v-tab :value="1" class="rounded-t-md">新播客推荐</v-tab> </v-tabs> <v-window v-model="tab"> <v-window-item :value="0"> <card-row> <podcast-cover v-for="item in podcasts.hots" :key="item.id" :data="item" /> </card-row> </v-window-item> <v-window-item :value="1"> <card-row> <podcast-cover v-for="item in podcasts.recommends" :key="item.id" :data="item" /> </card-row> </v-window-item> </v-window> </div> </template>
from aviary.mission.phase_builder_base import PhaseBuilderBase from aviary.mission.initial_guess_builders import InitialGuessState, InitialGuessIntegrationVariable, InitialGuessControl from aviary.utils.aviary_values import AviaryValues from aviary.variable_info.variables import Dynamic from aviary.variable_info.enums import SpeedType from aviary.mission.gasp_based.ode.descent_ode import DescentODE class DescentPhase(PhaseBuilderBase): default_name = 'descent_phase' default_ode_class = DescentODE _meta_data_ = {} _initial_guesses_meta_data_ = {} def build_phase(self, aviary_options: AviaryValues = None): phase = self.phase = super().build_phase(aviary_options) # Retrieve user options values user_options = self.user_options input_speed_type = user_options.get_val('input_speed_type') EAS_limit = user_options.get_val('EAS_limit', units='kn') # Add states self.add_altitude_state(user_options) self.add_mass_state(user_options) self.add_distance_state(user_options) # Add boundary constraint self.add_altitude_constraint(user_options) # Add parameter if necessary if input_speed_type == SpeedType.EAS: phase.add_parameter("EAS", opt=False, units="kn", val=EAS_limit) # Add timeseries outputs phase.add_timeseries_output( Dynamic.Mission.MACH, output_name=Dynamic.Mission.MACH, units="unitless") phase.add_timeseries_output("EAS", output_name="EAS", units="kn") phase.add_timeseries_output("TAS", output_name="TAS", units="kn") phase.add_timeseries_output(Dynamic.Mission.FLIGHT_PATH_ANGLE, output_name=Dynamic.Mission.FLIGHT_PATH_ANGLE, units="deg") phase.add_timeseries_output("alpha", output_name="alpha", units="deg") phase.add_timeseries_output("theta", output_name="theta", units="deg") phase.add_timeseries_output("aero.CL", output_name="CL", units="unitless") phase.add_timeseries_output( Dynamic.Mission.THRUST_TOTAL, output_name=Dynamic.Mission.THRUST_TOTAL, units="lbf") phase.add_timeseries_output("aero.CD", output_name="CD", units="unitless") return phase def _extra_ode_init_kwargs(self): """ Return extra kwargs required for initializing the ODE. """ # TODO: support external_subsystems and meta_data in the base class return { 'input_speed_type': self.user_options.get_val('input_speed_type'), 'mach_cruise': self.user_options.get_val('mach_cruise'), 'EAS_limit': self.user_options.get_val('EAS_limit', 'kn'), } # Adding metadata for the DescentPhase DescentPhase._add_meta_data( 'analytic', val=False, desc='this is an analytic phase (no states).') DescentPhase._add_meta_data( 'reserve', val=False, desc='this phase is part of the reserve mission.') DescentPhase._add_meta_data( 'target_distance', val={}, desc='the amount of distance traveled in this phase added as a constraint') DescentPhase._add_meta_data( 'target_duration', val={}, desc='the amount of time taken by this phase added as a constraint') DescentPhase._add_meta_data('fix_initial', val=False) DescentPhase._add_meta_data('input_initial', val=False) DescentPhase._add_meta_data('EAS_limit', val=0, units='kn') DescentPhase._add_meta_data('mach_cruise', val=0) DescentPhase._add_meta_data('input_speed_type', val=SpeedType.MACH) DescentPhase._add_meta_data('final_altitude', val=0, units='ft') DescentPhase._add_meta_data('duration_bounds', val=(0, 0), units='s') DescentPhase._add_meta_data('duration_ref', val=1, units='s') DescentPhase._add_meta_data('alt_lower', val=0, units='ft') DescentPhase._add_meta_data('alt_upper', val=0, units='ft') DescentPhase._add_meta_data('alt_ref', val=1, units='ft') DescentPhase._add_meta_data('alt_ref0', val=0, units='ft') DescentPhase._add_meta_data('alt_defect_ref', val=None, units='ft') DescentPhase._add_meta_data('alt_constraint_ref', val=None, units='ft') DescentPhase._add_meta_data('mass_lower', val=0, units='lbm') DescentPhase._add_meta_data('mass_upper', val=0, units='lbm') DescentPhase._add_meta_data('mass_ref', val=1, units='lbm') DescentPhase._add_meta_data('mass_ref0', val=0, units='lbm') DescentPhase._add_meta_data('mass_defect_ref', val=None, units='lbm') DescentPhase._add_meta_data('distance_lower', val=0, units='NM') DescentPhase._add_meta_data('distance_upper', val=0, units='NM') DescentPhase._add_meta_data('distance_ref', val=1, units='NM') DescentPhase._add_meta_data('distance_ref0', val=0, units='NM') DescentPhase._add_meta_data('distance_defect_ref', val=None, units='NM') DescentPhase._add_meta_data('num_segments', val=None, units='unitless') DescentPhase._add_meta_data('order', val=None, units='unitless') # Adding initial guess metadata DescentPhase._add_initial_guess_meta_data( InitialGuessIntegrationVariable(), desc='initial guess for time options') DescentPhase._add_initial_guess_meta_data( InitialGuessState('altitude'), desc='initial guess for altitude state') DescentPhase._add_initial_guess_meta_data( InitialGuessState('mass'), desc='initial guess for mass state') DescentPhase._add_initial_guess_meta_data( InitialGuessState('distance'), desc='initial guess for distance state') DescentPhase._add_initial_guess_meta_data( InitialGuessControl('throttle'), desc='initial guess for throttle')
/* * misc_example.c * * Simple Misc Driver depending on an external symbol * * Copyright (C) 2014 Nick Glynn * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ #include <linux/miscdevice.h> #include <linux/fs.h> #include <linux/kernel.h> #include <linux/module.h> static int sample_open(struct inode *inode, struct file *file) { pr_info("I have been awoken\n"); return 0; } static int sample_close(struct inode *inodep, struct file *filp) { pr_info("Sleepy time\n"); return 0; } static ssize_t sample_write(struct file *file, const char __user *buf, size_t len, loff_t *ppos) { pr_info("Yummy - I just ate %d bytes\n", len); return len; /* But we don't actually do anything with the data */ } static const struct file_operations sample_fops = { .owner = THIS_MODULE, .write = sample_write, .open = sample_open, .release = sample_close, .llseek = no_llseek, }; struct miscdevice sample_device = { .minor = MISC_DYNAMIC_MINOR, .name = "simple_misc", .fops = &sample_fops, }; extern void call_out(void); static int __init misc_init(void) { int error; error = misc_register(&sample_device); if (error) { pr_err("can't misc_register :(\n"); return error; } /* Symbol used from different module */ call_out(); pr_info("I'm in\n"); return 0; } static void __exit misc_exit(void) { misc_deregister(&sample_device); pr_info("I'm out\n"); } module_init(misc_init) module_exit(misc_exit) MODULE_DESCRIPTION("Simple Misc Driver depending on external symbol"); MODULE_AUTHOR("Nick Glynn <nick.glynn@feabhas.com>"); MODULE_LICENSE("GPL");
import { SendIcon } from 'lucide-react' import { Button } from '../ui/button' import { Textarea } from '../ui/textarea' import { useContext, useRef } from 'react' import { ChatContext } from './ChatContext' export default function ChatInput({ isDisabled }: { isDisabled?: boolean }) { const { addMessage, handleInputChange, isLoading, message } = useContext(ChatContext) const textAreaRef = useRef<HTMLTextAreaElement | null>(null) return ( <div className='absolute bottom-0 left-0 w-full'> <form className='mx-2 flex flex-row gap-3 md:last:mb-6 lg:mx-auto lg:max-w-2xl xl:max-w-3xl'> <div className="relative flex h-full flex-1 items-stretch md:flex-col"> <div className="relative flex flex-col w-full flex-grow p-4"> <div className="relative"> <Textarea rows={1} maxRows={4} autoFocus placeholder='Enter your prompt text' className='resize-none pr-12 text-base py-3 scrollbar-thumb-blue scrollbar-thumb-rounded scrollbar-track-blue-lighter scrollbar-w-2 scrolling-touch' onChange={handleInputChange} value={message} ref={textAreaRef} onKeyDown={(e) => { if (e.key === 'Enter' && !e.shiftKey) { e.preventDefault(); addMessage() textAreaRef.current?.focus(); } }} /> <Button disabled={isLoading || isDisabled || message === ''} className='absolute bottom-1.5 right-[8px]' aria-label='Send Message' type='submit' onClick={(e) => { e.preventDefault(); addMessage() textAreaRef.current?.focus(); }} > <SendIcon className='h-4 w-4' /> </Button> </div> </div> </div> </form> </div> ) }
import * as React from "react"; import InputLabel from "@mui/material/InputLabel"; import MenuItem from "@mui/material/MenuItem"; import FormControl from "@mui/material/FormControl"; import Select from "@mui/material/Select"; import { SelectInputProps } from "@mui/material/Select/SelectInput"; export function SimpleSelection(props: Props) { React.useEffect(() => { if (!props.value && props.onChange) { const item = props.items.filter((item) => !item.deactivated); props.onChange( { target: { name: item[0].value, value: item[0].value, }, } as any, undefined ); } }, [props.value, props.onChange]); return ( <FormControl fullWidth> <InputLabel id="demo-simple-select-label">{props.label}</InputLabel> <Select value={props.value} label={props.label} onChange={props.onChange} onBlur={props.onBlur} ref={props.ref} > {props.items.map((item) => ( <MenuItem disabled={item.deactivated} value={item.value}> {item.name} </MenuItem> ))} </Select> </FormControl> ); } interface Props extends BaseForm { items: Array<{ value: string; name: string; deactivated?: boolean; }>; label: string; } export interface BaseForm { name: string; onChange: SelectInputProps<string>["onChange"]; onBlur: () => void; ref: React.Ref<unknown>; value?: string; }
function [J, grad] = costFunctionReg(theta, X, y, lambda) %COSTFUNCTIONREG Compute cost and gradient for logistic regression with regularization % J = COSTFUNCTIONREG(theta, X, y, lambda) computes the cost of using % theta as the parameter for regularized logistic regression and the % gradient of the cost w.r.t. to the parameters. % Initialize some useful values m = length(y); % number of training examples % You need to return the following variables correctly J = 0; grad = zeros(size(theta)); % Instructions: Compute the cost of a particular choice of theta. % You should set J to the cost. % Compute the partial derivatives and set grad to the partial % derivatives of the cost w.r.t. each parameter in theta n = size(theta)(1); h = sigmoid(X*theta); ht = h'; y1 = log(ht)*y; y2 = log(1-ht)*(1-y); J = -1/m*sum(y1 + y2) + lambda/2/m*sum(theta(2:n, :).^2); l = ones(n, 1) * lambda; l(1) = 0; grad = 1/m*(X')*(h-y) + l.*theta/m; end
<!DOCTYPE html> <!---include header.html which contains the header links--> {% include 'inc/header.html' %} {% extends "layouts/base.html" %} {% block title %}collage{% endblock title %} {% block body %} <div class="container-fluid"> <div class="row"> <div class="col-md-12"> <div class="col-md-12"> <div class="col-md-8"> <h4 style="padding-left:20px;">Collage Registration Lists</h4> </div> <!--Add a flash message that display a successful message while adding new record --> {% with messages = get_flashed_messages(with_categories = true) %} {% if messages %} {% for category, message in messages %} <div id="alert-success" class="alert alert-{{ category }} alert-dismissible show" role="alert"> <span>{{ message }}</span> </div> {% endfor %} {% endif %} {% endwith %} </div> </div> <!-- end of outer row --> <!-- Search Bar --> <div class="form-control"> <div class="row mt-2"> <div class="col-md-8"> <div class="search"><i class="fas fa-search"></i> <input type="text" id="searchInput" class="form-control" onkeyup="searchFunction()" placeholder="Search Here..."> </div> </div> <!-- add button --> <div class="col-md-2"> <button id="myBtn" class="myBtn btn btn-success" data-bs-toggle="" data-bs-target="#modalAdd"> New Register</button> </div> </div> </div> {% if collages %} <!-- display all collage query results if not empty --> <div class="table-responsive"> <form method="POST" action="{{url_for('collage_bp.delete')}}"> <table class="table tableCheck table-hover table-light table-striped" id="myTable"> <!-- check that if the data is empty--> <thead> <th><input type="checkbox" id="checkall" data-bs-placement="top" data-bs-toggle="tooltip" title="Select All Rows" data-bs-title="Select All Rows" data-bs-tooltip="Select All Rows" class="form-check-input"/></th> <th>Collage Name</th> <th>Registration Date</th> <th>Action</th> </thead> <tbody> <!-- Show all collage data in the table--> {% for row in collages %} <tr> <td><input type="checkbox" value="{{ row.id }}" data-bs-placement="top" data-bs-toggle="tooltip" title="Select Row" data-bs-title="Select Row" data-bs-tooltip="Select Row" name="mycheckbox" class="form-check-input" /></td> <td> <div class="edit">{{row.collageName}}</div> <input type="text" class="txtEdit form-control" value="{{row.collageName}}" id="collageName_{{row.id}}"/> </td> <td>{{row.date_registered}}</td> <!-- action buttons --> <td> <a href="/branchInfo/{{row.id}}/" data-bs-placement="top" data-bs-toggle="tooltip" title="View" class="btn btn-sm btn-xs" data-bs-title="View" data-bs-target="#editModal"> <i class="fas fa-info-circle" style="color:green" aria-hidden="true"></i></a> <a href="/deleteSingle/{{row.id}}" onclick="return confirm('Are you shure you want to Delete?')" data-bs-placement="top" data-bs-toggle="tooltip" title="Delete" class="btn btn-sm btn-xs" data-bs-title="Delete" data-bs-target="#delete" > <i class="fas fa-trash-alt" style="color:red" aria-hidden="true"></i></a> </td> </tr> {% endfor %} </tbody> </table> <div class="col-sm-1 float-start" id ="checkedDelete"> <input type="submit" onclick="return confirm('Are you shure you want to Delete?')" value="Delete" class="btn btn-primary"> </div> </form> </div> <!-- end of div class responsive --> {% else %} <!-- else statment to return if the query result is empty --> <h2>NO! Registerd Collage</h2> {% endif %} </div> <!--end of table container-fluid--> <!-- Modal Add collage office --> <div class="modal" id="modalAdd" data-bs-backdrop="static" data-bs-keyboard="false" tabindex="-1" aria-labelledby="myModalLabel" aria-hidden="true"> <div class="modal-dialog"> <div class="modal-content"> <div class="modal-header"> <h5 class="modal-title" id="myModalLabel">New Register</h5> <button class="btn-close float-end" data-bs-dismiss="modal" aria-label="Close"></button> </div> <div class="modal-body"> <form action="{{url_for('collage_bp.add_collage')}}" method="POST" name="add_skills" id="add_skills"> <div class="container1 row g-3"> <label for="inputZoneName" class="form-label"> Collage Name፡</label> <div> <input type="text" class="" name="newFieldText[]" required/> <a href="#" class="btn-success float-end add_form_field">+</a> </div> </div> <div class="modal-footer"> <button class="btn btn-primary" type="submit">Register</button> </div> </form> </div> </div> </div> </div> <div class="modal-footer"> {% include 'inc/footer.html' %} </div> <!--inline JS --> <script type="text/javascript" src="{{ url_for('static', filename='main.js') }}"></script> <script type="text/javascript" src="{{ url_for('static', filename='pagination.js') }}"></script> {% endblock body %}
## Static Keyword Static variables have a property of preserving their value even after they are out of their scope! The purpose of these is to limit scope of a variable or function to a file ## Declaration - Declaration of a variable or function simply declares that the variable or function exists somewhere in the program, but the memory is not allocated for them. - It tells the program what its type is going to be. In case of function declarations, it also tells the program the arguments, their data types, the order of those arguments, and the return type of the function. ## Defination - When we define a variable or function, in addition to everything that a declaration does, it also allocates memory for that variable or function.
/** * We use `importSvg()` and `importRemixIcon()` utilities to code-split icons away. * This plugin renames the chunks that contain these icons from * 35140.dfd465bd.chunk.js * to * icon.dfd465bd.chunk.js * to make it easier to filter them out in the network tab. * * Why do it here and not in `chunkFilename`, as canonically intended? Because * we have lots of icons, and, as of Mar 2023, V8 (the JS engine in Chrome) * can’t handle that: https://bugs.chromium.org/p/v8/issues/detail?id=13887 */ class IconChunkNamingPlugin { apply(compiler) { const webpackConfig = compiler.options; if ( // checking only for the `[contenthash` part because // the ending might be dynamic: `]` or `:8]` or `:some-other-number]` !webpackConfig.output.chunkFilename.includes("[contenthash") && !webpackConfig.output.chunkFilename.includes("[chunkhash") ) { // The plugin requires the chunkFilename to include [contenthash] or [chunkhash]. That’s because // the plugin renames every icon chunk to "icon". If chunkFilename doesn’t include the `[contenthash]` or `[chunkhash]` // placeholder, we’d end up with multiple chunks named "icon". This might result in overwriting // the icons or (in development) even hanging the build process completely. throw new Error( "IconChunkNamingPlugin: the output.chunkFilename config must include [contenthash] " + "or [chunkhash] to give every chunk file a unique name", ); } compiler.hooks.thisCompilation.tap( "IconChunkNamingPlugin", (compilation) => { compilation.hooks.afterOptimizeChunks.tap( "IconChunkNamingPlugin", (chunks) => { const { chunkGraph } = compilation; // Walk over all chunks webpack emits for (const chunk of chunks) { // Get all modules in the current chunk const chunkModules = chunkGraph.getChunkModules(chunk); // Only if the chunk has exactly one module... const hasOnlyOneModule = chunkModules.length === 1; if (!hasOnlyOneModule) continue; // ...and that module is either a SVG icon or a Remix icon... const modulePath = chunkModules[0].resource; const isSvgIcon = modulePath.endsWith(".svg.js") || modulePath.endsWith(".svg"); const isRemixIcon = modulePath.match( /node_modules[\\\/]remixicon-react[\\\/]/, ); if (!isSvgIcon && !isRemixIcon) continue; // ...then rename the chunk to "icon" chunk.name = "icon"; } }, ); }, ); } } module.exports = IconChunkNamingPlugin;
import Link from "next/link"; import itemJson from "../../../services/item.json"; import PortofolioItem from "./PortofolioItem"; interface PortofolioProps { onPage?: boolean; } export default function Portofolio(props: PortofolioProps) { const { onPage } = props; const itemPortofolio = itemJson.data; return ( <> <section className="section-portofolio"> <div className="container"> <div className="row justify-content-center"> <h3 className="text-center">Portofolio</h3> </div> <div className="row row-cols-1 row-cols-md-2 row-cols-lg-3 g-3 mt-3"> {itemPortofolio.map((item) => { return ( <PortofolioItem key={item.id} title={item.title} href={`/portofolio/detail/${item.id}`} icon={item.image[0].image} /> ); })} </div> <div className="row mt-5"> <div className="col text-center"> {onPage ? ( <Link href="/portofolio"> <a className="btn btn-primary"> More Portofolio{" "} <i className="fa-solid fa-location-arrow ms-2"></i> </a> </Link> ) : ( <Link href="/"> <a className="btn btn-outline-primary"> <i className="fa fa-arrow-circle-left ms-2"></i> Back </a> </Link> )} </div> </div> </div> </section> </> ); }
document.addEventListener('DOMContentLoaded', () => { let carrito = []; let historial = []; const divisa = '$'; const DOMitems = document.querySelector('#items'); const DOMcarrito = document.querySelector('#carrito'); const DOMtotal = document.querySelector('#total'); const DOMbotonVaciar = document.querySelector('#boton-vaciar'); const DOMbotonComprar = document.querySelector('#boton-comprar'); const DOMbotonHistorial = document.querySelector('#boton-historial'); const miLocalStorage = window.localStorage; function renderizarProductos() { baseDeDatos.forEach((info) => { const miNodo = document.createElement('div'); miNodo.classList.add('card', 'col-sm-4'); const miNodoCardBody = document.createElement('div'); miNodoCardBody.classList.add('card-body'); const miNodoTitle = document.createElement('h5'); miNodoTitle.classList.add('card-title'); miNodoTitle.textContent = info.nombre; const miNodoImagen = document.createElement('img'); miNodoImagen.classList.add('img-fluid'); miNodoImagen.setAttribute('src', info.imagen); const miNodoPrecio = document.createElement('p'); miNodoPrecio.classList.add('card-text'); miNodoPrecio.textContent = `${divisa}${info.precio}`; const miNodoBoton = document.createElement('button'); miNodoBoton.classList.add('btn', 'btn-primary'); miNodoBoton.textContent = '+'; miNodoBoton.setAttribute('marcador', info.id); miNodoBoton.addEventListener('click', addProductoAlCarrito); miNodoCardBody.appendChild(miNodoImagen); miNodoCardBody.appendChild(miNodoTitle); miNodoCardBody.appendChild(miNodoPrecio); miNodoCardBody.appendChild(miNodoBoton); miNodo.appendChild(miNodoCardBody); DOMitems.appendChild(miNodo); }); } //añadir producto a carro function addProductoAlCarrito(evento) { carrito.push(evento.target.getAttribute('marcador')) renderizarCarrito(); guardarCarritoEnLocalStorage(); } //mostrar prod carro function renderizarCarrito() { DOMcarrito.textContent = ''; const carritoSinDuplicados = [...new Set(carrito)]; carritoSinDuplicados.forEach((item) => { const miItem = baseDeDatos.filter((itemBaseDatos) => { return itemBaseDatos.id === parseInt(item); }); const numeroUnidadesItem = carrito.reduce((total, itemId) => { return itemId === item ? total += 1 : total; }, 0); const miNodo = document.createElement('li'); miNodo.classList.add('list-group-item', 'text-right', 'mx-2'); miNodo.textContent = numeroUnidadesItem + ' x ' + miItem[0].nombre + ' - ' + divisa + miItem[0].precio; //boton borrar const miBoton = document.createElement('button'); miBoton.classList.add('btn', 'btn-danger', 'mx-5'); miBoton.textContent = 'X'; miBoton.style.marginLeft = '1rem'; miBoton.dataset.item = item; miBoton.onclick = borrarItemCarrito; miNodo.appendChild(miBoton); DOMcarrito.appendChild(miNodo); }); DOMtotal.textContent = calcularTotal(); } //eliminar elemento function borrarItemCarrito(evento) { const id = evento.target.dataset.item; carrito = carrito.filter((carritoId) => { return carritoId !== id; }); Toastify({ text: "Se ha eliminado el producto", duration: 2000 }).showToast(); renderizarCarrito(); guardarCarritoEnLocalStorage(); } //calc total function calcularTotal() { return carrito.reduce((total, item) => { const miItem = baseDeDatos.filter((itemBaseDatos) => { return itemBaseDatos.id === parseInt(item); }); return total + miItem[0].precio; }, 0); } DOMbotonVaciar.onclick = vaciarCarrito; //vaciar carro function vaciarCarrito() { if (carrito.length !== 0) { carrito = []; Swal.fire({ title: 'Desea vaciar carrito', icon: 'warning', showCancelButton: true, confirmButtonText: 'Aceptar', cancelButtonText: 'Cancelar' }).then((result) => { if (result.isConfirmed) { renderizarCarrito(); localStorage.clear(); Swal.fire({ title: 'Se ha vaciado el carrito', icon: 'success' }) } else { cargarCarritoDeLocalStorage(); }; }); } else { Swal.fire('El carrito está vacío'); } } function comprarProducto() { console.log(carrito.length) if (carrito.length === 0) { Swal.fire('El carrito está vacío'); } else { historial.push([...carrito]); Swal.fire('Se ha realizado su compra'); carrito = []; renderizarCarrito(); guardarCarritoEnLocalStorage(); } } DOMbotonComprar.onclick = comprarProducto; function guardarCarritoEnLocalStorage() { miLocalStorage.setItem('carrito', JSON.stringify(carrito)); } function cargarCarritoDeLocalStorage() { if (miLocalStorage.getItem('carrito') !== null) { carrito = JSON.parse(miLocalStorage.getItem('carrito')); } } async function detalleProducto(productoId) { return new Promise((resolve, reject) => { const producto = baseDeDatos.find(item => item.id === parseInt(productoId)); if (producto) { resolve({ nombre: producto.nombre, cantidad: 1 }); } else { reject(new Error('Id ' + productoId + ' no encontrado')); } }); } async function verHistorial() { if (historial.length === 0) { Swal.fire('No se ha encontrado historial de compras'); return; } const histDetalle = []; for (let i = 0; i < historial.length; i++) { const prodDetalle = []; for (const productoId of historial[i]) { try { const detalle = await detalleProducto(productoId); prodDetalle.push(`${detalle.nombre} - Cantidad: ${detalle.cantidad}`); } catch (error) { Swal.fire('Error ' + error.message); return; } } histDetalle.push(`Compra ${i + 1}: ${prodDetalle.join(', ')}`); } Swal.fire('Historial de compras:\n' + histDetalle.join('\n')); } DOMbotonHistorial.onclick = verHistorial; cargarCarritoDeLocalStorage(); renderizarProductos(); renderizarCarrito(); });
package com.aboredswe.demo.service; import com.aboredswe.demo.error.BlogNotFoundException; import com.aboredswe.demo.error.TagNotFoundException; import com.aboredswe.demo.error.UserNotFoundException; import com.aboredswe.demo.model.Blog; import com.aboredswe.demo.model.BlogPostPayload; import com.aboredswe.demo.model.Comment; import com.aboredswe.demo.model.User; import com.aboredswe.demo.repository.BlogRepository; import com.aboredswe.demo.repository.CommentRepository; import jakarta.validation.Valid; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import java.util.ArrayList; import java.util.Date; import java.util.List; import java.util.Optional; @Service public class BlogService { @Autowired private BlogRepository blogRepository; @Autowired private AuthService authService; @Autowired private CommentRepository commentRepository; @Autowired private TagService tagService; public Blog findBlogById(String id) throws BlogNotFoundException { Optional<Blog> foundBlog = blogRepository.findById(id); if(foundBlog.isEmpty()){ throw new BlogNotFoundException(); } return foundBlog.get(); } public List<Blog> findAllBlogs(){ return blogRepository.findAll(); } public List<Blog> findBlogsByEmail(String email){ return blogRepository.findAll() .stream() .filter(blog -> blog.getAuthor().getEmail().equals(email)) .toList(); } public List<Blog> searchBlogs(String keyword) { List<Blog> allBlogs = blogRepository.findAll(); return allBlogs .stream(). filter(blog -> blog.getTitle().toLowerCase().startsWith(keyword.toLowerCase())) .toList(); } public Blog addBlog(@Valid BlogPostPayload blogPostPayload) throws UserNotFoundException { Blog blog = blogRepository.save(buildBlog(blogPostPayload)); addTags(blog); return blog; } public Blog modifyBlog(BlogPostPayload blogPostPayload,String blogId) throws UserNotFoundException { Blog blog = buildBlog(blogPostPayload); blog.setId(blogId); return editBlog(blog); } public void deleteBlog(String blogId) throws BlogNotFoundException, TagNotFoundException { Blog foundBlog = findBlogById(blogId); deleteBlogIdFromTags(foundBlog); deleteCommentsOfThisBlog(foundBlog); blogRepository.deleteById(blogId); } public List<String> addLike(String userEmail, String blogId) throws BlogNotFoundException { Blog foundBlog = findBlogById(blogId); if(!foundBlog.getLikedBy().contains(userEmail)){ foundBlog.getLikedBy().add(userEmail); editBlog(foundBlog); } return foundBlog.getLikedBy(); } public List<String> removeLike(String userEmail, String blogId) throws BlogNotFoundException { Blog foundBlog = findBlogById(blogId); if(foundBlog.getLikedBy().contains(userEmail)){ foundBlog.getLikedBy().remove(userEmail); editBlog(foundBlog); } return foundBlog.getLikedBy(); } public Blog editBlog(Blog blog) { addTags(blog); return blogRepository.save(blog); } private Blog buildBlog(BlogPostPayload blogPostPayload) throws UserNotFoundException { User foundUser = authService.findByEmail(blogPostPayload.getAuthorEmail()); return Blog.builder() .title(blogPostPayload.getTitle()) .content(blogPostPayload.getContent()) .author(foundUser) .date(new Date()) .tags(blogPostPayload.getTags()) .likedBy(new ArrayList<String>()) .comments(new ArrayList<Comment>()) .build(); } private void addTags(Blog blog){ for(String tagName : blog.getTags()){ tagService.addTag(tagName,blog.getId()); } } private void deleteCommentsOfThisBlog(Blog blog) throws BlogNotFoundException { for(Comment comment : blog.getComments()){ commentRepository.deleteById(comment.getId()); } } private void deleteBlogIdFromTags(Blog blog) throws TagNotFoundException { for(String tagName : blog.getTags()){ tagService.deleteBlogIdFromTag(blog.getId(), tagName); } } }
<script> /* * Copyright 2021 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /** * Controller functions for the sidebar UI */ /** * Sets a message to the status field in the sidebar */ function setStatus(status) { console.log(status); document.getElementById('status').innerHTML = status; } function changeButtonStatus(buttonId, backgroundColor, disabled) { const button = document.getElementById(buttonId); button.disabled = disabled; button.style.backgroundColor = backgroundColor; button.style.borderColor = backgroundColor; } /** * Loads data from DV360 into the sheet */ function loadFromDV() { setStatus('Loading line items from DV360...'); changeButtonStatus('loadFromDV', '#A9A9A9', true,); // Clear the Log tab getLogger().clear().then(function(result) { // Create jobs to be executed var jobs = [ { 'entity': 'InsertionOrder' },{ 'entity': 'LineItem' } ]; // Run jobs return new Runner().run('identifyItemsToLoad', jobs); }).then(function(loadJobs) { return new Runner().run('generateQAReport', [{jobs: loadJobs}]); }).then(function(result) { // Log results console.log(result); return getLogger().log(result) }).then(function(result) { // Change status back to Ready setStatus('The DV360 information has been loaded successfully!'); changeButtonStatus('loadFromDV', '#93c47d', false); }); } /** * Pushes data to DV360 */ function pushToDV360() { if(confirm("Are you sure you want to push the changes to DV360?")) { setStatus('Pushing to DV360...'); changeButtonStatus('pushToDV360', '#A9A9A9', true,); // Clear the Log tab getLogger().clear().then(function(result) { // Create jobs to be executed var jobs = [ { 'entity': 'LineItem' } ]; setStatus('Identifying items to update...'); // Run jobs return new Runner().run('pushToDV360', jobs); }).then(function(result) { // Log results console.log("Logging pushToDV360 jobs..."); console.log(result); // Change status setStatus('The Brand Safety Controls have been pushed successfully! Please verify them in the UI.'); changeButtonStatus('pushToDV360', '#93c47d', false); return getLogger().log(result) }); } } /** * Waits for all SDF Download tasks in the jobs to complete * * params: jobs.tasks tasks to check and wait for */ function waitForSDFTasksCompletion(jobs, wait=5000) { return new Runner().run('refreshSDFTasks', jobs).then(jobs => { var complete = true; jobs.forEach(job => { job.tasks.forEach(task => { if(!task.done) { complete = false; } }); }); if(complete) { return jobs; } else { return new Promise(resolve => setTimeout(resolve, wait)).then(() => waitForSDFTasksCompletion(jobs, wait)); } }); } /** * Loads data from DV using SDFs, which allows for read access to YouTube * related entities */ function sdfLoad() { setStatus('Loading from DV360'); var jobs = [{ 'entity': 'InsertionOrder' }]; new Runner().run('createSDFTasks', jobs) .then(function(jobs) { setStatus('Waiting for SDFs to be generated'); return waitForSDFTasksCompletion(jobs); }).then(jobs => { setStatus('Parsing SDFs and generating report'); return new Runner().run('sdfLoad', jobs); }).then(jobs => { setStatus('Ready'); }).catch(error => { console.log(error); setStatus('An Error happened!'); }); } /** * Clears the feed */ function clearFeed() { if(confirm("Are you sure you want to clear the feed?")) { setStatus('Clearing feed...'); new Runner().run('clear', [{ 'sheetName': 'QA', 'range': 'A2:AZ' }]).then(() => setStatus('Ready')); } } /** * Checks for errors in the jobs list, throws exception if one is found * * params: jobs, list of jobs to check * */ function checkErrors(jobs) { jobs.forEach(job => { if(job.status == 'ERROR') { throw job.error; } }); } /** * Apply Brand Safety Controls to the line items in the QA tab */ function applyBrandSafetyControlsConfiguration() { setStatus('Applying Brand Safety Controls...'); changeButtonStatus('applyBrandSafetyControls', '#A9A9A9', true,); google.script.run.withSuccessHandler(successHandler).withFailureHandler(errorHandler).applyBrandSafetyControlsConfiguration(); } function successHandler() { changeButtonStatus('applyBrandSafetyControls', '#93c47d', false); setStatus('The Brand Safety Controls have been applied successfully! Please validate them before pushing to DV360.'); } function errorHandler(param) { changeButtonStatus('applyBrandSafetyControls', '#93c47d', false); setStatus('There was an error while applying the Brand Safety Controls.'); } /** * Executes the underwriter budget and date validation */ function underwriter() { setStatus('Reading underwriter segments ...'); var jobs = [{ 'entity': 'Underwriter' }]; new Runner().run('load', jobs) .then(jobs => { checkErrors(jobs); console.log(jobs); setStatus('Ready'); }).catch(error => { console.log(error); setStatus(`An Error happened! ${error}`); }); } /** * Loads reports from DV360 based on configurations in the Reports tab */ function loadReports() { setStatus('Loading ...'); var job = { 'entity': 'Reports' } new Runner().run('identifyItemsToLoad', [job]).then(jobs => { var loadJobs = []; jobs.forEach(job => loadJobs = loadJobs.concat(job.jobs)); return new Runner().run('load', loadJobs); }).then(jobs => { checkErrors(jobs); setStatus('Ready'); }).catch(error => { console.log(error); setStatus('An error happened'); }); } /** * Based on the data in the report tab, schedule the report triggers to pull * reports automatically on a daily basis */ function scheduleReportTriggers() { if(confirm("Are you sure you want to schedule daily report pulls for the reports configured in the Report tab?")) { setStatus('Configuring report pulls ...'); var job = { 'entity': 'Reports' } new Runner().run('scheduleReportTriggers', [job]).then(jobs => { checkErrors(jobs); setStatus('Ready'); }).catch(error => { console.log(error); setStatus('An error happened'); }); } } /** * Forces Underwriter to reload advertisers and budget segments in the next * scheduled execution */ function forceReload() { if(confirm("Are you sure you want Underwriter to fully reload advertisers and budget segments on the next scheduled execution?")) { setStatus('Preparing full reload ...'); var job = { } new Runner().run('setupFullReload', [job]).then(jobs => { checkErrors(jobs); setStatus('Ready'); }).catch(error => { console.log(error); setStatus('An error happened'); }); } } /** * Loads the Advertiser tab based on data in the Underwriter tab */ function loadAdvertisers() { if(confirm("Are you sure you want to reload the data in the Advertisers tab?")) { setStatus('Loading Advertisers ...'); var job = { 'entity': 'Advertiser', 'incremental': false } new Runner().run('load', [job]).then(jobs => { checkErrors(jobs); setStatus('Ready'); }).catch(error => { console.log(error); setStatus('An error happened'); }); } } /** * Loads the Budget Segment tab based on data in the Advertiser tab */ function loadBudgetSegments() { if(confirm("Are you sure you want to reload the data in the Budget Segments tab?")) { setStatus('Loading Budget Segments ...'); var job = { 'entity': 'Budget Segment', 'incremental': false } new Runner().run('load', [job]).then(jobs => { checkErrors(jobs); setStatus('Ready'); }).catch(error => { console.log(error); setStatus('An error happened'); }); } } /** * Sets up underwiter trigers to run every 5 minutes */ function setupUnderwriterTriggers() { if(confirm("Are you sure you want to setup Underwriter to run every 5 minutes?")) { setStatus('Setting up Underwriter triggers ...'); var job = { 'entity': 'Advertiser' } new Runner().run('setupUnderwriterTriggers', [job]).then(jobs => { checkErrors(jobs); setStatus('Ready'); }).catch(error => { console.log(error); setStatus('An error happened'); }); } } /** * Deletes all scheduled project triggers */ function deleteAllTriggers() { if(confirm("Are you sure you want to stop Underwriter and report pulls?")) { setStatus('Deleting triggers ...'); var job = { } new Runner().run('deleteAllTriggers', [job]).then(jobs => { checkErrors(jobs); setStatus('Ready'); }).catch(error => { console.log(error); setStatus('An error happened'); }); } } </script>
"use client"; import Badge from "@/components/octopus/Badge"; import Comparison from "@/components/octopus/Comparison"; import { IMeterPointE, IPeriod } from "@/data/source"; import { evenRound, getTariffCodeWithoutPrefixSuffix, } from "../../utils/helpers"; import Lottie from "lottie-react"; import octopusIcon from "../../../public/lottie/octopus.json"; import FormattedPrice from "./FormattedPrice"; import { GrMoney } from "react-icons/gr"; import { LiaBalanceScaleSolid } from "react-icons/lia"; import { TbMoneybag, TbPigMoney } from "react-icons/tb"; import { PiQuestion } from "react-icons/pi"; import Loading from "../Loading"; import Remark from "./Remark"; import useDailyAmountCalculation from "@/hooks/useDailyAmountCalculation"; import DailyChart from "./DailyChart"; const getPeriodArray = (fromDate: Date, toDate: Date) => { const diffInDays = Math.round( (toDate.valueOf() - fromDate.valueOf()) / (1000 * 60 * 60 * 24) ); return Array.from({ length: diffInDays }).map( (_, i) => new Date( new Date(fromDate).setUTCDate(new Date(fromDate).getUTCDate() + i) ) ); }; const SavingsChartDaily = ({ type, gsp, deviceNumber, serialNo, period, agreements, compareTo, apiKey, dual = false, testRun = false, }: { type: "E" | "G"; gsp: string; deviceNumber: string; serialNo: string; period: IPeriod; agreements: IMeterPointE["agreements"]; compareTo: string; apiKey: string; dual?: boolean; testRun?: boolean; }) => { const latestDate = new Date(); latestDate.setUTCHours(23, 59, 59, 999); latestDate.setUTCDate(latestDate.getUTCDate() - 1); const fromDate = period.from; const toDate = period.to.valueOf() > latestDate.valueOf() ? latestDate : period.to; const periodArray = getPeriodArray(fromDate, toDate); const periodWithTariff = periodArray.map((date, i) => { let tariff = ""; agreements.forEach((agreement) => { if ( new Date(agreement.valid_from).valueOf() <= date.valueOf() && (agreement.valid_to === null || new Date(agreement?.valid_to).valueOf() >= date.valueOf()) ) { tariff = getTariffCodeWithoutPrefixSuffix(agreement.tariff_code); } }); return { date, tariff }; }); const { isLoading, isSuccess, results } = useDailyAmountCalculation({ type, periodWithTariff, deviceNumber, serialNo, gsp, compareTo, apiKey, dual, testRun, }); if (isLoading) return ( <div className="relative min-h-[300px]"> <Loading /> </div> ); if (!results) { return ( <div className="relative flex-1 flex flex-col gap-8 rounded-xl p-4 bg-theme-950 border border-accentPink-800/60 shadow-inner bg-gradient-to-br from-transparent via-theme-800/20 to-purple-600/30 bg-cover" style={{ backgroundImage: `linear-gradient(0deg, rgba(0,3,35,0.7) 30% , rgba(0,3,35,0.9) 70%, rgba(0,4,51,1) 100% )`, }} > <div className="flex-1 flex h-full items-center justify-center flex-col gap-2"> <Lottie animationData={octopusIcon} aria-hidden={true} className="w-16 h-16" /> <span className="text-sm font-light text-center"> Sorry, we have some issues here. Please check back later. </span> </div> </div> ); } const totalPriceSVT = results.reduce((acc, cur) => cur.SVTcost + acc, 0); const totalStandingChargeSVT = results.reduce( (acc, cur) => cur.SVTstandingCharge + acc, 0 ); const totalPrice = results.reduce((acc, cur) => cur.cost + acc, 0); const totalStandingCharge = results.reduce( (acc, cur) => cur.standingCharge + acc, 0 ); const totalUnit = results.reduce((acc, cur) => cur.reading + acc, 0); const totalSVT = (totalPriceSVT + totalStandingChargeSVT) / 100; const totalCost = (totalPrice + totalStandingCharge) / 100; const totalSaving = totalSVT - totalCost; const unitRateAverage = totalPrice / totalUnit; const unitRateAverageSVT = totalPriceSVT / totalUnit; return ( <> <div className="relative flex-1 flex flex-col gap-8 rounded-xl p-4 bg-theme-950 border border-accentPink-950 shadow-inner bg-gradient-to-br from-transparent via-theme-800/20 to-purple-600/30 bg-cover" style={{ backgroundImage: `linear-gradient(0deg, rgba(0,3,35,0.7) 30% , rgba(0,3,35,0.9) 70%, rgba(0,4,51,1) 100% )`, }} > <div className="flex flex-col flex-1 text-white/80 text-sm"> <div className="flex flex-1 flex-col md:flex-row justify-between gap-4 max-h-full overflow-hidden mb-8"> <DailyChart data={results} type={type} month={fromDate.toLocaleDateString("en-GB", { month: "short" })} dual={dual} /> <div className="flex flex-col font-normal justify-start divide-y [&>div]:border-accentBlue-900 gap-3"> <div className="flex flex-wrap justify-between items-start md:block text-[#85cbf9] bg-theme-900/30"> <Badge label={`Total ${ totalCost - totalSVT < 0 ? `Saving` : `Increase` }`} icon={ totalCost - totalSVT < 0 ? ( <TbPigMoney className="stroke-[#85cbf9]" /> ) : ( <GrMoney className="stroke-[#85cbf9]" /> ) } variant="item" /> <div className="font-digit text-4xl flex flex-col items-end justify-start"> <FormattedPrice price={Math.abs(totalSaving)} value="pound" /> <div className="text-xs"> <Comparison change={evenRound( ((totalCost - totalSVT) / totalSVT) * 100, 0 )} compare={`Variable Tariff`} /> </div> </div> </div> <div className="flex flex-wrap justify-between items-start md:block text-[#aaffdd]"> <Badge label="Average Unit Rate" icon={<LiaBalanceScaleSolid className="fill-[#aaffdd]" />} variant="item" /> <div className="font-digit text-4xl flex flex-col items-end justify-start"> <FormattedPrice price={unitRateAverage} value="pence" /> <div className="text-xs"> <Comparison change={evenRound( ((unitRateAverage - unitRateAverageSVT) / unitRateAverageSVT) * 100, 0 )} compare={`Variable Tariff`} /> </div> </div> </div> <div className={`flex flex-wrap justify-between items-start md:block text-white`} > <Badge label={`Total Cost`} icon={<TbMoneybag className="stroke-white" />} variant="item" /> <div className="font-digit text-4xl flex flex-col items-end justify-start font-medium"> <FormattedPrice price={totalCost} value="pound" /> </div> </div> <div className={`flex flex-wrap justify-between items-start md:block text-accentPink-500`} > <Badge label={`Total SVT Cost`} icon={<TbMoneybag className="text-accentPink-500" />} variant="item" /> <div className="font-digit text-4xl flex flex-col items-end justify-start"> <FormattedPrice price={totalSVT} value="pound" /> </div> </div> </div> </div> <div className="text-white/80 text-sm flex items-center gap-1"> <PiQuestion className="fill-accentPink-500 w-6 h-6" /> Why are the above results different from my Octopus bills? <Remark variant="badge"> As we cannot get your bills directly from Octopus, we have applied approximations and assumptions in the calculations. Reasons for the differences may be missing data, rounding or, in the case of gas, the conversion of reading of gas volume to kWh (the unit used in our daily quote) because{" "} <strong>gas cost calculation is very complex.</strong> The unit of readings from smart meters differ depending on the generation of meter (i.e. SMETS1 meters have the consumption data pre-converted to kWh while SMETS2 meters transfer consumption data in the raw cubic meters which has to be converted to kWh based on a sophisticated formula.). If the calculated costs here deviate a lot from your actual charges on your bill, please click on your postcode on the top of the page to change the{" "} <strong>Gas Conversion Factor</strong>. </Remark> </div> </div> </div> </> ); }; export default SavingsChartDaily;
import { IDictionary } from "~/types/dictionary.interface" export interface IReplaceDotService<T> { endcodeObjectKey: (field: string) => string, decodeObjectKey: (field: string) => string, updateObjectKeys: (obj: T) => IDictionary<string> } export class ReplaceDotService<T> implements IReplaceDotService<T> { public endcodeObjectKey(field: string): string { if(/_/g.test(field)) { return field.replace(/_/g, '.') } return field; } public decodeObjectKey(field: string): string { if(/\./g.test(field)) { return field.replace(/\./g, '_') } return field; } public updateObjectKeys(obj: T): IDictionary<string> { const newObj: IDictionary<string> = {} Object .entries(obj) .forEach(([field, value]) => { try { newObj[this.endcodeObjectKey(field)] = value } catch(err: any) { console.warn(`Can't parse field '${field}'`) } }) return newObj } }
import { Component, OnInit } from "@angular/core"; import { FormControl, Validators } from "@angular/forms"; import { ActivatedRoute, Router } from "@angular/router"; import { Livro } from "../livro.model"; import { LivroService } from "../livro.service"; @Component({ selector: "app-livro-create", templateUrl: "./livro-create.component.html", styleUrls: ["./livro-create.component.css"], }) export class LivroCreateComponent implements OnInit { titulo = new FormControl("", [Validators.minLength(3)]); nome_autor = new FormControl("", [Validators.minLength(3)]); texto = new FormControl("", [Validators.minLength(10)]); id_cat: String = ""; livro: Livro = { id: "", nome_autor: "", texto: "", titulo: "", }; constructor( private service: LivroService, private route: ActivatedRoute, private routes: Router ) {} ngOnInit(): void { this.id_cat = this.route.snapshot.paramMap.get("id_cat")!; } getMessage(){ } getMessageTitulo() { if (this.titulo.invalid) { return "O campo TÍTULO deve conter no mínimo 3 caracteres e no máximo 100"; } return false; } getMessageNomeAutor() { if (this.nome_autor.invalid) { return "O campo NOME AUTOR deve conter no mínimo 3 caracteres e no máximo 50"; } return false; } getMessageTexto() { if (this.texto.invalid) { return "O Campo TEXTO deve conter no mínimo 10 caracteres e no máximo 10000"; } return false; } create(): void { this.service.create(this.livro, this.id_cat).subscribe( (result) => { this.service.mensagem("Livro criado com sucesso!"); this.routes.navigate([`categorias/${this.id_cat}/livros`]); }, (err) => { this.service.mensagem( "Houve um erro no cadastro do seu livro, tente novamente" ); this.routes.navigate([`categorias/${this.id_cat}/livros`]); } ); } cancel(): void { this.routes.navigate([`/categorias/${this.id_cat}/livros`]); } }
package com.bvp.patan.adapter import android.content.ClipData import android.content.ClipboardManager import android.content.Context import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.TextView import androidx.recyclerview.widget.RecyclerView import com.bvp.patan.R import com.bvp.patan.model.ListItemPhotos import com.bvp.patan.operations.Operations import java.util.* class PhotosAdapter( private val context: Context, private var photosList: ArrayList<ListItemPhotos> ) : RecyclerView.Adapter<PhotosAdapter.ViewHolder>() { companion object { const val TAG = "PhotosAdapterTAG" } override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder { val view = LayoutInflater.from(context).inflate(R.layout.list_item_photos, parent, false) return ViewHolder(view) } override fun getItemCount(): Int { return photosList.size } override fun onBindViewHolder(holder: ViewHolder, position: Int) { val item = photosList[position] holder.tvLink.text = item.link holder.tvDesc.text = item.desc holder.tvLink.setOnLongClickListener { copyToClipboard(item.link) true } holder.itemView.setOnLongClickListener { copyToClipboard(item.link) true } } private fun copyToClipboard(link: String?) { val clipboardManager = context.getSystemService(Context.CLIPBOARD_SERVICE) as ClipboardManager val clipData = ClipData.newPlainText("copy", link) clipboardManager.setPrimaryClip(clipData) Operations(context).displayToast(context.getString(R.string.link_copied_to_clipboard)) } class ViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) { val tvLink = itemView.findViewById(R.id.tvLink) as TextView val tvDesc = itemView.findViewById(R.id.tvDesc) as TextView } }
--- meta: title: "Styling and customization" parentTitle: "Comments" description: "CSS variables, dark mode, localization, and more" --- Styling [default components](/docs/products/comments/default-components) and [primitives](/docs/products/comments/primitives) is enabled through a range of means, such as CSS variables, class names, and more. It’s also possible to use [overrides](/docs/products/comments/styling-and-customization#Overrides-and-localization) to modify any strings used in the default components, which is especially helpful for localization. ## Default components To add the default components’ theme, import the [default styles](/docs/api-reference/liveblocks-react-ui#Default-styles) CSS file. ```ts import "@liveblocks/react-ui/styles.css"; ``` You can also import one of two CSS files to enable [dark mode](/docs/api-reference/liveblocks-react-ui#Dark-mode), depending on how you’d like to enable it. ```ts // Dark mode using the system theme with `prefers-color-scheme` import "@liveblocks/react-ui/styles/dark/media-query.css"; ``` ```ts // Dark mode using `className="dark"`, `data-theme="dark"`, or `data-dark="true"` import "@liveblocks/react-ui/styles/dark/attributes.css"; ``` ### CSS variables A number of [CSS variables](/docs/api-reference/liveblocks-react-ui#CSS-variables) can be used to customize colors, spacing, and more. This is our recommended path for styling the default components, as you can quickly and easily modify all components with just a few variables. ```css /* Styles all default components */ .lb-root { --lb-accent: purple; --lb-spacing: 1em; --lb-radius: 0; } ``` ### Class names Should you need deeper customization, [class names](/docs/api-reference/liveblocks-react-ui#Class-names) can be styled, some of which provide contextual data attributes. ```css .lb-thread { /* Customise thread */ } .lb-avatar[data-loading] { /* Customise avatar loading state */ } ``` ### Overrides and localization It’s possible to [override strings](/docs/api-reference/liveblocks-react-ui#Overrides) used in the default components, which has a couple of different uses, the first being localization. In this example, we’re globally switching the word _Anonymous_ to _Anonyme_ for French users. ```tsx import { LiveblocksUIConfig } from "@liveblocks/react-ui"; export function App() { return ( <LiveblocksUIConfig overrides={{ locale: "fr", USER_UNKNOWN: "Anonyme" /* ... */ }} > {/* ... */} </LiveblocksUIConfig> ); } ``` You can also override strings on a component basis, for example if you’d like to change the placeholder text in the [`Composer`](/docs/api-reference/liveblocks-react-ui#Composer). ```tsx import { Composer } from "@liveblocks/react-ui"; function Component() { return ( <Composer overrides={{ COMPOSER_PLACEHOLDER: "Reply to thread…", }} /> ); } ``` ## Primitives Primitives [can be styled like any other element](/docs/products/comments/primitives#Use-regular-props) in your React application—each component passes down props to its root element, meaning you can use regular HTML props. ```tsx import { Composer } from "@liveblocks/react-ui/primitives"; function Component() { return ( <Composer.Submit className="btn-primary" style={{ color: "#ffffff" }}> Reply </Composer.Submit> ); } ``` You can use your custom design system components with primitives by using the `asChild` property, which will [merge the primitive’s props](/docs/products/comments/primitives#Merge-with-your-design-system-components) into your component’s. ```tsx highlight="6" import { Composer } from "@liveblocks/react-ui/primitives"; import { Button } from "@/my-design-system"; function Component() { return ( <Composer.Submit asChild> <Button variant="primary">Reply</Button> </Composer.Submit> ); } ``` ### Tailwind Style primitives with [Tailwind](https://tailwindcss.com) by adding class names. ```tsx import { Composer } from "@liveblocks/react-ui/primitives"; function Component() { return ( <Composer.Submit className="bg-black text-white">Reply</Composer.Submit> ); } ``` ### CSS modules Style primitives with [CSS modules](https://github.com/css-modules/css-modules) as you would any other component. ```tsx import { Composer } from "@liveblocks/react-ui"; import styles from "./Component.module.css"; function Component() { return <Composer.Submit className={styles.submit}>Reply</Composer.Submit>; } ```
'use client'; import Styles from './styles.module.css'; import 'bootstrap/dist/css/bootstrap.css'; import React, { useState, useEffect } from 'react'; import { FontAwesomeIcon } from '@fortawesome/react-fontawesome'; import { faTrash } from '@fortawesome/free-solid-svg-icons'; import Table from 'react-bootstrap/Table'; import Button from 'react-bootstrap/Button'; <Route path="/eliminarmovimiento" component={EliminarMovimiento} /> const EliminarMovimiento = () => { // Definir un estado para almacenar los movimientos const [movimientos, setMovimientos] = useState([]); useEffect(() => { // acá se puede hacer una solicitud api o cargar los datos const movimientosData = [ { id: 1, descripcion: 'Gasto 1', monto: 100 }, { id: 2, descripcion: 'Ingreso 1', monto: 200 }, { id: 3, descripcion: 'Gasto 2', monto: 50 }, ]; setMovimientos(movimientosData); }, []); // Función para eliminar un movimiento por su ID const eliminarMovimiento = (id) => { setMovimientos((movimientos) => movimientos.filter((movimiento) => movimiento.id !== id)); }; return ( <div className={Styles.eliminarMovimiento}> <h1>Eliminar Movimiento Contable</h1> <Table striped bordered hover> <thead> <tr> <th>ID</th> <th>Descripción</th> <th>Monto</th> <th>Acciones</th> </tr> </thead> <tbody> {movimientos.map((movimiento) => ( <tr key={movimiento.id}> <td>{movimiento.id}</td> <td>{movimiento.descripcion}</td> <td>${movimiento.monto}</td> <td> <Button variant="danger" onClick={() => eliminarMovimiento(movimiento.id)}> <FontAwesomeIcon icon={faTrash} /> Eliminar </Button> </td> </tr> ))} </tbody> </Table> </div> ); }; export default EliminarMovimiento;
import numpy as np import streamlit as st from PIL import Image from utils import process_image, get_footer, load_model import keras.preprocessing.image as image from copy import deepcopy colors=["red","orange","green","brown"] options = ['Mild Demented', 'Moderate Demented','Non Demented','Very Mild Demented'] def highlight_prediction(options, idx): options = deepcopy(options) highlight = f'''<span style="color:{colors[idx]}" >**{options[idx]}** </span> ''' options[idx] = highlight return '<br>'.join(options) if __name__ == '__main__': st.image("assets/Brain.jpg") st.write(" ") st.markdown("<h1 style='text-align: center; color: black;'>" "<center>&emsp;&emsp;Alzheimer Stage Detection from Medical Images</center></h1>", unsafe_allow_html=True) st.markdown("<br>", unsafe_allow_html=True) uploaded_file = st.file_uploader("Upload a medical image...", type=["jpg","png","jpeg"]) st.markdown(get_footer(), unsafe_allow_html=True) if uploaded_file is not None: img_in = Image.open(uploaded_file) img_in_processed = process_image(img_in) col1, col2 = st.columns(2) col1.image(img_in_processed) st.write("Brain MRI Image") model = load_model('Trained_Models/LastModel.h5') prediction = model.predict(img_in_processed) idx = np.argmax(prediction) col2.markdown("### Predicted Type") col2.markdown(highlight_prediction(options, idx), unsafe_allow_html=True) st.image("assets/symptoms.png") else: st.image("assets/symptoms.png")
import { NavLink } from 'react-router-dom' import { useEffect, useState } from 'react' import { useDispatch, useSelector } from 'react-redux' import { PATH_ARTICLE, PATH_NEW_ARTICLE, PATH_PROFILE, PATH_SIGN_IN, PATH_SIGN_UP, } from '../../routes' import avatar from '../../assets/smiley-cyrus.jpg' import { selectStatus, logoutUser, fetchGetProfile, selectToken, selectUserName, selectImageUser, } from '../../store/slices/loginSlice' import useAuth from '../../hooks/use-auth' import style from './Header.module.scss' export default function Header() { const { isAuth } = useAuth() const dispatch = useDispatch() const status = useSelector(selectStatus) const image = useSelector(selectImageUser) const username = useSelector(selectUserName) const token = useSelector(selectToken) const [imgError, setImgError] = useState(false) const handleLogout = () => { dispatch(logoutUser()) } useEffect(() => { if (isAuth && status === 'succeeded') { dispatch(fetchGetProfile({ token })) } }, [status, dispatch]) const handleImgError = () => { setImgError(true) } return ( <header className={style.header}> <div className={style.header__container}> <NavLink to={PATH_ARTICLE} className={({ isActive }) => isActive ? `${style.active} ${style.header__container__btn} ${style.name__blog}` : `${style.header__container__btn} ${style.name__blog}` } type="button" > Realworld Blog </NavLink> </div> {isAuth ? ( <div className={style.header__container}> <NavLink to={PATH_NEW_ARTICLE} className={({ isActive }) => isActive ? `${style.header__container__btn} ${style.create_article_activ}` : `${style.header__container__btn} ${style.create_article}` } type="button" > Create article </NavLink> <NavLink to={PATH_PROFILE} className={({ isActive }) => isActive ? `${style.header__container__btn} ${style.username} ${style.active}` : `${style.header__container__btn} ${style.username}` } type="button" > <span className={style.username_span}>{username}</span> {imgError ? ( <img className={style.username_img} src={avatar} alt="Avatar" /> ) : ( <img className={style.username_img} src={image || avatar} onError={handleImgError} alt="Author Avatar" /> )} </NavLink> <NavLink to={PATH_ARTICLE} className={({ isActive }) => isActive ? `${style.header__container__btn} ${style.logout} ` : `${style.header__container__btn} ${style.logout}` } type="button" onClick={handleLogout} > Log Out </NavLink> </div> ) : ( <div className={style.header__container}> <NavLink to={PATH_SIGN_IN} className={({ isActive }) => isActive ? `${style.header__container__btn} ${style.sign__in} ${style.active}` : `${style.header__container__btn} ${style.sign__in}` } type="button" > Sign In </NavLink> <NavLink to={PATH_SIGN_UP} className={({ isActive }) => isActive ? `${style.header__container__btn} ${style.sign__up_activ}` : `${style.header__container__btn} ${style.sign__up}` } type="button" > Sign Up </NavLink> </div> )} </header> ) }
# XQuery # Caractéristiques ### Langage fonctionnel ### Analogue à SQL ### Basé sur XPath ### Standardisé par le W3C ??? # Caractéristiques ### Langage fonctionnel ### Analogue à SQL ### Basé sur XPath ### Standardisé par le W3C --- ## Littéraux 1 'test' string(16+1) concat((16+1), 1) fn:concat('test', 'ajout') 'e' || 1 1 = 2 ``` if (1 = 1) then 'oui' else 'non' ``` # FLOWR ``` let $msg := 'Hello World !' return $msg ``` ``` let $seq := (3, 2, 1) for $i in $seq return $i + 1 ``` ``` let $seq := (3, 2, 1) for $i in $seq order by $i return $i ``` ``` let $seq := (3, 2, 1) for $i in $seq order by $i ascending return $i ``` ``` let $seq := (3, 2, 1) for $i in $seq order by $i descending return $i ``` ```xquery let $document := fn:doc("tei.xml") for $persName in $document//tei:persName where $persName/@id order by $persName/@id return $persName/text() ``` ```xquery for $i in (1, 2, 3) return $i ``` ```xquery for $i in (1, 2, 3) return $i * $i ``` ```xquery for $i in (1, 2, 3) return if ($i mod 2 = 0) then $i * $i ``` ```xquery for $i in (1, 2, 3) return if ($i mod 2) then $i * $i ``` --- http://www.tutorialspoint.com/xquery/xquery_quick_guide.htm https://www.ibm.com/docs/en/db2-for-zos/11?topic=zos-xml
import { all, takeLatest, call, put } from 'redux-saga/effects'; import { Alert } from 'react-native'; // import history from '~/services/history'; import api from '~/services/api'; import { signInSuccess, signFailure } from './actions'; export function* signIn({ payload }) { // Alert.alert('Gympoint', 'signIn'); try { const { id } = payload; // Alert.alert('Gympoint', id); const response = yield call(api.post, '/session/students', { student_id: id, }); const { token, user } = response.data; if (!user) { Alert.alert('Gympoint', 'Usuário não encontrado'); return; } api.defaults.headers.Authorization = `Bearer ${token}`; yield put(signInSuccess(token, user)); // history.push('/'); } catch (err) { yield put(signFailure()); Alert.alert('Gympoint', 'Falha na autenticação'); } } export function setToken({ payload }) { if (!payload) return; const { token } = payload.auth; if (token) { api.defaults.headers.Authorization = `Bearer ${token}`; } } export function signOut() { // history.push('/signin'); } export default all([ takeLatest('persist/REHYDRATE', setToken), takeLatest('@auth/SIGN_IN_REQUEST', signIn), takeLatest('@auth/SIGN_OUT', signOut), ]);
import seaborn as sns from matplotlib import pyplot as plt num_epochs = 20 epoch_size = 3068 reset_epochs = [2, 5, 8, 11, 14] reset_steps = [epoch * epoch_size for epoch in reset_epochs] num_training_steps = num_epochs * epoch_size num_warmup_steps = 0.06 * num_training_steps if __name__ == '__main__': steppoints = [] if not reset_steps[0] == 0: reset_steps = [0] + reset_steps warmup_starts = set(reset_steps) for step in reset_steps: steppoints.append(step) steppoints.append(step + num_warmup_steps) steppoints.append(num_training_steps) # Determine which range an integer belongs to using binary search def find_range(n): for idx, step in enumerate(steppoints): if step <= n < steppoints[idx + 1]: if step in warmup_starts: return step, steppoints[idx + 1], True # is warmup else: return step, steppoints[idx + 1], False # is not warmup def lr_lambda(current_step: int): range_start, range_end, is_warmup = find_range(current_step) if is_warmup: return float(current_step - range_start) / float(max(1, range_end - range_start)) else: return max( 0.0, float(range_end - current_step) / float(max(1, range_end - range_start)) ) steps = list(range(num_training_steps)) lrs = [lr_lambda(step) for step in steps] sns.lineplot(x=steps, y=lrs) plt.savefig('lr_test.png')
// // ViewController.swift // BreweryBess // // Created by Francisco Santana Cardoso on 28/01/22. // import UIKit import RealmSwift class MainViewController: UIViewController, UITextFieldDelegate { // MARK: Attributes var searchText: String? var listOrder: OrdenationBreweryType = .evaluetion var breweryId: String = "" private lazy var searchViewModel: SearchViewModel = AppContainer.shared.resolve(SearchViewModel.self)! lazy var brewerySearchResultView = Bundle.main.loadNibNamed("BreweriesSearchResultView", owner: self, options: nil)?.first as? BreweriesSearchResultView lazy var carouselView = Bundle.main.loadNibNamed("CarouselView", owner: self, options: nil)?.first as? CarouselView lazy var errorView = Bundle.main.loadNibNamed("ErrorView", owner: self, options: nil)?.first as? ErrorView // MARK: IBOutlet @IBOutlet weak var textFieldSearch: UITextField! @IBOutlet weak var homeContainer: UIView! override func viewDidLoad() { super.viewDidLoad() imageTextfield() brewerySearchResultView?.delegate = self carouselView?.delegate = self homeContainer.addSubview(self.carouselView!) } @IBAction func clickFavoritos(_ sender: Any) { self.performSegue(withIdentifier: "FavoritesViewController", sender: self) } @IBAction func clickMyEvaluations(_ sender: UIBarButtonItem) { let controller = MyEvaluationsView() navigationController?.pushViewController(controller, animated: true) } override var preferredStatusBarStyle: UIStatusBarStyle { return .lightContent } func imageTextfield() { let imageview = UIImageView(frame: CGRect(x: 16, y: 8, width: 23, height: 23)) let image = UIImage(named: "lupa") imageview.image = image imageview.contentMode = .scaleAspectFit let view = UIView(frame: CGRect(x: 0, y: 0, width: 40, height: 40)) view.addSubview(imageview) textFieldSearch?.leftViewMode = .always textFieldSearch?.leftView = view } } extension MainViewController: BreweriesSearchResultViewDelegate { func didSelectBrewery() { self.breweryId = self.searchViewModel.listOrder[self.brewerySearchResultView?.selectCell ?? 0].id let detailsViewController = UIStoryboard(name: "Details", bundle: nil).instantiateViewController(withIdentifier: "DetailsViewController") as? DetailsViewController detailsViewController?.selectBreweryId = self.breweryId navigationController?.pushViewController(detailsViewController ?? DetailsViewController(), animated: true) } func didClickFavorite(_ button: UIButton, cell: Int) { let favorite = Favorite() favorite.id = self.searchViewModel.listOrder[cell].id favorite.name = self.searchViewModel.listOrder[cell].name favorite.brewery_type = self.searchViewModel.listOrder[cell].brewery_type favorite.average = self.searchViewModel.listOrder[cell].average self.searchViewModel.savefavorite(favorite: favorite) button.setImage(UIImage(named: "favorited.png"), for: .normal) } func didiClickShere() { print("Compartilhar") } func didClickSort() { if self.listOrder == .evaluetion { self.listOrder = .alphabetic } else { self.listOrder = .evaluetion } brewerySearchResultView?.sortLabel.text = listOrder.rawValue searchViewModel.searchResultReorder = { breweries in DispatchQueue.main.async { self.brewerySearchResultView?.breweries = breweries self.brewerySearchResultView?.frame = self.homeContainer.frame self.homeContainer.addSubview(self.brewerySearchResultView!) self.brewerySearchResultView?.searchResultTableView.reloadData() } } self.searchViewModel.reorder(Order: self.listOrder) } } extension MainViewController: TopTenCarouselDelegate { func handleTap(breweryId: String) { let detailsViewController = UIStoryboard(name: "Details", bundle: nil).instantiateViewController(withIdentifier: "DetailsViewController") as? DetailsViewController detailsViewController?.selectBreweryId = breweryId navigationController?.pushViewController(detailsViewController ?? DetailsViewController(), animated: true) } } // MARK: search Result extension MainViewController { func setErrorType (error: ErrorTitle) { self.errorView?.frame = self.homeContainer.frame self.errorView?.setErrorType(error) self.homeContainer.addSubview(self.errorView!) } func textFieldShouldReturn(_ textField: UITextField) -> Bool { self.searchText = textField.text?.trimmingCharacters(in: .whitespaces).addingPercentEncoding(withAllowedCharacters: .alphanumerics) searchViewModel.searchResult = { breweries, statusCode in DispatchQueue.main.async { if self.searchText?.isEmpty == true || statusCode == 400 { self.setErrorType(error: .searchTextError) } else { switch statusCode { case 404, 500: self.setErrorType(error: .resultError) case 200: self.brewerySearchResultView?.sortLabel.text = self.listOrder.rawValue self.brewerySearchResultView?.breweries = breweries self.brewerySearchResultView?.frame = self.homeContainer.frame self.homeContainer.addSubview(self.brewerySearchResultView!) default: break } } self.brewerySearchResultView?.searchResultTableView.reloadData() } } searchViewModel.search(city: self.searchText ?? "") textField.resignFirstResponder() return true } }
const IMAGES_BASED_ON_STATES = { walking: [ // "./src/img/character/walk/walk1.png", "./src/img/character/walk/walk2.png", "./src/img/character/walk/walk3.png", "./src/img/character/walk/walk4.png", "./src/img/character/walk/walk5.png", "./src/img/character/walk/walk6.png", "./src/img/character/walk/walk7.png", ], flying: [ "./src/img/character/fly/fly1.png", "./src/img/character/fly/fly2.png", "./src/img/character/fly/fly3.png", "./src/img/character/fly/fly4.png", "./src/img/character/fly/fly5.png", ], idle: [ "./src/img/character/idle/idle1.png", "./src/img/character/idle/idle2.png", "./src/img/character/idle/idle3.png", "./src/img/character/idle/idle4.png", "./src/img/character/idle/idle5.png", "./src/img/character/idle/idle6.png", ], dying: [ "./src/img/character/dead/dead1.png", "./src/img/character/dead/dead2.png", "./src/img/character/dead/dead3.png", "./src/img/character/dead/dead4.png", "./src/img/character/dead/dead5.png", "./src/img/character/dead/dead6.png", "./src/img/character/dead/dead7.png", "./src/img/character/dead/dead8.png", ], }; let index = 0; class Character { constructor(x, y, width, height) { this.x = x; this.y = y; this.width = width; this.height = height; this.color = "rgba(255, 0,0, 0.2)"; this.vx = 0; this.vy = 0; this.bullets = []; this.isGrounded = false; this.state = "walking"; } draw(ctx) { this.drawImageBasedOnState(ctx); if(HAS_COIN_POWER_UP || !SHOULD_COLLIDE_WITH_OBSTACLE_AND_MISSILE){ ctx.fillStyle = this.color; ctx.fillRect(this.x, this.y, this.width, this.height); } this.y += this.vy; this.applyGravity(); this.drawBullets(); } drawImageBasedOnState(ctx) { const image = new Image(); // Get the array of images based on the current state const imageArray = IMAGES_BASED_ON_STATES[this.state]; // Ensure there are images in the array if (imageArray && imageArray.length > 0) { // Get the current index for the animation const currentIndex = Math.floor(index) % imageArray.length; // Set the image source based on the current index image.src = imageArray[currentIndex]; // Increment the index for the next frame index += 0.2; // Adjust the speed of animation as needed } // Draw the image ctx.drawImage(image, this.x, this.y, this.width, this.height); } // gravity applied to character applyGravity() { if (!this.isGrounded) { this.vy += GRAVITY; } } // push bullet in bullets array and shoot shoot(angle) { const bulletSpeed = 5; // Adjust the speed as needed const angleInRadians = (angle * Math.PI) / 180; // Shoot bullets at a 30-degree angle // Calculate the initial velocity components based on the angle const vx = bulletSpeed * Math.cos(angleInRadians); const vy = -bulletSpeed * Math.sin(angleInRadians); const bullet1 = new Bullet( this.x + this.width / 2 - 25, this.y + this.height - 33, 10, 50, 1, vx, vy ); const bullet2 = new Bullet( this.x + this.width / 2 - 25, this.y + this.height - 33, 10, 50, 1, -vx, vy ); this.bullets.push(bullet1, bullet2, bullet1, bullet2); // bullet fire sound let bulletAudio = new Audio( "https://rpg.hamsterrepublic.com/wiki-images/2/21/Collision8-Bit.ogg" ); bulletAudio.play(); } // drawing bullets drawBullets() { for (let i = this.bullets.length - 1; i >= 0; i--) { this.bullets[i].update(); this.bullets[i].draw(ctx); // Check if bullet goes off-screen and remove it if (this.bullets[i].y > canvas.height) { this.bullets.splice(i, 1); } } } }
package cn.itcast.oa.view.action; import java.util.HashSet; import java.util.List; import org.apache.commons.codec.cli.Digest; import org.apache.commons.codec.digest.DigestUtils; import org.springframework.context.annotation.Scope; import org.springframework.stereotype.Controller; import com.opensymphony.xwork2.ActionContext; import cn.itcast.oa.base.BaseAction; import cn.itcast.oa.domain.Department; import cn.itcast.oa.domain.Role; import cn.itcast.oa.domain.User; import cn.itcast.oa.util.DepartmentUtils; @Controller @Scope("prototype") public class UserAction extends BaseAction<User>{ private Long departmentId; private Long[] roleIds; /** 列表*/ public String list() throws Exception{ List<User> userList=userService.findAll(); ActionContext.getContext().put("userList", userList); return "list"; } /** 删除*/ public String delete() throws Exception{ userService.delete(model.getId()); return "toList"; } /** 添加页面*/ public String addUI() throws Exception{ //准备数据 departmentList List<Department> topList=departmentService.findTopList(); List<Department> departmentList=DepartmentUtils.getAllDepartments(topList); ActionContext.getContext().put("departmentList",departmentList ); //准备数据roleList List<Role> roleList=roleService.findAll(); ActionContext.getContext().put("roleList", roleList); return "saveUI"; } /**添加*/ public String add() throws Exception{ // //封装到对象中 (当model是实体类型时,也可以使用model,但要设置未封装的属性) //设置部门 model.setDepartment(departmentService.getById(departmentId)); //设置岗位 List<Role> roleList=roleService.getByIds(roleIds); model.setRoles(new HashSet<Role>(roleList)); //使用md5摘要 String md5Digest=DigestUtils.md5Hex("1234"); model.setPassword(md5Digest); // User user=new User(); // user.setName(model.getName()); // user.setDescription(model.getDescription()); // //保存到数据库中 // userService.save(user); userService.save(model); return "toList"; } /** 修改页面*/ public String editUI() throws Exception{ //准备数据 departmentList List<Department> topList=departmentService.findTopList(); List<Department> departmentList=DepartmentUtils.getAllDepartments(topList); ActionContext.getContext().put("departmentList",departmentList ); //准备数据roleList List<Role> roleList=roleService.findAll(); ActionContext.getContext().put("roleList", roleList); //准备回显数据 User user=userService.getById(model.getId()); ActionContext.getContext().getValueStack().push(user); if(user.getDepartment()!=null) departmentId=user.getDepartment().getId(); if(user.getRoles()!=null) { roleIds=new Long[user.getRoles().size()]; int index=0; for(Role role:user.getRoles()) { roleIds[index++]=role.getId(); } } return "saveUI"; } /** 修改*/ public String edit() throws Exception{ //从数据库获取原对象 User user=userService.getById(model.getId()); //设置修改的属性 user.setLoginName(model.getLoginName()); user.setName(model.getName()); user.setGender(model.getGender()); user.setPhoneNumber(model.getPhoneNumber()); user.setEmail(model.getEmail()); user.setDescription(model.getDescription()); //设置部门 user.setDepartment(departmentService.getById(departmentId)); //设置岗位 List<Role> roleList=roleService.getByIds(roleIds); user.setRoles(new HashSet<Role>(roleList)); //保存到数据库 userService.update(user); return "toList"; } /**初始化密码功能*/ public String initPassword()throws Exception{ //从数据库获取原对象 User user=userService.getById(model.getId()); //设置修改的属性 String md5Digest=DigestUtils.md5Hex("1234"); user.setPassword(md5Digest); //保存到数据库 userService.update(user); return "toList"; } /**登录页面*/ public String loginUI() throws Exception{ return "loginUI"; } /**登录*/ public String login() throws Exception{ User user=userService.findByLoginNameAndPassword(model.getLoginName(),model.getPassword()); if(user==null) { addFieldError("login", "用户名或密码不正确!"); return "loginUI"; } else { //登录用户 ActionContext.getContext().getSession().put("user", user); return "toIndex"; } } /**注销*/ public String logout() throws Exception{ ActionContext.getContext().getSession().remove("user"); return "logout"; } //---------------- public Long getDepartmentId() { return departmentId; } public void setDepartmentId(Long departmentId) { this.departmentId = departmentId; } public Long[] getRoleIds() { return roleIds; } public void setRoleIds(Long[] roleIds) { this.roleIds = roleIds; } }
import { Field, InputType } from "@nestjs/graphql"; import { IsString, IsNotEmpty, MaxLength, MinLength } from "class-validator"; @InputType() export class CreateTodoInput { @Field( { description: 'Header of TODO' } ) @IsString() @IsNotEmpty() @MinLength(1) @MaxLength(80) title: string; @Field( { description: "What needs to be done?" } ) @IsString() @IsNotEmpty() @MinLength(1) @MaxLength(200) description: string; }
import { StageType, TournamentStatus } from '@generated/graphql' import React from 'react' import { TournamentCard, TournamentCardProps } from '.' import dayjs from 'dayjs' import { Story } from '@storybook/react' export default { title: 'Components/UI/TournamentCard', component: TournamentCard, } export const ExampleTournamentCard: Story<TournamentCardProps> = ({ ...args }) => <TournamentCard {...args} /> ExampleTournamentCard.args = { tournament: { id: 'tournament', title: 'Test Tournament', date: dayjs('2021-01-01 18:00:00').toDate(), game: { title: 'Brawlhalla' }, gameMode: { name: '1vs1' }, playersCount: 8, hostUser: { id: '1', displayName: 'SpooderMan', linkedAccounts: [{ id: '1' }], }, platforms: [{ name: 'PC' }], stages: [{ type: StageType.Single }], maxPlayers: 100, status: TournamentStatus.Started, roundsCount: 5, completedRounds: 3, activeRound: { id: '1' }, }, backgroundSrc: 'https://images.unsplash.com/photo-1506865952017-eba1745396f6?ixid=MXwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHw%3D&ixlib=rb-1.2.1&auto=format&fit=crop&w=1825&q=80', }