text stringlengths 184 4.48M |
|---|
<template>
<div class="table-responsive">
<table class="table">
<tr>
<th style="width: 20%;">Title</th>
<td>{{taskInfo.title}}</td>
</tr>
<tr>
<th style="width: 20%;">Priority</th>
<td>
<span :class="`badge ${taskInfo.priority == 'Urgent' ? 'bg-danger' : 'bg-success'}`">
{{taskInfo.priority}}
</span>
</td>
</tr>
<tr>
<th style="width: 20%;">Start Date</th>
<td>{{taskInfo.start_date}}</td>
</tr>
<tr>
<th style="width: 20%;">End Date</th>
<td>{{taskInfo.end_date}}</td>
</tr>
<tr>
<th style="width: 20%;">Description</th>
<td>{{taskInfo.description}}</td>
</tr>
<tr>
<th style="width: 20%;">Assigned To</th>
<td>
<span :class="`badge bg-dark mx-1`" v-for="(user, index) in taskInfo.users" :key="index">
{{user.name}}
</span>
</td>
</tr>
<tr>
<th style="width: 20%;">Status</th>
<td>
<p v-if="taskInfo.progress == 0" class="text-danger">No Progress</p>
<p v-if="taskInfo.progress > 0 && taskInfo.progress < 100" class="text-warning">Under Progress</p>
<p v-if="taskInfo.progress == 100" class="text-success">Completed</p>
</td>
</tr>
<tr>
<th style="width: 20%;">Performed By</th>
<td>
<p>
{{(taskInfo.performed_by !== 0 ? taskInfo.performed_by_user?.name : '...')}}
</p>
</td>
</tr>
<tr>
<th style="width: 20%;">Progress</th>
<td>
<p>
{{taskInfo.progress}} %
</p>
</td>
</tr>
<tr>
<th style="width: 20%;">Result</th>
<td>
<p>
{{taskInfo.result ? taskInfo.result : 'No results yet!'}}
</p>
</td>
</tr>
<tr>
<th style="width: 20%;">Task File</th>
<td>
<a :href="`${url}public/tasks/${taskInfo.file}`" target="_blank" class="btn btn-success text-dark" v-if="taskInfo.file">
<i class="fa fa-download"></i>
</a>
<p v-else>No file uploaded yet!</p>
</td>
</tr>
</table>
</div>
</template>
<script>
export default {
props: ['taskInfo'],
data() {
return {
url: '',
}
},
mounted() {
this.url = window.url
}
}
</script> |
/*
This file is part of libkabc.
Copyright (c) 2004 Tobias Koenig <tokoe@kde.org>
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Library General Public
License as published by the Free Software Foundation; either
version 2 of the License, or (at your option) any later version.
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; see the file COPYING.LIB. If not, write to
the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
Boston, MA 02110-1301, USA.
*/
#ifndef KABC_SORTMODE_H
#define KABC_SORTMODE_H
#include "kabc_export.h"
#include "addressee.h"
namespace KABC {
class Field;
/**
@short Sort method for sorting an addressee list.
This interface should be reimplemented by classes which shall act as
SortModes for KABC::AddresseeList.
*/
class KABC_EXPORT SortMode
{
public:
virtual ~SortMode();
/**
Reimplement this method and return whether the first contact is 'smaller'
than the second.
*/
virtual bool lesser( const KABC::Addressee &first, const KABC::Addressee &second ) const = 0;
};
/**
@short Implements comparison by name.
This class implements a comparison of two Addressee objects by name.
*/
class KABC_EXPORT NameSortMode : public SortMode
{
public:
/**
Specifies which parts of the name are used for comparison.
*/
enum NameType {
FormattedName, /**< use the formatted name, e.g. "John Doe" */
FamilyName, /**< use the last name, e.g. "Doe" */
GivenName /**< use the first name, e.g. "John" */
};
/**
Constructor.
Creates a NameSortMethod with FormattedName as name type set.
*/
NameSortMode();
/**
Constructor.
Creates a NameSortMethod with the specified name type.
@param type The name type.
@param ascending if @c true, Addressee object are sorted in
ascending order; if @c false, objects are sorted in
descending order
*/
explicit NameSortMode( NameType type, bool ascending = true );
virtual ~NameSortMode();
/**
Returns whether the first contact is 'smaller' then the second.
*/
virtual bool lesser( const KABC::Addressee &first, const KABC::Addressee &second ) const;
private:
class Private;
Private *const d;
Q_DISABLE_COPY( NameSortMode )
};
/**
@short Implements comparison by an arbitrary field.
This class implements a comparison of two Addressee objects by the
value of an arbitrary field.
*/
class KABC_EXPORT FieldSortMode : public SortMode
{
public:
/**
Constructor.
Creates a FieldSortMethod with the specified @p field.
@param field The field.
@param ascending if @c true, Addressee object are sorted in
ascending order; if @c false, objects are sorted in
descending order
*/
explicit FieldSortMode( KABC::Field *field, bool ascending = true );
virtual ~FieldSortMode();
/**
Returns whether the first contact is 'smaller' then the second.
*/
virtual bool lesser( const KABC::Addressee &first, const KABC::Addressee &second ) const;
private:
class Private;
Private *const d;
Q_DISABLE_COPY( FieldSortMode )
};
}
#endif |
<!--
* @Descripttion:
* @version:
* @Author: by_mori
* @Date: 2021-09-25 23:09:37
* @LastEditors: by_mori
* @LastEditTime: 2021-09-26 10:48:22
-->
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>拦截器</title>
<!-- <script src="https://cdn.bootcdn.net/ajax/libs/axios/0.21.1/axios.min.js"></script> -->
</head>
<body>
<script>
//构造函数
function Axios(config) {
this.config = config;
this.interceptors = {
request: new InterceptorManager(),
response: new InterceptorManager(),
};
}
//发送请求 难点与重点
Axios.prototype.request = function (config) {
//创建一个 promise 对象
let promise = Promise.resolve(config);
//创建一个数组
const chains = [dispatchRequest, undefined];
//处理拦截器
//请求拦截器 将请求拦截器的回调 压入到 chains 的前面 request.handles = []
this.interceptors.request.handlers.forEach((item) => {
chains.unshift(item.fulfilled, item.rejected);
});
//响应拦截器
this.interceptors.response.handlers.forEach((item) => {
chains.push(item.fulfilled, item.rejected);
});
// console.log(chains);
//遍历
while (chains.length > 0) {
promise = promise.then(chains.shift(), chains.shift());
}
return promise;
};
//发送请求
function dispatchRequest(config) {
// 返回一个 promise对象
return new Promise((resolve, reject) => {
resolve({
status: 200,
statusText: 'OK',
});
});
}
//创建实例
let context = new Axios({});
//创建axios函数
let axios = Axios.prototype.request.bind(context);
//将 context 属性 config interceptors 添加至 axios 函数对象身上
Object.keys(context).forEach((key) => {
axios[key] = context[key];
});
// console.dir(axios);
//拦截器管理器 构造函数
function InterceptorManager() {
this.handlers = [];
}
InterceptorManager.prototype.use = function (fulfilled, rejected) {
this.handlers.push({
fulfilled,
rejected,
});
};
//以下为功能测试代码
axios.interceptors.request.use(
function one(config) {
console.log('请求拦截器 成功 - 1号');
//修改 config 中的参数
// config.params = { a: 100 };
return config;
},
function one(error) {
console.log('请求拦截器 失败 - 1号');
return Promise.reject(error);
}
);
axios.interceptors.request.use(
function two(config) {
console.log('请求拦截器 成功 - 2号');
//修改 config 中的参数
// config.timeout = 1000;
return config;
},
function two(error) {
console.log('请求拦截器 失败 - 2号');
return Promise.reject(error);
}
);
// 设置响应拦截器
axios.interceptors.response.use(
function (response) {
console.log('响应拦截器 成功 1号');
console.log(response.data);
// return response.data;
return response;
},
function (error) {
console.log('响应拦截器 失败 1号');
return Promise.reject(error);
}
);
axios.interceptors.response.use(
function (response) {
console.log('响应拦截器 成功 2号');
// return response.data;
return response;
},
function (error) {
console.log('响应拦截器 失败 2号');
return Promise.reject(error);
}
);
console.dir(axios);
//发送请求
axios({
method: 'GET',
url: 'http://localhost:3000/posts',
}).then((response) => {
console.log(response);
});
</script>
</body>
</html> |
from turtle import Turtle
class Snake(object):
def __init__(self) -> None:
self.XCORR = 0
self.yCORR = 0
self.segments = []
for i in range(3):
t = Turtle(shape='square')
t.penup()
t.color('Spring Green')
t.setpos(x=self.XCORR, y=self.yCORR)
self.XCORR -= 20
print(t.speed())
self.segments.append(t)
self.snakeHead = self.segments[0]
self.snakeTail = self.segments[-1]
print(self.snakeHead.pos())
def addSegment(self):
t = Turtle(shape='square')
t.penup()
t.color('Spring Green')
new_x = self.segments[-1].xcor()
new_y = self.segments[-1].ycor()
t.setpos(x=new_x, y=new_y)
self.segments.append(t)
def move(self):
for snakeSeg in range(len(self.segments)-1, 0, -1):
new_x = self.segments[snakeSeg-1].xcor()
new_y = self.segments[snakeSeg-1].ycor()
self.segments[snakeSeg].goto(new_x,new_y)
self.snakeHead.fd(20)
def detectWallCollision(self):
if (self.snakeHead.xcor() > 300 or self.snakeHead.xcor() < -300):
return True
elif (self.snakeHead.ycor() > 300 or self.snakeHead.ycor() < -300):
return True
return False
def detectSelfCollision(self):
for segment in self.segments[1:]:
if (self.snakeHead.distance(segment) < 5):
return True
return False
def detectCollission(self):
return (self.detectWallCollision() or self.detectSelfCollision())
# Change direction to right
def Right(self):
if self.snakeHead.heading() != 180:
self.snakeHead.setheading(0)
# change direction to left
def Left(self):
if self.snakeHead.heading() != 0:
self.snakeHead.setheading(180)
# Change direction to up
def Up(self):
if self.snakeHead.heading() != 270:
self.snakeHead.setheading(90)
# Change direction to down
def Down(self):
if self.snakeHead.heading() != 90:
self.snakeHead.setheading(270) |
import React, { useState } from "react";
import { MdEdit } from "react-icons/md";
import AdminEditProduct from "./AdminEditProduct";
function AdminProductCard({ data, fetchData }) {
const [editProduct, setEditProduct] = useState(false);
return (
<div className="bg-white p-4 rounded-lg mt-2 h-64">
<div className="w-32 h-full flex flex-col justify-between">
<div className="w-28 h-28 flex items-center mx-auto">
<img
className="h-full w-full hover:scale-125 cursor-pointer rounded-lg mx-auto object-fill"
src={data?.productImage[0]}
/>
</div>
<h1 className="text-center mt-2 text-ellipsis line-clamp-2 text-black">
{data.productName}
</h1>
<div className="flex justify-center items-center">
<p className="font-semibold text-center text-black">
₹ {data?.price}.00
</p>
<div
onClick={() => setEditProduct(true)}
className="w-fit ml-auto p-2 bg-orange-100 rounded-full hover:bg-orange-200 cursor-pointer"
>
<MdEdit className="text-black hover:scale-125" />
</div>
</div>
</div>
{editProduct && (
<AdminEditProduct
fetchData={fetchData}
productData={data}
onClose={() => setEditProduct(false)}
/>
)}
</div>
);
}
export default AdminProductCard; |
// Copyright (c) 2013 Dougrist Productions
//
// 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.
//
// Author: Benjamin Crist
// File: carcassonne/gui/button.cc
#include "carcassonne/gui/button.h"
namespace carcassonne {
namespace gui {
Button::Button()
: state_(STATE_NORMAL),
text_scale_(1.0f),
text_y_offset_(0.0f),
font_(nullptr)
{
}
Button::Button(const Button& other)
: state_(other.state_),
drawing_plane_(other.drawing_plane_),
event_plane_(other.event_plane_),
text_(other.text_),
text_scale_(other.text_scale_),
text_y_offset_(other.text_y_offset_),
font_(other.font_),
action_(other.action_)
{
for (int i = 0; i < 3; ++i)
{
background_[i] = other.background_[i];
text_color_[i] = other.text_color_[i];
}
}
Button& Button::operator=(const Button& other)
{
state_ = other.state_;
drawing_plane_ = other.drawing_plane_;
event_plane_ = other.event_plane_;
text_ = other.text_;
text_scale_ = other.text_scale_;
text_y_offset_ = other.text_y_offset_;
font_ = other.font_;
action_ = other.action_;
for (int i = 0; i < 3; ++i)
{
background_[i] = other.background_[i];
text_color_[i] = other.text_color_[i];
}
return *this;
}
void Button::setDrawingPlane(const gfx::Rect& rect)
{
drawing_plane_ = rect;
}
void Button::setEventPlane(const gfx::Rect& rect)
{
event_plane_ = rect;
}
void Button::setSprite(State state, const gfx::Sprite& sprite)
{
background_[static_cast<unsigned int>(state)] = sprite;
}
void Button::setTextColor(State state, const glm::vec4& color)
{
text_color_[static_cast<unsigned int>(state)] = color;
}
void Button::setTextScale(float scale)
{
text_scale_ = scale;
}
void Button::setTextYOffset(float offset)
{
text_y_offset_ = offset;
}
void Button::setText(const std::string& content)
{
text_ = content;
}
void Button::setFont(gfx::TextureFont* font)
{
font_ = font;
}
void Button::setAction(const std::function<void()>& action)
{
action_ = action;
}
void Button::onHover(const glm::vec3& coords)
{
if (checkEventPlane(coords))
state_ = STATE_HOVERED;
else
state_ = STATE_NORMAL;
}
void Button::onLeftDown(const glm::vec3& coords)
{
if (checkEventPlane(coords))
state_ = STATE_ACTIVE;
}
void Button::onLeftDrag(const glm::vec3& coords, const glm::vec3& down_coords)
{
if (checkEventPlane(coords) && checkEventPlane(down_coords))
state_ = STATE_ACTIVE;
else
state_ = STATE_NORMAL;
}
void Button::onLeftUp(const glm::vec3& coords, const glm::vec3& down_coords)
{
if (checkEventPlane(coords))
{
state_ = STATE_HOVERED;
if (checkEventPlane(down_coords) && action_)
action_();
}
}
void Button::onLeftCancel(const glm::vec3& coords, const glm::vec3& down_coords)
{
if (checkEventPlane(coords))
state_ = STATE_HOVERED;
}
/*void Button::update()
{
}*/
void Button::draw()
{
unsigned int state = static_cast<unsigned int>(state_);
glPushMatrix();
glTranslatef(drawing_plane_.left(), drawing_plane_.top(), 0);
//glScalef(drawing_plane_.width(), drawing_plane_.height(), 0);
gfx::Texture::disableAny();
glDisable(GL_CULL_FACE);
glDisable(GL_DEPTH_TEST);
//glColor3f(1,0,0);
//glRectf(0, 0, drawing_plane_.width(), drawing_plane_.height());
//background_[state].draw();
glTranslatef(0, text_y_offset_, 0);
glScalef(text_scale_, text_scale_, 1);
glColor4fv(glm::value_ptr(text_color_[state]));
if (font_)
font_->print(text_, GL_MODULATE);
glPopMatrix();
}
bool Button::checkEventPlane(const glm::vec3& coords) const
{
return coords.x >= event_plane_.left() && coords.x < event_plane_.right() &&
coords.y >= event_plane_.top() && coords.y < event_plane_.bottom();
}
} // namespace carcassonne::gui
} // namespace carcassonne |
import * as request from 'supertest';
import { omit } from 'lodash';
import { HttpStatus, INestApplication } from '@nestjs/common';
import { createTestApplication } from '@app/tests/utils/helpers.utils';
import { UserEntity } from '@app/entities';
import { ProfessionEnum } from '@app/enum';
describe('UserController', () => {
let app: INestApplication;
const createUserInfo = {
name: 'name',
password: 'password',
email: 'email@example.com',
profession: ProfessionEnum.DEVELOPER
};
beforeEach(async () => {
await UserEntity.clear();
});
beforeAll(async () => {
app = await createTestApplication();
});
describe('POST /users', () => {
describe('with invalid email', () => {
it('should return validation error', async () => {
const errorResponse: request.Response = await request(app.getHttpServer())
.post('/users')
.send({
user: {
...createUserInfo,
email: null
}
})
.expect(HttpStatus.BAD_REQUEST);
expect(errorResponse.text).toMatchInlineSnapshot(
`"{"statusCode":400,"message":["email must be an email","email should not be empty"],"error":"Bad Request"}"`
);
});
});
describe('with invalid password', () => {
it('should return validation error', async () => {
const errorResponse: request.Response = await request(app.getHttpServer())
.post('/users')
.send({
user: {
...createUserInfo,
password: null
}
})
.expect(HttpStatus.BAD_REQUEST);
expect(errorResponse.text).toMatchInlineSnapshot(`"{"statusCode":400,"message":["password should not be empty"],"error":"Bad Request"}"`);
});
});
describe('with invalid name', () => {
it('should return validation error', async () => {
const errorResponse: request.Response = await request(app.getHttpServer())
.post('/users')
.send({
user: {
...createUserInfo,
name: null
}
})
.expect(HttpStatus.BAD_REQUEST);
expect(errorResponse.text).toMatchInlineSnapshot(`"{"statusCode":400,"message":["name should not be empty"],"error":"Bad Request"}"`);
});
});
describe('with invalid profession', () => {
it('should return validation error', async () => {
const errorResponse: request.Response = await request(app.getHttpServer())
.post('/users')
.send({
user: {
...createUserInfo,
profession: null
}
})
.expect(HttpStatus.BAD_REQUEST);
expect(errorResponse.text).toMatchInlineSnapshot(
`"{"statusCode":400,"message":["profession must be one of the following values: DEVELOPER, PRODUCT_MANAGER, DESIGNER, OTHERS","profession should not be empty"],"error":"Bad Request"}"`
);
});
});
describe('with email in use', () => {
it('should return EMAIL_IN_USE', async () => {
await request(app.getHttpServer()).post('/users').send({
user: createUserInfo
});
const errorResponse: request.Response = await request(app.getHttpServer())
.post('/users')
.send({
user: {
...createUserInfo
}
})
.expect(HttpStatus.CONFLICT);
expect(errorResponse.text).toMatchInlineSnapshot(`"{"statusCode":409,"message":"EMAIL_IN_USE"}"`);
});
});
describe('with valid data and email is not in use', () => {
it('should return the user created', async () => {
const response: request.Response = await request(app.getHttpServer())
.post('/users')
.send({
user: createUserInfo
})
.expect(HttpStatus.CREATED);
expect(response.body).toHaveProperty('token');
expect(response.body).toMatchObject(omit(createUserInfo, ['password']));
});
});
});
describe('GET /users', () => {
describe('without token', () => {
it('should return the unauthorized error', async () => {
const { body: errorResponse }: request.Response = await request(app.getHttpServer()).get('/users').expect(HttpStatus.UNAUTHORIZED);
expect(errorResponse.message).toMatchInlineSnapshot(`"UNAUTHORIZED"`);
});
});
describe('with token of a non existent or deleted user', () => {
it('should return the unauthorized error', async () => {
const { body } = await request(app.getHttpServer()).post('/users').send({ user: createUserInfo }).expect(HttpStatus.CREATED);
await UserEntity.update(body.id, { is_deleted: true });
const { body: errorResponse }: request.Response = await request(app.getHttpServer())
.get('/users')
.set('Authorization', `Bearer ${body.token}`)
.expect(HttpStatus.UNAUTHORIZED);
expect(errorResponse.message).toMatchInlineSnapshot(`"UNAUTHORIZED"`);
});
});
});
describe('PUT /users', () => {
describe('without token', () => {
it('should return the unauthorized error', async () => {
const { body: errorResponse }: request.Response = await request(app.getHttpServer()).put('/users').expect(HttpStatus.UNAUTHORIZED);
expect(errorResponse.message).toMatchInlineSnapshot(`"UNAUTHORIZED"`);
});
});
describe('with token of a non existent or deleted user', () => {
it('should return the unauthorized error', async () => {
const { body } = await request(app.getHttpServer()).post('/users').send({ user: createUserInfo }).expect(HttpStatus.CREATED);
await UserEntity.update(body.id, { is_deleted: true });
const { body: errorResponse }: request.Response = await request(app.getHttpServer())
.put('/users')
.set('Authorization', `Bearer ${body.token}`)
.expect(HttpStatus.UNAUTHORIZED);
expect(errorResponse.message).toMatchInlineSnapshot(`"UNAUTHORIZED"`);
});
});
describe('with valid data', () => {
describe('and the email is in use', () => {
it('should return EMAIL_IN_USE error', async () => {
await request(app.getHttpServer()).post('/users').send({ user: createUserInfo }).expect(HttpStatus.CREATED);
const { body: secondUserResponse } = await request(app.getHttpServer())
.post('/users')
.send({ user: { ...createUserInfo, email: 'new-email@example.com' } })
.expect(HttpStatus.CREATED);
const { body: errorResponse }: request.Response = await request(app.getHttpServer())
.put('/users')
.send({ user: createUserInfo })
.set('Authorization', `Bearer ${secondUserResponse.token}`)
.expect(HttpStatus.CONFLICT);
expect(errorResponse.message).toMatchInlineSnapshot(`"EMAIL_IN_USE"`);
});
});
describe('and email is not in use', () => {
it('should return the user updated', async () => {
const { body: userResponse } = await request(app.getHttpServer()).post('/users').send({ user: createUserInfo }).expect(HttpStatus.CREATED);
const { body: updateResponse }: request.Response = await request(app.getHttpServer())
.put('/users')
.send({ user: createUserInfo })
.set('Authorization', `Bearer ${userResponse.token}`)
.expect(HttpStatus.OK);
expect(updateResponse).toMatchObject(omit(createUserInfo, ['password']));
});
});
});
});
}); |
import { useState } from 'react';
import {
Container,
Space,
TextInput,
PasswordInput,
Button,
Alert
} from '@mantine/core';
import { useForm } from '@mantine/form';
export default function Login({ setToken, setTab }) {
const [alertOpen, setAlertOpen] = useState(false);
const [isLogging, setIsLogging] = useState(false);
const form = useForm({
initialValues: {
username: '',
password: '',
},
validate: {
username: (value) => (value === '' ? "Username cannot be emtpy" : null),
// password: (value) => (value === '' ? "Password cannot be empty" : null),
password: (value) => value === '',
},
});
async function loginUser(credentials) {
const fd = new FormData()
fd.append('username', credentials.username);
fd.append('password', credentials.password)
console.log("Trying log in...")
return fetch('https://acro-events.onrender.com/api/auth/login', {
method: 'POST',
// headers: {
// 'Content-Type': 'application/json'
// },
// body: JSON.stringify(credentials)
body: fd,
}).then(data => data.json())
// })
}
async function handleSubmit(e) {
e.preventDefault();
// console.log('Submitting with values', username, password);
// console.log(form.getInputProps())
// console.log(form.getInputProps('name'))
// console.log(form.values)
const {username, password} = form.values
form.validate()
console.log(username, password, form.isValid())
if (!form.isValid()) {
console.log("invalid credentials")
return
}
setIsLogging(true);
const res = await loginUser({
username,
password
});
setIsLogging(false);
setAlertOpen(!res.success);
if (res.success) {
setTab('timeline');
}
console.log('Done with log in process')
console.log("Received token is ", res.token);
setToken(res);
}
return (
<>
{ alertOpen && (
<Alert title="Invalid Credentials!" color="yellow">
Username or password is incorrect. Please try again
</Alert>
)}
<Container py="xl" size="xs">
<form onSubmit={handleSubmit}>
<TextInput
placeholder="Enter your username"
label="Username"
withAsterisk
{...form.getInputProps('username')}
/>
<Space h='md' />
<PasswordInput
placeholder="Password"
label="Password"
withAsterisk
{...form.getInputProps('password')}
/>
<Space h='md' />
<Button type="submit" variant="outline" uppercase
onClick={handleSubmit}
disabled={isLogging}
>
Submit
</Button>
</form>
</Container>
</>
)
} |
import fs from 'fs';
import yargs from 'yargs';
import { mkdirpSync } from 'fs-extra';
import path from 'path';
import convertPythonModel from './convert-python-model';
import { getString } from './prompt/getString';
import { ifDefined } from './prompt/ifDefined';
import { ProgressBar } from './utils/ProgressBar';
/****
* Type Definitions
*/
/****
* Constants
*/
const ROOT_DIR = path.resolve(__dirname, '../..');
const MODELS_FOLDER = path.resolve(ROOT_DIR, 'models');
/****
* Utility Functions
*/
const filterReadDir = (file: string) => {
return !['.DS_Store'].includes(file);
};
const readModelDirectory = (root: string, folder = '') => {
const files: string[] = [];
const dirToRead = path.resolve(root, folder);
for (const file of fs.readdirSync(dirToRead)) {
if (filterReadDir(file)) {
const relativefilepath = path.join(folder, file);
const fullfilepath = path.resolve(root, folder, file);
if (fs.lstatSync(fullfilepath).isDirectory()) {
for (const child of readModelDirectory(root, relativefilepath)) {
files.push(child);
}
} else {
files.push(relativefilepath);
}
}
}
return files;
}
const filterFiles = (files: string[]) => {
return files.filter(file => (file.endsWith('.h5')) && !file.includes('srgan'));
}
const convertStringToExport = (name: string) => {
const parts = name.split('-');
return parts.slice(1).filter(Boolean).reduce((str, part) => {
return `${str}${part[0].toUpperCase()}${part.slice(1)}`;
}, parts[0]);
}
const getModelInfo = (file: string) => {
const parts = file.split('/');
const folder = parts[0];
const weight = parts.pop();
const params = folder.split('-');
const architecture = params[0];
const scale = params[6][1];
const dataset = params[10].split('data').pop();
let exportName = convertStringToExport(`${folder.split('patch')[0]}-${weight?.split('vary_cFalse').pop()?.split('_').join('-').split('.')[0]}-data${dataset}`);
let size;
if (exportName.startsWith('rdnC1D2G4G064T10')) {
size = 'small';
exportName = `small${exportName.slice(16)}`;
}
if (exportName.startsWith('rdnC1D10G64G064T10')) {
size = 'medium';
exportName = `medium${exportName.slice(18)}`;
}
if (exportName.startsWith('rrdn')) {
size = 'large';
exportName = `large${exportName.slice(18)}`;
}
const modelPath = `models/${file}/${weight?.split('.')[0]}/model.json`;
return { exportName, scale, meta: {
scale: parseInt(scale, 10),
architecture,
C: parseInt(params[1].slice(1), 10),
D: parseInt(params[2].slice(1), 10),
G: parseInt(params[3].slice(1), 10),
G0: parseInt(params[4].slice(2), 10),
T: parseInt(params[5].slice(1), 10),
patchSize: parseInt(`${params[7].split('patchsize').pop()}`, 10),
compress: parseInt(`${params[8].split('compress').pop()}`, 10),
sharpen: parseInt(`${params[9].split('sharpen').pop()}`, 10),
dataset,
varyCompression: params[11].split('vary_c').pop(),
size,
}, architecture, modelPath};
}
const updateIndex = (folder: string, files: string[], shouldClearOutExports?: boolean) => {
const packageJSONPath = path.resolve(folder, 'package.json');
const packageJSON = JSON.parse(fs.readFileSync(packageJSONPath, 'utf-8'));
if (shouldClearOutExports === true) {
packageJSON['exports'] = {};
}
packageJSON['exports'] = {
...packageJSON['exports'],
".": {
"require": `./dist/cjs/index.js`,
"import": `./dist/esm/index.js`
}
};
const umdPath = path.resolve(folder, 'umd-names.json');
const umdNames: Record<string, string> = {};
const index: string[] = [];
files.forEach(file => {
const { exportName, scale, meta, architecture, modelPath } = getModelInfo(file);
const indexPath = path.resolve(folder, `src/models/esrgan/${exportName}.ts`);
mkdirpSync(path.dirname(indexPath));
fs.writeFileSync(indexPath, `
import getModelDefinition from '../../utils/getModelDefinition';
const ${exportName} = getModelDefinition(${scale}, '${architecture}', '${modelPath}', ${JSON.stringify(meta, null, 2)});
export default ${exportName};
`.trim(), 'utf-8');
packageJSON['exports'] = {
...packageJSON['exports'],
[`./models/esrgan/${exportName}`]: {
"require": `./dist/cjs/models/esrgan/${exportName}.js`,
"import": `./dist/esm/models/esrgan/${exportName}.js`
},
};
umdNames[`./models/esrgan/${exportName}`] = `${exportName}`;
fs.writeFileSync(packageJSONPath, JSON.stringify(packageJSON, null, 2), 'utf-8');
fs.writeFileSync(umdPath, JSON.stringify(umdNames, null, 2), 'utf-8');
index.push(`export { default as ${exportName}, } from './models/esrgan/${exportName}';`);
});
fs.writeFileSync(path.resolve(folder, 'src/index.ts'), index.join('\n'), 'utf-8')
}
/****
* Main function
*/
const convertPythonModelFolder = async (folder: string, outputModel: string, convertModels = true, shouldClearOutExports?: boolean) => {
const files = filterFiles(readModelDirectory(folder));
const progressBar = new ProgressBar(files.length)
const outputModelFolder = path.resolve(MODELS_FOLDER, outputModel);
for (const file of files) {
const fullfilepath = path.resolve(folder, file);
const outputDirectory = path.resolve(outputModelFolder, 'models', file);
if (convertModels) {
await convertPythonModel(fullfilepath, outputDirectory);
}
progressBar.update();
}
progressBar.end();
updateIndex(outputModelFolder, files, shouldClearOutExports);
};
/****
* Functions to expose the main function as a CLI tool
*/
type Answers = {
modelFolder: string;
outputModel: string;
skipConvertModels?: boolean;
shouldClearOutExports?: boolean;
}
const getArgs = async (): Promise<Answers> => {
const argv = await yargs.command('convert-python-model-folder', 'convert folder', yargs => {
yargs.positional('folder', {
describe: 'The folder containing models',
}).positional('output', {
describe: 'The output model folder to write to',
}).options({
skipConvertModels: { type: 'boolean' },
shouldClearOutExports: { type: 'boolean' },
});
})
.help()
.argv;
const modelFolder = await getString('What is the folder containing the models you wish to convert?', argv._[0]);
const outputModel = await getString('What is the folder you wish to write to? (Specify a non-absolute path, it will be placed in the models directory)', argv._[1]);
return {
skipConvertModels: ifDefined(argv, 'skipConvertModels', 'boolean'),
shouldClearOutExports: ifDefined(argv, 'shouldClearOutExports', 'boolean'),
outputModel,
modelFolder
};
}
if (require.main === module) {
(async () => {
const { modelFolder, outputModel, skipConvertModels } = await getArgs();
await convertPythonModelFolder(modelFolder, outputModel, skipConvertModels !== true, shouldClearOutExports);
})();
} |
package com.master.controller;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.UUID;
import org.jdbi.v3.core.Jdbi;
import com.master.MasterConfiguration;
import com.master.api.ApiResponse;
import com.master.client.LinkageNwService;
import com.master.core.constants.Constants;
import com.master.core.validations.GetVpaByMobileSchema;
import com.master.core.validations.HspIdSchema;
import com.master.db.model.Hsp;
import com.master.services.HspService;
import com.master.utility.Helper;
import jakarta.validation.Validator;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.validation.ConstraintViolation;
import jakarta.ws.rs.Consumes;
import jakarta.ws.rs.POST;
import jakarta.ws.rs.Path;
import jakarta.ws.rs.Produces;
import jakarta.ws.rs.core.Context;
import jakarta.ws.rs.core.MediaType;
import jakarta.ws.rs.core.Response;
@Path("/api/hsp")
@Produces(MediaType.APPLICATION_JSON)
public class HspController extends BaseController {
private LinkageNwService linkageNwService;
private HspService hspService;
public HspController(MasterConfiguration configuration, Validator validator, Jdbi jdbi) {
super(configuration, validator, jdbi);
this.linkageNwService = new LinkageNwService(configuration);
this.hspService = new HspService(configuration, jdbi);
}
private Response response(Response.Status status, Object data) {
return Response.status(status).entity(data).build();
}
@POST
@Path("/getVpaByMobile")
@Produces(MediaType.APPLICATION_JSON)
@Consumes(MediaType.APPLICATION_JSON)
public Response getVpaByMobile(@Context HttpServletRequest request,
GetVpaByMobileSchema body) {
Set<ConstraintViolation<GetVpaByMobileSchema>> violations = validator.validate(body);
if (!violations.isEmpty()) {
// Construct error message from violations
String errorMessage = violations.stream()
.map(ConstraintViolation::getMessage)
.reduce("", (acc, msg) -> acc.isEmpty() ? msg : acc + "; " + msg);
return response(Response.Status.BAD_REQUEST, new ApiResponse<>(false, errorMessage, null));
}
ApiResponse<Object> befiscRes = this.linkageNwService.getVpaByMobile(Long.parseLong(body.getMobile()));
logger.info("BEFISC RESPONSE : {}", Helper.toJsonString(befiscRes));
if (!befiscRes.getStatus()) {
return response(Response.Status.NOT_FOUND, befiscRes);
}
Map<String, Object> data = (Map<String, Object>) befiscRes.getData();
String accountName = data.get("accountName").toString().toLowerCase();
String merchantName = data.get("name").toString().toLowerCase();
boolean validHsp = false;
for (String candidateKeyword : Constants.hspKeywords) {
candidateKeyword = candidateKeyword.toLowerCase();
if (accountName.contains(candidateKeyword) || merchantName.contains(candidateKeyword)) {
validHsp = true;
break;
}
}
String uuid = UUID.randomUUID().toString();
data.put("uuid", uuid);
data.put("mobile", body.getMobile());
data.put("status", validHsp ? "VERIFIED" : "PENDING");
Long hspId = this.hspService.insertHspByMobile(data);
if (hspId == null) {
return response(Response.Status.FORBIDDEN,
new ApiResponse<>(false, "Failed to add hsp", null));
}
return response(Response.Status.OK,
new ApiResponse<>(validHsp, validHsp ? "Valid Healthcase" : "Invalid Healthcare",
Map.of("vpa", data.get("vpa"), "merchant_name", merchantName, "hsp_id", hspId)));
}
@POST
@Path("/getHspListByIds")
@Produces(MediaType.APPLICATION_JSON)
@Consumes(MediaType.APPLICATION_JSON)
public Response getHspListByIds(HspIdSchema body) {
Set<ConstraintViolation<HspIdSchema>> violations = validator.validate(body);
if (!violations.isEmpty()) {
// Construct error message from violations
String errorMessage = violations.stream()
.map(ConstraintViolation::getMessage)
.reduce("", (acc, msg) -> acc.isEmpty() ? msg : acc + "; " + msg);
return response(Response.Status.BAD_REQUEST, new ApiResponse<>(false, errorMessage, null));
}
List<Hsp> hspList = this.hspService.getHspDataListByIds(body.getHspIds());
if (hspList == null || hspList.isEmpty()) {
return response(Response.Status.NOT_FOUND, new ApiResponse<>(false, "No hsp data found", null));
}
return response(Response.Status.OK, new ApiResponse<>(true, "Hsp details fetch success", hspList));
}
} |
#Script used to create goterms.gmt file used for Mitch and enrichment analysis
#Load GO terms blasted from Omicsbox
goterms <- read.delim('pc.goterms.txt', header = TRUE) %>%
dplyr::select(c(SeqName, GO.IDs, GO.Names, Description))
colnames(goterms) <- c("protein_id", "GO_terms", "GO_descripton", "description")
goterms.df <- dplyr::right_join(goterms, pc.annotations, by = 'protein_id')
#Make GO term list
splitgt.df <- as_tibble(goterms.df) %>%
separate_longer_delim(c(GO_terms, GO_descripton), delim = ";")
splitgt.df <- as.data.frame(splitgt.df)
#strip leading spaces
splitgt.df$GO_terms <- gsub(" ","",splitgt.df$GO_terms)
splitgt.df$GO_descripton <- gsub("^ ","",splitgt.df$GO_descripton)
gu <- unique(splitgt.df$GO_terms)
gul <- lapply(1:length(gu), function(i){
mygo <- gu[i]
unique(splitgt.df[splitgt.df$GO_terms == mygo, "gene_id"])
})
names(gul) <- lapply(1:length(gu), function(i){
mygo <- gu[i]
desc <- head(splitgt.df[splitgt.df$GO_terms == mygo, "GO_descripton"],1)
id_desc <- paste(mygo,desc)
})
writeGMT <- function (object, fname ){
if (class(object) != "list") stop("object should be of class 'list'")
if(file.exists(fname)) unlink(fname)
for (iElement in 1:length(object)){
write.table(t(c(make.names(rep(names(object)[iElement],2)),object[[iElement]])),
sep="\t",quote=FALSE,
file=fname,append=TRUE,col.names=FALSE,row.names=FALSE)
}
}
writeGMT(object=gul,fname="goterms.gmt") |
import { BookCardContainer, BookCardContent } from './styles'
import Image from 'next/image'
import StarsRating from '@/components/StarsRating'
interface BookCardProps {
coverImageUrl: string
title: string
author: string
rate: number
}
export default function BookCard({
coverImageUrl,
title,
author,
rate,
}: BookCardProps) {
return (
<BookCardContainer>
<Image
quality={100}
src={coverImageUrl}
width={108}
height={152}
alt=" Book cover image "
/>
<BookCardContent>
<label>
<h1>{title}</h1>
<span>{author}</span>
</label>
<StarsRating rate={rate} />
</BookCardContent>
</BookCardContainer>
)
} |
<template>
<div class="order" v-loading="loading">
<el-tabs v-model="activeName" >
<el-tab-pane label="所有订单" name="AllOrder">
<el-table :data="orders">
<el-table-column label="订单编号" prop="id"></el-table-column>
<el-table-column label="下单时间" prop="orderTime"></el-table-column>
<el-table-column label="总价" prop="total"></el-table-column>
<el-table-column label="状态" prop="status"></el-table-column>
<el-table-column label="顾客id" prop="customerId"></el-table-column>
<el-table-column label="操作" >
<template #default="record">
<a href="" @click.prevent="toDetailHandler(record.row)" style="color:blue">详情</a>
</template>
</el-table-column>
</el-table>
</el-tab-pane>
<el-tab-pane label="待支付" name="WaitPay">
<el-table :order="orderPay" >
<el-table-column label="订单编号" prop="id"></el-table-column>
<el-table-column label="下单时间" prop="orderTime"></el-table-column>
<el-table-column label="总价" prop="total"></el-table-column>
<el-table-column label="状态" prop="status"></el-table-column>
<el-table-column label="顾客id" prop="customerId"></el-table-column>
</el-table>
</el-tab-pane >
<el-tab-pane label="待派单" name="WaitSend">
<el-table :data="orderSend" >
<el-table-column label="订单编号" prop="id"></el-table-column>
<el-table-column label="下单时间" prop="orderTime"></el-table-column>
<el-table-column label="总价" prop="total"></el-table-column>
<el-table-column label="状态" prop="status"></el-table-column>
<el-table-column label="顾客id" prop="customerId"></el-table-column>
<el-table-column label="操作" >
<template #default="record">
<a href="" @click.prevent="toSendOrder(record.row.id)" style="color:blue">派单</a>
</template>
</el-table-column>
</el-table>
</el-tab-pane>
<el-tab-pane label="待接单" name="WaitReceive">
<el-table :data="orderReceive">
<el-table-column label="订单编号" prop="id"></el-table-column>
<el-table-column label="下单时间" prop="orderTime"></el-table-column>
<el-table-column label="总价" prop="total"></el-table-column>
<el-table-column label="状态" prop="status"></el-table-column>
<el-table-column label="顾客id" prop="customerId"></el-table-column>
<el-table-column label="操作" >
<template #default="record">
<a href="" @click.prevent="" style="color:blue" @click="close(record.row.id)">取消</a>
</template>
</el-table-column>
</el-table>
</el-tab-pane>
<el-tab-pane label="待服务" name="WaitService">
<el-table :data="orderService">
<el-table-column label="订单编号" prop="id"></el-table-column>
<el-table-column label="下单时间" prop="orderTime"></el-table-column>
<el-table-column label="总价" prop="total"></el-table-column>
<el-table-column label="状态" prop="status"></el-table-column>
<el-table-column label="顾客id" prop="customerId"></el-table-column>
</el-table>
</el-tab-pane>
<el-tab-pane label="待确认" name="WaitSure">
<el-table :data="orderSure" >
<el-table-column label="订单编号" prop="id"></el-table-column>
<el-table-column label="下单时间" prop="orderTime"></el-table-column>
<el-table-column label="总价" prop="total"></el-table-column>
<el-table-column label="状态" prop="status"></el-table-column>
<el-table-column label="顾客id" prop="customerId"></el-table-column>
</el-table>
</el-tab-pane>
<el-tab-pane label="已完成" name="Complate">
<el-table :data="orderComplate">
<el-table-column label="订单编号" prop="id"></el-table-column>
<el-table-column label="下单时间" prop="orderTime"></el-table-column>
<el-table-column label="总价" prop="total"></el-table-column>
<el-table-column label="状态" prop="status"></el-table-column>
<el-table-column label="顾客id" prop="customerId"></el-table-column>
</el-table>
</el-tab-pane>
</el-tabs>
<!-- 派单模态框 -->
<el-dialog title="派单" :visible.sync="visible" @close="dialogCloseHandler">
<el-form :model="order" ref="orderForm">
<el-form-item label="员工" prop="waiterId">
<el-select v-model="order.waiterId">
<el-option v-for="a in orderReceive" :key="a.id" :value="a.waiterId" :label="a.waiterId"></el-option>
</el-select>
</el-form-item>
<!-- <el-form-item label="订单" prop="waiterId">
<el-select v-model="order.id">
<el-option v-for="a in orderReceive" :key="a.id" :value="a.id" :label="a.id"></el-option>
</el-select>
</el-form-item> -->
</el-form>
<div slot="footer" class="dialog-footer">
<el-button size="small" @click="closeModal">取 消</el-button>
<el-button size="small" type="primary" @click="SendOrder">确 定</el-button>
</div>
</el-dialog>
<!-- /模态框 -->
</div>
</template>
<script>
import {mapState,mapGetters,mapMutations,mapActions} from 'vuex'
export default {
data(){
return{
activeName:"AllOrder",
ids:[],
order:{
orderId:{}
},
}
},
created(){
this.findAllOrders();
},
computed:{
...mapState("order",["orders","orderSend","orderReceive","orderService","orderSure","orderComplate","orderPay","visible","title","loading"]),
},
methods:{
...mapMutations("order",["showModal","closeModal","setTitle"]),
...mapActions("order",["findAllOrders","Send","closeOrder"]),
//普通方法
toSendOrder(id){
this.showModal();
this.order.orderId=id
},
SendOrder(){
this.Send(this.order).then((response)=>{
this.$message({
type:"success",
message:response.statusText
})
})
},
dialogCloseHandler(){
this.$refs.orderForm.resetFields();
this.closeModal()
},
close(orderId){
this.closeOrder(orderId).then((response)=>{
this.$message({
type:"success",
message:response.statusText
})
})
},
toDetailHandler(order){
this.$router.push({
path:"./orderDetails",
query:{customerId:order.customerId,id:order.id}
})
},
}
}
</script>
<style scoped>
</style> |
#Region "Microsoft.VisualBasic::4e5cdf96e4f3060657a08b5ba647d03c, sciBASIC#\Data\BinaryData\HDF5\types\FixedPoint.vb"
' Author:
'
' asuka (amethyst.asuka@gcmodeller.org)
' xie (genetics@smrucc.org)
' xieguigang (xie.guigang@live.com)
'
' Copyright (c) 2018 GPL3 Licensed
'
'
' GNU GENERAL PUBLIC LICENSE (GPL3)
'
'
' This program is free software: you can redistribute it and/or modify
' it under the terms of the GNU General Public License as published by
' the Free Software Foundation, either version 3 of the License, or
' (at your option) any later version.
'
' This program is distributed in the hope that it will be useful,
' but WITHOUT ANY WARRANTY; without even the implied warranty of
' MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
' GNU General Public License for more details.
'
' You should have received a copy of the GNU General Public License
' along with this program. If not, see <http://www.gnu.org/licenses/>.
' /********************************************************************************/
' Summaries:
' Code Statistics:
' Total Lines: 44
' Code Lines: 39
' Comment Lines: 0
' Blank Lines: 5
' File Size: 1.57 KB
' Class FixedPoint
'
' Properties: bitOffset, bitPrecision, byteOrder, highPadding, lowPadding
' signed, typeInfo
'
' Function: ToString
'
'
' /********************************************************************************/
#End Region
Imports System.Numerics
Namespace type
Public Class FixedPoint : Inherits DataType
Public Property byteOrder As ByteOrder
Public Property lowPadding As Boolean
Public Property highPadding As Boolean
Public Property signed As Boolean
Public Property bitOffset As Short
Public Property bitPrecision As Short
Public Overrides ReadOnly Property typeInfo As System.Type
Get
If signed Then
Select Case bitPrecision
Case 8 : Return GetType(SByte)
Case 16 : Return GetType(Short)
Case 32 : Return GetType(Integer)
Case 64 : Return GetType(Long)
Case Else
Throw New NotSupportedException
End Select
Else
Select Case bitPrecision
Case 8, 16
Return GetType(Integer)
Case 32
Return GetType(Long)
Case 64
Return GetType(BigInteger)
Case Else
Throw New NotSupportedException
End Select
End If
End Get
End Property
Public Overrides Function ToString() As String
Return $"({byteOrder.ToString} {Me.GetType.Name}) {typeInfo.FullName}"
End Function
End Class
End Namespace |
from flask import Flask, render_template, request, jsonify
import joblib
import numpy as np
app = Flask(__name__)
# Load the pre-trained model
model_path = 'model.pkl'
try:
with open(model_path, 'rb') as model_file:
model = joblib.load(model_file)
except Exception as e:
print(f"Error loading the model: {e}")
model = None
@app.route('/')
def index():
return render_template('index.html')
@app.route('/predict', methods=['POST'])
def predict():
try:
if model is None:
return jsonify({'error': 'Model not loaded'})
# Get input data from the form
pregnancies = float(request.form['pregnancies'])
glucose = float(request.form['glucose'])
blood_pressure = float(request.form['blood_pressure'])
skin_thickness = float(request.form['skin_thickness'])
insulin = float(request.form['insulin'])
bmi = float(request.form['bmi'])
diabetes_pedigree_function = float(request.form['diabetes_pedigree_function'])
age = float(request.form['age'])
# Make prediction using the loaded model
input_data = np.array([[pregnancies, glucose, blood_pressure, skin_thickness, insulin, bmi, diabetes_pedigree_function, age]])
prediction = model.predict(input_data)
# Return the prediction as JSON
return jsonify({'prediction': int(prediction[0])})
except Exception as e:
return jsonify({'error': str(e)})
if __name__ == '__main__':
app.run(debug=True) |
package com.udemy.groceryshoppingapi.auth.service
import com.udemy.groceryshoppingapi.auth.entity.VerificationToken
import com.udemy.groceryshoppingapi.auth.repository.VerificationTokenRepository
import com.udemy.groceryshoppingapi.auth.util.SignUpMapper
import com.udemy.groceryshoppingapi.dto.AuthenticationRequest
import com.udemy.groceryshoppingapi.dto.AuthenticationResponse
import com.udemy.groceryshoppingapi.dto.EmailConfirmedResponse
import com.udemy.groceryshoppingapi.dto.RegisterRequest
import com.udemy.groceryshoppingapi.error.AccountVerificationException
import com.udemy.groceryshoppingapi.error.SignUpException
import com.udemy.groceryshoppingapi.error.TokenExpiredException
import com.udemy.groceryshoppingapi.error.UserNotFoundException
import com.udemy.groceryshoppingapi.error.UsernamePasswordMismatchException
import com.udemy.groceryshoppingapi.user.entity.AppUser
import com.udemy.groceryshoppingapi.user.repository.AppUserRepository
import jakarta.transaction.Transactional
import org.slf4j.LoggerFactory
import org.springframework.security.authentication.AuthenticationManager
import org.springframework.security.authentication.BadCredentialsException
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken
import org.springframework.security.core.userdetails.UsernameNotFoundException
import org.springframework.security.crypto.password.PasswordEncoder
import org.springframework.stereotype.Service
import java.time.Instant
import java.time.temporal.ChronoUnit
import java.util.UUID
@Service
class AccountManagementServiceImpl(
private val passwordEncoder: PasswordEncoder,
private val jwtService: JwtService,
private val authenticationManager: AuthenticationManager,
private val mapper: SignUpMapper,
private val appUserRepository: AppUserRepository,
private val verificationTokenRepository: VerificationTokenRepository,
private val emailService: EmailService
) : AccountManagementService {
companion object {
private const val TEN_CHARACTERS = 10
}
private val log = LoggerFactory.getLogger(javaClass)
@Transactional
override fun signUp(request: RegisterRequest): EmailConfirmedResponse {
checkForSignUpMistakes(request)
val user = mapper.toEntity(request, passwordEncoder)
val savedUser = appUserRepository.save(user)
val (token, verificationToken) = initiateEmailVerificationToken(savedUser)
verificationTokenRepository.save(verificationToken)
emailService.sendVerificationEmail(savedUser, token)
return EmailConfirmedResponse("Please, check your emails and spam/junk folder for ${user.email} to verify your account")
}
override fun verifyUser(token: String): EmailConfirmedResponse {
val currentVerificationToken: VerificationToken =
verificationTokenRepository.findByToken(token) ?: throw AccountVerificationException("Invalid Token")
val user = currentVerificationToken.appUser
if (currentVerificationToken.isExpired()) {
log.error("Token Expired for user: $user")
currentVerificationToken.token = UUID.randomUUID().toString()
currentVerificationToken.expiryDate = Instant.now().plus(15, ChronoUnit.MINUTES)
verificationTokenRepository.save(currentVerificationToken)
emailService.sendVerificationEmail(user, currentVerificationToken.token)
throw TokenExpiredException("Token expired. A new verification link has been sent to your email: ${user.email}")
}
if (user.isVerified) {
log.error("Account Already Verified: $user")
throw AccountVerificationException("Account Already Verified")
}
user.isVerified = true
appUserRepository.save(user)
return EmailConfirmedResponse("Account Verified Successfully")
}
@Transactional
override fun signIn(request: AuthenticationRequest): AuthenticationResponse {
val user =
appUserRepository.findByAppUsername(request.username) ?: throw UsernameNotFoundException("User not found")
if (!user.isVerified) {
log.error("user not verified: $user")
throw SignUpException("You didn't clicked yet on the verification link, check your email: ${user.email}")
}
try {
authenticationManager.authenticate(UsernamePasswordAuthenticationToken(request.username, request.password))
} catch (bce: BadCredentialsException) {
log.error("Username or password is incorrect: ${bce.message}")
throw UsernamePasswordMismatchException("Username or password is incorrect")
}
val jwtToken = jwtService.generateAccessToken(user)
val refreshToken = jwtService.generateRefreshToken(user)
return AuthenticationResponse(jwtToken, refreshToken)
}
override fun requestPasswordReset(email: String): EmailConfirmedResponse {
val user = appUserRepository.findByEmail(email) ?: throw UserNotFoundException("E-Mail: $email does not exist!")
val newPassword = UUID.randomUUID().toString().take(TEN_CHARACTERS)
user.appPassword = passwordEncoder.encode(newPassword)
appUserRepository.save(user)
emailService.sendPasswordResetEmail(user, newPassword)
return EmailConfirmedResponse("New password sent to $email")
}
private fun initiateEmailVerificationToken(appUser: AppUser): Pair<String, VerificationToken> {
val token = UUID.randomUUID().toString()
val verificationToken = VerificationToken(
token = token,
appUser = appUser,
expiryDate = Instant.now().plus(15, ChronoUnit.MINUTES)
)
return Pair(token, verificationToken)
}
private fun checkForSignUpMistakes(request: RegisterRequest) {
appUserRepository.findByEmail(request.email)?.let {
log.error("User email already exists: $request")
throw SignUpException("User email already exists!")
}
appUserRepository.findByAppUsername(request.username)?.let {
log.error("Username already exists: $request")
throw SignUpException("Username already exists!")
}
if (request.password != request.passwordConfirmation) {
log.error("Password and password confirmation does not match: $request")
throw SignUpException("Password and password confirmation does not match!")
}
}
} |
import React from 'react';
import { Formik, Form, Field, ErrorMessage } from 'formik';
import * as Yup from 'yup';
const FormVal = Yup.object({
nombre: Yup.string().required('Necesario'),
apellido: Yup.string().required('Necesario'),
direccion: Yup.string().required('Necesario'),
email: Yup.string().email().required('Necesario'),
celular: Yup.number().required('Necesario').positive().integer(),
recibo: Yup.string().required('Necesario'),
mediopago: Yup.string().required('Necesario')
});
const Formclir = () => (
<div>
<Formik
initialValues={{ nombre: '', apellido: '',direccion:'',email:'',celular:'', recibo:undefined, mediopago:'' }}
validationSchema = {FormVal}
validate={values => {
const errors = {};
if (!values.email) {
errors.email = 'Necesario';
} else if (
!/^[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,}$/i.test(values.email)
) {
errors.email = 'Correo inválido';
}
return errors;
}}
onSubmit={(values, { setSubmitting }) => {
const requestOptions = {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(values)
};
fetch('http://localhost:5000/crearusuario', requestOptions)
.then(response => {
if(response.status === 200){
return response.json()
}else{
alert('Ocurrió un error al crear usuario')
}
})
.then(data=>{
alert('Usuario creado correctamente')
})
setSubmitting(false)
}}
>
{({ isSubmitting, setFieldValue }) => (
<Form>
Nombre
<Field name="nombre"/>
<ErrorMessage name="nombre" component="div" />
Apellido
<Field name="apellido"/>
<ErrorMessage name="apellido" component="div" />
Dirección
<Field name="direccion"/>
Email
<Field type="email" name="email" />
<ErrorMessage name="email" component="div" />
Número de celular
<Field name="celular" />
<ErrorMessage name="celular" component="div" />
Recibo de servicio público
<input type="file" name="recibo" onChange={(e) => {
const fileReader = new FileReader();
fileReader.onload = () => {
if (fileReader.readyState === 2) {
setFieldValue('recibo', fileReader.result);
}
};
fileReader.readAsDataURL(e.target.files[0]);
}} />
<ErrorMessage name="recibo" component="div" />
Medio de pago
<Field name="mediopago"/>
<ErrorMessage name="mediopago" component="div" />
Tarjeta débito o crédito
<button type="submit" className="btn btn-outline-secondary" disabled={isSubmitting}>
Registrarme
</button>
</Form>
)}
</Formik>
</div>
);
export default Formclir; |
# Memo
Pope TV
- assert
- 경우의 수를 줄여라.
- 나의 확신과 판단이 코드에 들어간다.
- e.g. 어떤 수를 짝수로 바꾼 뒤에는 그게 짝수인지 assert를 넣어도 된다.
- 그러니까 나는 분명 짝수로 바꿈!! 그렇게 알고 있으셈! 했는데 짝수가 나올수도 있으니 그걸 체크해라.
- string에서 첫 단어 자르기 연산을 한 뒤 새 string이 대문자로 시작하는 지 assert를 넣어도 된다.
- 즉, 내가 작성한 code에 대해서 일어나선 안될 일에 대해서 체크?
Deterministic / Non-Deterministic
결정론적 결과 / 비결정론적 결과
결정론적 결과는 input에 같으면 그에 대한 output이 항상 일정하다.
하지만 비결정론적 결과란 input이 같아도 항상 같은 output이 나오지 않는다.
예를 들어 current_time() current_temperature()와 같은 함수를 예로 들 수 있다.
##### <span style='color:#f7b731'>Exception / Assert</span>
- Exception
예외가 발생했을 때, 그 예외를 처리하기 위한 코드.
- Assert
어떤 조건이 True임을 보증하기 위해서 사용한다.
즉, 이 조건이 참일 때 코드는 내가 보장한다.
하지만 False일 때는 보장할 수 없다.
```
name = "2BlockDMask"
assert name[0].isalpha(), "이름의 맨 처음은 알파벳으로 시작해주세요"
```
예외 / 에러
##### <span style='color:#f7b731'>Unit test</span>
```# views.py
from django.contrib.auth.decorators import login_required
from django.shortcuts import redirect, render
from .models import Order, Product
@login_required
def purchase_product(request, product_id):
product = Product.objects.get(pk=product_id)
if request.method == 'POST':
quantity = int(request.POST.get('quantity'))
if quantity <= 0 or quantity > product.stock:
return render(request, 'purchase_product.html', {'product': product, 'error': 'Invalid quantity.'})
order = Order.objects.create(user=request.user, product=product, quantity=quantity)
product.stock -= quantity
product.save()
return redirect('profile')
return render(request, 'purchase_product.html', {'product': product})
```
1. 해당 view api는 product_id를 통해 해당 product에 대한 정보를 불러온다.
2. request_method는 POST여야 한다.
3. request를 통해 보내온 parameter quantity가 재고 보다 작으냐 크냐를 조건으로 하여 다른 response를 보낸다.
4. 그리고 해당 조건을 모두 만족할 경우 재고를 줄인다.
5.
```
# tests.py
from django.test import TestCase, Client, mock
from .models import Order, Product
from .views import purchase_product
class PurchaseProductViewTests(TestCase):
def setUp(self):
self.product = Product.objects.create(name='Test Product', price=10.00, stock=5)
self.client = Client()
def test_get_request_renders_product_details(self):
response = self.client.get(f'/purchase/{self.product.pk}/')
self.assertEqual(response.status_code, 200)
self.assertTemplateUsed('purchase_product.html')
self.assertIn(self.product.name, response.content.decode())
def test_post_request_with_invalid_quantity_renders_error(self):
response = self.client.post(f'/purchase/{self.product.pk}/', {'quantity': 'abc'})
self.assertEqual(response.status_code, 200)
self.assertTemplateUsed('purchase_product.html')
self.assertIn('Invalid quantity.', response.content.decode())
@mock.patch.object(Product, 'save')
def test_post_request_with_valid_quantity_creates_order_and_updates_stock(self, mock_save):
response = self.client.post(f'/purchase/{self.product.pk}/', {'quantity': 2})
self.assertEqual(response.status_code, 302)
self.assertRedirects(response, '/profile/')
order = Order.objects.get(user=self.client.user, product=self.product)
self.assertEqual(order.quantity, 2)
mock_save.assert_called_once()
self.assertEqual(self.product.stock, 3)
```
1. 해당 unit test에서는 setUp method를 통하여 mock object를 만든다.
2. Client django library를 이용하여 request를 보내기 위한 fake client instance를 만든다.
3. fake Client instance를 통하여 fake request를 보내는데 1번에서 만들었던 mock object를 request의 argument로 보낸다.
4. test_get_request_renders_product_details: Checks response for rendering approriate template and displaying product details. |
import React, { useEffect, useState } from "react";
import "../styles/cartPage.css";
import { useAuthContext } from "../context/AuthContext";
import ProductCard from "../components/ProductCard";
import { useNavigate } from "react-router-dom";
import { useStoreContext } from "../context/storeContext";
import { PulseLoader } from "react-spinners";
const Cart = () => {
const navigate = useNavigate();
const {
userState: { cart },
} = useAuthContext();
const [loader, setLoader] = useState(true);
const override = {
position: "fixed",
top: "50%",
left: "47.5%",
margin: "auto",
borderColor: "red",
};
const { dispatchStore } = useStoreContext();
const cartData = cart?.map((product) => (
<ProductCard data={product} cartCard />
));
const totalPriceWithoutDiscount = cart?.reduce(
(sum, { originalPrice, qty }) => sum + originalPrice * qty,
0
);
const totalPriceWithDiscount = cart?.reduce(
(sum, { offerPrice, qty }) => sum + offerPrice * qty,
0
);
const totalDiscount = totalPriceWithoutDiscount - totalPriceWithDiscount;
useEffect(() => {
dispatchStore({ type: "setDisplaySearchModal", payload: false });
dispatchStore({ type: "setInDisplay", payload: false });
}, []);
useEffect(() => {
setTimeout(() => {
setLoader(false);
}, 1000);
}, []);
return (
<>
{loader ? (
<PulseLoader
color="black"
loading={loader}
size={25}
cssOverride={override}
aria-label="Loading Spinner"
data-testid="loader"
/>
) : (
<>
{cart?.length === 0 ? (
<EmptyCartComponent />
) : (
<div className="cartPage">
<section className="cartItems">
<h1>Cart items: ({cart.length} )</h1>
{cartData}
</section>
<section className="cartSummary">
<h2>Cart Summary</h2>
<section className="summaryRow">
<span className="summaryColumn">
<p>Price ({cart.length} items)</p>
<p>₹{totalPriceWithoutDiscount}</p>
</span>
<span className="summaryColumn">
<p>Discount</p>
<p>-₹{totalDiscount}</p>
</span>
</section>
<section className="summaryRow">
<span className="summaryColumn">
<p>Total Amount</p>
<p style={{ fontSize: "1.2rem", fontWeight: 700 }}>
₹{totalPriceWithoutDiscount - totalDiscount}
</p>
</span>
</section>
<button
className="checkoutBtn "
onClick={() => navigate("/checkout")}
>
CHECKOUT
</button>
</section>
</div>
)}
</>
)}
</>
);
};
export default Cart;
function EmptyCartComponent() {
const navigate = useNavigate();
return (
<div className="emptyCartComponent">
<h1>No items in your cart ! </h1>
<button onClick={() => navigate("/store")}>Explore Yo-Store!</button>
</div>
);
} |
import React, { useState } from 'react';
import { Form, Button, Container, Row, Col } from 'react-bootstrap';
import { Link, useNavigate } from 'react-router-dom';
import { useSignupUserMutation } from '~/services/appApi';
import './signup.css';
import botImg from '~/assets/images/bot.jpeg';
import Loading from '~/components/Loading/Loading';
function Signup() {
const [email, setEmail] = useState('');
const [password, setPassword] = useState('');
const [name, setName] = useState('');
const [signupUser, { isLoading, error }] = useSignupUserMutation();
const navigate = useNavigate();
//Image upload state
const [image, setImage] = useState(null);
const [uploadingImg, setUpLoadingImg] = useState(false);
const [imagePreview, setImagePreview] = useState(null);
function validateImg(e) {
const file = e.target.files[0];
if (file.size >= 1024 * 1024) {
return alert('Max file size is 1mb');
} else {
setImage(file);
setImagePreview(URL.createObjectURL(file));
}
}
const uploadImage = async () => {
const data = new FormData();
data.append('file', image);
data.append('upload_preset', 'chat_app');
try {
setUpLoadingImg(true);
let res = await fetch('https://api.cloudinary.com/v1_1/dcnxg5hjv/image/upload', {
method: 'post',
body: data,
});
const urlData = await res.json();
setUpLoadingImg(false);
return urlData.url;
} catch (err) {
setUpLoadingImg(false);
console.log(err);
}
};
const handleSignup = async (e) => {
e.preventDefault();
if (!image) return alert('Please upload your profile picture');
const url = await uploadImage(image);
console.log(url);
//signup the user
signupUser({ name, email, password, picture: url }).then(({ data }) => {
if (data) {
console.log(data);
navigate('/chat');
}
});
};
return (
<Container>
{(uploadingImg || isLoading) && <Loading />}
<Row>
<Col
md={7}
className="d-flex align-items-center justify-content-center flex-direction-column"
>
<Form style={{ width: '80%', maxWidth: 500 }} onSubmit={handleSignup}>
<h1 className="text-center">Create account</h1>
<div className="signup-profile-pic__container">
<img src={imagePreview || botImg} alt="bot-img" className="signup-profile-pic" />
<label htmlFor="image-upload" className="image-upload-label">
<i className="fa fa-plus-circle add-picture-icon"></i>
</label>
<input
type="file"
id="image-upload"
hidden
accept="image/png, image/jpeg"
onChange={validateImg}
/>
</div>
{error && <p className="alert alert-danger">{error.data}</p>}
<Form.Group className="mb-3" controlId="formBasicEmail">
<Form.Group className="mb-3" controlId="formBasicName">
<Form.Label>Name</Form.Label>
<Form.Control
type="text"
placeholder="Your name"
onChange={(e) => {
setName(e.target.value);
}}
value={name}
/>
</Form.Group>
<Form.Label>Email address</Form.Label>
<Form.Control
type="email"
placeholder="Enter email"
onChange={(e) => {
setEmail(e.target.value);
}}
value={email}
/>
<Form.Text className="text-muted">
We'll never share your email with anyone else.
</Form.Text>
</Form.Group>
<Form.Group className="mb-3" controlId="formBasicPassword">
<Form.Label>Password</Form.Label>
<Form.Control
type="password"
placeholder="Password"
onChange={(e) => {
setPassword(e.target.value);
}}
value={password}
/>
</Form.Group>
<Button variant="primary" type="submit">
{uploadingImg || isLoading ? 'Signing you up...' : 'Signup'}
</Button>
<div className="py-4">
<p className="text-center">
Already have an account ? <Link to="/login">Signup</Link>
</p>
</div>
</Form>
</Col>
<Col md={5} className="signup__bg"></Col>
</Row>
</Container>
);
}
export default Signup; |
import 'dart:io';
import 'package:flutter_qrscan/models/scan_model.dart';
import 'package:path/path.dart';
import 'package:path_provider/path_provider.dart';
import 'package:sqflite/sqflite.dart';
class DBProvider {
static Database _database;
static final DBProvider db = DBProvider._();
DBProvider._();
Future<Database> get database async {
if (_database != null) {
return _database;
} else {
_database = await initDB();
return _database;
}
}
Future<Database> initDB() async {
Directory documentsDirectory = await getApplicationDocumentsDirectory();
final path = join(documentsDirectory.path, "ScansDB.db");
return await openDatabase(path, version: 1, onOpen: (db) {},
onCreate: (Database db, int version) async {
await db.execute("""
CREATE TABLE Scans(
id INTEGER PRIMARY KEY,
type TEXT,
value TEXT
)
""");
});
}
Future<int> newScanRaw(ScanModel newScan) async {
final id = newScan.id;
final type = newScan.type;
final value = newScan.value;
// Verify db
final db = await database;
final res = await db.rawInsert("""
INSERT INTO Scans (id, type, value)
VALUES ("$id", "$type", "$value")
""");
return res;
}
Future<int> newScan(ScanModel newScan) async {
// Verify db
final db = await database;
final res = await db.insert("Scans", newScan.toJson());
return res;
}
Future<ScanModel> getScanById(int id) async {
// Verify db
final db = await database;
final res = await db.query("Scans", where: "id = ?", whereArgs: [id]);
return res.isNotEmpty
? ScanModel.fromJson(res.first)
: null;
}
Future<List<ScanModel>> getScans() async {
// Verify db
final db = await database;
final res = await db.query("Scans");
return res.isNotEmpty
? res.map((e) => ScanModel.fromJson(e)).toList()
: [];
}
Future<List<ScanModel>> getScansByType(String type) async {
// Verify db
final db = await database;
final res = await db.query("Scans", where: "type = ?", whereArgs: [type]);
return res.isNotEmpty
? res.map((e) => ScanModel.fromJson(e)).toList()
: [];
}
Future<int> updateScan(ScanModel scan) async {
// Verify db
final db = await database;
final res = await db.update("Scans", scan.toJson(), where: "id = ?", whereArgs: [scan.id]);
return res;
}
Future<int> deleteScan(int id) async {
// Verify db
final db = await database;
final res = await db.delete("Scans", where: "id = ?", whereArgs: [id]);
return res;
}
Future<int> deleteScans() async {
// Verify db
final db = await database;
final res = await db.delete("Scans");
return res;
}
} |
/*------------------------------------------------------------------
* README
*
* Cisco ONE-P Python SDK
*
* Copyright (c) 2011-2014 by Cisco Systems, Inc.
* All rights reserved.
*------------------------------------------------------------------
*/
Introduction:
------------
The APIs contained in these modules allow the developer to design
controller applications that interface to compatible Cisco network
elements. These applications will be able to configure the element
and retrieve statistics.
WARNING:
It is suggested that the developer be very knowlegable of the
network element configuration before applying. You can bring down
a production network with the wrong setup!
onePK Python API Refrence:
--------------------------
The onePK Python API Refrence is provided in HTML format and can be
found in the docs directory. Open the index.html with a web browser.
Installing Modules
-------------------
Must have Python version 2.7.
From root of uncompressed directory type:
python setup.py install
This will install the SDK modules in the standard directory.
If you wish to locate the modules into a custom directory:
python setup.py install --prefix="<your custom directory>"
This will install the SDK modules in :
<your custom directory>/lib/python2.7/site-packages/onep
Be sure that your custom directory is included in the PYTHONPATH.
Creating Application
--------------------
Must have a Cisco network device capable of communicating
with ONE-P APIs. Network Element must also have onep
configured with the socket transport and have the correct
onep services activated. A network interface must be
configured with a valid IP address and pingable.
First step to communicate with network element is to connect. See
sample.py for a very basic example. You should be able to run:
./sample.py
Usage:
sample.py -a <element address or FQDN> [-t <transport_type>] \
[-C <client cert file> -K <client private key file> \
-R <root certificates file>]
-a <ip_addr or FQDN> Network element's IP Address or Fully Qualified Domain Name
-t <tls|tipc> Transport type. Default is TLS connection
-C <clientcert.pem> Client certificate file required TLS connection
(default location ./clientcert.pem)
-K <clientkey.pem> Client private key file required for TLS connection
(default location ./clientkey.pem)
-R <nerootca.pem> Root certificate file required for TLS connection
(default location ./nerootca.pem)
The application will prompt the user to enter username and password that
are configured on the network element you are connecting to.
For more information on how to use TLS connection please refer to the
Getting Started Guide.
Happy Scripting! |
/**
* @openapi
*
* /category/:
* get:
* tags: [Category]
* summary: Get all categories
* description: Use to request all categories
* produces:
* - application/json
* responses:
* 200:
* description: List of categories
* content:
* application/json:
* schema:
* type: array
* items:
* $ref: '#/components/schemas/CategoryResponse'
* example:
* - uuid: 4911b72b-a448-4e2d-874b-ed91874d1061
* name: Home
* icon: HO
* visible: 1
* enable: 1
* parentUuid: ""
* - uuid: 858e8322-991c-47ae-97a1-845665d7d010
* name: Health
* icon: HE
* visible: 1
* enable: 1
* parentUuid: ""
*
*
* post:
* tags: [Category]
* summary: Create a new category
* description: Use to create an category
* produces:
* - application/json
* requestBody:
* required: true
* content:
* application/json:
* schema:
* $ref: '#/components/schemas/CategoryCreate'
* responses:
* 201:
* description: Category created
* content:
* application/json:
* schema:
* $ref: '#/components/schemas/CategoryResponse'
* 400:
* description: Name is required
* 409:
* description: Name already exists
*
* /category/{uuid}:
* get:
* tags: [Category]
* summary: Get one category
* description: Use to request one category
* produces:
* - application/json
* parameters:
* - in: path
* name: uuid
* description: Uuid of category
* responses:
* 200:
* description: Category by uuid
* content:
* application/json:
* schema:
* $ref: '#/components/schemas/CategoryResponse'
* 400:
* description: Bad uuid
* 404:
* description: Category not found
*
* put:
* tags: [Category]
* summary: Update an category
* description: Use to update an category
* produces:
* - application/json
* parameters:
* - in: path
* name: uuid
* description: Uuid of category
* requestBody:
* required: true
* content:
* application/json:
* schema:
* $ref: '#/components/schemas/CategoryUpdate'
* responses:
* 200:
* description: Category updated
* content:
* application/json:
* schema:
* $ref: '#/components/schemas/CategoryResponse'
* 400:
* description: Bad uuid
* 404:
* description: Category or parent category not found
* 409:
* description: Name already exists
*
* delete:
* tags: [Category]
* summary: Delete an category
* description: Use to delete an category
* produces:
* - application/json
* parameters:
* - in: path
* name: uuid
* description: Uuid of category
* responses:
* 200:
* description: Category deleted
* content:
* application/json:
* schema:
* type: boolean
* example: true
* 400:
* description: Bad uuid
* 404:
* description: Category not found
*/ |
import React, { useState } from 'react'
import AppBar from '@mui/material/AppBar'
import Box from '@mui/material/Box'
import Container from '@mui/material/Container'
import Toolbar from '@mui/material/Toolbar'
import Typography from '@mui/material/Typography'
import IconButton from '@mui/material/IconButton'
import Navbar from '../Navbar'
import Drawer from '../Drawer'
//IMPORTING SVG'S
import logo_desk from '../../assets/img/logo_desc.svg'
import logo_mob from '../../assets/img/logo_mob.svg'
import burger_menu from '../../assets/img/burger_menu.svg'
import styles from './styles'
const Header = () => {
const [openDrawer, setOpenDrawer] = useState(false)
return (
<AppBar position='static' sx={styles.appBar}>
<Container maxWidth='xl' sx={styles.container}>
<Drawer open={openDrawer} onClose={() => setOpenDrawer(false)} />
<Toolbar disableGutters>
<Typography component='a' sx={styles.logoDesk} href='/'>
<img src={logo_desk} alt='logo' />
</Typography>
<Box sx={{ flexGrow: 1, display: { xs: 'flex', lg: 'none' } }}>
<IconButton
size='large'
color='inherit'
aria-label='menu'
onClick={() => setOpenDrawer(true)}
>
<img src={burger_menu} alt='burger menu' />
</IconButton>
</Box>
<Typography component='a' sx={styles.logoMob} href='/'>
<img src={logo_mob} alt='logo' />
</Typography>
<Box sx={{ flexGrow: 1, display: { xs: 'none', lg: 'flex' } }}>
<Navbar />
</Box>
</Toolbar>
</Container>
</AppBar>
)
}
export default Header |
package com.ybg.rp.manager.partner
import grails.test.mixin.*
import spock.lang.*
@TestFor(PartnerUserInfoController)
@Mock(PartnerUserInfo)
class PartnerUserInfoControllerSpec extends Specification {
def populateValidParams(params) {
assert params != null
// TODO: Populate valid properties like...
//params["name"] = 'someValidName'
assert false, "TODO: Provide a populateValidParams() implementation for this generated test suite"
}
void "Test the index action returns the correct model"() {
when:"The index action is executed"
controller.index()
then:"The model is correct"
!model.partnerUserInfoList
model.partnerUserInfoCount == 0
}
void "Test the create action returns the correct model"() {
when:"The create action is executed"
controller.create()
then:"The model is correctly created"
model.partnerUserInfo!= null
}
void "Test the save action correctly persists an instance"() {
when:"The save action is executed with an invalid instance"
request.contentType = FORM_CONTENT_TYPE
request.method = 'POST'
def partnerUserInfo = new PartnerUserInfo()
partnerUserInfo.validate()
controller.save(partnerUserInfo)
then:"The create view is rendered again with the correct model"
model.partnerUserInfo!= null
view == 'create'
when:"The save action is executed with a valid instance"
response.reset()
populateValidParams(params)
partnerUserInfo = new PartnerUserInfo(params)
controller.save(partnerUserInfo)
then:"A redirect is issued to the show action"
response.redirectedUrl == '/partnerUserInfo/show/1'
controller.flash.message != null
PartnerUserInfo.count() == 1
}
void "Test that the show action returns the correct model"() {
when:"The show action is executed with a null domain"
controller.show(null)
then:"A 404 error is returned"
response.status == 404
when:"A domain instance is passed to the show action"
populateValidParams(params)
def partnerUserInfo = new PartnerUserInfo(params)
controller.show(partnerUserInfo)
then:"A model is populated containing the domain instance"
model.partnerUserInfo == partnerUserInfo
}
void "Test that the edit action returns the correct model"() {
when:"The edit action is executed with a null domain"
controller.edit(null)
then:"A 404 error is returned"
response.status == 404
when:"A domain instance is passed to the edit action"
populateValidParams(params)
def partnerUserInfo = new PartnerUserInfo(params)
controller.edit(partnerUserInfo)
then:"A model is populated containing the domain instance"
model.partnerUserInfo == partnerUserInfo
}
void "Test the update action performs an update on a valid domain instance"() {
when:"Update is called for a domain instance that doesn't exist"
request.contentType = FORM_CONTENT_TYPE
request.method = 'PUT'
controller.update(null)
then:"A 404 error is returned"
response.redirectedUrl == '/partnerUserInfo/index'
flash.message != null
when:"An invalid domain instance is passed to the update action"
response.reset()
def partnerUserInfo = new PartnerUserInfo()
partnerUserInfo.validate()
controller.update(partnerUserInfo)
then:"The edit view is rendered again with the invalid instance"
view == 'edit'
model.partnerUserInfo == partnerUserInfo
when:"A valid domain instance is passed to the update action"
response.reset()
populateValidParams(params)
partnerUserInfo = new PartnerUserInfo(params).save(flush: true)
controller.update(partnerUserInfo)
then:"A redirect is issued to the show action"
partnerUserInfo != null
response.redirectedUrl == "/partnerUserInfo/show/$partnerUserInfo.id"
flash.message != null
}
void "Test that the delete action deletes an instance if it exists"() {
when:"The delete action is called for a null instance"
request.contentType = FORM_CONTENT_TYPE
request.method = 'DELETE'
controller.delete(null)
then:"A 404 is returned"
response.redirectedUrl == '/partnerUserInfo/index'
flash.message != null
when:"A domain instance is created"
response.reset()
populateValidParams(params)
def partnerUserInfo = new PartnerUserInfo(params).save(flush: true)
then:"It exists"
PartnerUserInfo.count() == 1
when:"The domain instance is passed to the delete action"
controller.delete(partnerUserInfo)
then:"The instance is deleted"
PartnerUserInfo.count() == 0
response.redirectedUrl == '/partnerUserInfo/index'
flash.message != null
}
} |
import React, { createContext, useEffect, useState } from "react";
import axios from "axios";
const Greenshop = createContext();
export function Contexts({ children }) {
const [data, setdata] = useState([]);
const [uniquedata, setuniquedata] = useState();
const [productdata, setproductdata] = useState([]);
const [userdata, setuserdata] = useState([]);
const [isModalOpen, setIsModalOpen] = useState(true);
const [plant_Id, setplant_Id] = useState("");
// const handleDelete = (id) => {
// axios
// .delete("http://localhost:8000/api/task/" + id)
// .then((res) => {
// console.log(res.data);
// setRenderdata(!renderdata);
// })
// .catch((err) => console.log(err));
// };
useEffect(() => {
const getuniData = async () => {
let got = await axios.get("http://localhost:8000/api/cards/" + plant_Id);
console.log(plant_Id);
console.log(got.data);
const unData = JSON.parse(JSON.stringify(got.data));
setuniquedata(unData);
// setuniquedata(got.data);
};
getuniData();
}, [plant_Id]);
useEffect(() => {
const getData = async () => {
let got = await axios.get("http://localhost:8000/api/cards");
setdata(await got.data);
};
getData();
}, []);
console.log(data);
useEffect(() => {
const getData = async () => {
let usersdata = await axios.get("http://localhost:8000/api/user");
setuserdata(await usersdata.data);
};
getData();
}, []);
console.log(userdata);
return (
<Greenshop.Provider
value={{
data,
setdata,
productdata,
setproductdata,
userdata,
isModalOpen,
setIsModalOpen,
uniquedata,
setuniquedata,
plant_Id,
setplant_Id,
}}
>
{children}
</Greenshop.Provider>
);
}
export default Greenshop; |
import { test, expect } from '@playwright/test';
const timeoutWait: number = 10000;
test.describe('Лендинг', () => {
test('Получение пробной версии', async ({ page }) => {
await page.goto('https://elma365.com/ru/');
const getTrial = page.locator('#sticky-wrapper > header > div > nav > ul:nth-child(2) > li:nth-child(1) > a');
await getTrial.click();
const modal = page.locator('#trialRegister > div');
await expect(modal).toBeVisible();
await modal.locator('#name').click({ timeout: timeoutWait });
await modal.locator('#name').fill('testtest', { timeout: timeoutWait });
await modal.locator('#email').click({ timeout: timeoutWait });
await modal.locator('#email').fill('elma@elma.test', { timeout: timeoutWait });
await modal.locator('#customer_phone').click({ timeout: timeoutWait });
await modal.locator('#customer_phone').fill('89991112233', { timeout: timeoutWait });
await modal.locator('#companyName').click({ timeout: timeoutWait });
await modal.locator('#companyName').fill('first test', { timeout: timeoutWait });
await modal.locator('#jobPosition').click({ timeout: timeoutWait });
await modal.locator('#jobPosition').fill('test job pos', { timeout: timeoutWait });
await modal.locator('#companySize').click({ timeout: timeoutWait });
await modal.locator('#companySize').selectOption({index: 3}, {force:true, timeout: timeoutWait});
await modal.locator('#companySize').click({ timeout: timeoutWait });
await modal.locator('div[class*="privacy-policy"][class*="form-checkbox"] input[type*="checkbox"]').click({force:true, timeout: timeoutWait });
await modal.locator('button').click();
})
}); |
/*
Write a function that takes a sentence string as an argument and returns that string with every occurrence of a
"number word" — 'zero', 'one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight', 'nine' — converted to its
corresponding digit character.
P:
- Take sentence string as argument
- find any number word within: 'zero', 'one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight', 'nine'
- convert the num word to the num digit
Input: sentence string
output: string with num words replaced by nums
E:
below
D:
string -> array -> string
A:
- create a lowercase string variable which just carries every letter in the alphabet
- create a constant object converter with num words as key and num digit as value
- create function wordToDigit with one param string
- split string into array of words (watch for 'four.' for example)
- iterate through each element
- if element contains non-alpha character
- slice it off and store
- if converter contains the key of the current element, replace the current element with the converter value
- restore sliced off char if needed
- join the array back together with spaces between each digit and log
*/
const ALPHABET = 'abcdefghijklmnopqrstuvwxyz';
const CONVERTER = {
'zero': '0',
'one': '1',
'two': '2',
'three': '3',
'four': '4',
'five': '5',
'six': '6',
'seven': '7',
'eight': '8',
'nine': '9',
}
function wordToDigit(str) {
Object.keys(CONVERTER).forEach(word => {
let regex = new RegExp(word, 'gi');
str = str.replace(regex, CONVERTER[word]);
});
console.log(str);
}
wordToDigit('Please call me at five five five one two three four. Thanks.');
// "Please call me at 5 5 5 1 2 3 4. Thanks." |
import 'package:flutter/material.dart';
import 'package:flutter_svg/svg.dart';
import 'package:get/get.dart';
import '../../core/presentation/themes/colors_manager.dart';
class HeadLineBottomSheet extends StatelessWidget {
const HeadLineBottomSheet({
Key? key,
this.height,
required this.bottomSheetTitle,
required this.body,
}) : super(key: key);
final Widget body;
final double? height;
final String bottomSheetTitle;
@override
Widget build(BuildContext context) {
return SizedBox(
height: height,
child: Column(
crossAxisAlignment: CrossAxisAlignment.center,
children: [
SvgPicture.asset('assets/images/icons/bottom-sheet-swapper.svg'),
Expanded(
child: Container(
decoration: const BoxDecoration(
color: Colors.white,
borderRadius: BorderRadius.only(
topRight: Radius.circular(16),
topLeft: Radius.circular(16),
),
),
child: Column(
children: [
Center(
child: Container(
padding: const EdgeInsets.symmetric(
horizontal: 25,
vertical: 8,
),
margin: const EdgeInsets.only(bottom: 10),
decoration: const BoxDecoration(
borderRadius: BorderRadius.only(
bottomLeft: Radius.circular(18),
bottomRight: Radius.circular(18),
),
color: ColorManager.primaryColor,
),
child: Text(
bottomSheetTitle,
style: Get.textTheme.titleMedium!.copyWith(
color: Colors.white,
fontWeight: FontWeight.w800,
),
),
),
),
Expanded(
child: body,
)
],
),
),
)
],
),
);
}
} |
package com.smakhorin.easycodeandroidtask.core.ui;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import com.smakhorin.easycodeandroidtask.R;
public class WorkingHoursAlertDialog extends AlertDialog {
private final Boolean isWithinWorkingHours;
private final Context context;
public WorkingHoursAlertDialog(Context context, Boolean isWithinWorkingHours) {
super(context);
this.isWithinWorkingHours = isWithinWorkingHours;
this.context = context;
}
protected WorkingHoursAlertDialog(Context context, boolean cancelable, OnCancelListener cancelListener, Boolean isWithinWorkingHours) {
super(context, cancelable, cancelListener);
this.isWithinWorkingHours = isWithinWorkingHours;
this.context = context;
}
protected WorkingHoursAlertDialog(Context context, int themeResId, Boolean isWithinWorkingHours) {
super(context, themeResId);
this.isWithinWorkingHours = isWithinWorkingHours;
this.context = context;
}
public void display() {
setTitle(context.getString(R.string.information));
String message;
if (isWithinWorkingHours) {
message = context.getString(R.string.within_working_hours);
} else {
message = context.getString(R.string.outside_working_hours);
}
setMessage(message);
setButton(BUTTON_NEUTRAL, context.getString(R.string.ok), (dialog, which) -> dismiss());
}
} |
import React, { useState, useEffect } from "react";
import { AiFillPlayCircle } from "react-icons/ai";
import { getSearchMovie } from "../Api.js";
import { Link } from "react-router-dom";
const NowPlaying = () => {
const [nowPlayingMovies, setNowPlayingMovies] = useState([]);
const [searchInput, setSearchInput] = useState("");
const [showResults, setShowResults] = useState(false);
useEffect(() => {
if (searchInput.length > 3) {
getSearchMovie(searchInput).then((result) => {
setNowPlayingMovies(result.results);
setShowResults(true);
});
} else {
setNowPlayingMovies([]);
setShowResults(false);
}
}, [searchInput]);
const handleSearch = (e) => {
setSearchInput(e.target.value);
};
const nowPlayingList = () => {
return nowPlayingMovies.map((movie, i) => {
return (
<div
className=" w-1/2 sm:w-1/3 md:w-1/4 lg:w-1/5 2xl:w-1/12 px-2 mb-6"
key={i}
>
<div className="bg-inherit shadow-md shadow-light rounded-lg overflow-hidden">
<div className="relative">
<div className="group cursor-pointer">
<Link to="/watchmovie">
<img
src={`https://image.tmdb.org/t/p/w500/${movie.poster_path}`}
alt=""
className="w-full object-cover transition-opacity duration-300 group-hover:opacity-40"
/>
<div className="absolute inset-0 flex items-center justify-center opacity-0 transition-opacity duration-300 group-hover:opacity-100">
<div className="flex items-center justify-center">
<AiFillPlayCircle className="h-12 w-12 text-primary " />
</div>
</div>
<div className="absolute inset-0 flex items-start justify-center opacity-0 transition-opacity duration-300 group-hover:opacity-100">
<h2 className="text-light text-sm font-semibold pt-2 px-2 text-center">
{movie.title}
</h2>
</div>
<div className="absolute inset-0 flex items-end justify-center opacity-0 transition-opacity duration-300 group-hover:opacity-100">
<p className="text-xs italic text-light font-light bg-red-600 px-3 py-1 rounded-full mb-2">
Rate : {movie.vote_average}
</p>
</div>
</Link>
</div>
</div>
<div className="flex flex-wrap justify-center items-center py-2 gap-2">
<Link to="/watchmovie">
<button className="bg-psecond font-normal text-xs sm:text-sm text-light px-2 py-1 md:px-4 md:py-2 rounded-lg hover:opacity-90">
Watch
</button>
</Link>
<Link to="/download">
<button className="bg-psecond mt-0.5 sm:mt-0 font-normal text-xs sm:text-sm text-light px-2 py-1 md:px-4 md:py-2 rounded-lg hover:opacity-90 inline-flex items-center">
<svg
className="fill-current h-3 w-3 mr-1"
xmlns="http://www.w3.org/2000/svg"
viewBox="0 0 20 20"
>
<path d="M13 8V2H7v6H2l8 8 8-8h-5zM0 18h20v2H0v-2z" />
</svg>
Download
</button>
</Link>
</div>
</div>
</div>
);
});
};
return (
<div>
<div className="w-full bg-second px-4">
<div className="flex justify-start bg-dark rounded-lg px-4">
<label htmlFor="search" className="w-full">
<input
type="search"
name="search"
id="search"
placeholder="Search movie.."
className="w-full px-2 py-2 bg-dark text-light outline-none"
value={searchInput}
onChange={handleSearch}
/>
</label>
</div>
</div>
{showResults && (
<div className="bg-second px-6 pb-4">
<div className="font-semibold text-base text-primary py-3">
<div className="text-sm md:text-base lg:text-xl">
<div className="flex items-center">
<hr className="border-primary flex-grow" />
<div className="mx-4">Hasil Pencarian</div>
<hr className="border-primary flex-grow" />
</div>
</div>
</div>
<div className="flex flex-wrap mt-4 -mx-2">{nowPlayingList()}</div>
<div className="flex justify-center ">
<button className="bg-light text-psecond font-semibold text-sm px-4 py-2 rounded-full hover:opacity-80">
Load More
</button>
</div>
</div>
)}
</div>
);
};
export default NowPlaying; |
import re
def _contains_date(text):
# Check if the document contains a date
# date can be in the format of 01/01/2021 or January 1, 2021 or 01-01-2021 or 01.01.2021 or 01 01 2021 or 1 Jan 2021
# or 1 January 2021 or 1st January 2021 or 1st Jan 2021 or 1st Jan, 2021 or 1st January, 2021
re_pattern = r'(\d{1,2}[-/\. ]\d{1,2}[-/\. ]\d{2,4})|((\d{1,2}(st|nd|rd|th)?\s)?(Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)[a-z]*\s\d{2,4})'
return re.search(re_pattern, text)
def _contains_currency(text):
# Check if the document contains a currency
# Currency can be in the format of $1,000,000 or $1M or $1 million or anything starting with a dollar sign
re_pattern = r'\$[\d,]+(\.\d{2})?(\s?(million|billion|trillion))?'
return re.search(re_pattern, text)
def _contains_time(text):
# Check if the document contains a time
# Time can be in the format of 12:00 AM or 12:00 PM or 12:00:00 AM or 12:00:00 PM
re_pattern = r'(\d{1,2}:\d{2}(:\d{2})?\s?[AaPp][Mm])'
return re.search(re_pattern, text)
def _contains_email(text):
# Check if the document contains an email
re_pattern = r'[\w\.-]+@[\w\.-]+'
return re.search(re_pattern, text)
def _contains_url(text):
# Check if the document contains a URL
re_pattern = r'https?://\S+'
return re.search(re_pattern, text)
def _contains_phone_number(text):
# Check if the document contains a phone number
re_pattern = r'(\d{3}-\d{3}-\d{4})|(\(\d{3}\)\s?\d{3}-\d{4})'
return re.search(re_pattern, text)
reannotations = {
"contains_date": _contains_date,
"contains_currency": _contains_currency,
"contains_time": _contains_time,
"contains_email": _contains_email,
"contains_url": _contains_url,
"contains_phone_number": _contains_phone_number
} |
package io.loopcamp.test.day01_Intro;
import io.restassured.RestAssured;
import io.restassured.response.Response;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;
public class HelloWorldApiTest {
String url = "https://sandbox.api.service.nhs.uk/hello-world/hello/world"; // API Endpoint
@DisplayName("Hello World GET request")
@Test
public void helloWorldGetRequestTest(){
//send a GET request and save response inside the Response object
Response response = RestAssured.get(url);
//Print response body in a formatted way (in this case JSON format) - RESPONSE BODY
response.prettyPrint(); // this also returns String.
//Print status code - RESPONSE CODE
System.out.println("Status Code: " + response.statusCode()); // 200
System.out.println("Status Line: " + response.statusLine()); // HTTP/1.1 200 OK
// assert/validate that Response Code is 200
Assertions.assertEquals(200, response.statusCode(), "Did not match");
// You can also assign RESPONSE STATUS CODE into a variable and then use variable to assert
int actualStatusCode = response.statusCode();
Assertions.assertEquals(200, actualStatusCode, "Did not match");
// .asString(); method will return the RESPONSE BODY as a String.
String actualResponseBody = response.asString();
//System.out.println(actualResponseBody);
// Can you assert the Hello World! is in the body?
Assertions.assertTrue( actualResponseBody.contains("Hello World!") );
}
} |
<?php
namespace App\Models;
use App\Traits\HasRateConversion;
use Carbon\Carbon;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
class Order extends Model
{
use HasFactory,HasRateConversion;
public const STATUS_PENDING = 1;
public const STATUS_AWAITING_FULFILLMENT = 2;
public const STATUS_AWAITING_SHIPPING = 3;
public const STATUS_PARTIALLY_SHIPPED = 4;
public const STATUS_SHIPPED = 5;
public const STATUS_AWAITING_PICKUP = 6;
public const STATUS_COMPLETED = 7;
public const STATUS_CANCELLED = 8;
public const STATUS_DISPUTED = 9;
public const STATUS_AWAITING_REFUND = 10;
public const STATUS_REFUNDED = 11;
protected $table = "orders";
protected $fillable = ['user_id','billing_address_id','order_number','total_amount','status','transaction_id'];
protected $appends = ['converted_amount'];
public function getCreatedAtAttribute($value){
$carbon = new Carbon($value);
return $carbon->toFormattedDateString();
}
public function subOrders(){
return $this->hasMany(SubOrder::class,'order_id');
}
public function items(){
return $this->hasMany(OrderItem::class,'order_id');
}
public function billingAddress(){
return $this->belongsTo(BillingAddress::class,'billing_address_id');
}
public function user(){
return $this->belongsTo(User::class,"user_id");
}
public function getConvertedAmountAttribute(){
return $this->baseToUserCurrency($this->total_amount);
}
} |
import { useState } from "react";
import { Navigate } from "react-router-dom";
import Input from "../layout/Input";
import ResetPasswordModal from "../modals/ResetPasswordModal";
import { doSignInWithEmailAndPassword } from "../../util/firebase/auth";
import { useAuth } from "../contexts/authContext";
import notification from "../../util/notification";
import Loading from "../layout/Loading";
function LoginPage() {
const { userLoggedIn } = useAuth();
const [isResetPasswordModalVisible, setResetPasswordModalVisibility] = useState(false);
const [email, setEmail] = useState("");
const [password, setPassword] = useState("");
const [loading, setLoading] = useState(false);
const handleSubmit = async (e) => {
e.preventDefault();
setLoading(true);
if (!userLoggedIn) {
try {
await doSignInWithEmailAndPassword(email, password);
notification("success", "You're logged in successfully!");
} catch (ex) {
notification("error", ex.message);
}
}
setLoading(false);
};
if (userLoggedIn) return <Navigate to={"/account"} replace={true} />;
return (
<>
{loading && <Loading />}
{isResetPasswordModalVisible && <ResetPasswordModal hideModal={() => setResetPasswordModalVisibility(false)} />}
<div className="container my-5">
<div className="row justify-content-center">
<div className="col-md-6">
<div className="card">
<h2 className="card-header text-center">Login</h2>
<div className="card-body">
<form onSubmit={handleSubmit}>
<Input
label="Email address"
id="email"
type="email"
placeholder="Enter your email"
value={email}
onChange={(e) => setEmail(e.target.value)}
/>
<Input
label="Password"
id="password"
type="password"
placeholder="Enter your password"
value={password}
onChange={(e) => setPassword(e.target.value)}
/>
<button type="submit" className="btn btn-primary w-100 mt-3">
Login
</button>
<div className="text-center mt-3">
<button type="button" className="btn btn-link" onClick={() => setResetPasswordModalVisibility(true)}>
Forgot password?
</button>
</div>
</form>
</div>
</div>
</div>
</div>
</div>
</>
);
}
export default LoginPage; |
<script lang="ts" setup>
import {computed, onMounted, reactive, ref, watch} from 'vue';
import {type Coordinate, type FoodItemDTO, type FrogDTO} from "@/api/generated";
import {getTileType} from "@/composables/EditorHelper";
import {computedEager, useMouseInElement} from "@vueuse/core";
import {useAssetStore} from "@/stores/AssetStore";
import FoodItemComponent from "@/components/render/FoodItemComponent.vue";
interface MapDrawerProps {
mapString: string;
showDebugInfo?: boolean
showHoverTile?: boolean
selectedTile?: Coordinate,
frog?: FrogDTO,
foodTiles?: FoodItemDTO[]
}
const emit = defineEmits<{
(e: "update:selectedTile", val: Coordinate): void
(e: "click"): void
(e: "contextmenu", val: MouseEvent): void
}>()
const assets = useAssetStore();
const props = withDefaults(defineProps<MapDrawerProps>(), {
foodTiles: () => [] as FoodItemDTO[]
});
const canvas = ref<HTMLCanvasElement | null>(null);
const bufferCanvas = ref<HTMLCanvasElement | null>(null);
const width = computedEager(() => window.innerWidth * .5);
const height = computedEager(() => window.innerHeight);
function computeTileSizeX() {
return width.value / Math.max(...props.mapString.trim().split('\n').map(val => val.length));
}
function computeTileSizeY() {
return height.value / props.mapString.trim().split('\n').length;
}
const observer = useMouseInElement(canvas)
const hoveredTile = reactive<Coordinate>({x: 0, y: 0})
watch(() => {
return {x: observer.elementX.value, y: observer.elementY.value}
}, value => {
if (!props.showHoverTile) return;
if (!observer.isOutside.value) {
const x = Math.floor(value.x / computeTileSizeX())
const y = Math.floor(value.y / computeTileSizeY())
if (x !== hoveredTile.x || y !== hoveredTile.y) {
hoveredTile.x = x;
hoveredTile.y = y;
emit("update:selectedTile", hoveredTile)
drawMap()
}
}
})
watch(() => props, () => drawMap(), {deep: true})
function drawBufferedImage() {
const visibleCtx = canvas.value?.getContext('2d');
if (visibleCtx && bufferCanvas.value) {
visibleCtx.clearRect(0, 0, visibleCtx.canvas.width, visibleCtx.canvas.height);
visibleCtx.drawImage(bufferCanvas.value, 0, 0);
}
}
watch(width, () => drawMap())
watch(height, () => drawMap())
function drawMap() {
if (!bufferCanvas.value || !props.mapString) return;
const ctx: CanvasRenderingContext2D | null = bufferCanvas.value.getContext('2d');
if (!ctx) return;
ctx.clearRect(0, 0, ctx.canvas.width, ctx.canvas.height);
const tileSizeX = computeTileSizeX()
const tileSizeY = computeTileSizeY()
const mapLines = props.mapString.trim().split('\n');
const calls: Promise<any>[] = []
mapLines.forEach((column, y) => {
const yPos = y * tileSizeY;
Array.from(column).forEach((char, x) => {
const img = assets.getAssetImage(getTileType(char))
img.then((data) => ctx.drawImage(data, x * tileSizeX, yPos, tileSizeX, tileSizeY))
calls.push(img)
});
})
Promise.all(calls).then(() => {
if (props.showHoverTile) {
ctx.strokeRect(hoveredTile.x * tileSizeX, hoveredTile.y * tileSizeY, tileSizeX, tileSizeY)
}
drawFrog(tileSizeX, tileSizeY)
drawBufferedImage()
})
}
watch(() => props.frog, () => drawFrog())
onMounted(() => {
setTimeout(drawMap, 50)
});
function handleContextMenuEvent(event: MouseEvent) {
event.preventDefault()
emit('contextmenu', event)
}
const imagePosition: Coordinate = reactive({x: 0, y: 0})
function drawFrog(tileSizeX: number = computeTileSizeX(), tileSizeY: number = computeTileSizeY()) {
const frog = props.frog;
if (frog && canvas.value) {
const left = canvas.value.offsetLeft
imagePosition.x = Math.floor(left + (frog.position.x * tileSizeX))
imagePosition.y = Math.floor((frog.position.y * tileSizeY))
}
}
const frogTexture = computed(() => {
if (props.frog) {
return assets.getEntity(props.frog.direction)
}
return undefined
})
const offsetLeft = computed(() => canvas.value?.offsetLeft ?? 0)
</script>
<template>
<div>
<canvas ref="canvas"
:class="{'editable':showHoverTile}"
:height="height"
:width="width"
class="position-relative"
@click="$emit('click')"
@contextmenu="handleContextMenuEvent"/>
<canvas v-show="false"
ref="bufferCanvas"
:height="height"
:width="width"
class="position-absolute"/>
<FoodItemComponent v-for="food in foodTiles" :key="food.pos.x +'x'+food.pos.y"
:amount="food.amount"
:offset-left="offsetLeft"
:position="food.pos"
:tile-size-x="computeTileSizeX"
:tile-size-y="computeTileSizeY"/>
<!--Frog view-->
<v-img v-show="frog" ref="frogView" :height="computeTileSizeY()" :src="frogTexture"
:style="{ top: `${imagePosition.y}px`, left: `${imagePosition.x}px` }"
:width="computeTileSizeX()"
alt="frog-gif" class="position-absolute no-mouse-interaction"/>
<div v-if="showDebugInfo" class="bottomRight">
<div>Tile: {{ hoveredTile.x }} x {{ hoveredTile.y }}</div>
<div>Frog: {{ imagePosition }}</div>
</div>
</div>
</template>
<style>
.bottomRight {
top: 10px;
right: 10px;
position: fixed;
background-color: rgba(128, 128, 128, 0.7);
color: white;
}
.editable {
cursor: url("/assets/cursor/pencil.png") 0 32, auto;
}
.no-mouse-interaction {
pointer-events: none;
}
</style> |
import "../styles/globals.css";
import type { AppProps as NextAppProps } from "next/app";
import { ApolloCache, ApolloProvider } from "@apollo/client";
import { useApollo } from "../graphql/client";
import dynamic from "next/dynamic";
import { Suspense } from "react";
import localFont from "next/font/local";
import { Analytics } from "@vercel/analytics/react";
const sansFont = localFont({
src: "../public/inter.roman.var.woff2",
weight: "100 900",
display: "swap",
});
const Archipelago = dynamic(
() => import("../components/Navigation/Archipelago")
);
type AppProps<P = any> = {
pageProps: P;
} & Omit<NextAppProps<P>, "pageProps">;
interface CustomPageProps {
initialApolloState?: ApolloCache<any>;
}
export default function MyApp({
Component,
pageProps,
}: AppProps<CustomPageProps>) {
const apolloClient = useApollo(pageProps.initialApolloState);
return (
<>
<ApolloProvider client={apolloClient}>
<style jsx global>
{`
:root {
--sans-font: ${sansFont.style.fontFamily};
}
`}
</style>
<Component {...pageProps} />
<Analytics />
<Suspense>
<Archipelago />
</Suspense>
</ApolloProvider>
</>
);
} |
// Copyright (C) 2023, Ava Labs, Inc. All rights reserved.
// See the file LICENSE for licensing terms.
//go:generate mockgen -source=$GOFILE -destination=./mocks/mock_eth_client.go -package=mocks
package evm
import (
"context"
"crypto/ecdsa"
"math/big"
"runtime"
"sync"
"github.com/ava-labs/avalanchego/ids"
"github.com/ava-labs/avalanchego/utils/logging"
avalancheWarp "github.com/ava-labs/avalanchego/vms/platformvm/warp"
"github.com/ava-labs/awm-relayer/config"
"github.com/ava-labs/subnet-evm/core/types"
"github.com/ava-labs/subnet-evm/ethclient"
predicateutils "github.com/ava-labs/subnet-evm/predicate"
"github.com/ava-labs/subnet-evm/x/warp"
"github.com/ethereum/go-ethereum/common"
"go.uber.org/zap"
)
const (
// Set the max fee to twice the estimated base fee.
// TODO: Revisit this constant factor when we add profit determination, or make it configurable
BaseFeeFactor = 2
MaxPriorityFeePerGas = 2500000000 // 2.5 gwei
)
// Client interface wraps the ethclient.Client interface for mocking purposes.
type Client interface {
ethclient.Client
}
// Implements DestinationClient
type destinationClient struct {
client ethclient.Client
lock *sync.Mutex
destinationBlockchainID ids.ID
pk *ecdsa.PrivateKey
eoa common.Address
currentNonce uint64
logger logging.Logger
}
func NewDestinationClient(logger logging.Logger, subnetInfo config.DestinationSubnet) (*destinationClient, error) {
// Dial the destination RPC endpoint
client, err := ethclient.Dial(subnetInfo.GetNodeRPCEndpoint())
if err != nil {
logger.Error(
"Failed to dial rpc endpoint",
zap.Error(err),
)
return nil, err
}
destinationID, err := ids.FromString(subnetInfo.BlockchainID)
if err != nil {
logger.Error(
"Could not decode destination chain ID from string",
zap.Error(err),
)
return nil, err
}
pk, eoa, err := subnetInfo.GetRelayerAccountInfo()
if err != nil {
logger.Error(
"Could not extract relayer account information from config",
zap.Error(err),
)
return nil, err
}
// Explicitly zero the private key when it is gc'd
runtime.SetFinalizer(pk, func(pk *ecdsa.PrivateKey) {
pk.D.SetInt64(0)
pk = nil
})
nonce, err := client.NonceAt(context.Background(), eoa, nil)
if err != nil {
logger.Error(
"Failed to get nonce",
zap.Error(err),
)
return nil, err
}
return &destinationClient{
client: client,
lock: new(sync.Mutex),
destinationBlockchainID: destinationID,
pk: pk,
eoa: eoa,
currentNonce: nonce,
logger: logger,
}, nil
}
func (c *destinationClient) SendTx(signedMessage *avalancheWarp.Message,
toAddress string,
gasLimit uint64,
callData []byte) error {
// Synchronize teleporter message requests to the same destination chain so that message ordering is preserved
c.lock.Lock()
defer c.lock.Unlock()
// We need the global 32-byte representation of the destination chain ID, as well as the destination's configured blockchainID
// Without the destination's configured blockchainID, transaction signature verification will fail
destinationChainIDBigInt, err := c.client.ChainID(context.Background())
if err != nil {
c.logger.Error(
"Failed to get chain ID from destination chain endpoint",
zap.Error(err),
)
return err
}
// Get the current base fee estimation, which is based on the previous blocks gas usage.
baseFee, err := c.client.EstimateBaseFee(context.Background())
if err != nil {
c.logger.Error(
"Failed to get base fee",
zap.Error(err),
)
return err
}
// Get the suggested gas tip cap of the network
// TODO: Add a configurable ceiling to this value
gasTipCap, err := c.client.SuggestGasTipCap(context.Background())
if err != nil {
c.logger.Error(
"Failed to get gas tip cap",
zap.Error(err),
)
return err
}
to := common.HexToAddress(toAddress)
gasFeeCap := baseFee.Mul(baseFee, big.NewInt(BaseFeeFactor))
gasFeeCap.Add(gasFeeCap, big.NewInt(MaxPriorityFeePerGas))
// Construct the actual transaction to broadcast on the destination chain
tx := predicateutils.NewPredicateTx(
destinationChainIDBigInt,
c.currentNonce,
&to,
gasLimit,
gasFeeCap,
gasTipCap,
big.NewInt(0),
callData,
types.AccessList{},
warp.ContractAddress,
signedMessage.Bytes(),
)
// Sign and send the transaction on the destination chain
signer := types.LatestSignerForChainID(destinationChainIDBigInt)
signedTx, err := types.SignTx(tx, signer, c.pk)
if err != nil {
c.logger.Error(
"Failed to sign transaction",
zap.Error(err),
)
return err
}
if err := c.client.SendTransaction(context.Background(), signedTx); err != nil {
c.logger.Error(
"Failed to send transaction",
zap.Error(err),
)
return err
}
// Increment the nonce to use on the destination chain now that we've sent
// a transaction using the current value.
c.currentNonce++
c.logger.Info(
"Sent transaction",
zap.String("txID", signedTx.Hash().String()),
)
return nil
}
func (c *destinationClient) Client() interface{} {
return c.client
}
func (c *destinationClient) SenderAddress() common.Address {
return c.eoa
}
func (c *destinationClient) DestinationBlockchainID() ids.ID {
return c.destinationBlockchainID
} |
from heapq import heappush, heappop
from time import perf_counter
def find_shortest_flight(flights, source, destination):
# Check if arguments are valid
if not flights:
raise Exception("Flights not given")
if type(flights) is not list:
raise Exception("Flights must be a list")
if not source:
raise Exception("Source not given")
if type(source) is not str:
raise Exception("Source city code must be a string")
if not destination:
raise Exception("Destination not given")
if type(destination) is not str:
raise Exception("Destination city code must be a string")
# A dictionary to map city codes to indices
city_code_to_index = {}
index = 0
for flight in flights:
if len(flight) != 2:
raise Exception("Flight must contain 2 elements: source and destination")
if type(flight[0]) is not str or type(flight[1]) is not str:
raise Exception("City code must be a string")
for city in flight:
if city not in city_code_to_index:
city_code_to_index[city] = index
index += 1
# Check if the source and destination cities are in the city code dictionary
# if not the function returns 0
if source not in city_code_to_index or destination not in city_code_to_index:
return 0
# Number of cities
cities = len(city_code_to_index)
# Adjacency list for each city index
adj_list = [[] for _ in range(cities)]
# Populate the adjacency list
for flight in flights:
src_index = city_code_to_index[flight[0]]
dest_index = city_code_to_index[flight[1]]
adj_list[src_index].append((dest_index, 1)) # Cost is assumed to be 1 as per the original example
# Implementing Priority Queue
pq = []
src_index = city_code_to_index[source]
dst_index = city_code_to_index[destination]
# Start with the source city
heappush(pq, (0, src_index))
# Dijkstra's algorithm for finding the shortest path between the nodes(cities)
while pq:
cost, current = heappop(pq)
if current == dst_index:
return cost
for next_index, next_cost in adj_list[current]:
heappush(pq, (cost + next_cost, next_index))
# If no routes exist, return 0
return 0
if __name__ == '__main__':
flight_list = [['SOF', 'IST'], ['IST', 'CMB'], ['CMB', 'MLE']]
source_city = 'SOF'
dest_city = 'MLE'
start = perf_counter()
ans = find_shortest_flight(flight_list, source_city, dest_city)
end = perf_counter()
print("Fastest time:", ans)
print("Execution time (seconds):", end - start) |
---
title: .NET용 Aspose.Font를 사용하여 CFF 글꼴을 디스크에 저장
linktitle: .NET용 Aspose.Font를 사용하여 CFF 글꼴을 디스크에 저장
second_title: Aspose.Font .NET API
description: 단계별 가이드를 통해 .NET용 Aspose.Font를 사용하여 CFF 글꼴을 디스크에 저장하는 방법을 알아보세요. .NET 애플리케이션에서 글꼴 조작을 쉽게 마스터할 수 있습니다.
type: docs
weight: 11
url: /ko/net/cff-font-handling/save-cff-font-to-disc/
---
## 소개
.NET용 Aspose.Font를 사용하여 CFF(Compact Font Format) 글꼴을 디스크에 저장하는 방법에 대한 포괄적인 튜토리얼에 오신 것을 환영합니다. .NET 애플리케이션에서 글꼴 데이터를 조작해야 하는 경우 안정적인 라이브러리가 얼마나 중요한지 알고 계실 것입니다. Aspose.Font for .NET은 글꼴을 쉽게 로드, 편집 및 저장할 수 있는 강력한 API입니다. 이 가이드에서는 프로세스를 단계별로 안내하여 마지막에는 CFF 글꼴 작업 방법을 확실하게 이해할 수 있도록 도와드립니다. 뛰어들어보자!
## 전제조건
시작하기 전에 다음 전제 조건이 충족되었는지 확인하세요.
- .NET용 Aspose.Font: 다음에서 다운로드할 수 있습니다.[Aspose 릴리스 페이지](https://releases.aspose.com/font/net/).
- .NET 개발 환경: Visual Studio 또는 기타 호환 가능한 IDE.
- C#에 대한 기본 이해: C# 프로그래밍 언어 및 .NET 프레임워크에 대한 지식.
- 글꼴 파일: 작업하려는 CFF 글꼴 파일(예:`OpenSans-Regular.cff`).
## 네임스페이스 가져오기
.NET용 Aspose.Font를 사용하려면 프로젝트에 필요한 네임스페이스를 가져와야 합니다. 수행 방법은 다음과 같습니다.
```csharp
using Aspose.Font.Cff;
using Aspose.Font.Sources;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
```
이제 프로세스를 간단한 단계로 나누어 보겠습니다.
## 1단계: 바이트 배열에서 CFF 글꼴 로드
먼저 CFF 글꼴을 애플리케이션에 로드해야 합니다. 여기에는 글꼴 파일을 바이트 배열로 읽은 다음`FontDefinition` 관리할 개체입니다.
## 1.1단계: 글꼴 파일을 바이트 배열로 읽기
글꼴 파일이 있는 디렉터리를 지정하여 시작하세요. 그런 다음 글꼴 파일을 바이트 배열로 읽습니다.
```csharp
string dataDir = "Your Document Directory";
byte[] fontMemoryData = File.ReadAllBytes(dataDir + "OpenSans-Regular.cff");
```
## 1.2단계: FontDefinition 객체 생성
다음으로`FontDefinition` 글꼴 데이터를 관리하기 위해 바이트 배열을 사용할 개체입니다.
```csharp
FontDefinition fd = new FontDefinition(FontType.CFF, new FontFileDefinition("cff", new ByteContentStreamSource(fontMemoryData)));
```
## 2단계: CFF 글꼴 열기
와 더불어`FontDefinition` 개체가 준비되면 다음 단계는 .NET용 Aspose.Font를 사용하여 글꼴을 여는 것입니다.
## 2.1단계: Open 메서드 사용
사용`Open` 의 방법`Font` 글꼴을 로드하는 클래스입니다. 반환된 객체를`CffFont`.
```csharp
CffFont cffFont = Aspose.Font.Font.Open(fd) as CffFont;
```
## 3단계: CFF 글꼴 개체 작업
이제 글꼴이 로드되었으므로 필요에 따라 글꼴을 조작할 수 있습니다. 이 튜토리얼에서는 디스크에 저장하는 작업을 진행하겠습니다.
## 4단계: CFF 글꼴을 디스크에 저장
마지막으로 로드된 CFF 글꼴을 디스크의 새 파일에 저장합니다.
## 4.1단계: 출력 파일 경로 정의
새 CFF 글꼴 파일을 저장할 전체 경로를 지정합니다.
```csharp
string outputFile = "Your Document Directory" + "OpenSans-Regular_out.cff";
```
## 4.2단계: 글꼴 저장
사용`Save` 의 방법`CffFont` 지정된 경로에 글꼴을 쓰는 개체입니다.
```csharp
cffFont.Save(outputFile);
```
## 결론
축하해요! .NET용 Aspose.Font를 사용하여 CFF 글꼴을 로드하고 저장하는 방법을 성공적으로 배웠습니다. 이 튜토리얼에서는 .NET 애플리케이션에서 글꼴 데이터를 조작하는 데 필요한 필수 단계를 다루므로 글꼴 파일을 자신 있게 처리할 수 있습니다. 데스크톱 애플리케이션을 개발하든 웹 서비스를 개발하든 .NET용 Aspose.Font는 다양한 글꼴 형식을 원활하게 사용하는 데 필요한 도구를 제공합니다.
## FAQ
### 1. CFF 폰트란 무엇인가요?
CFF(Compact Font Format) 글꼴은 PostScript 및 PDF 문서에 주로 사용되는 글꼴 형식입니다. 컴팩트한 스토리지와 고품질 렌더링을 제공합니다.
### 2. Aspose.Font for .NET을 다른 글꼴 형식과 함께 사용할 수 있나요?
예, .NET용 Aspose.Font는 TTF, OTF, Type 1 등을 포함한 다양한 글꼴 형식을 지원합니다.
### 3. Aspose.Font for .NET을 사용하려면 라이선스가 필요한가요?
예, .NET용 Aspose.Font는 전체 기능을 사용하려면 라이선스가 필요합니다. 다음에서 평가용 임시 라이센스를 얻을 수 있습니다.[여기](https://purchase.aspose.com/temporary-license/).
### 4. 더 자세한 문서는 어디서 찾을 수 있나요?
자세한 문서는 다음에서 확인할 수 있습니다.[.NET 문서 페이지용 Aspose.Font](https://reference.aspose.com/font/net/).
### 5. 문제가 발생하면 어떻게 지원을 받을 수 있나요?
방문하시면 지원을 받으실 수 있습니다.[Aspose.Font 지원 포럼](https://forum.aspose.com/c/font/41). |
import image from "../../../assets/form-img.png";
import { InputField } from "../../../components";
import { Link, useNavigate } from "react-router-dom";
import { Toaster } from "react-hot-toast";
import { useDispatch } from "react-redux";
import { setUser } from "../../../redux/slices/userSlice";
import { USER_ROLES } from "../../../api/roles";
import { notifyFailure, notifySuccess } from "../../../utils/Utils";
import { users } from "../../CommonPages/forgotPassword/queriesAndUtils";
import { loadingEnd, loadingStart } from "../../../redux/slices/loadingSlice";
import { z } from "zod";
import { useForm } from "react-hook-form";
import { zodResolver } from "@hookform/resolvers/zod";
import { getDoctorToken } from "../../../api/apiCalls/doctorsApi";
import { DOCTOR_TOKEN_QUERY } from "./queries";
const inputs = [
{
label: "Email",
type: "email",
placeholder: "Enter your email",
name: "email",
},
{
label: "Password",
type: "password",
placeholder: "************",
name: "password",
},
];
const FormSchema = z.object({
email: z.string().min(1, { message: "Email is required" }).email(),
password: z.string().min(1, { message: "Password is required" }),
});
export default function DoctorSignIn() {
const {
register,
handleSubmit,
setError,
formState: { errors },
} = useForm({ resolver: zodResolver(FormSchema) });
const navigate = useNavigate();
const dispatch = useDispatch();
const handleLogin = async (data: Inputs) => {
dispatch(loadingStart());
const tokenRes = await getDoctorToken(DOCTOR_TOKEN_QUERY, data);
dispatch(loadingEnd());
if (tokenRes?.token) {
const userData = { ...tokenRes, role: USER_ROLES.doctor };
dispatch(setUser(userData));
notifySuccess("Login Success! Redirecting...");
setTimeout(() => {
navigate("/doctor-dashboard/profile");
}, 1000);
} else {
notifyFailure(tokenRes?.error || "Login Failed!");
setError("email", { type: "custom" });
setError("password", {
type: "custom",
});
}
};
const onSubmit = async (data: any) => {
handleLogin(data);
};
return (
<main className="grid grid-cols-12 items-center my-12">
<section className="col-start-3 col-span-5">
<div className="mx-8 w-4/5 justify-self-center rounded-lg">
<div className=" text-primary my-3 pt-2 pb-4 px-5 flex justify-between items-center">
<h3 className="text-3xl font-bold">Doctor Login</h3>
<small className="font-medium">
Not a Doctor?{" "}
<Link to="/patient/sign-in" className="font-bold">
Sign In
</Link>
</small>
</div>
<form onSubmit={handleSubmit(onSubmit)} className="pt-2 pb-6 px-5">
{inputs?.map((input) => (
<InputField
label={input.label}
name={input.name}
type={input.type}
placeholder={input.placeholder}
properties={{ ...register(input.name) }}
error={errors[input.name]}
/>
))}
<div className="flex items-start justify-around my-2">
<div className="flex items-center">
<input
id="loggedIn"
type="checkbox"
value=""
className="w-4 h-4 text-blue-600 bg-gray-100 border-gray-300 rounded focus:ring-blue-500 dark:focus:ring-blue-600 dark:ring-offset-gray-800 focus:ring-2 dark:bg-gray-700 dark:border-gray-600"
/>
<label
htmlFor="loggedIn"
className="ms-1 text-sm font-medium text-primary"
>
Keep me logged in
</label>
</div>
<Link
to="/forgot-password/1"
state={{ for: users.doctor }}
className="text-sm text-primary underline"
>
Forgot Password?
</Link>
</div>
<button className="form-btn my-3">Log In</button>
<small className="block my-1 text-primary text-center">
Do not have an account?{" "}
<Link to="/doctor/sign-up" className="font-bold">
Sign Up
</Link>
</small>
</form>
</div>
</section>
<section className="col-span-4">
<img src={image} alt="Doctors Image" className="w-full" />
</section>
<Toaster />
</main>
);
}
interface Inputs {
email: string;
password: string;
} |
package utils
import (
"encoding/json"
"fmt"
"log"
"os"
"testing"
"github.com/google/go-cmp/cmp"
"github.com/hashicorp/terraform-plugin-framework/types/basetypes"
)
var transformJSON = cmp.FilterValues(func(x, y []byte) bool {
return json.Valid(x) && json.Valid(y)
}, cmp.Transformer("ParseJSON", func(in []byte) (out interface{}) {
if err := json.Unmarshal(in, &out); err != nil {
panic(err) // should never occur given previous filter to ensure valid JSON
}
return out
}))
func TestDynamicValueObject(t *testing.T) {
jsonObj := map[string]interface{}{
"boolValue": true,
"intValue": 42,
"floatValue": 3.14,
"stringValue": "hello",
"objectValue": map[string]interface{}{"key": map[string]interface{}{"key2": map[string]interface{}{"key3": true}}},
"arrayIntValue": []interface{}{1, 2, 3},
"arrayBoolValue": []interface{}{true, false, true},
"arrayStringValue": []interface{}{"hi", "there", "bye"},
"arrayObjectValue": []interface{}{
map[string]interface{}{"key4": map[string]interface{}{"key5": map[string]interface{}{"key6": true}}},
map[string]interface{}{"key4": map[string]interface{}{"key5": map[string]interface{}{"key6": true}}},
map[string]interface{}{"key4": map[string]interface{}{"key5": map[string]interface{}{"key6": true}}},
},
}
types, value := jsonToTFTypes(jsonObj)
obj, diags := basetypes.NewObjectValue(types, value)
if diags.HasError() {
log.Println(diags.Errors())
os.Exit(1)
}
val, err := TFTypesToBytes(obj)
if err != nil {
t.Error(err)
}
bytes, err := json.Marshal(jsonObj)
if err != nil {
t.Error(err)
}
if !cmp.Equal(bytes, val) {
fmt.Println(cmp.Diff(bytes, val, transformJSON))
t.Error(err)
}
}
func TestInconsistentArrayType(t *testing.T) {
jsonObj := map[string]interface{}{
"boolValue": true,
"arrayObjectValue": []interface{}{
map[string]interface{}{"key4": map[string]interface{}{"key5": map[string]interface{}{"key6": true}}},
map[string]interface{}{"key4": map[string]interface{}{"key5": map[string]interface{}{"key6": true}}},
map[string]interface{}{"key7": map[string]interface{}{"key8": map[string]interface{}{"key9": true}}},
},
}
defer func() {
r := recover()
if r == nil {
t.Errorf("The function should have panicked")
}
_ = r
}()
jsonToTFTypes(jsonObj)
}
func TestNullData(t *testing.T) {
jsonObj := map[string]interface{}{
"boolValue": true,
"nullValue": nil,
}
_, diags := JSONToTerraformDynamicValue(jsonObj)
if !diags.HasError() {
t.Error("Diagnostics should have an error")
}
if diags[0].Summary() != "Null or nil is not allowed" {
t.Error("Diagnostics error is unrelated. Not interested in this error.")
}
}
func TestEmptyList(t *testing.T) {
jsonObj := map[string]interface{}{
"boolValue": true,
"arrayObjectValue": []interface{}{},
}
_, diags := JSONToTerraformDynamicValue(jsonObj)
if !diags.HasError() {
t.Error("Diagnostics should have an error")
}
if diags[0].Summary() != "List / Tuple / Set / Array cannot be empty" {
t.Error("Diagnostics error is unrelated. Not interested in this error.")
}
}
func TestEmptyObject(t *testing.T) {
jsonObj := map[string]interface{}{
"boolValue": true,
"emptyObjectValue": map[string]interface{}{"key": map[string]interface{}{"key2": map[string]interface{}{"key3": nil}}},
}
_, diags := JSONToTerraformDynamicValue(jsonObj)
if !diags.HasError() {
t.Error("Diagnostics should have an error")
}
if diags[0].Summary() != "Null or nil is not allowed" {
t.Error("Diagnostics error is unrelated. Not interested in this error.")
}
}
func TestHandlePanicCorrectly(t *testing.T) {
jsonObj := map[string]interface{}{
"boolValue": true,
"arrayObjectValue": []interface{}{
map[string]interface{}{"key4": map[string]interface{}{"key5": map[string]interface{}{"key6": true}}},
map[string]interface{}{"key4": map[string]interface{}{"key5": map[string]interface{}{"key6": true}}},
map[string]interface{}{"key7": map[string]interface{}{"key8": map[string]interface{}{"key9": true}}},
},
}
_, diags := JSONToTerraformDynamicValue(jsonObj)
if !diags.HasError() {
t.Error("Diagnostics should have an error")
}
if diags[0].Summary() != "Complex types do not allow objects with different keys. All objects in list/set/tuple must have the same keys and nested keys." {
t.Error("Diagnostics error is unrelated. Not interested in this error.")
}
} |
<?php
namespace App\Http\Requests\Api\Pokemon;
use Illuminate\Contracts\Validation\ValidationRule;
use Illuminate\Foundation\Http\FormRequest;
class UpdateRequest extends FormRequest
{
/**
* @return array<string, ValidationRule|array<mixed>|string>
*/
public function rules(): array
{
return [
'name' => ['required', 'string', 'max:255'],
'base_experience' => ['required', 'integer'],
'height' => ['required', 'integer'],
'weight' => ['required', 'integer'],
'order' => ['required', 'integer'],
];
}
} |
'use client';
import { Button } from '@/components/ui/button';
import { useToast } from '@/components/ui/use-toast';
import { useCreatePlaygroundMutation } from '@/hooks/useCreatePlaygroundMutation';
import { useSession } from 'next-auth/react';
import {
useParams,
usePathname,
useRouter,
useSearchParams,
} from 'next/navigation';
import React from 'react';
type Props = {};
const UpgradePlayground = (props: Props) => {
const createPlaygroundMutation = useCreatePlaygroundMutation();
const router = useRouter();
const params = useParams();
const searchP = useSearchParams();
const pathname = usePathname().split('/');
const session = useSession();
const isLoggedIn = !!session.data?.user;
const { toast } = useToast();
if (!isLoggedIn) {
return;
}
if (searchP.get('playground-id')) {
return;
}
if (!pathname.includes('visualizer')) {
return;
}
return (
<Button
aria-label="convert-to-playground"
className="min-w-fit mx-2"
onClick={async () => {
const url = new URL(window.location.href);
const res = await createPlaygroundMutation.mutateAsync();
url.searchParams.set('playground-id', String(res.playground.id));
router.push(url.toString());
toast({
title: 'Playground created!',
description:
'All changes will now be saved, you will always be able to see this playground when navigating to playgrounds',
});
}}
variant={'outline'}
>
{createPlaygroundMutation.isLoading
? 'Converting...'
: 'Convert to playground'}
</Button>
);
};
export default UpgradePlayground; |
import { BadRequestException, Inject, Injectable } from '@nestjs/common'
import { ClientGrpc } from '@nestjs/microservices'
import { firstValueFrom } from 'rxjs'
import { ParseResponseGrpc } from '../../grpc-client.helper'
import {
FilterHistoryTransferDTO,
GrpcUserBalanceDTO,
GrpcUserBalanceResponseDTO,
HistoryTransferDTO,
HistoryTransferResponseDTO,
ListGrpcUserBalanceResponseDTO,
} from './user-balance.dto'
import {
IGrpcUserBalanceListRequest,
IGrpcUserBalanceService,
} from './user-balance.interface'
@Injectable()
export class GrpcUserBalanceService {
private boGrpcUserBalanceService: IGrpcUserBalanceService
/**
* constructor
* @param client
*/
constructor(@Inject('BO_USER_BALANCE_PACKAGE') private client: ClientGrpc) {}
/**
* onModuleInit
*/
onModuleInit() {
this.boGrpcUserBalanceService =
this.client.getService<IGrpcUserBalanceService>('BOUserBalanceService')
}
/**
* list
* @param listRequest
* @returns
*/
async list(
listRequest: IGrpcUserBalanceListRequest,
): Promise<ListGrpcUserBalanceResponseDTO> {
const result = await firstValueFrom(
this.boGrpcUserBalanceService.list(listRequest),
)
return ParseResponseGrpc<ListGrpcUserBalanceResponseDTO>(
GrpcUserBalanceDTO,
result,
)
}
/**
* getSummary
* @returns
*/
async getSummary() {
const result = await firstValueFrom(
this.boGrpcUserBalanceService.summary({}),
)
return ParseResponseGrpc<GrpcUserBalanceResponseDTO>(
GrpcUserBalanceDTO,
result,
)
}
/**
* export
* @param listRequest
* @returns
*/
async export(listRequest: IGrpcUserBalanceListRequest) {
const result = await firstValueFrom(
this.boGrpcUserBalanceService.export(listRequest),
)
return result
}
/**
* listExport
* @param listRequest
* @returns
*/
async listExport(listRequest: IGrpcUserBalanceListRequest) {
const result = await firstValueFrom(
this.boGrpcUserBalanceService.listExport(listRequest),
)
return result
}
/**
* listTransfers
* @param listRequest
* @returns
*/
async listTransfers(
listRequest: FilterHistoryTransferDTO,
): Promise<HistoryTransferResponseDTO> {
try {
const result = await firstValueFrom(
this.boGrpcUserBalanceService.listTransfers(listRequest),
)
return ParseResponseGrpc<HistoryTransferResponseDTO>(
HistoryTransferDTO,
result,
)
} catch (error) {
throw new BadRequestException(error)
}
}
/**
* exportTransfers
* @param listRequest
* @returns
*/
async exportTransfers(listRequest: FilterHistoryTransferDTO) {
const result = await firstValueFrom(
this.boGrpcUserBalanceService.exportListTransfers(listRequest),
)
return result.data
}
} |
import java.util.Arrays;
import java.util.Scanner;
public class Solution {
static Scanner sc = new Scanner(System.in);
static StringBuilder sb = new StringBuilder();
// 테스트케이스 입력받기
static int testCase = sc.nextInt();
static int N; // 섬의 개수
static double E; // 세율
static long[][] map; // 섬의 x, y 좌표
static double[] minCost; // 최소 비용을 저장할 변수
static double ans; // 답을 저장할 변수
static boolean[] visited; // 방문 체크
static final long INF = Long.MAX_VALUE;
static void input() {
// 섬의 갯수 입력받기
N = sc.nextInt();
// 섬의 x, y좌표를 저장할 배열
map = new long[N][2];
// 섬들의 x좌표 입력받기
for(int i=0;i<N;i++) {
map[i][0] = sc.nextLong();
}
// 섬들의 y좌표 입력받기
for(int i=0;i<N;i++) {
map[i][1] = sc.nextLong();
}
// 세율 입력받기
E = sc.nextDouble();
}
static void solve() {
// 최저 비용과 방문여부를 저장할 배열 생성
minCost = new double[N];
visited = new boolean[N];
// 최대값으로 초기화
Arrays.fill(minCost, INF);
// 시작 섬을 0번 노드로 설정
int start = 0;
minCost[start] = 0;
// 모든 섬을 순회하며 최소 비용 갱신
for(int i=0;i<N;i++) {
// 현재 섬에서 연결되는 간선 중 가장 가중치가 작은 간선을 찾는다.
int minNode = -1;
for(int j=0;j<N;j++) {
if(!visited[j] && (minNode == -1 || minCost[j] < minCost[minNode])) {
minNode = j;
}
}
// 최소 비용을 갖는 섬을 방문한다.
visited[minNode] = true;
// 현재 섬과 연결된 섬의 비용을 갱신한다.
for(int j=0;j<N;j++) {
// 방문 안한 섬이면
if(!visited[j]) {
// 거리 값을 계산해주고
double cost = cal(minNode, j);
if(cost < minCost[j]) {
minCost[j] = cost;
}
}
}
}
// 최소 비용을 구해준다.
ans = 0;
for(int i=0;i<N;i++) {
ans += minCost[i];
}
}
public static void main(String[] args) {
// 테스트 케이스만큼 반복
for(int tc=1;tc<=testCase;tc++) {
input();
// solve 메서드
solve();
// 세율 곱해서 갱신
ans *= E;
// 형식에 맞게 담아주기
sb.append("#"+tc+" "+ Math.round(ans)+"\n");
}
System.out.println(sb);
}
// 거리 계산 메서드
static double cal(int i, int j) {
// 거리계산
double cost = Math.pow(Math.abs(map[i][0] - map[j][0]), 2) + Math.pow(Math.abs(map[i][1] - map[j][1]), 2);
return cost;
}
} |
import React, { useContext, useEffect, useState } from 'react';
import { AuthContext } from '../../Provider/AuthProvider';
import Tittle from '../../Common_Component\'s/Tittle';
import useTitle from '../../Hooks/useTitle';
const MyEnrolledClasses = () => {
useTitle('Dashboard/My Enrolled Classes')
const [myClasses, setMyClasses] = useState([]);
console.log(myClasses);
const { user } = useContext(AuthContext);
const { email } = user || {}
useEffect(() => {
fetch(`https://the-music-mystrey-server.vercel.app/myEnrolledClasses/${email}`)
.then(res => res.json())
.then(data => setMyClasses(data))
}, [user])
return (
<div className='w-full'>
<Tittle heading={"My Enrolled Classes"}></Tittle>
<div className="overflow-x-auto w-10/12 mx-auto">
<table className="table mt-8">
{/* head */}
<thead>
<tr className='text-center'>
<th className='font-bold text-black text-base border-2 border-black hover:bg-teal-500 duration-700'>Course Image</th>
<th className='font-bold text-black text-base border-2 border-black hover:bg-teal-500 duration-700'>Course Name</th>
<th className='font-bold text-black text-base border-2 border-black hover:bg-teal-500 duration-700'>Teacher Name</th>
<th className='font-bold text-black text-base border-2 border-black hover:bg-teal-500 duration-700'>Payed</th>
<th className='font-bold text-black text-base border-2 border-black hover:bg-teal-500 duration-700'>Id</th>
</tr>
</thead>
<tbody>
{
myClasses.map(enrolledClass => <tr key={enrolledClass._id} enrolledClass={enrolledClass}>
<td className='font-bold text-black text-base border-2 border-black hover:bg-teal-500 duration-700 text-center'>
<div className="flex items-center space-x-3">
<div className="avatar">
<div className="mask mask-circle w-16 h-1w-16">
<img src={enrolledClass.courseImg}/>
</div>
</div>
</div>
</td>
<td className='font-bold text-black text-base border-2 border-black hover:bg-teal-500 duration-700 text-center'>{enrolledClass.courseName}</td>
<td className='font-bold text-black text-base border-2 border-black hover:bg-teal-500 duration-700 text-center'>{enrolledClass.teacherName}</td>
<td className='font-bold text-black text-base border-2 border-black hover:bg-teal-500 duration-700 text-center'>$ {enrolledClass.Price}</td>
<td className='font-bold text-black text-base border-2 border-black hover:bg-teal-500 duration-700 text-center'>{enrolledClass.transactionId}</td>
</tr>)
}
</tbody>
</table>
</div>
</div>
);
};
export default MyEnrolledClasses; |
'use client';
import React, { useEffect, useState } from 'react';
import _ from 'lodash';
import { QuestionTypes } from '@/app/data/question';
import { Container, Row } from 'react-bootstrap';
import { FontAwesomeIcon } from '@fortawesome/react-fontawesome';
import { faSpinner } from '@fortawesome/free-solid-svg-icons'
import styles from './Questions.module.css';
import QuestionBox from './QuestionBox/QuestionBox';
import Result from '../Result/Result';
type QuestionTypeProp = {
questions: QuestionTypes[];
};
const Questions = ({ questions }: QuestionTypeProp) => {
const [currentQuestions, setCurrentQuestions] = useState(questions);
const [currentQuestionIndex, setCurrentQuestionIndex] = useState(0);
const [userAnswers, setUserAnswers] = useState([] as string[]);
const [totalScore, setTotalScore] = useState(0);
const [isLoading, setIsLoading] = useState(true);
const [isSubmitting, setIsSubmitting] = useState(false);
const [isSubmittingExam, setIsSubmittingExam] = useState(false);
useEffect(() => {
setTimeout(() => {
setIsLoading(false)
}, 1000)
}, [isLoading]);
const handleSubmitOption = (answer: string) => {
if (!isSubmitting) {
setUserAnswers([...userAnswers, answer]);
setIsSubmitting(true);
setTimeout(() => {
if (currentQuestionIndex < questions.length - 1) {
setCurrentQuestionIndex(currentQuestionIndex + 1);
setIsSubmitting(false);
}
}, 1000);
}
};
const handleSubmitExam = () => {
let userTotalScore = 0
const questionAnswers = _.toArray(_.mapValues(currentQuestions, 'correctAnswer'))
questionAnswers.map((ans, i) => {
if(_.isEqual(ans, userAnswers[i])) {
userTotalScore += 1
}
})
setTotalScore(userTotalScore);
setIsLoading(true)
setIsSubmittingExam(true)
};
const renderLoading = () => {
return (
<div className={styles.loadingContainer} >
<FontAwesomeIcon
size="2xl"
icon={faSpinner}
spin={true}
/>
</div>
)
}
const currentQuestion = currentQuestions[currentQuestionIndex];
return (
<Container className={styles.componentContainer}>
<Row>
{
isLoading ? renderLoading()
: (
isSubmittingExam ? (
isLoading ? renderLoading() :
<Result totalQuestionLength={_.size(questions)} totalScore={totalScore}/>
) : (
<QuestionBox
questionLength={_.size(questions)}
questionNumber={currentQuestionIndex + 1}
instruction={currentQuestion.instruction}
question={currentQuestion.question}
options={currentQuestion.options}
timeLimit={currentQuestion.timeLimit}
onSubmitExam={handleSubmitExam}
onSubmitOption={handleSubmitOption}
/>
)
)
}
</Row>
</Container>
);
};
export default Questions; |
using System;
using System.Data;
namespace Pattern
{
class Program
{
static string[] patterns = new string[]
{
"Right Triangle Star Pattern",
"Left Triangle Star Pattern",
"Pyramid Star Pattern",
"Diamond Star Pattern",
"Right Triangle Number Pattern",
"Right Triangle Repeat Number Pattern",
"Pyramid Number Pattern (Asc)",
"Pyramid Number Pattern (Desc)",
"Pyramid Repeat Number Pattern",
"Diamond Alphabet Pattern Way 1",
"Diamond Alphabet Pattern Way 2"
};
static void Main(string[] args)
{
while (true)
{
int userChoice = GetUserChoice();
int rowInput = GetRowInput(userChoice);
switch (userChoice)
{
case 1:
RightTriangleStar(rowInput);
break;
case 2:
LeftTriangleStar(rowInput);
break;
case 3:
PyramidStar(rowInput);
break;
case 4:
DiamondStar(rowInput);
break;
case 5:
RightAngleNumber(rowInput);
break;
case 6:
RightAngleNumberRepeat(rowInput);
break;
case 7:
PyramidAscending(rowInput);
break;
case 8:
PyramidDescending(rowInput);
break;
case 9:
PyramidRepeat(rowInput);
break;
case 10:
DiamondAlphabetWay1(rowInput);
break;
case 11:
DiamondAlphabetWay2(rowInput);
break;
}
Console.WriteLine("Press any key to continue or press 0 to exit: ");
char keyChar = Console.ReadKey(true).KeyChar;
if (keyChar == '0') break;
}
}
static int GetUserChoice()
{
while (true)
{
for (int i = 0; i < patterns.Length; i++)
{
Console.WriteLine($"{i+1}. {patterns[i]}");
}
Console.Write("Please enter a number from the list below to choose your pattern: ");
string userInput = Console.ReadLine();
if (string.IsNullOrWhiteSpace(userInput))
{
Console.WriteLine("Error! Input cannot be blank!");
continue;
}
if (!int.TryParse(userInput, out int userChoice) || userChoice < 1 || userChoice > patterns.Length)
{
Console.WriteLine("Error! Please only enter a number between 1 and {0}!", patterns.Length);
continue;
}
Console.WriteLine("You've selected: {0}", patterns[userChoice - 1]);
return userChoice;
}
}
static int GetRowInput(int userChoice)
{
while (true)
{
Console.Write("Please enter the number of rows you want for {0}: ", patterns[userChoice - 1]);
string userInput = Console.ReadLine();
if (string.IsNullOrWhiteSpace(userInput))
{
Console.WriteLine("Error! Input cannot be blank!");
continue;
}
if (!int.TryParse(userInput, out int rowInput) || rowInput < 1)
{
Console.WriteLine("Error! Only a positive whole number is accepted!");
continue;
}
return rowInput;
}
}
static void RightTriangleStar(int rowInput)
{
for (int i = 1; i <= rowInput; i++)
{
for (int j = 1; j <= i; j++)
{
Console.Write("*");
}
Console.WriteLine();
}
}
static void LeftTriangleStar(int rowInput)
{
for (int i = 1; i <= rowInput; i++)
{
for (int space = 1; space <= rowInput - i; space++)
{
Console.Write(" ");
}
for (int j = 1; j <= i; j++)
{
Console.Write("*");
}
Console.WriteLine();
}
}
static void PyramidStar(int rowInput)
{
for (int i = 1; i <= rowInput; i++)
{
for (int space = i; space <= rowInput; space++)
{
Console.Write(" ");
}
for (int j = 1; j < i; j++)
{
Console.Write("*");
}
for (int k = 1; k <= i; k++)
{
Console.Write("*");
}
Console.WriteLine();
}
}
static void DiamondStar(int rowInput)
{
for (int i = 1; i < rowInput; i++)
{
for (int space = i; space <= rowInput; space++)
{
Console.Write(" ");
}
for (int j = 1; j < i; j++)
{
Console.Write($"{"*",2}");
}
for (int k = 1; k <= i; k++)
{
Console.Write($"{"*",2}");
}
Console.WriteLine();
}
for (int i = 1; i <= rowInput; i++)
{
for (int space = 1; space <= i; space++)
{
Console.Write(" ");
}
for (int j = i; j < rowInput; j++)
{
Console.Write($"{"*",2}");
}
for (int k = i; k <= rowInput; k++)
{
Console.Write($"{"*",2}");
}
Console.WriteLine();
}
}
static void RightAngleNumber(int rowInput)
{
for (int i = 1; i <= rowInput; i++)
{
for (int j = 1; j <= i; j++)
{
Console.Write(j);
}
Console.WriteLine();
}
}
static void RightAngleNumberRepeat(int rowInput)
{
for (int i = 1; i <= rowInput; i++)
{
for (int j = 1; j <= i; j++)
{
Console.Write(i);
}
Console.WriteLine();
}
}
static void PyramidAscending(int rowInput)
{
for (int i = 1; i <= rowInput; i++)
{
for (int s = i; s <= rowInput; s++)
{
Console.Write(" ");
}
for (int j = 1; j <= 2*i-1; j++)
{
Console.Write(j);
}
Console.WriteLine();
}
}
static void PyramidDescending(int rowInput)
{
for (int i = 1; i <= rowInput; i++)
{
for (int space = 1; space < i; space++)
{
Console.Write(" ");
}
for (int j = 1; j <= 2*(rowInput - i + 1) - 1; j++)
{
Console.Write($"{j,2}");
}
Console.WriteLine();
}
}
static void PyramidRepeat(int rowInput)
{
for (int i = 1; i <= rowInput; i++)
{
for (int s = i; s <= rowInput; s++)
{
Console.Write(" ");
}
for (int j = 1; j <= 2 * i - 1; j++)
{
Console.Write($"{i,2}");
}
Console.WriteLine();
}
}
static void DiamondAlphabetWay1(int rowInput)
{
char ch = 'A';
for (int i = 1; i < rowInput; i++)
{
for (int s = i; s <= rowInput; s++)
{
Console.Write(" ");
}
for (int j = 1; j <= i; j++)
{
Console.Write($"{ch,2}");
}
for (int k = 1; k < i; k++)
{
Console.Write($"{ch,2}");
}
Console.WriteLine();
ch++;
}
for (int i = 1; i <= rowInput; i++)
{
for (int s = 1; s <= i; s++)
{
Console.Write(" ");
}
for (int j = i; j <= rowInput; j++)
{
Console.Write($"{ch,2}");
}
for (int j = i; j < rowInput; j++)
{
Console.Write($"{ch,2}");
}
Console.WriteLine();
ch--;
}
}
static void DiamondAlphabetWay2(int rowInput)
{
char ch = 'A';
for (int i = 1; i <= rowInput; i++)
{
for (int s = i; s <= rowInput; s++)
{
Console.Write(" ");
}
for (int j = 1; j <= 2*i-1; j++)
{
Console.Write($"{ch,2}");
}
Console.WriteLine();
ch++;
}
ch = (char)(ch - 2);
for (int i = 1; i <= rowInput; i++)
{
for (int s = 1; s <= i + 1; s++)
{
Console.Write(" ");
}
for (int j = 1; j <= 2*(rowInput-i)-1; j++)
{
Console.Write($"{ch,2}");
}
Console.WriteLine();
ch--;
}
}
}
} |
---
title: 【生活】麥當勞買一送一可以,星巴克要小心
description: 買一送一在消費心理上有不同的狀態。麥當勞的買一送一解決了生理需求和提供便利,而星巴克的買一送一可能追求社交地位和心理滿足。買一送一觸發情緒,影響購買決策。選擇買一送一反映價值觀和生活方式,但要建立在必要需求上。
date: 2023-10-27
image: cover.png
categories: [職涯與生活]
keywords: ETF, Podcast, Podcaster, 保險, 儲蓄, 台股, 基金, 懶得變有錢, 房地產, 投資, 投資理財, 支出, 收入, 月配息, 理財, 理財規劃, 瑪斯理財兩三事, 稅務, 總體經濟, 美股, 職涯心得, 股利收入, 複委託, 記帳, 讀書心得, 財務規劃, 財商, 貸款, 資產配置, 退休規劃, 開源節流
tags: [收支, 理財規劃, 職涯與生活, 財務規劃]
Status: Notion
slug: 【Income and Expenses】McDonald's buy one get one free is available, be careful with Starbucks.
---
## **懶人提要**
各位想懶還不能懶以及不能懶但很像懶的懶粉們,今天我們來聊聊**[買一送一](https://www.storm.mg/lifestyle/4889362)**這個看似美好,但**[買一送一](https://www.storm.mg/lifestyle/4889362)**還是有不同的消費心理狀態。你以為隨便**[買一送一](https://www.storm.mg/lifestyle/4889362)**都是一種好事嗎?
### **麥當勞的買一送一:不只是食物,重點它算得上生理需求**

首先,我們來談談[麥當勞](https://www.mcdonalds.com/tw/zh-tw.html)。當你選擇[麥當勞](https://www.mcdonalds.com/tw/zh-tw.html)的[買一送一](https://www.storm.mg/lifestyle/4889362),你不只是在買食物,你是在買時間和便利。這個選擇不僅解決了你的飢餓問題,還讓你的生活更有效率。幾乎沒有人覺得吃[麥當勞](https://www.mcdonalds.com/tw/zh-tw.html)是一種時尚、侈奢的樣態(不討論弱勢家庭看待[麥當勞](https://www.mcdonalds.com/tw/zh-tw.html)的態度)。這麼說來[麥當勞](https://www.mcdonalds.com/tw/zh-tw.html)的**[買一送一](https://www.storm.mg/lifestyle/4889362)**就是一種可以盡情消費的高CP表現!
### 連買個麥當勞買一送一都要這麼理性的嗎?靠,理財也太累了吧!
當然不是連買一個[麥當勞](https://www.mcdonalds.com/tw/zh-tw.html)就要這麼累!這裡想表達的是我們會買[麥當勞](https://www.mcdonalds.com/tw/zh-tw.html)**[買一送一](https://www.storm.mg/lifestyle/4889362)**重點還是在生理需求加上CP值的一種呈現。
不斷強調生理需求的原因是因為在馬斯洛的需求理論裡面生理需求本來就是一種不可避免的需求。
### **星巴克:是超越生理需求的咖啡,也是社交象徵以及心理滿足**

接著,我們來看看[星巴克](https://www.starbucks.com.tw/)。三不五時[星巴克](https://www.starbucks.com.tw/)也會有買一送一的時候,但是你可以回想一下每一次去買[星巴克](https://www.starbucks.com.tw/)的時候是不是心裡有一種好像賺到的感覺!畢竟咖啡是喝不飽的,那我們又為什麼一定要買[星巴克](https://www.starbucks.com.tw/)買一送一,而不是CityCaffee寄杯買一送一呢?
你可能是在追求一種社交地位。每次你看到那個綠色的商標,你會不自覺地想到買一送一,偶爾的買一送一就會讓人心裡癢癢,但這真的值得嗎?從我的角度,喝[星巴克](https://www.starbucks.com.tw/)比較像娛樂支出,而不是飲食支出啦!
### **買一送一,是快樂還是壓力?**
買一送一這個概念會觸發我們的某種情緒。對於[麥當勞](https://www.mcdonalds.com/tw/zh-tw.html),那可能是滿足和安全感;對於[星巴克](https://www.starbucks.com.tw/),那可能是自豪或者壓力。這些情緒會影響我們的購買決策。
當然不會有買喝的東西的時候是一種壓力,但是你可以回想一下當今天辦公室的人都在揪[星巴克](https://www.starbucks.com.tw/)買一送一的時候1杯120塊錢的飲料縱使買一送一還是需要60塊錢!這個時候如果收入高一點的人當然無所謂,但是從理財的角度來看1杯60塊錢的飲料他就不一定是必要性的支出或真的需求的支出,他可能就變成了你在辦公室社交上面的一種連結。
### **你跑去麥當勞買一送一說明了什麼?**
當你在社交媒體上看到朋友們炫耀他們的買一送一,你會不會也想參一腳?這就是社會曝光和從眾效應在作祟。
之前我曾經分享過我在高鐵站看到一個正妹打破玻璃瓶的牛奶的故事,事情是這個樣子的,有一天我在高鐵站前面有一個短裙正妹迎面走過來就當我們擦身而過的時候匡啷一聲玻璃瓶掉在地上白色的液體灑滿一地,我連看都不用看就知道那個是Dr milk。所以當天早上我的早餐就變成了Dr.milk。
我們都會有被觸發的時候,就像在社群上面看到朋友都在曬[麥當勞](https://www.mcdonalds.com/tw/zh-tw.html)的買一送一,我們就也會跟風衝一波一樣。
(我今天也想吃[麥當勞](https://www.mcdonalds.com/tw/zh-tw.html)啦)
### **買一送一沒錯啊!但要建立在你的必要需求上**
想像一下,你走在街上,看到[麥當勞](https://www.mcdonalds.com/tw/zh-tw.html)和[星巴克](https://www.starbucks.com.tw/),兩家都有買一送一的優惠。你的選擇會反映出你的價值觀和生活方式。如果你的買一送一建立在「必要」那怎麼買都沒問題!如果只是「需要」或是「想要」那就可以思考看是有沒有一定要。

## 懶得有結論
{{< quote author="懶得變有錢 | 瑪斯就是懶大" source="About 懶得變有錢" url="https://lazytoberich.com.tw/about-me/">}}
我知道有的時候消費很難理性,但就是因為很難理性所以理財才會很無聊,因為理財很無聊就很難有趣,所以大部分的人理財就會失敗。每次寫文章寫到很感慨的時候我就希望有多少人能夠接受這麼無聊的事情聽聽我的podcast,讓我陪你們一起走過這個無聊的時光,讓理財有趣一點。
{{< /quote >}}

<iframe id="embedPlayer" src="https://embed.podcasts.apple.com/us/podcast/%E6%87%B6%E5%BE%97%E8%AE%8A%E6%9C%89%E9%8C%A2/id1707756115?itsct=podcast_box_player&itscg=30200&ls=1&theme=auto" height="450px" frameborder="0" sandbox="allow-forms allow-popups allow-same-origin allow-scripts allow-top-navigation-by-user-activation" allow="autoplay *; encrypted-media *; clipboard-write" style="width: 100%; max-width: 660px; overflow: hidden; border-radius: 10px; transform: translateZ(0px); animation: 2s ease 0s 6 normal none running loading-indicator; background-color: rgb(228, 228, 228);"></iframe>
## 👉[透過更多地方收聽「懶得變有錢」Podcast](https://solink.soundon.fm/lazytoberich) |
import 'package:bloc_counter/logic/cubit/counter_cubit.dart';
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
class HomeScreen extends StatefulWidget {
const HomeScreen({
super.key,
required this.title,
required this.color,
});
final String title;
final Color color;
@override
State<HomeScreen> createState() => _HomeScreenState();
}
class _HomeScreenState extends State<HomeScreen> {
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
backgroundColor: widget.color,
title: Text(widget.title, style: const TextStyle(color: Colors.white),),
),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
const Text(
'You have pushed the button this many times:',
style: TextStyle(fontWeight: FontWeight.bold),
),
BlocConsumer<CounterCubit, CounterState>(
listener: (context, state) {
if (state.wasIncremented == true) {
ScaffoldMessenger.of(context).showSnackBar(
const SnackBar(
content: Text("Incremented"),
duration: Duration(milliseconds: 300),
),
);
} else if (state.wasIncremented == false) {
ScaffoldMessenger.of(context).showSnackBar(
const SnackBar(
content: Text("Decremented"),
duration: Duration(milliseconds: 300),
),
);
}
},
builder: (context, state) {
if (state.counterValue < 0) {
return Text(
'BRR, NEGATIVE ${state.counterValue}',
style: Theme.of(context).textTheme.headlineMedium,
);
} else if (state.counterValue % 2 == 0) {
return Text(
'YAAAY ${state.counterValue}',
style: Theme.of(context).textTheme.headlineMedium,
);
} else if (state.counterValue == 5) {
return Text(
'HMM, NUMBER 5 ',
style: Theme.of(context).textTheme.headlineMedium,
);
} else {
return Text(
state.counterValue.toString(),
style: Theme.of(context).textTheme.headlineMedium,
);
}
},
),
const SizedBox(
height: 30,
),
Row(
mainAxisAlignment: MainAxisAlignment.center,
crossAxisAlignment: CrossAxisAlignment.center,
children: [
FloatingActionButton(
onPressed: () {
BlocProvider.of<CounterCubit>(context).decrement();
},
tooltip: 'Decrement',
child: const Icon(Icons.remove),
),
const SizedBox(
width: 100,
),
FloatingActionButton(
onPressed: () {
BlocProvider.of<CounterCubit>(context).increment();
},
tooltip: 'Increment',
child: const Icon(Icons.add),
),
],
),
const SizedBox(
height: 30,
),
OutlinedButton(
onPressed: () {
Navigator.of(context).pushNamed('/second');
},
style: OutlinedButton.styleFrom(
side: BorderSide(color: widget.color),
),
child: Text(
"Go to Second Screen",
style: TextStyle(fontSize: 20, color: widget.color),
),
),
const SizedBox(
height: 20,
),
OutlinedButton(
onPressed: () {
Navigator.of(context).pushNamed('/third');
},
style: OutlinedButton.styleFrom(
side: BorderSide(color: widget.color),
),
child: Text(
"Go to Third Screen",
style: TextStyle(fontSize: 20, color: widget.color),
),
)
],
),
),
);
}
} |
package basicdatastructure;
import org.junit.Test;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
* Assignment1Q2: Utility class for working with Armstrong numbers.
*/
public final class Assignment1Q2 {
// Logger for logging messages
private static final Logger logger = Logger.getLogger(Assignment1Q2.class.getName());
// Private constructor to prevent instantiation
public Assignment1Q2() {
}
/**
* Checks if a given number is an Armstrong number.
*
* @param num The number to check.
* @return True if the number is an Armstrong number, false otherwise.
*/
public static boolean isArmstrongNumber(int num) {
final int originalNum = num;
int sum = 0;
while (num != 0) {
final int rem = num % 10;
sum += (rem * rem * rem);
num = num / 10;
}
return sum == originalNum;
}
/**
* Prints Armstrong numbers in the specified range.
*
* @param start The start of the range.
* @param end The end of the range.
*/
public static void printArmstrongNumbersInRange(final int start, final int end) {
if (start <= 0 || end <= 0 || start > end) {
logger.log(Level.INFO, "Invalid input range. Please provide valid positive integers.");
return;
}
logger.log(Level.INFO, "Armstrong numbers in the range " + start + " to " + end + ":");
for (int i = start; i <= end; i++) {
if (isArmstrongNumber(i)) {
logger.log(Level.INFO, String.valueOf(i));
}
}
}
/**
* JUnit test for the printArmstrongNumbersInRange method.
*/
@Test
public void testPrintArmstrongNumbersInRange() {
// Test with a valid range
Assignment1Q2.printArmstrongNumbersInRange(100, 999);
// Test with an invalid range (start > end)
logger.log(Level.INFO, "Expected: Invalid input range. Please provide valid positive integers.");
Assignment1Q2.printArmstrongNumbersInRange(999, 100);
// Test with an invalid range (negative start)
logger.log(Level.INFO, "Expected: Invalid input range. Please provide valid positive integers.");
Assignment1Q2.printArmstrongNumbersInRange(-100, 999);
// Test with an invalid range (negative end)
logger.log(Level.INFO, "Expected: Invalid input range. Please provide valid positive integers.");
Assignment1Q2.printArmstrongNumbersInRange(100, -999);
// Test with an invalid range (both negative)
logger.log(Level.INFO, "Expected: Invalid input range. Please provide valid positive integers.");
Assignment1Q2.printArmstrongNumbersInRange(-100, -999);
// Test with an invalid range (both zero)
logger.log(Level.INFO, "Expected: Invalid input range. Please provide valid positive integers.");
Assignment1Q2.printArmstrongNumbersInRange(0, 0);
}
/**
* Main method to demonstrate the usage of Armstrong number utility methods.
*
* @param args Command-line arguments (not used in this context).
*/
public static void main(String[] args) {
final int num1 = 100;
final int num2 = 999;
// Print Armstrong numbers in the specified range
printArmstrongNumbersInRange(num1, num2);
}
} |
import { Todo } from '@todo-app/shared/domain';
export async function getTodos(
token: string | null
): Promise<{ message: string; todos: Todo[] }> {
const res = await fetch('/api/todo', {
headers: {
Authorization: 'Bearer ' + token,
},
});
if (res.status !== 200) {
throw new Error('Failed to fetch todos.');
}
return res.json();
}
export async function addTodo(
title: string,
token: string | null
): Promise<{ message: string; todo: Todo }> {
const res = await fetch('/api/todo', {
method: 'POST',
headers: {
Authorization: 'Bearer ' + token,
'Content-Type': 'application/json',
},
body: JSON.stringify({ title }),
});
if (res.status !== 201) {
throw new Error('Creating a todo failed!');
}
return res.json();
}
export async function addManyTodos(
token: string | null,
todos: Todo[]
): Promise<{ message: string; todos: Todo[] }> {
const res = await fetch('/api/todo/add-many', {
method: 'POST',
headers: {
Authorization: 'Bearer ' + token,
'Content-Type': 'application/json',
},
body: JSON.stringify({ todos }),
});
if (res.status !== 201) {
throw new Error('Creating a todos failed!');
}
return res.json();
}
export async function updateTodoStatus(
id: string,
token: string | null
): Promise<{ message: string }> {
const res = await fetch('/api/todo/' + id, {
method: 'PUT',
headers: {
Authorization: 'Bearer ' + token,
'Content-Type': 'application/json',
},
});
if (res.status !== 200) {
throw new Error('Updating a todo failed!');
}
return res.json();
}
export async function updateTodosOrder(
token: string | null,
todos: Todo[]
): Promise<{ message: string }> {
const res = await fetch('/api/todo/update-order', {
method: 'PUT',
headers: {
Authorization: 'Bearer ' + token,
'Content-Type': 'application/json',
},
body: JSON.stringify({ todos }),
});
if (res.status !== 200) {
throw new Error('Saving todos order failed!');
}
return res.json();
}
export async function deleteTodo(
id: string,
token: string | null
): Promise<{ message: string; todoId: string }> {
const res = await fetch('/api/todo/' + id, {
method: 'DELETE',
headers: {
Authorization: 'Bearer ' + token,
},
});
if (res.status !== 200) {
throw new Error('Deleting a todo failed!');
}
return res.json();
}
export async function deleteCompletedTodos(
token: string | null
): Promise<{ message: string }> {
const res = await fetch('/api/todo/delete-completed', {
method: 'delete',
headers: {
Authorization: 'Bearer ' + token,
},
});
if (res.status !== 200) {
throw new Error('Deleting completed todos failed!');
}
return res.json();
} |
@extends('layout.app')
@section('content')
<div class="container">
<div class="row">
<div class="col-lg-12 text-center">
<h3 class="page-title">Edit Device</h3>
</div>
<div class="col-lg-12 mt-5">
<form action="{{ route('devices.update', $device->id) }}" method="POST" enctype="multipart/form-data">
@csrf
@method('PUT')
<div class="form-group">
<label for="location_id">Location Id:</label>
<input type="text" class="form-control" id="location_id" name="location_id" value="{{ $device->location_id }}" readonly>
</div>
<br>
<div class="form-group">
<label for="number">Number:</label>
<input type="number" class="form-control" id="number" name="number" value="{{ $device->number }}" required>
</div>
<br>
<div class="form-group">
{{-- TODO: store the device types in the database and fetch and list them here instead of hardcoding --}}
<label for="type">Type:</label>
<select class="form-control" id="type" name="type" required>
<option value="">Select a Type</option>
<option value="1" {{ $device->type == 1 ? 'selected' : '' }}>POS</option>
<option value="2" {{ $device->type == 2 ? 'selected' : '' }}>KIOSK</option>
<option value="3" {{ $device->type == 3 ? 'selected' : '' }}>Digital Signage</option>
</select>
</div>
<br>
<div class="form-group">
<label for="image">Image:</label>
<div>
@if ($device->image)
<img src="{{ asset('storage/' . $device->image) }}" alt="Current Image" style="max-width: 200px;">
@else
<p>No image uploaded</p>
@endif
</div>
</div>
<div class="form-group">
<label for="new_image">Upload New Image:</label>
<input type="file" class="form-control-file" id="new_image" name="new_image" accept="image/*">
</div>
<br>
<div class="form-group">
<label>Status:</label><br>
<div class="form-check form-check-inline">
<input class="form-check-input" type="radio" name="status" id="status_active" value="1" {{ $device->status == 1 ? 'checked' : '' }} required>
<label class="form-check-label" for="status_active">Active</label>
</div>
<div class="form-check form-check-inline">
<input class="form-check-input" type="radio" name="status" id="status_inactive" value="0" {{ $device->status == 0 ? 'checked' : '' }}>
<label class="form-check-label" for="status_inactive">Inactive</label>
</div>
</div>
<br>
<button type="submit" class="btn btn-primary">Update Device</button>
<a href="{{ url()->previous() }}" class="btn btn-secondary">Back</a>
</form>
</div>
</div>
</div>
@endsection |
import * as MySqlDataSource from '../../models/MySqlDataSource';
import * as brapi from '../../data/network/brapi.api';
import TestHelper from '../../tests/TestHelperSQLite';
import initializeDatabase from '../../helpers/initializeDatabase';
import brapApiMock from '../../tests/brap.api.mock';
import investimentosService from '../investimentos.service';
import WalletStock from '../../models/entities/WalletStock';
import IClient from '../../interfaces/IClient';
import clientService from '../client.service';
describe('Testes da camada de service(investimentos) da aplicação', () => {
let mockGetDataSource: jest.SpyInstance;
let mockBrapApi: jest.SpyInstance;
beforeAll(async () => {
await TestHelper.instance.setupTestDB();
mockGetDataSource = jest
.spyOn(MySqlDataSource, 'default')
.mockReturnValue(TestHelper.instance.getDataSource());
mockBrapApi = jest
.spyOn(brapi, 'default')
.mockReturnValue(brapApiMock());
await initializeDatabase();
const payload = {
name: 'alan Fernandes',
username: 'AjnfXP',
password: '123456',
} as IClient;
const newClient = await clientService.setClient(payload);
const dataSource = await TestHelper.instance.getDataSource();
await dataSource.createQueryBuilder().insert().into(WalletStock)
.values([
{
stockId: 10,
walletId: newClient.wallet.id,
quantity: 150,
},
{
stockId: 5,
walletId: newClient.wallet.id,
quantity: 200,
},
{
stockId: 30,
walletId: newClient.wallet.id,
quantity: 300,
},
{
stockId: 40,
walletId: newClient.wallet.id,
quantity: 500,
},
])
.execute();
}, 60000);
afterAll(async () => {
await TestHelper.instance.dropDB();
mockGetDataSource.mockClear();
mockBrapApi.mockClear();
}, 60000);
it(
'"listStocksSeparately()" - Testa se a função retorna todas a ações disponíveis na corretora separadas por "purchased" e "available".',
(done) => {
investimentosService.listStocksSeparately(1).then((list) => {
expect(list).toHaveProperty('purchased');
expect(list).toHaveProperty('available');
done();
});
},
);
it(
'"listStocksSeparately()" - Testa se as ações em "purchased" contém a quantidade comprada.',
(done) => {
investimentosService.listStocksSeparately(1).then((list) => {
expect(list.purchased[0]).toHaveProperty('purchasedQuantity');
done();
});
},
);
}); |
import { Box, Typography } from "@mui/material";
import { useContext, useEffect, useState } from "react";
import Footer from "../../components/shared/Footer";
import PageHeader from "../../components/shared/PageHeader";
import DriverCardList from "../../components/driver/views/DriverCardList";
import SearchFilterForm from "../../components/shared/SearchFilterForm";
import { Driver } from "../../services/dataTypes";
import { useNavigate } from "react-router-dom";
import { driverService } from "../../services/driverService";
import { UserContext, UserContextType } from "../../contexts/UserContext";
import { MessageContext, MessageContextType } from "../../contexts/MessageContext";
const DriverListPage = () => {
const { user } = useContext(UserContext) as UserContextType;
const navigate = useNavigate();
const { setMessage } = useContext(MessageContext) as MessageContextType;
const [filteredDrivers, setFilteredDrivers] = useState<Driver[]>([]);
const [driverList, setDriverList] = useState<Driver[]>([]);
const [data, setData] = useState<Partial<Driver>>({
fullName: "",
address: "",
vehicleAssigned: "",
contactNumber: "",
licenseNumber: "",
expirationDate: "",
dlCodes: ""
});
useEffect(() => {
if (user !== null) {
driverService
.getDriversByOperator(user.id)
.then((response) => {
setDriverList(response);
})
.catch((error) => {
setMessage(error.response.data || "Failed to retrieve drivers.")
});
}
else{
console.log('No user logged in')
setMessage("No user logged in");
window.localStorage.removeItem("ARANGKADA_USER");
navigate('/', { replace: true });
}
}, [user, setMessage, navigate]);
useEffect(() => {
setFilteredDrivers(driverList);
}, [driverList]);
const handleFilterSubmit = (filters: Partial<Driver>) => {
const filtered = driverList.filter((driver) => {
for (const key in filters) {
if (
filters.hasOwnProperty(key) &&
driver.hasOwnProperty(key) &&
filters[key] !== undefined &&
filters[key] !== null &&
String(driver[key as keyof Driver])
.toLowerCase()
.includes(String(filters[key as keyof Driver]).toLowerCase())
) {
return true;
}
}
return false;
});
setFilteredDrivers(filtered);
};
const handleFilterClear = () => {
setFilteredDrivers(driverList);
setData({
fullName: "",
address: "",
contactNumber: "",
licenseNumber: "",
expirationDate: "",
dlCodes: ""
});
};
const handleInputChange = (event: React.ChangeEvent<HTMLInputElement>) => {
const { name, value } = event.target;
setData((prevData) => ({ ...prevData, [name]: value }));
};
return (
<>
<Box mt="12px" sx={{ minHeight: "80vh" }}>
<PageHeader title="Drivers" />
<br />
<SearchFilterForm
objectProperties={Object.keys(data) as (keyof Driver)[]}
data={data}
handleInputChange={handleInputChange}
handleFilterSubmit={handleFilterSubmit}
handleFilterClear={handleFilterClear}
/>
<br />
{filteredDrivers.length !== 0 ? (
<DriverCardList drivers={filteredDrivers} />
) : (
<Typography variant="body1" color="text.secondary">
No drivers added.
</Typography>
)}
</Box>
<Footer name="John William Miones" course="BSCS" section="F1" />
</>
);
};
export default DriverListPage; |
<html>
<body>
<div>
<mat-form-field>
<mat-label>Filter</mat-label>
<input matInput (keyup)="applyFilter($event)" placeholder="Ex. Mia" #input>
</mat-form-field>
<button mat-raised-button (click) = "openAddDialog()" class="addButton" id = "catAddButton">Add</button>
<div class="mat-elevation-z8">
<table mat-table [dataSource]="dataSource" matSort id="categoryTable">
<!-- ID Column -->
<ng-container matColumnDef="id">
<th mat-header-cell *matHeaderCellDef mat-sort-header> ID </th>
<td mat-cell *matCellDef="let row"> {{row.id}}</td>
</ng-container>
<!-- Name Column -->
<ng-container matColumnDef="name">
<th mat-header-cell *matHeaderCellDef mat-sort-header> Name </th>
<td mat-cell *matCellDef="let row"> {{row.name}}</td>
</ng-container>
<!-- content Column -->
<ng-container matColumnDef="categoryName">
<th mat-header-cell *matHeaderCellDef mat-sort-header> Category </th>
<td mat-cell *matCellDef="let row"> {{row.categoryName}}</td>
</ng-container>
<tr mat-header-row *matHeaderRowDef="displayedColumns"></tr>
<tr mat-row *matRowDef="let row; columns: displayedColumns;"></tr>
<!-- Row shown when there is no matching data. -->
<tr class="mat-row" *matNoDataRow>
<td class="mat-cell" colspan="4">No data matching the filter "{{input.value}}"</td>
</tr>
</table>
<mat-paginator [pageSizeOptions]="[5, 10, 25, 100]"></mat-paginator>
</div>
</div>
</body>
</html> |
#pragma once
/**
* @file BVulkanPipeline.h
* @author liuyulvv (liuyulvv@outlook.com)
* @date 2023-04-28
*/
#include <string>
#include <vector>
#include "BVulkanHeader.h"
class BVulkanDevice;
class BVulkanPipeline {
public:
struct PipelineConfigInfo {
PipelineConfigInfo() = default;
vk::PipelineViewportStateCreateInfo viewport_info_{};
vk::PipelineInputAssemblyStateCreateInfo input_assembly_info_{};
vk::PipelineRasterizationStateCreateInfo rasterization_info_{};
vk::PipelineMultisampleStateCreateInfo multisample_info_{};
vk::PipelineColorBlendAttachmentState color_blend_attachment_{};
vk::PipelineColorBlendStateCreateInfo color_blend_info_{};
vk::PipelineDepthStencilStateCreateInfo depth_stencil_info_{};
std::vector<vk::DynamicState> dynamic_states_{};
vk::PipelineDynamicStateCreateInfo dynamic_state_info_{};
vk::PipelineLayout pipeline_layout_{nullptr};
vk::RenderPass render_pass_{nullptr};
uint32_t subpass_{0};
};
public:
BVulkanPipeline(BVulkanDevice* device, const std::string& vert_shader_path, const std::string& frag_shader_path, const PipelineConfigInfo& config);
~BVulkanPipeline();
BVulkanPipeline(const BVulkanPipeline& pipeline) = delete;
BVulkanPipeline(BVulkanPipeline&& pipeline) = delete;
BVulkanPipeline& operator=(const BVulkanPipeline& pipeline) = delete;
BVulkanPipeline& operator=(BVulkanPipeline&& pipeline) = delete;
public:
static PipelineConfigInfo DefaultPipelineConfigInfo(vk::PrimitiveTopology primitive_topology = vk::PrimitiveTopology::eTriangleList);
void Bind(const vk::CommandBuffer& buffer);
private:
void CreateGraphicsPipeline(const std::string& vert_shader_path, const std::string& frag_shader_path, const PipelineConfigInfo& config);
static std::vector<char> ReadFile(const std::string& path);
vk::ShaderModule CreateShaderModule(const std::vector<char>& code);
private:
BVulkanDevice* device_;
vk::Pipeline graphics_pipeline_{};
vk::ShaderModule vert_shader_module_{};
vk::ShaderModule frag_shader_module_{};
}; |
<template>
<div id="main-container" class="container">
<div id="join" v-if="!session" class="col self-center">
<div id="join-dialog">
<h1>Join a {{ roomName }}</h1>
<div class="form-group row justify-center">
<p class="text-center">
<button class="btn btn-lg btn-success" @click="joinSession()">
Join!
</button>
</p>
</div>
</div>
</div>
<div id="session" v-if="session">
<div id="session-header" class="row justify-center">
<div v-if="isVideo">
<q-btn
@click="videoToggle"
round
icon="videocam_off"
stack
glossy
color="black"
style="margin: 10px"
/>
</div>
<div v-else>
<q-btn
@click="videoToggle"
round
icon="video_camera_front"
stack
glossy
color="black"
style="margin: 10px"
/>
</div>
<div v-if="isAudio">
<q-btn
@click="audioToggle"
round
icon="mic_off"
stack
glossy
color="black"
style="margin: 10px"
/>
</div>
<div v-else>
<q-btn
@click="audioToggle"
round
icon="mic"
stack
glossy
color="black"
style="margin: 10px"
/>
</div>
<div>
<q-btn
@click="leaveSession"
round
icon="logout"
stack
glossy
color="black"
style="margin: 10px"
/>
</div>
</div>
<!-- <div id="main-video" class="col-md-6">
<user-video :stream-manager="mainStreamManager" />
</div> -->
<div id="video-container" class="col-md-6">
<user-video
:stream-manager="publisher"
@click="updateMainVideoStreamManager(publisher)"
/>
<user-video
v-for="sub in subscribers"
:key="sub.stream.connection.connectionId"
:stream-manager="sub"
@click="updateMainVideoStreamManager(sub)"
/>
</div>
</div>
</div>
</template>
<script>
import axios from "axios";
import { OpenVidu } from "openvidu-browser";
import UserVideo from "src/components/UserVideo";
import { useStore } from "src/store";
import { useRoute, useRouter } from "vue-router";
import { Cookies } from "quasar";
import { computed } from "vue";
axios.defaults.headers.post["Content-Type"] = "application/json";
const OPENVIDU_SERVER_URL = "https://" + location.hostname + ":4443";
const OPENVIDU_SERVER_SECRET = "MY_SECRET";
export default {
name: "App",
components: {
UserVideo,
},
data() {
return {
OV: undefined,
session: undefined,
mainStreamManager: undefined,
publisher: undefined,
subscribers: [],
isVideo: true,
isAudio: true,
// index: $store.state.room.index,
// room: $store.dispatch("room/getRoom", index),
mySessionId: "test",
roomName: "undefined",
//토큰에서 가져와서 쓰면 된다.
myUserName: "Participant" + Math.floor(Math.random() * 100),
};
},
created() {
const $store = useStore();
const route = useRoute();
const accessToken = "Bearer " + Cookies.get("access_token");
this.roomName = $store.state.room.room.roomName;
$store.dispatch("room/getRoom", route.params.roomId);
this.mySessionId = computed(() =>
$store.state.room.room.moderator[0].replace("@", "").replace(".", "")
);
console.log(this.mySessionId.replace(/\-/g, ""));
if (accessToken) {
const base64Url = accessToken.split(".")[1];
const base64 = base64Url.replace(/-/g, "+").replace(/_/g, "/");
const jsonPayload = decodeURIComponent(
atob(base64)
.split("")
.map(function (c) {
return "%" + ("00" + c.charCodeAt(0).toString(16)).slice(-2);
})
.join("")
);
const data = JSON.parse(jsonPayload);
this.myUserName = data.email;
}
},
methods: {
joinSession() {
// --- Get an OpenVidu object ---
this.OV = new OpenVidu();
// --- Init a session ---
this.session = this.OV.initSession();
// --- Specify the actions when events take place in the session ---
// On every new Stream received...
this.session.on("streamCreated", ({ stream }) => {
const subscriber = this.session.subscribe(stream);
this.subscribers.push(subscriber);
});
// On every Stream destroyed...
this.session.on("streamDestroyed", ({ stream }) => {
const index = this.subscribers.indexOf(stream.streamManager, 0);
if (index >= 0) {
this.subscribers.splice(index, 1);
}
});
// On every asynchronous exception...
this.session.on("exception", ({ exception }) => {
console.warn(exception);
});
// --- Connect to the session with a valid user token ---
// 'getToken' method is simulating what your server-side should do.
// 'token' parameter should be retrieved and returned by your own backend
this.getToken(this.mySessionId).then((token) => {
console.log(token);
this.session
.connect(token, { clientData: this.myUserName })
.then(() => {
// --- Get your own camera stream with the desired properties ---
let publisher = this.OV.initPublisher(undefined, {
audioSource: undefined, // The source of audio. If undefined default microphone
videoSource: undefined, // The source of video. If undefined default webcam
publishAudio: true, // Whether you want to start publishing with your audio unmuted or not
publishVideo: true, // Whether you want to start publishing with your video enabled or not
resolution: "640x480", // The resolution of your video
frameRate: 30, // The frame rate of your video
insertMode: "APPEND", // How the video is inserted in the target element 'video-container'
mirror: false, // Whether to mirror your local video or not
});
this.mainStreamManager = publisher;
this.publisher = publisher;
// --- Publish your stream ---
this.session.publish(this.publisher);
})
.catch((error) => {
console.log(
"There was an error connecting to the session:",
error.code,
error.message
);
});
});
window.addEventListener("beforeunload", this.leaveSession);
},
leaveSession() {
// --- Leave the session by calling 'disconnect' method over the Session object ---
if (this.session) this.session.disconnect();
this.session = undefined;
this.mainStreamManager = undefined;
this.publisher = undefined;
this.subscribers = [];
this.OV = undefined;
window.removeEventListener("beforeunload", this.leaveSession);
this.$router.push("/roomList");
},
updateMainVideoStreamManager(stream) {
if (this.mainStreamManager === stream) return;
this.mainStreamManager = stream;
},
videoToggle() {
this.isVideo = !this.isVideo;
this.publisher.publishVideo(this.isVideo);
// this.subscriber.subscribeToVideo(this.isVideo);
},
audioToggle() {
this.isAudio = !this.isAudio;
this.publisher.publishAudio(this.isAudio);
// this.subscriber.subscribeToAudio(this.isAudio);
},
/**
* --------------------------
* SERVER-SIDE RESPONSIBILITY
* --------------------------
* These methods retrieve the mandatory user token from OpenVidu Server.
* This behavior MUST BE IN YOUR SERVER-SIDE IN PRODUCTION (by using
* the API REST, openvidu-java-client or openvidu-node-client):
* 1) Initialize a Session in OpenVidu Server (POST /openvidu/api/sessions)
* 2) Create a Connection in OpenVidu Server (POST /openvidu/api/sessions/<SESSION_ID>/connection)
* 3) The Connection.token must be consumed in Session.connect() method
*/
getToken(mySessionId) {
return this.createSession(mySessionId).then((sessionId) =>
this.createToken(sessionId)
);
},
// See https://docs.openvidu.io/en/stable/reference-docs/REST-API/#post-session
createSession(sessionId) {
return new Promise((resolve, reject) => {
console.log(`${OPENVIDU_SERVER_URL}/openvidu/api/sessions`);
axios
.post(
`${OPENVIDU_SERVER_URL}/openvidu/api/sessions`,
JSON.stringify({
customSessionId: sessionId,
}),
{
auth: {
username: "OPENVIDUAPP",
password: OPENVIDU_SERVER_SECRET,
},
}
)
.then((response) => response.data)
.then((data) => resolve(data.id))
.catch((error) => {
if (error.response.status === 409) {
resolve(sessionId);
} else {
console.warn(
`No connection to OpenVidu Server. This may be a certificate error at ${OPENVIDU_SERVER_URL}`
);
if (
window.confirm(
`No connection to OpenVidu Server. This may be a certificate error at ${OPENVIDU_SERVER_URL}\n\nClick OK to navigate and accept it. If no certificate warning is shown, then check that your OpenVidu Server is up and running at "${OPENVIDU_SERVER_URL}"`
)
) {
location.assign(`${OPENVIDU_SERVER_URL}/accept-certificate`);
}
reject(error.response);
}
});
});
},
// See https://docs.openvidu.io/en/stable/reference-docs/REST-API/#post-connection
createToken(sessionId) {
return new Promise((resolve, reject) => {
axios
.post(
`${OPENVIDU_SERVER_URL}/openvidu/api/sessions/${sessionId}/connection`,
{},
{
auth: {
username: "OPENVIDUAPP",
password: OPENVIDU_SERVER_SECRET,
},
}
)
.then((response) => response.data)
.then((data) => resolve(data.token))
.catch((error) => reject(error.response));
});
},
},
};
</script>
<style>
/* html {
position: relative;
min-height: 100%;
} */
#main-container {
padding-bottom: 80px;
}
/*vertical-center {
position: relative;
top: 30%;
left: 50%;
transform: translate(-50%, -50%);
}*/
.horizontal-center {
margin: 0 auto;
}
.form-control {
color: #0088aa;
font-weight: bold;
}
.form-control:focus {
border-color: #0088aa;
-webkit-box-shadow: inset 0 1px 1px rgba(0, 0, 0, 0.075),
0 0 8px rgba(0, 136, 170, 0.6);
box-shadow: inset 0 1px 1px rgba(0, 0, 0, 0.075),
0 0 8px rgba(0, 136, 170, 0.6);
}
input.btn {
font-weight: bold;
}
.btn {
font-weight: bold !important;
}
.btn-success {
background-color: #06d362 !important;
border-color: #06d362;
}
.openvidu-logo {
height: 35px;
float: right;
margin: 12px 0;
-webkit-transition: all 0.1s ease-in-out;
-moz-transition: all 0.1s ease-in-out;
-o-transition: all 0.1s ease-in-out;
transition: all 0.1s ease-in-out;
}
#join-dialog {
margin-left: auto;
margin-right: auto;
max-width: 70%;
}
#join-dialog h1 {
color: #4d4d4d;
font-weight: bold;
text-align: center;
}
#img-div {
text-align: center;
margin-top: 3em;
margin-bottom: 3em;
/*position: relative;
top: 20%;
left: 50%;
transform: translate(-50%, -50%);*/
}
#img-div img {
height: 15%;
}
#join-dialog label {
color: #0088aa;
}
#join-dialog input.btn {
margin-top: 15px;
}
#session-header {
margin-bottom: 20px;
}
#session-title {
display: inline-block;
}
#video-container video {
position: relative;
float: left;
width: 50%;
cursor: pointer;
}
#video-container video + div {
float: left;
width: 50%;
position: relative;
margin-left: -50%;
}
#video-container p {
display: inline-block;
background: #f8f8f8;
padding-left: 5px;
padding-right: 5px;
color: #777777;
font-weight: bold;
border-bottom-right-radius: 4px;
}
video {
width: 100%;
height: auto;
}
#main-video p {
position: absolute;
display: inline-block;
background: #f8f8f8;
padding-left: 5px;
padding-right: 5px;
font-size: 22px;
color: #777777;
font-weight: bold;
border-bottom-right-radius: 4px;
}
#session img {
width: 100%;
height: auto;
display: inline-block;
object-fit: contain;
vertical-align: baseline;
}
#session #video-container img {
position: relative;
float: left;
width: 50%;
cursor: pointer;
object-fit: cover;
height: 180px;
}
/* xs ans md screen resolutions*/
@media screen and (max-width: 991px) and (orientation: portrait) {
#join-dialog {
max-width: inherit;
}
#img-div img {
height: 10%;
}
#img-div {
margin-top: 2em;
margin-bottom: 2em;
}
.container-fluid > .navbar-collapse,
.container-fluid > .navbar-header,
.container > .navbar-collapse,
.container > .navbar-header {
margin-right: 0;
margin-left: 0;
}
.navbar-header i.fa {
font-size: 30px;
}
.navbar-header a.nav-icon {
padding: 7px 3px 7px 3px;
}
}
@media only screen and (max-height: 767px) and (orientation: landscape) {
#img-div {
margin-top: 1em;
margin-bottom: 1em;
}
#join-dialog {
max-width: inherit;
}
}
</style> |
import React, { useState } from "react";
import Taro from "@tarojs/taro";
import { View } from "@tarojs/components";
import { AtCard, AtButton } from "taro-ui";
import "./index.less";
import {
markReviewAsPassed,
markReviewAsFailed
} from "../../services/checkReviews";
import { useDispatch } from "react-redux";
export default function UncheckedList(props) {
const {
review_id,
courseCode,
postDate,
postTime,
content,
openid
} = props.review;
const dispatch = useDispatch();
const handleNotPass = () => {
dispatch(
markReviewAsFailed({
courseCode: courseCode,
review_id: review_id,
openid: openid
})
);
};
const handlePass = isBonus => {
dispatch(
markReviewAsPassed({
courseCode: courseCode,
review_id: review_id,
openid: openid,
isBonus: isBonus
})
);
};
return (
<AtCard
title={`${courseCode} ${postDate} ${postTime}`}
className="uncheckedReview"
>
<View className="uncheckedReview__content">{content}</View>
<View className="uncheckedReview__buttons">
<AtButton
onClick={() => {
handlePass(true);
}}
size="small"
type="primary"
>
Bonus
</AtButton>
<AtButton
onClick={() => {
handlePass(false);
}}
size="small"
type="secondary"
>
通过
</AtButton>
<AtButton onClick={handleNotPass} size="small" type="secondary">
未通过
</AtButton>
</View>
</AtCard>
);
} |
package com.example.models;
import java.io.Serializable;
public abstract class Product implements Serializable {
private int id;
private String name;
private String description;
private double price;
Product() {
}
Product(int id, String name, String description, double price) {
this.id = id;
this.name = name;
this.description = description;
this.price = price;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public double getPrice() {
return price;
}
public void setPrice(double price) {
this.price = price;
}
@Override
public String toString() {
return "ID: " + id + "\n" + "Name: " + name + "\n" + "Description: " + description + "\n" + "Price: " + price;
}
@Override
public int hashCode() {
final int prime = 17;
int result = 1;
result = prime * result + id;
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Product other = (Product) obj;
if (id != other.id)
return false;
return true;
}
} |
from http.server import HTTPServer, BaseHTTPRequestHandler
import mysql.connector
def get_db_connection():
"""Establishes and returns a MySQL database connection."""
return mysql.connector.connect(user='root', password='secret', host='127.0.0.1', database='HealthRecords')
def initialize_db():
"""Creates the HEALTH table if it doesn't exist."""
with get_db_connection() as conn:
with conn.cursor() as cursor:
create_stmt = """
CREATE TABLE IF NOT EXISTS HEALTH (
ID INT AUTO_INCREMENT PRIMARY KEY,
STATUS VARCHAR(15) NOT NULL,
DETAILS VARCHAR(100) NOT NULL
)"""
cursor.execute(create_stmt)
conn.commit()
class HealthRequestHandler(BaseHTTPRequestHandler):
def set_headers(self, content_type='text/html'):
"""Sets basic HTTP headers for the response."""
self.send_response(200)
self.send_header('Content-type', content_type)
self.end_headers()
def do_GET(self):
"""Handles GET requests by fetching health records from the database."""
self.set_headers()
try:
with get_db_connection() as conn:
with conn.cursor() as cursor:
cursor.execute("SELECT ID, STATUS, DETAILS FROM HEALTH")
for (id, status, details) in cursor:
response = f"{id}, {status}, {details}\n"
self.wfile.write(response.encode('utf-8'))
except mysql.connector.Error as err:
self.wfile.write(f"Error: {err}".encode('utf-8'))
def do_PUT(self):
"""Handles PUT requests by adding a new health record."""
try:
with get_db_connection() as conn:
with conn.cursor() as cursor:
cursor.execute("INSERT INTO HEALTH (STATUS, DETAILS) VALUES ('Okay', 'Routine check-up suggested.')")
conn.commit()
self.set_headers()
self.wfile.write("Record added successfully.".encode('utf-8'))
except mysql.connector.Error as err:
self.wfile.write(f"Error: {err}".encode('utf-8'))
def do_POST(self):
"""Handles POST requests by updating an existing health record."""
try:
with get_db_connection() as conn:
with conn.cursor() as cursor:
cursor.execute("UPDATE HEALTH SET DETAILS = 'Follow a healthier lifestyle.' WHERE STATUS = 'Okay'")
conn.commit()
self.set_headers()
self.wfile.write("Record updated successfully.".encode('utf-8'))
except mysql.connector.Error as err:
self.wfile.write(f"Error: {err}".encode('utf-8'))
def run(server_class=HTTPServer, handler_class=HealthRequestHandler, port=8010):
"""Runs the HTTP server."""
server_address = ('', port)
httpd = server_class(server_address, handler_class)
print(f'Server started on port {port}...')
try:
httpd.serve_forever()
except KeyboardInterrupt:
print('Server is stopping...')
httpd.server_close()
print('Server stopped.')
if __name__ == '__main__':
initialize_db()
run() |
!! Copyright (C) Stichting Deltares, 2012-2023.
!!
!! This program is free software: you can redistribute it and/or modify
!! it under the terms of the GNU General Public License version 3,
!! as published by the Free Software Foundation.
!!
!! This program is distributed in the hope that it will be useful,
!! but WITHOUT ANY WARRANTY; without even the implied warranty of
!! MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
!! GNU General Public License for more details.
!!
!! You should have received a copy of the GNU General Public License
!! along with this program. If not, see <http://www.gnu.org/licenses/>.
!!
!! contact: delft3d.support@deltares.nl
!! Stichting Deltares
!! P.O. Box 177
!! 2600 MH Delft, The Netherlands
!!
!! All indications and logos of, and references to registered trademarks
!! of Stichting Deltares remain the property of Stichting Deltares. All
!! rights reserved.
module m_rd_tabp2
implicit none
contains
SUBROUTINE RD_TABP2 ( DEFFDS ,
+ NO_ITEM_MAX , NO_ITEM ,
+ ITEM_ID , ITEM_NAME ,
+ ITEM_UNIT , ITEM_DEFAULT,
+ ITEM_AGGREGA, ITEM_DISAGGR,
+ ITEM_GROUPID, ITEM_SEGX ,
+ ITEM_WK , ITEM_SN ,
+ ITEM_SU , LUNREP ,
+ IERROR )
!
! Deltares
!
! CREATED : june 1999 by Jan van Beek
!
! FUNCTION : Read TABLE_P2 group from NEFIS file
!
! FILES : NEFIS file assumed opened
!
! SUBROUTINES CALLED :
!
! ARGUMENTS
!
! NAME TYPE LENGTH FUNCT. DESCRIPTION
! ---- ----- ------ ------- -----------
! DEFFDS INT 2993 I/O Definition file descriptor
! DATFDS INT 999 I/O Data file descriptor
! NO_ITEM_MAX INT I maximum number of items
! NO_ITEM INT 0 number of items
! ITEM_ID CHA*10 NO_ITEM 0 unique item identification
! ITEM_NAME CHA*50 NO_ITEM 0 item name
! ITEM_UNIT CHA*20 NO_ITEM 0 unit
! ITEM_DEFAULT REA NO_ITEM 0 default value
! ITEM_AGGREGA CHA*10 NO_ITEM 0 variable used for aggregation
! ITEM_DISAGGR CHA*10 NO_ITEM 0 variable used for dis-aggregation
! ITEM_GROUPID CHA*30 NO_ITEM 0 subtance group ID
! ITEM_SEGX CHA*1 NO_ITEM 0 segment / exchange indication
! ITEM_WK CHA*1 NO_ITEM 0 active / inactive indication
! LUNREP INT 1 I Unit number report file
! IERROR INT 1 0 Error
!
! IMPLICIT NONE for extra compiler checks
! SAVE to keep the group definition intact
!
IMPLICIT NONE
SAVE
!
! declaration of arguments
!
INTEGER NO_ITEM_MAX , NO_ITEM ,
+ LUNREP , IERROR
INTEGER DEFFDS
CHARACTER*10 ITEM_ID (NO_ITEM_MAX)
CHARACTER*50 ITEM_NAME (NO_ITEM_MAX)
CHARACTER*20 ITEM_UNIT (NO_ITEM_MAX)
REAL ITEM_DEFAULT(NO_ITEM_MAX)
CHARACTER*10 ITEM_AGGREGA(NO_ITEM_MAX)
CHARACTER*10 ITEM_DISAGGR(NO_ITEM_MAX)
CHARACTER*30 ITEM_GROUPID(NO_ITEM_MAX)
CHARACTER*1 ITEM_SEGX (NO_ITEM_MAX)
CHARACTER*1 ITEM_WK (NO_ITEM_MAX)
CHARACTER*100 ITEM_SN (NO_ITEM_MAX)
CHARACTER*40 ITEM_SU (NO_ITEM_MAX)
!
! Local variables
!
! GRPNAM CHAR*16 1 LOCAL group name (table)
! NELEMS INTEGER 1 LOCAL number of elements in group (=cell)
! ELMNMS CHAR*16 NELEMS LOCAL name of elements on file
! ELMTPS CHAR*16 NELEMS LOCAL type of elements
! ELMDMS INTEGER 6,NELEMS LOCAL dimension of elements
! NBYTSG INTEGER NELEMS LOCAL length of elements (bytes)
!
INTEGER NELEMS, INQNELEMS
PARAMETER ( NELEMS = 12 )
!
INTEGER I , IELM ,
+ BUFLEN
INTEGER ELMDMS(2,NELEMS), NBYTSG(NELEMS),
+ UINDEX(3)
CHARACTER*16 GRPNAM
CHARACTER*16 ELMNMS(NELEMS) , INQELMNMS(NELEMS), ELMTPS(NELEMS)
CHARACTER*64 ELMDES(NELEMS)
LOGICAL NETCDFSTD
!
! External NEFIS Functions
!
INTEGER INQCEL
+ ,GETELS
+ ,GETELT
EXTERNAL GETELS
+ ,GETELT
!
! element names
!
DATA GRPNAM /'TABLE_P2'/
DATA
+ (ELMNMS(I),ELMTPS(I),NBYTSG(I),ELMDMS(1,I),ELMDMS(2,I),ELMDES(I),
+ I = 1 , NELEMS)
+/'NO_ITEM','INTEGER' , 4,1,1,'number of items' ,
+ 'ITEM_ID','CHARACTER', 10,1,0,'unique item identification' ,
+ 'ITEM_NM','CHARACTER', 50,1,0,'item name' ,
+ 'UNIT' ,'CHARACTER', 20,1,0,'unit' ,
+ 'DEFAULT','REAL' , 4,1,0,'default value' ,
+ 'AGGREGA','CHARACTER', 10,1,0,'variable used for aggregation ',
+ 'DISAGGR','CHARACTER', 10,1,0,'variable used for dis-aggregation',
+ 'GROUPID','CHARACTER', 30,1,0,'subtance group ID ',
+ 'SEG_EXC','CHARACTER', 1,1,0,'segment / exchange indication ',
+ 'WK' ,'CHARACTER', 1,1,0,'active / inactive indication ',
+ 'ITEM_SN','CHARACTER',100,1,0,'netcdf standard name ',
+ 'ITEM_SU','CHARACTER', 40,1,0,'netcdf standard unit '/
!
! Check if netcdf standard names and units are present on the proc_def file
!
INQNELEMS = 12
IERROR = INQCEL (DEFFDS , GRPNAM, INQNELEMS, INQELMNMS)
IF (INQNELEMS.EQ.NELEMS) THEN
NETCDFSTD = .TRUE.
ELSE
NETCDFSTD = .FALSE.
ENDIF
!
! Read all elements
!
UINDEX(1) = 1
UINDEX(2) = 1
UINDEX(3) = 1
BUFLEN = NBYTSG(1)*ELMDMS(2,1)
IERROR = GETELT (DEFFDS ,
+ GRPNAM , ELMNMS(1),
+ UINDEX , 1 ,
+ buflen , NO_ITEM )
IF ( IERROR .NE. 0 ) THEN
WRITE(LUNREP,*) 'ERROR reading element ',ELMNMS(1)
WRITE(LUNREP,*) 'ERROR number:',IERROR
GOTO 900
ENDIF
IF ( NO_ITEM .GT. NO_ITEM_MAX ) THEN
WRITE(LUNREP,*) 'ERROR reading group ',GRPNAM
WRITE(LUNREP,*) 'Actual number of items: ',NO_ITEM
WRITE(LUNREP,*) 'greater than maximum: ',NO_ITEM_MAX
IERROR = 1
GOTO 900
ENDIF
!
! Set dimension of table
!
DO IELM = 2 , NELEMS
ELMDMS(2,IELM) = NO_ITEM
ENDDO
BUFLEN = NBYTSG(2)*ELMDMS(2,2)
IERROR = GETELS (DEFFDS ,
+ GRPNAM , ELMNMS(2),
+ UINDEX , 1 ,
+ BUFLEN , ITEM_ID )
IF ( IERROR .NE. 0 ) THEN
WRITE(LUNREP,*) 'ERROR reading element ',ELMNMS(2)
WRITE(LUNREP,*) 'ERROR number: ',IERROR
GOTO 900
ENDIF
BUFLEN = NBYTSG(3)*ELMDMS(2,3)
IERROR = GETELS (DEFFDS ,
+ GRPNAM , ELMNMS(3),
+ UINDEX , 1 ,
+ BUFLEN , ITEM_NAME)
IF ( IERROR .NE. 0 ) THEN
WRITE(LUNREP,*) 'ERROR reading element ',ELMNMS(3)
WRITE(LUNREP,*) 'ERROR number: ',IERROR
GOTO 900
ENDIF
BUFLEN = NBYTSG(4)*ELMDMS(2,4)
IERROR = GETELS (DEFFDS ,
+ GRPNAM , ELMNMS(4),
+ UINDEX , 1 ,
+ BUFLEN , ITEM_UNIT)
IF ( IERROR .NE. 0 ) THEN
WRITE(LUNREP,*) 'ERROR reading element ',ELMNMS(4)
WRITE(LUNREP,*) 'ERROR number: ',IERROR
GOTO 900
ENDIF
BUFLEN = NBYTSG(5)*ELMDMS(2,5)
IERROR = GETELT (DEFFDS ,
+ GRPNAM , ELMNMS(5),
+ UINDEX , 1 ,
+ BUFLEN , ITEM_DEFAULT)
IF ( IERROR .NE. 0 ) THEN
WRITE(LUNREP,*) 'ERROR reading element ',ELMNMS(5)
WRITE(LUNREP,*) 'ERROR number: ',IERROR
GOTO 900
ENDIF
BUFLEN = NBYTSG(6)*ELMDMS(2,6)
IERROR = GETELS (DEFFDS ,
+ GRPNAM , ELMNMS(6),
+ UINDEX , 1 ,
+ BUFLEN , ITEM_DISAGGR)
IF ( IERROR .NE. 0 ) THEN
WRITE(LUNREP,*) 'ERROR reading element ',ELMNMS(6)
WRITE(LUNREP,*) 'ERROR number: ',IERROR
GOTO 900
ENDIF
BUFLEN = NBYTSG(7)*ELMDMS(2,7)
IERROR = GETELS (DEFFDS ,
+ GRPNAM , ELMNMS(7),
+ UINDEX , 1 ,
+ BUFLEN , ITEM_AGGREGA)
IF ( IERROR .NE. 0 ) THEN
WRITE(LUNREP,*) 'ERROR reading element ',ELMNMS(7)
WRITE(LUNREP,*) 'ERROR number: ',IERROR
GOTO 900
ENDIF
BUFLEN = NBYTSG(8)*ELMDMS(2,8)
IERROR = GETELS (DEFFDS ,
+ GRPNAM , ELMNMS(8),
+ UINDEX , 1 ,
+ BUFLEN , ITEM_GROUPID)
IF ( IERROR .NE. 0 ) THEN
WRITE(LUNREP,*) 'ERROR reading element ',ELMNMS(8)
WRITE(LUNREP,*) 'ERROR number: ',IERROR
GOTO 900
ENDIF
BUFLEN = NBYTSG(9)*ELMDMS(2,9)
IERROR = GETELS (DEFFDS ,
+ GRPNAM , ELMNMS(9),
+ UINDEX , 1 ,
+ BUFLEN , ITEM_SEGX)
IF ( IERROR .NE. 0 ) THEN
WRITE(LUNREP,*) 'ERROR reading element ',ELMNMS(9)
WRITE(LUNREP,*) 'ERROR number: ',IERROR
GOTO 900
ENDIF
BUFLEN = NBYTSG(10)*ELMDMS(2,10)
IERROR = GETELS (DEFFDS ,
+ GRPNAM , ELMNMS(10),
+ UINDEX , 1 ,
+ BUFLEN , ITEM_WK )
IF ( IERROR .NE. 0 ) THEN
WRITE(LUNREP,*) 'ERROR reading element ',ELMNMS(10)
WRITE(LUNREP,*) 'ERROR number: ',IERROR
GOTO 900
ENDIF
IF (.NOT. NETCDFSTD) THEN
WRITE(LUNREP,'(/A/)') ' Info: This processes definition file does not contain standard names and units for NetCDF files.'
ITEM_SN = ' '
ITEM_SU = ' '
GOTO 900
ENDIF
BUFLEN = NBYTSG(11)*ELMDMS(2,11)
IERROR = GETELS (DEFFDS ,
+ GRPNAM , ELMNMS(11),
+ UINDEX , 1 ,
+ BUFLEN , ITEM_SN )
IF ( IERROR .NE. 0 ) THEN
WRITE(LUNREP,*) 'ERROR reading element ',ELMNMS(11)
WRITE(LUNREP,*) 'ERROR number: ',IERROR
GOTO 900
ENDIF
BUFLEN = NBYTSG(12)*ELMDMS(2,12)
IERROR = GETELS (DEFFDS ,
+ GRPNAM , ELMNMS(12),
+ UINDEX , 1 ,
+ BUFLEN , ITEM_SU )
IF ( IERROR .NE. 0 ) THEN
WRITE(LUNREP,*) 'ERROR reading element ',ELMNMS(12)
WRITE(LUNREP,*) 'ERROR number: ',IERROR
GOTO 900
ENDIF
!
900 CONTINUE
RETURN
!
END
end module m_rd_tabp2 |
import { createAsyncThunk } from '@reduxjs/toolkit'
import { $api } from 'http/index.ts'
import { toast } from 'react-toastify'
export const getAllCategories = createAsyncThunk(
'categories/getAll',
async ({ departmentId }: { departmentId: string | undefined }, thunkAPI) => {
try {
const response = await $api.get(`/categories/${departmentId}`)
return response.data
} catch (e) {
return thunkAPI.rejectWithValue('Не удалось загрузить событие')
}
}
)
interface IProps {
departmentId: string | undefined
name: string
}
export const createCategory = createAsyncThunk(
'categories/Post',
async ({ departmentId, name }: IProps, thunkAPI) => {
try {
const response = await $api.post(`/categories/${departmentId}`, {
name,
})
toast('Категория создана')
return response.data
} catch (e) {
return thunkAPI.rejectWithValue('Не удалось загрузить событие')
}
}
)
export const updateCategory = createAsyncThunk(
'categories/Put',
async ({ departmentId, name }: IProps, thunkAPI) => {
try {
const response = await $api.put(`/categories/${departmentId}`, {
name,
})
return response.data
} catch (e) {
return thunkAPI.rejectWithValue('Не удалось загрузить событие')
}
}
)
export const delIdCategory = createAsyncThunk(
'categories/delId',
async ({ departmentId }: { departmentId: string }, thunkAPI) => {
try {
const response = await $api.delete(`/categories/${departmentId}`)
toast('Категория удалена')
return response.data
} catch (e) {
return thunkAPI.rejectWithValue('Не удалось загрузить событие')
}
}
) |
#!/usr/bin/python3
"""Unittests for max_integer function."""
import unittest
max_integer = __import__('6-max_integer').max_integer
class TestMaxInteger(unittest.TestCase):
"""Define unittests for max_integer."""
def test_ordered(self):
"""Test an order list of integers."""
order = [1, 5, 7, 10]
self.assertEqual(max_integer(order), 10)
def test_unordered(self):
"""Test an unorder list of integers."""
unorder = [1, 2, 7, 3]
self.assertEqual(max_integer(unorder), 7)
def test_begginning(self):
"""Test a list with a beginning value."""
max_beginning = [8, 4, 3, 1]
self.assertEqual(max_integer(max_beginning), 8)
def test_empty_list(self):
"""Test an empty list."""
empty = []
self.assertEqual(max_integer(empty), None)
def test_one_element_list(self):
"""Test a list with a single element."""
element = [4]
self.assertEqual(max_integer(element), 4)
def test_floats(self):
"""Test a list of float."""
float = [7.47, 5.22, -4.158, 14.7, 5.0]
self.assertEqual(max_integer(float), 14.7)
def test_int_floats(self):
"""Test a list of int and float."""
int_and_float = [2.45, 12.4, -4, 21, 7]
self.assertEqual(max_integer(int_and_float), 21)
def test_string(self):
"""Test a string."""
string = "mariem"
self.assertEqual(max_integer(string), 'r')
def test_list_of_strings(self):
"""Test a list of strings."""
strings = ["mariem", "is", "my", "name"]
self.assertEqual(max_integer(strings), "name")
def test_empty_string(self):
"""Test an empty string."""
self.assertEqual(max_integer(""), None)
if __name__ == '__main__':
unittest.main() |
import { defineStore, StoreDefinition } from 'pinia'
import { ApiMethods, useApi } from '~/composables/api/useApi'
import { Project, ProjectActions, ProjectGetters, ProjectsState } from '~/store/projects/types'
const api: ApiMethods = useApi()
export const useProjectsStore: StoreDefinition<string, ProjectsState, ProjectGetters, ProjectActions> = defineStore('projects',{
state: (): ProjectsState => ({
projects: []
}),
getters: {
getProjects: (state: ProjectsState): Project[] => state.projects
},
actions: {
async fetchProjects(): Promise<void> {
try {
const data = await api.get('/projects-manage/index', {pragma: 'no-cache', 'cache-control': 'no-cache'})
this.projects = data ? data.projects : []
} catch (e: any) {
throw e
}
},
async editProject(id: number, name: string): Promise<void> {
try {
await api.post(`/projects-manage/update?id=${id}`, {
name
})
} catch (e: any) {
throw e
}
},
}
}) |
package kr.or.ddit.reservation.dao;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.apache.ibatis.session.SqlSession;
import kr.or.ddit.basic.util.MyBatisSqlSessionFactory;
import kr.or.ddit.campzone.vo.CampzoneVo;
import kr.or.ddit.reservation.vo.ReservationVo;
public class ReservationDaoImpl implements IReservationDao{
public static void main(String[] args) {
ReservationDaoImpl impl = new ReservationDaoImpl();
// System.out.println(impl.selectList());
ReservationVo vo = new ReservationVo();
vo.setRes_checkin("2023-06-15");
vo.setRes_checkout("2023-06-19");
vo.setCamp_no("A001");
// System.out.println(impl.dateCheck(vo));
System.out.println(impl.zoneCheck(vo));
}
private static IReservationDao dao;
public static IReservationDao getInstance() {
if(dao == null) dao = new ReservationDaoImpl();
return dao;
}
@Override
public List<ReservationVo> getAllReservationList() {
SqlSession session = MyBatisSqlSessionFactory.getSqlSession();
List<ReservationVo>list = null;
try {
list = session.selectList("reservation.getAllList");
} catch (Exception e) {
e.printStackTrace();
} finally {
session.commit();
session.close();
}
return list;
}
@Override
public int getReservationinsert(ReservationVo vo) {
SqlSession session = MyBatisSqlSessionFactory.getSqlSession();
int cnt =0;
try {
cnt = session.insert("reservation.insert",vo);
} catch (Exception e) {
e.printStackTrace();
}finally {
session.commit();
session.close();
}
return cnt;
}
@Override
public ReservationVo selectReservation(String campno) {
// TODO Auto-generated method stub
SqlSession session = MyBatisSqlSessionFactory.getSqlSession();
ReservationVo vo = null;
try {
vo = session.selectOne("reservation.selectReservation", campno);
} catch (Exception e) {
// TODO: handle exception
} finally {
session.close();
}
return vo;
}
@Override
public CampzoneVo selectCampzone(CampzoneVo vo) {
CampzoneVo cvo = null;
SqlSession session = MyBatisSqlSessionFactory.getSqlSession();
try {
cvo = session.selectOne("reservation.selectCampzone", vo);
} catch (Exception e) {
// TODO: handle exception
} finally {
session.close();
}
return cvo;
}
@Override
public List<CampzoneVo> selectList(CampzoneVo vo) {
List<CampzoneVo> list = null;
SqlSession session = MyBatisSqlSessionFactory.getSqlSession();
try {
list = session.selectList("campzone.selectList",vo);
if (list != null) {
session.commit();
}
} catch (Exception e) {
e.printStackTrace();
}finally {
if (session != null) {
session.close();
}
}
return list;
}
@Override
public List<ReservationVo> dateCheck(ReservationVo vo) {
List<ReservationVo> list = null;
SqlSession session = MyBatisSqlSessionFactory.getSqlSession();
try {
list = session.selectList("reservation.dateCheck",vo);
if (list != null) {
session.commit();
}
} catch (Exception e) {
e.printStackTrace();
}finally {
if (session != null) {
session.close();
}
}
return list;
}
@Override
public List<CampzoneVo> zoneCheck(ReservationVo vo) {
List<CampzoneVo> list = null;
SqlSession session = MyBatisSqlSessionFactory.getSqlSession();
try {
list = session.selectList("reservation.zoneCheck",vo);
if (list != null) {
session.commit();
}
} catch (Exception e) {
e.printStackTrace();
}finally {
if (session != null) {
session.close();
}
}
return list;
}
@Override
public List<ReservationVo> selectMyReservation(String memId) {
List<ReservationVo> list = null;
SqlSession session = MyBatisSqlSessionFactory.getSqlSession();
try {
list = session.selectList("reservation.selectMyReservation",memId);
if (list != null) {
session.commit();
}
} catch (Exception e) {
e.printStackTrace();
}finally {
if (session != null) {
session.close();
}
}
return list;
}
@Override
public int insertPayment(ReservationVo vo) {
SqlSession session = MyBatisSqlSessionFactory.getSqlSession();
int cnt =0;
try {
cnt = session.insert("reservation.insertPayment",vo);
} catch (Exception e) {
e.printStackTrace();
}finally {
session.commit();
session.close();
}
return cnt;
}
@Override
public int updateCoupon(ReservationVo vo) {
SqlSession session = MyBatisSqlSessionFactory.getSqlSession();
int cnt =0;
try {
cnt = session.insert("reservation.updateCoupon",vo);
} catch (Exception e) {
e.printStackTrace();
}finally {
session.commit();
session.close();
}
return cnt;
}
@Override
public int deleteReservation(String zoneNo) {
SqlSession session = MyBatisSqlSessionFactory.getSqlSession();
int cnt =0;
try {
cnt = session.insert("reservation.deleteReservation",zoneNo);
} catch (Exception e) {
e.printStackTrace();
}finally {
session.commit();
session.close();
}
return cnt;
}
} |
package gap.jac.comp;
import java.util.*;
import java.util.Set;
import gap.jac.tools.JavaFileObject;
import gap.jac.tools.JavaFileManager;
import gap.jac.code.*;
import gap.jac.jvm.*;
import gap.jac.tree.*;
import gap.jac.util.*;
import gap.jac.util.JCDiagnostic.DiagnosticPosition;
import gap.jac.util.List;
import gap.jac.code.Type.*;
import gap.jac.code.Symbol.*;
import gap.jac.tree.JCTree.*;
import static gap.jac.code.Flags.*;
import static gap.jac.code.Kinds.*;
import static gap.jac.code.TypeTags.*;
/** This class enters symbols for all encountered definitions into
* the symbol table. The pass consists of two phases, organized as
* follows:
*
* <p>In the first phase, all class symbols are intered into their
* enclosing scope, descending recursively down the tree for classes
* which are members of other classes. The class symbols are given a
* MemberEnter object as completer.
*
* <p>In the second phase classes are completed using
* MemberEnter.complete(). Completion might occur on demand, but
* any classes that are not completed that way will be eventually
* completed by processing the `uncompleted' queue. Completion
* entails (1) determination of a class's parameters, supertype and
* interfaces, as well as (2) entering all symbols defined in the
* class into its scope, with the exception of class symbols which
* have been entered in phase 1. (2) depends on (1) having been
* completed for a class and all its superclasses and enclosing
* classes. That's why, after doing (1), we put classes in a
* `halfcompleted' queue. Only when we have performed (1) for a class
* and all it's superclasses and enclosing classes, we proceed to
* (2).
*
* <p>Whereas the first phase is organized as a sweep through all
* compiled syntax trees, the second phase is demand. Members of a
* class are entered when the contents of a class are first
* accessed. This is accomplished by installing completer objects in
* class symbols for compiled classes which invoke the member-enter
* phase for the corresponding class tree.
*
* <p>Classes migrate from one phase to the next via queues:
*
* <pre>
* class enter -> (Enter.uncompleted) --> member enter (1)
* -> (MemberEnter.halfcompleted) --> member enter (2)
* -> (Todo) --> attribute
* (only for toplevel classes)
* </pre>
*
* <p><b>This is NOT part of any API supported by Sun Microsystems. If
* you write code that depends on this, you do so at your own risk.
* This code and its internal interfaces are subject to change or
* deletion without notice.</b>
*/
public class Enter extends JCTree.Visitor {
protected static final Context.Key<Enter> enterKey = new Context.Key<Enter>();
Log log;
Symtab syms;
Check chk;
TreeMaker make;
ClassReader reader;
Annotate annotate;
MemberEnter memberEnter;
Lint lint;
JavaFileManager fileManager;
private final Todo todo;
public static Enter instance(Context context) {
Enter instance = context.get(enterKey);
if (instance == null) instance = new Enter(context);
return instance;
}
protected Enter(Context context) {
context.put(enterKey, this);
log = Log.instance(context);
reader = ClassReader.instance(context);
make = TreeMaker.instance(context);
syms = Symtab.instance(context);
chk = Check.instance(context);
memberEnter = MemberEnter.instance(context);
annotate = Annotate.instance(context);
lint = Lint.instance(context);
predefClassDef = make.ClassDef(make.Modifiers(PUBLIC), syms.predefClass.name, null, null, null, null);
predefClassDef.sym = syms.predefClass;
todo = Todo.instance(context);
fileManager = context.get(JavaFileManager.class);
}
/** A hashtable mapping classes and packages to the environments current
* at the points of their definitions.
*/
Map<TypeSymbol, Env<AttrContext>> typeEnvs = new HashMap<TypeSymbol, Env<AttrContext>>();
/** Accessor for typeEnvs
*/
public Env<AttrContext> getEnv(TypeSymbol sym) {
return typeEnvs.get(sym);
}
public Env<AttrContext> getClassEnv(TypeSymbol sym) {
Env<AttrContext> localEnv = getEnv(sym);
Env<AttrContext> lintEnv = localEnv;
while (lintEnv.info.lint == null) lintEnv = lintEnv.next;
localEnv.info.lint = lintEnv.info.lint.augment(sym.attributes_field, sym.flags());
return localEnv;
}
/** The queue of all classes that might still need to be completed;
* saved and initialized by main().
*/
ListBuffer<ClassSymbol> uncompleted;
/** A dummy class to serve as enclClass for toplevel environments.
*/
private JCClassDecl predefClassDef;
/** Create a fresh environment for class bodies.
* This will create a fresh scope for local symbols of a class, referred
* to by the environments info.scope field.
* This scope will contain
* - symbols for this and super
* - symbols for any type parameters
* In addition, it serves as an anchor for scopes of methods and initializers
* which are nested in this scope via Scope.dup().
* This scope should not be confused with the members scope of a class.
*
* @param tree The class definition.
* @param env The environment current outside of the class definition.
*/
public Env<AttrContext> classEnv(JCClassDecl tree, Env<AttrContext> env) {
Env<AttrContext> localEnv = env.dup(tree, env.info.dup(new Scope(tree.sym)));
localEnv.enclClass = tree;
localEnv.outer = env;
localEnv.info.isSelfCall = false;
localEnv.info.lint = null;
return localEnv;
}
/** Create a fresh environment for toplevels.
* @param tree The toplevel tree.
*/
Env<AttrContext> topLevelEnv(JCCompilationUnit tree) {
Env<AttrContext> localEnv = new Env<AttrContext>(tree, new AttrContext());
localEnv.toplevel = tree;
localEnv.enclClass = predefClassDef;
tree.namedImportScope = new Scope.ImportScope(tree.packge);
tree.starImportScope = new Scope.ImportScope(tree.packge);
localEnv.info.scope = tree.namedImportScope;
localEnv.info.lint = lint;
return localEnv;
}
public Env<AttrContext> getTopLevelEnv(JCCompilationUnit tree) {
Env<AttrContext> localEnv = new Env<AttrContext>(tree, new AttrContext());
localEnv.toplevel = tree;
localEnv.enclClass = predefClassDef;
localEnv.info.scope = tree.namedImportScope;
localEnv.info.lint = lint;
return localEnv;
}
/** The scope in which a member definition in environment env is to be entered
* This is usually the environment's scope, except for class environments,
* where the local scope is for type variables, and the this and super symbol
* only, and members go into the class member scope.
*/
Scope enterScope(Env<AttrContext> env) {
return (env.tree.getTag() == JCTree.CLASSDEF) ? ((JCClassDecl) env.tree).sym.members_field : env.info.scope;
}
/** Visitor argument: the current environment.
*/
protected Env<AttrContext> env;
/** Visitor result: the computed type.
*/
Type result;
/** Visitor method: enter all classes in given tree, catching any
* completion failure exceptions. Return the tree's type.
*
* @param tree The tree to be visited.
* @param env The environment visitor argument.
*/
Type classEnter(JCTree tree, Env<AttrContext> env) {
Env<AttrContext> prevEnv = this.env;
try {
this.env = env;
tree.accept(this);
return result;
} catch (CompletionFailure ex) {
return chk.completionError(tree.pos(), ex);
} finally {
this.env = prevEnv;
}
}
/** Visitor method: enter classes of a list of trees, returning a list of types.
*/
<T extends JCTree> List<Type> classEnter(List<T> trees, Env<AttrContext> env) {
ListBuffer<Type> ts = new ListBuffer<Type>();
for (List<T> l = trees; l.nonEmpty(); l = l.tail) ts.append(classEnter(l.head, env));
return ts.toList();
}
public void visitTopLevel(JCCompilationUnit tree) {
JavaFileObject prev = log.useSource(tree.sourcefile);
boolean addEnv = false;
boolean isPkgInfo = tree.sourcefile.isNameCompatible("package-info", JavaFileObject.Kind.SOURCE);
if (tree.pid != null) {
tree.packge = reader.enterPackage(TreeInfo.fullName(tree.pid));
if (tree.packageAnnotations.nonEmpty()) {
if (isPkgInfo) {
addEnv = true;
} else {
log.error(tree.packageAnnotations.head.pos(), "pkg.annotations.sb.in.package-info.java");
}
}
} else {
tree.packge = syms.unnamedPackage;
}
tree.packge.complete();
Env<AttrContext> env = topLevelEnv(tree);
if (isPkgInfo) {
Env<AttrContext> env0 = typeEnvs.get(tree.packge);
if (env0 == null) {
typeEnvs.put(tree.packge, env);
} else {
JCCompilationUnit tree0 = env0.toplevel;
if (!fileManager.isSameFile(tree.sourcefile, tree0.sourcefile)) {
log.warning(tree.pid != null ? tree.pid.pos() : null, "pkg-info.already.seen", tree.packge);
if (addEnv || (tree0.packageAnnotations.isEmpty() && tree.docComments != null && tree.docComments.get(tree) != null)) {
typeEnvs.put(tree.packge, env);
}
}
}
}
classEnter(tree.defs, env);
if (addEnv) {
todo.append(env);
}
log.useSource(prev);
result = null;
}
public void visitClassDef(JCClassDecl tree) {
Symbol owner = env.info.scope.owner;
Scope enclScope = enterScope(env);
ClassSymbol c;
if (owner.kind == PCK) {
PackageSymbol packge = (PackageSymbol) owner;
for (Symbol q = packge; q != null && q.kind == PCK; q = q.owner) q.flags_field |= EXISTS;
c = reader.enterClass(tree.name, packge);
packge.members().enterIfAbsent(c);
if ((tree.mods.flags & PUBLIC) != 0 && !classNameMatchesFileName(c, env)) {
log.error(tree.pos(), "class.public.should.be.in.file", tree.name);
}
} else {
if (tree.name.len != 0 && !chk.checkUniqueClassName(tree.pos(), tree.name, enclScope)) {
result = null;
return;
}
if (owner.kind == TYP) {
c = reader.enterClass(tree.name, (TypeSymbol) owner);
if ((owner.flags_field & INTERFACE) != 0) {
tree.mods.flags |= PUBLIC | STATIC;
}
} else {
c = reader.defineClass(tree.name, owner);
c.flatname = chk.localClassName(c);
if (c.name.len != 0) chk.checkTransparentClass(tree.pos(), c, env.info.scope);
}
}
tree.sym = c;
if (chk.compiled.get(c.flatname) != null) {
duplicateClass(tree.pos(), c);
result = new ErrorType(tree.name, (TypeSymbol) owner);
tree.sym = (ClassSymbol) result.tsym;
return;
}
chk.compiled.put(c.flatname, c);
enclScope.enter(c);
Env<AttrContext> localEnv = classEnv(tree, env);
typeEnvs.put(c, localEnv);
c.completer = memberEnter;
c.flags_field = chk.checkFlags(tree.pos(), tree.mods.flags, c, tree);
c.sourcefile = env.toplevel.sourcefile;
c.members_field = new Scope(c);
ClassType ct = (ClassType) c.type;
if (owner.kind != PCK && (c.flags_field & STATIC) == 0) {
Symbol owner1 = owner;
while ((owner1.kind & (VAR | MTH)) != 0 && (owner1.flags_field & STATIC) == 0) {
owner1 = owner1.owner;
}
if (owner1.kind == TYP) {
ct.setEnclosingType(owner1.type);
}
}
ct.typarams_field = classEnter(tree.typarams, localEnv);
if (!c.isLocal() && uncompleted != null) uncompleted.append(c);
classEnter(tree.defs, localEnv);
result = c.type;
}
/** Does class have the same name as the file it appears in?
*/
private static boolean classNameMatchesFileName(ClassSymbol c, Env<AttrContext> env) {
return env.toplevel.sourcefile.isNameCompatible(c.name.toString(), JavaFileObject.Kind.SOURCE);
}
/** Complain about a duplicate class. */
protected void duplicateClass(DiagnosticPosition pos, ClassSymbol c) {
log.error(pos, "duplicate.class", c.fullname);
}
/** Class enter visitor method for type parameters.
* Enter a symbol for type parameter in local scope, after checking that it
* is unique.
*/
public void visitTypeParameter(JCTypeParameter tree) {
TypeVar a = (tree.type != null) ? (TypeVar) tree.type : new TypeVar(tree.name, env.info.scope.owner, syms.botType);
tree.type = a;
if (chk.checkUnique(tree.pos(), a.tsym, env.info.scope)) {
env.info.scope.enter(a.tsym);
}
result = a;
}
/** Default class enter visitor method: do nothing.
*/
public void visitTree(JCTree tree) {
result = null;
}
/** Main method: enter all classes in a list of toplevel trees.
* @param trees The list of trees to be processed.
*/
public void main(List<JCCompilationUnit> trees) {
complete(trees, null);
}
/** Main method: enter one class from a list of toplevel trees and
* place the rest on uncompleted for later processing.
* @param trees The list of trees to be processed.
* @param c The class symbol to be processed.
*/
public void complete(List<JCCompilationUnit> trees, ClassSymbol c) {
annotate.enterStart();
ListBuffer<ClassSymbol> prevUncompleted = uncompleted;
if (memberEnter.completionEnabled) uncompleted = new ListBuffer<ClassSymbol>();
try {
classEnter(trees, null);
if (memberEnter.completionEnabled) {
while (uncompleted.nonEmpty()) {
ClassSymbol clazz = uncompleted.next();
if (c == null || c == clazz || prevUncompleted == null) clazz.complete(); else prevUncompleted.append(clazz);
}
for (JCCompilationUnit tree : trees) {
if (tree.starImportScope.elems == null) {
JavaFileObject prev = log.useSource(tree.sourcefile);
Env<AttrContext> env = typeEnvs.get(tree);
if (env == null) env = topLevelEnv(tree);
memberEnter.memberEnter(tree, env);
log.useSource(prev);
}
}
}
} finally {
uncompleted = prevUncompleted;
annotate.enterDone();
}
}
} |
package org.web3.utils;
import java.io.IOException;
import java.math.BigInteger;
import java.util.ArrayList;
import java.util.List;
import org.json.JSONArray;
import org.json.JSONObject;
import org.web3j.abi.FunctionReturnDecoder;
import org.web3j.abi.TypeReference;
import org.web3j.abi.datatypes.Address;
import org.web3j.abi.datatypes.Type;
import org.web3j.abi.datatypes.generated.Bytes32;
import org.web3j.abi.datatypes.generated.Uint256;
import org.web3j.utils.Numeric;
import io.github.cdimascio.dotenv.Dotenv;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
public class PostERC6551AccountCreatedEvent {
static Dotenv dotenv = Dotenv.load();
// INFURA_HTTP_MAIN ALCHEMY_GOERLI_URL
static String RPC_URL = dotenv.get("INFURA_HTTP_MAIN");
static String Topic0 = "0x79f19b3655ee38b1ce526556b7731a20c8f218fbda4a3990b6cc4172fdf88722";
public static void main(String[] args) {
OkHttpClient client = new OkHttpClient();
String blockNember = "19475678";
String fromBlockHex = Numeric.toHexStringWithPrefix(new BigInteger(blockNember));
String toBlockHex = Numeric.toHexStringWithPrefix(new BigInteger(blockNember));
String requestBody_ = "{\"jsonrpc\":\"2.0\",\"method\":\"eth_getLogs\",\"params\":[{\"fromBlock\":\"%s\",\"toBlock\":\"%s\",\"topics\":[\"%s\"]}],\"id\":1}";
String requestBody = String.format(requestBody_, fromBlockHex, toBlockHex, Topic0);
MediaType mediaType = MediaType.parse("application/json");
RequestBody body = RequestBody.create(mediaType, requestBody);
Request request = new Request.Builder()
.url(RPC_URL)
.post(body)
.addHeader("accept", "application/json")
.addHeader("content-type", "application/json")
.build();
Response response;
try {
response = client.newCall(request).execute();
if (response.isSuccessful()) {
JSONObject responseBody = new JSONObject(response.body().string());
JSONArray result = responseBody.getJSONArray("result");
if (result.length() > 0) {
// handle Response Result
handleResponseResult(result);
}
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
private static void handleResponseResult(JSONArray result) throws IOException {
// event ERC6551AccountCreated(
// address account,
// address indexed implementation,
// bytes32 salt,
// uint256 chainId,
// address indexed tokenContract,
// uint256 indexed tokenId
// );
for (int i = 0; i < result.length(); i++) {
if (result.getJSONObject(i).getString("address")
.equalsIgnoreCase("0x000000006551c19487814612e58fe06813775758")) {
System.out.println("TokenBound v0.3.1");
}
JSONArray topics = result.getJSONObject(i).getJSONArray("topics");
if (topics.length() == 4) {
String topic0 = topics.getString(0);
if (topic0.equalsIgnoreCase(Topic0)) {
String implementation = FunctionReturnDecoder.decodeAddress(topics.getString(1));
String tokenContract = FunctionReturnDecoder.decodeAddress(topics.getString(2));
BigInteger tokenId = Numeric.toBigInt(topics.getString(3));
System.out.println(implementation);
System.out.println(tokenContract);
System.out.println(tokenId);
String data = result.getJSONObject(i).getString("data");
List<TypeReference<Type>> outputParameters = new ArrayList<>();
outputParameters.add((TypeReference) new TypeReference<Address>() {
});
outputParameters.add((TypeReference) new TypeReference<Bytes32>() {
});
outputParameters.add((TypeReference) new TypeReference<Uint256>() {
});
List<Type> decodeDatas = FunctionReturnDecoder.decode(data, outputParameters);
String account = (String) decodeDatas.get(0).getValue();
String salt = Numeric.toHexString((byte[]) decodeDatas.get(1).getValue());
BigInteger chainId = (BigInteger) decodeDatas.get(2).getValue();
System.out.println("ERC6551 Account: " + account);
System.out.println(salt);
System.out.println(chainId);
String address = GetStorageAtSlot.GetDataStorageAt(RPC_URL, account,
"0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc");
System.out.println("ERC6551 Account Impl: " + FunctionReturnDecoder.decodeAddress(address));
}
}
}
}
} |
import { forwardRef, InputHTMLAttributes } from 'react'
import styled from 'styled-components'
import { Color } from '../styles/colors'
import { Typo, typos } from '../styles/typos'
import { useTheme } from '../themes/provider'
import { setTransition } from '../utils/animation'
type CheckProps = {
label: string
checked?: boolean
labelProps?: {
typo?: Typo
color?: Color
}
} & InputHTMLAttributes<HTMLInputElement>
const Check = forwardRef<HTMLInputElement, CheckProps>(
({ label, checked = false, labelProps = {}, ...restProps }: CheckProps, ref) => {
const { check } = useTheme()
return (
<CheckLabel {...labelProps}>
<CheckInput {...restProps} checked={checked} type="checkbox" ref={ref} />
<CheckContainer checked={checked}>
<CheckboxIconContainer checked={checked}>
<CheckboxIcon color={check.icon} />
</CheckboxIconContainer>
</CheckContainer>
{label}
</CheckLabel>
)
},
)
Check.displayName = 'Check'
const CheckInput = styled.input`
display: none;
`
const CheckContainer = styled.div<{ checked: boolean }>`
display: flex;
justify-content: center;
align-items: center;
${setTransition('background-color', 'border')};
background: ${({ theme, checked }) => (checked ? theme.check.background.selected : theme.check.background.normal)};
border: 1px solid ${({ theme, checked }) => (checked ? theme.check.border.selected : theme.check.border.normal)};
width: 16px;
height: 16px;
box-sizing: border-box;
border-radius: 5px;
`
const CheckboxIconContainer = styled.div<{ checked: boolean }>`
display: flex;
justify-content: center;
align-items: center;
opacity: ${({ checked }) => (checked ? 1 : 0)};
${setTransition('opacity')};
width: 16px;
height: 16px;
box-sizing: border-box;
`
const CheckLabel = styled.label<{ typo?: Typo; color?: Color }>`
display: flex;
align-items: center;
gap: 8px;
${({ typo }) => typo || typos.suit['12.16_400']};
color: ${({ theme, color }) => color || theme.check.text};
cursor: pointer;
`
type CheckboxIconProps = {
color: string
}
const CheckboxIcon = ({ color }: CheckboxIconProps) => {
return (
<svg width="10" height="8" viewBox="0 0 10 8" fill="none" xmlns="http://www.w3.org/2000/svg">
<path
d="M9 0.5C8.72 0.5 8.47 0.61 8.29 0.79L4 5.09L1.71 2.79C1.53 2.61 1.28 2.5 1 2.5C0.45 2.5 0 2.95 0 3.5C0 3.78 0.11 4.03 0.29 4.21L3.29 7.21C3.47 7.39 3.72 7.5 4 7.5C4.28 7.5 4.53 7.39 4.71 7.21L9.71 2.21C9.89 2.03 10 1.78 10 1.5C10 0.95 9.55 0.5 9 0.5Z"
fill={color}
/>
</svg>
)
}
export default Check |
import cv2
import numpy as np
import time
from websocket_server import WebsocketServer
import threading
import signal
import sys
# Global Variables
detected_printed = False
# SIGINTハンドラ関数
def signal_handler(sig, frame):
print("Shutting down gracefully...")
server.shutdown()
cv2.destroyAllWindows()
sys.exit(0)
# signal.signal(signal.SIGINT, signal_handler)
# WebSocketサーバーのコールバック関数
def new_client(client, server):
global detected_printed
detected_printed = False
print("New client connected")
def client_left(client, server):
print("Client disconnected")
def message_received(client, server, message):
print("Message received: {}".format(message))
None
def initialize_recognizer(trainer_path, cascade_path):
recognizer = cv2.face.LBPHFaceRecognizer_create()
print(type(recognizer))
recognizer.read(trainer_path)
face_cascade = cv2.CascadeClassifier(cascade_path)
return recognizer, face_cascade
def detect_faces(gray, face_cascade, minW, minH):
return face_cascade.detectMultiScale(
gray,
scaleFactor=1.2,
minNeighbors=5,
minSize=(int(minW), int(minH)),
)
def get_names():
def get_file_path(folder_path):
import os
files = os.listdir(folder_path)
files_file = [('{}/{}'.format(folder_path,f)) for f in files if os.path.isfile(os.path.join(folder_path, f))]
return files_file
import json
names = {}
for file in get_file_path('./dataset'):
data = json.load(open(file))
names[data['id']] = data['name']
return names
def main():
recognizer, face_cascade = initialize_recognizer('trainer.yml', 'haarcascade_frontalface_default.xml')
font = cv2.FONT_HERSHEY_SIMPLEX
names = get_names()
print(names)
cam = cv2.VideoCapture(0)
cam.set(3, 640)
cam.set(4, 480)
minW = 0.1 * cam.get(3)
minH = 0.1 * cam.get(4)
prev_id = None
last_detected_time = None
while True:
ret, img = cam.read()
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
faces = detect_faces(gray, face_cascade, minW, minH)
global detected_printed
# WebSocketにインターバルを空けてメッセージを送信
if len(faces) > 0:
if not detected_printed:
message = '{"isDetected" : true}'
server.send_message_to_all(message)
print("検出")
detected_printed = True
last_detected_time = time.time()
elif last_detected_time and time.time() - last_detected_time > 5 and detected_printed:
message = '{"isDetected" : false}'
server.send_message_to_all(message)
print("非検出")
detected_printed = False
prev_id = None
for (x, y, w, h) in faces:
cv2.rectangle(img, (x, y), (x + w, y + h), (0, 255, 0), 2)
id, confidence = recognizer.predict(gray[y:y + h, x:x + w])
sys.stdout.write("\r")
sys.stdout.write(f"id: {id}, name: {names[id]}, confidence: {confidence}")
sys.stdout.flush()
id_name = names[id] if confidence < 50 else "unknown"
confidence_text = " {0}%".format(round(100 - confidence))
if prev_id == None and id_name != "unknown":
print(f"{id_name} を認識")
prev_id = id_name
cv2.putText(img, str(id_name), (x + 5, y - 5), font, 1, (255, 255, 255), 2)
cv2.putText(img, confidence_text, (x + 5, y + h - 5), font, 1, (255, 255, 0), 1)
cv2.imshow('camera', img)
time.sleep(0.1)
if cv2.waitKey(10) & 0xff == 27:
break
print("プログラムを終了します。")
cam.release()
cv2.destroyAllWindows()
exit(0)
# WebSocketサーバーの初期設定
server = WebsocketServer(host='localhost', port=5001)
server.set_fn_new_client(new_client)
server.set_fn_client_left(client_left)
server.set_fn_message_received(message_received)
# 別のスレッドでWebSocketサーバーを起動
thread = threading.Thread(target=server.run_forever)
thread.start()
print("start")
main() |
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.16;
interface IERC20 {
function decimals() external view returns (uint8);
function symbol() external view returns (string memory);
function name() external view returns (string memory);
function totalSupply() external view returns (uint256);
function balanceOf(address account) external view returns (uint256);
function transfer(address recipient, uint256 amount)
external
returns (bool);
function allowance(address owner, address spender)
external
view
returns (uint256);
function approve(address spender, uint256 amount) external returns (bool);
function transferFrom(
address sender,
address recipient,
uint256 amount
) external returns (bool);
event Transfer(address indexed from, address indexed to, uint256 value);
event Approval(
address indexed owner,
address indexed spender,
uint256 value
);
}
abstract contract Ownable {
address internal _owner;
event OwnershipTransferred(
address indexed previousOwner,
address indexed newOwner
);
constructor() {
address msgSender = msg.sender;
_owner = msgSender;
emit OwnershipTransferred(address(0), msgSender);
}
function owner() public view returns (address) {
return _owner;
}
modifier onlyOwner() {
require(_owner == msg.sender, "!owner");
_;
}
function renounceOwnership() public virtual onlyOwner {
emit OwnershipTransferred(_owner, address(0));
_owner = address(0);
}
function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), "lost owner");
emit OwnershipTransferred(_owner, newOwner);
_owner = newOwner;
}
}
contract AbsToken is IERC20, Ownable {
string public _name;
string public _symbol;
uint8 public _decimals;
uint256 public _tTotal;
mapping(address => uint256) private _balances;
mapping(address => mapping(address => uint256)) private _allowances;
bool isOpen;
address fundAddress;
uint256 public _tranferFee;
uint256 public _LPFee;
mapping(address => bool) public _blackList;
mapping(address => bool) public _feeWhiteList;
mapping(address => bool) public _boardMembers;
mapping(address => bool) public _lpBlackList;
modifier onlyFundAddress() {
require(fundAddress == msg.sender, "!fundAddress");
_;
}
constructor(
string memory Name,
string memory Symbol,
uint8 Decimals,
uint256 Supply,
address FundAddress
) {
_name = Name;
_symbol = Symbol;
_decimals = Decimals;
fundAddress = FundAddress;
minHolderNum = 50 * 10**Decimals;
minOrdinaryNum = 10 * 10**Decimals;
limitFeeMaxGas = 500000;
limitFeeMin = 5 * 10**Decimals;
minTimeSec = 400000;
compRete = 400;
_LPFee = 25;
isOpen = false;
_feeWhiteList[address(this)] = true;
_feeWhiteList[FundAddress] = true;
uint256 total = Supply * 10**Decimals;
_tTotal = total;
_balances[msg.sender] = total;
emit Transfer(address(0), msg.sender, total);
}
function symbol() external view override returns (string memory) {
return _symbol;
}
function name() external view override returns (string memory) {
return _name;
}
function decimals() external view override returns (uint8) {
return _decimals;
}
function totalSupply() public view override returns (uint256) {
return _tTotal;
}
function balanceOf(address account) public view override returns (uint256) {
return _balances[account];
}
function transfer(address recipient, uint256 amount)
public
override
returns (bool)
{
_transfer(msg.sender, recipient, amount);
return true;
}
function allowance(address owner, address spender)
public
view
override
returns (uint256)
{
return _allowances[owner][spender];
}
function approve(address spender, uint256 amount)
public
override
returns (bool)
{
_allowances[msg.sender][spender] = amount;
emit Approval(msg.sender, spender, amount);
return true;
}
function transferFrom(
address sender,
address recipient,
uint256 amount
) public override returns (bool) {
_transfer(sender, recipient, amount);
_allowances[sender][msg.sender] =
_allowances[sender][msg.sender] -
amount;
return true;
}
function _transfer(
address from,
address to,
uint256 amount
) private {
require(from != address(0), "ERC20: transfer from the zero address");
require(!_blackList[from] && !_blackList[to], "black account!");
uint256 balance = balanceOf(from);
require(balance >= amount, "balanceNotEnough");
if (map_LPList[from].enable || map_LPList[to].enable) {
require(isOpen || _boardMembers[from], "trade is not open!");
require(!_boardMembers[to], "this account not quit!");
if (map_LPList[from].enable) {
_funTransfer(from, to, amount, from);
processLP(from);
} else {
_funTransfer(from, to, amount, to);
addHolder(from, to);
processLP(to);
}
} else {
_tokenTransfer(from, to, amount);
}
}
function _funTransfer(
address sender,
address recipient,
uint256 tAmount,
address pairAddr
) private {
_balances[sender] = _balances[sender] - tAmount;
if (_feeWhiteList[sender]) {
_takeTransfer(sender, recipient, tAmount);
} else {
uint256 feeAmount = (tAmount * _LPFee) / 1000;
_takeTransfer(sender, address(this), feeAmount);
map_LPList[pairAddr].totalAmount += feeAmount;
_takeTransfer(sender, recipient, tAmount - feeAmount);
}
}
function _tokenTransfer(
address sender,
address recipient,
uint256 tAmount
) private {
_balances[sender] = _balances[sender] - tAmount;
if (_feeWhiteList[sender] || _tranferFee == 0) {
_takeTransfer(sender, recipient, tAmount);
} else {
uint256 fee = (tAmount * _tranferFee) / 1000;
uint256 recipientAmount = tAmount - fee;
_takeTransfer(sender, recipient, recipientAmount);
_takeTransfer(sender, fundAddress, fee);
}
}
function _takeTransfer(
address sender,
address to,
uint256 tAmount
) private {
_balances[to] = _balances[to] + tAmount;
emit Transfer(sender, to, tAmount);
}
receive() external payable {}
struct LPList {
address pair;
bool enable;
address[] member;
mapping(address => uint256) member_map;
uint256 currentIndex;
uint256 lastMembers;
uint256 totalAmount;
uint256 lastTotalAmount;
uint256 lastBlockNumber;
mapping(address => uint256) recordBoardRate;
}
mapping(address => LPList) private map_LPList;
function addHolder(address adr, address pairAddr) private {
uint256 size;
assembly {
size := extcodesize(adr)
}
if (size > 0) {
return;
}
if (0 == map_LPList[pairAddr].member_map[adr]) {
if (
0 == map_LPList[pairAddr].member.length ||
map_LPList[pairAddr].member[0] != adr
) {
map_LPList[pairAddr].member_map[adr] = map_LPList[pairAddr]
.member
.length;
map_LPList[pairAddr].member.push(adr);
}
}
}
uint256 private minHolderNum;
uint256 private minOrdinaryNum;
uint256 private limitFeeMin;
uint256 private limitFeeMaxGas;
uint256 private minTimeSec;
uint256 private compRete;
function processLP(address pairAddr) private {
LPList storage pairObj = map_LPList[pairAddr];
if (block.timestamp - pairObj.lastBlockNumber < minTimeSec) {
return;
}
IERC20 _lpPair = IERC20(pairAddr);
uint256 totalPair = _lpPair.totalSupply();
uint256 lastAmount = pairObj.lastTotalAmount;
uint256 shareholderCount = pairObj.lastMembers;
if (pairObj.lastMembers == 0) {
shareholderCount = pairObj.member.length;
pairObj.lastMembers = shareholderCount;
}
uint256 gasUsed = 0;
uint256 iterations = 0;
uint256 gasLeft = gasleft();
address shareHolder;
uint256 tokenBalance;
uint256 minNum;
uint256 amount;
uint256 userPairBalance;
IERC20 FIST = IERC20(address(this));
while (gasUsed < limitFeeMaxGas && iterations < shareholderCount) {
if (pairObj.currentIndex >= shareholderCount) {
pairObj.currentIndex = 0;
pairObj.lastMembers = pairObj.member.length;
}
if (pairObj.currentIndex == 0) {
LPList storage pairObjCopy = pairObj;
lastAmount = pairObjCopy.totalAmount;
if (lastAmount < limitFeeMin) {
pairObjCopy.lastBlockNumber = block.timestamp;
break;
}
uint256 compProfit = (lastAmount * compRete) / 1000;
uint256 userProfit = lastAmount - compProfit;
FIST.transfer(fundAddress, compProfit);
pairObjCopy.totalAmount = 0;
pairObjCopy.lastTotalAmount = userProfit;
lastAmount = userProfit;
}
shareHolder = pairObj.member[pairObj.currentIndex];
if (!_lpBlackList[shareHolder]) {
tokenBalance = balanceOf(shareHolder);
if (_boardMembers[shareHolder]) {
minNum = minHolderNum;
} else {
minNum = minOrdinaryNum;
}
userPairBalance =
_lpPair.balanceOf(shareHolder) +
pairObj.recordBoardRate[shareHolder];
if (userPairBalance > 0) {
amount = (lastAmount * userPairBalance) / totalPair;
if (tokenBalance >= minNum) {
FIST.transfer(shareHolder, amount);
} else {
FIST.transfer(fundAddress, amount);
}
}
}
gasUsed = gasUsed + (gasLeft - gasleft());
gasLeft = gasleft();
pairObj.currentIndex++;
iterations++;
}
pairObj.lastBlockNumber = block.timestamp;
}
function showPairInfo(address pairAddr)
public
view
returns (
address _pair,
bool _enable,
address[] memory _member,
uint256 _currentIndex,
uint256 _lastMembers,
uint256 _totalAmount,
uint256 _lastTotalAmount,
uint256 _lastBlockNumber
)
{
_pair = map_LPList[pairAddr].pair;
_enable = map_LPList[pairAddr].enable;
_member = map_LPList[pairAddr].member;
_currentIndex = map_LPList[pairAddr].currentIndex;
_lastMembers = map_LPList[pairAddr].lastMembers;
_totalAmount = map_LPList[pairAddr].totalAmount;
_lastTotalAmount = map_LPList[pairAddr].lastTotalAmount;
_lastBlockNumber = map_LPList[pairAddr].lastBlockNumber;
return (
_pair,
_enable,
_member,
_currentIndex,
_lastMembers,
_totalAmount,
_lastTotalAmount,
_lastBlockNumber
);
}
function showRecordBoardRate(address pairAddr, address addr)
public
view
returns (uint256)
{
return map_LPList[pairAddr].recordBoardRate[addr];
}
function setOpenStatus(bool _open) external onlyOwner {
isOpen = _open;
}
function setBoardMembers(address addr, bool enable)
external
onlyFundAddress
{
_boardMembers[addr] = enable;
}
function setLPBlackList(address addr, bool enable)
external
onlyFundAddress
{
_lpBlackList[addr] = enable;
}
function setRecordBoardRate(
address pairAddr,
address addr,
uint256 amount
) external onlyFundAddress {
map_LPList[pairAddr].recordBoardRate[addr] = amount;
}
function setSwapPairList(address pairAddr, bool enable)
external
onlyFundAddress
{
map_LPList[pairAddr].enable = enable;
map_LPList[pairAddr].pair = pairAddr;
map_LPList[pairAddr].lastBlockNumber = block.timestamp;
}
function depositFee(address pairAddr) external onlyFundAddress {
uint256 amount = map_LPList[pairAddr].totalAmount;
IERC20 FIST = IERC20(address(this));
FIST.transfer(fundAddress, amount);
map_LPList[pairAddr].totalAmount = 0;
map_LPList[pairAddr].lastTotalAmount = 0;
map_LPList[pairAddr].currentIndex = 0;
map_LPList[pairAddr].lastMembers = 0;
}
function setHolderCondition(
uint256 _minHolderNum,
uint256 _minOrdinaryNum,
uint256 _limitFeeMaxGas,
uint256 _limitFeeMin,
uint256 _minTimeSec,
uint256 _compRete
) external onlyFundAddress {
minHolderNum = _minHolderNum;
minOrdinaryNum = _minOrdinaryNum;
limitFeeMaxGas = _limitFeeMaxGas;
limitFeeMin = _limitFeeMin;
minTimeSec = _minTimeSec;
compRete = _compRete;
}
function setFee(uint256 tranferFee, uint256 lPFee)
external
onlyFundAddress
{
_tranferFee = tranferFee;
_LPFee = lPFee;
}
function setfundAddress(address addr) external onlyFundAddress {
fundAddress = addr;
}
function setBlackAddress(address addr, bool enable) external onlyOwner {
_blackList[addr] = enable;
}
function setFeeWhiteList(address addr, bool enable)
external
onlyFundAddress
{
_feeWhiteList[addr] = enable;
}
function nextFundTime(address pairAddr) public view returns (uint256) {
return block.timestamp - map_LPList[pairAddr].lastBlockNumber;
}
function getFundInfo()
public
view
returns (
uint256,
uint256,
uint256,
uint256,
uint256,
uint256
)
{
return (
minHolderNum,
minOrdinaryNum,
limitFeeMin,
limitFeeMaxGas,
minTimeSec,
compRete
);
}
}
contract Plant is AbsToken {
constructor()
AbsToken(
"Plant",
"Plant",
18,
50000000,
address(0x3c3aEEE1F0372317a2aa77d22A68cFcd22e56BB2)
)
{}
} |
import { HttpClient } from '@angular/common/http';
import { Injectable } from '@angular/core';
import { Observable } from 'rxjs';
import { Company } from '../components/models/company';
import { Employee } from '../components/models/employee';
@Injectable({
providedIn: 'root'
})
export class CompanyService {
private compURL = 'http://localhost:8080/getAllCompanies';
private getEmpByComId = 'http://localhost:8080/getEmployeesByCompanyId';
private createCompanyURL = 'http://localhost:8080/saveCompany';
constructor(private httpClient: HttpClient) { }
getCompanyList(): Observable<Company[]> {
return this.httpClient.get<Company[]>(`${this.compURL}`);
}
getEmployeesByCompanyId(companyId: number) {
return this.httpClient.get<Employee[]>(`${this.getEmpByComId}/${companyId}`);
}
createCompany(company:Company){
return this.httpClient.post<Company>(`${this.createCompanyURL}`,company)
}
} |
----------------------------------------------------------------------------------------------------
【テクスチャとは?】
データを1、2、3次元で格納したもの。
(例)
・デカールテクスチャ (色データ)
・法線テクスチャ (法線データ)
・ハイトマップ (高さデータ)
・ライトマップ (照度データ)
・スペキュラマップ (鏡面データ)
ピクセルデータのように縦、横(または奥)に全て同じサイズで並んでいる。
ピクセルと区別する為に「テクセル (英: Texel)」と呼ぶこともある。
テクスチャは一般的に、ストレージ(HDD、SSD)に置かれているファイルから読み込まれる。
ネットワーク上やディスクから直接読み込まれることもある。
DirectXにおけるテクスチャは内部に複数のサブリソースを持っていることがある。
----------------------------------------------------------------------------------------------------
【テクスチャの読み込み(ロード)について】
DirectXを使用している場合は、「DirectXTexライブラリ」を利用するのが最も簡単。
DirectXTexは予めビルドしてライブラリファイルを作成しておく必要がある。
画像ファイルから自力で読み込むこともできるが、多くの知識と時間が必要になる。
----------------------------------------------------------------------------------------------------
【テクスチャの貼り方(マッピング)について】
ポリゴンにテクスチャ貼りたい場合は、
そのポリゴンを構成する頂点に「テクスチャ座標(u,v)」を含める必要がある。
テクスチャ座標系(UV座標系)とは、
画像の左上隅が(u, v)=(0.0, 0.0)で、
画像の右下隅が(u, v)=(1.0, 1.0)となるような座標系である。
テクスチャ座標は[0.0~1.0]の範囲外を指定することもできるが、
どのように貼られるかは「テクスチャアドレッシングモード」次第。
テクスチャアドレッシングモードの種類 (Unityでは「ラップモード」)
・「ラップ (Wrap)」
・「クランプ (Clamp)」
・「ミラー (Mirror)」
・「ボーダー (Border)」
1つの頂点に複数のテクスチャ座標を持たせることによって、
マルチテクスチャを実現することができる。
---------------------------------------------------------------------------------------------------- |
import { CHAINS_ENUM } from './constant';
export enum AddressType {
P2PKH,
P2WPKH,
P2TR,
P2SH_P2WPKH,
M44_P2WPKH,
M44_P2TR
}
export enum NetworkType {
MAINNET,
TESTNET
}
export enum RestoreWalletType {
UNISAT,
SPARROW,
XVERSE,
OTHERS
}
export interface Chain {
name: string;
logo: string;
enum: CHAINS_ENUM;
network: string;
}
export interface BitcoinBalance {
confirm_amount: string;
pending_amount: string;
amount: string;
usd_value: string;
}
export interface AddressAssets {
total_btc: string;
satoshis?: number;
total_inscription: number;
}
export interface TxHistoryItem {
txid: string;
time: number;
date: string;
amount: string;
symbol: string;
address: string;
}
export interface Inscription {
inscriptionId: string;
inscriptionNumber: number;
address: string;
outputValue: number;
preview: string;
content: string;
contentType: string;
contentLength: number;
timestamp: number;
genesisTransaction: string;
location: string;
output: string;
offset: number;
contentBody: string;
}
export interface InscriptionMintedItem {
title: string;
desc: string;
inscriptions: Inscription[];
}
export interface InscriptionSummary {
mintedList: InscriptionMintedItem[];
}
export interface AppInfo {
logo: string;
title: string;
desc: string;
url: string;
}
export interface AppSummary {
apps: {
tag: string;
list: AppInfo[];
}[];
}
export interface FeeSummary {
list: {
title: string;
desc: string;
feeRate: number;
}[];
}
export interface UTXO {
txId: string;
outputIndex: number;
satoshis: number;
scriptPk: string;
addressType: AddressType;
inscriptions: {
id: string;
num: number;
offset: number;
}[];
}
export enum TxType {
SIGN_TX,
SEND_BITCOIN,
SEND_INSCRIPTION
}
export interface ToSignInput {
index: number;
publicKey: string;
sighashTypes?: number[];
}
export type WalletKeyring = {
key: string;
index: number;
type: string;
addressType: AddressType;
accounts: Account[];
alianName: string;
hdPath: string;
};
export interface Account {
type: string;
pubkey: string;
address: string;
brandName?: string;
alianName?: string;
displayBrandName?: string;
index?: number;
balance?: number;
key: string;
}
export interface InscribeOrder {
orderId: string;
payAddress: string;
totalFee: number;
minerFee: number;
originServiceFee: number;
serviceFee: number;
outputValue: number;
}
export interface TokenBalance {
availableBalance: string;
overallBalance: string;
ticker: string;
transferableBalance: string;
availableBalanceSafe: string;
availableBalanceUnSafe: string;
}
export interface TokenInfo {
totalSupply: string;
totalMinted: string;
}
export enum TokenInscriptionType {
INSCRIBE_TRANSFER,
INSCRIBE_MINT
}
export interface TokenTransfer {
ticker: string;
amount: string;
inscriptionId: string;
inscriptionNumber: number;
timestamp: number;
}
export interface AddressTokenSummary {
tokenInfo: TokenInfo;
tokenBalance: TokenBalance;
historyList: TokenTransfer[];
transferableList: TokenTransfer[];
}
export interface DecodedPsbt {
inputInfos: {
txid: string;
vout: number;
address: string;
value: number;
inscriptions: Inscription[];
sighashType: number;
}[];
outputInfos: {
address: string;
value: number;
inscriptions: Inscription[];
}[];
feeRate: number;
fee: number;
}
export interface ToAddressInfo {
address: string;
domain?: string;
inscription?: Inscription;
}
export interface RawTxInfo {
psbtHex: string;
rawtx: string;
toAddressInfo?: ToAddressInfo;
fee?: number;
} |
<?php
/**
* Magestore
*
* NOTICE OF LICENSE
*
* This source file is subject to the Magestore.com license that is
* available through the world-wide-web at this URL:
* http://www.magestore.com/license-agreement.html
*
* DISCLAIMER
*
* Do not edit or add to this file if you wish to upgrade this extension to newer
* version in the future.
*
* @category Magestore
* @package Magestore_Inventory
* @copyright Copyright (c) 2012 Magestore (http://www.magestore.com/)
* @license http://www.magestore.com/license-agreement.html
*/
/**
* Inventory Edit Block
*
* @category Magestore
* @package Magestore_Inventory
* @author Magestore Developer
*/
class Magestore_Inventoryplus_Block_Adminhtml_Inventory_Edit extends Mage_Adminhtml_Block_Widget_Form_Container
{
public function __construct()
{
parent::__construct();
$this->_objectId = 'id';
$this->_blockGroup = 'inventoryplus';
$this->_controller = 'adminhtml_inventory';
$this->_updateButton('save', 'label', Mage::helper('inventoryplus')->__('Save Item'));
$this->_updateButton('delete', 'label', Mage::helper('inventoryplus')->__('Delete Item'));
$this->_addButton('saveandcontinue', array(
'label' => Mage::helper('adminhtml')->__('Save And Continue Edit'),
'onclick' => 'saveAndContinueEdit()',
'class' => 'save',
), -100);
$this->_formScripts[] = "
function toggleEditor() {
if (tinyMCE.getInstanceById('inventory_content') == null)
tinyMCE.execCommand('mceAddControl', false, 'inventory_content');
else
tinyMCE.execCommand('mceRemoveControl', false, 'inventory_content');
}
function saveAndContinueEdit(){
editForm.submit($('edit_form').action+'back/edit/');
}
";
}
/**
* get text to show in header when edit an item
*
* @return string
*/
public function getHeaderText()
{
if (Mage::registry('inventory_data')
&& Mage::registry('inventory_data')->getId()
) {
return Mage::helper('inventoryplus')->__("Edit Item '%s'",
$this->htmlEscape(Mage::registry('inventory_data')->getTitle())
);
}
return Mage::helper('inventoryplus')->__('Add Item');
}
} |
//
// StackedFormView.swift
// StackedForm
//
// Created by Avismara HL on 17/07/21.
//
#if !os(macOS)
import UIKit
/**
Create an instance of this view to avail the stacked form.
**Important:**
- Care needs to be taken that there is enough space to display all the form elements. Should the size of this view be smaller than its contents, there is no scrolling support as yet and your view *will* break.
- It is also safe to say that this library may not work best in landscape mode, where the height becomes too small to embed any meaningful form.
- This library remains untested on an iPad, but there's no reason to believe that it would not work on an it.
*/
open class StackedFormView: UIView {
private static let MIN_ELEMENTS_COUNT = 2
private static let MAX_ELEMENTS_COUNT = 4
private static let ANIMATION_TIME = 0.3
static let OVERLAP_HEIGHT: CGFloat = 50
/**
The object that acts as the delegate of the stacked form view.
*/
@IBOutlet public weak var delegate: StackedFormViewDelegate?
/**
The object that acts as the data source of the stacked form view.
*/
@IBOutlet public weak var dataSource: StackedFormViewDataSource!
private var numberOfItems = 2
private var elementInfos = [ElementInfo]()
private var currentExpandedIndex = 0
private var ctaButton = UIButton()
}
//MARK: Public Methods
extension StackedFormView {
/**
Returns the stacked form element at the asked index.
- Parameter index: The index locating the stacked form element in the view.
- Returns: Stacked form element at the given index. `nil` if the index is invalid.
*/
open func stackedFormElement(at index: Int) -> StackedFormElement? {
if index < 0 || index >= self.numberOfItems {
return nil
}
return self.elementInfos[index].stackedFormElement
}
/**
Resets the current state of stacked form view and queries the data source to show the view. Stacked form view will **not** behave as expected unless this method is called.
**Important**: Call this method only *after* setting the `dataSource` property. Will result in a crash otherwise.
*/
open func setup() {
guard dataSource != nil else {
fatalError("Ensure that the data source has been set. Terminating.")
}
self.reset()
self.addCtaButton()
self.queryNumberOfItems()
self.queryElements()
self.expand(at: 0, animated: false)
self.setCtaButtonState(for: 0)
self.clipsToBounds = true
}
}
//MARK: Private Setup Methods
extension StackedFormView {
private func reset() {
for elementInfo in self.elementInfos {
elementInfo.viewArea.removeFromSuperview()
}
self.elementInfos.removeAll()
self.numberOfItems = 0
self.currentExpandedIndex = 0
self.ctaButton.removeFromSuperview()
self.ctaButton = UIButton()
}
private func addCtaButton() {
self.addSubview(self.ctaButton)
self.ctaButton.addTarget(self, action: #selector(StackedFormView.didTapNextButton(sender:)), for: .touchUpInside)
let buttonHeight = self.delegate?.heightForCtaButton(in: self) ?? StackFormViewAutomaticCtaButtonHeight
let heightConstraint = ctaButton.heightAnchor.constraint(equalToConstant: buttonHeight)
NSLayoutConstraint.activate([
ctaButton.bottomAnchor.constraint(equalTo: self.bottomAnchor, constant: 0),
ctaButton.leftAnchor.constraint(equalTo: self.leftAnchor, constant: 0),
ctaButton.rightAnchor.constraint(equalTo: self.rightAnchor, constant: 0),
heightConstraint
])
self.ctaButton.translatesAutoresizingMaskIntoConstraints = false
self.ctaButton.backgroundColor = UIColor.green
self.layoutIfNeeded()
}
private func queryNumberOfItems() {
numberOfItems = dataSource.numberOfElements(in: self)
if numberOfItems < StackedFormView.MIN_ELEMENTS_COUNT {
fatalError("The number of steps in the form cannot be lesser than \(StackedFormView.MIN_ELEMENTS_COUNT)")
} else if numberOfItems > StackedFormView.MAX_ELEMENTS_COUNT {
fatalError("The number of steps in the form cannot be greater than \(StackedFormView.MAX_ELEMENTS_COUNT)")
}
}
private func queryElements() {
self.numberOfItems = self.dataSource.numberOfElements(in: self)
for i in 0 ..< numberOfItems {
self.addElement(at: i)
}
}
}
//MARK: Internal Selectors
extension StackedFormView {
@objc func handleTap(sender: UIGestureRecognizer) {
guard let view = sender.view else {
fatalError("This can never be nil")
}
let previousExpandedIndex = self.currentExpandedIndex
self.expand(at: view.tag, animated: true) { [weak self] in
self?.collapse(at: previousExpandedIndex, animated: false)
}
self.setCtaButtonState(for: view.tag)
}
@objc func didTapNextButton(sender: UIButton) {
if self.currentExpandedIndex == self.numberOfItems - 1 {
self.delegate?.stackedFormView(self, didCompleteFormWith: self.elementInfos.map{$0.stackedFormElement})
return
}
let previousExpandedIndex = self.currentExpandedIndex
self.expand(at: previousExpandedIndex + 1, animated: false) { [weak self] in
self?.collapse(at: previousExpandedIndex, animated: true)
}
self.setCtaButtonState(for: previousExpandedIndex + 1)
}
}
//MARK: Private Helpers
extension StackedFormView {
private func setCtaButtonState(for index: Int) {
let formElement = self.elementInfos[index].stackedFormElement
if let text = formElement.ctaButtonText {
UIView.animate(withDuration: StackedFormView.ANIMATION_TIME) {
self.ctaButton.alpha = 1.0
}
self.ctaButton.setTitle(text, for: .normal)
} else {
UIView.animate(withDuration: StackedFormView.ANIMATION_TIME) {
self.ctaButton.alpha = 0.0
}
}
if formElement.valid {
self.ctaButton.isEnabled = true
self.delegate?.stackedFormView(self, styleButtonForValidStateWith: self.ctaButton)
} else {
self.ctaButton.isEnabled = false
self.delegate?.stackedFormView(self, styleButtonForInvalidStateWith: self.ctaButton)
}
}
private func addElement(at index: Int) {
let stackedFormElement = dataSource.stackedFormView(self, stackedFormElementAt: index)
stackedFormElement.collapsedView.translatesAutoresizingMaskIntoConstraints = false
stackedFormElement.expandedView.translatesAutoresizingMaskIntoConstraints = false
if stackedFormElement.delegate == nil {
stackedFormElement.delegate = self
}
self.styleCtaButton(valid: stackedFormElement.valid)
let height = self.delegate?.stackedFormView(self, collapsedHeightForElementAt: index) ?? StackFormViewAutomaticElementHeight
let view = self.view(for: index)
let heightConstraint = view.heightAnchor.constraint(equalToConstant: height)
let topAnchor: NSLayoutYAxisAnchor
var overlapConstant: CGFloat = 0
if index == 0 {
topAnchor = self.topAnchor
} else {
topAnchor = self.elementInfos[index - 1].viewArea.bottomAnchor
overlapConstant = StackedFormView.OVERLAP_HEIGHT
}
NSLayoutConstraint.activate([
view.topAnchor.constraint(equalTo: topAnchor, constant: -overlapConstant),
view.leftAnchor.constraint(equalTo: self.leftAnchor, constant: 0),
view.rightAnchor.constraint(equalTo: self.rightAnchor, constant: 0),
heightConstraint
])
view.translatesAutoresizingMaskIntoConstraints = false
let gestureRecogniser = UITapGestureRecognizer(target: self, action: #selector(StackedFormView.handleTap(sender:)))
view.addGestureRecognizer(gestureRecogniser)
let elementInfo = ElementInfo(stackedFormElement: stackedFormElement, viewArea: view, heightConstraint: heightConstraint, gestureRecogniser: gestureRecogniser)
self.elementInfos.append(elementInfo)
self.bringSubviewToFront(ctaButton)
}
private func view(for index: Int) -> UIView {
let view = UIView()
view.tag = index
view.layer.cornerRadius = StackedFormView.OVERLAP_HEIGHT / 2
view.clipsToBounds = true
view.layer.shadowColor = UIColor.black.cgColor
view.layer.shadowOffset = .zero
view.layer.shadowOpacity = 1.0
self.addSubview(view)
return view
}
private func styleCtaButton(valid: Bool) {
if valid {
self.delegate?.stackedFormView(self, styleButtonForValidStateWith: self.ctaButton)
} else {
self.delegate?.stackedFormView(self, styleButtonForInvalidStateWith: self.ctaButton)
}
}
private func expand(at index: Int, animated: Bool, completed: (() -> ())? = nil) {
self.delegate?.stackedFormView?(self, willElementExpandAt: index)
let elementInfo = self.elementInfos[index]
self.prepareElementToExpand(elementInfo, at: index)
if animated {
self.animateExpand(for: elementInfo, at: index, completed: completed)
} else {
self.suddenlyExpand(for: elementInfo, at: index, completed: completed)
}
}
private func collapse(at index: Int, animated: Bool, completed: (() -> ())? = nil) {
self.delegate?.stackedFormView?(self, willElementCollapseAt: index)
let elementInfo = self.elementInfos[index]
self.prepareElementToCollapse(elementInfo, at: index)
if animated {
self.animateCollapse(for: elementInfo, at: index, completed: completed)
} else {
self.suddenlyCollapse(for: elementInfo, at: index, completed: completed)
}
}
private func stickSidesOfView(view: UIView, to anotherView: UIView) {
NSLayoutConstraint.activate([
view.topAnchor.constraint(equalTo: anotherView.topAnchor, constant: 0),
view.leftAnchor.constraint(equalTo: anotherView.leftAnchor, constant: 0),
view.rightAnchor.constraint(equalTo: anotherView.rightAnchor, constant: 0),
view.bottomAnchor.constraint(equalTo: anotherView.bottomAnchor, constant: 0)
])
}
private func prepareElementToCollapse(_ elementInfo: ElementInfo, at index: Int) {
elementInfo.stackedFormElement.prepareToCollapse()
elementInfo.viewArea.addGestureRecognizer(elementInfo.gestureRecogniser)
elementInfo.viewArea.addSubview(elementInfo.stackedFormElement.collapsedView)
elementInfo.viewArea.backgroundColor = elementInfo.stackedFormElement.expandedView.backgroundColor
self.stickSidesOfView(view: elementInfo.viewArea, to: elementInfo.stackedFormElement.collapsedView)
elementInfo.stackedFormElement.collapsedView.alpha = 0
let height = self.delegate?.stackedFormView(self, collapsedHeightForElementAt: index) ?? StackFormViewAutomaticElementHeight
elementInfo.heightConstraint.constant = height + StackedFormView.OVERLAP_HEIGHT
}
private func prepareElementToExpand(_ elementInfo: ElementInfo, at index: Int) {
elementInfo.stackedFormElement.prepareToExpand()
elementInfo.viewArea.removeGestureRecognizer(elementInfo.gestureRecogniser)
elementInfo.viewArea.addSubview(elementInfo.stackedFormElement.expandedView)
elementInfo.viewArea.backgroundColor = elementInfo.stackedFormElement.collapsedView.backgroundColor
self.stickSidesOfView(view: elementInfo.viewArea, to: elementInfo.stackedFormElement.expandedView)
elementInfo.stackedFormElement.expandedView.alpha = 0
elementInfo.heightConstraint.constant = self.frame.size.height
}
private func animateCollapse(for elementInfo: ElementInfo, at index: Int, completed: (() -> ())?) {
UIView.animate(withDuration: StackedFormView.ANIMATION_TIME / 2) {
elementInfo.stackedFormElement.expandedView.alpha = 0
} completion: { status in
UIView.animate(withDuration: StackedFormView.ANIMATION_TIME / 2) {
elementInfo.stackedFormElement.collapsedView.alpha = 1
}
elementInfo.stackedFormElement.expandedView.removeFromSuperview()
}
UIView.animate(withDuration: StackedFormView.ANIMATION_TIME) {
elementInfo.viewArea.backgroundColor = elementInfo.stackedFormElement.collapsedView.backgroundColor
self.layoutIfNeeded()
} completion: { _ in
self.delegate?.stackedFormView?(self, didElementCollapseAt: index)
completed?()
}
}
private func animateExpand(for elementInfo: ElementInfo, at index: Int, completed: (() -> ())?) {
UIView.animate(withDuration: StackedFormView.ANIMATION_TIME / 2) {
elementInfo.stackedFormElement.collapsedView.alpha = 0
} completion: { status in
UIView.animate(withDuration: StackedFormView.ANIMATION_TIME / 2) {
elementInfo.stackedFormElement.expandedView.alpha = 1
self.currentExpandedIndex = index
}
elementInfo.stackedFormElement.collapsedView.removeFromSuperview()
}
UIView.animate(withDuration: StackedFormView.ANIMATION_TIME) {
elementInfo.viewArea.backgroundColor = elementInfo.stackedFormElement.expandedView.backgroundColor
self.layoutIfNeeded()
} completion: { _ in
completed?()
self.delegate?.stackedFormView?(self, didElementExpandAt: index)
}
}
private func suddenlyCollapse(for elementInfo: ElementInfo, at index: Int, completed: (() -> ())?) {
elementInfo.stackedFormElement.expandedView.removeFromSuperview()
elementInfo.stackedFormElement.collapsedView.alpha = 1.0
elementInfo.viewArea.backgroundColor = elementInfo.stackedFormElement.collapsedView.backgroundColor
self.delegate?.stackedFormView?(self, didElementCollapseAt: index)
completed?()
}
private func suddenlyExpand(for elementInfo: ElementInfo, at index: Int, completed: (() -> ())?) {
elementInfo.stackedFormElement.collapsedView.removeFromSuperview()
elementInfo.stackedFormElement.expandedView.alpha = 1.0
self.currentExpandedIndex = index
elementInfo.viewArea.backgroundColor = elementInfo.stackedFormElement.expandedView.backgroundColor
self.delegate?.stackedFormView?(self, didElementExpandAt: index)
completed?()
}
}
//MARK: ElementInfo Class Declaration
extension StackedFormView {
private class ElementInfo {
let stackedFormElement: StackedFormElement
let heightConstraint: NSLayoutConstraint
let viewArea: UIView
let gestureRecogniser: UIGestureRecognizer
init(stackedFormElement: StackedFormElement, viewArea: UIView, heightConstraint: NSLayoutConstraint, gestureRecogniser: UIGestureRecognizer) {
self.stackedFormElement = stackedFormElement
self.heightConstraint = heightConstraint
self.viewArea = viewArea
self.gestureRecogniser = gestureRecogniser
}
}
}
//MARK: StackedFormElementDelegate Implementations
extension StackedFormView: StackedFormElementDelegate {
public func didFinishInput(in stackedFormElement: StackedFormElement) {
self.didTapNextButton(sender: self.ctaButton)
}
public func dataDidBecomeInvalid(in stackedFormElement: StackedFormElement) {
self.ctaButton.isEnabled = false
self.delegate?.stackedFormView(self, styleButtonForInvalidStateWith: self.ctaButton)
}
public func dataDidBecomeValid(in stackedFormElement: StackedFormElement) {
self.ctaButton.isEnabled = true
self.delegate?.stackedFormView(self, styleButtonForValidStateWith: self.ctaButton)
}
}
#endif |
/*
Author: cuckoo
Date: 2017/05/03 22:20:18
Update:
Problem: Count Primes
Difficulty: Easy
Source: https://leetcode.com/problems/count-primes/#/description
*/
#include <algorithm> // for count()
#include <vector>
using std::vector;
class Solution {
public:
int countPrimes(int n) {
return countPrimesSecond(n);
}
/* wrong - example {49(7 * 7)}
int countPrimesFirst(int n)
{
if(n <= 1) return 0;
if(n == 2) return 1;
if(n == 3) return 2;
if(n == 4) return 2;
if(n == 5) return 3;
int num = 5, count = 3;
while(++num <= n)
if(num % 2 != 0 && num % 3 != 0 && num % 5 != 0)
++count;
return count;
}
*/
int countPrimesSecond(int n)
{
if(n <= 1) return 0;
vector<bool> is_prime(n, true);
is_prime[0] = is_prime[1] = false;
for(int i = 0; i * i < n; ++i)
{
if(is_prime[i])
{
for(int j = i * i; j < n; j += i)
is_prime[j] = false;
}
}
return count(is_prime.begin(), is_prime.end(), true);
}
}; |
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
const defaultPadding = 30.0;
const statusBarColor = Color(0xFF004060);
const redColor = Color(0xFFEF5A5A);
const greenColor = Color(0xFF008421);
const yellowColor = Color(0xFFffcc00);
const boxShadowColor = Colors.black26;
const boxBorderColor = Color(0xFFCBCBCB);
const boxBorderWidth = 0.5;
const maxWidgetWidth = 700.0;
class AppTheme {
//FONT
static const primaryFont = 'NotoNaskhArabic';
//COLORS
static const primaryColor = Colors.blue;
static const onPrimaryColor = Color(0xfffffefe);
static const secondaryColor = Colors.deepPurple;
static const onSecondaryColor = Color(0xfffffefe);
static const tertiaryColor = Color(0xFF0C6591);
static const onTertiaryColor = Color(0xfffffefe);
static const surfaceColor = Color(0xfffffefe);
static const onSurfaceColor = Color(0xff1A374D);
static const backgroundColor = Color(0xfffffefe);
static const onBackgroundColor = Color(0xff1A374D);
static const errorColor = Color(0xFFff382e);
static const onErrorColor = Color(0xfffffefe);
static ThemeData appTheme(double ratio) =>
ThemeData(
applyElevationOverlayColor: false,
cupertinoOverrideTheme: const NoDefaultCupertinoThemeData(),
// extensions:,
inputDecorationTheme: const InputDecorationTheme(
enabledBorder: OutlineInputBorder(
borderSide: BorderSide(color: Colors.grey),
),
border: OutlineInputBorder(
borderSide: BorderSide(color: Colors.grey),
)),
materialTapTargetSize: MaterialTapTargetSize.shrinkWrap,
pageTransitionsTheme: const PageTransitionsTheme(),
scrollbarTheme: const ScrollbarThemeData(),
primaryColor: primaryColor,
colorScheme: const ColorScheme(
brightness: Brightness.light,
primary: primaryColor,
onPrimary: onPrimaryColor,
primaryContainer: primaryColor,
onPrimaryContainer: onPrimaryColor,
secondary: secondaryColor,
onSecondary: onSecondaryColor,
secondaryContainer: secondaryColor,
onSecondaryContainer: onSecondaryColor,
tertiary: tertiaryColor,
onTertiary: onTertiaryColor,
// tertiaryContainer: ,
// onTertiaryContainer: ,
error: errorColor,
onError: onErrorColor,
background: backgroundColor,
onBackground: onBackgroundColor,
surface: surfaceColor,
onSurface: onSurfaceColor),
brightness: Brightness.light,
//
//
// primarySwatch: MaterialColor(primary, swatch),
// primaryColor: Color(value),
//
//
// primaryColor: Color(value),
// primaryColorDark: Color(value),
//
//
// focusColor: Color(value),
// hoverColor: Color(value),
shadowColor: boxShadowColor,
// canvasColor: Color(value),
// scaffoldBackgroundColor: Color(value),
// bottomAppBarColor: Color(value),
cardColor: onTertiaryColor,
// dividerColor: Color(value),
// highColor: Color(value),
// splashColor: Color(value),
// selectedRowColor: Color(value),
unselectedWidgetColor: Colors.white,
// disabledColor: Color(value),
// secondaryHeaderColor: Color(value),
// backgroundColor: Color(value),
// dialogBackgroundColor: Color(value),
// indicatorColor: Color(value),
// hintColor: Color(value),
// errorColor: Color(value),
// toggleableActiveColor: Color(value),
fontFamily: primaryFont,
typography: Typography(),
textTheme: const TextTheme(
displayLarge: TextStyle(),
//T:57 E:64 P:0
displayMedium: TextStyle(),
//T:45 E:52 P:0
displaySmall: TextStyle(),
//T:36 E:44 P:0
headlineLarge: TextStyle(),
//T:32 E:40 P:0
headlineMedium: TextStyle(),
//T:28 E:36 P:0
headlineSmall: TextStyle(),
//T:24 E:32 P:0
titleLarge: TextStyle(),
//T:22 E:28 P:0
titleMedium: TextStyle(),
//T:16 E:24 P:0.15
titleSmall: TextStyle(),
//T:14 E:20 P:0.1
bodyLarge: TextStyle(),
//T:14 E:20 P:0.1
bodyMedium: TextStyle(),
//T:12 E:16 P:0.5
bodySmall: TextStyle(),
//T:11 E:16 P:0.5
labelLarge: TextStyle(),
//T:16 E:24 P:0.15
labelMedium: TextStyle(),
//T:14 E:20 P:0.25
labelSmall: TextStyle(), //T:12 E:16 P:0.4
),
primaryTextTheme: const TextTheme(),
iconTheme: const IconThemeData(color: primaryColor, size: 20),
primaryIconTheme: const IconThemeData(size: 20),
appBarTheme: const AppBarTheme(),
bannerTheme: const MaterialBannerThemeData(),
bottomAppBarTheme: const BottomAppBarTheme(),
bottomNavigationBarTheme: const BottomNavigationBarThemeData(
selectedItemColor: primaryColor,
unselectedItemColor: secondaryColor,
),
bottomSheetTheme: const BottomSheetThemeData(),
buttonBarTheme: const ButtonBarThemeData(),
buttonTheme: const ButtonThemeData(),
cardTheme: const CardTheme(),
checkboxTheme: const CheckboxThemeData(),
chipTheme: const ChipThemeData(),
dataTableTheme: const DataTableThemeData(),
dialogTheme: const DialogTheme(),
dividerTheme: const DividerThemeData(),
drawerTheme: const DrawerThemeData(),
elevatedButtonTheme: const ElevatedButtonThemeData(),
floatingActionButtonTheme: const FloatingActionButtonThemeData(),
listTileTheme: const ListTileThemeData(),
navigationBarTheme: const NavigationBarThemeData(),
navigationRailTheme: const NavigationRailThemeData(),
outlinedButtonTheme: const OutlinedButtonThemeData(),
popupMenuTheme: const PopupMenuThemeData(),
progressIndicatorTheme: const ProgressIndicatorThemeData(),
radioTheme: const RadioThemeData(),
sliderTheme: const SliderThemeData(),
snackBarTheme: const SnackBarThemeData(),
switchTheme: const SwitchThemeData(),
tabBarTheme: const TabBarTheme(),
textButtonTheme: const TextButtonThemeData(),
textSelectionTheme: const TextSelectionThemeData(),
timePickerTheme: const TimePickerThemeData(),
toggleButtonsTheme: const ToggleButtonsThemeData(),
tooltipTheme: const TooltipThemeData(),
expansionTileTheme: const ExpansionTileThemeData(),
);
} |
package ru.ifmo.se.entity.readers;
import ru.ifmo.se.entity.Color;
import ru.ifmo.se.entity.Person;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.PrintWriter;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
public class PersonReader {
private static boolean validateHairColor(String line) {
try{
Color.valueOf(line);
return true;
} catch(IllegalArgumentException e){
return false;
}
}
private static boolean validateDate(String line) {
return line.matches("^\\d{4}-(0?[1-9]|1[012])-(0?[1-9]|[12][0-9]|3[01])$");
}
private static String readAndParseName(BufferedReader reader, PrintWriter printer) throws IOException {
String line;
do {
printer.print("Введите имя автора: ");
printer.flush();
line = reader.readLine();
}while (line != null && !LabWorkReader.validateName(line));
return line;
}
private static Date readAndParseBirthday(BufferedReader reader, PrintWriter printer) throws IOException {
String line;
DateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
Date date = null;
do{
printer.print("Введите день рождения в формате yyyy-MM-dd: ");
printer.flush();
line = reader.readLine();
if (line == null)
return null;
try {
date = formatter.parse(line);
} catch (ParseException e) {}
}while(!validateDate(line));
return date;
}
private static Integer readAndParseHeight(BufferedReader reader, PrintWriter printer) throws IOException {
String line;
while (true) {
try {
printer.print("Введите рост: ");
printer.flush();
line = reader.readLine();
if (line == null) return null;
Integer.parseInt(line);
} catch (Exception e){
printer.println("Что-то пошло не так... Введите целое число");
continue;
}
if (Integer.parseInt(line) > 0)
break;
printer.println("Значение должно быть больше 0");
}
return Integer.parseInt(line);
}
private static Double readAndParseWeight(BufferedReader reader, PrintWriter printer) throws IOException {
String line;
while (true) {
try {
printer.print("Введите вес: ");
printer.flush();
line = reader.readLine();
if (line == null) return null;
Double.parseDouble(line);
} catch (Exception e){
printer.println("Что-то пошло не так... Введите дробное число");
continue;
}
if (Double.parseDouble(line) > 0)
break;
printer.println("Значение должно быть больше 0");
}
return Double.parseDouble(line);
}
private static Color readAndParseHairColor(BufferedReader reader, PrintWriter printer) throws IOException {
String line;
do {
printer.println("Введите цвет волос");
for (Color cur: Color.values()){
printer.println(cur.name());
}
printer.print("Ваш выбор: ");
printer.flush();
line = reader.readLine();
if (line == null)
return null;
line = line.toUpperCase();
} while (!validateHairColor(line));
return Color.valueOf(line);
}
public static Person readPerson(BufferedReader reader, PrintWriter printer) throws IOException {
Person result = new Person();
String name = readAndParseName(reader, printer);
Date birthday = readAndParseBirthday(reader, printer);
Integer height = readAndParseHeight(reader, printer);
Double weight = readAndParseWeight(reader, printer);
Color color = readAndParseHairColor(reader, printer);
if (name == null || birthday == null || height == null || weight == null || color == null)
return null;
result.setAuthorName(name);
result.setBirthday(birthday);
result.setHeight(height);
result.setWeight(weight);
result.setHairColor(color);
return result;
}
} |
import os
import re
from flask import Flask, jsonify, render_template, request, url_for
from cs50 import SQL
from helpers import lookup
# Configure application
app = Flask(__name__)
# Configure CS50 Library to use SQLite database
db = SQL("sqlite:///mashup.db")
# Ensure responses aren't cached
@app.after_request
def after_request(response):
response.headers["Cache-Control"] = "no-cache, no-store, must-revalidate"
response.headers["Expires"] = 0
response.headers["Pragma"] = "no-cache"
return response
@app.route("/")
def index():
"""Render map"""
if not os.environ.get("API_KEY"):
raise RuntimeError("API_KEY not set")
return render_template("index.html", key=os.environ.get("API_KEY"))
@app.route("/articles")
def articles():
"""Look up articles for geo.Call lookup. Complete the implementation of
/articles in such a way that it outputs a JSON array of objects,
each of which represents an article for geo,
whereby geo is passed into /articles as a GET parameter"""
articles = lookup(request.args.get("geo"))
if len(articles) > 5:
return jsonify([articles[0], articles[1], articles[2], articles[3], articles[4]])
else:
return jsonify(articles)
@app.route("/search")
def search():
"""Search for places that match query
Complete the implementation of /search in such a way that it outputs a JSON array of objects,
each of which represents a row from places that somehow matches the value of q"""
place = db.execute("SELECT * FROM places WHERE postal_code = :q", q=request.args.get("q"))
if len(place) > 5:
return jsonify([place[0], place[1], place[2], place[3], place[4]])
else:
return jsonify(place)
@app.route("/update")
def update():
"""Find up to 10 places within view"""
# Ensure parameters are present
if not request.args.get("sw"):
raise RuntimeError("missing sw")
if not request.args.get("ne"):
raise RuntimeError("missing ne")
# Ensure parameters are in lat,lng format
if not re.search("^-?\d+(?:\.\d+)?,-?\d+(?:\.\d+)?$", request.args.get("sw")):
raise RuntimeError("invalid sw")
if not re.search("^-?\d+(?:\.\d+)?,-?\d+(?:\.\d+)?$", request.args.get("ne")):
raise RuntimeError("invalid ne")
# Explode southwest corner into two variables
sw_lat, sw_lng = map(float, request.args.get("sw").split(","))
# Explode northeast corner into two variables
ne_lat, ne_lng = map(float, request.args.get("ne").split(","))
# Find 10 cities within view, pseudorandomly chosen if more within view
if sw_lng <= ne_lng:
# Doesn't cross the antimeridian
rows = db.execute("""SELECT * FROM places
WHERE :sw_lat <= latitude AND latitude <= :ne_lat AND (:sw_lng <= longitude AND longitude <= :ne_lng)
GROUP BY country_code, place_name, admin_code1
ORDER BY RANDOM()
LIMIT 10""",
sw_lat=sw_lat, ne_lat=ne_lat, sw_lng=sw_lng, ne_lng=ne_lng)
else:
# Crosses the antimeridian
rows = db.execute("""SELECT * FROM places
WHERE :sw_lat <= latitude AND latitude <= :ne_lat AND (:sw_lng <= longitude OR longitude <= :ne_lng)
GROUP BY country_code, place_name, admin_code1
ORDER BY RANDOM()
LIMIT 10""",
sw_lat=sw_lat, ne_lat=ne_lat, sw_lng=sw_lng, ne_lng=ne_lng)
# Output places as JSON
return jsonify(rows) |
import logging
import unicodedata
from io import BytesIO
import pathway as pw
CHARS_PER_TOKEN = 3
PUNCTUATION = [".", "?", "!", "\n"]
@pw.udf
def chunk_texts(
texts: str | list[str],
min_tokens: int = 50,
max_tokens: int = 500,
encoding_name: str = "cl100k_base",
) -> list[str]:
"""
Splits a given string or a list of strings into chunks based on token
count.
This function tokenizes the input texts and splits them into smaller parts ("chunks")
ensuring that each chunk has a token count between `min_tokens` and
`max_tokens`. It also attempts to break chunks at sensible points such as
punctuation marks.
Arguments:
texts: string or list of strings.
min_tokens: minimum tokens in a chunk of text.
max_tokens: maximum size of a chunk in tokens.
encoding_name: name of the encoding from `tiktoken`.
Example:
# >>> from pathway.stdlib.ml import chunk_texts
# >>> import pathway as pw
# >>> t = pw.debug.table_from_markdown(
# ... '''| text
# ... 1| cooltext'''
# ... )
# >>> t += t.select(chunks = chunk_texts(pw.this.text, min_tokens=1, max_tokens=1))
# >>> pw.debug.compute_and_print(t, include_id=False)
# text | chunks
# cooltext | ('cool', 'text')
"""
import tiktoken
if not isinstance(texts, str):
texts = "\n".join(texts)
tokenizer = tiktoken.get_encoding(encoding_name)
text: str = texts
text = normalize_unicode(text)
tokens = tokenizer.encode_ordinary(text)
output = []
i = 0
while i < len(tokens):
chunk_tokens = tokens[i : i + max_tokens]
chunk = tokenizer.decode(chunk_tokens)
last_punctuation = max([chunk.rfind(p) for p in PUNCTUATION], default=-1)
if last_punctuation != -1 and last_punctuation > CHARS_PER_TOKEN * min_tokens:
chunk = chunk[: last_punctuation + 1]
i += len(tokenizer.encode_ordinary(chunk))
output.append(chunk)
return output
def normalize_unicode(text: str):
"""
Get rid of ligatures
"""
return unicodedata.normalize("NFKC", text)
@pw.udf
def extract_texts(data: bytes) -> list[str]:
"""
Extract text elements from binary data using the partition function from
unstructured-io.
Visit [unstructured-io](https://unstructured-io.github.io/unstructured/) to know
more.
Arguments:
data (bytes): Binary data representing the text format file.
Returns:
list[str]: A list of extracted text elements.
Example
# >>> from pathway.stdlib.ml import extract_texts
# >>> import pathway as pw
# >>> t = pw.debug.table_from_markdown(
# ... '''| text
# ... 1| cooltext'''
# ... )
# >>> t += t.select(bytes = pw.apply(str.encode, pw.this.text))
# >>> t = t.select(decoded=extract_texts(pw.this.bytes))
# >>> pw.debug.compute_and_print(t, include_id=False)
# decoded
# ('cooltext',)
"""
from unstructured.partition.auto import partition
file_like = BytesIO(data)
try:
elements = partition(file=file_like)
texts = [element.text for element in elements]
except ValueError as ve:
logging.error(f"Value Error: {str(ve)}")
return []
except Exception as e:
logging.exception(f"An unexpected error occurred: {str(e)}")
return []
return texts |
<h2>Template Driven</h2>
<form (ngSubmit)="onSubmit(form)" #form="ngForm">
<div ngModelGroup="userData">
<div class="form-group">
<label for="username">Username</label>
<input
type="text"
class="form-control"
id="username"
name="username"
[ngModel]="user.username"
required
/>
</div>
<div class="form-group">
<label for="email">E-Mail</label>
<input
type="email"
class="form-control"
id="email"
name="email"
[ngModel]="user.email"
pattern="^[\w!#$%&'*+\-/=?\^`{|}~]+(\.[\w!#$%&'*+\-/=?\^`{|}~]+)*@[\-\w]+[\.\-\w]*\.[a-zA-Z]{2,9}$"
required
email
#email="ngModel"
/>
<span *ngIf="!email.valid && email.touched" class="text-danger small"
>Invalid E-Mail</span
>
</div>
</div>
<div>
<div class="form-group">
<label for="password">Password</label>
<input
type="password"
class="form-control"
id="password"
name="password"
[ngModel]="user.password"
required
/>
</div>
</div>
<div>
<div class="form-group" *ngFor="let gender of genders">
<label for="radio">
<input
type="radio"
name="gender"
[ngModel]="user.gender"
[value]="gender"
/>
{{ gender }}
</label>
</div>
</div>
<button type="submit" class="btn btn-primary mt-3" [disabled]="!form.valid">
Submit
</button>
</form> |
<!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">
<%@ taglib prefix="form" uri="http://www.springframework.org/tags/form" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<!-- 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">
<link rel="shortcut icon" type="image/icon" href="/images/favicon.ico"/>
<link href="/css/style.css" type="text/css" rel="stylesheet">
<script src="https://kit.fontawesome.com/d450c035a5.js" crossorigin="anonymous"></script>
<title>Welkom bij Plannie</title>
</head>
<body >
<jsp:include page="header.jsp"/>
<div class="container mt-3">
<div class="row">
<div class="col-sm-8">
<div class="jumbotron shadow border">
<div class="row">
<p class="lead">Info 3</p>
<p>
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Suspendisse enim velit, tempor vel dolor et, porttitor vestibulum odio. Ut quis elit eu est viverra aliquam a ultricies leo. Curabitur non arcu hendrerit, vestibulum dui sit amet, suscipit diam. Integer suscipit dui tortor, euismod accumsan magna dictum ut. Curabitur sit amet nunc id sapien malesuada aliquet sit amet et arcu. In hendrerit porta justo vitae tempus. Orci varius natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Integer sit amet felis mauris. Proin vitae condimentum dolor. Mauris commodo porttitor mi, in consequat dui posuere ac. Praesent vitae enim magna. Sed egestas malesuada ligula, vel molestie tortor finibus at. Fusce vestibulum convallis tempus. Ut vel erat ultrices, placerat sapien a, ornare erat. Aliquam scelerisque convallis mauris a interdum. Etiam rhoncus in mi nec mollis. Cras malesuada elit et purus tincidunt varius. Suspendisse placerat lacus non libero pretium volutpat. Ut malesuada, ex non vehicula vulputate, quam ex ullamcorper dolor, id consectetur libero quam viverra ex. Aliquam blandit cursus ipsum consequat dictum. Cras vitae urna bibendum lorem maximus sollicitudin. Praesent consequat ultrices mi in bibendum. Nunc lorem dui, elementum id massa sed, dictum vehicula nulla. Maecenas in semper eros, eget vehicula risus. Integer vel lorem consequat ipsum auctor pretium imperdiet vitae sem. Sed volutpat, eros non eleifend mattis, lorem risus congue ante, et laoreet nulla felis ac augue. Curabitur rutrum dui tellus, dapibus eleifend augue hendrerit et. Phasellus efficitur urna tortor, et venenatis ipsum sagittis vitae. Nam tincidunt consectetur diam eget suscipit. Aenean at purus faucibus, venenatis lectus quis, maximus nisi.
</p>
<p>
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Suspendisse enim velit, tempor vel dolor et, porttitor vestibulum odio. Ut quis elit eu est viverra aliquam a ultricies leo. Curabitur non arcu hendrerit, vestibulum dui sit amet, suscipit diam. Integer suscipit dui tortor, euismod accumsan magna dictum ut. Curabitur sit amet nunc id sapien malesuada aliquet sit amet et arcu. In hendrerit porta justo vitae tempus. Orci varius natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Integer sit amet felis mauris. Proin vitae condimentum dolor. Mauris commodo porttitor mi, in consequat dui posuere ac. Praesent vitae enim magna. Sed egestas malesuada ligula, vel molestie tortor finibus at. Fusce vestibulum convallis tempus. Ut vel erat ultrices, placerat sapien a, ornare erat. Aliquam scelerisque convallis mauris a interdum. Etiam rhoncus in mi nec mollis. Cras malesuada elit et purus tincidunt varius. Suspendisse placerat lacus non libero pretium volutpat. Ut malesuada, ex non vehicula vulputate, quam ex ullamcorper dolor, id consectetur libero quam viverra ex. Aliquam blandit cursus ipsum consequat dictum. Cras vitae urna bibendum lorem maximus sollicitudin. Praesent consequat ultrices mi in bibendum. Nunc lorem dui, elementum id massa sed, dictum vehicula nulla. Maecenas in semper eros, eget vehicula risus. Integer vel lorem consequat ipsum auctor pretium imperdiet vitae sem. Sed volutpat, eros non eleifend mattis, lorem risus congue ante, et laoreet nulla felis ac augue. Curabitur rutrum dui tellus, dapibus eleifend augue hendrerit et. Phasellus efficitur urna tortor, et venenatis ipsum sagittis vitae. Nam tincidunt consectetur diam eget suscipit. Aenean at purus faucibus, venenatis lectus quis, maximus nisi.
</p>
</div>
</div>
</div>
<div class="col-sm-4">
<div class="jumbotron shadow" style="background-color: #FF3B56;">
<div class="row" >
<p class="lead text-white">Info 1</p>
</div>
<hr class="my-4">
<div class="row">
<p class="lead text-white mt-3">Info 2</hp>
<hr class="my-4">
</div>
</div>
</div>
</div>
<div class="row mb-3">
<div class="col-sm-offset-1 col-sm-10 mb-5">
<div class="card w-75 mx-auto">
<div class="card-body">
<p>Contact</p>
</div>
</div>
</div>
</div>
</div>
<div class="modal fade" id="loginmodal" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel" aria-hidden="true">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="inloggenmodal">Inloggen</h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body">
<form:form id="loginForm" action="/index" modelAttribute="loginForm" method="post">
<div class="form-group">
<form:input type="email" class="form-control" id="username" path="username" placeholder="Email"/>
</div>
<div class="form-group">
<form:input type="password" id="password" path="password" class="form-control" placeholder="Wachtwoord"/>
<a id="resetten" class="nav-link text-dark" data-toggle="modal" data-target="#resetmodal">Wachtwoord resetten</a>
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-dismiss="modal">Annuleer</button>
<button id="login" type="submit" class="btn btn-primary">Login</button>
</form:form>
</div>
</div>
</div>
</div>
<div class="modal fade" id="resetmodal" tabindex="-1" role="dialog" aria-labelledby="resetmodal" aria-hidden="true">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" class="close" id="resetmodal2"><p>Wachtwoord Resetten</p></h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<form:form id="updatePasswordForm" action="/wachtwoordReset" modelAttribute="updatePasswordForm" method="post">
<div class="modal-body">
<div class="form-group">
<form:input type="email" class="form-control" id="usernameReset" path="email" placeholder="Email"/>
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-dismiss="modal">Annuleer</button>
<button id="resetWachtwoord" type="submit" class="btn btn-primary">Reset Wachtwoord</button>
</div>
</form:form>
</div>
</div>
</div>
<!-- Footer -->
<footer class="py-4 bg-dark text-white-50">
<!-- Footer Elements -->
<div class="container">
<!-- Call to action -->
<ul class="list-unstyled list-inline text-center py-2">
<h6 class="mb-1"><small>Registreer je snel: <a id="registreren" href="/registreren" class="text-white">klik hier!</a></small></h6>
</li>
</ul>
<!-- Call to action -->
</div>
<!-- Footer Elements -->
</footer>
<!-- 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/popper.js@1.16.0/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>
</body>
</html> |
class QuizBrain :
def __init__(self, list):
self.question_number =0
self.question_list = list
self.score = 0
def next_question(self):
question_ask = self.question_list[self.question_number]
self.question_number += 1
user_ans = input(f"Q.{self.question_number } : {question_ask.text} (True/False) :")
self.check_answer(user_ans,question_ask.answer)
def still_has_questions(self):
return self.question_number < len(self.question_list)
def check_answer(self, user_ans, correct_ans):
if user_ans.lower() == correct_ans.lower():
self.score +=1
print("You got it right!")
else:
print("You got it wrong")
print(f"The correct answer was : {correct_ans}.")
print(f"Your current score is: {self.score}/{self.question_number}")
print("\n") |
package com.stackroute.pe2;
import static org.junit.Assert.*;
import org.junit.AfterClass;
import org.junit.BeforeClass;
import org.junit.Test;
public class FolderFileNamesReaderTest {
public static FolderFileNamesReader folderFileNamesReader;
@BeforeClass
public static void setUp()
{
folderFileNamesReader = new FolderFileNamesReader();
}
@AfterClass
public static void tearDown()
{
folderFileNamesReader = null;
}
@Test()
public void testForGetTextFilenamesOfFolder()
{
String[] filenames = folderFileNamesReader.getFolderFilenames("/home/srujana/Documents/srujana", "txt");
assertEquals(1,filenames.length);
assertEquals("sjn.txt", filenames[0]);
}
@Test()
public void testForGetPdfFilenamesOfFolder()
{
String[] filenames = folderFileNamesReader.getFolderFilenames("/home/srujana/Documents/srujana", "pdf");
assertEquals(1,filenames.length);
assertEquals("sjn.pdf", filenames[0]);
}
@Test()
public void testForGetFilenamesOfFolderFailure()
{
String[] filenames = folderFileNamesReader.getFolderFilenames("/home/srujana/Documents/Dummy", "pdf");
assertNull(null,filenames);
}
} |
import { useState, useEffect } from "react";
import { useDispatch, useSelector } from "react-redux";
import { useNavigate } from "react-router-dom";
import { addCardsMagic } from "../../reducers/cardsSlice";
import { getUser } from "../../reducers/sliceUser";
import { Col, Container, Row, Pagination } from "react-bootstrap";
import { bringCardsByName } from "../../services/apiCalls";
import { MagicCard } from "../../common/magicCard/MagicCard";
import { Searcher } from "../../common/searcher/Searcher";
import { Filter } from "../../common/filter/Filter";
import Load1 from '/public/images/load/load-1.gif'
import Load2 from '/public/images/load/load-2.gif'
import Load3 from '/public/images/load/load-3.gif'
import Load4 from '/public/images/load/load-4.gif'
import Load5 from '/public/images/load/load-5.gif'
import Load6 from '/public/images/load/load-6.gif'
import Load7 from '/public/images/load/load-7.gif'
import Load8 from '/public/images/load/load-8.gif'
import Load9 from '/public/images/load/load-9.gif'
import "./Home.css";
export const Home = () => {
const navigate = useNavigate();
const [cards, setCards] = useState([]);
const [page, setPage] = useState(1);
const [totalPages, setTotalPages] = useState(1);
const [input, setInput] = useState("");
const [colours, setColours] = useState("b,w,u,r,g");
const dispatch = useDispatch();
const [loading, setLoading] = useState(false);
const [imgLoad, setImgLoad] = useState();
const images = {
1: Load1,
2: Load2,
3: Load3,
4: Load4,
5: Load5,
6: Load6,
7: Load7,
8: Load8,
9: Load9,
}
const userEmailLogin = useSelector(getUser).user.email;
const userName = useSelector(getUser).user.name;
const calculateTotalPages = (res) => {
if (res.headers["total-count"] % 100 == 0) {
return Math.trunc(res.headers["total-count"] / 100);
} else {
return Math.trunc(res.headers["total-count"] / 100) + 1;
}
};
const changeValue = (name) => {
setPage(1);
setInput(name);
};
const changeColours = (changedColours) => {
setPage(1);
setColours(changedColours);
};
useEffect(() => {
let imgValue = Math.trunc(1 + Math.random() * 8);
setImgLoad(imgValue)
setLoading(true);
const bringData = setTimeout(() => {
bringCardsByName(input, colours, page)
.then((res) => {
setLoading(false);
setCards(res.cards);
setTotalPages(calculateTotalPages(res));
dispatch(addCardsMagic(res.cards));
})
.catch((error) => {
console.log(`Error en la llamada bringCardsByName: ${error}`);
});
}, 500);
return () => clearTimeout(bringData);
}, [page, input, colours]);
const cambiarPagina = (pag) => {
// window.scrollTo({ top: anchor.current.offsetTop, behavior: "smooth" });
let pagina = pag;
if (pagina < 1) {
pagina = 1;
}
if (pagina > totalPages) {
pagina = totalPages;
}
setPage(pagina);
};
return (
<>
<Container fluid className="box-name-home">
<Row className="d-flex align-items-center justify-content-center ">
<Col className="d-flex align-items-center justify-content-start py-1" sm={11}>
{userEmailLogin
?<h6 className="login-home-logued">{`Bienvenido, ${userName}`}</h6>
:<h6 className="login-home" onClick={()=>{navigate("/login")}}>¡¡Logueate!!</h6>
}
</Col>
</Row>
</Container>
<Container fluid className="bg-dark box-searcher-home">
<Row className="d-flex justify-content-center ">
<Col sm={10}>
<Row className="d-flex align-items-center justify-content-center ">
<Col sm={12} lg={4} className="d-flex justify-content-center ">
<Searcher changeValue={(e) => changeValue(e)} />
</Col>
<Col
sm={12}
lg={8}
className="d-flex align-items-center justify-content-center text-info"
>
<Filter changeColours={(e) => changeColours(e)} />
</Col>
</Row>
</Col>
</Row>
</Container>
{!loading && cards && cards.length<=0 && (
<>
<Container
fluid
className="d-flex align-items-center justify-content-center flex-column bg-dark py-1 box-cards-home"
>
<Row>
<Col
className="rounded-2 my-2 d-flex align-items-center justify-content-center no-results"
>
<h2>No se han encontrado resultados</h2>
</Col>
</Row>
<Row>
<Pagination className="mt-4 p-2 box-pagination-home">
<Pagination.First
className="pagination-button-home"
disabled={page <= 1}
onClick={() => {
cambiarPagina(1);
}}
/>
<Pagination.Prev
className="pagination-button-home"
disabled={page <= 1}
onClick={() => {
cambiarPagina(page - 1);
}}
/>
<Pagination.Ellipsis />
{page > 1 && (
<Pagination.Item
onClick={() => {
cambiarPagina(page - 1);
}}
>
{page - 1}
</Pagination.Item>
)}
<Pagination.Item active>{page}</Pagination.Item>
{page < totalPages && (
<Pagination.Item
onClick={() => {
cambiarPagina(page + 1);
}}
>
{page + 1}
</Pagination.Item>
)}
<Pagination.Ellipsis />
<Pagination.Next
className="pagination-button-home"
disabled={page >= totalPages}
onClick={() => {
cambiarPagina(page + 1);
}}
/>
<Pagination.Last
className="pagination-button-home"
disabled={page >= totalPages}
onClick={() => {
cambiarPagina(totalPages);
}}
/>
</Pagination>
</Row>
</Container>
</>
)}
{!loading && cards && cards.length>0 && (
<>
<Container
fluid
className="d-flex align-items-center justify-content-center flex-column bg-dark py-1 box-cards-home flip-vertical-right"
>
<Row className="wrapper">
{cards &&
cards.map((card) => {
setTimeout
return (
<Col
key={card.id}
className="rounded-2 my-2 d-flex align-items-center justify-content-center home-card"
>
<MagicCard
id={card.id}
name={card.name}
colors={card.colors}
type={card.type}
image={card.imageUrl}
rarity={card.rarity}
info={card.text}
{...card}
/>
</Col>
);
})}
</Row>
<Row>
<Pagination className="mt-4 p-2 box-pagination-home">
<Pagination.First
className="pagination-button-home"
disabled={page <= 1}
onClick={() => {
cambiarPagina(1);
}}
/>
<Pagination.Prev
className="pagination-button-home"
disabled={page <= 1}
onClick={() => {
cambiarPagina(page - 1);
}}
/>
<Pagination.Ellipsis />
{page > 1 && (
<Pagination.Item
onClick={() => {
cambiarPagina(page - 1);
}}
>
{page - 1}
</Pagination.Item>
)}
<Pagination.Item active>{page}</Pagination.Item>
{page < totalPages && (
<Pagination.Item
onClick={() => {
cambiarPagina(page + 1);
}}
>
{page + 1}
</Pagination.Item>
)}
<Pagination.Ellipsis />
<Pagination.Next
className="pagination-button-home"
disabled={page >= totalPages}
onClick={() => {
cambiarPagina(page + 1);
}}
/>
<Pagination.Last
className="pagination-button-home"
disabled={page >= totalPages}
onClick={() => {
cambiarPagina(totalPages);
}}
/>
</Pagination>
</Row>
</Container>
</>
)}
{loading && (
<Container className="box-detail">
<Row className="d-flex align-items-center justify-content-center box-detail p-5">
<Col
sm={12}
className="d-flex align-items-center justify-content-center box-detail "
>
{
<img
className="rounded-4"
src={images[imgLoad]}
alt="load-img"
/>
}
</Col>
<Col
sm={12}
className="d-flex align-items-center justify-content-center box-detail py-2 text-light"
>
Cargando...
</Col>
</Row>
</Container>
)}
</>
);
}; |
/*
This query is for MMS messages from the mmssms.db
*/
SELECT
/* Add a row number at the beggining of each row */
ROW_NUMBER() OVER() AS 'Row #',
pdu._id AS 'MMS_ID',
pdu.thread_id AS 'Thread ID',
/* Date/Time of the message in UTC */
CASE
WHEN pdu.date > 0 THEN strftime('%Y-%m-%d %H:%M:%S', pdu.date, 'UNIXEPOCH')
ELSE 'n/a'
END AS 'Date (UTC)',
/* Date/Time the message was sent in UTC */
CASE
WHEN pdu.date_sent > 0 THEN strftime('%Y-%m-%d %H:%M:%S', pdu.date_sent, 'UNIXEPOCH')
ELSE 'n/a'
END as 'Date Sent (UTC)',
/* Message direction (incoming/outgoing) */
CASE
WHEN pdu.msg_box = 1 THEN 'Incoming'
WHEN pdu.msg_box = 2 THEN 'Outgoing'
ELSE pdu.msg_box
END AS 'Direction',
/* Was the message read */
pdu.read AS 'Read',
/* Phone number of the message sender */
/* Removes unnecessary text at the start of the string to leave just the 10-digit phone number */
CASE
WHEN (SELECT SUBSTR(address,3) FROM addr WHERE pdu._id=addr.msg_id AND addr.type=137 AND addr.address LIKE '%+1%') IS NULL THEN (SELECT address FROM addr WHERE pdu._id=addr.msg_id AND addr.type=137)
ELSE (SELECT SUBSTR(address,3) FROM addr WHERE pdu._id=addr.msg_id AND addr.type=137 AND addr.address LIKE '%+1%')
END AS 'FROM',
/* Phone number of the message recipient */
/* Removes unnecessary text at the start of the string to leave just the 10-digit phone number */
CASE
WHEN (SELECT SUBSTR(address,3) FROM addr WHERE pdu._id=addr.msg_id AND addr.type=151 AND addr.address LIKE '%+1%') IS NULL THEN (SELECT address FROM addr WHERE pdu._id=addr.msg_id AND addr.type=151)
ELSE (SELECT SUBSTR(address,3) FROM addr WHERE pdu._id=addr.msg_id AND addr.type=151 AND addr.address LIKE '%+1%')
END AS 'TO',
/* If the message was CCed to anyone, it will be listed here */
CASE
WHEN (SELECT address FROM addr WHERE pdu._id=addr.msg_id AND addr.type=130) IS NULL THEN 'n/a'
ELSE (SELECT address FROM addr WHERE pdu._id=addr.msg_id AND addr.type=130)
END AS 'CC',
/* If the message was BCCed to anyone, it will be listed here */
CASE
WHEN (SELECT address FROM addr WHERE pdu._id=addr.msg_id AND addr.type=129) IS NULL THEN 'n/a'
ELSE (SELECT address FROM addr WHERE pdu._id=addr.msg_id AND addr.type=129)
END AS 'BCC',
part._id AS 'part_id',
part.seq,
part.ct AS 'Data Type',
/* File name of the attached file (if any) */
CASE
WHEN part.cl IS NULL THEN 'n/a'
ELSE part.cl
END AS 'File Name',
/* File path of the attached file (if any) */
part._data AS 'File Path',
/* Message content */
part.text AS 'Message',
pdu.creator AS 'Creator',
pdu.sim_imsi AS 'SIM IMSI',
pdu.correlation_tag AS 'Correlation Tag',
pdu.ct_l AS 'URI',
/* Source for each line of data */
'File: \data\data\com.android.providers.telephony\databases\mmssms.db; Table: pdu(_id: ' || pdu._id || ')' AS 'Data Source'
FROM pdu
LEFT JOIN part ON part.mid=pdu._id
/* Groups the messages first by the `_id` value, then by `date` and then by `part_id` */
ORDER BY pdu._id, pdu.date, part_id
/*
Query for just SMS messages from the mmssms.db
*/
SELECT
/* Add a row number at the beggining of each row */
ROW_NUMBER() OVER() AS 'Row #',
sms._id AS 'SMS_ID',
sms.thread_id AS 'Thread ID',
/* Removes unnecessary text at the start of the string to leave just the 10-digit phone number */
/* Formats string as a U.S. phone number, i.e. (###) ###-#### */
CASE
WHEN LENGTH(sms.address) = 12 AND sms.address LIKE '%+1%' THEN '(' || SUBSTR(sms.address,3,3) || ') ' || SUBSTR(sms.address,6,3) || '-' || SUBSTR(sms.address,9,4)
WHEN LENGTH(sms.address) = 10 THEN '(' || SUBSTR(sms.address,1,3) || ') ' || SUBSTR(sms.address,4,3) || '-' || SUBSTR(sms.address,7,4)
ELSE sms.address
END AS 'Address',
CASE
WHEN sms.person IS NULL THEN 'n/a'
ELSE sms.person
END AS 'Person',
/* Date/Time of the message */
CASE
WHEN sms.date > 0 THEN strftime('%Y-%m-%d %H:%M:%S', sms.date / 1000, 'UNIXEPOCH')
ELSE 'n/a'
END AS 'Date/Time (UTC)',
/* Message direction (incoming/outgoing) */
CASE sms.type
WHEN 1 THEN 'Incoming'
WHEN 2 THEN 'Outgoing'
ELSE sms.type
END AS 'Direction',
/* Was the message read */
CASE sms.read
WHEN 0 THEN 'Unread'
WHEN 1 THEN 'Read'
ELSE sms.read
END AS 'Message Read',
/* Was a subject listed for the message */
CASE
WHEN sms.subject IS NULL THEN 'n/a'
ELSE sms.subject
END AS 'Subject',
/* Message content */
sms.body AS 'Message Text',
/* Removes unnecessary text at the start of the string to leave just the 10-digit phone number */
/* Formats string as a U.S. phone number, i.e. (###) ###-#### */
CASE
WHEN sms.service_center IS NULL THEN 'n/a'
WHEN LENGTH(sms.service_center) = 12 AND sms.service_center LIKE '%+1%' THEN '(' || SUBSTR(sms.service_center,3,3) || ') ' || SUBSTR(sms.service_center,6,3) || '-' || SUBSTR(sms.service_center,9,4)
ELSE sms.service_center
END AS 'Service Center',
sms.creator AS 'Creator',
sms.correlation_tag AS 'Correlation Tag',
sms.sim_imsi AS 'SIM IMSI',
/* Source for each line of data */
'File: \data\data\com.android.providers.telephony\databases\mmssms.db; Table: sms(_id: ' || sms._id || ')' AS 'Data Source'
FROM sms
/* Groups the messages first by the `thread_id` value and then by the `date` value */
ORDER BY sms.thread_id, sms.date |
// The MIT License (MIT)
//
// Copyright (c) 2023 Olrea, Florian Dang
//
// 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.
#ifndef OPENAI_HPP_
#define OPENAI_HPP_
#if OPENAI_VERBOSE_OUTPUT
#pragma message ("OPENAI_VERBOSE_OUTPUT is ON")
#endif
#include <iostream>
#include <stdexcept>
#include <string>
#include <vector>
#include <sstream>
#include <mutex>
#include <cstdlib>
#include <map>
#ifndef CURL_STATICLIB
#include <curl/curl.h>
#else
#include "curl/curl.h"
#endif
#ifdef _ECS36B_JSONCPP_
#include "ecs36b_Common.h"
#include "ecs36b_Exception.h"
#else /* _ECS36B_JSONCPP_ */
// #include <nlohmann/json.hpp> // nlohmann/json
#include "json.hpp" // nlohmann/json
#endif /* _ECS36B_JSONCPP_ */
namespace openai {
namespace _detail {
#ifdef _ECS36B_JSONCPP_
#else /* _ECS36B_JSONCPP_ */
// Json alias
using Json = nlohmann::json;
#endif /* _ECS36B_JSONCPP_ */
struct Response {
std::string text;
bool is_error;
std::string error_message;
};
// Simple curl Session inspired by CPR
class Session {
public:
Session(bool throw_exception) : throw_exception_{throw_exception} {
initCurl();
ignoreSSL();
}
Session(bool throw_exception, std::string proxy_url) : throw_exception_{ throw_exception } {
initCurl();
ignoreSSL();
setProxyUrl(proxy_url);
}
~Session() {
curl_easy_cleanup(curl_);
curl_global_cleanup();
if (mime_form_ != nullptr) {
curl_mime_free(mime_form_);
}
}
void initCurl() {
curl_global_init(CURL_GLOBAL_ALL);
curl_ = curl_easy_init();
if (curl_ == nullptr) {
throw std::runtime_error("curl cannot initialize");
// here we throw it shouldn't happen
}
}
void ignoreSSL() {
curl_easy_setopt(curl_, CURLOPT_SSL_VERIFYPEER, 0L);
}
void setUrl(const std::string& url) { url_ = url; }
void setToken(const std::string& token, const std::string& organization) {
token_ = token;
organization_ = organization;
}
void setProxyUrl(const std::string& url) {
proxy_url_ = url;
curl_easy_setopt(curl_, CURLOPT_PROXY, proxy_url_.c_str());
}
void setBody(const std::string& data);
void setMultiformPart(const std::pair<std::string, std::string>& filefield_and_filepath,
const std::map<std::string, std::string>& fields);
Response getPrepare();
Response postPrepare(const std::string& contentType = "");
Response deletePrepare();
Response makeRequest(const std::string& contentType = "");
std::string easyEscape(const std::string& text);
private:
static size_t writeFunction(void* ptr, size_t size, size_t nmemb, std::string* data){
data->append((char*) ptr, size * nmemb);
return size * nmemb;
}
private:
CURL* curl_;
CURLcode res_;
curl_mime *mime_form_ = nullptr;
std::string url_;
std::string proxy_url_;
std::string token_;
std::string organization_;
bool throw_exception_;
std::mutex mutex_request_;
};
inline void
Session::setBody
(const std::string& data)
{
if (curl_)
{
curl_easy_setopt(curl_, CURLOPT_POSTFIELDSIZE, data.length());
curl_easy_setopt(curl_, CURLOPT_POSTFIELDS, data.data());
}
}
inline void
Session::setMultiformPart
(const std::pair<std::string, std::string>& fieldfield_and_filepath,
const std::map<std::string, std::string>& fields)
{
// https://curl.se/libcurl/c/curl_mime_init.html
if (curl_)
{
if (mime_form_ != nullptr)
{
curl_mime_free(mime_form_);
mime_form_ = nullptr;
}
curl_mimepart *field = nullptr;
mime_form_ = curl_mime_init(curl_);
field = curl_mime_addpart(mime_form_);
curl_mime_name(field, fieldfield_and_filepath.first.c_str());
curl_mime_filedata(field, fieldfield_and_filepath.second.c_str());
for (const auto &field_pair : fields)
{
field = curl_mime_addpart(mime_form_);
curl_mime_name(field, field_pair.first.c_str());
curl_mime_data(field, field_pair.second.c_str(), CURL_ZERO_TERMINATED);
}
curl_easy_setopt(curl_, CURLOPT_MIMEPOST, mime_form_);
}
}
inline Response
Session::getPrepare
(void)
{
if (curl_)
{
curl_easy_setopt(curl_, CURLOPT_HTTPGET, 1L);
curl_easy_setopt(curl_, CURLOPT_POST, 0L);
curl_easy_setopt(curl_, CURLOPT_NOBODY, 0L);
}
return makeRequest();
}
inline Response
Session::postPrepare
(const std::string& contentType)
{
return makeRequest(contentType);
}
inline Response
Session::deletePrepare()
{
if (curl_)
{
curl_easy_setopt(curl_, CURLOPT_HTTPGET, 0L);
curl_easy_setopt(curl_, CURLOPT_NOBODY, 0L);
curl_easy_setopt(curl_, CURLOPT_CUSTOMREQUEST, "DELETE");
}
return makeRequest();
}
inline Response
Session::makeRequest(const std::string& contentType)
{
std::lock_guard<std::mutex> lock(mutex_request_);
struct curl_slist* headers = NULL;
if (!contentType.empty())
{
headers = curl_slist_append(headers,
std::string{"Content-Type: " + contentType}.c_str());
if (contentType == "multipart/form-data")
{
headers = curl_slist_append(headers, "Expect:");
}
}
headers = curl_slist_append(headers,
std::string{"Authorization: Bearer " + token_}.c_str());
if (!organization_.empty())
{
headers = curl_slist_append(headers,
std::string{"OpenAI-Organization: " + organization_}.c_str());
}
curl_easy_setopt(curl_, CURLOPT_HTTPHEADER, headers);
curl_easy_setopt(curl_, CURLOPT_URL, url_.c_str());
std::string response_string;
std::string header_string;
curl_easy_setopt(curl_, CURLOPT_WRITEFUNCTION, writeFunction);
curl_easy_setopt(curl_, CURLOPT_WRITEDATA, &response_string);
curl_easy_setopt(curl_, CURLOPT_HEADERDATA, &header_string);
#ifdef _ECS36B_JSONCPP_
// sfwu "not sure if this is needed" (for timeout consideration)
curl_easy_setopt(curl_, CURLOPT_TIMEOUT, 0);
#endif /* _ECS36B_JSONCPP_ */
// std::cout << url_ << std::endl;
res_ = curl_easy_perform(curl_);
bool is_error = false;
std::string error_msg{};
if(res_ != CURLE_OK)
{
is_error = true;
error_msg = "OpenAI curl_easy_perform() failed: " +
std::string{curl_easy_strerror(res_)};
if (throw_exception_)
{
throw std::runtime_error(error_msg);
}
else
{
std::cerr << error_msg << '\n';
}
}
#ifdef _ECS36B_VERBOSE_
std::cout << "response_string " << response_string << std::endl;
#endif /* _ECS36B_VERBOSE_ */
return { response_string, is_error, error_msg };
}
inline std::string
Session::easyEscape
(const std::string& text)
{
char *encoded_output = curl_easy_escape(curl_, text.c_str(),
static_cast<int>(text.length()));
const auto str = std::string{ encoded_output };
curl_free(encoded_output);
return str;
}
// forward declaration for category structures
class OpenAI;
// https://platform.openai.com/docs/api-reference/models
// List and describe the various models available in the API.
// You can refer to the Models documentation to understand
// what models are available and the differences between them.
struct CategoryModel
{
#ifdef _ECS36B_JSONCPP_
Json::Value list();
Json::Value retrieve(const std::string& model);
#else /* _ECS36B_JSONCPP_ */
Json list();
Json retrieve(const std::string& model);
#endif /* _ECS36B_JSONCPP_ */
CategoryModel(OpenAI& openai) : openai_{openai} {}
private:
OpenAI& openai_;
};
// https://platform.openai.com/docs/api-reference/completions
// Given a prompt, the model will return one or more predicted completions, and can also return the probabilities of alternative tokens at each position.
struct CategoryCompletion
{
#ifdef _ECS36B_JSONCPP_
Json::Value create(Json::Value input);
#else /* _ECS36B_JSONCPP_ */
Json create(Json input);
#endif /* _ECS36B_JSONCPP_ */
CategoryCompletion(OpenAI& openai) : openai_{openai} {}
private:
OpenAI& openai_;
};
// https://platform.openai.com/docs/api-reference/chat
// Given a prompt, the model will return one or more predicted chat completions.
struct CategoryChat
{
#ifdef _ECS36B_JSONCPP_
Json::Value create(Json::Value input);
#else /* _ECS36B_JSONCPP_ */
Json create(Json input);
#endif /* _ECS36B_JSONCPP_ */
CategoryChat(OpenAI& openai) : openai_{openai} {}
private:
OpenAI& openai_;
};
// https://platform.openai.com/docs/api-reference/audio
// Learn how to turn audio into text.
struct CategoryAudio
{
#ifdef _ECS36B_JSONCPP_
Json::Value transcribe(Json::Value input);
Json::Value translate(Json::Value input);
#else /* _ECS36B_JSONCPP_ */
Json transcribe(Json input);
Json translate(Json input);
#endif /* _ECS36B_JSONCPP_ */
CategoryAudio(OpenAI& openai) : openai_{openai} {}
private:
OpenAI& openai_;
};
// https://platform.openai.com/docs/api-reference/edits
// Given a prompt and an instruction, the model will return an edited version of the prompt.
struct CategoryEdit
{
#ifdef _ECS36B_JSONCPP_
Json::Value create(Json::Value input);
#else /* _ECS36B_JSONCPP_ */
Json create(Json input);
#endif /* _ECS36B_JSONCPP_ */
CategoryEdit(OpenAI& openai) : openai_{openai} {}
private:
OpenAI& openai_;
};
// https://platform.openai.com/docs/api-reference/images
// Given a prompt and/or an input image, the model will generate a new image.
struct CategoryImage {
#ifdef _ECS36B_JSONCPP_
Json::Value create(Json::Value input);
Json::Value edit(Json::Value input);
Json::Value variation(Json::Value input);
#else /* _ECS36B_JSONCPP_ */
Json create(Json input);
Json edit(Json input);
Json variation(Json input);
#endif /* _ECS36B_JSONCPP_ */
CategoryImage(OpenAI& openai) : openai_{openai} {}
private:
OpenAI& openai_;
};
// https://platform.openai.com/docs/api-reference/embeddings
// Get a vector representation of a given input that can be easily consumed by machine learning models and algorithms.
struct CategoryEmbedding
{
#ifdef _ECS36B_JSONCPP_
Json::Value create(Json::Value input);
#else /* _ECS36B_JSONCPP_ */
Json create(Json input);
#endif /* _ECS36B_JSONCPP_ */
CategoryEmbedding(OpenAI& openai) : openai_{openai} {}
private:
OpenAI& openai_;
};
struct FileRequest
{
std::string file;
std::string purpose;
};
// https://platform.openai.com/docs/api-reference/files
// Files are used to upload documents that can be used with features like Fine-tuning.
struct CategoryFile
{
#ifdef _ECS36B_JSONCPP_
Json::Value list(void);
Json::Value upload(Json::Value input);
Json::Value del(const std::string& file); // TODO
Json::Value retrieve(const std::string& file_id);
Json::Value content(const std::string& file_id);
#else /* _ECS36B_JSONCPP_ */
Json list();
Json upload(Json input);
Json del(const std::string& file); // TODO
Json retrieve(const std::string& file_id);
Json content(const std::string& file_id);
#endif /* _ECS36B_JSONCPP_ */
CategoryFile(OpenAI& openai) : openai_{openai} {}
private:
OpenAI& openai_;
};
// https://platform.openai.com/docs/api-reference/fine-tunes
// Manage fine-tuning jobs to tailor a model to your specific training data.
struct CategoryFineTune {
#ifdef _ECS36B_JSONCPP_
Json::Value create(Json::Value input);
Json::Value list(void);
Json::Value retrieve(const std::string& fine_tune_id);
Json::Value content(const std::string& fine_tune_id);
Json::Value cancel(const std::string& fine_tune_id);
Json::Value events(const std::string& fine_tune_id);
Json::Value del(const std::string& model); // TODO
#else /* _ECS36B_JSONCPP_ */
Json create(Json input);
Json list();
Json retrieve(const std::string& fine_tune_id);
Json content(const std::string& fine_tune_id);
Json cancel(const std::string& fine_tune_id);
Json events(const std::string& fine_tune_id);
Json del(const std::string& model);
#endif /* _ECS36B_JSONCPP_ */
CategoryFineTune(OpenAI& openai) : openai_{openai} {}
private:
OpenAI& openai_;
};
// https://platform.openai.com/docs/api-reference/moderations
// Given a input text, outputs if the model classifies it as violating OpenAI's content policy.
struct CategoryModeration
{
#ifdef _ECS36B_JSONCPP_
Json::Value create(Json::Value input);
#else /* _ECS36B_JSONCPP_ */
Json create(Json input);
#endif /* _ECS36B_JSONCPP_ */
CategoryModeration(OpenAI& openai) : openai_{openai} {}
private:
OpenAI& openai_;
};
// OpenAI
class OpenAI
{
public:
OpenAI(const std::string& token = "",
const std::string& organization = "",
bool throw_exception = true)
: session_{throw_exception}, token_{token},
organization_{organization}, throw_exception_{throw_exception}
{
if (token.empty())
{
if(const char* env_p = std::getenv("OPENAI_API_KEY"))
{
token_ = std::string{env_p};
}
}
session_.setUrl("https://api.openai.com/v1/");
session_.setToken(token_, organization_);
}
OpenAI(const OpenAI&) = delete;
OpenAI& operator=(const OpenAI&) = delete;
OpenAI(OpenAI&&) = delete;
OpenAI& operator=(OpenAI&&) = delete;
void setProxy(const std::string& url) { session_.setProxyUrl(url); }
// void change_token(const std::string& token) { token_ = token; };
void setThrowException(bool throw_exception) { throw_exception_ = throw_exception; }
void setMultiformPart(const std::pair<std::string, std::string>& filefield_and_filepath,
const std::map<std::string, std::string>& fields)
{
session_.setMultiformPart(filefield_and_filepath, fields);
}
#ifdef _ECS36B_JSONCPP_
Json::Value post(const std::string& suffix, const std::string& data,
const std::string& contentType)
#else /* _ECS36B_JSONCPP_ */
Json post(const std::string& suffix, const std::string& data, const std::string& contentType)
#endif /* _ECS36B_JSONCPP_ */
{
setParameters(suffix, data, contentType);
auto response = session_.postPrepare(contentType);
if (response.is_error)
{
trigger_error(response.error_message);
}
#ifdef _ECS36B_JSONCPP_
Json::Value json;
if (myParseJSON(response.text, &json) == 0)
{
checkResponse(json);
}
#else /* _ECS36B_JSONCPP_ */
Json json{};
if (isJson(response.text))
{
json = Json::parse(response.text);
checkResponse(json);
}
#endif /* _ECS36B_JSONCPP_ */
else
{
#if OPENAI_VERBOSE_OUTPUT
std::cerr << "Response is not a valid JSON";
std::cout << "<< " << response.text << "\n";
#endif
}
return json;
}
#ifdef _ECS36B_JSONCPP_
Json::Value get(const std::string& suffix, const std::string& data = "")
#else /* _ECS36B_JSONCPP_ */
Json get(const std::string& suffix, const std::string& data = "")
#endif /* _ECS36B_JSONCPP_ */
{
setParameters(suffix, data);
auto response = session_.getPrepare();
if (response.is_error) { trigger_error(response.error_message); }
#ifdef _ECS36B_JSONCPP_
Json::Value json;
if (myParseJSON(response.text, &json) == 0)
{
checkResponse(json);
}
#else /* _ECS36B_JSONCPP_ */
Json json{};
if (isJson(response.text))
{
json = Json::parse(response.text);
checkResponse(json);
}
#endif /* _ECS36B_JSONCPP_ */
else
{
#if OPENAI_VERBOSE_OUTPUT
std::cerr << "Response is not a valid JSON";
std::cout << "<< " << response.text << "\n";
#endif
}
return json;
}
#ifdef _ECS36B_JSONCPP_
Json::Value post(const std::string& suffix, const Json::Value& json,
const std::string& contentType="application/json")
{
#ifdef _ECS36B_VERBOSE_
std::cout << "post called\n";
#endif /* _ECS36B_VERBOSE_ */
return post(suffix, json.toStyledString(), contentType);
}
#else /* _ECS36B_JSONCPP_ */
Json post(const std::string& suffix, const Json& json,
const std::string& contentType="application/json")
{
return post(suffix, json.dump(), contentType);
}
#endif /* _ECS36B_JSONCPP_ */
#ifdef _ECS36B_JSONCPP_
Json::Value del(const std::string& suffix)
#else /* _ECS36B_JSONCPP_ */
Json del(const std::string& suffix)
#endif /* _ECS36B_JSONCPP_ */
{
setParameters(suffix, "");
auto response = session_.deletePrepare();
if (response.is_error) { trigger_error(response.error_message); }
#ifdef _ECS36B_JSONCPP_
Json::Value json;
if (myParseJSON(response.text, &json) == 0)
{
checkResponse(json);
}
#else /* _ECS36B_JSONCPP_ */
Json json{};
if (isJson(response.text))
{
json = Json::parse(response.text);
checkResponse(json);
}
#endif /* _ECS36B_JSONCPP_ */
else
{
#if OPENAI_VERBOSE_OUTPUT
std::cerr << "Response is not a valid JSON\n";
std::cout << "<< " << response.text<< "\n";
#endif
}
return json;
}
std::string easyEscape(const std::string& text) { return session_.easyEscape(text); }
void debug() const { std::cout << token_ << '\n'; }
void setBaseUrl(const std::string &url)
{
base_url = url;
}
std::string getBaseUrl() const
{
return base_url;
}
private:
std::string base_url{ "https://api.openai.com/v1/" };
void setParameters
(const std::string& suffix, const std::string& data, const std::string& contentType = "")
{
auto complete_url = base_url+ suffix;
session_.setUrl(complete_url);
if (contentType != "multipart/form-data")
{
session_.setBody(data);
}
#ifdef _ECS36B_VERBOSE_
std::cout << "<< ecs36b request: "<< complete_url << " " << data << '\n';
#endif /* _ECS36B_VERBOSE_ */
#if OPENAI_VERBOSE_OUTPUT
std::cout << "<< request: "<< complete_url << " " << data << '\n';
#endif
}
#ifdef _ECS36B_JSONCPP_
void
checkResponse(const Json::Value& json)
#else /* _ECS36B_JSONCPP_ */
void
checkResponse(const Json& json)
#endif /* _ECS36B_JSONCPP_ */
{
#ifdef _ECS36B_JSONCPP_
if (true) // Need to work on this part later!!!! Felix reminder.
{
#else /* _ECS36B_JSONCPP_ */
if (json.count("error"))
{
auto reason = json["error"].dump();
trigger_error(reason);
#if OPENAI_VERBOSE_OUTPUT
std::cerr << ">> response error :\n" << json.dump(2) << "\n";
#endif
#endif /* _ECS36B_JSONCPP_ */
}
}
#ifdef _ECS36B_JSONCPP_
// we need to handle the throw catch stuff for json parsing
#else /* _ECS36B_JSONCPP_ */
// as of now the only way
bool
isJson(const std::string &data)
{
bool rc = true;
try
{
auto json = Json::parse(data); // throws if no json
}
catch (std::exception &)
{
rc = false;
}
return(rc);
}
#endif /* _ECS36B_JSONCPP_ */
void
trigger_error(const std::string& msg)
{
if (throw_exception_)
{
throw std::runtime_error(msg);
}
else
{
std::cerr << "[OpenAI] error. Reason: " << msg << '\n';
}
}
public:
CategoryModel model {*this};
CategoryCompletion completion{*this};
CategoryEdit edit {*this};
CategoryImage image {*this};
CategoryEmbedding embedding {*this};
CategoryFile file {*this};
CategoryFineTune fine_tune {*this};
CategoryModeration moderation{*this};
CategoryChat chat {*this};
CategoryAudio audio {*this};
// CategoryEngine engine{*this}; // Not handled since deprecated (use Model instead)
private:
Session session_;
std::string token_;
std::string organization_;
bool throw_exception_;
};
inline std::string
bool_to_string(const bool b)
{
std::ostringstream ss;
ss << std::boolalpha << b;
return ss.str();
}
inline OpenAI&
start
(const std::string& token = "", const std::string& organization = "",
bool throw_exception = true)
{
static OpenAI instance{token, organization, throw_exception};
return instance;
}
inline OpenAI&
instance()
{
return start();
}
#ifdef _ECS36B_JSONCPP_
inline Json::Value
post
(const std::string& suffix, const Json::Value& json)
{
std::cout << "\n\npost called 1\n\n";
return instance().post(suffix, json);
}
#else /* _ECS36B_JSONCPP_ */
inline Json
post
(const std::string& suffix, const Json& json)
{
std::cout << "\n\npost called 1\n\n";
return instance().post(suffix, json);
}
#endif /* _ECS36B_JSONCPP_ */
#ifdef _ECS36B_JSONCPP_
inline Json::Value
get
(const std::string& suffix /*, const Json& json*/)
{
return instance().get(suffix);
}
#else /* _ECS36B_JSONCPP_ */
inline Json
get
(const std::string& suffix/*, const Json& json*/)
{
return instance().get(suffix);
}
#endif /* _ECS36B_JSONCPP_ */
// Helper functions to get category structures instance()
inline CategoryModel&
model(void)
{
return instance().model;
}
inline CategoryCompletion&
completion(void)
{
return instance().completion;
}
inline CategoryChat&
chat(void)
{
return instance().chat;
}
inline CategoryAudio&
audio(void)
{
return instance().audio;
}
inline CategoryEdit&
edit(void)
{
return instance().edit;
}
inline CategoryImage&
image(void)
{
return instance().image;
}
inline CategoryEmbedding&
embedding(void)
{
return instance().embedding;
}
inline CategoryFile&
file(void)
{
return instance().file;
}
inline CategoryFineTune&
fineTune(void)
{
return instance().fine_tune;
}
inline CategoryModeration&
moderation(void)
{
return instance().moderation;
}
// Definitions of category methods
// GET https://api.openai.com/v1/models
// Lists the currently available models, and provides basic information about each one such as the owner and availability.
#ifdef _ECS36B_JSONCPP_
inline Json::Value
CategoryModel::list
(void)
#else /* _ECS36B_JSONCPP_ */
inline Json
CategoryModel::list
(void)
#endif /* _ECS36B_JSONCPP_ */
{
return openai_.get("models");
}
// GET https://api.openai.com/v1/models/{model}
// Retrieves a model instance, providing basic information about the model such as the owner and permissioning.
#ifdef _ECS36B_JSONCPP_
inline Json::Value
CategoryModel::retrieve
(const std::string& model)
#else /* _ECS36B_JSONCPP_ */
inline Json
CategoryModel::retrieve
(const std::string& model)
#endif /* _ECS36B_JSONCPP_ */
{
return openai_.get("models/" + model);
}
// POST https://api.openai.com/v1/completions
// Creates a completion for the provided prompt and parameters
#ifdef _ECS36B_JSONCPP_
inline Json::Value
CategoryCompletion::create
(Json::Value input)
#else /* _ECS36B_JSONCPP_ */
inline Json
CategoryCompletion::create
(Json input)
#endif /* _ECS36B_JSONCPP_ */
{
// std::cout << "CategoryCompletion create called\n";
return openai_.post("completions", input);
}
// POST https://api.openai.com/v1/chat/completions
// Creates a chat completion for the provided prompt and parameters
#ifdef _ECS36B_JSONCPP_
inline Json::Value
CategoryChat::create
(Json::Value input)
#else /* _ECS36B_JSONCPP_ */
inline Json
CategoryChat::create
(Json input)
#endif /* _ECS36B_JSONCPP_ */
{
return openai_.post("chat/completions", input);
}
// POST https://api.openai.com/v1/audio/transcriptions
// Transcribes audio into the input language.
#ifdef _ECS36B_JSONCPP_
inline Json::Value
CategoryAudio::transcribe
(Json::Value input)
{
openai_.setMultiformPart({"file", input["file"].asString()},
std::map<std::string, std::string>{
{"model", input["model"].asString()}}
);
#else /* _ECS36B_JSONCPP_ */
inline Json
CategoryAudio::transcribe
(Json input)
{
openai_.setMultiformPart({"file", input["file"].get<std::string>()},
std::map<std::string, std::string>{
{"model", input["model"].get<std::string>()}}
);
#endif /* _ECS36B_JSONCPP_ */
return openai_.post("audio/transcriptions", std::string{""}, "multipart/form-data");
}
// POST https://api.openai.com/v1/audio/translations
// Translates audio into into English..
#ifdef _ECS36B_JSONCPP_
inline Json::Value
CategoryAudio::translate
(Json::Value input)
{
openai_.setMultiformPart({"file", input["file"].asString()},
std::map<std::string, std::string>{
{"model", input["model"].asString()}}
);
#else /* _ECS36B_JSONCPP_ */
inline Json
CategoryAudio::translate
(Json input)
{
openai_.setMultiformPart({"file", input["file"].get<std::string>()},
std::map<std::string, std::string>{
{"model", input["model"].get<std::string>()}}
);
#endif /* _ECS36B_JSONCPP_ */
return openai_.post("audio/translations", std::string{""}, "multipart/form-data");
}
// POST https://api.openai.com/v1/translations
// Creates a new edit for the provided input, instruction, and parameters
#ifdef _ECS36B_JSONCPP_
inline Json::Value
CategoryEdit::create
(Json::Value input)
#else /* _ECS36B_JSONCPP_ */
inline Json
CategoryEdit::create
(Json input)
#endif /* _ECS36B_JSONCPP_ */
{
return openai_.post("edits", input);
}
// POST https://api.openai.com/v1/images/generations
// Given a prompt and/or an input image, the model will generate a new image.
#ifdef _ECS36B_JSONCPP_
inline Json::Value
CategoryImage::create
(Json::Value input)
#else /* _ECS36B_JSONCPP_ */
inline Json CategoryImage::create(Json input)
#endif /* _ECS36B_JSONCPP_ */
{
return openai_.post("images/generations", input);
}
// POST https://api.openai.com/v1/images/edits
// Creates an edited or extended image given an original image and a prompt.
#ifdef _ECS36B_JSONCPP_
inline Json::Value
CategoryImage::edit
(Json::Value input)
{
// need more works here <== Felix
std::string prompt = input["prompt"].asString(); // required
// Default values
std::string mask = "";
int n = 1;
std::string size = "1024x1024";
std::string response_format = "url";
std::string user = "";
if ((input["mask"].isNull() == false) &&
(input["mask"].isString() == true))
{
mask = input["mask"].asString();
}
if ((input["n"].isNull() == false) &&
(input["n"].isInt() == true))
{
n = input["n"].asInt();
}
if ((input["size"].isNull() == false) &&
(input["size"].isString() == true))
{
size = input["size"].asString();
}
if ((input["response_format"].isNull() == false) &&
(input["response_format"].isString() == true))
{
response_format = input["response_format"].asString();
}
if ((input["user"].isNull() == false) &&
(input["user"].isString() == true))
{
user = input["user"].asString();
}
openai_.setMultiformPart({"image",input["image"].asString()},
std::map<std::string, std::string>{
{"prompt", prompt},
{"mask", mask},
{"n", std::to_string(n)},
{"size", size},
{"response_format", response_format},
{"user", user}
}
);
#else /* _ECS36B_JSONCPP_ */
inline Json CategoryImage::edit(Json input)
{
std::string prompt = input["prompt"].get<std::string>(); // required
// Default values
std::string mask = "";
int n = 1;
std::string size = "1024x1024";
std::string response_format = "url";
std::string user = "";
if (input.contains("mask"))
{
mask = input["mask"].get<std::string>();
}
if (input.contains("n"))
{
n = input["n"].get<int>();
}
if (input.contains("size"))
{
size = input["size"].get<std::string>();
}
if (input.contains("response_format"))
{
response_format = input["response_format"].get<std::string>();
}
if (input.contains("user"))
{
user = input["user"].get<std::string>();
}
openai_.setMultiformPart({"image",input["image"].get<std::string>()},
std::map<std::string, std::string>{
{"prompt", prompt},
{"mask", mask},
{"n", std::to_string(n)},
{"size", size},
{"response_format", response_format},
{"user", user}
}
);
#endif /* _ECS36B_JSONCPP_ */
return openai_.post("images/edits", std::string{""}, "multipart/form-data");
}
// POST https://api.openai.com/v1/images/variations
// Creates a variation of a given image.
#ifdef _ECS36B_JSONCPP_
inline Json::Value
CategoryImage::variation
(Json::Value input)
{
// need more work
// Default values
int n = 1;
std::string size = "1024x1024";
std::string response_format = "url";
std::string user = "";
if ((input["n"].isNull() == false) &&
(input["n"].isInt() == true))
{
n = input["n"].asInt();
}
if ((input["size"].isNull() == false) &&
(input["size"].isString() == true))
{
size = input["size"].asString();
}
if ((input["response_format"].isNull() == false) &&
(input["response_format"].isString() == true))
{
response_format = input["response_format"].asString();
}
if ((input["user"].isNull() == false) &&
(input["user"].isString() == true))
{
user = input["user"].asString();
}
openai_.setMultiformPart({"image",input["image"].asString()},
std::map<std::string, std::string>{
{"n", std::to_string(n)},
{"size", size},
{"response_format", response_format},
{"user", user}
}
);
#else /* _ECS36B_JSONCPP_ */
inline Json CategoryImage::variation(Json input) {
// Default values
int n = 1;
std::string size = "1024x1024";
std::string response_format = "url";
std::string user = "";
if (input.contains("n")) {
n = input["n"].get<int>();
}
if (input.contains("size")) {
size = input["size"].get<std::string>();
}
if (input.contains("response_format")) {
response_format = input["response_format"].get<std::string>();
}
if (input.contains("user")) {
user = input["user"].get<std::string>();
}
openai_.setMultiformPart({"image",input["image"].get<std::string>()},
std::map<std::string, std::string>{
{"n", std::to_string(n)},
{"size", size},
{"response_format", response_format},
{"user", user}
}
);
#endif /* _ECS36B_JSONCPP_ */
return openai_.post("images/variations", std::string{""}, "multipart/form-data");
}
#ifdef _ECS36B_JSONCPP_
inline Json::Value CategoryEmbedding::create(Json::Value input)
#else /* _ECS36B_JSONCPP_ */
inline Json CategoryEmbedding::create(Json input)
#endif /* _ECS36B_JSONCPP_ */
{
return openai_.post("embeddings", input);
}
#ifdef _ECS36B_JSONCPP_
inline Json::Value CategoryFile::list()
#else /* _ECS36B_JSONCPP_ */
inline Json CategoryFile::list()
#endif /* _ECS36B_JSONCPP_ */
{
return openai_.get("files");
}
#ifdef _ECS36B_JSONCPP_
inline Json::Value CategoryFile::upload(Json::Value input)
{
openai_.setMultiformPart({"file", input["file"].asString()},
std::map<std::string, std::string>{
{"purpose", input["purpose"].asString()}
}
);
#else /* _ECS36B_JSONCPP_ */
inline Json CategoryFile::upload(Json input)
{
openai_.setMultiformPart({"file", input["file"].get<std::string>()},
std::map<std::string, std::string>{
{"purpose", input["purpose"].get<std::string>()}
}
);
#endif /* _ECS36B_JSONCPP_ */
return openai_.post("files", std::string{""}, "multipart/form-data");
}
#ifdef _ECS36B_JSONCPP_
inline Json::Value CategoryFile::del(const std::string& file_id)
#else /* _ECS36B_JSONCPP_ */
inline Json CategoryFile::del(const std::string& file_id)
#endif /* _ECS36B_JSONCPP_ */
{
return openai_.del("files/" + file_id);
}
#ifdef _ECS36B_JSONCPP_
inline Json::Value CategoryFile::retrieve(const std::string& file_id)
#else /* _ECS36B_JSONCPP_ */
inline Json CategoryFile::retrieve(const std::string& file_id)
#endif /* _ECS36B_JSONCPP_ */
{
return openai_.get("files/" + file_id);
}
#ifdef _ECS36B_JSONCPP_
inline Json::Value CategoryFile::content(const std::string& file_id)
#else /* _ECS36B_JSONCPP_ */
inline Json CategoryFile::content(const std::string& file_id)
#endif /* _ECS36B_JSONCPP_ */
{
return openai_.get("files/" + file_id + "/content");
}
#ifdef _ECS36B_JSONCPP_
inline Json::Value CategoryFineTune::create(Json::Value input)
#else /* _ECS36B_JSONCPP_ */
inline Json CategoryFineTune::create(Json input)
#endif /* _ECS36B_JSONCPP_ */
{
return openai_.post("fine-tunes", input);
}
#ifdef _ECS36B_JSONCPP_
inline Json::Value CategoryFineTune::list()
#else /* _ECS36B_JSONCPP_ */
inline Json CategoryFineTune::list()
#endif /* _ECS36B_JSONCPP_ */
{
return openai_.get("fine-tunes");
}
#ifdef _ECS36B_JSONCPP_
inline Json::Value CategoryFineTune::retrieve(const std::string& fine_tune_id)
#else /* _ECS36B_JSONCPP_ */
inline Json CategoryFineTune::retrieve(const std::string& fine_tune_id)
#endif /* _ECS36B_JSONCPP_ */
{
return openai_.get("fine-tunes/" + fine_tune_id);
}
#ifdef _ECS36B_JSONCPP_
inline Json::Value CategoryFineTune::content(const std::string& fine_tune_id)
#else /* _ECS36B_JSONCPP_ */
inline Json CategoryFineTune::content(const std::string& fine_tune_id)
#endif /* _ECS36B_JSONCPP_ */
{
return openai_.get("fine-tunes/" + fine_tune_id + "/content");
}
#ifdef _ECS36B_JSONCPP_
inline Json::Value CategoryFineTune::cancel(const std::string& fine_tune_id)
{
// not sure about this. should check later.
return openai_.post("fine-tunes/" + fine_tune_id + "/cancel", Json::Value{});
#else /* _ECS36B_JSONCPP_ */
inline Json CategoryFineTune::cancel(const std::string& fine_tune_id)
{
return openai_.post("fine-tunes/" + fine_tune_id + "/cancel", Json{});
#endif /* _ECS36B_JSONCPP_ */
}
#ifdef _ECS36B_JSONCPP_
inline Json::Value CategoryFineTune::events(const std::string& fine_tune_id)
#else /* _ECS36B_JSONCPP_ */
inline Json CategoryFineTune::events(const std::string& fine_tune_id)
#endif /* _ECS36B_JSONCPP_ */
{
return openai_.get("fine-tunes/" + fine_tune_id + "/events");
}
#ifdef _ECS36B_JSONCPP_
inline Json::Value CategoryFineTune::del(const std::string& model)
#else /* _ECS36B_JSONCPP_ */
inline Json CategoryFineTune::del(const std::string& model)
#endif /* _ECS36B_JSONCPP_ */
{
return openai_.del("models/" + model);
}
#ifdef _ECS36B_JSONCPP_
inline Json::Value CategoryModeration::create(Json::Value input)
#else /* _ECS36B_JSONCPP_ */
inline Json CategoryModeration::create(Json input)
#endif /* _ECS36B_JSONCPP_ */
{
return openai_.post("moderations", input);
}
} // namespace _detail
// Public interface
using _detail::OpenAI;
// instance
using _detail::start;
using _detail::instance;
// Generic methods
using _detail::post;
using _detail::get;
// Helper categories access
using _detail::model;
using _detail::completion;
using _detail::edit;
using _detail::image;
using _detail::embedding;
using _detail::file;
using _detail::fineTune;
using _detail::moderation;
using _detail::chat;
using _detail::audio;
#ifdef _ECS36B_JSONCPP_
// should we do something here??
#else /* _ECS36B_JSONCPP_ */
using _detail::Json;
#endif /* _ECS36B_JSONCPP_ */
} // namespace openai
#endif // OPENAI_HPP_ |
import React from "react";
import { Container } from "../styles/Container";
import { Typography } from "../styles/Typography";
import css from "./NewsReport.module.css";
interface Props {
title: string;
description: string;
content: string;
image: string;
url: string;
}
export default function NewsReport({
title,
description,
content,
image,
url,
}: Props) {
return (
<Container className={css.cardBody}>
<Typography variant="h5">{title}</Typography>
<img src={image} alt={title} />
<Typography>{description}</Typography>
<a href={url} target="_blank" rel="noreferrer">
<Typography>Read more...</Typography>
</a>
</Container>
);
} |
package Geo::WebService::OpenCellID::measure;
use warnings;
use strict;
use base qw{Geo::WebService::OpenCellID::Base};
use Geo::WebService::OpenCellID::Response::measure::add;
our $VERSION = '0.03';
=head1 NAME
Geo::WebService::OpenCellID::measure - Perl API for the opencellid.org database
=head1 SYNOPSIS
use Geo::WebService::OpenCellID;
my $gwo=Geo::WebService::OpenCellID->new(key=>$apikey);
my $point=$gwo->measure->get(mcc=>$country,
mnc=>$network,
lac=>$locale,
cellid=>$cellid);
printf "Lat:%s, Lon:%s\n", $point->latlon;
=head1 DESCRIPTION
Perl Interface to the database at http://www.opencellid.org/
=head1 USAGE
=head1 METHODS
=head2 add
Returns a response object L<Geo::WebService::OpenCellID::Response::measure::add>.
my $response=$gwo->cell->add(key=>$myapikey,
lat=>$lat,
lon=>$lon,
mnc=>$mnc,
mcc=>$mcc,
lac=>$lac,
cellid=>$cellid,
measured_at=>$dt, #time format is not well defined
#use is optional
#suggest W3C e.g. 2009-02-28T07:25Z
);
<?xml version="1.0" encoding="UTF-8" ?>
<rsp cellid="126694" id="6121024" stat="ok">
<res>Measure added, id:6121024</res>
</rsp>
=cut
sub add {
my $self=shift;
return $self->parent->call("measure/add",
"Geo::WebService::OpenCellID::Response::measure::add",
@_);
}
=head1 BUGS
Submit to RT and email the Author
=head1 SUPPORT
Try the Author or Try 8motions.com
=head1 AUTHOR
Michael R. Davis
CPAN ID: MRDVT
STOP, LLC
domain=>michaelrdavis,tld=>com,account=>perl
http://www.stopllc.com/
=head1 COPYRIGHT
This program is free software; you can redistribute
it and/or modify it under the same terms as Perl itself.
The full text of the license can be found in the
LICENSE file included with this module.
=head1 SEE ALSO
=cut
1; |
<?php
namespace TYPO3\CMS\Frontend\Tests\Unit\Controller;
/***************************************************************
* Copyright notice
*
* (c) 2009-2011 Oliver Klee (typo3-coding@oliverklee.de)
* All rights reserved
*
* This script is part of the TYPO3 project. The TYPO3 project 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.
*
* The GNU General Public License can be found at
* http://www.gnu.org/copyleft/gpl.html.
*
* This script 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.
*
* This copyright notice MUST APPEAR in all copies of the script!
***************************************************************/
/**
* Testcase for TYPO3\CMS\Frontend\Controller\TypoScriptFrontendController
*
* @author Oliver Klee <typo3-coding@oliverklee.de>
*/
class TypoScriptFrontendControllerTest extends \TYPO3\CMS\Core\Tests\UnitTestCase {
/**
* @var \PHPUnit_Framework_MockObject_MockObject|\TYPO3\CMS\Core\Tests\AccessibleObjectInterface|\TYPO3\CMS\Frontend\Controller\TypoScriptFrontendController
*/
private $fixture;
public function setUp() {
$this->fixture = $this->getAccessibleMock('\\TYPO3\\CMS\\Frontend\\Controller\\TypoScriptFrontendController', array('dummy'), array(), '', FALSE);
$this->fixture->TYPO3_CONF_VARS = $GLOBALS['TYPO3_CONF_VARS'];
$this->fixture->TYPO3_CONF_VARS['SYS']['encryptionKey'] = '170928423746123078941623042360abceb12341234231';
}
public function tearDown() {
unset($this->fixture);
}
// Tests concerning rendering content
/**
* @test
*/
public function headerAndFooterMarkersAreReplacedDuringIntProcessing() {
$GLOBALS['TSFE'] = $this->setupTsfeMockForHeaderFooterReplacementCheck();
$GLOBALS['TSFE']->INTincScript();
$this->assertContains('headerData', $GLOBALS['TSFE']->content);
$this->assertContains('footerData', $GLOBALS['TSFE']->content);
}
/**
* This is the callback that mimics a USER_INT extension
*/
public function INTincScript_processCallback() {
$GLOBALS['TSFE']->additionalHeaderData[] = 'headerData';
$GLOBALS['TSFE']->additionalFooterData[] = 'footerData';
}
/**
* Setup a tslib_fe object only for testing the header and footer
* replacement during USER_INT rendering
*
* @return \PHPUnit_Framework_MockObject_MockObject
*/
protected function setupTsfeMockForHeaderFooterReplacementCheck() {
/** @var \PHPUnit_Framework_MockObject_MockObject|\TYPO3\CMS\Frontend\Controller\TypoScriptFrontendController $tsfe */
$tsfe = $this->getMock('TYPO3\\CMS\\Frontend\\Controller\\TypoScriptFrontendController', array(
'INTincScript_process',
'INTincScript_includeLibs',
'INTincScript_loadJSCode',
'setAbsRefPrefix'
), array(), '', FALSE);
$tsfe->expects($this->once())->method('INTincScript_process')->will($this->returnCallback(array($this, 'INTincScript_processCallback')));
$tsfe->content = file_get_contents(__DIR__ . '/Fixtures/renderedPage.html');
$tsfe->config['INTincScript_ext']['divKey'] = '679b52796e75d474ccbbed486b6837ab';
$tsfe->config['INTincScript'] = array('INT_SCRIPT.679b52796e75d474ccbbed486b6837ab' => array());
$GLOBALS['TT'] = new \TYPO3\CMS\Core\TimeTracker\NullTimeTracker();
return $tsfe;
}
// Tests concerning codeString
/**
* @test
*/
public function codeStringForNonEmptyStringReturns10CharacterHashAndCodedString() {
$this->assertRegExp('/^[0-9a-f]{10}:[a-zA-Z0-9+=\\/]+$/', $this->fixture->codeString('Hello world!'));
}
/**
* @test
*/
public function decodingCodedStringReturnsOriginalString() {
$clearText = 'Hello world!';
$this->assertEquals($clearText, $this->fixture->codeString($this->fixture->codeString($clearText), TRUE));
}
// Tests concerning sL
/**
* @test
*/
public function localizationReturnsUnchangedStringIfNotLocallangLabel() {
$string = uniqid();
$this->assertEquals($string, $this->fixture->sL($string));
}
// Tests concerning roundTripCryptString
/**
* @test
*/
public function roundTripCryptStringCreatesStringWithSameLengthAsInputString() {
$clearText = 'Hello world!';
$this->assertEquals(strlen($clearText), strlen($this->fixture->_callRef('roundTripCryptString', $clearText)));
}
/**
* @test
*/
public function roundTripCryptStringCreatesResultDifferentFromInputString() {
$clearText = 'Hello world!';
$this->assertNotEquals($clearText, $this->fixture->_callRef('roundTripCryptString', $clearText));
}
/**
* @test
*/
public function roundTripCryptStringAppliedTwoTimesReturnsOriginalString() {
$clearText = 'Hello world!';
$refValue = $this->fixture->_callRef('roundTripCryptString', $clearText);
$this->assertEquals($clearText, $this->fixture->_callRef('roundTripCryptString', $refValue));
}
/**
* @test
*/
public function isModifyPageIdTestCalled() {
$GLOBALS['TT'] = $this->getMock('TYPO3\\CMS\Core\\TimeTracker\\TimeTracker');
$this->fixture = $this->getMock(
'\\TYPO3\\CMS\\Frontend\\Controller\\TypoScriptFrontendController',
array(
'initUserGroups',
'setSysPageWhereClause',
'checkAndSetAlias',
'findDomainRecord',
'getPageAndRootlineWithDomain'
),
array(),
'',
FALSE
);
$this->fixture->page = array();
$pageRepository = $this->getMock('TYPO3\\CMS\\Frontend\\Page\\PageRepository');
\TYPO3\CMS\Core\Utility\GeneralUtility::addInstance('TYPO3\\CMS\\Frontend\\Page\\PageRepository', $pageRepository);
$initialId = rand(1, 500);
$expectedId = $initialId + 42;
$this->fixture->id = $initialId;
$this->fixture->TYPO3_CONF_VARS['SC_OPTIONS']['tslib/class.tslib_fe.php']['modifyPageId'][] = function($params, $frontendController) {
return $params['id'] + 42;
};
$this->fixture->fetch_the_id();
$this->assertSame($expectedId, $this->fixture->id);
}
/**
* @test
*/
public function translationOfRootLinesSetsTheTemplateRootLineToReversedVersionOfMainRootLine() {
$rootLine = array(
array('uid' => 1),
array('uid' => 2)
);
$pageContextMock = $this->getMock('TYPO3\\CMS\\Frontend\\Page\\PageRepository');
$templateServiceMock = $this->getMock('TYPO3\\CMS\\Core\\TypoScript\\TemplateService');
$pageContextMock
->expects($this->any())
->method('getRootline')
->will($this->returnValue($rootLine));
$this->fixture->_set('sys_page', $pageContextMock);
$this->fixture->_set('tmpl', $templateServiceMock);
$this->fixture->sys_language_uid = 1;
$this->fixture->rootLine = array();
$this->fixture->tmpl->rootLine = array();
$this->fixture->_call('updateRootLinesWithTranslations');
$this->assertSame($rootLine, $this->fixture->rootLine);
$this->assertSame(array_reverse($rootLine), $this->fixture->tmpl->rootLine);
}
}
?> |
package com.ujcms.commons.file;
import freemarker.template.Template;
import org.springframework.lang.Nullable;
import org.springframework.web.multipart.MultipartFile;
import java.awt.image.RenderedImage;
import java.io.File;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.List;
import java.util.Map;
/**
* 文件处理接口
*
* @author PONY
*/
public interface FileHandler {
String SET_READABLE_FAILED = "set file readable failed";
/**
* 根据 URL 地址获取文件名。
*
* @param url 文件的 URL 地址
* @return 去除前缀文件名
*/
@Nullable
default String getName(@Nullable String url) {
if (url != null && url.startsWith(getDisplayPrefix())) {
return url.substring(getDisplayPrefix().length());
}
return null;
}
/**
* 获取前缀
*
* @return 前缀
*/
String getDisplayPrefix();
/**
* 存储文件
*
* @param filename 文件名
* @param template 模板
* @param dataModel 模板数据
*/
void store(String filename, Template template, Map<String, Object> dataModel);
/**
* 存储文件
*
* @param filename 文件名
* @param multipart 上传文件
*/
void store(String filename, MultipartFile multipart);
/**
* 存储图片文件
*
* @param filename 文件名
* @param image 图片
* @param formatName 图片格式
*/
void store(String filename, RenderedImage image, String formatName);
/**
* 存储文件
*
* @param filename 文件名
* @param source 输入流。调用者需要自己负责关闭流
*/
void store(String filename, InputStream source);
/**
* 存储文件
*
* @param filename 文件名
* @param file 本地文件
*/
void store(String filename, File file);
/**
* 存储文件
*
* @param filename 文件名
* @param text 正文
*/
void store(String filename, String text);
/**
* 创建文件夹
*
* @param dir 文件夹
* @return 是否成功
*/
boolean mkdir(String dir);
/**
* 解压文件
*
* @param zipPart zip multipart 文件
* @param destDir 解压目录
* @param ignoredExtensions 需要忽略的扩展名
*/
void unzip(MultipartFile zipPart, String destDir, String... ignoredExtensions);
/**
* 压缩文件
*
* @param dir 需要压缩的文件夹
* @param names 需压缩的文件名
* @param out 压缩后的zip输出流
*/
void zip(String dir, String[] names, OutputStream out);
/**
* 重命名
*
* @param filename 源文件名
* @param to 目标文件
* @return 是否成功
*/
boolean rename(String filename, String to);
/**
* 移动文件
*
* @param filename 文件名
* @param destDir 目标文件夹
*/
void moveTo(String filename, String destDir);
/**
* 移动文件
*
* @param dir 待移动文件夹
* @param names 待移动文件
* @param destDir 目标文件夹
*/
void moveTo(String dir, String[] names, String destDir);
/**
* 文件是否存在,且不是文件夹
*
* @param filename 文件名
* @return 是否操作
*/
boolean exist(String filename);
/**
* 获取本地文件
*
* @param filename 文件名
* @return 本地文件。文件不存在时,返回null。
*/
@Nullable
File getFile(String filename);
/**
* 获取WebFile
*
* @param filename 文件名
* @return 本地文件。文件不存在时,返回null。
*/
@Nullable
WebFile getWebFile(String filename);
/**
* 写入输出流
*
* @param filename 文件名
* @param out 输入流
*/
void writeOutputStream(String filename, OutputStream out);
/**
* 复制。可以复制文件,也可以文件夹
*
* @param src 源文件
* @param dest 目标文件
*/
void copy(String src, String dest);
/**
* 复制
*
* @param dir 待复制文件夹
* @param names 待复制文件
* @param destDir 目标文件夹
*/
void copy(String dir, String[] names, String destDir);
/**
* 删除文件及上级空文件夹
*
* @param filename 文件名
* @return 是否删除成功
*/
boolean deleteFileAndEmptyParentDir(String filename);
/**
* 删除文件
*
* @param filename 文件名
* @return 是否删除成功
*/
boolean deleteFile(String filename);
/**
* 删除文件夹
*
* @param directory 文件夹
* @return 是否删除成功
*/
boolean deleteDirectory(String directory);
/**
* 列出文件列表
*
* @param path 路径
* @return 文件列表
*/
default List<WebFile> listFiles(String path) {
return listFiles(path, file -> true);
}
/**
* 搜索文件列表
*
* @param path 路径
* @param search 搜索关键字
* @return 文件列表
*/
default List<WebFile> listFiles(String path, String search) {
return listFiles(path, new SearchWebFileFilter(search));
}
/**
* 列出文件列表
*
* @param path 路径
* @param filter 过滤器
* @return 文件列表
*/
List<WebFile> listFiles(String path, WebFileFilter filter);
} |
import type { Meta, StoryObj } from '@storybook/react'
import { Input } from '@/components/ui/input/input'
const meta = {
component: Input,
tags: ['autodocs'],
title: 'Components/Input',
} satisfies Meta<typeof Input>
export default meta
type Story = StoryObj<typeof meta>
export const Text: Story = {
args: {
label: 'Label',
placeholder: 'Placeholder',
},
}
export const Password: Story = {
args: {
label: 'Label',
placeholder: 'Placeholder',
type: 'password',
},
}
export const Search: Story = {
args: {
label: 'Label',
placeholder: 'Placeholder',
type: 'search',
},
}
export const Disabled: Story = {
args: {
disabled: true,
label: 'Label',
placeholder: 'Placeholder',
type: 'text',
},
}
export const Error: Story = {
args: {
errorMessage: 'ErrorMessage',
label: 'Label',
placeholder: 'Placeholder',
type: 'text',
},
} |
import Switch from "react-switch";
import React, { useMemo, useState } from "react";
import { Link } from "react-router-dom";
import { bytesToFileSize } from "../util/fileSize";
import { toast } from "react-toastify";
import Button from "./util/Button";
import { DownloadDetails } from "../../models/api";
interface PropTypes {
result: DownloadDetails;
}
export const DownloadSettings = ({ result }: PropTypes) => {
const [force, setForce] = useState(false);
const [collection, setCollection] = useState(false);
const [collectionName, setCollectionName] = useState("");
const download = () => {
toast.success(`Download started!`);
window.electron.startDownload(force, collectionName)
};
const downloadDisabled = useMemo(() => {
return collection && (collectionName === "")
}, [collection, collectionName])
const fileSize = useMemo(() => {
return bytesToFileSize(force ? result.totalSizeForce : result.totalSize)
}, [force, result.totalSizeForce, result.totalSize])
return (
<div className="flex flex-col gap-4">
<span className="font-bold text-lg dark:text-white">Download</span>
<div className="flex flex-col gap-1">
<span className="font-medium">Summary</span>
<div className="flex flex-col gap-0">
<span>
{result.beatmaps} Beatmaps ({result.setsForce} Beatmap Sets)
</span>
<span>
{force ? result.setsForce : result.sets} Sets to download
</span>
<span>Total Size: {fileSize}</span>
</div>
</div>
<div className="flex flex-col gap-1">
<span className="font-medium">Settings</span>
<div className="flex flex-col gap-2">
<div className="flex items-center gap-2">
<span>Force Download All Maps</span>
<Switch checked={force} onChange={(e) => setForce(e)} />
</div>
<div className="flex items-center gap-2">
<span>Create Collection</span>
<Switch checked={collection} onChange={(e) => setCollection(e)} />
{collection && (
<input
className="input-height p-2 w-40 border-gray-300 border rounded focus:outline-blue-500"
placeholder="Name"
value={collectionName}
onChange={(e) => setCollectionName(e.target.value)}
/>
)}
</div>
</div>
</div>
<div className="flex items-center">
<Link className={`${downloadDisabled ? 'pointer-events-none' : ''}`} to="/downloads">
<Button color="green" onClick={download} disabled={downloadDisabled}>
Download
</Button>
</Link>
{downloadDisabled && (
<span className="text-red-500 text-sm ml-4">
Collection name cannot be empty
</span>
)}
</div>
</div>
);
}; |
let currentPlayer = "x";
let winOptions = [];
let winner = null;
let fullSquares = 0;
let gameBoardState;
let $gameStateContainer;
let $currentPlayerContainer;
const logCurrentBoardState = () => {
const logValues = [];
gameBoardState.forEach((row) => {
const rowValues = [];
row.forEach(($space) => {
rowValues.push(getSpaceValue($space));
});
logValues.push(` ${rowValues.join(" | ")} `);
});
console.log("Current Board State:");
console.log(logValues.join("\n-----------\n"));
};
const updateCurrentPlayer = () => {
currentPlayer = currentPlayer === "x" ? "o" : "x";
updateCurrentPlayerMsg();
};
const isStalemate = () => fullSquares === 9;
const isGameOver = () => isStalemate() || !!winner;
const getSpaceValue = ($space) => $space.dataset.value;
const resetSpaceValue = ($space) => {
$space.dataset.value = " ";
$space.firstElementChild.innerHTML = "";
};
const showNewGameState = (msg = "", className = "") => {
$gameStateContainer.className = className;
$gameStateContainer.innerHTML = msg;
};
const showNewGameError = (msg) => {
showNewGameState(msg, "error");
};
const updateCurrentPlayerMsg = () => ($currentPlayerContainer.innerHTML = `${currentPlayer}, it's your turn!`);
const buildWinOptions = () => {
let wins = [];
const diagWin = [];
for (let x = 0; x < 3; x++) {
const rowWin = [];
const colWin = [];
for (let y = 0; y < 3; y++) {
rowWin.push([x, y]);
colWin.push([y, x]);
}
diagWin.push([x, x]);
wins.push(rowWin);
wins.push(colWin);
}
return [
...wins,
diagWin,
[
[2, 0],
[1, 1],
[0, 2],
],
];
};
const isWin = () => {
let isWin = false;
winOptions.forEach((winSet) => {
let points = 0;
winSet.forEach((spaceCoordinates) => {
const x = spaceCoordinates[0];
const y = spaceCoordinates[1];
const $space = gameBoardState[x][y];
const spaceValue = getSpaceValue($space);
if (spaceValue !== currentPlayer) {
return;
// not a winner
}
points++;
});
if (points === 3) {
isWin = true;
return;
}
});
return isWin;
};
const checkForWin = () => {
const winState = isWin();
if (winState === true) {
showNewGameState(`Congratulations player ${currentPlayer}, you've won the game!`, "success");
winner = currentPlayer;
} else if (fullSquares === 9) {
showNewGameState("Stalemate!");
}
return winState;
};
const resetGame = () => {
winner = null;
currentPlayer = "x";
fullSquares = 0;
showNewGameState();
updateCurrentPlayerMsg();
for (let row = 0; row < 3; row++) {
for (let col = 0; col < 3; col++) {
resetSpaceValue(gameBoardState[row][col]);
}
}
};
const onSpaceClick = ($space) => {
if (isGameOver()) {
console.log("game is over");
if (confirm("The game is already over, do you want to start over?")) {
resetGame();
}
return;
}
const currentValue = getSpaceValue($space);
if (currentValue !== " ") {
const msg = "Sorry this space is already taken, try another";
console.log(msg);
showNewGameError(msg);
return;
}
$space.dataset.value = currentPlayer;
$space.firstElementChild.innerHTML = currentPlayer;
logCurrentBoardState();
showNewGameState();
fullSquares++;
const isWin = checkForWin();
if (isWin || isStalemate()) {
return;
}
updateCurrentPlayer();
};
const createSpace = () => {
const $space = document.createElement("div");
$space.className = "game-space";
$space.dataset.value = " ";
const $spaceButton = document.createElement("button");
$spaceButton.setAttribute("type", "button");
$spaceButton.addEventListener("click", () => onSpaceClick($space));
$space.appendChild($spaceButton);
return $space;
};
const buildArray = (builderFn, length = 3) => {
const array = [];
for (let i = 0; i < length; i++) {
array.push(builderFn());
}
return array;
};
const buildBoardRow = ($container) => {
const spaceArray = buildArray(createSpace);
const $row = document.createElement("div");
$row.className = "game-row";
$container.appendChild($row);
spaceArray.forEach(($space) => {
$row.appendChild($space);
});
return spaceArray;
};
const buildInitialGameBoard = (gameBoardId) => {
const $gameBoardContainer = document.getElementById(gameBoardId);
const rows = buildArray(() => buildBoardRow($gameBoardContainer));
return rows;
};
const initClearButton = () => {
document.getElementById("clear-board").addEventListener("click", resetGame);
};
document.body.onload = () => {
$gameStateContainer = document.getElementById("game-state");
$currentPlayerContainer = document.getElementById("current-player");
initClearButton("clear-board");
winOptions = buildWinOptions();
gameBoardState = buildInitialGameBoard("game-board");
}; |
package com.example.demo.servlet;
import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Part;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.nio.file.Files;
import java.nio.file.Paths;
@WebServlet("/upload-file")
@MultipartConfig
public class UploadFileServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
resp.setContentType("text/html");
resp.getWriter().write("<html><body>");
resp.getWriter().write("<form action='upload-file' method='post' enctype='multipart/form-data'>");
resp.getWriter().write("<input type='file' name='file' /><br />");
resp.getWriter().write("<input type='submit' value='Upload File' />");
resp.getWriter().write("</form>");
resp.getWriter().write("</body></html>");
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
String uploadDir = "F:\\fpt\\java\\upload";
for (Part part : req.getParts()) {
String fileName = getSubmittedFileName(part);
if (fileName != null) {
String filePath = uploadDir + File.separator + fileName;
try (InputStream input = part.getInputStream()) {
Files.copy(input, Paths.get(filePath));
}
}
}
resp.setContentType("text/html");
resp.getWriter().write("<html><body>");
resp.getWriter().write("File uploaded successfully!");
resp.getWriter().write("</body></html>");
}
private String getSubmittedFileName(Part part) {
for (String cd : part.getHeader("content-disposition").split(";")) {
if (cd.trim().startsWith("filename")) {
String fileName = cd.substring(cd.indexOf('=') + 1).trim().replace("\"", "");
if (!fileName.isEmpty()) {
return fileName;
}
}
}
return null;
}
} |
<template>
<nav class="flex" aria-label="Breadcrumb">
<ol role="list" class="flex items-center space-x-4">
<li>
<div>
<Link :href="route('home')" class="text-gray-400 hover:text-gray-500">
<HomeIcon class="flex-shrink-0 h-5 w-5" aria-hidden="true" />
<span class="sr-only">Home</span>
</Link>
</div>
</li>
<li v-for="page in path" :key="page.name">
<div class="flex items-center">
<ChevronRightIcon class="flex-shrink-0 h-5 w-5 text-gray-400" aria-hidden="true" />
<Link :href="page.href" class="ml-4 text-sm font-medium text-gray-500 hover:text-gray-700" :aria-current="page.current ? 'page' : undefined">
{{ page.name }}
</Link>
</div>
</li>
</ol>
</nav>
</template>
<script>
import { ChevronRightIcon, HomeIcon } from '@heroicons/vue/solid'
import { Head, Link } from '@inertiajs/inertia-vue3'
const AdminRoute = { name: 'Admin', href: '/admin/dashboard', current: false };
const UserRoute = { name: 'User', href: '/user/dashboard', current: false };
const ProfileRoute = { name: 'Profile', href: '/profile', current: false };
const breadcrumbs = {
AdminDashboard: [AdminRoute, { name: 'Dashboard', href: '/admin/dashboard', current: true }],
AdminReviews: [AdminRoute, { name: 'Reviews', href: '/admin/reviews', current: true }],
AdminThings: [AdminRoute, { name: 'Things', href: '/admin/things', current: true }],
AdminOrganizations: [AdminRoute, { name: 'Organizations', href: '/admin/organizations', current: true }],
AdminOrganizationsCreate: [AdminRoute, { name: 'Organizations', href: '/admin/organizations', current: false}, { name: 'Create', href: '/admin/organizations/create', current: true }],
AdminUsers: [AdminRoute, { name: 'Users', href: '/admin/users', current: true }],
UserDashboard: [UserRoute, { name: "Dashboard", href: "/user/dashboard", current: true }],
UserThings: [UserRoute, { name: "Things", href: "/user/things", current: true }],
UserThingsCreate: [UserRoute, { name: "Things", href: "/user/things", current: false }, { name: 'Create', href: '/user/things/create', current: true}],
UserReviews: [UserRoute, { name: "Reviews", href: "/user/reviews", current: true }],
UserReviewsCreate: [UserRoute, { name: "Reviews", href: "/user/reviews", current: false }, { name: 'Create', href: '/user/reviews/create', current: true}],
UserProfile: [UserRoute, { name: "Profile", href: "/user/profile", current: true }],
};
export default {
props: {
name: String,
},
components: {
ChevronRightIcon,
HomeIcon,
Link,
},
data() {
return {
path: breadcrumbs[this.name]
}
},
}
</script> |
package com.webank.wedatasphere.exchangis.job.server.builder.transform.mappings;
import com.webank.wedatasphere.exchangis.datasource.core.utils.Json;
import com.webank.wedatasphere.exchangis.job.domain.params.JobParamDefine;
import com.webank.wedatasphere.exchangis.job.domain.params.JobParams;
import com.webank.wedatasphere.exchangis.job.server.builder.JobParamConstraints;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
/**
* Elastic search datax mapping
*/
public class EsDataxParamsMapping extends AbstractExchangisJobParamsMapping{
private static final Logger LOG = LoggerFactory.getLogger(EsDataxParamsMapping.class);
/**
* Elastic search urls
*/
private static final JobParamDefine<String> ELASTIC_URLS = JobParams.define("elasticUrls", "elasticUrls", urls -> {
List<String> elasticUrls = Json.fromJson(urls, List.class, String.class);
if (Objects.nonNull(elasticUrls)){
return StringUtils.join(elasticUrls, ",");
}
return null;
}, String.class);
/**
* Index name
*/
private static final JobParamDefine<String> INDEX = JobParams.define("index", JobParamConstraints.DATABASE);
/**
* Index type
*/
private static final JobParamDefine<String> TYPE = JobParams.define("type", JobParamConstraints.TABLE);
/**
* If in security connection
*/
private static final JobParamDefine<String> SECURE = JobParams.define("secure");
/**
* Max merge count
*/
private static final JobParamDefine<Map<String, Object>> SETTINGS = JobParams.define("settings",
() -> {
Map<String, Object> settings = new HashMap<>();
settings.put("index.merge.scheduler.max_merge_count", 100);
return settings;
});
/**
* Clean up
*/
private static final JobParamDefine<String> CLEANUP = JobParams.define("cleanUp", () -> "false");
/**
* Max pool size
*/
private static final JobParamDefine<String> CLIENT_MAX_POOL_SIZE = JobParams.define("clientConfig.maxPoolSize", () -> "1");
/**
* Socket time out
*/
private static final JobParamDefine<String> CLIENT_SOCK_TIMEOUT = JobParams.define("clientConfig.sockTimeout", () -> "60000");
/**
* Connection timeout
*/
private static final JobParamDefine<String> CLIENT_CONN_TIMEOUT = JobParams.define("clientConfig.connTimeout", () -> "60000");
/**
* Timeout
*/
private static final JobParamDefine<String> CLIENT_TIMEOUT = JobParams.define("clientConfig.timeout", () -> "60000");
/**
* Compress
*/
private static final JobParamDefine<String> CLIENT_COMPRESS = JobParams.define("clientConfig.compress", () -> "true");
@Override
public String dataSourceType() {
return "elasticsearch";
}
@Override
public boolean acceptEngine(String engineType) {
return "datax".equalsIgnoreCase(engineType);
}
@Override
public JobParamDefine<?>[] sourceMappings() {
return new JobParamDefine[0];
}
@Override
public JobParamDefine<?>[] sinkMappings() {
return new JobParamDefine[]{USERNAME, PASSWORD, ELASTIC_URLS, INDEX, TYPE, SECURE,
SETTINGS, CLEANUP, CLIENT_MAX_POOL_SIZE, CLIENT_SOCK_TIMEOUT, CLIENT_CONN_TIMEOUT,
CLIENT_TIMEOUT, CLIENT_COMPRESS
};
}
} |
/*
* 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.
*/
/**
* @author Vadim L. Bogdanov
*/
package javax.swing;
import java.awt.Color;
import java.awt.Component;
import java.awt.Rectangle;
import java.awt.event.KeyEvent;
import java.awt.event.MouseEvent;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import java.util.Arrays;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
import javax.swing.plaf.ComponentUI;
import javax.swing.plaf.UIResource;
import javax.swing.plaf.basic.BasicIconFactory;
import javax.swing.plaf.basic.BasicTabbedPaneUI;
public class JTabbedPaneTest extends SwingTestCase {
private class MyChangeListener implements ChangeListener {
public boolean eventFired;
public ChangeEvent event;
public void stateChanged(final ChangeEvent e) {
eventFired = true;
event = e;
}
}
private class MyPropertyChangeListener implements PropertyChangeListener {
public boolean eventFired;
public void propertyChange(final PropertyChangeEvent event) {
eventFired = true;
}
}
private static Icon someIcon = BasicIconFactory.createEmptyFrameIcon();
private String tabTitle1 = "tab1";
private Icon tabIcon = null;
private JComponent tabComponent1 = new JPanel();
private String tabTip1 = "tip1";
private int tabIndex1 = 0;
private String tabTitle2 = "tab2";
private JComponent tabComponent2 = new JPanel();
private String tabTip2 = "tip2";
private JComponent tabComponent3 = new JPanel();
private JTabbedPane tabbed;
public JTabbedPaneTest(final String name) {
super(name);
}
/*
* @see TestCase#setUp()
*/
@Override
protected void setUp() throws Exception {
super.setUp();
tabbed = new JTabbedPane();
tabbed.setSize(100, 50);
tabbed.insertTab(tabTitle1, tabIcon, tabComponent1, tabTip1, tabIndex1);
tabbed.insertTab(tabTitle2, tabIcon, tabComponent2, tabTip2, tabIndex1);
tabbed.insertTab(tabTitle1, tabIcon, tabComponent3, tabTip1, 0);
}
/*
* @see TestCase#tearDown()
*/
@Override
protected void tearDown() throws Exception {
super.tearDown();
}
public void testRemoveAll() {
tabbed.removeAll();
assertEquals("removed tabs", 0, tabbed.getTabCount());
assertEquals("removed components", 0, tabbed.getComponentCount());
assertEquals("no selected component", -1, tabbed.getSelectedIndex());
}
public void testUpdateUI() {
tabbed.updateUI();
ComponentUI ui1 = tabbed.getUI();
ComponentUI ui2 = UIManager.getUI(tabbed);
// at least names of classes must be the same
assertEquals(ui2.getClass().getName(), ui1.getClass().getName());
}
public void testGetTabCount() {
assertEquals(3, tabbed.getTabCount());
}
public void testGetTabRunCount() {
assertEquals(tabbed.getUI().getTabRunCount(tabbed), tabbed.getTabRunCount());
tabbed.setUI(null);
assertEquals(0, tabbed.getTabRunCount());
}
public void testFireStateChanged() {
MyChangeListener l = new MyChangeListener();
tabbed.addChangeListener(l);
tabbed.fireStateChanged();
assertTrue(l.eventFired);
assertSame("source", tabbed, l.event.getSource());
}
public void testJTabbedPane() {
tabbed = new JTabbedPane();
assertEquals("placement", SwingConstants.TOP, tabbed.getTabPlacement());
assertEquals("tabLayout", JTabbedPane.WRAP_TAB_LAYOUT, tabbed.getTabLayoutPolicy());
assertTrue("ui != null", tabbed.getUI() != null);
assertEquals("empty", 0, tabbed.getTabCount());
}
public void testJTabbedPaneint() {
tabbed = new JTabbedPane(SwingConstants.BOTTOM);
assertEquals("placement", SwingConstants.BOTTOM, tabbed.getTabPlacement());
assertEquals("tabLayout", JTabbedPane.WRAP_TAB_LAYOUT, tabbed.getTabLayoutPolicy());
}
public void testJTabbedPaneintint() {
tabbed = new JTabbedPane(SwingConstants.RIGHT, JTabbedPane.SCROLL_TAB_LAYOUT);
assertEquals("placement", SwingConstants.RIGHT, tabbed.getTabPlacement());
assertEquals("tabLayout", JTabbedPane.SCROLL_TAB_LAYOUT, tabbed.getTabLayoutPolicy());
}
public void testRemoveTabAt() {
int oldTabCount = tabbed.getTabCount();
tabbed.removeTabAt(tabbed.indexOfComponent(tabComponent3));
assertFalse("removed", tabbed.isAncestorOf(tabComponent3));
assertTrue("visible", tabComponent3.isVisible());
assertEquals("count -= 1", oldTabCount - 1, tabbed.getTabCount());
}
/*
* Class under test for void remove(Component)
*/
public void testRemoveComponent() {
int oldTabCount = tabbed.getTabCount();
tabbed.remove(new JLabel());
assertEquals("count didn't change", oldTabCount, tabbed.getTabCount());
tabbed.remove((Component) null);
assertEquals("count didn't change", oldTabCount, tabbed.getTabCount());
tabbed.remove(tabComponent3);
assertFalse("removed", tabbed.isAncestorOf(tabComponent3));
assertTrue("visible", tabComponent3.isVisible());
assertEquals("count -= 1", oldTabCount - 1, tabbed.getTabCount());
}
/*
* Class under test for void remove(int)
*/
public void testRemoveint() {
int oldTabCount = tabbed.getTabCount();
tabbed.remove(tabbed.indexOfComponent(tabComponent3));
assertFalse("removed", tabbed.isAncestorOf(tabComponent3));
assertTrue("visible", tabComponent3.isVisible());
assertEquals("count -= 1", oldTabCount - 1, tabbed.getTabCount());
}
public void testSetGetSelectedIndex() {
assertEquals("0 by default", 2, tabbed.getSelectedIndex());
assertFalse("invisible", tabbed.getComponentAt(1).isVisible());
tabbed.setSelectedIndex(1);
assertFalse("invisible", tabbed.getComponentAt(0).isVisible());
assertEquals("set to 1", 1, tabbed.getSelectedIndex());
assertEquals("set in model", 1, tabbed.getModel().getSelectedIndex());
if (isHarmony()) {
assertTrue("visible", tabbed.getSelectedComponent().isVisible());
}
boolean caught = false;
try {
tabbed.setSelectedIndex(100);
} catch (IndexOutOfBoundsException e) {
caught = true;
}
assertTrue("caught", caught);
tabbed = new JTabbedPane();
assertEquals("no selection", -1, tabbed.getSelectedIndex());
}
public void testSetGetTabLayoutPolicy() {
assertEquals("default", JTabbedPane.WRAP_TAB_LAYOUT, tabbed.getTabLayoutPolicy());
MyPropertyChangeListener l = new MyPropertyChangeListener();
tabbed.addPropertyChangeListener("tabLayoutPolicy", l);
tabbed.setTabLayoutPolicy(JTabbedPane.SCROLL_TAB_LAYOUT);
assertEquals("set", JTabbedPane.SCROLL_TAB_LAYOUT, tabbed.getTabLayoutPolicy());
assertTrue(l.eventFired);
boolean caught = false;
try {
tabbed.setTabLayoutPolicy(-4);
} catch (IllegalArgumentException e) {
caught = true;
}
assertTrue("IllegalArgumentException", caught);
}
public void testSetGetTabPlacement() {
assertEquals("default", SwingConstants.TOP, tabbed.getTabPlacement());
MyPropertyChangeListener l = new MyPropertyChangeListener();
tabbed.addPropertyChangeListener("tabPlacement", l);
tabbed.setTabPlacement(SwingConstants.LEFT);
assertEquals("set", SwingConstants.LEFT, tabbed.getTabPlacement());
assertTrue(l.eventFired);
boolean caught = false;
try {
tabbed.setTabPlacement(-4);
} catch (IllegalArgumentException e) {
caught = true;
}
assertTrue("IllegalArgumentException", caught);
}
public void testIndexAtLocation() {
int x = 2;
int y = 2;
assertEquals(tabbed.getUI().tabForCoordinate(tabbed, x, y), tabbed
.indexAtLocation(x, y));
tabbed.setUI(null);
assertEquals(-1, tabbed.indexAtLocation(x, y));
}
public void testSetGetDisplayedMnemonicIndexAt() {
assertEquals(-1, tabbed.getDisplayedMnemonicIndexAt(0));
tabbed.setDisplayedMnemonicIndexAt(0, 1);
assertEquals(1, tabbed.getDisplayedMnemonicIndexAt(0));
}
public void testSetGetMnemonicAt() {
assertEquals(-1, tabbed.getMnemonicAt(1));
tabbed.setMnemonicAt(1, KeyEvent.VK_X);
assertEquals(KeyEvent.VK_X, tabbed.getMnemonicAt(1));
}
public void testSetIsEnabledAt() {
assertTrue("by default", tabbed.isEnabledAt(1));
tabbed.setEnabledAt(1, false);
assertFalse("set to false", tabbed.isEnabledAt(1));
tabbed.setEnabledAt(1, true);
assertTrue("set to true", tabbed.isEnabledAt(1));
}
/*
* Class under test for Component add(Component)
*/
public void testAddComponent() {
JComponent comp = new JLabel("label");
comp.setName("label");
Component result = tabbed.add(comp);
assertEquals("result", comp, result);
assertEquals("index", 3, tabbed.indexOfComponent(comp));
assertEquals("title", "label", tabbed.getTitleAt(3));
assertNull("tip", tabbed.getToolTipTextAt(3));
class UIResourceButton extends JButton implements UIResource {
private static final long serialVersionUID = 1L;
}
int tabCount = tabbed.getTabCount();
comp = new UIResourceButton();
result = tabbed.add(comp);
assertSame(comp, result);
assertEquals("no new tab for UIResource", tabCount, tabbed.getTabCount());
}
/*
* Class under test for Component add(Component, int)
*/
public void testAddComponentint() {
JComponent comp = new JLabel("label");
comp.setName("label");
Component result = tabbed.add(comp, 2);
assertEquals("result", comp, result);
assertEquals("index", 2, tabbed.indexOfComponent(comp));
assertEquals("title", "label", tabbed.getTitleAt(2));
assertNull("tip", tabbed.getToolTipTextAt(2));
}
/*
* Class under test for void add(Component, Object)
*/
public void testAddComponentObject() {
int index = 3;
JComponent comp = new JLabel("label");
comp.setName("labelName");
Object constraints = "label";
tabbed.add(comp, constraints);
assertEquals("index", index, tabbed.indexOfComponent(comp));
assertEquals("title", constraints, tabbed.getTitleAt(index));
tabbed.remove(comp);
comp = new JLabel("label");
comp.setName("labelName");
constraints = someIcon;
tabbed.add(comp, constraints);
assertEquals("title", "", tabbed.getTitleAt(index));
assertEquals("icon", constraints, tabbed.getIconAt(index));
tabbed.remove(comp);
comp = new JLabel("label");
comp.setName("labelName");
constraints = new Integer(3); // just some Object
tabbed.add(comp, constraints);
assertEquals("title", "labelName", tabbed.getTitleAt(tabbed.indexOfComponent(comp)));
assertNull("icon", tabbed.getIconAt(tabbed.indexOfComponent(comp)));
tabbed.remove(comp);
}
/*
* Class under test for void add(Component, Object, int)
*/
public void testAddComponentObjectint() {
int index = 2;
JComponent comp = new JLabel("label");
comp.setName("labelName");
Object constraints = "label";
tabbed.add(comp, constraints, index);
assertEquals("index", index, tabbed.indexOfComponent(comp));
assertEquals("title", constraints, tabbed.getTitleAt(index));
tabbed.remove(comp);
comp = new JLabel("label");
comp.setName("labelName");
constraints = BasicIconFactory.createEmptyFrameIcon(); // just some icon
tabbed.add(comp, constraints, index);
assertEquals("title", "", tabbed.getTitleAt(index));
assertEquals("icon", constraints, tabbed.getIconAt(index));
tabbed.remove(comp);
comp = new JLabel("label");
comp.setName("labelName");
constraints = new Integer(3); // just some Object
tabbed.add(comp, constraints, 1);
if (BasicSwingTestCase.isHarmony()) {
assertEquals("title", "labelName", tabbed.getTitleAt(tabbed.indexOfComponent(comp)));
}
assertNull("icon", tabbed.getIconAt(tabbed.indexOfComponent(comp)));
tabbed.remove(comp);
}
/*
* Class under test for Component add(String, Component)
*/
public void testAddStringComponent() {
JComponent comp = new JLabel("label");
Component result = tabbed.add("label", comp);
assertEquals("result", comp, result);
assertEquals("index", 3, tabbed.indexOfComponent(comp));
assertEquals("title", "label", tabbed.getTitleAt(3));
assertNull("tip", tabbed.getToolTipTextAt(3));
}
/*
* Class under test for void addChangeListener(ChangeListener)
*/
public void testAddRemoveChangeListener() {
ChangeListener l = new MyChangeListener();
int len = tabbed.getChangeListeners().length;
tabbed.addChangeListener(l);
assertEquals("added", len + 1, tabbed.getChangeListeners().length);
tabbed.removeChangeListener(l);
assertEquals("removed", len, tabbed.getChangeListeners().length);
tabbed.addChangeListener(null);
assertEquals("adding null: no action", len, tabbed.getChangeListeners().length);
tabbed.removeChangeListener(null);
assertEquals("removing null: no action", len, tabbed.getChangeListeners().length);
}
/*
* Class under test for void addTab(String, Component)
*/
public void testAddTabStringComponent() {
JComponent comp = new JLabel("label");
tabbed.addTab("label", comp);
assertEquals("index", 3, tabbed.indexOfComponent(comp));
assertEquals("title", "label", tabbed.getTitleAt(3));
assertNull("tip", tabbed.getToolTipTextAt(3));
}
/*
* Class under test for void addTab(String, Icon, Component)
*/
public void testAddTabStringIconComponent() {
JComponent comp = new JLabel("label");
tabbed.addTab("label", someIcon, comp);
assertEquals("index", 3, tabbed.indexOfComponent(comp));
assertEquals("title", "label", tabbed.getTitleAt(3));
assertEquals("icon", someIcon, tabbed.getIconAt(3));
assertNull("tip", tabbed.getToolTipTextAt(3));
}
/*
* Class under test for void addTab(String, Icon, Component, String)
*/
public void testAddTabStringIconComponentString() {
JComponent comp = new JLabel("label");
tabbed.addTab("label", someIcon, comp, "tip");
assertEquals("index", 3, tabbed.indexOfComponent(comp));
assertEquals("title", "label", tabbed.getTitleAt(3));
assertEquals("icon", someIcon, tabbed.getIconAt(3));
assertEquals("tip", "tip", tabbed.getToolTipTextAt(3));
}
/*
* Class under test for ChangeListener createChangeListener()
*/
public void testCreateChangeListener() {
ChangeListener l1 = tabbed.createChangeListener();
assertNotNull("not null", l1);
assertNotSame("not same", l1, tabbed.changeListener);
}
/*
* Class under test for AccessibleContext getAccessibleContext()
*/
public void testGetAccessibleContext() {
assertTrue(tabbed.getAccessibleContext() instanceof JTabbedPane.AccessibleJTabbedPane);
}
/*
* Class under test for Rectangle getBoundsAt(int)
*/
public void testGetBoundsAt() {
assertEquals(tabbed.getBoundsAt(1), tabbed.getUI().getTabBounds(tabbed, 1));
tabbed.setUI(null);
assertNull(tabbed.getBoundsAt(1));
}
/*
* Class under test for ChangeListener[] getChangeListeners()
*/
public void testGetChangeListeners() {
tabbed.setUI(null);
assertEquals("empty array", 0, tabbed.getChangeListeners().length);
tabbed.addChangeListener(new MyChangeListener());
assertEquals("1 element", 1, tabbed.getChangeListeners().length);
}
/*
* Class under test for void setTitleAt(int, String)
*/
public void testSetTitleAt() {
String newTitle = "newTitle";
tabbed.setTitleAt(1, newTitle);
assertEquals("newTitle is set", newTitle, tabbed.getTitleAt(1));
boolean catched = false;
try {
tabbed.setTitleAt(-1, newTitle);
} catch (IndexOutOfBoundsException e) {
catched = true;
}
assertTrue("IndexOutOfBoundsException: index < 0", catched);
catched = false;
try {
tabbed.setTitleAt(tabbed.getTabCount(), newTitle);
} catch (IndexOutOfBoundsException e) {
catched = true;
}
assertTrue("IndexOutOfBoundsException: index >= tab count", catched);
}
/*
* Class under test for String getTitleAt(int)
*/
public void testGetTitleAt() {
assertEquals("title1", tabTitle1, tabbed.getTitleAt(0));
assertEquals("title2", tabTitle2, tabbed.getTitleAt(1));
assertEquals("title1_2", tabTitle1, tabbed.getTitleAt(2));
boolean catched = false;
try {
tabbed.getTitleAt(-1);
} catch (IndexOutOfBoundsException e) {
catched = true;
}
assertTrue("IndexOutOfBoundsException: index < 0", catched);
catched = false;
try {
tabbed.getTitleAt(tabbed.getTabCount());
} catch (IndexOutOfBoundsException e) {
catched = true;
}
assertTrue("IndexOutOfBoundsException: index >= tab count", catched);
}
/*
* Class under test for String getToolTipText(MouseEvent)
*/
public void testGetToolTipTextMouseEvent() {
Rectangle bounds = tabbed.getBoundsAt(1);
tabbed.setToolTipTextAt(1, "tooltip");
MouseEvent e = new MouseEvent(tabbed, MouseEvent.MOUSE_MOVED, 0L, 0, bounds.x + 1,
bounds.y + 1, 1, false);
assertEquals("tooltip", tabbed.getToolTipText(e));
e = new MouseEvent(tabbed, MouseEvent.MOUSE_MOVED, 0L, 0, Short.MAX_VALUE,
Short.MAX_VALUE, 1, false);
assertNull(tabbed.getToolTipText(e));
}
/*
* Class under test for String getUIClassID()
*/
public void testGetUIClassID() {
assertEquals("uiClassID", "TabbedPaneUI", tabbed.getUIClassID());
}
/*
* Class under test for int indexOfComponent(Component)
*/
public void testIndexOfComponent() {
assertEquals("index of null", -1, tabbed.indexOfComponent(null));
tabbed.setComponentAt(2, tabComponent1);
assertEquals("comp1", 2, tabbed.indexOfComponent(tabComponent1));
}
/*
* Class under test for int indexOfTab(Icon)
*/
public void testIndexOfTabIcon() {
Icon otherIcon = BasicIconFactory.getCheckBoxIcon();
assertEquals("index of null", 0, tabbed.indexOfTab((Icon) null));
tabbed.setIconAt(1, someIcon);
assertEquals(1, tabbed.indexOfTab(someIcon));
assertEquals("no icon", -1, tabbed.indexOfTab(otherIcon));
}
/*
* Class under test for int indexOfTab(String)
*/
public void testIndexOfTabString() {
assertEquals("index of null", -1, tabbed.indexOfTab((String) null));
tabbed.setTitleAt(1, "someTitle");
assertEquals(1, tabbed.indexOfTab("someTitle"));
assertEquals("no icon", -1, tabbed.indexOfTab("otherTitle"));
}
public void testInsertTab() {
tabbed.removeAll();
tabbed = new JTabbedPane();
assertEquals(-1, tabbed.getSelectedIndex());
tabbed.insertTab(tabTitle1, tabIcon, tabComponent1, tabTip1, 0);
assertEquals(0, tabbed.getSelectedIndex());
tabbed.insertTab(tabTitle2, tabIcon, tabComponent2, tabTip2, 0);
assertEquals(2, tabbed.getTabCount());
assertEquals(1, tabbed.getSelectedIndex());
assertSame(tabComponent1, tabbed.getComponent(0));
assertSame(tabComponent2, tabbed.getComponent(1));
assertSame(tabComponent2, tabbed.getComponentAt(0));
assertSame(tabComponent1, tabbed.getComponentAt(1));
assertEquals(1, tabbed.indexOfComponent(tabComponent1));
assertEquals(0, tabbed.indexOfComponent(tabComponent2));
assertEquals("title1", tabbed.getTitleAt(1), tabTitle1);
assertEquals("component1", tabbed.getComponentAt(1), tabComponent1);
assertEquals("tip1", tabbed.getToolTipTextAt(1), tabTip1);
if (isHarmony()) {
assertTrue("component1.isVisible()", tabComponent1.isVisible());
} else {
assertFalse("component1.isVisible()", tabComponent1.isVisible());
}
assertNotNull("background", tabbed.getBackgroundAt(1));
assertNotNull("foreground", tabbed.getForegroundAt(1));
assertEquals("title2", tabbed.getTitleAt(0), tabTitle2);
assertEquals("component2", tabbed.getComponentAt(0), tabComponent2);
assertEquals("tip2", tabbed.getToolTipTextAt(0), tabTip2);
assertFalse("component2.isVisible()", tabComponent2.isVisible());
tabbed.insertTab(tabTitle1, tabIcon, tabComponent3, tabTip1, 2);
assertSame(tabComponent1, tabbed.getComponent(0));
assertSame(tabComponent2, tabbed.getComponent(1));
assertSame(tabComponent3, tabbed.getComponent(2));
assertSame(tabComponent2, tabbed.getComponentAt(0));
assertSame(tabComponent1, tabbed.getComponentAt(1));
assertSame(tabComponent3, tabbed.getComponentAt(2));
assertEquals(1, tabbed.indexOfComponent(tabComponent1));
assertEquals(0, tabbed.indexOfComponent(tabComponent2));
assertEquals(2, tabbed.indexOfComponent(tabComponent3));
assertEquals(1, tabbed.getSelectedIndex());
assertEquals(3, tabbed.getTabCount());
assertFalse(tabComponent3.isVisible());
tabbed.insertTab(tabTitle1, tabIcon, tabComponent3, tabTip1, 0);
assertSame(tabComponent1, tabbed.getComponent(0));
assertSame(tabComponent2, tabbed.getComponent(1));
assertSame(tabComponent3, tabbed.getComponent(2));
assertSame(tabComponent3, tabbed.getComponentAt(0));
assertSame(tabComponent2, tabbed.getComponentAt(1));
assertSame(tabComponent1, tabbed.getComponentAt(2));
assertEquals(2, tabbed.indexOfComponent(tabComponent1));
assertEquals(1, tabbed.indexOfComponent(tabComponent2));
assertEquals(0, tabbed.indexOfComponent(tabComponent3));
assertEquals(2, tabbed.getSelectedIndex());
assertEquals(3, tabbed.getTabCount());
tabbed.insertTab(null, tabIcon, tabComponent3, tabTip1, 0);
assertSame(tabComponent1, tabbed.getComponent(0));
assertSame(tabComponent2, tabbed.getComponent(1));
assertSame(tabComponent3, tabbed.getComponent(2));
assertSame(tabComponent3, tabbed.getComponentAt(0));
assertSame(tabComponent2, tabbed.getComponentAt(1));
assertSame(tabComponent1, tabbed.getComponentAt(2));
assertEquals(2, tabbed.indexOfComponent(tabComponent1));
assertEquals(1, tabbed.indexOfComponent(tabComponent2));
assertEquals(0, tabbed.indexOfComponent(tabComponent3));
assertEquals(2, tabbed.getSelectedIndex());
assertEquals("tabCount == 2", 3, tabbed.getTabCount());
assertEquals("title is empty, not null", "", tabbed.getTitleAt(0));
JButton tabComponent4 = new JButton();
tabbed.insertTab(null, tabIcon, tabComponent4, tabTip1, 1);
assertSame(tabComponent1, tabbed.getComponent(0));
assertSame(tabComponent2, tabbed.getComponent(1));
assertSame(tabComponent3, tabbed.getComponent(2));
assertSame(tabComponent4, tabbed.getComponent(3));
assertSame(tabComponent3, tabbed.getComponentAt(0));
assertSame(tabComponent4, tabbed.getComponentAt(1));
assertSame(tabComponent2, tabbed.getComponentAt(2));
assertSame(tabComponent1, tabbed.getComponentAt(3));
assertEquals(3, tabbed.indexOfComponent(tabComponent1));
assertEquals(2, tabbed.indexOfComponent(tabComponent2));
assertEquals(1, tabbed.indexOfComponent(tabComponent4));
assertEquals(0, tabbed.indexOfComponent(tabComponent3));
assertEquals(3, tabbed.getSelectedIndex());
}
/*
* Class under test for String paramString()
*/
public void testParamString() {
String paramString = tabbed.paramString();
assertNotNull(paramString);
assertFalse("".equals(paramString));
}
/*
* Class under test for void setBackgroundAt(int, Color)
*/
public void testSetBackgroundAt() {
tabbed.setBackgroundAt(1, Color.RED);
assertEquals(Color.RED, tabbed.getBackgroundAt(1));
tabbed.setBackgroundAt(1, null);
assertEquals("not null", tabbed.getBackground(), tabbed.getBackgroundAt(1));
}
/*
* Class under test for Color getBackgroundAt(int)
*/
public void testGetBackgroundAt() {
assertTrue("instanceof UIResource", tabbed.getBackgroundAt(1) instanceof UIResource);
}
/*
* Class under test for void setForegroundAt(int, Color)
*/
public void testSetForegroundAt() {
tabbed.setForegroundAt(1, Color.RED);
assertEquals(Color.RED, tabbed.getForegroundAt(1));
tabbed.setForegroundAt(1, null);
assertEquals("not null", tabbed.getForeground(), tabbed.getForegroundAt(1));
}
/*
* Class under test for Color getForegroundAt(int)
*/
public void testGetForegroundAt() {
assertTrue("instanceof UIResource", tabbed.getForegroundAt(1) instanceof UIResource);
}
public void testSetGetComponentAt() {
JComponent newComp = new JLabel("new");
int tabCount = tabbed.getTabCount();
int index = tabbed.indexOfComponent(tabComponent2);
assertSame(tabComponent1, tabbed.getComponent(0));
assertSame(tabComponent2, tabbed.getComponent(1));
assertSame(tabComponent3, tabbed.getComponent(2));
assertSame(tabComponent3, tabbed.getComponentAt(0));
assertSame(tabComponent2, tabbed.getComponentAt(1));
assertSame(tabComponent1, tabbed.getComponentAt(2));
assertEquals(2, tabbed.indexOfComponent(tabComponent1));
assertEquals(1, tabbed.indexOfComponent(tabComponent2));
assertEquals(0, tabbed.indexOfComponent(tabComponent3));
tabbed.setComponentAt(index, newComp);
assertSame(tabComponent1, tabbed.getComponent(0));
assertSame(tabComponent3, tabbed.getComponent(1));
assertSame(newComp, tabbed.getComponent(2));
assertSame(tabComponent3, tabbed.getComponentAt(0));
assertSame(newComp, tabbed.getComponentAt(1));
assertSame(tabComponent1, tabbed.getComponentAt(2));
assertEquals(2, tabbed.indexOfComponent(tabComponent1));
assertEquals(1, tabbed.indexOfComponent(newComp));
assertEquals(0, tabbed.indexOfComponent(tabComponent3));
assertEquals(-1, tabbed.indexOfComponent(tabComponent2));
assertEquals("tabCount", tabCount, tabbed.getTabCount());
assertSame("component", newComp, tabbed.getComponentAt(index));
assertFalse("newComp is not visible", newComp.isVisible());
tabbed.setComponentAt(index, tabComponent3);
assertSame(tabComponent1, tabbed.getComponent(0));
assertSame(tabComponent3, tabbed.getComponent(1));
assertSame(tabComponent3, tabbed.getComponentAt(0));
assertSame(tabComponent1, tabbed.getComponentAt(1));
assertEquals(0, tabbed.indexOfComponent(tabComponent3));
assertEquals(1, tabbed.indexOfComponent(tabComponent1));
assertEquals("tabCount - 1", tabCount - 1, tabbed.getTabCount());
assertEquals("visibility", !BasicSwingTestCase.isHarmony(), tabComponent3.isVisible());
}
public void testSetGetDisabledIconAt() {
assertNull(tabbed.getDisabledIconAt(0));
tabbed.setDisabledIconAt(0, someIcon);
assertSame(someIcon, tabbed.getDisabledIconAt(0));
}
public void testSetGetIconAt() {
tabbed.setIconAt(1, someIcon);
assertEquals(someIcon, tabbed.getIconAt(1));
}
public void testSetGetModel() {
assertNotNull("default", tabbed.getModel());
PropertyChangeController cont = new PropertyChangeController();
tabbed.addPropertyChangeListener(cont);
DefaultSingleSelectionModel model = new DefaultSingleSelectionModel();
tabbed.setModel(model);
assertEquals("set", model, tabbed.getModel());
assertTrue("fired property change event", cont.isChanged("model"));
assertTrue("listener", Arrays.asList(
((DefaultSingleSelectionModel) tabbed.getModel()).getChangeListeners())
.contains(tabbed.changeListener));
// set model with another selected index, no state change event is fired
tabbed.setModel(null);
MyChangeListener changeListener = new MyChangeListener();
tabbed.addChangeListener(changeListener);
model.setSelectedIndex(2);
tabbed.setModel(model);
assertFalse(changeListener.eventFired);
}
public void testSetGetSelectedComponentComponent() {
tabbed.setSelectedComponent(tabComponent2);
assertSame(tabComponent2, tabbed.getSelectedComponent());
assertEquals(tabbed.indexOfComponent(tabComponent2), tabbed.getSelectedIndex());
boolean caught = false;
try {
tabbed.setSelectedComponent(new JLabel());
} catch (final IllegalArgumentException e) {
caught = true;
}
assertTrue(caught);
}
public void testSetGetToolTipTextAt() {
JComponent comp = new JLabel();
tabbed.add(comp);
int index = tabbed.indexOfComponent(comp);
assertNull("by default", tabbed.getToolTipTextAt(index));
tabbed.setToolTipTextAt(index, "newTip");
assertEquals("newTip", tabbed.getToolTipTextAt(index));
tabbed.setToolTipTextAt(index, null);
assertNull(tabbed.getToolTipTextAt(index));
}
public void testSetGetUI() {
BasicTabbedPaneUI ui = new BasicTabbedPaneUI();
tabbed.setUI(ui);
assertSame(ui, tabbed.getUI());
}
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.