text
stringlengths 184
4.48M
|
---|
// Distant Lands 2022.
using UnityEngine;
#if UNITY_EDITOR
using UnityEditor;
#endif
namespace DistantLands.Cozy.Data
{
[System.Serializable]
[CreateAssetMenu(menuName = "Distant Lands/Cozy/FX/Event FX", order = 361)]
public class EventFX : FXProfile
{
public CozyEventModule events;
public bool isPlaying;
public delegate void OnCall();
public event OnCall onCall;
public void RaiseOnCall()
{
onCall?.Invoke();
}
public delegate void OnEnd();
public event OnEnd onEnd;
public void RaiseOnEnd()
{
onEnd?.Invoke();
}
public void PlayEffect()
{
if (!isPlaying)
{
isPlaying = true;
onCall?.Invoke();
}
}
public override void PlayEffect(float weight)
{
if (weight > 0.5f)
PlayEffect();
else
StopEffect();
}
public void StopEffect()
{
if (isPlaying)
{
isPlaying = false;
onEnd?.Invoke();
}
}
public override bool InitializeEffect(CozyWeather weather)
{
base.InitializeEffect(weather);
if (!weatherSphere.GetModule<CozyEventModule>())
return false;
events = weatherSphere.GetModule<CozyEventModule>();
return true;
}
}
#if UNITY_EDITOR
[CustomEditor(typeof(EventFX))]
[CanEditMultipleObjects]
public class E_EventFX : E_FXProfile
{
public override void OnInspectorGUI()
{
serializedObject.Update();
EditorGUILayout.HelpBox("No other properties to adjust! Set events in the Cozy Event Module!", MessageType.Info);
serializedObject.ApplyModifiedProperties();
}
public override void RenderInWindow(Rect pos)
{
}
public override float GetLineHeight()
{
return 0;
}
}
#endif
}
|
package top.sharehome.demo03flow;
import java.util.concurrent.Executor;
import java.util.concurrent.Executors;
import java.util.concurrent.Flow;
import java.util.concurrent.SubmissionPublisher;
/**
* Flow示例代码
* 这里演示的是Reactive Streams规范的示例代码,它存在于Java9+版本JUC包下Flow类中。
* 这个类似于Kafka或者RabbitMQ这样的消息队列,在这个规范中有四个组件:
* 1、发布者(必要)
* 2、处理器(不必要,它本身就是一个发布者和订阅者的融合体)
* 3、订阅者(必要)
* 4、订阅关系(必要)
* 他们可以按照下面这个顺序进行工作流:
* 发布者 ==发布消息==> 缓冲区 ==取出消息==> 处理器 ==处理完后的消息==> 缓冲区 ==取出消息==> 订阅者
* 注意:以上的缓冲区为同一个缓冲区,该缓冲区由JMV自身维护,同时还维护着一个线程池;处理器和订阅者可以有多个,这样就预示着有多个订阅关系;
* 一直到这里就把Stream流这部分前置知识了解清楚了,从Lambda、stream、flow三部分中能够看出响应式编程的一些特点:
* 1、底层(内核上):基于数据缓冲队列+消息驱动模型+异步回调机制(事件驱动)
* 2、编码(形式上):流式编程+链式调用+声明式API
* 3、效果(形式上):优雅全异步+消息实时处理+高吞吐量+占用少量资源
*
* @author AntonyCheng
*/
public class FlowDemo {
/**
* 定义处理器类
* 由于处理器既是发布者,也是订阅者,Flow.Processor接口中就包含了Flow.Publisher和Flow.Subscriber中包含的方法;
* 所以继承SubmissionPublisher就是为了方便不再去考虑实现Flow.Publisher中的方法,以免自己写submit函数。
*
* @author AntonyCheng
*/
private static class Processor extends SubmissionPublisher<String> implements Flow.Processor<String, String> {
// 将订阅关系转变为变量,方便能够拿出发布者发布在缓存中的数据
private Flow.Subscription subscription;
private String processorCode;
Processor() {
}
Processor(String processorCode) {
this.processorCode = processorCode;
}
@Override
public void onSubscribe(Flow.Subscription subscription) {
System.out.println(Thread.currentThread() + " 处理器" + processorCode + "开始订阅:" + subscription);
// 向缓存请求一条数据以便于激活处理器
subscription.request(1);
this.subscription = subscription;
}
@Override
public void onNext(String item) {
System.out.println(Thread.currentThread() + " 处理器" + processorCode + "开始处理:" + item);
item = "p" + item;
submit(item);
// 每次操作完之后向缓存请求一条数据
subscription.request(1);
}
// 在接收到错误信号时
@Override
public void onError(Throwable throwable) {
System.out.println(Thread.currentThread() + " 处理器" + processorCode + "接收到错误信号:" + throwable);
}
// 在接收完成时
@Override
public void onComplete() {
System.out.println(Thread.currentThread() + " 处理器" + processorCode + "接收完成信息");
}
}
/**
* 方法入口
*
* @param args 参数
* @author AntonyCheng
*/
public static void main(String[] args) throws InterruptedException {
// 1、定义一个发布者
SubmissionPublisher<String> publisher = new SubmissionPublisher<String>();
// 2、定义两个处理器,在每个元素前面加一个"p"
Processor processor1 = new Processor("1");
Processor processor2 = new Processor("2");
// 3、定义两个订阅者:订阅数据
Flow.Subscriber<String> subscriber1 = new Flow.Subscriber<String>() {
// 将订阅关系转变为变量,方便能够拿出发布者发布在缓存中的数据
private Flow.Subscription subscription;
// 在订阅开始时要执行的回调
@Override
public void onSubscribe(Flow.Subscription subscription) {
System.out.println(Thread.currentThread() + " 订阅者1号开始订阅:" + subscription);
this.subscription = subscription;
// 向缓存请求一条数据以便于激活订阅者
subscription.request(1);
}
// 在下一个元素到达时,即接收到数据时
@Override
public void onNext(String item) {
System.out.println(Thread.currentThread() + " 订阅者1号接收到的消息:" + item);
if ("ppp-7".equals(item)) {
// 模拟取消订阅,当拿到"pp-7"时取消订阅
subscription.cancel();
} else {
// 每次操作完之后向缓存请求一条数据
subscription.request(1);
}
}
// 在接收到错误信号时
@Override
public void onError(Throwable throwable) {
System.out.println(Thread.currentThread() + " 订阅者1号接收到错误信号:" + throwable);
}
// 在接收完成时
@Override
public void onComplete() {
System.out.println(Thread.currentThread() + " 订阅者1号接收完成信息");
}
};
Flow.Subscriber<String> subscriber2 = new Flow.Subscriber<String>() {
// 将订阅关系转变为变量,方便能够拿出发布者发布在缓存中的数据
private Flow.Subscription subscription;
// 在订阅开始时要执行的回调
@Override
public void onSubscribe(Flow.Subscription subscription) {
System.out.println(Thread.currentThread() + " 订阅者2号开始订阅:" + subscription);
this.subscription = subscription;
// 向缓存请求一条数据以便于激活订阅者
subscription.request(1);
}
// 在下一个元素到达时,即接收到数据时
@Override
public void onNext(String item) {
System.out.println(Thread.currentThread() + " 订阅者2号接收到的消息:" + item);
// 每次操作完之后向缓存请求一条数据
subscription.request(1);
}
// 在接收到错误信号时
@Override
public void onError(Throwable throwable) {
System.out.println(Thread.currentThread() + " 订阅者2号接收到错误信号:" + throwable);
}
// 在接收完成时
@Override
public void onComplete() {
System.out.println(Thread.currentThread() + " 订阅者2号接收完成信息");
}
};
// 4、绑定发布者、处理器和订阅者(责任链)
publisher.subscribe(processor1); // 由发布者发布信息给处理器1
processor1.subscribe(processor2); // 由发布者发布信息给处理器2
processor2.subscribe(subscriber1); // 由处理器2发布信息给订阅者1
processor2.subscribe(subscriber2); // 由处理器2发布信息给订阅者2
// 5、确定绑定上之后开始发送数据
for (int i = 0; i < 10; i++) {
if (i < 9) {
// 隔一秒发一条,以免发太快缓存中来不及读取消息就抛出了异常
Thread.sleep(1000);
// 发布者发布十条数据到Buffer区
publisher.submit("p-" + i);
} else {
// 模拟一个异常抛出,中断发布
publisher.closeExceptionally(new RuntimeException("发布者太累了,不想干了..."));
}
}
// 6、关闭发布者通道,能够激活订阅者的onComplete回调函数,允许重复调用,但是对关闭的发布者调用close方法无效
publisher.close();
// 绑定之后发布者有数据,订阅者就会拿到,但是在测试时需要保证主线程不被停掉
Thread.sleep(20000);
}
}
|
# Copyright 2023 Synnax Labs, Inc.
#
# Use of this software is governed by the Business Source License included in the file
# licenses/BSL.txt.
#
# As of the Change Date specified in that file, in accordance with the Business Source
# License, use of this software will be governed by the Apache License, Version 2.0,
# included in the file licenses/APL.txt.
from __future__ import annotations
from typing import Type
import urllib3
from urllib3 import PoolManager
from urllib3.exceptions import HTTPError, MaxRetryError
from urllib3.response import BaseHTTPResponse
from freighter.context import Context, Role
from freighter.encoder import EncoderDecoder
from freighter.exceptions import ExceptionPayload, Unreachable, decode_exception
from freighter.transport import RQ, RS, MiddlewareCollector
from freighter.unary import UnaryClient
from freighter.url import URL
class HTTPClient(MiddlewareCollector):
"""HTTPClientFactory provides a factory for creating POST and GET implementation of
the UnaryClient protocol.
"""
__ERROR_ENCODING_HEADER_KEY = "Error-Encoding"
__ERROR_ENCODING_HEADER_VALUE = "freighter"
__CONTENT_TYPE_HEADER_KEY = "Content-Type"
__pool: PoolManager
__endpoint: URL
__encoder_decoder: EncoderDecoder
__secure: bool
def __init__(
self,
url: URL,
encoder_decoder: EncoderDecoder,
secure: bool = False,
**kwargs,
):
"""
:param url: The base URL for the client.
:param encoder_decoder: The encoder/decoder to use for the client.
:param secure: Whether to use HTTPS.
"""
super().__init__()
self.__endpoint = url
self.__endpoint.protocol = "https" if secure else "http"
self.__encoder_decoder = encoder_decoder
self.__secure = secure
self.__pool = PoolManager(cert_reqs="CERT_NONE", **kwargs)
urllib3.disable_warnings()
def __(self) -> UnaryClient:
return self
def send(
self, target: str, req: RQ, res_t: Type[RS]
) -> tuple[RS, None] | tuple[None, Exception]:
"""Implements the UnaryClient protocol."""
return self.request(
"POST",
self.__endpoint.child(target).stringify(),
"client",
req,
res_t,
)
@property
def __headers(self) -> dict[str, str]:
return {
self.__CONTENT_TYPE_HEADER_KEY: self.__encoder_decoder.content_type(),
self.__ERROR_ENCODING_HEADER_KEY: self.__ERROR_ENCODING_HEADER_VALUE,
}
def request(
self,
method: str,
url: str,
role: Role,
request: RQ | None = None,
res_t: Type[RS] | None = None,
) -> tuple[RS, None] | tuple[None, Exception]:
in_ctx = Context(url, self.__endpoint.protocol, role)
res: RS | None = None
def finalizer(ctx: Context) -> tuple[Context, Exception | None]:
nonlocal res
out_meta_data = Context(url, self.__endpoint.protocol, role)
data = None
if request is not None:
data = self.__encoder_decoder.encode(request)
head = {**self.__headers, **ctx.params}
http_res: BaseHTTPResponse
try:
http_res = self.__pool.request(
method=method, url=url, headers=head, body=data
)
except MaxRetryError as e:
return out_meta_data, Unreachable(url, e.url)
except HTTPError as e:
return out_meta_data, e
out_meta_data.params = http_res.headers
if http_res.status < 200 or http_res.status >= 300:
err = self.__encoder_decoder.decode(http_res.data, ExceptionPayload)
return out_meta_data, decode_exception(err)
if http_res.data is None:
return out_meta_data, None
res = self.__encoder_decoder.decode(http_res.data, res_t)
return out_meta_data, None
_, exc = self.exec(in_ctx, finalizer)
return res, exc
|
import React from 'react'
import { Form, Row, Col, ListGroup, Image, Button, Card } from 'react-bootstrap'
import { FaTrash } from 'react-icons/fa'
import { useDispatch, useSelector } from 'react-redux';
import { Link, useNavigate } from 'react-router-dom';
import Message from '../components/Message';
import { addToCart, removeFromCart } from '../slices/cartSlice';
const CartScreen = () => {
const navigate = useNavigate();
const dispatch = useDispatch();
const cart = useSelector(state => state.cart);
const { cartItems } = cart;
const addToCartHandler = async (product, qty) => {
dispatch(addToCart({ ...product, qty }));
}
const removeFromCartHandler = async (id) => {
dispatch(removeFromCart(id));
}
return (<>
<Row>
<Col md={8}>
<h1 style={{ marginBottom: '20px' }}>Shopping Cart</h1>
{cartItems.length === 0 ? (
<Message variant={'info'}>
Your cart is empty <Link to="/">Go Back</Link>
</Message>
) : (<ListGroup variant='flush'>{
cartItems.map(item => (
<ListGroup.Item key={item.id}>
<Row>
<Col md={2}>
<Image src={item.images[0]} alt={item.name} fluid rounded />
</Col>
<Col md={3}>
<Link to={`/product/${item.id}`}>{item.name}</Link>
</Col>
<Col md={2}>
${item.price}
</Col>
<Col md={2}>
<Form.Control as='select' value={item.qty} onChange={(e) => addToCartHandler(item, Number(e.target.value))}>
{[...Array(item.countInStock).keys()].map(x => (
<option key={x + 1} value={x + 1}>{x + 1}</option>
))}
</Form.Control>
</Col>
<Col md={2}>
<Button type='button' variant='light' onClick={() => removeFromCartHandler(item.id)}>
<FaTrash color='red' />
</Button>
</Col>
</Row>
</ListGroup.Item>
))
}</ListGroup>)}
</Col>
<Col md={4}>
<Card>
<ListGroup variant='flush'>
<ListGroup.Item>
<h2>Subtotal ({cartItems.reduce((acc, item) => acc + item.qty, 0)}) items</h2>
${cartItems.reduce((acc, item) => acc + item.qty * item.price, 0).toFixed(2)}
</ListGroup.Item>
<ListGroup.Item>
<Button type='button' className='btn-block' disabled={cartItems.length === 0} onClick={() => navigate('/login?redirect=shipping')}>
Proceed To Checkout
</Button>
</ListGroup.Item>
</ListGroup>
</Card>
</Col>
</Row>
</>)
}
export default CartScreen
|
import React from "react";
import styled from "styled-components";
const Start = styled.div`
width: 15rem;
margin: auto;
padding-top: 10rem;
`
const Button = styled.button`
background-color: black;
border: none;
color: white;
padding: 15px 32px;
text-align: center;
text-decoration: none;
display: inline-block;
font-size: 16px;
margin: 1rem 3rem
cursor: pointer;
&:hover{
background: white;
color: #01484a;
}
`
const Name = styled.input`
width: 100%;
padding: 12px 20px;
margin: 8px 0;
display: inline-block;
border: 1px solid #ccc;
border-radius: 4px;
box-sizing: border-box;
`
const Label = styled.label`
color:white;
padding: 12px 0px;
`
const StartTest = (props) => {
const handleChange = (e) => {
const { value } = e.target
props.setName(value)
}
const onStart=()=>{
props.setStart(true)
}
return (
<Start>
<Label>Please enter your name:</Label>
<Name type='text' name='name' onChange={handleChange}/>
{props.name?
<Button onClick={()=>onStart()}>Start Quiz</Button>:null}
</Start>
);
}
export default StartTest;
|
import 'dart:io';
import 'package:dartz/dartz.dart';
import 'package:dio/dio.dart';
import 'package:template_clean_architecture/core/error/failure.dart';
import 'package:template_clean_architecture/core/resource/constant/api_list.dart';
import 'package:template_clean_architecture/features/auth/data/data.dart';
import 'package:template_clean_architecture/features/tips/data/datasources/remote/remote.dart';
import 'package:template_clean_architecture/features/tips/domain/entities/tips_entities.dart';
import 'package:template_clean_architecture/features/tips/domain/repositories/repositories.dart';
class TipsRepositoryImpl extends TipsRepository {
final TipsServiceRemote _tipsServiceRemote;
final AuthLocalService _authLocalService;
TipsRepositoryImpl(this._tipsServiceRemote, this._authLocalService);
@override
Future<Either<Failure, TipsResponseEntity>> getTips() async {
try {
final token = await _authLocalService.getCredentialToLocal();
final httpResponse = await _tipsServiceRemote.getTips(
token: token,
contentType: contentType,
);
if ((httpResponse.response.statusCode ?? 0) < 200 ||
(httpResponse.response.statusCode ?? 0) > 201) {
throw DioException(
requestOptions: httpResponse.response.requestOptions,
response: httpResponse.response,
);
}
return Right(httpResponse.data.toEntity());
} on DioException catch (e) {
return Left(ServerFailure(e.response?.data['message'] ?? e.message));
} on SocketException {
return const Left(ConnectionFailure('Failed to connect to the network'));
}
}
}
|
import React from 'react';
import Matter from 'matter-js';
import { Image } from 'react-native';
import { array, object, string } from 'prop-types';
const airplane = require('../assets/airplane.png');
const Plane = (props) => {
const width = props.size[0];
const height = props.size[1];
const x = props.body.position.x - width / 2;
const y = props.body.position.y - height / 2;
return (
<Image
style={{
position: 'absolute',
left: x,
top: y,
width: width,
height: height,
}}
resizeMode="stretch"
source={airplane}
/>
);
};
export default (world, color, pos, size) => {
const initialPlane = Matter.Bodies.rectangle(
pos.x,
pos.y,
size.width,
size.height
);
Matter.World.add(world, [initialPlane]);
return {
body: initialPlane,
size: [size.width, size.height],
color: color,
renderer: <Plane />,
};
};
Plane.propTypes = {
size: array,
body: object,
color: string,
};
// import React, {Component} from 'react';
// import {Animated} from 'react-native';
// class Plane extends Component {
// constructor(props) {
// super(props);
// this.animatedValue = new Animated.Value(this.props.body.velocity.y);
// }
// render() {
// const width = this.props.size[0];
// const height = this.props.size[1];
// const x = this.props.body.position.x - width / 2;
// const y = this.props.body.position.y - height / 2;
// this.animatedValue.setValue(this.props.body.velocity.y);
// let rotation = this.animatedValue.interpolate({
// inputRange: [-10, 0, 10, 20],
// outputRange: ['-30deg', '10deg', '20deg', '45deg'],
// extrapolate: 'clamp',
// });
// return (
// <Animated.Image
// style={{
// position: 'absolute',
// left: x,
// top: y,
// width: width,
// height: height,
// transform: [{rotate: rotation}],
// }}
// source={airplane}
// resizeMode="stretch"
// />
// );
// }
// }
// export default (world, color, pos, size) => {
// const initialPlane = Matter.Bodies.rectangle(
// pos.x,
// pos.y,
// size.width,
// size.height,
// );
// Matter.World.add(world, [initialPlane]);
// return {
// body: initialPlane,
// size: [size.width, size.height],
// color: color,
// renderer: <Plane />,
// };
// };
|
from pathlib import Path
from typing import TYPE_CHECKING, Any, Union, cast
from tarina import lang
from nonebot.internal.driver import Request
from nonebot.adapters import Bot, Event, Message
from ..export import Target, MessageExporter, SerializeFailed, export
from ..segment import At, File, Text, AtAll, Audio, Emoji, Image, Reply, Video, Voice, Reference, CustomNode
if TYPE_CHECKING:
from nonebot.adapters.red.message import MessageSegment
class RedMessageExporter(MessageExporter["MessageSegment"]):
def get_message_type(self):
from nonebot.adapters.red.message import Message
return Message
@classmethod
def get_adapter(cls) -> str:
return "RedProtocol"
def get_target(self, event: Event) -> Target:
from nonebot.adapters.red.api.model import ChatType
from nonebot.adapters.red.api.model import Message as MessageModel
assert isinstance(event, MessageModel)
return Target(str(event.peerUin or event.peerUid), private=event.chatType == ChatType.FRIEND)
def get_message_id(self, event: Event) -> str:
from nonebot.adapters.red.event import MessageEvent
assert isinstance(event, MessageEvent)
return f"{event.msgId}#{event.msgSeq}"
@export
async def text(self, seg: Text, bot: Bot) -> "MessageSegment":
ms = self.segment_class
return ms.text(seg.text)
@export
async def at(self, seg: At, bot: Bot) -> "MessageSegment":
ms = self.segment_class
return ms.at(seg.target)
@export
async def at_all(self, seg: AtAll, bot: Bot) -> "MessageSegment":
ms = self.segment_class
return ms.at_all()
@export
async def emoji(self, seg: Emoji, bot: Bot) -> "MessageSegment":
ms = self.segment_class
return ms.face(seg.id)
@export
async def media(self, seg: Union[Image, Voice, Video, Audio, File], bot: Bot) -> "MessageSegment":
ms = self.segment_class
name = seg.__class__.__name__.lower()
method = {
"image": ms.image,
"voice": ms.voice,
"video": ms.video,
"audio": ms.voice,
"file": ms.file,
}[name]
if seg.path:
return method(Path(seg.path))
elif seg.raw:
return method(seg.raw_bytes)
elif seg.url:
resp = await bot.adapter.request(Request("GET", seg.url))
return method(resp.content) # type: ignore
else:
raise SerializeFailed(lang.require("nbp-uniseg", "invalid_segment").format(type=name, seg=seg))
@export
async def reply(self, seg: Reply, bot: Bot) -> "MessageSegment":
ms = self.segment_class
if "#" in seg.id:
_id, _seq = seg.id.split("#", 1)
return ms.reply(_seq, _id)
return ms.reply(seg.id)
@export
async def reference(self, seg: Reference, bot: Bot) -> "MessageSegment":
from nonebot.adapters.red.message import ForwardNode
ms = self.segment_class
if not seg.content or not isinstance(seg.content, list):
raise SerializeFailed(
lang.require("nbp-uniseg", "invalid_segment").format(type="forward", seg=seg)
)
nodes = []
for node in seg.content:
if not isinstance(node, CustomNode):
raise SerializeFailed(
lang.require("nbp-uniseg", "invalid_segment").format(type="forward", seg=seg)
)
content = self.get_message_type()()
if isinstance(node.content, str):
content.extend(self.get_message_type()(node.content))
elif isinstance(node.content, list):
content.extend(await self.export(node.content, bot, True)) # type: ignore
else:
content.extend(node.content)
nodes.append(ForwardNode(uin=node.uid, name=node.name, time=node.time, message=content))
return ms.forward(nodes)
async def send_to(self, target: Target, bot: Bot, message: Message):
from nonebot.adapters.red.bot import Bot as RedBot
assert isinstance(bot, RedBot)
if TYPE_CHECKING:
assert isinstance(message, self.get_message_type())
if target.private:
return await bot.send_friend_message(target=target.id, message=message)
else:
return await bot.send_group_message(target=target.id, message=message)
async def recall(self, mid: Any, bot: Bot, context: Union[Target, Event]):
from nonebot.adapters.red.bot import Bot as RedBot
from nonebot.adapters.red.api.model import Message as MessageModel
assert isinstance(bot, RedBot)
_mid: MessageModel = cast(MessageModel, mid)
await bot.recall_message(_mid.chatType, _mid.peerUin, _mid.msgId)
return
def get_reply(self, mid: Any):
from nonebot.adapters.red.api.model import Message as MessageModel
_mid: MessageModel = cast(MessageModel, mid)
return Reply(f"{_mid.msgId}#{_mid.msgSeq}")
|
<template>
<div>
<!--Stats cards-->
<div class="row">
<div class="col-md-6 col-xl-4" v-for="stats in statsCards" :key="stats.title">
<stats-card>
<div class="icon-big text-center" :class="`icon-${stats.type}`" slot="header">
<i :class="stats.icon"></i>
</div>
<div class="numbers" slot="content">
<p>{{stats.title}}</p>
{{stats.value}}
</div>
<div class="stats" slot="footer">
<i :class="stats.footerIcon"></i> {{stats.footerText}}
</div>
</stats-card>
</div>
</div>
<!--Charts-->
<div class="row">
<div class="col-12">
<chart-card title="Last 1 month time spent"
sub-title=""
:chart-data="activityChart.data"
:chart-options="activityChart.options">
<div slot="legend">
<i class="fa fa-circle text-info"></i> Work
<i class="fa fa-circle text-warning"></i> Health
</div>
</chart-card>
</div>
</div>
</div>
</template>
<script>
import { StatsCard, ChartCard } from "@/components/index";
import Chartist from 'chartist';
export default {
components: {
StatsCard,
ChartCard
},
/**
* Chart data used to render stats, charts. Should be replaced with server data
*/
data() {
return {
statsCards: [
{
type: "info",
icon: "fa fa-clock-o",
title: "Time utilised",
value: "",
footerText: "Current month",
footerIcon: "ti-calendar",
key: 'current_month_time',
},
{
type: "success",
icon: "ti-wallet",
title: "Salary",
value: "",
footerText: "Current month",
footerIcon: "ti-timer",
key: 'current_month_rate',
},
{
type: "danger",
icon: "fa fa-heartbeat",
title: "Health",
value: "",
footerText: "Current month",
footerIcon: "ti-timer",
key: 'current_month_health_time',
},
{
type: "info",
icon: "fa fa-clock-o",
title: "Total time utilised",
value: "",
footerText: "Till date",
footerIcon: "ti-calendar",
key: 'total_time',
},
{
type: "success",
icon: "ti-wallet",
title: "Total salary",
value: "",
footerText: "Till date",
footerIcon: "ti-timer",
key: 'total_rate',
},
{
type: "danger",
icon: "fa fa-heartbeat",
title: "Total Health",
value: "",
footerText: "Till date",
footerIcon: "ti-timer",
key: 'health_total_time',
}
],
activityChart: {
data: {},
options: {
seriesBarDistance: 10,
axisX: {
showGrid: false
},
height: "245px"
}
},
};
},
mounted() {
this.getStats();
this.getGraph();
},
methods: {
getStats() {
axios.get('stats')
.then((response) => {
let data = response.data;
if(data.status) {
this.statsCards.forEach(stat => {
stat.value = data.stats[stat.key];
});
}
},(error) => {
this.$notify({
message: 'Oops! There was something wrong in fetching the statatics.',
type: 'danger'
})
});
},
getGraph() {
axios.get('graph')
.then((response) => {
let data = response.data;
if(data.status) {
this.activityChart.data.labels = data.dates;
this.activityChart.data.series = data.series;
// So that the chart is rendered
window.dispatchEvent(new Event('resize'));
}
},(error) => {
this.$notify({
message: 'Oops! There was something wrong in fetching the graph information.',
type: 'danger'
})
});
},
}
};
</script>
<style>
</style>
|
import PropTypes from 'prop-types';
import React, { useState, useEffect } from 'react';
import { getAllProducts, getAllSales, getSellersUsers } from '../axios';
import DeliveryContext from './DeliveryContext';
function DeliveryProvider({ children }) {
const [itemsInCart, setItemsInCart] = useState([]);
const [products, setProducts] = useState([]);
const [user, setUser] = useState({});
const [orders, setOrders] = useState([]);
const [sellers, setSellers] = useState([]);
const [sale, setSale] = useState({});
const [delivery, setDelivery] = useState(false);
const [preparing, setPreparing] = useState(false);
const [dispatch, setDispatch] = useState(false);
useEffect(() => {
const getProducts = async () => {
const result = await getAllProducts();
setProducts(result.data);
};
getProducts();
const getSellers = async () => {
const sellersList = await getSellersUsers();
setSellers(sellersList);
};
getSellers();
const getSales = async () => {
const salesList = await getAllSales();
setOrders(salesList.data);
};
getSales();
}, []);
const contextValue = {
itemsInCart,
setItemsInCart,
products,
setProducts,
user,
setUser,
sellers,
setSellers,
orders,
setOrders,
sale,
setSale,
delivery,
setDelivery,
preparing,
setPreparing,
dispatch,
setDispatch,
};
return (
<DeliveryContext.Provider value={ contextValue }>
{ children }
</DeliveryContext.Provider>
);
}
DeliveryProvider.propTypes = {
children: PropTypes.node.isRequired,
};
export default DeliveryProvider;
|
package xyz.wagyourtail.jsmacros.client.api.event.impl.world;
import net.minecraft.client.gui.hud.ClientBossBar;
import xyz.wagyourtail.doclet.DocletEnumType;
import xyz.wagyourtail.doclet.DocletReplaceReturn;
import xyz.wagyourtail.jsmacros.client.api.helpers.world.entity.BossBarHelper;
import xyz.wagyourtail.jsmacros.core.event.BaseEvent;
import xyz.wagyourtail.jsmacros.core.event.Event;
import java.util.UUID;
/**
* @author Wagyourtail
* @since 1.2.7
*/
@Event(value = "Bossbar", oldName = "BOSSBAR_UPDATE")
public class EventBossbar extends BaseEvent {
public final BossBarHelper bossBar;
public final String uuid;
@DocletReplaceReturn("BossBarUpdateType")
@DocletEnumType(name = "BossBarUpdateType", type =
"""
'ADD' | 'REMOVE' | 'UPDATE_PERCENT'
| 'UPDATE_NAME' | 'UPDATE_STYLE' | 'UPDATE_PROPERTIES'
"""
)
public final String type;
public EventBossbar(String type, UUID uuid, ClientBossBar bossBar) {
if (bossBar != null) {
this.bossBar = new BossBarHelper(bossBar);
} else {
this.bossBar = null;
}
this.uuid = uuid.toString();
this.type = type;
}
@Override
public String toString() {
return String.format("%s:{\"bossBar\": %s}", this.getEventName(), bossBar != null ? bossBar.toString() : uuid);
}
}
|
//
// WorkingWithDataPlayground.swift
// Navigation
//
// Created by Mauro Grillo on 03/02/2024.
//
import SwiftUI
// MARK: Programmatic navigation with NavigationStack
struct WorkingWithDataPlayground: View {
@State private var path = [Int]()
var body: some View {
NavigationStack(path: $path) {
VStack {
Button("Show 32") {
path = [32]
}
Button("Show 64") {
path.append(64)
}
Button("Show 32 then 64") {
path = [32, 64]
}
}
.navigationDestination(for: Int.self) { selection in
Text("You selected \(selection)")
}
}
}
}
// MARK: Navigating to different data types using NavigationPath
struct NavigationPathView: View {
@State private var navigationPath = NavigationPath()
var body: some View {
NavigationStack(path: $navigationPath) {
List {
ForEach(0..<5) { i in
NavigationLink("Select Number: \(i)", value: i)
}
ForEach(0..<5) { i in
NavigationLink("Select String: \(i)", value: String(i))
}
}
.toolbar {
Button("Push 556") {
navigationPath.append(556)
}
Button("Push Hello") {
navigationPath.append("Hello")
}
}
.navigationDestination(for: Int.self) { selection in
Text("You selected the number \(selection)")
}
.navigationDestination(for: String.self) { selection in
Text("You selected the string \(selection)")
}
}
}
}
// MARK: How to make a NavigationStack return to its root view programmatically
struct DetailView2: View {
var number: Int
// @Binding var path: [Int]
@Binding var path: NavigationPath
var body: some View {
NavigationLink("Go to Random Number", value: Int.random(in: 1...1000))
.navigationTitle("Number: \(number)")
.toolbar {
Button("Home") {
// path.removeAll()
path = NavigationPath()
}
}
}
}
struct NavigationStackReturnToRoot: View {
// @State private var path = [Int]
@State private var path = NavigationPath()
var body: some View {
NavigationStack(path: $path) {
DetailView2(number: 0, path: $path)
.navigationDestination(for: Int.self) { i in
DetailView2(number: i, path: $path)
}
}
}
}
// MARK: How to save NavigationStack paths using Codable
struct DetailRandomView: View {
var number: Int
var body: some View {
NavigationLink("Go to Random Number", value: Int.random(in: 1...1000))
.navigationTitle("Number: \(number)")
}
}
@Observable
class PathStore {
var path: NavigationPath {
didSet {
save()
}
}
private let savePath = URL.documentsDirectory.appending(path: "SavedPath")
init() {
if let data = try? Data(contentsOf: savePath) {
if let decoded = try? JSONDecoder().decode(NavigationPath.CodableRepresentation.self, from: data) {
path = NavigationPath(decoded)
return
}
}
path = NavigationPath()
}
func save() {
guard let representation = path.codable else { return }
do {
let data = try JSONEncoder().encode(representation)
try data.write(to: savePath)
} catch {
print("Failed to save navigation data")
}
}
}
struct NavigationStackPathsCodable: View {
@State private var pathStore = PathStore()
var body: some View {
NavigationStack(path: $pathStore.path) {
DetailRandomView(number: 0)
.navigationDestination(for: Int.self) { i in
DetailRandomView(number: i)
}
}
}
}
#Preview {
NavigationStackPathsCodable()
}
|
public class BackupCampaignMember{
/*
<apex:page standardController="Campaign" extensions="CampaignMemberRelatedListController">
<apex:includeScript value="//ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js" />
<apex:includeScript value="//cdnjs.cloudflare.com/ajax/libs/jquery.tablesorter/2.17.8/js/jquery.tablesorter.min.js" />
<apex:stylesheet value="//cdnjs.cloudflare.com/ajax/libs/jquery.tablesorter/2.17.8/css/theme.blue.css" />
<Script>
function confirmDelete(){ //it is called by an delete link or button and show alert with ok and cancel button if press ok then it redirects to a method in controller.
if(confirm('Are you sure?'))
return true;
return false;
};
$(document).ready(function(){
$("[id$='campMemberTable']").tablesorter({theme: 'blue', dateFormat : "dd/mm/yyyy"});
});
</Script>
<style>
.actionColumn {
color: #999;
padding: 5px 5px 2px;
}
.actionLink{
text-decoration: none;
}
a:hover {
cursor: pointer;
}
</style>
<apex:form >
<apex:pageBlock >
<apex:pageblockbuttons location="top">
<apex:commandButton value="Add New" title="Add New" onclick="window.open('/apex/Create_New_Campaign_Member?campid={!Campaign.id}')"/>
</apex:pageblockbuttons>
<apex:pageBlockTable value="{!campMemList}" var="campmemb" rendered="{!NOT(campMemList.empty)}" id="campMemberTable" styleclass="tablesorter">
<apex:column styleClass="actionColumn">
<apex:facet name="header">Action</apex:facet>
<a class="actionLink" href="/{!campmemb.id}/e?retURL=%2F{!campmemb.campaignId}" title="Edit" style=" color:#015ba7" target="_top">Edit</a> | <apex:commandLink styleClass="actionLink" title="Remove" value=" Remove" onclick="return confirm('Are you sure?')" action="{!DelCampMember}" style="cursor: pointer; color:#015ba7" target="_top"><apex:param name="removeMemberId" value="{!campmemb.Id}" assignTo="{!deleteCampMemberId}" /></apex:commandLink>
</apex:column>
<apex:column >
<apex:facet name="header">Type</apex:facet>
<apex:outputPanel >
<a class="Mylinks" href="/{!campmemb.contactId}" style="cursor: pointer" target="_top">{!campmemb.type}</a>
</apex:outputPanel>
</apex:column>
<apex:column value="{!campmemb.status}"/>
<apex:column >
<apex:facet name="header">First Name</apex:facet>
<apex:outputPanel >
<a class="Mylinks" href="/{!campmemb.id}" style="cursor: pointer" target="_top">{!campmemb.firstname}</a>
</apex:outputPanel>
</apex:column>
<apex:column >
<apex:facet name="header">Last Name</apex:facet>
<apex:outputPanel >
<a class="Mylinks" href="/{!campmemb.id}" style="cursor: pointer" target="_top">{!campmemb.lastname}</a>
</apex:outputPanel>
</apex:column>
<apex:column value="{!campmemb.title}"/>
<apex:column >
<apex:facet name="header">Company</apex:facet>
<apex:outputPanel >
{!campmemb.CompanyOrAccount}
</apex:outputPanel>
</apex:column>
<apex:column value="{!campmemb.Dietary_Reqs__c}"/>
<apex:column value="{!campmemb.Notes__c}" style="overflow: hidden; max-width: 20ch"/>
</apex:pageBlockTable>
</apex:pageBlock>
</apex:form>
</apex:page>
-----------------------------------Controller of the above vf page---------------------------------------------------
* @author: Anuj Bhadauria | makepositive
* @date: 14 December 2017
* @description: class for CampaignMember RelatedList.
public with sharing class CampaignMemberRelatedListController{
public final Campaign camp {get;set;}
public campaignmember cm {get;set;}
public List<CampaignMember> campMemList {get;set;}
public String campmemberid {get;set;}
public String deleteCampMemberId {get;set;}
//Fetching the table columns which need to show on campaignmember relatedlist
public CampaignMemberRelatedListController(ApexPages.StandardController controller){
campmemberid = ApexPages.currentPage().getParameters().get('campmembid');
this.camp = (Campaign)controller.getRecord();
Id campId = camp.Id;
campMemList = [Select id, contactId, Lastname, Firstname, Type, Status, Title, CompanyOrAccount, campaignId, Dietary_Reqs__c, Notes__c from CampaignMember where campaignId =:campId];
}
//This methods returns to the detail page of campaign after deleting a record
public PageReference DelCampMember(){
try{
if(deleteCampMemberId != null){
cm = new CampaignMember(id=deleteCampMemberId);
Delete cm;
}
PageReference pageRef = new PageReference('/'+camp.id);
pageRef.setRedirect(true);
return pageRef;
}
Catch(Exception e){
System.debug('Exception '+e);
}
return null;
}
}
----------------------------------------Second VF page Campaign Member---------------------------------------------
<apex:page controller="InsertCampaignMemberController" tabStyle="CampaignMember">
<apex:form id="frm">
<apex:sectionHeader title="Campaign Member Edit" subtitle="Campaign Member" />
<apex:messages style="color:red"/>
<apex:pageBlock title="Campaign Member Edit">
<apex:pageBlockButtons >
<apex:commandButton action="{!SaveCampMember}" value="Save" reRender="frm"/>
<apex:commandButton action="{!SaveAndNewCampMember}" value="Save & New" reRender="frm"/>
<apex:commandButton action="{!CancelCampMember}" value="Cancel" immediate="true"/>
</apex:pageBlockButtons>
<apex:pageBlockSection title="Campaign Member Information" columns="2">
<apex:inputField value="{!cm.campaignid}" id="cmpid"/>
<apex:repeat value="{!$ObjectType.CampaignMember.FieldSets.CampaignMemberFields}" var="field">
<apex:inputField value="{!cm[field]}" required="{!field.Required}" rendered="{!if(field!='Status',true,false)}"/>
<apex:selectList rendered="{!if(field=='Status',true,false)}" label="Status" size="1" value="{!status}" required="{!field.Required}">
<apex:selectOptions value="{!statusList}"></apex:selectOptions>
</apex:selectList>
</apex:repeat>
</apex:pageBlockSection>
</apex:pageBlock>
</apex:form>
</apex:page>
----------------------------------------Controller of the above vf page------------------------------------------------
* @author: Anuj Bhadauria | makepositive
* @date: 14 December 2017
* @description: class for Inserting and Editing new Campaign Member.
public with sharing class InsertCampaignMemberController{
public final Id campId {get;set;}
public campaignmember cm {get;set;}
public String campmemberid {get;set;}
public list<CampaignMemberStatus> cmStatus {get;set;}
public list<SelectOption> statusList{get;set;}
public String status {get;set;}
//Accessing thes which we need to display on the page through fieldset i.e 'CampaignMemberFields'
public InsertCampaignMemberController() {
statusList = new list<SelectOption>();
campId = ApexPages.currentPage().getParameters().get('campid');
campmemberid = ApexPages.currentPage().getParameters().get('campmembid');
system.debug(campmemberid);
String queryString = null;
cmStatus = new list<CampaignMemberStatus>();
if(campId!=null){
cmStatus = [Select id,label,IsDefault from CampaignMemberStatus where campaignId =:campId];
if(cmStatus.size()>0){
for(CampaignMemberStatus c : cmStatus){
if(c.isdefault == true){
status = c.label;
}
statusList.add(new SelectOption(c.label,c.label));
}
}
}
if(campmemberid != null){
queryString = 'Select id,CampaignId ';
for(Schema.FieldSetMember fld :SObjectType.CampaignMember.FieldSets.CampaignMemberFields.getFields()) {
queryString += ', ' + fld.getFieldPath();
}
queryString += ' from CampaignMember where id= \''+ campmemberid + '\'' ;
system.debug(queryString );
cm = database.query(queryString);
}
else {
cm = new campaignmember ();
cm.campaignid = campId ;
}
}
//This methods returns to the new record page of campaign after saving a record
public PageReference SaveCampMember(){
try{
cm.Status = Status;
upsert cm;
PageReference pageRef = new PageReference('/'+campId);
pageRef.setRedirect(true);
return pageRef;
}
Catch(Exception e){
ApexPages.addMessages(e);
}
return null;
}
//This methods returns to the detail page of campaign after saving and editing a record
public PageReference SaveAndNewCampMember(){
try{
cm.Status = Status;
upsert cm;
PageReference pageRef = new PageReference('/apex/Create_New_Campaign_Member?campid='+campId);
pageRef.setRedirect(true);
return pageRef;
}
Catch(Exception e){
ApexPages.addMessages(e);
}
return null;
}
//This methods cancel the record and return to the campaign detail page
public PageReference CancelCampMember(){
PageReference pageRef = new PageReference('/'+campId);
pageRef.setRedirect(true);
return pageRef;
}
}
*/
}
|
import { DayEntry } from 'src/app/model-classes/nutrition-log/day-entry';
import { NutritionLog } from 'src/app/model-classes/nutrition-log/nutrition-log';
import { TestHelpers } from 'src/app/services/general/testHelpers';
import { AngularFirestore } from '@angular/fire/firestore';
import { AuthenticationService } from './authentication.service';
import { TimeService } from '../general/time-constant.service';
import { StateManagerService } from '../general/state-manager.service';
import { ObjectStorageService } from '../general/object-storage.service';
import { SnackBarService } from 'src/app/shared-modules/material/snack-bar-manager.service';
import { ConversionService } from '../general/conversion.service';
import { TierPermissionsService } from '../general/tier-permissions.service';
import { FirebaseGeneralService } from './firebase-general.service';
import { PayloadService } from './payload.service';
import { Router } from '@angular/router';
import { AngularFireAuth } from '@angular/fire/auth';
import { NutritionConstanstsService } from '../nutrition-log/nutrition-constansts.service';
import { FirebaseNutritionService } from './firebase-nutrition.service';
import { autoSpy } from 'autoSpy';
import { UserProfile } from 'src/app/model-classes/general/user-profile';
import { BehaviorSubject, Observable, of } from 'rxjs';
import { EnergyPayload } from 'functions/src/classes/energy-payload';
import { CallableWrapperService } from './callable-wrapper.service';
import { MobileHealthSyncService } from '../general/mobile-health-sync.service';
import { EnvironmentService } from '../general/environment.service';
describe('FirebaseNutritionService', () => {
const testHelpers: TestHelpers = new TestHelpers();
let service: FirebaseNutritionService;
let checkDocRef;
beforeEach(() => {
service = setup().build();
checkDocRef = service.checkIfDocumentOffline;
service.checkIfDocumentOffline = async () => false;
});
it('should open the in depth nutrition log when openInDepthNutritionLog is called', () => {
const navigateSpy = spyOn(service.router, 'navigate');
service.openInDepthNutritionLog(testHelpers.getRandomNutritionLog());
expect(navigateSpy).toHaveBeenCalled();
});
it('should get the log summary document when getLogSummaryDocument is called', () => {
const dbCollSpy = spyOn(service.db, 'collection').and.returnValue({
doc: function () {
return {
collection: function () {
return {
doc: function () {
return {}
}
}
}
}
}
} as any);
service.getLogSummaryDocument(1);
expect(dbCollSpy).toHaveBeenCalled();
});
it('should return the day entries document when getDayEntriesDocument is called', () => {
const dbCollSpy = spyOn(service.db, 'collection').and.returnValue({
doc: function () {
return {
collection: function () {
return {
doc: function () {
return {}
}
}
}
}
}
} as any);
service.getDayEntriesDocument(1);
expect(dbCollSpy).toHaveBeenCalled();
});
it('should delete a log from the current user when deleteLogFromCurrentUser is called (no error)', (done) => {
spyOn(service, 'getLogSummaryDocument').and.returnValue({
delete: function () {
return new Promise(resolve => resolve(null));
}
} as any);
spyOn(service, 'getDayEntriesDocument').and.returnValue({
delete: function () {
return new Promise(resolve => resolve(null));
}
} as any);
const nutrLog: NutritionLog = testHelpers.getRandomNutritionLog();
const userProfile: UserProfile = testHelpers.createFreeUserProfile();
userProfile.mainNutrLogId = nutrLog.id;
spyOn(service.stateManager, 'getCurrentUser').and.returnValue(userProfile);
spyOn(service.payload, 'getEnergyPayLoad').and.returnValue({
estimatedTDEE: 1800
} as any);
spyOn(service.firebaseGeneralService, 'removeUserMainNutrLog').and.returnValue(new Promise(resolve => resolve(null)));
const snackBarSpy = spyOn(service.snackBarManager, 'showSuccessMessage');
service.deleteLogFromCurrentUser(nutrLog).then(() => {
expect(snackBarSpy).toHaveBeenCalled();
done();
});
});
it('should delete a log from the current user when deleteLogFromCurrentUser is called (error)', (done) => {
spyOn(service, 'getLogSummaryDocument').and.returnValue(null);
spyOn(service, 'getDayEntriesDocument').and.returnValue(null);
const nutrLog: NutritionLog = testHelpers.getRandomNutritionLog();
const userProfile: UserProfile = testHelpers.createFreeUserProfile();
userProfile.mainNutrLogId = nutrLog.id;
spyOn(service.stateManager, 'getCurrentUser').and.returnValue(userProfile);
spyOn(service.payload, 'getEnergyPayLoad').and.returnValue({
estimatedTDEE: 1800
} as any);
spyOn(service.firebaseGeneralService, 'removeUserMainNutrLog').and.returnValue(new Promise(resolve => resolve(null)));
const snackBarSpy = spyOn(service.snackBarManager, 'showFailureMessage');
service.deleteLogFromCurrentUser(nutrLog).then(() => {
expect(snackBarSpy).toHaveBeenCalled();
done();
});
});
it('should add a nutrition log to the current user when addNutritionalLogToCurrentUser is called (no error)', (done) => {
const nutrLog: NutritionLog = testHelpers.getRandomNutritionLog();
spyOn(service.objectManager, 'convertLogSummaryToFireStorageFormat').and.returnValue({});
spyOn(service, 'getLogSummaryDocument').and.returnValue({
set: function () {
return new Promise(resolve => resolve(null));
}
} as any);
const snackBarSpy = spyOn(service.snackBarManager, 'showSuccessMessage');
service.addNutritionalLogToCurrentUser(nutrLog).then(() => {
expect(snackBarSpy).toHaveBeenCalled();
done();
});
});
it('should NOT add a nutrition log to the current user when addNutritionalLogToCurrentUser is called if the document is offline', (done) => {
const nutrLog: NutritionLog = testHelpers.getRandomNutritionLog();
spyOn(service.objectManager, 'convertLogSummaryToFireStorageFormat').and.returnValue({});
spyOn(service, 'getLogSummaryDocument').and.returnValue({
set: function () {
return new Promise(resolve => resolve(null));
}
} as any);
service.checkIfDocumentOffline = async () => true;
const snackBarSpy = spyOn(service.snackBarManager, 'showSuccessMessage');
service.addNutritionalLogToCurrentUser(nutrLog).then(() => {
expect(snackBarSpy).not.toHaveBeenCalled();
done();
});
});
it('should show a warning message if the document is unavailable when addNutritionLogToCurrentUser() is called (no error)', (done) => {
const nutrLog: NutritionLog = testHelpers.getRandomNutritionLog();
spyOn(service.objectManager, 'convertLogSummaryToFireStorageFormat').and.returnValue({});
spyOn(service, 'getLogSummaryDocument').and.returnValue({
set: function () {
return new Promise(resolve => resolve(null));
}
} as any);
service.objectManager.convertLogSummaryToFireStorageFormat = () => { throw { code: service.ERROR_CODE_UNAVAILABLE } }
const snackBarSpy = spyOn(service.snackBarManager, 'showWarningMessage');
service.addNutritionalLogToCurrentUser(nutrLog).then(() => {
expect(snackBarSpy).toHaveBeenCalledWith(service.MESSAGE_UNAVAILABLE);
done();
});
});
it('should add a nutrition log to the current user when addNutritionalLogToCurrentUser is called (error)', (done) => {
const nutrLog: NutritionLog = testHelpers.getRandomNutritionLog();
const snackBarSpy = spyOn(service.snackBarManager, 'showFailureMessage');
service.addNutritionalLogToCurrentUser(nutrLog).then(() => {
expect(snackBarSpy).toHaveBeenCalled();
done();
});
});
it('should update an existing log for the current user when updateExistingLogForCurrentUser is called (no error)', (done) => {
const nutrLog: NutritionLog = testHelpers.getRandomNutritionLog();
spyOn(service.time, 'getTimeStamp').and.returnValue(new Date().getTime());
spyOn(service.objectManager, 'convertLogSummaryToFireStorageFormat').and.returnValue({});
spyOn(service, 'getLogSummaryDocument').and.returnValue({
update: function () {
return new Promise(resolve => resolve(null));
}
} as any);
const snackBarSpy = spyOn(service.snackBarManager, 'showSuccessMessage');
service.updateExistingLogForCurrentUser(nutrLog).then(() => {
expect(snackBarSpy).toHaveBeenCalled();
done();
});
});
it('should update an existing log for the current user when updateExistingLogForCurrentUser is called (error)', (done) => {
const nutrLog: NutritionLog = testHelpers.getRandomNutritionLog();
const snackBarSpy = spyOn(service.snackBarManager, 'showFailureMessage');
service.updateExistingLogForCurrentUser(nutrLog).then(() => {
expect(snackBarSpy).toHaveBeenCalled();
done();
});
});
it('should delete the day entry from the log when deleteEntryFromLog is called (no error)', (done) => {
const dayEntry: DayEntry = testHelpers.getRandomEntry();
const nutrLog: NutritionLog = testHelpers.getRandomNutritionLog();
spyOn(service, 'getDayEntriesDocument').and.returnValue({
set: function () {
return new Promise(resolve => resolve(null));
}
} as any);
spyOn(service.objectManager, 'convertDayEntryListToFireStorageFormat').and.returnValue({} as any);
const snackBarSpy = spyOn(service.snackBarManager, 'showSuccessMessage');
service.deleteEntryFromLog(dayEntry, nutrLog).then(() => {
expect(snackBarSpy).toHaveBeenCalled();
done();
});
});
it('should NOT delete the day entry from the log when deleteEntryFromLog is called (no error)', (done) => {
const dayEntry: DayEntry = testHelpers.getRandomEntry();
const nutrLog: NutritionLog = testHelpers.getRandomNutritionLog();
service.checkIfDocumentOffline = async () => true;
spyOn(service, 'getDayEntriesDocument').and.returnValue({
set: function () {
return new Promise(resolve => resolve(null));
}
} as any);
spyOn(service.objectManager, 'convertDayEntryListToFireStorageFormat').and.returnValue({} as any);
const snackBarSpy = spyOn(service.snackBarManager, 'showSuccessMessage');
service.deleteEntryFromLog(dayEntry, nutrLog).then(() => {
expect(snackBarSpy).not.toHaveBeenCalled();
done();
});
});
it('should delete the day entry from the log when deleteEntryFromLog is called (error)', (done) => {
const dayEntry: DayEntry = testHelpers.getRandomEntry();
const nutrLog: NutritionLog = testHelpers.getRandomNutritionLog();
const snackBarSpy = spyOn(service.snackBarManager, 'showFailureMessage');
service.deleteEntryFromLog(dayEntry, nutrLog).then(() => {
expect(snackBarSpy).toHaveBeenCalled();
done();
});
});
it('should add an entry to a log when addEntryToLog is called (no error)', (done) => {
const dayEntry: DayEntry = testHelpers.getRandomEntry();
const nutrLog: NutritionLog = testHelpers.getRandomNutritionLog();
spyOn(service, 'getDayEntriesDocument').and.returnValue({
set: function () {
return new Promise(resolve => resolve(null));
}
} as any);
spyOn(service.objectManager, 'convertDayEntryListToFireStorageFormat').and.returnValue({});
spyOn(service, 'markLogAsUpdated').and.returnValue(new Promise(resolve => resolve(null)));
const snackBarSpy = spyOn(service.snackBarManager, 'showSuccessMessage');
service.addEntryToLog(dayEntry, nutrLog).then(() => {
expect(snackBarSpy).toHaveBeenCalled();
done();
});
});
it('should add an entry to a log when addEntryToLog is called and not show the messages if hideMessages is true (no error)', (done) => {
const dayEntry: DayEntry = testHelpers.getRandomEntry();
const nutrLog: NutritionLog = testHelpers.getRandomNutritionLog();
spyOn(service, 'getDayEntriesDocument').and.returnValue({
set: function () {
return new Promise(resolve => resolve(null));
}
} as any);
spyOn(service.objectManager, 'convertDayEntryListToFireStorageFormat').and.returnValue({});
spyOn(service, 'markLogAsUpdated').and.returnValue(new Promise(resolve => resolve(null)));
const snackBarSpy = spyOn(service.snackBarManager, 'showSuccessMessage');
service.addEntryToLog(dayEntry, nutrLog, true).then(() => {
expect(snackBarSpy).not.toHaveBeenCalled();
done();
});
});
it('should add an entry to a log when addEntryToLog is called (no error and updating exisitng)', (done) => {
const dayEntry: DayEntry = testHelpers.getRandomEntry();
const nutrLog: NutritionLog = testHelpers.getRandomNutritionLog();
nutrLog.dayEntries = [
dayEntry
];
spyOn(service, 'getDayEntriesDocument').and.returnValue({
set: function () {
return new Promise(resolve => resolve(null));
}
} as any);
spyOn(service.objectManager, 'convertDayEntryListToFireStorageFormat').and.returnValue({});
spyOn(service, 'markLogAsUpdated').and.returnValue(new Promise(resolve => resolve(null)));
const snackBarSpy = spyOn(service.snackBarManager, 'showSuccessMessage');
service.addEntryToLog(dayEntry, nutrLog).then(() => {
expect(snackBarSpy).toHaveBeenCalled();
done();
});
});
it('should add an entry to a log when addEntryToLog is called and try to write to the health app if mobile', (done) => {
const dayEntry: DayEntry = testHelpers.getRandomEntry();
const nutrLog: NutritionLog = testHelpers.getRandomNutritionLog();
nutrLog.dayEntries = [
dayEntry
];
spyOn(service, 'getDayEntriesDocument').and.returnValue({
set: function () {
return new Promise(resolve => resolve(null));
}
} as any);
spyOn(service.objectManager, 'convertDayEntryListToFireStorageFormat').and.returnValue({});
spyOn(service, 'markLogAsUpdated').and.returnValue(new Promise(resolve => resolve(null)));
const snackBarSpy = spyOn(service.snackBarManager, 'showSuccessMessage');
service.environmentSrvice.isMobile = true;
service.addEntryToLog(dayEntry, nutrLog).then(() => {
expect(snackBarSpy).toHaveBeenCalled();
expect(service.mobileHealthService.writeToHealthAppIfAuthorized).toHaveBeenCalled();
done();
});
});
it('should add an entry to a log when addEntryToLog is called (error)', (done) => {
const dayEntry: DayEntry = testHelpers.getRandomEntry();
const nutrLog: NutritionLog = testHelpers.getRandomNutritionLog();
const snackBarSpy = spyOn(service.snackBarManager, 'showFailureMessage');
service.addEntryToLog(dayEntry, nutrLog).then(() => {
expect(snackBarSpy).toHaveBeenCalled();
done();
});
});
it('should mark a log as updated when markLogAsUpdated is called', (done) => {
const nutrLog: NutritionLog = testHelpers.getRandomNutritionLog();
const timeStampSpy = spyOn(service.time, 'getTimeStamp').and.returnValue(new Date().getTime());
const logSummarySpy = spyOn(service.objectManager, 'convertLogSummaryToFireStorageFormat').and.returnValue({});
const logDocumentSpy = spyOn(service, 'getLogSummaryDocument').and.returnValue({
update: function () {
return new Promise(resolve => resolve(null));
}
} as any);
service.markLogAsUpdated(nutrLog).then(() => {
expect(timeStampSpy).toHaveBeenCalled();
expect(logSummarySpy).toHaveBeenCalled();
expect(logDocumentSpy).toHaveBeenCalled();
done();
});
});
it('should return all the nutr log subscriptions when getAllNutrLogsSubscription is called', (done) => {
spyOn(service.objectManager, 'convertLogSummaryFromFireStorageFormat').and.returnValue({} as any);
spyOn(service.objectManager, 'convertDayEntryListFromStorageFormat').and.returnValue({} as any);
const dbCollectionSpy = spyOn(service.db, 'collection').and.returnValue({
doc: function () {
return {
collection: function () {
return {
valueChanges: function () {
return of([{}, {}, {}]);
}
}
}
}
}
} as any);
service.getAllNutrLogsSubscription().toPromise().then(() => {
expect(dbCollectionSpy).toHaveBeenCalled();
done();
});
});
it('should get the nutrition log entries subscription when getNutrLogEntriesSubscription is called', () => {
const dayEntriesSpy = spyOn(service, 'getDayEntriesDocument').and.returnValue({
valueChanges: function () {
return of([{}, {}, {}]);
}
} as any);
service.getNutrLogEntriesSubscription(1);
expect(dayEntriesSpy).toHaveBeenCalled();
});
it('should get the nutrition log summary subscription when getNutrLogSummarySubscription is called', () => {
const logSummarySpy = spyOn(service, 'getLogSummaryDocument').and.returnValue({
valueChanges: function () {
return of([{}, {}, {}]);
}
} as any);
service.getNutrLogSummarySubscription(1);
expect(logSummarySpy).toHaveBeenCalled();
});
it("should return todays date if the observedLog is null and getAutoPromptDate() is called", () => {
const expectedReturnValue = new Date();
const actualDate = service.getAutoPromptDate(null, new EnergyPayload());
const actualIsExpected = (
expectedReturnValue.getDate() === actualDate.getDate()
&& expectedReturnValue.getMonth() === actualDate.getMonth()
&& expectedReturnValue.getFullYear() === actualDate.getFullYear())
expect(actualIsExpected).toBe(true);
});
it("should return todays date if the observedPayload is null and getAutoPromptDate() is called", () => {
const expectedReturnValue = new Date();
const someLog = new NutritionLog();
someLog.dayEntries = testHelpers.getRandomEntryList();
const actualDate = service.getAutoPromptDate(someLog, null);
const actualIsExpected = (
expectedReturnValue.getDate() === actualDate.getDate()
&& expectedReturnValue.getMonth() === actualDate.getMonth()
&& expectedReturnValue.getFullYear() === actualDate.getFullYear())
expect(actualIsExpected).toBe(true);
});
it("should return todays date if the observedLog is empty and getAutoPromptDate() is called", () => {
const expectedReturnValue = new Date();
const someLog = new NutritionLog();
const actualDate = service.getAutoPromptDate(someLog, new EnergyPayload());
const actualIsExpected = (
expectedReturnValue.getDate() === actualDate.getDate()
&& expectedReturnValue.getMonth() === actualDate.getMonth()
&& expectedReturnValue.getFullYear() === actualDate.getFullYear())
expect(actualIsExpected).toBe(true);
});
it("should return one day after the payloads latest date if the observed log is not empty or null and getAutoPromptDate() is called", () => {
const observedLog = new NutritionLog();
observedLog.dayEntries = [new DayEntry()];
const expectedOneDayLater = testHelpers.getRandomDate();
const payloadLatesDate = new Date();
service.time.getOneDayLater = (date: Date) => {
if (date.getTime() === payloadLatesDate.getTime()) {
return expectedOneDayLater
}
else {
return null;
}
}
const payload = new EnergyPayload();
payload.latestDate = payloadLatesDate.getTime();
const expectedReturnValue = service.time.getOneDayLater(payloadLatesDate);
const actualDate = service.getAutoPromptDate(observedLog, payload);
const actualIsExpected = (
expectedReturnValue.getDate() === actualDate.getDate()
&& expectedReturnValue.getMonth() === actualDate.getMonth()
&& expectedReturnValue.getFullYear() === actualDate.getFullYear())
expect(actualIsExpected).toBe(true);
});
it("should say the document is offline if an error occurs when checkIfDocumentIsOffline() is called ", async () => {
const fakeDocument: any = {
missingTheNessaryProperties: "soThisWillCauseAnError"
};
service.checkIfDocumentOffline = checkDocRef;
const docIsOffline = await service.checkIfDocumentOffline(fakeDocument);
expect(docIsOffline).toBe(true);
expect(service.snackBarManager.showWarningMessage).toHaveBeenCalled();
});
it("should say the document is or is not from the cache based on hte _fromCache when checkIfDocumentIsOffline() is called ", async () => {
let fakeDocument: any = {
get: () => {
return {
toPromise: () => {
return {
'_fromCache': true
}
}
}
}
};
service.checkIfDocumentOffline = checkDocRef;
let docIsOffline = await service.checkIfDocumentOffline(fakeDocument);
expect(docIsOffline).toBe(true);
expect(service.snackBarManager.showWarningMessage).toHaveBeenCalled();
fakeDocument = {
get: () => {
return {
toPromise: () => {
return {
'_fromCache': false
}
}
}
}
};
service.checkIfDocumentOffline = checkDocRef;
docIsOffline = await service.checkIfDocumentOffline(fakeDocument);
expect(docIsOffline).toBe(false);
expect(service.snackBarManager.showWarningMessage).toHaveBeenCalled();
});
it("should return INSUFFICIENT_DATA if there is an error when getNutrLogEntriesSubscription() is called ", () => {
service.constants.INSUFFICIENT_DATA = "someValue" as any;
const mySubject = new BehaviorSubject<any>(null);
const fakeDocument = {
valueChanges: () => mySubject
}
service.getDayEntriesDocument = () => { return fakeDocument as any };
service.objectManager.convertDayEntryListFromStorageFormat = () => { throw "error" }
const someObservable: Observable<any> = service.getNutrLogEntriesSubscription(null);
someObservable.subscribe((value) => {
expect(value).toBe(service.constants.INSUFFICIENT_DATA);
});
mySubject.next("someValue")
});
it("should return a converted entry list if there is NOT an error when getNutrLogEntriesSubscription() is called ", () => {
const expectedReturn = "someExpectedValue";
const mySubject = new BehaviorSubject<any>(null);
const fakeDocument = {
valueChanges: () => mySubject
}
service.getDayEntriesDocument = () => { return fakeDocument as any };
service.objectManager.convertDayEntryListFromStorageFormat = () => { return expectedReturn as any }
const someObservable: Observable<any> = service.getNutrLogEntriesSubscription(null);
someObservable.subscribe((value) => {
expect(value).toBe(expectedReturn);
});
mySubject.next("someValue")
});
it("should return a converted log if there is NOT an error when getNutrLogSummarySubscription() is called ", () => {
const expectedReturn = "someExpectedValue";
const mySubject = new BehaviorSubject<any>(null);
const fakeDocument = {
valueChanges: () => mySubject
}
service.getLogSummaryDocument = () => { return fakeDocument as any };
service.objectManager.convertLogSummaryFromFireStorageFormat = () => { return expectedReturn as any }
const someObservable: Observable<any> = service.getNutrLogSummarySubscription(null);
someObservable.subscribe((value) => {
expect(value).toBe(expectedReturn);
});
mySubject.next("someValue")
});
it("should NOT return a converted log if there is an error when getNutrLogSummarySubscription() is called ", () => {
service.constants.INSUFFICIENT_DATA = "someValue" as any;
const mySubject = new BehaviorSubject<any>(null);
const fakeDocument = {
valueChanges: () => mySubject
}
service.getLogSummaryDocument = () => { return fakeDocument as any };
service.objectManager.convertLogSummaryFromFireStorageFormat = () => { throw "error" };
const someObservable: Observable<any> = service.getNutrLogSummarySubscription(null);
someObservable.subscribe((value) => {
expect(value).toBe(service.constants.INSUFFICIENT_DATA);
});
mySubject.next("someValue")
});
it("should not do anything else if addEntryToLog() is called and the document is offline ", async () => {
service.getDayEntriesDocument = () => null;
service.checkIfDocumentOffline = async () => true;
const addedEntry = await service.addEntryToLog(new DayEntry(), new NutritionLog());
expect(addedEntry).toBe(false);
});
it("should not delete the log or do anything if the log is not online and deleteLogFromCurrentUser() is called ", async () => {
const logSpy = jasmine.createSpy();
const entrySpy = jasmine.createSpy();
service.getLogSummaryDocument = () => {
return {
delete: logSpy
} as any;
};
service.getDayEntriesDocument = () => {
return {
delete: entrySpy
} as any;
}
service.checkIfDocumentOffline = async () => true;
await service.deleteLogFromCurrentUser(new NutritionLog());
expect(logSpy).not.toHaveBeenCalled();
expect(entrySpy).not.toHaveBeenCalled();
});
it("should still delete the log if the log is online but not the main log and deleteLogFromCurrentUser() is called ", async () => {
const logSpy = jasmine.createSpy();
const entrySpy = jasmine.createSpy();
service.getLogSummaryDocument = () => {
return {
delete: logSpy
} as any;
};
service.getDayEntriesDocument = () => {
return {
delete: entrySpy
} as any;
}
const log = new NutritionLog();
const user = new UserProfile();
user.mainNutrLogId = log.id + Math.random();
service.checkIfDocumentOffline = async () => false;
service.stateManager.getCurrentUser = () => user;
await service.deleteLogFromCurrentUser(log);
expect(logSpy).toHaveBeenCalled();
expect(entrySpy).toHaveBeenCalled();
});
it("should not update the log for the current user if the log is offline", async () => {
let summarySpy = jasmine.createSpy();
service.getLogSummaryDocument = () => {
return {
update: summarySpy
} as any;
}
service.checkIfDocumentOffline = async () => true;
await service.updateExistingLogForCurrentUser(new NutritionLog())
expect(summarySpy).not.toHaveBeenCalled();
});
it("should call the sync health data cloud func when syncDataFromHealth() is caleld ", async () => {
const log = new NutritionLog();
const prof = new UserProfile();
const entries = [];
await service.syncDataFromHealth(log, prof, entries);
expect(service.wrapper.firebaseCloudFunction).toHaveBeenCalled()
});
});
function setup() {
const db = autoSpy(AngularFirestore);
const auth = autoSpy(AuthenticationService);
const time = autoSpy(TimeService);
const stateManager = autoSpy(StateManagerService);
const objectManager = autoSpy(ObjectStorageService);
const snackBarManager = autoSpy(SnackBarService);
const conversionManager = autoSpy(ConversionService);
const tierPermissionsService = autoSpy(TierPermissionsService);
const firebaseGeneralService = autoSpy(FirebaseGeneralService);
const payload = autoSpy(PayloadService);
const router = autoSpy(Router);
const afAuth = autoSpy(AngularFireAuth);
const constants = autoSpy(NutritionConstanstsService);
const wrapper = autoSpy(CallableWrapperService);
const mobileHealthService = autoSpy(MobileHealthSyncService);
const environment = autoSpy(EnvironmentService)
const builder = {
db,
auth,
time,
stateManager,
objectManager,
snackBarManager,
conversionManager,
tierPermissionsService,
firebaseGeneralService,
payload,
router,
afAuth,
constants,
default() {
return builder;
},
build() {
jasmine.getEnv().allowRespy(true);
stateManager.currentUserProfile = new BehaviorSubject<UserProfile>(new TestHelpers().createFreeUserProfile());
return new FirebaseNutritionService(db, auth, time, stateManager, objectManager, snackBarManager, conversionManager, tierPermissionsService, firebaseGeneralService, payload, router, afAuth, constants, wrapper, mobileHealthService, environment);
}
};
return builder;
}
|
package com.example.roomempresas.list
import android.os.Bundle
import androidx.fragment.app.Fragment
import androidx.recyclerview.widget.GridLayoutManager
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.fragment.app.viewModels
import androidx.lifecycle.Lifecycle
import androidx.lifecycle.lifecycleScope
import androidx.lifecycle.repeatOnLifecycle
import com.example.dblib.model.entity.Empresa
import com.example.roomempresas.R
import com.example.roomempresas.app.EmpresaApplication
import com.example.roomempresas.databinding.FragmentItemListBinding
import com.example.roomempresas.viewmodel.EmpresaViewModel
import kotlinx.coroutines.flow.collectLatest
import kotlinx.coroutines.launch
/**
* A fragment representing a list of Items.
*/
class EmpresaFragment : Fragment() {
private var columnCount = 1
private val viewModel: EmpresaViewModel by viewModels {
EmpresaViewModel.EmpresaViewModelFactory((this@EmpresaFragment.requireActivity().application as EmpresaApplication).repository)
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
arguments?.let {
columnCount = it.getInt(ARG_COLUMN_COUNT)
}
}
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
val view = inflater.inflate(R.layout.fragment_item_list, container, false)
// Set the adapter
if (view is RecyclerView) {
with(view) {
layoutManager = when {
columnCount <= 1 -> LinearLayoutManager(context)
else -> GridLayoutManager(context, columnCount)
}
adapter = MyEmpresaRecyclerViewAdapter(listOf<Empresa>())
}
}
return view
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
val adapter = FragmentItemListBinding.bind(view).list.adapter
viewLifecycleOwner.lifecycleScope.launch {
viewLifecycleOwner.repeatOnLifecycle(Lifecycle.State.STARTED) {
viewModel.allEmpresas.collectLatest { empresas ->
empresas?.let {
FragmentItemListBinding.bind(view).list.adapter = MyEmpresaRecyclerViewAdapter(empresas)
}
}
}
}
}
companion object {
// TODO: Customize parameter argument names
const val ARG_COLUMN_COUNT = "column-count"
// TODO: Customize parameter initialization
@JvmStatic
fun newInstance(columnCount: Int) =
EmpresaFragment().apply {
arguments = Bundle().apply {
putInt(ARG_COLUMN_COUNT, columnCount)
}
}
}
}
|
//
// LockControlItem.swift
// BetterKia-iOS
//
// Created by Joschua Haß on 19.02.23.
//
import SwiftUI
struct LockControlItem: View {
@ObservedObject var vehicleManager: VehicleManager
@State var isBusy = false;
var body: some View {
Button {
if (vehicleManager.isVehicleLocked) {
isBusy = true;
Task {
await vehicleManager.unlock();
isBusy = false;
}
} else {
isBusy = true;
Task {
await vehicleManager.lock();
isBusy = false;
}
}
}
label:
{
if (isBusy) {
ProgressView()
.frame(height: 20)
.frame(maxWidth: .infinity, alignment: .center)
} else {
if (vehicleManager.isVehicleLocked) {
Image(systemName: "lock.fill")
.resizable()
.aspectRatio(contentMode: .fit)
.frame(height: 20)
.foregroundColor(.gray)
.frame(maxWidth: .infinity, alignment: .center)
} else {
Image(systemName: "lock.open.fill")
.resizable()
.aspectRatio(contentMode: .fit)
.frame(height: 20)
.foregroundColor(.white)
.frame(maxWidth: .infinity, alignment: .center)
}
}
}
.disabled(isBusy)
}
}
struct LockControlItemPreviews: PreviewProvider {
static var previews: some View {
DashboardView(vehicleManager: VehicleManager.getPreviewInstance())
.previewDisplayName("Dashboard: Data")
.previewDevice(PreviewDevice(rawValue: "iPhone 14"))
DashboardView()
.previewDisplayName("Dashboard: No Data")
.previewDevice(PreviewDevice(rawValue: "iPhone 14"))
}
}
|
/****************************************************************************
**
** Copyright (C) 2008-2010 Nokia Corporation and/or its subsidiary(-ies).
** All rights reserved.
** Contact: Nokia Corporation (developer.feedback@nokia.com)
**
** This file is part of the HbWidgets module of the UI Extensions for Mobile.
**
** GNU Lesser General Public License Usage
** This file may be used under the terms of the GNU Lesser General Public
** License version 2.1 as published by the Free Software Foundation and
** appearing in the file LICENSE.LGPL included in the packaging of this file.
** Please review the following information to ensure the GNU Lesser General
** Public License version 2.1 requirements will be met:
** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Nokia gives you certain additional
** rights. These rights are described in the Nokia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** If you have questions regarding the use of this file, please contact
** Nokia at developer.feedback@nokia.com.
**
****************************************************************************/
#ifndef HBDEVICEMESSAGEBOXSYMBIAN_H
#define HBDEVICEMESSAGEBOXSYMBIAN_H
#if defined(__SYMBIAN32__) || defined(SYMBIAN) || defined(HB_DOXYGEN)
#include <e32base.h>
class CHbDeviceMessageBoxPrivate;
class MHbDeviceMessageBoxObserver;
class CHbDeviceMessageBoxSymbian : public CBase
{
public:
enum TType {
ENone,
EInformation,
EQuestion,
EWarning
};
enum TButtonId {
EInvalidButton = -1,
EAcceptButton,
ERejectButton
};
public:
IMPORT_C static CHbDeviceMessageBoxSymbian* NewL(TType aType = ENone,
MHbDeviceMessageBoxObserver *aObserver = 0);
IMPORT_C ~CHbDeviceMessageBoxSymbian();
IMPORT_C static TButtonId QuestionL(const TDesC& aText,
const TDesC& aAcceptButtonText, const TDesC& aRejectButtonText);
IMPORT_C static TButtonId QuestionL(const TDesC& aText, TUint aStandardButtons = 0);
IMPORT_C static void InformationL(const TDesC& aText);
IMPORT_C static void WarningL(const TDesC& aText);
IMPORT_C void ShowL();
IMPORT_C void UpdateL();
IMPORT_C void Close();
IMPORT_C TButtonId ExecL();
IMPORT_C void SetTypeL(TType aType);
IMPORT_C TType Type() const;
IMPORT_C void SetTextL(const TDesC& aText);
IMPORT_C const TPtrC Text() const;
IMPORT_C void SetIconNameL(const TDesC& aIconName);
IMPORT_C const TPtrC IconName() const;
IMPORT_C void SetAnimationDefinitionL(const TDesC& aAnimationDefinition);
IMPORT_C TPtrC AnimationDefinition() const;
IMPORT_C void SetIconVisible(TBool aVisible);
IMPORT_C TBool IconVisible() const;
IMPORT_C void SetTimeout(TInt aTimeout);
IMPORT_C TInt Timeout() const;
IMPORT_C void SetDismissPolicy(TInt aHbPopupDismissPolicy);
IMPORT_C TInt DismissPolicy() const;
IMPORT_C void SetButtonTextL(TButtonId aButton, const TDesC& aText);
IMPORT_C const TPtrC ButtonText(TButtonId aButton) const;
IMPORT_C void SetButton(TButtonId aButton, TBool aEnable);
IMPORT_C TBool HasButton(TButtonId aButton) const;
IMPORT_C void SetStandardButtons(TUint aButtons);
IMPORT_C TUint StandardButtons() const;
IMPORT_C void SetObserver(MHbDeviceMessageBoxObserver *aObserver);
private:
friend class CHbDeviceMessageBoxPrivate;
CHbDeviceMessageBoxSymbian();
CHbDeviceMessageBoxPrivate* d;
};
class MHbDeviceMessageBoxObserver
{
public:
virtual void MessageBoxClosed(const CHbDeviceMessageBoxSymbian* aMessageBox,
CHbDeviceMessageBoxSymbian::TButtonId aButton) = 0;
};
#endif // defined(__SYMBIAN32__) || defined(SYMBIAN) || defined(HB_DOXYGEN)
#endif // HBDEVICEMESSAGEBOXSYMBIAN_H
|
import {
AfterViewInit,
Component,
ElementRef,
EventEmitter,
Input,
OnChanges,
OnDestroy,
Output,
ViewChild,
} from '@angular/core';
import {
MemberFilterTile,
type MemberFilterTileProps,
ComponentAdapter,
createElement,
} from '@sisense/sdk-ui-preact';
import { SisenseContextService } from '../services/sisense-context.service';
import { ThemeService } from '../services/theme.service';
import type { Arguments, ArgumentsAsObject } from '../types/utility-types';
import {
createSisenseContextConnector,
createThemeContextConnector,
} from '../component-wrapper-helpers';
import { template, rootId } from '../component-wrapper-helpers/template';
/**
* Member Filter Tile Component
*/
@Component({
selector: 'csdk-member-filter-tile',
template,
})
export class MemberFilterTileComponent implements AfterViewInit, OnChanges, OnDestroy {
/**
* @internal
*/
@ViewChild(rootId)
preactRef!: ElementRef<HTMLDivElement>;
/**
* {@inheritDoc @sisense/sdk-ui!MemberFilterTileProps.title}
*/
@Input()
title!: MemberFilterTileProps['title'];
/**
* {@inheritDoc @sisense/sdk-ui!MemberFilterTileProps.dataSource}
*/
@Input()
dataSource: MemberFilterTileProps['dataSource'];
/**
* {@inheritDoc @sisense/sdk-ui!MemberFilterTileProps.attribute}
*/
@Input()
attribute!: MemberFilterTileProps['attribute'];
/**
* {@inheritDoc @sisense/sdk-ui!MemberFilterTileProps.filter}
*/
@Input()
filter!: MemberFilterTileProps['filter'];
/**
* {@inheritDoc @sisense/sdk-ui!MemberFilterTileProps.onChange}
*/
@Output()
filterChange = new EventEmitter<
ArgumentsAsObject<MemberFilterTileProps['onChange'], ['filter']>
>();
private componentAdapter: ComponentAdapter;
/**
* Constructor for the `MemberFilterTileComponent`.
*
* @param sisenseContextService - Sisense context service
* @param themeService - Theme service
*/
constructor(
/**
* Sisense context service
*
* @category Constructor
*/
public sisenseContextService: SisenseContextService,
/**
* Theme service
*
* @category Constructor
*/
public themeService: ThemeService,
) {
this.componentAdapter = new ComponentAdapter(
() => this.createPreactComponent(),
[
createSisenseContextConnector(this.sisenseContextService),
createThemeContextConnector(this.themeService),
],
);
}
/**
* @internal
*/
ngAfterViewInit() {
this.componentAdapter.render(this.preactRef.nativeElement);
}
/**
* @internal
*/
ngOnChanges() {
if (this.preactRef) {
this.componentAdapter.render(this.preactRef.nativeElement);
}
}
private createPreactComponent() {
const props = {
title: this.title,
dataSource: this.dataSource,
attribute: this.attribute,
filter: this.filter,
onChange: (...[filter]: Arguments<MemberFilterTileProps['onChange']>) =>
this.filterChange.emit({ filter }),
};
return createElement(MemberFilterTile, props);
}
/**
* @internal
*/
ngOnDestroy() {
this.componentAdapter.destroy();
}
}
|
/*
* StkAnalystenschaetzung.java
*
* Created on 13.07.2006 07:06:22
*
* Copyright (c) MARKET MAKER Software AG. All Rights Reserved.
*/
package de.marketmaker.istar.merger.web.easytrade.block;
import de.marketmaker.istar.domain.data.HistoricEstimates;
import de.marketmaker.istar.domain.instrument.Quote;
import de.marketmaker.istar.domain.profile.Profile;
import de.marketmaker.istar.merger.context.RequestContextHolder;
import de.marketmaker.istar.merger.provider.estimates.EstimatesProvider;
import de.marketmaker.istar.merger.web.easytrade.DefaultSymbolCommand;
import de.marketmaker.istar.merger.web.easytrade.SymbolCommand;
import java.util.HashMap;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.validation.BindException;
import org.springframework.web.servlet.ModelAndView;
/**
* Returns historic estimates of the economic development of a given stock corporation for the last few weeks and/or months depending on the data item.
* <p>
* In the response, the XML entity name of a data item is suffixed with its value's age.
* The age is given as a single-digit number that is appended with <code>w</code> for weeks or <code>m</code> for months.
* </p>
*
* @author Oliver Flege
* @author Thomas Kiesgen
*/
public class StkHistoricEstimates extends EasytradeCommandController {
private EstimatesProvider estimatesProvider;
private EasytradeInstrumentProvider instrumentProvider;
public StkHistoricEstimates() {
super(DefaultSymbolCommand.class);
}
public void setInstrumentProvider(EasytradeInstrumentProvider instrumentProvider) {
this.instrumentProvider = instrumentProvider;
}
public void setEstimatesProvider(EstimatesProvider estimatesProvider) {
this.estimatesProvider = estimatesProvider;
}
protected ModelAndView doHandle(HttpServletRequest request, HttpServletResponse response,
Object o, BindException errors) {
final SymbolCommand cmd = (SymbolCommand) o;
final Quote quote = this.instrumentProvider.getQuote(cmd);
final Map<String, Object> model = new HashMap<>();
model.put("instrument", quote.getInstrument());
model.put("referencequote", quote);
final HistoricEstimates historicEstimates = getEstimates(quote);
model.put("historicEstimates", historicEstimates);
return new ModelAndView("stkhistoricestimates", model);
}
private HistoricEstimates getEstimates(Quote quote) {
final Profile profile = RequestContextHolder.getRequestContext().getProfile();
return this.estimatesProvider.getHistoricEstimates(profile, quote.getInstrument().getId());
}
}
|
import { randomBytes } from 'crypto';
const capitalLetters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
const capitalLettersLength = capitalLetters.length;
const numbers = '0123456789';
const numbersLength = numbers.length;
/**
* Generates a random name in the format "ADA DAD ADA" where:
* A: is alphabetic character A-Z
* D: is a digit 0-9
*/
export function getRandomName(): string {
const nameLength = 9;
let randomName = '';
for (let i = 0; i < nameLength; i++) {
const randomNumber = parseInt(randomBytes(4).toString('hex'), 16);
if (i % 2 === 0) {
randomName += capitalLetters[randomNumber % capitalLettersLength] || ' ';
} else {
randomName += numbers[randomNumber % numbersLength] || ' ';
}
// The following conditions means: if not at the beginning nor the end of
// the randomName string, then put a space after every 3 characters.
if (i && i < nameLength - 1 && (i + 1) % 3 === 0) {
randomName += ' ';
}
}
return randomName;
}
|
// db.ts
import Dexie, { type Table } from 'dexie';
import { indexedDB, IDBKeyRange } from "fake-indexeddb";
export interface Match {
matchNum: number;
competition: number;
teams: Array<number>;
students: Array<number>;
studentAssignments: Record<number, Assignment>;
quantitativeData: Record<number, QuantitativeData>;
qualitativeData: Record<number, QualitativeData>;
}
export interface QuantitativeData {
alliance: 'b' | 'r';
autoLeave: boolean;
autoLow: number;
autoHigh: number;
teleopLow: number;
teleopHigh: number;
rung: -1 | 0 | 1 | 2 | 3 | 4;
fouls: number;
techFouls: number;
incap: number;
}
export interface QualitativeData {
alliance: 'b' | 'r';
driverSkill: number;
sturdiness: number;
compatibility: number;
notes: string;
}
export interface Assignment {
student: number;
team: number;
team2?: number;
team3?: number;
matchNum: number;
alliance: 'b' | 'r';
type: 'quant' | 'qual';
}
export interface Result {
type: 'quant' | 'qual';
id: number;
matchNum: number;
team: number;
data: QuantitativeData;
}
export interface Student {
id: number;
name: string;
}
export class Database extends Dexie {
assignments!: Table<Assignment>;
results!: Table<Result>;
constructor() {
super('clidb');
this.version(1).stores({
assignments: '++rid, student, matchNum, type',
results: '++rid, matchNum, team',
});
}
}
export const db = new Database();
|
from time import sleep
from selenium.webdriver.remote.webelement import WebElement
class elements_list_not_empty(object):
def __init__(self, locator: tuple, pooling_timeout=0):
self.locator = locator
self.pooling_timeout = pooling_timeout / 1000
def __call__(self, driver):
sleep(self.pooling_timeout)
elements = driver.find_elements(*self.locator)
if len(elements) > 0:
return elements
else:
return False
class element_items_not_empty(object):
def __init__(self, element, items_attribute, pooling_timeout=0):
self.element = element
self.items_attribute = items_attribute
self.pooling_timeout = pooling_timeout / 1000
def __call__(self, driver):
sleep(self.pooling_timeout)
if len(getattr(self.element, self.items_attribute)) > 0:
return getattr(self.element, self.items_attribute)
else:
return False
class element_text_not_empty(object):
"""
Ожидание элемента с непустым текстом
"""
def __init__(self, element: WebElement, pooling_timeout: float = 0):
"""
Args:
element: инициализированный экземпляр класса WebElement
pooling_timeout: float время повторного опроса (в миллисекундах)
"""
self.element = element
self.pooling_timeout = pooling_timeout / 100
def __call__(self, driver):
sleep(self.pooling_timeout)
if self.element:
if len(self.element.text) > 0:
return True
return False
class element_text_empty(object):
"""
Ожидание элемента с пустым текстом
"""
def __init__(self, element: WebElement, pooling_timeout: float = 0):
"""
Args:
element: инициализированный экземпляр класса WebElement
pooling_timeout: float время повторного опроса (в миллисекундах)
"""
self.element = element
self.pooling_timeout = pooling_timeout / 100
def __call__(self, driver):
sleep(self.pooling_timeout)
if self.element:
if len(self.element.text) == 0:
return True
return False
class element_contains_text(object):
"""
Ожидание элемента содержащего текст (неполное совпадение одного из текстов)
"""
def __init__(self, element: WebElement, *text, pooling_timeout: float = 0):
"""
Args:
element: инициализированный экземпляр класса WebElement
text: tuple ожидаемый текст (один и более)
pooling_timeout: float таймаут повторного опроса (в миллисекундах)
"""
self.element = element
self.text = text
self.pooling_timeout = pooling_timeout / 1000
def __call__(self, driver):
sleep(self.pooling_timeout)
if self.element:
if any(t in self.element.text for t in self.text):
return True
return False
class element_has_text(object):
"""
Ожидание элемента с текстом (полное совпадение одного из текстов)
"""
def __init__(self, element: WebElement, *text, pooling_timeout: float = 0):
"""
Args:
element: инициализированный экземпляр класса WebElement
text: tuple ожидаемый текст
pooling_timeout: float таймаут повторного опроса (в миллисекундах)
"""
self.element = element
self.text = text
self.pooling_timeout = pooling_timeout / 1000
def __call__(self, driver):
sleep(self.pooling_timeout)
if self.element:
if any(self.element.text == t for t in self.text):
return True
return False
|
import React from "react";
import "./experience.css";
import ExperienceContent from "./ExperienceContent";
const experience = [
{
title: "Frontend Development",
skills: [
"HTML",
"CSS/SASS",
"Javascript",
"TypeScript",
"React",
"Wordpress",
],
},
{
title: "Backend Development",
skills: ["Node", "Express", "MongoDB", "PHP", "Python"],
},
{
title: "UI/UX",
skills: ["Elementor", "Figma", "Adobe XD", "Illustrator", "Photoshop"],
},
];
const Experience = () => {
return (
<section id="experience">
<h5>What Skills I Have</h5>
<h2>My Experience</h2>
<div className="container experience__container">
{experience.map((item) => {
return <ExperienceContent title={item.title} skills={item.skills} />;
})}
</div>
</section>
);
};
export default Experience;
|
#include <cs50.h>
#include <stdio.h>
int get_cents(void);
int calculate_quarters(int cents);
int calculate_dimes(int cents);
int calculate_nickels(int cents);
int calculate_pennies(int cents);
int main(void)
{
// Ask how many cents the customer is owed
int cents = get_cents();
// Calculate the number of quarters to give the customer
int quarters = calculate_quarters(cents);
cents = cents - quarters * 25;
// Calculate the number of dimes to give the customer
int dimes = calculate_dimes(cents);
cents = cents - dimes * 10;
// Calculate the number of nickels to give the customer
int nickels = calculate_nickels(cents);
cents = cents - nickels * 5;
// Calculate the number of pennies to give the customer
int pennies = calculate_pennies(cents);
cents = cents - pennies * 1;
// Sum coins
int coins = quarters + dimes + nickels + pennies;
// Print total number of coins to give the customer
printf("%i\n", coins);
}
int get_cents(void)
{
int cents_number;
do
{
cents_number = get_int("How many cents must be given?");
}
while (cents_number < 0);
return cents_number;
}
int calculate_quarters(int cents)
{
int coins;
coins = cents / 25;
return coins;
}
int calculate_dimes(int cents)
{
int coins;
coins = cents / 10;
return coins;
}
int calculate_nickels(int cents)
{
int coins;
coins = cents / 5;
return coins;
}
int calculate_pennies(int cents)
{
int coins;
coins = cents / 1;
return coins;
}
|
import { useContext, useEffect, useState } from 'react';
import {SocketContext} from '../../Context/SocketContext'
import { Card, CardContent } from '@mui/material';
import { useNavigate, useLocation } from 'react-router-dom';
import BidHistoryTable from "../content/AuctionRoomBidTable";
import ChatBox from "../content/ChatBox";
import TimerCountDown from '../common/Timer';
import { Room } from '../../types';
import Navbar from "../common/Navbar";
import { TextField, FormControl, Button, Grid } from '@mui/material';
import '../../styles/HomePage.css';
import dayjs from 'dayjs';
const AuctionRoom = () => {
const navigate = useNavigate();
const socket = useContext(SocketContext).socket;
const location = useLocation();
const room: Room = location.state;
const [bidPrice, setBidPrice] = useState<string>("");
const [viewerCount, setViewerCount] = useState<number>(0);
const handleSubmitBid = () => {
socket?.emit("sending_bid", { price: parseInt(bidPrice), auction_id: room.id });
};
useEffect(() => {
console.log(room);
socket?.emit("joining_room", { auction_id: room.id });
socket?.on("joined_room", (data) => { setViewerCount(data['viewer_count']); });
socket?.on("exited_room", (data) => { setViewerCount(data['viewer_count']); });
return () => {
socket?.emit("exiting_room", { auction_id: room.id });
socket?.off("joined_room");
socket?.off("exited_room");
};
}, [socket]);
// Navigate to Payment Page when auction ends
useEffect(() => {
if (room.room_status === 'complete') {
navigate('/payment'); // Adjust the path as necessary
}
}, [room.room_status]);
return (
<Grid container spacing={2} className="homepage-container" style={{ marginTop: '80px' }}>
<Grid container justifyContent="center" spacing={2}>
<Navbar />
<Grid item xs={12} md={8} lg={6}>
<Card raised style={{ backgroundColor: '#424242', padding: '1rem' }}>
<CardContent>
<div style={{ display: 'flex', alignItems: 'flex-start' }}>
<img
src={room.image_url}
alt={`Image of ${room.card_name}`}
className="auction-room-image"
style={{ marginRight: '20px', width: '200px', height: 'auto' }} // Adjust width as needed
/>
<div>
<Typography variant="h4" component="h1" gutterBottom>
Auction Room {room.card_name}
</Typography>
<Typography variant="h6" component="h2">
Current Viewer Count: {viewerCount}
</Typography>
{(() => {
switch (room.room_status) {
case "active":
return (
<div>
<h2>Countdown Till Auction End</h2>
<TimerCountDown date={dayjs(room.date_end)} />
</div>
);
case "inactive":
return (
<div>
<h2>Countdown Till Auction Starts</h2>
<TimerCountDown date={dayjs(room.date_start)} />
</div>
);
case "complete":
return <p>AUCTION COMPLETE</p>;
}
})()}
<div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', padding: '1rem' }}>
<FormControl className="bid-input" style={{ flexGrow: 1, marginRight: '1rem' }}>
<TextField
label="Enter Bid Price"
variant="outlined"
value={bidPrice}
type="number"
onChange={(e) => setBidPrice(e.target.value)}
InputProps={{ style: { fontSize: '1.5rem' } }} // Make the text larger
InputLabelProps={{ style: { fontSize: '1.5rem' } }} // Adjust the label size if needed
/>
</FormControl>
<Button
onClick={handleSubmitBid}
variant="contained"
size="large"
style={{
fontSize: '1.5rem',
padding: '0.5rem 2rem',
minWidth: '150px'
}}
>
BID
</Button>
</div>
</div>
</div>
</CardContent>
</Card>
<Grid item style={{ marginTop: '20px', marginLeft: '20px' }}>
<BidHistoryTable {...room} />
</Grid>
</Grid>
<Grid item xs={12} md={4} lg={6}>
<div style={{ height: '300px' }}> {/* Set a fixed height and allow scrolling */}
<ChatBox {...room} />
</div>
</Grid>
</Grid>
</Grid>
);
}
export default AuctionRoom;
|
package dao;
import business.User;
import java.security.NoSuchAlgorithmException;
/**
* @author playerzer0-ui
*/
public interface UserDaoInterface {
/**
* register a user to the database
* @param username the username
* @param email the email
* @param password the password
* @param address the address
* @param phone the phone number
* @return the user
*/
User registerUser(String username, String email, String password, String address, String phone) throws NoSuchAlgorithmException;
/**
* login the user
* @param email the email
* @param password the password
* @return the user
*/
User loginUser(String email, String password);
/**
* get the user by ID
* @param userID the userID
* @return the user
*/
User getUserByID(int userID);
/**
* delete the user by ID
* @param userID the userID
* @return rows affected
*/
int deleteUserByID(int userID);
/**
* add or subtract fee to the user
* @param userID the userID
* @param fee fee to add or reduce (+/-)
* @return number of rows affected
*/
int updateFee(int userID, int fee);
/**
* check a username, this can determine whether it exists or not, could used to check
* duplicates or a new unique name
* @param username the username
* @return true(more than one) or false(none)
*/
boolean checkUsername(String username);
/**
* check email, to check for a duplicate or a new email
* @param email the email
* @return true(more than one) or false(none)
*/
boolean checkEmail(String email);
/**
* update the userID, this can be used to enable or disable a user, simply
* change userType to -1, to enable, change to 0
* @param userID the userID
* @return rows affected
*/
int updateUserTypeByID(int userID, int userType);
}
|
import { Link } from "react-router-dom";
import { useEffect, useState } from "react"; //for hooking
import axios from "axios"; // used in fetching http request to the server
import StudentSideBar from "../../student/StudentSideBar";
import { Container } from "../../../componentcss/styledcss/Container.styled";
//import Swal from "sweetalert2";
const baseUrl = "http://127.0.0.1:8000/api";
function StudentAssignments() {
const [assignmentData, setAssignmentData] = useState([]);
const student_id = localStorage.getItem("student_id");
//const teacher_id = localStorage.getItem("teacher_id");
useEffect(() => {
document.title = "SS | My Assignments";
//axios fetch assignments when page loads
try {
axios.get(baseUrl + "/student_assignments/" + student_id).then((res) => {
setAssignmentData(res.data);
});
} catch (error) {
console.log(error);
}
}, []);
// console.log(courseData);
//Student put assignment data
const markAsDone = (assignment_id, title, detail, student, teacher) => {
const _formData = new FormData();
_formData.append("student_assignment_status", true);
_formData.append("title", title);
_formData.append("detail", detail);
_formData.append("student", student);
_formData.append("teacher", teacher);
try {
axios
.put(
baseUrl + "/student_mark_assignment_status/" + assignment_id,
_formData,
{
headers: {
"content-type": "multipart/form-data", //allows posting of img and video data to db
},
}
)
.then((res) => {
//console.log(res.data);
if (res.status === 200 || res.status === 201) {
window.location.reload();
}
});
} catch (error) {
console.log(error);
}
};
return (
<Container>
<div className="row">
<aside className="col-md-3">
<StudentSideBar />
</aside>
<section className="col-md-9">
<div className="card">
<h5 className="card-header text-dark">My Assignments</h5>
<div className="card-body">
<table className="table table-striped">
<thead>
<tr>
<th className="text-start">Assignment</th>
<th className="text-start">Teacher</th>
<th className="text-start">Action</th>
</tr>
</thead>
<tbody>
{/* data mapping */}
{assignmentData.map(
(
row,
index // notice the row, data fetched one level down
) => (
<tr>
<td>
<Link
to={"/course_details/" + row.id}
className="text-start ms-4 fs-6 fw-normal text-success"
>
{index + 1 + ". " + row.title}
</Link>
</td>
<td className="text-start text-secondary">
{row.teacher.surname + " " + row.teacher.first_name}
</td>
<td className="text-start">
{row.student_assignment_status === false && (
<button
onClick={() =>
markAsDone(
row.id,
row.title,
row.detail,
row.student.id,
row.teacher.id
)
}
className="btn btn-success btn-sm p-1"
>
Mark as done
</button>
)}
{row.student_assignment_status === true && (
<span className="badge bg-primary">Completed</span>
)}
</td>
</tr>
)
)}
</tbody>
</table>
</div>
</div>
</section>
</div>
</Container>
);
}
export default StudentAssignments;
|
#include "userManager.h"
#include "user.h"
#include <QTextStream>
#include <QSqlQuery>
#include <QDebug>
#include <QSqlError>
#include <QCoreApplication>
#include <QDir>
#include <QSql>
#include <QSqlDatabase>
using namespace std;
UserManager::~UserManager()
{
qDeleteAll(m_users);
m_users.clear();
}
UserManager::UserManager(QObject *parent) : QObject(parent)
{
QSqlDatabase dateBase = QSqlDatabase::addDatabase("QSQLITE");
QString databasePath = QCoreApplication::applicationDirPath() + QDir::separator() + "Uzytkownicy1.db";
dateBase.setDatabaseName(databasePath);
if (!dateBase.open())
{
qDebug() << "Nie można otworzyć bazy danych:" << dateBase.lastError().text();
return;
}
QSqlQuery query;
if (!query.exec("CREATE TABLE IF NOT EXISTS Uzytkownicy1 (id INTEGER PRIMARY KEY AUTOINCREMENT, nick TEXT, password TEXT)"))
{
qDebug() << "Nie udało się utworzyć tabeli użytkowników:" << query.lastError().text();
}
if (!query.exec("CREATE TABLE IF NOT EXISTS user_contacts (user_id INTEGER, contact_id INTEGER, PRIMARY KEY (user_id, contact_id), FOREIGN KEY (user_id) REFERENCES Uzytkownicy1(id), FOREIGN KEY (contact_id) REFERENCES Uzytkownicy1(id))"))
{
qDebug() << "Nie udało się utworzyć tabeli kontaktów:" << query.lastError().text();
}
}
void UserManager::loadUser()
{
if (!dateBase.isOpen())
{
qDebug() << "Baza danych nie jest otwarta!";
return;
}
QSqlQuery query;
if (query.exec("SELECT id, nick, password FROM Uzytkownicy1"))
{
while (query.next())
{
int id = query.value(0).toInt();
QString nick = query.value(1).toString();
QString password = query.value(2).toString();
User* newUser = new User(nick, id, password, this);
m_users[nick] = newUser;
}
}
else
{
qDebug() << "Błąd wczytywania użytkowników: " << query.lastError().text();
}
}
QString UserManager::getLoggedInUserNick() const
{
return loggedInUserNick;
}
int UserManager::getLoggedInUserID(const QString& userNick)
{
QSqlDatabase database = QSqlDatabase::database();
if (!database.isOpen()) {
// Obsługa błędu otwarcia bazy danych
return -1;
}
QSqlQuery query(database);
query.prepare("SELECT id FROM Uzytkownicy1 WHERE nick = :nick");
query.bindValue(":nick", userNick);
if (!query.exec()) {
// Obsługa błędu wykonania zapytania
return -1;
}
if (query.next()) {
return query.value(0).toInt();
} else {
// Użytkownik o danym nicku nie istnieje
return -1;
}
}
bool UserManager::registerUser(const QString& nick, const QString& password)
{
qDebug() << "registerUser called";
QSqlQuery queryCheck(dateBase);
queryCheck.prepare("SELECT * FROM Uzytkownicy1 WHERE nick = :nick");
queryCheck.bindValue(":nick", nick);
if (!queryCheck.exec() || queryCheck.next())
{
qDebug() << "Rejestracja nieudana - użytkownik o takim nicku już istnieje lub błąd zapytania.";
return false; // Użytkownik już istnieje lub błąd zapytania
}
QSqlQuery queryAdd(dateBase);
queryAdd.prepare("INSERT INTO Uzytkownicy1 (nick, password) VALUES (:nick, :password)");
queryAdd.bindValue(":nick", nick);
queryAdd.bindValue(":password", password);
if (!queryAdd.exec())
{
qDebug() << "Błąd przy dodawaniu użytkownika do bazy danych:" << queryAdd.lastError().text();
return false;
}
qDebug() << "Rejestracja przebiegła pomyślnie.";
return true;
}
bool UserManager::loginUser(const QString& nick, const QString& password)
{
QSqlQuery query(dateBase);
query.prepare("SELECT id, nick, password FROM Uzytkownicy1 WHERE nick = :nick AND password = :password");
query.bindValue(":nick", nick);
query.bindValue(":password", password);
if (!query.exec())
{
return false;
}
if (query.next()) {
loggedInUserNick = nick;
int userId = query.value(0).toInt(); // Pobranie ID użytkownika
User* loggedInUser = new User(nick, userId, password, this);
m_users[nick] = loggedInUser;
loggedInUser->loadContacts(); // Wczytaj kontakty użytkownika
return true;
} else {
return false;
}
}
void UserManager::addContact(const QString& userNick, int contactId)
{
User* user = m_users[userNick];
if (!user) {
qDebug() << "Błąd: Nie znaleziono użytkownika.";
return;
}
QSqlQuery queryCheck(dateBase);
queryCheck.prepare("SELECT id FROM Uzytkownicy1 WHERE id = :contactId");
queryCheck.bindValue(":contactId", contactId);
if (!queryCheck.exec() || !queryCheck.next())
{
qDebug() << "Błąd przy sprawdzaniu istnienia kontaktu lub użytkownik o ID " << contactId << " nie istnieje.";
return;
}
user->addContact(contactId);
QSqlQuery query;
query.prepare("INSERT INTO user_contacts (user_id, contact_id) VALUES (:user_id, :contact_id)");
query.bindValue(":user_id", user->getId());
query.bindValue(":contact_id", contactId);
if (!query.exec())
{
qDebug() << "Błąd przy dodawaniu kontaktu do bazy danych:" << query.lastError().text();
}
else
{
qDebug() << "Kontakt został dodany.";
}
}
void UserManager::removeContact(const QString& userNick, int contactId)
{
auto userIter = m_users.find(userNick);
if (userIter != m_users.end())
{
User* userPtr = userIter.value();
if (userPtr)
{
// Usuń kontakt z bazy danych
QSqlQuery query;
query.prepare("DELETE FROM user_contacts WHERE user_id = :user_id AND contact_id = :contact_id");
query.bindValue(":user_id", userPtr->getId());
query.bindValue(":contact_id", contactId);
if (!query.exec())
{
qDebug() << "Błąd przy usuwaniu kontaktu z bazy danych:" << query.lastError().text();
return;
}
// Usuń kontakt z pamięci
userPtr->removeContact(contactId);
// Emituj sygnał informujący o usunięciu kontaktu
//emit contactRemoved(contactId);
}
}
else
{
qDebug() << "Użytkownik " << userNick << " nie istnieje.";
}
}
QString UserManager::getUserNameByID(int id)
{
for (auto &user : m_users)
{
if (user->getId() == id)
{
return user->getNick();
}
}
return QString();
}
QVector<int>UserManager::getContactsForUser(const QString& userNick)
{
User* user = m_users[userNick];
if(user)
{
return user->getContacts();
}
return QVector<int>();
}
bool UserManager::isContactExists(const QString& userNick, int contactId) {
auto userIter = m_users.find(userNick);
if (userIter == m_users.end()) {
return false; // Użytkownik nie znaleziony
}
User* user = userIter.value();
const QVector<int>& contacts = user->getContacts();
return contacts.contains(contactId); // Sprawdź, czy ID kontaktu istnieje w liście kontaktów
}
bool UserManager::changePassword(const QString &oldPassword,const QString &newPassword)
{
User* loggedInUser = findUserbyNick(getLoggedInUserNick());
if (!loggedInUser)
{
qDebug() << "Brak zalogowanego użytkownika.";
return false;
}
if (loggedInUser->getPassword() != oldPassword)
{
qDebug() << "Niepoprawne stare hasło.";
return false;
}
// Zaktualizuj hasło w bazie danych
QSqlDatabase database = QSqlDatabase::database();
QSqlQuery query(database);
query.prepare("UPDATE Uzytkownicy1 SET password = :newPassword WHERE nick = :nick");
query.bindValue(":newPassword", newPassword);
query.bindValue(":nick", loggedInUser->getNick());
if (!query.exec())
{
qDebug() << "Błąd aktualizacji hasła w bazie danych:" << query.lastError().text();
return false;
}
loggedInUser->setPassword(newPassword);
return true;
}
User* UserManager::findUserbyNick(const QString& nick)
{
return m_users.value(nick, nullptr);
}
|
import { fetchComments, addComment, editPost, deleteComment } from '../api/axios'
import { SendOutlined, EditOutlined, DeleteOutlined } from '@ant-design/icons'
import React, { useState, useEffect } from 'react'
import { Button, Input, Space } from 'antd'
import { useUser } from '../UserContext'
import { Link } from 'react-router-dom'
import Comment from './Comment'
function Post({ post, onDeletePost }) {
const { defaultUser } = useUser();
const [comments, setComments] = useState([]);
const [commentText, setCommentText] = useState('');
const [isEditing, setIsEditing] = useState(false);
const [editedText, setEditedText] = useState(post.body);
const [showAllComments, setShowAllComments] = useState(false);
const authorInitials = (name) => {
const nameParts = name.split(' ');
const initials = nameParts.map((part) => part.charAt(0));
return initials.join('');
};
const handleDeleteClick = () => {
onDeletePost(post.id);
};
useEffect(() => {
fetchComments(post.id)
.then((data) => {
setComments(data);
})
.catch((error) => {
console.error('Error fetching comments:', error);
});
}, [post.id]);
const handleCommentSubmit = () => {
if (commentText.trim() === "") {
return;
}
const addedComment = {
name: commentText,
body: commentText,
authorId: defaultUser.id,
authorInitials: authorInitials(defaultUser.name),
authorName: defaultUser.name,
};
addComment(post.id, addedComment)
.then((response) => {
console.log('New comment added:', response);
setComments([response, ...comments]);
setCommentText("");
})
.catch((error) => {
console.error("Error adding comment:", error);
});
};
const handleDeleteComment = (commentId) => {
console.log("Comment ID:", commentId);
deleteComment(commentId)
.then(() => {
const updatedComments = comments.filter((comment) => comment.id !== commentId);
setComments(updatedComments);
console.log("Comment deleted successfully.");
})
.catch((error) => {
console.error("Error deleting comment:", error);
});
};
const handleEditPost = () => {
if (editedText !== post.body) {
const editedPost = {
title: post.title,
body: editedText,
userId: post.userId,
authorInitials: post.authorInitials,
authorName: post.authorName,
};
editPost(post.id, editedPost)
.then((response) => {
console.log('Post edited successfully:', response);
post.body = editedText;
setIsEditing(false);
})
.catch((error) => {
console.error("Error editing comment:", error);
});
}
};
return (
<>
<div className="post" style={{ display: 'flex', alignItems: 'center', marginBottom: '11px', marginTop: '7px' }}>
<Link to={`/profile/${post.userId}`} state={{ post }}>
<div className="author-initials">
<p>{post.authorInitials}</p>
</div>
</Link>
<div style={{ marginLeft: '11px' }}>
<Link to={`/profile/${post.userId}`} state={{ post }}>
<h5>{post.authorName}</h5>
</Link>
</div>
</div>
<div className="post-details" style={{ flex: 1 }}>
<Link to={`/posts/${post.id}`} state={{ post }}>
<h5>{post.title}</h5>
</Link>
</div>
<div className="post-details" style={{ flex: 1 }}>
<div className="post-body">
{isEditing ? (
<>
<Input style={{backgroundColor: "#f0f0f0", color: "black", fontSize: "11px", borderRadius: "0"}}
value={editedText}
onChange={(e) => setEditedText(e.target.value)}
/>
<Button type="text" style={{ backgroundColor: "#f0f0f0", color: "black", height: "30px", fontSize: "11px", fontWeight: "bold", borderRadius: "0", marginTop: '11px', marginBottom: '17px' }} onClick={handleEditPost}>Save</Button>
<Button type="text" style={{ backgroundColor: "#ffffff",color: "black", height: "30px", fontSize: "11px", fontWeight: "bold", borderRadius: "0", marginTop: '11px', marginBottom: '17px' }}onClick={() => setIsEditing(false)}>Cancel</Button>
</>
) : (
<p>
{post.body}
<EditOutlined style={{marginLeft: '11px'}} onClick={() => setIsEditing(true)} />
<DeleteOutlined style={{marginLeft: '7px'}} onClick={handleDeleteClick} />
</p>
)}
</div>
</div>
<div className="post-comments">
{comments.length > 3 && (
<Button
type="text"
style={{
backgroundColor: "#f3f3f3",
color: "black",
fontSize: "11px",
fontWeight: 'bold',
height: "30px",
borderRadius: "0",
marginBottom: '17px'
}}
onClick={() => setShowAllComments(!showAllComments)}
>
{showAllComments ? "Hide previous comments" : "See previous comments"}
</Button>
)}
{showAllComments
? comments.map((comment) => (
<Comment key={comment.id} comment={comment} post={post} onDeleteComment={handleDeleteComment}/>
))
: comments.slice(0, 3).map((comment) => (
<Comment key={comment.id} comment={comment} post={post} onDeleteComment={handleDeleteComment}/>
))}
</div>
<div className="comment-form">
<Space.Compact style={{width: '100%', marginBottom: '11px', marginTop: '7px'}}>
<div className="author-initials" style={{marginRight: '11px'}}>
<p>{authorInitials(defaultUser.name)}</p>
</div>
<Input
type="text"
placeholder="Add a comment ..."
style={{ backgroundColor: "#f3f3f3", borderRadius: "0", color: 'black', fontSize: '11px', height: '31px' }}
bordered={false}
value={commentText}
onChange={(e) => setCommentText(e.target.value)}
/>
<Button
type="text"
focusable={false}
onClick={handleCommentSubmit}
style={{
backgroundColor: "#f3f3f3",
color: "black",
fontSize: "11px",
height: "31px",
borderRadius: "0"
}}
>
<SendOutlined />
</Button>
</Space.Compact>
</div>
</>
);
}
export default Post;
|
use super::Resource;
use crate::{
any::FruityAny,
introspect::{IntrospectFields, IntrospectMethods},
script_value::{ScriptValue, TryFromScriptValue, TryIntoScriptValue},
sync::{Arc, RwLock, RwLockReadGuard, RwLockWriteGuard},
FruityError, FruityResult,
};
use fruity_game_engine_macro::typescript;
use std::ops::{Deref, DerefMut};
/// A reference over an any resource that is supposed to be used by components
#[derive(Debug, Clone, FruityAny)]
pub struct AnyResourceReference {
/// The name of the resource
pub name: String,
/// The resource reference
pub resource: Arc<dyn Resource>,
}
impl AnyResourceReference {
/// Create a resource reference from a resource
pub fn from_native<T: IntrospectFields + IntrospectMethods + Send + Sync + ?Sized>(
name: &str,
resource: Box<T>,
) -> Self {
AnyResourceReference {
name: name.to_string(),
resource: Arc::new(RwLock::new(resource)),
}
}
/// Get the name of the referenced resource
pub fn get_name(&self) -> String {
self.name.clone()
}
/// Get the name of the referenced resource
pub fn downcast<T: IntrospectFields + IntrospectMethods + Send + Sync + ?Sized>(
&self,
) -> Option<ResourceReference<T>> {
self.resource
.clone()
.as_any_arc()
.downcast::<RwLock<Box<T>>>()
.ok()
.map(|resource| ResourceReference::new(&self.name, resource))
}
}
impl IntrospectFields for AnyResourceReference {
fn is_static(&self) -> FruityResult<bool> {
self.resource.is_static()
}
fn get_class_name(&self) -> FruityResult<String> {
self.resource.get_class_name()
}
fn get_field_names(&self) -> FruityResult<Vec<String>> {
self.resource.get_field_names()
}
fn set_field_value(&mut self, _name: &str, _value: ScriptValue) -> FruityResult<()> {
unreachable!()
}
fn get_field_value(&self, name: &str) -> FruityResult<ScriptValue> {
self.resource.get_field_value(name)
}
}
impl IntrospectMethods for AnyResourceReference {
fn get_const_method_names(&self) -> FruityResult<Vec<String>> {
self.resource.get_const_method_names()
}
fn call_const_method(&self, name: &str, args: Vec<ScriptValue>) -> FruityResult<ScriptValue> {
self.resource.call_const_method(name, args)
}
fn get_mut_method_names(&self) -> FruityResult<Vec<String>> {
Ok(vec![])
}
fn call_mut_method(
&mut self,
_name: &str,
_args: Vec<ScriptValue>,
) -> FruityResult<ScriptValue> {
unreachable!()
}
}
impl TryIntoScriptValue for AnyResourceReference {
fn into_script_value(self) -> FruityResult<ScriptValue> {
Ok(ScriptValue::Object(Box::new(self)))
}
}
impl TryFromScriptValue for AnyResourceReference {
fn from_script_value(value: ScriptValue) -> FruityResult<Self> {
match value {
ScriptValue::Object(value) => match value.downcast::<Self>() {
Ok(value) => Ok(*value),
Err(value) => Err(FruityError::InvalidArg(format!(
"Couldn't convert a {} to {}",
value.deref().get_type_name(),
std::any::type_name::<Self>()
))),
},
value => Err(FruityError::InvalidArg(format!(
"Couldn't convert {:?} to native object",
value
))),
}
}
}
/// A reference over a resource that is supposed to be used by components
#[derive(Debug, FruityAny)]
#[typescript("type ResourceReference<T> = T")]
pub struct ResourceReference<T: IntrospectFields + IntrospectMethods + Send + Sync + ?Sized> {
/// The name of the resource
pub name: String,
/// The resource reference
pub resource: Arc<RwLock<Box<T>>>,
}
impl<T: IntrospectFields + IntrospectMethods + Send + Sync + ?Sized> ResourceReference<T> {
/// Create a resource reference from a resource
pub fn new(name: &str, resource: Arc<RwLock<Box<T>>>) -> Self {
ResourceReference {
name: name.to_string(),
resource,
}
}
/// Get the name of the referenced resource
pub fn get_name(&self) -> String {
self.name.clone()
}
/// Create a read guard over the resource
pub fn read(&self) -> ResourceReadGuard<T> {
let inner_guard = self.resource.read();
// Safe cause the resource guard contains an arc to the referenced resource so it will
// not be released until the guard is released
let inner_guard = unsafe {
std::mem::transmute::<RwLockReadGuard<Box<T>>, RwLockReadGuard<'static, Box<T>>>(
inner_guard,
)
};
ResourceReadGuard::<T> {
_referenced: self.resource.clone(),
inner_guard,
}
}
/// Create a write guard over the resource
pub fn write(&self) -> ResourceWriteGuard<T> {
let inner_guard = self.resource.write();
// Safe cause the resource guard contains an arc to the referenced resource so it will
// not be released until the guard is released
let inner_guard = unsafe {
std::mem::transmute::<RwLockWriteGuard<Box<T>>, RwLockWriteGuard<'static, Box<T>>>(
inner_guard,
)
};
ResourceWriteGuard::<T> {
_referenced: self.resource.clone(),
inner_guard,
}
}
}
impl<T: IntrospectFields + IntrospectMethods + Send + Sync + ?Sized> Clone
for ResourceReference<T>
{
fn clone(&self) -> Self {
ResourceReference::<T>::new(&self.name, self.resource.clone())
}
}
impl<T: IntrospectFields + IntrospectMethods + Send + Sync + ?Sized> IntrospectFields
for ResourceReference<T>
{
fn is_static(&self) -> FruityResult<bool> {
self.resource.is_static()
}
fn get_class_name(&self) -> FruityResult<String> {
self.resource.get_class_name()
}
fn get_field_names(&self) -> FruityResult<Vec<String>> {
self.resource.get_field_names()
}
fn set_field_value(&mut self, _name: &str, _value: ScriptValue) -> FruityResult<()> {
unreachable!()
}
fn get_field_value(&self, name: &str) -> FruityResult<ScriptValue> {
self.resource.get_field_value(name)
}
}
impl<T: IntrospectFields + IntrospectMethods + Send + Sync + ?Sized> IntrospectMethods
for ResourceReference<T>
{
fn get_const_method_names(&self) -> FruityResult<Vec<String>> {
self.resource.get_const_method_names()
}
fn call_const_method(&self, name: &str, args: Vec<ScriptValue>) -> FruityResult<ScriptValue> {
self.resource.call_const_method(name, args)
}
fn get_mut_method_names(&self) -> FruityResult<Vec<String>> {
Ok(vec![])
}
fn call_mut_method(
&mut self,
_name: &str,
_args: Vec<ScriptValue>,
) -> FruityResult<ScriptValue> {
unreachable!()
}
}
impl<T> TryIntoScriptValue for ResourceReference<T>
where
T: IntrospectFields + IntrospectMethods + Send + Sync + ?Sized,
{
fn into_script_value(self) -> FruityResult<ScriptValue> {
Ok(ScriptValue::Object(Box::new(self)))
}
}
impl<T> TryFromScriptValue for ResourceReference<T>
where
T: IntrospectFields + IntrospectMethods + Send + Sync + ?Sized,
{
fn from_script_value(value: ScriptValue) -> FruityResult<Self> {
match value {
ScriptValue::Object(value) => match value.downcast::<Self>() {
Ok(value) => Ok(*value),
Err(value) => Err(FruityError::InvalidArg(format!(
"Couldn't convert a {} to {}",
value.deref().get_type_name(),
std::any::type_name::<Self>()
))),
},
value => Err(FruityError::InvalidArg(format!(
"Couldn't convert {:?} to native object",
value
))),
}
}
}
/// A read guard for a resource reference
pub struct ResourceReadGuard<T: IntrospectFields + IntrospectMethods + Send + Sync + ?Sized> {
_referenced: Arc<RwLock<Box<T>>>,
inner_guard: RwLockReadGuard<'static, Box<T>>,
}
impl<'a, T: IntrospectFields + IntrospectMethods + Send + Sync + ?Sized> ResourceReadGuard<T> {
/// Downcast to the original sized type that implement the resource trait
pub fn downcast_ref<U: IntrospectFields + IntrospectMethods + Send + Sync>(&self) -> &U {
self.deref().as_any_ref().downcast_ref::<U>().unwrap()
}
}
impl<'a, T: IntrospectFields + IntrospectMethods + Send + Sync + ?Sized> Deref
for ResourceReadGuard<T>
{
type Target = T;
fn deref(&self) -> &Self::Target {
self.inner_guard.deref()
}
}
/// A write guard for a resource reference
pub struct ResourceWriteGuard<T: IntrospectFields + IntrospectMethods + Send + Sync + ?Sized> {
_referenced: Arc<RwLock<Box<T>>>,
inner_guard: RwLockWriteGuard<'static, Box<T>>,
}
impl<T: IntrospectFields + IntrospectMethods + Send + Sync + ?Sized> ResourceWriteGuard<T> {
/// Downcast to the original sized type that implement the resource trait
pub fn downcast_ref<U: IntrospectFields + IntrospectMethods + Send + Sync>(&self) -> &U {
self.deref().as_any_ref().downcast_ref::<U>().unwrap()
}
}
impl<T: IntrospectFields + IntrospectMethods + Send + Sync + ?Sized> ResourceWriteGuard<T> {
/// Downcast to the original sized type that implement the resource trait
pub fn downcast_mut<U: IntrospectFields + IntrospectMethods + Send + Sync>(
&mut self,
) -> &mut U {
self.deref_mut().as_any_mut().downcast_mut::<U>().unwrap()
}
}
impl<T: IntrospectFields + IntrospectMethods + Send + Sync + ?Sized> Deref
for ResourceWriteGuard<T>
{
type Target = T;
fn deref(&self) -> &Self::Target {
self.inner_guard.deref()
}
}
impl<T: IntrospectFields + IntrospectMethods + Send + Sync + ?Sized> DerefMut
for ResourceWriteGuard<T>
{
fn deref_mut(&mut self) -> &mut Self::Target {
self.inner_guard.deref_mut()
}
}
|
use std::ffi::OsStr;
#[derive(Debug, Clone)]
pub enum MimeType {
Jshp,
Html,
Css,
Txt,
Xml,
Jpeg,
Gif,
Webp,
Png,
Svg,
Icon,
OctetStream,
Js,
Json,
}
impl MimeType {
pub fn to_content_type_string(&self) -> String {
match self {
// TODO change to text/html when js executing is done.
// Wont print now since the syntax is incorrect.
Self::Jshp => "text/plain",
Self::Html => "text/html",
Self::Css => "text/css",
Self::Txt => "text/plain",
Self::Xml => "text/xml",
Self::Jpeg => "image/jpeg",
Self::Gif => "image/gif",
Self::Webp => "image/webp",
Self::Png => "image/png",
Self::Svg => "image/svg+xml",
Self::Icon => "image/x-icon",
Self::OctetStream => "application/octet-stream",
Self::Js => "application/javascript",
Self::Json => "application/json",
}.to_string()
}
}
impl From<&str> for MimeType {
fn from(value: &str) -> Self {
match value.to_lowercase().as_str() {
"jshp" => Self::Jshp,
"html" | "htmls" => Self::Html,
"css" => Self::Css,
"txt" => Self::Txt,
"xml" => Self::Xml,
"gif" => Self::Gif,
"jpeg" => Self::Jpeg,
"jpg" => Self::Jpeg,
"png" => Self::Png,
"svg" => Self::Svg,
"webp" => Self::Webp,
"ico" => Self::Icon,
"js" => Self::Js,
"json" => Self::Json,
_ => Self::OctetStream,
}
}
}
impl From<Option<&OsStr>> for MimeType {
fn from(value: Option<&OsStr>) -> Self {
match value {
Some(ext) => {
let ext = ext.to_str().expect("Should be convertable");
MimeType::from(ext)
},
None => {
Self::OctetStream
}
}
}
}
impl From<String> for MimeType {
fn from(value: String) -> Self {
MimeType::from(value.as_str())
}
}
|
using H3LibraryProject.API.DTOs;
using H3LibraryProject.Repositories.Database;
using H3LibraryProject.Repositories.Repositories;
using H3LibraryProject.Services.Services;
using Moq;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Xunit;
namespace H3LibraryProject.Tests.ServiceTests
{
public class GenreServiceTests
{
private readonly GenreService _service;
private readonly Mock<IGenreRepository> _mockRepository = new();
public GenreServiceTests()
{
_service = new(_mockRepository.Object);
}
[Fact]
public async void CreateGenre_ShouldReturnGenreResponse_whenGenreIsCreated()
{
//Arrange
int id = 1;
Genre genre = new()
{
GenreId = id,
Name = "Test",
LeasePeriod = 14
};
GenreRequest request = new()
{
Name = "Test",
LeasePeriod = 14
};
_mockRepository
.Setup(x => x.InsertNewGenre(It.IsAny<Genre>()))
.ReturnsAsync(genre);
//Act
var result = await _service.CreateGenre(request);
//Assert
Assert.NotNull(result);
Assert.IsType<GenreResponse>(result);
}
[Fact]
public async void CreateGenre_ShouldReturnNull_WhenGenreIsNotCreated()
{
//Arrange
GenreRequest request = new()
{
Name = "Test",
LeasePeriod = 14
};
_mockRepository
.Setup(x => x.InsertNewGenre(It.IsAny<Genre>()))
.ReturnsAsync(() => null);
//Act
var result = await _service.CreateGenre(request);
//Assert
Assert.Null(result);
}
[Fact]
public async void DeleteGenre_ShouldReturnGenreResponse_WhenGenreIsDeleted()
{
//Arrange
int id = 1;
Genre genre = new()
{
GenreId = id,
Name = "Test",
LeasePeriod = 14
};
_mockRepository
.Setup(x => x.DeleteGenre(It.IsAny<int>()))
.ReturnsAsync(genre);
//Act
var result = await _service.DeleteGenre(id);
//Assert
Assert.NotNull(result);
Assert.IsType<GenreResponse>(result);
Assert.Equal(id, result.GenreId);
}
[Fact]
public async void DeleteGenre_ShouldReturnNull_WhenGenreIsNotDeleted()
{
//Arrange
int id = 1;
_mockRepository
.Setup(x => x.DeleteGenre(It.IsAny<int>()))
.ReturnsAsync(() => null);
//Act
var result = await _service.DeleteGenre(id);
//Assert
Assert.Null(result);
}
[Fact]
public async void GetAllGenres_ShouldReturnListOfGenreResponse_WhenGenresExist()
{
//Arrange
int id = 1;
List<Genre> genres = new()
{
new()
{
GenreId = id,
Name = "Test",
LeasePeriod = 14
},
new()
{
GenreId = id+1,
Name = "Test",
LeasePeriod = 14
}
};
_mockRepository
.Setup(l => l.SelectAllGenres())
.ReturnsAsync(genres);
//Act
var result = await _service.GetAllGenres();
//Assert
Assert.NotNull(result);
Assert.IsType<List<GenreResponse>>(result);
Assert.Equal(genres.Count, result.Count);
}
[Fact]
public async void GetAllGenres_ShouldReturnEmptyListOfGenreResponse_WhenNoGenresExist()
{
//Arrange
List<Genre> genres = new();
_mockRepository
.Setup(l => l.SelectAllGenres())
.ReturnsAsync(genres);
//Act
var result = await _service.GetAllGenres();
//Assert
Assert.NotNull(result);
Assert.IsType<List<GenreResponse>>(result);
Assert.Empty(result);
}
[Fact]
public async void GetGenresById_ShouldReturnGenreResponse_WhenTheGenreExist()
{
//Arrange
int id = 1;
Genre genre = new()
{
GenreId = id,
Name = "Test",
LeasePeriod = 14
};
_mockRepository
.Setup(x => x.SelectGenreById(It.IsAny<int>()))
.ReturnsAsync(genre);
//Act
var result = await _service.GetGenreById(id);
//Assert
Assert.NotNull(result);
Assert.IsType<GenreResponse>(result);
Assert.Equal(id, result.GenreId);
}
[Fact]
public async void GetGenresById_ShouldReturnNull_WhenTheGenreDoesNotExist()
{
//Arrange
int id = 1;
_mockRepository
.Setup(x => x.SelectGenreById(It.IsAny<int>()))
.ReturnsAsync(() => null);
//Act
var result = await _service.GetGenreById(id);
//Assert
Assert.Null(result);
}
[Fact]
public async void UpdateGenre_ShouldReturnGenreResponse_WhenTheGenreIsUpdated()
{
//Arrange
int id = 1;
GenreRequest request = new()
{
Name = "Test",
LeasePeriod = 14
};
Genre genre = new()
{
GenreId = id,
Name = "Test",
LeasePeriod = 14
};
_mockRepository
.Setup(x => x.UpdateExistingGenre(It.IsAny<int>(), It.IsAny<Genre>()))
.ReturnsAsync(genre);
//Act
var result = await _service.UpdateGenre(id, request);
//Assert
Assert.NotNull(result);
Assert.IsType<GenreResponse>(result);
}
[Fact]
public async void UpdateGenre_ShouldReturnNull_WhenTheGenreIsNotUpdated()
{
//Arrange
int id = 1;
GenreRequest request = new()
{
Name = "Test",
LeasePeriod = 14
};
_mockRepository
.Setup(x => x.UpdateExistingGenre(It.IsAny<int>(), It.IsAny<Genre>()))
.ReturnsAsync(() => null);
//Act
var result = await _service.UpdateGenre(id, request);
//Assert
Assert.Null(result);
}
}
}
|
import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { AllUsersComponent } from './containers/all-users/all-users.component';
import { CreateUserComponent } from './containers/create-user/create-user.component';
import { EditUserComponent } from './containers/edit-user/edit-user.component';
import { UserFormComponent } from './components/user-form/user-form.component';
import { UsersTableComponent } from './components/users-table/users-table.component';
import {RouterModule, Routes} from "@angular/router";
import {MatFormFieldModule} from "@angular/material/form-field";
import {ReactiveFormsModule} from "@angular/forms";
import {MatInputModule} from "@angular/material/input";
import {MatButtonModule} from "@angular/material/button";
import {MatTableModule} from "@angular/material/table";
const routes: Routes = [
{
path: '',
component: AllUsersComponent
},
{
path: 'create',
component: CreateUserComponent
},
{
path: 'edit/:id',
component: EditUserComponent
}
]
@NgModule({
declarations: [
AllUsersComponent,
CreateUserComponent,
EditUserComponent,
UserFormComponent,
UsersTableComponent
],
imports: [
CommonModule,
RouterModule.forChild(routes),
MatFormFieldModule,
ReactiveFormsModule,
MatInputModule,
MatButtonModule,
MatTableModule
]
})
export class UsersModule { }
|
import React from 'react'
import Typography from '@mui/material/Typography'
import { Avatar, List } from '@mui/material'
import { CalendarMonth, LocationCity, Person } from '@mui/icons-material'
import {
AvatarItem,
TextItem
} from '../../../../atoms/Home/ProjectsContainer/Card'
interface ListAboutProjectProps {
username: string
city: string
date: string
}
export default function ListAboutProject({
username,
city,
date
}: ListAboutProjectProps) {
return (
<Typography variant="body2" color="text.secondary">
<List>
<AvatarItem text={<TextItem>{username}</TextItem>}>
<Avatar sx={{ width: 24, height: 24 }}>
<Person />
</Avatar>
</AvatarItem>
<AvatarItem text={<TextItem>{date}</TextItem>}>
<CalendarMonth sx={{ width: 24, height: 24 }} />
</AvatarItem>
<AvatarItem text={<TextItem>{city}</TextItem>}>
<LocationCity sx={{ width: 24, height: 24 }} />
</AvatarItem>
</List>
</Typography>
)
}
|
package com.Security.SpringSecurity.config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.core.session.SessionRegistry;
import org.springframework.security.core.session.SessionRegistryImpl;
import org.springframework.security.web.SecurityFilterChain;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
@Configuration
@EnableWebSecurity
public class SecurityConfig {
//Firts configuration
/*
@Bean
public SecurityFilterChain filterChain(HttpSecurity httpSecurity) throws Exception{
return httpSecurity
//.csrf().disable() CSRF (CROSS SIDE RESQUEST FORGERY) Deshabilitar la protección CSRF (formularios)
.authorizeHttpRequests()//Para configurar las URL protegidas y las que nó
.requestMatchers("/security/v2").permitAll() //Para agregar los endpoints SIN seguridad
.anyRequest().authenticated()//Para cualquier otro debe estar autenticado
.and() //Para agregar mas seguridad
.formLogin().permitAll() //Para el formulario de autenticación para todos
.and()
.build();
}*/
//Second configuration
/*@Bean
public SecurityFilterChain filterChain(HttpSecurity httpSecurity) throws Exception {
return httpSecurity
.authorizeHttpRequests(auth->{
auth.requestMatchers("/security/v2").permitAll();
auth.anyRequest().authenticated();
})
.formLogin().permitAll()
.and()
.build();
}*/
//Build complete configuration with comments about this topic
@Bean
public SecurityFilterChain filterChain(HttpSecurity httpSecurity) throws Exception {
return httpSecurity
//.csrf().disable() CSRF (CROSS SIDE RESQUEST FORGERY) Deshabilitar la protección CSRF (formularios)
.authorizeHttpRequests(auth->{ //Para configurar las URL protegidas y las que nó
auth.requestMatchers("/security/v2").permitAll(); //Para agregar los endpoints SIN seguridad
auth.anyRequest().authenticated(); //Para indicar que cualquier otro debe estar autenticado
})
.formLogin() //Para el formulario de autenticación para todos
.successHandler(successHandler()) // URL para la redirección indicada en la funcion de abajo
.permitAll() //Para que todas las paginas bloqueadas tengas el formulario
.and()
.sessionManagement() // Para configurar el comportamiento de las sessiones
.sessionCreationPolicy(SessionCreationPolicy.ALWAYS) //ALWAYS - IF_REQUIRED - NEVER - STATELESS
//Always: Va a crear una sesión siempre que no haya una creada, si existe una la va a reutilizar
//IF_REQUIRED: Crea una nueva sesion solo si es necesario, si no es existe crea una
//NEVER: No crea ninguna sesion, utiliza una si ya esta creada sino no hace nada
//STATELESS: No crea ninguna sesion, todas las solicitudes las trabaja independendiente y no guarda nada
.invalidSessionUrl("https://google.es") //Si la sesion es invalida (no autentica) se redirige a la direccion indicada
.maximumSessions(1)// Cantidad maxima de sesiones abiertas por usuario
.expiredUrl("/login") //Sirve para que al expirar la sesion de usuario lo redirija a la ubicacion indicada
.sessionRegistry(sessionRegistry()) //Este se encarga de administrar el registro de los usuarios
.and()
.sessionFixation() //Sirve para evitar que un usuario vulnere la seguridad y usar su sesion de forma indefinida
.migrateSession() // Sirve para cuando la aplicación sea atacada cambiar el ID de sesion
//.newSession() // Crea una nueva sesion cuando sea atacada la app
//.none() // Inavilita la fixation
.and()
.httpBasic()// Es una autenticación basica, se envia el usuario y contraseña en el header. Pruebas en postman
.and()
.build();
}
@Bean
public SessionRegistry sessionRegistry(){
return new SessionRegistryImpl();
}
public AuthenticationSuccessHandler successHandler(){
return ((request, response, authentication) -> {
response.sendRedirect("/security/session");
});
}
}
|
<html>
<head>
<title>Sapphire</title>
</head>
<body>
<div id="container"></div>
<script src="https://visjs.github.io/vis-network/standalone/umd/vis-network.min.js"></script>
<script type="text/javascript">
var ws;
var visNodes = null
var visEdges = null
var previousData = null;
if (window.WebSocket === undefined) {
document.getElementById("container").append("Your browser does not support WebSockets")
} else {
ws = initWS();
}
function initWS() {
var prefix = "wss://"
if (window.location.protocol == "http:") {
prefix = "ws://"
}
var socket = new WebSocket(prefix + window.location.host + "/ws"),
container = document.getElementById("container")
socket.onopen = function () {
};
socket.onmessage = function (e) {
wsMessage = JSON.parse(e.data)
switch (wsMessage.Action) {
case "init":
genGraph(wsMessage.Content)
break;
case "service.create":
addNode(wsMessage.Content, "service")
break;
case "service.remove":
removeNode(wsMessage.Content, "service")
break;
case "network.create":
addNode(wsMessage.Content, "network")
break;
case "network.destroy":
removeNode(wsMessage.Content, "network")
break;
case "network.connect":
addNetworkConnection(wsMessage.Content)
break;
}
}
socket.onclose = function () {
}
return socket;
}
function addNetworkConnection(relation) {
visEdges.add({
from: "network-" + relation.Network,
to: "service-" + relation.Service,
})
}
function addNode(name, type) {
visNodes.add({
id: type + "-" + name,
label: name,
group: type
})
}
function removeNode(name, type) {
visNodes.remove({
id: type + "-" + name,
})
}
function genGraph(data) {
var nodes = []
var edges = []
for (var serviceName in data.Services) {
if (serviceName == "") continue;
nodes.push({
id: "service-" + serviceName,
label: serviceName,
group: 'service'
})
}
for (var networkName in data.Networks) {
if (networkName == "ingress") continue;
var network = data.Networks[networkName]
if (!network.Services || network.Services.length < 1) {
console.log("network not for services", network);
continue;
}
nodes.push({
id: "network-" + networkName,
label: networkName,
group: 'network'
})
for (var serviceName in data.Networks[networkName].Services) {
edges.push({
from: "network-" + networkName,
to: "service-" + serviceName
})
}
}
// create a network
var container = document.getElementById('container');
var data = {
nodes: visNodes = new vis.DataSet(nodes),
edges: visEdges = new vis.DataSet(edges),
};
var options = {
edges: {
color: "#CCC",
smooth: true
},
layout: {improvedLayout: true},
physics: {
barnesHut: {gravitationalConstant: -30000, avoidOverlap: 0.9},
stabilization: {iterations: 2500}
},
groups: {
'network': {
color: "#2B7CE9",
shape: 'image',
image: "/images/network.svg"
},
'service': {
shape: 'image',
color: "#C5000B",
image: "/images/service.svg"
},
'container': {
shape: 'image',
color: "#C5000B",
image: "/images/container.svg"
},
}
};
var network = new vis.Network(container, data, options);
}
/* */
</script>
</body>
</html>
|
import React, { useContext } from 'react'
import { ProductContext } from '../context/ProductContext';
import { Button, Card, Container } from 'react-bootstrap';
import { LinkContainer } from 'react-router-bootstrap';
import { useParams } from 'react-router-dom';
import { useCart } from 'react-use-cart';
import { ToastContainer, toast } from 'react-toastify';
import 'react-toastify/dist/ReactToastify.css';
const ProductDetails = () => {
const [products] = useContext(ProductContext);
const { addItem } = useCart();
const notify = () => toast.success('Product added!', {
position: "bottom-right",
autoClose: 3000,
hideProgressBar: false,
closeOnClick: true,
pauseOnHover: true,
draggable: true,
progress: undefined,
theme: "colored",
});
const { url } = useParams();
const details = products.find(item => item.id == url);
return (
<>
{details === undefined ? <h1>Loading...</h1> :
<Container className='text-center mt-5'>
<Card className='mx-5 details-card d-flex flex-row justify-content-center align-items-center border-0'>
<Card.Img src={details.image} style={{ width: "400px" }} />
<Card.Body>
<Card.Title>{details.title}</Card.Title>
<Card.Text>
<p><span>Description:</span> {details.description}</p>
<p className='fs-3 mt-3'>{details.price} $</p>
</Card.Text>
<LinkContainer to="/products">
<Button variant='danger'>Back to products</Button>
</LinkContainer>
<Button variant='warning ms-3' onClick={() => { notify(addItem(details)) }}>Add to cart</Button>
</Card.Body>
</Card>
<ToastContainer
position="top-right"
autoClose={1000}
hideProgressBar={false}
newestOnTop={false}
closeOnClick
rtl={false}
pauseOnFocusLoss
draggable
pauseOnHover
theme="colored"
/>
</Container>
}
</>
)
}
export default ProductDetails
|
const { ShareDoesntValidError, ShareCreatedSuccessfully, ShareUpdatedSuccessfully } = require('../messages/messages')
const container = require('../../src/container');
class ShareController {
constructor() {
this.ShareRepository = container.resolve('ShareRepository');
}
async getShareByName(req, res) {
let name = req.params.name;
return await this.ShareRepository.getShareByName(name).then((share) => {
return res.status(200).json({share})
}).catch(err => {
return res.status(400).json({err})
});
}
async createShare(req, res) {
let { name, amount } = req.body
await this.ShareRepository.create({ name, amount }).then((share) => {
return res.status(201).json({
"message": ShareCreatedSuccessfully,
share
})
}).catch(err => {
return res.status(400).json({err})
});
}
async bulkCreateShare(req, res) {
let { shares } = req.body
await this.ShareRepository.bulkCreate(shares).then((share) => {
return res.status(201).json({
"message": ShareCreatedSuccessfully,
share
})
}).catch(err => {
return res.status(400).json({err})
});
}
async updateShareAmount(req, res) {
let { name, amount } = req.body
const share = await this.ShareRepository.getShareByName(name)
if(share != null) {
await this.ShareRepository.update(amount, name).then(async () => {
return res.status(201).json({
"message": ShareUpdatedSuccessfully,
"name": name,
"amount": amount
})
}).catch(err => {
return res.status(400).json({err})
});
} else {
return res.status(400).json({"message": ShareDoesntValidError});
}
}
}
module.exports = new ShareController();
|
---
title: "Running GBRS"
teaching: 60
exercises: 60
---
:::::::::::::::::::::::::::::::::::::: questions
- How do I run GBRS on my FASTQ files at JAX?
- How do I run GBRS on my FASTQ files at another institution?
::::::::::::::::::::::::::::::::::::::::::::::::
::::::::::::::::::::::::::::::::::::: objectives
- At JAX: analyze FASTQ files using GBRS on the High Performance Computing cluster.
- At other institutions: configure Nexflow and the reference files and analyze
FASTQ files using GBRS.
::::::::::::::::::::::::::::::::::::::::::::::::
## At the Jackson Laboratory (JAX)
The GBRS Nextflow pipeline is configured to run on *sumner*, the High Performance
Computing (HPC) cluster at JAX.
We will consider two scenarios:
1. You are analyzing expression data from Diversity Outbred mice;
1. You are analyzing expression data from some other cross;
### GBRS for Diversity Outbred Mice
The Next-Generaiong Operations (NGSOps) team has configured the default
arrguments for the GBRS Nextflow pipeline to use the reference files for GRCm39
and Ensembl version 105. This means that the arguments that point GBRS to the
locations of the founder genomes, founder transcriptomes, and aligner indices
are already set.
Here is the entire script:
```
#!/bin/bash
#SBATCH --qos=batch # job queue
#SBATCH --ntasks=1 # number of nodes
#SBATCH --cpus-per-task=1 # number of cores
#SBATCH --mem=1G # memory pool for all cores
#SBATCH --time=48:00:00 # wall clock time (D-HH:MM)
################################################################################
# Run GBRS on each sample. GRCm39. Ensembl 105.
#
# Daniel Gatti
# dan.gatti@jax.org
# 2022-09-28
################################################################################
set -e -u -x -o pipefail
##### VARIABLES #####
# Base directory for project.
BASE_DIR=/projects/research_lab_directory/diabetes
# Sample metadata file.
SAMPLE_META_FILE=${BASE_DIR}/data/gbrs_sample_metadata.csv
# Base /flashscratch directory.
FLASHSCRATCH=/flashscratch/dgatti
# Temporary working directory.
TMP_DIR=${FLASHSCRATCH}/tmp
# Temporary output directory.
OUT_DIR=${FLASHSCRATCH}/results
# Final results directory (in backed up space)
DEST_DIR=${BASE_DIR}/results
# GBRS path.
GBRS_GITHUB_PATH=TheJacksonLaboratory/cs-nf-pipelines
# GBRS version on Github.
GBRS_VERSION=v0.4.2
# Singularity cache directory.
#export NXF_SINGULARITY_CACHEDIR=${flashscratch}/singularity_cache
##### MAIN #####
mkdir -p ${OUT_DIR}
mkdir -p ${DEST_DIR}
mkdir -p ${TMP_DIR}
#mkdir -p ${NXF_SINGULARITY_CACHEDIR}
module load singularity
cd ${TMP_DIR}
nextflow run ${GBRS_GITHUB_PATH} \
-r ${GBRS_VERSION} \
-profile sumner \
-w ${TMP_DIR} \
--workflow gbrs \
--pubdir ${OUT_DIR} \
--csv_input ${SAMPLE_META_FILE} \
-resume
# Copy output files from OUT_DIR to DEST_DIR.
DIRS=`(ls ${OUT_DIR})`
for i in ${DIRS}
do
cp ${OUT_DIR}/${i}/stats/* ${DEST_DIR}
cp ${OUT_DIR}/${i}/gbrs/*_counts ${DEST_DIR}
cp ${OUT_DIR}/${i}/gbrs/*.tsv ${DEST_DIR}
cp ${OUT_DIR}/${i}/gbrs/*.pdf ${DEST_DIR}
done
# Clean up tmp directory.
rm -rf ${TMP_DIR}
```
For Diversity Outbred (DO) mice, the reference files are stored in the
reference data directories `/projects/omics_share` on *sumner*.
JAX uses [slurm](https://jacksonlaboratory.sharepoint.com/sites/ResearchIT/SitePages/Submitting-Basic-Jobs-with-SLURM.aspx)
(NOTE: This is an internal JAX link which requires a JAX login.) to manage
computing jobs on *sumner*. There are several good tutorials on using *slurm*
on the JAX [Research IT Documentation Library](https://jacksonlaboratory.sharepoint.com/sites/ResearchIT/SitePages/Documentation.aspx).
#### *slurm* Options Block
*slurm* scripts are *bash* scripts, so they start with:
```
#!/bin/bash
```
Next, we use a *slurm* options block to tell *slurm* what computing resources
we would like to use. You could pass *slurm* options in at the command line, but
we recommend using an options block in your script so that you have a record of
the resources required to run your job.
Each line in the *slurm* options block starts with:
```
#SBATCH
```
This tells *slurm* that what follows on this line is a *slurm* option. There
are many *slurm* options, which are exhaustively enumerated in the
[slurm documentation](https://slurm.schedmd.com/sbatch.html). Here we will use
only a few of the options:
```
#SBATCH --qos=batch # job queue
#SBATCH --ntasks=1 # number of nodes
#SBATCH --cpus-per-task=1 # number of cores
#SBATCH --mem=1G # memory pool for all cores
#SBATCH --time=48:00:00 # wall clock time (D-HH:MM)
```
The first option specifies the job queue to use for this job. In this case, it
is the "batch" queue on *sumner*.
```
#SBATCH --qos=batch # job queue
```
The next two options specify the number of nodes and number of CPUs (or cores)
per node to use. In this case, we will use one node and one CPU. This may seem
confusing because we would like to use many nodes and cores to reduce the total
run time of our job. But Nextflow handles resource request. This script just
starts the Nextflow job, which does not require many resources. If you request
more nodes and CPUs here, you will only be tying up resources that will sit
idle while your job run. So **one** node and **one** CPU per node are sufficient.
```
#SBATCH --ntasks=1 # number of nodes
#SBATCH --cpus-per-task=1 # number of cores
```
The next option specifies the memory required for this task. We will request
one Gigabyte (G). Again, this may seem like a small amount of memory for a
large computational job, but this is only the memeory required to start and
manage the Nextflow job. Nextflow will request the resources that it needs to
run GBRS.
```
#SBATCH --mem=1G # memory pool for all cores
```
The last option that we will speicify is the total wall-clock time needed to
complete the job. This needs to be the total amount of time required to complete
the job. This can be difficult to estimate and depends upon the number of
samples, depth of coverage, and the configuration and utilization of the cluster.
> DMG: TBD: Should we run 50, 100, 200 & 300 samples and include a time/samples plot?
I have 350 samples that we could use for this. It's not going to be linear with
more sample, but it's something.
```
#SBATCH --time=48:00:00 # wall clock time (D-HH:MM)
```
#### Header Section
```
################################################################################
# Run GBRS on each sample. GRCm39. Ensembl 105.
#
# Daniel Gatti
# dan.gatti@jax.org
# 2022-09-28
################################################################################
```
This section is not required, but it allows you to add some comments about what
are doing. It is also a consistent place to put your name, contact information,
and the date. Putting your name and contact information helps to keep you
accountable for the code. Putting the date in the header helps you to remember
when you wrote the script.
#### Error Handling
```
set -e -u -x -o pipefail
```
This commands tells *bash* to exit if any line of the script fails (-e), to
catch uninitialized variables (-u), to print commands as we run (-x), and to
output the last exit code (-o).
#### Variable Section
We strongly recommend that you use *bash* variables to build file paths and
specify arguments to the GBRS script. The reason for this is that it is easier
to remember what each varible is when it is given a meaningful name.
Consider this script which runs the "analysis_tool_of_science":
```
analysis_tool_of_science -t 8 \
-g /path/to/another/file \
-a /really/long/path/to/yet/another/file \
-i /path/to/mystery/file/number1 /path/to/mystery/file/number2 \
-x /path/to/some/directory/on/the/cluster
-o /path/to/another/directory/with/a/file/prefix
```
You can read the tool's documentation to find out what each file is, but that
requires extra time. This script would be easier to read if the paths had
meaningful names. In the code block below, we give each file a meaningful
variable name and provide a comment explaining what each file is. We also use
this opportunity to specify the genome and annotation builds.
```
# FASTA file containing genome sequence for GRCm39.
GENOME_FASTA=/path/to/another/file
# GTF file containing genome annotation for Ensembl 105.
ANNOTATION_GTF=/really/long/path/to/yet/another/file
# Paths to the forward and reverse FASTQ files.
FASTQ_FILE1=/path/to/mystery/file/number1
FASTQ_FILE2=/path/to/mystery/file/number2
# Path to temporary directory for analysis_tool.
TEMP_DIR=/path/to/some/directory/on/the/cluster
# Path to output file, with a file prefix.
OUTPUT_PATH=/path/to/another/directory/with/a/file/prefix
analysis_tool_of_science -t 8 \
-g ${GENOME_FASTA} \
-a ${ANNOTATION_GTF} \
-i $(FASTQ_FILE1} ${FASTQ_FILE2} \
-x ${TEMP_DIR}
-o ${OUTPUT_PATH}
```
This makes the script much easier for yourself (a year from now) and others
to read and understand.
First, we will focus on variables that set the location of your files and
working directories.
```
# Base directory for project.
BASE_DIR=/projects/research_lab_directory/diabetes
```
We like to set a "base directory", which is the high-level directory for the
project on which you are working. In this case, we are using a diabetes project
as an example. We use the base directory to create other file paths which
are below this directory.
```
# Sample metadata file.
SAMPLE_META_FILE=${BASE_DIR}/data/sodo_gbrs_metadata.csv
```
This is the path to the sample metadata file, which contains information
about your samples. This includies the sample ID, sex, outbreeding generation,
sequencer lane, and paths to the forward and reverse FASTQ files. Each row will
contain information for one sample.
The `sampleID` column should contain values that you use to identify the samples.
The `sex` column should contain the mouse's sex recorded as 'F' for females or
'M' for males.
The `generation` column should contain the outbreeding generation for the mouse.
The `lane` column should contain the lane number on which the sample was run.
This can sometimes be found in the FASTQ file name. In the example below, it is
recorded as 'L004' in the FASTQ file names and this is what we used in the
`lane` column.
The `fastq_1` and `fastq_2` columns contain the full path to the forward and
reverse FASTQ files. In this case, we copied the files to /flashscratch, which
is the temporary sratch storage space for large files.
Below is an example of the top of a sample metadata file. It is comma-delimited
and has column names as the top.
```
sampleID,sex,generation,lane,fastq_1,fastq_2
D2,F,46,L004,/flashscratch/dgatti/fastq/D2_GT22-11729_CTAGGCAT-ACAGAGGT_S224_L004_R1_001.fastq.gz,/flashscratch/dgatti/fastq/D2_GT22-11729_CTAGGCAT-ACAGAGGT_S224_L004_R2_001.fastq.gz
D3,F,46,L001,/flashscratch/dgatti/fastq/D3_GT22-11665_CGGCTAAT-CTCGTTCT_S21_L001_R1_001.fastq.gz,/flashscratch/dgatti/fastq/D3_GT22-11665_CGGCTAAT-CTCGTTCT_S21_L001_R2_001.fastq.gz
D4,F,46,L001,/flashscratch/dgatti/fastq/D4_GT22-11670_TACGCTAC-CGTGTGAT_S65_L001_R1_001.fastq.gz,/flashscratch/dgatti/fastq/D4_GT22-11670_TACGCTAC-CGTGTGAT_S65_L001_R2_001.fastq.gz
D5,F,46,L001,/flashscratch/dgatti/fastq/D5_GT22-11708_GAGCAGTA-TGAGCTGT_S57_L001_R1_001.fastq.gz,/flashscratch/dgatti/fastq/D5_GT22-11708_GAGCAGTA-TGAGCTGT_S57_L001_R2_001.fastq.gz
```
Notice that we have copied the FASTQ files over to /flashscratch. This isn't
required but we do this to simplify the file paths.
```
# Base /flashscratch directory.
FLASHSCRATCH=/flashscratch/username
```
This is the path to your directory on /flashscratch. You should create this
before you begin your analysis. And you should replace 'username' with your
username.
```
# Temporary directory.
TMP_DIR=${FLASHSCRATCH}/tmp
```
This is the path to the temporary directory where Nextflow and GBRS can store
temporary working files during the analysis.
```
# Output directory.
OUT_DIR=${FLASHSCRATCH}/results
```
This is the directory where you would like GBRS to write your results. You
should place this on /flashscratch and then copy the files that you need over
to /projects when the analysis is complete.
```
# Final results directory (in backed up space)
DEST_DIR=${BASE_DIR}/results/gbrs
```
This is the directory to which you will copy your final results. It should be
a location that is backed up (like /projects). Remember, /flashscratch is not
backed up and your files will be deleted without notice after 10 days.
Once you have set all of the paths and created your sample metadata file, you
can submit the script to the *slurm* queue. Save the script to a file called
'run_gbrs.sh', and then submit it using 'sbatch'.
```
sbatch run_gbrs.sh
```
### GBRS for Other Mouse Crosses
workflow GBRS {
// Step 0: Download data and concat Fastq files if needed.
meta_ch = null
if (params.download_data){
FILE_DOWNLOAD(ch_input_sample)
if (params.read_type == 'PE'){
FILE_DOWNLOAD.out.read_meta_ch.map{it -> [it[0], it[2][0], 'R1']}.set{r1}
FILE_DOWNLOAD.out.read_meta_ch.map{it -> [it[0], it[2][1], 'R2']}.set{r2}
read_ch = r1.mix(r2)
} else if (params.read_type == 'SE'){
FILE_DOWNLOAD.out.read_meta_ch.map{it -> [it[0], it[2][0], 'R1']}.set{read_ch}
}
FILE_DOWNLOAD.out.read_meta_ch.map{it -> [it[0], it[1]]}.set{meta_ch}
}
// Step 00: Concat local Fastq files from CSV input if required.
if (!params.download_data && params.csv_input){
CONCATENATE_LOCAL_FILES(ch_input_sample)
if (params.read_type == 'PE'){
CONCATENATE_LOCAL_FILES.out.read_meta_ch.map{it -> [it[0], it[2][0], 'R1']}.set{r1}
CONCATENATE_LOCAL_FILES.out.read_meta_ch.map{it -> [it[0], it[2][1], 'R2']}.set{r2}
read_ch = r1.mix(r2)
} else if (params.read_type == 'SE'){
CONCATENATE_LOCAL_FILES.out.read_meta_ch.map{it -> [it[0], it[2][0], 'R1']}.set{read_ch}
}
CONCATENATE_LOCAL_FILES.out.read_meta_ch.map{it -> [it[0], it[1]]}.set{meta_ch}
}
// Step 00: Concatenate Fastq files if required.
if (params.concat_lanes && !params.csv_input){
if (params.read_type == 'PE'){
CONCATENATE_READS_PE(read_ch)
temp_read_ch = CONCATENATE_READS_PE.out.concat_fastq
temp_read_ch.map{it -> [it[0], it[1][0], 'R1']}.set{r1}
temp_read_ch.map{it -> [it[0], it[1][1], 'R2']}.set{r2}
read_ch = r1.mix(r2)
} else if (params.read_type == 'SE'){
CONCATENATE_READS_SE(read_ch)
temp_read_ch = CONCATENATE_READS_SE.out.concat_fastq
temp_read_ch.map{it -> [it[0], it[1], 'R1']}.set{read_ch}
}
}
RUN_EMASE(read_ch)
// workflow found in: subworkflows/run-emase
if (meta_ch) {
RUN_EMASE.out.emase_genes_tpm.join(meta_ch)
.map{it -> [it[0], it[1], it[2].sex, it[2].generation]}
.set{grbs_recon_input}
} else {
RUN_EMASE.out.emase_genes_tpm
.map{it -> [it[0], it[1], params.sample_sex, params.sample_generation]}
.set{grbs_recon_input}
}
GBRS_RECONSTRUCT(grbs_recon_input)
GBRS_QUANTIFY_GENOTYPES(RUN_EMASE.out.compressed_emase_h5.join(GBRS_RECONSTRUCT.out.genotypes_tsv))
GBRS_INTERPOLATE(GBRS_RECONSTRUCT.out.genoprobs_npz)
GBRS_PLOT(GBRS_INTERPOLATE.out.interpolated_genoprobs)
GBRS_EXPORT(GBRS_INTERPOLATE.out.interpolated_genoprobs)
}
For Diversity Outbred (DO) mice, the reference files are stored in the
reference data directories `/projects/omics_share` on *sumner*. We will use
these files as examples ot show you which arguments to provide.
JAX uses [slurm](https://jacksonlaboratory.sharepoint.com/sites/ResearchIT/SitePages/Submitting-Basic-Jobs-with-SLURM.aspx)
(NOTE: This is an internal JAX link which requires a JAX login.) to manage
computing jobs on *sumner*. There are several good tutorials on using *slurm*
on the JAX [Research IT Documentation Library](https://jacksonlaboratory.sharepoint.com/sites/ResearchIT/SitePages/Documentation.aspx).
#### *slurm* Options Block
*slurm* scripts are *bash* scripts, so they start with:
```
#!/bin/bash
```
Next, we use a *slurm* options block to tell *slurm* what computing resources
we would like to use. You could pass *slurm* options in at the command line, but
we recommend using an options block in your script so that you have a record of
the resources required to run your job.
Each line in the *slurm* options block starts with:
```
#SBATCH
```
This tells *slurm* that what follows on this line is a *slurm* option. There
are many *slurm* options, which are exhaustively enumerated in the
[slurm documentation](https://slurm.schedmd.com/sbatch.html). Here we will use
only a few of the options:
```
#SBATCH --qos=batch # job queue
#SBATCH --ntasks=1 # number of nodes
#SBATCH --cpus-per-task=1 # number of cores
#SBATCH --mem=1G # memory pool for all cores
#SBATCH --time=48:00:00 # wall clock time (D-HH:MM)
```
The first option specifies the job queue to use for this job. In this case, it
is the "batch" queue on *sumner*.
```
#SBATCH --qos=batch # job queue
```
The next two options specify the number of nodes and number of CPUs (or cores)
per node to use. In this case, we will use one node and one CPU. This may seem
confusing because we would like to use many nodes and cores to reduce the total
run time of our job. But Nextflow handles resource request. This script just
starts the Nextflow job, which does not require many resources. If you request
more nodes and CPUs here, you will only be tying up resources that will sit
idle while your job run. So **one** node and **one** CPU per node are sufficient.
```
#SBATCH --ntasks=1 # number of nodes
#SBATCH --cpus-per-task=1 # number of cores
```
The next option specifies the memory required for this task. We will request
one Gigabyte (G). Again, this may seem like a small amount of memory for a
large computational job, but this is only the memeory required to start and
manage the Nextflow job. Nextflow will request the resources that it needs to
run GBRS.
```
#SBATCH --mem=1G # memory pool for all cores
```
The last option that we will speicify is the total wall-clock time needed to
complete the job. This needs to be the total amount of time required to complete
the job. This can be difficult to estimate and depends upon the number of
samples, depth of coverage, and the configuration and utilization of the cluster.
> DMG: TBD: Should we run 50, 100, 200 & 300 samples and include a time/samples plot?
I have 350 samples that we could use for this. It's not going to be linear with
more sample, but it's something.
```
#SBATCH --time=48:00:00 # wall clock time (D-HH:MM)
```
#### Header Section
This section is not required, but it allows you to add some comments about what
are doing. It is also a consistent place to put your name, contact information,
and the date. Putting your name and contact information helps to keep you
accountable for the code. Putting the date in the header helps you to remember
when you wrote the script.
```
################################################################################
# Run GBRS on each sample.
# GRCm39. Ensembl 105.
#
# Daniel Gatti
# dan.gatti@jax.org
# 2022-09-28
################################################################################
```
#### Variable Section
We strongly recommend that you use *bash* variables to build file paths and
specify arguments to the GBRS script. The reason for this is that it is easier
to remember what each varible is when it is given a meaningful name.
Consider this script which runs the "analysis_tool_of_science":
```
analysis_tool_of_science -t 8 \
-g /path/to/another/file \
-a /really/long/path/to/yet/another/file \
-i /path/to/mystery/file/number1 /path/to/mystery/file/number2 \
-x /path/to/some/directory/on/the/cluster
-o /path/to/another/directory/with/a/file/prefix
```
You can read the tool's documentation to find out what each file is, but that
requires extra time. It would be easier to read if the paths had meaningful
names. In the code block below, we give each file a meaningful variable name
and prrovide a comment explaining what each file is. We also use this
opportunity to specify the genome and annotation builds.
```
# FASTA file containing genome sequence for GRCm39.
GENOME_FASTA=/path/to/another/file
# GTF file containing genome annotation for Ensembl 105.
ANNOTATION_GTF=/really/long/path/to/yet/another/file
# Paths to the forward and reverse FASTQ files.
FASTQ_FILE1=/path/to/mystery/file/number1
FASTQ_FILE2=/path/to/mystery/file/number2
# Path to temporary directory for analysis_tool.
TEMP_DIR=/path/to/some/directory/on/the/cluster
# Path to output file, with a file prefix.
OUTPUT_PATH=/path/to/another/directory/with/a/file/prefix
analysis_tool_of_science -t 8 \
-g ${GENOME_FASTA} \
-a ${ANNOTATION_GTF} \
-i $(FASTQ_FILE1} ${FASTQ_FILE2} \
-x ${TEMP_DIR}
-o ${OUTPUT_PATH}
```
This makes the script much easier for yourself (a year from now) and others
to read and understand.
The GBRS script has a lot of variables. We will explain each one so that you
know what to use for your samples.
In this first section, we will focus on variables that set the location of
your files and working directories.
```
# Base directory for project.
BASE_DIR=/projects/research_lab_directory/diabetes
```
We like to set a "base directory", which is the high-level directory for the
project which you are working on. In this case, we are using a diabetes project
as an example. We use the base directory to create other file paths which
are below this directory.
```
# Sample metadata file.
SAMPLE_META_FILE=${BASE_DIR}/data/sodo_gbrs_metadata.csv
```
This is the path to the sample metadata file. This file contains information
about your samples, including the sample ID, sex, outbreeding generation,
sequencer lane, and paths to the forward and reverse FASTQ files. Each row will
contain information for one sample.
The `sampleID` should contain values that you use to identify the samples.
The `sex` column should contain the mouse's sex recorded as 'F' for females or
'M' for males.
The `generation` column should contain the outbreeding generation for the mouse.
The `lane` column should contain the lane number on which the sample was run.
This can sometimes be found in the FASTQ file name. In the example below, it is
recorded as 'L004' in the FASTQ file names and this is what we used in the
`lane` column.
The `fastq_1` and `fastq_2` columns contain the full path to the forward and
reverse FASTQ files. In this case, we copied the files to /flashscratch, which
is the temporary sratch storage space for large files.
> DMG: TBD: explain why we should copy the files over to /flashscrath instead
of using them from /projects.
```
sampleID,sex,generation,lane,fastq_1,fastq_2
D2,F,46,L004,/flashscratch/dgatti/fastq/D2_GT22-11729_CTAGGCAT-ACAGAGGT_S224_L004_R1_001.fastq.gz,/flashscratch/dgatti/fastq/D2_GT22-11729_CTAGGCAT-ACAGAGGT_S224_L004_R2_001.fastq.gz
D3,F,46,L001,/flashscratch/dgatti/fastq/D3_GT22-11665_CGGCTAAT-CTCGTTCT_S21_L001_R1_001.fastq.gz,/flashscratch/dgatti/fastq/D3_GT22-11665_CGGCTAAT-CTCGTTCT_S21_L001_R2_001.fastq.gz
D4,F,46,L001,/flashscratch/dgatti/fastq/D4_GT22-11670_TACGCTAC-CGTGTGAT_S65_L001_R1_001.fastq.gz,/flashscratch/dgatti/fastq/D4_GT22-11670_TACGCTAC-CGTGTGAT_S65_L001_R2_001.fastq.gz
D5,F,46,L001,/flashscratch/dgatti/fastq/D5_GT22-11708_GAGCAGTA-TGAGCTGT_S57_L001_R1_001.fastq.gz,/flashscratch/dgatti/fastq/D5_GT22-11708_GAGCAGTA-TGAGCTGT_S57_L001_R2_001.fastq.gz
```
```
# Base /flashscratch directory.
FLASHSCRATCH=/flashscratch/username
```
This is the path to your directory on /flashscratch. You should create this
before you begin your analysis.
```
# Temporary directory.
TMP_DIR=${FLASHSCRATCH}/tmp
```
This is the path to the temporary directory where Nextflow and GBRS can store
temporary working files during the analysis.
```
# Output directory.
OUT_DIR=${FLASHSCRATCH}/results
```
This is the directory where you would like GBRS to write your results. You
should place this on /flashscratch and then copy the files that you need over
to /projects when the analysis is complete.
```
# Final results directory (in backed up space)
DEST_DIR=${BASE_DIR}/results/gbrs
```
This is the directory to which you will copy your final results. It should be
a location that is backed up (like /projects). Remember, /flashscratch is not
backed up and your files will be deleted without notice after 10 days.
In the next section, we will focus on the reference files that are required by
GBRS.
```
# GBRS Reference File Directory
GBRS_REF_DIR=/projects/omics_share/mouse/GRCm39/supporting_files/emase_gbrs/rel_2112_v8
```
This is the directory where the GBRS reference files are stored. These are a
series of files which contain information about genes and transcripts in the
eight DO founder strains. The numbers in the directory refere to the
[Sanger Mouse Genomes Project](https://www.sanger.ac.uk/data/mouse-genomes-project/)
release. "2112" refers to the 12th month of 2021. "v8" refers to version 8 of
their genetic variant release.
There are eight arguments that point to the reference files used by GBRS.
```
# GBRS Transcripts.
GBRS_TRANSCRIPTS=${GBRS_REF_DIR}/emase.fullTranscripts.info
```
This file contains the list of transcripts in Ensembl 105 that GBRS will quantify.
```
# GBRS/EMASE gene to transcript file.
GBRS_GENE2TRANS=${GBRS_REF_DIR}/emase.gene2transcripts.tsv
```
This file contains the list of transcripts which map to each gene. Each row
contains one gene, followed by its associated Ensembl transcripts.
```
# GBRS Full Transcript.
GBRS_FULL_TRANSCRIPTS=${GBRS_REF_DIR}/emase.pooled.fullTranscripts.info
```
This file contains a list of transcript lengths in each of the eight DO founders.
> DMG: Confirm this with Mike.
```
# GBRS Emission Probs.
GBRS_EMIS_PROBS=${GBRS_REF_DIR}/gbrs_emissions_all_tissues.avecs.npz
```
This file contains the allele emission probabilities for the hidden Markov model.
These are used at each gene to estimate the probability that a given allele
is obsered, given that the model is in a certain genotype state.
```
# GBRS Transmission Probs.
GBRS_TRANS_PROBS=${GBRS_REF_DIR}/transition_probabilities
```
This directory contains the transmission probabilities for the hidden Markov model.
There are many files in this directory, one for each DO outbreeding generation.
Each file contains the probability of changing genotype state between each gene
at a given DO outbreeding generation.
```
# Ensembl 105 gene positions.
ENSEMBL_105=${GBRS_REF_DIR}/ref.gene_pos.ordered_ensBuild_105.npz
```
This file contains the Ensembl 105 gene positions in a python format.
```
# GBRS 69K Marker Grid.
MARKER_GRID=${GBRS_REF_DIR}/ref.genome_grid.GRCm39.tsv
```
This file contains the pseudomarker genome grid which is used to report results.
Each tissue expresses different gene, which leads GBRS to estimate genotypes
at different genomic positions in each tissue. In order to standardize results,
GBRS interpolates its founder haplotype estimates to a common grid of 74,165
positions.
```
# Bowtie index for GBRS.
BOWTIE_INDEX=/projects/compsci/omics_share/mouse/GRCm39/transcriptome/indices/imputed/rel_2112_v8/bowtie/bowtie.transcripts
```
This is the path to the bowtie index files. There are multiple files and this
variable should contain the directory and the file prefix for the index files.
In this case, the file prefix is "bowtie.transcripts" and the files are named
"bowtie.transcripts.1.ewbt", "bowtie.transcripts.2.ewbt", etc.
```
# GBRS path.
GBRS_GITHUB_PATH=TheJacksonLaboratory/cs-nf-pipelines
```
This is the Github path to the Computational Science `nextflow` pipelines.
```
# Singularity cache directory.
export NXF_SINGULARITY_CACHEDIR=${flashscratch}/singularity_cache
```
This is the cache directory where Singularity will store containers which it
downloads during the analysis run.
> DMG: confirm with Mike.
#### Entire GBRS Script
Here is the whole script in one piece.
```
#!/bin/bash
#SBATCH --qos=batch # job queue
#SBATCH --ntasks=1 # number of nodes
#SBATCH --cpus-per-task=1 # number of cores
#SBATCH --mem=1G # memory pool for all cores
#SBATCH --time=48:00:00 # wall clock time (D-HH:MM)
################################################################################
# Run GBRS on each sample.
# GRCm39. Ensembl 105.
#
# Daniel Gatti
# dan.gatti@jax.org
# 2022-09-28
################################################################################
##### VARIABLES #####
# Base directory for project.
BASE_DIR=/projects/bolcun-filas-lab/DO_Superovulation
# Sample metadata file.
SAMPLE_META_FILE=${BASE_DIR}/gbrs_sample_metadata.csv
# Base /flashscratch directory.
FLASHSCRATCH=/flashscratch/dgatti
# Temporary directory.
TMP_DIR=${FLASHSCRATCH}/tmp
# Output directory.
OUT_DIR=${FLASHSCRATCH}/results
# Final results directory (in backed up space)
DEST_DIR=${BASE_DIR}/results/gbrs/grcm39
# GBRS Reference File Directory
GBRS_REF_DIR=/projects/churchill-lab/projects/GBRS_GRCm39
# GBRS Transcripts.
GBRS_TRANSCRIPTS=${GBRS_REF_DIR}/emase.fullTranscripts.info
# GBRS/EMASE gene to transcript file.
GBRS_GENE2TRANS=${GBRS_REF_DIR}/emase.gene2transcripts.tsv
# GBRS Full Transcript.
GBRS_FULL_TRANSCRIPTS=${GBRS_REF_DIR}/emase.pooled.fullTranscripts.info
# GBRS Emission Probs.
GBRS_EMIS_PROBS=${GBRS_REF_DIR}/gbrs_emissions_all_tissues.avecs.npz
# GBRS Transmission Probs.
GBRS_TRANS_PROBS=${GBRS_REF_DIR}/transition_probabilities
# Ensembl 105 gene positions.
ENSEMBL_105=${GBRS_REF_DIR}/ref.gene_pos.ordered_ensBuild_105.npz
# GBRS 69K Marker Grid.
MARKER_GRID=${GBRS_REF_DIR}/ref.genome_grid.GRCm39.tsv
# Bowtie index for GBRS.
BOWTIE_INDEX=/projects/compsci/omics_share/mouse/GRCm39/transcriptome/indices/imputed/rel_2112_v8/bowtie/bowtie.transcripts
# GBRS path.
GBRS_GITHUB_PATH=TheJacksonLaboratory/cs-nf-pipelines
# Singularity cache directory.
export NXF_SINGULARITY_CACHEDIR=${flashscratch}/singularity_cache
##### MAIN #####
mkdir -p ${OUT_DIR}
mkdir -p ${DEST_DIR}
mkdir -p ${TMP_DIR}
mkdir -p ${NXF_SINGULARITY_CACHEDIR}
module load singularity
cd ${TMP_DIR}
nextflow run ${GBRS_GITHUB_PATH} \
-profile sumner \
--workflow gbrs \
--pubdir ${OUT_DIR} \
-w ${TMP_DIR} \
--bowtie_index ${BOWTIE_INDEX} \
--csv_input ${SAMPLE_META_FILE} \
--transcripts_info ${GBRS_TRANSCRIPTS} \
--gene2transcript_csv ${GBRS_GENE2TRANS} \
--full_transcript_info ${GBRS_FULL_TRANSCRIPTS} \
--emission_prob_avecs ${GBRS_EMIS_PROBS} \
--trans_prob_dir ${GBRS_TRANS_PROBS} \
--gene_position_file ${ENSEMBL_105} \
--genotype_grid ${MARKER_GRID} \
-resume
# Copy output files from OUT_DIR to DEST_DIR.
DIRS=`ls ${OUT_DIR}`
for i in ${DIRS}
do
CURR_DEST_DIR=${DEST_DIR}/$i
mkdir -p ${CURR_DEST_DIR}
cp ${OUT_DIR}/${i}/stats/* ${CURR_DEST_DIR}
cp ${OUT_DIR}/${i}/gbrs/*_counts ${CURR_DEST_DIR}
cp ${OUT_DIR}/${i}/gbrs/*.tsv ${CURR_DEST_DIR}
cp ${OUT_DIR}/${i}/gbrs/*.pdf ${CURR_DEST_DIR}
done
```
::::::::::::::::::::::::::::::::::::: keypoints
- Use *bash* variables to build file paths and analysis tool arguments.
::::::::::::::::::::::::::::::::::::::::::::::::
[r-markdown]: https://rmarkdown.rstudio.com/
|
import { useMemo } from 'react';
import { useForm } from 'react-hook-form';
import { useLocation } from 'react-router-dom';
import NavLink from '@components/NavLink';
import Sidebar from '@components/Sidebar';
import { scale } from '@scripts/helpers';
import { useFieldCSS } from '@scripts/hooks/useFieldCSS';
interface LinkData {
label: string;
to: string;
}
interface LinkGroup {
label: string;
links: LinkData[];
}
const items: LinkGroup[] = [
{
label: 'Система',
links: [
{
label: 'Монитор питания',
to: '/periphery/system/vcc-monitor',
},
{
label: 'Монитор тактирования',
to: '/periphery/system/cycle-monitor',
},
{
label: 'ПДП',
to: '/periphery/system/pdp',
},
{
label: 'Тактирование',
to: '/periphery/system/cycle',
},
{
label: 'Прерывания',
to: '/periphery/system/interrupts',
},
{
label: 'GPIO',
to: '/periphery/system/gpio',
},
{
label: 'WDT',
to: '/periphery/system/wdt',
},
{
label: "Bus' WDT",
to: '/periphery/system/bus-wdt',
},
],
},
{
label: 'Аналоговые блоки',
links: [
{
label: 'АЦП',
to: '/periphery/analog/adc',
},
{
label: 'Температурный сенсор',
to: '/periphery/analog/temp',
},
{
label: 'ЦАП',
to: '/periphery/analog/dac',
},
],
},
{
label: 'Таймеры',
links: [
{
label: 'RTC',
to: '/periphery/timers/rtc',
},
{
label: 'TIMER32',
to: '/periphery/timers/timer32',
},
{
label: 'TIMER16',
to: '/periphery/timers/timer16',
},
],
},
{
label: 'Интерфейсы',
links: [
{
label: 'I2C0',
to: '/periphery/interface/i2c0',
},
{
label: 'I2C1',
to: '/periphery/interface/i2c1',
},
{
label: 'SPI0',
to: '/periphery/interface/spi0',
},
{
label: 'SPI1',
to: '/periphery/interface/spi1',
},
{
label: 'SPIFI',
to: '/periphery/interface/spifi',
},
{
label: 'USART',
to: '/periphery/interface/usart',
},
],
},
{
label: 'Криптография',
links: [
{
label: 'Крипто-блок',
to: '/periphery/crypto/block',
},
{
label: 'CRC',
to: '/periphery/crypto/crc',
},
],
},
];
// const NavLink = ({ link, label }: LinkData) => {
// const match = useMatch(`${link}/*`);
// return (
// <Link
// to={link}
// css={{
// color: colors.link,
// textDecoration: 'none',
// padding: `${scale(1)}px ${scale(2)}px`,
// borderRadius: scale(3, true),
// border: `1px solid ${colors.grey200}`,
// ...(match && {
// borderColor: colors.link,
// background: colors.link,
// color: colors.white,
// cursor: 'default',
// }),
// ...(!match && {
// ':hover': {
// border: `1px solid ${colors.link}`,
// },
// }),
// }}
// >
// {label}
// </Link>
// );
// };
const SidebarContainer = ({ isDark, className }: { isDark: boolean; className?: string }) => {
const { pathname } = useLocation();
const activeGroupId = useMemo<string>(() => {
let groupIndex = 0;
for (let i = 0; i < items.length; i += 1) {
const groupItems = items[i].links;
if (groupItems.map(e => e.to).includes(pathname)) {
groupIndex = i;
break;
}
}
return `${groupIndex}`;
}, [pathname]);
const { basicFieldCSS } = useFieldCSS({});
const { register, watch } = useForm({
defaultValues: {
search: '',
},
});
const search = watch('search');
const filteredItems = useMemo(
() =>
items.filter(el => {
const term = search.toLowerCase();
if (el.label.toLowerCase().includes(term)) return true;
const concat = el.links
.map(e => e.label)
.join(',')
.toLowerCase();
return concat.includes(term);
}),
[search]
);
const preExpanded = useMemo<string[]>(() => {
if (filteredItems.length < 3) return ['0', '1'];
return [activeGroupId];
}, [activeGroupId, filteredItems]);
return (
<Sidebar title="Список перифирий" className={className}>
<input
css={[basicFieldCSS, { marginBottom: scale(2) }]}
placeholder="Поиск"
autoComplete="off"
{...register('search')}
/>
<Sidebar.Nav
preExpanded={preExpanded}
animationType="fadeIn"
allowMultipleExpanded={false}
allowZeroExpanded
variant={isDark ? 'dark' : 'primary'}
isIconVertical
>
{filteredItems &&
filteredItems.map((group, index) => (
<Sidebar.Group id={`${index}`} key={index} title={group.label}>
<div
css={{
display: 'grid',
gridTemplateColumns: '1fr',
gap: scale(1),
}}
>
{group.links.map(({ to, label }, index) => (
<NavLink variant={isDark ? 'dark' : 'primary'} key={index} to={to}>
{label}
</NavLink>
))}
</div>
</Sidebar.Group>
))}
</Sidebar.Nav>
</Sidebar>
);
};
export default SidebarContainer;
|
import "../App.css";
import { useState, useRef } from "react";
import { Button, Form } from "react-bootstrap";
import axios from "axios";
import { LeafletContainer } from "../maps/formMap/leaflet-container";
import { LeafletMap } from "../maps/formMap/leaflet-map";
import { LeafletContainer1 } from "../maps/formMap/formUserLoc/leaflet-container";
import { LeafletMap1 } from "../maps/formMap/formUserLoc/leaflet-map";
import { Popup } from "react-leaflet";
import UploadLogo from "../components/UploadLogo";
import SearchButton from "../components/SearchButton";
import { NavLink } from "react-router-dom";
import Logo from "../components/Logo";
import LogoutButton from "../components/LogoutButton";
import Logonotext from "../assets/logonotext.png";
import { useNavigate } from "react-router-dom";
const UploadPage = () => {
const inputRefCity = useRef();
const inputRefZipcode = useRef();
const inputRefAddress = useRef();
const inputRefType = useRef();
const [image, setImage] = useState("");
const [coordinates, setCoordinates] = useState({ lat: 0, lon: 0 });
//const [marker, setMarker] = useState([]);
const [popup, setPopup] = useState(false);
const navigate = useNavigate();
const onSubmit = (e) => {
e.preventDefault();
const address =
inputRefZipcode.current.value +
" " +
inputRefAddress.current.value +
", " +
inputRefCity.current.value;
axios
.get(
`https://nominatim.openstreetmap.org/search?q=${address}&format=json&limit=1`
)
.then((response) => {
if (response.data[0]) {
console.log(response.data[0]);
const { lat, lon } = response.data[0];
setCoordinates({ lat, lon });
//console.log(coordinates);
const formData = new FormData();
formData.append("image", image);
formData.append("city", inputRefCity.current.value);
formData.append("zipcode", inputRefZipcode.current.value);
formData.append("adress", inputRefAddress.current.value);
formData.append("lat", response.data[0].lat);
formData.append("lon", response.data[0].lon);
formData.append("type", inputRefType.current.value);
axios
.post("/api/addbuilding", formData)
.then((response) => {
console.log(response);
// setIsSubmitting(false);
})
.catch((error) => {
console.log(error);
// setIsSubmitting(false);
});
} else {
console.error("No data returned from API request");
}
});
};
const logout = async () => {
try {
const response = await axios.get("api/user/logout", {
headers: {
"ngrok-skip-browser-warning": "69420",
},
});
console.log(response);
navigate("/");
} catch (error) {
console.log(error);
}
};
return (
<div className="font-custom1 h-screen w-screen flex flex-col m-0 p-0">
<div className="flex h-1/12 w-full box-border justify-between px-5 p-3 items-center ">
<Logo />
<LogoutButton onClick={logout} />
</div>
<h3 className="h-1/6 m-1 uppercase text-black font-bold text-5xl flex items-center justify-center">
UPLOAD A SPACE
</h3>
<div className="h-4/6 w-full flex box-border items-center justify-around ">
<Form
onSubmit={onSubmit}
className="w-1/4 flex flex-col justify-center items-center font-bold text-xl"
>
<div className="flex w-full flex-col items-center">
<Form.Group
className="flex w-52 p-1 justify-start"
controlId="image"
>
<Form.Label>Image: </Form.Label>
<Form.Control
type="file"
className="text-xs font-normal h-6 "
onChange={(event) => {
if (event.target.files && event.target.files[0]) {
setImage(event.target.files[0]);
console.log(event.target.files[0]);
//URL.createObjectURL(event.target.files[0])
}
}}
/>
</Form.Group>
<Form.Group
className="flex p-1 w-52 justify-between"
controlId="city"
>
<Form.Label>City:</Form.Label>
<Form.Control
className="text-xs font-normal w-32 h-6 border rounded-xl p-1 px-3"
type="text"
ref={inputRefCity}
placeholder="Enter your city"
/>
</Form.Group>
<Form.Group
className="flex p-1 w-52 justify-between"
controlId="zipcode"
>
<Form.Label>Zipcode: </Form.Label>
<Form.Control
className="text-xs font-normal w-32 h-6 border rounded-xl p-1 px-3 "
type="text"
ref={inputRefZipcode}
placeholder="Enter your zipcode"
/>
</Form.Group>
<Form.Group
className="flex p-1 w-52 justify-between"
controlId="address"
>
<Form.Label>Address: </Form.Label>
<Form.Control
className="text-xs font-normal w-32 h-6 border rounded-xl p-1 px-3 "
type="text"
ref={inputRefAddress}
placeholder="Enter your address"
/>
</Form.Group>
<Form.Group
className="flex w-52 p-1 justify-between"
controlId="typeSelect"
>
<Form.Label>Type: </Form.Label>
<select
className="text-xs w-24 h-5 font-normal"
ref={inputRefType}
>
<option className="text-xs font-normal" value="All"></option>
<option className="text-xs font-normal" value="Housing">
Housing
</option>
<option className="text-xs font-normal" value="Gardens">
Gardens
</option>
<option className="text-xs font-normal" value="Factories">
Factories
</option>
<option className="text-xs font-normal" value="Offices">
Offices
</option>
<option className="text-xs font-normal" value="Multiple">
Multiple
</option>
</select>
</Form.Group>
</div>
<Button
className="text-xl rounded-2xl p-3 mt-28 border "
type="submit"
>
Add a building
</Button>
</Form>
<div className="w-2/3 h-5/6 mr-10 flex box-border overflow:hidden truncate ">
{coordinates.lat === 0 && coordinates.lon === 0 && (
<LeafletContainer1 className="object-cover h-full w-full font-Custom1">
<LeafletMap1>
<Popup className="popup">
Your position is here
</Popup>
</LeafletMap1>
</LeafletContainer1>
)}
{coordinates.lat !== 0 && coordinates.lon !== 0 && (
<LeafletContainer className="object-cover h-full w-full font-Custom1" center={[coordinates.lat, coordinates.lon]} zoom={13}>
<LeafletMap coordinates={coordinates} onClick={() => setPopup(true)}>
<Popup className="popup">
{image && (
<img
src={image}
alt="selected photo"
style={{ width: "150px", height: "150px" }}
/>
)}
<p>City: {inputRefCity.current.value}</p>
<p>Zipcode: {inputRefZipcode.current.value}</p>
<p>Address: {inputRefAddress.current.value}</p>
<p>Type: {inputRefType.current.value}</p>
</Popup>
</LeafletMap>
</LeafletContainer>
)}
</div>
</div>
<footer className="h-1/12 pt-4 flex justify-center">
<div className=" rounded-3xl p-1 px-3 flex items-center justify-start text-center text-black font-bold text-lg w-30 mb-4 ">
<img
src={Logonotext}
alt="Logo"
className=" p-1 w-7 flex justify-center font-bold item-center "
/>
</div>
</footer>
</div>
);
};
export default UploadPage;
|
from django.shortcuts import get_object_or_404, render, redirect
from django.contrib import messages
from django.contrib.auth.models import User
from django.contrib.auth.decorators import login_required
from .forms import UserUpdateForm, ProfileUpdateForm, RegisterForm
def register(request):
if request.method == "POST":
form = RegisterForm(request.POST)
if form.is_valid():
form.save()
messages.success(request, "User created successfully!")
return redirect('blog:list')
else:
form = RegisterForm()
return render(request,
"account/register.html", {"form": form})
def profile(request, pk):
user = get_object_or_404(User, pk=pk)
return render(request, "account/profile.html", {"user": user})
@login_required
def update_profile(request):
if request.method == 'POST':
user_form = UserUpdateForm(request.POST, instance=request.user)
profile_form = ProfileUpdateForm(
request.POST, request.FILES, instance=request.user.profile)
if user_form and profile_form:
user_form.save()
profile_form.save()
messages.success(request, "Profile updated successfully")
return redirect('profile', request.user.pk)
else:
user_form = UserUpdateForm(instance=request.user)
profile_form = ProfileUpdateForm(instance=request.user)
context = {
"user_form": user_form,
"profile_form": profile_form
}
return render(request, "account/update.html", context)
|
import {
useFonts,
Poppins_900Black,
Poppins_400Regular,
Poppins_500Medium,
Poppins_700Bold,
Poppins_600SemiBold,
} from "@expo-google-fonts/poppins";
import SignIn from "@modules/Authentication/SignIn";
import SignUp from "@modules/Authentication/SignUp";
import Welcome from "@modules/Authentication/Welcome";
import Dashboard from "@modules/Dashboard";
import * as SplashScreen from "expo-splash-screen";
import React from "react";
import { StatusBar } from "react-native";
import { ThemeProvider } from "styled-components";
import theme from "./src/themes/theme";
const App: React.FC = () => {
const [fontsLoaded] = useFonts({
Poppins_900Black,
Poppins_400Regular,
Poppins_500Medium,
Poppins_700Bold,
Poppins_600SemiBold,
});
if (!fontsLoaded) {
return null;
}
setTimeout(SplashScreen.hideAsync, 5000);
return (
<ThemeProvider theme={theme}>
<StatusBar
backgroundColor="transparent"
translucent
barStyle="light-content"
/>
<Dashboard />
</ThemeProvider>
);
};
export default App;
|
package com.mall.common.utils;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.databind.ObjectMapper;
public class FuyouResult {
// 定义jackson对象
private static final ObjectMapper MAPPER = new ObjectMapper();
// 响应业务状态
private Integer status;
// 响应消息
private String msg;
// 响应中的数据
private Object data;
@JsonIgnore
private String ok; // 不使用
public static FuyouResult build(Integer status, String msg, Object data) {
return new FuyouResult(status, msg, data);
}
public static FuyouResult build(Integer status, String msg, Object data, String ok) {
return new FuyouResult(status, msg, data, ok);
}
public static FuyouResult ok(Object data) {
return new FuyouResult(data);
}
public static FuyouResult ok() {
return new FuyouResult(null);
}
public static FuyouResult errorMsg(String msg) {
return new FuyouResult(500, msg, null);
}
public static FuyouResult errorMap(Object data) {
return new FuyouResult(501, "error", data);
}
public static FuyouResult errorTokenMsg(String msg) {
return new FuyouResult(502, msg, null);
}
public static FuyouResult errorException(String msg) {
return new FuyouResult(555, msg, null);
}
public static FuyouResult errorUserQQ(String msg) {
return new FuyouResult(556, msg, null);
}
public FuyouResult() {
}
public FuyouResult(Integer status, String msg, Object data) {
this.status = status;
this.msg = msg;
this.data = data;
}
public FuyouResult(Integer status, String msg, Object data, String ok) {
this.status = status;
this.msg = msg;
this.data = data;
this.ok = ok;
}
public FuyouResult(Object data) {
this.status = 200;
this.msg = "OK";
this.data = data;
}
public Boolean isOK() {
return this.status == 200;
}
public Integer getStatus() {
return status;
}
public void setStatus(Integer status) {
this.status = status;
}
public String getMsg() {
return msg;
}
public void setMsg(String msg) {
this.msg = msg;
}
public Object getData() {
return data;
}
public void setData(Object data) {
this.data = data;
}
public String getOk() {
return ok;
}
public void setOk(String ok) {
this.ok = ok;
}
}
|
<script>
import { onMount, createEventDispatcher } from "svelte";
import { createTimer } from "./stores.js";
import { jiggleJS as jiggle, scaleJS as scale, scaleCSS } from "./utils.js";
const dispatch = createEventDispatcher();
export let delay = 5;
export let countdown = 20;
let isDelay;
let isCountdown;
let timer;
onMount(() => {
timer = createTimer(delay + 1);
isDelay = true;
return () => timer.remove();
});
$: if (timer && $timer === 0) {
if (isDelay) {
timer.start(countdown);
isDelay = false;
isCountdown = true;
} else {
timer.remove();
dispatch("end");
isOver = true;
}
}
let isPaused;
let isOver;
const toggleTimer = () => {
if (isOver) return;
isPaused = !isPaused;
if (isPaused) {
timer.pause();
} else {
timer.start($timer);
}
};
</script>
<div>
<svg viewBox="-15.5 -15.5 30 30">
{#if isDelay}
<g transition:scale={{ duration: 200 }}>
<circle r="10" fill="#f9c801" stroke="#3c3c3c" />
<g
text-anchor="middle"
dominant-baseline="central"
font-family="sans-serif"
paint-order="stroke"
fill="#ffffff"
stroke="#3c3c3c"
stroke-width="1.65"
stroke-linejoin="round"
stroke-linecap="round"
font-size="14"
>
{#key $timer - 1}
<g in:jiggle>
<text>{$timer - 1}</text>
</g>
{/key}
</g>
</g>
{/if}
{#if isCountdown}
<g in:scale={{ delay: 200 }}>
<g
text-anchor="middle"
dominant-baseline="central"
font-family="sans-serif"
paint-order="stroke"
fill="#ffffff"
stroke="#3c3c3c"
stroke-width="1.65"
stroke-linejoin="round"
stroke-linecap="round"
font-size="14"
>
<text>{$timer}</text>
</g>
</g>
{/if}
</svg>
{#if !isOver}
<button transition:scaleCSS on:click={toggleTimer}>
{#if isPaused}
<span class="visually-hidden">Resume</span>
<svg viewBox="-15.5 -15.5 30 30">
<g
fill="#ffffff"
stroke="#3c3c3c"
stroke-width="1.65"
stroke-linejoin="round"
stroke-linecap="round"
>
<path stroke-dasharray="40" d="M -6 -8 l 12 8 -12 8z" />
</g>
</svg>
{:else}
<span class="visually-hidden">Pause</span>
<svg viewBox="-15.5 -15.5 30 30">
<g
fill="#ffffff"
stroke="#3c3c3c"
stroke-width="1.65"
stroke-linejoin="round"
stroke-linecap="round"
>
<path stroke-dasharray="38" d="M -8 -8 h 5 v 16 h -5z" />
<path d="M 2 -8 h 5 v 16 h -5z" />
</g>
</svg>
{/if}
</button>
{/if}
</div>
<style>
div {
width: 12rem;
margin-left: auto;
margin-right: auto;
}
svg,
button {
display: block;
}
div > svg {
width: 100%;
height: auto;
}
button {
cursor: pointer;
width: 4rem;
margin-left: auto;
margin-right: auto;
background: none;
border: none;
}
button > svg {
width: 100%;
height: auto;
}
</style>
|
import 'package:adf_provider/provider/produto_model.dart';
import 'package:adf_provider/provider/produto_widget.dart';
import 'package:adf_provider/provider/user_model.dart';
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
class ProviderPage extends StatelessWidget {
const ProviderPage({Key? key}) : super(key: key);
@override
Widget build(BuildContext context) {
var user = Provider.of<UserModel>(context);
// var user = context.read<UserModel>(); // retorna uma instância sen ficar escutando alterações
// var imageAvatar = context.select<UserModel, String>((userModel) => userModel.imgAvatar);
// var user = context.watch<UserModel>();
return Provider(
create: (_) => ProdutoModel(nome: 'Fábrica de apps'),
child: Scaffold(
appBar: AppBar(
title: const Text('Provider'),
),
body: Center(
child: Padding(
padding: const EdgeInsets.all(10.0),
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
CircleAvatar(
backgroundImage: NetworkImage(user.imgAvatar),
radius: 60,
),
const SizedBox(height: 20),
Row(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Text(user.name),
Text('(${user.birthDate})'),
],
),
// Provider(create: (_) => ProdutoModel(nome: 'Fábrica de apps'),
const ProdutoWidget(),
],
),
),
),
),
);
}
}
|
{
type NetworkErrorState = {
result: 'fail';
reason: 'offline' | 'down' | 'timeout';
};
type SuccessState = {
result: 'success';
};
type ResultState = SuccessState | NetworkErrorState;
class NetworkClient {
tryConnect(): ResultState {
return {
result: 'fail',
reason: 'offline'
}
}
}
class UserService{
constructor(private client: NetworkClient) {}
login(){
this.client.tryConnect();
}
}
class App{
constructor(private userService: UserService){}
run() {
this.userService.login();
};
}
const client = new NetworkClient();
const service = new UserService(client);
const app = new App(service);
app.run();
}
// 언제 Error를 쓰고 언제 Error State를 써야할까?
// Error(Exception): 가급적 정말정말 예상하지 못한 곳에서 사용
// ErrorState: 조금 더 세부적인 에러를 결정하고 싶을 때(예상가능한 에러)
// ex. 네트워크 에러는 코드를 작성할 때 예상할 수 있는 state임
// 성공할 수도 있고 실패할 수도 있고, 실패한다면 어떤 실패인지 예상할 수 있음
// 따라서 tryConnect한 다음에 어떤 상태가 되는지 ResultState를 리턴하게 만드는 것이 더 좋음
|
package jpabook.jpashop.repository.order.query;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Repository;
import javax.persistence.EntityManager;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
/**
* Entity가 아닌 화면이나 API용으로 DTO들을 가져올 때 (화면에 FIT하게)
*
*/
@Repository
@RequiredArgsConstructor
public class OrderQueryRepository {
private final EntityManager em;
/**
* Collection은 못가져온다.
* @return
*/
public List<OrderQueryDto> findOrderQueryDtos() {
List<OrderQueryDto> result = findOrders(); //query 1번 -> N개
result.forEach(o -> {
List<OrderItemQueryDto> orderItems = findOrderItems(o.getOrderId()); // Query N번
o.setOrderItems(orderItems);
});
return result;
}
private List<OrderItemQueryDto> findOrderItems(Long orderId) {
return em.createQuery("select new jpabook.jpashop.repository.order.query.OrderItemQueryDto(oi.order.id, i.name, oi.orderPrice, oi.count)" +
" from OrderItem oi" +
" join oi.item i" +
" where oi.order.id = :orderId", OrderItemQueryDto.class).setParameter("orderId", orderId).getResultList();
}
//V4 Dto로 Collection 처리
public List<OrderQueryDto> findOrders() {
return em.createQuery("select new jpabook.jpashop.repository.order.query.OrderQueryDto(o.id, m.name, o.orderDateTime, o.status, d.address)" +
" from Order o" +
" join o.member m" +
" join o.delivery d", OrderQueryDto.class)
.getResultList();
}
//V5 기존 stream을 통해 OrderDto에 OrderItems LAZYLOADING 초기화
//해주고 Items 초기화를 하기 위해 개별적인 orderitem & item select query를
//넘어서 In절로 한번에 가져온다.
/**
* Order와 x To One인 아이들 최대한 fetch join, join 해서 먼저 가져온다.
* LAZY LOADING인 Order.Collection들 (Order(1)-OrderItems(N))을
* IN 구문을 통해 각 Order에 해당하는 OrderItems 개수만큼만 호출되던 쿼리 수를
* DB에선 단 한번에 모든 Order와 연결되어있는 OrderItems를 한번에 호출하게 변함
*
* 이후 가져온 orderItems 리스트를 OrderId 순으로 GroupingBy 해서
* key : order_id, value : list of OrderItems
* Order에 해당 id와 맞는 OrderItems list를 꺼내 set 해준다.
*
* 총 쿼리 = Orders 불러올 떄 1번 + 전체 OrderItems 꺼내올 떄 1번 = 2번
* @return
*/
public List<OrderQueryDto> findAllByDto_optimization() {
List<OrderQueryDto> orders = findOrders();
List<Long> orderIds = toOrderIds(orders);
Map<Long, List<OrderItemQueryDto>> orderItemMap = findOrderItemMap(orderIds);
orders.forEach(o -> o.setOrderItems(orderItemMap.get(o.getOrderId())));
return orders;
}
private Map<Long, List<OrderItemQueryDto>> findOrderItemMap(List<Long> orderIds) {
List<OrderItemQueryDto> orderItems = em.createQuery(
"select new jpabook.jpashop.repository.order.query.OrderItemQueryDto(oi.order.id, i.name, oi.orderPrice, oi.count)" +
" from OrderItem oi" +
" join oi.item i" +
" where oi.order.id in :orderIds", OrderItemQueryDto.class)
.setParameter("orderIds", orderIds)
.getResultList();
Map<Long, List<OrderItemQueryDto>> orderItemMap = orderItems.stream()
.collect(Collectors.groupingBy(OrderItemQueryDto::getOrderId));
return orderItemMap;
}
private List<Long> toOrderIds(List<OrderQueryDto> orders) {
return orders.stream().map(o -> o.getOrderId())
.collect(Collectors.toList());
}
//V6 쿼리 1번에 해결하는 법
public List<OrderFlatDto> findAllByDto_flat() {
return em.createQuery(
"select new jpabook.jpashop.repository.order.query.OrderFlatDto(o.id, m.name, o.orderDateTime, o.status, d.address, i.name, oi.orderPrice, oi.count)" +
" from Order o" +
" join o.member m" +
" join o.delivery d" +
" join o.orderItems oi" +
" join oi.item i", OrderFlatDto.class
).getResultList();
}
}
|
'''
Clasa care incapsuleaza implementarea modelului de ACP
'''
import numpy as np
def standardise(x):
'''
x - data table, expect numpy.ndarray
'''
means = np.mean(x, axis=0)
stds = np.std(x, axis=0)
Xstd = (x - means) / stds
return Xstd
class PCA:
# constructorul primeste o matrice X standardizata
def __init__(self, X):
self.X = X
# calcul matrice de varianta-covarianta pentru X
self.Cov = np.cov(m=X, rowvar=False) # variabilele sunt pe coloane
print(self.Cov.shape)
# calcul valori proprii si vectori proprii pentru matricea de varianta-covarianta
self.valoriProprii, self.vectoriiProprii = np.linalg.eigh(a=self.Cov)
print(self.valoriProprii, self.valoriProprii.shape)
print(self.vectoriiProprii.shape)
# sortare descrescatoare valori proprii si vectori proprii
k_desc = [k for k in reversed(np.argsort(self.valoriProprii))]
print(k_desc)
self.alpha = self.valoriProprii[k_desc]
self.A = self.vectoriiProprii[:, k_desc]
# regularizare vectorilor proprii
for j in range(self.A.shape[1]):
minCol = np.min(a=self.A[:, j])
maxCol = np.max(a=self.A[:, j])
if np.abs(minCol) > np.abs(maxCol):
self.A[:, j] = (-1) * self.A[:, j]
# calcul componente principale
self.C = self.X @ self.A
# self.C = np.matmul(self.X, self.A) # alternativa
# calcul corelatie dintre variabilele observate si componentele principale
# factor loadings
self.Rxc = self.A * np.sqrt(self.alpha)
self.C2 = self.C * self.C
# self.C2 = np.square(self.C)
def getAlpha(self):
# return self.valoriProprii
return self.alpha
def getA(self):
# return self.vectoriiProprii
return self.A
def getComponentePrincipale(self):
return self.C
def getFactorLoadings(self):
return self.Rxc
def getScoruri(self):
# calcul scoruri
return self.C / np.sqrt(self.alpha)
def getCalitateObservatii(self):
SL = np.sum(self.C2, axis=1) # sume pe linii
return np.transpose(self.C2.T / SL)
# calcul contributie observatii la explicarea variantei axelor componentelor principale
def getContributieObservatii(self):
return self.C2 / (self.X.shape[0] * self.alpha)
def getComunalitati(self):
Rxc2 = np.square(self.Rxc)
return np.cumsum(a=Rxc2, axis=1) # sume pe linii
|
import Foundation
protocol NetworkManagerProtocol {
func fetchProducts(completion: @escaping (Result<[Product], Error>) -> Void)
}
class StoreClient: NetworkManagerProtocol {
static let shared = StoreClient()
private init() {}
private let apiUrl = "https://fakestoreapi.com/products"
func fetchProducts(completion: @escaping (Result<[Product], Error>) -> Void) {
guard let url = URL(string: apiUrl) else { return }
URLSession.shared.dataTask(with: url) { data, response, error in
var result: Result<[Product], Error>
defer {
DispatchQueue.main.async {
completion(result)
}
}
if let error = error {
result = .failure(error)
}
guard let data = data else {
result = .success([])
return
}
do {
let products = try JSONDecoder().decode([Product].self, from: data)
result = .success(products)
}
catch let error {
result = .failure(error)
}
}.resume()
}
}
|
import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
final phoneProvider = StateProvider<String>((ref) => '');
class PhoneTextField extends ConsumerWidget {
final _labelFont = const TextStyle(
fontSize: 12,
color: Color.fromARGB(255, 145, 146, 150),
height: 1.5,
letterSpacing: 0.6,
fontWeight: FontWeight.w500);
final _errorText = const TextStyle(
fontSize: 12,
color: Color.fromARGB(255, 240, 93, 93),
height: 1.5,
letterSpacing: 0.6,
fontWeight: FontWeight.w500);
const PhoneTextField({super.key});
@override
Widget build(BuildContext context, WidgetRef ref) {
return SizedBox(
width: 750,
child: TextFormField(
validator: (value) {
if (value!.isEmpty) {
return 'Enter your phone number';
} else {
return null;
}
},
onChanged: (String value) =>
ref.watch(phoneProvider.notifier).update((state) => value),
autovalidateMode: AutovalidateMode.onUserInteraction,
keyboardType: TextInputType.number,
decoration: InputDecoration(
isDense: true,
labelStyle: _labelFont,
hintText: 'Phone number',
hintStyle: _labelFont,
alignLabelWithHint: true,
errorStyle: _errorText,
fillColor: const Color.fromARGB(255, 237, 236, 236),
filled: true,
enabledBorder: OutlineInputBorder(
borderSide: const BorderSide(
color: Colors.transparent,
),
borderRadius: BorderRadius.circular(2.0),
),
focusedBorder: OutlineInputBorder(
borderSide: const BorderSide(
color: Color.fromARGB(240, 52, 3, 199),
),
borderRadius: BorderRadius.circular(2.0),
),
errorBorder: OutlineInputBorder(
borderSide: const BorderSide(
color: Color.fromARGB(255, 240, 93, 93),
),
borderRadius: BorderRadius.circular(2.0),
),
focusedErrorBorder: OutlineInputBorder(
borderSide: const BorderSide(
color: Color.fromARGB(255, 240, 93, 93),
),
borderRadius: BorderRadius.circular(2.0),
),
),
),
);
}
}
|
* Vuex Store
*
* The store of the application.
*
* http://vuex.vuejs.org/en/index.html
*/
import Vuex from 'vuex';
import createLogger from 'vuex/dist/logger';
// Modules
import account from './modules/account';
import auth from './modules/auth';
import navigation from './modules/navigation';
const debug = process.env.NODE_ENV !== 'production';
export default new Vuex.Store({
/**
* Assign the modules to the store.
*/
modules: {
account,
auth,
navigation,
},
/**
* If strict mode should be enabled.
*/
strict: debug,
/**
* Plugins used in the store.
*/
plugins: debug ? [createLogger()] : [],
});
|
import { FastifyInstance } from 'fastify'
import { z } from 'zod'
import { randomUUID } from 'crypto'
import { checkSessionIdExists } from '../middlewares/check-session-id-exists'
import { knex } from '../database'
export async function mealsRoutes(app: FastifyInstance) {
app.get(
'/',
{
preHandler: [checkSessionIdExists],
},
async (request) => {
const { sessionId } = request.cookies
const meals = await knex('meals').where('session_id', sessionId).select()
return { meals }
},
)
app.get(
'/:id',
{
preHandler: [checkSessionIdExists],
},
async (request) => {
const { sessionId } = request.cookies
const getMealsParamsSchema = z.object({
id: z.string().uuid(),
})
const { id } = getMealsParamsSchema.parse(request.params)
const meal = await knex('meals')
.where({ id, session_id: sessionId })
.first()
return { meal }
},
)
app.post(
'/',
{
preHandler: [checkSessionIdExists],
},
async (request, reply) => {
const sessionId = request.cookies.sessionId
const createMealBodySchema = z.object({
name: z.string(),
description: z.string(),
datetimeMeal: z.string(),
isDiet: z.boolean(),
})
const { name, description, datetimeMeal, isDiet } =
createMealBodySchema.parse(request.body)
await knex('meals').insert({
id: randomUUID(),
name,
description,
datetime_meal: datetimeMeal,
is_diet: isDiet,
session_id: sessionId,
})
return reply.status(201).send()
},
)
app.put(
'/:id',
{
preHandler: [checkSessionIdExists],
},
async (request, reply) => {
const sessionId = request.cookies.sessionId
const getMealsParamsSchema = z.object({
id: z.string().uuid(),
})
const { id } = getMealsParamsSchema.parse(request.params)
const editMealBodySchema = z.object({
name: z.string(),
description: z.string(),
datetimeMeal: z.string(),
isDiet: z.boolean(),
})
const { name, description, datetimeMeal, isDiet } =
editMealBodySchema.parse(request.body)
await knex('meals').where({ id, session_id: sessionId }).update({
name,
description,
datetime_meal: datetimeMeal,
is_diet: isDiet,
})
return reply.status(204).send()
},
)
app.delete(
'/:id',
{
preHandler: [checkSessionIdExists],
},
async (request, reply) => {
const { sessionId } = request.cookies
const getMealsParamsSchema = z.object({
id: z.string().uuid(),
})
const { id } = getMealsParamsSchema.parse(request.params)
await knex('meals').where({ id, session_id: sessionId }).delete()
return reply.status(204).send()
},
)
}
|
use anyhow;
use cpal::{
traits::{DeviceTrait, HostTrait, StreamTrait},
FromSample, SizedSample,
};
use ljud::*;
// see the `full` folder for the params
const ELEVATION: &str = "-20";
const AZIMUTH: &str = "270";
// const AZIMUTH: &str = "090";
// const AZIMUTH: &str = "000";
fn main() -> anyhow::Result<()> {
let host = cpal::default_host();
let device = host
.default_output_device()
.expect("failed to find output device");
println!("Output device: {}", device.name()?);
let config = device.default_output_config().unwrap();
println!("Default output config: {:?}", config);
match config.sample_format() {
cpal::SampleFormat::I8 => run::<i8>(&device, &config.into()),
cpal::SampleFormat::I16 => run::<i16>(&device, &config.into()),
// cpal::SampleFormat::I24 => run::<I24>(&device, &config.into()),
cpal::SampleFormat::I32 => run::<i32>(&device, &config.into()),
// cpal::SampleFormat::I48 => run::<I48>(&device, &config.into()),
cpal::SampleFormat::I64 => run::<i64>(&device, &config.into()),
cpal::SampleFormat::U8 => run::<u8>(&device, &config.into()),
cpal::SampleFormat::U16 => run::<u16>(&device, &config.into()),
// cpal::SampleFormat::U24 => run::<U24>(&device, &config.into()),
cpal::SampleFormat::U32 => run::<u32>(&device, &config.into()),
// cpal::SampleFormat::U48 => run::<U48>(&device, &config.into()),
cpal::SampleFormat::U64 => run::<u64>(&device, &config.into()),
cpal::SampleFormat::F32 => run::<f32>(&device, &config.into()),
cpal::SampleFormat::F64 => run::<f64>(&device, &config.into()),
sample_format => panic!("Unsupported sample format '{sample_format}'"),
}
}
const BLOCK_SIZE: usize = 128;
pub fn run<T>(device: &cpal::Device, config: &cpal::StreamConfig) -> Result<(), anyhow::Error>
where
T: SizedSample + FromSample<f32>,
{
let sample_rate = config.sample_rate.0;
let channels = config.channels as usize;
// let azimuth = "270"; // see the `full` folder
let mut ctx = Context::new()
.channels(channels as u8)
.sample_rate(sample_rate)
.buffer_size(BLOCK_SIZE as u32)
.set_graph(svec![(
"output",
svec![
audio_player("sin440.wav").looping(true).boxed(),
// audio_player("assets/sounds/done.wav").looping(true).boxed(),
convolution(20, 0).boxed(),
// convolution([
// &format!("assets/mit-hrtf/full/elev{ELEVATION}/L{ELEVATION}e{AZIMUTH}a.wav"),
// &format!("assets/mit-hrtf/full/elev{ELEVATION}/R{ELEVATION}e{AZIMUTH}a.wav")
// ])
// .boxed()
]
)])
.init();
let err_fn = |err| eprintln!("an error occurred on stream: {}", err);
let stream = device.build_output_stream(
config,
move |data: &mut [T], _: &cpal::OutputCallbackInfo| {
let blocks_needed = data.len() / 2 / BLOCK_SIZE;
let block_step = channels * BLOCK_SIZE;
for current_block in 0..blocks_needed {
let block = ctx.next_block();
for i in 0..BLOCK_SIZE {
for chan in 0..channels {
let value: T = T::from_sample(block[chan][i]);
data[(i * channels + chan) + (current_block) * block_step] = value;
}
}
}
},
err_fn,
None,
)?;
stream.play()?;
std::thread::sleep(std::time::Duration::from_millis(30000));
Ok(())
}
|
import { Injectable } from '@angular/core';
import { FormControl, Validators } from '@angular/forms';
import { PLLodashService } from '../pl-lodash/pl-lodash.service';
function _isModelEmpty(model: any) {
let emptyVal: boolean = !model || (Array.isArray(model) && !model.length);
// File model is an object - need either file(s) or existing file
if (model && model !== undefined && (model.file !== undefined || model.files !== undefined)) {
if (!model.file && !model.files.length && !model.existingFiles.length) {
emptyVal = true;
} else {
emptyVal = false;
}
}
return emptyVal;
}
@Injectable()
export class PLInputErrorsService {
constructor(private plLodash: PLLodashService) {}
setName(name: string = '') {
if (name) {
return name;
}
return this.plLodash.randomString();
}
isModelEmpty(model: any) {
return _isModelEmpty(model);
}
setDisabled(formControl: any, disabled: boolean, reValidate: boolean = false, model?: any, validations?: any) {
if (formControl && disabled !== undefined) {
let changed = false;
// Important to not toggle unnecessarily - messes with validation.
// Also, will need to revalidate after toggle disabled state.
if (disabled && !formControl.disabled) {
formControl.disable();
changed = true;
} else if (!disabled && !formControl.enabled) {
formControl.enable();
changed = true;
}
if (changed && reValidate) {
this.reValidate(model, formControl, validations);
}
}
}
addFormControl(formControl: any, name: string, modelValue: any, disabled: boolean, validations: any = {}) {
const validators = this.setUpValidators(validations);
formControl.addControl(name, new FormControl({ value: modelValue, disabled: disabled }, validators));
// formControl.addControl(name, new FormControl(modelValue, validators));
}
setUpValidators(validations: any = {}) {
const validators: any[] = [];
if (validations.required) {
validators.push(Validators.required);
}
if (validations.checkboxrequired) {
validators.push(this.validateCheckboxRequired);
}
if (validations.arrayrequired) {
validators.push(this.validateArrayRequired);
}
if (validations.filerequired) {
validators.push(this.validateFileRequired);
}
if (validations.maxfilesize) {
validators.push(this.validateMaxFileSize(validations.maxfilesize));
}
if (validations.fileextensions) {
validators.push(this.validateFileExtensions(validations.fileextensions));
}
if (validations.minlength) {
validators.push(Validators.minLength(validations.minlength));
}
if (validations.maxlength) {
validators.push(Validators.maxLength(validations.maxlength));
}
if (validations.pattern) {
validators.push(Validators.pattern(validations.pattern));
}
if (validations.min || validations.min === 0) {
validators.push(this.validateMin(validations.min));
}
if (validations.max || validations.max === 0) {
validators.push(this.validateMax(validations.max));
}
if (validations.number) {
validators.push(this.validateNumber);
}
if (validations.email) {
validators.push(this.validateEmail);
}
if (validations.url) {
validators.push(this.validateUrl);
}
if (validations.tel) {
validators.push(this.validateTel);
}
if (validations.zipcode) {
validators.push(this.validateZipcode);
}
return validators;
}
validateCheckboxRequired(formControl: any) {
return formControl.value ? null : { checkboxrequired: true };
}
validateArrayRequired(formControl: any) {
return formControl.value && formControl.value.length ? null : { arrayrequired: true };
}
validateFileRequired(formControl: any) {
const model = formControl.value;
const emptyVal = _isModelEmpty(model);
return !emptyVal ? null : { filerequired: true };
}
validateMaxFileSize(maxfilesize: number) {
return (formControl: any) => {
let biggestFileSize = -1;
const model = formControl.value;
if (model) {
if (model.files && model.files.length) {
for (let ii = 0; ii < model.files.length; ii++) {
let file = model.files[ii];
if (file.size > biggestFileSize) {
biggestFileSize = file.size;
}
}
}
if (model.file && model.file.size > biggestFileSize) {
biggestFileSize = model.file.size;
}
if (biggestFileSize > 0) {
// Convert to MB.
biggestFileSize = biggestFileSize / 1024 / 1024;
}
}
return !formControl.value || maxfilesize === null || biggestFileSize < maxfilesize
? null
: {
maxfilesize: { valid: false },
};
};
}
validateFileExtensions(fileextensions: string) {
return (formControl: any) => {
let extensions = fileextensions.split(',');
const model = formControl.value;
let valid = true;
if (model) {
if (model.files && model.files.length) {
for (let ii = 0; ii < model.files.length; ii++) {
let file = model.files[ii];
let extension = this.plLodash.getFileExtension(file.name);
if (extensions.indexOf(extension) < 0) {
valid = false;
break;
}
}
}
if (model.file) {
let extension = this.plLodash.getFileExtension(model.file.name);
if (extensions.indexOf(extension) < 0) {
valid = false;
}
}
}
return !formControl.value || fileextensions === null || valid
? null
: {
fileextensions: { valid: false },
};
};
}
validateMin(min: number) {
return (formControl: any) => {
// value may be 0, so falsy checks against value are insufficient
return typeof(formControl.value) === 'undefined' ||
formControl.value === null ||
formControl.value === '' ||
min === null ||
parseFloat(formControl.value) >= min ? null : { min: { valid: false } };
};
}
validateMax(max: number) {
// value may be 0, so falsy checks against value are insufficient
return (formControl: any) => {
return typeof(formControl.value) === 'undefined' ||
formControl.value === null ||
formControl.value === '' ||
max === null ||
parseFloat(formControl.value) <= max ? null : { max: { valid: false } };
};
}
validateEmail(formControl: any) {
// http://emailregex.com/
const regex = /^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
return !formControl.value || regex.test(formControl.value)
? null
: {
email: { valid: false },
};
}
validateUrl(formControl: any) {
// http://stackoverflow.com/questions/3809401/what-is-a-good-regular-expression-to-match-a-url
const regex = /https?:\/\/(www\.)?[-a-zA-Z0-9@:%._\+~#=]{2,256}\.[a-z]{2,6}\b([-a-zA-Z0-9@:%_\+.~#?&//=]*)/;
return !formControl.value || regex.test(formControl.value)
? null
: {
url: { valid: false },
};
}
validateZipcode(formControl: any) {
const regex = /^\d{5}(?:[-\s]\d{4})?$/;
return !formControl.value || regex.test(formControl.value)
? null
: {
zipcode: { valid: false },
};
}
validateTel(formControl: any) {
//const regex = /[0-9]{9,14}/;
const regex = /^(\(?\+?[0-9]*\)?)?[0-9_\- \(\)]*$/;
return !formControl.value || regex.test(formControl.value)
? null
: {
tel: { valid: false },
};
}
validateNumber(formControl: any) {
const regex = /[0-9]/;
return !formControl.value || regex.test(formControl.value)
? null
: {
number: { valid: false },
};
}
addErrors(formControl: any, newErrors: any = {}) {
let combinedErrors = Object.assign({}, formControl.errors, newErrors);
this.setErrors(formControl, combinedErrors);
}
setErrors(formControl: any, errors1: any) {
let errors = errors1;
if (Object.getOwnPropertyNames(errors).length <= 0) {
errors = null;
}
formControl.setErrors(errors);
}
reValidate(model: any, formControl: any, validations: any = {}, setDirty: boolean = true) {
if (!formControl) {
return;
}
const errors: any[] = [];
const emptyVal = this.isModelEmpty(model);
const newErrors: any = {};
let error: any;
// TODO - reuse the built in validators?
if (validations.required && emptyVal) {
newErrors.required = true;
}
if (validations.checkboxrequired) {
error = this.validateCheckboxRequired({ value: model });
if (error) {
newErrors.checkboxrequired = true;
}
}
if (validations.arrayrequired) {
error = this.validateArrayRequired({ value: model });
if (error) {
newErrors.arrayrequired = true;
}
}
if (validations.filerequired) {
error = this.validateFileRequired({ value: model });
if (error) {
newErrors.filerequired = true;
}
}
if (validations.maxfilesize) {
error = this.validateMaxFileSize(validations.maxfilesize)({
value: model,
});
if (error) {
newErrors.maxfilesize = true;
}
}
if (validations.fileextensions) {
error = this.validateFileExtensions(validations.fileextensions)({
value: model,
});
if (error) {
newErrors.fileextensions = true;
}
}
if ((validations.minlength || validations.minlength === 0) && model.length < validations.minlength) {
newErrors.minlength = true;
}
if (validations.maxlength && model.length > validations.maxlength) {
newErrors.maxlength = true;
}
if (validations.pattern && model.length) {
const regex = new RegExp(validations.pattern);
if (!regex.test(model)) {
newErrors.pattern = true;
}
}
if (validations.min || validations.min === 0) {
error = this.validateMin(validations.min)({ value: model });
if (error) {
newErrors.min = true;
}
}
if (validations.max || validations.max === 0) {
error = this.validateMax(validations.max)({ value: model });
if (error) {
newErrors.max = true;
}
}
if (validations.number) {
error = this.validateMax(validations.max)({ value: model });
if (error) {
newErrors.max = true;
}
}
if (validations.email) {
error = this.validateEmail({ value: model });
if (error) {
newErrors.email = true;
}
}
if (validations.zipcode) {
error = this.validateZipcode({ value: model });
if (error) {
newErrors.zipcode = true;
}
}
if (validations.url) {
error = this.validateUrl({ value: model });
if (error) {
newErrors.url = true;
}
}
if (validations.tel) {
error = this.validateTel({ value: model });
if (error) {
newErrors.tel = true;
}
}
this.setErrors(formControl, newErrors);
if (setDirty) {
formControl.markAsDirty();
}
}
}
|
from collections import OrderedDict
import os
from django.utils._os import safe_join
from django.core.exceptions import ImproperlyConfigured
from django.conf import settings
from django.contrib.staticfiles.finders import FileSystemFinder
from django.core.files.storage import FileSystemStorage
from django.contrib.staticfiles import utils
import tenant_schemas.utils
class TenantStaticFilesFinder(FileSystemFinder):
def __init__(self, apps=None, *args, **kwargs):
# List of locations with static files
self.locations = []
# Maps dir paths to an appropriate storage instance
self.storages = OrderedDict()
if not isinstance(settings.MULTI_TENANT_DIR, str):
raise ImproperlyConfigured(
"You need to set the MULTI_TENANT_DIR setting")
tenant_dir = settings.MULTI_TENANT_DIR
for tenant_name in [f for f in os.listdir(tenant_dir) if os.path.isdir(os.path.join(tenant_dir, f))]:
tenant_static_dir = os.path.join(getattr(settings, 'MULTI_TENANT_DIR', None),
tenant_name,
'static')
if os.path.exists(tenant_static_dir):
self.locations.append((tenant_name, tenant_static_dir))
for prefix, root in self.locations:
filesystem_storage = FileSystemStorage(location=root)
filesystem_storage.prefix = prefix
self.storages[root] = filesystem_storage
super(FileSystemFinder, self).__init__(*args, **kwargs)
def find(self, path, all=False):
"""
Looks for files in the client static directories.
static/assets/greatbarier/images/logo.jpg
will translate to
MULTI_TENANT_DIR/greatbarier/static/images/logo.jpg
"""
tenants = tenant_schemas.utils.get_tenant_model().objects.all()
tenant_dir = getattr(settings, 'MULTI_TENANT_DIR', None)
if not tenant_dir:
return []
for tenant in tenants:
if "{0}/".format(tenant.client_name) in path:
tenant_path = path.replace('{0}/'.format(tenant.client_name),
'{0}/static/'.format(tenant.client_name))
local_path = safe_join(tenant_dir, tenant_path)
if os.path.exists(local_path):
if all:
return [local_path]
return local_path
return []
|
// SPDX-License-Identifier: UNLICENSED
pragma solidity 0.8.17;
import "../Base.sol";
import "../rewards/ERC20.sol";
import "../rewards/ERC1155.sol";
import "@openzeppelin/contracts/interfaces/IERC20.sol";
import "@openzeppelin/contracts/interfaces/IERC165.sol";
import "@openzeppelin/contracts/interfaces/IERC1155.sol";
import "@openzeppelin/contracts/interfaces/IERC1155Receiver.sol";
abstract contract ERC1155Staking is BaseStaking, IERC165, IERC1155Receiver {
IERC1155 private _stakeToken;
uint256 private _stakeNftId;
event StakingNftTokenChanged(address token, uint256 nftId);
/**
* @dev Set the token used for staking
* @param token Address of the token contract
* @param nftId Id of the NFT to accept for stake
*
* Reverts if the token is set to address(0)
*/
function setStakingToken(address token, uint256 nftId) external onlyOwner {
require(token != address(0), "Can't set token to address(0)");
require(
address(_stakeToken) == address(0),
"Staking token is already set"
);
_stakeToken = IERC1155(token);
_stakeNftId = nftId;
emit StakingNftTokenChanged(token, nftId);
}
/**
* @dev Get the address of the token used for staking
* @return (address, uint256) Address of the token contract and the NFT ID
*/
function getStakingToken() external view returns (address, uint256) {
return (address(_stakeToken), _stakeNftId);
}
/**
* @dev Transfers `amount` tokens from the user to this contract
* @param amount Amount of tokens being staked
*
* Reverts if `amount` is not greater than 0
* Reverts if staking window is smaller than the block timestamp
*/
function stake(uint256 amount) external {
require(amount > 0, "Cannot stake 0 tokens");
require(_unlockTime > 0, "Cannot stake yet");
require(block.timestamp <= _unlockTime, "Cannot stake anymore");
address user = _msgSender();
recordStakeWeight(user, amount);
_stake[user] += amount;
emit Staked(user, amount);
_stakeToken.safeTransferFrom(
user,
address(this),
_stakeNftId,
amount,
""
);
}
/**
* @dev Unstake tokens
*
* Reverts if user stake amount is not greater than 0
* Reverts if block timestamp is not bigger than the unlock time
* or the user is not allowed to unstake early
*
* A penalty may be applied if the user removes their stake early
*/
function unstake() external {
address user = _msgSender();
require(_stake[user] > 0, "Cannot unstake 0 tokens");
require(canUnstake(user), "Cannot unstake yet");
uint256 amount = _stake[user];
_stake[user] = 0;
if (block.timestamp < _unlockTime) {
uint256 penalty = (amount * _penalties[user]) / 100;
emit UnStaked(user, amount - penalty);
/**
* No reward distributed, decrease the stake pool size
*/
_stakePoolWeight -= _stakeWeight[user];
_stakeWeight[user] = 0;
if (penalty > 0) {
_stakeToken.safeTransferFrom(
address(this),
_penaltyAddress,
_stakeNftId,
penalty,
""
);
}
_stakeToken.safeTransferFrom(
address(this),
user,
_stakeNftId,
amount - penalty,
""
);
} else {
emit UnStaked(user, amount);
_stakeToken.safeTransferFrom(
address(this),
user,
_stakeNftId,
amount,
""
);
uint256 reward = getRewardSize(user);
_stakeWeight[user] = 0;
sendRewards(user, reward);
}
}
/* ERC1155 methods */
/**
* @dev See {IERC1155-onERC1155Received}.
*/
function onERC1155Received(
address,
address,
uint256,
uint256,
bytes calldata
) external view returns (bytes4) {
return IERC1155Receiver(this).onERC1155Received.selector;
}
/* ERC1155 methods */
/**
* @dev See {IERC1155-onERC1155BatchReceived}.
*/
function onERC1155BatchReceived(
address,
address,
uint256[] calldata,
uint256[] calldata,
bytes calldata
) external pure returns (bytes4) {
return 0x00000000;
}
/* ERC165 methods */
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId)
public
pure
virtual
override(IERC165)
returns (bool)
{
return interfaceId == type(IERC1155Receiver).interfaceId;
}
}
contract ERC1155StakerERC20Rewarder is ERC1155Staking, ERC20Rewards {}
contract ERC1155StakerERC1155Rewarder is
ERC1155Staking,
ERC1155RewardsNonReceiver
{}
|
# TFT helper
## Description
This project is designed to automate certain actions within a game environment. It utilizes image recognition through Google Tesseract OCR to read text from the game screen and perform actions based on predefined conditions. The script can start and stop gameplay, find matches, accept matches, and more based on in-game stages or events.
## Environment Setup
### Requirements:
- Python 3.6 or higher
- Pillow (PIL Fork)
- Google Tesseract OCR
- Supported systems: Windows / macOS / Linux
This project has been developed and tested on Windows 10.
### Installation
#### 1. Install Google Tesseract OCR
- **Tesseract OCR GitHub repository:** [https://github.com/tesseract-ocr/tesseract](https://github.com/tesseract-ocr/tesseract)
- **Windows Tesseract download link:** [https://digi.bib.uni-mannheim.de/tesseract/](https://digi.bib.uni-mannheim.de/tesseract/)
- **macOS and Linux installation guide:** [Tesseract OCR Installation](https://tesseract-ocr.github.io/tessdoc/Installation.html)
#### 2. Install Required Python Packages
Install the required Python packages using `pip`:
```bash
pip install pillow pytesseract pyautogui keyboard
```
Note: Depending on your system, you might need to use pip3 instead of pip.
### Usage
To use this script, simply run the `main.py` file from your terminal:
```bash
python main.py
```
Or on some systems:
```bash
python3 main.py
```
### Controls
- Press q to stop the automation script.
- Hotkeys and other controls are defined within the script and can be customized as needed.
### Features
- Text recognition from the game screen.
- Game start, stop, and find match automation.
- In-game action automation based on stage detection.
- Logging system to track actions and events.
### Contributing
- Contributions to this project are welcome. Please ensure that you update tests as appropriate.
### License
[MIT](https://choosealicense.com/licenses/mit/)
### Disclaimer
This project is for educational purposes only. The author is not responsible for any misuse or damage caused by this program.
|
# Copyright (c) 2022, NVIDIA CORPORATION. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import argparse
import os
import sys
import traceback
from nvflare.cli_exception import CLIException
from nvflare.cli_unknown_cmd_exception import CLIUnknownCmdException
from nvflare.dashboard.cli import define_dashboard_parser, handle_dashboard
from nvflare.fuel.hci.tools.authz_preview import define_authz_preview_parser, run_command
from nvflare.lighter.provision import define_provision_parser, handle_provision
from nvflare.private.fed.app.simulator.simulator import define_simulator_parser, run_simulator
from nvflare.tool.job.job_cli import def_job_cli_parser, handle_job_cli_cmd
from nvflare.tool.poc.poc_commands import def_poc_parser, handle_poc_cmd
from nvflare.tool.preflight_check import check_packages, define_preflight_check_parser
from nvflare.utils.cli_utils import (
create_job_template_config,
create_poc_workspace_config,
create_startup_kit_config,
get_hidden_config,
save_config,
)
CMD_POC = "poc"
CMD_PROVISION = "provision"
CMD_PREFLIGHT_CHECK = "preflight_check"
CMD_SIMULATOR = "simulator"
CMD_DASHBOARD = "dashboard"
CMD_AUTHZ_PREVIEW = "authz_preview"
CMD_JOB = "job"
CMD_CONFIG = "config"
def check_python_version():
if sys.version_info >= (3, 11):
raise RuntimeError("Python versions 3.11 and above are not yet supported. Please use Python 3.8, 3.9 or 3.10.")
if sys.version_info < (3, 8):
raise RuntimeError("Python versions 3.6 and below are not supported. Please use Python 3.8, 3.9 or 3.10")
def def_provision_parser(sub_cmd):
cmd = CMD_PROVISION
provision_parser = sub_cmd.add_parser(cmd)
define_provision_parser(provision_parser)
return {cmd: provision_parser}
def def_dashboard_parser(sub_cmd):
cmd = CMD_DASHBOARD
dashboard_parser = sub_cmd.add_parser(cmd)
define_dashboard_parser(dashboard_parser)
return {cmd: dashboard_parser}
def def_preflight_check_parser(sub_cmd):
cmd = CMD_PREFLIGHT_CHECK
checker_parser = sub_cmd.add_parser(cmd)
define_preflight_check_parser(checker_parser)
return {cmd: checker_parser}
def def_simulator_parser(sub_cmd):
cmd = CMD_SIMULATOR
simulator_parser = sub_cmd.add_parser(cmd)
define_simulator_parser(simulator_parser)
return {cmd: simulator_parser}
def handle_simulator_cmd(simulator_args):
status = run_simulator(simulator_args)
# make sure the script terminate after run
if status:
sys.exit(status)
def def_authz_preview_parser(sub_cmd):
cmd = CMD_AUTHZ_PREVIEW
authz_preview_parser = sub_cmd.add_parser(cmd)
define_authz_preview_parser(authz_preview_parser)
return {cmd: authz_preview_parser}
def handle_authz_preview(args):
run_command(args)
def def_config_parser(sub_cmd):
cmd = "config"
config_parser = sub_cmd.add_parser(cmd)
config_parser.add_argument(
"-d", "--startup_kit_dir", type=str, nargs="?", default=None, help="startup kit location"
)
config_parser.add_argument(
"-pw", "--poc_workspace_dir", type=str, nargs="?", default=None, help="POC workspace location"
)
config_parser.add_argument(
"-jt", "--job_templates_dir", type=str, nargs="?", default=None, help="job templates location"
)
config_parser.add_argument("-debug", "--debug", action="store_true", help="debug is on")
return {cmd: config_parser}
def handle_config_cmd(args):
config_file_path, nvflare_config = get_hidden_config()
nvflare_config = create_startup_kit_config(nvflare_config, args.startup_kit_dir)
nvflare_config = create_poc_workspace_config(nvflare_config, args.poc_workspace_dir)
nvflare_config = create_job_template_config(nvflare_config, args.job_templates_dir)
save_config(nvflare_config, config_file_path)
def parse_args(prog_name: str):
_parser = argparse.ArgumentParser(description=prog_name)
_parser.add_argument("--version", "-V", action="store_true", help="print nvflare version")
sub_cmd = _parser.add_subparsers(description="sub command parser", dest="sub_command")
sub_cmd_parsers = {}
sub_cmd_parsers.update(def_poc_parser(sub_cmd))
sub_cmd_parsers.update(def_preflight_check_parser(sub_cmd))
sub_cmd_parsers.update(def_provision_parser(sub_cmd))
sub_cmd_parsers.update(def_simulator_parser(sub_cmd))
sub_cmd_parsers.update(def_dashboard_parser(sub_cmd))
sub_cmd_parsers.update(def_authz_preview_parser(sub_cmd))
sub_cmd_parsers.update(def_job_cli_parser(sub_cmd))
sub_cmd_parsers.update(def_config_parser(sub_cmd))
args, argv = _parser.parse_known_args(None, None)
cmd = args.__dict__.get("sub_command")
sub_cmd_parser = sub_cmd_parsers.get(cmd)
if argv:
msg = f"{prog_name} {cmd}: unrecognized arguments: {''.join(argv)}\n"
print(f"\nerror: {msg}")
sub_cmd_parser.print_help()
_parser.exit(2, "\n")
return _parser, _parser.parse_args(), sub_cmd_parsers
handlers = {
CMD_POC: handle_poc_cmd,
CMD_PROVISION: handle_provision,
CMD_PREFLIGHT_CHECK: check_packages,
CMD_SIMULATOR: handle_simulator_cmd,
CMD_DASHBOARD: handle_dashboard,
CMD_AUTHZ_PREVIEW: handle_authz_preview,
CMD_JOB: handle_job_cli_cmd,
CMD_CONFIG: handle_config_cmd,
}
def run(prog_name):
cwd = os.getcwd()
sys.path.append(cwd)
prog_parser, prog_args, sub_cmd_parsers = parse_args(prog_name)
sub_cmd = None
try:
sub_cmd = prog_args.sub_command
if sub_cmd:
handlers[sub_cmd](prog_args)
elif prog_args.version:
print_nvflare_version()
else:
prog_parser.print_help()
except CLIUnknownCmdException as e:
print(e)
print_help(prog_parser, sub_cmd, sub_cmd_parsers)
sys.exit(1)
except CLIException as e:
print(e)
sys.exit(1)
except Exception as e:
print(f"\nUnable to handle command: {sub_cmd} due to: {e} \n")
if hasattr(prog_args, "debug"):
if prog_args.debug:
print(traceback.format_exc())
else:
print_help(prog_parser, sub_cmd, sub_cmd_parsers)
def print_help(prog_parser, sub_cmd, sub_cmd_parsers):
if sub_cmd:
sub_parser = sub_cmd_parsers[sub_cmd]
if sub_parser:
print(f"sub_parser is: {sub_parser}")
sub_parser.print_help()
else:
prog_parser.print_help()
else:
prog_parser.print_help()
def print_nvflare_version():
import nvflare
print(f"NVFlare version is {nvflare.__version__}")
def main():
check_python_version()
run("nvflare")
if __name__ == "__main__":
main()
|
/* -*- Mode: C; indent-tabs-mode: t; c-basic-offset: 4; tab-width: 4 -*- */
/*
* gtimer.c
* Copyright (C) 2013 Jente Hidskes <jthidskes@outlook.com>
*
* gtimeutils 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.
*
* gtimeutils 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/>.
*/
#include <config.h>
#include <gtk/gtk.h>
#include <canberra.h>
#include <glib/gi18n.h>
#include <glib/gprintf.h>
#include <libnotify/notify.h>
#include <stdlib.h>
enum {
STARTED,
PAUSED,
STOPPED
};
ca_context *sound;
static gboolean start_on_run = FALSE;
const gchar *entry_text = N_("Notification text");
gint state = STOPPED, hours = 0, minutes = 0, seconds = 0;
GtkWidget *timer_display, *hbox1, *entry, *button_timer, *button_reset, *spin_seconds, *spin_minutes, *spin_hours;
static GOptionEntry entries[] = {
{ "seconds", 's', 0, G_OPTION_ARG_INT, &seconds, N_("Specify seconds to count down from"), NULL },
{ "minutes", 'm', 0, G_OPTION_ARG_INT, &minutes, N_("Specify minutes to count down from"), NULL },
{ "hours", 'u', 0, G_OPTION_ARG_INT, &hours, N_("Specify hours to count down from"), NULL },
{ "text", 't', 0, G_OPTION_ARG_STRING, &entry_text, N_("Set an alternative notification text"), NULL },
{ "run", 'r', 0, G_OPTION_ARG_NONE, &start_on_run, N_("Immediately start the countdown"), NULL },
{ NULL },
};
void reset_display (void) {
gchar *markup;
markup = g_markup_printf_escaped ("<span font=\"48\" weight=\"heavy\"><tt>%s</tt></span>", _("HH:MM:SS"));
gtk_label_set_markup (GTK_LABEL (timer_display), markup);
g_free (markup);
}
void notify (void) {
NotifyNotification *notify;
GError *error_notify = NULL;
entry_text = gtk_entry_get_text (GTK_ENTRY (entry));
if(g_strcmp0 (entry_text, "Notification text") != 0)
notify = notify_notification_new (entry_text, NULL, "clocks");
else
notify = notify_notification_new (_("Time is up!"), NULL, "clocks");
notify_notification_set_category (notify, "GTimeUtils");
notify_notification_set_urgency (notify, NOTIFY_URGENCY_NORMAL);
notify_notification_show (notify, &error_notify);
if(error_notify)
g_fprintf (stderr, "Can not initialize notification: %s\n", error_notify->message);
ca_context_play(sound, 0, CA_PROP_APPLICATION_NAME, "Gtimer", CA_PROP_EVENT_ID, "complete-copy", CA_PROP_MEDIA_ROLE, "notification", CA_PROP_APPLICATION_ICON_NAME, "clocks", CA_PROP_CANBERRA_CACHE_CONTROL, "never", NULL);
}
void counter (void) {
gchar *markup, output[100];
seconds = gtk_spin_button_get_value (GTK_SPIN_BUTTON (spin_seconds));
minutes = gtk_spin_button_get_value (GTK_SPIN_BUTTON (spin_minutes));
hours = gtk_spin_button_get_value (GTK_SPIN_BUTTON (spin_hours));
seconds += 60 * minutes;
seconds += 3600 * hours;
if(seconds == 0) {
notify();
gtk_button_set_label (GTK_BUTTON (button_timer), _("Start"));
gtk_widget_set_sensitive (button_reset, FALSE);
gtk_widget_set_sensitive (entry, TRUE);
state = STOPPED;
start_on_run = FALSE;
} else {
seconds -= 1;
hours = seconds / 3600;
seconds -= 3600 * hours;
minutes = seconds / 60;
seconds -= 60 * minutes;
gtk_spin_button_set_value (GTK_SPIN_BUTTON (spin_seconds), seconds);
gtk_spin_button_set_value (GTK_SPIN_BUTTON (spin_minutes), minutes);
gtk_spin_button_set_value (GTK_SPIN_BUTTON (spin_hours), hours);
sprintf (output, "%02d:%02d:%02d", hours, minutes, seconds);
gtk_label_set_text (GTK_LABEL (timer_display), output);
markup = g_markup_printf_escaped ("<span font=\"48\" weight=\"heavy\"><tt>%s</tt></span>", output);
gtk_label_set_markup (GTK_LABEL (timer_display), markup);
g_free (markup);
}
}
gboolean timer_function (void) {
if(state == STARTED || start_on_run)
counter();
return TRUE;
}
void on_timer_button_clicked (void) {
if(state == STOPPED) {
gtk_button_set_label (GTK_BUTTON (button_timer), _("Stop"));
gtk_widget_set_sensitive (button_reset, TRUE);
gtk_widget_set_sensitive (entry, FALSE);
state = STARTED;
} else if(state == PAUSED) {
gtk_button_set_label (GTK_BUTTON (button_timer), _("Stop"));
state = STARTED;
} else if(state == STARTED) {
gtk_button_set_label (GTK_BUTTON (button_timer), _("Continue"));
state = PAUSED;
}
}
void on_reset_button_clicked (void) {
if(state == PAUSED || state == STARTED) {
state = STOPPED;
gtk_button_set_label (GTK_BUTTON (button_timer), _("Start"));
reset_display();
gtk_spin_button_set_value (GTK_SPIN_BUTTON (spin_seconds), 0);
gtk_spin_button_set_value (GTK_SPIN_BUTTON (spin_minutes), 0);
gtk_spin_button_set_value (GTK_SPIN_BUTTON (spin_hours), 0);
gtk_widget_set_sensitive (button_reset, FALSE);
gtk_widget_set_sensitive (entry, TRUE);
}
}
int main (int argc, char *argv[]) {
GError *error_parsearg = NULL;
GOptionContext *context;
GtkWidget *window, *vbox, *hbox2;
GtkAdjustment *sadj, *madj, *hadj;
#ifdef ENABLE_NLS
bindtextdomain (GETTEXT_PACKAGE, PACKAGE_LOCALE_DIR);
bind_textdomain_codeset (GETTEXT_PACKAGE, "UTF-8");
textdomain (GETTEXT_PACKAGE);
#endif
gtk_init (&argc, &argv);
notify_init ("Gtimer");
ca_context_create (&sound);
context = g_option_context_new (_("- a simple countdown timer"));
g_option_context_add_main_entries (context, entries, NULL);
#ifdef ENABLE_NLS
g_option_context_set_translation_domain (context, GETTEXT_PACKAGE);
#endif
if (!g_option_context_parse (context, &argc, &argv, &error_parsearg)) {
g_fprintf (stderr, "%s\n", error_parsearg->message);
exit(1);
}
vbox = gtk_box_new (GTK_ORIENTATION_VERTICAL, 5);
hbox1 = gtk_box_new (GTK_ORIENTATION_HORIZONTAL, 0);
hbox2 = gtk_box_new (GTK_ORIENTATION_HORIZONTAL, 0);
gtk_box_set_spacing (GTK_BOX (hbox2), 5);
gtk_container_set_border_width (GTK_CONTAINER (vbox), 5);
timer_display = gtk_label_new (NULL);
reset_display();
sadj = gtk_adjustment_new (0, 0, 60, 1, 1, 0);
madj = gtk_adjustment_new (0, 0, 60, 1, 1, 0);
hadj = gtk_adjustment_new (0, 0, 24, 1, 1, 0);
spin_seconds = gtk_spin_button_new (sadj, 1, 0);
spin_minutes = gtk_spin_button_new (madj, 1, 0);
spin_hours = gtk_spin_button_new (hadj, 1, 0);
gtk_spin_button_set_wrap (GTK_SPIN_BUTTON (spin_seconds), TRUE);
gtk_spin_button_set_value (GTK_SPIN_BUTTON (spin_seconds), seconds);
g_object_set (spin_seconds, "shadow-type", GTK_SHADOW_IN, NULL);
gtk_spin_button_set_wrap (GTK_SPIN_BUTTON (spin_minutes), TRUE);
gtk_spin_button_set_value (GTK_SPIN_BUTTON (spin_minutes), minutes);
g_object_set (spin_minutes, "shadow-type", GTK_SHADOW_IN, NULL);
gtk_spin_button_set_wrap (GTK_SPIN_BUTTON (spin_hours), TRUE);
gtk_spin_button_set_value (GTK_SPIN_BUTTON (spin_hours), hours);
g_object_set (spin_hours, "shadow-type", GTK_SHADOW_IN, NULL);
entry = gtk_entry_new();
gtk_entry_set_text (GTK_ENTRY (entry), entry_text);
button_timer = gtk_button_new();
gtk_button_set_label (GTK_BUTTON (button_timer), _("Start"));
button_reset = gtk_button_new_with_label (_("Reset"));
gtk_widget_set_sensitive (button_reset, FALSE);
gtk_box_pack_start (GTK_BOX (hbox1), spin_hours, TRUE, FALSE, 5);
gtk_box_pack_start (GTK_BOX (hbox1), spin_minutes, TRUE, FALSE, 5);
gtk_box_pack_start (GTK_BOX (hbox1), spin_seconds, TRUE, FALSE, 5);
gtk_box_pack_start (GTK_BOX (vbox), timer_display, FALSE, TRUE, 5);
gtk_box_pack_start (GTK_BOX (hbox2), button_timer, TRUE, TRUE, 0);
gtk_box_pack_start (GTK_BOX (hbox2), button_reset, TRUE, TRUE, 0);
gtk_container_add (GTK_CONTAINER (vbox), hbox1);
gtk_box_pack_start (GTK_BOX (vbox), entry, FALSE, TRUE, 5);
gtk_container_add (GTK_CONTAINER (vbox), hbox2);
window = gtk_window_new (GTK_WINDOW_TOPLEVEL);
gtk_window_set_title (GTK_WINDOW (window), "Gtimer");
gtk_container_add (GTK_CONTAINER (window), vbox);
gtk_widget_show_all (window);
g_timeout_add_seconds (1, (GSourceFunc) timer_function, NULL);
g_signal_connect (window, "destroy", G_CALLBACK (gtk_main_quit), NULL);
g_signal_connect (button_timer, "clicked", G_CALLBACK (on_timer_button_clicked), NULL);
g_signal_connect (button_reset, "clicked", G_CALLBACK (on_reset_button_clicked), NULL);
gtk_main();
notify_uninit();
ca_context_destroy (sound);
g_option_context_free (context);
return 0;
}
|
# -*- coding: utf-8 -*-
import scrapy
import datetime
import time
import scrapy
import re
from scrapy.linkextractors import LinkExtractor
from scrapy.spiders import CrawlSpider, Rule
from yqc_tianjin_spider.items import YqcTianjinSpiderItem
keys = ['创新',
'创业',
'改革',
'促进',
'发展',
'措施',
'进一步',
'扩大',
'培育',
'工作方案',
'行动计划',
'专项资金',
'鼓励',
'扶持',
'加快',
'管理',
'推动',
'激发',
'实施',
'推广',
'产业',
'推进',
'加强',
'改进',
'提升',
'规划',
'落实',
'政策',
'征集',
'建设',
'构建',
'行动方案',
'实现',
'开展',
'开放',
'总体方案',
'投资',
'补贴',
'申报',
'征收',
'引导基金',
'资助',
'降低',
'深化',
'科技']
count = 1
class TianjinSpider(CrawlSpider):
name = 'tianjin'
allowed_domains = ['tj.gov.cn']
start_urls = ['http://gk.tj.gov.cn/index_47.shtml']
rules = (
Rule(LinkExtractor(allow=r'.*gk.tj.gov.cn.*'),
callback='parse_page',
follow=False),
)
cont_dict = {}
def parse_item(self, response):
print("5. parse_item(): " + datetime.datetime.now().strftime(
'%Y-%m-%d %H:%M:%S.%f') + " -> " + response.url)
title = response.xpath("//*[@id='span_docTitle']/text()").get()
cont = response.xpath("//*[@class='article']").get()
index_id = response.xpath("/html/body/div[5]/div[2]/table/tbody/tr[1]/td[2]/text()").get()
pub_org = response.xpath("//*[@id='span_publisher']/text()[2]").get()
pub_time = response.xpath("/html/body/div[5]/div[2]/table/tbody/tr[2]/td[4]/text()[2]").get()
doc_id = response.xpath("/html/body/div[5]/div[2]/table/tbody/tr[2]/td[2]/text()").get()
region = str('天津')
update_time = datetime.datetime.now().strftime("%Y-%m-%d 00:00:00")
if not title:
return
print("\t>>> " + title)
for key in keys:
if key in title:
self.dict_add_one(re.sub('[\s+]', ' ', title), response.url, re.sub('[\s+]', ' ', cont),
re.sub('[\s+]', ' ', pub_time), re.sub('[\s+]', ' ', pub_org), index_id, doc_id,
region, update_time, key)
item = YqcTianjinSpiderItem(cont_dict=self.cont_dict)
yield item
def dict_add_one(self, title, url, cont, pub_time, pub_org, index_id, doc_id, region, update_time, doc_key):
time.sleep(0.3)
if title in self.cont_dict:
self.cont_dict[title]['key_cnt'] += 1
self.cont_dict[title]['doc_key'] = self.cont_dict[title]['doc_key'] + ',' + doc_key
else:
cnt_dict = {'key_cnt': 1, 'title': title, 'url': url, 'cont': cont, 'pub_time': pub_time,
'pub_org': pub_org, 'index_id': index_id, 'doc_id': doc_id, 'region': region,
'update_time': update_time, 'doc_key': doc_key}
self.cont_dict[title] = cnt_dict
def parse_page(self, response):
url = response.url
print("4. parse_page(): " + datetime.datetime.now().strftime(
'%Y-%m-%d %H:%M:%S.%f') + " -> " + url)
url_prefix = 'http://gk.tj.gov.cn/gkml'
if str('REPORT_NDOC_006051') in url or str('REPORT_NDOC_006010') in url:
print("\t>>> debug: " + url)
if str('currentPage') in url:
tr_list = response.xpath("//*[@id='main']/div[1]/div/div[2]/table/tbody//tr")
for tr in tr_list:
# print(tr)
url = tr.xpath("./td[1]/a/@href").get()
full_url = url_prefix + url
yield scrapy.Request(full_url, callback=self.parse_item)
else:
if str('REPORT_NDOC_006051') in url or str('REPORT_NDOC_006010') in url:
print('\t>>> no currentPage')
title = response.xpath("//*[@class='content_title content_title_h1']/text()").get()
cont = response.xpath("//*[@class='content_article']").get()
index_id = response.xpath("//*[@id='zoomcon']/p[1]/text()").get()
if not index_id or index_id is None or len(index_id) < 2:
index_id = response.xpath("//*[@id='zoomcon']/p[1]/span/text()").get()
pub_org = response.xpath("//*[@id='laiyuan']/b/text()").get()
pub_time = response.xpath("//ul[@class='fl']/li[@class='date']/span/text()").get()
doc_id = str('_NULL')
region = str('广州')
update_time = datetime.datetime.now().strftime("%Y-%m-%d 00:00:00")
if not title:
return
print("\t>>> " + title)
for key in keys:
if key in title:
# print("\t>>> included")
self.dict_add_one(re.sub('[\s+]', ' ', title), response.url, re.sub('[\s+]', ' ', cont),
re.sub('[\s+]', ' ', pub_time), pub_org, index_id, doc_id, region, update_time,
key)
item = YqcTianjinSpiderItem(cont_dict=self.cont_dict)
print("6. parse_page(): " + datetime.datetime.now().strftime(
'%Y-%m-%d %H:%M:%S.%f') + " -> " + url)
# print("\n")
# print(item)
yield item
|
https://leetcode.com/problems/apples-oranges/
# Write your MySQL query statement below
/**
One Table: Sales
(sale_date, fruit) is the primary key for Sales table.
Sales table contains the sales of "apples" and "oranges" sold each day.
PROBLEM: report the difference between the number of apples and oranges sold each day.
STEPS:
each day::: GROUP BY sale_date
SUM (Case Statement)
USING WINDOW FUNCTION to solve::::::::::
SELECT DISTINCT
sale_date,
SUM(CASE WHEN fruit = 'apples' THEN sold_num
WHEN fruit = 'oranges' THEN -sold_num END) OVER( PARTITION BY sale_date ORDER BY sale_date)
AS diff
FROM Sales
*/
SELECT
sale_date,
SUM(CASE WHEN fruit = 'apples' THEN sold_num
WHEN fruit = 'oranges' THEN -sold_num END)
AS diff
FROM Sales
GROUP BY sale_date
ORDER BY sale_date
|
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title th:text="${post.title}">Document</title>
<link rel="icon" href="/assets/icon.png">
<link rel="stylesheet" href="/css/style.css" />
<link rel="stylesheet" href="/css/layout.css" />
</head>
<body>
<div class="container">
<header th:insert="Fragments.html :: header"></header>
<main class="main-content">
<section class="main-content__post post">
<h3 class="post__topic-title main-content__topic-title"><a th:text="${post.topic.name}" th:href="'/topics/'+${post.topic.id}" class="main-content__topic-link post__topic-link">Topic</a>
</h3>
<h2 th:text="${post.title}" class="post__title main-content__topic-title">Post Title</h2>
<p class="postDate" th:text="'Posted: '+ ${postDateTime}"></p>
<p th:text="${post.content}" class="post__content">Lorem ipsum dolor sit, amet consectetur adipisicing elit. Doloremque blanditiis, aut quae fuga id quis ut.
Eligendi necessitatibus blanditiis officia, odio deleniti natus molestiae fugiat ex quod vel aliquam illum.
</p>
<div>
<ul>
<li class="postCommentLine" th:each="theComment : ${post.postComments}" th:text="'* ' + ${theComment}"></li>
</ul>
</div>
<br>
<div>
<form th:action="|/submitHashtag|" method="POST">
<div class="AddHashtag">
<h2>Add A Hashtag</h2>
<p class="emptyHashtagInput" >(Duplicated hashtag will not add to the list.)</p>
<label style="color: #84A98C">Hashtag: </label>
<input class="inputText" type="text" name = "hashtagContent" placeholder="#GoodPost">
<input type="hidden" name = "postId" th:value="${post.id}">
<button class="submitButtonHash" type="submit"><strong>Submit Hashtag</strong></button>
</div>
</form>
</div>
<div>
<form th:action="|/submitComment|" method="POST">
<input type="hidden" name = "postId" th:value="${post.id}">
<div class="AddComment">
<h2>Add A Comment</h2>
<p class="emptyHashtagInput" >(Duplicated comment will not add to the list.)</p>
<label style="color: #84A98C">Comment: </label>
<textarea id="postComment" name="postComment" rows="3" cols="50" maxlength="150" placeholder="Good post"></textarea>
<div>
<br>
<button class="submitButtonComment" type="submit"><strong>Submit Comment</strong></button>
</div>
</div>
</form>
</div>
</section>
</main>
</div>
</body>
</html>
|
use helpers::C;
use sov_bank::{get_token_address, Bank, BankConfig, CallMessage, Coins, TotalSupplyResponse};
use sov_modules_api::default_context::DefaultContext;
use sov_modules_api::utils::generate_address;
use sov_modules_api::{Address, Context, Error, Module, WorkingSet};
use sov_prover_storage_manager::{new_orphan_storage, SnapshotManager};
use sov_state::{DefaultStorageSpec, ProverStorage};
mod helpers;
pub type Storage = ProverStorage<DefaultStorageSpec, SnapshotManager>;
#[test]
fn freeze_token() {
let bank = Bank::<C>::default();
let tmpdir = tempfile::tempdir().unwrap();
let mut working_set = WorkingSet::new(new_orphan_storage(tmpdir.path()).unwrap());
let empty_bank_config = BankConfig::<C> { tokens: vec![] };
bank.genesis(&empty_bank_config, &mut working_set).unwrap();
let minter_address = generate_address::<DefaultContext>("minter");
let sequencer_address = generate_address::<DefaultContext>("sequencer");
let minter_context = C::new(minter_address, sequencer_address, 1);
let salt = 0;
let token_name = "Token1".to_owned();
let initial_balance = 100;
let token_address = get_token_address::<C>(&token_name, minter_address.as_ref(), salt);
// ---
// Deploying token
let mint_message = CallMessage::CreateToken {
salt,
token_name: token_name.clone(),
initial_balance,
minter_address,
authorized_minters: vec![minter_address],
};
let _minted = bank
.call(mint_message, &minter_context, &mut working_set)
.expect("Failed to mint token");
// No events at the moment. If there are, needs to be checked
assert!(working_set.events().is_empty());
// -----
// Freeze
let freeze_message = CallMessage::Freeze { token_address };
let _freeze = bank
.call(freeze_message, &minter_context, &mut working_set)
.expect("Failed to freeze token");
assert!(working_set.events().is_empty());
// ----
// Try to freeze an already frozen token
let freeze_message = CallMessage::Freeze { token_address };
let freeze = bank.call(freeze_message, &minter_context, &mut working_set);
assert!(freeze.is_err());
let Error::ModuleError(err) = freeze.err().unwrap();
let mut chain = err.chain();
let message_1 = chain.next().unwrap().to_string();
let message_2 = chain.next().unwrap().to_string();
assert!(chain.next().is_none());
assert_eq!(
format!(
"Failed freeze token_address={} by sender {}",
token_address, minter_address
),
message_1
);
assert_eq!(format!("Token {} is already frozen", token_name), message_2);
// create a second token
let token_name_2 = "Token2".to_owned();
let initial_balance = 100;
let token_address_2 = get_token_address::<C>(&token_name_2, minter_address.as_ref(), salt);
// ---
// Deploying second token
let mint_message = CallMessage::CreateToken {
salt,
token_name: token_name_2.clone(),
initial_balance,
minter_address,
authorized_minters: vec![minter_address],
};
let _minted = bank
.call(mint_message, &minter_context, &mut working_set)
.expect("Failed to mint token");
// No events at the moment. If there are, needs to be checked
assert!(working_set.events().is_empty());
// Try to freeze with a non authorized minter
let unauthorized_address = generate_address::<C>("unauthorized_address");
let sequencer_address = generate_address::<C>("sequencer");
let unauthorized_context = C::new(unauthorized_address, sequencer_address, 1);
let freeze_message = CallMessage::Freeze {
token_address: token_address_2,
};
let freeze = bank.call(freeze_message, &unauthorized_context, &mut working_set);
assert!(freeze.is_err());
let Error::ModuleError(err) = freeze.err().unwrap();
let mut chain = err.chain();
let message_1 = chain.next().unwrap().to_string();
let message_2 = chain.next().unwrap().to_string();
assert!(chain.next().is_none());
assert_eq!(
format!(
"Failed freeze token_address={} by sender {}",
token_address_2, unauthorized_address
),
message_1
);
assert_eq!(
format!(
"Sender {} is not an authorized minter of token {}",
unauthorized_address, token_name_2
),
message_2
);
// Try to mint a frozen token
let mint_amount = 10;
let new_holder = generate_address::<C>("new_holder");
let mint_message = CallMessage::Mint {
coins: Coins {
amount: mint_amount,
token_address,
},
minter_address: new_holder,
};
let query_total_supply =
|token_address: Address, working_set: &mut WorkingSet<DefaultContext>| -> Option<u64> {
let total_supply: TotalSupplyResponse =
bank.supply_of(None, token_address, working_set).unwrap();
total_supply.amount
};
let minted = bank.call(mint_message, &minter_context, &mut working_set);
assert!(minted.is_err());
let Error::ModuleError(err) = minted.err().unwrap();
let mut chain = err.chain();
let message_1 = chain.next().unwrap().to_string();
let message_2 = chain.next().unwrap().to_string();
assert!(chain.next().is_none());
assert_eq!(
format!(
"Failed mint coins(token_address={} amount={}) to {} by authorizer {}",
token_address, mint_amount, new_holder, minter_address
),
message_1
);
assert_eq!(
format!("Attempt to mint frozen token {}", token_name),
message_2
);
// -----
// Try to mint an unfrozen token, sanity check
let mint_amount = 10;
let mint_message = CallMessage::Mint {
coins: Coins {
amount: mint_amount,
token_address: token_address_2,
},
minter_address,
};
let _minted = bank
.call(mint_message, &minter_context, &mut working_set)
.expect("Failed to mint token");
assert!(working_set.events().is_empty());
let total_supply = query_total_supply(token_address_2, &mut working_set);
assert_eq!(Some(initial_balance + mint_amount), total_supply);
let query_user_balance =
|token_address: Address,
user_address: Address,
working_set: &mut WorkingSet<DefaultContext>|
-> Option<u64> { bank.get_balance_of(user_address, token_address, working_set) };
let bal = query_user_balance(token_address_2, minter_address, &mut working_set);
assert_eq!(Some(110), bal);
}
|
require("dotenv").config();
const { Sequelize, Op } = require("sequelize");
const fs = require("fs");
const path = require("path");
const { DB_USER, DB_PASSWORD, DB_HOST } = process.env;
const sequelize = new Sequelize(
`postgres://${DB_USER}:${DB_PASSWORD}@${DB_HOST}/edarkostore`,
{
logging: false, // set to console.log to see the raw SQL queries
native: false, // lets Sequelize know we can use pg-native for ~30% more speed
}
);
const basename = path.basename(__filename); // me da el nombre del archivo donde estoy si le paso una ruta, _filename es la ruta donde estoy
const modelDefiners = []; // seria un array de cada modelo
// Leemos todos los archivos de la carpeta models, los requerimos y agregamos al arreglo modelDefiners
fs.readdirSync(path.join(__dirname, "/models")) // ["file1.js","file2.js"]
.filter(
(element) =>
element.indexOf(".") !== 0 &&
element !== basename &&
element.slice(-3) === ".js"
) // ["file1","file2"]
.forEach((element) => {
modelDefiners.push(require(path.join(__dirname, "/models", element))); // empezamos a requerir cada model y lo pusheamos a modelDefiners
});
// Injectamos la conexion (sequelize) a todos los modelos
modelDefiners.forEach((model) => model(sequelize));
// En sequelize.models están todos los modelos importados como propiedades
// Para relacionarlos hacemos un destructuring
const {
Product,
Category,
Image,
Supplier,
Comment,
User,
Order,
OrderDetail,
} = sequelize.models;
// Aca vendrian las relaciones
// Product.hasMany(Reviews);
Product.belongsToMany(Category, {
as: "categories",
through: "ProductCategory",
timestamps: false,
});
Category.belongsToMany(Product, {
through: "ProductCategory",
timestamps: false,
});
Product.belongsToMany(Image, {
through: "ProductImage",
timestamps: false,
});
Image.belongsToMany(Product, {
through: "ProductImage",
timestamps: false,
});
Product.belongsToMany(Supplier, { through: "ProductSupplier" });
Supplier.belongsToMany(Product, { through: "ProductSupplier" });
Product.belongsToMany(User, { through: Comment });
User.belongsToMany(Product, { through: Comment });
Product.belongsToMany(User, { through: "Favorite" });
User.belongsToMany(Product, { through: "Favorite" });
User.hasMany(Order);
Order.belongsTo(User);
Order.belongsToMany(Product, { through: OrderDetail });
Product.belongsToMany(Order, { through: OrderDetail });
module.exports = {
...sequelize.models, // para poder importar los modelos así: const { Product } = require('./db.js');
conn: sequelize, // para importart la conexión { conn } = require('./db.js');
Op,
};
|
--문제 설명
--다음은 어느 한 서점에서 판매중인 도서들의 도서 정보(BOOK), 판매 정보(BOOK_SALES) 테이블입니다.
--
--BOOK 테이블은 각 도서의 정보를 담은 테이블로 아래와 같은 구조로 되어있습니다.
--
--Column name Type Nullable Description
--BOOK_ID INTEGER FALSE 도서 ID
--CATEGORY VARCHAR(N) FALSE 카테고리 (경제, 인문, 소설, 생활, 기술)
--AUTHOR_ID INTEGER FALSE 저자 ID
--PRICE INTEGER FALSE 판매가 (원)
--PUBLISHED_DATE DATE FALSE 출판일
--BOOK_SALES 테이블은 각 도서의 날짜 별 판매량 정보를 담은 테이블로 아래와 같은 구조로 되어있습니다.
--
--Column name Type Nullable Description
--BOOK_ID INTEGER FALSE 도서 ID
--SALES_DATE DATE FALSE 판매일
--SALES INTEGER FALSE 판매량
--문제
--2022년 1월의 카테고리 별 도서 판매량을 합산하고, 카테고리(CATEGORY), 총 판매량(TOTAL_SALES) 리스트를 출력하는 SQL문을 작성해주세요.
--결과는 카테고리명을 기준으로 오름차순 정렬해주세요.
--
--예시
--예를 들어 BOOK 테이블과 BOOK_SALES 테이블이 다음과 같다면
--
--BOOK_ID CATEGORY AUTHOR_ID PRICE PUBLISHED_DATE
--1 인문 1 10000 2020-01-01
--2 경제 1 9000 2021-02-05
--3 경제 2 9000 2021-03-11
--BOOK_ID SALES_DATE SALES
--1 2022-01-01 2
--2 2022-01-02 3
--1 2022-01-05 1
--2 2022-01-20 5
--2 2022-01-21 6
--3 2022-01-22 2
--2 2022-02-11 3
--2022년 1월의 도서 별 총 판매량은 도서 ID 가 1 인 도서가 총 3권, 도서 ID 가 2 인 도서가 총 14권 이고, 도서 ID 가 3 인 도서가 총 2권 입니다.
--
--카테고리 별로 판매량을 집계한 결과는 다음과 같습니다.
--
--CATEGORY TOTAL_SALES
--인문 3
--경제 16
--카테고리명을 오름차순으로 정렬하면 다음과 같이 나와야 합니다.
--
--CATEGORY TOTAL_SALES
--경제 16
--인문 3
SELECT B.CATEGORY
,SUM(BS.SALES) AS TOTAL_SALES
FROM BOOK B
INNER JOIN BOOK_SALES BS
ON B.BOOK_ID = BS.BOOK_ID
AND TO_CHAR(BS.SALES_DATE, 'YYYYMM') = '202201'
GROUP BY B.CATEGORY
ORDER BY B.CATEGORY
|
import 'package:tpt_frontend/feature/setting/widgets/edit_profile_widget.dart';
import 'package:tpt_frontend/feature/setting/widgets/profile_picture_reset_password_widget.dart';
import 'package:flutter/material.dart';
import 'package:flutter_iconly/flutter_iconly.dart';
import 'package:get/get.dart';
import 'package:tpt_frontend/feature/setting/setting_controller.dart';
import 'package:tpt_frontend/resources/resources.dart';
import 'package:tpt_frontend/utills/helper/responsive.dart';
import 'package:tpt_frontend/utills/widget/button/primary_button.dart';
import 'package:sizer/sizer.dart';
class SettingPage extends StatelessWidget {
const SettingPage({super.key});
@override
Widget build(BuildContext context) {
return GetBuilder<SettingController>(
builder: (controller) {
return SafeArea(
child: Container(
width: 100.w,
height: 100.h,
margin: const EdgeInsets.fromLTRB(24, 24, 0, 0),
decoration: const BoxDecoration(
color: AppColors.background2,
borderRadius: BorderRadius.only(
topLeft: Radius.circular(20),
bottomLeft: Radius.circular(20),
topRight: Radius.circular(20),
bottomRight: Radius.circular(0),
),
),
child: SingleChildScrollView(
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
if (!Responsive.isDesktop(context))
IconButton(
icon: const Icon(Icons.menu),
onPressed: (){
Scaffold.of(context).openDrawer();
}
),
Column(
mainAxisAlignment: MainAxisAlignment.start,
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Container(
padding: const EdgeInsets.symmetric(horizontal: 32, vertical: 32),
height: 100.h-24,
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(
"Setting",
textAlign: TextAlign.left,
style: Theme.of(context).textTheme.headlineMedium!.copyWith(
color: AppColors.white,
fontWeight: FontWeight.w700
),
),
const SizedBox(height: 24),
Row(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Expanded(
child: SizedBox(
height: 80.h-3,
child: Column(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Column(
children: [
const SizedBox(height: 24),
PrimaryButtonWidget(
shape: MaterialStateProperty.all<RoundedRectangleBorder>(
const RoundedRectangleBorder(
borderRadius: BorderRadius.horizontal(
left: Radius.circular(10),
right: Radius.circular(0),
)
),
),
customColors: controller.settingTabIndex == 0
? AppColors.background1
: AppColors.black.withOpacity(0.2),
margin: const EdgeInsets.all(0),
buttonText: "Profile",
onPressed: () async {
controller.changeTabIndex(0);
},
textStyle: Theme.of(context).textTheme.bodyLarge!.copyWith(
color: controller.settingTabIndex == 0
? AppColors.white
: AppColors.white.withOpacity(0.5),
fontWeight: FontWeight.w600
)
),
const SizedBox(height: 24),
// PrimaryButtonWidget(
// shape: MaterialStateProperty.all<RoundedRectangleBorder>(
// const RoundedRectangleBorder(
// borderRadius: BorderRadius.horizontal(
// left: Radius.circular(10),
// right: Radius.circular(0),
// )
// ),
// ),
// customColors: controller.settingTabIndex == 1
// ? AppColors.background1
// : AppColors.black.withOpacity(0.2),
// margin: const EdgeInsets.all(0),
// buttonText: "Device",
// onPressed: () async {
// controller.changeTabIndex(1);
// },
// textStyle: Theme.of(context).textTheme.bodyLarge!.copyWith(
// color: controller.settingTabIndex == 1
// ? AppColors.white
// : AppColors.white.withOpacity(0.5),
// fontWeight: FontWeight.w600
// )
// ),
],
),
PrimaryButtonWidget(
width: 10.w,
customColors: AppColors.red,
margin: const EdgeInsets.all(0),
padding: 8,
buttonText: "Logout",
withIcon: true,
icon: const Icon(
IconlyLight.logout,
color: AppColors.white,
size: 16,
),
textStyle: Theme.of(context).textTheme.bodyLarge!.copyWith(
color: AppColors.white,
fontWeight: FontWeight.w600
),
onPressed: () async {
controller.logout();
},
),
],
),
),
),
Expanded(
flex: 5,
child: controller.settingTabIndex == 0
? Container(
width: 80.w,
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(20),
color: AppColors.background1
),
padding: const EdgeInsets.all(40),
child: Row(
crossAxisAlignment: CrossAxisAlignment.center,
children: [
ProfilePictureResetPasswordWidget(
controller: controller,
),
const SizedBox(width: 24),
EditProfileWidget(
controller: controller,
),
],
),
)
: Container(
width: 80.w,
height: 80.h-3,
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(20),
color: AppColors.background1
),
// child: ,
)
)
],
),
],
),
),
],
)
],
),
),
),
);
}
);
}
}
|
# 🔑 Liveness, Readiness, Resource Limits, Env. Variables
## Liveness Probes
Bazen container’ların içerisinde çalışan uygulamalar, tam anlamıyla doğru çalışmayabilir. Çalışan uygulama çökmemiş, kapanmamış ama aynı zamanda tam işlevini yerine getirmiyorsa kubelet bunu tespit edemiyor.
Liveness, sayesinde container’a **bir request göndererek, TCP connection açarak veya container içerisinde bir komut çalıştırarak** doğru çalışıp çalışmadığını anlayabiliriz.
_Açıklama kod içerisinde_ :arrow\_down:
```shell
# http get request gönderelim.
# eğer 200 ve üzeri cevap dönerse başarılı!
# dönmezse kubelet container'ı yeniden başlatacak.
apiVersion: v1
kind: Pod
metadata:
labels:
test: liveness
name: liveness-http
spec:
containers:
- name: liveness
image: k8s.gcr.io/liveness
args:
- /server
livenessProbe:
httpGet: # get request'i gönderiyoruz.
path: /healthz # path tanımı
port: 8080 # port tanımı
httpHeaders: # get request'imize header eklemek istersek
- name: Custom-Header
value: Awesome
initialDelaySeconds: 3 # uygulama hemen ayağa kalkmayabilir,
# çalıştıktan x sn sonra isteği gönder.
periodSeconds: 3 # kaç sn'de bir bu istek gönderilecek.
# (healthcheck test sürekli yapılır.)
---
# uygulama içerisinde komut çalıştıralım.
# eğer exit -1 sonucu alınırsa container baştan başlatılır.
apiVersion: v1
kind: Pod
metadata:
labels:
test: liveness
name: liveness-exec
spec:
containers:
- name: liveness
image: k8s.gcr.io/busybox
args:
- /bin/sh
- -c
- touch /tmp/healthy; sleep 30; rm -rf /tmp/healthy; sleep 600
livenessProbe:
exec: # komut çalıştırılır.
command:
- cat
- /tmp/healthy
initialDelaySeconds: 5
periodSeconds: 5
---
# tcp connection yaratalım. Eğer başarılıysa devam eder, yoksa
# container baştan başlatılır.
apiVersion: v1
kind: Pod
metadata:
name: goproxy
labels:
app: goproxy
spec:
containers:
- name: goproxy
image: k8s.gcr.io/goproxy:0.1
ports:
- containerPort: 8080
livenessProbe: # tcp connection yaratılır.
tcpSocket:
port: 8080
initialDelaySeconds: 15
periodSeconds: 20
```
## Readiness Probes
.png>)
#### **Örnek Senaryo**
3 podumuz ve 1 LoadBalancer service’imiz var. Bir güncelleme yaptık; yeni bir image oluşturduk. Eski podlar devreden çıktı, yenileri alındı. Yenileri alındığından itibaren LoadBalancer gelen trafiği yönlendirmeye başlayacaktır. Peki, benim uygulamalarım ilk açıldığında bir yere bağlanıp bir data çekip, bunu işliyor ve sonra çalışmaya başlıyorsa? Bu süre zarfında gelen requestler doğru cevaplanamayacaktır. Kısacası, uygulamamız çalışıyor ama hizmet sunmaya hazır değil.
–> **Kubelet,** bir containerın ne zaman trafiği kabul etmeye (Initial status) hazır olduğunu bilmek için **Readiness Probes** kullanır. Bir Poddaki tüm container’lar Readiness Probes kontrolünden onay alırsa **Service Pod’un arkasına eklenir.**
Yukarıdaki örnekte, yeni image’lar oluşturulurken eski Pod’lar hemen **terminate** edilmez. Çünkü, içerisinde daha önceden alınmış istekler ve bu istekleri işlemek için yürütülen işlemler olabilir. Bu sebeple, k8s önce bu Pod’un service ile ilişkisini keser ve yeni istekler almasını engeller. İçerideki mevcut isteklerinde sonlanmasını bekler.
`terminationGracePeriodSconds: 30` –> Mevcut işlemler biter, 30 sn bekler ve kapanır. (_30sn default ayardır, gayet yeterlidir._)
**–> Readiness ile Liveness arasındaki fark, Readiness ilk çalışma anını baz alırken, Liveness sürekli çalışıp çalışmadığını kontrol eder.**
> Örneğin; Backend’in ilk açılışta MongoDB’ye bağlanması için geçen bir süre vardır. MongoDB bağlantısı sağlandıktan sonraPod’un arkasına Service eklenmesi mantıklıdır. **Bu sebeple, burada readiness’i kullanabiliriz.**
Aynı Liveness’ta olduğu gibi 3 farklı yöntem vardır:
* **http/get**, **tcp connection** ve **command çalıştırma**.
```shell
apiVersion: apps/v1
kind: Deployment
metadata:
name: frontend
labels:
team: development
spec:
replicas: 3
selector:
matchLabels:
app: frontend
template:
metadata:
labels:
app: frontend
spec:
containers:
- name: frontend
image: ozgurozturknet/k8s:blue
ports:
- containerPort: 80
livenessProbe:
httpGet:
path: /healthcheck
port: 80
initialDelaySeconds: 5
periodSeconds: 5
readinessProbe:
httpGet:
path: /ready # Bu endpoint'e istek atılır, OK dönerse uygulama çalıştırılır.
port: 80
initialDelaySeconds: 20 # Başlangıçtan 20 sn gecikmeden sonra ilk kontrol yapılır.
periodSeconds: 3 # 3sn'de bir denemeye devam eder.
terminationGracePeriodSconds: 50 # Yukarıda yazıldı açıklaması.
---
apiVersion: v1
kind: Service
metadata:
name: frontend
spec:
selector:
app: frontend
ports:
- protocol: TCP
port: 80
targetPort: 80
```
## Resource Limits
\-> Pod’ların CPU ve Memory kısıtlamalarını yönetmemizi sağlar. Aksini belirtmediğimiz sürece K8s üzerinde çalıştığı makinenin CPU ve Memory’sini %100 kullanabilir. Bu durum bir sorun oluşturur. Bu sebeple Pod’ların ne kadar CPU ve Memory kullanacağını belirtebiliriz.
### CPU Tanımı
.png>)
### Memory Tanımı

### YAML Dosyasında Tanım
```shell
apiVersion: v1
kind: Pod
metadata:
labels:
test: requestlimit
name: requestlimit
spec:
containers:
- name: requestlimit
image: ozgurozturknet/stress
resources:
requests: # Podun çalışması için en az gereken gereksinim
memory: "64M" # Bu podu en az 64M 250m (yani çeyrek core)
cpu: "250m" # = Çeyrek CPU core = "0.25"
limits: # Podun çalışması için en fazla gereken limit
memory: "256M"
cpu: "0.5" # = "Yarım CPU Core" = "500m"
```
–> Eğer gereksinimler sağlanamazsa **container oluşturulamaz.**
–> Memory, CPU’ya göre farklı çalışıyor. K8s içerisinde memory’nin limitlerden fazla değer istediğinde engellemesi gibi bir durum yok. Eğer memory, limitlerden fazlasına ihtiyaç duyarsa “OOMKilled” durumuna geçerek pod restart edilir.
> **Araştırma konusu:** Bir pod’un limitlerini ve min. gereksinimlerini neye göre belirlemeliyiz?
## Environment Variables
Örneğin, bir node.js sunucusu oluşturduğumuzu ve veritabanı bilgilerini sunucu dosyaları içerisinde sakladığımızı düşünelim. Eğer, sunucu dosyalarından oluşturduğumuz container image’ı başka birisinin eline geçerse büyük bir güvenlik açığı meydana gelir. Bu sebeple **Environment Variables** kullanmamız gerekir.
### YAML Tanımlaması
```shell
apiVersion: v1
kind: Pod
metadata:
name: envpod
labels:
app: frontend
spec:
containers:
- name: envpod
image: ozgurozturknet/env:latest
ports:
- containerPort: 80
env:
- name: USER # önce name'ini giriyoruz.
value: "Ozgur" # sonra value'sunu giriyoruz.
- name: database
value: "testdb.example.com"
```
### Pod içinde tanımlanmış Env. Var.’ları Görmek
```shell
kubectl exec <podName> -- printenv
```
## Port-Forward (Local -> Pod)
–> Kendi local sunucularımızdan istediğimiz k8s cluster’ı içerisindeki object’lere direkt ulaşabilmek için **port-forward** açabiliriz. Bu object’i test etmek için en iyi yöntemlerden biridir.
```shell
kubectl port-forward <objectType>/<podName> <localMachinePort>:<podPort>
kubectl port-forward pod/envpod 8080:80
# Benim cihazımdaki 8080 portuna gelen tüm istekleri,bu podun 80 portuna gönder.
curl 127.0.0.1:8080
# Test için yazabilirsin.
```
_CMD + C yapıldığında port-forwarding sona erer._
|
#include "main.h"
/**
* print_triangle - prints a triangle
* @size: takes a value
*
* Description: a function that prints a triangle
* followed by a new line.
* Return: 0 always success
*/
void print_triangle(int size)
{
int i;
int j;
if (size <= 0)
{
_putchar('\n');
}
for (i = 0; i < size; i++)
{
for (j = 0; j < size; j++)
{
if (i + j >= size - 1)
{
_putchar('#');
}
else
{
_putchar(' ');
}
}
_putchar(' ');
_putchar('\n');
}
}
|
import { Injectable } from '@angular/core';
import { BehaviorSubject, Subject } from 'rxjs';
import { CartItem } from '../common/cart-item';
@Injectable({
providedIn: 'root'
})
export class CartService {
cartItems: CartItem[];
/* Subject is a sublacc of Observable.
We can use Subject to publish event in our code.
The event will be sent to ALL of the subscribers */
totalPrice: Subject<number> = new BehaviorSubject<number>(0);
totalQuantity: Subject<number> = new BehaviorSubject<number>(0);
totalShippingPrice: Subject<number> = new BehaviorSubject<number>(0);
/*
cartItems uses the constructor to initialises the cartItems variable.
If there is a value in the sessionStorage cartItems value we initialise with that value, otherwise we initialise to an empty array.
The reason for JSON.parse is sessionStorage and localStorage store strings. So we need to convert the string back into a javascript object equivalent (json).
*/
constructor() {
this.cartItems = JSON.parse(sessionStorage.getItem('cartItems')!) ? JSON.parse(sessionStorage.getItem('cartItems')!) : [];
}
addToCart(theCartItem: CartItem) {
// check if we already have the item in our cart
let alreadyExistsInCart: boolean = false;
let existingCartItem: CartItem | undefined;
if (this.cartItems.length > 0) {
// find the item in the cart based on item id
// for(let tempCartItem of this.cartItems){
// if(tempCartItem.id === theCartItem.id){
// existingCartItem = tempCartItem;
// break;
// }
// }
// refactored code. Returns first element that passes, else returns undefined.
existingCartItem = this.cartItems.find(tempCartItem => (tempCartItem.id === theCartItem.id));
// check if we found it
alreadyExistsInCart = (existingCartItem != undefined);
}
if (alreadyExistsInCart) {
//increment the quantity
existingCartItem!.quantity++;
}
else {
// add the item to the array
this.cartItems.push(theCartItem);
}
//compute cart total price and total quantity
this.computeCartTotals();
}
computeCartTotals() {
let totalPriceValue: number = 0;
let totalQuantityValue: number = 0;
let totalShippingPrice: number = 0;
for (let currentCartItem of this.cartItems) {
totalPriceValue += currentCartItem.quantity * currentCartItem.unitPrice;
totalQuantityValue += currentCartItem.quantity;
}
totalShippingPrice = 0.05 * totalPriceValue;
// publish the new values ... all subscribers will receive the new data
this.totalPrice.next(totalPriceValue);
this.totalQuantity.next(totalQuantityValue);
this.totalShippingPrice.next(totalShippingPrice);
//log cart data for debugging purposes
this.logCartData(totalPriceValue, totalQuantityValue, totalShippingPrice);
this.cartItemsInSessionStorage();
}
logCartData(totalPriceValue: number, totalQuantityValue: number, totalShippingPrice: number) {
console.log('Contents of the cart');
for (let tempCartItem of this.cartItems) {
const subTotalPrice = tempCartItem.quantity * tempCartItem.unitPrice;
console.log(`name: ${tempCartItem.name}, quantity=${tempCartItem.quantity},
unitPrice=${tempCartItem.unitPrice}, subTotalPrice=${subTotalPrice}`);
}
//toFixed(2) means two digits after decimal (124.98)
console.log(`totalPrice: ${totalPriceValue.toFixed(2)}, totalQuantity: ${totalQuantityValue}, totalShippingPrice: ${totalShippingPrice.toFixed(2)}`);
console.log('-----');
}
decrementQuantity(cartItem: CartItem) {
cartItem.quantity--;
if (cartItem.quantity === 0) {
this.removeItemsFromCart(cartItem);
}
else {
this.computeCartTotals();
}
}
removeItemsFromCart(cartItem: CartItem) {
// get the index of item in the array
const itemIndex = this.cartItems.findIndex(
tempCartItem => tempCartItem.id === cartItem.id);
// if found, remove the item from the array at the given index. If it would not find it then index will be -1.
if (itemIndex > -1) {
this.cartItems.splice(itemIndex, 1);
this.computeCartTotals();
}
}
/*
Sets the sessionStorage cartItems value with the currentItems variable value.
The reason for JSON.stringify is sessionStorage and localStorage store strings. So this allows us to convert our array into a string equivalent.
*/
cartItemsInSessionStorage() {
sessionStorage.setItem('cartItems', JSON.stringify(this.cartItems));
}
}
|
import { createApp } from "vue";
import App from "./App.vue";
import "./registerServiceWorker";
import router from "./router";
import store from "./store";
import axios from "axios";
axios.interceptors.request.use(
(config) => {
// Exclude login route from setting Authorization header
if (config.url !== `${process.env.VUE_APP_API_BASE_URL}/api/auth/login/`) {
const token = localStorage.getItem("token");
if (token) {
config.headers["Authorization"] = `Token ${token}`;
}
}
return config;
},
(error) => {
return Promise.reject(error);
}
);
import VueAxios from "vue-axios";
import "@mdi/font/css/materialdesignicons.css";
// Vuetify
import "vuetify/styles";
import { createVuetify } from "vuetify";
import * as components from "vuetify/components";
import * as directives from "vuetify/directives";
const vuetify = createVuetify({
components,
directives,
theme: {
defaultTheme: "myTheme",
themes: {
myTheme: {
dark: false, // Set the initial value of the dark theme
},
},
},
});
// vuedraggable
import Draggable from "vuedraggable";
const app = createApp(App);
app
.use(store)
.use(vuetify)
.use(router)
.use(VueAxios, axios)
.directive("v-draggable", Draggable);
app.mount("#app");
|
.TH haveged 8 "February 10, 2014" "version 1.9" "SYSTEM ADMINISTRATION COMMANDS"
.SH NAME
haveged \- Generate random numbers and feed linux random device.
.SH SYNOPSIS
.B haveged [options]
.SH DESCRIPTION
.B haveged
generates an unpredictable stream of random numbers harvested from the indirect
effects of hardware events on hidden processor state (caches, branch predictors,
memory translation tables, etc) using the HAVEGE (HArdware Volatile Entropy
Gathering and Expansion) algorithm. The algorithm operates in user space, no
special privilege is required for file system access to the output stream.
.P
Linux pools randomness for distribution by the /dev/random and /dev/urandom
device interfaces. The standard mechanisms of filling the /dev/random pool may
not be sufficient to meet demand on systems with high needs or limited user
interaction. In those circumstances,
.B haveged
may be run as a privileged daemon to fill the /dev/random pool whenever the
supply of random bits in /dev/random falls below the low water mark of the
device.
.P
.B haveged
tunes itself to its environment and provides the same built-in test suite
for the output stream as used on certified hardware security devices. See
.B NOTES
below for further information.
.SH OPTIONS
.TP
-b nnn, --buffer=nnn
Set collection buffer size to nnn KW. Default is 128KW (or 512KB).
.TP
-d nnn, --data=nnn
Set data cache size to nnn KB. Default is 16 or as determined dynamically.
.TP
-f file, --file=file
Set output file path for non-daemon use. Default is "sample",
use "-" for stdout.
.TP
-F , --Foreground
Run daemon in foreground. Do not fork and detach.
.TP
-i nnn, --inst=nnn
Set instruction cache size to nnn KB. Default is 16 or as determined dynamically.
.TP
-n nnn, --number=nnn
Set number of bytes written to the output file. The value may be specified using one
of the suffixes k, m, g, or t. The upper bound of this value is "16t" (2^44 Bytes = 16TB).
A value of 0 indicates unbounded output and forces output to stdout. This argument is
required if the daemon interface is not present. If the daemon interface is present, this
setting takes precedence over any --run value.
.TP
-o <spec>, --onlinetest=<spec>
Specify online tests to run. The <spec> consists of optional "t"ot and
"c"ontinuous groups, each group indicates the procedures to be run, using "a<n>"
to indicate a AIS-31 procedure A variant, and "b" to indicate AIS procedure B.
The specifications are order independent (procedure B always runs first in each
group) and case insensitive. The a<n> variations exist to mitigate the a slow
autocorrelation test (test5). Normally all procedure A tests, except the first
are iterated 257 times. An a<n> option indicates test5 should only be executed
every modulo <n> times during the procedure's 257 repetitions. The effect is so
noticable that A8 is the usual choice.
The "tot" tests run only at initialization - there are no negative performance
consequences except for a slight increase in the time required to initialize.
The "tot" tests guarantee haveged has initialized properly. The use of both test
procedures in the "tot" test is highly recommended because the two test emphasize
different aspects of RNG quality.
In continuous testing, the test sequence is cycled repeatedly. For example, the
string "tbca8b" (suitable for an AIS NTG.1 device) would run procedure B for the
"tot" test, then cycle between procedure A8 and procedure B continuously for all
further output. Continuous testing does not come for free, impacting both
throughput and resource consumption. Continual testing also opens up the possibility
of a test failure. A strict retry procedure recovers from spurious failure in all but
the most extreme circumstances. When the retry fails, operation will terminate unless
a "w" has been appended to the test token to make the test advisory only. In our
example above, the string "tbca8wbw" would make all continuous tests advisory. For
more detailed information on AIS retries see
.B NOTES
below.
Complete control over the test configuration is provided for flexibility. The
defaults (ta8bcb" if run as a daemon and "ta8b" otherwise) are suitable for most
circumstances.
.TP
-p file, --pidfile=file
Set file path for the daemon pid file. Default is "/var/run/haveged.pid",
.TP
-r n, --run=n
Set run level for daemon interface:
n = 0 Run as daemon - must be root. Fills /dev/random when the supply of random bits
falls below the low water mark of the device.
n = 1 Display configuration info and terminate.
n > 1 Write <n> kb of output. Deprecated (use --number instead), only provided for backward
compatibility.
If --number is specified, values other than 0,1 are ignored. Default is 0.
.TP
-v n, --verbose=n
Set diagnostic bitmap as sum of following options:
1=Show build/tuning summary on termination, summary for online test retries.
2=Show online test retry details
4=Show timing for collections
8=Show collection loop layout
16=Show collection loop code offsets
32=Show all online test completion detail
Default is 0. Use -1 for all diagnostics.
.TP
-w nnn, --write=nnn
Set write_wakeup_threshold of daemon interface to nnn bits. Applies only to run level 0.
.TP
-?, --help
This summary of program options.
.SH NOTES
.P
haveged tunes the HAVEGE algorithm for maximum effectiveness using a hierarchy
of defaults, command line options, virtual file system information, and cpuid
information where available. Under most circumstances, user input is not
required for excellent results.
.P
Run-time testing provides assurance of correct haveged operation. The run-time
test suite is modeled upon the AIS-31 specification of the German Common
Criteria body, BIS. This specification is typically applied to hardware devices,
requiring formal certification and mandated start-up and continuous operational
testing. Because haveged runs on many different hardware platforms, certification
cannot be a goal, but the AIS-31 test suite provides the means to assess haveged
output with the same operational tests applied to certified hardware devices.
.P
AIS test procedure A performs 6 tests to check for statistically inconspicuous
behavior. AIS test procedure B performs more theoretical tests such as checking
multi-step transition probabilities and making an empirical entropy estimate.
Procedure A is the much more resource and compute intensive of the two but is
still recommended for the haveged start-up tests. Procedure B is well suited to
use of haveged as a daemon because the test entropy estimate confirms the
entropy estimate haveged uses when adding entropy to the /dev/random device.
.P
No test is perfect. There is a 10e-4 probability that a perfect generator will
fail either of the test procedures. AIS-31 mandates a strict retry policy to
filter out false alarms and haveged always logs test procedure failures. Retries
are expected but rarely observed except when large data sets are generated with
continuous testing. See the
.B libhavege(3)
notes for more detailed information.
.SH FILES
If running as a daemon, access to the following files is required
.RS
.P
.I /dev/random
.P
.I /proc/sys/kernel/osrelease
.P
.I /proc/sys/kernel/random/poolsize
.P
.I /proc/sys/kernel/random/write_wakeup_threshold
.RE
.SH DIAGNOSTICS
Haveged returns 0 for success and non-zero for failure. The failure return code is 1
"general failure" unless execution is terminated by signal <n>, in which case
the return code will be 128 + <n>. The following diagnostics are issued to stderr
upon non-zero termination:
Cannot fork into the background
.RS
Call to daemon(3) failed.
.RE
Cannot open file <s> for writing.
.RS
Could not open sample file <s> for writing.
.RE
Cannot write data in file:
.RS
Could not write data to the sample file.
.RE
Couldn't get pool size.
.RS
Unable to read /proc/sys/kernel/random/poolsize
.RE
Couldn't initialize HAVEGE rng
.RS
Invalid data or instruction cache size.
.RE
Couldn't open PID file <s> for writing
.RS
Unable to write daemon PID
.RE
Couldn't open random device
.RS
Could not open /dev/random for read-write.
.RE
Couldn't query entropy-level from kernel: error
.RS
Call to ioctl(2) failed.
.RE
Couldn't open PID file <path> for writing
.RS
Error writing /var/run/haveged.pid
.RE
Fail:set_watermark()
.RS
Unable to write to /proc/sys/kernel/random/write_wakeup_threshold
.RE
RNDADDENTROPY failed!
.RS
Call to ioctl(2) to add entropy failed
.RE
RNG failed
.RS
The random number generator failed self-test or encountered a fatal error.
.RE
Select error
.RS
Call to select(2) failed.
.RE
Stopping due to signal <n>
.RS
Signal <n> caught.
.RE
Unable to setup online tests
.RS
Memory unavailable for online test resources.
.SH EXAMPLES
.TP
Write 1.5MB of random data to the file /tmp/random
haveged -n 1.5M -f /tmp/random
.TP
Generate a /tmp/keyfile for disk encryption with LUKS
haveged -n 2048 -f /tmp/keyfile
.TP
Overwrite partition /dev/sda1 with random data. Be careful, all data on the partition will be lost!
haveged -n 0 | dd of=/dev/sda1
.TP
Generate random ASCII passwords of the length 16 characters
(haveged -n 1000 -f - 2>/dev/null | tr -cd '[:graph:]' | fold -w 16 && echo ) | head
.TP
Write endless stream of random bytes to the pipe. Utility pv measures the speed by which data are written to the pipe.
haveged -n 0 | pv > /dev/null
.TP
Evaluate speed of haveged to generate 1GB of random data
haveged -n 1g -f - | dd of=/dev/null
.TP
Create a random key file containing 65 random keys for the encryption program aespipe.
haveged -n 3705 -f - 2>/dev/null | uuencode -m - | head -n 66 | tail -n 65
.TP
Test the randomness of the generated data with dieharder test suite
haveged -n 0 | dieharder -g 200 -a
.TP
Generate 16k of data, testing with procedure A and B with detailed test results. No c result seen because a single buffer fill did not contain enough data to complete the test.
haveged -n 16k -o tba8ca8 -v 33
.TP
Generate 16k of data as above with larger buffer. The c test now completes - enough data now generated to complete the test.
haveged -n 16k -o tba8ca8 -v 33 -b 512
.TP
Generate 16m of data as above, observe many c test completions with default buffer size.
haveged -n 16m -o tba8ca8 -v 33
.TP
Generate large amounts of data - in this case 16TB. Enable initialization test but made continuous tests advisory only to avoid a possible situation that program will terminate because of procedureB failing two times in a row. The probability of procedureB to fail two times in a row can be estimated as <TB to generate>/3000 which yields 0.5% for 16TB.
haveged -n 16T -o tba8cbw -f - | pv > /dev/null
.TP
Generate large amounts of data (16TB). Disable continuous tests for the maximum throughput but run the online tests at the startup to make sure that generator for properly initialized:
haveged -n 16T -o tba8c -f - | pv > /dev/null
.SH SEE ALSO
.TP
.BR libhavege(3),
.BR cryptsetup(8),
.BR aespipe(1),
.BR pv(1),
.BR openssl(1),
.BR uuencode(1)
.SH REFERENCES
.I HArdware Volatile Entropy Gathering and Expansion: generating unpredictable random numbers at user level
by A. Seznec, N. Sendrier, INRIA Research Report, RR-4592, October 2002
.I A proposal for: Functionality classes for random number generators
by W. Killmann and W. Schindler, version 2.0, Bundesamt fur Sicherheit in der
Informationstechnik (BSI), September, 2011
.I A Statistical Test Suite for the Validation of Random NUmber Generators and Pseudorandom Number Generators for Cryptographic Applications,
special publication SP800-22, National Institute of Standards and Technology, revised April, 2010
Additional information can also be found at
.B http://www.issihosts.com/haveged/
.SH AUTHORS
Gary Wuertz <gary@issiweb.com> and Jirka Hladky <hladky jiri AT gmail DOT com>
|
import React, { useState } from 'react'
import './EditProfil.css';
import { IMG_BASE } from '../../App';
import { FontAwesomeIcon } from '@fortawesome/react-fontawesome';
import { faPen, faX } from '@fortawesome/free-solid-svg-icons';
import { useTranslation } from 'react-i18next';
import { useCookies } from 'react-cookie';
import { updateUser } from '../../API/User/updateUser';
import { updateCover } from '../../API/User/updateCover';
import { updatePic } from '../../API/User/updatePic';
const EditProfil = ({userData , display , setDisplay}) => {
const [ t ] = useTranslation("global");
const [userNameCookies,setUserNameCookies] = useCookies(['username']);
const [cover,setCover] = useState(null);
const [pic,setPic] = useState(null);
const [username,setUsername] = useState(userData.username);
const [bio,setBio] = useState(userData.bio);
const [previewCover, setPreviewCover] = useState(IMG_BASE+userData.cover);
const [previewPic, setPreviewPic] = useState(IMG_BASE+userData.profilePic);
const handleCoverChange = (e) => {
const selectedFile = e.target.files[0];
if (selectedFile) {
setCover(selectedFile);
// Read the selected file and create a URL for preview
const reader = new FileReader();
reader.onload = () => {
setPreviewCover(reader.result);
};
reader.readAsDataURL(selectedFile);
}
};
const handlePicChange = (e) => {
const selectedFile = e.target.files[0];
if (selectedFile) {
setPic(selectedFile);
// Read the selected file and create a URL for preview
const reader = new FileReader();
reader.onload = () => {
setPreviewPic(reader.result);
};
reader.readAsDataURL(selectedFile);
}
};
const handleUpdateCover = async()=>{
try {
//send the new post to the signup api
const coverData = new FormData();
coverData.append('user_id', userData._id);
coverData.append('cover', cover);
const response = await updateCover(coverData);
console.log(response); // Handle success or display error message
} catch (error) {
console.error(error);
}
}
const handleUpdatePic = async()=>{
try {
//send the new post to the signup api
const picData = new FormData();
picData.append('user_id', userData._id);
picData.append('profilePic', pic);
const response = await updatePic(picData);
console.log(response); // Handle success or display error message
} catch (error) {
console.error(error);
}
}
const [usernameErr,setUsernameErr] = useState('');
const [isErr,setIsErr] = useState(true);
const handeUsernameValidity = ()=>{
const userPattern = /^[A-Za-z]+([.\-_@# 0-9]?[A-Za-z]+)+$/;
if(!username){
setUsernameErr(<p className='alert alert-danger err'>{t('signup.Errs.usernameErr')}</p>);
setIsErr(true);
}else if(!userPattern.test(username)){
setUsernameErr(<p className='alert alert-danger err'>{t('signup.Errs.invalidUsernameErr')}</p>);
setIsErr(true);
}else{
setUsernameErr("");
return false
}
return isErr;
}
const handleUpdateUser = async()=>{
const isNotValid = handeUsernameValidity();
if(!isNotValid){
const updatedUser = {user_id : userData._id , username , bio};
try {
//send the new user to the signup api
const response = await updateUser(updatedUser);
//Check if there is an err
if(response.errName === "usernameErr"){
setUsernameErr(<p className='alert alert-danger err'>{t('signup.Errs.existedUsernameErr')}</p>);
}else{// Rederect user to the login if there is no err
setUserNameCookies('username', username)
}
console.log(response); // Handle success or display error message
setDisplay('none');
window.location.reload();
} catch (error) {
console.error(error);
}
}
}
return (
<div className='EditProfil-container' style={{display}}>
<FontAwesomeIcon className='close' icon={faX} onClick={()=>{setDisplay('none')}}/>
<div className="cover-container">
<img src={previewCover} alt="" className="cover-img" />
<div className='edit-cover-container'>
<label className='edit-cover' htmlFor="cover">
<FontAwesomeIcon icon={faPen}/>
<p>edit cover pic</p>
</label>
<input type="file" accept='.jpeg , .png , .jpg' id="cover" style={{display:'none'}} onChange={(e)=>{handleCoverChange(e)}}/>
</div>
</div>
<div className="Pic">
<div className="pic-container">
<img src={previewPic} alt="" className="pic-img" />
</div>
<div className='edit-pic-container'>
<label className='edit-pic' htmlFor="pic">
<FontAwesomeIcon icon={faPen}/>
<p>edit profile pic</p>
</label>
<input type="file" id="pic" accept='.jpeg , .png , .jpg' style={{display:'none'}} onChange={(e)=>{handlePicChange(e)}}/>
</div>
</div>
<div className="input-container">
<label htmlFor="" className="form-label">username:</label>
<input type="text" className="form-control" value={username} onChange={(e)=>{setUsername(e.target.value)}}/>
{usernameErr}
</div>
<div className="input-container">
<label htmlFor="" className="form-label">bio:</label>
<input type="text" className="form-control" value={bio} onChange={(e)=>{setBio(e.target.value)}}/>
</div>
<div className="submit-container">
<button className="btn btn-primary" onClick={()=>{handleUpdateUser();cover && handleUpdateCover(); pic && handleUpdatePic();}}>Edit</button>
</div>
</div>
)
}
export default EditProfil
|
/*
* ModSecurity, http://www.modsecurity.org/
* Copyright (c) 2023 Trustwave Holdings, Inc. (http://www.trustwave.com/)
*
* 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
*
* If any of the files related to licensing are missing or if you have any
* other questions related to licensing please contact Trustwave Holdings, Inc.
* directly using the email address security@modsecurity.org.
*
*/
#ifdef __cplusplus
#include <string>
#include <chrono>
#endif
#ifndef SRC_COLLECTION_DATA_H_
#define SRC_COLLECTION_DATA_H_
#ifdef __cplusplus
namespace modsecurity {
namespace collection {
namespace backend {
class CollectionData {
public:
CollectionData() :
m_hasValue(false),
m_hasExpiryTime(false) { }
CollectionData(const std::string &value) :
m_hasValue(true),
m_hasExpiryTime(false),
m_value(value) { }
void setValue(const std::string &value) {
m_value = value;
m_hasValue = true;
}
bool hasValue() const { return m_hasValue;}
const std::string& getValue() const { return m_value;}
void setExpiry(int32_t seconds_until_expiry);
bool hasExpiry() const { return m_hasExpiryTime;}
bool isExpired() const;
std::string getSerialized() const;
void setFromSerialized(const char* serializedData, size_t length);
private:
bool m_hasValue;
bool m_hasExpiryTime;
std::string m_value;
std::chrono::system_clock::time_point m_expiryTime;
};
} // namespace backend
} // namespace collection
} // namespace modsecurity
#endif
#endif // SRC_COLLECTION_DATA_H_
|
class NFA:
def __init__(self, states, alphabet, transitions, start_state, accept_states):
self.states = states
self.alphabet = alphabet
self.transitions = transitions
self.start_state = start_state
self.accept_states = accept_states
def process_input(self, input_string):
current_states = {self.start_state}
for symbol in input_string:
next_states = set()
for state in current_states:
if symbol in self.transitions[state]:
next_states.update(self.transitions[state][symbol])
current_states = next_states
return bool(current_states & self.accept_states)
def run_nfa(nfa, test_strings):
for string in test_strings:
if nfa.process_input(string):
print(f'String "{string}" is accepted.')
else:
print(f'String "{string}" is not accepted.')
nfa_empty_set = NFA(
states={0},
alphabet={"a", "b"},
transitions={0: {"a": set(), "b": set()}},
start_state=0,
accept_states=set(),
)
nfa_epsilon_set = NFA(
states={0},
alphabet={"a", "b"},
transitions={0: {"a": {0}, "b": {0}}},
start_state=0,
accept_states={0},
)
# NFA for (ab)*
nfa_ab_star = NFA(
states={0, 1, 2},
alphabet={"a", "b"},
transitions={
0: {"a": {1}, "b": {0}},
1: {"a": {0}, "b": {2}},
2: {"a": {1}, "b": {2}},
},
start_state=0,
accept_states={2},
)
if __name__ == "__main__":
test_strings = ["", "a", "b", "ab", "ba", "aaabab", "abbababba"]
print("Testing NFA for ∅:")
run_nfa(nfa_empty_set, test_strings)
print("\nTesting NFA for {ε}:")
run_nfa(nfa_epsilon_set, test_strings)
print("\nTesting NFA for (ab)*:")
run_nfa(nfa_ab_star, test_strings)
|
import {matchDetailData} from './../mockup/data';
import {base} from './../util/base';
let table = {
props: ['players'],
template: `
<table class="table">
<thead>
<tr class="table-head">
<th>玩家头像</th>
<th>英雄</th>
<th>总金钱</th>
<th>K/D/A</th>
<th>道具</th>
<th>英雄伤害</th>
<th>建筑伤害</th>
<th>补刀</th>
<th>等级</th>
</tr>
</thead>
<tbody class="table-result">
<tr v-for="item in players">
<td>
<img src='/static/img/default.jpg' height="30" />
</td>
<td>
<img onerror="ifImgNotExist(this)"
:src="getImgUrl('hero', item.hero_id)"
:alt="item.hero_name||item.hero_id" height="30" />
</td>
<td>17388 (15.9%)</td>
<td>{{item.kill}}/{{item.death}}/{{item.assist}}</td>
<td><img src="/static/img/item/magic_wand_icon.png" height="30" title="Magic Wand"><img src="/static/img/item/tranquil_boots_icon.png" height="30" title="Tranquil Boots"><img src="/static/img/item/hand_of_midas_icon.png" height="30" title="Hand of Midas"><img src="/static/img/item/magic_wand_icon.png" height="30" title="Observer and Sentry Wards"><img src="/static/img/item/tranquil_boots_icon.png" height="30" title="Town Portal Scroll"><img src="/static/img/item/linken's_sphere_icon.png" height="30" title="Linken"></td>
<td>15095 (17.1%)</td>
<td>53</td>
<td>122</td>
<td>{{item.level}}</td>
</tr>
</tbody>
</table>
`,
methods: {
getImgUrl: base.getImgUrl
}
};
let matchDetail = {
template: `
<div class="match-detail">
<div class="match-detail-left">
<img onerror="ifImgNotExist(this)"
:src="getImgUrl('team', detail.winner.team_id)"
:alt="detail.winner.team_id" />
</div>
<div class="match-detail-middle left-win">
<div class="match-detail-total-item">
<span>{{detail.winner.kill}}</span>
<span>
<a class="btn btn-danger btn-lg" href="#">击杀</a>
</span>
<span>{{detail.loser.kill}}</span>
</div>
<div class="match-detail-total-item">
<span>{{detail.winner.ward}}</span>
<span>
<a class="btn btn-danger btn-lg" href="#">插眼</a>
</span>
<span>{{detail.loser.ward}}</span>
</div>
<div class="match-detail-total-item">
<span>{{detail.winner.smoke}}</span>
<span>
<a class="btn btn-danger btn-lg" href="#">开雾</a>
</span>
<span>{{detail.loser.smoke}}</span>
</div>
<div class="match-detail-total-item">
<span>{{detail.winner.roshan}}</span>
<span>
<a class="btn btn-danger btn-lg" href="#">肉山</a>
</span>
<span>{{detail.loser.roshan}}</span>
</div>
</div>
<div class="match-detail-right">
<img onerror="ifImgNotExist(this)"
:src="getImgUrl('team', detail.loser.team_id)"
:alt="detail.loser.team_id" />
</div>
</div>
<div class="match-btnbar">
<div class="btn-group">
<a :href="'#?' + detail.replay_id" class="btn btn-primary btn-lg">观看replay</a>
</div>
<div class="btn-group">
<button type="button" class="btn btn-primary btn-lg">个人表现</button>
<button @click="handleClick" type="button" class="btn btn-primary btn-lg dropdown-toggle" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
<span class="caret"></span>
<span class="sr-only">Toggle Dropdown</span>
</button>
<ul class="dropdown-menu" v-show="menu_display">
<li v-for="item in detail.winner.players">
<span>
<img onerror="ifImgNotExist(this)"
:src="getImgUrl('hero', item.hero_id)"
:alt="item.hero_name||item.hero_id" />
</span>
<span>{{item.hero_id}}</span>
</li>
<li v-for="item in detail.loser.players">
<span>
<img onerror="ifImgNotExist(this)"
:src="getImgUrl('hero', item.hero_id)"
:alt="item.hero_name||item.hero_id" />
</span>
<span :href="'#?' + item.hero_id">{{item.hero_id}}</span>
</li>
</ul>
</div>
<div class="btn-group">
<a :href="'#?' + detail.video_id" class="btn btn-primary btn-lg">下载录像</a>
</div>
</div>
<div class="match-info">
<table class="table">
<thead>
<tr class="table-head">
<th>比赛ID</th>
<th>比赛时间</th>
<th>胜利方</th>
<th>比赛模式</th>
<th>时长</th>
</tr>
</thead>
<tbody>
<tr>
<td>{{match_id}}</td>
<td>5天前</td>
<td>{{detail.winner.team_name}}</td>
<td>{{detail.match_mode}}</td>
<td>{{detail.duration}}</td>
</tr>
</tbody>
</table>
<table-component :players="detail.winner.players"></table-component>
<table-component :players="detail.loser.players"></table-component>
</div>
`,
components: {
'table-component': table
},
created: function () {
let url = `${this.api}?match_id=${this.match_id}`;
console.log(url)
$.getJSON(url, function(data) {
if (data && data.result) {
console.log(data.result);
} else {
console.log('req error');
}
});
},
data: () => {
return {
api: '/getMatchDetail',
menu_display: false,
detail: matchDetailData,
match_id: base.getUrlParam('match_id')
};
},
methods: {
handleClick: function () {
this.menu_display = !this.menu_display;
},
getImgUrl: base.getImgUrl,
}
};
export {
matchDetail
}
|
package pure_test
import (
"context"
"errors"
"reflect"
"testing"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"github.com/redpanda-data/benthos/v4/internal/component/testutil"
"github.com/redpanda-data/benthos/v4/internal/manager/mock"
"github.com/redpanda-data/benthos/v4/internal/message"
_ "github.com/redpanda-data/benthos/v4/internal/impl/pure"
)
func TestCatchEmpty(t *testing.T) {
conf, err := testutil.ProcessorFromYAML(`
catch: []
`)
require.NoError(t, err)
proc, err := mock.NewManager().NewProcessor(conf)
if err != nil {
t.Fatal(err)
}
exp := [][]byte{
[]byte("foo bar baz"),
}
msgs, res := proc.ProcessBatch(context.Background(), message.QuickBatch(exp))
if res != nil {
t.Fatal(res)
}
if len(msgs) != 1 {
t.Errorf("Wrong count of result msgs: %v", len(msgs))
}
if act := message.GetAllBytes(msgs[0]); !reflect.DeepEqual(exp, act) {
t.Errorf("Wrong results: %s != %s", act, exp)
}
_ = msgs[0].Iter(func(i int, p *message.Part) error {
if p.ErrorGet() != nil {
t.Errorf("Unexpected part %v failed flag", i)
}
return nil
})
}
func TestCatchBasic(t *testing.T) {
conf, err := testutil.ProcessorFromYAML(`
catch:
- bloblang: 'root = if batch_index() == 0 { content().encode("base64") }'
`)
require.NoError(t, err)
proc, err := mock.NewManager().NewProcessor(conf)
if err != nil {
t.Fatal(err)
}
parts := [][]byte{
[]byte("foo bar baz"),
[]byte("1 2 3 4"),
[]byte("hello foo world"),
}
exp := [][]byte{
[]byte("Zm9vIGJhciBiYXo="),
[]byte("MSAyIDMgNA=="),
[]byte("aGVsbG8gZm9vIHdvcmxk"),
}
msg := message.QuickBatch(parts)
_ = msg.Iter(func(i int, p *message.Part) error {
p.ErrorSet(errors.New("foo"))
return nil
})
msgs, res := proc.ProcessBatch(context.Background(), msg)
if res != nil {
t.Fatal(res)
}
if len(msgs) != 1 {
t.Errorf("Wrong count of result msgs: %v", len(msgs))
}
if act := message.GetAllBytes(msgs[0]); !reflect.DeepEqual(exp, act) {
t.Errorf("Wrong results: %s != %s", act, exp)
}
_ = msgs[0].Iter(func(i int, p *message.Part) error {
if p.ErrorGet() != nil {
t.Errorf("Unexpected part %v failed flag", i)
}
return nil
})
}
func TestCatchFilterSome(t *testing.T) {
conf, err := testutil.ProcessorFromYAML(`
catch:
- bloblang: 'root = if !content().contains("foo") { deleted() }'
`)
require.NoError(t, err)
proc, err := mock.NewManager().NewProcessor(conf)
if err != nil {
t.Fatal(err)
}
parts := [][]byte{
[]byte("foo bar baz"),
[]byte("1 2 3 4"),
[]byte("hello foo world"),
}
exp := [][]byte{
[]byte("foo bar baz"),
[]byte("hello foo world"),
}
msg := message.QuickBatch(parts)
_ = msg.Iter(func(i int, p *message.Part) error {
p.ErrorSet(errors.New("foo"))
return nil
})
msgs, res := proc.ProcessBatch(context.Background(), msg)
if res != nil {
t.Fatal(res)
}
if len(msgs) != 1 {
t.Errorf("Wrong count of result msgs: %v", len(msgs))
}
if act := message.GetAllBytes(msgs[0]); !reflect.DeepEqual(exp, act) {
t.Errorf("Wrong results: %s != %s", act, exp)
}
_ = msgs[0].Iter(func(i int, p *message.Part) error {
if p.ErrorGet() != nil {
t.Errorf("Unexpected part %v failed flag", i)
}
return nil
})
}
func TestCatchMultiProcs(t *testing.T) {
conf, err := testutil.ProcessorFromYAML(`
catch:
- bloblang: 'root = if !content().contains("foo") { deleted() }'
- bloblang: 'root = if batch_index() == 0 { content().encode("base64") }'
`)
require.NoError(t, err)
proc, err := mock.NewManager().NewProcessor(conf)
if err != nil {
t.Fatal(err)
}
parts := [][]byte{
[]byte("foo bar baz"),
[]byte("1 2 3 4"),
[]byte("hello foo world"),
}
exp := [][]byte{
[]byte("Zm9vIGJhciBiYXo="),
[]byte("aGVsbG8gZm9vIHdvcmxk"),
}
msg := message.QuickBatch(parts)
_ = msg.Iter(func(i int, p *message.Part) error {
p.ErrorSet(errors.New("foo"))
return nil
})
msgs, res := proc.ProcessBatch(context.Background(), msg)
if res != nil {
t.Fatal(res)
}
if len(msgs) != 1 {
t.Errorf("Wrong count of result msgs: %v", len(msgs))
}
if act := message.GetAllBytes(msgs[0]); !reflect.DeepEqual(exp, act) {
t.Errorf("Wrong results: %s != %s", act, exp)
}
_ = msgs[0].Iter(func(i int, p *message.Part) error {
if p.ErrorGet() != nil {
t.Errorf("Unexpected part %v failed flag", i)
}
return nil
})
}
func TestCatchNotFails(t *testing.T) {
conf, err := testutil.ProcessorFromYAML(`
catch:
- bloblang: 'root = if batch_index() == 0 { content().encode("base64") }'
`)
require.NoError(t, err)
proc, err := mock.NewManager().NewProcessor(conf)
if err != nil {
t.Fatal(err)
}
parts := [][]byte{
[]byte(`FAILED ENCODE ME PLEASE`),
[]byte("NOT FAILED, DO NOT ENCODE"),
[]byte(`FAILED ENCODE ME PLEASE 2`),
}
exp := [][]byte{
[]byte("RkFJTEVEIEVOQ09ERSBNRSBQTEVBU0U="),
[]byte("NOT FAILED, DO NOT ENCODE"),
[]byte("RkFJTEVEIEVOQ09ERSBNRSBQTEVBU0UgMg=="),
}
msg := message.QuickBatch(parts)
msg.Get(0).ErrorSet(errors.New("foo"))
msg.Get(2).ErrorSet(errors.New("foo"))
msgs, res := proc.ProcessBatch(context.Background(), msg)
if res != nil {
t.Fatal(res)
}
if len(msgs) != 1 {
t.Errorf("Wrong count of result msgs: %v", len(msgs))
}
if act := message.GetAllBytes(msgs[0]); !reflect.DeepEqual(exp, act) {
t.Errorf("Wrong results: %s != %s", act, exp)
}
_ = msgs[0].Iter(func(i int, p *message.Part) error {
if p.ErrorGet() != nil {
t.Errorf("Unexpected part %v failed flag", i)
}
return nil
})
}
func TestCatchFilterAll(t *testing.T) {
conf, err := testutil.ProcessorFromYAML(`
catch:
- bloblang: 'root = if !content().contains("foo") { deleted() }'
`)
require.NoError(t, err)
proc, err := mock.NewManager().NewProcessor(conf)
if err != nil {
t.Fatal(err)
}
parts := [][]byte{
[]byte("bar baz"),
[]byte("1 2 3 4"),
[]byte("hello world"),
}
msg := message.QuickBatch(parts)
_ = msg.Iter(func(i int, p *message.Part) error {
p.ErrorSet(errors.New("foo"))
return nil
})
msgs, res := proc.ProcessBatch(context.Background(), msg)
assert.NoError(t, res)
if len(msgs) != 0 {
t.Errorf("Wrong count of result msgs: %v", len(msgs))
}
}
|
// Name: archive.h
// Purpose: interface of wxArchive* classes
// Author: wxWidgets team
// Licence: wxWindows licence
/**
@class wxArchiveInputStream
This is an abstract base class which serves as a common interface to
archive input streams such as wxZipInputStream.
wxArchiveInputStream::GetNextEntry returns an wxArchiveEntry object containing
the meta-data for the next entry in the archive (and gives away ownership).
Reading from the wxArchiveInputStream then returns the entry's data. Eof()
becomes @true after an attempt has been made to read past the end of the
entry's data.
When there are no more entries, GetNextEntry() returns @NULL and sets Eof().
@library{wxbase}
@category{archive,streams}
@see @ref overview_archive, wxArchiveEntry, wxArchiveOutputStream
*/
class wxArchiveInputStream : public wxFilterInputStream
{
public:
/**
Closes the current entry. On a non-seekable stream reads to the end of
the current entry first.
*/
virtual bool CloseEntry() = 0;
/**
Closes the current entry if one is open, then reads the meta-data for
the next entry and returns it in a wxArchiveEntry object, giving away
ownership. Reading this wxArchiveInputStream then returns the entry's data.
*/
wxArchiveEntry* GetNextEntry();
/**
Closes the current entry if one is open, then opens the entry specified
by the wxArchiveEntry object.
@a entry must be from the same archive file that this wxArchiveInputStream
is reading, and it must be reading it from a seekable stream.
*/
virtual bool OpenEntry(wxArchiveEntry& entry) = 0;
};
/**
@class wxArchiveOutputStream
This is an abstract base class which serves as a common interface to
archive output streams such as wxZipOutputStream.
wxArchiveOutputStream::PutNextEntry is used to create a new entry in the
output archive, then the entry's data is written to the wxArchiveOutputStream.
Another call to PutNextEntry() closes the current entry and begins the next.
@library{wxbase}
@category{archive,streams}
@see @ref overview_archive, wxArchiveEntry, wxArchiveInputStream
*/
class wxArchiveOutputStream : public wxFilterOutputStream
{
public:
/**
Calls Close() if it has not already been called.
*/
virtual ~wxArchiveOutputStream();
/**
Closes the archive, returning @true if it was successfully written.
Called by the destructor if not called explicitly.
@see wxOutputStream::Close()
*/
virtual bool Close();
/**
Close the current entry.
It is called implicitly whenever another new entry is created with CopyEntry()
or PutNextEntry(), or when the archive is closed.
*/
virtual bool CloseEntry() = 0;
/**
Some archive formats have additional meta-data that applies to the archive
as a whole.
For example in the case of zip there is a comment, which is stored at the end
of the zip file. CopyArchiveMetaData() can be used to transfer such information
when writing a modified copy of an archive.
Since the position of the meta-data can vary between the various archive
formats, it is best to call CopyArchiveMetaData() before transferring
the entries. The wxArchiveOutputStream will then hold on to the meta-data
and write it at the correct point in the output file.
When the input archive is being read from a non-seekable stream, the
meta-data may not be available when CopyArchiveMetaData() is called,
in which case the two streams set up a link and transfer the data
when it becomes available.
*/
virtual bool CopyArchiveMetaData(wxArchiveInputStream& stream) = 0;
/**
Takes ownership of @a entry and uses it to create a new entry in the
archive. @a entry is then opened in the input stream @a stream
and its contents copied to this stream.
For archive types which compress entry data, CopyEntry() is likely to be
much more efficient than transferring the data using Read() and Write()
since it will copy them without decompressing and recompressing them.
@a entry must be from the same archive file that @a stream is
accessing. For non-seekable streams, @a entry must also be the last
thing read from @a stream.
*/
virtual bool CopyEntry(wxArchiveEntry* entry,
wxArchiveInputStream& stream) = 0;
/**
Create a new directory entry (see wxArchiveEntry::IsDir) with the given
name and timestamp.
PutNextEntry() can also be used to create directory entries, by supplying
a name with a trailing path separator.
*/
virtual bool PutNextDirEntry(const wxString& name,
const wxDateTime& dt = wxDateTime::Now()) = 0;
/**
Takes ownership of entry and uses it to create a new entry in the archive.
The entry's data can then be written by writing to this wxArchiveOutputStream.
*/
virtual bool PutNextEntry(wxArchiveEntry* entry) = 0;
/**
Create a new entry with the given name, timestamp and size. The entry's
data can then be written by writing to this wxArchiveOutputStream.
*/
virtual bool PutNextEntry(const wxString& name,
const wxDateTime& dt = wxDateTime::Now(),
wxFileOffset size = wxInvalidOffset) = 0;
};
/**
@class wxArchiveEntry
This is an abstract base class which serves as a common interface to
archive entry classes such as wxZipEntry.
These hold the meta-data (filename, timestamp, etc.), for entries
in archive files such as zips and tars.
@section archiveentry_nonseekable About non-seekable streams
This information applies only when reading archives from non-seekable streams.
When the stream is seekable GetNextEntry() returns a fully populated wxArchiveEntry.
See @ref overview_archive_noseek for more information.
For generic programming, when the worst case must be assumed, you can rely on
all the fields of wxArchiveEntry being fully populated when
wxArchiveInputStream::GetNextEntry() returns, with the following exceptions:
@li GetSize(): guaranteed to be available after the entry has been read to Eof(),
or CloseEntry() has been called;
@li IsReadOnly(): guaranteed to be available after the end of the archive has
been reached, i.e. after GetNextEntry() returns NULL and Eof() is true.
@library{wxbase}
@category{archive,streams}
@see @ref overview_archive, @ref overview_archive_generic,
wxArchiveInputStream, wxArchiveOutputStream, wxArchiveNotifier
*/
class wxArchiveEntry : public wxObject
{
public:
/**
Returns a copy of this entry object.
*/
wxArchiveEntry* Clone() const;
/**
Gets the entry's timestamp.
*/
virtual wxDateTime GetDateTime() const = 0;
/**
Sets the entry's timestamp.
*/
virtual void SetDateTime(const wxDateTime& dt) = 0;
/**
Returns the entry's name, by default in the native format.
The name can include directory components, i.e. it can be a full path.
If this is a directory entry, (i.e. if IsDir() is @true) then the
returned string is the name with a trailing path separator.
*/
virtual wxString GetName(wxPathFormat format = wxPATH_NATIVE) const = 0;
/**
Sets the entry's name.
Setting a name with a trailing path separator sets IsDir().
@see GetName()
*/
virtual void SetName(const wxString& name,
wxPathFormat format = wxPATH_NATIVE) = 0;
/**
Returns the size of the entry's data in bytes.
*/
virtual wxFileOffset GetSize() const = 0;
/**
Sets the size of the entry's data in bytes.
*/
virtual void SetSize(wxFileOffset size) = 0;
/**
Returns the path format used internally within the archive to store
filenames.
*/
virtual wxPathFormat GetInternalFormat() const = 0;
/**
Returns the entry's filename in the internal format used within the
archive. The name can include directory components, i.e. it can be a
full path.
The names of directory entries are returned without any trailing path
separator. This gives a canonical name that can be used in comparisons.
@see @ref overview_archive_byname
*/
virtual wxString GetInternalName() const = 0;
/**
Returns a numeric value unique to the entry within the archive.
*/
virtual wxFileOffset GetOffset() const = 0;
/**
Returns @true if this is a directory entry.
Directory entries are entries with no data, which are used to store
the meta-data of directories. They also make it possible for completely
empty directories to be stored.
@note
The names of entries within an archive can be complete paths, and
unarchivers typically create whatever directories are necessary as they
restore files, even if the archive contains no explicit directory entries.
*/
virtual bool IsDir() const = 0;
/**
Marks this entry as a directory if @a isDir is @true. See IsDir() for more info.
*/
virtual void SetIsDir(bool isDir = true) = 0;
/**
Returns @true if the entry is a read-only file.
*/
virtual bool IsReadOnly() const = 0;
/**
Sets this entry as a read-only file.
*/
virtual void SetIsReadOnly(bool isReadOnly = true) = 0;
/**
Sets the notifier (see wxArchiveNotifier) for this entry.
Whenever the wxArchiveInputStream updates this entry, it will then invoke
the associated notifier's wxArchiveNotifier::OnEntryUpdated method.
Setting a notifier is not usually necessary. It is used to handle
certain cases when modifying an archive in a pipeline (i.e. between
non-seekable streams).
*/
void SetNotifier(wxArchiveNotifier& notifier);
/**
Unsets the notifier eventually attached to this entry.
*/
virtual void UnsetNotifier();
};
/**
@class wxArchiveClassFactory
Allows the creation of streams to handle archive formats such as zip and tar.
For example, given a filename you can search for a factory that will
handle it and create a stream to read it:
@code
factory = wxArchiveClassFactory::Find(filename, wxSTREAM_FILEEXT);
if (factory)
stream = factory->NewStream(new wxFFileInputStream(filename));
@endcode
wxArchiveClassFactory::Find can also search for a factory by MIME type
or wxFileSystem protocol.
The available factories can be enumerated using
wxArchiveClassFactory::GetFirst() and wxArchiveClassFactory::GetNext().
@library{wxbase}
@category{archive,streams}
@see @ref overview_archive, @ref overview_archive_generic, wxArchiveEntry,
wxArchiveInputStream, wxArchiveOutputStream, wxFilterClassFactory
*/
class wxArchiveClassFactory : public wxObject
{
public:
/**
Returns @true if this factory can handle the given protocol, MIME type
or file extension.
When using wxSTREAM_FILEEXT for the second parameter, the first parameter
can be a complete filename rather than just an extension.
*/
bool CanHandle(const wxString& protocol,
wxStreamProtocolType type = wxSTREAM_PROTOCOL) const;
/**
A static member that finds a factory that can handle a given protocol, MIME
type or file extension. Returns a pointer to the class factory if found, or
@NULL otherwise. It does not give away ownership of the factory.
When using wxSTREAM_FILEEXT for the second parameter, the first parameter
can be a complete filename rather than just an extension.
*/
static const wxArchiveClassFactory* Find(const wxString& protocol,
wxStreamProtocolType type = wxSTREAM_PROTOCOL);
/**
Returns the wxMBConv object that the created streams will use when
translating meta-data. The initial default, set by the constructor,
is wxConvLocal.
*/
wxMBConv& GetConv() const;
/**
Sets the wxMBConv object that the created streams will use when
translating meta-data.
*/
void SetConv(wxMBConv& conv);
//@{
/**
GetFirst and GetNext can be used to enumerate the available factories.
For example, to list them:
@code
wxString list;
const wxArchiveClassFactory *factory = wxArchiveClassFactory::GetFirst();
while (factory) {
list << factory->GetProtocol() << wxT("\n");
factory = factory->GetNext();
}
@endcode
GetFirst() and GetNext() return a pointer to a factory or @NULL if no more
are available. They do not give away ownership of the factory.
*/
static const wxArchiveClassFactory* GetFirst();
const wxArchiveClassFactory* GetNext() const;
//@}
/**
Calls the static GetInternalName() function for the archive entry type,
for example wxZipEntry::GetInternalName.
*/
virtual wxString GetInternalName(const wxString& name,
wxPathFormat format = wxPATH_NATIVE) const = 0;
/**
Returns the wxFileSystem protocol supported by this factory.
Equivalent to @code wxString(*GetProtocols()) @endcode.
*/
wxString GetProtocol() const;
/**
Returns the protocols, MIME types or file extensions supported by this
factory, as an array of null terminated strings.
It does not give away ownership of the array or strings.
For example, to list the file extensions a factory supports:
@code
wxString list;
const wxChar *const *p;
for (p = factory->GetProtocols(wxSTREAM_FILEEXT); *p; p++)
list << *p << wxT("\n");
@endcode
*/
virtual const wxChar** GetProtocols(wxStreamProtocolType type = wxSTREAM_PROTOCOL) const = 0;
/**
Create a new wxArchiveEntry object of the appropriate type.
*/
wxArchiveEntry* NewEntry() const;
//@{
/**
Create a new input or output stream to read or write an archive.
If the parent stream is passed as a pointer then the new archive stream
takes ownership of it. If it is passed by reference then it does not.
*/
wxArchiveInputStream* NewStream(wxInputStream& stream) const;
wxArchiveOutputStream* NewStream(wxOutputStream& stream) const;
wxArchiveInputStream* NewStream(wxInputStream* stream) const;
wxArchiveOutputStream* NewStream(wxOutputStream* stream) const;
//@}
/**
Adds this class factory to the list returned by GetFirst() or GetNext().
It is not necessary to do this to use the archive streams. It is usually
used when implementing streams, typically the implementation will
add a static instance of its factory class.
It can also be used to change the order of a factory already in the list,
bringing it to the front. This isn't a thread safe operation
so can't be done when other threads are running that will be using the list.
The list does not take ownership of the factory.
*/
void PushFront();
/**
Removes this class factory from the list returned by GetFirst() and GetNext().
Removing from the list isn't a thread safe operation so can't be done when
other threads are running that will be using the list.
The list does not own the factories, so removing a factory does not delete it.
*/
void Remove();
};
/**
@class wxArchiveNotifier
If you need to know when a wxArchiveInputStream updates a wxArchiveEntry
object, you can create a notifier by deriving from this abstract base class,
overriding wxArchiveNotifier::OnEntryUpdated.
An instance of your notifier class can then be assigned to the wxArchiveEntry
object using wxArchiveEntry::SetNotifier.
Your OnEntryUpdated() method will then be invoked whenever the input
stream updates the entry.
Setting a notifier is not usually necessary. It is used to handle
certain cases when modifying an archive in a pipeline (i.e. between
non-seekable streams).
See @ref overview_archive_noseek.
@library{wxbase}
@category{archive,streams}
@see @ref overview_archive_noseek, wxArchiveEntry, wxArchiveInputStream,
wxArchiveOutputStream
*/
class wxArchiveNotifier
{
public:
/**
This method must be overridden in your derived class.
*/
virtual void OnEntryUpdated(wxArchiveEntry& entry) = 0;
};
/**
@class wxArchiveIterator
An input iterator template class that can be used to transfer an archive's
catalogue to a container. It is only available if wxUSE_STL is set to 1
in setup.h, and the uses for it outlined below require a compiler which
supports member templates.
@code
template<class Arc, class T = typename Arc::entry_type*>
class wxArchiveIterator
{
// this constructor creates an 'end of sequence' object
wxArchiveIterator();
// template parameter 'Arc' should be the type of an archive input stream
wxArchiveIterator(Arc& arc) {
// ...
}
};
@endcode
The first template parameter should be the type of archive input stream
(e.g. wxArchiveInputStream) and the second can either be a pointer to an entry
(e.g. wxArchiveEntry*), or a string/pointer pair
(e.g. std::pair<wxString,wxArchiveEntry*>).
The @c wx/archive.h header defines the following typedefs:
@code
typedef wxArchiveIterator<wxArchiveInputStream> wxArchiveIter;
typedef wxArchiveIterator<wxArchiveInputStream,
std::pair<wxString, wxArchiveEntry*> > wxArchivePairIter;
@endcode
The header for any implementation of this interface should define similar
typedefs for its types, for example in @c wx/zipstrm.h there is:
@code
typedef wxArchiveIterator<wxZipInputStream> wxZipIter;
typedef wxArchiveIterator<wxZipInputStream,
std::pair<wxString, wxZipEntry*> > wxZipPairIter;
@endcode
Transferring the catalogue of an archive @e arc to a vector @e cat,
can then be done something like this:
@code
std::vector<wxArchiveEntry*> cat((wxArchiveIter)arc, wxArchiveIter());
@endcode
When the iterator is dereferenced, it gives away ownership of an entry
object. So in the above example, when you have finished with @e cat
you must delete the pointers it contains.
If you have smart pointers with normal copy semantics (i.e. not auto_ptr
or wxScopedPtr), then you can create an iterator which uses them instead.
For example, with a smart pointer class for zip entries @e ZipEntryPtr:
@code
typedef std::vector<ZipEntryPtr> ZipCatalog;
typedef wxArchiveIterator<wxZipInputStream, ZipEntryPtr> ZipIter;
ZipCatalog cat((ZipIter)zip, ZipIter());
@endcode
Iterators that return std::pair objects can be used to populate a std::multimap,
to allow entries to be looked up by name.
The string is initialised using the wxArchiveEntry object's
wxArchiveEntry::GetInternalName function.
@code
typedef std::multimap<wxString, wxZipEntry*> ZipCatalog;
ZipCatalog cat((wxZipPairIter)zip, wxZipPairIter());
@endcode
Note that this iterator also gives away ownership of an entry
object each time it is dereferenced. So in the above example, when
you have finished with @e cat you must delete the pointers it contains.
Or if you have them, a pair containing a smart pointer can be used
(again @e ZipEntryPtr), no worries about ownership:
@code
typedef std::multimap<wxString, ZipEntryPtr> ZipCatalog;
typedef wxArchiveIterator<wxZipInputStream,
std::pair<wxString, ZipEntryPtr> > ZipPairIter;
ZipCatalog cat((ZipPairIter)zip, ZipPairIter());
@endcode
@library{wxbase}
@category{archive,streams}
@see wxArchiveEntry, wxArchiveInputStream, wxArchiveOutputStream
*/
class wxArchiveIterator
{
public:
/**
Default constructor.
*/
wxArchiveIterator();
/**
Construct the iterator that returns all the entries in the archive input
stream @a arc.
*/
wxArchiveIterator(Arc& arc);
/**
Returns an entry object from the archive input stream, giving away
ownership.
*/
const T operator*() const;
//@{
/**
Position the input iterator at the next entry in the archive input stream.
*/
wxArchiveIterator operator++();
wxArchiveIterator operator++(int);
//@}
};
|
//
// Copyright (c) 2013-2015 Antti Karhu.
//
// 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.
#include "Math/Matrix3x3.h"
namespace Huurre3D
{
//Initialize static variables
const Matrix3x3 Matrix3x3::ZERO(Vector3(0,0,0), Vector3(0,0,0), Vector3(0,0,0));
const Matrix3x3 Matrix3x3::IDENTITY(Vector3(1,0,0), Vector3(0,1,0), Vector3(0,0,1));
Matrix3x3::Matrix3x3(const Vector3& col0, const Vector3& col1, const Vector3& col2)
{
set(col0, col1, col2);
}
Matrix3x3::Matrix3x3(const Matrix3x3& matrix)
{
cols[0] = matrix.cols[0];
cols[1] = matrix.cols[1];
cols[2] = matrix.cols[2];
}
void Matrix3x3::set(const Vector3& col0, const Vector3& col1, const Vector3& col2)
{
cols[0] = col0;
cols[1] = col1;
cols[2] = col2;
}
const Vector3& Matrix3x3::operator[](int index) const
{
return cols[index];
}
Vector3& Matrix3x3::operator[](int index)
{
return cols[index];
}
Matrix3x3& Matrix3x3::operator = (const Matrix3x3& rhs)
{
cols[0] = rhs.cols[0];
cols[1] = rhs.cols[1];
cols[2] = rhs.cols[2];
return *this;
}
bool Matrix3x3::operator == (const Matrix3x3& rhs) const
{
return cols[0] == rhs.cols[0] && cols[1] == rhs.cols[1] && cols[2] == rhs.cols[2];
}
bool Matrix3x3::operator != (const Matrix3x3& rhs) const
{
return cols[0] != rhs.cols[0] || cols[1] != rhs.cols[1] || cols[2] != rhs.cols[2];
}
Matrix3x3 Matrix3x3::operator + (const Matrix3x3& rhs) const
{
return Matrix3x3(cols[0] + rhs.cols[0], cols[1] + rhs.cols[1], cols[2] + rhs.cols[2]);
}
Matrix3x3& Matrix3x3::operator += (const Matrix3x3& rhs)
{
cols[0] += rhs.cols[0];
cols[1] += rhs.cols[1];
cols[2] += rhs.cols[2];
return *this;
}
Matrix3x3 Matrix3x3::operator - (const Matrix3x3& rhs) const
{
return Matrix3x3(cols[0] - rhs.cols[0], cols[1] - rhs.cols[1], cols[2] - rhs.cols[2]);
}
Matrix3x3& Matrix3x3::operator -= (const Matrix3x3& rhs)
{
cols[0] -= rhs.cols[0];
cols[1] -= rhs.cols[1];
cols[2] -= rhs.cols[2];
return *this;
}
Matrix3x3 Matrix3x3::operator -() const
{
return Matrix3x3(-cols[0], -cols[1], -cols[2]);
}
float Matrix3x3::trace() const
{
return cols[0].x + cols[1].y + cols[2].z;
}
Matrix3x3 Matrix3x3::operator * (const Matrix3x3& rhs) const
{
return Matrix3x3(*this * rhs.cols[0], *this * rhs.cols[1], *this * rhs.cols[2]);
}
Matrix3x3& Matrix3x3::operator *= (const Matrix3x3& rhs)
{
set(*this * rhs.cols[0], *this * rhs.cols[1], *this * rhs.cols[2]);
return *this;
}
Matrix3x3 Matrix3x3::operator * (float scalar) const
{
return Matrix3x3(cols[0] * scalar, cols[1] * scalar, cols[2] * scalar);
}
Matrix3x3& Matrix3x3::operator *= (float scalar)
{
cols[0] *= scalar;
cols[1] *= scalar;
cols[2] *= scalar;
return *this;
}
Vector3 Matrix3x3::operator * (const Vector3& rhs) const
{
return Vector3(cols[0] * rhs.x + cols[1] * rhs.y + cols[2] * rhs.z);
}
float Matrix3x3::determinant() const
{
//Calculates determinant using triple product.
return cols[0].dot(cols[1].cross(cols[2]));
}
Matrix3x3 Matrix3x3::transpose() const
{
return Matrix3x3(Vector3(cols[0].x, cols[1].x, cols[2].x),
Vector3(cols[0].y, cols[1].y, cols[2].y),
Vector3(cols[0].z, cols[1].z, cols[2].z));
}
Matrix3x3 Matrix3x3::inverse() const
{
Matrix3x3 transpose = this->transpose();
float invDet = 1.0f / this->determinant();
return Matrix3x3(transpose.cols[1].cross(transpose.cols[2]) * invDet,
transpose.cols[2].cross(transpose.cols[0]) * invDet,
transpose.cols[0].cross(transpose.cols[1]) * invDet);
}
}
|
/***************************************************************************
*
* Copyright Kai Özer, 2003-2018
*
* This file is part of MI-SUGAR.
*
* MI-SUGAR 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.
*
* MI-SUGAR 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 MI-SUGAR; if not, write to the Free Software Foundation, Inc.,
* 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*
****************************************************************************/
#import "MI_SchematicElementChooser.h"
#import "MI_SubcircuitDocumentModel.h"
#import "MI_SubcircuitElement.h"
extern NSString* MISUGAR_SUBCIRCUIT_LIBRARY_FOLDER;
/*
Acts as a data source for the subcircuit elements table.
There is only a single library manager for one session.
When the application starts the files in the directory
~/Library/Application Support/MI-SUGAR/Subcircuits/
are read and MI_SubcircuitElement objects are created.
The element names populate the table in the elements
panel. The graphical representation of the selected
element is shown in the drag source for subcircuits.
The library manager also makes sure that there is only
a single system-wide definition (document model) for
each type of subcircuit. The definitions are stored
in a dictionary which uses the name of the subcircuit
schematic element as key.
*/
@interface MI_SubcircuitLibraryManager : NSObject <NSOutlineViewDataSource, NSOutlineViewDelegate>
{
// widget which holds the draggable representation of a subcircuit element
MI_SchematicElementChooser* chooser;
// widget which holds the list of subcircuits
NSOutlineView* table;
// namespace display field
NSTextField* namespaceField;
}
// The view element shows the graphical representation of the selected subcircuit
- (instancetype) initWithChooserView:(MI_SchematicElementChooser*)chooser
tableView:(NSOutlineView*)table
namespaceView:(NSTextField*)nsField;
// Saves the model in a file in the subcircuit library directory.
// Optionally opens the newly created subcircuit document.
- (BOOL) addSubcircuitToLibrary:(MI_SubcircuitDocumentModel*)definition
show:(BOOL)openDocument;
// Refreshes the list of available subcircuits in the repository.
- (void) refreshList;
// Calls refreshList and sets the shape of the top item in the display.
- (void) refreshAll;
// Connects to the MacInit site and downloads new subcircuits
- (void) synchronizeWithOnlineLibrary;
// Returns the document model (the definition) of a subcircuit given the
// fully qualified name of the subcircuit element
- (MI_SubcircuitDocumentModel*) modelForSubcircuitName:(NSString*)name;
// Opens the definition of the selected subcircuit in a document window
- (IBAction) showDefinitionOfSelectedSubcircuit:(id)sender;
// returns the file path of the default subcircuit library
+ (NSString*) defaultSubcircuitLibraryPath;
// Checks if the given folder exists and optionally notifies the user if not
- (BOOL) validateLibraryFolder:(NSString*)folderPath
warnUser:(BOOL)warn;
// Performs all necessary tasks to display the given element
- (void) displaySubcircuitElement:(MI_SubcircuitElement*)element;
@end
|
/*
* This file is part of the ScaleGraph project (http://scalegraph.org).
*
* This file is licensed to You under the Eclipse Public License (EPL);
* You may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* http://www.opensource.org/licenses/eclipse-1.0.php
*
* (C) Copyright ScaleGraph Team 2011-2012.
*/
package example;
import x10.util.Team;
import org.scalegraph.api.SpectralClustering;
import org.scalegraph.Config;
import org.scalegraph.graph.Graph;
import org.scalegraph.graph.GraphGenerator;
import org.scalegraph.io.impl.CSVWriter;
import org.scalegraph.io.NamedDistData;
import org.scalegraph.util.random.Random;
import org.scalegraph.util.MathAppend;
import org.scalegraph.util.Dist2D;
public final class SpectralClusteringExample {
public static def main(args: Array[String]) {
val config = Config.get();
val team = config.worldTeam();
// val dist = config.dist2d();
val weightAttr = "weight";
val R = 1 << (MathAppend.ceilLog2(team.size()) / 2);
val C = team.size() / R;
val dist = Dist2D.make2D(team, C, R);
// the number of cluster
val numCluster = 2;
// tolerance
val tolerance = 0.01;
// max iteration
val maxitr = 1000;
// thread
val threshold = 0.001;
val outputPath = "sc-%d";
// Generate RMAT graph
val scale = 10;
val edgeFactor = 8;
val rnd = new Random(2, 3);
val edgeList = GraphGenerator.genRMAT(scale, edgeFactor, 0.45, 0.15, 0.15, rnd);
val g = Graph.make(edgeList);
// Generate edge weight
val weight = GraphGenerator.genRandomEdgeValue(scale, edgeFactor, rnd);
g.setEdgeAttribute[Double](weightAttr, weight);
// Call API
Console.OUT.println("XXXXX");
val W = g.createDistSparseMatrix[Double](dist, weightAttr, false, false);
val result = SpectralClustering.run(W, numCluster, tolerance, maxitr, threshold);
Console.OUT.println("XXXXX");
// Write output
val namedDistData = new NamedDistData(["sc_result" as String], [result as Any]);
CSVWriter.write(team, outputPath, namedDistData, true);
}
}
|
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* ft_printf.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: adbourji <marvin@42.fr> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2023/12/09 11:27:16 by adbourji #+# #+# */
/* Updated: 2023/12/13 16:23:59 by adbourji ### ########.fr */
/* */
/* ************************************************************************** */
#include "ft_printf.h"
/*
* A ft_printf function tailored to match printf().
* Controls output that is formatted based on the given format string.
*/
static int ft_check_format(char x, va_list list)
{
int count;
count = 0;
if (x == 'c')
count = ft_putchar(va_arg(list, int));
else if (x == 's')
count = ft_putstr(va_arg(list, char *));
else if (x == 'p')
{
count = ft_putstr("0x");
count += ft_putnbr_base2(va_arg(list, unsigned long));
}
else if (x == 'd' || x == 'i')
count = ft_putnbr(va_arg(list, int));
else if (x == 'u')
count = ft_putnbr_base(va_arg(list, unsigned int), "0123456789");
else if (x == 'x')
count = ft_putnbr_base(va_arg(list, unsigned int), "0123456789abcdef");
else if (x == 'X')
count = ft_putnbr_base(va_arg(list, unsigned int), "0123456789ABCDEF");
else if (x == '%')
count = ft_putchar('%');
else
count = ft_putchar(x);
return (count);
}
int ft_printf(const char *format, ...)
{
va_list list;
int i;
int count;
va_start(list, format);
i = 0;
count = 0;
while (format[i])
{
if (format[i] == '%')
{
if (format[i + 1] == '\0')
break ;
count += ft_check_format(format[i + 1], list);
i++;
}
else
count += ft_putchar(format[i]);
i++;
}
va_end(list);
return (count);
}
/*
int main(void)
{
int test;
test = ft_printf("\n\tTESTING ft_printf:\n\n");
test = ft_printf("Character: %c\n", 'A');
test = ft_printf("String: %s\n", "Hello World!");
test = ft_printf("Integer (%%d): %d\n", 1337);
test = ft_printf("Integer (%%i): %i\n", 42);
test = ft_printf("Unsigned Integer (%%u): %u\n", 2023);
test = ft_printf("Hexadecimal (%%x): %x\n", 255);
test = ft_printf("HEXADECIMAL (%%X): %X\n", 127);
test = ft_printf("Pointer Address: %p\n", (void *)0);
test = ft_printf("Percentage (%%%): %%\n");
test = ft_printf("NULL String: %s\n", NULL);
test = ft_printf("Large Integer: %d\n", 2147483647);
test = ft_printf("Negative Large Integer: %d\n", -2147483648);
test = ft_printf("Combined: %c %s %d", 'L', "LEET", 1337);
}
*/
|
package com.msc.cache;
/**
* This class acts as a wrapper for any Cacheable java object being placed on a Cache.
* It is the class responsible for controling the statistics of each entity, for proper analisys
* of clean up, notification and loading mechanisms of the CacheManager.
*
* @author <a href="mailto:mscaldas@gmail.com">Marcelo Caldas</a>
*/
public class CachedEntity implements Cacheable {
/**
* Defines the idle Time as undefined, meaning that an object can
* theoretically be idle for an unlimited time.
*/
public static final long UNDEFINED_IDLE_TIME = -1;
/**
* Defines the time to live as undefined, meaning that an object can
* theoretically be live for an unlimited time.
*/
public static final long UNDEFINED_TIME_TO_LIVE = -1;
/**
* The maxIdleTime specifies how long an object can live on the cache without any hit.
* if the maxIdleTime is UNDEFINED, then it is not taken into consideration during clean up
* mechanism.
* Idle Time is defined in Number of Seconds.
*/
private long maxIdleTime;
/**
* Every time a object receives a hit, the lastAccessedTime is updated, for future recalculation of
* cleanup when maxIdleTime is defined.
*/
private long lastAccessedTime ;
/**
* The maxTimeToLive specifies how long an object can live on the cache.
* if the maxTimeToLive is UNDEFINED, then it is not taken into consideration during clean up
* mechanism.
*/
private long maxTimeToLive;
/**
* Every time a new entity is registered, the creationTime is set for the current timestamp of the system.
* This property is used for future cleanup mechanisms when maxTimeToLive is defined.
*/
private long creationTime ;
/**
* This property points to the actual entity being cached. This is the information that a user wants
* when hitting a cache.
*/
private Cacheable entity;
/** a boolean indicating whether the entity has been invalidated or not. */
private boolean invaldiated;
/**
* Counter for how many times this entity have been hit.
* This property is used for cleanup mechanisms based on the number of hits (least resource used, etc)
*/
private long numberOfHits;
public CachedEntity() {
long currentTime = System.currentTimeMillis();
this.lastAccessedTime = currentTime;
this.creationTime = currentTime;
}
public Object getCacheKey() {
return this.entity.getCacheKey();
}
public long getMaxIdleTime() {
return maxIdleTime;
}
public void setMaxIdleTime(long maxIdleTime) {
this.maxIdleTime = maxIdleTime;
}
public long getLastAccessedTime() {
return lastAccessedTime;
}
public long getMaxTimeToLive() {
return maxTimeToLive;
}
public void setMaxTimeToLive(long maxTimeToLive) {
this.maxTimeToLive = maxTimeToLive;
}
public long getCreationTime() {
return creationTime;
}
public Cacheable getEntity() {
return entity;
}
public void setEntity(Cacheable entity) {
this.entity = entity;
}
public boolean isInvaldiated() {
return invaldiated;
}
public void setInvaldiated(boolean invaldiated) {
this.invaldiated = invaldiated;
}
public long getNumberOfHits() {
return numberOfHits;
}
public void hit() {
this.numberOfHits++;
this.lastAccessedTime = System.currentTimeMillis();
}
}
|
//SPDX-License-Identifier: BUSL-1.1
pragma solidity 0.8.10;
import "../interfaces/components/IUserDepositManager.1.sol";
import "../libraries/LibSanitize.sol";
import "../state/river/BalanceToDeposit.sol";
/// @title User Deposit Manager (v1)
/// @author Kiln
/// @notice This contract handles the inbound transfers cases or the explicit submissions
abstract contract UserDepositManagerV1 is IUserDepositManagerV1 {
/// @notice Handler called whenever a user has sent funds to the contract
/// @dev Must be overridden
/// @param _depositor Address that made the deposit
/// @param _recipient Address that receives the minted shares
/// @param _amount Amount deposited
function _onDeposit(address _depositor, address _recipient, uint256 _amount) internal virtual;
function _setBalanceToDeposit(uint256 newBalanceToDeposit) internal virtual;
/// @inheritdoc IUserDepositManagerV1
function deposit() external payable {
_deposit(msg.sender);
}
/// @inheritdoc IUserDepositManagerV1
function depositAndTransfer(address _recipient) external payable {
LibSanitize._notZeroAddress(_recipient);
_deposit(_recipient);
}
/// @inheritdoc IUserDepositManagerV1
receive() external payable {
_deposit(msg.sender);
}
/// @inheritdoc IUserDepositManagerV1
fallback() external payable {
revert LibErrors.InvalidCall();
}
/// @notice Internal utility calling the deposit handler and emitting the deposit details
/// @param _recipient The account receiving the minted shares
function _deposit(address _recipient) internal {
if (msg.value == 0) {
revert EmptyDeposit();
}
_setBalanceToDeposit(BalanceToDeposit.get() + msg.value);
_onDeposit(msg.sender, _recipient, msg.value);
emit UserDeposit(msg.sender, _recipient, msg.value);
}
}
|
use winit::event_loop::{ControlFlow, EventLoop};
use winit::window::{Window, WindowBuilder};
use cgmath::*;
use wgpu::{Device, Queue, Surface, SurfaceConfiguration};
use winit::dpi::PhysicalSize;
use winit::event::{ElementState, Event, KeyboardInput, VirtualKeyCode, WindowEvent};
use winit::platform::unix::EventLoopExtUnix;
use crate::scene::Scene;
pub const OPENGL_TO_WGPU_MATRIX: Matrix4<f32> = Matrix4::new(
1.0, 0.0, 0.0, 0.0,
0.0, 1.0, 0.0, 0.0,
0.0, 0.0, 0.5, 0.0,
0.0, 0.0, 0.5, 1.0,
);
pub struct Engine {
pub window: Window,
pub surface: Surface,
pub device: Device,
pub queue: Queue,
pub config: SurfaceConfiguration,
pub size: PhysicalSize<u32>,
}
impl Engine {
pub fn new(name: &str, any_thread: bool) -> (Self, EventLoop<()>) {
env_logger::init();
let event_loop = if any_thread { EventLoop::new_any_thread() } else { EventLoop::new() };
let window = WindowBuilder::new().build(&event_loop).unwrap();
window.set_title(name);
let (surface, device, queue, config, size) = pollster::block_on(init_wgpu(&window));
let app = Engine {
window,
surface,
device,
queue,
config,
size,
};
(app, event_loop)
}
pub fn resize(&mut self, new_size: PhysicalSize<u32>) {
if new_size.width > 0 && new_size.height > 0 {
self.size = new_size;
self.config.width = new_size.width;
self.config.height = new_size.height;
self.surface.configure(&self.device, &self.config);
}
}
pub fn manage_event(&mut self, event: &WindowEvent) {
match event {
WindowEvent::Resized(physical_size) => {
self.resize(*physical_size);
}
WindowEvent::ScaleFactorChanged { new_inner_size, .. } => {
self.resize(**new_inner_size);
}
_ => {}
}
}
pub fn start(mut self, mut scene: Scene, event_loop: EventLoop<()>, mut callback: impl FnMut() + 'static) {
event_loop.run(move |event, _, control_flow| match event {
Event::WindowEvent {
ref event,
window_id
} if window_id == self.window.id() => {
self.manage_event(event);
scene.manage_event(event);
match event {
WindowEvent::CloseRequested | WindowEvent::KeyboardInput {
input:
KeyboardInput {
state: ElementState::Pressed,
virtual_keycode: Some(VirtualKeyCode::Escape),
..
},
..
} => *control_flow = ControlFlow::Exit,
_ => {}
}
}
Event::RedrawRequested(_) => {
scene.update(&mut self);
callback();
match scene.render(&mut self) {
Ok(_) => {}
Err(wgpu::SurfaceError::Lost) => {
scene.resize(self.window.inner_size());
self.resize(self.window.inner_size());
}
Err(wgpu::SurfaceError::OutOfMemory) => *control_flow = ControlFlow::Exit,
Err(e) => eprintln!("{}", e)
}
}
Event::MainEventsCleared => {
self.window.request_redraw();
}
_ => {}
});
}
}
pub async fn init_wgpu(window: &Window) -> (Surface, Device, Queue, SurfaceConfiguration, PhysicalSize<u32>) {
let size = window.inner_size();
let instance = wgpu::Instance::new(wgpu::Backends::all());
//let instance = wgpu::Instance::new(wgpu::Backends::VULKAN);
let surface = unsafe { instance.create_surface(window) };
let adapter = instance
.request_adapter(&wgpu::RequestAdapterOptions {
power_preference: wgpu::PowerPreference::default(),
compatible_surface: Some(&surface),
force_fallback_adapter: false,
})
.await
.unwrap();
let (device, queue) = adapter
.request_device(
&wgpu::DeviceDescriptor {
label: None,
features: wgpu::Features::POLYGON_MODE_LINE,
limits: wgpu::Limits::default(),
},
None, // Trace path
)
.await
.unwrap();
let config = wgpu::SurfaceConfiguration {
usage: wgpu::TextureUsages::RENDER_ATTACHMENT,
format: *surface.get_supported_formats(&adapter).first().unwrap(),
width: size.width,
height: size.height,
present_mode: wgpu::PresentMode::Fifo,
};
surface.configure(&device, &config);
(surface, device, queue, config, size)
}
|
package com.androiddevs.shoppinglisttestingyt.ui
import androidx.hilt.lifecycle.ViewModelInject
import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.androiddevs.shoppinglisttestingyt.data.local.ShoppingItem
import com.androiddevs.shoppinglisttestingyt.data.remote.responses.ImageResponse
import com.androiddevs.shoppinglisttestingyt.other.Constants
import com.androiddevs.shoppinglisttestingyt.other.Event
import com.androiddevs.shoppinglisttestingyt.other.Resource
import com.androiddevs.shoppinglisttestingyt.repositories.ShoppingRepository
import kotlinx.coroutines.launch
/**
* Inject our repository into this viewmodel
* by using Hilt ?
*/
class ShoppingViewModel @ViewModelInject constructor(
private val repository: ShoppingRepository
) : ViewModel() {
val shoppingItems = repository.observeAllShoppingItem()
val totalPrice = repository.observeTotalPrice()
// private にするのが吉
private val _images = MutableLiveData<Event<Resource<ImageResponse>>>()
// Mutable を消すことで、このクラスに post(追加) できないようにしている
val images: LiveData<Event<Resource<ImageResponse>>> = _images
private val _curImageUrl = MutableLiveData<String>()
val curImageUrl: LiveData<String> = _curImageUrl
private val _insertShoppingItemStatus = MutableLiveData<Event<Resource<ShoppingItem>>>()
val insertShoppingItemStatus: LiveData<Event<Resource<ShoppingItem>>> = _insertShoppingItemStatus
fun setCurlImageUrl(url: String) {
_curImageUrl.postValue(url)
}
// delete の処理が被るといけないから、launch している・?
fun deleteShoppingItem(shoppingItem: ShoppingItem) = viewModelScope.launch {
repository.deleteShoppingItem(shoppingItem)
}
fun insertShoppingItemIntoDb(shoppingItem: ShoppingItem) = viewModelScope.launch {
repository.insertShoppingItem(shoppingItem)
}
fun insertShoppingItem(name: String, amountString: String, priceString: String) {
if (name.isEmpty() || amountString.isEmpty() || priceString.isEmpty()) {
_insertShoppingItemStatus.postValue(Event(Resource.error("The fields must not be empty", null)))
return
}
if (name.length > Constants.MAX_NAME_LENGTH) {
_insertShoppingItemStatus.postValue(Event(Resource.error("The name of the item" +
"must not exceed ${Constants.MAX_NAME_LENGTH} characters", null)))
return
}
if (priceString.length > Constants.MAX_PRICE_LENGTH) {
_insertShoppingItemStatus.postValue(Event(Resource.error("The price of the item" +
"must not exceed ${Constants.MAX_PRICE_LENGTH} characters", null)))
return
}
var amount = try {
amountString.toInt()
} catch (e: Exception) {
_insertShoppingItemStatus.postValue(Event(Resource.error("Please enter a valid amount", null)))
return
}
val shoppingItem = ShoppingItem(name, amount, priceString.toFloat(), _curImageUrl.value ?: "")
insertShoppingItemIntoDb(shoppingItem)
setCurlImageUrl("") // HOME WORK
_insertShoppingItemStatus.postValue(Event(Resource.success(shoppingItem)))
}
fun searchForImage(imageQuery: String) {
if (imageQuery.isEmpty()) {
return
}
_images.value = Event(Resource.loading(null))
viewModelScope.launch {
val response = repository.searchForImage(imageQuery)
_images.value = Event(response)
}
}
}
|
package org.frameworkset.elasticsearch.imp;
/**
* Copyright 2020 bboss
* <p>
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* <p>
* http://www.apache.org/licenses/LICENSE-2.0
* <p>
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import com.frameworkset.util.SimpleStringUtil;
import org.frameworkset.elasticsearch.serial.SerialUtil;
import org.frameworkset.runtime.CommonLauncher;
import org.frameworkset.tran.CommonRecord;
import org.frameworkset.tran.DataRefactor;
import org.frameworkset.tran.DataStream;
import org.frameworkset.tran.config.ImportBuilder;
import org.frameworkset.tran.context.Context;
import org.frameworkset.tran.output.fileftp.FilenameGenerator;
import org.frameworkset.tran.output.ftp.FtpOutConfig;
import org.frameworkset.tran.plugin.es.input.ElasticsearchInputConfig;
import org.frameworkset.tran.plugin.file.output.FileOutputConfig;
import org.frameworkset.tran.schedule.CallInterceptor;
import org.frameworkset.tran.schedule.ImportIncreamentConfig;
import org.frameworkset.tran.schedule.TaskContext;
import org.frameworkset.tran.util.RecordGenerator;
import java.io.Writer;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Map;
/**
* <p>Description: elasticsearch到sftp数据上传案例</p>
* <p></p>
* <p>Copyright (c) 2020</p>
* @Date 2021/2/1 14:39
* @author biaoping.yin
* @version 1.0
*/
public class ES2FileFtpDemo {
public static void main(String[] args){
ImportBuilder importBuilder = new ImportBuilder();
importBuilder.setBatchSize(500).setFetchSize(1000);
String ftpIp = CommonLauncher.getProperty("ftpIP","localhost");//同时指定了默认值
FileOutputConfig fileFtpOupputConfig = new FileOutputConfig();
FtpOutConfig ftpOutConfig = new FtpOutConfig();
fileFtpOupputConfig.setFtpOutConfig(ftpOutConfig);
ftpOutConfig.setBackupSuccessFiles(true);
ftpOutConfig.setTransferEmptyFiles(true);
ftpOutConfig.setFtpIP(ftpIp);
ftpOutConfig.setFtpPort(5322);
ftpOutConfig.setFtpUser("xxx");
ftpOutConfig.setFtpPassword("xxx@123");
ftpOutConfig.setRemoteFileDir("/home/xxx/failLog");
ftpOutConfig.setKeepAliveTimeout(100000);
ftpOutConfig.setFailedFileResendInterval(-1);
fileFtpOupputConfig.setFileDir("c:\\workdir");
fileFtpOupputConfig.setFilenameGenerator(new FilenameGenerator() {
@Override
public String genName(TaskContext taskContext, int fileSeq) {
String formate = "yyyyMMddHHmm";
//HN_BOSS_TRADE00001_YYYYMMDDHHMM_000001.txt
SimpleDateFormat dateFormat = new SimpleDateFormat(formate);
String time = dateFormat.format(new Date());
String _fileSeq = fileSeq+"";
int t = 6 - _fileSeq.length();
if(t > 0){
String tmp = "";
for(int i = 0; i < t; i ++){
tmp += "0";
}
_fileSeq = tmp+_fileSeq;
}
return "HN_BOSS_TRADE"+_fileSeq + "_"+time +"_" + _fileSeq+".txt";
}
});
fileFtpOupputConfig.setRecordGenerator(new RecordGenerator() {
@Override
public void buildRecord(Context taskContext, CommonRecord record, Writer builder) {
SerialUtil.normalObject2json(record.getDatas(),builder);
String data = (String)taskContext.getTaskContext().getTaskData("data");
// System.out.println(data);
}
});
importBuilder.setOutputConfig(fileFtpOupputConfig);
importBuilder.setIncreamentEndOffset(300);//单位秒,同步从上次同步截止时间当前时间前5分钟的数据,下次继续从上次截止时间开始同步数据
//vops-chbizcollect-2020.11.26,vops-chbizcollect-2020.11.27
ElasticsearchInputConfig elasticsearchInputConfig = new ElasticsearchInputConfig();
elasticsearchInputConfig
.setDslFile("dsl2ndSqlFile.xml")
.setDslName("scrollQuery")
.setScrollLiveTime("10m")
// .setSliceQuery(true)
// .setSliceSize(5)
// .setQueryUrl("dbdemo/_search")
.setQueryUrlFunction((TaskContext taskContext,Date lastStartTime,Date lastEndTime)->{
String formate = "yyyy.MM.dd";
SimpleDateFormat dateFormat = new SimpleDateFormat(formate);
String startTime = dateFormat.format(lastEndTime);
Date endTime = new Date();
String endTimeStr = dateFormat.format(endTime);
return "dbdemo/_search";
// return "dbdemo-"+startTime+ ",dbdemo-"+endTimeStr+"/_search";
// return "vops-chbizcollect-2020.11.26,vops-chbizcollect-2020.11.27/_search";
});
importBuilder.setInputConfig(elasticsearchInputConfig)
.addParam("fullImport",false)
// //添加dsl中需要用到的参数及参数值
.addParam("var1","v1")
.addParam("var2","v2")
.addParam("var3","v3");
//定时任务配置,
importBuilder.setFixedRate(false)//参考jdk timer task文档对fixedRate的说明
// .setScheduleDate(date) //指定任务开始执行时间:日期
.setDeyLay(1000L) // 任务延迟执行deylay毫秒后执行
.setPeriod(30000L); //每隔period毫秒执行,如果不设置,只执行一次
//定时任务配置结束
//设置任务执行拦截器,可以添加多个
importBuilder.addCallInterceptor(new CallInterceptor() {
@Override
public void preCall(TaskContext taskContext) {
System.out.println("preCall 1");
taskContext.addTaskData("data","testData");
}
@Override
public void afterCall(TaskContext taskContext) {
System.out.println("afterCall 1");
}
@Override
public void throwException(TaskContext taskContext, Throwable e) {
System.out.println("throwException 1");
}
});
// //设置任务执行拦截器结束,可以添加多个
//增量配置开始
importBuilder.setLastValueColumn("collecttime");//手动指定日期增量查询字段变量名称
importBuilder.setFromFirst(false);//setFromfirst(false),如果作业停了,作业重启后从上次截止位置开始采集数据,
//setFromfirst(true) 如果作业停了,作业重启后,重新开始采集数据
importBuilder.setLastValueStorePath("es2fileftp_import");//记录上次采集的增量字段值的文件路径,作为下次增量(或者重启后)采集数据的起点,不同的任务这个路径要不一样
// importBuilder.setLastValueStoreTableName("logs");//记录上次采集的增量字段值的表,可以不指定,采用默认表名increament_tab
importBuilder.setLastValueType(ImportIncreamentConfig.TIMESTAMP_TYPE);//如果没有指定增量查询字段名称,则需要指定字段类型:ImportIncreamentConfig.NUMBER_TYPE 数字类型
// 或者ImportIncreamentConfig.TIMESTAMP_TYPE 日期类型
// importBuilder.setLastValue(new Date());
//增量配置结束
//映射和转换配置开始
// /**
// * db-es mapping 表字段名称到es 文档字段的映射:比如document_id -> docId
// * 可以配置mapping,也可以不配置,默认基于java 驼峰规则进行db field-es field的映射和转换
// */
// importBuilder.addFieldMapping("document_id","docId")
// .addFieldMapping("docwtime","docwTime")
// .addIgnoreFieldMapping("channel_id");//添加忽略字段
//
//
// /**
// * 为每条记录添加额外的字段和值
// * 可以为基本数据类型,也可以是复杂的对象
// */
// importBuilder.addFieldValue("testF1","f1value");
// importBuilder.addFieldValue("testInt",0);
// importBuilder.addFieldValue("testDate",new Date());
// importBuilder.addFieldValue("testFormateDate","yyyy-MM-dd HH",new Date());
// TestObject testObject = new TestObject();
// testObject.setId("testid");
// testObject.setName("jackson");
// importBuilder.addFieldValue("testObject",testObject);
importBuilder.addFieldValue("author","张无忌");
// importBuilder.addFieldMapping("operModule","OPER_MODULE");
// importBuilder.addFieldMapping("logContent","LOG_CONTENT");
// importBuilder.addFieldMapping("logOperuser","LOG_OPERUSER");
/**
* 重新设置es数据结构
*/
importBuilder.setDataRefactor(new DataRefactor() {
public void refactor(Context context) throws Exception {
//可以根据条件定义是否丢弃当前记录
//context.setDrop(true);return;
// if(s.incrementAndGet() % 2 == 0) {
// context.setDrop(true);
// return;
// }
String data = (String)context.getTaskContext().getTaskData("data");
// System.out.println(data);
// context.addFieldValue("author","duoduo");//将会覆盖全局设置的author变量
context.addFieldValue("title","解放");
context.addFieldValue("subtitle","小康");
// context.addIgnoreFieldMapping("title");
//上述三个属性已经放置到docInfo中,如果无需再放置到索引文档中,可以忽略掉这些属性
// context.addIgnoreFieldMapping("author");
// //修改字段名称title为新名称newTitle,并且修改字段的值
// context.newName2ndData("title","newTitle",(String)context.getValue("title")+" append new Value");
/**
* 获取ip对应的运营商和区域信息
*/
Object ipInfo = context.getValue("ipInfo");
if(ipInfo != null) {
if(ipInfo instanceof String)
context.addFieldValue("ipinfo", ipInfo);
else{
context.addFieldValue("ipinfo", SimpleStringUtil.object2json(ipInfo));
}
}
else{
context.addFieldValue("ipinfo", "");
}
DateFormat dateFormat = SerialUtil.getDateFormateMeta().toDateFormat();
// Date optime = context.getDateValue("LOG_OPERTIME",dateFormat);
// context.addFieldValue("logOpertime",optime);
context.addFieldValue("newcollecttime",new Date());
/**
//关联查询数据,单值查询
Map headdata = SQLExecutor.queryObjectWithDBName(Map.class,context.getEsjdbc().getDbConfig().getDbName(),
"select * from head where billid = ? and othercondition= ?",
context.getIntegerValue("billid"),"otherconditionvalue");//多个条件用逗号分隔追加
//将headdata中的数据,调用addFieldValue方法将数据加入当前es文档,具体如何构建文档数据结构根据需求定
context.addFieldValue("headdata",headdata);
//关联查询数据,多值查询
List<Map> facedatas = SQLExecutor.queryListWithDBName(Map.class,context.getEsjdbc().getDbConfig().getDbName(),
"select * from facedata where billid = ?",
context.getIntegerValue("billid"));
//将facedatas中的数据,调用addFieldValue方法将数据加入当前es文档,具体如何构建文档数据结构根据需求定
context.addFieldValue("facedatas",facedatas);
*/
}
});
//映射和转换配置结束
/**
* 内置线程池配置,实现多线程并行数据导入功能,作业完成退出时自动关闭该线程池
*/
importBuilder.setParallel(true);//设置为多线程并行批量导入,false串行
importBuilder.setQueue(10);//设置批量导入线程池等待队列长度
importBuilder.setThreadCount(50);//设置批量导入线程池工作线程数量
importBuilder.setContinueOnError(true);//任务出现异常,是否继续执行作业:true(默认值)继续执行 false 中断作业执行
// importBuilder.setDebugResponse(false);//设置是否将每次处理的reponse打印到日志文件中,默认false,不打印响应报文将大大提升性能,只有在调试需要的时候才打开,log日志级别同时要设置为INFO
// importBuilder.setDiscardBulkResponse(true);//设置是否需要批量处理的响应报文,不需要设置为false,true为需要,默认true,如果不需要响应报文将大大提升处理速度
importBuilder.setPrintTaskLog(true);
/**
* 执行es数据导入数据库表操作
*/
DataStream dataStream = importBuilder.builder();
dataStream.execute();//执行导入操作
}
}
|
<?php
namespace App\Http\Requests\Auth\Sessions;
use Illuminate\Foundation\Http\FormRequest;
use Illuminate\Support\Facades\Auth;
use Illuminate\Validation\ValidationException;
class Store extends FormRequest
{
public function authorize(): bool
{
return true;
}
public function rules(): array
{
return [
'email' => 'required|string|email',
'password' => 'required|string',
];
}
public function attributes(): array
{
return [
'email' => 'Email',
'password' => 'Password',
];
}
public function tryAuthUser() {
if(!Auth::attempt($this->only('email', 'password'), $this->remember)) {
throw ValidationException::withMessages([
'email' => trans('auth.failed'),
]);
}
}
}
|
package md.utm.isa.ruleengine.statement;
import com.bpodgursky.jbool_expressions.*;
import com.bpodgursky.jbool_expressions.parsers.ExprParser;
import com.bpodgursky.jbool_expressions.rules.RuleSet;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
import java.util.HashMap;
public class StatementTest {
@Test
public void testExpression() {
Expression<String> expr = And.of(
Variable.of("A"),
Variable.of("B"),
Or.of(Variable.of("C"), Not.of(Variable.of("C"))));
HashMap<String, Boolean> booleanBooleanHashMap = new HashMap<>();
booleanBooleanHashMap.put("A", true);
booleanBooleanHashMap.put("B", true);
booleanBooleanHashMap.put("C", true);
Expression<String> halfAssigned = RuleSet.assign(expr, booleanBooleanHashMap);
Assertions.assertTrue(Boolean.parseBoolean(halfAssigned.toString()));
}
@Test
public void testParsing() {
Expression<String> parsedExpression = RuleSet.simplify(ExprParser.parse("(((!C)|C)&A&B)"));
HashMap<String, Boolean> booleanBooleanHashMap = new HashMap<>();
booleanBooleanHashMap.put("A", true);
booleanBooleanHashMap.put("B", true);
booleanBooleanHashMap.put("C", true);
Assertions.assertNotNull(parsedExpression);
Expression<String> result = RuleSet.assign(parsedExpression, booleanBooleanHashMap);
Assertions.assertTrue(Boolean.parseBoolean(result.toString()));
}
}
|
import Foundation
import Combine
protocol ListCitiesNavigationHandler {
func listModelDidRequestToPresentCityWeatherInfo(
_ model: ListCitiesModel,
cityModel: CityModel?,
lon: Double?,
lat: Double?
)
}
final class ListCitiesModel {
private let navigationHandler: ListCitiesNavigationHandler
let requestState = CurrentValueSubject<RequestState, Never>(.finished)
let reloadCitiesData = PassthroughSubject<Void, Never>()
var cityModel = [CityModel]()
init(navigationHandler: ListCitiesNavigationHandler) {
self.navigationHandler = navigationHandler
loadCities()
}
func showWeatherCityInfo(cityModel: CityModel?, lon: Double?, lat: Double?) {
navigationHandler.listModelDidRequestToPresentCityWeatherInfo(self, cityModel: cityModel, lon: lon, lat: lat)
}
func loadCities() {
DispatchQueue.global().async {
if let path = Bundle.main.path(forResource: "city.list", ofType: "json") {
do {
let data = try Data(contentsOf: URL(fileURLWithPath: path), options: .mappedIfSafe)
let jsonDecoder = JSONDecoder()
var cities = try jsonDecoder.decode([CityModel].self, from: data)
cities.sort {
$0.name < $1.name
}
DispatchQueue.main.async { [self] in
self.cityModel.append(contentsOf: cities)
reloadCitiesData.send(())
requestState.send(.finished)
}
}
catch {
self.requestState.send(.failed(error))
print("Error: \(error.localizedDescription)")
}
}
}
}
}
|
package com.challenge.api.dto;
import com.fasterxml.jackson.annotation.JsonInclude;
import lombok.*;
import javax.validation.constraints.NotBlank;
import javax.validation.constraints.Size;
import java.util.List;
@Getter
@Setter
@Builder
@NoArgsConstructor
@AllArgsConstructor
@JsonInclude(JsonInclude.Include.NON_EMPTY)
public class PlanetDTORequest {
@NotBlank(message = "Name is mandatory")
@Size(min = 3, message = "Name should have at least 5 characters")
private String name;
@NotBlank(message = "Climate is mandatory")
@Size(min = 3, message = "Climate should have at least 5 characters")
private String climate;
@NotBlank(message = "Terrain is mandatory")
@Size(min = 3, message = "Terrain should have at least 5 characters")
private String terrain;
private List<FilmDTORequest> films;
}
|
import React from 'react';
import './ReviewItem.css';
import { faCoffee,faTrashAlt } from '@fortawesome/free-solid-svg-icons'
import { FontAwesomeIcon } from '@fortawesome/react-fontawesome';
const ReviewItem = ({product,handleRemoveButton}) => {
const{id,name,price,quantity,shipping,img} = product;
return (
<div className='review-Item'>
<div>
<img src={img} alt="" />
</div>
<div className='review-details-container'>
<div className='review-details'>
<p>{name}</p>
<p><small>name: ${price}</small></p>
<p><small>Shipping: ${shipping}</small></p>
<p><small>price: {quantity}</small></p>
</div>
<div className='button-container'>
<button className='button-delete' onClick={() => handleRemoveButton(id)}>
<FontAwesomeIcon className='deleteIcon' icon={faTrashAlt}></FontAwesomeIcon>
</button>
</div>
</div>
</div>
);
};
export default ReviewItem;
|
---
title: "DNA methylation measurement"
subtitle: "Multi-resolution analysis"
author: "Piero Palacios Bernuy"
format: html
editor: visual
---
## Loading data
```{r}
library(minfi)
library(IlluminaHumanMethylation450kmanifest)
library(IlluminaHumanMethylation450kanno.ilmn12.hg19)
library(tidyverse)
library(TxDb.Hsapiens.UCSC.hg19.knownGene)
library(Gviz)
```
``` r
# This code is not executed due to limit size (50 mb) of github
# Please load the 450karrar_processed.rds data that is the resulto of this code
# If you want to do this with the original data, you can find this data on:
# https://github.com/genomicsclass/tcgaMethylationSubset
targets <- read.csv("targets.txt", sep = "\t")
targets$Basename <- paste0(getwd(),"/notebooks/", targets$Basename)
dat <- read.metharray(targets$Basename, verbose = T)
pData(dat) <- as(targets, "DataFrame")
## preprocessing
dat <- preprocessIllumina(dat)
dat <- mapToGenome(dat)
## Here we are collaping CpGs for a zxoom_out view of the methylated sites
dat <- cpgCollapse(dat))
```
## Multi-resolution analysis
```{r}
dat <- readRDS(file = "450karray_processed_multiresolution2.rds")
targets <- pData(dat$object)
```
```{r}
#| label: Island-status
mcols(granges(dat$object))$type |>
table() |>
prop.table() |>
as.data.frame() |>
dplyr::rename("Island Status" = Var1) |>
gt::gt()
```
```{r}
cancer_status <- factor(pData(dat$object)$Status,
levels = c("normal","cancer"))
X <- model.matrix(~cancer_status)
res <- blockFinder(dat$object,X,cutoff = 0.05)
```
```{r}
tab=makeGRangesFromDataFrame(res$table, keep.extra.columns = T)
index= granges(dat$obj)%over% (tab[1]+10000)
pos=start(dat$obj)[index]
col=as.numeric(cancer_status)
matplot(pos,getBeta(dat$obj)[index,],col=col,pch=1,cex=0.5)
##and these are the estimated difference
plot(pos,res$fitted[index])
```
## Plotting
```{r}
genome <- "hg19"
dmr <- res$table[2,]
chrom <- dmr$chr
start <- dmr$start
end <- dmr$end
minbase <- start
maxbase <- end
pal <- c("#E41A1C", "#377EB8")
iTrack <- IdeogramTrack(genome = genome, chromosome = dmr$chr, name = dmr$chr)
gTrack <- GenomeAxisTrack(col="black", cex=1, name = "", fontcolor="black")
# rTrack <- UcscTrack(genome = genome,
# chromosome = chrom,
# track = "NCBI RefSeq",
# from = minbase,
# to = maxbase,
# trackType = "GeneRegionTrack",
# rstarts = "exonStarts",
# rends = "exonEnds",
# gene = "name",
# symbol = "name2",
# transcript = "name",
# strand = "strand",
# fill = "darkblue",
# stacking = "squish",
# name = "RefSeq",
# showId = TRUE,
# geneSymbol = TRUE)
gr <- granges(dat$object)
index_1 <- which(targets$Status == "normal")
index_2 <- which(targets$Status == "cancer")
targets$Status[index_1] <- paste(targets$Status[index_1],1:17, sep = ".")
targets$Status[index_2] <- paste(targets$Status[index_2],1:17, sep = ".")
a <- getBeta(dat$object) |>
as.data.frame()
names(a) <- targets$Status
index <- order(targets$Status)
a <- a[,index]
for(i in 1:length(targets$Status)){
n <- colnames(a)[i]
mcols(gr)[,n] <- a[,i]
}
# gr$beta <- getBeta(dat$object)
mcols(gr) <- mcols(gr)[,4:37]
methTrack <- DataTrack(range = gr,
genome = genome,
chromosome = chrom,
ylim = c(-0.05, 1.05),
col = pal,
type = c("a"),
name = "DNA Meth.\n(beta value)",
background.panel = "white",
legend = TRUE,
cex.title = 0.8,
cex.axis = 0.8,
cex.legend = 0.8)
dmrTrack <- AnnotationTrack(start = start,
end = end,
genome = genome,
name = "DMR - Multi-resolution",
chromosom = chrom)
txTr <- GeneRegionTrack(TxDb.Hsapiens.UCSC.hg19.knownGene, chromosome = chrom,name="Longest transcript")
tracks <- list(iTrack, gTrack, methTrack, dmrTrack, txTr)
sizes <- c(2, 2, 5, 2, 1) # set up the relative sizes of the tracks
```
```{r}
png(file="track_plot.png", width = 1200, height = 550)
plotTracks(tracks,
from = minbase,
to = maxbase,
showTitle = TRUE,
add53 = TRUE,
add35 = TRUE,
grid = TRUE,
lty.grid = 3,
sizes = sizes,
groups = rep(c("cancer","normal"), each=17),
length(tracks),
shape="arrow",collapseTranscripts = "longest")
dev.off()
```
|
import { custom } from 'assets/iconsets'
import { createVuetify } from 'vuetify'
import { aliases, mdi } from 'vuetify/iconsets/mdi'
export default defineNuxtPlugin((NuxtApp) => {
const vuetify = createVuetify({
ssr: true,
icons: {
defaultSet: 'mdi',
aliases,
sets: {
mdi,
custom,
},
},
defaults: {
VTextField: {
variant: 'outlined',
bgColor: 'white',
color: 'primary',
},
VSelect: {
variant: 'outlined',
bgColor: 'white',
color: 'primary',
noDataText: 'Ничего не найдено',
},
VAlert: {
border: 'start',
},
VChip: {
variant: 'flat', color: 'primary',
},
VBtn: {
variant: 'outlined', color: 'primary',
},
VFileInput: {
variant: 'outlined', color: 'primary',
},
VAutocomplete: {
variant: 'outlined',
bgColor: 'white',
color: 'primary',
noDataText: 'Ничего не найдено',
},
VDataTable: {
noDataText: 'Не найдено анкет по заданному фильтру',
},
},
theme: {
themes: {
light: {
dark: false,
colors: {
background: '#fff',
error: '#FF7C7C',
info: '#2196F3',
success: '#27B19B',
warning: '#FB8C00',
},
},
},
},
})
NuxtApp.vueApp.use(vuetify)
})
|
//
// iTermRule.m
// iTerm
//
// Created by George Nachman on 6/24/14.
//
//
#import "iTermRule.h"
#import "NSStringITerm.h"
@interface iTermRule()
@property(nonatomic, copy) NSString *username;
@property(nonatomic, copy) NSString *hostname;
@property(nonatomic, copy) NSString *path;
@property(nonatomic, readwrite) BOOL sticky;
@end
@implementation iTermRule
+ (instancetype)ruleWithString:(NSString *)string {
// Any rule may begin with ! to indicate it is sticky (it will be reverted to in the future if
// no APS rule matches).
// hostname
// username@
// username@hostname
// username@hostname:path
// username@*:path
// hostname:path
// /path
NSString *username = nil;
NSString *hostname = nil;
NSString *path = nil;
BOOL sticky = NO;
if ([string hasPrefix:@"!"]) {
sticky = YES;
string = [string substringFromIndex:1];
}
NSUInteger atSign = [string rangeOfString:@"@"].location;
NSUInteger colon = [string rangeOfString:@":"].location;
if (atSign != NSNotFound) {
// user@host[:path]
username = [string substringToIndex:atSign];
if (colon != NSNotFound && colon < atSign) {
// malformed, like foo:bar@baz
colon = NSNotFound;
} else if (colon != NSNotFound) {
// user@host:path
hostname = [string substringWithRange:NSMakeRange(atSign + 1, colon - atSign - 1)];
} else if (colon == NSNotFound) {
// user@host
hostname = [string substringFromIndex:atSign + 1];
}
}
if (colon != NSNotFound) {
// [user@]host:path
if (!hostname) {
hostname = [string substringToIndex:colon];
}
path = [string substringFromIndex:colon + 1];
} else if (atSign == NSNotFound && [string hasPrefix:@"/"]) {
// /path
path = string;
} else if (atSign == NSNotFound && colon == NSNotFound) {
// host
hostname = string;
}
if ([hostname isEqualToString:@"*"]) {
// user@*:path or *:path
hostname = nil;
}
iTermRule *rule = [[[iTermRule alloc] init] autorelease];
rule.username = username;
rule.hostname = hostname;
rule.path = path;
rule.sticky = sticky;
return rule;
}
- (void)dealloc {
[_hostname release];
[_username release];
[_path release];
[super dealloc];
}
- (NSString *)description {
return [NSString stringWithFormat:@"<%@: %p hostname=%@ username=%@ path=%@>",
[self class], self, self.hostname, self.username, self.path];
}
// This is a monotonically increasing function whose range is [0, 1) for the domain of nonnegative
// values. It grows very slowly so that for any value of x that could be a Unix path name,
// squash(x + 1) - squash(x) > machine_epsilon.
- (double)squash:(double)x {
assert(x >= 0);
return x / (x + 1.0);
}
- (double)scoreForHostname:(NSString *)hostname
username:(NSString *)username
path:(NSString *)path {
const int kHostExactMatchScore = 8;
const int kHostPartialMatchScore = 4;
const int kUserExactMatchScore = 2;
const int kPathExactMatchScore = 1;
const int kPathPartialMatchScore = 0;
double score = 0;
if (self.hostname != nil) {
NSRange wildcardPos = [self.hostname rangeOfString:@"*"];
if (wildcardPos.location == NSNotFound && [hostname isEqualToString:self.hostname]) {
score += kHostExactMatchScore;
} else if ([hostname stringMatchesGlobPattern:self.hostname caseSensitive:NO]) {
score += kHostPartialMatchScore * (1.0 + [self squash:self.hostname.length]);
} else if (self.hostname.length) {
return 0;
}
}
if ([username isEqualToString:self.username]) {
score += kUserExactMatchScore;
} else if (self.username.length) {
return 0;
}
if (self.path != nil) {
// Make sure path ends in a / so a path glob pattern "/foo/bar/*" will match a path of "/foo/bar".
NSString *pathForGlob = path;
if (![pathForGlob hasSuffix:@"/"]) {
pathForGlob = [pathForGlob stringByAppendingString:@"/"];
}
NSRange wildcardPos = [self.path rangeOfString:@"*"];
if (wildcardPos.location == NSNotFound && [path isEqualToString:self.path]) {
score += kPathExactMatchScore;
} else if ([pathForGlob stringMatchesGlobPattern:self.path caseSensitive:YES]) {
score += kPathPartialMatchScore + [self squash:self.path.length];
} else if (self.path.length) {
return 0;
}
}
return score;
}
@end
|
'use client';
import { MagnifyingGlassIcon } from '@heroicons/react/24/outline';
import { useSearchParams, usePathname, useRouter } from 'next/navigation';
import { useDebouncedCallback } from 'use-debounce';
export default function Search({ placeholder }: { placeholder: string }) {
const searchParams = useSearchParams();
const pathname = usePathname();
const { replace } = useRouter();
const handleSearch = useDebouncedCallback((term) => {
//manipulation de l'URL
const params = new URLSearchParams(searchParams);
params.set('page', '1'); // reset the page number to 1 when a new search term is entered.
if (term) { // if term is not empty, set the "query" parameter to the search term.
params.set('query', term);
} else { // if term is not empty, remove the "query" parameter from the URL.
params.delete('query');
}
replace(`${pathname}?${params.toString()}`); // params.toString() translates this input into a URL-friendly format.
}, 300);
return (
<div className="relative flex flex-1 flex-shrink-0">
<label htmlFor="search" className="sr-only">
Search
</label>
<input
className="peer block w-full rounded-md border border-gray-200 py-[9px] pl-10 text-sm outline-2 placeholder:text-gray-500"
placeholder={placeholder}
onChange={(e) => handleSearch(e.target.value)}
defaultValue={searchParams.get('query')?.toString()}
/>
<MagnifyingGlassIcon className="absolute left-3 top-1/2 h-[18px] w-[18px] -translate-y-1/2 text-gray-500 peer-focus:text-gray-900" />
</div>
);
}
|
//
// ListRowView.swift
// Todo
//
// Created by krishna on 05/06/24.
//
import SwiftUI
struct ListRowView: View {
@Binding var task: Task
var body: some View {
HStack{
Image(systemName: task.isDone ? "checkmark.circle.fill" : "checkmark.circle")
.foregroundColor(task.isDone ? .blue : .primary)
Text(task.title)
Spacer()
if(!task.isDone){
Button(action: {
task.isDone.toggle()
}){
Text("markAsDone")
.font(.system(size: 14))
.padding(10)
.background(Color.blue)
.foregroundColor(.white)
.cornerRadius(100)
}
}
}
.padding(.vertical,15)
.padding(.horizontal)
}
}
struct ListRowView_Previews: PreviewProvider {
static var previews: some View {
ListRowView(task: .constant(Task(title: "Sample")))
}
}
|
const allQuestions = [
{
question: "¿Cuál es el piloto con más campeonatos de Fórmula 1?",
options: ["Lewis Hamilton", "Michael Schumacher", "Juan Manuel Fangio"],
answer: "Michael Schumacher",
},
{
question: "¿Qué equipo ha ganado más campeonatos de constructores?",
options: ["Ferrari", "Mercedes", "McLaren"],
answer: "Ferrari",
},
{
question: "¿En qué país se corre el Gran Premio de Mónaco?",
options: ["Italia", "España", "Mónaco"],
answer: "Mónaco",
},
{
question: "¿Qué piloto es conocido como 'The Flying Finn'?",
options: ["Kimi Räikkönen", "Valtteri Bottas", "Max Verstappen"],
answer: "Kimi Räikkönen",
},
{
question: "¿Cuántos títulos mundiales ha ganado Ayrton Senna?",
options: ["2", "3", "4"],
answer: "3",
},
{
question: "¿Cuál es el circuito más largo del calendario de Fórmula 1?",
options: ["Monza", "Spa-Francorchamps", "Silverstone"],
answer: "Spa-Francorchamps",
},
{
question: "¿En qué ciudad se encuentra el circuito de Yas Marina?",
options: ["Dubai", "Abu Dhabi", "Doha"],
answer: "Abu Dhabi",
},
{
question: "¿Cuál es el país de origen del piloto de Fórmula 1 Lando Norris?",
options: ["Reino Unido", "Estados Unidos", "Australia"],
answer: "Reino Unido",
},
{
question: "¿Cuántos equipos compiten en la Fórmula 1 en la temporada 2023?",
options: ["8 equipos", "10 equipos", "12 equipos"],
answer: "10 equipos",
},
{
question: "¿Quién es el piloto con más pole positions en la historia de la Fórmula 1?",
options: ["Lewis Hamilton", "Ayrton Senna", "Michael Schumacher"],
answer: "Lewis Hamilton",
},
{
question: "¿Cuál es el equipo más antiguo que todavía compite en la Fórmula 1?",
options: ["Ferrari", "Williams", "McLaren"],
answer: "McLaren",
},
{
question: "¿En qué año se celebró el primer Campeonato Mundial de Fórmula 1?",
options: ["1950", "1947", "1952"],
answer: "1950",
},
{
question: "¿Cuál es el país natal del piloto de Fórmula 1 Daniel Ricciardo?",
options: ["Australia", "Canadá", "Italia"],
answer: "Australia",
},
{
question: "¿En qué circuito se celebra el Gran Premio de Italia?",
options: ["Monza", "Imola", "Mugello"],
answer: "Monza",
},
{
question: "¿Cuál es el país de origen de la escudería Red Bull Racing?",
options: ["Reino Unido", "Austria", "Italia"],
answer: "Austria",
},
{
question: "¿Cuántas carreras se disputan en una temporada de Fórmula 1 en promedio?",
options: ["18", "20", "22"],
answer: "20",
},
{
question: "¿Cuál es el piloto más joven en ganar un Gran Premio de Fórmula 1?",
options: ["Max Verstappen", "Sebastian Vettel", "Charles Leclerc"],
answer: "Max Verstappen",
},
{
question: "¿Cuántos puntos se otorgan al piloto que logra la vuelta más rápida en una carrera de Fórmula 1?",
options: ["1 punto", "2 puntos", "3 puntos"],
answer: "1 punto",
},
];
function selectRandomQuestions(allQuestions, count) {
const selectedQuestions = [];
const shuffledQuestions = [...allQuestions];
for (let i = 0; i < count; i++) {
const randomIndex = Math.floor(Math.random() * shuffledQuestions.length);
const randomQuestion = shuffledQuestions.splice(randomIndex, 1)[0];
selectedQuestions.push(randomQuestion);
}
return selectedQuestions;
}
const selectedQuestions = selectRandomQuestions(allQuestions, 10);
let currentQuestionIndex = 0;
let correctAnswers = 0;
let playerName = "";
let playerEmail = "";
let playerEdad = "";
const userAnswers = [];
function showQuestion() {
const main = document.getElementById("main");
main.innerHTML = "";
if (!playerName || !playerEmail || !playerEdad) {
const playerNameInput = document.createElement("input");
playerNameInput.type = "text";
playerNameInput.id = "nombre";
playerNameInput.placeholder = "Ingresa tu nombre";
const playerEdadInput = document.createElement("input");
playerEdadInput.type = "text";
playerEdadInput.id = "edad";
playerEdadInput.placeholder = "Ingresa tu edad";
const playerEmailInput = document.createElement("input");
playerEmailInput.type = "email";
playerEmailInput.id = "email";
playerEmailInput.placeholder = "Ingresa tu correo electrónico";
const startButton = document.createElement("button");
startButton.innerText = "Comenzar Cuestionario";
startButton.onclick = function () {
playerName = document.getElementById("nombre").value;
playerEdad = document.getElementById("edad").value;
playerEmail = document.getElementById("email").value;
const emailPattern = /^[a-zA-Z0-9._-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,4}$/;
if (!playerName || !playerEmail || !playerEdad || isNaN(playerEdad) || playerEdad < 4 || playerEdad > 100 || !emailPattern.test(playerEmail)) {
Swal.fire({
icon: 'error',
title: 'Error',
html: '<p>Por favor, ingresa lo siguiente:</p><ul><li>Un nombre valido</li><li>Una edad válida (entre 4 y 100)</li><li>Un correo electrónico válido</li></ul>',
});
} else {
playerNameInput.style.display = "none";
playerEdadInput.style.display = "none";
playerEmailInput.style.display = "none";
startButton.style.display = "none";
showQuestion();
}
};
main.appendChild(playerNameInput);
main.appendChild(playerEdadInput);
main.appendChild(playerEmailInput);
main.appendChild(startButton);
} else {
const question = selectedQuestions[currentQuestionIndex];
const questionDiv = document.createElement("div");
questionDiv.innerHTML = `<p>${question.question}</p>`;
for (let j = 0; j < question.options.length; j++) {
const option = question.options[j];
const radioInput = document.createElement("input");
radioInput.type = "radio";
radioInput.name = "options";
radioInput.value = option;
questionDiv.appendChild(radioInput);
questionDiv.appendChild(document.createTextNode(option));
questionDiv.appendChild(document.createElement("br"));
}
const submitButton = document.createElement("button");
submitButton.innerText = "Siguiente";
submitButton.onclick = function () {
const selectedAnswer = document.querySelector('input[name="options"]:checked');
if (selectedAnswer) {
const userAnswer = selectedAnswer.value;
userAnswers[currentQuestionIndex] = userAnswer;
if (userAnswer === question.answer) {
correctAnswers++;
}
currentQuestionIndex++;
if (currentQuestionIndex < selectedQuestions.length) {
showQuestion();
} else {
showResults();
}
}
};
main.appendChild(questionDiv);
main.appendChild(submitButton);
}
}
function showResults() {
const main = document.getElementById("main");
main.innerHTML = "";
const resultMessage = document.createElement("div");
resultMessage.classList.add("alert-message");
if (correctAnswers >= 8) {
resultMessage.textContent = "¡Felicidades! Eres un experto en Fórmula 1";
} else if (correctAnswers >= 5) {
resultMessage.textContent = "Mmm, conoces algo de Fórmula 1";
} else {
resultMessage.textContent = "Patético, no sabes de Fórmula 1";
}
const scoreMessage = document.createElement("div");
scoreMessage.classList.add("alert-result");
scoreMessage.innerHTML = `Respuestas correctas: <span class="result-correct">${correctAnswers}</span>/10`;
const buttonContainer = document.createElement("div");
const viewRankingButton = document.createElement("button");
viewRankingButton.innerText = "Ver Ranking";
viewRankingButton.onclick = showRanking;
const viewAnswersButton = document.createElement("button");
viewAnswersButton.innerText = "Ver Respuestas";
viewAnswersButton.onclick = showAnswers;
const restartButton = document.createElement("button");
restartButton.innerText = "Reiniciar";
restartButton.onclick = function () {
location.reload();
};
buttonContainer.style.display = "flex";
buttonContainer.style.justifyContent = "space-between";
buttonContainer.style.marginTop = "10px";
buttonContainer.appendChild(viewRankingButton);
buttonContainer.appendChild(viewAnswersButton);
buttonContainer.appendChild(restartButton);
main.appendChild(resultMessage);
main.appendChild(scoreMessage);
main.appendChild(buttonContainer);
}
function showAnswers() {
const main = document.getElementById("main");
main.innerHTML = "";
for (let i = 0; i < selectedQuestions.length; i++) {
const question = selectedQuestions[i];
const questionDiv = document.createElement("div");
questionDiv.innerHTML = `<p>${question.question}</p>`;
main.appendChild(questionDiv);
const userAnswerDiv = document.createElement("div");
const userAnswer = userAnswers[i];
userAnswerDiv.textContent = `Tu respuesta: ${userAnswer ? userAnswer : "No respondida"}`;
main.appendChild(userAnswerDiv);
const correctAnswerDiv = document.createElement("div");
correctAnswerDiv.textContent = `Respuesta correcta: ${question.answer}`;
main.appendChild(correctAnswerDiv);
main.appendChild(document.createElement("hr"));
}
const backButton = document.createElement("button");
backButton.innerText = "Atrás";
backButton.onclick = showResults;
main.appendChild(backButton);
}
function showRanking() {
const main = document.getElementById("main");
main.innerHTML = "";
let rankingData = JSON.parse(localStorage.getItem("rankingData")) || [];
rankingData.push({ playerName, playerEdad, playerEmail, score: correctAnswers });
rankingData.sort((a, b) => b.score - a.score);
localStorage.setItem("rankingData", JSON.stringify(rankingData));
const table = document.createElement("table");
const tableHeader = document.createElement("thead");
const headerRow = document.createElement("tr");
const playerNameHeader = document.createElement("th");
playerNameHeader.textContent = "Nombre del Jugador";
const playerEdadHeader = document.createElement("th");
playerEdadHeader.textContent = "Edad";
const playerEmailHeader = document.createElement("th");
playerEmailHeader.textContent = "Correo Electrónico";
const playerScoreHeader = document.createElement("th");
playerScoreHeader.textContent = "Puntaje";
headerRow.appendChild(playerNameHeader);
headerRow.appendChild(playerEdadHeader);
headerRow.appendChild(playerEmailHeader);
headerRow.appendChild(playerScoreHeader);
tableHeader.appendChild(headerRow);
table.appendChild(tableHeader);
const tableBody = document.createElement("tbody");
for (let i = 0; i < rankingData.length; i++) {
const playerData = rankingData[i];
const row = document.createElement("tr");
const playerNameCell = document.createElement("td");
const playerEdadCell = document.createElement("td");
const playerEmailCell = document.createElement("td");
const playerScoreCell = document.createElement("td");
playerNameCell.textContent = playerData.playerName;
playerEdadCell.textContent = playerData.playerEdad;
playerEmailCell.textContent = playerData.playerEmail;
playerScoreCell.textContent = playerData.score;
row.appendChild(playerNameCell);
row.appendChild(playerEdadCell);
row.appendChild(playerEmailCell);
row.appendChild(playerScoreCell);
tableBody.appendChild(row);
}
table.appendChild(tableBody);
main.appendChild(table);
const backButton = document.createElement("button");
backButton.innerText = "Atrás";
backButton.onclick = showResults;
main.appendChild(backButton);
}
showQuestion();
|
package helloworld.lin.com.databasetest.ZhangFourteen;
import android.app.ProgressDialog;
import android.content.Intent;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import org.litepal.LitePal;
import org.litepal.crud.DataSupport;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
import helloworld.lin.com.databasetest.R;
import helloworld.lin.com.databasetest.ZhangFourteen.db.City;
import helloworld.lin.com.databasetest.ZhangFourteen.db.County;
import helloworld.lin.com.databasetest.ZhangFourteen.db.Province;
import helloworld.lin.com.databasetest.ZhangFourteen.gson.Weather;
import helloworld.lin.com.databasetest.ZhangFourteen.util.HttpUtil;
import helloworld.lin.com.databasetest.ZhangFourteen.util.Utility;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Response;
public class ChooseAreaFragment extends Fragment {
public static final int LEVEL_PROVINCE = 0;
public static final int LEVEL_CITY = 1;
public static final int LEVEL_COUNTY = 2;
private ProgressDialog progressDialog;
private TextView titleText;
private Button backButton;
private ListView listView;
private ArrayAdapter<String> adapter;
private List<String> dataList = new ArrayList<>();
private List<Province> provinceList;
private List<City> cityList;
private List<County> countyList;
private Province selectedProvince;
private City selectedCity;
private int currentLevel;
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.choose_area,container,false);
titleText = view.findViewById(R.id.title_text);
backButton = view.findViewById(R.id.back_button);
listView = view.findViewById(R.id.list_view);
adapter = new ArrayAdapter<String>(getContext(),android.R.layout.simple_list_item_1,dataList);
listView.setAdapter(adapter);
return view;
}
@Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
if(currentLevel == LEVEL_PROVINCE){
selectedProvince = provinceList.get(position);
queryCities();
}else if(currentLevel == LEVEL_CITY){
selectedCity = cityList.get(position);
queryCounties();
}else if (currentLevel == LEVEL_COUNTY){
String weatherId = countyList.get(position).getWeatherId();
Intent intent = new Intent(getActivity(), WeatherActivity.class);
Log.d("到这里了999", "onResponse: ");
intent.putExtra("weather_id",weatherId);
startActivity(intent);
getActivity().finish();
}
}
});
backButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if(currentLevel == LEVEL_COUNTY){
queryCities();
}else if(currentLevel == LEVEL_CITY){
queryProvinces();
}
}
});
queryProvinces();
}
private void queryProvinces() {
titleText.setText("中国");
backButton.setVisibility(View.GONE);
provinceList = LitePal.findAll(Province.class);
Log.d("到这里了888", "onResponse: " + provinceList.size());
// provinceList = DataSupport.findAll(Province.class);
if(provinceList.size() > 0){
dataList.clear();
for(Province province : provinceList){
dataList.add(province.getProvinceName());
}
adapter.notifyDataSetChanged();
listView.setSelection(0);
currentLevel = LEVEL_PROVINCE;
}else{
String address = "http://guolin.tech/api/china";
queryFromServer(address,"province");
}
}
private void queryCities(){
titleText.setText(selectedProvince.getProvinceName());
backButton.setVisibility(View.VISIBLE);
cityList = LitePal.where("provinceId = ?",String.valueOf(selectedProvince.getId())).find(City.class);
if(cityList.size() > 0){
Log.d("到这里了666", "onResponse: ");
dataList.clear();
// for (City city : cityList){
// dataList.add(city.getCityName());
// }
for (int i = 0; i < cityList.size(); i++) {
dataList.add(cityList.get(i).getCityName());
}
adapter.notifyDataSetChanged();
listView.setSelection(0);
currentLevel = LEVEL_CITY;
}else{
int provinceCode = selectedProvince.getProvinceCode();
String address = "http://guolin.tech/api/china/" + provinceCode;
queryFromServer(address,"city");
Log.d("到这里了444", "onResponse: ");
}
}
private void queryCounties(){
titleText.setText(selectedCity.getCityName());
backButton.setVisibility(View.VISIBLE);
countyList = LitePal.where("cityId = ?",String.valueOf(selectedCity.getId())).find(County.class);
// countyList = DataSupport.where("cityid = ?",String.valueOf(selectedCity.getId())).find(County.class);
if(countyList.size() > 0){
dataList.clear();
for (County county : countyList){
dataList.add(county.getCountyName());
}
adapter.notifyDataSetChanged();
listView.setSelection(0);
currentLevel = LEVEL_COUNTY;
}else{
int provinceCode = selectedProvince.getProvinceCode();
int cityCode = selectedCity.getCityCode();
String address = "http://guolin.tech/api/china/" + provinceCode + "/" + cityCode;
queryFromServer(address,"county");
}
}
private void queryFromServer(String address,final String type){
showProgressDialog();
HttpUtil.sendOkHttpRequest(address, new Callback() {
@Override
public void onResponse(Call call, Response response) throws IOException {
String responseText = response.body().string();
boolean result = false;
if("province".equals(type)){
result = Utility.handleProvinceResponse(responseText);
}else if("city".equals(type)){
result = Utility.handleCityResponse(responseText,selectedProvince.getId());
}else if("county".equals(type)){
result = Utility.handleCountyResponse(responseText,selectedCity.getId());
}
if (result){
getActivity().runOnUiThread(new Runnable() {
@Override
public void run() {
closeProgressDialog();
if("province".equals(type)){
queryProvinces();
}else if ("city".equals(type)){
queryCities();
}else if ("county".equals(type)){
queryCounties();
}
}
});
}
}
@Override
public void onFailure(Call call, IOException e) {
getActivity().runOnUiThread(new Runnable() {
@Override
public void run() {
closeProgressDialog();
Toast.makeText(getContext(),"加载失败",Toast.LENGTH_SHORT).show();
}
});
}
});
}
private void showProgressDialog(){
if(progressDialog == null){
progressDialog = new ProgressDialog(getActivity());
progressDialog.setMessage("正在加载...");
progressDialog.setCanceledOnTouchOutside(false);
}
progressDialog.show();
}
private void closeProgressDialog(){
if(progressDialog != null){
progressDialog.dismiss();
}
}
}
|
import 'package:flutter/material.dart';
import 'package:great_places_new/providers/grate_places.dart';
import 'package:great_places_new/screens/places_list_screen.dart';
import 'package:great_places_new/utils/app_routes.dart';
import 'package:provider/provider.dart';
import '../screens/place_form_screen.dart';
void main() {
runApp(MyApp(
));
}
class MyApp extends StatelessWidget {
final ThemeData theme = ThemeData();
MyApp({super.key});
@override
Widget build(BuildContext context) {
return ChangeNotifierProvider(
create: (ctx) => GreatPlaces(),
child: MaterialApp(
debugShowCheckedModeBanner: false,
title: 'Great Places',
theme: theme.copyWith(
colorScheme: theme.colorScheme
.copyWith(primary: Colors.indigo, secondary: Colors.amber),
),
home: const PlacesListScreen(),
routes: {
AppRoutes.PLACE_FORM: (ctx) => const PlaceFormScreen(),
},
),
);
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.