text
stringlengths 184
4.48M
|
|---|
import React, { useCallback } from 'react';
import './Button.css';
/**
* Buttons to the platform.
* @param {JSX.Element} icon - If you want you can show an icon betwen de text .
* @param {string} label - button label.
* @callback onClick - action to execute when click the button.
* @param {boolean} disabled - the button is disabled.
* @param {type=primary|secondary|clear} type - indicates type of button and change css.
* @param {Object} styleButton - if you want change other styles you can use style.
* @param {Object} styleIcon - if you want change other styles you can use style.
*/
export const Button = ({icon, label, onClick, disabled=false, type="primary" , styleButton={}, styleIcon={} }) => {
const handleClick = useCallback((e)=>{
e.preventDefault();
onClick && onClick();
},[onClick])
return (
<button
onClick={handleClick}
disabled={disabled}
className={`buttons btn_${type}`}
style={styleButton}
>
{icon &&
<div className="icons_button" style={styleIcon}>
{icon}
</div>
}
{label}
</button>
)
}
|
from __future__ import annotations
import networkx as nx
import pandas as pd
# STFU
import graphein
graphein.verbose(enabled=False)
pd.options.mode.chained_assignment = None # default='warn'
import warnings
warnings.simplefilter(action='ignore', category=FutureWarning)
import os
from pathlib import Path
from typing import Callable, Dict, Generator, List, Optional, Tuple, Any
from loguru import logger as log
import torch
from tqdm import tqdm
from graphein.ml.conversion import GraphFormatConvertor
from graphein.protein.config import ProteinGraphConfig
from graphein.protein.graphs import construct_graphs_mp
from graphein.protein.utils import (
download_alphafold_structure,
download_pdb,
download_pdb_multiprocessing,
)
from graphein.utils.dependencies import import_message
try:
import torch
from torch_geometric.data import Data, Dataset, InMemoryDataset
except ImportError:
import_message(
"graphein.ml.datasets.torch_geometric_dataset",
"torch_geometric",
conda_channel="pyg",
pip_install=True,
)
from torch import Tensor
# TODO:
# raise issue in pytorch_geometric about error when creating dataset. (with download)
# Note: we had to resolve this issue manually by manually creating a `raw` directory
# and moving files across that the `download` method was meant to create.
class PhosphositeGraphDataset(Dataset):
def __init__(
self,
root: str,
paths: List[str] | None = None,
pdb_codes: List[str] | None = None,
uniprot_ids: List[str] | None = None,
graph_labels: List[Tensor] | None = None,
node_labels: List[Tensor] | None = None,
chain_selections: List[str] | None = None,
graphein_config: ProteinGraphConfig = ProteinGraphConfig(),
graph_format_convertor: GraphFormatConvertor = GraphFormatConvertor(src_format="nx", dst_format="pyg"),
graph_transformation_funcs: List[Callable[..., Any]] | None = None,
pdb_transform: List[Callable[..., Any]] | None = None,
transform: Callable[..., Any] | None = None,
pre_transform: Callable[..., Any] | None = None,
pre_filter: Callable[..., Any] | None = None,
num_cores: int = 16,
af_version: int = 2,
y_label_map: Dict[Dict[str, Tensor]] | None = None,
):
if uniprot_ids is None:
# Use everything provided in the label dictionary.
uniprot_ids = list(y_label_map.keys())
self.uniprot_ids = uniprot_ids
self.examples: Dict[int, str] = dict(enumerate(self.uniprot_ids))
if graph_labels is not None:
self.graph_label_map = dict(enumerate(graph_labels))
else:
self.graph_label_map = None
if node_labels is not None:
self.node_label_map = dict(enumerate(node_labels))
else:
self.node_label_map = None
if chain_selections is not None:
self.chain_selection_map = dict(enumerate(chain_selections))
else:
self.chain_selection_map = None
self.root = root
self.y_label_map = y_label_map
# Configs
self.config = graphein_config
self.graph_format_convertor = graph_format_convertor
self.num_cores = num_cores
self.pdb_transform = pdb_transform
self.graph_transformation_funcs = graph_transformation_funcs
self.af_version = af_version
super().__init__(
root,
transform=transform,
pre_transform=pre_transform,
pre_filter=pre_filter,
)
self.config.pdb_dir = Path(self.raw_dir)
@property
def raw_file_names(self) -> List[str]:
"""Names of raw files in the dataset."""
# Return the uniprot_ids in raw_dir
return [f"{uniprot_id}.pdb" for uniprot_id in self.uniprot_ids]
@property
def raw_dir(self) -> str:
return os.path.join(self.root, "raw")
@property
def processed_file_names(self) -> List[str]:
"""Names of processed files to look for"""
return [f"{uniprot_id}.pt" for uniprot_id in self.uniprot_ids]
def download(self):
pass
def process(self):
"""Processes structures from files into PyTorch Geometric Data."""
# Preprocess PDB files
if self.pdb_transform:
self.transform_pdbs()
idx = 0
# Chunk dataset for parallel processing
chunk_size = 128
def divide_chunks(l: List[str], n: int = 2) -> Generator:
for i in range(0, len(l), n):
yield l[i : i + n]
# chunks = list(divide_chunks(self.structures, chunk_size))
chunks: List[int] = list(
divide_chunks(list(self.examples.keys()), chunk_size)
)
for chunk in tqdm(chunks):
pdbs = [self.examples[idx] for idx in chunk]
# Get chain selections
if self.chain_selection_map is not None:
chain_selections = [
self.chain_selection_map[idx] for idx in chunk
]
else:
chain_selections = ["all"] * len(chunk)
# Create graph objects
file_names = [f"{self.raw_dir}/{pdb}.pdb" for pdb in pdbs]
graphs = construct_graphs_mp(
path_it=file_names,
config=self.config,
chain_selections=chain_selections,
return_dict=False,
)
old_len = len(graphs)
graphs = [g for g in graphs if g is not None]
if old_len - len(graphs) > 0:
print("number of None graphs: ", old_len - len(graphs))
if self.graph_transformation_funcs is not None:
graphs = [self.transform_graphein_graphs(g) for g in graphs]
# Convert to PyTorch Geometric Data
converted = []
for i, g in enumerate(graphs):
try:
converted_graph = self.graph_format_convertor(g)
converted.append(converted_graph)
except:
tqdm.write(f"failed to convert graph {g}")
continue
#graphs = [self.graph_format_convertor(g) for g in graphs]
graphs = converted
# Assign labels
if self.graph_label_map:
labels = [self.graph_label_map[idx] for idx in chunk]
for i, _ in enumerate(chunk):
graphs[i].graph_y = labels[i]
if self.node_label_map:
labels = [self.node_label_map[idx] for idx in chunk]
for i, _ in enumerate(chunk):
graphs[i].graph_y = labels[i]
data_list = graphs
del graphs
if self.pre_filter is not None:
data_list = [g for g in data_list if self.pre_filter(g)]
if self.pre_transform is not None:
data_list = [self.pre_transform(data) for data in data_list]
# TODO: handle chain selections?
# for now just save each graph by its `name`
for i, g in enumerate(data_list):
torch.save(
g,
os.path.join(self.processed_dir, f"{g.name}.pt"),
)
# Update valid modiform_ids
# get all .pt uniprot_ids
self.uniprot_ids = [
u
for u in self.uniprot_ids
if os.path.exists(os.path.join(self.processed_dir, f"{u}.pt"))
]
# Don't have to update the y_label_map because it's a dict
# and the dataset can only be indexed into the valid uniprot_ids
# (i.e. valid uniprot_id means graph has been constructed)
# and we already pre-filter for making sure the unipro_id sequence
# is valid and maps with our sites.
def len(self) -> int:
"""
Returns length of graphs.
"""
return len(self.uniprot_ids)
def get(self, idx: int):
"""
Returns PyTorch Geometric Data object for a given index.
:param idx: Index to retrieve.
:type idx: int
:return: PyTorch Geometric Data object.
"""
if isinstance(idx, str):
# assume uniprot_id
uniprot_id = idx
else:
uniprot_id = self.uniprot_ids[idx]
data = torch.load(
os.path.join(self.processed_dir, f"{uniprot_id}.pt")
)
assert isinstance(data, Data), f"{uniprot_id}: Data is not a PyTorch Geometric Data object. Got {type(data)}."
assert uniprot_id == data.name, f"Uniprot ID '{uniprot_id}' does not match data.name '{data.name}' at index {idx}."
if self.y_label_map is not None:
data.y_index = self.y_label_map[uniprot_id]["idx"]
data.y = self.y_label_map[uniprot_id]["y"]
#data.phosphosite_index = torch.tensor(site_indexes, dtype=torch.long)
# NOTE: not necessary to store any extra information.
return data
def transform_graphein_graphs(self, graph: nx.Graph):
for func in self.graph_transformation_funcs:
graph = func(graph)
return graph
|
<template>
<div id="app">
<h2>---------modules内容----------</h2>
<h2>{{$store.state.a.name}}</h2>
<button @click="changeNameA">修改名字</button>
<button @click="achangeNameA">异步修改名字</button>
<h2>{{$store.getters.fullName}}</h2>
<h2>{{$store.getters.fullName2}}</h2>
<h2>{{$store.getters.fullName3}}</h2>
<h2>{{$store.state.b.name}}</h2>
<h2>----------App内容------------</h2>
<h2>{{$store.state.counter}}</h2>
<button @click="addition">+</button>
<button @click="subtraction">-</button>
<button @click="addCount(5)">+5</button>
<button @click="addCount(10)">+10</button>
<button @click="addStudent">添加学生</button>
<h2>----------App内容: getters相关信息---</h2>
<h2>{{$store.getters.powerCounter}}</h2>
<h2>{{$store.getters.more20stu}}</h2>
<h2>{{$store.getters.more20stuLength}}</h2>
<h2>{{$store.getters.moreAgestu(10)}}</h2>
<h2>----------App内容: info对象的内容是否是响应式的---</h2>
<h2>{{$store.state.info}}</h2>
<button @click="changeInfo">修改信息</button>
<button @click="achangeInfo">异步修改信息</button>
<h2>----------Hello Vuex内容------------</h2>
<hello-vuex></hello-vuex>
</div>
</template>
<script>
import HelloVuex from "./components/HelloVuex";
import * as types from "./store/mutations-types"
export default {
name: 'App',
data(){
return{
message:"我是App组件",
}
},
components: {
HelloVuex,
},
methods:{
addition(){
this.$store.commit(types.INCREMENT);
},
subtraction(){
this.$store.commit(types.DECREMENT);
},
addCount(count){
//payload: 负载
//1. 普通的提交风格
// this.$store.commit('incrementCount', count);
//2. 特殊的提交封装
this.$store.commit({
type: 'incrementCount',
count: count,
});
},
addStudent(){
const stu = {id:114, name: 'curry', age: 12};
this.$store.commit('addStudent', stu);
},
changeInfo(){
this.$store.commit('updateInfo');
},
achangeInfo(){
// this.$store.dispatch('aUpdateInfo', {
// message: '我是携带的信息',
// success:()=> {
// console.log('里面已经完成了');
// },
// failed: ()=>{
// console.log('里面失败了');
// }
// }
// );
this.$store.dispatch('aUpdateInfo',
'我是携带的信息').then(res=>{
console.log('里面完成了提交');
console.log(res);
});
},
changeNameA(){
this.$store.commit('updateNameA');
},
achangeNameA(){
this.$store.dispatch('aUpdateName');
}
}
}
</script>
<style>
</style>
|
from django.contrib.auth import authenticate
from django.utils.translation import gettext_lazy as _
from rest_framework import serializers
from rest_framework.authtoken.serializers import AuthTokenSerializer
from users.serializers import UserSerializer
class LoginSerializer(serializers.Serializer):
username = serializers.CharField(label=_("Username"), write_only=True)
password = serializers.CharField(
label=_("Password"),
style={"input_type": "password"},
trim_whitespace=False,
write_only=True,
)
user = UserSerializer(read_only=True)
remember_me = serializers.BooleanField(
label=_("Remember me"), required=False, default=False
)
def validate(self, attrs):
username = attrs.get("username")
password = attrs.get("password")
if username and password:
user = authenticate(
request=self.context.get("request"),
username=username,
password=password,
)
# The authenticate call simply returns None for is_active=False
# users. (Assuming the default ModelBackend authentication
# backend.)
if not user:
msg = _(
"Couldn't login with the given information. Password or Username may be wrong."
)
raise serializers.ValidationError(msg, code="authorization")
else:
msg = "Kullanıcı adı ve şifre girilmeli."
raise serializers.ValidationError(msg, code="authorization")
attrs["user"] = user
return attrs
class LogoutSerializer(serializers.Serializer):
digest = serializers.CharField(
label="Token digest", write_only=True, required=False
)
class LogoutAllSerializer(serializers.Serializer):
pass
|
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
<link rel="stylesheet" href="./layui/css/layui.css">
</head>
<body>
<div class="layui-tab" lay-filter="demo1" lay-allowclose="true">
<ul class="layui-tab-title">
<li class="layui-this" lay-id="11">网站设置</li>
<li lay-id="22">用户管理</li>
<li lay-id="33">权限分配</li>
<li lay-id="44">商品管理</li>
<li lay-id="55">订单管理</li>
</ul>
<div class="layui-tab-content">
<div class="layui-tab-item layui-show">内容1</div>
<div class="layui-tab-item">内容2</div>
<div class="layui-tab-item">内容3</div>
<div class="layui-tab-item">内容4</div>
<div class="layui-tab-item">内容5</div>
</div>
</div>
<button class="layui-btn site-demo-active" data-type="tabAdd">新增Tab项</button>
<script src="./layui/layui.js"></script>
<script>
layui.use('element', function () {
var $ = layui.jquery
, element = layui.element; //Tab的切换功能,切换事件监听等,需要依赖element模块
//触发事件
var active = {
tabAdd: function () {
console.log(1)
//新增一个Tab项
element.tabAdd('demo1', {
title: '新选项' + (Math.random() * 1000 | 0) //用于演示
, content: '内容' + (Math.random() * 1000 | 0)
, id: new Date().getTime() //实际使用一般是规定好的id,这里以时间戳模拟下
})
}
, tabDelete: function (othis) {
//删除指定Tab项
element.tabDelete('demo1', '44'); //删除:“商品管理”
othis.addClass('layui-btn-disabled');
}
, tabChange: function () {
//切换到指定Tab项
element.tabChange('demo', '22'); //切换到:用户管理
}
};
$('.site-demo-active').on('click', function () {
var othis = $(this), type = othis.data('type');
active[type] ? active[type].call(this, othis) : '';
});
//Hash地址的定位
var layid = location.hash.replace(/^#test=/, '');
element.tabChange('test', layid);
element.on('tab(test)', function (elem) {
location.hash = 'test=' + $(this).attr('lay-id');
});
});
</script>
</body>
</html>
|
//
// AddOrEditQuestionView.swift
// Copyright (c) 2022 LeitnerBox
//
// Created by Hamed Hosseini on 10/28/22.
import CoreData
import SwiftUI
struct AddOrEditQuestionView: View {
@EnvironmentObject var objVM: ObjectsContainer
@Environment(\.dismiss) var dissmiss
@Environment(\.colorScheme) var colorScheme
@Environment(\.managedObjectContext) var context: NSManagedObjectContext
@State var showTagPicker: Bool = false
@State var showSynonymPicker: Bool = false
private var questionVMBinding: Binding<QuestionViewModel> { $objVM.questionVM }
private var questionVM: QuestionViewModel { objVM.questionVM }
var body: some View {
HStack(spacing: 0) {
Spacer()
ScrollView {
VStack(spacing: 36) {
VStack(alignment: .leading) {
TextEditorView(
placeholder: "Enter your question here...",
shortPlaceholder: "Question",
string: questionVMBinding.questionString,
textEditorHeight: 48
)
if questionVM.batchInserPhrasesMode {
Text("When you are in the batch mode the question filed automatically split all th questions by (NewLine/Enter).")
.font(.caption2)
.foregroundColor(.gray)
}
}
if !questionVM.batchInserPhrasesMode {
CheckBoxView(isActive: questionVMBinding.isManual, text: "Manual Answer")
if questionVM.isManual {
TextEditorView(
placeholder: "Enter your Answer here...",
shortPlaceholder: "Answer",
string: questionVMBinding.answer,
textEditorHeight: 48
)
TextEditorView(
placeholder: "Enter your description here...",
shortPlaceholder: "Description",
string: questionVMBinding.detailDescription,
textEditorHeight: 48
)
}
}
CheckBoxView(isActive: questionVMBinding.completed, text: "Complete Answer")
HStack {
Button {
withAnimation {
questionVM.favorite.toggle()
}
} label: {
HStack {
Image(systemName: questionVM.favorite == true ? "star.fill" : "star")
.resizable()
.scaledToFit()
.frame(width: 32, height: 32)
.foregroundColor(.accentColor)
Text(verbatim: "favorite")
.font(.body.weight(.semibold))
}
}
Spacer()
}
VStack(alignment: .leading) {
Button {
showTagPicker.toggle()
} label: {
Label("Tags", systemImage: "plus.circle")
}
.keyboardShortcut("t", modifiers: [.command])
.buttonStyle(.borderless)
QuestionTagList(tags: questionVM.tags) { tag in
questionVM.removeTagForQuestion(tag)
}
Button {
showSynonymPicker.toggle()
} label: {
Label("Synonyms", systemImage: "plus.circle")
}
.buttonStyle(.borderless)
QuestionSynonymList(synonyms: questionVM.synonyms) { _ in
} onLongClick: { synonymQuestion in
withAnimation {
questionVM.removeSynonym(synonymQuestion)
}
}
}
Button {
questionVM.save()
questionVM.reset()
dissmiss()
} label: {
HStack {
Spacer()
Label("Save", systemImage: "checkmark.square.fill")
Spacer()
}
}
.buttonStyle(.bordered)
.controlSize(.large)
.tint(.accentColor)
Spacer()
}
.padding()
}
Spacer()
}
.animation(.easeInOut, value: questionVM.tags.count)
.animation(.easeInOut, value: questionVM.question?.tagsArray?.count)
.animation(.easeInOut, value: questionVM.synonyms.count)
.animation(.easeInOut, value: questionVM.completed)
.animation(.easeInOut, value: questionVM.favorite)
.navigationBarTitleDisplayMode(.inline)
.navigationTitle(questionVM.title)
.animation(.easeInOut, value: questionVM.isManual)
.toolbar {
ToolbarItem {
Button(action: questionVM.reset) {
Label("Clear", systemImage: "trash.square")
.font(.title3)
.symbolRenderingMode(.palette)
.foregroundStyle(colorScheme == .dark ? .white : .black.opacity(0.5), Color.accentColor)
}
}
ToolbarItem {
Button {
withAnimation {
questionVM.batchInserPhrasesMode.toggle()
}
} label: {
Label("Pharses", systemImage: questionVM.batchInserPhrasesMode ? "plus.app" : "rectangle.stack.badge.plus")
.font(.title3)
.symbolRenderingMode(.palette)
.foregroundStyle(colorScheme == .dark ? .white : .black.opacity(0.5), Color.accentColor)
}
}
ToolbarItemGroup(placement: .keyboard) {
HStack {
Spacer()
Button("Done") {
UIApplication.shared.sendAction(#selector(UIResponder.resignFirstResponder), to: nil, from: nil, for: nil)
}
}
}
}
.contentShape(Rectangle())
.sheet(isPresented: $showSynonymPicker) {
QuestionSynonymPickerView { question in
questionVM.addSynonym(question)
}
.environmentObject(objVM)
}
.sheet(isPresented: $showTagPicker) {
TagsListPickerView { tag in
questionVM.addTagToQuestion(tag)
}
.environmentObject(objVM)
}
.onDisappear {
questionVM.reset()
context.rollback()
}
}
}
struct AddQuestionView_Previews: PreviewProvider {
struct Preview: View {
static let leitner = PersistenceController.shared.generateAndFillLeitner().first!
static let question = Question(context: PersistenceController.shared.viewContext)
@StateObject var viewModel = QuestionViewModel(
viewContext: PersistenceController.shared.viewContext,
leitner: Preview.leitner,
question: question
)
var body: some View {
AddOrEditQuestionView()
.environmentObject(viewModel)
.environment(\.managedObjectContext, PersistenceController.shared.viewContext)
}
}
static var previews: some View {
NavigationStack {
Preview()
}
}
}
|
Given an array nums of size n, return the majority element.
The majority element is the element that appears more than ⌊n / 2⌋ times.
You may assume that the majority element always exists in the array.
##################################################################################3
Example 1:
Input: nums = [3,2,3]
Output: 3
Example 2:
Input: nums = [2,2,1,1,1,2,2]
Output: 2
###################################################################################
Solution:
import java.util.*;
class Solution
{
public int majorityElement(int[] nums)
{
int n = nums.length;
HashMap<Integer,Integer> map = new HashMap<Integer,Integer>();
for(int i=0; i<n; ++i)
{
int value = map.getOrDefault(nums[i],0)+1;
map.put(nums[i], value );
}
int max = (Collections.max(map.values()));
if(max>n/2)
{
for(Map.Entry<Integer, Integer> entry : map.entrySet())
{
if (entry.getValue()==max)
{
return entry.getKey();
}
}
}
return 0;
}
}
|
package ba.unsa.etf.rpr.dao;
import ba.unsa.etf.rpr.exceptions.CourtroomException;
import java.util.List;
/**
* The base interface for other DAO interfaces
* All methods throw a CourtroomException in case of SQL or other unexpected errors
* @param <Type> generic type that enables other DAO interfaces to extend a single interface
* @author Kemal Lipovača
*/
public interface DAO<Type> {
/**
* The method that retrieves an item from the database by matching IDs
* @param id the ID of the item
* @return the item found in the database with the matching ID or null for no match found
*/
Type getById(int id) throws CourtroomException;
/**
* The method that adds an item to the database
* @param item the item that is to be added
* @return the item used as the parameter but with an assigned ID to it
*/
Type add(Type item) throws CourtroomException;
/**
* The method that updates an existing item in the database
* @param item the item that is to be updated
*/
void update(Type item) throws CourtroomException;
/**
* The method that deletes an item from the database with the matching ID
* @param id the ID of the item
*/
void delete(int id) throws CourtroomException;
/**
* The method that retrieves all items from the database of the same type
* @return a list container of all the items acquired
*/
List<Type> getAll() throws CourtroomException;
}
|
import 'package:auto_size_text/auto_size_text.dart';
import 'package:cached_network_image/cached_network_image.dart';
import 'package:education/bloc/education_bloc.dart';
import 'package:education/components/informatica_bolumu/loading_widget.dart';
import 'package:education/constants/app_color.dart';
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
class PersonalComputerTestPage extends StatefulWidget {
const PersonalComputerTestPage({super.key});
@override
State<PersonalComputerTestPage> createState() =>
_PersonalComputerTestPageState();
}
class _PersonalComputerTestPageState extends State<PersonalComputerTestPage> {
int indexpersonalComputer = 0;
int tuuraJooptor = 0;
int kataJooptor = 0;
@override
Widget build(BuildContext context) {
return BlocBuilder<TestsBloc, EducationState>(
builder: (context, state) {
if (state is EducationLoading) {
return const LoadingWidget();
} else if (state is TestSuccess) {
return SafeArea(
child: Scaffold(
appBar: AppBar(
leading: IconButton(
onPressed: () {
Navigator.pop(context);
},
icon: const Icon(Icons.arrow_back),
),
title: Row(
mainAxisAlignment: MainAxisAlignment.end,
children: [
Card(
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(10.0),
),
child: Padding(
padding: const EdgeInsets.symmetric(horizontal: 5.0),
child: Row(
mainAxisAlignment: MainAxisAlignment.end,
children: [
Text(
'$kataJooptor',
style: const TextStyle(
color: AppColors.red,
fontSize: 16,
fontWeight: FontWeight.bold),
),
const Padding(
padding: EdgeInsets.symmetric(horizontal: 5),
child: Text(
'|',
style: TextStyle(fontSize: 17),
)),
Text(
'$tuuraJooptor',
style: const TextStyle(
color: Colors.green,
fontSize: 16,
fontWeight: FontWeight.bold),
),
],
),
),
),
const SizedBox(
width: 5,
),
],
),
elevation: 0,
),
body: Column(
children: [
SliderTheme(
data: SliderThemeData(
thumbShape: SliderComponentShape.noThumb,
trackHeight: 3,
activeTrackColor: Colors.red,
inactiveTrackColor: Colors.black,
activeTickMarkColor: Colors.blue,
trackShape: const RectangularSliderTrackShape()),
child: Slider(
min: 0,
max: 5,
value: indexpersonalComputer.toDouble(),
onChanged: (value) {},
),
),
Padding(
padding: const EdgeInsets.symmetric(horizontal: 10),
child: Center(
child: AutoSizeText(
state.testTopicsModel[0].informatica[0]
.personalComputer[indexpersonalComputer].guestion,
// widget.personalComputer[indexpersonalComputer].text,
style: const TextStyle(fontSize: 20, height: 2),
textAlign: TextAlign.center,
maxLines: 1,
),
),
),
Expanded(
flex: 1,
child: Padding(
padding: const EdgeInsets.all(10),
child: SizedBox(
width: double.infinity,
height: double.infinity,
child: CachedNetworkImage(
imageUrl: state.testTopicsModel[0].informatica[0]
.personalComputer[indexpersonalComputer].image,
fit: BoxFit.cover,
placeholder: (context, url) => Transform.scale(
scale: 0.2,
child: const CircularProgressIndicator(
color: Colors.red,
strokeWidth: 20,
)),
errorWidget: (context, url, error) =>
const Icon(Icons.error),
),
),
),
),
Expanded(
child: GridView.builder(
padding: const EdgeInsets.only(
left: 5,
right: 5,
),
// physics: NeverScrollableScrollPhysics(),
gridDelegate:
const SliverGridDelegateWithFixedCrossAxisCount(
crossAxisCount: 2,
childAspectRatio: 1.6,
),
itemCount: 4,
itemBuilder: ((context, index) {
return Card(
color: Colors.grey[400],
child: InkWell(
onTap: () {
// usaSuroo[indexUsaSurooJoop].jooptor[index].isBool;
if (indexpersonalComputer + 1 ==
state
.testTopicsModel[0]
.informatica[0]
.personalComputer[
indexpersonalComputer]
.options
.length
// indexpersonalComputer + 1 ==
// widget.personalComputer.length
) {
showDialog<String>(
context: context,
builder: (BuildContext context) =>
AlertDialog(
title:
const Text('Сиздин тест жыйынтыгыңыз!'),
content: Text(
'Туура: $tuuraJooptor\nКата:$kataJooptor'),
actions: <Widget>[
TextButton(
onPressed: () {
indexpersonalComputer = 0;
kataJooptor = 0;
tuuraJooptor = 0;
setState(() {});
Navigator.pop(context);
},
child: const Text('Cancel'),
),
],
),
);
} else {
if (state
.testTopicsModel[0]
.informatica[0]
.personalComputer[index]
.options[indexpersonalComputer]
.correct ==
true) {
tuuraJooptor++;
} else {
kataJooptor++;
}
setState(() {
indexpersonalComputer++;
});
}
},
child: Center(
child: AutoSizeText(
state
.testTopicsModel[0]
.informatica[0]
.personalComputer[0]
.options[indexpersonalComputer]
.answer,
textAlign: TextAlign.center,
maxLines: 5,
),
),
),
);
}),
),
),
],
),
),
);
} else if (state is EducationError) {
return Text(state.text);
} else {
throw ('ERROR in TEST');
}
},
);
}
}
|
-- name: CreateUser :exec
INSERT INTO users (name, email, password) VALUES (?, ?, ?);
-- name: GetUsers :many
SELECT * FROM users;
-- name: GetUserById :one
SELECT * FROM users WHERE id = ?;
-- name: UpdateUser :exec
UPDATE users SET email = ?, password = ? WHERE name = ?;
-- name: DeleteUser :exec
DELETE FROM users WHERE name = ?;
-- name: CreateMetadata :exec
INSERT INTO metadata (user_id, user_type, photo, description, status, address)
VALUES (?, ?, ?, ?, ?, ?);
-- name: GetMetadataById :one
SELECT * FROM metadata WHERE id = ?;
-- name: GetMetadata :many
SELECT * FROM metadata;
-- name: UpdateMetadata :exec
UPDATE metadata SET user_id = ?, user_type = ?, photo = ?, description = ?, status = ?, address = ? WHERE id = ? ;
-- name: DeleteMetadata :exec
DELETE FROM metadata WHERE id = ?;
-- name: CreateInstrument :exec
INSERT INTO instrument (user_id, is_active, instrument_name)
VALUES (?, ?, ?);
-- name: GetInstrumentByUserId :one
SELECT * FROM instrument WHERE user_id = ?;
-- name: GetAllInstruments :many
SELECT * FROM instrument;
-- name: UpdateInstrumentByUserId :exec
UPDATE instrument SET is_active = ?, instrument_name = ? WHERE user_id = ? ;
-- name: DeleteInstrumentByUserId :exec
DELETE FROM instrument WHERE user_id = ?;
-- name: CreateInvite :exec
INSERT INTO invites (user_id, remittee, status, invite_type)
VALUES (?, ?, ?, ?) ;
-- name: GetInviteByUserId :one
SELECT * FROM invites WHERE user_id = ?;
-- name: GetAllInvites :many
SELECT * FROM invites;
-- name: UpdateInviteByUserId :exec
UPDATE invites SET remittee = ?, status = ?, invite_type = ? WHERE user_id = ? ;
-- name: DeleteInviteByUserId :exec
DELETE FROM invites WHERE user_id = ?;
-- name: CreateSolicitation :exec
INSERT INTO solicitation (user_id, remittee, status, invite_type)
VALUES (?, ?, ?, ?);
-- name: GetSolicitationByUserId :one
SELECT * FROM solicitation WHERE user_id = ?;
-- name: GetAllSolicitations :many
SELECT * FROM solicitation;
-- name: UpdateSolicitationByUserId :exec
UPDATE solicitation SET remittee = ?, status = ?, invite_type = ? WHERE user_id = ?;
-- name: DeleteSolicitationByUserId :exec
DELETE FROM solicitation WHERE user_id = ?;
-- name: InsertRepertoire :exec
INSERT INTO repertoire (user_id, name, is_active, music_list_id)
VALUES (?, ?, ?, ?);
-- name: SelectAllRepertoire :many
SELECT * FROM repertoire;
-- name: SelectRepertoireById :one
SELECT * FROM repertoire WHERE user_id = ?;
-- name: UpdateRepertoire :exec
UPDATE repertoire
SET name = ?, is_active = ?, music_list_id = ?
WHERE user_id = ?;
-- name: DeleteRepertoire :exec
DELETE FROM repertoire WHERE user_id = ?;
|
import React from "react";
const useSpeech = () => {
const synth = window.speechSynthesis;
const [isSpeaking, setIsSpeaking] = React.useState(false);
const [isPause, setIsPause] = React.useState(false);
const [value, setValue] = React.useState("");
const [rate, setRate] = React.useState("1");
const [pitch, setPitch] = React.useState("1");
const resume = () => {
setIsPause(false);
synth.resume();
};
const pause = () => {
setIsPause(true);
synth.pause();
};
const pauseOrResume = () => {
if (synth.paused) {
resume();
} else {
pause();
}
};
const cancle = () => {
if (synth.speaking) {
synth.cancel();
}
};
const speak = () => {
const utterThis = new SpeechSynthesisUtterance(value);
utterThis.rate = Number(rate);
utterThis.pitch = Number(pitch);
utterThis.onstart = (ev: SpeechSynthesisEvent) => {
setIsSpeaking(true);
};
utterThis.onend = (ev: SpeechSynthesisEvent) => {
setIsSpeaking(false);
};
synth.speak(utterThis);
};
return {
isSpeaking,
isPause,
value,
rate,
pitch,
setValue,
setRate,
setPitch,
resume,
pause,
pauseOrResume,
cancle,
speak
};
};
export default useSpeech;
|
import { createStore, action, thunk, computed } from "easy-peasy";
import client from "./api/post";
export default createStore({
posts: [],
setPosts: action((state, payload) => {
state.posts = payload;
}),
searchResults: [],
setSearchResults: action((state, payload) => {
state.searchResults = payload;
}),
search: "",
setSearch: action((state, payload) => {
state.search = payload;
}),
postBody: "",
setPostBody: action((state, payload) => {
state.postBody = payload;
}),
postTitle: "",
setPostTitle: action((state, payload) => {
state.postTitle = payload;
}),
editTitle: "",
setEditTitle: action((state, payload) => {
state.editTitle = payload;
}),
editBody: "",
setEditBody: action((state, payload) => {
state.editBody = payload;
}),
getPostCount: computed((state) => state.posts.length),
getPostById: computed((state) => {
return(id) => state.posts.find((post) => (post.id).toString() === id)}),
savePost: thunk( async (actions, newPost, Helpers) => {
const { posts } = Helpers.getState();
try {
const response = await client.post('/blog' , newPost);
actions.setPosts([...posts, response.data]);
actions.setPostTitle('');
actions.setPostBody('');
} catch (err) {
console.log(err.message);
}
}),
deletePost: thunk( async (actions, id, Helpers) => {
const { posts } = Helpers.getState();
try {
const postsList = posts.filter(post => post.id !== id);
await client.delete(`/blog/${id}`);
actions.setPosts(postsList);
} catch (err) {
console.log(err.message);
}
}),
editPost: thunk( async (actions, updatedPost, Helpers) => {
const { posts } = Helpers.getState()
const { id } = updatedPost;
try {
const response = await client.put(`/blog/${id}`, updatedPost);
actions.setPosts( posts.map(post => (post.id).toString() === id ? {...response.data} : post));
// actions.setEditTitle('');
// actions.setEditBody('');
} catch (err) {
console.log(err.message);
}
})
});
|
import { TreatmentEffectiveness } from '@/store/types';
const getTreatmentEfficacyDescription = (effectiveness: TreatmentEffectiveness): string => {
switch (effectiveness) {
case TreatmentEffectiveness.RELAPSE:
return 'The treatment resulted in a full relapse of the symptoms';
case TreatmentEffectiveness.NO_IMPROVEMENT:
return 'The treatment did not result in any improvement';
case TreatmentEffectiveness.SOME_IMPROVEMENT:
return 'The treatment resulted in some improvement';
case TreatmentEffectiveness.GOOD_IMPROVEMENT:
return 'The treatment resulted in a good improvement of the symptom conditions';
default:
return '?';
}
};
const getPainLevelDescription = (painLevel: number): string => {
switch (painLevel) {
case 1:
return 'Mild pain. Can function';
case 1.5:
return 'Slight pain. Can somewhat function';
case 2:
return 'Moderate pain. Can function, but it is difficult ';
case 2.5:
return 'Severe pain. Can hardly function';
case 3:
return 'Extreme pain. Cannot function';
default:
return '?';
}
};
export { getTreatmentEfficacyDescription, getPainLevelDescription };
|
#ifndef PERSONA_H
#define PERSONA_H
#include <string>
using namespace std;
class Persona{
private:
string dni_,
nombre_,
apellidos_,
direccion_,
localidad_,
provincia_,
pais_;
int edad_;
public:
Persona(string dni,string nombre="",string apellidos="",int edad=0,string direccion="",string localidad="",string provincia="",string pais="");
inline string getDNI() const {
return dni_;
}
inline void setDNI(string dni){
dni_=dni;
}
inline string getNombre() const {
return nombre_;
}
inline void setNombre(string nombre){
nombre_=nombre;
}
inline string getApellidos() const {
return apellidos_;
}
inline void setApellidos(string apellidos){
apellidos_=apellidos;
}
inline string getDireccion() const {
return direccion_;
}
inline void setDireccion(string direccion){
direccion_=direccion;
}
inline string getLocalidad() const {
return localidad_;
}
inline void setLocalidad(string localidad){
localidad_=localidad;
}
inline string getProvincia() const {
return provincia_;
}
inline void setProvincia(string provincia){
provincia_=provincia;
}
inline string getPais() const {
return pais_;
}
inline void setPais(string pais){
pais_=pais;
}
inline int getEdad() const {
return edad_;
}
bool setEdad(int edad);
inline string getApellidosyNombre(){
return(apellidos_+", "+nombre_);
}
inline bool mayor(){
return(edad_>=18);
}
};
#endif
|
import { useEffect, useState } from 'react'
import { useCallback } from 'react'
import { Labels, createNode } from '../../types'
import * as E from 'fp-ts/Either'
import AceEditor from 'react-ace'
import 'ace-builds/src-noconflict/mode-javascript'
import 'ace-builds/src-noconflict/theme-dracula'
import { pipe } from 'fp-ts/lib/function'
const title = 'Function'
const description =
'Lets you run a custom javascript function'
const inputLabels: ReadonlyArray<{
_tag: 'string'
value: string
}> = [] as const
const outputLabels = [
{
_tag: 'string',
value: 'result',
},
] as const satisfies Labels
const contentLabels = [
{
_tag: 'string',
value: 'function',
},
] as const satisfies Labels
const getArgs = (raw_string: string) => {
const argPattern = /function\s?(.*)\(([^)]*)\)/ // Regular expression pattern
const matches = raw_string.match(argPattern) // Get array with matched strings
// console.log("raw_string", raw_string)
// console.log("matches", matches)
if (matches) {
const name = matches[1].trim() // Get first matched substring
const args = matches[2] // Get first matched substring
.split(',') // Split arguments in the form 'arg1, arg2, arg3'
.map((arg: string) => arg.trim()) // Trim whitespace around each argument
.filter((arg: string) => arg) // Remove empty ones
return [name, args] as [string, string[]]
}
return [null, []] as [null, string[]]
}
const getBody = (raw_string: string) => {
const bodyPattern = /{([\s\S]*)}/ // Regular expression pattern
const body = raw_string.match(bodyPattern)?.[1] // Get array with matched strings
return body
}
const node = {
function: createNode({
config: {
title,
description,
inputLabels,
outputLabels,
contentLabels,
// lazy: true,
},
func: ({ inputs, contents }) => {
// console.log('inputs', inputs)
const [name, args] = getArgs(contents.function?.value ?? '')
const body = getBody(contents.function?.value ?? '')
const customFunc = pipe(
E.fromNullable(new Error("no function body"))(body),
E.chainW((body) =>
E.tryCatch(
() => new Function(...args, body),
(reason) => new Error(String(reason))
)),
)
// if (E.isRight(customFunc)) {
// console.log('customFunc', customFunc.right({a: 1}))
// }
const result = pipe(
customFunc,
E.chain((func) => {
for (const key of args) {
if (inputs[key] === null) {
return E.left(new Error(`missing input ${key}`))
}
}
return E.right(func)
}),
E.chain((func) =>
E.tryCatch(
() => func(...args.map((key) => inputs[key]?.value)),
(reason) => new Error(String(reason))
),
),
E.map((result) => ({
result: {
_tag: "string",
value: result.toString()
} as const
}))
)
console.log("inputs", inputs)
console.log("contents", contents)
console.log("result", result)
return result
},
Component: ({ contents, setContents }) => {
// console.log('contents', contents)
return <AceEditor
value={contents.function?.value.toString() ?? ''}
height='200px'
mode='javascript'
theme='dracula'
onChange={(e) => setContents({
function: {
_tag: 'string',
value: e
}
})}
className='w-full p-2 rounded-md mb-4 nodrag'
placeholder='function(a, b) { return a + b }'
/>
},
getInputLabels: ({contents}) => {
const [name, args] = getArgs(contents.function?.value ?? '')
return E.right(
args.map((arg) => ({
_tag: 'string',
value: arg,
} as const
))
)
},
getTitle: (contents) => {
const [name, args] = getArgs(contents.function?.value ?? '')
return name ?? 'function'
},
})
}
export default node
|
Note:
1.Ikkada importent emity ante top to bottom povali code,
2.bottom to top code podu okay na....
debugging
==========
debugging means to find the error and took correct the error also..
Note:
The 'try' block lets you test a block of code for errors.(1.try blocks anedi, try lo unde code lo errors unnayoo ledo
check chesthundi.okavella erros unte haa errors ni hadle
cheyadaniki try nundi 'except' lo ki jump chesthundi.
2.ledu try lo emi errors leuv annapudu code anedi try lo ne execute hai
bayataku vasthundi.Errors unte ne except lo ki jump auvthundi lekunte jump kadu..)
The 'except' block lets you handle the error. (try nunchi vachina haa error ni except handle chesthundi)
raise Exception
If a specific "condition" occurs(ఏర్పడుతుంది), you can manually raise exceptions with a raise keyword.
Ex:
try:
f = open("C:/Users/BALAMURALI/Desktop/test.txt")
except:
print('Could not open file')
finally:
f.close()
print('Program continue')
output
------
Program continue
EX:
try:
f = open("C:/Users/BALAMURALI/Desktop/good.txt") --->good.txt ane file ledu kabbati ee location lo error vasthundi..
except:
print('Could not open file')
finally:
f.close()
print('Program continue')
output
------
Could not open file
Traceback (most recent call last):
File "C:\Users\BALAMURALI\Desktop\python.py", line 6, in <module>
f.close()
NameError: name 'f' is not defined
((Specific ga "if condition" lo euuvali ante ela "raise Exception" ela euvvachunu..))
EX:
x = 10
if x > 5:
raise Exception('x should not exceed 5.The value of x was: {}'.format(x))
output
-------
Traceback (most recent call last):
File "C:\Users\BALAMURALI\Desktop\python.py", line 3, in <module>
raise Exception('x should not exceed 5.The value of x was: {}'.format(x))
Exception: x should not exceed 5(x 5కి మించకూడదు).The value of x was: 10
(OR)
EX:
x = 2
if x > 5:
raise Exception('x should not exceed 5.The value of x was: {}'.format(x))
print('Code is Executed..!!')
output
------
Code is Executed..!!
Ex:
student_age = int(input('Enter student age:'))
if student_age < 2:
raise Exception("Sorry!,student age cannot be lower than 2") (క్షమించండి!, విద్యార్థి వయస్సు 2 కంటే తక్కువ ఉండకూడదు)
print('Student age higher then 2')
print('So code is executed!!')
output
------
Enter student age:4
Student age higher then 2
So code is executed!!
output
-----
Enter student age:2
Student age higher then 2
So code is executed!!
output
-------
Enter student age:1
Traceback (most recent call last):
File "C:\Users\BALAMURALI\Desktop\python.py", line 4, in <module>
raise Exception("Sorry!,student age cannot be lower than 2")
Exception: Sorry!,student age cannot be lower than 2 (క్షమించండి!, విద్యార్థి వయస్సు 2 కంటే తక్కువ ఉండకూడదు)
output
------
Enter student age:-3
Traceback (most recent call last):
File "C:\Users\BALAMURALI\Desktop\python.py", line 4, in <module>
raise Exception("Sorry!,student age cannot be lower than 2")
Exception: Sorry!,student age cannot be lower than 2
EX:
student_age = int(input('Enter Student age:'))
if student_age > 2:
raise Exception ("Sorry!,Student age cannot be Higher than 2 ")
print('The condition is true')
print('The code is End')
output
-------
Enter Student age:3
Traceback (most recent call last):
File "C:\Users\BALAMURALI\Desktop\python.py", line 4, in <module>
raise Exception ("Sorry!,Student age cannot be Higher than 2 ")
Exception: Sorry!,Student age cannot be Higher than 2
output
-------
Enter Student age:1
The condition is true
The code is End
EX:
try:
raise Exception('spam','eggs') #args ante evi = spam,eggs
except Exception as inst:
print(type(inst))
print(inst.args)
print(inst)
x,y = inst.args
print('x=', x)
print('y=', y)
output
-------
<class 'Exception'>
('spam', 'eggs')
('spam', 'eggs')
x= spam
y= eggs
raise ValueError
EX:
try:
amount = 1999
if amount < 2999:
# raise the ValueError
raise ValueError("Please add money in your account")
else:
print("You are eligible to purchase DSA Self Paced course")
# if false then raise the value error
except ValueError as e:
print(e)
output
------
Please add money in your account
EX:
while True:
try:
x = int(input("Please enter a number:"))
break
except ValueError:
print('Oops! That was no valid number. Try again....')
output
-------
Please enter a number: # observe here ikkada number menction cheyaledu kabbati, again and again vasthune untundi...
Oops! That was no valid number. Try again....
Please enter a number:
Oops! That was no valid number. Try again....
Please enter a number:
output
--------
Please enter a number:2 #observe here ikkada number menction cheshamu kabbati, ikkadi varukey program end auvthundi..
Syntax:
try:
{Run This code}
except:
{Run this code if an exception occurs}
(మినహాయింపు సంభవించినట్లయితే ఈ కోడ్ని అమలు చేయండి.)
else:
{Run this code if no exception occurs}
(మినహాయింపు జరగకపోతే ఈ కోడ్ని అమలు చేయండి)
finally
{Always run this code}
Exception
=========
An exception is a runtime error which can be handled by the 'programmer'.
All exceptions are represented as classes in python.
Type of Exception
1. Built-in Exception -Exceptions which are already available in python Language.The
base class for all built-in exceptions is BaseException class.
2. User Defined Exception -A programmer can create his own exceptions,called
User-defined exceptions.
Need of Exception Handling
1.When an exception occurs,the program terminates suddenly.
2.Suddenly termination of program may occupt the program.
3.Exception may cause data loss from the database or a file.
Exception Handling
Try-The try block contains code which may cause exceptions.
Syntax:
Statements
Except - The except block is used to catch an exception that is raised in the try block.(ట్రై బ్లాక్లో లేవనెత్తిన మినహాయింపును క్యాచ్ చేయడానికి మినహా బ్లాక్ ఉపయోగించబడుతుంది.)
There can be multiple except block for try block.(ట్రై బ్లాక్ కోసం 'బ్లాక్ మినహా అనేకం' ఉండవచ్చు)
syntax:
except ExceptionName:
statements
Else - This block will get executed when no exception is raised.Else block is executed after try block
(మినహాయింపు లేకపోయినా ఈ బ్లాక్ అమలు చేయబడుతుంది. ప్రయత్నించిన తర్వాత బ్లాక్ ఎగ్జిక్యూట్ చేయబడుతుంది)
syntax:
else:
statements
Finally - This block will get executed irrespective of whether there is an exception or not.
(మినహాయింపు ఉందా లేదా అనే దానితో సంబంధం లేకుండా ఈ బ్లాక్ అమలు చేయబడుతుంది)
syntax:
finally:
statements
1.We can write several except blocks for a single try block.
2.we can write multiple except blocks to handle multiple exceptions.
3.we can write block without any except blocks.
4.we can not write except block without a try block.
5.Finally block is always executed irrespective of whether there is an exception or not.
6.Else block is optional
7.Finally block is optional
EX:1
try:
statement
except ExceptionClassName:
Statement
else: #Optional
Statement
finally: #Optional
Statement
OR
try:
Statement
except ExceptionClassName:
statement
EX:2(Multiple Exception blocks)
try:
Statement
except ExceptionClassName1:
Statement
except ExceptionClassName2:
Statement
Except
---------
1.with the ExceptionClass Name
except ExceptionClassName:
Statement
2.Exception as an object
except ExceptionClassName as obj:
Statement
3.Multiple Exception within tuple
except(ExceptionClassName1,ExceptionClassName2,ExceptioncClassName3,......):
Statement
4.Catch any Type of Exception
except:
Statement
------------Theory complete----------
Note: ela yee errors naina handle cheyadaniki supparat supparat ga except errors untai okay na.. example ga nenu
ZeroDivisionError, IndexError ni chupinchanu inka untai google lo chudu..
ZeroDivisionError
------------------
ZeroDivisionError anedi only "Division zero tho chesina" Error ni matrame handle chesthundi.
EX:
def this_fails():
x = 1/0
try:
this_fails()
except ZeroDivisionError as err:
print('Handling run-time error:',err)
output
-------
Handling run-time error: division by zero
EX:
L = [22,33,44,55]
try:
print(L[3])
print(100/0) ---->Look here
print(L[0])
except: # ela only 'except' anipedithey anni errors ni handle chesthundi ani..artham
print("Exception Generated...")
print("End of Program...")
EX:
L = [22,33,44,55]
try:
print(L[3])
print(100/0)
print(L[0])
except ZeroDivisionError:
print("Division 0 is not correct")
print("End of Program...")
output
-------
55
Exception Generated...
End of Program...
EX:
try:
numerator = int(input('Enter numerator:'))
denominator = int(input('Enter denominator:'))
result = numerator/denominator
print(result)
except: # ela only 'except' anipedithey anni errors ni handle chesthundi ani..artham
print('Denominator cannot be 0. Please try again')
print("Program End!!")
output
------
Enter numerator:12
Enter denominator:0
Denominator cannot be 0. Please try again
Program End
EX:
try:
numerator = int(input('Enter numerator:'))
denominator = int(input('Enter denominator:'))
result = numerator/denominator
print(result)
except ZeroDivisionError:
print('Denominator cannot be 0. Please try again')
print("Program End!!")
output
------
Enter numerator:10
Enter denominator:0
Denominator cannot be 0. Please try again
Program End!!
IndexError
----------
EX:
L = [11,22,33,44]
a = L[6]
print(a)
outptu
------
Traceback (most recent call last):
File "C:\Users\BALAMURALI\Desktop\python.py", line 2, in <module>
a = L[6]
IndexError: list index out of range
Ex:python program just you will analysis
L = [11,22,33,44]
a = L[3]
print(a)
output
------
44 -------->ela ravali answer index number esthey
Ex:
L = [11,22,33,44]
try:
print(L[3])
print(L[4])
print(L[0])
except IndexError:
print("You are enter Wrong index number try again!!")
print("End of Program...")
output
------
44
You are enter Wrong index number try again!!
End of Program...
EX:
my_list = [1,2,3]
i =int(input('Enter index:'))
print(my_list[i])
output
------
Enter index:5
Traceback (most recent call last):
File "C:\Users\BALAMURALI\Desktop\python.py", line 16, in <module>
print(my_list[i])
IndexError: list index out of range
output
------
Enter index:2
3
**Note: ela indexError vachinappudu, try lo except lo ela handle cheyali
EX:
L = [22,33,44,55]
try:
print(L[3])
print(L[7])
print(L[0])
except IndexError:
print("Index out of the range...")
print("End of Program...")
output
-----
55
Index out of the range...
End of Program...
EX:
try:
my_list = [1,2,3]
i =int(input('Enter index:'))
print(my_list[i])
except IndexError:
print("Index cannot be greater than size of list.")
print("Program End!!")
output
-----
Enter index:6
Index cannot be greater than size of list.
Program End!!
output
------
Enter index:2
3
Program End!!
EX:
try:
numerator = int(input('Enter numerator:'))
denominator = int(input('Enter denominator:'))
result = numerator/denominator
print(result)
my_list = [1,2,3]
i =int(input('Enter index:'))
print(my_list[i])
except ZeroDivisionError:
print('Denominator cannot be 0. Please try again')
except IndexError:
print("Index cannot be greater than size of list.")
print("Program End!!")
output
------
Enter numerator:5
Enter denominator:2
2.5
Enter index:2
3
Program End!!
output
-------
Enter numerator:3
Enter denominator:0
Denominator cannot be 0. Please try again
Program End!!
output
------
Enter numerator:2
Enter denominator:1
2.0
Enter index:4
Index cannot be greater than size of list.
Program End!!
NameError
==========
Raised when a 'variable' is not found in local or global scope
(స్థానిక లేదా ప్రపంచ పరిధిలో ఒక 'వేరియబుల్' కనిపించనప్పుడు లేవనెత్తబడింది)
*********************************
Note: particular ga Error ekkada undi ani thelusukovali ante ela rayali "Exception"
EX:
a = b
output
-----
Traceback (most recent call last):
File "C:\Users\BALAMURALI\Desktop\python.py", line 1, in <module>
a = b #a ku value vachesi b, b ku value ekkada undi.
NameError: name 'b' is not defined
(OR)
EX:
try:
a = b
except Exception as e:
print(e)
output
------
name 'b' is not defined
*********************************
EX:
a = b ##a ku value vachesi b, b ku value ekkada undi.
ouptut
-----
Traceback (most recent call last):
File "C:\Users\BALAMURALI\Desktop\python.py", line 1, in <module>
a = b #a ku value vachesi b, b ku value ekkada undi.
NameError: name 'b' is not defined
EX:
try:
a = b
except:
print("Some problem may have occured")
output
-------
Some problem may have occured
EX:
L1 = [22,33,44,55]
print(L[3])
output
-------
Traceback (most recent call last):
File "C:\Users\BALAMURALI\Desktop\python.py", line 2, in <module>
print(L[3])
NameError: name 'L' is not defined
Ex:
L1 = [22,33,44,55]
try:
print(L1[3])
print(L[1])
print(L1[0])
except NameError:
print("Sorry! NameError Try agian okay")
print("End of Program...")
output
------
55
Sorry! NameError Try agian okay
End of Program...
EX:
a = "Hello i am a Student"
b = "Ok"
print(a + c)
output
------
Traceback (most recent call last):
File "C:\Users\BALAMURALI\Desktop\python.py", line 3, in <module>
print(a + c)
NameError: name 'c' is not defined---------------------->Look here
EX:
try:
a = "Hello i am a Student"
b = "Ok"
c = a + b
print(z)
except NameError:
print("Sorry! NameError Try agian okay")
print("End of Program...")
output
------
Sorry! NameError Try agian okay
End of Program...
EX:
a = 12
b = 16
print(a + m)
output
------
Traceback (most recent call last):
File "C:\Users\BALAMURALI\Desktop\python.py", line 3, in <module>
print(a + m)
NameError: name 'm' is not defined
EX:
a = 12
b = 16
try:
print(a + m)
except NameError:
print("Sorry! NameError Try agian okay")
print("End of Program...")
output
------
Sorry! NameError Try agian okay
End of Program...
EX:
try:
print(x)
except NameError:
print("variable x is not defined")
output
-------
variable x is not defined
EX:
try:
x = 20
y = 10
z = x + y
print(f'c value is:{z}')
except NameError:
print("variable x is not defined")
output
------
c value is:30
Syntax Errors
syntax error ante starting and colsing semicoluns same undali
EX:
print("I am Murali')
output
------
File "C:\Users\BALAMURALI\Desktop\python.py", line 1
print("I am Murali')
^
SyntaxError: EOL while scanning string literal
EX:
try:
print("Hello I am Murali')
output
------
File "C:\Users\BALAMURALI\Desktop\python.py", line 2
print("Hello I am Murali')
^
SyntaxError: EOL while scanning string literal--->like this
Type Error
Ex:
print('Hello'+2)
output
------
Traceback (most recent call last):
File "C:\Users\BALAMURALI\Desktop\python.py", line 1, in <module>
print('Hello'+2)
TypeError: can only concatenate str (not "int") to str
EX:
a = 'Hello'
b = 12
c = a + b
print(c)
output
-----
Traceback (most recent call last):
File "C:\Users\BALAMURALI\Desktop\python.py", line 3, in <module>
c = a + b
TypeError: can only concatenate str (not "int") to str----------------->look here...
EX:
L1 = [22,3,55]
T = (4,56,67)
print(L1+T)
output
-------
Traceback (most recent call last):
File "C:\Users\BALAMURALI\Desktop\python.py", line 3, in <module>
print(L1+T)
TypeError: can only concatenate list (not "tuple") to list
ValueError
ValueError is thrown when a finction's argument is of an inappropriate type.
Ex:
EX:
a = int(input('Ener value:'))
print(a)
ouptut
------
Ener value:22
22
EX:
a = int(input('Ener value:'))
print(a)
output
------
Ener value:xyz
Traceback (most recent call last):
File "C:\Users\BALAMURALI\Desktop\python.py", line 1, in <module>
a = int(input('Ener value:'))
ValueError: invalid literal for int() with base 10: 'xyz' ---------->look here
EX:
a = int(input('Ener Float value:'))
print(a)
outptu
-----
Ener Float value:23.6
Traceback (most recent call last):
File "C:\Users\BALAMURALI\Desktop\python.py", line 1, in <module>
a = int(input('Ener Float value:'))
ValueError: invalid literal for int() with base 10: '23.6'
EX:
a = float(input('Ener Float value:'))
print(a)
output
------
Ener Float value:2.3
2.3
EX:
a = float(input('Ener Float value:'))
print(a)
outptu
------
Ener Float value:jik
Traceback (most recent call last):
File "C:\Users\BALAMURALI\Desktop\python.py", line 1, in <module>
a = float(input('Ener Float value:'))
ValueError: could not convert string to float: 'jik'---------->look here
ModuleNotFoundError
ModuleNotFoundError is thrown when a module could not be found.
EX:
import maths-->maths anedi python lo lene ledu okay appudu errorvasthundi
output
-------
Traceback (most recent call last):
File "C:\Users\BALAMURALI\Desktop\python.py", line 1, in <module>
import maths
ModuleNotFoundError: No module named 'maths'
EX:
import social ------->social anedi python lo lene ledu okay appudu errorvasthundi
output
------
Traceback (most recent call last):
File "C:\Users\BALAMURALI\Desktop\python.py", line 1, in <module>
import social
ModuleNotFoundError: No module named 'social'
ImportError
------------
ImportError is thrown when a specified function cannot be found
EX:
from math import sqrt --------->math lo sqrt function undi kabatti error radu..
a = sqrt(144)
print(a)
output
-----
12.0
Ex:
from math import cube -->math lo cube function undadu kabatti importError vasthundi.
a = cube(144)
print(a)
output
------
Traceback (most recent call last):
File "C:\Users\BALAMURALI\Desktop\python.py", line 1, in <module>
from math import cube
ImportError: cannot import name 'cube' from 'math' (unknown location)
KeyError
---------
KeyError is thrown when a key is not found.This exception is raised when a mapping(dictionary)key
is not found in the set of existing keys.
EX:
emp_dict = {'Name':'Murali', 'ID':1}
emp_id = emp_dict['ID']
print('The Employee ID is {}'.format(emp_id))
emp_role = emp_dict['Role']
print(emp_role)
output
-----
The Employee ID is 1
Traceback (most recent call last):
File "C:\Users\BALAMURALI\Desktop\python.py", line 6, in <module>
emp_role = emp_dict['Role']
KeyError: 'Role'
(OR)--->handle the KeyError
emp_dict = {'Name':'Murali', 'ID':1}
try:
emp_id = emp_dict['ID']
print('The Employee ID is {}'.format(emp_id))
emp_role = emp_dict['Role']
print(emp_role)
except KeyError as ke:
print('Key Not Found in Employee Dictionary:',ke)
EX:
a = {1:'Hello',2:'Good',3:"Nice"}
c = a[2]
print(c)
output
-------
Good
EX:
a = {1:'Hello',2:'Good',3:"Nice"}
c = a[4]
print(c)
output
------
Traceback (most recent call last):
File "C:\Users\BALAMURALI\Desktop\python.py", line 2, in <module>
c = a[4]
KeyError: 4 ----------->look here
EX:
a = {"name":"BalaMurali","age":26,"Color":"Black","city":"NDK"}
b = a['name']
print(b)
output
------
BalaMurali
EX:
a = {"name":"BalaMurali","age":26,"Color":"Black","city":"NDK"}
b = a['village']
print(b)
output
------
Traceback (most recent call last):
File "C:\Users\BALAMURALI\Desktop\python.py", line 5, in <module>
b = a['village']
KeyError: 'village' ----------->look here
EOFError
---------
EOFError raised when the imput() function hits the end-of-file condition.
How to Handle Exceptions
---------------------------
In python,exceptions can be handled using a try statement.
try: The critical operation which can raise an exception is placed inside the try clause.
except: The code that handles the exceptions is written in the except clause.
Syntax
--------
try:
statements that generate exceptions
except:
statement(s) to handle exceptions
finally block
----------------
finally block anedi try,except blocks execute aina auvakapoina finally block execute authundi.
EX:
try:
numerator = int(input('Enter numerator:'))
denominator = int(input('Enter denominator:'))
result = numerator/denominator
print(result)
except ZeroDivisionError:
print('Denominator cannot be 0. Please try again')
finally:
print('Always printed')
print("Program End!!")
output
------
Enter numerator:3
Enter denominator:2
1.5
Always printed
Program End!!
output
------
Enter numerator:3
Enter denominator:0
Denominator cannot be 0. Please try again
Always printed
Program End!!
EX:
try:
my_list = [1,2,3]
i =int(input('Enter index:'))
print(my_list[i])
except IndexError:
print("Index cannot be greater than size of list.")
finally:
print('Always printed')
print("Program End!!")
output
-------
Enter index:3
Index cannot be greater than size of list.
Always printed
Program End!!
output
------
Enter index:2
3
Always printed
Program End!!
EX:
try:
numerator = int(input('Enter numerator:'))
denominator = int(input('Enter denominator:'))
result = numerator/denominator
print(result)
my_list = [1,2,3]
i =int(input('Enter index:'))
print(my_list[i])
except ZeroDivisionError:
print('Denominator cannot be 0. Please try again')
except IndexError:
print("Index cannot be greater than size of list.")
finally:
print('Always printed')
print("Program End!!")
output
------
Enter numerator:2
Enter denominator:0
Denominator cannot be 0. Please try again
Always printed ----> look here
Program End!!
output
------
Enter numerator:2
Enter denominator:1
2.0
Enter index:5
Index cannot be greater than size of list.
Always printed ---->look here
Program End!!
output
-----
Enter numerator:2
Enter denominator:3
0.6666666666666666
Enter index:2
3
Always printed --->look here
Program End!!
else block
-----------
else block anedi, try block lo unna 'mootham code' execute aitheyne else block lo unna code execute auvthundi
try block lo error vasthe else block execute kadu..appudu haa error ni try block vachesi 'except lo ki' pampisthundi
idi nuv handle cheai ani..
EX:
try:
print("Hello I am Murali")
except:
print("Something went wrong")
else:
print("Nothing went wrong")
output
------
Hello I am Murali
Nothing went wrong
Ex:
try:
numerator = int(input('Enter numerator:'))
denominator = int(input('Enter denominator:'))
result = numerator/denominator
print(result)
except ZeroDivisionError:
print('Denominator cannot be 0. Please try again')
else:
print('ok')
finally:
print('Always printed')
print("Program End!!")
output
------
Enter numerator:3
Enter denominator:0
Denominator cannot be 0. Please try again
Always printed
Program End!!
output
-------
Enter numerator:3
Enter denominator:5
0.6
ok
Always printed
Program End!!
EX:
try:
numerator = int(input('Enter numerator:'))
denominator = int(input('Enter denominator:'))
result = numerator/denominator
print(result)
my_list = [1,2,3]
i =int(input('Enter index:'))
print(my_list[i])
except ZeroDivisionError:
print('Denominator cannot be 0. Please try again')
except IndexError:
print("Index cannot be greater than size of list.")
else:
print('Ok')
finally:
print('Always printed')
print("Program End!!")
output
------
Enter numerator:3
Enter denominator:0
Denominator cannot be 0. Please try again
Always printed
Program End!!
output
------
Enter numerator:3
Enter denominator:2
1.5
Enter index:4
Index cannot be greater than size of list.
Always printed
Program End!!
output
------
Enter numerator:2
Enter denominator:3
0.6666666666666666
Enter index:2
3
Ok
Always printed
Program End!!
Ex:
try:
my_list = [1,2,3]
i =int(input('Enter index:'))
print(my_list[i])
except IndexError:
print("Index cannot be greater than size of list.")
else:
print('ok')
finally:
print('Always printed')
print("Program End!!")
output
------
Enter index:3
Index cannot be greater than size of list.
Always printed
Program End!!
output
------
Enter index:2
3
ok
Always printed
Program End!!
EX:
a = 10
b = 5
d = a/b
print(d)
print('Rest of the code')
output
------
2.0
Rest of the code
EX:
a = 10
b = 0 #---->0 tho division cheyakudadu rule anthey.
d = a/b
print(d)
print('Rest of the code')
output
------
Traceback (most recent call last):
File "C:\Users\BALAMURALI\Desktop\python.py", line 3, in <module>
d = a/b
ZeroDivisionError: division by zero
note:ela error vasthundi.appudu e error ni handle cheyali ante 'exception' use cheyali.
****************************************************
Note:
try lo rasina code error vasthundi(error throw chesthundi) ani anipisthe, ahh error ni handle
cheyadaniki 'except' block lo ahh error ni handle cheyavachunu.
******************************************************
EX:
a = 10
b = 5
try:
d = a/b
print(d)
except ZeroDivisionError:
print('Division by Zero Not Allowed')
print('Rest of the code')
output
------
2.0
Rest of the code
EX:
a = 10
b = 5
try:
c = a/b
print(f'c value is:{c}')
except ZeroDivisionError:
print('Zero Division Not Allowed')
print('Rest of the code')
output
------
c value is:2.0
Rest of the code
EX:
a = 10
b = 0
try:
d = a/b
print(d)
except ZeroDivisionError:
print('Division by Zero Not Allowed')
print('Rest of the code')
output
------
Division by Zero Not Allowed
Rest of the code
EX:
a = 10
b = 5
try:
d = a/b
print(d)
print('Inside Try')
except ZeroDivisionError:
print('Division by Zero Not Allowed')
print('Rest of the code')
output
------
2.0
Inside Try
Rest of the code
EX:
a = 10
b = 0
try:
d = a/b
print(d)
print('Inside Try')
except ZeroDivisionError:
print('Division by Zero Not Allowed')
print('Rest of the code')
output
------
Division by Zero Not Allowed
Rest of the code
EX:
a = 10
b = 5
try:
d = a/b
print(d)
print('Inside Try')
except ZeroDivisionError:
print('Division by Zero Not Allowed')
else:
print('Inside Else')
print('Rest of the code')
output
------
2.0
Inside Try
Inside Else
Rest of the code
EX:
a = 10
b = 0
try:
d = a/b
print(d)
print('Inside Try')
except ZeroDivisionError:
print('Division by Zero Not Allowed')
else:
print('Inside Else')
print('Rest of the code')
output
-----
Division by Zero Not Allowed
Rest of the code
EX:
a = 10
b = 5
try:
d = a/b
print(d)
print('Inside Try')
except ZeroDivisionError:
print('Division by Zero Not Allowed')
else:
print('Inside Else')
finally:
print('Inside Finally')
print('Rest of the code')
output
------
2.0
Inside Try
Inside Else
Inside Finally
Rest of the code
EX:
a = 10
b = 0
try:
d = a/b
print(d)
print('Inside Try')
except ZeroDivisionError:
print('Division by Zero Not Allowed')
else:
print('Inside Else')
finally:
print('Inside Finally')
print('Rest of the code')
output
------
Division by Zero Not Allowed
Inside Finally
Rest of the code
EX:
a = 10
b = 0
try:
d = a/b
print(d)
print('Inside Try')
except ZeroDivisionError as obj:
print(obj)
print('Rest of the code')
output
-------
division by zero
Rest of the code
EX:
a = 10
b = 5
try:
d = a/b
print(d)
print('Inside Try')
except ZeroDivisionError as obj:
print(obj)
print('Rest of the code')
output
------
2.0
Inside Try
Rest of the code
Ex:
a = 10
b = 0
try:
d = a/b
print(d)
except ZeroDivisionError as obj:
print(obj)
except NameError as ob:
print(ob)
print('Rest of the code')
outout
-------
division by zero
Rest of the code
EX:
a = 10
b = 0
try:
d = a/c---->kavalani rashanu.NameError ela vasthundo chudam ani.
print(d)
except ZeroDivisionError as obj:
print(obj)
except NameError as ob:
print(ob)
print('Rest of the code')
output
-------
name 'c' is not defined
Rest of the code
EX:
a = 10
b = 0
try:
d = a/b
print(d)
except (NameError,ZeroDivisionError) as obj:
print(obj)
print('Rest of the code')
output
------
division by zero
Rest of the code
EX:
a = 10
b = 0
try:
d = a/c
print(d)
except (NameError,ZeroDivisionError) as obj:
print(obj)
print('Rest of the code')
output
------
name 'c' is not defined
Rest of the code
EX:
a = 10
b = 0
try:
d = a/c
print(d)
except: #(ExceptionClassName mention cheyakunda ela kuda simple ga rayavachunu)
print('Exception Handler')
print('Rest of the code')
output
------
Exception Handler
Rest of the code
EX:
a = 10
b = 0
try:
d = a/b
print(d)
except:
print('Exception Handler')
print('Rest of the code')
output
-------
Exception Handler
Rest of the code
Assert Statement in Python
The assert Statement is useful to ensure that a given condition is True.If it is
not true,it raises AssertionError.
syntax: assert condition,error_message
1.If the condition is False then the exception by the name AssertionError is
raised along with the message.
2.If message is not given and the condition is False then also AssertionError
is raised without message.
EX:
a = 20
assert a <= 10
output
------
Traceback (most recent call last):
File "C:\Users\BALAMURALI\Desktop\python.py", line 2, in <module>
assert a <= 10
AssertionError -------->Look here
EX:
a = 20
assert a <= 10,'Invalid Number'
output
-----
Traceback (most recent call last):
File "C:\Users\BALAMURALI\Desktop\python.py", line 2, in <module>
assert a <= 10,'Invalid Number'
AssertionError: Invalid Number ------>Look here
EX:
a = 10
assert a <= 10,'Invalid Number'
output
------
output vachindi adi kanabadadu.
Difference between Error and Exception in Python
1.An exception is an error that can be handled by a programmer.
2.An exception which are not handled by programmer,becomes an error.
3.All exceptions occur only at runtime.
4.Error may occur at compile time or runtime.
User Defined Exception in Python
A Programmer can create his own exceptions, called user-defined exceptions or Custom Exception.
1.Creating Exception Class using Exception Class as a Base Class
2.Raising Exception
3.Handling Exception
Creating Exception
--------------------
We can create our own exception by creating a sub class to built-in Exception class.
syntax:
class MyException(Exception):
pass
class MyException(Exception):
def __init__(self,arg):
self.msg = arg
Raising Exception
-------------------
raise statement is used to raise the user defined exception.
synatx:
raise MyException('message')
Handling Exception
-----------------
Using try and except block programmer can handle exceptions.
syntax:
try:
statement
except MyException as mye:
Statement
EX:
class BalanceException(Exception):
pass
def checkbalance():
money = 10000
withdraw = 5000
balance = money - withdraw
print(balance)
checkbalance()
output
-----
5000
EX:
class BalanceException(Exception):
pass
def checkbalance():
money = 10000
withdraw = 5000 ---->Look here
try:
balance = money - withdraw
if(balance <= 2000):
raise BalanceException('Insufficient Balance')
print(balance)
except BalanceException as be:
print(be)
checkbalance()
output
-------
5000
EX:
class BalanceException(Exception):
pass
def checkbalance():
money = 10000
withdraw = 9000------>Look here
try:
balance = money - withdraw
if(balance <= 2000):
raise BalanceException('Insufficient Balance')
print(balance)
except BalanceException as be:
print(be)
checkbalance()
output
-------
Insufficient Balance
(OR)
EX:
class BalanceException(Exception):
pass
def checkbalance():
money = 10000
withdraw = 4000
balance = money - withdraw
if(balance <= 2000):
raise BalanceException('Insufficient Balance')
print(balance)
try:
checkbalance()
except BalanceException as be:
print(be)
output
------
6000
EX:
class BalanceException(Exception):
pass
def checkbalance():
money = 10000
withdraw = 9000
balance = money - withdraw
if(balance <= 2000):
raise BalanceException('Insufficient Balance')
print(balance)
try:
checkbalance()
except BalanceException as be:
print(be)
output
------
Insufficient Balance
Difference between Error and Warning in Python
It is compulsory to handle all error otherwise program will not
exceute,while warning represents a caution and even though it is
not handled,the program will exceute.
Errors are derived as sub class 'StandardError',While warning derived as sub class
from 'Warning' class.
Logging in Python
Logging is useful to track the error or exception or information.It
also helps in debugging.
we use Logging Module to log the error.
syntax:
import logging
from logging import *
basicConfig(**kwargs)Method
This method is used to config the logging system.
syntax:
basicConfig(**kwargs)
1.filename -It specifies that a FileHandler be crated,using the specified filename,
rather than a StreamHandler.
2.filemode - IF filename is specified,open the file in this mode.Defaults to 'a'. We
can write 'w'
3.level - Set the root logger level to the specified level.
4.format - Use the specified format string for the handler.
5.datefmt -Use the specified data/time format,as accepted by time.strftime()
6.style -If format is specified,use this style for the format string.One of '%','{' or'$'
for printf-style,str.format() or string.Template respectively.Defaults to '%'.
Levels
------
NOTSET - 0
DEBUG - 10
INFO - 20
WARNING - 30
ERROR - 40
CRITICAL - 50
Methods
-----------
getLogger()-This method returns a logger with the specified name or,if name is None,return a
logger which is the root logger of the hierarchy if specified,the name is typically a dot -separated
hierarchical name like 'a','a.b', or 'a.b.c.d'.
info(msg) - This will log a message with level INFO on this logger.
warning(msg) - This will log a message with level WARNING on this logger.
error(msg) - This islog a message with level ERROR on this logger.
critical(msg) - This will log a message with level CRITICAL on this logger
exception(msg) - This will log a message with level ERROR on this logger.
Format
----------
Format can take a string with LogRecord attributes in any arrangement you like
asctime - Human-readable time when the LogRecord was created.By default this is
of the form '2003-07-08 16:49:45,896'(the numbers after the comma are millisecond portion of the time).
EX:%(asctime)s
created - Time when the LogRecord was created(as returned by time.time()).
EX:%(created)f
filename - Filename portion of pathname.
LogRecord attributes
-------------------
levelname - Text logging level for the message('DEBUG','INFO','WARNING','ERROR','CRITICAL').
EX:%(levelname)s
levelno - Numeric logging level for the message('DEBUG','INFO','WARNING','ERROR','CRITICAL').
EX:%(levelno)s
lineno - Source line number where the logging call was issued(if available)
message - The logged message,computed as msg % args.This is set when Formatter.format() is invoked.
EX:%(message)s
name -Name of the logger used to log the call
Ex:%(name)s
pathname - Full pathname of the source file where the logging call was issued(if available)
EX:%(pathname)s
args,exc_info,funcname,module,msecs,msg,process,processname,relativecreated,stack_info,thread,threadname.
EX:
from logging import *
warning('This is warning')
error('This is error')
critical('This is critical')
debug('This is Debug')
info('This is Ingo')
output
------
WARNING:root:This is warning
ERROR:root:This is error
CRITICAL:root:This is critical
Note:debug,info viti output's kanipinchauv.
EX:
from logging import *
basicConfig(filename ='logfile.log')
warning('This is warning')
error('This is error')
critical('This is critical')
output
------
logfile file open cheai
EX:
from logging import *
basicConfig(filename ='logfile.log',level = DEBUG)
debug('This is Debug')
info('This is Info')
warning('This is warning')
error('This is error')
critical('This is critical')
output
-----
logfile file open cheai
EX:
from logging import *
basicConfig(filename ='logfile.log',level = DEBUG,filemode = 'w')
debug('This is Debug')
info('This is Info')
warning('This is warning')
error('This is error')
critical('This is critical')
output
-----
logfile file open cheai
EX:
from logging import *
basicConfig(filename ='logfile.log',level = DEBUG,filemode = 'w')
debug('This is Debug in w mode')
info('This is Info')
warning('This is warning')
error('This is error')
critical('This is critical')
output
-----
logfile file open cheai
EX:
from logging import *
basicConfig(filename ='logfile.log',level = DEBUG,filemode = 'w',format = '%(asctime)s -- %(message)s')
debug('This is Debug in w mode')
info('This is Info')
warning('This is warning')
error('This is error')
critical('This is critical')
output
-----
logfile file open cheai
EX:
from logging import *
LOG_FORMAT = '%(asctime)s// %(message)s // %(lineno)d'
basicConfig(filename ='logfile.log',level = DEBUG,filemode = 'w',format = LOG_FORMAT)
debug('This is Debug in w mode')
info('This is Info')
warning('This is warning')
error('This is error')
critical('This is critical')
output
------
logfile file open cheai
EX:
from logging import *
LOG_FORMAT = '{asctime}// {message} // {lineno}'
basicConfig(filename ='logfile.log',level = DEBUG,filemode = 'w',format = LOG_FORMAT,style = '{')
debug('This is Debug in w mode')
info('This is Info')
warning('This is warning')
error('This is error')
critical('This is critical')
ouput
-----
logfile file open cheai
EX:
from logging import *
LOG_FORMAT = '{lineno} ***{name}*** {asctime} *** {message}'
basicConfig(filename ='logfile.log',level = DEBUG,filemode = 'w',format = LOG_FORMAT,style = '{')
debug('This is Debug in w mode')
info('This is Info')
warning('This is warning')
error('This is error')
critical('This is critical')
output
-----
logfile file open cheai
EX:
from logging import *
LOG_FORMAT = '{lineno} ***{name}*** {asctime} *** {message}'
basicConfig(filename ='logfile.log',level = DEBUG,filemode = 'w',format = LOG_FORMAT,style = '{')
logger = getLogger('Geek')
logger.debug('This is Debug')
logger.info('This is Info')
logger.warning('This is warning')
logger.error('This is error')
logger.critical('This is critical')
output
-----
logfile file open cheai
|
## load packages
library(nflfastR)
library(tidyverse)
library(broom)
## load data
chap_6_file <- "./data/pbp_r_chap_6.csv"
if (!file.exists(chap_6_file)) {
pbp_r <- load_pbp(2016:2022)
write_csv(pbp_r, chap_6_file)
} else {
pbp_r <- read_csv(chap_6_file)
}
pbp_r_pass <-
pbp_r |>
filter(!is.na(passer_id))
## format data
pbp_r_pass_td_y <- pbp_r_pass |>
mutate(
pass_touchdown = ifelse(is.na(pass_touchdown), 0, pass_touchdown)
) |>
group_by(season, week, passer_id, passer) |>
summarize(
n_passes = n(), pass_td_y = sum(pass_touchdown),
total_line = mean(total_line)
) |>
filter(n_passes >= 10)
## print summary output to screen
pbp_r_pass_td_y |>
group_by(pass_td_y) |>
summarize(n = n())
## use summary to see different summary of data
pbp_r_pass_td_y |>
ungroup() |>
select(-passer, -passer_id) |>
summary()
## calculate mean and use with Poisson
pass_td_y_mean_r <-
pbp_r_pass_td_y |>
pull(pass_td_y) |>
mean()
plot_pos_r <-
tibble(x = seq(0, 7)) |>
mutate(expected = dpois(x = x, lambda = pass_td_y_mean_r))
ggplot() +
geom_histogram(
data = pbp_r_pass_td_y,
aes(x = pass_td_y, y = after_stat(count / sum(count))),
binwidth = 0.5
) +
geom_line(
data = plot_pos_r, aes(x = x, y = expected),
color = "red", linewidth = 1
) +
theme_bw() +
xlab("Touchdown passes per player per game for 2016 to 2022") +
ylab("Probability")
## individual player total for QB
# pass_ty_d greater than or equal to 10 per week
pbp_r_pass_td_y_geq10 <-
pbp_r_pass_td_y |>
filter(n_passes >= 10)
# take the average touchdown passes for each QB for the previous season
# and current season up to the current game
x_r <- tibble()
for (season_idx in seq(2017, 2022)) {
for (week_idx in seq(1, 22)) {
week_calc_r <-
pbp_r_pass_td_y_geq10 |>
filter((season == (season_idx - 1)) |
(season == season_idx & week < week_idx)) |>
group_by(passer_id, passer) |>
summarize(
n_games = n(),
pass_td_rate = mean(pass_td_y),
.groups = "keep"
) |>
mutate(season = season_idx, week = week_idx)
x_r <- bind_rows(x_r, week_calc_r)
}
}
## look at example output
x_r |>
filter(passer == "P.Mahomes") |>
tail()
## include game totals
pbp_r_pass_td_y_geq10 <-
pbp_r_pass_td_y_geq10 |>
inner_join(x_r, by = c("season", "week", "passer_id", "passer"))
## weekly plots totals
weekly_passing_id_r_plot <-
pbp_r_pass_td_y_geq10 |>
ggplot(aes(x = week, y = pass_td_y, group = passer_id)) +
geom_line(alpha = 0.25) +
facet_wrap(vars(season), nrow = 3) +
theme_bw() +
theme(strip.background = element_blank()) +
ylab("Total passing touchdowns") +
xlab("Week of season")
weekly_passing_id_r_plot
## save for book
fig_6_3 <-
weekly_passing_id_r_plot +
theme(text = element_text(size = 13))
fig_6_3
ggsave("fig_6_3.png", fig_6_3, width = 6, height = 4.25)
## include trend line
weekly_passing_id_r_plot +
geom_smooth(
method = "glm", method.args = list("family" = "poisson"),
se = FALSE,
linewidth = 0.5, color = "blue", alpha = 0.25
)
## save for book
fig_6_4 <-
weekly_passing_id_r_plot +
theme(text = element_text(size = 13))
fig_6_4
ggsave("fig_6_4.png", fig_6_4, width = 6, height = 4.25)
## Poisson regression
pass_fit_r <-
glm(pass_td_y ~ pass_td_rate + total_line,
data = pbp_r_pass_td_y_geq10, family = "poisson"
)
pbp_r_pass_td_y_geq10 <-
pbp_r_pass_td_y_geq10 |>
ungroup() |>
mutate(exp_pass_td = predict(pass_fit_r, type = "response"))
summary(pass_fit_r) |>
print()
tidy(pass_fit_r, exponentiate = TRUE, conf.int = TRUE)
pbp_r_pass_td_y_geq10 |>
filter(passer == "P.Mahomes", season == 2022, week == 22) |>
select(-pass_td_y, -n_passes, -passer_id, -week, -season, -n_games)
## PMF and CDF
pbp_r_pass_td_y_geq10 <-
pbp_r_pass_td_y_geq10 |>
mutate(
p_0_td = dpois(
x = 0,
lambda = exp_pass_td
),
p_1_td = dpois(
x = 1,
lambda = exp_pass_td
),
p_2_td = dpois(
x = 2,
lambda = exp_pass_td
),
p_g2_td = ppois(
q = 2,
lambda = exp_pass_td,
lower.tail = FALSE
)
)
pbp_r_pass_td_y_geq10 |>
filter(passer == "P.Mahomes", season == 2022, week == 22) |>
select(-pass_td_y, -n_games, -n_passes, -passer_id, -week, -season)
## Regression coefficients
x <- rpois(n = 10, lambda = 1)
print(x)
glm_out_r <-
glm(x ~ 1, family = "poisson")
print(tidy(glm_out_r))
print(tidy(glm_out_r, exponentiate = TRUE))
## example with regression coefficients
bal_td_r <- pbp_r |>
filter(posteam == "BAL" & season == 2022) |>
group_by(game_id, week) |>
summarize(td_per_game = sum(touchdown, na.rm = TRUE), .groups = "drop") |>
mutate(week = week - 1)
ggplot(bal_td_r, aes(x = week, y = td_per_game)) +
geom_point() +
theme_bw() +
stat_smooth(
method = "glm",
formula = "y ~ x", method.args = list(family = "poisson")
) +
xlab("Week") +
ylab("Touchdowns per game") +
scale_y_continuous(breaks = seq(0, 6)) +
scale_x_continuous(breaks = seq(1, 20, by = 2))
## save for book
fig_6_6 <-
ggplot(bal_td_r, aes(x = week, y = td_per_game)) +
geom_point() +
theme_bw() +
stat_smooth(
method = "glm",
formula = "y ~ x", method.args = list(family = "poisson")
) +
xlab("Week") +
ylab("Touchdowns per game") +
scale_y_continuous(breaks = seq(0, 6)) +
scale_x_continuous(breaks = seq(1, 20, by = 2)) +
theme(text = element_text(size = 13))
fig_6_6
ggsave("fig_6_6.png", fig_6_6, width = 6, height = 4.25)
glm_bal_td_r <-
glm(td_per_game ~ week, data = bal_td_r, family = "poisson")
print(tidy(glm_bal_td_r))
print(tidy(glm_bal_td_r, exponentiate = TRUE))
|
import { onActivated, onDeactivated, Ref, watch } from 'vue'
export function useKeepScroll(el: Ref<any>) {
let scrollTop = 0
let scrollLeft = 0
function save() {
if (!el.value) return
scrollTop = el.value.scrollTop
scrollLeft = el.value.scrollLeft
}
function restore() {
if (!el.value) return
el.value.scrollTop = scrollTop
el.value.scrollLeft = scrollLeft
}
let listenedEl: HTMLElement | null = null
function removeEventListener() {
listenedEl?.removeEventListener('scroll', save)
listenedEl = null
}
function addEventListener() {
if (!el.value) return
if (listenedEl === el.value) return
removeEventListener()
listenedEl = el.value
listenedEl?.addEventListener('scroll', save)
}
watch(el, addEventListener)
onActivated(addEventListener)
onDeactivated(removeEventListener)
onActivated(restore)
}
|
@using HomeRentManagement.Data;
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title">Update Home Owner</h5>
<button type="button" class="btn-close" aria-label="Close" @onclick="hideUpdate"></button>
</div>
<div class="modal-body">
<form @onsubmit="UpdateHouseBtn">
<div class="form-group">
<label for="HouseName">HouseName:</label>
<input type="text" class="form-control" @bind=@updateHouse.HouseName required />
</div>
<div class="form-group">
<label for="HouseAddress">HouseAddress:</label>
<input type="text" class="form-control" @bind=@updateHouse.HouseAddress required />
</div>
<div class="form-group">
<label for="Floor ">Floor:</label>
<input type="number" class="form-control" @bind="updateHouse.floorNumber" required />
</div>
<div class="form-group">
<label for="Status">Status:</label>
<select class="form-control" @bind="@updateHouse.StatusId" required>
@foreach (var status in statusOptions)
{
<option value="@status.Id">@status.Name</option>
}
</select>
</div>
<button type="submit" class="btn btn-primary mt-3">Update</button>
</form>
</div>
</div>
</div>
@code {
[Parameter]
public House updateHouse{ get; set; }
[Parameter]
public List<Status> statusOptions{ get; set; }
[Parameter]
public EventCallback UpdateHouseBtn{ get; set; }
[Parameter]
public EventCallback hideUpdate { get; set; }
}
|
from typing import Dict, List, Tuple, Type, TYPE_CHECKING
if TYPE_CHECKING:
from ..client import CQiClient
from ..status import StatusOk
from .corpora import Corpus
from .resource import Collection, Model
class Attribute(Model):
@property
def api_name(self) -> str:
return self.attrs['api_name']
@property
def name(self) -> str:
return self.attrs['name']
@property
def size(self) -> int:
return self.attrs['size']
def drop(self) -> 'StatusOk':
''' unload attribute from memory '''
return self.client.api.cl_drop_attribute(self.api_name)
class AttributeCollection(Collection):
model: Type[Attribute] = Attribute
def __init__(self, client: 'CQiClient' = None, corpus: 'Corpus' = None):
super().__init__(client=client)
self.corpus: 'Corpus' = corpus
def _get(self, attribute_name: str) -> Dict:
api_name: str = f'{self.corpus.api_name}.{attribute_name}'
return {
'api_name': api_name,
'name': attribute_name,
'size': self.client.api.cl_attribute_size(api_name)
}
def get(self, attribute_name: str) -> Attribute:
return self.prepare_model(self._get(attribute_name))
def list(self) -> List[Attribute]:
raise NotImplementedError
class AlignmentAttribute(Attribute):
def cpos_by_id(self, id: int) -> Tuple[int, int, int, int]:
''' returns (src_start, src_end, target_start, target_end) '''
return self.client.api.cl_alg2cpos(self.api_name, id)
def ids_by_cpos(self, cpos_list: List[int]) -> List[int]:
''' returns -1 for every corpus position not inside an alignment '''
return self.client.api.cl_cpos2alg(self.api_name, cpos_list)
class AlignmentAttributeCollection(AttributeCollection):
model: Type[AlignmentAttribute] = AlignmentAttribute
def list(self) -> List[AlignmentAttribute]:
return [
self.get(x) for x in
self.client.api.corpus_alignment_attributes(self.corpus.api_name)
]
class PositionalAttribute(Attribute):
@property
def lexicon_size(self) -> int:
return self.attrs['lexicon_size']
def cpos_by_id(self, id: int) -> List[int]:
''' returns all corpus positions where the given token occurs '''
return self.client.api.cl_id2cpos(self.api_name, id)
def cpos_by_ids(self, id_list: List[int]) -> List[int]:
'''
returns all corpus positions where one of the tokens in <id_list>
occurs; the returned list is sorted as a whole, not per token id
'''
return self.client.api.cl_idlist2cpos(self.api_name, id_list)
def freqs_by_ids(self, id_list: List[int]) -> List[int]:
''' returns 0 for every ID in <id_list> that is out of range '''
return self.client.api.cl_id2freq(self.api_name, id_list)
def ids_by_cpos(self, cpos_list: List[int]) -> List[int]:
'''
returns -1 for every corpus position in <cpos_list> that is out of
range
'''
return self.client.api.cl_cpos2id(self.api_name, cpos_list)
def ids_by_regex(self, regex: str) -> List[int]:
'''
returns lexicon IDs of all tokens that match <regex>; the returned
list may be empty (size 0);
'''
return self.client.api.cl_regex2id(self.api_name, regex)
def ids_by_values(self, value_list: List[str]) -> List[int]:
'''
returns -1 for every string in <value_list> that is not found in the
lexicon
'''
return self.client.api.cl_str2id(self.api_name, value_list)
def values_by_cpos(self, cpos_list: List[int]) -> List[str]:
'''
returns "" for every corpus position in <cpos_list> that is out of
range
'''
return self.client.api.cl_cpos2str(self.api_name, cpos_list)
def values_by_ids(self, id_list: List[int]) -> List[str]:
''' returns "" for every ID in <id_list> that is out of range '''
return self.client.api.cl_id2str(self.api_name, id_list)
class PositionalAttributeCollection(AttributeCollection):
model: Type[PositionalAttribute] = PositionalAttribute
def _get(self, positional_attribute_name: str) -> Dict:
attrs = super()._get(positional_attribute_name)
attrs['lexicon_size'] = self.client.api.cl_lexicon_size(attrs['api_name'])
return attrs
def list(self) -> List[PositionalAttribute]:
return [
self.get(x) for x in
self.client.api.corpus_positional_attributes(self.corpus.api_name)
]
class StructuralAttribute(Attribute):
@property
def has_values(self) -> bool:
return self.attrs['has_values']
def cpos_by_id(self, id: int) -> Tuple[int, int]:
'''
returns start and end corpus positions of structure region with id
<id>
'''
return self.client.api.cl_struc2cpos(self.api_name, id)
def ids_by_cpos(self, cpos_list: List[int]) -> List[int]:
'''
returns -1 for every corpus position not inside a structure region
'''
return self.client.api.cl_cpos2struc(self.api_name, cpos_list)
def lbound_by_cpos(self, cpos_list: List[int]) -> List[int]:
'''
returns left boundary of s-attribute region enclosing cpos, -1 if not
in region
'''
return self.client.api.cl_cpos2lbound(self.api_name, cpos_list)
def rbound_by_cpos(self, cpos_list: List[int]) -> List[int]:
'''
returns right boundary of s-attribute region enclosing cpos, -1 if not
in region
'''
return self.client.api.cl_cpos2rbound(self.api_name, cpos_list)
def values_by_ids(self, id_list: List[int]) -> List[str]:
'''
returns annotated string values of structure regions in <id_list>; ""
if out of range
check has_values property first
'''
return self.client.api.cl_struc2str(self.api_name, id_list)
class StructuralAttributeCollection(AttributeCollection):
model: Type[StructuralAttribute] = StructuralAttribute
def _get(self, structural_attribute_name: str) -> Dict:
attrs = super()._get(structural_attribute_name)
attrs['has_values'] = self.client.api.corpus_structural_attribute_has_values(attrs['api_name'])
return attrs
def list(self, filters: Dict = {}) -> List[StructuralAttribute]:
structural_attributes = [
self.get(x) for x in
self.client.api.corpus_structural_attributes(self.corpus.api_name)
]
for k, v in filters.items():
if k == 'has_values':
structural_attributes = [
x for x in structural_attributes
if x.has_values == v
]
elif k == 'part_of':
structural_attributes = [
x for x in structural_attributes
if x.name.startswith(f'{v.name}_')
]
return structural_attributes
|
import React, { useEffect, useState } from "react";
import Style from "./style.module.css";
import { Modal } from "react-bootstrap";
function JobCard({item}) {
// console.log(item)
const [show, setShow] = useState(false);
const handleClose = () => setShow(false);
const handleShow = () => setShow(true);
return (
<div>
<div>
<div className={Style.jobCard}>
<div className={`d-flex ${Style.jobpostDate}`}>
<div>⏳</div>
<div className="ps-2">Posted 10 days ago</div>
</div>
<div className="d-flex align-content-center ">
<div className={`${Style.companyImg}`}>
<img
width={100}
src="https://storage.googleapis.com/weekday-assets/airtableAttachment_1711092299539_00e8b.png"
/>
</div>
<div className={` ms-2 ${Style.CompanyInfo}`}>
<div className={`${Style.companyName}`}>fyno</div>
<div className={`${Style.JobRole}`}>{item.jobRole}</div>
<div className={`${Style.JobLocation}`}>{item.location}</div>
</div>
</div>
<div className={`${Style.JobBudget}`}>
Estimated Salary: ₹18 - 35 LPA ✅
</div>
<div className={`${Style.AboutCompnaySection}`}>
<div className={`${Style.title}`}>About Company</div>
<div style={{ fontWeight: "500" }}>About us</div>
<div className={`${Style.jobDescription}`}>
{item.jobDetailsFromCompany}
</div>
</div>
<div onClick={handleShow} className={`${Style.viewJobSection}`}>
View Job
</div>
<div className={`${Style.ExperienceSection}`}>
<div className={`${Style.ExperienceTitle}`}>Mininum Experience</div>
<div className={`${Style.TotalExp}`}>2 years</div>
</div>
<div className={`${Style.jobBtns}`}>
<button className={`${Style.EasyApply}`}>⚡ Easy Apply</button>
<button className={`${Style.Referral}`}>
<div className={`${Style.ReferralImg}`}>
{Array(2)
.fill(true)
.map((item, index) => (
<div key={index}>
<img
alt="referral-img"
src="https://www.gravatar.com/avatar/2c7d99fe281ecd3bcd65ab915bac6dd5?s=30"
/>
<div className={`${Style.dot}`}></div>
</div>
))}
</div>
<div className="ms-2">Unlock referral asks</div>
</button>
</div>
</div>
</div>
{/* For View Job Details */}
<Modal
className={`${Style.JobDetailsPopup}`}
centered
show={show}
onHide={handleClose}
>
<div className={`${Style.JDDetails}`}>
<h5>Job Description</h5>
<div className={`${Style.AboutCompnaySection}`}>
<div>
<div className={`${Style.title}`}>About Company :</div>
<div
style={{
fontSize: ".8rem",
fontWeight: "400",
padding: "1rem 0",
}}
>
Due Diligence AI that runs comprehensive financial, legal,
regulatory and reputational risk analysis on any given target.
</div>
</div>
<div style={{ fontWeight: "400", fontSize: "1rem" }}>
About us :
</div>
<div className={`${Style.jobDescription}`}>
{item.jobDetailsFromCompany}
</div>
<div style={{ fontWeight: "400", fontSize: "1rem" }}>
Job Summary :
</div>
<div className={`${Style.jobDescription}`}>
We are on the lookout for a React Developer with a minimum of 2
years of experience, proficient in integrating third-party cloud
services, deploying React applications, and knowledgeable in state
management, CSS, and Next.js. The ideal candidate will develop,
maintain, and enhance high-quality web applications, ensuring both
functionality and aesthetic appeal.
</div>
<div style={{ fontWeight: "400", fontSize: "1rem" }}>
Key Responsibilities :
</div>
<div className={`${Style.jobDescription}`}>
Build and refine front-end components and libraries. Translate
designs into high-quality code, ensuring both functionality and
visual fidelity. Optimize application performance for a wide range
of devices and browsers. Monitor and adjust post-deployment
performance. Work closely with UI/UX designers and back-end
developers. Engage in code reviews and actively participate in
team meetings.
</div>
<div style={{ fontWeight: "400", fontSize: "1rem" }}>
Qualifications :
</div>
<div className={`${Style.jobDescription}`}>
Bachelor’s degree in Computer Science, IT, or related field. At
least 2 years in React development. Deep understanding of React.js
and its core principles. Experience with state management tools
(Redux, Context API). Proficiency in CSS and experience with CSS
preprocessors ( Tailwind CSS, SASS and LESS). Familiarity with
Next.js. Experience with RESTful APIs and modern authorization
mechanisms (e.g., JWT). Knowledge in deploying React applications.
Familiarity with front-end development tools (Babel, Webpack,
NPM). Strong problem-solving skills, along with excellent
analytical and communication abilities. Ability to work
effectively in a fast-paced, team-oriented environment.
</div>
<div style={{ fontWeight: "400", fontSize: "1rem" }}>Skills :</div>
<div className={`${Style.jobDescription}`}>
front-end development tools,jwt,html,next.js,state management
tools,restful apis,css,javascript,redux,deploying react
applications,react.js,nextjs,tailwind css,reactjs
</div>
</div>
</div>
</Modal>
</div>
);
}
export default JobCard;
|
package PollSystemApplication.repository;
import PollSystemApplication.model.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Repository;
import java.util.List;
import java.util.Map;
@Repository
public class UserRepositoryImpl implements UserRepository {
private static final String USER_TABLE_NAME = "user";
private static final String POLL_TABLE_NAME = "poll";
private static final String ANSWERS_TABLE_NAME = "answers";
@Autowired
JdbcTemplate jdbcTemplate;
@Override
public Long createUser(User user) {
String sql = "INSERT INTO " + USER_TABLE_NAME + " (first_name, last_name, email ,age, address , joining_date ) VALUES (?, ?,?, ? , ? , ? )";
jdbcTemplate.update(sql, user.getFirstName(), user.getLastName(), user.getEmail(), user.getAge(), user.getAddress(), user.getJoiningDate());
return jdbcTemplate.queryForObject("SELECT LAST_INSERT_ID();", Long.class);
}
@Override
public Map<String, Object> getUserById(Long userId) {
String sql = "SELECT * FROM " + USER_TABLE_NAME + " WHERE user.id=?";
return jdbcTemplate.queryForMap(sql, userId);
}
@Override
public void updateUserById(Long userId, User user) {
String sql = "UPDATE " + USER_TABLE_NAME + " SET first_name=?, last_name=?, email=? , age=? , address=? , joining_date=? " +
"WHERE id=?";
jdbcTemplate.update(sql, user.getFirstName(), user.getLastName(), user.getEmail(), user.getAge(), user.getAddress(), user.getJoiningDate(), userId);
}
@Override
public void deleteUserById(Long userId) {
String sql = "DELETE FROM " + USER_TABLE_NAME + " WHERE user.id=?";
jdbcTemplate.update(sql, userId);
}
@Override
public void toAnswer(User user) {
String sql = "INSERT INTO " + ANSWERS_TABLE_NAME + " (user_id ,question_id ,answer ) VALUES ( ?, ? , ? )";
jdbcTemplate.update(sql, user.getId(), user.getQuestionId(), user.getAnswer());
}
@Override
public List<Map<String, Object>> countUsersAnswerOption(Long questionId) {
String sql = "SELECT SUM(answer=poll.first_option) AS Counter_For_First_Option ,SUM(answer=poll.second_option) AS Counter_For_Second_Option , SUM(answer=poll.third_option) AS Counter_For_Third_Option ,SUM(answer=poll.fourth_option) AS Counter_For_Fourth_Option FROM " + USER_TABLE_NAME + " LEFT JOIN " + ANSWERS_TABLE_NAME + " ON user.id = answers.user_id" + " LEFT JOIN " + POLL_TABLE_NAME + " ON answers.question_id = poll.id " + " WHERE question_id=?";
return jdbcTemplate.queryForList(sql, questionId);
}
@Override
public Map<String, Object> countUsersAnsweredInTotal(Long questionId) {
String sql = "SELECT COUNT(DISTINCT user_id) AS Users_Answered_In_Total FROM " + USER_TABLE_NAME + " LEFT JOIN " + ANSWERS_TABLE_NAME + " ON user.id = answers.user_id" + " LEFT JOIN " + POLL_TABLE_NAME + " ON answers.question_id = poll.id " + " WHERE answer=first_option AND answers.question_id=? OR answer=second_option AND answers.question_id=? OR answer=third_option AND answers.question_id=? OR answer=fourth_option AND answers.question_id=?";
return jdbcTemplate.queryForMap(sql, questionId, questionId, questionId, questionId);
}
@Override
public List<Map<String, Object>> getUserAnswers(Long userId) {
String sql = "SELECT DISTINCT question_id , answer FROM " + USER_TABLE_NAME + " LEFT JOIN " + ANSWERS_TABLE_NAME + " ON user.id = answers.user_id" + " LEFT JOIN " + POLL_TABLE_NAME + " ON answers.question_id = poll.id " + " WHERE answer=first_option AND user_id=? OR answer=second_option AND user_id=? OR answer=third_option AND user_id=? OR answer=fourth_option AND user_id=?";
return jdbcTemplate.queryForList(sql, userId, userId, userId, userId);
}
@Override
public Map<String, Object> countQuestionsUserAnswered(Long userId) {
String sql = "SELECT COUNT(DISTINCT question_id) AS Questions_User_Answered_To FROM " + USER_TABLE_NAME + " LEFT JOIN " + ANSWERS_TABLE_NAME + " ON user.id = answers.user_id" + " LEFT JOIN " + POLL_TABLE_NAME + " ON answers.question_id = poll.id " + " WHERE answer=first_option AND user_id=? OR answer=second_option AND user_id=? OR answer=third_option AND user_id=? OR answer=fourth_option AND user_id=?";
return jdbcTemplate.queryForMap(sql, userId, userId, userId, userId);
}
@Override
public List<Map<String, Object>> AllQuestionsWithDetails() {
String sql = "SELECT title , SUM(answer=poll.first_option) AS Users_Choose_First_Answer_Option ,SUM(answer=poll.second_option) AS Users_Choose_Second_Answer_Option , SUM(answer=poll.third_option) AS Users_Choose_Third_Answer_Option ,SUM(answer=poll.fourth_option) AS Users_Choose_Fourth_Answer_Option FROM " + USER_TABLE_NAME + " LEFT JOIN " + ANSWERS_TABLE_NAME + " ON user.id = answers.user_id" + " LEFT JOIN " + POLL_TABLE_NAME + " ON answers.question_id = poll.id " + " GROUP BY title";
return jdbcTemplate.queryForList(sql);
}
}
|
@extends('admin.layouts.app')
@section('panel')
<div class="row">
<div class="col-lg-12">
<div class="d-flex align-items-center justify-content-between">
<h4>Create Loan Plants</h4>
<a href="{{ route('admin.plan.index') }}"
class="btn btn-sm btn--primary box--shadow1 text-white text--small addBtn"><i
class="fa fa-fw fa-plus"></i>@lang('Back TO loan Plan')</a>
</div>
<hr>
<div class="card b-radius--10 ">
<div class="card-body p-0">
<form action="{{ route('admin.loan.plan.post') }}" method="POST">
@csrf
<input type="hidden" name="id" required>
<div class="modal-body">
<div class="row">
<div class="col-12 col-md-6 py-2">
<label for="edit_name">@lang('Title')</label>
<input type="text" name="title" value="{{ old('title') }}" class="form-control">
<span class="text-danger">{{ $errors->first('title') }}</span>
</div>
<div class="col-12 col-md-6 py-2">
<label for="edit_name">@lang('Interest Type')</label>
<select name="interest_type" class="form-control">
<option value="">select</option>
<option value="1" {{ old('interest_type') == '1' ? 'selectd' : '' }}>fixed
</option>
<option value="2" {{ old('interest_type') == '2' ? 'selectd' : '' }}>percentage
</option>
</select>
<span class="text-danger">{{ $errors->first('interest_type') }}</span>
</div>
<div class="col-12 col-md-6 py-2">
<label for="edit_name">@lang('Loan Type')</label>
<select name="loan_type" class="form-control">
<option value="">select</option>
<option value="one time" {{ old('loan_type') == 'one time' ? 'selectd' : '' }}>one
time</option>
<option value="weakly" {{ old('loan_type') == 'weakly' ? 'selectd' : '' }}>weakly
</option>
<option value="monthly" {{ old('loan_type') == 'monthly' ? 'selectd' : '' }}>monthly
</option>
<option value="yearly" {{ old('loan_type') == 'yearly' ? 'selectd' : '' }}>yearly
</option>
</select>
<span class="text-danger">{{ $errors->first('loan_type') }}</span>
</div>
<div class="col-12 col-md-6 py-2">
<label for="edit_name">@lang('Interest')</label>
<input type="number" name="interest" value="{{ old('interest') }}"
class="form-control">
<span class="text-danger">{{ $errors->first('interest') }}</span>
</div>
<div class="col-12 col-md-6 py-2">
<label for="edit_name">@lang('Minimum')</label>
<input type="number" name="min" value="{{ old('min') }}" class="form-control">
<span class="text-danger">{{ $errors->first('min') }}</span>
</div>
<div class="col-12 col-md-6 py-2">
<label for="edit_name">@lang('Maximum')</label>
<input type="number" name="max" value="{{ old('max') }}" class="form-control">
<span class="text-danger">{{ $errors->first('max') }}</span>
</div>
<div class="col-12 col-md-6 py-2">
<label for="edit_name">@lang('Late fees Type')</label>
<select name="late_fees_type" class="form-control">
<option value="">select</option>
<option value="1" {{ old('late_fees_type') == '1' ? 'selectd' : '' }}>fixed
</option>
<option value="2" {{ old('late_fees_type') == '2' ? 'selectd' : '' }}>
percentage</option>
</select>
<span class="text-danger">{{ $errors->first('late_fees_type') }}</span>
</div>
<div class="col-12 col-md-6 py-2">
<label for="edit_name">@lang('Late fees')</label>
<input type="number" name="late_fees" value="{{ old('late_fees') }}"
class="form-control">
<span class="text-danger">{{ $errors->first('late_fees') }}</span>
</div>
<div class="col-12 col-md-6 py-2">
<label for="edit_name">@lang('Data')</label>
<input type="number" name="data" value="{{ old('data') }}" class="form-control">
<span class="text-danger">{{ $errors->first('data') }}</span>
</div>
<div class="col-12 py-2 text-center">
<button class="btn btn-primary" type="submit">Create</button>
</div>
</div>
</div>
</form>
</div>
</div>
</div>
</div>
@endsection
|
#!/usr/bin/python3
"""This modules defines a function for element-wise division of a matrix
and a helper function for raising a specific exception with its detail
"""
def matrix_divided(matrix, div):
"""Divides each element in a matrix by a number
Args:
matrix: list of lists of numbers
div: number to divide matrix elements by
Returns:
a new matrix of the quotients
"""
if not isinstance(matrix, list):
raise_matrix_error()
len_first = len(matrix[0])
for row in matrix:
if not isinstance(row, list) or not len(row):
raise_matrix_error()
if len(row) != len_first:
raise TypeError('Each row of the matrix must have the same size')
for i in row:
if not isinstance(i, int) and not isinstance(i, float):
raise_matrix_error()
if not isinstance(div, int) and not isinstance(div, float):
raise TypeError('div must be a number')
if div:
return [[round(i/div, 2) for i in row] for row in matrix]
else:
raise ZeroDivisionError('division by zero')
def raise_matrix_error():
"""Raises a TypeError."""
raise TypeError(
'matrix must be a matrix (list of lists) of integers/floats')
|
package com.direct2web.citysip.Adapter.SpaAndSalonAdapter;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.ViewGroup;
import androidx.annotation.NonNull;
import androidx.databinding.DataBindingUtil;
import androidx.recyclerview.widget.RecyclerView;
import com.direct2web.citysip.Model.SpaAndSalon.Appointment.OrderItem;
import com.direct2web.citysip.R;
import com.direct2web.citysip.databinding.RawDoctorServiceItemBinding;
import com.direct2web.citysip.databinding.RawSpaSalonServiceItemBinding;
import java.util.ArrayList;
import java.util.List;
public class ServiceItemSpaAndSalonAdapter extends RecyclerView.Adapter<ServiceItemSpaAndSalonAdapter.viewHolder> {
List<OrderItem> orderList;
Context context;
List<OrderItem> orderItemList = new ArrayList<>();
public ServiceItemSpaAndSalonAdapter(List<OrderItem> orderList, Context context) {
this.orderList = orderList;
this.context = context;
}
@NonNull
@Override
public ServiceItemSpaAndSalonAdapter.viewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
LayoutInflater layoutInflater = LayoutInflater.from(parent.getContext());
RawSpaSalonServiceItemBinding binding = DataBindingUtil.inflate(layoutInflater, R.layout.raw_spa_salon_service_item, parent, false);
// set the view's size, margins, paddings and layout parameters
return new viewHolder(binding);
}
@Override
public void onBindViewHolder(@NonNull ServiceItemSpaAndSalonAdapter.viewHolder holder, int position) {
OrderItem order = orderList.get(position);
holder.binding.txtName.setText(order.getServiceName());
holder.binding.txtQnty.setText(order.getQty());
holder.binding.txtAmount.setText(order.getAmount());
holder.binding.txtAppointmentDate.setText(order.getAppointmentDate());
holder.binding.txtAppointmentTime.setText(order.getAppointmentTime());
}
@Override
public int getItemCount() {
return (orderList != null) ? orderList.size() : 0;
}
public class viewHolder extends RecyclerView.ViewHolder {
RawSpaSalonServiceItemBinding binding;
public viewHolder(@NonNull RawSpaSalonServiceItemBinding itemView) {
super(itemView.getRoot());
this.binding = itemView;
}
}
}
|
import React from "react";
export const Stars = (score: number | string) => {
//console.log("type", typeof score)
if (typeof score === 'string') {
score = parseInt(score);
}
score = (score > 0) ? Math.round((5 / 100) * score) : 0;
//console.log(score)
const star = (key: number) => (<span className="material-icons" key={key} >star</span>);
const halfStar = (key: number) => (<span className="material-icons" key={key}>star_half</span>);
const outLineStar = (key: number) => (<span className="material-icons" key={key}>star_outline</span>);
const stars = (score: number) => {
let stars = [];
for (let i = 0; i < 5; i++) {
if (i < score) {
stars.push(star(i));
} else if (i === score - 1) {
if (((5 / 100) * score % 1 > 0.49)) {
stars.push(halfStar(i));
} else {
stars.push(outLineStar(i))
}
} else {
stars.push(outLineStar(i))
}
}
return stars;
}
return <>{stars(score)}</>;
}
|
import uuid
from django.db import models
from django.contrib.auth.models import AbstractUser
from django.contrib.gis.geos import Point
class UserRole(models.TextChoices):
ADMIN = 'admin'
WAITER = 'waiter'
CUSTOMER = 'customer'
class User(AbstractUser):
username = models.CharField(max_length=255, default=uuid.uuid4, unique=True)
phone_number = models.CharField(max_length=12, null=True, unique=True)
email = models.EmailField(max_length=255, null=True, unique=True)
first_name = models.CharField(max_length=255, null=True)
last_name = models.CharField(max_length=255, null=True)
profile_picture = models.ImageField(upload_to='user', help_text='User Images', null=True)
role = models.CharField(max_length=10, choices=UserRole.choices, default=UserRole.CUSTOMER)
USERNAME_FIELD = 'username'
REQUIRED_FIELDS = ['email', 'phone_number']
def __str__(self):
return self.phone_number
class Meta:
ordering = ('-date_joined',)
verbose_name = "User"
verbose_name_plural = "Users"
db_table = "user"
|
import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:flutter_cinemapedia/shared/widgets.dart';
import 'package:flutter_cinemapedia/features/movies/providers.dart';
import 'package:flutter_cinemapedia/features/movies/widgets.dart';
class MoviesView extends ConsumerStatefulWidget {
const MoviesView({super.key});
@override
MoviesViewState createState() => MoviesViewState();
}
class MoviesViewState extends ConsumerState<MoviesView> {
@override
void initState() {
super.initState();
// providers
ref.read(nowPlayingMoviesProvider.notifier).loadNextPage();
ref.read(upcomingMoviesProvider.notifier).loadNextPage();
ref.read(popularMoviesProvider.notifier).loadNextPage();
}
@override
Widget build(BuildContext context) {
final initialLoading = ref.watch(initialLoadingProvider);
if (initialLoading) return const FullScreenLoader();
final slideshowMovies = ref.watch(movieSlideshowProvider);
final nowPlayingMovies = ref.watch(nowPlayingMoviesProvider);
final upcomingMovies = ref.watch(upcomingMoviesProvider);
final popularMovies = ref.watch(popularMoviesProvider);
return CustomScrollView(
slivers: [
const SliverAppBar(
floating: true,
flexibleSpace: FlexibleSpaceBar(
background: CustomAppbar(),
),
),
SliverList(
delegate: SliverChildBuilderDelegate(
(context, index) => Column(
children: [
MovieSlideshow(movies: slideshowMovies),
MovieHorizontalListView(
title: 'En cines',
subtitle: 'Lunes 20',
movies: nowPlayingMovies,
onEndScroll:
ref.read(nowPlayingMoviesProvider.notifier).loadNextPage,
),
MovieHorizontalListView(
title: 'Próximamente',
subtitle: 'En este mes',
movies: upcomingMovies,
onEndScroll:
ref.read(upcomingMoviesProvider.notifier).loadNextPage,
),
MovieHorizontalListView(
title: 'Populares',
movies: popularMovies,
onEndScroll:
ref.read(popularMoviesProvider.notifier).loadNextPage,
),
const SizedBox(height: 20),
],
),
childCount: 1,
))
],
);
}
}
|
#include <assert.h>
#include <getopt.h>
#include <netdb.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/stat.h>
#include <unistd.h>
#include "server.h"
static const struct option long_options[] =
{
{ "address", 1, NULL, 'a' },
{ "help", 0, NULL, 'h' },
{ "module-dir", 1, NULL, 'm' },
{ "port", 1, NULL, 'p' },
{ "verbose", 0, NULL, 'v' },
};
static const char* const short_options = "a:hm:p:v";
static const char* const usage_template =
"Usage: %s [ options ]\n"
" -a, --address ADDR Bind to local address (by default, bind\n"
" to all local addresses).\n"
" -h, --help Print this information.\n"
" -m, --module-dir DIR Load modules from specified directory\n"
" (by default, use executable directory).\n"
" -p, --port PORT Bind to specified port.\n"
" -v, --verbose Print verbose messages.\n";
static void print_usage (int is_error)
{
fprintf (is_error ? stderr : stdout, usage_template, program_name);
exit (is_error ? 1 : 0);
}
int main (int argc, char* const argv[])
{
struct in_addr local_address;
uint16_t port;
int next_option;
program_name = argv[0];
local_address.s_addr = INADDR_ANY;
port = 0;
verbose = 0;
module_dir = get_self_executable_directory ();
assert (module_dir != NULL);
do
{
next_option =
getopt_long (argc, argv, short_options, long_options, NULL);
switch (next_option)
{
case 'a':
{
struct hostent* local_host_name;
local_host_name = gethostbyname (optarg);
if (local_host_name == NULL || local_host_name->h_length == 0)
error (optarg, "invalid host name");
else
local_address.s_addr =
*((int*) (local_host_name->h_addr_list[0]));
}
break;
case 'h':
print_usage (0);
case 'm':
{
struct stat dir_info;
if (access (optarg, F_OK) != 0)
error (optarg, "module directory does not exist");
if (access (optarg, R_OK | X_OK) != 0)
error (optarg, "module directory is not accessible");
if (stat (optarg, &dir_info) != 0 || !S_ISDIR (dir_info.st_mode))
error (optarg, "not a directory");
module_dir = strdup (optarg);
}
break;
case 'p':
{
long value;
char* end;
value = strtol (optarg, &end, 10);
if (*end != '\0')
print_usage (1);
port = (uint16_t) htons (value);
}
break;
case 'v':
verbose = 1;
break;
case '?':
print_usage (1);
case -1:
break;
default: abort ();
}
} while (next_option != -1);
if (optind != argc)
print_usage (1);
if (verbose)
printf ("modules will be loaded from %s\n", module_dir);
server_run (local_address, port);
return 0;
}
|
// colorise log output
fn log_info(message: &str) {
println!("\x1b[1;32m{}\x1b[0m", message);
}
fn log_error(message: &str) {
println!("\x1b[1;31m{}\x1b[0m", message)
}
fn log_warning(message: &str) {
println!("\x1b[1;33m{}\x1b[0m", message)
}
fn log_debug(message: &str) {
println!("\x1b[1;34m{}\x1b[0m", message)
}
fn log_trace(message: &str) {
println!("\x1b[1;35m{}\x1b[0m", message)
}
pub fn logger(level: &str, message: &str) {
match level {
"info" => log_info(message),
"error" => log_error(message),
"warning" => log_warning(message),
"debug" => log_debug(message),
"trace" => log_trace(message),
_ => log_info(message),
}
}
#[macro_export]
/// Macro for logging an info message.
///
/// This macro takes a format string and arguments, and logs a warning message using the `logger` function from the `log` module.
/// The format string and arguments are passed to the `format!` macro to create the final log message.
///
/// # Examples
///
/// ```
/// info!("Invalid input: {}", input);
/// ```
macro_rules! info {
($($arg:tt)*) => ({
$crate::log::logger("info", &format!($($arg)*));
})
}
#[macro_export]
/// Macro for logging an error message.
///
/// This macro takes a format string and arguments, and logs a warning message using the `logger` function from the `log` module.
/// The format string and arguments are passed to the `format!` macro to create the final log message.
///
/// # Examples
///
/// ```
/// error!("Invalid input: {}", input);
/// ```
macro_rules! error {
($($arg:tt)*) => ({
$crate::log::logger("error", &format!($($arg)*));
})
}
#[macro_export]
/// Macro for logging a warning message.
///
/// This macro takes a format string and arguments, and logs a warning message using the `logger` function from the `log` module.
/// The format string and arguments are passed to the `format!` macro to create the final log message.
///
/// # Examples
///
/// ```
/// warning!("Invalid input: {}", input);
/// ```
macro_rules! warning {
($($arg:tt)*) => ({
$crate::log::logger("warning", &format!($($arg)*));
})
}
#[macro_export]
/// Macro for logging a debug message.
///
/// This macro takes a format string and arguments, and logs a warning message using the `logger` function from the `log` module.
/// The format string and arguments are passed to the `format!` macro to create the final log message.
///
/// # Examples
///
/// ```
/// debug!("Invalid input: {}", input);
/// ```
macro_rules! debug {
($($arg:tt)*) => ({
$crate::log::logger("debug", &format!($($arg)*));
})
}
#[macro_export]
/// Macro for logging a warning message.
///
/// This macro takes a format string and arguments, and logs a warning message using the `logger` function from the `log` module.
/// The format string and arguments are passed to the `format!` macro to create the final log message.
///
/// # Examples
///
/// ```
/// trace!("Invalid input: {}", input);
/// ```
macro_rules! trace {
($($arg:tt)*) => ({
$crate::log::logger("trace", &format!($($arg)*));
})
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_logger() {
logger("info", "test");
logger("error", "test");
logger("warning", "test");
logger("debug", "test");
logger("trace", "test");
}
#[test]
fn test_logger_macro() {
info!("test");
error!("test");
warning!("test");
debug!("test");
trace!("test");
}
}
|
import sys
from . import config_logger
from .arguments import parse_args
from .utils import (
SEP_BOLD,
SEP_SLIM,
SEP_WIDTH,
Config,
Status,
get_choice_as_int,
stderr_write,
strftime,
)
def _print_header(args):
"""Print the program header with command details."""
stderr_write(
f"{SEP_BOLD}\n"
f'{"Rina: The All-in-One Japanese AV Toolbox":^{SEP_WIDTH}}\n'
f"{SEP_SLIM}\n"
)
config = {"command": None, "source": None}
include = ("recursive",)
config.update({k: v for k, v in vars(args).items() if v or k in include})
kl = max(map(len, config))
for k, v in config.items():
# format certain types
if isinstance(v, float):
v = strftime(v)
elif isinstance(v, range):
v = ", ".join(map(str, v))
stderr_write(f"{k.title():>{kl}}: {v}\n")
stderr_write(f"{SEP_BOLD}\n")
def process_stream(stream, args):
changed = []
failure = []
total = 0
for obj in stream:
total += 1
obj.print()
if obj.status == Status.UPDATED:
changed.append(obj)
elif obj.status == Status.FAILURE:
failure.append(obj)
if total:
stderr_write(f"{SEP_BOLD}\n")
stderr_write(
f"{args.command.title()} scan finished.\n"
f"Total: {total}. Changed: {len(changed)}. Failure: {len(failure)}.\n"
)
if not changed:
stderr_write("No change can be made.\n")
return
msg = (
f"{SEP_BOLD}\n"
"Please choose an option:\n"
f"1) apply changes ({len(changed)} items)\n"
f"2) reload changes ({len(changed)} items)\n"
f"3) reload failures ({len(failure)} items)\n"
"4) quit\n"
)
while True:
choice = get_choice_as_int(msg, 4)
if choice == 1:
break
if choice == 4:
sys.exit()
for obj in changed if choice == 2 else failure:
obj.print()
failure.clear()
stderr_write(f"{SEP_BOLD}\nApplying changes...\n")
for obj in progressbar(changed):
try:
obj.apply()
except OSError as e:
failure.append(e)
for obj in failure:
stderr_write(f"Failed to process file: {obj}\n")
def progressbar(sequence, width: int = SEP_WIDTH):
"""Make an iterator that returns values from the input sequence while
printing a progress bar."""
total = len(sequence)
fmt = f"\rProgress |{{:-<{width}}}| {{:.1%}} Complete".format
for i, obj in enumerate(sequence, 1):
stderr_write(fmt("█" * (i * width // total), i / total))
yield obj
if total:
stderr_write("\n")
def main():
args = parse_args()
config_logger(args.verbose)
Config.DRYRUN = args.dryrun
Config.YES = args.yes
_print_header(args)
if args.command == "video":
from rina import files, video
if args.type == "keyword":
video.from_string(args.source).print()
elif args.type == "dir":
process_stream(video.from_args(args), args)
files.update_dir_mtime(args.source)
else:
process_stream((video.from_path(args.source),), args)
elif args.command == "idol":
from rina import idol
if args.type == "keyword":
idol.Idol(args.source).print()
else:
process_stream(idol.from_args(args), args)
elif args.command == "dir":
from rina import files
files.update_dir_mtime(args.source)
elif args.command == "concat":
from rina import concat
concat.main(args)
elif args.command == "birth":
from rina import birth
birth.main(args)
else:
raise ValueError(args.command)
if __name__ == "__main__":
main()
|
import React, { useState } from "react";
import NoteDelete from "./NoteDelete";
import NoteEdit from "./NoteEdit";
import { connect } from "react-redux";
import { categorizeNote } from "../../actions";
import { Button, Card, CardContent, CardActions } from "@material-ui/core";
function Note(props) {
const [deleteShow, setDeleteShow] = useState(false);
const [editShow, setEditShow] = useState(false);
const toggleEdit = () => setEditShow(!editShow);
const closeEditView = () => setEditShow(false);
const renderEdit = (editShow, id) => {
if (editShow && id === props.id) {
return (
<NoteEdit
id={props.id}
content={props.content}
closeEditView={closeEditView}
/>
);
} else {
return null;
}
};
const toggleDelete = () => setDeleteShow(!deleteShow);
const renderDelete = (deleteShow, id) => {
if (deleteShow && id === props.id) {
return (
<NoteDelete
style={{ marginRight: "20px" }}
id={props.id}
toggleDelete={toggleDelete}
/>
);
} else {
return null;
}
};
const renderButtons = () => {
if (props.organize) return null;
switch (props.category) {
case "maybe" || "referense":
return (
<>
<Button
onClick={() => {
props.categorizeNote(props.id, "in-tray");
}}
className="click"
>
Move to In-Tray
</Button>
<Button onClick={() => toggleEdit()} className="click">
Edit
</Button>
<Button onClick={() => toggleDelete()} className="red-text click">
Delete
</Button>
</>
);
case "done":
return (
<p>
Completed on:{" "}
{props.completedDate
? new Date(props.completedDate).toLocaleString()
: "N/A"}
</p>
);
default:
return (
<>
<Button
onClick={() => {
props.categorizeNote(props.id, "done");
}}
>
Complete
</Button>
<Button onClick={() => toggleEdit()} className="click">
Edit
</Button>
<Button onClick={() => toggleDelete()}>Delete</Button>
</>
);
}
};
return (
<Card raised key={props.id} className="margin-top notes">
<CardContent>
<p>{!editShow ? props.content : null}</p>
{renderEdit(editShow, props.id)}
</CardContent>
<CardActions>{renderButtons()}</CardActions>
{renderDelete(deleteShow, props.id)}
</Card>
);
}
export default connect(null, { categorizeNote })(Note);
|
---
id: 3
title: '💥 3.2 功能介绍'
---
3.2 对比 3.1 有相当大的变化。既对底层逻辑进行了梳理,修复了许多问题,提高了稳定性,也对用户 api 进行了整合。
期待大佬们体验并提出意见建议。
沟通方式:
- QQ 群:897838127
- [点击提交 Issues](https://gitee.com/g1879/DrissionPage/issues)
## ✅️️ 特性改变
### 📌 `WebPage`不再自动切换模式
旧版本中,调用非当前模式独有的方法,会先自动切换模式。比如在 d 模式调用`post()`方法,会自动切换到 s 模式。
3.2 中,只有显式调用`change_mode()`时才会切换模式。因此,可以在 s 模式时控制浏览器,不会产生冲突。使用更灵活。
### 📌 `WebPage`的标签页对象也可以切换模式
`WebPage`的`get_tab()`方法现在返回`WebPageTab`对象,也能切换模式。创建时默认处于 d 模式。
### 📌 更改找不到元素时返回值
旧版本中,查找不到元素会返回`None`,3.2 版中会返回一个`NoneElement`对象。
该对象用`if`判断表现为`False`,调用其功能会抛出`ElementNotFoundError`异常。这样可以用`if`判断是否找到元素,也可以用`try`去捕获异常。
查找多个元素找不到时,依然返回空的`list`,这点和旧版本一致。
示例,当我们查找一个不存在的元素时:
```python
ele = page.ele('xxxxxxx')
```
❌ 当前版本用`None`判断的方式将不可用:
```python
if ele is None:
print('没有找到。')
```
⭕ 正确做法:
```python
# 用if判断
if not ele:
print('没有找到。')
if ele:
print('找到了。')
```
```python
# 用try捕获
try:
ele.click()
except ElementNotFoundError:
print('没有找到。')
```
### 📌 部分方法调整
- `run_js()`方法参数顺序作了调整
- `drag()`和`drag_to()`方法删除了`shake`参数
- 元素对象去除`wait_ele()`方法,改用`wait.xxxx()`方法等待自身属性改变
- `ChromiumPage`的`to_tab()`、`close_tabs()`、`close_other_tabs()`方法可接收标签页对象
- `ActionChains`导入路径改为`from DrissionPage.common import ActionChains`
- `Keys`导入路径改为`from DrissionPage.common import Keys`
### 📌 下载默认使用浏览器
避免不了解 DownloadKit 的用户以为点击后程序没有反应。
现在点击后默认用浏览器下载到程序当前路径,可用`download_set.save_path()`设置保存位置。
## ✅️️ api 整合
随着功能的增加,同类 api 也越来越多,比如`ChromiumPage`以`set_`开头的方法就有 9 个,元素点击的方式有 5 种。如何这些同类的 api 全堆在一起,会显得十分凌乱。
因此,3.2 版对大量 api 做了整合,避免提示界面越来越臃肿,也增强了开发灵活性。
旧版的 api 目前还将保留,但将在以后的版本中舍弃。
旧版:
```python
page.set_timeouts(20, 30, 40)
```
新版:
```python
page.set.timeouts(20, 30, 40)
```
### 📌 浏览器页面对象
| 旧版 | 新版 | 说明 |
|:-----------------------------:|:------------------------:|:------------------:|
| set_timeouts() | set.timeouts() | 超时设置 |
| set_session_storage() | set.session_storage() | session storage 设置 |
| set_local_storage() | set.local_storage() | local storage 设置 |
| set_user_agent() | set.user_agent() | user agent 设置 |
| set_cookies() | set.cookies() | cookies 设置 |
| set_headers() | set.headers() | headers 设置 |
| set_page_load_strategy.xxxx() | set.load_strategy.xxxx() | 页面加载策略设置 |
| set_window.xxxx() | set.window.xxxx() | 浏览器大小位置设置 |
| set_main_tab() | set.main_tab() | 主 tab 设置 |
| wait_loading() | wait.load_start() | 等待页面加载开始 |
| wait_ele().xxxx() | wait.ele_xxxx() | 等待元素变成某种状态 |
| scroll_to_see() | scroll.to_see() | 把元素滚动到视口 |
| hide_browser() | set.window.hide() | 隐藏浏览器 |
| show_browser() | set.window.show() | 显示浏览器 |
| to_front() | set.tab_to_front() | 设置某个标签页到激活状态 |
### 📌 元素对象
| 旧版 | 新版 | 说明 |
|:-----------------:|:---------------------------:|:---------------:|
| wait_ele().xxxx() | wait.xxxx() | 等待元素变成某种状态 |
| r_click() | click.right() | 右键点击元素 |
| m_click() | clikc.middle() | 中键点击元素 |
| r_click_at() | click.right_at() | 带偏移量中键点击元数据 |
| click_at() | click.left_at() | 带偏移量左键点击元素 |
| set_attr() | set.attr() | 设置 attribute 属性 |
| set_prop() | set.prop() | 设置 property 属性 |
| set_innerHTML() | set.innerHTML() | 设置 innerHTML 内容 |
| midpoint | locations.midpoint | 获取元素中点在页面位置 |
| client_location | locations.viewport_location | 获取元素左上角在视口位置 |
| client_midpoint | locations.viewport_midpoint | 获取元素中点在视口位置 |
| is_selected | states.is_selected | 获取元素是否被选中 |
| is_displayed | states.is_displayed | 获取元素是否显示 |
| is_enabled | states.is_enabled | 获取元素是否可操作 |
| is_alive | states.is_alive | 获取元素是否仍然在 DOM 内 |
| is_in_viewport | states.is_in_viewport | 获取元素是否在视口内 |
| pseudo_before | pseudo.before | 获取 before 伪元素内容 |
| pseudo_after | pseudo.after | 获取 after 伪元素内容 |
| obj_id | ids.obj_id | 获取元素 object id |
| node_id | ids.node_id | 获取元素 node id |
| backend_id | ids.backend_id | 获取元素 backend id |
| doc_id | ids.doc_id | 获取元素 doc id |
## ✅️️ 新增功能
### 📌 拦截上传控件填写路径
之前的版本中,要上传文件需要开发者先在 DOM 内找到文件上传控件,有些经过伪装后实时加载的`<input>`元素并不好找,有时也会由 js 控制。
新版本中,再也无需费心查找上传控件,只要设置好要上传的路径,然后点击触发文本选择框,程序会自动拦截选择框,并把路径输入到控件,非常便利。
示例:
```python
# 设置要上传的文件路径
page.set.upload_files('demo.txt')
# 点击触发文件选择框按钮
btn_ele.click()
# 等待路径填入
page.wait.upload_paths_inputted()
```
点击按钮后,文本选择框被拦截不会弹出,但可以看到文件路径已经传入其中。
由于此动作是异步输入,需显式等待输入完成才进行下一步操作。
### 📌 优先读取项目路径 ini 文件
旧版本中默认 ini 文件存放在 DrissionPage 安装目录下,修改要通过代码进行,给调试带来不便。新版会优先在用户项目文件夹下查找`'dp_configs.ini'`文件并使用,使开发时可方便地手动更改配置。项目打包也可以直接打包而不会造成找不到文件问题。
`easy_set`方法中增加`configs_to_here()`方法,调用该方法可直接把默认 ini 文件复制到当前路径。
### 📌 查找元素增加或语法
查找元素增加`@|`语法,用于或关系匹配多个属性:
```python
page('@|class=xxx@|name=abc')
```
或语法`@|`不能跟与语法`@@`共同生效。
### 📌 找不到元素时可抛出异常
找不到元素时,除了返回`NoneElement`对象,也可设置直接抛出异常。
```python
from DrissionPage.easy_set import raise_when_ele_not_found
raise_when_ele_not_found(True)
```
该设置是全局设置,设置后整个项目都会生效。
**示例:**
```python
from DrissionPage import SessionPage
from DrissionPage.easy_set import raise_when_ele_not_found
raise_when_ele_not_found(True)
page = SessionPage()
page.get('https://www.baidu.com')
ele = page('xxxxxx')
```
上面的代码会抛出`ElementNotFound`异常。
### 📌 新增一批异常
新增一批异常,调用位置:
```python
from DrissionPage.errors import ElementLossError
```
- `AlertExistsError`:调用页面功能若存在未处理的弹出框则抛出
- `ContextLossError`:页面被刷新后仍调用其中的元素时抛出
- `ElementLossError`:元素因页面或自身被刷新而失效时抛出
- `CallMethodError`:调用 cdp 时产生的异常
- `TabClosedError`:标签页关闭后仍调用其功能时抛出
- `ElementNotFoundError`:找不到元素抛出
- `JavaScriptError`:JavaScript 运行错误
- `NoRectError`:对没有大小和位置信息的元素获取这些信息时抛出
### 📌 新增的方法和属性
`ChromiumPage`:
| 名称 | 说明 |
|:---------------------------------:|:---------------------:|
| run_cdp_loaded() | 执行 cdp 命令,执行前等待页面加载完成 |
| run_js_loaded() | 执行 js 语句,执行前等待页面加载完成 |
| wait.load_complete() | 等待页面加载完毕 |
| wait.upload_paths_inputted() | 等待上传文件路径输入到文件选择框 |
| rect.browser_location | 获取浏览器左上角在屏幕上坐标 |
| rect.page_location | 获取页面左上角在屏幕上坐标 |
| rect.viewport_location | 获取视口在屏幕上坐标 |
| rect.browser_size | 获取浏览器大小 |
| rect.page_size | 获取页面大小 |
| rect.viewport_size | 获取视口大小,不含滚动条 |
| rect.viewport_size_with_scrollbar | 获取视口大小,含滚动条 |
| remove_ele() | 从页面上移除一个元素 |
| get_frame() | 获取一个`ChromiumFrame`对象 |
`SessionPage`新增一系列设置方法:
| 名称 | 说明 |
|:-------------------:|:-------------:|
| set.header() | 设置一个 header 值 |
| set.proxies() | 设置代理 |
| set.auth() | 设置登录信息 |
| set.hooks() | 设置回调方法 |
| set.params() | 设置连接参数 |
| set.cert() | 设置证书 |
| set.stream() | 设置是否使用流式响应内容 |
| set.trust_env() | 设置是否信任环境 |
| set.max_redirects() | 设置最大重定向次数 |
| set.max_redirects() | 添加适配器 |
`ChromiumElement`:
| 名称 | 说明 |
|:------------------------------:|:--------------:|
| locations.screen_location | 获取元素左上角在屏幕上的坐标 |
| locations.screen_midpoint | 获取元素中间点在屏幕上的坐标 |
| locations.screen_click_point | 获取元素点击点在屏幕上的坐标 |
| locations.click_point | 获取元素点击点在页面上的坐标 |
| locations.viewport_click_point | 获取元素点击点在视口上的坐标 |
| states.is_covered | 获取元素是否被覆盖 |
| click.at() | 带偏移量点击元素,可指定按键 |
| wait.covered() | 等待元素被覆盖 |
| wait.covered() | 等待元素不被覆盖 |
### 📌 命令行工具
新增支持命令行工具。
- `--set-browser-path`(`-p`):设置配置文件中的浏览器路径
- `--set-user-path`(`-u`):设置配置文件中的用户数据路径
- `--configs-to-here`(`-c`):复制默认配置文件到当前路径
- `--launch-browser`(`-l`):启动浏览器,传入端口号,0表示用配置文件中的值
```shell
dp --set-browser-path '/Application/Goolge Chrome.app/Contents/MacOS/Google Chrome'
```
## ✅️️ 优化和问题修复
- [x] 对程序底层和业务逻辑进行了重新梳理,优化程序逻辑,大幅增强稳定性
- [x] 新旧版本完全隔离,新版以后开发可放飞自我,无需担心影响以前用`MixPage`开发的程序
- [x] 现在会返回开发者能看懂的异常信息
- [x] 修复页面加载和退出触发弹窗引起的问题
- [x] 修复`<iframe>`加载时可能出现的 500 错误
- [x] 修复异域`<iframe>`点击问题
- [x] 没有位置和大小信息的元素在获取这些信息时,现在会抛出异常
- [x] 修复内存没有正确释放的问题
- [x] 修复点击被固定栏遮挡问题
- [x] 接管新出现的`<iframe>`会自动等待内容加载
- [x] 修复`<iframe>`在同域和异域间互相跳转时会卡住的问题
- [x] 修复`<iframe>`内元素截图出现偏移问题
|
/* This source file is a part of the GePhex Project.
Copyright (C) 2001-2004
Georg Seidel <georg@gephex.org>
Martin Bayer <martin@gephex.org>
Phillip Promesberger <coma@gephex.org>
This program is free software; you can redistribute it and/or
modify it under the terms of the GNU General Public License
as published by the Free Software Foundation; either version 2
of the License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.*/
#include "ossdriver.h"
//#include <iostream>
#include <stdexcept>
#include <unistd.h>
#include <sys/types.h>
#include <sys/time.h>
#include <sys/soundcard.h>
#include <sys/ioctl.h>
#include <fcntl.h>
#include <stdio.h>
#include <errno.h>
struct OSSDriver::Impl
{
Impl() : fd(-1), bytes_per_sample(-1) {}
int fd;
int bytes_per_sample;
};
static int open_device(const char* device_name, int* fd);
static void close_device(int *fd);
static int read_data(int fd, unsigned char* buf, int buf_len);
//---------------------------------------------------------------------------
OSSDriver::OSSDriver()
: m_impl(new Impl())
{
}
OSSDriver::~OSSDriver()
{
if (this->is_open())
this->close();
}
void OSSDriver::open(logT /*logger*/,
device_id_t device,
int sample_rate,
sample_format format,
int channels)
{
if (this->is_open())
throw std::logic_error("Device already open");
char device_string[64];
int fd;
snprintf(device_string, sizeof(device_string), "/dev/dsp%i", device);
if (!open_device(device_string, &fd))
{
std::string msg = "Cannot open device: '";
msg += device_string;
msg += "'";
throw std::runtime_error(msg.c_str());
}
int bytes_per_sample;
try
{
// init to samplerate etc. pp.
int f, f_o;
if (format == SF_16LE)
{
f = f_o = AFMT_S16_LE;
bytes_per_sample = 2;
}
else
throw std::invalid_argument("Unknown sample format");
if (ioctl(fd, SNDCTL_DSP_SETFMT, &f) == -1)
{
throw std::runtime_error("Error when setting audio format");
}
if (f != f_o)
{
throw std::runtime_error("Sample format not supported");
}
int ch = channels;
if (ioctl(fd, SNDCTL_DSP_CHANNELS, &ch) == -1)
{
throw std::runtime_error("Error when setting channels");
}
if (ch != channels)
{
throw std::runtime_error("Channels not supported");
}
int speed = sample_rate;
if (ioctl(fd, SNDCTL_DSP_SPEED, &speed)==-1)
{
throw std::runtime_error("Error when setting sample rate");
}
if ( speed != sample_rate)
{
throw std::runtime_error("sample rate not supported");
}
// set fragments
// note: periods are called fragments in the OSS world
// the parameter has the number of fragments in teh upper 16 bit
// and the logarithm base 2 of the fragment size in the lower
// 16 bit.
int frag;
const int PERIOD_SIZE = 128;
frag = (sample_rate / (10*PERIOD_SIZE)) << 16;
int bytes_per_period = PERIOD_SIZE * bytes_per_sample;
int power = 0;
// determine power = min {k | 2^k >= bytes_per_period}
while (1 << power < bytes_per_period)
++power;
frag |= power;
if (ioctl(fd, SNDCTL_DSP_SETFRAGMENT, &frag) == -1)
{
throw std::runtime_error("Error when setting buffer");
}
// check fragment size
audio_buf_info info;
if (ioctl(fd, SNDCTL_DSP_GETISPACE, &info) == -1)
{
throw std::runtime_error("Error when querying buffers");
}
/* std::cout << "fragment size = " << info.fragsize << "\n";
std::cout << "frags total = " << info.fragstotal << "\n";
std::cout << "fragments = " << info.fragments << "\n";*/
int frag_size;
if (ioctl(fd, SNDCTL_DSP_GETBLKSIZE, &frag_size) == -1)
{
throw std::runtime_error("Error when querying fragment size");
}
// std::cout << "fragment size = " << frag_size << "\n";
}
catch (...)
{
this->close();
throw;
}
m_impl->fd = fd;
m_impl->bytes_per_sample = bytes_per_sample;
}
void OSSDriver::close()
{
if (!this->is_open())
return;
close_device(&m_impl->fd);
m_impl->fd = -1;
m_impl->bytes_per_sample = -1;
}
int minimum(int a, int b)
{
return (a < b) ? a : b;
}
int OSSDriver::read(unsigned char* data, int num_samples)
{
if (!this->is_open())
throw std::logic_error("Device not open");
// check fragment size
audio_buf_info info;
if (ioctl(m_impl->fd, SNDCTL_DSP_GETISPACE, &info) == -1)
{
throw std::runtime_error("Error when querying buffers");
}
//std::cout << "fragment size = " << info.fragsize << "\n";
// std::cout << "frags total = " << info.fragstotal << "\n";
// std::cout << "fragments = " << info.fragments << "\n";
int bytes_to_read = minimum(info.fragments * info.fragsize,
num_samples*m_impl->bytes_per_sample);
int len = read_data(m_impl->fd, data,
bytes_to_read);
if (len < 0)
throw std::runtime_error("Error at read");
return len / m_impl->bytes_per_sample;
}
bool OSSDriver::is_open() const
{
return m_impl->fd != -1;
}
//---------------------------------------------------------------------------
// returns 1 on success
static int open_device(const char* device_name, int* fd)
{
// open the OSS device for reading
*fd = open(device_name, O_RDONLY, 0);
if (*fd < 0)
return 0;
return 1;
}
static void close_device(int *fd)
{
if (*fd != -1)
{
close(*fd);
*fd = -1;
}
}
static int read_data(int fd, unsigned char* buf, int buf_len)
{
fd_set readfds;
int len;
if (fd < 0)
return -1;
{
struct timeval tv;
tv.tv_sec = 0;
tv.tv_usec = 0;
FD_ZERO(&readfds);
FD_SET(fd,&readfds);
select(fd+1,&readfds,0,0,&tv);
//TODO: handle EINTR
}
if (FD_ISSET(fd, &readfds))
{
errno = 0;
// do
{
len = read(fd, buf, buf_len);
if (len == -1 && errno != EINTR)
{
return -1;
}
else
{
return len;
}
}// while (errno != EINTR);
}
else
{
return 0;
}
}
|
import { Injectable } from '@angular/core';
import {Observable} from "rxjs";
import {Course} from "../models/course";
@Injectable({
providedIn: 'root'
})
export class CourseService {
constructor() { }
private description: string = `"Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor
incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris
nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum
dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt
mollit anim id est laborum."`;
courses: Course[] = [
{ id: 1, title: 'Complete Modern HTML Course', price: 100, desc: this.description, image: './../assets/courses/html5.png', rating: 5, duration: 10, author: 'Mohammed el lorry'},
{ id: 2, title: 'Complete Modern CSS Course', price: 200, desc: this.description, image: './../assets/courses/Css.png', rating: 5, duration: 10, author: 'Mohammed el lorry'},
{ id: 3, title: 'Complete Modern JavaScript Course', price: 399, desc: this.description, image: './../assets/courses/course1.jpg', rating: 5, duration: 18.2, author: 'Steve smith'},
{ id: 4, title: 'Complete Modern TYPESCRIPT Course', price: 200, desc: this.description, image: './../assets/courses/typeScript.png', rating: 5, duration: 10, author: 'Mohammed el lorry'},
{ id: 5, title: 'Complete Modern PHP Course', price: 499, desc: this.description, image: './../assets/courses/php.png', rating: 3.5, duration: 10, author: 'Mohammed el lorry'},
{ id: 6, title: 'A complete Angular Course', price: 599, desc: this.description, image: './../assets/courses/course2.jpg', rating: 4.9, duration: 20.8, author: 'Sarah King'},
{ id: 7, title: 'A Complete Node JS Bootcamp', price: 449, desc: this.description, image: './../assets/courses/course3.jpg', rating: 3.7, duration: 16.6, author: 'Mark Vought'},
{ id: 8, title: 'A Complete React Developer Course', price: 599, desc: this.description, image: './../assets/courses/course4.jpg', rating: 4.8, duration: 28.2, author: 'Sarah King'},
{ id: 9, title: 'ASP.NET Core with Web API', price: 649, desc: this.description, image: './../assets/courses/course5.jpg', rating: 3.5, duration: 34.4, author: 'Steve smith'},
{ id: 10, title: 'Froentend Development with Vue.js', price: 329, desc: this.description, image: './../assets/courses/course6.jpg', rating: 4.5, duration: 17.7, author: 'Steve smith'},
{ id: 11, title: 'A Complete Python Bootcamp', price: 469, desc: this.description, image: './../assets/courses/course7.jpg', rating: 3.4, duration: 32.6, author: 'Mark Vought'},
{ id: 12, title: 'Machine Learning with Python', price: 1299, desc: this.description, image: './../assets/courses/course8.jpg', rating: 4.8, duration: 26.7, author: 'Sarah King'},
]
getAllcourses(){
return new Observable<Course[]>((sub) => {
setTimeout(() => {
sub.next(this.courses);
}, 5000)
})
}
}
|
import { DatePipe } from '@angular/common';
import { Component, EventEmitter, Input, Output } from '@angular/core';
import { AbstractControl, FormBuilder, FormGroup, Validators } from '@angular/forms';
import { faCircleNotch, faCloudArrowUp, faXmark } from '@fortawesome/free-solid-svg-icons';
import { NgbModal } from '@ng-bootstrap/ng-bootstrap';
import { ToastrService } from 'ngx-toastr';
import { Subject } from 'rxjs';
import { ModalMessageComponent } from 'src/app/shared/modals/modal-message/modal-message.component';
import { DepositService } from 'src/app/shared/services/deposit.service';
import { RevenueService } from 'src/app/shared/services/revenue.service';
@Component({
selector: 'app-replace-cheque',
templateUrl: './replace-cheque.component.html',
styleUrls: ['./replace-cheque.component.scss']
})
export class ReplaceChequeComponent {
constructor(
private fb: FormBuilder,
private toastrService: ToastrService,
private depositservice: DepositService,
private modalService: NgbModal,
) { }
@Input() actionType: any;
@Input() details: any;
isLoading: boolean = false;
faXmark = faXmark;
faCloudArrowUp = faCloudArrowUp;
faCircleNotch = faCircleNotch;
loading = false;
form!: FormGroup;
bankList: any = [];
message: string = '';
messageError: string = '';
isStatus = false;
submitted = false;
unsubscribe = new Subject<void>();
filesToUpload: File[] = [];
@Output() sendtoLoadData = new EventEmitter();
ngOnInit(): void {
this.form = this.fb.group({
ChequeNo: ['', [Validators.required]],
ChequeDate: ['', [Validators.required]],
BankId: [null, [Validators.required]],
ChequeCustomer: ['', [Validators.required]],
Customer: false,
Note: ['', [Validators.required, Validators.maxLength(200)]],
});
this.depositservice.getBankLookups(11).subscribe(response => {
this.makeBankList(response.data || [])
});
}
sameCustomer() {
if (this.form.get('Customer')?.value) {
this.form.get('ChequeCustomer')?.clearValidators(); // Remove the required validator
this.form.get('ChequeCustomer')?.setValue('');
} else {
this.form.get('ChequeCustomer')?.setValidators(Validators.required); // Add the required validator
this.form.get('ChequeCustomer')?.setValue(this.details?.customer?.customerName);
}
this.form.get('ChequeCustomer')?.updateValueAndValidity(); // Update the control's validity status
}
makeBankList(item: any) {
let array = [];
if (item.length > 0) {
for (let index = 0; index < item.length; index++) {
const element = item[index];
let obj = {
id: element.id,
bankName: element?.name?.[0].lookupName
}
array.push(obj);
}
}
this.bankList = array;
}
onFileSelected(event: any): void {
this.filesToUpload = event.target.files;
}
ngOnDestroy() {
this.unsubscribe.next();
this.unsubscribe.complete();
}
bankSelected(item: any) {
this.form.get('BankId')?.setValue(item);
}
remove(item: string) {
if (item == 'ChequeNo')
this.form.get('ChequeNo')?.setValue(null);
else if (item == 'ChequeCustomer') {
this.form.get('ChequeCustomer')?.setValue('');
this.form.get('Customer')?.setValue(false)
}
}
removeCollectionDateFilter() {
this.form.get('ChequeDate')?.patchValue('');
}
onDateValueChange(event: any) {
const date = new Date(event);
if (isNaN(date.getTime())) {
// Invalid date, do not patch the value
return;
}
const pipe = new DatePipe('en-US');
this.form.get('ChequeDate')?.patchValue(pipe.transform(event) || '');
}
onSubmit() {
this.submitted = true;
this.form.markAllAsTouched();
if (this.form.valid) {
this.isLoading = true;
if (this.filesToUpload && this.filesToUpload.length > 0) {
const formData: FormData = new FormData();
for (let i = 0; i < this.filesToUpload.length; i++) {
formData.append('Image', this.filesToUpload[i]);
}
const fromDate = new Date(this.form.value.ChequeDate);
const formattedFromDate = fromDate.toISOString();
formData.append('DepositedChequeId', this.details.id.toString());
formData.append('ActionId', this.actionType.id.toString());
formData.append('ChequeAmount', this.details?.chequeCollectionJod.toString());
formData.append('ChequeNo', this.form.value.ChequeNo.toString());
formData.append('ChequeDate', formattedFromDate);
formData.append('BankId', this.form.value.BankId.toString());
formData.append('ChequeCustomer', this.form.value.ChequeCustomer);
formData.append('Notes', this.form.value.Note);
this.depositservice.actionOnCheques(formData)
.subscribe({
next: response => {
if (response.isSuccess) {
const modalRef = this.modalService.open(ModalMessageComponent);
modalRef.componentInstance.type = 'success';
modalRef.componentInstance.message = 'Your ' + this.actionType?.name?.[0].lookupName + " Action Successfully Performed";
modalRef.componentInstance.loadPageData.subscribe((result: any) => {
this.sendtoLoadData.emit('true');
});
// this.sendtoLoadData.emit('true');
} else {
const modalRef = this.modalService.open(ModalMessageComponent);
modalRef.componentInstance.type = 'error';
modalRef.componentInstance.messageError = response.errors;
}
},
error: (err) => {
const modalRef = this.modalService.open(ModalMessageComponent);
modalRef.componentInstance.type = 'error';
modalRef.componentInstance.messageError = err?.error?.errors;
},
})
.add(() => (this.isLoading = false));
} else {
this.toastrService.error('please Upload Image');
}
}
}
get formControls() {
return this.form.controls;
}
close() {
this.sendtoLoadData.emit();
}
get formValid(): { [key: string]: AbstractControl } {
return this.form.controls;
}
}
|
import React, {useState} from 'react';
import styles from '@/styles/contacts.module.css'
export default function ContactForm() {
// Input states
const [name, setName] = useState('');
const [email, setEmail] = useState('');
const [purpose, setPurpose] = useState('');
const [message, setMessage] = useState('');
const [btn, setBtn] = useState(false);
const [send, setSend] = useState(false);
const [fail, setFail] = useState(false);
const resetForm = () => {
setName('')
setEmail('')
setMessage('')
}
// Form submit handler
const submitForm = async (e) => {
e.preventDefault();
setBtn(true)
const res = await fetch('http://localhost:3000/api/submit-form', {
method: 'POST',
body: JSON.stringify({ name, email, message }),
});
// Success if status code is 201
if (res.status === 201) {
(console.log("success"), {
type: 'success'
});
setSend(true)
setBtn(false)
resetForm()
const timerId = setTimeout(() => {
setSend(false)
}, 3000);
return () => clearTimeout(timerId);
} else {
(console.log("fail"), {
type: 'error'
});
setFail(true)
setBtn(false)
resetForm()
const timerId = setTimeout(() => {
setFail(false)
}, 3000);
return () => clearTimeout(timerId);
}
};
return(
<div className={send ? styles.send : null}>
<form className={styles.mainForm} onSubmit={submitForm}>
<div className={styles.mainFormRow}>
<input
type="text"
id="name"
name="name"
placeholder="Ваше имя"
required
value={name}
onChange={(e) => setName(e.target.value)}
/>
<input
type="email"
name="email"
placeholder="Ваш Email"
required
value={email}
onChange={(e) => setEmail(e.target.value)}
/>
</div>
{/* <div>
<select name="purpose" id="purpose" value={purpose}
onChange={(e) => setPurpose(e.target.value)}>
<option value="Ничего не выбрано">
Select one
</option>
<option value="Web Development">Web Development</option>
<option value="App Development">App Development</option>
<option value="Query / Question">Query / Question</option>
<option value="Feedback / Message">Feedback / Message</option>
</select>
</div> */}
<div className={styles.mainFormRow}>
<textarea
name="message"
id="message"
rows="5"
placeholder="Что вас интересует?"
required
value={message}
onChange={(e) => setMessage(e.target.value)}
></textarea>
</div>
<div className={styles.mainFormRow}>
<button className="mainBtn" type="submit" disabled={!email || !name || !message}>
{btn ? 'Отправляется...' : 'Отправить'}
</button>
{
send ?
<div className={styles.noticeSuccess}>Спасибо за сообщение! 👍 Я свяжусь с вами в ближайшее время</div> :
fail ?
<div className={styles.noticeFail}>Неудача! Свяжитесь со мной другим способом или отправьте сообщение позже</div> :
null
}
</div>
</form>
</div>
);
}
/*
export default function ContactForm() {
const[click, setClick] = useState(false)
async function handleSubmit(event) {
event.preventDefault();
const formData = new FormData(event.target);
formData.append("access_key", "3eaa5353-83d7-492c-8771-8f636e5bf2db");
const object = Object.fromEntries(formData);
const json = JSON.stringify(object);
setClick()
const response = await fetch("https://api.web3forms.com/submit", {
method: "POST",
headers: {
"Content-Type": "application/json",
Accept: "application/json"
},
body: json
});
const result = await response.json();
if (result.success) {
console.log(result);
//setClick()
} else {
console.log(result);
}
}
return (
<div className={click ? styles.val : null }>
<form className={styles.mainForm} onSubmit={handleSubmit}>
<div className={styles.mainFormRow}>
<input type="text" name="name" placeholder="Ваше имя" required/>
<input type="email" name="email" placeholder="Ваш Email" required/>
</div>
<textarea name="message" placeholder="Напишите, что вы хотите сделать..."></textarea>
<input type="checkbox" name="botcheck" className="hidden" style={{display: 'none'}} />
<button type="submit" onClick={() => setClick(true)} className="mainBtn">
{click ? "Отправляется..." : "Отправить" }
</button>
</form>
</div>
);
}
*/
// export default function ContactForm() {
// const [state, handleSubmit] = useForm("xyyabpzj");
// if (state.succeeded) {
// return <p>Спасибо! Я с вами обязательно свяжусь</p>;
// }
// return (
// <form className={styles.mainForm} onSubmit={handleSubmit}>
// <div className={styles.mainFormRow}>
// <input id="who" type="text" name="Кто ты?" placeholder="Ваше имя"/>
// <ValidationError prefix="Who" field="who" errors={state.errors} />
// <input id="email" type="email" name="Email" placeholder="Ваш Email"/>
// <ValidationError prefix="Email" field="email" errors={state.errors} />
// </div>
// <textarea id="message" name="Сообщение" placeholder="Напишите, что вы хотите сделать..." />
// <ValidationError prefix="Message" field="message" errors={state.errors} />
// <button type="submit" className="mainBtn" disabled={state.submitting}>
// {state.submitting ? 'Отправляем...' : 'Отправить'}
// </button>
// <ValidationError errors={state.errors} />
// </form>
// );
// }
|
---
title: AEM as a Cloud Service の Asset Compute マイクロサービスの拡張性
description: このチュートリアルでは、オリジナルのアセットを円に切り抜いてアセットレンディションを作成し設定可能なコントラストと明るさを適用する、シンプルな Asset Compute ワーカーの作成について順を追って説明します。ワーカー自体は基本的ですが、このチュートリアルではこのワーカーを使用して、AEM as a Cloud Service で使用するカスタム Asset Compute ワーカーの作成、開発およびデプロイを行います。
feature: Asset Compute Microservices
version: Cloud Service
doc-type: Tutorial
jira: KT-5802
thumbnail: KT-5802.jpg
topic: Integrations, Development
role: Developer
level: Intermediate, Experienced
last-substantial-update: 2022-08-15T00:00:00Z
exl-id: 575b12f9-b57f-41f7-bd39-56d242de4747
duration: 340
source-git-commit: af928e60410022f12207082467d3bd9b818af59d
workflow-type: tm+mt
source-wordcount: '986'
ht-degree: 100%
---
# Asset Compute マイクロサービスの拡張性
AEM as Cloud Service の Asset Compute マイクロサービスは、AEM に保存されたアセットのバイナリデータの読み取りと操作に使用される(最も一般的には、カスタムアセットレンディションの作成に使用される)カスタムワーカーの開発とデプロイをサポートしています。
AEM 6.x ではカスタム AEM ワークフロープロセスを使用してアセットレンディションの読み取り、変換および書き戻しを行っていましたが、AEM as a Cloud Service では、Asset Compute ワーカーがこのニーズを満たします。
## 作業の内容
>[!VIDEO](https://video.tv.adobe.com/v/40965?quality=12&learn=on)
このチュートリアルでは、オリジナルのアセットを円に切り抜いてアセットレンディションを作成し設定可能なコントラストと明るさを適用する、シンプルな Asset Compute ワーカーの作成について順を追って説明します。ワーカー自体は基本的ですが、このチュートリアルではこのワーカーを使用して、AEM as a Cloud Service で使用するカスタム Asset Compute ワーカーの作成、開発およびデプロイを行います。
### 目的 {#objective}
1. Asset Compute ワーカーの作成とデプロイに必要なアカウントとサービスをプロビジョニングしてセットアップします。
1. Asset Compute プロジェクトを作成し設定します。
1. カスタムレンディションを生成する Asset Compute ワーカーを開発します。
1. テストを作成し、カスタム Asset Compute ワーカーのデバッグ方法を学びます。
1. Asset Compute ワーカーをデプロイし、処理プロファイルを通じて AEM as a Cloud Service オーサーサービスと統合します。
## セットアップ
Asset Compute ワーカーの拡張に適切に備える方法を学び、プロビジョニングと設定が必要なサービスとアカウントや、開発用にローカルにインストールするソフトウェアについて理解します。
### アカウントとサービスのプロビジョニング{#accounts-and-services}
このチュートリアルを完了するには、次のアカウントとサービスのプロビジョニングとそれらへのアクセス、AEM as a Cloud Service 開発環境またはサンドボックスプログラム、Application Builder と Microsoft Azure Blob Storage へのアクセスが必要です。
+ [アカウントとサービスのプロビジョニング](./set-up/accounts-and-services.md)
### ローカル開発環境
Asset Compute プロジェクトのローカル開発には、Microsoft Visual Studio Code、Docker Desktop、Node.js、npm サポートモジュールなど、従来の AEM 開発とは異なる特定の開発者ツールセットが必要です。
+ [ローカル開発環境のセットアップ](./set-up/development-environment.md)
### App Builder
Asset Compute プロジェクトは特別に定義された App Builder プロジェクトなので、Adobe Developer Console で App Builder にアクセスして設定およびデプロイする必要があります。
+ [App Builder を設定する](./set-up/app-builder.md)
## 開発
Asset Compute プロジェクトを作成して設定したあと、カスタムのアセットレンディションを生成するカスタムワーカーを開発する方法について説明します。
### Asset Compute プロジェクトの新規作成
Asset Compute プロジェクトは、1 つ以上の Asset Compute ワーカーを含んでおり、インタラクティブな Adobe I/O CLI を使用して生成されます。Asset Compute プロジェクトは、特別に構造化された App Builder プロジェクトであり、ひいては Node.js プロジェクトになります。
+ [Asset Compute プロジェクトの新規作成](./develop/project.md)
### 環境変数の設定
環境変数は、ローカル開発用の `.env` ファイルに保持され、ローカル開発に必要な Adobe I/O 資格情報やクラウドストレージ資格情報を提供するために使用されます。
+ [ 環境変数の設定](./develop/environment-variables.md)
### manifest.yml の設定
Asset Compute プロジェクトには、プロジェクト内に含まれるすべての Asset Compute ワーカーを定義するマニフェストと、Adobe I/O Runtime にデプロイして実行するときに使用できるリソースが含まれています。
+ [manifest.yml の設定](./develop/manifest.md)
### ワーカーの開発
Asset Compute ワーカーには、結果のアセットレンディションの生成または生成の調整を行うカスタムコードが含まれているので、ワーカーの開発は、Asset Compute マイクロサービスの拡張の中核となります。
+ [Asset Compute ワーカーの開発](./develop/worker.md)
### Asset Compute 開発ツールの使用
Asset Compute 開発ツールは、ワーカーが生成したレンディションをデプロイ、実行およびプレビューするためのローカル web ハーネスを提供し、迅速かつ反復的な Asset Compute ワーカー開発をサポートします。
+ [Asset Compute 開発ツールの使用](./develop/development-tool.md)
## テストとデバッグ
カスタム Asset Compute ワーカーをテストして、自信を持って運用できるようにする方法と、Asset Compute ワーカーをデバッグして、カスタムコードがどう実行されるかを把握し問題をトラブルシューティングする方法を説明します。
### ワーカーのテスト
Asset Compute は、ワーカーのテストスイートを作成して、適切な動作を保証するテストを簡単に定義できるようにするためのテストフレームワークを提供しています。
+ [ワーカーのテスト](./test-debug/test.md)
### ワーカーのデバッグ
Asset Compute ワーカーは、従来の `console.log(..)` 出力から __VS Code__ や __wskdebug__ との統合まで、様々なレベルのデバッグを提供しており、開発者がワーカーコードをリアルタイムで実行しながら 1 ステップずつ実行できます。
+ [ワーカーのデバッグ](./test-debug/debug.md)
## デプロイ
カスタム Asset Compute ワーカーをまず Adobe I/O Runtime にデプロイし、次に AEM Assets の処理プロファイルを通じて AEM as a Cloud Service オーサーから呼び出すことで、カスタム Asset Compute ワーカーを AEM as a Cloud Service と統合する方法について説明します。
### Adobe I/O Runtime へのデプロイ
Asset Compute ワーカーを AEM as a Cloud Service で使用するには、Adobe I/O Runtime にデプロイする必要があります。
+ [処理プロファイルの使用](./deploy/runtime.md)
### AEM 処理プロファイルを通じたワーカーの統合
Asset Compute ワーカーは、Adobe I/O Runtime にいったんデプロイすると、[アセット処理プロファイル](../../assets/configuring/processing-profiles.md)を通じて AEM as a Cloud Service に登録できるようになります。処理プロファイルをアセットフォルダーに適用すると、そのフォルダー内のアセットにも処理プロファイルが適用されます。
+ [AEM 処理プロファイルとの統合](./deploy/processing-profiles.md)
## 詳細
これの簡略化されたチュートリアルでは、前の章で獲得した基本的な知識に基づいて、より高度なユースケースに取り組んでいます。
+ メタデータを AEM に書き戻すことができる [Asset Compute メタデータワーカーの開発](./advanced/metadata.md)
## GitHub のコードベース
このチュートリアルのコードベースは、GitHub で次の場所から入手できます。
+ [adobe/aem-guides-wknd-asset-compute](https://github.com/adobe/aem-guides-wknd-asset-compute)(マスターブランチ)
ソースコードには、必要な `.env` ファイルまたは `config.json` ファイルが含まれていません。これらは、[アカウントとサービス](#accounts-and-services)の情報を使用して追加および設定する必要があります。
## その他のリソース
さらなる情報のほか、Asset Compute ワーカーの開発に役立つ API や SDK を提供する様々な Asset Compute リソースを以下に示します。
### ドキュメント化
+ [Asset Compute サービスのドキュメント](https://experienceleague.adobe.com/docs/asset-compute/using/extend/understand-extensibility.html?lang=ja)
+ [Asset Compute 開発ツールの README](https://github.com/adobe/asset-compute-devtool)
+ [Asset Compute サンプルワーカー](https://github.com/adobe/asset-compute-example-workers)
### API と SDK
+ [Asset Compute SDK](https://github.com/adobe/asset-compute-sdk)
+ [Asset Compute Commons](https://github.com/adobe/asset-compute-commons)
+ [Asset Compute XMP](https://github.com/adobe/asset-compute-xmp#readme)
+ [Adobe Cloud Blobstore Wrapper ライブラリ](https://github.com/adobe/node-cloud-blobstore-wrapper)
+ [Adobe Node Fetch Retry ライブラリ](https://github.com/adobe/node-fetch-retry)
+ [Asset Compute サンプルワーカー](https://github.com/adobe/asset-compute-example-workers)
|
import React from 'react';
import { ResponsiveBar } from '@nivo/bar';
export function DiscreteGraph({graph_data, id, groupid}) {
let graphKeys = ['count']
if (groupid) {
let allKeys = graph_data[0].keys()
let idIndex = allKeys.indexOf('id')
allKeys.splice(idIndex, 1)
graphKeys = allKeys
}
return (
<ResponsiveBar
data={graph_data}
keys={graphKeys}
indexBy="id"
margin={{ top: 50, right: 130, bottom: 100, left: 60 }}
padding={ graph_data.length < 5? 0.6 : 0 }
valueScale={{ type: 'linear' }}
indexScale={{ type: 'band', round: true }}
colors={{ scheme: 'nivo' }}
borderColor={{
from: 'color',
modifiers: [
[
'darker',
1.6
]
]
}}
axisTop={null}
axisRight={null}
axisBottom={{
tickSize: 5,
tickPadding: 5,
tickRotation: 0,
legend: id,
legendPosition: 'middle',
legendOffset: 32,
truncateTickAt: 0,
format: (value) => String(value).length > 13 ? "" : value
}}
axisLeft={{
tickSize: 5,
tickPadding: 5,
tickRotation: 0,
legend: 'Count',
legendPosition: 'middle',
legendOffset: -40,
truncateTickAt: 0
}}
labelSkipWidth={12}
labelSkipHeight={12}
labelTextColor={{
from: 'color',
modifiers: [
[
'darker',
1.6
]
]
}}
legends={[
{
dataFrom: 'keys',
anchor: 'bottom-right',
direction: 'column',
justify: false,
translateX: 120,
translateY: 0,
itemsSpacing: 2,
itemWidth: 100,
itemHeight: 20,
itemDirection: 'left-to-right',
itemOpacity: 0.85,
symbolSize: 20,
effects: [
{
on: 'hover',
style: {
itemOpacity: 1
}
}
]
}
]}
role="application"
ariaLabel="Nivo bar chart demo"
barAriaLabel={e=>e.id+": "+e.formattedValue+" in country: "+e.indexValue}
/>
)
}
|
package tests;
import io.qameta.allure.Epic;
import io.qameta.allure.Step;
import io.qameta.allure.junit4.DisplayName;
import lib.CoreTestCase;
import lib.Platform;
import lib.ui.ArticlePageObject;
import lib.ui.SearchPageObject;
import lib.ui.factories.ArticlePageObjectFactory;
import lib.ui.factories.SearchPageObjectFactory;
import org.junit.Assert;
import org.junit.Test;
@Epic("Application condition tests")
public class ChangeAppConditionTests extends CoreTestCase
{
@Test
@DisplayName("Change screen orientation")
@Step("Starting test 'testChangeScreenOrientation'")
public void testChangeScreenOrientation()
{
if (Platform.getInstance().isMW()){
return;
}
SearchPageObject SearchPageObject = SearchPageObjectFactory.get(driver);
SearchPageObject.initSearchInput();
SearchPageObject.typeSearchLine("Java");
SearchPageObject.clickByArticleWithSubstring("Object-oriented programming language");
ArticlePageObject ArticlePageObject = ArticlePageObjectFactory.get(driver);
String title_before_rotation = ArticlePageObject.getArticleTitle();
this.rotateScreenLandscape();
String title_after_rotation = ArticlePageObject.getArticleTitle();
Assert.assertEquals(
"Article title changed",
title_before_rotation,
title_after_rotation
);
this.rotateScreenPortrait();
String title_after_second_rotation = ArticlePageObject.getArticleTitle();
Assert.assertEquals(
"Article title changed",
title_before_rotation,
title_after_second_rotation
);
}
@Test
@DisplayName("Check article in background")
@Step("Starting test 'testCheckArticleInBackground'")
public void testCheckArticleInBackground() {
if (Platform.getInstance().isMW()){
return;
}
SearchPageObject SearchPageObject = SearchPageObjectFactory.get(driver);
SearchPageObject.initSearchInput();
SearchPageObject.typeSearchLine("Java");
SearchPageObject.waitForSearchResult("Object-oriented programming language");
this.backgroundApp(2);
SearchPageObject.waitForSearchResult("Object-oriented programming language");
}
}
|
#include <stdio.h>
#include <stdlib.h>
struct Queue {
int front, rear, size;
unsigned capacity;
int* array;
};
struct Queue* createQueue(unsigned capacity) {
struct Queue* queue = (struct Queue*)malloc(sizeof(struct Queue));
queue->capacity = capacity;
queue->front = queue->size = 0;
queue->rear = capacity - 1;
queue->array = (int*)malloc(queue->capacity * sizeof(int));
return queue;
}
int isFull(struct Queue* queue) {
return (queue->size == queue->capacity);
}
int isEmpty(struct Queue* queue) {
return (queue->size == 0);
}
void enqueue(struct Queue* queue, int item) {
if (isFull(queue))
return;
queue->rear = (queue->rear + 1) % queue->capacity;
queue->array[queue->rear] = item;
queue->size = queue->size + 1;
}
int dequeue(struct Queue* queue) {
if (isEmpty(queue))
return -1;
int item = queue->array[queue->front];
queue->front = (queue->front + 1) % queue->capacity;
queue->size = queue->size - 1;
return item;
}
int size(struct Queue* queue) {
return queue->size;
}
int main() {
struct Queue* queue = createQueue(5);
enqueue(queue, 1);
enqueue(queue, 2);
enqueue(queue, 3);
printf("Size of the queue: %d\n", size(queue));
dequeue(queue);
printf("Size after dequeue: %d\n", size(queue));
return 0;
}
|
package com.example.apitrainapp.ui.adapter
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import androidx.recyclerview.widget.RecyclerView.Adapter
import androidx.recyclerview.widget.RecyclerView.ViewHolder
import coil.load
import com.example.apitrainapp.R
import com.example.apitrainapp.data.model.DogSample
class DogAdapter(private val dogs: MutableList<DogSample>) : Adapter<DogViewHolder>() {
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): DogViewHolder {
val inflater = LayoutInflater.from(parent.context)
return DogViewHolder(inflater.inflate(R.layout.holder_dog, parent, false))
}
override fun getItemCount(): Int = dogs.size
override fun onBindViewHolder(holder: DogViewHolder, position: Int) {
holder.bind(dogs[position])
}
fun addDog(dog: DogSample) {
dogs.add(dog)
notifyItemInserted(dogs.size - 1)
}
}
class DogViewHolder(itemView: View) : ViewHolder(itemView) {
fun bind(dog: DogSample) {
itemView.findViewById<ImageView>(R.id.dog_image).load(dog.message)
}
}
|
package com.oad.pawsavers.caretype;
import org.mapstruct.InheritInverseConfiguration;
import org.mapstruct.Mapper;
import org.mapstruct.Mapping;
import org.mapstruct.Mappings;
import java.util.List;
@Mapper(componentModel = "spring")
public interface CareTypeMapper {
@Mappings({
@Mapping(source = "id", target = "careTypeId"),
@Mapping(source = "careName", target = "nameOfCare"),
})
CareTypeDTO toCareTypeDTO(CareType careType);
List<CareTypeDTO> toCareTypeDTOList(List<CareType> careTypeList);
@InheritInverseConfiguration
CareType toCareTypeEntity(CareTypeDTO careTypeDTO);
}
|
package com.xm.controller;
import java.util.List;
import java.util.stream.Collectors;
import org.modelmapper.ModelMapper;
import org.modelmapper.PropertyMap;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import com.xm.dto.MenuDto;
import com.xm.model.AjaxResponse;
import com.xm.model.Menu;
import com.xm.service.MenuService;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
@RestController
public class MenuController {
@Autowired
private MenuService menuService;
@GetMapping("/menu/query")
public AjaxResponse queryAllMenus(){
List<Menu> list = menuService.getAllMenus();
ModelMapper modelMapper = new ModelMapper();
modelMapper.addMappings(new PropertyMap<Menu, MenuDto>() {
@Override
protected void configure() {
skip(destination.getPermissionDtos());
}
});
List<MenuDto> dtoList = list.stream()
.map(menu -> modelMapper.map(menu, MenuDto.class))
.collect(Collectors.toList());
return AjaxResponse.ok(dtoList);
}
@PostMapping("/menu/add")
public AjaxResponse addMenu(@RequestBody MenuDto menuDto) {
menuService.addMenu(menuDto);
return AjaxResponse.ok(null);
}
@PostMapping("/menu/delete")
public AjaxResponse deleteMenu(@RequestBody MenuDto menuDto){
menuService.deleteMenu(menuDto);
return AjaxResponse.ok(null);
}
@PostMapping("/menu/update")
public AjaxResponse updateMenu(@RequestBody MenuDto menuDto){
menuService.updateMenu(menuDto);
return AjaxResponse.ok(null);
}
@PostMapping("/menu/order/adjust")
public AjaxResponse adjustOrder(@RequestBody MenuDto menuDto){
menuService.adjustOrder(menuDto);
return AjaxResponse.ok(null);
}
}
|
import { cn } from '@/lib/utils';
import { DetailedHTMLProps } from 'react';
interface IPorps extends DetailedHTMLProps<React.InputHTMLAttributes<HTMLInputElement>, HTMLInputElement> {
id: string;
label?: string;
placeholder: string;
type: string;
labelClass?: string;
}
const Input = ({ label, id, placeholder, type, labelClass, ...props }: IPorps) => {
return (
<label htmlFor={id} className={cn('flex flex-col gap-[10px]', labelClass)}>
{label && <p>{label}</p>}
<input
type={type}
placeholder={placeholder}
id={id}
className='bg-[#1D1F1E] p-[10px] rounded-[10px] w-full placeholder:text-gray'
{...props}
/>
</label>
);
};
export default Input;
|
import React from "react"
import PropTypes from "prop-types"
function Header({ text, textColor, textBg }) {
const colors = {
backgroundColor: textBg,
color: textColor,
}
return (
<header style={colors}>
<div className="container">
<h2>{text}</h2>
</div>
</header>
)
}
Header.defaultProps = {
text: "Feedback UI",
textColor: "#FF6969",
textBg: "rgba(0,0,0,0.4)",
}
Header.propTypes = {
text: PropTypes.string,
}
export default Header
|
import React, { useEffect, useState } from 'react';
import JewelryList from '../components/page/jewelryList/jewelryList';
import Sort from '../components/common/sort/sort';
import FilterNav from '../components/navigation/filterNav';
import { useSelector } from 'react-redux';
import { getJewelriesList } from '../store/jewelries';
import Pagination from '../components/common/pagination/pagination';
import { paginate } from '../utils/paginate';
import _ from 'lodash';
import './catalogPage.scss';
const CatalogPage = () => {
const jewelries = useSelector(getJewelriesList());
const [currentPage, setCurrentPage] = useState(1);
const [selectedType, setSelectedType] = useState();
const [selectedMaterial, setSelectedMaterial] = useState();
const [selectedColor, setSelectedColor] = useState();
const [selectedTechnique, setSelectedTechnique] = useState();
const [sortBy, setSortBy] = useState({ path: 'price', order: 'asc' });
const pageSize = 4;
useEffect(() => {
setCurrentPage(1);
}, [selectedType, selectedColor, selectedMaterial, selectedTechnique]);
const handleTypeSelect = (item) => {
setSelectedType(item);
setSelectedMaterial();
setSelectedColor();
setSelectedTechnique();
};
const handleMaterialSelect = (item) => {
setSelectedType();
setSelectedMaterial(item);
setSelectedColor();
setSelectedTechnique();
};
const handleColorsSelect = (item) => {
setSelectedType();
setSelectedMaterial();
setSelectedColor(item);
setSelectedTechnique();
};
const handleTechniquesSelect = (item) => {
setSelectedType();
setSelectedMaterial();
setSelectedColor();
setSelectedTechnique(item);
};
const clearFilter = () => {
setSelectedType();
setSelectedColor();
setSelectedMaterial();
setSelectedTechnique();
};
const handlePageChange = (pageIndex) => {
setCurrentPage(pageIndex);
};
const handleSort = (item) => {
console.log('sort', item);
setSortBy(item);
};
function filterJewelries(data) {
if (selectedType) {
return data.filter(
(jewelry) => jewelry.jewelryType === selectedType.value
);
}
if (selectedMaterial) {
return data.filter((jewelry) =>
jewelry.materials.some((m) => m === selectedMaterial.value)
);
}
if (selectedColor) {
return data.filter((jewelry) =>
jewelry.colors.some((c) => c === selectedColor.value)
);
}
if (selectedTechnique) {
return data.filter((jewelry) =>
jewelry.techniques.some((t) => t === selectedTechnique.value)
);
}
return data;
}
const filteredJewelries = filterJewelries(jewelries);
const count = filteredJewelries.length;
const sortedJewelries = _.orderBy(
filteredJewelries,
[sortBy.path],
[sortBy.order]
);
const jewelriesCrop = paginate(sortedJewelries, currentPage, pageSize);
return (
<>
<div>
<h1 className='caption'>Каталог</h1>
<div className='header-filter'>
<FilterNav
onChangeType={handleTypeSelect}
onChangeMaterial={handleMaterialSelect}
onChangeColor={handleColorsSelect}
onChangeTechnique={handleTechniquesSelect}
clearFilters={clearFilter}
/>
</div>
<Sort onSort={handleSort} />
<JewelryList jewelries={jewelriesCrop} />
</div>
<div className='d-flex justify-content-center'>
<Pagination
itemsCount={count}
pageSize={pageSize}
currentPage={currentPage}
onPageChange={handlePageChange}
/>
</div>
</>
);
};
export default CatalogPage;
|
import { useEffect, useState } from "react";
import { useParams } from "react-router-dom";
import Nav from "../../ui/nav/Nav";
import NotFound from "../../ui/notFound/NotFound";
import ResultsTable from "../../ui/resultsTable/ResultsTable";
import ClipboardCopy from "../copyToClipboard/CopyToClipboard";
import { Pie } from "../pie/Pie";
import ResultsStyled from "./styles";
const Results = () => {
const { id } = useParams();
const [results, setResults] = useState<Record<string, any>>({});
const [waitResponse, setWaitResponse] = useState(false);
useEffect(() => {
setInterval(() => {
setWaitResponse(true);
}, 1200);
}, []);
const percent = results?.percent;
const fillColor = (percent: number) => {
if (percent < 70) return "#db3232";
if (percent >= 70 && percent < 85) return "#eb9f2d";
if (percent >= 85) return "#68bc30";
else return "grey";
};
useEffect(() => {
fetch(`http://localhost:3001/test/${id}`, { method: "GET" })
.then((res) => res.json())
.then((data) => {
setResults(data);
});
}, [id]);
return (
<ResultsStyled>
<Nav title="QuizTime!" link="/" />
{waitResponse && !results.testId && <NotFound />}
{results.testId && (
<main className="wrapper">
<div className="results-id">
<p>Save your Results Id to access your results again later:</p>
<ClipboardCopy copyText={id as string} />
</div>
<div className="title">
<h2>Results</h2>
</div>
<div className="container results-container">
<div className="results">
<Pie percentage={percent} color={fillColor(percent)} />
<div className="row-container">
<div className="row">
<p>Test:</p>
<p>{results?.testName}</p>
</div>
<div className="row">
<p>Score:</p>
<p>{results?.percent}%</p>
</div>
<div className="row">
<p>Passing Percent:</p>
<p>70%</p>
</div>
<div className="row">
<p>Status:</p>
<p>{results?.percent > 70 ? "Passed" : "Failed"}</p>
</div>
</div>
</div>
</div>
<div className="title">
<h2>Review</h2>
</div>
<div className="container review-container">
<div className="review">
{results.qaMap && (
<ResultsTable
resultsData={results.qaMap}
testId={results.testId}
/>
)}
</div>
</div>
</main>
)}
</ResultsStyled>
);
};
export default Results;
|
import { useState } from "react";
import { PostDetail } from "./PostDetail";
import { useQuery } from "react-query";
const maxPostPage = 10;
async function fetchPosts() {
const response = await fetch(
"https://jsonplaceholder.typicode.com/posts?_limit=10&_page=0"
);
return response.json();
}
export function Posts() {
const [currentPage, setCurrentPage] = useState(0);
const [selectedPost, setSelectedPost] = useState(null);
// replace with useQuery
const {data, isLoading, isError, error} = useQuery("posts", fetchPosts, {staleTime: 2000});
if(isLoading){
return <div style={{textAlign:'center'}}>Loading...</div>
}
if(isError){
return <>
<div style={{textAlign:'center'}}>Oops, Somethng went wrong!...</div>
<p>{error.toString()}</p>
</>
}
return (
<>
<ul>
{data.map((post) => (
<li
key={post.id}
className="post-title"
onClick={() => setSelectedPost(post)}
>
{post.title}
</li>
))}
</ul>
<div className="pages">
<button disabled onClick={() => {}}>
Previous page
</button>
<span>Page {currentPage + 1}</span>
<button disabled onClick={() => {}}>
Next page
</button>
</div>
<hr />
{selectedPost && <PostDetail post={selectedPost} />}
</>
);
}
|
import React from 'react';
import {Text, View, StyleSheet, StatusBar, Platform} from 'react-native';
import {size} from '../theme/fontstyle';
import {Fontfamily} from '../theme/fontFamily';
import {moderateScale, verticalScale} from 'react-native-size-matters';
import {themeColors} from '../theme/colors';
import {LogoIcon} from '../assets/svg';
type HeaderProps = {
title?: boolean;
leftChildren?: React.ReactNode;
rightChildren?: React.ReactNode;
centerTitle?: any;
childStyle?: any;
centerStyle?: any;
rightStyle?: any;
containerStyle?: any;
children?: React.ReactNode;
sizeprop?: number;
width?:string
rightChildrenWidth?:string
leftChildrenWidth?:string
};
const Header: React.FC<HeaderProps> = ({
title,
leftChildren,
rightChildren,
centerTitle,
childStyle,
centerStyle,
rightStyle,
containerStyle,
children,
sizeprop,
width,
rightChildrenWidth,
leftChildrenWidth,
}) => {
return (
<>
<StatusBar backgroundColor="transparent" translucent={true} />
<View style={{...styles.container, ...containerStyle}}>
<View style={styles.child}>
<View style={[{...styles.leftChildren, ...childStyle,width:leftChildrenWidth ? leftChildrenWidth :'30%'}]}>
{leftChildren}
</View>
<View style={[{...styles.center, ...centerStyle,width:width ? width :'35%'}]}>
{title ? (
<LogoIcon />
) : children ? (
children
) : (
<Text style={[styles.centerTitle,{fontSize:sizeprop ? sizeprop: size.lg}]}>{centerTitle}</Text>
)}
</View>
<View style={[{...styles.rightChildren, ...rightStyle,width:rightChildrenWidth ? rightChildrenWidth :'30%'}]}>
{rightChildren}
</View>
</View>
</View>
</>
);
};
export default Header;
const styles = StyleSheet.create({
container: {
paddingHorizontal: moderateScale(22),
paddingTop: Platform.OS === 'ios' ? moderateScale(10) : moderateScale(10),
},
child: {
flexDirection: 'row',
justifyContent: 'space-between',
alignItems: 'center',
height: verticalScale(30),
},
leftChildren: {
width: '30%',
},
center: {
width: '35%',
alignItems: 'center',
},
rightChildren: {
width: '30%',
alignItems: 'flex-end',
},
title: {
color: themeColors.primaryColor,
fontSize: size.lg,
fontWeight: '500',
fontFamily: Fontfamily.Avenier,
},
centerTitle: {
color: 'white',
fontSize: size.lg,
fontWeight: '500',
fontFamily: Fontfamily.Avenier,
},
});
|
import SwiftUI
struct ContentView: View {
@State private var selectedTemperature: Double = 22
@State private var selectedRoom: Room = .chambre
@State private var temperaturesForRooms: [Room: Double] = Room.allCases.reduce(into: [:]) { $0[$1] = 22 }
@State private var hvacModesForRooms: [Room: HvacModes] = Room.allCases.reduce(into: [:]) { $0[$1] = .off }
var body: some View {
NavigationView {
GeometryReader { geometry in
ZStack {
Color("Background").ignoresSafeArea()
VStack(spacing: 0) {
TabView(selection: $selectedRoom) {
ForEach(Room.allCases, id: \.self) { room in
ThermostatView(
temperature: self.bindingFor(room: room),
mode: self.hvacModeBindingFor(room: room),
room: room
)
.tag(room)
}
}
.tabViewStyle(PageTabViewStyle())
.frame(width: geometry.size.width, height: geometry.size.width)
}
}
}
.navigationBarTitleDisplayMode(.inline)
.navigationTitle(selectedRoom.rawValue)
}
}
private func bindingFor(room: Room) -> Binding<Double> {
Binding(
get: { self.temperaturesForRooms[room, default: 22] },
set: { self.temperaturesForRooms[room] = $0 }
)
}
private func hvacModeBindingFor(room: Room) -> Binding<HvacModes> {
Binding(
get: { self.hvacModesForRooms[room, default: .off] },
set: { self.hvacModesForRooms[room] = $0 }
)
}
}
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView().environmentObject(ClimateViewModel()) // This is where you add the environment object
}
}
|
<?php
namespace Tarikul\Contact\Mail;
use Illuminate\Bus\Queueable;
use Illuminate\Mail\Mailable;
use Illuminate\Queue\SerializesModels;
class SendContactMail extends Mailable
{
use Queueable, SerializesModels;
public $message;
public $name;
/**
* Create a new message instance.
*
* @return void
*/
public function __construct($name, $message)
{
$this->name = $name;
$this->message = $message;
}
/**
* Build the message.
*
* @return $this
*/
public function build()
{
return $this->markdown('contact::contact.email')->with(['message' => $this->message, 'name' => $this->name]);
}
}
|
#include <string>
#include <glad/glad.h>
#include "Shader.h"
#include <cassert>
#include <fstream>
#include <sstream>
#include <iostream>
#include "glog/logging.h"
#include <GL/gl.h>
/**
* \brief
* \param _path glsl文件路径
* \param _type Shader类型
*/
Shader::Shader(const std::string& _path, SHADER_TYPE _type): m_path(_path)
{
const auto type = transformShaderTypeToGlEnum(_type);
std::string source;
std::ifstream shaderFile;
shaderFile.exceptions(std::ifstream::failbit | std::ifstream::badbit);
try {
shaderFile.open(_path);
std::stringstream shaderStream;
shaderStream << shaderFile.rdbuf();
shaderFile.close();
source = shaderStream.str();
}
catch (std::ifstream::failure& _e) {
LOG(ERROR) << "path(" << _path << ")" << _e.what();
exit(-1);
}
const auto code = source.c_str();
m_id = glCreateShader(type);
glShaderSource(m_id, 1, &code, nullptr);
glCompileShader(m_id);
checkCompileErrors(m_id, SHADER_TYPE::VERTEX);
}
Shader::~Shader()
{
assert(m_id != -1);
glDeleteShader(m_id);
}
GLenum Shader::transformShaderTypeToGlEnum(SHADER_TYPE _type)
{
switch (_type)
{
case SHADER_TYPE::VERTEX: return GL_VERTEX_SHADER;
case SHADER_TYPE::FRAGMENT: return GL_FRAGMENT_SHADER;
case SHADER_TYPE::GEOMETRY: return GL_GEOMETRY_SHADER;
}
}
/**
* \brief 检查编译错误
* \param shader id
* \param type 代码类型
*/
void Shader::checkCompileErrors(unsigned int shader, SHADER_TYPE type)
{
int success;
glGetShaderiv(shader, GL_COMPILE_STATUS, &success);
if (!success)
{
char infoLog[1024];
glGetShaderInfoLog(shader, 1024, nullptr, infoLog);
LOG(ERROR) << "An error occurred while compiling shader code (" << m_path << ") " << infoLog;
exit(-1);
}
}
|
import React from "react";
import { CurrentUserContext } from "../contexts/CurrentUserContext";
import PopupWithForm from "./PopupWithForm";
function EditAvatarPopup(props) {
const ref = React.useRef();
function handleSubmit(e) {
e.preventDefault();
props.onUpdateAvatar({
avatar: ref.current.value,
});
}
React.useEffect(() => {
ref.current.value = "";
}, [props.isOpen]);
return (
<PopupWithForm
title="Обновить аватар"
name="avatar-edit"
buttonText="Сохранить."
isOpen={props.isOpen}
onClose={props.onClose}
onSubmit={handleSubmit}
>
<label className="popup__form-label">
<input
type="url"
className="popup__input popup__input_type_link"
name="avatar"
id="avatar-input"
placeholder="Ссылка на картинку"
required
ref={ref}
/>
<span className="form__input-error avatar-input-error">
Введите адрес сайта.
</span>
</label>
</PopupWithForm>
);
}
export default EditAvatarPopup;
|
import Component from './Component';
import About from './components/About';
import Contact from './components/Contact';
import Footer from './components/Footer';
import Header from './components/Header';
import HeroBanner from './components/HeroBanner';
import Projects from './components/Projects';
interface IAppState {
projectsList: string[];
}
export default class App extends Component {
public state: IAppState;
constructor() {
super('app');
this.state = {
projectsList: [
'auto-ngtemplate-loader',
'hue-remote',
'cluster-cleanup',
'colorcode',
'simple-load-tester',
'federator'
]
};
}
public render() {
const header = new Header();
const heroBanner = new HeroBanner();
const about = new About();
const projects = new Projects(this.state.projectsList);
const contact = new Contact();
const footer = new Footer();
return `
<div class="flex-column">
${header.render()}
${heroBanner.render()}
${about.render()}
${projects.render()}
${contact.render()}
${footer.render()}
</div>
`;
}
}
|
How to create your own node module?
Rectange.js
module.exports = (length, breadth, callback) => {
if (length <= 0 || breadth <= 0)
setTimeout(() => callback(new Error(
"Dimensions cannot be negative: length = "
+ length + ", and breadth = "
+ breadth), null), 5000);
else
setTimeout(() => callback(null, {
Perimeter: () => (2*(length+breadth)),
Area:() => (length*breadth) }), 5000);
}
How ot use this node module in your own app?
var rect = require('./rectangle');
module.exports.Rect = function Rect(l, b) {
rect(l, b, (err, rectangle) => {
if (err)
console.log("There is an ERROR!!: ", err.message);
else {
console.log("Area of rectangle with dimensions length = "
+ l + " and breadth = " + b + " : " + rectangle.Area());
console.log("Perimeter of the rectangle with dimensions length = "
+ l + " and breadth = " + b + " : " + rectangle.Perimeter());
}
console.log("\n\n");
});
};
var rect = require("./module");
rect.Rect(5, 2);
rect.Rect(-1, 0);
rect.Rect(12, 4);
rect.Rect(8, 6);
rect.Rect(3, 4);
|
import Link from 'next/link';
import { HoverCard, HoverCardContent, HoverCardTrigger } from '@/components/ui/hover-card';
import FooterMenu from 'components/layout/footer-menu';
import { getMenu } from 'lib/shopify';
import { ArrowUpRight } from 'lucide-react';
import Image from 'next/image';
import { Suspense } from 'react';
import { FaFacebook, FaInstagram, FaXTwitter, FaYoutube } from 'react-icons/fa6';
const { COMPANY_NAME, SITE_NAME } = process.env;
export default async function Footer() {
const currentYear = new Date().getFullYear();
const copyrightDate = 2023 + (currentYear > 2023 ? `-${currentYear}` : '');
const skeleton = 'w-full h-6 animate-pulse rounded bg-neutral-200 dark:bg-neutral-700';
const menu = await getMenu('next-js-frontend-footer-menu');
const copyrightName = COMPANY_NAME || SITE_NAME || '';
return (
<footer className="bg-neutral-900 text-sm text-muted-foreground">
<div className="mx-auto flex w-full max-w-7xl flex-col justify-between gap-6 border-t-2 px-6 py-12 text-sm md:flex-row md:gap-12 md:px-4 min-[1320px]:px-0">
<div className="gap-12 space-y-8 md:flex md:space-y-0">
<Link className="gap-2 text-white hover:text-muted-foreground md:pt-1" href="/">
<div>
<Link className="flex font-bold" href={'/'}>
<Image
src="/logos/the-armoury-bookshop.png"
height="40"
width="40"
alt="The Armoury Bookshop Logo"
className="mr-4"
/>
<div className="my-auto hover:text-muted-foreground">
<p className="relative my-auto whitespace-nowrap font-logo text-xl leading-none">
<span className="absolute -top-2.5 left-4 text-sm">The</span>
Armoury
</p>
<p className="ml-2 whitespace-nowrap font-logo text-xl leading-none">Bookshop</p>
</div>
</Link>
</div>
</Link>
<Suspense
fallback={
<div className="flex h-[188px] w-[200px] flex-col gap-2">
<div className={skeleton} />
<div className={skeleton} />
<div className={skeleton} />
<div className={skeleton} />
<div className={skeleton} />
<div className={skeleton} />
</div>
}
>
<FooterMenu menu={menu} />
</Suspense>
</div>
<div>
<div className="flex flex-col gap-2">
<div className="flex justify-center gap-4">
<a
href="https://x.com/thearmourybookshop"
target="_blank"
rel="noreferrer"
className="text-muted-foreground hover:text-white"
>
<FaXTwitter className="my-auto h-6 w-6" />
</a>
<a
href="https://www.facebook.com/thearmourybookshop"
target="_blank"
rel="noreferrer"
className="text-muted-foreground hover:text-white"
>
<FaFacebook className="my-auto h-6 w-6" />
</a>
<a
href="https://www.instagram.com/thearmourybookshop/"
target="_blank"
rel="noreferrer"
className="text-muted-foreground hover:text-white"
>
<FaInstagram className="my-auto h-6 w-6" />
</a>
<a
href="https://www.youtube.com/@TheArmouryBookshop"
target="_blank"
rel="noreferrer"
className="text-muted-foreground hover:text-white"
>
<FaYoutube className="my-auto h-6 w-6" />
</a>
</div>
</div>
</div>
</div>
<div className="border-t-2 py-6 text-sm">
<div className="mx-auto flex w-full max-w-7xl flex-col items-center gap-1 px-4 md:flex-row md:gap-0 md:px-4 min-[1320px]:px-0">
<p>
© {copyrightDate} {copyrightName}
{copyrightName.length && !copyrightName.endsWith('.') ? '.' : ''} All rights reserved.
</p>
<p className="md:ml-auto">
Part of{' '}
<HoverCard>
<HoverCardTrigger className="cursor-pointer font-medium underline-offset-4 hover:text-white hover:underline">
61 Oaks Group
</HoverCardTrigger>
<HoverCardContent className="text-left">
<div className="space-y-1">
<p className="text-sm">
A collection of initiatives, projects and business that are aimed at reforming
their sectors to build up ruins, raise up former devastations, repair ruined
cities and provide discipleship for the future generation of leaders.
</p>
<div className="flex items-center pt-2">
<a
href="https://61oaksgroup.com.au/"
target="_blank"
rel="noreferrer"
className="flex text-xs text-muted-foreground hover:text-accent-foreground"
>
Website <ArrowUpRight className="h-3 w-3" />
</a>
</div>
</div>
</HoverCardContent>
</HoverCard>
</p>
</div>
</div>
</footer>
);
}
|
package com.social.media.confessionmedia.authorizationserver.service;
import com.social.media.confessionmedia.authorizationserver.config.JwtProvider;
import com.social.media.confessionmedia.authorizationserver.dto.*;
import com.social.media.confessionmedia.authorizationserver.exceptions.SocialGeneralException;
import com.social.media.confessionmedia.authorizationserver.model.User;
import com.social.media.confessionmedia.authorizationserver.model.VerificationToken;
import com.social.media.confessionmedia.authorizationserver.repository.VerificationTokenRepo;
import com.social.media.confessionmedia.authorizationserver.repository.UserRepo;
import lombok.AllArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AnonymousAuthenticationToken;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.oauth2.jwt.Jwt;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.time.Instant;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.time.temporal.ChronoUnit;
import java.util.Optional;
import java.util.UUID;
@AllArgsConstructor
@Service
public class AuthService {
private UserRepo userRepo;
private PasswordEncoder passwordEncoder;
private VerificationTokenRepo verificationTokenRepo;
private MailService mailService;
// AuthenticationManager is autowired from SecurityConfig init.
@Autowired
private AuthenticationManager authenticationManager;
private JwtProvider jwtProvider;
private AccessTokenService accessTokenService;
private RefreshTokenService refreshTokenService;
private final String PATTERN_FORMAT = "dd/MM/YYYY hh:mm:ss";
private final DateTimeFormatter formatter = DateTimeFormatter.ofPattern(PATTERN_FORMAT)
.withZone(ZoneId.systemDefault());
@Transactional
public void signUp(RegisterFormDTO registerFormDTO) {
User user = new User();
user.setEmail(registerFormDTO.getEmail());
user.setUserName(registerFormDTO.getUsername());
user.setEnabled(false); // UnActivated account
user.setCreated(Instant.now());
checkDuplicateUsernameOrEmail(user);
user.setPassword(passwordEncoder.encode(registerFormDTO.getPassword()));
userRepo.save(user);
String tokenValue = generateVerification(user);
mailService.sendRegisterConfirmationEmail(user, tokenValue);
}
private void checkDuplicateUsernameOrEmail(User user) {
userRepo.findByUserNameOrEmail(user.getUserName(), user.getEmail())
.ifPresent( u -> {throw new RuntimeException("A user with this username or email already exists");});
}
private String generateVerification(User user) {
String tokenValue = UUID.randomUUID().toString();
VerificationToken vt = new VerificationToken();
vt.setTokenValue(tokenValue);
vt.setUser(user);
vt.setCreated(Instant.now());
verificationTokenRepo.save(vt);
return tokenValue;
}
public void verificationRegisteredAccountByToken(String tokenValue) {
Optional<VerificationToken> optionalVerificationToken = verificationTokenRepo.findByTokenValue(tokenValue);
optionalVerificationToken.orElseThrow(() -> new SocialGeneralException("Invalid token"));
fetchUserAndEnable(optionalVerificationToken.get());
}
private void fetchUserAndEnable(VerificationToken token) {
// Token entity has User_id, lazy load
User u = token.getUser();
u.setEnabled(true);
userRepo.save(u);
}
@Transactional
public AuthenticationResponseDTO login(RequestLoginDTO requestLoginDTO) throws Exception, AuthenticationException {
UsernamePasswordAuthenticationToken userPwdAuthToken =
new UsernamePasswordAuthenticationToken(requestLoginDTO.getUsername(), requestLoginDTO.getPassword());
Authentication authenticationCore = authenticationManager.authenticate(userPwdAuthToken);
User userModel = (User) authenticationCore.getPrincipal();
String accessToken = accessTokenService.generateNewAccessTokenByUserName(userModel.getUserName());
String refreshedToken = refreshTokenService.generateAndSaveRefreshToken(userModel.getUserName());
String accessTokenExpiration = formatter.format(Instant.now().plus(jwtProvider.getJwtExpirationInMinutes(), ChronoUnit.MINUTES));
String refreshedExpiration = formatter.format(Instant.now().plus(jwtProvider.getRefreshExpiration(), ChronoUnit.MINUTES));
return AuthenticationResponseDTO.builder()
.accessToken(accessToken)
.refreshToken(refreshedToken)
.username(requestLoginDTO.getUsername())
.accessTokenExpiresAt(accessTokenExpiration)
.refreshTokenExpiresAt(refreshedExpiration)
.build();
}
/// If access token is expired, call this method to request a new one
public AuthenticationResponseDTO requestNewAccessToken(NewAccessTokenRequestDTO newAccessTokenRequestDTO) {
String accessToken = accessTokenService.generateNewAccessTokenByRefreshToken(newAccessTokenRequestDTO);
String accessTokenExpiration = formatter.format(Instant.now().plus(jwtProvider.getJwtExpirationInMinutes(), ChronoUnit.MINUTES));
return AuthenticationResponseDTO.builder()
.accessToken(accessToken)
.refreshToken(newAccessTokenRequestDTO.getRefreshToken())
.username(newAccessTokenRequestDTO.getUsername())
.accessTokenExpiresAt(accessTokenExpiration)
.build();
}
public AuthenticationResponseDTO logout(NewAccessTokenRequestDTO tokenRequestDTO) {
if(tokenRequestDTO.getRefreshToken().isEmpty() == false){
Optional<User> userOp = userRepo.findByUserName(tokenRequestDTO.getUsername());
refreshTokenService.revokeAllUserRefreshedTokens(userOp.get());
}
return AuthenticationResponseDTO.builder()
.accessToken(null)
.refreshToken(null)
.username(tokenRequestDTO.getUsername())
.accessTokenExpiresAt(null)
.build();
}
@Transactional(readOnly = true)
public User getCurrentUser() {
Jwt principal = (Jwt )SecurityContextHolder.getContext().getAuthentication().getPrincipal();
return userRepo.findByUserName(principal.getSubject())
.orElseThrow(() -> new UsernameNotFoundException("User name not found - " + principal.getSubject()));
}
public boolean isLoggedIn() {
Authentication auth = SecurityContextHolder.getContext().getAuthentication();
return auth.isAuthenticated() && !(auth instanceof AnonymousAuthenticationToken);
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Player : MonoBehaviour
{
[Header("Attack details")]
[SerializeField] Vector2[] _attackMovement;
[Header("Move Setup")]
[SerializeField] float _moveSpeed = 5f;
[SerializeField] float _jumpVelocity = 3f;
[Header("Dash Info")]
[SerializeField] float _dashSpeed;
[SerializeField] float _dashDuration;
[SerializeField] float _dashTimer;
float _dashCooldown;
public float DashDirection { get; private set; }
[Header("Check Collisions")]
[SerializeField] Transform _groundCheck;
[SerializeField] float _groundCheckDistance;
[SerializeField] Transform _wallCheck;
[SerializeField] float _wallCheckDistance;
[SerializeField] LayerMask _groundLayer;
public Rigidbody2D RB { get; private set; }
public Animator Anim { get; private set; }
public PlayerStateMachine StateMachine { get; private set; }
public PlayerIdleState IdleState { get; private set; }
public PlayerMoveState MoveState { get; private set; }
public PlayerJumpState JumpState { get; private set; }
public PlayerAirState AirState { get; private set; }
public PlayerDashState DashState { get; private set; }
public PlayerWallSlideState WallSlideState { get; private set; }
public PlayerWallJumpState WallJumpState { get; private set; }
public PlayerPrimaryAttackState PrimaryAttackState { get; private set; }
public float MoveSpeed => _moveSpeed;
public float JumpVelocity => _jumpVelocity;
public float DashSpeed => _dashSpeed;
public float DashDuration => _dashDuration;
public Vector2[] AttackMovement => _attackMovement;
public int FacingDir { get; private set; } = 1;
public bool IsBusy { get; private set; }
bool isFacingRight = true;
void Awake()
{
StateMachine = new PlayerStateMachine();
IdleState = new PlayerIdleState(this, StateMachine, "Idle");
MoveState = new PlayerMoveState(this, StateMachine, "Move");
JumpState = new PlayerJumpState(this, StateMachine, "Jump");
AirState = new PlayerAirState(this, StateMachine, "Jump");
DashState = new PlayerDashState(this, StateMachine, "Dash");
WallSlideState = new PlayerWallSlideState(this, StateMachine, "WallSlide");
WallJumpState = new PlayerWallJumpState(this, StateMachine, "Jump");
PrimaryAttackState = new PlayerPrimaryAttackState(this, StateMachine, "Attack");
}
void Start()
{
Anim = GetComponentInChildren<Animator>();
RB = GetComponent<Rigidbody2D>();
StateMachine.Initialize(IdleState);
}
void Update()
{
StateMachine.CurrentState.Update();
CheckForDashInput();
}
public IEnumerator BusyFor(float seconds)
{
IsBusy = true;
yield return new WaitForSeconds(seconds);
IsBusy = false;
}
public void AnimationTrigger() => StateMachine.CurrentState.AnimationFinishTrigger();
#region Velocity
public void SetVelocity(float xVelocity, float yVelocity)
{
RB.velocity = new Vector2(xVelocity, yVelocity);
FlipController(xVelocity);
}
public void SetZeroVelocity() => RB.velocity = Vector2.zero;
#endregion
#region Flip
private void Flip()
{
FacingDir *= -1;
isFacingRight = !isFacingRight;
transform.Rotate(0, 180, 0);
}
private void FlipController(float x)
{
if (x > 0 && !isFacingRight)
Flip();
else if (x < 0 && isFacingRight)
Flip();
}
#endregion
#region Collision
public bool IsGrounded() => Physics2D.Raycast(_groundCheck.position, Vector2.down, _groundCheckDistance, _groundLayer);
public bool IsWallDetected() => Physics2D.Raycast(_wallCheck.position, Vector2.right * FacingDir, _wallCheckDistance, _groundLayer);
private void CheckForDashInput()
{
if (IsWallDetected())
return;
_dashCooldown -= Time.deltaTime;
if (Input.GetKeyDown(KeyCode.LeftShift) && _dashCooldown < 0)
{
DashDirection = Input.GetAxisRaw("Horizontal");
if (DashDirection == 0)
DashDirection = FacingDir;
StateMachine.ChangeState(DashState);
_dashCooldown = _dashTimer;
}
}
void OnDrawGizmos()
{
Gizmos.DrawLine(_groundCheck.position, new Vector3(_groundCheck.position.x, _groundCheck.position.y - _groundCheckDistance));
Gizmos.DrawLine(_wallCheck.position, new Vector3(_wallCheck.position.x + _wallCheckDistance, _wallCheck.position.y));
}
#endregion
}
|
#[macro_use] //Para usar las macro creada
extern crate diesel; //Extendible de diesel
extern crate tera; //Extendible de tera
pub mod api; //Usando los datos de la api
pub mod database; //Usando los datos de la base de datos
pub mod inserts; //Usando los datos de los inserts
pub mod models; //Usando los datos de los modelos
pub mod schemas; //Usando los datos del squema //Usando los datos de la api
use crate::api::{
contact, contact_post, index, post, profile, query_index_get, query_index_post, service,
}; //Usando los datos de la api
use actix_web::{web, App, HttpServer}; //Usando Actix web
use diesel::pg::PgConnection; // Import the Diesel postgres connection
use diesel::r2d2::Pool; //Import the r2d2 pool multi conexiones para la data base
use diesel::r2d2::{self, ConnectionManager}; //Import the r2d2 connection manager
use dotenv::dotenv; // Import the dotenv library
use std::env; //Import the env library
use tera::Tera; //Usando Tera
type DbPool = r2d2::Pool<ConnectionManager<PgConnection>>; //Definir el tipo de la conexion
//********************************************* PRINCIPAL FUNCTION MAIN*********************************************
#[actix_web::main]
//Funcion principal
async fn main() -> std::io::Result<()> {
// Cargar las variables de entorno
dotenv().ok();
// Crear la pool de conexiones
let db_url = env::var("DATABASE_URL").expect("db url variable no encontrada");
let connection = ConnectionManager::<PgConnection>::new(db_url);
let pool = Pool::builder()
.build(connection)
.expect("No se pudo construir la Pool");
// Obtener el puerto del servidor
let port = env::var("PORT").expect("La variable de entorno PORT no existe.");
let port: u16 = port.parse().unwrap();
// Print the url of the server to the console
println!("Server running at http://localhost:{}", port);
//Crear el servidor
HttpServer::new(move || {
//Use Tera
let tera = Tera::new(concat!(env!("CARGO_MANIFEST_DIR"), "/templates/**/*")).unwrap();
//Crear el servidor
App::new()
.service(index)
.service(query_index_get) //para que no hayan errores en la pool de los datos se deben de crear una copia de los datos y inicializarla en el servidor con una nueva
.service(query_index_post)
.service(profile)
.service(service)
.service(post)
.service(contact)
.service(contact_post)
.app_data(web::Data::new(pool.clone()))
.app_data(web::Data::new(tera.clone()))
})
.bind(("0.0.0.0", port))
.unwrap()
.run()
.await
}
//********************************************* END PRINCIPAL FUNCTION MAIN*********************************************
/*
TIPS PARA LOS COMENTARIOS PARA DOCUMENTAR MY CODE DIOSSSS TODO LO QUE FALTA POR HACER "THANKS GOOD , FOR THE GOOD TIMES IN LIVE CODING "
*aaaa
!aaaa
? aaaa
TODO : aa
@param MyParam
*/
|
package org.example.demo.minio.controller;
import javax.servlet.http.HttpServletResponse;
import org.example.demo.minio.config.MinioClientConfig;
import org.example.demo.minio.utils.MinioUtil;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import io.minio.MinioClient;
/**
* @author hekai
* @date 2024/3/8
*/
@RestController
@RequestMapping("/minio")
public class MinioController {
@PostMapping("/upload")
public void uploadFile(@RequestBody MultipartFile file) {
MinioClient minio_client = MinioClientConfig.getMinioClient();
boolean is_upload_success = MinioUtil.minioUpload(file, "", "test");
}
@GetMapping("/preview")
public String getFilePreviewUrl(@RequestParam String file_name) {
MinioClient minio_client = MinioClientConfig.getMinioClient();
String url = MinioUtil.getPreviewFileUrl("test", file_name);
return url;
}
@GetMapping("/download")
public void downloadFile(@RequestParam String file_name, HttpServletResponse response) {
MinioClient minio_client = MinioClientConfig.getMinioClient();
MinioUtil.minioDownload("test", file_name, "/home/hekai/" + file_name);
}
@DeleteMapping("/delete")
public String deleteFile(String file_name) {
MinioClient minio_client = MinioClientConfig.getMinioClient();
MinioUtil.deleteFile("test", file_name);
return "";
}
}
|
import 'package:flutter/material.dart';
import 'package:flutter_svg/flutter_svg.dart';
import 'package:resume/Cards/main_content_card.dart';
import 'package:resume/Cards/side_content_card.dart';
import 'package:resume/NavBar/nav_bar_item.dart';
import 'package:resume/Pages/home_page.dart';
import 'package:resume/Pages/logs_page.dart';
import 'package:resume/Pages/pages.dart';
import 'package:resume/Pages/profile_page.dart';
import 'package:resume/Pages/resume_page.dart';
void main() {
runApp(const MyApp());
}
class MyApp extends StatelessWidget {
const MyApp({super.key});
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Paul Huang',
theme: ThemeData(
useMaterial3: true,
),
home: const MyHomePage(title: 'Paul Huang'),
);
}
}
class MyHomePage extends StatefulWidget {
const MyHomePage({super.key, required this.title});
final String title;
@override
State<MyHomePage> createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
List<Pages> pages = [
HomePage(),
ProfilePage(),
ResumePage(),
LogsPage(),
];
int _curPage = 0;
void select(int n) {
_curPage = n;
}
@override
Widget build(BuildContext context) {
return Scaffold(
body: Stack(
children: [
SizedBox.expand(
child: SvgPicture.asset(
'assets/background/rainbow-vortex.svg',
fit: BoxFit.cover,
),
),
Container(
margin: const EdgeInsets.fromLTRB(140.0, 40.0, 100.0, 40.0),
decoration: const BoxDecoration(
color: Color.fromARGB(255, 128, 128, 128),
borderRadius: BorderRadius.all(
Radius.circular(20.0),
),
boxShadow: [
BoxShadow(
color: Color.fromARGB(144, 0, 0, 0),
offset: Offset(-5.0, 5.0),
blurRadius: 10,
)
],
),
child: Row(
children: [
Container(
height: MediaQuery.of(context).size.height,
width: 101.0,
decoration: const BoxDecoration(
color: Color.fromARGB(255, 24, 24, 26),
borderRadius: BorderRadius.horizontal(
left: Radius.circular(20.0),
),
),
child: Column(
children: pages
.map(
(e) => NavBarItem(
icon: e.icon,
title: e.title,
selected: pages.indexOf(e) == _curPage,
onTap: () {
setState(
() {
select(pages.indexOf(e));
},
);
},
),
)
.toList(),
),
),
Expanded(
child: MainContentCard(
currentPage: _curPage,
content: pages[_curPage].pageView,
),
),
const SideContentCard(),
],
),
),
],
),
);
}
}
|
package dto
import "github.com/Meystergod/online-store/internal/domain/model"
type CreateDiscount struct {
Title string `json:"title" bson:"title" validate:"required"`
Percent int `json:"percent" bson:"percent" validate:"required"`
IsActive bool `json:"is-active" bson:"is-active" validate:"required"`
}
type UpdateDiscount struct {
Title string `json:"title" bson:"title" validate:"required"`
Percent int `json:"percent" bson:"percent" validate:"required"`
IsActive bool `json:"is-active" bson:"is-active" validate:"required"`
}
func (createDiscount *CreateDiscount) ToModel() *model.Discount {
return &model.Discount{
Title: createDiscount.Title,
Percent: createDiscount.Percent,
IsActive: createDiscount.IsActive,
}
}
func (updateDiscount *UpdateDiscount) ToModel() *model.Discount {
return &model.Discount{
Title: updateDiscount.Title,
Percent: updateDiscount.Percent,
IsActive: updateDiscount.IsActive,
}
}
|
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import '../../theming/colors/colors_manager.dart';
import '../../theming/styles/fonts.dart';
import '../../validators/base_validators.dart';
class AppTextFormField extends StatelessWidget {
final bool obsure;
final bool selectAllOnFocus;
final TextInputType? type;
final FormFieldSetter? onSaved;
final FormFieldSetter? onChange;
final VoidCallback? onTap;
final FormFieldValidator? validate;
final String? label;
final String? hintText;
final List<BaseValidator> validators;
final int? maxLines;
final bool isEnableBorder;
final bool enable;
final bool autofocus;
final TextEditingController? controller;
final Widget? prefix;
final Widget? suffix;
final double? h;
final double? w;
final FocusNode? focusNode;
final String? inputFormatterText;
final List<TextInputFormatter>? inputFormatter;
final double? borderRadius;
final double? fontSize;
final FontWeight fontWeight;
final TextStyle? hintStyle;
final TextStyle? style;
final Color? labelColor;
const AppTextFormField(
{Key? key,
this.obsure = false,
this.selectAllOnFocus = false,
this.borderRadius,
this.hintStyle,
this.style,
this.focusNode,
this.enable = true,
this.autofocus = false,
this.type,
this.onSaved,
this.validators = const [],
this.fontSize,
this.fontWeight = AppFontWeight.weight_400,
this.onChange,
this.onTap,
this.validate,
this.inputFormatter,
this.inputFormatterText,
this.label,
this.hintText,
this.maxLines,
this.isEnableBorder = true,
this.controller,
this.prefix,
this.suffix,
this.labelColor,
this.h,
this.w})
: super(key: key);
@override
Widget build(BuildContext context) {
return SizedBox(
height: h,
width: w,
child: TextFormField(
onTapOutside: (event) {
FocusManager.instance.primaryFocus?.unfocus();
},
autovalidateMode: AutovalidateMode.disabled,
controller: controller,
style: style ?? Styles.font14PrimaryColorWeight500(),
obscureText: obsure,
enabled: enable,
autofocus: autofocus,
onTap: gestureTapCallback(),
focusNode: focusNode,
onSaved: onSaved,
validator: (value) => BaseValidator.validateValue(
context, inputFormatterText ?? value, validators, true),
onChanged: onChange,
maxLines: maxLines,
inputFormatters: inputFormatter,
decoration: InputDecoration(
contentPadding:
const EdgeInsets.symmetric(vertical: 0, horizontal: 16),
errorBorder: isEnableBorder
? OutlineInputBorder(
borderRadius: BorderRadius.circular(borderRadius ?? 60),
borderSide: const BorderSide(
color: AppFixedColors.red,
))
: InputBorder.none,
hintText: hintText,
enabledBorder: isEnableBorder ? defaultBorder() : null,
disabledBorder: defaultBorder(),
border: isEnableBorder
? OutlineInputBorder(
borderRadius: BorderRadius.circular(borderRadius ?? 60),
borderSide: BorderSide(
color: ColorsManager.instance(context).primaryColor,
))
: InputBorder.none,
// focusColor: Colors.black,
focusedBorder: isEnableBorder
? OutlineInputBorder(
borderSide: BorderSide(
width: 1,
color: ColorsManager.instance(context).primaryColor,
),
borderRadius: BorderRadius.circular(borderRadius ?? 60),
)
: null,
labelText: label,
hintStyle: hintStyle ?? Styles.font14PrimaryColorWeight500(),
labelStyle: Styles.font14PrimaryColorWeight500(),
prefixIcon: prefix,
suffixIcon: suffix,
),
keyboardType: type ??
TextInputType.text,
),
);
}
GestureTapCallback? gestureTapCallback() {
if (selectAllOnFocus) {
return () => controller?.selection = TextSelection(
baseOffset: 0, extentOffset: controller!.value.text.length);
} else {
return onTap;
}
}
OutlineInputBorder defaultBorder() {
return OutlineInputBorder(
borderRadius: BorderRadius.circular(borderRadius ?? 60),
borderSide: BorderSide(color: ColorsManager.defaultInstance.primaryColor),
);
}
}
|
package com.bogdan801.heartbeat_test_task.presentation.components
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material3.AlertDialog
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Text
import androidx.compose.material3.TextButton
import androidx.compose.runtime.Composable
import androidx.compose.ui.unit.dp
@Composable
fun WarningDialogBox(
showDialog: Boolean = false,
text: String = "",
onConfirm: () -> Unit = {},
onDismiss: () -> Unit = {}
) {
if(showDialog){
AlertDialog(
onDismissRequest = onDismiss,
shape = RoundedCornerShape(5.dp),
containerColor = MaterialTheme.colorScheme.background,
text = {
Text(
text = text,
style = MaterialTheme.typography.bodyLarge,
color = MaterialTheme.colorScheme.onBackground
)
},
confirmButton = {
TextButton(onClick = onConfirm) {
Text("CONFIRM")
}
},
dismissButton = {
TextButton(onClick = onDismiss) {
Text("DISMISS")
}
}
)
}
}
|
@extends('layouts.main')
@section('content')
<!-- Content Header (Page header) -->
<div class="content-header">
<div class="container-fluid">
<div class="row mb-2">
<div class="col-sm-6">
<h1 class="m-0">Редактировать аптеку</h1>
</div><!-- /.col -->
<div class="col-sm-6">
<ol class="breadcrumb float-sm-right">
<li class="breadcrumb-item"><a href="{{ route('main.index') }}">Главная</a></li>
</ol>
</div><!-- /.col -->
</div><!-- /.row -->
</div><!-- /.container-fluid -->
</div>
<!-- /.content-header -->
<!-- Main content -->
<section class="content">
<div class="container-fluid">
<!-- Edit Pharmacy Form -->
<div class="row">
<div class="col-md-6">
<div class="card">
<div class="card-body">
<form action="{{ route('pharmacy.update', $pharmacy->id) }}" method="post">
@csrf
@method('patch')
<div class="form-group">
<label for="name">Название</label>
<input type="text" class="form-control @error('name') is-invalid @enderror" name="name" value="{{ old('name', $pharmacy->name) }}" placeholder="Название">
@error('name')
<div class="invalid-feedback">{{ $message }}</div>
@enderror
</div>
<div class="form-group">
<label for="city">Город</label>
<input type="text" class="form-control @error('city') is-invalid @enderror" name="city" value="{{ old('city', $pharmacy->city) }}" placeholder="Город">
@error('city')
<div class="invalid-feedback">{{ $message }}</div>
@enderror
</div>
<div class="form-group">
<label for="address">Адрес</label>
<input type="text" class="form-control @error('address') is-invalid @enderror" name="address" value="{{ old('address', $pharmacy->address) }}" placeholder="Адрес">
@error('address')
<div class="invalid-feedback">{{ $message }}</div>
@enderror
</div>
<div class="form-group">
<label for="phone">Телефон</label>
<input type="text" class="form-control @error('phone') is-invalid @enderror" name="phone" value="{{ old('phone', $pharmacy->phone) }}" placeholder="Телефон">
@error('phone')
<div class="invalid-feedback">{{ $message }}</div>
@enderror
</div>
<div class="form-group">
<label for="work_hours">Часы работы</label>
<div class="row">
<div class="col">
<input type="time" class="form-control @error('work_start') is-invalid @enderror" name="work_start" value="{{ old('work_start', substr($pharmacy->work_start, 0, -3)) }}" placeholder="Начало работы">
@error('work_start')
<div class="invalid-feedback">{{ $message }}</div>
@enderror
</div>
<div class="col">
<input type="time" class="form-control @error('work_end') is-invalid @enderror" name="work_end" value="{{ old('work_end', substr($pharmacy->work_end, 0, -3)) }}" placeholder="Окончание работы">
@error('work_end')
<div class="invalid-feedback">{{ $message }}</div>
@enderror
</div>
</div>
</div>
<div class="form-group">
<input type="submit" class="btn btn-primary" value="Обновить">
</div>
</form>
</div>
</div>
</div>
</div>
</div><!-- /.container-fluid -->
</section>
@endsection
|
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Models\Customer;
use App\Models\Location;
use App\Models\Category;
use App\Models\Item;
use App\Models\Order;
use App\Models\Setting;
use Illuminate\Support\Facades\DB;
use PDF;
class CustomerController extends Controller
{
public function store(Request $request){
$existingCustomer = Customer::where('name', $request->input('name'))->first();
if ($existingCustomer){
return back()->with('error', 'Customer already exists!');
}
else {
$data = $request->validate([
'name' => 'required|string|max:255|unique:customers,name'
]);
if(Customer::create($data)){
if($request->route()->getName() == "pos.index"){
return response()->json(['message' => "Thank you!"]);
}
else{
return back()->with('success', 'Customer Created Successfully!');
}
}
else{
return back()->with('error', 'Customer Creation Not Successful!');
}
}
}
public function index(){
$customers = Customer::orderBy('name', 'asc')
->paginate(10);
$locations = Location::all();
$categories = Category::all();
$items = Item::all();
$setting = Setting::first();
$customers = Customer::select('customers.name as name',
'customers.id as id',
DB::raw('SUM(orders.remaining_due) as total_remaining_due')) // Calculate the total remaining_due using SUM
->leftJoin('orders', 'orders.customer_id', '=', 'customers.id')
->groupBy('customers.name', 'customers.id')
->paginate(10);
return view('customers.index', compact('items', 'locations', 'categories', 'customers', 'setting'));
}
public function downloadSoa($customerId){
$customerorders = Order::getCustomerReceivables($customerId);
$pdf = PDF::loadView('customers.billing', ['customerorders' => $customerorders]);
return $pdf->download('billing_statement.pdf');
}
}
|
//
// CampusMap.swift
// Campus
//
// Created by Kha-Yu Cheam on 10/7/20.
//
import SwiftUI
import MapKit
struct CampusMap: View {
@EnvironmentObject var locationsManager: LocationsManager
@State var userMapInteractionMode: MapUserTrackingMode = .follow
@Binding var showFavorites: Bool
var shownBuildings: [Building] {
if (showFavorites) {
let favoritedBuilding = locationsManager.allBuildings.filter({ $0.favorited })
let buildingSet = Set(favoritedBuilding).union(Set(locationsManager.plottedBuildings))
return Array(buildingSet)
} else {
return locationsManager.plottedBuildings
}
}
let pinSize: CGFloat = 24
var body: some View {
Map(coordinateRegion: $locationsManager.region,
interactionModes: .all,
showsUserLocation: locationsManager.showUserLocation,
userTrackingMode: $userMapInteractionMode,
annotationItems: shownBuildings){ building in
MapAnnotation(coordinate: CLLocationCoordinate2D(latitude: building.latitude, longitude: building.longitude)){
annotationForType(for: building)
}
}
}
func annotationForType(for building: Building) -> some View {
if building.favorited {
return Image(systemName: "star.fill")
.resizable()
.foregroundColor(.yellow)
.frame(width: pinSize, height: pinSize)
} else {
return Image(systemName: "mappin.and.ellipse")
.resizable()
.foregroundColor(.blue)
.frame(width: pinSize, height: pinSize)
}
}
}
//struct CampusMap_Previews: PreviewProvider {
// @State var showFavorites: Bool = true
// static var previews: some View {
// CampusMap(showFavorites: $showFavorites)
// }
//}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Rendering;
using Microsoft.EntityFrameworkCore;
using FlightDomain.Model;
using FlightInfrastructure;
namespace FlightInfrastructure.Controllers
{
public class AirportsController : Controller
{
private readonly DbflightsContext _context;
public AirportsController(DbflightsContext context)
{
_context = context;
}
// GET: Airports
public async Task<IActionResult> Index()
{
var dbflightsContext = _context.Airports.Include(a => a.City);
return View(await dbflightsContext.ToListAsync());
}
public async Task<IActionResult> ArrivalAirport(int? id)
{
var dbflightsContext = await _context.Airports.Include(f => f.FlightArrivalAiroportNavigations).Where(a => a.Id == id).FirstOrDefaultAsync();
return View(dbflightsContext.FlightArrivalAiroportNavigations);
}
public async Task<IActionResult> DepartureAirport(int? id)
{
var dbflightsContext = await _context.Airports.Include(f => f.FlightDepartureAiroportNavigations).Where(b => b.Id == id).FirstOrDefaultAsync();
return View(dbflightsContext.FlightDepartureAiroportNavigations);
}
// GET: Airports/Details/5
public async Task<IActionResult> Details(int? id)
{
if (id == null)
{
return NotFound();
}
var airport = await _context.Airports
.Include(a => a.City)
.FirstOrDefaultAsync(m => m.Id == id);
if (airport == null)
{
return NotFound();
}
return View(airport);
}
// GET: Airports/Create
public IActionResult Create()
{
ViewData["Cities"] = new SelectList(_context.Cities, "Id", "Name");
return View();
}
// POST: Airports/Create
// To protect from overposting attacks, enable the specific properties you want to bind to.
// For more details, see http://go.microsoft.com/fwlink/?LinkId=317598.
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Create(int Id, [Bind("Id, City, Name")] Airport airport)
{
var existingAirport = await _context.Airports.FirstOrDefaultAsync(c => c.Name == airport.Name);
if (existingAirport != null)
{
ModelState.AddModelError("Name", "Аеоропорт з такою назвою вже існує.");
return View(airport);
}
City city = _context.Cities.Include(c => c.Country).FirstOrDefault(c => c.Name == airport.City.Name);
airport.City = city;
ModelState.Clear();
TryValidateModel(airport);
if (ModelState.IsValid)
{
_context.Add(airport);
await _context.SaveChangesAsync();
return RedirectToAction(nameof(Index));
}
ViewData["Cities"] = new SelectList(_context.Cities, "Id", "Name", airport.City.Name);
return View(airport);
}
// GET: Airports/Edit/5
public async Task<IActionResult> Edit(int? id)
{
if (id == null)
{
return NotFound();
}
var airport = await _context.Airports.FindAsync(id);
if (airport == null)
{
return NotFound();
}
ViewData["CityId"] = new SelectList(_context.Cities, "Id", "Name", airport.CityId);
return View(airport);
}
// POST: Airports/Edit/5
// To protect from overposting attacks, enable the specific properties you want to bind to.
// For more details, see http://go.microsoft.com/fwlink/?LinkId=317598.
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Edit(int id, [Bind("Id,CityId,Name")] Airport airport)
{
if (id != airport.Id)
{
return NotFound();
}
if (ModelState.IsValid)
{
try
{
_context.Update(airport);
await _context.SaveChangesAsync();
}
catch (DbUpdateConcurrencyException)
{
if (!AirportExists(airport.Id))
{
return NotFound();
}
else
{
throw;
}
}
return RedirectToAction(nameof(Index));
}
ViewData["CityId"] = new SelectList(_context.Cities, "Id", "Name", airport.CityId);
return View(airport);
}
// GET: Airports/Delete/5
public async Task<IActionResult> Delete(int? id)
{
if (id == null)
{
return NotFound();
}
var airport = await _context.Airports
.Include(a => a.City)
.FirstOrDefaultAsync(m => m.Id == id);
if (airport == null)
{
return NotFound();
}
return View(airport);
}
// POST: Airports/Delete/5
[HttpPost, ActionName("Delete")]
[ValidateAntiForgeryToken]
public async Task<IActionResult> DeleteConfirmed(int id)
{
var airport = await _context.Airports.FindAsync(id);
if (airport != null)
{
_context.Airports.Remove(airport);
}
await _context.SaveChangesAsync();
return RedirectToAction(nameof(Index));
}
private bool AirportExists(int id)
{
return _context.Airports.Any(e => e.Id == id);
}
}
}
|
//
// CryptoAnalyzer.swift
// Spotlight ePOS
//
// Created by Lu on 23/1/23.
//
import Foundation
import JavaScriptCore
class CryptoAnalyzer {
static let shared = CryptoAnalyzer() // treat as a singleton
private let vm = JSVirtualMachine()
private let context: JSContext
private init() {
let jsCode = try? String.init(contentsOf: Bundle.main.url(forResource: "Crypto.bundle", withExtension: "js")!)
let nativeLog: @convention(block) (String) -> Void = { message in
print("JS Log: \(message)")
}
// Create a new JavaScript context that will contain the state of our evaluated JS code.
self.context = JSContext(virtualMachine: self.vm)
// Register our native logging function in the JS context
self.context.setObject(nativeLog, forKeyedSubscript: "nativeLog" as NSString)
// Evaluate the JS code that defines the functions to be used later on.
self.context.evaluateScript(jsCode)
}
func analyze(_ message: String, _ key: String) async -> String {
let jsModule = self.context.objectForKeyedSubscript("Crypto")
let jsAnalyzer = jsModule?.objectForKeyedSubscript("Analyzer")
if let result = jsAnalyzer?.invokeMethod("analyze", withArguments: [message, key]) {
return result.toString()
}
return ""
}
}
|
# Zugriff mit SSH-Key
---
## Passwort vs. SSH-Schlüssel
- **Passwort**:
- Textbasierte Authentifizierung.
- Kann leicht erraten oder geknackt werden, wenn es schwach ist.
- **SSH-Schlüssel**:
- Kryptografisches Schlüsselpaar: öffentlicher und privater Schlüssel.
- Sicherer als ein Passwort, da es auf komplexer Kryptographie basiert.
## SSH Login
- **Keypairs wurden erstellt und heruntergeladen**
<img src="images/../../images/keypairs.png" alt="module1" style="max-width:100%;">
- **Keypairs in git bash testen**
### Key 1
ssh ubuntu@3.84.147.147 -i noah-1.pem -o ServerAliveInterval=30
<img src="images/../../images/pem1.png" alt="module1" style="max-width:100%;">
### Key 2
- **Command:** ssh ubuntu@3.84.147.147 -i noah-3.pem -o ServerAliveInterval=30
<img src="images/../../images/pem2.png" alt="module1" style="max-width:100%;">
### Instanz
### Key pairs
| Name | Instance ID | Instance State | Instance Type | Status Check | Alarm Status | Availability Zone | Public IPv4 DNS | Public IPv4 Address | Elastic IP | IPv6 IPs | Monitoring | Security Group Name | Key Name | Launch Time | Platform Details |
|--------|----------------------|----------------|---------------|-------------------|--------------|-------------------|------------------------------------------|---------------------|------------|----------|------------|---------------------|----------|-----------------------|------------------|
| kn02-b | i-0f397113bac70806d | Running | t2.micro | 2/2 checks passed | 0 in alarm | us-east-1a | ec2-3-84-147-147.compute-1.amazonaws.com | 3.84.147.147 | – | – | disabled | launch-wizard-2 | **noah-1** | 2023/09/15 10:42 GMT+2 | Linux/UNIX |
#### Reflexion
- Es geht nur mit dem ersten Key, da man mit dem gelauncht ist und somit nur mit dem sich authentifizieren. Man müsste den anderen Key also auch launchen.
|
package com.g1t11.socialmagnet.model.farm;
import com.g1t11.socialmagnet.util.TextUtils;
/**
* Represent a stealing record. Used to keep track of how many crops were
* stolen, how much xp was gained, and how much gold was gained when stealing
* from a friend's farm.
*/
public class StealingRecord {
private String cropName;
private int quantity;
private int totalXpGained;
private int totalGoldGained;
/**
* Creates an empty stealing record.
*/
public StealingRecord() {}
/**
* Creates a stealing record with specified crop, quantity, total
* experience point and gold gained.
* @param cropName The name of the crop.
* @param quantity The quantity of produced stolen.
* @param totalXpGained The total experience point gained.
* @param totalGoldGained The total gold gained.
*/
public StealingRecord(String cropName, int quantity,
int totalXpGained, int totalGoldGained) {
this.cropName = cropName;
this.quantity = quantity;
this.totalXpGained = totalXpGained;
this.totalGoldGained = totalGoldGained;
}
/**
* Creates a stealing record with specified crop and quantity.
* @param crop The name of the crop.
* @param quantity The quantity of produced stolen.
*/
public StealingRecord(Crop crop, int quantity) {
this(crop.getName(), quantity, quantity * crop.getPerUnitXp(),
quantity * crop.getSalePrice());
}
/**
* Gets the name of the crop.
* @return The name of the crop.
*/
public String getCropName() {
return cropName;
}
/**
* Sets crop name of stealing record.
* @param cropName Crop name.
*/
public void setCropName(String cropName) {
this.cropName = cropName;
}
public int getQuantity() {
return quantity;
}
/**
* Sets quantity for stealing.
* @param quantity The quantity for stealing.
*/
public void setQuantity(int quantity) {
this.quantity = quantity;
}
/**
* Gets total experience points gained.
* @return The total experience points gained.
*/
public int getTotalXpGained() {
return totalXpGained;
}
/**
* Sets total experience points gained.
* @param totalXpGained The total experience points gained.
*/
public void setTotalXpGained(int totalXpGained) {
this.totalXpGained = totalXpGained;
}
/**
* Gets the total gold gained.
* @return The total gold gained.
*/
public int getTotalGoldGained() {
return totalGoldGained;
}
/**
* Sets total gold gained.
* @param totalGoldGained Total gold gained.
*/
public void setTotalGoldGained(int totalGoldGained) {
this.totalGoldGained = totalGoldGained;
}
@Override
public String toString() {
return String.format("%s for %d XP and %d gold",
TextUtils.countedWord(quantity, cropName, cropName + "s"),
totalXpGained,
totalGoldGained);
}
}
|
<template>
<div>
<Sidebar />
<div class="main-content">
<TopNav />
<div class="container-fluid">
<div class="row justify-content-center">
<div class="col-12 col-lg-10 col-xl-8">
<!-- Header -->
<div class="header mt-md-5">
<div class="header-body">
<div class="row align-items-center">
<div class="col">
<!-- Pretitle -->
<h6 class="header-pretitle">Productos</h6>
<!-- Title -->
<h1 class="header-title">Nuevo producto</h1>
</div>
</div>
<!-- / .row -->
<div class="row align-items-center">
<div class="col">
<!-- Nav -->
<ul class="nav nav-tabs nav-overflow header-tabs">
<router-link class="nav-link" to="/producto">
Todos los producto
</router-link>
<li class="nav-item">
<a class="nav-link active">Nuevo producto</a>
</li>
</ul>
</div>
</div>
</div>
</div>
<div class="mb-7">
<div class="row justify-content-between align-items-center">
<div class="col">
<div class="row align-items-center">
<div class="col-auto">
<!-- Avatar -->
<div class="avatar">
<img
class="avatar-img rounded-circle"
:src="str_image"
alt="..."
/>
</div>
</div>
<div class="col ms-n2">
<!-- Heading -->
<h4 class="mb-1">
<b>Portada</b>
</h4>
<!-- Text -->
<small class="text-muted">
PNG or JPG no bigger than 1000px wide and tall.
</small>
</div>
</div>
<!-- / .row -->
</div>
<div class="col-auto">
<!-- Button -->
<label for="file-upload" class="btn btn-sm btn-primary">
Upload
</label>
<input
style="display: none"
id="file-upload"
type="file"
v-on:change="uploadImage($event)"
/>
</div>
</div>
<!-- / .row -->
<!-- Divider -->
<hr class="my-5" />
<div class="row">
<div class="col-12 col-md-12">
<!-- Email address -->
<div class="form-group">
<!-- Label -->
<label class="mb-1"> Título del producto </label>
<!-- Form text -->
<small class="form-text text-muted">
This contact will be shown to others publicly, so choose
it carefully.
</small>
<!-- Input -->
<input
type="text"
class="form-control"
placeholder="Título del producto"
v-model="producto.titulo"
/>
</div>
</div>
<div class="col-12 col-md-6">
<!-- First name -->
<div class="form-group">
<!-- Label -->
<label class="form-label"> Categoria </label>
<!-- Form text -->
<small class="form-text text-muted">
This contact will be shown to others publicly, so choose
it carefully.
</small>
<!-- Input -->
<select
name=""
class="form-select"
v-model="producto.categoria"
>
<option value="" disabled selected>Seleccionar</option>
<option :value="item" v-for="item in $categorias">
{{ item }}
</option>
</select>
</div>
</div>
<div class="col-12 col-md-6">
<!-- First name -->
<div class="form-group">
<!-- Label -->
<label class="form-label"> SubCategoria </label>
<!-- Form text -->
<small class="form-text text-muted">
This contact will be shown to others publicly, so choose
it carefully.
</small>
<!-- Input -->
<select
name=""
class="form-select"
v-model="producto.subcategoria"
>
<option value="" disabled selected>Seleccionar</option>
<option :value="item" v-for="item in subcategorias">
{{ item }}
</option>
</select>
</div>
</div>
<div class="col-12 col-md-6">
<!-- Last name -->
<div class="form-group">
<!-- Label -->
<label class="form-label"> Variedad </label>
<!-- Input -->
<input
type="text"
class="form-control"
placeholder="Titulo de la variedad"
v-model="producto.str_variedad"
/>
</div>
</div>
<div class="col-12 col-md-6">
<!-- Last name -->
<div class="form-group">
<!-- Label -->
<label class="form-label"> Precio </label>
<!-- Input -->
<input
type="number"
class="form-control"
placeholder="Precio"
disabled
value="0"
/>
</div>
</div>
<div class="col-12 col-md-12">
<!-- Phone -->
<div class="form-group">
<!-- Label -->
<label class="form-label"> Extracto </label>
<!-- Input -->
<textarea
class="form-control"
id=""
rows="3"
placeholder="Extracto"
v-model="producto.extracto"
></textarea>
</div>
</div>
</div>
<!-- / .row -->
<div class="row">
<div class="col-12 col-md-6">
<!-- Public profile -->
<div class="form-group">
<!-- Label -->
<label class="mb-1"> Producto publicado </label>
<!-- Form text -->
<small class="form-text text-muted">
Making your profile public means that anyone on the
Dashkit network will be able to find you.
</small>
<div class="row">
<div class="col-auto">
<!-- Switch -->
<div class="form-check form-switch">
<input
class="form-check-input"
type="checkbox"
id="switchOne"
v-model="producto.estado"
/>
<label
class="form-check-label"
for="switchOne"
></label>
</div>
</div>
<div class="col ms-n2">
<!-- Help text -->
<small class="text-muted"> Borrador activado </small>
</div>
</div>
<!-- / .row -->
</div>
</div>
<div class="col-12 col-md-6">
<!-- Allow for additional Bookings -->
<div class="form-group">
<!-- Label -->
<label class="mb-1"> En descuento </label>
<!-- Form text -->
<small class="form-text text-muted">
If you are available for hire outside of the current
situation, you can encourage others to hire you.
</small>
<div class="row">
<div class="col-auto">
<!-- Switch -->
<div class="form-check form-switch">
<input
class="form-check-input"
type="checkbox"
id="switchTwo"
v-model="producto.descuento"
/>
<label
class="form-check-label"
for="switchTwo"
></label>
</div>
</div>
<div class="col ms-n2">
<!-- Help text -->
<small class="text-muted">
Descuento desactivado
</small>
</div>
</div>
<!-- / .row -->
</div>
</div>
</div>
<!-- / .row -->
<!-- Divider -->
<hr class="mt-4 mb-5" />
<!-- Button -->
<button class="btn btn-primary" v-on:click="validar()">
Crear producto
</button>
</div>
</div>
</div>
<!-- / .row -->
</div>
</div>
</div>
</template>
<script>
import axios from "axios";
export default {
name: "CreateProductoApp",
components: {
Sidebar: () => import("@/components/Sidebar.vue"),
TopNav: () => import("@/components/TopNav.vue"),
},
data() {
return {
str_image: "/assets/img/avatar-1.jpg",
producto: {
categoria: "",
estado: false,
descuento: false,
portada: undefined,
subcategoria: "",
},
subcategorias: ["Hombres", "Mujeres", "Accesorios"],
portada: undefined,
};
},
methods: {
uploadImage($event) {
var image;
if ($event.target.files.length >= 1) {
image = $event.target.files[0];
}
console.log(image);
if (image.size <= 1000000) {
if (
image.type == "image/jpeg" ||
image.type == "image/png" ||
image.type == "image/webp" ||
image.type == "image/jpg"
) {
this.str_image = URL.createObjectURL(image);
this.portada = image;
this.producto.portada = this.portada;
} else {
this.$notify({
group: "foo",
title: "ERROR",
text: "El recurso debe ser imagen.",
type: "error",
});
this.portada = undefined;
}
} else {
this.$notify({
group: "foo",
title: "ERROR",
text: "La imagen debe pesar menos de 1MB",
type: "error",
});
this.portada = undefined;
}
},
validar() {
if (!this.producto.titulo) {
this.$notify({
group: "foo",
title: "ERROR",
text: "Ingrese el titulo del producto",
type: "error",
});
} else if (!this.producto.categoria) {
this.$notify({
group: "foo",
title: "ERROR",
text: "Seleccione la categoria del producto",
type: "error",
});
} else if (!this.producto.subcategoria) {
this.$notify({
group: "foo",
title: "ERROR",
text: "Seleccione la categoria del producto",
type: "error",
});
} else if (!this.producto.extracto) {
this.$notify({
group: "foo",
title: "ERROR",
text: "Ingrese el extracto del producto",
type: "error",
});
} else if (!this.producto.str_variedad) {
this.$notify({
group: "foo",
title: "ERROR",
text: "Ingrese el variedad del producto",
type: "error",
});
} else if (this.producto.portada == undefined) {
this.$notify({
group: "foo",
title: "ERROR",
text: "Selecciona una imagen de portada",
type: "error",
});
} else {
this.registro();
}
},
registro() {
var fm = new FormData();
fm.append("titulo", this.producto.titulo);
fm.append("categoria", this.producto.categoria);
fm.append("subcategoria", this.producto.subcategoria);
fm.append("extracto", this.producto.extracto);
fm.append("estado", this.producto.estado);
fm.append("str_variedad", this.producto.str_variedad);
fm.append("descuento", this.producto.descuento);
fm.append("portada", this.producto.portada); //IMAGEN
axios
.post(this.$url + "/registro_producto_admin", fm, {
headers: {
"Content-Type": "multipart/form-data",
Authorization: this.$store.state.token,
},
})
.then((result) => {
if (result.data.message) {
this.$notify({
group: "foo",
title: "ERROR",
text: result.data.message,
type: "error",
});
} else {
this.$notify({
group: "foo",
title: "SUCCESS",
text: "Se registro correctamente el producto.",
type: "success",
});
this.$router.push({ name: "producto-index" });
}
});
},
},
};
</script>
|
Операции состоят из самой операции + - ** и операндов к которым применяется операыия
3 + 7; // infix операции
+4; // prefix
$i++; // postfix
Операции Унарные Бинарные Тринарные. Унарная - только 1 операнд.
Приоритет
3 * 4 - 1;
3 * (4 - 1);
Функции
sqrt(4); // 2
sin(0); // 0
cos(pi()); // -1
Функции принимают на вход аргументы именно как выражения
sqrt(2 ** 4);
sin(deg2rad(90)); // 1
Операции это просто запись функций в infix форме. 2 ** 2 = **(2, 2)
ЗАДАНИЕ
Выведите на экран значение следующих выражений:
Произведение двух подвыражений, одно из которых это семь во второй степени,
а второе это разность между остатком от деления ста на три и цифрой пять.
echo (7 ** 2) * (100 % 3 - 5);
Квадратный корень из суммы двух подвыражений, одно из которых это
косинус pi радиан, а вторая это синус девяноста градусов.
echo sqrt(cos(pi()) + sin(deg2rad(90)));
|
Problem Number: 2054
Problem Name: Two Best Non-Overlapping Events
Link: https://leetcode.com/problems/kth-distinct-string-in-an-array/
Question
You are given a 0-indexed 2D integer array of events where events[i] = [startTimei, endTimei, valuei]. The ith event starts at startTimei and ends at endTimei, and
if you attend this event, you will receive a value of valuei. You can choose at most two non-overlapping events to attend such that the sum of their values is maximized.
Return this maximum sum.
Note that the start time and end time is inclusive: that is, you cannot attend two events where one of them starts and the other ends at the same time. More
specifically, if you attend an event with end time t, the next event must start at or after t + 1.
Video Link: 1. https://www.youtube.com/watch?v=KruCyeofUo8 (APPROACH 1)
2. https://www.youtube.com/watch?v=DQbfHqzgasU (APPROACH 2)
3. https://youtu.be/Nhvf_hmDa6I?t=1255 (APPROACH 3)
4. https://youtu.be/Nhvf_hmDa6I?t=2612 (APPROACH 4)
Solution
Time Complexity: O(N * (log(N)), where N is the total number of events
Space Complexity: O(N), where N is the total number of events
APPROACH 1
// SORTING START TIMES OF THE EVENT AND APPLYING BINARY SEARCH
class Solution {
public:
int maxTwoEvents(vector<vector<int>>& events) {
int n = events.size();
// Time Complexity: O(N * log(N))
// sorting in increasing order of starting time
sort(events.begin(), events.end(), [](vector<int> &a, vector<int> &b){
// sorting in increasing start times when both are not equal
if(a[0] != b[0]){
return a[0] < b[0];
}
// sorting in increasing end times when both start times are equal
else{
return a[1] < b[1];
}
});
// Time Complexity: O(N)
/* stores the max score if we have to select a job from the given interval. As here starting times are sorted, we will find the interval where the end time
for a job is smaller than the smallest starting time of the job in the interval. When we will find the interval we can choose any job we want. So, we will
find the job which gives max score. The interval will mostly end at last element as we sorted the starting times. Therefore, max score will be calculated using
suffix max
*/
vector<int> max_score(n);
max_score[n-1] = events[n-1][2];
for(int i=n-2; i>=0; i--){
max_score[i] = max(max_score[i+1], events[i][2]);
}
// Time Complexity: O(N * log(N))
// we will try to find another job for every job
int ans = 0;
for(int i=0; i<n; i++){
// applying binary search to find the interval of suitable jobs
int low = i+1;
int high = n-1;
// stores the interval starting index
int p = -1;
while(low <= high){
int mid = ((high - low)/2) + low;
/* if the end time of the particular job is smaller than the starting time of job we want to select, we will store it's index and search for lower
starting times, till start time of the "mid" is smaller than or equal to end time of the job
*/
if(events[i][1] < events[mid][0]){
p = mid;
high = mid - 1;
}
// when the start time of the job we want is smaller than or equal to end time of the particular job, we will search for higher values of start times
else{
low = mid + 1;
}
}
// when we are able to find the another job for a particular job
if(p != -1){
int current = events[i][2] + max_score[p];
ans = max(ans, current);
}
// if we want to take that job only
ans = max(ans, events[i][2]);
}
// return max score we can achieve
return ans;
}
};
Time Complexity: O(N * (log(N)), where N is the total number of events
Space Complexity: O(N), where N is the total number of events
APPROACH 2
// SORTING END TIMES OF THE EVENT AND APPLYING BINARY SEARCH
class Solution {
public:
int maxTwoEvents(vector<vector<int>>& events) {
int n = events.size();
// Time Complexity: O(N * log(N))
// sorting in increasing order of ending time
sort(events.begin(), events.end(), [](vector<int> &a, vector<int> &b){
// sorting in increasing end times when both are not equal
if(a[1] != b[1]){
return a[1] < b[1];
}
// sorting in increasing start times when both end times are equal
else{
return a[0] < b[0];
}
});
// Time Complexity: O(N)
/* stores the max score if we have to select a job from the given interval. As here ending times are sorted, we will find the interval where the start time for
a job is greater than the largest ending time of the job in the interval. When we will find the interval we can choose any job we want. So, we will find the job
which gives max score. The interval will mostly start from first element as we sorted the ending times. Therefore, max score will be calculated using prefix max
*/
vector<int> max_score(n);
max_score[0] = events[0][2];
for(int i=1; i<n; i++){
max_score[i] = max(max_score[i-1], events[i][2]);
}
// Time Complexity: O(N * log(N))
// we will try to find another job for every job
int ans = 0;
for(int i=0; i<n; i++){
// applying binary search to find the interval of suitable jobs
int low = 0;
int high = i-1;
// stores the interval starting index
int p = -1;
while(low <= high){
int mid = ((high - low)/2) + low;
/* if the start time of the particular job is greater than the end time of job we want to select, we will store it's index and search for higher ending
times, till end time of the "mid" is greater than or equal to start time of the job
*/
if(events[i][0] > events[mid][1]){
p = mid;
low = mid + 1;
}
// when the end time of the job we want is greater than or equal to start time of the particular job, we will search for lower values of end times
else{
high = mid - 1;
}
}
// when we are able to find the another job for a particular job
if(p != -1){
int current = events[i][2] + max_score[p];
ans = max(ans, current);
}
// if we want to take that job only
ans = max(ans, events[i][2]);
}
// return max score we can achieve
return ans;
}
};
Time Complexity: O((N * (log(N)) + N) = O(N * (log(N)), where N is the total number of events
Space Complexity: O(N), where N is the total number of events
APPROACH 3
// SORTING START TIMES OF THE EVENT AND USING PRIORITY QUEUE
class Solution {
public:
int maxTwoEvents(vector<vector<int>>& events) {
int n = events.size();
// sorting in increasing order of starting time
sort(events.begin(), events.end());
// as priority queue is by default max heap and here we want min heap we will take negative values
priority_queue<pair<int, pair<int, int>>> pq;
int ans = 0; // stores the final answer when we consider one or two jobs
int max_value = 0; // stores the max answer when the jobs are done and we are checking whther it will help in other job or not
// for every job we will try to find the max score
for(int i=0; i<n; i++){
// from priority queue we check whether the job present has end time smaller than the starting time of current job and from all jobs which finishes before
// the particular job take max_score
while(!pq.empty() && (-1 * pq.top().first < events[i][0])){
// if yes, then we will find the max score if do the jobs present in priority queue finsihes before the particular event
max_value = max(max_value, pq.top().second.second);
pq.pop();
}
// max score achieved by the particular job
ans = max(ans, max_value + events[i][2]);
// pushing it in the priority queue for making it available for other jobs
pq.push({-1 * events[i][1], {events[i][0], events[i][2]}});
}
// return max score we can achieve
return ans;
}
};
Time Complexity: O(N * (log(N)), where N is the total number of events
Space Complexity: O(N), where N is the total number of events
APPROACH 4
// SORTING START TIMES OF THE EVENT AND USING RECURSION, DP AND BINARY SEARCH
class Solution {
public:
int func(int idx, int jobs, vector<vector<int>>& events, vector<vector<int>>& dp){
// when we have processed all events or we have done 2 jobs, then we wont go further
if(idx == events.size() || jobs == 2){
return 0;
}
if(dp[idx][jobs] != -1){
return dp[idx][jobs];
}
// finds the index which will be available after the current job is over
vector<int> vec = {events[idx][1], INT_MAX, INT_MAX};
int nextind = upper_bound(events.begin(), events.end(), vec) - events.begin();
// if we will perform this particular job
int val1 = events[idx][2] + func(nextind, jobs + 1, events, dp);
// if we dont perform this particular job
int val2 = func(idx + 1, jobs, events, dp);
// returning the max score out of both
return dp[idx][jobs] = max(val1, val2);
}
int maxTwoEvents(vector<vector<int>>& events) {
// sorting in terms of start time
sort(events.begin(), events.end());
int n = events.size();
int k = 2;
// stores the max score for all events
vector<vector<int>> dp(n, vector<int>(k, -1));
return func(0, 0, events, dp);
}
};
|
const numParticles = 100;
const particles = [];
let fieldStrength = 0.01;
let size
function setup() {
createCanvas(windowWidth, windowHeight, WEBGL);
colorMode(HSB, 360, 100, 100, 100);
size = min(width, height);
for (let i = 0; i < numParticles; i++) {
let x = random(width*0.4, width*0.6)
let y = random(height*0.4, height*0.6)
let z = random(-size*0.2, size*0.2)
particles.push(new Particle(x, y, z));
}
}
function draw() {
// background(0);
rotateX(frameCount * 0.008);
rotateY(frameCount * 0.01);
rotateZ(frameCount * 0.1);
for (let p of particles) {
const force = getFieldForce(p.pos);
p.applyForce(force);
p.update();
p.display();
p.edges();
}
fieldStrength *= 1.003
if(fieldStrength > 100) fieldStrength = 0.01
}
function getFieldForce(pos) {
const x = map(pos.x, size*0.35, size*0.65, 0, 1);
const y = map(pos.y, size*0.35, size*0.65, 0, 1);
const z = map(pos.z, -size*0.2, size*0.2, 0, 1);
const noiseValue = noise(x, y, z);
const angle = noiseValue * TWO_PI * 4;
const force = p5.Vector.fromAngle(angle);
force.mult(fieldStrength);
return force;
}
class Particle {
constructor(x, y, z) {
this.pos = createVector(x, y, z);
this.vel = createVector();
this.acc = createVector();
this.hue = map(noise(this.pos.x, this.pos.y, frameCount), 0, 1, 200, 400);
}
applyForce(force) {
this.acc.add(force);
}
update() {
this.vel.add(this.acc);
this.pos.add(this.vel);
this.acc.mult(0);
}
display() {
// noFill();
// stroke(255);
// box(size*0.5);
push();
stroke(this.hue, 20, 100, 100);
// strokeWeight(2);
translate(this.pos.x - width / 2, this.pos.y - height / 2, this.pos.z);
noFill()
box(2);
pop();
}
edges() {
if (this.pos.x > width*0.65) this.pos.x = width*0.35;
if (this.pos.x < width*0.35) this.pos.x = width*0.65;
if (this.pos.y > height*0.65) this.pos.y = height*0.35;
if (this.pos.y < height*0.35) this.pos.y = height*0.65;
if (this.pos.z > size*0.2) this.pos.z = -size*0.2;
if (this.pos.z < -size*0.2) this.pos.z = size*0.2;
}
}
|
package part2;
import java.awt.*; // for Graphics, Frame
import java.awt.event.WindowAdapter; // to close
import java.awt.event.WindowEvent; // to close
public abstract class AbstractSolution extends Frame {
// Fields
protected static final int WIDTH = 600; // initial frame dimensions
protected static final int HEIGHT = 600;
protected int depth; // recursion depth
protected int initialLength;
protected SolutionType type;
// Constructors
public AbstractSolution() {
this.setSize(WIDTH, HEIGHT);
this.setVisible(true);
this.setBackground(Color.white);
this.depth = 0;
initialLength = 0;
this.type = SolutionType.FkSolution;
addWindowListener(new WindowHandler()); // to close
setTitle("Dessins recursifs au niveau : " + depth);
}
public AbstractSolution(int depth, int length, SolutionType type) {
this.setSize(WIDTH, HEIGHT);
this.setVisible(true);
this.setBackground(Color.white);
this.depth = depth;
initialLength = length;
this.type = type;
addWindowListener(new WindowHandler()); // to close
setTitle("Dessins recursifs au niveau : " + depth);
}
private class WindowHandler extends WindowAdapter {
public void windowClosing(WindowEvent e) {
System.exit(0);
}
}
public void paint(Graphics g) {
int frameHeight = getSize().height;
int frameWidth = getSize().width;
Graphics2D g2d = (Graphics2D) g;
g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
RenderingHints.VALUE_ANTIALIAS_ON);
g2d.clearRect(0, 0, frameWidth, frameHeight);
switch (type) {
case FkSolution:
drawSolution1(g2d);
break;
case F2kSolution:
drawSolution2(g2d, frameWidth, frameHeight);
break;
case F3kSolution:
drawSolution3(g2d, frameWidth, frameHeight);
break;
case F4kSolution:
drawSolution4(g2d, frameWidth, frameHeight);
break;
default:
System.err
.println("unknown SolutionType\tpart2.AbstractSolution.paint()");
}
}
/**
* drawSolutionk call for FkSolution instances.
*
* @param g2d
* the graphic object to draw into
*/
private void drawSolution1(Graphics2D g2d) {
if (type == SolutionType.FkSolution) {
g2d.setColor(Color.magenta);
drawSolutionk(g2d, 1, getInsets().top + 1, initialLength, depth);
} else
System.err
.println("Invalid use of part2.AbstractSolution.drawSolution1(), SolutionType different of FkSolution.");
}
/**
* drawSolutionk call for F2kSolution instances.
*
* @param g2d
* the graphic object to draw into
* @param frameWidth
* the width of the frame
* @param frameHeight
* the height of the frame
*/
private void drawSolution2(Graphics2D g2d, int frameWidth, int frameHeight) {
if (type == SolutionType.F2kSolution) {
g2d.setColor(Color.green);
drawSolutionk(g2d, frameWidth / 2 - initialLength / 2, frameHeight
/ 2 - initialLength / 2, initialLength, depth,
Position.CENTER.getValue());
} else
System.err
.println("Invalid use of part2.AbstractSolution.drawSolution2(), SolutionType different of F2kSolution.");
}
/**
* drawSolutionk call for F3kSolution instances.
*
* @param g2d
* the graphic object to draw into
* @param frameWidth
* the width of the frame
* @param frameHeight
* the height of the frame
*/
private void drawSolution3(Graphics2D g2d, int frameWidth, int frameHeight) {
if (type == SolutionType.F3kSolution) {
g2d.setColor(Color.black);
drawSolutionk(g2d, frameWidth / 2 - initialLength / 2, frameHeight
/ 2 - initialLength / 2, initialLength, depth,
Position.CENTER.getValue());
} else
System.err
.println("Invalid use of part2.AbstractSolution.drawSolution3(), SolutionType different of F3kSolution.");
}
/**
* drawSolutionk call for F4kSolution instances.
*
* @param g2d
* the graphic object to draw into
* @param frameWidth
* the width of the frame
* @param frameHeight
* the height of the frame
*/
private void drawSolution4(Graphics2D g2d, int frameWidth, int frameHeight) {
if (type == SolutionType.F4kSolution) {
g2d.setColor(Color.black);
g2d.fillRect(0, 0, frameWidth, frameHeight);
g2d.setColor(Color.white);
g2d.translate(frameWidth / 2, frameHeight / 2);
drawSolutionk(g2d, -initialLength / 2, -initialLength / 2,
initialLength, depth, 1);
} else
System.err
.println("Invalid use of part2.AbstractSolution.drawSolution4(), SolutionType different of F4kSolution.");
}
/**
* Produces a recursive drawing.
*
* @param drawingArea
* the graphic object in which we draw
* @param args
* the coordinates, length and others if necessary, and recursion
* depth
*/
public abstract void drawSolutionk(Graphics2D drawingArea, int... args);
/**
* Returns a string representation of this solution and its values.
*/
public String toString() {
return type + " " + depth + " " + initialLength + " "
+ super.toString();
}
}
|
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<%@ taglib tagdir="/WEB-INF/tags" prefix="h"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/functions" prefix="fn"%>
<h:header title="Tables Management"
bodyClasses="font-sans bg-gray-100 flex min-h-screen" />
<h:adminSidebar from='TableManagementServlet' />
<main class="flex-1 p-10">
<h2 class="text-xl font-semibold mb-4 flex justify-between items-center">
Tables
<button id="addTableButton"
class="float-right bg-red-500 text-white px-4 py-2 rounded-md inline-block hover:bg-red-600 transition">
Add Table</button>
</h2>
<form action="${pageContext.request.contextPath}/TableManagementServlet" method="get">
<input type="hidden" name="page" value="${currentPage}" />
<div class="flex gap-2 mb-4 items-end">
<div class="flex flex-col gap-2 flex-1">
<label for="searchTerm">Search Term</label>
<input type="text" id="searchTerm" name="searchTerm" class="border border-gray-300 rounded-md px-2 py-1 flex-grow" value="${searchTerm}">
</div>
<div class="flex flex-col gap-2 flex-1">
<label for="searchBy">Search By</label>
<select id="searchBy" name="searchBy" class="border border-gray-300 rounded-md px-2 py-1">
<option value="all" <c:if test="${searchBy eq 'all'}">selected</c:if>>All</option>
<option value="table_name" <c:if test="${searchBy eq 'table_name'}">selected</c:if>>Table Name</option>
<option value="seat_numbers" <c:if test="${searchBy eq 'table_capacity'}">selected</c:if>>Table Capacity</option>
<option value="room_name" <c:if test="${searchBy eq 'room_name'}">selected</c:if>>Room Name</option>
</select>
</div>
<button type="submit" class="bg-red-500 text-white px-4 py-2 rounded-md inline-block hover:bg-red-600 transition flex-1 h-fit max-w-12">
Search
</button>
</div>
</form>
<%
boolean tableCreated = request.getParameter("tableCreated") != null;
boolean tableUpdated = request.getParameter("tableUpdated") != null;
boolean tableDeleted = request.getParameter("tableDeleted") != null;
if (tableCreated) {
%>
<div class='bg-green-500 w-full py-2 text-sm rounded-lg fadeUp createMsg text-white text-center font-semibold'>Table Updated</div>
<script>setTimeout(()=>{
document.querySelector('.createMsg').remove();
},4000)</script>
<%
}
else if (tableUpdated) {
%>
<div class='bg-green-500 w-full py-2 text-sm rounded-lg fadeUp updateMsg text-white text-center font-semibold'>Table Updated</div>
<script>setTimeout(()=>{
document.querySelector('.updateMsg').remove();
},4000)</script>
<%
}
else if (tableDeleted) {
%>
<div class='bg-green-500 w-full py-2 text-sm rounded-lg fadeUp deleteMsg text-white text-center font-semibold'>Table Deleted</div>
<script>setTimeout(()=>{
document.querySelector('.deleteMsg').remove();
},4000)</script>
<%
}
%>
<c:choose>
<c:when test="${empty allTables}">
<div class="text-gray-500 mb-2">No tables added.</div>
</c:when>
<c:otherwise>
<table
class="rounded min-w-full border-collapse border border-gray-200 mt-4"
style="box-shadow: -10px 0px 20px 8px rgb(0 0 0/ 7%);">
<thead class='bg-gray-200 '>
<tr class='border border-1 border-gray-300'>
<th class="p-2 text-left text-gray-500 font-medium">Table
Name</th>
<th class="p-2 text-left text-gray-500 font-medium">Table
Capacity <span class='text-xs'>(seats)</span></th>
<th class="p-2 text-left text-gray-500 font-medium">Room Name</th>
<th class="p-2 text-left text-gray-500 font-medium">Actions</th>
</tr>
</thead>
<tbody>
<c:forEach var="table" items="${allTables}" varStatus="loop">
<tr
class="border-b border-1 border-gray-300 transition hover:bg-gray-200">
<td class="p-2">${fn:escapeXml(table.name)}</td>
<td class="p-2 text-left text-gray-500 font-medium">
<c:choose>
<c:when test="${table.capacity >= 10}">
10+
</c:when>
<c:otherwise>
${table.capacity}
</c:otherwise>
</c:choose>
</td>
<td class="p-2">${fn:escapeXml(table.roomName)}</td>
<td class="p-2 flex gap-2">
<button
class="editTableButton text-blue-500 hover:text-blue-600"
data-id="${table.id}" data-name="${table.name}"
data-capacity="${table.capacity}"
data-room-id="${table.roomId}">
<i class="fas fa-edit"></i>
</button>
<button class="deleteTableButton text-red-500 hover:text-red-600" data-id="${table.id}">
<i class="fas fa-trash"></i>
</button>
</td>
</tr>
</c:forEach>
</tbody>
</table>
<!-- Pagination Controls -->
<c:if test="${totalPages > 1}">
<div class="pagination flex items-center justify-center gap-2 pt-4">
<c:forEach begin="1" end="${totalPages}" var="page">
<a href="${pageContext.request.contextPath}/TableManagementServlet?page=${page}"
class="px-4 py-2 rounded-md hover:bg-gray-300 focus:outline-none focus:bg-gray-300 ${currentPage == page ? 'bg-red-500 text-white pointer-events-none' : ''}">
${page}
</a>
</c:forEach>
</div>
</c:if>
</c:otherwise>
</c:choose>
<div id="tableModal" class="relative z-10 hidden"
aria-labelledby="modal-title" role="dialog" aria-modal="true">
<div
class="fixed inset-0 bg-gray-500 bg-opacity-75 transition-opacity modalBackdrop"></div>
<div class="fixed inset-0 z-10 w-screen overflow-y-auto">
<div
class="flex min-h-full items-end justify-center p-4 text-center sm:items-center sm:p-0">
<div
class="opacity-0 translate-y-4 sm:translate-y-0 sm:scale-95 relative transform overflow-hidden rounded-lg bg-white px-4 pb-4 pt-5 text-left shadow-xl transition-all sm:my-8 sm:w-full sm:max-w-sm sm:p-6 modalPanel">
<form id="tableForm" action="TableManagementServlet" method="post"
class="bg-white px-4 pt-5 pb-4 sm:p-6 sm:pb-4">
<input name="id" id="editInput" value="" type="hidden"/>
<div class="mb-4">
<label for="name" class="block text-gray-700 font-bold mb-2">Table
Name *:</label> <input type="text" id="name" name="name"
class="w-full border rounded-md py-2 px-3 focus:outline-none focus:border-blue-500"
placeholder="Table Name" required />
</div>
<div class="mb-4">
<label for="seatsCapacity"
class="block text-gray-700 font-bold mb-2">Table
Capacity *:</label> <select id="seatsCapacity" name="seatsCapacity"
class="w-full border rounded-md py-2 px-3 focus:outline-none focus:border-blue-500"
required>
<option disabled selected value="">Table Capacity</option>
<option value="2">2</option>
<option value="4">4</option>
<option value="6">6</option>
<option value="8">8</option>
<option value="10">10</option>
</select>
</div>
<div class="mb-4">
<label for="roomId" class="block text-gray-700 font-bold mb-2">Table
Room *:</label> <select id="roomId" name="roomId"
class="w-full border rounded-md py-2 px-3 focus:outline-none focus:border-blue-500"
required>
<option disabled selected value="">Select a room</option>
<c:forEach var="room" items="${allRooms}" varStatus="loop">
<option value="${room.id}">${room.name}</option>
</c:forEach>
</select>
</div>
<ul class='submissionErrors text-sm text-red-500 py-2'>
</ul>
<div class="flex items-center justify-between">
<button id="submitButton" type="submit"
class="bg-green-500 text-white px-4 py-2 rounded-md hover:bg-green-600 focus:outline-none">Create
Table</button>
<button type="button" id="cancelButton"
class="text-gray-500 hover:underline">Cancel</button>
</div>
</form>
</div>
</div>
</div>
</div>
</main>
<script>
document.addEventListener('DOMContentLoaded', function () {
const modal = document.getElementById('tableModal');
const modalBackdrop = modal.querySelector('.modalBackdrop');
const modalPanel = modal.querySelector('.modalPanel');
const addTableButton = document.getElementById('addTableButton');
const cancelButton = document.getElementById('cancelButton');
const tableForm = document.getElementById('tableForm');
const editTableButtons = document.querySelectorAll('.editTableButton');
const deleteTableButtons = document.querySelectorAll('.deleteTableButton');
function showModal() {
modal.classList.remove('hidden');
setTimeout(() => {
modalBackdrop.classList.add('opacity-100');
modalBackdrop.classList.remove('opacity-0');
modalPanel.classList.add('opacity-100','translate-y-0','sm:scale-100')
modalPanel.classList.remove('opacity-0','sm:translate-y-0','sm:scale-95')
}, 10);
}
function hideModal() {
modalBackdrop.classList.add('opacity-0');
modalBackdrop.classList.remove('opacity-100');
modalPanel.classList.add('opacity-0','sm:translate-y-0','sm:scale-95')
modalPanel.classList.remove('opacity-100','translate-y-0','sm:scale-100')
setTimeout(() => {
modal.classList.add('hidden');
}, 300);
}
addTableButton.addEventListener('click', function () {
tableForm.reset();
tableForm.setAttribute('action', 'create');
submitButton.textContent = 'Create Table';
showModal();
});
cancelButton.addEventListener('click', function () {
hideModal();
});
editTableButtons.forEach(button => {
button.addEventListener('click', function () {
const tableId = this.getAttribute('data-id');
const tableName = this.getAttribute('data-name');
const tableCapacity = this.getAttribute('data-capacity');
const roomId = this.getAttribute('data-room-id');
document.getElementById('editInput').value = tableId;
document.getElementById('name').value = tableName;
document.getElementById('seatsCapacity').value = tableCapacity;
document.getElementById('roomId').value = roomId;
tableForm.setAttribute('action', 'edit');
submitButton.textContent = 'Update Table';
showModal();
});
});
deleteTableButtons.forEach(button => {
button.addEventListener('click', function () {
if(window.confirm('Are you sure you want to delete this table? There might be reservations linked to this table.')){
const tableId = this.getAttribute('data-id');
deleteTable(tableId);
}
});
});
function deleteTable(tableId) {
fetch(`/reservation_system/TableManagementServlet?id=`+ tableId, {
method: 'DELETE',
headers: {
'Content-Type': 'application/json'
}
})
.then(response => {
if (!response.ok) {
pushError('Failed to delete table.');
return;
}
return response.json();
})
.then(data => {
if (data.status === 'success') {
window.location.href='${pageContext.request.contextPath}/TableManagementServlet?tableDeleted=true';
} else {
pushError(data.message);
}
})
.catch(error => {
console.error('Error:', error.message);
});
}
tableForm.addEventListener('submit', function (e) {
e.preventDefault();
const formData = new FormData(tableForm);
const data = {};
formData.forEach((value, key) => {
data[key] = value;
});
const action = tableForm.getAttribute('action');
const url = '/reservation_system/TableManagementServlet';
let method = 'POST';
if (action === 'edit') {
method = 'PUT';
}
fetch(url, {
method: method,
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify(data)
})
.then(response => response.json())
.then(data => {
if(data.status === 'success'){
if(action === 'edit')
window.location.href='${pageContext.request.contextPath}/TableManagementServlet?tableUpdated=true';
else
window.location.href='${pageContext.request.contextPath}/TableManagementServlet?tableCreated=true';
}else if(data.status === 'USER_SESSION_EXPIRED'){
window.location.href='${pageContext.request.contextPath}/LoginServlet?notLoggedIn=true';
}else{
pushError(data.message);
}
})
.catch(error => {
console.error('Error:', error);
});
});
const pushError =(msg, success=false) => {
const li = document.createElement('li');
li.innerText = msg;
li.classList.add('fadeup');
if(!success){
li.classList.add('text-red-500')
}else{
li.classList.add('text-green-500')
}
document.querySelector('.submissionErrors').appendChild(li);
setTimeout(()=>{
li.remove();
},2000)
}
});
</script>
<h:footer />
|
interface City {
id: number;
wikiDataId: string;
type: string;
city: string;
name: string;
country: string;
countryCode: string;
region: string;
regionCode: string;
regionWdId: string;
latitude: number;
longitude: number;
population: number;
}
interface Link {
rel: string;
href: string;
}
interface Metadata {
currentOffset: number;
totalCount: number;
}
export interface GeoData {
data: City[];
links: Link[];
metadata: Metadata;
}
export interface CityDetails {
data: {
id: number;
wikiDataId: string;
type: string;
city: string;
name: string;
country: string;
countryCode: string;
region: string;
regionCode: string;
elevationMeters: number;
latitude: number;
longitude: number;
population: number;
timezone: string;
distance: null | number;
deleted: boolean;
placeType: string;
}
}
|
import AdminService from "../Services/Admin";
class AdminController {
/**
* @swagger
* /admin/assign-role:
* post:
* summary: Assign a role to a user
* tags: [Admin]
* requestBody:
* required: true
* content:
* application/json:
* schema:
* type: object
* properties:
* userId:
* type: string
* description: The user ID
* roleId:
* type: string
* description: The role ID to assign
* responses:
* 200:
* description: Role assigned successfully
* 400:
* description: Bad request
* 500:
* description: Internal server error
*/
static async assignRoleToUser(req, res) {
try {
const response = await AdminService.assignRoleToUser(req);
if (response.type) {
return res.status(200).json(response);
}
return res.status(400).json(response);
} catch (err) {
return res
.status(500)
.json({
type: false,
data: null,
message: `assignRoleToUser failed: ${err}`,
});
}
}
/**
* @swagger
* /admin/remove-role:
* post:
* summary: Remove a role from a user
* tags: [Admin]
* requestBody:
* required: true
* content:
* application/json:
* schema:
* type: object
* properties:
* userId:
* type: string
* description: The user ID
* roleId:
* type: string
* description: The role ID to remove
* responses:
* 200:
* description: Role removed successfully
* 400:
* description: Bad request
* 500:
* description: Internal server error
*/
static async removeRoleFromUser(req, res) {
try {
const response = await AdminService.removeRoleFromUser(req);
if (response.type) {
return res.status(200).json(response);
}
return res.status(400).json(response);
} catch (err) {
return res
.status(500)
.json({
type: false,
data: null,
message: `removeRoleFromUser failed: ${err}`,
});
}
}
/**
* @swagger
* /admin/create-role:
* post:
* summary: Create a new role
* tags: [Admin]
* requestBody:
* required: true
* content:
* application/json:
* schema:
* type: object
* required:
* - name
* properties:
* name:
* type: string
* enum: ['user', 'support', 'finance', 'admin']
* description: The name of the role to create. Must be one of 'user', 'support', 'finance', 'admin'.
* permissions:
* type: array
* items:
* type: string
* description: An array of permissions associated with the role.
* responses:
* 201:
* description: Role created successfully
* 400:
* description: Bad request. This can occur if the role name is not one of the specified enums or required fields are missing.
* 500:
* description: Internal server error
*/
static async createRole(req, res) {
try {
const response = await AdminService.createRole(req);
if (response.type) {
return res.status(201).json(response);
}
return res.status(400).json(response);
} catch (err) {
return res
.status(500)
.json({
type: false,
data: null,
message: `createRole failed: ${err}`,
});
}
}
/**
* @swagger
* /admin/update-role:
* put:
* summary: Update an existing role
* tags: [Admin]
* parameters:
* - in: query
* name: id
* required: true
* schema:
* type: string
* description: The role ID to update
* requestBody:
* required: true
* content:
* application/json:
* schema:
* type: object
* properties:
* name:
* type: string
* description: The role name to update
* permissions:
* type: array
* items:
* type: string
* description: An array of permissions associated with the role.
* responses:
* 200:
* description: Role updated successfully
* 400:
* description: Bad request
* 500:
* description: Internal server error
*/
static async updateRole(req, res) {
try {
const response = await AdminService.updateRole(req);
if (response.type) {
return res.status(200).json(response);
}
return res.status(400).json(response);
} catch (err) {
return res
.status(500)
.json({
type: false,
data: null,
message: `updateRole failed: ${err}`,
});
}
}
/**
* @swagger
* /admin/delete-role:
* delete:
* summary: Delete a role
* tags: [Admin]
* parameters:
* - in: params
* name: id
* required: true
* schema:
* type: string
* description: The role ID to delete
* responses:
* 200:
* description: Role deleted successfully
* 400:
* description: Bad request
* 500:
* description: Internal server error
*/
static async deleteRole(req, res) {
try {
const response = await AdminService.deleteRole(req);
if (response.type) {
return res.status(200).json(response);
}
return res.status(400).json(response);
} catch (err) {
return res
.status(500)
.json({
type: false,
data: null,
message: `deleteRole failed: ${err}`,
});
}
}
/**
* @swagger
* /admin/get-roles:
* get:
* summary: Get a list of all roles
* tags: [Admin]
* responses:
* 200:
* description: A list of roles
* content:
* application/json:
* schema:
* type: array
* items:
* type: object
* properties:
* roleId:
* type: string
* description: The role ID
* roleName:
* type: string
* description: The name of the role
* 400:
* description: Bad request
* 500:
* description: Internal server error
*/
static async getRoles(req, res) {
try {
const response = await AdminService.getRoles(req);
if (response.type) {
return res.status(200).json(response);
}
return res.status(400).json(response);
} catch (err) {
return res
.status(500)
.json({
type: false,
data: null,
message: `getRoles failed: ${err}`,
});
}
}
}
export default AdminController;
|
import "./page.css";
import CommentForm from "./CommentForm";
import clientPromise from "../../../../util/data/database";
import DeleteComment from "./DeleteComment";
import EditAndDelete from "./EditAndDelete";
import VerifyTokenAndGetUserInfo from "../../../../util/helpers/VerifyTokenAndGetUserInfo";
import React from "react";
import { ObjectId } from "mongodb";
export default async function PostDetail({ params }: { params: any }) {
const db = (await clientPromise).db("voca");
const parentsID = params.postID;
const userData = await VerifyTokenAndGetUserInfo();
const result = await db
.collection("discussions")
.findOne({ _id: new ObjectId(params.postID) });
const commentData = await db
.collection("comments")
.find({ parent: new ObjectId(parentsID) })
.toArray();
return (
<>
<>
{result && (
<div className="post-detail-bg">
<div className="post-detail-container">
<div className="post-detail-delete-edit-container">
<EditAndDelete
result={result._id.toString()}
email={result.email}
userEmail={(userData as any).email}
/>
</div>
<p className="post-detail-date">
{result.updatedAt === "" ? (
<>{result.createdAt}</>
) : (
<>{result.updatedAt} Edited</>
)}
</p>
<h1 className="post-detail-header">{result.title}</h1>
<p className="post-detail-content">{result.content}</p>
<div className="commentsSection">
<p className="comments-header">Comments:</p>
{commentData.map((contentForcomment: any, index: any) => {
return (
<React.Fragment key={index}>
<p className="comments-user">
{contentForcomment.firstname}
</p>
<p className="comments-date">
{contentForcomment.createdAt}
</p>
{(userData as any).email === contentForcomment.email ? (
<DeleteComment
contentForcomment={contentForcomment._id.toString()}
/>
) : null}
<p className="comments">{contentForcomment.content}</p>
</React.Fragment>
);
})}
</div>
<CommentForm parentsID={parentsID} userData={userData} />
</div>
</div>
)}
</>
</>
);
}
|
import 'reflect-metadata'
import { CodeResponsesEnum } from '../src/types'
// @ts-ignore
import request from 'supertest'
import { app } from '../src/settings'
import { UserType } from '../src/repositores/users-db-repository'
import { userLogin } from './assets'
import { UsersService } from '../src/services/users-service'
import { SecurityType } from '../src/repositores/security-db-repository'
import mongoose from 'mongoose'
import dotenv from 'dotenv'
import { SecurityService } from '../src/services/security-service'
import { container } from '../src/composition-root'
dotenv.config()
const dbName = 'hw'
const mongoURI = process.env.mongoURI || `mongodb://0.0.0.0:27017/${dbName}`
describe('/secure', () => {
const usersService = container.resolve(UsersService)
const securityService = container.resolve(SecurityService)
let sessions: SecurityType[]
let cookie_1: string[]
let cookie_2: string[]
let cookie_3: string[]
let cookie_4: string[]
let user: UserType | null
let sessions2: SecurityType[]
let cookie2: string[]
let user2: UserType | null
beforeAll(async () => {
/* Connecting to the database before each test. */
await mongoose.connect(mongoURI)
await request(app).delete('/testing/all-data').expect(204)
})
afterAll(async () => {
/* Closing database connection after each test. */
await mongoose.connection.close()
})
describe('POST auth/registration', () => {
it('+ POST registration', async function () {
await request(app)
.post('/auth/registration')
.send({
login: 'admin',
password: 'admin123',
email: 'margokomilfo.dek@gmail.com',
})
.expect(CodeResponsesEnum.Not_content_204)
user = await usersService.getUserByLoginOrEmail('margokomilfo.dek@gmail.com')
})
it('+ POST registration', async function () {
await request(app)
.post('/auth/registration')
.send({
login: 'margo',
password: 'margo123456',
email: 'margokomilfo@gmail.com',
})
.expect(CodeResponsesEnum.Not_content_204)
user2 = await usersService.getUserByLoginOrEmail('margokomilfo@gmail.com')
})
})
describe('POST auth/registration-confirmation', () => {
it('+ POST correct code', async function () {
await request(app)
.post('/auth/registration-confirmation')
.send({ code: user!.confirmationData.code })
.expect(CodeResponsesEnum.Not_content_204)
})
it('+ POST correct code', async function () {
await request(app)
.post('/auth/registration-confirmation')
.send({ code: user2!.confirmationData.code })
.expect(CodeResponsesEnum.Not_content_204)
})
})
describe('POST auth/login', () => {
it('+ POST login user', async function () {
const { _cookie } = await userLogin(
{ loginOrEmail: 'admin', password: 'admin123' },
'Chrome'
)
cookie_1 = _cookie
user = await usersService._getUserById(user!.id)
sessions = await securityService.getSessionsByUserId(user!.id)
expect(sessions.length).toBe(1)
})
it('+ POST login user', async function () {
const { _cookie } = await userLogin(
{ loginOrEmail: 'admin', password: 'admin123' },
'iMac'
)
cookie_2 = _cookie
user = await usersService._getUserById(user!.id)
sessions = await securityService.getSessionsByUserId(user!.id)
expect(sessions.length).toBe(2)
})
it('+ POST login user', async function () {
const { _cookie } = await userLogin(
{ loginOrEmail: 'admin', password: 'admin123' },
'iPhone'
)
cookie_3 = _cookie
user = await usersService._getUserById(user!.id)
sessions = await securityService.getSessionsByUserId(user!.id)
expect(sessions.length).toBe(3)
})
it('+ POST login user', async function () {
const { _cookie } = await userLogin(
{ loginOrEmail: 'admin', password: 'admin123' },
'Other'
)
cookie_4 = _cookie
user = await usersService._getUserById(user!.id)
sessions = await securityService.getSessionsByUserId(user!.id)
expect(sessions.length).toBe(4)
})
it('+ POST login user', async function () {
const { _cookie } = await userLogin(
{ loginOrEmail: 'margo', password: 'margo123456' },
'Other'
)
cookie2 = _cookie
user2 = await usersService._getUserById(user2!.id)
sessions2 = await securityService.getSessionsByUserId(user2!.id)
expect(sessions2.length).toBe(1)
})
})
describe('GET devices', () => {
it('GET devices', async () => {
const res = await request(app)
.get('/security/devices')
.set('User-Agent', 'Chrome')
.set('Cookie', cookie_1!)
.expect(CodeResponsesEnum.Success_200)
expect(res.body.length).toBe(4)
})
})
describe('POST auth/refresh-token', () => {
it('+ POST returned newAccessToken and newRefreshToken authorized', async function () {
const response = await request(app)
.post('/auth/refresh-token')
.set('Cookie', cookie_1!)
.send({})
.expect(CodeResponsesEnum.Success_200)
cookie_1 = response.get('Set-Cookie')
expect(response.body.accessToken).toBeDefined()
})
})
describe('POST auth/logout', () => {
it('+ POST logout', async function () {
await request(app)
.post('/auth/logout')
.set('Cookie', cookie_4!)
.send({})
.expect(CodeResponsesEnum.Not_content_204)
user = await usersService._getUserById(user!.id)
sessions = await securityService.getSessionsByUserId(user!.id)
expect(sessions.length).toBe(3)
})
})
describe('DELETE session', () => {
it('- DELETE session with not correct deviceId', async () => {
await request(app)
.delete('/security/devices/1234')
.set('Cookie', cookie_1!)
.expect(CodeResponsesEnum.Not_found_404)
})
it('- DELETE session with not correct deviceId', async () => {
await request(app)
.delete('/security/devices/' + sessions2[0]!.deviceId)
.set('Cookie', cookie_1!)
.expect(CodeResponsesEnum.Forbidden_403)
})
it('+ DELETE session with correct deviceId', async () => {
await request(app)
.delete('/security/devices/' + sessions[2]!.deviceId)
.set('Cookie', cookie_1!)
.expect(CodeResponsesEnum.Not_content_204)
const res = await request(app)
.get('/security/devices')
.set('User-Agent', 'Chrome')
.set('Cookie', cookie_1!)
.expect(CodeResponsesEnum.Success_200)
expect(res.body.length).toBe(2)
})
})
describe('DELETE sessions', () => {
it('+ DELETE all sessions without current', async () => {
await request(app)
.delete('/security/devices')
.set('Cookie', cookie_1!)
.expect(CodeResponsesEnum.Not_content_204)
const res = await request(app).get('/security/devices').set('Cookie', cookie_1!)
expect(res.body.length).toBe(1)
})
})
})
|
//
// MaximumSubarray.swift
// Algorithms
//
// Created by Richard Ash on 4/27/17.
// Copyright © 2017 Richard. All rights reserved.
//
import Foundation
func findMaximumSubarray<T: Number>(_ array: [T]) -> (low: Int, high: Int, sum: T){
guard array.count > 1 else {
let sum = array.isEmpty ? T.zero: array[0]
let high = array.isEmpty ? 0: 1
return (0, high, sum)
}
var change = Array(repeating: T.zero, count: array.count-1)
for i in 1..<array.count {
change[i-1] = array[i] - array[i-1]
}
return findMaximumSubarrayR(change, low: 0, high: change.count - 1)
}
func findMaximumSubarrayR<T: Number>(_ array: [T], low: Int, high: Int) -> (low: Int, high: Int, sum: T){
guard high != low else { return (low, high, array[low]) }
let mid = (high+low)/2
let (leftLow, leftHigh, leftSum) = findMaximumSubarrayR(array, low: low, high: mid)
let (rightLow, rightHigh, rightSum) = findMaximumSubarrayR(array, low: mid+1, high: high)
let (crossLow, crossHigh, crossSum) = findMaxCrossingSubarray(array, low: low, mid: mid, high: high)
if leftSum >= rightSum && leftSum >= crossSum {
return (leftLow, leftHigh, leftSum)
} else if rightSum >= leftSum && rightSum >= crossSum {
return (rightLow, rightHigh, rightSum)
} else {
return (crossLow, crossHigh, crossSum)
}
}
func findMaxCrossingSubarray<T: Number>(_ array: [T], low: Int, mid: Int, high: Int) -> (low: Int, high: Int, sum: T) {
var leftSum = T.min
var sum = T.zero
var maxLeft = 0
for i in low...mid {
let index = mid - i
sum = sum + array[index]
if sum > leftSum {
leftSum = sum
maxLeft = index
}
}
var rightSum = T.min
sum = T.zero
var maxRight = 0
for j in mid+1...high {
sum = sum + array[j]
if sum > rightSum {
rightSum = sum
maxRight = j
}
}
return (maxLeft, maxRight, leftSum + rightSum)
}
|
import { Routes, Route } from "react-router-dom";
import HomePage from "./pages";
import CategoryDetailPage from "./pages/category_detail";
import CreateTodoPage from "./pages/create_todo";
import UpdateTodoPage from "./pages/update_todo";
import TodoDetail from "./pages/todo_detail";
import CompletedTasksPage from "./pages/completed-tasks";
import OverdueTasksPage from "./pages/overdue-tasks";
const routes = () => {
return (
<Routes>
<Route path="/" element={<HomePage />}></Route>
<Route path="/personal" element={<CategoryDetailPage />}></Route>
<Route
path="/categories/:categoryId"
element={<CategoryDetailPage />}
></Route>
<Route path="/create" element={<CreateTodoPage />}></Route>
<Route path="/update" element={<UpdateTodoPage />}></Route>
<Route path="/todo/:todoId" element={<TodoDetail />}></Route>
<Route path="/completed-tasks" element={<CompletedTasksPage />}></Route>
<Route path="/overdue-tasks" element={<OverdueTasksPage />}></Route>
</Routes>
);
};
export default routes;
|
import { Box, Container, Stack } from '@chakra-ui/react';
import React from 'react';
import { Link } from './Link';
import { Logo } from './Logo';
import SocialButton from './SocialButton';
import { FaTwitter, FaYoutube, FaInstagram, FaLinkedin } from 'react-icons/fa';
import { langStrings, LanguageUnion } from '../translations/langStrings';
import { useSiteMetadata } from '../hooks/use-site-medatadata';
import { constructPath } from '../translations/constructCommonPath';
type FooterProps = {
language: LanguageUnion;
navigationPages: {
nodes: {
slug: string;
title: string;
}[];
};
};
const Footer = ({ language, navigationPages, ...props }: FooterProps) => {
let lastPage;
let remainingPages;
if (navigationPages.nodes) {
lastPage = navigationPages.nodes[navigationPages.nodes.length - 1];
remainingPages = navigationPages.nodes.slice(0, -1);
}
const sitemetada = useSiteMetadata();
const { postsPath, tagsPath, baseLanguage } = sitemetada;
return (
<div>
<Box>
<Container
as={Stack}
maxW={'6xl'}
py={4}
spacing={4}
justify={'center'}
align={'center'}
>
<Logo />
<Stack direction={'row'} spacing={6}>
<Link to={constructPath('', language)}>
{langStrings.home_link_header[language]}
</Link>
<Link to={constructPath(postsPath, language)}>
{langStrings.all_posts_link[language]}
</Link>
<Link to={constructPath(tagsPath, language)}>
{langStrings.all_tags_link[language]}
</Link>
{/* {remainingPages &&
remainingPages.map((page) => (
<Link to={`/${page.slug}/`}>{page.title}</Link>
))}
{lastPage && (
<Link to={`/${lastPage.slug}/`}>{lastPage.title}</Link>
)} */}
</Stack>
</Container>
<Box borderTopWidth={1} borderStyle={'solid'}>
<Container
as={Stack}
maxW={'6xl'}
py={4}
direction={{ base: 'column', md: 'row' }}
spacing={4}
justify={{ base: 'center' }}
align={{ base: 'center', md: 'center' }}
>
<Stack direction={'row'} spacing={6}>
<SocialButton label={'Twitter'} to={'#'}>
<FaTwitter />
</SocialButton>
<SocialButton label={'YouTube'} to={'#'}>
<FaYoutube />
</SocialButton>
<SocialButton label={'Instagram'} to={'#'}>
<FaInstagram />
</SocialButton>
<SocialButton label={'Linkedin'} to={'#'}>
<FaLinkedin />
</SocialButton>
</Stack>
</Container>
</Box>
</Box>
</div>
);
};
export default Footer;
|
(* ::Package:: *)
BeginPackage["refl`"]
refl::usage = "refl is a collection of routines related to finding optical and physical properties of thin film optics. It includes the routines parrattR, parrattRough, matR, imdFile, imdMenu, imdIndex, imdIndexAt, imdIndexFunction."
matR::usage = "matR[nd, theta, lambda, fractionS] returns a two element list with the reflectance and transmittance of a stack of thin films on a substrate (which could be a vacuum). [At this point, the transmittance is not yet implemented.] The list nd is a list of index of refraction/thickness pairs with the substrate as the first element and the vacuum usually as the last element. The thickness of the substrate and vacuum layers should be set to zero. The argument theta is the angle of incidence and reflection measured from grazing on the vacuum side in degrees. The lambda argument is the wavelength wavelength using the same units as the layer thickness. The fractionS argument is the intensity of the s-polarized component of the incident light. This calculation is slower than using the Parratt formula if only reflection is desired."
parrattR::usage = "parrattR[nd, theta, lambda, fractionS] returns the reflectance of a stack of thin films on a substrate (which could be a vacuum). The list nd is a list of index of refraction/thickness pairs with the substrate as the first element and the vacuum usually as the last element. The thickness of the substrate and vacuum layers should be set to zero. The argument theta is the angle of incidence and reflection measured from grazing on the vacuum side in degrees. The lambda argument is the wavelength wavelength using the same units as the layer thickness. The fractionS argument is the intensity of the s-polarized component of the incident light. This calculation is faster than using the matrix formula in matR if only reflection is desired."
parrattRough::usage = "parrattRough[nd, theta, lambda, fractionS, sigma] returns the reflectance of a stack of thin films on a substrate (which could be a vacuum). The list nd is a list of index of refraction/thickness pairs with the substrate as the first element and the vacuum usually as the last element. The thickness of the substrate and vacuum layers should be set to zero. The argument theta is the angle of incidence and reflection measured from grazing on the vacuum side in degrees. The lambda argument is the wavelength wavelength using the same units as the layer thickness. The fractionS argument is the intensity of the s-polarized component of the incident light. The calculation is corrected for roughness of the top interface between the vacuum and top layer having a surface rms roughness of sigma using the Debye-Waller correction. This calculation is faster than using the matrix formula in matR if only reflection is desired."
imdFile::usage = "imdFile[] returns a list of strings of filenames with index of refraction in them."
imdMenu::usage = "imdMenu[selection] draws a menu button which returns the selected file name with index of refraction data as the value of the argument selection on return."
imdIndex::usage = "imdIndex[file] returns a list of the complex index of refraction stored in file."
imdIndexAt::usage = "imdIndexAt[file, wavelength] returns the complex index of refraction from file interpolated to the given wavelength measured in nanometers."
imdIndexFunction::usage = "imdIndexFunction[file] returns the interpolation function of the index of refraction in file."
Begin["`Private`"]
matR[nd_, theta_, lambda_, percentS_]:=Module[{rs,ts, rp, tp, ky,ki, kzi, Ci, A, B,rmats, rm, rmatp},
ky=2*Pi*Cos[theta*Pi/180]/lambda;
ki[ni_]:=2*Pi*ni/lambda;
kzi[ni_]:=Sqrt[ki[ni]^2-ky^2];
Ci[ni_, di_]:=Exp[I*kzi[ni]*di/2];
rmats[n1_, n2_, d1_, d2_]:= Module[{kz1, kz2, fs12, gs12, fs21, gs21, C1, C2},
kz1=kzi[n1];
kz2=kzi[n2];
fs12=(kz1-kz2)/(kz1+kz2);
(* Print[StringForm["fs12=``",fs12]]; *)
gs12=2kz1/(kz1+kz2);
fs21=-fs12;
gs21=2kz2/(kz1+kz2);
C1=Ci[n1,d1];
C2=Ci[n2 ,d2];
{{gs21*C1*C2-fs21*fs12*C1*C2/gs12,
fs12*C1/(gs12*C2)},
{-fs21*C2/(gs12*C1),
1/(gs12*C1*C2)}}
];
rmatp[n1_, n2_, d1_, d2_]:= Module[{kz1, kz2, fp12, gp12, fp21, gp21, C1, C2},
kz1=kzi[n1];
kz2=kzi[n2];
fp12=(n2^2*kz1-n1^2*kz2)/(n1^2*kz2+n2^2*kz1);
(* Print[StringForm["fp12=``",fp12]]; *)
gp12=2n1*n2*kz1/(n1^2*kz2+n2^2*kz1);
fp21=-fp12;
gp21=2*n1*n2*kz2/(n1^2*kz2+n2^2*kz1);
C1=Ci[n1,d1];
C2=Ci[n2, d2];
{{gp21*C1*C2-fp21*fp12*C1*C2/gp12,
fp12*C1/(gp12*C2)},
{-fp21*C2/(gp12*C1),
1/(gp12*C1*C2)}}
];
A={{1,0},{0,1}};
B=A;
(* Print[A]; *)
For[i=2, i<=Length[nd], i++,
A=rmats[nd[[i,1]], nd[[i-1,1]],nd[[i,2]],nd[[i-1,2]]].A;
B=rmatp[nd[[i,1]], nd[[i-1,1]],nd[[i,2]],nd[[i-1,2]]].B;
];
ts=1/A[[2,2]];
rs=ts*A[[1,2]];
tp=1/B[[2,2]];
rp=tp*B[[1,2]];
(* Returning the transmission is a bit subtle. I'll save that for later *)
percentS*Abs[rs]^2+(1-percentS)*Abs[rp]^2
]
parrattR[nd_, theta_, lambda_, percentS_]:=Module[{rs, rp, Si, fs, fp, k, Ci, f, Ci12},
k:=2*Pi/lambda;
Si[ni_]:=Sqrt[ni^2-Cos[theta*Pi/180]^2];
Ci[ni_, di_]:=Exp[2*I*k*Si[ni]*di];fs[n1_, n2_]:=(Si[n1]-Si[n2])/(Si[n1]+Si[n2]);
fp[n1_, n2_]:=(n2^2*Si[n1]-n1^2*Si[n2])/(n2^2*Si[n1]+n1^2*Si[n2]);
rs=0;
rp=0;
For[i=2, i<=Length[nd],i++,
f=fs[nd[[i,1]],nd[[i-1,1]]];
Ci12=Ci[nd[[i,1]],nd[[i,2]]];
rs=Ci12*(f+rs)/(1+f*rs);
f=fp[nd[[i,1]], nd[[i-1,1]]];
rp=Ci12*(f+rp)/(1+f*rp);
];
(* Print[StringForm["rs=`` rp=``",rs, rp]]; *)
percentS*Abs[rs]^2+(1-percentS)*Abs[rp]^2
]
parrattRough[nd_, theta_, lambda_, percentS_, sigma_]:=Module[{rs, rp, Si, fs, fp, k, Ci, f, Ci12, q, dbf},
k:=2*Pi/lambda;
Si[ni_]:=Sqrt[ni^2-Cos[theta*Pi/180]^2];
Ci[ni_, di_]:=Exp[2*I*k*Si[ni]*di];fs[n1_, n2_]:=(Si[n1]-Si[n2])/(Si[n1]+Si[n2]);
fp[n1_, n2_]:=(n2^2*Si[n1]-n1^2*Si[n2])/(n2^2*Si[n1]+n1^2*Si[n2]);
rs=0;
rp=0;
For[i=2, i<=Length[nd],i++,
f=fs[nd[[i,1]],nd[[i-1,1]]];
If[i==Length[nd],
q=4 Pi Re[nd[[i-1,1]]]/lambda Sin[theta*Pi/180];
f=f*Exp[-q^2 sigma^2/2];
];
Ci12=Ci[nd[[i,1]],nd[[i,2]]];
rs=Ci12*(f+rs)/(1+f*rs);
f=fp[nd[[i,1]], nd[[i-1,1]]];
If[i==Length[nd],
(* Print["f before ",f]; *)
f=f*Exp[-q^2 sigma^2/2];
(* Print["f after ", f]; *)
]; (* sigma^2/2?? *)
rp=Ci12*(f+rp)/(1+f*rp);
];
(* Print[StringForm["rs=`` rp=``",rs, rp]]; *)
percentS*Abs[rs]^2+(1-percentS)*Abs[rp]^2
]
imdFile[]:=Module[{nkLines,nkFiles},
nkFiles=Import["http://volta.byu.edu/nk","HTML"];
nkLines=StringSplit[nkFiles,"\n"];
First[StringSplit[#]]&/@ nkLines[[6;;-3]]
]
(* Read the index of refraction data from a file *)
dataList[file_String]:=Module[{nkDir="http://volta.byu.edu/nk",nkData},
nkData=Import[StringJoin[{nkDir,"/",file}],"Table"];
(* just keep the header information *)
nkData=Select[nkData,MatchQ[First[#],_Real]&];
(* convert to nm and complex numbers *)
Map[{#[[1]]/10,#[[2]]+I #[[3]]}&,nkData]
]
imdMenu[selection_]:=Module[{names},
names=imdFile[];
PopupMenu[Dynamic[selection],names]
]
imdIndex[file_String]:=Module[{data},
data=dataList[file];
Fold[If[MemberQ[Map[First,#1], First[#2]],#1,Append[#1,#2]]&,{},data]
]
imdIndexFunction[file_String]:=Module[{goodList},
goodList=imdIndex[file];
Interpolation[goodList]
]
imdIndexAt[file_String, wavelength_Real]:=Module[{ifunc},
ifunc=imdIndexFunction[file];
ifunc[wavelength]
]
End[]
EndPackage[ ]
|
package com.tonghannteng.noteapp.presentation.detail
import androidx.compose.runtime.State
import androidx.compose.runtime.mutableStateOf
import androidx.lifecycle.SavedStateHandle
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.tonghannteng.noteapp.data.model.Note
import com.tonghannteng.noteapp.data.repository.IRepository
import com.tonghannteng.noteapp.data.repository.RepositoryState
import com.tonghannteng.noteapp.navigation.Argument
import com.tonghannteng.noteapp.presentation.home.NoteUIState
import dagger.hilt.android.lifecycle.HiltViewModel
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.flow.MutableSharedFlow
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.asSharedFlow
import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.flow.flowOn
import kotlinx.coroutines.launch
import javax.inject.Inject
/**
* @author: Tonghann Teng
* @since: 1/15/24
*/
@HiltViewModel
class NoteDetailEditViewModel @Inject constructor(
private val repository: IRepository,
savedStateHandle: SavedStateHandle
) : ViewModel() {
companion object {
private const val TAG = "NoteDetailViewModel"
}
private val noteId: String? = savedStateHandle[Argument.NOTE_ID]
private var _noteDetailResult = MutableStateFlow<NoteUIState<Note>>(NoteUIState.Loading())
var noteDetailResult = _noteDetailResult.asStateFlow()
private val _eventFlow = MutableSharedFlow<UiEvent>()
var eventFlow = _eventFlow.asSharedFlow()
private val _state = mutableStateOf(Note())
val state: State<Note> = _state
init {
if (noteId == "-1") {
getNewNote()
} else {
getNoteDetail()
}
}
private fun getNewNote() {
viewModelScope.launch(Dispatchers.Main) {
repository.generateNoteId()
.flowOn(Dispatchers.IO)
.collect {
val note = Note(
id = it,
title = "Enter title...",
description = "Enter description..."
)
_state.value = note
_noteDetailResult.value = NoteUIState.Success(note)
}
}
}
private fun getNoteDetail() {
viewModelScope.launch(Dispatchers.Main) {
repository.getTodoNote()
.flowOn(Dispatchers.IO)
.collect { result ->
when (result) {
is RepositoryState.Success -> {
val noteDetail = result.data.find { it.id == noteId }
if (noteDetail == null) {
_noteDetailResult.value = NoteUIState.Error("Note ID Note Found")
} else {
_noteDetailResult.value = NoteUIState.Success(noteDetail)
_state.value = noteDetail.copy()
}
}
is RepositoryState.Failure -> {
_noteDetailResult.value = NoteUIState.Error(result.exception.toString())
}
}
}
}
}
private fun updateNote() {
viewModelScope.launch(Dispatchers.Main) {
val updateNote = _state.value
repository.updateTodoNote(note = updateNote)
.flowOn(Dispatchers.IO)
.collect { result ->
when (result) {
is RepositoryState.Success -> {
_eventFlow.emit(UiEvent.SaveNote)
}
is RepositoryState.Failure -> {
// TODO: implement error case
}
}
}
}
}
fun onEvent(event: NoteDetailEditEvent) {
when (event) {
is NoteDetailEditEvent.SaveNote -> {
updateNote()
}
is NoteDetailEditEvent.EnterTitle -> {
_state.value = _state.value.copy(
title = event.value
)
}
is NoteDetailEditEvent.EnterDescription -> {
_state.value = _state.value.copy(
description = event.value
)
}
}
}
sealed class UiEvent {
data object SaveNote : UiEvent()
}
}
|
import { NumberSymbol } from '@angular/common';
import { Component } from '@angular/core';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css'],
})
export class AppComponent {
password = '';
disabled = true;
// above is the same as
/* constructor() {
this.password = '';
} */
length = 0;
includeLetters = false;
includeNumbers = false;
includeSymbols = false;
onChangeLength(value: string) {
const parsedLength = parseInt(value);
console.log(`Parsed length is ${parsedLength}`);
if (!isNaN(parsedLength)) {
this.length = parsedLength;
} else {
this.length = 0;
}
console.log(`Length is ${this.length}`);
}
onButtonClick() {
console.log(`About to generate a password with the following:
Letters: ${this.includeLetters}
Numbers: ${this.includeNumbers}
Symbols: ${this.includeSymbols}
Length: ${this.length}
`);
const letters = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
const numbers = '0123456789';
const symbols = '!@#$%^&*()';
let validChars = '';
if (this.includeLetters) {
validChars += letters;
}
if (this.includeNumbers) {
validChars += numbers;
}
if (this.includeSymbols) {
validChars += symbols;
}
let generatedPassword = '';
for (let i = 0; i < this.length; i++) {
const ltrIdx = Math.round(Math.random() * validChars.length) + 1;
generatedPassword += validChars[ltrIdx];
}
this.password = generatedPassword;
}
getPassword() {
return this.password;
}
onChangeUseLetters() {
this.includeLetters = !this.includeLetters;
}
onChangeUseNumbers() {
this.includeNumbers = !this.includeNumbers;
}
onChangeUseSymbols() {
this.includeSymbols = !this.includeSymbols;
}
}
|
"""
CS3640 | Fall 2021 | Assignment 3
BGP Routing Tables and Identifying BGP Hijacks
ParseUpdates.py
---------------
The class in this file contains methods to parse BGP MRT files that contain
route announcements and withdrawals from peer ASes. You will need to
implement methods to read a supplied MRT file and extract specific information
about announced and withdrawn routes. You will then use this information to
build your routing table.
"""
from os import times
import mrtparse
import json
import time
import logging
class ParseUpdates:
"""
Class for parsing updates recorded in BGP MRT dumps.
"""
def __init__(self, filename):
"""
:param filename: This is the MRT file to be parsed by the methods in
this class. Sample files can be found in `./data/`.
self.announcements and self.withdrawals are dictionaries that are keyed
by timestamps and contain the list of all BGP route announcements and
withdrawals at each timestamp.
self.n_announcements and self.n_withdrawals are the number of route
announcements and withdrawals observed in the supplied MRT file.
You will update all these parameters as you complete checkpoints 1 & 2.
"""
self.filename = filename
self.announcements, self.withdrawals = {}, {}
self.n_announcements, self.n_withdrawals = 0, 0
self.time_to_parse = 0
def parse_updates(self):
"""
Checkpoint ID: 1 [1 point]
In this function, you will read an MRT file using the `mrtparse` library.
For each update in the MRT file, you will need to parse the timestamp,
the peer_as that shared the update, and the bgp message containing the
updates. You will then call the `__parse_announcement_updates` and
`__parse_withdrawal_updates` methods with these parameters.
:return: True if parsing was completed successfully. False otherwise.
"""
start_time = time.time()
###
# fill in your code here
###
# get data from mrtparse
for update in mrtparse.Reader(self.filename):
# parse the update
timestamp = update.data['timestamp'][0]
peer_as = update.data['peer_as']
bgp_message = update.data['bgp_message'] # bgp_message dict
# run the appropriate functions
self.__parse_announcement_updates(timestamp, peer_as, bgp_message)
self.__parse_withdrawal_updates(timestamp, peer_as, bgp_message)
# python3 Tests.py -cp 1
###
self.time_to_parse = time.time() - start_time
logging.info("Time taken to parse all records: %s second(s)" %
self.time_to_parse)
logging.info("Routes announced: %s | Routes withdrawn: %s" %
(self.n_announcements, self.n_withdrawals))
return True
def __parse_announcement_updates(self, timestamp, peer_as, bgp_message):
"""
Checkpoint ID: 1 [1 points]
In this function, you will take a timestamp, peer_as, and bgp_message as
input and then do the following:
- increment n_announcements by the number of announced routes contained
in bgp_message.
- extract the advertised destination ip ranges from bgp_message.
- extract the advertised AS path and next hop information from the bgp
attributes in bgp_message.
- create a dictionary named `update` which has the following keys
populated by the data you just extracted: timestamp, range (this
is the advertised CIDR IP address range being announced), next_hop,
peer_as, and as_path.
- update the `self.announcements` attribute with this new record.
`self.announcements` is a dictionary of lists keyed by `timestamp`.
There will be multiple messages for a single timestamp, so
make sure that you aren't overwriting any existing entries
when you should be appending to the already existing entries
instead.
:param timestamp: Timestamp obtained from the BGP header.
:param peer_as: Peer AS obtained from the BGP header.
:param bgp_message: BGP message containing all updates.
:return: True if announcements were properly recorded. False otherwise.
"""
###
# fill in your code here
###
dest_ip_range = bgp_message['nlri']
next_hop, as_path = None, None
if len(bgp_message['path_attributes']) > 2: # hacky!
next_hop = bgp_message['path_attributes'][2]
as_path = bgp_message['path_attributes'][1]
out = []
for pre in dest_ip_range:
update = {
"timestamp": timestamp,
"range": pre,
"next_hop": next_hop,
"peer_as": peer_as,
"as_path": as_path
}
out.append(update)
if not (timestamp in self.announcements):
self.announcements[timestamp] = []
self.announcements[timestamp] = self.announcements[timestamp] + out
self.n_announcements += len(dest_ip_range)
# python3 Tests.py -cp 1
###
return True
def __parse_withdrawal_updates(self, timestamp, peer_as, bgp_message):
"""
Checkpoint ID: 1 [1 points]
In this function, you will take a timestamp, peer_as, and bgp_message as
input and then do the following:
- increment n_withdrawals by the number of withdrawn routes contained
in bgp_message.
- create a dictionary named `update` which has the following keys
populated by the data you just extracted: timestamp, range (this
is the advertised CIDR IP address range being announced),
peer_as, and as_path.
- update the `self.withdrawals` attribute with this new record.
`self.withdrawals` is a dictionary of lists keyed by `timestamp`.
There will be multiple messages for a single timestamp, so
make sure that you aren't overwriting any existing entries
when you should be appending to the already existing entries
instead.
:param timestamp: Timestamp obtained from the BGP header.
:param peer_as: Peer AS obtained from the BGP header.
:param bgp_message: BGP message containing all updates.
:return: True if announcements were properly recorded. False otherwise.
"""
###
# fill in your code here
###
withdrawn_routes = bgp_message['withdrawn_routes']
out = []
for pre in withdrawn_routes:
update = {
"timestamp": timestamp,
"range": pre,
"peer_as": peer_as,
}
out.append(update)
if not (timestamp in self.withdrawals):
self.withdrawals[timestamp] = []
self.withdrawals[timestamp] = self.withdrawals[timestamp] + out
self.n_withdrawals += len(bgp_message['withdrawn_routes'])
# python3 Tests.py -cp 1
###
return True
def get_next_updates(self):
"""
You do not need to implement anything in this method.
This method simply yields the next collection of announcements and
withdrawals when called. Records yielded are sorted by time.
:return:
"""
timestamps = sorted(
list(set(self.announcements.keys()).union(set(self.withdrawals.keys()))))
for timestamp in timestamps:
update_record = {'announcements': [],
'withdrawals': [], 'timestamp': timestamp}
if timestamp in self.announcements.keys():
update_record['announcements'] = self.announcements[timestamp]
if timestamp in self.withdrawals.keys():
update_record['withdrawals'] = self.withdrawals[timestamp]
yield update_record
yield {'announcements': [], 'withdrawals': [], 'timestamp': None}
def to_json_helper_function(self, destination_json):
"""
This is a helper function that converts the MRT file saved in
`self.filename` to a JSON file and saves it to disk.
:param destination_json: The location at which to save the converted
JSON file.
"""
records = []
for entry in mrtparse.Reader(self.filename):
records.append(entry.data)
with open(destination_json, "w") as fp:
json.dump(obj=records, fp=fp, indent=2, sort_keys=False)
def main():
pu = ParseUpdates(filename="./data/updates.20080219.0015.bz2")
pu.parse_updates()
pu.to_json_helper_function("./sample-mrt-in-json.json")
logging.info("Time taken to parse all records: %s second(s)" % pu.time_to_parse)
logging.info("Routes announced: %s | Routes withdrawn: %s" % (pu.n_announcements, pu.n_withdrawals))
updates = pu.get_next_updates()
while True:
next_updates = next(updates)
if next_updates['timestamp'] is None:
logging.info("No more updates to process in file: %s" %
pu.filename)
break
else:
logging.info("At timestamp: %s | %s announcements | %s withdrawals" % (next_updates['timestamp'],
len(
next_updates['announcements']),
len(next_updates['withdrawals'])))
if __name__ == '__main__':
main()
|
package micro
import (
"strings"
"time"
"github.com/avast/retry-go"
"github.com/pkg/errors"
)
var retryDelayTypeMap = map[string]retry.DelayTypeFunc{
"BackOff": retry.BackOffDelay,
"Fixed": retry.FixedDelay,
"Random": retry.RandomDelay,
}
var retryRetryIfMap = map[string]retry.RetryIfFunc{}
func RegisterRetryDelayTypeFunc(key string, delayTypeFunc retry.DelayTypeFunc) {
retryDelayTypeMap[key] = delayTypeFunc
}
func RegisterRetryRetryIf(key string, retryIfFunc retry.RetryIfFunc) {
retryRetryIfMap[key] = retryIfFunc
}
type RetryOptions struct {
Attempts uint `dft:"3"`
// 重试间隔,当 DelayType == Fixed || DelayType == BackOff 时有效
Delay time.Duration `dft:"1s"`
// 最大重试间隔时间
MaxDelay time.Duration `dft:"3m"`
// 随机重试间隔,当 DelayType == Random 时有效
MaxJitter time.Duration `dft:"1s"`
LastErrorOnly bool
// Fixed: 固定重试间隔为 Delay
// BackOff: 以 Delay 为基础,重试间隔指数增长,Delay, Delay >> 1, Delay >> 2
// Random: 重试间隔为 (0, MaxJitter) 中的一个随机值
// Fixed,Random: 重试间隔 (Delay, Delay + MaxJitter) 中的一个随机值
DelayType string `dft:"BackOff"`
// 使用定义在 retryRetryIfMap 中的 retryIf 方法
// 默认重试非 retry.Unrecoverable 的所有错误
RetryIf string
}
type Retry struct {
OnRetry retry.OnRetryFunc
RetryIf retry.RetryIfFunc
DelayType retry.DelayTypeFunc
options *RetryOptions
}
func NewRetryWithOptions(options *RetryOptions) (*Retry, error) {
delayType, err := parseDelayType(options.DelayType)
if err != nil {
return nil, errors.Wrap(err, "NewRetry failed")
}
r := &Retry{
options: options,
DelayType: delayType,
}
if options.RetryIf != "" {
if retryIf, ok := retryRetryIfMap[options.RetryIf]; ok {
r.RetryIf = func(err error) bool {
if !retry.IsRecoverable(err) {
return false
}
return retryIf(err)
}
} else {
return nil, errors.Errorf("unsupported retryIf [%v] func", options.RetryIf)
}
}
return r, nil
}
func parseDelayType(dt string) (retry.DelayTypeFunc, error) {
if dt == "" {
return nil, nil
}
vs := strings.Split(dt, ",")
if len(vs) == 1 {
if delayType, ok := retryDelayTypeMap[dt]; ok {
return delayType, nil
}
return nil, errors.Errorf("unsupported delayType [%v]", dt)
}
var funs []retry.DelayTypeFunc
for _, v := range vs {
fun, err := parseDelayType(strings.TrimSpace(v))
if err != nil {
return nil, err
}
funs = append(funs, fun)
}
return retry.CombineDelay(funs...), nil
}
func (r *Retry) Do(fun func() error) error {
var opts []retry.Option
if r.options.Attempts != 0 {
opts = append(opts, retry.Attempts(r.options.Attempts))
}
if r.options.Delay != 0 {
opts = append(opts, retry.Delay(r.options.Delay))
}
if r.options.MaxDelay != 0 {
opts = append(opts, retry.MaxDelay(r.options.MaxDelay))
}
if r.options.MaxJitter != 0 {
opts = append(opts, retry.MaxJitter(r.options.MaxJitter))
}
if r.options.LastErrorOnly {
opts = append(opts, retry.LastErrorOnly(true))
}
if r.DelayType != nil {
opts = append(opts, retry.DelayType(r.DelayType))
}
if r.OnRetry != nil {
opts = append(opts, retry.OnRetry(r.OnRetry))
}
if r.RetryIf != nil {
opts = append(opts, retry.RetryIf(r.RetryIf))
}
return retry.Do(fun, opts...)
}
|
import Footer from "../pages/shared/Footer/Footer";
import { Outlet } from "react-router-dom";
import NavigationBar from "../pages/shared/Navigationbar/Navigationbar";
import { useEffect, useState } from "react";
import { Spinner } from "react-bootstrap";
const Main = () => {
const [isLoading, setIsLoading] = useState(true);
useEffect(() => {
setTimeout(() => {
setIsLoading(false);
}, 2000);
}, []);
return (
<div>
{/* Loading Spinner Here */}
{isLoading ? (
<div
style={{ marginTop: "400px" }}
className="d-flex justify-content-center align-items-center mt-5"
>
<Spinner className="fs-5 mt-5" animation="border" variant="danger" />
</div>
) : (
<>
<NavigationBar></NavigationBar>
<Outlet></Outlet>
<Footer></Footer>
</>
)}
</div>
);
};
export default Main;
|
class Vec3 extends Array {
static UP = [0, 1, 0];
static DOWN = [0, -1, 0];
static LEFT = [-1, 0, 0];
static RIGHT = [1, 0, 0];
static FORWARD = [0, 0, 1];
static BACK = [0, 0, -1];
constructor(v, y, z) {
super(3);
if (v instanceof Vec3 || v instanceof Float32Array || v instanceof Array && v.length == 3) {
this[0] = v[0];
this[1] = v[1];
this[2] = v[2];
} else if (typeof v === "number" && typeof y === "number" && typeof z === "number") {
this[0] = v;
this[1] = y;
this[2] = z;
} else if (typeof v === "number") {
this[0] = v;
this[1] = v;
this[2] = v;
} else {
this[0] = 0;
this[1] = 0;
this[2] = 0;
}
}
get len() {
return Math.sqrt(this[0] ** 2 + this[1] ** 2 + this[2] ** 2);
}
get lenSqr() {
return this[0] ** 2 + this[1] ** 2 + this[2] ** 2;
}
get isZero() {
return this[0] === 0 && this[1] === 0 && this[2] === 0;
}
clone() {
return new Vec3(this);
}
minAxis() {
if (this[0] < this[1] && this[0] < this[2])
return 0;
if (this[1] < this[2])
return 1;
return 2;
}
maxAxis() {
if (this[0] > this[1] && this[0] > this[2])
return 0;
if (this[1] > this[2])
return 1;
return 2;
}
xyz(x, y, z) {
this[0] = x;
this[1] = y;
this[2] = z;
return this;
}
copy(a) {
this[0] = a[0];
this[1] = a[1];
this[2] = a[2];
return this;
}
copyTo(a) {
a[0] = this[0];
a[1] = this[1];
a[2] = this[2];
return this;
}
setInfinite(sign = 1) {
this[0] = Infinity * sign;
this[1] = Infinity * sign;
this[2] = Infinity * sign;
return this;
}
rnd(x0 = 0, x1 = 1, y0 = 0, y1 = 1, z0 = 0, z1 = 1) {
let t;
t = Math.random();
this[0] = x0 * (1 - t) + x1 * t;
t = Math.random();
this[1] = y0 * (1 - t) + y1 * t;
t = Math.random();
this[2] = z0 * (1 - t) + z1 * t;
return this;
}
fromAdd(a, b) {
this[0] = a[0] + b[0];
this[1] = a[1] + b[1];
this[2] = a[2] + b[2];
return this;
}
fromSub(a, b) {
this[0] = a[0] - b[0];
this[1] = a[1] - b[1];
this[2] = a[2] - b[2];
return this;
}
fromMul(a, b) {
this[0] = a[0] * b[0];
this[1] = a[1] * b[1];
this[2] = a[2] * b[2];
return this;
}
fromScale(a, s) {
this[0] = a[0] * s;
this[1] = a[1] * s;
this[2] = a[2] * s;
return this;
}
fromScaleThenAdd(scale, a, b) {
this[0] = a[0] * scale + b[0];
this[1] = a[1] * scale + b[1];
this[2] = a[2] * scale + b[2];
return this;
}
fromCross(a, b) {
const ax = a[0], ay = a[1], az = a[2], bx = b[0], by = b[1], bz = b[2];
this[0] = ay * bz - az * by;
this[1] = az * bx - ax * bz;
this[2] = ax * by - ay * bx;
return this;
}
fromNegate(a) {
this[0] = -a[0];
this[1] = -a[1];
this[2] = -a[2];
return this;
}
fromInvert(a) {
this[0] = 1 / a[0];
this[1] = 1 / a[1];
this[2] = 1 / a[2];
return this;
}
fromPerpendicular(a) {
this[0] = -a[1];
this[1] = a[0];
this[2] = a[2];
return this;
}
fromQuat(q, v) {
const qx = q[0], qy = q[1], qz = q[2], qw = q[3], vx = v[0], vy = v[1], vz = v[2], x1 = qy * vz - qz * vy, y1 = qz * vx - qx * vz, z1 = qx * vy - qy * vx, x2 = qw * x1 + qy * z1 - qz * y1, y2 = qw * y1 + qz * x1 - qx * z1, z2 = qw * z1 + qx * y1 - qy * x1;
this[0] = vx + 2 * x2;
this[1] = vy + 2 * y2;
this[2] = vz + 2 * z2;
return this;
}
fromPolar(lon, lat) {
const phi = (90 - lat) * 0.01745329251, theta = lon * 0.01745329251, sp = Math.sin(phi);
this[0] = -sp * Math.sin(theta);
this[1] = Math.cos(phi);
this[2] = sp * Math.cos(theta);
return this;
}
fromStruct(v) {
this[0] = v.x;
this[1] = v.y;
this[2] = v.z;
return this;
}
toStruct(v) {
v.x = this[0];
v.y = this[1];
v.z = this[2];
return this;
}
fromVec2(v, isYUp = false) {
this[0] = v[0];
if (isYUp) {
this[1] = 0;
this[2] = v[1];
} else {
this[1] = v[1];
this[2] = 0;
}
return this;
}
fromNorm(v) {
let mag = Math.sqrt(v[0] ** 2 + v[1] ** 2 + v[2] ** 2);
if (mag == 0)
return this;
mag = 1 / mag;
this[0] = v[0] * mag;
this[1] = v[1] * mag;
this[2] = v[2] * mag;
return this;
}
fromTriNorm(a, b, c) {
const ab = new Vec3().fromSub(b, a);
const ac = new Vec3().fromSub(c, a);
return this.fromCross(ab, ac).norm();
}
fromAxisAngle(axis, rad, v = Vec3.FORWARD) {
const cp = new Vec3().fromCross(axis, v), dot = Vec3.dot(axis, v), s = Math.sin(rad), c = Math.cos(rad), ci = 1 - c;
this[0] = v[0] * c + cp[0] * s + axis[0] * dot * ci;
this[1] = v[1] * c + cp[1] * s + axis[1] * dot * ci;
this[2] = v[2] * c + cp[2] * s + axis[2] * dot * ci;
return this;
}
fromOrthogonal(v) {
if (v[0] >= 0.57735026919) {
this[0] = v[1];
this[1] = -v[0];
this[2] = 0;
} else {
this[0] = 0;
this[1] = v[2];
this[2] = -v[1];
}
return this;
}
fromReflect(dir, norm) {
const factor = -2 * Vec3.dot(norm, dir);
this[0] = factor * norm[0] + dir[0];
this[1] = factor * norm[1] + dir[1];
this[2] = factor * norm[2] + dir[2];
return this;
}
fromPlaneProj(v, planePos, planeNorm) {
const planeConst = -Vec3.dot(planePos, planeNorm);
const scl = -(Vec3.dot(planeNorm, v) + planeConst);
this[0] = v[0] + planeNorm[0] * scl;
this[1] = v[1] + planeNorm[1] * scl;
this[2] = v[2] + planeNorm[2] * scl;
return this;
}
fromProject(from, to) {
const denom = Vec3.dot(to, to);
if (denom < 1e-6) {
this[0] = 0;
this[1] = 0;
this[2] = 0;
} else {
const scl = Vec3.dot(from, to) / denom;
this[0] = to[0] * scl;
this[1] = to[1] * scl;
this[2] = to[2] * scl;
}
return this;
}
fromBuf(ary, idx) {
this[0] = ary[idx];
this[1] = ary[idx + 1];
this[2] = ary[idx + 2];
return this;
}
toBuf(ary, idx) {
ary[idx] = this[0];
ary[idx + 1] = this[1];
ary[idx + 2] = this[2];
return this;
}
pushTo(ary) {
ary.push(this[0], this[1], this[2]);
return this;
}
fromLerp(a, b, t) {
const ti = 1 - t;
this[0] = a[0] * ti + b[0] * t;
this[1] = a[1] * ti + b[1] * t;
this[2] = a[2] * ti + b[2] * t;
return this;
}
fromNLerp(a, b, t) {
const ti = 1 - t;
this[0] = a[0] * ti + b[0] * t;
this[1] = a[1] * ti + b[1] * t;
this[2] = a[2] * ti + b[2] * t;
this.norm();
return this;
}
fromSlerp(a, b, t) {
const angle = Math.acos(Math.min(Math.max(Vec3.dot(a, b), -1), 1));
const sin = Math.sin(angle);
const ta = Math.sin((1 - t) * angle) / sin;
const tb = Math.sin(t * angle) / sin;
this[0] = ta * a[0] + tb * b[0];
this[1] = ta * a[1] + tb * b[1];
this[2] = ta * a[2] + tb * b[2];
return this;
}
fromHermite(a, b, c, d, t) {
const tt = t * t;
const f1 = tt * (2 * t - 3) + 1;
const f2 = tt * (t - 2) + t;
const f3 = tt * (t - 1);
const f4 = tt * (3 - 2 * t);
this[0] = a[0] * f1 + b[0] * f2 + c[0] * f3 + d[0] * f4;
this[1] = a[1] * f1 + b[1] * f2 + c[1] * f3 + d[1] * f4;
this[2] = a[2] * f1 + b[2] * f2 + c[2] * f3 + d[2] * f4;
return this;
}
fromBezier(a, b, c, d, t) {
const it = 1 - t;
const it2 = it * it;
const tt = t * t;
const f1 = it2 * it;
const f2 = 3 * t * it2;
const f3 = 3 * tt * it;
const f4 = tt * t;
this[0] = a[0] * f1 + b[0] * f2 + c[0] * f3 + d[0] * f4;
this[1] = a[1] * f1 + b[1] * f2 + c[1] * f3 + d[1] * f4;
this[2] = a[2] * f1 + b[2] * f2 + c[2] * f3 + d[2] * f4;
return this;
}
fromCubic(a, b, c, d, t) {
const t2 = t * t, t3 = t * t2, a0 = d[0] - c[0] - a[0] + b[0], a1 = d[1] - c[1] - a[1] + b[1], a2 = d[2] - c[2] - a[2] + b[2];
this[0] = a0 * t3 + (a[0] - b[0] - a0) * t2 + (c[0] - a[0]) * t + b[0];
this[1] = a1 * t3 + (a[1] - b[1] - a1) * t2 + (c[1] - a[1]) * t + b[1];
this[2] = a2 * t3 + (a[2] - b[2] - a2) * t2 + (c[2] - a[2]) * t + b[2];
return this;
}
add(a) {
this[0] += a[0];
this[1] += a[1];
this[2] += a[2];
return this;
}
sub(v) {
this[0] -= v[0];
this[1] -= v[1];
this[2] -= v[2];
return this;
}
mul(v) {
this[0] *= v[0];
this[1] *= v[1];
this[2] *= v[2];
return this;
}
div(v) {
this[0] /= v[0];
this[1] /= v[1];
this[2] /= v[2];
return this;
}
scale(v) {
this[0] *= v;
this[1] *= v;
this[2] *= v;
return this;
}
divScale(v) {
this[0] /= v;
this[1] /= v;
this[2] /= v;
return this;
}
addScaled(a, s) {
this[0] += a[0] * s;
this[1] += a[1] * s;
this[2] += a[2] * s;
return this;
}
invert() {
this[0] = 1 / this[0];
this[1] = 1 / this[1];
this[2] = 1 / this[2];
return this;
}
norm() {
let mag = Math.sqrt(this[0] ** 2 + this[1] ** 2 + this[2] ** 2);
if (mag != 0) {
mag = 1 / mag;
this[0] *= mag;
this[1] *= mag;
this[2] *= mag;
}
return this;
}
cross(b) {
const ax = this[0], ay = this[1], az = this[2], bx = b[0], by = b[1], bz = b[2];
this[0] = ay * bz - az * by;
this[1] = az * bx - ax * bz;
this[2] = ax * by - ay * bx;
return this;
}
abs() {
this[0] = Math.abs(this[0]);
this[1] = Math.abs(this[1]);
this[2] = Math.abs(this[2]);
return this;
}
floor() {
this[0] = Math.floor(this[0]);
this[1] = Math.floor(this[1]);
this[2] = Math.floor(this[2]);
return this;
}
ceil() {
this[0] = Math.ceil(this[0]);
this[1] = Math.ceil(this[1]);
this[2] = Math.ceil(this[2]);
return this;
}
min(a) {
this[0] = Math.min(this[0], a[0]);
this[1] = Math.min(this[1], a[1]);
this[2] = Math.min(this[2], a[2]);
return this;
}
max(a) {
this[0] = Math.max(this[0], a[0]);
this[1] = Math.max(this[1], a[1]);
this[2] = Math.max(this[2], a[2]);
return this;
}
nearZero() {
if (Math.abs(this[0]) <= 1e-6)
this[0] = 0;
if (Math.abs(this[1]) <= 1e-6)
this[1] = 0;
if (Math.abs(this[2]) <= 1e-6)
this[2] = 0;
return this;
}
negate() {
this[0] = -this[0];
this[1] = -this[1];
this[2] = -this[2];
return this;
}
snap(v) {
this[0] = v[0] != 0 ? Math.floor(this[0] / v[0]) * v[0] : 0;
this[1] = v[1] != 0 ? Math.floor(this[1] / v[1]) * v[1] : 0;
this[2] = v[2] != 0 ? Math.floor(this[2] / v[2]) * v[2] : 0;
return this;
}
clamp(min, max) {
this[0] = Math.min(Math.max(this[0], min[0]), max[0]);
this[1] = Math.min(Math.max(this[1], min[1]), max[1]);
this[2] = Math.min(Math.max(this[2], min[2]), max[2]);
return this;
}
damp(v, lambda, dt) {
const t = Math.exp(-lambda * dt);
const ti = 1 - t;
this[0] = this[0] * t + v[0] * ti;
this[1] = this[1] * t + v[1] * ti;
this[2] = this[2] * t + v[2] * ti;
return this;
}
dot(b) {
return this[0] * b[0] + this[1] * b[1] + this[2] * b[2];
}
axisAngle(axis, rad) {
const cp = new Vec3().fromCross(axis, this), dot = Vec3.dot(axis, this), s = Math.sin(rad), c = Math.cos(rad), ci = 1 - c;
this[0] = this[0] * c + cp[0] * s + axis[0] * dot * ci;
this[1] = this[1] * c + cp[1] * s + axis[1] * dot * ci;
this[2] = this[2] * c + cp[2] * s + axis[2] * dot * ci;
return this;
}
rotate(rad, axis = "x") {
const sin = Math.sin(rad), cos = Math.cos(rad), x = this[0], y = this[1], z = this[2];
switch (axis) {
case "y":
this[0] = z * sin + x * cos;
this[2] = z * cos - x * sin;
break;
case "x":
this[1] = y * cos - z * sin;
this[2] = y * sin + z * cos;
break;
case "z":
this[0] = x * cos - y * sin;
this[1] = x * sin + y * cos;
break;
}
return this;
}
transformQuat(q) {
const qx = q[0], qy = q[1], qz = q[2], qw = q[3], vx = this[0], vy = this[1], vz = this[2], x1 = qy * vz - qz * vy, y1 = qz * vx - qx * vz, z1 = qx * vy - qy * vx, x2 = qw * x1 + qy * z1 - qz * y1, y2 = qw * y1 + qz * x1 - qx * z1, z2 = qw * z1 + qx * y1 - qy * x1;
this[0] = vx + 2 * x2;
this[1] = vy + 2 * y2;
this[2] = vz + 2 * z2;
return this;
}
transformMat3(m) {
const x = this[0], y = this[1], z = this[2];
this[0] = x * m[0] + y * m[3] + z * m[6];
this[1] = x * m[1] + y * m[4] + z * m[7];
this[2] = x * m[2] + y * m[5] + z * m[8];
return this;
}
transformMat4(m) {
const x = this[0], y = this[1], z = this[2], w = m[3] * x + m[7] * y + m[11] * z + m[15] || 1;
this[0] = (m[0] * x + m[4] * y + m[8] * z + m[12]) / w;
this[1] = (m[1] * x + m[5] * y + m[9] * z + m[13]) / w;
this[2] = (m[2] * x + m[6] * y + m[10] * z + m[14]) / w;
return this;
}
static len(a) {
return Math.sqrt(a[0] ** 2 + a[1] ** 2 + a[2] ** 2);
}
static lenSqr(a) {
return a[0] ** 2 + a[1] ** 2 + a[2] ** 2;
}
static dist(a, b) {
return Math.sqrt((a[0] - b[0]) ** 2 + (a[1] - b[1]) ** 2 + (a[2] - b[2]) ** 2);
}
static distSqr(a, b) {
return (a[0] - b[0]) ** 2 + (a[1] - b[1]) ** 2 + (a[2] - b[2]) ** 2;
}
static dot(a, b) {
return a[0] * b[0] + a[1] * b[1] + a[2] * b[2];
}
static cross(a, b, out = new Vec3()) {
const ax = a[0], ay = a[1], az = a[2], bx = b[0], by = b[1], bz = b[2];
out[0] = ay * bz - az * by;
out[1] = az * bx - ax * bz;
out[2] = ax * by - ay * bx;
return out;
}
static norm(a) {
let mag = Math.sqrt(a[0] ** 2 + a[1] ** 2 + a[2] ** 2);
if (mag != 0) {
mag = 1 / mag;
a[0] = a[0] * mag;
a[1] = a[1] * mag;
a[2] = a[2] * mag;
}
return a;
}
static angle(a, b) {
const d = this.dot(a, b), c = new Vec3().fromCross(a, b);
return Math.atan2(Vec3.len(c), d);
}
static scaleThenAdd(scale, a, b, out = new Vec3()) {
out[0] = a[0] * scale + b[0];
out[1] = a[1] * scale + b[1];
out[2] = a[2] * scale + b[2];
return out;
}
static fromQuat(q, v = [0, 0, 1]) {
return new Vec3(v).transformQuat(q);
}
static iterBuf(buf) {
let i = 0;
const result = { value: new Vec3(), done: false }, len = buf.length, next = () => {
if (i >= len)
result.done = true;
else {
result.value.fromBuf(buf, i);
i += 3;
}
return result;
};
return { [Symbol.iterator]() {
return { next };
} };
}
}class Quat extends Array {
static LOOKXP = [0, -0.7071067811865475, 0, 0.7071067811865475];
static LOOKXN = [0, 0.7071067811865475, 0, 0.7071067811865475];
static LOOKYP = [0.7071067811865475, 0, 0, 0.7071067811865475];
static LOOKYN = [-0.7071067811865475, 0, 0, 0.7071067811865475];
static LOOKZP = [0, -1, 0, 0];
static LOOKZN = [0, 0, 0, 1];
constructor(v) {
super(4);
if (v instanceof Quat || v instanceof Float32Array || v instanceof Array && v.length == 4) {
this[0] = v[0];
this[1] = v[1];
this[2] = v[2];
this[3] = v[3];
} else {
this[0] = 0;
this[1] = 0;
this[2] = 0;
this[3] = 1;
}
}
get x() {
return this[0];
}
set x(v) {
this[0] = v;
}
get y() {
return this[1];
}
set y(v) {
this[1] = v;
}
get z() {
return this[2];
}
set z(v) {
this[2] = v;
}
get w() {
return this[3];
}
set w(v) {
this[3] = v;
}
xyzw(x, y, z, w) {
this[0] = x;
this[1] = y;
this[2] = z;
this[3] = w;
return this;
}
identity() {
this[0] = 0;
this[1] = 0;
this[2] = 0;
this[3] = 1;
return this;
}
copy(a) {
this[0] = a[0];
this[1] = a[1];
this[2] = a[2];
this[3] = a[3];
return this;
}
copyTo(a) {
a[0] = this[0];
a[1] = this[1];
a[2] = this[2];
a[3] = this[3];
return this;
}
clone() {
return new Quat(this);
}
toString(rnd = 0) {
if (rnd == 0)
return "[" + this.join(",") + "]";
else {
let s = "[";
for (let i = 0; i < 4; i++) {
switch (this[i]) {
case 0:
s += "0,";
break;
case 1:
s += "1,";
break;
default:
s += this[i].toFixed(rnd) + ",";
break;
}
}
return s.slice(0, -1) + "]";
}
}
isZero() {
return this[0] == 0 && this[1] == 0 && this[2] == 0 && this[3] == 0;
}
lenSqr() {
return this[0] ** 2 + this[1] ** 2 + this[2] ** 2 + this[3] ** 2;
}
len() {
return Math.sqrt(this[0] ** 2 + this[1] ** 2 + this[2] ** 2 + this[3] ** 2);
}
getAxisAngle() {
if (this[3] > 1)
this.norm();
const angle = 2 * Math.acos(this[3]), s = Math.sqrt(1 - this[3] * this[3]);
if (s < 1e-3)
return [1, 0, 0, 0];
return [this[0] / s, this[1] / s, this[2] / s, angle];
}
getAngle() {
if (this[3] > 1)
this.norm();
return 2 * Math.acos(this[3]);
}
getAxis(out) {
if (this[3] > 1)
this.norm();
const s = Math.sqrt(1 - this[3] ** 2);
out = out || [0, 0, 0];
if (s < 1e-3) {
out[0] = 1;
out[1] = 0;
out[2] = 0;
} else {
out[0] = this[0] / s;
out[1] = this[1] / s;
out[2] = this[2] / s;
}
return out;
}
fromPolar(lon, lat, up) {
lat = Math.max(Math.min(lat, 89.999999), -89.999999);
const phi = (90 - lat) * 0.01745329251, theta = lon * 0.01745329251, phi_s = Math.sin(phi), v = [
-(phi_s * Math.sin(theta)),
Math.cos(phi),
phi_s * Math.cos(theta)
];
this.fromLook(v, up || Vec3.UP);
return this;
}
toPolar() {
const fwd = new Vec3().fromQuat(this, Vec3.FORWARD);
const flat = new Vec3(fwd[0], 0, fwd[2]).norm();
let lon = Vec3.angle(Vec3.FORWARD, flat);
let lat = Vec3.angle(flat, fwd);
const d_side = Vec3.dot(fwd, Vec3.RIGHT);
const d_up = Vec3.dot(fwd, Vec3.UP);
if (d_side < 0)
lon = -lon;
if (d_up < 0)
lat = -lat;
if (d_up > 0.999 || d_up <= -0.999)
lon = 0;
const to_deg = 180 / Math.PI;
return [lon * to_deg, lat * to_deg];
}
fromBuf(ary, idx) {
this[0] = ary[idx];
this[1] = ary[idx + 1];
this[2] = ary[idx + 2];
this[3] = ary[idx + 3];
return this;
}
toBuf(ary, idx) {
ary[idx] = this[0];
ary[idx + 1] = this[1];
ary[idx + 2] = this[2];
ary[idx + 3] = this[3];
return this;
}
pushTo(ary) {
ary.push(this[0], this[1], this[2], this[3]);
return this;
}
fromMul(a, b) {
const ax = a[0], ay = a[1], az = a[2], aw = a[3], bx = b[0], by = b[1], bz = b[2], bw = b[3];
this[0] = ax * bw + aw * bx + ay * bz - az * by;
this[1] = ay * bw + aw * by + az * bx - ax * bz;
this[2] = az * bw + aw * bz + ax * by - ay * bx;
this[3] = aw * bw - ax * bx - ay * by - az * bz;
return this;
}
fromAxisAngle(axis, rad) {
const half = rad * 0.5;
const s = Math.sin(half);
this[0] = axis[0] * s;
this[1] = axis[1] * s;
this[2] = axis[2] * s;
this[3] = Math.cos(half);
return this;
}
fromSwing(a, b) {
const dot = Vec3.dot(a, b);
if (dot < -0.999999) {
const tmp = new Vec3().fromCross(Vec3.LEFT, a);
if (tmp.len < 1e-6)
tmp.fromCross(Vec3.UP, a);
this.fromAxisAngle(tmp.norm(), Math.PI);
} else if (dot > 0.999999) {
this[0] = 0;
this[1] = 0;
this[2] = 0;
this[3] = 1;
} else {
const v = Vec3.cross(a, b, [0, 0, 0]);
this[0] = v[0];
this[1] = v[1];
this[2] = v[2];
this[3] = 1 + dot;
this.norm();
}
return this;
}
fromInvert(q) {
const a0 = q[0], a1 = q[1], a2 = q[2], a3 = q[3], dot = a0 * a0 + a1 * a1 + a2 * a2 + a3 * a3;
if (dot == 0) {
this[0] = this[1] = this[2] = this[3] = 0;
return this;
}
const invDot = 1 / dot;
this[0] = -a0 * invDot;
this[1] = -a1 * invDot;
this[2] = -a2 * invDot;
this[3] = a3 * invDot;
return this;
}
fromNegate(q) {
this[0] = -q[0];
this[1] = -q[1];
this[2] = -q[2];
this[3] = -q[3];
return this;
}
fromLook(dir, up = [0, 1, 0]) {
const zAxis = new Vec3(dir).norm();
const xAxis = new Vec3().fromCross(up, zAxis).norm();
const yAxis = new Vec3().fromCross(zAxis, xAxis).norm();
const m00 = xAxis[0], m01 = xAxis[1], m02 = xAxis[2], m10 = yAxis[0], m11 = yAxis[1], m12 = yAxis[2], m20 = zAxis[0], m21 = zAxis[1], m22 = zAxis[2], t = m00 + m11 + m22;
let x, y, z, w, s;
if (t > 0) {
s = Math.sqrt(t + 1);
w = s * 0.5;
s = 0.5 / s;
x = (m12 - m21) * s;
y = (m20 - m02) * s;
z = (m01 - m10) * s;
} else if (m00 >= m11 && m00 >= m22) {
s = Math.sqrt(1 + m00 - m11 - m22);
x = 0.5 * s;
s = 0.5 / s;
y = (m01 + m10) * s;
z = (m02 + m20) * s;
w = (m12 - m21) * s;
} else if (m11 > m22) {
s = Math.sqrt(1 + m11 - m00 - m22);
y = 0.5 * s;
s = 0.5 / s;
x = (m10 + m01) * s;
z = (m21 + m12) * s;
w = (m20 - m02) * s;
} else {
s = Math.sqrt(1 + m22 - m00 - m11);
z = 0.5 * s;
s = 0.5 / s;
x = (m20 + m02) * s;
y = (m21 + m12) * s;
w = (m01 - m10) * s;
}
this[0] = x;
this[1] = y;
this[2] = z;
this[3] = w;
return this;
}
fromNBlend(a, b, t) {
const a_x = a[0];
const a_y = a[1];
const a_z = a[2];
const a_w = a[3];
const b_x = b[0];
const b_y = b[1];
const b_z = b[2];
const b_w = b[3];
const dot = a_x * b_x + a_y * b_y + a_z * b_z + a_w * b_w;
const ti = 1 - t;
const s = dot < 0 ? -1 : 1;
this[0] = ti * a_x + t * b_x * s;
this[1] = ti * a_y + t * b_y * s;
this[2] = ti * a_z + t * b_z * s;
this[3] = ti * a_w + t * b_w * s;
return this.norm();
}
fromLerp(a, b, t) {
const ti = 1 - t;
this[0] = a[0] * ti + b[0] * t;
this[1] = a[1] * ti + b[1] * t;
this[2] = a[2] * ti + b[2] * t;
this[3] = a[3] * ti + b[3] * t;
return this;
}
fromNLerp(a, b, t) {
const ti = 1 - t;
this[0] = a[0] * ti + b[0] * t;
this[1] = a[1] * ti + b[1] * t;
this[2] = a[2] * ti + b[2] * t;
this[3] = a[3] * ti + b[3] * t;
return this.norm();
}
fromSlerp(a, b, t) {
const ax = a[0], ay = a[1], az = a[2], aw = a[3];
let bx = b[0], by = b[1], bz = b[2], bw = b[3];
let omega, cosom, sinom, scale0, scale1;
cosom = ax * bx + ay * by + az * bz + aw * bw;
if (cosom < 0) {
cosom = -cosom;
bx = -bx;
by = -by;
bz = -bz;
bw = -bw;
}
if (1 - cosom > 1e-6) {
omega = Math.acos(cosom);
sinom = Math.sin(omega);
scale0 = Math.sin((1 - t) * omega) / sinom;
scale1 = Math.sin(t * omega) / sinom;
} else {
scale0 = 1 - t;
scale1 = t;
}
this[0] = scale0 * ax + scale1 * bx;
this[1] = scale0 * ay + scale1 * by;
this[2] = scale0 * az + scale1 * bz;
this[3] = scale0 * aw + scale1 * bw;
return this;
}
fromAxes(xAxis, yAxis, zAxis) {
const m00 = xAxis[0], m01 = xAxis[1], m02 = xAxis[2], m10 = yAxis[0], m11 = yAxis[1], m12 = yAxis[2], m20 = zAxis[0], m21 = zAxis[1], m22 = zAxis[2], t = m00 + m11 + m22;
let x, y, z, w, s;
if (t > 0) {
s = Math.sqrt(t + 1);
w = s * 0.5;
s = 0.5 / s;
x = (m12 - m21) * s;
y = (m20 - m02) * s;
z = (m01 - m10) * s;
} else if (m00 >= m11 && m00 >= m22) {
s = Math.sqrt(1 + m00 - m11 - m22);
x = 0.5 * s;
s = 0.5 / s;
y = (m01 + m10) * s;
z = (m02 + m20) * s;
w = (m12 - m21) * s;
} else if (m11 > m22) {
s = Math.sqrt(1 + m11 - m00 - m22);
y = 0.5 * s;
s = 0.5 / s;
x = (m10 + m01) * s;
z = (m21 + m12) * s;
w = (m20 - m02) * s;
} else {
s = Math.sqrt(1 + m22 - m00 - m11);
z = 0.5 * s;
s = 0.5 / s;
x = (m20 + m02) * s;
y = (m21 + m12) * s;
w = (m01 - m10) * s;
}
this[0] = x;
this[1] = y;
this[2] = z;
this[3] = w;
return this;
}
fromMat3(m) {
let fRoot;
const fTrace = m[0] + m[4] + m[8];
if (fTrace > 0) {
fRoot = Math.sqrt(fTrace + 1);
this[3] = 0.5 * fRoot;
fRoot = 0.5 / fRoot;
this[0] = (m[5] - m[7]) * fRoot;
this[1] = (m[6] - m[2]) * fRoot;
this[2] = (m[1] - m[3]) * fRoot;
} else {
let i = 0;
if (m[4] > m[0])
i = 1;
if (m[8] > m[i * 3 + i])
i = 2;
const j = (i + 1) % 3;
const k = (i + 2) % 3;
fRoot = Math.sqrt(m[i * 3 + i] - m[j * 3 + j] - m[k * 3 + k] + 1);
this[i] = 0.5 * fRoot;
fRoot = 0.5 / fRoot;
this[3] = (m[j * 3 + k] - m[k * 3 + j]) * fRoot;
this[j] = (m[j * 3 + i] + m[i * 3 + j]) * fRoot;
this[k] = (m[k * 3 + i] + m[i * 3 + k]) * fRoot;
}
return this;
}
fromMat4(mat) {
const trace = mat[0] + mat[5] + mat[10];
let S = 0;
if (trace > 0) {
S = Math.sqrt(trace + 1) * 2;
this[3] = 0.25 * S;
this[0] = (mat[6] - mat[9]) / S;
this[1] = (mat[8] - mat[2]) / S;
this[2] = (mat[1] - mat[4]) / S;
} else if (mat[0] > mat[5] && mat[0] > mat[10]) {
S = Math.sqrt(1 + mat[0] - mat[5] - mat[10]) * 2;
this[3] = (mat[6] - mat[9]) / S;
this[0] = 0.25 * S;
this[1] = (mat[1] + mat[4]) / S;
this[2] = (mat[8] + mat[2]) / S;
} else if (mat[5] > mat[10]) {
S = Math.sqrt(1 + mat[5] - mat[0] - mat[10]) * 2;
this[3] = (mat[8] - mat[2]) / S;
this[0] = (mat[1] + mat[4]) / S;
this[1] = 0.25 * S;
this[2] = (mat[6] + mat[9]) / S;
} else {
S = Math.sqrt(1 + mat[10] - mat[0] - mat[5]) * 2;
this[3] = (mat[1] - mat[4]) / S;
this[0] = (mat[8] + mat[2]) / S;
this[1] = (mat[6] + mat[9]) / S;
this[2] = 0.25 * S;
}
return this;
}
fromAngularVec(v) {
let len = Vec3.len(v);
if (len < 1e-6) {
this.identity();
return this;
}
const h = 0.5 * len;
const s = Math.sin(h);
const c = Math.cos(h);
len = 1 / len;
this[0] = s * (v[0] * len);
this[1] = s * (v[1] * len);
this[2] = s * (v[2] * len);
this[3] = c;
return this;
}
toAngularVec(out) {
const v = this.getAxisAngle();
out = out || new Vec3();
return out.fromScale(v, v[3]);
}
fromEuler(x, y, z) {
let xx = 0, yy = 0, zz = 0;
if (x instanceof Vec3 || x instanceof Float32Array || x instanceof Array && x.length == 3) {
xx = x[0] * 0.01745329251 * 0.5;
yy = x[1] * 0.01745329251 * 0.5;
zz = x[2] * 0.01745329251 * 0.5;
} else if (typeof x === "number" && typeof y === "number" && typeof z === "number") {
xx = x * 0.01745329251 * 0.5;
yy = y * 0.01745329251 * 0.5;
zz = z * 0.01745329251 * 0.5;
}
const c1 = Math.cos(xx), c2 = Math.cos(yy), c3 = Math.cos(zz), s1 = Math.sin(xx), s2 = Math.sin(yy), s3 = Math.sin(zz);
this[0] = s1 * c2 * c3 + c1 * s2 * s3;
this[1] = c1 * s2 * c3 - s1 * c2 * s3;
this[2] = c1 * c2 * s3 - s1 * s2 * c3;
this[3] = c1 * c2 * c3 + s1 * s2 * s3;
return this.norm();
}
fromEulerXY(x, y) {
const xx = x * 0.01745329251 * 0.5, yy = y * 0.01745329251 * 0.5, c1 = Math.cos(xx), c2 = Math.cos(yy), s1 = Math.sin(xx), s2 = Math.sin(yy);
this[0] = s1 * c2;
this[1] = c1 * s2;
this[2] = -s1 * s2;
this[3] = c1 * c2;
return this.norm();
}
fromEulerOrder(x, y, z, order = "YXZ") {
const c1 = Math.cos(x * 0.5), c2 = Math.cos(y * 0.5), c3 = Math.cos(z * 0.5), s1 = Math.sin(x * 0.5), s2 = Math.sin(y * 0.5), s3 = Math.sin(z * 0.5);
switch (order) {
case "XYZ":
this[0] = s1 * c2 * c3 + c1 * s2 * s3;
this[1] = c1 * s2 * c3 - s1 * c2 * s3;
this[2] = c1 * c2 * s3 + s1 * s2 * c3;
this[3] = c1 * c2 * c3 - s1 * s2 * s3;
break;
case "YXZ":
this[0] = s1 * c2 * c3 + c1 * s2 * s3;
this[1] = c1 * s2 * c3 - s1 * c2 * s3;
this[2] = c1 * c2 * s3 - s1 * s2 * c3;
this[3] = c1 * c2 * c3 + s1 * s2 * s3;
break;
case "ZXY":
this[0] = s1 * c2 * c3 - c1 * s2 * s3;
this[1] = c1 * s2 * c3 + s1 * c2 * s3;
this[2] = c1 * c2 * s3 + s1 * s2 * c3;
this[3] = c1 * c2 * c3 - s1 * s2 * s3;
break;
case "ZYX":
this[0] = s1 * c2 * c3 - c1 * s2 * s3;
this[1] = c1 * s2 * c3 + s1 * c2 * s3;
this[2] = c1 * c2 * s3 - s1 * s2 * c3;
this[3] = c1 * c2 * c3 + s1 * s2 * s3;
break;
case "YZX":
this[0] = s1 * c2 * c3 + c1 * s2 * s3;
this[1] = c1 * s2 * c3 + s1 * c2 * s3;
this[2] = c1 * c2 * s3 - s1 * s2 * c3;
this[3] = c1 * c2 * c3 - s1 * s2 * s3;
break;
case "XZY":
this[0] = s1 * c2 * c3 - c1 * s2 * s3;
this[1] = c1 * s2 * c3 - s1 * c2 * s3;
this[2] = c1 * c2 * s3 + s1 * s2 * c3;
this[3] = c1 * c2 * c3 + s1 * s2 * s3;
break;
}
return this.norm();
}
mul(q) {
const ax = this[0], ay = this[1], az = this[2], aw = this[3], bx = q[0], by = q[1], bz = q[2], bw = q[3];
this[0] = ax * bw + aw * bx + ay * bz - az * by;
this[1] = ay * bw + aw * by + az * bx - ax * bz;
this[2] = az * bw + aw * bz + ax * by - ay * bx;
this[3] = aw * bw - ax * bx - ay * by - az * bz;
return this;
}
pmul(q) {
const ax = q[0], ay = q[1], az = q[2], aw = q[3], bx = this[0], by = this[1], bz = this[2], bw = this[3];
this[0] = ax * bw + aw * bx + ay * bz - az * by;
this[1] = ay * bw + aw * by + az * bx - ax * bz;
this[2] = az * bw + aw * bz + ax * by - ay * bx;
this[3] = aw * bw - ax * bx - ay * by - az * bz;
return this;
}
norm() {
let len = this[0] ** 2 + this[1] ** 2 + this[2] ** 2 + this[3] ** 2;
if (len > 0) {
len = 1 / Math.sqrt(len);
this[0] *= len;
this[1] *= len;
this[2] *= len;
this[3] *= len;
}
return this;
}
invert() {
const a0 = this[0], a1 = this[1], a2 = this[2], a3 = this[3], dot = a0 * a0 + a1 * a1 + a2 * a2 + a3 * a3;
if (dot == 0) {
this[0] = this[1] = this[2] = this[3] = 0;
return this;
}
const invDot = 1 / dot;
this[0] = -a0 * invDot;
this[1] = -a1 * invDot;
this[2] = -a2 * invDot;
this[3] = a3 * invDot;
return this;
}
negate() {
this[0] = -this[0];
this[1] = -this[1];
this[2] = -this[2];
this[3] = -this[3];
return this;
}
conjugate() {
this[0] = -this[0];
this[1] = -this[1];
this[2] = -this[2];
return this;
}
scaleAngle(scl) {
if (this[3] > 1)
this.norm();
const angle = 2 * Math.acos(this[3]), len = 1 / Math.sqrt(this[0] ** 2 + this[1] ** 2 + this[2] ** 2), half = angle * scl * 0.5, s = Math.sin(half);
this[0] = this[0] * len * s;
this[1] = this[1] * len * s;
this[2] = this[2] * len * s;
this[3] = Math.cos(half);
return this;
}
transformVec3(v) {
const qx = this[0], qy = this[1], qz = this[2], qw = this[3], vx = v[0], vy = v[1], vz = v[2], x1 = qy * vz - qz * vy, y1 = qz * vx - qx * vz, z1 = qx * vy - qy * vx, x2 = qw * x1 + qy * z1 - qz * y1, y2 = qw * y1 + qz * x1 - qx * z1, z2 = qw * z1 + qx * y1 - qy * x1;
v[0] = vx + 2 * x2;
v[1] = vy + 2 * y2;
v[2] = vz + 2 * z2;
return this;
}
rotX(rad) {
rad *= 0.5;
const ax = this[0], ay = this[1], az = this[2], aw = this[3], bx = Math.sin(rad), bw = Math.cos(rad);
this[0] = ax * bw + aw * bx;
this[1] = ay * bw + az * bx;
this[2] = az * bw - ay * bx;
this[3] = aw * bw - ax * bx;
return this;
}
rotY(rad) {
rad *= 0.5;
const ax = this[0], ay = this[1], az = this[2], aw = this[3], by = Math.sin(rad), bw = Math.cos(rad);
this[0] = ax * bw - az * by;
this[1] = ay * bw + aw * by;
this[2] = az * bw + ax * by;
this[3] = aw * bw - ay * by;
return this;
}
rotZ(rad) {
rad *= 0.5;
const ax = this[0], ay = this[1], az = this[2], aw = this[3], bz = Math.sin(rad), bw = Math.cos(rad);
this[0] = ax * bw + ay * bz;
this[1] = ay * bw - ax * bz;
this[2] = az * bw + aw * bz;
this[3] = aw * bw - az * bz;
return this;
}
rotDeg(deg, axis = 0) {
const rad = deg * Math.PI / 180;
switch (axis) {
case 0:
this.rotX(rad);
break;
case 1:
this.rotY(rad);
break;
case 2:
this.rotZ(rad);
break;
}
return this;
}
pmulInvert(q) {
let ax = q[0], ay = q[1], az = q[2], aw = q[3];
const dot = ax * ax + ay * ay + az * az + aw * aw;
if (dot === 0) {
ax = ay = az = aw = 0;
} else {
const dot_inv = 1 / dot;
ax = -ax * dot_inv;
ay = -ay * dot_inv;
az = -az * dot_inv;
aw = aw * dot_inv;
}
const bx = this[0], by = this[1], bz = this[2], bw = this[3];
this[0] = ax * bw + aw * bx + ay * bz - az * by;
this[1] = ay * bw + aw * by + az * bx - ax * bz;
this[2] = az * bw + aw * bz + ax * by - ay * bx;
this[3] = aw * bw - ax * bx - ay * by - az * bz;
return this;
}
pmulAxisAngle(axis, rad) {
const half = rad * 0.5;
const s = Math.sin(half);
const ax = axis[0] * s;
const ay = axis[1] * s;
const az = axis[2] * s;
const aw = Math.cos(half);
const bx = this[0], by = this[1], bz = this[2], bw = this[3];
this[0] = ax * bw + aw * bx + ay * bz - az * by;
this[1] = ay * bw + aw * by + az * bx - ax * bz;
this[2] = az * bw + aw * bz + ax * by - ay * bx;
this[3] = aw * bw - ax * bx - ay * by - az * bz;
return this;
}
mulAxisAngle(axis, angle) {
const half = angle * 0.5, s = Math.sin(half), bx = axis[0] * s, by = axis[1] * s, bz = axis[2] * s, bw = Math.cos(half), ax = this[0], ay = this[1], az = this[2], aw = this[3];
this[0] = ax * bw + aw * bx + ay * bz - az * by;
this[1] = ay * bw + aw * by + az * bx - ax * bz;
this[2] = az * bw + aw * bz + ax * by - ay * bx;
this[3] = aw * bw - ax * bx - ay * by - az * bz;
return this;
}
dotNegate(q, chk) {
if (Quat.dot(q, chk) < 0)
this.fromNegate(q);
else
this.copy(q);
return this;
}
mirrorX() {
this[1] = -this[1];
this[2] = -this[2];
return this;
}
random() {
const u1 = Math.random(), u2 = Math.random(), u3 = Math.random(), r1 = Math.sqrt(1 - u1), r2 = Math.sqrt(u1);
this[0] = r1 * Math.sin(6.283185307179586 * u2);
this[1] = r1 * Math.cos(6.283185307179586 * u2);
this[2] = r2 * Math.sin(6.283185307179586 * u3);
this[3] = r2 * Math.cos(6.283185307179586 * u3);
return this;
}
mulUnitVecs(a, b) {
const dot = Vec3.dot(a, b);
const ax = this[0], ay = this[1], az = this[2], aw = this[3];
let bx, by, bz, bw;
if (dot < -0.999999) {
const axis = Vec3.cross(Vec3.LEFT, a);
if (Vec3.len(axis) < 1e-6)
Vec3.cross(Vec3.UP, a, axis);
Vec3.norm(axis);
const half = Math.PI * 0.5, s = Math.sin(half);
bx = axis[0] * s;
by = axis[1] * s;
bz = axis[2] * s;
bw = Math.cos(half);
} else if (dot > 0.999999) {
bx = 0;
by = 0;
bz = 0;
bw = 1;
} else {
const v = Vec3.cross(a, b);
bx = v[0];
by = v[1];
bz = v[2];
bw = 1 + dot;
let len = bx ** 2 + by ** 2 + bz ** 2 + bw ** 2;
if (len > 0) {
len = 1 / Math.sqrt(len);
bx *= len;
by *= len;
bz *= len;
bw *= len;
}
}
this[0] = ax * bw + aw * bx + ay * bz - az * by;
this[1] = ay * bw + aw * by + az * bx - ax * bz;
this[2] = az * bw + aw * bz + ax * by - ay * bx;
this[3] = aw * bw - ax * bx - ay * by - az * bz;
return this;
}
static dot(a, b) {
return a[0] * b[0] + a[1] * b[1] + a[2] * b[2] + a[3] * b[3];
}
static lenSqr(a, b) {
return (a[0] - b[0]) ** 2 + (a[1] - b[1]) ** 2 + (a[2] - b[2]) ** 2 + (a[3] - b[3]) ** 2;
}
static nblend(a, b, t, out) {
const a_x = a[0];
const a_y = a[1];
const a_z = a[2];
const a_w = a[3];
const b_x = b[0];
const b_y = b[1];
const b_z = b[2];
const b_w = b[3];
const dot = a_x * b_x + a_y * b_y + a_z * b_z + a_w * b_w;
const ti = 1 - t;
const s = dot < 0 ? -1 : 1;
out[0] = ti * a_x + t * b_x * s;
out[1] = ti * a_y + t * b_y * s;
out[2] = ti * a_z + t * b_z * s;
out[3] = ti * a_w + t * b_w * s;
return out.norm();
}
static slerp(a, b, t, out) {
const ax = a[0], ay = a[1], az = a[2], aw = a[3];
let bx = b[0], by = b[1], bz = b[2], bw = b[3];
let omega, cosom, sinom, scale0, scale1;
cosom = ax * bx + ay * by + az * bz + aw * bw;
if (cosom < 0) {
cosom = -cosom;
bx = -bx;
by = -by;
bz = -bz;
bw = -bw;
}
if (1 - cosom > 1e-6) {
omega = Math.acos(cosom);
sinom = Math.sin(omega);
scale0 = Math.sin((1 - t) * omega) / sinom;
scale1 = Math.sin(t * omega) / sinom;
} else {
scale0 = 1 - t;
scale1 = t;
}
out[0] = scale0 * ax + scale1 * bx;
out[1] = scale0 * ay + scale1 * by;
out[2] = scale0 * az + scale1 * bz;
out[3] = scale0 * aw + scale1 * bw;
return out;
}
static shortest(from, to, out) {
const ax = from[0], ay = from[1], az = from[2], aw = from[3];
let bx = to[0], by = to[1], bz = to[2], bw = to[3];
const dot = ax * bx + ay * by + az * bz + aw * bw;
if (dot < 0) {
bx = -bx;
by = -by;
bz = -bz;
bw = -bw;
}
const d = bx * bx + by * by + bz * bz + bw * bw;
if (d === 0) {
bx = 0;
by = 0;
bz = 0;
bw = 0;
} else {
const di = 1 / d;
bx = -bx * di;
by = -by * di;
bz = -bz * di;
bw = bw * di;
}
out[0] = ax * bw + aw * bx + ay * bz - az * by;
out[1] = ay * bw + aw * by + az * bx - ax * bz;
out[2] = az * bw + aw * bz + ax * by - ay * bx;
out[3] = aw * bw - ax * bx - ay * by - az * bz;
return out;
}
static swing(a, b) {
return new Quat().fromSwing(a, b);
}
static axisAngle(axis, rad) {
return new Quat().fromAxisAngle(axis, rad);
}
}class Vec2 extends Array {
constructor(v, y) {
super(2);
if (v instanceof Vec2 || v instanceof Float32Array || v instanceof Array && v.length == 2) {
this[0] = v[0];
this[1] = v[1];
} else if (typeof v === "number" && typeof y === "number") {
this[0] = v;
this[1] = y;
} else if (typeof v === "number") {
this[0] = v;
this[1] = v;
} else {
this[0] = 0;
this[1] = 0;
}
}
xy(x, y) {
if (y != void 0) {
this[0] = x;
this[1] = y;
} else
this[0] = this[1] = x;
return this;
}
get x() {
return this[0];
}
set x(v) {
this[0] = v;
}
get y() {
return this[1];
}
set y(v) {
this[1] = v;
}
clone() {
return new Vec2(this);
}
copy(v) {
this[0] = v[0];
this[1] = v[1];
return this;
}
reset() {
this[0] = 0;
this[1] = 0;
return this;
}
toString(rnd = 0) {
if (rnd == 0)
return "[" + this.join(",") + "]";
else {
let s = "[";
for (let i = 0; i < 2; i++) {
switch (this[i]) {
case 0:
s += "0,";
break;
case 1:
s += "1,";
break;
default:
s += this[i].toFixed(rnd) + ",";
break;
}
}
return s.slice(0, -1) + "]";
}
}
isZero() {
return this[0] == 0 && this[1] == 0;
}
nearZero(x = 1e-6, y = 1e-6) {
if (Math.abs(this[0]) <= x)
this[0] = 0;
if (Math.abs(this[1]) <= y)
this[1] = 0;
return this;
}
rnd(x0 = 0, x1 = 1, y0 = 0, y1 = 1) {
let t;
t = Math.random();
this[0] = x0 * (1 - t) + x1 * t;
t = Math.random();
this[1] = y0 * (1 - t) + y1 * t;
return this;
}
angle(v) {
return v ? Math.atan2(v[1] * this[0] - v[0] * this[1], v[0] * this[0] + v[1] * this[1]) : Math.atan2(this[1], this[0]);
}
setLen(len) {
return this.norm().scale(len);
}
len() {
return Math.sqrt(this[0] * this[0] + this[1] * this[1]);
}
lenSqr() {
return this[0] * this[0] + this[1] * this[1];
}
toVec3(isYUp = true, n = 0) {
const v = [this[0], 0, 0];
if (isYUp) {
v[1] = n;
v[2] = this[1];
} else {
v[1] = this[1];
v[2] = n;
}
return v;
}
fromAngleLen(ang, len) {
this[0] = len * Math.cos(ang);
this[1] = len * Math.sin(ang);
return this;
}
fromAdd(a, b) {
this[0] = a[0] + b[0];
this[1] = a[1] + b[1];
return this;
}
fromSub(a, b) {
this[0] = a[0] - b[0];
this[1] = a[1] - b[1];
return this;
}
fromMul(a, b) {
this[0] = a[0] * b[0];
this[1] = a[1] * b[1];
return this;
}
fromScale(a, s) {
this[0] = a[0] * s;
this[1] = a[1] * s;
return this;
}
fromLerp(a, b, t = 0.5) {
const tt = 1 - t;
this[0] = a[0] * tt + b[0] * t;
this[1] = a[1] * tt + b[1] * t;
return this;
}
fromMax(a, b) {
this[0] = Math.max(a[0], b[0]);
this[1] = Math.max(a[1], b[1]);
return this;
}
fromMin(a, b) {
this[0] = Math.min(a[0], b[0]);
this[1] = Math.min(a[1], b[1]);
return this;
}
fromFloor(v) {
this[0] = Math.floor(v[0]);
this[1] = Math.floor(v[1]);
return this;
}
fromFract(v) {
this[0] = v[0] - Math.floor(v[0]);
this[1] = v[1] - Math.floor(v[1]);
return this;
}
fromNegate(a) {
this[0] = -a[0];
this[1] = -a[1];
return this;
}
fromNorm(a) {
const mag = Math.sqrt(a[0] ** 2 + a[1] ** 2);
if (mag == 0)
return this;
this[0] = a[0] / mag;
this[1] = a[1] / mag;
return this;
}
fromInvert(a) {
this[0] = a[0] != 0 ? 1 / a[0] : 0;
this[1] = a[1] != 0 ? 1 / a[1] : 0;
return this;
}
fromLineProjecton(from, to) {
const denom = Vec2.dot(to, to);
if (denom < 1e-6)
return this;
const scl = Vec2.dot(from, to) / denom;
this.fromScale(to, scl);
return this;
}
fromBuf(ary, idx) {
this[0] = ary[idx];
this[1] = ary[idx + 1];
return this;
}
toBuf(ary, idx) {
ary[idx] = this[0];
ary[idx + 1] = this[1];
return this;
}
pushTo(ary) {
ary.push(this[0], this[1]);
return this;
}
add(v) {
this[0] += v[0];
this[1] += v[1];
return this;
}
sub(v) {
this[0] -= v[0];
this[1] -= v[1];
return this;
}
mul(v) {
this[0] *= v[0];
this[1] *= v[1];
return this;
}
div(v) {
this[0] = v[0] != 0 ? this[0] / v[0] : 0;
this[1] = v[1] != 0 ? this[1] / v[1] : 0;
return this;
}
scale(v) {
this[0] *= v;
this[1] *= v;
return this;
}
divScale(v) {
this[0] /= v;
this[1] /= v;
return this;
}
scaleThenAdd(scale, a, b) {
this[0] = a[0] * scale + b[0];
this[1] = a[1] * scale + b[1];
return this;
}
floor() {
this[0] = Math.floor(this[0]);
this[1] = Math.floor(this[1]);
return this;
}
negate() {
this[0] = -this[0];
this[1] = -this[1];
return this;
}
min(a) {
this[0] = Math.min(this[0], a[0]);
this[1] = Math.min(this[1], a[1]);
return this;
}
max(a) {
this[0] = Math.max(this[0], a[0]);
this[1] = Math.max(this[1], a[1]);
return this;
}
norm() {
const mag = Math.sqrt(this[0] ** 2 + this[1] ** 2);
if (mag == 0)
return this;
this[0] = this[0] / mag;
this[1] = this[1] / mag;
return this;
}
lerp(v, t) {
const ti = 1 - t;
this[0] = this[0] * ti + v[0] * t;
this[1] = this[1] * ti + v[1] * t;
return this;
}
rotate(rad) {
const cos = Math.cos(rad), sin = Math.sin(rad), x = this[0], y = this[1];
this[0] = x * cos - y * sin;
this[1] = x * sin + y * cos;
return this;
}
rotateDeg(deg) {
const rad = deg * Math.PI / 180, cos = Math.cos(rad), sin = Math.sin(rad), x = this[0], y = this[1];
this[0] = x * cos - y * sin;
this[1] = x * sin + y * cos;
return this;
}
invert() {
this[0] = 1 / this[0];
this[1] = 1 / this[1];
return this;
}
rotP90() {
const x = this[0];
this[0] = this[1];
this[1] = -x;
return this;
}
rotN90() {
const x = this[0];
this[0] = -this[1];
this[1] = x;
return this;
}
static add(a, b) {
return new Vec2().fromAdd(a, b);
}
static sub(a, b) {
return new Vec2().fromSub(a, b);
}
static scale(v, s) {
return new Vec2().fromScale(v, s);
}
static floor(v) {
return new Vec2().fromFloor(v);
}
static fract(v) {
return new Vec2().fromFract(v);
}
static lerp(v0, v1, t) {
return new Vec2().fromLerp(v0, v1, t);
}
static len(v0) {
return Math.sqrt(v0[0] ** 2 + v0[1] ** 2);
}
static lenSqr(v0) {
return v0[0] ** 2 + v0[1] ** 2;
}
static dist(a, b) {
return Math.sqrt((a[0] - b[0]) ** 2 + (a[1] - b[1]) ** 2);
}
static distSqr(a, b) {
return (a[0] - b[0]) ** 2 + (a[1] - b[1]) ** 2;
}
static dot(a, b) {
return a[0] * b[0] + a[1] * b[1];
}
static det(a, b) {
return a[0] * b[1] - a[1] * b[0];
}
static project(from, to) {
const out = new Vec2();
const denom = Vec2.dot(to, to);
if (denom < 1e-6)
return out;
const scl = Vec2.dot(from, to) / denom;
return out.fromScale(to, scl);
}
static scaleThenAdd(scale, a, b) {
return new Vec2().scaleThenAdd(scale, a, b);
}
static projectPlane(from, to, planeNorm) {
const out = new Vec2();
const denom = Vec2.dot(to, planeNorm);
if (denom < 1e-6 && denom > -1e-6)
return out;
const t = Vec2.dot(from, planeNorm) / denom;
return out.fromScale(to, t);
}
static rotateDeg(v, deg) {
const out = new Vec2();
const rad = deg * Math.PI / 180, cos = Math.cos(rad), sin = Math.sin(rad), x = v[0], y = v[1];
out[0] = x * cos - y * sin;
out[1] = x * sin + y * cos;
return out;
}
static rotP90(v) {
const out = new Vec2();
out[0] = v[1];
out[1] = -v[0];
return out;
}
static rotN90(v) {
const out = new Vec2();
out[0] = -v[1];
out[1] = v[0];
return out;
}
static angleTo(a, b) {
return Math.atan2(b[1] * a[0] - b[0] * a[1], b[0] * a[0] + b[1] * a[1]);
}
static bufIter(buf) {
let i = 0;
const result = { value: new Vec2(), done: false }, len = buf.length, next = () => {
if (i >= len)
result.done = true;
else {
result.value.fromBuf(buf, i);
i += 2;
}
return result;
};
return { [Symbol.iterator]() {
return { next };
} };
}
}class Mat4 extends Array {
constructor() {
super(16);
this[0] = 1;
this[1] = 0;
this[2] = 0;
this[3] = 0;
this[4] = 0;
this[5] = 1;
this[6] = 0;
this[7] = 0;
this[8] = 0;
this[9] = 0;
this[10] = 1;
this[11] = 0;
this[12] = 0;
this[13] = 0;
this[14] = 0;
this[15] = 1;
}
identity() {
this[0] = 1;
this[1] = 0;
this[2] = 0;
this[3] = 0;
this[4] = 0;
this[5] = 1;
this[6] = 0;
this[7] = 0;
this[8] = 0;
this[9] = 0;
this[10] = 1;
this[11] = 0;
this[12] = 0;
this[13] = 0;
this[14] = 0;
this[15] = 1;
return this;
}
clearTranslation() {
this[12] = this[13] = this[14] = 0;
this[15] = 1;
return this;
}
copy(mat, offset = 0) {
let i;
for (i = 0; i < 16; i++)
this[i] = mat[offset + i];
return this;
}
copyTo(out) {
for (let i = 0; i < 16; i++)
out[i] = this[i];
return this;
}
determinant() {
const a00 = this[0], a01 = this[1], a02 = this[2], a03 = this[3], a10 = this[4], a11 = this[5], a12 = this[6], a13 = this[7], a20 = this[8], a21 = this[9], a22 = this[10], a23 = this[11], a30 = this[12], a31 = this[13], a32 = this[14], a33 = this[15], b0 = a00 * a11 - a01 * a10, b1 = a00 * a12 - a02 * a10, b2 = a01 * a12 - a02 * a11, b3 = a20 * a31 - a21 * a30, b4 = a20 * a32 - a22 * a30, b5 = a21 * a32 - a22 * a31, b6 = a00 * b5 - a01 * b4 + a02 * b3, b7 = a10 * b5 - a11 * b4 + a12 * b3, b8 = a20 * b2 - a21 * b1 + a22 * b0, b9 = a30 * b2 - a31 * b1 + a32 * b0;
return a13 * b6 - a03 * b7 + a33 * b8 - a23 * b9;
}
frob() {
return Math.hypot(
this[0],
this[1],
this[2],
this[3],
this[4],
this[5],
this[6],
this[7],
this[8],
this[9],
this[10],
this[11],
this[12],
this[13],
this[14],
this[15]
);
}
getTranslation(out = [0, 0, 0]) {
out[0] = this[12];
out[1] = this[13];
out[2] = this[14];
return out;
}
getScale(out = [0, 0, 0]) {
const m11 = this[0], m12 = this[1], m13 = this[2], m21 = this[4], m22 = this[5], m23 = this[6], m31 = this[8], m32 = this[9], m33 = this[10];
out[0] = Math.sqrt(m11 * m11 + m12 * m12 + m13 * m13);
out[1] = Math.sqrt(m21 * m21 + m22 * m22 + m23 * m23);
out[2] = Math.sqrt(m31 * m31 + m32 * m32 + m33 * m33);
return out;
}
getRotation(out = [0, 0, 0, 1]) {
const trace = this[0] + this[5] + this[10];
let S = 0;
if (trace > 0) {
S = Math.sqrt(trace + 1) * 2;
out[3] = 0.25 * S;
out[0] = (this[6] - this[9]) / S;
out[1] = (this[8] - this[2]) / S;
out[2] = (this[1] - this[4]) / S;
} else if (this[0] > this[5] && this[0] > this[10]) {
S = Math.sqrt(1 + this[0] - this[5] - this[10]) * 2;
out[3] = (this[6] - this[9]) / S;
out[0] = 0.25 * S;
out[1] = (this[1] + this[4]) / S;
out[2] = (this[8] + this[2]) / S;
} else if (this[5] > this[10]) {
S = Math.sqrt(1 + this[5] - this[0] - this[10]) * 2;
out[3] = (this[8] - this[2]) / S;
out[0] = (this[1] + this[4]) / S;
out[1] = 0.25 * S;
out[2] = (this[6] + this[9]) / S;
} else {
S = Math.sqrt(1 + this[10] - this[0] - this[5]) * 2;
out[3] = (this[1] - this[4]) / S;
out[0] = (this[8] + this[2]) / S;
out[1] = (this[6] + this[9]) / S;
out[2] = 0.25 * S;
}
return out;
}
toNormalMat3(out) {
const a00 = this[0], a01 = this[1], a02 = this[2], a03 = this[3], a10 = this[4], a11 = this[5], a12 = this[6], a13 = this[7], a20 = this[8], a21 = this[9], a22 = this[10], a23 = this[11], a30 = this[12], a31 = this[13], a32 = this[14], a33 = this[15], b00 = a00 * a11 - a01 * a10, b01 = a00 * a12 - a02 * a10, b02 = a00 * a13 - a03 * a10, b03 = a01 * a12 - a02 * a11, b04 = a01 * a13 - a03 * a11, b05 = a02 * a13 - a03 * a12, b06 = a20 * a31 - a21 * a30, b07 = a20 * a32 - a22 * a30, b08 = a20 * a33 - a23 * a30, b09 = a21 * a32 - a22 * a31, b10 = a21 * a33 - a23 * a31, b11 = a22 * a33 - a23 * a32;
let det = b00 * b11 - b01 * b10 + b02 * b09 + b03 * b08 - b04 * b07 + b05 * b06;
out = out || [0, 0, 0, 0, 0, 0, 0, 0, 0];
if (!det)
return out;
det = 1 / det;
out[0] = (a11 * b11 - a12 * b10 + a13 * b09) * det;
out[1] = (a12 * b08 - a10 * b11 - a13 * b07) * det;
out[2] = (a10 * b10 - a11 * b08 + a13 * b06) * det;
out[3] = (a02 * b10 - a01 * b11 - a03 * b09) * det;
out[4] = (a00 * b11 - a02 * b08 + a03 * b07) * det;
out[5] = (a01 * b08 - a00 * b10 - a03 * b06) * det;
out[6] = (a31 * b05 - a32 * b04 + a33 * b03) * det;
out[7] = (a32 * b02 - a30 * b05 - a33 * b01) * det;
out[8] = (a30 * b04 - a31 * b02 + a33 * b00) * det;
return out;
}
fromPerspective(fovy, aspect, near, far) {
const f = 1 / Math.tan(fovy * 0.5), nf = 1 / (near - far);
this[0] = f / aspect;
this[1] = 0;
this[2] = 0;
this[3] = 0;
this[4] = 0;
this[5] = f;
this[6] = 0;
this[7] = 0;
this[8] = 0;
this[9] = 0;
this[10] = (far + near) * nf;
this[11] = -1;
this[12] = 0;
this[13] = 0;
this[14] = 2 * far * near * nf;
this[15] = 0;
return this;
}
fromOrtho(left, right, bottom, top, near, far) {
const lr = 1 / (left - right), bt = 1 / (bottom - top), nf = 1 / (near - far);
this[0] = -2 * lr;
this[1] = 0;
this[2] = 0;
this[3] = 0;
this[4] = 0;
this[5] = -2 * bt;
this[6] = 0;
this[7] = 0;
this[8] = 0;
this[9] = 0;
this[10] = 2 * nf;
this[11] = 0;
this[12] = (left + right) * lr;
this[13] = (top + bottom) * bt;
this[14] = (far + near) * nf;
this[15] = 1;
return this;
}
fromMul(a, b) {
const a00 = a[0], a01 = a[1], a02 = a[2], a03 = a[3], a10 = a[4], a11 = a[5], a12 = a[6], a13 = a[7], a20 = a[8], a21 = a[9], a22 = a[10], a23 = a[11], a30 = a[12], a31 = a[13], a32 = a[14], a33 = a[15];
let b0 = b[0], b1 = b[1], b2 = b[2], b3 = b[3];
this[0] = b0 * a00 + b1 * a10 + b2 * a20 + b3 * a30;
this[1] = b0 * a01 + b1 * a11 + b2 * a21 + b3 * a31;
this[2] = b0 * a02 + b1 * a12 + b2 * a22 + b3 * a32;
this[3] = b0 * a03 + b1 * a13 + b2 * a23 + b3 * a33;
b0 = b[4];
b1 = b[5];
b2 = b[6];
b3 = b[7];
this[4] = b0 * a00 + b1 * a10 + b2 * a20 + b3 * a30;
this[5] = b0 * a01 + b1 * a11 + b2 * a21 + b3 * a31;
this[6] = b0 * a02 + b1 * a12 + b2 * a22 + b3 * a32;
this[7] = b0 * a03 + b1 * a13 + b2 * a23 + b3 * a33;
b0 = b[8];
b1 = b[9];
b2 = b[10];
b3 = b[11];
this[8] = b0 * a00 + b1 * a10 + b2 * a20 + b3 * a30;
this[9] = b0 * a01 + b1 * a11 + b2 * a21 + b3 * a31;
this[10] = b0 * a02 + b1 * a12 + b2 * a22 + b3 * a32;
this[11] = b0 * a03 + b1 * a13 + b2 * a23 + b3 * a33;
b0 = b[12];
b1 = b[13];
b2 = b[14];
b3 = b[15];
this[12] = b0 * a00 + b1 * a10 + b2 * a20 + b3 * a30;
this[13] = b0 * a01 + b1 * a11 + b2 * a21 + b3 * a31;
this[14] = b0 * a02 + b1 * a12 + b2 * a22 + b3 * a32;
this[15] = b0 * a03 + b1 * a13 + b2 * a23 + b3 * a33;
return this;
}
fromInvert(mat) {
const a00 = mat[0], a01 = mat[1], a02 = mat[2], a03 = mat[3], a10 = mat[4], a11 = mat[5], a12 = mat[6], a13 = mat[7], a20 = mat[8], a21 = mat[9], a22 = mat[10], a23 = mat[11], a30 = mat[12], a31 = mat[13], a32 = mat[14], a33 = mat[15], b00 = a00 * a11 - a01 * a10, b01 = a00 * a12 - a02 * a10, b02 = a00 * a13 - a03 * a10, b03 = a01 * a12 - a02 * a11, b04 = a01 * a13 - a03 * a11, b05 = a02 * a13 - a03 * a12, b06 = a20 * a31 - a21 * a30, b07 = a20 * a32 - a22 * a30, b08 = a20 * a33 - a23 * a30, b09 = a21 * a32 - a22 * a31, b10 = a21 * a33 - a23 * a31, b11 = a22 * a33 - a23 * a32;
let det = b00 * b11 - b01 * b10 + b02 * b09 + b03 * b08 - b04 * b07 + b05 * b06;
if (!det)
return this;
det = 1 / det;
this[0] = (a11 * b11 - a12 * b10 + a13 * b09) * det;
this[1] = (a02 * b10 - a01 * b11 - a03 * b09) * det;
this[2] = (a31 * b05 - a32 * b04 + a33 * b03) * det;
this[3] = (a22 * b04 - a21 * b05 - a23 * b03) * det;
this[4] = (a12 * b08 - a10 * b11 - a13 * b07) * det;
this[5] = (a00 * b11 - a02 * b08 + a03 * b07) * det;
this[6] = (a32 * b02 - a30 * b05 - a33 * b01) * det;
this[7] = (a20 * b05 - a22 * b02 + a23 * b01) * det;
this[8] = (a10 * b10 - a11 * b08 + a13 * b06) * det;
this[9] = (a01 * b08 - a00 * b10 - a03 * b06) * det;
this[10] = (a30 * b04 - a31 * b02 + a33 * b00) * det;
this[11] = (a21 * b02 - a20 * b04 - a23 * b00) * det;
this[12] = (a11 * b07 - a10 * b09 - a12 * b06) * det;
this[13] = (a00 * b09 - a01 * b07 + a02 * b06) * det;
this[14] = (a31 * b01 - a30 * b03 - a32 * b00) * det;
this[15] = (a20 * b03 - a21 * b01 + a22 * b00) * det;
return this;
}
fromAdjugate(a) {
const a00 = a[0], a01 = a[1], a02 = a[2], a03 = a[3], a10 = a[4], a11 = a[5], a12 = a[6], a13 = a[7], a20 = a[8], a21 = a[9], a22 = a[10], a23 = a[11], a30 = a[12], a31 = a[13], a32 = a[14], a33 = a[15], b00 = a00 * a11 - a01 * a10, b01 = a00 * a12 - a02 * a10, b02 = a00 * a13 - a03 * a10, b03 = a01 * a12 - a02 * a11, b04 = a01 * a13 - a03 * a11, b05 = a02 * a13 - a03 * a12, b06 = a20 * a31 - a21 * a30, b07 = a20 * a32 - a22 * a30, b08 = a20 * a33 - a23 * a30, b09 = a21 * a32 - a22 * a31, b10 = a21 * a33 - a23 * a31, b11 = a22 * a33 - a23 * a32;
this[0] = a11 * b11 - a12 * b10 + a13 * b09;
this[1] = a02 * b10 - a01 * b11 - a03 * b09;
this[2] = a31 * b05 - a32 * b04 + a33 * b03;
this[3] = a22 * b04 - a21 * b05 - a23 * b03;
this[4] = a12 * b08 - a10 * b11 - a13 * b07;
this[5] = a00 * b11 - a02 * b08 + a03 * b07;
this[6] = a32 * b02 - a30 * b05 - a33 * b01;
this[7] = a20 * b05 - a22 * b02 + a23 * b01;
this[8] = a10 * b10 - a11 * b08 + a13 * b06;
this[9] = a01 * b08 - a00 * b10 - a03 * b06;
this[10] = a30 * b04 - a31 * b02 + a33 * b00;
this[11] = a21 * b02 - a20 * b04 - a23 * b00;
this[12] = a11 * b07 - a10 * b09 - a12 * b06;
this[13] = a00 * b09 - a01 * b07 + a02 * b06;
this[14] = a31 * b01 - a30 * b03 - a32 * b00;
this[15] = a20 * b03 - a21 * b01 + a22 * b00;
return this;
}
fromFrustum(left, right, bottom, top, near, far) {
const rl = 1 / (right - left);
const tb = 1 / (top - bottom);
const nf = 1 / (near - far);
this[0] = near * 2 * rl;
this[1] = 0;
this[2] = 0;
this[3] = 0;
this[4] = 0;
this[5] = near * 2 * tb;
this[6] = 0;
this[7] = 0;
this[8] = (right + left) * rl;
this[9] = (top + bottom) * tb;
this[10] = (far + near) * nf;
this[11] = -1;
this[12] = 0;
this[13] = 0;
this[14] = far * near * 2 * nf;
this[15] = 0;
return this;
}
fromQuatTranScale(q, v, s) {
const x = q[0], y = q[1], z = q[2], w = q[3], x2 = x + x, y2 = y + y, z2 = z + z, xx = x * x2, xy = x * y2, xz = x * z2, yy = y * y2, yz = y * z2, zz = z * z2, wx = w * x2, wy = w * y2, wz = w * z2, sx = s[0], sy = s[1], sz = s[2];
this[0] = (1 - (yy + zz)) * sx;
this[1] = (xy + wz) * sx;
this[2] = (xz - wy) * sx;
this[3] = 0;
this[4] = (xy - wz) * sy;
this[5] = (1 - (xx + zz)) * sy;
this[6] = (yz + wx) * sy;
this[7] = 0;
this[8] = (xz + wy) * sz;
this[9] = (yz - wx) * sz;
this[10] = (1 - (xx + yy)) * sz;
this[11] = 0;
this[12] = v[0];
this[13] = v[1];
this[14] = v[2];
this[15] = 1;
return this;
}
fromQuatTran(q, v) {
const x = q[0], y = q[1], z = q[2], w = q[3], x2 = x + x, y2 = y + y, z2 = z + z, xx = x * x2, xy = x * y2, xz = x * z2, yy = y * y2, yz = y * z2, zz = z * z2, wx = w * x2, wy = w * y2, wz = w * z2;
this[0] = 1 - (yy + zz);
this[1] = xy + wz;
this[2] = xz - wy;
this[3] = 0;
this[4] = xy - wz;
this[5] = 1 - (xx + zz);
this[6] = yz + wx;
this[7] = 0;
this[8] = xz + wy;
this[9] = yz - wx;
this[10] = 1 - (xx + yy);
this[11] = 0;
this[12] = v[0];
this[13] = v[1];
this[14] = v[2];
this[15] = 1;
return this;
}
fromQuat(q) {
const x = q[0], y = q[1], z = q[2], w = q[3], x2 = x + x, y2 = y + y, z2 = z + z, xx = x * x2, xy = x * y2, xz = x * z2, yy = y * y2, yz = y * z2, zz = z * z2, wx = w * x2, wy = w * y2, wz = w * z2;
this[0] = 1 - (yy + zz);
this[1] = xy + wz;
this[2] = xz - wy;
this[3] = 0;
this[4] = xy - wz;
this[5] = 1 - (xx + zz);
this[6] = yz + wx;
this[7] = 0;
this[8] = xz + wy;
this[9] = yz - wx;
this[10] = 1 - (xx + yy);
this[11] = 0;
this[12] = 0;
this[13] = 0;
this[14] = 0;
this[15] = 1;
return this;
}
fromQuatTranScaleOrigin(q, v, s, o) {
const x = q[0], y = q[1], z = q[2], w = q[3];
const x2 = x + x;
const y2 = y + y;
const z2 = z + z;
const xx = x * x2;
const xy = x * y2;
const xz = x * z2;
const yy = y * y2;
const yz = y * z2;
const zz = z * z2;
const wx = w * x2;
const wy = w * y2;
const wz = w * z2;
const sx = s[0];
const sy = s[1];
const sz = s[2];
const ox = o[0];
const oy = o[1];
const oz = o[2];
const out0 = (1 - (yy + zz)) * sx;
const out1 = (xy + wz) * sx;
const out2 = (xz - wy) * sx;
const out4 = (xy - wz) * sy;
const out5 = (1 - (xx + zz)) * sy;
const out6 = (yz + wx) * sy;
const out8 = (xz + wy) * sz;
const out9 = (yz - wx) * sz;
const out10 = (1 - (xx + yy)) * sz;
this[0] = out0;
this[1] = out1;
this[2] = out2;
this[3] = 0;
this[4] = out4;
this[5] = out5;
this[6] = out6;
this[7] = 0;
this[8] = out8;
this[9] = out9;
this[10] = out10;
this[11] = 0;
this[12] = v[0] + ox - (out0 * ox + out4 * oy + out8 * oz);
this[13] = v[1] + oy - (out1 * ox + out5 * oy + out9 * oz);
this[14] = v[2] + oz - (out2 * ox + out6 * oy + out10 * oz);
this[15] = 1;
return this;
}
fromDualQuat(a) {
const bx = -a[0], by = -a[1], bz = -a[2], bw = a[3], ax = a[4], ay = a[5], az = a[6], aw = a[7];
const translation = [0, 0, 0];
let magnitude = bx * bx + by * by + bz * bz + bw * bw;
if (magnitude > 0) {
magnitude = 1 / magnitude;
translation[0] = (ax * bw + aw * bx + ay * bz - az * by) * 2 * magnitude;
translation[1] = (ay * bw + aw * by + az * bx - ax * bz) * 2 * magnitude;
translation[2] = (az * bw + aw * bz + ax * by - ay * bx) * 2 * magnitude;
} else {
translation[0] = (ax * bw + aw * bx + ay * bz - az * by) * 2;
translation[1] = (ay * bw + aw * by + az * bx - ax * bz) * 2;
translation[2] = (az * bw + aw * bz + ax * by - ay * bx) * 2;
}
this.fromQuatTran(a, translation);
return this;
}
fromAxisAngle(axis, rad) {
let x = axis[0], y = axis[1], z = axis[2], len = Math.hypot(x, y, z);
if (len < 1e-6)
return this;
len = 1 / len;
x *= len;
y *= len;
z *= len;
const s = Math.sin(rad);
const c = Math.cos(rad);
const t = 1 - c;
this[0] = x * x * t + c;
this[1] = y * x * t + z * s;
this[2] = z * x * t - y * s;
this[3] = 0;
this[4] = x * y * t - z * s;
this[5] = y * y * t + c;
this[6] = z * y * t + x * s;
this[7] = 0;
this[8] = x * z * t + y * s;
this[9] = y * z * t - x * s;
this[10] = z * z * t + c;
this[11] = 0;
this[12] = 0;
this[13] = 0;
this[14] = 0;
this[15] = 1;
return this;
}
fromRotX(rad) {
const s = Math.sin(rad), c = Math.cos(rad);
this[0] = 1;
this[1] = 0;
this[2] = 0;
this[3] = 0;
this[4] = 0;
this[5] = c;
this[6] = s;
this[7] = 0;
this[8] = 0;
this[9] = -s;
this[10] = c;
this[11] = 0;
this[12] = 0;
this[13] = 0;
this[14] = 0;
this[15] = 1;
return this;
}
fromRotY(rad) {
const s = Math.sin(rad), c = Math.cos(rad);
this[0] = c;
this[1] = 0;
this[2] = -s;
this[3] = 0;
this[4] = 0;
this[5] = 1;
this[6] = 0;
this[7] = 0;
this[8] = s;
this[9] = 0;
this[10] = c;
this[11] = 0;
this[12] = 0;
this[13] = 0;
this[14] = 0;
this[15] = 1;
return this;
}
fromRotZ(rad) {
const s = Math.sin(rad), c = Math.cos(rad);
this[0] = c;
this[1] = s;
this[2] = 0;
this[3] = 0;
this[4] = -s;
this[5] = c;
this[6] = 0;
this[7] = 0;
this[8] = 0;
this[9] = 0;
this[10] = 1;
this[11] = 0;
this[12] = 0;
this[13] = 0;
this[14] = 0;
this[15] = 1;
return this;
}
fromLook(eye, center, up) {
let x0, x1, x2, y0, y1, y2, z0, z1, z2, len;
const eyex = eye[0];
const eyey = eye[1];
const eyez = eye[2];
const upx = up[0];
const upy = up[1];
const upz = up[2];
const centerx = center[0];
const centery = center[1];
const centerz = center[2];
if (Math.abs(eyex - centerx) < 1e-6 && Math.abs(eyey - centery) < 1e-6 && Math.abs(eyez - centerz) < 1e-6) {
this.identity();
return this;
}
z0 = eyex - centerx;
z1 = eyey - centery;
z2 = eyez - centerz;
len = 1 / Math.sqrt(z0 * z0 + z1 * z1 + z2 * z2);
z0 *= len;
z1 *= len;
z2 *= len;
x0 = upy * z2 - upz * z1;
x1 = upz * z0 - upx * z2;
x2 = upx * z1 - upy * z0;
len = Math.sqrt(x0 * x0 + x1 * x1 + x2 * x2);
if (!len) {
x0 = 0;
x1 = 0;
x2 = 0;
} else {
len = 1 / len;
x0 *= len;
x1 *= len;
x2 *= len;
}
y0 = z1 * x2 - z2 * x1;
y1 = z2 * x0 - z0 * x2;
y2 = z0 * x1 - z1 * x0;
len = Math.sqrt(y0 * y0 + y1 * y1 + y2 * y2);
if (!len) {
y0 = 0;
y1 = 0;
y2 = 0;
} else {
len = 1 / len;
y0 *= len;
y1 *= len;
y2 *= len;
}
this[0] = x0;
this[1] = y0;
this[2] = z0;
this[3] = 0;
this[4] = x1;
this[5] = y1;
this[6] = z1;
this[7] = 0;
this[8] = x2;
this[9] = y2;
this[10] = z2;
this[11] = 0;
this[12] = -(x0 * eyex + x1 * eyey + x2 * eyez);
this[13] = -(y0 * eyex + y1 * eyey + y2 * eyez);
this[14] = -(z0 * eyex + z1 * eyey + z2 * eyez);
this[15] = 1;
return this;
}
fromTarget(eye, target, up) {
const eyex = eye[0], eyey = eye[1], eyez = eye[2], upx = up[0], upy = up[1], upz = up[2];
let z0 = eyex - target[0], z1 = eyey - target[1], z2 = eyez - target[2], len = z0 * z0 + z1 * z1 + z2 * z2;
if (len > 0) {
len = 1 / Math.sqrt(len);
z0 *= len;
z1 *= len;
z2 *= len;
}
let x0 = upy * z2 - upz * z1, x1 = upz * z0 - upx * z2, x2 = upx * z1 - upy * z0;
len = x0 * x0 + x1 * x1 + x2 * x2;
if (len > 0) {
len = 1 / Math.sqrt(len);
x0 *= len;
x1 *= len;
x2 *= len;
}
this[0] = x0;
this[1] = x1;
this[2] = x2;
this[3] = 0;
this[4] = z1 * x2 - z2 * x1;
this[5] = z2 * x0 - z0 * x2;
this[6] = z0 * x1 - z1 * x0;
this[7] = 0;
this[8] = z0;
this[9] = z1;
this[10] = z2;
this[11] = 0;
this[12] = eyex;
this[13] = eyey;
this[14] = eyez;
this[15] = 1;
return this;
}
fromBuf(ary, idx) {
this[0] = ary[idx];
this[1] = ary[idx + 1];
this[2] = ary[idx + 2];
this[3] = ary[idx + 3];
this[4] = ary[idx + 4];
this[5] = ary[idx + 5];
this[6] = ary[idx + 6];
this[7] = ary[idx + 7];
this[8] = ary[idx + 8];
this[9] = ary[idx + 9];
this[10] = ary[idx + 10];
this[11] = ary[idx + 11];
this[12] = ary[idx + 12];
this[13] = ary[idx + 13];
this[14] = ary[idx + 14];
this[15] = ary[idx + 15];
return this;
}
toBuf(ary, idx) {
ary[idx] = this[0];
ary[idx + 1] = this[1];
ary[idx + 2] = this[2];
ary[idx + 3] = this[3];
ary[idx + 4] = this[4];
ary[idx + 5] = this[5];
ary[idx + 6] = this[6];
ary[idx + 7] = this[7];
ary[idx + 8] = this[8];
ary[idx + 9] = this[9];
ary[idx + 10] = this[10];
ary[idx + 11] = this[11];
ary[idx + 12] = this[12];
ary[idx + 13] = this[13];
ary[idx + 14] = this[14];
ary[idx + 15] = this[15];
return this;
}
add(b) {
this[0] = this[0] + b[0];
this[1] = this[1] + b[1];
this[2] = this[2] + b[2];
this[3] = this[3] + b[3];
this[4] = this[4] + b[4];
this[5] = this[5] + b[5];
this[6] = this[6] + b[6];
this[7] = this[7] + b[7];
this[8] = this[8] + b[8];
this[9] = this[9] + b[9];
this[10] = this[10] + b[10];
this[11] = this[11] + b[11];
this[12] = this[12] + b[12];
this[13] = this[13] + b[13];
this[14] = this[14] + b[14];
this[15] = this[15] + b[15];
return this;
}
sub(b) {
this[0] = this[0] - b[0];
this[1] = this[1] - b[1];
this[2] = this[2] - b[2];
this[3] = this[3] - b[3];
this[4] = this[4] - b[4];
this[5] = this[5] - b[5];
this[6] = this[6] - b[6];
this[7] = this[7] - b[7];
this[8] = this[8] - b[8];
this[9] = this[9] - b[9];
this[10] = this[10] - b[10];
this[11] = this[11] - b[11];
this[12] = this[12] - b[12];
this[13] = this[13] - b[13];
this[14] = this[14] - b[14];
this[15] = this[15] - b[15];
return this;
}
mul(b) {
const a00 = this[0], a01 = this[1], a02 = this[2], a03 = this[3], a10 = this[4], a11 = this[5], a12 = this[6], a13 = this[7], a20 = this[8], a21 = this[9], a22 = this[10], a23 = this[11], a30 = this[12], a31 = this[13], a32 = this[14], a33 = this[15];
let b0 = b[0], b1 = b[1], b2 = b[2], b3 = b[3];
this[0] = b0 * a00 + b1 * a10 + b2 * a20 + b3 * a30;
this[1] = b0 * a01 + b1 * a11 + b2 * a21 + b3 * a31;
this[2] = b0 * a02 + b1 * a12 + b2 * a22 + b3 * a32;
this[3] = b0 * a03 + b1 * a13 + b2 * a23 + b3 * a33;
b0 = b[4];
b1 = b[5];
b2 = b[6];
b3 = b[7];
this[4] = b0 * a00 + b1 * a10 + b2 * a20 + b3 * a30;
this[5] = b0 * a01 + b1 * a11 + b2 * a21 + b3 * a31;
this[6] = b0 * a02 + b1 * a12 + b2 * a22 + b3 * a32;
this[7] = b0 * a03 + b1 * a13 + b2 * a23 + b3 * a33;
b0 = b[8];
b1 = b[9];
b2 = b[10];
b3 = b[11];
this[8] = b0 * a00 + b1 * a10 + b2 * a20 + b3 * a30;
this[9] = b0 * a01 + b1 * a11 + b2 * a21 + b3 * a31;
this[10] = b0 * a02 + b1 * a12 + b2 * a22 + b3 * a32;
this[11] = b0 * a03 + b1 * a13 + b2 * a23 + b3 * a33;
b0 = b[12];
b1 = b[13];
b2 = b[14];
b3 = b[15];
this[12] = b0 * a00 + b1 * a10 + b2 * a20 + b3 * a30;
this[13] = b0 * a01 + b1 * a11 + b2 * a21 + b3 * a31;
this[14] = b0 * a02 + b1 * a12 + b2 * a22 + b3 * a32;
this[15] = b0 * a03 + b1 * a13 + b2 * a23 + b3 * a33;
return this;
}
pmul(b) {
const a00 = b[0], a01 = b[1], a02 = b[2], a03 = b[3], a10 = b[4], a11 = b[5], a12 = b[6], a13 = b[7], a20 = b[8], a21 = b[9], a22 = b[10], a23 = b[11], a30 = b[12], a31 = b[13], a32 = b[14], a33 = b[15];
let b0 = this[0], b1 = this[1], b2 = this[2], b3 = this[3];
this[0] = b0 * a00 + b1 * a10 + b2 * a20 + b3 * a30;
this[1] = b0 * a01 + b1 * a11 + b2 * a21 + b3 * a31;
this[2] = b0 * a02 + b1 * a12 + b2 * a22 + b3 * a32;
this[3] = b0 * a03 + b1 * a13 + b2 * a23 + b3 * a33;
b0 = this[4];
b1 = this[5];
b2 = this[6];
b3 = this[7];
this[4] = b0 * a00 + b1 * a10 + b2 * a20 + b3 * a30;
this[5] = b0 * a01 + b1 * a11 + b2 * a21 + b3 * a31;
this[6] = b0 * a02 + b1 * a12 + b2 * a22 + b3 * a32;
this[7] = b0 * a03 + b1 * a13 + b2 * a23 + b3 * a33;
b0 = this[8];
b1 = this[9];
b2 = this[10];
b3 = this[11];
this[8] = b0 * a00 + b1 * a10 + b2 * a20 + b3 * a30;
this[9] = b0 * a01 + b1 * a11 + b2 * a21 + b3 * a31;
this[10] = b0 * a02 + b1 * a12 + b2 * a22 + b3 * a32;
this[11] = b0 * a03 + b1 * a13 + b2 * a23 + b3 * a33;
b0 = this[12];
b1 = this[13];
b2 = this[14];
b3 = this[15];
this[12] = b0 * a00 + b1 * a10 + b2 * a20 + b3 * a30;
this[13] = b0 * a01 + b1 * a11 + b2 * a21 + b3 * a31;
this[14] = b0 * a02 + b1 * a12 + b2 * a22 + b3 * a32;
this[15] = b0 * a03 + b1 * a13 + b2 * a23 + b3 * a33;
return this;
}
invert() {
const a00 = this[0], a01 = this[1], a02 = this[2], a03 = this[3], a10 = this[4], a11 = this[5], a12 = this[6], a13 = this[7], a20 = this[8], a21 = this[9], a22 = this[10], a23 = this[11], a30 = this[12], a31 = this[13], a32 = this[14], a33 = this[15], b00 = a00 * a11 - a01 * a10, b01 = a00 * a12 - a02 * a10, b02 = a00 * a13 - a03 * a10, b03 = a01 * a12 - a02 * a11, b04 = a01 * a13 - a03 * a11, b05 = a02 * a13 - a03 * a12, b06 = a20 * a31 - a21 * a30, b07 = a20 * a32 - a22 * a30, b08 = a20 * a33 - a23 * a30, b09 = a21 * a32 - a22 * a31, b10 = a21 * a33 - a23 * a31, b11 = a22 * a33 - a23 * a32;
let det = b00 * b11 - b01 * b10 + b02 * b09 + b03 * b08 - b04 * b07 + b05 * b06;
if (!det)
return this;
det = 1 / det;
this[0] = (a11 * b11 - a12 * b10 + a13 * b09) * det;
this[1] = (a02 * b10 - a01 * b11 - a03 * b09) * det;
this[2] = (a31 * b05 - a32 * b04 + a33 * b03) * det;
this[3] = (a22 * b04 - a21 * b05 - a23 * b03) * det;
this[4] = (a12 * b08 - a10 * b11 - a13 * b07) * det;
this[5] = (a00 * b11 - a02 * b08 + a03 * b07) * det;
this[6] = (a32 * b02 - a30 * b05 - a33 * b01) * det;
this[7] = (a20 * b05 - a22 * b02 + a23 * b01) * det;
this[8] = (a10 * b10 - a11 * b08 + a13 * b06) * det;
this[9] = (a01 * b08 - a00 * b10 - a03 * b06) * det;
this[10] = (a30 * b04 - a31 * b02 + a33 * b00) * det;
this[11] = (a21 * b02 - a20 * b04 - a23 * b00) * det;
this[12] = (a11 * b07 - a10 * b09 - a12 * b06) * det;
this[13] = (a00 * b09 - a01 * b07 + a02 * b06) * det;
this[14] = (a31 * b01 - a30 * b03 - a32 * b00) * det;
this[15] = (a20 * b03 - a21 * b01 + a22 * b00) * det;
return this;
}
translate(v, y, z) {
let xx, yy, zz;
if (v instanceof Float32Array || v instanceof Array && v.length == 3) {
xx = v[0];
yy = v[1];
zz = v[2];
} else if (typeof v === "number" && typeof y === "number" && typeof z === "number") {
xx = v;
yy = y;
zz = z;
} else
return this;
this[12] = this[0] * xx + this[4] * yy + this[8] * zz + this[12];
this[13] = this[1] * xx + this[5] * yy + this[9] * zz + this[13];
this[14] = this[2] * xx + this[6] * yy + this[10] * zz + this[14];
this[15] = this[3] * xx + this[7] * yy + this[11] * zz + this[15];
return this;
}
scale(x, y, z) {
if (y == void 0)
y = x;
if (z == void 0)
z = x;
this[0] *= x;
this[1] *= x;
this[2] *= x;
this[3] *= x;
this[4] *= y;
this[5] *= y;
this[6] *= y;
this[7] *= y;
this[8] *= z;
this[9] *= z;
this[10] *= z;
this[11] *= z;
return this;
}
transpose() {
const a01 = this[1], a02 = this[2], a03 = this[3], a12 = this[6], a13 = this[7], a23 = this[11];
this[1] = this[4];
this[2] = this[8];
this[3] = this[12];
this[4] = a01;
this[6] = this[9];
this[7] = this[13];
this[8] = a02;
this[9] = a12;
this[11] = this[14];
this[12] = a03;
this[13] = a13;
this[14] = a23;
return this;
}
decompose(out_r, out_t, out_s) {
out_t[0] = this[12];
out_t[1] = this[13];
out_t[2] = this[14];
const m11 = this[0];
const m12 = this[1];
const m13 = this[2];
const m21 = this[4];
const m22 = this[5];
const m23 = this[6];
const m31 = this[8];
const m32 = this[9];
const m33 = this[10];
out_s[0] = Math.hypot(m11, m12, m13);
out_s[1] = Math.hypot(m21, m22, m23);
out_s[2] = Math.hypot(m31, m32, m33);
const is1 = 1 / out_s[0];
const is2 = 1 / out_s[1];
const is3 = 1 / out_s[2];
const sm11 = m11 * is1;
const sm12 = m12 * is2;
const sm13 = m13 * is3;
const sm21 = m21 * is1;
const sm22 = m22 * is2;
const sm23 = m23 * is3;
const sm31 = m31 * is1;
const sm32 = m32 * is2;
const sm33 = m33 * is3;
const trace = sm11 + sm22 + sm33;
let S = 0;
if (trace > 0) {
S = Math.sqrt(trace + 1) * 2;
out_r[3] = 0.25 * S;
out_r[0] = (sm23 - sm32) / S;
out_r[1] = (sm31 - sm13) / S;
out_r[2] = (sm12 - sm21) / S;
} else if (sm11 > sm22 && sm11 > sm33) {
S = Math.sqrt(1 + sm11 - sm22 - sm33) * 2;
out_r[3] = (sm23 - sm32) / S;
out_r[0] = 0.25 * S;
out_r[1] = (sm12 + sm21) / S;
out_r[2] = (sm31 + sm13) / S;
} else if (sm22 > sm33) {
S = Math.sqrt(1 + sm22 - sm11 - sm33) * 2;
out_r[3] = (sm31 - sm13) / S;
out_r[0] = (sm12 + sm21) / S;
out_r[1] = 0.25 * S;
out_r[2] = (sm23 + sm32) / S;
} else {
S = Math.sqrt(1 + sm33 - sm11 - sm22) * 2;
out_r[3] = (sm12 - sm21) / S;
out_r[0] = (sm31 + sm13) / S;
out_r[1] = (sm23 + sm32) / S;
out_r[2] = 0.25 * S;
}
return this;
}
rotX(rad) {
const s = Math.sin(rad), c = Math.cos(rad), a10 = this[4], a11 = this[5], a12 = this[6], a13 = this[7], a20 = this[8], a21 = this[9], a22 = this[10], a23 = this[11];
this[4] = a10 * c + a20 * s;
this[5] = a11 * c + a21 * s;
this[6] = a12 * c + a22 * s;
this[7] = a13 * c + a23 * s;
this[8] = a20 * c - a10 * s;
this[9] = a21 * c - a11 * s;
this[10] = a22 * c - a12 * s;
this[11] = a23 * c - a13 * s;
return this;
}
rotY(rad) {
const s = Math.sin(rad), c = Math.cos(rad), a00 = this[0], a01 = this[1], a02 = this[2], a03 = this[3], a20 = this[8], a21 = this[9], a22 = this[10], a23 = this[11];
this[0] = a00 * c - a20 * s;
this[1] = a01 * c - a21 * s;
this[2] = a02 * c - a22 * s;
this[3] = a03 * c - a23 * s;
this[8] = a00 * s + a20 * c;
this[9] = a01 * s + a21 * c;
this[10] = a02 * s + a22 * c;
this[11] = a03 * s + a23 * c;
return this;
}
rotZ(rad) {
const s = Math.sin(rad), c = Math.cos(rad), a00 = this[0], a01 = this[1], a02 = this[2], a03 = this[3], a10 = this[4], a11 = this[5], a12 = this[6], a13 = this[7];
this[0] = a00 * c + a10 * s;
this[1] = a01 * c + a11 * s;
this[2] = a02 * c + a12 * s;
this[3] = a03 * c + a13 * s;
this[4] = a10 * c - a00 * s;
this[5] = a11 * c - a01 * s;
this[6] = a12 * c - a02 * s;
this[7] = a13 * c - a03 * s;
return this;
}
rotAxisAngle(axis, rad) {
let x = axis[0], y = axis[1], z = axis[2], len = Math.sqrt(x * x + y * y + z * z);
if (Math.abs(len) < 1e-6)
return this;
len = 1 / len;
x *= len;
y *= len;
z *= len;
const s = Math.sin(rad);
const c = Math.cos(rad);
const t = 1 - c;
const a00 = this[0];
const a01 = this[1];
const a02 = this[2];
const a03 = this[3];
const a10 = this[4];
const a11 = this[5];
const a12 = this[6];
const a13 = this[7];
const a20 = this[8];
const a21 = this[9];
const a22 = this[10];
const a23 = this[11];
const b00 = x * x * t + c;
const b01 = y * x * t + z * s;
const b02 = z * x * t - y * s;
const b10 = x * y * t - z * s;
const b11 = y * y * t + c;
const b12 = z * y * t + x * s;
const b20 = x * z * t + y * s;
const b21 = y * z * t - x * s;
const b22 = z * z * t + c;
this[0] = a00 * b00 + a10 * b01 + a20 * b02;
this[1] = a01 * b00 + a11 * b01 + a21 * b02;
this[2] = a02 * b00 + a12 * b01 + a22 * b02;
this[3] = a03 * b00 + a13 * b01 + a23 * b02;
this[4] = a00 * b10 + a10 * b11 + a20 * b12;
this[5] = a01 * b10 + a11 * b11 + a21 * b12;
this[6] = a02 * b10 + a12 * b11 + a22 * b12;
this[7] = a03 * b10 + a13 * b11 + a23 * b12;
this[8] = a00 * b20 + a10 * b21 + a20 * b22;
this[9] = a01 * b20 + a11 * b21 + a21 * b22;
this[10] = a02 * b20 + a12 * b21 + a22 * b22;
this[11] = a03 * b20 + a13 * b21 + a23 * b22;
return this;
}
transformVec3(v, out) {
const x = v[0], y = v[1], z = v[2];
out = out || v;
out[0] = this[0] * x + this[4] * y + this[8] * z + this[12];
out[1] = this[1] * x + this[5] * y + this[9] * z + this[13];
out[2] = this[2] * x + this[6] * y + this[10] * z + this[14];
return out;
}
transformVec4(v, out) {
const x = v[0], y = v[1], z = v[2], w = v[3];
out = out || v;
out[0] = this[0] * x + this[4] * y + this[8] * z + this[12] * w;
out[1] = this[1] * x + this[5] * y + this[9] * z + this[13] * w;
out[2] = this[2] * x + this[6] * y + this[10] * z + this[14] * w;
out[3] = this[3] * x + this[7] * y + this[11] * z + this[15] * w;
return out;
}
static mul(a, b) {
return new Mat4().fromMul(a, b);
}
static invert(a) {
return new Mat4().fromInvert(a);
}
}class Transform {
rot = new Quat();
pos = new Vec3(0);
scl = new Vec3(1);
constructor(rot, pos, scl) {
if (rot instanceof Transform)
this.copy(rot);
else if (rot && pos && scl)
this.set(rot, pos, scl);
}
reset() {
this.rot.identity();
this.pos.xyz(0, 0, 0);
this.scl.xyz(1, 1, 1);
return this;
}
copy(t) {
this.rot.copy(t.rot);
this.pos.copy(t.pos);
this.scl.copy(t.scl);
return this;
}
set(r, p, s) {
if (r)
this.rot.copy(r);
if (p)
this.pos.copy(p);
if (s)
this.scl.copy(s);
return this;
}
clone() {
return new Transform(this);
}
mul(cr, cp, cs) {
if (cr instanceof Transform) {
cp = cr.pos;
cs = cr.scl;
cr = cr.rot;
}
if (cr && cp) {
this.pos.add(new Vec3(this.scl).mul(cp).transformQuat(this.rot));
if (cs)
this.scl.mul(cs);
this.rot.mul(cr);
}
return this;
}
pmul(pr, pp, ps) {
if (pr instanceof Transform) {
pp = pr.pos;
ps = pr.scl;
pr = pr.rot;
}
if (!pr || !pp || !ps)
return this;
this.pos.mul(ps).transformQuat(pr).add(pp);
if (ps)
this.scl.mul(ps);
this.rot.pmul(pr);
return this;
}
addPos(cp, ignoreScl = false) {
if (ignoreScl)
this.pos.add(new Vec3().fromQuat(this.rot, cp));
else
this.pos.add(new Vec3().fromMul(cp, this.scl).transformQuat(this.rot));
return this;
}
pivotRot(pivot, q) {
this.rot.pmul(q);
const offset = new Vec3().fromSub(this.pos, pivot).transformQuat(q);
this.pos[0] = pivot[0] + offset[0];
this.pos[1] = pivot[1] + offset[1];
this.pos[2] = pivot[2] + offset[2];
return this;
}
fromMul(tp, tc) {
const v = new Vec3().fromMul(tp.scl, tc.pos).transformQuat(tp.rot);
this.pos.fromAdd(tp.pos, v);
this.scl.fromMul(tp.scl, tc.scl);
this.rot.fromMul(tp.rot, tc.rot);
return this;
}
fromInvert(t) {
this.rot.fromInvert(t.rot);
this.scl.fromInvert(t.scl);
this.pos.fromNegate(t.pos).mul(this.scl).transformQuat(this.rot);
return this;
}
transformVec3(v, out) {
const vx = v[0] * this.scl[0];
const vy = v[1] * this.scl[1];
const vz = v[2] * this.scl[2];
const qx = this.rot[0];
const qy = this.rot[1];
const qz = this.rot[2];
const qw = this.rot[3];
const x1 = qy * vz - qz * vy;
const y1 = qz * vx - qx * vz;
const z1 = qx * vy - qy * vx;
const x2 = qw * x1 + qy * z1 - qz * y1;
const y2 = qw * y1 + qz * x1 - qx * z1;
const z2 = qw * z1 + qx * y1 - qy * x1;
const rtn = out || v;
rtn[0] = vx + 2 * x2 + this.pos[0];
rtn[1] = vy + 2 * y2 + this.pos[1];
rtn[2] = vz + 2 * z2 + this.pos[2];
return rtn;
}
}class DualQuat extends Array {
constructor(q, t) {
super(8);
if (q && t)
this.fromQuatTran(q, t);
else if (q) {
this[0] = q[0];
this[1] = q[1];
this[2] = q[2];
this[3] = q[3];
} else
this[3] = 1;
}
reset() {
this[0] = 0;
this[1] = 0;
this[2] = 0;
this[3] = 1;
this[4] = 0;
this[5] = 0;
this[6] = 0;
this[7] = 0;
return this;
}
clone() {
const out = new DualQuat();
out[0] = this[0];
out[1] = this[1];
out[2] = this[2];
out[3] = this[3];
out[4] = this[4];
out[5] = this[5];
out[6] = this[6];
out[7] = this[7];
return out;
}
copy(a) {
this[0] = a[0];
this[1] = a[1];
this[2] = a[2];
this[3] = a[3];
this[4] = a[4];
this[5] = a[5];
this[6] = a[6];
this[7] = a[7];
return this;
}
lenSqr() {
return this[0] * this[0] + this[1] * this[1] + this[2] * this[2] + this[3] * this[3];
}
getTranslation(out = [0, 0, 0]) {
const ax = this[4], ay = this[5], az = this[6], aw = this[7], bx = -this[0], by = -this[1], bz = -this[2], bw = this[3];
out[0] = (ax * bw + aw * bx + ay * bz - az * by) * 2;
out[1] = (ay * bw + aw * by + az * bx - ax * bz) * 2;
out[2] = (az * bw + aw * bz + ax * by - ay * bx) * 2;
return out;
}
getQuat(out = [0, 0, 0, 0]) {
out[0] = this[0];
out[1] = this[1];
out[2] = this[2];
out[3] = this[3];
return out;
}
fromBuf(ary, idx) {
this[0] = ary[idx];
this[1] = ary[idx + 1];
this[2] = ary[idx + 2];
this[3] = ary[idx + 3];
this[4] = ary[idx + 4];
this[5] = ary[idx + 5];
this[6] = ary[idx + 6];
this[7] = ary[idx + 7];
return this;
}
toBuf(ary, idx) {
ary[idx] = this[0];
ary[idx + 1] = this[1];
ary[idx + 2] = this[2];
ary[idx + 3] = this[3];
ary[idx + 4] = this[4];
ary[idx + 5] = this[5];
ary[idx + 6] = this[6];
ary[idx + 7] = this[7];
return this;
}
fromQuatTran(q, t) {
const ax = t[0] * 0.5;
const ay = t[1] * 0.5;
const az = t[2] * 0.5;
const bx = q[0];
const by = q[1];
const bz = q[2];
const bw = q[3];
this[0] = bx;
this[1] = by;
this[2] = bz;
this[3] = bw;
this[4] = ax * bw + ay * bz - az * by;
this[5] = ay * bw + az * bx - ax * bz;
this[6] = az * bw + ax * by - ay * bx;
this[7] = -ax * bx - ay * by - az * bz;
return this;
}
fromTranslation(t) {
this[0] = 0;
this[1] = 0;
this[2] = 0;
this[3] = 1;
this[4] = t[0] * 0.5;
this[5] = t[1] * 0.5;
this[6] = t[2] * 0.5;
this[7] = 0;
return this;
}
fromQuat(q) {
this[0] = q[0];
this[1] = q[1];
this[2] = q[2];
this[3] = q[3];
this[4] = 0;
this[5] = 0;
this[6] = 0;
this[7] = 0;
return this;
}
fromMul(a, b) {
const ax0 = a[0], ay0 = a[1], az0 = a[2], aw0 = a[3];
const ax1 = a[4], ay1 = a[5], az1 = a[6], aw1 = a[7];
const bx0 = b[0], by0 = b[1], bz0 = b[2], bw0 = b[3];
const bx1 = b[4], by1 = b[5], bz1 = b[6], bw1 = b[7];
this[0] = ax0 * bw0 + aw0 * bx0 + ay0 * bz0 - az0 * by0;
this[1] = ay0 * bw0 + aw0 * by0 + az0 * bx0 - ax0 * bz0;
this[2] = az0 * bw0 + aw0 * bz0 + ax0 * by0 - ay0 * bx0;
this[3] = aw0 * bw0 - ax0 * bx0 - ay0 * by0 - az0 * bz0;
this[4] = ax0 * bw1 + aw0 * bx1 + ay0 * bz1 - az0 * by1 + ax1 * bw0 + aw1 * bx0 + ay1 * bz0 - az1 * by0;
this[5] = ay0 * bw1 + aw0 * by1 + az0 * bx1 - ax0 * bz1 + ay1 * bw0 + aw1 * by0 + az1 * bx0 - ax1 * bz0;
this[6] = az0 * bw1 + aw0 * bz1 + ax0 * by1 - ay0 * bx1 + az1 * bw0 + aw1 * bz0 + ax1 * by0 - ay1 * bx0;
this[7] = aw0 * bw1 - ax0 * bx1 - ay0 * by1 - az0 * bz1 + aw1 * bw0 - ax1 * bx0 - ay1 * by0 - az1 * bz0;
return this;
}
fromNorm(a) {
let magnitude = a[0] ** 2 + a[1] ** 2 + a[2] ** 2 + a[3] ** 2;
if (magnitude == 0)
return this;
magnitude = 1 / Math.sqrt(magnitude);
const a0 = a[0] * magnitude;
const a1 = a[1] * magnitude;
const a2 = a[2] * magnitude;
const a3 = a[3] * magnitude;
const b0 = a[4];
const b1 = a[5];
const b2 = a[6];
const b3 = a[7];
const a_dot_b = a0 * b0 + a1 * b1 + a2 * b2 + a3 * b3;
this[0] = a0;
this[1] = a1;
this[2] = a2;
this[3] = a3;
this[4] = (b0 - a0 * a_dot_b) * magnitude;
this[5] = (b1 - a1 * a_dot_b) * magnitude;
this[6] = (b2 - a2 * a_dot_b) * magnitude;
this[7] = (b3 - a3 * a_dot_b) * magnitude;
return this;
}
fromInvert(a) {
const sqlen = 1 / (a[0] * a[0] + a[1] * a[1] + a[2] * a[2] + a[3] * a[3]);
this[0] = -a[0] * sqlen;
this[1] = -a[1] * sqlen;
this[2] = -a[2] * sqlen;
this[3] = a[3] * sqlen;
this[4] = -a[4] * sqlen;
this[5] = -a[5] * sqlen;
this[6] = -a[6] * sqlen;
this[7] = a[7] * sqlen;
return this;
}
fromConjugate(a) {
this[0] = -a[0];
this[1] = -a[1];
this[2] = -a[2];
this[3] = a[3];
this[4] = -a[4];
this[5] = -a[5];
this[6] = -a[6];
this[7] = a[7];
return this;
}
add(q) {
this[0] = this[0] + q[0];
this[1] = this[1] + q[1];
this[2] = this[2] + q[2];
this[3] = this[3] + q[3];
this[4] = this[4] + q[4];
this[5] = this[5] + q[5];
this[6] = this[6] + q[6];
this[7] = this[7] + q[7];
return this;
}
mul(q) {
const ax0 = this[0], ay0 = this[1], az0 = this[2], aw0 = this[3];
const ax1 = this[4], ay1 = this[5], az1 = this[6], aw1 = this[7];
const bx0 = q[0], by0 = q[1], bz0 = q[2], bw0 = q[3];
const bx1 = q[4], by1 = q[5], bz1 = q[6], bw1 = q[7];
this[0] = ax0 * bw0 + aw0 * bx0 + ay0 * bz0 - az0 * by0;
this[1] = ay0 * bw0 + aw0 * by0 + az0 * bx0 - ax0 * bz0;
this[2] = az0 * bw0 + aw0 * bz0 + ax0 * by0 - ay0 * bx0;
this[3] = aw0 * bw0 - ax0 * bx0 - ay0 * by0 - az0 * bz0;
this[4] = ax0 * bw1 + aw0 * bx1 + ay0 * bz1 - az0 * by1 + ax1 * bw0 + aw1 * bx0 + ay1 * bz0 - az1 * by0;
this[5] = ay0 * bw1 + aw0 * by1 + az0 * bx1 - ax0 * bz1 + ay1 * bw0 + aw1 * by0 + az1 * bx0 - ax1 * bz0;
this[6] = az0 * bw1 + aw0 * bz1 + ax0 * by1 - ay0 * bx1 + az1 * bw0 + aw1 * bz0 + ax1 * by0 - ay1 * bx0;
this[7] = aw0 * bw1 - ax0 * bx1 - ay0 * by1 - az0 * bz1 + aw1 * bw0 - ax1 * bx0 - ay1 * by0 - az1 * bz0;
return this;
}
pmul(q) {
const ax0 = q[0], ay0 = q[1], az0 = q[2], aw0 = q[3];
const ax1 = q[4], ay1 = q[5], az1 = q[6], aw1 = q[7];
const bx0 = this[0], by0 = this[1], bz0 = this[2], bw0 = this[3];
const bx1 = this[4], by1 = this[5], bz1 = this[6], bw1 = this[7];
this[0] = ax0 * bw0 + aw0 * bx0 + ay0 * bz0 - az0 * by0;
this[1] = ay0 * bw0 + aw0 * by0 + az0 * bx0 - ax0 * bz0;
this[2] = az0 * bw0 + aw0 * bz0 + ax0 * by0 - ay0 * bx0;
this[3] = aw0 * bw0 - ax0 * bx0 - ay0 * by0 - az0 * bz0;
this[4] = ax0 * bw1 + aw0 * bx1 + ay0 * bz1 - az0 * by1 + ax1 * bw0 + aw1 * bx0 + ay1 * bz0 - az1 * by0;
this[5] = ay0 * bw1 + aw0 * by1 + az0 * bx1 - ax0 * bz1 + ay1 * bw0 + aw1 * by0 + az1 * bx0 - ax1 * bz0;
this[6] = az0 * bw1 + aw0 * bz1 + ax0 * by1 - ay0 * bx1 + az1 * bw0 + aw1 * bz0 + ax1 * by0 - ay1 * bx0;
this[7] = aw0 * bw1 - ax0 * bx1 - ay0 * by1 - az0 * bz1 + aw1 * bw0 - ax1 * bx0 - ay1 * by0 - az1 * bz0;
return this;
}
scale(s) {
this[0] = this[0] * s;
this[1] = this[1] * s;
this[2] = this[2] * s;
this[3] = this[3] * s;
this[4] = this[4] * s;
this[5] = this[5] * s;
this[6] = this[6] * s;
this[7] = this[7] * s;
return this;
}
norm() {
let magnitude = this[0] ** 2 + this[1] ** 2 + this[2] ** 2 + this[3] ** 2;
if (magnitude == 0)
return this;
magnitude = 1 / Math.sqrt(magnitude);
const a0 = this[0] * magnitude;
const a1 = this[1] * magnitude;
const a2 = this[2] * magnitude;
const a3 = this[3] * magnitude;
const b0 = this[4];
const b1 = this[5];
const b2 = this[6];
const b3 = this[7];
const a_dot_b = a0 * b0 + a1 * b1 + a2 * b2 + a3 * b3;
this[0] = a0;
this[1] = a1;
this[2] = a2;
this[3] = a3;
this[4] = (b0 - a0 * a_dot_b) * magnitude;
this[5] = (b1 - a1 * a_dot_b) * magnitude;
this[6] = (b2 - a2 * a_dot_b) * magnitude;
this[7] = (b3 - a3 * a_dot_b) * magnitude;
return this;
}
invert() {
const sqlen = 1 / (this[0] ** 2 + this[1] ** 2 + this[2] ** 2 + this[3] ** 2);
this[0] = -this[0] * sqlen;
this[1] = -this[1] * sqlen;
this[2] = -this[2] * sqlen;
this[3] = this[3] * sqlen;
this[4] = -this[4] * sqlen;
this[5] = -this[5] * sqlen;
this[6] = -this[6] * sqlen;
this[7] = this[7] * sqlen;
return this;
}
conjugate() {
this[0] = -this[0];
this[1] = -this[1];
this[2] = -this[2];
this[4] = -this[4];
this[5] = -this[5];
this[6] = -this[6];
return this;
}
translate(v) {
const ax1 = this[0], ay1 = this[1], az1 = this[2], aw1 = this[3];
const ax2 = this[4], ay2 = this[5], az2 = this[6], aw2 = this[7];
const bx1 = v[0] * 0.5, by1 = v[1] * 0.5, bz1 = v[2] * 0.5;
this[0] = ax1;
this[1] = ay1;
this[2] = az1;
this[3] = aw1;
this[4] = aw1 * bx1 + ay1 * bz1 - az1 * by1 + ax2;
this[5] = aw1 * by1 + az1 * bx1 - ax1 * bz1 + ay2;
this[6] = aw1 * bz1 + ax1 * by1 - ay1 * bx1 + az2;
this[7] = -ax1 * bx1 - ay1 * by1 - az1 * bz1 + aw2;
return this;
}
mulQuat(q) {
const qx = q[0], qy = q[1], qz = q[2], qw = q[3];
let ax = this[0], ay = this[1], az = this[2], aw = this[3];
this[0] = ax * qw + aw * qx + ay * qz - az * qy;
this[1] = ay * qw + aw * qy + az * qx - ax * qz;
this[2] = az * qw + aw * qz + ax * qy - ay * qx;
this[3] = aw * qw - ax * qx - ay * qy - az * qz;
ax = this[4];
ay = this[5];
az = this[6];
aw = this[7];
this[4] = ax * qw + aw * qx + ay * qz - az * qy;
this[5] = ay * qw + aw * qy + az * qx - ax * qz;
this[6] = az * qw + aw * qz + ax * qy - ay * qx;
this[7] = aw * qw - ax * qx - ay * qy - az * qz;
return this;
}
pmulQuat(q) {
const qx = q[0], qy = q[1], qz = q[2], qw = q[3];
let bx = this[0], by = this[1], bz = this[2], bw = this[3];
this[0] = qx * bw + qw * bx + qy * bz - qz * by;
this[1] = qy * bw + qw * by + qz * bx - qx * bz;
this[2] = qz * bw + qw * bz + qx * by - qy * bx;
this[3] = qw * bw - qx * bx - qy * by - qz * bz;
bx = this[4];
by = this[5];
bz = this[6];
bw = this[7];
this[4] = qx * bw + qw * bx + qy * bz - qz * by;
this[5] = qy * bw + qw * by + qz * bx - qx * bz;
this[6] = qz * bw + qw * bz + qx * by - qy * bx;
this[7] = qw * bw - qx * bx - qy * by - qz * bz;
return this;
}
rotX(rad) {
const bbx = this[0], bby = this[1], bbz = this[2], bbw = this[3];
let bx = -this[0], by = -this[1], bz = -this[2], bw = this[3];
const ax = this[4], ay = this[5], az = this[6], aw = this[7];
const ax1 = ax * bw + aw * bx + ay * bz - az * by;
const ay1 = ay * bw + aw * by + az * bx - ax * bz;
const az1 = az * bw + aw * bz + ax * by - ay * bx;
const aw1 = aw * bw - ax * bx - ay * by - az * bz;
rad *= 0.5;
const sin = Math.sin(rad), cos = Math.cos(rad);
bx = this[0] = bbx * cos + bbw * sin;
by = this[1] = bby * cos + bbz * sin;
bz = this[2] = bbz * cos - bby * sin;
bw = this[3] = bbw * cos - bbx * sin;
this[4] = ax1 * bw + aw1 * bx + ay1 * bz - az1 * by;
this[5] = ay1 * bw + aw1 * by + az1 * bx - ax1 * bz;
this[6] = az1 * bw + aw1 * bz + ax1 * by - ay1 * bx;
this[7] = aw1 * bw - ax1 * bx - ay1 * by - az1 * bz;
return this;
}
rotY(rad) {
const bbx = this[0], bby = this[1], bbz = this[2], bbw = this[3];
let bx = -this[0], by = -this[1], bz = -this[2], bw = this[3];
const ax = this[4], ay = this[5], az = this[6], aw = this[7];
const ax1 = ax * bw + aw * bx + ay * bz - az * by;
const ay1 = ay * bw + aw * by + az * bx - ax * bz;
const az1 = az * bw + aw * bz + ax * by - ay * bx;
const aw1 = aw * bw - ax * bx - ay * by - az * bz;
rad *= 0.5;
const sin = Math.sin(rad), cos = Math.cos(rad);
bx = this[0] = bbx * cos - bbz * sin;
by = this[1] = bby * cos + bbw * sin;
bz = this[2] = bbz * cos + bbx * sin;
bw = this[3] = bbw * cos - bby * sin;
this[4] = ax1 * bw + aw1 * bx + ay1 * bz - az1 * by;
this[5] = ay1 * bw + aw1 * by + az1 * bx - ax1 * bz;
this[6] = az1 * bw + aw1 * bz + ax1 * by - ay1 * bx;
this[7] = aw1 * bw - ax1 * bx - ay1 * by - az1 * bz;
return this;
}
rotZ(rad) {
const bbx = this[0], bby = this[1], bbz = this[2], bbw = this[3];
let bx = -this[0], by = -this[1], bz = -this[2], bw = this[3];
const ax = this[4], ay = this[5], az = this[6], aw = this[7];
const ax1 = ax * bw + aw * bx + ay * bz - az * by;
const ay1 = ay * bw + aw * by + az * bx - ax * bz;
const az1 = az * bw + aw * bz + ax * by - ay * bx;
const aw1 = aw * bw - ax * bx - ay * by - az * bz;
rad *= 0.5;
const sin = Math.sin(rad), cos = Math.cos(rad);
bx = this[0] = bbx * cos + bby * sin;
by = this[1] = bby * cos - bbx * sin;
bz = this[2] = bbz * cos + bbw * sin;
bw = this[3] = bbw * cos - bbz * sin;
this[4] = ax1 * bw + aw1 * bx + ay1 * bz - az1 * by;
this[5] = ay1 * bw + aw1 * by + az1 * bx - ax1 * bz;
this[6] = az1 * bw + aw1 * bz + ax1 * by - ay1 * bx;
this[7] = aw1 * bw - ax1 * bx - ay1 * by - az1 * bz;
return this;
}
rotAxisAngle(axis, rad) {
if (Math.abs(rad) < 1e-6)
return this;
const axisLength = 1 / Math.sqrt(axis[0] ** 2 + axis[1] ** 2 + axis[2] ** 2);
rad = rad * 0.5;
const s = Math.sin(rad);
const bx = s * axis[0] * axisLength;
const by = s * axis[1] * axisLength;
const bz = s * axis[2] * axisLength;
const bw = Math.cos(rad);
const ax1 = this[0], ay1 = this[1], az1 = this[2], aw1 = this[3];
const ax = this[4], ay = this[5], az = this[6], aw = this[7];
this[0] = ax1 * bw + aw1 * bx + ay1 * bz - az1 * by;
this[1] = ay1 * bw + aw1 * by + az1 * bx - ax1 * bz;
this[2] = az1 * bw + aw1 * bz + ax1 * by - ay1 * bx;
this[3] = aw1 * bw - ax1 * bx - ay1 * by - az1 * bz;
this[4] = ax * bw + aw * bx + ay * bz - az * by;
this[5] = ay * bw + aw * by + az * bx - ax * bz;
this[6] = az * bw + aw * bz + ax * by - ay * bx;
this[7] = aw * bw - ax * bx - ay * by - az * bz;
return this;
}
transformVec3(v, out) {
const pos = this.getTranslation();
const qx = this[0], qy = this[1], qz = this[2], qw = this[3];
const vx = v[0], vy = v[1], vz = v[2];
const x1 = qy * vz - qz * vy;
const y1 = qz * vx - qx * vz;
const z1 = qx * vy - qy * vx;
const x2 = qw * x1 + qy * z1 - qz * y1;
const y2 = qw * y1 + qz * x1 - qx * z1;
const z2 = qw * z1 + qx * y1 - qy * x1;
out = out || v;
out[0] = vx + 2 * x2 + pos[0];
out[1] = vy + 2 * y2 + pos[1];
out[2] = vz + 2 * z2 + pos[2];
return out;
}
}class Vec3Wizzy {
static xp(v, o) {
const x = v[0], y = v[1], z = v[2];
o[0] = x;
o[1] = -z;
o[2] = y;
return o;
}
static xn(v, o) {
const x = v[0], y = v[1], z = v[2];
o[0] = x;
o[1] = z;
o[2] = -y;
return o;
}
static yp(v, o) {
const x = v[0], y = v[1], z = v[2];
o[0] = -z;
o[1] = y;
o[2] = x;
return o;
}
static yn(v, o) {
const x = v[0], y = v[1], z = v[2];
o[0] = z;
o[1] = y;
o[2] = -x;
return o;
}
static zp(v, o) {
const x = v[0], y = v[1], z = v[2];
o[0] = y;
o[1] = -x;
o[2] = z;
return o;
}
static zn(v, o) {
const x = v[0], y = v[1], z = v[2];
o[0] = -y;
o[1] = x;
o[2] = z;
return o;
}
static xp_yn(v, o) {
const x = v[0], y = v[1], z = v[2];
o[0] = -y;
o[1] = -z;
o[2] = x;
return o;
}
static xp_yp(v, o) {
const x = v[0], y = v[1], z = v[2];
o[0] = y;
o[1] = -z;
o[2] = -x;
return o;
}
static xp_yp_yp(v, o) {
const x = v[0], y = v[1], z = v[2];
o[0] = -x;
o[1] = -z;
o[2] = -y;
return o;
}
static xp_xp(v, o) {
const x = v[0], y = v[1], z = v[2];
o[0] = x;
o[1] = -y;
o[2] = -z;
return o;
}
static yn_yn(v, o) {
const x = v[0], y = v[1], z = v[2];
o[0] = -x;
o[1] = y;
o[2] = -z;
return o;
}
}export{DualQuat,Mat4,Quat,Transform,Vec2,Vec3,Vec3Wizzy};
|
import * as React from 'react';
import { DataGrid } from '@mui/x-data-grid';
import { styled } from "@mui/material/styles"
import { roundTo } from 'round-to'
import HorizontalRuleIcon from '@mui/icons-material/HorizontalRule';
import { NumericFormat, numericFormatter } from 'react-number-format';
const CustomDataGrid = styled(DataGrid)((props) => ({
'&.MuiDataGrid-root': {
display: 'flex',
justifyContent: 'center',
border: '0px !important',
fontWeight: 'normal',
color: '#707070',
},
'.MuiDataGrid-columnHeaders': {
minHeight: '100px !important',
maxHeight: '100px !important',
borderBottom: '3px solid #D8A500',
},
'div.MuiDataGrid-columnHeaderTitle': {
color: '#194174',
fontWeight: '900'
},
'.MuiDataGrid-iconButtonContainer': {
position: 'absolute',
top: -20,
right: '50%',
visibility: 'visible',
width: 28,
height: 28
},
'.MuiDataGrid-sortIcon': {
opacity: '1 !important'
},
'.MuiDataGrid-menuIcon': {
position: 'absolute',
top: -20,
visibility: 'visible',
width: 28,
height: 28,
left: '50%'
},
'.MuiDataGrid-columnSeparator > *': {
visibility: 'hidden',
},
'.MuiDataGrid-columnSeparator': {
backgroundColor: '#F3DEA6 !important',
width: '2px',
minHeight: '40px !important',
right: 0
},
'.MuiDataGrid-virtualScroller': {
marginTop: '100px !important',
},
'.MuiDataGrid-cell': {
display: 'flex',
justifyContent: 'center'
},
'.MuiDataGrid-cellContent': {
fontSize: '15px',
fontWeight: 'normal',
color: '#707070'
},
'.MuiDataGrid-virtualScrollerRenderZone': {
// borderBottom: '3px solid #D8A500'
},
'&.MuiDataGrid-root .MuiDataGrid-columnHeader:focus': {
outline: 'none',
},
'.MuiDataGrid-footerContainer': {
display: 'none',
}
}))
function CustomDataGridFooter ({ aggregateData, currencyCountry }) {
return (
<div className='data-grid-footer'>
<div className='data-grid-footer-table-head-row'>
<div className='table-head-spacing'></div>
<div className='table-head-cell'>Shares</div>
<div className='table-head-cell'>Value Traded{` (${currencyCountry})`}</div>
<div className='table-head-cell adv-cell'>% ADV</div>
<div className='table-head-cell spread-cell'>Spread (bps)</div>
<div className='table-head-cell'>Volatility (%)</div>
<div className='table-head-cell moo-cell'>% MOO</div>
<div className='table-head-cell moc-cell'>% MOC</div>
<div className='table-head-cell'>Est. Duration (Day)</div>
{/* <div className='table-head-cell config-manager-cell'>Config Manager Performance Estimate</div>
<div className='table-head-cell performance-estimate-cell'>Performance Estimate</div> */}
</div>
<div className='data-grid-footer-table-body-row'>
<div className='footer-title'>Total</div>
<div className='footer-data'>
<div className='table-cell'>{aggregateData && aggregateData.totalShares ? <NumericFormat value={String(aggregateData.totalShares)} displayType='text' thousandSeparator="," /> : ''}</div>
<div className='table-cell'>{aggregateData && aggregateData.totalValueTraded ? <NumericFormat value={String(roundTo(aggregateData.totalValueTraded, 0))} displayType='text' thousandSeparator="," /> : ''}</div>
<div className='table-cell adv-cell'>{aggregateData && aggregateData.avgAdv ? <NumericFormat value={String(aggregateData.avgAdv)} displayType='text' thousandSeparator="," suffix=' %' /> : ''}</div>
<div className='table-cell spread-cell'>{aggregateData && aggregateData.avgSpread ? <NumericFormat value={String(aggregateData.avgSpread)} displayType='text' thousandSeparator="," suffix=' bps' /> : ''}</div>
<div className='table-cell'>{aggregateData && aggregateData.avgVoatility ? <NumericFormat value={String(aggregateData.avgVoatility)} displayType='text' thousandSeparator="," suffix=' %' /> : ''}</div>
<div className='table-cell moo-cell'>{aggregateData && aggregateData.avgMoo ? <NumericFormat value={String(aggregateData.avgMoo)} displayType='text' thousandSeparator="," suffix=' %' /> : ''}</div>
<div className='table-cell moc-cell'>{aggregateData && aggregateData.avgMoc ? <NumericFormat value={String(aggregateData.avgMoc)} displayType='text' thousandSeparator="," suffix=' %' /> : ''}</div>
<div className='table-cell'>{aggregateData && aggregateData.maxEstimateDuration ? aggregateData.maxEstimateDuration : ''}</div>
{/* <div className='table-cell config-manager-cell'>{(aggregateData && (aggregateData.beforeOptimizedPerformance && !isNaN(aggregateData.beforeOptimizedPerformance))) ? <NumericFormat value={String(roundTo(aggregateData.beforeOptimizedPerformance, 2))} displayType='text' thousandSeparator="," /> : '-'}</div>
<div className='table-cell performance-estimate-cell'>{(aggregateData && (aggregateData.optimizedPerformance && !isNaN(aggregateData.optimizedPerformance))) ? <NumericFormat value={String(roundTo(aggregateData.optimizedPerformance, 2))} displayType='text' thousandSeparator="," /> : '-'}</div> */}
</div>
</div>
</div>
)
}
export default function DataTable ({ tableData, aggregateData, currencyCountry, allOptimizedParamsData, isVisible }) {
let columns = [
{ field: 'symbol', headerName: 'Symbol', width: 90, headerAlign: 'center' },
{ field: 'name', headerName: 'Name', width: 160, headerAlign: 'center' },
{ field: 'country', headerName: 'Country', width: 90, headerAlign: 'center' },
{ field: 'side', headerName: 'Side', width: 85, headerAlign: 'center' },
{ field: 'orderType', headerName: 'Order Type', width: 85, headerAlign: 'center' },
{
field: 'price', headerName: 'Limit Price', width: 85, headerAlign: 'center',
renderCell: function renderCell (params) {
if (!params.value) {
return '-'
}
return <span><NumericFormat value={params.value} displayType='text' thousandSeparator="," /></span>
}
},
{ field: 'strategy', headerName: 'Strategy', width: 85, headerAlign: 'center' },
{
field: 'portfolioPercentage', headerName: '% Portfolio', width: 85, headerAlign: 'center',
renderCell: function renderCell (params) {
return <span><NumericFormat value={params.value} displayType='text' thousandSeparator="," />%</span>
}
},
{
field: 'shares', headerName: 'Shares', width: 80, headerAlign: 'center',
renderCell: function renderCell (params) {
return <NumericFormat value={params.value} displayType='text' thousandSeparator="," />
}
},
{
field: 'valueTraded', headerName: `Value Traded (${currencyCountry})`, width: 150, headerAlign: 'center',
renderCell: function renderCell (params) {
if (!params.value) {
return <NumericFormat value={params.value} displayType='text' thousandSeparator="," />
}
return <NumericFormat value={roundTo(params.value, 0)} displayType='text' thousandSeparator="," />
}
},
{ field: 'adv', headerName: '% ADV', width: 80, headerAlign: 'center' },
{
field: 'spread', headerName: 'Spread (bps)', width: 130, headerAlign: 'center',
renderCell: function renderCell (params) {
return <span> <NumericFormat value={params.value} displayType='text' thousandSeparator="," /> bps</span>
}
},
{ field: 'volatility', headerName: 'Volatility (%)', width: 130, headerAlign: 'center' },
{ field: 'moo', headerName: '% MOO', width: 95, headerAlign: 'center' },
{
field: 'moc', headerName: '% MOC', width: 90, headerAlign: 'center',
// headerClassName: 'hideRightSeparator'
},
{ field: 'estimateDuration', headerName: 'Est. Duration (Day)', width: 95, headerAlign: 'center' },
];
if (allOptimizedParamsData.length > 0) {
const optimizedParamsField = []
aggregateData['optimizedFieldList'] = []
let optimizedPerformanceSumProduct = 0
let beforeOptimizedPerformanceSumProduct = 0
allOptimizedParamsData.forEach((optimizedParamsData) => {
//each stock
const optimizedParamDataList = optimizedParamsData.optimizedParameters
const beforeOptimizedPerformance = optimizedParamsData.beforeOptimizedPerformance
const optimizedPerformance = optimizedParamsData.optimizedPerformance
if (optimizedParamsField.length === 0) {
optimizedParamsField.push(
{
field: 'beforeOptimizedPerformance', headerName: 'Config Manager Performance Estimate', width: 90, headerAlign: 'center',
renderCell: function renderCell (params) {
return <NumericFormat value={String(params.value ? params.value : '-')} displayType='text' thousandSeparator="," />
}
}
)
optimizedParamsField.push(
{
field: 'optimizedPerformance', headerName: 'Performance Estimate', width: 90, headerAlign: 'center',
renderCell: function renderCell (params) {
return <NumericFormat value={String(params.value ? params.value : '-')} displayType='text' thousandSeparator="," />
}
}
)
}
const stock = optimizedParamsData.symbol
const tradeDetailFound = tableData.find((tradeDetailData) => tradeDetailData.symbol === stock)
if (!tradeDetailFound) {
return
}
const valueTraded = tradeDetailFound['valueTraded']
// handle performance estimate
tradeDetailFound['optimizedPerformance'] = optimizedPerformance ? optimizedPerformance : '-'
tradeDetailFound['beforeOptimizedPerformance'] = beforeOptimizedPerformance ? beforeOptimizedPerformance : '-'
optimizedPerformanceSumProduct += (valueTraded * optimizedPerformance)
beforeOptimizedPerformanceSumProduct += (valueTraded * beforeOptimizedPerformance)
for (let optimizedParamData of optimizedParamDataList) {
const fieldName = optimizedParamData.parameter
const value = optimizedParamData.value
const fieldFound = optimizedParamsField.find((fieldData) => fieldData.field === fieldName)
if (tradeDetailFound) {
tradeDetailFound[fieldName] = value
}
if (fieldFound) {
continue
}
optimizedParamsField.push(
{
field: fieldName, headerName: fieldName, width: 90, headerAlign: 'center',
renderCell: function renderCell (params) {
return params.value ? params.value : '-'
}
},
)
aggregateData['optimizedFieldList'].push({ fieldName, value: '-' })
}
})
aggregateData['optimizedPerformance'] = optimizedPerformanceSumProduct ? optimizedPerformanceSumProduct / aggregateData['totalValueTraded'] : '-'
aggregateData['beforeOptimizedPerformance'] = beforeOptimizedPerformanceSumProduct ? beforeOptimizedPerformanceSumProduct / aggregateData['totalValueTraded'] : '-'
columns = [...columns, ...optimizedParamsField]
}
return (
<>
{
isVisible &&
<>
<div className='trade-detail-table-view '>
{
<CustomDataGrid
rows={isVisible ? tableData : []}
columns={isVisible ? columns : []}
pageSize={100}
rowHeight={100}
/>
}
</div>
{
CustomDataGridFooter({ aggregateData, currencyCountry })
}
</>
}
</>
);
}
|
import graphene
from graphene_django import DjangoObjectType, DjangoListField
from .models import Author
class AuthorType(DjangoObjectType):
class Meta:
model = Author
fields = '__all__'
class AuthorInput(graphene.InputObjectType):
author_name = graphene.String()
year_born = graphene.String()
year_died = graphene.String()
country = graphene.String()
books_written = graphene.Int()
class Query(graphene.ObjectType):
all_authors = graphene.List(AuthorType)
author = graphene.Field(AuthorType, author_name=graphene.String())
def resolve_all_authors(self, info, **kwargs):
return Author.objects.all()
def resolve_author(self, info, author_name):
return Author.objects.get(pk=author_name)
class CreateAuthor(graphene.Mutation):
class Arguments:
author_data = AuthorInput(required=True)
author = graphene.Field(AuthorType)
@staticmethod
def mutate(root, info, author_data=None):
author_instance = Author(
author_name = author_data.author_name,
year_born = author_data.year_born,
year_died = author_data.year_died,
country = author_data.country,
books_written = author_data.books_written
)
author_instance.save()
return CreateAuthor(author=author_instance)
class UpdateAuthor(graphene.Mutation):
class Arguments:
author_data = AuthorInput(required=True)
author = graphene.Field(AuthorType)
@staticmethod
def mutate(root, info, author_data=None):
author_instance = Author.objects.get(pk=author_data.name)
if author_instance:
author_instance.author_name = author_data.author_name
author_instance.year_born = author_data.year_born
author_instance.year_died = author_data.year_died
author_instance.country = author_data.country
author_instance.books_written = author_data.books_written
return UpdateAuthor(author=author_instance)
return UpdateAuthor(author=None)
class DeleteAuthor(graphene.Mutation):
class Arguments:
id = graphene.Int()
author = graphene.Field(AuthorType)
@staticmethod
def mutate(root, info, id):
author_instance = Author.objects.get(pk=id)
author_instance.delete()
return None
class Mutation(graphene.ObjectType):
create_author = CreateAuthor.Field()
update_author = UpdateAuthor.Field()
delete_author = DeleteAuthor.Field()
|
<?php
namespace App\Http\Controllers\Admin;
use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use App\User;
use Validator;
use Illuminate\Support\Str;
class StaffController extends Controller
{
public function __construct()
{
view()->share('type', 'manage-staff');
}
public function index(Request $request)
{
$data = User::where('level', 'Staff')->orderBy('created_at', 'desc')->paginate(25);
return view('admin.manage-staff.index', compact('data'));
}
public function store(Request $request)
{
$data = $request->all();
$user = User::where('email', $data['email'])->orWhere('phone', $data['phone'])->first();
if ($user) {
return redirect()->back()->with('delete', 'Email or Phone used');
} else {
$validator = Validator::make($data, [
'name' => 'required',
'phone' => 'required',
'ic_number' => 'required',
'email' => 'required|email',
]);
if ($validator->fails()) {
return redirect()->back()
->withErrors($validator)
->withInput();
}
$data['password'] = bcrypt(Str::random(5));
User::create($data);
return redirect()->back()->with('message', 'Add successfully!');
}
}
public function delete($id)
{
User::findOrFail($id)->delete();
return redirect()->back()->with('delete', 'Delete successfully!');
}
}
|
import matplotlib.pyplot as plt
from typing import Union
import numpy as np
import os
import io
from PIL import Image
def sample_batch(dataset):
batch = dataset.take(1).get_single_element()
if isinstance(batch, tuple):
batch = batch[0]
return batch.numpy()
def display(
images: np.ndarray,
n=10,
merge=True,
size=(20, 3),
cmap: Union[str, None] = "gray_r",
as_type="float32",
save_to:Union[str, None]=None,
):
"""
Displays n random images from each one of the supplied arrays.
"""
# if images.max() > 1.0:
# images = images / 255.0
# elif images.min() < 0.0:
# images = (images + 1.0) / 2.0
images = (images - images.min()) / (images.max() - images.min())
if merge:
fig, axs = plt.subplots(1, n, figsize=size, gridspec_kw={'wspace': 0})
for i in range(n):
axs[i].imshow(images[i].astype(as_type), cmap=cmap)
axs[i].axis("off")
if save_to:
if os.path.isdir(save_to):
raise ValueError("save_to must be a file path, not a directory.")
fig.savefig(save_to, bbox_inches="tight", pad_inches=0)
print(f"\nSaved to {save_to}")
else:
plt.show(fig)
else:
for i in range(n):
plt.axis("off")
plt.imshow(images[i].astype(as_type), cmap=cmap)
if save_to:
if os.path.isfile(save_to):
raise ValueError("save_to must be a directory, not a file path.")
plt.savefig(f"../output/gan_{i}.png")
plt.close()
else:
plt.show()
|
import Parsing
extension Many where Result == [Upstream.Output], Separator == Always<Input, Void> {
/// Initializes a parser that attempts to run the given parser at least and at most the given
/// number of times, accumulating the outputs in an array.
///
/// - Parameters:
/// - upstream: Another parser.
/// - minimum: The minimum number of times to run this parser and consider parsing to be
/// successful.
/// - maximum: The maximum number of times to run this parser before returning the output.
@inlinable
public init(
_ upstream: Upstream,
exactly count: Int
) {
self.init(upstream, atLeast: count, atMost: count)
}
}
|
from typing import List, Optional, Any
from fastapi import Depends
from sqlalchemy.orm import Session
from data.models import Todo
from database import get_db
from data.schemas import TodoCreate
from fastapi import HTTPException
class TodoRepository:
db: Session
def __init__(
self, db: Session
) -> None:
self.db = db
def setDb(self,db):
self.db = db
return self
def list(
self,
name: Optional[str],
limit: Optional[int],
start: Optional[int],
) -> List[Todo]:
query = self.db.query(Todo)
if name:
query = query.filter_by(name=name)
return query.offset(start).limit(limit).all()
def get(self, todo_id: int) -> Any | Todo:
todo =self.db.query(Todo).filter(Todo.id==todo_id).first() or None
if todo is None:
raise HTTPException(status_code=404, detail="Todo not found")
return todo
def create(self, todo_create: TodoCreate) -> Todo:
db_item = Todo(**todo_create.dict())
self.db.add(self.db_item)
self.db.commit()
self.db.refresh(db_item)
return db_item
def get_todo_repository(db):
return TodoRepository(db)
|
import { Component } from '@angular/core';
import { FormBuilder } from '@angular/forms';
import * as Mnemonic from "bitcore-mnemonic";
import * as CryptoJS from "crypto-js";
import * as bip39 from "bip39";
import { hdkey } from "ethereumjs-wallet";
import * as util from "ethereumjs-util";
import Web3 from 'web3';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
// seeds ex
export class AppComponent {
loginForm: any;
encrypted: any;
wallet: any = {
address: ''
}
web3: any;
defaultSeeds : string = 'february current defy one inform wet hurry cupboard type enable spare famous'
constructor(private formBuilder: FormBuilder) {
this.loginForm = this.formBuilder.group({
seeds: '',
password: ''
});
this.encrypted = localStorage.getItem('seeds');
this.initializeWallet(this.defaultSeeds);
this.web3 = new Web3;
this.web3.setProvider(
new this.web3.providers.HttpProvider('https://ropsten.infura.io/v3/d09825f256ae4705a74fdee006040903')
);
}
sendLogin (loginData: any) {
let { seeds, password } = loginData;
if(this.encrypted){
if(!password)
return alert('Please, enter your credentials');
const decrypted = CryptoJS.AES.decrypt(this.encrypted, password).toString(CryptoJS.enc.Utf8);
seeds = decrypted;
this.loginForm.reset();
this.initializeWallet(seeds);
} else {
if(!password || !seeds)
return alert('Please, enter your credentials');
const validSeeds = Mnemonic.isValid(seeds);
if(!validSeeds)
return alert('Invalid seeds');
const encryptedSeeds = CryptoJS.AES.encrypt(seeds, password).toString();
localStorage.setItem('seeds', encryptedSeeds);
}
}
async initializeWallet(seeds: string){
const mnemonic = new Mnemonic(seeds);
const seed = await bip39.mnemonicToSeed(mnemonic.toString());
const path = "m/44'/60'/0'/0/0";
const wallet = hdkey
.fromMasterSeed(seed)
.derivePath(path)
.getWallet();
const privateKey = wallet.getPrivateKey();
const publicKey = util.privateToPublic(privateKey);
const address = "0x" + util.pubToAddress(publicKey).toString("hex");
this.wallet.address = address;
}
}
|
<script setup>
import { ref, onMounted, nextTick } from 'vue';
import ApexCharts from "vue3-apexcharts";
import GenericLayout from '@/Layouts/GenericLayout.vue';
const props = defineProps({
customers_meta: Object,
customer_orders_meta: Array,
products_meta: Object,
product_options_meta: Object,
});
const customerSelectedMonth = ref(0);
const customersSeries = ref([
{
name: 'sales',
data: []
},
{
name: 'orders',
data: []
}
]);
const customerOptions = ref({
chart: {
height: 350,
type: 'line',
foreColor: '#b8b8b8',
zoom: {
enabled: false
},
toolbar: {
show: false
}
},
dataLabels: {
enabled: false
},
colors: ["#ff6e40", "#05b171"],
stroke: {
width: 4,
curve: 'smooth',
},
legend: {
show: false
},
markers: {
size: 0,
hover: {
sizeOffset: 6
}
},
xaxis: {
min: 0,
categories: []
},
yaxis: {
min: 0,
tickAmount: 1
},
tooltip: {
y: [
{
title: {
formatter: function (val) {
return val
}
}
},
{
title: {
formatter: function (val) {
return val
}
}
},
{
title: {
formatter: function (val) {
return val;
}
}
}
]
},
grid: {
borderColor: '#ededed',
}
});
const calculateGrowth = (order) => {
if (order.length) return ["0", ""];
const percentage = order[1] ? (order[0].total_orders - order[1].total_orders) / 100 : 100;
return percentage < 0 ? [percentage, "danger"] : [percentage, "success"];
}
onMounted(() => {
if(props.customer_orders_meta.length) {
customerSelectedMonth.value = props.customer_orders_meta[props.customer_orders_meta.length - 1].month;
props.customer_orders_meta.forEach(order => {
if(customerSelectedMonth.value == order.month) {
const date = new Date(order.created_at);
if(!customerOptions.value.xaxis.categories.includes(`${date.getDay()} ${date.toLocaleDateString("en-us", { month: "short" })}`)) customerOptions.value.xaxis.categories.push(`${date.getDay()} ${date.toLocaleDateString("en-us", { month: "short" })}`)
customersSeries.value[0].data.push(parseInt(order.total_paid));
customersSeries.value[1].data.push(parseInt(order.total_orders));
}
});
customerOptions.value.xaxis.min = customerOptions.value.xaxis.categories[customerOptions.value.xaxis.categories.length - 1];
}
nextTick(() => {
window.dispatchEvent(new Event('resize'));
});
});
</script>
<template>
<GenericLayout>
<div class="content ">
<div class="row row-cols-1 row-cols-md-3 g-4">
<div class="col-lg-4 col-md-12">
<div class="card h-100">
<div class="card-body">
<div class="d-flex mb-3">
<div class="display-7">
<i class="bi bi-basket"></i>
</div>
<div class="dropdown ms-auto">
<a href="#" data-bs-toggle="dropdown" class="btn btn-sm" aria-haspopup="true"
aria-expanded="false">
<i class="bi bi-three-dots"></i>
</a>
<div class="dropdown-menu dropdown-menu-end">
<a href="#" class="dropdown-item">View Detail</a>
<a href="#" class="dropdown-item">Download</a>
</div>
</div>
</div>
<h4 class="mb-3">Total Customers</h4>
<div class="d-flex mb-3" style="position: relative;">
<div class="display-7">{{ customers_meta.total_customers }}</div>
</div>
<div class="text-success">
Over last month 100% <i
class="small bi bi-arrow-up"></i>
</div>
</div>
</div>
</div>
<div class="col-lg-4 col-md-12">
<div class="card h-100">
<div class="card-body">
<div class="d-flex mb-3">
<div class="display-7">
<i class="bi bi-basket"></i>
</div>
<div class="dropdown ms-auto">
<a href="#" data-bs-toggle="dropdown" class="btn btn-sm" aria-haspopup="true"
aria-expanded="false">
<i class="bi bi-three-dots"></i>
</a>
<div class="dropdown-menu dropdown-menu-end">
<a href="#" class="dropdown-item">View Detail</a>
<a href="#" class="dropdown-item">Download</a>
</div>
</div>
</div>
<h4 class="mb-3">Total Customer Orders</h4>
<div class="d-flex mb-3" style="position: relative;">
<div class="display-7">{{ customer_orders_meta.length }}</div>
</div>
<div class="text-{{ calculateGrowth(customer_orders_meta)[1] }}">
Over last month {{ calculateGrowth(customer_orders_meta)[0] }}% <i
class="small bi bi-arrow-up"></i>
</div>
</div>
</div>
</div>
<div class="col-lg-4 col-md-12">
<div class="card h-100">
<div class="card-body">
<div class="d-flex mb-3">
<div class="display-7">
<i class="bi bi-basket"></i>
</div>
<div class="dropdown ms-auto">
<a href="#" data-bs-toggle="dropdown" class="btn btn-sm" aria-haspopup="true"
aria-expanded="false">
<i class="bi bi-three-dots"></i>
</a>
<div class="dropdown-menu dropdown-menu-end">
<a href="#" class="dropdown-item">View Detail</a>
<a href="#" class="dropdown-item">Download</a>
</div>
</div>
</div>
<h4 class="mb-3">Total Binapoints</h4>
<div class="d-flex mb-3" style="position: relative;">
<div class="display-7">$B {{ $page.props.auth.user.binapoints }}</div>
</div>
<div class="text-success">
Over last month 1.4% <i class="small bi bi-arrow-up"></i>
</div>
</div>
</div>
</div>
<div class="col-lg-7 col-md-12">
<div class="card widget h-100">
<div class="card-header d-flex">
<h6 class="card-title">
Customer Sales Chart
<a href="#" class="bi bi-question-circle ms-1 small" data-bs-toggle="tooltip" title=""
data-bs-original-title="Daily orders and sales"
aria-label="Daily orders and sales"></a>
</h6>
<div class="d-flex gap-3 align-items-center ms-auto">
<div class="dropdown">
<a href="#" data-bs-toggle="dropdown" class="btn btn-sm" aria-haspopup="true"
aria-expanded="false">
<i class="bi bi-three-dots"></i>
</a>
<div class="dropdown-menu dropdown-menu-end">
<a href="#" class="dropdown-item">View Detail</a>
<a href="#" class="dropdown-item">Download</a>
</div>
</div>
</div>
</div>
<div class="card-body" style="position: relative;">
<div class="d-md-flex align-items-center mb-3">
<div class="d-flex align-items-center">
<div class="display-7 me-3">
<i class="bi bi-bag-check me-2 text-success"></i>KSH 10.552,40
</div>
<span class="text-success">
<i class="bi bi-arrow-up me-1 small"></i>8.30%
</span>
</div>
<div class="d-flex gap-4 align-items-center ms-auto mt-3 mt-lg-0">
<select class="form-select">
<optgroup label="2020">
<option value="October">October</option>
<option value="November">November</option>
<option value="December">December</option>
</optgroup>
<optgroup label="2021">
<option value="January">January</option>
<option value="February">February</option>
<option value="March">March</option>
<option value="April">April</option>
<option value="May" selected="">May</option>
<option value="June">June</option>
<option value="July">July</option>
<option value="August">August</option>
<option value="September">September</option>
<option value="October">October</option>
<option value="November">November</option>
<option value="December">December</option>
</optgroup>
</select>
</div>
</div>
<div id="sales-chart">
<ApexCharts :options="customerOptions" :series="customersSeries" />
</div>
<div class="d-flex justify-content-center gap-4 align-items-center ms-auto mt-3 mt-lg-0">
<div>
<i class="bi bi-circle-fill mr-2 text-primary me-1 small"></i>
<span>Sales</span>
</div>
<div>
<i class="bi bi-circle-fill mr-2 text-success me-1 small"></i>
<span>Orders</span>
</div>
</div>
<div class="resize-triggers">
<div class="expand-trigger">
<div style="width: 869px; height: 496px;"></div>
</div>
<div class="contract-trigger"></div>
</div>
</div>
</div>
</div>
<div class="col-lg-5 col-md-12">
<div class="card widget">
<div class="card-header">
<h5 class="card-title">Site Overview</h5>
</div>
<div class="row g-4">
<div class="col-md-6">
<div class="card border-0">
<div class="card-body text-center">
<div class="display-5">
<i class="bi bi-box text-secondary"></i>
</div>
<h5 class="my-3">Total Products</h5>
<div class="text-muted">{{ products_meta.products_count }} Product</div>
</div>
</div>
</div>
<div class="col-md-6">
<div class="card border-0">
<div class="card-body text-center">
<div class="display-5">
<i class="bi bi-receipt text-warning"></i>
</div>
<h5 class="my-3">Total Sold</h5>
<div class="text-muted">{{ product_options_meta.total_sold }} Sold</div>
</div>
</div>
</div>
<div class="col-md-6">
<div class="card border-0">
<div class="card-body text-center">
<div class="display-5">
<i class="bi bi-eye text-info"></i>
</div>
<h5 class="my-3">Product Views</h5>
<div class="text-muted">{{ products_meta.product_views }} Views</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</GenericLayout>
</template>
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.