text
stringlengths 184
4.48M
|
|---|
import { useState } from "react";
import { Box, Text, Flex } from "@chakra-ui/react";
import FilterItem from "../molecules/filter-item";
import { useHistory, useLocation } from "react-router-dom";
interface IFilterProps {}
const FilterBox: React.FunctionComponent<IFilterProps> = (props) => {
const location = useLocation();
const history = useHistory();
const query = new URLSearchParams(location.search);
const filterData = [
{
title: "Meeting",
options: [
{ value: "school of the spirit", title: "SOS" },
{ value: "writing the vision", title: "WTV" },
{ value: "prayer meeting", title: "PM" },
{ value: "lekki soul center", title: "LSC" },
],
},
{
title: "Year",
options: [
{ value: "2022", title: "2022" },
{ value: "2021", title: "2021" },
{ value: "2020", title: "2020" },
{ value: "2019", title: "2019" },
],
},
{
title: "Month",
options: [
{ value: "january", title: "January" },
{ value: "february", title: "February" },
{ value: "march", title: "March" },
{ value: "april", title: "April" },
{ value: "may", title: "May" },
{ value: "june", title: "June" },
{ value: "july", title: "July" },
{ value: "august", title: "August" },
{ value: "september", title: "September" },
{ value: "october", title: "October" },
{ value: "november", title: "November" },
{ value: "december", title: "December" },
],
},
{
title: "Location",
options: [
{ value: "kosofe", title: "Kosofe" },
{ value: "noic", title: "NOIC" },
{ value: "faith plaza", title: "Faith Plaza" },
{ value: "lekki", title: "Lekki" },
],
},
];
const [activeFilter, setActiveFilter] = useState(0);
return (
<Box
minW="235px"
borderRadius="4px"
background="linear-gradient(165.9deg, #1C0225 -3.31%, #050F28 50.49%, #081944 90.59%)"
border="1px solid #FFFFFF"
p="16px 24px"
zIndex="99"
height="fit-content"
>
<Flex
pt="19px"
pb="16px"
mb="22px"
borderBottom="1px solid rgba(255, 255, 255, 0.3)"
alignContent="center"
>
<svg
width="18"
height="18"
viewBox="0 0 18 18"
fill="none"
xmlns="http://www.w3.org/2000/svg"
>
<rect width="18" height="18" rx="4.90909" fill="#FFEED1" />
<path
d="M13.0909 5.64551H4.90909L8.18182 9.51551V12.191L9.81818 13.0091V9.51551L13.0909 5.64551Z"
stroke="#7B4B36"
strokeWidth="0.818182"
strokeLinecap="round"
strokeLinejoin="round"
/>
</svg>
<Text
color="white"
mr="22px"
ml="8px"
fontSize="14px"
lineHeight="18px"
fontWeight="400"
>
Filters
</Text>
</Flex>
{filterData.map((filterItem, index) => (
<FilterItem
handleRadioChange={(e: string) => {
const searchQuery = query.get("query") || "";
const meeting = query.get("meeting") || "";
const year = query.get("year") || "";
const month = query.get("month") || "";
const locationQuery = query.get("location") || "";
const title = filterItem.title;
if (title.toLowerCase() === "meeting") {
history.push(
`/search?query=${searchQuery}&meeting=${e}${
year && `&year=${year}`
}${month && `&month=${month}`}${
locationQuery && `&location=${locationQuery}`
}`
);
} else if (title.toLowerCase() === "year") {
history.push(
`/search?query=${searchQuery}${
meeting && `&meeting=${meeting}`
}&year=${e}${month && `&month=${month}`}${
locationQuery && `&location=${locationQuery}`
}`
);
} else if (title.toLowerCase() === "month") {
history.push(
`/search?query=${searchQuery}${
meeting && `&meeting=${meeting}`
}${year && `&year=${year}`}&month=${e}${
locationQuery && `&location=${locationQuery}`
}`
);
} else if (title.toLowerCase() === "location") {
history.push(
`/search?query=${searchQuery}${
meeting && `&meeting=${meeting}`
}${year && `&year=${year}`}${
month && `&month=${month}`
}&location=${e}`
);
}
}}
key={filterItem.title}
title={filterItem.title}
options={filterItem.options}
active={activeFilter === index}
onClick={() => {
if (activeFilter === index) {
setActiveFilter(-1);
} else {
setActiveFilter(index);
}
}}
/>
))}
</Box>
);
};
export default FilterBox;
|
---
title: Rover template commands
description: For use with Apollo Federation
---
A **supergraph** (also called a federated graph) is a graph composed of multiple **subgraphs**:
```mermaid
graph BT;
gateway(["Supergraph (A + B + C)"]);
serviceA[Subgraph A];
serviceB[Subgraph B];
serviceC[Subgraph C];
gateway --- serviceA & serviceB & serviceC;
```
Rover template commands help you create new subgraphs from templated projects in various [federation-compatible implementations](/federation/building-supergraphs/supported-subgraphs).
This feature helps you quickly start up a new GraphQL project or explore various subgraph implementations. If you want to contribute a new template, [open an issue here](https://github.com/apollographql/rover/issues/new/choose)!
## Create a new subgraph
Run `rover template use <PATH>` to generate the boilerplate for a new subgraph. You can either use the guided wizard experience to select a template, or specify a template with the `--template` flag.
### Using the wizard
Run `rover template use <PATH>` to start a wizard that helps you create a new subgraph project. The wizard walks you through a series of questions to help you choose a template.
```bash
rover template use my-new-subgraph
```
By default, the wizard prompts you for which programming language to use for your project. You can optionally provide a `--language` option to skip this prompt.
> Run `rover template use --help` to see a list of available languages.
```shell
rover template use my-new-python-subgraph --language python
```
### Skipping the wizard
If you know exactly which template you want to use, you can specify the `--template` option to skip the wizard:
```shell
rover template use my-new-javascript-subgraph --template subgraph-javascript-apollo-server
```
> Use `rover template list` to see a list of available templates.
## Listing available templates
The `rover template list` command lists each available template with its corresponding ID (which you can provide to the `--template` option of `rover template use`). It also displays each template's name, language, and Repo URL. To learn more about a specific template, go to its repo URL and see its `README.md` file.
This command accepts the same `--language` option as `rover template use` to filter the list of templates.
> For a machine-readable output, use the `--json` flag.
Templates are currently available for the following libraries and languages:
| Language | Name | ID | Template Repository |
|------------|----------------------------------------------------------------------------------------|--------------------------------------|------------------------------------------------------------------------------------------------------------------|
| C# | [Hot Chocolate (Annotations)](https://chillicream.com/docs/hotchocolate/) | `subgraph-csharp-hot-chocolate` | [View repository](https://github.com/apollographql/subgraph-template-dotnet-hotchocolate-annotation-boilerplate) |
| Go | [Go (gqlgen)](https://gqlgen.com/getting-started/) | `subgraph-go-gqlgen` | [View repository](https://github.com/apollographql/subgraph-template-go-gqlgen-boilerplate) |
| Java | [Spring GraphQL](https://spring.io/projects/spring-graphql) | `subgraph-java-spring-graphql` | [View repository](https://github.com/apollographql/subgraph-template-java-spring-graphql-boilerplate) |
| JavaScript | [Apollo Server (JS)](https://www.apollographql.com/docs/apollo-server/) | `subgraph-javascript-apollo-server` | [View repository](https://github.com/apollographql/subgraph-template-javascript-apollo-server-boilerplate) |
| Kotlin | [GraphQL Kotlin](https://opensource.expediagroup.com/graphql-kotlin/docs/) | `subgraph-graphql-kotlin` | [View repository](https://github.com/apollographql/subgraph-template-graphql-kotlin-boilerplate) |
| Python | [Strawberry with FastAPI](https://strawberry.rocks) | `subgraph-python-strawberry-fastapi` | [View repository](https://github.com/strawberry-graphql/subgraph-template-strawberry-fastapi) |
| Python | [Ariadne with FastAPI](https://ariadnegraphql.org) | `subgraph-python-ariadne-fastapi` | [View repository](https://github.com/patrick91/subgraph-template-ariadne-fastapi) |
| Rust | [async-graphql with Axum](https://async-graphql.github.io/async-graphql/en/index.html) | `subgraph-rust-async-graphql` | [View repository](https://github.com/apollographql/subgraph-template-rust-async-graphql) |
| TypeScript | [Apollo Server (TS)](https://www.apollographql.com/docs/apollo-server/) | `subgraph-typescript-apollo-server` | [View repository](https://github.com/apollographql/subgraph-template-typescript-apollo-server-boilerplate) |
|
import { Link, useParams } from "react-router-dom"
import useProyectos from "../hooks/useProyectos";
import useAdmin from "../hooks/useAdmin";
import useAuth from "../hooks/useAuth";
import { useEffect } from "react";
const PreviewProyecto = ({proyecto}) => {
const {auth} = useAuth()
const admin = useAdmin()
const { handleModalEliminarProyecto } = useProyectos();
const { nombre, _id, cliente, creador} = proyecto
return (
<div className='border-b p-5 flex items-center gap-2 justify-between'>
<div className="flex gap-2 items-center">
<p className=" flex-1">
{nombre}
<span className=" text-sm text-gray-500 uppercase">{' '}{cliente}</span>
</p>
{auth._id !== creador && (
<p className=" p-1 bg-green-500 rounded-md text-white text-xs uppercase font-bold">Colaborador</p>
)}
</div>
<div className=" flex gap-2 items-center">
{auth._id === creador && (
<div
onClick={() => handleModalEliminarProyecto(proyecto)}
className=" cursor-pointer flex items-center gap-2 text-gray-400 hover:text-red-700 transition-colors">
<svg
xmlns="http://www.w3.org/2000/svg"
className="h-6 w-6"
fill="none"
viewBox="0 0 24 24"
stroke="currentColor"
strokeWidth={2}
>
<path
strokeLinecap="round"
strokeLinejoin="round"
d="M19 7l-.867 12.142A2 2 0 0116.138 21H7.862a2 2 0 01-1.995-1.858L5 7m5 4v6m4-6v6m1-10V4a1 1 0 00-1-1h-4a1 1 0 00-1 1v3M4 7h16"
/>
</svg>
</div>
)}
<Link to={`${_id}`}
className=' text-gray-600 hover:text-gray-800 uppercase text-sm font-bold'
>
Ver Proyecto
</Link>
</div>
</div>
)
}
export default PreviewProyecto
|
import { db } from '@/db'
import type { Prisma, SubCategory } from '@prisma/client';
import { notFound } from 'next/navigation';
import { z } from 'zod'
import { Result } from '../utils';
const SubCategorySchema = z.object({
title:
z.string({
required_error: "title should be greater than 3 characters"
}).min(3).max(255),
content: z.string({
required_error: "title should be greater than 10 characters"
}).min(10).max(4000),
categoryId:
z.number({
required_error: "Category Id should be present"
}),
})
export async function fetchAll() {
try {
const result = await db.subCategory.findMany({
orderBy: [
{
updatedAt: 'desc',
}
],
})
return Result.Success(result);
}
catch (error) {
return Result.Error(error);
}
}
export async function fetchById(id: number) {
try {
const subCategory = await db.subCategory.findFirst({
where: {
id
}
})
if (!subCategory) {
return Result.Error("sub-category not found");
}
return Result.Success(subCategory)
}
catch (error) {
return Result.Error(error);
}
}
export async function create(data: Prisma.SubCategoryUncheckedCreateInput) {
const result = SubCategorySchema.safeParse({
title: data.title,
content: data.content,
categoryId: data.categoryId,
})
if (!result.success) {
return Result.ValidationError(result.error.flatten().fieldErrors)
}
let subCategory: SubCategory
try {
subCategory = await db.subCategory.create({
data: result.data
})
return Result.Success(subCategory)
} catch (error) {
return Result.Error(error);
}
}
export async function updateById(id: number, data: Prisma.SubCategoryUncheckedUpdateInput) {
const result = SubCategorySchema.safeParse({
title: data.title,
content: data.content,
categorId: data.categoryId
})
if (!result.success) {
return Result.ValidationError(result.error.flatten().fieldErrors)
}
let subCategory: SubCategory
try {
subCategory = await db.subCategory.update({
where: { id },
data: result.data
})
return Result.Success(subCategory);
} catch (error: unknown) {
return Result.Error(error);
}
}
export async function deleteById(id: number) {
let subCategory: SubCategory
try {
subCategory = await db.subCategory.delete({
where: { id },
})
return Result.Success(subCategory)
} catch (error: unknown) {
return Result.Error(error);
}
}
|
#! /usr/bin/env python
# -*- coding: utf-8 -*-
#
# Copyright 2020-2023 Alibaba Group Holding Limited.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
import pickle
from typing import Any
from typing import Optional
from vineyard._C import IPCClient
from vineyard._C import Object
from vineyard._C import ObjectMeta
from vineyard.core.builder import BuilderContext
from vineyard.core.resolver import ResolverContext
from vineyard.data.utils import build_buffer
if pickle.HIGHEST_PROTOCOL < 5:
import pickle5 as pickle # pylint: disable=shadow-import
def default_builder(client: IPCClient, value: Any, **kwargs):
'''Default builder: pickle (version 5), then build a blob object for it.'''
payload = pickle.dumps(value, protocol=5)
buffer = build_buffer(client, payload, len(payload))
meta = ObjectMeta(**kwargs)
meta['typename'] = 'vineyard::PickleBuffer'
meta['nbytes'] = len(payload)
meta['size_'] = len(payload)
meta.add_member('buffer_', buffer)
return client.create_metadata(meta)
def default_resolver(obj: Object):
view = memoryview(obj.member('buffer_'))[0 : int(obj.meta['size_'])]
return pickle.loads(view, fix_imports=True)
def register_default_types(
builder_ctx: Optional[BuilderContext] = None,
resolver_ctx: Optional[ResolverContext] = None,
):
if builder_ctx is not None:
builder_ctx.register(object, default_builder)
if resolver_ctx is not None:
resolver_ctx.register('vineyard::PickleBuffer', default_resolver)
|
//
// String+Extensions.swift
// Convos
//
// Created by Nitsan Asraf on 10/07/2022.
//
import UIKit
extension String {
func getColorByName() -> UIColor {
switch self {
case "white":
return .white
case "green":
return .systemGreen
case "cyan blue":
return .systemCyan
case "orange":
return .orange
case "vibrant yellow":
return .systemYellow
case "pink red":
return .systemPink
default:
return .black
}
}
func makeComparable() -> String {
return self.trimmingCharacters(in: .whitespacesAndNewlines).lowercased()
}
}
|
\input texinfo
@c -*- texinfo -*-
@c %**start of header
@setfilename nomad.info
@documentencoding UTF-8
@settitle Nomad Reference Manual
@documentlanguage en
@c %**end of header
@include version.texi
@include urls.texi
@copying
Copyright @copyright{} 2019 Amar M. Singh@*
@quotation
Permission is granted to copy, distribute and/or modify this document
under the terms of the GNU Free Documentation License, Version 1.3 or
any later version published by the Free Software Foundation; with no
Invariant Sections, no Front-Cover Texts, and no Back-Cover Texts. A
copy of the license is included in the section entitled ``GNU Free
Documentation License.''
@end quotation
@end copying
@dircategory Nomad
@direntry
* Nomad: (nomad). Extensible self-documenting web browser.
@end direntry
@titlepage
@title Nomad Reference Manual
@subtitle A User's Guide for Nomad Web Browser
@author The Nomad Developers
@page
@vskip 0pt plus 1filll
Edition @value{EDITION} @*
@value{UPDATED-MONTH} @*
@insertcopying
@end titlepage
@contents
@c *********************************************************************
@node Top
@top The Nomad Browser
Nomad is an extensible, customisable, self-documenting web browser. This
manual describes how to use Nomad and some of the ways to customise it;
it corresponds to the Nomad version @value{VERSION}.
@c See 'manual-html-mono' and 'manual-html-node' in admin/admin.el.
@html
The homepage for Nomad is at
<a href="@value{HOMEPAGE}">Nongnu.org</a>.<br>
To view this manual in other formats, see
<a href="@value{MANUALS}">Online Manuals</a>.<br>
@end html
For information on the extension language for Nomad, see @ref{Top, Guile
Reference Manual,, guile,}.
For information on Emacsy library used in Nomad, see @ref{Top, Emacsy,,
emacsy,}.
This is the Nomad User Manual for the Nomad Web Browser,
@value{VERSION}.@refill
@insertcopying
@menu
* Distribution:: Get the source code
* Installation:: Install Nomad using Guix
* Usage:: Using Nomad from the command line, application keybinds
* API:: The programming interface
* Extensions:: Modules and extensions for Nomad
* Development:: Making changes to the source code and contributing
* Copying:: The GNU General Public License gives you permission to redistribute Nomad
* Documentation License:: The license for this documentation
@end menu
@c *********************************************************************
@node Distribution
@chapter Distribution
Nomad is @dfn{free software}; this means that everyone is free to use it
and free to redistribute it under certain conditions. Nomad is not in
the public domain; it is copyrighted and there are restrictions on its
distribution. The precise conditions are found in the GNU General Public
License that comes with Nomad. @footnote{This manual is itself covered by
the GNU Free Documentation License. This license is similar in spirit
to the General Public License, but is more suitable for documentation.}
Get the latest source code using git from Nongnu.org
@example
git clone @value{GIT}
@end example
@ifnothtml
The list of releases are available at @value{RELEASES}
@end ifnothtml
@ifhtml
@html
The list of releases are available at <a href="@value{RELEASES}">Releases.</a>
@end html
@end ifhtml
@c *********************************************************************
@node Installation
@chapter Installation
If you use the Gnu Guix package manager, then you can easily install
Nomad with
@example
guix package -i nomad
@end example
If you want the latest package, clone the source repository
@example
git clone @value{GIT}
cd nomad
guix package -f ./guix.scm
@end example
To build using the GNU build system, see @ref{Development}.
@c *********************************************************************
@node Usage
@chapter Usage
@section Command-line
The browser can be run from a shell by typing
@example
nomad
@end example
To disable the loading of @samp{~/.nomad} configuration file
@example
nomad -Q
@end example
For more options, see
@example
nomad --help
@end example
@section Keybinds
Nomad intends to support Emacs-like keybinds because it's design was
inspired from Emacs. However there is no limitation on what Keybindings
Nomad can support. Nomad has the concept of key-maps just like Emacs and
users should be able to define their own keymaps.
At the top level you might want to use `M-x` (Meta/Alt X) to use the
execute command menu.
In a Webview buffer the `webview-mode-map` is active which contains the
following keybinds.
@multitable {aaaaaaaaaa} {aaaaaaaaaaaaa}
@headitem Key stroke
@tab Command
@item "C-b"
@tab (next-buffer)
@item "C-u"
@tab (back)
@item "C-m"
@tab (forward)
@item "C-n"
@tab (scroll-down)
@item "C-f"
@tab (hints)
@item "C-p"
@tab (scroll-up)
@item "C-r"
@tab (reload)
@end multitable
In Nomad's Ibuffer menu the `ctrl-x-map` is active which has these
keybindings.
@multitable {aaaaaaaaaa} {aaaaaaaaaaaaa}
@headitem Key stroke
@tab Command
@item "b"
@tab (next-buffer)
@item "k"
@tab (kill-buffer)
@end multitable
@c *********************************************************************
@node API
@chapter API
The modules and features provided by Nomad are in flux. The best option is
to consult the source directly. @uref{@value{GIT}}
@c *********************************************************************
@node Extensions
@chapter Extensions
You can customize nomad by writing your configurations to `~/.nomad`,
which is just a scheme file!
Examples
@example
(set! search-provider-format "https://google.ca/search?q=~a")
@end example
@c *********************************************************************
@node Development
@chapter Development
In Ubuntu 19.04, the the following snippet will install most
dependencies.
@example
sudo apt install -y \
guile-2.2 \
guile-2.2-dev \
guile-library \
libgtk-3-dev \
libwebkit2gtk-4.0-dev \
libgtksourceview-4-dev
@end example
Using Guix, the following snippet will install all required dependencies
in a temporary shell.
@example
guix environment -l ./guix.scm
@end example
Then build the package with
@example
autoreconf -vif
./configure
make
@end example
@section Run from Source
Once you've built Nomad without errors, to run Nomad from the local
build.
@example
make test
./pre-inst-env ./src/nomad
@end example
@c *********************************************************************
@node Copying
@appendix GNU GENERAL PUBLIC LICENSE
@include gpl.texi
@c *********************************************************************
@node Documentation License
@appendix GNU Free Documentation License
@include doclicense.texi
@bye
|
import {
View,
Text,
ScrollView,
Dimensions,
Image,
Pressable,
TouchableOpacity,
} from "react-native";
import React, { useEffect, useState } from "react";
import { NativeStackHeaderProps } from "@react-navigation/native-stack";
import { s } from "react-native-wind";
import { SafeAreaView } from "react-native-safe-area-context";
import { Entypo, Feather } from "@expo/vector-icons";
import Slick from "react-native-slick";
import ModalComponent from "../components/Modal";
import CategoryCard from "../components/CategoryCard";
import Product from "../components/Product";
import { client } from "../lib/sanity.server";
import { urlForImage } from "../lib/sanity";
import { addToCart, selectCartItems } from "../features/cartSlice";
import { useDispatch, useSelector } from "react-redux";
import { selectFavoritesItems } from "../features/favoritesSlice";
import Header from "../components/Header";
import Carousel from "../components/Carousel";
const window = Dimensions.get("window");
const PAGE_WIDTH = window.width;
const HomeScreen = ({ navigation }: NativeStackHeaderProps) => {
const [categories, setCategories] = useState([]);
const [products, setProducts] = useState([]);
useEffect(() => {
client.fetch(`*[_type == 'category']`).then((res) => {
setCategories(res);
});
client.fetch(`*[_type == 'product']`).then((res) => {
setProducts(res);
});
}, []);
const items = useSelector(selectCartItems);
// const favoritesItems = useSelector(selectFavoritesItems);
// console.log(favoritesItems);
return (
<SafeAreaView style={s`h-full`}>
<Header />
<ScrollView
showsVerticalScrollIndicator={false}
scrollEventThrottle={16}
bounces={false}
>
{/* header */}
{/* carousel */}
<Carousel />
{/* categories */}
<View style={s` pr-0`}>
<View style={s`p-3 flex-row justify-between items-center`}>
<Text style={s`capitalize font-bold text-xl mb-3`}>Categories</Text>
<TouchableOpacity onPress={() => navigation.navigate("Shop")}>
<Text style={s`text-gray-500 capitalize`}>Show all</Text>
</TouchableOpacity>
</View>
<View style={s`pl-3`}>
<ScrollView
horizontal
showsHorizontalScrollIndicator={false}
bounces={false}
>
{categories.map((item) => (
<CategoryCard
key={item._id}
name={item.name}
image={urlForImage(item.image).url()}
/>
))}
</ScrollView>
</View>
</View>
{/* best sellers */}
<View style={s`p-3 pr-0 mt-5`}>
<Text style={s`capitalize font-bold text-xl mb-3`}>Best seller</Text>
<View>
<ScrollView horizontal showsHorizontalScrollIndicator={false}>
{products.map((product) => (
<Product
key={product._id}
id={product._id}
name={product.name}
price={product.price}
image={urlForImage(product.image).url()}
description={product.description}
item={product}
/>
))}
</ScrollView>
</View>
</View>
<View style={s`p-3 pr-0 mt-5`}>
<Text style={s`capitalize font-bold text-xl mb-3`}>Best seller</Text>
<View>
<ScrollView horizontal showsHorizontalScrollIndicator={false}>
{products.map((product) => (
<Product
key={product._id}
id={product._id}
name={product.name}
price={product.price}
image={urlForImage(product.image).url()}
description={product.description}
item={product}
/>
))}
</ScrollView>
</View>
</View>
</ScrollView>
</SafeAreaView>
);
};
export default HomeScreen;
|
#pragma once
#include "../App/ZetaRay.h"
namespace ZetaRay::Util
{
// Ref: https://stackoverflow.com/questions/18633697/fastdelegate-and-lambdas-cant-get-them-to-work-don-clugstons-fastest-possib
struct Function
{
Function() noexcept = default;
template <typename F>
Function(F&& f) noexcept
{
static_assert(sizeof(F) <= BUFFER_SIZE, "Memory needed exceeded capture buffer size.");
static_assert(std::is_move_constructible_v<F>);
m_lambda = &Get<F>();
new (&m_buffer) F(ZetaMove(f));
}
~Function() noexcept
{
if (m_lambda)
{
m_lambda->destruct(&m_buffer);
}
}
Function(Function&& other) noexcept
: m_lambda(other.m_lambda)
{
other.m_lambda = nullptr;
memcpy(m_buffer, other.m_buffer, BUFFER_SIZE);
memset(other.m_buffer, 0, BUFFER_SIZE);
}
Function& operator=(Function&& other) noexcept
{
m_lambda = other.m_lambda;
other.m_lambda = nullptr;
memcpy(m_buffer, other.m_buffer, BUFFER_SIZE);
memset(other.m_buffer, 0, BUFFER_SIZE);
return *this;
}
bool IsSet() const noexcept
{
return m_lambda != nullptr;
}
//template <typename F>
//void Reset(F&& f) noexcept
//{
// static_assert(sizeof(F) <= BUFFER_SIZE, "Memory needed exceede capture buffer size.");
// static_assert(std::is_move_constructible_v<F>);
// if (m_lambda)
// m_lambda->destruct(&m_buffer);
// m_lambda = &Get<F>();
// new (&m_buffer) F(ZetaMove(f));
//}
ZetaInline void Run() noexcept
{
return m_lambda->call(&m_buffer);
}
private:
static constexpr int BUFFER_SIZE = 40;
struct LambdaFuncPtrs
{
void (*call)(void*);
void (*destruct)(void*);
};
template <typename F>
static void Call(void* f)
{
(*reinterpret_cast<F*>(f))();
}
template <typename F>
static void Destruct(void* f)
{
reinterpret_cast<F*>(f)->~F();
}
template <typename F>
const LambdaFuncPtrs& Get()
{
static const LambdaFuncPtrs lambda = { &Call<F>, &Destruct<F> };
return lambda;
}
const LambdaFuncPtrs* m_lambda = nullptr;
alignas(alignof(std::max_align_t)) uint8_t m_buffer[BUFFER_SIZE];
};
}
|
type Category =
'general'|
'business'|
'entertainment'|
'health'|
'science'|
'sports'|
'technology';
type NewsResponse = {
pagination: Pagination;
data: Article[];
}
type Pagination = {
count: Int;
limit: Int;
offset: Int;
total: Int;
}
type Article = {
author: string | null;
category: string;
country: string;
description: string;
image: string | null;
language: string;
published_at : string;
source: string;
title: string;
url: string;
}
|
import { useConnectWallet } from "@web3-onboard/react";
import { BigNumber, ethers } from "ethers";
import { useCallback, useEffect, useMemo, useState } from "react";
import { ERC20, ERC20__factory } from "../web3/abi/types";
import { isValidAddress } from "../helpers/web3";
export default function useERC20(address: string) {
const [{ wallet, connecting }, connect, disconnect] = useConnectWallet();
const [provider, setProvider] = useState<ethers.providers.Web3Provider>();
const [contract, setContract] = useState<ERC20>();
useEffect(() => {
if (wallet) {
const ethersProvider = new ethers.providers.Web3Provider(wallet.provider);
setProvider(ethersProvider);
}
}, [wallet]);
useEffect(() => {
if (provider && address) {
const _contract = ERC20__factory.connect(address, provider);
setContract(_contract);
}
}, [provider, address]);
const getBalance = useCallback(
async (walletAddress: string) => {
if (contract && isValidAddress(walletAddress)) {
return await contract.balanceOf(walletAddress);
} else {
return BigNumber.from(0);
}
},
[contract]
);
return { getBalance };
}
|
#These informations are taken from video called "10 Key Data Structure We Use Every Day" by ByteByteGo.
//These are common datastructures used in programming
1. List:
Lists are versatile and essential datastructures in software development.
They are great for storing and manipulating ordered data.
They are useful in various applications like task management, social media feeds, user preferences
and shopping carts.
In task management applications, a list can be used to store and organize task for each user.
Task can be added, removed or reordered easily and users can mark them as complete or incomplete.
Lists are also useful in social media applications like twitter, where they can store and display
a user's feed in real-time, ensuring the latest content is shown in the correct order.
2. Arrays:
Arrays are another fundamental data structure.
They provide a fixed-size ordered collection of elements.
They are particularly well-suited for situations where the size of the collection
is known or doesn't change frequently.
Arrays are commonly used in mathematical operations, storing large data sets,
or when there is a need for randm access to elements.
For example: In a weather application, an array could be used to store temperature readings
for a specifics location over a defined period.
This allows for easy calculations like averages and trends.
Arrays are also widely used in image processing where each pixel's color data can be represented
in a two-dimensional array. It enables efficient manipulation and transformation of the image.
3. Stacks:
Stacks follow the Last-In-First-Out (LIFO) principle. They are perfect for supporting undo/redo operations
in text editors or maintaining browsing history in web browsers.
In text editor, a stack can be used to storeeach change made to the text,
Making it simple to revert to a previous state when the user triggers and undo operation.
4. Queues:
Queues operate on a First-In-First-Out (FIFO) basis.
They are good for managing printer jobs, sending usr actions in games or handling messages in chat applications.
In chat applications, a queue can be used to store incoming messages in the order they are received.
5. Heaps:
Heaps, on the other hand are used for task scheduling and memory management.
They are especially helpful in implementing priority queues, where we need to access the highest or lowest priority item efficiently.
6. Trees:
Trees organize data hierarchically. They are useful for representing data with natural hierarchies or relationships.
They can be used in various applications like database indexing, AI decision making, and files systems.
In AI decision-making, trees like decision trees are used in machine learning for classification tasks.
Trees are also used in database indexing, where they can help speed up search, insert or delete operations.
For example, B trees and B+ trees are commonly used in relational database to efficiently manage and index large amount of data.
7. Hash Tables:
Hash Tables allows for efficient data lookup, insertion and deletion.
They use a hash function to map keys to their corresponding storage locations.
It enables constant time access to the stores values. Hash tables are widely used in various applications, such as search engines,
caching systems and programming language interpreters or compilers.
In search engines, hash tables can be used to store and quickly retrieve indexed data based on keywords.
This provides fast and relevant search results.
Caching systems may use hash tables to store and manage cached data. It allows for rapid access to frequently requested
resources and improves overall system performance.
Another example is the implementation of symbol tables in programming language interpreters or compilers.
Hash tables can be used to efficiently manage and look up variables, functions and other symbols defined in the source code.
8. Suffix trees:
Suffix trees are specialized for searching strings in documents.
This makes them perfect for text editors and search algorithms.
In a search engine, a suffix tree can be used to efficiently locate all occurrences of a search term
within a large corpus of text.
9. Graphs:
Graphs are all about tracking relationships or finding paths. This makes them invaluable in social networks,
recommendation engines and pathfinding algorithms.
In a social network, a graph can be used to represent the connections between users.
It enables features like friend suggestions or analyzing network trends.
10. R-Trees:
R-trees are good at finding nearest neighbors. They are crucial for mapping apps and geolocation services.
In a mapping application, R-trees can be used to store spatial data such as points of interest.
This enables efficient queries to find the nearest locations based on the user's current position.
IMPORTANT NOTES:
Cache Friendliness and how it relates to various data structures, including lists, arrays and others mentioned above.
CPU cache is a small, fast memory between the main memory (Random Access memory) and the CPU.
It stores recently accessed data and instructions, so the CPU can access them quickly without fetching them from
the slower main memory. Different data structures have varying levels of cache friendliness based on how their elementsare stored in memory.
Contiguous memory storage, like that in arrays, allows for better cache locality and fewer cache misses, resulting in improved performance.
When an array element is accessed, the cache can prefetch and store nearby elements, anticipating taht they might be accessed soon.
On the other hand, data structures with non-contiguous memory storage, like linked list, can experience more cache misses and reduced
performance. In a linked list, elements are stored in nodes scattered throughout the memory and each node contains a pointer to the next
node in the sequence. This makes it difficult for the CPU to predict and load the next node before it's needed.
Other data structures, such as trees, hash tables and graphs also have varying degrees of cache friendliness based on their implementation
and use case. This disparity in access times can lead to performance issues in modern computing,
particularly in situations where cache misses occur frequently. We should be mindful of this when working
with performance-critical applications and choose the appropriate data structure based on the specific requirements
and constraints of their projects.
|
import { ErrorMessageMode } from '/#/axios';
import BaseApi from '/@/views/ppspirit/base/BaseApi';
/**
* @description 数据集合管理APi
* @author Liv
* @date 05/04/2023
* @export
* @class DataSourceApi
* @extends {BaseApi}
*/
export class DataCollectionApi extends BaseApi {
apiPrefix(): string {
return '/sys/datacollection';
}
/**
* @description 测试链接
* @author Liv
* @date 05/04/2023
* @param {string} id
* @param {ErrorMessageMode} [mode='modal']
* @returns {*}
* @memberof DataSourceApi
*/
executeSql({ id, timeout, params }: any, mode: ErrorMessageMode = 'modal') {
return this.getHttp().post(
{
url: this.prependApiPrefix(`/executeSql/${id}`),
data: params,
timeout,
},
{
errorMessageMode: mode,
},
);
}
}
|
package com.leetcode.test172.LRUCache;
import java.util.HashMap;
import java.util.Map;
//146. LRU Cache
class LRUCache {
int capacity;
Map<Integer, Node> map;
Node head, tail;
public LRUCache (int capacity) {
this.capacity = capacity;
map = new HashMap<>();
}
public int get (int key) {
if (map.containsKey(key)) {
remove(map.get(key));
insert(map.get(key));
return map.get(key).value;
}
return -1;
}
public void put (int key, int value) {
if (map.containsKey(key)) {
get(key);
map.get(key).value = value;
} else {
if (map.size() == capacity) {
removeLRU();
}
Node n = new Node(key, value);
insert(n);
map.put(key, n);
}
}
private void removeLRU () {
map.remove(head.key);
remove(head);
}
private void remove (Node node) {
Node p = node.prev;
Node n = node.next;
if (node == head) {
head = n;
} else if (node == tail) {
tail = p;
}
if (p != null) {
p.next = n;
}
if (n != null) {
n.prev = p;
}
}
private void insert (Node n) {
if (head == null) {
head = n;
tail = n;
} else {
tail.next = n;
n.prev = tail;
tail = n;
}
}
private static class Node {
int key, value;
Node prev, next;
Node (int k, int v) {
key = k;
value = v;
}
}
public static void main (String[] args) {
LRUCache cache = new LRUCache(2);
int[][] arr = new int[][] {{2, 1}, {3, 2}, {3}, {2}, {4, 3}, {2}, {3}, {4}};
for (int[] a : arr) {
if (a.length == 1)
System.out.println(cache.get(a[0]));
else
cache.put(a[0], a[1]);
}
}
}
|
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.nio.file.Files;
import java.nio.file.StandardCopyOption;
import java.util.Base64;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Part;
import javax.xml.ws.soap.SOAPFaultException;
import service.AdminDatabaseService;
import service.AdminDatabaseService_Service;
import service.Dupflix;
/**
*
* @author Niya
*/
@WebServlet(urlPatterns = {"/AdminUpdateServlet"})
@MultipartConfig(
fileSizeThreshold = 1024 * 1024 * 100, // 1 MB
maxFileSize = 1024 * 1024 * 100, // 10 MB
maxRequestSize = 1024 * 1024 * 150 // 15 MB
)
public class AdminUpdateServlet extends HttpServlet {
/**
* Processes requests for both HTTP <code>GET</code> and <code>POST</code>
* methods.
*
* @param request servlet request
* @param response servlet response
* @throws ServletException if a servlet-specific error occurs
* @throws IOException if an I/O error occurs
*/
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
try (PrintWriter out = response.getWriter()) {
/* TODO output your page here. You may use following sample code. */
out.println("<!DOCTYPE html>");
out.println("<html>");
out.println("<head>");
out.println("<title>Servlet AdminUpdateServlet</title>");
out.println("</head>");
out.println("<body>");
out.println("<h1>Servlet AdminUpdateServlet at " + request.getContextPath() + "</h1>");
out.println("</body>");
out.println("</html>");
}
}
// <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
/**
* Handles the HTTP <code>GET</code> method.
*
* @param request servlet request
* @param response servlet response
* @throws ServletException if a servlet-specific error occurs
* @throws IOException if an I/O error occurs
*/
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
Dupflix flix = new Dupflix();
int postId = Integer.parseInt(request.getParameter("post_id"));
AdminDatabaseService_Service adminService = new AdminDatabaseService_Service();
AdminDatabaseService port = adminService.getAdminDatabaseServicePort();
flix = port.getDupFlixData(postId);
request.setAttribute("dupFlix", flix);
request.getRequestDispatcher("AdminUpdateIndex.jsp").forward(request, response);
}
/**
* Handles the HTTP <code>POST</code> method.
*
* @param request servlet request
* @param response servlet response
* @throws ServletException if a servlet-specific error occurs
* @throws IOException if an I/O error occurs
*/
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
try {
AdminDatabaseService_Service adminService = new AdminDatabaseService_Service();
AdminDatabaseService port = adminService.getAdminDatabaseServicePort();
Dupflix flix = new Dupflix();
flix.setDupflixId(Integer.parseInt(request.getParameter("post_id")));
flix.setMovieName(request.getParameter("title"));
flix.setMovieSubtitle(request.getParameter("subtitle"));
flix.setCategoryType(request.getParameter("category"));
flix.setMovieDescription(request.getParameter("description"));
flix.setDirector(request.getParameter("director"));
flix.setProducer(request.getParameter("producer"));
flix.setThumbnail( Base64.getDecoder().decode(request.getParameter("thumbnail")));
System.out.println(request.getParameter("title"));
flix.setIstrending("Y");
int success = port.editDupFlixData(flix);
if(success == 1){
out.println("<script type='text/javascript'>");
out.println("alert('Uploaded Successfully');");
out.println("</script>");
}
} catch(SOAPFaultException ex){
out.println("<script type='text/javascript'>");
out.println("alert('Disney is prohibited in movies');");
out.println("</script>");
}
catch (Exception ex) {
out.println("<script type='text/javascript'>");
out.println("alert('Error in Uploading. Please try after sometime');");
out.println("</script>");
Logger.getLogger(AdminServlet.class.getName()).log(Level.SEVERE, null, ex);
}
RequestDispatcher rd = request.getRequestDispatcher("ManageIndex.jsp");
rd.forward(request,response);
}
/**
* Returns a short description of the servlet.
*
* @return a String containing servlet description
*/
@Override
public String getServletInfo() {
return "Short description";
}// </editor-fold>
}
|
import { NextFunction, Request, Response, Router } from 'express';
import { JsonApiResponse } from '@util/responses';
import { getServiceAreaDataBySiteId } from '@datastore/serviceArea/serviceAreaGetStore';
import { getDepartmentDataBySiteId } from '@datastore/department/departmentGetStore';
import { getRoleDataBySiteId } from '@datastore/role/roleGetStore';
import {
getHospitalGeoDetails,
loadSiteDetailsById,
fetchFilteredSiteData,
getSiteStatusCountsByHospitalId,
} from '@datastore/site/siteGetStore';
import { getUnitDataBySiteID } from '@datastore/unit/unitGetStore';
import { getOrganisationSiteFilterRequestSchema } from '@lib/schemas/siteSchemas';
import { authorizeRequest } from '@middlewares/jwt';
import {
hospitalIdRequestSchema,
siteIdRequestSchema,
} from '@lib/schemas/commonSchemas';
const siteGetRequest = Router();
/**
* Retrieves detailed information for a specific site based on a hospital or site ID.
* This endpoint is designed to provide comprehensive details about a site, such as
* location, services offered, and operational status. The current implementation
* expects to fetch data based on a hospitalId, but the route does not currently
* parse this ID from the request. This needs to be updated to either include a
* route parameter or a query string to properly function.
*
* @route GET /get-information
* @param {string} hospitalId - The unique identifier of the hospital or site to retrieve information from.
* @returns {Object} A response object containing the site details or an error message in case of failure.
*/
siteGetRequest.get(
'/get-information',
async (req: Request, res: Response, next: NextFunction) => {
try {
// const siteData = await getSiteInformation(req.params.hospitalId as string)
} catch (error) {
next(error);
}
}
);
/**
* Fetches unique countries and states for sites linked to a specific hospital ID.
* @param hospitalId The hospital's unique identifier.
* @param token Authorization token required for access.
* @returns An object with arrays of distinct countries and states.
*/
siteGetRequest.get(
'/:hospitalId/locations/distinct',
authorizeRequest(['SUPER_ADMIN', 'HOSPITAL_ADMIN']),
async (req: Request, res: Response, next: NextFunction) => {
try {
const requestBody = hospitalIdRequestSchema.parse(req.params);
const data = await getHospitalGeoDetails(requestBody.hospitalId);
return JsonApiResponse(res, 'Success', true, data, 200);
} catch (error) {
next(error);
}
}
);
/**
* Retrieves filtered site data for an organization within an account context, supporting advanced
* filtering options such as date ranges, search terms, and location. This endpoint requires an
* authorization token and supports pagination.
* @param token The authorization token required for validating user permissions.
* @param hospital_id Identifier for the hospital associated with the sites being queried.
* @param page Page number for pagination of the site data.
* @param per_page Number of site records per page.
* @param from_date Start date for filtering site data.
* @param to_date End date for filtering site data.
* @param search Search term for filtering sites.
* @param country Country filter for the sites.
* @param status Operational status filter for the sites.
* @param state State filter for the sites.
* @returns Paginated and filtered data specific to site details for a given organization.
*/
siteGetRequest.get(
'/organization/sites/filters',
authorizeRequest(['SUPER_ADMIN', 'HOSPITAL_ADMIN']),
async (req: Request, res: Response, next: NextFunction) => {
try {
const requestBody = getOrganisationSiteFilterRequestSchema.parse(
req.query
);
const data = await fetchFilteredSiteData(
requestBody.page,
requestBody.per_page,
requestBody?.search,
requestBody?.from_date,
requestBody?.to_date,
requestBody?.country,
requestBody?.status,
requestBody?.state,
requestBody.hospital_id
);
return JsonApiResponse(res, 'Success', true, data, 200);
} catch (error) {
next(error);
}
}
);
/**
* Retrieves detailed information about a specific site identified by its unique site ID.
* This endpoint is designed to provide comprehensive details about the site, including
* its operational data, location, and other relevant attributes. The information is
* primarily intended for display in user interfaces or for administrative purposes.
*
* @route GET /account/site/:siteId/details
* @param {string} siteId - The unique identifier of the site. This ID is required to
* fetch specific site details and must be provided in the URL.
* @returns {Object} A JSON response containing a success status, a message, and the
* detailed site data if successful. If an error occurs, it returns a
* response with a failure status and the error message.
*/
siteGetRequest.get(
'/details/:siteId',
authorizeRequest([
'SUPER_ADMIN',
'HOSPITAL_ADMIN',
'SITE_ADMIN',
'ADMIN',
'HUMAN_RESOURCES',
]),
async (req: Request, res: Response, next: NextFunction) => {
try {
const requestBody = siteIdRequestSchema.parse(req.params);
const site = await loadSiteDetailsById(requestBody.siteId);
return JsonApiResponse(
res,
site ? 'Site Info Request Success' : 'Something Went Wrong',
!!site,
site,
200
);
} catch (error) {
next(error);
}
}
);
/**
* Retrieves detailed organizational structure data (departments, roles, service areas, and units)
* for a specified site. This endpoint requires authorization and is intended for users with specific
* administrative roles within the hospital.
*
* @route GET /account/site/:siteId/organizational-structures
* @param siteId The unique identifier of the site for which organizational data is requested.
* @header token Authorization token required to validate user permissions. Must be provided in the request headers.
* @returns A JSON response containing the organizational data if the user is authorized, or an error message if not authorized or in case of an error.
*/
siteGetRequest.get(
'/:siteId/organizational-structures',
authorizeRequest([
'SUPER_ADMIN',
'HOSPITAL_ADMIN',
'SITE_ADMIN',
'HUMAN_RESOURCES',
]),
async (req: Request, res: Response, next: NextFunction) => {
try {
const requestBody = siteIdRequestSchema.parse(req.params);
const [department, role, serviceArea, unit] = await Promise.all([
getDepartmentDataBySiteId(requestBody.siteId),
getRoleDataBySiteId(requestBody.siteId),
getServiceAreaDataBySiteId(requestBody.siteId),
getUnitDataBySiteID(requestBody.siteId),
]);
return JsonApiResponse(
res,
'Success',
true,
{
department,
role,
serviceArea,
unit,
},
200
);
} catch (error) {
next(error);
}
}
);
siteGetRequest.get(
'/status-counts/organization/:hospitalId',
authorizeRequest([
'SUPER_ADMIN',
'HOSPITAL_ADMIN',
'SITE_ADMIN',
'HUMAN_RESOURCES',
]),
async (req: Request, res: Response, next: NextFunction) => {
try {
const requestBody = hospitalIdRequestSchema.parse(req.params);
const data = await getSiteStatusCountsByHospitalId(
requestBody.hospitalId
);
return JsonApiResponse(res, 'Success', true, data, 200);
} catch (error) {
next(error);
}
}
);
export default siteGetRequest;
|
<div class="mat-typography">
<div class="row">
<div class="col-sm">
<div class="row">
<div class="col-md-12">
<form [formGroup]="userForm">
<h1 class='mv3' i18n>{{login ? 'Login' : 'Sign Up'}}</h1>
<div class='flex flex-column'>
<div class="row">
<div class="col">
<!-- First Name -->
<mat-form-field class="full-width" *ngIf="!login">
<mat-label i18n>First Name</mat-label>
<input matInput type="text" [formControl]="firstName" minlength="3" required i18n-placeholder placeholder="John">
<mat-icon matPrefix>title</mat-icon>
<mat-hint i18n>Your first name</mat-hint>
<mat-error *ngIf="firstName.invalid" i18n>Please enter your first name</mat-error>
</mat-form-field>
</div>
<div class="col">
<!-- Last Name -->
<mat-form-field class="full-width" *ngIf="!login">
<mat-label i18n>Last Name</mat-label>
<input matInput type="text" [formControl]="lastName" minlength="3" required i18n-placeholder placeholder="Doe">
<mat-icon matPrefix>title</mat-icon>
<mat-hint i18n>Your last name</mat-hint>
<mat-error *ngIf="lastName.invalid" i18n>Please enter your last name</mat-error>
</mat-form-field>
</div>
</div>
<div class="row">
<div class="col">
<!-- E-Mail -->
<mat-form-field class="full-width">
<mat-label i18n>E-Mail</mat-label>
<input matInput type="text" [formControl]="email" minlength="3" required i18n-placeholder placeholder="john.doe@provider.com">
<mat-icon matPrefix>email</mat-icon>
<mat-hint i18n>Your email adress</mat-hint>
<mat-error *ngIf="email.invalid" i18n>Please enter your email adress</mat-error>
</mat-form-field>
</div>
<div class="col">
<!-- Password -->
<mat-form-field class="full-width">
<mat-label i18n>Password</mat-label>
<input matInput type="password" [formControl]="password" minlength="5" placeholder="mySuper@Secret123">
<mat-icon matPrefix>security</mat-icon>
<mat-hint i18n>Your password</mat-hint>
<mat-error *ngIf="password.invalid" i18n>Please enter at least 5 characters. There is no max password length!</mat-error>
</mat-form-field>
</div>
</div>
</div>
<div class='flex mt3'>
<button mat-raised-button color="primary" class="mat-btn float-left" (click)="confirm()" i18n="Login Button">
{{login ? 'Login' : 'Create Account'}}</button>
<button mat-raised-button color="primary" class="mat-btn float-left" [disabled]="disableSignup" (click)="login = !login" i18n="Login Mode">
{{login ? 'Need to create an account?' : 'Already have an account?'}}</button>
<button mat-raised-button color="primary" class="mat-btn float-left" (click)="resetPassword()" i18n>Forgot password?</button>
</div>
</form>
</div>
</div>
</div>
</div>
<div class="row" *ngIf="alerts">
<div class="col">
<ngb-alert [dismissible]="true" [type]="alert.type" *ngFor="let alert of alerts" (close)="close(alert)">
<p><strong>{{alert.message}}</strong></p>
</ngb-alert>
</div>
</div>
</div>
|
<!DOCTYPE html>
<html>
<head>
<title>PORTFOLIO WEBSITE</title>
<link rel="preconnect" href="https://fonts.googleapis.com">
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
<link href="https://fonts.googleapis.com/css2?family=Poppins:wght@400;500
;700&family=Roboto:wght@400;500;700&display=swap" rel="stylesheet">
<link rel="preconnect" href="https://fonts.googleapis.com">
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
<link href="https://fonts.googleapis.com/css2?family=Domine:wght@700&f
amily=Poppins:wght@400;500;700&family=Roboto:wght@400;500;700&displa
y=swap" rel="stylesheet">
<link rel="preconnect" href="https://fonts.googleapis.com">
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
<link href="https://fonts.googleapis.com/css2?family=Barlow+Semi+Condensed:ital,
wght@0,400;1,200;1,600&family=Domine:wght@700&family=Poppins:wght@400;500;700&fami
ly=Roboto:wght@400;500;700&display=swap" rel="stylesheet">
<link rel="preconnect" href="https://fonts.googleapis.com">
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
<link href="https://fonts.googleapis.com/css2?family=Barlow+Semi+Condensed:ital,wght@0,400;1,200;1,600&family=Domine:wght@700&family=Poppins:wght@400;500;700&family=Roboto:wght@400;500;700&family=Source+Sans+3:ital,wght@1,200&display=swap" rel="stylesheet">
<link rel="preconnect" href="https://fonts.googleapis.com">
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
<link href="https://fonts.googleapis.com/css2?family=Libre+Baskerville:ital@1&display=swap" rel="stylesheet">
<link rel = "stylesheet" href = "header.css">
<link rel = "stylesheet" href = "introduction.css">
<link rel = "stylesheet" href = "aboutme.css">
<link rel = "stylesheet" href = "portfolio.css">
<link rel = "stylesheet" href = "footer.css">
</head>
<body>
<header class = "head">
<div class = "logo">
<img class = bulb src = "IMG_2082.jpg">
</div>
<div class = "title">
Aaditya Chari
</div>
<nav class = "links">
<a style = "text-decoration: none;" href = "#sn1" class = "link-items"><span class = "int1">Introduction</span></a>
<a style = "text-decoration: none;" href = "#sn2" class = "link-items"><span class = "int2">About Me</span></a>
<a style = "text-decoration: none;" href = "#sn3" class = "link-items"><span class = "int3">Projects</span></a>
<a style = "text-decoration: none;" href = "#sn4" class = "link-items"><span class = "int4">Contact</span></a>
</nav>
</header>
<section id = "sn1" class = "buffer">.</section>
<div class = "intro">
<div class = "wording">
<p class = "line1">👋 Hi, I'm Aaditya.</p>
<p class = "line2">This is my <span class = "line21">Portfolio Website.</span></p>
<p class = "line3">Welcome to my digital showcase, where <span class = "line31">creativity</span> meets <span class = "line32">functionality.</span></p>
<p class = "line4">As a passionate engineering student with a keen eye for detail, I invite you to explore...</p>
</div>
<div class = "photo">
<img class = "picture" src = "image.png">
</div>
</div>
<section id = "sn2" class = "buffer">.</section>
<div class = "about_title">About me</div>
<div class = "aboutme">
<div class = "p1">
<p class = "tit1">My Education</p>
<p>Currently, I'm pursuing an undergraduate degree in Electrical Engineering from the Indian Institute of Technology, Kharagpur.</p>
</div>
<div class = "p3">
<p class = "tit3">My Skills</p>
<p class = "cont2">• Programming in Python</p>
<p class = "cont2">• Circuit Simulation using LTspice</p>
<p class = "cont2">• HTML, CSS and JavaScript</p>
<p class = "cont2">• An Intermediate Knowledge of C++ and Java</p>
</div>
<div class = "p2">
<p class = "tit2">My Interests</p>
<p class = "cont1">Web Development</p>
<p class = "cont1">Data Analysis</p>
<p class = "cont1">Transform Calculus</p>
<p class = "cont1">Machine Learning</p>
<p class = "cont1">Reading</p>
</div>
</div>
<section id = "sn3" class = "buffer">.</section>
<div class = "portfolio_title">My Projects</div>
<div class = "portfolio">
<div onclick = "left();" class = "left_button"><img class = "rimg2" src = "https://icones.pro/wp-content/uploads/2021/06/symbole-fleche-gauche-rouge.png"></div>
<div class = "writing">
<p class = "wtitle-js wtitle">JOSAA LOGIN PAGE</p>
<p class = "wcont-js wcont">This is a project made using basic html and css, in the early days of my web development journey. It is an elementary model of the JOSAA Counselling login page, containing all the necessary details to sign a student in.</p>
</div>
<div class = "imjs image"><a href = "https://acac2491.github.io/JOSAA-CLONE/" target = "_blank"><img class = "storejs storecss" src = "josaa.png"></a></div>
<div onclick = "right();" class = "right_button"><img class = "rimg1" src = "https://icones.pro/wp-content/uploads/2021/06/symbole-fleche-droite-rouge.png"></div>
</div>
<section id = "sn4" class = "main">
<div class = "footer">
<a href = "https://in.linkedin.com/in/aaditya-chari-70a01727b" target = "_blank"><img class = "icons1" src = "https://cdn.icon-icons.com/icons2/693/PNG/512/LinkedIn_Rounded_Solid_icon-icons.com_61559.png"></a>
<a href = "https://www.facebook.com/people/Aaditya-Chari/pfbid0cGTE7QxSqBNk6Wsds7BHfckZKQyAbUjzhJUQ32AMb14c3SrUheEVbWtreqrRGZqyl/" target = "_blank"><img class = "icons2" src = "https://cdn3.iconfinder.com/data/icons/glypho-social-and-other-logos/64/logo-facebook-512.png"></a>
<a href = "https://www.instagram.com/yb_ac/" target = "_blank"><img class = "icons3" src = "https://www.iconpacks.net/icons/2/free-instagram-logo-icon-3497-thumb.png"></a>
<a href = "https://github.com/ACAC2491" target = "_blank"><img class = "icons4" src = "https://github.githubassets.com/assets/GitHub-Mark-ea2971cee799.png"></a>
</div>
<div class = "designedby">
<p class = "lastwords">Designed By : Aaditya Chari, 2023</p>
</div>
</section>
<script src = "port.js"></script>
</body>
</html>
|
# FrontendMentor React Native 🤓
## Init an expo app
```Bash
npx create-expo-app AwesomeProject
cd AwesomeProject
npx expo start
```
## Run the app
```Bash
npm start
```
## Use custom font
1. Install the font with expo
```Bash
npx expo install @expo-google-fonts/inter expo-font
```
2. Import the fonts in your JS file
```javascript
import { Inter_400Regular } from "@expo-google-fonts/inter";
import { useFonts } from "expo-font";
```
3. Define font variables
```javascript
export default function App() {
const { onPress, title = "Save" } = props;
const [fontsLoaded] = useFonts({ Inter_400Regular });
if (!fontsLoaded) {
return <Text>Loading...</Text>;
}
return (
...
);
}
```
4. Set your style in your stylesheet
```javascript
const styles = StyleSheet.create({
catch: {
color: colors.white,
fontFamily: "Inter_400Regular",
fontSize: 14,
marginVertical: 20,
},
});
```
|
package com.ravspace.composedemo.ui.searchdemo.di
import com.ravspace.composedemo.ui.searchdemo.di.qualifier.SearchRetrofit
import com.ravspace.composedemo.ui.searchdemo.service.ApiService
import dagger.Module
import dagger.Provides
import dagger.hilt.InstallIn
import dagger.hilt.components.SingletonComponent
import retrofit2.Retrofit
import retrofit2.converter.gson.GsonConverterFactory
import javax.inject.Singleton
@Module
@InstallIn(SingletonComponent::class)
class NetworkSearchModule {
@Provides
@Singleton
// @Named("search")
@SearchRetrofit
fun provideRetrofitSearch(): Retrofit {
return Retrofit.Builder()
.baseUrl("https://api.jsonbin.io/")
.addConverterFactory(GsonConverterFactory.create())
.build()
}
@Singleton
@Provides
@SearchRetrofit
//@Named("search")
fun provideSearchApi(retrofitApi: Retrofit): ApiService {
return retrofitApi.create(ApiService::class.java)
}
}
|
# frozen_string_literal: true
require "rails_helper"
describe Planets::MetalMineUpgradeForm do
describe "#valid?" do
context "when all conditions are met" do
it "returns true" do
stub_metal_mine_upgrade
planet = build_stubbed(:planet, metal: 100)
form = described_class.new(planet: planet)
expect(form.valid?).to be true
end
end
context "when there is a pending upgrade" do
it "returns false" do
stub_metal_mine_upgrade
planet = create(:planet, metal: 100)
create(:metal_mine_upgrade, :in_progress, planet: planet)
form = described_class.new(planet: planet)
expect(form.valid?).to be false
expect(form.errors).to be_added(:base, :pending_upgrade)
end
end
context "when there are insufficient resources" do
it "returns false" do
stub_metal_mine_upgrade(cost: 150)
planet = build_stubbed(:planet, metal: 100)
form = described_class.new(planet: planet)
expect(form.valid?).to be false
expect(form.errors).to be_added(:base, :insufficient_resources)
end
end
end
describe "#save" do
it "creates a metal mine upgrade" do
stub_metal_mine_upgrade
planet = create(:planet, metal: 100)
form = described_class.new(planet: planet)
expect { form.save }.to change(planet.pending_metal_mine_upgrades, :count).by(1)
end
it "deducts the cost from the planet" do
stub_metal_mine_upgrade
planet = create(:planet, metal: 100)
form = described_class.new(planet: planet)
expect { form.save }.to change { planet.reload.metal }.by(-50)
end
it "schedules a job for completion" do
freeze_time do
stub_metal_mine_upgrade(duration: 2.minutes)
allow(CompleteMetalMineUpgradeJob).to receive(:perform_at)
planet = create(:planet, metal: 100)
form = described_class.new(planet: planet)
form.save
expect(CompleteMetalMineUpgradeJob).to(
have_received(:perform_at).with(
2.minutes.from_now,
planet.pending_metal_mine_upgrades.first.id
)
)
end
end
context "when the form is invalid" do
it "returns false" do
stub_metal_mine_upgrade(cost: 150)
planet = build_stubbed(:planet, metal: 100)
form = described_class.new(planet: planet)
expect(form.save).to be false
end
end
context "when it fails" do
it "doesn't cost resources to the planet and doesn't start the upgrade" do
stub_metal_mine_upgrade
planet = create(:planet, metal: 100)
form = described_class.new(planet: planet)
allow(planet).to receive(:save!).and_raise(ActiveRecord::RecordInvalid)
form.save
rescue ActiveRecord::RecordInvalid
expect(planet.reload.metal).to eq(100)
expect(planet.pending_metal_mine_upgrades.count).to eq(0)
end
end
end
def stub_metal_mine_upgrade(cost: 50, duration: 2.minutes)
allow(MetalMineUpgrade).to receive_messages(
cost_for_level: cost,
duration_for_level: duration
)
end
end
|
/*
* Copyright (c) 2011 Higepon(Taro Minowa) <higepon@users.sourceforge.jp>
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED
* TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
*/
#ifndef _TERMINAL_COMMANDLINE_CURSOR_PROBE_
#define _TERMINAL_COMMANDLINE_CURSOR_PROBE_
class TerminalCommandLineCursorProbe : public MonAPI::Probe
{
private:
TestTerminal& terminal_;
int lastCursor_;
int expectedCursor_;
void describe(std::string& d, int n)
{
char buf[32];
snprintf(buf, sizeof(buf), "%d", n);
d += "<";
d += buf;
d += ">";
}
public:
TerminalCommandLineCursorProbe(TestTerminal& terminal, int expectedCursor) :
terminal_(terminal),
expectedCursor_(expectedCursor)
{
}
void sample()
{
lastCursor_ = terminal_.getCommandField().getCursor();
}
bool isSatisfied()
{
return lastCursor_ == expectedCursor_;
}
void describeTo(std::string& d)
{
describe(d, expectedCursor_);
}
void describeFailureTo(std::string& d)
{
describe(d, lastCursor_);
}
};
#endif // _TERMINAL_COMMANDLINE_CURSOR_PROBE_
|
---
title: Úkol 3.2. Počet mrtvých a raněných v západní Evropě po letech a měsících
---
Zjisti počet mrtvých a raněných v západní Evropě po letech a měsících.
:::solution
Stejně jako v prvním úkolu, jen s filtrem na západní Evropu.
- `IYEAR`, `IMONTH`
```sql
SELECT IYEAR
, IMONTH
, SUM(NKILL) AS KILLED
, SUM(NWOUND) AS WOUNDED
FROM TEROR
WHERE REGION_TXT = 'Western Europe'
GROUP BY IYEAR, IMONTH
ORDER BY IYEAR, IMONTH;
```
- `DATE_PART()`
```sql
SELECT DATE_PART(YEAR, IDATE)
, DATE_PART(MONTH, IDATE)
, SUM(NKILL) AS KILLED
, SUM(NWOUND) AS WOUNDED
FROM TEROR
WHERE REGION_TXT = 'Western Europe'
GROUP BY DATE_PART(YEAR, IDATE)
, DATE_PART(MONTH, IDATE)
ORDER BY DATE_PART(YEAR, IDATE)
, DATE_PART(MONTH, IDATE);
```
:::
|
from datetime import datetime
from typing import Any
from uuid import UUID
from sqlalchemy import JSON
from sqlalchemy import UUID as UUID_
from sqlalchemy import Boolean, DateTime, ForeignKey, String
from sqlalchemy.orm import (
DeclarativeBase,
Mapped,
declared_attr,
mapped_column,
)
class Base(DeclarativeBase):
"""
A class describing the declarative
base of the model classes
Attributes
----------
id: int
The primary key of a an instance of Base
"""
__abstract__ = True
@declared_attr.directive
def __tablename__(cls) -> str:
"""
A declared attribute for __tablename__
The __tablename__ for a classed derived from
Base is its own name in lowercase by default.
Returns
-------
str
The class name in lowercase
"""
return cls.__name__.lower()
id: Mapped[UUID] = mapped_column(UUID_(as_uuid=True), primary_key=True)
class Part(Base):
"""A class describing Parts
Attributes
----------
id: UUID
The primary key of a Part instance in the database
name: str
The name of a Part
modified_timestamp: datetime.datetime
The timestamp when Part was last modified
"""
name: Mapped[str] = mapped_column(String)
modified_timestamp: Mapped[datetime] = mapped_column(
DateTime(timezone=False)
)
def __init__(
self,
id: UUID,
name: str,
modified_timestamp: datetime,
):
self.id = id
self.name = name
self.modified_timestamp = modified_timestamp
class Test(Base):
"""
A class describing Tests
Attributes
----------
part_id: int
id of a Part the Test instance has been run on
timestamp: datetime
The timestamp when Test was ran
succesful: bool
The result of the Test
data: dict[str, str]
Additional json data of the Test
"""
part_id: Mapped[UUID] = mapped_column(
UUID_(as_uuid=True), ForeignKey(Part.id, ondelete="CASCADE")
)
timestamp: Mapped[datetime] = mapped_column(DateTime(timezone=False))
successful: Mapped[bool] = mapped_column(Boolean)
data: Mapped[dict[Any, Any] | None] = mapped_column(JSON, nullable=True)
def __init__(
self,
id: UUID,
part_id: UUID,
timestamp: datetime,
successful: bool,
data: dict[Any, Any] | None = None,
) -> None:
self.id = id
self.part_id = part_id
self.timestamp = timestamp
self.successful = successful
self.data = data
|
# (C) Datadog, Inc. 2023-present
# All rights reserved
# Licensed under a 3-clause BSD style license (see LICENSE)
import concurrent.futures
import logging
from contextlib import nullcontext as does_not_raise
import mock
import pytest
from confluent_kafka.admin._group import ConsumerGroupListing, ListConsumerGroupsResult
from datadog_checks.kafka_consumer import KafkaCheck
from datadog_checks.kafka_consumer.kafka_consumer import _get_interpolated_timestamp
pytestmark = [pytest.mark.unit]
@pytest.mark.parametrize(
'legacy_config, kafka_client_config, value',
[
pytest.param("ssl_check_hostname", "_tls_validate_hostname", False, id='legacy validate_hostname param false'),
pytest.param("ssl_check_hostname", "_tls_validate_hostname", True, id='legacy validate_hostname param true'),
pytest.param("ssl_cafile", "_tls_ca_cert", "ca_file", id='legacy tls_ca_cert param'),
pytest.param("ssl_certfile", "_tls_cert", "cert", id='legacy tls_cert param'),
pytest.param("ssl_keyfile", "_tls_private_key", "private_key", id='legacy tls_private_key param'),
pytest.param(
"ssl_password",
"_tls_private_key_password",
"private_key_password",
id='legacy tls_private_key_password param',
),
],
)
def test_tls_config_legacy(legacy_config, kafka_client_config, value, check):
kafka_consumer_check = check({legacy_config: value})
assert getattr(kafka_consumer_check.config, kafka_client_config) == value
@pytest.mark.parametrize(
'ssl_check_hostname_value, tls_validate_hostname_value, expected_value',
[
pytest.param(True, True, True, id='Both true'),
pytest.param(False, False, False, id='Both false'),
pytest.param(False, True, True, id='only tls_validate_hostname_value true'),
pytest.param(True, False, False, id='only tls_validate_hostname_value false'),
pytest.param(False, "true", True, id='tls_validate_hostname true as string'),
pytest.param(False, "false", False, id='tls_validate_hostname false as string'),
],
)
def test_tls_validate_hostname_conflict(
ssl_check_hostname_value, tls_validate_hostname_value, expected_value, check, kafka_instance
):
kafka_instance.update(
{"ssl_check_hostname": ssl_check_hostname_value, "tls_validate_hostname": tls_validate_hostname_value}
)
kafka_consumer_check = check(kafka_instance)
assert kafka_consumer_check.config._tls_validate_hostname == expected_value
@pytest.mark.parametrize(
'tls_verify, expected',
[
pytest.param({}, "true", id='given empty tls_verify, expect default string true'),
pytest.param({'tls_verify': True}, "true", id='given True tls_verify, expect string true'),
pytest.param(
{
'tls_verify': False,
"tls_cert": None,
"tls_ca_cert": None,
"tls_private_key": None,
"tls_private_key_password": None,
},
"false",
id='given False tls_verify and other TLS options none, expect string false',
),
pytest.param(
{'tls_verify': False, "tls_private_key_password": "password"},
"true",
id='given False tls_verify but TLS password, expect string true',
),
],
)
def test_tls_verify_is_string(tls_verify, expected, check, kafka_instance):
kafka_instance.update(tls_verify)
kafka_consumer_check = check(kafka_instance)
config = kafka_consumer_check.config
assert config._tls_verify == expected
mock_client = mock.MagicMock()
mock_client.get_highwater_offsets.return_value = ({}, "")
@pytest.mark.parametrize(
'sasl_oauth_token_provider, expected_exception, mocked_admin_client',
[
pytest.param(
{},
pytest.raises(Exception, match="sasl_oauth_token_provider required for OAUTHBEARER sasl"),
None,
id="No sasl_oauth_token_provider",
),
pytest.param(
{'sasl_oauth_token_provider': {}},
pytest.raises(Exception, match="The `url` setting of `auth_token` reader is required"),
None,
id="Empty sasl_oauth_token_provider, url missing",
),
pytest.param(
{'sasl_oauth_token_provider': {'url': 'http://fake.url'}},
pytest.raises(Exception, match="The `client_id` setting of `auth_token` reader is required"),
None,
id="client_id missing",
),
pytest.param(
{'sasl_oauth_token_provider': {'url': 'http://fake.url', 'client_id': 'id'}},
pytest.raises(Exception, match="The `client_secret` setting of `auth_token` reader is required"),
None,
id="client_secret missing",
),
pytest.param(
{'sasl_oauth_token_provider': {'url': 'http://fake.url', 'client_id': 'id', 'client_secret': 'secret'}},
does_not_raise(),
mock_client,
id="valid config",
),
],
)
def test_oauth_config(
sasl_oauth_token_provider, expected_exception, mocked_admin_client, check, dd_run_check, kafka_instance
):
kafka_instance.update(
{
'monitor_unlisted_consumer_groups': True,
'security_protocol': 'SASL_PLAINTEXT',
'sasl_mechanism': 'OAUTHBEARER',
}
)
kafka_instance.update(sasl_oauth_token_provider)
with expected_exception:
with mock.patch(
'datadog_checks.kafka_consumer.kafka_consumer.KafkaClient',
return_value=mocked_admin_client,
):
dd_run_check(check(kafka_instance))
# TODO: After these tests are finished and the revamp is complete,
# the tests should be refactored to be parameters instead of separate tests
@mock.patch("datadog_checks.kafka_consumer.kafka_consumer.KafkaClient")
def test_when_consumer_lag_less_than_zero_then_emit_event(
mock_generic_client, check, kafka_instance, dd_run_check, aggregator
):
# Given
# consumer_offset = {(consumer_group, topic, partition): offset}
consumer_offset = {("consumer_group1", "topic1", "partition1"): 2}
# highwater_offset = {(topic, partition): offset}
highwater_offset = {("topic1", "partition1"): 1}
mock_client = mock.MagicMock()
mock_client.get_consumer_offsets.return_value = consumer_offset
mock_client.get_highwater_offsets.return_value = (highwater_offset, "cluster_id")
mock_client.get_partitions_for_topic.return_value = ['partition1']
mock_client.get_consumer_group_state.return_value = "STABLE"
mock_generic_client.return_value = mock_client
# When
kafka_consumer_check = check(kafka_instance)
dd_run_check(kafka_consumer_check)
# Then
aggregator.assert_metric(
"kafka.broker_offset",
count=1,
tags=['optional:tag1', 'partition:partition1', 'topic:topic1', 'kafka_cluster_id:cluster_id'],
)
aggregator.assert_metric(
"kafka.consumer_offset",
count=1,
tags=[
'consumer_group:consumer_group1',
'optional:tag1',
'partition:partition1',
'topic:topic1',
'kafka_cluster_id:cluster_id',
'consumer_group_state:STABLE',
],
)
aggregator.assert_metric(
"kafka.consumer_lag",
count=1,
tags=[
'consumer_group:consumer_group1',
'optional:tag1',
'partition:partition1',
'topic:topic1',
'kafka_cluster_id:cluster_id',
'consumer_group_state:STABLE',
],
)
aggregator.assert_event(
"Consumer group: consumer_group1, "
"topic: topic1, partition: partition1 has negative consumer lag. "
"This should never happen and will result in the consumer skipping new messages "
"until the lag turns positive.",
count=1,
tags=[
'consumer_group:consumer_group1',
'optional:tag1',
'partition:partition1',
'topic:topic1',
'kafka_cluster_id:cluster_id',
'consumer_group_state:STABLE',
],
)
@mock.patch("datadog_checks.kafka_consumer.kafka_consumer.KafkaClient")
def test_when_partition_is_none_then_emit_warning_log(
mock_generic_client, check, kafka_instance, dd_run_check, aggregator, caplog
):
# Given
# consumer_offset = {(consumer_group, topic, partition): offset}
consumer_offset = {("consumer_group1", "topic1", "partition1"): 2}
# highwater_offset = {(topic, partition): offset}
highwater_offset = {("topic1", "partition1"): 1}
mock_client = mock.MagicMock()
mock_client.get_consumer_offsets.return_value = consumer_offset
mock_client.get_highwater_offsets.return_value = (highwater_offset, "cluster_id")
mock_client.get_partitions_for_topic.return_value = None
mock_generic_client.return_value = mock_client
caplog.set_level(logging.WARNING)
# When
kafka_consumer_check = check(kafka_instance)
dd_run_check(kafka_consumer_check)
# Then
aggregator.assert_metric(
"kafka.broker_offset",
count=1,
tags=['optional:tag1', 'partition:partition1', 'topic:topic1', 'kafka_cluster_id:cluster_id'],
)
aggregator.assert_metric("kafka.consumer_offset", count=0)
aggregator.assert_metric("kafka.consumer_lag", count=0)
aggregator.assert_event(
"Consumer group: consumer_group1, "
"topic: topic1, partition: partition1 has negative consumer lag. "
"This should never happen and will result in the consumer skipping new messages "
"until the lag turns positive.",
count=0,
)
expected_warning = (
"Consumer group: consumer_group1 has offsets for topic: topic1, "
"partition: partition1, but that topic has no partitions "
"in the cluster, so skipping reporting these offsets"
)
assert expected_warning in caplog.text
@mock.patch("datadog_checks.kafka_consumer.kafka_consumer.KafkaClient")
def test_when_partition_not_in_partitions_then_emit_warning_log(
mock_generic_client, check, kafka_instance, dd_run_check, aggregator, caplog
):
# Given
# consumer_offset = {(consumer_group, topic, partition): offset}
consumer_offset = {("consumer_group1", "topic1", "partition1"): 2}
# highwater_offset = {(topic, partition): offset}
highwater_offset = {("topic1", "partition1"): 1}
mock_client = mock.MagicMock()
mock_client.get_consumer_offsets.return_value = consumer_offset
mock_client.get_highwater_offsets.return_value = (highwater_offset, "cluster_id")
mock_client.get_partitions_for_topic.return_value = ['partition2']
mock_generic_client.return_value = mock_client
caplog.set_level(logging.WARNING)
# When
kafka_consumer_check = check(kafka_instance)
dd_run_check(kafka_consumer_check)
# Then
aggregator.assert_metric(
"kafka.broker_offset",
count=1,
tags=['optional:tag1', 'partition:partition1', 'topic:topic1', 'kafka_cluster_id:cluster_id'],
)
aggregator.assert_metric("kafka.consumer_offset", count=0)
aggregator.assert_metric("kafka.consumer_lag", count=0)
aggregator.assert_event(
"Consumer group: consumer_group1, "
"topic: topic1, partition: partition1 has negative consumer lag. "
"This should never happen and will result in the consumer skipping new messages "
"until the lag turns positive.",
count=0,
)
expected_warning = (
"Consumer group: consumer_group1 has offsets for topic: topic1, partition: partition1, "
"but that topic partition isn't included in the cluster partitions, "
"so skipping reporting these offsets"
)
assert expected_warning in caplog.text
@mock.patch("datadog_checks.kafka_consumer.kafka_consumer.KafkaClient")
def test_when_highwater_metric_count_hit_context_limit_then_no_more_highwater_metrics(
mock_generic_client, kafka_instance, dd_run_check, aggregator, caplog
):
# Given
# consumer_offset = {(consumer_group, topic, partition): offset}
consumer_offset = {("consumer_group1", "topic1", "partition1"): 2}
# highwater_offset = {(topic, partition): offset}
highwater_offset = {("topic1", "partition1"): 3, ("topic2", "partition2"): 3}
mock_client = mock.MagicMock()
mock_client.get_consumer_offsets.return_value = consumer_offset
mock_client.get_highwater_offsets.return_value = (highwater_offset, "cluster_id")
mock_client.get_partitions_for_topic.return_value = ['partition1']
mock_generic_client.return_value = mock_client
caplog.set_level(logging.WARNING)
# When
kafka_consumer_check = KafkaCheck('kafka_consumer', {'max_partition_contexts': 2}, [kafka_instance])
dd_run_check(kafka_consumer_check)
# Then
aggregator.assert_metric("kafka.broker_offset", count=2)
aggregator.assert_metric("kafka.consumer_offset", count=0)
aggregator.assert_metric("kafka.consumer_lag", count=0)
expected_warning = "Discovered 3 metric contexts"
assert expected_warning in caplog.text
@mock.patch("datadog_checks.kafka_consumer.kafka_consumer.KafkaClient")
def test_when_consumer_metric_count_hit_context_limit_then_no_more_consumer_metrics(
mock_generic_client, kafka_instance, dd_run_check, aggregator, caplog
):
# Given
# consumer_offset = {(consumer_group, topic, partition): offset}
consumer_offset = {("consumer_group1", "topic1", "partition1"): 2, ("consumer_group1", "topic2", "partition2"): 2}
# highwater_offset = {(topic, partition): offset}
highwater_offset = {("topic1", "partition1"): 3, ("topic2", "partition2"): 3}
mock_client = mock.MagicMock()
mock_client.get_consumer_offsets.return_value = consumer_offset
mock_client.get_highwater_offsets.return_value = (highwater_offset, "cluster_id")
mock_client.get_partitions_for_topic.return_value = ['partition1']
mock_generic_client.return_value = mock_client
caplog.set_level(logging.DEBUG)
# When
kafka_consumer_check = KafkaCheck('kafka_consumer', {'max_partition_contexts': 3}, [kafka_instance])
dd_run_check(kafka_consumer_check)
# Then
aggregator.assert_metric("kafka.broker_offset", count=2)
aggregator.assert_metric("kafka.consumer_offset", count=1)
aggregator.assert_metric("kafka.consumer_lag", count=0)
expected_warning = "Discovered 4 metric contexts"
assert expected_warning in caplog.text
expected_debug = "Reported contexts number 1 greater than or equal to contexts limit of 1"
assert expected_debug in caplog.text
def test_when_empty_string_consumer_group_then_skip(kafka_instance):
consumer_groups_result = ListConsumerGroupsResult(
valid=[
ConsumerGroupListing(group_id="", is_simple_consumer_group=True), # Should be filtered out
ConsumerGroupListing(group_id="my_consumer", is_simple_consumer_group=True),
]
)
kafka_instance['monitor_unlisted_consumer_groups'] = True
future = concurrent.futures.Future()
future.set_result(consumer_groups_result)
with mock.patch("datadog_checks.kafka_consumer.client.AdminClient.list_consumer_groups", return_value=future):
kafka_consumer_check = KafkaCheck('kafka_consumer', {}, [kafka_instance])
assert kafka_consumer_check.client._get_consumer_groups() == ["my_consumer"]
def test_get_interpolated_timestamp():
assert _get_interpolated_timestamp({0: 100, 10: 200}, 5) == 150
assert _get_interpolated_timestamp({10: 100, 20: 200}, 5) == 50
assert _get_interpolated_timestamp({0: 100, 10: 200}, 15) == 250
assert _get_interpolated_timestamp({10: 200}, 15) is None
|
<!DOCTYPE html>
<html>
<head>
<!-- Required meta tags -->
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<!-- Bootstrap CSS -->
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@4.4.1/dist/css/bootstrap.min.css"
integrity="sha384-Vkoo8x4CGsO3+Hhxv8T/Q5PaXtkKtu6ug5TOeNV6gBiFeWPGFN9MuhOf23Q9Ifjh" crossorigin="anonymous">
<!-- HTMX -->
<script src="https://unpkg.com/htmx.org@1.9.5"
integrity="sha384-xcuj3WpfgjlKF+FXhSQFQ0ZNr39ln+hwjN3npfM9VBnUskLolQAcN80McRIVOPuO"
crossorigin="anonymous"></script>
</head>
<body>
<form id="form" hx-encoding='multipart/form-data' hx-post="/order/CreateProduct" hx-target="#errorsAlert">
<button type="submit" class="btn btn-primary">
Submit
</button>
<!-- <input type="text" class="form-control" id="inputJson" name="inputJson"
placeholder="Enter promts for your image" contenteditable="true" style="height: 800px;"> -->
<textarea class="form-control" id="inputJson" name="inputJson" style="height: 800px;"></textarea>
</form>
<button type="button" class="btn btn-primary" onclick="CreateJSON()">
Genenerate
</button>
<div>
<a href="/order/GetInfo">
<button type="button" class="btn btn-info">
Go to get order</button>
</a>
</div>
<div id="errorsAlert">
</div>
</body>
<script>
function GenenerateStringWithInt(length) {
const alphabetDictionary = {
0: 'a',
1: 'b',
2: 'c',
3: 'd',
4: 'e',
5: 'f',
6: 'g',
7: 'h',
8: 'i',
9: 'j',
10: 'k',
11: 'l',
12: 'm',
13: 'n',
14: 'o',
15: 'p',
16: 'q',
17: 'r',
18: 's',
19: 't',
20: 'u',
21: 'v',
22: 'w',
23: 'x',
24: 'y',
25: 'z'
};
result = ""
for (let index = 0; index < length; index++) {
var checkLetter = Math.floor(Math.random() * 1)
if (checkLetter == 0) {
var indexAlhabet = Math.floor(Math.random() * 26);
result += alphabetDictionary[indexAlhabet]
} else {
var number = Math.floor(Math.random() * 10)
result += toString(number)
}
}
return result
}
function GenenerateString(length) {
const alphabetDictionary = {
0: 'a',
1: 'b',
2: 'c',
3: 'd',
4: 'e',
5: 'f',
6: 'g',
7: 'h',
8: 'i',
9: 'j',
10: 'k',
11: 'l',
12: 'm',
13: 'n',
14: 'o',
15: 'p',
16: 'q',
17: 'r',
18: 's',
19: 't',
20: 'u',
21: 'v',
22: 'w',
23: 'x',
24: 'y',
25: 'z'
};
result = ""
for (let index = 0; index < length; index++) {
var indexAlhabet = Math.floor(Math.random() * 26);
result += alphabetDictionary[indexAlhabet]
}
return result
}
function GenenerateInt(max) {
return Math.floor(Math.random() * max);
}
function CreateJSON() {
console.log("start create JSON");
var order = new Object()
order.order_uid = GenenerateStringWithInt(20)
order.track_number = GenenerateString(10)
order.entry = GenenerateString(4)
var delivery = new Object()
delivery.name = "Test delivery"
delivery.phone = "+7000000000"
delivery.zip = "2639809"
delivery.city = "Perm"
delivery.address = "Ploshad Mira"
delivery.region = "Perm krai"
delivery.email = "test@gmail.com"
order.delivery = delivery
var payment = new Object()
payment.transaction = order.order_uid
payment.request_id = GenenerateString(5)
payment.currency = "USD"
payment.provider = "wbpay"
payment.amount = GenenerateInt(9999)
payment.payment_dt = GenenerateInt(9999999)
payment.bank = "alpha"
payment.delivery_cost = GenenerateInt(99999)
payment.goods_total = GenenerateInt(999)
payment.custom_fee = GenenerateInt(99)
order.payment = payment
var items = []
var count = Math.floor(Math.random() * 5) + 1;
for (let index = 0; index < count; index++) {
var item = new Object()
item.chrt_id = GenenerateInt(999999)
item.track_number = order.track_number
item.price = GenenerateInt(9999)
item.rid = GenenerateStringWithInt(20)
item.name = "test"
item.sale = GenenerateInt(50)
item.size = "0"
item.total_price = GenenerateInt(9999)
item.nm_id = GenenerateInt(9999999)
item.brand = "Test"
item.status = 202
items.push(item)
}
order.locale = GenenerateString(2)
order.internal_signature = GenenerateString(5)
order.customer_id = GenenerateString(10)
order.delivery_service = GenenerateString(10)
order.shardkey = GenenerateStringWithInt(5)
order.sm_id = GenenerateInt(9999)
order.date_created = "2021-11-26T06:22:19Z"
order.oof_shard = GenenerateStringWithInt(5)
order.items = items
var jsonString = JSON.stringify(order, null, 2)
document.getElementById('inputJson').value = jsonString
}
</script>
|
Shader "Custom/LambertDiffusionLighting"
{
Properties {
_diffuseMap ("Texture", 2D) = "white" {}
_normalMap ("Normal", 2D) = "bump" {}
_materialColor ("Material Color", Color) = (0.5, 0.5, 0.5, 1)
_ambientIntensity ("Ambient Light Color", Color) = (0, 0, 1, 1)
_ambientReflection ("Ambient Reflection Constant", Range(0, 1)) = 1
_diffuseIntensity ("Diffuse Light Color", Color) = (0, 0, 1, 1)
_diffuseReflection ("Diffuse Reflection Constant", Range(0, 1)) = 1
}
SubShader {
Tags {
"Queue" = "Geometry"
}
CGPROGRAM
#pragma surface surf LambertDiffusion
struct Input {
float2 uv_diffuseMap;
float2 uv_normalMap;
};
sampler2D _diffuseMap;
sampler2D _normalMap;
fixed4 _materialColor;
fixed4 _ambientIntensity;
half _ambientReflection;
fixed4 _diffuseIntensity;
half _diffuseReflection;
void surf(Input IN, inout SurfaceOutput o) {
half4 diffuseColor = tex2D(_diffuseMap, IN.uv_diffuseMap);
o.Albedo = diffuseColor.rgb * _materialColor.rgb;
o.Alpha = diffuseColor.a * _materialColor.a;
o.Normal = normalize(UnpackNormal(tex2D(_normalMap, IN.uv_normalMap)).xyz);
}
// Experimenting with fixed4 (11-bit precision)
half4 LightingLambertDiffusion(SurfaceOutput s, half3 lightDir, half atten) {
half4 ambient = half4(_ambientReflection * _ambientIntensity.rgb * atten, _ambientIntensity.a);
half3 lightDirNorm = normalize(lightDir);
half LdotN = saturate(dot(lightDirNorm, s.Normal));
half4 diffuse = half4(_diffuseReflection * s.Albedo * LdotN * _diffuseIntensity * atten, s.Alpha);
return diffuse + ambient;
}
ENDCG
}
FallBack "Diffuse"
}
|
<template>
<div>
<form @submit.prevent="onSubmit">
<loading v-if="!formSchema" />
<b-loading :active="submitting" />
<form-generator
v-if="formSchema"
:schema="filteredSchema"
v-model="data"
:initial-data="initialData"
:show-labels="false"
:errors="errors"
class="field"/>
<!-- <div class="control has-text-centered">
<b-field>
<b-input
expanded
placeholder="Invite to Organization" />
<b-button
class="submit-button--secondary"
type="is-secondary"> {{ $t('webapp.orgs.send_email') }} </b-button>
</b-field>
</div> -->
<div class="control submit-button__wrapper has-text-centered">
<b-button
ref="submit"
:disabled="submitting"
native-type="submit"
type="is-primary"
class="submit-button">{{ $t('webapp.orgs.create') }}</b-button>
</div>
</form>
</div>
</template>
<script>
import FormGenerator from '@/components/form-generator/FormGenerator';
import Loading from '@/components/shared/Loading';
import { mapActions } from 'vuex';
export default {
name: 'CreateOrgForm',
components: {
FormGenerator,
Loading,
},
data() {
return {
data: null,
formSchema: null,
errors: {},
submitting: false,
};
},
computed: {
initialData() {
return {};
},
filteredSchema() {
if (!this.formSchema) return null;
const { description, ...schema } = this.formSchema;
description.type = 'text';
return { ...schema, description };
},
},
async mounted() {
const response = await this.getNewOrgSchema();
this.formSchema = response;
},
methods: {
...mapActions([
'getNewOrgSchema',
'createOrg',
]),
async onSubmit() {
this.submitting = true;
try {
const response = await this.createOrg(this.data);
this.$emit('created', response.data.nickname);
} catch (error) {
const data = error.response && error.response.data;
if (data) {
this.errors = data;
}
} finally {
this.submitting = false;
}
},
},
};
</script>
<style lang="scss" scoped>
.submit-button {
padding: 0 3rem;
&__wrapper {
margin-top: 3.5rem;
}
&--secondary {
margin-left: 0.625rem;
}
}
</style>
|
import { UniverseLayer } from "@formant/universe";
import * as THREE from "three";
export class LightsaberLayer extends UniverseLayer {
static layerTypeId = "lightsaber";
static commonName = "Lightsaber";
static description = "A weapon of a more civilized age.";
saberGeo = new THREE.BoxGeometry(0.0418, 0.0418, 0.91);
saberMat = new THREE.MeshBasicMaterial({ color: 0xffff00 });
saberCube = new THREE.Mesh(this.saberGeo, this.saberMat);
baseGeo = new THREE.BoxGeometry(0.04318, 0.04318, 0.2286);
baseMat = new THREE.MeshBasicMaterial({ color: 0xbac4e2 });
baseCube = new THREE.Mesh(this.baseGeo, this.baseMat);
init() {
this.baseCube.add(this.saberCube);
this.saberCube.position.set(0, 0, -0.5);
this.add(this.baseCube);
}
onEnterVR(xr: THREE.WebXRManager): void {
xr.getControllerGrip(1).add(this.baseCube);
}
onExitVR(xr: THREE.WebXRManager): void {
xr.getControllerGrip(1).remove(this.baseCube);
}
onGamePadButtonChanged(
_source: THREE.XRInputSource,
_button: number,
value: number
): void {
if (value === 1) {
const randomColor = Math.random() * 0xffffff;
this.saberMat.color.set(randomColor);
}
}
destroy(): void {
this.baseGeo.dispose();
this.baseMat.dispose();
this.saberGeo.dispose();
this.saberMat.dispose();
}
}
|
import { FormLayout, Input, KeyValueInput } from "@components/Form";
import {
TextInput,
Button,
Textarea,
Modal,
useMantineTheme,
List,
Divider,
Text,
Flex,
Loader,
Card,
} from "@mantine/core";
import {
IconAlertCircle,
IconArrowsTransferUp,
IconCheck,
IconTrash,
} from "@tabler/icons";
import {
ADD_MODERATOR,
DELETE_COMMUNITY,
REMOVE_MODERATOR,
UPDATE_COMMUNITY,
} from "@operations/mutations";
import ImageInput from "@components/Form/ImageInput";
import { useMutation, useQuery } from "@apollo/client";
import {
GET_COMMUNITY_MEMBERS_BY_NAME,
GET_COMMUNITY_MODERATORS,
GET_COMMUNITY_RULES,
} from "@operations/queries";
import { useState } from "react";
import { useDisclosure } from "@mantine/hooks";
import { useForm } from "@mantine/form";
import { notifications } from "@mantine/notifications";
import TableSelection from "@components/Form/Table";
import CMSearch from "@components/Search/CMSearch";
import { Role } from "@prisma/client";
type data = {
data: {
id: string;
name: string;
description: string;
avatar: string;
banner: string;
};
};
const example = {
data: [
{
id: "1",
avatar:
"https://images.unsplash.com/photo-1624298357597-fd92dfbec01d?ixlib=rb-1.2.1&ixid=MnwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&auto=format&fit=crop&w=250&q=80",
name: "Robert Wolfkisser",
job: "Engineer",
email: "rob_wolf@gmail.com",
},
{
id: "2",
avatar:
"https://images.unsplash.com/photo-1586297135537-94bc9ba060aa?ixlib=rb-1.2.1&ixid=MnwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&auto=format&fit=crop&w=250&q=80",
name: "Jill Jailbreaker",
job: "Engineer",
email: "jj@breaker.com",
},
{
id: "3",
avatar:
"https://images.unsplash.com/photo-1632922267756-9b71242b1592?ixlib=rb-1.2.1&ixid=MnwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&auto=format&fit=crop&w=250&q=80",
name: "Henry Silkeater",
job: "Designer",
email: "henry@silkeater.io",
},
{
id: "4",
avatar:
"https://images.unsplash.com/photo-1507003211169-0a1dd7228f2d?ixlib=rb-1.2.1&ixid=MnwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&auto=format&fit=crop&w=250&q=80",
name: "Bill Horsefighter",
job: "Designer",
email: "bhorsefighter@gmail.com",
},
{
id: "5",
avatar:
"https://images.unsplash.com/photo-1630841539293-bd20634c5d72?ixlib=rb-1.2.1&ixid=MnwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&auto=format&fit=crop&w=250&q=80",
name: "Jeremy Footviewer",
job: "Manager",
email: "jeremy@foot.dev",
},
],
};
const CommunitySettingForm = (props: data) => {
const { id, name, description, avatar, banner } = props.data;
const [opened, { open, close }] = useDisclosure(false);
const theme = useMantineTheme();
const deleteForm = useForm({
initialValues: {
confirm: "",
},
validate: (values) => {
const errors: Record<string, string> = {};
if (values.confirm !== name) {
errors.confirm = `Please type ${name} to confirm`;
}
return errors;
},
});
const [isDeleting, setIsDeleting] = useState(false);
const [deleteCommunity] = useMutation(DELETE_COMMUNITY);
const { data: moderators } = useQuery(GET_COMMUNITY_MODERATORS, {
variables: { communityId: id },
});
const { loading, data: rules } = useQuery(GET_COMMUNITY_RULES, {
variables: { communityId: id },
});
const [addModerator] = useMutation(ADD_MODERATOR);
const [removeModerator] = useMutation(REMOVE_MODERATOR);
return (
<>
<FormLayout
layout={"horizontal"}
label={"Community Avatar"}
description={"The avatar of the community"}
input={
<ImageInput
img={`https://ik.imagekit.io/umtfellow/tr:h-600/${avatar}`}
mutation={UPDATE_COMMUNITY({ avatar: true })}
imgName={name}
argType={"avatar"}
variables={{ id: id }}
/>
}
/>
<FormLayout
layout={"horizontal"}
label={"Community banner"}
description={"The banner of the community"}
input={
<ImageInput
isBanner
img={`https://ik.imagekit.io/umtfellow/tr:h-600/${banner}`}
mutation={UPDATE_COMMUNITY({ banner: true })}
imgName={name}
argType={"banner"}
variables={{ id: id }}
/>
}
/>
<FormLayout
layout={"vertical"}
label={"Community Name"}
description={"The name of the community"}
input={
<Input
argType="name"
component={TextInput}
mutation={UPDATE_COMMUNITY({ name: true })}
variables={{ id: id }}
placeholder={name || "Community Name"}
value={name}
mt="-1em"
mb="1em"
/>
}
/>
<FormLayout
layout={"vertical"}
label={"Community Description"}
description={"The description of the community"}
input={
<Input
argType="description"
component={Textarea}
mutation={UPDATE_COMMUNITY({ description: true })}
variables={{ id: id }}
mt="-1em"
mb="1em"
placeholder={description || "Community Description"}
value={description}
/>
}
/>
<FormLayout
layout={"vertical"}
label={"Moderators"}
description={
"Add or remove moderators from the community. Maximum 5 mods."
}
input={
<>
<CMSearch
onChange={(val) => {
console.log(val);
}}
placeholder="Search for members"
query={GET_COMMUNITY_MEMBERS_BY_NAME}
queryVar={{
communityId: id,
role: Role.USER,
}}
onItemSubmit={async (item) => {
const res = await addModerator({
variables: {
communityId: id,
userId: item.id,
},
update: (cache, { data }) => {
const existing: any = cache.readQuery({
query: GET_COMMUNITY_MODERATORS,
variables: { communityId: id },
});
const newModerator = data?.addModerator;
cache.writeQuery({
query: GET_COMMUNITY_MODERATORS,
variables: { communityId: id },
data: {
getCommunityModerators: [
...(existing?.getCommunityModerators || []),
newModerator,
],
},
});
},
});
}}
/>
<Card withBorder mt="md">
{moderators && moderators.getCommunityModerators.length > 0 ? (
<TableSelection
communityId={id}
data={(moderators && moderators.getCommunityModerators) || []}
/>
) : (
<Card>
<Text>
There is no moderators yet for{" "}
<Text fw="bold" span>
{name}
</Text>{" "}
community.
</Text>
</Card>
)}
</Card>
</>
}
/>
{loading || (
<FormLayout
layout={"vertical"}
label={"Community Rules"}
description={
'Add specific rules to govern the conduct and content within your community. By defining clear guidelines, you can foster a positive and inclusive environment for all members. Use the "Rule" input to provide a concise description of the rule, and the "Description" input to provide additional details and context for better understanding and adherence.'
}
input={
<KeyValueInput
_key="Name"
value="Description"
data={rules.getCommunityRules || []}
communityId={id}
/>
}
/>
)}
{/* <FormLayout
layout={"horizontal"}
label={"Archive Community"}
description={
"Activate this setting to transition a community into an archived state. Once archived, the community will no longer be actively participatory, but users can still view its content and history. It is an ideal option for preserving valuable discussions while limiting further interactions such as joining or posting new content."
}
input={
<Button
fullWidth
type="reset"
color="orange"
variant="light"
leftIcon={<IconTrash size={16} />}
>
Archive Community
</Button>
}
/> */}
<Divider color="red" label="Danger zone" my="md" />
{/* <FormLayout
layout={"horizontal"}
label={"Transfer Ownership"}
description={
"Transfer ownership of the community to another moderator."
}
input={
<Button
fullWidth
type="reset"
color="orange"
variant="light"
leftIcon={<IconArrowsTransferUp size={16} />}
>
Transfer Ownership
</Button>
}
/> */}
<FormLayout
layout={"horizontal"}
label={"Delete Community"}
description={
"By deleting the community, you will lose all the data associated with it. This action is irreversible."
}
input={
<>
<Button
fullWidth
type="reset"
color="red"
variant="light"
leftIcon={<IconTrash size={16} />}
onClick={open}
>
Delete Community
</Button>
<Modal
opened={opened}
onClose={close}
centered
title={
<Text fw="bolder" color="red">
<Flex gap="xs" align="center">
<IconAlertCircle color="red" size={18} />
Delete {name}
</Flex>
</Text>
}
overlayProps={{
color:
theme.colorScheme === "dark"
? theme.colors.dark[9]
: theme.colors.gray[2],
opacity: 0.55,
blur: 3,
}}
size="lg"
>
<Modal.Body>
Please take note of the following points before proceeding with
the community deletion:
<List>
<List.Item>
This action is permanent and cannot be undone.
</List.Item>
<List.Item>
Deleting the community will remove all content, discussions,
and member data associated with it.
</List.Item>
<List.Item>
Consider alternative options such as addressing concerns
through moderation or rule changes.
</List.Item>
<List.Item>
Once deleted, the community cannot be recovered.
</List.Item>
</List>
<Divider my="md" />
<Text fw="bold">
Are you absolutely certain you want to proceed with deleting
the community?
</Text>
<Text>
Please type the{" "}
<Text fw="bold" span>
{name}
</Text>{" "}
to confirm:
</Text>
<TextInput {...deleteForm.getInputProps("confirm")} />
<Button
fullWidth
color="red"
mt="md"
disabled={isDeleting || deleteForm.values.confirm !== name}
leftIcon={isDeleting && <Loader size="xs" />}
onClick={async () => {
setIsDeleting(true);
try {
await deleteCommunity({
variables: { id: id },
update: (cache) => {
cache.evict({
id: cache.identify({
__typename: "Community",
id: id,
}),
});
},
});
notifications.show({
title: "Community deleted",
message: `The community ${name} has been deleted.`,
color: "green",
icon: <IconCheck size={18} />,
});
// router.push("/");
} catch (err: any) {
notifications.show({
title: "An error occurred.",
message: err.message,
color: "red",
icon: <IconAlertCircle size={18} />,
});
} finally {
setIsDeleting(false);
deleteForm.reset();
close();
}
}}
>
Yes I'm sure - Delete Community
</Button>
</Modal.Body>
</Modal>
</>
}
/>
</>
);
};
export default CommunitySettingForm;
|
// Copyright (c) 2023 The Brave Authors. All rights reserved.
// This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this file,
// You can obtain one at https://mozilla.org/MPL/2.0/.
// Assets
import {
UpholdIcon,
GeminiIcon,
ZebpayIcon,
BitflyerIcon
} from '../assets/svg-icons/provider_icons'
// Utils
import { getLocale } from "../../common/locale"
// Types
import {
externalWalletProviders
} from "../common/async/brave_rewards_api_proxy"
import { BraveWallet } from "../constants/types"
import {
ExternalWalletProvider
} from '../../brave_rewards/resources/shared/lib/external_wallet'
export const getRewardsProviderName = (provider: string) => {
const capitalized = provider.charAt(0).toUpperCase() + provider.slice(1)
const localeString = `braveWallet${capitalized}`
const foundLocale = getLocale(localeString)
// If getLocale returns the string it was passed, that means
// no localization string was found. So we return the
// provider in that case.
return foundLocale === localeString
? provider
: foundLocale
}
export const getRewardsAccountName = (provider?: string) => {
if (!provider) {
return ''
}
return getLocale('braveWalletRewardsAccount')
.replace('$1', getRewardsProviderName(provider))
}
export const getRewardsTokenDescription =
(provider: ExternalWalletProvider | null) => {
if (!provider) {
return ''
}
return getLocale('braveWalletBraveRewardsDescription')
.replace('$1', getRewardsProviderName(provider))
}
export const getNormalizedExternalRewardsWallet =
(externalRewardsProvider?: ExternalWalletProvider | null) => {
if (!externalRewardsProvider) {
return undefined
}
return {
accountId: {
address: '0x',
bitcoinAccountIndex: 0,
coin: BraveWallet.CoinType.ETH,
keyringId: 0,
kind: 0,
uniqueKey: externalRewardsProvider
},
address: '0x',
hardware: undefined,
name: getRewardsAccountName(externalRewardsProvider)
}
}
export const getNormalizedExternalRewardsNetwork =
(externalRewardsProvider?: ExternalWalletProvider | null) => {
if (!externalRewardsProvider) {
return undefined
}
return {
activeRpcEndpointIndex: 0,
blockExplorerUrls: [''],
chainId: externalRewardsProvider,
chainName: getRewardsProviderName(externalRewardsProvider),
coin: 0,
supportedKeyrings: [],
decimals: 0,
iconUrls: [],
isEip1559: true,
rpcEndpoints: [],
symbol: externalRewardsProvider,
symbolName: externalRewardsProvider
}
}
export const getIsRewardsAccount =
(accountId?: Pick<BraveWallet.AccountId, 'uniqueKey'>) => {
if (!accountId) {
return false
}
return externalWalletProviders
.includes(accountId.uniqueKey)
}
export const getIsRewardsNetwork =
(network?: Pick<BraveWallet.NetworkInfo, 'chainId'>) => {
if (!network) {
return false
}
return externalWalletProviders
.includes(network.chainId)
}
export const getIsRewardsToken =
(token?: Pick<BraveWallet.BlockchainToken, 'chainId'>) => {
if (!token) {
return false
}
return externalWalletProviders
.includes(token.chainId)
}
export const getRewardsProviderIcon =
(provider: ExternalWalletProvider | null) => {
switch (provider) {
case 'bitflyer': return BitflyerIcon
case 'gemini': return GeminiIcon
case 'uphold': return UpholdIcon
case 'zebpay': return ZebpayIcon
default: return ''
}
}
export const getRewardsProviderBackground =
(provider: ExternalWalletProvider | null) => {
switch (provider) {
case 'bitflyer': return 'rgb(52, 152, 212)'
case 'gemini': return 'rgb(97, 217, 245)'
case 'uphold': return 'rgb(73, 204, 104)'
case 'zebpay': return 'rgb(3, 116, 242)'
default: return ''
}
}
export const getRewardsBATToken =
(provider: ExternalWalletProvider | undefined) => {
if (!provider) {
return undefined
}
return {
contractAddress: '0x0D8775F648430679A709E98d2b0Cb6250d2887EF',
name: 'Basic Attention Token',
symbol: 'BAT',
logo: 'chrome://erc-token-images/bat.png',
isErc20: true,
isErc721: false,
isErc1155: false,
isNft: false,
isSpam: false,
decimals: 18,
visible: true,
tokenId: '',
coingeckoId: '',
coin: BraveWallet.CoinType.ETH,
chainId: provider
}
}
|
# `justify-content`
Свойство, с помощью которого можно выровнять элементы вдоль оси строки. Данное свойство работает, только если общая ширина столбцов меньше ширины контейнера сетки. Другими словами, вам нужно свободное пространство вдоль оси строки контейнера, чтобы выровнять его столбцы слева или справа.
## Пример
```css
.container {
display: grid;
justify-content: start;
}
```
## Значения
### `justify-content: start` (по умолчанию)
Выравнивает сетку по левой стороне грид-контейнера.
### `justify-content: end`
Выравнивает сетку по правой стороне грид-контейнера.
### `justify-content: center`
Выравнивает сетку по центру грид-контейнера.
### `justify-content: stretch`
Масштабирует элементы, чтобы сетка могла заполнить всю ширину грид-контейнера.
### `justify-content: space-around`
Одинаковое пространство между элементами и полуразмерные отступы по краям.
### `justify-content: space-evenly`
Одинаковое пространство между элементами и полноразмерные отступы по краям.
### `justify-content: space-between`
Одинаковое пространство между элементами без отступов по краям.
|
#!/usr/bin/python3
"""Defines an empty class BaseGeometry."""
class BaseGeometry:
"""
Empty class representing the base geometry.
Methods:
- area(self): Raises an exception with the message
"area() is not implemented."
- integer_validator(self, name, value): Validates if a value is
a positive integer.
"""
def area(self):
"""
Raises an exception with the message "area() is not implemented."
Returns:
- None
"""
raise Exception("area() is not implemented")
def integer_validator(self, name, value):
"""
Validates if a value is a positive integer.
Args:
- name (str): The name of the value.
- value (int): The value to be validated.
Returns:
- None
Raises:
- TypeError: If the value is not an integer.
- ValueError: If the value is not greater than 0.
"""
if type(value) != int:
raise TypeError("{} must be an integer".format(name))
elif value <= 0:
raise ValueError("{} must be greater than 0".format(name))
|
import os
import time
import unittest
from typing import Tuple
import numpy as np
from robot_arm_controller.control.arm_kinematics import ArmParameters
from robot_arm_controller.controller import ArmController, Settings
from robot_arm_controller.utils.prints import console
class TestController(unittest.TestCase):
controller: ArmController
EPSILON = 0.1
@classmethod
def setUpClass(cls) -> None:
console.log("Starting test_controller.py!", style="bold green")
# Arm parameters
arm_params: ArmParameters = ArmParameters()
arm_params.a2x = 0
arm_params.a2z = 172.48
arm_params.a3z = 173.5
arm_params.a4z = 0
arm_params.a4x = 126.2
arm_params.a5x = 64.1
arm_params.a6x = 169
cls.controller = ArmController(arm_parameters=arm_params)
cls.controller.start(websocket_server=False, wait=True)
cls.controller.print_status = os.environ.get("PRINT_STATUS", "False").upper() == "TRUE"
console.log("Runing with print_status:", cls.controller.print_status, style="bold green")
cls.controller.set_setting_joints(Settings.STEPS_PER_REV_MOTOR_AXIS, 800)
cls.controller.set_setting_joints(Settings.CONVERSION_RATE_AXIS_JOINTS, 1)
cls.controller.set_setting_joints(Settings.SPEED_RAD_PER_S, 0.3)
cls.controller.set_setting_joints(Settings.HOMING_OFFSET_RADS, np.pi / 4)
cls.controller.home()
@classmethod
def tearDownClass(cls) -> None:
cls.controller.stop()
def tearDown(self) -> None:
self.controller.move_to_angles([0, 0, 0, 0, 0, 0])
self.controller.wait_done_moving()
def test_health_check(self) -> None:
console.log("Running test: test_health_check", style="bold yellow")
self.assertTrue(self.controller.health_check())
def test_move_to(self) -> None:
console.log("Running test: test_move_to", style="bold yellow")
epsilon = 0.01
self.controller.wait_done_moving()
angles = [0.1, 0.2, 0.3, 0.4, 0.5, 0.6]
self.controller.move_to_angles(angles)
self.controller.wait_done_moving()
all_close = np.allclose(self.controller.current_angles, angles, atol=epsilon)
self.assertTrue(all_close, msg=f"Expected {angles}, got {self.controller.current_angles}")
angles = [0.2, 0.3, 0.4, 0.5, 0.6, 0.7]
self.controller.move_to_angles(angles)
self.controller.wait_done_moving()
all_close = np.allclose(self.controller.current_angles, angles, atol=epsilon)
self.assertTrue(all_close, msg=f"Expected {angles}, got {self.controller.current_angles}")
angles = [0.0, 0.0, 0.0, 0.0, 0.0, 0.0]
self.controller.move_to_angles(angles)
self.controller.wait_done_moving()
all_close = np.allclose(self.controller.current_angles, angles, atol=epsilon)
self.assertTrue(all_close, msg=f"Expected {angles}, got {self.controller.current_angles}")
angles = [-0.1, -0.2, -0.3, -0.4, -0.5, -0.6]
self.controller.move_to_angles(angles)
self.controller.wait_done_moving()
all_close = np.allclose(self.controller.current_angles, angles, atol=epsilon)
self.assertTrue(all_close, msg=f"Expected {angles}, got {self.controller.current_angles}")
def test_double_home(self) -> None:
console.log("Running test: test_double_home", style="bold yellow")
self.controller.wait_done_moving()
self.controller.home()
self.assertTrue(np.allclose(self.controller.current_angles, [0, 0, 0, 0, 0, 0], atol=0.1))
self.assertTrue(self.controller.is_homed)
self.controller.home()
self.assertTrue(self.controller.is_homed)
self.assertTrue(np.allclose(self.controller.current_angles, [0, 0, 0, 0, 0, 0], atol=0.1))
def get_and_set_joint_settings(
self, setting_key: Settings, init_value: float, change_per_iter: bool = True
) -> Tuple[bool, str]:
console.log(f"Running test: test_joint_settings for {setting_key}", style="bold yellow")
# homing_direction
correct = True
for i in range(self.controller.num_joints):
if change_per_iter:
value = init_value + i
else:
value = init_value
self.controller.set_setting_joint(setting_key, value, i)
setting = self.controller.get_setting_joint(setting_key, i)
correct = correct and (abs(setting - value) < self.EPSILON)
return correct, f"Expected {value}, got {setting}"
def test_joint_settings(self) -> None:
console.log("Running test: test_joint_settings", style="bold yellow")
correct, msg = self.get_and_set_joint_settings(Settings.HOMING_DIRECTION, -1, False)
correct, msg = self.get_and_set_joint_settings(Settings.HOMING_DIRECTION, 1, False)
self.assertTrue(correct, msg)
correct, msg = self.get_and_set_joint_settings(Settings.SPEED_RAD_PER_S, 1.2)
self.assertTrue(correct, msg)
correct, msg = self.get_and_set_joint_settings(Settings.STEPS_PER_REV_MOTOR_AXIS, 220)
correct, msg = self.get_and_set_joint_settings(Settings.STEPS_PER_REV_MOTOR_AXIS, 5000, False)
self.assertTrue(correct, msg)
correct, msg = self.get_and_set_joint_settings(Settings.CONVERSION_RATE_AXIS_JOINTS, 1.128)
correct, msg = self.get_and_set_joint_settings(Settings.CONVERSION_RATE_AXIS_JOINTS, 1, False)
self.assertTrue(correct, msg)
correct, msg = self.get_and_set_joint_settings(Settings.HOMING_OFFSET_RADS, np.pi / 7)
correct, msg = self.get_and_set_joint_settings(Settings.HOMING_OFFSET_RADS, np.pi / 4, False)
self.assertTrue(correct, msg)
def test_speed_settings(self) -> None:
console.log("Running test: test_speed_settings", style="bold yellow")
self.controller.wait_done_moving()
self.controller.set_setting_joints(Settings.SPEED_RAD_PER_S, 1)
speeds = self.controller.get_setting_joints(Settings.SPEED_RAD_PER_S)
self.assertTrue(np.allclose(speeds, [1, 1, 1, 1, 1, 1], atol=0.1))
self.controller.move_to_angles([0, 0, 0, 0, 0, 0])
self.controller.wait_done_moving()
start_time = time.time()
self.controller.move_to_angles([1, 1, 1, 1, 1, 1])
self.controller.wait_done_moving()
end_time = time.time()
speeds = self.controller.get_setting_joints(Settings.SPEED_RAD_PER_S)
self.assertTrue(np.allclose(speeds, [1, 1, 1, 1, 1, 1], atol=0.1))
self.assertTrue(end_time - start_time < 1.4, msg=f"Expected 1s, got {end_time - start_time}")
self.controller.move_to_angles([0, 0, 0, 0, 0, 0])
self.controller.set_setting_joints(Settings.SPEED_RAD_PER_S, 0.5)
start_time = time.time()
self.controller.move_to_angles([1, 1, 1, 1, 1, 1])
self.controller.wait_done_moving()
end_time = time.time()
self.assertTrue(end_time - start_time > 1.9, msg=f"Expected 2s, got {end_time - start_time}")
self.controller.set_setting_joints(Settings.SPEED_RAD_PER_S, 1)
def test_set_tool_value(self) -> None:
console.log("Running test: test_set_tool_value", style="bold yellow")
self.controller.set_tool_value(0)
self.controller.wait_done_moving()
all_close = np.allclose(self.controller.tool_value, 0, atol=0.15)
self.assertTrue(all_close, msg=f"Expected {0} got {self.controller.tool_value}")
self.controller.set_tool_value(1)
self.controller.wait_done_moving()
all_close = np.allclose(self.controller.tool_value, 1, atol=0.15)
self.assertTrue(all_close, msg=f"Expected {1} got {self.controller.tool_value}")
self.controller.set_tool_value(-1)
self.controller.wait_done_moving()
all_close = np.allclose(self.controller.tool_value, -1, atol=0.15)
self.assertTrue(all_close, msg=f"Expected {-1} got {self.controller.tool_value}")
self.controller.set_tool_value(0.5)
self.controller.wait_done_moving()
all_close = np.allclose(self.controller.tool_value, 0.5, atol=0.15)
self.assertTrue(all_close, msg=f"Expected {0.5} got {self.controller.tool_value}")
self.controller.set_tool_value(-0.5)
self.controller.wait_done_moving()
all_close = np.allclose(self.controller.tool_value, -0.5, atol=0.15)
self.assertTrue(all_close, msg=f"Expected {-0.5} got {self.controller.tool_value}")
def test_speed_with_modified_settings(self) -> None:
console.log("Running test: test_speed_with_modified_settings", style="bold yellow")
self.controller.move_to_angles([0, 0, 0, 0, 0, 0])
self.controller.wait_done_moving()
self.controller.set_setting_joints(Settings.CONVERSION_RATE_AXIS_JOINTS, 1.5)
self.controller.set_setting_joint(Settings.CONVERSION_RATE_AXIS_JOINTS, 4, 2)
self.controller.set_setting_joint(Settings.CONVERSION_RATE_AXIS_JOINTS, 1, 1)
self.controller.set_setting_joints(Settings.STEPS_PER_REV_MOTOR_AXIS, 8000)
self.controller.set_setting_joint(Settings.STEPS_PER_REV_MOTOR_AXIS, 3434, 0)
self.controller.set_setting_joint(Settings.STEPS_PER_REV_MOTOR_AXIS, 6457, 3)
self.controller.set_setting_joints(Settings.SPEED_RAD_PER_S, 1)
speeds = self.controller.get_setting_joints(Settings.SPEED_RAD_PER_S)
self.assertTrue(np.allclose(speeds, [1, 1, 1, 1, 1, 1], atol=0.1))
self.controller.wait_done_moving()
self.assertTrue(np.allclose(self.controller.current_angles, [0, 0, 0, 0, 0, 0], atol=0.1))
start_time = time.time()
self.controller.move_to_angles([1, 1, 1, 1, 1, 1])
self.controller.wait_done_moving()
self.assertTrue(np.allclose(self.controller.current_angles, [1, 1, 1, 1, 1, 1], atol=0.1))
end_time = time.time()
self.assertTrue(end_time - start_time < 1.4, msg=f"Expected 1s, got {end_time - start_time}")
speeds = self.controller.get_setting_joints(Settings.SPEED_RAD_PER_S)
self.assertTrue(np.allclose(speeds, [1, 1, 1, 1, 1, 1], atol=0.1))
def test_move_queue_size(self) -> None:
self.controller.wait_done_moving()
self.controller.move_to_angles([0, 0, 0, 0, 0, 0])
time.sleep(1)
self.controller.wait_done_moving()
self.assertTrue(np.allclose(self.controller.current_angles, [0, 0, 0, 0, 0, 0], atol=0.1))
self.controller.set_setting_joints(Settings.SPEED_RAD_PER_S, 0.4)
self.controller.move_to_angles([-1, -1, -1, -1, -1, -1])
time.sleep(1)
self.assertEqual(self.controller.move_queue_size, 1)
self.controller.move_to_angles([0.7, 0.7, 0.7, 0.7, 0.7, 0.7])
self.controller.move_to_angles([0.8, 0.8, 0.8, 0.8, 0.8, 0.8])
self.controller.move_to_angles([0.9, 0.9, 0.9, 0.9, 0.9, 0.9])
self.controller.set_tool_value(1)
time.sleep(1)
self.assertEqual(self.controller.move_queue_size, 5)
self.controller.wait_done_moving()
self.assertEqual(self.controller.move_queue_size, 0)
self.controller.set_setting_joints(Settings.SPEED_RAD_PER_S, 0.1)
self.controller.move_to_angles([-0.7, -0.7, -0.7, -0.7, -0.7, -0.7])
self.controller.move_to_angles([-0.8, -0.8, -0.8, -0.8, -0.8, -0.8])
self.controller.move_to_angles([-0.9, -0.9, -0.9, -0.9, -0.9, -0.9])
# make sure the queue is size 3
time.sleep(0.5)
self.assertEqual(self.controller.move_queue_size, 3)
self.controller.stop_movement()
time.sleep(0.5)
self.assertEqual(self.controller.move_queue_size, 0)
|
//
// ViewControllerObserver.swift
// PerformanceSuite
//
// Created by Maryin Nikita on 06/07/2021.
//
import ObjectiveC.runtime
import UIKit
protocol ViewControllerObserver {
func beforeInit(viewController: UIViewController)
func beforeViewDidLoad(viewController: UIViewController)
func afterViewWillAppear(viewController: UIViewController)
func afterViewDidAppear(viewController: UIViewController)
func beforeViewWillDisappear(viewController: UIViewController)
func beforeViewDidDisappear(viewController: UIViewController)
}
final class ViewControllerObserverFactory<T: ViewControllerObserver>: ViewControllerObserver {
required init(metricsReceiver: ScreenMetricsReceiver, observerMaker: @escaping () -> T) {
self.metricsReceiver = metricsReceiver
self.observerMaker = observerMaker
}
private let metricsReceiver: ScreenMetricsReceiver
private let observerMaker: () -> T
static func existingObserver(for viewController: UIViewController) -> T? {
var vc: UIViewController? = viewController
while let current = vc {
let tPointer = unsafeBitCast(T.self, to: UnsafeRawPointer.self)
if let result = objc_getAssociatedObject(current, tPointer) as? T {
return result
}
vc = current.parent
}
return nil
}
private func observer(for viewController: UIViewController) -> T? {
guard metricsReceiver.shouldTrack(viewController: viewController) else {
return nil
}
if let observer = Self.existingObserver(for: viewController) {
return observer
}
let tPointer = unsafeBitCast(T.self, to: UnsafeRawPointer.self)
let observer = observerMaker()
objc_setAssociatedObject(viewController, tPointer, observer, .OBJC_ASSOCIATION_RETAIN_NONATOMIC)
return observer
}
func beforeInit(viewController: UIViewController) {
observer(for: viewController)?.beforeInit(viewController: viewController)
}
func beforeViewDidLoad(viewController: UIViewController) {
observer(for: viewController)?.beforeViewDidLoad(viewController: viewController)
}
func afterViewDidAppear(viewController: UIViewController) {
observer(for: viewController)?.afterViewDidAppear(viewController: viewController)
}
func beforeViewWillDisappear(viewController: UIViewController) {
observer(for: viewController)?.beforeViewWillDisappear(viewController: viewController)
}
func afterViewWillAppear(viewController: UIViewController) {
observer(for: viewController)?.afterViewWillAppear(viewController: viewController)
}
func beforeViewDidDisappear(viewController: UIViewController) {
observer(for: viewController)?.beforeViewDidDisappear(viewController: viewController)
}
}
class ViewControllerObserverCollection: ViewControllerObserver {
init(observers: [ViewControllerObserver]) {
self.observers = observers
}
private let observers: [ViewControllerObserver]
func beforeInit(viewController: UIViewController) {
observers.forEach { o in
o.beforeInit(viewController: viewController)
}
}
func beforeViewDidLoad(viewController: UIViewController) {
observers.forEach { o in
o.beforeViewDidLoad(viewController: viewController)
}
}
func afterViewDidAppear(viewController: UIViewController) {
observers.forEach { o in
o.afterViewDidAppear(viewController: viewController)
}
}
func afterViewWillAppear(viewController: UIViewController) {
observers.forEach { o in
o.afterViewWillAppear(viewController: viewController)
}
}
func beforeViewWillDisappear(viewController: UIViewController) {
observers.forEach { o in
o.beforeViewWillDisappear(viewController: viewController)
}
}
func beforeViewDidDisappear(viewController: UIViewController) {
observers.forEach { o in
o.beforeViewDidDisappear(viewController: viewController)
}
}
}
|
# Wave animation
import matplotlib.pyplot as plt
import numpy as np
import matplotlib.animation as animation
# initial conditions
k = 2.0
w = 2.0
x_m = 10.0
# wave form)
def h(s):
if s > -10 and s < -9:
return .5
return 0
# Time, Space / simulation parameters
dt = .01
dx = .01
t_end = 1000
t = np.arange(0,t_end, dt)
x = np.arange(-x_m,x_m, dx)
# Compute dynamics
y = []
for i in range(0, t_end):
y.append(list(map(lambda x: h(k*x - w*t[i]), x)))
# Animate
fig, ((ax)) = plt.subplots(1,1)
ax.set_ylim(bottom=-1,top=1)
ax.set_xlim(left=-x_m,right=x_m)
line, = ax.plot([], [], lw=3)
ax.grid(1)
def animate(i):
line.set_data(x, y[i])
return line,
anim = animation.FuncAnimation(fig, animate, interval=5, blit=True)
plt.show()
|
package edu.lehigh.cse216.emp520.backend;
import java.util.Date;
import java.util.ArrayList;
/**
* DataRowIdea holds a row of idea information. A row of idea information consists of
* an idea_id, the username of the poster, the content, athe numbers of upvotes and downvotes,
* a list of all associated comments, and a validity.
*
* Because we will ultimately be converting instances of this object into JSON
* directly, we need to make the fields public. That being the case, we will
* not bother with having getters and setters... instead, we will allow code to
* interact with the fields directly.
*/
public class DataRowIdea {
/**
* The unique identifier associated with this element. It's final, because
* we never want to change it.
*/
public final int mId;
/**
* The foreign key for an idea.
* uUsername connects an idea to it's poster.
*/
public String uUsername;
/**
* The remaining attributes associated with ideas, including their relevant comments
*/
public String mContent;
public int mUpvotes;
public int mDownvotes;
public boolean mValid;
public ArrayList<DataRowComment> mComments;
/**
* The creation date for this row of data. Once it is set, it cannot be
* changed
*/
public final Date mCreated;
public String mFilename;
public String mBase64;
public String mLink;
public String mFileID;
/**
* Create a new DataRowIdea with the provided data, and a
* creation date based on the system clock at the time the constructor was
* called
*
* @param id the idea_id of the idea
* @param username the username of the poster of this idea
* @param content the content of the idea
* @param upvotes the number of upvotes on the idea
* @param downvotes the number of downvotes on the idea
* @param comments the comments associated with this idea
* @param valid the validity of this idea (whether or not it is allowed to appear in the app)
*/
DataRowIdea(int id, String username, String content, int upvotes, int downvotes, ArrayList<DataRowComment> comments, boolean valid, String base64, String filename, String link, String fileID) {
mId = id;
uUsername = username;
mContent = content;
mUpvotes = upvotes;
mDownvotes = downvotes;
mComments = comments;
mValid = valid;
mCreated = new Date();
mBase64 = base64;
mFilename = filename;
mLink = link;
mFileID = fileID;
}
/**
* Copy constructor to create one DataRowIdea from another
*
* @param data the DataRowIdea that we want to make a copy of
*/
DataRowIdea(DataRowIdea data) {
mId = data.mId;
uUsername = data.uUsername;
mContent = data.mContent;
mUpvotes = data.mUpvotes;
mDownvotes = data.mDownvotes;
mValid = data.mValid;
mComments = data.mComments;
mCreated = data.mCreated;
mFilename = data.mFilename;
mBase64 = data.mBase64;
mLink = data.mLink;
mFileID = data.mFileID;
}
}
|
import {CraftingRecipe, RequiredEquipment} from "../../Interfaces/Crafting/ICraftingRecipe.sol";
import {ItemType, MaterialRequirement} from "../../Interfaces/GameObjects/IGameObjects.sol";
import {CraftingMaterial} from "../../Interfaces/GameObjects/ICrafting/ICraftingMaterials.sol";
pragma solidity ^0.8.0;
contract ArmorLightRecipes {
function recipe(uint id) external view returns (CraftingRecipe memory _recipe) {
if (id == 43) return SoldiersTunic();
else if (id == 44) return PriestsTunic();
else if (id == 45) return FaithTunic();
else if (id == 46) return TraineesTunic();
else if (id == 47) return MagiciansShirt();
else if (id == 48) return SealedShirt();
else if (id == 49) return GateKeepersShirt();
else if (id == 50) return ElementalistsShirt();
else if (id == 51) return AlcemistsJacket();
else if (id == 52) return ArchmagesJacket();
else if (id == 53) return ElvenJacket();
else if (id == 54) return ChosensJacket();
else if (id == 55) return ProphetsJacket();
else if (id == 56) return EldersJacket();
else if (id == 57) return AncientCuirass();
else if (id == 58) return MoonlightCuirass();
else if (id == 59) return SunlightCuirass();
else if (id == 60) return CycleCuirass();
else if (id == 61) return DemonicRobe();
else if (id == 62) return AngelicRobe();
else if (id == 63) return EternalRobe();
revert(".la");
}
function SoldiersTunic() public view returns (CraftingRecipe memory _recipe) {
_recipe.requiredGold = 50;
_recipe.requiredEssence = 5;
_recipe.materialRequirements = new MaterialRequirement[](1);
_recipe.materialRequirements[0] = MaterialRequirement({
material : CraftingMaterial.JUTE,
amount : 20
});
}
function PriestsTunic() public view returns (CraftingRecipe memory _recipe) {
_recipe.requiredGold = 50;
_recipe.requiredEssence = 5;
_recipe.materialRequirements = new MaterialRequirement[](2);
_recipe.materialRequirements[0] = MaterialRequirement({
material : CraftingMaterial.BOLT_OF_JUTE,
amount : 28
});
}
function FaithTunic() public view returns (CraftingRecipe memory _recipe) {
_recipe.requiredGold = 50;
_recipe.requiredEssence = 5;
_recipe.materialRequirements = new MaterialRequirement[](2);
_recipe.materialRequirements[0] = MaterialRequirement({
material : CraftingMaterial.BOLT_OF_WOOL,
amount : 16
});
_recipe.materialRequirements[1] = MaterialRequirement({
material : CraftingMaterial.BOLT_OF_JUTE,
amount : 16
});
}
function TraineesTunic() public view returns (CraftingRecipe memory _recipe) {
_recipe.requiredGold = 50;
_recipe.requiredEssence = 5;
_recipe.materialRequirements = new MaterialRequirement[](2);
_recipe.materialRequirements[0] = MaterialRequirement({
material : CraftingMaterial.BOLT_OF_WOOL,
amount : 28
});
_recipe.materialRequirements[1] = MaterialRequirement({
material : CraftingMaterial.BOLT_OF_JUTE,
amount : 8
});
}
function MagiciansShirt() public view returns (CraftingRecipe memory _recipe) {
_recipe.requiredGold = 50;
_recipe.requiredEssence = 5;
_recipe.materialRequirements = new MaterialRequirement[](2);
_recipe.materialRequirements[0] = MaterialRequirement({
material : CraftingMaterial.BOLT_OF_COTTON,
amount : 16
});
_recipe.materialRequirements[1] = MaterialRequirement({
material : CraftingMaterial.BOLT_OF_WOOL,
amount : 16
});
}
function SealedShirt() public view returns (CraftingRecipe memory _recipe) {
_recipe.requiredGold = 50;
_recipe.requiredEssence = 5;
_recipe.materialRequirements = new MaterialRequirement[](2);
_recipe.materialRequirements[0] = MaterialRequirement({
material : CraftingMaterial.BOLT_OF_COTTON,
amount : 28
});
_recipe.materialRequirements[1] = MaterialRequirement({
material : CraftingMaterial.BOLT_OF_WOOL,
amount : 8
});
}
function GateKeepersShirt() public view returns (CraftingRecipe memory _recipe) {
_recipe.requiredGold = 50;
_recipe.requiredEssence = 5;
_recipe.materialRequirements = new MaterialRequirement[](2);
_recipe.materialRequirements[0] = MaterialRequirement({
material : CraftingMaterial.BOLT_OF_LINEN,
amount : 16
});
_recipe.materialRequirements[1] = MaterialRequirement({
material : CraftingMaterial.BOLT_OF_COTTON,
amount : 16
});
}
function ElementalistsShirt() public view returns (CraftingRecipe memory _recipe) {
_recipe.requiredGold = 50;
_recipe.requiredEssence = 5;
_recipe.materialRequirements = new MaterialRequirement[](2);
_recipe.materialRequirements[0] = MaterialRequirement({
material : CraftingMaterial.BOLT_OF_LINEN,
amount : 28
});
_recipe.materialRequirements[1] = MaterialRequirement({
material : CraftingMaterial.BOLT_OF_COTTON,
amount : 8
});
}
function AlcemistsJacket() public view returns (CraftingRecipe memory _recipe) {
_recipe.requiredGold = 50;
_recipe.requiredEssence = 5;
_recipe.materialRequirements = new MaterialRequirement[](2);
_recipe.materialRequirements[0] = MaterialRequirement({
material : CraftingMaterial.BOLT_OF_SILK,
amount : 16
});
_recipe.materialRequirements[1] = MaterialRequirement({
material : CraftingMaterial.BOLT_OF_LINEN,
amount : 16
});
}
function ArchmagesJacket() public view returns (CraftingRecipe memory _recipe) {
_recipe.requiredGold = 50;
_recipe.requiredEssence = 5;
_recipe.materialRequirements = new MaterialRequirement[](2);
_recipe.materialRequirements[0] = MaterialRequirement({
material : CraftingMaterial.BOLT_OF_SILK,
amount : 28
});
_recipe.materialRequirements[1] = MaterialRequirement({
material : CraftingMaterial.BOLT_OF_LINEN,
amount : 8
});
}
function ElvenJacket() public view returns (CraftingRecipe memory _recipe) {
_recipe.requiredGold = 50;
_recipe.requiredEssence = 5;
_recipe.materialRequirements = new MaterialRequirement[](2);
_recipe.materialRequirements[0] = MaterialRequirement({
material : CraftingMaterial.BOLT_OF_HEMP,
amount : 16
});
_recipe.materialRequirements[1] = MaterialRequirement({
material : CraftingMaterial.BOLT_OF_SILK,
amount : 16
});
}
function ChosensJacket() public view returns (CraftingRecipe memory _recipe) {
_recipe.requiredGold = 50;
_recipe.requiredEssence = 5;
_recipe.materialRequirements = new MaterialRequirement[](2);
_recipe.materialRequirements[0] = MaterialRequirement({
material : CraftingMaterial.BOLT_OF_HEMP,
amount : 28
});
_recipe.materialRequirements[1] = MaterialRequirement({
material : CraftingMaterial.BOLT_OF_SILK,
amount : 8
});
}
function ProphetsJacket() public view returns (CraftingRecipe memory _recipe) {
_recipe.requiredGold = 50;
_recipe.requiredEssence = 5;
_recipe.materialRequirements = new MaterialRequirement[](2);
_recipe.materialRequirements[0] = MaterialRequirement({
material : CraftingMaterial.BOLT_OF_CASHMERE,
amount : 16
});
_recipe.materialRequirements[1] = MaterialRequirement({
material : CraftingMaterial.BOLT_OF_HEMP,
amount : 16
});
}
function EldersJacket() public view returns (CraftingRecipe memory _recipe) {
_recipe.requiredGold = 50;
_recipe.requiredEssence = 5;
_recipe.materialRequirements = new MaterialRequirement[](2);
_recipe.materialRequirements[0] = MaterialRequirement({
material : CraftingMaterial.BOLT_OF_CASHMERE,
amount : 28
});
_recipe.materialRequirements[1] = MaterialRequirement({
material : CraftingMaterial.BOLT_OF_HEMP,
amount : 8
});
}
function AncientCuirass() public view returns (CraftingRecipe memory _recipe) {
_recipe.requiredGold = 50;
_recipe.requiredEssence = 5;
_recipe.materialRequirements = new MaterialRequirement[](2);
_recipe.materialRequirements[0] = MaterialRequirement({
material : CraftingMaterial.BOLT_OF_VISCOSE,
amount : 16
});
_recipe.materialRequirements[1] = MaterialRequirement({
material : CraftingMaterial.BOLT_OF_CASHMERE,
amount : 16
});
}
function MoonlightCuirass() public view returns (CraftingRecipe memory _recipe) {
_recipe.requiredGold = 50;
_recipe.requiredEssence = 5;
_recipe.materialRequirements = new MaterialRequirement[](2);
_recipe.materialRequirements[0] = MaterialRequirement({
material : CraftingMaterial.BOLT_OF_VISCOSE,
amount : 28
});
_recipe.materialRequirements[1] = MaterialRequirement({
material : CraftingMaterial.BOLT_OF_CASHMERE,
amount : 8
});
}
function SunlightCuirass() public view returns (CraftingRecipe memory _recipe) {
_recipe.requiredGold = 50;
_recipe.requiredEssence = 5;
_recipe.materialRequirements = new MaterialRequirement[](2);
_recipe.materialRequirements[0] = MaterialRequirement({
material : CraftingMaterial.BOLT_OF_LYOCELL,
amount : 16
});
_recipe.materialRequirements[1] = MaterialRequirement({
material : CraftingMaterial.BOLT_OF_VISCOSE,
amount : 16
});
}
function CycleCuirass() public view returns (CraftingRecipe memory _recipe) {
_recipe.requiredGold = 50;
_recipe.requiredEssence = 5;
_recipe.materialRequirements = new MaterialRequirement[](2);
_recipe.materialRequirements[0] = MaterialRequirement({
material : CraftingMaterial.BOLT_OF_LYOCELL,
amount : 28
});
_recipe.materialRequirements[1] = MaterialRequirement({
material : CraftingMaterial.BOLT_OF_VISCOSE,
amount : 8
});
_recipe.equipmentRequirements = new RequiredEquipment[](2);
_recipe.equipmentRequirements[0] = RequiredEquipment({
itemType: ItemType.ARMOR,
id: 58
});
_recipe.equipmentRequirements[1] = RequiredEquipment({
itemType: ItemType.ARMOR,
id: 59
});
}
function DemonicRobe() public view returns (CraftingRecipe memory _recipe) {
_recipe.requiredGold = 50;
_recipe.requiredEssence = 5;
_recipe.materialRequirements = new MaterialRequirement[](2);
_recipe.materialRequirements[0] = MaterialRequirement({
material : CraftingMaterial.BOLT_OF_RAYON,
amount : 16
});
_recipe.materialRequirements[1] = MaterialRequirement({
material : CraftingMaterial.BOLT_OF_LYOCELL,
amount : 16
});
}
function AngelicRobe() public view returns (CraftingRecipe memory _recipe) {
_recipe.requiredGold = 50;
_recipe.requiredEssence = 5;
_recipe.materialRequirements = new MaterialRequirement[](2);
_recipe.materialRequirements[0] = MaterialRequirement({
material : CraftingMaterial.BOLT_OF_RAYON,
amount : 28
});
_recipe.materialRequirements[1] = MaterialRequirement({
material : CraftingMaterial.BOLT_OF_LYOCELL,
amount : 8
});
}
function EternalRobe() public view returns (CraftingRecipe memory _recipe) {
_recipe.requiredGold = 50;
_recipe.requiredEssence = 5;
_recipe.materialRequirements = new MaterialRequirement[](10);
_recipe.materialRequirements[0] = MaterialRequirement({
material : CraftingMaterial.BOLT_OF_RAYON,
amount : 50
});
_recipe.materialRequirements[1] = MaterialRequirement({
material : CraftingMaterial.BOLT_OF_JUTE,
amount : 33
});
_recipe.materialRequirements[2] = MaterialRequirement({
material : CraftingMaterial.BOLT_OF_WOOL,
amount : 33
});
_recipe.materialRequirements[3] = MaterialRequirement({
material : CraftingMaterial.BOLT_OF_COTTON,
amount : 33
});
_recipe.materialRequirements[4] = MaterialRequirement({
material : CraftingMaterial.BOLT_OF_LINEN,
amount : 33
});
_recipe.materialRequirements[5] = MaterialRequirement({
material : CraftingMaterial.BOLT_OF_SILK,
amount : 33
});
_recipe.materialRequirements[6] = MaterialRequirement({
material : CraftingMaterial.BOLT_OF_HEMP,
amount : 33
});
_recipe.materialRequirements[7] = MaterialRequirement({
material : CraftingMaterial.BOLT_OF_CASHMERE,
amount : 33
});
_recipe.materialRequirements[8] = MaterialRequirement({
material : CraftingMaterial.BOLT_OF_VISCOSE,
amount : 33
});
_recipe.materialRequirements[9] = MaterialRequirement({
material : CraftingMaterial.BOLT_OF_LYOCELL,
amount : 33
});
}
}
|
// SPDX-License-Identifier: BSL 1.1
pragma solidity ^0.8.13;
import {Math} from "openzeppelin-contracts/contracts/utils/math/Math.sol";
import {Ownable} from "openzeppelin-contracts/contracts/access/Ownable.sol";
import {AccessControl} from "openzeppelin-contracts/contracts/access/AccessControl.sol";
import {ERC20} from "openzeppelin-contracts/contracts/token/ERC20/ERC20.sol";
import {IAccessControl} from "openzeppelin-contracts/contracts/access/IAccessControl.sol";
import {IERC20} from "openzeppelin-contracts/contracts/token/ERC20/IERC20.sol";
import {IERC20Metadata} from "openzeppelin-contracts/contracts/token/ERC20/extensions/IERC20Metadata.sol";
import {IOffchainFundUser} from "src/interfaces/IOffchainFundUser.sol";
import {IOffchainFundAdmin} from "src/interfaces/IOffchainFundAdmin.sol";
interface IOffchainFund is
IOffchainFundUser,
IOffchainFundAdmin,
IAccessControl,
IERC20,
IERC20Metadata
{
struct Order {
uint256 epoch;
uint256 amount;
}
/// @dev Net asset value of the fund
/// @return nav Net asset value
function nav() external view returns (uint256 nav);
/// @dev Maximum `USDC` balance that can be held
/// @return cap Maximum `USDC` balance that can be held
function cap() external view returns (uint256 cap);
/// @dev Minimum `USDC` balance that can be deposited
/// @return min Minimum `USDC` balance that can be deposited
function min() external view returns (uint256 min);
/// @dev Current increment for the net asset value updates
/// @return epoch Current increment for the net asset value updates
function epoch() external view returns (uint256 epoch);
/// @dev Price per share as calculated by the net asset value
/// @return currentPrice Price per share
function currentPrice() external view returns (uint256 currentPrice);
/// @dev Total number of shares
/// @return totalShares Total number of shares
function totalShares() external view returns (uint256 totalShares);
/// @dev State of a user's pending deposits
/// @param account Address that placed the order
/// @return epoch The epoch of the deposit
/// @return amount The amount of `USDC` deposited
function userDeposits(
address account
) external view returns (uint256 epoch, uint256 amount);
/// @dev State of a user's pending redemptions
/// @param account Address that placed the order
/// @return epoch The epoch of the redeem
/// @return amount The amount of fund shares to redeem
function userRedemptions(
address account
) external view returns (uint256 epoch, uint256 amount);
/// @dev Checks criteria for receiving fund shares
/// @param account Address that placed the order
/// @return canProcess Whether the order can be processed or not
/// @return message The message for why the order can/can't be processed
function canProcessDeposit(
address account
) external returns (bool canProcess, string memory message);
/// @dev Checks criteria for receiving `USDC`
/// @param account Address that placed the order
/// @return canProcess Whether the order can be processed or not
/// @return message The message for why the order can/can't be processed
function canProcessRedeem(
address account
) external returns (bool canProcess, string memory message);
/// @dev Checks that the address is a member of the whitelist
/// @param account Address that placed the order
/// @return _isWhitelisted Whether the address is a member of the whitelist
function isWhitelisted(
address account
) external view returns (bool _isWhitelisted);
}
contract OffchainFund is Ownable, AccessControl, ERC20, IOffchainFund {
bytes32 public constant WHITELIST =
keccak256(abi.encode("offchain.fund.whitelist"));
uint8 public immutable DECIMAL_FACTOR;
IERC20 public immutable usdc;
bool public drained = false;
uint256 public cap = 0;
uint256 public min = 1e6;
uint256 public epoch = 1;
uint256 public currentPrice = 1e8;
uint256 public tempMint = 0;
uint256 public pendingDeposits = 0;
uint256 public currentDeposits = 0;
uint256 public tempBurn = 0;
uint256 public pendingRedemptions = 0;
uint256 public currentRedemptions = 0;
uint256 public preDrainDepositCount = 0;
uint256 public postDrainDepositCount = 0;
uint256 public currentDepositCount = 0;
mapping(address => Order) public userDeposits;
mapping(address => Order) public userRedemptions;
constructor(
address owner,
address usdc_,
string memory name_,
string memory symbol_
) ERC20(name_, symbol_) {
_transferOwnership(owner);
_grantRole(DEFAULT_ADMIN_ROLE, owner);
usdc = IERC20(usdc_);
DECIMAL_FACTOR = IERC20Metadata(usdc_).decimals();
}
/// @notice Transfer `USDC` to the contract
/// @param assets Number of `USDC` tokens to be transferred to the contract
function refill(uint256 assets) external {
assert(usdc.transferFrom(_msgSender(), address(this), assets));
emit Refill(_msgSender(), epoch, assets);
}
/// @notice Place order to receive fund shares by depositing `USDC`
/// @param assets Number of `USDC` tokens to deposit
function deposit(uint256 assets) external onlyRole(WHITELIST) {
uint256 amount;
uint256 balance;
require(assets >= min, "deposit is less than the minimum");
require(
cap >= pendingDeposits + assets,
"deposit would exceed epoch cap"
);
(bool valid, ) = _canProcessDeposit(_msgSender());
require(!valid, "user has unprocessed userDeposits");
balance = usdc.balanceOf(address(this));
assert(usdc.transferFrom(_msgSender(), address(this), assets));
// Ensure any fee taken on the transfer is accounted for
amount = usdc.balanceOf(address(this)) - balance;
// We restrict a user from adding to their deposit if they had made one
// before `drain` was called.
if (drained) {
uint256 userEpoch = userDeposits[_msgSender()].epoch;
require(
userEpoch == 0 || userEpoch == epoch + 1,
"cannot add to deposit after drain"
);
userDeposits[_msgSender()].epoch = epoch + 1;
postDrainDepositCount = userDeposits[_msgSender()].amount == 0
? postDrainDepositCount + 1
: postDrainDepositCount;
} else {
userDeposits[_msgSender()].epoch = epoch;
preDrainDepositCount = userDeposits[_msgSender()].amount == 0
? preDrainDepositCount + 1
: preDrainDepositCount;
}
pendingDeposits += amount;
userDeposits[_msgSender()].amount += amount;
emit Deposit(_msgSender(), epoch, amount);
}
/// @notice Process the batch of deposit orders for accounts to receive fund shares
/// @param accountList Address list that placed orders
function batchProcessDeposit(address[] calldata accountList) external {
address account;
uint256 length = accountList.length;
for (uint256 i = 0; i < length; ++i) {
account = accountList[i];
(bool valid, ) = _canProcessDeposit(account);
if (!valid) continue;
_processDeposit(account);
}
}
/// @notice Process the deposit order for account to receive fund shares
/// @param account Address that placed the order
function processDeposit(address account) external {
(bool valid, string memory message) = _canProcessDeposit(account);
require(valid, message);
_processDeposit(account);
}
/// @notice Process the redeem order for an account to receive `USDC`
/// @param account Address that placed the order
function _processDeposit(address account) private {
// sanity checks, should never fail, added just in case
assert(currentPrice > 0);
assert(currentDepositCount > 0);
uint256 assets = userDeposits[account].amount;
assert(currentDeposits >= assets);
uint256 shares = (assets * 1e8 * 1e18) /
(currentPrice * 10 ** DECIMAL_FACTOR);
delete userDeposits[account];
currentDepositCount--;
currentDeposits -= assets;
// Safety restriction to prevent overflow from rounding
tempMint -= Math.min(shares, tempMint);
address recipient = _isWhitelisted(account) ? account : owner();
_mint(recipient, shares);
emit ProcessDeposit(
_msgSender(),
recipient,
epoch,
shares,
assets,
currentPrice
);
}
/// @notice Checks criteria for receiving fund shares
/// @param account Address that placed the order
/// @return bool Whether the order can be processed or not
/// @return string The message for why the order can/can't be processed
function canProcessDeposit(
address account
) external view returns (bool, string memory) {
return _canProcessDeposit(account);
}
/// @notice Checks criteria for receiving fund shares
/// @param account Address that placed the order
/// @return bool Whether the order can be processed or not
/// @return string The message for why the order can/can't be processed
function _canProcessDeposit(
address account
) private view returns (bool, string memory) {
if (userDeposits[account].epoch == 0)
return (false, "account has no mint order");
if (userDeposits[account].epoch >= epoch)
return (false, "nav has not been updated for mint");
return (true, "");
}
/// @notice Place order to receive `USDC` by burning fund shares
/// @param shares Number of fund tokens to burn
function redeem(uint256 shares) external onlyRole(WHITELIST) {
(bool valid, ) = _canProcessRedeem(_msgSender());
require(!valid, "user has unprocessed redemptions");
_burnFrom(_msgSender(), shares);
pendingRedemptions += shares;
userRedemptions[_msgSender()].epoch = drained ? epoch + 1 : epoch;
userRedemptions[_msgSender()].amount += shares;
emit Redeem(_msgSender(), epoch, shares);
}
/// @notice Process the batch of redeem orders for accounts to receive `USDC`
/// @param accountList Address list that placed orders
function batchProcessRedeem(
address[] calldata accountList
) external onlyOwner {
address account;
uint256 length = accountList.length;
for (uint256 i = 0; i < length; ++i) {
account = accountList[i];
(bool valid, ) = _canProcessRedeem(account);
if (!valid) continue;
_processRedeem(account);
}
}
/// @notice Process the redeem order for an account to receive `USDC`
/// @param account Address that placed the order
function processRedeem(address account) external onlyOwner {
(bool valid, string memory message) = _canProcessRedeem(account);
require(valid, message);
_processRedeem(account);
}
/// @notice Process the redeem order for an account to receive `USDC`
/// @param account Address that placed the order
function _processRedeem(address account) private {
uint256 shares = userRedemptions[account].amount;
uint256 value = (shares * currentPrice) / 1e8;
// sanity checks, should never fail, added just in case
assert(currentRedemptions > 0);
assert(currentRedemptions >= shares);
uint256 contractsUsdcBalance = usdc.balanceOf(address(this));
assert(contractsUsdcBalance > 0);
uint256 balance = contractsUsdcBalance -
Math.min(contractsUsdcBalance, pendingDeposits);
uint256 available = (shares * balance * 1e18) /
(currentRedemptions * 10 ** DECIMAL_FACTOR);
currentRedemptions -= shares;
address recipient = _isWhitelisted(account) ? account : owner();
if (value > available) {
/**
*
* This calculation can be done in one of two ways:
*
* 1) Take the percentage of the total value being redeemed and
* subract it from the order:
*
* (amount * (value - available)) / value
*
* 2) Take the amount of tokens required to transfer out the amount
* of value the user is redeeming:
*
* (available * 1e8) / currentPrice
*
* Both methods are mathematically identical since:
*
* amount * (available / value)
* = amount * (available / (currentPrice * amount) / 1e8)
* = (available * 1e8) / currentPrice
*
*/
// Safety restriction to prevent overflow in case of rounding
uint256 deduct = Math.min(
(available * 1e8) / currentPrice,
userRedemptions[account].amount
);
userRedemptions[account].epoch = epoch;
userRedemptions[account].amount -= deduct;
pendingRedemptions += userRedemptions[account].amount;
// Safety restriction to prevent overflow from rounding
available = Math.min(
(available * 10 ** DECIMAL_FACTOR) / 1e18,
contractsUsdcBalance
);
assert(usdc.transfer(recipient, available));
emit ProcessRedeem(
_msgSender(),
recipient,
epoch,
deduct,
available,
currentPrice,
false
);
return;
}
delete userRedemptions[account];
// Safety restriction to prevent overflow in case of rounding
value = Math.min(
(value * 10 ** DECIMAL_FACTOR) / 1e18,
contractsUsdcBalance
);
assert(usdc.transfer(recipient, value));
emit ProcessRedeem(
_msgSender(),
recipient,
epoch,
shares,
value,
currentPrice,
true
);
}
/// @notice Checks criteria for receiving `USDC`
/// @param account Address that placed the order
/// @return bool Whether the order can be processed or not
/// @return string The message for why the order can/can't be processed
function canProcessRedeem(
address account
) external view returns (bool, string memory) {
return _canProcessRedeem(account);
}
/// @notice Checks criteria for receiving `USDC`
/// @param account Address that placed the order
/// @return bool Whether the order can be processed or not
/// @return string The message for why the order can/can't be processed
function _canProcessRedeem(
address account
) private view returns (bool, string memory) {
if (userRedemptions[account].epoch == 0)
return (false, "account has no redeem order");
if (userRedemptions[account].epoch >= epoch)
return (false, "nav has not been updated for redeem");
return (true, "");
}
/// @notice Pulls the maximum amount of available `USDC`
function drain() external onlyOwner {
require(!drained, "price has not been updated");
drained = true;
uint256 assets = pendingDeposits;
currentDeposits += pendingDeposits;
pendingDeposits = 0;
uint256 shares = pendingRedemptions;
currentRedemptions += pendingRedemptions;
pendingRedemptions = 0;
tempBurn = shares;
assert(usdc.transfer(_msgSender(), assets));
emit Drain(_msgSender(), epoch, assets, shares);
}
/// @notice Update the NAV per share for the fund and increment the epoch
/// @param price New share price
function update(uint256 price) external onlyOwner {
require(price > 0, "price cannot be set to 0");
require(drained, "user deposits have not been pulled");
require(
currentDepositCount == 0,
"deposits have not been fully processed"
);
++epoch;
drained = false;
currentPrice = price;
currentDepositCount = preDrainDepositCount;
preDrainDepositCount = postDrainDepositCount;
postDrainDepositCount = 0;
tempBurn = 0;
tempMint =
(currentDeposits * 1e8 * 1e18) /
(currentPrice * 10 ** DECIMAL_FACTOR);
emit Update(_msgSender(), epoch, currentPrice, totalShares());
}
/// @notice Net asset value of the fund
/// @return uint256 Net asset value of the fund
function nav() external view returns (uint256) {
return (currentPrice * totalShares()) / 1e8;
}
/// @notice Total supply of shares
/// @return uint256 Total supply of shares
function totalShares() public view returns (uint256) {
return tempMint + tempBurn + pendingRedemptions + totalSupply();
}
/// @notice Sets the limit on USDC accepted per epoch
/// @param cap_ The new limit on deposits
function adjustCap(uint256 cap_) external onlyOwner {
cap = cap_;
}
/// @notice Sets the minimum deposit amount
/// @param min_ The new minimum deposit
function adjustMin(uint256 min_) external onlyOwner {
min = min_;
}
/// @notice Adds an address to the whitelist
/// @param account Address to add to the whitelist
function addToWhitelist(address account) external {
grantRole(WHITELIST, account);
}
/// @notice Process batch of addresses to be whitelisted
/// @param accounts Address list to add to whitlist
function batchAddToWhitelist(address[] calldata accounts) external {
uint256 length = accounts.length;
for (uint256 i = 0; i < length; ++i) {
grantRole(WHITELIST, accounts[i]);
}
}
/// @notice Process batch of addresses to be removed the whitelist
/// @param account Address to remove from the whitelist
function removeFromWhitelist(address account) external {
revokeRole(WHITELIST, account);
}
/// @notice Process batch of addresses to be removed from whitelist
/// @param accounts Address list to remove from whitlist
function batchRemoveFromWhitelist(address[] calldata accounts) external {
uint256 length = accounts.length;
for (uint256 i = 0; i < length; ++i) {
revokeRole(WHITELIST, accounts[i]);
}
}
/// @notice Checks that the address is a member of the whitelist
/// @param account Address that placed the order
/// @return bool Whether the address is a member of the whitelist
function isWhitelisted(address account) external view returns (bool) {
return _isWhitelisted(account);
}
/// @notice Checks that the address is a member of the whitelist
/// @param account Address that placed the order
/// @return bool Whether the address is a member of the whitelist
function _isWhitelisted(address account) private view returns (bool) {
return hasRole(WHITELIST, account);
}
/// @notice transfer `ETH` to the sender/owner
function recover() external onlyOwner {
payable(_msgSender()).transfer(address(this).balance);
}
/// @notice transfer `ERC-20` tokens to the sender/owner
/// @param token_ Asset transferred out
/// @return bool Status of the transfer
function recover(address token_) external onlyOwner returns (bool) {
IERC20 token = IERC20(token_);
return token.transfer(_msgSender(), token.balanceOf(address(this)));
}
function _beforeTokenTransfer(
address from,
address to,
uint256
) internal override {
require(
to == address(0) || hasRole(WHITELIST, to),
"receiver address is not in the whitelist"
);
require(
from == address(0) || hasRole(WHITELIST, from),
"sender address is not in the whitelist"
);
}
function _burnFrom(address account, uint256 amount) private {
_spendAllowance(account, address(this), amount);
_burn(account, amount);
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.8.0) (utils/math/Math.sol)
pragma solidity ^0.8.0;
/**
* @dev Standard math utilities missing in the Solidity language.
*/
library Math {
enum Rounding {
Down, // Toward negative infinity
Up, // Toward infinity
Zero // Toward zero
}
/**
* @dev Returns the largest of two numbers.
*/
function max(uint256 a, uint256 b) internal pure returns (uint256) {
return a > b ? a : b;
}
/**
* @dev Returns the smallest of two numbers.
*/
function min(uint256 a, uint256 b) internal pure returns (uint256) {
return a < b ? a : b;
}
/**
* @dev Returns the average of two numbers. The result is rounded towards
* zero.
*/
function average(uint256 a, uint256 b) internal pure returns (uint256) {
// (a + b) / 2 can overflow.
return (a & b) + (a ^ b) / 2;
}
/**
* @dev Returns the ceiling of the division of two numbers.
*
* This differs from standard division with `/` in that it rounds up instead
* of rounding down.
*/
function ceilDiv(uint256 a, uint256 b) internal pure returns (uint256) {
// (a + b - 1) / b can overflow on addition, so we distribute.
return a == 0 ? 0 : (a - 1) / b + 1;
}
/**
* @notice Calculates floor(x * y / denominator) with full precision. Throws if result overflows a uint256 or denominator == 0
* @dev Original credit to Remco Bloemen under MIT license (https://xn--2-umb.com/21/muldiv)
* with further edits by Uniswap Labs also under MIT license.
*/
function mulDiv(
uint256 x,
uint256 y,
uint256 denominator
) internal pure returns (uint256 result) {
unchecked {
// 512-bit multiply [prod1 prod0] = x * y. Compute the product mod 2^256 and mod 2^256 - 1, then use
// use the Chinese Remainder Theorem to reconstruct the 512 bit result. The result is stored in two 256
// variables such that product = prod1 * 2^256 + prod0.
uint256 prod0; // Least significant 256 bits of the product
uint256 prod1; // Most significant 256 bits of the product
assembly {
let mm := mulmod(x, y, not(0))
prod0 := mul(x, y)
prod1 := sub(sub(mm, prod0), lt(mm, prod0))
}
// Handle non-overflow cases, 256 by 256 division.
if (prod1 == 0) {
return prod0 / denominator;
}
// Make sure the result is less than 2^256. Also prevents denominator == 0.
require(denominator > prod1);
// 512 by 256 division.
// Make division exact by subtracting the remainder from [prod1 prod0].
uint256 remainder;
assembly {
// Compute remainder using mulmod.
remainder := mulmod(x, y, denominator)
// Subtract 256 bit number from 512 bit number.
prod1 := sub(prod1, gt(remainder, prod0))
prod0 := sub(prod0, remainder)
}
// Factor powers of two out of denominator and compute largest power of two divisor of denominator. Always >= 1.
// See https://cs.stackexchange.com/q/138556/92363.
// Does not overflow because the denominator cannot be zero at this stage in the function.
uint256 twos = denominator & (~denominator + 1);
assembly {
// Divide denominator by twos.
denominator := div(denominator, twos)
// Divide [prod1 prod0] by twos.
prod0 := div(prod0, twos)
// Flip twos such that it is 2^256 / twos. If twos is zero, then it becomes one.
twos := add(div(sub(0, twos), twos), 1)
}
// Shift in bits from prod1 into prod0.
prod0 |= prod1 * twos;
// Invert denominator mod 2^256. Now that denominator is an odd number, it has an inverse modulo 2^256 such
// that denominator * inv = 1 mod 2^256. Compute the inverse by starting with a seed that is correct for
// four bits. That is, denominator * inv = 1 mod 2^4.
uint256 inverse = (3 * denominator) ^ 2;
// Use the Newton-Raphson iteration to improve the precision. Thanks to Hensel's lifting lemma, this also works
// in modular arithmetic, doubling the correct bits in each step.
inverse *= 2 - denominator * inverse; // inverse mod 2^8
inverse *= 2 - denominator * inverse; // inverse mod 2^16
inverse *= 2 - denominator * inverse; // inverse mod 2^32
inverse *= 2 - denominator * inverse; // inverse mod 2^64
inverse *= 2 - denominator * inverse; // inverse mod 2^128
inverse *= 2 - denominator * inverse; // inverse mod 2^256
// Because the division is now exact we can divide by multiplying with the modular inverse of denominator.
// This will give us the correct result modulo 2^256. Since the preconditions guarantee that the outcome is
// less than 2^256, this is the final result. We don't need to compute the high bits of the result and prod1
// is no longer required.
result = prod0 * inverse;
return result;
}
}
/**
* @notice Calculates x * y / denominator with full precision, following the selected rounding direction.
*/
function mulDiv(
uint256 x,
uint256 y,
uint256 denominator,
Rounding rounding
) internal pure returns (uint256) {
uint256 result = mulDiv(x, y, denominator);
if (rounding == Rounding.Up && mulmod(x, y, denominator) > 0) {
result += 1;
}
return result;
}
/**
* @dev Returns the square root of a number. If the number is not a perfect square, the value is rounded down.
*
* Inspired by Henry S. Warren, Jr.'s "Hacker's Delight" (Chapter 11).
*/
function sqrt(uint256 a) internal pure returns (uint256) {
if (a == 0) {
return 0;
}
// For our first guess, we get the biggest power of 2 which is smaller than the square root of the target.
//
// We know that the "msb" (most significant bit) of our target number `a` is a power of 2 such that we have
// `msb(a) <= a < 2*msb(a)`. This value can be written `msb(a)=2**k` with `k=log2(a)`.
//
// This can be rewritten `2**log2(a) <= a < 2**(log2(a) + 1)`
// → `sqrt(2**k) <= sqrt(a) < sqrt(2**(k+1))`
// → `2**(k/2) <= sqrt(a) < 2**((k+1)/2) <= 2**(k/2 + 1)`
//
// Consequently, `2**(log2(a) / 2)` is a good first approximation of `sqrt(a)` with at least 1 correct bit.
uint256 result = 1 << (log2(a) >> 1);
// At this point `result` is an estimation with one bit of precision. We know the true value is a uint128,
// since it is the square root of a uint256. Newton's method converges quadratically (precision doubles at
// every iteration). We thus need at most 7 iteration to turn our partial result with one bit of precision
// into the expected uint128 result.
unchecked {
result = (result + a / result) >> 1;
result = (result + a / result) >> 1;
result = (result + a / result) >> 1;
result = (result + a / result) >> 1;
result = (result + a / result) >> 1;
result = (result + a / result) >> 1;
result = (result + a / result) >> 1;
return min(result, a / result);
}
}
/**
* @notice Calculates sqrt(a), following the selected rounding direction.
*/
function sqrt(uint256 a, Rounding rounding) internal pure returns (uint256) {
unchecked {
uint256 result = sqrt(a);
return result + (rounding == Rounding.Up && result * result < a ? 1 : 0);
}
}
/**
* @dev Return the log in base 2, rounded down, of a positive value.
* Returns 0 if given 0.
*/
function log2(uint256 value) internal pure returns (uint256) {
uint256 result = 0;
unchecked {
if (value >> 128 > 0) {
value >>= 128;
result += 128;
}
if (value >> 64 > 0) {
value >>= 64;
result += 64;
}
if (value >> 32 > 0) {
value >>= 32;
result += 32;
}
if (value >> 16 > 0) {
value >>= 16;
result += 16;
}
if (value >> 8 > 0) {
value >>= 8;
result += 8;
}
if (value >> 4 > 0) {
value >>= 4;
result += 4;
}
if (value >> 2 > 0) {
value >>= 2;
result += 2;
}
if (value >> 1 > 0) {
result += 1;
}
}
return result;
}
/**
* @dev Return the log in base 2, following the selected rounding direction, of a positive value.
* Returns 0 if given 0.
*/
function log2(uint256 value, Rounding rounding) internal pure returns (uint256) {
unchecked {
uint256 result = log2(value);
return result + (rounding == Rounding.Up && 1 << result < value ? 1 : 0);
}
}
/**
* @dev Return the log in base 10, rounded down, of a positive value.
* Returns 0 if given 0.
*/
function log10(uint256 value) internal pure returns (uint256) {
uint256 result = 0;
unchecked {
if (value >= 10**64) {
value /= 10**64;
result += 64;
}
if (value >= 10**32) {
value /= 10**32;
result += 32;
}
if (value >= 10**16) {
value /= 10**16;
result += 16;
}
if (value >= 10**8) {
value /= 10**8;
result += 8;
}
if (value >= 10**4) {
value /= 10**4;
result += 4;
}
if (value >= 10**2) {
value /= 10**2;
result += 2;
}
if (value >= 10**1) {
result += 1;
}
}
return result;
}
/**
* @dev Return the log in base 10, following the selected rounding direction, of a positive value.
* Returns 0 if given 0.
*/
function log10(uint256 value, Rounding rounding) internal pure returns (uint256) {
unchecked {
uint256 result = log10(value);
return result + (rounding == Rounding.Up && 10**result < value ? 1 : 0);
}
}
/**
* @dev Return the log in base 256, rounded down, of a positive value.
* Returns 0 if given 0.
*
* Adding one to the result gives the number of pairs of hex symbols needed to represent `value` as a hex string.
*/
function log256(uint256 value) internal pure returns (uint256) {
uint256 result = 0;
unchecked {
if (value >> 128 > 0) {
value >>= 128;
result += 16;
}
if (value >> 64 > 0) {
value >>= 64;
result += 8;
}
if (value >> 32 > 0) {
value >>= 32;
result += 4;
}
if (value >> 16 > 0) {
value >>= 16;
result += 2;
}
if (value >> 8 > 0) {
result += 1;
}
}
return result;
}
/**
* @dev Return the log in base 10, following the selected rounding direction, of a positive value.
* Returns 0 if given 0.
*/
function log256(uint256 value, Rounding rounding) internal pure returns (uint256) {
unchecked {
uint256 result = log256(value);
return result + (rounding == Rounding.Up && 1 << (result * 8) < value ? 1 : 0);
}
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.7.0) (access/Ownable.sol)
pragma solidity ^0.8.0;
import "../utils/Context.sol";
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* By default, the owner account will be the one that deploys the contract. This
* can later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
abstract contract Ownable is Context {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
constructor() {
_transferOwnership(_msgSender());
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
_checkOwner();
_;
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view virtual returns (address) {
return _owner;
}
/**
* @dev Throws if the sender is not the owner.
*/
function _checkOwner() internal view virtual {
require(owner() == _msgSender(), "Ownable: caller is not the owner");
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
_transferOwnership(address(0));
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
_transferOwnership(newOwner);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Internal function without access restriction.
*/
function _transferOwnership(address newOwner) internal virtual {
address oldOwner = _owner;
_owner = newOwner;
emit OwnershipTransferred(oldOwner, newOwner);
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.8.0) (access/AccessControl.sol)
pragma solidity ^0.8.0;
import "./IAccessControl.sol";
import "../utils/Context.sol";
import "../utils/Strings.sol";
import "../utils/introspection/ERC165.sol";
/**
* @dev Contract module that allows children to implement role-based access
* control mechanisms. This is a lightweight version that doesn't allow enumerating role
* members except through off-chain means by accessing the contract event logs. Some
* applications may benefit from on-chain enumerability, for those cases see
* {AccessControlEnumerable}.
*
* Roles are referred to by their `bytes32` identifier. These should be exposed
* in the external API and be unique. The best way to achieve this is by
* using `public constant` hash digests:
*
* ```
* bytes32 public constant MY_ROLE = keccak256("MY_ROLE");
* ```
*
* Roles can be used to represent a set of permissions. To restrict access to a
* function call, use {hasRole}:
*
* ```
* function foo() public {
* require(hasRole(MY_ROLE, msg.sender));
* ...
* }
* ```
*
* Roles can be granted and revoked dynamically via the {grantRole} and
* {revokeRole} functions. Each role has an associated admin role, and only
* accounts that have a role's admin role can call {grantRole} and {revokeRole}.
*
* By default, the admin role for all roles is `DEFAULT_ADMIN_ROLE`, which means
* that only accounts with this role will be able to grant or revoke other
* roles. More complex role relationships can be created by using
* {_setRoleAdmin}.
*
* WARNING: The `DEFAULT_ADMIN_ROLE` is also its own admin: it has permission to
* grant and revoke this role. Extra precautions should be taken to secure
* accounts that have been granted it.
*/
abstract contract AccessControl is Context, IAccessControl, ERC165 {
struct RoleData {
mapping(address => bool) members;
bytes32 adminRole;
}
mapping(bytes32 => RoleData) private _roles;
bytes32 public constant DEFAULT_ADMIN_ROLE = 0x00;
/**
* @dev Modifier that checks that an account has a specific role. Reverts
* with a standardized message including the required role.
*
* The format of the revert reason is given by the following regular expression:
*
* /^AccessControl: account (0x[0-9a-f]{40}) is missing role (0x[0-9a-f]{64})$/
*
* _Available since v4.1._
*/
modifier onlyRole(bytes32 role) {
_checkRole(role);
_;
}
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
return interfaceId == type(IAccessControl).interfaceId || super.supportsInterface(interfaceId);
}
/**
* @dev Returns `true` if `account` has been granted `role`.
*/
function hasRole(bytes32 role, address account) public view virtual override returns (bool) {
return _roles[role].members[account];
}
/**
* @dev Revert with a standard message if `_msgSender()` is missing `role`.
* Overriding this function changes the behavior of the {onlyRole} modifier.
*
* Format of the revert message is described in {_checkRole}.
*
* _Available since v4.6._
*/
function _checkRole(bytes32 role) internal view virtual {
_checkRole(role, _msgSender());
}
/**
* @dev Revert with a standard message if `account` is missing `role`.
*
* The format of the revert reason is given by the following regular expression:
*
* /^AccessControl: account (0x[0-9a-f]{40}) is missing role (0x[0-9a-f]{64})$/
*/
function _checkRole(bytes32 role, address account) internal view virtual {
if (!hasRole(role, account)) {
revert(
string(
abi.encodePacked(
"AccessControl: account ",
Strings.toHexString(account),
" is missing role ",
Strings.toHexString(uint256(role), 32)
)
)
);
}
}
/**
* @dev Returns the admin role that controls `role`. See {grantRole} and
* {revokeRole}.
*
* To change a role's admin, use {_setRoleAdmin}.
*/
function getRoleAdmin(bytes32 role) public view virtual override returns (bytes32) {
return _roles[role].adminRole;
}
/**
* @dev Grants `role` to `account`.
*
* If `account` had not been already granted `role`, emits a {RoleGranted}
* event.
*
* Requirements:
*
* - the caller must have ``role``'s admin role.
*
* May emit a {RoleGranted} event.
*/
function grantRole(bytes32 role, address account) public virtual override onlyRole(getRoleAdmin(role)) {
_grantRole(role, account);
}
/**
* @dev Revokes `role` from `account`.
*
* If `account` had been granted `role`, emits a {RoleRevoked} event.
*
* Requirements:
*
* - the caller must have ``role``'s admin role.
*
* May emit a {RoleRevoked} event.
*/
function revokeRole(bytes32 role, address account) public virtual override onlyRole(getRoleAdmin(role)) {
_revokeRole(role, account);
}
/**
* @dev Revokes `role` from the calling account.
*
* Roles are often managed via {grantRole} and {revokeRole}: this function's
* purpose is to provide a mechanism for accounts to lose their privileges
* if they are compromised (such as when a trusted device is misplaced).
*
* If the calling account had been revoked `role`, emits a {RoleRevoked}
* event.
*
* Requirements:
*
* - the caller must be `account`.
*
* May emit a {RoleRevoked} event.
*/
function renounceRole(bytes32 role, address account) public virtual override {
require(account == _msgSender(), "AccessControl: can only renounce roles for self");
_revokeRole(role, account);
}
/**
* @dev Grants `role` to `account`.
*
* If `account` had not been already granted `role`, emits a {RoleGranted}
* event. Note that unlike {grantRole}, this function doesn't perform any
* checks on the calling account.
*
* May emit a {RoleGranted} event.
*
* [WARNING]
* ====
* This function should only be called from the constructor when setting
* up the initial roles for the system.
*
* Using this function in any other way is effectively circumventing the admin
* system imposed by {AccessControl}.
* ====
*
* NOTE: This function is deprecated in favor of {_grantRole}.
*/
function _setupRole(bytes32 role, address account) internal virtual {
_grantRole(role, account);
}
/**
* @dev Sets `adminRole` as ``role``'s admin role.
*
* Emits a {RoleAdminChanged} event.
*/
function _setRoleAdmin(bytes32 role, bytes32 adminRole) internal virtual {
bytes32 previousAdminRole = getRoleAdmin(role);
_roles[role].adminRole = adminRole;
emit RoleAdminChanged(role, previousAdminRole, adminRole);
}
/**
* @dev Grants `role` to `account`.
*
* Internal function without access restriction.
*
* May emit a {RoleGranted} event.
*/
function _grantRole(bytes32 role, address account) internal virtual {
if (!hasRole(role, account)) {
_roles[role].members[account] = true;
emit RoleGranted(role, account, _msgSender());
}
}
/**
* @dev Revokes `role` from `account`.
*
* Internal function without access restriction.
*
* May emit a {RoleRevoked} event.
*/
function _revokeRole(bytes32 role, address account) internal virtual {
if (hasRole(role, account)) {
_roles[role].members[account] = false;
emit RoleRevoked(role, account, _msgSender());
}
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.8.0) (token/ERC20/ERC20.sol)
pragma solidity ^0.8.0;
import "./IERC20.sol";
import "./extensions/IERC20Metadata.sol";
import "../../utils/Context.sol";
/**
* @dev Implementation of the {IERC20} interface.
*
* This implementation is agnostic to the way tokens are created. This means
* that a supply mechanism has to be added in a derived contract using {_mint}.
* For a generic mechanism see {ERC20PresetMinterPauser}.
*
* TIP: For a detailed writeup see our guide
* https://forum.openzeppelin.com/t/how-to-implement-erc20-supply-mechanisms/226[How
* to implement supply mechanisms].
*
* We have followed general OpenZeppelin Contracts guidelines: functions revert
* instead returning `false` on failure. This behavior is nonetheless
* conventional and does not conflict with the expectations of ERC20
* applications.
*
* Additionally, an {Approval} event is emitted on calls to {transferFrom}.
* This allows applications to reconstruct the allowance for all accounts just
* by listening to said events. Other implementations of the EIP may not emit
* these events, as it isn't required by the specification.
*
* Finally, the non-standard {decreaseAllowance} and {increaseAllowance}
* functions have been added to mitigate the well-known issues around setting
* allowances. See {IERC20-approve}.
*/
contract ERC20 is Context, IERC20, IERC20Metadata {
mapping(address => uint256) private _balances;
mapping(address => mapping(address => uint256)) private _allowances;
uint256 private _totalSupply;
string private _name;
string private _symbol;
/**
* @dev Sets the values for {name} and {symbol}.
*
* The default value of {decimals} is 18. To select a different value for
* {decimals} you should overload it.
*
* All two of these values are immutable: they can only be set once during
* construction.
*/
constructor(string memory name_, string memory symbol_) {
_name = name_;
_symbol = symbol_;
}
/**
* @dev Returns the name of the token.
*/
function name() public view virtual override returns (string memory) {
return _name;
}
/**
* @dev Returns the symbol of the token, usually a shorter version of the
* name.
*/
function symbol() public view virtual override returns (string memory) {
return _symbol;
}
/**
* @dev Returns the number of decimals used to get its user representation.
* For example, if `decimals` equals `2`, a balance of `505` tokens should
* be displayed to a user as `5.05` (`505 / 10 ** 2`).
*
* Tokens usually opt for a value of 18, imitating the relationship between
* Ether and Wei. This is the value {ERC20} uses, unless this function is
* overridden;
*
* NOTE: This information is only used for _display_ purposes: it in
* no way affects any of the arithmetic of the contract, including
* {IERC20-balanceOf} and {IERC20-transfer}.
*/
function decimals() public view virtual override returns (uint8) {
return 18;
}
/**
* @dev See {IERC20-totalSupply}.
*/
function totalSupply() public view virtual override returns (uint256) {
return _totalSupply;
}
/**
* @dev See {IERC20-balanceOf}.
*/
function balanceOf(address account) public view virtual override returns (uint256) {
return _balances[account];
}
/**
* @dev See {IERC20-transfer}.
*
* Requirements:
*
* - `to` cannot be the zero address.
* - the caller must have a balance of at least `amount`.
*/
function transfer(address to, uint256 amount) public virtual override returns (bool) {
address owner = _msgSender();
_transfer(owner, to, amount);
return true;
}
/**
* @dev See {IERC20-allowance}.
*/
function allowance(address owner, address spender) public view virtual override returns (uint256) {
return _allowances[owner][spender];
}
/**
* @dev See {IERC20-approve}.
*
* NOTE: If `amount` is the maximum `uint256`, the allowance is not updated on
* `transferFrom`. This is semantically equivalent to an infinite approval.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function approve(address spender, uint256 amount) public virtual override returns (bool) {
address owner = _msgSender();
_approve(owner, spender, amount);
return true;
}
/**
* @dev See {IERC20-transferFrom}.
*
* Emits an {Approval} event indicating the updated allowance. This is not
* required by the EIP. See the note at the beginning of {ERC20}.
*
* NOTE: Does not update the allowance if the current allowance
* is the maximum `uint256`.
*
* Requirements:
*
* - `from` and `to` cannot be the zero address.
* - `from` must have a balance of at least `amount`.
* - the caller must have allowance for ``from``'s tokens of at least
* `amount`.
*/
function transferFrom(
address from,
address to,
uint256 amount
) public virtual override returns (bool) {
address spender = _msgSender();
_spendAllowance(from, spender, amount);
_transfer(from, to, amount);
return true;
}
/**
* @dev Atomically increases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) {
address owner = _msgSender();
_approve(owner, spender, allowance(owner, spender) + addedValue);
return true;
}
/**
* @dev Atomically decreases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
* - `spender` must have allowance for the caller of at least
* `subtractedValue`.
*/
function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) {
address owner = _msgSender();
uint256 currentAllowance = allowance(owner, spender);
require(currentAllowance >= subtractedValue, "ERC20: decreased allowance below zero");
unchecked {
_approve(owner, spender, currentAllowance - subtractedValue);
}
return true;
}
/**
* @dev Moves `amount` of tokens from `from` to `to`.
*
* This internal function is equivalent to {transfer}, and can be used to
* e.g. implement automatic token fees, slashing mechanisms, etc.
*
* Emits a {Transfer} event.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `from` must have a balance of at least `amount`.
*/
function _transfer(
address from,
address to,
uint256 amount
) internal virtual {
require(from != address(0), "ERC20: transfer from the zero address");
require(to != address(0), "ERC20: transfer to the zero address");
_beforeTokenTransfer(from, to, amount);
uint256 fromBalance = _balances[from];
require(fromBalance >= amount, "ERC20: transfer amount exceeds balance");
unchecked {
_balances[from] = fromBalance - amount;
// Overflow not possible: the sum of all balances is capped by totalSupply, and the sum is preserved by
// decrementing then incrementing.
_balances[to] += amount;
}
emit Transfer(from, to, amount);
_afterTokenTransfer(from, to, amount);
}
/** @dev Creates `amount` tokens and assigns them to `account`, increasing
* the total supply.
*
* Emits a {Transfer} event with `from` set to the zero address.
*
* Requirements:
*
* - `account` cannot be the zero address.
*/
function _mint(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: mint to the zero address");
_beforeTokenTransfer(address(0), account, amount);
_totalSupply += amount;
unchecked {
// Overflow not possible: balance + amount is at most totalSupply + amount, which is checked above.
_balances[account] += amount;
}
emit Transfer(address(0), account, amount);
_afterTokenTransfer(address(0), account, amount);
}
/**
* @dev Destroys `amount` tokens from `account`, reducing the
* total supply.
*
* Emits a {Transfer} event with `to` set to the zero address.
*
* Requirements:
*
* - `account` cannot be the zero address.
* - `account` must have at least `amount` tokens.
*/
function _burn(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: burn from the zero address");
_beforeTokenTransfer(account, address(0), amount);
uint256 accountBalance = _balances[account];
require(accountBalance >= amount, "ERC20: burn amount exceeds balance");
unchecked {
_balances[account] = accountBalance - amount;
// Overflow not possible: amount <= accountBalance <= totalSupply.
_totalSupply -= amount;
}
emit Transfer(account, address(0), amount);
_afterTokenTransfer(account, address(0), amount);
}
/**
* @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens.
*
* This internal function is equivalent to `approve`, and can be used to
* e.g. set automatic allowances for certain subsystems, etc.
*
* Emits an {Approval} event.
*
* Requirements:
*
* - `owner` cannot be the zero address.
* - `spender` cannot be the zero address.
*/
function _approve(
address owner,
address spender,
uint256 amount
) internal virtual {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
/**
* @dev Updates `owner` s allowance for `spender` based on spent `amount`.
*
* Does not update the allowance amount in case of infinite allowance.
* Revert if not enough allowance is available.
*
* Might emit an {Approval} event.
*/
function _spendAllowance(
address owner,
address spender,
uint256 amount
) internal virtual {
uint256 currentAllowance = allowance(owner, spender);
if (currentAllowance != type(uint256).max) {
require(currentAllowance >= amount, "ERC20: insufficient allowance");
unchecked {
_approve(owner, spender, currentAllowance - amount);
}
}
}
/**
* @dev Hook that is called before any transfer of tokens. This includes
* minting and burning.
*
* Calling conditions:
*
* - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens
* will be transferred to `to`.
* - when `from` is zero, `amount` tokens will be minted for `to`.
* - when `to` is zero, `amount` of ``from``'s tokens will be burned.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(
address from,
address to,
uint256 amount
) internal virtual {}
/**
* @dev Hook that is called after any transfer of tokens. This includes
* minting and burning.
*
* Calling conditions:
*
* - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens
* has been transferred to `to`.
* - when `from` is zero, `amount` tokens have been minted for `to`.
* - when `to` is zero, `amount` of ``from``'s tokens have been burned.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _afterTokenTransfer(
address from,
address to,
uint256 amount
) internal virtual {}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (access/IAccessControl.sol)
pragma solidity ^0.8.0;
/**
* @dev External interface of AccessControl declared to support ERC165 detection.
*/
interface IAccessControl {
/**
* @dev Emitted when `newAdminRole` is set as ``role``'s admin role, replacing `previousAdminRole`
*
* `DEFAULT_ADMIN_ROLE` is the starting admin for all roles, despite
* {RoleAdminChanged} not being emitted signaling this.
*
* _Available since v3.1._
*/
event RoleAdminChanged(bytes32 indexed role, bytes32 indexed previousAdminRole, bytes32 indexed newAdminRole);
/**
* @dev Emitted when `account` is granted `role`.
*
* `sender` is the account that originated the contract call, an admin role
* bearer except when using {AccessControl-_setupRole}.
*/
event RoleGranted(bytes32 indexed role, address indexed account, address indexed sender);
/**
* @dev Emitted when `account` is revoked `role`.
*
* `sender` is the account that originated the contract call:
* - if using `revokeRole`, it is the admin role bearer
* - if using `renounceRole`, it is the role bearer (i.e. `account`)
*/
event RoleRevoked(bytes32 indexed role, address indexed account, address indexed sender);
/**
* @dev Returns `true` if `account` has been granted `role`.
*/
function hasRole(bytes32 role, address account) external view returns (bool);
/**
* @dev Returns the admin role that controls `role`. See {grantRole} and
* {revokeRole}.
*
* To change a role's admin, use {AccessControl-_setRoleAdmin}.
*/
function getRoleAdmin(bytes32 role) external view returns (bytes32);
/**
* @dev Grants `role` to `account`.
*
* If `account` had not been already granted `role`, emits a {RoleGranted}
* event.
*
* Requirements:
*
* - the caller must have ``role``'s admin role.
*/
function grantRole(bytes32 role, address account) external;
/**
* @dev Revokes `role` from `account`.
*
* If `account` had been granted `role`, emits a {RoleRevoked} event.
*
* Requirements:
*
* - the caller must have ``role``'s admin role.
*/
function revokeRole(bytes32 role, address account) external;
/**
* @dev Revokes `role` from the calling account.
*
* Roles are often managed via {grantRole} and {revokeRole}: this function's
* purpose is to provide a mechanism for accounts to lose their privileges
* if they are compromised (such as when a trusted device is misplaced).
*
* If the calling account had been granted `role`, emits a {RoleRevoked}
* event.
*
* Requirements:
*
* - the caller must be `account`.
*/
function renounceRole(bytes32 role, address account) external;
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.6.0) (token/ERC20/IERC20.sol)
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20 {
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `to`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address to, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `from` to `to` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(
address from,
address to,
uint256 amount
) external returns (bool);
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC20/extensions/IERC20Metadata.sol)
pragma solidity ^0.8.0;
import "../IERC20.sol";
/**
* @dev Interface for the optional metadata functions from the ERC20 standard.
*
* _Available since v4.1._
*/
interface IERC20Metadata is IERC20 {
/**
* @dev Returns the name of the token.
*/
function name() external view returns (string memory);
/**
* @dev Returns the symbol of the token.
*/
function symbol() external view returns (string memory);
/**
* @dev Returns the decimals places of the token.
*/
function decimals() external view returns (uint8);
}
// SPDX-License-Identifier: BSL 1.1
pragma solidity ^0.8.13;
import {IERC20} from "openzeppelin-contracts/contracts/token/ERC20/IERC20.sol";
interface IOffchainFundUser {
/// @dev Emitted when `USDC` is deposited to the fund
/// @param sender The sender of the `USDC`
/// @param epoch The epoch of the deposit
/// @param assets The amount of `USDC` deposited
event Deposit(
address indexed sender,
uint256 indexed epoch,
uint256 assets
);
/// @dev Emitted when fund shares redeem order is placed
/// @param sender The sender of the redeem order
/// @param epoch The epoch of the redeem order
/// @param shares The amount of fund shares to redeem
event Redeem(address indexed sender, uint256 indexed epoch, uint256 shares);
/// @dev The asset of the fund
/// @return usdc `USDC` token
function usdc() external view returns (IERC20 usdc);
/// @dev Place order to receive fund shares by depositing `USDC`
/// @param amount The amount of `USDC` to deposit
function deposit(uint256 amount) external;
/// @dev Place order to receive `USDC` by burning fund shares
/// @param shares The amount of shares to redeem
function redeem(uint256 shares) external;
}
// SPDX-License-Identifier: BSL 1.1
pragma solidity ^0.8.13;
interface IOffchainFundAdmin {
/// @dev Emitted when the owner Refills the contract with USDC
/// @param sender The sender of the `USDC`
/// @param epoch The epoch of the refill
/// @param assets The amount of `USDC` refilled
event Refill(address indexed sender, uint256 indexed epoch, uint256 assets);
/// @dev Emitted when the funds are drained from the contract
/// @param sender The caller of the drain() function
/// @param epoch The epoch of the drain
/// @param assets The amount of `USDC` drained
/// @param shares The amount of shares to be burned
event Drain(
address indexed sender,
uint256 indexed epoch,
uint256 assets,
uint256 shares
);
/// @dev Emitted when the price is updated and the epoch starts
/// @param sender The caller of the update() function
/// @param epoch The epoch of the update
/// @param price The new price of the share
/// @param totalShares The total amount of shares available
event Update(
address indexed sender,
uint256 indexed epoch,
uint256 price,
uint256 totalShares
);
/// @dev Emitted when the deposit order is processed
/// @param sender The caller of the processDeposit() function
/// @param account The account that placed the deposit order
/// @param epoch The current epoch
/// @param shares The amount of shares received
/// @param assets The amount of `USDC` deposited
/// @param price The price of the share
event ProcessDeposit(
address indexed sender,
address indexed account,
uint256 indexed epoch,
uint256 shares,
uint256 assets,
uint256 price
);
/// @dev Emitted when the redeem order is processed
/// @param sender The caller of the processRedeem() function
/// @param account The account that placed the redeem order
/// @param epoch The current epoch
/// @param shares The amount of shares burned
/// @param assets The amount of `USDC` received
/// @param price The price of the share
/// @param filled Whether the order was fully filled or not
event ProcessRedeem(
address indexed sender,
address indexed account,
uint256 indexed epoch,
uint256 shares,
uint256 assets,
uint256 price,
bool filled
);
/// @dev Total deposits submitted in the current epoch
/// @return _pendingDeposits Total deposits submitted in the current epoch
function pendingDeposits() external view returns (uint256 _pendingDeposits);
/// @dev All passed passed available to be processed on a price update
/// @return _currentDeposits All passed passed available to be processed on a price update
function currentDeposits() external view returns (uint256 _currentDeposits);
/// @dev Number of accounts with current deposits
/// @return _currentDepositCount Number of accounts with current deposits
function currentDepositCount()
external
view
returns (uint256 _currentDepositCount);
/// @dev Returns whether the Fund is drained (cut-off) of deposits or not
/// @return _drained whether the Fund is drained (cut-off) of deposits or not
function drained() external view returns (bool _drained);
/// @dev Number of accounts with pre-drain deposits
/// @return _preDrainDepositCount Number of accounts with pre-drain deposits
function preDrainDepositCount()
external
view
returns (uint256 _preDrainDepositCount);
/// @dev Number of accounts with post-drain deposits
/// @return _postDrainDepositCount Number of accounts with post-drain deposits
function postDrainDepositCount()
external
view
returns (uint256 _postDrainDepositCount);
/// @dev Total redemptions submitted in the current epoch
/// @return _pendingRedemptions Total redemptions submitted in the current epoch
function pendingRedemptions()
external
view
returns (uint256 _pendingRedemptions);
/// @dev All passed redemptions available to be processed
/// @return _currentRedemptions All passed redemptions available to be processed
function currentRedemptions()
external
view
returns (uint256 _currentRedemptions);
/// @dev Sets the limit on USDC accepted per epoch
/// @param cap_ The new limit on deposits
function adjustCap(uint256 cap_) external;
/// @dev Sets the minimum deposit amount
/// @param min_ The new minimum deposit
function adjustMin(uint256 min_) external;
/// @dev Adds an address to the whitelist
/// @param account Address to add to the whitelist
function addToWhitelist(address account) external;
/// @dev Removes address from the whitelist
/// @param account Address to remove from the whitelist
function removeFromWhitelist(address account) external;
/// @dev Process batch of addresses to be whitelisted
/// @param accounts Address list to add to whitlist
function batchAddToWhitelist(address[] calldata accounts) external;
/// @dev Process batch of addresses to be removed the whitelist
/// @param accounts Address list to remove from the whitelist
function batchRemoveFromWhitelist(address[] calldata accounts) external;
/// @dev Pulls the maximum amount of available `USDC`
function drain() external;
/// @dev Update the NAV per share for the fund and increment the epoch
/// @param price New share price
function update(uint256 price) external;
/// @dev Transfer `USDC` to the contract
/// @param assets Number of `USDC` tokens to be transferred to the contract
function refill(uint256 assets) external;
/// @dev Process the redeem order for an account to receive `USDC`
/// @param account Address that placed the order
function processRedeem(address account) external;
/// @dev Process the deposit order for account to receive fund shares
/// @param account Address that placed the order
function processDeposit(address account) external;
/// @dev Process the batch of deposit orders for accounts to receive fund shares
/// @param accountList Address list that placed orders
function batchProcessDeposit(address[] calldata accountList) external;
/// @dev Process the batch of redeem orders for accounts to receive `USDC`
/// @param accountList Address list that placed orders
function batchProcessRedeem(address[] calldata accountList) external;
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/Context.sol)
pragma solidity ^0.8.0;
/**
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract Context {
function _msgSender() internal view virtual returns (address) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes calldata) {
return msg.data;
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.8.0) (utils/Strings.sol)
pragma solidity ^0.8.0;
import "./math/Math.sol";
/**
* @dev String operations.
*/
library Strings {
bytes16 private constant _SYMBOLS = "0123456789abcdef";
uint8 private constant _ADDRESS_LENGTH = 20;
/**
* @dev Converts a `uint256` to its ASCII `string` decimal representation.
*/
function toString(uint256 value) internal pure returns (string memory) {
unchecked {
uint256 length = Math.log10(value) + 1;
string memory buffer = new string(length);
uint256 ptr;
/// @solidity memory-safe-assembly
assembly {
ptr := add(buffer, add(32, length))
}
while (true) {
ptr--;
/// @solidity memory-safe-assembly
assembly {
mstore8(ptr, byte(mod(value, 10), _SYMBOLS))
}
value /= 10;
if (value == 0) break;
}
return buffer;
}
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation.
*/
function toHexString(uint256 value) internal pure returns (string memory) {
unchecked {
return toHexString(value, Math.log256(value) + 1);
}
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length.
*/
function toHexString(uint256 value, uint256 length) internal pure returns (string memory) {
bytes memory buffer = new bytes(2 * length + 2);
buffer[0] = "0";
buffer[1] = "x";
for (uint256 i = 2 * length + 1; i > 1; --i) {
buffer[i] = _SYMBOLS[value & 0xf];
value >>= 4;
}
require(value == 0, "Strings: hex length insufficient");
return string(buffer);
}
/**
* @dev Converts an `address` with fixed length of 20 bytes to its not checksummed ASCII `string` hexadecimal representation.
*/
function toHexString(address addr) internal pure returns (string memory) {
return toHexString(uint256(uint160(addr)), _ADDRESS_LENGTH);
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/introspection/ERC165.sol)
pragma solidity ^0.8.0;
import "./IERC165.sol";
/**
* @dev Implementation of the {IERC165} interface.
*
* Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check
* for the additional interface id that will be supported. For example:
*
* ```solidity
* function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
* return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId);
* }
* ```
*
* Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation.
*/
abstract contract ERC165 is IERC165 {
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
return interfaceId == type(IERC165).interfaceId;
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/introspection/IERC165.sol)
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC165 standard, as defined in the
* https://eips.ethereum.org/EIPS/eip-165[EIP].
*
* Implementers can declare support of contract interfaces, which can then be
* queried by others ({ERC165Checker}).
*
* For an implementation, see {ERC165}.
*/
interface IERC165 {
/**
* @dev Returns true if this contract implements the interface defined by
* `interfaceId`. See the corresponding
* https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section]
* to learn more about how these ids are created.
*
* This function call must use less than 30 000 gas.
*/
function supportsInterface(bytes4 interfaceId) external view returns (bool);
}
|
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Document</title>
<link
href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css"
rel="stylesheet"
integrity="sha384-EVSTQN3/azprG1Anm3QDgpJLIm9Nao0Yz1ztcQTwFspd3yD65VohhpuuCOmLASjC"
crossorigin="anonymous"
/>
</head>
<body>
<div class="container">
<h1 class="text-center">Message WebApp </h1>
<div
class="row d-flex justify-content-center"
>
<div class="col">
<input
type="text"
name="text"
id="text"
placeholder="enter your message"
/>
<button class="btn btn-primary" id="btn">Submit</button>
</div>
</div>
<div class="row d-flex justify-content-start" id="temp-body">
</div>
</div>
<script>
let text=document.getElementById('text')
let btn=document.getElementById('btn')
let temp_body=document.getElementById('temp-body')
let edit=''
let gArr=[]
function print()
{
let tmeplate=''
gArr.map((item)=>{
tmeplate+=`<div class="col-md-4">
<div class="card">
<div class="card-body">
<h1>${item.text}</h1>
</div>
<div class="card-footer">
<button class="btn btn-primary" onclick="editHandler(${item.id})">edit</button>
<button class="btn btn-danger" onclick="deleteHandler(${item.id})">del</button>
</div>
</div>
</div>`
})
temp_body.innerHTML=tmeplate
}
btn.addEventListener('click',()=>{
if(!text.value)
{
alert('required field ****')
return
}
else{
//this is for the edit
if(edit)
{
let obj={id:edit.id,text:text.value}
fetch('/',{method:"PUT",body:JSON.stringify(obj)}).then((item)=>{
return item.json()
}).then((data)=>{
gArr=data;
print()
})
edit=''
}
//this is for addition
else{
//1.send into nodejs
//2. create into db
fetch('/',{method:"POST",body:JSON.stringify(text.value)}).then((res)=>{
return res.json()
}).then((data)=>{
console.log(data)
gArr=data;
print()
}).catch((err)=>{
console.log(err.message)
})
}
}
})
//this is for the delete
function deleteHandler(id)
{
console.log('hello i am id',id)
fetch(`/`,{method:"DELETE",body:JSON.stringify(id)}).then((item)=>{
return item.json()
}).then((data)=>{
gArr=data;
print()
})
}
//this is for the edithandler
function editHandler(id)
{
console.log('id',id)
let findData=gArr.find((item)=>{
return item.id==id
})
edit=findData
text.value=findData.text
}
</script>
</body>
</html>
|
import { useState, Fragment } from 'react';
import { Transition, Dialog } from '@headlessui/react';
import { closeIcon, filterIcon } from '../assets';
import CustomButton from './CustomButton';
import Checkbox from './Checkbox';
import TabSelect from './TabSelect';
import RadioSelect from './RadioSelect';
const Filters = ({ language }) => {
const [isOpen, setIsOpen] = useState(false);
const [sort] = useState(['Сначала дешевле', 'Сначала дороже']);
const [sortingOption, setSortingOption] = useState('');
const [currency] = useState(['UZS', 'USD']);
const [selectedCurrency, setSelectedCurrency] = useState('');
const [typesOfSale] = useState(['Рассрочка', 'Опт', 'Розница']);
const [selectedTypeOfSale, setSelectedTypeOfSale] = useState('');
const [conditions] = useState(['Новый', 'Б/У']);
const [selectedCondition, setSelectedCondition] = useState('');
const [sellers] = useState(['Верифицированный', 'Не верифицированный']);
const [selectedSeller, setSelectedSeller] = useState('');
const [productsNearby, setProductsNearby] = useState(false);
const [bidding, setBidding] = useState(false);
const openModal = () => {
setIsOpen(true);
};
const closeModal = () => {
setIsOpen(false);
};
return (
<>
<CustomButton styles="py-1 px-2 flex justify-between items-center gap-2 bg-black text-white text-[12px] self-start" onClick={openModal}>
<img src={filterIcon} alt="filter icon" width={20} height={20} />
{language.Filter}
</CustomButton>
<Transition appear show={isOpen} as={Fragment}>
<Dialog as="div" className="relative z-10" onClose={closeModal}>
<Transition.Child
as={Fragment}
enter="ease-out duration-300"
enterFrom="opacity-0"
enterTo="opacity-100"
leave="ease-in duration-200"
leaveFrom="opacity-100"
leaveTo="opacity-0"
>
<div className="fixed inset-0 bg-black/25" />
</Transition.Child>
<div className="fixed inset-0 overflow-y-auto">
<div className="flex min-h-full items-end justify-center text-center">
<Transition.Child
as={Fragment}
enter="ease-linear duration-300 transform"
enterFrom="-translate-x-full"
enterTo="translate-x-0"
leave="ease-out duration-200 transform"
leaveFrom="translate-x-0"
leaveTo="-translate-x-full"
>
<Dialog.Panel className="w-full h-screen transform overflow-hidden rounded-t-2xl bg-white p-6 text-left align-middle shadow-xl transition-all">
<Dialog.Title as="h3" className="text-lg font-medium leading-6 text-center">
{language.Filter}
</Dialog.Title>
<div className="flex flex-col justify-center items-start mt-4 font-light gap-6">
<RadioSelect options={sort} selectedOption={sortingOption} setSelectedOption={setSortingOption} title="Сортировать" />
<Checkbox value={productsNearby} onValueChange={setProductsNearby} title="Товары рядом" />
<Checkbox value={bidding} onValueChange={setBidding} title="Возможен торг" />
<RadioSelect options={currency} selectedOption={selectedCurrency} setSelectedOption={setSelectedCurrency} title="Валюта" />
<RadioSelect
options={typesOfSale}
selectedOption={selectedTypeOfSale}
setSelectedOption={setSelectedTypeOfSale}
title="Тип продажи"
width="25%"
/>
<RadioSelect options={conditions} selectedOption={selectedCondition} setSelectedOption={setSelectedCondition} title="Состояние" />
<RadioSelect options={sellers} selectedOption={selectedSeller} setSelectedOption={setSelectedSeller} title="Продавец" />
</div>
<div className="mt-8 w-full flex justify-center gap-2">
<CustomButton styles="mt-5 p-3 w-[80%] bg-white text-[14px] ring-1 ring-[var(--color-light-gray)] rounded-[30px] shadow-sm">
Сброс фильтров
</CustomButton>
<CustomButton styles="mt-5 p-3 w-[80%] bg-[var(--color-green)] text-white text-[14px] rounded-[30px] shadow-sm">Применить</CustomButton>
</div>
<div className="mt-4">
<CustomButton onClick={closeModal} styles="absolute top-2 right-2 border-none">
<img src={closeIcon} alt="close icon" width={18} height={18} className="active:opacity-75 duration-75 ease-in" />
</CustomButton>
</div>
</Dialog.Panel>
</Transition.Child>
</div>
</div>
</Dialog>
</Transition>
</>
);
};
export default Filters;
|
import React from "react";
import {
Box,
Typography,
FormControl,
Input,
FormHelperText,
TextField,
Stack,
Select,
MenuItem,
TextareaAutosize,
} from "@pankod/refine-mui";
import { FormProps } from "interfaces/common";
import CustomButton from "./customButton";
const Form = ({
type,
register,
handleSubmit,
handleImageChange,
formLoading,
onFinishHandler,
propertyImage,
}: FormProps) => {
return (
<Box>
<Typography fontSize={25} fontWeight={750} color={"#697089"}>
{type} Property
</Typography>
<Box mt={2} borderRadius={5} padding={"20px"} bgcolor={"#FFFFFF"}>
<form
style={{
marginTop: "20px",
width: "100%",
display: "flex",
flexDirection: "column",
gap: "20px",
}}
onSubmit={handleSubmit(onFinishHandler)}
>
<FormControl>
<FormHelperText
sx={{
fontSize: 16,
fontWeight: 600,
color: "#697089",
margin: "0 0 10px 0",
}}
>
Property Name
</FormHelperText>
<TextField
fullWidth
required
{...register("title", { required: true })}
placeholder="Property Name"
id="propertyName" // Updated to a unique ID
variant="outlined"
color="info"
/>
</FormControl>
<FormControl>
<FormHelperText
sx={{
fontSize: 16,
fontWeight: 600,
color: "#697089",
margin: "0 0 10px 0",
}}
>
Property Description
</FormHelperText>
<TextareaAutosize
{...register("description", { required: true })}
placeholder="Property Description"
color="info"
required
style={{
width: "100%",
height: "100px",
padding: "10px",
fontSize: "16px",
borderRadius: "8px",
border: "1px solid #697089",
color: "#697089",
backgroundColor: "#FFFFFF",
}}
/>
</FormControl>
<Stack direction="row" gap={2}>
<FormControl>
<FormHelperText
sx={{
fontSize: 16,
fontWeight: 600,
color: "#697089",
margin: "0 0 10px 0",
}}
>
Property Type
</FormHelperText>
<Select
{...register("propertyType", { required: true })}
color="info"
variant="outlined"
fullWidth
required
displayEmpty
inputProps={{ "aria-label": "Without label" }}
defaultValue={"apartment"}
>
<MenuItem value="bedsitter">Bedsitter</MenuItem>
<MenuItem value="apartment">Apartment</MenuItem>
<MenuItem value="condos">Condos</MenuItem>
<MenuItem value="bungalow">Bungalow</MenuItem>
<MenuItem value="mansion">Mansion</MenuItem>
<MenuItem value="duplex">Duplex</MenuItem>
<MenuItem value="farmhouse">Farmhouse</MenuItem>
<MenuItem value="chalet">Chalet</MenuItem>
<MenuItem value="townhouse">Townhouse</MenuItem>
<MenuItem value="villa">Villa</MenuItem>
</Select>
</FormControl>
<FormControl>
<FormHelperText
sx={{
fontSize: 16,
fontWeight: 600,
color: "#697089",
margin: "0 0 10px 0",
}}
>
Property Price
</FormHelperText>
<TextField
{...register("price", { required: true })}
type="number"
placeholder="Property Price"
id="propertyPrice"
variant="outlined"
color="info"
fullWidth
/>
</FormControl>
</Stack>
<FormControl>
<FormHelperText
sx={{
fontSize: 16,
fontWeight: 600,
color: "#697089",
margin: "0 0 10px 0",
}}
>
Property Location
</FormHelperText>
<TextField
type="text"
{...register("location", { required: true })}
color="info"
required
placeholder="Property Location"
id="propertyLocation"
variant="outlined"
fullWidth
/>
</FormControl>
<Stack direction="column" gap={2} mb={2} justifyContent={"center"}>
<Stack direction="row" gap={2}>
<Typography
color={"#697089"}
fontWeight={600}
fontSize={16}
my={"10px"}
>
Upload Property Photo
</Typography>
<Input
type="file"
// accessKey="image"
hidden
sx={{
backgroundColor: "#FFFFFF",
borderRadius: 1,
textTransform: "capitalize",
color: "#fff",
"&:hover": {
backgroundColor: "transparent",
},
}}
onChange={(e) => {
// @ts-ignore
handleImageChange(e.target.files[0]);
}}
/>
</Stack>
<Typography
fontSize={16}
fontWeight={600}
color={"#697089"}
variant="h6"
sx={{ wordBreak: "break-all" }}
>
{propertyImage?.name}
</Typography>
</Stack>
<CustomButton
type="submit"
label={formLoading ? "Loading..." : "Submit"}
backgroundColor={"#697089"}
color={"#fff"}
// handleClick={() => {}}
/>
</form>
</Box>
</Box>
);
};
export default Form;
|
import axios from 'axios';
import {getData, storeData} from "./util";
import {ACCESS_TOKEN, API_BASE_URL} from "../constants/common";
import {PROFILE, STUB_CURRENT_USER, STUB_SIGN_UP, STUB_TOKEN} from "../util/stub";
const api = axios.create({
baseURL: API_BASE_URL,
headers: {
"Content-Type": "application/json"
},
});
const IS_USING_STUB = false;
interface ISignInResponse {
token: string;
}
export async function signIn(signInRequest) {
if (!IS_USING_STUB) {
return await api.post<ISignInResponse>("/auth/signin", signInRequest).then(resp => resp.data);
} else {
return STUB_TOKEN
}
}
interface ISignUpResponse {
token: string;
}
export async function signUp(signUpRequest) {
if (!IS_USING_STUB) {
return api.post<ISignUpResponse>("/auth/signup", signUpRequest);
} else {
return STUB_SIGN_UP
}
}
export async function loadTasks() {
if (!IS_USING_STUB) {
const token = await getData(ACCESS_TOKEN);
const config = {
headers: { }
};
const api1 = axios.create({
baseURL: API_BASE_URL,
headers: {
"Content-Type": "application/json",
Authorization: `Bearer ${token}`
},
});
return api1.get<ITaskResponse[]>("/tasks", config).then(resp => resp.data);
} else {
return []
}
}
export async function createTask(taskDto) {
if (!IS_USING_STUB) {
const token = await getData(ACCESS_TOKEN);
const config = {
headers: { Authorization: `Bearer ${token}` }
};
return api.post<ITaskResponse[]>("/tasks", taskDto, config).then(resp => resp.data);
} else {
return []
}
}
export async function updateTask(taskId, taskDto) {
if (!IS_USING_STUB) {
const token = await getData(ACCESS_TOKEN);
const config = {
headers: { Authorization: `Bearer ${token}` }
};
return api.put<ITaskResponse[]>(`/tasks/${taskId}`, taskDto, config).then(resp => resp.data);
} else {
return []
}
}
interface ICurrentUser {
id: number;
username: string;
firstName: string;
lastName: string;
}
export async function getCurrentUser() {
/* if (!IS_USING_STUB) {
return api.get<ICurrentUser>("/auth/me");
} else {
return STUB_CURRENT_USER
}*/
return STUB_CURRENT_USER
}
interface ILessonResponse {
id: number;
title: string;
description: string;
video: string;
learningTime: number
}
interface ITaskResponse {
id: number;
body: string;
isCompleted: boolean;
}
export async function getProfile(userId) {
const token = await getData(ACCESS_TOKEN);
const config = {
headers: { }
};
const api1 = axios.create({
baseURL: API_BASE_URL,
headers: {
"Content-Type": "application/json",
Authorization: `Bearer ${token}`
},
});
return api1.get<ICurrentUser>(`/users/${userId}`, config).then(resp => resp.data);
}
|
<section class="[ flex flex-col ] [ space-y-1 ]">
<IntegerSequenceDemo Numbers="productIds"></IntegerSequenceDemo>
<table class="[ table-fixed border-collapse ] [ bg-white ] [ border-2 ] [ dark:bg-black dark:border-slate-500 ] [ mt-2 ] [ w-full ]">
<thead>
<tr class="[ bg-gray-100 ] [ dark:bg-slate-500 ]">
<th class="[ border-2 ] [ dark:border-slate-600 ] [ p-2 ]">Id</th>
<th class="[ border-2 ] [ dark:border-slate-600 ] [ p-2 ]">Name</th>
</tr>
</thead>
<tbody>
@foreach (var product in products)
{
<tr>
<td class="[ border-2 ] [ dark:border-slate-700 ] [ p-2 ]">@product.Id</td>
<td class="[ border-2 ] [ dark:border-slate-700 ] [ p-2 ]">@product.Name</td>
</tr>
}
</tbody>
</table>
</section>
<p>Common Product Ids : @string.Join(", ", common.Select(product => product.Id))</p>
<button type="button" class="[ bg-cyan-500 ] [ text-white ] [ px-4 py-2 ] [ inline-block ] [ rounded-md ] [ inline-flex ] [ space-x-1 ]" @onclick="HandleIntersectBy">
Intersect By
</button>
<button type="button" class="[ bg-fuchsia-500 ] [ text-white ] [ px-4 py-2 ] [ inline-block ] [ rounded-md ] [ inline-flex ] [ space-x-1 ]" @onclick="Reset">
Reset
</button>
@code
{
private List<int> productIds = new(3);
private IEnumerable<Product> products = new ProductSource().Products;
private List<Product> common = new();
private void HandleIntersectBy()
{
common = products.IntersectBy(productIds, product => product.Id).ToList();
}
private void Reset()
{
productIds = new(3);
products = new ProductSource().Products;
common = new();
}
}
|
<template>
<div class="flex items-center flex-col justify-center">
<img src="../../assets/img/logoLingian.png" alt="" />
<div v-if="$route.path !== '/admin'">
<div v-if="!display" class="w-full flex justify-center items-center">
<q-select
rounded
outlined
v-model="model"
:options="options"
label="Login As"
color="dark"
class="outline-none focus:bg-none active:bg-none w-full"
bg-color="white" />
<q-btn
unelevated
rounded
color="green"
label="Next"
text-color="dark"
class="px-8 mt-4"
@click="handleNext" />
</div>
</div>
<q-form
class="flex items-center flex-col mt-3 gap-4"
@submit.prevent="login"
v-if="display || $route.path === '/admin'">
<!-- <q-input
rounded
standout
bottom-slots
v-model="Email"
label="Email"
placeholder="Enter Email Here"
for="Email"
bg-color="white"
color="dark"
:dense="dense" /> -->
<q-input
rounded
outlined
v-model="email"
color="dark"
bg-color="white"
label="Email"
for="email"
placeholder="Enter Email Here"
clear-icon="backspace"
class="md:w-80 w-60 drop-shadow-sm outline-none focus:bg-none active:bg-none">
</q-input>
<q-input
rounded
outlined
v-model="pw"
color="dark"
bg-color="white"
label="Password"
for="password"
type="password"
class="md:w-80 w-60 drop-shadow-sm">
</q-input>
<q-btn
text-color="dark"
unelevated
size="md"
rounded
padding="sm"
@click="login"
color="green"
label="login"
class="px-20 w-40 font-semibold items-center text-semibold">
</q-btn>
</q-form>
<p class="mt-8" v-if="$route.path === '/mitra'">
Don't have an account?
<a class="text-[#D1CB2A]" href="/mitra/register">Create an account</a>
</p>
</div>
</template>
<script lang="ts">
import { ref, computed } from 'vue'
import { useRoute } from 'vue-router'
import axios from 'axios'
import api from 'src/AxiosInterceptors'
import { Cookies, useQuasar } from 'quasar'
export default {
setup() {
const $q = useQuasar()
return {
showNotif() {
$q.notify({
message: 'Login successful!',
textColor: 'green',
color: 'white',
position: 'top',
actions: [
{
icon: 'close',
color: 'green',
round: true,
handler: () => {
/* ... */
},
},
],
})
},
errorNotif() {
$q.notify({
message: 'Login Failed!',
color: 'red',
position: 'top',
actions: [
{
icon: 'close',
color: 'white',
round: true,
handler: () => {
/* ... */
},
},
],
})
},
}
},
data() {
return {
email: '',
pw: '',
ph: '',
dense: false,
model: null,
options: ['User', 'Mitra'],
display: false,
}
},
computed: {
$route() {
return useRoute()
},
},
methods: {
// async login() {
// if (this.$route.path === '/admin') {
// try {
// const response = await axios.post(
// 'http://localhost:8080/auth/login',
// {
// email: this.email,
// password: this.pw,
// },
// {
// withCredentials: true,
// }
// )
// const token = response.data.data.accessToken
// console.log(token)
// localStorage.setItem('token', token)
// this.$router.push('/mitra/upload')
// } catch (error) {
// console.error('Login failed!', error.message)
// }
// }
// },
async login() {
if (this.$route.path === '/admin') {
try {
const response = await api.post(
'/auth/login',
{ email: this.email, password: this.pw },
{ withCredentials: true }
)
const token = response.data.data.accessToken
// console.log(token)
console.log('berhasil login')
console.log(response.data.message)
const refreshToken = Cookies.get('refreshToken')
// console.log(refreshToken)
// localStorage.setItem('auth', true)
localStorage.setItem('token', token)
this.showNotif()
this.$nextTick(() => {
this.$router.push('/admin/home')
})
// this.$router.push({
// path: '/admin/home',
// query: { successMessage: 'Login successful' },
// })
} catch (error) {
this.errorNotif()
console.error('Login failed', error)
}
} else if (this.$route.path === '/login') {
try {
const response = await api.post(
'/auth/login',
{ email: this.email, password: this.pw },
{ withCredentials: true }
)
const token = response.data.data.accessToken
// console.log(token)
console.log('berhasil login')
const refreshToken = Cookies.get('refreshToken')
// console.log(refreshToken)
// localStorage.setItem('auth', true)
localStorage.setItem('token', token)
this.showNotif()
this.$nextTick(() => {
this.$router.push('/home')
})
} catch (error) {
this.errorNotif()
console.error('Login failed', error)
}
} else if (this.$route.path === '/mitra') {
try {
const response = await api.post(
'/auth/login',
{ email: this.email, password: this.pw },
{ withCredentials: true }
)
const token = response.data.data.accessToken
// console.log(token)
console.log('berhasil login')
const refreshToken = Cookies.get('refreshToken')
// console.log(refreshToken)
// localStorage.setItem('auth', true)
localStorage.setItem('token', token)
this.showNotif()
this.$nextTick(() => {
this.$router.push('/mitra/home')
})
} catch (error) {
this.errorNotif()
console.error('Login failed', error)
}
}
},
handleNext() {
if (this.model === 'User') {
this.display = true
console.log('tes')
} else if (this.model === 'Mitra') {
this.display = true
this.$router.push('/mitra')
}
},
},
}
</script>
|
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
class CreateWeaponTable extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('weapon', function (Blueprint $table) {
$table->bigIncrements('id');
$table->string('weapon_name');
$table->string('kinds');
$table->string('ability');
$table->integer('rarity');
$table->text('comment');
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::dropIfExists('weapon');
}
}
|
/*
///
/// ---
/// title: Align
/// section: Formatting
/// ---
///
/// __OBJECT ALIGNMENT__
///
/// - align--top - align-items: flex-start
/// - align--center - align-items: center
/// - align--bottom - align-items: flex-end
///
/// __TEXT ALIGNMENT__
///
/// - text--left - text-align: left
/// - text--right - text-align: right
/// - text--center - text-align: center
/// - text--justify - text-align: justify
///
*/
// OBJECT ALIGNMENT
.align {
&_top { align-items: flex-start; }
&_center { align-items: center; }
&_bottom { align-items: flex-end; }
}
// TEXT ALIGNMENT
.text {
&-left { text-align: left; }
&-right { text-align: right; }
&-center { text-align: center; }
&-justify { text-align: justify; }
}
|
from datetime import datetime
from sqlalchemy import JSON, func, String
from sqlalchemy.orm import Mapped, mapped_column, registry
reg = registry()
@reg.mapped_as_dataclass
class AuthenticationModel:
__tablename__ = "adm_clients"
id: Mapped[int] = mapped_column(init=False, primary_key=True, autoincrement=True)
id_account: Mapped[int] = mapped_column(nullable=False)
codigo_cliente: Mapped[int] = mapped_column(nullable=False)
razao_social: Mapped[str] = mapped_column(String(255), nullable=True)
nick_name: Mapped[str] = mapped_column(String(255), nullable=True)
cnpj: Mapped[str] = mapped_column(String(255), nullable=True)
tipo_empresa: Mapped[str] = mapped_column(String(255), nullable=True)
uf: Mapped[str] = mapped_column(String(255), nullable=True)
chave_api_1: Mapped[str] = mapped_column(String(255), nullable=True)
chave_api_2: Mapped[str] = mapped_column(String(255), nullable=True)
chave_api_3: Mapped[str] = mapped_column(String(255), nullable=True)
codigo_generico_1: Mapped[str] = mapped_column(String(255), nullable=True)
codigo_generico_2: Mapped[str] = mapped_column(String(255), nullable=True)
modules: Mapped[dict | list] = mapped_column(JSON, nullable=True)
subModules: Mapped[dict | list] = mapped_column(JSON, nullable=True)
status: Mapped[bool] = mapped_column(nullable=False)
created_by: Mapped[str] = mapped_column(String(255), nullable=True)
created_at: Mapped[datetime] = mapped_column(init=False, server_default=func.now())
updated_at: Mapped[datetime] = mapped_column(
init=False, onupdate=func.now(), nullable=True
)
@reg.mapped_as_dataclass
class SumulaModel:
__tablename__ = "api_sumula"
id: Mapped[int] = mapped_column(init=False, primary_key=True, autoincrement=True)
competicao: Mapped[str] = mapped_column(String(255), nullable=True)
rodada: Mapped[str] = mapped_column(String(255), nullable=True)
data: Mapped[str] = mapped_column(String(255), nullable=True)
horario: Mapped[str] = mapped_column(String(255), nullable=True)
estadio: Mapped[str] = mapped_column(String(255), nullable=True)
mandante: Mapped[str] = mapped_column(String(255), nullable=True)
visitante: Mapped[str] = mapped_column(String(255), nullable=True)
ano: Mapped[int] = mapped_column()
jogo_num: Mapped[int] = mapped_column()
jogo: Mapped[str] = mapped_column(JSON)
arbitragem: Mapped[list[dict[str, str]]] = mapped_column(JSON)
cronologia: Mapped[dict[str, dict[str, str]]] = mapped_column(JSON)
escalacao: Mapped[dict] = mapped_column(JSON)
gols: Mapped[list[dict[str, str]] | list] = mapped_column(JSON, nullable=True)
cartoes_amarelo: Mapped[list[dict] | list] = mapped_column(JSON)
cartoes_vermelho: Mapped[list[dict] | list] = mapped_column(JSON)
comissao: Mapped[dict] = mapped_column(JSON)
ocorrencias: Mapped[dict[str, str]] = mapped_column(JSON)
acrescimos: Mapped[dict[str, str]] = mapped_column(JSON)
observacao: Mapped[dict[str, str]] = mapped_column(JSON)
assistente: Mapped[dict[str, str]] = mapped_column(JSON)
substituicao: Mapped[list[dict[str, str]]] = mapped_column(JSON)
url_pdf: Mapped[str] = mapped_column(String(255), nullable=True)
created_at: Mapped[datetime] = mapped_column(init=False, server_default=func.now())
updated_at: Mapped[datetime] = mapped_column(
init=False, onupdate=func.now(), nullable=True
)
@reg.mapped_as_dataclass
class Logs:
__tablename__ = "api_logs"
id: Mapped[int] = mapped_column(init=False, primary_key=True, autoincrement=True)
id_client: Mapped[int] = mapped_column()
dh_chamada: Mapped[datetime] = mapped_column()
dh_retorno: Mapped[datetime] = mapped_column()
url_chamada: Mapped[str] = mapped_column(String(255), nullable=True)
st_sucesso: Mapped[bool] = mapped_column()
dados_retorno: Mapped[dict] = mapped_column(JSON)
cd_ocorrencia: Mapped[int] = mapped_column()
ds_erro: Mapped[str] = mapped_column(String(255), nullable=True)
|
---
layout: post
title: "Dodecagonal Coordinates"
date: 2024-03-03 07:38:00 +0100
categories: "tilemesh"
---
<p align="center">
<img src="/Pictures/Post_2/N_from_P.svg" height=400px alt="Ni from Phi"/>
</p>
<ul>
<li>Back to the <a href="/topics/tiles">Tiles</a> topic index.</li>
<li><a href="https://github.com/Duncuiad/MovingFrames/blob/main/OpenGLPG/Core/Dodec.h">Dodec</a> on GitHub <svg class="svg-icon"><use xlink:href="{{ '/assets/minima-social-icons.svg#github' | relative_url }}"></use></svg> </li>
</ul>
In the <a href="/tilemesh/2024/02/14/tilemesh/">introductory post</a> to the *Tiles* section, we saw how to generate a square-triangle tiling of the plane. At the end of that post, I called your attention to a handful of questions that relate to how this generation can be best implemented. I'll recap the first two issues here, so that it will be easier to keep them in mind as you read the post.
- When an edge gets split in two, we use the edge's vertices' positions to calculate the middle vertex's position on the plane. Every time this happens, the *numerical errors* get worse.
- One defining property of regular grids, like a checkerboard pattern, is that each vertex is identified by its *coordinates* on the grid. For example, we can take the point $(78, -172)$ and immediately know two things: that it is indeed a vertex in the grid, and that its neighbours are exactly the vertices $(77, -172)$, $(79, -172)$, $(78, -173)$ and $(78, -171)$, respectively to the west, the east, the south and the north of the original point. Unfortunately, this structure is not available on just any polygonal mesh.
In this post, we'll turn this sad state of affairs on its head and see that *there actually exists* a coordinate system which works well with square-triangle grids. What's more, this coordinate system allows us to retrieve the position of any point on the grid. Finding a solution to the second issue, then, will promptly deliver a solution to the first.
In order to find the coordinate system that suits our needs, I first need to take you on a detour to expand on two crucial concepts: what coordinates really are and how we can use the product and sum of complex numbers to construct all the possible points in the square-triangle grid, using only a handful of basic points.
<h2>1. What Are Coordinates, Really?</h2>
Coordinates are a lot like a recipe, in that they tell you how much of various ingredients you need to blend to obtain the result you're looking for. What is often implicit or overlooked, when we talk about coordinates in any given context, is what these ingredients actually are.
To avoid confusion, I'll stick to a naming convention: the term 'coordinate' will only be used here to describe the *integer* kind of coordinates, whereas I'll refer to the concept of "$x-$ and $y-$ *real* coordinates" of a point on the plane simply as its 'position'.
Let's begin with coordinates on a square grid: we're all familiar with identifying points on such a grid by counting how many steps east and how many steps north we need to take to reach those points when starting from the origin.
<p align="center">
<img src="/Pictures/Post_2/Square_Grid.svg" height=400px alt="Square Grid"/>
<p class="post-meta" align="center">Coordinates on a square grid</p>
</p>
I've written down the point $(3,2)$ in the picture using its complex form: $3+2i$. Complex numbers are a great tool for 2D geometry. We'll have our chance to leverage them later, so let's start using them from the outset and get some familiarity. What's important here is just that there are two special 'vectors'[^vector], $1$ and $i$, from which we can build all other points in the grid, starting from the origin, which is the 'vector' $0$.
So far we've had two possible directions to move along -- horizontal and vertical -- and two integers: the number of steps (with sign) along each direction. Moving on to a triangular grid, we see that we can move in three different directions. So do we need three integers to identify a point on the grid? The answer is no: three are too many.
<p align="center">
<img src="/Pictures/Post_2/Triangular_Grid.gif" alt="Triangular Grid"/>
<p class="post-meta" align="center">Coordinates on a triangular grid</p>
</p>
Let's give a name to the three red vectors: $1$, $\zeta$ and $\zeta^2$. If you're familiar with multiplying complex numbers, you can see how $\zeta^2$ is indeed obtained by multiplying $\zeta$ with itself. If you're not, you can take them as three symbols, each corresponding to a different vector in the plane. The picture shows a point on the grid as a circled white dot, as well as three different ways of reaching it using the red vectors. Each separate way uses *only two* of the three vectors.
The directions -- with their generating vectors -- are indeed three, but, as you might have noticed, they are not *independent*. You can obtain any of the three vectors from the other two[^3]: $\zeta^2$ can be reached by going against $1$ once and then taking one step against $\zeta$. In formulas, $\zeta^2=-1-\zeta$. Of course, there's nothing more fundamental about $\zeta$ and $1$ than $\zeta^2$: we have $\zeta=-1-\zeta^2$ and even $1$ is just $1=-\zeta-\zeta^2$.
We say that each of the collections $\left\\{1, \zeta \right\\}$, $\left\\{1, \zeta^2 \right\\} $ and $\left\\{\zeta,\zeta^2\right\\}$ is a *basis* of the triangular grid.
<h3>Coordinates and Bases</h3>
For a collection of vectors to form a basis, it needs to satisfy two properties at the same time. As we have just seen, the vectors need to be independent, so that we're not including *more* vectors *than are necessary*. But to make up a basis, they also need to be *enough*, in that any point of the grid must be reachable by taking a sequence of steps along those vectors. In that case, we say that the vectors *generate* the grid. As an example of why we want this to hold, take the collection $\left\\{1, 2\zeta \right\\}$. It is made of independent vectors but it fails to be a basis of the triangular grid, since the point $\zeta$ can't be reached[^5].
What the picture highlights, then, is that each basis assigns *different coordinates* to the same point. Which of the possible bases we use is not so important. What we need to keep in mind, rather, is that coordinates only have meaning in relation to one specific basis.
This is the key takeaway of this first detour: basis vectors are the *ingredients* to some coordinates' *recipe*. If we want to find a coordinate system for the square-triangle grid, what we need to identify is one -- or more -- collections of vectors on the plane that are at the same time *independent* and *generate* all points on the grid.
<h2>2. Finding the 'Middle Point' of an Edge</h2>
Take a moment to think back to the first post, <a href="/tilemesh/2024/02/14/tilemesh#Deflation_Rules">where we discussed the deflation rules</a> for the square-triangle grid.
When a deflation step is applied, all the edges in the grid are split into two new edges. These two child edges meet at a vertex that wasn't in the grid before the deflation. Let's call this vertex the 'middle point' of the parent edge. Since we generate grids by applying consecutive deflations to a simple square or triangle, all vertices in any grid are either the vertices of the original shape or the middle point of some pair of vertices of the previous generation (which themselves were either vertices of the original shape or middle points -- and so on). Following this line of thought to its final consequence, we can deconstruct the problem of generating all the vertices of the grid into the repetition of the much simpler task of finding the middle point of any given (ordered) pair of vertices.
The prototypical example of a middle point is the one constructed on the edge that goes from $0$ to $1$. Let's call this point $\nu$ (pronounced 'nee' or 'noo'). As we saw in the last post, it's a point that makes an angle of $15^\circ$ counterclockwise with the $x$ axis and whose distance from $0$ is $\frac{1}{2} \left( \sqrt{6} - \sqrt{2} \right)$. You can also check that its real part is $\frac{1}{2}$.
Using $\nu$, it's easy to generate all other middle points via scale, rotation, and translation. By rotating and scaling $\nu$ by a factor of $q-p$ and then translating it by $p$, $\nu$ can be taken from the edge $0$-$1$ to an arbitrary edge $p$-$q$. This is how that looks:
<p align="center">
<img src="/Pictures/Post_2/Middle_Point.gif" alt="Middle Point"/>
<p class="post-meta" align="center">Bringing $\nu$ to a different edge</p>
</p>
We can also bundle this process into a single expression!
For any two points $p$ and $q$, this simple formula returns their middle point on the complex plane:
$$
\text{m}\left(p,q\right) = p + \nu \left(q-p\right)
$$
We can now use the formula to deduce the position of all the vertices of a tiling after one round of deflation:
<p align="center">
<img src="/Pictures/Post_2/Deflation_From_Midpoint.jpg" alt="Deflation Coordinates"/>
<p class="post-meta" align="center">Vertices of the Deflation Diagram. The middle points are obtained by applying the formula to their parent edge's endpoints</p>
</p>
And we could go on forever, applying the formula to get the positions of the vertices that appear after further deflations.
<h2>3. A Coordinate System for the Square-Triangle Grid</h2>
<h3>What We Need</h3>
In section 1, we saw how finding a coordinate system for the square-triangle grid actually means finding a basis of vectors. Now, thanks to section 2, we know what properties that basis needs to satisfy:
- The original vertices of the basic square and triangle have to be in the grid generated by the basis. They are the points $0, 1, \tau, i, 1+i$ in the last picture of section 2.
- The (signed) sum of points on the grid has to be on the grid as well.
- The product of any point on the grid with $\nu$ has to be on the grid.
In fact, we will look for a basis whose generated grid satisfies a *stronger* set of properties. Here 'stronger' means that we can derive the previous properties from the new ones. They are:
- The grid is closed under addition, negation and multiplication[^7].
- The grid contains the points $0, 1, \nu, \tau, i$[^8].
The reason for this shift is that it yields a structure that is quite *regular*[^9], just like the square and the triangular grids were. There will likely be more points in it, than are needed to include the whole square-triangle grid, but this is not an issue for us: we only need it to provide a good coordinate system --- and it will.
<h3>The Construction</h3>
In the picture that depicts the vertices of the deflation diagram, you can notice that everything is built using only four elementary points, beyond $0$. They are $1$, $\nu$, $i$, and $\tau$ (we also explicitly required them to be on the grid). Every other point is obtained by addition or multiplication of those four. This sounds like a good candidate for a basis, doesn't it? Sadly, it can't be one: the four vectors are actually dependent, since $\tau = 1 + i - \nu$.
Mindful of what we did when we found the collection $\left\\{1, \zeta, \zeta^2 \right\\}$ to be dependent in Section 1, you might ask if we should just leave $\tau$ out of the picture and take $\left\\{1, i, \nu \right\\}$ as our basis. These vectors are indeed independent (nice!), but regretfully they don't allow us to reach all the points in the deflation diagram. This is because the grid made of all the possible combinations of $1$, $i$ and $\nu$ is closed under addition but not under multiplication. In fact, there is no way to add $1$, $i$ and $\nu$ together and obtain the point $i\nu$, which is the product $i \cdot \nu$.
To successfully reach all points in the square-triangle grid, we need to add $i\nu$ to the collection. Now, if we could show that the grid generated by $\left\\{1, i, \nu, i\nu \right\\}$ is closed under multiplication (which is the last requirement left to satisfy), then these vectors would indeed form a basis for the smallest *regular* grid that *contains any possible vertex* in the square-triangle grid.
<details>
<summary>$\boxed{\text{Proof}} - \text{The grid generated by } \left\{1, i, \nu, i\nu \right\}$ $\text{ is closed under multiplication}$</summary>
<br>
<hr>
Since the complex product distributes over the sum, it's sufficient to check something simpler: that multiplying elements of the candidate basis together always yields points that lie on the grid generated by that same collection.
<br>
Here are the possible products (I'll skip those involving $1$ because they are obvious):
$$
\begin{array}{rcl}
i \cdot i & = & -1 \\
i \cdot \nu & = & i\nu \\
i \cdot i\nu & = & -\nu \\
\nu \cdot \nu & = & \nu^2 = -i + \nu + 2i\nu \\
\nu \cdot i\nu & = & i \cdot \nu^2 = 1 - 2\nu + i\nu \\
i\nu \cdot i\nu & = & -\nu^2 = i - \nu - 2i\nu \\
\end{array}
$$
Checking that $\nu^2 = -i + \nu + 2i\nu$ isn't as immediate as the other equalities, but you can verify it, for example, by equating the real and imaginary parts of the two sides of the equality.
<br>
<hr>
</details>
<br>
And just like that, we found our coordinate system.
<p align="center">
<img src="/Pictures/Post_2/NI_Basis.svg" height=400px alt="NI Basis"/>
<p class="post-meta" align="center">The point of coordinates $(-1,1,3,-1)$ on the basis $\left\{1, i, \nu, i\nu \right\}$ </p>
</p>
This four-dimensional regular grid in the plane is well known to mathematicians: it's $\mathbb{Z}\left[\zeta_{12}\right]$, the "ring of integers of the cyclotomic field $\mathbb{Q}\left(\zeta_{12}\right)$", where $\zeta_{12}$ is the "primitive twelfth root of unity". It's one of many structures studied by a branch of mathematics called number theory. For simplicity, I refer to its elements as "dodecs" in the code implementation, short for "dodecagonal (numbers)". I'll refer to them by the same name here, but keep in mind that their actual name in maths is the former.
One thing that is worth mentioning is that the dodec grid contains both the square and the triangular regular grids as subgrids. This is because it is closed under addition and multiplication and it contains the generating vectors of both: $1$ and $i$ for the square grid and $1$ and $\tau$ for the triangular one. It is also the smallest regular grid in which you can build regular dodecagons, hence its pet name.
In the code, dodecs are implemented as a class made of four integers: the coordinates with respect to the basis $\left\\{1, i, \nu, i\nu \right\\}$. The class allows you to add and multiply dodecs, in a way that I'll describe in the next section, as well as compute their position. Since performing operations between them doesn't generate numerical errors, there's no problem in hashing them. In fact, vertices in the TileMesh class are kept in a hashmap whose keys are dodecs. This allows us to get an existing vertex in the mesh very quickly by providing its integer coordinates.
Naturally, as seen in Section 1, we could express dodecs in many different bases. The code implementation provides conversions of the coordinates to a handful of meaningful bases other than $\left\\{1, i, \nu, i\nu \right\\}$.
<h3>Adding and Multiplying Coordinates</h3>
Remember that we use sums and products of points that lie on the square-triangle grid to generate the vertices of a new deflation. This makes the two operations pivotal to the generation of the grid, so we need a way to perform them efficiently.
Since the dodec grid is closed under addition and multiplication (of complex numbers), we could take two coordinate quadruples, find what points they represent on some basis, add or multiply those points together on the complex plane and then find the coordinates that represent the result on the same basis. This procedure, transposed directly in code, would require introducing approximations in the first and second steps, preventing us from being able to perform the third and last one.
Lucky for us, we can do the mathematical heavy-lifting up-front and obtain formulas for adding and multiplying the coordinates directly, without performing any conversion down the line. The formula for the sum is the same in all bases, whereas the product one changes based on the particular basis being used.
I'll use one of the alternative bases to show how to build the sum and product operations on the coordinates, for two reasons: it's a basis that is more commonly used when working with $\mathbb{Z}\left[\zeta_{12}\right]$ and the calculations are a little more straightforward than when using the other one.
This basis is $\left\\{1, \varphi, \varphi^2, \varphi^3 \right\\}$[^11] and this picture shows how you can obtain $\nu$ with it:
$$
\nu = 1 - \varphi^2 + \varphi^3
$$
<p align="center">
<img src="/Pictures/Post_2/N_from_P.svg" height=400px alt="Nu from Phi"/>
<p class="post-meta" align="center">$\nu$ over the basis $\left\{ 1, \varphi, \varphi^2, \varphi^3 \right\}$ </p>
</p>
It also shows that, in this basis, $i = \varphi^3$. With a little calculation, you can find that $i\nu = \varphi - 1$. You can also find the inverse mapping between the bases, which means constructing every element of $\left\\{1, \varphi, \varphi^2, \varphi^3 \right\\}$ using only elements of $\left\\{1, i, \nu, i\nu \right\\}$.
On this basis, the coordinates are added like this:
$$
\left(
\begin{array}{c}
x_0\\y_0\\z_0\\w_0
\end{array}
\right)
+
\left(
\begin{array}{c}
x_1\\y_1\\z_1\\w_1
\end{array}
\right)
=
\left(
\begin{array}{c}
x_0+x_1\\y_0+y_1\\z_0+z_1\\w_0+w_1
\end{array}
\right)
$$
and multiplied like this:
$$
\begin{array}{c}
\left(
\begin{array}{c}
x_0\\y_0\\z_0\\w_0
\end{array}
\right)
\cdot
\left(
\begin{array}{c}
x_1\\y_1\\z_1\\w_1
\end{array}
\right)
\\ \\
=
\\ \\
\left(
\begin{array}{c}
x_0 x_1 - y_0 w_1 - z_0 z_1 - w_0 y_1 - w_0 w_1 \\
x_0 y_1 + y_0 x_1 - z_0 w_1 - w_0 z_1 \\
x_0 z_1 + y_0 y_1 + z_0 x_1 + y_0 w_1 + z_0 z_1 + w_0 y_1 \\
x_0 w_1 + y_0 z_1 + z_0 y_1 + w_0 x_1 + z_0 w_1 + w_0 z_1
\end{array}
\right)
\end{array}
$$
<details>
<summary>$\boxed{\text{Proof}} - \text{Deducing the formulas}$</summary>
<br>
<hr>
We define the sum to work like the complex sum operates on the corresponding points on the complex plane:
$$
\left(x_0,y_0,z_0,w_0\right) + \left(x_1,y_1,z_1,w_1\right) \leftrightarrow
\left( x_0 + y_0 \varphi + z_0 \varphi^2 + w_0 \varphi^3 \right) + \left( x_1 + y_1 \varphi + z_1 \varphi^2 + w_1 \varphi^3 \right)
$$
We can rearrange the terms and factor the common ones:
$$
\begin{array}{rl}
& x_0 + y_0 \varphi + z_0 \varphi^2 + w_0 \varphi^3 + x_1 + y_1 \varphi + z_1 \varphi^2 + w_1 \varphi^3 \\
= & \left(x_0 + x_1\right) + \left(y_0 + y_1\right) \varphi + \left(z_0 + z_1\right) \varphi^2 + \left(w_0 + w_1\right) \varphi^3
\end{array}
$$
Reading the coefficients of the basis vectors, we find the coordinates:
$$
\left(x_0+x_1,y_0+y_1,z_0+z_1,w_0+w_1\right)
$$
The product is computed similarly:
$$
\left(x_0,y_0,z_0,w_0\right) \cdot \left(x_1,y_1,z_1,w_1\right) \leftrightarrow
\left( x_0 + y_0 \varphi + z_0 \varphi^2 + w_0 \varphi^3 \right) \cdot \left( x_1 + y_1 \varphi + z_1 \varphi^2 + w_1 \varphi^3 \right)
$$
This time around distribute the product over the sum:
$$
\begin{array}{rcl}
& x_0 x_1 & 1 \\
+ & \left( x_0 y_1 + y_0 x_1 \right) & \varphi \\
+ & \left( x_0 z_1 + y_0 y_1 + z_0 x_1 \right) & \varphi^2 \\
+ & \left( x_0 w_1 + y_0 z_1 + z_0 y_1 + w_0 x_1 \right) & \varphi^3 \\
+ & \left( y_0 w_1 + z_0 z_1 + w_0 y_1 \right) & \varphi^4 \\
+ & \left( z_0 w_1 + w_0 z_1 \right) & \varphi^5 \\
+ & w_0 w_1 & \varphi^6 \\
\end{array}
$$
A peculiarity of the number $\varphi$ is that $\varphi^4 = \varphi^2 - 1$. This lets us lower the degree of some terms, by expressing $\varphi^4$, $\varphi^5$ and $\varphi^6$ on the basis $\left\{1, \varphi, \varphi^2, \varphi^3 \right\}$:
$$
\begin{array}{rcl}
\varphi^4 & = & \varphi^2 - 1 \\
\varphi^5 = \varphi \cdot \varphi^4 & = & \varphi^3 - \varphi \\
\varphi^6 = \varphi^2 \cdot \varphi^4 & = & \varphi^4 - \varphi^2 = \left(\varphi^2 - 1\right) - \varphi^2 = -1
\end{array}
$$
Substituting in the previous expression,
$$
\begin{array}{rcl}
& x_0 x_1 - \left( y_0 w_1 + z_0 z_1 + w_0 y_1 \right) - w_0 w_1 & 1\\
+ & \left( x_0 y_1 + y_0 x_1 \right) - \left( z_0 w_1 + w_0 z_1 \right) & \varphi \\
+ & \left( x_0 z_1 + y_0 y_1 + z_0 x_1 \right) + \left( y_0 w_1 + z_0 z_1 + w_0 y_1 \right) & \varphi^2 \\
+ & \left( x_0 w_1 + y_0 z_1 + z_0 y_1 + w_0 x_1 \right) + \left( z_0 w_1 + w_0 z_1 \right) & \varphi^3 \\
\end{array}
$$
Which says that the coordinates of the product are
$$
\left(
\begin{array}{c}
x_0 x_1 - y_0 w_1 - z_0 z_1 - w_0 y_1 - w_0 w_1 \\
x_0 y_1 + y_0 x_1 - z_0 w_1 - w_0 z_1 \\
x_0 z_1 + y_0 y_1 + z_0 x_1 + y_0 w_1 + z_0 z_1 + w_0 y_1 \\
x_0 w_1 + y_0 z_1 + z_0 y_1 + w_0 x_1 + z_0 w_1 + w_0 z_1
\end{array}
\right)
$$
<hr>
</details>
<p align="center">
<img src="/Pictures/Post_2/Deflation_Coordinates.jpg" alt="Deflation Coordinates"/>
<p class="post-meta" align="center">Vertex Coordinates of the Deflation Diagram over the basis $\left\{ 1, \varphi, \varphi^2, \varphi^3 \right\}$</p>
</p>
<h3>Wrapping Up</h3>
This last result completes the search for integer coordinates to assign to the vertices of the mesh. It took a while: we first found out that coordinates are numbers that rely on an underlying list of generating vectors, which is called a basis. Then we saw how we could use the addition and multiplication of complex numbers to generate the vertices of the square-triangle grid. Finally, we put the two together and found a regular structure, the dodec grid, that contains all possible vertices of the square-triangle grid, at any level of deflation, and assigns them four integer coordinates that uniquely identify each of them.
Using these coordinates, we're able to give a satisfying answer to the original questions:
- The generation of middle points of pairs of vertices can be performed via coordinate-wise addition and multiplication, which doesn't require approximations and doesn't propagate errors.
- The vertices of the mesh can be stored in a hash-map (a dictionary), whose keys are dodec coordinates. If we know a vertex's coordinates, we can retrieve it from the map in constant time[^10] (very very fast). This is a lot better than having to look for a vertex, whose position in the plane matches a given 2D vector of floats, in a potentially very long list.
Pretty cool huh? Well, stay tuned because there's still more to find out. Until the next post!
___
<h3>Notes and References:</h3>
[^vector]: I'll sometimes use the term 'vector' improperly in this post for a simple reason: people who didn't study maths at university are used to calling objects with multiple coordinates 'vectors'. There's no doubt that any mathematician who happens to read this page is going to badly cringe every single time they see the word 'vector' used in this context. If you're wondering why, it's because the spaces treated in this post are not vector spaces, but $\mathbb{Z}$-modules. They share similarities with vector spaces, but they are way less straightforward.
[^3]: You might be tempted to infer that since the plane is bidimensional, there can't be grids with bases made of more than two vectors. However, the grid we'll use later is an example of a grid with a larger basis. Your intuition would be correct in the context of *vector spaces*, where scalars are free to range over numbers like the reals. In that context, the 'dimension' is exactly the number of elements of a basis, so all bases of the plane have two elements. Here however we're working with a different structure, a $\mathbb{Z}$-module, where the scalars range over the integers.
[^5]: Here you can spot one big difference between *actual* vector spaces and these grids, which are objects called free $\mathbb{Z}$-modules. In vector spaces of dimension $n$, as soon as you have $n$ independent vectors, they form a basis: you can reach all the vector space. On the triangular grid however, sometimes two independent vectors are enough and sometimes they are not.
[^7]: Being closed under addition and multiplication means that if any two points are on the grid, then it's guaranteed that respectively their sum and their product are on the grid as well.
[^8]: Notice that we can drop the explicit requirement of $1+i$ being on the grid: its presence follows from $1$ and $i$ being included and the grid being closed under addition. Also notice how, compared to the previous set of properties, we have to explicitly require $\nu$ to be included.
[^9]: This kind of structure is called a *ring* in maths. In particular, this would be a *subring* of the complex numbers. The particular ring we will build also happens to be a free *abelian group* (of finite rank), which is another name for a (free) $\mathbb{Z}$-module. It's this latter kind of structure that we're actually interested in when we talk about (regular) grids: the set of all points that can be reached by stepping (with *full steps*) along a finite collection of 'vectors'.
[^10]: A neat consequence of this is that we can easily, given a fixed deflation height and a vertex on the grid, retrieve all the vertices adjacent to the given vertex in constant time, without the need to keep them stored in memory for all vertices. That's because we can calculate the coordinates of all the candidate neighbouring vertices (they are 12) and check if any of them are actually on the mesh. Most of the times, 5 (and sometimes 6) out of the 12 candidates will be retrieved successfully.
[^11]: $\varphi$ is actually the primitive twelfth root of unity itself: $\zeta_{12}$. However, I thought I'd keep things simple and assign a different name to each primitive root of unity that gets used in this post. You might have spotted the other ones: $\zeta$ is actually $\zeta_3$, $i$ is $\zeta_4$ and $\tau$ is $\zeta_6$.
|
#include <vector>
#include <list>
#include <map>
#include "UnitTest++/src/UnitTest++.h"
#include "ptr.h"
// a simple class that reference counts itself
class RefCounter
{
public:
RefCounter() { s_instances++; }
virtual ~RefCounter() { s_instances--; }
virtual signed Get(signed x) { return x; }
static signed s_instances;
};
signed RefCounter::s_instances = 0;
// and a derived class off of RefCounter (for testing list of base pointers)
class RefCounterDerived: public RefCounter
{
public:
virtual signed Get(signed x) { return x*2; }
};
// a test fixture we need for setup/teardown of each test
struct InstanceFixture
{
InstanceFixture()
{
RefCounter::s_instances = 0;
}
~InstanceFixture()
{
// empty
}
};
TEST_FIXTURE(InstanceFixture,AutoDeletion)
{
CHECK_EQUAL(0,RefCounter::s_instances);
{
ptr<RefCounter> a(new RefCounter);
CHECK_EQUAL(1,RefCounter::s_instances);
}
CHECK_EQUAL(0,RefCounter::s_instances);
}
TEST_FIXTURE(InstanceFixture,AssignZeroForDeletion)
{
CHECK_EQUAL(0,RefCounter::s_instances);
ptr<RefCounter> a = new RefCounter;
CHECK_EQUAL(1,RefCounter::s_instances);
a = 0;
CHECK_EQUAL(0,RefCounter::s_instances);
}
TEST_FIXTURE(InstanceFixture,ArrayAutoDeletion)
{
CHECK_EQUAL(0,RefCounter::s_instances);
{
array_ptr<RefCounter> a(new RefCounter[20]);
CHECK_EQUAL(20,RefCounter::s_instances);
}
CHECK_EQUAL(0,RefCounter::s_instances);
}
TEST_FIXTURE(InstanceFixture,ArrayAssignZeroForDeletion)
{
CHECK_EQUAL(0,RefCounter::s_instances);
array_ptr<RefCounter> a = new RefCounter[20];
CHECK_EQUAL(20,RefCounter::s_instances);
a = 0;
CHECK_EQUAL(0,RefCounter::s_instances);
}
TEST_FIXTURE(InstanceFixture,AssignNewPointerForDeletion)
{
CHECK_EQUAL(0,RefCounter::s_instances);
ptr<RefCounter> a = new RefCounter;
CHECK_EQUAL(1,RefCounter::s_instances);
a = new RefCounter;
CHECK_EQUAL(1,RefCounter::s_instances);
a = 0;
CHECK_EQUAL(0,RefCounter::s_instances);
}
TEST_FIXTURE(InstanceFixture,ArrayAssignNewPointerForDeletion)
{
CHECK_EQUAL(0,RefCounter::s_instances);
array_ptr<RefCounter> a = new RefCounter[37];
CHECK_EQUAL(37,RefCounter::s_instances);
a = new RefCounter[10];
CHECK_EQUAL(10,RefCounter::s_instances);
a = 0;
CHECK_EQUAL(0,RefCounter::s_instances);
}
TEST_FIXTURE(InstanceFixture,CopyToAnotherSmartPointer)
{
CHECK_EQUAL(0,RefCounter::s_instances);
ptr<RefCounter> a = new RefCounter;
CHECK_EQUAL(1,RefCounter::s_instances);
ptr<RefCounter> b(a);
CHECK_EQUAL(1,RefCounter::s_instances);
a = 0;
CHECK_EQUAL(1,RefCounter::s_instances);
b = 0;
CHECK_EQUAL(0,RefCounter::s_instances);
}
TEST_FIXTURE(InstanceFixture,ArrayCopyToAnotherSmartPointer)
{
CHECK_EQUAL(0,RefCounter::s_instances);
array_ptr<RefCounter> a = new RefCounter[3];
CHECK_EQUAL(3,RefCounter::s_instances);
array_ptr<RefCounter> b(a);
CHECK_EQUAL(3,RefCounter::s_instances);
a = 0;
CHECK_EQUAL(3,RefCounter::s_instances);
b = 0;
CHECK_EQUAL(0,RefCounter::s_instances);
}
TEST_FIXTURE(InstanceFixture,StlVector)
{
CHECK_EQUAL(0,RefCounter::s_instances);
std::vector< ptr<RefCounter> > va,vb;
{
{
std::vector< ptr<RefCounter> > vc;
vc.push_back(new RefCounter);
CHECK_EQUAL(1,RefCounter::s_instances);
vc.push_back(new RefCounter);
CHECK_EQUAL(2,RefCounter::s_instances);
vc.push_back(new RefCounter);
CHECK_EQUAL(3,RefCounter::s_instances);
vb = vc;
CHECK_EQUAL(3,RefCounter::s_instances);
}
CHECK_EQUAL(3,RefCounter::s_instances);
va.push_back(vb[0]);
CHECK_EQUAL(3,RefCounter::s_instances);
vb.clear();
CHECK_EQUAL(1,RefCounter::s_instances);
}
CHECK_EQUAL(1,RefCounter::s_instances);
va.clear();
CHECK_EQUAL(0,RefCounter::s_instances);
}
TEST_FIXTURE(InstanceFixture,ArrayStlVector)
{
CHECK_EQUAL(0,RefCounter::s_instances);
std::vector< array_ptr<RefCounter> > va,vb;
{
{
std::vector< array_ptr<RefCounter> > vc;
vc.push_back(new RefCounter[5]);
CHECK_EQUAL(5,RefCounter::s_instances);
vc.push_back(new RefCounter[3]);
CHECK_EQUAL(8,RefCounter::s_instances);
vc.push_back(new RefCounter[7]);
CHECK_EQUAL(15,RefCounter::s_instances);
vb = vc;
CHECK_EQUAL(15,RefCounter::s_instances);
}
CHECK_EQUAL(15,RefCounter::s_instances);
va.push_back(vb[0]);
CHECK_EQUAL(15,RefCounter::s_instances);
vb.clear();
CHECK_EQUAL(5,RefCounter::s_instances);
}
CHECK_EQUAL(5,RefCounter::s_instances);
va.clear();
CHECK_EQUAL(0,RefCounter::s_instances);
}
TEST_FIXTURE(InstanceFixture,StlList)
{
CHECK_EQUAL(0,RefCounter::s_instances);
std::list< ptr<RefCounter> > la,lb;
{
{
std::list< ptr<RefCounter> > lc;
lc.push_back(new RefCounter);
CHECK_EQUAL(1,RefCounter::s_instances);
lc.push_back(new RefCounter);
CHECK_EQUAL(2,RefCounter::s_instances);
lc.push_back(new RefCounter);
CHECK_EQUAL(3,RefCounter::s_instances);
lb = lc;
CHECK_EQUAL(3,RefCounter::s_instances);
}
CHECK_EQUAL(3,RefCounter::s_instances);
la.push_back(lb.front());
CHECK_EQUAL(3,RefCounter::s_instances);
lb.clear();
CHECK_EQUAL(1,RefCounter::s_instances);
}
CHECK_EQUAL(1,RefCounter::s_instances);
la.clear();
CHECK_EQUAL(0,RefCounter::s_instances);
}
TEST_FIXTURE(InstanceFixture,ArrayStlList)
{
CHECK_EQUAL(0,RefCounter::s_instances);
std::list< array_ptr<RefCounter> > la,lb;
{
{
std::list< array_ptr<RefCounter> > lc;
lc.push_back(new RefCounter[7]);
CHECK_EQUAL(7,RefCounter::s_instances);
lc.push_back(new RefCounter[8]);
CHECK_EQUAL(15,RefCounter::s_instances);
lc.push_back(new RefCounter[80]);
CHECK_EQUAL(95,RefCounter::s_instances);
lb = lc;
CHECK_EQUAL(95,RefCounter::s_instances);
}
CHECK_EQUAL(95,RefCounter::s_instances);
la.push_back(lb.front());
CHECK_EQUAL(95,RefCounter::s_instances);
lb.clear();
CHECK_EQUAL(7,RefCounter::s_instances);
}
CHECK_EQUAL(7,RefCounter::s_instances);
la.clear();
CHECK_EQUAL(0,RefCounter::s_instances);
}
TEST_FIXTURE(InstanceFixture,EqualityOperators)
{
CHECK_EQUAL(0,RefCounter::s_instances);
RefCounter* xa = new RefCounter;
RefCounter* xb = new RefCounter;
ptr<RefCounter> pa,pb;
if ( xa < xb )
{
pa = xa;
pb = xb;
}
else
{
pa = xb;
pb = xa;
}
CHECK_EQUAL(2,RefCounter::s_instances);
CHECK(pa<pb);
CHECK(pb>pa);
CHECK(pa<=pa);
CHECK(pb>=pb);
CHECK(pa<=pa);
CHECK(pb>=pb);
CHECK(pa==pa);
CHECK(pb==pb);
CHECK(pa!=pb);
pa = 0;
CHECK_EQUAL(1,RefCounter::s_instances);
pb = 0;
CHECK_EQUAL(0,RefCounter::s_instances);
}
TEST_FIXTURE(InstanceFixture,ArrayEqualityOperators)
{
CHECK_EQUAL(0,RefCounter::s_instances);
RefCounter* xa = new RefCounter[4];
RefCounter* xb = new RefCounter[6];
array_ptr<RefCounter> pa,pb;
if ( xa < xb )
{
pa = xa;
pb = xb;
}
else
{
pa = xb;
pb = xa;
}
CHECK_EQUAL(10,RefCounter::s_instances);
CHECK(pa<pb);
CHECK(pb>pa);
CHECK(pa<=pa);
CHECK(pb>=pb);
CHECK(pa<=pa);
CHECK(pb>=pb);
CHECK(pa==pa);
CHECK(pb==pb);
CHECK(pa!=pb);
pa = 0;
CHECK_EQUAL(6,RefCounter::s_instances);
pb = 0;
CHECK_EQUAL(0,RefCounter::s_instances);
}
TEST_FIXTURE(InstanceFixture,AccessPointer)
{
CHECK_EQUAL(0,RefCounter::s_instances);
ptr<RefCounter> a = new RefCounter;
CHECK_EQUAL(1,RefCounter::s_instances);
CHECK_EQUAL(5,(*a).Get(5));
CHECK_EQUAL(5,a->Get(5));
a = 0;
CHECK_EQUAL(0,RefCounter::s_instances);
}
TEST_FIXTURE(InstanceFixture,ArrayAccessPointer)
{
CHECK_EQUAL(0,RefCounter::s_instances);
array_ptr<RefCounter> a = new RefCounter[6];
CHECK_EQUAL(6,RefCounter::s_instances);
CHECK_EQUAL(5,(*a).Get(5));
CHECK_EQUAL(5,a->Get(5));
CHECK_EQUAL(5,a[0].Get(5));
a = 0;
CHECK_EQUAL(0,RefCounter::s_instances);
}
TEST_FIXTURE(InstanceFixture,BasicInheritance)
{
CHECK_EQUAL(0,RefCounter::s_instances);
ptr<RefCounter> a = new RefCounterDerived;
CHECK_EQUAL(1,RefCounter::s_instances);
CHECK_EQUAL(10,(*a).Get(5));
CHECK_EQUAL(10,a->Get(5));
a = 0;
CHECK_EQUAL(0,RefCounter::s_instances);
}
TEST_FIXTURE(InstanceFixture,ArrayBasicInheritance)
{
CHECK_EQUAL(0,RefCounter::s_instances);
array_ptr<RefCounter> a = new RefCounterDerived[2];
CHECK_EQUAL(2,RefCounter::s_instances);
CHECK_EQUAL(10,(*a).Get(5));
CHECK_EQUAL(10,a->Get(5));
a = 0;
CHECK_EQUAL(0,RefCounter::s_instances);
}
TEST_FIXTURE(InstanceFixture,ListOfBasePointers)
{
CHECK_EQUAL(0,RefCounter::s_instances);
std::vector< ptr<RefCounter> > v;
v.push_back(new RefCounter);
CHECK_EQUAL(1,RefCounter::s_instances);
v.push_back(new RefCounterDerived);
CHECK_EQUAL(2,RefCounter::s_instances);
v.clear();
CHECK_EQUAL(0,RefCounter::s_instances);
}
TEST_FIXTURE(InstanceFixture,ArrayListOfBasePointers)
{
CHECK_EQUAL(0,RefCounter::s_instances);
std::vector< array_ptr<RefCounter> > v;
v.push_back(new RefCounter[5]);
CHECK_EQUAL(5,RefCounter::s_instances);
v.push_back(new RefCounterDerived[2]);
CHECK_EQUAL(7,RefCounter::s_instances);
v.clear();
CHECK_EQUAL(0,RefCounter::s_instances);
}
TEST_FIXTURE(InstanceFixture,CopyInvalidPointers)
{
CHECK_EQUAL(0,RefCounter::s_instances);
ptr<RefCounter> a;
CHECK_EQUAL(0,RefCounter::s_instances);
CHECK(!a.valid());
ptr<RefCounter> b(a);
CHECK(!a.valid());
CHECK(!b.valid());
CHECK_EQUAL(0,RefCounter::s_instances);
b = new RefCounter;
CHECK(!a.valid());
CHECK(b.valid());
CHECK_EQUAL(1,RefCounter::s_instances);
b = a;
CHECK(!a.valid());
CHECK(!b.valid());
CHECK_EQUAL(0,RefCounter::s_instances);
}
TEST_FIXTURE(InstanceFixture,ArrayCopyInvalidPointers)
{
CHECK_EQUAL(0,RefCounter::s_instances);
array_ptr<RefCounter> a;
CHECK_EQUAL(0,RefCounter::s_instances);
CHECK(!a.valid());
array_ptr<RefCounter> b(a);
CHECK(!a.valid());
CHECK(!b.valid());
CHECK_EQUAL(0,RefCounter::s_instances);
b = new RefCounter[3];
CHECK(!a.valid());
CHECK(b.valid());
CHECK_EQUAL(3,RefCounter::s_instances);
b = a;
CHECK(!a.valid());
CHECK(!b.valid());
CHECK_EQUAL(0,RefCounter::s_instances);
}
TEST_FIXTURE(InstanceFixture,BoolValidityCheck)
{
CHECK_EQUAL(0,RefCounter::s_instances);
{
ptr<RefCounter> a, b(new RefCounter), c;
CHECK_EQUAL(1,RefCounter::s_instances);
CHECK(!a);
CHECK(!a.valid());
CHECK(!c);
CHECK(!c.valid());
CHECK(b);
CHECK(b.valid());
CHECK(a || b || c);
a = b;
CHECK_EQUAL(1,RefCounter::s_instances);
CHECK(a);
CHECK(a.valid());
CHECK(b);
CHECK(b.valid());
CHECK(a || b);
CHECK(a && b);
b = 0;
CHECK_EQUAL(1,RefCounter::s_instances);
CHECK(a);
CHECK(a.valid());
CHECK(!b);
CHECK(!b.valid());
c = new RefCounterDerived;
CHECK_EQUAL(2,RefCounter::s_instances);
CHECK(c);
CHECK(c.valid());
}
CHECK_EQUAL(0,RefCounter::s_instances);
}
TEST_FIXTURE(InstanceFixture,ArrayBoolValidityCheck)
{
CHECK_EQUAL(0,RefCounter::s_instances);
{
array_ptr<RefCounter> a, b(new RefCounter[1]), c;
CHECK_EQUAL(1,RefCounter::s_instances);
CHECK(!a);
CHECK(!a.valid());
CHECK(!c);
CHECK(!c.valid());
CHECK(b);
CHECK(b.valid());
CHECK(a || b || c);
a = b;
CHECK_EQUAL(1,RefCounter::s_instances);
CHECK(a);
CHECK(a.valid());
CHECK(b);
CHECK(b.valid());
CHECK(a || b);
CHECK(a && b);
b = 0;
CHECK_EQUAL(1,RefCounter::s_instances);
CHECK(a);
CHECK(a.valid());
CHECK(!b);
CHECK(!b.valid());
c = new RefCounterDerived[1];
CHECK_EQUAL(2,RefCounter::s_instances);
CHECK(c);
CHECK(c.valid());
}
CHECK_EQUAL(0,RefCounter::s_instances);
}
TEST_FIXTURE(InstanceFixture,MapMadness)
{
CHECK_EQUAL(0,RefCounter::s_instances);
{
std::map< ptr<RefCounter>, ptr<RefCounter> > m,m1,m2,m3,m4;
CHECK_EQUAL(0,RefCounter::s_instances);
for (int i=0;i<1000;++i)
{
m[ new RefCounter ] = new RefCounterDerived;
CHECK_EQUAL((i+1)*2,RefCounter::s_instances);
}
m1 = m2 = m3 = m4 = m;
CHECK_EQUAL(2000,RefCounter::s_instances);
m.clear();
CHECK_EQUAL(2000,RefCounter::s_instances);
m2.clear();
CHECK_EQUAL(2000,RefCounter::s_instances);
m3.clear();
CHECK_EQUAL(2000,RefCounter::s_instances);
m4.clear();
CHECK_EQUAL(2000,RefCounter::s_instances);
}
CHECK_EQUAL(0,RefCounter::s_instances);
}
TEST_FIXTURE(InstanceFixture,ArrayMapMadness)
{
CHECK_EQUAL(0,RefCounter::s_instances);
{
std::map< array_ptr<RefCounter>, array_ptr<RefCounter> > m,m1,m2,m3,m4;
CHECK_EQUAL(0,RefCounter::s_instances);
for (int i=0;i<1000;++i)
{
m[ new RefCounter[2] ] = new RefCounterDerived[2];
CHECK_EQUAL((i+1)*4,RefCounter::s_instances);
}
m1 = m2 = m3 = m4 = m;
CHECK_EQUAL(4000,RefCounter::s_instances);
m.clear();
CHECK_EQUAL(4000,RefCounter::s_instances);
m2.clear();
CHECK_EQUAL(4000,RefCounter::s_instances);
m3.clear();
CHECK_EQUAL(4000,RefCounter::s_instances);
m4.clear();
CHECK_EQUAL(4000,RefCounter::s_instances);
}
CHECK_EQUAL(0,RefCounter::s_instances);
}
TEST_FIXTURE(InstanceFixture,ArrayIndexing)
{
int* p = new int[10];
for (int i=0;i<10;++i)
{
p[i] = i;
}
array_ptr<int> q = p;
for (int i=0;i<10;++i)
{
CHECK_EQUAL(i,q[i]);
CHECK_EQUAL(&(p[i]),&(q[i]));
}
}
int main(int argc, char** argv)
{
return UnitTest::RunAllTests();
}
|
import { CurrentFormetter} from "@/Utilities/Councey";
import React from "react";
import Button from "@/components/Button";
import Link from "next/link";
export default function CourseItem({ course, loading, error }) {
return (
<div>
{course && (
<div className="w-full lg:[30rem] shadow-md rounded-md overflow-hidden ">
<div className="w-full h-[20rem] overflow-hidden flex justify-center">
<img
src={course.cover}
alt={course.title}
className="object-cover w-full h-full"
/>
</div>
<div className="p-5 space-y-2 w-full">
<h1 className=" text-3xl font-medium">{course.title}</h1>
<p className=" flex justify-between">
<span>
By{" "}
<span className=" text-black font-semibold">
{course.instructor}
</span>
</span>
<span className=" ">
Duration:{" "}
<span className=" text-black font-semibold">
{course.duration}
</span>
</span>
</p>
<p>
<span className=" font-semibold text-black">{course.rating}</span>
</p>
<p className=" text-gray-500">{course.description.substring(0, 100)}...</p>
<div className=" flex justify-between items-center">
<p className=" text-lg font-semibold">
{CurrentFormetter(parseFloat(course.price))}
</p>
<Link className="text-white font-semibold bg-black px-6 py-3 rounded-md hover:bg-gray-900 transition-colors"
href={`/courses/${course.id}`} >view deatiles</Link>
</div>
</div>
</div>
)}
</div>
);
}
|
from multiprocessing import Process, Queue, Pool, Pipe,Manager
# from queue import Queue # 这个不能用在这里
import time
# def producer(queue):
# queue.put("a")
# time.sleep(2)
#
# def consumer(queue):
# time.sleep(2)
# data = queue.get()
# print(data)
#
# if __name__ == "__main__":
# queue = Queue(10)
# my_producer = Process(target=producer, args=(queue,))
# my_consumer = Process(target=consumer, args=(queue,))
# my_producer.start()
# my_consumer.start()
# my_producer.join()
# my_consumer.join()
# pass
# 共享全局变量通信
# 共享全局变量是不能适用于多进程编程的,可以适用于多线程,需要同步
# 多进程时进程之间的数据是完全隔离的,会把进程的全局变量完全复制一份,两边数据修改时不会相互影响
# multiprocessing中的queue不能用于pool进程池
# pool中的进程间通信需要使用 manager中的queue
# from queue import Queue
# from multiprocessing import Queue
# from multiprocessing import Manager
# Manager().Queue()
# def producer(a):
# a += 100
# time.sleep(2)
#
# def consumer(a):
# time.sleep(2)
# print(a)
#
# if __name__ == "__main__":
# a = 1
# my_producer = Process(target=producer, args=(a,))
# my_consumer = Process(target=consumer, args=(a,))
# my_producer.start()
# my_consumer.start()
# my_producer.join()
# my_consumer.join()
# pass
# def producer(a):
# a += 100
# time.sleep(2)
#
# def consumer(a):
# time.sleep(2)
# print(a)
#
# if __name__ == "__main__":
# queue = Manager.Queue(10)
# pool = Pool(2)
#
# pool.apply_async(producer, args=(queue,))
# pool.apply_async(consumer, args=(queue,))
#
# pool.close()
# pool.join()
# 通过管道pipe实现进程间通信
# 类似于socket的发送与接收
# pipe的性能高于queue
# def producer(pipe):
# pipe.send("Hello,ajioy!")
#
# def consumer(pipe):
# print(pipe.recv())
#
# if __name__ == "__main__":
# recv_pipe, send_pipe = Pipe()
# # pipe只适用于两个进程间的通信
# pool = Pool(2)
# my_producer = Process(target=producer, args=(send_pipe, ))
# my_consumer = Process(target=consumer, args=(recv_pipe, ))
#
# my_producer.start()
# my_consumer.start()
# my_producer.join()
# my_consumer.join()
def add_data(p_dict, key, value):
p_dict[key] = value
if __name__ == "__main__":
progress_dict = Manager().dict()
first_progress = Process(target=add_data, args=(progress_dict, "ajioy1"))
second_progress = Process(target=add_data, args=(progress_dict, "ajioy1"))
first_progress.start()
second_progress.start()
first_progress.join()
second_progress.join()
print(progress_dict)
|
using System.Collections.Generic;
using System.Linq;
using TMPro;
using UnityEngine;
namespace WaveMakerScript
{
public class WaveMaker : MonoBehaviour
{
Resources Resources;
GroupBoxManager GroupBoxManager;
FileManager FileManager;
private void Awake()
{
Resources = GetComponent<Resources>();
FileManager = GetComponent<FileManager>();
}
public void SaveFile()
{
List<string> files = FileManager.Get_Files();
if (files.Any(x => x == Resources.WMFileName) || Resources.WMFileName.Length < 5 || Resources.WMFileName.Length > 15)
{
if ((Resources.SelectedFile != Resources.WMFileName) || ((Resources.SelectedFile == Resources.WMFileName) && Resources.SelectedFile == "")
|| Resources.WMFileName == "Official" || Resources.WMFileName == "Tutorial")
{
SoundsManager.Play(SoundsName.WaveMakerError_UI);
Resources.WarningWindow.SetActive(true); Resources.WarningWindow.transform.SetAsLastSibling();
return;
}
}
WaveDatabaseScriptable database = ScriptableObject.CreateInstance<WaveDatabaseScriptable>();
int waveSize = Resources.FileContent.Waves.Count();
for (int waveID = 0; waveID < waveSize; waveID++)
{
Wave wave = new Wave();
wave.Timer = Resources.FileContent.Waves[waveID].Timer();
int splitSize = Resources.FileContent.Waves[waveID].Splits.Count();
for (int splitID = 0; splitID < splitSize; splitID++)
{
WaveStep waveStep = new WaveStep();
waveStep.Timer = Resources.FileContent.Waves[waveID].Splits[splitID].Timer();
wave.Splits.Add(waveStep);
int enemySize = Resources.FileContent.Waves[waveID].Splits[splitID].Enemies.Count();
for (int enemyID = 0; enemyID < enemySize; enemyID++)
{
List<EnemyGB> enemies = Resources.FileContent.Waves[waveID].Splits[splitID].Enemies;
Enemy enemy = new Enemy();
enemy.Timer = enemies[enemyID].Timer();
enemy.Name = (Enemies)enemies[enemyID].Type.value;
waveStep.Enemies.Add(enemy);
}
}
database.Waves.Add(wave);
}
WaveManager.SaveWavesInTxtFile(Resources.WMFileName + ".txt", database);
Resources.SaveWindow.SetActive(true);
Resources.SaveWindow.transform.SetAsLastSibling();
SoundsManager.Play(SoundsName.WaveMakerConfirm_UI);
}
/// <summary>
/// It's purpose is to instantiate a simple gameObject
/// from the parent's transform, a type, an index and a version
/// </summary>
public GameObject Instantiate_UIObject(GroupBox type, Transform parent, int index, Mode mode)
{
GameObject GameObject = null;
GameObject[] prefabs = mode == Mode.WaveDisplay ? Resources.WDPrefabs : Resources.WMPrefabs;
GameObject = Instantiate(prefabs[(int)type]);
GameObject.transform.SetParent(parent, false);
GameObject.transform.SetSiblingIndex(index);
GameObject.name = GameObject.name.Replace("(Clone)", "");
return GameObject;
}
#region Set_Color
private bool Compare_Colors(Color prevColor, Color currColor)
{
float sum = currColor.r + currColor.g + currColor.b;
float sum2 = prevColor.r + prevColor.g + prevColor.b;
if (Mathf.Abs(sum - sum2) < 0.3f)
{
return false;
}
return true;
}
private bool Compare_Colors(Color prevColor, Color currColor, Color nextColor)
{
List<Color> colors = new List<Color> { prevColor, nextColor };
foreach (Color color in colors)
{
float sum = currColor.r + currColor.g + currColor.b;
float sum2 = color.r + color.g + color.b;
if (Mathf.Abs(sum - sum2) < 0.3f)
{
return false;
}
}
return true;
}
private Color Randomize_Color(GroupBox type)
{
bool canReturn = false;
Color color;
do
{
color = Random.ColorHSV(0.2f, 1f, 1f, 1f, 0.5f, 1f);
switch (type)
{
case GroupBox.Wave:
if (color.b > color.g * 1.2 && color.b > color.r * 1.2) { canReturn = true; }
break;
case GroupBox.Split:
if (color.g > color.r * 1.2 && color.g > color.b * 1.2) { canReturn = true; }
break;
case GroupBox.Enemy:
if (color.r > color.g * 1.2 && color.r > color.b * 1.2) { canReturn = true; }
break;
}
} while (!canReturn);
return color;
}
private void Get_Color(GameObject obj, bool _isInit)
{
GBResources res = obj.GBRes();
GroupBoxLayout gbl = obj.GBLayout();
int offset = Resources.WTMode == Mode.WaveDisplay ? 1 : 2;
int childOffset = Resources.WTMode == Mode.WaveDisplay ? 0 : -1;
if (res.ListID > 0)
{
Color prevColor, color, nextColor;
Transform content = gbl.Parents[0].GBRes().Content;
int childs = content.childCount;
prevColor = gbl.Parents[0].GBRes().Content.GetChild(res.HierarchyID - offset).gameObject.GBRes().color;
if ((gbl.Parents[0].GBRes().Content.childCount + childOffset >= res.HierarchyID + offset) && _isInit)
{
nextColor = gbl.Parents[0].GBRes().Content.GetChild(res.HierarchyID + offset).gameObject.GBRes().color;
do
{
color = Randomize_Color(res.Type);
} while (!Compare_Colors(prevColor, color, nextColor));
res.Color = color;
return;
}
do
{
color = Randomize_Color(res.Type);
} while (!Compare_Colors(prevColor, color));
res.Color = color;
return;
}
res.Color = Randomize_Color(res.Type);
}
#endregion
#region Fill_GroupBox
public void Set_Color(GameObject GroupBox, bool _isInit)
{
GBResources Res = GroupBox.GetComponent<GBResources>();
Res.Start();
Get_Color(GroupBox, _isInit);
}
/// <summary>
/// Fills a Wave GroupBox
/// with data from the groupbox prefab
/// Allows better data management and optimization
/// </summary>
public void Fill_GroupBox(GameObject GroupBox, WaveGB Wave)
{
GBResources Res = GroupBox.GetComponent<GBResources>();
Wave.Layout = GroupBox.GetComponent<GroupBoxLayout>();
Wave.GroupBox = GroupBox;
Wave.Content = Res.Content;
Wave.Data = Res.Data;
}
/// <summary>
/// Fills a Wave GroupBox
/// with data from the groupbox prefab
/// Allows better data management and optimization
/// </summary>
public void Fill_GroupBox(GameObject GroupBox, SplitGB Split)
{
GBResources Res = GroupBox.GetComponent<GBResources>();
Split.Layout = GroupBox.GetComponent<GroupBoxLayout>();
Split.GroupBox = GroupBox;
Split.Content = Res.Content;
Split.Data = Res.Data;
}
/// <summary>
/// Fills a Wave GroupBox
/// with data from the groupbox prefab
/// Allows better data management and optimization
/// </summary>
public void Fill_GroupBox(GameObject GroupBox, EnemyGB Enemy)
{
GBResources Res = GroupBox.GetComponent<GBResources>();
Enemy.Layout = GroupBox.GetComponent<GroupBoxLayout>();
Enemy.GroupBox = GroupBox;
Enemy.Data = Res.Data;
Enemy.Stats = Res.Stats;
Enemy.Type = Res.EnemyType;
Enemy.Image = Res.Image;
}
#endregion
#region Fill_Values
/// <summary>
/// Fills in a given Input Field a value
/// used for modifying Timers, Numbers or Amounts
/// </summary>
public void Fill_Value(TMP_InputField Field, float value)
{
Field.text = Format_Value(value);
}
public string Format_Value(float value)
{
string str = null;
str = value > 9 || value.ToString().Contains(',') ? value.ToString() : "0" + value.ToString();
return str;
}
public void Fill_Values(WaveGB waveGB, float[] values)
{
Fill_Value(waveGB.Data[(int)Data.Number], values[0]);
Fill_Value(waveGB.Data[(int)Data.Timer], values[1]);
Fill_Value(waveGB.Data[(int)Data.Amount], values[2]);
}
public void Fill_Values(SplitGB splitGB, float[] values)
{
Fill_Value(splitGB.Data[(int)Data.Number], values[0]);
Fill_Value(splitGB.Data[(int)Data.Timer], values[1]);
Fill_Value(splitGB.Data[(int)Data.Amount], values[2]);
}
public void Fill_Values(EnemyGB enemyGB, float[] values)
{
Fill_Value(enemyGB.Data[(int)Data.Number], values[0]);
Fill_Value(enemyGB.Data[(int)Data.Timer], values[1]);
}
public void Change_UnitPicture(GameObject gameObject)
{
gameObject.GBRes().Image.sprite = gameObject.GBRes().sprites[gameObject.GBRes().EnemyType.value];
}
public void Fill_Amounts(int value)
{
List<GameObject> results = new List<GameObject>();
Resources.WDRoot.Contains("Wave_Amount", results);
Resources.FileContent.Amount.AddRange(results.Select(x => x.GetComponent<TMP_InputField>()));
Resources.FileContent.Amount.ForEach(x => Fill_Value(x, value));
}
#endregion
#region File_Content
public void Fill_FileContent()
{
Resources.FileContent = new FileContent();
Resources.FileContent.Content = Resources.WDRoot.Contains("Waves_Content").transform;
Resources.FileContent.LoadingPanel = Resources.WDRoot.Contains("Loading_Screen");
Resources.FileContent.Layout = Resources.WDRoot.GetComponent<GroupBoxLayout>();
}
#endregion
#region IgnoreList
/// <summary>
/// Allows the ignorelist to include the gameobjects
/// from the wave displayer
/// </summary>
public void Fill_IgnoreList(GameObject gameObject, int index)
{
//List<GameObject> list = new List<GameObject>();
//gameObject.GetAllChilds(list);
//Resources.IgnoreList[index].AddRange(list);
}
public void Empty_IgnoreList(int index)
{
//Resources.IgnoreList[index].Clear();
}
#endregion
}
}
|
<template>
<div v-show="show" class="artist-page">
<div class="artist-info">
<div class="head">
<img :src="proxy.$filters.resizeImage(artist.img1v1Url, 1024)" />
</div>
<div>
<div class="name">{{ artist.name }}</div>
<div class="artist">{{ $t('artist.artist') }}</div>
<div class="statistics">
<a @click="scrollTo('popularTracks')">{{ artist.musicSize }} {{ $t('common.songs') }}</a>
·
<a @click="scrollTo('seeMore', 'start')">{{ artist.albumSize }} {{ $t('artist.withAlbums') }}</a>
·
<a @click="scrollTo('mvs')">{{ artist.mvSize }} {{ $t('artist.videos') }}</a>
</div>
<div class="description" @click="toggleFullDescription">
{{ artist.briefDesc }}
</div>
<div class="buttons">
<ButtonTwoTone icon-class="play" @click="playPopularSongs()">
{{ $t('common.play') }}
</ButtonTwoTone>
<ButtonTwoTone color="grey" @click="followArtist">
<span v-if="artist.followed">{{ $t('artist.following') }}</span>
<span v-else>{{ $t('artist.follow') }}</span>
</ButtonTwoTone>
<ButtonTwoTone
icon-class="more"
:icon-button="true"
:horizontal-padding="0"
color="grey"
@click="openMenu"
/>
</div>
</div>
</div>
<div class="latest-release">
<div class="section-title">{{ $t('artist.latestRelease') }}</div>
<div class="release">
<div class="container">
<Cover
:id="latestRelease.id"
:image-url="proxy.$filters.resizeImage(latestRelease.picUrl)"
type="album"
:fixed-size="128"
:play-button-size="30"
/>
<div class="info">
<div class="name">
<router-link :to="`/album/${latestRelease.id}`">{{ latestRelease.name }}</router-link>
</div>
<div class="date">
{{ proxy.$filters.formatDate(latestRelease.publishTime) }}
</div>
<div class="type">
{{ proxy.$filters.formatAlbumType(latestRelease.type, latestRelease) }}
· {{ latestRelease.size }} {{ $t('common.songs') }}
</div>
</div>
</div>
<div v-show="latestMV.id" class="container latest-mv">
<div
class="cover"
@mouseover="mvHover = true"
@mouseleave="mvHover = false"
@click="goToMv(latestMV.id)"
>
<img :src="latestMV.coverUrl" />
<transition name="fade">
<div
v-show="mvHover"
class="shadow"
:style="{
background: 'url(' + latestMV.coverUrl + ')',
}"
/>
</transition>
</div>
<div class="info">
<div class="name">
<router-link :to="'/mv/' + latestMV.id">{{ latestMV.name }}</router-link>
</div>
<div class="date">
{{ proxy.$filters.formatDate(latestMV.publishTime) }}
</div>
<div class="type">{{ $t('artist.latestMV') }}</div>
</div>
</div>
<div v-show="!latestMV.id" />
</div>
</div>
<div id="popularTracks" class="popular-tracks">
<div class="section-title">{{ $t('artist.popularSongs') }}</div>
<TrackList :tracks="popularTracks.slice(0, showMorePopTracks ? 24 : 12)" :type="'tracklist'" />
<div id="seeMore" class="show-more">
<button @click="showMorePopTracks = !showMorePopTracks">
<span v-show="!showMorePopTracks">{{ $t('artist.showMore') }}</span>
<span v-show="showMorePopTracks">{{ $t('artist.showLess') }}</span>
</button>
</div>
</div>
<div v-if="albums.length !== 0" id="albums" class="albums">
<div class="section-title">{{ $t('artist.albums') }}</div>
<CoverRow :type="'album'" :items="albums" :sub-text="'releaseYear'" :show-play-button="true" />
</div>
<div v-if="mvs.length !== 0" id="mvs" class="mvs">
<div class="section-title">
MVs
<router-link v-show="hasMoreMV" :to="`/artist/${artist.id}/mv`">{{ $t('home.seeMore') }}</router-link>
</div>
<MvRow :mvs="mvs" subtitle="publishTime" />
</div>
<div v-if="eps.length !== 0" class="eps">
<div class="section-title">{{ $t('artist.EPsSingles') }}</div>
<CoverRow :type="'album'" :items="eps" :sub-text="'albumType+releaseYear'" :show-play-button="true" />
</div>
<div v-if="similarArtist.length !== 0" class="similar-artists">
<div class="section-title">{{ $t('artist.similarArtists') }}</div>
<CoverRow type="artist" :column-number="6" gap="36px 28px" :items="similarArtist.slice(0, 12)" />
</div>
<Modal
:show="showFullDescription"
:close="toggleFullDescription"
:show-footer="false"
:click-outside-hide="true"
:title="$t('artist.artistDesc')"
>
<p class="description-fulltext">
{{ artist.briefDesc }}
</p>
</Modal>
<ContextMenu ref="artistMenu">
<div class="item" @click="copyUrl(artist.id)">{{ $t('contextMenu.copyUrl') }}</div>
</ContextMenu>
</div>
</template>
<script>
import { ref, computed, onActivated, getCurrentInstance } from 'vue'
import { useStore } from 'vuex'
import { useRoute, useRouter, onBeforeRouteUpdate } from 'vue-router'
import NProgress from 'nprogress'
import { useI18n } from 'vue-i18n'
import useClipboard from 'vue-clipboard3'
import { getArtist, getArtistAlbum, artistMv, followAArtist, similarArtists } from '@render/NeteastApi/artist'
import { isAccountLoggedIn } from '@render/utils/auth'
import ButtonTwoTone from '@render/components/ButtonTwoTone.vue'
import TrackList from '@render/components/TrackList.vue'
import CoverRow from '@render/components/CoverRow.vue'
import Cover from '@render/components/Cover.vue'
import MvRow from '@render/components/MvRow.vue'
import Modal from '@render/components/Modal.vue'
import ContextMenu from '@render/components/ContextMenu.vue'
export default {
name: 'Artist',
components: {
Cover,
ButtonTwoTone,
TrackList,
CoverRow,
MvRow,
Modal,
ContextMenu,
},
setup() {
const store = useStore()
const route = useRoute()
const router = useRouter()
const { t } = useI18n()
const { proxy } = getCurrentInstance()
const { toClipboard } = useClipboard()
const show = ref(false)
const artist = ref({
img1v1Url: 'https://p1.music.126.net/VnZiScyynLG7atLIZ2YPkw==/18686200114669622.jpg',
})
const popularTracks = ref([])
const albumsData = ref([])
const latestRelease = ref({
picUrl: '',
publishTime: 0,
id: 0,
name: '',
type: '',
size: '',
})
const showMorePopTracks = ref(false)
const showFullDescription = ref(false)
const mvs = ref([])
const hasMoreMV = ref(false)
const similarArtist = ref([])
const mvHover = ref(false)
const player = computed(() => store.state.player)
const showToast = (toast) => {
store.dispatch('toast/showToast', toast)
}
const albums = computed(() => {
return albumsData.value.filter((a) => a.type === '专辑')
})
const eps = computed(() => {
return albumsData.value.filter((a) => ['EP/Single', 'EP', 'Single'].includes(a.type))
})
const latestMV = computed(() => {
const mv = mvs.value[0] || []
return {
id: mv.id || mv.vid,
name: mv.name || mv.title,
coverUrl: `${mv.imgurl16v9 || mv.cover || mv.coverUrl}?param=464y260`,
publishTime: mv.publishTime,
}
})
const goToAlbum = (id) => {
router.push({
name: 'album',
params: {
id,
},
})
}
const goToMv = (id) => {
router.push({
path: '/mv/' + id,
})
}
const playPopularSongs = (trackID = 'first') => {
let trackIDs = popularTracks.value.map((track) => track.id)
if (trackIDs === undefined) {
dispatch('toast/showToast', `${t('toast.cannotPlay')} ${artist.value.name}`, { root: true })
} else {
store.dispatch('player/replacePlaylist', { trackIDs, id: artist.value.id, type: 'artist', trackID })
}
}
const followArtist = () => {
if (!isAccountLoggedIn()) {
showToast(t('toast.needToLogin'))
return
}
followAArtist({
id: artist.value.id,
t: artist.value.followed ? 0 : 1,
}).then((res) => {
if (res.code === 200) {
artist.value.followed = !artist.value.followed
}
})
}
const scrollTo = (div, block = 'center') => {
document.getElementById(div).scrollIntoView({
behavior: 'smooth',
block,
})
}
const toggleFullDescription = () => {
showFullDescription.value = !showFullDescription.value
if (showFullDescription.value) {
store.commit('enableScrolling', false)
} else {
store.commit('enableScrolling', true)
}
}
const loadData = (id, next = undefined) => {
setTimeout(() => {
if (!show.value) {
NProgress.start()
}
}, 1000)
show.value = false
proxy.$root.$refs.main.scrollTo({
top: 0,
})
getArtist(id).then((res) => {
artist.value = res.artist
popularTracks.value = res.hotSongs
if (next !== undefined) {
next()
}
NProgress.done()
show.value = true
})
getArtistAlbum({ id: id, limit: 200 }).then((res) => {
albumsData.value = res.hotAlbums
latestRelease.value = res.hotAlbums[0]
})
artistMv({ id }).then((res) => {
mvs.value = res.mvs
hasMoreMV.value = res.hasMore
})
similarArtists(id).then((res) => {
similarArtist.value = res.artists
})
}
const openMenu = (e) => {
proxy.$refs.artistMenu.openMenu(e)
}
const copyUrl = async (id) => {
try {
await toClipboard('https://music.163.com/#/artist?id=' + id)
showToast(t('toast.copied'))
} catch (error) {
showToast(`${t('toast.copyFailed')}${error}`)
}
}
onBeforeRouteUpdate((to, from, next) => {
artist.value.img1v1Url = 'https://p1.music.126.net/VnZiScyynLG7atLIZ2YPkw==/18686200114669622.jpg'
loadData(to.params.id, next)
})
onActivated(() => {
if (artist.value?.id?.toString() !== route.params.id) {
loadData(route.params.id)
} else {
proxy.$root.$refs.scrollbar.restorePosition()
}
})
return {
store,
route,
proxy,
router,
show,
artist,
popularTracks,
albumsData,
latestRelease,
showMorePopTracks,
showFullDescription,
mvs,
hasMoreMV,
similarArtist,
mvHover,
showToast,
albums,
eps,
latestMV,
goToAlbum,
goToMv,
playPopularSongs,
followArtist,
scrollTo,
toggleFullDescription,
loadData,
openMenu,
copyUrl,
}
},
}
</script>
<style lang="scss" scoped>
.artist-page {
margin-top: 32px;
}
.artist-info {
display: flex;
align-items: center;
margin-bottom: 26px;
color: var(--color-text);
img {
height: 248px;
width: 248px;
border-radius: 50%;
margin-right: 56px;
box-shadow: rgba(0, 0, 0, 0.2) 0px 12px 16px -8px;
}
.name {
font-size: 56px;
font-weight: 700;
}
.artist {
font-size: 18px;
opacity: 0.88;
margin-top: 24px;
}
.statistics {
font-size: 14px;
opacity: 0.68;
margin-top: 2px;
}
.buttons {
margin-top: 26px;
display: flex;
.shuffle {
padding: 8px 11px;
.svg-icon {
margin: 0;
}
}
}
.description {
user-select: none;
font-size: 14px;
opacity: 0.68;
margin-top: 24px;
display: -webkit-box;
-webkit-box-orient: vertical;
-webkit-line-clamp: 2;
overflow: hidden;
cursor: pointer;
white-space: pre-line;
&:hover {
transition: opacity 0.3s;
opacity: 0.88;
}
}
}
.section-title {
font-weight: 600;
font-size: 22px;
opacity: 0.88;
color: var(--color-text);
margin-bottom: 16px;
padding-top: 46px;
display: flex;
justify-content: space-between;
align-items: flex-end;
a {
font-size: 13px;
font-weight: 600;
opacity: 0.68;
}
}
.latest-release {
color: var(--color-text);
.release {
display: flex;
}
.container {
display: flex;
flex: 1;
align-items: center;
border-radius: 12px;
}
img {
height: 96px;
border-radius: 8px;
}
.info {
margin-left: 24px;
}
.name {
font-size: 18px;
font-weight: 600;
margin-bottom: 8px;
}
.date {
font-size: 14px;
opacity: 0.78;
}
.type {
margin-top: 2px;
font-size: 12px;
opacity: 0.68;
}
}
.popular-tracks {
.show-more {
display: flex;
button {
padding: 4px 8px;
margin-top: 8px;
border-radius: 6px;
font-size: 12px;
opacity: 0.78;
color: var(--color-secondary);
font-weight: 600;
&:hover {
opacity: 1;
}
}
}
}
.similar-artists {
.section-title {
margin-bottom: 24px;
}
}
.latest-mv {
.cover {
position: relative;
transition: transform 0.3s;
&:hover {
cursor: pointer;
}
}
img {
border-radius: 0.75em;
height: 128px;
object-fit: cover;
user-select: none;
}
.shadow {
position: absolute;
top: 6px;
height: 100%;
width: 100%;
filter: blur(16px) opacity(0.4);
transform: scale(0.9, 0.9);
z-index: -1;
background-size: cover;
border-radius: 0.75em;
}
.fade-enter-active,
.fade-leave-active {
transition: opacity 0.3s;
}
.fade-enter, .fade-leave-to /* .fade-leave-active below version 2.1.8 */ {
opacity: 0;
}
}
.description-fulltext {
font-size: 16px;
margin-top: 24px;
display: -webkit-box;
-webkit-box-orient: vertical;
overflow: hidden;
white-space: pre-line;
}
</style>
|
/*************************************************************************
*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* Copyright 2008 by Sun Microsystems, Inc.
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile$
* $Revision$
*
* This file is part of OpenOffice.org.
*
* OpenOffice.org is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License version 3
* only, as published by the Free Software Foundation.
*
* OpenOffice.org is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License version 3 for more details
* (a copy is included in the LICENSE file that accompanied this code).
*
* You should have received a copy of the GNU Lesser General Public License
* version 3 along with OpenOffice.org. If not, see
* <http://www.openoffice.org/license.html>
* for a copy of the LGPLv3 License.
*
************************************************************************/
package com.sun.star.lib.uno.typeinfo;
import com.sun.star.uno.Type;
public class MemberTypeInfo extends TypeInfo
{
int m_index;
private final Type m_unoType; // @since UDK 3.2
private final int m_typeParameterIndex; // @since UDK 3.2
/**
Create a member type info with a UNO type that cannot unambiguously be
represented as a Java 1.2 type.
@param name the name of this member; must not be <code>null</code>
@param index the index among the direct members
@param flags any flags (<code>UNSIGNED</code>, <code>ANY</code>,
<code>INTERFACE</code>, <code>TYPE_PARAMETER</code>)
@param unoType the exact UNO type; or <code>null</code> if the UNO type
is already unambiguously represented by the Java 1.2 type
@param typeParameterIndex the index of the type parameter that determines
the type of this parameterized member; or <code>-1</code> if this member
is of an explicit type, or is the member of a plain struct type
@since UDK 3.2
*/
public MemberTypeInfo(
String name, int index, int flags, Type unoType, int typeParameterIndex)
{
super(name, flags);
m_index = index;
m_unoType = unoType;
m_typeParameterIndex = typeParameterIndex;
}
public MemberTypeInfo(String name, int index, int flags )
{
this(name, index, flags, null, -1);
}
public int getIndex()
{
return m_index;
}
/**
Get the exact UNO type of this member type info, in case it cannot
unambiguously be represented as a Java 1.2 type.
@return the exact UNO type of this member type info, or <code>null</code>
if the UNO type is already unambiguously represented by the Java 1.2
type
@since UDK 3.2
*/
public final Type getUnoType() {
return m_unoType;
}
/**
Returns the index of the type parameter that determines the parameterized
type of this member.
@return the index of the type parameter that determines the type of this
parameterized member; if this member is of an explicit type, or is the
member of a plain struct type, <code>-1</code> is returned
@since UDK 3.2
*/
public final int getTypeParameterIndex() {
return m_typeParameterIndex;
}
}
|
/*
* Copyright (C) 2022 Stanislav Georgiev
* https://github.com/slaviboy
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.slaviboy.weather.features.weather.di
import android.app.Application
import android.content.Context
import android.content.SharedPreferences
import androidx.room.Room
import com.slaviboy.weather.features.weather.data.local.WeatherApiResponseDatabase
import com.slaviboy.weather.features.weather.data.remote.WeatherApi
import com.slaviboy.weather.features.weather.data.repository.SettingsRepositoryImplementation
import com.slaviboy.weather.features.weather.data.repository.WeatherRepositoryImplementation
import com.slaviboy.weather.features.weather.domain.repository.SettingsRepository
import com.slaviboy.weather.features.weather.domain.repository.WeatherRepository
import com.slaviboy.weather.features.weather.domain.usecase.GetCityUseCase
import com.slaviboy.weather.features.weather.domain.usecase.GetCityUseCaseImplementation
import com.slaviboy.weather.features.weather.domain.usecase.GetWeatherUseCase
import com.slaviboy.weather.features.weather.domain.usecase.GetWeatherUseCaseImplementation
import dagger.Module
import dagger.Provides
import dagger.hilt.InstallIn
import dagger.hilt.components.SingletonComponent
import retrofit2.Retrofit
import retrofit2.converter.gson.GsonConverterFactory
import javax.inject.Singleton
@Module
@InstallIn(SingletonComponent::class)
object CityWeatherModule {
@Provides
@Singleton
fun provideGetCityWeatherUseCase(repository: WeatherRepository): GetWeatherUseCase {
return GetWeatherUseCaseImplementation(repository)
}
@Provides
@Singleton
fun provideGetCityUseCase(repository: WeatherRepository): GetCityUseCase {
return GetCityUseCaseImplementation(repository)
}
@Provides
@Singleton
fun provideCityWeatherRepository(
api: WeatherApi,
database: WeatherApiResponseDatabase
): WeatherRepository {
return WeatherRepositoryImplementation(api, database.daoWeather)
}
@Provides
@Singleton
fun provideCityWeatherDatabase(application: Application): WeatherApiResponseDatabase {
return Room.databaseBuilder(
application, WeatherApiResponseDatabase::class.java, "weather"
).createFromAsset("database/weather.db")
.build()
}
@Provides
@Singleton
fun provideSharedPreferences(application: Application): SharedPreferences {
return application.getSharedPreferences("settings", Context.MODE_PRIVATE)
}
@Provides
@Singleton
fun provideSettingsRepository(
sharedPreferences: SharedPreferences
): SettingsRepository {
return SettingsRepositoryImplementation(sharedPreferences)
}
@Provides
@Singleton
fun provideWeatherApi(): WeatherApi {
return Retrofit.Builder()
.baseUrl(WeatherApi.BASE_URL)
.addConverterFactory(GsonConverterFactory.create())
.build()
.create(WeatherApi::class.java)
}
}
|
import { XSnippetDefinition } from "../../models/app.ts";
export const testing: XSnippetDefinition = {
meta: {
title: "Testing",
},
snippets: {
desc: {
name: "describe",
body: "describe('$1', () => {\n\t$0\n})",
},
cont: {
name: "context",
body: "context('$1', () => {\n\t$0\n})",
},
it: {
name: "test (synchronous)",
body: "it('$1', () => {\n\t$0\n})",
},
ita: {
name: "test (asynchronous)",
body: "it('$1', async () => {\n\t$0\n})",
},
itc: {
name: "test (callback)",
body: "it('$1', (done) => {\n\t$0\n\tdone()\n})",
},
bf: {
name: "before test suite",
body: "before(() => {\n\t$0\n})",
},
bfe: {
name: "before each test",
body: "beforeEach(() => {\n\t$0\n})",
},
aft: {
name: "after test suite",
body: "after(() => {\n\t$0\n})",
},
afe: {
name: "after each test",
body: "afterEach(() => {\n\t$0\n})",
},
},
};
|
import "../styles/globals.css";
import type { AppProps } from "next/app";
import {
ApolloClient,
InMemoryCache,
ApolloProvider,
HttpLink,
} from "@apollo/client";
const client = new ApolloClient({
cache: new InMemoryCache(),
link: new HttpLink({ uri: "http://localhost:4000/graphql" }),
});
function MyApp({ Component, pageProps }: AppProps) {
return (
<ApolloProvider client={client}>
<Component {...pageProps} />
</ApolloProvider>
);
}
export default MyApp;
|
import pytest
from .pages.basket_page import BasketPage
from .pages.login_page import LoginPage
from .pages.product_page import ProductPage
link = "http://selenium1py.pythonanywhere.com/catalogue/coders-at-work_207/"
class TestUserAddToBasketFromProductPage:
@pytest.fixture(scope="function", autouse=True)
def setup(self, browser):
page = LoginPage(browser, link)
page.open()
page.go_to_login_page()
page.register_new_user()
page.should_be_authorized_user()
def test_user_cant_see_success_message(self, browser):
page = ProductPage(browser, link)
page.open()
page.should_not_be_success_message()
@pytest.mark.need_review
def test_user_can_add_product_to_basket(self, browser):
page = ProductPage(browser, link)
page.open()
page.add_product_to_basket()
page.should_be_thing_in_basket(page.return_book_name())
page.should_be_same_price(page.return_book_price())
@pytest.mark.parametrize('number', [0, 1, 2, 3, 4, 5, 6,
pytest.param(7, marks=pytest.mark.xfail(reason="fixing this bug right now")), 8, 9])
def test_guest_can_add_product_to_basket(browser, number):
link_param = f'{link}?promo=offer{number}'
page = ProductPage(browser, link_param)
page.open()
page.add_product_to_basket()
page.solve_quiz_and_get_code()
page.should_be_thing_in_basket(page.return_book_name())
page.should_be_same_price(page.return_book_price())
@pytest.mark.xfail
def test_guest_cant_see_success_message_after_adding_product_to_basket(browser):
page = ProductPage(browser, link)
page.open()
page.add_product_to_basket()
page.should_not_be_success_message()
def test_guest_cant_see_success_message(browser):
page = ProductPage(browser, link)
page.open()
page.should_not_be_success_message()
@pytest.mark.xfail
def test_message_disappeared_after_adding_product_to_basket(browser):
page = ProductPage(browser, link)
page.open()
page.add_product_to_basket()
page.should_be_disappeared_message()
def test_guest_should_see_login_link_on_product_page(browser):
page = ProductPage(browser, link)
page.open()
page.should_be_login_link()
def test_guest_can_go_to_login_page_from_product_page(browser):
page = ProductPage(browser, link)
page.open()
page.go_to_login_page()
def test_guest_cant_see_product_in_basket_opened_from_product_page(browser):
page = ProductPage(browser, link)
page.open()
page.go_to_basket_page()
basket_page = BasketPage(browser, browser.current_url)
basket_page.should_be_no_goods_in_basket()
basket_page.should_be_empty_message()
|
---
title: "面向对象编程思想 (二)"
date: 2013-02-17T15:51:00+08:00
tags: ["php"]
draft: false
toc: true
---
  示例:
```php
<?php
//声明一个笔记本的类
class NoteBook{
//成员属性
private $name;
private $type;
private $os;
private $work;
//构造函数:创建和初始化对象成员属性
function __construct($name,$type,$os,$work){
$this->name = $name;
$this->type = $type;
$this->os = $os;
$this->work = $work;
}
function __get($proName){
return "======>".$this->$proName."<======<br/>";
}
function __set($proName,$proValue){
echo "======>".$this->$proName = $proValue."<======<br/>";
}
function __isset($proName){
return isset($this->$proName);
}
function __unset($proName){
unset($this->$proName);
}
//成员方法
function say(){
return "<p>应用于".$this->work." - ".
$this->name." - ".
$this->type." - ".
$this->os."</p>";
}
}
$macbook = new NoteBook("MacBook Pro","MC374","Mac OS X Snow Leopard","设计");
echo $macbook->say();
echo $macbook->name;
echo $macbook->type;
echo $macbook->os;
echo $macbook->work;
echo "<hr/>";
$macbook->name = "SONY";
$macbook->type = "ZT288";
$macbook->os = "Windows 7";
$macbook->work = "娱乐";
unset($macbook->name);
echo "<hr/>";
if(isset($macbook->name)){
echo "成员属性 name 存在于 NoteBook 类中";
}else{
echo "成员属性 name 不存在于 NoteBook 类中";
}
?>
```
|
import { collection, doc, onSnapshot, updateDoc } from "firebase/firestore";
import { useEffect } from "react";
import { useDispatch, useSelector } from "react-redux";
import { allOrder, updateOrderStatus } from "../../../store/slices/order.slice";
import { db } from "../../../../firebase";
import { formatPrice } from "../../../utils/format-price";
export default function OrderList() {
const orders = useSelector((state) => state.order.orders);
const dispatch = useDispatch();
const fetchOrders = async () => {
try {
const ordersRef = collection(db, "order");
const unsubscribe = onSnapshot(ordersRef, (ordersSnapshot) => {
const ordersData = ordersSnapshot.docs.map((doc) => ({
id: doc.id,
...doc.data(),
}));
dispatch(allOrder(ordersData));
});
return unsubscribe;
} catch (error) {
console.error("Error fetching orders: ", error);
}
};
useEffect(() => {
fetchOrders();
}, []);
const handleUpdateStatus = async (orderId, newStatus) => {
try {
dispatch(updateOrderStatus({ orderId, status: newStatus }));
const orderDocRef = doc(db, "order", orderId);
await updateDoc(orderDocRef, { status: newStatus });
} catch (error) {
console.error("Error updating order status: ", error);
}
};
const sortedOrders = orders.slice().sort((a, b) => {
const statusOrder = {
"order received": 1,
pending: 2,
paid: 3,
};
return statusOrder[a.status] - statusOrder[b.status];
});
return (
<section>
<div className="flex justify-between w-full pb-4 items-center">
<h2 className="text-2xl font-bold mb-4">Order Details</h2>
</div>
<div className="overflow-y-auto max-h-96">
<table className="w-full border text-center">
<thead>
<tr className="bg-black text-white">
<th className="border p-4">Order ID</th>
<th className="border p-4">User Name</th>
<th className="border p-4">Items</th>
<th className="border p-4">Service</th>
<th className="border p-4">Total Price</th>
<th className="border p-4">Date & Time</th>
<th className="border p-4">Status</th>
<th className="border p-4">Actions</th>
</tr>
</thead>
<tbody>
{sortedOrders.map((order) => (
<tr key={order.id}>
<td className="border p-4">{order.id}</td>
<td className="border p-4">{order.userName}</td>
<td className="border p-4">
<ul>
{order.items.map((item, index) => (
<li key={index}>
{item.productName} (Quantity: {item.quantity})
</li>
))}
</ul>
</td>
<td className="border p-4">{order.service}</td>
<td className="border p-4">{formatPrice(order.totalPrice)}</td>
<td className="border p-4">{order.time} <br /> {order.date}</td>
<td className="border p-4">{order.status}</td>
<td className="border p-4">
<select className="focus:outline-none"
value={order.status}
onChange={(e) =>
handleUpdateStatus(order.id, e.target.value)
}
>
<option value="pending">Pending</option>
<option value="order received">Order Received</option>
<option value="paid">Paid</option>
</select>
</td>
</tr>
))}
</tbody>
</table>
</div>
</section>
);
}
|
import datetime
import time
import threading
from unittest.mock import patch, MagicMock
from django.db import connection
from django.test import TestCase, TransactionTestCase, tag
from django.utils import timezone
from squad.core.models import Group, ProjectStatus, PatchSource, DelayedReport
from squad.core.tasks.notification import maybe_notify_project_status
from squad.core.tasks.notification import notify_project_status
from squad.core.tasks.notification import notification_timeout
from squad.core.tasks.notification import notify_patch_build_created
from squad.core.tasks.notification import notify_patch_build_finished
from squad.core.tasks.notification import notify_delayed_report_callback
from squad.core.tasks.notification import notify_delayed_report_email
class TestNotificationTasks(TestCase):
def setUp(self):
group = Group.objects.create(slug='mygroup')
self.project1 = group.projects.create(slug='myproject1')
self.project2 = group.projects.create(slug='myproject2')
@patch("squad.core.tasks.notification.send_status_notification")
def test_notify_project_status(self, send_status_notification):
build = self.project1.builds.create(datetime=timezone.now())
environment = self.project1.environments.create(slug='env')
build.test_runs.create(environment=environment)
status = ProjectStatus.create_or_update(build)
notify_project_status(status.id)
send_status_notification.assert_called_with(status)
@patch("squad.core.tasks.notification.send_status_notification")
def test_maybe_notify_project_status(self, send_status_notification):
build = self.project1.builds.create(datetime=timezone.now())
environment = self.project1.environments.create(slug='env')
build.test_runs.create(environment=environment)
status = ProjectStatus.create_or_update(build)
maybe_notify_project_status(status.id)
send_status_notification.assert_called_with(status)
@patch("squad.core.tasks.notification.notify_patch_build_finished")
def test_maybe_notify_project_status_notify_patch_build_finished(self, notify_patch_build_finished):
build = self.project1.builds.create(datetime=timezone.now())
environment = self.project1.environments.create(slug='env')
build.test_runs.create(environment=environment)
status = ProjectStatus.create_or_update(build)
maybe_notify_project_status(status.id)
notify_patch_build_finished.delay.assert_called_with(build.id)
@patch("squad.core.tasks.notification.notify_patch_build_finished")
def test_maybe_notify_project_status_notify_patch_build_finished_active_plugin(self, notify_patch_build_finished):
build = self.project1.builds.create(datetime=timezone.now())
environment = self.project1.environments.create(slug='env')
build.test_runs.create(environment=environment)
build.pluginscratch_set.create()
status = ProjectStatus.create_or_update(build)
maybe_notify_project_status(status.id)
notify_patch_build_finished.delay.assert_not_called()
build.pluginscratch_set.all().delete()
maybe_notify_project_status(status.id)
notify_patch_build_finished.delay.assert_called_with(build.id)
@patch("squad.core.tasks.notification.send_status_notification")
def test_maybe_notify_project_status_do_not_send_dup_notification(self, send_status_notification):
build = self.project1.builds.create(datetime=timezone.now())
environment = self.project1.environments.create(slug='env')
build.test_runs.create(environment=environment)
status = ProjectStatus.create_or_update(build)
status.notified = True
status.save()
maybe_notify_project_status(status.id)
send_status_notification.assert_not_called()
@patch("django.utils.timezone.now")
@patch("squad.core.tasks.notification.send_status_notification")
@patch("squad.core.tasks.notification.maybe_notify_project_status.apply_async")
def test_maybe_notify_project_status_wait_before_notification(self, apply_async, send_status_notification, now):
self.project1.wait_before_notification = 3600 # 1 hour
self.project1.save()
# build was created half an hour ago
now.return_value = timezone.make_aware(datetime.datetime(2017, 10, 20, 10, 30, 0))
build = self.project1.builds.create(datetime=timezone.make_aware(datetime.datetime(2017, 10, 20, 10, 0, 0)))
environment = self.project1.environments.create(slug='env')
build.test_runs.create(environment=environment)
status = ProjectStatus.create_or_update(build)
maybe_notify_project_status(status.id)
send_status_notification.assert_not_called()
apply_async.assert_called_with(args=[status.id], countdown=1801)
@patch("django.utils.timezone.now")
@patch("squad.core.tasks.notification.send_status_notification")
@patch("squad.core.tasks.notification.maybe_notify_project_status.apply_async")
def test_maybe_notify_project_status_notifies_after_wait_before_notification(self, apply_async, send_status_notification, now):
self.project1.wait_before_notification = 3600 # 1 hour
self.project1.save()
# build was created more than one hour ago
now.return_value = timezone.make_aware(datetime.datetime(2017, 10, 20, 10, 30, 0))
build = self.project1.builds.create(datetime=timezone.make_aware(datetime.datetime(2017, 10, 20, 9, 0, 0)))
environment = self.project1.environments.create(slug='env')
build.test_runs.create(environment=environment)
status = ProjectStatus.create_or_update(build)
maybe_notify_project_status(status.id)
send_status_notification.assert_called_with(status)
apply_async.assert_not_called()
@patch("squad.core.tasks.notification.notification_timeout.apply_async")
def test_maybe_notify_project_status_schedule_timeout(self, apply_async):
self.project1.notification_timeout = 3600 # 1 hour
self.project1.save()
build = self.project1.builds.create(datetime=timezone.now())
environment = self.project1.environments.create(slug='env')
build.test_runs.create(environment=environment)
status = ProjectStatus.create_or_update(build)
maybe_notify_project_status(status.id)
apply_async.assert_called_with(args=[status.id], countdown=3600)
@patch("squad.core.tasks.notification.notification_timeout.apply_async")
def test_maybe_notify_project_status_schedule_timeout_not_requested(self, apply_async):
build = self.project1.builds.create(datetime=timezone.now())
environment = self.project1.environments.create(slug='env')
build.test_runs.create(environment=environment)
status = ProjectStatus.create_or_update(build)
maybe_notify_project_status(status.id)
apply_async.assert_not_called()
@patch("squad.core.tasks.notification.send_status_notification")
def test_notification_timeout(self, send_status_notification):
self.project1.notification_timeout = 3600 # 1 hour
self.project1.save()
build = self.project1.builds.create(datetime=timezone.now())
environment = self.project1.environments.create(slug='env')
build.test_runs.create(environment=environment)
status = ProjectStatus.create_or_update(build)
notification_timeout(status.id)
send_status_notification.assert_called_with(status)
@patch("squad.core.tasks.notification.send_status_notification")
def test_notification_timeout_active_plugin(self, send_status_notification):
self.project1.notification_timeout = 3600 # 1 hour
self.project1.save()
build = self.project1.builds.create(datetime=timezone.now())
environment = self.project1.environments.create(slug='env')
build.test_runs.create(environment=environment)
build.pluginscratch_set.create()
status = ProjectStatus.create_or_update(build)
notification_timeout(status.id)
send_status_notification.assert_called_with(status)
@patch("squad.core.tasks.notification.send_status_notification")
def test_notification_timeout_noop(self, send_status_notification):
self.project1.notification_timeout = 3600 # 1 hour
self.project1.save()
build = self.project1.builds.create(datetime=timezone.now())
environment = self.project1.environments.create(slug='env')
build.test_runs.create(environment=environment)
status = ProjectStatus.create_or_update(build)
status.notified = True
status.save()
notification_timeout(status.id)
send_status_notification.assert_not_called()
@patch("squad.core.tasks.notification.send_status_notification")
def test_notification_timeout_only_once(self, send_status_notification):
self.project1.notification_timeout = 3600 # 1 hour
self.project1.save()
build = self.project1.builds.create(datetime=timezone.now())
environment = self.project1.environments.create(slug='env')
build.test_runs.create(environment=environment)
status = ProjectStatus.create_or_update(build)
notification_timeout(status.id)
notification_timeout(status.id)
self.assertEqual(1, len(send_status_notification.call_args_list))
@patch("squad.core.tasks.notification.notification_timeout.apply_async")
def test_notification_timeout_only_one_task(self, notification_timeout_apply_async):
self.project1.notification_timeout = 3600 # 1 hour
self.project1.save()
build = self.project1.builds.create(datetime=timezone.now())
environment = self.project1.environments.create(slug='env')
build.test_runs.create(environment=environment)
status = ProjectStatus.create_or_update(build)
maybe_notify_project_status(status.id)
maybe_notify_project_status(status.id)
self.assertEqual(1, len(notification_timeout_apply_async.call_args_list))
# https://stackoverflow.com/a/10949616/3908350
class TestNotificationTasksRaceCondition(TransactionTestCase):
def mock_apply_async(args, countdown=None):
time.sleep(1)
@tag('skip_sqlite')
@patch("squad.core.tasks.notification.notification_timeout.apply_async", side_effect=mock_apply_async)
def test_notification_race_condition(self, notification_timeout_apply_async):
group = Group.objects.create(slug='mygroup')
project = group.projects.create(slug='myproject1', notification_timeout=1)
build = project.builds.create(datetime=timezone.now())
status = ProjectStatus.create_or_update(build)
# ref: https://stackoverflow.com/a/56584761/3908350
def thread(status_id):
maybe_notify_project_status(status_id)
connection.close()
parallel_task_1 = threading.Thread(target=thread, args=(status.id,))
parallel_task_2 = threading.Thread(target=thread, args=(status.id,))
parallel_task_1.start()
parallel_task_2.start()
parallel_task_1.join()
parallel_task_2.join()
self.assertEqual(1, notification_timeout_apply_async.call_count)
@tag('skip_sqlite')
@patch("squad.core.tasks.notification.notify_patch_build_finished.delay")
def test_maybe_notify_project_status_notify_patch_build_finished_do_not_send_dup_race_condition(self, notify_patch_build_finished):
group = Group.objects.create(slug='mygroup')
project = group.projects.create(slug='myproject1')
build = project.builds.create(datetime=timezone.now())
environment = project.environments.create(slug='env')
build.test_runs.create(environment=environment)
status = ProjectStatus.create_or_update(build)
def thread(status_id):
maybe_notify_project_status(status_id)
connection.close()
parallel_task_1 = threading.Thread(target=thread, args=(status.id,))
parallel_task_2 = threading.Thread(target=thread, args=(status.id,))
parallel_task_1.start()
parallel_task_2.start()
parallel_task_1.join()
parallel_task_2.join()
self.assertEqual(1, notify_patch_build_finished.call_count)
class TestPatchNotificationTasks(TestCase):
def setUp(self):
group = Group.objects.create(slug='mygroup')
self.project = group.projects.create(slug='myproject')
self.patch_source = PatchSource.objects.create(
name='foo',
implementation='example',
)
@patch("squad.core.models.PatchSource.get_implementation")
def test_notify_patch_build_created(self, get_implementation):
build = self.project.builds.create(
version='1',
patch_source=self.patch_source,
patch_id='0123456789',
)
plugin = MagicMock()
get_implementation.return_value = plugin
notify_patch_build_created(build.id)
plugin.notify_patch_build_created.assert_called_with(build)
@patch("squad.core.models.PatchSource.get_implementation")
def test_notify_patch_build_finished(self, get_implementation):
build = self.project.builds.create(
version='1',
patch_source=self.patch_source,
patch_id='0123456789',
)
plugin = MagicMock()
get_implementation.return_value = plugin
notify_patch_build_finished(build.id)
plugin.notify_patch_build_finished.assert_called_with(build)
class TestReportNotificationTasks(TestCase):
def setUp(self):
self.group = Group.objects.create(slug='mygroup')
self.project = self.group.projects.create(slug='myproject')
self.build = self.project.builds.create(version='1')
self.report = self.build.delayed_reports.create()
@patch('requests.Session')
def test_callback_notification(self, send_mock):
url = "https://foo.bar.com"
self.report.callback = url
self.report.save()
notify_delayed_report_callback(self.report.pk)
send_mock.assert_any_call()
report = DelayedReport.objects.get(pk=self.report.pk)
self.assertTrue(report.callback_notified)
@patch('requests.Session.send')
def test_callback_notification_sent_earlier(self, send_mock):
self.report.callback = "https://foo.bar.com"
self.report.callback_notified = True
self.report.save()
notify_delayed_report_callback(self.report.pk)
send_mock.assert_not_called()
@patch('squad.core.models.DelayedReport.send')
def test_email_notification(self, send_mock):
self.report.email_recipient = "foo@bar.com"
self.report.save()
notify_delayed_report_email(self.report.pk)
send_mock.assert_called_with()
@patch('squad.core.models.DelayedReport.send')
def test_email_notification_sent_earlier(self, send_mock):
self.report.email_recipient = "foo@bar.com"
self.report.email_recipient_notified = True
self.report.save()
notify_delayed_report_email(self.report.pk)
send_mock.assert_not_called()
|
/*
* #%L
* ICE-9 - Algo Client API
* %%
* Copyright (C) 2010 - 2015 Snowfall Systems, Inc.
* %%
* This file is part of PortfolioEffect Quant Client.
*
* PortfolioEffect Quant Client is free software: you can redistribute
* it and/or modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* PortfolioEffect Quant Client 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 PortfolioEffect Quant Client. If not, see <http://www.gnu.org/licenses/>.
* #L%
*/
package com.portfolioeffect.quant.client.message;
import org.apache.commons.lang.builder.ToStringBuilder;
import org.apache.commons.lang.builder.ToStringStyle;
import com.portfolioeffect.quant.client.message.type.EncryptMethodType;
import com.portfolioeffect.quant.client.message.type.SessionStatusType;
public class LogonResponse extends FastMessage{
private static final long serialVersionUID = -3894267039689187741L;
private final SessionStatusType sessionStatusType; // field "SessionStatus"
private final int heartbeatIntervalSec; // field "HeartBtInt"
private final EncryptMethodType encryptMethodType;
public LogonResponse(StandardHeader messageHeader, EncryptMethodType encryptMethodType,
SessionStatusType sessionStatusType, int heartbeatIntervalSec) {
super(messageHeader);
this.sessionStatusType = sessionStatusType;
this.heartbeatIntervalSec = heartbeatIntervalSec;
this.encryptMethodType = encryptMethodType;
}
public SessionStatusType getSessionStatusType() {
return sessionStatusType;
}
public int getHeartbeatIntervalSec() {
return heartbeatIntervalSec;
}
public EncryptMethodType getEncryptMethodType() {
return encryptMethodType;
}
@Override
public String toString() {
return ToStringBuilder.reflectionToString(this, ToStringStyle.MULTI_LINE_STYLE);
}
}
|
//
// $Revision: $
// $NoKeywords: $
#ifndef UTLOBJECTREFERENCE_H
#define UTLOBJECTREFERENCE_H
#ifdef _WIN32
#pragma once
#endif
#include "tier1/utlintrusivelist.h"
#include "mathlib/mathlib.h"
#pragma push_macro("GetObject")
#undef GetObject
// Purpose: class for keeping track of all the references that exist to an object. When the object
// being referenced is freed, all of the references pointing at it will become null.
//
// To Use:
// Add a DECLARE_REFERENCED_CLASS to the class that you want to use CutlReferences with.
// Replace pointers to that class with CUtlReferences.
// Check these references for null in appropriate places.
//
// NOTE : You can still happily use pointers instead of references where you want to - these
// pointers will not magically become null like references would, but if you know no one is going
// to delete the underlying object during a partcular section of code, it doesn't
// matter. Basically, CUtlReferences don't rely on every use of an object using one.
template<class T>
class CUtlReference
{
public:
FORCEINLINE CUtlReference(void)
{
m_pNext = m_pPrev = NULL;
m_pObject = NULL;
}
FORCEINLINE CUtlReference( T* pObj ) : CUtlReference()
{
AddRef( pObj );
}
FORCEINLINE CUtlReference( const CUtlReference<T>& other ) : CUtlReference()
{
if ( other.IsValid() )
{
AddRef( (T*)( other.GetObject() ) );
}
}
FORCEINLINE ~CUtlReference(void)
{
KillRef();
}
FORCEINLINE void Set(T *pObj)
{
if ( m_pObject != pObj )
{
KillRef();
AddRef( pObj );
}
}
FORCEINLINE bool IsValid( void) const
{
return ( m_pObject != NULL );
}
FORCEINLINE T* operator()(void) const
{
return m_pObject;
}
FORCEINLINE operator T*() const
{
return m_pObject;
}
FORCEINLINE T* GetObject( void ) const
{
return m_pObject;
}
FORCEINLINE T* operator->() const
{
return m_pObject;
}
FORCEINLINE CUtlReference &operator=( const CUtlReference& otherRef )
{
Set( otherRef.m_pObject );
return *this;
}
FORCEINLINE CUtlReference &operator=( T *pObj )
{
Set( pObj );
return *this;
}
FORCEINLINE bool operator==( T const *pOther ) const
{
return ( pOther == m_pObject );
}
FORCEINLINE bool operator==( T *pOther ) const
{
return ( pOther == m_pObject );
}
FORCEINLINE bool operator==( const CUtlReference& o ) const
{
return ( o.m_pObject == m_pObject );
}
FORCEINLINE bool operator!=( T const *pOther ) const
{
return ( pOther != m_pObject );
}
FORCEINLINE bool operator!=( T *pOther ) const
{
return ( pOther != m_pObject );
}
FORCEINLINE bool operator!=( const CUtlReference& o ) const
{
return ( o.m_pObject != m_pObject );
}
FORCEINLINE bool operator!=( std::nullptr_t ) const
{
return IsValid();
}
FORCEINLINE bool operator==( std::nullptr_t ) const
{
return !IsValid();
}
public:
CUtlReference *m_pNext;
CUtlReference *m_pPrev;
T *m_pObject;
private:
FORCEINLINE void AddRef( T *pObj )
{
m_pObject = pObj;
if ( pObj )
{
pObj->m_References.AddToHead( this );
}
}
FORCEINLINE void KillRef(void)
{
if ( m_pObject )
{
m_pObject->m_References.RemoveNode( this );
m_pObject = NULL;
}
}
template<typename T_> friend class CUtlReferenceVector;
};
template<class T>
class CUtlReferenceList : public CUtlIntrusiveDList<CUtlReference<T>>
{
public:
CUtlReferenceList()
{
this->RemoveAll();
}
~CUtlReferenceList( void )
{
CUtlReference<T> *i = CUtlIntrusiveDList<CUtlReference<T>>::m_pHead;
while( i )
{
CUtlReference<T> *n = i->m_pNext;
i->m_pNext = NULL;
i->m_pPrev = NULL;
i->m_pObject = NULL;
i = n;
}
CUtlIntrusiveDList<CUtlReference<T> >::m_pHead = NULL;
}
};
//-----------------------------------------------------------------------------
// Put this macro in classes that are referenced by CUtlReference
//-----------------------------------------------------------------------------
#define DECLARE_REFERENCED_CLASS( _className ) \
private: \
CUtlReferenceList<_className> m_References; \
template<class T> friend class CUtlReference;
template <class T>
class CUtlReferenceVector : public CUtlBlockVector<CUtlReference<T>>
{
using Base = CUtlBlockVector<CUtlReference<T>>;
public:
void AddToTail( T* src )
{
Base::AddToTail( src );
}
void RemoveAll()
{
for ( int i = 0; i < Base::Count(); i++ )
{
Base::Element( i ).KillRef();
}
Base::RemoveAll();
}
int Find( T* src ) const
{
return Base::FindMatch( [src]( const CUtlReference<T> & ref ) -> bool { return ref.GetObject() == src; } );
}
void FastRemove( int elem )
{
Assert( Base::IsValidIndex( elem ) );
if ( this->m_Size > 0 )
{
if ( elem != this->m_Size -1 )
{
Base::Element( elem ) = Base::Element( this->m_Size - 1 );
}
Destruct( &Base::Element( this->m_Size - 1 ) );
--this->m_Size;
}
}
bool FindAndFastRemove( T* src )
{
int elem = Find( src );
if ( elem != -1 )
{
FastRemove( elem );
return true;
}
return false;
}
void Remove( int elem )
{
Assert( Base::IsValidIndex( elem ) );
if ( this->m_Size > 0 )
{
for ( int i = elem; i < ( this->m_Size - 1 ); i++ )
{
Base::Element( i ) = Base::Element( i + 1 );
}
Destruct( &Base::Element( this->m_Size - 1 ) );
--this->m_Size;
}
}
bool FindAndRemove( T* src )
{
int elem = Find( src );
if ( elem != -1 )
{
Remove( elem );
return true;
}
return false;
}
T* operator[]( int i ) const
{
return Base::operator[]( i );
}
T* Element( int i ) const
{
return Base::Element( i );
}
private:
//
// Disallow methods of CUtlBlockVector that can cause element addresses to change, thus
// breaking assumptions of CUtlReference. If any of these becomes needed just add a safe
// implementation to the public section.
//
void RemoveMultiple( int elem, int num );
void RemoveMultipleFromHead(int num);
void RemoveMultipleFromTail(int num);
void Swap( CUtlReferenceVector< T > &vec );
void Purge();
void PurgeAndDeleteElements();
void Compact();
};
#pragma pop_macro("GetObject")
#endif
|
import { pool } from "../db.js";
export const get_personas = async (req, res) => {
try {
// Se hace la query que devuelva todos los datos de todas las personas en la base de datos.
const [result] = await pool.query(
"SELECT * FROM Persona INNER JOIN Vivienda ON Persona.id_vivienda = Vivienda.id_vivienda INNER JOIN Municipio ON Vivienda.id_municipio = Municipio.id_municipio LEFT JOIN Familia ON Persona.id_familia = Familia.id_familia"
);
res.json(result);
} catch (error) {
return res.status(500).json({ message: error.message });
}
}
export const update_persona = async (req, res) => {
try{
// Actualiza los datos recibidos dentro del json persona
const result = await pool.query(
"UPDATE Persona SET ? WHERE id_persona = ?",
[req.body.persona, req.params.id]
);
// Revisa si existe la persona en la base de datos, sino retorna informando que no existe.
if(check_existence(res, result.affectedRows, "La persona no está registrada en la base de datos.") === false){
return;
}
// Función para editar la información del hogar
update_hogar(req, res, req.params.id);
//Si existe retorna un mensaje de éxito al front.
res.status(200).json({message : "Los datos de la persona con documento "+req.params.id.toString()+" han sido modificados."});
}catch (error){
return res.status(500).json({message : error.message});
}
}
export const create_persona = async (req, res) => {
//console.log(req.body);
try{
// Se recibe el json del front
const persona = req.body.persona;
const vivienda = req.body.vivienda;
// Se crea un registro con una nueva persona
const [persona_result] = await pool.query(
"INSERT INTO Persona(documento, primer_nombre, segundo_nombre, primer_apellido, segundo_apellido, edad) VALUES (?, ?, ?, ?, ?, ?)",
[persona.documento, persona.primer_nombre, persona.segundo_nombre, persona.primer_apellido, persona.segundo_apellido, parseInt(persona.edad, 10)]
);
// Se busca la id de la nueva persona
const [new_persona] = await pool.query(
"SELECT id_persona FROM Persona WHERE documento = ?",
[persona.documento]
);
// Revisar la información del hogar
update_hogar(req, res, new_persona[0].id_persona);
res.status(201).json({ message: "¡Persona creada!" });
}catch (error){
if (error.message.includes('Duplicate') && error.message.includes('documento')) {
return res.status(400).json({ message: 'El documento ya existe' });
} else if (error.message.includes("Check constraint 'persona_chk_1' is violated.")) {
return res.status(400).json({ message: 'La edad ingresada no es válida' });
} else {
return res.status(500).json({message : error.message});
}
}
}
const update_hogar = async (req, res, id_persona) => {
try{
//Usando el nombre del municipio buscamos su id en la base de datos
var [id_municipio] = await pool.query(
"SELECT id_municipio FROM Municipio WHERE nombre_municipio = ?",
[req.body.vivienda.nombre_municipio]
);
//Se busca si existe una vivienda que tenga el minicipio y la dirección ingresada,
//es decir, si la vivienda existe en la base de datos
var [result_vivienda] = await pool.query(
"SELECT * FROM Vivienda WHERE id_municipio = ? AND direccion = ?",
[id_municipio[0].id_municipio, req.body.vivienda.direccion]
);
//console.log(result_vivienda);
//Si no existe se crea la nueva vivienda
//console.log("vivienda", result_vivienda);
//if(check_existence(res, result_vivienda.length, "") === false){
if (result_vivienda.length === 0) {
await pool.query(
"INSERT INTO Vivienda(id_municipio, direccion) VALUES (?, ?)",
[id_municipio[0].id_municipio, req.body.vivienda.direccion]
);
// Se busca la id de la nueva casa creada
const [new_vivienda] = await pool.query(
"SELECT id_vivienda FROM Vivienda WHERE direccion = ? AND id_municipio = ?",
[req.body.vivienda.direccion, id_municipio[0].id_municipio]
);
//console.log(new_vivienda);
//Usando la id de la nueva vivienda creada, se modifica el id_vivienda dentro de persona
await pool.query(
"UPDATE Persona SET id_vivienda = ? WHERE id_persona = ?",
[new_vivienda[0].id_vivienda, id_persona]
);
return;
}
//Si existe, se modifica el id_vivienda dentro de persona
await pool.query(
"UPDATE Persona SET id_vivienda = ? WHERE id_persona = ?",
[result_vivienda[0].id_vivienda, id_persona]
);
}catch (error){
return res.status(500).json({message : error.message});
}
}
export const delete_persona = async (req, res) => {
try{
// Intenta eliminar la persona con la id_persona
const [result] = await pool.query(
"DELETE FROM Persona WHERE id_persona = ?",
[req.params.id]
);
// Si no existe envía una notificación y retorna
if(check_existence(res, result.affectedRows, "La persona no se encuentra registrada en la base de datos.")===false){
return;
}
// Si existe envía un mensaje de éxito al front.
res.json({message : "La persona ha sido eliminada con éxito."});
}catch (error){
return res.status(500).json({message : error.message});
}
}
const check_existence = (res, result, message) => {
if(result === 0){
if(message.length >0){
res.json({message: message});
}
return false;
}
return true;
}
|
import React, {useEffect, useState} from 'react'
function SkillCard(props) {
const {image, title, skills} = props
const displayDevelopment = skills.development.map( (skill, index) => {
return <li key={index} className='skill-list-item'>
<img src={skill.image} alt="" />
<h4>{skill.name}</h4>
</li>
})
const displayDesign = skills.design && skills.design.map ( (skill, index) => {
return <li key={index} className='skill-list-item'>
<img src={skill.image} alt="" />
<h4>{skill.name}</h4>
</li>
})
return (
<div className='skill-card'>
<div className='skill-card-cover'>
<h1>{title}</h1>
<img src={image} alt="" />
</div>
<div className='skill-card-content'>
<div>
<h3>Development</h3>
<ul className='skill-list'>
{displayDevelopment}
</ul>
</div>
{skills.design &&
<div>
<h3>Design</h3>
<ul className='skill-list'>
{displayDesign}
</ul>
</div>
}
</div>
</div>
)
}
export default SkillCard
|
CREATE OR REPLACE FUNCTION action_on_insert()
RETURNS trigger
AS $$
DECLARE
p_sales_id integer;
p_good_id integer;
p_sales_qty integer;
v_good_name varchar(63);
v_good_price numeric(12, 2);
v_sum numeric(12, 2);
BEGIN
p_sales_id = NEW.sales_id;
p_good_id = NEW.good_id;
p_sales_qty = NEW.sales_qty;
select good_name, good_price into v_good_name, v_good_price
from goods
where goods_id = p_good_id;
v_sum = v_good_price * p_sales_qty;
if exists (
select 1
from good_sum_mart
where good_name = v_good_name)
then
update good_sum_mart
set sum_sale = sum_sale + v_sum
where good_name = v_good_name
else
insert into good_sum_mart(good_name, sum_sale)
values (v_good_name, v_sum);
end if;
RETURN NEW;
END;
$$
LANGUAGE plpgsql
VOLATILE
SET search_path = pract_functions, public
COST 100;
CREATE TRIGGER trigger_insert_sales
AFTER INSERT
ON sales
FOR EACH ROW
EXECUTE PROCEDURE action_on_insert();
|
/*reset do css*/
*{
margin: 0;
padding: 0;
box-sizing: border-box;
}
body {
/*background-image:url('../img/fundo.jpg');*/
background-image:url('../img/nfundo.jpg');
background-size: cover;
font-family: 'Source Code Pro', monospace;
height: 100vh;
font-size: 12px;
}
/*@ como se fosse um if - se a tela tiver pelo menos 400px vai carregar estes estilos */
@media (min-width: 400px){
body {
font-size: 14px;
}
}
/* breakpoint */
@media (min-width: 600px){
body {
font-size: 18px;
}
}
/* breakpoint */
@media (min-width: 1200px) {
body {
font-size: 20px;
}
}
header {
height: 50vh;
display: flex;
justify-content: center;
align-items: center;
}
.menu {
background-color: white;
position: fixed;
width: 100vw;
top: 0;
z-index: 1;
}
.menu ul {
display: Flex;
justify-content: space-around;
}
.menu li {
list-style: none;
}
.menu a {
display: block;
padding: 10px 20px;
transition: background-color 1s, color 1s;
}
.menu a:hover{
background-color:#F4A460;
color: white;
}
a {
color:#D2691E;
text-decoration: none;
}
a:hover {
text-decoration: underline;
}
//*.titulo {
transform: scale(0.2) translateY(50vh);
opacity: 0;
animation:linear 2s animacaoTitulo forwards;
} */
@keyframes animacaoTitulo {
from {
transform: scale(0.2) translateY(500ms);
opacity: 0;
}
to {
transform: scale(1) translateY(0);
opacity: 1;
}
}
.site-subtitle,
.site-title {
text-align: center;
color:#D2691E;
}
.site-title{
font-size: 3em;
font-family: 'Noto Sans JP', sans-serif;
}
.site-subtitle {
font-style: italic;
font-family: 'Roboto', sans-serif;
line-height: 1.5em;
}
.sobre,
.contato,
.portfolio{
padding: 4em;
color: rgb(37, 16, 0);
min-height: 100vh;
}
}
@media (min-width: 1200px) {
.container {
margin-right: auto;
margin-left: auto;
max-width: 1200px;
}
}
.sobre h2,
.contato h2,
.portfolio h2 {
font-family: 'Roboto', sans-serif;
margin-bottom: 1.2em;
font-size: 1.5em;
}
.sobre p {
font-family: 'Source Code Pro', monospace
color: darksalmon;
margin-bottom: 1.2em;
text-indent: 1.5em;
text-align: justify;
}
.sobre a {
color: darkred;
}
.sobre .mpic {
float: left;
margin-right: 1.2em;
}
@media (max-width: 560px) {
.sobre .mpic {
clip-path: polygon(20% 0%, 80% 0%, 100% 20%, 100% 80%, 80% 100%, 20% 100%, 0% 80%, 0% 20%);
}
}
.sobre .mpic img {
border-radius: 1%;
/*clip-path: polygon(0% 0%, 75% 0%, 100% 50%, 75% 100%, 0% 100%); */
}
.portfolio .grid {
display: grid;
gap: 2em;
}
@media (min-width:560px) {
.portfolio .grid {
grid-template-columns: 240px 240px;
}
}
@media (min-width:880px) {
.portfolio .grid {
grid-template-columns: repeat(3, 260px);
align-content: center;
justify-content: center;
height: calc (100vh- 31px - 8em);
}
}
.portfolio figure {
text-align: center;
}
.img-portfolio {
height: 190px;
width: 100%;
object-fit: cover;
object-position: center;
border-radius: 2%;
transition: transform 500ms;
}
/*.img-portfolio:hover {
transform: scale(1.2);
/*rotate rotacciona a img */
.flip-card {
height: 180px;
perspective: 1000px;
}
.flip-card:hover .card {
transform: rotateY(180deg);
}
.card {
position: relative;
transform-style: preserve-3d;
transition: transform 1s;
}
.card-front,
.card-back {
/*entando fazer a frente-verso funcionar */
backface-visibility: hidden;
left: 0;
position: absolute;
top: 0;
width: 100%;
}
.card-back {
display: flex;
align-items: center;
justify-content: center;
height: 190px;
width: 100%;
transform: rotateY(180deg);
}
.contato .icons {
text-align: center;
}
.contato a {
font-size: 2em;
transition: text-shadow 1s;
}
.contato a:active,
.contato a:hover {
text-decoration: none;
text-shadow: 0px 0px 45px coral;
/*rgba cores*/
}
|
import './Input.css'
import { useState } from 'react'
import { livros } from './../Pesquisa/dadosPesquisa'
function Input() {
const [livrosPesquisados, setLivrosPesquisados] = useState([])
const [input, setInput] = useState('')
function pesquisar(textoDigitado){
const resultadoPesquisa = livros.filter(livro => livro.nome.includes(textoDigitado))
setLivrosPesquisados(resultadoPesquisa)
setInput(textoDigitado)
if(textoDigitado == ''){
setLivrosPesquisados([])
}
}
return (
<div>
<input className='pesquisa-livro'
type='text'
placeholder='Escreva sua próxima leitura...'
onChange={(e)=> pesquisar(e.target.value)
}
/>
{ input.length == 0 ? '':livrosPesquisados?.map(
livro =>
<div className='resultado-livro'>
<p className='p'>{livro.nome}</p>
<img src={livro.src} alt={livro.nome}/>
</div>
)
}
</div>
)
}
export default Input
|
import { LucideIcon } from 'lucide-react';
import { cn } from '@/lib/utils';
import styles from './Heading.module.scss';
interface HeadingProps {
title: string;
description: string;
Icon: LucideIcon;
iconColor?: string;
iconBgColor?: string;
}
const Heading = ({
title,
description,
Icon,
iconColor,
iconBgColor,
}: HeadingProps) => (
<div className={styles.heading}>
<div className={cn(styles.iconBg, iconBgColor)}>
<Icon className={cn(styles.icon, iconColor)} />
</div>
<div>
<h2 className={styles.title}>
{title}
</h2>
<p className={styles.desc}>
{description}
</p>
</div>
</div>
);
export default Heading;
|
<template>
<li
class="data-base__item"
:class="{
'spinner-small': store.isItemLoading || isUpdating,
'loading-error': store.isItemLoadingFailed
}"
>
<div class="data-base__product admin-product">
<h3 class="data-base__name">{{ item.name }}</h3>
<span class="data-base__created"
>Создан: {{ editors.editDate(item.created) }}</span
>
<span class="data-base__changed"
>Изменен: {{ editors.editDate(item.changed) }}</span
>
<router-link
class="data-base__change-button"
:to="{ name: 'adminChangeProduct', params: { id } }"
>Изменить</router-link
>
<ul class="data-base__volume volume-block">
<li class="volume-block__item">
<div class="volume-block__body">
<span class="volume-block__header">Объем/вес</span
><span class="volume-block__header">Цена</span
><span class="volume-block__header">До скидки</span
><span class="volume-block__header">Кол-во</span>
</div>
</li>
<li
v-for="volume in item.volumes"
:key="volume.id"
class="volume-block__item"
>
<div
class="volume-block__body"
:class="{
'volume-block__body--three-items': !volume.subprice
}"
>
<span class="volume-block__volume">{{
editors.editVolumeFormat(volume.volume)
}}</span>
<div class="volume-block__price price">
<input
ref="priceInput"
@input="patch"
type="text"
class="price__input"
v-model.number="volume.price"
/>
<span class="price__currency">₽</span>
</div>
<div class="volume-block__ceil ciel">
<input
ref="priceInput"
@input="patch"
type="text"
class="ceil__input"
v-model.number="volume.subprice"
/>
<span v-if="volume.subprice" class="ceil__currency">₽</span>
</div>
<div class="volume-block__quantity quantity">
<input
@input="patch"
type="text"
class="quantity__input"
v-model.number="volume.quantity"
/>
</div>
</div>
</li>
</ul>
<button
class="data-base__button-del button-del"
type="button"
aria-label="Удалить товар"
@click.prevent="deleteItem"
>
<svg width="20" height="20" fill="currentColor">
<path
d="M17 1L1 17m16 0L1 1"
stroke="#9D9D9D"
stroke-width=".8"
></path>
</svg>
</button>
</div>
</li>
</template>
<script setup>
/* eslint-disable */
import {
defineProps,
defineEmits,
ref,
toRef,
watch,
onBeforeUnmount
} from 'vue'
import useEditors from '@/hooks/useEditors'
import useApi from '@/hooks/useApi'
import { store } from '@/store/store'
const { fetch, fetchWithParams } = useApi()
const props = defineProps(['id', 'pagination'])
const emit = defineEmits(['update:items', 'update:pagination'])
const url = `api/products/${props.id}`
const editors = useEditors()
const item = ref({})
const getData = (res) => {
item.value = res.data
}
const useFetch = async (
method,
{ func },
string = 'ItemLoading',
body = {}
) => {
fetch(method, url, body, string).then((res) => func(res))
}
useFetch('get', { func: getData })
const intervalId = setInterval(
() => useFetch('get', { func: getData }, ''),
1000
)
onBeforeUnmount(() => {
clearInterval(intervalId)
})
const deleteItem = () => {
fetchWithParams('delete', url, props.pagination, 'ItemLoading').then(
(res) => {
emit('update:pagination', res.data.pagination)
emit('update:items', res.data.items)
clearInterval(intervalId)
}
)
}
const input = ref(null)
const priceInput = ref(null)
const patch = () => {
fetch(
'patch',
`api/products/${props.id}`,
{ volumes: item.value.volumes },
`${props.id}Updating`
)
}
const isUpdating = toRef(store, `is${props.id}Updating`)
</script>
|
SSL_CTX_new():
SSL_CTX_new() is a function in the OpenSSL library that creates a new SSL_CTX object, which is used to configure SSL connections. An SSL_CTX object is essentially a configuration object that is used to specify which SSL/TLS protocol versions to use, which cipher suites to use, and other SSL-related options.
Prototype:
arduino
Copy code
SSL_CTX *SSL_CTX_new(const SSL_METHOD *method);
Parameters:
method: The SSL/TLS protocol version to use (e.g. TLSv1.2_client_method(), TLSv1_method(), etc.).
Return value:
If successful, returns a pointer to a new SSL_CTX object.
If an error occurs, returns NULL.
SSL_CTX_use_certificate_file():
SSL_CTX_use_certificate_file() is a function in the OpenSSL library that loads a certificate into an SSL_CTX object from a file in PEM format. This function is used to load the server's own certificate, which is used to authenticate the server to clients.
Prototype:
arduino
Copy code
int SSL_CTX_use_certificate_file(SSL_CTX *ctx, const char *file, int type);
Parameters:
ctx: Pointer to an SSL_CTX object.
file: Path to the certificate file in PEM format.
type: Type of certificate file (e.g. SSL_FILETYPE_PEM).
Return value:
Returns 1 if the certificate was successfully loaded, 0 if the certificate could not be loaded, or -1 if an error occurred.
SSL_CTX_use_PrivateKey_file():
SSL_CTX_use_PrivateKey_file() is a function in the OpenSSL library that loads a private key into an SSL_CTX object from a file in PEM format. This function is used to load the server's private key, which is used to decrypt data that is sent to the server.
Prototype:
arduino
Copy code
int SSL_CTX_use_PrivateKey_file(SSL_CTX *ctx, const char *file, int type);
Parameters:
ctx: Pointer to an SSL_CTX object.
file: Path to the private key file in PEM format.
type: Type of private key file (e.g. SSL_FILETYPE_PEM).
Return value:
Returns 1 if the private key was successfully loaded, 0 if the private key could not be loaded, or -1 if an error occurred.
SSL_CTX_load_verify_locations():
SSL_CTX_load_verify_locations() is a function in the OpenSSL library that loads a set of trusted CA certificates into an SSL_CTX object. This function is used to specify which CA certificates the server should use to verify the authenticity of client certificates.
Prototype:
objectivec
Copy code
int SSL_CTX_load_verify_locations(SSL_CTX *ctx, const char *CAfile, const char *CApath);
Parameters:
ctx: Pointer to an SSL_CTX object.
CAfile: Path to a file containing trusted CA certificates in PEM format.
CApath: Path to a directory containing trusted CA certificates in PEM format.
Return value:
Returns 1 if the CA certificates were successfully loaded, or 0 if an error occurred.
SSL_CTX_set_verify():
SSL_CTX_set_verify() is a function in the OpenSSL library that sets the SSL verify mode and callback function for an SSL_CTX object. This function is used to specify how the server should verify client certificates.
Prototype:
arduino
Copy code
void SSL_CTX_set_verify(SSL_CTX *ctx, int mode, int (*verify_callback)(int, X509_STORE_CTX *));
Parameters:
ctx: Pointer to an SSL_CTX object.
mode: SSL verify mode (e.g. SSL_VERIFY_PEER).
verify_callback: Pointer to a callback function that is called during the SSL handshake to verify the client certificate.
Return value:
SSL_new():
Creates a new SSL object that can be used to establish an SSL/TLS connection.
Returns a pointer to the newly created SSL object or NULL if an error occurred.
Syntax: SSL *SSL_new(SSL_CTX *ctx);
SSL_set_fd():
Associates a socket file descriptor with an SSL object.
This sets up the SSL object to read and write data to the given file descriptor.
Returns 1 on success, 0 otherwise.
Syntax: int SSL_set_fd(SSL *ssl, int fd);
SSL_connect():
Initiates an SSL/TLS handshake with a server.
The SSL/TLS handshake is a process where the client and server agree on encryption and authentication methods to use for the connection.
Returns 1 on success, 0 on failure, and a negative number if an error occurred.
Syntax: int SSL_connect(SSL *ssl);
SSL_accept():
Waits for an SSL/TLS handshake from a client.
The SSL/TLS handshake is a process where the client and server agree on encryption and authentication methods to use for the connection.
Returns 1 on success, 0 on failure, and a negative number if an error occurred.
Syntax: int SSL_accept(SSL *ssl);
SSL_read():
Receives data over an SSL/TLS connection.
Reads up to num bytes of data from the SSL/TLS connection into the buffer pointed to by buf.
Returns the number of bytes read, 0 if the connection has been closed, and a negative number if an error occurred.
Syntax: int SSL_read(SSL *ssl, void *buf, int num);
SSL_write():
Sends data over an SSL/TLS connection.
Writes up to num bytes of data from the buffer pointed to by buf to the SSL/TLS connection.
Returns the number of bytes written and a negative number if an error occurred.
Syntax: int SSL_write(SSL *ssl, const void *buf, int num);
SSL_shutdown():
Shuts down an SSL/TLS connection.
Sends a close_notify alert to the other end of the SSL/TLS connection, indicating that the connection is being terminated.
Returns 1 on success, 0 on failure, and a negative number if an error occurred.
Syntax: int SSL_shutdown(SSL *ssl);
SSL_free():
Frees an SSL object and releases any associated memory.
Syntax: void SSL_free(SSL *ssl);
SSL_CTX_free():
Frees an SSL context and releases any associated memory.
Syntax: void SSL_CTX_free(SSL_CTX *ctx);
|
import 'package:craft/components/buttons.dart';
import 'package:craft/components/text_field.dart';
import 'package:craft/data/model/facility.dart';
import 'package:craft/screens/home.dart';
import 'package:craft/screens/optimization/flow_metric_information.dart';
import 'package:flutter/material.dart';
import '../../theme/colors.dart' as craft_colors;
class FacilityInformationScreen extends StatefulWidget {
const FacilityInformationScreen({super.key});
@override
State<StatefulWidget> createState() => _FacilityInformationScreenState();
}
class _FacilityInformationScreenState extends State<FacilityInformationScreen> {
late double _deviceHeight, _deviceWidth;
final Facility facility = Facility();
// final TextEditingController _nameController = TextEditingController();
// final TextEditingController _totalAreaController = TextEditingController();
// final TextEditingController _lengthController = TextEditingController();
// final TextEditingController _breadthController = TextEditingController();
// final TextEditingController _rowsController = TextEditingController();
// final TextEditingController _columnsController = TextEditingController();
@override
void initState() {
super.initState();
}
@override
Widget build(BuildContext context) {
_deviceHeight = MediaQuery.of(context).size.height;
_deviceWidth = MediaQuery.of(context).size.width;
// var disabled = (_nameController.text.isEmpty ||
// _totalAreaController.text.isEmpty ||
// _lengthController.text.isEmpty ||
// _breadthController.text.isEmpty ||
// _rowsController.text.isEmpty ||
// _columnsController.text.isEmpty);
var disabled = (facility.name == null ||
facility.totalArea == null ||
facility.length == null ||
facility.breadth == null ||
facility.rows == null ||
facility.columns == null);
return Scaffold(
body: Container(
color: craft_colors.Colors.white,
child: SafeArea(
child: Container(
padding: EdgeInsets.only(
left: _deviceWidth * 0.05,
right: _deviceWidth * 0.05,
bottom: _deviceHeight * .02,
top: _deviceHeight * .02,
),
height: _deviceHeight,
width: _deviceWidth,
child: Column(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Column(
children: [
Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: List.generate(
3,
(index) => Expanded(
child: Container(
margin: EdgeInsets.only(right: index < 3 ? 8 : 0),
height: 12,
color: (index > 0)
? const Color(0xFFEEEEEE)
: craft_colors.Colors.primary,
),
),
),
),
const SizedBox(height: 40),
Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
const Expanded(
child: Text(
"Enter the facility information",
style: TextStyle(
color: craft_colors.Colors.primary,
fontWeight: FontWeight.bold,
fontSize: 20,
fontFamily: "SpaceGrotesk",
),
),
),
InkWell(
onTap: () => Navigator.of(context).pushAndRemoveUntil(
MaterialPageRoute(
builder: (context) => const HomeScreen(),
),
(Route<dynamic> route) => false,
),
child: Container(
decoration: BoxDecoration(
shape: BoxShape.circle,
color:
craft_colors.Colors.primary.withOpacity(.75),
),
padding: const EdgeInsets.all(4),
child: const Icon(
Icons.close,
color: craft_colors.Colors.white,
),
),
)
],
),
SizedBox(height: _deviceHeight * .05),
],
),
SizedBox(height: _deviceHeight * .025),
Expanded(
child: ListView(
children: [
FacilityInput(
// controller: _nameController,
hintText: "Enter the facility name",
autofocus: true,
onChanged: (p0) => setState(() => facility.name = p0),
),
FacilityInput(
// controller: _totalAreaController,
keyboardType: const TextInputType.numberWithOptions(
decimal: true,
),
hintText: "Enter the total area of the facility",
onChanged: (p0) => setState(
() => facility.totalArea = double.parse(p0)),
),
FacilityInput(
// controller: _lengthController,
keyboardType: const TextInputType.numberWithOptions(
decimal: true,
),
hintText: "Enter the length of each department",
onChanged: (p0) =>
setState(() => facility.length = double.parse(p0)),
),
FacilityInput(
// controller: _breadthController,
keyboardType: const TextInputType.numberWithOptions(
decimal: true,
),
hintText: "Enter the breadth of each department",
onChanged: (p0) =>
setState(() => facility.breadth = double.parse(p0)),
),
FacilityInput(
// controller: _rowsController,
keyboardType: TextInputType.number,
hintText: "Enter the number of rows",
onChanged: (p0) =>
setState(() => facility.rows = int.parse(p0)),
),
FacilityInput(
// controller: _columnsController,
keyboardType: TextInputType.number,
hintText: "Enter the number of columns",
onChanged: (p0) =>
setState(() => facility.columns = int.parse(p0)),
),
],
),
),
const SizedBox(height: 15),
defaultButton(
width: _deviceWidth,
text: "Next",
backgroundColor: disabled
? craft_colors.Colors.primary.withOpacity(.4)
: craft_colors.Colors.primary,
onPressed: () => {if (!disabled) navigate()},
)
],
),
),
),
),
);
}
void navigate() {
// facility.name = _nameController.text;
// facility.totalArea = double.parse(_totalAreaController.text);
// facility.length = double.parse(_lengthController.text);
// facility.breadth = double.parse(_breadthController.text);
// facility.rows = int.parse(_rowsController.text);
// facility.columns = int.parse(_columnsController.text);
debugPrint("$facility");
Navigator.pushNamedAndRemoveUntil(
context,
FlowMetricInformationScreen.routeName,
ModalRoute.withName('/'),
arguments: facility,
);
}
}
|
import type { AppProps } from 'next/app'
import { useState } from 'react'
import { darkTheme } from '../../stitches.config'
import { Footer } from '../components/Footer'
import { Header } from '../components/Header'
import { Container, globalStyles } from '../styles/global'
export default function App({ Component, pageProps }: AppProps) {
const [theme, setTheme] = useState('light')
const getPreferredTheme = () => {
if (window.matchMedia) {
if (window.matchMedia('(prefers-color-scheme: dark)').matches) {
return 'dark'
} else {
return 'light'
}
}
return 'light'
}
// function handleTheme() {
// setTheme(getPreferredTheme == 'light' ? darkTheme : 'light')
// }
function handleTheme() {
setTheme('light' === theme ? darkTheme : 'light')
}
return (
<body className={theme}>
<Container>
<Header />
<Component {...pageProps} />
</Container>
<button onClick={handleTheme}>Trocar</button>
<Footer />
{globalStyles()}
</body>
)
}
|
# Pattern - Stack
- Basic Stack Operations:
* Utilizing the fundamental stack operations of push, pop, and peek.
* Common problems: "Valid Parentheses," "Implement Stack using Queues."
- Minimum or Maximum Stack:
* Extending the basic stack operations to support constant-time retrieval of minimum or maximum elements.
* Common problems: "Min Stack," "Largest Rectangle in Histogram."
- Monotonic Stack:
* Maintaining a monotonically increasing or decreasing order within the stack.
* Common problems: "Daily Temperatures," "Next Greater Element II."
- Two Stacks for Functionality:
* Using two stacks to implement specific functionality or operations.
* Common problems: "Queue using Stacks," "Evaluate Reverse Polish Notation."
- Expression Parsing and Evaluation:
* Parsing and evaluating expressions using stacks for operator precedence.
* Common problems: "Evaluate Reverse Polish Notation," "Basic Calculator II."
- Tracking Indices and Positions:
* Using stacks to track indices or positions for various purposes.
* Common problems: "Remove Duplicate Letters," "Decode String."
- Balanced Parentheses and Brackets:
* Solving problems related to checking balanced parentheses or brackets.
* Common problems: "Valid Parentheses," "Longest Valid Parentheses."
- Depth and Nesting Level:
* Using stacks to track depth or nesting level of elements.
* Common problems: "Maximum Nesting Depth of Two Valid Parentheses Strings."
- Postfix Notation (Reverse Polish Notation):
* Solving problems related to postfix notation using stacks.
* Common problems: "Evaluate Reverse Polish Notation," "Basic Calculator II."
- Window or Sliding Window Operations:
* Using stacks to manage elements within a window or sliding window.
* Common problems: "Sliding Window Maximum," "Remove All Adjacent Duplicates In String."
- Reversal Using Stack:
* Reversing elements using a stack.
* Common problems: "Reverse String," "Reverse Linked List."
- Undo or Rollback Operations:
* Using stacks to implement undo or rollback operations.
* Common problems: "Online Stock Span," "Maximal Rectangle."
|
package controller
import (
"github.com/a-h/gemini"
"github.com/a-h/gemini/mux"
. "github.com/binaryphile/lilleygram/controller/shortcuts"
"github.com/binaryphile/lilleygram/helper"
"github.com/binaryphile/lilleygram/middleware"
. "github.com/binaryphile/lilleygram/must"
"github.com/binaryphile/lilleygram/opt"
"github.com/binaryphile/lilleygram/slice"
"github.com/binaryphile/lilleygram/sqlrepo"
"log"
"net/url"
"path/filepath"
"text/template"
)
type GramController struct {
baseTemplateNames []string
funcs template.FuncMap
listTemplate *Template
handler *Mux
repo sqlrepo.GramRepo
}
func NewGramController(repo sqlrepo.GramRepo) GramController {
c := GramController{
baseTemplateNames: []string{
"view/layout/base.tmpl",
"view/partial/nav.tmpl",
"view/partial/footer.tmpl",
},
funcs: template.FuncMap{
"incr": func(index int) int {
return index + 1
},
},
repo: repo,
}
fileName := "view/timeline.tmpl"
templates := append([]string{fileName}, c.baseTemplateNames...)
c.listTemplate = Must(template.New(filepath.Base(fileName)).Funcs(c.funcs).ParseFiles(templates...))
return c
}
func (c GramController) Add(writer ResponseWriter, request *Request) {
var err error
defer writeError(writer, err)
if request.URL.RawQuery == "" {
err = helper.InputPrompt(writer, "Compose your gram of up to 500 characters:")
return
}
user, _ := middleware.CertUserFromRequest(request)
gram, err := url.QueryUnescape(request.URL.RawQuery)
_, err = c.repo.Add(user.UserID, gram)
if err != nil {
return
}
err = helper.Redirect(writer, "/")
}
func (c GramController) List(writer ResponseWriter, request *Request) {
var err error
defer writeError(writer, err)
user, _ := middleware.CertUserFromRequest(request)
grams, err := c.repo.List(user.UserID)
if err != nil {
return
}
data := struct {
helper.User
Grams []helper.Gram
}{
User: user,
Grams: slice.Map(helper.GramFromModel, grams),
}
if deployEnv, ok := middleware.DeployEnvFromRequest(request); ok && deployEnv == "local" {
fileName := "view/timeline.tmpl"
templates := append([]string{fileName}, c.baseTemplateNames...)
c.listTemplate = Must(template.New(filepath.Base(fileName)).Funcs(c.funcs).ParseFiles(templates...))
}
err = c.listTemplate.Execute(writer, data)
}
func (c GramController) Handler(routes ...map[string]Handler) *Mux {
handlers := opt.OfFirst(routes).Or(c.Routes())
router := mux.NewMux()
for pattern, h := range handlers {
router.AddRoute(pattern, h)
}
return router
}
func (c GramController) Routes() map[string]Handler {
return map[string]Handler{
"/": HandlerFunc(c.List),
"/grams/add": HandlerFunc(c.Add),
"/grams/{id}/sparkle": HandlerFunc(c.Sparkle),
}
}
func (c GramController) ServeGemini(writer ResponseWriter, request *Request) {
if c.handler == nil {
c.handler = c.Handler()
}
c.handler.ServeGemini(writer, request)
}
func (c GramController) Sparkle(writer ResponseWriter, request *Request) {
var err error
defer writeError(writer, err)
user, _ := middleware.CertUserFromRequest(request)
gramID, ok := middleware.Uint64FromRequest(request, "id")
if !ok {
gemini.BadRequest(writer, request)
log.Print("no ID")
return
}
_, err = c.repo.Sparkle(gramID, user.UserID)
err = helper.Redirect(writer, "/")
}
|
import { LightClientTransport } from '@lodestar/light-client/transport'
import { getCurrentSlot } from '@lodestar/light-client/utils'
import { ForkName } from '@lodestar/params'
import { allForks, ssz } from '@lodestar/types'
import { BeaconLightClientNetwork } from './beacon.js'
import {
BeaconLightClientNetworkContentType,
LightClientBootstrapKey,
LightClientFinalityUpdateKey,
LightClientForkName,
LightClientOptimisticUpdateKey,
LightClientUpdatesByRange,
LightClientUpdatesByRangeKey,
} from './types.js'
import { Debugger } from 'debug'
import { bytesToHex, concatBytes, hexToBytes } from '@ethereumjs/util'
import { genesisData } from '@lodestar/config/networks'
import { getBeaconContentKey } from './util.js'
export class UltralightTransport implements LightClientTransport {
protocol: BeaconLightClientNetwork
logger: Debugger
constructor(protocol: BeaconLightClientNetwork) {
this.protocol = protocol
this.logger = protocol.logger.extend('LightClientTransport')
}
async getUpdates(
startPeriod: number,
count: number,
): Promise<{ version: ForkName; data: allForks.LightClientUpdate }[]> {
const range = []
this.logger(
`requesting lightClientUpdatesByRange starting with period ${startPeriod} and count ${count}`,
)
while (range.length === 0) {
const rangeKey = hexToBytes(
getBeaconContentKey(
BeaconLightClientNetworkContentType.LightClientUpdatesByRange,
LightClientUpdatesByRangeKey.serialize({
startPeriod: BigInt(startPeriod),
count: BigInt(count),
}),
),
)
let decoded
decoded = await this.protocol.findContentLocally(rangeKey)
if (decoded === undefined || bytesToHex(decoded) === '0x') {
decoded = await this.protocol.sendFindContent(
this.protocol.routingTable.random()!.nodeId,
rangeKey,
)
decoded = decoded !== undefined ? decoded.value : undefined
}
if (decoded !== undefined) {
const updateRange = LightClientUpdatesByRange.deserialize(decoded as Uint8Array)
for (const update of updateRange) {
const forkhash = update.slice(0, 4)
const forkname = this.protocol.beaconConfig.forkDigest2ForkName(
forkhash,
) as LightClientForkName
range.push({
version: forkname as ForkName,
data: ssz[forkname].LightClientUpdate.deserialize(update.slice(4)),
})
}
return range
}
}
throw new Error(`range starting with period ${startPeriod} could not be retrieved`)
}
async getOptimisticUpdate(): Promise<{
version: ForkName
data: allForks.LightClientOptimisticUpdate
}> {
let optimisticUpdate, forkname
const currentSlot = BigInt(
getCurrentSlot(this.protocol.beaconConfig, genesisData.mainnet.genesisTime),
)
this.logger(`requesting LightClientOptimisticUpdate for ${currentSlot.toString(10)}`)
// Try to get optimistic update locally
const localUpdate = await this.protocol.findContentLocally(
hexToBytes(
getBeaconContentKey(
BeaconLightClientNetworkContentType.LightClientOptimisticUpdate,
LightClientOptimisticUpdateKey.serialize({
signatureSlot: currentSlot,
}),
),
),
)
if (localUpdate !== undefined && bytesToHex(localUpdate) !== '0x') {
const forkhash = localUpdate.slice(0, 4) as Uint8Array
forkname = this.protocol.beaconConfig.forkDigest2ForkName(forkhash) as LightClientForkName
optimisticUpdate = ssz[forkname].LightClientOptimisticUpdate.deserialize(localUpdate.slice(4))
return {
version: forkname,
data: optimisticUpdate,
}
}
// Try to get optimistic update from Portal Network
const decoded = await this.protocol.sendFindContent(
this.protocol.routingTable.random()!.nodeId,
concatBytes(
new Uint8Array([BeaconLightClientNetworkContentType.LightClientOptimisticUpdate]),
LightClientOptimisticUpdateKey.serialize({
signatureSlot: currentSlot,
}),
),
)
if (decoded !== undefined) {
const forkhash = decoded.value.slice(0, 4) as Uint8Array
forkname = this.protocol.beaconConfig.forkDigest2ForkName(forkhash) as LightClientForkName
optimisticUpdate = ssz[forkname].LightClientOptimisticUpdate.deserialize(
(decoded.value as Uint8Array).slice(4),
)
return {
version: forkname,
data: optimisticUpdate,
}
}
// TODO: Determine if there is a better process for handling where no update is retrieved
// since Portal Network only returns optimistic updates by slot (maybe backstep one slot at a time until one
// is retrieved?)
throw new Error('optimistic update could not be retrieved')
}
async getFinalityUpdate(): Promise<{
version: ForkName
data: allForks.LightClientFinalityUpdate
}> {
let finalityUpdate, forkname
const currentFinalitySlot = this.protocol.lightClient?.getFinalized().beacon.slot
if (currentFinalitySlot === undefined) {
throw new Error('Light Client is not running or no Finality Update is available')
}
const currentSlot = BigInt(
getCurrentSlot(this.protocol.beaconConfig, genesisData.mainnet.genesisTime),
)
// Ask for the next possible finality update (or current finality slot if next would still be in the future)
const nextFinalitySlot =
currentSlot >= currentFinalitySlot + 32
? BigInt(currentFinalitySlot + 32)
: BigInt(currentFinalitySlot)
this.logger(`requesting LightClientFinalityUpdate for ${nextFinalitySlot.toString(10)}`)
// Try retrieving finality update locally
const localUpdate = await this.protocol.findContentLocally(
hexToBytes(
getBeaconContentKey(
BeaconLightClientNetworkContentType.LightClientFinalityUpdate,
LightClientFinalityUpdateKey.serialize({
finalitySlot: nextFinalitySlot,
}),
),
),
)
if (localUpdate !== undefined && bytesToHex(localUpdate) !== '0x') {
const forkhash = localUpdate.slice(0, 4) as Uint8Array
forkname = this.protocol.beaconConfig.forkDigest2ForkName(forkhash) as LightClientForkName
finalityUpdate = ssz[forkname].LightClientFinalityUpdate.deserialize(localUpdate.slice(4))
return {
version: forkname,
data: finalityUpdate,
}
}
// Try to get finality update from Portal Network
const decoded = await this.protocol.sendFindContent(
this.protocol.routingTable.random()!.nodeId,
concatBytes(
new Uint8Array([BeaconLightClientNetworkContentType.LightClientFinalityUpdate]),
LightClientFinalityUpdateKey.serialize({ finalitySlot: nextFinalitySlot }),
),
)
if (decoded !== undefined) {
const forkhash = decoded.value.slice(0, 4) as Uint8Array
forkname = this.protocol.beaconConfig.forkDigest2ForkName(forkhash) as LightClientForkName
finalityUpdate = ssz[forkname].LightClientFinalityUpdate.deserialize(
(decoded.value as Uint8Array).slice(4),
)
return {
version: forkname,
data: finalityUpdate,
}
}
// TODO: Determine best method for finding "best" update
throw new Error('LightClientFinalityUpdate could not be retrieved')
}
async getBootstrap(
blockRoot: string,
): Promise<{ version: ForkName; data: allForks.LightClientBootstrap }> {
let forkname, bootstrap
const localBootstrap = await this.protocol.findContentLocally(
hexToBytes(
getBeaconContentKey(
BeaconLightClientNetworkContentType.LightClientBootstrap,
LightClientBootstrapKey.serialize({ blockHash: hexToBytes(blockRoot) }),
),
),
)
if (localBootstrap !== undefined && localBootstrap.length !== 0) {
this.logger('Found LightClientBootstrap locally. Initializing light client...')
try {
forkname = this.protocol.beaconConfig.forkDigest2ForkName(
localBootstrap.slice(0, 4),
) as LightClientForkName
bootstrap = ssz[forkname].LightClientBootstrap.deserialize(localBootstrap.slice(4))
} catch (err) {
this.logger('Error loading local bootstrap error')
this.logger(err)
}
} else {
const peers = this.protocol.routingTable.nearest(this.protocol.enr.nodeId, 5)
let forkname
this.logger(`requesting lightClientBootstrap for trusted block root ${blockRoot}`)
// Try to get bootstrap from Portal Network
for (const peer of peers) {
const decoded = await this.protocol.sendFindContent(
peer.nodeId,
concatBytes(
new Uint8Array([BeaconLightClientNetworkContentType.LightClientBootstrap]),
LightClientBootstrapKey.serialize({ blockHash: hexToBytes(blockRoot) }),
),
)
if (decoded !== undefined) {
const forkhash = decoded.value.slice(0, 4) as Uint8Array
forkname = this.protocol.beaconConfig.forkDigest2ForkName(forkhash) as LightClientForkName
bootstrap = ssz[forkname].LightClientBootstrap.deserialize(
(decoded.value as Uint8Array).slice(4),
)
break
}
}
}
if (bootstrap === undefined) {
throw new Error('could not retrieve bootstrap from Portal Network')
}
return {
version: forkname as ForkName,
data: bootstrap,
}
}
onOptimisticUpdate(
handler: (optimisticUpdate: allForks.LightClientOptimisticUpdate) => void,
): void {
this.protocol.on('ContentAdded', (contentKey, contentType, content) => {
if (contentType === BeaconLightClientNetworkContentType.LightClientOptimisticUpdate) {
const value = hexToBytes(content)
const forkhash = value.slice(0, 4) as Uint8Array
const forkname = this.protocol.beaconConfig.forkDigest2ForkName(
forkhash,
) as LightClientForkName
try {
handler(
ssz[forkname].LightClientOptimisticUpdate.deserialize((value as Uint8Array).slice(4)),
)
} catch (err) {
this.logger('something went wrong trying to process Optimistic Update')
this.logger(err)
}
}
})
}
onFinalityUpdate(handler: (finalityUpdate: allForks.LightClientFinalityUpdate) => void): void {
this.protocol.on('ContentAdded', (contentKey, contentType, content) => {
if (contentType === BeaconLightClientNetworkContentType.LightClientFinalityUpdate) {
const value = hexToBytes(content)
const forkhash = value.slice(0, 4) as Uint8Array
const forkname = this.protocol.beaconConfig.forkDigest2ForkName(
forkhash,
) as LightClientForkName
try {
handler(
ssz[forkname].LightClientFinalityUpdate.deserialize((value as Uint8Array).slice(4)),
)
} catch (err) {
this.logger('something went wrong trying to process Finality Update')
this.logger(err)
}
}
})
}
}
|
import React, { StrictMode } from "react";
import ReactDOM from "react-dom/client";
import "./index.css";
import WordSearchMaker from "./wordsearchmaker";
import WordSearchGame from "./wordsearchplay";
import "bootstrap/dist/css/bootstrap.min.css";
import { BrowserRouter, Navigate, Route, Routes } from "react-router-dom";
import Home from "./homepage";
import Header from "./header";
/*
function Header() {
return (
<header className="nav-header">
<nav className="nav-top" style={{ display: "flex" }}>
<h1 onClick={() => { window.location.href = "https://zabzabdoda.com/" }} style={{ cursor: "pointer" }} className="nav-items">Word Search</h1>
</nav>
</header>
);
}*/
const root = ReactDOM.createRoot(document.getElementById("root"));
root.render(
<StrictMode>
<BrowserRouter>
<Header />
<Routes>
<Route path="/" element={<Home />} />
<Route path="/create" element={<WordSearchMaker />} />
<Route path="/play/:state" element={<WordSearchGame data-bs-theme="dark" />} />
<Route path="*" element={<Navigate to="/" replace />} />
</Routes>
</BrowserRouter>
</StrictMode>
);
|
// lib for inputs and outputs
#include <Ticker.h>
// Relay para encendido de la valvula solenoide para el riego
#define RELAY_PIN D1
#define HORA_EN_SEGUNDOS 3600
Ticker ticker_cada_seg;
// 10 min encendido
int riego_segs = HORA_EN_SEGUNDOS / 6;
// cada 2 hora
int espera_segs = HORA_EN_SEGUNDOS * 2;
// remain time for next riego state
int remain_riego_segs = riego_segs;
// Riego state
bool riego_state = false;
void turn_off_riego()
{
riego_state = false;
remain_riego_segs = espera_segs;
// turn off the RELAY
digitalWrite(RELAY_PIN, LOW); // turn the RELAY off (LOW is the voltage level)
digitalWrite(LED_BUILTIN, LOW); // Turn the LED on by making the voltage LOW (active low on the ESP-01)
}
void turn_on_riego()
{
riego_state = true;
remain_riego_segs = riego_segs;
// turn on the RELAY
digitalWrite(RELAY_PIN, HIGH); // turn the RELAY on (HIGH is the voltage level)
digitalWrite(LED_BUILTIN, HIGH); // Turn the LED off (Note that HIGH is the voltage level: active low)
}
// return remain time for next riego state en minutos
float get_remain_riego_segs()
{
return remain_riego_segs;
}
// set riego times
void set_riego_config(int horaEncendido, int minEncendido, int segEncendido,
int horaApagado, int minApagado, int segApagado)
{
riego_segs = (horaEncendido * HORA_EN_SEGUNDOS) + (minEncendido * 60) + segEncendido;
espera_segs = (horaApagado * HORA_EN_SEGUNDOS) + (minApagado * 60) + segApagado;
}
int get_horas_restantes()
{
return remain_riego_segs / HORA_EN_SEGUNDOS;
}
int get_minutos_restantes()
{
return (int(remain_riego_segs) % HORA_EN_SEGUNDOS) / 60;
}
int get_segundos_restantes()
{
return (int(remain_riego_segs) % HORA_EN_SEGUNDOS) % 60;
}
// get riego times
String riego_config_str()
{
String riego_config = "Encendido: ";
riego_config += String(riego_segs / HORA_EN_SEGUNDOS) + ":";
riego_config += String((int(riego_segs) % HORA_EN_SEGUNDOS) / 60) + ":";
riego_config += String((int(riego_segs) % HORA_EN_SEGUNDOS) % 60);
riego_config += " Apagado: ";
riego_config += String(espera_segs / HORA_EN_SEGUNDOS) + ":";
riego_config += String((int(espera_segs) % HORA_EN_SEGUNDOS) / 60) + ":";
riego_config += String((int(espera_segs) % HORA_EN_SEGUNDOS) % 60);
return riego_config;
}
void timers_setup()
{
// timer to save remain time for next riego state
ticker_cada_seg.attach(1, []() {
remain_riego_segs--;
if (remain_riego_segs <= 0)
{
if (riego_state)
{
turn_off_riego();
}
else
{
turn_on_riego();
}
}
});
}
void perifericos_setup()
{
pinMode(LED_BUILTIN, OUTPUT); // Initialize the LED_BUILTIN pin as an output
pinMode(RELAY_PIN, OUTPUT); // Initialize the RELAY_PIN pin as an output
// RELAY starts on
turn_on_riego();
timers_setup();
}
|
#!/usr/bin/env python
# coding: utf-8
# In[47]:
#%%writefile seg.py
import streamlit as st
import tensorflow as tf
import segmentation_models as sm
from tensorflow.keras.preprocessing import image
from PIL import Image, ImageOps
import pandas as pd
import numpy as np
import os
os.environ["SM_FRAMEWORK"] = "tf.keras"
st.markdown(
f"""
<style>
.stApp {{
background-image: url("https://images.pexels.com/photos/1261728/pexels-photo-1261728.jpeg");
background-attachment: fixed;
background-size: cover
}}
</style>
""",
unsafe_allow_html=True
)
html_temp = """
<div style="background-color:pink ;padding:6px;">
<h2 style="color:white;text-align:center;">CNN based automated segmentation of urinary stones from ureteroscopy images using efficientnet based U-Net</h2>
</div>
"""
st.markdown(html_temp,unsafe_allow_html=True)
st.write(' ')
st.write(' ')
html_temp1 = """
<div style="background-color:#ABBAEA ;padding:6px;">
<h2 style="color:white;text-align:center;">CENTER OF EXCELLENCE IN MEDICAL IMAGING</h2>
</div>
"""
st.markdown(html_temp1,unsafe_allow_html=True)
activities=['SECTION 1-Introduction','SECTION 2-Deep learning tool for segmentation of urinary stones using ureteroscopy images','SECTION 3- About the team']
option=st.sidebar.selectbox('choose the options displayed below',activities)
st.subheader(option)
if option=='SECTION 1-Introduction':
st.write('this project is about the development and deployment of a deep learning algorithm for the segmentation of urinary stones from ureteroscopy images.')
st.subheader('Background')
st.write('Urinary stones is a serious medical issue that affects 12% of the global population. Ureteroscopy is one such standard diagnostic procedure for urinary stones. Targeting stones during ureteroscopy is challenging due to poor image quality, floating debris, and severe occlusions in the endoscopy video. Automated segmentation and localization of the stone fragments is one potential approach and can improvise the diagnostic accuracy while conserving time. Deep learning networks have proven to perform well in automated segmentation tasks.')
st.subheader('Objective')
st.write('To develop an algorithm for automated segmentation of urinary stones using deep neural networks.')
st.subheader('Materials and Methods')
st.write('1020 ureteroscopy frames containing urinary stones were collected retrospectively for this work. The ground truth annotations for the urinary stones were manually marked by experts. The proposed architecture for automated segmentation is a EfficientNetB2 based U-Net. The training dataset comprises of 80% of data and the remaining 20% was allotted to validation. The trained algorithm was deployed into a user interface for real time diagnostic usage. The proposed user interface segments the region of urinary stone and also identifies the composition material of the stone along with its severity.')
st.subheader('Results')
st.write('The proposed architecture produced 90% dice score, 93% jaccard score, 96% precision and 87% recall on testing data.')
st.subheader('Conclusion')
st.write('Hence a deep learning algorithm and a real time user interface has been developed. Urologists may be able to employ the proposed algorithm in real time for dynamic and effective segmentation of urinary stones to support their surgical and medical decision-making skills.')
elif option=='SECTION 2-Deep learning tool for segmentation of urinary stones using ureteroscopy images':
def load_model():
model=tf.keras.models.load_model(r"urine-stone-seg-model.h5",compile=False)
return model
with st.spinner('Model is being loaded..'):
model=load_model()
file = st.file_uploader("Please upload any image from the local machine in case of computer or upload camera image in case of mobile.", type=["jpg", "png","jpeg"])
st.set_option('deprecation.showfileUploaderEncoding', False)
if file is None:
st.text("Please upload an image file within the allotted file size")
else:
img = Image.open(file)
size = (224,224)
image = ImageOps.fit(img, size, Image.ANTIALIAS)
st.image(image)
imag = np.asarray(image)
imag=imag/255
imaga = np.expand_dims(imag,axis=0)
if st.button('Segment'):
predictions = model.predict(imaga)
predictions=np.reshape(predictions,(224,224))
a=np.unique(predictions)
b=np.sqrt(len(a)/(3.14))
st.write('predicted mask')
st.image(predictions)
st.markdown("""
<div style="background-color: green;padding:3px;border: 3px solid;">
<h2 style="color:white;text-align:center;">Predicted stone is of material- Calcium oxalate!!</h2>
</div>
""" ,unsafe_allow_html=True)
st.subheader('Area of the stone:- '+str(len(a)*0.2645833333)+' mm' +' or '+str(len(a)*0.02645833333)+' cm')
st.subheader('Diameter of the stone:- '+str(2*b*0.2645833333)+' mm'+' or '+str(2*b*0.02645833333)+' cm')
st.subheader('Radius of the stone:- '+str(b*0.2645833333)+' mm'+' or '+str(b*0.02645833333)+' cm')
elif option=='SECTION 3- About the team':
st.markdown("""
<div style="background-color: rgb(43, 204, 166);padding:3px;border: 3px solid;">
<h2 style="color:white;text-align:center;">V.A.Sairam, Department of Biomedical Engineering, Rajalakshmi Engineering College, Chennai, India</h2>
</div>
""" ,unsafe_allow_html=True)
st.write(' ')
st.write(' ')
st.markdown("""
<div style="background-color: rgb(192, 219, 103);padding:3px;border: 3px solid;">
<h2 style="color:white;text-align:center;">G.Lakshmipriya, Department of Biomedical Engineering, Rajalakshmi Engineering College, Chennai, India</h2>
</div>
""" ,unsafe_allow_html=True)
st.write(' ')
st.write(' ')
st.markdown("""
<div style="background-color: rgb(230, 149, 213);padding:3px;border: 3px solid;">
<h2 style="color:white;text-align:center;">Jeffi Catherine, Department of Biomedical Engineering, Rajalakshmi Engineering College, Chennai, India</h2>
</div>
""" ,unsafe_allow_html=True)
st.write(' ')
st.write(' ')
st.markdown("""
<div style="background-color: rgb(219, 103, 165);padding:3px;border: 3px solid;">
<h2 style="color:white;text-align:center;">M Malathi, Department of Biomedical Engineering, Rajalakshmi Engineering College, Chennai, India</h2>
</div>
""" ,unsafe_allow_html=True)
st.write(' ')
st.write(' ')
st.markdown("""
<div style="background-color: rgb(252, 172, 73);padding:3px;border: 3px solid;">
<h2 style="color:white;text-align:center;">K S Keerthana, Department of Biomedical Engineering, Rajalakshmi Engineering College, Chennai, India</h2>
</div>
""" ,unsafe_allow_html=True)
st.write(' ')
st.write(' ')
st.subheader('Mentors')
st.markdown("""
<div style="background-color: green;padding:3px;border: 3px solid;">
<h2 style="color:white;text-align:center;">Dr.S.Rajkumar, Head of the Department, Department of Biomedical Engineering, Rajalakshmi Engineering College, Chennai, India</h2>
</div>
""" ,unsafe_allow_html=True)
st.write(' ')
st.write(' ')
st.markdown("""
<div style="background-color: green;padding:3px;border: 3px solid;">
<h2 style="color:white;text-align:center;">Dr.V.Sapthagirivasan, Capegemini Technology Sevices Limited India</h2>
</div>
""" ,unsafe_allow_html=True)
st.write(' ')
st.write(' ')
st.write('https://www.linkedin.com/in/sairamadithya')
st.write('https://github.com/sairamadithya')
st.write('https://medium.com/@sairamadithya2002')
st.write('https://www.quora.com/profile/Sairam-Adithya')
|
import React from "react"
import userEvent from "@testing-library/user-event"
import { GraphQLError } from "graphql"
import { act, render, screen, waitFor } from "testing"
import Commits, { GET_COMMITS } from "./Commits"
test("renders", async () => {
render(<Commits />, {
withRouter: true,
})
await waitFor(() => {
expect(screen.getAllByText(/Hello world/i)).toBeTruthy()
})
})
test("renders branch", async () => {
render(<Commits />, {
path: "/:organisationName/:workspaceName/reports/:type/:owner/:repo",
route: "/org/demo/reports/github/owner/repo?branch=aBranch",
})
await waitFor(() => {
expect(screen.getAllByText(/Hello world/i)).toBeTruthy()
})
})
test("row click", async () => {
const user = userEvent.setup()
const { container } = render(<Commits />, {
path: "/:organisationName/:workspaceName/reports/:type/:owner/:repo",
route: "/org/demo/reports/github/owner/repo",
routes: [
"/:organisationName/:workspaceName/reports/:type/:owner/:repo/commits/:reference",
],
})
await waitFor(() => {
expect(screen.getAllByText(/Hello world/i)).toBeTruthy()
})
await act(
// eslint-disable-next-line testing-library/no-container, testing-library/no-node-access
async () => await user.click(container.querySelectorAll("tbody > tr")[0])
)
expect(screen.getByText("New Page")).toBeInTheDocument()
})
test("not found", async () => {
const mocks = [
{
request: {
query: GET_COMMITS,
variables: {
organisationName: "org",
workspaceName: "demo",
type: "github",
owner: "owner",
repo: "repo",
},
},
result: {
data: {
workspace: {
id: "1",
repository: null,
},
},
},
},
]
render(<Commits />, {
mocks,
path: "/:organisationName/:workspaceName/reports/:type/:owner/:repo",
route: "/org/demo/reports/github/owner/repo",
})
await waitFor(() => {
expect(screen.getByText("Page not found")).toBeInTheDocument()
})
})
test("error", async () => {
const mocks = [
{
request: {
query: GET_COMMITS,
variables: {
organisationName: "org",
workspaceName: "demo",
type: "github",
owner: "owner",
repo: "repo",
},
},
result: {
errors: [new GraphQLError("Error!")],
},
},
]
render(<Commits />, {
mocks,
path: "/:organisationName/:workspaceName/reports/:type/:owner/:repo",
route: "/org/demo/reports/github/owner/repo",
})
await waitFor(() => {
expect(screen.getByText("Error!")).toBeInTheDocument()
})
})
|
import { SingleAbstract } from '../singleAbstract';
import * as helper from './helper';
import { NotAutenticatedError, UrlNotSupportedError } from '../Errors';
import { point100 } from '../ScoreMode/point100';
import { point10 } from '../ScoreMode/point10';
import { smiley3 } from '../ScoreMode/smiley3';
import { stars5 } from '../ScoreMode/stars5';
import { point100decimal } from '../ScoreMode/point100decimal';
export class Single extends SingleAbstract {
constructor(protected url: string) {
super(url);
this.logger = con.m(this.shortName, '#3db4f2');
return this;
}
private animeInfo: any;
private displayUrl = '';
shortName = 'AniList';
authenticationUrl =
'https://anilist.co/api/v2/oauth/authorize?client_id=1487&response_type=token';
protected handleUrl(url) {
if (url.match(/anilist\.co\/(anime|manga)\/\d*/i)) {
this.type = utils.urlPart(url, 3) === 'anime' ? 'anime' : 'manga';
this.ids.ani = Number(utils.urlPart(url, 4));
return;
}
if (url.match(/myanimelist\.net\/(anime|manga)\/\d*/i)) {
this.type = utils.urlPart(url, 3) === 'anime' ? 'anime' : 'manga';
this.ids.mal = Number(utils.urlPart(url, 4));
return;
}
throw new UrlNotSupportedError(url);
}
getCacheKey() {
return this.getKey(['ANILIST']);
}
getPageId() {
return this.ids.ani;
}
_getStatus() {
return parseInt(helper.statusTranslate[this.animeInfo.mediaListEntry.status]);
}
_setStatus(status) {
this.animeInfo.mediaListEntry.status = helper.statusTranslate[status];
}
_getScore() {
if (Number(this.animeInfo.mediaListEntry.score) === 0) return 0;
const score = Math.round(Number(this.animeInfo.mediaListEntry.score) / 10);
if (score === 0) return 1;
return score;
}
_setScore(score) {
this.animeInfo.mediaListEntry.score = score * 10;
}
_getAbsoluteScore() {
return Number(this.animeInfo.mediaListEntry.score);
}
_setAbsoluteScore(score) {
this.animeInfo.mediaListEntry.score = Number(score);
}
_getEpisode() {
return this.animeInfo.mediaListEntry.progress;
}
_setEpisode(episode) {
this.animeInfo.mediaListEntry.progress = parseInt(`${episode}`);
}
_getVolume() {
return this.animeInfo.mediaListEntry.progressVolumes;
}
_setVolume(volume) {
this.animeInfo.mediaListEntry.progressVolumes = volume;
}
_getTags() {
let tags = this.animeInfo.mediaListEntry.notes;
if (tags === null || tags === 'null') tags = '';
return tags;
}
_setTags(tags) {
this.animeInfo.mediaListEntry.notes = tags;
}
_getTitle() {
return this.animeInfo.title.userPreferred;
}
_getTotalEpisodes() {
const eps = this.animeInfo.episodes ? this.animeInfo.episodes : this.animeInfo.chapters;
if (eps === null) return 0;
return eps;
}
_getTotalVolumes() {
const vol = this.animeInfo.volumes;
if (!vol) return 0;
return vol;
}
_getDisplayUrl() {
return this.displayUrl !== '' && this.displayUrl !== null ? this.displayUrl : this.url;
}
_getImage() {
return this.animeInfo.coverImage.large;
}
_getRating() {
return Promise.resolve(this.animeInfo.averageScore);
}
async _update() {
let selectId = this.ids.mal;
let selectQuery = 'idMal';
if (Number.isNaN(this.ids.mal)) {
selectId = this.ids.ani;
selectQuery = 'id';
}
const query = `
query ($id: Int, $type: MediaType) {
Media (${selectQuery}: $id, type: $type) {
id
idMal
siteUrl
episodes
chapters
volumes
averageScore
coverImage{
large
}
title {
userPreferred
}
mediaListEntry {
id
status
progress
progressVolumes
score(format: POINT_100)
repeat
notes
}
}
}
`;
const variables = {
id: selectId,
type: this.type!.toUpperCase(),
};
this._authenticated = true;
return this.apiCall(query, variables)
.catch(e => {
if (e instanceof NotAutenticatedError) {
this._authenticated = false;
return this.apiCall(query, variables, false);
}
throw e;
})
.then(json => {
this.logger.log('[SINGLE]', 'Data', json);
this.animeInfo = json.data.Media;
this.ids.ani = this.animeInfo.id;
if (Number.isNaN(this.ids.mal) && this.animeInfo.idMal) {
this.ids.mal = this.animeInfo.idMal;
}
this.displayUrl = this.animeInfo.siteUrl;
this._onList = true;
if (this.animeInfo.mediaListEntry === null) {
this._onList = false;
this.animeInfo.mediaListEntry = {
notes: '',
progress: 0,
progressVolumes: 0,
repeat: 0,
score: 0,
status: 'PLANNING',
};
}
if (!this._authenticated) throw new NotAutenticatedError('Not Authenticated');
});
}
async _sync() {
let query = `
mutation ($mediaId: Int, $status: MediaListStatus, $progress: Int, $scoreRaw: Int, $notes: String) {
SaveMediaListEntry (mediaId: $mediaId, status: $status, progress: $progress, scoreRaw: $scoreRaw, notes: $notes) {
id
status
progress
}
}
`;
const variables = {
mediaId: this.ids.ani,
status: this.animeInfo.mediaListEntry.status,
progress: this.animeInfo.mediaListEntry.progress,
scoreRaw: this.animeInfo.mediaListEntry.score,
notes: this.animeInfo.mediaListEntry.notes,
volumes: null,
};
if (this.type === 'manga') {
query = `
mutation ($mediaId: Int, $status: MediaListStatus, $progress: Int, $scoreRaw: Int, $notes: String, $volumes: Int) {
SaveMediaListEntry (mediaId: $mediaId, status: $status, progress: $progress, scoreRaw: $scoreRaw, notes: $notes, progressVolumes: $volumes) {
id
status
progress
progressVolumes
}
}
`;
variables.volumes = this.animeInfo.mediaListEntry.progressVolumes;
}
return this.apiCall(query, variables).then(json => {
if (json && json.data && json.data.SaveMediaListEntry && json.data.SaveMediaListEntry.id) {
this.animeInfo.mediaListEntry.id = json.data.SaveMediaListEntry.id;
}
return json;
});
}
protected apiCall(query, variables, authentication = true) {
return helper.apiCall(query, variables, authentication);
}
public getScoreMode() {
switch (api.settings.get('anilistOptions').scoreFormat) {
case 'POINT_100':
return point100;
case 'POINT_3':
return smiley3;
case 'POINT_5':
return stars5;
case 'POINT_10_DECIMAL':
return point100decimal;
default:
return point10;
}
}
_delete() {
const query = `
mutation ($mediaId: Int) {
DeleteMediaListEntry(id: $mediaId) {
deleted
}
}
`;
const variables = {
mediaId: this.animeInfo.mediaListEntry.id,
};
return this.apiCall(query, variables);
}
}
|
'use client';
import React, { useRef, useEffect, useState } from 'react';
import { supabase } from './supabase';
import TypingEffect from './TypingEffect';
interface CanvasDrawerProps {
width?: number;
height?: number;
}
const CanvasDrawer: React.FC<CanvasDrawerProps> = (props) => {
const canvasRef = useRef<HTMLCanvasElement | null>(null);
const [drawing, setDrawing] = useState(false);
const [context, setContext] = useState<CanvasRenderingContext2D | null>(null);
const [color, setColor] = useState('#f87171');
const [dimensions, setDimensions] = useState({
width: props.width,
height: props.height,
});
// set as blank string and then getChillPrompt()
const [prompt, setPrompt] = useState('draw a cat');
let currentColor = color;
const drawingColors = ['#34d399', '#f87171', '#a3e635'];
useEffect(() => {
setDimensions({
width: props.width || window.innerWidth * 0.9,
height: props.height || window.innerHeight * 0.6,
});
}, [props.width, props.height]);
useEffect(() => {
if (canvasRef.current) {
const renderCtx = canvasRef.current.getContext('2d');
if (renderCtx) {
setContext(renderCtx);
}
}
}, [context]);
const getCoordinates = (
e: React.MouseEvent<HTMLCanvasElement> | React.TouchEvent<HTMLCanvasElement>
) => {
const canvas = canvasRef.current!;
const rect = canvas.getBoundingClientRect();
const x =
'clientX' in e ? e.clientX - rect.left : e.touches[0].clientX - rect.left;
const y =
'clientY' in e ? e.clientY - rect.top : e.touches[0].clientY - rect.top;
return { x, y };
};
const startDrawing = (
e: React.MouseEvent<HTMLCanvasElement> | React.TouchEvent<HTMLCanvasElement>
) => {
if (!context) return;
const { x, y } = getCoordinates(e);
setDrawing(true);
context.beginPath();
context.moveTo(x, y);
context.lineJoin = 'round';
context.lineCap = 'round';
};
const draw = (
e: React.MouseEvent<HTMLCanvasElement> | React.TouchEvent<HTMLCanvasElement>
) => {
if (!drawing || !context) return;
const { x, y } = getCoordinates(e);
context.lineTo(x, y);
context.strokeStyle = color;
context.lineWidth = 5;
context.stroke();
};
const stopDrawing = () => {
setDrawing(false);
};
const clearCanvas = () => {
if (!context) return;
context.clearRect(
0,
0,
dimensions.width || canvasRef.current!.clientWidth,
dimensions.height || canvasRef.current!.clientHeight
);
};
const saveCanvas = () => {
if (!canvasRef.current) return;
const tempCanvas = document.createElement('canvas');
if (dimensions.width && dimensions.height && tempCanvas) {
tempCanvas.width = dimensions.width;
tempCanvas.height = dimensions.height;
const tempContext = tempCanvas.getContext('2d');
if (!tempContext) return;
tempContext.fillStyle = 'black';
tempContext.fillRect(0, 0, dimensions.width, dimensions.height);
tempContext.drawImage(canvasRef.current, 0, 0);
const dataURL = tempCanvas.toDataURL('image/png');
// Create a download link and trigger the download
const link = document.createElement('a');
link.href = dataURL;
link.download = 'canvas_drawing.png';
document.body.appendChild(link);
link.click();
document.body.removeChild(link);
uploadCanvasToSupabase(tempCanvas, prompt);
}
};
async function uploadCanvasToSupabase(
canvas: HTMLCanvasElement,
prompt: string
): Promise<void> {
const blob = await new Promise<Blob>((resolve) => {
canvas.toBlob((blob) => {
if (blob) {
resolve(blob);
} else {
throw new Error('Failed to convert canvas to Blob');
}
}, 'image/png');
});
const response = await fetch('http://localhost:3000/api/drawings', {
method: 'POST',
body: JSON.stringify({
blob: blob,
prompt: prompt,
}),
});
let result: string = await response.json();
// if (result.includes('Error')) {
// throw new Error(result);
// } else {
console.log(result);
clearCanvas();
setPrompt('now draw something cooler');
// }
}
function generateUniqueFileName() {
const timestamp = new Date().toISOString();
const randomString = Math.random().toString(36).slice(2, 9);
return `${prompt.split(' ').join('-')}-${timestamp}-${randomString}.png`;
}
return (
<>
<TypingEffect textContent={`${prompt}`} />
<div
style={{
padding: '1em',
touchAction: 'none',
}}
>
<canvas
ref={canvasRef}
width={dimensions.width}
height={dimensions.height}
onMouseDown={startDrawing}
onMouseUp={stopDrawing}
onMouseOut={stopDrawing}
onMouseMove={draw}
onTouchStart={startDrawing}
onTouchEnd={stopDrawing}
onTouchMove={draw}
style={{
touchAction: 'none',
background: 'black',
}}
className="drawn-border"
/>
<div className="flex flex-wrap justify-center">
{drawingColors.map((color) => (
<button
key={color}
style={{
backgroundColor: `${color === currentColor ? color : 'black'}`,
color: `${color === currentColor ? 'black' : color}`,
margin: '5px',
padding: '10px 5px',
borderRadius: '5px',
border: `5px solid ${color}`,
}}
onClick={() => setColor(color)}
>
{color}
</button>
))}
<button
style={{
margin: '5px',
background: 'transparent',
padding: '10px 5px',
borderRadius: '5px',
}}
className="border-2 border-blue-300 border-solid text-blue-300"
onClick={clearCanvas}
>
Clear Drawing
</button>
<button
style={{
margin: '5px',
padding: '10px 5px',
borderRadius: '5px',
}}
className="border-2 border-green-300 border-solid bg-green-300 text-black font-bold text-2xl"
onClick={saveCanvas}
>
Save
</button>
</div>
</div>
</>
);
};
export default CanvasDrawer;
|
//
// SettingsViewController.m
// tsr-ios-demo
//
//
#import <Foundation/Foundation.h>
#import "SettingsViewController.h"
#import "VideoPlayViewController.h"
#import <MobileCoreServices/MobileCoreServices.h>
@interface SettingsViewController () <UIDocumentPickerDelegate, UICollectionViewDataSource, UICollectionViewDelegate>
@property (strong, nonatomic) UISegmentedControl *chooseTypeSegmentedControl;
@property (strong, nonatomic) UISegmentedControl *algorithmOptionsSegmentedControl;
@property (strong, nonatomic) UILabel *videoLocalHeaderLabel;
@property (strong, nonatomic) UILabel *srLabel;
@property (strong, nonatomic) UIButton *showCollectionViewButton;
@property (strong, nonatomic) UIButton *chooseFileButton;
@property (strong, nonatomic) UIButton *startPlayButton;
@property (nonatomic, strong) NSURL *selectedVideoURL;
@property (nonatomic, strong) UILabel *videoNameLabel;
@property (nonatomic, strong) UISegmentedControl *resolutionRatioControl;
@property (nonatomic, strong) UIView *horizontalLine;
@property (strong, nonatomic) UICollectionView *collectionView;
@property (strong, nonatomic) NSArray *data;
@property (strong, nonatomic) UIView *overlayView;
@end
@implementation SettingsViewController
- (void)viewDidLoad {
[super viewDidLoad];
self.view.backgroundColor = [UIColor whiteColor];
int top = 50;
int left = 20;
// Choose type segmented control
self.chooseTypeSegmentedControl = [[UISegmentedControl alloc] initWithItems:@[@"Album's Video", @"Build-in Video"]];
self.chooseTypeSegmentedControl.tintColor = [UIColor colorWithRed:26/255.0 green:221/255.0 blue:202/255.0 alpha:1.0];
self.chooseTypeSegmentedControl.frame = CGRectMake(left, top, self.view.bounds.size.width - 40, 50);
self.chooseTypeSegmentedControl.selectedSegmentIndex = 1;
[self.chooseTypeSegmentedControl addTarget:self action:@selector(chooseTypeSegmentChanged:) forControlEvents:UIControlEventValueChanged];
[self.view addSubview:self.chooseTypeSegmentedControl];
// 添加用于显示视频名称的标签
self.selectedVideoURL = [[NSBundle mainBundle] URLForResource:@"girl-544x960" withExtension:@"mp4"];
self.videoNameLabel = [[UILabel alloc] initWithFrame:CGRectMake(left, top + 50, self.view.bounds.size.width - 40, 50)];
self.videoNameLabel.text = @"Using video: girl-544x960";
[self.view addSubview:self.videoNameLabel];
// 初始化数据
self.data = @[@"4K", @"1080P", @"864P", @"720P", @"576P", @"540P", @"girl-544x960"];
// 创建并设置UICollectionViewFlowLayout
UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc] init];
layout.itemSize = CGSizeMake(1000, 50);
layout.minimumInteritemSpacing = 10;
layout.minimumLineSpacing = 10;
layout.sectionInset = UIEdgeInsetsMake(10, 10, 10, 10);
layout.scrollDirection = UICollectionViewScrollDirectionVertical;
// 创建并设置UICollectionView
self.collectionView = [[UICollectionView alloc] initWithFrame:self.view.bounds collectionViewLayout:layout];
self.collectionView.backgroundColor = [UIColor whiteColor];
self.collectionView.dataSource = self;
self.collectionView.hidden = YES; // 初始时隐藏CollectionView
self.collectionView.delegate = self;
[self.collectionView registerClass:[UICollectionViewCell class] forCellWithReuseIdentifier:@"CellIdentifier"];
// 创建并设置显示CollectionView的按钮
self.showCollectionViewButton = [UIButton buttonWithType:UIButtonTypeSystem];
self.showCollectionViewButton.frame = CGRectMake(left, top + 100, self.view.bounds.size.width - 40, 50);
[self.showCollectionViewButton setTitle:@"Select build-in video" forState:UIControlStateNormal];
[self.showCollectionViewButton addTarget:self action:@selector(showCollectionView) forControlEvents:UIControlEventTouchUpInside];
self.showCollectionViewButton.hidden = NO;
[self.view addSubview:self.showCollectionViewButton];
// 添加选择文件按钮
self.chooseFileButton = [UIButton buttonWithType:UIButtonTypeSystem];
[self.chooseFileButton setTitle:@"Select album's video" forState:UIControlStateNormal];
[self.chooseFileButton addTarget:self action:@selector(chooseVideoButtonTapped:) forControlEvents:UIControlEventTouchUpInside];
self.chooseFileButton.frame = CGRectMake(left, top + 100, self.view.bounds.size.width - 40, 50);
self.chooseFileButton.hidden = YES;
[self.view addSubview:self.chooseFileButton];
// 分割线
self.horizontalLine = [[UIView alloc]initWithFrame:CGRectMake(0, top + 150, self.view.bounds.size.width, 1)];
self.horizontalLine.backgroundColor = [UIColor grayColor];
[self.view addSubview:self.horizontalLine];
// Add Super Resolution Options segmented control
self.algorithmOptionsSegmentedControl = [[UISegmentedControl alloc] initWithItems:@[@"Standard SR", @"Pro SR", @"Pro Image Enhance", @"Play directly"]];
self.algorithmOptionsSegmentedControl.frame = CGRectMake(left, top + 170, self.view.bounds.size.width - 40, 50);
self.algorithmOptionsSegmentedControl.selectedSegmentIndex = 0;
self.algorithmOptionsSegmentedControl.apportionsSegmentWidthsByContent = YES;
[self.algorithmOptionsSegmentedControl addTarget:self action:@selector(superResolutionOptionsChanged:) forControlEvents:UIControlEventValueChanged];
[self.view addSubview:self.algorithmOptionsSegmentedControl];
// 超分辨率标签
_srLabel = [[UILabel alloc] initWithFrame:CGRectMake(left, top + 220, self.view.bounds.size.width - 40, 50)];
_srLabel.text = @"Super Resolution Ratio";
[self.view addSubview:_srLabel];
// 添加超分辨率倍率选择器
NSArray *resolutionRatios = @[@"1.0", @"1.25", @"1.5", @"1.7", @"2.0"];
self.resolutionRatioControl = [[UISegmentedControl alloc] initWithItems:resolutionRatios]; self.resolutionRatioControl.frame = CGRectMake(left, top + 270, self.view.bounds.size.width - 40, 50); self.resolutionRatioControl.selectedSegmentIndex = 4; // 默认选择2.0
[self.view addSubview:self.resolutionRatioControl];
// 分割线
self.horizontalLine = [[UIView alloc]initWithFrame:CGRectMake(0, top + 350, self.view.bounds.size.width, 1)];
self.horizontalLine.backgroundColor = [UIColor grayColor];
[self.view addSubview:self.horizontalLine];
// 添加播放视频按钮
self.startPlayButton = [UIButton buttonWithType:UIButtonTypeSystem];
[self.startPlayButton setTitle:@"Play Video" forState:UIControlStateNormal];
[self.startPlayButton addTarget:self action:@selector(playVideoButtonTapped:) forControlEvents:UIControlEventTouchUpInside];
self.startPlayButton.frame = CGRectMake([UIScreen mainScreen].bounds.size.width / 2 - 50, top + 370, 100, 50);
[self.view addSubview:self.startPlayButton];
// 创建并设置覆盖其他控件的视图
self.overlayView = [[UIView alloc] initWithFrame:self.view.bounds];
self.overlayView.backgroundColor = [[UIColor grayColor] colorWithAlphaComponent:0.5]; // 半透明的灰色
self.overlayView.hidden = YES; // 初始时隐藏
[self.view addSubview:self.overlayView];
[self.view insertSubview:self.collectionView aboveSubview:self.self.overlayView];
}
- (IBAction)chooseVideoButtonTapped:(id)sender {
// 创建并显示 UIImagePickerController
UIImagePickerController *imagePickerController = [[UIImagePickerController alloc] init];
imagePickerController.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
imagePickerController.mediaTypes = @[(NSString *)kUTTypeMovie];
imagePickerController.delegate = self;
[self presentViewController:imagePickerController animated:YES completion:nil];
}
- (void)playVideoButtonTapped:(id)sender {
// 获取选中的超分辨率倍率
NSString *selectedResolutionRatio = [self.resolutionRatioControl titleForSegmentAtIndex:self.resolutionRatioControl.selectedSegmentIndex];
float srRatio = [selectedResolutionRatio floatValue];
NSLog(@"Selected resolution ratio: %@", selectedResolutionRatio);
NSString *selectedAlgorithm = [self.algorithmOptionsSegmentedControl titleForSegmentAtIndex:self.algorithmOptionsSegmentedControl.selectedSegmentIndex];
NSLog(@"Selected algorithm: %@", selectedAlgorithm);
// 显示 ViewController
VideoPlayViewController *videoPlayVC = [[VideoPlayViewController alloc] initWithVideoURL:self.selectedVideoURL srRatio:srRatio algorithm:selectedAlgorithm];
videoPlayVC.modalPresentationStyle = UIModalPresentationFullScreen;
[self presentViewController:videoPlayVC animated:YES completion:nil];
}
- (void)chooseTypeSegmentChanged:(UISegmentedControl *)sender {
switch (sender.selectedSegmentIndex) {
case 0: // Album's video
// 显示与Album's video相关的UI
self.showCollectionViewButton.hidden = YES;
self.chooseFileButton.hidden = NO;
break;
case 1: // Build-in Video
// 显示与Build-in Video相关的UI
self.showCollectionViewButton.hidden = NO;
self.chooseFileButton.hidden = YES;
break;
default:
break;
}
}
- (void)superResolutionOptionsChanged:(UISegmentedControl *)sender {
if (sender.selectedSegmentIndex == 0 || sender.selectedSegmentIndex == 1) {
self.resolutionRatioControl.hidden = NO;
self.srLabel.hidden = NO;
} else {
self.resolutionRatioControl.hidden = YES;
self.srLabel.hidden = YES;
}
}
- (void)showCollectionView {
self.collectionView.hidden = NO; // 显示CollectionView
self.overlayView.hidden = NO;
}
#pragma mark - UIImagePickerControllerDelegate
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary<UIImagePickerControllerInfoKey,id> *)info {
self.selectedVideoURL = info[UIImagePickerControllerMediaURL];
self.videoNameLabel.text = [NSString stringWithFormat:@"%@%@", @"Using video: ", [self.selectedVideoURL lastPathComponent]];
// 在这里处理选定的视频(例如,读取内容、显示预览等)
NSLog(@"Selected album's video: %@", self.selectedVideoURL);
// 关闭 UIImagePickerController
[picker dismissViewControllerAnimated:YES completion:nil];
}
- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker {
// 用户取消了视频选择
NSLog(@"Video selection was cancelled");
[picker dismissViewControllerAnimated:YES completion:nil];
}
#pragma mark - UICollectionViewDataSource
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
return self.data.count;
}
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
UICollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"CellIdentifier" forIndexPath:indexPath];
UILabel *label = (UILabel *)[cell viewWithTag:100];
if (!label) {
label = [[UILabel alloc] initWithFrame:cell.bounds];
label.tag = 100;
label.textAlignment = NSTextAlignmentCenter;
[cell addSubview:label];
}
label.text = self.data[indexPath.item];
cell.backgroundColor = [UIColor lightGrayColor];
return cell;
}
#pragma mark - UICollectionViewDelegate
- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath {
NSString *selectedItem = self.data[indexPath.item];
self.videoNameLabel.text = [NSString stringWithFormat:@"%@%@", @"Using video: ", selectedItem];
self.overlayView.hidden = YES;
self.collectionView.hidden = YES; // 初始时隐藏CollectionView
self.selectedVideoURL = [[NSBundle mainBundle] URLForResource:selectedItem withExtension:@"mp4"];
NSLog(@"Selected item: %@", selectedItem);
}
@end
|
import React, { useContext, useState } from 'react';
import { useForm } from "react-hook-form";
import toast from 'react-hot-toast';
import { Link, useNavigate } from 'react-router-dom';
import { AuthContext } from '../../contexts/AuthProvider';
import useToken from '../../hooks/useToken';
const SignUp = () => {
const { register, formState: { errors }, handleSubmit } = useForm();
const [signUpError, setSignUpError] = useState('');
const [createdEmail, setCreatedEmail] = useState('');
const { createUser, updateUser, googleSignIn, googleProvider } = useContext(AuthContext);
const [token] = useToken(createdEmail);
const navigate = useNavigate();
if (token) {
navigate('/');
}
const handleSignIn = (data) => {
setSignUpError('');
createUser(data.email, data.password)
.then(res => {
const user = res.user;
console.log(user);
toast('User Created Successfully');
const userInfo = {
displayName: data.name
}
updateUser(userInfo)
.then(() => {
saveUser(data.name, data.email, data.role);
})
.catch(error => console.log(error))
})
.catch(error => {
console.log(error);
setSignUpError(error.message)
});
}
const handlegoogleSignin = (provider) => {
setSignUpError('');
googleSignIn(googleProvider)
.then(result => {
const user = result.user;
console.log(user);
toast('User Created Successfully');
const userInfo = {
displayName: user.name
}
updateUser(userInfo)
.then(() => {
saveUser(user.name, user.email, 'buyer');
})
.catch(error => console.log(error))
})
.catch(err => console.error(err));
}
const saveUser = (name, email, role) => {
const user = { name, email, role };
fetch(`https://resale-market-server-nayem-mursalin.vercel.app/users`, {
method: 'POST',
headers: {
'content-type': 'application/json'
},
body: JSON.stringify(user)
})
.then(res => res.json())
.then(data => {
setCreatedEmail(email);
})
}
return (
<div className='h-[800px] flex justify-center items-center'>
<div className='w-96 p-7'>
<h2 className='text-xl text-center'>SignUp</h2>
<form onSubmit={handleSubmit(handleSignIn)}>
<div className='form-control w-full w-max-xs'>
<label className='label'><span className='label-text'>Name</span></label>
<input type="name"
{...register("name", { required: "Name is Required" })}
className="input input-bordered w-full max-w-xs" />
{errors.name && <p className='text-red-600' role="alert">{errors.name?.message}</p>}
</div>
<div className='form-control w-full w-max-xs'>
<label className='label'><span className='label-text'>Email</span></label>
<input type="email"
{...register("email", { required: "Email is Required" })}
className="input input-bordered w-full max-w-xs" />
{errors.email && <p className='text-red-600' role="alert">{errors.email?.message}</p>}
</div>
<div className='form-control w-full w-max-xs'>
<label className='label'> <span className='label-text'>Password</span></label>
<input type="password"
{...register("password", {
required: "Psssword is Required",
minLength: { value: 6, message: "Password must be 6 character or longer" }
})}
className="input input-bordered w-full max-w-xs" />
{errors.password && <p className='text-red-600'>{errors.password?.message}</p>}
</div>
<div className='form-control w-full w-max-xs'>
<label className='label'> <span className='label-text'>Select a User Type</span></label>
<select {...register("role", {
required: "User Type is Required"
})}
className="input input-bordered w-full max-w-xs">
<option value="buyer">Buyer</option>
<option value="Seller">Seller</option>
</select>
</div>
<input className='btn btn-accent w-full mt-4' value="SignUp" type="submit" />
<div>
{signUpError && <p className='text-red-600'>{signUpError}</p>}
</div>
</form>
<br></br>
<p>Already have an Account? <Link className='text-secondary' to="/login">Please Login</Link></p>
<div className="divider">OR</div>
<button onClick={handlegoogleSignin} className='btn btn-outline w-full'>CONTINUE WITH GOOGLE</button>
</div>
</div>
);
};
export default SignUp;
|
package com.ecommerce.site.admin.controller;
import com.ecommerce.site.admin.annotation.PagingAndSortingParam;
import com.ecommerce.site.admin.exception.QuestionNotFoundException;
import com.ecommerce.site.admin.helper.PagingAndSortingHelper;
import com.ecommerce.site.admin.model.entity.Question;
import com.ecommerce.site.admin.security.UserDetailsImpl;
import com.ecommerce.site.admin.service.QuestionService;
import javax.servlet.http.HttpServletRequest;
import org.jetbrains.annotations.NotNull;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.annotation.AuthenticationPrincipal;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;
@Controller
@RequestMapping("/questions")
public class QuestionController {
private final String defaultRedirectUrl = "redirect:/questions/offset/10/page/1?sortField=askTime&sortDir=desc";
@Autowired
private QuestionService service;
@GetMapping("")
public String listFirstPage() {
return defaultRedirectUrl;
}
@GetMapping("/offset/{pageSize}/page/{pageNumber}")
public String listByPage(@PagingAndSortingParam(listName = "listQuestions", moduleUrl = "/questions") PagingAndSortingHelper helper,
@PathVariable("pageSize") int pageSize, @PathVariable("pageNumber") int pageNumber) {
service.listByPage(pageNumber, pageSize, helper);
return "questions/questions";
}
@GetMapping("/detail/{id}")
public String viewQuestion(@PathVariable("id") Integer id, @NotNull Model model, RedirectAttributes attributes) {
try {
Question question = service.get(id);
model.addAttribute("question", question);
return "questions/question_detail_modal";
} catch (QuestionNotFoundException e) {
attributes.addFlashAttribute("message", e.getMessage());
return defaultRedirectUrl;
}
}
@GetMapping("/edit/{id}")
public String editQuestion(@PathVariable("id") Integer id, @NotNull Model model, RedirectAttributes attributes) {
try {
Question question = service.get(id);
model.addAttribute("question", question);
model.addAttribute("pageTitle", String.format("Edit Question (ID %s)", id));
return "questions/question_form";
} catch (QuestionNotFoundException e) {
attributes.addFlashAttribute("message", e.getMessage());
return defaultRedirectUrl;
}
}
@PostMapping("/save")
public String saveQuestion(Question question, @NotNull RedirectAttributes attributes,
@AuthenticationPrincipal @NotNull UserDetailsImpl userDetails) {
try {
service.save(question, userDetails.user());
attributes.addFlashAttribute("message", String.format("The Question ID %s has been updated successfully", question.getId()));
} catch (QuestionNotFoundException ex) {
attributes.addFlashAttribute("message", String.format("Could not find any question with ID %s", question.getId()));
}
return defaultRedirectUrl;
}
@GetMapping("/{id}/approve")
public String approveQuestion(@PathVariable("id") Integer id, @NotNull RedirectAttributes attributes, @NotNull HttpServletRequest request) {
service.approve(id);
attributes.addFlashAttribute("message", String.format("The Question ID %s has been approved", id));
return String.format("redirect:%s", request.getHeader("Referer"));
}
@GetMapping("/{id}/disapprove")
public String disapproveQuestion(@PathVariable("id") Integer id, @NotNull RedirectAttributes attributes, @NotNull HttpServletRequest request) {
service.disapprove(id);
attributes.addFlashAttribute("message", String.format("The Question ID %s has been disapproved", id));
return String.format("redirect:%s", request.getHeader("Referer"));
}
@GetMapping("/delete/{id}")
public String deleteQuestion(@PathVariable("id") Integer id, @NotNull RedirectAttributes attributes, HttpServletRequest request) {
try {
service.delete(id);
attributes.addFlashAttribute("message", String.format("The question ID %s has been deleted successfully", id));
} catch (QuestionNotFoundException e) {
attributes.addFlashAttribute("message", e.getMessage());
}
return String.format("redirect:%s", request.getHeader("Referer"));
}
}
|
import React from 'react';
import { Props } from '../model';
import Image from 'next/image';
import Button from '@/widgets/button/ui';
import GitHub from '@mui/icons-material/GitHub';
import Link from 'next/link';
import Animation from "@/widgets/animation";
const ProjectCard = ({data, lang, dict, key}: Props) => {
const formattedData = {
from: new Date(data.from),
to: new Date(data.to),
};
const animationDuration = 0.7 + (0.3 * key)
return (
<Animation variant="card" duration={animationDuration}>
<div className="border-2 p-6 rounded-3xl border-accent-2 bg-light/30 backdrop-blur-md">
<div className="flex gap-6 flex-wrap">
<Image
className="min-w-full sm:min-w-96 bg-light flex-1 min-h-44 rounded-3xl sm:max-w-[504px] max-h-[288px] w-full h-full"
width={0}
height={0}
src={data.image}
alt={data.title[lang]}
/>
<div className="flex-1">
<h2 className="text-accent-3 text-3xl font-bold">{data.title[lang]}</h2>
<p className="text-white text-2xl font-bold mt-6">
{data.description[lang]}
</p>
</div>
</div>
<div className="flex mt-6 gap-6 flex-wrap">
<div className="min-w-full sm:min-w-96 flex-1 max-w-[504px] w-full">
<div className="flex gap-6 w-full">
<Link href={data.url} target="_blank" className="flex-1">
<Button className="w-full">{dict.viewButton}</Button>
</Link>
{
data.github && data.github?.length > 0 ?
<Link className="flex-1" href={data.github} target="_blank">
<Button className="w-full"><GitHub className="w-8 h-8"/></Button>
</Link>
: ""
}
</div>
<h3 className="text-white text-2xl font-bold mt-6">{dict.from}{formattedData.from.toLocaleDateString()} {dict.to}{formattedData.to.toLocaleDateString()}</h3>
</div>
<div className="flex flex-2 sm:w-1/2 justify-start flex-wrap gap-6">
{data.tags.map((tag: string, key: number) =>
<div
className="py-2 px-6 h-12 bg-accent-1 text-center text-white rounded-full text-2xl font-bold"
key={key}>{tag.length > 14 ? `${tag.slice(0, 14)}...` : tag}</div>
)}
</div>
</div>
</div>
</Animation>
);
};
export default ProjectCard;
|
package pl5;
/*
* Autor: Ander José Fernández Vega
* Practica: P5 - LALR con CUP
*/
import java_cup.runtime.*;
import java.io.*;
import java.util.List;
import java.util.LinkedList;
parser code {:
public static void main(String[] argv){
if (argv.length == 0) {
System.out.println("Uso : java Parser <inputfile)>");
}
else{
try {
java.io.FileInputStream stream = new java.io.FileInputStream(argv[0]);
java.io.Reader reader = new java.io.InputStreamReader(stream);
Scanner analizadorLexico= new Yylex(reader);
Parser parserObj = new Parser();
parserObj.setScanner(analizadorLexico);
parserObj.parse();
}
catch(Exception x) {
System.out.println("Error fatal.");
}
}
}
// SYNTAX ERRORs
public void syntax_error(Symbol cur_token){
String msg="[Parser] Error de sintaxis: '"+
symbl_name_from_id(cur_token.sym)+
"' en línea "+cur_token.left+", columna "+cur_token.right+"\n";
List<Integer> list_of_ids = expected_token_ids();
LinkedList<String> list = new LinkedList<String>();
for (Integer token_id : list_of_ids)
list.add(symbl_name_from_id(token_id));
msg += "\tTipos de tokens esperados: " + list +"\n";
System.out.println(msg);
}
:};
/*Inicializacion del analizador lexico si procede*/
/* Con JFlex esto no es necesario */
//init with {: s.init(); :};
/*Siguiente token al lexico*/
//scan with {: return this.getScanner().next_token(); :};
/*Terminales tokens que puede devolver el lexico*/
terminal SEMICOLON, PLUS, MINUS, TIMES, DIV, POW, SQRT, LEFT_BRACKET, RIGHT_BRACKET, UPLUS, UMINUS;
/*Terminales con atributo*/
terminal Float FLOAT;
/* No terminales sin atributo*/
non terminal listaexpr;
/* No terminales con atributo*/
non terminal Float expr;
/*Precedencias*/
precedence left PLUS,MINUS;
precedence left TIMES,DIV;
precedence right POW;
precedence nonassoc SQRT;
precedence left UMINUS, UPLUS;
/*Gramatica*/
// S-->SE;|e
// E-->E+E|E-E|E*E|E/E|E^E|sqrt(E)|(E)| ufloat
listaexpr ::= listaexpr expr:e SEMICOLON {: System.out.println("= " + e); :}
|
|error:e {: :} SEMICOLON /* gestión de errores sintácticos */
;
expr ::= expr:e1 PLUS expr:e2
{: RESULT= new Float(e1.floatValue() + e2.floatValue()); :}
| expr:e1 MINUS expr:e2
{: RESULT= new Float(e1.floatValue() - e2.floatValue()); :}
| expr:e1 TIMES expr:e2
{: RESULT= new Float(e1.floatValue() * e2.floatValue()); :}
| expr:e1 DIV expr:e2
{: RESULT= new Float(e1.floatValue() / e2.floatValue()); :}
| expr:e1 POW expr:e2
{: RESULT= new Float(Math.pow(e1.floatValue(), e2.floatValue())); :}
| SQRT LEFT_BRACKET expr:e RIGHT_BRACKET
{: RESULT= new Float(Math.sqrt(e.floatValue())); :}
| FLOAT:n
{: RESULT=n; :}
| MINUS expr:e
{: RESULT= new Float(0-e.floatValue()); :} %prec UMINUS
| PLUS expr:e
{: RESULT= new Float(0+e.floatValue()); :} %prec UPLUS
| LEFT_BRACKET expr:e RIGHT_BRACKET
{: RESULT=e; :}
;
|
---
title: Accès aux indicateurs de performance clés
description: Découvrez comment accéder à vos indicateurs clés de performance et définir le processus de création de rapports
exl-id: 8556e0e3-a557-4fd6-9b82-09cb1decff0a
source-git-commit: bc3c054e781789aa2a2b94f77b0616caec15e2ff
workflow-type: tm+mt
source-wordcount: '544'
ht-degree: 94%
---
# Mesurez-vous les éléments les plus importants ?{#measuring-the-things-that-matter-most}
>[!CONTEXTUALHELP]
>id="aemcloud_assesskpis"
>title="Évaluation des indicateurs de performance clés"
>abstract="Avant de vous engager dans le lancement d’Adobe Experience Manager, toutes les personnes impliquées dans le projet doivent connaître vos trois principaux indicateurs de performance clés et la raison pour laquelle ils sont importants."
>additional-url="https://experienceleague.adobe.com/docs/experience-manager-cloud-service/onboarding/best-practices/aligning-kpis.html?lang=fr" text="Alignement des indicateurs de performance clés"
>additional-url="https://experienceleague.adobe.com/docs/experience-manager-cloud-service/onboarding/best-practices/choose-right-team.html?lang=fr" text="Choix de la bonne équipe"
Avant de vous engager dans le lancement d’Adobe Experience Manager, toutes les personnes impliquées dans le projet doivent connaître vos trois principaux indicateurs de performance clés et la raison pour laquelle ils sont importants.
**Choisir les bons indicateurs de performance clés vous aidera à tirer le meilleur parti d’Adobe Experience Manager**
Dans une étude de 2018, IDC a analysé la valeur commerciale que plusieurs grandes sociétés ont observé lors de leur utilisation d’Adobe Experience Manager. En moyenne, les organisations qui utilisaient les Experience Manager Sites ont augmenté la productivité de leurs équipes d’expérience digitale de 23 %, ont réduit le temps nécessaire à leurs modifications rédactionnelles mineures de 64 % et ont augmenté le nombre des visites mensuelles sur leurs sites de 10 %. Les sociétés qui utilisaient Experience Manager Assets ont augmenté de 19 % la productivité de leurs équipes de ressources numériques, réduit de 47 % le temps nécessaire à la création de nouvelles ressources et réduit de 20 % le délai de lancement des campagnes marketing.
Pour réaliser les mêmes gains spectaculaires, votre organisation doit avoir des objectifs clairs pour votre mise en oeuvre Experience Manager. Vous devez également définir des indicateurs de performance clés qui aident tous vos collaborateurs à garder le cap sur ces objectifs.
## Accès aux indicateurs de performance clés
Lors de l’évaluation de vos indicateurs de performance clés, assurez-vous des points suivants :
1. L’indicateur de performance clé se rapporte spécifiquement à la solution (Experience Manager).
1. L’indicateur de performance clé est étroitement lié à un objectif que l’équipe dirigeante juge d’une importance critique.
1. Cet objectif contribue directement à un objectif commercial défendu par au moins un cadre supérieur.
1. Vous disposez des informations de base pour comparer la situation actuelle aux résultats que vous obtenez après le lancement d’Experience Manager.
1. L’indicateur de performance clé (KPI) examinera un élément qui peut être mesuré à intervalles réguliers.
Après avoir confirmé que vous disposez des KPI appropriés, vous devez déterminer comment et à quel moment vous allez créer des rapports sur chaque KPI pour les parties prenantes concernées.
Lors de la définition de votre processus de compte-rendu, prenez en compte les questions suivantes :
1. Quelle est l’audience de ce rapport sur les indicateurs de performance clés ? Pour chaque KPI, assurez-vous d’avoir identifié un promoteur ou une promotrice (quelqu’un qui compte sur vous et sur le reste de l’équipe pour l’évaluation de cette mesure) ainsi qu’une liste plus longue de personnes qui devraient recevoir des rapports réguliers.
1. À quelle fréquence génèrerez-vous des rapports sur cet indicateur de performance clé ?
1. Comment allez-vous suivre cet indicateur de performance clé ? Qui va extraire les données ? Quelles sources de données cette personne ou cette équipe utilisera-t-elle ? Existe-t-il des mesures que vous puissiez prendre dès maintenant pour faciliter ce processus ?
1. Quel sera le format du rapport ?
1. Comment le rapport sera-t-il remis ?
Une fois que vous aurez lancé votre implémentation d’Experience Manager, un ensemble solide de KPI vous permettra de déterminer rapidement si vous êtes sur la bonne voie. Si vous n’atteignez pas un de vos KPI, vous devez apporter des modifications à la façon dont vos équipes utilisent Experience Manager. Si vous dépassez rapidement l’un de vos objectifs de KPI, commencez par célébrer votre victoire. Vous aurez cependant intérêt à recalibrer votre objectif pour essayer d’obtenir un résultat encore meilleur.
>[!TIP]
>
> Si vous avez besoin d’aide supplémentaire sur vos KPI, contactez [Adobe Consulting Services](https://www.adobe.com/fr/experience-cloud/consulting-services.html) ou votre partenaire d’implémentation.
|
import { NavigationContainer } from "@react-navigation/native";
import { createBottomTabNavigator } from "@react-navigation/bottom-tabs";
import { StyleSheet, View, Text } from "react-native";
import AlarmScreen from "./screens/AlarmScreen";
import TimerScreen from "./screens/TimerScreen";
import Ionicons from "@expo/vector-icons/Ionicons";
import { SafeAreaView } from "react-native";
const Tab = createBottomTabNavigator();
export default function App() {
return (
<SafeAreaView style={styles.container}>
<NavigationContainer>
<Tab.Navigator
screenOptions={({ route }) => ({
tabBarIcon: ({ focused, color, size }) => {
let iconName;
if (route.name === "Alarm") {
iconName = focused ? "alarm" : "alarm-outline";
} else if (route.name === "Timer") {
iconName = focused ? "timer" : "timer-outline";
}
// You can return any component that you like here!
return <Ionicons name={iconName} size={size} color={color} />;
},
tabBarActiveTintColor: "#F6E8EA",
tabBarInactiveTintColor: "gray",
tabBarStyle: { backgroundColor: "#0D1821" },
headerStyle: { backgroundColor: "#0D1821" },
headerTintColor: "#F6E8EA",
})}
>
<Tab.Screen name={"Alarm"} component={AlarmScreen} />
<Tab.Screen name={"Timer"} component={TimerScreen} />
</Tab.Navigator>
</NavigationContainer>
</SafeAreaView>
);
}
const styles = StyleSheet.create({
container: {
width: "100%",
height: "100%",
backgroundColor: "#0D1821",
},
});
|
import { NgModule } from '@angular/core';
import { RouterModule, Routes } from '@angular/router';
import { HomeComponent } from './home/home.component';
import { ContactUsComponent } from './contact-us/contact-us.component';
import { UserProfileComponent } from './user-profile/my-profile.component';
import { SellerDashboardComponent } from './customer/seller/seller-dashboard/seller-dashboard.component';
import { ProductComponent } from './product-crud/product/product.component';
const routes: Routes = [
{ path: '', redirectTo: '', component: HomeComponent, pathMatch: 'full' },
{ path: '', component: HomeComponent },
{ path: 'contact-us', component: ContactUsComponent },
{ path: 'my-profile', component: UserProfileComponent },
//after login to seller
{
path: '',
children: [
{
path: 'seller-dashboard',
component: SellerDashboardComponent,
},
{
path: 'product',
component: ProductComponent,
},
],
},
];
@NgModule({
imports: [RouterModule.forRoot(routes)],
exports: [RouterModule],
})
export class AppRoutingModule {}
|
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Content</title>
<link rel="stylesheet" href="course_science.css" type="text/css">
</head>
<body>
<div class="wrap">
<div class="header">
<img src="images/globe.gif" class="globe" alt="Image of Globe" />
<div class="courseTitle">
SCH3U: Chemistry, Grade 11, University Preparation</div>
<h1>
Unit 3: Quantities in Chemical Reactions</h1>
<h2>
Activity 1: Chemistry in Science, Technology, Society and the Environment</h2>
</div>
<div class="subNav">
<a href="overview.html">Overview</a> | <a href="expectations.html">Expectations</a> | <b>Content</b> | <a href="assignment.html">Assignment</a>
</div>
<h3>
Content</h3>
<hr />
<h4><strong>Measurements, Reactions and Calculations</strong></h4>
<table width="95%" cellpadding="5">
<tr>
<td><img src="images/cake.jpg" alt="This is a photo of a slice being taken from a chocolate cake." width="200" height="155"></td>
<td>Remember that delicious cake for dessert or was it a piece of pie you tried? Were there seconds? Think about the effort that was put into making that dessert. A recipe shows the exact ingredients and their measurements, as well as the specific steps to follow to ensure a delicious dessert. </td>
</tr>
</table>
<p>People who make cakes follow an experimental procedure. The recipe lists the chemicals and their respective amounts, the equipment, and the steps involved in producing a successful product; in this case, a dessert. Chemists approach chemical reactions in the same way. The reactants and lab apparatus are known. The steps are followed in order to produce the conditions necessary for the reaction(s). Any significant missteps in following the procedure can lead to disastrous results. </p>
<table width="95%" cellpadding="5">
<tr>
<td><img src="images/peanutbutter.jpg" alt="This is a photo of a jar of peanut butter and toast." width="133" height="200"></td>
<td>Quantitative procedures or applications are critical components in ensuring success in analysis and/or production. A case in point: One common ingredient in the production of peanut butter is salt. A peanut butter factory produces an enormous amount of peanut butter during a shift. The rate of the amount of salt added to the peanut butter is dependent on how fast and how much peanut meal is processed per hour. Peanut butter that is too salty, or not salty enough, will not meet the company’s standards required to ensure a saleable product.</td>
</tr>
</table>
<p>One way to make sure that the levels of salt meet the company standard is to perform a chemical analysis of the peanut butter. The amount of salt can be measured by a simple reaction:</p>
<p align="center">NaCl(aq) + AgNO<span class="subscript">3</span>(aq) <img src="images/Arrow_wh.gif" width="14" height="12"> AgCl(s) + NaNO<span class="subscript">3</span>(aq)</p>
<p>The reactants’ respective amounts in this reaction are critical to ensuring that the results are a true indication of the amount of salt in the peanut butter. Any mistake in measuring the amount of tested peanut butter, and/or the solution of silver nitrate, will produce a false reading. If mistakes are made in the lab, then the error-filled chemical analysis will not properly identify the amount of salt in the peanut butter sample. </p>
<table width="95%" cellpadding="5">
<tr>
<td width="21%"><img src="images/cast.jpg" alt="This is a photo of a detached cast." width="141" height="200"></td>
<td width="79%"><p>Sometimes, too much of one reactant can be a good thing in a chemical reaction. A case in point: In creating a cast, the temperature of the reaction will exceed 100°C when mixing precise amounts of plaster and water. This reaction produces a lot of heat. The technician who helps to mix the water and plaster, follows a procedure and knows that there must be an excess amount of water in the preparation of the cast. The reaction is as follows:</p>
<p>2CaSO<span class="subscript">4</span>•½H<span class="subscript">2</span>O(s) + 3H<span class="subscript">2</span>O(l) <img src="images/Arrow_wh.gif" width="14" height="12"> 2CaSO<span class="subscript">4</span>•2H<span class="subscript">2</span>O(s)</p></td>
</tr>
</table>
<h4><img src="images/question.gif" alt="Questions Icon" width="42" height="42" border="0"> Question </h4>
<div class="questions">
<ol>
<li>What purpose would an excess amount of water serve in this reaction during the preparation of a cast?</li>
</ol>
<ol><a href="answer_01.html" target="_blank"> <img src="images/answer_english.gif" border="0" alt="Answer Button"> Answer</a>
</ol>
</div>
<br>
<p><strong>Significant Figures and Calculations: </strong></p>
<table width="95%" cellpadding="5">
<tr>
<td><img src="images/liquidvolume.jpg" alt="This is a photo of a clear liquid in a graduated cylinder." width="133" height="200"></td>
<td><p>The precision of a measurement is expressed by its significant figures. Comparing the volumes of two samples, Sample A (17.4 mL) and Sample B (17 mL), it is evident that Sample A is measured and rounded off to the nearest tenth of a millilitre and Sample B is measured and rounded off to its nearest unit value. Sample A’s measurement has three significant figures and Sample B has two significant figures. Sample A has a more precise measurement compared to the measurement for Sample B. </p>
</td>
</tr>
</table>
<h4><img src="images/example.gif" alt="Example Icon" width="42" height="42"> Example</h4>
<p>In determining the number of significant figures, examine the following examples to act as a reference:</p>
<p><img src="images/chart.gif" width="581" height="292"></p>
<p>Take note of the following guidelines that were used in the example above:</p>
<ul>
<li>Numbers 1 to 9, inclusive, are significant, i.e., 2785.3 has five significant figures;</li>
<li>Any zero between digits is significant, i.e., 1003. 02 has 6 significant figures;</li>
<li>Any zero to the left of a non-zero digit doesn’t count as a significant figure, i.e., 0.002 85 has 3 significant figures;</li>
<li>Any zero and only zeros to the right of a decimal are significant, i.e., 25.00 has 4 significant figures;</li>
<li>Any zero to the right of a digit in a decimal position is significant, i.e., 93.210 0 has 6 significant figures;</li>
<li>Any zero between the rightmost digit and the “invisible” decimal may or may not be significant depending on knowing the context of the number, i.e., 50 could have 2 significant digits if we know that maybe someone performed exactly 50 sit-ups or 50 could have 1 significant figure if someone estimated that there were about 50 candies in the bag.</li>
</ul>
<p class="navbuttons">
<a href="content_02.html">Next</a>
</p>
<p class="disclaimer">
This is a disclaimer. External Resources will open in a new window. Not responsible for external content.<br />
Unless otherwise indicated, all images in this Activity are from the public domain or are © clipart.com or Microsoft clipart and are used with permission.
</p>
<hr />
<div class="subNav">
<a href="overview.html">Overview</a> | <a href="expectations.html">Expectations</a> | <b>Content</b> | <a href="assignment.html">Assignment</a>
</div>
</div>
</body>
</html>
|
package com.example.shopmate_app.ui.fragments.utils
import android.content.Context
import android.graphics.Canvas
import android.graphics.Color
import android.graphics.drawable.ColorDrawable
import android.graphics.drawable.Drawable
import androidx.core.content.ContextCompat
import androidx.recyclerview.widget.ItemTouchHelper
import androidx.recyclerview.widget.RecyclerView
import com.example.shopmate_app.R
open class SwipeToDeleteCallback(context: Context) : ItemTouchHelper.SimpleCallback(0, ItemTouchHelper.LEFT or ItemTouchHelper.RIGHT) {
private val deleteIcon: Drawable = ContextCompat.getDrawable(context, R.drawable.trash_can_outline)!!
private val assignIcon: Drawable = ContextCompat.getDrawable(context, R.drawable.account_convert)!!
private val intrinsicWidth = deleteIcon.intrinsicWidth
private val intrinsicHeight = deleteIcon.intrinsicHeight
private val backgroundDelete = ColorDrawable(Color.RED)
private val backgroundAssign = ColorDrawable(Color.GREEN)
override fun onMove(
recyclerView: RecyclerView,
viewHolder: RecyclerView.ViewHolder,
target: RecyclerView.ViewHolder
): Boolean {
return false
}
override fun onSwiped(viewHolder: RecyclerView.ViewHolder, direction: Int) {
// This method will be overridden in the fragment
}
override fun onChildDraw(
c: Canvas,
recyclerView: RecyclerView,
viewHolder: RecyclerView.ViewHolder,
dX: Float,
dY: Float,
actionState: Int,
isCurrentlyActive: Boolean
) {
val itemView = viewHolder.itemView
val itemHeight = itemView.bottom - itemView.top
if (dX > 0) {
// Swiping to the right
backgroundAssign.setBounds(itemView.left, itemView.top, itemView.left + dX.toInt(), itemView.bottom)
backgroundAssign.draw(c)
val assignIconTop = itemView.top + (itemHeight - intrinsicHeight) / 2
val assignIconMargin = (itemHeight - intrinsicHeight) / 2
val assignIconLeft = itemView.left + assignIconMargin
val assignIconRight = itemView.left + assignIconMargin + intrinsicWidth
val assignIconBottom = assignIconTop + intrinsicHeight
assignIcon.setBounds(assignIconLeft, assignIconTop, assignIconRight, assignIconBottom)
assignIcon.draw(c)
} else if (dX < 0) {
// Swiping to the left
backgroundDelete.setBounds(itemView.right + dX.toInt(), itemView.top, itemView.right, itemView.bottom)
backgroundDelete.draw(c)
val deleteIconTop = itemView.top + (itemHeight - intrinsicHeight) / 2
val deleteIconMargin = (itemHeight - intrinsicHeight) / 2
val deleteIconLeft = itemView.right - deleteIconMargin - intrinsicWidth
val deleteIconRight = itemView.right - deleteIconMargin
val deleteIconBottom = deleteIconTop + intrinsicHeight
deleteIcon.setBounds(deleteIconLeft, deleteIconTop, deleteIconRight, deleteIconBottom)
deleteIcon.draw(c)
}
super.onChildDraw(c, recyclerView, viewHolder, dX, dY, actionState, isCurrentlyActive)
}
}
|
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
class Solution {
public:
void rotate(vector<vector<int>>& matrix) {
int n = matrix.size();
int m = matrix[0].size();
vector<vector<int>> temp(n, vector<int>(m, 0));
for (int i = 0; i < n; i++) {
for (int j = 0; j < i; j++) {
swap(matrix[i][j], matrix[j][i]);
}
}
for (int i = 0; i < n; i++) {
reverse(matrix[i].begin(), matrix[i].end());
}
}
};
int main() {
vector<vector<int>> matrix = {
{1, 2, 3},
{4, 5, 6},
{7, 8, 9}
};
Solution solution;
cout << "Original Matrix:" << endl;
for (const auto &row : matrix) {
for (int num : row) {
cout << num << " ";
}
cout << endl;
}
solution.rotate(matrix);
cout << "\nRotated Matrix:" << endl;
for (const auto &row : matrix) {
for (int num : row) {
cout << num << " ";
}
cout << endl;
}
return 0;
}
|
import Card from "@/components/Card";
import Box from "@/components/p5/Art";
import { Context } from "@/components/Provider";
import GridDot from "@/components/ui/gridDot";
import { useBackButton, useMainButton, useViewport } from "@tma.js/sdk-react";
import React, { useContext, useEffect, useState } from "react";
export default function Art() {
const { userData, goPage } = useContext(Context);
const [revealed, setRevealed] = useState([false, false, false, false, false]);
useEffect(() => {
const timers: any = [];
for (let i = 0; i < revealed.length; i++) {
timers.push(
setTimeout(() => {
setRevealed((prev) => {
const newRevealed = [...prev];
newRevealed[i] = true;
return newRevealed;
});
}, i * 2000)
); // 每個Card延遲2秒顯示
}
return () => {
timers.forEach((timer: any) => clearTimeout(timer));
};
}, []);
type Strength = 'A LITTLE' | 'SOMEWHAT' | 'PRETTY' | 'VERY';
type Trait =
| 'INTROVERTED'
| 'EXTRAVERTED'
| 'PRAGMATIC'
| 'IDEALISTIC'
| 'RATIONAL'
| 'EMOTIONAL'
| 'METHODICAL'
| 'UNPREDICTABLE'
| 'INHERENT'
| 'MOLDED'
| 'ANCHORING'
| 'ADAPTABLE'
| 'PESSIMISTIC'
| 'OPTIMISTIC'
| 'RETROSPECTIVE'
| 'FORWARD-THINKING';
const traitMappings: Record<number, Trait[]> = {
1: ['INTROVERTED', 'EXTRAVERTED'],
2: ['PRAGMATIC', 'IDEALISTIC'],
3: ['RATIONAL', 'EMOTIONAL'],
4: ['METHODICAL', 'UNPREDICTABLE'],
5: ['INHERENT', 'MOLDED'],
6: ['ANCHORING', 'ADAPTABLE'],
7: ['PESSIMISTIC', 'OPTIMISTIC'],
8: ['RETROSPECTIVE', 'FORWARD-THINKING'],
};
interface TraitStrength {
trait: Trait;
strength: Strength;
}
const getStrength = (score: number): Strength => {
if (score <= 0.1) return 'A LITTLE';
if (score <= 0.4) return 'SOMEWHAT';
if (score <= 0.6) return 'PRETTY';
return 'VERY';
};
const [traits, setTraits] = useState<TraitStrength[]>([]);
useEffect(() => {
const initialTraits = userData.score.map((score, index) => {
const traitPair = traitMappings[index + 1];
const traitValue = score > 0.5 ? traitPair[1] : traitPair[0];
return {
trait: traitValue,
strength: getStrength(score),
};
});
setTraits(initialTraits);
}, [userData]);
const interpretation = traits.reduce((acc, trait, index) => {
const separator = index < traits.length - 1 ? ', ' : '.';
return `${acc}${trait.strength} <b>${trait.trait}</b>${separator} `;
}, '');
const userArg1 = userData.score[0] > 0.5 ? 'INTROVERT' : 'EXTRAVERT';
const userArg2 = userData.score[2] > 0.5 ? 'EMOTIONAL' : 'RATIONAL';
return (
<div className="relative flex h-full w-full flex-col items-center justify-between gap-1 p-1">
<div className="relative flex h-[382px] w-full cursor-pointer flex-col justify-end overflow-hidden rounded-lg bg-transparent uppercase hover:opacity-80">
{userData && userData.user_id && userData.score && (
<Box
userID={userData.user_id}
userScore={userData.score as any}
overScreen={true}
/>
)}
</div>
<Card
className={`flex flex-col items-start justify-start gap-4 p-12 transition-all delay-1000 duration-1000 ${revealed[0] ? "opacity-100" : "opacity-0"} ease-in-out`}
>
<GridDot count={8} />
{traits.length > 0 && (
<a
className="text-base tracking-[2.4px]"
dangerouslySetInnerHTML={{ __html: `THIS IS MY INTERPRETATION OF YOUR SYNTAX AS SOMEONE WHO IS ${interpretation}` }}
/>
)}
</Card>
<Card
className={`flex flex-col items-start justify-start gap-4 p-12 transition-all delay-1000 duration-1000 ${revealed[1] ? "opacity-100" : "opacity-0"} ease-in-out`}
>
<GridDot count={8} />
<a>THROUGH THE SAME SYNTAX, THIS IS HOW I WOULD HAVE SEEN YOU AS AN <b>{userArg1}</b>:</a>
</Card>
<div
className={`relative flex h-[382px] w-full cursor-pointer flex-col justify-end overflow-hidden rounded-lg bg-transparent uppercase delay-1000 duration-1000 hover:opacity-80 ${revealed[2] ? "opacity-100" : "opacity-0"} ease-in-out`}
>
{userData && userData.user_id && userData.score && (
<Box
userID={userData.user_id}
userScore={[userData.score[0] > 0.5 ? 0 : 1, ...userData.score.slice(1)]}
overScreen={true}
/>
)}
</div>
<Card
className={`flex flex-col items-start justify-start gap-4 p-12 delay-1000 duration-1000 ${revealed[3] ? "opacity-100" : "opacity-0"} ease-in-out`}
>
<GridDot count={8} />
<a>AND THIS IS HOW I WOULD HAVE SEEN YOU AS SOMEONE <b>{userArg2}</b>:</a>
</Card>
<div
className={`relative flex h-[382px] w-full cursor-pointer flex-col justify-end overflow-hidden rounded-lg bg-transparent uppercase delay-1000 duration-1000 hover:opacity-80 ${revealed[2] ? "opacity-100" : "opacity-0"} ease-in-out`}
>
{userData && userData.user_id && userData.score && (
<Box
userID={userData.user_id}
userScore={[...userData.score.slice(0, 2), userData.score[2] > 0.5 ? 0 : 1, ...userData.score.slice(3)]}
overScreen={true}
/>
)}
</div>
<div
className={`w-full space-y-1 delay-1000 duration-1000 ${revealed[4] ? "opacity-100" : "opacity-0"} ease-in-out`}
>
<div className="h-[62px] w-full">
<button
className="h-full w-full rounded-md border bg-white text-lg text-blackBg hover:border-white/20 hover:bg-white/80"
onClick={() => goPage("/")}
>
{"HOW DOES THIS WORK?"}
</button>
</div>
<div className="h-[62px] w-full">
<button
className="h-full w-full rounded-md border bg-white text-lg text-blackBg hover:border-white/20 hover:bg-white/80"
onClick={() => goPage("/")}
>
{"WHY DID YOU DO THIS?"}
</button>
</div>
<div className="h-[62px] w-full">
<button
className="h-full w-full rounded-md border bg-white text-lg text-blackBg hover:border-white/20 hover:bg-white/80"
onClick={() => goPage("/")}
>
{"WHAT ELSE IS THERE?"}
</button>
</div>
</div>
</div>
);
}
|
# Blog Application Backend
This project forms the backend of a blog application, leveraging Node.js, Express.js, and MongoDB. It supports user registration and login, creating and managing blog posts, and categorizing posts. Below are the details of the project's structure and functionalities.
## Project Structure
### Models
- **User Model (`User.js`)**: Defines the schema for users, including username, email, password, and profile picture.
- **Post Model (`Post.js`)**: Outlines the schema for blog posts, detailing the title, description, photo, username (author), and categories.
- **Category Model (`Category.js`)**: Specifies the schema for categories, simply comprising a name for each category.
### Routes
- **Authentication (`Auth.js`)**: Handles user registration and login, employing bcrypt for password hashing and validation.
- **User Management (`Users.js`)**: Supports updating and deleting user profiles, with additional functionality to retrieve user data by ID. Passwords are rehashed upon update if changed.
- **Post Management (`Posts.js`)**: Enables creating, updating, deleting, and fetching posts. Posts can be filtered by username or category through query parameters.
- **Category Management (`Categories.js`)**: Allows for adding new categories and retrieving all existing categories.
### Main Server File (`index.js`)
- Initializes and runs the Express.js server, setting up middleware for JSON parsing and routing.
- Establishes the MongoDB connection using Mongoose.
- Includes a route for file uploads using multer, demonstrating an approach to handling media in posts.
## Features
- **Secure Authentication**: Utilizes bcrypt for hashing and checking passwords, ensuring secure user authentication.
- **CRUD Operations**: Supports Create, Read, Update, and Delete operations for both posts and user profiles.
- **Dynamic Content Filtering**: Fetches posts based on specific criteria like username or category, allowing for dynamic content display.
- **File Upload**: Implements a basic file upload mechanism for adding photos to posts.
## Conclusion
This backend application provides a solid foundation for a blog platform, emphasizing security in user authentication, flexibility in content management, and simplicity in category handling. The modular structure facilitates easy expansion and integration with frontend technologies to create a full-stack application.
|
import { AiOutlineSearch } from "react-icons/ai";
import { RxCross1 } from "react-icons/rx";
import ActionLoader from "../../../Components/Loader/ActionLoader";
import Badge from "../../../Components/Badge/Badge";
import { useLazyGetArtistsQuery } from "../../../features/artist/artistApi";
import { useAssignCollabToDemoMutation } from "../../../features/demo/demoApi";
const AssignArtistToDemo = ({ demoId }) => {
const [getArtists, { data, isLoading }] = useLazyGetArtistsQuery();
const [assignCollabToDemo] = useAssignCollabToDemoMutation();
const handleSearch = (e) => {
if (e.key === "Enter") {
getArtists({ page: 1, search: e.target.value });
}
}
const handleAssign = (artistId) => {
assignCollabToDemo({
demoId,
artistId
})
.then(data => {
console.log(data);
})
}
return (
<div className="pt-8 relative">
{/* <RxCross1 size={20} className="absolute top-0 right-0 m-4 cursor-pointer" /> */}
<h4 className='font-semibold text-lg'>Add collaborators</h4>
<div className="mt-10">
<div className="flex justify-between items-center mb-5 gap-5">
<h5 className="text-xl font-bold border-b flex-grow pb-1">Artists</h5>
<div className="flex relative">
<input onKeyUp={handleSearch} type="search" name="search" className='border border-gray-300 py-2 w-60 pl-10 pr-3 outline-0 focus:ring-1 focus:ring-blue-500 focus:border-blue-500 text-sm rounded' placeholder='Search your artist here...' required />
<AiOutlineSearch className='w-6 h-6 text-gray-500 absolute top-1/2 -translate-y-1/2 left-2' />
</div>
</div>
{data?.results?.length && <ul className="h-64 overflow-y-auto shadow-md border">
{isLoading && <div className="flex justify-center mt-2">
<ActionLoader />
</div>}
{data?.results?.map(artist => <li onClick={() => handleAssign(artist.id)} className="hover:bg-gray-200 py-2 border-b flex items-center justify-between px-2">{artist.name} <Badge type="success" className="border border-green-200 cursor-pointer text-sm font-normal">Assign</Badge></li>)}
</ul>}
</div>
</div>
)
}
export default AssignArtistToDemo;
|
var app = require('../../../config/express.js'),
request = require('supertest')(app);
var async = require('async');
var dataService = require('../../create_data');
var chance = require('chance').Chance();
module.exports = function () {
describe('delete /interaction/activity/:interactionId/users/:userId', function () {
var accessToken =[];//分别为公司的第一,二,四人
var now = new Date();
var nowYear = now.getFullYear();
var nowMonth = now.getMonth();
var data;
before(function (done) {
data = dataService.getData();
async.parallel([
function(cb) {
request.post('/users/login')
.send({
phone: data[2].users[0].phone,
password: '55yali'
})
.end(function (err, res) {
if (err) return cb(err);
if (res.statusCode === 200) {
accessToken[0] = res.body.token;
}
cb()
});
},
function(cb) {
request.post('/users/login')
.send({
phone: data[2].users[1].phone,
password: '55yali'
})
.end(function (err, res) {
if (err) return cb(err);
if (res.statusCode === 200) {
accessToken[1] = res.body.token;
}
cb()
});
},function(cb) {
request.post('/users/login')
.send({
phone: data[2].users[3].phone,
password: '55yali'
})
.end(function (err, res) {
if (err) return cb(err);
if (res.statusCode === 200) {
accessToken[2] = res.body.token;
}
cb()
});
}
],
function(err, results) {
done(err)
});
});
it('应该成功退出公司活动', function (done) {
var user = data[2].users[1];
var interaction = data[2].activities[0];
request.delete('/interaction/activity/'+interaction.id+'/users/'+user.id)
.set('x-access-token', accessToken[1])
.expect(200)
.end(function (err, res) {
if (err) return done(err);
res.body.should.have.properties('activity');
done();
});
});
it('应该成功退出小队活动', function (done) {
var user = data[2].users[0];
var interaction = data[2].teams[0].activities[0];
request.delete('/interaction/activity/'+interaction.id+'/users/'+user.id)
.set('x-access-token', accessToken[0])
.expect(200)
.end(function (err, res) {
if (err) return done(err);
res.body.should.have.properties('activity');
done();
});
});
it('退出未参加的活动应该返回400', function (done) {
var user = data[2].users[3];
var interaction = data[2].activities[0];
request.delete('/interaction/activity/'+interaction.id+'/users/'+user.id)
.set('x-access-token', accessToken[2])
.expect(400)
.end(function (err, res) {
if (err) return done(err);
res.body.msg.should.equal('您还没有参加该活动');
done();
});
});
it('退出已经截止的活动应该返回400', function (done) {
var user = data[2].users[0];
var interaction = data[2].activities[3];
request.delete('/interaction/activity/'+interaction.id+'/users/'+user.id)
.set('x-access-token', accessToken[0])
.expect(400)
.end(function (err, res) {
if (err) return done(err);
res.body.msg.should.equal('活动报名已经截止,无法退出');
done();
});
});
it('活动Id格式错误应该返回500', function (done) {
var user = data[2].users[0];
var interaction = data[1].activities[0];
request.delete('/interaction/activity/124/users/'+user.id)
.set('x-access-token', accessToken[0])
.expect(500)
.end(function (err, res) {
if (err) return done(err);
res.body.msg.should.equal('服务器发生错误');
done();
});
});
it('退出不存在的活动错误应该返回404', function (done) {
var user = data[2].users[0];
var interaction = data[1].activities[0];
request.delete('/interaction/activity/54a90ba66c8100d54ce78316/users/'+user.id)
.set('x-access-token', accessToken[0])
.expect(404)
.end(function (err, res) {
if (err) return done(err);
res.body.msg.should.equal('该活动不存在');
done();
});
});
})
}
|
@extends('layouts.app')
@section('contain')
<section id="cart_items">
<div class="container col-sm-12">
<div class="breadcrumbs">
<ol class="breadcrumb">
<li><a href="#">Home</a></li>
<li class="active">Shopping Cart</li>
</ol>
</div>
<div class="table-responsive cart_info">
<?php
$contents= Cart::content();
?>
<table class="table table-condensed">
<thead>
<tr class="cart_menu">
<td class="image">Image</td>
<td class="description">Name</td>
<td class="quantity">Quantity</td>
<td class="price">Price</td>
<td class="total">Total</td>
<td></td>
<td class="action">Action</td>
<td></td>
</tr>
</thead>
<tbody>
@foreach($contents as $datas)
<tr>
<td class="cart_product">
<a href=""><img src="{{url($datas->options->image)}}" style="height: 80px;width: 80px;" alt=""></a>
</td>
<td class="cart_description">
<h4><a href="">{{$datas->name}}</a></h4>
</td>
<td class="cart_price">
<p>{{$datas->price}}</p>
</td>
<td class="cart_quantity">
<div class="cart_quantity_button">
<form action="{{url('/update_cart')}}" method="post">
{{csrf_field()}}
<input class="cart_quantity_input" type="text" name="quantity" value="{{$datas->qty}}" autocomplete="off" size="2">
<input type="hidden" name="rowId" value="{{$datas->rowId}}">
<input type="submit" value="update" class="btn btn-default">
</form>
</div>
</td>
<td class="cart_total">
<p class="cart_total_price">{{$datas->total}}</p>
</td>
<td class="cart_delete">
<a class="cart_quantity_delete" href="{{url('/delete_cart_item/'.$datas->rowId)}}"><i class="fa fa-times"></i></a>
</td>
</tr>
@endforeach
</tbody>
</table>
</div>
</div>
</section> <!--/#cart_items-->
<section id="do_action">
<div class="row">
<!--
<div class="col-sm-6">
<div class="chose_area">
<ul class="user_option">
<li>
<input type="checkbox">
<label>Use Coupon Code</label>
</li>
<li>
<input type="checkbox">
<label>Use Gift Voucher</label>
</li>
<li>
<input type="checkbox">
<label>Estimate Shipping & Taxes</label>
</li>
</ul>
<ul class="user_info">
<li class="single_field">
<label>Country:</label>
<select>
<option>United States</option>
<option>Bangladesh</option>
<option>UK</option>
<option>India</option>
<option>Pakistan</option>
<option>Ucrane</option>
<option>Canada</option>
<option>Dubai</option>
</select>
</li>
<li class="single_field">
<label>Region / State:</label>
<select>
<option>Select</option>
<option>Dhaka</option>
<option>London</option>
<option>Dillih</option>
<option>Lahore</option>
<option>Alaska</option>
<option>Canada</option>
<option>Dubai</option>
</select>
</li>
<li class="single_field zip-field">
<label>Zip Code:</label>
<input type="text">
</li>
</ul>
<a class="btn btn-default update" href="">Get Quotes</a>
<a class="btn btn-default check_out" href="">Continue</a>
</div>
</div>
-->
<div class="col-sm-12">
<div class="total_area">
<ul>
<li>Cart Sub Total <span>{{Cart::subtotal()}}</span></li>
<li>Eco Tax <span>{{Cart::tax()}}</span></li>
<li>Shipping Cost <span>Free</span></li>
<li>Total <span>{{Cart::total()}}</span></li>
</ul>
<?php $customer_id=Session::get('customer_id');
?>
@if($customer_id !=NULL)
<a class="btn btn-default check_out" href="{{url('/chechout')}}">Check Out</a>
@else
<a class="btn btn-default check_out" href="{{url('/login_check')}}">Check Out</a>
@endif
</div>
</div>
</div>
</div>
</section>
@endsection
|
import { FC, useState } from 'react';
import { Input } from '../../../../shared/infrastructure/components/ui/input/Input';
import { Button } from '../../../../shared/infrastructure/components/ui/button/Button';
import AuthUserEmail from '../../../domain/AuthUserEmail';
import AuthUserPassword from '../../../domain/AuthUserPassword';
import { Loading } from '../../../../shared/infrastructure/components/ui/loading/Loading';
type AuthenticateViewProps = {
onAuthenticate: (email: AuthUserEmail, password: AuthUserPassword) => void,
loading: boolean,
error?: string,
}
export const AuthenticateView: FC<AuthenticateViewProps> = ({ onAuthenticate, loading, error }) => {
const [email, setEmail] = useState('')
const [password, setPassword] = useState('')
const isValidForm = (): boolean => {
try {
new AuthUserEmail(email) && new AuthUserPassword(password);
return true
} catch (_) {
return false;
}
}
const handleLogin = () => {
if (isValidForm()) {
onAuthenticate(new AuthUserEmail(email), new AuthUserPassword(password))
}
}
return (
<>
<div>
<form onSubmit={(event) => {
event.preventDefault()
handleLogin()
}}>
<Input
value={email}
onChange={setEmail}
type={'email'}
placeholder={'Email'}
/>
<Input
value={password}
onChange={setPassword}
type={'password'}
placeholder={'password'}
/>
<Button
disabled={!isValidForm()}
type={'submit'}
>Acceder</Button>
{error && <p>{error}</p>}
</form>
</div>
<Loading loading={loading}/>
</>
)
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.