text
stringlengths
184
4.48M
import { FC, ReactNode } from 'react' import { useNavigate } from 'react-router-dom' import { AiFillCloseCircle } from 'react-icons/ai' import { BottomNav, Divider, Typography } from '../..' import styles from './LayoutDetails.module.scss' interface Props { children: ReactNode title: string } export const LayoutDetails: FC<Props> = ({ children, title = '' }) => { const navigate = useNavigate() const backHandler = () => { navigate(-1) } return ( <div className={styles.layoutDetails}> <button className={styles.close} onClick={backHandler}> <AiFillCloseCircle size='1.5rem' /> </button> <Typography tag='h1' size='xl' className={styles.title}> {title} </Typography> <Divider /> {children} <div className={styles.bottomNavWrapper}> <Divider className={styles.bottomNavDivider} /> <BottomNav /> </div> </div> ) }
import * as mariadb from 'mariadb'; import logger from '../logger.js'; /** * @type {mariadb.Pool} */ export let pool; const chickenTableCreate = `CREATE TABLE IF NOT EXISTS chicken ( id INT NOT NULL AUTO_INCREMENT, farmyard_id INT NOT NULL, name VARCHAR(255) NOT NULL, birthday DATE, weight INT NOT NULL, steps INT NOT NULL DEFAULT 0, isRunning BOOLEAN NOT NULL DEFAULT false, PRIMARY KEY (id), FOREIGN KEY (farmyard_id) REFERENCES farmyard(id) )`; const farmYardTableCreate = `CREATE TABLE IF NOT EXISTS farmyard ( id INT NOT NULL AUTO_INCREMENT, name VARCHAR(255) NOT NULL, PRIMARY KEY (id) )`; export async function setupDatabase() { let connection; try { connection = await mariadb.createConnection({ host: process.env.DB_HOST, user: process.env.DB_USER, password: process.env.DB_PWD, }); let result = await connection.query(`CREATE DATABASE IF NOT EXISTS ${process.env.DB_NAME}`); if (result.affectedRows === 1) logger.info(`Database '${process.env.DB_NAME}' created`); pool = mariadb.createPool({ host: process.env.DB_HOST, user: process.env.DB_USER, password: process.env.DB_PWD, database: process.env.DB_NAME, }); result = await pool.query(farmYardTableCreate); if (result.warningStatus === 0) logger.info('Table \'farmyard\' created'); result = await pool.query(chickenTableCreate); if (result.warningStatus === 0) logger.info('Table \'chicken\' created'); return undefined; } catch (err) { return err; } finally { if (connection) connection.end(); } }
import React from "react"; import { createRoot } from "react-dom/client"; import News from "./News"; import useNews from "../../hooks/useNews"; const Top = () => { const { news, getNews, isLoading } = useNews(); if (isLoading) getNews(); return ( <main style={{ textAlign: "center" }}> <h2>店舗ニュース</h2> {isLoading ? ( <h2>Now Loading...</h2> ) : ( <div style={{ display: "flex", flexWrap: "wrap" }}> {news.length ? ( <> {news.map((val) => ( <News key={val.id} title={val.title} text={val.text} image={val.image} date={val.date} /> ))} </> ) : ( <p>ニュースがありません</p> )} </div> )} </main> ); }; const container = document.querySelector("#app")!; const root = createRoot(container); root.render(<Top />);
import 'package:cep_register/constants/breakpoints.dart'; import 'package:cep_register/constants/colors.dart'; import 'package:cep_register/constants/string.dart'; import 'package:cep_register/models/cep.model.dart'; import 'package:cep_register/viewModel/cep.view_model.dart'; import 'package:cep_register/widgets/label_h1.dart'; import 'package:cep_register/widgets/label_h2.dart'; import 'package:flutter/material.dart'; class ShowSearchedCep extends StatelessWidget { ShowSearchedCep({required this.cep, super.key}); final CepModel cep; final TextEditingController referenciaController = TextEditingController(text: ""); @override Widget build(BuildContext context) { var estado = cep.uf ?? ""; var endereco = cep.logradouro ?? ""; var cidade = cep.localidade ?? ""; return Container( decoration: const BoxDecoration( color: CustonColors.backgroundColor, borderRadius: BorderRadius.all(Radius.circular(Breakpoints.b16)), ), child: Padding( padding: const EdgeInsets.all(Breakpoints.b16), child: Column( mainAxisAlignment: MainAxisAlignment.start, crossAxisAlignment: CrossAxisAlignment.start, children: [ Center(child: LabelH2(label: endereco)), Padding( padding: const EdgeInsets.only(bottom: Breakpoints.b8), child: Row( crossAxisAlignment: CrossAxisAlignment.center, mainAxisAlignment: MainAxisAlignment.center, children: [ LabelH2(label: cidade), const SizedBox(width: Breakpoints.b8), LabelH2(label: estado) ], ), ), const SizedBox(width: Breakpoints.b32), const LabelH2(textAlign: TextAlign.start, label: addReference), const SizedBox(width: Breakpoints.b8), TextFormField( controller: referenciaController, ), Center( child: ElevatedButton( style: ElevatedButton.styleFrom( backgroundColor: Colors.white, ), child: const LabelH2( label: registerCep, ), onPressed: () { if (referenciaController.text != "") { FocusScope.of(context).unfocus(); cep.referencia = referenciaController.text; CepViewModel().registerCEP(cep); _showAlertDialog( context, referenciaController.text, cep.CEP!); } else { _showAlertDialog( context, referenciaController.text, cep.CEP!); } }, ), ) ], ), ), ); } } void _showAlertDialog(BuildContext context, String reference, String cep) { showDialog( context: context, builder: (BuildContext context) { return AlertDialog( title: const LabelH1(label: atention), content: LabelH2( label: reference.isEmpty ? needReference : "O cep $cep foi salvo com a referencia: $reference"), actions: <Widget>[ ElevatedButton( child: const LabelH2(label: close), onPressed: () { Navigator.of(context).pop(); }, ), ], ); }, ); }
using System; using System.Threading; using System.Threading.Tasks; using AutoMapper; using CleanArchitecture.TestApplication.Domain.Common.Exceptions; using CleanArchitecture.TestApplication.Domain.Repositories.Inheritance; using Intent.RoslynWeaver.Attributes; using MediatR; [assembly: DefaultIntentManaged(Mode.Fully)] [assembly: IntentTemplate("Intent.Application.MediatR.QueryHandler", Version = "1.0")] namespace CleanArchitecture.TestApplication.Application.Inheritance.ConcreteClasses.GetConcreteClassById { [IntentManaged(Mode.Merge, Signature = Mode.Fully)] public class GetConcreteClassByIdQueryHandler : IRequestHandler<GetConcreteClassByIdQuery, ConcreteClassDto> { private readonly IConcreteClassRepository _concreteClassRepository; private readonly IMapper _mapper; [IntentManaged(Mode.Ignore)] public GetConcreteClassByIdQueryHandler(IConcreteClassRepository concreteClassRepository, IMapper mapper) { _concreteClassRepository = concreteClassRepository; _mapper = mapper; } [IntentManaged(Mode.Fully, Body = Mode.Fully)] public async Task<ConcreteClassDto> Handle(GetConcreteClassByIdQuery request, CancellationToken cancellationToken) { var concreteClass = await _concreteClassRepository.FindByIdAsync(request.Id, cancellationToken); if (concreteClass is null) { throw new NotFoundException($"Could not find ConcreteClass '{request.Id}'"); } return concreteClass.MapToConcreteClassDto(_mapper); } } }
<?php /** * @package test * @author Valerio Riva <[email protected]> * @copyright Copyright (c) 2012, Lynx s.r.l. * @license http://www.gnu.org/licenses/gpl-2.0.html GNU Public License v.2 * @version 0.1 */ class QuestionMultipleCheckTest extends QuestionTest { protected $variation = ADA_NORMAL_TEST_VARIATION; /** * used to configure object with database's data options * * @access protected * */ protected function configureProperties() { if (!parent::configureProperties()) { return false; } //fourth character: variation $this->variation = $this->tipo{3}; return true; } /** * return necessaries html objects that represent the object * * @access protected * * @param $ref reference to the object that will contain this rendered object * @param $feedback "show feedback" flag on rendering * @param $rating "show rating" flag on rendering * @param $rating_answer "show correct answer" on rendering * * @return an object of CDOMElement */ protected function renderingHtml(&$ref = null,$feedback=false,$rating=false,$rating_answer=false) { if (!$this->display) return new CText(''); //if we don't have to display this question, let's return an empty item $out = parent::renderingHtml($ref,$feedback,$rating,$rating_answer); $name = $this->getPostFieldName(); $post_data = $this->getPostData(); if (!empty($this->_children)) { $_children = $this->_children; if ($this->searchParent('RootTest')->shuffle_answers) { shuffle($_children); } while (!empty($_children)) { foreach($_children as $k=>$v) { if ($v->extra_answer && count($_children)>1) { continue; } $inputId = $name.'['.$k.']'; $answer = CDOMElement::create('label','for:'.$inputId); $answer->addChild(new CText($v->testo)); $input = CDOMElement::create('checkbox','id:'.$inputId); $input->setAttribute('class','radio_multiple_test'); $input->setAttribute('style','vertical-align:middle; margin-top:0px;'); $input->setAttribute('name',$name.'['.self::POST_ANSWER_VAR.'][]'); $input->setAttribute('value',$v->id_nodo); //feedback section if ($feedback) { $input->setAttribute('disabled',''); if ($this->givenAnswer['risposta'][self::POST_ANSWER_VAR] && in_array($v->id_nodo,$this->givenAnswer['risposta'][self::POST_ANSWER_VAR])) { $input->setAttribute('checked', ''); if ($v->correttezza>0) { $answer->setAttribute('class', 'right_answer_test'); } else { $answer->setAttribute('class', 'wrong_answer_test'); } } } else if ($post_data[self::POST_ANSWER_VAR] == $v->id_nodo) { $input->setAttribute('checked',''); } $li = CDOMElement::create('li'); $class = 'answer_multiple_test'; switch($this->variation) { case ADA_ERASE_TEST_VARIATION: $class.= ' erase_variation_test'; break; case ADA_HIGHLIGHT_TEST_VARIATION: $class.= ' highlight_variation_test'; break; } $li->setAttribute('class', $class); $li->addChild($input); $li->addChild($answer); $string = $answer->getAttribute('class'); if ($_SESSION['sess_id_user_type'] == AMA_TYPE_STUDENT) { if ($feedback && $rating_answer && !strstr($string,'right_answer_test')) { $correctAnswer = $this->getMostCorrectAnswer(); if ($correctAnswer) { $popup = CDOMElement::create('div','id:popup_'.$this->id_nodo); $popup->setAttribute('style','display:none;'); $popup->addChild(new CText($correctAnswer->testo)); $answer->setAttribute('class', $string.' answerPopup'); $answer->setAttribute('title',$this->id_nodo); $li->addChild(new CText($popup->getHtml())); } } else if ($feedback && $rating) { $li->addChild(new CText(' ('.$v->correttezza.' '.translateFN('Punti').')')); } } if ($v->extra_answer && $this->variation == ADA_NORMAL_TEST_VARIATION) { $answer = CDOMElement::create('text'); $answer->setAttribute('class','text_standard_test'); $answer->setAttribute('name',$name.'['.self::POST_OTHER_VAR.']['.$v->id_nodo.']'); $answer->setAttribute('onkeyup','autoCheckForOtherAnswer(this);'); if ($feedback && isset($this->givenAnswer['risposta'][self::POST_OTHER_VAR][$v->id_nodo])) { $answer->setAttribute('disabled', ''); $answer->setAttribute('value',$this->givenAnswer['risposta'][self::POST_OTHER_VAR][$v->id_nodo]); } else if (!empty($post_data[self::POST_OTHER_VAR])) { $answer->setAttribute('value',$post_data[self::POST_OTHER_VAR]); } $li->addChild(new CText('&nbsp;')); $li->addChild($answer); } if ($_SESSION['sess_id_user_type'] != AMA_TYPE_STUDENT) { $v->correttezza = is_null($v->correttezza)?0:$v->correttezza; $li->addChild(new CText(' ('.$v->correttezza.' '.translateFN('punti').')')); } $ref->addChild($li); unset($_children[$k]); } $ref->addChild(CDOMElement::create('li','class:clear')); } } return $out; } /** * implementation of exerciseCorrection for MultipleCheck question type * * @access public * * @return a value representing the points earned or an array containing points and attachment elements */ public function exerciseCorrection($data) { $points = null; if (is_array($data) && !empty($data)) { $points = 0; if (!empty($data[self::POST_ANSWER_VAR])) { foreach($data[self::POST_ANSWER_VAR] as $k=>$v) { $answer = $this->searchChild($v); if ($answer) { $points+= $answer->correttezza; } } } } if ($points > $this->getMaxScore()) { $points = $this->getMaxScore(); } return array('points'=>$points,'attachment'=>null); } /** * return exercise max score * * @access public * * @return a value representing the max score */ public function getMaxScore() { $score = 0; if (!empty($this->_children)) { foreach($this->_children as $v) { $score+= $v->correttezza; } } return $score; } }
import { Injectable } from '@angular/core'; import { FormBuilder, FormControl, FormGroup, Validators } from '@angular/forms'; @Injectable() export class UserFormService { constructor ( private readonly fb: FormBuilder ) {} buildForm (): FormGroup { return this.fb.group({ name: new FormControl('', [Validators.required]), lastName: new FormControl('', [Validators.required]), email: new FormControl('', [Validators.required, Validators.pattern('([a-zA-Z0-9][-a-zA-Z0-9_\+\.]*[a-zA-Z0-9])\@([a-zA-Z0-9][-a-zA-Z0-9\.]*[a-zA-Z0-9])[\.]+([a-zA-Z0-9]{2,4})$')] ), avatar: new FormControl('', [Validators.required]), image: new FormControl('', []), }); } }
/** * @license Apache-2.0 * * Copyright (c) 2020 The Stdlib Authors. * * 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. */ 'use strict'; // MODULES // var tape = require( 'tape' ); var floor = require( '@stdlib/math-base-special-floor' ); var isnan = require( '@stdlib/math-base-assert-is-nan' ); var Float32Array = require( '@stdlib/array-float32' ); var sdsnanmeanors = require( './../lib/sdsnanmeanors.js' ); // TESTS // tape( 'main export is a function', function test( t ) { t.ok( true, __filename ); t.strictEqual( typeof sdsnanmeanors, 'function', 'main export is a function' ); t.end(); }); tape( 'the function has an arity of 3', function test( t ) { t.strictEqual( sdsnanmeanors.length, 3, 'has expected arity' ); t.end(); }); tape( 'the function calculates the arithmetic mean of a strided array, ignoring `NaN` values', function test( t ) { var x; var v; x = new Float32Array( [ 1.0, -2.0, -4.0, 5.0, NaN, 0.0, 3.0 ] ); v = sdsnanmeanors( x.length, x, 1 ); t.strictEqual( v, 0.5, 'returns expected value' ); x = new Float32Array( [ -4.0, NaN ] ); v = sdsnanmeanors( x.length, x, 1 ); t.strictEqual( v, -4.0, 'returns expected value' ); x = new Float32Array( [ NaN, NaN ] ); v = sdsnanmeanors( x.length, x, 1 ); t.strictEqual( isnan( v ), true, 'returns expected value' ); t.end(); }); tape( 'if provided an `N` parameter less than or equal to `0`, the function returns `NaN`', function test( t ) { var x; var v; x = new Float32Array( [ 1.0, -2.0, -4.0, 5.0, 3.0 ] ); v = sdsnanmeanors( 0, x, 1 ); t.strictEqual( isnan( v ), true, 'returns expected value' ); v = sdsnanmeanors( -1, x, 1 ); t.strictEqual( isnan( v ), true, 'returns expected value' ); t.end(); }); tape( 'if provided an `N` parameter equal to `1`, the function returns the first element', function test( t ) { var x; var v; x = new Float32Array( [ 1.0, -2.0, -4.0, 5.0, 3.0 ] ); v = sdsnanmeanors( 1, x, 1 ); t.strictEqual( v, 1.0, 'returns expected value' ); t.end(); }); tape( 'the function supports a `stride` parameter', function test( t ) { var N; var x; var v; x = new Float32Array([ 1.0, // 0 2.0, 2.0, // 1 -7.0, -2.0, // 2 3.0, 4.0, // 3 2.0, NaN // 4 ]); N = floor( x.length / 2 ); v = sdsnanmeanors( N, x, 2 ); t.strictEqual( v, 1.25, 'returns expected value' ); t.end(); }); tape( 'the function supports a negative `stride` parameter', function test( t ) { var N; var x; var v; x = new Float32Array([ 1.0, // 4 2.0, 2.0, // 3 -7.0, -2.0, // 2 3.0, 4.0, // 1 2.0, NaN // 0 ]); N = floor( x.length / 2 ); v = sdsnanmeanors( N, x, -2 ); t.strictEqual( v, 1.25, 'returns expected value' ); t.end(); }); tape( 'if provided a `stride` parameter equal to `0`, the function returns the first element', function test( t ) { var x; var v; x = new Float32Array( [ 1.0, -2.0, -4.0, 5.0, 3.0 ] ); v = sdsnanmeanors( x.length, x, 0 ); t.strictEqual( v, 1.0, 'returns expected value' ); t.end(); }); tape( 'the function supports view offsets', function test( t ) { var x0; var x1; var N; var v; x0 = new Float32Array([ 2.0, 1.0, // 0 2.0, -2.0, // 1 -2.0, 2.0, // 2 3.0, 4.0, // 3 6.0, NaN // 4 ]); x1 = new Float32Array( x0.buffer, x0.BYTES_PER_ELEMENT*1 ); // start at 2nd element N = floor(x1.length / 2); v = sdsnanmeanors( N, x1, 2 ); t.strictEqual( v, 1.25, 'returns expected value' ); t.end(); });
package org.example.consumermodule.rabbitmq.listeners; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.*; import org.example.consumermodule.service.AnimalStreamService; import org.example.producermodule.dto.AnimalDTO; import org.example.producermodule.dto.AnimalDeleteDTO; import org.example.producermodule.dto.AnimalUpdateDTO; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.Mockito; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.mock.mockito.MockBean; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.aot.DisabledInAotMode; import org.springframework.test.context.junit.jupiter.SpringExtension; @ContextConfiguration(classes = {AnimalStreamApiListener.class}) @ExtendWith(SpringExtension.class) @DisabledInAotMode class AnimalStreamApiListenerTest { @Autowired private AnimalStreamApiListener animalStreamApiListener; @MockBean private AnimalStreamService animalStreamService; /** * Method under test: {@link AnimalStreamApiListener#save(AnimalDTO)} */ @Test void testSave() { // Arrange doNothing().when(animalStreamService).save(any(), any()); AnimalDTO animalDTO = new AnimalDTO("Name", "Kind Animal", "Venomous", "Type Power Supply", "Age"); // Act animalStreamApiListener.save(animalDTO); // Assert that nothing has changed verify(animalStreamService, times(1)).save(any(), any()); assertEquals("Age", animalDTO.getAge()); assertEquals("Kind Animal", animalDTO.getKindAnimal()); assertEquals("Name", animalDTO.getName()); assertEquals("Type Power Supply", animalDTO.getTypePowerSupply()); assertEquals("Venomous", animalDTO.getVenomous()); } /** * Method under test: {@link AnimalStreamApiListener#update(AnimalUpdateDTO)} */ @Test void testUpdate() { // Arrange doNothing().when(animalStreamService).update(any()); // Act animalStreamApiListener.update(new AnimalUpdateDTO()); // Assert that nothing has changed verify(animalStreamService, times(1)).update(any()); } /** * Method under test: {@link AnimalStreamApiListener#delete(AnimalDeleteDTO)} */ @Test void testDelete() { // Arrange doNothing().when(animalStreamService).delete(any()); // Act animalStreamApiListener.delete(new AnimalDeleteDTO()); // Assert that nothing has changed verify(animalStreamService, times(1)).delete(any()); } }
/* Problem Description Given an integer n, you have to find the nth fibonacci number. The fibonacci sequence is given by 0,1,1,2,3,5,8,... where 0 and 1 are the 0th and 1st fibonacci numbers respectively and every consecutive number is the sum of the previous two numbers in the sequence. Input format There is one line of input, containing an integer n. Output format Print the nth fibonacci number. Sample Input 1 3 Sample Output 1 2 Explanation 1 3rd fibonacci number is equal to the sum of 1st and 2nd fibonacci numbers i.e. 1 + 1 = 2. */ function nthFibonacciNumber(n) { if (n < 0) { return -1; } if (n <= 1) { return n; } return nthFibonacciNumber(n - 1) + nthFibonacciNumber(n - 2); } let result = nthFibonacciNumber(5); console.log("Fifth fibonacii number is : ", result); let result2 = nthFibonacciNumber(3); console.log("Third fibonacii number is : ", result2);
import { Component, OnInit } from '@angular/core'; import { FormControl, FormGroup, FormBuilder, Validators, } from '@angular/forms'; import { MatDialog } from '@angular/material/dialog'; import { MatSnackBar } from '@angular/material/snack-bar'; import { ActivatedRoute, Router } from '@angular/router'; import { switchMap } from 'rxjs/operators'; import { ConfirmDialogItemComponent } from '../../components/confirm-dialog-item/confirm-dialog-item.component'; import { ItemDto } from '../../interfaces/characters.interfaces'; import { CharactersService } from '../../services/characters.service'; import { ItemsService } from '../../services/items.service'; @Component({ selector: 'app-add-item', templateUrl: './add-item.component.html', styles: [ ` /* Chrome, Safari, Edge, Opera */ input::-webkit-outer-spin-button, input::-webkit-inner-spin-button { -webkit-appearance: none; margin: 0; } /* Firefox */ input[type='number'] { -moz-appearance: textfield; } img { width: 600px; height: 600px; } .detailContainer { text-align: center; justify-content: center; align-items: center; border: 5px solid black; border-radius: 7px; padding: 10px; } .detailContainerTitle { text-align: center; justify-content: center; align-items: center; } input { margin-right: 50px; } .input-container { margin-bottom: 30px; } .textcontainer { margin-top: 10px; margin-bottom: 10px; border: 2px solid grey; border-radius: 10px; width: 200px; height: 30px; position: relative; } .textcontainerId { margin-top: 10px; margin-bottom: 1px; border: 2px solid grey; border-radius: 10px; width: 70px; height: 30px; position: relative; } .margtoptitle { margin-top: 10px; } .content { position: absolute; width: inherit; height: auto; top: 13%; transform: translateY(-13%); text-align: center; } strong { margin-left: 10px; font-size: 35px; } `, ], }) // implements OnInit export class AddItemComponent { action: string = ''; action2: string = ''; get nameErrorMsg() { if (this.itemForm.get('itemName')?.errors?.required) { return 'El nombre es obligatorio'; } else if (this.itemForm.get('itemName')?.errors?.minlength) { return 'El nombre debe contener al menos 3 caracteres'; } else return; } get descErrorMsg() { if (this.itemForm.get('itemDesc')?.errors?.required) { return 'La descripción es obligatoria'; } else if (this.itemForm.get('itemDesc')?.errors?.minlength) { return 'La descripción es demasiado corta (min. 20 caracteres)'; } else return; } get weightErrorMsg() { if (this.itemForm.get('itemWeight')?.errors?.required) { return 'El peso es obligatorio'; } else if (this.itemForm.get('itemWeight')?.errors?.min) { return 'El peso no puede ser menor a 0'; } else return; } get priceErrorMsg() { if (this.itemForm.get('itemPrice')?.errors?.required) { return 'El precio es obligatorio'; } else if (this.itemForm.get('itemPrice')?.errors?.min) { return 'El precio no puede ser menor a 0'; } else return; } itemForm: FormGroup = this.formBuilder.group({ itemName: ['', [Validators.required, Validators.minLength(3)]], itemType: ['Arma', [Validators.required]], itemDesc: ['', [Validators.required, Validators.minLength(20)]], itemWeight: [0, [Validators.required, Validators.min(0)]], itemPrice: [0, [Validators.required, Validators.min(0)]], itemQtty: [0, [Validators.min(0)]], itemDur: [0, [Validators.min(0)]], itemUses: [0, [Validators.min(0)]], itemImg: [''], }); item: ItemDto = { name: '', type: '', description: '', weight: 0, price: 0, quantity: 0, itemImg: '', }; constructor( private router: Router, private activatedRoute: ActivatedRoute, private snackBar: MatSnackBar, private dialog: MatDialog, private formBuilder: FormBuilder, private itemsService: ItemsService ) {} ngOnInit(): void { if (this.router.url.includes('edit')) { this.activatedRoute.params .pipe( switchMap(({ itemId }) => this.itemsService.getItemByIdPostgres(itemId) ) ) .subscribe((item) => { this.item = item; this.itemForm.reset({ itemName: item.name, itemType: item.type, itemDesc: item.description, itemPrice: item.price, itemWeight: item.weight, itemQtyy: item.quantity, itemDur: item.durability, itemUses: item.uses, itemImg: item.itemImg, }); }); this.action = 'Editar'; this.action2 = 'Actualizar'; } else { this.action = 'Nuevo'; this.action2 = 'Crear'; } } saveItem() { let item: ItemDto, item2: ItemDto; if (this.router.url.includes('edit')) { console.log('editando'); let id: number = 0; this.activatedRoute.params.subscribe(({ characterId }) => { this.activatedRoute.params.subscribe(({ itemId }) => { id = Number(itemId); }); console.log(id); item = { itemId: id, characterId: Number(characterId), name: this.itemForm.get('itemName')?.value, type: this.itemForm.get('itemType')?.value, description: this.itemForm.get('itemDesc')?.value, price: this.itemForm.get('itemPrice')?.value, weight: this.itemForm.get('itemWeight')?.value, quantity: this.itemForm.get('itemQtyy')?.value, durability: this.itemForm.get('itemDur')?.value, uses: this.itemForm.get('itemUses')?.value, itemImg: this.itemForm.get('itemImg')?.value, }; this.item = item; console.log(this.item); this.itemsService.updateItemPostgres(this.item).subscribe((item) => { console.log(item); this.showSnackBar(`${item.name} ha sido actualizado correctamente`); }); }); } else { console.log('creando'); this.activatedRoute.params.subscribe(({ characterId }) => { item2 = { characterId: Number(characterId), name: this.itemForm.get('itemName')?.value, type: this.itemForm.get('itemType')?.value, description: this.itemForm.get('itemDesc')?.value, price: this.itemForm.get('itemPrice')?.value, weight: this.itemForm.get('itemWeight')?.value, quantity: this.itemForm.get('itemQtyy')?.value, durability: this.itemForm.get('itemDur')?.value, uses: this.itemForm.get('itemUses')?.value, itemImg: this.itemForm.get('itemImg')?.value, }; this.item = item2; console.log(this.item); this.itemsService .postItemPostgres(characterId, this.item) .subscribe((item) => { this.activatedRoute.params.subscribe(({ userId, characterId }) => { this.showSnackBar(`${item.name} ha sido creado correctamente`); // this.router.navigate(['..', String(userId), 'home/characters/1', String(characterId), 'inventory']); this.router.navigate([ `../../${userId}/home/characters/${userId}1/${characterId}/inventory`, ]); }); }); }); } console.log('saving'); if (this.itemForm.get('itemName')?.value === 0) { this.showSnackBar('El personaje creado debe tener un nombre'); return; } } deleteItem() { const dialog = this.dialog.open(ConfirmDialogItemComponent, { width: '350px', data: { ...this.item }, }); dialog.afterClosed().subscribe((res) => { if (res) { this.itemsService .deleteItemPostgres(this.item.itemId!) .subscribe(() => { this.activatedRoute.params.subscribe(({ userId, characterId }) => { console.log(userId, characterId); this.showSnackBar( `${this.item.name} ha sido borrado correctamente` ); this.router.navigate([ `../../${userId}/home/characters/${userId}1/${characterId}/inventory`, ]); }); }); } }); } isAddItem() { return this.router.url.includes('additem'); } showSnackBar(msg: string) { this.snackBar.open(msg, 'Ok!', { duration: 3000, }); } isFieldValid(field: string) { return ( this.itemForm.get(field)?.invalid && this.itemForm.get(field)?.touched ); } }
import { Module } from '@nestjs/common'; import { ConfigModule } from '@nestjs/config'; import { TypeOrmModule } from '@nestjs/typeorm'; import { AppController } from './app.controller'; import { AppService } from './app.service'; import { UserModule } from './user/user.module'; import { ServicesModule } from './services/services.module'; import { ServiceCategoriesModule } from './service_categories/service_categories.module'; import { MulterModule } from '@nestjs/platform-express'; import { ServeStaticModule } from '@nestjs/serve-static'; import { join } from 'path'; import { ReviewsModule } from './reviews/reviews.module'; import { MessagesModule } from './messages/messages.module'; import { OrdersModule } from './orders/orders.module'; @Module({ imports: [ ServeStaticModule.forRoot({ rootPath: join(__dirname, '..', 'public'), }), ConfigModule.forRoot({ isGlobal: true, }), TypeOrmModule.forRoot({ type: 'mysql', host: process.env.DB_HOST, port: parseInt(process.env.DB_PORT), username: process.env.DB_USERNAME, password: process.env.DB_PASSWORD, database: process.env.DB_NAME, synchronize: true, autoLoadEntities: true, }), UserModule, ServicesModule, ServiceCategoriesModule, ReviewsModule, MessagesModule, MulterModule.register({}), OrdersModule, ], controllers: [AppController], providers: [AppService], }) export class AppModule {}
classdef Net < handle properties id; cells; net_size; end properties(Constant) smooth_param = 256 end methods function [obj] = Net(id, cells) obj.id = id; obj.cells = cells; obj.net_size = length(cells); end function [pins] = locate_pins(obj, x, y) pins.x = x(obj.cells); pins.y = y(obj.cells); end function [W, dW] = WAWL(obj, x, y) %% ------------- WAWL() % Computation of value and gradient of the weighted-average smooth % approximation of the net's half-perimeter wirelength. pins = obj.locate_pins(x, y); [maxSx, maxdSx] = obj.smooth_extrema(pins.x, obj.smooth_param); [maxSy, maxdSy] = obj.smooth_extrema(pins.y, obj.smooth_param); [minSx, mindSx] = obj.smooth_extrema(pins.x, -obj.smooth_param); [minSy, mindSy] = obj.smooth_extrema(pins.y, -obj.smooth_param); W = maxSx - minSx + maxSy - minSy; dW.x = maxdSx - mindSx; dW.y = maxdSy - mindSy; end function [V, dV] = pin_spread(obj, x, y) %% ------------- pin_spread() % Computation of the value and gradient for sum of the variances of % the net's x and y coordinates. pins = obj.locate_pins(x, y); V = var(pins.x) + var(pins.y); dV.x = (2/obj.net_size)*(pins.x - mean(pins.x)); dV.y = (2/obj.net_size)*(pins.y - mean(pins.y)); end end methods(Static) function [S_, dS_] = smooth_extrema(z, t) %% --------------- smooth_extrema() % The smoothing paramater determines whether the minimum (t < 0) or % the maximum (t > 0) of w is approximated. Note that the argument z % is normalized, the approximate maximum is computed, and then % rescaled. This is to prevent overflow in v = exp(t*u). z_norm = norm(z); u = z/z_norm; v = exp(t*u); w = v/sum(v); S = w'*u; % Smooth max of the unit vector u q = w.*(1 + t*(u - S)); S_ = z_norm*S; dS_ = q + (S - q'*u)*u; end end end
let imgQuestao = document.querySelector('.imagemDaQuestao img'); let pergunta = document.querySelector('#pergunta'); let questaoAtual = 0; let questaoNumero = 0; let pontuacao = 0; // ALTERNATIVAS let a = document.querySelector('#a'); let b = document.querySelector('#b'); let c = document.querySelector('#c'); let d = document.querySelector('#d'); // article com a class questoes let articleQuestoes = document.querySelector('.questoes'); // ol li com as alternativas let alternativas = document.querySelector('#alternativas'); // Questões const q1 = { numQuestao: 1, imagem: '1.svg', pergunta: "Qual Constelação é Essa?", alternativaA: "Ursa Maior", alternativaB: "Andrômeda", alternativaC: "Ursa Menor", alternativaD: "Cachorrinho", correta: "Andrômeda", }; const q2 = { numQuestao: 2, imagem: '1.svg', pergunta: "Qual Constelação é Essa?", alternativaA: "Ursa Maior", alternativaB: "Órion", alternativaC: "Ursa Menor", alternativaD: "Cachorrinho", correta: "Ursa Maior", }; const q3 = { numQuestao: 3, imagem: '2.svg', pergunta: "Qual Constelação é Essa?", alternativaA: "Ursa Maior", alternativaB: "Órion", alternativaC: "Ursa Menor", alternativaD: "Cachorrinho", correta: "Ursa Menor", }; const q4 = { numQuestao: 4, imagem: '3.svg', pergunta: "Qual Constelação é Essa?", alternativaA: "Ursa Maior", alternativaB: "Órion", alternativaC: "Ursa Menor", alternativaD: "Cão Maior", correta: "Cão Maior", }; const q5 = { numQuestao: 5, imagem: '4.svg', pergunta: "Qual Constelação é Essa?", alternativaA: "Ursa Maior", alternativaB: "Pégaso", alternativaC: "Ursa Menor", alternativaD: "Cão Maior", correta: "Pégaso", }; // ARRAY DAS QUETÕES const questoes = [q1, q2, q3, q4, q5]; let total = document.querySelector('#total'); // MONTAR A 1a QUESTAO COMPLETA, para iniciar o Quiz imgQuestao.setAttribute('src', 'img/' + q1.imagem); // ADICIONE pergunta.textContent = q1.pergunta; a.textContent = q1.alternativaA; b.textContent = q1.alternativaB; c.textContent = q1.alternativaC; d.textContent = q1.alternativaD; // CONFIGURAR O VALUE INICIAL DA 1a QUESTAO COMPLETA a.setAttribute('value', '1A'); b.setAttribute('value', '1B'); c.setAttribute('value', '1C'); d.setAttribute('value', '1D'); function bloquearAlternativas() { document.querySelector('#alternativas').classList.add('bloqueado'); } function desbloquearAlternativas() { document.querySelector('#alternativas').classList.remove('bloqueado'); } function mostrarQuestao(questaoNumero) { const questao = questoes[questaoNumero]; imgQuestao.setAttribute('src', 'img/' + questao.imagem); pergunta.textContent = questao.pergunta; a.textContent = questao.alternativaA; b.textContent = questao.alternativaB; c.textContent = questao.alternativaC; d.textContent = questao.alternativaD; // Configurar o value das alternativas para a questão atual a.setAttribute('value', questao.numQuestao + 'A'); b.setAttribute('value', questao.numQuestao + 'B'); c.setAttribute('value', questao.numQuestao + 'C'); d.setAttribute('value', questao.numQuestao + 'D'); // Limpar qualquer seleção anterior a.classList.remove('selecionado'); b.classList.remove('selecionado'); c.classList.remove('selecionado'); d.classList.remove('selecionado'); // Atualizar a barra de progresso const progresso = ((questaoNumero + 1) / questoes.length) * 100; document.getElementById('progresso').value = progresso; desbloquearAlternativas(); } function verificarSeAcertou(alternativa, elemento) { const questaoAtual = questoes[questaoNumero]; const respostaSelecionada = alternativa.textContent; if (respostaSelecionada === questaoAtual.correta) { elemento.classList.add('correta'); pontuacao++; // Aumenta a pontuação } else { elemento.classList.add('errado'); } bloquearAlternativas(); setTimeout(function () { questaoNumero++; // Avança para a próxima questão if (questaoNumero < questoes.length) { mostrarQuestao(questaoNumero); } else { mostrarResultados(); } }); } function mostrarResultados() { // Exibe a pontuação e o total de questões document.querySelector('#pontuacao').textContent = pontuacao; document.getElementById('totalQuestoes').textContent = questoes.length; // Exibe a seção de finalização document.getElementById('finalizacao').style.display = 'block'; // Oculta a seção de questões document.querySelector('.tela-principal').style.display = 'none'; document.querySelector('.iniciar').style.display = 'none'; } function reiniciarQuiz() { // Reseta a pontuação e reinicia o quiz pontuacao = 0; questaoNumero = 0; mostrarQuestao(questaoNumero); document.getElementById('finalizacao').style.display = 'none'; document.querySelector('.tela-principal').style.display = 'block'; }
package br.com.moreira; public abstract class CompositeSpecification<T> implements Specification<T> { @Override public abstract boolean isSatisfiedBy(T t); @Override public Specification<T> and(Specification<T> specification){ return new AndSpecification<>(this,specification); } @Override public Specification<T> or(Specification<T> specification){ return new OrSpecification<>(this,specification); } @Override public Specification<T> not(){ return new NotSpecification<>(this); } }
<?php namespace Drupal\Tests\views\Kernel\Handler; use Drupal\Tests\views\Kernel\ViewsKernelTestBase; use Drupal\views\Views; /** * Tests the time interval handler. * * @group views * @see \Drupal\views\Plugin\views\field\TimeInterval */ class FieldTimeIntervalTest extends ViewsKernelTestBase { /** * Views used by this test. * * @var string[] */ public static $testViews = ['test_view']; /** * {@inheritdoc} */ protected static $modules = [ 'node_test_views', ]; /** * Ages dataset. */ protected array $ages = [ [0, '0 sec', 2], [1000, '16 min', 1], [1000000, '1 week 4 days 13 hours 46 min', 4], [100000000, '3 years 2 months', 5], [NULL, '', 3], ]; /** * Tests the TimeInterval handler. */ public function testFieldTimeInterval(): void { $view = Views::getView('test_view'); $view->setDisplay(); $this->executeView($view); foreach ($view->result as $delta => $row) { [, $formatted_value, $granularity] = $this->ages[$delta]; $view->field['age']->options['granularity'] = $granularity; $this->assertEquals($formatted_value, $view->field['age']->advancedRender($row)); } } /** * {@inheritdoc} */ protected function schemaDefinition() { $schema_definition = parent::schemaDefinition(); $schema_definition['views_test_data']['fields']['age']['not null'] = FALSE; return $schema_definition; } /** * {@inheritdoc} */ protected function viewsData() { $data = parent::viewsData(); $data['views_test_data']['age']['field']['id'] = 'time_interval'; return $data; } /** * {@inheritdoc} */ protected function dataSet() { $data_set = parent::dataSet(); foreach ($data_set as $delta => $person) { $data_set[$delta]['age'] = $this->ages[$delta][0]; } return $data_set; } }
public class Cat extends Pet implements Boardable{ private String hairLength; public Cat (String name, String ownerName, String color, int sexid,String hairLength) { super(name,ownerName,color); this.hairLength=hairLength; super.setSex(sexid); } public String getHairLength(){ return this.hairLength; }// returns the string hairLength public String toString() { return "CAT:\n"+super.toString()+"\nHair: "+this.hairLength; } /* method that returns a String that identifies the pet as Cat and returns a complete description of the cat, including the values stored in the Pet parent class.*/ @Override public void setBoardStart(int month, int day, int year) { // TODO Auto-generated method stub super.start_date=year*10000+month*100+day; } @Override public void setBoardEnd(int month, int day, int year) { // TODO Auto-generated method stub super.end_date=year*10000+month*100+day; } @Override public boolean boarding(int month, int day, int year) { // TODO Auto-generated method stub int curr_date=year*10000+month*100+day; if((curr_date<super.end_date&&curr_date>super.start_date)||curr_date==super.end_date||curr_date==super.start_date) return true; return false; } }
package com.drag.ss.fh_stepcounter import FHStepCounterApi import StepToday import android.Manifest import android.app.ActivityManager import android.app.AlarmManager import android.app.PendingIntent import android.content.BroadcastReceiver import android.content.Context import android.content.Intent import android.content.IntentFilter import android.content.pm.PackageManager import android.os.Build import android.provider.Settings.ACTION_REQUEST_SCHEDULE_EXACT_ALARM import android.util.Log import androidx.annotation.RequiresApi import com.drag.ss.fh_stepcounter.interfaces.SensorEventInterface import com.drag.ss.fh_stepcounter.models.SensorResponse import com.drag.ss.fh_stepcounter.receivers.AlarmReceiver import com.drag.ss.fh_stepcounter.receivers.SensorAlarmBootReceiver import com.drag.ss.fh_stepcounter.services.AlarmService import com.dragn.pawday_step.QueueEvent import io.flutter.embedding.engine.plugins.FlutterPlugin import io.flutter.embedding.engine.plugins.activity.ActivityAware import io.flutter.embedding.engine.plugins.activity.ActivityPluginBinding import io.flutter.plugin.common.EventChannel import java.util.Date import kotlin.math.roundToInt /** FhStepcounterPlugin */ class FhStepcounterPlugin: FlutterPlugin, FHStepCounterApi, ActivityAware { private var activity: ActivityPluginBinding? = null private var binding: FlutterPlugin.FlutterPluginBinding? = null companion object{ lateinit var queueEvent: QueueEvent } lateinit var fhStepSensorListener: FHStepCounterSensorListener override fun onAttachedToActivity(binding: ActivityPluginBinding) { activity = binding FHStepCounterApi.setUp(this.binding!!.binaryMessenger, this) } override fun onDetachedFromActivityForConfigChanges() { activity = null FHStepCounterApi.setUp(this.binding!!.binaryMessenger, null) } override fun onReattachedToActivityForConfigChanges(binding: ActivityPluginBinding) { activity = binding FHStepCounterApi.setUp(this.binding!!.binaryMessenger, this) } override fun onDetachedFromActivity() { stop() activity = null FHStepCounterApi.setUp(this.binding!!.binaryMessenger, null) binding = null } override fun onAttachedToEngine(flutterPluginBinding: FlutterPlugin.FlutterPluginBinding) { binding = flutterPluginBinding val eventChannel = EventChannel(this.binding?.binaryMessenger, "io.dragn/pawday/event_channel") FHStepCounterApi.setUp(this.binding!!.binaryMessenger, this) queueEvent = QueueEvent(eventChannel) } override fun onDetachedFromEngine(binding: FlutterPlugin.FlutterPluginBinding) { this.binding = null if(this.binding != null) { FHStepCounterApi.setUp(this.binding!!.binaryMessenger, null) } } fun checkServiceRunning(serviceName: String): HashMap<String, Boolean> { val myMap: HashMap<String, Boolean> = HashMap() var serviceRunning = false val am = activity?.activity?.getSystemService(Context.ACTIVITY_SERVICE) as ActivityManager val l = am.getRunningServices(50) val i: Iterator<ActivityManager.RunningServiceInfo> = l.iterator() while (i.hasNext()) { val runningServiceInfo = i .next() if (runningServiceInfo.service.className == serviceName) { serviceRunning = true if (serviceRunning) { myMap["isRunning"] = serviceRunning } if (runningServiceInfo.foreground) { myMap["isForeground"] = runningServiceInfo.foreground } } } return myMap } override fun requestPermission() { val arrayString = arrayOf<String>(Manifest.permission.ACTIVITY_RECOGNITION) activity?.activity?.requestPermissions(arrayString, 0) if(Build.VERSION.SDK_INT > Build.VERSION_CODES.TIRAMISU){ val alarmManager = this.activity?.activity?.getSystemService(Context.ALARM_SERVICE) as AlarmManager if (!alarmManager.canScheduleExactAlarms()) { this.activity?.activity?.startActivity(Intent(ACTION_REQUEST_SCHEDULE_EXACT_ALARM)) } } } override fun checkPermission(): Boolean { activity?.activity?.let { context -> val alarmManager = context.getSystemService(Context.ALARM_SERVICE) as AlarmManager if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) { when { alarmManager.canScheduleExactAlarms() -> { return activity?.activity?.checkSelfPermission(Manifest.permission.ACTIVITY_RECOGNITION) == PackageManager.PERMISSION_GRANTED } else -> { return false } } } else { return if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) { activity?.activity?.checkSelfPermission(Manifest.permission.ACTIVITY_RECOGNITION) == PackageManager.PERMISSION_GRANTED } else { false } } } return false } override fun onStart(initialTodayStep: Double){ activity?.activity?.let { context -> try { // check if already run this service: val event = HashMap<String, Any>() val isRecording: Boolean = FHStepCounterUtil.getIsRecording(context) if (isRecording) { val data: HashMap<*, *> = checkServiceRunning(AlarmService::class.java.name) if (data.containsKey("isRunning") && data.containsKey("isForeground")) { return } else { FHStepCounterUtil.setIsRecording(context, false) onStart(initialTodayStep) return } } val intent = Intent(context, AlarmReceiver::class.java) intent.setAction(FHStepCounterSensorListener.SENSOR_STEP_BROADCAST) intent.putExtra("enabled", true) intent.putExtra("delay", FHStepCounterSensorListener.ALARM_DELAY_IN_SECOND) intent.putExtra("repeat", true) // val pendingIntent = PendingIntent.getBroadcast( // context, // 0, // intent, // PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_IMMUTABLE // ) // val alarmManager = context.getSystemService(Context.ALARM_SERVICE) as AlarmManager // // alarmManager.setExactAndAllowWhileIdle( // AlarmManager.RTC_WAKEUP, // System.currentTimeMillis() + FHStepCounterSensorListener.ALARM_DELAY_IN_SECOND, // pendingIntent // ) context.sendBroadcast(intent) FHStepCounterUtil.setIsRecording(context, true) /// for reboot val filter = IntentFilter() filter.addAction(Intent.ACTION_BOOT_COMPLETED) context.registerReceiver(mBroadcastReceiver, filter) val stepModel: HashMap<String, Double> = HashMap() stepModel["time"] = Date().time.toDouble() stepModel["value"] = initialTodayStep val recordedStep = ArrayList<HashMap<String, Double>>() recordedStep.add(stepModel) FHStepCounterUtil.setRecordedSteps(context, recordedStep) fhStepSensorListener = FHStepCounterSensorListener(context, object : SensorEventInterface { override fun onEvent(sensorResponse: SensorResponse?) { if (sensorResponse != null) { val iStepModel = HashMap<String, Double>() iStepModel["time"] = sensorResponse.lastUpdated.toDouble() iStepModel["value"] = initialTodayStep.roundToInt().toDouble() val newRecordedSteps = ArrayList<HashMap<String, Double>>() newRecordedSteps.add(iStepModel) sensorResponse.recordedSteps = newRecordedSteps // save to storage val oldTotalStep: Long = FHStepCounterUtil.getTotalStep(context) FHStepCounterUtil.setLastUpdatedStep(context, sensorResponse.lastUpdatedStep) FHStepCounterUtil.setLastUpdatedTime(context, sensorResponse.lastUpdated) FHStepCounterUtil.setTotalStep(context, sensorResponse.totalStep) if (oldTotalStep != sensorResponse.totalStep) { // only add new record if we have new changes FHStepCounterUtil.setRecordedSteps(context, sensorResponse.recordedSteps) } } fhStepSensorListener.stopSensor() // setup alarm for foreground/background/app killed work: // // setup broadcast receiver for step record: // event["start"] = true queueEvent.emit(event) } override fun onFailed() { event["start"] = false queueEvent.emit(event) } }) fhStepSensorListener.startSensor() } catch (e: Exception) { queueEvent.emitError(e) } } } override fun getTodayStep() : StepToday { activity?.activity?.let { try { val lastUpdated = FHStepCounterUtil.getLastUpdatedTime(it).toDouble() val sensorResponse = SensorResponse() sensorResponse.recordedSteps = FHStepCounterUtil.getRecordedSteps(it) ?: ArrayList() val step = sensorResponse.getTodayStep() return StepToday( lastUpdated, step ) } catch (e: java.lang.Exception) { return StepToday(null, 0) } } return StepToday(null, 0) } override fun getRecords() { activity?.activity?.let { context -> try { val recordedStep: ArrayList<HashMap<String, Double>> = FHStepCounterUtil.getRecordedSteps( context ) ?: ArrayList<HashMap<String, Double>>() val map: HashMap<String, Any> = HashMap() val event: HashMap<String, Any> = HashMap() map.put("lastUpdated", FHStepCounterUtil.getLastUpdatedTime(context)) map.put("recorded", recordedStep) event["getRecords"] = map queueEvent.emit(event) } catch (e: java.lang.Exception) { queueEvent.emitError(e) } } } fun isServiceRunning(serviceName: String): Boolean { activity?.activity?.let { context -> var serviceRunning = false val activityManager = context.getSystemService(Context.ACTIVITY_SERVICE) as ActivityManager val l = activityManager.getRunningServices(50) val i: Iterator<ActivityManager.RunningServiceInfo> = l.iterator() while (i.hasNext()) { val runningServiceInfo = i .next() if (runningServiceInfo.service.className == serviceName) { serviceRunning = true if (runningServiceInfo.foreground) { //service run in foreground } } } return serviceRunning } return false } override fun stop() { activity?.activity?.let { context -> val isRunning: Boolean = FHStepCounterUtil.getIsRecording(context) val event: HashMap<String, Any> = HashMap() if (!isRunning) { return } val intent = Intent(context, AlarmReceiver::class.java) intent.putExtra("enabled", false) intent.putExtra("repeat", false) intent.setAction(FHStepCounterSensorListener.SENSOR_STEP_BROADCAST_STOP) // setup broadcast receiver for step record: context.sendBroadcast(intent) // val pendingIntent = PendingIntent.getBroadcast( // context, // 0, // intent, // PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_IMMUTABLE // ) // // val alarmManager = context.getSystemService(Context.ALARM_SERVICE) as AlarmManager // alarmManager.setExactAndAllowWhileIdle( // AlarmManager.RTC_WAKEUP, // System.currentTimeMillis(), // pendingIntent // ) logout() event["stop"] = true fhStepSensorListener.stopSensor() queueEvent.emit(event) } } override fun pause() { activity?.activity?.let { context -> val isRunning: Boolean = FHStepCounterUtil.getIsRecording(context) val event: HashMap<String, Any> = HashMap() if (!isRunning) { return } val intent = Intent(context, AlarmReceiver::class.java) intent.putExtra("enabled", false) intent.putExtra("repeat", false) intent.setAction(FHStepCounterSensorListener.SENSOR_STEP_BROADCAST_STOP) // setup broadcast receiver for step record: context.sendBroadcast(intent) // val pendingIntent = PendingIntent.getBroadcast( // context, // 0, // intent, // PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_IMMUTABLE // ) // val alarmManager = context.getSystemService(Context.ALARM_SERVICE) as AlarmManager // alarmManager.setExactAndAllowWhileIdle( // AlarmManager.RTC_WAKEUP, // System.currentTimeMillis(), // pendingIntent // ) val sensorResponse = SensorResponse() sensorResponse.recordedSteps = FHStepCounterUtil.getRecordedSteps(context) ?: ArrayList() val todayStep = sensorResponse.getTodayStep() fhStepSensorListener.stopSensor() FHStepCounterUtil.setStepOnPause(context, todayStep) event["onPauseStep"] = todayStep queueEvent.emit(event) } } override fun clearData() { activity?.activity?.let { context -> FHStepCounterUtil.setLastUpdatedStep(context, 0L) FHStepCounterUtil.setLastUpdatedTime(context, 0L) FHStepCounterUtil.setTotalStep(context, 0L) FHStepCounterUtil.setRecordedSteps(context, ArrayList()) FHStepCounterUtil.setIsRecording(context, false) FHStepCounterUtil.setStepOnPause(context, 0L) val event = HashMap<String, Any>() try { event["clearData"] = true queueEvent.emit(event) } catch (e: java.lang.Exception) { event["clearData"] = false queueEvent.emit(event) } } } override fun logout() { activity?.activity?.let {context -> FHStepCounterUtil.setLastUpdatedStep(context, 0L); FHStepCounterUtil.setLastUpdatedTime(context, 0L); FHStepCounterUtil.setTotalStep(context, 0L); FHStepCounterUtil.setRecordedSteps(context, ArrayList()); FHStepCounterUtil.setIsRecording(context, false); } } override fun isRecording() : Boolean { activity?.activity?.let { context -> val output: Boolean = FHStepCounterUtil.getIsRecording(context) // val event = HashMap<String, Any>() return if (output) { val data: HashMap<*, *> = checkServiceRunning(AlarmService::class.java.name) if (data.containsKey("isRunning") && data.containsKey("isForeground")) { true } else { FHStepCounterUtil.setIsRecording(context, false) false } } else { false } } return false } override fun getPauseSteps(): Long { activity?.activity?.let { context -> val a = FHStepCounterUtil.getStepOnPause(context) return FHStepCounterUtil.getStepOnPause(context) } return 0L } private val mBroadcastReceiver: BroadcastReceiver = object : BroadcastReceiver() { override fun onReceive(context: Context, intent: Intent) { if (intent.action == Intent.ACTION_BOOT_COMPLETED) { val serviceIntent = Intent(context, SensorAlarmBootReceiver::class.java) context.startService(serviceIntent) } } } }
import classNames from 'classnames'; import { FC, memo, useState } from 'react'; import { Product } from '../../types/Product'; import { ProductItem } from '../ProductItem'; import arrowLeft from '../../assets/svg/arrowLeft.svg'; import arrowRigth from '../../assets/svg/arrowRigth.svg'; import './products-slider.scss'; type Props = { title: string; products: Product[]; }; const visibleCount = 4; export const ProductsSlider: FC<Props> = memo(({ title, products }) => { const [start, setStart] = useState(0); const end = start + visibleCount; return ( <div className="products-slider"> <div className="products-slider__top-row"> <h2 className="products-slider__title title">{title}</h2> <div className="products-slider__navigate "> <button aria-label="navigate" type="button" className={classNames('products-slider__button button-square', { 'button-square--disabled': start <= 0, })} onClick={() => setStart((prev) => prev - 1)} > <img src={arrowLeft} alt="arrowLeft" /> </button> <button aria-label="navigate" type="button" className={classNames('products-slider__button button-square', { 'button-square--disabled': end > products.length - 1, })} onClick={() => setStart((prev) => prev + 1)} > <img src={arrowRigth} alt="arrowRigth" /> </button> </div> </div> <div className="products-slider__products grid"> {products.slice(start, end).map((product: Product) => ( <ProductItem product={product} key={product.itemId} /> ))} </div> </div> ); });
# Theory of Operation {#theoryOperation} [TOC] This section gives an overview of the general operation of CMSIS-Drivers. It explains the \ref DriverFunctions that are common in all CMSIS-Drivers along with the \ref CallSequence. The topic \ref Data_Xfer_Functions describes how data read/write operations to the peripheral are implemented. Each CMSIS-Driver defines an \ref AccessStruct for calling the various driver functions and each peripheral (that is accessed via a CMSIS-Driver) has one \ref DriverInstances "Driver Instance". ## Common Driver Functions {#DriverFunctions} Each CMSIS-Driver contains these functions: - `GetVersion`: can be called at any time to obtain version information of the driver interface. - `GetCapabilities`: can be called at any time to obtain capabilities of the driver interface. - `Initialize`: must be called before powering the peripheral using `PowerControl`. This function performs the following: - allocate I/O resources. - register an optional `SignalEvent` callback function. - `SignalEvent`: is an optional callback function that is registered with the `Initialize` function. This callback function is initiated from interrupt service routines and indicates hardware events or the completion of a data block transfer operation. - `PowerControl`: Controls the power profile of the peripheral and needs to be called after `Initialize`. Typically, three power options are available (see \ref ARM_POWER_STATE): - `ARM_POWER_FULL`: Peripheral is turned on and fully operational. The driver initializes the peripheral registers, interrupts, and (optionally) DMA. - `ARM_POWER_LOW` : (optional) Peripheral is in low power mode and partially operational; usually, it can detect external events and wake-up. - `ARM_POWER_OFF`: Peripheral is turned off and not operational (pending operations are terminated). This is the state after device reset. - `Uninitialize`: Complementary function to Initialize. Releases the I/O pin resources used by the interface. - `Control`: Several drivers provide a control function to configure communication parameters or execute miscellaneous control functions. The section \ref CallSequence contains more information on the operation of each function. Additional functions are specific to each driver interface and are described in the individual sections of each driver. ## Cortex-M Processor Mode {#ProcessorMode} The CMSIS-Driver functions access peripherals and interrupts and are designed to execute in **Privileged** mode. When calling CMSIS-Driver functions from RTOS threads, it should be ensure that these threads execute in **Privileged** mode. ## Function Call Sequence {#CallSequence} For normal operation of the driver, the API functions `GetVersion`, `GetCapabilities`, `Initialize`, `PowerControl`, `Uninitialize` are called in the following order: \msc a [label="", textcolor="indigo", linecolor="indigo", arclinecolor="indigo"], b [label="", textcolor="blue", linecolor="blue", arclinecolor="blue"]; a rbox a [label="Middleware", linecolor="indigo"], b rbox b [label="Driver", linecolor="blue"]; --- [label="Verify API version"]; a=>b [label="GetVersion ()", textcolor="gray", linecolor="gray"]; --- [label="Obtain driver features"]; a=>b [label="GetCapabilities (...)", textcolor="gray", linecolor="gray"]; --- [label="Setup software resources"]; a=>b [label="Initialize (...)", textcolor="red", linecolor="red"]; --- [label="Setup the peripheral"]; a=>b [label="PowerControl (ARM_POWER_FULL)", textcolor="red", linecolor="red"]; --- [label="Operate with the peripheral"]; a=>b [label="Data Transfer Functions"]; a<=b [label="SignalEvent (...)"]; --- [label="Wait for external hardware events"]; a=>b [label="PowerControl (ARM_POWER_LOW)"]; a<=b [label="SignalEvent (...)"]; --- [label="Stop working with peripheral"]; a=>b [label="PowerControl (ARM_POWER_OFF)", textcolor="red", linecolor="red"]; a=>b [label="Uninitialize (...)", textcolor="red", linecolor="red"]; \endmsc The functions `GetVersion` and `GetCapabilities` can be called any time to obtain the required information from the driver. These functions return always the same information. ### Start Sequence {#CS_start} To start working with a peripheral the functions `Initialize` and `PowerControl` need to be called in this order: ```c drv->Initialize (...); // Allocate I/O pins drv->PowerControl (ARM_POWER_FULL); // Power up peripheral, setup IRQ/DMA ``` - `Initialize` typically allocates the I/O resources (pins) for the peripheral. The function can be called multiple times; if the I/O resources are already initialized it performs no operation and just returns with \ref ARM_DRIVER_OK. - `PowerControl` (`ARM_POWER_FULL`) sets the peripheral registers including interrupt (NVIC) and optionally DMA. The function can be called multiple times; if the registers are already set it performs no operation and just returns with \ref ARM_DRIVER_OK. ### Stop Sequence {#CS_stop} To stop working with a peripheral the functions `PowerControl` and `Uninitialize` need to be called in this order: ```c drv->PowerControl (ARM_POWER_OFF); // Terminate any pending transfers, reset IRQ/DMA, power off peripheral drv->Uninitialize (...); // Release I/O pins ``` The functions `PowerControl` and `Uninitialize` always execute and can be used to put the peripheral into a **Safe State**, for example after any data transmission errors. To restart the peripheral in a error condition, you should first execute the \ref CS_stop and then the \ref CS_start. - `PowerControl` (`ARM_POWER_OFF`) terminates any pending data transfers with the peripheral, disables the peripheral and leaves it in a defined mode (typically the reset state). - when DMA is used it is disabled (including the interrupts) - peripheral interrupts are disabled on NVIC level - the peripheral is reset using a dedicated reset mechanism (if available) or by clearing the peripheral registers - pending peripheral interrupts are cleared on NVIC level - driver variables are cleared - `Uninitialize` always releases I/O pin resources. ## Shared I/O Pins {#Share_IO} All CMSIS-Driver provide a \ref CS_start and \ref CS_stop. Therefore two different drivers can share the same I/O pins, for example UART1 and SPI1 can have overlapping I/O pins. In this case the communication channels can be used as shown below: ```c SPI1drv->Initialize (...); // Start SPI1 SPI1drv->PowerControl (ARM_POWER_FULL); ... // Do operations with SPI1 SPI1drv->PowerControl (ARM_POWER_OFF); // Stop SPI1 SPI1drv->Uninitialize (); ... USART1drv->Initialize (...); // Start USART1 USART1drv->PowerControl (ARM_POWER_FULL); ... // Do operations with USART1 USART1drv->PowerControl (ARM_POWER_OFF); // Stop USART1 USART1drv->Uninitialize (); ``` ## Data Transfer Functions {#Data_Xfer_Functions} A CMSIS-Driver implements non-blocking functions to transfer data to a peripheral. This means that the driver configures the read or write access to the peripheral and instantly returns to the calling application. The function names for data transfer end with: - `Send` to write data to a peripheral. - `Receive` to read data from a peripheral. - `Transfer` to indicate combined read/write operations to a peripheral. During a data transfer, the application can query the number of transferred data items using functions named <b>Get<i>xxx</i>Count</b>. On completion of a data transfer, the driver calls a callback function with a specific event code. During the data exchange with the peripheral, the application can decide to: - Wait (using an RTOS scheduler) for the callback completion event. The RTOS is controlled by the application code which makes the driver itself RTOS independent. - Use polling functions that return the number of transferred data items to show progress information or partly read or fill data transfer buffers. - Prepare another data transfer buffer for the next data transfer. The following diagram shows the basic communication flow when using the `_Send` function in an application. ![Non-blocking Send Function](./images/Non_blocking_transmit_small.png) ## Access Struct {#AccessStruct} A CMSIS-Driver publishes an \ref AccessStruct with the data type name `ARM_DRIVER_xxxx` that gives to access the driver functions. **Code Example:** Function Access of the SPI driver ```c typedef struct _ARM_DRIVER_SPI { ARM_DRIVER_VERSION (*GetVersion) (void); ARM_SPI_CAPABILITIES (*GetCapabilities) (void); int32_t (*Initialize) (ARM_SPI_SignalEvent_t cb_event); int32_t (*Uninitialize) (void); int32_t (*PowerControl) (ARM_POWER_STATE state); int32_t (*Send) (const void *data, uint32_t num); int32_t (*Receive) ( void *data, uint32_t num); int32_t (*Transfer) (const void *data_out, void *data_in, uint32_t num); uint32_t (*GetDataCount) (void); int32_t (*Control) (uint32_t control, uint32_t arg); ARM_SPI_STATUS (*GetStatus) (void); } const ARM_DRIVER_SPI; ``` ### Driver Instances {#DriverInstances} A device may offer several peripherals of the same type. For such devices, the CMSIS-Driver publishes multiple instances of the \ref AccessStruct. The name of each driver instance reflects the names of the peripheral available in the device. **Code Example:** \ref AccessStruct for three SPIs in a microcontroller device. ```c ARM_DRIVER_SPI Driver_SPI1; // access functions for SPI1 interface ARM_DRIVER_SPI Driver_SPI2; // access functions for SPI2 interface ARM_DRIVER_SPI Driver_SPI3; // access functions for SPI3 interface ``` The access functions can be passed to middleware to specify the driver instance that the middleware should use for communication. **Naming Convention** The access structs need to follow this naming convention: the keyword `Driver` followed by an underscore `_`, the interface name `IFNAME` (usually in upper case letters), and the instance number `n`. Here's the full list of access struct names for all drivers (n to be replaced with the actual instance number): ```c Driver_CANn Driver_ETH_MACn Driver_ETH_PHYn Driver_Flashn Driver_GPIOn Driver_I2Cn Driver_MCIn Driver_NANDn Driver_SAIn Driver_SPIn Driver_Storagen Driver_USARTn Driver_USBDn Driver_USBHn Driver_WiFin ``` **Example:** ```c void init_middleware (ARM_DRIVER_SPI *Drv_spi) ... \\ inside the middleware the SPI driver functions are called with: \\ Drv_spi->function (...); ``` ```c \\ setup middleware init_middleware (&Driver_SPI1); // connect middleware to SPI1 interface : init_middleware (&Driver_SPI2); // connect middleware to SPI2 interface ``` ## CMSIS-Driver Files {#cmsis_driver_files} The API of each CMSIS-Driver peripheral is published in a corresponding header file in the directory `.\CMSIS\Driver\Include\` It is recommended to include such header file in the implementation file of the CMSIS-Driver. Template files are available to simplify the development of a CMSIS-Driver. These are code skeletons that provide the structure of a CMSIS-Driver. They are available in the directory`.\CMSIS\Driver\DriverTemplates\`. You can also refer to working \ref listOfImplementations "CMSIS-Driver Implementations" to see how CMSIS-Drivers get implemented on real devices. The table below summarizes the API header and template files for CMSIS-Driver interfaces, with links to GitHub and API references. | Header File | Template File | API Reference :----------------------|:-------------------------|:----------------------- [Driver_Common.h](https://github.com/ARM-software/CMSIS_6/blob/main/CMSIS/Driver/Include/Driver_Common.h)| Not applicable | \ref common_drv_gr [Driver_CAN.h](https://github.com/ARM-software/CMSIS_6/blob/main/CMSIS/Driver/Include/Driver_CAN.h) | [Driver_CAN.c](https://github.com/ARM-software/CMSIS_6/blob/main/CMSIS/Driver/DriverTemplates/Driver_CAN.c) |\ref can_interface_gr [Driver_ETH.h](https://github.com/ARM-software/CMSIS_6/blob/main/CMSIS/Driver/Include/Driver_ETH.h) | - |\ref eth_interface_gr [Driver_ETH_MAC.h](https://github.com/ARM-software/CMSIS_6/blob/main/CMSIS/Driver/Include/Driver_ETH_MAC.h) | [Driver_ETH_MAC.c](https://github.com/ARM-software/CMSIS_6/blob/main/CMSIS/Driver/DriverTemplates/Driver_ETH_MAC.c) | \ref eth_mac_interface_gr [Driver_ETH_PHY.h](https://github.com/ARM-software/CMSIS_6/blob/main/CMSIS/Driver/Include/Driver_ETH_MAC.h) | [Driver_ETH_PHY.c](https://github.com/ARM-software/CMSIS_6/blob/main/CMSIS/Driver/DriverTemplates/Driver_ETH_PHY.c) | \ref eth_phy_interface_gr [Driver_Flash.h](https://github.com/ARM-software/CMSIS_6/blob/main/CMSIS/Driver/Include/Driver_Flash.h) | [Driver_Flash.c](https://github.com/ARM-software/CMSIS_6/blob/main/CMSIS/Driver/DriverTemplates/Driver_Flash.c) | \ref flash_interface_gr [Driver_GPIO.h](https://github.com/ARM-software/CMSIS_6/blob/main/CMSIS/Driver/Include/Driver_GPIO.h) | [Driver_GPIO.c](https://github.com/ARM-software/CMSIS_6/blob/main/CMSIS/Driver/DriverTemplates/Driver_GPIO.c) | \ref gpio_interface_gr [Driver_I2C.h](https://github.com/ARM-software/CMSIS_6/blob/main/CMSIS/Driver/Include/Driver_I2C.h) | [Driver_I2C.c](https://github.com/ARM-software/CMSIS_6/blob/main/CMSIS/Driver/DriverTemplates/Driver_I2C.c) | \ref i2c_interface_gr [Driver_MCI.h](https://github.com/ARM-software/CMSIS_6/blob/main/CMSIS/Driver/Include/Driver_MCI.h) | [Driver_MCI.c](https://github.com/ARM-software/CMSIS_6/blob/main/CMSIS/Driver/DriverTemplates/Driver_MCI.c) | \ref mci_interface_gr [Driver_NAND.h](https://github.com/ARM-software/CMSIS_6/blob/main/CMSIS/Driver/Include/Driver_NAND.h) | [Driver_NAND.c](https://github.com/ARM-software/CMSIS_6/blob/main/CMSIS/Driver/DriverTemplates/Driver_NAND.c) | \ref nand_interface_gr [Driver_SAI.h](https://github.com/ARM-software/CMSIS_6/blob/main/CMSIS/Driver/Include/Driver_SAI.h) | [Driver_SAI.c](https://github.com/ARM-software/CMSIS_6/blob/main/CMSIS/Driver/DriverTemplates/Driver_SAI.c) | \ref sai_interface_gr [Driver_SPI.h](https://github.com/ARM-software/CMSIS_6/blob/main/CMSIS/Driver/Include/Driver_SPI.h) | [Driver_SPI.c](https://github.com/ARM-software/CMSIS_6/blob/main/CMSIS/Driver/DriverTemplates/Driver_SPI.c) | \ref spi_interface_gr [Driver_Storage.h](https://github.com/ARM-software/CMSIS_6/blob/main/CMSIS/Driver/Include/Driver_Storage.h) | [Driver_Storage.c](https://github.com/ARM-software/CMSIS_6/blob/main/CMSIS/Driver/DriverTemplates/Driver_Storage.c) | \ref storage_interface_gr [Driver_USART.h](https://github.com/ARM-software/CMSIS_6/blob/main/CMSIS/Driver/Include/Driver_USART.h) | [Driver_USART.c](https://github.com/ARM-software/CMSIS_6/blob/main/CMSIS/Driver/DriverTemplates/Driver_USART.c) | \ref usart_interface_gr [Driver_USB.h](https://github.com/ARM-software/CMSIS_6/blob/main/CMSIS/Driver/Include/Driver_USB.h) | - | \ref usb_interface_gr [Driver_USBD.h](https://github.com/ARM-software/CMSIS_6/blob/main/CMSIS/Driver/Include/Driver_USBD.h) | [Driver_USBD.c](https://github.com/ARM-software/CMSIS_6/blob/main/CMSIS/Driver/DriverTemplates/Driver_USBD.c) | \ref usbd_interface_gr [Driver_USBH.h](https://github.com/ARM-software/CMSIS_6/blob/main/CMSIS/Driver/Include/Driver_USBH.h) | [Driver_USBH.c](https://github.com/ARM-software/CMSIS_6/blob/main/CMSIS/Driver/DriverTemplates/Driver_USBH.c) | \ref usbh_interface_gr [Driver_WiFi.h](https://github.com/ARM-software/CMSIS_6/blob/main/CMSIS/Driver/Include/Driver_WiFi.h) | [Driver_WiFi.c](https://github.com/ARM-software/CMSIS_6/blob/main/CMSIS/Driver/DriverTemplates/Driver_WiFi.c) | \ref wifi_interface_gr ## Driver Configuration {#DriverConfiguration} For a device family, the drivers may be configurable, but the configuration of the drivers itself is not part of the CMSIS-Driver specification. ## Code Example {#CodeExample} The following example code shows the usage of the SPI interface. \include SPI_Demo.c
/* * Copyright 2019 igur. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package ebay.scraper.client; import okhttp3.OkHttpClient; import okhttp3.logging.HttpLoggingInterceptor; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.context.ApplicationContext; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.context.support.PropertySourcesPlaceholderConfigurer; import pl.droidsonroids.retrofit2.JspoonConverterFactory; import retrofit2.Call; import retrofit2.Response; import retrofit2.Retrofit; import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory; import ebay.scraper.model.ResultPage; import java.io.IOException; import java.util.Map; @Configuration public class RetrofitClient { @Autowired private ApplicationContext applicationContext; @Autowired private OkHttpClient httpClient; @Autowired private Retrofit retrofit; @Autowired private RequestService requestService; @Bean public static PropertySourcesPlaceholderConfigurer propertySourcesPlaceholderConfigurer() { return new PropertySourcesPlaceholderConfigurer(); } @Bean OkHttpClient providesHTTPClient() { HttpLoggingInterceptor interceptor = new HttpLoggingInterceptor(); interceptor.setLevel(HttpLoggingInterceptor.Level.BODY); return new OkHttpClient.Builder().addInterceptor(interceptor).build(); } @Bean Retrofit providesRetrofit(@Value("${ebay.scrape.url:http://ebay-kleinanzeigen.de/}") String ebayScrapeUrl) { return new Retrofit.Builder() .baseUrl(ebayScrapeUrl) .client(httpClient) .addConverterFactory(JspoonConverterFactory.create()) .addCallAdapterFactory(RxJava2CallAdapterFactory.create()) .build(); } @Bean RequestService providesRequestService() { return retrofit.create(RequestService.class); } public ResultPage query(Map<String, String> parameters) throws IOException { Call<ResultPage> resultPageCall = requestService.getResultPage(parameters); Response<ResultPage> res = resultPageCall.execute(); return res.body(); } }
// Copyright Epic Games, Inc. All Rights Reserved. #pragma once #include "CoreMinimal.h" #include "GameFramework/Character.h" #include "InputActionValue.h" #include "assignemt_runnerCharacter.generated.h" UCLASS(config=Game) class Aassignemt_runnerCharacter : public ACharacter { GENERATED_BODY() /** Camera boom positioning the camera behind the character */ UPROPERTY(VisibleAnywhere, BlueprintReadOnly, Category = Camera, meta = (AllowPrivateAccess = "true")) class USpringArmComponent* CameraBoom; /** Follow camera */ UPROPERTY(VisibleAnywhere, BlueprintReadOnly, Category = Camera, meta = (AllowPrivateAccess = "true")) class UCameraComponent* FollowCamera; /** MappingContext */ UPROPERTY(EditAnywhere, BlueprintReadOnly, Category = Input, meta = (AllowPrivateAccess = "true")) class UInputMappingContext* DefaultMappingContext; /** Move Input Action */ UPROPERTY(EditAnywhere, BlueprintReadOnly, Category = Input, meta = (AllowPrivateAccess = "true")) class UInputAction* MoveAction; public: Aassignemt_runnerCharacter(); void Move(const FInputActionValue& Value); protected: // APawn interface virtual void SetupPlayerInputComponent(class UInputComponent* PlayerInputComponent) override; // To add mapping context virtual void BeginPlay(); virtual void Tick(float DeltaTime) override; public: /** Returns CameraBoom subobject **/ FORCEINLINE class USpringArmComponent* GetCameraBoom() const { return CameraBoom; } /** Returns FollowCamera subobject **/ FORCEINLINE class UCameraComponent* GetFollowCamera() const { return FollowCamera; } static inline FVector startLocation; private: FVector currentLocation; };
import http, { ServerResponse, OutgoingHttpHeaders, IncomingMessage, } from "http"; interface Context { res: ServerResponse; req: IncomingMessage; onerror: (err: Error) => void; request: { url: string; pathname: string; query: string; }; response: { statusCode: number; statusMessage: string; body: string | Buffer; headers: OutgoingHttpHeaders; }; } type MiddleWare = (ctx: Context, next: NextHandler) => Promise<void>; type NextHandler = () => Promise<void>; type Controller = (ctx: Context) => Promise<void>; const METHODS: ("get" | "post" | "put" | "delete")[] = [ "get", "post", "put", "delete", ]; class Router { pathToHandler: Record<string, Record<string, Function>> = {}; get: (path: string, handler: Controller) => void = () => void 0; post: (path: string, handler: Controller) => void = () => void 0; put: (path: string, handler: Controller) => void = () => void 0; delete: (path: string, handler: Controller) => void = () => void 0; constructor() { // this.pathToHandler = {}; METHODS.forEach((method) => { this[method] = (path: string, handler: Controller) => { this.pathToHandler[method] = {}; this.pathToHandler[method][path] = handler; }; }); } routes = this._routes.bind(this); async _routes(ctx: Context, next: NextHandler) { const path = ctx.req.url || "/"; switch (ctx.req.method?.toLowerCase()) { case "get": await this.pathToHandler["get"][path](ctx); break; case "post": await this.pathToHandler["post"][path](ctx); break; case "put": await this.pathToHandler["put"][path](ctx); break; case "delete": await this.pathToHandler["delete"][path](ctx); break; default: throw "METHOD Error"; } await next(); } } class MyKoa { middlewares: MiddleWare[]; constructor() { this.middlewares = []; } /** * * @param {(ctx, next: ) => Promise<undefined>} fn */ use(fn: MiddleWare) { this.middlewares.push(fn); } createContext(request: IncomingMessage, response: ServerResponse): Context { const context = { req: request, res: response, onerror: (err: Error) => { console.error(err); }, request: { url: "", pathname: "", query: "", }, response: { statusCode: 404, statusMessage: "not found", body: "", headers: { "content-type": "application/json", Connection: "Keep-Alive", "Keep-Alive": "timeout=5, max=1000", }, }, }; return context; } compose() { return async (ctx: Context, final: MiddleWare) => { const run = async () => { const current = this.middlewares.shift(); if (current) { await Promise.resolve(current(ctx, run)); } else { final(ctx, async () => {}); } }; run(); }; } createlistener() { const fn = this.compose(); return (req: IncomingMessage, res: ServerResponse) => { const ctx = this.createContext(req, res); return this.handleRequest(ctx, fn); }; } async respond(ctx: Context) { const res = ctx.res; res.writeHead( ctx.response.statusCode, ctx.response.statusMessage, ctx.response.headers || {} ); res.write( ctx.response.body, "utf-8" ); res.end(); } async handleRequest(ctx: Context, fnMiddleware: MiddleWare) { const handleServerResponse = () => this.respond(ctx); const onerror = (err: Error) => ctx.onerror(err); try { await fnMiddleware(ctx, async () => { console.log("last one"); }); await handleServerResponse(); } catch (e) { onerror(e as Error); } } listen(PORT: number) { http.createServer(this.createlistener()).listen(PORT, () => { console.log("start success"); }); } } const app = new MyKoa(); const router = new Router(); router.get("/hello", async (ctx) => { ctx.response.statusCode = 200; ctx.response.statusMessage = "ok"; ctx.response.body = "hello world"; }); app.use(router.routes); app.listen(3000);
package su22_09_dohuynhanhvu_ce171446; import java.util.*; /** * * @author Do Huynh Anh Vu - CE171446 */ public class Coefficient { //======= THUOC TINH ========= protected ArrayList<Double> result; //======= KHOI TAO ========== public Coefficient() { } public Coefficient(ArrayList result) { this.result = result; } //========= GET & SET ======== /** * get Result array * * @return array */ public ArrayList getResult() { return result; } /** * set new result array * * @param result */ public void setResult(ArrayList result) { this.result = result; } /** * Method to check if number is odd or not, display */ public void CheckOdd() { ArrayList<Double> arr = new ArrayList<>(); // Initialize new array to not affect the data of main array for (int i = 0; i < result.size(); i++) { if (result.get(i) % 2 != 0) { // If number is valid add to the new array arr.add(result.get(i)); } } display(arr); //Show to the monitor } /** * Method to check if number is even or not, display */ public void CheckEven() { ArrayList<Double> arr = new ArrayList<>(); // Initialize new array to not affect the data of main array for (int i = 0; i < result.size(); i++) { if (result.get(i) % 2 == 0) { // If number is valid add to the new array arr.add(result.get(i)); } } display(arr); //Show to the monitor } /** * Method to check if number is perfect square or not, display */ public void CheckSquare() { ArrayList<Double> arr = new ArrayList<>(); // Initialize new array to not affect the data of main array for (int i = 0; i < result.size(); i++) { int j = 0; while (j <= result.get(i)) { if (Math.pow(j, 2) == result.get(i)) { arr.add(result.get(i)); // If number is valid add to the new array break; } j++; } } display(arr); //Show to the monitor } /** * Method to show input array to monitor * @param input */ public void display(ArrayList<Double> input) { int n = input.size(); for (int i = 0; i < n - 1; i++) { System.out.print(input.get(i) + ", "); // Have ", " between elements } System.out.println(input.get(n - 1)); // Last element does not have "," } }
/********************************************************************************************************************* * MM32F327X-G9P Opensourec Library 即(MM32F327X-G9P 开源库)是一个基于官方 SDK 接口的第三方开源库 * Copyright (c) 2022 SEEKFREE 逐飞科技 * * 本文件是 MM32F327X-G9P 开源库的一部分 * * MM32F327X-G9P 开源库 是免费软件 * 您可以根据自由软件基金会发布的 GPL(GNU General Public License,即 GNU通用公共许可证)的条款 * 即 GPL 的第3版(即 GPL3.0)或(您选择的)任何后来的版本,重新发布和/或修改它 * * 本开源库的发布是希望它能发挥作用,但并未对其作任何的保证 * 甚至没有隐含的适销性或适合特定用途的保证 * 更多细节请参见 GPL * * 您应该在收到本开源库的同时收到一份 GPL 的副本 * 如果没有,请参阅<https://www.gnu.org/licenses/> * * 额外注明: * 本开源库使用 GPL3.0 开源许可证协议 以上许可申明为译文版本 * 许可申明英文版在 libraries/doc 文件夹下的 GPL3_permission_statement.txt 文件中 * 许可证副本在 libraries 文件夹下 即该文件夹下的 LICENSE 文件 * 欢迎各位使用并传播本程序 但修改内容时必须保留逐飞科技的版权声明(即本声明) * * 文件名称 zf_driver_gpio * 公司名称 成都逐飞科技有限公司 * 版本信息 查看 libraries/doc 文件夹内 version 文件 版本说明 * 开发环境 IAR 8.32.4 or MDK 5.37 * 适用平台 MM32F327X_G9P * 店铺链接 https://seekfree.taobao.com/ * * 修改记录 * 日期 作者 备注 * 2022-08-10 Teternal first version ********************************************************************************************************************/ #include "zf_driver_gpio.h" GPIO_Type *gpio_group[8] = {GPIOA, GPIOB, GPIOC, GPIOD, GPIOE, GPIOF, GPIOG, GPIOH}; //------------------------------------------------------------------------------------------------------------------- // 函数简介 gpio 输出设置 // 参数说明 pin 选择的引脚 (可选择范围由 zf_driver_gpio.h 内 gpio_pin_enum 枚举值确定) // 参数说明 dat 0:低电平 1:高电平 // 返回参数 void // 使用示例 gpio_set_level(D5, 1); // D5 输出高电平 // 备注信息 //------------------------------------------------------------------------------------------------------------------- void gpio_set_level (gpio_pin_enum pin, const uint8 dat) { if(dat) { gpio_high(pin); // 输出高电平 } else { gpio_low(pin); // 输出低电平 } } //------------------------------------------------------------------------------------------------------------------- // 函数简介 gpio 电平获取 // 参数说明 pin 选择的引脚 (可选择范围由 zf_driver_gpio.h 内 gpio_pin_enum 枚举值确定) // 返回参数 uint8 引脚当前电平 // 使用示例 uint8 status = gpio_get_level(D5); // 获取 D5 引脚电平 // 备注信息 //------------------------------------------------------------------------------------------------------------------- uint8 gpio_get_level (gpio_pin_enum pin) { return ((gpio_group[(pin & 0xE0) >> 5]->IDR & (((uint16)0x0001) << (pin & 0x1F))) ? 1 : 0); } //------------------------------------------------------------------------------------------------------------------- // 函数简介 gpio 翻转电平 // 参数说明 pin 选择的引脚 (可选择范围由 zf_driver_gpio.h 内 gpio_pin_enum 枚举值确定) // 返回参数 void // 使用示例 gpio_toggle_level(D5); // 翻转 D5 电平 // 备注信息 //------------------------------------------------------------------------------------------------------------------- void gpio_toggle_level (gpio_pin_enum pin) { if(gpio_group[(pin & 0xE0) >> 5]->IDR & (((uint16)0x0001) << (pin & 0x1F))) { gpio_group[(pin & 0xE0) >> 5]->BRR |= (((uint16)0x0001) << (pin & 0x1F)); // 输出低电平 } else { gpio_group[(pin & 0xE0) >> 5]->BSRR |= (((uint16)0x0001) << (pin & 0x1F)); // 输出高电平 } } //------------------------------------------------------------------------------------------------------------------- // 函数简介 gpio 方向设置 // 参数说明 pin 选择的引脚 (可选择范围由 zf_driver_gpio.h 内 gpio_pin_enum 枚举值确定) // 参数说明 dir 引脚的方向 输出:GPO 输入:GPI // 参数说明 mode 引脚的模式 (可选择范围由 zf_driver_gpio.h 内 gpio_mode_enum 枚举值确定) // 返回参数 void // 使用示例 gpio_set_dir(D5, GPI, GPI_PULL_UP); // 设置 D5 为上拉输入 // 备注信息 //------------------------------------------------------------------------------------------------------------------- void gpio_set_dir (gpio_pin_enum pin, gpio_dir_enum dir, gpio_mode_enum mode) { uint32 temp = 0; uint8 io_group = ((pin & 0xE0) >> 5); // 提取IO分组 uint8 io_pin = (pin & 0x1F); // 提取IO引脚下标 if(0x08 > io_pin) // 低8位引脚 { temp = gpio_group[io_group]->CRL; temp &= ~(0x0000000f << (io_pin * 4)); // 清空模式 temp |= (((uint32)dir | (uint32)(mode & 0x0C)) << (io_pin * 4)); // 写入对应模式 gpio_group[io_group]->CRL = temp; } else // 高8位引脚 { temp = gpio_group[io_group]->CRH; temp &= ~(0x0000000f << ((io_pin - 8) * 4)); // 清空模式 temp |= (((uint32)dir | (uint32)(mode & 0x0C)) << ((io_pin - 8) * 4)); // 写入对应模式 gpio_group[io_group]->CRH = temp; } } //------------------------------------------------------------------------------------------------------------------- // 函数简介 gpio 初始化 // 参数说明 pin 选择的引脚 (可选择范围由 zf_driver_gpio.h 内 gpio_pin_enum 枚举值确定) // 参数说明 mode 引脚的方向 [GPI/GPIO] // 参数说明 dat 引脚初始化时设置的电平状态,输出时有效 0:低电平 1:高电平 仅在设置为输出模式时有效 // 参数说明 mode 引脚的模式 (可选择范围由 zf_driver_gpio.h 内 gpio_mode_enum 枚举值确定) // 返回参数 void // 使用示例 gpio_init(D1, GPI, GPIO_HIGH, GPI_PULL_UP); // 备注信息 //------------------------------------------------------------------------------------------------------------------- void gpio_init (gpio_pin_enum pin, gpio_dir_enum dir, const uint8 dat, gpio_mode_enum mode) { uint32 temp = 0; uint8 io_group = ((pin & 0xE0) >> 5); // 提取IO分组 uint8 io_pin = (pin & 0x1F); // 提取IO引脚下标 RCC->AHB1ENR |= (0x00000001 << io_group); // 使能 GPIOx 时钟 if(dir == GPI) { if(mode == GPI_PULL_UP) { gpio_high(pin); // 初始化电平设置高 } else { gpio_low(pin); // 初始化电平设置低 } } else { gpio_set_level(pin, dat); } if(0x08 > io_pin) // 低8位引脚 { temp = gpio_group[io_group]->AFRL; temp &= ~(0x0000000F << (io_pin * 4)); // 清空 AF 复用 temp |= ((uint32)15 << (io_pin * 4)); // AF 复用设置 15 保留 gpio_group[io_group]->AFRL = temp; temp = gpio_group[io_group]->CRL; temp &= ~(0x0000000F << (io_pin * 4)); // 清空模式 temp |= (((uint32)dir | (uint32)(mode & 0x0C)) << (io_pin * 4)); // 写入对应模式 gpio_group[io_group]->CRL = temp; } else // 高8位引脚 { temp = gpio_group[io_group]->AFRH; temp &= ~(0x0000000F << ((io_pin - 8) * 4)); // 清空 AF 复用 temp |= ((uint32)15 << ((io_pin - 8) * 4)); // AF 复用设置 15 保留 gpio_group[io_group]->AFRH = temp; temp = gpio_group[io_group]->CRH; temp &= ~(0x0000000F << ((io_pin - 8) * 4)); // 清空模式 temp |= (((uint32)dir | (uint32)(mode & 0x0C)) << ((io_pin - 8) * 4)); // 写入对应模式 gpio_group[io_group]->CRH = temp; } } //------------------------------------------------------------------------------------------------------------------- // 函数简介 gpio 复用功能初始化 一般是内部调用 // 参数说明 pin 选择的引脚 (可选择范围由 zf_driver_gpio.h 内 gpio_pin_enum 枚举值确定) // 参数说明 mode 引脚的方向 [GPI/GPIO] // 参数说明 af 引脚的功能选择 (可选择范围由 zf_driver_gpio.h 内 gpio_af_enum 枚举值确定) // 参数说明 mode 引脚的模式 (可选择范围由 zf_driver_gpio.h 内 gpio_mode_enum 枚举值确定) // 返回参数 void // 使用示例 afio_init(D5, GPO, GPIO_AF0, GPO_AF_PUSH_PULL); // 备注信息 //------------------------------------------------------------------------------------------------------------------- void afio_init (gpio_pin_enum pin, gpio_dir_enum dir, gpio_af_enum af, gpio_mode_enum mode) { uint32 temp = 0; uint8 io_group = ((pin & 0xE0) >> 5); // 提取IO分组 uint8 io_pin = (pin & 0x1F); // 提取IO引脚下标 RCC->AHB1ENR |= (0x00000001 << io_group); // 使能 GPIOx 时钟 if(0x08 > io_pin) // 低8位引脚 { temp = gpio_group[io_group]->AFRL; temp &= ~(0x0000000F << (io_pin * 4)); // 清空 AF 复用 temp |= ((uint32)af << (io_pin * 4)); // AF 复用设置对应功能 gpio_group[io_group]->AFRL = temp; temp = gpio_group[io_group]->CRL; temp &= ~(0x0000000F << (io_pin * 4)); // 清空模式 temp |= (((uint32)dir | (uint32)(mode & 0x0C)) << (io_pin * 4)); // 写入对应模式 gpio_group[io_group]->CRL = temp; } else // 高8位引脚 { temp = gpio_group[io_group]->AFRH; temp &= ~(0x0000000F << ((io_pin - 8) * 4)); // 清空 AF 复用 temp |= ((uint32)af << ((io_pin - 8) * 4)); // AF 复用设置对应功能 gpio_group[io_group]->AFRH = temp; temp = gpio_group[io_group]->CRH; temp &= ~(0x0000000F << ((io_pin - 8) * 4)); // 清空模式 temp |= (((uint32)dir | (uint32)(mode & 0x0C)) << ((io_pin - 8) * 4)); // 写入对应模式 gpio_group[io_group]->CRH = temp; } }
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> </head> <body> <!-- 1. document.createElement() 2. document.body.appendChild() 3. console.dỉr() 4. innerText, id, className, style --> <!-- <h1 id="heading">Hello guys</h1> <script> const h1 = document.getElementById('heading') console.log(h1) </script> --> <div id="root"></div> <script> const root = document.getElementById('root') const h1 = document.createElement('h1') h1.innerText = 'Hello guys' h1.setAttribute('id', 'heading') h1.className = 'test class-2' // h1.style.color = 'red' // h1.style = 'color: green; font-size: 40px;' Object.assign(h1.style, { color: 'blue', backgroundColor: '#333' }) console.log(h1) // document.body.appendChild(h1) root.appendChild(h1) </script> </body> </html>
## Contents 1. 개요 2. 역사 3. 규칙 4. YOSAKOI 5. 기타 6. 관련 항목 [[edit](http://rigvedawiki.net/r1/wiki.php/%EC%9A%94%EC%82%AC%EC%BD%94%EC%9D%B 4?action=edit&section=1)] ## 1. 개요 ¶ 2014 요사코이 축제 우승팀 十人十彩(십인십채)의 요사코이 2014 YOSAKOI 소란 축제 우승팀 夢想漣えさし(유메소란에사시)의 YOSAKOI 일본의 단체 무용의 한 종류. 일본 시코쿠의 코치 현에서 열리는 축제의 이름에서 비롯되었다. 요사코이 축제에서 추는 춤을 통틀어서 요사코이라고 부른다. <del>냐루코</del>[나루코](%EB%82%98%EB%A3%A8%EC%BD%94.md)라는 도구를 손에 들고 자유롭게 안무를 짜서 직접 만든 음악에 맞추어 길거리를 활보하며 춤을 추면서 조금씩 앞으로 나아간다. 기본적으로 군무(群舞)이기 때문에 혼자서는 하지 않는다. 팀의 규모는 5~6명의 소규모에서 100명이 넘는 대규모까지 다양하고, 매년 200팀 이상이 출전한다. 본무대 기간은 2~3일에 불과한데 이 시간동안 한군데에서 200팀의 무대를 소화하는 것이 불가능하므로 스테이지는 15~20여 군데로 나누어져 있다. 요사코이 축제는 각 팀의 독자적인 춤을 선보인 후에 이것을 평가하여 승부를 내는 것이 보통이다. 우승팀에게는 공식적인 상품이나 상금은 없지만 여기에서 돋보이면 별도로 스폰서가 붙어서 의상 협찬을 해준다든지 공연 비용을 대준다든지 하는 경우가 있다.`[1]` 특별히 실력이 출중한 개인에게는 상 대신 특수제작한 메달을 수여한다. 십수 미터 떨어져서 본 군무가 매우 장관이라 볼거리라는 측면에서 굉장히 화려하다. 공연 모습을 담은 DVD, BD도 매년 출시되고 있다. 군무 행렬의 맨 앞에는 지카타샤(地方車)`[2]`라는 차가 선두를 이끈다. 공연에 사용되는 음악을 지카타샤에서 튼다. 보컬이 여기 타서 생으로 노래를 부르거나 추임새를 넣기도 하고, 북이나 다른 악기를 싣고 연주하기도 한다. 지카타샤는 대개 렌트카지만, 대규모 팀의 경우 팀 소유거나 스폰서에게 협찬받기도 한다. 맨 앞에서 팀의 개성을 돋보이는 역할을 하기 때문에 각 팀들은 안무의 연출 뿐만 아니라 지카타샤를 꾸미는 데도 많은 열정을 쏟는다. 공연 내용과 관계없이 지카타샤의 모습만을 가지고 평가하는 지카타샤 상도 있다. [[edit](http://rigvedawiki.net/r1/wiki.php/%EC%9A%94%EC%82%AC%EC%BD%94%EC%9D%B 4?action=edit&section=2)] ## 2. 역사 ¶ 요사코이의 의상이 대개 일본 전통 의상 풍이기 때문에 잘 모르는 외국인들에게는 예로부터 전해져 온 전통적인 춤이라는 인상이 있지만 실제 축제의 역사는 60년 정도로 그리 길지 않다. 코치의 옆 현인 토쿠시마 현의 축제 ‘아와오도리’에 대항하기 위해서 실험적으로 개발하여 산업 박람회의 부대행사격 퍼레이드로 선보인 것이 좋은 반응을 얻어 축제로 만들게 된 것이다. 하지만 대개 지역 민요나 전통 음악을 어레인지해서 내놓는지라`[3]` 음악이 현대적이더라도 프레이즈 자체는 전통 음악에 가깝다. 전통과 현대의 음악과 춤을 잘 융합했다고도 할 수 있다. 아와오도리가 약 400년의 역사`[4]`를 갖는 그야말로 진짜 역사와 전통의 춤 축제라면, 요사코이는 <del>한국 곳곳의 축제들처럼</del> 축제이기 때문에 엄밀히 말하면 무용의 장르라고 할 수는 없지만, 현재는 지역사회를 넘어서 전국적으로 널리 퍼져 있어서 인지도가 높다. 인지도가 높아졌다고는 하나, 여전히 아와오도리에 비할 바는 되지 못한다. 아와오도리는 학교 축제 때도 자주 만나볼 수 있고 아예 체육 교과과정에 포함되어 있는 곳도 있을 정도라서(...) 아예 아와오도리를 테마로 잡고 만든 게임 노래까지 있을 정도이다([祭JAPAN](%E7%A5%AD%20JAPAN.md), [阿波おどり -Awaodori-](%E9%98%BF%E6%B3%A2%E3%81%8A%E3%81%A9%E3%82%8A%20-Awaodori-.md)). 요사코이라는 단어의 유래에 대해서는 여러 가지 설이 있다. 가장 유력한 것은 '밤에 오세요'라는 뜻의 일본어 고어인 夜さり来い(요사리코이)가 변화되었다는 설. 이외에는 노동자들이 일을 하면서 외치는 기합소리 ヨッショコイ(욧쇼코이)가 변화되었다는 설, 들렀다 가라는 뜻의 よってらっしゃい(욧테랏샤이)가 변화되었다는 설, 지역에서 전승된 민요 가사 중 한 구절에서 따왔다는 설 등이 있다. [[edit](http://rigvedawiki.net/r1/wiki.php/%EC%9A%94%EC%82%AC%EC%BD%94%EC%9D%B 4?action=edit&section=3)] ## 3. 규칙 ¶ 요사코이 춤은 팀마다 개성이 뚜렷하고 자유로운 형식이라 통일성은 없지만, 1팀당 인원은 150명 이하, 일본 전통 의상이 연상되는 의상, 나루코를 들고 전진하는 듯한 안무, ‘요사코이 나루코 춤’의 프레이즈를 반드시 넣을 것 등의 나름대로의 규칙이 있다. 그 이외에는 곡의 장르나 어레인지, 연출 등 모든 사항이 자유이다. 지카타샤도 안전이 확보된다면 어떤 장식을 해도 무방하다. 단 과도한 경쟁을 방지하기 위해 차량의 크기에는 제한이 있다. 아와오도리와 차별되는 점은, 맨손으로 춤추지 않고 나루코라는 도구를 사용한다는 것. [[edit](http://rigvedawiki.net/r1/wiki.php/%EC%9A%94%EC%82%AC%EC%BD%94%EC%9D%B 4?action=edit&section=4)] ## 4. YOSAKOI ¶ 90년대 이전까지는 지방 축제로서의 성격이 강했는데, 90년대 초반에 삿포로에서 요사코이 축제에서 파생시킨 YOSAKOI 소란 축제를 만들었다. 코치 현의 정통 요사코이(よさこい)와는 달리 YOSAKOI는 좀더 자유롭고 제약이 적기 때문에, 이후 이것이 전국적으로 히트쳐 퍼지게 되었다. 현재는 코치 현 본가의 요사코이보다 삿포로의 YOSAKOI가 훨씬 참가자도 많고 개최기간도 길어졌다. <del>주객전도</del> 전국적인 축제로 자리잡은 이후에는, 거리를 활보하는 퍼레이드 형식이 아닌, 팀별로 각자의 요사코이 춤을 선보이는 경연대회 형식으로 탈바꿈하게 되었다. 코치 현에서 의식한 경쟁 상대 아와오도리가 전형적인 퍼레이드 형태라는 것과 대조적이다. 하지만 본가의 요사코이는 여전히 퍼레이드와 비슷한 형식을 고수하고 있다. 어쩌면 YOSAKOI가 편히 앉아서 관람할 수 있는 무대 형식이기 때문에 더 대중적으로 어필한 것일 수도 있다. [[edit](http://rigvedawiki.net/r1/wiki.php/%EC%9A%94%EC%82%AC%EC%BD%94%EC%9D%B 4?action=edit&section=5)] ## 5. 기타 ¶ 축제의 주제가라고 할 수 있는 'よさこい鳴子踊り(요사코이 나루코 춤)'는 당시 코치에 살고 있던`[5]` 작곡가 타케마사 에이사쿠가 민요 ‘요사코이부시’를 바탕으로 만든 것이다. 타케마사는 이외에도 요사코이에 나루코를 쓰자고 제안하기도 했다. ![naruko.jpg](//z.enha.kr/http://rigvedawiki.net/r1/pds/_ec_9a_94_ec_82_ac_ec_ bd_94_ec_9d_b4/naruko.jpg) [JPG image (20.85 KB)] 나루코의 원래 모습.나루코는 원래 논밭에서 새를 쫓기 위해 사용되던 무인 도구였는데 `[6]` 타케마사의 제안으로 사람이 들고 타악기의 일종으로 쓸 수 있도록 모습을 바꾸었다. [[edit](http://rigvedawiki.net/r1/wiki.php/%EC%9A%94%EC%82%AC%EC%BD%94%EC%9D%B 4?action=edit&section=6)] ## 6. 관련 항목 ¶ * [하나야마타](%ED%95%98%EB%82%98%EC%95%BC%EB%A7%88%ED%83%80.md) \- 요사코이를 소재로 한 만화, 애니메이션. 하나야마타에 등장하는 것은 본가 요사코이가 아닌 YOSAKOI 쪽이다.<del>그리고 이 작품이 아니었으면 리그베다위키에 요사코이 항목이 생길 일은 없었을것이다.</del> * [나츠메키](%EB%82%98%EC%B8%A0%EB%A9%94%ED%82%A4.md) \- 하나야마타와 마찬가지로 요사코이를 소재로 한 만화. 하나야마타가 여중생 5명의 우정을 토대로 한 것이라면 이건 고교생들의 러브스토리도 섞여있는 이야기. 본가 요사코이를 토대로 하고 있으며, 실제 요사코이 팀들도 간접적으로 등장. * [나루코](%EB%82%98%EB%A3%A8%EC%BD%94.md) * <del>[냐루코](%EB%83%90%EB%A3%A8%EC%BD%94.md)</del> `\----` * `[1]` 지역에 따라 100만 엔 이상의 상금이 걸린 대회도 있다. * `[2]` 경트럭이나 봉고를 팀의 전체 컨셉에 맞도록 개조해서 꾸민 차 * `[3]` 힙합, 재즈 등 서양 음악이 주류이다. * `[4]` 1587년 아와 지방에 도쿠시마성(徳島城)을 완공했을 때 영주 하치스카 이에마사(蜂須賀家政)가 성의 완성을 축하하는 의미로, 좋아하는 춤을 추게 만들었다는게 아와오도리의 시작이라고 한다. * `[5]` 출신은 에히메 현이다. * `[6]` 밧줄에 깡통이 걸려 있어서 거기에 뭔가가 지나가면 소리가 나는 것과 비슷하다고 보면 된다.
import { Connection, PublicKey, Signer, TransactionInstruction } from "@solana/web3.js"; import { struct, nu64, u8 } from "buffer-layout"; import * as IDS from "../../../utils/ids"; import { createTokenAccount } from "./createTokenAccount"; const LAYOUT = struct<DepositLiquidityData>([ u8("action"), nu64("amount"), u8("divvyPdaBumpSeed") ]) interface DepositLiquidityData { action: number; amount: number; divvyPdaBumpSeed: number; }; export const depositLiquidityTransaction = async ( connection: Connection, userAccount: PublicKey, userHtTokenAccount: PublicKey | undefined, userUsdtTokenAccount: PublicKey | undefined, usdcMintPubkey: PublicKey, action: "deposit" | "withdraw", usdcLamports: number, divvyPdaBumpSeed: number) : Promise<[ix: TransactionInstruction[], signers: Signer[]]> => { let ix: TransactionInstruction[] = []; let signers: Signer[] = []; if (userHtTokenAccount == null) { let [userHtTokenSigner, htIx] = await createTokenAccount( connection, IDS.HT_MINT, userAccount); ix = [...ix, ...htIx]; signers = [...signers, userHtTokenSigner]; userHtTokenAccount = userHtTokenSigner.publicKey; } if (userUsdtTokenAccount == null) { let [usdcSigner, usdcIx] = await createTokenAccount( connection, usdcMintPubkey, userAccount); ix = [...ix, ...usdcIx]; signers = [...signers, usdcSigner]; userUsdtTokenAccount = usdcSigner.publicKey; } const depositLiquidityIx = depositLiquidityInstruction( userAccount, userHtTokenAccount, userUsdtTokenAccount, action, usdcLamports, divvyPdaBumpSeed); return [[...ix, depositLiquidityIx], signers]; } export const depositLiquidityInstruction = ( userAccount: PublicKey, userHtTokenAccount: PublicKey, userUsdtTokenAccount: PublicKey, action: "deposit" | "withdraw", usdcLamports: number, divvyPdaBumpSeed: number): TransactionInstruction => { const data: DepositLiquidityData = { action: action === "deposit" ? 0 : 1, amount: usdcLamports, divvyPdaBumpSeed: divvyPdaBumpSeed }; const dataBuffer = Buffer.alloc(LAYOUT.span); LAYOUT.encode(data, dataBuffer); const instruction = new TransactionInstruction({ keys: [ { pubkey: userAccount, isSigner: true, isWritable: true }, { pubkey: IDS.HT_MINT, isSigner: false, isWritable: true }, { pubkey: IDS.TOKEN_PROGRAM_ID, isSigner: false, isWritable: false }, { pubkey: userHtTokenAccount, isSigner: false, isWritable: true }, { pubkey: IDS.HOUSE_POOL_PDA_ACCOUNT, isSigner: false, isWritable: true }, { pubkey: userUsdtTokenAccount, isSigner: false, isWritable: true }, { pubkey: IDS.HOUSE_POOL_USDC_ACCOUNT, isSigner: false, isWritable: true }, { pubkey: IDS.HOUSE_POOL_STATE_ACCOUNT, isSigner: false, isWritable: true }, { pubkey: IDS.BET_POOL_STATE_ACCOUNT, isSigner: false, isWritable: false } ], programId: IDS.HOUSE_POOL_PROGRAM_ID, data: dataBuffer, }); return instruction; }
#ifndef _DATE #define _DATE #include <iostream> using namespace std; class Date { private: int month; int day; int year; public: Date(); Date(int _month, int _day, int _year); Date(const Date& obj); ~Date(); void setDate(int _month, int _day, int _year); void setMonth(int _month); void setDay(int _day); void setYear(int _year); int getMonth() const; int getDay() const; int getYear() const; Date getDate() const; friend ostream& operator<<(ostream& out, const Date& obj); friend istream& operator>>(istream& in, Date& obj); bool operator>(const Date& other) const; bool operator<(const Date& other) const; bool operator==(const Date& other) const; }; #endif
/* eslint-disable consistent-return */ // это файл контроллеров const bcrypt = require('bcryptjs'); // импортируем bcrypt const User = require('../models/user'); const SALT_ROUNDS = 10; const { generateToken } = require('../helpers/jwt'); const BadRequest = require('../errors/error400'); const NotFound = require('../errors/error404'); const Unauthorized = require('../errors/error401'); const Conflict = require('../errors/error409'); const { ok, created, MONGO_DUPLICATE_ERROR_CODE, } = require('../utils/statusResponse'); // Получаем всех пользователей 500 module.exports.getUsers = (req, res, next) => { User.find({}) // найти вообще всех .then((users) => res.send({ data: users })) .catch(next); }; // Получаем текущего пользователя по id 404 module.exports.getCurrentUser = (req, res, next) => { const { userId } = req.params; User.findById(userId) .orFail(() => new NotFound('Нет пользователя с таким id')) .then((users) => res.send({ data: users })) .catch(next); }; // получаем инф о текущем пользователе module.exports.getCurrentUserProfile = (req, res, next) => { console.log('REQ', req.user); const { _id } = req.user; User.findById(_id) .orFail(() => new NotFound('Пользователь не существует')) .then((user) => res.status(ok).send({ data: user })) .catch(next); }; // дорабатываем контроллер создание пользователя // eslint-disable-next-line arrow-body-style module.exports.createUser = (req, res, next) => { const { name, about, avatar, email, password, } = req.body; // если емэйл и пароль отсутствует - возвращаем ошибку. bcrypt .hash(password, SALT_ROUNDS) // eslint-disable-next-line arrow-body-style .then((hash) => { return User.create({ name, about, avatar, email, password: hash, // записываем хеш в базу, }); }) // пользователь создан .then((user) => res.status(created).send({ _id: user._id, name: user.name, about: user.about, avatar: user.avatar, email: user.email, })) .catch((err) => { if (err.name === 'ValidationError') { next(new BadRequest('Невалидные данные пользователя')); } else if (err.code === MONGO_DUPLICATE_ERROR_CODE) { next(new Conflict('Email занят')); } else { next(err); } }); }; // логин module.exports.login = (req, res, next) => { const { email, password } = req.body; User.findOne({ email }) .select('+password') .then((user) => { if (!user) { // Инструкция throw генерирует исключение и обработка кода // переходит в следующий блок catch(next) throw new Unauthorized('Не авторизован'); } else { return bcrypt .compare(password, user.password) .then((isPasswordCorrect) => { if (!isPasswordCorrect) { throw new Unauthorized('Не авторизован'); } else { const token = generateToken({ _id: user._id.toString() }); res.send({ token }); } }).catch(() => next(new Unauthorized('Неправильный Email или пароль'))); } }) .catch(next); }; // обновляем данные пользователя module.exports.patchProfile = (req, res, next) => { const { name, about } = req.body; User.findByIdAndUpdate( req.user._id, { name, about }, { new: true, runValidators: true }, ) .orFail(() => new NotFound('Пользователь с таким id не найден')) .then((user) => { res.status(ok).send(user); }) .catch((err) => { if (err.name === 'ValidationError' || err.name === 'CastError') { next(new BadRequest('Некорректные данные')); } else { next(err); } }); }; // обновляем аватар module.exports.patchAvatar = (req, res, next) => { const { avatar } = req.body; User.findByIdAndUpdate( req.user._id, { avatar }, { new: true, runValidators: true }, ) .orFail(() => new NotFound('Пользователь с таким id не найден')) .then((user) => { res.status(ok).send(user); }) .catch((err) => { if (err.name === 'ValidationError' || err.name === 'CastError') { next(new BadRequest('Некорректные данные')); } else { next(err); } }); };
/* eslint-disable react-hooks/exhaustive-deps */ /* eslint-disable @typescript-eslint/no-explicit-any */ import { init, getPreferences, onPreferencesChanged } from 'cookie-though'; import { Config } from 'cookie-though/dist/types/types'; import useCookieBlocker from 'src/components/features/useCookieBlocker'; import { patterns } from 'src/utils/cookieBlocker/variables'; import { FC, ReactNode, useEffect, useState } from 'react'; interface ICookieConsent { children: ReactNode; } const config: Config = { policies: [ { id: 'essential', label: 'Essential Cookies', description: 'We need to save some technical cookies, for the website to function properly.', category: 'essential' }, { id: 'functional', label: 'Functional Cookies', category: 'functional', description: 'We need to save some basic preferences eg. language.' }, { id: 'targeting and advertising', label: 'Targeting and advertising cookies', category: 'personalisation', description: 'Cookie used for advertising targeting purposes.' }, { id: 'statistics', label: 'Statistics', category: 'statistics', description: 'These cookies collect statistical information on the number and behavior of users visiting the site and their preferences.' } ], essentialLabel: 'Always on', permissionLabels: { accept: 'Accept', acceptAll: 'Accept all', decline: 'Decline' }, cookiePreferenceKey: 'cookie-preferences', header: { title: 'Humaapi Cookies !', // subTitle: "You're probably fed up with these banners...", description: 'Well ok, these cookies are neither sweet, nor chocolate, nor soft. But they allow us to know you better and to offer you content that you will love to devour. And that is worth all the cookies in the world.' }, cookiePolicy: { url: '/cookie-policy', label: 'Read the full cookie declaration' }, customizeLabel: 'I choose' }; const CookieConsent: FC<ICookieConsent> = (props) => { const { children } = props; const cookieBlocker = useCookieBlocker(); const [isMount, setIsMount] = useState(false); const isTrue = (value: any) => value.isEnabled === true; useEffect(() => { setIsMount(true); // eslint-disable-next-line @typescript-eslint/no-non-null-assertion patterns!.blacklist = []; // eslint-disable-next-line @typescript-eslint/no-non-null-assertion patterns!.whitelist = [/www\.google\.com/]; cookieBlocker.startMonitoring(); cookieBlocker.blockDynamicScript(); init(config); }, []); if (isMount) { onPreferencesChanged((preferences) => { if (preferences.cookieOptions.every(isTrue)) { cookieBlocker.unblock(); return; } if (preferences.cookieOptions[2].isEnabled) { cookieBlocker.unblock(/www\.google\.com/); } }); } return <div>{children}</div>; }; export default CookieConsent;
<?php namespace App\Entity; use App\Repository\ObjetsRepository; use Doctrine\Common\Collections\ArrayCollection; use Doctrine\Common\Collections\Collection; use Doctrine\ORM\Mapping as ORM; #[ORM\Entity(repositoryClass: ObjetsRepository::class)] class Objets { #[ORM\Id] #[ORM\GeneratedValue] #[ORM\Column] private ?int $id = null; #[ORM\Column(length: 255)] private ?string $nom = null; #[ORM\Column(length: 255)] private ?string $description = null; #[ORM\OneToMany(mappedBy: 'objet', targetEntity: Emprunts::class)] private Collection $emprunts; public function __construct() { $this->emprunts = new ArrayCollection(); } public function getId(): ?int { return $this->id; } public function getNom(): ?string { return $this->nom; } public function setNom(string $nom): static { $this->nom = $nom; return $this; } public function getDescription(): ?string { return $this->description; } public function setDescription(string $description): static { $this->description = $description; return $this; } /** * @return Collection<int, Emprunts> */ public function getEmprunts(): Collection { return $this->emprunts; } public function addEmprunt(Emprunts $emprunt): static { if (!$this->emprunts->contains($emprunt)) { $this->emprunts->add($emprunt); $emprunt->setObjet($this); } return $this; } public function removeEmprunt(Emprunts $emprunt): static { if ($this->emprunts->removeElement($emprunt)) { // set the owning side to null (unless already changed) if ($emprunt->getObjet() === $this) { $emprunt->setObjet(null); } } return $this; } public function __toString() { return $this->getNom() ; } }
package database import ( "fmt" "spotigram/internal/config" infrastructureAbstractions "spotigram/internal/infrastructure/abstractions" "database/sql" "github.com/gocql/gocql" _ "github.com/lib/pq" ) // Returns a postgres based sql database provider. func NewCassandraCqlDatabaseProvider(cfg *config.Config) infrastructureAbstractions.CqlDatabaseProvider { cluster := gocql.NewCluster(cfg.CqlDb.Host) cluster.ProtoVersion = 4 s, err := cluster.CreateSession() if err != nil { panic(fmt.Errorf("error creating cassandra session: %v", err)) } initializeCassandraKeyspace(cfg, s) s.Close() cluster.Keyspace = cfg.CqlDb.KeySpace s, err = cluster.CreateSession() if err != nil { panic(fmt.Errorf("error creating cassandra session in keyspace: %v", err)) } initializeCassandraTable(cfg, s) return &cassandraCqlDatabaseProvider{session: s} } // Returns a postgres based sql database provider. func NewPostgresSqlDatabaseProvider(cfg *config.Config) infrastructureAbstractions.SqlDatabaseProvider { dsn := fmt.Sprintf( "host=%s user=%s password=%s dbname=%s port=%d sslmode=%s TimeZone=%s", cfg.SqlDb.Host, cfg.SqlDb.User, cfg.SqlDb.Password, cfg.SqlDb.DBName, cfg.SqlDb.Port, cfg.SqlDb.SSLMode, cfg.SqlDb.TimeZone, ) db, err := sql.Open("postgres", dsn) if err != nil { panic("failed to connect Postgres database.") } err = db.Ping() if err != nil { panic(fmt.Errorf("ping to database failed: %v", err)) } initializePostgresDatabase(cfg, db) return &postgresSqlDatabaseProvider{Db: db} }
/** * Sample for Bubble Series */ import * as React from "react"; import * as ReactDOM from "react-dom"; import { EmitType } from '@syncfusion/ej2-base'; import { ChartComponent, SeriesCollectionDirective, SeriesDirective, Inject, BubbleSeries, Tooltip, IPointRenderEventArgs, ILoadedEventArgs, ChartTheme, DataLabel } from '@syncfusion/ej2-react-charts'; import { Browser } from '@syncfusion/ej2-base'; import { bubbleFabricColors, bubbleMaterialDarkColors, bubbleMaterialColors, bubbleBootstrap5DarkColors, bubbleBootstrapColors, bubbleHighContrastColors, bubbleFluentDarkColors, bubbleFluentColors, bubbleTailwindDarkColors, bubbleTailwindColors, pointFabricColors, pointMaterialDarkColors, pointMaterialColors, pointBootstrap5DarkColors, pointBootstrapColors, pointHighContrastColors, pointFluentDarkColors, pointFluentColors, pointTailwindDarkColors, pointTailwindColors, bubbleBootstrap5Colors, pointBootstrap5Colors, bubbleMaterial3Colors, pointMaterial3Colors, bubbleMaterial3DarkColors, pointMaterial3DarkColors } from './theme-color'; import { SampleBase } from '../common/sample-base'; export let pointRender: EmitType<IPointRenderEventArgs> = (args: IPointRenderEventArgs): void => { let selectedTheme: string = location.hash.split('/')[1]; selectedTheme = selectedTheme ? selectedTheme : 'material'; if (selectedTheme && selectedTheme.indexOf('fabric') > -1) { args.fill = bubbleFabricColors[args.point.index % 10]; args.border.color = pointFabricColors[args.point.index % 10];; } else if (selectedTheme === 'material-dark') { args.fill = bubbleMaterialDarkColors[args.point.index % 10]; args.border.color = pointMaterialDarkColors[args.point.index % 10];; } else if (selectedTheme === 'material') { args.fill = bubbleMaterialColors[args.point.index % 10]; args.border.color = pointMaterialColors[args.point.index % 10]; } else if (selectedTheme === 'bootstrap5-dark') { args.fill = bubbleBootstrap5DarkColors[args.point.index % 10]; args.border.color = pointBootstrap5DarkColors[args.point.index % 10]; } else if (selectedTheme === 'bootstrap5') { args.fill = bubbleBootstrap5Colors[args.point.index % 10]; args.border.color = pointBootstrap5Colors[args.point.index % 10]; } else if (selectedTheme === 'bootstrap') { args.fill = bubbleBootstrapColors[args.point.index % 10]; args.border.color = pointBootstrapColors[args.point.index % 10]; } else if (selectedTheme === 'bootstrap4') { args.fill = bubbleBootstrapColors[args.point.index % 10]; args.border.color = pointBootstrapColors[args.point.index % 10]; } else if (selectedTheme === 'bootstrap-dark') { args.fill = bubbleBootstrapColors[args.point.index % 10]; args.border.color = pointBootstrapColors[args.point.index % 10]; } else if (selectedTheme === 'highcontrast') { args.fill = bubbleHighContrastColors[args.point.index % 10]; args.border.color = pointHighContrastColors[args.point.index % 10]; } else if (selectedTheme === 'fluent-dark') { args.fill = bubbleFluentDarkColors[args.point.index % 10]; args.border.color = pointFluentDarkColors[args.point.index % 10]; } else if (selectedTheme === 'fluent') { args.fill = bubbleFluentColors[args.point.index % 10]; args.border.color = pointFluentColors[args.point.index % 10]; } else if (selectedTheme === 'tailwind-dark') { args.fill = bubbleTailwindDarkColors[args.point.index % 10]; args.border.color = pointTailwindDarkColors[args.point.index % 10]; } else if (selectedTheme === 'tailwind') { args.fill = bubbleTailwindColors[args.point.index % 10]; args.border.color = pointTailwindColors[args.point.index % 10]; } else if (selectedTheme === 'material3') { args.fill = bubbleMaterial3Colors[args.point.index % 10]; args.border.color = pointMaterial3Colors[args.point.index % 10]; } else if (selectedTheme === 'material3-dark') { args.fill = bubbleMaterial3DarkColors[args.point.index % 10]; args.border.color = pointMaterial3DarkColors[args.point.index % 10]; } }; export let data: any[] = [ { x: 92.2, y: 7.8, size: 1.347, text: 'China',r:'China' }, { x: 74, y: 6.5, size: 1.241, text: 'India',r:'India' }, { x: 90.4, y: 6.0, size: 0.238, text: 'Indonesia',r: Browser.isDevice ? 'ID' : 'Indonesia' }, { x: 99.4, y: 2.2, size: 0.312, text: 'United States' ,r:'US'}, { x: 88.6, y: 1.3, size: 0.197, text: 'Brazil' ,r: Browser.isDevice ? 'BR' : 'Brazil'}, { x: 99, y: 0.7, size: 0.0818, text: 'Germany' ,r: Browser.isDevice ? 'DE' : 'Germany'}, { x: 72, y: 2.0, size: 0.0826, text: 'Egypt' ,r: Browser.isDevice ? 'EG' : 'Egypt'}, { x: 99.6, y: 3.4, size: 0.143, text: 'Russia' ,r: Browser.isDevice ? 'RUS' : 'Russia' }, { x: 96.5, y: 0.2, size: 0.128, text: 'Japan' ,r: Browser.isDevice ? 'JP' : 'Japan'}, { x: 86.1, y: 4.0, size: 0.115, text: 'MeLiteracy Ion' ,r:'MLI'}, { x: 92.6, y: 5.2, size: 0.096, text: 'Philippines' ,r:'PH'}, { x: 61.3, y: 1.45, size: 0.162, text: 'Nigeria' ,r:'Nigeria'}, { x: 82.2, y: 3.97, size: 0.7, text: 'Hong Kong' ,r: Browser.isDevice ? 'HK' : 'Hong Kong'}, { x: 79.2, y: 4.9, size: 0.162, text: 'Netherland' ,r:'NL'}, { x: 72.5, y: 4.5, size: 0.7, text: 'Jordan' ,r:'Jordan'}, { x: 81, y: 2.5, size: 0.21, text: 'Australia' ,r: Browser.isDevice ? 'AU' : 'Australia'}, { x: 66.8, y: 3.9, size: 0.028, text: 'Mongolia' ,r:'MN'}, { x: 78.4, y: 2.9, size: 0.231, text: 'Taiwan' ,r: Browser.isDevice ? 'TW' : 'Taiwan'} ]; const SAMPLE_CSS = ` .control-fluid { padding: 0px !important; } ellipse[id*=_Trackball_0] { strokeWidth: 1 !important; } `; /** * Bubble sample */ export class Bubble extends SampleBase<{}, {}> { render() { return ( <div className='control-pane'> <style> {SAMPLE_CSS} </style> <div className='control-section'> <ChartComponent id='charts' style={{ textAlign: "center" }} primaryXAxis={{ minimum: 65, maximum: 102, interval: 5, crossesAt: 5 }} load={this.load.bind(this)} primaryYAxis={{ minimum: 0, maximum: 10, crossesAt: 85, interval: 2.5 }} width={Browser.isDevice ? '100%' : '75%'} title='World Countries Details' pointRender={pointRender} legendSettings={{ visible: false }} loaded={this.onChartLoad.bind(this)} tooltip={{ enableMarker: false, enable: true, header: "<b>${point.tooltip}</b>", format: "Literacy Rate : <b>${point.x}%</b> <br/>GDP Annual Growth Rate : <b>${point.y}</b><br/>Population : <b>${point.size} Billion</b>" }}> <Inject services={[BubbleSeries, Tooltip, DataLabel]} /> <SeriesCollectionDirective> <SeriesDirective dataSource={data} type='Bubble' minRadius={3} maxRadius={8} tooltipMappingName='text' border={{width:2}} xName='x' yName='y' size='size' marker={{ dataLabel: { visible: true,name: 'r', position: 'Middle', font: { fontWeight: '500', color: '#ffffff' } } }} > </SeriesDirective> </SeriesCollectionDirective> </ChartComponent> </div> <div id="action-description"> <p> This React bubble chart example visualizes the literacy rates and GDP growth rates of countries. A tooltip shows more information about the countries. </p> </div> <div id="description"> <p> In this example, you can see how to render and configure the bubble chart. The bubble chart is a type of chart that shows three dimensions of the data. Each point is drawn as a bubble, where the bubble's size depends on the <code>Size</code> property. You can also use the <code>Fill</code> property to customize the data appearance. </p> <p> <code>Tooltip</code> is enabled in this example, to see the tooltip in action, hover a point or tap on a point in touch enabled devices. </p> <br></br> <p><b>Injecting Module</b></p> <p> Chart component features are segregated into individual feature-wise modules. To use bubble series, we need to inject <code>BubbleSeries</code> module into <code>services</code>. </p> <p> More information on the bubble series can be found in this &nbsp; <a target="_blank" href="https://ej2.syncfusion.com/react/documentation/chart/chart-types/bubble">documentation section</a>. </p> </div> </div> ) } public onChartLoad(args: ILoadedEventArgs): void { let chart: Element = document.getElementById('charts'); chart.setAttribute('title', ''); }; public load(args: ILoadedEventArgs): void { let selectedTheme: string = location.hash.split('/')[1]; selectedTheme = selectedTheme ? selectedTheme : 'Material'; args.chart.theme = (selectedTheme.charAt(0).toUpperCase() + selectedTheme.slice(1)). replace(/-dark/i, "Dark").replace(/contrast/i,'Contrast') as ChartTheme; }; }
<?php namespace App\DTOs\Post; use App\Http\Resources\Api\v1\Post\PostResource; use App\Models\Post; use Illuminate\Database\Eloquent\Collection; use Illuminate\Http\Resources\Json\AnonymousResourceCollection; use Illuminate\Http\Resources\Json\JsonResource; use WendellAdriel\ValidatedDTO\ValidatedDTO; class PostResponseDTO extends ValidatedDTO { public bool $success; public string|null $message; public PostResource $post; /** * Defines the validation rules for the DTO. */ protected function rules(): array { return [ 'success' => ['nullable'], 'message' => ['nullable', 'string'], 'post' => ['required'], ]; } /** * Defines the default values for the properties of the DTO. */ protected function defaults(): array { return [ 'success' => true, 'message' => 'Success', ]; } /** * Defines the type casting for the properties of the DTO. */ protected function casts(): array { return []; } }
/* * @Author: kim * @Date: 2022-09-07 18:10:32 * @Description: 按钮 */ import { FC, ReactNode, MouseEvent, useCallback } from 'react' import classNames from 'classnames' import Icon from '@/components/Icon' import { getPrefixCls } from '@/components/config' export interface ButtonProps { prefixCls?: string className?: string loading?: boolean // 是否加载中 block?: boolean // 将按钮宽度调整为其父宽度的选项 disabled?: boolean // 按钮失效状态 ghost?: boolean // 幽灵属性,使按钮背景透明 danger?: boolean // 设置危险按钮 shape?: 'default' | 'circle' | 'round' // 设置按钮形状 type?: 'primary' | 'dashed' | 'link' | 'text' | 'default' // 设置按钮类型 size?: 'large' | 'normal' | 'small' | 'mini' // 设置按钮大小 onClick?: (e: MouseEvent<HTMLButtonElement>) => any children?: ReactNode } const Button: FC<ButtonProps> = (props) => { const { prefixCls: customizePrefixCls, className, loading = false, block = false, disabled = false, danger = false, ghost = false, size = 'normal', shape = 'default', type = 'default', onClick, children } = props const prefixCls = getPrefixCls('button',customizePrefixCls) const classes = classNames( prefixCls, { [`${prefixCls}-block`]: block, [`${prefixCls}-${shape}`]: shape !== 'default' && shape, [`${prefixCls}-${type}`]: type, [`${prefixCls}-loading`]: loading, [`${prefixCls}-${size}`]: size && size !== 'normal', [`${prefixCls}-ghost`]: ghost, [`${prefixCls}-dangerous`]: !!danger, }, className, ) const handleClick = useCallback((e: MouseEvent<HTMLButtonElement>) => { if (disabled) return onClick && onClick(e) }, [disabled, onClick]) return <button className={classes} disabled={disabled} onClick={handleClick}> {loading && <span className={`${prefixCls}-loading-icon`}><Icon type='loading' /></span>} <span>{children}</span> </button> } export default Button
/** * @file string_util.cpp * @brief * @author Shijie Zhou * @copyright 2024 Shijie Zhou */ #include "string_util.h" #include <string.h> #include <algorithm> #ifdef _WIN32 #define WIN32_LEAN_AND_MEAN #include <Windows.h> #else #include <unistd.h> #include <sys/stat.h> #include <iconv.h> #endif // _WIN32 namespace sys { void string_util::split(const std::string& src, const std::string& pattern, std::vector<std::string>& result,int max,bool removeEmpty) { std::string::size_type pos = 0; std::string::size_type size = src.size(); if (max == 0||size==0||pattern.size()==0) return; while (pos <= size) { std::string::size_type end = src.find(pattern, pos); std::string s; if ((max >= 0&& result.size() >= max-1)||end==std::string::npos) { s = src.substr(pos, std::string::npos); pos = std::string::npos; } else { s = src.substr(pos, end-pos); pos = end; } if (removeEmpty) { if (!s.empty()) { result.push_back(s); } } else { result.push_back(s); } if (pos < size) { pos += pattern.size(); } } } std::vector<std::string> string_util::split(const std::string& src, const std::string& pattern, int max, bool removeEmpty) { std::vector<std::string> result; std::string::size_type pos = 0; std::string::size_type size = src.size(); if (max == 0 || size == 0 || pattern.size() == 0) return result; while (pos <= size) { std::string::size_type end = src.find(pattern, pos); std::string s; if ((max >= 0 && result.size() >= max - 1) || end == std::string::npos) { s = src.substr(pos, std::string::npos); pos = std::string::npos; } else { s = src.substr(pos, end - pos); pos = end; } if (removeEmpty) { if (!s.empty()) { result.push_back(s); } } else { result.push_back(s); } if (pos < size) { pos += pattern.size(); } } return result; } std::string string_util::gb2312_to_utf8(const std::string& gb2312) { std::vector<wchar_t> buff(gb2312.size()); #ifdef _MSC_VER std::locale loc("zh-CN"); #else std::locale loc("zh_CN.GB18030"); #endif wchar_t* pwsz_next = nullptr; const char* psz_next = nullptr; mbstate_t state = {}; int res = std::use_facet<std::codecvt<wchar_t, char, mbstate_t> > (loc).in(state, gb2312.data(), gb2312.data() + gb2312.size(), psz_next, buff.data(), buff.data() + buff.size(), pwsz_next); if (std::codecvt_base::ok == res) { std::wstring_convert<std::codecvt_utf8<wchar_t>> cutf8; return cutf8.to_bytes(std::wstring(buff.data(), pwsz_next)); } return ""; } std::string string_util::utf8_to_gb2312(const std::string& utf8) { std::wstring_convert<std::codecvt_utf8<wchar_t>> cutf8; std::wstring wtemp = cutf8.from_bytes(utf8); #ifdef _MSC_VER std::locale loc("zh_CN"); #else std::locale loc("zh_CN.GB18030"); #endif const wchar_t* pwsz_next = nullptr; char* psz_next = nullptr; mbstate_t state = {}; std::vector<char> buff(wtemp.size() * 2); int res = std::use_facet<std::codecvt<wchar_t, char, mbstate_t> > (loc).out(state, wtemp.data(), wtemp.data() + wtemp.size(), pwsz_next, buff.data(), buff.data() + buff.size(), psz_next); if (std::codecvt_base::ok == res) { return std::string(buff.data(), psz_next); } return ""; } std::string string_util::w2s(const std::wstring& wstr) { #ifdef _WIN32 std::string res; int len = WideCharToMultiByte(CP_ACP, 0, wstr.c_str(), wstr.size(), nullptr, 0, nullptr, nullptr); if (len <= 0) { return res; } char* buffer = new char[len + 1]; if (buffer == nullptr) { return res; } WideCharToMultiByte(CP_ACP, 0, wstr.c_str(), wstr.size(), buffer, len, nullptr, nullptr); buffer[len] = '\0'; res.append(buffer); delete[] buffer; return res; #else setlocale(LC_ALL, "en_US.UTF-8"); const wchar_t* wchSrc = wstr.c_str(); size_t nWStr = wcstombs(NULL, wchSrc, 0) + 1; char* chDest = new char[nWStr]; memset(chDest, 0, nWStr); wcstombs(chDest, wchSrc, nWStr); std::string strRes = chDest; delete[] chDest; return strRes; #endif } std::wstring string_util::s2w(const std::string& str) { #ifdef _WIN32 std::wstring res; int len = MultiByteToWideChar(CP_ACP, 0, str.c_str(), str.size(), nullptr, 0); if (len < 0) { return res; } wchar_t* buffer = new wchar_t[len + 1]; if (buffer == nullptr) { return res; } MultiByteToWideChar(CP_ACP, 0, str.c_str(), str.size(), buffer, len); buffer[len] = '\0'; res.append(buffer); delete[] buffer; return res; #else std::string strUtf8 = str; setlocale(LC_ALL, "en_US.UTF-8"); const char* chSrc = strUtf8.c_str(); size_t nStr = mbstowcs(NULL, chSrc, 0) + 1; wchar_t* wchDest = new wchar_t[nStr]; memset(wchDest, 0, nStr); mbstowcs(wchDest, chSrc, nStr); std::wstring wStrRes = wchDest; delete[] wchDest; return wStrRes; #endif } char* string_util::alloc(const std::string& s) { char* ret = nullptr; size_t len = s.size() + 1; if (len <= 0) { return ret; } ret = (char*)malloc(len); memset(ret, 0, len); s.copy(ret, len); return ret; } void string_util::free(char** p) { if (p && (*p)) { ::free(*p); *p = NULL; } } std::string string_util::join_path(std::string& path1, std::string& path2, const std::string& separator) { auto itr = path1.rbegin(); if (itr != path1.rend()) { if (*itr == '/' || *itr == '\\') { path1.erase((itr + 1).base()); } } else { path1 = path2; return path1; } auto itr2 = path2.begin(); if (itr2 != path2.end()) { if (*itr2 == '/' || *itr2 == '\\') { path2.erase(itr2); } } return path1.append(separator).append(path2); } // trim from start (in place) void string_util::ltrim(std::string& s) { s.erase(s.begin(), std::find_if(s.begin(), s.end(), [](unsigned char ch) { return !std::isspace(ch); })); } // trim from end (in place) void string_util::rtrim(std::string& s) { s.erase(std::find_if(s.rbegin(), s.rend(), [](unsigned char ch) { return !std::isspace(ch); }).base(), s.end()); } // trim from both ends (in place) void string_util::trim(std::string& s) { rtrim(s); ltrim(s); } bool string_util::icasecompare(const std::string& a, const std::string& b) { return std::equal(a.begin(), a.end(), b.begin(), b.end(), [](char c1, char c2) { return std::tolower(c1) == std::tolower(c2); } ); } }
<!doctype html> <html lang="en"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <title>{{ $title }}</title> <link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-4bw+/aepP/YC94hEpVNVgiZdgIC5+VKNBQNGCHeKRQN+PtmoHDEXuppvnDJzQIu9" crossorigin="anonymous"> <script src="https://code.jquery.com/jquery-3.7.1.min.js" integrity="sha256-/JqT3SQfawRcv/BIHPThkBvs0OEvtFFmqPF/lYI/Cxo=" crossorigin="anonymous"></script> <script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script> </head> <body> <nav class="navbar navbar-expand-lg bg-body-tertiary"> <div class="container-fluid"> <div class="collapse navbar-collapse" id="navbarSupportedContent"> <ul class="navbar-nav me-auto mb-2 mb-lg-0"> <li class="nav-item"> <a class="nav-link " href="/home/products">Home</a> </li> @if( session('admin') !== null && session('admin') == true) <li class="nav-item"> <a class="nav-link" href="/admin">Admin</a> </li> <li class="nav-item"> <a class="nav-link" href="/admin/products">Products</a> </li> <li class="nav-item"> <a class="nav-link" href="/admin/brands">Brands</a> </li> <li class="nav-item"> <a class="nav-link" href="/admin/orders">Orders</a> </li> <li class="nav-item"> <a class="nav-link" href="/logout">Logout</a> </li> @elseif(session('admin') == null) <li class="nav-item"> <a class="nav-link" href="/sign-up">Sign-up</a> </li> <li class="nav-item"> <a class="nav-link" href="/sign-in">Sign-in</a> </li> @endif </ul> </div> </div> </nav> {{ $slot }} <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.bundle.min.js" integrity="sha384-HwwvtgBNo3bZJJLYd8oVXjrBZt8cqVSpeBNS5n7C8IVInixGAoxmnlMuBnhbgrkm" crossorigin="anonymous"></script> </body> </html>
/************************************** * 作用:SQLLite Server操作实现 * 作者:Nick.Yan * 日期: 2009-03-29 * 网址:www.redglove.com.cn **************************************/ using System; using System.Collections; using System.Collections.Specialized; using System.Data; using System.Data.SQLite; using System.Configuration; namespace JqueryApp { public class SQLiteHelper { //数据库连接字符串(web.config来配置),可以动态更改SQLString支持多数据库. public static string connectionString = "Data Source=" + System.Web.HttpContext.Current.Server.MapPath(ConfigurationManager.AppSettings["SQLString"]); public SQLiteHelper() { } #region 公用方法 public static int GetMaxID(string FieldName, string TableName) { string strsql = "select max(" + FieldName + ")+1 from " + TableName; object obj = GetSingle(strsql); if (obj == null) { return 1; } else { return int.Parse(obj.ToString()); } } public static bool Exists(string strSql) { object obj = GetSingle(strSql); int cmdresult; if ((Object.Equals(obj, null)) || (Object.Equals(obj, System.DBNull.Value))) { cmdresult = 0; } else { cmdresult = int.Parse(obj.ToString()); } if (cmdresult == 0) { return false; } else { return true; } } public static bool Exists(string strSql, params SQLiteParameter[] cmdParms) { object obj = GetSingle(strSql, cmdParms); int cmdresult; if ((Object.Equals(obj, null)) || (Object.Equals(obj, System.DBNull.Value))) { cmdresult = 0; } else { cmdresult = int.Parse(obj.ToString()); } if (cmdresult == 0) { return false; } else { return true; } } #endregion #region 执行简单SQL语句 /// <summary> /// 执行SQL语句,返回影响的记录数 /// </summary> /// <param name="SQLString">SQL语句</param> /// <returns>影响的记录数</returns> public static int ExecuteSql(string SQLString) { using (SQLiteConnection connection = new SQLiteConnection(connectionString)) { using (SQLiteCommand cmd = new SQLiteCommand(SQLString, connection)) { try { connection.Open(); int rows = cmd.ExecuteNonQuery(); return rows; } catch (System.Data.SQLite.SQLiteException E) { connection.Close(); throw new Exception(E.Message); } } } } /// <summary> /// 执行SQL语句,设置命令的执行等待时间 /// </summary> /// <param name="SQLString"></param> /// <param name="Times"></param> /// <returns></returns> public static int ExecuteSqlByTime(string SQLString, int Times) { using (SQLiteConnection connection = new SQLiteConnection(connectionString)) { using (SQLiteCommand cmd = new SQLiteCommand(SQLString, connection)) { try { connection.Open(); cmd.CommandTimeout = Times; int rows = cmd.ExecuteNonQuery(); return rows; } catch (System.Data.SQLite.SQLiteException E) { connection.Close(); throw new Exception(E.Message); } } } } /// <summary> /// 执行多条SQL语句,实现数据库事务。 /// </summary> /// <param name="SQLStringList">多条SQL语句</param> public static void ExecuteSqlTran(ArrayList SQLStringList) { using (SQLiteConnection conn = new SQLiteConnection(connectionString)) { conn.Open(); SQLiteCommand cmd = new SQLiteCommand(); cmd.Connection = conn; SQLiteTransaction tx = conn.BeginTransaction(); cmd.Transaction = tx; try { for (int n = 0; n < SQLStringList.Count; n++) { string strsql = SQLStringList[n].ToString(); if (strsql.Trim().Length > 1) { cmd.CommandText = strsql; cmd.ExecuteNonQuery(); } } tx.Commit(); } catch (System.Data.SQLite.SQLiteException E) { tx.Rollback(); throw new Exception(E.Message); } } } /// <summary> /// 执行带一个存储过程参数的的SQL语句。 /// </summary> /// <param name="SQLString">SQL语句</param> /// <param name="content">参数内容,比如一个字段是格式复杂的文章,有特殊符号,可以通过这个方式添加</param> /// <returns>影响的记录数</returns> public static int ExecuteSql(string SQLString, string content) { using (SQLiteConnection connection = new SQLiteConnection(connectionString)) { SQLiteCommand cmd = new SQLiteCommand(SQLString, connection); SQLiteParameter myParameter = new SQLiteParameter("@content", DbType.String); myParameter.Value = content; cmd.Parameters.Add(myParameter); try { connection.Open(); int rows = cmd.ExecuteNonQuery(); return rows; } catch (System.Data.SQLite.SQLiteException E) { throw new Exception(E.Message); } finally { cmd.Dispose(); connection.Close(); } } } /// <summary> /// 执行带一个存储过程参数的的SQL语句。 /// </summary> /// <param name="SQLString">SQL语句</param> /// <param name="content">参数内容,比如一个字段是格式复杂的文章,有特殊符号,可以通过这个方式添加</param> /// <returns>影响的记录数</returns> public static object ExecuteSqlGet(string SQLString, string content) { using (SQLiteConnection connection = new SQLiteConnection(connectionString)) { SQLiteCommand cmd = new SQLiteCommand(SQLString, connection); SQLiteParameter myParameter = new SQLiteParameter("@content", DbType.String); myParameter.Value = content; cmd.Parameters.Add(myParameter); try { connection.Open(); object obj = cmd.ExecuteScalar(); if ((Object.Equals(obj, null)) || (Object.Equals(obj, System.DBNull.Value))) { return null; } else { return obj; } } catch (System.Data.SQLite.SQLiteException E) { throw new Exception(E.Message); } finally { cmd.Dispose(); connection.Close(); } } } /// <summary> /// 向数据库里插入图像格式的字段(和上面情况类似的另一种实例) /// </summary> /// <param name="strSQL">SQL语句</param> /// <param name="fs">图像字节,数据库的字段类型为image的情况</param> /// <returns>影响的记录数</returns> public static int ExecuteSqlInsertImg(string strSQL, byte[] fs) { using (SQLiteConnection connection = new SQLiteConnection(connectionString)) { SQLiteCommand cmd = new SQLiteCommand(strSQL, connection); SQLiteParameter myParameter = new SQLiteParameter("@fs", DbType.Binary); myParameter.Value = fs; cmd.Parameters.Add(myParameter); try { connection.Open(); int rows = cmd.ExecuteNonQuery(); return rows; } catch (System.Data.SQLite.SQLiteException E) { throw new Exception(E.Message); } finally { cmd.Dispose(); connection.Close(); } } } /// <summary> /// 执行一条计算查询结果语句,返回查询结果(object)。 /// </summary> /// <param name="SQLString">计算查询结果语句</param> /// <returns>查询结果(object)</returns> public static object GetSingle(string SQLString) { using (SQLiteConnection connection = new SQLiteConnection(connectionString)) { using (SQLiteCommand cmd = new SQLiteCommand(SQLString, connection)) { try { connection.Open(); object obj = cmd.ExecuteScalar(); if ((Object.Equals(obj, null)) || (Object.Equals(obj, System.DBNull.Value))) { return null; } else { return obj; } } catch (System.Data.SQLite.SQLiteException e) { connection.Close(); throw new Exception(e.Message); } } } } /// <summary> /// 执行查询语句,返回SQLiteDataReader(使用该方法切记要手工关闭SQLiteDataReader和连接) /// </summary> /// <param name="strSQL">查询语句</param> /// <returns>SQLiteDataReader</returns> public static SQLiteDataReader ExecuteReader(string strSQL) { SQLiteConnection connection = new SQLiteConnection(connectionString); SQLiteCommand cmd = new SQLiteCommand(strSQL, connection); try { connection.Open(); SQLiteDataReader myReader = cmd.ExecuteReader(); return myReader; } catch (System.Data.SQLite.SQLiteException e) { throw new Exception(e.Message); } //finally //不能在此关闭,否则,返回的对象将无法使用 //{ // cmd.Dispose(); // connection.Close(); //} } /// <summary> /// 执行查询语句,返回DataSet /// </summary> /// <param name="SQLString">查询语句</param> /// <returns>DataSet</returns> public static DataSet Query(string SQLString) { using (SQLiteConnection connection = new SQLiteConnection(connectionString)) { DataSet ds = new DataSet(); try { connection.Open(); SQLiteDataAdapter command = new SQLiteDataAdapter(SQLString, connection); command.Fill(ds, "ds"); } catch (System.Data.SQLite.SQLiteException ex) { throw new Exception(ex.Message); } return ds; } } public static DataSet Query(string SQLString, string TableName) { using (SQLiteConnection connection = new SQLiteConnection(connectionString)) { DataSet ds = new DataSet(); try { connection.Open(); SQLiteDataAdapter command = new SQLiteDataAdapter(SQLString, connection); command.Fill(ds, TableName); } catch (System.Data.SQLite.SQLiteException ex) { throw new Exception(ex.Message); } return ds; } } /// <summary> /// 执行查询语句,返回DataSet,设置命令的执行等待时间 /// </summary> /// <param name="SQLString"></param> /// <param name="Times"></param> /// <returns></returns> public static DataSet Query(string SQLString, int Times) { using (SQLiteConnection connection = new SQLiteConnection(connectionString)) { DataSet ds = new DataSet(); try { connection.Open(); SQLiteDataAdapter command = new SQLiteDataAdapter(SQLString, connection); command.SelectCommand.CommandTimeout = Times; command.Fill(ds, "ds"); } catch (System.Data.SQLite.SQLiteException ex) { throw new Exception(ex.Message); } return ds; } } #endregion #region 执行带参数的SQL语句 /// <summary> /// 执行SQL语句,返回影响的记录数 /// </summary> /// <param name="SQLString">SQL语句</param> /// <returns>影响的记录数</returns> public static int ExecuteSql(string SQLString, params SQLiteParameter[] cmdParms) { using (SQLiteConnection connection = new SQLiteConnection(connectionString)) { using (SQLiteCommand cmd = new SQLiteCommand()) { try { PrepareCommand(cmd, connection, null, SQLString, cmdParms); int rows = cmd.ExecuteNonQuery(); cmd.Parameters.Clear(); return rows; } catch (System.Data.SQLite.SQLiteException E) { throw new Exception(E.Message); } } } } /// <summary> /// 执行多条SQL语句,实现数据库事务。 /// </summary> /// <param name="SQLStringList">SQL语句的哈希表(key为sql语句,value是该语句的SQLiteParameter[])</param> public static void ExecuteSqlTran(Hashtable SQLStringList) { using (SQLiteConnection conn = new SQLiteConnection(connectionString)) { conn.Open(); using (SQLiteTransaction trans = conn.BeginTransaction()) { SQLiteCommand cmd = new SQLiteCommand(); try { //循环 foreach (DictionaryEntry myDE in SQLStringList) { string cmdText = myDE.Key.ToString(); SQLiteParameter[] cmdParms = (SQLiteParameter[])myDE.Value; PrepareCommand(cmd, conn, trans, cmdText, cmdParms); int val = cmd.ExecuteNonQuery(); cmd.Parameters.Clear(); trans.Commit(); } } catch { trans.Rollback(); throw; } } } } /// <summary> /// 执行一条计算查询结果语句,返回查询结果(object)。 /// </summary> /// <param name="SQLString">计算查询结果语句</param> /// <returns>查询结果(object)</returns> public static object GetSingle(string SQLString, params SQLiteParameter[] cmdParms) { using (SQLiteConnection connection = new SQLiteConnection(connectionString)) { using (SQLiteCommand cmd = new SQLiteCommand()) { try { PrepareCommand(cmd, connection, null, SQLString, cmdParms); object obj = cmd.ExecuteScalar(); cmd.Parameters.Clear(); if ((Object.Equals(obj, null)) || (Object.Equals(obj, System.DBNull.Value))) { return null; } else { return obj; } } catch (System.Data.SQLite.SQLiteException e) { throw new Exception(e.Message); } } } } /// <summary> /// 执行查询语句,返回SQLiteDataReader (使用该方法切记要手工关闭SQLiteDataReader和连接) /// </summary> /// <param name="strSQL">查询语句</param> /// <returns>SQLiteDataReader</returns> public static SQLiteDataReader ExecuteReader(string SQLString, params SQLiteParameter[] cmdParms) { SQLiteConnection connection = new SQLiteConnection(connectionString); SQLiteCommand cmd = new SQLiteCommand(); try { PrepareCommand(cmd, connection, null, SQLString, cmdParms); SQLiteDataReader myReader = cmd.ExecuteReader(); cmd.Parameters.Clear(); return myReader; } catch (System.Data.SQLite.SQLiteException e) { throw new Exception(e.Message); } //finally //不能在此关闭,否则,返回的对象将无法使用 //{ // cmd.Dispose(); // connection.Close(); //} } /// <summary> /// 执行查询语句,返回DataSet /// </summary> /// <param name="SQLString">查询语句</param> /// <returns>DataSet</returns> public static DataSet Query(string SQLString, params SQLiteParameter[] cmdParms) { using (SQLiteConnection connection = new SQLiteConnection(connectionString)) { SQLiteCommand cmd = new SQLiteCommand(); PrepareCommand(cmd, connection, null, SQLString, cmdParms); using (SQLiteDataAdapter da = new SQLiteDataAdapter(cmd)) { DataSet ds = new DataSet(); try { da.Fill(ds, "ds"); cmd.Parameters.Clear(); } catch (System.Data.SQLite.SQLiteException ex) { throw new Exception(ex.Message); } return ds; } } } public static void PrepareCommand(SQLiteCommand cmd, SQLiteConnection conn, SQLiteTransaction trans, string cmdText, SQLiteParameter[] cmdParms) { if (conn.State != ConnectionState.Open) conn.Open(); cmd.Connection = conn; cmd.CommandText = cmdText; if (trans != null) cmd.Transaction = trans; cmd.CommandType = CommandType.Text;//cmdType; if (cmdParms != null) { foreach (SQLiteParameter parameter in cmdParms) { if ((parameter.Direction == ParameterDirection.InputOutput || parameter.Direction == ParameterDirection.Input) && (parameter.Value == null)) { parameter.Value = DBNull.Value; } cmd.Parameters.Add(parameter); } } } #endregion #region 存储过程操作 /// <summary> /// 执行存储过程 (使用该方法切记要手工关闭SQLiteDataReader和连接) /// </summary> /// <param name="storedProcName">存储过程名</param> /// <param name="parameters">存储过程参数</param> /// <returns>SQLiteDataReader</returns> public static SQLiteDataReader RunProcedure(string storedProcName, IDataParameter[] parameters) { SQLiteConnection connection = new SQLiteConnection(connectionString); SQLiteDataReader returnReader; connection.Open(); SQLiteCommand command = BuildQueryCommand(connection, storedProcName, parameters); command.CommandType = CommandType.StoredProcedure; returnReader = command.ExecuteReader(); //Connection.Close(); 不能在此关闭,否则,返回的对象将无法使用 return returnReader; } /// <summary> /// 执行存储过程 /// </summary> /// <param name="storedProcName">存储过程名</param> /// <param name="parameters">存储过程参数</param> /// <returns>结果中第一行第一列</returns> public static string RunProc(string storedProcName, IDataParameter[] parameters) { using (SQLiteConnection connection = new SQLiteConnection(connectionString)) { string StrValue; connection.Open(); SQLiteCommand cmd; cmd = BuildQueryCommand(connection, storedProcName, parameters); StrValue = cmd.ExecuteScalar().ToString(); connection.Close(); return StrValue; } } /// <summary> /// 执行存储过程 /// </summary> /// <param name="storedProcName">存储过程名</param> /// <param name="parameters">存储过程参数</param> /// <param name="tableName">DataSet结果中的表名</param> /// <returns>DataSet</returns> public static DataSet RunProcedure(string storedProcName, IDataParameter[] parameters, string tableName) { using (SQLiteConnection connection = new SQLiteConnection(connectionString)) { DataSet dataSet = new DataSet(); connection.Open(); SQLiteDataAdapter sqlDA = new SQLiteDataAdapter(); sqlDA.SelectCommand = BuildQueryCommand(connection, storedProcName, parameters); sqlDA.Fill(dataSet, tableName); connection.Close(); return dataSet; } } public static DataSet RunProcedure(string storedProcName, IDataParameter[] parameters, string tableName, int Times) { using (SQLiteConnection connection = new SQLiteConnection(connectionString)) { DataSet dataSet = new DataSet(); connection.Open(); SQLiteDataAdapter sqlDA = new SQLiteDataAdapter(); sqlDA.SelectCommand = BuildQueryCommand(connection, storedProcName, parameters); sqlDA.SelectCommand.CommandTimeout = Times; sqlDA.Fill(dataSet, tableName); connection.Close(); return dataSet; } } /// <summary> /// 构建 SQLiteCommand 对象(用来返回一个结果集,而不是一个整数值) /// </summary> /// <param name="connection">数据库连接</param> /// <param name="storedProcName">存储过程名</param> /// <param name="parameters">存储过程参数</param> /// <returns>SQLiteCommand</returns> public static SQLiteCommand BuildQueryCommand(SQLiteConnection connection, string storedProcName, IDataParameter[] parameters) { SQLiteCommand command = new SQLiteCommand(storedProcName, connection); command.CommandType = CommandType.StoredProcedure; foreach (SQLiteParameter parameter in parameters) { if (parameter != null) { // 检查未分配值的输出参数,将其分配以DBNull.Value. if ((parameter.Direction == ParameterDirection.InputOutput || parameter.Direction == ParameterDirection.Input) && (parameter.Value == null)) { parameter.Value = DBNull.Value; } command.Parameters.Add(parameter); } } return command; } /// <summary> /// 执行存储过程,返回影响的行数 /// </summary> /// <param name="storedProcName">存储过程名</param> /// <param name="parameters">存储过程参数</param> /// <param name="rowsAffected">影响的行数</param> /// <returns></returns> public static int RunProcedure(string storedProcName, IDataParameter[] parameters, out int rowsAffected) { using (SQLiteConnection connection = new SQLiteConnection(connectionString)) { int result; connection.Open(); SQLiteCommand command = BuildIntCommand(connection, storedProcName, parameters); rowsAffected = command.ExecuteNonQuery(); result = (int)command.Parameters["ReturnValue"].Value; //Connection.Close(); return result; } } /// <summary> /// 创建 SQLiteCommand 对象实例(用来返回一个整数值) /// </summary> /// <param name="storedProcName">存储过程名</param> /// <param name="parameters">存储过程参数</param> /// <returns>SQLiteCommand 对象实例</returns> public static SQLiteCommand BuildIntCommand(SQLiteConnection connection, string storedProcName, IDataParameter[] parameters) { SQLiteCommand command = BuildQueryCommand(connection, storedProcName, parameters); command.Parameters.Add(new SQLiteParameter("ReturnValue", DbType.Int32, 4, ParameterDirection.ReturnValue, false, 0, 0, string.Empty, DataRowVersion.Default, null)); return command; } /// <summary> /// 执行SQL语句 /// </summary> /// <param name="storedProcName">存储过程名</param> /// <param name="parameters">存储过程参数</param> /// <returns>结果中第一行第一列</returns> public static string RunSql(string query) { string str; using (SQLiteConnection connection = new SQLiteConnection(connectionString)) { using (SQLiteCommand cmd = new SQLiteCommand(query, connection)) { try { connection.Open(); str = (cmd.ExecuteScalar().ToString() == "") ? "" : cmd.ExecuteScalar().ToString(); return str; } catch (System.Data.SQLite.SQLiteException E) { connection.Close(); throw new Exception(E.Message); } } } } #endregion #region 参数转换 /// <summary> /// 放回一个SQLiteParameter /// </summary> /// <param name="name">参数名字</param> /// <param name="type">参数类型</param> /// <param name="size">参数大小</param> /// <param name="value">参数值</param> /// <returns>SQLiteParameter的值</returns> public static SQLiteParameter MakeSQLiteParameter(string name, DbType type, int size, object value) { SQLiteParameter parm = new SQLiteParameter(name, type, size); parm.Value = value; return parm; } public static SQLiteParameter MakeSQLiteParameter(string name, DbType type, object value) { SQLiteParameter parm = new SQLiteParameter(name, type); parm.Value = value; return parm; } #endregion } }
import { HttpClient, HttpErrorResponse } from '@angular/common/http'; import { Injectable } from '@angular/core'; import { catchError, Observable, tap, throwError } from 'rxjs'; import { IPet } from '../pet/pet'; import { IOwner } from './owner'; @Injectable({ providedIn: 'root', }) export class OwnerService { private ownerUrl = 'http://localhost:8080/owner'; constructor(private http: HttpClient) {} findAll(): Observable<IOwner[]> { return this.http.get<IOwner[]>(this.ownerUrl + '/findAll').pipe( tap((data) => console.log('All', JSON.stringify(data))), catchError(this.handleError) ); } findById(id: number): Observable<IOwner> { return this.http.get<IOwner>(this.ownerUrl + `/findById/${id}`).pipe( tap((data) => console.log('All', JSON.stringify(data))), catchError(this.handleError) ); } addOwner(newOwner: IOwner): Observable<IOwner> { return this.http.post<IOwner>(this.ownerUrl + '/add', newOwner).pipe( tap((data) => console.log('All', JSON.stringify(data))), catchError(this.handleError) ); } findPetByOwnerId(id: number): Observable<IPet[]> { return this.http .get<IPet[]>(this.ownerUrl + `/findPetByOwnerId/${id}`) .pipe( tap((data) => console.log('All', JSON.stringify(data))), catchError(this.handleError) ); } findByPetId(id: number): Observable<IOwner> { return this.http.get<IOwner>(this.ownerUrl + `/findByPetId/${id}`).pipe( tap((data) => console.log('All', JSON.stringify(data))), catchError(this.handleError) ); } findByPetName(name: string): Observable<IOwner[]> { return this.http .get<IOwner[]>(this.ownerUrl + `/findByPetName?name=${name}`) .pipe( tap((data) => console.log('All', JSON.stringify(data))), catchError(this.handleError) ); } findByDateCreated(dateCreated: string): Observable<IOwner[]> { return this.http .get<IOwner[]>( this.ownerUrl + `/findByDateCreated?dateCreated=${dateCreated}` ) .pipe( tap((data) => console.log('All', JSON.stringify(data))), catchError(this.handleError) ); } createOrUpdateRelation(ownerID : number, pet: IPet) { return this.http.put<IPet>(this.ownerUrl + `/updateRelation/${ownerID}`, pet).pipe( tap((data) => console.log('All', JSON.stringify(data))), catchError(this.handleError) ) } private handleError(err: HttpErrorResponse) { let errorMessage = ''; if (err.error instanceof ErrorEvent) { errorMessage = `An error occurred: ${err.message}`; } else { errorMessage = `Server returned code: ${err.status}, error message is: ${err.message}`; } console.log(errorMessage); return throwError(() => err.error.message); } }
/** * @file w2h_queue.h * @author gotaly * @data 2012-08-14 * @email [email protected] * Queue for w2h. * API of Queue for w2h */ #ifndef W2H_QUEUE_H #define W2H_QUEUE_H #include "inc.h" /** * struct of queue. */ struct w2h_queue_s{ size_t head; size_t tail; size_t size; size_t used; char *mem; }; typedef struct w2h_queue_s w2h_queue_t; /** * use memory mem which has size bytes memory to creat a queue. * @param mem: memory for queue * @param size: size of queue * @return a w2h_queue_t *queue */ extern w2h_queue_t *w2h_queue_create(char *mem,size_t size); /** * enqueue a item data with len length into queue. * @param queue : queue to be enqueue * @param data : data to enqueue * @param len : length of data * @return 0 on sucess ,-1 on failed */ extern int w2h_queue_enqueue(w2h_queue_t *queue,void *data,size_t len); /** * dequeue a item from queue to address **data and store item's length into *len. * at first ,*len is length of *data,if it is smaller than the length of which to * be dequeue,*data will be expanded and *len will be changed togethor. * @param queue:queue to be dequeue * @param len :len of *data * @param data : dequeued item will be store in *data * @return 0 on sucess ,-1 on failed */ extern int w2h_queue_dequeue(w2h_queue_t *queue,void **data,size_t *len); /** * if queue is empty return true(1) or return 0 */ extern int w2h_queue_empty(w2h_queue_t *queue); /** * if queue is full return true(1) or return 0 */ extern int w2h_queue_full(w2h_queue_t *queue); #endif
package repository import ( "bytes" "errors" "fmt" "log" "time" "github.com/jmoiron/sqlx" "github.com/vamika-digital/wms-api-server/core/business/master/domain" "github.com/vamika-digital/wms-api-server/core/business/master/dto/outwardrequest" "github.com/vamika-digital/wms-api-server/core/business/master/reports" "github.com/vamika-digital/wms-api-server/global/drivers" ) type SQLOutwardRequestRepository struct { DB *sqlx.DB } func NewSQLOutwardRequestRepository(conn drivers.Connection) (OutwardRequestRepository, error) { db := conn.GetDB() if db == nil { return nil, errors.New("failed to get database connection") } return &SQLOutwardRequestRepository{DB: conn.GetDB()}, nil } func (r *SQLOutwardRequestRepository) getFilterQueryWithArgs(page int, pageSize int, sort string, filter *outwardrequest.OutwardRequestFilterDto) (string, map[string]interface{}) { var queryBuffer bytes.Buffer args := make(map[string]interface{}) if filter.Query != "" { queryBuffer.WriteString(" AND (order_no LIKE :query)") args["query"] = "%" + filter.Query + "%" } if filter.ID != 0 { queryBuffer.WriteString(" AND id = :id") args["id"] = filter.ID } if filter.OrderNo != "" { queryBuffer.WriteString(" AND order_no=:order_no") args["order_no"] = filter.OrderNo } if filter.Status.IsValid() { queryBuffer.WriteString(" AND status = :status") args["status"] = filter.Status } if filter.Customer != nil && filter.Customer.ID > 0 { queryBuffer.WriteString(" AND customer_id = :customer_id") args["customer_id"] = filter.Customer.ID } if sort != "" { queryBuffer.WriteString(fmt.Sprintf(" ORDER BY %s", sort)) } if page > 0 { queryBuffer.WriteString(" LIMIT :start, :end") args["start"] = (page - 1) * pageSize args["end"] = pageSize } return queryBuffer.String(), args } func (r *SQLOutwardRequestRepository) GetTotalCount(filter *outwardrequest.OutwardRequestFilterDto) (int, error) { var count int var queryBuffer bytes.Buffer queryBuffer.WriteString("SELECT COUNT(*) FROM outwardrequests WHERE deleted_at IS NULL") filterQuery, args := r.getFilterQueryWithArgs(0, 0, "", filter) queryBuffer.WriteString(filterQuery) query := queryBuffer.String() namedQuery, err := r.DB.PrepareNamed(query) if err != nil { log.Printf("%+v\n", err) return 0, err } err = namedQuery.Get(&count, args) if err != nil { log.Printf("%+v\n", err) return 0, err } return count, nil } func (r *SQLOutwardRequestRepository) GetAll(page int, pageSize int, sort string, filter *outwardrequest.OutwardRequestFilterDto) ([]*domain.OutwardRequest, error) { outwardrequests := make([]*domain.OutwardRequest, 0) var queryBuffer bytes.Buffer queryBuffer.WriteString("SELECT * FROM outwardrequests WHERE deleted_at IS NULL") filterQuery, args := r.getFilterQueryWithArgs(page, pageSize, sort, filter) queryBuffer.WriteString(filterQuery) query := queryBuffer.String() namedQuery, err := r.DB.PrepareNamed(query) if err != nil { log.Printf("%+v\n", err) return nil, err } err = namedQuery.Select(&outwardrequests, args) if err != nil { log.Printf("%+v\n", err) return nil, err } return outwardrequests, nil } func (r *SQLOutwardRequestRepository) Create(outwardrequest *domain.OutwardRequest) error { var count int err := r.DB.Get(&count, "SELECT COUNT(*) FROM outwardrequests WHERE order_no = ?", outwardrequest.OrderNo) if err != nil { log.Printf("%+v\n", err) return err } if count > 0 { return fmt.Errorf("a outwardrequest with the order number %s already exists", outwardrequest.OrderNo) } tx, err := r.DB.Beginx() if err != nil { log.Printf("%+v\n", err) return err } query := `INSERT INTO outwardrequests (issued_date, order_no, customer_id, status, last_updated_by) VALUES(:issued_date, :order_no, :customer_id, :status, :last_updated_by)` res, err := tx.NamedExec(query, outwardrequest) if err != nil { log.Printf("%+v\n", err) _ = tx.Rollback() return err } id, err := res.LastInsertId() if err != nil { log.Printf("%+v\n", err) _ = tx.Rollback() return err } outwardrequest.ID = id for _, item := range outwardrequest.Items { item.OutwardRequestID = outwardrequest.ID query = "INSERT INTO outwardrequest_items (outwardrequest_id, product_id, quantity) VALUES(:outwardrequest_id, :product_id, :quantity)" if _, err := tx.NamedExec(query, item); err != nil { _ = tx.Rollback() return err } } return tx.Commit() } func (r *SQLOutwardRequestRepository) GetById(outwardrequestID int64) (*domain.OutwardRequest, error) { outwardrequest := &domain.OutwardRequest{} err := r.DB.Get(outwardrequest, "SELECT * FROM outwardrequests WHERE id = ? AND deleted_at IS NULL", outwardrequestID) return outwardrequest, err } func (r *SQLOutwardRequestRepository) GetByOrderNo(outwardrequestNumber string) (*domain.OutwardRequest, error) { outwardrequest := &domain.OutwardRequest{} err := r.DB.Get(outwardrequest, "SELECT * FROM outwardrequests WHERE order_no = ? AND deleted_at IS NULL", outwardrequestNumber) return outwardrequest, err } func (r *SQLOutwardRequestRepository) Update(outwardrequest *domain.OutwardRequest) error { var count int err := r.DB.Get(&count, "SELECT COUNT(*) FROM outwardrequests WHERE order_no = ? AND id != ?", outwardrequest.OrderNo, outwardrequest.ID) if err != nil { log.Printf("%+v\n", err) return err } if count > 0 { return fmt.Errorf("a outwardrequest with the order number %s already exists", outwardrequest.OrderNo) } tx, err := r.DB.Beginx() if err != nil { log.Printf("%+v\n", err) return err } query := "UPDATE outwardrequests SET issued_date=:issued_date, order_no=:order_no, customer_id=:customer_id, last_updated_by=:last_updated_by WHERE id=:id" _, err = tx.NamedExec(query, outwardrequest) if err != nil { log.Printf("%+v\n", err) tx.Rollback() return err } query = "DELETE FROM outwardrequest_items WHERE outwardrequest_id=?" _, err = tx.Exec(query, outwardrequest.ID) if err != nil { log.Printf("%+v\n", err) tx.Rollback() return err } for _, item := range outwardrequest.Items { item.OutwardRequestID = outwardrequest.ID query = "INSERT INTO outwardrequest_items (outwardrequest_id, product_id, quantity) VALUES(:outwardrequest_id, :product_id, :quantity)" if _, err := tx.NamedExec(query, item); err != nil { _ = tx.Rollback() return err } } return tx.Commit() } func (r *SQLOutwardRequestRepository) Delete(outwardrequestID int64) error { _, err := r.DB.Exec("UPDATE outwardrequests SET deleted_at = NOW() WHERE id = ?", outwardrequestID) return err } func (r *SQLOutwardRequestRepository) DeleteByIDs(outwardrequestIDs []int64) error { if len(outwardrequestIDs) == 0 { return nil } query := "UPDATE outwardrequests SET deleted_at = NOW() WHERE id IN (?)" query, args, err := sqlx.In(query, outwardrequestIDs) if err != nil { log.Printf("%+v\n", err) return err } query = r.DB.Rebind(query) _, err = r.DB.Exec(query, args...) return err } func (r *SQLOutwardRequestRepository) GetItemsForOutwardRequests(orderIDs []int64) (map[int64][]*domain.OutwardRequestItem, error) { itemsMap := make(map[int64][]*domain.OutwardRequestItem) query := `SELECT * FROM outwardrequest_items WHERE outwardrequest_id IN (?)` query, args, err := sqlx.In(query, orderIDs) if err != nil { log.Printf("%+v\n", err) return nil, err } query = r.DB.Rebind(query) var items []*domain.OutwardRequestItem if err := r.DB.Select(&items, query, args...); err != nil { log.Printf("%+v\n", err) return nil, err } for _, item := range items { itemsMap[item.OutwardRequestID] = append(itemsMap[item.OutwardRequestID], item) } return itemsMap, nil } func (r *SQLOutwardRequestRepository) GetItemsForOutwardRequest(orderID int64) ([]*domain.OutwardRequestItem, error) { var outwardrequestItems []*domain.OutwardRequestItem query := "SELECT * FROM outwardrequest_items WHERE outwardrequest_id=:outwardrequest_id" args := map[string]interface{}{ "outwardrequest_id": orderID, } namedQuery, err := r.DB.PrepareNamed(query) if err != nil { log.Printf("%+v\n", err) return nil, err } err = namedQuery.Select(&outwardrequestItems, args) if err != nil { log.Printf("%+v\n", err) return nil, err } return outwardrequestItems, nil } func (r *SQLOutwardRequestRepository) GetShipperLabels(requestID int64, requestName string) ([]*reports.OutwardRequestShipperReport, error) { var shipperReports []*reports.OutwardRequestShipperReport query := "SELECT report.*, p.code as product_code, p.name as product_name, s.shipper_number as shipper_number, s.packed_at as shipper_packed_at FROM ( SELECT request_id, request_name, batch_no, product_id, shipperlabel_id as shipper_id, count(*) as package_count from wms.stocks where request_id = :request_id AND request_name = :request_name AND status = 'STOCK-OUT' group by request_id, request_name, batch_no, product_id, shipperlabel_id) as report LEFT JOIN products p ON report.product_id = p.id LEFT JOIN shipperlabels s ON report.shipper_id = s.id" args := map[string]interface{}{ "request_id": requestID, "request_name": requestName, } namedQuery, err := r.DB.PrepareNamed(query) if err != nil { log.Printf("%+v\n", err) return nil, err } err = namedQuery.Select(&shipperReports, args) if err != nil { log.Printf("%+v\n", err) return nil, err } return shipperReports, nil } func (r *SQLOutwardRequestRepository) GenerateShipperLabels(shipperLabelForm *domain.ShipperLabel, batchNo string, productID int64) error { var shipperReports []*reports.OutwardRequestShipperReport var shippers []*domain.ShipperLabel query := "SELECT * from shipperlabels s WHERE s.outwardrequest_id = :outwardrequest_id AND batch_no = :batch_no ORDER BY created_at desc" args := map[string]interface{}{ "outwardrequest_id": shipperLabelForm.OutwardRequestID, "batch_no": batchNo, } namedQuery, err := r.DB.PrepareNamed(query) if err != nil { log.Printf("%+v\n", err) return err } err = namedQuery.Select(&shippers, args) if err != nil { log.Printf("%+v\n", err) return err } query = "SELECT report.*, p.name as product_name, p.code as product_code, s.shipper_number as shipper_number, s.packed_at as shipper_packed_at FROM ( SELECT request_id, request_name, batch_no, product_id, shipperlabel_id as shipper_id, count(*) as package_count from wms.stocks where request_id=:request_id AND request_name=:request_name AND batch_no=:batch_no AND product_id=:product_id AND status = 'STOCK-OUT' AND shipperlabel_id IS NULL group by request_id, request_name, batch_no, product_id, shipperlabel_id) as report LEFT JOIN products p ON report.product_id = p.id LEFT JOIN shipperlabels s ON report.shipper_id = s.id" args = map[string]interface{}{ "request_id": shipperLabelForm.OutwardRequestID, "request_name": "*domain.OutwardRequest", "batch_no": batchNo, "product_id": productID, } namedQuery, err = r.DB.PrepareNamed(query) if err != nil { log.Printf("%+v\n", err) return err } err = namedQuery.Select(&shipperReports, args) if err != nil { log.Printf("%+v\n", err) return err } if len(shipperReports) <= 0 { return fmt.Errorf("no data found with the given request") } if len(shipperReports) > 1 { return fmt.Errorf("somthing wrong with the given request") } shipperCount := len(shippers) shipperReport := shipperReports[0] shipperLabelForm.PackedAt = time.Now() shipperLabelForm.ShipperNumber = fmt.Sprintf("%s%s%d", shipperReport.BatchNo, "00", shipperCount+1) shipperLabelForm.ProductCode = shipperReport.ProductCode shipperLabelForm.ProductName = shipperReport.ProductName shipperLabelForm.BatchNo = shipperReport.BatchNo shipperLabelForm.PackedQty = fmt.Sprintf("%dNos", shipperReport.PackageCount) tx, err := r.DB.Beginx() if err != nil { log.Printf("%+v\n", err) return err } query = `INSERT INTO shipperlabels ( shipper_number, customer_name, product_code, product_name, batch_no, packed_qty, packed_at, outwardrequest_id ) VALUES(:shipper_number, :customer_name, :product_code, :product_name, :batch_no, :packed_qty, :packed_at, :outwardrequest_id)` res, err := tx.NamedExec(query, shipperLabelForm) if err != nil { log.Printf("%+v\n", err) _ = tx.Rollback() return err } id, err := res.LastInsertId() if err != nil { log.Printf("%+v\n", err) _ = tx.Rollback() return err } shipperLabelForm.ID = id err = tx.Commit() if err != nil { log.Printf("%+v\n", err) _ = tx.Rollback() return err } tx, err = r.DB.Beginx() if err != nil { log.Printf("%+v\n", err) return err } _, err = r.DB.Exec("UPDATE stocks SET shipperlabel_id = ? WHERE request_id = ? AND request_name = ? AND batch_no = ? AND product_id = ? AND shipperlabel_id IS NULL", shipperLabelForm.ID, shipperLabelForm.OutwardRequestID, "*domain.OutwardRequest", shipperLabelForm.BatchNo, productID) if err != nil { log.Printf("%+v\n", err) _ = tx.Rollback() return err } return tx.Commit() }
<?php use Illuminate\Support\Facades\Route; use App\Http\Controllers\CasillaController; use App\Http\Controllers\CandidatoController; use App\Http\Controllers\EleccionController; use App\Http\Controllers\VotoController; use App\Http\Controllers\pdfController; use App\Http\Controllers\Auth\LoginController; /* |-------------------------------------------------------------------------- | Web Routes |-------------------------------------------------------------------------- | | Here is where you can register web routes for your application. These | routes are loaded by the RouteServiceProvider within a group which | contains the "web" middleware group. Now create something great! | */ Route::get('/', function () { return view('welcome'); }); Route::get('casilla/pdf', [CasillaController::class, 'generatepdf']); Route::resource("casilla",CasillaController::class); Route::resource("candidato", CandidatoController::class); Route::resource("eleccion", EleccionController::class); Route::resource("voto", VotoController::class); Route::get('preview', [pdfController::class, 'preview']); Route::get('download', [pdfController::class, 'download'])->name('download'); Route::get('/login','App\Http\Controllers\Auth\LoginController@index'); Route::get('/login/facebook', 'App\Http\Controllers\Auth\LoginController@redirectToFacebookProvider'); Route::get('/login/facebook/callback', 'App\Http\Controllers\Auth\LoginController@handleProviderFacebookCallback'); Route::middleware(['auth'])->group (function () { });
package br.com.fiap.IaFuture.model; import java.time.LocalDate; import com.fasterxml.jackson.annotation.JsonFormat; import jakarta.persistence.Column; import jakarta.persistence.Entity; import jakarta.persistence.GeneratedValue; import jakarta.persistence.GenerationType; import jakarta.persistence.Id; import jakarta.persistence.JoinColumn; import jakarta.persistence.ManyToOne; import jakarta.validation.constraints.Pattern; import lombok.Data; @Entity @Data public class InteracaoCliente { @Id @GeneratedValue(strategy = GenerationType.AUTO) private Long id_interacao; @JsonFormat(pattern = "dd/MM/yyyy") private LocalDate data_interacao; @Column(length = 20) @Pattern( regexp = "^(visita_site|interacao_social|compra_site|envio_email|clique_anuncio)$", message = "Tipo deve ser visita_site, interacao_social, compra_site, envio_email, clique_anuncio" ) private String tipo; @Column(length = 20) @Pattern( regexp = "^(facebook|instagram|twitter|site|email)$", message = "Canal deve ser facebook, instagram, twitter, site, email" ) private String canal; @ManyToOne @JoinColumn(name = "id_cliente") private Cliente cliente; }
package com.stockmarket.core_d.events; import com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBAttribute; import com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBDocument; import com.stockmarket.core_d.enums.Events; import lombok.Getter; import lombok.NoArgsConstructor; import lombok.Setter; @Getter @Setter @NoArgsConstructor @DynamoDBDocument public class StockPriceAddedEvent extends DomainEvent { @DynamoDBAttribute private String companyCode; @DynamoDBAttribute private Double stockPrice; public StockPriceAddedEvent(String aggregateId, String aggregateType, String companyCode, Double stockPrice) { super(aggregateId, aggregateType, Events.STOCK_PRICE_ADDED_EVENT.getValue()); this.companyCode = companyCode; this.stockPrice = stockPrice; } }
import "./RecentProductCard.css" import {useNavigate} from 'react-router-dom' import {Rating} from '@mui/material' import {useState} from 'react' function RecentProductCard({id, name, price, brand, image, initialRating}) { const [rating, setRating] = useState(initialRating) const navigate = useNavigate(); const handleClick = () => { navigate(`/product/${id}`) } return ( <div className="container"> <div className="card" onClick={handleClick}> <div className="image-container"> <img src={image}/> </div> <h3 className="name">{name}</h3> <p className="brand">{brand}</p> <p className="price">${price}</p> </div> <Rating className="rating" name="simple-controlled" value={rating || 0} onChange={async (event, newValue) => { setRating(newValue); await fetch(`http://localhost:4000/api/products/${id}`, { method: 'put', headers: {'Content-Type': 'application/json'}, body: JSON.stringify({ rating: newValue }) }) }} /> </div> ) } export default RecentProductCard;
#ifndef STUDIO_H_ #define STUDIO_H_ #include <vector> #include <string> #include "workout.h" #include "trainer.h" #include "action.h" class Studio { public: Studio(); explicit Studio(const std::string &configFilePath); Studio(const Studio &other); Studio(Studio &&other); void start(); int getNumOfTrainers() const; std::vector<Trainer *> getTrainers(); Trainer *getTrainer(int tid); int getTraineesAvailableId(); void increaseAvailableId(); void decreaseAvailableId(); virtual ~Studio(); virtual Studio &operator=(const Studio &other); virtual Studio &operator=(Studio &&other); const std::vector<BaseAction *> &getActionsLog() const; // Return a reference to the history of actions std::vector<Workout> &getWorkoutOptions(); void setClose(); void clear(); void clearPointers(); private: bool open; std::vector<Trainer *> trainers; std::vector<Workout> workout_options; std::vector<BaseAction *> actionsLog; int traineesAvailableId = 0; }; std::tuple<std::vector<Trainer *> *, std::vector<Workout> *> parseConfigFile(const std::string &configFilePath); std::vector<std::string> *splitByDelimiter(std::string &s, std::string delimiter); #endif
import { useEffect, useState } from "react"; interface EnumSelectorProps { values: { value: string; label: string }[]; selected: string; setSelected?: (ret: string) => void; style?: React.CSSProperties; className?: string; } export const Select = ({ values, selected, setSelected, style, className, }: EnumSelectorProps): JSX.Element => { const [currentValue, setCurrentValue] = useState<string>(selected); useEffect(() => setCurrentValue(selected), [selected]); return ( <div className={`selector-main ${className}`} style={{ display: "flex", flexDirection: "column", justifyContent: "center", }} > <select className="selector-select" style={{ borderRadius: "4px", ...style }} value={currentValue} onChange={(e) => setSelected && setSelected(e.currentTarget.value)} > {values.map((k, i) => ( <option key={`${i}-${k.value}`} value={k.value} > {k.label} </option> ))} </select> </div> ); };
package org.example.windows; import org.example.Request; import org.example.Student; import redis.clients.jedis.Jedis; import redis.clients.jedis.JedisPool; import javax.swing.*; import java.awt.*; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import static org.example.windows.StartWindow.jedisPool; public class StudentWindow extends MedicalFrame { private Student student; JTextField medicalRequestField; JButton submitRequestButton; public StudentWindow(Student student) { this.student = student; setTitle("Студент: " + student.getName() + " " + student.getSurname()); setLayout(new GridBagLayout()); GridBagConstraints constraints = new GridBagConstraints(); constraints.fill = GridBagConstraints.HORIZONTAL; constraints.insets = new Insets(20, 20, 20, 20); Font labelFont = new Font("Arial", Font.BOLD, 16); Font buttonFont = new Font("Arial", Font.PLAIN, 16); JLabel nameLabel = new JLabel("Ім'я: " + student.getName() + " " + student.getSurname()); nameLabel.setFont(labelFont); JLabel healthStatus = new JLabel("Стан: " + (student.isIll() ? "Хворий" : "Здоровий")); healthStatus.setFont(labelFont); JLabel imageLabel = new JLabel(); if (student.isIll()) { ImageIcon imageIcon = new ImageIcon(new ImageIcon("src/main/resources/ill.png").getImage().getScaledInstance(70, 70, Image.SCALE_DEFAULT)); imageLabel = new JLabel(imageIcon); imageLabel.setHorizontalAlignment(JLabel.CENTER); } else { ImageIcon imageIcon = new ImageIcon(new ImageIcon("src/main/resources/healthy.png").getImage().getScaledInstance(70, 70, Image.SCALE_DEFAULT)); imageLabel = new JLabel(imageIcon); imageLabel.setHorizontalAlignment(JLabel.CENTER); } ImageIcon imageIcon = new ImageIcon(new ImageIcon("src/main/resources/edit.jpeg").getImage().getScaledInstance(35, 25, Image.SCALE_DEFAULT)); JButton editButton = new JButton(imageIcon); editButton.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { dispose(); new UpdateWindow(student).setVisible(true); } }); constraints.gridx = 2; constraints.gridy = 0; constraints.anchor = GridBagConstraints.NORTHEAST; add(editButton, constraints); medicalRequestField = new JTextField(20); medicalRequestField.setFont(labelFont); submitRequestButton = new JButton("Відправити запит"); submitRequestButton.setFont(buttonFont); constraints.gridx = 0; constraints.gridy = 0; constraints.gridwidth = 2; constraints.anchor = GridBagConstraints.CENTER; add(nameLabel, constraints); constraints.gridx = 0; constraints.gridy = 1; add(healthStatus, constraints); constraints.gridx = 0; constraints.gridy = 2; add(imageLabel, constraints); constraints.gridx = 0; constraints.gridy = 3; add(medicalRequestField, constraints); constraints.gridx = 0; constraints.gridy = 4; add(submitRequestButton, constraints); submitRequestButton.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { try (Jedis jedis = jedisPool.getResource()) { String medicalRequest = medicalRequestField.getText(); Request newRequest = new Request(student.getStudentID(), medicalRequest, false); jedis.set("request:" + student.getStudentID(), newRequest.toJson()); JOptionPane.showMessageDialog(null, "Запит відправлено!"); } } }); setLocationRelativeTo(null); } }
// Copyright 2014 Thomas E. Vaughan // // This file is part of Ulam. // // Ulam is free software: You can redistribute it and/or modify it under the // terms of the GNU General Public License as published by the Free Software // Foundation, either Version 3 of the License, or (at your option) any later // version. // // Ulam 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 // Ulam. If not, see <http://www.gnu.org/licenses/>. #include <cstdio> // for printf() #include <cstdlib> // for exit() #include <iostream> // for cerr #include "Natural.hpp" using namespace std; vector< Factors > Natural::mFactors; Natural::Natural(unsigned nn) : mOffset(nn - 1) { if (nn == 0) { cerr << "Natural::Natural: Zero is not a natural number." << endl; exit(-1); } if (nn > mFactors.size() || (nn > 1 && mFactors[mOffset].size() == 0)) { cerr << "Natural::Natural: " << nn << " not initialized" << endl; exit(-1); } } /// Unsigned multiple of an unsigned base value. The base is fixed at /// construction, but the factor can be modified. class Multiple { unsigned mBase; ///< Base value. unsigned mMult; ///< Multiple (base*factor). unsigned mFact; ///< Factor. public: /// \param bb Base value. /// \param ff Factor. Multiple(unsigned bb = 0, unsigned ff = 1) : mBase(bb), mMult(bb * ff), mFact(ff) { } unsigned base() const { return mBase; } ///< \return Base value. unsigned mult() const { return mMult; } ///< \return Multiple (base*fact). unsigned fact() const { return mFact; } ///< \return Factor. /// Set factor. /// \param ff New value for factor. void fact(unsigned ff) { mFact = ff; mMult = mBase * ff; } void incFact() { mMult = mBase * (++mFact); } ///< Increment factor. }; void Natural::init(unsigned max) { if (max == 0) { cerr << "Natural::init: ERROR: Maximum must be positive." << endl; exit(-1); } mFactors.clear(); mFactors.resize(max); if (max == 1) return; vector< Multiple > primes; for (unsigned current = 2; current <= max; ++current) { vector<Factor>& factors = mFactors[current - 1]; if (factors.size() == 0) { // The current number is prime because its factorization is null. primes.push_back(current); factors.push_back(current); } for (unsigned ii = 0; ii < primes.size(); ++ii) { Multiple& prime = primes[ii]; if (prime.mult() <= current && prime.mult() + prime.base() <= max) { prime.incFact(); unsigned const base = prime.base(); unsigned const fact = prime.fact(); Factors const& fA = Natural(base).factors(); Factors const& fB = Natural(fact).factors(); mFactors[base * fact - 1] = fA * fB; } } if (factors.size() == 0) { cerr << "Natural::init: ERROR: no factors for " << current << endl; exit(1); } } }
import { QuestionType } from '@/modules/questions/types'; import React, { useEffect, useState } from 'react'; import { Form, Input, Select, Button } from 'antd'; import { ChapterType, SubjectType } from '@/modules/subjects/types'; import CKEditorInput from '@/components/ckeditor/input'; import { getChapters, getSubjects } from '@/modules/subjects/services'; import { postQuestion, putQuestion } from '@/modules/questions/services'; import toast from 'react-hot-toast'; type Props = { question?: QuestionType; setQuestion?: (question: QuestionType) => void, questions: QuestionType[], setQuestions: (questions: QuestionType[]) => void, setOpen: (state: boolean) => void, update?: boolean; propSubjectId?: number | null; chapterId?: number | null; selectedQuestions?: QuestionType[], fetch?: (page: number) => void; page?: number; setSelectedQuestions?: (questions: QuestionType[]) => void, }; const { TextArea } = Input; const { Option } = Select; const QuestionForm: React.FC<Props> = ({ question, setQuestion, questions, setQuestions, fetch, page, setOpen, update, selectedQuestions, setSelectedQuestions, propSubjectId, chapterId }) => { const [form] = Form.useForm(); const [grade, setGrade] = useState(question ? question.grade : 0); const [subjectId, setSubjectId] = useState((question && question.subject_id) ? question.subject_id : 0); const [subjects, setSubjects] = useState<SubjectType[]>([]); const [chapters, setChapters] = useState<ChapterType[]>([]); useEffect(() => { if (grade != 0) { getSubject(grade); if (subjectId != 0) { getChapter(subjectId); } } }, []) const getSubject = (grade: number) => { getSubjects({ grade: grade, perPage: 100 }).then((res) => { setSubjects(res.data[0].data); }) } const getChapter = (subjectId: number) => { getChapters({ subject_id: subjectId, perPage: 100 }).then((res) => { setChapters(res.data[0].data); }) } useEffect(() => { if (question) { form.setFieldsValue({ question: question.question, answer_1: question.answer_1, answer_2: question.answer_2, answer_3: question.answer_3, answer_4: question.answer_4, answer_correct: question.answer_correct.toString(), answer_detail: question.answer_detail, subject_id: question.subject_id?.toString(), grade: question.grade.toString(), chapter_id: question.chapter_id?.toString(), level: question.level.toString(), }); } else { form.resetFields(); } }, [question, form]); const onFinish = (values: QuestionType) => { console.log('Form values: ', values); if (update && question) { const updatedQuestion: QuestionType = { ...question!, ...values, answer_correct: parseInt(values.answer_correct.toString()), subject_id: values.subject_id ? parseInt(values.subject_id.toString()) : null, grade: parseInt(values.grade.toString()), chapter_id: values.chapter_id ? parseInt(values.chapter_id.toString()) : null, level: parseInt(values.level.toString()), }; setQuestion && setQuestion(updatedQuestion); console.log(updatedQuestion); putQuestion(question?.id, updatedQuestion).then((res) => { if (res.status && res.status.success) { setOpen(false); if (fetch && page) { fetch(page); } toast.success("Chỉnh sửa câu hỏi thành công.") } }) return; } else { postQuestion(values).then((res) => { if (res.status && res.status.success) { form.resetFields(); setOpen(false); setQuestions([res.data[0], ...questions]); if (selectedQuestions && setSelectedQuestions != undefined) { setSelectedQuestions([...selectedQuestions, res.data[0]]); } toast.success('Thêm câu hỏi thành công.') } }) } }; const handleChangeGrade = (e: any) => { console.log(e); setGrade(e); getSubject(e); } const handleChangeSubject = (e: any) => { console.log(e); setSubjectId(e) getChapter(e) } return ( <Form form={form} layout="vertical" onFinish={onFinish} > <Form.Item label="Nội dung câu hỏi" name="question" rules={[{ required: true, message: 'Vui lòng nhập câu hỏi' }]} > <CKEditorInput initialValue={question ? question.question : ''} onChange={(data: string) => form.setFieldValue('content', data)} placeholder='Nhập nội dung' /> </Form.Item> <Form.Item label="Đáp án 1" name="answer_1" rules={[{ required: true, message: 'Vui lòng nhập đáp án 1' }]} > <CKEditorInput initialValue={question ? question.answer_1 : ''} onChange={(data: string) => form.setFieldValue('content', data)} placeholder='Nhập nội dung' /> </Form.Item> <Form.Item label="Đáp án 2" name="answer_2" rules={[{ required: true, message: 'Vui lòng nhập đáp án 2' }]} > <CKEditorInput initialValue={question ? question.answer_2 : ''} onChange={(data: string) => form.setFieldValue('content', data)} placeholder='Nhập nội dung' /> </Form.Item> <Form.Item label="Đáp án 3" name="answer_3" rules={[{ required: true, message: 'Vui lòng nhập đáp án 3' }]} > <CKEditorInput initialValue={question ? question.answer_3 : ''} onChange={(data: string) => form.setFieldValue('content', data)} placeholder='Nhập nội dung' /> </Form.Item> <Form.Item label="Đáp án 4" name="answer_4" rules={[{ required: true, message: 'Vui lòng nhập đáp án 4' }]} > <CKEditorInput initialValue={question ? question.answer_4 : ''} onChange={(data: string) => form.setFieldValue('content', data)} placeholder='Nhập nội dung' /> </Form.Item> <Form.Item label="Đáp án đúng" name="answer_correct" rules={[{ required: true, message: 'Vui lòng chọn đáp án đúng cho câu hỏi' }]} > <Select placeholder={'Chọn đáp án đúng'}> <Option value="1">Đáp án 1</Option> <Option value="2">Đáp án 2</Option> <Option value="3">Đáp án 3</Option> <Option value="4">Đáp án 4</Option> </Select> </Form.Item> <Form.Item label="Giải thích" name="answer_detail"> <CKEditorInput initialValue={question ? question.answer_detail : ''} onChange={(data: string) => form.setFieldValue('content', data)} placeholder='Nhập nội dung' /> </Form.Item> { (propSubjectId && chapterId) ? (<></>) : (<><Form.Item label="Khối lớp" name="grade" rules={[{ required: true, message: 'Vui lòng chọn khối lớp' }]}> <Select placeholder='Chọn khối lớp' onChange={handleChangeGrade}> <Option value="10">10</Option> <Option value="11">11</Option> <Option value="12">12</Option> <Option value="13">Kiến thức tổng hợp</Option> </Select> </Form.Item> { grade != 0 ? <Form.Item label="Môn học" name="subject_id" rules={[{ required: true, message: 'Vui lòng chọn môn học' }]}> <Select placeholder='Chọn môn học' onChange={handleChangeSubject}> { subjects && subjects.map((subject) => ( <> <Option value={subject.id} key={subject.id}>{subject.name}</Option> </> )) } </Select> </Form.Item> : '' } { subjectId != 0 ? <Form.Item label="Chương" name="chapter_id"> <Select placeholder='Chọn chương'> { chapters && chapters.map((chapter) => ( <> <Option value={chapter.id} key={chapter.id}>{chapter.name}</Option> </> )) } </Select> </Form.Item> : '' }</>) } <Form.Item label="Độ khó" name="level" rules={[{ required: true, message: 'Vui lòng chọn mức độ câu hỏi' }]}> <Select placeholder={'Chọn độ khó câu hỏi'}> <Option value="1">Dễ</Option> <Option value="2">Cơ bản</Option> <Option value="3">Bình thường</Option> <Option value="4">Khó</Option> <Option value="5">Nâng cao</Option> </Select> </Form.Item> <Form.Item> <Button type="primary" htmlType="submit"> Lưu lại </Button> </Form.Item> </Form> ); }; export default QuestionForm;
# Transform Load functions: # en for loop som, för varje fil i pokebelt # öppnar json filen, # läser ut base happiness # sparar / appendar base happiness datan till en csv fil som sparas i pokedata/observations/observation_YY-MM-dd-HH-mm.csv # ett bash kommando ska sedan deleta alla json-filerna, så att mappen är tom till nästa körning import csv import os import datetime import csv import json base_dir = os.path.dirname(os.path.abspath(__file__)) path_to_pokemons = os.path.join(base_dir, '../pokedata/pokebelt') path_to_observations = os.path.join(base_dir, '../pokedata/observations') def create_pokemon_list(): """Creates a list containing all file names in the pokebelt directory (.json files).""" pokemon_list = os.listdir(path_to_pokemons) print(f"Pokemon_list: {pokemon_list}") return pokemon_list def transform_load(list_of_pokemon_jsons): pokemons_list_of_dicts = [] field_names = ['name', 'base_happiness'] timestamp = datetime.datetime.now().strftime("%Y-%m-%d_%H-%M-%S") for pokemon in list_of_pokemon_jsons: with open(f'{path_to_pokemons}/{pokemon}', 'r') as file: pokef = json.load(file) dict = {'name': pokef['name'] , 'base_happiness': pokef['base_happiness']} pokemons_list_of_dicts.append(dict) with open(f'{path_to_observations}/observation_{timestamp}.csv', 'w', newline='') as file: writer = csv.DictWriter(file, fieldnames=field_names) writer.writeheader() writer.writerows(pokemons_list_of_dicts) print("Observation data written.") if __name__ == '__main__': pokemons_2 = create_pokemon_list() transform_load(pokemons_2)
import { Command, CommandoMessage } from 'discord.js-commando'; import RoleList from '../../templates/Announcement_RoleList'; import CONSTANTS from '../../constants'; import { hasPermissions } from '../../bot-utils'; import { genericError } from '../../errorManagement'; import { Message } from 'discord.js'; export default class rolehelper extends Command { constructor(client) { super(client, { name: 'rolelist', memberName: 'rolelist', group: 'everyone', description: 'Show the rolelist in the channel', examples: ['rolelist'], }); } hasPermission(msg) { const permissions = { roles: [CONSTANTS.ROLES.ANY], channels: [CONSTANTS.CHANNELS.ALFRED_COMMANDS], }; return hasPermissions(this.client, permissions, msg); } // eslint-disable-next-line class-methods-use-this onError(err, message, args, fromPattern, result) { return genericError(err, message); } // eslint-disable-next-line async run(msg: CommandoMessage): Promise<Message> { try { await msg.delete(); return msg.channel.send({ embed: new RoleList().embed(), }); } catch (e) { console.error(e); } } }
import fnmatch import os import traceback from concurrent.futures import ProcessPoolExecutor from datetime import datetime, timedelta from functools import partial import pandas as pd import requests from astropy.io import fits from bs4 import BeautifulSoup from tqdm import tqdm from ecallisto_ng.data_download.utils import ( concat_dfs_by_instrument, ecallisto_fits_to_pandas, extract_datetime_from_filename, extract_instrument_name, filter_dataframes, instrument_name_to_globbing_pattern, ) BASE_URL = "http://soleil80.cs.technik.fhnw.ch/solarradio/data/2002-20yy_Callisto" LOCAL_URL = "/mnt/nas05/data01/radio/2002-20yy_Callisto" def get_ecallisto_data( start_datetime, end_datetime, instrument_name=None, verbose=False, freq_start=None, freq_end=None, download_from_local=False, ): """ Get the e-Callisto data within a date range and optional instrument regex pattern. For big requests, it is recommended to use the generator function `get_ecallisto_data_generator`, which allows for processing each file individually without loading everything into memory at once. Parameters ---------- start_datetime : datetime-like The start date for the file search. end_datetime : datetime-like The end date for the file search. instrument_string : str or None The instrument name you want to match in file URLs. If None, all files are considered. Substrings also work, such as 'ALASKA'. verbose : bool Whether to print progress information. freq_start : float or None The start frequency for the filter. freq_end : float or None The end frequency for the filter. download_from_local : bool Whether to download the files from the local directory instead of the remote directory. Useful if you are working with a local copy of the data. Returns ------- dict of str: `~pandas.DataFrame` or `~pandas.DataFrame` Dictionary of instrument names and their corresponding dataframes. """ file_urls = get_remote_files_url(start_datetime, end_datetime, instrument_name) if not file_urls: print( f"No files found for {instrument_name} between {start_datetime} and {end_datetime}." ) return {} if download_from_local: file_urls = [file_url.replace(BASE_URL, LOCAL_URL) for file_url in file_urls] dfs = download_fits_process_to_pandas(file_urls, verbose) dfs = concat_dfs_by_instrument(dfs, verbose) dfs = filter_dataframes( dfs, start_datetime, end_datetime, verbose, freq_start=freq_start, freq_end=freq_end, ) return dfs def get_ecallisto_data_generator( start_datetime, end_datetime, instrument_name=None, freq_start=None, freq_end=None, base_url=BASE_URL, ): """ Generator function to yield e-Callisto data one file at a time within a date range. It returns a tuple with (instrument_name, dataframe) This function is a generator, using `yield` to return dataframes one by one. This is beneficial for handling large datasets or when working with limited memory, as it allows for processing each file individually without loading everything into memory at once. Parameters ---------- start_datetime : datetime-like The start date for the file search. end_datetime : datetime-like The end date for the file search. instrument_names : List[str] or str or None The instrument name you want to match in file URLs. If None, all files are considered. freq_start : float or None The start frequency for the filter. freq_end : float or None The end frequency for the filter. base_url : str The base URL of the remote file directory. Yields ------ pandas.DataFrame A tuple with (instrument_name, dataframe) Example ------- >>> start = <start_datetime> >>> end = <end_datetime> >>> instrument = <instrument_name> >>> data_generator = get_ecallisto_data_generator(start, end, instrument) >>> for instrument_name, data_frame in data_generator: ... process_data(data_frame) # Replace with your processing function or whatever you want to do with the data """ if isinstance(instrument_name, str): instrument_name = [instrument_name] if instrument_name is None: # Get all instrument names with available data. This makes the generator more efficient # because it doesn't have to check for each instrument name individually. instrument_name = get_instrument_with_available_data( start_datetime, end_datetime ) for instrument_name_ in instrument_name: file_urls = get_remote_files_url( start_datetime, end_datetime, instrument_name_, base_url ) if not file_urls: print( f"No files found for {instrument_name} between {start_datetime} and {end_datetime}." ) return {} try: dfs = download_fits_process_to_pandas(file_urls) dfs = concat_dfs_by_instrument(dfs) dfs = filter_dataframes( dfs, start_datetime, end_datetime, freq_start=freq_start, freq_end=freq_end, ) for key, value in dfs.items(): yield key, value except Exception as e: print(f"Error for {instrument_name_}: {e}") print(f"Skipping {instrument_name_}.") continue def get_instrument_with_available_data( start_date=None, end_date=None, instrument_name=None ): """ Retrieve sorted list of unique instrument names with available data in a specified date range. Parameters ---------- start_date : pd.Timestamp or None The start date for querying data. If None, the current timestamp is used. end_date : pd.Timestamp or None The end date for querying data. If None, it is set to three days prior to the current timestamp. instrument_name : str, optional Name of the specific instrument to query. If None, all available instruments are considered. Returns ------- list of str A sorted list of unique instrument names for which data is available in the specified date range. Returns an empty list if no data is found. Notes ----- - The function depends on `get_remote_files_url` to fetch URLs of available data files. - `extract_instrument_name` is used to parse instrument names from the file URLs. - If both `start_date` and `end_date` are None, the function defaults to a date range from the current date to three days prior. Examples -------- >>> get_instrument_with_available_data(pd.Timestamp('2023-01-01'), pd.Timestamp('2023-01-10'), 'Instrument') ['InstrumentA', 'InstrumentB', 'InstrumentX'] """ if start_date is None or end_date is None: # Set start_date to now end_date = pd.Timestamp.now() # Set end_date to 1 day ago start_date = end_date - pd.Timedelta(days=1) file_urls = get_remote_files_url(start_date, end_date, instrument_name) if not file_urls: print( f"No files found for {instrument_name} between {start_date} and {end_date}." ) return {} instrument_names = [extract_instrument_name(file_url) for file_url in file_urls] return sorted(list(set(instrument_names))) def download_fits_process_to_pandas(file_urls, verbose=False): with ProcessPoolExecutor(max_workers=os.cpu_count()) as executor: # Use tqdm for progress tracking, passing the total number of tasks partial_f = partial(fetch_fits_to_pandas, verbose=verbose) results = list( tqdm( executor.map(partial_f, file_urls), total=len(file_urls), desc="Downloading and processing files", ) ) # Check if any of the results are None if verbose and any(result is None for result in results): print("Some files could not be downloaded (See traceback above).") # Remove None values results = [result for result in results if result is not None] return results def fetch_fits_to_pandas(file_url, verbose=False): try: fits_file = fits.open(file_url, cache=False) df = ecallisto_fits_to_pandas(fits_file) # Add the instrument name to it df.attrs["ANTENNAID"] = extract_instrument_name(file_url)[-2:] return df except Exception as e: if verbose: print(f"Error for {file_url}: {e}") traceback.print_exc() return None def fetch_date_files(date_url): """ Fetch and parse file URLs from a given date URL. Parameters ---------- date_url : str The URL for a specific date to fetch files from. session : requests.Session The requests session object for HTTP requests. Returns ------- list of str List of file URLs ending with '.gz'. """ session = requests.Session() response = session.get(date_url) try: soup = BeautifulSoup( response.content, "lxml" ) # using lxml parser because it's faster file_names = [ link.get("href") for link in soup.find_all("a") if link.get("href").endswith(".gz") ] to_return = [date_url + file_name for file_name in file_names] except Exception as e: print(f"Error fetching {date_url}.") print(e) to_return = [] finally: session.close() return to_return def get_remote_files_url( start_date, end_date, instrument_name=None, base_url="http://soleil80.cs.technik.fhnw.ch/solarradio/data/2002-20yy_Callisto", ): """ Get the remote file URLs within a date range and optional instrument regex pattern. Parameters ---------- start_date : datetime-like The start date for the file search. end_date : datetime-like The end date for the file search. instrument_string : str or None The instrument name you want to match in file URLs. If None, all files are considered. Substrings also work, such as 'ALASKA'. base_url : str The base URL of the remote file directory. Returns ------- list of str List of file URLs that match the criteria. """ file_urls = [] date_urls = [ f"{base_url}/{date.year}/{str(date.month).zfill(2)}/{str(date.day).zfill(2)}/" for date in pd.date_range(start_date, end_date, inclusive="both") ] with ProcessPoolExecutor(max_workers=os.cpu_count()) as executor: # Map each URL to a fetch function with a session results = executor.map(fetch_date_files, date_urls) # Flatten the results results = [item for sublist in results for item in sublist] glob_pattern = instrument_name_to_globbing_pattern(instrument_name) file_urls = fnmatch.filter(results, glob_pattern) # Extact datetime from filename file_datetimes = [ extract_datetime_from_filename(file_name) for file_name in file_urls ] # Filter out files that are not in the date range file_urls = [ file_url for file_url, file_datetime in zip(file_urls, file_datetimes) if start_date - timedelta(minutes=15) <= file_datetime <= end_date + timedelta(minutes=15) ] # Timedelta because a file contains up to 15 minutes of data return file_urls
export function GetCardBlockData(data: any, provider: string) { let returnData: { id: any; title: any; description: any; backgroundImage: any; button: any; cards: any; roundedImage: boolean; variant: number; grid: number }; switch (provider) { case "strapi": returnData = { "id": data?.id ? data.id : "yt", "title": data?.Title ? data.Title : "", "description": data?.Description ? data.Description : "", "backgroundImage": data?.Background_Image?.data?.attributes?.url ? process.env.NEXT_PUBLIC_STRAPI_BASE_URL + data.Background_Image.data.attributes.url : "", "button": data?.ButtonTitle ? data.ButtonTitle : "", "cards": data?.cards.data ? data.cards.data : "", "roundedImage": data?.CardImageRounded ? data.CardImageRounded : "", "variant": 1, "grid": 1 } break; case "contentstack": returnData = { "id": data?.id ? data.id:"", "title": data?.title ? data.title : "", "description": data?.description ? data.description : "", "backgroundImage": data?.background_imageConnection?.edges[0]?.node?.url ? data.background_imageConnection.edges[0].node.url : "", "button": data?.ButtonTitle ? data.ButtonTitle : "", "cards": data?.card_collectionConnection?.edges ? data.card_collectionConnection.edges : "", "roundedImage": data?.rounded_image ? data.rounded_image : false, "variant": data?.variant ? data.variant : 1, "grid": data?.grid ? data.grid : 3 } break; case "contentful": returnData = { "id": data?.id ? data.id : "yt", "title": data?.title ? data.title : "", "description": data?.description ? data.description : "", "backgroundImage": data?.backgroundImage?.url ? data.backgroundImage.url : "", "button": data?.buttonTitle ? data.buttonTitle : "", "cards": data?.cardsCollection?.items ? data.cardsCollection.items : "", "roundedImage": data?.roundedImage ? data.roundedImage : false, "variant": data?.variant ? data.variant : 1, "grid": data?.grid ? data.grid : 3 } break; case "drupal": returnData = { "id": data?.id ? data.id : "", "title": data?.title ? data.title : "", "description": data?.body ? data.body : "", "backgroundImage": data?.field_bio_image ? data.field_bio_image : "", "button": data?.buttonTitle ? data.buttonTitle : "", "cards": data?.field_featured_card?.items ? data.field_featured_card.items:"", "roundedImage": data?.roundedImage ? data.roundedImage : true, "variant": data?.variant ? data.variant : 1, "grid": data?.grid ? data.grid : 3 } break default: returnData = { "id": "55", "title": "Dummy Title", "description": "Dummy Description Sit nihil eius vel suscipit eaque sed porro obcaecati ab consectetur minima sed vero ullam. Eum voluptatem deleniti id deserunt aliquam ab pariatur reprehenderit eos nulla dicta. Eos sunt officiis et quia omnis et enim incidunt", "backgroundImage": process.env.NEXT_PUBLIC_STRAPI_BASE_URL + "/uploads/1368x500_5_634d0c434c.png", "button": "Dummy Click Me", "cards": [ { 'id': "1", 'title': "Dummy Card Title 1", 'slug': "abc", "description": "Dummy Description Sit nihil eius vel suscipit eaque sed porro obcaecati ab consectetur minima sed vero ullam. Eum voluptatem deleniti id deserunt aliquam ab pariatur reprehenderit eos nulla dicta. Eos sunt officiis et quia omnis et enim incidunt", 'shortdescription': "Dummy Card short description 1 Sit nihil eius vel suscipit eaque sed porro obcaecati ab consectetur minima sed vero ullam. Eum voluptatem deleniti id deserunt aliquam ab pariatur reprehenderit eos nulla dicta. Eos sunt officiis et quia omnis et enim incidunt", 'image': { "url": process.env.NEXT_PUBLIC_STRAPI_BASE_URL + "/uploads/400x400_af3b8c58a1.png", "width": "250", "height": "250", 'alt': "card Image", } }, { 'id': "2", 'title': "Dummy Card Title 2", 'slug': "abc", "description": "Dummy Description Sit nihil eius vel suscipit eaque sed porro obcaecati ab consectetur minima sed vero ullam. Eum voluptatem deleniti id deserunt aliquam ab pariatur reprehenderit eos nulla dicta. Eos sunt officiis et quia omnis et enim incidunt", 'shortdescription': "Dummy Card short description 2 Sit nihil eius vel suscipit eaque sed porro obcaecati ab consectetur minima sed vero ullam. Eum voluptatem deleniti id deserunt aliquam ab pariatur reprehenderit eos nulla dicta. Eos sunt officiis et quia omnis et enim incidunt", 'image': { "url": process.env.NEXT_PUBLIC_STRAPI_BASE_URL + "/uploads/400x400_af3b8c58a1.png", "width": "250", "height": "250", 'alt': "card Image", } }, { 'id': "1", 'title': "Dummy Card Title 3", 'slug': "abc", "description": "Dummy Description Sit nihil eius vel suscipit eaque sed porro obcaecati ab consectetur minima sed vero ullam. Eum voluptatem deleniti id deserunt aliquam ab pariatur reprehenderit eos nulla dicta. Eos sunt officiis et quia omnis et enim incidunt", 'shortdescription': "Dummy Card short description 3 Sit nihil eius vel suscipit eaque sed porro obcaecati ab consectetur minima sed vero ullam. Eum voluptatem deleniti id deserunt aliquam ab pariatur reprehenderit eos nulla dicta. Eos sunt officiis et quia omnis et enim incidunt", 'image': { "url": process.env.NEXT_PUBLIC_STRAPI_BASE_URL + "/uploads/400x400_af3b8c58a1.png", "width": "250", "height": "250", 'alt': "card Image", } } ], "roundedImage": true, "variant": 1, "grid": 1 } break } return returnData; }
#pragma once #include <stdint.h> #ifdef __cplusplus extern "C" { #endif #define PI 3.14159265359f #define DEG_2_RAD (PI / 180.0f) #define RAD_2_DEG (180.0f / PI) #define MAT4_IDENTITY \ (Mat4) \ { \ 1.0f, 0.0f, 0.0f, 0.0f, \ 0.0f, 1.0f, 0.0f, 0.0f, \ 0.0f, 0.0f, 1.0f, 0.0f, \ 0.0f, 0.0f, 0.0f, 1.0f \ } #define QUATERNION_IDENTITY \ (Quaternion) { 0.0f, 0.0f, 0.0f, 1.0f } /// @brief A two-component vector typedef struct { float x; float y; } Vec2; /// @brief A three-component vector typedef struct { float x; float y; float z; } Vec3; /// @brief A four-component vector typedef struct { float x; float y; float z; float w; } Vec4; /// @brief A quaternion typedef struct { float x; float y; float z; float w; } Quaternion; /// @brief A 4x4 matrix typedef struct { float m[4][4]; } Mat4; /// @brief Get the length of a vector /// @param v /// @return The length of the vector float vec2_length(Vec2 v); /// @brief Get the length of a vector /// @param v /// @return The length of the vector float vec3_length(Vec3 v); /// @brief Get the squared length of a vector /// @param v /// @return The squared length of the vector float vec2_lengthSq(Vec2 v); /// @brief Get the squared length of a vector /// @param v /// @return The squared length of the vector float vec3_lengthSq(Vec3 v); /// @brief Get the distance between two vectors /// @param lhs /// @param rhs /// @return The distance between the given vectors float vec2_distance(Vec2 lhs, Vec2 rhs); /// @brief Get the distance between two vectors /// @param lhs /// @param rhs /// @return The distance between the given vectors float vec3_distance(Vec3 lhs, Vec3 rhs); /// @brief Get the squared distance between two vectors /// @param lhs /// @param rhs /// @return The squared distance between the given vectors float vec2_distanceSq(Vec2 lhs, Vec2 rhs); /// @brief Get the squared distance between two vectors /// @param lhs /// @param rhs /// @return The squared distance between the given vectors float vec3_distanceSq(Vec3 lhs, Vec3 rhs); /// @brief Clamp the value between a minimum and maximum /// @param value /// @param min /// @param max /// @return A value clamped between min and max float clamp(float value, float min, float max); /// @brief Linearly interpolate between two values /// @param lhs /// @param rhs /// @param t /// @return A value between lhs and rhs float lerp(float lhs, float rhs, float t); /// @brief Linearly interpolate between two values /// @param lhs /// @param rhs /// @param t /// @return A value between lhs and rhs Vec2 vec2_lerp(Vec2 lhs, Vec2 rhs, float t); /// @brief Linearly interpolate between two values /// @param lhs /// @param rhs /// @param t /// @return A value between lhs and rhs Vec3 vec3_lerp(Vec3 lhs, Vec3 rhs, float t); /// @brief Linearly interpolate between two values /// @param lhs /// @param rhs /// @param t /// @return A value between lhs and rhs Vec4 vec4_lerp(Vec4 lhs, Vec4 rhs, float t); /// @brief Componentwise-mutiply two vectors /// @param lhs /// @param rhs /// @return The product of both vectors Vec2 vec2_mul(Vec2 lhs, Vec2 rhs); /// @brief Componentwise-mutiply two vectors /// @param lhs /// @param rhs /// @return The product of both vectors Vec3 vec3_mul(Vec3 lhs, Vec3 rhs); /// @brief Componentwise-mutiply two vectors /// @param lhs /// @param rhs /// @return The product of both vectors Vec4 vec4_mul(Vec4 lhs, Vec4 rhs); /// @brief Add two vectors /// @param lhs /// @param rhs /// @return The sum of both vectors Vec2 vec2_add(Vec2 lhs, Vec2 rhs); /// @brief Add two vectors /// @param lhs /// @param rhs /// @return The sum of both vectors Vec3 vec3_add(Vec3 lhs, Vec3 rhs); /// @brief Add two vectors /// @param lhs /// @param rhs /// @return The sum of both vectors Vec4 vec4_add(Vec4 lhs, Vec4 rhs); /// @brief Subtract two vectors /// @param lhs /// @param rhs /// @return The difference of both vectors Vec2 vec2_sub(Vec2 lhs, Vec2 rhs); /// @brief Subtract two vectors /// @param lhs /// @param rhs /// @return The difference of both vectors Vec3 vec3_sub(Vec3 lhs, Vec3 rhs); /// @brief Subtract two vectors /// @param lhs /// @param rhs /// @return The difference of both vectors Vec4 vec4_sub(Vec4 lhs, Vec4 rhs); /// @brief Divide two vectors /// @param lhs /// @param rhs /// @return The quotient of both vectors Vec2 vec2_div(Vec2 lhs, Vec2 rhs); /// @brief Divide two vectors /// @param lhs /// @param rhs /// @return The quotient of both vectors Vec3 vec3_div(Vec3 lhs, Vec3 rhs); /// @brief Divide two vectors /// @param lhs /// @param rhs /// @return The quotient of both vectors Vec4 vec4_div(Vec4 lhs, Vec4 rhs); /// @brief Compute the dot product of the given vectors /// @param lhs The vector on the lefthand side /// @param rhs The vector on the righthand side /// @return The dot product of the two vectors float vec2_dot(Vec2 lhs, Vec2 rhs); /// @brief Compute the dot product of the given vectors /// @param lhs The vector on the lefthand side /// @param rhs The vector on the righthand side /// @return The dot product of the two vectors float vec3_dot(Vec3 lhs, Vec3 rhs); /// @brief Compute the dot product of the given vectors /// @param lhs The vector on the lefthand side /// @param rhs The vector on the righthand side /// @return The dot product of the two vectors float vec4_dot(Vec4 lhs, Vec4 rhs); /// @brief Compute the cross product of the given vectors /// @param lhs The vector on the lefthand side /// @param rhs The vector on the righthand side /// @return The cross product of the two vectors Vec3 vec3_cross(Vec3 lhs, Vec3 rhs); /// @brief Normalize the given vector /// @param v The vector to normalize void vec2_normalize(Vec2 *v); /// @brief Normalize the given vector /// @param v The vector to normalize void vec3_normalize(Vec3 *v); /// @brief Normalize the given vector /// @param v The vector to normalize void vec4_normalize(Vec4 *v); /// @brief Normalize the given quaternion /// @param q The quaternion to normalize void quat_normalize(Quaternion *q); /// @brief Invert the given quaternion /// @param q Pointer to the quaternion to invert void quat_invert(Quaternion *q); /// @brief Rotate a vector by a quaternion /// @param q The quaternion representing a rotation /// @param v The vector to rotate /// @return A rotated vector Vec3 vec3_transformQuat(Quaternion q, Vec3 v); /// @brief Multiply two quaternions together /// @param lhs Quaternion on the lefthand side /// @param rhs Quaternion on the righthand side /// @return The multiplied result Quaternion quat_mul(Quaternion lhs, Quaternion rhs); /// @brief Construct a quaternion from rotation around each axis /// @param eulerAngles Rotation around each axis in radians /// @return An equivalent quaternion Quaternion quat_fromEuler(Vec3 eulerAngles); /// @brief Transform a single vector with a matrix without the aid of the SIMD matrix unit /// @param mat The transform matrix /// @param vec The vector to transform /// @return The transformed vector Vec4 vec4_transform(Mat4 mat, Vec4 vec); /// @brief Construct a matrix from the given translation /// @param translation The translation /// @return A translation matrix Mat4 mat4_translate(Vec3 translation); /// @brief Construct a matrix from the given scale /// @param scale The scale /// @return A scale matrix Mat4 mat4_scale(Vec3 scale); /// @brief Construct a matrix from the given rotation /// @param rotation The rotation /// @return A rotation matrix Mat4 mat4_rotation(Quaternion rotation); /// @brief Construct an orthographic projection matrix /// @param left The left side of the frustum /// @param right The right side of the frustum /// @param top The top side of the frustum /// @param bottom The bottom side of the frustum /// @param near The near clip distance /// @param far The far clip distance /// @return An orthographic projection matrix Mat4 mat4_projectionOrtho(float left, float right, float top, float bottom, float near, float far); /// @brief Construct an orthographic projection matrix /// @param aspectRatio The aspect ratio of the frustum (width/height) /// @param scale The height of the frustum /// @param near The near clip distance /// @param far The far clip distance /// @return An orthographic projection matrix centered at origin Mat4 mat4_projectionOrthoAspect(float aspectRatio, float scale, float near, float far); /// @brief Construct a perspective projection matrix /// @param aspectRatio The aspect ratio of the frustum (width/height) /// @param fieldOfView The vertical field of view in radians /// @param near The near clip distance /// @param far The far clip distance /// @return A perspective projection matrix centered at origin Mat4 mat4_projectionPerspective(float aspectRatio, float fieldOfView, float near, float far); /// @brief Multiply two matrices together manually without the aid of the SIMD matrix unit /// @param lhs Matrix on the lefthand side /// @param rhs Matrix on the righthand side /// @return The multiplied matrix result Mat4 mat4_mul(Mat4 lhs, Mat4 rhs); /// @brief Load identity matrix into the SIMD matrix register void mat4_loadIdentitySIMD(); /// @brief Load a matrix into the SIMD matrix register /// @param mat The matrix to load extern void mat4_loadSIMD(const Mat4 *mat); /// @brief Store the value in the SIMD matrix register to the given matrix /// @param mat The matrix to store the value into extern void mat4_storeSIMD(Mat4 *mat); /// @brief Multiply internal SIMD matrix register with the given matrix /// @param mat The matrix to multiply into the SIMD matrix register extern void mat4_mulSIMD(const Mat4 *mat); /// @brief Transform a list of input Vec4s using the SIMD matrix unit /// @param invec Pointer to list of input vectors to transform /// @param outvec Pointer to list of output vectors to write /// @param count Number of vectors to transform /// @param stride Number of bytes between each vector (0 implies tightly packed array of Vec4) extern void mat4_transformSIMD(const Vec4 *invec, Vec4 *outvec, uint32_t count, uint32_t stride); #ifdef __cplusplus } #endif
from datetime import date, datetime from typing import Dict, List import requests from .base_parser import BaseParser from bs4 import BeautifulSoup class DouParser(BaseParser): """ A parser for scraping job listings from DOU. Attributes: CATEGORY_URL_MAP (dict): A mapping of job categories to their corresponding URLs. JOBS_URL (str): The base URL for job listings. SET_LANG_URL (str): The URL for setting the language to English. USER_AGENT (str): The user agent to use for the HTTP requests. """ CATEGORY_URL_MAP = { ".NET": ".NET", "AI/ML": "AI/ML", "Android": "Android", "Architect": "Architect", "Big Data": "Big Data", "Blockchain": "Blockchain", "C++": "C%2B%2B", "Data Engineer": "Data Engineer", "Data Science": "Data Science", "DevOps": "DevOps", "Embedded": "Embedded", "Flutter": "Flutter", "Front End": "Front End", "Golang": "Golang", "Java": "Java", "Node.js": "Node.js", "PHP": "PHP", "Python": "Python", "React Native": "React Native", "Ruby": "Ruby", "Rust": "Rust", "Scala": "Scala", "iOS/macOS": "iOS/macOS", } JOBS_URL = "https://jobs.dou.ua/vacancies/" SET_LANG_URL = "https://dou.ua/?switch_lang=en" USER_AGENT = "Mozilla/5.0 (Macintosh; Intel Mac OS X 10.15; rv:101.0) Gecko/20100101 Firefox/101.0" def __get_jobs_from_page(self, page_html: str, category: str) -> List[Dict]: """ Extracts job listings from a page HTML. Args: page_html (str): The HTML content of the page. category (str): The category of the job listings. Returns: List[Dict]: A list of job listings as dictionaries. """ soup = BeautifulSoup(page_html, "html.parser") li_tags = soup.find_all("li", class_="l-vacancy") jobs = [] for li in li_tags: a_tag = li.find("a", class_="vt") title = a_tag.text.strip('\n "«»') url = a_tag["href"].rstrip("?from=list_hot") company = li.find("a", class_="company").text.strip('\n "«»') date_str = li.find("div", class_="date").text.strip() published_at = datetime.strptime(date_str, "%d %B %Y").date() jobs.append( { "category": category, "company": company, "published_at": published_at, "source": "dou", "title": title, "url": url, } ) return jobs def __get_all_jobs_by_category(self, category: str) -> List[Dict]: """ Retrieves all job listings for a specific category. Args: category (str): The category of the job listings. Returns: List[Dict]: A list of job listings as dictionaries. """ try: with requests.Session() as session: category_url = ( f"{self.JOBS_URL}?category={self.CATEGORY_URL_MAP[category]}" ) headers = {"User-Agent": self.USER_AGENT, "Referer": category_url} # set language to English session.get(self.SET_LANG_URL, headers=headers) response = session.get(category_url, headers=headers) soup = BeautifulSoup(response.text, "html.parser") csrf_token = soup.find("input", {"name": "csrfmiddlewaretoken"})[ "value" ] post_url = f"{self.JOBS_URL}xhr-load/?category={self.CATEGORY_URL_MAP[category]}" count = 0 jobs = [] while True: data = { "csrfmiddlewaretoken": csrf_token, "count": count, } post_response = session.post(post_url, data=data, headers=headers) response_data = post_response.json() page_html = response_data["html"] jobs_from_page = self.__get_jobs_from_page(page_html, category) jobs.extend(jobs_from_page) if response_data["last"]: break count += 40 return jobs except requests.exceptions.RequestException as e: print(f"Request failed: {e}") return [] def get_jobs_by_category( self, category: str, start_date: date, end_date: date ) -> List[Dict]: """ Get job listings by category and within a specified date range. Args: category (str): The category of jobs to retrieve. start_date (date): The start date of the date range. end_date (date): The end date of the date range. Returns: List[Dict]: A list of job listings as dictionaries. """ jobs = [ job for job in self.__get_all_jobs_by_category(category) if start_date <= job["published_at"] <= end_date ] return jobs def get_job_description(self, url: str) -> str: """ Get the description of a job listing. Args: url (str): The URL of the job listing. Returns: str: The description of the job listing. """ headers = {"User-Agent": self.USER_AGENT, "Referer": url} with requests.Session() as session: # set language to English session.get(self.SET_LANG_URL, headers=headers) response = session.get(url, headers=headers) response.raise_for_status() soup = BeautifulSoup(response.text, "html.parser") div_tag = soup.find("div", class_="l-vacancy") div_tag.find("h1", class_="g-h2").extract() div_tag.find("div", class_="sh-info").extract() div_tag.find("div", class_="likely").extract() div_tag.find("div", class_="reply").extract() description = self.convert_html_to_text(str(div_tag)) return description
// // Created by irantha on 5/14/23. // #include <atomic> #include <catch2/catch_test_macros.hpp> #include <thread> #include <vector> #include "async_spin_wait.hpp" #include "task/async_task.hpp" #include "task/sync_task.hpp" #include "task/task.hpp" #include "test/async_test_utils.hpp" #include "async_event.hpp" #include "sync_auto_reset_countdown_event.hpp" #include "sync_auto_reset_event.hpp" #include "sync_manual_reset_event.hpp" namespace Levelz::Async::Test { using namespace std::chrono_literals; TEST_CASE("AsyncEvent - initially signal", "[AsyncEvent]") { std::atomic<int> value = 0; AsyncEvent event { true }; auto coroutine = [&value, &event]() -> Task<int> { value = 1; co_await event; value = 2; co_return -1; }; auto runner = [&]() -> SyncTask<> { auto task = coroutine(); REQUIRE(value == 0); auto returnValue = co_await task; REQUIRE(returnValue == -1); REQUIRE(value == 2); }; runner().get(); } TEST_CASE("AsyncEvent - initially not signal", "[AsyncEvent]") { std::atomic<int> value = 0; AsyncEvent event { false }; SyncAutoResetEvent syncEvent { false }; auto run = [&]() -> SyncTask<int> { value++; syncEvent.set(); co_await event; value++; syncEvent.set(); co_return 0; }; auto task = run(); syncEvent.wait(); REQUIRE(value == 1); event.signal(); syncEvent.wait(); REQUIRE(value == 2); REQUIRE(task.get() == 0); } TEST_CASE("AsyncEvent - multiple waiting coroutines", "[AsyncEvent]") { REPEAT_HEADER constexpr int count = 100; std::atomic<int> value = 0; AsyncEvent event { false }; SyncAutoResetEvent syncEvent { false }; SyncAutoResetCountDownEvent syncCountdownEvent { count }; auto run = [&]() -> SyncTask<int> { value++; syncEvent.set(); co_await event; int tmp = ++value; syncCountdownEvent.set(); co_return tmp; }; std::vector<SyncTask<int>> tasks; tasks.reserve(count); for (int i = 0; i < count; i++) { tasks.push_back(run()); syncEvent.wait(); REQUIRE(value == i + 1); } REQUIRE(value == count); event.signal(); syncCountdownEvent.wait(); REQUIRE(value == count * 2); std::vector<int> values; values.reserve(count); for (int i = 0; i < count; i++) { values.push_back(tasks[i].get()); } std::sort(values.begin(), values.end()); for (int i = 0; i < count; i++) { REQUIRE(values[i] == count + 1 + i); } REQUIRE(values[count - 1] == 200); REPEAT_FOOTER } TEST_CASE("AsyncEvent - reset", "[AsyncEvent]") { constexpr int count = 1000; std::atomic<int> value = 0; AsyncEvent event { false }; SyncAutoResetCountDownEvent syncCountdownEvent { count }; auto run = [&]() -> SyncTask<int> { value++; syncCountdownEvent.set(); co_await event; int tmp = ++value; syncCountdownEvent.set(); co_return tmp; }; std::vector<SyncTask<int>> tasks; tasks.reserve(count); for (int i = 0; i < count; i++) { tasks.push_back(run()); } syncCountdownEvent.wait(); REQUIRE(value == count); event.signal(); syncCountdownEvent.wait(); REQUIRE(value == 2 * count); event.reset(); for (int i = 0; i < count; i++) { tasks.push_back(run()); } syncCountdownEvent.wait(); REQUIRE(value == count * 3); event.signal(); syncCountdownEvent.wait(); REQUIRE(value == count * 4); for (auto& t : tasks) (void)t.get(); } TEST_CASE("AsyncEvent - async enqueue event", "[AsyncEvent]") { std::atomic<int> value = 0; AsyncEvent sourceEvent {}; AsyncEvent targetEvent {}; sourceEvent.enqueue(targetEvent); SyncAutoResetEvent syncEvent { false }; auto run = [&]() -> SyncTask<int> { value++; syncEvent.set(); co_await targetEvent; value++; syncEvent.set(); co_return 0; }; auto task = run(); syncEvent.wait(); REQUIRE(value == 1); sourceEvent.signal(); syncEvent.wait(); REQUIRE(value == 2); task.get(); } TEST_CASE("AsyncEvent - async enqueue sync event", "[AsyncEvent]") { std::atomic<int> value = 0; AsyncEvent sourceEvent {}; SyncManualResetEvent targetEvent { false }; sourceEvent.enqueue(targetEvent); SyncAutoResetEvent syncEvent { false }; auto run = [&]() -> SyncTask<int> { value++; syncEvent.set(); AsyncSpinWait spinWait; while (!targetEvent.isSet()) spinWait.spinOne(); value++; syncEvent.set(); co_return 0; }; auto task = run(); syncEvent.wait(); REQUIRE(value == 1); sourceEvent.signal(); syncEvent.wait(); REQUIRE(value == 2); task.get(); } TEST_CASE("Immediately cancel Async awaiting on event", "[AsyncEvent]") { REPEAT_HEADER AsyncEvent event; std::atomic<int> value2 = 0; std::atomic<int> value1 = 0; auto c2 = [&]() -> Async<> { value2++; co_await event; value2++; }; auto c1 = [&]() -> Async<> { value1++; co_await event; value1++; }; auto runner = [&]() -> Sync<> { auto task1 = c1(); auto task2 = c2(); AsyncSpinWait spinWait; while (event.waitListedCount() != 2) spinWait.spinOne(); REQUIRE(value2 == 1); REQUIRE(value1 == 1); task2.cancel(); REQUIRE(event.waitListedCount() == 1); REQUIRE_THROWS_AS(co_await task2, CancellationError); event.signal(); co_await task1; REQUIRE(value1 == 2); REQUIRE(value2 == 1); co_return; }; runner().get(); REPEAT_FOOTER } }
/*: ## Exercise - For-In Loops Create a for-in loop that loops through values 1 to 100, and prints each of the values. */ for values in 1 ... 100{ print(values) } /*: Create a for-in loop that loops through each of the characters in the `alphabet` string below, and prints each of the values alongside the index. */ let alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ" for (index, letters) in alphabet.enumerated(){ print("\(index): \(letters)") } /*: Create a `[String: String]` dictionary, where the keys are names of states and the values are their capitals. Include at least three key/value pairs in your collection, then use a for-in loop to iterate over the pairs and print out the keys and values in a sentence. */ let canada = ["Ontario": "Toronto", "Nova Scotia": "Halifax", "Alberta": "Edmonton", "Manitoba": "Winnipeg"] for (province, capital) in canada { print("The Capital of \(province) is \(capital).") } //: page 1 of 6 | [Next: App Exercise - Movements](@next)
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> <script src="https://cdn.tailwindcss.com"></script> <link href="https://cdn.jsdelivr.net/npm/[email protected]/fonts/remixicon.css" rel="stylesheet" /> <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/swiper@11/swiper-bundle.min.css" /> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/animate.css/4.1.1/animate.min.css" /> <script src="https://cdn.jsdelivr.net/npm/swiper@11/swiper-bundle.min.js"></script> </head> <body> <div class="flex justify-between py-2 px-14 bg-amber-500 text-white"> <div> <i class="ri-facebook-fill bg-white text-amber-500 p-1 rounded-full"></i> <i class="ri-instagram-fill bg-white text-amber-500 p-1 rounded-full"></i> <i class="ri-whatsapp-fill bg-white text-amber-500 p-1 rounded-full"></i> </div> <div> <i class="ri-phone-fill"></i> +977-9876543210 <i class="ri-mail-fill"></i> [email protected] </div> </div> <nav class="bg-blue-900 lg:flex hidden items-center justify-between px-14 sticky top-0 z-10"> <img src="https://mmatnepal.com/images/logo.png" class="h-20 bg-white" alt=""> <div class="text-white font-bold"> <a class="p-4" href="index.html">Home</a> <a class="p-4" href="about.html">About Us</a> <a class="p-4" href="flights.html">Flights</a> <a class="p-4" href="">Packages</a> <a class="p-4" href="">Blog</a> <a class="p-4" href="gallery.html">Gallery</a> <a class="p-4" href="contact.html">Contact</a> </div> </nav> <nav class="bg-blue-900 px-4 block lg:hidden sticky top-0 z-10"> <div class="flex justify-between items-center"> <img src="https://mmatnepal.com/images/logo.png" class="h-20 bg-white" alt=""> <i onclick="controlNav()" class="ri-menu-line text-3xl text-white"></i> </div> <div id="menu" class="text-white font-bold hidden"> <a class="p-4 block" href="index.html">Home</a> <a class="p-4 block" href="about.html">About Us</a> <a class="p-4 block" href="flights.html">Flights</a> <a class="p-4 block" href="">Packages</a> <a class="p-4 block" href="">Blog</a> <a class="p-4 block" href="gallery.html">Gallery</a> <a class="p-4 block" href="contact.html">Contact</a> </div> </nav> <!-- Slider main container --> <div class="swiper swiper1"> <!-- Additional required wrapper --> <div class="swiper-wrapper"> <!-- Slides --> <div class="swiper-slide"> <div class="relative"> <img src="https://mmatnepal.com/public/trekkings/Fx0AmCdzWuO84b2z79Nd.jpg" class="w-full" alt=""> <div class="absolute right-10 bottom-10 w-72 bg-black text-white p-4 bg-opacity-50 rounded"> <h2 class="text-2xl font-bold">Mount Everest</h2> <p>Lorem ipsum dolor sit amet consectetur adipisicing elit. Ipsa suscipit recusandae ipsam facere porro placeat?</p> </div> </div> </div> <div class="swiper-slide"> <div> <img src="https://mmatnepal.com/public/trekkings/Fx0AmCdzWuO84b2z79Nd.jpg" class="w-full" alt=""> </div> </div> </div> <!-- If we need pagination --> <div class="swiper-pagination"></div> <!-- If we need navigation buttons --> <div class="swiper-button-prev"></div> <div class="swiper-button-next"></div> <!-- If we need scrollbar --> <div class="swiper-scrollbar"></div> </div> <div class="flex bg-amber-500 px-14 items-center"> <p class="p-4 bg-amber-600 text-white">Notices</p> <marquee onmouseover="this.stop()" onmouseout="this.start()" class="text-white font-bold">This is a notice</marquee> </div> <!-- Start of Services --> <div class="py-10"> <h2 class="text-center text-3xl font-bold">Our Services</h2> <p class="text-center text-gray-600">Here are our services</p> <div class="swiper swiper2"> <!-- Additional required wrapper --> <div class="swiper-wrapper"> <!-- Slides --> <div class="swiper-slide"> <div> <img src="https://mmatnepal.com/public/trekkings/Fx0AmCdzWuO84b2z79Nd.jpg" class="w-full" alt=""> </div> </div> <div class="swiper-slide"> <div> <img src="https://mmatnepal.com/public/trekkings/Fx0AmCdzWuO84b2z79Nd.jpg" class="w-full" alt=""> </div> </div> <div class="swiper-slide"> <div> <img src="https://mmatnepal.com/public/trekkings/Fx0AmCdzWuO84b2z79Nd.jpg" class="w-full" alt=""> </div> </div> <div class="swiper-slide"> <div> <img src="https://mmatnepal.com/public/trekkings/Fx0AmCdzWuO84b2z79Nd.jpg" class="w-full" alt=""> </div> </div> <div class="swiper-slide"> <div> <img src="https://mmatnepal.com/public/trekkings/Fx0AmCdzWuO84b2z79Nd.jpg" class="w-full" alt=""> </div> </div> </div> <!-- If we need pagination --> <div class="swiper-pagination"></div> <!-- If we need navigation buttons --> <div class="swiper-button-prev"></div> <div class="swiper-button-next"></div> <!-- If we need scrollbar --> <div class="swiper-scrollbar"></div> </div> </div> <!-- End of Services --> <div class="grid grid-cols-2"> <p class="p-6 bg-blue-800 text-white font-bold text-3xl text-center">About Majestic Mountain Adventure & Tours</p> <p class="p-6 bg-amber-500 text-white font-bold text-3xl text-center">Why Travel With Us ?</p> </div> <!-- Start of Packages --> <div class="py-10 bg-gray-100"> <h2 class="text-center text-3xl font-bold">Our Packages</h2> <p class="text-center text-gray-600">Enjoy your time with our wonderful packages</p> <div class="grid grid-cols-3 gap-10 p-14"> <div class="bg-white hover:scale-105 duration-300 animate__animated animate__fadeInUp wow"> <img src="https://mmatnepal.com/public/packages/VbSBYex4qLjU48HITyxb.jpg" alt=""> <div class="flex justify-between items-center py-4 px-2"> <h2 class="font-bold text-2xl">Bhutan Tour</h2> <p>3 Nights/ 4 days</p> </div> </div> <div class="bg-white hover:scale-105 duration-300"> <img src="https://mmatnepal.com/public/packages/VbSBYex4qLjU48HITyxb.jpg" alt=""> <div class="flex justify-between items-center py-4 px-2"> <h2 class="font-bold text-2xl">Bhutan Tour</h2> <p>3 Nights/ 4 days</p> </div> </div> <div class="bg-white hover:scale-105 duration-300"> <img src="https://mmatnepal.com/public/packages/VbSBYex4qLjU48HITyxb.jpg" alt=""> <div class="flex justify-between items-center py-4 px-2"> <h2 class="font-bold text-2xl">Bhutan Tour</h2> <p>3 Nights/ 4 days</p> </div> </div> </div> <div class="text-center py-10"> <a href="" class="bg-amber-500 px-10 uppercase py-4 rounded-lg hover:bg-amber-600 hover:text-white duration-300">See More</a> </div> </div> <!-- End of Packages --> <div class="grid lg:grid-cols-4 md:grid-cols-2 gap-10 px-14 py-10"> <div class="p-5 text-center"> <i class="ri-car-fill text-7xl text-amber-500"></i> <h2 class="font-bold text-3xl">Comfortable Journey</h2> <p class="text-gray-600 mt-5">Have a wonderful and enjoyable journey with our travels and tours packages.</p> </div> <div class="p-5 text-center"> <i class="ri-car-fill text-7xl text-amber-500"></i> <h2 class="font-bold text-3xl">Comfortable Journey</h2> <p class="text-gray-600 mt-5">Have a wonderful and enjoyable journey with our travels and tours packages.</p> </div> <div class="p-5 text-center"> <i class="ri-car-fill text-7xl text-amber-500"></i> <h2 class="font-bold text-3xl">Comfortable Journey</h2> <p class="text-gray-600 mt-5">Have a wonderful and enjoyable journey with our travels and tours packages.</p> </div> <div class="p-5 text-center"> <i class="ri-car-fill text-7xl text-amber-500"></i> <h2 class="font-bold text-3xl">Comfortable Journey</h2> <p class="text-gray-600 mt-5">Have a wonderful and enjoyable journey with our travels and tours packages.</p> </div> </div> <!-- Start of Flights --> <div class="py-10 bg-gray-100 grid md:grid-cols-2 gap-10 px-14"> <div> <h2 class="text-blue-700 font-bold text-3xl text-center">Top <span class="text-amber-500">Domestic</span> Flights</h2> <p class="font-bold text-center text-gray-700">List of Domestic Flights</p> <div class="grid grid-cols-2 mt-4 group"> <div class="h-full flex items-center justify-center text-center text-white font-bold text-lg bg-blue-800 group-hover:bg-amber-500"> Bharatpur <br>to <br> Kathmandu </div> <div class="h-72 overflow-hidden"> <img src="https://mmatnepal.com/public/flights/1aTgX4jTll6QAAfE7iko.jpg" class="group-hover:scale-105 object-cover h-72 w-full duration-300" alt=""> </div> </div> <div class="grid grid-cols-2 mt-4 group"> <div class="h-full flex items-center justify-center text-center text-white font-bold text-lg bg-blue-800 group-hover:bg-amber-500"> Bharatpur <br>to <br> Kathmandu </div> <div class="h-72 overflow-hidden"> <img src="https://mmatnepal.com/public/flights/1aTgX4jTll6QAAfE7iko.jpg" class="group-hover:scale-105 object-cover h-72 w-full duration-300" alt=""> </div> </div> </div> <div> <h2 class="text-blue-700 font-bold text-3xl text-center">Top <span class="text-amber-500">Domestic</span> Flights</h2> <p class="font-bold text-center text-gray-700">List of Domestic Flights</p> <div class="grid grid-cols-2 mt-4 group"> <div class="h-full flex items-center justify-center text-center text-white font-bold text-lg bg-blue-800 group-hover:bg-amber-500"> Bharatpur <br>to <br> Kathmandu </div> <div class="h-72 overflow-hidden"> <img src="https://mmatnepal.com/public/flights/1aTgX4jTll6QAAfE7iko.jpg" class="group-hover:scale-105 object-cover h-72 w-full duration-300" alt=""> </div> </div> <div class="grid grid-cols-2 mt-4 group"> <div class="h-full flex items-center justify-center text-center text-white font-bold text-lg bg-blue-800 group-hover:bg-amber-500"> Bharatpur <br>to <br> Kathmandu </div> <div class="h-72 overflow-hidden"> <img src="https://mmatnepal.com/public/flights/1aTgX4jTll6QAAfE7iko.jpg" class="group-hover:scale-105 object-cover h-72 w-full duration-300" alt=""> </div> </div> </div> </div> <!-- End of Flights --> <!-- Start of Trekking --> <div class="py-10 bg-gray-100"> <h2 class="text-center text-3xl font-bold">Our Trekkings</h2> <p class="text-center text-gray-600">Explore different places with our wonderful trekking packages.</p> <div class="grid lg:grid-cols-3 md:grid-cols-2 gap-10 p-14"> <div class="bg-white hover:-translate-y-5 duration-300 cursor-pointer shadow-lg rounded-lg"> <img src="https://mmatnepal.com/public/packages/VbSBYex4qLjU48HITyxb.jpg" class="rounded-t-lg h-72 object-cover w-full" alt=""> <div class="flex justify-between items-center py-4 px-2"> <h2 class="font-bold text-2xl">Bhutan Tour</h2> <p>3 Nights/ 4 days</p> </div> </div> <div class="bg-white hover:-translate-y-5 duration-300 cursor-pointer shadow-lg rounded-lg"> <img src="https://mmatnepal.com/public/packages/VbSBYex4qLjU48HITyxb.jpg" class="rounded-t-lg h-72 object-cover w-full" alt=""> <div class="flex justify-between items-center py-4 px-2"> <h2 class="font-bold text-2xl">Bhutan Tour</h2> <p>3 Nights/ 4 days</p> </div> </div> <div class="bg-white hover:-translate-y-5 duration-300 cursor-pointer shadow-lg rounded-lg"> <img src="https://mmatnepal.com/public/packages/VbSBYex4qLjU48HITyxb.jpg" class="rounded-t-lg h-72 object-cover w-full" alt=""> <div class="flex justify-between items-center py-4 px-2"> <h2 class="font-bold text-2xl">Bhutan Tour</h2> <p>3 Nights/ 4 days</p> </div> </div> </div> <div class="text-center py-10"> <a href="" class="bg-amber-500 px-10 uppercase py-4 rounded-lg hover:bg-amber-600 hover:text-white duration-300">See More</a> </div> </div> <!-- End of Trekking --> <footer class="pt-10"> <div class="bg-blue-700 text-white px-14 py-8 grid md:grid-cols-3 gap-10"> <div> <h2 class="text-2xl font-bold">Contact Us</h2> <p class="font-bold text-xl">Magestic Mountain Adventure & Tours</p> <p class="mt-4">Bharatpur, Chitwan <br> +977-9855090899 <br> [email protected]</p> </div> <div> <h2 class="text-2xl font-bold">Subscribe Newsletter</h2> <form action=""> <input type="text" placeholder="Email Address" class="bg-transparent border rounded-lg p-2 block placeholder:text-white"> <button class="block mt-2 bg-white px-10 text-black rounded-lg py-2">Subscribe</button> </form> </div> <div> <h2 class="text-2xl font-bold mb-2">Certificate & Partners</h2> <img src="https://mmatnepal.com/images/footer-image.jpeg" alt=""> </div> </div> <div class="px-14 py-4 bg-blue-900 text-gray-200 flex md:flex-row flex-col justify-between items-center"> <p> &copy; 2024 All Right Reserved | MMAT NEPAL | Designed and Developed By BITS</p> <div class="flex items-center"> We accept: <img src="https://mmatnepal.com/images/visa.jpeg" alt=""> <img src="https://mmatnepal.com/images/connectips.png" alt=""> <img src="https://mmatnepal.com/images/esewa.png" alt=""> </div> </div> </footer> <script src="https://cdnjs.cloudflare.com/ajax/libs/wow/1.1.2/wow.min.js" integrity="sha512-Eak/29OTpb36LLo2r47IpVzPBLXnAMPAVypbSZiZ4Qkf8p/7S/XRG5xp7OKWPPYfJT6metI+IORkR5G8F900+g==" crossorigin="anonymous" referrerpolicy="no-referrer"></script> <script> new WOW().init(); </script> <script> const swiper = new Swiper('.swiper1', { // Optional parameters direction: 'horizontal', loop: true, autoplay: { delay: 3000, }, // If we need pagination pagination: { el: '.swiper-pagination', }, // Navigation arrows navigation: { nextEl: '.swiper-button-next', prevEl: '.swiper-button-prev', }, // And if we need scrollbar scrollbar: { el: '.swiper-scrollbar', }, }); </script> <script> const swiper2 = new Swiper('.swiper2', { // Optional parameters direction: 'horizontal', loop: true, autoplay: { delay: 3000, }, slidesPerView: 3, spaceBetween: 30, // If we need pagination pagination: { el: '.swiper-pagination', }, // Navigation arrows navigation: { nextEl: '.swiper-button-next', prevEl: '.swiper-button-prev', }, // And if we need scrollbar scrollbar: { el: '.swiper-scrollbar', }, }); </script> <script> function controlNav() { var menu = document.getElementById('menu'); if(menu.style.display == 'block') { menu.style.display = 'none'; } else { menu.style.display = 'block'; } } </script> </body> </html>
// pages/api/create.js import { NextRequest, NextResponse } from "next/server"; import { connectToDatabase, DATABASE_NAME, COLLECTION_NAME, OTHER_SONGS_COLLECTION } from "@/lib/mongo"; import { Cities, LeaderBoardResponse, LeaderboardSong, SongScore } from "@/lib/types"; import { ynkSongs } from "@/lib/types"; export async function GET(req: NextRequest, res: NextResponse) { try { let city = req.nextUrl.searchParams.get("city") as Cities const client = await connectToDatabase(); const db = client.db(DATABASE_NAME); const collection = db.collection(OTHER_SONGS_COLLECTION); let result: any[] if (city === "steve") { city = "steve" result = await collection.aggregate([ { $unwind: "$songs" }, { $group: { _id: "$songs.id", id: { $first: "$songs.id" }, name: { $first: "$songs.name" }, album: { $first: "$songs.album"}, points: { $sum: "$songs.points"} } } ]).toArray() } else { result = await collection.aggregate([ { $unwind: "$songs" }, { $match: { city } }, { $group: { _id: "$songs.id", id: { $first: "$songs.id" }, name: { $first: "$songs.name" }, album: { $first: "$songs.album"}, points: { $sum: "$songs.points"} } } ]).toArray() } if (result.length === 0) { let response: LeaderBoardResponse & {success: boolean} = { city, success: true, total: 0, songs: [] } return NextResponse.json(response, { status: 200}) } client.close(); const total: number = Object.values(result).reduce((acc, curr) => acc+curr.points, 0) const songs = result.map(song => { const randomNumber = Math.floor(Math.random() * 100); const randomScore = { id: song.id, name: song.name, album: song.album, points: song.points + randomNumber } return randomScore }) let response: LeaderBoardResponse & {success: boolean} = { city, success: true, total, songs: songs as SongScore[] } return NextResponse.json(response, { status: 200}) } catch (error) { console.log(error) return NextResponse.json({success: false}, {status: 500}) } };
<!DOCTYPE HTML> <html lang="en" xmlns:th="http://www.thymeleaf.org" > <head> <meta charset="utf-8"> <title>ISIMA</title> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta name="description" content=""> <meta name="author" content=""> <!-- Styles --> <link href="css/bootstrap.css" th:href="@{/css/bootstrap.css}" rel="stylesheet"> <link href="css/style.css" th:href="@{/css/style.css}" rel="stylesheet"> <link rel='stylesheet' id='prettyphoto-css' href="css/prettyPhoto.css" th:href="@{/css/prettyPhoto.css}" type='text/css' media='all'> <link href="css/fontello.css" th:href="@{/css/fontello.css}" type="text/css" rel="stylesheet"> <!--[if lt IE 7]> <link href="css/fontello-ie7.css" type="text/css" rel="stylesheet"> <![endif]--> <!-- Google Web fonts --> <link href='http://fonts.googleapis.com/css?family=Quattrocento:400,700' th:href='@{http://fonts.googleapis.com/css?family=Quattrocento:400,700}' rel='stylesheet' type='text/css'> <link href='http://fonts.googleapis.com/css?family=Patua+One' th:href='@{http://fonts.googleapis.com/css?family=Patua+One}' rel='stylesheet' type='text/css'> <link href='http://fonts.googleapis.com/css?family=Open+Sans' th:href='@{http://fonts.googleapis.com/css?family=Open+Sans}' rel='stylesheet' type='text/css'> <script type="text/javascript" th:src="@{http://code.jquery.com/jquery-1.10.2.js}"> </script> <script type="text/javascript" th:src="@{http://code.jquery.com/ui/1.10.3/jquery-ui.js}"> </script> <link rel="stylesheet" th:href="@{http://code.jquery.com/ui/1.10.2/themes/smoothness/jquery-ui.css}" /> <style type="text/css"> table { border-collapse: collapse; width: 70%; padding: 15px; font-size: 18px; font-style:italic; text-align: center; border-right-style: solid; border-spacing: 15px; margin: 0 auto; } caption { font-size: 23px; font-style:italic; text-align: center; color: black; } th{ background-color:white; color: black; } th,td { border: 2px solid #ddd; padding: 15px; color : black; } a:link {color: red;} a:visited {color: red;} a:hover {color: black;} a:active {color: black;} </style> </head> <body> <div class="navbar-wrapper"> <div class="navbar navbar-inverse navbar-fixed-top"> <div class="navbar-inner"> <div class="container"> <!-- Responsive Navbar Part 1: Button for triggering responsive navbar (not covered in tutorial). Include responsive CSS to utilize. --> <a class="btn btn-navbar" data-toggle="collapse" data-target=".nav-collapse"> <span class="icon-bar"></span> <span class="icon-bar"></span> <span class="icon-bar"></span> </a> <h1 class="brand"><a th:href="@{/}">ISIMA</a></h1> <!-- Responsive Navbar Part 2: Place all navbar contents you want collapsed withing .navbar-collapse.collapse. --> <nav class="pull-right nav-collapse collapse"> <ul id="menu-main" class="nav"> <li><a title="ACCEUIL" th:href="@{/}">ACCEUIL</a></li> <li><a title="EXAMEN" th:href="@{/examen/form}">EXAMEN</a></li> <li><a title="ENSEIGNANT" th:href="@{/enseignant/form}">ENSEIGNANT</a></li> <li><a title="SALLE" th:href="@{/salle/form}">SALLE</a></li> <li><a title="MATIERE" th:href="@{/matiere/form}">MATIERE</a></li> <li><a title="Calendrier" th:href="@{/calendrier/fichierCalendrier}">CALENDRIER</a></li> <li><a title="Fiche de Suivie" th:href="@{/fichSuivie/fichierFichSuivie}">Fich Suivie</a></li> <li><a title="Déconnexion" th:href="@{/logout}">DECONNEXION</a></li> </ul> </nav> </div> <!-- /.container --> </div> <!-- /.navbar-inner --> </div> <!-- /.navbar --> </div> <!-- /.navbar-wrapper --> <div id="top"></div> <!-- ******************** HeaderWrap ********************--> <div id="headerwrap"> <header class="clearfix"> <h1><span>ISIMA</span> INSTITUT SUPERIER DE L'INFORMATIQUE </h1> <div class="container"> <div class="row"> <div class="span12"> <form th:action="@{/enseignant/recherche}" th:method="get"> <input type="text" name="nom" class="cform-text" size="40" title="your email"/> <input type="submit" value="RECHERCHER" class="cform-submit"/> </form> <form>  <div class="panel panel-primary" th:if="${pageEnseignants != null}" > <div class="panel-body" > <table> <thead> <caption >Listes Des Enseignants</caption> <tr> <th> Nom</th> <th> Email</th> <th> Grade</th> </tr> </thead> <tbody> <tr th:each="enseignant : ${pageEnseignants.content}"> <td th:text="${enseignant.nom}"></td> <td th:text="${enseignant.email}"></td> <td th:text="${enseignant.grade}"></td> </tr> </tbody> </table> <div style="margin-left: 2%"> <ul class="nav nav-pills"> <li th:each="p,status:${pages}" th:class="${page}==@{pageCourante}?'active':''"> <a th:href="@{/enseignant/fichierEnsei(page=${status.index})}" th:text="${status.index}"></a> </li> </ul> </div> </div> </div>    </div> </div> <br> <br> <br> </form> <form>  <div class="panel panel-primary" th:if="${pageMatieres != null}" > <div class="panel-body" > <table> <thead> <caption >Listes Des Matieres</caption> <tr> <th> Matiere</th> <th> Enseignant</th> <th> Coefficiant </th> <th>Niveau</th> </tr> </thead> <tbody> <tr th:each="matiere : ${pageMatieres.content}"> <td th:text="${matiere.nomMatiere}"></td> <td th:text="${matiere.enseignant.nom}"></td> <td th:text="${matiere.coe}"></td> <td th:text="${matiere.niveau}"></td> </tr> </tbody> </table> <div style="margin-left: 2%"> <ul class="nav nav-pills"> <li th:each="p,status:${pages}" th:class="${page}==@{pageCourante}?'active':''"> <a th:href="@{/matiere/fichierMatiere(page=${status.index})}" th:text="${status.index}"></a> </li> </ul> </div> </div> </div>    </div> </div> <br> <br> <br> </form> <div class="row"> <div class="span12"> <ul class="icon"> <li><a href="https://www.facebook.com/ISIMa.Officiel/" target="_blank"><i class="icon-facebook-circled"></i></a></li> <li><a href="#" target="_blank"><i class="icon-twitter-circled"></i></a></li> <li><a href="#" target="_blank"><i class="icon-skype-circled"></i></a></li> </ul> </div> </div> </header> </div> </BODY> </HTML>
note description: "Fast-CGI HTTP headers and custom headers" author: "Finnian Reilly" copyright: "Copyright (c) 2001-2022 Finnian Reilly" contact: "finnian at eiffel hyphen loop dot com" license: "MIT license (See: en.wikipedia.org/wiki/MIT_License)" date: "2023-08-14 10:40:12 GMT (Monday 14th August 2023)" revision: "24" class FCGI_HTTP_HEADERS inherit EL_REFLECTIVELY_SETTABLE rename foreign_naming as Snake_case_upper, make_default as make, field_included as is_any_field redefine make end EL_SETTABLE_FROM_ZSTRING rename make_default as make redefine set_table_field end EL_MODULE_ITERABLE; EL_MODULE_NAMING create make feature {NONE} -- Initialization make do Precursor create custom_table.make (3) end feature -- Access as_table (translater: EL_NAME_TRANSLATER): HASH_TABLE [ZSTRING, STRING] -- table of all non-empty headers with name-keys adjusted to use hyphen word separator -- if `kebab_names' is true local table: like field_table; value: ZSTRING do table := field_table create Result.make (custom_table.count + 7) from table.start until table.after loop value := field_string (table.item_for_iteration) if not value.is_empty then Result [translater.exported (table.key_for_iteration)] := value end table.forth end from custom_table.start until custom_table.after loop value := custom_table.item_for_iteration if not value.is_empty then Result [translater.exported (custom_table.key_for_iteration)] := value end custom_table.forth end end custom (name: STRING): ZSTRING local kebab_name: STRING do create kebab_name.make (name.count) Naming.from_kebab_case (name, kebab_name) if custom_table.has_key (kebab_name) then Result := custom_table.found_item else create Result.make_empty end end selected (name_list: ITERABLE [STRING]; translater: EL_NAME_TRANSLATER): HASH_TABLE [ZSTRING, STRING] -- returns table of field values for keys present in `name_list' local l_name: STRING do create Result.make (Iterable.count (name_list)) across name_list as name loop l_name := translater.imported (name.item) if field_table.has_key_8 (l_name) then Result.extend (field_string (field_table.found_item), name.item) else if custom_table.has_key (l_name) then Result.extend (custom_table.found_item, name.item) end end end end feature -- Access attributes accept: ZSTRING accept_encoding: ZSTRING accept_language: ZSTRING authorization: ZSTRING cache_control: ZSTRING connection: ZSTRING content_length: INTEGER content_type: ZSTRING cookie: ZSTRING from_: ZSTRING -- Trailing `_' to distinguish from Eiffel keyword host: ZSTRING referer: ZSTRING upgrade_insecure_requests: ZSTRING user_agent: ZSTRING x_forwarded_host: ZSTRING feature -- Element change set_accept (a_accept: ZSTRING) do accept := a_accept end set_accept_encoding (a_accept_encoding: ZSTRING) do accept_encoding := a_accept_encoding end set_accept_language (a_accept_language: ZSTRING) do accept_language := a_accept_language end set_authorization (a_authorization: ZSTRING) do authorization := a_authorization end set_cache_control (a_cache_control: ZSTRING) do cache_control := a_cache_control end set_connection (a_connection: ZSTRING) do connection := a_connection end set_content_length (a_content_length: INTEGER) do content_length := a_content_length end set_content_type (a_content_type: ZSTRING) do content_type := a_content_type end set_cookie (a_cookie: ZSTRING) do cookie := a_cookie end set_custom (name: STRING; value: ZSTRING) local kebab_name: STRING do create kebab_name.make (name.count) Naming.from_kebab_case (name, kebab_name) custom_table [kebab_name] := value end set_from (a_from: ZSTRING) do from_ := a_from end set_host (a_host: ZSTRING) do host := a_host end set_referer (a_referer: ZSTRING) do referer := a_referer end set_upgrade_insecure_requests (a_upgrade_insecure_requests: ZSTRING) do upgrade_insecure_requests := a_upgrade_insecure_requests end set_user_agent (a_user_agent: ZSTRING) do user_agent := a_user_agent end wipe_out do reset_fields custom_table.wipe_out content_length := -1 end feature {NONE} -- Implementation set_table_field (table: like field_table; name: STRING; value: ZSTRING) -- set field with name do Precursor (table, name, value) if not table.found then custom_table.extend (value, name.as_lower) end end feature {NONE} -- Internal attributes custom_table: HASH_TABLE [ZSTRING, STRING] note option: transient attribute end -- custom_table fields prefixed with x_ feature {NONE} -- Constants Snake_case_upper: EL_SNAKE_CASE_TRANSLATER once Result := {EL_CASE}.Upper end end
# game_controller.py from database.models import Game, db, Protagonist, AlbumTheme from typing import Optional, Dict, Any import json from datetime import datetime # from generate.qinghua_completions import init_game_plot import generate.qinghua_completions as gpt_completions def add_game(user_id, protagonist_id, theme_id, content=None, prompt_history=None): # 获取主角信息 protagonist_query = Protagonist.query protagonist_query = protagonist_query.filter_by(id=protagonist_id, valid='1') protagonist = protagonist_query.first() # 获取故事主题信息 theme_query = AlbumTheme.query theme_query = theme_query.filter_by(id=theme_id, valid='1') theme = theme_query.first() gpt = gpt_completions.init_game_plot(protagonist.name) # print(gpt['add']) new_content = json.loads(gpt['add']) new_prompt_history = [{ 'role': 'user', 'content': f"1、我希望你扮演一个基于文本的冒险游戏(游戏背景:{theme.theme},游戏主角:{protagonist.name + ',' +protagonist.description},故事概述:{theme.description});" "2、你要基于游戏背景,游戏主角及故事描述,创建8个回合的游戏,你将回复故事情节内容描述及 3 个选项;" "3、你需要首先给我第一个场景及情节描述,并给我提供 3 个选项;" "4、如果我回复“换一换”,则重新生成当前回合的故事情节内容描述及选项(round、chapter不变,content及choice内容重新生成);" "5、如果我回复选项中的其中一个(选项序号),则继续生成下一回合内容(round、chapter、content及choice改变,根据选项生成下一回合所需内容);" "6、如果我回复“自定义”,则根据“自定义”的内容继续生成下一回合内容(round、chapter、content及choice改变,根据自定义内容生成下一回合所需内容);" "7、每个回合的故事情节描述必须控制在 80 字以内。故事需要在第八回合结束(在round:8,chapter:最终结局时结束);" "8、故事的八个回合的情节结构分别是:故事的开端、情节推进、矛盾产生、关键决策、情节发展、高潮冲突、结局逼近、最终结局,八个情节按此顺序逐层递进,缺一不可;" "9、你给我的故事情节描述需要非常有趣好玩,可以带悬疑解密,也可以搞怪搞笑,前后逻辑有联系;" "10、你返回给我的内容包含如下:" "1)round:回合数,是整数,从 1 开始递增,1代表第一回合,2代表第二回合,以此类推;如果回复“换一换”则保持不变(继续在当前回合);" "2)chapter:章节名,枚举值,故事的开端(round:1,chapter:故事的开端)、情节推进(round:2,chapter:情节推进)、" "矛盾产生(round:3,chapter:矛盾产生)、关键决策((round:4,chapter:关键决策))、情节发展((round:5,chapter:情节发展))、" "高潮冲突(round:6,chapter:高潮冲突)、结局逼近(round:7,chapter:解决逼近)、最终结局(round:8,chapter:最终结局);" "3)content:具体的故事情节描述内容;" "11、返回的内容输出成 json 的格式,健值对参考上述序号9的内容(注意:你输出的内容只需要 json 格式返回,其他格式内容不需要返回);" "12、注意,请严格按照下面示例的格式输出(仅参考输出格式,内容请严格按照上述 1-10 点要求创作),示例如下:" "{\"round\":1,\"chapter\":\"故事的开端\",\"content\":\"你收到了霍格沃茨的入学通知书,搭乘霍格沃茨特快列车来到" "了这所神秘的魔法学校。列车穿过山峦和森林,最后抵达了你的目的地。远远望去,霍格沃茨魔法学校屹立在一座高高的山顶上," "城堡式的建筑气势恢宏,令人叹为观止。你怀揣着激动的心情,跟随其他新生一起走下列车,准备进入学校开始新的魔法" "生活。\",\"choice\":[\"a. 走进学校大门\",\"b. 先去参观大礼堂\",\"c. 沿着湖边小路走\"]}" "13、输出之前,请仔细检查一次是否均满足上述所说的 12 条规则再输出。" },{ 'role': 'assistant', 'content': gpt['add'] }] # # 如果content和prompt_history没有提供,使用默认值 # if content is None: # content = [ # { # "round": 1, # "chapter": "故事的开端", # "content": f"{protagonist.name}是一位年轻的勇者,他听说白雪公主被邪恶的巨龙抓走了,于是决定去拯救她。他带着他的弓和箭,开始了这段冒险之旅。" # "他穿过一片阴暗的森林,攀过了险峻的山峰,最后来到了巨龙的巢穴。他看到白雪公主被囚禁在一个坚固的笼子里,他决定救她出来。", # "choice": ["a. 使用魔法攻击巨龙", "b. 偷偷寻找巨龙的弱点", "c. 用食物引开巨龙"] # } # ] # # if prompt_history is None: # prompt_history = [{"role": "user", "content": f"1、 我希望你扮演一个基于文本的冒险游戏( 游戏主题: {protagonist.name}拯救白雪公主的故事," # f"主角: {protagonist.name}); 2、游戏总共8回合,你将回复故事情节内容描述及3个选项。" # "您将回复故事情节内容的描述;3、你需要首先给我第一个场景及情节描述," # "并给我提供3个选项;4、如果我回复选项中的其中一个(选项序号)," # "则继续生成下一回合内容;5、如果我回复换“换一换”,则重新生成当前回合的故事" # "情节内容描述及选项;6、每个回合的故事情节必须控制在80字以内。故事需要在八" # "个回合内结束;7、故事的8个情节结构分别是故事的开端、情节推进、矛盾产生、" # "关键决策、情节发展、高潮冲突、结局逼近、最终结局,8个情节按此顺序逐层递进;" # "8、你给我的情节需要有趣好玩,适合儿童阅读,前后逻辑有联系;" # "9、你返回给我的内容包含如下:1)round:是整数,从1开始递增,如果“换一换”" # "则保持不变;2)chapter:枚举值:分别是故事的开端、情节推进、矛盾产生、" # "关键决策、情节发展、高潮冲突、结局逼近、最终结局;3)content:具体的故" # "事情节描述内容;4)choice: 故事对应的3个选项,用a、b、c英文字母序号开" # "头(故事的最后一个回合最后一话不提供选项选择)10、返回的内容封装成json" # "的格式,健值对参考上述序号9的内容(只需要json格式返回,其他格式内容不需" # "要返回)11、注意,请严格按照下面示例的格式,内容请按照上述1-10点要求创作," # "示例:{\"round\":1,\"chapter\":\"故事的开端\",\"content\":\"你" # "收到了霍格沃茨的入学通知书,搭乘霍格沃茨特快列车来到了这所神秘的魔法学校。" # "列车穿过山峦和森林,最后抵达了你的目的地。远远望去,霍格沃茨魔法学校屹立在" # "一座高高的山顶上,城堡式的建筑气势恢宏,令人叹为观止。你怀揣着激动的心情," # "跟随其他新生一起走下列车,准备进入学校开始新的魔法生活。\",\"choice\":" # "[\"a. 走进学校大门\",\"b. 先去参观大礼堂\",\"c. 沿着湖边小路走\"]}" # ""}, {"role": "assistant", "content": "{\"round\":1,\"chapter\"" # ":\"故事的开端\",\"content\":" # "\"人杰是一位年轻的勇者,他听说" # "白雪公主被邪恶的巨龙抓走了," # "于是决定去拯救她。他带着他的剑" # "和盾牌,开始了这段冒险之旅。" # "他穿过了森林,越过了山脉," # "最后来到了巨龙的巢穴。他看到" # "白雪公主被囚禁在一个笼子里," # "他决定救她出来。\",\"cho" # "ice\":[\"a. 直接攻击" # "巨龙\",\"b. 先找到" # "巨龙的弱点\",\"c. 用食物引开巨龙\"]}"}] # # 创建新的Game对象 new_game = Game( user_id=user_id, protagonist_id=protagonist_id, theme_id=theme_id, content=json.dumps([new_content],ensure_ascii=False), # 序列化为JSON字符串 prompt_history=json.dumps(new_prompt_history,ensure_ascii=False), # 序列化为JSON字符串 created_at=datetime.utcnow(), updated_at=datetime.utcnow(), valid=True, if_finish=False ) # 添加到数据库 db.session.add(new_game) db.session.commit() # 返回新创建的游戏的ID return new_game.id def get_game(id: int) -> dict: game_query = Game.query if id: game_query = game_query.filter_by(id=id, valid='1') game = game_query.first() # 根据查询结果返回相应的值 if game: return { "id": game.id, "user_id": game.user_id, "theme_id": game.theme_id, "protagonist_id": game.protagonist_id, "content": game.content, "created_at": game.created_at, "updated_at": game.updated_at, "valid": game.valid, "if_finish": game.if_finish, "prompt_history": game.prompt_history, } else: return {} def edit_game(id: int, user_id: Optional[int] = None, protagonist_id: Optional[int] = None, theme_id: Optional[int] = None, content: Optional[str] = None, if_finish: Optional[str] = None, prompt_history: Optional[str] = None) -> Dict[str, Any]: game_query = Game.query if id: game_query = game_query.filter_by(id=id, valid='1') game = game_query.first() # 根据查询结果返回相应的值 if game: if user_id: game.user_id = user_id if protagonist_id: game.protagonist_id = protagonist_id if theme_id: game.theme_id = theme_id if if_finish: game.if_finish = if_finish if content: game.content = content if prompt_history: game.prompt_history = prompt_history db.session.commit() return { "id": game.id, "user_id": game.user_id, "theme_id": game.theme_id, "protagonist_id": game.protagonist_id, "content": game.content, "created_at": game.created_at, "updated_at": game.updated_at, "valid": game.valid, "if_finish": game.if_finish, "prompt_history": game.prompt_history, } else: return {} def del_game(): return '' def reset_game_plot(game_id): game_query = Game.query if game_id: game_query = game_query.filter_by(id=game_id, valid='1') game = game_query.first() # 根据查询结果返回相应的值 if game: content_arr = json.loads(game.content) prompt_history_arr = json.loads(game.prompt_history) # print(content_arr) # print(prompt_history_arr) game.content = json.dumps([content_arr[0]], ensure_ascii=False) game.prompt_history = json.dumps(prompt_history_arr[:2], ensure_ascii=False) db.session.commit() return { "id": game.id, "user_id": game.user_id, "theme_id": game.theme_id, "protagonist_id": game.protagonist_id, "content": game.content, "created_at": game.created_at, "updated_at": game.updated_at, "valid": game.valid, "if_finish": game.if_finish, "prompt_history": game.prompt_history, } else: return {} def is_json(myjson): try: json_object = json.loads(myjson) except json.JSONDecodeError: return False return True def save_game_data(user_id, theme, protagonist, game_data): theme = json.loads(theme) protagonist = json.loads(protagonist) prompt_history = json.loads(game_data) # print('history:',prompt_history) new_game = Game( user_id=user_id, protagonist_id=protagonist['id'], theme_id=theme['id'], content=json.dumps([json.loads(prompt_history[-1]['content'])], ensure_ascii=False), prompt_history=json.dumps(prompt_history, ensure_ascii=False), created_at=datetime.utcnow(), updated_at=datetime.utcnow(), valid=True, if_finish=False ) # 添加到数据库 db.session.add(new_game) db.session.commit() print(new_game.id) # 返回新创建的游戏的ID return new_game.id
<%@ page isELIgnored="false" %> <%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8" %> <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %> <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> <link rel="stylesheet" href="${pageContext.request.contextPath}/resources/css/style.css"> <link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-rbsA2VBKQhggwzxH7pPCaAqO46MgnOM80zW1RWuH61DGLwZJEdK2Kadq2F9CUG65" crossorigin="anonymous"> <link rel="stylesheet" href="https://fonts.googleapis.com/css2?family=Material+Symbols+Outlined:opsz,wght,FILL,GRAD@48,400,0,0" /> <script src="https://kit.fontawesome.com/92ef16d217.js" crossorigin="anonymous"></script> </head> <body> <style> .cancel { background-color: red; } </style> <!-- Navbar --> <jsp:include page="/WEB-INF/views/nav.jsp" /> <!-- Navbar --> <!-- admin main --> <div class="container admin"> <table class="table table-hover"> <thead> <tr> <th scope="col">ID</th> <th scope="col">Hình ảnh</th> <th scope="col">Tên sản phẩm</th> <th scope="col">Giá bán</th> <th scope="col">Đã bán</th> <th scope="col">Tác vụ</th> </tr> </thead> <tbody> <c:forEach var="product" items="${products}"> <tr> <th scope="row">${product.id}</th> <td> <img src="${product.image}" alt="Los Angeles" class="admin-img"> </td> <td>${product.name}</td> <td>${product.price}</td> <td>${product.sold_count}</td> <td class="admin-icon"> <div class="row"> <div class="col"> <button class="open-button" onclick="openForm()"> <c:set var="Prod_id" value="${product.id}" /> <i class="fa-solid fa-pen-to-square"></i> </button> </div> <div class="col"> <form method="post" action="/shopping/adminHandle"> <input type="hidden" name="action" value="delete"> <input type="hidden" name="id" value="${product.id}"> <button type="submit">x</button> </form> </div> </div> </td> </tr> </c:forEach> </tbody> </table> <button class="add-button" style="background-color: black;color: white;padding: 1vh 2vh; float: right;" onclick="openAddForm()"> <c:set var="Prod_id" value="${product.id}" /> Thêm hàng hóa </button> </div> <form class="form-edit form-popup" id="myForm" action="/shopping/adminHandle?action=update" method="POST"> <h1 style="text-align: center;">Chỉnh sửa</h1> <label class="form-label" for="id">ID</label> <input name="id" value="${Prod_id}" class="form-control" /> <label class="form-label" for="name">Tên sản phẩm</label> <input name="name" type="text" class="form-control" /> <label class="form-label" for="price">Giá bán</label> <input name="price" type="number" class="form-control" /> <button type="submit" class="btn">Xác nhận</button> <button type="button" class="btn cancel" onclick="closeForm()">Đóng</button> </form> <form class="form-edit form-popup" id="addForm" action="/shopping/adminHandle?action=add" method="POST"> <h1 style="text-align: center;">Thêm hàng hóa</h1> <label class="form-label" for="name">Tên sản phẩm</label> <input name="name" type="text" class="form-control" /> <label class="form-label" for="price">Giá bán</label> <input name="price" type="number" class="form-control" /> <button type="submit" class="btn">Xác nhận</button> <button type="button" class="btn cancel" onclick="closeAddForm()">Đóng</button> </form> <!-- admin main --> <script> function openForm() { document.getElementById("myForm").style.display = "block"; } function closeForm() { document.getElementById("myForm").style.display = "none"; } function openAddForm() { document.getElementById("addForm").style.display = "block"; } function closeAddForm() { document.getElementById("addForm").style.display = "none"; } </script> <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.bundle.min.js" integrity="sha384-kenU1KFdBIe4zVF0s0G1M5b4hcpxyD9F7jL+jjXkk+Q2h455rYXK/7HAuoJl+0I4" crossorigin="anonymous"></script> </body> </html>
# mount 挂载文件系统。 ## 语法 ``` mount [-fnrsvw] [-t fstype] [-o options] device mountpoint ``` ## 命令行选项 - **-t** *fstype* 指示文件系统类型。 ## 例子 显示所有已安装的分区: ```sh $ mount ``` 将硬盘驱动器的第一个分区挂载到现有目录: ```sh $ mount -t ext4 /dev/sda1 /media/data ``` 参考物理磁盘分区卸载: ```sh $ umount /dev/sda1 ``` 参照挂载点卸载: ```sh $ umount /media/data ```
############################################################################## # Helper functions needed to run analyses in Sample Size Estimation using a # Latent Variable Model for Mixed Outcome Co-Primary, Multiple Primary and # Composite Endpoints # # Author: Martina McMenamin # ############################################################################# # Composite endpoint functions -------------------------------------------- #' @param mean.lat overall effect size on the composite using the latent variable model #' @param mean.bin overall effect size on the composite using the standard binary method #' @param var.lat estimated variance of effect using the latent variable model #' @param var.bin variance of effect using the standard binary method #' @param alpha significance level #' @param beta 1-desired power samplesize <- function(mean.lat, mean.bin, var.lat, var.bin, alpha, beta){ n.lat=(var.lat*(qnorm(1-beta)-(qnorm(alpha)))^2)/(mean.lat)^2 n.bin=(var.bin*(qnorm(1-beta)-(qnorm(alpha)))^2)/(mean.bin)^2 return(c(n.lat,n.bin)) } #' @param mean overall effect size on the composite #' @param var variance of effect (standard deviation squared) #' @param alpha significance level #' @param n overall sample size powerfunc<-function(mean,var,alpha,n){ power.lat=pnorm((mean/(sqrt(var/n)))-qnorm(1-alpha)) return(power.lat) } # Family wise error rate for multiple primary endpoints ------------------- #' @param K number of endpoints #' @param n sample size per arm #' @param delta effect size for each outcome #' @param Sigma covariance matrix for the outcomes #' @param SD standard deviation of outcomes #' @param rho correlation between endpoints #' @param adjust logical whether or not to implement Bonferroni correction #' @param sig.level alpha level #' @param power required power FWER <- function (K, n = NULL, delta = NULL, Sigma, SD, rho, adjust, sig.level = 0.025, power = NULL, tol = .Machine$double.eps^0.25) { sig.level = ifelse(adjust == TRUE, sig.level/K, sig.level) if (is.null(power)) { std.effect <- delta/sqrt(diag(Sigma)) z.alpha <- qnorm(1 - sig.level) crit.vals <- z.alpha - sqrt(n/2) * std.effect power <- 1 - pmvnorm(lower = -crit.vals, sigma = Sigma) } if (is.null(n)) { std.effect <- delta/sqrt(diag(Sigma)) z.alpha <- qnorm(1 - sig.level) ssize.fct <- function(n, std.effect, z.alpha, Sigma, power) { crit.vals <- z.alpha - sqrt(n/2) * std.effect pmvnorm(lower = -crit.vals, sigma = Sigma) - (1 - power) } n <- uniroot(ssize.fct, c(2, 1e+05), tol = tol, extendInt = "yes", std.effect = std.effect, z.alpha = z.alpha, Sigma.cor = Sigma, power = power)$root } NOTE <- "n is number in *each* group" METHOD <- "FWER for multiple primary endpoints" structure(list(n = n, delta = delta, SD = sqrt(diag(Sigma)), rho = Sigma[lower.tri(Sigma)], Sigma = Sigma, sig.level = sig.level, FWER = power, note = NOTE, method = METHOD), class = "power.mpe.test") }
import 'package:flutter/material.dart'; import 'package:flutter_svg/svg.dart'; import 'package:fluttertemplate/components/custom_alerts.dart'; import 'package:fluttertemplate/routes/routes.dart'; import 'package:fluttertemplate/widgets/divider.dart'; import 'package:get/get.dart'; import 'package:loading_animation_widget/loading_animation_widget.dart'; import 'package:fluttertemplate/utils/constants.dart'; import 'package:fluttertemplate/widgets/text_field.dart'; class Login extends StatefulWidget { const Login({Key? key}) : super(key: key); @override State<Login> createState() => _LoginState(); } class _LoginState extends State<Login> { bool _isButtonDisabled = false; var usernameController = TextEditingController(); var passwordController = TextEditingController(); void _login(){ String username = usernameController.text.trim(); String password = passwordController.text.trim(); if (username.isEmpty) { showErrorAlert("Username is required!", title: "Hang tight!"); _isButtonDisabled = false; } else if (password.isEmpty) { showErrorAlert("Password is required!", title: "Uh oh.."); _isButtonDisabled = false; } else { setState(() { _isButtonDisabled = true; }); if(username == "test" && password == "test"){ showSuccessAlert(title: "Success", "You are now logged in!"); setState(() { _isButtonDisabled = false; }); Get.toNamed(RouteHelper.getHome()); }else{ showErrorAlert(title: "Server Error", "Try again later!"); setState(() { _isButtonDisabled = false; }); } } } @override Widget build(BuildContext context) { var isDark = MediaQuery.of(context).platformBrightness == Brightness.dark; return Scaffold( body: SafeArea( child: Padding( padding: const EdgeInsets.all(tPadding.tDefaultPadding), child: Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ GestureDetector( onTap: () {Get.back();}, child: Container( padding: EdgeInsets.all(5), decoration: BoxDecoration( color: isDark ? tColors.cardColorDarkLoading : Colors.grey[200], shape: BoxShape.circle ), child: const Icon(Icons.arrow_back), ), ), const SpaceDivider(), Container( child: const Text("Login with Riot Games", style: TextStyle( fontSize: tSizes.titleSize, fontWeight: FontWeight.bold ),), ), const SpaceDivider(), CustomTextField( icon: "assets/icons/email-icon.svg", hint: "Username", txtController: usernameController, password: false, ), CustomTextField( icon: "assets/icons/password_icon.svg", hint: "Password", txtController: passwordController, password: true, ), const SpaceDivider(), GestureDetector( onTap: () { _isButtonDisabled ? null : _login(); }, child: Container( padding: EdgeInsets.all(15), decoration: BoxDecoration( color: isDark ? Colors.white : Colors.black87, borderRadius: BorderRadius.circular(10), ), child: Center( child: _isButtonDisabled ? LoadingAnimationWidget.staggeredDotsWave( color: isDark ? Colors.black87 : Colors.white, size: 21, ) : Text( "Login", style: TextStyle( color: isDark ? Colors.black87 : Colors.white, fontWeight: FontWeight.bold, fontSize: 14, ), ) , ), ), ), ], ), ), ), ); } }
import { ReactNode } from 'react'; import { useNavigate } from 'react-router'; import { useTranslation } from 'react-i18next'; import router from '../../../shared/services/router'; import { useAppDispatch } from '../../../shared/hooks/redux'; import modalObserver from '../../../shared/utils/observers/modalObserver'; import { ModalNamesEnum } from '../../../shared/enums/modalNames.enum'; import { deleteTransport, selfCancelShare, syncUserShare } from '../store/garageThunkV2'; import { ReactComponent as ViewIcon } from '../../../assets/Images/newGarage/action-menu/Eye.svg'; import { ReactComponent as EditIcon } from '../../../assets/Images/newGarage/action-menu/Edit.svg'; import { ReactComponent as ShareIcon } from '../../../assets/Images/newGarage/action-menu/Family.svg'; import { ReactComponent as CoverIcon } from '../../../assets/Images/newGarage/action-menu/Cover.svg'; import { ReactComponent as DeleteIcon } from '../../../assets/Images/newGarage/action-menu/Delete.svg'; import { AssignPeopleSelectValueModel } from '../../../shared/models/assignPeopleSelectValue.model'; import { setLoadingGarage } from '../store/garageSliceV2'; import { RootObjectDataOwner, RootObjectDataUsers } from '../store/types'; type GarageActionMenuType = { isEditor: boolean; isCreator: boolean; isDraft: boolean; isViewer: boolean; }; export type TransportInfo = { transportID: number; vehicleName: string; owner: RootObjectDataOwner; users: RootObjectDataUsers[]; }; // TODO i18n export const useGarageActionMenu = (userStatus: GarageActionMenuType, transportInfo: TransportInfo) => { const dispatch = useAppDispatch(); const navigate = useNavigate(); const { t } = useTranslation(); const deleteCurrentTransport = ({ transportID, vehicleName, }: Pick<TransportInfo, 'transportID' | 'vehicleName'>) => { modalObserver.addModal(ModalNamesEnum.alertModal, { props: { modalContent: { header: `Delete ${vehicleName}`, title: 'Your data will be lost!', subtitle: `Are you sure you want to delete ${vehicleName}?\nThis action cannot be undone.`, isShow: true, variantIcon: 'delete', }, rightBtnProps: { isShow: true, label: 'Delete', color: 'error', onClick: () => dispatch( deleteTransport({ transportID, vehicleName, }), ) .unwrap() .then(() => modalObserver.removeModal(ModalNamesEnum.alertModal)), }, leftBtnProps: { isShow: true, label: 'Cancel', }, }, }); }; const handleOpenShareModal = ( transportInfoUsers: Pick<TransportInfo, 'users' | 'owner' | 'transportID'>, ) => { modalObserver.addModal(ModalNamesEnum.shareModal, { props: { users: transportInfoUsers?.users, owner: transportInfoUsers?.owner, title: t('general.header.shareWith'), handleConfirm: (users: AssignPeopleSelectValueModel[]) => Promise.resolve().then(() => { dispatch(syncUserShare({ transportID: transportInfoUsers.transportID, users })); }), }, }); }; const selfCanselShareHandler = ({ transportID }: Pick<TransportInfo, 'transportID'>) => dispatch(selfCancelShare(transportID)); const createAction = ( label: string, startIcon: ReactNode, callback: () => void, isDisabled: boolean = false, ) => { return { label, callback, isContainStartIcon: true, startIcon, isDisabled, }; }; const view = createAction('View', ViewIcon, () => { dispatch(setLoadingGarage({ isLoading: false })); navigate( `${router.garageNew.children.garageCardInformation.path}/${transportInfo.transportID}/${router.garageNew.children.garageCardInformation.generalInfo.path}`, ); }); const stopShare = createAction('Cancel sharing', ShareIcon, () => selfCanselShareHandler({ ...transportInfo }), ); const del = createAction('Delete', DeleteIcon, () => deleteCurrentTransport({ ...transportInfo })); const changeCoverPhoto = createAction('Change cover photo', CoverIcon, () => {}); const share = createAction('Share', ShareIcon, () => handleOpenShareModal({ ...transportInfo })); const continueCreating = createAction('Continue creating', EditIcon, () => {}); if (userStatus.isCreator && !userStatus.isDraft) { return [...[view, share, changeCoverPhoto, del]]; } if (userStatus.isEditor) { return [...[view, changeCoverPhoto, stopShare]]; } if (userStatus.isViewer) { return [...[view, stopShare]]; } if (userStatus.isCreator && userStatus.isDraft) { return [...[continueCreating, del]]; } return []; };
@extends('layouts.navbar') @section('content') <div class="container"> <div class="flex flex-col items-center justify-center px-6 py-8 mx-auto lg:py-0 mt-10 mb-10"> <a href="#" class="flex items-center mb-6 text-2xl font-semibold text-gray-900 dark:text-white"> <img class="w-10 h-10 mr-2" src="https://static.vecteezy.com/system/resources/previews/024/043/961/original/money-clipart-transparent-background-free-png.png" alt="logo"> Keuangan </a> <div class="w-full bg-gray-100 rounded-lg shadow dark:border md:mt-0 sm:max-w-md xl:p-0 dark:bg-gray-800 dark:border-gray-700"> <div class="p-6 space-y-4 md:space-y-6 sm:p-8"> <h1 class="text-xl font-bold leading-tight tracking-tight text-gray-900 md:text-2xl dark:text-white"> Buat Akun Anda </h1> <form class="space-y-4 md:space-y-6" method="POST" action="{{ route('register') }}"> @csrf <div> <label for="name" class="block mb-2 text-sm font-medium text-gray-900 dark:text-white">Nama Anda</label> <input type="text" name="name" id="name" class="bg-gray-50 border border-gray-300 text-gray-900 sm:text-sm rounded-lg focus:ring-blue-600 focus:border-blue-600 block w-full p-2.5 dark:bg-gray-700 dark:border-gray-600 dark:placeholder-gray-400 dark:text-white dark:focus:ring-blue-500 dark:focus:border-blue-500 @error('name') is-invalid @enderror" value="{{ old('name') }}" required autocomplete="name" autofocus> @error('name') <span class="invalid-feedback" role="alert"> <strong>{{ $message }}</strong> </span> @enderror </div> <div> <label for="email" class="block mb-2 text-sm font-medium text-gray-900 dark:text-white">Email Anda</label> <input type="email" name="email" id="email" class="bg-gray-50 border border-gray-300 text-gray-900 sm:text-sm rounded-lg focus:ring-blue-600 focus:border-blue-600 block w-full p-2.5 dark:bg-gray-700 dark:border-gray-600 dark:placeholder-gray-400 dark:text-white dark:focus:ring-blue-500 dark:focus:border-blue-500 @error('email') is-invalid @enderror" value="{{ old('email') }}" required autocomplete="email" autofocus> @error('email') <span class="invalid-feedback" role="alert"> <strong>{{ $message }}</strong> </span> @enderror </div> <div> <label for="password" class="block mb-2 text-sm font-medium text-gray-900 dark:text-white">Password</label> <input type="password" name="password" id="password" class="bg-gray-50 border border-gray-300 text-gray-900 sm:text-sm rounded-lg focus:ring-blue-600 focus:border-blue-600 block w-full p-2.5 dark:bg-gray-700 dark:border-gray-600 dark:placeholder-gray-400 dark:text-white dark:focus:ring-blue-500 dark:focus:border-blue-500 @error('password') is-invalid @enderror" required autocomplete="new-password"> </div> <div> <label for="password_confirmation" class="block mb-2 text-sm font-medium text-gray-900 dark:text-white">Konfirmasi Password</label> <input type="password" name="password_confirmation" id="password_confirmation" class="bg-gray-50 border border-gray-300 text-gray-900 sm:text-sm rounded-lg focus:ring-blue-600 focus:border-blue-600 block w-full p-2.5 dark:bg-gray-700 dark:border-gray-600 dark:placeholder-gray-400 dark:text-white dark:focus:ring-blue-500 dark:focus:border-blue-500 " required autocomplete="new-password"> </div> <div class="form-group{{ $errors->has('g-recaptcha-response') ? ' has-error' : '' }}"> <div class="col-md-offset-4 col-md-6"> {!! app('captcha')->display() !!} {!! $errors->first('g-recaptcha-response', '<p class="help-block">:message</p>') !!} </div> </div> <button type="submit" class="w-full text-white bg-blue-600 hover:bg-blue-700 focus:ring-4 focus:outline-none focus:ring-blue-300 font-medium rounded-lg text-sm px-5 py-2.5 text-center dark:bg-blue-600 dark:hover:bg-blue-700 dark:focus:ring-blue-800">Register</button> </form> </div> </div> </div> </div> @endsection @section('scripts') <script src="https://www.google.com/recaptcha/api.js"></script> @endsection
<!DOCTYPE html> <html lang="en" ng-app="uglyThings"> <head> <meta charset="UTF-8"> <title>Ugly</title> <link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-1q8mTJOASx8j1Au+a5WDVnPi2lkFfwwEAa8hDDdjZlpLegxhjVME1fgjWPGmkzs7" crossorigin="anonymous"> <link rel="stylesheet" href="styles.css"> </head> <body ng-controller="mainController"> <h1>The Ugly</h1> <div class="container-fluid"> <div class="row"> <form ng-submit="addUgly(submission)" novalidate> <div class="col-sm-12 col-md-4 form-group"> <input class="form-control" placeholder="Title" ng-model="submission.titleField" type="text"> </div> <div class="col-sm-12 col-md-4 form-group"> <input class="form-control" placeholder="URL" ng-model="submission.urlField" type="url"> </div> <div class="col-sm-12 col-md-4 form-group"> <input class="form-control" placeholder="Description" ng-model="submission.descriptionField" type="text"> </div> <div class="buttonDiv"> <button type="submit" class="btn btn-primary"> Submit </button> </div> </form> </div> <div class="row"> <div ng-repeat="submission in uglyThings track by $index" class="col-xs-12 col-md-4 subBox"> <h2>{{ submission.titleField }}</h2> <div class="imgBox"> <img class="img-responsive" ng-src="{{submission.urlField }}" alt=""> </div> <p>{{ submission.descriptionField }}</p> <input ng-model="comment" type="text" class="form-control comment"> <button ng-click="addComment(comment, $index)" class="btn btn-info comlete">Comment</button> <button ng-click="deleteSub($index)" class="btn btn-danger comlete">Delete</button> <p ng-repeat="entry in submission.comments track by $index">{{ entry }}<button class="btn btn-danger commentDelete" ng-click="deleteComment($index, $parent.$index)">X</button></p> </div> </div> </div> </div> <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.5/angular.min.js"></script> <script src="app.js"></script> </head> </body> </html>
abstract class Shape{ abstract double perimeter(); // A shape has some perimeter, but the formula depends upon the entity or the object abstract double area(); } class Circle extends Shape{ double radius = 10; double perimeter(){ return 2*Math.PI*radius; } double area(){ return Math.PI*radius*radius; } } class Rectangle extends Shape{ double length=10; double breadth=5; double perimeter(){ return 2*(length+breadth); } double area(){ return length*breadth; } } public class AbstractClassExample2 { public static void main(String[] args) { Shape circle = new Circle(); Shape rectangle = new Rectangle(); System.out.println(circle.area()); System.out.println(circle.perimeter()); System.out.println(rectangle.area()); System.out.println(rectangle.perimeter()); } }
/* The CSS display property is used to control how an element is rendered in the browser. It specifies the type of box used for an HTML element and influences the layout and visibility of the element. */ /* The display property accepts various values, each determining how an element is displayed. */ /* In HTML, the default display property value is taken from the HTML specifications or from the browser/user default style sheet. */ /* block: This value generates a block-level element, creating a line break before and after the element. Block-level elements occupy the entire width of their container and stack vertically. */ /* inline: This value generates an inline-level element, allowing elements to flow within a line. Inline elements do not create line breaks and only occupy the space necessary for their content. */ /* Any height and width properties will have no effect */ /* inline -->> same line (jiksss) */ /* block -->> new line */ /* inline-block: This value combines aspects of block and inline. It generates an inline-level element that can have a specified width and height, and elements with inline-block will respect top and bottom margins, but not left and right margins. */ /* you can apply height and width values */ /* none: This value hides the element from the layout entirely, as if it doesn't exist. The element is not rendered and doesn't take up any space on the page. This is commonly used for hiding elements dynamically using JavaScript. */ *{ margin: 0; padding: 0; box-sizing: border-box; /* The box-sizing property in CSS is used to control how the total width and height of an element are calculated, taking into account the element's padding and border. By default, the width and height of an element are calculated based on its content box, which includes the content, padding, and border. */ } div{ display: block; /* display: inline; */ display: inline-block; /* display: none; */ border: 2px solid red; width: 300px; height: 300px; margin: 10px; padding: 50px; } a{ border: 2px solid saddlebrown; padding: 10px; margin: 10px; /* The visibility property in CSS is used to control the visibility of an element on a webpage. It determines whether an element is visible or hidden while still occupying its space in the layout. */ visibility: hidden; /* hidden: This value indicates that the element is hidden but still occupies its space in the layout. The element is not rendered, and it doesn't affect the positioning of other elements around it. */ visibility: visible; /* visible (default): This value indicates that the element is visible. It is rendered normally and displayed in the layout. */ } span{ display: span; display: block; display: inline-block; border: 2px solid green; margin: 10px; padding: 10px; }
package com.product.ordering.domain.entity; import com.product.ordering.domain.valueobject.WarehouseId; import com.product.ordering.domain.exception.WarehouseDomainException; import com.product.ordering.domain.valueobject.WarehouseName; public class Warehouse extends DomainEntity<WarehouseId> { public static WarehouseBuilder builder() { return new WarehouseBuilder(); } private final WarehouseName warehouseName; private final boolean isOpen; private Warehouse(WarehouseBuilder warehouseBuilder) { id(warehouseBuilder.warehouseId); warehouseName = warehouseBuilder.warehouseName; isOpen = warehouseBuilder.isOpen; } public void checkIfAvailable() { if (!isOpen) { throw new WarehouseDomainException("Warehouse with id: " + id() + " is not open"); } } public WarehouseName warehouseName() { return warehouseName; } public boolean isOpen() { return isOpen; } public static final class WarehouseBuilder { private WarehouseId warehouseId; private boolean isOpen; private WarehouseName warehouseName; private WarehouseBuilder() {} public WarehouseBuilder warehouseId(WarehouseId warehouseId) { this.warehouseId = warehouseId; return this; } public WarehouseBuilder warehouseName(WarehouseName warehouseName) { this.warehouseName = warehouseName; return this; } public WarehouseBuilder isOpen(boolean isOpen) { this.isOpen = isOpen; return this; } public Warehouse build() { return new Warehouse(this); } } }
# from bitcoinrpc.authproxy import AuthServiceProxy # rpc_user = "123456" # rpc_password = "123456" # rpc_url = "http://127.0.0.1:8332" # def user_address(): # """ # Get user address type. # """ # while True: # address_type = input("Select address type (legacy, p2sh-segwit, bech32): ").lower() # if address_type in ["legacy", "p2sh-segwit", "bech32"]: # return address_type # else: # print("Invalid address type. Please choose from legacy, p2sh-segwit, or bech32.") # wallet_connection = AuthServiceProxy(f"http://{rpc_user}:{rpc_password}@127.0.0.1:18332", timeout=290) # wallet_name = "testwallet80" # disable_private_keys = False # blank = False # passphrase = "" # avoid_reuse = True # descriptors = True # load_on_startup = True # external_signer = False # silent_payment = True # new_wallet = wallet_connection.createwallet( # wallet_name, # disable_private_keys, # blank, passphrase, # avoid_reuse, # descriptors, # load_on_startup,external_signer, # silent_payment) # import pdb; pdb.set_trace() # wallet_address = wallet_connection.getnewaddress("GenerateAddress",user_address()) # print("-") # print("Wallet Address: ", wallet_address) # #Retrive wallet spendable balance # wallet_balance = wallet_connection.getbalance() # print("-------------------------------------------------------------------------------") # print("Wallet Balance:",wallet_balance) # print("-\n") # #generate blocks # blocks = wallet_connection.generatetoaddress(101, wallet_address) # print("-------------------------------------------------------------------------------") # print("Generating Blocks") # print("-\n") # #new balance # new_balance = wallet_connection.getbalance() # print("-") # print("New wallet Balance:",new_balance) # print("-") # wallet_connection.settxfee(0.00001) # send_transaction = wallet_connection.sendtoaddress(wallet_address, 0.01, "test send") # print("-") # print("Transaction Id:",send_transaction) # print("-\n") import os import hashlib import ecdsa from bech32 import bech32_encode, convertbits # Constants G = ecdsa.SECP256k1.generator N = ecdsa.SECP256k1.order def sha256(data): return hashlib.sha256(data).digest() def hash_bip352_label(data): tag = sha256(b"BIP0352/Label") return sha256(tag + tag + data) def generate_private_key(): return os.urandom(32) def generate_public_key(private_key): sk = ecdsa.SigningKey.from_string(private_key, curve=ecdsa.SECP256k1) vk = sk.verifying_key return vk.to_string("compressed") def tweak_public_key(public_key, tweak): point = ecdsa.VerifyingKey.from_string(public_key, curve=ecdsa.SECP256k1).pubkey.point tweak_point = int.from_bytes(tweak, byteorder='big') * G new_point = point + tweak_point new_pubkey = ecdsa.VerifyingKey.from_public_point(new_point, curve=ecdsa.SECP256k1) return new_pubkey.to_string("compressed") def generate_silent_payment_address(bscan, bscan_priv, bm, label=None): # Calculate Bm with optional label if label is not None: tweak = hash_bip352_label(bscan_priv.to_bytes(32, 'big') + label.to_bytes(4, 'big')) bm = tweak_public_key(bm, tweak) # Create Bech32m address hrp = "sp" version_byte = 0 data = bytes([version_byte]) + bscan + bm converted = convertbits(data, 8, 5) return bech32_encode(hrp, converted) def main(): # Generate bscan (scan public key) and bscan_priv (scan private key) bscan_priv = int.from_bytes(generate_private_key(), byteorder='big') bscan = generate_public_key(bscan_priv.to_bytes(32, 'big')) # Generate bspend (spend public key) bspend_priv = int.from_bytes(generate_private_key(), byteorder='big') bspend = generate_public_key(bspend_priv.to_bytes(32, 'big')) # Generate silent payment address label = 1 # Optional label silent_payment_address = generate_silent_payment_address(bscan, bscan_priv, bspend, label) print("Silent Payment Address:", silent_payment_address) if __name__ == "__main__": main()
# Import necessary libraries from sklearn.model_selection import train_test_split from sklearn.ensemble import RandomForestClassifier from sklearn.tree import DecisionTreeClassifier from sklearn.linear_model import LogisticRegression from sklearn.metrics import ( accuracy_score, precision_score, recall_score, f1_score, confusion_matrix, plot_confusion_matrix, plot_roc_curve, precision_recall_curve, average_precision_score) import os import pandas as pd import seaborn as sns import matplotlib.pyplot as plt from sklearn.svm import SVC from sklearn.preprocessing import label_binarize from itertools import cycle import tensorflow as tf from tensorflow import keras from tensorflow.keras.models import Sequential from tensorflow.keras.layers import Dense labels=['Actual 0', 'Actual 1', 'Actual 2'] def plot_training_history(history): # Plot training history plt.figure(figsize=(12, 4)) # Plot training & validation accuracy values plt.subplot(1, 2, 1) plt.plot(history.history['accuracy']) plt.plot(history.history['val_accuracy']) plt.title('Model Accuracy') plt.xlabel('Epoch') plt.ylabel('Accuracy') plt.legend(['Train', 'Validation'], loc='upper left') # Plot training & validation loss values plt.subplot(1, 2, 2) plt.plot(history.history['loss']) plt.plot(history.history['val_loss']) plt.title('Model Loss') plt.xlabel('Epoch') plt.ylabel('Loss') plt.legend(['Train', 'Validation'], loc='upper left') plt.tight_layout() plt.show() def model_testing(file_name,model): df = pd.read_excel(file_name) X = df.drop(columns=['Flag']) y = df['Flag'] X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42) history = model.fit(X_train, y_train, epochs=10, batch_size=32, validation_split=0.4) plot_training_history(history) y_pred = model.predict(X_test) accuracy = accuracy_score(y_test, y_pred) precision = precision_score(y_test, y_pred, average='weighted') recall = recall_score(y_test, y_pred, average='weighted') f1 = f1_score(y_test, y_pred, average='weighted') conf_matrix = confusion_matrix(y_test, y_pred) return accuracy, precision, recall, f1, conf_matrix # Create models random_forest = RandomForestClassifier(n_estimators=100, random_state=42) logistic_regression = LogisticRegression(random_state=42, max_iter=1000) decision_tree = DecisionTreeClassifier(random_state=42) neural_network = Sequential([ Dense(128, input_shape=([7,]), activation='relu'), Dense(32, activation='relu'), Dense(16, activation='relu'), Dense(1, activation='relu') ]) neural_network.compile(optimizer=tf.keras.optimizers.SGD(lr=0.0001), loss=tf.keras.losses.MSE, metrics=[tf.keras.metrics.mean_squared_error,'accuracy']) # Create a list of models models = [neural_network] Eval_metrics=pd.DataFrame() confusion_mat=pd.DataFrame() # Test each model for model in models: model_name = type(model).__name__ accuracy, precision, recall, f1, conf_matrix = model_testing('master.xlsx', model) data={'Accuracy':[accuracy], 'Precision':[precision], 'Recall':[recall], 'F1_score':[f1], 'Model':[model_name] } conf=pd.DataFrame(conf_matrix) confusion_mat=confusion_mat.append(conf) data = pd.DataFrame(data) Eval_metrics=Eval_metrics.append(data) # Display the resulting DataFrame print(confusion_mat) print(Eval_metrics)
//: containers/SimpleHashMap.java // A demonstration hashed Map. package chap17_containers; import util.*; import java.util.*; public class SimpleHashMap<K,V> extends AbstractMap<K,V> { // Choose a prime number for the hash table size, to achieve a uniform distribution: static final int SIZE = 1024 - 3; // 997 // You can’t have a physical array of generics, but you can upcast to one: @SuppressWarnings("unchecked") LinkedList<MapEntry<K,V>>[] buckets = new LinkedList[SIZE]; public V put(K key, V value) { V oldValue = null; int index = Math.abs(key.hashCode()) % SIZE; if(buckets[index] == null) buckets[index] = new LinkedList<MapEntry<K,V>>(); LinkedList<MapEntry<K,V>> bucket = buckets[index]; MapEntry<K,V> pair = new MapEntry<>(key, value); boolean found = false; ListIterator<MapEntry<K,V>> it = bucket.listIterator(); int probes = 0; while(it.hasNext()) { probes++; MapEntry<K,V> iPair = it.next(); if(iPair.getKey().equals(key)) { System.out.print("Key collision!" + " new pair: " + pair + " replaced old pair " + iPair + " "); oldValue = iPair.getValue(); it.set(pair); // Replace old with new found = true; break; } } if(probes > 0) System.out.println( "probes: " + probes + " pair: " + pair + " index: " + index); if(!found) buckets[index].add(pair); return oldValue; } public V get(Object key) { int index = Math.abs(key.hashCode()) % SIZE; if(buckets[index] == null) return null; for(MapEntry<K,V> iPair : buckets[index]) if(iPair.getKey().equals(key)) return iPair.getValue(); return null; } public void clear() { for (List list : buckets) { if(list != null) list.clear();}} public V remove(Object key) { if (get(key) != null) { int index = Math.abs(key.hashCode()) % SIZE; Iterator<MapEntry<K,V>> it = buckets[index].iterator(); while(it.hasNext()) { MapEntry<K, V> iPair = it.next(); if (iPair.getKey().equals(key)) { V oldValue = iPair.getValue(); it.remove(); return oldValue; } } } return null; } public Set<Map.Entry<K,V>> entrySet() { Set<Map.Entry<K,V>> set= new HashSet<>(); for(LinkedList<MapEntry<K,V>> bucket : buckets) { if(bucket == null) continue; for(MapEntry<K,V> mpair : bucket) set.add(mpair); } return set; } public static void main(String[] args) { SimpleHashMap<String,String> m = new SimpleHashMap<>(); m.putAll(Countries.capitals(5)); System.out.println(m); // m.put("ANGOLA", "Luand"); // m.put("ANGOLA", "Luanda"); // m.put("BENIN", "Porto-Novo"); // System.out.println(m.get("ERITREA")); // System.out.println(m.entrySet()); // System.out.println(m.buckets[544]); // m.clear(); m.remove("BURKINA FASO"); System.out.println(m); } } /* Output: {CAMEROON=Yaounde, CONGO=Brazzaville, CHAD=N’djamena, COTE D’IVOIR (IVORY COAST)=Yamoussoukro, CENTRAL AFRICAN REPUBLIC=Bangui, GUINEA=Conakry, BOTSWANA=Gaberone, BISSAU=Bissau, EGYPT=Cairo, ANGOLA=Luanda, BURKINA FASO=Ouagadougou, ERITREA=Asmara, THE GAMBIA=Banjul, KENYA=Nairobi, GABON=Libreville, CAPE VERDE=Praia, ALGERIA=Algiers, COMOROS=Moroni, EQUATORIAL GUINEA=Malabo, BURUNDI=Bujumbura, BENIN=Porto-Novo, BULGARIA=Sofia, GHANA=Accra, DJIBOUTI=Dijibouti, ETHIOPIA=Addis Ababa} Asmara [CAMEROON=Yaounde, CONGO=Brazzaville, CHAD=N’djamena, COTE D’IVOIR (IVORY COAST)=Yamoussoukro, CENTRAL AFRICAN REPUBLIC=Bangui, GUINEA=Conakry, BOTSWANA=Gaberone, BISSAU=Bissau, EGYPT=Cairo, ANGOLA=Luanda, BURKINA FASO=Ouagadougou, ERITREA=Asmara, THE GAMBIA=Banjul, KENYA=Nairobi, GABON=Libreville, CAPE VERDE=Praia, ALGERIA=Algiers, COMOROS=Moroni, EQUATORIAL GUINEA=Malabo, BURUNDI=Bujumbura, BENIN=Porto-Novo, BULGARIA=Sofia, GHANA=Accra, DJIBOUTI=Dijibouti, ETHIOPIA=Addis Ababa] *///:~
package com.mohann.covid19.room.model; import androidx.room.ColumnInfo; import androidx.room.Entity; import androidx.room.PrimaryKey; import org.jetbrains.annotations.NotNull; import java.io.Serializable; import java.util.Comparator; @Entity(tableName = "statewise") public class StateWiseModel implements Serializable { @PrimaryKey(autoGenerate = true) private long id; @ColumnInfo(name = "active") private String active; @ColumnInfo(name = "confirmed") private String confirmed; @ColumnInfo(name = "deaths") private String deaths; @ColumnInfo(name = "deltaconfirmed") private String deltaconfirmed; @ColumnInfo(name = "deltadeaths") private String deltadeaths; @ColumnInfo(name = "deltarecovered") private String deltarecovered; @ColumnInfo(name = "lastupdatedtime") private String lastupdatedtime; @ColumnInfo(name = "migratedother") private String migratedother; @ColumnInfo(name = "recovered") private String recovered; @ColumnInfo(name = "state") private String state; @ColumnInfo(name = "statecode") private String statecode; @ColumnInfo(name = "statenotes") private String statenotes; public long getId() { return id; } public void setId(long id) { this.id = id; } @NotNull @Override public String toString() { return "StateWiseModel{" + "active='" + active + '\'' + ", confirmed='" + confirmed + '\'' + ", deaths='" + deaths + '\'' + ", deltaconfirmed='" + deltaconfirmed + '\'' + ", deltadeaths='" + deltadeaths + '\'' + ", deltarecovered='" + deltarecovered + '\'' + ", lastupdatedtime='" + lastupdatedtime + '\'' + ", migratedother='" + migratedother + '\'' + ", recovered='" + recovered + '\'' + ", state='" + state + '\'' + ", statecode='" + statecode + '\'' + ", statenotes='" + statenotes + '\'' + '}'; } public StateWiseModel(String active, String confirmed, String deaths, String deltaconfirmed, String deltadeaths, String deltarecovered, String lastupdatedtime, String migratedother, String recovered, String state, String statecode, String statenotes) { this.active = active; this.confirmed = confirmed; this.deaths = deaths; this.deltaconfirmed = deltaconfirmed; this.deltadeaths = deltadeaths; this.deltarecovered = deltarecovered; this.lastupdatedtime = lastupdatedtime; this.migratedother = migratedother; this.recovered = recovered; this.state = state; this.statecode = statecode; this.statenotes = statenotes; } public String getActive() { return active; } public void setActive(String active) { this.active = active; } public String getConfirmed() { return confirmed; } public void setConfirmed(String confirmed) { this.confirmed = confirmed; } public String getDeaths() { return deaths; } public void setDeaths(String deaths) { this.deaths = deaths; } public String getDeltaconfirmed() { return deltaconfirmed; } public void setDeltaconfirmed(String deltaconfirmed) { this.deltaconfirmed = deltaconfirmed; } public String getDeltadeaths() { return deltadeaths; } public void setDeltadeaths(String deltadeaths) { this.deltadeaths = deltadeaths; } public String getDeltarecovered() { return deltarecovered; } public void setDeltarecovered(String deltarecovered) { this.deltarecovered = deltarecovered; } public String getLastupdatedtime() { return lastupdatedtime; } public void setLastupdatedtime(String lastupdatedtime) { this.lastupdatedtime = lastupdatedtime; } public String getMigratedother() { return migratedother; } public void setMigratedother(String migratedother) { this.migratedother = migratedother; } public String getRecovered() { return recovered; } public void setRecovered(String recovered) { this.recovered = recovered; } public String getState() { return state; } public void setState(String state) { this.state = state; } public String getStatecode() { return statecode; } public void setStatecode(String statecode) { this.statecode = statecode; } public String getStatenotes() { return statenotes; } public void setStatenotes(String statenotes) { this.statenotes = statenotes; } public static Comparator<StateWiseModel> stateWiseModelComparator = (s1, s2) -> { return Integer.parseInt(s2.getConfirmed().replace(",", "")) - Integer.parseInt(s1.getConfirmed().replace(",", "")); }; }
import express from "express" import passport from 'passport' import { BearerStrategy, IBearerStrategyOptionWithRequest, ITokenPayload, VerifyCallback, } from 'passport-azure-ad' import config from './config'; const options: IBearerStrategyOptionWithRequest = { identityMetadata: `https://${config.metadata.authority}/${config.credentials.tenantID}/${config.metadata.version}/${config.metadata.discovery}`, issuer: `https://${config.metadata.authority}/${config.credentials.tenantID}/${config.metadata.version}`, clientID: config.credentials.clientID, audience: config.credentials.audience, validateIssuer: config.settings.validateIssuer, passReqToCallback: config.settings.passReqToCallback, loggingLevel: config.settings.loggingLevel, //scope: config.resource.scope, loggingNoPII: config.settings.loggingNoPII, }; const bearerStrategy = new BearerStrategy( options, (token: ITokenPayload, done: VerifyCallback) => { const user = { id: token.oid }; return done(null, user, token); } ); export class PassportConfiguration{ app: express.Application constructor(app: express.Application){ this.app = app } configure(){ this.app.use(passport.initialize()) passport.use(bearerStrategy) this.app.use( passport.authenticate('oauth-bearer', { session: false }), // authMiddleware ); } }
#include <iostream> using namespace std; #include <cmath> int main() { int n=0; cout<<"Enter the number of data points.\n"; cin>>n; float x[n],y[n];//array to store the coordinates of the points cout<<"Enter the data points as x and y coordiantes\n"; for(int i=0;i<n;i++) { cout<<(i+1)<<" point:\n"; cin>>x[i]; cin>>y[i]; } float sum_x=0.0f; float sum_y=0.0f; float sumSquare_x=0.0f; float sumSquare_y=0.0f; float sumCross_xy=0.0f; for(int i=0;i<n;i++) { sum_x+=x[i]; sum_y+=y[i]; sumSquare_x+=x[i]*x[i]; sumSquare_y+=y[i]*y[i]; sumCross_xy+=x[i]*y[i]; } float xMean=sum_x/n; float yMean=sum_y/n; double b=(sumCross_xy-(sum_x*sum_y/n))/(sumSquare_x-(sum_x*sum_x/n));//regression coefficient calculated double a=yMean-b*xMean; cout<<"The best fit line is y="<<a<<" + "<<b<<" x\n"; double xVar=sumSquare_x-(sum_x*sum_x/n); double yVar=sumSquare_y-(sum_y*sum_y/n); double r=b*xVar/yVar;//Karl Preason's coefficient of correlation calculated cout<<"The coefficient of coorelation is "<<r<<endl; return 0; }
import { useRouter } from "next/router"; import { useAuth } from "react-oidc-context"; const withAuth = (WrappedComponent) => { return (props) => { const auth = useAuth(); const router = useRouter(); if (auth.isLoading) { return <></> } if (!auth.isAuthenticated) { return ( <> <button onClick={() => auth.signinRedirect({ state: router.pathname, })}>Login</button> <h1>You need to login</h1> </> ) } return ( <> <button onClick={auth.removeUser}>Logout</button> <WrappedComponent {...props} /> </> ) } } export default withAuth;
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Luke Salisbury Photography - Main</title> <link rel="shortcut icon" type="image/jpg" href="Logo.png"/> <link rel="stylesheet" type="text/css" href="CSS/main.css"> <link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-EVSTQN3/azprG1Anm3QDgpJLIm9Nao0Yz1ztcQTwFspd3yD65VohhpuuCOmLASjC" crossorigin="anonymous"> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script> <meta http-equiv="imagetoolbar" content="no"/> </head> <body> <div id="page-container"> <nav class="navbar fixed-top navbar-expand-md" role="navigation"> <div class="navbar-brand"> <h3>Luke Salisbury<br> Photography</h3> </div> <button class="navbar-toggle custom-toggler d-block d-md-none" type="button" data-bs-toggle="collapse" data-bs-target="#headernav"> <span class="navbar-toggler-icon"></span> </button> <div class="navbar-collapse collapse" id="headernav"> <ul class="nav navbar-nav align-items-end"> <li class="nav-item active"> <a class="nav-link" href="#Main-Section">Home</a> </li> <li class="nav-item"> <a class="nav-link" href="#About-Section">About</a> </li> <li class="nav-item"> <a class="nav-link" href="#Work-Section">Work</a> </li> <li class="nav-item"> <a class="nav-link" href="#Contact-Section">Contact</a> </li> </ul> </div> </nav> <section id="Main-Section"> <div id="Top-Line"><hr></div> <!-- Main --> <div id="content-wrap"> <div class="row"> <div class="col-12 col-md-2 col-lg-3 offset-lg-1-right"> <img id="Main_Rings" src="Half Rings.png"> </div> <div class="col-12 col-md-5 col-lg-4"> <div id="Profession-Container"> <h3 id="Profession" class="img-fluid d-block m-auto">Bristol Based<br> Portrait Photographer</h3> </div> <div class="Calling_Button_Container"><a href="#Work-Section" style='text-decoration:none;'><button type="button" id="Calling_Button" class="btn btn-default d-block m-auto">My Work</button></a></div> </div> <div id="Main_Klaud_Container" class="col-12 col-md-5 col-lg-4"> <div class="overlayDiv"></div> <img id="Main_Klaud" class="img-fluid d-block m-auto" src="/Portfolio/Portraits/Klaud Edited.webp" alt="Isolation Self Portrait"> <div id="Image-Right-Line"><hr></div> </div> </div> </div> </section> <!-- About --> <section id="About-Section"> <div class="container-fluid"> <div class="row"> <div id="Luke_Self_Container" class="col-12 col-md-5 offset-md-1"> <img id="Luke_Self" class="img-fluid d-block m-auto fade-in" src="/Portfolio/Self Portraits/Isolation-final.webp" alt="Isolation Self Portrait"> <div id="Image-Left-Line" class="fade-in"><hr></div> </div> <div class="col-12 col-md-5"> <p id="About_Me" class="d-block m-auto fade-in">Hi, I'm Luke, a 22-year-old photographer! I like to take portrait, product, and landscape photos, and I like to incorporate different techniques such as long exposures into them. I started seriously getting into photography in the Summer of 2018 when I got my DSLR (Canon 60D).</p> </div> </div> </div> </section> <!-- Work --> <section id="Work-Section"> <div class="container-fluid overflow-hidden"> <div class="col-12 col-md-10 offset-md-1 images"> <div id="Thumbnails" class="m-auto justify-content-center"> <div class="Thumbnail-Container"><a href="/Portraits/"><img src="/Portfolio/Portraits Thumbnail.webp"></a></div> <div class="Thumbnail-Container"><a href="/Products/l"><img src="/Portfolio/Products Thumbnail.webp"></a></div> <div class="Thumbnail-Container"><a href="/Events/"><img src="/Portfolio/Events Thumbnail.webp"></a></div> <div class="Thumbnail-Container"><a href="/Self Portraits/"><img src="/Portfolio/Self Portraits Thumbnail.webp"></a></div> <div class="Thumbnail-Container"><a href="/Landscapes/"><img src="/Portfolio/Landscapes Thumbnail.webp"></a></div> <div class="Thumbnail-Container"><a href="/Sports/"><img src="/Portfolio/Sports Thumbnail.webp"></a></div> </div> </div> </div> </section> <!-- Contact --> <section id="Contact-Section"> <div class="container-fluid overflow-hidden"> <div class="row"> <div class="col-12 col-lg-5 offset-md-1"> <p id="Contact_Me" class="d-block m-auto fade-in">Want to get in contact about potential shoots? Click the button to send me an email!</p> </div> <div id="Form" class="col-12 col-lg-5"> <div class="Calling_Button_Container fade-in" id="Email-Container"><a href="mailto:[email protected]" style='text-decoration:none;'><button type="button" id="Calling_Button" class="btn btn-default d-block m-auto">Contact Me</button></a></div> </div> </div> </div> </section> <!-- Footer --> <footer id="Footer_Section"> <div class="container"> <div class="row"> <div class="col-12 col-md-6"> <p class="Footer_Text"><strong>@2022 by Luke Salisbury Photography</strong></p> </div> <div class="col-12 col-md-6"> <p class="Footer_Text"><strong>Designed and Developed by Klaudiusz Elzanowski</strong></p> </div> </div> </div> </footer> </div> <script src="https://code.jquery.com/jquery-3.6.0.js" integrity="sha256-H+K7U5CnXl1h5ywQfKtSj8PCmoN9aaq30gDh27Xc0jk=" crossorigin="anonymous"></script> <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.bundle.min.js" integrity="sha384-MrcW6ZMFYlzcLA8Nl+NtUVF0sA7MsXsP1UyJoMp4YLEuNSfAP+JcXn/tWtIaxVXM" crossorigin="anonymous"></script> <script src="/JS/fade.js"></script> </body> </html>
myApp.service('registration', ['$http', function ($http) { /********************************************************************** * Functions to check pattern of string **********************************************************************/ this.checkPatternEmail = function (email) { if (!email) return false; // regex for email var regex = /^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,4})+$/; // check if email respect the regex var testRegex = regex.test(email); // true if correct, false otherwise return testRegex; } this.checkPatternUsername = function (username) { if (!username) return false; // regex for email var regex = /^[a-zA-Z0-9-_]*$/; // check if email respect the regex var testRegex = regex.test(username); // true if correct, false otherwise // check if username respect min lenght var testMinLength = username.length >= 3; return testRegex && testMinLength; } this.checkPatternPassword = function (password) { if (!password) return false; return password.length >= 4; } /********************************************************************** * Check if email does not exist in database **********************************************************************/ this.checkEmailIsFree = function (email, callback) { $http.post('/auth/checkEmailIsFree', { email: email }) .then(function(response){ if (typeof(callback) == "function") { if (response.data.status === true) { callback(true); } else { callback(false); } } }); } /********************************************************************** * Check if username does not exist in database **********************************************************************/ this.checkUsernameIsFree = function (username, callback) { $http.post('/auth/checkUsernameIsFree', { username: username }) .then(function(response){ if (typeof(callback) == "function") { if (response.data.status === true) { callback(true); } else { callback(false); } } }); } /********************************************************************** * Register user email **********************************************************************/ this.register = function(email, callback) { $http.post('/auth/register', { email: email }) .then(function(response){ if (typeof(callback) == "function") { if (response.data.status === true) { // Success: message instruction callback(true, response.data.message); // format : callback(status, message) } else { // Success: message d'erreur callback(false, response.data.message); } } }) .catch(function(response){ // Error: message d'erreur if (typeof(callback) == "function") { callback(false, response.data.message); } }); } /********************************************************************** * Sign Up Token : Check if token is valid and get associated email **********************************************************************/ this.getEmailByToken = function (token, callback) { // Check if token is valid $http.get('/auth/signup?token=' + token) .then(function(response){ if (typeof(callback) == "function") { if (response.data.status === true) { // format : callback(status, email, message) callback(true, response.data.email, null); } else { callback(false, null,response.data.message); } } }) .catch(function(response){ if (typeof(callback) == "function") { callback(false, null, response.data.message); } }); } /********************************************************************** * Sign Up user **********************************************************************/ this.signup = function (data, callback) { $http.post('/auth/signup', data) .then(function(response){ if (typeof(callback) == "function") { if (response.data.status === true) { // format : callback(status, message) callback(true); } else { callback(false, response.data.message); } } }); } /********************************************************************** * Check username and password from user **********************************************************************/ this.checkUser = function (username, password, callback) { $http.post('/auth/checkUser', { username: username, password: password }) .then(function(response){ if (typeof(callback) == "function") { if (response.data.status === true) { callback(true); } else { callback(false); } } }); } }]);
import React from 'react'; import ReactDOM from 'react-dom/client'; import './index.css'; import App from './App'; import reportWebVitals from './reportWebVitals'; import { ApolloClient, ApolloProvider, InMemoryCache } from '@apollo/client'; import { createStore } from 'redux'; import { Provider } from 'react-redux'; import rootReducer from './reducers/rootReducer'; export const client = new ApolloClient({ uri: 'http://localhost:4000/graphql', cache: new InMemoryCache() }); const store = createStore(rootReducer); const root = ReactDOM.createRoot(document.getElementById('root')); root.render( <Provider store={store}> <ApolloProvider client={client}> <React.StrictMode> <App /> </React.StrictMode> </ApolloProvider> </Provider> ); // If you want to start measuring performance in your app, pass a function // to log results (for example: reportWebVitals(console.log)) // or send to an analytics endpoint. Learn more: https://bit.ly/CRA-vitals reportWebVitals();
pragma solidity ^0.5.2; import 'openzeppelin-solidity/contracts/token/ERC721/ERC721Full.sol'; import './Event.sol'; contract Tickets is ERC721{ //description can be a row-seat combination or anything else struct Ticket{ string description; address redeemedBy; } Event public ParentEvent; uint public numberOfTickets=0; uint256[] public TicketIds; mapping( uint256 => Ticket) public TicketData; uint256[] public RedeemedTickets; constructor(Event _eventAddress) public{ ParentEvent = _eventAddress; } function ticketsOfOwner(address _owner) public view returns(uint256[] memory) { uint256 ticketCount = balanceOf(_owner); if (ticketCount == 0) { return new uint256[](0); } else { uint256[] memory result = new uint256[](ticketCount); uint256 result_i = 0; for (uint256 i = 0; i < numberOfTickets; i++) { uint256 ticketId =TicketIds[i]; if (ownerOf(ticketId) == _owner) { result[result_i] = ticketId; result_i++; } } return result; } } function concat(string memory first, string memory second) pure private returns (string memory) { bytes memory _first = bytes(first); bytes memory _second = bytes(second); string memory both = new string(_first.length + _second.length); bytes memory _both = bytes(both); uint currentChar = 0; for (uint i = 0; i < _first.length; i++) _both[currentChar++] = _first[i]; for (uint i = 0; i < _second.length; i++) _both[currentChar++] = _second[i]; string memory result = string(_both); return result; } function uint2str(uint value) pure private returns (string memory) { if (value == 0) { return "0"; } uint i = value; uint len; while (i > 0) { len++; i /= 10; } bytes memory _str = new bytes(len); len --; while (value != 0) { _str[len--] = byte(uint8(48 + value % 10)); value /= 10; } string memory result = string(_str); return result; } function createDefaultTickets(uint rows, uint seatsPerRow) public{ for(uint row=1; row<=rows; row++){ string memory descriptionRow = "row "; descriptionRow = concat(descriptionRow,uint2str(row)); for(uint seat=1; seat<=seatsPerRow; seat++){ string memory description = concat(descriptionRow," seat "); addTicket(concat(description,uint2str(seat))); } } } function addTicket(string memory _description) public{ require(ParentEvent.released() == false,"Unable to add any tickets once the event is published"); require(msg.sender == ParentEvent.organizer(), "Only event organizer may add tickets."); uint256 ticketId = uint256(keccak256(abi.encode(ParentEvent,_description))); TicketData[ticketId] = Ticket(_description, address(0)); TicketIds.push(ticketId); _mint(address(ParentEvent.organizer()), ticketId); numberOfTickets += 1; } function publishOnMarket(uint256 ticketId, uint256 price) public{ require (ownerOf(ticketId) == msg.sender, "Only the owner can send a ticket"); require (isRedeemed(ticketId) == false, "Used ticket cannot be sold"); approve(address(ParentEvent), ticketId); ParentEvent.sellTicket(ticketId, price); } function cancelMarketPosition(uint256 ticketId) public{ require (ownerOf(ticketId) == msg.sender, "Only the owner can send a ticket"); approve(address(0), ticketId); } function isRedeemed(uint256 ticketId) view public returns(bool){ return TicketData[ticketId].redeemedBy != address(0); } function redeem(uint256 ticketId) public { require(msg.sender == ownerOf(ticketId), "Only ticket owner can redeem the ticket"); require(getApproved(ticketId) == address(0), "Ticket should not be published on market"); require (isRedeemed(ticketId) == false, "Same ticket can not be used twice"); safeTransferFrom(msg.sender, address(ParentEvent), ticketId); TicketData[ticketId].redeemedBy = msg.sender; RedeemedTickets.push(ticketId); } }
/* В Golang пакет flag предоставляет возможность создания пользовательских типов флагов с помощью интерфейса flag.Value. Этот интерфейс определен в пакете flag и включает методы, позволяющие пользовательским типам реализовать собственное поведение при установке и чтении флага. Интерфейс flag.Value включает следующие методы: String() string: Этот метод должен возвращать строковое представление значения флага. Set(string) error: Этот метод вызывается при установке значения флага из строки аргумента командной строки. Метод должен проанализировать переданную строку и установить соответствующее значение для флага. Если строка не может быть корректно разобрана, метод должен вернуть ошибку. Get() interface{}: Этот метод возвращает текущее значение флага в виде пустого интерфейса. Это используется внутренне пакетом flag для доступа к текущему значению флага. Вот пример создания пользовательского типа флага с использованием интерфейса flag.Value: */ // Запуск в консоли: go run castom_flag_1.go -customFlag 5 package main import ( "flag" "fmt" "strconv" ) // CustomFlagType - пользовательский тип флага type CustomFlagType int func (c *CustomFlagType) String() string { return strconv.Itoa(int(*c)) } func (c *CustomFlagType) Set(value string) error { // Парсинг строки и установка значения val, err := strconv.Atoi(value) if err != nil { return fmt.Errorf("неверное значение: %s", value) } *c = CustomFlagType(val) return nil } func main() { var customFlag CustomFlagType // Добавление флага с пользовательским типом flag.Var(&customFlag, "customFlag", "Пользовательский флаг") // Разбор аргументов командной строки flag.Parse() // Использование значения флага fmt.Println("Значение пользовательского флага:", customFlag) } /* В этом примере определен пользовательский тип CustomFlagType, реализующий интерфейс flag.Value. Затем создается переменная этого типа, и с помощью flag.Var она связывается с конкретным флагом командной строки. Таким образом, при использовании программы можно устанавливать значение флага customFlag с помощью аргумента командной строки. */
import React, { useState, useEffect } from "react"; import "./AdminPanel.css"; import { useSelector, useDispatch } from "react-redux"; import { Col, Container, Row } from "react-bootstrap"; import { NavLink } from "react-router-dom"; import axios from "axios"; import { FontAwesomeIcon } from "@fortawesome/react-fontawesome"; import { faSearch } from "@fortawesome/free-solid-svg-icons"; import { addLoggedUser } from "../../Store/Reducers/LoggedUserReducer"; const AdminPanel = () => { const dispatch = useDispatch(); const loggedUser = useSelector((state) => state.loggedUser); const mode = useSelector((state) => state.modeChanger); const [users, setUsers] = useState(); const [pageInfo, setPageInfo] = useState(); const [searchTerm, setSearchTerm] = useState(""); const [typingTimeout, setTypingTimeout] = useState(0); /*eslint-disable*/ useEffect(() => { handleSearch("1"); }, [searchTerm]); /*eslint-enable*/ const handleAdmin = async (e, user, role) => { e.preventDefault(); e.target.disabled = true; try { const newUser = await axios.put( `https://final-project-yb3m.onrender.com/api/v1/users/user/${user._id}`, { role: role, } ); handleSearch(pageInfo.currentPage); if (user._id === loggedUser._id && role === "user") { dispatch(addLoggedUser(newUser.data.user)); } } catch (error) { console.log(error); } finally { e.target.disabled = false; } }; const handleStatus = async (e, user, status) => { e.preventDefault(); e.target.disabled = true; try { const newUser = await axios.put( `https://final-project-yb3m.onrender.com/api/v1/users/user/${user._id}`, { status: status, } ); handleSearch(pageInfo.currentPage); if (user._id === loggedUser._id && status === "blocked") { dispatch(addLoggedUser(newUser.data.user)); } } catch (error) { console.log(error); } finally { e.target.disabled = false; } }; const handleDelete = async (e, user) => { e.preventDefault(); e.target.disabled = true; try { await axios.delete(`http://localhost:8080/api/v1/users/user/${user._id}`); handleSearch("1"); if (user._id === loggedUser._id) { dispatch(addLoggedUser("")); } } catch (error) { console.log(error); } finally { e.target.disabled = false; } }; const handleSearch = (page) => { // Clear previous timeout clearTimeout(typingTimeout); // Set a new timeout const timeoutId = setTimeout(async () => { try { const data = await axios.get( `https://final-project-yb3m.onrender.com/api/v1/users/searchUser?text=${searchTerm}&page=${page}` ); setUsers(data.data.user); setPageInfo(data.data.pageInfo); } catch (error) { console.log(error); setUsers([]); } }, 500); // Save the timeout ID setTypingTimeout(timeoutId); }; if (loggedUser.role === "admin" && loggedUser.status !== "blocked" && users) { return ( <div className={ mode === "dark" ? "admin-panel bg-dark-mode" : "admin-panel bg-light-mode" }> <Container> <div className={ mode === "dark" ? "admin-panel-card bg-dark-card" : "admin-panel-card bg-light-card" }> <div className="admin-panel-header">All Users</div> <div className="admin-panel-search"> <input type="text" autoFocus value={searchTerm} onChange={(e) => setSearchTerm(e.target.value)} /> <button onClick={() => handleSearch()}> <FontAwesomeIcon icon={faSearch} /> </button> </div> <div className="admin-panel-table"> {users.length === 0 && <div>Could not find users.</div>} {users.map((el, ind) => ( <div className="admin-panel-one-user" key={ind}> <Row> <Col xs={12} s={8} md={8} lg={8} xl={8}> <div className="one-user-name"> <div>Name : </div> <div>{el.firstName + " " + el.lastName}</div> </div> <div className="one-user-email"> <div>Email : </div> <div>{el.email}</div> </div> <div className="one-user-status"> <div>Status : </div> <div>{el.status}</div> </div> <div className="one-user-role"> <div>Role : </div> <div>{el.role}</div> </div> </Col> <Col xs={12} s={4} md={4} lg={4} xl={4}> <div className="admin-panel-one-user-btns"> <NavLink to={`/user/${el._id}`}> <button>Edit User</button> </NavLink> <button onClick={(e) => handleAdmin( e, el, el.role === "user" ? "admin" : "user" ) }> {el.role === "user" ? "Make Admin" : "Disable Admin"} </button> <button onClick={(e) => handleStatus( e, el, el.status === "active" ? "blocked" : "active" ) }> {el.status === "active" ? "Block User" : "Unblock User"} </button> <button style={{ background: "rgb(255, 139, 139)" }} onClick={(e) => handleDelete(e, el)}> Delete User </button> </div> </Col> </Row> </div> ))} </div> <div className="admin-panel-pagination"> <div className={ pageInfo.currentPage === 1 ? "admin-panel-one-page admin-panel-current-page" : "admin-panel-one-page" } onClick={() => { if (pageInfo.currentPage > 1) { handleSearch(pageInfo.currentPage - 1); } else { handleSearch(1); } }}> {pageInfo.currentPage > 2 ? "..." : "1"} </div> {pageInfo.currentPage <= pageInfo.totalPages && pageInfo.totalPages > 1 && ( <div className={ pageInfo.currentPage >= 2 ? "admin-panel-one-page admin-panel-current-page" : "admin-panel-one-page" } onClick={() => { if (pageInfo.currentPage < 2) { handleSearch(2); } }}> {pageInfo.currentPage > 2 ? pageInfo.currentPage : "2"} </div> )} {pageInfo.currentPage < pageInfo.totalPages && ( <div className="admin-panel-one-page" onClick={() => handleSearch(pageInfo.currentPage + 1)}> ... </div> )} </div> </div> </Container> </div> ); } else { return <div>404 Not Found</div>; } }; export default AdminPanel;
import React, { useEffect, useState, Fragment } from 'react'; const OneMovieFunc = (props) => { const [movie, setMovie] = useState({}) const [error, setError] = useState(null) useEffect(() => { fetch(`${process.env.REACT_APP_API_URL}/v1/movie/` + props.match.params.id) // .then((response) => response.json()) .then((response) => { if (response.status !== 200) { setError('Invalid response code: ' + response.status); } else { setError(null); } return response.json(); }) .then((json) => { setMovie(json.movie); }); },[props.match.params.id]); if (error !== null) { return ( <div>Error: {error.message}</div> ) } else { if (movie.genres) { movie.genres = Object.values(movie.genres); } else { movie.genres = []; } return ( <Fragment> <h2> Movie: {movie.title} ({movie.year}) </h2> <div className="float-start"> <small>Rating: {movie.mpaa_rating}</small> </div> <div className="float-end"> {movie.genres.map((m, index) => { return <span className="badge bg-secondary me-1" key={index}>{m}</span> })} </div> <div className="clearfix"></div> <hr/> <table className='table table-compact table-striped'> <thead></thead> <tbody> <tr> <td> <strong>Title:</strong> </td> <td>{movie.title}</td> </tr> <tr> <td><strong>Description:</strong></td> <td>{movie.description}</td> </tr> <tr> <td> <strong>Run time:</strong> </td> <td>{movie.runtime} minutes</td> </tr> </tbody> </table> </Fragment> ); } } export default OneMovieFunc;
import { Component, OnInit, ViewEncapsulation, ViewChild } from '@angular/core'; import { IDataOptions, PivotView, IDataSet } from '@syncfusion/ej2-angular-pivotview'; import { DropDownList, ChangeEventArgs } from '@syncfusion/ej2-angular-dropdowns'; import { CheckBox, Button } from '@syncfusion/ej2-angular-buttons'; import { GridSettings } from '@syncfusion/ej2-pivotview/src/pivotview/model/gridsettings'; import { enableRipple } from '@syncfusion/ej2-base'; enableRipple(false); /** * Pivot Table Member Sorting sample. */ /* tslint:disable */ declare var require: any; let Pivot_Data: IDataSet[] = require('./Pivot_Data.json'); @Component({ selector: 'ej2-pivotview-container', templateUrl: 'sorting.html', encapsulation: ViewEncapsulation.None, styleUrls: ['sorting.css'] }) export class SortingComponent implements OnInit { public dataSourceSettings: IDataOptions; public fieldsddl: DropDownList; public orderddl: DropDownList; public gridSettings: GridSettings; public applyBtn: Button; @ViewChild('pivotview') public pivotObj: PivotView; ngOnInit(): void { this.gridSettings = { columnWidth: 140 } as GridSettings; let order: string[] = ['Ascending', 'Descending']; let fields: { [key: string]: Object }[] = [ { Field: 'Country', Order: 'Country_asc' }, { Field: 'Products', Order: 'Products_asc' }, { Field: 'Year', Order: 'Year_asc' }, { Field: 'Order Source', Order: 'Order Source_asc' } ]; this.fieldsddl = new DropDownList({ dataSource: fields, fields: { text: 'Field', value: 'Order' }, index: 0, enabled: true, change: (args: ChangeEventArgs) => { if ((this.fieldsddl.dataSource as any)[this.fieldsddl.index].Order === (this.fieldsddl.dataSource as any)[this.fieldsddl.index].Field + '_asc') { this.orderddl.index = 0; } else { this.orderddl.index = 1; } } }); this.fieldsddl.appendTo('#fields'); this.orderddl = new DropDownList({ dataSource: order, index: 0, enabled: true, change: (args: ChangeEventArgs) => { if (args.value === 'Ascending') { (this.fieldsddl.dataSource as any)[this.fieldsddl.index].Order = (this.fieldsddl.dataSource as any)[this.fieldsddl.index].Field + '_asc'; } else { (this.fieldsddl.dataSource as any)[this.fieldsddl.index].Order = (this.fieldsddl.dataSource as any)[this.fieldsddl.index].Field + '_desc'; } this.fieldsddl.refresh(); } }); this.orderddl.appendTo('#order'); this.applyBtn = new Button({ cssClass: 'e-flat', isPrimary: true, }); this.applyBtn.appendTo('#apply'); let checkBoxObj: CheckBox = new CheckBox({ label: 'Enable Sorting', labelPosition: 'After', checked: true, change: (args: any) => { let ischecked: boolean = args.checked; this.fieldsddl.enabled = ischecked; this.orderddl.enabled = ischecked; this.applyBtn.disabled = !ischecked; this.pivotObj.dataSourceSettings.enableSorting = ischecked; } }); checkBoxObj.appendTo('#sorting'); document.getElementById('apply').onclick = () => { if (checkBoxObj.checked) { this.pivotObj.dataSourceSettings.enableSorting = true; this.pivotObj.dataSourceSettings.sortSettings = [ { name: 'Country', order: (this.fieldsddl.dataSource as any)[0].Order === 'Country_asc' ? 'Ascending' : 'Descending' }, { name: 'Products', order: (this.fieldsddl.dataSource as any)[1].Order === 'Products_asc' ? 'Ascending' : 'Descending' }, { name: 'Year', order: (this.fieldsddl.dataSource as any)[2].Order === 'Year_asc' ? 'Ascending' : 'Descending' }, { name: 'Order_Source', order: (this.fieldsddl.dataSource as any)[3].Order === 'Order Source_asc' ? 'Ascending' : 'Descending' } ]; } else { this.pivotObj.dataSourceSettings.enableSorting = false; this.pivotObj.dataSourceSettings.sortSettings = []; } }; this.dataSourceSettings = { rows: [{ name: 'Country' }, { name: 'Products' }], formatSettings: [{ name: 'Amount', format: 'C0' }], columns: [{ name: 'Year' }, { name: 'Order_Source', caption: 'Order Source' }], dataSource: Pivot_Data, expandAll: false, values: [{ name: 'In_Stock', caption: 'In Stock' }, { name: 'Sold', caption: 'Units Sold' }, { name: 'Amount', caption: 'Sold Amount' }], filters: [{ name: 'Product_Categories', caption: 'Product Categories' }], enableSorting: true }; } }
import { Component, OnInit } from '@angular/core'; import {Car} from "../../../model/car"; import {CarService} from "../../../service/car.service"; import Swal from "sweetalert2"; @Component({ selector: 'app-car-list', templateUrl: './car-list.component.html', styleUrls: ['./car-list.component.css'] }) export class CarListComponent implements OnInit { carList: Car[] = [] carDelete: Car; total: number; page: number = 0; constructor(private carService: CarService) { } ngOnInit(): void { this.getAll(); } getAll() { this.carService.getAll().subscribe(carList => { this.carList = carList.content; this.total = carList.totalPages; }) } deleteConfirm(car: Car) { this.carDelete = car; } delete(carDelete: Car) { this.carService.delete(carDelete).subscribe(next => this.getAll()); Swal.fire('Poof! Your imaginary file has been deleted!', '', 'success'); } previous() { if (this.page > 0){ this.page = this.page - 1; } } next() { if (this.page < this.total - 1) { this.page = this.page + 1; } } }
import 'package:flutter/material.dart'; import 'package:juai/common/theme.dart'; class Cell extends StatelessWidget { const Cell( this.text, { Key? key, this.border = true, this.right, this.isMustRight = true, this.onTap, }) : super(key: key); /// 底部 border 是否显示 final bool border; /// 右侧文字 final String text; /// 右侧内容 final Widget? right; final bool isMustRight; /// 点击回调 final VoidCallback? onTap; @override Widget build(BuildContext context) { return Padding( padding: const EdgeInsets.symmetric(horizontal: 12), child: InkWell( onTap: onTap, child: Container( padding: const EdgeInsets.symmetric(vertical: 16), decoration: BoxDecoration( border: Border( bottom: BorderSide(width: .5, color: border ? Theme.of(context).cardColor : Colors.transparent), )), child: Row( mainAxisAlignment: MainAxisAlignment.spaceBetween, children: [ Text( text, style: TextStyle( fontSize: WcaoTheme.fsL, color: WcaoTheme.base, ), ), const Spacer(), right ?? const SizedBox.shrink(), if (isMustRight == true) Icon( Icons.arrow_forward_ios, size: WcaoTheme.fsXl, color: WcaoTheme.secondary, ), ], ), ), ), ); } }
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ /* There were issues (possibly with syntax) in where a case and an if statement could be used. They are very similar where case seems more general. Trying to only use case statements led to issues so the following functions mix case and if statements. */ /* Rounds a timestamp up to the next interval */ CREATE OR REPLACE FUNCTION date_trunc_up(interval_precision TEXT, ts TIMESTAMP) RETURNS TIMESTAMP LANGUAGE SQL IMMUTABLE AS $$ SELECT CASE WHEN ts = date_trunc(interval_precision, ts) THEN ts ELSE date_trunc(interval_precision, ts + ('1 ' || interval_precision)::INTERVAL) END $$; /* This takes tsrange_to_shrink which is the requested time range to plot and makes sure it does not exceed the start/end times for the readings for the supplied meters. This can be an issue, in particular, because infinity is used to indicate to graph all readings. */ CREATE OR REPLACE FUNCTION shrink_tsrange_to_real_readings(tsrange_to_shrink TSRANGE, meter_ids INTEGER[]) RETURNS TSRANGE AS $$ DECLARE readings_max_tsrange TSRANGE; BEGIN SELECT tsrange(min(start_timestamp), max(end_timestamp)) INTO readings_max_tsrange FROM (readings r INNER JOIN unnest(meter_ids) meters(id) ON r.meter_id = meters.id); RETURN tsrange_to_shrink * readings_max_tsrange; END; $$ LANGUAGE 'plpgsql'; /* This takes tsrange_to_shrink which is the requested time range to plot and makes sure it does not exceed the start/end times for all the readings. This can be an issue, in particular, because infinity is used to indicate to graph all readings. This version does it to the nearest day by using the day reading view since bars use to the nearest day and this should be faster. This should be fine since bar uses the same view to get data. */ CREATE OR REPLACE FUNCTION shrink_tsrange_to_meters_by_day(tsrange_to_shrink TSRANGE, meter_ids INTEGER[]) RETURNS TSRANGE AS $$ DECLARE readings_max_tsrange TSRANGE; BEGIN SELECT tsrange(min(lower(time_interval)), max(upper(time_interval))) INTO readings_max_tsrange FROM daily_readings_unit dr -- Get all the meter_ids in the passed array of meters. INNER JOIN unnest(meter_ids) meters(id) ON dr.meter_id = meters.id; -- Make the original range be to the day by dropping parts of days at start/end. RETURN tsrange(date_trunc_up('day', lower(tsrange_to_shrink)), date_trunc('day', upper(tsrange_to_shrink))) * readings_max_tsrange; END; $$ LANGUAGE 'plpgsql'; /* The following views are all generated in src/server/models/Reading.js in createReadingsMaterializedViews. This is necessary because they can't be wrapped in a function (otherwise predicates would not be pushed down). */ /* The query shared by all of these views gets slow when one of two things happen: 1) It has to scan a large percentage of the readings table 2) It has to generate a large number of rows (by compressing to a small interval) We pick the best of both worlds by only materializing the large duration tables (day+ and then hour+). These produce fewer rows, making them acceptable to store, but they benefit from materialization because they require a scan of a large percentage of the readings table (to aggregate data over a large time range). The hourly table may not be that much smaller than the meter data but it can make it much faster for meters that read at sub-hour intervals so it's worth the extra disk space. The daily and hourly views are used when they give a minimum number of points as specified by the supplied parameter. It first tries daily since this is fastest, then hourly and finally uses raw/meter data if necessary. The goal is that the number of readings touched is never that large and when doing raw/meter readings the time range should be small so the number of readings retrieved is not large. It is assumed that the indices/optimizations allow for getting a subset of the raw/meter readings quickly. */ /** The next two create a view/table that takes the raw/meter readings and averages them for each day or hour. This is used by the line graph function below to make them faster since the values are already averaged. There are two types of readings: quantity and flow/raw. The quantity readings must be normalized by their time length. The flow/raw readings are already by time so they are just averaged. The one table contains both types of readings but are now equivalent so the line reading functions can use them both in the same way. */ CREATE MATERIALIZED VIEW IF NOT EXISTS daily_readings_unit AS SELECT -- This gives the weighted average of the reading rates, defined as -- sum(reading_rate * overlap_duration) / sum(overlap_duration) r.meter_id AS meter_id, CASE WHEN u.unit_represent = 'quantity'::unit_represent_type THEN (sum( (r.reading * 3600 / (extract(EPOCH FROM (r.end_timestamp - r.start_timestamp)))) -- Reading rate in kw * extract(EPOCH FROM -- The number of seconds that the reading shares with the interval least(r.end_timestamp, gen.interval_start + '1 day'::INTERVAL) - greatest(r.start_timestamp, gen.interval_start) ) ) / sum( extract(EPOCH FROM -- The number of seconds that the reading shares with the interval least(r.end_timestamp, gen.interval_start + '1 day'::INTERVAL) - greatest(r.start_timestamp, gen.interval_start) ) )) WHEN (u.unit_represent = 'flow'::unit_represent_type OR u.unit_represent = 'raw'::unit_represent_type) THEN (sum( (r.reading * 3600 / u.sec_in_rate) -- Reading rate in per hour * extract(EPOCH FROM -- The number of seconds that the reading shares with the interval least(r.end_timestamp, gen.interval_start + '1 day'::INTERVAL) - greatest(r.start_timestamp, gen.interval_start) ) ) / sum( extract(EPOCH FROM -- The number of seconds that the reading shares with the interval least(r.end_timestamp, gen.interval_start + '1 day'::INTERVAL) - greatest(r.start_timestamp, gen.interval_start) ) )) END AS reading_rate, -- The following code does the min/max for daily readings CASE WHEN u.unit_represent = 'quantity'::unit_represent_type THEN (max(( --Extract the maximum rate over each day (r.reading * 3600 / (extract(EPOCH FROM (r.end_timestamp - r.start_timestamp)))) -- Reading rate in kw * extract(EPOCH FROM -- The number of seconds that the reading shares with the interval least(r.end_timestamp, gen.interval_start + '1 day'::INTERVAL) - greatest(r.start_timestamp, gen.interval_start) ) ) / ( extract(EPOCH FROM -- The number of seconds that the reading shares with the interval least(r.end_timestamp, gen.interval_start + '1 day'::INTERVAL) - greatest(r.start_timestamp, gen.interval_start) ) ))) WHEN (u.unit_represent = 'flow'::unit_represent_type OR u.unit_represent = 'raw'::unit_represent_type) THEN (max(( (r.reading * 3600 / u.sec_in_rate) * extract(EPOCH FROM -- The number of seconds that the reading shares with the interval least(r.end_timestamp, gen.interval_start + '1 day'::INTERVAL) - greatest(r.start_timestamp, gen.interval_start) ) ) / ( extract(EPOCH FROM -- The number of seconds that the reading shares with the interval least(r.end_timestamp, gen.interval_start + '1 day'::INTERVAL) - greatest(r.start_timestamp, gen.interval_start) ) ))) END as max_rate, CASE WHEN u.unit_represent = 'quantity'::unit_represent_type THEN (min(( --Extract the minimum rate over each day (r.reading * 3600 / (extract(EPOCH FROM (r.end_timestamp - r.start_timestamp)))) -- Reading rate in kw * extract(EPOCH FROM -- The number of seconds that the reading shares with the interval least(r.end_timestamp, gen.interval_start + '1 day'::INTERVAL) - greatest(r.start_timestamp, gen.interval_start) ) ) / ( extract(EPOCH FROM -- The number of seconds that the reading shares with the interval least(r.end_timestamp, gen.interval_start + '1 day'::INTERVAL) - greatest(r.start_timestamp, gen.interval_start) ) ))) WHEN (u.unit_represent = 'flow'::unit_represent_type OR u.unit_represent = 'raw'::unit_represent_type) THEN (min(( (r.reading * 3600 / u.sec_in_rate) -- Reading rate in kw * extract(EPOCH FROM -- The number of seconds that the reading shares with the interval least(r.end_timestamp, gen.interval_start + '1 day'::INTERVAL) - greatest(r.start_timestamp, gen.interval_start) ) ) / ( extract(EPOCH FROM -- The number of seconds that the reading shares with the interval least(r.end_timestamp, gen.interval_start + '1 day'::INTERVAL) - greatest(r.start_timestamp, gen.interval_start) ) ))) END as min_rate, tsrange(gen.interval_start, gen.interval_start + '1 day'::INTERVAL, '()') AS time_interval FROM ((readings r -- This sequence of joins takes the meter id to its unit and in the final join -- it then uses the unit_index for this unit. INNER JOIN meters m ON r.meter_id = m.id) INNER JOIN units u ON m.unit_id = u.id) CROSS JOIN LATERAL generate_series( date_trunc('day', r.start_timestamp), -- Subtract 1 interval width because generate_series is end-inclusive date_trunc_up('day', r.end_timestamp) - '1 day'::INTERVAL, '1 day'::INTERVAL ) gen(interval_start) GROUP BY r.meter_id, gen.interval_start, u.unit_represent -- The order by ensures that the materialized view will be clustered in this way. ORDER BY gen.interval_start, r.meter_id; CREATE MATERIALIZED VIEW IF NOT EXISTS hourly_readings_unit AS SELECT -- This gives the weighted average of the reading rates, defined as -- sum(reading_rate * overlap_duration) / sum(overlap_duration) r.meter_id AS meter_id, CASE WHEN u.unit_represent = 'quantity'::unit_represent_type THEN (sum( (r.reading * 3600 / (extract(EPOCH FROM (r.end_timestamp - r.start_timestamp)))) -- Reading rate in kw * extract(EPOCH FROM -- The number of seconds that the reading shares with the interval least(r.end_timestamp, gen.interval_start + '1 hour'::INTERVAL) - greatest(r.start_timestamp, gen.interval_start) ) ) / sum( extract(EPOCH FROM -- The number of seconds that the reading shares with the interval least(r.end_timestamp, gen.interval_start + '1 hour'::INTERVAL) - greatest(r.start_timestamp, gen.interval_start) ) )) WHEN (u.unit_represent = 'flow'::unit_represent_type OR u.unit_represent = 'raw'::unit_represent_type) THEN (sum( (r.reading * 3600 / u.sec_in_rate) -- Reading rate in per hour * extract(EPOCH FROM -- The number of seconds that the reading shares with the interval least(r.end_timestamp, gen.interval_start + '1 hour'::INTERVAL) - greatest(r.start_timestamp, gen.interval_start) ) ) / sum( extract(EPOCH FROM -- The number of seconds that the reading shares with the interval least(r.end_timestamp, gen.interval_start + '1 hour'::INTERVAL) - greatest(r.start_timestamp, gen.interval_start) ) )) END AS reading_rate, -- The following code does the min/max for hourly readings CASE WHEN u.unit_represent = 'quantity'::unit_represent_type THEN (max(( -- Extract the maximum rate over each day (r.reading * 3600 / (extract(EPOCH FROM (r.end_timestamp - r.start_timestamp)))) -- Reading rate in kw * extract(EPOCH FROM -- The number of seconds that the reading shares with the interval least(r.end_timestamp, gen.interval_start + '1 hour'::INTERVAL) - greatest(r.start_timestamp, gen.interval_start) ) ) / ( extract(EPOCH FROM -- The number of seconds that the reading shares with the interval least(r.end_timestamp, gen.interval_start + '1 hour'::INTERVAL) - greatest(r.start_timestamp, gen.interval_start) ) ))) WHEN (u.unit_represent = 'flow'::unit_represent_type OR u.unit_represent = 'raw'::unit_represent_type) THEN (max(( -- For flow and raw data the max/min is per minute, so we multiply the max/min by 24 hrs * 60 min (r.reading * 3600 / u.sec_in_rate) -- Reading rate in kw * extract(EPOCH FROM -- The number of seconds that the reading shares with the interval least(r.end_timestamp, gen.interval_start + '1 hour'::INTERVAL) - greatest(r.start_timestamp, gen.interval_start) ) ) / ( extract(EPOCH FROM -- The number of seconds that the reading shares with the interval least(r.end_timestamp, gen.interval_start + '1 hour'::INTERVAL) - greatest(r.start_timestamp, gen.interval_start) ) ))) END as max_rate, CASE WHEN u.unit_represent = 'quantity'::unit_represent_type THEN (min(( --Extract the minimum rate over each day (r.reading * 3600 / (extract(EPOCH FROM (r.end_timestamp - r.start_timestamp)))) -- Reading rate in kw * extract(EPOCH FROM -- The number of seconds that the reading shares with the interval least(r.end_timestamp, gen.interval_start + '1 hour'::INTERVAL) - greatest(r.start_timestamp, gen.interval_start) ) ) / ( extract(EPOCH FROM -- The number of seconds that the reading shares with the interval least(r.end_timestamp, gen.interval_start + '1 hour'::INTERVAL) - greatest(r.start_timestamp, gen.interval_start) ) ))) WHEN (u.unit_represent = 'flow'::unit_represent_type OR u.unit_represent = 'raw'::unit_represent_type) THEN (min(( (r.reading * 3600 / u.sec_in_rate) -- Reading rate in kw * extract(EPOCH FROM -- The number of seconds that the reading shares with the interval least(r.end_timestamp, gen.interval_start + '1 hour'::INTERVAL) - greatest(r.start_timestamp, gen.interval_start) ) ) / ( extract(EPOCH FROM -- The number of seconds that the reading shares with the interval least(r.end_timestamp, gen.interval_start + '1 day'::INTERVAL) - greatest(r.start_timestamp, gen.interval_start) ) ))) END as min_rate, tsrange(gen.interval_start, gen.interval_start + '1 hour'::INTERVAL, '()') AS time_interval FROM ((readings r -- This sequence of joins takes the meter id to its unit and in the final join -- it then uses the unit_index for this unit. INNER JOIN meters m ON r.meter_id = m.id) INNER JOIN units u ON m.unit_id = u.id) CROSS JOIN LATERAL generate_series( date_trunc('hour', r.start_timestamp), -- Subtract 1 interval width because generate_series is end-inclusive date_trunc_up('hour', r.end_timestamp) - '1 hour'::INTERVAL, '1 hour'::INTERVAL ) gen(interval_start) GROUP BY r.meter_id, gen.interval_start, u.unit_represent -- The order by ensures that the materialized view will be clustered in this way. ORDER BY gen.interval_start, r.meter_id; -- TODO Check if needed and when to use as not done for hourly. CREATE EXTENSION IF NOT EXISTS btree_gist; -- We need a gist index to support the @> operation. CREATE INDEX if not exists idx_daily_readings_unit ON daily_readings_unit USING GIST(time_interval, meter_id); /* The following function determines the correct duration view to query from, and returns averaged or raw reading from it. It is designed to return data for plotting line graphs. It works on meters. It is the new version of compressed_readings_2 that works with units. It takes these parameters: meter_ids: A array of meter ids to query. graphic_unit_id: The unit id of the unit to use for the graphic. start_timestamp: The start timestamp of the data to return. end_timestamp: The end timestamp of the data to return. point_accuracy: Tells how decisions should be made on which types of points to return. 'auto' if automatic. max_raw_points: The maximum number of data points to return if using the raw points for a meter. Only used if 'auto' for point_accuracy. max_hour_points: The maximum number of data points to return if using the hour view. Only used if 'auto' for point_accuracy. Details on how this function works can be found in the devDocs in the resource generalization document. */ CREATE OR REPLACE FUNCTION meter_line_readings_unit ( meter_ids INTEGER[], graphic_unit_id INTEGER, start_stamp TIMESTAMP, end_stamp TIMESTAMP, point_accuracy reading_line_accuracy, max_raw_points INTEGER, max_hour_points INTEGER ) RETURNS TABLE(meter_id INTEGER, reading_rate FLOAT, min_rate FLOAT, max_rate FLOAT, start_timestamp TIMESTAMP, end_timestamp TIMESTAMP) AS $$ DECLARE requested_range TSRANGE; requested_interval INTERVAL; requested_interval_seconds INTEGER; unit_column INTEGER; frequency INTERVAL; frequency_seconds INTEGER; -- Which index of the meter_id array you are currently working on. current_meter_index INTEGER := 1; -- The id of the meter index working on current_meter_id INTEGER; -- Holds accuracy for current meter. current_point_accuracy reading_line_accuracy; BEGIN -- unit_column holds the column index into the cik table. This is the unit that was requested for graphing. SELECT unit_index INTO unit_column FROM units WHERE id = graphic_unit_id; -- For each frequency of points, verify that you will get the minimum graphing points to use for each meter. -- Start with the raw, then hourly and then daily if others will not work. -- Loop over all meters. WHILE current_meter_index <= cardinality(meter_ids) LOOP -- Reset the point accuracy for each meter so it does what is desired. current_point_accuracy := point_accuracy; current_meter_id := meter_ids[current_meter_index]; -- Make sure the time range is within the reading values for this meter. -- There may be a better way to create the array with one element as last argument. requested_range := shrink_tsrange_to_real_readings(tsrange(start_stamp, end_stamp, '[]'), array_append(ARRAY[]::INTEGER[], current_meter_id)); IF (current_point_accuracy = 'auto'::reading_line_accuracy) THEN -- The request wants automatic calculation of the points returned. -- The request_range will still be infinity if there is no meter data. This causes the -- auto calculation to fail because you cannot subtract them. -- Just check the upper range since simpler. IF (upper(requested_range) = 'infinity') THEN -- We know there is no data but easier to just let a query happen since fast. -- Do daily since that should be the fastest due to the least data in most cases. current_point_accuracy := 'daily'::reading_line_accuracy; ELSE -- The interval of time for the requested_range. requested_interval := upper(requested_range) - lower(requested_range); -- Get the seconds in the interval. -- Wanted to use the INTO syntax used above but could not get it to work so using the set syntax. requested_interval_seconds := (SELECT * FROM EXTRACT(EPOCH FROM requested_interval)); -- Get the frequency that this meter reads at. SELECT reading_frequency INTO frequency FROM meters WHERE id = current_meter_id; -- Get the seconds in the frequency. frequency_seconds := (SELECT * FROM EXTRACT(EPOCH FROM frequency)); -- The first part is making sure that there are no more than maximum raw readings to graph if use raw readings. -- Divide the time being graphed by the frequency of reading for this meter to get the number of raw readings. -- The second part checks if the frequency of raw readings is more than a day and use raw if this is the case -- because even daily would interpolate points. 1 day is 24 hours * 60 minute/hour * 60 seconds/minute = 86400 seconds. -- This can lead to too many points but do this for now since that is unlikely as you would need around 4+ years of data. -- Note this overrides the max raw points if it applies. IF ((requested_interval_seconds / frequency_seconds <= max_raw_points) OR (frequency_seconds >= 86400)) THEN -- Return raw meter data. current_point_accuracy := 'raw'::reading_line_accuracy; -- The first part is making sure that the number of hour points is no more than maximum hourly readings. -- Thus, check if no more than interval in seconds / (60 seconds/minute * 60 minutes/hour) = # hours in interval. -- The second part is making sure that the frequency of reading is an hour or less (3600 seconds) -- so you don't interpolate points by using the hourly data. ELSIF ((requested_interval_seconds / 3600 <= max_hour_points) AND (frequency_seconds <= 3600)) THEN -- Return hourly reading data. current_point_accuracy := 'hourly'::reading_line_accuracy; ELSE -- Return daily reading data. current_point_accuracy := 'daily'::reading_line_accuracy; END IF; END IF; END IF; -- At this point current_point_accuracy should never be 'auto'. IF (current_point_accuracy = 'raw'::reading_line_accuracy) THEN -- Gets raw meter data to graph. RETURN QUERY SELECT r.meter_id as meter_id, CASE WHEN u.unit_represent = 'quantity'::unit_represent_type THEN -- If it is quantity readings then need to convert to rate per hour by dividing by the time length where -- the 3600 is needed since EPOCH is in seconds. ((r.reading / (extract(EPOCH FROM (r.end_timestamp - r.start_timestamp)) / 3600)) * c.slope + c.intercept) WHEN (u.unit_represent = 'flow'::unit_represent_type OR u.unit_represent = 'raw'::unit_represent_type) THEN -- If it is flow or raw readings then it is already a rate so just convert it but also need to normalize -- to per hour. ((r.reading * 3600 / u.sec_in_rate) * c.slope + c.intercept) END AS reading_rate, -- There is no range of values on raw/meter data so return NaN to indicate that. -- The route will return this as null when it shows up in Redux state. cast('NaN' AS DOUBLE PRECISION) AS min_rate, cast('NaN' AS DOUBLE PRECISION) as max_rate, r.start_timestamp, r.end_timestamp FROM (((readings r INNER JOIN meters m ON m.id = current_meter_id) INNER JOIN units u ON m.unit_id = u.id) INNER JOIN cik c on c.row_index = u.unit_index AND c.column_index = unit_column) WHERE lower(requested_range) <= r.start_timestamp AND r.end_timestamp <= upper(requested_range) AND r.meter_id = current_meter_id -- This ensures the data is sorted ORDER BY r.start_timestamp ASC; -- The first part is making sure that the number of hour points is 1440 or less. -- Thus, check if no more than 1440 hours * 60 minutes/hour * 60 seconds/hour = 5184000 seconds. -- The second part is making sure that the frequency of reading is an hour or less (3600 seconds) -- so you don't interpolate points by using the hourly data. ELSIF (current_point_accuracy = 'hourly'::reading_line_accuracy) THEN -- Get hourly points to graph. See daily for more comments. RETURN QUERY SELECT hourly.meter_id AS meter_id, -- Convert the reading based on the conversion found below. -- Hourly readings are already averaged correctly into a rate. hourly.reading_rate * c.slope + c.intercept as reading_rate, hourly.min_rate * c.slope + c.intercept AS min_rate, hourly.max_rate * c.slope + c.intercept AS max_rate, lower(hourly.time_interval) AS start_timestamp, upper(hourly.time_interval) AS end_timestamp FROM (((hourly_readings_unit hourly INNER JOIN meters m ON m.id = current_meter_id) INNER JOIN units u ON m.unit_id = u.id) INNER JOIN cik c on c.row_index = u.unit_index AND c.column_index = unit_column) WHERE requested_range @> time_interval AND hourly.meter_id = current_meter_id -- This ensures the data is sorted ORDER BY start_timestamp ASC; ELSE -- Get daily points to graph. This should be an okay number but can be too many -- if there are a lot of days of readings. -- TODO Someday consider averaging days if too many. RETURN QUERY SELECT daily.meter_id AS meter_id, -- Convert the reading based on the conversion found below. -- Daily readings are already averaged correctly into a rate. daily.reading_rate * c.slope + c.intercept as reading_rate, daily.min_rate * c.slope + c.intercept AS min_rate, daily.max_rate * c.slope + c.intercept AS max_rate, lower(daily.time_interval) AS start_timestamp, upper(daily.time_interval) AS end_timestamp FROM (((daily_readings_unit daily -- Get all the meter_ids in the passed array of meters. -- This sequence of joins takes the meter id to its unit and in the final join -- it then uses the unit_index for this unit. INNER JOIN meters m ON m.id = current_meter_id) INNER JOIN units u ON m.unit_id = u.id) -- This is getting the conversion for the meter (row_index) and unit to graph (column_index). -- The slope and intercept are used above the transform the reading to the desired unit. INNER JOIN cik c on c.row_index = u.unit_index AND c.column_index = unit_column) WHERE requested_range @> time_interval AND daily.meter_id = current_meter_id -- This ensures the data is sorted ORDER BY start_timestamp ASC; END IF; current_meter_index := current_meter_index + 1; END LOOP; END; $$ LANGUAGE 'plpgsql'; /* The following function determines the correct duration view to query from, and returns averaged readings from it. It is designed to return data for plotting line graphs. It works on groups. It is the new version of compressed_group_readings_2 that works with units. It takes these parameters: group_ids: A array of group ids to query. graphic_unit_id: The unit id of the unit to use for the graph. start_timestamp: The start timestamp of the data to return. end_timestamp: The end timestamp of the data to return. point_accuracy: Tells how decisions should be made on which types of points to return. 'auto' if automatic. max_hour_points: The maximum number of data points to return if using the hour view. Only used if 'auto'/'raw' for point_accuracy. Details on how this function works can be found in the devDocs in the resource generalization document and above in the meter function that is equivalent. */ CREATE OR REPLACE FUNCTION group_line_readings_unit ( group_ids INTEGER[], graphic_unit_id INTEGER, start_stamp TIMESTAMP, end_stamp TIMESTAMP, point_accuracy reading_line_accuracy, max_hour_points INTEGER ) RETURNS TABLE(group_id INTEGER, reading_rate FLOAT, start_timestamp TIMESTAMP, end_timestamp TIMESTAMP) AS $$ DECLARE meter_ids INTEGER[]; requested_range TSRANGE; requested_interval INTERVAL; requested_interval_seconds INTEGER; meters_min_frequency INTERVAL; BEGIN -- First get all the meter ids that will be included in one or more groups being queried. -- In case meter is repeated, make this distinct. SELECT array_agg(DISTINCT gdm.meter_id) INTO meter_ids FROM groups_deep_meters gdm INNER JOIN unnest(group_ids) gids(id) ON gdm.group_id = gids.id; -- Calculate point accuracy if request (auto) or if raw since that is not allowed for groups. IF (point_accuracy = 'auto'::reading_line_accuracy OR point_accuracy = 'raw'::reading_line_accuracy) THEN -- The request needs automatic calculation of the points returned. -- Make sure the time range is within the reading values for meters in this group. requested_range := shrink_tsrange_to_real_readings(tsrange(start_stamp, end_stamp, '[]'), meter_ids); -- The request_range will still be infinity if there is no meter data. This causes the -- auto calculation to fail because you cannot subtract them. -- Just check the upper range since simpler. IF (upper(requested_range) = 'infinity') THEN -- We know there is no data but easier to just let a query happen since fast. -- Do daily since that should be the fastest due to the least data in most cases. point_accuracy := 'daily'::reading_line_accuracy; ELSE -- The interval of time for the requested_range. requested_interval := upper(requested_range) - lower(requested_range); -- Get the seconds in the interval. -- Wanted to use the INTO syntax used above but could not get it to work so using the set syntax. requested_interval_seconds := (SELECT * FROM EXTRACT(EPOCH FROM requested_interval)); -- Make sure that the number of hour points is no more than maximum hourly readings. -- Thus, check if no more than interval in seconds / (60 seconds/minute * 60 minutes/hour) = # hours in interval. IF (requested_interval_seconds / 3600 <= max_hour_points) THEN -- Return hourly reading data. point_accuracy := 'hourly'::reading_line_accuracy; ELSE -- Return daily reading data. point_accuracy := 'daily'::reading_line_accuracy; END IF; -- Groups can require reading interpolation because of multiple meters. For example, if one meter -- is 30 day reading frequency then it will interpolate to hourly or daily depending other -- meters (if exist). However, to limit this effect, if hourly has been selected automatically, -- check if shortest meter reading frequency for this group is more than an hour and then -- choose daily instead. IF (point_accuracy = 'hourly'::reading_line_accuracy) THEN -- Find the min reading frequency for all meters in the group. SELECT min(reading_frequency) INTO meters_min_frequency FROM (meters m INNER JOIN unnest(meter_ids) meters(id) ON m.id = meters.id); IF (EXTRACT(EPOCH FROM meters_min_frequency) > 3600) THEN -- The smallest meter frequency is greater than 1 hour (3600 seconds) so use daily instead. point_accuracy = 'daily'::reading_line_accuracy; END IF; END IF; END IF; END IF; -- point_accuracy should either be daily or hourly at this point. RETURN QUERY SELECT gdm.group_id AS group_id, SUM(readings.reading_rate) AS reading_rate, readings.start_timestamp, readings.end_timestamp -- point_accuracy not 'auto' so last two parameters not used so send -1. FROM meter_line_readings_unit(meter_ids, graphic_unit_id, start_stamp, end_stamp, point_accuracy, -1, -1) readings INNER JOIN groups_deep_meters gdm ON readings.meter_id = gdm.meter_id INNER JOIN unnest(group_ids) gids(id) ON gdm.group_id = gids.id GROUP BY gdm.group_id, readings.start_timestamp, readings.end_timestamp -- This ensures the data is sorted ORDER BY readings.start_timestamp ASC; END; $$ LANGUAGE 'plpgsql'; /* The following function returns data for plotting bar graphs. It works on meters. It should not be used on raw readings. It is the new version of compressed_barchart_readings_2 that works with units. It takes these parameters: meter_ids: A array of meter ids to query. graphic_unit_id: The unit id of the unit to use for the graph. bar_width_days: The number of days to use for the bar width. start_timestamp: The start timestamp of the data to return. end_timestamp: The end timestamp of the data to return. */ CREATE OR REPLACE FUNCTION meter_bar_readings_unit ( meter_ids INTEGER[], graphic_unit_id INTEGER, bar_width_days INTEGER, start_stamp TIMESTAMP, end_stamp TIMESTAMP ) RETURNS TABLE(meter_id INTEGER, reading FLOAT, start_timestamp TIMESTAMP, end_timestamp TIMESTAMP) AS $$ DECLARE bar_width INTERVAL; real_tsrange TSRANGE; real_start_stamp TIMESTAMP; real_end_stamp TIMESTAMP; unit_column INTEGER; num_bars INTEGER; BEGIN -- This is how wide (time interval) for each bar. bar_width := INTERVAL '1 day' * bar_width_days; /* This rounds to the day for the start and end times requested. It then shrinks in case the actual readings span less time than the request. This can commonly happen when you get +/-infinity for all readings available. It uses the day reading view because that is faster than using all the readings. This has an issue associated with it: 1) If the readings at the start/end have a partial day then it shows up as a day. The original code did: real_tsrange := shrink_tsrange_to_real_readings(tsrange(date_trunc_up('day', start_stamp), date_trunc('day', end_stamp))); and did not have this issue since it used the readings and then truncated up/down. A more general solution would be to change the daily (and hourly) view so it does not include partial ones at start/end. This would fix this case and also impact other uses in what seems a positive way. Note this does not address that missing days in a bar width get no value so the bar will likely read low. */ real_tsrange := shrink_tsrange_to_meters_by_day(tsrange(start_stamp, end_stamp), meter_ids); -- Get the actual start/end time rounded to the nearest day from the range. real_start_stamp := lower(real_tsrange); real_end_stamp := upper(real_tsrange); -- This gives the number of whole bars that will fit within the real start/end times. For example, if the number of days -- between start and end is 14 days and the bar width is 3 days then you get 4. num_bars := floor(extract(EPOCH FROM real_end_stamp - real_start_stamp) / extract(EPOCH FROM bar_width)); -- This makes the full bars go from the end time to as far back in time as possible. -- This means that if some time was dropped to get full bars it is at the start of the interval. -- It was felt that the most recent readings are the most important so drop older ones. -- It also helps with maps since they use the latest bar for their value. real_start_stamp := real_end_stamp - (num_bars * bar_width); -- Since the inner join on the generate_series adds the bar_width, we need to back up the -- end timestamp by that amount so it stops at the desired end timestamp. real_end_stamp := real_end_stamp - bar_width; -- unit_column holds the column index into the cik table. This is the unit that was requested for graphing. SELECT unit_index INTO unit_column FROM units WHERE id = graphic_unit_id; RETURN QUERY SELECT dr.meter_id AS meter_id, -- dr.reading_rate is the weighted average reading rate per hour over the day. -- Convert to a quantity by multiplying by the time in hours which is 24 since daily values. -- Then convert the reading based on the conversion found below. SUM(dr.reading_rate * 24) * c.slope + c.intercept AS reading, bars.interval_start AS start_timestamp, bars.interval_start + bar_width AS end_timestamp FROM (((((daily_readings_unit dr INNER JOIN generate_series(real_start_stamp, real_end_stamp, bar_width) bars(interval_start) ON tsrange(bars.interval_start, bars.interval_start + bar_width, '[]') @> dr.time_interval) -- Get all the meter_ids in the passed array of meters. INNER JOIN unnest(meter_ids) meters(id) ON dr.meter_id = meters.id) -- This sequence of joins takes the meter id to its unit and in the final join -- it then uses the unit_index for this unit. INNER JOIN meters m ON m.id = meters.id) -- Don't return bar data if raw since cannot sum. INNER JOIN units u ON m.unit_id = u.id AND u.unit_represent != 'raw'::unit_represent_type) -- This is getting the conversion for the meter (row_index) and unit to graph (column_index). -- The slope and intercept are used above the transform the reading to the desired unit. INNER JOIN cik c on c.row_index = u.unit_index AND c.column_index = unit_column) GROUP BY dr.meter_id, bars.interval_start, c.slope, c.intercept; END; $$ LANGUAGE 'plpgsql'; /* The following function returns data for plotting bar graphs. It works on groups. It should not be used on raw readings. It is the new version of compressed_barchart_group_readings_2 that works with units. It takes these parameters: group_ids: A array of group ids to query. graphic_unit_id: The unit id of the unit to use for the graph. bar_width_days: The number of days to use for the bar width. start_timestamp: The start timestamp of the data to return. end_timestamp: The end timestamp of the data to return. */ CREATE OR REPLACE FUNCTION group_bar_readings_unit ( group_ids INTEGER[], graphic_unit_id INTEGER, bar_width_days INTEGER, start_stamp TIMESTAMP, end_stamp TIMESTAMP ) RETURNS TABLE(group_id INTEGER, reading FLOAT, start_timestamp TIMESTAMP, end_timestamp TIMESTAMP) AS $$ DECLARE bar_width INTERVAL; real_tsrange TSRANGE; real_start_stamp TIMESTAMP; real_end_stamp TIMESTAMP; meter_ids INTEGER[]; BEGIN -- First get all the meter ids that will be included in one or more groups being queried. SELECT array_agg(DISTINCT gdm.meter_id) INTO meter_ids FROM groups_deep_meters gdm INNER JOIN unnest(group_ids) gids(id) ON gdm.group_id = gids.id; RETURN QUERY SELECT gdm.group_id AS group_id, SUM(readings.reading) AS reading, readings.start_timestamp, readings.end_timestamp FROM meter_bar_readings_unit(meter_ids, graphic_unit_id, bar_width_days, start_stamp, end_stamp) readings INNER JOIN groups_deep_meters gdm ON readings.meter_id = gdm.meter_id INNER JOIN unnest(group_ids) gids(id) on gdm.group_id = gids.id GROUP BY gdm.group_id, readings.start_timestamp, readings.end_timestamp; END; $$ LANGUAGE 'plpgsql';
package com.bjpowernode.crm.workbench.web.controller; import com.bjpowernode.crm.settings.domain.User; import com.bjpowernode.crm.settings.service.IUserService; import com.bjpowernode.crm.settings.service.impl.IUserServiceImpl; import com.bjpowernode.crm.utils.DateTimeUtil; import com.bjpowernode.crm.utils.PrintJson; import com.bjpowernode.crm.utils.ServiceFactory; import com.bjpowernode.crm.utils.UUIDUtil; import com.bjpowernode.crm.vo.PaginationVo; import com.bjpowernode.crm.workbench.domain.Activity; import com.bjpowernode.crm.workbench.domain.ActivityRemark; import com.bjpowernode.crm.workbench.service.ActivityService; import com.bjpowernode.crm.workbench.service.impl.ActivityServiceImpl; import jdk.nashorn.internal.ir.Flags; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; import java.util.HashMap; import java.util.List; import java.util.Map; /** * @author neo * @date 2021/2/20 * @time 18:26 */ public class ActivityController extends HttpServlet { @Override protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { System.out.println("进入市场活动控制器"); String path = request.getServletPath(); if("/workbench/activity/getUserList.do".equals(path)){ getUserList(request, response); }else if("/workbench/activity/save.do".equals(path)){ save(request, response); }else if("/workbench/activity/pageList.do".equals(path)){ pageList(request, response); }else if("/workbench/activity/delete.do".equals(path)){ delete(request, response); }else if("/workbench/activity/getUserListAndActivity.do".equals(path)){ getUserListAndActivity(request, response); }else if("/workbench/activity/update.do".equals(path)){ update(request, response); }else if("/workbench/activity/detail.do".equals(path)){ detail(request, response); }else if("/workbench/activity/getRemarkListByAid.do".equals(path)){ getRemarkListByAid(request, response); }else if("/workbench/activity/deleteRemark.do".equals(path)){ deleteRemark(request, response); }else if("/workbench/activity/saveRemark.do".equals(path)){ saveRemark(request, response); }else if("/workbench/activity/updateRemark.do".equals(path)){ updateRemark(request, response); } } private void updateRemark(HttpServletRequest request, HttpServletResponse response) { System.out.println("进入市场备注信息修改操作"); String id = request.getParameter("id"); String noteContent = request.getParameter("noteContent"); String editTime = DateTimeUtil.getSysTime(); String editBy = ((User)request.getSession().getAttribute("user")).getName(); String editFlag = "1"; // 1表示已经修改 ActivityRemark activityRemark = new ActivityRemark(); activityRemark.setId(id); activityRemark.setNoteContent(noteContent); activityRemark.setEditFlag(editFlag); activityRemark.setEditTime(editTime); activityRemark.setEditBy(editBy); ActivityService as = (ActivityService) ServiceFactory.getService(new ActivityServiceImpl()); boolean flag = as.updateRemark(activityRemark); Map<String, Object> map = new HashMap<>(); map.put("success", flag); map.put("activityRemark", activityRemark); PrintJson.printJsonObj(response, map); } private void saveRemark(HttpServletRequest request, HttpServletResponse response) { System.out.println("进入备注信息添加"); String noteContent = request.getParameter("noteContent"); String activityId = request.getParameter("activityId"); String id = UUIDUtil.getUUID(); String createTime = DateTimeUtil.getSysTime(); String createBy = ((User) request.getSession().getAttribute("user")).getName(); String editFlag = "0"; ActivityRemark activityRemark = new ActivityRemark(); activityRemark.setId(id); activityRemark.setNoteContent(noteContent); activityRemark.setActivityId(activityId); activityRemark.setCreateBy(createBy); activityRemark.setCreateTime(createTime); activityRemark.setEditFlag(editFlag); ActivityService as = (ActivityService) ServiceFactory.getService(new ActivityServiceImpl()); boolean flag = as.saveRemark(activityRemark); // 后端需要向前端返回的数据有success、activityRemark Map<String, Object> map = new HashMap<>(); map.put("success", flag); map.put("activityRemark", activityRemark); PrintJson.printJsonObj(response, map); } private void deleteRemark(HttpServletRequest request, HttpServletResponse response) { String id = request.getParameter("id"); System.out.println(id); ActivityService as = (ActivityService) ServiceFactory.getService(new ActivityServiceImpl()); boolean flag = as.deleteRemark(id); PrintJson.printJsonFlag(response, flag); } private void getRemarkListByAid(HttpServletRequest request, HttpServletResponse response) { System.out.println("根据市场活动的id取得备注信息列表"); String activityId = request.getParameter("activityId"); ActivityService as = (ActivityService) ServiceFactory.getService(new ActivityServiceImpl()); List<ActivityRemark> remarks = as.getRemarkListByAid(activityId); PrintJson.printJsonObj(response, remarks); } private void detail(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { System.out.println("进入跳转到详细信息页的操作"); String id = request.getParameter("id"); ActivityService as = (ActivityService) ServiceFactory.getService(new ActivityServiceImpl()); Activity activity = as.detail(id); request.setAttribute("activity", activity); request.getRequestDispatcher("/workbench/activity/detail.jsp").forward(request, response); } private void update(HttpServletRequest request, HttpServletResponse response) { System.out.println("进入执行市场活动修改操作"); String id = request.getParameter("id"); String owner = request.getParameter("owner"); String name = request.getParameter("name"); String startDate = request.getParameter("startDate"); String endDate = request.getParameter("endDate"); String cost = request.getParameter("cost"); String description = request.getParameter("description"); // 修改时间 String editTime = DateTimeUtil.getSysTime(); // 修改人:当前登录的用户 String editBy = ((User)request.getSession().getAttribute("user")).getName(); Activity activity = new Activity(); activity.setId(id); activity.setName(name); activity.setOwner(owner); activity.setCost(cost); activity.setStartDate(startDate); activity.setEndDate(endDate); activity.setDescription(description); activity.setEditBy(editBy); activity.setEditTime(editTime); ActivityService as = (ActivityService) ServiceFactory.getService(new ActivityServiceImpl()); boolean flag = as.update(activity); } private void getUserListAndActivity(HttpServletRequest request, HttpServletResponse response) { System.out.println("执行获得用户列表和根据id获取单条市场活动信息对象的controller"); String id = request.getParameter("id"); ActivityService as = (ActivityService) ServiceFactory.getService(new ActivityServiceImpl()); /* 分析: 前端页面需要获取一个userList 还需要获得一个activity对象 考虑到复用率不大,故采取map封装的形式将其返回 */ Map<String, Object> map = as.getUserListAndActivity(id); PrintJson.printJsonObj(response, map); } private void delete(HttpServletRequest request, HttpServletResponse response) { System.out.println("执行市场活动的删除操作"); String[] ids = request.getParameterValues("id"); ActivityService as = (ActivityService) ServiceFactory.getService(new ActivityServiceImpl()); boolean flag = as.delete(ids); PrintJson.printJsonFlag(response, flag); } private void pageList(HttpServletRequest request, HttpServletResponse response) { System.out.println("进入到查询市场活动信息列表的操作(结合条件查询以及分页查询)"); String name = request.getParameter("name"); String owner = request.getParameter("owner"); String startDate = request.getParameter("startDate"); String endDate = request.getParameter("endDate"); int pageNo = Integer.valueOf(request.getParameter("pageNo")); // 每页展现的记录数 int pageSize = Integer.valueOf(request.getParameter("pageSize")); // 计算略过的记录数 int skipCount = (pageNo - 1) * pageSize; // 注意:需要将数据封装了之后传递给service层 // 但是:Vo是从后台查出数据将其封装给前端传递 // 遇到此种情况可以使用map Map<String, Object> map = new HashMap<>(); map.put("name", name); map.put("owner", owner); map.put("startDate", startDate); map.put("endDate", endDate); map.put("skipCount", skipCount); map.put("pageSize", pageSize); ActivityService as = (ActivityService) ServiceFactory.getService(new ActivityServiceImpl()); /* 前端需要的是市场活动信息列表和 一个查询的总记录条数 业务层拿到了以上两项信息之后,然后怎么返回数据呢 map map.put("total":total) map.put("dataList":dataList); map-----json -------------- vo * (复用率少就临时使用map、复用率高就是用Vo) paginationVo<T> private int total; private List<T> dataList; PaginationVo<Activity> vo = new PaginationVo<>(); vo.setTotal(total), vo.setDataList(dataList), 将来分页查询每个模块都有,所以我们选择使用通用的Vo操作起来比较方便 PrintJson vo ---- json字符串 */ PaginationVo<Activity> vo = as.pageList(map); // vo ---- json字符串 PrintJson.printJsonObj(response, vo); } private void save(HttpServletRequest request, HttpServletResponse response) { System.out.println("执行市场活动添加操作"); String id = UUIDUtil.getUUID(); String owner = request.getParameter("owner"); String name = request.getParameter("name"); String startDate = request.getParameter("startDate"); String endDate = request.getParameter("endDate"); String cost = request.getParameter("cost"); String description = request.getParameter("description"); // 创建时间:当前系统时间 String createTime = DateTimeUtil.getSysTime(); // 创建人,当前登录的用户 从session作用域对象中取出。 String createBy = ((User)request.getSession().getAttribute("user")).getName(); Activity activity = new Activity(); activity.setId(id); activity.setOwner(owner); activity.setName(name); activity.setStartDate(startDate); activity.setEndDate(endDate); activity.setCost(cost); activity.setDescription(description); activity.setCreateBy(createBy); activity.setCreateTime(createTime); ActivityService as = (ActivityService) ServiceFactory.getService(new ActivityServiceImpl()); boolean flag = as.save(activity); PrintJson.printJsonFlag(response, flag); } private void getUserList(HttpServletRequest request, HttpServletResponse response) { System.out.println("取得用户信息列表"); IUserService us = (IUserService) ServiceFactory.getService(new IUserServiceImpl()); List<User> uList = us.getUserList(); PrintJson.printJsonObj(response, uList); } }
{ module Lexer ( -- * Invoking Alex Alex , AlexPosn (..) , alexGetInput , alexError , runAlex , alexMonadScan , Range (..) , RangedToken (..) , Token (..) , scanMany ) where import Control.Monad (when) import Data.ByteString.Lazy.Char8 (ByteString) import Data.Text import Data.Text.Encoding import qualified Data.ByteString.Lazy.Char8 as BS } -- In the middle, we insert our definitions for the lexer, which will generate the lexemes for our grammar. %wrapper "monadUserState-bytestring" $digit = [0-9] $alpha = [a-zA-Z] @id = ($alpha | \_ | \= | \& | \! | \|) ($alpha | $digit | \_ | \' | \? | \=)* tokens :- <0> $white+ { skip } -- List <0> "[" { tok LBrack } <0> "]" { tok RBrack } <0> "," { tok Comma } -- Literals <0> "False" { tok LFalse } <0> "True" { tok LTrue } <0> \"[^\"]*\" { tokString } <0> $digit+ { tokInteger } -- Syntax <0> "let" { tok Let } <0> "=" { tok Eq } <0> ";" { tok SemiColon } <0> "in" { tok In } <0> "(" { tok LPar } <0> ")" { tok RPar } -- Comments <0> "--" .*\n { skip } -- Identifiers <0> @id { tokIdentifier } { -- At the bottom, we may insert more Haskell definitions, such as data structures, auxiliary functions, etc. data AlexUserState = AlexUserState { } alexInitUserState :: AlexUserState alexInitUserState = AlexUserState alexEOF :: Alex RangedToken alexEOF = do (pos, _, _, _) <- alexGetInput pure $ RangedToken EOF (Range pos pos) data Range = Range { start :: AlexPosn , stop :: AlexPosn } deriving (Eq, Show) -- | Performs the union of two ranges by creating a new range starting at the -- start position of the first range, and stopping at the stop position of the -- second range. instance Semigroup Range where Range a _ <> Range _ b = Range a b data RangedToken = RangedToken { rtToken :: Token , rtRange :: Range } deriving (Eq, Show) tok :: Token -> AlexAction RangedToken tok ctor inp len = pure RangedToken { rtToken = ctor , rtRange = mkRange inp len } tokString inp@(_, _, str, _) len = pure RangedToken { rtToken = String $ decodeUtf8Lenient $ BS.toStrict $ BS.take len str , rtRange = mkRange inp len } tokInteger :: AlexAction RangedToken tokInteger inp@(_, _, str, _) len = pure RangedToken { rtToken = Integer $ read $ BS.unpack $ BS.take len str , rtRange = mkRange inp len } tokIdentifier inp@(_, _, str, _) len = pure RangedToken { rtToken = Identifier $ decodeUtf8Lenient $ BS.toStrict $ BS.take len str , rtRange = mkRange inp len } data Token -- Identiifers = Identifier Text -- Equals | Eqs -- Literals | String Text | Integer Integer | LFalse | LTrue -- Parentheses | LPar | RPar -- Lists | LBrack | RBrack | Comma -- Syntax | Let | Eq | In | SemiColon -- Ghost | Ghost -- EOF | EOF deriving (Eq, Show) mkRange :: AlexInput -> Int64 -> Range mkRange (start, _, str, _) len = Range{start = start, stop = stop} where stop = BS.foldl' alexMove start $ BS.take len str scanMany :: ByteString -> Either String [RangedToken] scanMany input = runAlex input go where go = do output <- alexMonadScan if rtToken output == EOF then pure [output] else (output :) <$> go }
<!DOCTYPE html> <html lang="pt-BR"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Primeiros passos com o DOM</title> <style> body { background-color: rgb(142, 159, 216); color: white; font: normal 18px serif; } </style> </head> <body> <h1>A Isabela, minha prometida, o mundo feito para nós dois, estamos aqui e ficaremos ali pra cá. Sem mais guerras. Sem mais dores. Sem mais pranto. Vamos retomar ao estado inicial. O mundo sem Ivana. O mundo sem Yanni. O mundo sem prazer carnal. O mundo ideal e prematuro. Onde todos nós estaremos lá... Sem brigas... Intrigas... Desacordos... </h1> <H1>Iniciando dom</H1> <P>No inferno se desculpe com meus irmãos</P> <p>Aprendendo a usar <strong> DOM </strong> em JavaScript.</p> <div id="amores">Clique em mim</div> <div name="sonho"> Sonhos flácidos repleto de memórias ilustres.</div> <script> var corpo = window.document.body var h1 = window.document.getElementsByTagName('h1')[0] var p1 = window.document.getElementsByTagName('p')[1] // Selecionei por tagname, no caso o 'p' (paragraph), e o que está no colchete [X] é o parágrafo. var d = window.document.getElementById('amores') // Aqui foi utilizado a id dentro da diva var n = window.document.getElementsByName('sonho') [0] // Aqui foi por nome na segunda div. window.document.write('Está escrito assim: ' + p1.innerText) p1.style.color = 'blue' corpo.style.background = 'black' /* window.alert(h1.innerText) window.alert(p1.innerText) */ d.style.background = 'green' n.style.background = 'CYAN' var o = window.document.querySelector('div#amores') .style.color = 'pink' </script> </body> </html>
import React, { useState } from 'react'; function SignUp() { const [credentials, setCredentials] = useState({ username: '', password: '', }); const [error, setError] = useState(''); const handleChange = (e) => { const { name, value } = e.target; setCredentials(prevState => ({ ...prevState, [name]: value })); }; const handleSubmit = async (e) => { e.preventDefault(); setError(''); try { const response = await fetch('https://localhost:8080/signup', { method: 'POST', headers: { 'Content-Type': 'application/json', }, body: JSON.stringify(credentials), }); if (!response.ok) { const errorData = await response.text(); setError(errorData); return; } alert('Signup successful'); // Redirect the user or clear the form setCredentials({ username: '', password: '' }); } catch (error) { console.error('Signup error:', error); setError('An error occurred. Please try again later.'); } }; return ( <div> <h2>Sign Up</h2> <form onSubmit={handleSubmit}> <div> <label>Username</label> <input type="text" name="username" value={credentials.username} onChange={handleChange} required /> </div> <div> <label>Password</label> <input type="password" name="password" value={credentials.password} onChange={handleChange} required /> </div> {error && <p style={{ color: 'red' }}>{error}</p>} <button type="submit">Sign Up</button> </form> </div> ); } export default SignUp;
<!DOCTYPE html> <meta charset="utf-8"> <style> body { font: 10px sans-serif; } .axis path, .axis line { fill: none; stroke: #000; shape-rendering: crispEdges; } .x.axis path { display: none; } .line { fill: none; stroke: steelblue; stroke-width: 1.5px; } </style> <body> <script src="../../third/d3.min.js"></script> <script> var margin = {top: 20, right: 80, bottom: 30, left: 50}, width = 960 - margin.left - margin.right, height = 500 - margin.top - margin.bottom; var parseDate = d3.time.format("%b-%Y").parse; var x = d3.time.scale() .range([0, width]); var y = d3.scale.linear() .range([height, 0]); var color = d3.scale.category10(); var xAxis = d3.svg.axis() .scale(x) .orient("bottom"); var yAxis = d3.svg.axis() .scale(y) .orient("left"); var line = d3.svg.line() .interpolate("basis") .x(function(d) { return x(d.date); }) .y(function(d) { return y(d.temperature); }); var svg = d3.select("body").append("svg") .attr("width", width + margin.left + margin.right) .attr("height", height + margin.top + margin.bottom) .append("g") .attr("transform", "translate(" + margin.left + "," + margin.top + ")"); d3.csv("data/cpi.csv", function(error, data) { data = data.slice(9); data = data.map(function(d){ return { "date": d.date, // "sydney": d["Index Numbers ; All groups CPI ; Sydney ;"], "everything": d["Index Numbers ; All groups CPI ; Australia ;"], "health": d["Index Numbers ; Health ; Australia ;"], "education": d["Index Numbers ; Education ; Australia ;"], } }); data.forEach(function(d) { d.date = parseDate(d.date); }); color.domain(d3.keys(data[0]).filter(function(key) { return key !== "date"; })); var cities = color.domain().map(function(name) { return { name: name, values: data.map(function(d) { return {date: d.date, temperature: +d[name]}; }) }; }); x.domain(d3.extent(data, function(d) { return d.date; })); y.domain([ d3.min(cities, function(c) { return d3.min(c.values, function(v) { return v.temperature; }); }), d3.max(cities, function(c) { return d3.max(c.values, function(v) { return v.temperature; }); }) ]); svg.append("g") .attr("class", "x axis") .attr("transform", "translate(0," + height + ")") .call(xAxis); svg.append("g") .attr("class", "y axis") .call(yAxis) .append("text") .attr("transform", "rotate(-90)") .attr("y", 6) .attr("dy", ".71em") .style("text-anchor", "end") .text("CPI"); var city = svg.selectAll(".city") .data(cities) .enter().append("g") .attr("class", "city"); city.append("path") .attr("class", "line") .attr("d", function(d) { return line(d.values); }) .style("stroke", function(d) { return color(d.name); }); // city.append("text") // .datum(function(d) { return {name: d.name, value: d.values[d.values.length - 1]}; }) // .attr("transform", function(d) { return "translate(" + x(d.value.date) + "," + y(d.value.temperature) + ")"; }) // .attr("x", 3) // .attr("dy", ".35em") // .style("text-anchor", "end") // .text(function(d) { return d.name; }); var legend = svg.selectAll('.legend') .data(cities) .enter() .append('g') .attr('class', 'legend'); legend.append('rect') .attr('x', width/2 + 20) .attr('y', function(d, i){ return i * 20;}) .attr('width', 10) .attr('height', 10) .style('fill', function(d) { return color(d.name); }); legend.append('text') .attr('x', width/2 + 35) .attr('y', function(d, i){ return (i * 20) + 9;}) .text(function(d){ return d.name; }); }); </script>
/** * @abstruct list container with key/value pair in linked data structure */ #ifndef __listtable_h_ #define __listtable_h_ #include <stdlib.h> #include <stdbool.h> #include <stdint.h> #ifdef __cplusplus extern "C" { #endif enum { LISTTABLE_THREADSAFE = (0x01), // make it thread-safe LISTTABLE_UNIQUE = (0x01 << 1), // keys are unique LISTTABLE_CASEINSENSITIVE = (0x01 << 2), // keys are case insensitive LISTTABLE_INSERTTOP = (0x01 << 3), // insert new key at the top LISTTABLE_LOOKUPFORWARD = (0x01 << 4), // find key from the top (default: backward) }; typedef struct listtable_s listtable; typedef struct listtable_obj_t listtableObj; typedef struct listtable_data_t listtableData; struct listtable_s { // capsulated member functions bool (*put) (listtable* tbl, const char* name, const void* data, size_t size); bool (*putstr) (listtable* tbl, const char* name, const char* str); bool (*putstrf) (listtable* tbl, const char* name, const char* format, ...); bool (*putint) (listtable* tbl, const char* name, int64_t num); void* (*get) (listtable* tbl, const char* name, size_t* size, bool newmem); char* (*getstr) (listtable* tbl, const char* name, bool newmem); int64_t (*getint) (listtable* tbl, const char* name); listtableData *(*getmulti) (listtable* tbl, const char* name, bool newmem, size_t* numobjs); void (*freemulti) (listtableData* objs); size_t (*remove) (listtable* tbl, const char* name); bool (*removeobj) (listtable* tbl, const listtableObj* obj); bool (*getnext) (listtable* tbl, listtableObj* obj, const char* name, bool newmem); size_t (*size) (listtable* tbl); void (*sort) (listtable* tbl); void (*clear) (listtable* tbl); bool (*save) (listtable* tbl, const char* filepath, char sepchar, bool encode); ssize_t (*load) (listtable* tbl, const char* filepath, char sepchar, bool decode); bool (*debug) (listtable* tbl, FILE* out); void (*lock) (listtable* tbl); void (*unlock) (listtable* tbl); void (*free) (listtable* tbl); // private methods bool (*namematch) (listtableObj* obj, const char* name, uint32_t hash); int (*namecmp) (const char* s1, const char* s2); // private variables - do not access directly bool unique; // keys are unique bool caseinsensitive; // case insensitive key comparison bool keepsorted; // keep table in sorted (default: insertion order) bool inserttop; // add new key at the top. (default: bottom) bool lookupforward; // find keys from the top. (default: backward) void* qmutex; // initialized when listableOPT_THREADSAFE is given size_t num; // number of elements listtableObj* first; // first object pointer listtableObj* last; // last object pointer }; struct listtable_obj_t { uint32_t hash; // 32bit-hash value of object name char* name; // object name void* data; // data size_t size; // data size listtableObj* prev; // previous link listtableObj* next; // next link }; struct listtable_data_t { void* data; size_t size; uint8_t type; }; // public functions extern listtable* listTable(int options); extern bool listablePut(listtable* tbl, const char* name, const void* data, size_t size); extern bool listablePutAsString(listtable* tbl, const char* name, const char* str); extern bool listablePutAsStringf(listtable* tbl, const char* name, const char* format, ...); extern bool listablePutAsInt(listtable* tbl, const char* name, int64_t num); extern void* listableGet(listtable* tbl, const char* name, size_t* size, bool newmem); extern char* listableGetAsString(listtable* tbl, const char* name, bool newmem); extern int64_t listableGetAsInt(listtable* tbl, const char* name); extern listtableData* listableGetMulti(listtable* tbl, const char* name, bool newmem, size_t* numobjs); extern void listableFreeMulti(listtableData* objs); extern size_t listableRemove(listtable* tbl, const char* name); extern bool listableRemoveObj(listtable* tbl, const listtableObj* obj); extern bool listableGetNext(listtable* tbl, listtableObj* obj, const char* name, bool newmem); extern size_t listableSize(listtable* tbl); extern void listableSort(listtable* tbl); extern void listableClear(listtable* tbl); extern bool listableSave(listtable* tbl, const char* filepath, char sepchar, bool encode); extern ssize_t listableLoad(listtable* tbl, const char* filepath, char sepchar, bool decode); extern bool listableDebug(listtable* tbl, FILE *out); extern void listableLock(listtable* tbl); extern void listableUnlock(listtable* tbl); extern void listableFree(listtable* tbl); #ifdef __cplusplus } #endif #endif
using TeamsTranscript.Abstractions; using TeamsTranscript.Abstractions.Configuration; using TeamsTranscript.Abstractions.Transformers; using TechTalk.SpecFlow; namespace TeamsTranscript.Specs.Steps; [Binding] public class TranscriptionTransformerSteps { private readonly ScenarioContext scenarioContext; public TranscriptionTransformerSteps(ScenarioContext scenarioContext) { this.scenarioContext = scenarioContext; } [Given(@"I have the following list of transformations:")] public void GivenIHaveTheFollowingListOfTransformations(Table table) { List<Replacement> replacements = new(); foreach (var row in table.Rows) { replacements.Add(new Replacement(row["old"], row["new"])); } this.scenarioContext.Add("transformation_options", new TransformationOptions(replacements)); } [When(@"I transform the Transcription")] public void WhenITransformTheTranscription() { var transcriptions = this.scenarioContext.Get<IEnumerable<Transcription>>("transcriptions"); var transformationOptions = this.scenarioContext.Get<TransformationOptions>("transformation_options"); TranscriptionTransformer transformer = new(); IEnumerable<Transcription> processesTranscriptions = transformer.Transform(transcriptions, transformationOptions); this.scenarioContext.Add("results", processesTranscriptions); } }
// // RadioStations.swift // skurring // // Created by Daniel Bornstedt on 26/07/2019. // Copyright © 2019 Daniel Bornstedt. All rieghts reserved. // import Foundation import UIKit import MarqueeLabel protocol RadioPlayerViewControllerHandler: class { func playerViewControllerDidDismiss() func playerViewControllerDidShow() } final class RadioPlayerViewController: UIViewController { private let styleGuide = StyleGuideFactory.current weak var radioPlayerViewControllerDelegate: RadioPlayerViewControllerHandler? private var radioPlayer: RadioPlayer? { didSet { self.radioPlayer?.metaDataHandlerDelegate = self } } private lazy var radioStations: [RadioObject] = [] private var currentIndex = 0 private let isLandscape = UIDevice.current.orientation.isLandscape private let speedometer = SpeedometerView() private let featureStack = FeatureStackView() private let weatherView = WeatherView() private let radioImageView = UIImageView() private let radioNameTextLabel = UILabel() private let metaDataTextLabel = MarqueeLabel( frame: .zero, duration: 8, fadeLength: 30 ) private var hiResLabel: UILabel = { let label = UILabel() label.text = "Hi-Res \n Audio" label.textColor = .white label.numberOfLines = 2 label.font = UIFont.systemFont(ofSize: 10) return label }() private func nextStation() { currentIndex = radioStations.index(after: currentIndex) print(radioStations[currentIndex].name) } private var portraitConstraints = [NSLayoutConstraint]() private var landscapeConstraints = [NSLayoutConstraint]() init(for index: Int, radioStations: [RadioObject]) { super.init(nibName: nil, bundle: nil) self.currentIndex = index self.radioStations = radioStations NotificationCenter.default.addObserver( self, selector: #selector(applicationDidBecameActive), name: .applicationDidBecomeActive, object: nil ) } required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") } deinit { NotificationCenter.default.removeObserver(self) radioPlayer = nil } override func viewDidLoad() { addSubViews() addDefaultConstraints() setupSubviews() addGestures() handleLandscapeRotation(isLandscape: isLandscape) setRadioData { [weak self] radioStation in guard let self = self else { return } let isHQAudio = UserDefaults().bool(forKey: ConstantHelper.streamQualityHigh) self.hiResLabel.isHidden = !isHQAudio || radioStation.radioHQURL.isEmpty let radioURL = isHQAudio && !radioStation.radioHQURL.isEmpty ? radioStation.radioHQURL : radioStation.radioURL self.radioPlayer = RadioPlayer( radioStream: radioURL, channelName: radioStation.name ) self.updateUIWithRadioStationData(with: radioStation) } } override func viewDidAppear(_ animated: Bool) { DispatchQueue.main.async { self.radioPlayer?.play() } } override func viewWillDisappear(_ animated: Bool) { radioPlayerViewControllerDelegate?.playerViewControllerDidDismiss() } override func viewWillAppear(_ animated: Bool) { radioPlayerViewControllerDelegate?.playerViewControllerDidShow() speedometer.isHidden = !UserDefaults().bool(forKey: ConstantHelper.speedometer) radioImageView.isHidden = !speedometer.isHidden featureStack.isHidden = !UserDefaults().bool(forKey: ConstantHelper.airPlay) radioNameTextLabel.isHidden = !UserDefaults().bool(forKey: ConstantHelper.radioChannel) metaDataTextLabel.isHidden = !UserDefaults().bool(forKey: ConstantHelper.metadataInfo) weatherView.isHidden = !UserDefaults().bool(forKey: ConstantHelper.weather) if !speedometer.isHidden || !weatherView.isHidden { LocationManager.shared.startUpdatingLocation() } } override func viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator) { let islandScape = UIDevice.current.orientation.isLandscape handleLandscapeRotation(isLandscape: islandScape) } private func updateUIWithRadioStationData(with station: RadioObject) { DispatchQueue.main.async { self.radioImageView.image = station.image self.radioNameTextLabel.text = station.name } } private func setupSubviews() { view.backgroundColor = styleGuide.colors.buttonBackgroundColor metaDataTextLabel.textColor = .white radioNameTextLabel.textColor = .white metaDataTextLabel.textAlignment = .center radioNameTextLabel.textAlignment = .center metaDataTextLabel.font = UIFont.systemFont(ofSize: 20) radioNameTextLabel.font = UIFont.systemFont(ofSize: 20) radioImageView.contentMode = .scaleAspectFit } private func addSubViews() { let subViews = [ radioImageView, metaDataTextLabel, radioNameTextLabel, featureStack, speedometer, weatherView, hiResLabel ] subViews.forEach(view.addSubview) } private func setRadioData(completion: @escaping (RadioObject) -> Void) { for radioStation in radioStations { if radioStation.buttonTag == currentIndex { DispatchQueue.main.async { completion(radioStation) } } } } private func addGestures() { let gesture = UITapGestureRecognizer( target: self, action: #selector(dismissVC) ) view.addGestureRecognizer(gesture) } @objc func dismissVC() { self.dismiss(animated: true, completion: nil) } @objc private func applicationDidBecameActive(notification: Notification) { radioPlayer?.play() } private func handleLandscapeRotation(isLandscape: Bool) { deactivateOrientationConstraints() if !isLandscape { featureStack.updateAxis(orientation: .portrait) addPortraitConstraints() } else { featureStack.updateAxis(orientation: .landscape) addLandscapeConstraints() } } private func addDefaultConstraints() { radioImageView.translatesAutoresizingMaskIntoConstraints = false radioNameTextLabel.translatesAutoresizingMaskIntoConstraints = false metaDataTextLabel.translatesAutoresizingMaskIntoConstraints = false speedometer.translatesAutoresizingMaskIntoConstraints = false hiResLabel.translatesAutoresizingMaskIntoConstraints = false NSLayoutConstraint.activate( [ hiResLabel.leadingAnchor.constraint(equalTo: view.safeAreaLayoutGuide.leadingAnchor, constant: 5), hiResLabel.topAnchor.constraint(equalTo: view.safeAreaLayoutGuide.topAnchor, constant: 5), radioImageView.heightAnchor.constraint(equalToConstant: 150), radioImageView.widthAnchor.constraint(equalToConstant: 200), radioImageView.centerXAnchor.constraint(equalTo: view.centerXAnchor), radioImageView.centerYAnchor.constraint(equalTo: view.centerYAnchor), radioNameTextLabel.heightAnchor.constraint(equalToConstant: 30), radioNameTextLabel.leadingAnchor.constraint(equalTo: view.leadingAnchor), radioNameTextLabel.trailingAnchor.constraint(equalTo: view.trailingAnchor), radioNameTextLabel.bottomAnchor.constraint(equalTo: metaDataTextLabel.topAnchor), metaDataTextLabel.heightAnchor.constraint(equalToConstant: 30), metaDataTextLabel.leadingAnchor.constraint(equalTo: view.leadingAnchor), metaDataTextLabel.trailingAnchor.constraint(equalTo: view.trailingAnchor), metaDataTextLabel.bottomAnchor.constraint(equalTo: view.safeAreaLayoutGuide.bottomAnchor) ] ) } private func addPortraitConstraints() { portraitConstraints = [ speedometer.heightAnchor.constraint(equalToConstant: 200), speedometer.widthAnchor.constraint(equalToConstant: 200), speedometer.centerYAnchor.constraint(equalTo: view.centerYAnchor), speedometer.centerXAnchor.constraint(equalTo: view.centerXAnchor), featureStack.widthAnchor.constraint(equalToConstant: 270), featureStack.heightAnchor.constraint(equalToConstant: 40), featureStack.bottomAnchor.constraint(equalTo: radioNameTextLabel.topAnchor, constant: -20), featureStack.centerXAnchor.constraint(equalTo: view.centerXAnchor), weatherView.topAnchor.constraint(equalTo: view.topAnchor, constant: 20), weatherView.trailingAnchor.constraint(equalTo: view.safeAreaLayoutGuide.trailingAnchor, constant: -20), weatherView.heightAnchor.constraint(equalToConstant: 70), weatherView.widthAnchor.constraint(equalToConstant: 100), ] NSLayoutConstraint.activate(portraitConstraints) } private func addLandscapeConstraints() { landscapeConstraints = [ speedometer.heightAnchor.constraint(equalToConstant: 300), speedometer.widthAnchor.constraint(equalToConstant: 300), speedometer.centerXAnchor.constraint(equalTo: view.centerXAnchor), speedometer.bottomAnchor.constraint(equalTo: radioNameTextLabel.topAnchor), featureStack.widthAnchor.constraint(equalToConstant: 30), featureStack.heightAnchor.constraint(equalToConstant: 250), featureStack.leadingAnchor.constraint(equalTo: view.safeAreaLayoutGuide.leadingAnchor, constant: 20), weatherView.topAnchor.constraint(equalTo: view.topAnchor, constant: 20), weatherView.trailingAnchor.constraint(equalTo: view.safeAreaLayoutGuide.trailingAnchor, constant: -20), weatherView.heightAnchor.constraint(equalToConstant: 100), weatherView.widthAnchor.constraint(equalToConstant: 100), ] NSLayoutConstraint.activate(landscapeConstraints) } private func deactivateOrientationConstraints() { NSLayoutConstraint.deactivate(portraitConstraints) NSLayoutConstraint.deactivate(landscapeConstraints) } } extension RadioPlayerViewController: MetaDataHandlerDelegate { func fetchMetaData(metaData: String?) { DispatchQueue.main.async { self.metaDataTextLabel.text = metaData } } }