text
stringlengths 184
4.48M
|
---|
/*
https://docs.nestjs.com/controllers#controllers
*/
import {
Controller,
Delete,
Get,
Param,
Post,
Query,
Res,
UploadedFile,
UseInterceptors,
} from '@nestjs/common';
import { FileInterceptor } from '@nestjs/platform-express';
import { ApiBasicAuth, ApiTags } from '@nestjs/swagger';
import { CurrentUser } from 'src/decorators';
import { UserEntity } from 'src/entities';
import { FilesService } from './files.service';
import { FetchDto } from 'src/dto/fetch.dto';
import { Response } from 'express';
@ApiTags('Files')
@ApiBasicAuth('access-token')
@Controller('files')
export class FilesController {
constructor(private filesService: FilesService) {}
@Post('/upload-image')
@UseInterceptors(FileInterceptor('image'))
async uploadImage(
@UploadedFile() image: Express.Multer.File,
@CurrentUser() currentUser: UserEntity,
): Promise<any> {
return this.filesService.createFileImage(image, currentUser);
}
@Get('/')
paginate(
@Query() fetchDto: FetchDto,
@CurrentUser() currentUser: UserEntity,
@Res({ passthrough: true }) res: Response,
) {
return this.filesService.paginate(fetchDto, currentUser, res);
}
@Get(':id')
findOne(@Param('id') id: string) {
return this.filesService.findById(id);
}
@Delete(':id')
delete(@Param('id') id: string) {
return this.filesService.delete(id);
}
} |
// function genericConstraint1<T>(arg: T): T {
// console.log(arg.length) TIDAK BISA KARENA DATA DINAMIS/GENERIC
// return arg
// }
interface Length {
length: number
}
function genericConstraint1<T extends Length>(arg: T): T {
console.log(arg.length)
return arg
}
const generic = genericConstraint1('Tes')
console.log(generic)
// const generic2 = genericConstraint1(222) // Tidak bisa karena tidak bisa dihitung length nya\
const generic2 = genericConstraint1({ length: 10, value: 222}) |
import { useEffect, useState } from "react";
import { createQuestion, getSubjects } from "../../utils/QuizService";
const AddQuestion = () => {
const [question, setQuestion] = useState("");
const [questionType, setQuestionType] = useState("single");
const [choices, setChoices] = useState([""]);
const [correctAnswers, setCorrectAnswers] = useState([""]);
const [subject, setSubject] = useState("");
const [newSubject, setNewSubject] = useState("");
const [subjectOptions, setSubjectOptions] = useState([""]);
useEffect(()=>{
fetchSubjects();
},[])
const fetchSubjects = async () => {
try {
const subjectData = await getSubjects();
setSubjectOptions(subjectData);
} catch (error) {
console.error(error);
}
};
const handleAddChoice = () => {
const lastChoice = choices[choices.length - 1];
const lastChoiceLetter = lastChoice ? lastChoice.charAt(0) : "A";
const newChoiceLetter = String.fromCharCode(
lastChoiceLetter.charCodeAt(0) + 1
);
const newChoice = `${newChoiceLetter}.`;
setChoices([...choices, newChoice]);
};
const handleRemoveChoice = (index) => {
setChoices(choices.filter((choice, i) => i !== index));
};
const handleChoiceChange = (index, value) => {
setChoices(choices.map((choice, i) => (i === index ? value : choice)));
};
const handleCorrectAnswerChange = (index, value) => {
setCorrectAnswers(
correctAnswers.map((answer, i) => (i === index ? value : answer))
);
};
const handleAddCorrectAnswer = () => {
setCorrectAnswers([...correctAnswers, ""]);
};
const handleRemoveCorrectAnswer = (index) => {
setCorrectAnswers(correctAnswers.filter((answer, i) => i !== index));
};
const handleSubmit = async (e) => {
e.preventDefault();
try {
const result = {
question,
questionType,
choices,
correctAnswers: correctAnswers.map((answer) => {
const choiceLetter = answer.charAt(0).toUpperCase();
const choiceIndex = choiceLetter.charCodeAt(0) - 65;
return choiceIndex >= 0 && choiceIndex < choices.length
? choiceLetter
: null;
}),
subject,
};
await createQuestion(result);
setQuestion("");
setQuestionType("");
setChoices([""]);
setCorrectAnswers([""]);
setSubject("");
} catch (error) {
console.error(error);
}
};
const handleAddSubject = () => {
if (newSubject.trim() !== "") {
setSubject(newSubject.trim());
setSubjectOptions([...subjectOptions, newSubject.trim()]);
setNewSubject("");
}
};
return (
<div className="container">
<div className="row justify-content-center">
<div className="col-md-6 mt-5">
<div className="card">
<div className="card-header">
<h5>Add New Question</h5>
</div>
<div className="card-body">
<form onSubmit={handleSubmit} className="p-2">
<div className="mb-3">
<label htmlFor="subject" className="form-label text">
{" "}
Select a Subject{" "}
</label>
<select
name=""
id="subject"
value={subject}
onChange={(e) => setSubject(e.target.value)}
className="form-control"
>
<option value={""}>Select a subject</option>
<option value={"New"}>Add New Subject</option>
{subjectOptions.map((option) => {
<option key={option} value={option}>
{option}
</option>;
})}
</select>
</div>
{subject == "New" && (
<div className="mb-3">
<label
htmlFor="new-subject"
className="form-label text-info"
>
Add a new Subject
</label>
<input
type="text"
id="new-subject"
value={newSubject}
onChange={(e) => setNewSubject(e.target.value)}
className="form-control"
/>
<button
type="button"
className="btn btn-outline-primary btn-sm"
onClick={handleAddSubject}
>
Add Subject
</button>
</div>
)}
<div className="mb-2">
<label htmlFor="question" className="form-label text-info">
Question
</label>
<textarea
className="form-control"
rows={4}
value={question}
onChange={(e) => setQuestion(e.target.value)}
></textarea>
</div>
<div className="mb-3">
<label
htmlFor="question-type"
className="form-label text-info"
>
Question Type
</label>
<select
className="form-control"
id="question-type"
value={questionType}
onChange={(e) => setQuestionType(e.target.value)}
>
<option value={"single"}>Single Answer</option>
<option value={"multiple"}>Multiple Answer</option>
</select>
</div>
<div className="mb-3">
<label htmlFor="choices" className="form-label text-info">
Choices
</label>
{choices.map((choice, index) => {
<div key={index} className="input-group mb-3">
<input
type="text"
value={choice}
onChange={(e) =>
handleChoiceChange(index, e.target.value)
}
className="form-control"
/>
<button
onClick={() => handleRemoveChoice(index)}
className="btn btn-outline-danger btn-sm"
>
Remove
</button>
</div>;
})}
<button
onClick={() => handleAddChoice}
className="btn btn-outline-primary btn-sm"
>
Add Choice
</button>
</div>
{questionType === "single" && (
<div className="mb-3">
<label htmlFor="answer" className="form-label text-info">
Correct Answers
</label>
<input
type="text"
value={correctAnswers[0]}
onChange={(e) =>
handleCorrectAnswerChange(0, e.target.value)
}
className="form-control"
/>
</div>
)}
{questionType === "mutilple" && (
<div className="mb-3">
<label htmlFor="answer" className="form-label text-info">
Correct Answers (s)
</label>
{correctAnswers.map((answer, index) => {
<div>
<input
type="text"
value={answer[0]}
onChange={(e) =>
handleCorrectAnswerChange(index, e.target.value)
}
className="form-control"
/>
{
index > 0 && (
<button type="button"
className="btn btn-danger btn-sm"
onClick={() => handleRemoveCorrectAnswer(index)}
>
Remove
</button>
)
}
</div>;
})}
<button
type="button"
className="btn btn-outline-info"
onClick={handleAddCorrectAnswer}
>Add Correct Answer</button>
</div>
)}
{
!correctAnswers.length && <p>Please enter atleast one correct answer</p>
}
<div className="btn-group">
<button type="submit" className="btn btn-outline-success mr-2">
Save Question
</button>
<button type="submit" className="btn btn-outline-success mr-2">
Save Question
</button>
</div>
</form>
</div>
</div>
</div>
</div>
</div>
);
};
export default AddQuestion; |
@extends('main')
@section('title', '| Edit Blog Post')
@section('stylesheets')
{!! Html::style('css/select2.min.css') !!}
<script src="//cloud.tinymce.com/stable/tinymce.min.js"></script>
<script>
tinymce.init({
selector: 'textarea',
plugins: 'link code',
menubar: false
});
</script>
@endsection
@section('content')
<div class="row">
{!! Form::model($post, ['route' => ['posts.update', $post->id], 'method' => 'PUT', 'files'=>true]) !!}
<div class="col-md-8">
{{ Form::label('title', 'Title:') }}
{{ Form::text('title', null, ["class" => 'form-control input-lg']) }}
{{ Form::label('slug', 'Slug:', ['class' => 'form-spacing-top']) }}
{{ Form::text('slug', null, ["class" => 'form-control']) }}
{{ Form::label('tags', 'Tags:', ['class' => 'form-spacing-top']) }}
{{ Form::select('tags[]', $tags, null, ['class'=>'form-control select2-multi', 'multiple' => 'multiple'])}}
{{ Form::label('featured_img', 'Update Featured Image:', ['class' => 'form-spacing-top'])}}
{{ Form::file('featured_img')}}
{{ Form::label('category_id', 'Category', ['class' => 'form-spacing-top'])}}
{{ Form::select('category_id', $categories, $post->category_id, ['class'=>'form-control'])}}
{{ Form::label('body', "Body:", ['class' => 'form-spacing-top']) }}
{{ Form::textarea('body', null, ['class' => 'form-control']) }}
</div>
<div class="col-md-4">
<div class="well">
<dl class="dl-horizontal">
<dt>Created At:</dt>
<dd>{{ date('M j, Y h:ia', strtotime($post->created_at)) }}</dd>
</dl>
<dl class="dl-horizontal">
<dt>Last Updated:</dt>
<dd>{{ date('M j, Y h:ia', strtotime($post->updated_at)) }}</dd>
</dl>
<hr>
<div class="row">
<div class="col-sm-6">
{!! Html::linkRoute('posts.show', 'Cancel', array($post->id), array('class' => 'btn btn-danger btn-block')) !!}
</div>
<div class="col-sm-6">
{{ Form::submit('Save Changes', ['class' => 'btn btn-success btn-block']) }}
</div>
</div>
</div>
</div>
{!! Form::close() !!}
</div> <!-- end of .row (form) -->
@stop
@section('scripts')
{!! Html::script('js/select2.min.js') !!}
<script type="text/javascript">
$(".select2-multi").select2();
$('.select2-multi').select2().val({!! json_encode($post->tags()->allRelatedIds()) !!}).trigger('change');
</script>
@endsection |
import React, { useState, useEffect } from 'react';
import { useRouter } from 'next/router';
import { useDebounce } from '@/hooks/useDebounce';
import signupStyle from '../styles/Signup.module.css';
import { timeToString } from '@/utils/CommonUtils';
import axios from 'axios';
//mui notification
import Snackbar from '@mui/material/Snackbar';
import Button from '@mui/material/Button';
const Signup = () => {
//아이디
const [id, setId] = useState('');
const [idValidate, setIdValidate] = useState<boolean>(true);
//비밀번호
const [password, setPassword] = useState('');
const [passwordValidate, setPasswordValidate] = useState<boolean>(true);
//비밀번호 확인
const [pwDoubleCheckText, setPwDoubleCheckText] = useState('');
const [pwDoubleValidate, setPwDoubleValidate] = useState<boolean>(true);
//이메일
const [email, setEmail] = useState('');
const [emailValidate, setEmailValidate] = useState<boolean>(true);
const [sendMailLoading, setSendMailLoading] = useState(false);
//이메일 인증번호 ID
const [verifyCode, setVerifyCode] = useState('');
const [verifyCodeId, setVerifyCodeId] = useState('');
const [verifyCodeValidate, setVerifyCodeValidate] = useState<boolean>(true);
//닉네임
const [nickname, setNickname] = useState('');
const [nicknameValidate, setNicknameValidate] = useState<boolean>(true);
//블로그 이름
const [blogName, setBlogName] = useState('');
const [blogNameValidate, setBlogNameValidate] = useState<boolean>(true);
//notification 팝업
const [showNoti, setShowNoti] = useState(false);
const router = useRouter();
// 타이핑할때마다 아이디 중복검사 무분별한 api 호출을 막기위해 0.5초 딜레이를 두고 딜레이안에 다른 값이 들어오면 딜레이 초기화
const debouncedSearchTerm = useDebounce(id, 500);
useEffect(() => {
if (debouncedSearchTerm) {
idCheck(debouncedSearchTerm);
}
}, [debouncedSearchTerm]);
const submitHandler = async (e: React.FormEvent<HTMLFormElement>) => {
e.preventDefault();
//email, password 유효성 검사
if (!(await idCheck(id))) {
return;
} else if (!(await emailCheck(email))) {
return;
} else if (!passwordCheck(password)) {
return;
} else if (!passwordDoubleCheck(pwDoubleCheckText)) {
return;
} else if (!blogNameCheck(blogName)) {
return;
} else if (!nicknameCheck(nickname)) {
return;
} else if (!(await verifyCodeCheck())) {
return;
}
axios.post('/api/HandleUser', { data: { type: 'deleteVerifyCode', verifyCodeId: verifyCodeId } });
const currentTime = timeToString(new Date());
const params = { type: 'signup', id: id, email: email, nickname: nickname.replaceAll(' ', '').replaceAll('\\', '\\\\'), password: password, blogName: blogName.replaceAll('\\', '\\\\'), rgsnDttm: currentTime, amntDttm: currentTime };
await axios.post('/api/HandleUser', { data: params }).then((res) => {
setShowNoti(true);
});
};
const idCheck = async (id: string) => {
const idRegEx = /^[a-z0-9]{5,20}$/;
let isValidate = idRegEx.test(id);
const params = { type: 'getUser', id: id };
if (!isValidate) {
setIdValidate(false);
document.querySelector('.idErrMsg')!.innerHTML = '<div class="mt5">아이디는 5-20자의 영문 소문자, 숫자만 사용 가능합니다. </div>';
} else {
//ID 중복검사
await axios.post('/api/HandleUser', { data: params }).then((res) => {
const userCnt = res.data.totalItems;
if (userCnt > 0) {
isValidate = false;
document.querySelector('.idErrMsg')!.innerHTML = '<div class="mt5">이미 가입되어 있는 아이디입니다.</div>';
} else {
setIdValidate(true);
document.querySelector('.idErrMsg')!.innerHTML = '';
}
});
}
return isValidate;
};
const emailCheck = async (email: string) => {
const emailRegEx = /^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/;
let isValidate = emailRegEx.test(email);
if (!isValidate) {
setEmailValidate(false);
document.querySelector('.emailErrMsg')!.innerHTML = '<div class="mt5">이메일 형식이 올바르지 않습니다.</div>';
} else {
setEmailValidate(true);
document.querySelector('.emailErrMsg')!.innerHTML = '';
}
return isValidate;
};
const passwordCheck = (password: string) => {
//8~16자의 영문 대/소문자, 숫자를 반드시 포함하여 구성(특수문자도 포함가능)
const passwordRegEx = /^(?=.*[A-Za-z])(?=.*\d)[A-Za-z\d\S]{8,16}$/;
const isValidate = passwordRegEx.test(password);
if (!isValidate) {
setPasswordValidate(false);
document.querySelector('.passwordErrMsg')!.innerHTML = '<div class="mt5">비밀번호는 8~16자의 영문 대/소문자, 숫자, 특수문자를 조합하여 입력하세요.</div>';
} else {
setPasswordValidate(true);
document.querySelector('.passwordErrMsg')!.innerHTML = '';
}
return isValidate;
};
const passwordDoubleCheck = (passwordText: string) => {
const isValidate = password === passwordText ? true : false;
if (!isValidate) {
setPwDoubleValidate(false);
document.querySelector('.pwDobleCheckErrMsg')!.innerHTML = '<div class="mt5">비밀번호가 일치하지 않습니다.</div>';
} else {
setPwDoubleValidate(true);
document.querySelector('.pwDobleCheckErrMsg')!.innerHTML = '';
}
return isValidate;
};
const nicknameCheck = (nickname: string) => {
const isValidate = nickname.replaceAll(' ', '').length === 0 ? false : true;
if (!isValidate) {
setNicknameValidate(false);
document.querySelector('.nicknameErrMsg')!.innerHTML = '<div class="mt5">닉네임을 입력해주세요.</div>';
} else {
setNicknameValidate(true);
document.querySelector('.nicknameErrMsg')!.innerHTML = '';
}
return isValidate;
};
const blogNameCheck = (blogName: string) => {
const isValidate = blogName.replaceAll(' ', '').length === 0 ? false : true;
if (!isValidate) {
setBlogNameValidate(false);
document.querySelector('.blogNameErrMsg')!.innerHTML = '<div class="mt5">블로그 이름을 입력해주세요.</div>';
} else {
setBlogNameValidate(true);
document.querySelector('.blogNameErrMsg')!.innerHTML = '';
}
return isValidate;
};
const closeNoti = (event?: React.SyntheticEvent | Event, reason?: string) => {
if (reason === 'clickaway') {
return;
}
setShowNoti(false);
router.push('/');
};
const mailHandler = async () => {
if (!(await emailCheck(email))) {
return;
}
if (!sendMailLoading) {
alert('입력하신 이메일 주소로 인증번호가 발송되었습니다.\n인증번호는 발송시간을 기준으로 24시간동안 유효합니다. ');
setSendMailLoading(true);
sendMail();
}
};
const sendMail = async () => {
//기존에 인증번호가 있고 재진행하는 경우라면 기존 인증번호 데이터는 삭제
if (verifyCodeId) {
axios.post('/api/HandleUser', { data: { type: 'deleteVerifyCode', verifyCodeId: verifyCodeId } });
}
const params = { mode: 'sendMailCode', mailAddress: email };
await axios.post('/api/SendMailHandler', { data: params }).then((res) => {
setVerifyCodeId(res.data.insertId);
});
setSendMailLoading(false);
};
const verifyCodeCheck = async () => {
let isValidate;
if (verifyCode.replaceAll(' ', '').length === 0) {
setVerifyCodeValidate(false);
isValidate = false;
document.querySelector('.verifyCodeErrMsg')!.innerHTML = '<div class="mt5">인증번호를 입력해주세요.</div>';
return isValidate;
} else if (!verifyCodeId) {
setVerifyCodeValidate(false);
isValidate = false;
document.querySelector('.verifyCodeErrMsg')!.innerHTML = '<div class="mt5">이메일 인증을 진행해주세요.</div>';
return isValidate;
} else {
const params = { userInputCode: verifyCode.replaceAll(' ', ''), verifyCodeId: verifyCodeId };
isValidate = (await axios.post('/api/CheckVerifyCode', { data: params })).data.isValid;
if (!isValidate) {
setVerifyCodeValidate(false);
document.querySelector('.verifyCodeErrMsg')!.innerHTML = '<div class="mt5">인증번호가 일치하지 않습니다.</div>';
} else {
setVerifyCodeValidate(true);
document.querySelector('.verifyCodeErrMsg')!.innerHTML = '';
}
}
return isValidate;
};
return (
<div className={signupStyle.signup_div}>
<span className={signupStyle.signup_title}>keylog</span>
<form onSubmit={submitHandler} className={signupStyle.signup_form}>
<div className={signupStyle.signup_input_div}>
<div className={`${signupStyle.signup_emoji} ${idValidate ? '' : signupStyle.validateErr} btlr`}>
<i className={'fa-solid fa-user'}></i>
</div>
<input
type='text'
value={id}
className={`${signupStyle.signup_input_text} ${idValidate ? '' : signupStyle.validateErr} btrr`}
placeholder='아이디'
autoComplete='off'
required
onChange={(e) => {
setId(e.target.value);
}}
></input>
</div>
<div className={signupStyle.signup_input_div}>
<div className={`${signupStyle.signup_emoji} ${passwordValidate ? '' : signupStyle.validateErr}`}>
<i className='fa-solid fa-lock'></i>
</div>
<input
type='password'
value={password}
className={`${signupStyle.signup_input_text} ${passwordValidate ? '' : signupStyle.validateErr}`}
placeholder='비밀번호'
required
autoComplete='off'
onChange={(e) => {
setPassword(e.target.value);
passwordCheck(e.target.value);
}}
></input>
</div>
<div className={signupStyle.signup_input_div}>
<div className={`${signupStyle.signup_emoji} ${pwDoubleValidate ? '' : signupStyle.validateErr}`}>
<i className='fa-solid fa-check'></i>
</div>
<input
type='password'
value={pwDoubleCheckText}
className={`${signupStyle.signup_input_text} ${pwDoubleValidate ? '' : signupStyle.validateErr}`}
placeholder='비밀번호 확인'
required
autoComplete='off'
onChange={(e) => {
setPwDoubleCheckText(e.target.value);
passwordDoubleCheck(e.target.value);
}}
></input>
</div>
<div className={signupStyle.signup_input_div}>
<div className={`${signupStyle.signup_emoji} ${emailValidate ? '' : signupStyle.validateErr}`}>
<i className={'fa-solid fa-envelope'}></i>
</div>
<input
type='text'
value={email}
className={`${signupStyle.signup_input_text} ${emailValidate ? '' : signupStyle.validateErr} brn`}
placeholder='이메일'
autoComplete='off'
required
onChange={(e) => {
setEmail(e.target.value);
emailCheck(e.target.value);
}}
></input>
<div className={`${signupStyle.signup_vrfy_code_btn_div}`}>
<button id='signup_vrfy_code_btn' className={`${signupStyle.signup_vrfy_code_btn}`} onClick={() => mailHandler()}>
인증번호 요청
</button>
</div>
</div>
<div className={signupStyle.signup_input_div}>
<div className={`${signupStyle.signup_emoji} ${verifyCodeValidate ? '' : signupStyle.validateErr}`}>
<i className='fa-solid fa-user-check'></i>
</div>
<input
type='text'
value={verifyCode}
className={`${signupStyle.signup_input_text} ${verifyCodeValidate ? '' : signupStyle.validateErr}`}
placeholder='인증번호'
autoComplete='off'
required
onChange={(e) => {
setVerifyCode(e.target.value);
}}
></input>
</div>
<div className={`${signupStyle.signup_input_div}`}>
<div className={`${signupStyle.signup_emoji} ${blogNameValidate ? '' : signupStyle.validateErr}`}>
<i className='fa-solid fa-star'></i>
</div>
<input
type='text'
value={blogName}
className={`${signupStyle.signup_input_text} ${blogNameValidate ? '' : signupStyle.validateErr}`}
maxLength={30}
placeholder='블로그 이름'
required
autoComplete='off'
onChange={(e) => {
setBlogName(e.target.value);
blogNameCheck(e.target.value);
}}
></input>
</div>
<div className={`${signupStyle.signup_input_div} mb10`}>
<div className={`${signupStyle.signup_emoji} ${nicknameValidate ? '' : signupStyle.validateErr} bb bblr`}>
<i className='fa-solid fa-address-card'></i>
</div>
<input
type='text'
value={nickname}
className={`${signupStyle.signup_input_text} ${nicknameValidate ? '' : signupStyle.validateErr} bb bbrr`}
maxLength={20}
placeholder='닉네임'
required
autoComplete='off'
onChange={(e) => {
setNickname(e.target.value);
nicknameCheck(e.target.value);
}}
></input>
</div>
<div className={`idErrMsg ${signupStyle.validateErrMsg}`}></div>
<div className={`emailErrMsg ${signupStyle.validateErrMsg}`}></div>
<div className={`passwordErrMsg ${signupStyle.validateErrMsg}`}></div>
<div className={`pwDobleCheckErrMsg ${signupStyle.validateErrMsg}`}></div>
<div className={`nicknameErrMsg ${signupStyle.validateErrMsg}`}></div>
<div className={`blogNameErrMsg ${signupStyle.validateErrMsg}`}></div>
<div className={`verifyCodeErrMsg ${signupStyle.validateErrMsg}`}></div>
<button type='submit' className={signupStyle.signup_btn}>
가입하기
</button>
</form>
<Snackbar
open={showNoti}
message='회원가입이 완료되었습니다.'
onClose={closeNoti}
action={
<React.Fragment>
<Button color='primary' size='small' onClick={closeNoti}>
확인
</Button>
</React.Fragment>
}
anchorOrigin={{ vertical: 'top', horizontal: 'center' }}
></Snackbar>
</div>
);
};
export default Signup; |
/*
'''
Print all K-length binary strings without consecutive 1s
Given an integer *maxLen*, print all binary strings of size *maxLen* that don't have 1s next to each other. That is, no string should contain the substring 11, 111, 1111, 11111, etc. You can assume *maxLen* > 0.
EXAMPLE(S)
printBinaryWithoutConsecutive1s(maxLen=2)
00
01
10
printBinaryWithoutConsecutive1s(maxLen=3)
000
001
010
100
101
'''
*/
function printBinaryWithoutConsecutive1s(maxLen, currentStr = '') {
if (currentStr.length == maxLen) {
return console.log(currentStr)
}
const lastChar = currentStr[currentStr.length - 1] || ''
if (lastChar == '0' || lastChar == '') {
printBinaryWithoutConsecutive1s(maxLen, currentStr + '0')
printBinaryWithoutConsecutive1s(maxLen, currentStr + '1')
} else if (lastChar === '1') {
printBinaryWithoutConsecutive1s(maxLen, currentStr + '0')
}
} |
/*******************************************************************************
* Copyright (c) 2005, 2010 Andrea Bittau, University College London, and others
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* Andrea Bittau - initial API and implementation from the PsychoPath XPath 2.0
* Mukul Gandhi - bug 280798 - PsychoPath support for JDK 1.4
*******************************************************************************/
package org.eclipse.wst.xml.xpath2.processor.internal.function;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
import org.eclipse.wst.xml.xpath2.api.ResultSequence;
import org.eclipse.wst.xml.xpath2.processor.DynamicError;
import org.eclipse.wst.xml.xpath2.processor.internal.SeqType;
import org.eclipse.wst.xml.xpath2.processor.internal.types.QName;
import org.eclipse.wst.xml.xpath2.processor.internal.types.XSBoolean;
import org.eclipse.wst.xml.xpath2.processor.internal.types.XSString;
/**
* Returns an xs:boolean indicating whether or not the value of $arg1 ends with
* a sequence of collation units that provides a minimal match to the collation
* units of M$arg2 according to the collation that is used.
*/
public class FnEndsWith extends Function {
private static Collection _expected_args = null;
/**
* Constructor for FnEndsWith.
*/
public FnEndsWith() {
super(new QName("ends-with"), 2);
}
/**
* Evaluate arguments.
*
* @param args
* argument expressions.
* @throws DynamicError
* Dynamic error.
* @return Result of evaluation.
*/
public ResultSequence evaluate(Collection args, org.eclipse.wst.xml.xpath2.api.EvaluationContext ec) throws DynamicError {
return ends_with(args);
}
/**
* Ends-with operation.
*
* @param args
* Result from the expressions evaluation.
* @throws DynamicError
* Dynamic error.
* @return Result of fn:ends-with operation.
*/
public static ResultSequence ends_with(Collection args) throws DynamicError {
Collection cargs = Function.convert_arguments(args, expected_args());
// get args
Iterator argiter = cargs.iterator();
ResultSequence arg1 = (ResultSequence) argiter.next();
String str1 = "";
String str2 = "";
if (!arg1.empty())
str1 = ((XSString) arg1.first()).value();
ResultSequence arg2 = (ResultSequence) argiter.next();
if (!arg2.empty())
str2 = ((XSString) arg2.first()).value();
int str1len = str1.length();
int str2len = str2.length();
if (str1len == 0 && str2len != 0) {
return XSBoolean.FALSE;
}
if (str2len == 0) {
return XSBoolean.TRUE;
}
return XSBoolean.valueOf(str1.endsWith(str2));
}
/**
* Obtain a list of expected arguments.
*
* @return Result of operation.
*/
public synchronized static Collection expected_args() {
if (_expected_args == null) {
_expected_args = new ArrayList();
SeqType arg = new SeqType(new XSString(), SeqType.OCC_QMARK);
_expected_args.add(arg);
_expected_args.add(arg);
}
return _expected_args;
}
} |
import { action, makeObservable, observable } from 'mobx';
import { TGroup, TGroupAdd } from 'model/api/groups/types';
import { TUser, TUserAdd, UsersRolesEnum } from 'model/api/users/types';
import { GroupsService } from 'model/services/groups';
import { ProjectsService } from 'model/services/projects';
import { UsersService } from 'model/services/users';
import { AutocompleteControllerStore, Loading } from '@stores/common';
import { StoreManager } from '@stores/manager';
import { TProject } from 'model/api/projects/types';
import { TUid } from '@api/types';
class UniSettingsStore {
private groupsService!: GroupsService;
private usersService!: UsersService;
private projectsService!: ProjectsService;
private manager!: StoreManager;
@observable
newGroup?: TGroupAdd;
@observable
newStudent?: TUserAdd;
groups: TGroup[] = [];
students: TUser[] = [];
teachers: TUser[] = [];
loadingGroups = new Loading();
loadingStudents = new Loading();
loadingTeachers = new Loading();
loadingProjects = new Loading();
studentsAutocomplete!: AutocompleteControllerStore;
groupsAutocomplete!: AutocompleteControllerStore;
constructor() {
makeObservable(this);
}
init = (
usersService: UsersService,
groupsService: GroupsService,
projectsService: ProjectsService,
manager: StoreManager
) => {
this.groupsService = groupsService;
this.usersService = usersService;
this.projectsService = projectsService;
this.manager = manager;
this.studentsAutocomplete = new AutocompleteControllerStore(
usersService.getStudentsShort
);
this.groupsAutocomplete = new AutocompleteControllerStore(
groupsService.getListItems
);
};
getGroups = async () => {
if (this.groups.length) return this.groups;
try {
this.loadingGroups.start();
const response = await this.groupsService.getListItems();
const sorted = response.sort();
this.groups.push(...sorted);
} catch (error) {
this.manager.callBackendError(error, 'Ошибка получения групп');
} finally {
this.loadingGroups.stop();
}
};
addGroup = async () => {
if (!this.newGroup) return;
if (!this.newGroup.name) {
this.manager.callToastError('Необходимо ввести группу');
return;
}
try {
this.loadingGroups.start();
const response = await this.groupsService.addRecord(this.newGroup);
this.groups.push(response);
this.updateNewGroup(undefined);
this.manager.callToastSuccess('Группа успешно добавлена');
} catch (error) {
this.manager.callBackendError(error, 'Ошибка получения групп');
} finally {
this.loadingGroups.stop();
}
};
getStudents = async () => {
if (this.students.length) return this.students;
try {
this.loadingStudents.start();
const response = await this.usersService.getStudents();
const sorted = response.sort();
this.students.push(...sorted);
} catch (error) {
this.manager.callBackendError(error, 'Ошибка получения students');
} finally {
this.loadingStudents.stop();
}
};
getStudentsByGroup = async (group: string) => {
try {
this.loadingStudents.start();
const response = await this.usersService.getStudentsByGroup(group);
const sorted = response.sort();
return sorted;
} catch (error) {
this.manager.callBackendError(error, 'Ошибка получения students');
} finally {
this.loadingStudents.stop();
}
};
getTeachers = async () => {
if (this.teachers.length) return this.teachers;
try {
this.loadingTeachers.start();
const response = await this.usersService.getTeachers();
const sorted = response.sort();
this.teachers.push(...sorted);
} catch (error) {
this.manager.callBackendError(error, 'Ошибка получения teachers');
} finally {
this.loadingTeachers.stop();
}
};
getProjects = async (id: TUid, role: UsersRolesEnum) => {
try {
this.loadingProjects.start();
const response = await this.projectsService.getListById(id, role);
const sorted = response.sort();
return sorted;
} catch (error) {
this.manager.callBackendError(error, 'Ошибка получения userProjects');
} finally {
this.loadingProjects.stop();
}
};
@action
updateNewGroup = (newGroup?: TGroupAdd) => {
this.newGroup = newGroup;
};
@action
updateNewStudent = (newStudent?: TUserAdd) => {
this.newStudent = newStudent;
};
}
export default UniSettingsStore; |
from django.conf import settings
from django.db import models
from django.utils.functional import cached_property
from django.utils.translation import gettext_lazy as _
from ..querysets import UserStudentMappingQuerySet
class UserStudentMapping(models.Model):
objects = UserStudentMappingQuerySet.as_manager()
id = models.AutoField(primary_key=True)
student = models.ForeignKey(
"Student",
verbose_name=_("Student"),
related_name="experimental_student",
on_delete=models.CASCADE,
)
user = models.ForeignKey(
settings.AUTH_USER_MODEL,
verbose_name=_("User"),
related_name="experimental_user",
on_delete=models.CASCADE,
)
date_joined = models.DateTimeField(auto_now_add=True)
added_by = models.ForeignKey(
settings.AUTH_USER_MODEL,
null=True,
on_delete=models.SET_NULL,
)
class Meta:
unique_together = [("student", "user")]
@cached_property
def has_assigned_student_yourself(self):
return self.added_by_id == self.user_id |
import axios, { CancelTokenSource } from "axios";
import { useDispatch, useSelector } from "react-redux";
import { CustomerDetails } from "../store/customerManagement/customer/types";
import { clearDialog, selectDialogState, setDialogOpen } from "../store/dialog/actions";
import map from "lodash/map";
import { MeetingLog, NotesLog } from "../store/dashboard/types";
import moment from "moment";
import { selectCurrentUserRole, selectSystemSessionToken } from "../store/system/actions";
import { useCallback, useEffect, useRef, useState } from "react";
import { getCompany, selectCompanyList } from "../store/listManagement/company/actions";
export const currencyConverter = (data: number) => {
var formatter = new Intl.NumberFormat("en-US", {
style: "currency",
currency: "USD",
minimumFractionDigits: 0,
// These options are needed to round to whole numbers if that's what you want.
//minimumFractionDigits: 0, // (this suffices for whole numbers, but will print 2500.10 as $2,500.1)
//maximumFractionDigits: 0, // (causes 2500.99 to be printed as $2,501)
});
return formatter.format(data);
};
export const stringValidator = (string: string, removeAllSpaces = false) =>
string
? removeAllSpaces
? string.replace(" ", "").toLowerCase().trim().split(/\s+/).join(" ")
: string.toLowerCase().trim().split(/\s+/).join(" ")
: string;
export const initAxiosCancelToken = (
cancellableRequest: CancelTokenSource | null
): CancelTokenSource => {
if (cancellableRequest) {
(cancellableRequest as CancelTokenSource).cancel();
}
return axios.CancelToken.source();
};
export const stringParser = (stringArray: Array<string>) => {
let output = [];
for (var i = 0; i < stringArray.length; i++) {
let stringArr = stringArray[i].split(" ");
if (stringArr.length > 1) {
output.push(stringArr);
} else {
output.push(stringArray[i]);
}
}
return output;
};
export const emailValidator = (email: string): boolean => {
var pattern = new RegExp(
/^(("[\w-\s]+")|([\w-]+(?:\.[\w-]+)*)|("[\w-\s]+")([\w-]+(?:\.[\w-]+)*))(@((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$)|(@\[?((25[0-5]\.|2[0-4][0-9]\.|1[0-9]{2}\.|[0-9]{1,2}\.))((25[0-5]|2[0-4][0-9]|1[0-9]{2}|[0-9]{1,2})\.){2}(25[0-5]|2[0-4][0-9]|1[0-9]{2}|[0-9]{1,2})\]?$)/i
);
return pattern.test(`${email}`);
};
export const numberValidator = (number: string) => {
// eslint-disable-next-line
return /^[\+]?[(]?[0-9]{3}[)]?[-\s\.]?[0-9]{3}[-\s\.]?[0-9]{4,6}$/im.test(number);
};
// added by jeff
interface Media {
name: string;
path: string;
size: string | number;
type: string;
file?: File;
}
export function mapToOptions(arr: any[]) {
const autocompleteOptions = arr.map((item) => ({
label: item.name ? item.name : item,
value: item.id ? item.id : item,
}));
const options = arr.map((item) => ({
id: item.id ? item.id : item,
name: item.name ? item.name : item,
}));
return { autocompleteOptions, options };
}
export function mapToProductOptions(arr: any[]) {
const autocompleteOptions = arr.map((item) => ({
label: item.modelName,
value: item.id,
}));
const options = arr.map((item) => ({
id: item.id,
name: item.modelName,
}));
return { autocompleteOptions, options };
}
export function mapToAreaOptions(arr: CustomerDetails[]) {
const options = arr.map((item) => ({
id: item.area,
name: item.area,
}));
return { options };
}
export function maptoProvinceOrCity(arr: any[], type: "province" | "city/town") {
const isProvince = type === "province";
const options = map(arr[0], (data: any) => ({
id: isProvince ? data.name : data,
name: isProvince ? data.name : data,
}));
return { options };
}
export function transformFileList(fileList: FileList, oldMedia: Array<Media>, isMultiple: boolean) {
let media: Array<Media> = [];
const existingMediaNames = oldMedia.map((m) => m.name);
for (const f of fileList) {
if (!existingMediaNames.includes(f.name)) {
media = [
...media,
{
path: "",
name: (f as File).name,
size: (f as File).size,
type: (f as File).type,
file: f as File,
},
];
}
}
return isMultiple ? [...oldMedia, ...media] : media;
}
export const notesLabelLookUp: Record<string, string> = {
"COMPETITION::INFORMATION": "Competition Information",
"CUSTOMER::EXPERIENCE": "Customer Experience",
"GENERAL::COMMENT": "General Comment",
"PRODUCT::PERFORMANCE": "Product Performance",
"PRODUCT::QUALITY": "Product Quality",
"UNMET::NEED": "Unmet Need",
};
export const getNotesLabel = (noteId: string) => {
const key = noteId.split("::").slice(0, 2).join("::");
return notesLabelLookUp[key];
};
export const getAverageRatingAsScore = (item: NotesLog) =>
item.customerExperience &&
(
item.customerExperience?.reduce((acc, curr) => (acc += curr.rating), 0) /
item.customerExperience?.length
).toFixed(2);
export const getMeetingStatus = (meeting: MeetingLog) => {
let status = meeting.isCancelled ? "Cancelled" : "Open";
return status;
};
export function isInPast30Days(date: string) {
const endDate = moment().subtract(1, "day");
const startDate = moment().subtract(30, "days");
return moment(date).isBetween(startDate, endDate);
}
export function isInNext7Days(date: string) {
const startDate = moment().add(1, "day");
const endDate = moment().add(7, "days");
return moment(date).isBetween(startDate, endDate);
}
export function isInNext14Days(date: string) {
const startDate = moment().add(1, "day");
const endDate = moment().add(14, "days");
return moment(date).isBetween(startDate, endDate);
}
export function isCurrentDate(date: string) {
return moment().format("YYYY-MM-DD") === moment(date).format("YYYY-MM-DD");
}
export function formatDateForTable(date: string) {
return moment(date).format("YYYY-MM-DD");
}
// FOR API CALL
const API_URL = process.env.REACT_APP_API_URL;
// axios instance for users and content mngt
export const executeApiCall = (sessionToken: string) =>
axios.create({
baseURL: API_URL,
headers: {
Authorization: `Bearer ${sessionToken}`,
},
});
// HOOKS
export function useDialog() {
const dispatch = useDispatch();
const dialog = useSelector(selectDialogState);
function closeDialog() {
dispatch(clearDialog());
}
function openConfirmSaveDialog(label: string | undefined) {
dispatch(
setDialogOpen({
dialogOpen: true,
dialogLabel: label ? label : "",
dialogType: "save",
docId: "",
})
);
}
function openDeleteDialog(label: string | undefined, docId: string) {
dispatch(
setDialogOpen({
dialogOpen: true,
dialogLabel: label ? label : "",
dialogType: "delete",
docId,
})
);
}
return { dialog, closeDialog, openConfirmSaveDialog, openDeleteDialog };
}
export default function useCompany(
currentCompany?: string,
changeCallback?: (company: string) => void
) {
const dispatch = useDispatch();
const sessionToken = useSelector(selectSystemSessionToken);
const userRole = useSelector(selectCurrentUserRole);
const isUserSuper = userRole === "SUPER ADMIN";
const [selectedCompany, setSelectedCompany] = useState<string>("");
const savedCallback = useRef(changeCallback);
// Remember the latest callback if it changes
useEffect(() => {
savedCallback.current = changeCallback;
}, [changeCallback]);
const noCompanySelected = !selectedCompany || !currentCompany;
const isSuperAdmin = currentCompany === "SUPERADMIN";
useEffect(() => {
dispatch(getCompany(sessionToken));
}, [dispatch, sessionToken]);
useEffect(() => {
if (isSuperAdmin) return setSelectedCompany("");
const _companyId = currentCompany ? currentCompany : "";
setSelectedCompany(_companyId);
}, [currentCompany, isSuperAdmin]);
const { companyArray } = useSelector(selectCompanyList);
const companySelectOptions = companyArray
.filter((c) => c.isActive)
.map((item) => ({
id: item.companyId,
name: item.name,
}));
const handleCompanyChange = useCallback((e: React.ChangeEvent<HTMLInputElement | any>) => {
const companyName = e.target.value;
if (!companyName) return;
setSelectedCompany(companyName);
// update store
if (savedCallback.current) savedCallback.current(companyName);
}, []);
return {
selectedCompany,
noCompanySelected,
companySelectOptions,
handleCompanyChange,
isUserSuper,
};
} |
/*
* TeamStats by Mats Bovin ([email protected])
* v1.3.0 February 2007
* Copyright (c) 2004-07 Mats Bovin
*
* Android / Java port by Hayden Pronto-Hussey
* v0.1 August 2012
*
* This file is part of TeamStats.
*
* TeamStats is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* TeamStats 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 TeamStats; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
package mBovin.TeamStats.Core;
import java.util.ArrayList;
import java.util.Collections;
public class League {
private ILeagueStore mLeagueStore;
private String mName;
private Integer mYear;
private boolean mIsSplit;
private int mTeamCount;
private int mRoundCount;
private int mMatchCount;
private int mPlayedMatchCount;
private int mWinPoints;
private int mDrawPoints;
private int mLossPoints;
private long mTableLines;
private TableSortMethod mTableSort;
private ArrayList<Team> mTeamList;
public League() {
mRoundCount = 1;
}
public League(ILeagueStore leagueStore) {
mLeagueStore = leagueStore;
mLeagueStore.LoadHeader(this);
}
public ILeagueStore getmLeagueStore() {
return mLeagueStore;
}
public void setmLeagueStore(ILeagueStore mLeagueStore) {
this.mLeagueStore = mLeagueStore;
}
public String getmName() {
return mName;
}
public void setmName(String mName) {
this.mName = mName;
}
public int getmYear() {
return mYear;
}
public void setmYear(int mYear) {
this.mYear = mYear;
}
public boolean ismIsSplit() {
return mIsSplit;
}
public void setmIsSplit(boolean mIsSplit) {
this.mIsSplit = mIsSplit;
}
public int getmTeamCount() {
return mTeamCount;
}
public void setmTeamCount(int mTeamCount) {
this.mTeamCount = mTeamCount;
}
public int getmRoundCount() {
return mRoundCount;
}
public void setmRoundCount(int mRoundCount) {
this.mRoundCount = mRoundCount;
}
public int getmMatchCount() {
return mMatchCount;
}
public void setmMatchCount(int mMatchCount) {
this.mMatchCount = mMatchCount;
}
public int getmPlayedMatchCount() {
return mPlayedMatchCount;
}
public void setmPlayedMatchCount(int mPlayedMatchCount) {
this.mPlayedMatchCount = mPlayedMatchCount;
}
public int getmWinPoints() {
return mWinPoints;
}
public void setmWinPoints(int mWinPoints) {
this.mWinPoints = mWinPoints;
}
public int getmDrawPoints() {
return mDrawPoints;
}
public void setmDrawPoints(int mDrawPoints) {
this.mDrawPoints = mDrawPoints;
}
public int getmLossPoints() {
return mLossPoints;
}
public void setmLossPoints(int mLossPoints) {
this.mLossPoints = mLossPoints;
}
public long getmTableLines() {
return mTableLines;
}
public void setmTableLines(long l) {
this.mTableLines = l;
}
public TableSortMethod getmTableSort() {
return mTableSort;
}
public void setmTableSort(TableSortMethod mTableSort) {
this.mTableSort = mTableSort;
}
public String Season() {
return (mIsSplit) ?
mYear.toString() + "-" + (((mYear + 1) % 100)):
mYear.toString();
}
public String FullName() {
return this.mName + " " + this.Season();
}
public Team GetTeam(int teamIndex) {
if (mTeamList == null) {
GetTeams();
}
return mTeamList.get(teamIndex);
}
public ArrayList<Team> GetTeams() {
if (mTeamList == null) {
mTeamList = mLeagueStore.LoadTeams(this);
}
return mTeamList;
}
public ArrayList<Integer> GetTableLines() {
ArrayList<Integer> linesList = new ArrayList<Integer> (mTeamCount);
for (int i = 0; i < mTeamCount; i++) {
if (IsTableLine(i + 1)) {
linesList.add(i + 1);
}
}
return linesList;
}
public boolean IsTableLine(int position) {
Double base = (double) 2;
return ((long)Math.pow(base, (double)(position - 1)) & mTableLines) > 0;
}
public int GetLastPlayedRound() {
int lastPlayedRound = 1;
Match match;
ArrayList<Match> matchList = mLeagueStore.LoadMatches(this);
for (int i = matchList.size()-1; i >=0; i--) {
match = matchList.get(i);
if (match.IsPlayed()) {
lastPlayedRound = match.getmRound();
break;
}
}
return lastPlayedRound;
}
public ArrayList<Match> GetMatches(boolean onlyPlayed) {
return mLeagueStore.LoadMatches(this, new MatchFilterPlayed(), onlyPlayed);
}
public ArrayList<Match> GetMatchesForRound(int round) {
return mLeagueStore.LoadMatches(this, new MatchFilterRound(), round);
}
public ArrayList<Match> GetMatchesforTeam(int teamIndex, boolean includeHome, boolean includeAway) {
return mLeagueStore.LoadMatches(this, new MatchFilterTeam(), teamIndex, includeHome, includeAway);
}
/// Creates the specified number of teams. The teams are
/// added to mTableTeamList and saved.
public void AddTeams(int teamCount) {
mTeamCount = teamCount;
Team[] teamList = {};
for (int i = 0; i < mTeamCount; i++) {
teamList[i] = new Team(this, i, "Team" + (i + 1));
}
mLeagueStore.SaveHeader(this);
mLeagueStore.SaveTeams(this, teamList);
}
/// Adds a match to the league.
public void AddMatch(Match match) {
ArrayList<Match> matchlist = mLeagueStore.LoadMatches(this);
matchlist.add(match);
mMatchCount++;
if (match.IsPlayed()) {
mPlayedMatchCount++;
}
Save();
Collections.sort(matchlist);
mLeagueStore.SaveMatches(this, matchlist);
}
/// Loads all the matches of the league, sorts them (on the matchdate)
/// and then saves them again.
/// Use this method when match dates have changed.
public void SortMatches() {
ArrayList<Match> matchlist = mLeagueStore.LoadMatches(this);
Collections.sort(matchlist);
mLeagueStore.SaveMatches(this, matchlist);
}
/// Increases the number of rounds for this league.
public void AddRound() {
mRoundCount++;
Save();
}
/// Decreases the number of rounds for this league. An exception is
/// thrown if the last round contains any matches.
public void DeleteLastRound() throws Exception {
ArrayList<Match> matches = GetMatchesForRound(mRoundCount);
if (matches.size() > 0) {
throw new Exception("Last Round is not empty");
}
mRoundCount--;
Save();
}
public void Save() {
mLeagueStore.SaveHeader(this);
}
} |
module Animate
{
/** A very simple class to represent tool bar buttons */
export class ToolBarButton extends Component
{
private _radioMode: boolean;
private _pushButton: boolean;
private _proxyDown: any;
constructor( text : string, image : string, pushButton : boolean = false, parent?: Component )
{
super("<div class='toolbar-button tooltip'><div><img src='" + image + "' /></div><div class='tooltip-text tooltip-text-bg'>" + text + "</div></div>", parent );
this._pushButton = pushButton;
this._radioMode = false;
this._proxyDown = this.onClick.bind( this );
this.element.on( "click", this._proxyDown );
}
/** Cleans up the button */
dispose()
{
this.element.off( "mousedown", this._proxyDown );
this._proxyDown = null;
super.dispose();
}
onClick( e )
{
var element: JQuery = this.element;
if ( this._pushButton )
{
if ( !element.hasClass( "selected" ) )
this.selected = true;
else
this.selected = false;
}
}
/**
* Set if the component is selected. When set to true a css class of 'selected' is added to the {Component}
*/
set selected( val: boolean )
{
if ( val )
this.element.addClass( "selected" );
else
this.element.removeClass( "selected" );
if ( this._radioMode && val && this.parent )
{
var pChildren: Array<IComponent> = this.parent.children;
for ( var i = 0, len = pChildren.length; i < len; i++ )
if ( pChildren[i] != this && pChildren[i] instanceof ToolBarButton )
( <ToolBarButton>pChildren[i] ).selected = false;
}
}
/**
* Get if the component is selected. When set to true a css class of 'selected' is added to the {Component}
*/
get selected(): boolean { return this.element.hasClass("selected"); }
/**
* If true, the button will act like a radio button. It will deselect any other ToolBarButtons in its parent when its selected.
*/
set radioMode( val: boolean )
{
this._radioMode = val;
}
get radioMode(): boolean { return this._radioMode; }
}
} |
/* CLIQUE NO SINAL DE "+", À ESQUERDA, PARA EXIBIR A DESCRIÇÃO DO EXEMPLO
*
* Copyright (C) 2014 - UNIVALI - Universidade do Vale do Itajaí
*
* Este arquivo de código fonte é livre para utilização, cópia e/ou modificação
* desde que este cabeçalho, contendo os direitos autorais e a descrição do programa,
* seja mantido.
*
* Se tiver dificuldade em compreender este exemplo, acesse as vídeoaulas do Portugol
* Studio para auxiliá-lo:
*
* https://www.youtube.com/watch?v=K02TnB3IGnQ&list=PLb9yvNDCid3jQAEbNoPHtPR0SWwmRSM-t
*
* Descrição:
*
* Este exemplo pede ao usuario que informe dois números. Logo após,
* calcula e exibe:
*
* a) A soma entre os números
* b) A subtração entre os números
* c) A multiplicação entre os números
* d) A divisão entre os números
*
* Autores:
*
* Giordana Maria da Costa Valle
* Carlos Alexandre Krueger
*
* Data: 01/06/2013
*/
programa
{
funcao inicio()
{
inteiro anoNascimento, anoFuturo,sub
escreva("Digite o ano futuro:")
leia(anoFuturo)
escreva("Digite o ano de seu nascimento:")
leia(anoNascimento)
sub = anoFuturo - anoNascimento // Subtrai os dois valores
escreva("\n No ano de 2035 a sua idade será:", sub) // Exibe o resultado da subtração
}
}
/* $$$ Portugol Studio $$$
*
* Esta seção do arquivo guarda informações do Portugol Studio.
* Você pode apagá-la se estiver utilizando outro editor.
*
* @POSICAO-CURSOR = 1110;
* @DOBRAMENTO-CODIGO = [1];
* @PONTOS-DE-PARADA = ;
* @SIMBOLOS-INSPECIONADOS = ;
* @FILTRO-ARVORE-TIPOS-DE-DADO = inteiro, real, logico, cadeia, caracter, vazio;
* @FILTRO-ARVORE-TIPOS-DE-SIMBOLO = variavel, vetor, matriz, funcao;
*/ |
import { NgModule } from '@angular/core';
import { RouterModule, Routes } from '@angular/router';
import { HomeComponent } from './home/home.component';
import { LoginComponent } from './login/login.component';
import { OrderComponent } from './order/order.component';
import { SignUpComponent } from './sign-up/sign-up.component';
import {AuthGuard} from "./auth/auth.guard";
const routes: Routes = [
{path:"home",component:HomeComponent},
{path:"order",canActivate:[AuthGuard],component:OrderComponent},
{path:"login",component:LoginComponent},
{path:"signup",component:SignUpComponent},
{path:"**",component:HomeComponent}
];
@NgModule({
imports: [RouterModule.forRoot(routes)],
exports: [RouterModule]
})
export class AppRoutingModule { } |
/*
* Copyright The Cryostat 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.
*/
package io.cryostat.net.web.http.api.v1;
import java.io.File;
import java.nio.file.Path;
import java.util.Set;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import io.cryostat.configuration.CredentialsManager;
import io.cryostat.core.log.Logger;
import io.cryostat.net.AuthManager;
import io.cryostat.net.security.ResourceAction;
import io.cryostat.net.web.http.HttpMimeType;
import io.cryostat.recordings.RecordingArchiveHelper;
import io.cryostat.recordings.RecordingNotFoundException;
import io.vertx.core.http.HttpHeaders;
import io.vertx.core.http.HttpMethod;
import io.vertx.core.http.HttpServerResponse;
import io.vertx.ext.web.RoutingContext;
import io.vertx.ext.web.handler.HttpException;
import org.hamcrest.MatcherAssert;
import org.hamcrest.Matchers;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Disabled;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.Mock;
import org.mockito.Mockito;
import org.mockito.junit.jupiter.MockitoExtension;
@Disabled
@ExtendWith(MockitoExtension.class)
class RecordingGetHandlerTest {
RecordingGetHandler handler;
@Mock AuthManager authManager;
@Mock CredentialsManager credentialsManager;
@Mock RecordingArchiveHelper recordingArchiveHelper;
@Mock Logger logger;
@Mock RoutingContext ctx;
@Mock HttpServerResponse resp;
@BeforeEach
void setup() {
this.handler =
new RecordingGetHandler(
authManager, credentialsManager, recordingArchiveHelper, logger);
}
@Test
void shouldHandleGETRequest() {
MatcherAssert.assertThat(handler.httpMethod(), Matchers.equalTo(HttpMethod.GET));
}
@Test
void shouldHandleCorrectPath() {
MatcherAssert.assertThat(
handler.path(), Matchers.equalTo("/api/v1/recordings/:recordingName"));
}
@Test
void shouldHaveExpectedRequiredPermissions() {
MatcherAssert.assertThat(
handler.resourceActions(), Matchers.equalTo(Set.of(ResourceAction.READ_RECORDING)));
}
@Test
void shouldThrow404IfNoMatchingRecordingFound() throws Exception {
Mockito.when(authManager.validateHttpHeader(Mockito.any(), Mockito.any()))
.thenReturn(CompletableFuture.completedFuture(true));
Mockito.when(ctx.response()).thenReturn(resp);
Mockito.when(
resp.putHeader(
Mockito.any(CharSequence.class), Mockito.any(CharSequence.class)))
.thenReturn(resp);
String recordingName = "foo";
Mockito.when(ctx.pathParam("recordingName")).thenReturn(recordingName);
CompletableFuture<Path> future = Mockito.mock(CompletableFuture.class);
Mockito.when(recordingArchiveHelper.getRecordingPath(recordingName)).thenReturn(future);
ExecutionException e = Mockito.mock(ExecutionException.class);
Mockito.when(future.get()).thenThrow(e);
Mockito.when(e.getCause())
.thenReturn(new RecordingNotFoundException("archives", recordingName));
HttpException ex = Assertions.assertThrows(HttpException.class, () -> handler.handle(ctx));
MatcherAssert.assertThat(ex.getStatusCode(), Matchers.equalTo(404));
}
@Test
void shouldHandleSuccessfulGETRequest() throws Exception {
Mockito.when(authManager.validateHttpHeader(Mockito.any(), Mockito.any()))
.thenReturn(CompletableFuture.completedFuture(true));
Mockito.when(ctx.response()).thenReturn(resp);
Mockito.when(
resp.putHeader(
Mockito.any(CharSequence.class), Mockito.any(CharSequence.class)))
.thenReturn(resp);
String recordingName = "foo";
Mockito.when(ctx.pathParam("recordingName")).thenReturn(recordingName);
CompletableFuture<Path> future = Mockito.mock(CompletableFuture.class);
Mockito.when(recordingArchiveHelper.getRecordingPath(recordingName)).thenReturn(future);
Path archivedRecording = Mockito.mock(Path.class);
Mockito.when(future.get()).thenReturn(archivedRecording);
Mockito.when(archivedRecording.toString()).thenReturn("/path/to/recording.jfr");
File file = Mockito.mock(File.class);
Mockito.when(archivedRecording.toFile()).thenReturn(file);
Mockito.when(file.length()).thenReturn(12345L);
handler.handle(ctx);
Mockito.verify(resp).putHeader(HttpHeaders.CONTENT_TYPE, HttpMimeType.OCTET_STREAM.mime());
Mockito.verify(resp).putHeader(HttpHeaders.CONTENT_LENGTH, "12345");
Mockito.verify(resp).sendFile(archivedRecording.toString());
}
} |
using System.Text.RegularExpressions;
using AdventOfCode.Lib;
using Microsoft.Extensions.Configuration;
using Serilog;
using TextCopy;
namespace AdventOfCode.Cli;
public sealed partial class Application(
IConfiguration config,
ILogger logger,
IHttpClientFactory httpClientFactory,
IClipboard clipboard)
{
public async Task RunAsync(string[] args)
{
var aocYear = args[0];
var aocDay = args[1];
var client = httpClientFactory.CreateClient("AoC");
var input = await client.GetStringAsync($"{aocYear}/day/{aocDay}/input");
if (input is "Error")
{
logger.Fatal("Error while fetching input data");
return;
}
// Get AoC title
var instructions = await client.GetStringAsync($"{aocYear}/day/{aocDay}");
var title = AocDayTitleRegex().Match(instructions).Groups[2].Value;
var question = AocPart1QuestionRegex().Match(instructions).Groups[1].Value;
logger.Information("Current Directory: {Path}", Directory.GetCurrentDirectory());
var day = aocDay
.Pipe(int.Parse)
.Pipe(PrependLeadingZero);
// Create Aoc Day X file
var srcDirectory = config["Directories:src"]!;
var aocFilePath = $@"{srcDirectory}\{aocYear}\AdventOfCode.Y{aocYear}"
.Pipe(Path.GetFullPath)
.Pipe(CreateDirectory)
.Pipe(aocDir => Path.Combine(aocDir.FullName, CreateAocDayFileName(day)));
await CreateAocDayClassFileAsync(aocFilePath, title, aocYear, aocDay, day);
// Create Aoc Day X test file
var acoTestFilePath = $@"{srcDirectory}\{aocYear}\AdventOfCode.Y{aocYear}.Tests.Unit"
.Pipe(Path.GetFullPath)
.Pipe(CreateDirectory)
.Pipe(aocTestDir => Path.Combine(aocTestDir.FullName, CreateAocTestFileName(day)));
await CreateAocTestClassFileAsync(acoTestFilePath, title, question, aocYear, aocDay, day);
// Create Real input file
var (realInputFileName, testInputFileName) = CreateTestFileNames(day);
var aocDataDirectory = $@"{srcDirectory}\{aocYear}\AdventOfCode.Y{aocYear}.Tests.Unit\Data"
.Pipe(Path.GetFullPath)
.Pipe(CreateDirectory);
var realInputFilePath = Path.Combine(aocDataDirectory.FullName, realInputFileName);
await CreateRealInputFileAsync(realInputFilePath, input);
// Create Test input file
var testInputFilePath = Path.Combine(aocDataDirectory.FullName, testInputFileName);
await CreateTestInputFileAsync(testInputFilePath);
}
private async Task CreateAocDayClassFileAsync(string acoFilePath, string title, string aocYear,
string aocDay, string day)
{
if (File.Exists(acoFilePath))
{
logger.Information("File already exists: {File}", acoFilePath);
return;
}
logger.Information("File was created: {File}", acoFilePath);
await CreateAocTemplateAsync(acoFilePath, title, aocYear, aocDay, day);
}
private async Task CreateAocTestClassFileAsync(string acoTestFilePath, string title, string question,
string aocYear, string aocDay, string day)
{
if (File.Exists(acoTestFilePath))
{
logger.Information("File already exists: {File}", acoTestFilePath);
return;
}
logger.Information("File was created: {File}", acoTestFilePath);
await CreateAocTestTemplateAsync(acoTestFilePath, title, question, aocYear, aocDay, day);
}
private async Task CreateRealInputFileAsync(string realInputFilePath, string input)
{
if (File.Exists(realInputFilePath))
{
logger.Information("File already exists: {File}", realInputFilePath);
return;
}
logger.Information("File was created: {File}", realInputFilePath);
await File.WriteAllTextAsync(realInputFilePath, input);
}
private async Task CreateTestInputFileAsync(string testInputFilePath)
{
if (File.Exists(testInputFilePath))
{
logger.Information("File already exists: {File}", testInputFilePath);
return;
}
logger.Information("Awaiting copy from clipboard...");
await clipboard.SetTextAsync("");
string? text;
do
{
text = await clipboard.GetTextAsync();
} while (string.IsNullOrEmpty(text));
logger.Information("File was created: {File}", testInputFilePath);
await File.WriteAllTextAsync(testInputFilePath, text);
}
private DirectoryInfo CreateDirectory(string directoryPath)
{
if (Directory.Exists(directoryPath))
{
logger.Information("Directory already exists: {Directory}", directoryPath);
return new DirectoryInfo(directoryPath);
}
logger.Information("Directory does not exist: {Directory}", directoryPath);
return Directory.CreateDirectory(directoryPath);
}
private static async Task CreateAocTemplateAsync(string acoFilePath, string title, string aocYear, string aocDay,
string day)
{
var aocTemplate =
$$"""
using AdventOfCode.Lib;
namespace AdventOfCode.Y{{aocYear}};
[AocPuzzle({{aocYear}}, {{aocDay}}, "{{title}}")]
public sealed class Day{{day}} : IAocDay<int>
{
public static int Part1(AocInput input) => 0;
public static int Part2(AocInput input) => 0;
}
""";
await File.WriteAllTextAsync(acoFilePath, aocTemplate);
}
private static async Task CreateAocTestTemplateAsync(string realInputFilePath, string title, string question,
string aocYear, string aocDay, string day)
{
var aocTestTemplate =
$$"""
using System.ComponentModel;
using AdventOfCode.Lib;
using static AdventOfCode.Lib.AocFileReaderService;
namespace AdventOfCode.Y{{aocYear}}.Tests.Unit;
[AocPuzzle({{aocYear}}, {{aocDay}}, "{{title}}")]
public sealed class Day{{day}}Tests : IAocDayTest<int>
{
private const string Day = nameof(Day{{day}});
private const string TestData = @$"..\..\..\Data\{Day}_Test.txt";
private const string RealData = @$"..\..\..\Data\{Day}.txt";
private readonly Day{{day}} _sut = new();
public static TheoryData<AocInput, int> Part1Data => new()
{
{ ReadInput(TestData), 0 },
{ ReadInput(RealData), 0 }
};
public static TheoryData<AocInput, int> Part2Data => new()
{
{ ReadInput(TestData), 0 },
{ ReadInput(RealData), 0 }
};
[Theory]
[MemberData(nameof(Part1Data))]
[Description("{{question}}")]
public void Part1(AocInput input, int expected)
{
// Act
var result = Day{{day}}.Part1(input);
// Assert
result.Should().Be(expected);
}
[Theory]
[MemberData(nameof(Part2Data))]
[Description("<insert question 2 here>")]
public void Part2(AocInput input, int expected)
{
// Act
var result = Day{{day}}.Part2(input);
// Assert
result.Should().Be(expected);
}
}
""";
await File.WriteAllTextAsync(realInputFilePath, aocTestTemplate);
}
private static string PrependLeadingZero(int day) => day < 10 ? $"0{day}" : $"{day}";
private static string CreateAocDayFileName(string day) => $"Day{day}.cs";
private static string CreateAocTestFileName(string day) => $"Day{day}Tests.cs";
private static (string, string) CreateTestFileNames(string day) => ($"Day{day}.txt", $"Day{day}_Test.txt");
[GeneratedRegex(@"<h2>--- Day (\d*): (.*) ---</h2>")]
private static partial Regex AocDayTitleRegex();
[GeneratedRegex(@"<em>(.*\?)</em>")]
private static partial Regex AocPart1QuestionRegex();
} |
package com.jsrdev.jsrconsulthub
import com.jsrdev.jsrconsulthub.data.network.services.MedicService
import com.squareup.moshi.kotlin.reflect.KotlinJsonAdapterFactory
import com.squareup.moshi.Moshi
import kotlinx.coroutines.runBlocking
import okhttp3.HttpUrl
import org.junit.Assert.assertEquals
import org.junit.Assert.assertNotNull
import org.junit.Assert.assertTrue
import org.junit.Before
import org.junit.Test
import retrofit2.Retrofit
import retrofit2.converter.moshi.MoshiConverterFactory
class MedicApiServiceTest : BaseTest() {
private lateinit var medicService: MedicService
@Before // antes de cada test
fun setup() {
val url: HttpUrl = mockWebServer.url("/") // url a interceptar
medicService = Retrofit.Builder()
.baseUrl(url)
.addConverterFactory(
MoshiConverterFactory.create(
Moshi.Builder()
.add(KotlinJsonAdapterFactory())
.build()
)
)
.build()
.create(MedicService::class.java)
}
@Test
fun medicApiService() {
enqueue("get_medics.json")
runBlocking {
val medicApiResponse = medicService.getMedics( size = 10)
// asegurar que la respuesta no sea null
assertNotNull(medicApiResponse)
// asegurar que la lista no esté vacia
medicApiResponse.body()?.isNotEmpty()?.let { assertTrue("The list was empty", it) }
// verificar que algunos datos sean correctas
assertEquals("The IDs did not match", 5, medicApiResponse.body()?.get(4)?.id)
}
}
} |
<?php
class WPRT_Socials extends WP_Widget {
// Holds widget settings defaults, populated in constructor.
protected $defaults;
// Constructor
function __construct() {
$this->defaults = array(
'title' => '',
'width' => '',
'height' => '',
'gap' => '',
'size' => '',
'rounded' => '',
'facebook' => '',
'twitter' => '',
'youtube' => '',
'vimeo' => '',
'tumblr' => '',
'pinterest' => '',
'linkedin' => '',
'instagram' => '',
'github' => '',
'apple' => '',
'android' => '',
'behance' => '',
'dribbble' => '',
'flickr' => '',
'paypal' => '',
'soundcloud' => '',
'spotify' => '',
);
parent::__construct(
'widget_socials',
esc_html__( 'Socials', 'thecraft' ),
array(
'classname' => 'widget_socials',
'description' => esc_html__( 'Display the socials.', 'thecraft' )
)
);
}
// Display widget
function widget( $args, $instance ) {
$instance = wp_parse_args( $instance, $this->defaults );
extract( $instance );
extract( $args );
echo $before_widget;
if ( ! empty( $title ) ) { echo $before_title . $title . $after_title; }
$width = intval( $width );
$height = intval( $height );
$gap = intval( $gap );
$size = intval( $size );
$rounded = intval( $rounded );
$icon_bottom = 10;
$css = '';
$inner_css = '';
if ( ! empty( $gap ) ) {
$inner_css = 'padding: 0 '. ($gap/2) .'px;';
$css = 'margin: 0 -'. ($gap/2) .'px';
$icon_bottom = $gap/2;
}
$icon_css = 'margin-bottom:'. $icon_bottom .'px';
if ( ! empty( $width ) )
$icon_css .= ';width:'. $width .'px';
if ( ! empty( $height ) )
$icon_css .= ';height:'. $height .'px;line-height:'. $height .'px';
if ( ! empty( $size ) )
$icon_css .= ';font-size:'. $size .'px';
if ( ! empty( $rounded ) )
$icon_css .= ';border-radius:'. $rounded .'px';
$html = '';
foreach ( $instance as $k => $v ) {
if ( $v != '' && ! in_array( $k , array( 'title', 'width', 'height', 'size', 'rounded', 'gap' ) ) )
$html .= '<div class="icon" style="'. $inner_css .'"><a target="_blank" href="'. $v .'" style="'. $icon_css .'"><i class="craft-'. $k .'"></i></a></div>';
}
if ( $html )
printf( '<div class="socials clearfix" style="%2$s">%1$s</div>', $html, $css );
echo $after_widget;
}
// Update widget
function update( $new_instance, $old_instance ) {
$instance = $old_instance;
$instance['width'] = strip_tags( $new_instance['width'] );
$instance['height'] = strip_tags( $new_instance['height'] );
$instance['size'] = strip_tags( $new_instance['size'] );
$instance['rounded'] = strip_tags( $new_instance['rounded'] );
$instance['gap'] = strip_tags( $new_instance['gap'] );
$instance['title'] = strip_tags( $new_instance['title'] );
$instance['facebook'] = strip_tags( $new_instance['facebook'] );
$instance['twitter'] = strip_tags( $new_instance['twitter'] );
$instance['youtube'] = strip_tags( $new_instance['youtube'] );
$instance['vimeo'] = strip_tags( $new_instance['vimeo'] );
$instance['tumblr'] = strip_tags( $new_instance['tumblr'] );
$instance['pinterest'] = strip_tags( $new_instance['pinterest'] );
$instance['linkedin'] = strip_tags( $new_instance['linkedin'] );
$instance['instagram'] = strip_tags( $new_instance['instagram'] );
$instance['github'] = strip_tags( $new_instance['github'] );
$instance['apple'] = strip_tags( $new_instance['apple'] );
$instance['android'] = strip_tags( $new_instance['android'] );
$instance['behance'] = strip_tags( $new_instance['behance'] );
$instance['dribbble'] = strip_tags( $new_instance['dribbble'] );
$instance['flickr'] = strip_tags( $new_instance['flickr'] );
$instance['paypal'] = strip_tags( $new_instance['paypal'] );
$instance['soundcloud'] = strip_tags( $new_instance['soundcloud'] );
$instance['spotify'] = strip_tags( $new_instance['spotify'] );
return $instance;
}
// Widget setting
function form( $instance ) {
$instance = wp_parse_args( $instance, $this->defaults );
$fields = array(
'facebook' => esc_html__( 'Facebook URL:', 'thecraft' ),
'twitter' => esc_html__( 'Twitter URL:', 'thecraft' ),
'youtube' => esc_html__( 'Youtube URL:', 'thecraft' ),
'vimeo' => esc_html__( 'Vimeo URL:', 'thecraft' ),
'tumblr' => esc_html__( 'Tumblr URL:', 'thecraft' ),
'pinterest' => esc_html__( 'Pinterest URL:', 'thecraft' ),
'linkedin' => esc_html__( 'LinkedIn URL:', 'thecraft' ),
'instagram' => esc_html__( 'Instagram URL:', 'thecraft' ),
'github' => esc_html__( 'Github URL:', 'thecraft' ),
'apple' => esc_html__( 'Apple URL:', 'thecraft' ),
'android' => esc_html__( 'Android URL:', 'thecraft' ),
'behance' => esc_html__( 'Behance URL:', 'thecraft' ),
'dribbble' => esc_html__( 'Dribbble URL:', 'thecraft' ),
'flickr' => esc_html__( 'Flickr URL:', 'thecraft' ),
'paypal' => esc_html__( 'Paypal URL:', 'thecraft' ),
'soundcloud' => esc_html__( 'Soundcloud URL:', 'thecraft' ),
'spotify' => esc_html__( 'Spotify URL:', 'thecraft' )
); ?>
<p>
<label for="<?php echo esc_attr( $this->get_field_id( 'title' ) ); ?>"><?php esc_html_e( 'Title:', 'thecraft' ); ?></label>
<input class="widefat" id="<?php echo esc_attr( $this->get_field_id( 'title' ) ); ?>" name="<?php echo esc_attr( $this->get_field_name( 'title' ) ); ?>" type="text" value="<?php echo esc_attr( $instance['title'] ); ?>">
</p>
<p>
<label for="<?php echo esc_attr( $this->get_field_id( 'width' ) ); ?>"><?php esc_html_e('Width:', 'thecraft') ?></label>
<input class="widefat" id="<?php echo esc_attr( $this->get_field_id( 'width' ) ); ?>" name="<?php echo esc_attr( $this->get_field_name( 'width' ) ); ?>" type="text" size="2" value="<?php echo esc_attr( $instance['width'] ); ?>">
</p>
<p>
<label for="<?php echo esc_attr( $this->get_field_id( 'height' ) ); ?>"><?php esc_html_e('Height:', 'thecraft') ?></label>
<input class="widefat" id="<?php echo esc_attr( $this->get_field_id( 'height' ) ); ?>" name="<?php echo esc_attr( $this->get_field_name( 'height' ) ); ?>" type="text" size="2" value="<?php echo esc_attr( $instance['height'] ); ?>">
</p>
<p>
<label for="<?php echo esc_attr( $this->get_field_id( 'size' ) ); ?>"><?php esc_html_e('Icon Font Size:', 'thecraft') ?></label>
<input class="widefat" id="<?php echo esc_attr( $this->get_field_id( 'size' ) ); ?>" name="<?php echo esc_attr( $this->get_field_name( 'size' ) ); ?>" type="text" size="2" value="<?php echo esc_attr( $instance['size'] ); ?>">
</p>
<p>
<label for="<?php echo esc_attr( $this->get_field_id( 'rounded' ) ); ?>"><?php esc_html_e('Rounded:', 'thecraft') ?></label>
<input class="widefat" id="<?php echo esc_attr( $this->get_field_id( 'rounded' ) ); ?>" name="<?php echo esc_attr( $this->get_field_name( 'rounded' ) ); ?>" type="text" size="2" value="<?php echo esc_attr( $instance['rounded'] ); ?>">
</p>
<p>
<label for="<?php echo esc_attr( $this->get_field_id( 'gap' ) ); ?>"><?php esc_html_e('Spacing Between Items:', 'thecraft') ?></label>
<input class="widefat" id="<?php echo esc_attr( $this->get_field_id( 'gap' ) ); ?>" name="<?php echo esc_attr( $this->get_field_name( 'gap' ) ); ?>" type="text" size="2" value="<?php echo esc_attr( $instance['gap'] ); ?>">
</p>
<?php
foreach ( $fields as $k => $v ) {
printf(
'<p>
<label for="%s">%s</label>
<input type="text" class="widefat" id="%s" name="%s" value="%s">
</p>',
$this->get_field_id( $k ),
$v,
$this->get_field_id( $k ),
$this->get_field_name( $k ),
$instance[$k]
);
}
?>
<?php
}
}
add_action( 'widgets_init', 'register_wprt_socials' );
// Register widget
function register_wprt_socials() {
register_widget( 'WPRT_Socials' );
} |
/*---------------------------------------------------------------------------*\
========= |
\\ / F ield | OpenFOAM: The Open Source CFD Toolbox
\\ / O peration |
\\ / A nd | www.openfoam.com
\\/ M anipulation |
-------------------------------------------------------------------------------
Copyright (C) 2016 OpenFOAM Foundation
Copyright (C) 2020 OpenCFD Ltd.
-------------------------------------------------------------------------------
License
This file is part of OpenFOAM.
OpenFOAM 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.
OpenFOAM 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 OpenFOAM. If not, see <http://www.gnu.org/licenses/>.
Class
Foam::functionObjects::streamFunction
Group
grpFieldFunctionObjects
Description
Computes the stream function (i.e. https://w.wiki/Ncm).
Operands:
\table
Operand | Type | Location
input | surfaceScalarField | $FOAM_CASE/\<time\>/\<inpField\>
output file | - | -
output field | pointScalarField | $FOAM_CASE/\<time\>/\<outField\>
\endtable
Usage
Minimal example by using \c system/controlDict.functions:
\verbatim
streamFunction1
{
// Mandatory entries (unmodifiable)
type streamFunction;
libs (fieldFunctionObjects);
// Optional (inherited) entries
...
}
\endverbatim
where the entries mean:
\table
Property | Description | Type | Req'd | Dflt
type | Type name: streamFunction | word | yes | -
libs | Library name: fieldFunctionObjects | word | yes | -
\endtable
The inherited entries are elaborated in:
- \link functionObject.H \endlink
- \link fieldExpression.H \endlink
Minimal example by using the \c postProcess utility:
\verbatim
postProcess -func streamFunction
\endverbatim
See also
- Foam::functionObject
- Foam::functionObjects::fieldExpression
- Foam::functionObjects::fvMeshFunctionObject
- ExtendedCodeGuide::functionObjects::field::streamFunction
SourceFiles
streamFunction.C
\*---------------------------------------------------------------------------*/
#ifndef functionObjects_streamFunction_H
#define functionObjects_streamFunction_H
#include "fieldExpression.H"
#include "surfaceFieldsFwd.H"
#include "pointFieldsFwd.H"
// * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * //
namespace Foam
{
namespace functionObjects
{
/*---------------------------------------------------------------------------*\
Class streamFunction Declaration
\*---------------------------------------------------------------------------*/
class streamFunction
:
public fieldExpression
{
// Private Member Functions
//- Return the stream function field
tmp<pointScalarField> calc(const surfaceScalarField& phi) const;
//- Calculate the stream-function and return true if successful
virtual bool calc();
public:
//- Runtime type information
TypeName("streamFunction");
// Constructors
//- Construct for given objectRegistry and dictionary.
// Allow the possibility to load fields from files
streamFunction
(
const word& name,
const Time& runTime,
const dictionary& dict
);
//- No copy construct
streamFunction(const streamFunction&) = delete;
//- No copy assignment
void operator=(const streamFunction&) = delete;
//- Destructor
virtual ~streamFunction() = default;
};
// * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * //
} // End namespace functionObjects
} // End namespace Foam
// * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * //
#endif
// ************************************************************************* // |
<!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 href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384
-+0n0xVW2eSR5OomGNYDnhzAbDsOXxcvSN1TPprVMTNDbiYZCxYbOOl7+AMvyTG2x" crossorigin="anonymous">
<link rel="stylesheet" href="boot2.css">
</head>
<body>
<div class="container ">
<!-- image -->
<!-- class = d-block mx-auto to keep the element in middle position
class= float-start to keep the element at the start position
class = float -end to keep the element at the end position (i.e from left)
-->
<!-- img-fluid class to make the image responsive -->
<!-- to get light border around the image we use class = "img-thumbnail" -->
<img src="https://static.remove.bg/sample-gallery/graphics/bird-thumbnail.jpg"
class="d-block mx-auto img-fluid img-thumbnail w-25 "
alt="">
<!-- list -->
<!-- class="list-unstyled" is used to remove all the dots of the unordeered list -->
<!-- class="list-inline" is used to make list items in same line and
we have to add class="list-inline-item" for every element in the list to get in same linee-->
<!-- no neeed to usee unstyled when we are using list-inline -->
<ul class=" list-inline">
<li class="list-inline-item">python</li>
<li class="list-inline-item">java</li>
<li class="list-inline-item">c++</li>
<li class="list-inline-item">angular</li>
</ul>
<!-- tables -->
<!-- class ="table" makes thee table look more beautiful -->
<!-- class = "table-bordered" to apply borders to the table -->
<!-- class ="text-center" to make all the elements to move to center of the page -->
<!-- class = "table-striped " to make the alternative rows striped -->
<!-- class = "table -hover" to make the hover effect-->
<!-- class ="table-borderless" to make the table borderless -->
<!-- class ="table-sm" to decrease the size of table -->
<!-- we can use the colors using class ="table-dark" here dark color will applied -->
<table class="table text-center table-borderless table-striped ">
<thead class="table-dark">
<th >cart</th>
<th>account</th>
<th>policy</th>
</thead>
<tbody>
<tr class="table-primary">
<td>this</td>
<td>new</td>
<td>2000</td>
</tr>
<tr class="table-secondary">
<td>this</td>
<td>new</td>
<td>2000</td>
</tr>
<tr class="table-warning">
<td>this</td>
<td>new</td>
<td>2000</td>
</tr>
<tr class="table-danger">
<td>this</td>
<td>new</td>
<td>2000</td>
</tr>
<tr class="table-info">
<td>this</td>
<td>new</td>
<td>2000</td>
</tr>
<tr class="table-success" >
<td>this</td>
<td>new</td>
<td>2000</td>
</tr>
<tr class="table-body">
<td>this</td>
<td>new</td>
<td>2000</td>
</tr>
</tbody>
</table>
</div>
<script src="https://cdn.jsdelivr.net/npm/@popperjs/[email protected]/dist/umd/popper.min.js" integrity="sha384-IQsoLXl5PILFhosVNubq5LC7Qb9DXgDA9i+tQ8Zj3iwWAwPtgFTxbJ8NT4GN1R8p" crossorigin="anonymous"></script>
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.min.js" integrity="sha384-Atwg2Pkwv9vp0ygtn1JAojH0nYbwNJLPhwyoVbhoPwBhjQPR5VtM2+xf0Uwh9KtT" crossorigin="anonymous"></script>
</body>
</html> |
<template>
<div id="app">
<ejs-grid :dataSource="data" height='315' :rowDataBound='rowDataBound'>
<e-columns>
<e-column field='OrderID' headerText='Order ID' textAlign='Right' width=90></e-column>
<e-column field='CustomerID' headerText='Customer ID' width=120></e-column>
<e-column field='Freight' headerText='Freight' textAlign='Right' format='C2' width=90></e-column>
<e-column field='OrderDate' headerText='Order Date' textAlign='Right' format='yMd' type='date' width=120 > </e-column>
</e-columns>
</ejs-grid>
</div>
</template>
<script>
import Vue from "vue";
import { GridPlugin } from "@syncfusion/ej2-vue-grids";
import { data } from './datasource.js';
Vue.use(GridPlugin);
export default {
data() {
return {
data: data
};
},
methods: {
rowDataBound: (args) {
if (args.data['OrderID'] === 10249) {
args.rowHeight = 90;
}
}
}
});
</script>
<style>
@import "../node_modules/@syncfusion/ej2-vue-grids/styles/material.css";
</style> |
class Node {
constructor(val, left = null, right = null) {
this.val = val;
this.left = left;
this.right = right;
}
}
class BinarySearchTree {
constructor(root = null) {
this.root = root;
}
/** insert(val): insert a new node into the BST with value val.
* Returns the tree. Uses iteration. */
insert(val) {
// traverse BST
if(this.root === null){
this.root = new Node(val);
return this;
}
let currentNode = this.root;
while(true){
if(val > currentNode.val){
if(currentNode.right === null){
currentNode.right = new Node(val);
return this;
}
currentNode = currentNode.right;
} else {
if(currentNode.left === null){
currentNode.left = new Node(val);
return this;
}
currentNode = currentNode.left;
}
}
}
/** insertRecursively(val): insert a new node into the BST with value val.
* Returns the tree. Uses recursion. */
insertRecursively(val) {
if(this.root === null){
this.root = new Node(val);
return this;
}
const findInsertionPoint = (node) =>{
if(val > node.val){
if(node.right === null){
node.right = new Node(val);
// return this;
} else {
return findInsertionPoint(node.right);
}
}else {
if(node.left===null){
node.left = new Node(val);
// return this;
}else{
return findInsertionPoint(node.left);
}
}
}
findInsertionPoint(this.root);
return this;
}
/** find(val): search the tree for a node with value val.
* return the node, if found; else undefined. Uses iteration. */
find(val) {
if(this.root === null){
this.root = new Node(val);
return this;
}
let currentNode = this.root;
while(currentNode){
if(currentNode.val === val) return currentNode;
if(val > currentNode.val){
if(currentNode.right === null) return;
if(currentNode.right.val === val){
return currentNode.right;
}
currentNode = currentNode.right;
} else {
if(currentNode.left === null) return;
if(currentNode.left.val === val){
return currentNode.left;
}
currentNode = currentNode.left;
}
}
}
/** findRecursively(val): search the tree for a node with value val.
* return the node, if found; else undefined. Uses recursion. */
findRecursively(val) {
if(this.root === null){
return;
}
// let currentNode = this;
const locateNode = (node) =>{
if(node.val === val) return node;
// let currentNode = node;
if(val > node.val){
if(node.right === null) return;
if(node.right.val === val){
return node.right;
} else {
return locateNode(node.right);
}
}else {
if(node.left===null) return;
if(node.left.val === val){
return node.left;
} else{
return locateNode(node.left);
}
}
}
return locateNode(this.root);
}
/** dfsPreOrder(): Traverse the array using pre-order DFS.
* Return an array of visited nodes. */
dfsPreOrder() {
let currentNode = this.root;
let nodeArr = [];
const traversePreOrder = (currentNode) => {
nodeArr.push(currentNode.val);
if(currentNode.left) traversePreOrder(currentNode.left);
if(currentNode.right) traversePreOrder(currentNode.right);
}
traversePreOrder(currentNode);
return nodeArr;
}
/** dfsInOrder(): Traverse the array using in-order DFS.
* Return an array of visited nodes. */
dfsInOrder() {
let currentNode = this.root;
let nodeArr = [];
const traversePreOrder = (currentNode) => {
if(currentNode.left) traversePreOrder(currentNode.left);
nodeArr.push(currentNode.val);
if(currentNode.right) traversePreOrder(currentNode.right);
}
traversePreOrder(currentNode);
return nodeArr;
}
/** dfsPostOrder(): Traverse the array using post-order DFS.
* Return an array of visited nodes. */
dfsPostOrder() {
let currentNode = this.root;
let nodeArr = [];
const traversePreOrder = (currentNode) => {
if(currentNode.left) traversePreOrder(currentNode.left);
if(currentNode.right) traversePreOrder(currentNode.right);
nodeArr.push(currentNode.val);
}
traversePreOrder(currentNode);
return nodeArr;
}
/** bfs(): Traverse the array using BFS.
* Return an array of visited nodes. */
bfs() {
let resultArr = [];
let queue = [this.root];
while(queue.length !== 0){
// if greater than
let currentNode = queue.shift();
resultArr.push(currentNode.val);
if(currentNode.left) queue.push(currentNode.left);
if(currentNode.right) queue.push(currentNode.right);
}
return resultArr;
}
/** Further Study!
* remove(val): Removes a node in the BST with the value val.
* Returns the removed node. */
remove(val) {
}
/** Further Study!
* isBalanced(): Returns true if the BST is balanced, false otherwise. */
isBalanced() {
}
/** Further Study!
* findSecondHighest(): Find the second highest value in the BST, if it exists.
* Otherwise return undefined. */
findSecondHighest() {
}
}
module.exports = BinarySearchTree; |
import {
types,
getSnapshot,
unprotect,
protect,
applySnapshot,
} from "mobx-state-tree";
// Entities and Their Many Names
// 1. entity / type / interface / class / object / | set theory discrete mathematics
// 2. They are all pretty similar in theory and concept
// MobX Tree (Living Tree - Mutable State)
// 1. Mutable state
// 2. Protected strictly typed objects (run-time type information)
// 3. Tree Model (The Abstraction):
// 3.1: Shape (model, type information, views, actions) {}
// 3.2: Instance state (data) / (Instantiation of the Model)
// MobX Tree snapshots
// 1. Generated automatically
// 2. Immutable and structurally shared snapshots are generated automaticallys
// MobX: treeNode = types.model({}).views({}).actions({});
// 1. The instantiation of a Tree Model
// 2. How MST defines its interfaces / classes
// 3. Main Methods:
// 3.1: .model({}) = Member variable type definitions
// 3.2: .views({self => ({})})
// 3.2a: Derivation processes get function (getter computed variable / value )
// A derivative of state that typically returns a value
// 3.3: .actions({self => ({})})
// 3.3a: Set state actions Methods / Functions
// Ussually does not return a value]
// 3.3b: accepts a callback parameter is self keyword
// types Namespace
// - A namespace of types for MobX and Typescript
// Null saftey (types.optional)
// - types.optional(types.typeDeclaration, defaultValue);
// snapshots
// - Should be applied at the store level
// - applySnapshot
// Summary:
// 1. MST is MobX with type saftey and the use of interfaces for entities instead of classes
// 2. Manage state outside of the view (Conmponent) and without the need of a class entity
// 3. Has a strange syntaxs at first forsure
// Create two entities:
// 1. Todo
// 2. Author
interface AuthorInterface {
id: string;
fname: string;
lname?: string;
}
interface TodoInterface {
id: number;
task: string;
author: AuthorInterface;
completed: boolean;
}
// Tree Models
// Tree Model | The Abstraction / Mix of Interface and Implementation
const Author = types.model({
id: types.identifier,
fname: types.string,
lname: types.optional(types.string, ""),
});
// Tree Model| The Abstraction / Mix of Interface and Implementation
const Todo = types
.model({
id: types.identifierNumber,
task: types.string,
author: Author,
completed: types.boolean,
})
.actions((self) => ({
toggleComplete() {
self.completed = !self.completed;
},
edit(newTask: string) {
if (newTask) {
self.task = newTask;
}
},
}));
// Root Model Store
const RootStore = types
.model({
authors: types.map(Author),
todos: types.optional(types.map(Todo), {}),
})
.actions((self) => ({
addAuthor(author: AuthorInterface, id?: string) {
if (id) {
self.authors.set(id, author);
} else {
self.authors.put(author);
}
},
addTodo(todo: TodoInterface, id?: string) {
if (id) {
self.todos.set(id, todo);
} else {
self.todos.put(todo);
}
},
}));
// Objects
// Author Object: Passed to Author.create() creating an instance of the Tree Model (Tree Node)
const authorObject: AuthorInterface = {
id: "1101",
fname: "Kweayon",
};
const todoObject = {
id: 1101,
task: "Finish first MobX State Tree tutorial!",
author: authorObject,
completed: false,
};
// Tree Nodes
// Tree Node | The Instantiation
const todo1 = Todo.create({
id: 1101,
task: "Finish first MobX State Tree tutorial!",
author: authorObject,
completed: false,
});
// Print Snapshot
console.log(getSnapshot(todo1));
// Tree Node store
const store = RootStore.create({});
// Apply Snapshot Before store is used
applySnapshot(store, {});
// Update state via .actions function
store.addAuthor(authorObject);
store.addTodo(todoObject);
console.log(store.authors.get("1101"));
// I dont think this is recommended in typescript
// unprotect(store);
// store.authors.put(authorObject);
// store.todos.put(todoObject);
// protect(store);
// console.log(store.todos.get("1101")?.task); |
import React from 'react'
import '@testing-library/jest-dom/extend-expect'
import { screen, render } from '@testing-library/react'
import userEvent from '@testing-library/user-event'
import BlogForm from './BlogForm'
test('BlogForm calls the event handler with the right details when submitted', async () => {
const createBlog = jest.fn()
render(<BlogForm createBlog={createBlog} />).container
const title = screen.getByPlaceholderText('title')
const author = screen.getByPlaceholderText('author')
const url = screen.getByPlaceholderText('url')
const likes = screen.getByPlaceholderText('likes')
const submit = screen.getByRole('button')
await userEvent.type(title, 'The Lazy Fox')
await userEvent.type(author, 'Mr. Nobody')
await userEvent.type(url, 'https://google.com/ncr')
await userEvent.type(likes, '78')
await userEvent.click(submit)
expect(createBlog.mock.calls).toHaveLength(1)
expect(createBlog.mock.calls[0][0].title).toBe('The Lazy Fox')
expect(createBlog.mock.calls[0][0].author).toBe('Mr. Nobody')
expect(createBlog.mock.calls[0][0].url).toBe('https://google.com/ncr')
expect(createBlog.mock.calls[0][0].likes).toBe('78')
}) |
package com.example.mymusicplayer1_01;
import android.app.Service;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.net.Uri;
import android.os.Binder;
import android.os.Bundle;
import android.os.IBinder;
import android.preference.PreferenceManager;
import android.provider.MediaStore;
import android.util.Log;
public class MusicPlayerService extends Service implements
MediaPlayer.OnCompletionListener {
private static final String TAG = "MusicPlayerService";
public static final String ARGUMENT_PLAYER = "ARGUMENT_PLAYER";
private Context mContext;
private MediaPlayer mMediaPlayer;
private MediaPlayer.OnCompletionListener mOnCompletionListener;
private String mMediaId;
private String mMediaArtist;
private String mMediaTitle;
private String mMediaData;
private String mMediaDisplayName;
private String mMediaDuration;
private Bundle mBundle;
private boolean mIsPlaying;
private boolean mIsLooping;
private int mTotalDuration;
private int mCurrentPosition;
private int mAudioSessionId;
private SharedPreferences mPreferences;
private boolean mPrefAutomaticPlay = false;
private int mPrefSkipTime = 5000;
@Override
public void onCreate() {
super.onCreate();
Log.v(TAG, "onCreate()");
mContext = getApplicationContext();
mPreferences = PreferenceManager.getDefaultSharedPreferences(this);
createMediaPlayer();
registerBroadcastReceiver();
}
@Override
public void onDestroy() {
Log.v(TAG, "onDestroy()");
if (mMediaPlayer != null) {
try {
if (mMediaPlayer.isPlaying()) {
mMediaPlayer.stop();
}
mMediaPlayer.release();
mMediaPlayer = null;
} catch (Exception e) {
e.printStackTrace();
}
}
if (mIsReceiverRegistered == true) {
unregisterBroadcastReceiver();
}
super.onDestroy();
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
Log.v(TAG, "onStartCommand() action:" + intent.getAction());
// return super.onStartCommand(intent, flags, startId);
return Service.START_NOT_STICKY;
}
private void createMediaPlayer() {
try {
Log.v(TAG, "createMediaPlayer()");
if (mMediaPlayer == null) {
mMediaPlayer = new MediaPlayer();
// setVolumeControlStream(AudioManager.STREAM_MUSIC);
mMediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
mMediaPlayer.setOnCompletionListener(this);
mAudioSessionId = mMediaPlayer.getAudioSessionId();
Log.d(TAG, "... audio session ID: " + mAudioSessionId);
}
} catch (Exception e) {
e.printStackTrace();
}
}
private void loadPrefAutomaticPlay() {
boolean prefAutomaticPlay = (boolean) mPreferences.getBoolean(
getResources().getString(R.string.pref_automatic_play_key),
false);
if (prefAutomaticPlay != mPrefAutomaticPlay) {
mPrefAutomaticPlay = prefAutomaticPlay;
Log.v(TAG, "loadPrefAutomaticPlay() " + mPrefAutomaticPlay);
}
}
private void loadPrefSkipTime() {
String prefSkipTimeString = (String) mPreferences
.getString(
getResources().getString(R.string.pref_skip_second_key),
"5000");
int prefSkipTime = Integer.parseInt(prefSkipTimeString);
if (prefSkipTime != mPrefSkipTime) {
mPrefSkipTime = prefSkipTime;
Log.v(TAG, "loadPrefSkipTime() " + mPrefSkipTime);
}
}
public void setDataSource(Bundle aBundle) {
try {
Log.v(TAG, "setDataSource()");
if (mMediaPlayer == null) {
createMediaPlayer();
}
if (aBundle == null) {
return;
}
String id = (String) aBundle.getString(MediaStore.Audio.Media._ID);
if ((mMediaId != null) && (id.compareTo(mMediaId) == 0)) {
return;
} else {
Log.v(TAG, "... mMediaPlayer.reset() ");
mMediaPlayer.reset();
}
mMediaId = id;
mMediaArtist = (String) aBundle
.getString(MediaStore.Audio.Media.ARTIST);
mMediaTitle = (String) aBundle
.getString(MediaStore.Audio.Media.TITLE);
mMediaData = (String) aBundle
.getString(MediaStore.Audio.Media.DATA);
mMediaDisplayName = (String) aBundle
.getString(MediaStore.Audio.Media.DISPLAY_NAME);
mMediaDuration = (String) aBundle
.getString(MediaStore.Audio.Media.DURATION);
Log.v(TAG, "setDataSource() " + mMediaId + " : "
+ mMediaDisplayName + " : " + mMediaTitle + " : "
+ mMediaArtist);
Uri mediaUri = Uri.parse(mMediaData);
mMediaPlayer.setDataSource(mContext, mediaUri);
Log.v(TAG, "... prepare(), start()");
mMediaPlayer.prepare();
mMediaPlayer.start();
mMediaPlayer.pause();
mTotalDuration = Integer.parseInt(mMediaDuration);
Log.v(TAG, "... getDuration " + mTotalDuration);
mIsPlaying = mMediaPlayer.isPlaying();
mIsLooping = mMediaPlayer.isLooping();
loadPrefAutomaticPlay();
if (mPrefAutomaticPlay == false) {
Log.v(TAG, "... AutomaticPlay off --> pause()");
} else {
Log.v(TAG, "... AutomaticPlay on");
start();
}
} catch (Exception e) {
e.printStackTrace();
}
mBundle = aBundle;
}
public void start() {
Log.v(TAG, "start()");
if (mIsPlaying == true) {
return;
}
try {
mMediaPlayer.start();
mIsPlaying = true;
} catch (Exception e) {
e.printStackTrace();
}
}
public void pause() {
Log.v(TAG, "pause()");
if (mIsPlaying != true) {
return;
}
try {
mMediaPlayer.pause();
mIsPlaying = false;
} catch (Exception e) {
e.printStackTrace();
}
}
public void seekTo(int aMsec) {
Log.v(TAG, "seekTo(" + aMsec + ")");
try {
mMediaPlayer.seekTo(aMsec);
if (mIsPlaying == true) {
mMediaPlayer.start();
}
} catch (Exception e) {
e.printStackTrace();
}
}
public int skip(boolean aForward) {
Log.v(TAG, "skip(" + (aForward ? "FastForward" : "Rewind") + ")");
loadPrefSkipTime();
int destPos;
if (aForward) {
destPos = mCurrentPosition + mPrefSkipTime;
destPos = (destPos > mTotalDuration ? mTotalDuration : destPos);
} else {
destPos = mCurrentPosition - mPrefSkipTime;
destPos = (destPos < 0 ? 0 : destPos);
}
mMediaPlayer.seekTo(destPos);
if (mIsPlaying) {
mMediaPlayer.start();
}
return destPos;
}
public int getCurrentPosition() {
mCurrentPosition = mMediaPlayer.getCurrentPosition();
return mCurrentPosition;
}
public int getDuration() {
return mTotalDuration;
}
public int getAudioSessionId() {
return mAudioSessionId;
}
public String getTitle() {
return mMediaTitle;
}
public String getDisplayName() {
return mMediaDisplayName;
}
public String getId() {
return mMediaId;
}
public void setLooping(boolean aEnableLooping) {
mMediaPlayer.setLooping(aEnableLooping);
mIsLooping = aEnableLooping;
}
public boolean isLooping() {
return mIsLooping;
}
public boolean isPlaying() {
return mIsPlaying;
}
public void setOnCompletionListener(
MediaPlayer.OnCompletionListener aOnCompletionListener) {
if (mOnCompletionListener != aOnCompletionListener) {
Log.v(TAG, "setOnCompletionListener()");
mOnCompletionListener = aOnCompletionListener;
}
}
@Override
public void onCompletion(MediaPlayer mp) {
Log.v(TAG, "onCompletion()");
mIsPlaying = false;
if (mOnCompletionListener != null) {
mOnCompletionListener.onCompletion(mp);
}
}
public final IBinder mLocalBinder = new LocalBinder();
public class LocalBinder extends Binder {
MusicPlayerService getService() {
return MusicPlayerService.this;
}
}
@Override
public boolean onUnbind(Intent intent) {
Log.v(TAG, "onUnbind()");
return super.onUnbind(intent);
}
@Override
public IBinder onBind(Intent arg0) {
Log.v(TAG, "onBind()");
return mLocalBinder;
}
@Override
public void onRebind(Intent intent) {
Log.v(TAG, "onRebind()");
super.onRebind(intent);
}
private boolean mIsReceiverRegistered = false;
BroadcastReceiver myBroadcastReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
Log.v(TAG, "onReceive " + intent.getAction());
if (intent.getAction().equalsIgnoreCase(
android.media.AudioManager.ACTION_AUDIO_BECOMING_NOISY)) {
Log.d(TAG, "...audio becoming noisy, pause()");
pause();
} else if (intent.getAction().equalsIgnoreCase(
Intent.ACTION_HEADSET_PLUG)) {
int state = intent.getIntExtra("state", -1);
switch (state) {
case 0:
Log.d(TAG, "...Headset is unplugged, pause()");
pause();
break;
case 1:
Log.d(TAG, "...Headset is plugged");
break;
default:
Log.d(TAG, "I have no idea what the headset state is");
}
}
}
};
private void registerBroadcastReceiver() {
if (mIsReceiverRegistered == false) {
mContext.registerReceiver(myBroadcastReceiver, new IntentFilter(
"android.media.AudioManager.ACTION_AUDIO_BECOMING_NOISY"));
mContext.registerReceiver(myBroadcastReceiver, new IntentFilter(
"android.intent.action.HEADSET_PLUG"));
mIsReceiverRegistered = true;
}
}
private void unregisterBroadcastReceiver() {
if (mIsReceiverRegistered == true) {
mContext.unregisterReceiver(myBroadcastReceiver);
mIsReceiverRegistered = false;
}
}
} |
// SPDX-License-Identifier: MIT
pragma solidity >=0.7.6;
import "@openzeppelin/contracts/token/ERC721/ERC721.sol";
import "@openzeppelin/contracts/access/Ownable.sol";
/**
* @title ERC721Mock
* This mock just provides a public safeMint, mint, and burn functions for testing purposes
*/
contract ERC721Mock is Ownable, ERC721 {
uint256 tID;
constructor (string memory name, string memory symbol, uint256 tID_start, string memory baseURI)
ERC721(name, symbol) {
_setBaseURI(baseURI);
tID = tID_start;
}
function mintNFT(address recipient, string memory tokenURI) public onlyOwner returns (uint256)
{
safeMint(recipient, tID);
setTokenURI(tID, tokenURI);
tID += 1;
return tID;
}
function getLastTID() public view returns(uint256) {
return tID;
}
function baseURI() public view override returns (string memory) {
return baseURI();
}
function setBaseURI(string calldata newBaseURI) public {
_setBaseURI(newBaseURI);
}
function setTokenURI(uint256 tokenId, string memory _tokenURI) public {
_setTokenURI(tokenId, _tokenURI);
}
//for a specific tokenId, get the associated NFT
function getTokenURI(uint256 tokenId) public view returns (string memory) {
return tokenURI(tokenId);
}
function getName() public view returns (string memory) {
return name();
}
function getSymbol() public view returns (string memory) {
return symbol();
}
function exists(uint256 tokenId) public view returns (bool) {
return _exists(tokenId);
}
function mint(address to, uint256 tokenId) public {
_mint(to, tokenId);
}
function safeMint(address to, uint256 tokenId) public {
_safeMint(to, tokenId);
}
function safeMint(address to, uint256 tokenId, bytes memory _data) public {
_safeMint(to, tokenId, _data);
}
function burn(uint256 tokenId) public {
_burn(tokenId);
}
} |
import pytest
from src.scraper.utils import extract_product_id_from_url
def test_extract_product_id_from_url():
# Test cases with various URLs
test_cases = [
("https://tienda.mercadona.es/product/3505.2/14-sandia-baja-semillas-14-pieza", 3505.2),
("https://tienda.mercadona.es/product/15691.1/hogaza-centeno-50", 15691.1),
("https://tienda.mercadona.es/product/3529/sandia-baja-semillas-pieza", 3529),
("https://tienda.mercadona.es/product/3236/limones-malla", 3236),
]
for url, expected_product_id in test_cases:
assert extract_product_id_from_url(url) == expected_product_id
def test_invalid_url():
# Test case for an invalid URL
with pytest.raises(ValueError):
extract_product_id_from_url("invalid_url") |
<!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" />
<link rel="stylesheet" href="style.css" />
<title>Form Validation Redone</title>
</head>
<body>
<form
name="reg-form"
method="get"
action="thanks.html"
onsubmit="validateForm(event, this)"
>
<!-- Full name starts here -->
<label for="full-name">Full Name</label>
<input
name="full-name"
type="text"
id="vr-full-name"
placeholder="Enter your full number"
minlength="3"
/>
<span id="vr-fname-status"></span>
<!-- Email starts here -->
<label for="email">Email</label>
<input
type="email"
id="vr-email"
name="email"
placeholder="Enter your email"
required
/>
<!-- Select city starts here -->
<label for="city">Select City</label>
<select id="vr-city" name="city">
<option value="cairo">cairo</option>
<option value="london">london</option>
<option value="nevada">nevada</option>
<option value="sichuan">sichuan</option>
</select>
<!-- password starts here-->
<label for="password" name="password">Password</label>
<input
type="password"
id="password"
placeholder="Enter your password"
required
/>
<!-- Reenter password starts here -->
<label for="re-password">Re-enter password</label>
<input
type="password"
id="vr-re-password"
name="re-password"
placeholder="Re-enter your password"
required
onblur="validatePassword(this)"
/>
<div id="pass-matching-status"></div>
<!-- Consent starts here -->
<div>
<input type="checkbox" name="consent" id="vr-consent" />
<label for="consent">I accelpt the terms and conditions</label>
</div>
<!-- Register starts here -->
<input type="submit" name="submit" value="Register" />
</form>
<a href="/index.html">Click here to try it with JS</a>
<a href="/gallery.html">Visit gallery</a>
<script src="app.js"></script>
</body>
</html> |
import { formatDate } from '@angular/common';
import { Component, ElementRef, OnInit, ViewChild } from '@angular/core';
import { FormBuilder, FormGroup, Validators } from '@angular/forms';
import { Router } from '@angular/router';
import { IdentityInfo } from 'src/app/interfaces/identityInfo';
import Swal from 'sweetalert2';
@Component({
selector: 'app-identity',
templateUrl: './identity.component.html',
styleUrls: ['./identity.component.scss']
})
export class IdentityComponent implements OnInit {
identityForm!: FormGroup;
indentityInfo!: IdentityInfo;
url!: any;
@ViewChild('fileupload') myFileInput!: ElementRef;
isImageSaved!: boolean;
cardImageBase64!: string;
documentType = [
{ name: 'Паспорт' },
{ name: 'Свидетельство о рождении' },
{ name: 'Вод. удостоверение' }
]
constructor(
private fb: FormBuilder,
private router: Router,
) { }
ngOnInit() {
this.createIdentityForm();
if (localStorage.getItem('identityInfo')) {
this.indentityInfo = JSON.parse(localStorage.getItem('identityInfo') ?? '');
this.url = this.indentityInfo?.file;
this.identityForm.patchValue({
documentType: this.indentityInfo.documentType,
passportNumber: this.indentityInfo.passportNumber,
serial: this.indentityInfo.serial,
issuer: this.indentityInfo.issuer,
date: this.indentityInfo.date,
file: this.indentityInfo.file,
});
}
}
createIdentityForm() {
this.identityForm = this.fb.group({
documentType: ['', Validators.required],
passportNumber: ['', Validators.required],
serial: [''],
issuer: [''],
date: ['', Validators.required],
file: [null]
})
}
get formControls() {
return this.identityForm.controls;
}
onFileChanged(event: any) {
const files = event.target.files;
if (files.length === 0)
return;
const reader = new FileReader();
reader.readAsDataURL(files[0]);
reader.onload = (_event) => {
this.url = reader.result;
}
}
submitClientForm() {
if (this.identityForm.valid) {
this.identityForm.patchValue({
date: formatDate(this.identityForm.controls['date'].value, 'yyyy-MM-dd', 'en')
});
localStorage.setItem('identityInfo', JSON.stringify(this.identityForm.value));
this.router.navigate(['/created-client']);
Swal.fire({
title: 'Новый клиент успешно создан',
icon: 'success',
showCancelButton: false,
confirmButtonText: 'Продолжить',
buttonsStyling: false,
customClass: {
confirmButton: 'btn btn-success btn-lg'
},
});
}
}
fileChangeEvent(fileInput: any) {
if (fileInput.target.files && fileInput.target.files[0]) {
const reader = new FileReader();
reader.onload = (e: any) => {
const image = new Image();
image.src = e.target.result;
image.onload = () => {
const imgBase64Path = e.target.result;
this.url = imgBase64Path;
this.identityForm.patchValue({
file: this.url
})
};
};
reader.readAsDataURL(fileInput.target.files[0]);
}
}
deleteImage() {
this.identityForm.patchValue({
file: null
});
this.myFileInput.nativeElement.value = '';
this.url = null;
localStorage.removeItem('image');
}
} |
import React, { useEffect, useState } from 'react';
import styles from './SceneEditTitle.module.scss';
import { CheckMark32Icon, Cross32Icon, Edit32Icon } from '../../../icons';
import { updateSceneIdAndTitle } from '../../../api/scene';
const SceneEditTitle = ({ sceneData }) => {
const [editMode, setEditMode] = useState(false);
const [title, setTitle] = useState(sceneData?.sceneTitle);
const sceneId = STREET.utils.getCurrentSceneId();
useEffect(() => {
if (sceneData.sceneId === sceneId) {
setTitle(sceneData.sceneTitle);
}
}, [sceneData?.sceneTitle, sceneData?.sceneId, sceneId]);
const handleEditClick = () => {
const newTitle = prompt('Edit the title:', title);
if (newTitle !== null) {
if (newTitle !== title) {
setTitle(newTitle);
saveNewTitle(newTitle);
}
}
};
const saveNewTitle = async (newTitle) => {
setEditMode(false);
try {
await updateSceneIdAndTitle(sceneData?.sceneId, newTitle);
AFRAME.scenes[0].setAttribute('metadata', 'sceneTitle', newTitle);
AFRAME.scenes[0].setAttribute('metadata', 'sceneId', sceneData?.sceneId);
STREET.notify.successMessage(`New scene title saved: ${newTitle}`);
} catch (error) {
console.error('Error with update title', error);
STREET.notify.errorMessage(`Error updating scene title: ${error}`);
}
};
const handleCancelClick = () => {
if (sceneData && sceneData.sceneTitle !== undefined) {
setTitle(sceneData.sceneTitle);
}
setEditMode(false);
};
const handleKeyDown = (event) => {
if (event.key === 'Enter') {
saveNewTitle();
} else if (event.key === 'Escape') {
handleCancelClick();
}
};
return (
<div className={styles.wrapper}>
{editMode ? (
<div className={styles.edit}>
<input
className={styles.title}
value={title}
onChange={handleChange}
onKeyDown={handleKeyDown}
/>
<div className={styles.buttons}>
<div onClick={() => saveNewTitle(title)} className={styles.check}>
<CheckMark32Icon />
</div>
<div onClick={handleCancelClick} className={styles.cross}>
<Cross32Icon />
</div>
</div>
</div>
) : (
<div className={styles.readOnly}>
<p className={styles.title} onClick={handleEditClick}>
{title}
</p>
{!editMode && (
<div className={styles.editButton} onClick={handleEditClick}>
<Edit32Icon />
</div>
)}
</div>
)}
</div>
);
};
export { SceneEditTitle }; |
import 'package:bibleapp/widgets/headers/verse_header.dart';
import 'package:bibleapp/widgets/verse/verse.dart';
import 'package:flutter/material.dart';
import '../../models/chapter/chapter.dart';
import '../../models/verse/verse.dart';
class Verses extends StatelessWidget {
final List<VerseModel> verses;
final List<ChapterModel> chapters;
final String selectedBible;
final String selectedChapter;
const Verses(
{super.key,
required this.verses,
required this.chapters,
required this.selectedBible,
required this.selectedChapter});
@override
Widget build(BuildContext context) {
return Stack(
children: [
VerseHeader(
chapters: chapters,
selectedBible: selectedBible,
selectedChapter: selectedChapter),
Container(
margin: const EdgeInsets.only(top: 60),
child: ListView.builder(
itemCount: verses.length,
itemBuilder: (context, index) {
return Verse(verse: verses[index]);
},
),
),
],
);
}
} |
package com.clone.springbootredditbackend.service;
import com.clone.springbootredditbackend.Exception.PostNotFoundException;
import com.clone.springbootredditbackend.Exception.SubredditNotFoundException;
import com.clone.springbootredditbackend.domain.*;
import com.clone.springbootredditbackend.mapper.PostMapper;
import com.clone.springbootredditbackend.web.dto.PostRequest;
import com.clone.springbootredditbackend.web.dto.PostResponse;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.util.List;
import static java.util.stream.Collectors.toList;
@Service
@Slf4j
@Transactional
@RequiredArgsConstructor
public class PostService {
private final PostRepository postRepository;
private final SubredditRepository subredditRepository;
private final PostMapper postMapper;
private final AuthService authService;
private final UserRepository userRepository;
@Transactional
public void save(PostRequest postRequest) {
Subreddit subreddit =
subredditRepository.findByName(postRequest.getSubredditName())
.orElseThrow(() -> new SubredditNotFoundException(postRequest.getSubredditName()));
postRepository.save(postMapper.map(postRequest, subreddit, authService.getCurrentUser()));
}
@Transactional(readOnly = true)
public List<PostResponse> getAllPosts() {
return postRepository.findAll()
.stream()
.map(postMapper::mapToDto)
.collect(toList());
}
@Transactional(readOnly = true)
public PostResponse getPost(Long id) {
Post post = postRepository.findById(id)
.orElseThrow(()->new PostNotFoundException(id.toString()));
return postMapper.mapToDto(post);
}
@Transactional(readOnly = true)
public List<PostResponse> getPostsBySubreddit(Long subredditId) {
Subreddit subreddit = subredditRepository.findById(subredditId)
.orElseThrow(() -> new SubredditNotFoundException(
subredditId.toString()
));
List<Post> posts = postRepository.findAllBySubreddit(subreddit);
return posts.stream().map(postMapper::mapToDto).collect(toList());
}
@Transactional(readOnly = true)
public List<PostResponse> getPostsByUsername(String username) {
User user = userRepository.findByUsername(username)
.orElseThrow(() -> new UsernameNotFoundException(username));
return postRepository.findByUser(user)
.stream()
.map(postMapper::mapToDto)
.collect(toList());
}
@Transactional
public void update(Long id, PostRequest postRequest) {
Post post = postRepository.findById(id)
.orElseThrow(()->new PostNotFoundException(id.toString()));
Subreddit subreddit =
subredditRepository.findByName(postRequest.getSubredditName())
.orElseThrow(() -> new SubredditNotFoundException(postRequest.getSubredditName()));
post.updatePost(postRequest.getSubredditName(), postRequest.getDescription(), postRequest.getUrl(), subreddit);
}
@Transactional
public void delete(Long id) {
Post post = postRepository.findById(id)
.orElseThrow(()->new PostNotFoundException(id.toString()));
postRepository.delete(post);
}
} |
import "./App.css";
import { BrowserRouter as Router, Routes, Route } from "react-router-dom";
import Home from "./pages/Home";
import CreatePost from "./pages/CreatePost";
import ReadPost from "./pages/ReadPost";
import Login from "./pages/Login";
import Register from "./pages/Register";
import Header from "./components/Header";
function App() {
return (
<div className="App">
<Router>
<Header />
<Routes>
<Route path="/" element={<Home />} />
<Route path="/createpost" element={<CreatePost />} />
<Route path="/readpost/:id" element={<ReadPost />} />
<Route path="/login" element={<Login />} />
<Route path="/register" element={<Register />} />
</Routes>
</Router>
</div>
);
}
export default App; |
#!/usr/bin/env python3
'''
Copyright 2023 David Dovrat
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
'''
import rclpy
from rclpy.node import Node
from rcl_interfaces.msg import ParameterDescriptor
from ros_nemala import NodeManager as nm
from ros_nemala_interfaces.msg import Terminate
"""
###################################################################################
class NeMALA_Tools - a facade class for NeMALA tools.
###################################################################################
"""
class NeMALA_Tools(Node):
def __init__(self):
super().__init__('nemala_node_manager')
# declare ROS paramters
self._parameter_endpoint = self.declare_parameter(name='proxy_endpoint_publishers',
value="ipc:///tmp/publishers",
descriptor=ParameterDescriptor(description='Where to publish the service messages.')
)
self._manager = nm.NodeManager()
self.terminate_subscription = self.create_subscription(
Terminate,
'nemala_input_terminate_dispatcher',
self.terminate_callback,
10)
self.terminate_subscription # prevent unused variable warning
def terminate_callback(self, msg):
self.get_logger().info('Sending a termination request to dispatcher %d.' % msg.node_id)
argv = ["NodeManager", "terminate", '[%d]' % msg.node_id, self._parameter_endpoint.value]
self._manager.execute(argv)
def main(args=None):
# ros2 initialization
rclpy.init(args=args)
tools = NeMALA_Tools()
# Do
try:
rclpy.spin(tools)
except KeyboardInterrupt:
pass
# Die
tools.destroy_node()
###################################################################################
# Run the main function
###################################################################################
if __name__ == '__main__':
main() |
/*
This file is part of Cyclos (www.cyclos.org).
A project of the Social Trade Organisation (www.socialtrade.org).
Cyclos is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
Cyclos 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 Cyclos; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
package nl.strohalm.cyclos.entities.members.printsettings;
import nl.strohalm.cyclos.entities.Entity;
import nl.strohalm.cyclos.entities.Relationship;
import nl.strohalm.cyclos.entities.members.Member;
import javax.persistence.Column;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.Table;
/**
* Stores settings for a local receipt printer
*
* @author luis
*/
@Table(name = "print_settings")
@javax.persistence.Entity
public class ReceiptPrinterSettings extends Entity {
public static enum Relationships implements Relationship {
MEMBER("member");
private final String name;
private Relationships(final String name) {
this.name = name;
}
@Override
public String getName() {
return name;
}
}
private static final long serialVersionUID = 5677759942410107438L;
@ManyToOne
@JoinColumn(name = "member_id")
private Member member;
@Column(name = "name", nullable = false, length = 100)
private String name;
@Column(name = "printer_name", nullable = false, length = 100)
private String printerName;
@Column(name = "begin_doc_cmd", length = 100)
private String beginOfDocCommand;
@Column(name = "end_doc_cmd", length = 100)
private String endOfDocCommand;
@Column(name = "payment_message", length = 500)
private String paymentAdditionalMessage;
public String getBeginOfDocCommand() {
return beginOfDocCommand;
}
public String getEndOfDocCommand() {
return endOfDocCommand;
}
public Member getMember() {
return member;
}
@Override
public String getName() {
return name;
}
public String getPaymentAdditionalMessage() {
return paymentAdditionalMessage;
}
public String getPrinterName() {
return printerName;
}
public void setBeginOfDocCommand(final String beginOfDocCommand) {
this.beginOfDocCommand = beginOfDocCommand;
}
public void setEndOfDocCommand(final String endOfDocCommand) {
this.endOfDocCommand = endOfDocCommand;
}
public void setMember(final Member member) {
this.member = member;
}
public void setName(final String name) {
this.name = name;
}
public void setPaymentAdditionalMessage(final String paymentAdditionalMessage) {
this.paymentAdditionalMessage = paymentAdditionalMessage;
}
public void setPrinterName(final String printerName) {
this.printerName = printerName;
}
@Override
public String toString() {
return getId() + " " + name + ", printer: " + printerName + ", member: " + member;
}
} |
package com.example.myapplication;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.app.DatePickerDialog;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.Toast;
import com.example.myapplication.Adapters.BookingAdapter;
import com.example.myapplication.Adapters.BookingAdapter_for_add_booking;
import com.example.myapplication.models.Booking;
import com.example.myapplication.models.Room;
import com.google.firebase.firestore.FirebaseFirestore;
import com.google.firebase.firestore.QueryDocumentSnapshot;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.Locale;
public class Add_Booking_Activity extends AppCompatActivity {
Button button1, button2, button3;
RecyclerView recyclerView;
BookingAdapter_for_add_booking bookingAdapter;
ArrayList<Room> roomsList;
ArrayList<Booking> bookingsList;
ArrayList<LocalDate> date;
FirebaseFirestore db;
LocalDate checkInDate, checkOutDate;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_add_booking);
button1 = findViewById(R.id.button1);
button2 = findViewById(R.id.button2);
button3 = findViewById(R.id.button3);
recyclerView = findViewById(R.id.recycler);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
db = FirebaseFirestore.getInstance();
bookingsList = new ArrayList<Booking>();
roomsList = new ArrayList<Room>();
date = new ArrayList<LocalDate>();
checkInDate = LocalDate.now();
button1.setText(getFormattedDateTime(checkInDate));
checkOutDate = LocalDate.now().plusDays(1);
button2.setText(getFormattedDateTime(checkOutDate));
bookingAdapter = new BookingAdapter_for_add_booking(this, bookingsList, roomsList, checkInDate, checkOutDate);
recyclerView.setAdapter(bookingAdapter);
datePickerFunc();
db.collection("rooms").get().addOnCompleteListener(task -> {
if (task.isSuccessful()) {
roomsList.clear();
for (QueryDocumentSnapshot document : task.getResult()) {
Room room = document.toObject(Room.class);
room.setDocumentId(document.getId());
roomsList.add(room);
}
bookingAdapter.notifyDataSetChanged();
} else {
Toast.makeText(this, "Error in getting rooms", Toast.LENGTH_SHORT).show();
}
});
db.collection("bookings").get().addOnCompleteListener(task -> {
if (task.isSuccessful()) {
bookingsList.clear();
for (QueryDocumentSnapshot document : task.getResult()) {
Booking booking = document.toObject(Booking.class);
bookingsList.add(booking);
}
bookingAdapter.notifyDataSetChanged();
} else {
Toast.makeText(this, "Error in getting bookings", Toast.LENGTH_SHORT).show();
}
});
button3.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
bookingAdapter.updateDates(checkInDate, checkOutDate);
}
});
}
public LocalDateTime convertBtnTextToDateTime(String btnText) {
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("EEE, MMM dd, yyyy, hh:mm:ss a", Locale.ENGLISH);
return LocalDateTime.parse(btnText, formatter);
}
public String getFormattedDateTime(LocalDate date) {
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("MMM dd yyyy", Locale.ENGLISH);
return date.format(formatter);
}
private String makeDateString(int day, int month, int year) {
return getMonthFormat(month) + " " + day + " " + year;
}
private String getMonthFormat(int month) {
if (month == 1)
return "JAN";
if (month == 2)
return "FEB";
if (month == 3)
return "MAR";
if (month == 4)
return "APR";
if (month == 5)
return "MAY";
if (month == 6)
return "JUN";
if (month == 7)
return "JUL";
if (month == 8)
return "AUG";
if (month == 9)
return "SEP";
if (month == 10)
return "OCT";
if (month == 11)
return "NOV";
if (month == 12)
return "DEC";
// default should never happen
return "JAN";
}
public void datePickerFunc() {
Calendar cal = Calendar.getInstance();
int year = cal.get(Calendar.YEAR);
int month = cal.get(Calendar.MONTH);
int day = cal.get(Calendar.DAY_OF_MONTH);
button1.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
DatePickerDialog datePickerDialog = new DatePickerDialog(Add_Booking_Activity.this, new DatePickerDialog.OnDateSetListener() {
@Override
public void onDateSet(DatePicker datePicker, int year, int month, int dayOfMonth) {
month = month + 1;
String date1 = makeDateString(dayOfMonth, month, year);
button1.setText(date1);
checkInDate = LocalDate.of(year, month, dayOfMonth);
}
}, year, month, day);
datePickerDialog.show();
}
});
button2.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
DatePickerDialog datePickerDialog = new DatePickerDialog(Add_Booking_Activity.this, new DatePickerDialog.OnDateSetListener() {
@Override
public void onDateSet(DatePicker datePicker, int year, int month, int dayOfMonth) {
month = month + 1;
String date1 = makeDateString(dayOfMonth, month, year);
button2.setText(date1);
checkOutDate = LocalDate.of(year, month, dayOfMonth);
}
}, year, month, day);
datePickerDialog.show();
}
});
}
} |
const { parse } = require("csv-parse");
const path = require("path");
const fs = require("fs");
const planetModel = require("../model/planets.mongo");
const inhabitablePlanet = (planet) => {
return (
planet["koi_disposition"] === "CONFIRMED" &&
planet["koi_insol"] > 0.36 &&
planet["koi_insol"] < 1.11 &&
planet["koi_prad"] < 1.6
);
};
// The pipe function connects the readable stream to writable stream
function loadPlanets() {
return new Promise((resolve, reject) => {
fs.createReadStream(path.join(__dirname, "..", "data", "data.csv"))
.pipe(
parse({
//options
comment: "#",
columns: true,
})
)
.on("data", async (data) => {
if (inhabitablePlanet(data)) {
await createPlanet(data);
}
})
.on("error", (err) => {
console.log(err);
reject(err);
})
.on("end", () => {
resolve();
});
});
}
async function getAllPlanets() {
return await planetModel.find({}, "-_id -__v");
}
async function createPlanet(planet) {
await planetModel.findOneAndUpdate(
{ keplerName: planet.kepler_name },
{ keplerName: planet.kepler_name },
{
upsert: true,
}
);
}
module.exports = { loadPlanets, getAllPlanets }; |
<?php
// Function to update product descriptions by category
function update_product_descriptions_by_category($category_id, $new_description) {
// Query arguments
$args = array(
'post_type' => 'product',
'posts_per_page' => -1,
'tax_query' => array(
array(
'taxonomy' => 'product_cat',
'field' => 'term_id',
'terms' => $category_id,
),
),
);
// WP Query
$loop = new WP_Query($args);
if ($loop->have_posts()) {
while ($loop->have_posts()) {
$loop->the_post();
global $product;
// Set and save the new short description
$product->set_short_description($new_description);
$product->save();
}
}
// Reset WP Query
wp_reset_query();
}
// Function to update static product descriptions by category
function update_static_product_descriptions_by_category($category_id, $new_description) {
update_product_descriptions_by_category($category_id, $new_description);
}
// Function to update temporary product descriptions by category
function update_temp_product_descriptions_by_category($category_id, $new_description_temp, $start_date, $end_date) {
// Logging for debugging
error_log("Function update_temp_product_descriptions_by_category is running.");
error_log("Received description: " . $new_description_temp);
error_log("Received start date: " . $start_date);
error_log("Received end date: " . $end_date);
// Query arguments
$args = array(
'post_type' => 'product',
'posts_per_page' => -1,
'tax_query' => array(
array(
'taxonomy' => 'product_cat',
'field' => 'term_id',
'terms' => $category_id,
),
),
);
// WP Query
$loop = new WP_Query($args);
if ($loop->have_posts()) {
while ($loop->have_posts()) {
$loop->the_post();
global $product;
// Get the current short description
$current_short_description = $product->get_short_description();
// Add the temporary description to the short description
$new_short_description = $current_short_description . "<br><div class='temp-description'>{$new_description_temp}</div>";
// Set and save the new short description
$product->set_short_description($new_short_description);
$product->save();
}
} else {
// Log if no products are found in the specified category
error_log("No products found in the specified category.");
}
// Reset WP Query
wp_reset_query();
}
// Function to show temporary or regular description based on date
function show_temp_description() {
global $product;
// Get product ID and meta data
$product_id = $product->get_id();
$temp_description = get_post_meta($product_id, 'temp_description', true);
$start_date = get_post_meta($product_id, 'temp_description_start', true);
$end_date = get_post_meta($product_id, 'temp_description_end', true);
$current_date = date('Y-m-d');
// Show temporary or regular description based on date
if ($current_date >= $start_date && $current_date <= $end_date) {
echo htmlspecialchars_decode($temp_description);
} else {
echo $product->get_short_description();
}
}
// Function to handle AJAX request for adding timed banners
add_action('wp_ajax_add_massive_timed_banners', function() {
// Verify nonce
if (!isset($_POST['massive_banner_editor_nonce_field']) || !wp_verify_nonce($_POST['massive_banner_editor_nonce_field'], 'massive_banner_editor_nonce')) {
die('Security check failed');
}
// Extract POST data
$category_id = $_POST['category_id'];
$new_description_temp = urldecode($_POST['bannercontent']);
$start_date = $_POST['bannerStart'];
$end_date = $_POST['bannerExpiry'];
// Update temporary product descriptions
update_temp_product_descriptions_by_category($category_id, $new_description_temp, $start_date, $end_date);
// End AJAX request
wp_die();
});
// Function to enqueue admin scripts
function enqueue_my_admin_scripts() {
// Enqueue SweetAlert2 and custom JS
wp_enqueue_script('sweetalert2', 'https://cdn.jsdelivr.net/npm/sweetalert2@10', array('jquery'), null, true);
wp_enqueue_script(
'massive-description-editor-js',
plugin_dir_url(dirname(__FILE__)) . 'assets/js/massive-description-editor-js.js',
array('jquery')
);
// Localize script for AJAX
wp_localize_script('massive-description-editor-js', 'frontendajax', array(
'ajaxurl' => admin_url('admin-ajax.php')
));
}
// Hook to enqueue admin scripts
add_action('admin_enqueue_scripts', 'enqueue_my_admin_scripts');
// Function to verify nonce in AJAX function
add_action('wp_ajax_update_massive_product_descriptions', function() {
// Verify nonce
if (!isset($_POST['massive_desc_editor_nonce_field']) || !wp_verify_nonce($_POST['massive_desc_editor_nonce_field'], 'massive_desc_editor_nonce')) {
die('Security check failed');
}
// Extract POST data
$category_id = $_POST['category_id'];
$new_description = $_POST['new_description'];
// Update product descriptions
update_product_descriptions_by_category($category_id, $new_description);
// End AJAX request
wp_die();
}); |
import React, { useContext, useState } from 'react';
import { addDoc, serverTimestamp } from 'firebase/firestore';
import { FontAwesomeIcon } from '@fortawesome/react-fontawesome';
import { faComments } from '@fortawesome/free-solid-svg-icons';
import '../AddPost/AddPostLayout.css';
import { UserContext, needHelpPostsData } from '../../helpers/apiCommunication';
export const AddPost = () => {
const { user } = useContext(UserContext); // Zalogowany user
const [postData, setPostData] = useState({
post: '',
postTitle: '',
});
const onChange = (e) => {
const { name, value } = e.target;
setPostData({
...postData,
createdAt: serverTimestamp(),
userID: user.uid,
[name]: value,
});
};
const onClick = (e) => {
e.preventDefault();
addDoc(needHelpPostsData, postData);
setPostData({ post: '', postTitle: '' });
};
return (
<div className="bg-gradient">
<div className="addpost_container">
<div className="post-box">
<div className="left">
<FontAwesomeIcon className="icon" icon={faComments} />
</div>
<div className="right">
<form>
<label htmlFor="postTitle">Add title: </label>
<input
type="text"
value={postData.postTitle}
name="postTitle"
onChange={onChange}
className="field"
></input>
{/* Message */}
<label htmlFor="post">Add new post: </label>
<textarea
name="post"
value={postData.post}
placeholder="Share your needs or help."
className="field"
onChange={onChange}
></textarea>
</form>
<button type="submit" onClick={onClick} className="btn">
ADD POST
</button>
</div>
</div>
</div>
</div>
);
}; |
import axiosInstance from '../helper/axiosIntance';
import { useState, useEffect, useRef } from 'react';
const useAxios = ({url, config = {}}) => {
const [callFetch, setCallFetch] = useState(false);
const [datas, setDatas] = useState(null);
const [isLoading, setIsLoading] = useState(true);
const [error, setError] = useState('');
const effectRun = useRef(false);
const deleteElement = async (url, method) => {
try {
const response = await axiosInstance[method](url);
setCallFetch(true);
} catch (error) {
window.alert(`
Ocorreu um erro inesperado!
${error}
`
);
}
}
const postElement = async (_datas, urlSecundary ) => {
try {
await axiosInstance.post(urlSecundary, _datas);
setCallFetch(true);
return 201;
} catch (error) {
window.alert('Ocorreu um error inesperado! \n '+ error);
return error;
}
}
const putElement = async (_datas, {urlSchedule}) => {
const _url = `${urlSchedule}/${_datas.id}`;
try {
const response = await axiosInstance.put(_url, _datas);
setCallFetch(true);
return response;
} catch (error) {
window.alert('Ocorreu um error inesperado! \n '+ error);
return error;
}
}
useEffect(() => {
const controller = new AbortController();
const requestDatas = async () => {
try {
const response = await axiosInstance.get(url, config);
setDatas(response);
} catch (err) {
setError(err);
} finally {
setIsLoading(false);
setCallFetch(false);
}
}
requestDatas();
return () => {
controller.abort();
effectRun.current = true;
}
}, [callFetch]);
return {datas, isLoading, error, deleteElement, postElement, putElement};
}
export default useAxios; |
"use client";
import { useRef, useEffect } from "react";
import { Chart } from "chart.js/auto";
import "chartjs-adapter-date-fns";
export default function LineChart({ traffic }) {
const chartRef = useRef(null);
//content가 "0:00"인 데이터 걸러내기
let filterTimeZeroData = traffic.map((item) =>
item.filter((obj) => obj.content !== "0:00")
);
let myFilter = filterDir();
const backgroundColors = []; //배경색
const borderColors = []; //테두리색
const buttonFilterColors = [
"rgba(255, 99, 132, 0.2)",
"rgba(255, 159, 64, 0.2)",
"rgba(255, 205, 86, 0.2)",
"rgba(75, 192, 192, 0.2)",
"rgba(54, 162, 235, 0.2)",
"rgba(153, 102, 255, 0.2)",
"rgba(201, 203, 207, 0.2)",
];
// 구간별 색상 적용
myFilter.title.map((direction, idx) => {
let color;
if (idx >= 0 && idx < 6) {
color = "rgba(153, 102, 255, 0.2)";
} else {
color = "rgba(255, 159, 64, 0.2)";
}
backgroundColors.push(color);
borderColors.push(color.replace("0.2", "1"));
});
//버튼 눌렀을때 실행되는 방향별 필터링
function filterDir(start = 21, end = -1) {
let flattened = [].concat(...filterTimeZeroData);
const titles = flattened && flattened.map((item) => item.title);
const contents = flattened && flattened.map((item) => item.content);
const slicedTitles = titles.slice(start, end);
const slicedContents = contents.slice(start, end).map((time) => {
let [hour, minute] = time && time.split(":").map(Number);
return hour * 60 + minute;
});
return {
title: slicedTitles,
content: slicedContents,
};
}
const updateChart = (direction, filteredData) => {
const { title, content } = filteredData;
if (chartRef.current) {
const chart = chartRef.current.chart;
chart.data.labels = title;
chart.data.datasets[0].data = content;
// 버튼 이름이 전체면 같은 방향끼리 배경색 적용
if (direction == "전체") {
chart.data.datasets[0].backgroundColor = backgroundColors;
chart.data.datasets[0].borderColor = borderColors;
// 버튼 이름이 전체가 아니면 아래 배경색 각각 적용
} else if (direction !== "전체") {
chart.data.datasets[0].backgroundColor = buttonFilterColors;
chart.data.datasets[0].borderColor = buttonFilterColors.map((color) =>
color.replace("0.2", "1")
);
}
chart.update();
}
};
// 차트 보여주기
useEffect(() => {
if (chartRef.current) {
if (chartRef.current.chart) {
chartRef.current.chart.destroy();
}
const context = chartRef.current.getContext("2d");
const newChart = new Chart(context, {
type: "bar",
data: {
labels: myFilter.title,
datasets: [
{
axis: "y",
label: "",
data: myFilter.content,
backgroundColor: backgroundColors,
borderColor: borderColors,
borderWidth: 1,
},
],
},
options: {
//responsive: true,
animations: {
tension: {
duration: 1000,
easing: "linear",
from: "left",
},
},
indexAxis: "y",
scales: {
x: {
type: "linear", // x축을 수치형으로 설정
min: 0, // 최소값을 0으로 설정
},
y: { type: "category" },
},
plugins: {
legend: {
display: false,
},
},
},
});
chartRef.current.chart = newChart;
}
}, []);
return (
<div className="chartArea">
<h3>버스 고속도로 구간 별 소요시간</h3>
<div className="carDirBtn2">
{["전체", "서울 ⇒ 지방방향", "지방 ⇒ 지방방향"].map((a, index) => {
return (
<div
key={index}
className={index === 0 ? "active1" : "inactive1"}
onClick={(e) => {
const parentElement = e.target.parentElement;
Array.from(parentElement.children).forEach((child) => {
if (child === e.target) {
child.className = "active1";
} else {
child.className = "inactive1";
}
});
if (a == "전체") {
const filteredData = filterDir();
updateChart(a, filteredData);
} else if (a == "서울 ⇒ 지방방향") {
const filteredData = filterDir(21, 28);
updateChart(a, filteredData);
} else {
const filteredData = filterDir(28);
updateChart(a, filteredData);
}
}}
>
{a}
</div>
);
})}
</div>
<canvas ref={chartRef} />
</div>
);
} |
/* Copyright 2017 Eric Aubanel
* This file contains code implementing Algorithm 6.1
* using indexed min priority queue, i.e. Dijkstra's algorithm, in
* Elements of Parallel Computing, by Eric Aubanel, 2016, CRC Press.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
* -------------------------------------------------------------------
* Sequential implementation of SSSP solver using Dijkstra's algorithm.
* Assumes nonzero integer weights.
* Requires index min priority queue module (indexedMinPQ.h), which can
* be adapted from indexed max priority queue (as a binary heap)
* in Sedgewick's Algorithms in C, 3rd edition.
* Reads graph as a list of weighted edges preceeded by
* two integers indicating the number of vertices and the number of edges.
* Outputs list of distances to each vertex.
*/
#include <stdio.h>
#include <stdlib.h>
#include <limits.h>
#include "indexedMinPQ.h"
//read edge list from stdin and store CSR representation of graph
//in arrays V, E, and W.
void readGraph(int *V, int *E, int *W, int n, int m);
int main(int argc, char **argv){
int n, m; //number of vertices and edges
int *V, *E, *W; //Offset , edge, and weight arrays for CSR representation
int s; //source vertex
int *D; //distance array
if(argc < 2){
fprintf(stderr,"usage: %s source_vertex\n", argv[0]);
return 1;
}
s = strtol(argv[1], NULL, 10);
scanf("%d %d",&n, &m);
if(s >= n || s < 0){
printf("invalid source vertex\n");
return 1;
}
V = malloc((n+1)*sizeof(int));
E = malloc(m*sizeof(int));
W = malloc(m*sizeof(int));
D = malloc(n*sizeof(int));
if(!V || !E || !W || !D){
fprintf(stderr,"couldn't allocate memory\n");
return 1;
}
readGraph(V, E, W, n, m);
for(int i=0; i <n; i++)
D[i] = INT_MAX;
//initialize heap based on distance array of length n
//heap has max size n (third argument)
minHeapInit(D, n, n);
D[s] = 0;
//insert source vertex in heap
minHeapInsert(s);
while(!minHeapEmpty()){
//extract min element from heap
int i = heapExtractMin();
for(int k=V[i]; k<V[i+1]; k++){
int j = E[k];
if(D[j] > D[i]+W[k]){
D[j] = D[i] + W[k];
if(isInHeap(j)){
//update distance for vertex j and re-heapify
minHeapChange(j);
} else{
//insert vertex j in heap
minHeapInsert(j);
}
}
}
}
for(int i=0;i<n;i++)
printf("%d ",D[i]);
printf("\n");
}
void readGraph(int *V, int *E, int *W, int n, int m){
for(int i=0; i<n+1; i++)
V[i] = 0;
//create CSV arrays from edge list sorted by first vertex
int vold=-1;
for(int k=0; k<m; k++){
int vi, vo, wt;
if(scanf("%d %d %d", &vi, &vo, &wt)!= 3){
fprintf(stderr, "input invalid\n");
exit(1);
}
if(vi > n-1 || vo > n-1){
fprintf(stderr, "vertex index too large\n");
exit(1);
}
if(wt < 0){
fprintf(stderr, "nonzero weights only\n");
exit(1);
}
E[k] = vo;
W[k] = wt;
if(k == 0)
V[vi] = 0;
else if(vi != vold)
V[vi] = k;
vold = vi;
}
V[n] = m;
//Find first out-edge
int first = 0;
for(int i = 1; i < n; i++)
if(V[i] != 0){
first = i-1;
break;
}
//vertices with no out-edges
for(int i = n-1; i > first; i--)
if(V[i] ==0)
V[i] = V[i+1];
} |
import React, { useEffect, useState } from 'react'
import { Link } from 'react-router-dom'
import ExteriorAPI from '../services/ExteriorAPI'
import RoofAPI from '../services/RoofAPI'
import WheelsAPI from '../services/WheelsAPI'
import InteriorAPI from '../services/InteriorAPI'
import convertible from '../assets/convertible.png'
import coupe from '../assets/coupe.png'
import '../App.css'
import '../css/Card.css'
const Car = (props) => {
const [exterior, setExterior] = useState([])
const [roof, setRoof] = useState([])
const [wheels, setWheels] = useState([])
const [interior, setInterior] = useState([])
useEffect(() => {
(async () => {
try {
const exteriorData = await ExteriorAPI.getExterior(props.exterior)
setExterior(exteriorData)
}
catch (error) {
throw error
}
}) ()
}, [])
useEffect(() => {
(async () => {
try {
const roofData = await RoofAPI.getRoof(props.roof)
setRoof(roofData)
}
catch (error) {
throw error
}
}) ()
}, [])
useEffect(() => {
(async () => {
try {
const wheelsData = await WheelsAPI.getWheels(props.wheels)
setWheels(wheelsData)
}
catch (error) {
throw error
}
}) ()
}, [])
useEffect(() => {
(async () => {
try {
const interiorData = await InteriorAPI.getInterior(props.interior)
setInterior(interiorData)
}
catch (error) {
throw error
}
}) ()
}, [])
return (
<article>
<header>
<h3>{props.isconvertible ? <img src={convertible} /> : <img src={coupe} />} {props.name}</h3>
</header>
<div className='car-card'>
<div className='car-summary'>
<p><strong>🖌️ Exterior:</strong> {exterior.color}</p>
<p><strong>😎 Roof:</strong> {roof.color}</p>
</div>
<div className='car-summary'>
<p><strong>🛴 Wheels:</strong> {wheels.color}</p>
<p><strong>💺 Interior:</strong> {interior.color}</p>
</div>
<div className='car-price'>
<p>💰 ${props.price}</p>
<a href={'/customcars/' + props.id} role='button'>Details</a>
</div>
</div>
</article>
)
}
export default Car |
defmodule MuResponse.Endpoint do
use Phoenix.Endpoint, otp_app: :mu_response
socket "/socket", MuResponse.UserSocket
# Serve at "/" the static files from "priv/static" directory.
#
# You should set gzip to true if you are running phoenix.digest
# when deploying your static files in production.
plug Plug.Static,
at: "/", from: :mu_response, gzip: false,
only: ~w(css fonts images js favicon.ico robots.txt)
# Code reloading can be explicitly enabled under the
# :code_reloader configuration of your endpoint.
if code_reloading? do
socket "/phoenix/live_reload/socket", Phoenix.LiveReloader.Socket
plug Phoenix.LiveReloader
plug Phoenix.CodeReloader
end
plug Plug.RequestId
plug Plug.Logger
plug Plug.Parsers,
parsers: [:urlencoded, :multipart, :json],
pass: ["*/*"],
json_decoder: Poison
plug Plug.MethodOverride
plug Plug.Head
plug Plug.Session,
store: :cookie,
key: "_mu_response_key",
signing_salt: "H+oUaeBm"
plug MuResponse.Router
end |
import { Injectable, BadRequestException, NotFoundException } from '@nestjs/common';
import { UserRepository } from './user.repository';
import { InjectRepository } from '@nestjs/typeorm';
import { MapperService } from '../../shared/mapper.service';
import { UserDto } from './dto/user.dto';
import { User } from './user.entity';
import { UserDetails } from './user.details.entity';
import { getConnection } from 'typeorm';
import { Role } from '../role/role.entity';
@Injectable()
export class UserService {
constructor(
@InjectRepository(UserRepository)
private readonly _userRepository: UserRepository,
private readonly _mapperService: MapperService
){}
async get(id: number): Promise<UserDto>{
if(!id)
throw new BadRequestException("id must be sent")
const user: User = await this._userRepository.findOne(id,
{ where: {status: 'ACTIVE' }
});
if(!user)
throw new NotFoundException();
return this._mapperService.map<User, UserDto>(user, new UserDto());
}
async getAll(): Promise<UserDto[]>{
const users: User[] = await this._userRepository.find(
{where: {status: 'ACTIVE'}
});
if(!users)
throw new NotFoundException();
return this._mapperService.mapCollection<User, UserDto>(users, new UserDto());
}
async create(user: User): Promise<UserDto>{
const detail = new UserDetails();
user.details = detail;
const repo = await getConnection().getRepository(Role);
const defaultRole = await repo.findOne({where: {name: 'GENERAL'}});
user.roles = [defaultRole];
const savedUser: User = await this._userRepository.save(user);
return this._mapperService.map<User, UserDto>(savedUser, new UserDto);
}
async update(id: number, user: User):Promise<void>{
await this._userRepository.update(id, user);
}
async delete(id: number): Promise<void>{
const userExists = await this._userRepository.findOne(
id, { where: {status: 'ACTIVE'} });
if(!userExists)
throw new NotFoundException();
await this._userRepository.update(id, {status: 'INACTIVE'});
}
} |
<h1 class="command">ZRANGE</h1>
<pre>ZRANGE key start stop [BYSCORE|BYLEX] [REV] [LIMIT offset count] [WITHSCORES]</pre> <div class="metadata"> <p><strong>Available since 1.2.0.</strong></p> <p><strong>Time complexity:</strong> O(log(N)+M) with N being the number of elements in the sorted set and M the number of elements returned.</p> </div> <p>Returns the specified range of elements in the sorted set stored at <code><key></code>.</p> <p><a href="zrange">ZRANGE</a> can perform different types of range queries: by index (rank), by the score, or by lexicographical order.</p> <p>Starting with Redis 6.2.0, this command can replace the following commands: <a href="zrevrange">ZREVRANGE</a>, <a href="zrangebyscore">ZRANGEBYSCORE</a>, <a href="zrevrangebyscore">ZREVRANGEBYSCORE</a>, <a href="zrangebylex">ZRANGEBYLEX</a> and <a href="zrevrangebylex">ZREVRANGEBYLEX</a>.</p> <h2>Common behavior and options</h2> <p>The order of elements is from the lowest to the highest score. Elements with the same score are ordered lexicographically.</p> <p>The optional <code>REV</code> argument reverses the ordering, so elements are ordered from highest to lowest score, and score ties are resolved by reverse lexicographical ordering.</p> <p>The optional <code>LIMIT</code> argument can be used to obtain a sub-range from the matching elements (similar to <em>SELECT LIMIT offset, count</em> in SQL). A negative <code><count></code> returns all elements from the <code><offset></code>. Keep in mind that if <code><offset></code> is large, the sorted set needs to be traversed for <code><offset></code> elements before getting to the elements to return, which can add up to <span class="math">O(N) </span>time complexity.</p> <p>The optional <code>WITHSCORES</code> argument supplements the command's reply with the scores of elements returned. The returned list contains <code>value1,score1,...,valueN,scoreN</code> instead of <code>value1,...,valueN</code>. Client libraries are free to return a more appropriate data type (suggestion: an array with (value, score) arrays/tuples).</p> <h2>Index ranges</h2> <p>By default, the command performs an index range query. The <code><start></code> and <code><stop></code> arguments represent zero-based indexes, where <code>0</code> is the first element, <code>1</code> is the next element, and so on. These arguments specify an <strong>inclusive range</strong>, so for example, <code>ZRANGE myzset 0 1</code> will return both the first and the second element of the sorted set.</p> <p>The indexes can also be negative numbers indicating offsets from the end of the sorted set, with <code>-1</code> being the last element of the sorted set, <code>-2</code> the penultimate element, and so on.</p> <p>Out of range indexes do not produce an error.</p> <p>If <code><start></code> is greater than either the end index of the sorted set or <code><stop></code>, an empty list is returned.</p> <p>If <code><stop></code> is greater than the end index of the sorted set, Redis will use the last element of the sorted set.</p> <h2>Score ranges</h2> <p>When the <code>BYSCORE</code> option is provided, the command behaves like <a href="zrangebyscore">ZRANGEBYSCORE</a> and returns the range of elements from the sorted set having scores equal or between <code><start></code> and <code><stop></code>.</p> <p><code><start></code> and <code><stop></code> can be <code>-inf</code> and <code>+inf</code>, denoting the negative and positive infinities, respectively. This means that you are not required to know the highest or lowest score in the sorted set to get all elements from or up to a certain score.</p> <p>By default, the score intervals specified by <code><start></code> and <code><stop></code> are closed (inclusive). It is possible to specify an open interval (exclusive) by prefixing the score with the character <code>(</code>.</p> <p>For example:</p> <pre>ZRANGE zset (1 5 BYSCORE
</pre> <p>Will return all elements with <code>1 < score <= 5</code> while:</p> <pre>ZRANGE zset (5 (10 BYSCORE
</pre> <p>Will return all the elements with <code>5 < score < 10</code> (5 and 10 excluded).</p> <h2>Reverse ranges</h2> <p>Using the <code>REV</code> option reverses the sorted set, with index 0 as the element with the highest score.</p> <p>By default, <code><start></code> must be less than or equal to <code><stop></code> to return anything. However, if the <code>BYSCORE</code>, or <code>BYLEX</code> options are selected, the <code><start></code> is the highest score to consider, and <code><stop></code> is the lowest score to consider, therefore <code><start></code> must be greater than or equal to <code><stop></code> in order to return anything.</p> <p>For example:</p> <pre>ZRANGE zset 5 10 REV
</pre> <p>Will return the elements between index 5 and 10 in the reversed index.</p> <pre>ZRANGE zset 10 5 REV BYSCORE
</pre> <p>Will return all elements with scores less than 10 and greater than 5.</p> <h2>Lexicographical ranges</h2> <p>When the <code>BYLEX</code> option is used, the command behaves like <a href="zrangebylex">ZRANGEBYLEX</a> and returns the range of elements from the sorted set between the <code><start></code> and <code><stop></code> lexicographical closed range intervals.</p> <p>Note that lexicographical ordering relies on all elements having the same score. The reply is unspecified when the elements have different scores.</p> <p>Valid <code><start></code> and <code><stop></code> must start with <code>(</code> or <code>[</code>, in order to specify whether the range interval is exclusive or inclusive, respectively.</p> <p>The special values of <code>+</code> or <code>-</code> for <code><start></code> and <code><stop></code> mean positive and negative infinite strings, respectively, so for instance the command <code>ZRANGE myzset - + BYLEX</code> is guaranteed to return all the elements in the sorted set, providing that all the elements have the same score.</p> <p>The <code>REV</code> options reverses the order of the <code><start></code> and <code><stop></code> elements, where <code><start></code> must be lexicographically greater than <code><stop></code> to produce a non-empty result.</p> <h3>Lexicographical comparison of strings</h3> <p>Strings are compared as a binary array of bytes. Because of how the ASCII character set is specified, this means that usually this also have the effect of comparing normal ASCII characters in an obvious dictionary way. However, this is not true if non-plain ASCII strings are used (for example, utf8 strings).</p> <p>However, the user can apply a transformation to the encoded string so that the first part of the element inserted in the sorted set will compare as the user requires for the specific application. For example, if I want to add strings that will be compared in a case-insensitive way, but I still want to retrieve the real case when querying, I can add strings in the following way:</p> <pre>ZADD autocomplete 0 foo:Foo 0 bar:BAR 0 zap:zap
</pre> <p>Because of the first <em>normalized</em> part in every element (before the colon character), we are forcing a given comparison. However, after the range is queried using <code>ZRANGE ... BYLEX</code>, the application can display to the user the second part of the string, after the colon.</p> <p>The binary nature of the comparison allows to use sorted sets as a general purpose index, for example, the first part of the element can be a 64-bit big-endian number. Since big-endian numbers have the most significant bytes in the initial positions, the binary comparison will match the numerical comparison of the numbers. This can be used in order to implement range queries on 64-bit values. As in the example below, after the first 8 bytes, we can store the value of the element we are indexing.</p> <h2>Return value</h2> <p><a href="https://redis.io/topics/protocol#array-reply">Array reply</a>: list of elements in the specified range (optionally with their scores, in case the <code>WITHSCORES</code> option is given).</p> <h2>Examples</h2> <div class="example" data-session="3de3e22a7312e2c8dce8c4952831746f"> <span class="monospace prompt">redis> </span> <span class="monospace command">ZADD myzset 1 "one"</span> <code>(integer) 1</code> <span class="monospace prompt">redis> </span> <span class="monospace command">ZADD myzset 2 "two"</span> <code>(integer) 1</code> <span class="monospace prompt">redis> </span> <span class="monospace command">ZADD myzset 3 "three"</span> <code>(integer) 1</code> <span class="monospace prompt">redis> </span> <span class="monospace command">ZRANGE myzset 0 -1</span> <code>1) "one"
2) "two"
3) "three"</code> <span class="monospace prompt">redis> </span> <span class="monospace command">ZRANGE myzset 2 3</span> <code>1) "three"</code> <span class="monospace prompt">redis> </span> <span class="monospace command">ZRANGE myzset -2 -1</span> <code>1) "two"
2) "three"</code>
</div> <p>The following example using <code>WITHSCORES</code> shows how the command returns always an array, but this time, populated with <em>element_1</em>, <em>score_1</em>, <em>element_2</em>, <em>score_2</em>, ..., <em>element_N</em>, <em>score_N</em>.</p> <div class="example" data-session="3de3e22a7312e2c8dce8c4952831746f"> <span class="monospace prompt">redis> </span> <span class="monospace command">ZRANGE myzset 0 1 WITHSCORES</span> <code>1) "one"
2) "1"
3) "two"
4) "2"</code>
</div> <p>This example shows how to query the sorted set by score, excluding the value <code>1</code> and up to infinity, returning only the second element of the result:</p> <div class="example" data-session="3de3e22a7312e2c8dce8c4952831746f"> <span class="monospace prompt">redis> </span> <span class="monospace command">ZRANGE myzset (1 +inf BYSCORE LIMIT 1 1</span> <code>1) "three"</code>
</div> <h2>History</h2> <ul> <li> Redis version >= 6.2.0: Added the `REV`, `BYSCORE`, `BYLEX` and `LIMIT` options. </li> </ul> <div class="_attribution">
<p class="_attribution-p">
<a href="https://redis.io/commands/zrange" class="_attribution-link" target="_blank">https://redis.io/commands/zrange</a>
</p>
</div> |
//
// Created by jglrxavpok on 29/06/2023.
//
#pragma once
#include <Jolt/Physics/Collision/ObjectLayer.h>
#include <Jolt/Physics/Character/CharacterBase.h>
#include <Jolt/Physics/Character/Character.h>
#include <engine/physics/Types.h>
#include <engine/physics/Colliders.h>
#include <glm/glm.hpp>
#include "BodyUserData.h"
namespace Carrot::Physics {
/**
* Represents a physics body designed to be used for player and NPCs.
* By default, has the shape of a capsule.
*/
class Character {
public:
Character();
Character(const Character&);
Character(Character&&);
~Character();
Character& operator=(const Character&);
Character& operator=(Character&&);
public:
/// use 'applyColliderChanges' if you change this collider to make sure the character is aware of changes
Collider& getCollider();
const Collider& getCollider() const;
/// update shape of character. applies change immediately
void setCollider(Collider&& newCollider);
void applyColliderChanges();
/// updates height of the character. Used to determine a supporting plane, ie a plane
/// which determines whether the character is on the ground or not
void setHeight(float height);
/// update velocity of character. applied next update
void setVelocity(const glm::vec3& velocity);
/// get current velocity of character, updated on update
const glm::vec3& getVelocity() const;
/// update transform of character. applied next update. scale is ignored
void setWorldTransform(const Carrot::Math::Transform& transform);
/// get world transform of character. updated on update, no scale is applied. updated by physics engine.
const Carrot::Math::Transform& getWorldTransform() const;
/// gets the mass of of the character
float getMass() const;
/// updates the mass of the character, triggers a recreation of the physics body
void setMass(float mass);
/// check if the character is on the ground
bool isOnGround();
/// applies an impulse along the Z axis
void jump(float speed);
public:
CollisionLayerID getCollisionLayer() const;
void setCollisionLayer(CollisionLayerID id);
public:
void prePhysics();
void postPhysics();
bool isInWorld();
void addToWorld();
void removeFromWorld();
private:
void createJoltRepresentation();
private:
Carrot::Math::Transform worldTransform;
glm::vec3 velocity{0.0f};
bool dirtyTransform = false;
bool dirtyVelocity = false;
bool onGround = false;
bool inWorld = false;
CollisionLayerID layerID = 1 /* default moving layer */;
Collider collider;
JPH::CharacterSettings characterSettings;
std::unique_ptr<JPH::Character> physics;
BodyUserData bodyUserData { BodyUserData::Type::Character, this };
};
} // Carrot::Physics |
const socket = new WebSocket('ws://localhost:8081');
// Create a promise resolver map to handle different message types
const resolvers = {};
socket.onmessage = function(event) {
const data = event.data;
const type = data.charCodeAt(0);
const success = data.charCodeAt(1);
if (resolvers[type]) {
if ((type === 1 || type === 2 || type === 3 || type === 4 || type === 5) && success === 1) {
resolvers[type]({ success: true, data: data });
} else {
// Resolve the promise with an error object instead of rejecting
resolvers[type]({ success: false, errorMessage: "Operation failed or received unexpected message type" });
}
delete resolvers[type];
} else {
console.warn("Received unhandled message type:", type);
}
};
// Function to toggle views
function toggleLoginState(isLoggedIn) {
document.getElementById('not-logged-in').style.display = isLoggedIn ? 'none' : 'block';
document.getElementById('logged-in').style.display = isLoggedIn ? 'block' : 'none';
}
//Sending message to server and creates a promise to resolve when a message is received
function sendMessageToServer(messageString, type) {
return new Promise((resolve) => {
resolvers[type] = resolve;
socket.send(messageString);
});
}
// When the popup is opened, get the current tab's URL
chrome.tabs.query({active: true, currentWindow: true}, function(tabs) {
var currentTab = tabs[0];
var currentURL = currentTab.url;
currentURL = currentURL.split('.').slice(1,2);
// Set the URL as the value for the website input
document.getElementById('set-website').value = currentURL;
document.getElementById('get-website').value = currentURL;
});
document.getElementById('register').addEventListener('click', async () => {
const password = document.getElementById('register-password').value;
const buffer = new Uint8Array(1 + password.length);
buffer[0] = 1;
for (let i = 0; i < password.length; i++) {
buffer[i + 1] = password.charCodeAt(i); // Convert each character to ASCII value
}
try {
const response = await sendMessageToServer(buffer.buffer, 1);
if (!response.success) {
alert("Registration failed");
console.error(response.errorMessage);
return;
}
alert("Registered successfully! \nPlease login to continue.");
} catch (error) {
alert("Registration failed");
}
document.getElementById('register-password').value = '';
});
document.getElementById('login').addEventListener('click', async () => {
const password = document.getElementById('login-password').value;
const buffer = new Uint8Array(1 + password.length);
buffer[0] = 2;
for (let i = 0; i < password.length; i++) {
buffer[i + 1] = password.charCodeAt(i); // Convert each character to ASCII value
}
try {
const response = await sendMessageToServer(buffer.buffer, 2);
if (!response.success) {
alert("Login failed");
console.error(response.errorMessage);
return;
}
toggleLoginState(true);
alert("Logged in successfully!");
} catch (error) {
alert("Login failed");
}
document.getElementById('login-password').value = '';
});
document.getElementById('set').addEventListener('click', async () => {
const website = document.getElementById('set-website').value;
const username = document.getElementById('set-username').value;
const password = document.getElementById('set-password').value;
const buffer = new Uint8Array(1 + 10 + 20 + 20);
buffer[0] = 3;
for (let i = 0; i < website.length && i < 10; i++) {
buffer[i + 1] = website.charCodeAt(i); // Convert each character to ASCII value
}
buffer[website.length+1] = '\0';
for (let i = 0; i < username.length && i < 20; i++) {
buffer[i + 11] = username.charCodeAt(i); // Convert each character to ASCII value
}
buffer[11+username.length] = '\0'
for (let i = 0; i < password.length && i < 20; i++) {
buffer[i + 31] = password.charCodeAt(i); // Convert each character to ASCII value
}
buffer[31+password.length] = '\0';
try {
const response = await sendMessageToServer(buffer.buffer, 3);
if (!response.success) {
alert("Setting password failed");
console.error(response.errorMessage);
return;
}
alert("Password set successfully!");
} catch (error) {
alert("Setting password failed");
}
document.getElementById('set-website').value = '';
document.getElementById('set-username').value = '';
document.getElementById('set-password').value = '';
});
//Function ro remove trailing nulls from inputString which is received from the server
function removeTrailingNulls(inputString) {
const trimmedString = inputString.replace(/\0+$/, ''); // Remove trailing nulls
return trimmedString;
}
document.getElementById('get').addEventListener('click', async () => {
const website = document.getElementById('get-website').value;
const buffer = new Uint8Array(1 + 10);
buffer[0] = 4;
for (let i = 0; i < website.length && i < 10; i++) {
buffer[i + 1] = website.charCodeAt(i); // Convert each character to ASCII value
}
try {
const responseData = await sendMessageToServer(buffer.buffer, 4);
if (!responseData.success) {
alert("Getting password failed");
console.error(responseData.errorMessage);
return;
}
const websiteResult = removeTrailingNulls(responseData.data.substring(2, 12));
const usernameResult = removeTrailingNulls(responseData.data.substring(12, 32));
const passwordResult = removeTrailingNulls(responseData.data.substring(32, 52));
//document.getElementById('get-result').textContent = `Website: ${websiteResult}, Username: ${usernameResult}, Password: ${passwordResult}`;
showCustomAlert(usernameResult, passwordResult);
} catch (error) {
alert("Getting password failed");
}
});
document.getElementById('logout').addEventListener('click', async () => {
const buffer = new Uint8Array(1);
buffer[0] = 5;
try {
const response = await sendMessageToServer(buffer.buffer, 5);
if (!response.success) {
alert("Logout failed");
console.error(response.errorMessage);
return;
}
toggleLoginState(false);
alert("Logged out successfully!");
} catch (error) {
alert("Logout failed");
}
});
//Functions for custom popup ------------------------------
function showCustomAlert(username, password) {
document.getElementById('alert-username').textContent = username;
document.getElementById('alert-password').textContent = password;
document.getElementById('custom-alert').style.display = 'block';
}
document.addEventListener("DOMContentLoaded", function() {
var closeButton = document.getElementById('closeAlertButton');
closeButton.addEventListener('click', closeAlert, false);
}, false);
function closeAlert() {
document.getElementById('custom-alert').style.display = 'none';
}
//End functions for custom popup ------------------------------ |
/*
* Copyright © 2021 - 2022
* Author: Pavel Matusevich
* Licensed under GNU AGPLv3
* All rights are reserved.
* Last updated: 10/30/22, 7:57 PM
*/
package by.enrollie
import by.enrollie.annotations.UnsafeAPI
import by.enrollie.data_classes.*
import by.enrollie.providers.*
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.flow.MutableSharedFlow
import kotlinx.coroutines.flow.SharedFlow
import kotlinx.coroutines.launch
import java.time.LocalDate
import java.time.LocalDateTime
import java.time.ZoneOffset
import java.util.UUID
import java.util.concurrent.atomic.AtomicLong
interface TemporaryDatabaseModule {
fun clearDatabase()
}
class TemporaryDatabaseImplementation : DatabaseProviderInterface {
override val databasePluginID: String = "by.enrollie.database.temporary"
override val usersProvider: DatabaseUserProviderInterface = TemporaryDatabaseUserProvider()
override val rolesProvider: DatabaseRolesProviderInterface = TemporaryDatabaseRolesProvider()
override val classesProvider: DatabaseClassesProviderInterface = TemporaryDatabaseClassesProvider()
override val timetablePlacingProvider: DatabaseTimetablePlacingProviderInterface =
TemporaryDatabaseTimetablePlacingProvider()
override val authenticationDataProvider: DatabaseAuthenticationDataProviderInterface =
TemporaryDatabaseAuthenticationDataProvider()
override val lessonsProvider: DatabaseLessonsProviderInterface = TemporaryDatabaseLessonsProvider()
override val absenceProvider: DatabaseAbsenceProviderInterface = TemporaryDatabaseAbsenceProvider(this)
override val customCredentialsProvider: DatabaseCustomCredentialsProviderInterface =
TemporaryDatabaseCustomCredentialsProvider()
override fun <T> runInSingleTransaction(block: (database: DatabaseProviderInterface) -> T): T {
return block(this)
}
override suspend fun <T> runInSingleTransactionAsync(block: suspend (database: DatabaseProviderInterface) -> T): T {
return block(this)
}
fun clear() {
(customCredentialsProvider as TemporaryDatabaseModule).clearDatabase()
(absenceProvider as TemporaryDatabaseModule).clearDatabase()
(lessonsProvider as TemporaryDatabaseModule).clearDatabase()
(authenticationDataProvider as TemporaryDatabaseModule).clearDatabase()
(timetablePlacingProvider as TemporaryDatabaseModule).clearDatabase()
(classesProvider as TemporaryDatabaseModule).clearDatabase()
(rolesProvider as TemporaryDatabaseModule).clearDatabase()
(usersProvider as TemporaryDatabaseModule).clearDatabase()
}
}
class TemporaryDatabaseCustomCredentialsProvider : DatabaseCustomCredentialsProviderInterface, TemporaryDatabaseModule {
private val credentials = mutableMapOf<String, String>()
override fun clearDatabase() {
credentials.clear()
}
override fun getCredentials(userID: UserID, credentialsType: String): String? {
return credentials["$userID:$credentialsType"]
}
override fun setCredentials(userID: UserID, credentialsType: String, credentials: String) {
this.credentials["$userID:$credentialsType"] = credentials
}
override fun clearCredentials(userID: UserID, credentialsType: String) {
credentials.remove("$userID:$credentialsType")
}
}
class TemporaryDatabaseAbsenceProvider(private val database: DatabaseProviderInterface) :
DatabaseAbsenceProviderInterface, TemporaryDatabaseModule {
private val _eventsFlow = MutableSharedFlow<DatabaseAbsenceProviderInterface.AbsenceEvent>()
override val eventsFlow: SharedFlow<DatabaseAbsenceProviderInterface.AbsenceEvent>
get() = _eventsFlow
private val absences = mutableListOf<AbsenceRecord>()
private val dataRich = mutableListOf<Pair<LocalDate, ClassID>>()
override fun clearDatabase() {
absences.clear()
dataRich.clear()
nextAbsenceID.set(0)
}
override fun getAbsence(absenceID: AbsenceID): AbsenceRecord? {
return absences.find { it.id == absenceID }
}
override fun getAbsencesForUser(userID: UserID, datesRange: Pair<LocalDate, LocalDate>): List<AbsenceRecord> {
return absences.filter { it.student.id == userID && it.absenceDate in datesRange.first..datesRange.second }
}
override fun getAbsencesForClass(classID: ClassID, datesRange: Pair<LocalDate, LocalDate>): List<AbsenceRecord> {
return absences.filter { it.classID == classID && it.absenceDate in datesRange.first..datesRange.second }
}
override fun getAbsencesForClass(classID: ClassID, date: LocalDate): List<AbsenceRecord> {
return absences.filter { it.classID == classID && it.absenceDate == date }
}
override fun getClassesWithoutAbsenceInfo(date: LocalDate): List<ClassID> {
return database.classesProvider.getClasses().map { it.id }.filter { classID ->
absences.none { it.classID == classID && it.absenceDate == date } && dataRich.none { it.first == date && it.second == classID }
}
}
override fun getClassesWithoutAbsenceInfo(datesRange: Pair<LocalDate, LocalDate>): List<ClassID> {
return database.classesProvider.getClasses().map { it.id }.filter { classID ->
absences.none { it.classID == classID && it.absenceDate in datesRange.first..datesRange.second } && dataRich.none { it.first in datesRange.first..datesRange.second && it.second == classID }
}
}
override fun getDatesWithoutAbsenceInfo(classID: ClassID, datesRange: Pair<LocalDate, LocalDate>): List<LocalDate> {
return (datesRange.first.datesUntil(datesRange.second).toList() + datesRange.second).filter { date ->
absences.none { it.classID == classID && it.absenceDate == date } && dataRich.none { it.first == date && it.second == classID }
}
}
override fun <T : Any> updateAbsence(updatedByRole: String, absenceID: AbsenceID, field: Field<T>, value: T) {
val absence = absences.find { it.id == absenceID } ?: return
val role = database.rolesProvider.getAllRolesByMatch { it.uniqueID == updatedByRole }.first()
val updatedAbsence = when (field) {
Field(AbsenceRecord::absenceType) -> absence.copy(absenceType = value as AbsenceType)
Field(AbsenceRecord::lessonsList) -> absence.copy(lessonsList = value as List<TimetablePlace>)
else -> throw IllegalArgumentException("Field $field is not supported")
}.copy(
lastUpdatedBy = AuthorizedChangeAuthor(database.usersProvider.getUser(role.userID)!!, role),
lastUpdated = LocalDateTime.now()
)
absences.remove(absence)
absences.add(updatedAbsence)
CoroutineScope(Dispatchers.IO).launch {
_eventsFlow.emit(
DatabaseAbsenceProviderInterface.AbsenceEvent(
Event.EventType.UPDATED,
absence,
updatedAbsence
)
)
}
}
private val nextAbsenceID = AtomicLong(0)
override fun createAbsence(record: DatabaseAbsenceProviderInterface.NewAbsenceRecord): AbsenceRecord {
val creatorRole = database.rolesProvider.getAllRolesByMatch { it.uniqueID == record.creatorRoleID }.first()
val creatorUser = database.usersProvider.getUser(creatorRole.userID)!!
val absence = AbsenceRecord(
id = nextAbsenceID.addAndGet(1),
classID = record.classID,
student = database.usersProvider.getUser(record.studentUserID)!!,
absenceDate = record.absenceDate,
absenceType = record.absenceType,
lessonsList = record.skippedLessons,
created = LocalDateTime.now(),
createdBy = AuthorizedChangeAuthor(creatorUser, creatorRole),
lastUpdatedBy = null, lastUpdated = null
)
absences.add(absence)
dataRich.removeIf { it.first == absence.absenceDate && it.second == absence.classID }
CoroutineScope(Dispatchers.IO).launch {
_eventsFlow.emit(DatabaseAbsenceProviderInterface.AbsenceEvent(Event.EventType.CREATED, absence, null))
}
return absence
}
override fun createAbsences(absences: List<DatabaseAbsenceProviderInterface.NewAbsenceRecord>): List<AbsenceRecord> {
return absences.map { createAbsence(it) }
}
override fun markClassAsDataRich(sentByRole: String, classID: ClassID, date: LocalDate) {
if (dataRich.none { it.first == date && it.second == classID }) {
dataRich.add(date to classID)
}
}
override fun getAllAbsences(): List<AbsenceRecord> {
return absences
}
override fun getAbsences(datesRange: Pair<LocalDate, LocalDate>): List<AbsenceRecord> {
return absences.filter { it.absenceDate in datesRange.first..datesRange.second }
}
override fun getAbsences(date: LocalDate): List<AbsenceRecord> {
return absences.filter { it.absenceDate == date }
}
}
class TemporaryDatabaseLessonsProvider : DatabaseLessonsProviderInterface, TemporaryDatabaseModule {
private val _eventsFlow = MutableSharedFlow<DatabaseLessonsProviderInterface.LessonEvent>()
override val eventsFlow: SharedFlow<DatabaseLessonsProviderInterface.LessonEvent>
get() = _eventsFlow
private val lessons = mutableListOf<Lesson>()
private val subgroups = mutableListOf<Subgroup>()
override fun clearDatabase() {
lessons.clear()
subgroups.clear()
journalIDs.clear()
}
override fun getLesson(lessonID: LessonID): Lesson? {
return lessons.find { it.id == lessonID }
}
override fun getLessonsForClass(classID: ClassID): List<Lesson> {
return lessons.filter { it.classID == classID }
}
override fun getLessonsForClass(classID: ClassID, datesRange: Pair<LocalDate, LocalDate>): List<Lesson> {
return lessons.filter { it.classID == classID && it.date in datesRange.first..datesRange.second }
}
override fun getLessonsForClass(classID: ClassID, date: LocalDate): List<Lesson> {
return lessons.filter { it.classID == classID && it.date == date }
}
override fun getLessonsForTeacher(teacherID: UserID): List<Lesson> {
return lessons.filter { it.teacher == teacherID }
}
override fun getLessonsForTeacher(teacherID: UserID, datesRange: Pair<LocalDate, LocalDate>): List<Lesson> {
return lessons.filter { it.teacher == teacherID && it.date in datesRange.first..datesRange.second }
}
override fun getLessonsForTeacher(teacherID: UserID, date: LocalDate): List<Lesson> {
return lessons.filter { it.teacher == teacherID && it.date == date }
}
override fun createLesson(lesson: Lesson) {
lessons.add(lesson)
CoroutineScope(Dispatchers.IO).launch {
_eventsFlow.emit(DatabaseLessonsProviderInterface.LessonEvent(Event.EventType.CREATED, lesson, null))
}
}
override fun createOrUpdateLessons(lessons: List<Lesson>) {
lessons.forEach { lesson ->
val oldLesson = this.lessons.find { it.id == lesson.id }
if (oldLesson != null) {
this.lessons.remove(oldLesson)
this.lessons.add(lesson)
CoroutineScope(Dispatchers.IO).launch {
_eventsFlow.emit(
DatabaseLessonsProviderInterface.LessonEvent(
Event.EventType.UPDATED,
lesson,
oldLesson
)
)
}
} else {
this.lessons.add(lesson)
CoroutineScope(Dispatchers.IO).launch {
_eventsFlow.emit(
DatabaseLessonsProviderInterface.LessonEvent(
Event.EventType.CREATED,
lesson,
null
)
)
}
}
}
}
override fun deleteLesson(lessonID: LessonID) {
val lesson = lessons.find { it.id == lessonID }
if (lesson != null) {
lessons.remove(lesson)
CoroutineScope(Dispatchers.IO).launch {
_eventsFlow.emit(DatabaseLessonsProviderInterface.LessonEvent(Event.EventType.DELETED, lesson, null))
}
}
}
private val journalIDs = mutableMapOf<JournalID, String>()
override fun getJournalTitles(journals: List<JournalID>): Map<JournalID, String?> {
return journals.associateWith { journalIDs[it] }
}
override fun setJournalTitles(mappedTitles: Map<JournalID, String>) {
journalIDs.putAll(mappedTitles)
}
override fun getAllLessons(): List<Lesson> {
return lessons
}
override fun getLessons(date: LocalDate): List<Lesson> {
return lessons.filter { it.date == date }
}
override fun getLessons(datesRange: Pair<LocalDate, LocalDate>): List<Lesson> {
return lessons.filter { it.date in datesRange.first..datesRange.second }
}
override fun createSubgroup(
subgroupID: SubgroupID,
schoolClassID: ClassID,
subgroupName: String,
members: List<UserID>?
) {
subgroups.add(Subgroup(subgroupID, subgroupName, schoolClassID, members ?: listOf()))
}
override fun createSubgroups(subgroupsList: List<Subgroup>) {
subgroups.addAll(subgroupsList)
}
override fun getSubgroup(subgroupID: SubgroupID): Subgroup? {
return subgroups.find { it.id == subgroupID }
}
override fun <T : Any> updateSubgroup(subgroupID: SubgroupID, field: Field<T>, value: T) {
val subgroup = subgroups.find { it.id == subgroupID }
?: throw IllegalArgumentException("Subgroup with id $subgroupID not found")
val newSubgroup = when (field) {
Field(Subgroup::title) -> subgroup.copy(title = value as String)
Field(Subgroup::members) -> subgroup.copy(members = value as List<UserID>)
else -> throw IllegalArgumentException("Field $field is not supported")
}
subgroups.remove(subgroup)
subgroups.add(newSubgroup)
}
override fun deleteSubgroup(subgroupID: SubgroupID) {
subgroups.removeIf { it.id == subgroupID }
}
}
class TemporaryDatabaseAuthenticationDataProvider : DatabaseAuthenticationDataProviderInterface,
TemporaryDatabaseModule {
private val _eventsFlow = MutableSharedFlow<DatabaseAuthenticationDataProviderInterface.AuthenticationDataEvent>()
override val eventsFlow: SharedFlow<DatabaseAuthenticationDataProviderInterface.AuthenticationDataEvent>
get() = _eventsFlow
private val tokens = mutableListOf<AuthenticationToken>()
override fun clearDatabase() {
tokens.clear()
}
override fun getUserTokens(userID: UserID): List<AuthenticationToken> {
return tokens.filter { it.userID == userID }
}
override fun generateNewToken(userID: UserID): AuthenticationToken {
val token = AuthenticationToken(UUID.randomUUID().toString(), userID, LocalDateTime.now())
tokens.add(token)
CoroutineScope(Dispatchers.IO).launch {
_eventsFlow.emit(
DatabaseAuthenticationDataProviderInterface.AuthenticationDataEvent(
Event.EventType.CREATED,
token,
null
)
)
}
return token
}
override fun revokeToken(token: AuthenticationToken) {
tokens.remove(token)
CoroutineScope(Dispatchers.IO).launch {
_eventsFlow.emit(
DatabaseAuthenticationDataProviderInterface.AuthenticationDataEvent(
Event.EventType.DELETED,
token,
null
)
)
}
}
override fun getUserByToken(token: String): UserID? {
return tokens.find { it.token == token }?.userID
}
override fun checkToken(token: String, userID: UserID): Boolean {
return tokens.find { it.token == token && it.userID == userID } != null
}
}
class TemporaryDatabaseTimetablePlacingProvider : DatabaseTimetablePlacingProviderInterface, TemporaryDatabaseModule {
private val timetablePlacing = mutableListOf<Pair<LocalDateTime, TimetablePlaces>>()
override fun clearDatabase() {
timetablePlacing.clear()
}
override fun getTimetablePlaces(): TimetablePlaces {
return timetablePlacing.minBy { it.first.toEpochSecond(ZoneOffset.UTC) }.second
}
override fun getTimetablePlaces(date: LocalDate): TimetablePlaces? {
return timetablePlacing.firstOrNull { it.first.toLocalDate() == date }?.second
}
override fun updateTimetablePlaces(timetablePlaces: TimetablePlaces) {
timetablePlacing.add(LocalDateTime.now() to timetablePlaces)
}
}
class TemporaryDatabaseClassesProvider : DatabaseClassesProviderInterface, TemporaryDatabaseModule {
private val classes = mutableListOf<SchoolClass>()
private val pupilsOrdering = mutableMapOf<ClassID, List<Pair<UserID, Int>>>()
private val subgroups = mutableMapOf<ClassID, List<Subgroup>>()
override fun clearDatabase() {
classes.clear()
pupilsOrdering.clear()
subgroups.clear()
}
override fun getClass(classID: ClassID): SchoolClass? {
return classes.find { it.id == classID }
}
override fun getClasses(): List<SchoolClass> {
return classes
}
override fun createClass(classData: SchoolClass) {
classes.add(classData)
}
override fun batchCreateClasses(classes: List<SchoolClass>) {
this.classes.addAll(classes)
}
override fun <T : Any> updateClass(classID: ClassID, field: Field<T>, value: T) {
val snapshot = classes.find { it.id == classID } ?: return
val newClass = when (field) {
Field(SchoolClass::title) -> snapshot.copy(title = value as String)
Field(SchoolClass::shift) -> snapshot.copy(shift = value as TeachingShift)
else -> throw IllegalArgumentException("Field $field is not supported")
}
classes.remove(snapshot)
classes.add(newClass)
}
override fun getPupilsOrdering(classID: ClassID): List<Pair<UserID, Int>> {
return pupilsOrdering[classID] ?: emptyList()
}
override fun setPupilsOrdering(classID: ClassID, pupilsOrdering: List<Pair<UserID, Int>>) {
this.pupilsOrdering[classID] = pupilsOrdering
}
override fun getSubgroups(classID: ClassID): List<Subgroup> {
return subgroups[classID] ?: emptyList()
}
}
class TemporaryDatabaseRolesProvider : DatabaseRolesProviderInterface, TemporaryDatabaseModule {
private val _eventsFlow = MutableSharedFlow<DatabaseRolesProviderInterface.RoleEvent>()
override val eventsFlow: SharedFlow<DatabaseRolesProviderInterface.RoleEvent>
get() = _eventsFlow
private val roles = mutableListOf<RoleData>()
private val scope = CoroutineScope(Dispatchers.IO)
override fun clearDatabase() {
roles.clear()
}
override fun getRolesForUser(userID: UserID): List<RoleData> {
return roles.filter { it.userID == userID }
}
override fun appendRoleToUser(userID: UserID, role: DatabaseRolesProviderInterface.RoleCreationData): RoleData {
val roleData = RoleData(
role = role.role,
userID = userID,
roleGrantedDateTime = role.creationDate,
roleRevokedDateTime = role.expirationDate,
additionalInformation = role.informationHolder,
uniqueID = UUID.randomUUID().toString()
)
roles.add(roleData)
scope.launch {
_eventsFlow.emit(DatabaseRolesProviderInterface.RoleEvent(Event.EventType.CREATED, roleData, null))
}
return roleData
}
override fun batchAppendRolesToUsers(
users: List<UserID>, roleGenerator: (UserID) -> DatabaseRolesProviderInterface.RoleCreationData
) {
val roles = users.map { appendRoleToUser(it, roleGenerator(it)) }
scope.launch {
roles.forEach {
_eventsFlow.emit(DatabaseRolesProviderInterface.RoleEvent(Event.EventType.CREATED, it, null))
}
}
}
override fun getAllRolesByType(type: Roles.Role): List<RoleData> {
return roles.filter { it.role == type }
}
override fun getAllRolesByMatch(match: (RoleData) -> Boolean): List<RoleData> {
return roles.filter(match)
}
override fun getAllRolesWithMatchingEntries(vararg entries: Pair<Roles.Role.Field<*>, Any?>): List<RoleData> {
return roles.filter { role ->
entries.all {
@OptIn(UnsafeAPI::class)
role.unsafeGetField(it.first) == it.second
}
}
}
override fun <T : Any> updateRole(roleID: String, field: Field<T>, value: T) {
val role = roles.find { it.uniqueID == roleID } ?: return
scope.launch {
_eventsFlow.emit(DatabaseRolesProviderInterface.RoleEvent(Event.EventType.UPDATED, role, role))
}
}
override fun revokeRole(roleID: String, revokeDateTime: LocalDateTime?) {
val role = roles.find { it.uniqueID == roleID } ?: return
roles.remove(role)
val newRole = RoleData(
role = role.role,
userID = role.userID,
roleGrantedDateTime = role.roleGrantedDateTime,
roleRevokedDateTime = revokeDateTime ?: LocalDateTime.now(),
additionalInformation = @OptIn(UnsafeAPI::class) role.getRoleInformationHolder(),
uniqueID = role.uniqueID
)
roles.add(newRole)
scope.launch {
_eventsFlow.emit(DatabaseRolesProviderInterface.RoleEvent(Event.EventType.UPDATED, newRole, role))
}
}
override fun triggerRolesUpdate() {
//Do nothing
}
}
class TemporaryDatabaseUserProvider : DatabaseUserProviderInterface, TemporaryDatabaseModule {
private val users = mutableListOf<User>()
override val eventsFlow: SharedFlow<DatabaseUserProviderInterface.UserEvent>
get() = _eventsFlow
private val _eventsFlow = MutableSharedFlow<DatabaseUserProviderInterface.UserEvent>()
private val coroutineScope = CoroutineScope(Dispatchers.IO)
override fun clearDatabase() {
users.clear()
}
override fun getUser(userID: UserID): User? {
return users.find { it.id == userID }
}
override fun getUsers(): List<User> {
return users
}
override fun createUser(user: User) {
users.add(user)
coroutineScope.launch {
_eventsFlow.tryEmit(
DatabaseUserProviderInterface.UserEvent(
Event.EventType.CREATED, user, null
)
)
}
}
override fun batchCreateUsers(users: List<User>) {
this.users.addAll(users)
coroutineScope.launch {
users.forEach {
_eventsFlow.tryEmit(
DatabaseUserProviderInterface.UserEvent(
Event.EventType.CREATED, it, null
)
)
}
}
}
override fun <T : Any> updateUser(userID: UserID, field: Field<T>, value: T) {
val user = users.find { it.id == userID } ?: throw IllegalArgumentException("User with id $userID not found")
val oldUser = user.copy()
when (field) {
Field(User::name) -> {
users.remove(user)
users.add(user.copy(name = value as Name))
}
else -> throw IllegalArgumentException("Field $field is not supported")
}
coroutineScope.launch {
_eventsFlow.tryEmit(
DatabaseUserProviderInterface.UserEvent(
Event.EventType.UPDATED, user, oldUser
)
)
}
}
override fun deleteUser(userID: UserID) {
val user = users.find { it.id == userID } ?: throw IllegalArgumentException("User with id $userID not found")
users.remove(user)
coroutineScope.launch {
_eventsFlow.tryEmit(
DatabaseUserProviderInterface.UserEvent(
Event.EventType.DELETED, user, null
)
)
}
}
} |
<!-- <form [formGroup]="form" (submit)="submit()">
<mat-dialog-content class="mat-typography">
<section>
<div class="form-group">
<input type="text" placeholder="Passenger Name" formControlName="name">
</div>
<ngx-intl-tel-input
[cssClass]="'custom'"
[preferredCountries]="[CountryISO.UnitedStates, CountryISO.UnitedKingdom]"
[enableAutoCountrySelect]="false"
[enablePlaceholder]="true"
[searchCountryFlag]="true"
[searchCountryField]="[SearchCountryField.Iso2, SearchCountryField.Name]"
[selectFirstCountry]="false"
[selectedCountryISO]="CountryISO.India"
[maxLength]="15"
[phoneValidation]="true"
inputId="my-input-id"
name="phone"
formControlName="phone"
></ngx-intl-tel-input>
</section>
</mat-dialog-content>
<mat-dialog-actions >
<button mat-raised-button cdkFocusInitial color="primary">
Save
</button>
<button mat-button mat-dialog-close type="button">
Re-Set
</button>
</mat-dialog-actions>
</form> -->
<section>
<header class="d-flex justify-content-between align-items-center">
<h2 mat-dialog-title>
{{ 'AddPassengers' | translate }}
</h2>
<!-- <button mat-button routerLink="/2" type="button">
<mat-icon>
keyboard_backspace
</mat-icon>
{{ 'BackToBooking' | translate }}
</button> -->
</header>
<mat-list >
<ng-container *ngFor="let passenger of passengersList; index as i">
<mat-list-item *ngIf="activeEditIndex !== i; else showEditForm ">
<div matListItemTitle class="d-flex justify-content-between">
<span>
{{ passenger.full_name }}
<span class="light">
({{ Gender[passenger.gender] }})
</span>
</span>
<span class="light" *ngIf="passenger.phone">
{{ passenger.phone.countryName }}
</span>
<div class="d-flex action-btns">
<button mat-button class="edit" (click)="editPassenger(i)">
{{ 'Edit' | translate }}
</button>
<ng-container *ngIf="i !== 0">
<span class="pipe"></span>
<button mat-button class="delete" (click)="delete(i)">
{{ 'Delete' | translate }}
</button>
</ng-container>
</div>
</div>
<div *ngIf="passenger.phone" matListItemLine class="d-flex justify-content-between">
<span>
{{ passenger.phone.e164Number }}
</span>
<span>
{{ passenger.email }}
</span>
</div>
</mat-list-item>
<ng-template #showEditForm>
<app-passenger-form [inEdit]="true" [passengerForm]="editForm" [passengersList]="passengersList" (btnClicked)="updatePassenger($event)"></app-passenger-form>
</ng-template>
<mat-divider></mat-divider>
</ng-container>
</mat-list>
<!-- <form [formGroup]="passengersForm" #f="ngForm" (submit)="submit(f)" *ngIf="passengersForm">
<header class="mb-3" *ngIf="passengersList.length != 0">
<h2 mat-dialog-title>
Add Passengers
</h2>
</header>
<div class="row">
<div class="form-group col-md-7 mb-3">
<input type="text" placeholder="Passenger Name" formControlName="name">
</div>
<div class="form-group col-md-5 mb-3" >
<mat-radio-group formControlName="gender" aria-label="Select a gender" class="d-flex justify-content-end" color="primary">
<mat-radio-button [value]="1">Male</mat-radio-button>
<mat-radio-button [value]="2">Female</mat-radio-button>
</mat-radio-group>
</div>
<div class="col-md-6 form-group mb-3" *ngIf="passengersForm.controls.phone">
<ngx-intl-tel-input
[cssClass]="'custom'"
[preferredCountries]="preferredCountries"
[enableAutoCountrySelect]="false"
[enablePlaceholder]="true"
[searchCountryFlag]="true"
[searchCountryField]="[SearchCountryField.Iso2, SearchCountryField.Name]"
[selectFirstCountry]="false"
[selectedCountryISO]="passengersForm.controls.phone.value?.countryCode || CountryISO.Turkey"
[maxLength]="15"
[phoneValidation]="true"
inputId="my-input-id"
name="phone"
formControlName="phone"
customPlaceholder="Phone Number"
></ngx-intl-tel-input>
</div>
<div class="col-md-6 form-group mb-3" *ngIf="passengersForm.controls.email">
<input type="email" placeholder="Email" formControlName="email">
</div>
<div class="col-md-12 d-flex justify-content-center">
<button mat-button class="submit-btn">
<mat-icon>add</mat-icon>
Add More Passenger
</button>
</div>
</div>
</form> -->
<app-passenger-form [passengerForm]="passengersForm" [passengersList]="passengersList" (btnClicked)="submit($event)"></app-passenger-form>
<!-- <footer>
<button mat-raised-button [disabled]="passengersList.length == 0" color="primary" (click)="save()">
Done
</button>
</footer> -->
</section> |
#include <iostream>
#include <list>
using namespace std;
void PrintList(const list<int>&L)
{
for(_List_const_iterator<int> it=L.begin(); it != L.end(); it++)
{
cout<<*it<<" ";
}
cout<<endl;
}
//list 容器的大小操作
void test01()
{
list<int>L1;
L1.push_back(10);
L1.push_back(20);
L1.push_back(30);
L1.push_back(40);
PrintList(L1);
//判断是否为空
if(L1.empty())
{
cout<<"L1 is empty"<<endl;
}
else
{
cout<<"L1 is not empty"<<endl;
cout<<"size of L1: "<<L1.size()<<endl;
}
//重新指定个数大小
L1.resize(10,1000);
PrintList(L1);
L1.resize(2);
PrintList(L1);
}
int main() {
test01();
return 0;
} |
@c This is part of the Emacs manual.
@c Copyright (C) 1985, 1986, 1987, 1993, 1994, 1995, 1997, 2001, 2002,
@c 2003, 2004, 2005, 2006, 2007, 2008, 2009 Free Software Foundation, Inc.
@c See file emacs.texi for copying conditions.
@iftex
@chapter Characters, Keys and Commands
This chapter explains the character sets used by Emacs for input
commands, and the fundamental concepts of @dfn{keys} and
@dfn{commands}, whereby Emacs interprets your keyboard and mouse
input.
@end iftex
@ifnottex
@raisesections
@end ifnottex
@node User Input, Keys, Screen, Top
@section Kinds of User Input
@cindex input with the keyboard
@cindex keyboard input
@cindex character set (keyboard)
@cindex @acronym{ASCII}
@cindex C-
@cindex Control
@cindex control characters
GNU Emacs is primarily designed for use with the keyboard. While it
is possible to use the mouse to issue editing commands through the
menu bar and tool bar, that is not as efficient as using the keyboard.
Therefore, this manual mainly documents how to edit with the keyboard.
Keyboard input into Emacs is based on a heavily-extended version of
@acronym{ASCII}. The simplest characters that you can input into
Emacs correspond to graphic symbols such as @samp{a}, @samp{B},
@samp{3}, @samp{=}, the space character (conventionally denoted as
@key{SPC}), and so on. Entering these using the keyboard is
straightforward. Certain characters found on non-English keyboards
also fall into this category (@pxref{International}).
In addition to these simple characters, Emacs recognizes
@dfn{control characters} such as @key{RET}, @key{TAB}, @key{DEL},
@key{ESC}, @key{F1}, @key{Home}, @key{left}, etc. Most keyboards have
special keys for entering these.
@cindex modifier keys
@cindex Control
@cindex C-
@cindex Meta
@cindex M-
Emacs also recognizes control characters that are entered using
@dfn{modifier keys}. Two commonly-used modifier keys are
@key{Control} (which is usually labelled as @key{Ctrl}), and
@key{Meta} (which is usually labeled as @key{Alt})@footnote{We refer
to @key{Alt} as @key{Meta} for historical reasons.}. For example,
@kbd{Control-a} is entered by holding down the @key{Ctrl} key while
pressing @kbd{a}; we will refer to this as @kbd{C-a} for short.
Similarly @kbd{Meta-a}, or @kbd{M-a} for short, is entered by holding
down the @key{Alt} key and pressing @kbd{a}.
@cindex @key{ESC} replacing @key{Meta} key
You can also type Meta characters using two-character sequences
starting with @key{ESC}. Thus, you can enter @kbd{M-a} by typing
@kbd{@key{ESC} a}. You can enter @kbd{C-M-a} by typing @kbd{@key{ESC}
C-a}. Unlike @key{Meta}, @key{ESC} is entered as a separate
character. You don't hold down @key{ESC} while typing the next
character; instead, press @key{ESC} and release it, then enter the
next character. This feature is useful on certain text-only terminals
where the @key{Meta} key does not function reliably.
Modifier keys can apply not only to alphanumerical characters, but
also to special input characters, such as the arrow keys and mouse
buttons.
@cindex input event
@xref{Input Events,,, elisp, The Emacs Lisp Reference Manual}, for
the full Lisp-level details about keyboard and mouse input, which are
collectively referred to as @dfn{input events}. If you are not doing
Lisp programming, but simply want to redefine the meaning of some
characters or non-character events, see @ref{Customization}.
@cindex keys stolen by window manager
@cindex window manager, keys stolen by
On graphical displays, the window manager is likely to block the
character @kbd{M-@key{TAB}} before Emacs can see it. It may also
block @kbd{M-@key{SPC}}, @kbd{C-M-d} and @kbd{C-M-l}. If you have
these problems, we recommend that you customize your window manager to
turn off those commands, or put them on key combinations that Emacs
does not use.
@node Keys, Commands, User Input, Top
@section Keys
Some Emacs commands are invoked by just one input event; for
example, @kbd{C-f} moves forward one character in the buffer. But
Emacs also has commands that take two or more input events to invoke,
such as @kbd{C-x C-f} and @kbd{C-x 4 C-f}.
@cindex key
@cindex key sequence
@cindex complete key
@cindex prefix key
A @dfn{key sequence}, or @dfn{key} for short, is a sequence of one
or more input events that is meaningful as a unit. If a key sequence
invokes a command, we call it a @dfn{complete key}; for example,
@kbd{C-f}, @kbd{C-x C-f} and @kbd{C-x 4 C-f} are all complete keys.
If a key sequence isn't long enough to invoke a command, we call it a
@dfn{prefix key}; from the preceding example, we see that @kbd{C-x}
and @kbd{C-x 4} are prefix keys. Every key is either a complete key
or a prefix key.
A prefix key combines with the following input event to make a
longer key sequence, which may itself be complete or a prefix. For
example, @kbd{C-x} is a prefix key, so @kbd{C-x} and the next input
event combine to make a two-event key sequence. This two-event key
sequence could itself be a prefix key (such as @kbd{C-x 4}), or a
complete key (such as @kbd{C-x C-f}). There is no limit to the length
of a key sequence, but in practice people rarely use sequences longer
than three or four input events.
You can't add input events onto a complete key. For example, the
two-event sequence @kbd{C-f C-k} is not a key, because the @kbd{C-f}
is a complete key in itself, so @kbd{C-f C-k} cannot have an
independent meaning as a command. @kbd{C-f C-k} is two key sequences,
not one.@refill
By default, the prefix keys in Emacs are @kbd{C-c}, @kbd{C-h},
@kbd{C-x}, @kbd{C-x @key{RET}}, @kbd{C-x @@}, @kbd{C-x a}, @kbd{C-x
n}, @kbd{C-x r}, @kbd{C-x v}, @kbd{C-x 4}, @kbd{C-x 5}, @kbd{C-x 6},
@key{ESC}, @kbd{M-g}, and @kbd{M-o}. (@key{F1} and @key{F2} are
aliases for @kbd{C-h} and @kbd{C-x 6}.) This list is not cast in
stone; if you customize Emacs, you can make new prefix keys. You
could even eliminate some of the standard ones, though this is not
recommended for most users; for example, if you remove the prefix
definition of @kbd{C-x 4}, then @kbd{C-x 4 @var{anything}} would
become an invalid key sequence. @xref{Key Bindings}.
Typing the help character (@kbd{C-h} or @key{F1}) after a prefix key
displays a list of the commands starting with that prefix. The sole
exception to this rule is @key{ESC}: @kbd{@key{ESC}C-h} is equivalent
to @kbd{C-M-h}, which does something else entirely. You can, however,
use @key{F1} to displays a list of the commands starting with
@key{ESC}.
@node Commands, Entering Emacs, Keys, Top
@section Keys and Commands
@cindex binding
@cindex command
@cindex function definition
This manual is full of passages that tell you what particular keys
do. But Emacs does not assign meanings to keys directly. Instead,
Emacs assigns meanings to named @dfn{commands}, and then gives keys
their meanings by @dfn{binding} them to commands.
Every command has a name chosen by a programmer. The name is
usually made of a few English words separated by dashes; for example,
@code{next-line} or @code{forward-word}. A command also has a
@dfn{function definition} which is a Lisp program; this is how the
command does its work. In Emacs Lisp, a command is a Lisp function
with special properties that make it suitable for interactive use.
For more information on commands and functions, see @ref{What Is a
Function,, What Is a Function, elisp, The Emacs Lisp Reference
Manual}.
The bindings between keys and commands are recorded in tables called
@dfn{keymaps}. @xref{Keymaps}.
When we say that ``@kbd{C-n} moves down vertically one line'' we are
glossing over a subtle distinction that is irrelevant in ordinary use,
but vital for Emacs customization. The command @code{next-line} does
a vertical move downward. @kbd{C-n} has this effect @emph{because} it
is bound to @code{next-line}. If you rebind @kbd{C-n} to the command
@code{forward-word}, @kbd{C-n} will move forward one word instead.
In this manual, we will often speak of keys like @kbd{C-n} as
commands, even though strictly speaking the key is bound to a command.
Usually we state the name of the command which really does the work in
parentheses after mentioning the key that runs it. For example, we
will say that ``The command @kbd{C-n} (@code{next-line}) moves point
vertically down,'' meaning that the command @code{next-line} moves
vertically down, and the key @kbd{C-n} is normally bound to it.
Since we are discussing customization, we should tell you about
@dfn{variables}. Often the description of a command will say, ``To
change this, set the variable @code{mumble-foo}.'' A variable is a
name used to store a value. Most of the variables documented in this
manual are meant for customization: some command or other part of
Emacs examines the variable and behaves differently according to the
value that you set. You can ignore the information about variables
until you are interested in customizing them. Then read the basic
information on variables (@pxref{Variables}) and the information about
specific variables will make sense.
@ifnottex
@lowersections
@end ifnottex
@ignore
arch-tag: 9be43eef-d1f4-4d03-a916-c741ea713a45
@end ignore |
<link rel="import" href="../polymer/polymer.html"/>
<link rel="import" href="px-vis-behavior-common.html" />
<link rel="import" href="px-vis-behavior-d3.html" />
<link rel="import" href="px-vis-svg.html" />
<link rel="import" href="px-vis-canvas.html" />
<!--
Element which creates an Canvas element and context
##### Usage
<px-vis-svg-canvas
svg="{{svg}}"
px-svg-elem="{{pxSvgElem}}"
canvas="{{canvas}}"
width="[[width]]"
height="[[height]]"
margin="[[margin]]">
</px-vis-svg-canvas>
@element px-vis-svg
@blurb Element which creates an SVG element and sets up d3
@homepage index.html
@demo demo.html
-->
<link rel="import" href="css/px-vis-svg-canvas-styles.html">
<dom-module id="px-vis-svg-canvas">
<template>
<style include="px-vis-svg-canvas-styles"></style>
<div
class="rel-container"
style$="height:[[height]]px">
<px-vis-canvas
class="abs-elem inline--flex"
on-px-vis-canvas-context-updated="_refireEvent"
canvas-context="{{canvasContext}}"
width="[[width]]"
height="[[height]]"
margin="[[margin]]"
offset="[[offset]]">
</px-vis-canvas>
<px-vis-svg
class="abs-elem inline--flex"
on-px-vis-svg-updated="_refireEvent"
on-px-vis-svg-element-updated="_refireEvent"
svg="{{svg}}"
px-svg-elem="{{pxSvgElem}}"
width="[[width]]"
height="[[height]]"
margin="[[margin]]"
offset="[[offset]]">
</px-vis-svg>
</div>
</template>
</dom-module>
<script>
Polymer({
is: 'px-vis-svg-canvas',
behaviors: [
PxVisBehavior.sizing,
PxVisBehaviorD3.canvas,
PxVisBehaviorD3.svg
],
/**
* Properties block, expose attribute values to the DOM via 'reflect'
*
* @property properties
* @type Object
*/
properties: {},
/**
* Refires the caught events for precipitation pattern. We must refire because canvas and svg are "local" properties and thus the depth of their origin matters.
*
*/
_refireEvent: function(evt) {
evt.stopPropagation();
this.fire(evt.type,{ 'data': evt.detail.data, 'dataVar': evt.detail.dataVar, 'method': evt.detail.method });
}
});
</script> |
/**
* include structuredClone in test environment.
* @jest-environment ../../../../shared/test.environment.ts
*/
import { of, firstValueFrom } from "rxjs";
import { awaitAsync, trackEmissions } from "../../spec";
import { distinctIfShallowMatch, reduceCollection } from "./rx";
describe("reduceCollection", () => {
it.each([[null], [undefined], [[]]])(
"should return the default value when the collection is %p",
async (value: number[]) => {
const reduce = (acc: number, value: number) => acc + value;
const source$ = of(value);
const result$ = source$.pipe(reduceCollection(reduce, 100));
const result = await firstValueFrom(result$);
expect(result).toEqual(100);
},
);
it("should reduce the collection to a single value", async () => {
const reduce = (acc: number, value: number) => acc + value;
const source$ = of([1, 2, 3]);
const result$ = source$.pipe(reduceCollection(reduce, 0));
const result = await firstValueFrom(result$);
expect(result).toEqual(6);
});
});
describe("distinctIfShallowMatch", () => {
it("emits a single value", async () => {
const source$ = of({ foo: true });
const pipe$ = source$.pipe(distinctIfShallowMatch());
const result = trackEmissions(pipe$);
await awaitAsync();
expect(result).toEqual([{ foo: true }]);
});
it("emits different values", async () => {
const source$ = of({ foo: true }, { foo: false });
const pipe$ = source$.pipe(distinctIfShallowMatch());
const result = trackEmissions(pipe$);
await awaitAsync();
expect(result).toEqual([{ foo: true }, { foo: false }]);
});
it("emits new keys", async () => {
const source$ = of({ foo: true }, { foo: true, bar: true });
const pipe$ = source$.pipe(distinctIfShallowMatch());
const result = trackEmissions(pipe$);
await awaitAsync();
expect(result).toEqual([{ foo: true }, { foo: true, bar: true }]);
});
it("suppresses identical values", async () => {
const source$ = of({ foo: true }, { foo: true });
const pipe$ = source$.pipe(distinctIfShallowMatch());
const result = trackEmissions(pipe$);
await awaitAsync();
expect(result).toEqual([{ foo: true }]);
});
it("suppresses removed keys", async () => {
const source$ = of({ foo: true, bar: true }, { foo: true });
const pipe$ = source$.pipe(distinctIfShallowMatch());
const result = trackEmissions(pipe$);
await awaitAsync();
expect(result).toEqual([{ foo: true, bar: true }]);
});
}); |
// Flight booking fullname function
// When a user books a flight they write their firstname and surname, but when the ticket is printed a fullname should be displayed.
// Created a function which generate a full name from firstName, surname and useFor
function getFullName(firstName, surname, useFormalName, isMale) {
const fullName = `${firstName} ${surname}`;
// First statement is checking whether given parameters are strings or not and being sure they are not empty
if (
typeof firstName === "string" && //check parameter type
typeof surname === "string" && //checks parameter type
surname.trim().length && //removing all the spaces to check if its empty string or not
firstName.trim().length //removing all the spaces to check if its empty string or not
) {
// Second statement is checking if useFormalName parameter is true or false for giving the lord title
if (useFormalName) {
// Third statement is checking whether man or woman
if (isMale) {
return `Lord ${fullName}`;
} else {
return `Lady ${fullName}`;
}
} else {
return fullName;
}
}
// If type of firstName and surname parameters are not string or empty strings then returning the error message
else {
return "Wrong parameter type";
}
}
// 4 variables calling the functions has been created to check all the scenarios
const fullname1 = getFullName("Morgan", "Freeman", true, true);
const fullname2 = getFullName("Megan", "Fox", true, false);
const fullname3 = getFullName("Rihanna", true, false);
const fullname4 = getFullName("Clint", 4, true, false);
// Loging out the variables
console.log(fullname1); // Output will be : Lord Morgan Freeman
console.log(fullname2); // Output will be : Lady Megan Fox
console.log(fullname3); // Output will be : Wrong parameter type because surname string is empty
console.log(fullname4); // Output will be : Wrong parameter type because surname is not a string |
# https://www.baeldung.com/java-liskov-substitution-principle
from abc import abstractmethod
"""
Current proposed design.
BankingAppWithdrawalService
|
|
|
Account
/ | \
/ | \
/ | \
/ | \
/ | \
/ | \
/ | \
/ | \
SavingsAccount LongTermAccount CurrentAccount
"""
# Case:1- Violates
class Account:
total_amount = 10000
@abstractmethod
def deposit(self, amount):
pass
@abstractmethod
def withdrawal(self, amount):
pass
class BankingAppWithdrawalService:
def __init__(self, account):
self.account = account
def transaction(self):
pin = int(input('Please enter your pin: '))
if pin == 1234:
print('Transaction started...')
choice = input("Enter your choice: ")
if choice == "deposit":
amount = int(input("Please amount to deposit: "))
self.account.deposit(amount)
elif choice == "withdrawal":
amount = int(input("Please amount to withdrawal: "))
self.account.withdrawal(amount)
else:
raise Exception("Invalid selection")
class CurrentAccount(Account):
def deposit(self, amount):
print(f'Deposit to current account: {amount}')
self.total_amount += amount
return self.total_amount
def withdrawal(self, amount):
print(f'Withdrawal to current account: {amount}')
if self.total_amount <= 5000 or self.total_amount < amount:
return f"Can't withdraw amount: {amount}. Insufficient balance"
self.total_amount -= amount
return self.total_amount
class SavingAccount(Account):
def deposit(self, amount):
print(f'Deposit to saving account: {amount}')
self.total_amount += amount
return self.total_amount
def withdrawal(self, amount):
print(f'Deposit to saving account: {amount}')
if self.total_amount <= 0 or self.total_amount < amount:
return f"Can't withdraw amount: {amount}. Insufficient balance"
self.total_amount -= amount
return self.total_amount
class LongTermAccount(Account):
def deposit(self, amount):
print(f'Deposit to saving account: {amount}')
self.total_amount += amount
return self.total_amount
def withdrawal(self, amount):
raise Exception("Withdrawal is not allowed")
server = BankingAppWithdrawalService(SavingAccount())
server1 = BankingAppWithdrawalService(CurrentAccount())
server.transaction()
# Problem
server2 = BankingAppWithdrawalService(LongTermAccount())
"""
Problem starts here because, in the base class we had two functions and it was assumed that Any class extending Account
class with have at least withdrawal and deposit functionality. But with LongTermAccount class we don't want withdrawal
functionality. Since according to LSP, If base class is replaced by any child class, there should not be any effect on
users, but here once we replace Account class with LongTermAccount class, we get an exception while calling withdrawal
function.
Hence, LongTermAccount class should not be member of Account class.
Technically we should have two two types of class inheriting Account class (1. with withdrawal, 2. without withdrawal
functionality). In Account class, now we will have only deposit function.
BankingAppWithdrawalService
|
|
|
Account
/ \
/ \
/ \
/ \
/ \
/ \
/ \
/ \
WithoutWithdrawalAccount WithWithdrawalAccount
/ \ /
/ \ /
/ \ /
SavingsAccount CurrentAccount LongTermAccount
See part2-follow for LSP follow code.
""" |
import { z } from 'zod';
import { getServerSession } from 'next-auth';
import { authOptions } from '@/lib/auth/auth';
import {
addUserToFriendsList,
checkIfUserHasAFriendRequest,
checkIfUserIsFriend,
getUserById,
removeUserFriendRequest,
} from '@/lib/redis/api';
import { addFriendTrigger } from '@/lib/pusher/addFriend';
import { UserScheme } from '@/lib/redis/models/model-guards';
import { removeFriendRequestTrigger } from '@/lib/pusher/removeSendRequest';
export async function POST(req: Request) {
try {
const body = await req.json();
const { id: userIdToAdd } = z.object({ id: z.string() }).parse(body);
const session = await getServerSession(authOptions);
if (!session) {
return new Response('Unauthorized', { status: 401 });
}
// verify both users are not already friends
const isAlreadyFriend = await checkIfUserIsFriend(userIdToAdd, session.user.id);
if (isAlreadyFriend) {
// if users are already friends but request is still exists, remove it.
await removeUserFriendRequest(session.user.id, userIdToAdd);
const friend = await getUserById(userIdToAdd);
const parsedFriend = UserScheme.parse(friend);
await addFriendTrigger(session.user.id, parsedFriend);
return new Response('OK');
}
// check if user has already added
const hasFriendRequest = await checkIfUserHasAFriendRequest(session.user.id, userIdToAdd);
if (!hasFriendRequest) {
return new Response('No friend request found', { status: 400 });
}
const [user, friend] = await Promise.all([getUserById(session.user.id), getUserById(userIdToAdd)]);
const parsedUser = UserScheme.parse(user);
const parsedFriend = UserScheme.parse(friend);
await Promise.all([
addUserToFriendsList(session.user.id, userIdToAdd),
addUserToFriendsList(userIdToAdd, session.user.id),
removeUserFriendRequest(session.user.id, userIdToAdd),
addFriendTrigger(userIdToAdd, parsedUser),
addFriendTrigger(session.user.id, parsedFriend),
]);
const hasFriendMyFriendRequest = await checkIfUserHasAFriendRequest(userIdToAdd, session.user.id);
if (hasFriendMyFriendRequest) {
await Promise.all([
removeUserFriendRequest(userIdToAdd, session.user.id),
removeFriendRequestTrigger(userIdToAdd, session.user.id),
]);
}
return new Response('OK');
} catch (error) {
if (error instanceof z.ZodError) {
return new Response('Invalid request payload', { status: 422 });
}
if (error instanceof Error) {
return new Response(error.message, { status: 500 });
}
return new Response('Internal Server Error', { status: 500 });
}
} |
package com.wmx.service.impl;
import com.wmx.entity.TV;
import com.wmx.repository.TVRepository;
import com.wmx.service.TVService;
import com.wmx.service.TVServiceExt;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import javax.transaction.Transactional;
import java.util.List;
@Service
public class TVServiceImpl implements TVService {
@Resource
private TVRepository tvRepository;
@Resource
private TVServiceExt tvServiceExt;
@Override
public List<TV> findAll() {
//查询所有数据,并以主键 tvId 倒序排序
return tvRepository.findAll(Sort.by(Sort.Direction.DESC, "tvId"));
}
//org.springframework.transaction.annotation.Transactional:事务管理
//@Transactional 添加到哪个方法上,哪个方法就会进行事务管理.默认传播特性为REQUIRED
@Override
@Transactional
public void save(TV tv) {
tvServiceExt.deleteByIdExt(10);//调用其它类中的方法
//故意制造一个数组下标越界异常,典型的运行时异常
System.out.println("123".split(",")[1]);
tv.setTvName(tv.getTvName() + "_xxx");
tvRepository.save(tv);
}
@Override
public void deleteById(int id) {
tvRepository.deleteById(id);
}
} |
import {Row, Space} from 'antd';
import React, {useEffect} from 'react';
import ScrollContainer from 'react-indiana-drag-scroll'
import CardItem from './CardItem';
import '../index.css'
import * as Constant from "@/utils/constant";
const ListCard = ( { data, onChange}) => {
const handleActive = (id) => {
onChange(id);
}
const refs = data.reduce((acc, value) => {
acc[value.date] = React.createRef();
return acc;
}, {});
// Scroll Into View API: https://developer.mozilla.org/en-US/docs/Web/API/Element/scrollIntoView
useEffect(() => {
console.log(refs, "parent");
let length = data.length;
let isHappening = false;
if (!refs || !length) return;
// di chuyển xuống cuối
refs[data[length-1].date].current.scrollIntoView({
block: 'nearest',
});
data.map((item, index) => {
// scroll đang diễn ra
// TH ko có tour đang diễn ra check scroll đến tour sắp diễn ra
if(item.statusTour === Constant.STATUS_TOUR_HAPPENING || (item.statusTour === Constant.STATUS_TOUR_UPCOMING && !isHappening)) {
//if (index === 8) { //example for test
isHappening = true;
refs[item.date].current.scrollIntoView({
behavior: 'smooth',
block: 'nearest',
});
return "";
}
});
// nếu không có tour đang diễn ra thì scroll về band dầu
if (!isHappening) {
refs[data[0].date].current.scrollIntoView({
block: 'nearest',
});
}
}, [data])
return (
<>
<Row style={{ backgroundColor:'rgb(240, 242, 245)', marginRight: '-24px', marginLeft: '-24px', display: 'block'}}>
<div className="space-align-block fixed" style={{float: 'left'}}>
<Space direction="vertical" >
<div className="box-card">
<Space align="end" className="box-time" style={{ backgroundColor:"rgb(186, 195, 207)"}}>
<h4 className="text-time">Sáng</h4>
</Space>
</div>
<div className="box-card">
<Space align="end" className="box-time" style={{ backgroundColor:"rgb(149, 158, 171)"}}>
<h4 className="text-time">Chiều</h4>
</Space>
</div>
<div className="box-card">
<Space align="end" className="box-time" style={{ backgroundColor:"rgb(78, 90, 107)"}}>
<h4 className="text-time">Tối</h4>
</Space>
</div>
<Space align="center" className="box-time-none">
<div></div>
</Space>
</Space>
</div>
<ScrollContainer
horizontal={true}
hideScrollbars={true}
className="scroll-container"
>
<div className="space-align-container" >
{data.map((item, index) => {
return (
<CardItem
dataTour={item.locationOfTheTourWeatherInfoDtos}
date={item.date}
statusTour={item.statusTour}
key={index}
handleActive1={handleActive}
forwardRef={refs[item.date]}
/>
)
})}
</div>
</ScrollContainer>
</Row>
</>
);
};
export default ListCard; |
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>My Three.js Portfolio</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" type="text/css" href="style.css" />
</head>
<body>
<header>
<h1>Marlon Mountjoy</h1>
<nav>
<a href="index.html">Home</a>
<a href="projects.html">Projects</a>
<a href="contact.html">Contact</a>
<a href="mystery.html" class="active">Mystery</a>
</nav>
</header>
<div id="canvas-container"></div>
<!-- Include the Three.js library -->
<script src="https://cdn.jsdelivr.net/npm/[email protected]/build/three.min.js"></script>
<script>
// Define the scene, camera, and renderer
var scene = new THREE.Scene();
var camera = new THREE.PerspectiveCamera(75, window.innerWidth / window.innerHeight, 0.1, 1000);
camera.position.z = 12;
camera.position.x = 0;
camera.position.y = 1;
var renderer = new THREE.WebGLRenderer();
renderer.setSize(window.innerWidth, window.innerHeight);
// Add the renderer to the page
document.getElementById("canvas-container").appendChild(renderer.domElement);
// Create a cube with a texture
// Create the cube
const geometry = new THREE.BoxGeometry(4, 4, 4);
const materials = [
new THREE.MeshStandardMaterial({ map: new THREE.TextureLoader().load('images/resumePic1.png') }), // Front
new THREE.MeshStandardMaterial({ map: new THREE.TextureLoader().load('images/resumePic3.png') }), // Back
new THREE.MeshStandardMaterial({ map: new THREE.TextureLoader().load('images/resumePic2.png') }), // Top
new THREE.MeshStandardMaterial({ map: new THREE.TextureLoader().load('images/resumePic4.png') }), // Bottom
new THREE.MeshStandardMaterial({ map: new THREE.TextureLoader().load('images/indexHTMLpic.jpg') }), // Right
new THREE.MeshStandardMaterial({ map: new THREE.TextureLoader().load('images/indexHTMLpic.jpg') }) // Left
];
const cube = new THREE.Mesh(geometry, materials);
scene.add(cube);
// Add the cube to the scene
scene.add(cube);
// Create ambient light
var ambientLight = new THREE.AmbientLight(0xffffff, 0.5);
scene.add(ambientLight);
// Create directional light and add it to the scene
var directionalLight = new THREE.DirectionalLight(0xffffff, 1);
directionalLight.position.set(1, 1, 1).normalize();
scene.add(directionalLight);
// Add a shadow to the cube
renderer.shadowMap.enabled = true;
renderer.shadowMap.type = THREE.PCFSoftShadowMap;
cube.castShadow = true;
directionalLight.castShadow = true;
directionalLight.shadow.mapSize.width = 512;
directionalLight.shadow.mapSize.height = 512;
directionalLight.shadow.camera.near = 0.5;
directionalLight.shadow.camera.far = 500;
// Set the background color of the scene to gray
scene.background = new THREE.Color(0x07a07a);
// Animate the cube
function animate() {
requestAnimationFrame(animate);
cube.rotation.x += 0;
cube.rotation.y += 0;
renderer.render(scene, camera);
}
animate();
var zoomSpeed = 0.01; // The speed of the zoom
var minZoom = 5; // The minimum distance the camera can be from the cube
var maxZoom = 15; // The maximum distance the camera can be from the cube
// Add event listeners for mouse wheel scroll
document.addEventListener('wheel', function (event) {
event.preventDefault(); // Prevent the page from scrolling
var delta = event.deltaY * zoomSpeed;
camera.position.z += delta; // Zoom in or out based on mouse wheel scroll
if (camera.position.z < minZoom) {
camera.position.z = minZoom; // Limit the minimum distance the camera can be from the cube
} else if (camera.position.z > maxZoom) {
camera.position.z = maxZoom; // Limit the maximum distance the camera can be from the cube
}
}, { passive: false });
var mouse = new THREE.Vector2();
var raycaster = new THREE.Raycaster();
var intersectedObject, selectedObject;
var isMouseDown = false;
// Add event listeners for mouse down, move, and up events
document.addEventListener('mousedown', onMouseDown, false);
document.addEventListener('mousemove', onMouseMove, false);
document.addEventListener('mouseup', onMouseUp, false);
var dragSensitivity = 0.01; // Adjust this value to control the sensitivity of rotation while dragging
function onMouseDown(event) {
isMouseDown = true;
mouse.x = (event.clientX / window.innerWidth) * 2 - 1;
mouse.y = -(event.clientY / window.innerHeight) * 2 + 1;
raycaster.setFromCamera(mouse, camera);
var intersects = raycaster.intersectObjects(scene.children);
if (intersects.length > 0) {
intersectedObject = intersects[0].object;
selectedObject = intersectedObject;
}
}
function onMouseMove(event) {
if (isMouseDown && selectedObject) {
// Calculate the change in mouse position
var deltaX = event.movementX * dragSensitivity;
var deltaY = event.movementY * dragSensitivity;
// Rotate the cube around the x and y axes
selectedObject.rotation.y += deltaX;
selectedObject.rotation.x -= deltaY;
// Limit the rotation of the cube to prevent it from flipping upside down
selectedObject.rotation.x = Math.max(Math.min(selectedObject.rotation.x, Math.PI / 2), -Math.PI / 2);
}
}
function onMouseUp(event) {
isMouseDown = false;
intersectedObject = null;
selectedObject = null;
}
document.addEventListener('touchmove', function (event) {
if (event.scale !== 1) {
event.preventDefault();
}
}, { passive: false });
// Handle window resize events
window.addEventListener('resize', function() {
var width = window.innerWidth;
var height = window.innerHeight;
renderer.setSize(width, height);
camera.aspect = width / height;
camera.updateProjectionMatrix();
});
</script>
<div class="audio">
<audio controls autoplay loop src="audio/Scandinavianz - Hope (mp3).mp3"></audio>
</div>
</body>
</html> |
.\" Copyright (c) 1999
.\" Nick Hibma <[email protected]>. All rights reserved.
.\"
.\" Redistribution and use in source and binary forms, with or without
.\" modification, are permitted provided that the following conditions
.\" are met:
.\" 1. Redistributions of source code must retain the above copyright
.\" notice, this list of conditions and the following disclaimer.
.\" 2. Redistributions in binary form must reproduce the above copyright
.\" notice, this list of conditions and the following disclaimer in the
.\" documentation and/or other materials provided with the distribution.
.\"
.\" THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
.\" ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
.\" IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
.\" ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
.\" FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
.\" DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
.\" OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
.\" HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
.\" LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
.\" OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
.\" SUCH DAMAGE.
.\"
.\" $FreeBSD$
.\"
.Dd January 27, 2020
.Dt UMASS 4
.Os
.Sh NAME
.Nm umass
.Nd USB Mass Storage Devices driver
.Sh SYNOPSIS
To compile this driver into the kernel,
place the following line in your
kernel configuration file:
.Bd -ragged -offset indent
.Cd "device scbus"
.Cd "device usb"
.Cd "device umass"
.Ed
.Pp
Alternatively, to load the driver as a
module at boot time, place the following line in
.Xr loader.conf 5 :
.Bd -literal -offset indent
umass_load="YES"
.Ed
.Sh DESCRIPTION
The
.Nm
driver provides support for Mass Storage devices that attach to the USB
port.
.Pp
To use the
.Nm
driver,
.Xr usb 4
and one of
.Xr uhci 4
or
.Xr ohci 4
or
.Xr ehci 4
or
.Xr xhci 4
must be configured in the kernel.
Additionally, since
.Nm
uses the SCSI subsystem and sometimes acts as a SCSI device, it
requires
.Xr da 4
and
.Xr scbus 4
to be included in the kernel.
.Sh EXAMPLES
.Bd -literal -offset indent
device umass
device scbus
device da
device pass
.Ed
.Pp
Add the
.Nm
driver to the kernel.
.Pp
.Bd -literal -offset indent
camcontrol rescan 0:0:0
camcontrol rescan 0:0:1
camcontrol rescan 0:0:2
camcontrol rescan 0:0:3
.Ed
.Pp
Rescan all slots on a multi-slot flash reader, where the slots map to separate
LUNs on a single SCSI ID.
Typically only the first slot will be enabled at boot time.
This assumes that the flash reader is the first SCSI bus in the system and has 4 slots.
.Sh SEE ALSO
.Xr cfumass 4 ,
.Xr ehci 4 ,
.Xr ohci 4 ,
.Xr uhci 4 ,
.Xr usb 4 ,
.Xr xhci 4 ,
.Xr camcontrol 8
.\".Sh HISTORY
.Sh AUTHORS
.An -nosplit
The
.Nm
driver was written by
.An MAEKAWA Masahide Aq Mt [email protected]
and
.An Nick Hibma Aq Mt [email protected] .
.Pp
This manual page was written by
.An Nick Hibma Aq Mt [email protected] . |
<html>
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Contactanos | Maximiliano Ramos Zwenger</title>
<link rel="shortcut icon" href="favicon.png">
<link rel="stylesheet" href="css/estilos.css">
<link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-9ndCyUaIbzAi2FUVXJi0CjmCapSmO7SnpJef0486qhLnuZ2cdeRhO02iuK6FUUVM" crossorigin="anonymous">
<!-- Optimización SEO del Sitio Web -->
<meta name="description" content="Plantilla Personalizable de Sitio Web Responsive">
<meta name="keywords" content="Web, Responsive, Adaptble, Pagina Web, Web Personalizable, Custom Web, Responsive Web, Formulario de Contacto, Contact Form">
<meta property="og:type" content="Desarrollo Web">
<meta property="og:title" content="Formulario de Contacto de la Plantilla de Sitio Web Responsivo">
<meta property="og:description" content="Formulario de contacto personalizable del Sitio Web Responsive ideal para ofrecer servicios profesionales">
<meta property="og:image" content="https://raw.githubusercontent.com/mramoszwenger/PreEntrega3-RamosZwengerMaximiliano/sass-compiled-v3.1-preEntrega3%5DRamosZwengerMaximiliano/img/isotipoEmpresa.png>
<meta property="og:url" content="https://mramoszwenger.github.io/PreEntrega3-RamosZwengerMaximiliano">
</head>
<body>
<!-- Barra de navegacion -->
<header>
<nav class="navbar navbar-expand-lg navbar-light bg-light" id="principal-nav">
<!-- Logo institucional/corporativo -->
<div class="container-fluid">
<a class="animate__animated animate__bouncein navbar-brand" href="index.html">
<img src="img/logotipoEmpresa.png" alt="logo-empresa" class="company__logo">
</a>
<!-- Boton menu hamburgesa -->
<button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#mainNav">
<span class="navbar-toggler-icon"></span>
</button>
<!-- Elementos del menu -->
<div class="collapse navbar-collapse" id="mainNav">
<ul class="navbar-nav ms-auto">
<li class="nav-item">
<a class="nav-link active" href="index.html">Inicio</a>
</li>
<li class="nav-item">
<a class="nav-link" href="index.html#nosotros">Nosotros</a>
</li>
<li class="nav-item dropdown">
<a class="nav-link dropdown-toggle" href="#" id="navbarDropdown" role="button" data-bs-toggle="dropdown" >Servicios</a>
<ul class="dropdown-menu text-center">
<li>
<a class="dropdown-item" href="index.html#servicios">Servicio Uno</a>
</li>
<li>
<a class="dropdown-item" href="index.html#servicios">Servicio Dos</a>
</li>
<li>
<a class="dropdown-item" href="index.html#servicios">Servicio Tres</a>
</li>
</ul>
</li>
<li class="nav-item">
<a class="nav-link" href="contacto.html">Contacto</a>
</li>
</ul>
</div>
</div>
</nav>
</header>
<!-- Seccion contacto -->
<a name="contacto"></a>
<section class="container-fluid contact">
<div class="contact__head row">
<h2 class="contact__title">Contactanos</h2>
<div>
<p class="contact__description">Dejanos tus datos y en breve alguien de nuestro equipo se pondrá en contacto contigo.</p>
</div>
</div>
<div class="contact__background">
<form class="contact__form">
<div class="mb-3">
<input type="text" class="form-control" id="nombre-apellido" placeholder="Su nombre y apellido">
</div>
<div class="mb-3">
<input type="email" class="form-control" id="correo-electronico" placeholder="Su correo electrónico">
</div>
<div class="mb-3">
<input type="email" class="form-control" id="asunto" placeholder="Asunto del contacto">
</div>
<div class="mb-3">
<textarea class="form-control" id="mensaje" placeholder="Su mensaje..." rows="10"></textarea>
</div>
<div class="d-grid gap-2 text-center">
<button class="btn" id="contact__button" type="submit">Enviar mensaje</button>
</div>
</form>
</div>
</section>
<!-- Pie de pagina -->
<footer class="footer">
<h5 class="footer__description">©2023. Desarrollado por <a class="footer__link" href="#">Maximiliano Ramos Zwenger</a></h5>
</footer>
<!-- Bootstrap js -->
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.bundle.min.js" integrity="sha384-geWF76RCwLtnZ8qwWowPQNguL3RmwHVBC9FhGdlKrxdiJJigb/j/68SIy3Te4Bkz" crossorigin="anonymous"></script>
</body>
</html> |
import {
GlobeAltIcon,
InformationCircleIcon,
PencilSquareIcon,
} from '@heroicons/react/24/outline'
import { Link } from '@remix-run/react'
import clsx from 'clsx'
import { useMemo, useState } from 'react'
import { Collapse, Link as DaisyLink } from 'react-daisyui'
import { ClubStats } from '~/api/clubs'
import { CollectionDetail, CollectionStats } from '~/api/collection'
import useAddress from '~/hooks/useAddress'
import { usesAsteroidSocialLinks } from '~/utils/collection'
import { CollapseTextContent, CollapseTextTrigger } from './CollapseText'
import CollectionStatsComponent from './CollectionStats'
import InscriptionImage from './InscriptionImage'
import { NotAffiliatedWarning } from './alerts/NotAffiliatedAlert'
import Discord from './icons/discord'
import Telegram from './icons/telegram'
import Twitter from './icons/twitter'
export default function CollectionDetailComponent({
collection,
stats,
}: {
collection: CollectionDetail
stats: CollectionStats | ClubStats | undefined
}) {
const address = useAddress()
const { metadata, creator } = collection
const hasSocials =
metadata.twitter ||
metadata.telegram ||
metadata.discord ||
metadata.website
const notAffiliatedWarning = useMemo(() => {
return usesAsteroidSocialLinks(metadata)
}, [metadata])
const [open, setOpen] = useState(false)
return (
<div className="flex flex-col p-5 pb-6 border-b border-b-neutral">
<div className="flex items-center flex-col xl:flex-row">
<InscriptionImage
src={collection.content_path!}
isExplicit={collection.is_explicit}
className="size-20 shrink-0"
imageClassName="rounded-full"
/>
<div
className={clsx(
'flex flex-col xl:ml-4 mt-2 xl:mt-1 h-full items-center xl:items-start',
{
'justify-center': !hasSocials,
},
)}
>
<h2 className="text-xl flex items-center">
{collection.name}
{collection.metadata.description && (
<DaisyLink
onClick={() => setOpen(!open)}
color="ghost"
className="lg:hidden ml-2"
>
<InformationCircleIcon className="size-5" />
</DaisyLink>
)}
</h2>
{collection.metadata.description && (
<div className="hidden lg:flex">
<CollapseTextTrigger
onToggle={() => setOpen(!open)}
title={collection.metadata.description}
/>
</div>
)}
<div className="flex items-start justify-center xl:justify-start mt-3 gap-2">
{metadata.website && (
<DaisyLink
href={metadata.website}
title={`${collection.name} website`}
target="_blank"
>
<GlobeAltIcon className="size-5" />
</DaisyLink>
)}
{metadata.twitter && (
<DaisyLink
href={metadata.twitter}
title={`${collection.name} on X`}
target="_blank"
>
<Twitter className="size-5" />
</DaisyLink>
)}
{metadata.telegram && (
<DaisyLink
href={metadata.telegram}
title={`${collection.name} on Telegram`}
target="_blank"
>
<Telegram className="size-5" />
</DaisyLink>
)}
{metadata.discord && (
<DaisyLink
href={metadata.discord}
title={`${collection.name} on Discord`}
target="_blank"
>
<Discord className="size-5" />
</DaisyLink>
)}
{creator === address && (
<Link
to={`/app/edit/collection/${collection.symbol}`}
title="Edit collection"
>
<PencilSquareIcon className="size-5" />
</Link>
)}
</div>
</div>
{stats && (
<CollectionStatsComponent
className="mx-8"
stats={stats}
royaltyPercentage={collection.royalty_percentage}
/>
)}
</div>
{notAffiliatedWarning && <NotAffiliatedWarning className="mt-4" />}
<Collapse open={open} className="rounded-none">
<CollapseTextContent>
{collection.metadata.description}
</CollapseTextContent>
</Collapse>
</div>
)
} |
import {
html,
TemplateResult,
customElement,
state,
property,
LitElement,
} from 'lit-element';
import {retrieveSupabase} from '../luna-orbit';
import {WebsiteSettingsDB} from '../parts/dashboard/settings';
import {loader} from '../parts/dashboard/home';
/**
* Website footer
*/
@customElement('website-footer')
export class WebsiteFooter extends LitElement {
@state()
private _twitter: WebsiteSettingsDB | undefined;
@state()
private _telegram: WebsiteSettingsDB | undefined;
@state()
private _operatorAddress: WebsiteSettingsDB | undefined;
@state()
private _name: WebsiteSettingsDB | undefined;
@property({type: String})
public commission = 'Loading...';
public createRenderRoot(): this {
return this;
}
public async firstUpdated(): Promise<void> {
const supabase = retrieveSupabase();
const settingsData = (await supabase.from<WebsiteSettingsDB>('settings'))
.data;
if (settingsData) {
this._twitter = settingsData.find(
(setting) => setting.name === 'twitter'
);
this._telegram = settingsData.find(
(setting) => setting.name === 'telegram'
);
this._operatorAddress = settingsData.find(
(setting) => setting.name === 'operator-address'
);
this._name = settingsData.find((setting) => setting.name === 'name');
}
}
render(): TemplateResult {
return html`
${this._twitter && this._telegram && this._operatorAddress && this._name
? html`
<div class="bg-gradient-to-r from-indigo-300 to-blue-500">
<div
class="container px-5 py-8 mx-auto flex items-center sm:flex-row flex-col"
>
<a
class="flex title-font font-medium items-center md:justify-start justify-center text-white"
href="home"
>
<img
slot="branding"
class="block h-8 w-auto pointer-events-none"
src="/assets/logo.svg"
alt="LunaOrbit logo"
width="33"
height="32"
/>
<span class="ml-3 text-xl">${this._name.value}</span>
</a>
<p
class="text-sm text-white sm:ml-4 sm:pl-4 sm:border-l-2 sm:border-gray-200 sm:py-2 sm:mt-0 mt-4"
>
<a
title="Twitter"
href="https://twitter.com/justinlunaorbit"
class="text-white ml-1"
rel="noopener"
target="_blank"
>@${this._twitter.value}</a
>
|
<a
class="text-white ml-1"
target="_blank"
rel="noopener"
href="https://station.terra.money/validator/${this
._operatorAddress.value}"
>Validator commission :
<span id="commission" class="text-white"
>${this.commission}</span
></a
>
|
<a
class="text-white ml-1"
target="_blank"
rel="noopener"
href="https://github.com/terra-project/validator-profiles/tree/master/validators/${this
._operatorAddress.value}"
>Validator profile</a
>
</p>
<span
class="inline-flex sm:ml-auto sm:mt-0 mt-4 justify-center sm:justify-start"
>
<a
class="telegram m-4"
title="telegram"
class="ml-3 text-white"
href="http://t.me/${this._telegram.value.replace('@', '')}"
target="_blank"
rel="noopener"
>
<svg
fill="currentColor"
xmlns:xlink="http://www.w3.org/1999/xlink"
xml:space="preserve"
xmlns:serif="http://www.serif.com/"
class="w-5 h-5"
>
<path
id="telegram-1"
d="M18.384,22.779c0.322,0.228 0.737,0.285 1.107,0.145c0.37,-0.141 0.642,-0.457 0.724,-0.84c0.869,-4.084 2.977,-14.421 3.768,-18.136c0.06,-0.28 -0.04,-0.571 -0.26,-0.758c-0.22,-0.187 -0.525,-0.241 -0.797,-0.14c-4.193,1.552 -17.106,6.397 -22.384,8.35c-0.335,0.124 -0.553,0.446 -0.542,0.799c0.012,0.354 0.25,0.661 0.593,0.764c2.367,0.708 5.474,1.693 5.474,1.693c0,0 1.452,4.385 2.209,6.615c0.095,0.28 0.314,0.5 0.603,0.576c0.288,0.075 0.596,-0.004 0.811,-0.207c1.216,-1.148 3.096,-2.923 3.096,-2.923c0,0 3.572,2.619 5.598,4.062Zm-11.01,-8.677l1.679,5.538l0.373,-3.507c0,0 6.487,-5.851 10.185,-9.186c0.108,-0.098 0.123,-0.262 0.033,-0.377c-0.089,-0.115 -0.253,-0.142 -0.376,-0.064c-4.286,2.737 -11.894,7.596 -11.894,7.596Z"
/>
</svg>
</a>
<a
title="Twitter"
class="ml-3 text-white"
href="https://twitter.com/${this._twitter.value}"
target="_blank"
rel="noopener"
>
<svg
fill="currentColor"
stroke-linecap="round"
stroke-linejoin="round"
stroke-width="2"
class="w-5 h-5"
viewBox="0 0 24 24"
>
<path
d="M23 3a10.9 10.9 0 01-3.14 1.53 4.48 4.48 0 00-7.86 3v1A10.66 10.66 0 013 4s-4 9 5 13a11.64 11.64 0 01-7 2c9 5 20 0 20-11.5a4.5 4.5 0 00-.08-.83A7.72 7.72 0 0023 3z"
></path>
</svg>
</a>
</span>
</div>
</div>
`
: html` ${loader()} `}
`;
}
}
declare global {
interface HTMLElementTagNameMap {
'website-footer': WebsiteFooter;
}
} |
# Задание: Создайте функцию, которая принимает двумерный массив (лабиринт) и начальную и конечную точки.
# Функция должна возвращать путь от начальной до конечной точки или сообщение, что путь невозможен.
# Входные данные:
# Двумерный массив размера MxN, где '0' - это проход, а '1' - это стена.
# Координаты начальной и конечной точки.
def maze_search(labyrinth, start_row = 0, start_column = 0, end_row = 0, end_column = 0):
row = start_row
column = start_column
vector = [0, 1] # Направление движения
trajectory = [[start_row, start_column]] # Путь обхода лабиринта
attempts = 3 # Сколько раз нужно вернуться в исходную точку, чтобы прекратить поиски пути
# тут нужно добавить проверку что исходная точка внутри массива
while attempts and (row != end_row or column != end_column): # Ишем, пока не исчерпаем все попытки
# или не придем в конечную точку
new_row = row + vector[0]
new_column = column + vector[1] # что впереди
left_row = row - vector[1]
left_column = column + vector[0] # что слева
if left_row < 0 or left_column < 0 or left_row > len(labyrinth) - 1 or left_column > len(labyrinth[left_row]) - 1 or labyrinth[left_row][left_column]: # Если слева стена
if new_row < 0 or new_column < 0 or new_row > len(labyrinth) - 1 or new_column > len(labyrinth[new_row]) - 1 or labyrinth[new_row][new_column]: # Если впереди стена
vector[0], vector[1] = vector[1], -vector[0] # поворот вправо
else:
row = new_row
column = new_column # шаг вперед
trajectory.append([row, column]) # добавляем текущую точку траектории
else:
row = left_row
column = left_column
vector[0], vector[1] = -vector[1], vector[0] # шаг влево и поворот налево
trajectory.append([row, column]) # добавляем текущую точку траектории
if row == start_row and column == start_column:
trajectory = [[start_row, start_column]]
attempts -= 1
return trajectory # Если путь не найден возврашается список с единственной начальной координатой
if __name__ == "__main__":
labyrinth = [[0, 1, 0, 1, 0],
[0, 0, 0, 0, 0],
[1, 0, 1, 1, 0],
[1, 1, 0, 0, 0]]
trajectory = maze_search(labyrinth, 0, 0, 3, 3) # Это список координат
print(trajectory)
for coordinate in trajectory:
labyrinth[coordinate[0]][coordinate[1]] = 7 # Визуализация пути по лабиринту
for row in labyrinth:
print(row) |
import org.w3c.dom.css.Rect
fun main() {
val point = Point(10,20)
//Destructure data class
val (x,y) = point
println("$x, $y")
// Destructure an Array
val numbers = intArrayOf(1,2,3)
val(a,b,c) = numbers
println("a: $a, b: $b, c: $c")
// //Destructuring maps
// val person = mapOf("name" to "Venkat", "age" to 90)
//
// val (name, age) = person
//Destructuring function paramers
val rect = Rectangle(30, 30)
val area = calcArea(rect)
println("Area: $area")
}
data class Rectangle(val width: Int, val height: Int)
fun calcArea(rectangle: Rectangle): Int{
//Destructuring
val (width, height) = rectangle;
return width * height
}
data class Point(val x: Int, val y: Int) |
import 'package:shared_preferences/shared_preferences.dart';
import 'package:sqflite/sqflite.dart';
import '../../models/database_helper.dart';
import '../../widgets/Bouton.dart';
import '../../widgets/appbar.dart';
import 'package:flutter/material.dart';
import 'experience_home_page.dart';
class ExperiencePage7 extends StatelessWidget {
const ExperiencePage7({super.key});
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: const AppBar1(),
body: Center(
child: Column(mainAxisAlignment: MainAxisAlignment.center, children: [
const Text(
'Bravo vous avez complété l’expérience !',
textAlign: TextAlign.center,
style: TextStyle(
fontFamily: 'Roboto',
fontWeight: FontWeight.w400,
fontSize: 22,
),
),
const SizedBox(
height: 95,
),
Container(
width: 250,
height: 70,
child: GenericButton(
buttonText: 'Terminer l’expérience ',
onPressed: () async {
DatabaseHelper databaseHelper = DatabaseHelper();
Future<int?> getSavedUserId() async {
SharedPreferences prefs =
await SharedPreferences.getInstance();
return prefs.getInt('userId');
}
int? id = await getSavedUserId();
int? num =
await databaseHelper.getSessionNumeroWithHighestValue(id!);
if (num == null) {
await DatabaseHelper().insertSessionData(1, id);
} else {
await DatabaseHelper().insertSessionData(num + 1, id);
}
await DatabaseHelper().checkAndPrintSessionsTable();
Navigator.push(
context,
MaterialPageRoute(
builder: (context) => const ExperiencePage()),
);
},
buttonTextColor: const Color(0xFF381E72),
),
),
]),
),
);
}
} |
import React from "react";
import { Link } from "react-router-dom";
export interface DropdownItem {
text: string;
path: string;
}
export interface DropdownProps {
options: DropdownItem[];
}
const Dropdown: React.FC<{ props: DropdownProps }> = ({ props }) => {
const options = props.options;
const items = (
<ul>
{options.map((option: { text: string; path: string }) => (
<li className="dropdown-option">
<Link to={option.path}>{option.text}</Link>
</li>
))}
</ul>
);
return <div className="dropdown">{items}</div>;
};
export default Dropdown; |
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
contract DAOMembership {
mapping(address => bool) public whitelist;
address public owner;
constructor() {
owner = msg.sender;
}
function addMember(address _member) public {
require(msg.sender == owner, "Only owner can add members");
whitelist[_member] = true;
}
function removeMember(address _member) public {
require(msg.sender == owner, "Only owner can remove members");
whitelist[_member] = false;
}
function isMember(address _member) public view returns (bool) {
return whitelist[_member];
}
} |
package homeworks.hw19.StreamAPI;
import homeworks.hw19.Product.*;
import homeworks.hw19.Test.AfterSuite;
import homeworks.hw19.Test.BeforeSuite;
import homeworks.hw19.Test.Test;
import java.time.LocalDate;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class StreamApiMethodsTest {
private StreamApiMethods streamApiMethods;
private List<Product> products;
@BeforeSuite
public void setUp(){
System.out.println("Starting tests!\n");
streamApiMethods = new StreamApiMethods();
products = new ArrayList<>();
products.add(new Apple(100, LocalDate.of(2022, 6, 12)));
products.add(new Apple(105, LocalDate.of(2023, 5, 14)));
products.add(new Apple(95, LocalDate.of(2023, 6, 22)));
products.add(new Apple(20, LocalDate.of(2023, 6, 13)));
products.add(new Book(140, LocalDate.of(2022, 2, 26)));
products.add(new Book(400, LocalDate.of(2023, 6, 25)));
products.add(new Book(75, LocalDate.of(2023, 6, 21)));
products.add(new Book(60, LocalDate.of(2023, 4, 5)));
products.add(new Book(50, LocalDate.of(2023, 5, 29)));
products.add(new Book(350, LocalDate.of(2023, 4, 20)));
products.add(new Tea(200, LocalDate.of(2023, 6, 8)));
products.add(new Tea(250, LocalDate.of(2023, 5, 3)));
products.add(new Tea(130, LocalDate.of(2023, 6, 19)));
System.out.println("All products: ");
for (Product product : products) {
System.out.println(product);
}
}
/*@BeforeSuite
public void testErrSecondBeforeSuite(){
System.out.println("Hello, world!");
}*/
@Test(priority = 5)
public void getBooksAbovePrice_test(){
List<Product> expected = Arrays.asList(products.get(4), products.get(5), products.get(9));
List<Product> actual = streamApiMethods.getBooksAbovePrice(products, 100);
for (Product product: actual) {
System.out.println(product);
}
assert actual.equals(expected) : "Method getBooksAbovePrice_test failed!";
System.out.println("Method getBooksAbovePrice_test done!\n");
}
@Test(priority = 1)
public void getProductWithMinPrice_test(){
Book expected = (Book) products.get(8);
Book actual = (Book) streamApiMethods.getProductWithMinPrice(products, ProductType.BOOK);
System.out.println("\nThe book with the min price: \n" + actual);
assert actual.equals(expected) : "Method getProductWithMinPrice_test failed!";
System.out.println("Method getProductWithMinPrice_test done!\n");
}
@Test(priority = 5)
public void getLastThreeAddedProducts_test(){
List<Product> expected = Arrays.asList(products.get(5), products.get(2), products.get(6));
List<Product> actual = streamApiMethods.getLastThreeAddedProducts(products);
System.out.println("\nThe last three added products: ");
for (Product product: actual) {
System.out.println(product);
}
assert actual.equals(expected) : "Method getLastThreeAddedProducts_test failed!";
System.out.println("Method getLastThreeAddedProducts_test done!\n");
}
/*@Test(priority = 10)
public void AssertionError_test(){
Book expected = (Book) products.get(5);
Book actual = (Book) streamApiMethods.getProductWithMinPrice(products, ProductType.BOOK);
System.out.println("\nAssertionError Test: The book with the min price: \n" + actual);
assert actual.equals(expected) : "Method AssertionError_test failed!";
System.out.println("Method AssertionError_test done!\n");
}*/
@AfterSuite
public void tearDown(){
System.out.println("Tests done!");
}
} |
<!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">
<!-- https://fonts.google.com font-family: 'Raleway' and 'Roboto' -->
<link rel="preconnect" href="https://fonts.googleapis.com">
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
<link href="https://fonts.googleapis.com/css2?family=Raleway:wght@800&family=Roboto:wght@400;500;700;900&display=swap" rel="stylesheet">
<!-- /https://fonts.google.com font-family: 'Raleway' and 'Roboto' -->
<!-- Styles -->
<link rel="stylesheet" href="./css/styles.css">
<!-- /Styles -->
<title>Portfolio</title>
</head>
<body>
<!-- Portfolio Page -->
<header class="header">
<nav class="header-menu">
<!-- Logo Site -->
<a class="header-logo" href="./index.html"><span>Web</span>Studio</a>
<!-- /Logo Site -->
<!-- Menu Nav -->
<ul class="header-list">
<li class="header-menu-item list"><a class="header-menu-link link" href="./index.html">Studio</a></li>
<li class="header-menu-item list"><a class="header-menu-link link" href="./portfolio.html">Portfolio</a></li>
<li class="header-menu-item list"><a class="header-menu-link link" href="">Contacts</a></li>
</ul>
<!-- /Menu Nav -->
</nav>
<!-- Contacts -->
<address class="header-address">
<ul class="header-address-list">
<li class="header-address-item list"><a class="header-address-link link"
href="mailto:[email protected]">[email protected]</a></li>
<li class="header-address-item list"><a class="header-address-link link" href="tel:+110001111111">+11 (000)
111-11-11</a></li>
</ul>
</address>
<!-- /Contacts -->
</header>
<main>
<!-- Examples of projects section-->
<section class="portfolio">
<!-- DELETE IN CSS -->
<h1 class="visually-hidden">Portfolio (Examples of projects)</h1>
<!-- /DELETE IN CSS -->
<!-- Portfolio filter buttons-->
<ul class="portfolio-button-list list">
<li><button type="button" class="portfolio-button btn">All</button></li>
<li><button type="button" class="portfolio-button btn">Web Site</button></li>
<li><button type="button" class="portfolio-button btn">App</button></li>
<li><button type="button" class="portfolio-button btn">Design</button></li>
<li><button type="button" class="portfolio-button btn">Marketing</button></li>
</ul>
<!-- /Portfolio filter buttons-->
<!-- Row examples of projects -->
<ul class="portfolio-img-list list">
<li class="portfolio-img-item">
<img src="./images/row-one-foto-one-min.jpg" alt="banking-app-interface-concept-foto" width="360" height="300">
<h2 class="portfolio-subtitle subtitle">Banking App Interface Concept</h2>
<p class="portfolio-description text">App</p>
</li>
<li class="portfolio-img-item">
<img src="./images/row-one-foto-two-min.jpg" alt="marketing-cashless-payment-foto" width="360" height="300">
<h2 class="portfolio-subtitle subtitle">Cashless Payment</h2>
<p class="portfolio-description text">Marketing</p>
</li>
<li class="portfolio-img-item">
<img src="./images/row-one-foto-three-min.jpg" alt="app-meditaion-foto" width="360" height="300">
<h2 class="portfolio-subtitle subtitle">Meditaion App</h2>
<p class="portfolio-description text">App</p>
</li>
<li class="portfolio-img-item">
<img src="./images/row-three-foto-one-min.jpg" alt="design-instagram-stories-concept-design-foto" width="360" height="300">
<h2 class="portfolio-subtitle subtitle">Instagram Stories Concept</h2>
<p class="portfolio-description text">Design</p>
</li>
<li class="portfolio-img-item">
<img src="./images/row-three-foto-two-min.jpg" alt="web-site-organic-food-foto" width="360" height="300">
<h2 class="portfolio-subtitle subtitle">Organic Food</h2>
<p class="portfolio-description text">Web Site</p>
</li>
<li class="portfolio-img-item">
<img src="./images/row-three-foto-three-min.jpg" alt="web-fresh-coffee-site--foto" width="360" height="300">
<h2 class="portfolio-subtitle subtitle">Fresh Coffee</h2>
<p class="portfolio-description text">Web Site</p>
</li>
<li class="portfolio-img-item">
<img src="./images/row-two-foto-one-min.jpg" alt="marketing-taxi-service-foto" width="360" height="300">
<h2 class="portfolio-subtitle subtitle">Taxi Service</h2>
<p class="portfolio-description text">Marketing</p>
</li>
<li class="portfolio-img-item">
<img src="./images/row-two-foto-two-min.jpg" alt="design-screen-illustrations-foto" width="360" height="300">
<h2 class="portfolio-subtitle subtitle">Screen Illustrations</h2>
<p class="portfolio-description text">Design</p>
</li>
<li class="portfolio-img-item">
<img src="./images/row-two-foto-three-min.jpg" alt="marketing-online-courses-foto" width="360" height="300">
<h2 class="portfolio-subtitle subtitle">Online Courses</h2>
<p class="portfolio-description text">Marketing</p>
</li>
</ul>
</section>
<!-- /Row examples of projects-->
<!-- /Examples of projects section-->
</main>
<footer class="footer">
<a class="footer-logo list" href="./index.html"><span>Web</span>Studio</a>
<p class="footer-description text"> Increase the flow of customers and sales for your business with digital marketing &
growth solutions.</p>
</footer>
<!-- Portfolio Page -->
</body>
</html> |
<!--Two way binding-->
<!-- here we use ngModel which is a directive = an instruction you place on an html element-->
<!-- ngModel listens to the user input and emit the data to us and store that data in the text area-->
<!-- ngModel is not included in core angular package so we need to import it-->
<!-- we need to bind it to a property-->
<mat-card>
<mat-spinner *ngIf="isLoading"></mat-spinner>
<form (submit)="onSaveCompany(companyForm)" #companyForm="ngForm" *ngIf="!isLoading">
<mat-form-field>
<input
matInput
type="text"
name="companyName"
[ngModel]="company?.companyName"
required
placeholder="Company Name"
#companyName="ngModel">
<mat-error *ngIf="companyName.invalid">Please enter a the company's name.</mat-error>
</mat-form-field>
<mat-form-field>
<input matInput
type="text"
name="businessType"
[ngModel]="company?.businessType"
required
placeholder="Business Type"
#businessType="ngModel">
<mat-error *ngIf="businessType.invalid">Please enter the type of business.</mat-error>
</mat-form-field>
<mat-form-field>
<input matInput
type="text"
name="principalOfficeLocation"
[ngModel]="company?.principalOfficeLocation"
required
placeholder="Principal Office Location"
#principalOfficeLocation="ngModel">
<mat-error *ngIf="principalOfficeLocation.invalid">Please enter the location of the company's principal office.</mat-error>
</mat-form-field>
<mat-action-row>
<button mat-raised-button
color="primary"
type="submit">Save Company</button>
<button mat-button
color="primary" type="reset">Clear value</button>
</mat-action-row>
</form>
</mat-card> |
package ru.shutov.library.models;
import jakarta.persistence.*;
import jakarta.validation.constraints.Min;
import jakarta.validation.constraints.NotEmpty;
import java.util.Date;
@Entity
@NamedEntityGraph(name = "Book.owner", attributeNodes = @NamedAttributeNode("owner"))
@Table(name = "book")
public class Book {
@Id
@Column(name = "id")
@GeneratedValue(strategy = GenerationType.IDENTITY)
private int id;
@Column(name = "name")
@NotEmpty(message = "Name should not be empty")
private String name;
@Column(name = "year")
@Min(1800)
private int year;
@Column(name = "author")
@NotEmpty(message = "Author should not be empty")
private String author;
@ManyToOne
@JoinColumn(name = "person", referencedColumnName = "id")
private Person owner;
@Column(name = "assigned_at")
@Temporal(TemporalType.TIMESTAMP)
private Date assignedAt;
@Transient
private Boolean expired;
public Book() {}
public Book(int id, String name, String author, int year) {
this.id = id;
this.name = name;
this.year = year;
this.author = author;
}
public Book(int id, String name, String author, int year, Person owner) {
this.id = id;
this.name = name;
this.year = year;
this.author = author;
this.owner = owner;
}
public void setId(int id) {
this.id = id;
}
public void setName(String name) {
this.name = name;
}
public void setYear(int year) {
this.year = year;
}
public int getId() {
return id;
}
public String getName() {
return name;
}
public int getYear() {
return year;
}
public String getAuthor() {
return author;
}
public void setAuthor(String author) {
this.author = author;
}
public Person getOwner() {
return owner;
}
public void setOwner(Person person) {
this.owner = person;
}
public boolean hasPerson() {
return this.owner != null;
}
public Date getAssignedAt() {
return assignedAt;
}
public void setAssignedAt(Date assignedAt) {
this.assignedAt = assignedAt;
}
public Boolean getExpired() {
return expired;
}
public void setExpired(Boolean expired) {
this.expired = expired;
}
} |
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginLeft="4dp"
android:layout_marginRight="16dp"
android:baselineAligned="false"
android:divider="?android:attr/dividerHorizontal"
android:orientation="horizontal"
android:showDividers="middle"
tools:context="com.gamerscave.acrabackend.ErrorListActivity">
<!--
This layout is a two-pane layout for the Errors
master/detail flow.
See res/values-large/refs.xml and
res/values-w900dp/refs.xml for an example of layout aliases
that replace the single-pane version of the layout with
this two-pane version.
For more on layout aliases, see:
http://developer.android.com/training/multiscreen/screensizes.html#TaskUseAliasFilters
-->
<LinearLayout
android:layout_width="@dimen/item_width"
android:orientation="vertical"
android:layout_height="match_parent">
<Button android:layout_height="wrap_content"
android:text="Home"
android:id="@+id/home"
android:background="#FFF"
android:layout_width="match_parent"/>
<android.support.v7.widget.RecyclerView xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/error_list"
android:name="com.gamerscave.acrabackend.ErrorListFragment"
android:layout_width="@dimen/item_width"
android:layout_height="match_parent"
app:layoutManager="LinearLayoutManager"
tools:context="com.gamerscave.acrabackend.ErrorListActivity"
tools:listitem="@layout/error_list_content" />
</LinearLayout>
<FrameLayout
android:id="@+id/error_detail_container"
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="3" />
</LinearLayout> |
package com.celements.tag.controller;
import static java.util.stream.Collectors.*;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.Set;
import javax.annotation.concurrent.Immutable;
import javax.inject.Inject;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.celements.tag.CelTag;
import com.celements.tag.CelTagService;
import com.celements.web.service.IWebUtilsService;
import com.fasterxml.jackson.annotation.JsonInclude;
import one.util.streamex.EntryStream;
import one.util.streamex.StreamEx;
@RestController
@RequestMapping("/v1/celtags")
public class CelTagController {
private final CelTagService tagService;
private final IWebUtilsService webUtils;
@Inject
public CelTagController(
CelTagService tagService,
IWebUtilsService webUtils) {
this.tagService = tagService;
this.webUtils = webUtils;
}
@GetMapping
public Map<String, List<TagDto>> getTags() {
return EntryStream.of(tagService.getTagsByType().entries().stream())
.filterValues(CelTag::isRoot)
.mapValues(TagDto::new)
.grouping();
}
@GetMapping("/types")
public Set<String> getTypes() {
return tagService.getTagsByType().keySet();
}
@GetMapping("/{type}")
public List<TagDto> getTagsByType(
@PathVariable String type) {
return tagService.getTagsByType().get(type).stream()
.filter(CelTag::isRoot)
.sorted(CelTag.CMP_ORDER)
.map(TagDto::new)
.collect(toList());
}
@GetMapping("/{type}/{name}")
public ResponseEntity<TagDto> getTagByName(
@PathVariable String type,
@PathVariable String name) {
return tagService.getTag(type, name)
.map(TagDto::new)
.map(ResponseEntity::ok)
.orElseGet(() -> ResponseEntity.notFound().build());
}
@Immutable
@JsonInclude(JsonInclude.Include.NON_EMPTY)
public class TagDto {
public final String name;
public final int order;
public final Map<String, String> prettyName;
public final List<TagDto> children;
public TagDto(CelTag tag) {
name = tag.getName();
order = tag.getOrder();
prettyName = StreamEx.of(webUtils.getAllowedLanguages())
.mapToEntry(tag::getPrettyName)
.flatMapValues(Optional::stream)
.toImmutableMap();
children = tag.getChildren()
.sorted(CelTag.CMP_ORDER)
.map(TagDto::new)
.toImmutableList();
}
}
} |
import { memo,useState,useCallback } from "react";
function App(){
const[count,setCount]=useState(0);
const inputFunction=useCallback(()=>{
console.log("re-render");
},[])
return <div>
<ButtonComponent inputFunction={inputFunction}></ButtonComponent>
<button onClick={()=>{
setCount(count+1);
}}>Click me {count}</button>
</div>
}
{/* <Button> Hey there my name is anurag negi</Button> */}
const ButtonComponent=memo(({inputFunction})=>{
console.log("Child render");
return <div>
<button onClick={inputFunction}>Button clicked</button>
</div>
})
export default App |
% figure331 - Display leakage of Haar wavelet variance
% compared to other estimators
%
% Usage:
% run figure331
%
% $Id: figure331.m 569 2005-09-12 19:37:21Z ccornish $
% Load the data
[X, x_att] = wmtsa_data('msp');
base_depth = 350.0;
delta_depth = 0.1;
depth = base_depth + delta_depth * ([0:1:length(X)-1]);
depth = depth(:);
% Extract meausurments between depths of 489.5 to 899.0 meters
indices = find(depth >= 489.5 & depth <= 899.0);
X = X(indices);
depth = depth(indices);
N = 4096;
k = [1:1:2048];
f = k / (N * delta_depth);
f = f(:);
% Normalized frequency
fn = f/(f(end)*2);
SDF_theor = zeros(length(f), 1);
indices = find(f <= 5/128);
SDF_theor(indices) = 32.768;
indices = find(f > 5/128 & f <= 5/8);
SDF_theor(indices) = 32.768 * abs( (128 * f(indices) / 5).^(-3.5));
indices = find(f > 5/8 & f <= 5);
SDF_theor(indices) = abs( (8 * f(indices) / 5).^(-1.7)) / 500.;
% Subplot 1: Theoretical SDF and Haar and D6 squared gain functions
haxes1 = subplot(2, 2, 1);
loglog(f, SDF_theor, 'k--');
hold on;
XLim = [10^-3, 10^1];
YLim = [10^-5, 10^3];
set(haxes1, 'XLim', XLim);
set(haxes1, 'YLim', YLim);
xlabel('\itf');
% Calculate squared gain functions for Haar and D6 filters for level 1
[Hst_haar] = modwt_wavelet_sgf(fn, 'haar', 1);
[Hst_d6] = modwt_wavelet_sgf(fn, 'd6', 1);
loglog(f, Hst_haar, 'r-');
loglog(f, Hst_d6, 'b-');
legend(haxes1, {'Theoretical SDF', 'Haar', 'D6'});
% Subplot 2: 1st Pass band of theoretical SDF,
% and level 1 wavelet squared gain-SDF products for Haar and D6
haxes2 = subplot(2, 2, 2);
% Get pass band for [1/(2^2 * delta_depth), 1/(2 * delta_depth)] = [5/2, 5]
f_lower = 1 / (2^2 * delta_depth);
f_upper = 1 / (2 * delta_depth);
indices = find(f >= f_lower & f <= f_upper);
SDF_theor_pass = SDF_theor(indices);
loglog(f(indices), SDF_theor_pass, 'k--');
hold on;
patch([f(indices(1)) f(indices)' f(indices(end))], ...
[YLim(1) SDF_theor_pass' YLim(1)], 'y');
XLim = [10^-3, 10^1];
YLim = [10^-5, 10^3];
set(haxes2, 'XLim', XLim);
set(haxes2, 'YLim', YLim);
xlabel('\itf');
% Calculate squared gain functions for Haar and D6 filters for level 1
[Hst_haar] = modwt_wavelet_sgf(fn, 'haar', 1);
[Hst_d6] = modwt_wavelet_sgf(fn, 'd6', 1);
loglog(f, Hst_haar.*SDF_theor, 'r-');
loglog(f, Hst_d6.*SDF_theor, 'b-');
legend(haxes2, {'Pass-band SDF', 'Haar', 'D6'});
% Subplot 3: 2nd Pass band of theoretical SDF,
% and level 2 wavelet squared gain-SDF products for Haar and D6
haxes3 = subplot(2, 2, 3);
% Get pass band for [1/(2^3 * delta_depth), 1/(2^2 * delta_depth)]
f_lower = 1 / (2^3 * delta_depth);
f_upper = 1 / (2^2 * delta_depth);
indices = find(f >= f_lower & f <= f_upper);
SDF_theor_pass = SDF_theor(indices);
loglog(f(indices), SDF_theor_pass, 'k--');
hold on;
patch([f(indices(1)) f(indices)' f(indices(end))], ...
[YLim(1) SDF_theor_pass' YLim(1)], 'y');
XLim = [10^-3, 10^1];
YLim = [10^-5, 10^3];
set(haxes3, 'XLim', XLim);
set(haxes3, 'YLim', YLim);
xlabel('\itf');
% Calculate squared gain functions for Haar and D6 filters for level 2
[Hst_haar] = modwt_wavelet_sgf(fn, 'haar', 2);
[Hst_d6] = modwt_wavelet_sgf(fn, 'd6', 2);
loglog(f, Hst_haar.*SDF_theor, 'r-');
loglog(f, Hst_d6.*SDF_theor, 'b-');
legend(haxes3, {'Pass-band SDF', 'Haar', 'D6'});
% Subplot 4: Theoretical wavelet variances
% for Haar and D6 filters.
haxes4 = subplot(2, 2, 4);
clear Hst_haar Hst_d6 f_band_avg;
for (j = 1:9)
% Calculate squared gain functions for Haar and D6 filters for level j
[Hst_haar] = modwt_wavelet_sgf(fn, 'haar', j);
[Hst_d6] = modwt_wavelet_sgf(fn, 'd6', j);
cumtrapz_haar = cumtrapz(f, (Hst_haar .* SDF_theor));
cumtrapz_d6 = cumtrapz(f, (Hst_d6 .* SDF_theor));
wvar_haar(j, 1) = cumtrapz_haar(end);
wvar_d6(j, 1) = cumtrapz_d6(end);
% Calculate frequency bands
f_lower = 1 / (2^(j+1) * delta_depth);
f_upper = 1 / (2^j * delta_depth);
indices = find(f >= f_lower & f <= f_upper);
f_band_avg(j) = mean(f(indices), 1);
end
Tau_j = 2.^([1:9]-1);
Tau_j = Tau_j(:);
depth_Tau_j = Tau_j * delta_depth;
loglog(depth_Tau_j, wvar_haar(1:9), 'rx');
hold on;
loglog(depth_Tau_j, wvar_d6(1:9), 'b+');
XLim = [10^-2, 10^2];
YLim = [10^-5, 10^3];
set(haxes4, 'XLim', XLim);
set(haxes4, 'YLim', YLim);
xlabel('\it{\tau_j}');
legend(haxes4, {'Haar', 'D6'});
% Add title and footer to figure
title_str = ...
{['Figure 331.'], ...
['Leakage of Haar wavelet'], ...
['and comparison to theoretical SDF and D6 estimator']};
suptitle(title_str);
figure_datestamp(mfilename, gcf);
legend(haxes4, {'Haar', 'D6'}); |
package com.java.sravan.WS_RSMessenger.model;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlTransient;
@XmlRootElement
//We tell JAX-B as a clue that this is the xml root element
public class Comment {
private long id;
private String message;
private Date created;
private String author;
private Map<Long,Comment> comments=new HashMap<Long,Comment>();
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
public Date getCreated() {
return created;
}
public void setCreated(Date created) {
this.created = created;
}
public String getAuthor() {
return author;
}
public void setAuthor(String author) {
this.author = author;
}
// When we dont want some thing(Comments) to be ignored whenever messages instances have been converted to XML/JSON
@XmlTransient
public Map<Long, Comment> getComments() {
return comments;
}
public void setComments(Map<Long, Comment> comments) {
this.comments = comments;
}
public Comment(long id, String message, String author) {
super();
this.id = id;
this.message = message;
this.author = author;
}
// This default constructor is needed as this has to be converted to json or xml by frameworks for packing a response
public Comment() {
}
} |
;;; literef.el --- the main module.
;; Copyright(C) 2017-2018 Meir Goldenberg
;; This program is free software; you can redistribute it and/or
;; modify it under the terms of the GNU General Public License as
;; published by the Free Software Foundation; either version 2, or (at
;; your option) any later version.
;; This program is distributed in the hope that it will be useful, but
;; WITHOUT ANY WARRANTY; without even the implied warranty of
;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
;; General Public License for more details.
;; You should have received a copy of the GNU General Public License
;; along with this program. If not, see <http://www.gnu.org/licenses/>.
;;; Commentary:
;;
;; This module loads all the features of the system, starts
;; the server and performs some general setting up tasks.
;;; Code:
(defun literef-install-packages()
"Install any missing packages. The code is taken from
`https://stackoverflow.com/a/10093312/2725810'."
(setq package-list '(org org-ref pdf-tools smooth-scrolling company))
; list the repositories containing them
(setq package-archives '(("gnu" . "http://elpa.gnu.org/packages/")
("melpa-stable" . "http://stable.melpa.org/packages/")))
(package-initialize)
(let (flag)
(dolist (package package-list)
(unless (eq (package-installed-p package) t) ;; need to take into account
;; the built-in org package.
(when
(yes-or-no-p (concat
"The package " (symbol-name package)
" is not installed. Install it? "))
;; Make sure the contents are refreshed once.
(unless flag
(package-refresh-contents)
(setq flag t))
;; again, some what complicated to account for the built-in org
;; see https://emacs.stackexchange.com/q/45936/16048
(let ((desc (car (cdr (assq package package-archive-contents)))))
(if desc
(package-install desc 'dont-select)
(error (error "The package is unavailable. Something is wrong with the package system."))))
(when (eq package 'pdf-tools) (pdf-tools-install))))))
(package-initialize)
)
(literef-install-packages)
(require 'org)
(setq org-ref-completion-library 'org-ref-helm-cite)
(require 'org-ref)
(require 'bibtex-completion)
(require 'org-inlinetask)
(require 'literef-config)
(require 'literef-utils)
(require 'literef-helm)
(require 'literef-latex-map)
(require 'literef-citation-functions)
(require 'literef-graph)
(require 'literef-subgraph)
(require 'literef-export)
(require 'literef-pdf)
(require 'literef-server)
(require 'literef-citation-link)
;; start the server, while making sure that
;; only one instance of it is runnning.
(shell-command "pkill literef_server")
(call-process-shell-command
(concat (file-name-directory load-file-name)
"py/literef_server.py" " " literef-directory "&") nil 0)
;; advice org-ref-helm-insert-cite-link to begin by re-reading the default bibliography,
;; since entries could be added/removed.
;; (advice-add 'org-ref-helm-insert-cite-link :before #'literef-set-default-bibliography)
(advice-add 'org-ref-helm-cite :before #'literef-set-default-bibliography)
(defun literef-completion-fallback-candidates(_orig-fun)
"The LiteRef version of `bibtex-completion-fallback-candidates'. It simply returns `bibtex-completion-fallback-options' without appending this list by all the BibTeX files."
bibtex-completion-fallback-options)
;; Override `bibtex-completion-fallback-candidates'
(advice-add 'bibtex-completion-fallback-candidates :around #'literef-completion-fallback-candidates)
;; Turn off code evaluation security.
(setq org-confirm-babel-evaluate nil)
;; Set up pdflatex compilation.
(setq org-latex-pdf-process
'("pdflatex -interaction nonstopmode -output-directory %o %f"
"bibtex %b"
"pdflatex -interaction nonstopmode -output-directory %o %f"
"pdflatex -interaction nonstopmode -output-directory %o %f")) |
import CircularProgress from '@material-ui/core/CircularProgress';
import Fab from '@material-ui/core/Fab';
import Tooltip from '@material-ui/core/Tooltip';
import { green } from '@material-ui/core/colors';
import { createStyles, makeStyles, Theme } from '@material-ui/core/styles';
import CheckIcon from '@material-ui/icons/Check';
import ErrorOutlineOutlinedIcon from '@material-ui/icons/ErrorOutlineOutlined';
import MailOutlineIcon from '@material-ui/icons/MailOutline';
import VerifiedUserOutlinedIcon from '@material-ui/icons/VerifiedUserOutlined';
import clsx from 'clsx';
import React from 'react';
const useStyles = makeStyles((theme: Theme) => {
const dark = theme.palette.type === 'dark';
const grey = theme.palette.grey;
return createStyles({
root: {
display: 'flex',
alignItems: 'center',
},
wrapper: {
margin: theme.spacing(1),
position: 'relative',
},
buttonDone: {
color: dark ? grey[100] : grey[900],
},
fabProgress: {
color: green[600],
position: 'absolute',
top: -6,
left: -6,
zIndex: 1,
},
submit: {
color: dark ? grey[900] : grey[100],
backgroundColor: dark ? grey[100] : grey[900],
transition: 'all 0.5s ease-in-out',
'&:hover': {
color: dark ? grey[100] : grey[900],
backgroundColor: dark ? grey[900] : grey[100],
},
},
});
});
const SendFab: React.FC<{
tooltip?: string;
disabled: boolean;
loading: boolean;
submitForm: () => Promise<any>;
success: boolean;
error?: boolean;
icon?: 'mail' | 'pack';
}> = ({ tooltip, disabled, loading, submitForm, success, error, icon }) => {
const classes = useStyles();
const buttonClassname = clsx({
[classes.submit]: !success && !error,
});
icon ??= 'mail';
const FabIconButton = {
mail: () => MailOutlineIcon,
pack: () => VerifiedUserOutlinedIcon,
}[icon]();
return (
<div className={classes.root}>
<div className={classes.wrapper}>
{!success && !error && tooltip && (
<Tooltip title={tooltip}>
<Fab
color="inherit"
className={buttonClassname}
disabled={disabled}
onClick={() => !loading && submitForm()}>
<FabIconButton />
</Fab>
</Tooltip>
)}
{!success && !error && !tooltip && (
<Fab
color="inherit"
className={buttonClassname}
disabled={disabled}
onClick={() => !loading && submitForm()}>
<FabIconButton />
</Fab>
)}
{!!success && !error && (
<Fab color="inherit" className={classes.buttonDone} disabled={disabled}>
<CheckIcon />
</Fab>
)}
{!success && !!error && (
<Fab color="inherit" className={classes.buttonDone} disabled={disabled}>
<ErrorOutlineOutlinedIcon />
</Fab>
)}
{loading && <CircularProgress size={68} className={classes.fabProgress} />}
</div>
</div>
);
};
export default SendFab; |
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE html>
<html lang="ru"
xmlns="http://www.w3.org/1999/xhtml"
xmlns:h="http://xmlns.jcp.org/jsf/html"
xmlns:f="http://xmlns.jcp.org/jsf/core"
xmlns:p="http://primefaces.org/ui"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://xmlns.jcp.org/jsf/html">
<h:head>
<h:outputScript library="scripts" name="dots/CanvasPrinter.js"/>
<h:outputScript library="scripts" name="dots/onetime.js"/>
<!-- Библиотека компиляции less -->
<link rel="stylesheet/less" type="text/css" href="resources/styles/dots/styles.less" />
<script src="https://cdn.jsdelivr.net/npm/less" ></script>
<!-- Библиотека SweetAlert2 -->
<script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>
<title>Ахунов Амир | Веб программиирование</title>
</h:head>
<h:body>
<header>Ахунов Амир. P3215 Вариант 18967</header>
<div id="main-container">
<div id="form-container">
<h:form>
<div class="input-container" id="X-input-container">
<p:outputLabel styleClass="form-label" for="@next" value="Выберите X:"/>
<p:selectBooleanCheckbox value="false" itemLabel="-3" class="X-checkbox">
<f:ajax render="x" listener="#{pointHandler.point.setX(-3)}"/>
</p:selectBooleanCheckbox>
<p:selectBooleanCheckbox value="false" itemLabel="-2" class="X-checkbox">
<f:ajax render="x" listener="#{pointHandler.point.setX(-2)}"/>
</p:selectBooleanCheckbox>
<p:selectBooleanCheckbox value="false" itemLabel="-1" class="X-checkbox">
<f:ajax render="x" listener="#{pointHandler.point.setX(-1)}"/>
</p:selectBooleanCheckbox>
<p:selectBooleanCheckbox value="true" itemLabel="0" class="X-checkbox">
<f:ajax render="x" listener="#{pointHandler.point.setX(0)}"/>
</p:selectBooleanCheckbox>
<p:selectBooleanCheckbox value="false" itemLabel="1" class="X-checkbox">
<f:ajax render="x" listener="#{pointHandler.point.setX(1)}"/>
</p:selectBooleanCheckbox>
<p:selectBooleanCheckbox value="false" itemLabel="2" class="X-checkbox">
<f:ajax render="x" listener="#{pointHandler.point.setX(2)}"/>
</p:selectBooleanCheckbox>
<p:selectBooleanCheckbox value="false" itemLabel="3" class="X-checkbox">
<f:ajax render="x" listener="#{pointHandler.point.setX(3)}"/>
</p:selectBooleanCheckbox>
</div>
<div class="input-container" id="Y-input-container">
<p:outputLabel styleClass="form-label" for="@next" value="Выберите Y:"/>
<h:inputText id="Y-input"
name="Y-input"
type="text"
value="#{pointHandler.point.y}"
styleClass="Y-input input-area"
required="false"
maxlength="6"
validatorMessage="Не входит в [-5..3]"
converterMessage="Введите число">
<f:validateDoubleRange minimum="-5" maximum="3"/>
<f:ajax render="Y-value-message"/>
</h:inputText>
<h:message for="Y-input" id="Y-value-message"/>
</div>
<div class="input-container" id="R-input-container">
<p:outputLabel styleClass="form-label" for="@next" value="Выберите R:"/>
<p:selectBooleanCheckbox value="true" itemLabel="1" class="R-checkbox" >
<f:ajax onevent="canvasPrinter.redrawAll(1)" render="r" listener="#{pointHandler.point.setR(1)}"/>
</p:selectBooleanCheckbox>
<p:selectBooleanCheckbox value="false" itemLabel="1.5" class="R-checkbox">
<f:ajax onevent="canvasPrinter.redrawAll(1.5)" render="r" listener="#{pointHandler.point.setR(1.5)}"/>
</p:selectBooleanCheckbox>
<p:selectBooleanCheckbox value="false" itemLabel="2" class="R-checkbox">
<f:ajax onevent="canvasPrinter.redrawAll(2)" render="r" listener="#{pointHandler.point.setR(2)}"/>
</p:selectBooleanCheckbox>
<p:selectBooleanCheckbox value="false" itemLabel="2.5" class="R-checkbox">
<f:ajax onevent="canvasPrinter.redrawAll(2.5)" render="r" listener="#{pointHandler.point.setR(2.5)}"/>
</p:selectBooleanCheckbox>
<p:selectBooleanCheckbox value="false" itemLabel="3" class="R-checkbox">
<f:ajax onevent="canvasPrinter.redrawAll(3)" render="r" listener="#{pointHandler.point.setR(3)}"/>
</p:selectBooleanCheckbox>
</div>
<div class="input-container" id="buttons-container">
<h:button value="Назад" styleClass="surfing-button main-button" outcome="go-to-index" id="go_to_index_button"/>
<h:commandButton type="submit"
id="check"
styleClass="main-button"
value="Проверить"
action="#{pointHandler.add()}"/>
</div>
</h:form>
</div>
<div id="graph-container">
<canvas id="graph" width="300" height="300"/>
</div>
<div class="table-container">
<h:dataTable id="table" styleClass="main-table" value="#{pointHandler.points}" var="point" >
<p:remoteCommand name=""/>
<h:column>
<f:facet name="header">X</f:facet>
<h:outputText id="x" value="#{point.x}"/>
</h:column>
<h:column>
<f:facet name="header">Y</f:facet>
<h:outputText id="y" value="#{point.y}"/>
</h:column>
<h:column>
<f:facet name="header">R</f:facet>
<h:outputText id="r" value="#{point.r}"/>
</h:column>
<h:column>
<f:facet name="header">Результат</f:facet>
<h:outputText styleClass="#{point.statusHTMLClass}" id="status" value="#{point.statusString}"/>
</h:column>
<h:column>
<f:facet name="header">Текущее время</f:facet>
<h:outputText id="time" value="#{point.time}"/>
</h:column>
<h:column>
<f:facet name="header">Время работы (мкс)</f:facet>
<h:outputText id="script-time" value="#{point.scriptTime}"/>
</h:column>
</h:dataTable>
</div>
</div>
<h:panelGroup id="graphPanel">
<h:outputScript>
canvasPrinter.redrawAll(canvasPrinter.lastClickedR);
</h:outputScript>/
</h:panelGroup>
<p:remoteCommand name="addAttempt" action="#{pointHandler.addFromJS()}" update="table" process="@this"/>
<p:remoteCommand name="updateGraph" update="graphPanel" process="@this"/>
<p:remoteCommand name="checkUpdate" id="checkUpdate" action="#{pointHandler.loadPointsFromDb()}" update="@(#checkUpdate)" process="@this"/>
</h:body>
</html> |
class CreateSettings < ActiveRecord::Migration[4.2]
def self.up
unless ActiveRecord::Base.connection.table_exists? 'settings'
create_table :settings do |t|
t.string :var, null: false, unique: true
t.text :value, null: true
t.integer :thing_id, null: true, unique: true
t.string :thing_type, null: true, limit: 30
t.timestamps
end
add_index :settings, %i(thing_type thing_id var), unique: true
end
end
def self.down
drop_table :settings
end
end |
@page "/add-category"
@inject NavigationManager NavigationManager
@inject IAddCategory AddCategoryUseCase
<h3>Add Category</h3>
<br/>
@if(category != null)
{
<EditForm Model="@category" OnValidSubmit="@HandleValidSubmit">
<DataAnnotationsValidator/>
<ValidationSummary/>
<div class="form-group">
<label for="name">Name</label>
<InputText id="name" @bind-Value="category.Name" class="form-control"></InputText>
</div>
<div class="form-group">
<label for="description">Description</label>
<InputText id="description" @bind-Value="category.Description" class="form-control"></InputText>
</div>
<button type="submit" class="btn btn-primary">Save</button>
<button type="button" class="btn btn-primary" @onclick="OnCancel">Cancel</button>
</EditForm>
}
@code {
private Category category;
protected override void OnInitialized()
{
base.OnInitialized();
category = new Category();
}
private void HandleValidSubmit()
{
AddCategoryUseCase.Execute(category);
NavigationManager.NavigateTo("/categories");
}
private void OnCancel()
{
NavigationManager.NavigateTo("/categories");
}
} |
<!doctype html>
<html lang="en-US">
<head>
<meta charset="utf-8">
<meta http-equiv="x-ua-compatible" content="ie=edge">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<link rel="preload" as="font" href="https://kaban.my.id/fonts/vendor/jost/jost-v4-latin-regular.woff2" type="font/woff2" crossorigin>
<link rel="preload" as="font" href="https://kaban.my.id/fonts/vendor/jost/jost-v4-latin-500.woff2" type="font/woff2" crossorigin>
<link rel="preload" as="font" href="https://kaban.my.id/fonts/vendor/jost/jost-v4-latin-700.woff2" type="font/woff2" crossorigin>
<script>(()=>{var b=window.matchMedia&&window.matchMedia("(prefers-color-scheme: dark)").matches,a=localStorage.getItem("theme");b&&a===null&&(localStorage.setItem("theme","dark"),document.documentElement.setAttribute("data-dark-mode","")),b&&a==="dark"&&document.documentElement.setAttribute("data-dark-mode",""),a==="dark"&&document.documentElement.setAttribute("data-dark-mode","")})()</script>
<link rel="stylesheet" href="https://kaban.my.id/main.db54f9bfe0e34af6df4b69bf090ea48671e03ba69b420b89320e0b7076cea1816068ce8c0730dd086b3bdfdd35a007c4a11e27a6f0497d19c43496ed0c6108c9.css" integrity="sha512-21T5v+DjSvbfS2m/CQ6khnHgO6abQguJMg4LcHbOoYFgaM6MBzDdCGs73901oAfEoR4npvBJfRnENJbtDGEIyQ==" crossorigin="anonymous">
<noscript><style>img.lazyload { display: none; }</style></noscript>
<meta name="robots" content="index, follow">
<meta name="googlebot" content="index, follow, max-snippet:-1, max-image-preview:large, max-video-preview:-1">
<meta name="bingbot" content="index, follow, max-snippet:-1, max-image-preview:large, max-video-preview:-1">
<title>Flexbox - Roberto Kaban Blog's</title>
<meta name="description" content="Flexbox adalah metode tata letak satu dimensi untuk mengatur item dalam baris atau kolom.">
<link rel="canonical" href="https://kaban.my.id/css/tutorial/flexbox/">
<meta property="og:locale" content="en_US">
<meta property="og:type" content="article">
<meta property="og:title" content="Flexbox">
<meta property="og:description" content="Flexbox adalah metode tata letak satu dimensi untuk mengatur item dalam baris atau kolom.">
<meta property="og:url" content="https://kaban.my.id/css/tutorial/flexbox/">
<meta property="og:site_name" content="Roberto Kaban Blog's">
<meta property="article:published_time" content="2021-12-06T08:49:31+00:00">
<meta property="article:modified_time" content="2021-12-06T08:49:31+00:00">
<meta property="og:image" content="https://kaban.my.id/doks.png"/>
<meta property="og:image:alt" content="Roberto Kaban Blog's">
<meta name="twitter:card" content="summary_large_image">
<meta name="twitter:site" content="@robertokaban">
<meta name="twitter:creator" content="@robertokaban">
<meta name="twitter:title" content="Flexbox">
<meta name="twitter:description" content="Flexbox adalah metode tata letak satu dimensi untuk mengatur item dalam baris atau kolom.">
<meta name="twitter:image" content="https://kaban.my.id/doks.png">
<meta name="twitter:image:alt" content="Flexbox">
<script type="application/ld+json">
{
"@context": "https://schema.org",
"@graph": [
{
"@type": "Person",
"@id": "https://kaban.my.id/#/schema/person/1",
"name": "BlogRobertoKaban",
"url": "https://kaban.my.id/",
"sameAs": [
"https://twitter.com/robertokaban"
, "https://github.com/robertokaban"
],
"image": {
"@type": "ImageObject",
"@id": "https://kaban.my.id/#/schema/image/1",
"url": "https://kaban.my.id/doks.png",
"width": 1280 ,
"height": 640 ,
"caption": "BlogRobertoKaban"
}
},
{
"@type": "WebSite",
"@id": "https://kaban.my.id/#/schema/website/1",
"url": "https://kaban.my.id/",
"name": "Roberto Kaban Blog\u0027s",
"description": "Hanya sebuah catatan kecil untuk hal yang tidak ingin dilupakan.",
"publisher": {
"@id": "https://kaban.my.id/#/schema/person/1"
}
},
{
"@type": "WebPage",
"@id": "https://kaban.my.id/css/tutorial/flexbox/",
"url": "https://kaban.my.id/css/tutorial/flexbox/",
"name": "Flexbox",
"description": "Flexbox adalah metode tata letak satu dimensi untuk mengatur item dalam baris atau kolom.",
"isPartOf": {
"@id": "https://kaban.my.id/#/schema/website/1"
},
"about": {
"@id": "https://kaban.my.id/#/schema/person/1"
},
"datePublished": "2021-12-06T08:49:31CET",
"dateModified": "2021-12-06T08:49:31CET",
"breadcrumb": {
"@id": "https://kaban.my.id/css/tutorial/flexbox/#/schema/breadcrumb/1"
},
"primaryImageOfPage": {
"@id": "https://kaban.my.id/css/tutorial/flexbox/#/schema/image/2"
},
"inLanguage": "en-US",
"potentialAction": [{
"@type": "ReadAction", "target": ["https://kaban.my.id/css/tutorial/flexbox/"]
}]
},
{
"@type": "BreadcrumbList",
"@id": "https://kaban.my.id/css/tutorial/flexbox/#/schema/breadcrumb/1",
"name": "Breadcrumbs",
"itemListElement": [{
"@type": "ListItem",
"position": 1 ,
"item": {
"@type": "WebPage",
"@id": "https://kaban.my.id/",
"url": "https://kaban.my.id/",
"name": "Home"
}
},{
"@type": "ListItem",
"position": 2 ,
"item": {
"@type": "WebPage",
"@id": "https://kaban.my.id/css/",
"url": "https://kaban.my.id/css/",
"name": "Css"
}
},{
"@type": "ListItem",
"position": 3 ,
"item": {
"@type": "WebPage",
"@id": "https://kaban.my.id/css/tutorial/",
"url": "https://kaban.my.id/css/tutorial/",
"name": "Tutorial"
}
},{
"@type": "ListItem",
"position": 4 ,
"item": {
"@id": "https://kaban.my.id/css/tutorial/flexbox/"
}
}]
},
{
"@context": "https://schema.org",
"@graph": [
{
"@type": "ImageObject",
"@id": "https://kaban.my.id/css/tutorial/flexbox/#/schema/image/2",
"url": "https://kaban.my.id/doks.png",
"contentUrl": "https://kaban.my.id/doks.png",
"caption": "Flexbox"
}
]
}
]
}
</script>
<meta name="theme-color" content="#fff">
<link rel="icon" href="https://kaban.my.id/favicon.ico" sizes="any">
<link rel="icon" type="image/svg+xml" href="https://kaban.my.id/favicon.svg">
<link rel="apple-touch-icon" sizes="180x180" href="https://kaban.my.id/apple-touch-icon.png">
<link rel="icon" type="image/png" sizes="32x32" href="https://kaban.my.id/favicon-32x32.png">
<link rel="icon" type="image/png" sizes="16x16" href="https://kaban.my.id/favicon-16x16.png">
<link rel="manifest" crossorigin="use-credentials" href="https://kaban.my.id/site.webmanifest">
<script async src="https://www.googletagmanager.com/gtag/js?id=G-60VSDZFQR5"></script>
<script>
window.dataLayer = window.dataLayer || [];
function gtag(){dataLayer.push(arguments);}
gtag('js', new Date());
gtag('config', 'G-60VSDZFQR5');
</script>
</head>
<body class="css single">
<div class="sticky-top">
<div class="header-bar"></div>
<header class="navbar navbar-expand-lg navbar-light doks-navbar">
<nav class="container-xxl flex-wrap flex-lg-nowrap" aria-label="Main navigation">
<a class="navbar-brand order-0" href="/" aria-label="Roberto Kaban Blog's">
Roberto Kaban Blog's
</a>
<button class="btn btn-menu order-2 d-block d-lg-none" type="button" data-bs-toggle="offcanvas" data-bs-target="#offcanvasDoks" aria-controls="offcanvasDoks" aria-label="Open main menu">
<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="feather feather-menu"><line x1="3" y1="12" x2="21" y2="12"></line><line x1="3" y1="6" x2="21" y2="6"></line><line x1="3" y1="18" x2="21" y2="18"></line></svg>
</button>
<div class="offcanvas offcanvas-end border-0 py-lg-1" tabindex="-1" id="offcanvasDoks" data-bs-backdrop="true" aria-labelledby="offcanvasDoksLabel">
<div class="header-bar d-lg-none"></div>
<div class="offcanvas-header d-lg-none">
<h2 class="h5 offcanvas-title ps-2" id="offcanvasDoksLabel"><a class="text-dark" href="/">Roberto Kaban Blog's</a></h2>
<button type="button" class="btn-close text-reset me-2" data-bs-dismiss="offcanvas" aria-label="Close main menu"></button>
</div>
<div class="offcanvas-body p-4 p-lg-0">
<ul class="nav flex-column flex-lg-row align-items-lg-center mt-2 mt-lg-0 ms-lg-2 me-lg-auto">
<li class="nav-item">
<a class="nav-link ps-0 py-1" href="/about/">About Me</a>
</li>
<li class="nav-item">
<a class="nav-link ps-0 py-1" href="/contact/">Contact</a>
</li>
<li class="nav-item">
<a class="nav-link ps-0 py-1" href="/artikel/">Artikel</a>
</li>
<li class="nav-item">
<a class="nav-link ps-0 py-1" href="/coretanku/">Coretanku</a>
</li>
</ul>
<hr class="text-black-50 my-4 d-lg-none">
<form class="doks-search position-relative flex-grow-1 ms-lg-auto me-lg-2">
<input id="search" class="form-control is-search" type="search" placeholder="Cari di blog ini..." aria-label="Cari di blog ini..." autocomplete="off">
<div id="suggestions" class="shadow bg-white rounded d-none"></div>
</form>
<hr class="text-black-50 my-4 d-lg-none">
<ul class="nav flex-column flex-lg-row">
<li class="nav-item">
<a class="nav-link social-link" href="https://github.com/robertokaban"><svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="feather feather-github"><path d="M9 19c-5 1.5-5-2.5-7-3m14 6v-3.87a3.37 3.37 0 0 0-.94-2.61c3.14-.35 6.44-1.54 6.44-7A5.44 5.44 0 0 0 20 4.77 5.07 5.07 0 0 0 19.91 1S18.73.65 16 2.48a13.38 13.38 0 0 0-7 0C6.27.65 5.09 1 5.09 1A5.07 5.07 0 0 0 5 4.77a5.44 5.44 0 0 0-1.5 3.78c0 5.42 3.3 6.61 6.44 7A3.37 3.37 0 0 0 9 18.13V22"></path></svg><small class="ms-2 d-lg-none">GitHub</small></a>
</li>
<li class="nav-item">
<a class="nav-link social-link" href="https://twitter.com/robertokaban"><svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="feather feather-twitter"><path d="M23 3a10.9 10.9 0 0 1-3.14 1.53 4.48 4.48 0 0 0-7.86 3v1A10.66 10.66 0 0 1 3 4s-4 9 5 13a11.64 11.64 0 0 1-7 2c9 5 20 0 20-11.5a4.5 4.5 0 0 0-.08-.83A7.72 7.72 0 0 0 23 3z"></path></svg><small class="ms-2 d-lg-none">Twitter</small></a>
</li>
</ul>
<hr class="text-black-50 my-4 d-lg-none">
<button id="mode" class="btn btn-link" type="button" aria-label="Toggle user interface mode">
<span class="toggle-dark"><svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="feather feather-moon"><path d="M21 12.79A9 9 0 1 1 11.21 3 7 7 0 0 0 21 12.79z"></path></svg></span>
<span class="toggle-light"><svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="feather feather-sun"><circle cx="12" cy="12" r="5"></circle><line x1="12" y1="1" x2="12" y2="3"></line><line x1="12" y1="21" x2="12" y2="23"></line><line x1="4.22" y1="4.22" x2="5.64" y2="5.64"></line><line x1="18.36" y1="18.36" x2="19.78" y2="19.78"></line><line x1="1" y1="12" x2="3" y2="12"></line><line x1="21" y1="12" x2="23" y2="12"></line><line x1="4.22" y1="19.78" x2="5.64" y2="18.36"></line><line x1="18.36" y1="5.64" x2="19.78" y2="4.22"></line></svg></span>
</button>
</div>
</div>
</nav>
</header>
</div>
<div class="container-xxl">
<aside class="doks-sidebar">
<nav id="doks-docs-nav" class="collapse d-lg-none" aria-label="Tertiary navigation">
<ul class="list-unstyled collapsible-sidebar">
<li class="mb-1">
<button class="btn btn-toggle align-items-center rounded collapsed" data-bs-toggle="collapse" data-bs-target="#section-420758e7531f11b46494cbfaeea9e72a" aria-expanded="true">
Tutorial CSS
</button>
<div class="collapse show" id="section-420758e7531f11b46494cbfaeea9e72a">
<ul class="btn-toggle-nav list-unstyled fw-normal pb-1 small">
<li><a class="docs-link rounded" href="https://kaban.my.id/css/tutorial/pengenalan/">Pengenalan</a></li>
<li><a class="docs-link rounded" href="https://kaban.my.id/css/tutorial/basic/">Basic</a></li>
<li><a class="docs-link rounded" href="https://kaban.my.id/css/tutorial/sintax/">Sintax</a></li>
<li><a class="docs-link rounded" href="https://kaban.my.id/css/tutorial/selectors/">Selectors</a></li>
<li><a class="docs-link rounded" href="https://kaban.my.id/css/tutorial/comments/">Comments</a></li>
<li><a class="docs-link rounded" href="https://kaban.my.id/css/tutorial/colors/">Colors</a></li>
<li><a class="docs-link rounded" href="https://kaban.my.id/css/tutorial/backgroud/">Background</a></li>
<li><a class="docs-link rounded" href="https://kaban.my.id/css/tutorial/borders/">Borders</a></li>
<li><a class="docs-link rounded" href="https://kaban.my.id/css/tutorial/border-radius/">Border Radius</a></li>
<li><a class="docs-link rounded" href="https://kaban.my.id/css/tutorial/margin/">Margin</a></li>
<li><a class="docs-link rounded" href="https://kaban.my.id/css/tutorial/padding/">Padding</a></li>
<li><a class="docs-link rounded" href="https://kaban.my.id/css/tutorial/size/">Size</a></li>
<li><a class="docs-link rounded" href="https://kaban.my.id/css/tutorial/box-model/">Box Model</a></li>
<li><a class="docs-link rounded" href="https://kaban.my.id/css/tutorial/outline/">Outline</a></li>
<li><a class="docs-link rounded" href="https://kaban.my.id/css/tutorial/text-alignment/">Text Alignment</a></li>
<li><a class="docs-link rounded" href="https://kaban.my.id/css/tutorial/text-decoration/">Text Decoration</a></li>
<li><a class="docs-link rounded" href="https://kaban.my.id/css/tutorial/text-transform/">Text Transform</a></li>
<li><a class="docs-link rounded" href="https://kaban.my.id/css/tutorial/fonts/">Fonts</a></li>
<li><a class="docs-link rounded" href="https://kaban.my.id/css/tutorial/web-font/">Web Font</a></li>
<li><a class="docs-link rounded" href="https://kaban.my.id/css/tutorial/display/">Display</a></li>
<li><a class="docs-link rounded" href="https://kaban.my.id/css/tutorial/position/">Position</a></li>
<li><a class="docs-link rounded" href="https://kaban.my.id/css/tutorial/z-index/">Z Index</a></li>
<li><a class="docs-link rounded" href="https://kaban.my.id/css/tutorial/overflow/">Overflow</a></li>
<li><a class="docs-link rounded" href="https://kaban.my.id/css/tutorial/float/">Float</a></li>
<li><a class="docs-link rounded" href="https://kaban.my.id/css/tutorial/combinators/">Combinators</a></li>
<li><a class="docs-link rounded" href="https://kaban.my.id/css/tutorial/pseudo-classes/">Pseodo Classes</a></li>
<li><a class="docs-link rounded" href="https://kaban.my.id/css/tutorial/psesudo-elements/">Pseodo Elements</a></li>
<li><a class="docs-link rounded" href="https://kaban.my.id/css/tutorial/opocity/">Opocity</a></li>
<li><a class="docs-link rounded" href="https://kaban.my.id/css/tutorial/units/">Units</a></li>
<li><a class="docs-link rounded" href="https://kaban.my.id/css/tutorial/important/">Importants</a></li>
<li><a class="docs-link rounded" href="https://kaban.my.id/css/tutorial/math-function/">Math Function</a></li>
<li><a class="docs-link rounded" href="https://kaban.my.id/css/tutorial/gradient/">Gradients</a></li>
<li><a class="docs-link rounded" href="https://kaban.my.id/css/tutorial/shadow/">Shadows</a></li>
<li><a class="docs-link rounded" href="https://kaban.my.id/css/tutorial/word-wrap/">Word Wrap</a></li>
<li><a class="docs-link rounded" href="https://kaban.my.id/css/tutorial/word-spacing/">Word Spacing</a></li>
<li><a class="docs-link rounded" href="https://kaban.my.id/css/tutorial/writing-mode/">Writing Mode</a></li>
<li><a class="docs-link rounded" href="https://kaban.my.id/css/tutorial/ransform/">Transform</a></li>
<li><a class="docs-link rounded" href="https://kaban.my.id/css/tutorial/transitions/">Transitions</a></li>
<li><a class="docs-link rounded" href="https://kaban.my.id/css/tutorial/image-filter/">Image Filter</a></li>
<li><a class="docs-link rounded" href="https://kaban.my.id/css/tutorial/object-fit/">Image Fit</a></li>
<li><a class="docs-link rounded" href="https://kaban.my.id/css/tutorial/button/">Button</a></li>
<li><a class="docs-link rounded" href="https://kaban.my.id/css/tutorial/custom-property/">Custom Properties</a></li>
<li><a class="docs-link rounded" href="https://kaban.my.id/css/tutorial/box-sizing/">Box Sizing</a></li>
<li><a class="docs-link rounded" href="https://kaban.my.id/css/tutorial/media-query/">Media Query</a></li>
<li><a class="docs-link rounded active" href="https://kaban.my.id/css/tutorial/flexbox/">Flexbox</a></li>
<li><a class="docs-link rounded" href="https://kaban.my.id/css/tutorial/grid/">Grid</a></li>
</ul>
</div>
</li>
</ul>
</nav>
</aside>
</div>
<div class="wrap container-xxl" role="document">
<div class="content">
<div class="row flex-xl-nowrap">
<div class="col-lg-5 col-xl-4 docs-sidebar d-none d-lg-block">
<nav class="docs-links" aria-label="Main navigation">
<ul class="list-unstyled collapsible-sidebar">
<li class="mb-1">
<button class="btn btn-toggle align-items-center rounded collapsed" data-bs-toggle="collapse" data-bs-target="#section-420758e7531f11b46494cbfaeea9e72a" aria-expanded="true">
Tutorial CSS
</button>
<div class="collapse show" id="section-420758e7531f11b46494cbfaeea9e72a">
<ul class="btn-toggle-nav list-unstyled fw-normal pb-1 small">
<li><a class="docs-link rounded" href="https://kaban.my.id/css/tutorial/pengenalan/">Pengenalan</a></li>
<li><a class="docs-link rounded" href="https://kaban.my.id/css/tutorial/basic/">Basic</a></li>
<li><a class="docs-link rounded" href="https://kaban.my.id/css/tutorial/sintax/">Sintax</a></li>
<li><a class="docs-link rounded" href="https://kaban.my.id/css/tutorial/selectors/">Selectors</a></li>
<li><a class="docs-link rounded" href="https://kaban.my.id/css/tutorial/comments/">Comments</a></li>
<li><a class="docs-link rounded" href="https://kaban.my.id/css/tutorial/colors/">Colors</a></li>
<li><a class="docs-link rounded" href="https://kaban.my.id/css/tutorial/backgroud/">Background</a></li>
<li><a class="docs-link rounded" href="https://kaban.my.id/css/tutorial/borders/">Borders</a></li>
<li><a class="docs-link rounded" href="https://kaban.my.id/css/tutorial/border-radius/">Border Radius</a></li>
<li><a class="docs-link rounded" href="https://kaban.my.id/css/tutorial/margin/">Margin</a></li>
<li><a class="docs-link rounded" href="https://kaban.my.id/css/tutorial/padding/">Padding</a></li>
<li><a class="docs-link rounded" href="https://kaban.my.id/css/tutorial/size/">Size</a></li>
<li><a class="docs-link rounded" href="https://kaban.my.id/css/tutorial/box-model/">Box Model</a></li>
<li><a class="docs-link rounded" href="https://kaban.my.id/css/tutorial/outline/">Outline</a></li>
<li><a class="docs-link rounded" href="https://kaban.my.id/css/tutorial/text-alignment/">Text Alignment</a></li>
<li><a class="docs-link rounded" href="https://kaban.my.id/css/tutorial/text-decoration/">Text Decoration</a></li>
<li><a class="docs-link rounded" href="https://kaban.my.id/css/tutorial/text-transform/">Text Transform</a></li>
<li><a class="docs-link rounded" href="https://kaban.my.id/css/tutorial/fonts/">Fonts</a></li>
<li><a class="docs-link rounded" href="https://kaban.my.id/css/tutorial/web-font/">Web Font</a></li>
<li><a class="docs-link rounded" href="https://kaban.my.id/css/tutorial/display/">Display</a></li>
<li><a class="docs-link rounded" href="https://kaban.my.id/css/tutorial/position/">Position</a></li>
<li><a class="docs-link rounded" href="https://kaban.my.id/css/tutorial/z-index/">Z Index</a></li>
<li><a class="docs-link rounded" href="https://kaban.my.id/css/tutorial/overflow/">Overflow</a></li>
<li><a class="docs-link rounded" href="https://kaban.my.id/css/tutorial/float/">Float</a></li>
<li><a class="docs-link rounded" href="https://kaban.my.id/css/tutorial/combinators/">Combinators</a></li>
<li><a class="docs-link rounded" href="https://kaban.my.id/css/tutorial/pseudo-classes/">Pseodo Classes</a></li>
<li><a class="docs-link rounded" href="https://kaban.my.id/css/tutorial/psesudo-elements/">Pseodo Elements</a></li>
<li><a class="docs-link rounded" href="https://kaban.my.id/css/tutorial/opocity/">Opocity</a></li>
<li><a class="docs-link rounded" href="https://kaban.my.id/css/tutorial/units/">Units</a></li>
<li><a class="docs-link rounded" href="https://kaban.my.id/css/tutorial/important/">Importants</a></li>
<li><a class="docs-link rounded" href="https://kaban.my.id/css/tutorial/math-function/">Math Function</a></li>
<li><a class="docs-link rounded" href="https://kaban.my.id/css/tutorial/gradient/">Gradients</a></li>
<li><a class="docs-link rounded" href="https://kaban.my.id/css/tutorial/shadow/">Shadows</a></li>
<li><a class="docs-link rounded" href="https://kaban.my.id/css/tutorial/word-wrap/">Word Wrap</a></li>
<li><a class="docs-link rounded" href="https://kaban.my.id/css/tutorial/word-spacing/">Word Spacing</a></li>
<li><a class="docs-link rounded" href="https://kaban.my.id/css/tutorial/writing-mode/">Writing Mode</a></li>
<li><a class="docs-link rounded" href="https://kaban.my.id/css/tutorial/ransform/">Transform</a></li>
<li><a class="docs-link rounded" href="https://kaban.my.id/css/tutorial/transitions/">Transitions</a></li>
<li><a class="docs-link rounded" href="https://kaban.my.id/css/tutorial/image-filter/">Image Filter</a></li>
<li><a class="docs-link rounded" href="https://kaban.my.id/css/tutorial/object-fit/">Image Fit</a></li>
<li><a class="docs-link rounded" href="https://kaban.my.id/css/tutorial/button/">Button</a></li>
<li><a class="docs-link rounded" href="https://kaban.my.id/css/tutorial/custom-property/">Custom Properties</a></li>
<li><a class="docs-link rounded" href="https://kaban.my.id/css/tutorial/box-sizing/">Box Sizing</a></li>
<li><a class="docs-link rounded" href="https://kaban.my.id/css/tutorial/media-query/">Media Query</a></li>
<li><a class="docs-link rounded active" href="https://kaban.my.id/css/tutorial/flexbox/">Flexbox</a></li>
<li><a class="docs-link rounded" href="https://kaban.my.id/css/tutorial/grid/">Grid</a></li>
</ul>
</div>
</li>
</ul>
</nav>
</div>
<nav class="docs-toc d-none d-xl-block col-xl-3" aria-label="Secondary navigation">
<div class="d-xl-none">
<button class="btn btn-outline-primary btn-sm doks-toc-toggle collapsed" type="button" data-bs-toggle="collapse" data-bs-target="#onThisPage" aria-controls="doks-docs-nav" aria-expanded="false" aria-label="Toggle On this page navigation">
<span>Daftar isi</span>
<span>
<svg xmlns="http://www.w3.org/2000/svg" width="18" height="18" viewBox="0 0 24 24" class="doks doks-expand" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><title>Expand</title><polyline points="7 13 12 18 17 13"></polyline><polyline points="7 6 12 11 17 6"></polyline></svg>
<svg xmlns="http://www.w3.org/2000/svg" width="18" height="18" viewBox="0 0 24 24" class="doks doks-collapse" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><title>Collapse</title><polyline points="17 11 12 6 7 11"></polyline><polyline points="17 18 12 13 7 18"></polyline></svg>
</span>
</button>
<div class="collapse" id="onThisPage">
<div class="card card-body mt-3 py-1">
<div class="page-links">
<nav id="TableOfContents">
<ul>
<li><a href="#apa-itu-flexbox">Apa Itu Flexbox</a></li>
<li><a href="#flexbox-layout">Flexbox Layout</a></li>
<li><a href="#properti-di-flex-container">Properti di Flex Container</a></li>
<li><a href="#properti-di-flex-item">Properti di Flex Item</a></li>
<li><a href="#referensi">Referensi</a></li>
</ul>
</nav>
</div>
</div>
</div>
</div>
<div class="page-links d-none d-xl-block">
<h3>Daftar isi</h3>
<nav id="TableOfContents">
<ul>
<li><a href="#apa-itu-flexbox">Apa Itu Flexbox</a></li>
<li><a href="#flexbox-layout">Flexbox Layout</a></li>
<li><a href="#properti-di-flex-container">Properti di Flex Container</a></li>
<li><a href="#properti-di-flex-item">Properti di Flex Item</a></li>
<li><a href="#referensi">Referensi</a></li>
</ul>
</nav>
</div>
</nav>
<main class="docs-content col-lg-11 col-xl-9">
<nav aria-label="breadcrumb">
<ol class="breadcrumb">
<li class="breadcrumb-item"><a href="/">Home</a></li>
<li class="breadcrumb-item"><a href="/css/">Css</a></li>
<li class="breadcrumb-item"><a href="/css/tutorial/">Tutorial CSS</a></li>
<li class="breadcrumb-item active" aria-current="page">Flexbox</li>
</ol>
</nav>
<h1>Flexbox</h1>
<p class="lead"></p>
<nav class="d-xl-none" aria-label="Quaternary navigation">
<div class="d-xl-none">
<button class="btn btn-outline-primary btn-sm doks-toc-toggle collapsed" type="button" data-bs-toggle="collapse" data-bs-target="#onThisPage" aria-controls="doks-docs-nav" aria-expanded="false" aria-label="Toggle On this page navigation">
<span>Daftar isi</span>
<span>
<svg xmlns="http://www.w3.org/2000/svg" width="18" height="18" viewBox="0 0 24 24" class="doks doks-expand" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><title>Expand</title><polyline points="7 13 12 18 17 13"></polyline><polyline points="7 6 12 11 17 6"></polyline></svg>
<svg xmlns="http://www.w3.org/2000/svg" width="18" height="18" viewBox="0 0 24 24" class="doks doks-collapse" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><title>Collapse</title><polyline points="17 11 12 6 7 11"></polyline><polyline points="17 18 12 13 7 18"></polyline></svg>
</span>
</button>
<div class="collapse" id="onThisPage">
<div class="card card-body mt-3 py-1">
<div class="page-links">
<nav id="TableOfContents">
<ul>
<li><a href="#apa-itu-flexbox">Apa Itu Flexbox</a></li>
<li><a href="#flexbox-layout">Flexbox Layout</a></li>
<li><a href="#properti-di-flex-container">Properti di Flex Container</a></li>
<li><a href="#properti-di-flex-item">Properti di Flex Item</a></li>
<li><a href="#referensi">Referensi</a></li>
</ul>
</nav>
</div>
</div>
</div>
</div>
<div class="page-links d-none d-xl-block">
<h3>Daftar isi</h3>
<nav id="TableOfContents">
<ul>
<li><a href="#apa-itu-flexbox">Apa Itu Flexbox</a></li>
<li><a href="#flexbox-layout">Flexbox Layout</a></li>
<li><a href="#properti-di-flex-container">Properti di Flex Container</a></li>
<li><a href="#properti-di-flex-item">Properti di Flex Item</a></li>
<li><a href="#referensi">Referensi</a></li>
</ul>
</nav>
</div>
</nav>
<h1 id="css-flexbox">CSS Flexbox <a href="#css-flexbox" class="anchor" aria-hidden="true">#</a></h1>
<h2 id="apa-itu-flexbox">Apa Itu Flexbox <a href="#apa-itu-flexbox" class="anchor" aria-hidden="true">#</a></h2>
<p>Flexbox adalah metode tata letak satu dimensi untuk mengatur item dalam baris atau kolom. Flexbox diperkenalkan di CSS versi terbaru yaitu, CSS3. Dengan flexbox, mudah untuk memusatkan elemen pada halaman dan membuat antarmuka pengguna dinamis yang menyusut dan meluas secara otomatis.</p>
<p>Untuk membuat elemen HTML menjadi flexbox kita bisa pilih elemen tersebut dengan menggunakan CSS selector dan menambahkan properti <code>display</code> dengan value <code>flex</code>.</p>
<pre><code class="language-css">.flex-container {
display: flex;
}
</code></pre>
<h2 id="flexbox-layout">Flexbox Layout <a href="#flexbox-layout" class="anchor" aria-hidden="true">#</a></h2>
<p><img class="img-fluid lazyload blur-up" src="https://developer.mozilla.org/en-US/docs/Learn/CSS/CSS_layout/Flexbox/flex_terms.png" alt="flex-model"></p>
<ul>
<li>Main axis merupakan sumbu utama yang arahnya horizontal atau mendatar. Awal sumbu disebut main start dan akhir sumbu disebut main end.</li>
<li>Cross axis merupakan sumbu yang arahnya vertikal atau tegak. Awal sumbu disebut cross start dan akhir sumbu disebut cross end.</li>
<li>Flex container merupakan parent elemen dari flex item yang telah kita atur dengan CSS menggunakan <code>display: flex;</code>.</li>
<li>Flex item merupakan child elemen dari flex container.</li>
<li>Main size merupakan lebar dari flex item.</li>
<li>Cross size merupakan tinggi dari flex item.</li>
<li>Beberapa CSS properti di flex container:
<ul>
<li><code>flex-direction</code></li>
<li><code>flex-wrap</code></li>
<li><code>flex-flow</code></li>
<li><code>justify-content</code></li>
<li><code>align-items</code></li>
<li><code>align-content</code></li>
</ul>
</li>
<li>Beberapa CSS properti di flex item:
<ul>
<li><code>order</code></li>
<li><code>flex-grow</code></li>
<li><code>flex-shrink</code></li>
<li><code>flex-basis</code></li>
<li><code>flex</code></li>
<li><code>align-self</code></li>
</ul>
</li>
</ul>
<h2 id="properti-di-flex-container">Properti di Flex Container <a href="#properti-di-flex-container" class="anchor" aria-hidden="true">#</a></h2>
<p>Berikut adalah beberapa properti CSS yang ada di flex container untuk mengatur flex item:</p>
<ul>
<li>
<p><code>flex-direction</code> - Untuk menentukan arah flex item di dalam flex container.</p>
<p>Contoh:</p>
<p>Untuk mengatur flex item secara vertikal dengan arah dari atas ke bawah.</p>
<pre><code class="language-css">.flex-container {
flex-direction: column;
}
</code></pre>
<p>Untuk mengatur flex item secara horizontal dengan arah dari kiri ke kanan</p>
<pre><code class="language-css">.flex-container {
flex-direction: row;
}
</code></pre>
<p>Sama seperti row namun dengan arah sebaliknya</p>
<pre><code class="language-css">.flex-container {
flex-direction: row-reverse;
}
</code></pre>
<p>Sama seperti column namun dengan arah sebaliknya</p>
<pre><code class="language-css">.flex-container {
flex-direction: column-reverse;
}
</code></pre>
</li>
<li>
<p><code>flex-wrap</code> - Untuk menentukan apakah flex item harus wrap atau tidak, jika tidak ada cukup ruang untuk mereka pada main axis.</p>
<p>Contoh:</p>
<p>Flex item akan wrap jika tidak ada cukup ruang di dalam container</p>
<pre><code class="language-css">.flex-container {
flex-wrap: wrap;
}
</code></pre>
<p>Flex item tidak akan wrap meskipun tidak ada cukup ruang di dalam container</p>
<pre><code class="language-css">.flex-container {
flex-wrap: nowrap;
}
</code></pre>
<p>Flex item akan wrap dengan arah yang sebaliknya</p>
<pre><code class="language-css">.flex-container {
flex-wrap: wrap-reverse;
}
</code></pre>
</li>
<li>
<p><code>flex-flow</code> - Shorthand untuk <code>flex-direction</code> dan <code>flex-wrap</code>.</p>
<p>Contoh:</p>
<pre><code class="language-css">.flex-container {
flex-direction: row;
flex-wrap: wrap;
}
</code></pre>
<p>Maka shorthand nya akan seperti ini</p>
<pre><code class="language-css">.flex-container {
flex-flow: row wrap;
}
</code></pre>
</li>
<li>
<p><code>justify-content</code> - Untuk menyejajarkan flex item secara horizontal saat item tidak menggunakan semua ruang yang tersedia di main axis.</p>
<p>Contoh:</p>
<p>Menyejajarkan flex item di tengah main axis</p>
<pre><code class="language-css">.flex-container {
justify-content: center;
}
</code></pre>
<p>Menyejajarkan flex item di awal main axis</p>
<pre><code class="language-css">.flex-container {
justify-content: flex-start;
}
</code></pre>
<p>Menyejajarkan flex item di akhir main axis</p>
<pre><code class="language-css">.flex-container {
justify-content: flex-end;
}
</code></pre>
<p>Flex item akan memiliki ruang kosong diantara flex item</p>
<pre><code class="language-css">.flex-container {
justify-content: space-between;
}
</code></pre>
<p>Flex item akan memiliki ruang kosong disekitarnya</p>
<pre><code class="language-css">.flex-container {
justify-content: space-around;
}
</code></pre>
<p>Flex item akan memiliki ruang kosong disekitarnya dengan ukuran yang sama sesuai panjang main axis</p>
<pre><code class="language-css">.flex-container {
justify-content: space-evenly; /* */
}
</code></pre>
</li>
<li>
<p><code>align-items</code> - Untuk menyejajarkan flex item secara vertikal saat item tidak menggunakan semua ruang yang tersedia pada cross axis.</p>
<p>Contoh:</p>
<p>Menyejajarkan flex item di tengah cross axis</p>
<pre><code class="language-css">.flex-container {
align-items: center;
}
</code></pre>
<p>Flex item akan diregangkan sesuai dengan panjang cross axis</p>
<pre><code class="language-css">.flex-container {
align-items: stretch;
}
</code></pre>
<p>Menyejajarkan flex item di awal cross axis</p>
<pre><code class="language-css">.flex-container {
align-items: flex-start;
}
</code></pre>
<p>Menyejajarkan flex item di akhir cross axis</p>
<pre><code class="language-css">.flex-container {
align-items: flex-end;
}
</code></pre>
<p>Flex item akan diposisikan di garis dasar container</p>
<pre><code class="language-css">.flex-container {
align-items: baseline;
}
</code></pre>
</li>
<li>
<p><code>align-content</code> - Untuk memodifikasi perilaku properti flex-wrap. Hal ini mirip dengan align-item, tapi bukan untuk menyelaraskan flex item, melainkan untuk menyelaraskan garis flex.</p>
<p>Contoh:</p>
<p>Garis dikemas ke arah tengah container</p>
<pre><code class="language-css">.flex-container {
align-content: center;
}
</code></pre>
<p>Garis meregang untuk mengambil ruang yang tersisa di container</p>
<pre><code class="language-css">.flex-container {
align-content: stretch;
}
</code></pre>
<p>Garis dikemas ke awal cross axis</p>
<pre><code class="language-css">.flex-container {
align-content: flex-start;
}
</code></pre>
<p>Garis dikemas ke akhir cross axis</p>
<pre><code class="language-css">.flex-container {
align-content: flex-end;
}
</code></pre>
<p>Garis didistribusikan secara merata di dalam container</p>
<pre><code class="language-css">.flex-container {
align-content: space-between;
}
</code></pre>
<p>Garis didistribusikan secara merata di dalam container, dengan ruang setengah ukuran di kedua ujungnya</p>
<pre><code class="language-css">.flex-container {
align-content: space-around;
}
</code></pre>
<p>Garis didistribusikan secara merata di dalam container, dengan ruang yang sama di sekelilingnya</p>
<pre><code class="language-css">.flex-container {
align-content: space-evenly;
}
</code></pre>
</li>
</ul>
<h2 id="properti-di-flex-item">Properti di Flex Item <a href="#properti-di-flex-item" class="anchor" aria-hidden="true">#</a></h2>
<p>Berikut adalah beberapa properti CSS yang ada di flex item:</p>
<ul>
<li>
<p><code>order</code> - Untuk menentukan urutan flex item di dalam container yang sama.</p>
<p>Contoh:</p>
<p>Flex item akan berurutan mulai dari flex-item-1, flex-item-2, flex-item-3 sesuai order yang diberikan. Nilai defaultnya adalah 0.</p>
<pre><code class="language-css">.flex-container {
display: flex;
}
.flex-container .flex-item-1 {
order: 3;
}
.flex-container .flex-item-2 {
order: 2;
}
.flex-container .flex-item-3 {
order: 1;
}
</code></pre>
</li>
<li>
<p><code>flex-grow</code> - Untuk menentukan seberapa banyak flex item akan tumbuh relatif terhadap flex item lainnya di dalam container yang sama.</p>
<p>Contoh:</p>
<p>flex-item-1 akan memiliki ukuran lebih besar relatif terhadap flex item lainnya. Nilai defaultnya adalah 0.</p>
<pre><code class="language-css">.flex-container {
display: flex;
}
.flex-container .flex-item-1 {
flex-grow: 3;
}
.flex-container .flex-item-2 {
flex-grow: 1;
}
.flex-container .flex-item-3 {
flex-grow: 1;
}
</code></pre>
</li>
<li>
<p><code>flex-shrink</code> - Untuk menentukan seberapa banyak flex item akan menyusut relatif terhadap flex item lainnya di dalam wadah yang sama.</p>
<p>Contoh:</p>
<p>flex-item-1 akan menyusut lebih kecil relatif terhadap ukuran flex item lainnya. Nilai defaultnya adalah 1.</p>
<pre><code class="language-css">.flex-container {
display: flex;
}
.flex-container .flex-item-1 {
flex-shrink: 3;
}
</code></pre>
</li>
<li>
<p><code>flex-basis</code> - Untuk menentukan panjang awal flex item.</p>
<p>Contoh:</p>
<p>flex-item-1 akan memiliki panjang awal dengan ukuran 300px.</p>
<pre><code class="language-css">.flex-container {
display: flex;
}
.flex-container .flex-item-1 {
flex-basis: 300px;
}
</code></pre>
</li>
<li>
<p><code>flex</code> - Untuk shorthand properti flex-grow, flex-shrink, dan flex-basis.</p>
<p>Contoh:</p>
<p>Tidak menggunakan shorthand.</p>
<pre><code class="language-css">.flex-container {
display: flex;
}
.flex-container .flex-item-1 {
flex-grow: 1;
flex-shrink: 2;
flex-basis: 300px;
}
</code></pre>
<p>Saat menggunakan shorthand.</p>
<pre><code class="language-css">.flex-container {
display: flex;
}
.flex-container .flex-item-1 {
flex: 1 2 300px;
}
</code></pre>
</li>
<li>
<p><code>align-self</code> - Untuk menentukan perataan flex item secara spesifik untuk item tertentu (menimpa properti align-items container).</p>
<p>Contoh:</p>
<p>flex-item-1 akan berada di tengah cross axis, flex-item-2 akan berada di awal cross axis,
flex-item-3 akan berada di akhir cross axis.</p>
<pre><code class="language-css">.flex-container {
display: flex;
}
.flex-container .flex-item-1 {
align-self: flex-start;
}
.flex-container .flex-item-2 {
align-self: center;
}
.flex-container .flex-item-3 {
align-self: flex-end;
}
</code></pre>
<h2 id="referensi">Referensi <a href="#referensi" class="anchor" aria-hidden="true">#</a></h2>
<p>Untuk referensi lengkapnya, kalian bisa mengunjungi website berikut:</p>
<ul>
<li><a href="https://developer.mozilla.org/en-US/docs/Learn/CSS/CSS_layout/Flexbox">MDN Web Docs</a></li>
<li><a href="https://www.w3schools.com/css/css3_flexbox.asp">W3Schools</a></li>
</ul>
</li>
</ul>
<div class="page-footer-meta d-flex flex-column flex-md-row justify-content-between">
</div>
<div class="docs-navigation d-flex justify-content-between">
<a href="/css/tutorial/media-query/">
<div class="card my-1">
<div class="card-body py-2">
← Media Query
</div>
</div>
</a>
<a class="ms-auto" href="/css/tutorial/grid/">
<div class="card my-1">
<div class="card-body py-2">
Grid →
</div>
</div>
</a>
</div>
</main>
</div>
</div>
</div>
<footer class="footer text-muted">
<div class="container-xxl">
<div class="row">
<div class="col-lg-8 order-last order-lg-first">
<ul class="list-inline">
<li class="list-inline-item">Powered by <a class="text-muted" href="https://gohugo.io/">Hugo</a> and <a class="text-muted" href="https://github.com/">Github</a></li>
</ul>
</div>
<div class="col-lg-8 order-first order-lg-last text-lg-end">
<ul class="list-inline">
</ul>
</div>
</div>
</div>
</footer>
<script src="/js/bootstrap.min.5cdeb20ef814d367b4d5429ada9d342419eb34734de4713a71e5706485eaa75fa8d5d760c7a7f7ef20cb5494737eb8811729431813f22744c177384758c19081.js" integrity="sha512-XN6yDvgU02e01UKa2p00JBnrNHNN5HE6ceVwZIXqp1+o1ddgx6f37yDLVJRzfriBFylDGBPyJ0TBdzhHWMGQgQ==" crossorigin="anonymous" defer></script>
<script src="/js/highlight.min.6e0bbb1ba7e7c09c5287a998de4147da3f56f6fed3dc91b747789519a1de6486b086542ebb2ed60527cfc4c32b8ce175a08c257392e98d7bb3f09661f2bd5666.js" integrity="sha512-bgu7G6fnwJxSh6mY3kFH2j9W9v7T3JG3R3iVGaHeZIawhlQuuy7WBSfPxMMrjOF1oIwlc5LpjXuz8JZh8r1WZg==" crossorigin="anonymous" defer></script>
<script src="/main.min.124171d9dd7beef16c3e35cd8394ad0c5ca7699608f699d747030ef0b0c3e4c2782454dd406f78e14ef7336f4a15de8676a808261d92f9b1858f1ec3ff720269.js" integrity="sha512-EkFx2d177vFsPjXNg5StDFynaZYI9pnXRwMO8LDD5MJ4JFTdQG944U73M29KFd6GdqgIJh2S+bGFjx7D/3ICaQ==" crossorigin="anonymous" defer></script>
<script src="https://kaban.my.id/index.min.c1167ae8499907d50f7ab7a6ca141bb698dd1c592dc6715b27e6de83fab99dd89a31ce99d0c58667ae7704d0559a1942514f4d9a6c5b95a2c2b40ed0e6c3c179.js" integrity="sha512-wRZ66EmZB9UPeremyhQbtpjdHFktxnFbJ+beg/q5ndiaMc6Z0MWGZ653BNBVmhlCUU9NmmxblaLCtA7Q5sPBeQ==" crossorigin="anonymous" defer></script>
<div class="d-flex fixed-bottom pb-4 pb-lg-5 pe-4 pe-lg-5">
<a id="toTop" href="#" class="btn btn-outline-primary rounded-circle ms-auto p-2"><span class="visually-hidden">Top</span><svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="feather feather-chevron-up"><polyline points="18 15 12 9 6 15"></polyline></svg></a>
</div>
</body>
</html> |
package com.example.local.dao
import androidx.paging.PagingSource
import androidx.room.Dao
import androidx.room.Insert
import androidx.room.OnConflictStrategy
import androidx.room.Query
import com.example.local.entities.PokemonDetailEntity
import com.example.local.entities.PokemonDetailEntity.Companion.POKEMON_DETAIL_TABLE
import com.example.local.entities.PokemonEntity
import com.example.local.entities.PokemonEntity.Companion.POKEMON_TABLE
@Dao
interface PokemonDao {
@Insert(onConflict = OnConflictStrategy.REPLACE)
fun insertOrUpdatePokemonDetail(entity: PokemonDetailEntity)
@Query("SELECT * FROM $POKEMON_DETAIL_TABLE WHERE id = :id")
fun getPokemonDetail(id: Int): PokemonDetailEntity
@Query("DELETE FROM $POKEMON_DETAIL_TABLE")
fun deletePokemonDetail()
@Insert(onConflict = OnConflictStrategy.REPLACE)
fun insertOrUpdatePokemon(entities: ArrayList<PokemonEntity>)
@Query("SELECT * FROM $POKEMON_TABLE")
fun getAllPokemon(): PagingSource<Int, PokemonEntity>
@Query("DELETE FROM $POKEMON_TABLE")
fun deletePokemon()
} |
package com.van589.mooc.commons.utils;
import com.van589.mooc.commons.persistence.BeanCopyUtilCallBack;
import org.springframework.beans.BeanUtils;
import java.util.ArrayList;
import java.util.List;
import java.util.function.Supplier;
import static org.springframework.beans.BeanUtils.copyProperties;
/**
* 对 BeanUtils 不能复制 List 的拓展
*/
public class BeanCopyUtil extends BeanUtils {
/**
* 集合数据的拷贝
* @param sources: 数据源类
* @param target: 目标类::new(eg: UserVO::new)
* @return
*/
public static <S, T> List<T> copyListProperties(List<S> sources, Supplier<T> target) {
return copyListProperties(sources, target, null);
}
/**
* 带回调函数的集合数据的拷贝(可自定义字段拷贝规则)
* @param sources: 数据源类
* @param target: 目标类::new(eg: UserVO::new)
* @param callBack: 回调函数
* @return
*/
public static <S, T> List<T> copyListProperties(List<S> sources, Supplier<T> target, BeanCopyUtilCallBack<S, T> callBack) {
List<T> list = new ArrayList<>(sources.size());
for (S source : sources) {
T t = target.get();
copyProperties(source, t);
list.add(t);
if (callBack != null) {
// 回调
callBack.callBack(source, t);
}
}
return list;
}
} |
#include<WiFi.h>
#include<ESPAsyncWebServer.h>
#include<Update.h>
#include<SPIFFS.h>
#include<ESPmDNS.h>
const char * ssid="TOTOLINK N150RT";
const char * password="0422876333";
const char * host="blanka";
AsyncWebServer server(80);
void handleUpdate(AsyncWebServerRequest *req,String filename,size_t index,uint8_t *data,size_t len,bool final)
{
if(!index)
{
Serial.printf("Update firmware:%s\n",filename.c_str());
if(!Update.begin())
{
Update.printError(Serial);
}
}
if(len)
{
Update.write(data,len);
}
if(final)
{
if(Update.end(true))
{
Serial.printf("Wrote %u bytes\nRestart ESP32",index+len);
}
else
{
Update.printError(Serial);
}
}
}
void setup()
{
pinMode(LED_BUILTIN,OUTPUT);
Serial.begin(115200);
if(!SPIFFS.begin(true))
{
Serial.println("SPIFFS is broken");
return;
}
WiFi.mode(WIFI_STA);
WiFi.hostname("OTA_WEBSITE");
WiFi.begin(ssid,password);
while(WiFi.status()!=WL_CONNECTED)
{
Serial.print(".");
delay(500);
}
Serial.printf("\nIP address:%s\n",WiFi.localIP().toString().c_str());
if(!MDNS.begin(host))
{
Serial.println("Setup MDNS fail");
while(1)
{
delay(50);
}
}
server.serveStatic("/",SPIFFS,"/www/").setDefaultFile("index.html");
server.serveStatic("/favicon.ico",SPIFFS,"/www/favicon.ico");
server.serveStatic("/img",SPIFFS,"/www/img/");
server.serveStatic("/firmware",SPIFFS,"/www/firmware.html");
server.on("/upload",HTTP_POST,[](AsyncWebServerRequest *req){
req->send(200,"text/html;charset=utf-8",(Update.hasError()?"Update fail":"Update success"));
delay(3000);
ESP.restart();
},handleUpdate);
server.begin();
MDNS.setInstanceName("CCC ESP32");
MDNS.addService("http","tcp",80);
}
void loop()
{
digitalWrite(LED_BUILTIN,LOW);
delay(1000);
digitalWrite(LED_BUILTIN,HIGH);
delay(1000);
} |
<!DOCTYPE HTML>
<html lang="zh-CN">
<head>
<meta charset="UTF-8">
<title>Linux的服务管理 | Shadow</title>
<meta name="viewport" content="width=device-width, initial-scale=1,user-scalable=no">
<meta name="author" content="Shadow">
<meta name="description" content="介绍服务的分类、如何查看系统已安装的服务、启动服务的常用方式、设置服务的自启动以及如何查看系统已开启的服务。">
<meta property="og:type" content="article">
<meta property="og:title" content="Linux的服务管理">
<meta property="og:url" content="http://qq2867234.github.io/2016/03/14/Linux-service-manager/index.html">
<meta property="og:site_name" content="Shadow">
<meta property="og:description" content="介绍服务的分类、如何查看系统已安装的服务、启动服务的常用方式、设置服务的自启动以及如何查看系统已开启的服务。">
<meta property="og:updated_time" content="2016-05-12T05:45:40.474Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="Linux的服务管理">
<meta name="twitter:description" content="介绍服务的分类、如何查看系统已安装的服务、启动服务的常用方式、设置服务的自启动以及如何查看系统已开启的服务。">
<link rel="alternative" href="/atom.xml" title="Shadow" type="application/atom+xml">
<link rel="icon" href="/img/favicon.ico">
<link rel="apple-touch-icon" href="/img/jacman.jpg">
<link rel="apple-touch-icon-precomposed" href="/img/jacman.jpg">
<link rel="stylesheet" href="/css/style.css" type="text/css">
</head>
<body>
<header>
<div>
<div id="imglogo">
<a href="/"><img src="/img/logo.svg" alt="Shadow" title="Shadow"/></a>
</div>
<div id="textlogo">
<h1 class="site-name"><a href="/" title="Shadow">Shadow</a></h1>
<h2 class="blog-motto">Every day a little better than yesterday</h2>
</div>
<div class="navbar"><a class="navbutton navmobile" href="#" title="菜单">
</a></div>
<nav class="animated">
<ul>
<ul>
<li><a href="/">Home</a></li>
<li><a href="/archives">Archives</a></li>
<li><a href="/about">About</a></li>
<li>
<form class="search" action="//google.com/search" method="get" accept-charset="utf-8">
<label>Search</label>
<input type="search" id="search" name="q" autocomplete="off" maxlength="20" placeholder="搜索" />
<input type="hidden" name="q" value="site:qq2867234.github.io">
</form>
</li>
</ul>
</nav>
</div>
</header>
<div id="container">
<div id="main" class="post" itemscope itemprop="blogPost">
<article itemprop="articleBody">
<header class="article-info clearfix">
<h1 itemprop="name">
<a href="/2016/03/14/Linux-service-manager/" title="Linux的服务管理" itemprop="url">Linux的服务管理</a>
</h1>
<p class="article-author">By
<a href="/about" title="Shadow" target="_blank" itemprop="author">Shadow</a>
<p class="article-time">
<time datetime="2016-03-14T15:42:34.000Z" itemprop="datePublished"> 发表于 2016-03-14</time>
</p>
</header>
<div class="article-content">
<h3 id="系统运行级别">系统运行级别</h3><p>Linux系统包含以下7个运行级别</p>
<table>
<thead>
<tr>
<th style="text-align:center">级别</th>
<th style="text-align:left">描述</th>
</tr>
</thead>
<tbody>
<tr>
<td style="text-align:center">0</td>
<td style="text-align:left">关机</td>
</tr>
<tr>
<td style="text-align:center">1</td>
<td style="text-align:left">单用户模式(类似于windows的安全模式,主要用于系统修复)</td>
</tr>
<tr>
<td style="text-align:center">2</td>
<td style="text-align:left">不完全的命令行模式</td>
</tr>
<tr>
<td style="text-align:center">3</td>
<td style="text-align:left">完全的命令行模式,就是我们常用的标准字符界面</td>
</tr>
<tr>
<td style="text-align:center">4</td>
<td style="text-align:left">系统保留</td>
</tr>
<tr>
<td style="text-align:center">5</td>
<td style="text-align:left">图形界面模式</td>
</tr>
<tr>
<td style="text-align:center">6</td>
<td style="text-align:left">重启动</td>
</tr>
</tbody>
</table>
<p>其中最常见的是级别3和5。</p>
<p>要查看系统当前的运行级别,可以用 <code>runlevel</code> 命令,要修改运行级别,则使用 <code>init 级别编号</code> ,比如使用 <code>init 0</code> 命令,系统将关机。</p>
<h3 id="服务的分类">服务的分类</h3><ol>
<li>使用RPM包安装的服务<br> 安装位置:RPM包安装的默认位置</li>
<li>源码包安装的服务<br> 安装位置:用户指定,一般是<code>/usr/local/</code>(类似于windows的Program Files)<br> usr是 Unix System Resource(Unix系统资源)</li>
</ol>
<p>其中,RPM安装的默认位置:<br> <code>/etc/init.d/</code> 服务启动脚本(所有通过RPM包安装的服务的启动脚本,都在这个目录)<br> <code>/etc/sysconfig/</code> 初始化环境配置文件位置<br> <code>/etc/</code> 配置文件位置<br> <code>/var/lib/</code> 服务产生的数据放在这里<br> <code>/var/log/</code> 日志</p>
<h3 id="查看已安装的服务">查看已安装的服务</h3><ol>
<li><p>查看RPM包安装的服务,以及服务是否自启动</p>
<figure class="highlight bash"><table><tr><td class="code"><pre><span class="line">chkconfig --list</span><br><span class="line">结果(下面只列出其中一条): </span><br><span class="line">network <span class="number">0</span>:off <span class="number">1</span>:off <span class="number">2</span>:on <span class="number">3</span>:on <span class="number">4</span>:on <span class="number">5</span>:on <span class="number">6</span>:off</span><br><span class="line">注:<span class="number">0</span>-<span class="number">6</span> 表示服务器的<span class="number">7</span>个运行级别,on/off 表示系统处于指定级别下是否自动启动)</span><br></pre></td></tr></table></figure>
</li>
<li><p>源码包安装的服务,一般是/usr/local下。</p>
</li>
</ol>
<p>PS:很多服务名称后面会加个d,比如httpd、mysqld。d是用来表示守护进程的意思。</p>
<h3 id="启动RPM包安装的服务">启动RPM包安装的服务</h3><ol>
<li><code>/etc/init.d/serviceName start|stop|restart|status</code><br> 这是Linux系统标准的服务启动方式,推荐使用。</li>
<li><code>service serviceName start|stop|restart|status</code><br> 这是Redhat专有的命令。Redhat为了方便,单独开发的,只有redhat系列,才能使用这个命令,换一个linux版本,就不一定有了,所以最好不要太依赖这种方式。</li>
</ol>
<h3 id="启动源码包安装的服务">启动源码包安装的服务</h3><p>使用绝对路径,调用启动脚本来启动。可以通过查看源码包的安装说明,查看启动脚本的方法。<br>比如:<code>/usr/local/apache2/bin/apachectl start|stop</code></p>
<h3 id="RPM安装服务的自启动">RPM安装服务的自启动</h3><ol>
<li><p>使用<code>chkconfig</code>命令</p>
<figure class="highlight plain"><table><tr><td class="code"><pre><span class="line">chkconfig [--level 运行级别] [服务名] [on|off] # 比如要设置apache服务自启动,则使用下面的命令: # (其中,--level 2345为惯用写法。推荐使用这种方法来设置自启动) chkconfig --level 2345 httpd on</span><br></pre></td></tr></table></figure>
</li>
<li><p>修改<code>/etc/rc.local</code>文件<br> 这个文件是,在系统启动的时候,所有服务都启动完,用户登录前,最后执行的文件,系统会执行该文件里的所有命令。所以,只要将服务的启动命令(比如 <code>/etc/init.d/httpd start</code>)写到这个文件里,服务就能自启动了。</p>
</li>
<li>使用<code>ntsysv</code>命令管理自启动<br> 同样是Redhat系列专有。</li>
</ol>
<h3 id="源码包安装服务的自启动">源码包安装服务的自启动</h3><p>通过修改<code>/etc/rc.local</code>文件来设置。</p>
<p>还可以通过下面的两种方式,让源码包服务被服务管理命令识别:</p>
<ol>
<li><p>通过软链接来完成</p>
<figure class="highlight plain"><table><tr><td class="code"><pre><span class="line">ln -s /usr/local/apache2/bin/apachectl /etc/init.d/apache</span><br></pre></td></tr></table></figure>
</li>
<li><p>让源码包的服务能被chkconfig命令管理</p>
<figure class="highlight bash"><table><tr><td class="code"><pre><span class="line"><span class="comment"># 1. 先打开脚本文件</span></span><br><span class="line">vim /etc/init.d/apache</span><br><span class="line"><span class="comment"># 2. 然后在脚本的开头加入下面两行代码:</span></span><br><span class="line"><span class="comment"># chkconfig: 35 86 76</span></span><br><span class="line"><span class="comment"># description: source package apache</span></span><br><span class="line"><span class="comment"># 注:上面的#并不是注释,是用来指定httpd服务脚本可以被chkconfig命令管理。</span></span><br><span class="line"><span class="comment"># 第一行的格式是:chkconfig: 运行级别 启动顺序 关闭顺序</span></span><br><span class="line"><span class="comment"># 第二行的格式是:description: 说明内容(随意)</span></span><br><span class="line"></span><br><span class="line"><span class="comment"># 3. 最后将apache服务加入chkconfig命令进行管理</span></span><br><span class="line">chkconfig --add apache</span><br></pre></td></tr></table></figure>
</li>
</ol>
<h3 id="查看已开启的服务(推荐通过端口来判断)">查看已开启的服务(推荐通过端口来判断)</h3><ol>
<li><p>查看系统运行了哪些进程,来判断启动了哪些服务。<br> (但是系统中不光是服务会启动进程,一些系统程序也会启动进程,所以查出来的结果会比较多)<br> 列出系统中所有的进程:</p>
<figure class="highlight bash"><table><tr><td class="code"><pre><span class="line">ps aux</span><br></pre></td></tr></table></figure>
</li>
<li><p>查看系统打开了哪些端口,来判断启动了哪些服务。<br> (/etc/service文件保存了所有常规端口对应的服务)<br> 列出系统中所有已启动的服务:</p>
<figure class="highlight bash"><table><tr><td class="code"><pre><span class="line">netstat -tlunp </span><br><span class="line">-t 列出tcp数据</span><br><span class="line">-u 列出udp数据</span><br><span class="line"><span class="operator">-l</span> 列出正在监听的网络服务(不包含已经连接的网络服务)</span><br><span class="line">-n 用端口号来显示服务,而不是用服务名</span><br><span class="line">-p 列出该服务的进程ID(PID)</span><br></pre></td></tr></table></figure></li>
</ol>
</div>
<footer class="article-footer clearfix">
<div class="article-catetags">
<div class="article-categories">
<span></span>
<a class="article-category-link" href="/categories/Linux/">Linux</a>
</div>
<div class="article-tags">
<span></span> <a href="/tags/Linux/">Linux</a><a href="/tags/服务/">服务</a>
</div>
</div>
<div class="article-share" id="share">
<div data-url="http://qq2867234.github.io/2016/03/14/Linux-service-manager/" data-title="Linux的服务管理 | Shadow" data-tsina="undefined" class="share clearfix">
</div>
</div>
</footer>
</article>
<nav class="article-nav clearfix">
<div class="next">
<a href="/2016/03/05/The-underlying-implementation-of-common-container/" title="Java常用容器的实现原理">
<strong>下一篇:</strong><br/>
<span>Java常用容器的实现原理
</span>
</a>
</div>
</nav>
<section id="comments" class="comment">
<div class="ds-thread" data-thread-key="2016/03/14/Linux-service-manager/" data-title="Linux的服务管理" data-url="http://qq2867234.github.io/2016/03/14/Linux-service-manager/"></div>
</section>
</div>
<div class="openaside"><a class="navbutton" href="#" title="显示侧边栏"></a></div>
<div id="toc" class="toc-aside">
<strong class="toc-title">文章目录</strong>
<ol class="toc"><li class="toc-item toc-level-3"><a class="toc-link" href="#系统运行级别"><span class="toc-number">1.</span> <span class="toc-text">系统运行级别</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#服务的分类"><span class="toc-number">2.</span> <span class="toc-text">服务的分类</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#查看已安装的服务"><span class="toc-number">3.</span> <span class="toc-text">查看已安装的服务</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#启动RPM包安装的服务"><span class="toc-number">4.</span> <span class="toc-text">启动RPM包安装的服务</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#启动源码包安装的服务"><span class="toc-number">5.</span> <span class="toc-text">启动源码包安装的服务</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#RPM安装服务的自启动"><span class="toc-number">6.</span> <span class="toc-text">RPM安装服务的自启动</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#源码包安装服务的自启动"><span class="toc-number">7.</span> <span class="toc-text">源码包安装服务的自启动</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#查看已开启的服务(推荐通过端口来判断)"><span class="toc-number">8.</span> <span class="toc-text">查看已开启的服务(推荐通过端口来判断)</span></a></li></ol>
</div>
<div id="asidepart">
<div class="closeaside"><a class="closebutton" href="#" title="隐藏侧边栏"></a></div>
<aside class="clearfix">
<div class="categorieslist">
<p class="asidetitle">分类</p>
<ul>
<li><a href="/categories/Java/" title="Java">Java<sup>1</sup></a></li>
<li><a href="/categories/Linux/" title="Linux">Linux<sup>1</sup></a></li>
<li><a href="/categories/MySQL/" title="MySQL">MySQL<sup>2</sup></a></li>
<li><a href="/categories/Web/" title="Web">Web<sup>1</sup></a></li>
</ul>
</div>
<div class="rsspart">
<a href="/atom.xml" target="_blank" title="rss">RSS 订阅</a>
</div>
</aside>
</div>
</div>
<footer><div id="footer" >
<div class="line">
<span></span>
<div class="author"></div>
</div>
<section class="info">
<p> Hello, I'm Jason. This is my blog on GitHub. <br/>
Every day a little better than yesterday</p>
</section>
<div class="social-font" class="clearfix">
<a href="http://weibo.com/2609473321" target="_blank" class="icon-weibo" title="微博"></a>
<a href="https://github.com/qq2867234" target="_blank" class="icon-github" title="github"></a>
</div>
<p class="copyright">
Powered by <a href="http://hexo.io" target="_blank" title="hexo">hexo</a> and Theme by <a href="https://github.com/wuchong/jacman" target="_blank" title="Jacman">Jacman</a> © 2016
<a href="/about" target="_blank" title="Shadow">Shadow</a>
</p>
</div>
</footer>
<script src="/js/jquery-2.0.3.min.js"></script>
<script src="/js/jquery.imagesloaded.min.js"></script>
<script src="/js/gallery.js"></script>
<script src="/js/jquery.qrcode-0.12.0.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$('.navbar').click(function(){
$('header nav').toggleClass('shownav');
});
var myWidth = 0;
function getSize(){
if( typeof( window.innerWidth ) == 'number' ) {
myWidth = window.innerWidth;
} else if( document.documentElement && document.documentElement.clientWidth) {
myWidth = document.documentElement.clientWidth;
};
};
var m = $('#main'),
a = $('#asidepart'),
c = $('.closeaside'),
o = $('.openaside');
c.click(function(){
a.addClass('fadeOut').css('display', 'none');
o.css('display', 'block').addClass('fadeIn');
m.addClass('moveMain');
});
o.click(function(){
o.css('display', 'none').removeClass('beforeFadeIn');
a.css('display', 'block').removeClass('fadeOut').addClass('fadeIn');
m.removeClass('moveMain');
});
$(window).scroll(function(){
o.css("top",Math.max(20,260-$(this).scrollTop()));
});
$(window).resize(function(){
getSize();
/*if (myWidth >= 1024) {
$('header nav').removeClass('shownav');
}else{
m.removeClass('moveMain');
a.css('display', 'block').removeClass('fadeOut');
o.css('display', 'none');
$('#toc.toc-aside').css('display', 'none');
}*/
});
});
</script>
<script type="text/javascript">
$(document).ready(function(){
var ai = $('.article-content>iframe'),
ae = $('.article-content>embed'),
t = $('#toc'),
ta = $('#toc.toc-aside'),
o = $('.openaside'),
c = $('.closeaside');
if(ai.length>0){
ai.wrap('<div class="video-container" />');
};
if(ae.length>0){
ae.wrap('<div class="video-container" />');
};
c.click(function(){
ta.css('display', 'block').addClass('fadeIn');
});
o.click(function(){
ta.css('display', 'none');
});
$(window).scroll(function(){
ta.css("top",Math.max(80,320-$(this).scrollTop()));
});
});
</script>
<script type="text/javascript">
$(document).ready(function(){
var $this = $('.share'),
url = $this.attr('data-url'),
encodedUrl = encodeURIComponent(url),
title = $this.attr('data-title'),
tsina = $this.attr('data-tsina'),
description = $this.attr('description');
var html = [
'<div class="hoverqrcode clearfix"></div>',
'<a class="overlay" id="qrcode"></a>',
'<a href="https://www.facebook.com/sharer.php?u=' + encodedUrl + '" class="article-share-facebook" target="_blank" title="Facebook"></a>',
'<a href="https://twitter.com/intent/tweet?url=' + encodedUrl + '" class="article-share-twitter" target="_blank" title="Twitter"></a>',
'<a href="#qrcode" class="article-share-qrcode" title="微信"></a>',
'<a href="http://widget.renren.com/dialog/share?resourceUrl=' + encodedUrl + '&srcUrl=' + encodedUrl + '&title=' + title +'" class="article-share-renren" target="_blank" title="人人"></a>',
'<a href="http://service.weibo.com/share/share.php?title='+title+'&url='+encodedUrl +'&ralateUid='+ tsina +'&searchPic=true&style=number' +'" class="article-share-weibo" target="_blank" title="微博"></a>',
'<span title="Share to"></span>'
].join('');
$this.append(html);
$('.hoverqrcode').hide();
var myWidth = 0;
function updatehoverqrcode(){
if( typeof( window.innerWidth ) == 'number' ) {
myWidth = window.innerWidth;
} else if( document.documentElement && document.documentElement.clientWidth) {
myWidth = document.documentElement.clientWidth;
};
var qrsize = myWidth > 1024 ? 200:100;
var options = {render: 'image', size: qrsize, fill: '#2ca6cb', text: url, radius: 0.5, quiet: 1};
var p = $('.article-share-qrcode').position();
$('.hoverqrcode').empty().css('width', qrsize).css('height', qrsize)
.css('left', p.left-qrsize/2+20).css('top', p.top-qrsize-10)
.qrcode(options);
};
$(window).resize(function(){
$('.hoverqrcode').hide();
});
$('.article-share-qrcode').click(function(){
updatehoverqrcode();
$('.hoverqrcode').toggle();
});
$('.article-share-qrcode').hover(function(){}, function(){
$('.hoverqrcode').hide();
});
});
</script>
<script type="text/javascript">
var duoshuoQuery = {short_name:"chenjiusheng"};
(function() {
var ds = document.createElement('script');
ds.type = 'text/javascript';ds.async = true;
ds.src = '//static.duoshuo.com/embed.js';
ds.charset = 'UTF-8';
(document.getElementsByTagName('head')[0]
|| document.getElementsByTagName('body')[0]).appendChild(ds);
})();
</script>
<link rel="stylesheet" href="/fancybox/jquery.fancybox.css" media="screen" type="text/css">
<script src="/fancybox/jquery.fancybox.pack.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$('.article-content').each(function(i){
$(this).find('img').each(function(){
if ($(this).parent().hasClass('fancybox')) return;
var alt = this.alt;
if (alt) $(this).after('<span class="caption">' + alt + '</span>');
$(this).wrap('<a href="' + this.src + '" title="' + alt + '" class="fancybox"></a>');
});
$(this).find('.fancybox').each(function(){
$(this).attr('rel', 'article' + i);
});
});
if($.fancybox){
$('.fancybox').fancybox();
}
});
</script>
<!-- Analytics Begin -->
<!-- Analytics End -->
<!-- Totop Begin -->
<div id="totop">
<a title="返回顶部"><img src="/img/scrollup.png"/></a>
</div>
<script src="/js/totop.js"></script>
<!-- Totop End -->
<!-- MathJax Begin -->
<!-- mathjax config similar to math.stackexchange -->
<!-- MathJax End -->
<!-- Tiny_search Begin -->
<!-- Tiny_search End -->
</body>
</html> |
<h1>Post</h1>
<p>Earlier today I decided to write up a quick wrapper to the <a href="https://www.ibm.com/watson/developercloud/tone-analyzer.html">IBM Watson Tone Analyzer</a> using <a href="https://developer.ibm.com/openwhisk/">OpenWhisk</a>. It ended up being so incredibly trivial I doubted it made sense to even blog about it, but then I realized - this is part of what makes OpenWhisk, and serverless, so incredible.</p>
<p>I was able to deploy a function that acts as a proxy to the REST APIs Tone Analyzer uses. All this action does is literally expose the Watson Developer npm package interface to an OpenWhisk user. Here it is in its entirety:</p>
<pre><code class="language-javascript">var watson = require('watson-developer-cloud');
function main(args) {
var tone_analyzer = watson.tone_analyzer({
username: args.username,
password: args.password,
version: 'v3',
version_date: '2016-05-19'
});
return new Promise( (resolve, reject) => {
tone_analyzer.tone({text:args.text}, (err, tone) => {
if(err) return reject(err);
return resolve(tone);
});
});
}
exports.main = main;
</code></pre>
<p>If you weren't aware, the <a href="https://www.npmjs.com/package/watson-developer-cloud">watson-developer-cloud</a> package provides simple Node interfaces for over twenty different Watson services. And how well does it handle it? I've got one block of code to create an instance of <code>watson.tone_analyzer</code> and one call to <code>tone</code> to perform the analysis.</p>
<p>So yes - my code here is stupid simple, but within seconds I was able to deploy this to OpenWhisk in a package, mark the package shared, and now it's available to any OpenWhisk user. I can also use it with other actions as part of a sequence. You do need to provision the service in Bluemix of course, but that's fairly trivial to do as well.</p>
<p>This is <em>exactly</em> the kind of thing that is making me love serverless more and more every day. I didn't have to provision a server. I didn't have to setup Express or heck, even a Node.js server in general. I wrote my function and was done. In terms of cost - I just pay for my Tone Analyzer usage and I only pay for my action when it's actually invoked.</p>
<p>Here's an example of it in action. First, the call:</p>
<pre><code class="language-javascript">wsk action invoke "/[email protected]_My Space/watson/tone"
--param username secret --param password ilovecats
--param text "I am so mad!" -b -r
</code></pre>
<p>And the result. It's a pretty big set of data, and my input was <em>way</em> too small, but it certainly did pick up on the anger.</p>
<pre><code class="language-javascript">{
"document_tone": {
"tone_categories": [
{
"category_id": "emotion_tone",
"category_name": "Emotion Tone",
"tones": [
{
"score": 0.881688,
"tone_id": "anger",
"tone_name": "Anger"
},
{
"score": 0.022428,
"tone_id": "disgust",
"tone_name": "Disgust"
},
{
"score": 0.074133,
"tone_id": "fear",
"tone_name": "Fear"
},
{
"score": 0.006716,
"tone_id": "joy",
"tone_name": "Joy"
},
{
"score": 0.092043,
"tone_id": "sadness",
"tone_name": "Sadness"
}
]
},
{
"category_id": "language_tone",
"category_name": "Language Tone",
"tones": [
{
"score": 0,
"tone_id": "analytical",
"tone_name": "Analytical"
},
{
"score": 0,
"tone_id": "confident",
"tone_name": "Confident"
},
{
"score": 0,
"tone_id": "tentative",
"tone_name": "Tentative"
}
]
},
{
"category_id": "social_tone",
"category_name": "Social Tone",
"tones": [
{
"score": 0.022751,
"tone_id": "openness_big5",
"tone_name": "Openness"
},
{
"score": 0.234966,
"tone_id": "conscientiousness_big5",
"tone_name": "Conscientiousness"
},
{
"score": 0.366922,
"tone_id": "extraversion_big5",
"tone_name": "Extraversion"
},
{
"score": 0.567783,
"tone_id": "agreeableness_big5",
"tone_name": "Agreeableness"
},
{
"score": 0.001604,
"tone_id": "emotional_range_big5",
"tone_name": "Emotional Range"
}
]
}
]
}
}
</code></pre>} |
import { useState, useRef } from 'react';
import { Button, Label, Spinner, Textarea, TextInput } from 'flowbite-react';
import useAnalyzeTransactions from '~/hooks/analyze-transactions';
const AnalyzeTransactionsForm = ({ accountId, setOpenModal }) => {
const ref = useRef(null);
const [form, setForm] = useState({
accountId,
query: 'Could you categorize each transaction into tax categories? Show results in a bulleted list.'
});
const { trigger } = useAnalyzeTransactions(accountId, form.query);
const [isLoading, setIsLoading] = useState(false);
const onClickCancel = () => {
setForm({ accountId: '', query:'Could you categorize each transaction into tax categories? Show results in a bulleted list.'});
ref.current.value = '';
setIsLoading(false);
setOpenModal(false);
};
const onSubmit = async () => {
setIsLoading(true);
const response = await trigger(form);
if (response.status === 200) {
ref.current.value = response.data;
setIsLoading(false);
} else {
setIsLoading(false);
}
};
const onChangeQuery = (e) => setForm({ ...form, query: e.target.value });
return (
<div className="space-y-6">
<div className="mb-4">
<div className="mb-2 block">
<Label htmlFor="query" value="Query:" />
</div>
<TextInput
id="query"
onChange={onChangeQuery}
placeholder="Could you categorize each transaction into tax categories? Show results in a bulleted list."
required
value={form.query}
/>
</div>
<div className="mb-4">
<div className="mb-2 block">
<Textarea ref={ref} id="results" name="results" />
</div>
</div>
<div className="w-full flex justify-between pt-4">
<Button color="light" onClick={onClickCancel}>
Cancel
</Button>
<Button color="dark" onClick={onSubmit}>
{isLoading ? <Spinner color="white" size="md" /> : 'Submit'}
</Button>
</div>
</div>
);
};
export default AnalyzeTransactionsForm; |
import {RequestHandler} from 'express';
import {validationResult} from 'express-validator';
import bcrypt from 'bcryptjs';
import jsonwebtoken from 'jsonwebtoken';
import HttpError from '../errors/HttpError';
import NotFoundError from '../errors/NotFoundError';
import {PrismaClient} from '@prisma/client';
const prisma = new PrismaClient();
export const signUp: RequestHandler = async (req, res, next) => {
const errors = validationResult(req);
const name = (req.body as {name: string}).name;
const email = (req.body as {email: string}).email;
const role = (req.body as {role: string}).role;
const imgUrl = (req.body as {imgUrl: string}).imgUrl;
const password = (req.body as {password: string}).password;
if (errors.isEmpty()) {
const hashedPassword = await bcrypt.hash(password, 12);
let newUser;
try {
newUser = await prisma.user.create({
data: {
name: name,
email: email,
password: hashedPassword,
role: role,
img_url: imgUrl,
}
});
} catch (err) {
next(new HttpError('Could not create account!'));
}
let token;
try {
if (newUser) {
const secretKey: string = process.env.SECRET_KEY!;
token = jsonwebtoken.sign({
userId: newUser.id,
email: newUser.email
}, secretKey, {
expiresIn: '6h'
});
}
} catch (err) {
next(new HttpError('Registration is failed!'));
}
res.status(201).json({
message: 'Your account was created!',
user: newUser,
token: token,
expiration: 3600 * 1000 * 60
});
} else {
errors.array().map(e => next(new HttpError(e.msg, 400)));
}
};
export const login: RequestHandler = async (req, res, next) => {
const email = (req.body as {email: string}).email;
const password = (req.body as {password: string}).password;
let user;
try {
user = await prisma.user.findUnique({
where: {
email: email
}
});
} catch (err) {
next(new HttpError('Could not find user with entered email!'));
}
if (user) {
let token;
let isValidPassword = false;
isValidPassword = await bcrypt.compare(password, user.password);
if (isValidPassword) {
const secretKey: string = process.env.SECRET_KEY!;
token = jsonwebtoken.sign({
userId: user.id,
email: user.email
}, secretKey, {
expiresIn: '6h'
});
res.status(200).json({
message: 'User was authenticated!',
user: {
id: user.id,
name: user.name,
email: user.email,
currentProject: user.current_project_id
},
token,
expiration: 3600 * 1000 * 6
});
} else {
next(new HttpError('You entered wrong e-mail or password!', 401));
}
} else {
next(new HttpError('You entered wrong e-mail or password!', 401));
}
}
export const users: RequestHandler = async (req, res, next) => {
try {
const users = await prisma.user.findMany();
if (users) {
res.status(200).json({
users: users
});
} else {
next(new NotFoundError('Users were not found!'));
}
} catch (err) {
next(new HttpError('Could not find users!'));
}
}; |
<template>
<div class="proForm">
<div class="proForm_wrapper">
<h2>{{titleName}}</h2>
<el-form ref="proForm"
:model="proForm"
:rules="rules"
label-width="130px"
:label-position="labelPosition">
<el-form-item label="商品标识:"
prop="proType">
<el-radio-group v-model="proForm.proType">
<el-radio :label="1">药品</el-radio>
<el-radio :label="2">其他</el-radio>
</el-radio-group>
</el-form-item>
<el-form-item label="系统商品编号:"
prop="erpPid">
<el-input v-model="proForm.erpPid"
placeholder="请输入系统商品编号"></el-input>
</el-form-item>
<el-form-item label="类别编号:"
prop="ClsId">
<a-proCascader @clsparidChange="getclsparidChange($event)"
ref="cls"></a-proCascader>
<el-input v-model="proForm.ClsId"
v-show="false"></el-input>
</el-form-item>
<el-form-item label="品牌编号:"
prop="brandID">
<el-input v-model="proForm.brandID"
placeholder="请输入品牌编号"></el-input>
</el-form-item>
<el-form-item label="商品名称:"
prop="proName">
<el-input v-model="proForm.proName"
v-on:input="getPYcode"
placeholder="请输入系统商品名称"></el-input>
</el-form-item>
<el-form-item label="商品标签:"
prop="proTag">
<el-input v-model="proForm.proTag"
placeholder="请输入商品标签"></el-input>
</el-form-item>
<el-form-item label="助记码:"
prop="mnemonic">
<el-input v-model="proForm.mnemonic"
v-on:input="getPYcode"
placeholder="请输入助记码"></el-input>
</el-form-item>
<el-form-item label="商品条形码:"
prop="proBarcode">
<el-input v-model="proForm.proBarcode"
placeholder="请输入商品条形码"></el-input>
</el-form-item>
<el-form-item label="产地:"
prop="proArea">
<el-input v-model="proForm.proArea"
placeholder="请输入产地"></el-input>
</el-form-item>
<el-form-item label="规格:"
prop="proSize">
<el-input v-model="proForm.proSize"
placeholder="请输入规格"></el-input>
</el-form-item>
<el-form-item label="总部价:"
prop="proPrice">
<el-input v-model="proForm.proPrice"
placeholder="请输入总部价"></el-input>
</el-form-item>
<el-form-item label="商业模板:">
<div class="proTemplateList">
<div v-for="(item, index) in tmpUrl"
:key="index"
class="proTemplateItem"
:class="resultNum === index?'sel':''"
@click="getTemp(item,index)">
<img :src="item.url">
<p>{{item.name}}</p>
</div>
</div>
</el-form-item>
<el-form-item label="商品描述:"
prop="proDesc">
<wangEditor :value="proForm.proDesc.val"
:isUpload=true
:isFullEditor=true
:isViewSource=true></wangEditor>
</el-form-item>
<el-form-item label="橱窗图:"
prop="gallezyImg">
<el-input v-model="proForm.gallezyImg"
placeholder="请输入橱窗图"></el-input>
</el-form-item>
<el-form-item label="图片组"
prop="pImgJson">
<el-input v-model="proForm.pImgJson.val"></el-input>
<upLoadFile :limitNum=4
:multipleB=true
:showFileList=true
:fileExtensionName="fileExName"
:isFileSize=2
:getFileJson.sync="proForm.pImgJson"
ref="fileImg"
butText="点击选择上传文件"
listType="picture-card"></upLoadFile>
</el-form-item>
<el-form-item label="商品状态:"
prop="proFlag">
<el-radio-group v-model="proForm.proFlag">
<el-radio :label="1">上架</el-radio>
<el-radio :label="2">下架</el-radio>
<el-radio :label="3">冻结</el-radio>
</el-radio-group>
</el-form-item>
<el-form-item label="是否处方药:"
v-show="this.proForm.proType ===1"
prop="ethicalsFlag">
<el-radio-group v-model="proForm.ethicalsFlag">
<el-radio :label="0">不是处方药</el-radio>
<el-radio :label="1">是处方药</el-radio>
</el-radio-group>
</el-form-item>
<el-form-item label="是否医保品种:"
v-show="this.proForm.proType ===1"
prop="policyFlag">
<el-radio-group v-model="proForm.policyFlag">
<el-radio :label="0">不是</el-radio>
<el-radio :label="1">是</el-radio>
</el-radio-group>
</el-form-item>
<el-form-item label="是否包邮:"
prop="mailFlag">
<el-radio-group v-model="proForm.mailFlag">
<el-radio :label="0">不包邮</el-radio>
<el-radio :label="1">包邮</el-radio>
</el-radio-group>
</el-form-item>
<el-form-item label="是否限购:"
prop="salesFlag">
<el-radio-group v-model="proForm.salesFlag">
<el-radio :label="0">不限购</el-radio>
<el-radio :label="1">限购(与商品库存挂钩)</el-radio>
</el-radio-group>
</el-form-item>
<el-form-item label="单件送积分:"
prop="proCredit"
type="number">
<el-input v-model.number="proForm.proCredit"
placeholder="请输入单件送积分"></el-input>
</el-form-item>
<el-form-item label="是否参与促销:"
prop="promotionsFlag">
<el-radio-group v-model="proForm.promotionsFlag">
<el-radio :label="0">不参与</el-radio>
<el-radio :label="1">参与</el-radio>
</el-radio-group>
</el-form-item>
<el-form-item label="上架日期:"
prop="saleBeginTime">
<el-date-picker v-model="proForm.saleBeginTime"
type="datetime"
value-format="yyyy-MM-dd HH:mm:ss"
placeholder="选择上架日期时间">
</el-date-picker>
</el-form-item>
<el-form-item label="下架日期:"
prop="saleEndTime">
<el-date-picker v-model="proForm.saleEndTime"
type="datetime"
value-format="yyyy-MM-dd HH:mm:ss"
placeholder="选择下架日期时间">
</el-date-picker>
</el-form-item>
<el-form-item>
<el-button type="primary"
@click="SubmitFrom('proForm')">{{buttonStatus}}</el-button>
<el-button @click="resetForm('proForm')">重置</el-button>
</el-form-item>
</el-form>
</div>
<div class="proForm_preview">
<div class="hd">
<a class="btn act"
@click="applyTemp">点击应用此模板(<font style="#c00">!!使用模板将替换原来数据</font>)</a>
<a class="btn cls">关闭</a>
</div>
<div class="bd">
<div class="con">
<component :is="currentView"
ref="tempView"></component>
</div>
</div>
</div>
</div>
</template>
<script>
import upLoadFile from "@/components/publicComponents/upLoadFile/upLoadFileByOss"
import wangEditor from "@/components/publicComponents/wangEditor/wangEditor"
import { addProduct } from "@/api/api.js"
import { makePy } from "../../../../publicComponents/mnemonicCode/initials"
import { constants } from 'fs';
import Vue from 'vue'
import { format } from 'util'
export default {
components: {
upLoadFile,
wangEditor
},
data () {
return {
titleName: "商品添加",
buttonStatus: '',
labelPosition: "right",
fileExName: ['jpg', 'gif', 'png'],
proForm: {
erpPid: '',
ClsId: '',
brandID: '',
proName: '',
mnemonic: '',
proBarcode: '',
proArea: '',
proSize: '',
proPrice: '',
proDesc: { val: '' },
gallezyImg: '',
pImgJson: { val: '' },
proFlag: '',
proType: '',
proTag: '',
ethicalsFlag: 0,
policyFlag: 0,
mailFlag: '',
salesFlag: '',
proCredit: '',
promotionsFlag: '',
saleBeginTime: '',
saleEndTime: ''
},
tmpUrl: [
{ name: '通用', url: require('../images/T-icon/1.jpg'), templateName: 'Template0' }
],
rules: {
erpPid: [{ required: true, message: '系统商品编号不能为空', trigger: 'blur' }],
//ClsId: [{ required: true, message: '类别编号不能为空', trigger: 'blur' }],
//brandID: [{ required: true, message: '品牌编号不能为空', trigger: 'blur' }],
proName: [{ required: true, message: '商品名称不能为空', trigger: 'blur' }],
// mnemonic: [{ required: true, message: '助记码不能为空', trigger: 'blur' }],
// proBarcode: [{ required: true, message: '商品条形码不能为空', trigger: 'blur' }],
// proArea: [{ required: true, message: '产地不能为空', trigger: 'blur' }],
// proSize: [{ required: true, message: '规格不能为空', trigger: 'blur' }],
proPrice: [
{ required: true, message: '请填写价格,最大8位数,保留两位小数点' },
{ pattern: /^\d{1,8}(\.\d{1,2})?$/, message: '必须为数字,最大8位数,精确两位小数点' }
],
//proDesc: [{ required: true, message: '商品描述不能为空', trigger: 'blur' }],
gallezyImg: [{ required: true, message: '橱窗图不能为空', trigger: 'blur' }],
//pImgJson: [{ required: true, message: '请上传图片', trigger: 'blur' }],
proFlag: [{ required: true, message: '请选择商品状态', trigger: 'blur' }],
proType: [{ required: true, message: '请选择', trigger: 'blur' }],
//proTag: [{ required: true, message: '请输入', trigger: 'blur' }],
ethicalsFlag: [{ required: true, message: '请选择是否为处方药', trigger: 'blur' }],
policyFlag: [{ required: true, message: '请选择是否医保品种', trigger: 'blur' }],
mailFlag: [{ required: true, message: '请选择是否包邮', trigger: 'blur' }],
salesFlag: [{ required: true, message: '请选择是否限购', trigger: 'blur' }],
proCredit: [{ required: true, message: '单选送积分不能为空', trigger: 'change' }, { type: 'number', message: '只能输入数字', trigger: 'blur' }],
promotionsFlag: [{ required: true, message: '请选择是否参与促销', trigger: 'blur' }],
saleBeginTime: [{ required: true, message: '请选择上架日期', trigger: 'blur' }],
saleEndTime: [{ required: true, message: '请选择下架日期', trigger: 'blur' }]
},
tmpNum: '',
currentView: ''
}
},
mounted () {
this.showContent()
this.createTmpUrl()
},
computed: {
resultNum () { return this.tmpNum }
},
methods: {
createTmpUrl () {//生成模板数据
for (var i = 1; i <= 68; i++) {
this.tmpUrl.push({
name: "模板" + i, url: require("../images/T-icon/" + i + ".jpg")
})
}
},
getPYcode () {//助记码转换
const cname = this.proForm.proName
const getname = makePy(cname)[0]
this.proForm.mnemonic = getname
},
getTemp (item, index) {
this.tmpNum = index;
import(`../templates/template${index}.vue`).then(res => {
Vue.component(`template${index}`, res.default)
this.currentView = `template${index}`
})
},
applyTemp () {
const temp = this.$refs.tempView.$el
const newTemp = temp.cloneNode(true)
let tmpNode = document.createElement("div")
tmpNode.appendChild(newTemp)
const strHtml = tmpNode.innerHTML
tmpNode = null
this.proForm.proDesc.val = strHtml
},
getclsparidChange (msg) {
this.proForm.ClsId = msg
},
showContent () {
var formStatus = this.formStatus
if (formStatus === 0) {
this.titleName = "商品信息添加"
this.buttonStatus = "立即创建"
}
if (formStatus === 1) {
this.titleName = "商品信息修改"
this.buttonStatus = "提交修改"
}
},
SubmitFrom (formname) {
this.$refs[formname].validate((valid) => {
//console.log(valid);
var formStatus = this.formStatus
if (valid) {
if (formStatus === 0) {
let postList = {
"erpPid": this.proForm.erpPid,
"ClsId": this.proForm.ClsId,
"brandID": this.proForm.brandID,
"proName": this.proForm.proName,
"mnemonic": this.proForm.mnemonic,
"proBarcode": this.proForm.mnemonic,
"proArea": this.proForm.proArea,
"proSize": this.proForm.proSize,
"proPrice": this.proForm.proPrice,
"proDesc": this.proForm.proDesc.val,
"gallezyImg": this.proForm.gallezyImg,
"pImgJson": this.proForm.pImgJson.val,
"proFlag": this.proForm.proFlag,
"proType": this.proForm.proType,
"proTag": this.proForm.proTag,
"ethicalsFlag": this.proForm.ethicalsFlag,
"policyFlag": this.proForm.policyFlag,
"mailFlag": this.proForm.mailFlag,
"salesFlag": this.proForm.salesFlag,
"proCredit": this.proForm.proCredit,
"promotionsFlag": this.proForm.promotionsFlag,
"saleBeginTime": this.proForm.saleBeginTime,
"saleEndTime": this.proForm.saleEndTime
}
addProduct(postList).then(res => {
res = res.data
if (res.success === true) {
console.info(res.returnData)
this.$message.success(res.msgStr)
this.$router.push({
path: '/adminProList'
})
} else if (res.success === false) {
this.$message.error(res.msgStr)
console.table(res.returnData)
} else { return; }
})
//console.info(postList)
//console.table(postList)
}
if (formStatus === 1) {
console.log('submit')
}
} else {
//console.log('error')
this.$message.error('数据校验不通过')
return false
}
})
},
resetForm () { }
},
props: ['formStatus']
}
</script>
<style lang="scss">
@import "./adminProForm";
</style> |
import TextInput from '@/components/common/TextInput/TextInput';
import { ArticlesController } from '@/http/articles';
import { CreateArticleInput } from '@/types/articles';
import { errorHandler } from '@/utils/errorHandler';
import { Button, Paper, Typography } from '@mui/material';
import { useState } from 'react';
import { SubmitHandler, useForm } from 'react-hook-form';
function CreateArticleForm() {
const {
register,
reset,
handleSubmit,
formState: { errors },
} = useForm<CreateArticleInput>();
const [error, setError] = useState('');
const submitHandler: SubmitHandler<CreateArticleInput> = async (data) => {
try {
await ArticlesController.createArticle(data);
reset();
} catch (error: any) {
setError(errorHandler(error));
}
};
return (
<Paper
elevation={3}
style={{ padding: '30px', width: 'min(600px, 100% - 40px)' }}
>
<form
style={{ display: 'flex', flexDirection: 'column', gap: '20px' }}
onSubmit={handleSubmit(submitHandler)}
>
<TextInput
label="Title"
error={errors.title}
props={register('title', { required: 'Title is required' })}
/>
<TextInput
label="Creator"
error={errors.creator}
props={register('creator', { required: 'Creator is required' })}
/>
<TextInput
label="Description"
error={errors.description}
props={register('description', {
required: 'Description is required',
})}
/>
<TextInput
label="Content"
error={errors.content}
props={register('content', { required: 'Content is required' })}
/>
<TextInput
label="Link"
error={errors.link}
props={register('link', { required: 'Link is required' })}
/>
<TextInput
label="Guid"
error={errors.guid}
props={register('guid', { required: 'Guid is required' })}
/>
<TextInput
label="Publish Date"
error={errors.pubDate}
props={register('pubDate', { required: 'Publish Date is required' })}
/>
<Button variant="contained" type="submit">
Create
</Button>
{error && (
<Typography
fontSize={'14px'}
textAlign={'center'}
color={'red'}
padding={'10px'}
>
{error}
</Typography>
)}
</form>
</Paper>
);
}
export default CreateArticleForm; |
import { PrismaClient } from "@prisma/client";
import createOrders from "./Order";
import createProducts from "./Product";
import createProductLines from "./ProductLine";
import createUsers from "./User";
const prisma = new PrismaClient();
async function main() {
console.log("Start seeding ...");
createProductLines(prisma).then(() => {
console.log("Product lines created");
createProducts(prisma).then(() => {
console.log("Products created");
createUsers(prisma).then(() => {
console.log("Users created");
createOrders(prisma).then(() => {
console.log("Orders created");
});
});
});
});
}
main()
.then(async () => {
await prisma.$disconnect();
})
.catch(async (e) => {
console.error(e);
await prisma.$disconnect();
process.exit(1);
}); |
<!doctype html>
<html lang="en">
<head>
<!-- Required meta tags -->
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<!-- Bootstrap CSS -->
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" integrity="sha384-MCw98/SFnGE8fJT3GXwEOngsV7Zt27NXFoaoApmYm81iuXoPkFOJwJ8ERdknLPMO" crossorigin="anonymous">
<title>Dynamic Downhill</title>
</head>
<body>
<div class="container">
<!--NAV-->
<nav class="navbar navbar-expand-lg navbar-light bg-warning">
<a class="navbar-brand" href="#">DD</a>
<button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarSupportedContent" aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation">
<span class="navbar-toggler-icon"></span>
</button>
<div class="collapse navbar-collapse" id="navbarSupportedContent">
<ul class="navbar-nav mr-auto">
<li class="nav-item active">
<a class="nav-link" href="#about">About <span class="sr-only">(current)</span></a>
</li>
<li class="nav-item">
<a class="nav-link" href="#products">Products</a>
</li>
<li class="nav-item">
<a class="nav-link" href="#sale">Sale!</a>
</li>
</ul>
<form class="form-inline my-2 my-lg-0">
<input class="form-control mr-sm-2" type="search" placeholder="Search" aria-label="Search">
<button class="btn btn-primary my-2 my-sm-0" type="submit">Search</button>
</form>
</div>
</nav>
<!--/NAV-->
<!--JUMBOTRON-->
<div class="jumbotron jumbotron-fluid bg-warning text-center">
<div class="container">
<h1 class="display-4 text-primary">Dynamic Downhill</h1>
<p class="lead">You wouldn't want to be anywhere else on the web right now!</p>
</div>
</div>
<!--/JUMBOTRON-->
<!--DEALS-->
<div class="jumbotron jumbotron-fluid bg-dark mt-5 text-center">
<div class="container">
<h1 class="display-4 hidden-sm-down" style="color:#fff;font-family:roboto;font-weight:900;text-transform:uppercase">gear deals</h1>
<p class="lead text-warning">Click the link below to sign up for this month's gear deals!</p>
<button type="button" class="btn btn-outline-primary" data-toggle="modal" data-target="#register">Monthly Deals</button>
</div>
</div>
<!--/DEALS-->
<!--ALERT-->
<div class="alert alert-danger text-center" role="alert">
WARNING: We only sell badass gear!
</div>
<!--/ALERT-->
<!--ABOUT-->
<div id="about" class="container my-5">
<div class="row">
<div class="col-sm">
<img class="img-fluid" src="./img/lof.jpg" alt="">
</div>
<div class="col-sm">
<h3>About Us</h3>
<p>Here at DD, we deliver passion to the world of gravity sports.</p>
<p>Our mission is to supply you with the gear you need to send it like the pro's.</p>
<p>We're here to gurantee your thrill-seeking satisfaction.</p>
<p>Check out our featured inventory in the Products section.</p>
</div>
<div class="col-sm">
<h3>Featured Items</h3>
<ul class="list-group text-center">
<li class="list-group-item">
<a class="nav-link text-primary" href="#">Never Summer Proto FR</a>
</li>
<li class="list-group-item">
<a class="nav-link text-primary" href="#">Orangatang Stimulus</a>
</li>
<li class="list-group-item">
<a class="nav-link text-primary" href="#">Bataleon Atom</a>
</li>
<li class="list-group-item">
<a class="nav-link text-primary" href="#">Rogue Slalom Trucks</a>
</li>
</ul>
</div>
</div>
</div>
<!--/ABOUT-->
<!--PRODUCTS-->
<div id="products" class="container my-5">
<h4 class="text-primary text-center">Newest Products</h4>
<div class="row text-center">
<div class="col-sm-6">
<div class="card" style="width: 18rem;">
<span class="border-bottom">
<img class="card-img-top" src="./img/atom.png" alt="Card image cap">
</span>
<div class="card-body">
<h5 class="card-title">Bataleon Atom</h5>
<p class="card-text">Strap yourself in for the ride of your life! Tested by the best and ready to rip!</p>
<a href="#" class="btn btn-primary">More Product Info</a>
</div>
<a href="#" class="badge badge-pill badge-success">Add to Cart!</a>
</div>
</div>
<div class="col-sm-6">
<div class="card" style="width: 18rem;">
<span class="border-bottom">
<img class="card-img-top" src="./img/stims.png" alt="Card image cap">
</span>
<div class="card-body">
<h5 class="card-title">Orangatang Stimulus</h5>
<p class="card-text">Hit the streets with grip and style on the new Stim's, available in 3 durometers!</p>
<a href="#" class="btn btn-primary">More Product Info</a>
</div>
<a href="#" class="badge badge-pill badge-success">Add to Cart!</a>
</div>
</div>
</div>
</div>
<!--/PRODUCTS-->
<!--SALE-->
<div id="sale" class="container my-5">
</div>
<!--/SALE-->
<!--MAILER FORM-->
<div class="container text-center my-5">
<form>
<h4 class="text-primary mb-3">Sign up for our product release mailer!</h4>
<div class="form-group">
<input type="email" class="form-control" id="exampleInputEmail1" aria-describedby="emailHelp" placeholder="Enter email">
</div>
<button type="button" class="btn btn-primary popover-dismiss" data-container="body" data-toggle="popover" data-placement="bottom" data-content="We do not under any circumstance sell customer information">Submit</button>
</form>
</div>
<!--/MAILER FORM-->
<!--FORM MODAL-->
<div class="modal" id="register" tabindex="-1" role="dialog">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title">Please provide some basic contact information</h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body">
<form>
<fieldset class="form-group">
<label for="firstname">First Name:</label>
<input type="text" class="form-control" id="fname" placeholder="Jim">
</fieldset>
<fieldset class="form-group">
<label for="firstname">Email Address:</label>
<input type="text" class="form-control" id="emailadd" placeholder="[email protected]">
</fieldset>
</form>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-primary">Save changes</button>
<button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
</div>
</div>
</div>
</div>
<!--/FORM MODAL-->
<!--FOOTER-->
<div class="container mt-5">
<ul class="nav nav-inline">
<li class="nav-item">
<small><a class="nav-link active" href="#">Rewards Program</a></small>
</li>
<li class="nav-item">
<small><a class="nav-link" href="#">Career Opportunities</a></small>
</li>
<li class="nav-item">
<small class="nav-link" href="#">©2022 Dynamic Downhill®</small>
</li>
</ul>
</div>
<!--/FOOTER-->
</div>
<!-- Optional JavaScript -->
<!-- jQuery first, then Popper.js, then Bootstrap JS -->
<script src="https://code.jquery.com/jquery-3.3.1.slim.min.js" integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo" crossorigin="anonymous"></script>
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/umd/popper.min.js" integrity="sha384-ZMP7rVo3mIykV+2+9J3UJ46jBk0WLaUAdn689aCwoqbBJiSnjAK/l8WvCWPIPm49" crossorigin="anonymous"></script>
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.min.js" integrity="sha384-ChfqqxuZUCnJSK3+MXmPNIyE6ZbWh2IMqE241rYiqJxyMiZ6OW/JmZQ5stwEULTy" crossorigin="anonymous"></script>
<!--MAILER FORM BUTTON POPOVER-->
<script>
$('.popover-dismiss').popover({
trigger: 'focus'
})</script>
</body>
</html> |
import Client from '../database';
export type Orderproduct = {
id?: string|number;
order_id: string|number;
products_id: string|number;
quantity: number,
}
export class OrderproductStore {
async index(): Promise<string | Orderproduct[]> {
try {
const conn = await Client.connect()
const sql = 'SELECT * FROM order_products'
const result = await conn.query(sql)
conn.release()
if (!result.rows[0]) {
return `Could not find order`
} else {
return result.rows}
} catch (err) {
throw new Error(`Could not get order. Error: ${err}`)
}
}
async show(id: string): Promise<string | Orderproduct>{
try {
const sql = 'SELECT * FROM order_products WHERE id=($1) '
const conn = await Client.connect()
const result = await conn.query(sql, [id])
conn.release()
if (!result.rows[0]) {
return `Could not find order ${id}`
} else {
return result.rows[0]}
} catch (err) {
throw new Error(`Could not find order ${id}. Error: ${err}`)
}
}
async create(orderproduct: Orderproduct): Promise<string|Orderproduct> {
try {
try {
const sql1 = 'SELECT id FROM products WHERE id=($1)'
const sql2 = 'SELECT id FROM orders WHERE id=($1)'
const conn = await Client.connect()
const result1 = await conn.query(sql1, [orderproduct.products_id])
const result2 = await conn.query(sql2, [orderproduct.order_id])
conn.release()
if (!result2.rows[0]) {
return `Could not find user ${orderproduct.order_id}`
}else if (!result1.rows[0]) {
return `Could not find product ${orderproduct.products_id}`
}
} catch (error) {
throw new Error(`Could not find order ${orderproduct.order_id} or products ${orderproduct.products_id}. Error: ${error}`)
}
const sql = 'INSERT INTO order_products(order_id, products_id, quantity) VALUES($1, $2, $3) RETURNING *'
const conn = await Client.connect()
const result = await conn
.query(sql, [orderproduct.order_id, orderproduct.products_id, orderproduct.quantity])
const orders = result.rows[0]
conn.release()
return orders
} catch (err) {
throw new Error(`Could not add new order ${orderproduct.id}. Error: ${err}`)
}
}
async delete(id: string): Promise<string | Orderproduct> {
try {
const sql = 'DELETE FROM order_products WHERE id=($1) RETURNING *'
const conn = await Client.connect()
const result = await conn.query(sql, [id])
const orders = result.rows[0]
conn.release()
if (!orders) {
return `Could not delete orders ${id}`
} else {
return orders}
} catch (err) {
throw new Error(`Could not delete orders ${id}. Error: ${err}`)
}
}
} |
@extends('layouts.index')
@section('content')
<div class="d-flex">
@include('components.navigation')
<div class="container">
@include('components.navbar')
@php
$eventStatus = [
['name' => 'scheduled', 'label' => 'Scheduled'],
['name' => 'on-going', 'label' => 'On-going'],
['name' => 'done', 'label' => 'Done'],
];
$disabled = $event[0]->status == "done" ? true : false;
@endphp
<div class="row">
<a href="{{route('events')}}" style="width: fit-content"
class=" d-flex align-items-center text-black fw-bold mt-2 fs-1">
<svg xmlns="http://www.w3.org/2000/svg" height="36" viewBox="0 -960 960 960" width="36">
<path d="M560-240 320-480l240-240 56 56-184 184 184 184-56 56Z"/>
</svg>
Events</a>
<hr class="mb-0">
<div class="col-12 px-0">
@if($errors->any())
<div class="alert alert-danger">{{$errors->all()[0]}}</div>
@endif
@if(session('message'))
<div id="alert" class="">
<div class="alert
@if(session('status') == 'success')
alert-success
@else
alert-danger
@endif
rounded-0">{{session('message')}}</div>
<script>
jQuery(() => {
setTimeout(() => {
$(`#alert`).remove();
}, 3000)
})
</script>
</div>
@endif
<div class="container mt-3">
<div class="row justify-content-center">
<div class="col-12 col-md-10 ">
@if(Auth::user()->user_access == 'admin')
<form enctype="multipart/form-data" method="POST"
action="{{route('event.update', $event[0]->id)}}">
@else
<form method="POST"
action="{{route('register.store', $event[0]->id)}}">
@endif
@csrf
<div class="container">
<div class="row">
<div class="col-12 col-md-10">
<div class="form-floating mb-3 input-group-lg">
<input name="eventName" type="text" class="form-control"
@if($disabled || Auth::user()->user_access != 'admin') disabled
@endif
id="eventName" value="{{$event[0]->event_name}}">
<label for="eventName">Event Name</label>
</div>
</div>
<div class="col-12 col-md-2">
<x-forms.select
id="eventStatus"
label="Event Status"
margin="0"
:disabled="$disabled || Auth::user()->user_access != 'admin'"
:options="$eventStatus"
:value="$event[0]->status"
name="eventStatus">
</x-forms.select>
</div>
</div>
</div>
<div
class="d-flex flex-column align-items-center justify-content-center">
<x-forms.image
id="eventImage"
acceptedTypes="images/"
src="uploads/{{$event[0]->image}}"
:disabled="$disabled || Auth::user()->user_access != 'admin'">
</x-forms.image>
</div>
<div class="form-floating mx-2">
<textarea name="description" class="form-control"
placeholder="Leave a comment here" id="description"
@if($disabled || Auth::user()->user_access != 'admin') disabled @endif
style="height: 150px">{{$event[0]->description}}</textarea>
<label for="description">Event Description</label>
</div>
<div class="container-fluid mt-2">
<div class="row">
<div class="col-12 col-md-4">
<x-forms.input
type="text"
label="Location"
name="Location"
field="location"
value="{{$event[0]->location}}"
:disabled="$disabled || Auth::user()->user_access != 'admin'"
placeholder="event"></x-forms.input>
</div>
<div class="col-12 col-md-4">
<x-forms.input
type="date"
label="Event Start"
name="Event Start"
field="startDate"
placeholder="startDate"
:disabled="$disabled || Auth::user()->user_access != 'admin'"
:value="date('Y-m-d', strtotime($event[0]->event_start))">
</x-forms.input>
</div>
<div class="col-12 col-md-4">
<x-forms.input
type="date"
label="Event End"
name="Event End"
field="endDate"
placeholder="endDate"
:disabled="$disabled || Auth::user()->user_access != 'admin'"
:value="date('Y-m-d', strtotime($event[0]->event_end))">
</x-forms.input>
</div>
</div>
</div>
<div class="d-flex justify-content-center mt-4">
@if($event[0]->status != 'done' && Auth::user()->user_access == 'admin')
<x-buttons.primary
label="Save Changes"
btnType="success"
type="submit"
name="Approve"
class="btn btn-success"
value="Approve"
style="width: 50%"
id="approve">
</x-buttons.primary>
@endif
@if(Auth::user()->user_access == 'resident')
@if(($event[0]->status == 'scheduled') && $registration == 0)
<button type="button"
class="btn btn-success rounded-0 px-5 small"
data-bs-toggle="modal"
data-bs-target="#confirmModal"
style="min-width: 10rem;">Register
</button>
<x-modal.confirmation
message="Are you sure you want to register?"></x-modal.confirmation>
@else
<button type="button"
class="btn btn-secondary rounded-0 px-5 small disabled"
style="min-width: 10rem;">Registered
</button>
@endif
@endif
</div>
</form>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
<style>
.event-image {
height: 200px;
}
</style>
@endsection |
/*
* Copyright (c) 2021 Fraunhofer-Gesellschaft zur Foerderung der angewandten Forschung e. V.
* Copyright (c) 2023, SAP SE or an SAP affiliate company
*
* 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 org.eclipse.digitaltwin.aas4j.v3.model;
import org.eclipse.digitaltwin.aas4j.v3.model.annotations.IRI;
import org.eclipse.digitaltwin.aas4j.v3.model.annotations.KnownSubtypes;
import org.eclipse.digitaltwin.aas4j.v3.model.impl.DefaultKey;
/**
* A key is a reference to an element by its ID.
*/
@KnownSubtypes({
@KnownSubtypes.Type(value = DefaultKey.class)
})
public interface Key {
/**
* Denotes which kind of entity is referenced.
*
* More information under https://admin-shell.io/aas/3/0/Key/type
*
* @return Returns the KeyTypes for the property type.
*/
@IRI("https://admin-shell.io/aas/3/0/Key/type")
KeyTypes getType();
/**
* Denotes which kind of entity is referenced.
*
* More information under https://admin-shell.io/aas/3/0/Key/type
*
* @param type desired value for the property type.
*/
void setType(KeyTypes type);
/**
* The key value, for example an IRDI or an URI
*
* More information under https://admin-shell.io/aas/3/0/Key/value
*
* @return Returns the String for the property value.
*/
@IRI("https://admin-shell.io/aas/3/0/Key/value")
String getValue();
/**
* The key value, for example an IRDI or an URI
*
* More information under https://admin-shell.io/aas/3/0/Key/value
*
* @param value desired value for the property value.
*/
void setValue(String value);
} |
/**
* @file sys_data.h
* @copyright
* @license
* @version 1.0.0
* @date 20/03/2024
* @author Kha Nguyen
*
* @brief system data process data from user by uart
*/
/* Define to prevent recursive inclusion ------------------------------ */
#ifndef INC_SYSTEM_SYS_UART_H_
#define INC_SYSTEM_SYS_UART_H_
/* Includes ----------------------------------------------------------- */
#include "drv_uart.h"
/* Public defines ----------------------------------------------------- */
/**
* @brief enumeration define status system data
*/
typedef enum
{
SYS_UART_OK = 0U,
SYS_UART_ERROR,
} sys_uart_status_t;
/**
* @brief enumeration define packet type
*/
typedef enum
{
SYS_UART_CMD_CHECK_UART = 0U,
SYS_UART_CMD_SET_TIME,
SYS_UART_CMD_SET_EPOCH_TIME,
SYS_UART_CMD_GET_TIME,
SYS_UART_CMD_SET_MODE_TIME,
SYS_UART_CMD_SET_ALARM,
SYS_UART_CMD_CANCEL_ALARM,
SYS_UART_CMD_SET_BRIGHTNESS,
SYS_UART_CMD_SET_COLOR,
SYS_UART_CMD_GET_TEMPERATURE,
} sys_uart_cmd_type_t;
/**
* @brief enumeration define set mode time
*
* @example data sample : char[6] data = "uart2";
* process : bool uart_check = true;
*/
typedef bool sys_uart_cmd_check_t;
/**
* @brief enumeration define set mode time
*
* @note mode 12h : DS1307_MODE_12H
* @note mode 24h : DS1307_MODE_24H
*
* @example data simple : char data[] = "12"
* data process: ds1307_mode_t mode_t = 12;
*/
typedef enum
{
SYS_UART_MODE_24H = 0U, /* mode 24h */
SYS_UART_MODE_12H = 1U, /* mode 12h */
} sys_uart_cmd_mode_time_t;
/**
* @brief enumeration define set mode time
*
* @example data sample : char data[24] = "10h10p10s03d01m2024yfri"
* process : uint8_t hours = 10;
* uint8_t minutes = 10;
* uint8_t seconds = 10;
* uint8_t dow = 6;
* uint8_t date = 03;
* uint8_t month = 01;
* uint32_t year = 2024;
* ds1307_mode_t mode = 24h;
*/
typedef struct
{
uint8_t hours; /* Hours parameter, 24Hour mode, 00 to 23 */
uint8_t minutes; /* Minutes parameter, from 00 to 59 */
uint8_t seconds; /* Seconds parameter, from 00 to 59 */
uint8_t dow; /* Day in a week, from monday to sunday */
uint8_t date; /* Date in a month, 1 to 31 */
uint8_t month; /* Month in a year, 1 to 12 */
uint32_t year; /* Year parameter, 00 to 99, 00 is 2000 and 99 is 2099 */
} sys_uart_cmd_set_time_t;
/**
* @brief enumeration define data set epoch time
*
* @example data sample : char data[11] = "1709303879";
* process : uint32_t epoch_time = 1709303879;
*/
typedef uint32_t sys_uart_cmd_set_epoch_time_t;
/**
* @brief enumeration define process data get time
*
* @example data sample : char data[8] = "gettime";
* process : char get_time[8] = "gettime";
*/
typedef bool sys_uart_cmd_get_time_t;
/**
* @brief enumeration define set alarm & modify alarm
*
* @example data sample : char data[10] = "10h30p30s"
* process : uint8_t hours = 10;
* uint8_t minutes = 10;
* uint8_t seconds = 10;
*/
typedef struct
{
uint8_t hours; /* Hours parameter, 24Hour mode, 00 to 23 */
uint8_t minutes; /* Minutes parameter, from 00 to 59 */
uint8_t seconds; /* Seconds parameter, from 00 to 59 */
} sys_uart_cmd_alarm_t;
/**
* @brief enumeration define cancle alarm
*
* @example data simple : char data[7] = "cancle"
* data process: char cancle[7] = "cancle";
*/
typedef bool sys_uart_cmd_cancel_alarm_t;
/**
* @brief enumeration define set brightness
*
* @note brigthness's value from 0--100
*
* @example data simple : char data[3] = "50"
* data process: sys_uart_cmd_brigthness_t brightness = 50;
*/
typedef uint8_t sys_uart_cmd_brightness_t;
/**
* @brief enumeration define set color
*
* @note color1 : color1
* @note color2 : color2
*
* @example data simple : char data[7] = "color1"
* data process: sys_uart_cmd_color_t color = SYS_UART_COLOR_1;
*/
typedef enum
{
SYS_UART_COLOR_1 = 1U,
SYS_UART_COLOR_2,
} sys_uart_cmd_color_t;
/**
* @brief enumeration define process data get time
*
* @example data sample : char data[8] = "gettemp";
* process : char get_time[8] = "gettemp";
*/
typedef bool sys_uart_cmd_get_temp_t;
/**
* @brief Union for storing different types of data related to UART commands.
*
* @details This union allows the storage of different types of data structures
* representing various UART commands. It is used to encapsulate data
* associated with UART commands such as checking status, setting time,
* setting epoch time, getting time, setting mode, setting alarms,
* canceling alarms, adjusting brightness, setting color, and getting temperature.
*
* @note This union is designed to be flexible and accommodate different types
* of data structures corresponding to different UART commands.
*
* @see sys_uart_cmd_check_t, sys_uart_cmd_set_time_t, sys_uart_cmd_set_epoch_time_t,
* sys_uart_cmd_get_time_t, sys_uart_cmd_mode_time_t, sys_uart_cmd_alarm_t,
* sys_uart_cmd_cancel_alarm_t, sys_uart_cmd_brightness_t, sys_uart_cmd_color_t,
* sys_uart_cmd_get_temp_t
*/
typedef union
{
sys_uart_cmd_check_t uart_check;
sys_uart_cmd_set_time_t set_time;
sys_uart_cmd_set_epoch_time_t epoch_time;
sys_uart_cmd_get_time_t get_time;
sys_uart_cmd_mode_time_t mode_time;
sys_uart_cmd_alarm_t set_alarm;
sys_uart_cmd_cancel_alarm_t cancel_alarm;
sys_uart_cmd_brightness_t brightness;
sys_uart_cmd_color_t color;
sys_uart_cmd_get_temp_t temp;
} sys_uart_cmd_data_t;
/* Public enumerate/structure ----------------------------------------- */
/* Public macros ------------------------------------------------------ */
/* Public variables --------------------------------------------------- */
/* Public function prototypes ----------------------------------------- */
/**
* @brief Start the system UART (Universal Asynchronous Receiver-Transmitter) module.
*
* @param[in] None
*
* @attention This function initializes the UART module for communication.
*
* @return The status of the UART start operation.
*/
sys_uart_status_t sys_uart_start();
/**
* @brief Process UART commands.
*
* @param[out] type Pointer to store the type of UART command received.
* @param[out] data Pointer to store the data associated with the UART command.
*
* @return The status of the UART command processing operation.
*/
sys_uart_status_t sys_uart_process(sys_uart_cmd_type_t *type, sys_uart_cmd_data_t *data);
/**
* @brief Print formatted data to the UART.
*
* @param[in] fmt Format string followed by additional arguments.
* Follows the same syntax as printf function.
*
* @return None
*/
void sys_uart_print(const char *const fmt, ...);
#endif /* INC_SYSTEM_SYS_UART_H_ */
/* End of file -------------------------------------------------------- */ |
//
// FMDatePickerView.swift
// FMAccountBook
//
// Created by yfm on 2023/3/15.
//
import UIKit
let kDatePickerHeight: Double = 250.0
let kPickerHeight: Double = 290.0
let selectedColor = UIColor.color(hex: "#FA5252")
let bgColor = UIColor.color(hex: "#F6F6F6")
class FMDatePickerView: UIView {
var confirmBlock: ((Int, Int, Int)->())?
var year = 0
var month = 0
var day = 0
var years = [Int]()
var months = [Int]()
var days = [Int]()
lazy var contentView: UIView = {
let view = UIView()
view.backgroundColor = .black.withAlphaComponent(0.2)
let tapGes = UITapGestureRecognizer(target: self, action: #selector(dismiss))
view.addGestureRecognizer(tapGes)
return view
}()
lazy var containerView: UIView = {
let view = UIView(frame: CGRect(x: 0, y: kScreenHeight, width: kScreenWidth, height: kPickerHeight))
view.backgroundColor = bgColor
view.layer.cornerRadius = 8
view.layer.masksToBounds = true
view.layer.maskedCorners = [.layerMinXMinYCorner, .layerMaxXMinYCorner]
return view
}()
lazy var cancelButton: UIButton = {
let btn = UIButton()
btn.setTitle("取消", for: .normal)
btn.setTitleColor(.black, for: .normal)
btn.titleLabel?.font = .systemFont(ofSize: 16)
btn.addTarget(self, action: #selector(dismiss), for: .touchUpInside)
return btn
}()
lazy var doneButton: UIButton = {
let btn = UIButton()
btn.setTitle("确定", for: .normal)
btn.setTitleColor(.black, for: .normal)
btn.titleLabel?.font = .systemFont(ofSize: 16)
btn.addTarget(self, action: #selector(confirm), for: .touchUpInside)
return btn
}()
lazy var datePicker: UIPickerView = {
let view = UIPickerView(frame: .zero)
view.backgroundColor = bgColor
view.dataSource = self
view.delegate = self
return view
}()
init(date: String) {
super.init(frame: UIScreen.main.bounds)
buildData()
makeUI()
let array = date.components(separatedBy: "-")
year = Int(array[0]) ?? 2023
month = Int(array[1]) ?? 1
day = Int(array[2]) ?? 1
let yearIndex = years.firstIndex(of: year) ?? 0
let monthIndex = months.firstIndex(of: month) ?? 0
let dayIndex = days.firstIndex(of: day) ?? 0
datePicker.selectRow(yearIndex, inComponent: 0, animated: false)
datePicker.selectRow(monthIndex, inComponent: 1, animated: false)
datePicker.selectRow(dayIndex, inComponent: 2, animated: false)
}
@available(*, unavailable)
init() {
fatalError()
}
@available(*, unavailable)
override init(frame: CGRect) {
fatalError("init(frame:) has not been implemented")
}
@available(*, unavailable)
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
func buildData() {
year = Calendar.currentYear() ?? 2023
month = Calendar.currentMonth() ?? 1
day = Calendar.currentDay() ?? 1
years = Array(year-2...year)
months = Array(1...12)
days = Calendar.getDaysArray(year: year, month: month)
}
@objc func dismiss() {
removeFromSuperview()
}
@objc func confirm() {
confirmBlock?(year, month, day)
dismiss()
}
override func willMove(toSuperview newSuperview: UIView?) {
containerView.zy_y = kScreenHeight
UIView.animate(withDuration: 0.25, animations: { [weak self] in
self?.containerView.zy_y = kScreenHeight - kPickerHeight + kSafeAreaInsets.bottom
}, completion: { finish in
super.willMove(toSuperview: newSuperview)
})
}
override func removeFromSuperview() {
containerView.zy_y = kScreenHeight - kPickerHeight + kSafeAreaInsets.bottom
UIView.animate(withDuration: 0.25, animations: { [weak self] in
self?.containerView.zy_y = kScreenHeight
}, completion: { finish in
super.removeFromSuperview()
})
}
func makeUI() {
addSubview(contentView)
addSubview(containerView)
containerView.addSubview(cancelButton)
containerView.addSubview(doneButton)
containerView.addSubview(datePicker)
contentView.snp.makeConstraints { make in
make.edges.equalToSuperview()
}
cancelButton.snp.makeConstraints { make in
make.top.equalToSuperview().offset(10)
make.left.equalToSuperview().offset(10)
make.width.equalTo(60)
make.height.equalTo(40)
}
doneButton.snp.makeConstraints { make in
make.top.equalToSuperview().offset(10)
make.right.equalToSuperview().offset(-10)
make.width.equalTo(60)
make.height.equalTo(40)
}
datePicker.snp.makeConstraints { make in
make.top.equalTo(cancelButton.snp.bottom)
make.left.bottom.right.equalToSuperview()
}
}
}
extension FMDatePickerView {
func resetMonth() {
datePicker.selectRow(0, inComponent: 1, animated: true)
month = 1
}
func resetDay() {
days = Calendar.getDaysArray(year: year, month: month)
datePicker.reloadComponent(2)
datePicker.selectRow(0, inComponent: 2, animated: true)
day = 1
}
}
extension FMDatePickerView: UIPickerViewDelegate, UIPickerViewDataSource {
func numberOfComponents(in pickerView: UIPickerView) -> Int {
return 3
}
func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
if component == 0 {
return years.count
} else if component == 1 {
return months.count
} else {
return days.count
}
}
func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? {
if component == 0 {
return "\(years[row])" + "年"
} else if component == 1 {
return String(format: "%2d", months[row]) + "月"
} else {
return String(format: "%2d", days[row]) + "日"
}
}
func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {
if component == 0 {
year = years[row]
} else if component == 1 {
month = months[row]
} else {
day = days[row]
}
if component == 0 {
resetMonth()
resetDay()
}
if component == 1 {
resetDay()
}
}
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.